[PATCH] D107292: [clang] adds warning to alert user when they use alternative tokens in declarations

2021-08-12 Thread Christopher Di Bella via Phabricator via cfe-commits
cjdb added a comment.

In D107292#2939521 , @aaron.ballman 
wrote:

> In D107292#2923261 , @cjdb wrote:
>
>> Patch 2: expressions
>>
>> xor {}
>> bitand x // warning will suggest std::addressof in C++ land
>> and label
>
> An additional expression to cover, not that I think anyone would be this 
> awful by accident, is: `foo->compl Foo(); // Pseudo-destructor call`

Nice catch!

> One question I have about both declarations and expressions are whether we 
> have an appetite to diagnose overloaded operators or not. Personally, I think 
> it'd be reasonable to diagnose something like `foo->operator bitand();` or 
> `operator not_eq(A, B);` as expressions, but not reasonable to diagnose the 
> declaration of the overloaded operators using alternative tokens.

I agree that `bool operator and(T, T);` shouldn't be diagnosed on (and this 
patch's clang-tidy sibling will one day also diagnose that, but it's way off).

I think that `foo->operator bitand()` and `operator not_eq(expr1, expr2)` 
should only diagnose if `foo->operator&()` and `operator!=(expr1, expr2)` are 
diagnosed, //and// I think that should be a separate warning (I'm not saying 
that's a good or bad thing to do yet: let me sleep on that). I might be 
misunderstanding your intention though.


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D107292/new/

https://reviews.llvm.org/D107292

___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D107294: [clang-tidy] adds warning to suggest users replace symbols with words

2021-08-12 Thread Christopher Di Bella via Phabricator via cfe-commits
cjdb added inline comments.



Comment at: 
clang-tools-extra/clang-tidy/readability/AlternativeTokensCheck.cpp:85
+  assert(First != nullptr);
+  if (std::isalpha(*First) || Loc.isMacroID())
+return;

aaron.ballman wrote:
> `isLetter()`? (or potentially `isIdentifierHead()` if we need to care about 
> dollar-sign prefixed identifiers)
Is this necessary in the given context? The reason I was confident in using 
`isalpha` is because we know this is an operator and the only values that this 
could possibly be are one of `a`, `b`, `c`, `n`, `o`, or `x`.

(cc @cor3ntin)



Comment at: clang-tools-extra/clang-tidy/readability/StrictConstCorrectness.h:9
+
+#ifndef LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_READABILITY_STRICTCONSTCORRECTNESS_H
+#define LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_READABILITY_STRICTCONSTCORRECTNESS_H

aaron.ballman wrote:
> Did you mean to include this file in this review?
Lol nope. My bad.



Comment at: 
clang/test/Analysis/diagnostics/readability-strict-const-correctness.cpp:1
+// RUN: %check_clang_tidm1 %s readabilitm1-strict-const-correctness %t
+int f1()

aaron.ballman wrote:
> No idea how this managed to trigger a CI failure of `line 1: fg: no job 
> control` :-D
How did these files even get into this branch!? Sorry for the noise.


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D107294/new/

https://reviews.llvm.org/D107294

___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D108013: [NFC] Rename AttributeList::has/getAttribute() -> has/getAttributeImpl()

2021-08-12 Thread Arthur Eubanks via Phabricator via cfe-commits
aeubanks created this revision.
Herald added subscribers: ormris, foad, dexonsmith, lxfind, okura, jdoerfert, 
kuter, kerbowa, pengfei, Jim, hiraditya, jgravelle-google, sbc100, nhaehnle, 
jvesely, dylanmckay, dschuff, arsenm, jholewinski.
aeubanks added reviewers: rnk, efriedma.
aeubanks published this revision for review.
Herald added subscribers: llvm-commits, cfe-commits, aheejin.
Herald added a reviewer: jdoerfert.
Herald added a reviewer: sstefan1.
Herald added a reviewer: baziotis.
Herald added projects: clang, LLVM.

I've been bitten by AttributeList::getAttribute() multiple times now,
thinking that it's getParamAttribute(). Renaming it makes it clearer
that callers should use the param/fn/ret version so they don't have to
worry about the somewhat horrifying implementation details of the
attribute indexes.

I couldn't quite manage to make the methods private since some callers
need larger cleanups. Also, the C API directly uses the indexes. Perhaps
we can clean things up in the future.

Currently the naming is inconsistent (Attribute vs Attr), I'll clean
that in in a followup change.

This doesn't touch addAttribute(), I'll also clean that up in a followup
change since this change is already large enough.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D108013

Files:
  clang/lib/CodeGen/CodeGenModule.cpp
  llvm/include/llvm/IR/Attributes.h
  llvm/include/llvm/IR/Function.h
  llvm/include/llvm/IR/InstrTypes.h
  llvm/lib/Analysis/Lint.cpp
  llvm/lib/Analysis/VectorUtils.cpp
  llvm/lib/AsmParser/LLParser.cpp
  llvm/lib/Bitcode/Writer/BitcodeWriter.cpp
  llvm/lib/Bitcode/Writer/ValueEnumerator.cpp
  llvm/lib/CodeGen/GlobalISel/CallLowering.cpp
  llvm/lib/CodeGen/GlobalISel/LegalizerHelper.cpp
  llvm/lib/CodeGen/MachinePipeliner.cpp
  llvm/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp
  llvm/lib/CodeGen/TargetLoweringBase.cpp
  llvm/lib/IR/AsmWriter.cpp
  llvm/lib/IR/Attributes.cpp
  llvm/lib/IR/Core.cpp
  llvm/lib/IR/Function.cpp
  llvm/lib/IR/Instructions.cpp
  llvm/lib/IR/Statepoint.cpp
  llvm/lib/IR/Verifier.cpp
  llvm/lib/Linker/IRMover.cpp
  llvm/lib/Target/AArch64/GISel/AArch64CallLowering.cpp
  llvm/lib/Target/AMDGPU/Utils/AMDGPUBaseInfo.cpp
  llvm/lib/Target/AVR/AVRISelLowering.cpp
  llvm/lib/Target/Hexagon/HexagonOptimizeSZextends.cpp
  llvm/lib/Target/Hexagon/HexagonTargetMachine.cpp
  llvm/lib/Target/NVPTX/NVPTXAsmPrinter.cpp
  llvm/lib/Target/NVPTX/NVPTXISelLowering.cpp
  llvm/lib/Target/WebAssembly/WebAssemblyFastISel.cpp
  llvm/lib/Target/X86/X86ISelLowering.cpp
  llvm/lib/Transforms/Coroutines/CoroSplit.cpp
  llvm/lib/Transforms/IPO/Attributor.cpp
  llvm/lib/Transforms/IPO/DeadArgumentElimination.cpp
  llvm/lib/Transforms/IPO/FunctionAttrs.cpp
  llvm/lib/Transforms/IPO/GlobalOpt.cpp
  llvm/lib/Transforms/InstCombine/InstCombineCalls.cpp
  llvm/lib/Transforms/Instrumentation/MemorySanitizer.cpp
  llvm/lib/Transforms/Scalar/RewriteStatepointsForGC.cpp
  llvm/lib/Transforms/Utils/AssumeBundleBuilder.cpp
  llvm/lib/Transforms/Utils/BuildLibCalls.cpp
  llvm/lib/Transforms/Utils/FunctionComparator.cpp
  llvm/lib/Transforms/Utils/ValueMapper.cpp
  llvm/tools/llvm-reduce/deltas/ReduceAttributes.cpp
  llvm/unittests/IR/AttributesTest.cpp
  llvm/unittests/Transforms/Utils/VFABIUtils.cpp

Index: llvm/unittests/Transforms/Utils/VFABIUtils.cpp
===
--- llvm/unittests/Transforms/Utils/VFABIUtils.cpp
+++ llvm/unittests/Transforms/Utils/VFABIUtils.cpp
@@ -46,8 +46,7 @@
   Mappings.push_back("_ZGVnN8v_g");
   Mappings.push_back("_ZGVnN2v_g(custom_vg)");
   VFABI::setVectorVariantNames(CI, Mappings);
-  const StringRef S = CI->getAttribute(AttributeList::FunctionIndex,
-   "vector-function-abi-variant")
-  .getValueAsString();
+  const StringRef S =
+  CI->getFnAttr("vector-function-abi-variant").getValueAsString();
   EXPECT_EQ(S, "_ZGVnN8v_g,_ZGVnN2v_g(custom_vg)");
 }
Index: llvm/unittests/IR/AttributesTest.cpp
===
--- llvm/unittests/IR/AttributesTest.cpp
+++ llvm/unittests/IR/AttributesTest.cpp
@@ -54,7 +54,8 @@
  AttributeList::get(C, 1, Attribute::SExt)};
 
   AttributeList SetA = AttributeList::get(C, ASs);
-  AttributeList SetB = SetA.removeAttributes(C, 1, ASs[1].getAttributes(1));
+  AttributeList SetB =
+  SetA.removeAttributes(C, 1, ASs[1].getParamAttributes(0));
   EXPECT_NE(SetA, SetB);
 }
 
@@ -68,7 +69,7 @@
   B.clear();
   B.addAttribute(Attribute::SExt);
   AL = AL.addAttributes(C, AttributeList::ReturnIndex, B);
-  EXPECT_TRUE(AL.hasAttribute(AttributeList::ReturnIndex, Attribute::SExt));
+  EXPECT_TRUE(AL.hasRetAttr(Attribute::SExt));
   EXPECT_TRUE(AL.hasFnAttribute(Attribute::NoReturn));
 }
 
@@ -102,9 +103,9 @@
   AttributeList AL;
   AL = AL.addParamAttributes(C, 0, B_align_readonly);
   AL = AL.addAttributes(C, 0, B_stackalign_optnone);
-  

[PATCH] D107939: [clang][Arm] Fix the default floating point ABI for 'armv7-pc-win32-macho'

2021-08-12 Thread Akira Hatanaka via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rGee620b1743bc: [clang][Arm] Fix the default floating point 
ABI for (authored by sarahpurohit, committed by ahatanak).

Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D107939/new/

https://reviews.llvm.org/D107939

Files:
  clang/lib/Driver/ToolChains/Arch/ARM.cpp
  clang/test/Driver/windows-macho.c


Index: clang/test/Driver/windows-macho.c
===
--- /dev/null
+++ clang/test/Driver/windows-macho.c
@@ -0,0 +1,11 @@
+// RUN: %clang -target armv7-pc-win32-macho -msoft-float -### -c %s 2>&1 \
+// RUN: | FileCheck %s --check-prefix CHECK-SOFTFLOAT
+// CHECK-SOFTFLOAT-NOT: error: unsupported option '-msoft-float' for target 
'thumbv7-pc-windows-macho'
+
+// RUN: %clang -target armv7-pc-win32-macho -mhard-float -### -c %s 2>&1 \
+// RUN: | FileCheck %s --check-prefix CHECK-HARDFLOAT
+// CHECK-HARDFLOAT: error: unsupported option '-mhard-float' for target 
'thumbv7-pc-windows-macho'
+
+// RUN: %clang -target armv7-pc-win32-macho -### -c %s 2>&1 \
+// RUN: | FileCheck %s --check-prefix CHECK-DEFAULT-SOFTFLOAT-ABI
+// CHECK-DEFAULT-SOFTFLOAT-ABI: "-mfloat-abi" "soft"
Index: clang/lib/Driver/ToolChains/Arch/ARM.cpp
===
--- clang/lib/Driver/ToolChains/Arch/ARM.cpp
+++ clang/lib/Driver/ToolChains/Arch/ARM.cpp
@@ -314,6 +314,10 @@
 
   // FIXME: this is invalid for WindowsCE
   case llvm::Triple::Win32:
+// It is incorrect to select hard float ABI on MachO platforms if the ABI 
is
+// "apcs-gnu".
+if (Triple.isOSBinFormatMachO() && !useAAPCSForMachO(Triple))
+  return FloatABI::Soft;
 return FloatABI::Hard;
 
   case llvm::Triple::NetBSD:


Index: clang/test/Driver/windows-macho.c
===
--- /dev/null
+++ clang/test/Driver/windows-macho.c
@@ -0,0 +1,11 @@
+// RUN: %clang -target armv7-pc-win32-macho -msoft-float -### -c %s 2>&1 \
+// RUN: | FileCheck %s --check-prefix CHECK-SOFTFLOAT
+// CHECK-SOFTFLOAT-NOT: error: unsupported option '-msoft-float' for target 'thumbv7-pc-windows-macho'
+
+// RUN: %clang -target armv7-pc-win32-macho -mhard-float -### -c %s 2>&1 \
+// RUN: | FileCheck %s --check-prefix CHECK-HARDFLOAT
+// CHECK-HARDFLOAT: error: unsupported option '-mhard-float' for target 'thumbv7-pc-windows-macho'
+
+// RUN: %clang -target armv7-pc-win32-macho -### -c %s 2>&1 \
+// RUN: | FileCheck %s --check-prefix CHECK-DEFAULT-SOFTFLOAT-ABI
+// CHECK-DEFAULT-SOFTFLOAT-ABI: "-mfloat-abi" "soft"
Index: clang/lib/Driver/ToolChains/Arch/ARM.cpp
===
--- clang/lib/Driver/ToolChains/Arch/ARM.cpp
+++ clang/lib/Driver/ToolChains/Arch/ARM.cpp
@@ -314,6 +314,10 @@
 
   // FIXME: this is invalid for WindowsCE
   case llvm::Triple::Win32:
+// It is incorrect to select hard float ABI on MachO platforms if the ABI is
+// "apcs-gnu".
+if (Triple.isOSBinFormatMachO() && !useAAPCSForMachO(Triple))
+  return FloatABI::Soft;
 return FloatABI::Hard;
 
   case llvm::Triple::NetBSD:
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] ee620b1 - [clang][Arm] Fix the default floating point ABI for

2021-08-12 Thread Akira Hatanaka via cfe-commits

Author: Sarah Purohit
Date: 2021-08-12T21:46:30-07:00
New Revision: ee620b1743bc524ce4b84d8113cb5b43ddcf3b59

URL: 
https://github.com/llvm/llvm-project/commit/ee620b1743bc524ce4b84d8113cb5b43ddcf3b59
DIFF: 
https://github.com/llvm/llvm-project/commit/ee620b1743bc524ce4b84d8113cb5b43ddcf3b59.diff

LOG: [clang][Arm] Fix the default floating point ABI for
'armv7-pc-win32-macho'

It is incorrect to select the hardware floating point ABI on Mach-O
platforms using the Windows triple if the ABI is "apcs-gnu".

rdar://81810554

Differential Revision: https://reviews.llvm.org/D107939

Added: 
clang/test/Driver/windows-macho.c

Modified: 
clang/lib/Driver/ToolChains/Arch/ARM.cpp

Removed: 




diff  --git a/clang/lib/Driver/ToolChains/Arch/ARM.cpp 
b/clang/lib/Driver/ToolChains/Arch/ARM.cpp
index 4ab547fabe43..a6cf378f81f3 100644
--- a/clang/lib/Driver/ToolChains/Arch/ARM.cpp
+++ b/clang/lib/Driver/ToolChains/Arch/ARM.cpp
@@ -314,6 +314,10 @@ arm::FloatABI arm::getDefaultFloatABI(const llvm::Triple 
) {
 
   // FIXME: this is invalid for WindowsCE
   case llvm::Triple::Win32:
+// It is incorrect to select hard float ABI on MachO platforms if the ABI 
is
+// "apcs-gnu".
+if (Triple.isOSBinFormatMachO() && !useAAPCSForMachO(Triple))
+  return FloatABI::Soft;
 return FloatABI::Hard;
 
   case llvm::Triple::NetBSD:

diff  --git a/clang/test/Driver/windows-macho.c 
b/clang/test/Driver/windows-macho.c
new file mode 100644
index ..9e0a966937fa
--- /dev/null
+++ b/clang/test/Driver/windows-macho.c
@@ -0,0 +1,11 @@
+// RUN: %clang -target armv7-pc-win32-macho -msoft-float -### -c %s 2>&1 \
+// RUN: | FileCheck %s --check-prefix CHECK-SOFTFLOAT
+// CHECK-SOFTFLOAT-NOT: error: unsupported option '-msoft-float' for target 
'thumbv7-pc-windows-macho'
+
+// RUN: %clang -target armv7-pc-win32-macho -mhard-float -### -c %s 2>&1 \
+// RUN: | FileCheck %s --check-prefix CHECK-HARDFLOAT
+// CHECK-HARDFLOAT: error: unsupported option '-mhard-float' for target 
'thumbv7-pc-windows-macho'
+
+// RUN: %clang -target armv7-pc-win32-macho -### -c %s 2>&1 \
+// RUN: | FileCheck %s --check-prefix CHECK-DEFAULT-SOFTFLOAT-ABI
+// CHECK-DEFAULT-SOFTFLOAT-ABI: "-mfloat-abi" "soft"



___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D107939: [clang][Arm] Fix the default floating point ABI for 'armv7-pc-win32-macho'

2021-08-12 Thread Sarah Purohit via Phabricator via cfe-commits
sarahpurohit updated this revision to Diff 366179.
sarahpurohit added a comment.

Resolved syntax error with braces. No functional change otherwise.


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D107939/new/

https://reviews.llvm.org/D107939

Files:
  clang/lib/Driver/ToolChains/Arch/ARM.cpp
  clang/test/Driver/windows-macho.c


Index: clang/test/Driver/windows-macho.c
===
--- /dev/null
+++ clang/test/Driver/windows-macho.c
@@ -0,0 +1,11 @@
+// RUN: %clang -target armv7-pc-win32-macho -msoft-float -### -c %s 2>&1 \
+// RUN: | FileCheck %s --check-prefix CHECK-SOFTFLOAT
+// CHECK-SOFTFLOAT-NOT: error: unsupported option '-msoft-float' for target 
'thumbv7-pc-windows-macho'
+
+// RUN: %clang -target armv7-pc-win32-macho -mhard-float -### -c %s 2>&1 \
+// RUN: | FileCheck %s --check-prefix CHECK-HARDFLOAT
+// CHECK-HARDFLOAT: error: unsupported option '-mhard-float' for target 
'thumbv7-pc-windows-macho'
+
+// RUN: %clang -target armv7-pc-win32-macho -### -c %s 2>&1 \
+// RUN: | FileCheck %s --check-prefix CHECK-DEFAULT-SOFTFLOAT-ABI
+// CHECK-DEFAULT-SOFTFLOAT-ABI: "-mfloat-abi" "soft"
Index: clang/lib/Driver/ToolChains/Arch/ARM.cpp
===
--- clang/lib/Driver/ToolChains/Arch/ARM.cpp
+++ clang/lib/Driver/ToolChains/Arch/ARM.cpp
@@ -314,6 +314,10 @@
 
   // FIXME: this is invalid for WindowsCE
   case llvm::Triple::Win32:
+// It is incorrect to select hard float ABI on MachO platforms if the ABI 
is
+// "apcs-gnu".
+if (Triple.isOSBinFormatMachO() && !useAAPCSForMachO(Triple))
+  return FloatABI::Soft;
 return FloatABI::Hard;
 
   case llvm::Triple::NetBSD:


Index: clang/test/Driver/windows-macho.c
===
--- /dev/null
+++ clang/test/Driver/windows-macho.c
@@ -0,0 +1,11 @@
+// RUN: %clang -target armv7-pc-win32-macho -msoft-float -### -c %s 2>&1 \
+// RUN: | FileCheck %s --check-prefix CHECK-SOFTFLOAT
+// CHECK-SOFTFLOAT-NOT: error: unsupported option '-msoft-float' for target 'thumbv7-pc-windows-macho'
+
+// RUN: %clang -target armv7-pc-win32-macho -mhard-float -### -c %s 2>&1 \
+// RUN: | FileCheck %s --check-prefix CHECK-HARDFLOAT
+// CHECK-HARDFLOAT: error: unsupported option '-mhard-float' for target 'thumbv7-pc-windows-macho'
+
+// RUN: %clang -target armv7-pc-win32-macho -### -c %s 2>&1 \
+// RUN: | FileCheck %s --check-prefix CHECK-DEFAULT-SOFTFLOAT-ABI
+// CHECK-DEFAULT-SOFTFLOAT-ABI: "-mfloat-abi" "soft"
Index: clang/lib/Driver/ToolChains/Arch/ARM.cpp
===
--- clang/lib/Driver/ToolChains/Arch/ARM.cpp
+++ clang/lib/Driver/ToolChains/Arch/ARM.cpp
@@ -314,6 +314,10 @@
 
   // FIXME: this is invalid for WindowsCE
   case llvm::Triple::Win32:
+// It is incorrect to select hard float ABI on MachO platforms if the ABI is
+// "apcs-gnu".
+if (Triple.isOSBinFormatMachO() && !useAAPCSForMachO(Triple))
+  return FloatABI::Soft;
 return FloatABI::Hard;
 
   case llvm::Triple::NetBSD:
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D107961: [clang-format] Distinguish K C function definition and attribute

2021-08-12 Thread Owen Pan via Phabricator via cfe-commits
owenpan updated this revision to Diff 366176.
owenpan added a comment.

Added keywords `register`, `struct`, and `union` back.


CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D107961/new/

https://reviews.llvm.org/D107961

Files:
  clang/lib/Format/UnwrappedLineParser.cpp
  clang/unittests/Format/FormatTest.cpp


Index: clang/unittests/Format/FormatTest.cpp
===
--- clang/unittests/Format/FormatTest.cpp
+++ clang/unittests/Format/FormatTest.cpp
@@ -8247,6 +8247,13 @@
"  return a + b < c;\n"
"};",
Style);
+  verifyFormat("byte *\n" // Break here.
+   "f(a)\n"   // Break here.
+   "byte a[];\n"
+   "{\n"
+   "  return a;\n"
+   "}",
+   Style);
 
   // The return breaking style doesn't affect:
   // * function and object definitions with attribute-like macros
Index: clang/lib/Format/UnwrappedLineParser.cpp
===
--- clang/lib/Format/UnwrappedLineParser.cpp
+++ clang/lib/Format/UnwrappedLineParser.cpp
@@ -14,7 +14,6 @@
 
 #include "UnwrappedLineParser.h"
 #include "FormatToken.h"
-#include "clang/Basic/TokenKinds.h"
 #include "llvm/ADT/STLExtras.h"
 #include "llvm/Support/Debug.h"
 #include "llvm/Support/raw_ostream.h"
@@ -995,6 +994,14 @@
   Keywords.kw_import, tok::kw_export);
 }
 
+// This function checks whether a token is a K C (aka C78) type including
+// user-defined types.
+static bool isC78Type(const FormatToken ) {
+  return Tok.isOneOf(tok::kw_char, tok::kw_short, tok::kw_int, tok::kw_long,
+ tok::kw_unsigned, tok::kw_float, tok::kw_double,
+ tok::identifier);
+}
+
 // This function checks whether a token starts the first parameter declaration
 // in a K C (aka C78) function definition, e.g.:
 //   int f(a, b)
@@ -1006,9 +1013,8 @@
   if (!Tok)
 return false;
 
-  if (!Tok->isOneOf(tok::kw_int, tok::kw_char, tok::kw_float, tok::kw_double,
-tok::kw_struct, tok::kw_union, tok::kw_long, tok::kw_short,
-tok::kw_unsigned, tok::kw_register))
+  if (!isC78Type(*Tok) &&
+  !Tok->isOneOf(tok::kw_register, tok::kw_struct, tok::kw_union))
 return false;
 
   Tok = Tok->Previous;
@@ -1369,7 +1375,7 @@
 case tok::r_brace:
   addUnwrappedLine();
   return;
-case tok::l_paren:
+case tok::l_paren: {
   parseParens();
   // Break the unwrapped line if a K C function definition has a 
parameter
   // declaration.
@@ -1377,14 +1383,18 @@
 break;
   if (!Previous || Previous->isNot(tok::identifier))
 break;
-  if (Previous->Previous && Previous->Previous->is(tok::at))
+  const FormatToken *PrevPrev = Previous->Previous;
+  if (!PrevPrev || (!isC78Type(*PrevPrev) && PrevPrev->isNot(tok::star)))
 break;
-  if (!Line->Tokens.begin()->Tok->is(tok::kw_typedef) &&
-  isC78ParameterDecl(FormatTok)) {
+  const FormatToken *Next = AllTokens[Tokens->getPosition() + 1];
+  if (Next && Next->is(tok::l_paren))
+break;
+  if (isC78ParameterDecl(FormatTok)) {
 addUnwrappedLine();
 return;
   }
   break;
+}
 case tok::kw_operator:
   nextToken();
   if (FormatTok->isBinaryOperator())


Index: clang/unittests/Format/FormatTest.cpp
===
--- clang/unittests/Format/FormatTest.cpp
+++ clang/unittests/Format/FormatTest.cpp
@@ -8247,6 +8247,13 @@
"  return a + b < c;\n"
"};",
Style);
+  verifyFormat("byte *\n" // Break here.
+   "f(a)\n"   // Break here.
+   "byte a[];\n"
+   "{\n"
+   "  return a;\n"
+   "}",
+   Style);
 
   // The return breaking style doesn't affect:
   // * function and object definitions with attribute-like macros
Index: clang/lib/Format/UnwrappedLineParser.cpp
===
--- clang/lib/Format/UnwrappedLineParser.cpp
+++ clang/lib/Format/UnwrappedLineParser.cpp
@@ -14,7 +14,6 @@
 
 #include "UnwrappedLineParser.h"
 #include "FormatToken.h"
-#include "clang/Basic/TokenKinds.h"
 #include "llvm/ADT/STLExtras.h"
 #include "llvm/Support/Debug.h"
 #include "llvm/Support/raw_ostream.h"
@@ -995,6 +994,14 @@
   Keywords.kw_import, tok::kw_export);
 }
 
+// This function checks whether a token is a K C (aka C78) type including
+// user-defined types.
+static bool isC78Type(const FormatToken ) {
+  return Tok.isOneOf(tok::kw_char, tok::kw_short, tok::kw_int, tok::kw_long,
+ tok::kw_unsigned, tok::kw_float, tok::kw_double,
+ tok::identifier);
+}
+
 // This function checks whether a token starts the first parameter declaration
 // in a K C (aka C78) function definition, 

[PATCH] D107939: [clang][Arm] Fix the default floating point ABI for 'armv7-pc-win32-macho'

2021-08-12 Thread Sarah Purohit via Phabricator via cfe-commits
sarahpurohit accepted this revision.
sarahpurohit added a comment.

I do not have commit access. Can someone pull this?


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D107939/new/

https://reviews.llvm.org/D107939

___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D105265: [X86] AVX512FP16 instructions enabling 3/6

2021-08-12 Thread Craig Topper via Phabricator via cfe-commits
craig.topper added inline comments.



Comment at: clang/lib/Headers/avx512fp16intrin.h:953
+#define _mm512_cvt_roundpd_ph(A, R)
\
+  (__m128h) __builtin_ia32_vcvtpd2ph512_mask(  
\
+  (__v8df)(A), (__v8hf)_mm_undefined_ph(), (__mmask8)(-1), (int)(R))

Put extra parentheses here to avoid repeating PR51324. Same for any macro that 
has a typecast of builtin result.


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D105265/new/

https://reviews.llvm.org/D105265

___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D105264: [X86] AVX512FP16 instructions enabling 2/6

2021-08-12 Thread LuoYuanke via Phabricator via cfe-commits
LuoYuanke accepted this revision.
LuoYuanke added a comment.
This revision is now accepted and ready to land.

LGTM, but may wait 1 or 2 days for the comments from others.


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D105264/new/

https://reviews.llvm.org/D105264

___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D105264: [X86] AVX512FP16 instructions enabling 2/6

2021-08-12 Thread LuoYuanke via Phabricator via cfe-commits
LuoYuanke added inline comments.



Comment at: clang/lib/Headers/avx512vlfp16intrin.h:368
+_mm256_reduce_add_ph(__m256h __W) {
+  return __builtin_ia32_reduce_fadd_ph256(0.0f16, __W);
+}

From https://llvm.org/docs/LangRef.html#llvm-vector-reduce-add-intrinsic, 
-0.0f16 is better?


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D105264/new/

https://reviews.llvm.org/D105264

___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D105265: [X86] AVX512FP16 instructions enabling 3/6

2021-08-12 Thread Pengfei Wang via Phabricator via cfe-commits
pengfei added inline comments.



Comment at: clang/lib/Headers/avx512fp16intrin.h:1748
+
+#define _mm_cvt_roundsh_i32(A, R)  
\
+  (int)__builtin_ia32_vcvtsh2si32((__v8hf)(A), (int)(R))

LuoYuanke wrote:
> Does it also return i32 in x86_64 platform? We may unify the intrinsic both 
> for x86 and x86_x64 to return i32.
Yes. This is used for both x86 and x86_x64.



Comment at: clang/lib/Headers/avx512fp16intrin.h:1874
+
+static __inline__ __m512 __DEFAULT_FN_ATTRS512 _mm512_cvtxph_ps(__m256h __A) {
+  return (__m512)__builtin_ia32_vcvtph2psx512_mask(

LuoYuanke wrote:
> VCVTPH2PSX support broadcast compared to VCVTPH2PS, but for intrinsics there 
> is no difference. Do we need to add the new intrinsics? Ditto for its 
> variants.
Yes. The difference is the type. We previously use `__m256i` for the half 
vector since `_Float16` is not a legal type then.


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D105265/new/

https://reviews.llvm.org/D105265

___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D107540: [OMPIRBuilder] Clarify CanonicalLoopInfo. NFC.

2021-08-12 Thread Michael Kruse via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rGb1de32d6ddd9: [OMPIRBuilder] Clarify CanonicalLoopInfo. NFC. 
(authored by Meinersbur).

Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D107540/new/

https://reviews.llvm.org/D107540

Files:
  clang/lib/CodeGen/CGStmtOpenMP.cpp
  llvm/include/llvm/Frontend/OpenMP/OMPIRBuilder.h
  llvm/lib/Frontend/OpenMP/OMPIRBuilder.cpp
  llvm/unittests/Frontend/OpenMPIRBuilderTest.cpp
  mlir/lib/Target/LLVMIR/Dialect/OpenMP/OpenMPToLLVMIRTranslation.cpp

Index: mlir/lib/Target/LLVMIR/Dialect/OpenMP/OpenMPToLLVMIRTranslation.cpp
===
--- mlir/lib/Target/LLVMIR/Dialect/OpenMP/OpenMPToLLVMIRTranslation.cpp
+++ mlir/lib/Target/LLVMIR/Dialect/OpenMP/OpenMPToLLVMIRTranslation.cpp
@@ -338,8 +338,8 @@
   llvm::OpenMPIRBuilder::InsertPointTy allocaIP =
   findAllocaInsertPoint(builder, moduleTranslation);
   if (schedule == omp::ClauseScheduleKind::Static) {
-ompBuilder->createStaticWorkshareLoop(ompLoc, loopInfo, allocaIP,
-  !loop.nowait(), chunk);
+ompBuilder->applyStaticWorkshareLoop(ompLoc.DL, loopInfo, allocaIP,
+ !loop.nowait(), chunk);
   } else {
 llvm::omp::OMPScheduleType schedType;
 switch (schedule) {
@@ -360,8 +360,8 @@
   break;
 }
 
-ompBuilder->createDynamicWorkshareLoop(ompLoc, loopInfo, allocaIP,
-   schedType, !loop.nowait(), chunk);
+ompBuilder->applyDynamicWorkshareLoop(ompLoc.DL, loopInfo, allocaIP,
+  schedType, !loop.nowait(), chunk);
   }
 
   // Continue building IR after the loop. Note that the LoopInfo returned by
Index: llvm/unittests/Frontend/OpenMPIRBuilderTest.cpp
===
--- llvm/unittests/Frontend/OpenMPIRBuilderTest.cpp
+++ llvm/unittests/Frontend/OpenMPIRBuilderTest.cpp
@@ -1586,6 +1586,7 @@
 CanonicalLoopInfo *Loop =
 OMPBuilder.createCanonicalLoop(Loc, LoopBodyGenCB, StartVal, StopVal,
StepVal, IsSigned, InclusiveStop);
+InsertPointTy AfterIP = Loop->getAfterIP();
 
 // Tile the loop.
 Value *TileSizeVal = ConstantInt::get(LCTy, TileSize);
@@ -1594,7 +1595,7 @@
 
 // Set the insertion pointer to after loop, where the next loop will be
 // emitted.
-Builder.restoreIP(Loop->getAfterIP());
+Builder.restoreIP(AfterIP);
 
 // Extract the trip count.
 CanonicalLoopInfo *FloorLoop = GenLoops[0];
@@ -1663,12 +1664,20 @@
   CanonicalLoopInfo *CLI = OMPBuilder.createCanonicalLoop(
   Loc, LoopBodyGen, StartVal, StopVal, StepVal,
   /*IsSigned=*/false, /*InclusiveStop=*/false);
+  BasicBlock *Preheader = CLI->getPreheader();
+  BasicBlock *Body = CLI->getBody();
+  Value *IV = CLI->getIndVar();
+  BasicBlock *ExitBlock = CLI->getExit();
 
   Builder.SetInsertPoint(BB, BB->getFirstInsertionPt());
   InsertPointTy AllocaIP = Builder.saveIP();
 
-  CLI = OMPBuilder.createStaticWorkshareLoop(Loc, CLI, AllocaIP,
- /*NeedsBarrier=*/true);
+  OMPBuilder.applyStaticWorkshareLoop(DL, CLI, AllocaIP, /*NeedsBarrier=*/true);
+
+  BasicBlock *Cond = Body->getSinglePredecessor();
+  Instruction *Cmp = &*Cond->begin();
+  Value *TripCount = Cmp->getOperand(1);
+
   auto AllocaIter = BB->begin();
   ASSERT_GE(std::distance(BB->begin(), BB->end()), 4);
   AllocaInst *PLastIter = dyn_cast(&*(AllocaIter++));
@@ -1680,10 +1689,8 @@
   EXPECT_NE(PUpperBound, nullptr);
   EXPECT_NE(PStride, nullptr);
 
-  auto PreheaderIter = CLI->getPreheader()->begin();
-  ASSERT_GE(
-  std::distance(CLI->getPreheader()->begin(), CLI->getPreheader()->end()),
-  7);
+  auto PreheaderIter = Preheader->begin();
+  ASSERT_GE(std::distance(Preheader->begin(), Preheader->end()), 7);
   StoreInst *LowerBoundStore = dyn_cast(&*(PreheaderIter++));
   StoreInst *UpperBoundStore = dyn_cast(&*(PreheaderIter++));
   StoreInst *StrideStore = dyn_cast(&*(PreheaderIter++));
@@ -1705,15 +1712,15 @@
 
   // Check that the loop IV is updated to account for the lower bound returned
   // by the OpenMP runtime call.
-  BinaryOperator *Add = dyn_cast(>getBody()->front());
-  EXPECT_EQ(Add->getOperand(0), CLI->getIndVar());
+  BinaryOperator *Add = dyn_cast(>front());
+  EXPECT_EQ(Add->getOperand(0), IV);
   auto *LoadedLowerBound = dyn_cast(Add->getOperand(1));
   ASSERT_NE(LoadedLowerBound, nullptr);
   EXPECT_EQ(LoadedLowerBound->getPointerOperand(), PLowerBound);
 
   // Check that the trip count is updated to account for the lower and upper
   // bounds return by the OpenMP runtime call.
-  auto *AddOne = dyn_cast(CLI->getTripCount());
+  auto *AddOne = dyn_cast(TripCount);
   ASSERT_NE(AddOne, nullptr);
   ASSERT_TRUE(AddOne->isBinaryOp());
   auto *One = 

[clang] b1de32d - [OMPIRBuilder] Clarify CanonicalLoopInfo. NFC.

2021-08-12 Thread Michael Kruse via cfe-commits

Author: Michael Kruse
Date: 2021-08-12T21:02:19-05:00
New Revision: b1de32d6ddd90046171ecee0047fbf448a97e16f

URL: 
https://github.com/llvm/llvm-project/commit/b1de32d6ddd90046171ecee0047fbf448a97e16f
DIFF: 
https://github.com/llvm/llvm-project/commit/b1de32d6ddd90046171ecee0047fbf448a97e16f.diff

LOG: [OMPIRBuilder] Clarify CanonicalLoopInfo. NFC.

Add in-source documentation on how CanonicalLoopInfo is intended to be used. In 
particular, clarify what parts of a CanonicalLoopInfo is considered part of the 
loop, that those parts must be side-effect free, and that InsertPoints to 
instructions outside those parts can be expected to be preserved after method 
calls implementing loop-associated directives.

CanonicalLoopInfo are now invalidated after it does not describe canonical loop 
anymore and asserts when trying to use it afterwards.

In addition, rename `createXYZWorkshareLoop` to `applyXYZWorkshareLoop` and 
remove the update location to avoid that the impression that they insert 
something from scratch at that location where in reality its InsertPoint is 
ignored. createStaticWorkshareLoop does not return a CanonicalLoopInfo anymore. 
First, it was not a canonical loop in the clarified sense (containing 
side-effects in form of calls to the OpenMP runtime). Second, it is ambiguous 
which of the two possible canonical loops it should actually return. It will 
not be needed before a feature expected to be introduced in OpenMP 6.0

Also see discussion in D105706.

Reviewed By: ftynse

Differential Revision: https://reviews.llvm.org/D107540

Added: 


Modified: 
clang/lib/CodeGen/CGStmtOpenMP.cpp
llvm/include/llvm/Frontend/OpenMP/OMPIRBuilder.h
llvm/lib/Frontend/OpenMP/OMPIRBuilder.cpp
llvm/unittests/Frontend/OpenMPIRBuilderTest.cpp
mlir/lib/Target/LLVMIR/Dialect/OpenMP/OpenMPToLLVMIRTranslation.cpp

Removed: 




diff  --git a/clang/lib/CodeGen/CGStmtOpenMP.cpp 
b/clang/lib/CodeGen/CGStmtOpenMP.cpp
index f71f7b24a36ae..2328dd8198426 100644
--- a/clang/lib/CodeGen/CGStmtOpenMP.cpp
+++ b/clang/lib/CodeGen/CGStmtOpenMP.cpp
@@ -3621,7 +3621,8 @@ void CodeGenFunction::EmitOMPForDirective(const 
OMPForDirective ) {
   CGM.getOpenMPRuntime().getOMPBuilder();
   llvm::OpenMPIRBuilder::InsertPointTy AllocaIP(
   AllocaInsertPt->getParent(), AllocaInsertPt->getIterator());
-  OMPBuilder.createWorkshareLoop(Builder, CLI, AllocaIP, NeedsBarrier);
+  OMPBuilder.applyWorkshareLoop(Builder.getCurrentDebugLocation(), CLI,
+AllocaIP, NeedsBarrier);
   return;
 }
 

diff  --git a/llvm/include/llvm/Frontend/OpenMP/OMPIRBuilder.h 
b/llvm/include/llvm/Frontend/OpenMP/OMPIRBuilder.h
index ef4e387ec8edc..9e242b04cc6a5 100644
--- a/llvm/include/llvm/Frontend/OpenMP/OMPIRBuilder.h
+++ b/llvm/include/llvm/Frontend/OpenMP/OMPIRBuilder.h
@@ -257,18 +257,17 @@ class OpenMPIRBuilder {
   ///
   ///  * Sign of the step and the comparison operator might disagree:
   ///
-  ///  for (int i = 0; i < 42; --i)
+  ///  for (int i = 0; i < 42; i -= 1u)
   ///
   //
   /// \param Loc   The insert and source location description.
   /// \param BodyGenCB Callback that will generate the loop body code.
   /// \param Start Value of the loop counter for the first iterations.
-  /// \param Stop  Loop counter values past this will stop the the
-  ///  iterations.
+  /// \param Stop  Loop counter values past this will stop the loop.
   /// \param Step  Loop counter increment after each iteration; negative
-  ///  means counting down. \param IsSigned  Whether Start, 
Stop
-  ///  and Stop are signed integers.
-  /// \param InclusiveStop Whether  \p Stop itself is a valid value for the 
loop
+  ///  means counting down.
+  /// \param IsSigned  Whether Start, Stop and Step are signed integers.
+  /// \param InclusiveStop Whether \p Stop itself is a valid value for the loop
   ///  counter.
   /// \param ComputeIP Insertion point for instructions computing the trip
   ///  count. Can be used to ensure the trip count is available
@@ -335,7 +334,7 @@ class OpenMPIRBuilder {
   ///has a trip count of 0). This is permitted by the OpenMP specification.
   ///
   /// \param DLDebug location for instructions added for collapsing,
-  ///  such as instructions to compute derive the input loop's
+  ///  such as instructions to compute/derive the input loop's
   ///  induction variables.
   /// \param Loops Loops in the loop nest to collapse. Loops are specified
   ///  from outermost-to-innermost and every control flow of a
@@ -358,8 +357,16 @@ class OpenMPIRBuilder {
   /// the current thread, updates the relevant instructions in the canonical
   /// loop and calls to an OpenMP 

[PATCH] D107939: [clang][Arm] Fix the default floating point ABI for 'armv7-pc-win32-macho'

2021-08-12 Thread Akira Hatanaka via Phabricator via cfe-commits
ahatanak accepted this revision.
ahatanak added a comment.
This revision is now accepted and ready to land.

LGTM




Comment at: clang/lib/Driver/ToolChains/Arch/ARM.cpp:319
+// "apcs-gnu".
+if (Triple.isOSBinFormatMachO() && !useAAPCSForMachO(Triple)) {
+  return FloatABI::Soft;

You can omit the braces.

https://llvm.org/docs/CodingStandards.html#don-t-use-braces-on-simple-single-statement-bodies-of-if-else-loop-statements


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D107939/new/

https://reviews.llvm.org/D107939

___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D107703: [AST][clangd] Expose documentation of Attrs on hover.

2021-08-12 Thread Nico Weber via Phabricator via cfe-commits
thakis added a comment.

Also, I tweaked the tablegen bits a bit to be more like all the other tablegen 
bits in 189911203779e793cb7767ad233d9994a88c7ea3 
. Hope 
that's ok :)


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D107703/new/

https://reviews.llvm.org/D107703

___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] 1899112 - [gn build] manually port 18f9e25ce1fa43 (AttrDocTable)

2021-08-12 Thread Nico Weber via cfe-commits

Author: Nico Weber
Date: 2021-08-12T21:30:59-04:00
New Revision: 189911203779e793cb7767ad233d9994a88c7ea3

URL: 
https://github.com/llvm/llvm-project/commit/189911203779e793cb7767ad233d9994a88c7ea3
DIFF: 
https://github.com/llvm/llvm-project/commit/189911203779e793cb7767ad233d9994a88c7ea3.diff

LOG: [gn build] manually port 18f9e25ce1fa43 (AttrDocTable)

Also clang ClangAttrEmitter for -gen-clang-attr-doc-table to be
like all other tablegen: Produce a .inc file with the generated bits
and put the static parts into a regular .cpp file that includes the
.inc file.

Added: 
clang/lib/AST/AttrDocTable.cpp

Modified: 
clang/lib/AST/CMakeLists.txt
clang/utils/TableGen/ClangAttrEmitter.cpp
llvm/utils/gn/secondary/clang/lib/AST/BUILD.gn
llvm/utils/gn/secondary/clang/unittests/AST/BUILD.gn

Removed: 




diff  --git a/clang/lib/AST/AttrDocTable.cpp b/clang/lib/AST/AttrDocTable.cpp
new file mode 100644
index 0..3bfedac8b8f13
--- /dev/null
+++ b/clang/lib/AST/AttrDocTable.cpp
@@ -0,0 +1,27 @@
+//===--- AttrDocTable.cpp - implements Attr::getDocumentation() -*- C++ 
-*-===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+//
+//  This file contains out-of-line methods for Attr classes.
+//
+//===--===//
+
+#include "clang/AST/Attr.h"
+#include "llvm/ADT/StringRef.h"
+
+#include "AttrDocTable.inc"
+
+static const llvm::StringRef AttrDoc[] = {
+#define ATTR(NAME) AttrDoc_##NAME,
+#include "clang/Basic/AttrList.inc"
+};
+
+llvm::StringRef clang::Attr::getDocumentation(clang::attr::Kind K) {
+  if(K < llvm::array_lengthof(AttrDoc))
+return AttrDoc[K];
+  return "";
+}

diff  --git a/clang/lib/AST/CMakeLists.txt b/clang/lib/AST/CMakeLists.txt
index 2cb74a40b9800..9365a2272b3e7 100644
--- a/clang/lib/AST/CMakeLists.txt
+++ b/clang/lib/AST/CMakeLists.txt
@@ -13,7 +13,7 @@ clang_tablegen(Opcodes.inc
   SOURCE Interp/Opcodes.td
   TARGET Opcodes)
 
-clang_tablegen(AttrDocTable.cpp -gen-clang-attr-doc-table
+clang_tablegen(AttrDocTable.inc -gen-clang-attr-doc-table
   -I ${CMAKE_CURRENT_SOURCE_DIR}/../../include/
   SOURCE ${CMAKE_CURRENT_SOURCE_DIR}/../../include/clang/Basic/Attr.td
   TARGET ClangAttrDocTable)
@@ -124,6 +124,7 @@ add_clang_library(clangAST
   clangLex
 
   DEPENDS
+  ClangAttrDocTable
   Opcodes
   omp_gen
   )

diff  --git a/clang/utils/TableGen/ClangAttrEmitter.cpp 
b/clang/utils/TableGen/ClangAttrEmitter.cpp
index 345b13692b5ca..e5ac0847e1080 100644
--- a/clang/utils/TableGen/ClangAttrEmitter.cpp
+++ b/clang/utils/TableGen/ClangAttrEmitter.cpp
@@ -4207,10 +4207,6 @@ void 
EmitClangAttrSubjectMatchRulesParserStringSwitches(RecordKeeper ,
 void EmitClangAttrDocTable(RecordKeeper , raw_ostream ) {
   emitSourceFileHeader("Clang attribute documentation", OS);
 
-  OS << R"cpp(
-  #include "clang/AST/Attr.h"
-  #include "llvm/ADT/StringRef.h"
-  )cpp";
   std::vector Attrs = Records.getAllDerivedDefinitions("Attr");
   for (const auto *A : Attrs) {
 if (!A->getValueAsBit("ASTNode"))
@@ -4226,18 +4222,6 @@ void EmitClangAttrDocTable(RecordKeeper , 
raw_ostream ) {
   break;
 }
   }
-  OS << R"cpp(
-  static const llvm::StringRef AttrDoc[] = {
-  #define ATTR(NAME) AttrDoc_##NAME,
-  #include "clang/Basic/AttrList.inc"
-  };
-
-  llvm::StringRef clang::Attr::getDocumentation(clang::attr::Kind K) {
-if(K < llvm::array_lengthof(AttrDoc))
-  return AttrDoc[K];
-return "";
-  }
-  )cpp";
 }
 
 enum class SpellingKind {

diff  --git a/llvm/utils/gn/secondary/clang/lib/AST/BUILD.gn 
b/llvm/utils/gn/secondary/clang/lib/AST/BUILD.gn
index 4d645799dbf65..aee4db327096f 100644
--- a/llvm/utils/gn/secondary/clang/lib/AST/BUILD.gn
+++ b/llvm/utils/gn/secondary/clang/lib/AST/BUILD.gn
@@ -6,10 +6,17 @@ clang_tablegen("Opcodes") {
   td_file = "Interp/Opcodes.td"
 }
 
+clang_tablegen("AttrDocTable") {
+  visibility = [ ":AST" ]
+  args = [ "-gen-clang-attr-doc-table" ]
+  td_file = "//clang/include/clang/Basic/Attr.td"
+}
+
 static_library("AST") {
   output_name = "clangAST"
   configs += [ "//llvm/utils/gn/build:clang_code" ]
   deps = [
+":AttrDocTable",
 ":Opcodes",
 "//clang/include/clang/AST:AttrImpl",
 "//clang/include/clang/AST:AttrNodeTraverse",
@@ -51,6 +58,7 @@ static_library("AST") {
 "ASTImporterLookupTable.cpp",
 "ASTStructuralEquivalence.cpp",
 "ASTTypeTraits.cpp",
+"AttrDocTable.cpp",
 "AttrImpl.cpp",
 "CXXInheritance.cpp",
 "Comment.cpp",

diff  --git a/llvm/utils/gn/secondary/clang/unittests/AST/BUILD.gn 
b/llvm/utils/gn/secondary/clang/unittests/AST/BUILD.gn
index 127542d829f04..c275553d01c96 100644
--- 

[PATCH] D107703: [AST][clangd] Expose documentation of Attrs on hover.

2021-08-12 Thread Nico Weber via Phabricator via cfe-commits
thakis added a comment.

The docs are in rST format. Is that the format LSP wants?


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D107703/new/

https://reviews.llvm.org/D107703

___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D107540: [OMPIRBuilder] Clarify CanonicalLoopInfo. NFC.

2021-08-12 Thread Michael Kruse via Phabricator via cfe-commits
Meinersbur updated this revision to Diff 366161.
Meinersbur marked 7 inline comments as done.
Meinersbur added a comment.

- Address @ftynse's review


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D107540/new/

https://reviews.llvm.org/D107540

Files:
  clang/lib/CodeGen/CGStmtOpenMP.cpp
  llvm/include/llvm/Frontend/OpenMP/OMPIRBuilder.h
  llvm/lib/Frontend/OpenMP/OMPIRBuilder.cpp
  llvm/unittests/Frontend/OpenMPIRBuilderTest.cpp
  mlir/lib/Target/LLVMIR/Dialect/OpenMP/OpenMPToLLVMIRTranslation.cpp

Index: mlir/lib/Target/LLVMIR/Dialect/OpenMP/OpenMPToLLVMIRTranslation.cpp
===
--- mlir/lib/Target/LLVMIR/Dialect/OpenMP/OpenMPToLLVMIRTranslation.cpp
+++ mlir/lib/Target/LLVMIR/Dialect/OpenMP/OpenMPToLLVMIRTranslation.cpp
@@ -338,8 +338,8 @@
   llvm::OpenMPIRBuilder::InsertPointTy allocaIP =
   findAllocaInsertPoint(builder, moduleTranslation);
   if (schedule == omp::ClauseScheduleKind::Static) {
-ompBuilder->createStaticWorkshareLoop(ompLoc, loopInfo, allocaIP,
-  !loop.nowait(), chunk);
+ompBuilder->applyStaticWorkshareLoop(ompLoc.DL, loopInfo, allocaIP,
+ !loop.nowait(), chunk);
   } else {
 llvm::omp::OMPScheduleType schedType;
 switch (schedule) {
@@ -360,8 +360,8 @@
   break;
 }
 
-ompBuilder->createDynamicWorkshareLoop(ompLoc, loopInfo, allocaIP,
-   schedType, !loop.nowait(), chunk);
+ompBuilder->applyDynamicWorkshareLoop(ompLoc.DL, loopInfo, allocaIP,
+  schedType, !loop.nowait(), chunk);
   }
 
   // Continue building IR after the loop. Note that the LoopInfo returned by
Index: llvm/unittests/Frontend/OpenMPIRBuilderTest.cpp
===
--- llvm/unittests/Frontend/OpenMPIRBuilderTest.cpp
+++ llvm/unittests/Frontend/OpenMPIRBuilderTest.cpp
@@ -1586,6 +1586,7 @@
 CanonicalLoopInfo *Loop =
 OMPBuilder.createCanonicalLoop(Loc, LoopBodyGenCB, StartVal, StopVal,
StepVal, IsSigned, InclusiveStop);
+InsertPointTy AfterIP = Loop->getAfterIP();
 
 // Tile the loop.
 Value *TileSizeVal = ConstantInt::get(LCTy, TileSize);
@@ -1594,7 +1595,7 @@
 
 // Set the insertion pointer to after loop, where the next loop will be
 // emitted.
-Builder.restoreIP(Loop->getAfterIP());
+Builder.restoreIP(AfterIP);
 
 // Extract the trip count.
 CanonicalLoopInfo *FloorLoop = GenLoops[0];
@@ -1663,12 +1664,20 @@
   CanonicalLoopInfo *CLI = OMPBuilder.createCanonicalLoop(
   Loc, LoopBodyGen, StartVal, StopVal, StepVal,
   /*IsSigned=*/false, /*InclusiveStop=*/false);
+  BasicBlock *Preheader = CLI->getPreheader();
+  BasicBlock *Body = CLI->getBody();
+  Value *IV = CLI->getIndVar();
+  BasicBlock *ExitBlock = CLI->getExit();
 
   Builder.SetInsertPoint(BB, BB->getFirstInsertionPt());
   InsertPointTy AllocaIP = Builder.saveIP();
 
-  CLI = OMPBuilder.createStaticWorkshareLoop(Loc, CLI, AllocaIP,
- /*NeedsBarrier=*/true);
+  OMPBuilder.applyStaticWorkshareLoop(DL, CLI, AllocaIP, /*NeedsBarrier=*/true);
+
+  BasicBlock *Cond = Body->getSinglePredecessor();
+  Instruction *Cmp = &*Cond->begin();
+  Value *TripCount = Cmp->getOperand(1);
+
   auto AllocaIter = BB->begin();
   ASSERT_GE(std::distance(BB->begin(), BB->end()), 4);
   AllocaInst *PLastIter = dyn_cast(&*(AllocaIter++));
@@ -1680,10 +1689,8 @@
   EXPECT_NE(PUpperBound, nullptr);
   EXPECT_NE(PStride, nullptr);
 
-  auto PreheaderIter = CLI->getPreheader()->begin();
-  ASSERT_GE(
-  std::distance(CLI->getPreheader()->begin(), CLI->getPreheader()->end()),
-  7);
+  auto PreheaderIter = Preheader->begin();
+  ASSERT_GE(std::distance(Preheader->begin(), Preheader->end()), 7);
   StoreInst *LowerBoundStore = dyn_cast(&*(PreheaderIter++));
   StoreInst *UpperBoundStore = dyn_cast(&*(PreheaderIter++));
   StoreInst *StrideStore = dyn_cast(&*(PreheaderIter++));
@@ -1705,15 +1712,15 @@
 
   // Check that the loop IV is updated to account for the lower bound returned
   // by the OpenMP runtime call.
-  BinaryOperator *Add = dyn_cast(>getBody()->front());
-  EXPECT_EQ(Add->getOperand(0), CLI->getIndVar());
+  BinaryOperator *Add = dyn_cast(>front());
+  EXPECT_EQ(Add->getOperand(0), IV);
   auto *LoadedLowerBound = dyn_cast(Add->getOperand(1));
   ASSERT_NE(LoadedLowerBound, nullptr);
   EXPECT_EQ(LoadedLowerBound->getPointerOperand(), PLowerBound);
 
   // Check that the trip count is updated to account for the lower and upper
   // bounds return by the OpenMP runtime call.
-  auto *AddOne = dyn_cast(CLI->getTripCount());
+  auto *AddOne = dyn_cast(TripCount);
   ASSERT_NE(AddOne, nullptr);
   ASSERT_TRUE(AddOne->isBinaryOp());
   auto *One = dyn_cast(AddOne->getOperand(1));
@@ 

[PATCH] D106615: [Clang][LLVM] generate btf_tag annotations for DIComposite types

2021-08-12 Thread Yonghong Song via Phabricator via cfe-commits
yonghong-song added a comment.

@dblaikie The clang attr handling patch (D106614 
). Could you help review this patch which 
handles IR/BitCode Read/Write for btf_tag attributes?
This patch contains a common function which will be used by other DItypes, so 
this patch needs to be reviewed first.
If anybody else should review this patch, please let me know and I am happy to 
add them to reviewer list.

FYI. The following patches depends on this patch:

  https://reviews.llvm.org/D106616 (DIDerived type: struct/union members)
  https://reviews.llvm.org/D106618 (Subprogram type)
  https://reviews.llvm.org/D106619 (Global variable)
  https://reviews.llvm.org/D106620 (Function parameters)
  https://reviews.llvm.org/D106621 (output dwarf)


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D106615/new/

https://reviews.llvm.org/D106615

___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D106615: [Clang][LLVM] generate btf_tag annotations for DIComposite types

2021-08-12 Thread Yonghong Song via Phabricator via cfe-commits
yonghong-song updated this revision to Diff 366156.
yonghong-song added a comment.

- fix clang-format warnings.


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D106615/new/

https://reviews.llvm.org/D106615

Files:
  clang/lib/CodeGen/CGDebugInfo.cpp
  clang/lib/CodeGen/CGDebugInfo.h
  clang/test/CodeGen/attr-btf_tag-dicomposite.c
  llvm/include/llvm/IR/DebugInfoMetadata.h
  llvm/lib/AsmParser/LLParser.cpp
  llvm/lib/Bitcode/Reader/MetadataLoader.cpp
  llvm/lib/Bitcode/Writer/BitcodeWriter.cpp
  llvm/lib/IR/AsmWriter.cpp
  llvm/lib/IR/DebugInfoMetadata.cpp
  llvm/lib/IR/LLVMContextImpl.h
  llvm/test/Bitcode/attr-btf_tag-dicomposite.ll

Index: llvm/test/Bitcode/attr-btf_tag-dicomposite.ll
===
--- /dev/null
+++ llvm/test/Bitcode/attr-btf_tag-dicomposite.ll
@@ -0,0 +1,36 @@
+; REQUIRES: x86-registered-target
+; RUN: llvm-as < %s | llvm-dis | FileCheck %s
+
+%struct.t = type { i32 }
+
+@g = dso_local global %struct.t zeroinitializer, align 4, !dbg !0
+
+!llvm.dbg.cu = !{!2}
+!llvm.module.flags = !{!13, !14, !15, !16, !17}
+!llvm.ident = !{!18}
+
+!0 = !DIGlobalVariableExpression(var: !1, expr: !DIExpression())
+!1 = distinct !DIGlobalVariable(name: "g", scope: !2, file: !3, line: 2, type: !6, isLocal: false, isDefinition: true)
+!2 = distinct !DICompileUnit(language: DW_LANG_C99, file: !3, producer: "clang version 13.0.0 (https://github.com/llvm/llvm-project.git a20bed0ba269a4f9b67e58093c50af9ef0730fd1)", isOptimized: false, runtimeVersion: 0, emissionKind: FullDebug, enums: !4, globals: !5, splitDebugInlining: false, nameTableKind: None)
+!3 = !DIFile(filename: "struct.c", directory: "/home/yhs/work/tests/llvm/btf_tag")
+!4 = !{}
+!5 = !{!0}
+!6 = distinct !DICompositeType(tag: DW_TAG_structure_type, name: "t", file: !3, line: 1, size: 32, elements: !7, annotations: !10)
+!7 = !{!8}
+!8 = !DIDerivedType(tag: DW_TAG_member, name: "a", scope: !6, file: !3, line: 1, baseType: !9, size: 32)
+!9 = !DIBasicType(name: "int", size: 32, encoding: DW_ATE_signed)
+!10 = !{!11, !12}
+!11 = !{!"btf_tag", !"a"}
+!12 = !{!"btf_tag", !"b"}
+
+; CHECK:distinct !DICompositeType(tag: DW_TAG_structure_type, name: "t"
+; CHECK-SAME:   annotations: ![[ANNOT:[0-9]+]]
+; CHECK:![[ANNOT]] = !{![[TAG1:[0-9]+]], ![[TAG2:[0-9]+]]}
+; CHECK:![[TAG1]] = !{!"btf_tag", !"a"}
+; CHECK:![[TAG2]] = !{!"btf_tag", !"b"}
+!13 = !{i32 7, !"Dwarf Version", i32 4}
+!14 = !{i32 2, !"Debug Info Version", i32 3}
+!15 = !{i32 1, !"wchar_size", i32 4}
+!16 = !{i32 7, !"uwtable", i32 1}
+!17 = !{i32 7, !"frame-pointer", i32 2}
+!18 = !{!"clang version 13.0.0 (https://github.com/llvm/llvm-project.git a20bed0ba269a4f9b67e58093c50af9ef0730fd1)"}
Index: llvm/lib/IR/LLVMContextImpl.h
===
--- llvm/lib/IR/LLVMContextImpl.h
+++ llvm/lib/IR/LLVMContextImpl.h
@@ -569,6 +569,7 @@
   Metadata *Associated;
   Metadata *Allocated;
   Metadata *Rank;
+  Metadata *Annotations;
 
   MDNodeKeyImpl(unsigned Tag, MDString *Name, Metadata *File, unsigned Line,
 Metadata *Scope, Metadata *BaseType, uint64_t SizeInBits,
@@ -577,14 +578,15 @@
 Metadata *VTableHolder, Metadata *TemplateParams,
 MDString *Identifier, Metadata *Discriminator,
 Metadata *DataLocation, Metadata *Associated,
-Metadata *Allocated, Metadata *Rank)
+Metadata *Allocated, Metadata *Rank, Metadata *Annotations)
   : Tag(Tag), Name(Name), File(File), Line(Line), Scope(Scope),
 BaseType(BaseType), SizeInBits(SizeInBits), OffsetInBits(OffsetInBits),
 AlignInBits(AlignInBits), Flags(Flags), Elements(Elements),
 RuntimeLang(RuntimeLang), VTableHolder(VTableHolder),
 TemplateParams(TemplateParams), Identifier(Identifier),
 Discriminator(Discriminator), DataLocation(DataLocation),
-Associated(Associated), Allocated(Allocated), Rank(Rank) {}
+Associated(Associated), Allocated(Allocated), Rank(Rank),
+Annotations(Annotations) {}
   MDNodeKeyImpl(const DICompositeType *N)
   : Tag(N->getTag()), Name(N->getRawName()), File(N->getRawFile()),
 Line(N->getLine()), Scope(N->getRawScope()),
@@ -597,7 +599,7 @@
 Discriminator(N->getRawDiscriminator()),
 DataLocation(N->getRawDataLocation()),
 Associated(N->getRawAssociated()), Allocated(N->getRawAllocated()),
-Rank(N->getRawRank()) {}
+Rank(N->getRawRank()), Annotations(N->getRawAnnotations()) {}
 
   bool isKeyOf(const DICompositeType *RHS) const {
 return Tag == RHS->getTag() && Name == RHS->getRawName() &&
@@ -614,7 +616,8 @@
Discriminator == RHS->getRawDiscriminator() &&
DataLocation == RHS->getRawDataLocation() &&
Associated == RHS->getRawAssociated() &&
-   Allocated == RHS->getRawAllocated() && Rank == 

[PATCH] D107690: [Modules] Do not remove failed modules after the control block phase

2021-08-12 Thread Ben Barham via Phabricator via cfe-commits
bnbarham updated this revision to Diff 366154.
bnbarham added a comment.

Forgot to add the braces back in for the case statements


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D107690/new/

https://reviews.llvm.org/D107690

Files:
  clang/lib/Serialization/ASTReader.cpp
  clang/test/VFS/Inputs/UsesFoo.framework/Headers/UsesFoo.h
  clang/test/VFS/Inputs/UsesFoo.framework/Modules/module.modulemap
  clang/test/VFS/module-header-mismatches.m
  clang/test/VFS/umbrella-mismatch.m

Index: clang/test/VFS/umbrella-mismatch.m
===
--- clang/test/VFS/umbrella-mismatch.m
+++ /dev/null
@@ -1,7 +0,0 @@
-// RUN: rm -rf %t
-// RUN: sed -e "s;INPUT_DIR;%/S/Inputs;g" -e "s;OUT_DIR;%/S/Inputs;g" %S/Inputs/vfsoverlay.yaml > %t.yaml
-
-// RUN: %clang_cc1 -Werror -fmodules -fimplicit-module-maps -fmodules-cache-path=%t -ivfsoverlay %t.yaml -F %S/Inputs -fsyntax-only %s -Wno-atimport-in-framework-header -verify
-// RUN: %clang_cc1 -Werror -fmodules -fimplicit-module-maps -fmodules-cache-path=%t -F %S/Inputs -fsyntax-only %s -Wno-atimport-in-framework-header -verify
-// expected-no-diagnostics
-@import UsesFoo;
Index: clang/test/VFS/module-header-mismatches.m
===
--- /dev/null
+++ clang/test/VFS/module-header-mismatches.m
@@ -0,0 +1,86 @@
+// RUN: rm -rf %t
+// RUN: split-file %s %t
+// RUN: sed -e "s;TEST_DIR;%/t;g" %t/sed-overlay.yaml > %t/overlay.yaml
+
+// These tests first build with an overlay such that the header is resolved
+// to %t/other/Mismatch.h. They then build again with the header resolved
+// to the one in their directory.
+//
+// This should cause a rebuild if the contents is different (and thus multiple
+// PCMs), but this currently isn't the case. We should at least not error,
+// since this does happen in real projects (with a different copy of the same
+// file).
+
+// RUN: %clang_cc1 -Werror -fmodules -fimplicit-module-maps -fmodules-cache-path=%t/hf-mcp -ivfsoverlay %t/overlay.yaml -F %t/header-frameworks -fsyntax-only -verify %t/use.m
+// RUN: %clang_cc1 -Werror -fmodules -fimplicit-module-maps -fmodules-cache-path=%t/hf-mcp -F %t/header-frameworks -fsyntax-only -verify %t/use.m
+// RUN: find %t/hf-mcp -name "Mismatch-*.pcm" | count 1
+
+// RUN: %clang_cc1 -Werror -fmodules -fimplicit-module-maps -fmodules-cache-path=%t/df-mcp -ivfsoverlay %t/overlay.yaml -F %t/dir-frameworks -fsyntax-only -verify %t/use.m
+// RUN: %clang_cc1 -Werror -fmodules -fimplicit-module-maps -fmodules-cache-path=%t/hf-mcp -F %t/dir-frameworks -fsyntax-only -verify %t/use.m
+// RUN: find %t/df-mcp -name "Mismatch-*.pcm" | count 1
+
+// RUN: %clang_cc1 -Werror -fmodules -fimplicit-module-maps -fmodules-cache-path=%t/nf-mcp -ivfsoverlay %t/overlay.yaml -F %t/norm-frameworks -fsyntax-only -verify %t/use.m
+// RUN: %clang_cc1 -Werror -fmodules -fimplicit-module-maps -fmodules-cache-path=%t/nf-mcp -F %t/norm-frameworks -fsyntax-only -verify %t/use.m
+// RUN: find %t/nf-mcp -name "Mismatch-*.pcm" | count 1
+
+// RUN: %clang_cc1 -Werror -fmodules -fimplicit-module-maps -fmodules-cache-path=%t/m-mcp -ivfsoverlay %t/overlay.yaml -I %t/mod -fsyntax-only -verify %t/use.m
+// RUN: %clang_cc1 -Werror -fmodules -fimplicit-module-maps -fmodules-cache-path=%t/m-mcp -I %t/mod -fsyntax-only -verify %t/use.m
+// RUN: find %t/m-mcp -name "Mismatch-*.pcm" | count 1
+
+//--- use.m
+// expected-no-diagnostics
+@import Mismatch;
+
+//--- header-frameworks/Mismatch.framework/Modules/module.modulemap
+framework module Mismatch {
+  umbrella header "Mismatch.h"
+}
+//--- header-frameworks/Mismatch.framework/Headers/Mismatch.h
+
+//--- dir-frameworks/Mismatch.framework/Modules/module.modulemap
+framework module Mismatch {
+  umbrella "someheaders"
+}
+//--- dir-frameworks/Mismatch.framework/someheaders/Mismatch.h
+
+//--- norm-frameworks/Mismatch.framework/Modules/module.modulemap
+framework module Mismatch {
+  header "Mismatch.h"
+}
+//--- norm-frameworks/Mismatch.framework/Headers/Mismatch.h
+
+//--- mod/module.modulemap
+module Mismatch {
+  umbrella header "Mismatch.h"
+}
+//--- mod/Mismatch.h
+
+//--- other/Mismatch.h
+
+//--- sed-overlay.yaml
+{
+  'version': 0,
+  'roots': [
+{ 'name': 'TEST_DIR', 'type': 'directory',
+  'contents': [
+{ 'name': 'header-frameworks/Mismatch.framework/Headers/Mismatch.h',
+  'type': 'file',
+  'external-contents': 'TEST_DIR/other/Mismatch.h'
+},
+{ 'name': 'dir-frameworks/Mismatch.framework/someheaders',
+  'type': 'directory',
+  'external-contents': 'TEST_DIR/others'
+},
+{ 'name': 'norm-frameworks/Mismatch.framework/Headers/Mismatch.h',
+  'type': 'file',
+  'external-contents': 'TEST_DIR/other/Mismatch.h'
+},
+{ 'name': 'mod/Mismatch.h',
+  'type': 'file',
+  'external-contents': 'TEST_DIR/other/Mismatch.h'
+

[PATCH] D107921: [Modules] Fix bug where header resolution in modules doesn't work when compiling with relative paths.

2021-08-12 Thread Amy Huang via Phabricator via cfe-commits
akhuang updated this revision to Diff 366153.
akhuang added a comment.

add case for include_nexts; I don't entirely understand this part of the code 
so not sure if it's what we want, but it seems to make building with 
-no-canonical-prefixes happier


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D107921/new/

https://reviews.llvm.org/D107921

Files:
  clang/lib/Lex/HeaderSearch.cpp


Index: clang/lib/Lex/HeaderSearch.cpp
===
--- clang/lib/Lex/HeaderSearch.cpp
+++ clang/lib/Lex/HeaderSearch.cpp
@@ -819,9 +819,24 @@
   bool IncluderIsSystemHeader =
   Includer ? getFileInfo(Includer).DirInfo != SrcMgr::C_User :
   BuildSystemModule;
-  if (Optional FE = getFileAndSuggestModule(
-  TmpDir, IncludeLoc, IncluderAndDir.second, 
IncluderIsSystemHeader,
-  RequestingModule, SuggestedModule)) {
+
+  Optional FE = getFileAndSuggestModule(
+  TmpDir, IncludeLoc, IncluderAndDir.second, IncluderIsSystemHeader,
+  RequestingModule, SuggestedModule);
+
+  // If this is a system header, we should also search from the current
+  // working directory and not the directory of the module map.
+  if (!FE && IncluderIsSystemHeader) {
+// If this was an #include_next "/file", fail.
+if (!FromDir)
+  return None;
+
+FE = getFileAndSuggestModule(
+Filename, IncludeLoc, IncluderAndDir.second, 
IncluderIsSystemHeader,
+RequestingModule, SuggestedModule);
+  }
+
+  if (FE) {
 if (!Includer) {
   assert(First && "only first includer can have no file");
   return FE;


Index: clang/lib/Lex/HeaderSearch.cpp
===
--- clang/lib/Lex/HeaderSearch.cpp
+++ clang/lib/Lex/HeaderSearch.cpp
@@ -819,9 +819,24 @@
   bool IncluderIsSystemHeader =
   Includer ? getFileInfo(Includer).DirInfo != SrcMgr::C_User :
   BuildSystemModule;
-  if (Optional FE = getFileAndSuggestModule(
-  TmpDir, IncludeLoc, IncluderAndDir.second, IncluderIsSystemHeader,
-  RequestingModule, SuggestedModule)) {
+
+  Optional FE = getFileAndSuggestModule(
+  TmpDir, IncludeLoc, IncluderAndDir.second, IncluderIsSystemHeader,
+  RequestingModule, SuggestedModule);
+
+  // If this is a system header, we should also search from the current
+  // working directory and not the directory of the module map.
+  if (!FE && IncluderIsSystemHeader) {
+// If this was an #include_next "/file", fail.
+if (!FromDir)
+  return None;
+
+FE = getFileAndSuggestModule(
+Filename, IncludeLoc, IncluderAndDir.second, IncluderIsSystemHeader,
+RequestingModule, SuggestedModule);
+  }
+
+  if (FE) {
 if (!Includer) {
   assert(First && "only first includer can have no file");
   return FE;
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D107690: [Modules] Do not remove failed modules after the control block phase

2021-08-12 Thread Volodymyr Sapsai via Phabricator via cfe-commits
vsapsai accepted this revision.
vsapsai added a comment.
This revision is now accepted and ready to land.

Looks good to me. The only nitpicky thing is I don't remember if the code style 
requires braces around multi-line case blocks or not.


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D107690/new/

https://reviews.llvm.org/D107690

___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D107690: [Modules] Do not remove failed modules after the control block phase

2021-08-12 Thread Ben Barham via Phabricator via cfe-commits
bnbarham updated this revision to Diff 366152.
bnbarham marked an inline comment as done.
bnbarham edited the summary of this revision.
bnbarham added a comment.

Changed to keep setting the umbrella header/directory with a FIXME that it 
currently doesn't work for framework modules.


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D107690/new/

https://reviews.llvm.org/D107690

Files:
  clang/lib/Serialization/ASTReader.cpp
  clang/test/VFS/Inputs/UsesFoo.framework/Headers/UsesFoo.h
  clang/test/VFS/Inputs/UsesFoo.framework/Modules/module.modulemap
  clang/test/VFS/module-header-mismatches.m
  clang/test/VFS/umbrella-mismatch.m

Index: clang/test/VFS/umbrella-mismatch.m
===
--- clang/test/VFS/umbrella-mismatch.m
+++ /dev/null
@@ -1,7 +0,0 @@
-// RUN: rm -rf %t
-// RUN: sed -e "s;INPUT_DIR;%/S/Inputs;g" -e "s;OUT_DIR;%/S/Inputs;g" %S/Inputs/vfsoverlay.yaml > %t.yaml
-
-// RUN: %clang_cc1 -Werror -fmodules -fimplicit-module-maps -fmodules-cache-path=%t -ivfsoverlay %t.yaml -F %S/Inputs -fsyntax-only %s -Wno-atimport-in-framework-header -verify
-// RUN: %clang_cc1 -Werror -fmodules -fimplicit-module-maps -fmodules-cache-path=%t -F %S/Inputs -fsyntax-only %s -Wno-atimport-in-framework-header -verify
-// expected-no-diagnostics
-@import UsesFoo;
Index: clang/test/VFS/module-header-mismatches.m
===
--- /dev/null
+++ clang/test/VFS/module-header-mismatches.m
@@ -0,0 +1,86 @@
+// RUN: rm -rf %t
+// RUN: split-file %s %t
+// RUN: sed -e "s;TEST_DIR;%/t;g" %t/sed-overlay.yaml > %t/overlay.yaml
+
+// These tests first build with an overlay such that the header is resolved
+// to %t/other/Mismatch.h. They then build again with the header resolved
+// to the one in their directory.
+//
+// This should cause a rebuild if the contents is different (and thus multiple
+// PCMs), but this currently isn't the case. We should at least not error,
+// since this does happen in real projects (with a different copy of the same
+// file).
+
+// RUN: %clang_cc1 -Werror -fmodules -fimplicit-module-maps -fmodules-cache-path=%t/hf-mcp -ivfsoverlay %t/overlay.yaml -F %t/header-frameworks -fsyntax-only -verify %t/use.m
+// RUN: %clang_cc1 -Werror -fmodules -fimplicit-module-maps -fmodules-cache-path=%t/hf-mcp -F %t/header-frameworks -fsyntax-only -verify %t/use.m
+// RUN: find %t/hf-mcp -name "Mismatch-*.pcm" | count 1
+
+// RUN: %clang_cc1 -Werror -fmodules -fimplicit-module-maps -fmodules-cache-path=%t/df-mcp -ivfsoverlay %t/overlay.yaml -F %t/dir-frameworks -fsyntax-only -verify %t/use.m
+// RUN: %clang_cc1 -Werror -fmodules -fimplicit-module-maps -fmodules-cache-path=%t/hf-mcp -F %t/dir-frameworks -fsyntax-only -verify %t/use.m
+// RUN: find %t/df-mcp -name "Mismatch-*.pcm" | count 1
+
+// RUN: %clang_cc1 -Werror -fmodules -fimplicit-module-maps -fmodules-cache-path=%t/nf-mcp -ivfsoverlay %t/overlay.yaml -F %t/norm-frameworks -fsyntax-only -verify %t/use.m
+// RUN: %clang_cc1 -Werror -fmodules -fimplicit-module-maps -fmodules-cache-path=%t/nf-mcp -F %t/norm-frameworks -fsyntax-only -verify %t/use.m
+// RUN: find %t/nf-mcp -name "Mismatch-*.pcm" | count 1
+
+// RUN: %clang_cc1 -Werror -fmodules -fimplicit-module-maps -fmodules-cache-path=%t/m-mcp -ivfsoverlay %t/overlay.yaml -I %t/mod -fsyntax-only -verify %t/use.m
+// RUN: %clang_cc1 -Werror -fmodules -fimplicit-module-maps -fmodules-cache-path=%t/m-mcp -I %t/mod -fsyntax-only -verify %t/use.m
+// RUN: find %t/m-mcp -name "Mismatch-*.pcm" | count 1
+
+//--- use.m
+// expected-no-diagnostics
+@import Mismatch;
+
+//--- header-frameworks/Mismatch.framework/Modules/module.modulemap
+framework module Mismatch {
+  umbrella header "Mismatch.h"
+}
+//--- header-frameworks/Mismatch.framework/Headers/Mismatch.h
+
+//--- dir-frameworks/Mismatch.framework/Modules/module.modulemap
+framework module Mismatch {
+  umbrella "someheaders"
+}
+//--- dir-frameworks/Mismatch.framework/someheaders/Mismatch.h
+
+//--- norm-frameworks/Mismatch.framework/Modules/module.modulemap
+framework module Mismatch {
+  header "Mismatch.h"
+}
+//--- norm-frameworks/Mismatch.framework/Headers/Mismatch.h
+
+//--- mod/module.modulemap
+module Mismatch {
+  umbrella header "Mismatch.h"
+}
+//--- mod/Mismatch.h
+
+//--- other/Mismatch.h
+
+//--- sed-overlay.yaml
+{
+  'version': 0,
+  'roots': [
+{ 'name': 'TEST_DIR', 'type': 'directory',
+  'contents': [
+{ 'name': 'header-frameworks/Mismatch.framework/Headers/Mismatch.h',
+  'type': 'file',
+  'external-contents': 'TEST_DIR/other/Mismatch.h'
+},
+{ 'name': 'dir-frameworks/Mismatch.framework/someheaders',
+  'type': 'directory',
+  'external-contents': 'TEST_DIR/others'
+},
+{ 'name': 'norm-frameworks/Mismatch.framework/Headers/Mismatch.h',
+  'type': 'file',
+  'external-contents': 

[PATCH] D106614: [Clang] add btf_tag attribute

2021-08-12 Thread Yonghong Song via Phabricator via cfe-commits
This revision was landed with ongoing or failed builds.
This revision was automatically updated to reflect the committed changes.
Closed by commit rG1b194ef1ab3b: [Clang] add btf_tag attribute (authored by 
yonghong-song).

Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D106614/new/

https://reviews.llvm.org/D106614

Files:
  clang/include/clang/Basic/Attr.td
  clang/include/clang/Basic/AttrDocs.td
  clang/include/clang/Sema/Sema.h
  clang/lib/Sema/SemaDecl.cpp
  clang/lib/Sema/SemaDeclAttr.cpp
  clang/test/Misc/pragma-attribute-supported-attributes-list.test
  clang/test/Sema/attr-btf_tag.c

Index: clang/test/Sema/attr-btf_tag.c
===
--- /dev/null
+++ clang/test/Sema/attr-btf_tag.c
@@ -0,0 +1,42 @@
+// RUN: %clang_cc1 -x c -triple x86_64-pc-linux-gnu -dwarf-version=4 -fsyntax-only -verify %s
+
+#define __tag1 __attribute__((btf_tag("tag1")))
+#define __tag2 __attribute__((btf_tag("tag2")))
+#define __tag3 __attribute__((btf_tag("tag3")))
+
+#define __tag_no_arg __attribute__((btf_tag()))
+#define __tag_2_arg __attribute__((btf_tag("tag1", "tag2")))
+#define __invalid __attribute__((btf_tag(1)))
+
+struct __tag1 __tag2 t1;
+struct t1 {
+  int a __tag1;
+} __tag3;
+
+struct __tag1 t2;
+struct __tag2 __tag3 t2 {
+  int a __tag1;
+};
+
+int g1 __tag1;
+int g2 __tag_no_arg; // expected-error {{'btf_tag' attribute takes one argument}}
+int g3 __tag_2_arg; // expected-error {{'btf_tag' attribute takes one argument}}
+int i1 __invalid; // expected-error {{'btf_tag' attribute requires a string}}
+
+enum e1 {
+  E1
+} __tag1; // expected-error {{'btf_tag' attribute only applies to variables, functions, structs, unions, classes, and non-static data members}}
+
+enum e2 {
+  E2
+} __tag_no_arg; // expected-error {{'btf_tag' attribute only applies to variables, functions, structs, unions, classes, and non-static data members}}
+
+enum e3 {
+  E3
+} __tag_2_arg; // expected-error {{'btf_tag' attribute only applies to variables, functions, structs, unions, classes, and non-static data members}}
+
+int __tag1 __tag2 foo(struct t1 *arg, struct t2 *arg2);
+int __tag2 __tag3 foo(struct t1 *arg, struct t2 *arg2);
+int __tag1 foo(struct t1 *arg __tag1, struct t2 *arg2) {
+  return arg->a + arg2->a;
+}
Index: clang/test/Misc/pragma-attribute-supported-attributes-list.test
===
--- clang/test/Misc/pragma-attribute-supported-attributes-list.test
+++ clang/test/Misc/pragma-attribute-supported-attributes-list.test
@@ -22,6 +22,7 @@
 // CHECK-NEXT: Assumption (SubjectMatchRule_function, SubjectMatchRule_objc_method)
 // CHECK-NEXT: Availability ((SubjectMatchRule_record, SubjectMatchRule_enum, SubjectMatchRule_enum_constant, SubjectMatchRule_field, SubjectMatchRule_function, SubjectMatchRule_namespace, SubjectMatchRule_objc_category, SubjectMatchRule_objc_implementation, SubjectMatchRule_objc_interface, SubjectMatchRule_objc_method, SubjectMatchRule_objc_property, SubjectMatchRule_objc_protocol, SubjectMatchRule_record, SubjectMatchRule_type_alias, SubjectMatchRule_variable))
 // CHECK-NEXT: BPFPreserveAccessIndex (SubjectMatchRule_record)
+// CHECK-NEXT: BTFTag (SubjectMatchRule_variable, SubjectMatchRule_function, SubjectMatchRule_record, SubjectMatchRule_field)
 // CHECK-NEXT: BuiltinAlias (SubjectMatchRule_function)
 // CHECK-NEXT: CFAuditedTransfer (SubjectMatchRule_function)
 // CHECK-NEXT: CFConsumed (SubjectMatchRule_variable_is_parameter)
Index: clang/lib/Sema/SemaDeclAttr.cpp
===
--- clang/lib/Sema/SemaDeclAttr.cpp
+++ clang/lib/Sema/SemaDeclAttr.cpp
@@ -6842,6 +6842,30 @@
   Rec->addAttr(::new (S.Context) BPFPreserveAccessIndexAttr(S.Context, AL));
 }
 
+static bool hasBTFTagAttr(Decl *D, StringRef Tag) {
+  for (const auto *I : D->specific_attrs()) {
+if (I->getBTFTag() == Tag)
+  return true;
+  }
+  return false;
+}
+
+static void handleBTFTagAttr(Sema , Decl *D, const ParsedAttr ) {
+  StringRef Str;
+  if (!S.checkStringLiteralArgumentAttr(AL, 0, Str))
+return;
+  if (hasBTFTagAttr(D, Str))
+return;
+
+  D->addAttr(::new (S.Context) BTFTagAttr(S.Context, AL, Str));
+}
+
+BTFTagAttr *Sema::mergeBTFTagAttr(Decl *D, const BTFTagAttr ) {
+  if (hasBTFTagAttr(D, AL.getBTFTag()))
+return nullptr;
+  return ::new (Context) BTFTagAttr(Context, AL, AL.getBTFTag());
+}
+
 static void handleWebAssemblyExportNameAttr(Sema , Decl *D, const ParsedAttr ) {
   if (!isFunctionOrMethod(D)) {
 S.Diag(D->getLocation(), diag::warn_attribute_wrong_decl_type)
@@ -7879,6 +7903,9 @@
   case ParsedAttr::AT_BPFPreserveAccessIndex:
 handleBPFPreserveAccessIndexAttr(S, D, AL);
 break;
+  case ParsedAttr::AT_BTFTag:
+handleBTFTagAttr(S, D, AL);
+break;
   case ParsedAttr::AT_WebAssemblyExportName:
 handleWebAssemblyExportNameAttr(S, D, AL);
 break;
Index: 

[clang] 1b194ef - [Clang] add btf_tag attribute

2021-08-12 Thread Yonghong Song via cfe-commits

Author: Yonghong Song
Date: 2021-08-12T16:34:22-07:00
New Revision: 1b194ef1ab3b856afb8458fa9c58408360d292cb

URL: 
https://github.com/llvm/llvm-project/commit/1b194ef1ab3b856afb8458fa9c58408360d292cb
DIFF: 
https://github.com/llvm/llvm-project/commit/1b194ef1ab3b856afb8458fa9c58408360d292cb.diff

LOG: [Clang] add btf_tag attribute

A new attribute btf_tag is added. The syntax looks like
  __attribute__((btf_tag()))

Users may tag a particular structure/member/function/func_parameter/variable
declaration with an arbitrary string and the intention is
that this string is passed to dwarf so it is available for
post-compilation analysis. The string will be also passed
to .BTF section if the target is BPF. For each permitted
declaration, multiple btf_tag's are allowed.
For detailed use cases, please see
  https://lists.llvm.org/pipermail/llvm-dev/2021-June/151009.html

In case that there exist redeclarations, the btf_tag attributes
will be accumulated along with different declarations, and the
last declaration will contain all attributes.

Differential Revision: https://reviews.llvm.org/D106614

Added: 
clang/test/Sema/attr-btf_tag.c

Modified: 
clang/include/clang/Basic/Attr.td
clang/include/clang/Basic/AttrDocs.td
clang/include/clang/Sema/Sema.h
clang/lib/Sema/SemaDecl.cpp
clang/lib/Sema/SemaDeclAttr.cpp
clang/test/Misc/pragma-attribute-supported-attributes-list.test

Removed: 




diff  --git a/clang/include/clang/Basic/Attr.td 
b/clang/include/clang/Basic/Attr.td
index 12d09181a2ea8..13d8c15001c92 100644
--- a/clang/include/clang/Basic/Attr.td
+++ b/clang/include/clang/Basic/Attr.td
@@ -1835,6 +1835,14 @@ def BPFPreserveAccessIndex : InheritableAttr,
   let LangOpts = [COnly];
 }
 
+def BTFTag : InheritableAttr {
+  let Spellings = [Clang<"btf_tag">];
+  let Args = [StringArgument<"BTFTag">];
+  let Subjects = SubjectList<[Var, Function, Record, Field], ErrorDiag>;
+  let Documentation = [BTFTagDocs];
+  let LangOpts = [COnly];
+}
+
 def WebAssemblyExportName : InheritableAttr,
 TargetSpecificAttr {
   let Spellings = [Clang<"export_name">];

diff  --git a/clang/include/clang/Basic/AttrDocs.td 
b/clang/include/clang/Basic/AttrDocs.td
index c265a877e3b1a..a1206347ae454 100644
--- a/clang/include/clang/Basic/AttrDocs.td
+++ b/clang/include/clang/Basic/AttrDocs.td
@@ -2011,6 +2011,16 @@ preserving struct or union member access debuginfo 
indices of this
 struct or union, similar to clang ``__builtin_preserve_access_index()``.
   }];
 }
+def BTFTagDocs : Documentation {
+  let Category = DocCatFunction;
+  let Content = [{
+Clang supports the ``__attribute__((btf_tag("ARGUMENT")))`` attribute for all
+targets. This attribute may be attached to a struct/union, struct/union field,
+function, function parameter or variable declaration. If -g is specified,
+the ``ARGUMENT`` info will be preserved in IR and be emitted to dwarf.
+For BPF targets, the ``ARGUMENT`` info will be emitted to .BTF ELF section too.
+  }];
+}
 
 def MipsInterruptDocs : Documentation {
   let Category = DocCatFunction;

diff  --git a/clang/include/clang/Sema/Sema.h b/clang/include/clang/Sema/Sema.h
index bcd05a3e027c8..e38f50733bebe 100644
--- a/clang/include/clang/Sema/Sema.h
+++ b/clang/include/clang/Sema/Sema.h
@@ -3363,6 +3363,7 @@ class Sema final {
   EnforceTCBAttr *mergeEnforceTCBAttr(Decl *D, const EnforceTCBAttr );
   EnforceTCBLeafAttr *mergeEnforceTCBLeafAttr(Decl *D,
   const EnforceTCBLeafAttr );
+  BTFTagAttr *mergeBTFTagAttr(Decl *D, const BTFTagAttr );
 
   void mergeDeclAttributes(NamedDecl *New, Decl *Old,
AvailabilityMergeKind AMK = AMK_Redeclaration);

diff  --git a/clang/lib/Sema/SemaDecl.cpp b/clang/lib/Sema/SemaDecl.cpp
index eba5141c24c93..2f7cbdb79c0a5 100644
--- a/clang/lib/Sema/SemaDecl.cpp
+++ b/clang/lib/Sema/SemaDecl.cpp
@@ -2674,6 +2674,8 @@ static bool mergeDeclAttribute(Sema , NamedDecl *D,
 NewAttr = S.mergeEnforceTCBAttr(D, *TCBA);
   else if (const auto *TCBLA = dyn_cast(Attr))
 NewAttr = S.mergeEnforceTCBLeafAttr(D, *TCBLA);
+  else if (const auto *BTFA = dyn_cast(Attr))
+NewAttr = S.mergeBTFTagAttr(D, *BTFA);
   else if (Attr->shouldInheritEvenIfAlreadyPresent() || !DeclHasAttr(D, Attr))
 NewAttr = cast(Attr->clone(S.Context));
 

diff  --git a/clang/lib/Sema/SemaDeclAttr.cpp b/clang/lib/Sema/SemaDeclAttr.cpp
index 3b3e4a414c78c..30132a298b771 100644
--- a/clang/lib/Sema/SemaDeclAttr.cpp
+++ b/clang/lib/Sema/SemaDeclAttr.cpp
@@ -6842,6 +6842,30 @@ static void handleBPFPreserveAccessIndexAttr(Sema , 
Decl *D,
   Rec->addAttr(::new (S.Context) BPFPreserveAccessIndexAttr(S.Context, AL));
 }
 
+static bool hasBTFTagAttr(Decl *D, StringRef Tag) {
+  for (const auto *I : D->specific_attrs()) {
+if (I->getBTFTag() == Tag)
+  return true;
+  }
+  return false;
+}
+
+static void 

[PATCH] D108003: [Clang] Extend -Wbool-operation to warn about bitwise and of bools with side effects

2021-08-12 Thread Dávid Bolvanský via Phabricator via cfe-commits
xbolva00 updated this revision to Diff 366143.
xbolva00 marked an inline comment as not done.
xbolva00 added a comment.

New test with volatile int.


CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D108003/new/

https://reviews.llvm.org/D108003

Files:
  clang/include/clang/Basic/DiagnosticGroups.td
  clang/include/clang/Basic/DiagnosticSemaKinds.td
  clang/lib/Sema/SemaChecking.cpp
  clang/test/Sema/warn-bitwise-and-bool.c

Index: clang/test/Sema/warn-bitwise-and-bool.c
===
--- /dev/null
+++ clang/test/Sema/warn-bitwise-and-bool.c
@@ -0,0 +1,52 @@
+// RUN: %clang_cc1 -x c -fsyntax-only -verify -Wbool-operation %s
+// RUN: %clang_cc1 -x c -fsyntax-only -verify %s
+// RUN: %clang_cc1 -x c -fsyntax-only -fdiagnostics-parseable-fixits %s 2>&1 | FileCheck %s
+// RUN: %clang_cc1 -x c++ -fsyntax-only -verify -Wbool-operation %s
+// RUN: %clang_cc1 -x c++ -fsyntax-only -verify %s
+// RUN: %clang_cc1 -x c++ -fsyntax-only -fdiagnostics-parseable-fixits %s 2>&1 | FileCheck %s
+
+#ifdef __cplusplus
+typedef bool boolean;
+#else
+typedef _Bool boolean;
+#endif
+
+boolean foo(void);
+boolean bar(void);
+boolean baz(void) __attribute__((const));
+void sink(boolean);
+
+#define FOO foo()
+
+void test(boolean a, boolean b, int *p, volatile int *q, int i) {
+  b = a & b;
+  b = foo() & a;
+  b = (p != 0) & (*p == 42);
+  b = (q != 0) & (*q == 42); // expected-warning {{bitwise and of boolean expressions; did you mean logical and?}}
+  b = a & foo();  // expected-warning {{bitwise and of boolean expressions; did you mean logical and?}}
+  // CHECK: fix-it:"{{.*}}":{[[@LINE-1]]:9-[[@LINE-1]]:10}:"&&"
+  b = foo() & bar();  // expected-warning {{bitwise and of boolean expressions; did you mean logical and?}}
+  // CHECK: fix-it:"{{.*}}":{[[@LINE-1]]:13-[[@LINE-1]]:14}:"&&"
+  b = foo() & !bar(); // expected-warning {{bitwise and of boolean expressions; did you mean logical and?}}
+  // CHECK: fix-it:"{{.*}}":{[[@LINE-1]]:13-[[@LINE-1]]:14}:"&&"
+  b = a & baz();
+  b = a & FOO;// expected-warning {{bitwise and of boolean expressions; did you mean logical and?}}
+  // CHECK: fix-it:"{{.*}}":{[[@LINE-1]]:9-[[@LINE-1]]:10}:"&&"
+  b = !b & foo(); // expected-warning {{bitwise and of boolean expressions; did you mean logical and?}}
+  // CHECK: fix-it:"{{.*}}":{[[@LINE-1]]:10-[[@LINE-1]]:11}:"&&"
+  b = bar() & (i > 4);
+  b = (i == 7) & foo(); // expected-warning {{bitwise and of boolean expressions; did you mean logical and?}}
+#ifdef __cplusplus
+  b = a bitand foo(); // expected-warning {{bitwise and of boolean expressions; did you mean logical and?}}
+#endif
+
+  if (foo() & bar()) // expected-warning {{bitwise and of boolean expressions; did you mean logical and?}}
+;
+
+  sink(a & b);
+  sink(a & foo()); // expected-warning {{bitwise and of boolean expressions; did you mean logical and?}}
+  sink(foo() & bar()); // expected-warning {{bitwise and of boolean expressions; did you mean logical and?}}
+
+  int n = i + 10;
+  b = (n & (n-1));
+}
Index: clang/lib/Sema/SemaChecking.cpp
===
--- clang/lib/Sema/SemaChecking.cpp
+++ clang/lib/Sema/SemaChecking.cpp
@@ -13073,6 +13073,15 @@
   << OrigE->getSourceRange() << T->isBooleanType()
   << FixItHint::CreateReplacement(UO->getBeginLoc(), "!");
 
+  if (const auto *BO = dyn_cast(SourceExpr))
+if (BO->getOpcode() == BO_And &&
+BO->getLHS()->isKnownToHaveBooleanValue() &&
+BO->getRHS()->isKnownToHaveBooleanValue() &&
+BO->getRHS()->HasSideEffects(S.Context))
+  S.Diag(BO->getBeginLoc(), diag::warn_bitwise_and_bool)
+  << OrigE->getSourceRange()
+  << FixItHint::CreateReplacement(BO->getOperatorLoc(), "&&");
+
   // For conditional operators, we analyze the arguments as if they
   // were being fed directly into the output.
   if (auto *CO = dyn_cast(SourceExpr)) {
Index: clang/include/clang/Basic/DiagnosticSemaKinds.td
===
--- clang/include/clang/Basic/DiagnosticSemaKinds.td
+++ clang/include/clang/Basic/DiagnosticSemaKinds.td
@@ -7424,7 +7424,10 @@
 def warn_bitwise_negation_bool : Warning<
   "bitwise negation of a boolean expression%select{;| always evaluates to 'true';}0 "
   "did you mean logical negation?">,
-  InGroup>;
+  InGroup;
+def warn_bitwise_and_bool : Warning<
+  "bitwise and of boolean expressions; did you mean logical and?">,
+  InGroup;
 def err_decrement_bool : Error<"cannot decrement expression of type bool">;
 def warn_increment_bool : Warning<
   "incrementing expression of type bool is deprecated and "
Index: clang/include/clang/Basic/DiagnosticGroups.td
===
--- clang/include/clang/Basic/DiagnosticGroups.td
+++ 

[PATCH] D108003: [Clang] Extend -Wbool-operation to warn about bitwise and of bools with side effects

2021-08-12 Thread Dávid Bolvanský via Phabricator via cfe-commits
xbolva00 marked an inline comment as not done.
xbolva00 added inline comments.



Comment at: clang/test/Sema/warn-bitwise-and-bool.c:21-22
+void test(boolean a, boolean b, int i) {
+  b = a & b;
+  b = a & foo();  // expected-warning {{bitwise and of boolean 
expressions; did you mean logical and?}}
+  // CHECK: 
fix-it:"{{.*}}":{[[@LINE-1]]:9-[[@LINE-1]]:10}:"&&"

Quuxplusone wrote:
> So the warning triggers only when the RHS has side-effects? I'd like tests for
> ```
> foo() & a;  // should not trigger, by that logic, because && wouldn't 
> short-circuit anything?
> (p != nullptr) & (*p == 42);  // should certainly trigger: deref is a side 
> effect, and of course obviously this is a bug
> ```
Yes, but oh.

This is weird, HasSideEffects is false for this case. Works fine for volatile 
int.

@rsmith?


CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D108003/new/

https://reviews.llvm.org/D108003

___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D95583: Frontend: Add -f{, no-}implicit-modules-uses-lock and -Rmodule-lock

2021-08-12 Thread Duncan P. N. Exon Smith via Phabricator via cfe-commits
This revision was landed with ongoing or failed builds.
This revision was automatically updated to reflect the committed changes.
Closed by commit rGb714f73defc8: Frontend: Add 
-f{,no-}implicit-modules-uses-lock and -Rmodule-lock (authored by dexonsmith).

Changed prior to commit:
  https://reviews.llvm.org/D95583?vs=319738=366142#toc

Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D95583/new/

https://reviews.llvm.org/D95583

Files:
  clang/include/clang/Basic/DiagnosticFrontendKinds.td
  clang/include/clang/Basic/DiagnosticGroups.td
  clang/include/clang/Driver/Options.td
  clang/include/clang/Frontend/FrontendOptions.h
  clang/lib/Frontend/CompilerInstance.cpp
  clang/test/Modules/implicit-modules-use-lock.m

Index: clang/test/Modules/implicit-modules-use-lock.m
===
--- /dev/null
+++ clang/test/Modules/implicit-modules-use-lock.m
@@ -0,0 +1,23 @@
+// Confirm -fimplicit-modules-use-lock and -fno-implicit-modules-use-lock control
+// whether building a module triggers -Rmodule-lock, indirectly checking whether
+// a lock manager is being used.
+//
+// RUN: rm -rf %t.cache
+// RUN: %clang_cc1 -fmodules -fimplicit-module-maps \
+// RUN:   -fimplicit-modules-use-lock -Rmodule-lock \
+// RUN:   -fmodules-cache-path=%t.cache -I%S/Inputs/system-out-of-date \
+// RUN:   -fsyntax-only %s -Wnon-modular-include-in-framework-module \
+// RUN:   -Werror=non-modular-include-in-framework-module 2>&1 \
+// RUN: | FileCheck %s -check-prefix=CHECK-LOCKS
+//
+// RUN: rm -rf %t.cache
+// RUN: %clang_cc1 -fmodules -fimplicit-module-maps \
+// RUN:   -fno-implicit-modules-use-lock -Rmodule-lock \
+// RUN:   -fmodules-cache-path=%t.cache -I%S/Inputs/system-out-of-date \
+// RUN:   -fsyntax-only %s -Wnon-modular-include-in-framework-module \
+// RUN:   -Werror=non-modular-include-in-framework-module 2>&1 \
+// RUN: | FileCheck %s -check-prefix=CHECK-NO-LOCKS -allow-empty
+
+// CHECK-NO-LOCKS-NOT: remark:
+// CHECK-LOCKS: remark: locking '{{.*}}.pcm' to build module 'X' [-Rmodule-lock]
+@import X;
Index: clang/lib/Frontend/CompilerInstance.cpp
===
--- clang/lib/Frontend/CompilerInstance.cpp
+++ clang/lib/Frontend/CompilerInstance.cpp
@@ -1331,6 +1331,9 @@
 SourceLocation ModuleNameLoc, Module *Module, StringRef ModuleFileName) {
   DiagnosticsEngine  = ImportingInstance.getDiagnostics();
 
+  Diags.Report(ModuleNameLoc, diag::remark_module_lock)
+  << ModuleFileName << Module->Name;
+
   // FIXME: have LockFileManager return an error_code so that we can
   // avoid the mkdir when the directory already exists.
   StringRef Dir = llvm::sys::path::parent_path(ModuleFileName);
@@ -1389,6 +1392,25 @@
   }
 }
 
+/// Compile a module in a separate compiler instance and read the AST,
+/// returning true if the module compiles without errors, potentially using a
+/// lock manager to avoid building the same module in multiple compiler
+/// instances.
+static bool compileModuleAndReadAST(CompilerInstance ,
+SourceLocation ImportLoc,
+SourceLocation ModuleNameLoc,
+Module *Module, StringRef ModuleFileName) {
+  return ImportingInstance.getInvocation()
+ .getFrontendOpts()
+ .BuildingImplicitModuleUsesLock
+ ? compileModuleAndReadASTBehindLock(ImportingInstance, ImportLoc,
+ ModuleNameLoc, Module,
+ ModuleFileName)
+ : compileModuleAndReadASTImpl(ImportingInstance, ImportLoc,
+   ModuleNameLoc, Module,
+   ModuleFileName);
+}
+
 /// Diagnose differences between the current definition of the given
 /// configuration macro and the definition provided on the command line.
 static void checkConfigMacro(Preprocessor , StringRef ConfigMacro,
@@ -1866,8 +1888,8 @@
   }
 
   // Try to compile and then read the AST.
-  if (!compileModuleAndReadASTBehindLock(*this, ImportLoc, ModuleNameLoc, M,
- ModuleFilename)) {
+  if (!compileModuleAndReadAST(*this, ImportLoc, ModuleNameLoc, M,
+   ModuleFilename)) {
 assert(getDiagnostics().hasErrorOccurred() &&
"undiagnosed error in compileModuleAndReadAST");
 if (getPreprocessorOpts().FailedModules)
Index: clang/include/clang/Frontend/FrontendOptions.h
===
--- clang/include/clang/Frontend/FrontendOptions.h
+++ clang/include/clang/Frontend/FrontendOptions.h
@@ -289,6 +289,9 @@
   /// Whether we are performing an implicit module build.
   unsigned BuildingImplicitModule : 1;
 
+  /// Whether to use a filesystem lock when building implicit modules.
+  

[clang] b714f73 - Frontend: Add -f{,no-}implicit-modules-uses-lock and -Rmodule-lock

2021-08-12 Thread Duncan P. N. Exon Smith via cfe-commits

Author: Duncan P. N. Exon Smith
Date: 2021-08-12T15:58:19-07:00
New Revision: b714f73defc8e0755c7c7cf043df1f1c21344839

URL: 
https://github.com/llvm/llvm-project/commit/b714f73defc8e0755c7c7cf043df1f1c21344839
DIFF: 
https://github.com/llvm/llvm-project/commit/b714f73defc8e0755c7c7cf043df1f1c21344839.diff

LOG: Frontend: Add -f{,no-}implicit-modules-uses-lock and -Rmodule-lock

Add -cc1 flags `-fmodules-uses-lock` and `-fno-modules-uses-lock` to
allow the lock manager to be turned off when building implicit modules.

Add `-Rmodule-lock` so that we can see when it's being used.

Differential Revision: https://reviews.llvm.org/D95583

Added: 
clang/test/Modules/implicit-modules-use-lock.m

Modified: 
clang/include/clang/Basic/DiagnosticFrontendKinds.td
clang/include/clang/Basic/DiagnosticGroups.td
clang/include/clang/Driver/Options.td
clang/include/clang/Frontend/FrontendOptions.h
clang/lib/Frontend/CompilerInstance.cpp

Removed: 




diff  --git a/clang/include/clang/Basic/DiagnosticFrontendKinds.td 
b/clang/include/clang/Basic/DiagnosticFrontendKinds.td
index 0f4ccec385506..4bc5097762186 100644
--- a/clang/include/clang/Basic/DiagnosticFrontendKinds.td
+++ b/clang/include/clang/Basic/DiagnosticFrontendKinds.td
@@ -229,6 +229,8 @@ def remark_module_build : Remark<"building module '%0' as 
'%1'">,
   InGroup;
 def remark_module_build_done : Remark<"finished building module '%0'">,
   InGroup;
+def remark_module_lock : Remark<"locking '%0' to build module '%1'">,
+  InGroup;
 def err_modules_embed_file_not_found :
   Error<"file '%0' specified by '-fmodules-embed-file=' not found">,
   DefaultFatal;

diff  --git a/clang/include/clang/Basic/DiagnosticGroups.td 
b/clang/include/clang/Basic/DiagnosticGroups.td
index 1555a9ee24650..4a67dffb2f7d4 100644
--- a/clang/include/clang/Basic/DiagnosticGroups.td
+++ b/clang/include/clang/Basic/DiagnosticGroups.td
@@ -465,6 +465,7 @@ def MismatchedParameterTypes : 
DiagGroup<"mismatched-parameter-types">;
 def MismatchedReturnTypes : DiagGroup<"mismatched-return-types">;
 def MismatchedTags : DiagGroup<"mismatched-tags">;
 def MissingFieldInitializers : DiagGroup<"missing-field-initializers">;
+def ModuleLock : DiagGroup<"module-lock">;
 def ModuleBuild : DiagGroup<"module-build">;
 def ModuleImport : DiagGroup<"module-import">;
 def ModuleConflict : DiagGroup<"module-conflict">;

diff  --git a/clang/include/clang/Driver/Options.td 
b/clang/include/clang/Driver/Options.td
index a91114f76ff07..5d43660ca7dec 100644
--- a/clang/include/clang/Driver/Options.td
+++ b/clang/include/clang/Driver/Options.td
@@ -5301,6 +5301,12 @@ def fmodules_embed_all_files : Joined<["-"], 
"fmodules-embed-all-files">,
   HelpText<"Embed the contents of all files read by this compilation into "
"the produced module file.">,
   MarshallingInfoFlag>;
+defm fimplicit_modules_use_lock : BoolOption<"f", "implicit-modules-use-lock",
+  FrontendOpts<"BuildingImplicitModuleUsesLock">, DefaultTrue,
+  NegFlag,
+  PosFlag>;
 // FIXME: We only need this in C++ modules / Modules TS if we might textually
 // enter a 
diff erent module (eg, when building a header unit).
 def fmodules_local_submodule_visibility :

diff  --git a/clang/include/clang/Frontend/FrontendOptions.h 
b/clang/include/clang/Frontend/FrontendOptions.h
index 15c905d712a37..41ea45ca0b103 100644
--- a/clang/include/clang/Frontend/FrontendOptions.h
+++ b/clang/include/clang/Frontend/FrontendOptions.h
@@ -289,6 +289,9 @@ class FrontendOptions {
   /// Whether we are performing an implicit module build.
   unsigned BuildingImplicitModule : 1;
 
+  /// Whether to use a filesystem lock when building implicit modules.
+  unsigned BuildingImplicitModuleUsesLock : 1;
+
   /// Whether we should embed all used files into the PCM file.
   unsigned ModulesEmbedAllFiles : 1;
 
@@ -461,9 +464,9 @@ class FrontendOptions {
 SkipFunctionBodies(false), UseGlobalModuleIndex(true),
 GenerateGlobalModuleIndex(true), ASTDumpDecls(false),
 ASTDumpLookups(false), BuildingImplicitModule(false),
-ModulesEmbedAllFiles(false), IncludeTimestamps(true),
-UseTemporary(true), AllowPCMWithCompilerErrors(false),
-TimeTraceGranularity(500) {}
+BuildingImplicitModuleUsesLock(true), ModulesEmbedAllFiles(false),
+IncludeTimestamps(true), UseTemporary(true),
+AllowPCMWithCompilerErrors(false), TimeTraceGranularity(500) {}
 
   /// getInputKindForExtension - Return the appropriate input kind for a file
   /// extension. For example, "c" would return Language::C.

diff  --git a/clang/lib/Frontend/CompilerInstance.cpp 
b/clang/lib/Frontend/CompilerInstance.cpp
index d90b292808f21..0f9bd70efc73e 100644
--- a/clang/lib/Frontend/CompilerInstance.cpp
+++ b/clang/lib/Frontend/CompilerInstance.cpp
@@ -1331,6 +1331,9 @@ static bool compileModuleAndReadASTBehindLock(
 SourceLocation 

[PATCH] D108003: [Clang] Extend -Wbool-operation to warn about bitwise and of bools with side effects

2021-08-12 Thread Dávid Bolvanský via Phabricator via cfe-commits
xbolva00 added inline comments.



Comment at: clang/include/clang/Basic/DiagnosticSemaKinds.td:7428-7430
+def warn_bitwise_and_bool : Warning<
+  "bitwise and of boolean expressions; did you mean logical and?">,
+  InGroup;

Quuxplusone wrote:
> I suggest that the name and wording of this diagnostic should match 
> `warn_logical_instead_of_bitwise`, currently `"use of logical '%0' with 
> constant operand"`. So:
> ```
> def warn_bitwise_instead_of_logical : Warning<
>   "use of bitwise '%0' with boolean operand">,
> ```
> This neatly sidesteps the problem of what to call the `&` operator: I was not 
> thrilled with the phrase `bitwise and of`, but have no problem with `use of 
> bitwise '&'`.
I see the point but then I will not be able to provide -Wbool-operation-and 
flag to enable/disable this warning.

For example I know that Google prefers a new flag for every new warning so they 
dont have to disable eg. -Wbool-operation, but just this new warning while 
there are working on fixes for new warnings.

@hans what do you think?




CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D108003/new/

https://reviews.llvm.org/D108003

___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D108003: [Clang] Extend -Wbool-operation to warn about bitwise and of bools with side effects

2021-08-12 Thread Marshall Clow via Phabricator via cfe-commits
mclow.lists added a comment.

I suggest you take all the techniques at 
http://graphics.stanford.edu/~seander/bithacks.html and make sure they don't 
cause a warning.


CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D108003/new/

https://reviews.llvm.org/D108003

___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D107850: [WIP][asan] Implemented custom calling convention similar used by HWASan for X86. The feature should be code complete. The tests are coming in a later revision.

2021-08-12 Thread Kirill Stoimenov via Phabricator via cfe-commits
kstoimenov updated this revision to Diff 366141.
kstoimenov added a comment.

Added code generation tests and fixed some bugs along the way.


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D107850/new/

https://reviews.llvm.org/D107850

Files:
  clang/test/CodeGen/asan-use-callbacks.cpp
  llvm/include/llvm/IR/Intrinsics.td
  llvm/include/llvm/Transforms/Instrumentation/AddressSanitizer.h
  llvm/lib/Target/X86/X86AsmPrinter.cpp
  llvm/lib/Target/X86/X86AsmPrinter.h
  llvm/lib/Target/X86/X86InstrCompiler.td
  llvm/lib/Target/X86/X86MCInstLower.cpp
  llvm/lib/Target/X86/X86RegisterInfo.td
  llvm/lib/Transforms/Instrumentation/AddressSanitizer.cpp
  llvm/test/CodeGen/X86/asan-check-memaccess-add.ll
  llvm/test/CodeGen/X86/asan-check-memaccess-or.ll

Index: llvm/test/CodeGen/X86/asan-check-memaccess-or.ll
===
--- /dev/null
+++ llvm/test/CodeGen/X86/asan-check-memaccess-or.ll
@@ -0,0 +1,223 @@
+; RUN: llc < %s | FileCheck %s
+
+target triple = "x86_64-unknown-linux-gnu"
+
+define void @load1(i8* nocapture readonly %x) {
+; CHECK:  callq   __asan_check_load1_rn[[RN1:.*]]
+; CHECK:  callq   __asan_check_store1_rn[[RN1]]
+; CHECK-NEXT: retq
+  call void @llvm.asan.check.memaccess(i8* %x, i64 2147450880, i32 608)
+  call void @llvm.asan.check.memaccess(i8* %x, i64 2147450880, i32 624)
+  ret void
+}
+
+define void @load2(i16* nocapture readonly %x) {
+; CHECK:  callq   __asan_check_load2_rn[[RN2:.*]]
+; CHECK:  callq   __asan_check_store2_rn[[RN2]]
+; CHECK-NEXT: retq
+  %1 = ptrtoint i16* %x to i64
+  %2 = bitcast i16* %x to i8*
+  call void @llvm.asan.check.memaccess(i8* %2, i64 2147450880, i32 609)
+  call void @llvm.asan.check.memaccess(i8* %2, i64 2147450880, i32 625)
+  ret void
+}
+
+define void @load4(i32* nocapture readonly %x) {
+; CHECK:  callq   __asan_check_load4_rn[[RN4:.*]]
+; CHECK:  callq   __asan_check_store4_rn[[RN4]]
+; CHECK-NEXT: retq
+  %1 = ptrtoint i32* %x to i64
+  %2 = bitcast i32* %x to i8*
+  call void @llvm.asan.check.memaccess(i8* %2, i64 2147450880, i32 610)
+  call void @llvm.asan.check.memaccess(i8* %2, i64 2147450880, i32 626)
+  ret void
+}
+define void @load8(i64* nocapture readonly %x) {
+; CHECK:  callq   __asan_check_load8_rn[[RN8:.*]]
+; CHECK:  callq   __asan_check_store8_rn[[RN8]]
+; CHECK-NEXT: retq
+  %1 = ptrtoint i64* %x to i64
+  %2 = bitcast i64* %x to i8*
+  call void @llvm.asan.check.memaccess(i8* %2, i64 2147450880, i32 611)
+  call void @llvm.asan.check.memaccess(i8* %2, i64 2147450880, i32 627)
+  ret void
+}
+
+define void @load16(i128* nocapture readonly %x) {
+; CHECK:  callq   __asan_check_load16_rn[[RN16:.*]]
+; CHECK:  callq   __asan_check_store16_rn[[RN16]]
+; CHECK-NEXT: retq
+  %1 = ptrtoint i128* %x to i64
+  %2 = bitcast i128* %x to i8*
+  call void @llvm.asan.check.memaccess(i8* %2, i64 2147450880, i32 612)
+  call void @llvm.asan.check.memaccess(i8* %2, i64 2147450880, i32 628)
+  ret void
+}
+
+; CHECK:  __asan_check_load1_rn[[RN1]]:
+; CHECK-NEXT: movq[[REG:.*]], %r8
+; CHECK-NEXT: shrq$3, %r8
+; CHECK-NEXT: orq $2147450880, %r8
+; CHECK-NEXT: movb(%r8), %r8b
+; CHECK-NEXT: testb   %r8b, %r8b
+; CHECK-NEXT: jne [[EXTRA:.*]]
+; CHECK-NEXT: [[RET:.*]]:
+; CHECK-NEXT: retq
+; CHECK-NEXT: [[EXTRA]]:
+; CHECK-NEXT: pushq   %rcx
+; CHECK-NEXT: movq[[REG]], %rcx
+; CHECK-NEXT: andl$7, %ecx
+; CHECK-NEXT: cmpl%r8d, %ecx
+; CHECK-NEXT: popq%rcx
+; CHECK-NEXT: jl  [[RET]]
+; CHECK-NEXT: movq[[REG:.*]], %rdi
+; CHECK-NEXT: jmp __asan_report_load1
+
+; CHECK:  __asan_check_load2_rn[[RN2]]:
+; CHECK-NEXT: movq[[REG:.*]], %r8
+; CHECK-NEXT: shrq$3, %r8
+; CHECK-NEXT: orq $2147450880, %r8
+; CHECK-NEXT: movb(%r8), %r8b
+; CHECK-NEXT: testb   %r8b, %r8b
+; CHECK-NEXT: jne [[EXTRA:.*]]
+; CHECK-NEXT: [[RET:.*]]:
+; CHECK-NEXT: retq
+; CHECK-NEXT: [[EXTRA]]:
+; CHECK-NEXT: pushq   %rcx
+; CHECK-NEXT: movq[[REG]], %rcx
+; CHECK-NEXT: andl$7, %ecx
+; CHECK-NEXT: addl$1, %ecx
+; CHECK-NEXT: cmpl%r8d, %ecx
+; CHECK-NEXT: popq%rcx
+; CHECK-NEXT: jl  [[RET]]
+; CHECK-NEXT: movq[[REG:.*]], %rdi
+; CHECK-NEXT: jmp __asan_report_load2
+
+; CHECK:  __asan_check_load4_rn[[RN4]]:
+; CHECK-NEXT: movq[[REG:.*]], %r8
+; CHECK-NEXT: shrq$3, %r8
+; CHECK-NEXT: orq $2147450880, %r8
+; CHECK-NEXT: movb(%r8), %r8b
+; CHECK-NEXT: testb   %r8b, %r8b
+; CHECK-NEXT: jne [[EXTRA:.*]]
+; CHECK-NEXT: 

[PATCH] D108003: [Clang] Extend -Wbool-operation to warn about bitwise and of bools with side effects

2021-08-12 Thread Dávid Bolvanský via Phabricator via cfe-commits
xbolva00 updated this revision to Diff 366139.
xbolva00 added a comment.

Added new tests.

Thanks for recommendations.


CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D108003/new/

https://reviews.llvm.org/D108003

Files:
  clang/include/clang/Basic/DiagnosticGroups.td
  clang/include/clang/Basic/DiagnosticSemaKinds.td
  clang/lib/Sema/SemaChecking.cpp
  clang/test/Sema/warn-bitwise-and-bool.c

Index: clang/test/Sema/warn-bitwise-and-bool.c
===
--- /dev/null
+++ clang/test/Sema/warn-bitwise-and-bool.c
@@ -0,0 +1,51 @@
+// RUN: %clang_cc1 -x c -fsyntax-only -verify -Wbool-operation %s
+// RUN: %clang_cc1 -x c -fsyntax-only -verify %s
+// RUN: %clang_cc1 -x c -fsyntax-only -fdiagnostics-parseable-fixits %s 2>&1 | FileCheck %s
+// RUN: %clang_cc1 -x c++ -fsyntax-only -verify -Wbool-operation %s
+// RUN: %clang_cc1 -x c++ -fsyntax-only -verify %s
+// RUN: %clang_cc1 -x c++ -fsyntax-only -fdiagnostics-parseable-fixits %s 2>&1 | FileCheck %s
+
+#ifdef __cplusplus
+typedef bool boolean;
+#else
+typedef _Bool boolean;
+#endif
+
+boolean foo(void);
+boolean bar(void);
+boolean baz(void) __attribute__((const));
+void sink(boolean);
+
+#define FOO foo()
+
+void test(boolean a, boolean b, int *p, int i) {
+  b = a & b;
+  b = foo() & a;
+  b = (p != 0) & (*p == 42);
+  b = a & foo();  // expected-warning {{bitwise and of boolean expressions; did you mean logical and?}}
+  // CHECK: fix-it:"{{.*}}":{[[@LINE-1]]:9-[[@LINE-1]]:10}:"&&"
+  b = foo() & bar();  // expected-warning {{bitwise and of boolean expressions; did you mean logical and?}}
+  // CHECK: fix-it:"{{.*}}":{[[@LINE-1]]:13-[[@LINE-1]]:14}:"&&"
+  b = foo() & !bar(); // expected-warning {{bitwise and of boolean expressions; did you mean logical and?}}
+  // CHECK: fix-it:"{{.*}}":{[[@LINE-1]]:13-[[@LINE-1]]:14}:"&&"
+  b = a & baz();
+  b = a & FOO;// expected-warning {{bitwise and of boolean expressions; did you mean logical and?}}
+  // CHECK: fix-it:"{{.*}}":{[[@LINE-1]]:9-[[@LINE-1]]:10}:"&&"
+  b = !b & foo(); // expected-warning {{bitwise and of boolean expressions; did you mean logical and?}}
+  // CHECK: fix-it:"{{.*}}":{[[@LINE-1]]:10-[[@LINE-1]]:11}:"&&"
+  b = bar() & (i > 4);
+  b = (i == 7) & foo(); // expected-warning {{bitwise and of boolean expressions; did you mean logical and?}}
+#ifdef __cplusplus
+  b = a bitand foo(); // expected-warning {{bitwise and of boolean expressions; did you mean logical and?}}
+#endif
+
+  if (foo() & bar()) // expected-warning {{bitwise and of boolean expressions; did you mean logical and?}}
+;
+
+  sink(a & b);
+  sink(a & foo()); // expected-warning {{bitwise and of boolean expressions; did you mean logical and?}}
+  sink(foo() & bar()); // expected-warning {{bitwise and of boolean expressions; did you mean logical and?}}
+
+  int n = i + 10;
+  b = (n & (n-1));
+}
Index: clang/lib/Sema/SemaChecking.cpp
===
--- clang/lib/Sema/SemaChecking.cpp
+++ clang/lib/Sema/SemaChecking.cpp
@@ -13073,6 +13073,15 @@
   << OrigE->getSourceRange() << T->isBooleanType()
   << FixItHint::CreateReplacement(UO->getBeginLoc(), "!");
 
+  if (const auto *BO = dyn_cast(SourceExpr))
+if (BO->getOpcode() == BO_And &&
+BO->getLHS()->isKnownToHaveBooleanValue() &&
+BO->getRHS()->isKnownToHaveBooleanValue() &&
+BO->getRHS()->HasSideEffects(S.Context))
+  S.Diag(BO->getBeginLoc(), diag::warn_bitwise_and_bool)
+  << OrigE->getSourceRange()
+  << FixItHint::CreateReplacement(BO->getOperatorLoc(), "&&");
+
   // For conditional operators, we analyze the arguments as if they
   // were being fed directly into the output.
   if (auto *CO = dyn_cast(SourceExpr)) {
Index: clang/include/clang/Basic/DiagnosticSemaKinds.td
===
--- clang/include/clang/Basic/DiagnosticSemaKinds.td
+++ clang/include/clang/Basic/DiagnosticSemaKinds.td
@@ -7424,7 +7424,10 @@
 def warn_bitwise_negation_bool : Warning<
   "bitwise negation of a boolean expression%select{;| always evaluates to 'true';}0 "
   "did you mean logical negation?">,
-  InGroup>;
+  InGroup;
+def warn_bitwise_and_bool : Warning<
+  "bitwise and of boolean expressions; did you mean logical and?">,
+  InGroup;
 def err_decrement_bool : Error<"cannot decrement expression of type bool">;
 def warn_increment_bool : Warning<
   "incrementing expression of type bool is deprecated and "
Index: clang/include/clang/Basic/DiagnosticGroups.td
===
--- clang/include/clang/Basic/DiagnosticGroups.td
+++ clang/include/clang/Basic/DiagnosticGroups.td
@@ -64,6 +64,10 @@
 def SignConversion : DiagGroup<"sign-conversion">;
 def PointerBoolConversion : DiagGroup<"pointer-bool-conversion">;
 

[PATCH] D107632: [clangd] Avoid "expected one compiler job" by picking the first eligible job.

2021-08-12 Thread Sam McCall via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
sammccall marked an inline comment as done.
Closed by commit rG2ff7ca98a99b: [clangd] Avoid expected one compiler 
job by picking the first eligible job. (authored by sammccall).

Changed prior to commit:
  https://reviews.llvm.org/D107632?vs=364832=366136#toc

Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D107632/new/

https://reviews.llvm.org/D107632

Files:
  clang-tools-extra/clangd/unittests/ClangdTests.cpp
  clang/lib/Frontend/CreateInvocationFromCommandLine.cpp
  clang/unittests/Frontend/CMakeLists.txt
  clang/unittests/Frontend/UtilsTest.cpp

Index: clang/unittests/Frontend/UtilsTest.cpp
===
--- /dev/null
+++ clang/unittests/Frontend/UtilsTest.cpp
@@ -0,0 +1,37 @@
+//===- unittests/Frontend/UtilsTest.cpp ---===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+
+#include "clang/Frontend/Utils.h"
+#include "clang/Basic/Diagnostic.h"
+#include "clang/Basic/TargetOptions.h"
+#include "clang/Frontend/CompilerInstance.h"
+#include "clang/Frontend/CompilerInvocation.h"
+#include "llvm/Support/VirtualFileSystem.h"
+#include "gmock/gmock.h"
+#include "gtest/gtest.h"
+
+namespace clang {
+namespace {
+
+TEST(BuildCompilerInvocationTest, RecoverMultipleJobs) {
+  // This generates multiple jobs and we recover by using the first.
+  std::vector Args = {"clang", "--target=macho", "-arch",  "i386",
+"-arch", "x86_64", "foo.cpp"};
+  clang::IgnoringDiagConsumer D;
+  llvm::IntrusiveRefCntPtr CommandLineDiagsEngine =
+  clang::CompilerInstance::createDiagnostics(new DiagnosticOptions, ,
+ false);
+  std::unique_ptr CI = createInvocationFromCommandLine(
+  Args, CommandLineDiagsEngine, new llvm::vfs::InMemoryFileSystem(),
+  /*ShouldRecoverOnErrors=*/true);
+  ASSERT_TRUE(CI);
+  EXPECT_THAT(CI->TargetOpts->Triple, testing::StartsWith("i386-"));
+}
+
+} // namespace
+} // namespace clang
Index: clang/unittests/Frontend/CMakeLists.txt
===
--- clang/unittests/Frontend/CMakeLists.txt
+++ clang/unittests/Frontend/CMakeLists.txt
@@ -13,6 +13,7 @@
   PCHPreambleTest.cpp
   OutputStreamTest.cpp
   TextDiagnosticTest.cpp
+  UtilsTest.cpp
   )
 clang_target_link_libraries(FrontendTests
   PRIVATE
Index: clang/lib/Frontend/CreateInvocationFromCommandLine.cpp
===
--- clang/lib/Frontend/CreateInvocationFromCommandLine.cpp
+++ clang/lib/Frontend/CreateInvocationFromCommandLine.cpp
@@ -79,22 +79,24 @@
   }
 }
   }
-  if (Jobs.size() == 0 || !isa(*Jobs.begin()) ||
-  (Jobs.size() > 1 && !OffloadCompilation)) {
+
+  bool PickFirstOfMany = OffloadCompilation || ShouldRecoverOnErorrs;
+  if (Jobs.size() == 0 || (Jobs.size() > 1 && !PickFirstOfMany)) {
 SmallString<256> Msg;
 llvm::raw_svector_ostream OS(Msg);
 Jobs.Print(OS, "; ", true);
 Diags->Report(diag::err_fe_expected_compiler_job) << OS.str();
 return nullptr;
   }
-
-  const driver::Command  = cast(*Jobs.begin());
-  if (StringRef(Cmd.getCreator().getName()) != "clang") {
+  auto Cmd = llvm::find_if(Jobs, [](const driver::Command ) {
+return StringRef(Cmd.getCreator().getName()) == "clang";
+  });
+  if (Cmd == Jobs.end()) {
 Diags->Report(diag::err_fe_expected_clang_command);
 return nullptr;
   }
 
-  const ArgStringList  = Cmd.getArguments();
+  const ArgStringList  = Cmd->getArguments();
   if (CC1Args)
 *CC1Args = {CCArgs.begin(), CCArgs.end()};
   auto CI = std::make_unique();
Index: clang-tools-extra/clangd/unittests/ClangdTests.cpp
===
--- clang-tools-extra/clangd/unittests/ClangdTests.cpp
+++ clang-tools-extra/clangd/unittests/ClangdTests.cpp
@@ -624,10 +624,8 @@
   ClangdServer Server(CDB, FS, ClangdServer::optsForTest(), );
 
   auto FooCpp = testPath("foo.cpp");
-  // clang cannot create CompilerInvocation if we pass two files in the
-  // CompileCommand. We pass the file in ExtraFlags once and CDB adds another
-  // one in getCompileCommand().
-  CDB.ExtraClangFlags.push_back(FooCpp);
+  // clang cannot create CompilerInvocation in this case.
+  CDB.ExtraClangFlags.push_back("-###");
 
   // Clang can't parse command args in that case, but we shouldn't crash.
   runAddDocument(Server, FooCpp, "int main() {}");
@@ -1080,7 +1078,7 @@
   Opts.RunParser = CodeCompleteOptions::ParseIfReady;
 
   // This will make compile command broken and preamble absent.
-  

[clang-tools-extra] 2ff7ca9 - [clangd] Avoid "expected one compiler job" by picking the first eligible job.

2021-08-12 Thread Sam McCall via cfe-commits

Author: Sam McCall
Date: 2021-08-13T00:36:30+02:00
New Revision: 2ff7ca98a99bbfc4f44b8ba1e2e4e594f8ee253e

URL: 
https://github.com/llvm/llvm-project/commit/2ff7ca98a99bbfc4f44b8ba1e2e4e594f8ee253e
DIFF: 
https://github.com/llvm/llvm-project/commit/2ff7ca98a99bbfc4f44b8ba1e2e4e594f8ee253e.diff

LOG: [clangd] Avoid "expected one compiler job" by picking the first eligible 
job.

This happens in createInvocationWithCommandLine but only clangd currently passes
ShouldRecoverOnErorrs (sic).

One cause of this (with correct command) is several -arch arguments for mac
multi-arch support.

Fixes https://github.com/clangd/clangd/issues/827

Differential Revision: https://reviews.llvm.org/D107632

Added: 
clang/unittests/Frontend/UtilsTest.cpp

Modified: 
clang-tools-extra/clangd/unittests/ClangdTests.cpp
clang/lib/Frontend/CreateInvocationFromCommandLine.cpp
clang/unittests/Frontend/CMakeLists.txt

Removed: 




diff  --git a/clang-tools-extra/clangd/unittests/ClangdTests.cpp 
b/clang-tools-extra/clangd/unittests/ClangdTests.cpp
index 07f5da1fbc52f..4a2cba52f93ab 100644
--- a/clang-tools-extra/clangd/unittests/ClangdTests.cpp
+++ b/clang-tools-extra/clangd/unittests/ClangdTests.cpp
@@ -624,10 +624,8 @@ TEST(ClangdServerTest, InvalidCompileCommand) {
   ClangdServer Server(CDB, FS, ClangdServer::optsForTest(), );
 
   auto FooCpp = testPath("foo.cpp");
-  // clang cannot create CompilerInvocation if we pass two files in the
-  // CompileCommand. We pass the file in ExtraFlags once and CDB adds another
-  // one in getCompileCommand().
-  CDB.ExtraClangFlags.push_back(FooCpp);
+  // clang cannot create CompilerInvocation in this case.
+  CDB.ExtraClangFlags.push_back("-###");
 
   // Clang can't parse command args in that case, but we shouldn't crash.
   runAddDocument(Server, FooCpp, "int main() {}");
@@ -1080,7 +1078,7 @@ TEST(ClangdServerTest, FallbackWhenPreambleIsNotReady) {
   Opts.RunParser = CodeCompleteOptions::ParseIfReady;
 
   // This will make compile command broken and preamble absent.
-  CDB.ExtraClangFlags = {"yolo.cc"};
+  CDB.ExtraClangFlags = {"-###"};
   Server.addDocument(FooCpp, Code.code());
   ASSERT_TRUE(Server.blockUntilIdleForTest());
   auto Res = cantFail(runCodeComplete(Server, FooCpp, Code.point(), Opts));

diff  --git a/clang/lib/Frontend/CreateInvocationFromCommandLine.cpp 
b/clang/lib/Frontend/CreateInvocationFromCommandLine.cpp
index 2e23ebfdf1602..2a14b7aab52ee 100644
--- a/clang/lib/Frontend/CreateInvocationFromCommandLine.cpp
+++ b/clang/lib/Frontend/CreateInvocationFromCommandLine.cpp
@@ -79,22 +79,24 @@ std::unique_ptr 
clang::createInvocationFromCommandLine(
   }
 }
   }
-  if (Jobs.size() == 0 || !isa(*Jobs.begin()) ||
-  (Jobs.size() > 1 && !OffloadCompilation)) {
+
+  bool PickFirstOfMany = OffloadCompilation || ShouldRecoverOnErorrs;
+  if (Jobs.size() == 0 || (Jobs.size() > 1 && !PickFirstOfMany)) {
 SmallString<256> Msg;
 llvm::raw_svector_ostream OS(Msg);
 Jobs.Print(OS, "; ", true);
 Diags->Report(diag::err_fe_expected_compiler_job) << OS.str();
 return nullptr;
   }
-
-  const driver::Command  = cast(*Jobs.begin());
-  if (StringRef(Cmd.getCreator().getName()) != "clang") {
+  auto Cmd = llvm::find_if(Jobs, [](const driver::Command ) {
+return StringRef(Cmd.getCreator().getName()) == "clang";
+  });
+  if (Cmd == Jobs.end()) {
 Diags->Report(diag::err_fe_expected_clang_command);
 return nullptr;
   }
 
-  const ArgStringList  = Cmd.getArguments();
+  const ArgStringList  = Cmd->getArguments();
   if (CC1Args)
 *CC1Args = {CCArgs.begin(), CCArgs.end()};
   auto CI = std::make_unique();

diff  --git a/clang/unittests/Frontend/CMakeLists.txt 
b/clang/unittests/Frontend/CMakeLists.txt
index 3c25b43e95307..1a7b8193e1391 100644
--- a/clang/unittests/Frontend/CMakeLists.txt
+++ b/clang/unittests/Frontend/CMakeLists.txt
@@ -13,6 +13,7 @@ add_clang_unittest(FrontendTests
   PCHPreambleTest.cpp
   OutputStreamTest.cpp
   TextDiagnosticTest.cpp
+  UtilsTest.cpp
   )
 clang_target_link_libraries(FrontendTests
   PRIVATE

diff  --git a/clang/unittests/Frontend/UtilsTest.cpp 
b/clang/unittests/Frontend/UtilsTest.cpp
new file mode 100644
index 0..9f9c499591cef
--- /dev/null
+++ b/clang/unittests/Frontend/UtilsTest.cpp
@@ -0,0 +1,37 @@
+//===- unittests/Frontend/UtilsTest.cpp 
---===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+
+#include "clang/Frontend/Utils.h"
+#include "clang/Basic/Diagnostic.h"
+#include "clang/Basic/TargetOptions.h"
+#include "clang/Frontend/CompilerInstance.h"
+#include "clang/Frontend/CompilerInvocation.h"
+#include 

[PATCH] D107632: [clangd] Avoid "expected one compiler job" by picking the first eligible job.

2021-08-12 Thread Sam McCall via Phabricator via cfe-commits
sammccall marked an inline comment as done.
sammccall added inline comments.



Comment at: clang-tools-extra/clangd/Compiler.cpp:42
  const clang::Diagnostic ) {
+  DiagnosticConsumer::HandleDiagnostic(DiagLevel, Info);
   IgnoreDiagnostics::log(DiagLevel, Info);

kadircet wrote:
> not sure i follow this change. is this for making sure fatal/error diagnostic 
> counts can be checked (so that actions can signal failure) or something else?
Oops, this was leftover from when we were testing this in clangd. (And was for 
the reason you suggested, just for testing). Removed.



Comment at: clang/lib/Frontend/CreateInvocationFromCommandLine.cpp:92
-  const driver::Command  = cast(*Jobs.begin());
-  if (StringRef(Cmd.getCreator().getName()) != "clang") {
 Diags->Report(diag::err_fe_expected_clang_command);

kadircet wrote:
> sammccall wrote:
> > kadircet wrote:
> > > hmm, this looks like a subtle behaviour change. I definitely like the 
> > > behaviour you proposed better, but maybe do it in a separate patch for 
> > > making the revert easier if need be?
> > Which behavior change are do you mean?
> > 
> > When RecoverFromErrors is false and OffloadCompilation is false, behavior 
> > is same as before: if there isn't exactly one job we diagnose that and 
> > exit, if it's not suitable we diagnose that and exit.
> > 
> > When RecoverFromErrors is true we search for the first suitable job, 
> > instead of complaining that the number is wrong or the one at the front 
> > isn't suitable, this is the intended change (and basically only affects 
> > clangd).
> > 
> > When OffloadCompilation is true, there is a behavior change: previously 
> > we'd use the first job and fail if it's not clang, now we'll use the first 
> > clang job. The old behavior seems brittle and the change only affects 
> > (previously) error cases, and I'd have to add more complexity to preserve 
> > it - is this worthwhile?
> > When OffloadCompilation is true, there is a behavior change: previously 
> > we'd use the first job and fail if it's not clang, now we'll use the first 
> > clang job.
> 
> I was talking about this particular change.
> 
> > The old behavior seems brittle and the change only affects (previously) 
> > error cases
> 
> As mentioned I also like the new behaviour more, I just don't know about what 
> the offloading logic does (i suppose it is about cuda compilation) and I was 
> anxious about it breaking when one of the Jobs satisfy the constraint but it 
> is not the first one.
> 
> > and I'd have to add more complexity to preserve it - is this worthwhile?
> 
> One option could be to just keep this part the same (i.e. only use the first 
> Job as long as `PickFirstOfMany` is set, even if `OffloadCompilation` is 
> false). Then send a follow-up change, that'll search for a suitable job. That 
> way we can only revert the last one if it breaks and know the constraints. 
> (And decide to do the search iff `ShouldRecoverOnErorrs && !Offload`). But it 
> is not that important, feel free to just land as-is.
It makes sense. I think i'm happy enough with this patch just getting reverted 
in such a case though, especially since it's just "defense in depth" currently 
rather than "load-bearing".


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D107632/new/

https://reviews.llvm.org/D107632

___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D107690: [Modules] Do not remove failed modules after the control block phase

2021-08-12 Thread Volodymyr Sapsai via Phabricator via cfe-commits
vsapsai added a comment.

Why are you not just changing `return OutOfDate` to `return Failure` for 
SUBMODULE_UMBRELLA_HEADER and SUBMODULE_UMBRELLA_DIR? I have no strong opinion 
on this but it feels more in line with the rest of the changes. Also I've tried 
to do that and nothing seems to be broken.

And for the rest of the code for these records I think it is worth keeping 
`ModMap.setUmbrellaHeader` and `ModMap.setUmbrellaDir` with preceding 
preparation and checks. The code in ModuleMap seems to be complicated enough 
and stateful, so removing those setters can break some stuff. It is possible 
everything will be fine but I don't want to chance that unless required.


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D107690/new/

https://reviews.llvm.org/D107690

___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D108003: [Clang] Extend -Wbool-operation to warn about bitwise and of bools with side effects

2021-08-12 Thread Arthur O'Dwyer via Phabricator via cfe-commits
Quuxplusone added subscribers: mclow.lists, Quuxplusone.
Quuxplusone added inline comments.



Comment at: clang/include/clang/Basic/DiagnosticSemaKinds.td:7428-7430
+def warn_bitwise_and_bool : Warning<
+  "bitwise and of boolean expressions; did you mean logical and?">,
+  InGroup;

I suggest that the name and wording of this diagnostic should match 
`warn_logical_instead_of_bitwise`, currently `"use of logical '%0' with 
constant operand"`. So:
```
def warn_bitwise_instead_of_logical : Warning<
  "use of bitwise '%0' with boolean operand">,
```
This neatly sidesteps the problem of what to call the `&` operator: I was not 
thrilled with the phrase `bitwise and of`, but have no problem with `use of 
bitwise '&'`.



Comment at: clang/test/Sema/warn-bitwise-and-bool.c:21-22
+void test(boolean a, boolean b, int i) {
+  b = a & b;
+  b = a & foo();  // expected-warning {{bitwise and of boolean 
expressions; did you mean logical and?}}
+  // CHECK: 
fix-it:"{{.*}}":{[[@LINE-1]]:9-[[@LINE-1]]:10}:"&&"

So the warning triggers only when the RHS has side-effects? I'd like tests for
```
foo() & a;  // should not trigger, by that logic, because && wouldn't 
short-circuit anything?
(p != nullptr) & (*p == 42);  // should certainly trigger: deref is a side 
effect, and of course obviously this is a bug
```



Comment at: clang/test/Sema/warn-bitwise-and-bool.c:31
+  // CHECK: fix-it:"{{.*}}":{[[@LINE-1]]:9-[[@LINE-1]]:10}:"&&"
+  i = !b & foo(); // expected-warning {{bitwise and of boolean expressions; 
did you mean logical and?}}
+  // CHECK: 
fix-it:"{{.*}}":{[[@LINE-1]]:10-[[@LINE-1]]:11}:"&&"

Why is this assigning to `i` instead of `b`?
Actually, the assignment shouldn't matter to the diagnostic at all, right? 
Perhaps each test case should be written as, like,
```
void sink(bool);

   sink(a & b);
   sink(a & foo());
   sink(foo() & bar());
```
etc.



Comment at: clang/test/Sema/warn-bitwise-and-bool.c:34
+  b = bar() & (i > 4);
+  b = (i == 7) & foo(); // expected-warning {{bitwise and of boolean 
expressions; did you mean logical and?}}
+#ifdef __cplusplus

I'd also like a negative test for @mclow.lists' example of `int n = ...; b = (n 
& (n-1));` (where the //result// is being used as a boolean, but the bitwise op 
is correct and the logical op would be 100% wrong).



Comment at: clang/test/Sema/warn-bitwise-and-bool.c:36
+#ifdef __cplusplus
+  b = a and foo();
+#endif

I assume you meant `bitand` and expect a warning?


CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D108003/new/

https://reviews.llvm.org/D108003

___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D108003: [Clang] Extend -Wbool-operation to warn about bitwise and of bools with side effects

2021-08-12 Thread Dávid Bolvanský via Phabricator via cfe-commits
xbolva00 updated this revision to Diff 366130.

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D108003/new/

https://reviews.llvm.org/D108003

Files:
  clang/include/clang/Basic/DiagnosticGroups.td
  clang/include/clang/Basic/DiagnosticSemaKinds.td
  clang/lib/Sema/SemaChecking.cpp
  clang/test/Sema/warn-bitwise-and-bool.c


Index: clang/test/Sema/warn-bitwise-and-bool.c
===
--- /dev/null
+++ clang/test/Sema/warn-bitwise-and-bool.c
@@ -0,0 +1,38 @@
+// RUN: %clang_cc1 -x c -fsyntax-only -verify -Wbool-operation %s
+// RUN: %clang_cc1 -x c -fsyntax-only -verify %s
+// RUN: %clang_cc1 -x c -fsyntax-only -fdiagnostics-parseable-fixits %s 2>&1 | 
FileCheck %s
+// RUN: %clang_cc1 -x c++ -fsyntax-only -verify -Wbool-operation %s
+// RUN: %clang_cc1 -x c++ -fsyntax-only -verify %s
+// RUN: %clang_cc1 -x c++ -fsyntax-only -fdiagnostics-parseable-fixits %s 2>&1 
| FileCheck %s
+
+#ifdef __cplusplus
+typedef bool boolean;
+#else
+typedef _Bool boolean;
+#endif
+
+boolean foo(void);
+boolean bar(void);
+boolean baz(void) __attribute__((const));
+
+#define FOO foo()
+
+void test(boolean a, boolean b, int i) {
+  b = a & b;
+  b = a & foo();  // expected-warning {{bitwise and of boolean 
expressions; did you mean logical and?}}
+  // CHECK: 
fix-it:"{{.*}}":{[[@LINE-1]]:9-[[@LINE-1]]:10}:"&&"
+  b = foo() & bar();  // expected-warning {{bitwise and of boolean 
expressions; did you mean logical and?}}
+  // CHECK: 
fix-it:"{{.*}}":{[[@LINE-1]]:13-[[@LINE-1]]:14}:"&&"
+  b = foo() & !bar(); // expected-warning {{bitwise and of boolean 
expressions; did you mean logical and?}}
+  // CHECK: 
fix-it:"{{.*}}":{[[@LINE-1]]:13-[[@LINE-1]]:14}:"&&"
+  b = a & baz();
+  b = a & FOO;// expected-warning {{bitwise and of boolean expressions; 
did you mean logical and?}}
+  // CHECK: fix-it:"{{.*}}":{[[@LINE-1]]:9-[[@LINE-1]]:10}:"&&"
+  i = !b & foo(); // expected-warning {{bitwise and of boolean expressions; 
did you mean logical and?}}
+  // CHECK: 
fix-it:"{{.*}}":{[[@LINE-1]]:10-[[@LINE-1]]:11}:"&&"
+  b = bar() & (i > 4);
+  b = (i == 7) & foo(); // expected-warning {{bitwise and of boolean 
expressions; did you mean logical and?}}
+#ifdef __cplusplus
+  b = a and foo();
+#endif
+}
Index: clang/lib/Sema/SemaChecking.cpp
===
--- clang/lib/Sema/SemaChecking.cpp
+++ clang/lib/Sema/SemaChecking.cpp
@@ -13073,6 +13073,15 @@
   << OrigE->getSourceRange() << T->isBooleanType()
   << FixItHint::CreateReplacement(UO->getBeginLoc(), "!");
 
+  if (const auto *BO = dyn_cast(SourceExpr))
+if (BO->getOpcode() == BO_And &&
+BO->getLHS()->isKnownToHaveBooleanValue() &&
+BO->getRHS()->isKnownToHaveBooleanValue() &&
+BO->getRHS()->HasSideEffects(S.Context))
+  S.Diag(BO->getBeginLoc(), diag::warn_bitwise_and_bool)
+  << OrigE->getSourceRange()
+  << FixItHint::CreateReplacement(BO->getOperatorLoc(), "&&");
+
   // For conditional operators, we analyze the arguments as if they
   // were being fed directly into the output.
   if (auto *CO = dyn_cast(SourceExpr)) {
Index: clang/include/clang/Basic/DiagnosticSemaKinds.td
===
--- clang/include/clang/Basic/DiagnosticSemaKinds.td
+++ clang/include/clang/Basic/DiagnosticSemaKinds.td
@@ -7424,7 +7424,10 @@
 def warn_bitwise_negation_bool : Warning<
   "bitwise negation of a boolean expression%select{;| always evaluates to 
'true';}0 "
   "did you mean logical negation?">,
-  InGroup>;
+  InGroup;
+def warn_bitwise_and_bool : Warning<
+  "bitwise and of boolean expressions; did you mean logical and?">,
+  InGroup;
 def err_decrement_bool : Error<"cannot decrement expression of type bool">;
 def warn_increment_bool : Warning<
   "incrementing expression of type bool is deprecated and "
Index: clang/include/clang/Basic/DiagnosticGroups.td
===
--- clang/include/clang/Basic/DiagnosticGroups.td
+++ clang/include/clang/Basic/DiagnosticGroups.td
@@ -64,6 +64,10 @@
 def SignConversion : DiagGroup<"sign-conversion">;
 def PointerBoolConversion : DiagGroup<"pointer-bool-conversion">;
 def UndefinedBoolConversion : DiagGroup<"undefined-bool-conversion">;
+def BoolOperationNegation : DiagGroup<"bool-operation-negation">;
+def BoolOperationAnd : DiagGroup<"bool-operation-and">;
+def BoolOperation : DiagGroup<"bool-operation", [BoolOperationNegation,
+ BoolOperationAnd]>;
 def BoolConversion : DiagGroup<"bool-conversion", [PointerBoolConversion,
UndefinedBoolConversion]>;
 def IntConversion : DiagGroup<"int-conversion">;


Index: clang/test/Sema/warn-bitwise-and-bool.c

[PATCH] D107365: clangd: Make documentation property of completion items more similar

2021-08-12 Thread Sam McCall via Phabricator via cfe-commits
This revision was landed with ongoing or failed builds.
This revision was automatically updated to reflect the committed changes.
Closed by commit rG6b28835b3754: clangd: Make documentation property of 
completion items more similar (authored by ckandeler, committed by sammccall).

Changed prior to commit:
  https://reviews.llvm.org/D107365?vs=364790=366128#toc

Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D107365/new/

https://reviews.llvm.org/D107365

Files:
  clang-tools-extra/clangd/CodeComplete.cpp
  clang-tools-extra/clangd/unittests/CodeCompleteTests.cpp


Index: clang-tools-extra/clangd/unittests/CodeCompleteTests.cpp
===
--- clang-tools-extra/clangd/unittests/CodeCompleteTests.cpp
+++ clang-tools-extra/clangd/unittests/CodeCompleteTests.cpp
@@ -907,7 +907,7 @@
   auto Results = completions(
   R"cpp(
   // Non-doxygen comment.
-  int foo();
+  __attribute__((annotate("custom_annotation"))) int foo();
   /// Doxygen comment.
   /// \param int a
   int bar(int a);
@@ -919,7 +919,8 @@
   int x = ^
  )cpp");
   EXPECT_THAT(Results.Completions,
-  Contains(AllOf(Named("foo"), Doc("Non-doxygen comment.";
+  Contains(AllOf(Named("foo"),
+  Doc("Annotation: custom_annotation\nNon-doxygen comment.";
   EXPECT_THAT(
   Results.Completions,
   Contains(AllOf(Named("bar"), Doc("Doxygen comment.\n\\param int a";
Index: clang-tools-extra/clangd/CodeComplete.cpp
===
--- clang-tools-extra/clangd/CodeComplete.cpp
+++ clang-tools-extra/clangd/CodeComplete.cpp
@@ -403,8 +403,9 @@
   if (C.IndexResult) {
 SetDoc(C.IndexResult->Documentation);
   } else if (C.SemaResult) {
-SetDoc(getDocComment(*ASTCtx, *C.SemaResult,
- /*CommentsFromHeader=*/false));
+const auto DocComment = getDocComment(*ASTCtx, *C.SemaResult,
+  /*CommentsFromHeader=*/false);
+SetDoc(formatDocumentation(*SemaCCS, DocComment));
   }
 }
 if (Completion.Deprecated) {


Index: clang-tools-extra/clangd/unittests/CodeCompleteTests.cpp
===
--- clang-tools-extra/clangd/unittests/CodeCompleteTests.cpp
+++ clang-tools-extra/clangd/unittests/CodeCompleteTests.cpp
@@ -907,7 +907,7 @@
   auto Results = completions(
   R"cpp(
   // Non-doxygen comment.
-  int foo();
+  __attribute__((annotate("custom_annotation"))) int foo();
   /// Doxygen comment.
   /// \param int a
   int bar(int a);
@@ -919,7 +919,8 @@
   int x = ^
  )cpp");
   EXPECT_THAT(Results.Completions,
-  Contains(AllOf(Named("foo"), Doc("Non-doxygen comment.";
+  Contains(AllOf(Named("foo"),
+  Doc("Annotation: custom_annotation\nNon-doxygen comment.";
   EXPECT_THAT(
   Results.Completions,
   Contains(AllOf(Named("bar"), Doc("Doxygen comment.\n\\param int a";
Index: clang-tools-extra/clangd/CodeComplete.cpp
===
--- clang-tools-extra/clangd/CodeComplete.cpp
+++ clang-tools-extra/clangd/CodeComplete.cpp
@@ -403,8 +403,9 @@
   if (C.IndexResult) {
 SetDoc(C.IndexResult->Documentation);
   } else if (C.SemaResult) {
-SetDoc(getDocComment(*ASTCtx, *C.SemaResult,
- /*CommentsFromHeader=*/false));
+const auto DocComment = getDocComment(*ASTCtx, *C.SemaResult,
+  /*CommentsFromHeader=*/false);
+SetDoc(formatDocumentation(*SemaCCS, DocComment));
   }
 }
 if (Completion.Deprecated) {
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang-tools-extra] 6b28835 - clangd: Make documentation property of completion items more similar

2021-08-12 Thread Sam McCall via cfe-commits

Author: Christian Kandeler
Date: 2021-08-13T00:18:15+02:00
New Revision: 6b28835b3754aa3b795e7684b3e7f465b516f753

URL: 
https://github.com/llvm/llvm-project/commit/6b28835b3754aa3b795e7684b3e7f465b516f753
DIFF: 
https://github.com/llvm/llvm-project/commit/6b28835b3754aa3b795e7684b3e7f465b516f753.diff

LOG: clangd: Make documentation property of completion items more similar

... to the one of signature hints.
In particular, completion items now also carry annotations, which client
code might be interested in.

Reviewed By: sammccall

Differential Revision: https://reviews.llvm.org/D107365

Added: 


Modified: 
clang-tools-extra/clangd/CodeComplete.cpp
clang-tools-extra/clangd/unittests/CodeCompleteTests.cpp

Removed: 




diff  --git a/clang-tools-extra/clangd/CodeComplete.cpp 
b/clang-tools-extra/clangd/CodeComplete.cpp
index 593426127aa2..abaedff82686 100644
--- a/clang-tools-extra/clangd/CodeComplete.cpp
+++ b/clang-tools-extra/clangd/CodeComplete.cpp
@@ -403,8 +403,9 @@ struct CodeCompletionBuilder {
   if (C.IndexResult) {
 SetDoc(C.IndexResult->Documentation);
   } else if (C.SemaResult) {
-SetDoc(getDocComment(*ASTCtx, *C.SemaResult,
- /*CommentsFromHeader=*/false));
+const auto DocComment = getDocComment(*ASTCtx, *C.SemaResult,
+  /*CommentsFromHeader=*/false);
+SetDoc(formatDocumentation(*SemaCCS, DocComment));
   }
 }
 if (Completion.Deprecated) {

diff  --git a/clang-tools-extra/clangd/unittests/CodeCompleteTests.cpp 
b/clang-tools-extra/clangd/unittests/CodeCompleteTests.cpp
index 3170099b437b..e37b65a9d4b8 100644
--- a/clang-tools-extra/clangd/unittests/CodeCompleteTests.cpp
+++ b/clang-tools-extra/clangd/unittests/CodeCompleteTests.cpp
@@ -907,7 +907,7 @@ TEST(CompletionTest, Documentation) {
   auto Results = completions(
   R"cpp(
   // Non-doxygen comment.
-  int foo();
+  __attribute__((annotate("custom_annotation"))) int foo();
   /// Doxygen comment.
   /// \param int a
   int bar(int a);
@@ -919,7 +919,8 @@ TEST(CompletionTest, Documentation) {
   int x = ^
  )cpp");
   EXPECT_THAT(Results.Completions,
-  Contains(AllOf(Named("foo"), Doc("Non-doxygen comment.";
+  Contains(AllOf(Named("foo"),
+  Doc("Annotation: custom_annotation\nNon-doxygen comment.";
   EXPECT_THAT(
   Results.Completions,
   Contains(AllOf(Named("bar"), Doc("Doxygen comment.\n\\param int a";



___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D95581: Frontend: Refactor compileModuleAndReadAST, NFC

2021-08-12 Thread Duncan P. N. Exon Smith via Phabricator via cfe-commits
This revision was landed with ongoing or failed builds.
This revision was automatically updated to reflect the committed changes.
Closed by commit rGc130300f8ba0: Frontend: Refactor compileModuleAndReadAST, 
NFC (authored by dexonsmith).

Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D95581/new/

https://reviews.llvm.org/D95581

Files:
  clang/lib/Frontend/CompilerInstance.cpp

Index: clang/lib/Frontend/CompilerInstance.cpp
===
--- clang/lib/Frontend/CompilerInstance.cpp
+++ clang/lib/Frontend/CompilerInstance.cpp
@@ -1264,31 +1264,79 @@
   return Result;
 }
 
+/// Read the AST right after compiling the module.
+static bool readASTAfterCompileModule(CompilerInstance ,
+  SourceLocation ImportLoc,
+  SourceLocation ModuleNameLoc,
+  Module *Module, StringRef ModuleFileName,
+  bool *OutOfDate) {
+  DiagnosticsEngine  = ImportingInstance.getDiagnostics();
+
+  unsigned ModuleLoadCapabilities = ASTReader::ARR_Missing;
+  if (OutOfDate)
+ModuleLoadCapabilities |= ASTReader::ARR_OutOfDate;
+
+  // Try to read the module file, now that we've compiled it.
+  ASTReader::ASTReadResult ReadResult =
+  ImportingInstance.getASTReader()->ReadAST(
+  ModuleFileName, serialization::MK_ImplicitModule, ImportLoc,
+  ModuleLoadCapabilities);
+  if (ReadResult == ASTReader::Success)
+return true;
+
+  // The caller wants to handle out-of-date failures.
+  if (OutOfDate && ReadResult == ASTReader::OutOfDate) {
+*OutOfDate = true;
+return false;
+  }
+
+  // The ASTReader didn't diagnose the error, so conservatively report it.
+  if (ReadResult == ASTReader::Missing || !Diags.hasErrorOccurred())
+Diags.Report(ModuleNameLoc, diag::err_module_not_built)
+  << Module->Name << SourceRange(ImportLoc, ModuleNameLoc);
+
+  return false;
+}
+
 /// Compile a module in a separate compiler instance and read the AST,
 /// returning true if the module compiles without errors.
+static bool compileModuleAndReadASTImpl(CompilerInstance ,
+SourceLocation ImportLoc,
+SourceLocation ModuleNameLoc,
+Module *Module,
+StringRef ModuleFileName) {
+  if (!compileModule(ImportingInstance, ModuleNameLoc, Module,
+ ModuleFileName)) {
+ImportingInstance.getDiagnostics().Report(ModuleNameLoc,
+  diag::err_module_not_built)
+<< Module->Name << SourceRange(ImportLoc, ModuleNameLoc);
+return false;
+  }
+
+  return readASTAfterCompileModule(ImportingInstance, ImportLoc, ModuleNameLoc,
+   Module, ModuleFileName,
+   /*OutOfDate=*/nullptr);
+}
+
+/// Compile a module in a separate compiler instance and read the AST,
+/// returning true if the module compiles without errors, using a lock manager
+/// to avoid building the same module in multiple compiler instances.
 ///
 /// Uses a lock file manager and exponential backoff to reduce the chances that
 /// multiple instances will compete to create the same module.  On timeout,
 /// deletes the lock file in order to avoid deadlock from crashing processes or
 /// bugs in the lock file manager.
-static bool compileModuleAndReadAST(CompilerInstance ,
-SourceLocation ImportLoc,
-SourceLocation ModuleNameLoc,
-Module *Module, StringRef ModuleFileName) {
+static bool compileModuleAndReadASTBehindLock(
+CompilerInstance , SourceLocation ImportLoc,
+SourceLocation ModuleNameLoc, Module *Module, StringRef ModuleFileName) {
   DiagnosticsEngine  = ImportingInstance.getDiagnostics();
 
-  auto diagnoseBuildFailure = [&] {
-Diags.Report(ModuleNameLoc, diag::err_module_not_built)
-<< Module->Name << SourceRange(ImportLoc, ModuleNameLoc);
-  };
-
   // FIXME: have LockFileManager return an error_code so that we can
   // avoid the mkdir when the directory already exists.
   StringRef Dir = llvm::sys::path::parent_path(ModuleFileName);
   llvm::sys::fs::create_directories(Dir);
 
   while (1) {
-unsigned ModuleLoadCapabilities = ASTReader::ARR_Missing;
 llvm::LockFileManager Locked(ModuleFileName);
 switch (Locked) {
 case llvm::LockFileManager::LFS_Error:
@@ -1302,55 +1350,42 @@
   LLVM_FALLTHROUGH;
 case llvm::LockFileManager::LFS_Owned:
   // We're responsible for building the module ourselves.
-  if (!compileModule(ImportingInstance, ModuleNameLoc, Module,
- ModuleFileName)) {
-diagnoseBuildFailure();
-return false;
-  }
-  

[clang] c130300 - Frontend: Refactor compileModuleAndReadAST, NFC

2021-08-12 Thread Duncan P. N. Exon Smith via cfe-commits

Author: Duncan P. N. Exon Smith
Date: 2021-08-12T15:16:08-07:00
New Revision: c130300f8ba0363749cf2490bbd43515fad8a759

URL: 
https://github.com/llvm/llvm-project/commit/c130300f8ba0363749cf2490bbd43515fad8a759
DIFF: 
https://github.com/llvm/llvm-project/commit/c130300f8ba0363749cf2490bbd43515fad8a759.diff

LOG: Frontend: Refactor compileModuleAndReadAST, NFC

This renames `compileModuleAndReadAST`, adding a `BehindLock` suffix,
and refactors it to significantly reduce nesting.

- Split out helpers `compileModuleAndReadASTImpl` and
  `readASTAfterCompileModule` which have straight-line code that doesn't
  worry about locks.
- Use `break` in the interesting cases of `switch` statements to reduce
  nesting.
- Use early `return`s to reduce nesting.

Detangling the compile-and-read logic from the check-for-locks logic
should be a net win for readability, although I also have a side
motivation of making the locks optional in a follow-up.

No functionality change here.

Differential Revision: https://reviews.llvm.org/D95581

Added: 


Modified: 
clang/lib/Frontend/CompilerInstance.cpp

Removed: 




diff  --git a/clang/lib/Frontend/CompilerInstance.cpp 
b/clang/lib/Frontend/CompilerInstance.cpp
index c642af1849bc4..d90b292808f21 100644
--- a/clang/lib/Frontend/CompilerInstance.cpp
+++ b/clang/lib/Frontend/CompilerInstance.cpp
@@ -1264,31 +1264,79 @@ static bool compileModule(CompilerInstance 
,
   return Result;
 }
 
+/// Read the AST right after compiling the module.
+static bool readASTAfterCompileModule(CompilerInstance ,
+  SourceLocation ImportLoc,
+  SourceLocation ModuleNameLoc,
+  Module *Module, StringRef ModuleFileName,
+  bool *OutOfDate) {
+  DiagnosticsEngine  = ImportingInstance.getDiagnostics();
+
+  unsigned ModuleLoadCapabilities = ASTReader::ARR_Missing;
+  if (OutOfDate)
+ModuleLoadCapabilities |= ASTReader::ARR_OutOfDate;
+
+  // Try to read the module file, now that we've compiled it.
+  ASTReader::ASTReadResult ReadResult =
+  ImportingInstance.getASTReader()->ReadAST(
+  ModuleFileName, serialization::MK_ImplicitModule, ImportLoc,
+  ModuleLoadCapabilities);
+  if (ReadResult == ASTReader::Success)
+return true;
+
+  // The caller wants to handle out-of-date failures.
+  if (OutOfDate && ReadResult == ASTReader::OutOfDate) {
+*OutOfDate = true;
+return false;
+  }
+
+  // The ASTReader didn't diagnose the error, so conservatively report it.
+  if (ReadResult == ASTReader::Missing || !Diags.hasErrorOccurred())
+Diags.Report(ModuleNameLoc, diag::err_module_not_built)
+  << Module->Name << SourceRange(ImportLoc, ModuleNameLoc);
+
+  return false;
+}
+
 /// Compile a module in a separate compiler instance and read the AST,
 /// returning true if the module compiles without errors.
+static bool compileModuleAndReadASTImpl(CompilerInstance ,
+SourceLocation ImportLoc,
+SourceLocation ModuleNameLoc,
+Module *Module,
+StringRef ModuleFileName) {
+  if (!compileModule(ImportingInstance, ModuleNameLoc, Module,
+ ModuleFileName)) {
+ImportingInstance.getDiagnostics().Report(ModuleNameLoc,
+  diag::err_module_not_built)
+<< Module->Name << SourceRange(ImportLoc, ModuleNameLoc);
+return false;
+  }
+
+  return readASTAfterCompileModule(ImportingInstance, ImportLoc, ModuleNameLoc,
+   Module, ModuleFileName,
+   /*OutOfDate=*/nullptr);
+}
+
+/// Compile a module in a separate compiler instance and read the AST,
+/// returning true if the module compiles without errors, using a lock manager
+/// to avoid building the same module in multiple compiler instances.
 ///
 /// Uses a lock file manager and exponential backoff to reduce the chances that
 /// multiple instances will compete to create the same module.  On timeout,
 /// deletes the lock file in order to avoid deadlock from crashing processes or
 /// bugs in the lock file manager.
-static bool compileModuleAndReadAST(CompilerInstance ,
-SourceLocation ImportLoc,
-SourceLocation ModuleNameLoc,
-Module *Module, StringRef ModuleFileName) {
+static bool compileModuleAndReadASTBehindLock(
+CompilerInstance , SourceLocation ImportLoc,
+SourceLocation ModuleNameLoc, Module *Module, StringRef ModuleFileName) {
   DiagnosticsEngine  = ImportingInstance.getDiagnostics();
 
-  auto diagnoseBuildFailure = [&] {
-Diags.Report(ModuleNameLoc, diag::err_module_not_built)
-  

[PATCH] D107137: clangd: Provide hover info for include directives

2021-08-12 Thread Sam McCall via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rGf9c8602b53fd: clangd: Provide hover info for include 
directives (authored by ckandeler, committed by sammccall).

Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D107137/new/

https://reviews.llvm.org/D107137

Files:
  clang-tools-extra/clangd/Hover.cpp
  clang-tools-extra/clangd/Hover.h
  clang-tools-extra/clangd/unittests/HoverTests.cpp


Index: clang-tools-extra/clangd/unittests/HoverTests.cpp
===
--- clang-tools-extra/clangd/unittests/HoverTests.cpp
+++ clang-tools-extra/clangd/unittests/HoverTests.cpp
@@ -2760,6 +2760,15 @@
 
 // In test::Bar
 int foo = 3)",
+  },
+  {
+  [](HoverInfo ) {
+HI.Name = "stdio.h";
+HI.Definition = "/usr/include/stdio.h";
+  },
+  R"(stdio.h
+
+/usr/include/stdio.h)",
   }};
 
   for (const auto  : Cases) {
Index: clang-tools-extra/clangd/Hover.h
===
--- clang-tools-extra/clangd/Hover.h
+++ clang-tools-extra/clangd/Hover.h
@@ -58,7 +58,7 @@
   std::string Documentation;
   /// Source code containing the definition of the symbol.
   std::string Definition;
-
+  const char *DefinitionLanguage = "cpp";
   /// Access specifier for declarations inside class/struct/unions, empty for
   /// others.
   std::string AccessSpecifier;
Index: clang-tools-extra/clangd/Hover.cpp
===
--- clang-tools-extra/clangd/Hover.cpp
+++ clang-tools-extra/clangd/Hover.cpp
@@ -920,6 +920,22 @@
   if (TokensTouchingCursor.empty())
 return llvm::None;
 
+  // Show full header file path if cursor is on include directive.
+  if (const auto MainFilePath =
+  getCanonicalPath(SM.getFileEntryForID(SM.getMainFileID()), SM)) {
+for (const auto  : AST.getIncludeStructure().MainFileIncludes) {
+  if (Inc.Resolved.empty() || Inc.HashLine != Pos.line)
+continue;
+  HoverInfo HI;
+  HI.Name = std::string(llvm::sys::path::filename(Inc.Resolved));
+  // FIXME: We don't have a fitting value for Kind.
+  HI.Definition =
+  URIForFile::canonicalize(Inc.Resolved, *MainFilePath).file().str();
+  HI.DefinitionLanguage = "";
+  return HI;
+}
+  }
+
   // To be used as a backup for highlighting the selected token, we use back as
   // it aligns better with biases elsewhere (editors tend to send the position
   // for the left of the hovered token).
@@ -998,6 +1014,7 @@
 
 markup::Document HoverInfo::present() const {
   markup::Document Output;
+
   // Header contains a text of the form:
   // variable `var`
   //
@@ -1098,7 +1115,8 @@
: Definition;
 // Note that we don't print anything for global namespace, to not annoy
 // non-c++ projects or projects that are not making use of namespaces.
-Output.addCodeBlock(ScopeComment + DefinitionWithAccess);
+Output.addCodeBlock(ScopeComment + DefinitionWithAccess,
+DefinitionLanguage);
   }
 
   return Output;


Index: clang-tools-extra/clangd/unittests/HoverTests.cpp
===
--- clang-tools-extra/clangd/unittests/HoverTests.cpp
+++ clang-tools-extra/clangd/unittests/HoverTests.cpp
@@ -2760,6 +2760,15 @@
 
 // In test::Bar
 int foo = 3)",
+  },
+  {
+  [](HoverInfo ) {
+HI.Name = "stdio.h";
+HI.Definition = "/usr/include/stdio.h";
+  },
+  R"(stdio.h
+
+/usr/include/stdio.h)",
   }};
 
   for (const auto  : Cases) {
Index: clang-tools-extra/clangd/Hover.h
===
--- clang-tools-extra/clangd/Hover.h
+++ clang-tools-extra/clangd/Hover.h
@@ -58,7 +58,7 @@
   std::string Documentation;
   /// Source code containing the definition of the symbol.
   std::string Definition;
-
+  const char *DefinitionLanguage = "cpp";
   /// Access specifier for declarations inside class/struct/unions, empty for
   /// others.
   std::string AccessSpecifier;
Index: clang-tools-extra/clangd/Hover.cpp
===
--- clang-tools-extra/clangd/Hover.cpp
+++ clang-tools-extra/clangd/Hover.cpp
@@ -920,6 +920,22 @@
   if (TokensTouchingCursor.empty())
 return llvm::None;
 
+  // Show full header file path if cursor is on include directive.
+  if (const auto MainFilePath =
+  getCanonicalPath(SM.getFileEntryForID(SM.getMainFileID()), SM)) {
+for (const auto  : AST.getIncludeStructure().MainFileIncludes) {
+  if (Inc.Resolved.empty() || Inc.HashLine != Pos.line)
+continue;
+  HoverInfo HI;
+  HI.Name = std::string(llvm::sys::path::filename(Inc.Resolved));
+  // FIXME: We don't have a fitting value for Kind.
+  

[PATCH] D107137: clangd: Provide hover info for include directives

2021-08-12 Thread Sam McCall via Phabricator via cfe-commits
sammccall added a comment.

All done! Sorry for the delay.


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D107137/new/

https://reviews.llvm.org/D107137

___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang-tools-extra] f9c8602 - clangd: Provide hover info for include directives

2021-08-12 Thread Sam McCall via cfe-commits

Author: Christian Kandeler
Date: 2021-08-13T00:07:23+02:00
New Revision: f9c8602b53fd277e1428cb6e8e63485b14520a82

URL: 
https://github.com/llvm/llvm-project/commit/f9c8602b53fd277e1428cb6e8e63485b14520a82
DIFF: 
https://github.com/llvm/llvm-project/commit/f9c8602b53fd277e1428cb6e8e63485b14520a82.diff

LOG: clangd: Provide hover info for include directives

It's quite useful to be able to hover over an #include and see the full
path to the header file.

Reviewed By: sammccall

Differential Revision: https://reviews.llvm.org/D107137

Added: 


Modified: 
clang-tools-extra/clangd/Hover.cpp
clang-tools-extra/clangd/Hover.h
clang-tools-extra/clangd/unittests/HoverTests.cpp

Removed: 




diff  --git a/clang-tools-extra/clangd/Hover.cpp 
b/clang-tools-extra/clangd/Hover.cpp
index d16a2ebcbfd7..763125cd10f5 100644
--- a/clang-tools-extra/clangd/Hover.cpp
+++ b/clang-tools-extra/clangd/Hover.cpp
@@ -920,6 +920,22 @@ llvm::Optional getHover(ParsedAST , 
Position Pos,
   if (TokensTouchingCursor.empty())
 return llvm::None;
 
+  // Show full header file path if cursor is on include directive.
+  if (const auto MainFilePath =
+  getCanonicalPath(SM.getFileEntryForID(SM.getMainFileID()), SM)) {
+for (const auto  : AST.getIncludeStructure().MainFileIncludes) {
+  if (Inc.Resolved.empty() || Inc.HashLine != Pos.line)
+continue;
+  HoverInfo HI;
+  HI.Name = std::string(llvm::sys::path::filename(Inc.Resolved));
+  // FIXME: We don't have a fitting value for Kind.
+  HI.Definition =
+  URIForFile::canonicalize(Inc.Resolved, *MainFilePath).file().str();
+  HI.DefinitionLanguage = "";
+  return HI;
+}
+  }
+
   // To be used as a backup for highlighting the selected token, we use back as
   // it aligns better with biases elsewhere (editors tend to send the position
   // for the left of the hovered token).
@@ -998,6 +1014,7 @@ llvm::Optional getHover(ParsedAST , 
Position Pos,
 
 markup::Document HoverInfo::present() const {
   markup::Document Output;
+
   // Header contains a text of the form:
   // variable `var`
   //
@@ -1098,7 +1115,8 @@ markup::Document HoverInfo::present() const {
: Definition;
 // Note that we don't print anything for global namespace, to not annoy
 // non-c++ projects or projects that are not making use of namespaces.
-Output.addCodeBlock(ScopeComment + DefinitionWithAccess);
+Output.addCodeBlock(ScopeComment + DefinitionWithAccess,
+DefinitionLanguage);
   }
 
   return Output;

diff  --git a/clang-tools-extra/clangd/Hover.h 
b/clang-tools-extra/clangd/Hover.h
index 44ee9b7d7979..4e6314dfc5ed 100644
--- a/clang-tools-extra/clangd/Hover.h
+++ b/clang-tools-extra/clangd/Hover.h
@@ -58,7 +58,7 @@ struct HoverInfo {
   std::string Documentation;
   /// Source code containing the definition of the symbol.
   std::string Definition;
-
+  const char *DefinitionLanguage = "cpp";
   /// Access specifier for declarations inside class/struct/unions, empty for
   /// others.
   std::string AccessSpecifier;

diff  --git a/clang-tools-extra/clangd/unittests/HoverTests.cpp 
b/clang-tools-extra/clangd/unittests/HoverTests.cpp
index 54a27b748351..457cc55dd19a 100644
--- a/clang-tools-extra/clangd/unittests/HoverTests.cpp
+++ b/clang-tools-extra/clangd/unittests/HoverTests.cpp
@@ -2760,6 +2760,15 @@ Passed by const reference as arg_a (converted to int)
 
 // In test::Bar
 int foo = 3)",
+  },
+  {
+  [](HoverInfo ) {
+HI.Name = "stdio.h";
+HI.Definition = "/usr/include/stdio.h";
+  },
+  R"(stdio.h
+
+/usr/include/stdio.h)",
   }};
 
   for (const auto  : Cases) {



___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D108003: [Clang] Extend -Wbool-operation to warn for bitwise and of bools with side effects

2021-08-12 Thread Dávid Bolvanský via Phabricator via cfe-commits
xbolva00 added a comment.

Open questions:
1, warn for pattern boolA & boolB always? I think that we will have some false 
positives.
2, restrict this warning even more? RHS must be a call?
3, something similar for bitwise or?

@hans @nickdesaulniers maybe you want to try this new warning on Chrome/Linux 
kernel?


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D108003/new/

https://reviews.llvm.org/D108003

___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D108003: [Clang] Extend -Wbool-operation to warn for bitwise and of bools with side effects

2021-08-12 Thread Dávid Bolvanský via Phabricator via cfe-commits
xbolva00 created this revision.
xbolva00 added reviewers: hans, nickdesaulniers, aaron.ballman, rsmith.
xbolva00 requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

Motivation: 
https://arstechnica.com/gadgets/2021/07/google-pushed-a-one-character-typo-to-production-bricking-chrome-os-devices/

Warn for pattern boolA & boolB where boolB has possible side effects.

Fixes https://bugs.llvm.org/show_bug.cgi?id=51216


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D108003

Files:
  clang/include/clang/Basic/DiagnosticGroups.td
  clang/include/clang/Basic/DiagnosticSemaKinds.td
  clang/lib/Sema/SemaChecking.cpp
  clang/test/Sema/warn-bitwise-and-bool.c


Index: clang/test/Sema/warn-bitwise-and-bool.c
===
--- /dev/null
+++ clang/test/Sema/warn-bitwise-and-bool.c
@@ -0,0 +1,38 @@
+// RUN: %clang_cc1 -x c -fsyntax-only -verify -Wbool-operation %s
+// RUN: %clang_cc1 -x c -fsyntax-only -verify %s
+// RUN: %clang_cc1 -x c -fsyntax-only -fdiagnostics-parseable-fixits %s 2>&1 | 
FileCheck %s
+// RUN: %clang_cc1 -x c++ -fsyntax-only -verify -Wbool-operation %s
+// RUN: %clang_cc1 -x c++ -fsyntax-only -verify %s
+// RUN: %clang_cc1 -x c++ -fsyntax-only -fdiagnostics-parseable-fixits %s 2>&1 
| FileCheck %s
+
+#ifdef __cplusplus
+typedef bool boolean;
+#else
+typedef _Bool boolean;
+#endif
+
+boolean foo(void);
+boolean bar(void);
+boolean baz(void) __attribute__((const));
+
+#define FOO foo();
+
+void test(boolean a, boolean b, int i) {
+  b = a & b;
+  b = a & foo();  // expected-warning {{bitwise and of a boolean 
expression; did you mean logical and?}}
+  // CHECK: 
fix-it:"{{.*}}":{[[@LINE-1]]:9-[[@LINE-1]]:10}:"&&"
+  b = foo() & bar();  // expected-warning {{bitwise and of a boolean 
expression; did you mean logical and?}}
+  // CHECK: 
fix-it:"{{.*}}":{[[@LINE-1]]:13-[[@LINE-1]]:14}:"&&"
+  b = foo() & !bar(); // expected-warning {{bitwise and of a boolean 
expression; did you mean logical and?}}
+  // CHECK: 
fix-it:"{{.*}}":{[[@LINE-1]]:13-[[@LINE-1]]:14}:"&&"
+  b = a & baz();
+  b = a & FOO;// expected-warning {{bitwise and of a boolean expression; 
did you mean logical and?}}
+  // CHECK: fix-it:"{{.*}}":{[[@LINE-1]]:9-[[@LINE-1]]:10}:"&&"
+  i = !b & foo(); // expected-warning {{bitwise and of a boolean expression; 
did you mean logical and?}}
+  // CHECK: 
fix-it:"{{.*}}":{[[@LINE-1]]:10-[[@LINE-1]]:11}:"&&"
+  b = bar() & (i > 4);
+  b = (i == 7) & foo(); // expected-warning {{bitwise and of a boolean 
expression; did you mean logical and?}}
+#ifdef __cplusplus
+  b = a and foo();
+#endif
+}
Index: clang/lib/Sema/SemaChecking.cpp
===
--- clang/lib/Sema/SemaChecking.cpp
+++ clang/lib/Sema/SemaChecking.cpp
@@ -13073,6 +13073,15 @@
   << OrigE->getSourceRange() << T->isBooleanType()
   << FixItHint::CreateReplacement(UO->getBeginLoc(), "!");
 
+  if (const auto *BO = dyn_cast(SourceExpr))
+if (BO->getOpcode() == BO_And &&
+BO->getLHS()->isKnownToHaveBooleanValue() &&
+BO->getRHS()->isKnownToHaveBooleanValue() &&
+BO->getRHS()->HasSideEffects(S.Context))
+  S.Diag(BO->getBeginLoc(), diag::warn_bitwise_and_bool)
+  << OrigE->getSourceRange()
+  << FixItHint::CreateReplacement(BO->getOperatorLoc(), "&&");
+
   // For conditional operators, we analyze the arguments as if they
   // were being fed directly into the output.
   if (auto *CO = dyn_cast(SourceExpr)) {
Index: clang/include/clang/Basic/DiagnosticSemaKinds.td
===
--- clang/include/clang/Basic/DiagnosticSemaKinds.td
+++ clang/include/clang/Basic/DiagnosticSemaKinds.td
@@ -7424,7 +7424,10 @@
 def warn_bitwise_negation_bool : Warning<
   "bitwise negation of a boolean expression%select{;| always evaluates to 
'true';}0 "
   "did you mean logical negation?">,
-  InGroup>;
+  InGroup;
+def warn_bitwise_and_bool : Warning<
+  "bitwise and of a boolean expression; did you mean logical and?">,
+  InGroup;
 def err_decrement_bool : Error<"cannot decrement expression of type bool">;
 def warn_increment_bool : Warning<
   "incrementing expression of type bool is deprecated and "
Index: clang/include/clang/Basic/DiagnosticGroups.td
===
--- clang/include/clang/Basic/DiagnosticGroups.td
+++ clang/include/clang/Basic/DiagnosticGroups.td
@@ -64,6 +64,10 @@
 def SignConversion : DiagGroup<"sign-conversion">;
 def PointerBoolConversion : DiagGroup<"pointer-bool-conversion">;
 def UndefinedBoolConversion : DiagGroup<"undefined-bool-conversion">;
+def BoolOperationNegation : DiagGroup<"bool-operation-negation">;
+def BoolOperationAnd : DiagGroup<"bool-operation-and">;
+def BoolOperation : 

[clang-tools-extra] ece4e92 - [CodeComplete] Basic code completion for attribute names.

2021-08-12 Thread Sam McCall via cfe-commits

Author: Sam McCall
Date: 2021-08-12T23:49:10+02:00
New Revision: ece4e920852185b332c2f7ba027e0c4a2972855a

URL: 
https://github.com/llvm/llvm-project/commit/ece4e920852185b332c2f7ba027e0c4a2972855a
DIFF: 
https://github.com/llvm/llvm-project/commit/ece4e920852185b332c2f7ba027e0c4a2972855a.diff

LOG: [CodeComplete] Basic code completion for attribute names.

Only the bare name is completed, with no args.
For args to be useful we need arg names. These *are* in the tablegen but
not currently emitted in usable form, so left this as future work.

C++11, C2x, GNU, declspec, MS syntax is supported, with the appropriate
spellings of attributes suggested.
`#pragma clang attribute` is supported but not terribly useful as we
only reach completion if parens are balanced (i.e. the line is not truncated)

There's no filtering of which attributes might make sense in this
grammatical context (e.g. attached to a function). In code-completion context
this is hard to do, and will only work in few cases :-(

There's also no filtering by langopts: this is because currently the
only way of checking is to try to produce diagnostics, which requires a
valid ParsedAttr which is hard to get.
This should be fairly simple to fix but requires some tablegen changes
to expose the logic without the side-effect.

Differential Revision: https://reviews.llvm.org/D107696

Added: 
clang/test/CodeCompletion/attr.cpp

Modified: 
clang-tools-extra/clangd/CodeComplete.cpp
clang/include/clang/Parse/Parser.h
clang/include/clang/Sema/CodeCompleteConsumer.h
clang/include/clang/Sema/ParsedAttr.h
clang/include/clang/Sema/Sema.h
clang/lib/Frontend/ASTUnit.cpp
clang/lib/Parse/ParseDecl.cpp
clang/lib/Parse/ParseDeclCXX.cpp
clang/lib/Parse/ParsePragma.cpp
clang/lib/Sema/CodeCompleteConsumer.cpp
clang/lib/Sema/ParsedAttr.cpp
clang/lib/Sema/SemaCodeComplete.cpp
clang/tools/libclang/CIndexCodeCompletion.cpp

Removed: 




diff  --git a/clang-tools-extra/clangd/CodeComplete.cpp 
b/clang-tools-extra/clangd/CodeComplete.cpp
index 588161e651335..593426127aa27 100644
--- a/clang-tools-extra/clangd/CodeComplete.cpp
+++ b/clang-tools-extra/clangd/CodeComplete.cpp
@@ -715,6 +715,7 @@ bool contextAllowsIndex(enum CodeCompletionContext::Kind K) 
{
   case CodeCompletionContext::CCC_ObjCInstanceMessage:
   case CodeCompletionContext::CCC_ObjCClassMessage:
   case CodeCompletionContext::CCC_IncludedFile:
+  case CodeCompletionContext::CCC_Attribute:
   // FIXME: Provide identifier based completions for the following contexts:
   case CodeCompletionContext::CCC_Other: // Be conservative.
   case CodeCompletionContext::CCC_NaturalLanguage:

diff  --git a/clang/include/clang/Parse/Parser.h 
b/clang/include/clang/Parse/Parser.h
index 8eb3f9029d9d8..f42e59ab6ddfd 100644
--- a/clang/include/clang/Parse/Parser.h
+++ b/clang/include/clang/Parse/Parser.h
@@ -2834,7 +2834,10 @@ class Parser : public CodeCompletionHandler {
SourceLocation ScopeLoc,
CachedTokens );
 
-  IdentifierInfo *TryParseCXX11AttributeIdentifier(SourceLocation );
+  IdentifierInfo *TryParseCXX11AttributeIdentifier(
+  SourceLocation ,
+  Sema::AttributeCompletion Completion = Sema::AttributeCompletion::None,
+  const IdentifierInfo *EnclosingScope = nullptr);
 
   void MaybeParseMicrosoftAttributes(ParsedAttributes ,
  SourceLocation *endLoc = nullptr) {

diff  --git a/clang/include/clang/Sema/CodeCompleteConsumer.h 
b/clang/include/clang/Sema/CodeCompleteConsumer.h
index 87646ab950257..6b37e3c50dba7 100644
--- a/clang/include/clang/Sema/CodeCompleteConsumer.h
+++ b/clang/include/clang/Sema/CodeCompleteConsumer.h
@@ -329,6 +329,9 @@ class CodeCompletionContext {
 /// Code completion inside the filename part of a #include directive.
 CCC_IncludedFile,
 
+/// Code completion of an attribute name.
+CCC_Attribute,
+
 /// An unknown context, in which we are recovering from a parsing
 /// error and don't know which completions we should give.
 CCC_Recovery

diff  --git a/clang/include/clang/Sema/ParsedAttr.h 
b/clang/include/clang/Sema/ParsedAttr.h
index e3b910060231d..61a36ddcc1dbd 100644
--- a/clang/include/clang/Sema/ParsedAttr.h
+++ b/clang/include/clang/Sema/ParsedAttr.h
@@ -123,6 +123,7 @@ struct ParsedAttrInfo {
   }
 
   static const ParsedAttrInfo (const AttributeCommonInfo );
+  static ArrayRef getAllBuiltin();
 };
 
 typedef llvm::Registry ParsedAttrInfoRegistry;

diff  --git a/clang/include/clang/Sema/Sema.h b/clang/include/clang/Sema/Sema.h
index 441c928ac4f20..bcd05a3e027c8 100644
--- a/clang/include/clang/Sema/Sema.h
+++ b/clang/include/clang/Sema/Sema.h
@@ -12377,6 +12377,15 @@ class Sema final {
   const VirtSpecifiers *VS = nullptr);
   void CodeCompleteBracketDeclarator(Scope *S);
   

[PATCH] D107696: [CodeComplete] Basic code completion for attribute names.

2021-08-12 Thread Sam McCall via Phabricator via cfe-commits
This revision was landed with ongoing or failed builds.
This revision was automatically updated to reflect the committed changes.
Closed by commit rGece4e9208521: [CodeComplete] Basic code completion for 
attribute names. (authored by sammccall).

Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D107696/new/

https://reviews.llvm.org/D107696

Files:
  clang-tools-extra/clangd/CodeComplete.cpp
  clang/include/clang/Parse/Parser.h
  clang/include/clang/Sema/CodeCompleteConsumer.h
  clang/include/clang/Sema/ParsedAttr.h
  clang/include/clang/Sema/Sema.h
  clang/lib/Frontend/ASTUnit.cpp
  clang/lib/Parse/ParseDecl.cpp
  clang/lib/Parse/ParseDeclCXX.cpp
  clang/lib/Parse/ParsePragma.cpp
  clang/lib/Sema/CodeCompleteConsumer.cpp
  clang/lib/Sema/ParsedAttr.cpp
  clang/lib/Sema/SemaCodeComplete.cpp
  clang/test/CodeCompletion/attr.cpp
  clang/tools/libclang/CIndexCodeCompletion.cpp

Index: clang/tools/libclang/CIndexCodeCompletion.cpp
===
--- clang/tools/libclang/CIndexCodeCompletion.cpp
+++ clang/tools/libclang/CIndexCodeCompletion.cpp
@@ -541,6 +541,7 @@
 case CodeCompletionContext::CCC_MacroName:
 case CodeCompletionContext::CCC_PreprocessorExpression:
 case CodeCompletionContext::CCC_PreprocessorDirective:
+case CodeCompletionContext::CCC_Attribute:
 case CodeCompletionContext::CCC_TypeQualifiers: {
   //Only Clang results should be accepted, so we'll set all of the other
   //context bits to 0 (i.e. the empty set)
Index: clang/test/CodeCompletion/attr.cpp
===
--- /dev/null
+++ clang/test/CodeCompletion/attr.cpp
@@ -0,0 +1,88 @@
+int a [[gnu::used]];
+// RUN: %clang_cc1 -code-completion-at=%s:1:9 %s | FileCheck --check-prefix=STD %s
+// STD: COMPLETION: __carries_dependency__
+// STD-NOT: COMPLETION: __convergent__
+// STD: COMPLETION: __gnu__::__used__
+// STD-NOT: COMPLETION: __gnu__::used
+// STD-NOT: COMPLETION: __used__
+// STD: COMPLETION: _Clang::__convergent__
+// STD: COMPLETION: carries_dependency
+// STD: COMPLETION: clang::convergent
+// STD-NOT: COMPLETION: convergent
+// STD-NOT: COMPLETION: gnu::__used__
+// STD: COMPLETION: gnu::used
+// STD-NOT: COMPLETION: used
+// RUN: %clang_cc1 -code-completion-at=%s:1:14 %s | FileCheck --check-prefix=STD-NS %s
+// STD-NS-NOT: COMPLETION: __used__
+// STD-NS-NOT: COMPLETION: carries_dependency
+// STD-NS-NOT: COMPLETION: clang::convergent
+// STD-NS-NOT: COMPLETION: convergent
+// STD-NS-NOT: COMPLETION: gnu::used
+// STD-NS: COMPLETION: used
+int b [[__gnu__::used]];
+// RUN: %clang_cc1 -code-completion-at=%s:22:18 %s | FileCheck --check-prefix=STD-NSU %s
+// STD-NSU: COMPLETION: __used__
+// STD-NSU-NOT: COMPLETION: used
+
+int c [[using gnu: used]];
+// RUN: %clang_cc1 -code-completion-at=%s:27:15 %s | FileCheck --check-prefix=STD-USING %s
+// STD-USING: COMPLETION: __gnu__
+// STD-USING: COMPLETION: _Clang
+// STD-USING-NOT: COMPLETION: carries_dependency
+// STD-USING: COMPLETION: clang
+// STD-USING-NOT: COMPLETION: clang::
+// STD-USING-NOT: COMPLETION: gnu::
+// STD-USING: COMPLETION: gnu
+// RUN: %clang_cc1 -code-completion-at=%s:27:20 %s | FileCheck --check-prefix=STD-NS %s
+
+int d __attribute__((used));
+// RUN: %clang_cc1 -code-completion-at=%s:38:22 %s | FileCheck --check-prefix=GNU %s
+// GNU: COMPLETION: __carries_dependency__
+// GNU: COMPLETION: __convergent__
+// GNU-NOT: COMPLETION: __gnu__::__used__
+// GNU: COMPLETION: __used__
+// GNU-NOT: COMPLETION: _Clang::__convergent__
+// GNU: COMPLETION: carries_dependency
+// GNU-NOT: COMPLETION: clang::convergent
+// GNU: COMPLETION: convergent
+// GNU-NOT: COMPLETION: gnu::used
+// GNU: COMPLETION: used
+
+#pragma clang attribute push (__attribute__((internal_linkage)), apply_to=variable)
+int e;
+#pragma clang attribute pop
+// RUN: %clang_cc1 -code-completion-at=%s:51:46 %s | FileCheck --check-prefix=PRAGMA %s
+// PRAGMA: internal_linkage
+
+#ifdef MS_EXT
+int __declspec(thread) f;
+// RUN: %clang_cc1 -fms-extensions -DMS_EXT -code-completion-at=%s:58:16 %s | FileCheck --check-prefix=DS %s
+// DS-NOT: COMPLETION: __convergent__
+// DS-NOT: COMPLETION: __used__
+// DS-NOT: COMPLETION: clang::convergent
+// DS-NOT: COMPLETION: convergent
+// DS: COMPLETION: thread
+// DS-NOT: COMPLETION: used
+// DS: COMPLETION: uuid
+
+[uuid("123e4567-e89b-12d3-a456-426614174000")] struct g;
+// RUN: %clang_cc1 -fms-extensions -DMS_EXT -code-completion-at=%s:68:2 %s | FileCheck --check-prefix=MS %s
+// MS-NOT: COMPLETION: __uuid__
+// MS-NOT: COMPLETION: clang::convergent
+// MS-NOT: COMPLETION: convergent
+// MS-NOT: COMPLETION: thread
+// MS-NOT: COMPLETION: used
+// MS: COMPLETION: uuid
+#endif // MS_EXT
+
+void foo() {
+  [[omp::sequence(directive(parallel), directive(critical))]]
+  {}
+}
+// FIXME: support for omp 

[PATCH] D106509: [OpenMP][OpenACC] Implement `ompx_hold` map type modifier extension in Clang (1/2)

2021-08-12 Thread Joel E. Denny via Phabricator via cfe-commits
jdenny added inline comments.



Comment at: clang/include/clang/Driver/Options.td:2383
+defm openmp_extensions: BoolFOption<"openmp-extensions",
+  LangOpts<"OpenMPExtensions">, DefaultFalse,
+  PosFlag jdenny wrote:
> > ABataev wrote:
> > > Why do you want to disable it by default?
> > I thought that's what we agreed upon.
> > 
> > I'm personally happy if, in general, all features are enabled by default 
> > and users opt out by requesting strict conformance, but Clang doesn't do 
> > that today even for features from newer OpenMP standards.  Should it do so 
> > for extensions, which appear in no standard?
> > 
> > What would you prefer?
> I would enable it by default, as it may help users in some cases unless there 
> are no other strong opinions.
Well, that promotes my extensions, so I've made that change.


CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D106509/new/

https://reviews.llvm.org/D106509

___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D107836: [Attributes]: refactor to expose ParsedAttrInfo::acceptsLangOpts. NFC

2021-08-12 Thread Sam McCall via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG3b99acbff250: [Attributes]: refactor to expose 
ParsedAttrInfo::acceptsLangOpts. NFC (authored by sammccall).

Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D107836/new/

https://reviews.llvm.org/D107836

Files:
  clang/docs/ReleaseNotes.rst
  clang/include/clang/Sema/ParsedAttr.h
  clang/lib/Sema/ParsedAttr.cpp
  clang/utils/TableGen/ClangAttrEmitter.cpp


Index: clang/utils/TableGen/ClangAttrEmitter.cpp
===
--- clang/utils/TableGen/ClangAttrEmitter.cpp
+++ clang/utils/TableGen/ClangAttrEmitter.cpp
@@ -3803,14 +3803,8 @@
   if (LangOpts.empty())
 return;
 
-  OS << "bool diagLangOpts(Sema , const ParsedAttr ) ";
-  OS << "const override {\n";
-  OS << "  auto  = S.LangOpts;\n";
-  OS << "  if (" << GenerateTestExpression(LangOpts) << ")\n";
-  OS << "return true;\n\n";
-  OS << "  S.Diag(Attr.getLoc(), diag::warn_attribute_ignored) ";
-  OS << "<< Attr;\n";
-  OS << "  return false;\n";
+  OS << "bool acceptsLangOpts(const LangOptions ) const override {\n";
+  OS << "  return " << GenerateTestExpression(LangOpts) << ";\n";
   OS << "}\n\n";
 }
 
Index: clang/lib/Sema/ParsedAttr.cpp
===
--- clang/lib/Sema/ParsedAttr.cpp
+++ clang/lib/Sema/ParsedAttr.cpp
@@ -180,7 +180,10 @@
 }
 
 bool ParsedAttr::diagnoseLangOpts(Sema ) const {
-  return getInfo().diagLangOpts(S, *this);
+  if (getInfo().acceptsLangOpts(S.getLangOpts()))
+return true;
+  S.Diag(getLoc(), diag::warn_attribute_ignored) << *this;
+  return false;
 }
 
 bool ParsedAttr::isTargetSpecificAttr() const {
Index: clang/include/clang/Sema/ParsedAttr.h
===
--- clang/include/clang/Sema/ParsedAttr.h
+++ clang/include/clang/Sema/ParsedAttr.h
@@ -92,11 +92,9 @@
const Decl *D) const {
 return true;
   }
-  /// Check if this attribute is allowed by the language we are compiling, and
-  /// issue a diagnostic if not.
-  virtual bool diagLangOpts(Sema , const ParsedAttr ) const {
-return true;
-  }
+  /// Check if this attribute is allowed by the language we are compiling.
+  virtual bool acceptsLangOpts(const LangOptions ) const { return true; }
+
   /// Check if this attribute is allowed when compiling for the given target.
   virtual bool existsInTarget(const TargetInfo ) const {
 return true;
Index: clang/docs/ReleaseNotes.rst
===
--- clang/docs/ReleaseNotes.rst
+++ clang/docs/ReleaseNotes.rst
@@ -86,7 +86,13 @@
 Attribute Changes in Clang
 --
 
-- ...
+- Attributes loaded as clang plugins which are sensitive to LangOpts must
+  now override ``acceptsLangOpts`` instead of ``diagLangOpts``.
+  Returning false will produce a generic "attribute ignored" diagnostic, as
+  with clang's built-in attributes.
+  If plugins want to provide richer diagnostics, they can do so when the
+  attribute is handled instead, e.g. in ``handleDeclAttribute``.
+  (This was changed in order to better support attributes in code completion).
 
 Windows Support
 ---


Index: clang/utils/TableGen/ClangAttrEmitter.cpp
===
--- clang/utils/TableGen/ClangAttrEmitter.cpp
+++ clang/utils/TableGen/ClangAttrEmitter.cpp
@@ -3803,14 +3803,8 @@
   if (LangOpts.empty())
 return;
 
-  OS << "bool diagLangOpts(Sema , const ParsedAttr ) ";
-  OS << "const override {\n";
-  OS << "  auto  = S.LangOpts;\n";
-  OS << "  if (" << GenerateTestExpression(LangOpts) << ")\n";
-  OS << "return true;\n\n";
-  OS << "  S.Diag(Attr.getLoc(), diag::warn_attribute_ignored) ";
-  OS << "<< Attr;\n";
-  OS << "  return false;\n";
+  OS << "bool acceptsLangOpts(const LangOptions ) const override {\n";
+  OS << "  return " << GenerateTestExpression(LangOpts) << ";\n";
   OS << "}\n\n";
 }
 
Index: clang/lib/Sema/ParsedAttr.cpp
===
--- clang/lib/Sema/ParsedAttr.cpp
+++ clang/lib/Sema/ParsedAttr.cpp
@@ -180,7 +180,10 @@
 }
 
 bool ParsedAttr::diagnoseLangOpts(Sema ) const {
-  return getInfo().diagLangOpts(S, *this);
+  if (getInfo().acceptsLangOpts(S.getLangOpts()))
+return true;
+  S.Diag(getLoc(), diag::warn_attribute_ignored) << *this;
+  return false;
 }
 
 bool ParsedAttr::isTargetSpecificAttr() const {
Index: clang/include/clang/Sema/ParsedAttr.h
===
--- clang/include/clang/Sema/ParsedAttr.h
+++ clang/include/clang/Sema/ParsedAttr.h
@@ -92,11 +92,9 @@
const Decl *D) const {
 return true;
   }
-  /// Check if this attribute is allowed by the language we are compiling, and
-  /// issue a 

[clang] 3b99acb - [Attributes]: refactor to expose ParsedAttrInfo::acceptsLangOpts. NFC

2021-08-12 Thread Sam McCall via cfe-commits

Author: Sam McCall
Date: 2021-08-12T23:47:01+02:00
New Revision: 3b99acbff2504d9f056c6bb76974286322e60382

URL: 
https://github.com/llvm/llvm-project/commit/3b99acbff2504d9f056c6bb76974286322e60382
DIFF: 
https://github.com/llvm/llvm-project/commit/3b99acbff2504d9f056c6bb76974286322e60382.diff

LOG: [Attributes]: refactor to expose ParsedAttrInfo::acceptsLangOpts. NFC

We will use this function to filter code completion of attributes.

Differential Revision: https://reviews.llvm.org/D107836

Added: 


Modified: 
clang/docs/ReleaseNotes.rst
clang/include/clang/Sema/ParsedAttr.h
clang/lib/Sema/ParsedAttr.cpp
clang/utils/TableGen/ClangAttrEmitter.cpp

Removed: 




diff  --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index d20c08dbffa53..7604df7482c76 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -86,7 +86,13 @@ New Pragmas in Clang
 Attribute Changes in Clang
 --
 
-- ...
+- Attributes loaded as clang plugins which are sensitive to LangOpts must
+  now override ``acceptsLangOpts`` instead of ``diagLangOpts``.
+  Returning false will produce a generic "attribute ignored" diagnostic, as
+  with clang's built-in attributes.
+  If plugins want to provide richer diagnostics, they can do so when the
+  attribute is handled instead, e.g. in ``handleDeclAttribute``.
+  (This was changed in order to better support attributes in code completion).
 
 Windows Support
 ---

diff  --git a/clang/include/clang/Sema/ParsedAttr.h 
b/clang/include/clang/Sema/ParsedAttr.h
index f47f557adeb10..e3b910060231d 100644
--- a/clang/include/clang/Sema/ParsedAttr.h
+++ b/clang/include/clang/Sema/ParsedAttr.h
@@ -92,11 +92,9 @@ struct ParsedAttrInfo {
const Decl *D) const {
 return true;
   }
-  /// Check if this attribute is allowed by the language we are compiling, and
-  /// issue a diagnostic if not.
-  virtual bool diagLangOpts(Sema , const ParsedAttr ) const {
-return true;
-  }
+  /// Check if this attribute is allowed by the language we are compiling.
+  virtual bool acceptsLangOpts(const LangOptions ) const { return true; }
+
   /// Check if this attribute is allowed when compiling for the given target.
   virtual bool existsInTarget(const TargetInfo ) const {
 return true;

diff  --git a/clang/lib/Sema/ParsedAttr.cpp b/clang/lib/Sema/ParsedAttr.cpp
index ed03b0c7f688b..cba49d7116b02 100644
--- a/clang/lib/Sema/ParsedAttr.cpp
+++ b/clang/lib/Sema/ParsedAttr.cpp
@@ -180,7 +180,10 @@ void ParsedAttr::getMatchRules(
 }
 
 bool ParsedAttr::diagnoseLangOpts(Sema ) const {
-  return getInfo().diagLangOpts(S, *this);
+  if (getInfo().acceptsLangOpts(S.getLangOpts()))
+return true;
+  S.Diag(getLoc(), diag::warn_attribute_ignored) << *this;
+  return false;
 }
 
 bool ParsedAttr::isTargetSpecificAttr() const {

diff  --git a/clang/utils/TableGen/ClangAttrEmitter.cpp 
b/clang/utils/TableGen/ClangAttrEmitter.cpp
index 5fc2d50f65fa8..345b13692b5ca 100644
--- a/clang/utils/TableGen/ClangAttrEmitter.cpp
+++ b/clang/utils/TableGen/ClangAttrEmitter.cpp
@@ -3803,14 +3803,8 @@ static void GenerateLangOptRequirements(const Record ,
   if (LangOpts.empty())
 return;
 
-  OS << "bool diagLangOpts(Sema , const ParsedAttr ) ";
-  OS << "const override {\n";
-  OS << "  auto  = S.LangOpts;\n";
-  OS << "  if (" << GenerateTestExpression(LangOpts) << ")\n";
-  OS << "return true;\n\n";
-  OS << "  S.Diag(Attr.getLoc(), diag::warn_attribute_ignored) ";
-  OS << "<< Attr;\n";
-  OS << "  return false;\n";
+  OS << "bool acceptsLangOpts(const LangOptions ) const override {\n";
+  OS << "  return " << GenerateTestExpression(LangOpts) << ";\n";
   OS << "}\n\n";
 }
 



___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D97803: [clangd] Overload bundles are only deprecated if each overloads is.

2021-08-12 Thread Sam McCall via Phabricator via cfe-commits
This revision was landed with ongoing or failed builds.
This revision was automatically updated to reflect the committed changes.
Closed by commit rG08c04ca00542: [clangd] Overload bundles are only deprecated 
if each overloads is. (authored by sammccall).

Changed prior to commit:
  https://reviews.llvm.org/D97803?vs=327574=366116#toc

Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D97803/new/

https://reviews.llvm.org/D97803

Files:
  clang-tools-extra/clangd/CodeComplete.cpp
  clang-tools-extra/clangd/unittests/CodeCompleteTests.cpp


Index: clang-tools-extra/clangd/unittests/CodeCompleteTests.cpp
===
--- clang-tools-extra/clangd/unittests/CodeCompleteTests.cpp
+++ clang-tools-extra/clangd/unittests/CodeCompleteTests.cpp
@@ -1657,7 +1657,7 @@
   std::string Context = R"cpp(
 struct X {
   // Overload with int
-  int a(int);
+  int a(int) __attribute__((deprecated("", "")));
   // Overload with bool
   int a(bool);
   int b(float);
@@ -1695,6 +1695,7 @@
   EXPECT_EQ(A.ReturnType, "int"); // All overloads return int.
   // For now we just return one of the doc strings arbitrarily.
   ASSERT_TRUE(A.Documentation);
+  ASSERT_FALSE(A.Deprecated); // Not all overloads deprecated.
   EXPECT_THAT(
   A.Documentation->asPlainText(),
   AnyOf(HasSubstr("Overload with int"), HasSubstr("Overload with bool")));
Index: clang-tools-extra/clangd/CodeComplete.cpp
===
--- clang-tools-extra/clangd/CodeComplete.cpp
+++ clang-tools-extra/clangd/CodeComplete.cpp
@@ -282,6 +282,7 @@
   : ASTCtx(ASTCtx),
 EnableFunctionArgSnippets(Opts.EnableFunctionArgSnippets),
 IsUsingDeclaration(IsUsingDeclaration), NextTokenKind(NextTokenKind) {
+Completion.Deprecated = true; // cleared by any non-deprecated overload.
 add(C, SemaCCS);
 if (C.SemaResult) {
   assert(ASTCtx);
@@ -310,8 +311,6 @@
 return std::tie(X.range.start.line, X.range.start.character) <
std::tie(Y.range.start.line, Y.range.start.character);
   });
-  Completion.Deprecated |=
-  (C.SemaResult->Availability == CXAvailability_Deprecated);
 }
 if (C.IndexResult) {
   Completion.Origin |= C.IndexResult->Origin;
@@ -333,7 +332,6 @@
 }
 Completion.RequiredQualifier = std::string(ShortestQualifier);
   }
-  Completion.Deprecated |= (C.IndexResult->Flags & Symbol::Deprecated);
 }
 if (C.IdentifierResult) {
   Completion.Origin |= SymbolOrigin::Identifier;
@@ -409,6 +407,14 @@
  /*CommentsFromHeader=*/false));
   }
 }
+if (Completion.Deprecated) {
+  if (C.SemaResult)
+Completion.Deprecated &=
+C.SemaResult->Availability == CXAvailability_Deprecated;
+  if (C.IndexResult)
+Completion.Deprecated &=
+bool(C.IndexResult->Flags & Symbol::Deprecated);
+}
   }
 
   CodeCompletion build() {


Index: clang-tools-extra/clangd/unittests/CodeCompleteTests.cpp
===
--- clang-tools-extra/clangd/unittests/CodeCompleteTests.cpp
+++ clang-tools-extra/clangd/unittests/CodeCompleteTests.cpp
@@ -1657,7 +1657,7 @@
   std::string Context = R"cpp(
 struct X {
   // Overload with int
-  int a(int);
+  int a(int) __attribute__((deprecated("", "")));
   // Overload with bool
   int a(bool);
   int b(float);
@@ -1695,6 +1695,7 @@
   EXPECT_EQ(A.ReturnType, "int"); // All overloads return int.
   // For now we just return one of the doc strings arbitrarily.
   ASSERT_TRUE(A.Documentation);
+  ASSERT_FALSE(A.Deprecated); // Not all overloads deprecated.
   EXPECT_THAT(
   A.Documentation->asPlainText(),
   AnyOf(HasSubstr("Overload with int"), HasSubstr("Overload with bool")));
Index: clang-tools-extra/clangd/CodeComplete.cpp
===
--- clang-tools-extra/clangd/CodeComplete.cpp
+++ clang-tools-extra/clangd/CodeComplete.cpp
@@ -282,6 +282,7 @@
   : ASTCtx(ASTCtx),
 EnableFunctionArgSnippets(Opts.EnableFunctionArgSnippets),
 IsUsingDeclaration(IsUsingDeclaration), NextTokenKind(NextTokenKind) {
+Completion.Deprecated = true; // cleared by any non-deprecated overload.
 add(C, SemaCCS);
 if (C.SemaResult) {
   assert(ASTCtx);
@@ -310,8 +311,6 @@
 return std::tie(X.range.start.line, X.range.start.character) <
std::tie(Y.range.start.line, Y.range.start.character);
   });
-  Completion.Deprecated |=
-  (C.SemaResult->Availability == CXAvailability_Deprecated);
 }
 if (C.IndexResult) {
   Completion.Origin |= C.IndexResult->Origin;
@@ -333,7 +332,6 @@
 }
 Completion.RequiredQualifier = std::string(ShortestQualifier);
   }
-  

[clang-tools-extra] 08c04ca - [clangd] Overload bundles are only deprecated if each overloads is.

2021-08-12 Thread Sam McCall via cfe-commits

Author: Sam McCall
Date: 2021-08-12T23:46:08+02:00
New Revision: 08c04ca00542bc2605e7c5d723f8cf478f012f61

URL: 
https://github.com/llvm/llvm-project/commit/08c04ca00542bc2605e7c5d723f8cf478f012f61
DIFF: 
https://github.com/llvm/llvm-project/commit/08c04ca00542bc2605e7c5d723f8cf478f012f61.diff

LOG: [clangd] Overload bundles are only deprecated if each overloads is.

Fixes https://github.com/clangd/clangd/issues/705

Differential Revision: https://reviews.llvm.org/D97803

Added: 


Modified: 
clang-tools-extra/clangd/CodeComplete.cpp
clang-tools-extra/clangd/unittests/CodeCompleteTests.cpp

Removed: 




diff  --git a/clang-tools-extra/clangd/CodeComplete.cpp 
b/clang-tools-extra/clangd/CodeComplete.cpp
index b36cfd4ba00c..588161e65133 100644
--- a/clang-tools-extra/clangd/CodeComplete.cpp
+++ b/clang-tools-extra/clangd/CodeComplete.cpp
@@ -282,6 +282,7 @@ struct CodeCompletionBuilder {
   : ASTCtx(ASTCtx),
 EnableFunctionArgSnippets(Opts.EnableFunctionArgSnippets),
 IsUsingDeclaration(IsUsingDeclaration), NextTokenKind(NextTokenKind) {
+Completion.Deprecated = true; // cleared by any non-deprecated overload.
 add(C, SemaCCS);
 if (C.SemaResult) {
   assert(ASTCtx);
@@ -310,8 +311,6 @@ struct CodeCompletionBuilder {
 return std::tie(X.range.start.line, X.range.start.character) <
std::tie(Y.range.start.line, Y.range.start.character);
   });
-  Completion.Deprecated |=
-  (C.SemaResult->Availability == CXAvailability_Deprecated);
 }
 if (C.IndexResult) {
   Completion.Origin |= C.IndexResult->Origin;
@@ -333,7 +332,6 @@ struct CodeCompletionBuilder {
 }
 Completion.RequiredQualifier = std::string(ShortestQualifier);
   }
-  Completion.Deprecated |= (C.IndexResult->Flags & Symbol::Deprecated);
 }
 if (C.IdentifierResult) {
   Completion.Origin |= SymbolOrigin::Identifier;
@@ -409,6 +407,14 @@ struct CodeCompletionBuilder {
  /*CommentsFromHeader=*/false));
   }
 }
+if (Completion.Deprecated) {
+  if (C.SemaResult)
+Completion.Deprecated &=
+C.SemaResult->Availability == CXAvailability_Deprecated;
+  if (C.IndexResult)
+Completion.Deprecated &=
+bool(C.IndexResult->Flags & Symbol::Deprecated);
+}
   }
 
   CodeCompletion build() {

diff  --git a/clang-tools-extra/clangd/unittests/CodeCompleteTests.cpp 
b/clang-tools-extra/clangd/unittests/CodeCompleteTests.cpp
index cfa2def7a615..3170099b437b 100644
--- a/clang-tools-extra/clangd/unittests/CodeCompleteTests.cpp
+++ b/clang-tools-extra/clangd/unittests/CodeCompleteTests.cpp
@@ -1657,7 +1657,7 @@ TEST(CompletionTest, OverloadBundling) {
   std::string Context = R"cpp(
 struct X {
   // Overload with int
-  int a(int);
+  int a(int) __attribute__((deprecated("", "")));
   // Overload with bool
   int a(bool);
   int b(float);
@@ -1695,6 +1695,7 @@ TEST(CompletionTest, OverloadBundling) {
   EXPECT_EQ(A.ReturnType, "int"); // All overloads return int.
   // For now we just return one of the doc strings arbitrarily.
   ASSERT_TRUE(A.Documentation);
+  ASSERT_FALSE(A.Deprecated); // Not all overloads deprecated.
   EXPECT_THAT(
   A.Documentation->asPlainText(),
   AnyOf(HasSubstr("Overload with int"), HasSubstr("Overload with bool")));



___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D107002: [PowerPC] Implement XL compatibility builtin __addex

2021-08-12 Thread Lei Huang via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG8930af45c35b: [PowerPC] Implement XL compatibility builtin 
__addex (authored by lei).

Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D107002/new/

https://reviews.llvm.org/D107002

Files:
  clang/include/clang/Basic/BuiltinsPPC.def
  clang/include/clang/Basic/DiagnosticSemaKinds.td
  clang/lib/Basic/Targets/PPC.cpp
  clang/lib/Sema/SemaChecking.cpp
  clang/test/CodeGen/builtins-ppc-xlcompat-pwr9-64bit.c
  clang/test/CodeGen/builtins-ppc-xlcompat-pwr9-error.c
  clang/test/CodeGen/builtins-ppc-xlcompat-pwr9-warning.c
  llvm/include/llvm/IR/IntrinsicsPowerPC.td
  llvm/lib/Target/PowerPC/P9InstrResources.td
  llvm/lib/Target/PowerPC/PPCInstr64Bit.td
  llvm/test/CodeGen/PowerPC/builtins-ppc-xlcompat-pwr9-64bit.ll

Index: llvm/test/CodeGen/PowerPC/builtins-ppc-xlcompat-pwr9-64bit.ll
===
--- llvm/test/CodeGen/PowerPC/builtins-ppc-xlcompat-pwr9-64bit.ll
+++ llvm/test/CodeGen/PowerPC/builtins-ppc-xlcompat-pwr9-64bit.ll
@@ -29,3 +29,14 @@
   ret double %0
 }
 declare double @llvm.ppc.insert.exp(double, i64)
+
+declare i64 @llvm.ppc.addex(i64, i64, i32 immarg)
+define dso_local i64 @call_addex_0(i64 %a, i64 %b) {
+; CHECK-LABEL: call_addex_0:
+; CHECK:   # %bb.0: # %entry
+; CHECK-NEXT:addex 3, 3, 4, 0
+; CHECK-NEXT:blr
+entry:
+  %0 = tail call i64 @llvm.ppc.addex(i64 %a, i64 %b, i32 0)
+  ret i64 %0
+}
Index: llvm/lib/Target/PowerPC/PPCInstr64Bit.td
===
--- llvm/lib/Target/PowerPC/PPCInstr64Bit.td
+++ llvm/lib/Target/PowerPC/PPCInstr64Bit.td
@@ -1670,6 +1670,13 @@
  "hashchkp $RB, $D_RA_XD", IIC_IntGeneral, []>;
 }
 
+let Interpretation64Bit = 1, isCodeGenOnly = 1, hasSideEffects = 1 in
+def ADDEX8 : Z23Form_RTAB5_CY2<31, 170, (outs g8rc:$rT),
+  (ins g8rc:$rA, g8rc:$rB, u2imm:$CY),
+  "addex $rT, $rA, $rB, $CY", IIC_IntGeneral,
+  [(set i64:$rT, (int_ppc_addex i64:$rA, i64:$rB,
+timm:$CY))]>;
+
 //===--===//
 // Instruction Patterns
 //
Index: llvm/lib/Target/PowerPC/P9InstrResources.td
===
--- llvm/lib/Target/PowerPC/P9InstrResources.td
+++ llvm/lib/Target/PowerPC/P9InstrResources.td
@@ -1430,5 +1430,6 @@
   DCBI,
   DCCCI,
   ICCCI,
-  ADDEX
+  ADDEX,
+  ADDEX8
 )> { let Unsupported = 1; }
Index: llvm/include/llvm/IR/IntrinsicsPowerPC.td
===
--- llvm/include/llvm/IR/IntrinsicsPowerPC.td
+++ llvm/include/llvm/IR/IntrinsicsPowerPC.td
@@ -1706,7 +1706,10 @@
   def int_ppc_fres
   : GCCBuiltin<"__builtin_ppc_fres">,
 Intrinsic <[llvm_float_ty], [llvm_float_ty], [IntrNoMem]>;
-  
+  def int_ppc_addex
+  : GCCBuiltin<"__builtin_ppc_addex">,
+Intrinsic<[llvm_i64_ty], [llvm_i64_ty, llvm_i64_ty, llvm_i32_ty],
+  [IntrNoMem, IntrHasSideEffects, ImmArg>]>;
   def int_ppc_fsel : GCCBuiltin<"__builtin_ppc_fsel">,
  Intrinsic<[llvm_double_ty], [llvm_double_ty, llvm_double_ty, 
   llvm_double_ty], [IntrNoMem]>;
Index: clang/test/CodeGen/builtins-ppc-xlcompat-pwr9-warning.c
===
--- /dev/null
+++ clang/test/CodeGen/builtins-ppc-xlcompat-pwr9-warning.c
@@ -0,0 +1,11 @@
+// REQUIRES: powerpc-registered-target
+// RUN: %clang_cc1 -triple powerpc64-unknown-unknown -target-cpu pwr9 \
+// RUN:   -verify %s
+
+extern unsigned long long ull;
+extern long long ll;
+
+void test_builtin_ppc_addex() {
+  long long res = __builtin_ppc_addex(ll, ll, 1); // expected-warning {{argument value 1 will result in undefined behaviour}}
+  unsigned long long res2 = __builtin_ppc_addex(ull, ull, 3); // expected-warning {{argument value 3 will result in undefined behaviour}}
+}
Index: clang/test/CodeGen/builtins-ppc-xlcompat-pwr9-error.c
===
--- clang/test/CodeGen/builtins-ppc-xlcompat-pwr9-error.c
+++ clang/test/CodeGen/builtins-ppc-xlcompat-pwr9-error.c
@@ -9,7 +9,18 @@
 // RUN:   -fsyntax-only -Wall -Werror -verify %s
 
 extern unsigned int ui;
+extern unsigned long long ull;
+extern long long ll;
 
 void test_builtin_ppc_cmprb() {
   int res = __builtin_ppc_cmprb(3, ui, ui); // expected-error {{argument value 3 is outside the valid range [0, 1]}}
 }
+
+#ifdef __PPC64__
+
+void test_builtin_ppc_addex() {
+  long long res = __builtin_ppc_addex(ll, ll, 4); // expected-error {{argument value 4 is outside the valid range [0, 3]}}
+  unsigned long long res2 = __builtin_ppc_addex(ull, 

[clang] 8930af4 - [PowerPC] Implement XL compatibility builtin __addex

2021-08-12 Thread Lei Huang via cfe-commits

Author: Lei Huang
Date: 2021-08-12T16:38:21-05:00
New Revision: 8930af45c35b5224d3b90c8408957f6b7bfa1be0

URL: 
https://github.com/llvm/llvm-project/commit/8930af45c35b5224d3b90c8408957f6b7bfa1be0
DIFF: 
https://github.com/llvm/llvm-project/commit/8930af45c35b5224d3b90c8408957f6b7bfa1be0.diff

LOG: [PowerPC] Implement XL compatibility builtin __addex

Add builtin and intrinsic for `__addex`.

This patch is part of a series of patches to provide builtins for
compatibility with the XL compiler.

Reviewed By: stefanp, nemanjai, NeHuang

Differential Revision: https://reviews.llvm.org/D107002

Added: 
clang/test/CodeGen/builtins-ppc-xlcompat-pwr9-warning.c

Modified: 
clang/include/clang/Basic/BuiltinsPPC.def
clang/include/clang/Basic/DiagnosticSemaKinds.td
clang/lib/Basic/Targets/PPC.cpp
clang/lib/Sema/SemaChecking.cpp
clang/test/CodeGen/builtins-ppc-xlcompat-pwr9-64bit.c
clang/test/CodeGen/builtins-ppc-xlcompat-pwr9-error.c
llvm/include/llvm/IR/IntrinsicsPowerPC.td
llvm/lib/Target/PowerPC/P9InstrResources.td
llvm/lib/Target/PowerPC/PPCInstr64Bit.td
llvm/test/CodeGen/PowerPC/builtins-ppc-xlcompat-pwr9-64bit.ll

Removed: 




diff  --git a/clang/include/clang/Basic/BuiltinsPPC.def 
b/clang/include/clang/Basic/BuiltinsPPC.def
index dfe97af300f41..7a1795d9e550d 100644
--- a/clang/include/clang/Basic/BuiltinsPPC.def
+++ b/clang/include/clang/Basic/BuiltinsPPC.def
@@ -144,6 +144,7 @@ BUILTIN(__builtin_ppc_mfspr, "ULiIi", "")
 BUILTIN(__builtin_ppc_mtmsr, "vUi", "")
 BUILTIN(__builtin_ppc_mtspr, "vIiULi", "")
 BUILTIN(__builtin_ppc_stfiw, "viC*d", "")
+BUILTIN(__builtin_ppc_addex, "LLiLLiLLiCIi", "")
 
 BUILTIN(__builtin_ppc_get_timebase, "ULLi", "n")
 

diff  --git a/clang/include/clang/Basic/DiagnosticSemaKinds.td 
b/clang/include/clang/Basic/DiagnosticSemaKinds.td
index bf857f58951b3..73217b418e81f 100644
--- a/clang/include/clang/Basic/DiagnosticSemaKinds.td
+++ b/clang/include/clang/Basic/DiagnosticSemaKinds.td
@@ -9733,6 +9733,9 @@ def err_argument_invalid_range : Error<
 def warn_argument_invalid_range : Warning<
   "argument value %0 is outside the valid range [%1, %2]">, DefaultError,
   InGroup>;
+def warn_argument_undefined_behaviour : Warning<
+  "argument value %0 will result in undefined behaviour">,
+  InGroup>;
 def err_argument_not_multiple : Error<
   "argument should be a multiple of %0">;
 def err_argument_not_power_of_2 : Error<

diff  --git a/clang/lib/Basic/Targets/PPC.cpp b/clang/lib/Basic/Targets/PPC.cpp
index 839fb93ff3d0c..c15d2df33f9f7 100644
--- a/clang/lib/Basic/Targets/PPC.cpp
+++ b/clang/lib/Basic/Targets/PPC.cpp
@@ -236,6 +236,7 @@ static void defineXLCompatMacros(MacroBuilder ) {
   Builder.defineMacro("__frsqrtes", "__builtin_ppc_frsqrtes");
   Builder.defineMacro("__fsqrt", "__builtin_ppc_fsqrt");
   Builder.defineMacro("__fsqrts", "__builtin_ppc_fsqrts");
+  Builder.defineMacro("__addex", "__builtin_ppc_addex");
 }
 
 /// PPCTargetInfo::getTargetDefines - Return a set of the PowerPC-specific

diff  --git a/clang/lib/Sema/SemaChecking.cpp b/clang/lib/Sema/SemaChecking.cpp
index d3736311d5662..e5008330a4150 100644
--- a/clang/lib/Sema/SemaChecking.cpp
+++ b/clang/lib/Sema/SemaChecking.cpp
@@ -3294,6 +3294,7 @@ static bool isPPC_64Builtin(unsigned BuiltinID) {
   case PPC::BI__builtin_ppc_store8r:
   case PPC::BI__builtin_ppc_insert_exp:
   case PPC::BI__builtin_ppc_extract_sig:
+  case PPC::BI__builtin_ppc_addex:
 return true;
   }
   return false;
@@ -3435,6 +3436,19 @@ bool Sema::CheckPPCBuiltinFunctionCall(const TargetInfo 
, unsigned BuiltinID,
   case PPC::BI__builtin_ppc_insert_exp:
 return SemaFeatureCheck(*this, TheCall, "power9-vector",
 diag::err_ppc_builtin_only_on_arch, "9");
+  case PPC::BI__builtin_ppc_addex: {
+if (SemaFeatureCheck(*this, TheCall, "isa-v30-instructions",
+ diag::err_ppc_builtin_only_on_arch, "9") ||
+SemaBuiltinConstantArgRange(TheCall, 2, 0, 3))
+  return true;
+// Output warning for reserved values 1 to 3.
+int ArgValue =
+TheCall->getArg(2)->getIntegerConstantExpr(Context)->getSExtValue();
+if (ArgValue != 0)
+  Diag(TheCall->getBeginLoc(), diag::warn_argument_undefined_behaviour)
+  << ArgValue;
+return false;
+  }
   case PPC::BI__builtin_ppc_mtfsb0:
   case PPC::BI__builtin_ppc_mtfsb1:
 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31);

diff  --git a/clang/test/CodeGen/builtins-ppc-xlcompat-pwr9-64bit.c 
b/clang/test/CodeGen/builtins-ppc-xlcompat-pwr9-64bit.c
index 741e87194a7d4..50d5aefdd2941 100644
--- a/clang/test/CodeGen/builtins-ppc-xlcompat-pwr9-64bit.c
+++ b/clang/test/CodeGen/builtins-ppc-xlcompat-pwr9-64bit.c
@@ -80,3 +80,19 @@ double insert_exp (double d, unsigned long long ull) {
 // CHECK-NONPWR9-ERR:  error: this builtin is only valid on POWER9 or later 
CPUs
   return __insert_exp 

[PATCH] D107933: [clang] Expose unreachable fallthrough annotation warning

2021-08-12 Thread David Blaikie via Phabricator via cfe-commits
dblaikie added a comment.

Probably still worth fixing the bug too? (though maybe not a priority once it's 
moved out into -Wunreachable-code) - though the general fix, as discussed on 
the bug (comment 18 and 19 about why this doesn't already produce an 
unreachable-code warning), may require a significant amount of work.


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D107933/new/

https://reviews.llvm.org/D107933

___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D107933: [clang] Expose unreachable fallthrough annotation warning

2021-08-12 Thread Dávid Bolvanský via Phabricator via cfe-commits
xbolva00 added a comment.

Yes, something like that, plus I think you want put UnreachableCodeFallthrough 
into group UnreachableCode as well.


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D107933/new/

https://reviews.llvm.org/D107933

___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D107933: [clang] Expose unreachable fallthrough annotation warning

2021-08-12 Thread Nathan Chancellor via Phabricator via cfe-commits
nathanchance added a comment.

So something more along the lines of

  diff
  diff --git a/clang/include/clang/Basic/DiagnosticGroups.td 
b/clang/include/clang/Basic/DiagnosticGroups.td
  index 1555a9ee2465..0aa9a82e3d11 100644
  --- a/clang/include/clang/Basic/DiagnosticGroups.td
  +++ b/clang/include/clang/Basic/DiagnosticGroups.td
  @@ -823,10 +823,12 @@ def UnreachableCode : DiagGroup<"unreachable-code",
   [UnreachableCodeLoopIncrement]>;
   def UnreachableCodeBreak : DiagGroup<"unreachable-code-break">;
   def UnreachableCodeReturn : DiagGroup<"unreachable-code-return">;
  +def UnreachableCodeFallthrough : DiagGroup<"unreachable-code-fallthrough">;
   def UnreachableCodeAggressive : DiagGroup<"unreachable-code-aggressive",
   [UnreachableCode,
UnreachableCodeBreak,
  - UnreachableCodeReturn]>;
  + UnreachableCodeReturn,
  + UnreachableCodeFallthrough]>;
  
   // Aggregation warning settings.
  
  diff --git a/clang/include/clang/Basic/DiagnosticSemaKinds.td 
b/clang/include/clang/Basic/DiagnosticSemaKinds.td
  index bf857f58951b..f533076a6c77 100644
  --- a/clang/include/clang/Basic/DiagnosticSemaKinds.td
  +++ b/clang/include/clang/Basic/DiagnosticSemaKinds.td
  @@ -682,6 +682,9 @@ def warn_unreachable_return : Warning<
   def warn_unreachable_loop_increment : Warning<
 "loop will run at most once (loop increment never executed)">,
 InGroup, DefaultIgnore;
  +def warn_unreachable_fallthrough_attr : Warning<
  +  "fallthrough annotation in unreachable code">,
  +  InGroup, DefaultIgnore;
   def note_unreachable_silence : Note<
 "silence by adding parentheses to mark code as explicitly dead">;
  
  @@ -9578,9 +9581,6 @@ def err_fallthrough_attr_outside_switch : Error<
 "fallthrough annotation is outside switch statement">;
   def err_fallthrough_attr_invalid_placement : Error<
 "fallthrough annotation does not directly precede switch label">;
  -def warn_fallthrough_attr_unreachable : Warning<
  -  "fallthrough annotation in unreachable code">,
  -  InGroup, DefaultIgnore;
  
   def warn_unreachable_default : Warning<
 "default label in switch which covers all enumeration values">,
  diff --git a/clang/lib/Sema/AnalysisBasedWarnings.cpp 
b/clang/lib/Sema/AnalysisBasedWarnings.cpp
  index aa2602c8d925..99ce143d3559 100644
  --- a/clang/lib/Sema/AnalysisBasedWarnings.cpp
  +++ b/clang/lib/Sema/AnalysisBasedWarnings.cpp
  @@ -1125,7 +1125,7 @@ namespace {
   // unreachable in all instantiations of the template.
   if (!IsTemplateInstantiation)
 S.Diag(AS->getBeginLoc(),
  - diag::warn_fallthrough_attr_unreachable);
  + diag::warn_unreachable_fallthrough_attr);
   markFallthroughVisited(AS);
   ++AnnotatedCnt;
   break;

if I understand correctly?


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D107933/new/

https://reviews.llvm.org/D107933

___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D107002: [PowerPC] Implement XL compatibility builtin __addex

2021-08-12 Thread Lei Huang via Phabricator via cfe-commits
lei updated this revision to Diff 366094.
lei added a comment.

Fix name of new warning message to be more accuratly represent the diagnostic.


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D107002/new/

https://reviews.llvm.org/D107002

Files:
  clang/include/clang/Basic/BuiltinsPPC.def
  clang/include/clang/Basic/DiagnosticSemaKinds.td
  clang/lib/Basic/Targets/PPC.cpp
  clang/lib/Sema/SemaChecking.cpp
  clang/test/CodeGen/builtins-ppc-xlcompat-pwr9-64bit.c
  clang/test/CodeGen/builtins-ppc-xlcompat-pwr9-error.c
  clang/test/CodeGen/builtins-ppc-xlcompat-pwr9-warning.c
  llvm/include/llvm/IR/IntrinsicsPowerPC.td
  llvm/lib/Target/PowerPC/P9InstrResources.td
  llvm/lib/Target/PowerPC/PPCInstr64Bit.td
  llvm/test/CodeGen/PowerPC/builtins-ppc-xlcompat-pwr9-64bit.ll

Index: llvm/test/CodeGen/PowerPC/builtins-ppc-xlcompat-pwr9-64bit.ll
===
--- llvm/test/CodeGen/PowerPC/builtins-ppc-xlcompat-pwr9-64bit.ll
+++ llvm/test/CodeGen/PowerPC/builtins-ppc-xlcompat-pwr9-64bit.ll
@@ -29,3 +29,14 @@
   ret double %0
 }
 declare double @llvm.ppc.insert.exp(double, i64)
+
+declare i64 @llvm.ppc.addex(i64, i64, i32 immarg)
+define dso_local i64 @call_addex_0(i64 %a, i64 %b) {
+; CHECK-LABEL: call_addex_0:
+; CHECK:   # %bb.0: # %entry
+; CHECK-NEXT:addex 3, 3, 4, 0
+; CHECK-NEXT:blr
+entry:
+  %0 = tail call i64 @llvm.ppc.addex(i64 %a, i64 %b, i32 0)
+  ret i64 %0
+}
Index: llvm/lib/Target/PowerPC/PPCInstr64Bit.td
===
--- llvm/lib/Target/PowerPC/PPCInstr64Bit.td
+++ llvm/lib/Target/PowerPC/PPCInstr64Bit.td
@@ -1670,6 +1670,13 @@
  "hashchkp $RB, $D_RA_XD", IIC_IntGeneral, []>;
 }
 
+let Interpretation64Bit = 1, isCodeGenOnly = 1, hasSideEffects = 1 in
+def ADDEX8 : Z23Form_RTAB5_CY2<31, 170, (outs g8rc:$rT),
+  (ins g8rc:$rA, g8rc:$rB, u2imm:$CY),
+  "addex $rT, $rA, $rB, $CY", IIC_IntGeneral,
+  [(set i64:$rT, (int_ppc_addex i64:$rA, i64:$rB,
+timm:$CY))]>;
+
 //===--===//
 // Instruction Patterns
 //
Index: llvm/lib/Target/PowerPC/P9InstrResources.td
===
--- llvm/lib/Target/PowerPC/P9InstrResources.td
+++ llvm/lib/Target/PowerPC/P9InstrResources.td
@@ -1430,5 +1430,6 @@
   DCBI,
   DCCCI,
   ICCCI,
-  ADDEX
+  ADDEX,
+  ADDEX8
 )> { let Unsupported = 1; }
Index: llvm/include/llvm/IR/IntrinsicsPowerPC.td
===
--- llvm/include/llvm/IR/IntrinsicsPowerPC.td
+++ llvm/include/llvm/IR/IntrinsicsPowerPC.td
@@ -1706,7 +1706,10 @@
   def int_ppc_fres
   : GCCBuiltin<"__builtin_ppc_fres">,
 Intrinsic <[llvm_float_ty], [llvm_float_ty], [IntrNoMem]>;
-  
+  def int_ppc_addex
+  : GCCBuiltin<"__builtin_ppc_addex">,
+Intrinsic<[llvm_i64_ty], [llvm_i64_ty, llvm_i64_ty, llvm_i32_ty],
+  [IntrNoMem, IntrHasSideEffects, ImmArg>]>;
   def int_ppc_fsel : GCCBuiltin<"__builtin_ppc_fsel">,
  Intrinsic<[llvm_double_ty], [llvm_double_ty, llvm_double_ty, 
   llvm_double_ty], [IntrNoMem]>;
Index: clang/test/CodeGen/builtins-ppc-xlcompat-pwr9-warning.c
===
--- /dev/null
+++ clang/test/CodeGen/builtins-ppc-xlcompat-pwr9-warning.c
@@ -0,0 +1,11 @@
+// REQUIRES: powerpc-registered-target
+// RUN: %clang_cc1 -triple powerpc64-unknown-unknown -target-cpu pwr9 \
+// RUN:   -verify %s
+
+extern unsigned long long ull;
+extern long long ll;
+
+void test_builtin_ppc_addex() {
+  long long res = __builtin_ppc_addex(ll, ll, 1); // expected-warning {{argument value 1 will result in undefined behaviour}}
+  unsigned long long res2 = __builtin_ppc_addex(ull, ull, 3); // expected-warning {{argument value 3 will result in undefined behaviour}}
+}
Index: clang/test/CodeGen/builtins-ppc-xlcompat-pwr9-error.c
===
--- clang/test/CodeGen/builtins-ppc-xlcompat-pwr9-error.c
+++ clang/test/CodeGen/builtins-ppc-xlcompat-pwr9-error.c
@@ -9,7 +9,18 @@
 // RUN:   -fsyntax-only -Wall -Werror -verify %s
 
 extern unsigned int ui;
+extern unsigned long long ull;
+extern long long ll;
 
 void test_builtin_ppc_cmprb() {
   int res = __builtin_ppc_cmprb(3, ui, ui); // expected-error {{argument value 3 is outside the valid range [0, 1]}}
 }
+
+#ifdef __PPC64__
+
+void test_builtin_ppc_addex() {
+  long long res = __builtin_ppc_addex(ll, ll, 4); // expected-error {{argument value 4 is outside the valid range [0, 3]}}
+  unsigned long long res2 = __builtin_ppc_addex(ull, ull, -1); // expected-error 

[PATCH] D107648: [OpenCL] Clang diagnostics allow reporting C++ for OpenCL version.

2021-08-12 Thread Anastasia Stulova via Phabricator via cfe-commits
Anastasia added a comment.

Great! Thanks!

The suggested minor test clean-up can be addressed in the final commit!




Comment at: clang/test/SemaOpenCL/nosvm.cl:10
+// expected-warning@-2 {{'nosvm' attribute is deprecated and ignored in OpenCL 
C version 2.0}}
+#elif defined(CLCPP10)
+// expected-warning@-4 {{'nosvm' attribute is deprecated and ignored in C++ 
for OpenCL version 1.0}}

Here we could check for predefined macros `__OPENCL_CPP_VERSION `instead


CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D107648/new/

https://reviews.llvm.org/D107648

___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D107961: [clang-format] Distinguish K C function definition and attribute

2021-08-12 Thread Owen Pan via Phabricator via cfe-commits
owenpan added inline comments.



Comment at: clang/lib/Format/UnwrappedLineParser.cpp:17
 #include "FormatToken.h"
-#include "clang/Basic/TokenKinds.h"
 #include "llvm/ADT/STLExtras.h"

HazardyKnusperkeks wrote:
> Why is this not needed anymore?
It was added in [[ https://reviews.llvm.org/D107950 | D107950 ]] but not needed 
even there.


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D107961/new/

https://reviews.llvm.org/D107961

___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D107667: [clang/test] Run thinlto-clang-diagnostic-handler-in-be.c on x86

2021-08-12 Thread Thomas Preud'homme via Phabricator via cfe-commits
This revision was landed with ongoing or failed builds.
This revision was automatically updated to reflect the committed changes.
Closed by commit rG1e11ccad837c: [clang/test] Run 
thinlto-clang-diagnostic-handler-in-be.c on x86 (authored by thopre).

Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D107667/new/

https://reviews.llvm.org/D107667

Files:
  clang/test/CodeGen/thinlto-clang-diagnostic-handler-in-be.c


Index: clang/test/CodeGen/thinlto-clang-diagnostic-handler-in-be.c
===
--- clang/test/CodeGen/thinlto-clang-diagnostic-handler-in-be.c
+++ clang/test/CodeGen/thinlto-clang-diagnostic-handler-in-be.c
@@ -3,11 +3,11 @@
 // REQUIRES: x86-registered-target
 
 // RUN: llvm-profdata merge -o %t1.profdata %S/Inputs/thinlto_expect1.proftext
-// RUN: %clang -O2 -fexperimental-new-pass-manager -flto=thin -g 
-fprofile-use=%t1.profdata -c -o %t1.bo %s
+// RUN: %clang -target x86_64-linux-gnu -O2 -fexperimental-new-pass-manager 
-flto=thin -g -fprofile-use=%t1.profdata -c -o %t1.bo %s
 // RUN: llvm-lto -thinlto -o %t %t1.bo
-// RUN: %clang -cc1 -O2 -fexperimental-new-pass-manager -x ir %t1.bo 
-fthinlto-index=%t.thinlto.bc -emit-obj -Rpass-analysis=info 2>&1 | FileCheck 
%s -check-prefix=CHECK-REMARK
+// RUN: %clang -cc1 -triple x86_64-linux-gnu -O2 
-fexperimental-new-pass-manager -x ir %t1.bo -fthinlto-index=%t.thinlto.bc 
-emit-obj -Rpass-analysis=info 2>&1 | FileCheck %s -check-prefix=CHECK-REMARK
 // RUN: llvm-profdata merge -o %t2.profdata %S/Inputs/thinlto_expect2.proftext
-// RUN: %clang -cc1 -O2 -fexperimental-new-pass-manager -x ir %t1.bo 
-fthinlto-index=%t.thinlto.bc -fprofile-instrument-use-path=%t2.profdata 
-emit-obj 2>&1 | FileCheck %s -allow-empty -check-prefix=CHECK-NOWARNING
+// RUN: %clang -cc1 -triple x86_64-linux-gnu -O2 
-fexperimental-new-pass-manager -x ir %t1.bo -fthinlto-index=%t.thinlto.bc 
-fprofile-instrument-use-path=%t2.profdata -emit-obj 2>&1 | FileCheck %s 
-allow-empty -check-prefix=CHECK-NOWARNING
 
 int sum;
 __attribute__((noinline)) void bar() {


Index: clang/test/CodeGen/thinlto-clang-diagnostic-handler-in-be.c
===
--- clang/test/CodeGen/thinlto-clang-diagnostic-handler-in-be.c
+++ clang/test/CodeGen/thinlto-clang-diagnostic-handler-in-be.c
@@ -3,11 +3,11 @@
 // REQUIRES: x86-registered-target
 
 // RUN: llvm-profdata merge -o %t1.profdata %S/Inputs/thinlto_expect1.proftext
-// RUN: %clang -O2 -fexperimental-new-pass-manager -flto=thin -g -fprofile-use=%t1.profdata -c -o %t1.bo %s
+// RUN: %clang -target x86_64-linux-gnu -O2 -fexperimental-new-pass-manager -flto=thin -g -fprofile-use=%t1.profdata -c -o %t1.bo %s
 // RUN: llvm-lto -thinlto -o %t %t1.bo
-// RUN: %clang -cc1 -O2 -fexperimental-new-pass-manager -x ir %t1.bo -fthinlto-index=%t.thinlto.bc -emit-obj -Rpass-analysis=info 2>&1 | FileCheck %s -check-prefix=CHECK-REMARK
+// RUN: %clang -cc1 -triple x86_64-linux-gnu -O2 -fexperimental-new-pass-manager -x ir %t1.bo -fthinlto-index=%t.thinlto.bc -emit-obj -Rpass-analysis=info 2>&1 | FileCheck %s -check-prefix=CHECK-REMARK
 // RUN: llvm-profdata merge -o %t2.profdata %S/Inputs/thinlto_expect2.proftext
-// RUN: %clang -cc1 -O2 -fexperimental-new-pass-manager -x ir %t1.bo -fthinlto-index=%t.thinlto.bc -fprofile-instrument-use-path=%t2.profdata -emit-obj 2>&1 | FileCheck %s -allow-empty -check-prefix=CHECK-NOWARNING
+// RUN: %clang -cc1 -triple x86_64-linux-gnu -O2 -fexperimental-new-pass-manager -x ir %t1.bo -fthinlto-index=%t.thinlto.bc -fprofile-instrument-use-path=%t2.profdata -emit-obj 2>&1 | FileCheck %s -allow-empty -check-prefix=CHECK-NOWARNING
 
 int sum;
 __attribute__((noinline)) void bar() {
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] 1e11cca - [clang/test] Run thinlto-clang-diagnostic-handler-in-be.c on x86

2021-08-12 Thread Thomas Preud'homme via cfe-commits

Author: Thomas Preud'homme
Date: 2021-08-12T21:38:35+01:00
New Revision: 1e11ccad837c2d0d848349e7bc8f5800e5d365fc

URL: 
https://github.com/llvm/llvm-project/commit/1e11ccad837c2d0d848349e7bc8f5800e5d365fc
DIFF: 
https://github.com/llvm/llvm-project/commit/1e11ccad837c2d0d848349e7bc8f5800e5d365fc.diff

LOG: [clang/test] Run thinlto-clang-diagnostic-handler-in-be.c on x86

Clang test CodeGen/thinlto-clang-diagnostic-handler-in-be.c fails on
some non x86 targets, e.g. hexagon. Since the test already requires x86
to be available as a target this commit forces the target to x86_64.

Reviewed By: steven_wu

Differential Revision: https://reviews.llvm.org/D107667

Added: 


Modified: 
clang/test/CodeGen/thinlto-clang-diagnostic-handler-in-be.c

Removed: 




diff  --git a/clang/test/CodeGen/thinlto-clang-diagnostic-handler-in-be.c 
b/clang/test/CodeGen/thinlto-clang-diagnostic-handler-in-be.c
index 32489694289f6..1223cd9a5411b 100644
--- a/clang/test/CodeGen/thinlto-clang-diagnostic-handler-in-be.c
+++ b/clang/test/CodeGen/thinlto-clang-diagnostic-handler-in-be.c
@@ -3,11 +3,11 @@
 // REQUIRES: x86-registered-target
 
 // RUN: llvm-profdata merge -o %t1.profdata %S/Inputs/thinlto_expect1.proftext
-// RUN: %clang -O2 -fexperimental-new-pass-manager -flto=thin -g 
-fprofile-use=%t1.profdata -c -o %t1.bo %s
+// RUN: %clang -target x86_64-linux-gnu -O2 -fexperimental-new-pass-manager 
-flto=thin -g -fprofile-use=%t1.profdata -c -o %t1.bo %s
 // RUN: llvm-lto -thinlto -o %t %t1.bo
-// RUN: %clang -cc1 -O2 -fexperimental-new-pass-manager -x ir %t1.bo 
-fthinlto-index=%t.thinlto.bc -emit-obj -Rpass-analysis=info 2>&1 | FileCheck 
%s -check-prefix=CHECK-REMARK
+// RUN: %clang -cc1 -triple x86_64-linux-gnu -O2 
-fexperimental-new-pass-manager -x ir %t1.bo -fthinlto-index=%t.thinlto.bc 
-emit-obj -Rpass-analysis=info 2>&1 | FileCheck %s -check-prefix=CHECK-REMARK
 // RUN: llvm-profdata merge -o %t2.profdata %S/Inputs/thinlto_expect2.proftext
-// RUN: %clang -cc1 -O2 -fexperimental-new-pass-manager -x ir %t1.bo 
-fthinlto-index=%t.thinlto.bc -fprofile-instrument-use-path=%t2.profdata 
-emit-obj 2>&1 | FileCheck %s -allow-empty -check-prefix=CHECK-NOWARNING
+// RUN: %clang -cc1 -triple x86_64-linux-gnu -O2 
-fexperimental-new-pass-manager -x ir %t1.bo -fthinlto-index=%t.thinlto.bc 
-fprofile-instrument-use-path=%t2.profdata -emit-obj 2>&1 | FileCheck %s 
-allow-empty -check-prefix=CHECK-NOWARNING
 
 int sum;
 __attribute__((noinline)) void bar() {



___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D106509: [OpenMP][OpenACC] Implement `ompx_hold` map type modifier extension in Clang (1/2)

2021-08-12 Thread Alexey Bataev via Phabricator via cfe-commits
ABataev added inline comments.



Comment at: clang/include/clang/Driver/Options.td:2383
+defm openmp_extensions: BoolFOption<"openmp-extensions",
+  LangOpts<"OpenMPExtensions">, DefaultFalse,
+  PosFlag ABataev wrote:
> > Why do you want to disable it by default?
> I thought that's what we agreed upon.
> 
> I'm personally happy if, in general, all features are enabled by default and 
> users opt out by requesting strict conformance, but Clang doesn't do that 
> today even for features from newer OpenMP standards.  Should it do so for 
> extensions, which appear in no standard?
> 
> What would you prefer?
I would enable it by default, as it may help users in some cases unless there 
are no other strong opinions.



Comment at: clang/lib/Driver/ToolChains/Clang.cpp:5774-5776
+  if (Args.hasFlag(options::OPT_fopenmp_extensions,
+   options::OPT_fno_openmp_extensions, /*Default=*/false))
+CmdArgs.push_back("-fopenmp-extensions");

jdenny wrote:
> ABataev wrote:
> > Do we still need this?
> I tried removing these, but then the driver doesn't pass 
> `-fopenmp-extensions` to the front end.  Am I doing something wrong?
Ah, yes, still need to forward the option from driver to the frontend


CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D106509/new/

https://reviews.llvm.org/D106509

___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D106509: [OpenMP][OpenACC] Implement `ompx_hold` map type modifier extension in Clang (1/2)

2021-08-12 Thread Joel E. Denny via Phabricator via cfe-commits
jdenny added inline comments.



Comment at: clang/include/clang/Driver/Options.td:2383
+defm openmp_extensions: BoolFOption<"openmp-extensions",
+  LangOpts<"OpenMPExtensions">, DefaultFalse,
+  PosFlag Why do you want to disable it by default?
I thought that's what we agreed upon.

I'm personally happy if, in general, all features are enabled by default and 
users opt out by requesting strict conformance, but Clang doesn't do that today 
even for features from newer OpenMP standards.  Should it do so for extensions, 
which appear in no standard?

What would you prefer?



Comment at: clang/lib/Driver/ToolChains/Clang.cpp:5774-5776
+  if (Args.hasFlag(options::OPT_fopenmp_extensions,
+   options::OPT_fno_openmp_extensions, /*Default=*/false))
+CmdArgs.push_back("-fopenmp-extensions");

ABataev wrote:
> Do we still need this?
I tried removing these, but then the driver doesn't pass `-fopenmp-extensions` 
to the front end.  Am I doing something wrong?


CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D106509/new/

https://reviews.llvm.org/D106509

___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D107933: [clang] Expose unreachable fallthrough annotation warning

2021-08-12 Thread Dávid Bolvanský via Phabricator via cfe-commits
xbolva00 added a comment.

I think we should just move it, not delete it.


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D107933/new/

https://reviews.llvm.org/D107933

___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D107339: [analyzer] Retrieve a character from StringLiteral as an initializer for constant arrays.

2021-08-12 Thread Denys Petrov via Phabricator via cfe-commits
ASDenysPetrov updated this revision to Diff 366083.
ASDenysPetrov added a comment.

Rebased.


CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D107339/new/

https://reviews.llvm.org/D107339

Files:
  clang/lib/StaticAnalyzer/Core/RegionStore.cpp


Index: clang/lib/StaticAnalyzer/Core/RegionStore.cpp
===
--- clang/lib/StaticAnalyzer/Core/RegionStore.cpp
+++ clang/lib/StaticAnalyzer/Core/RegionStore.cpp
@@ -443,6 +443,8 @@
   Optional getSValFromInitListExprByIndex(const InitListExpr *ILE,
 const llvm::APSInt ,
 QualType ElemT);
+  SVal getSValFromStringLiteralByIndex(const StringLiteral *SL,
+   const llvm::APSInt , QualType 
ElemT);
 
 public: // Part of public interface to class.
 
@@ -1649,7 +1651,9 @@
   if (const auto *ILE = dyn_cast(Init))
 return getSValFromInitListExprByIndex(ILE, Idx, ElemT);
 
-  // FIXME: Handle StringLiteral.
+  // Handle StringLiteral.
+  if (const auto *SL = dyn_cast(Init))
+return getSValFromStringLiteralByIndex(SL, Idx, ElemT);
 
   // FIXME: Handle CompoundLiteralExpr.
 
@@ -1679,6 +1683,22 @@
   return svalBuilder.getConstantVal(E);
 }
 
+SVal RegionStoreManager::getSValFromStringLiteralByIndex(
+const StringLiteral *SL, const llvm::APSInt , QualType ElemT) {
+  assert(SL && "StringLiteral should not be null");
+  // If index is out of bounds, return Undef.
+  const int64_t I = Idx.getExtValue();
+  if (Idx.isSigned() && I < 0)
+return UndefinedVal();
+  // Technically, only i == length is guaranteed to be null.
+  // However, such overflows should be caught before reaching this point;
+  // the only time such an access would be made is if a string literal was
+  // used to initialize a larger array.
+  uint32_t Code =
+  (static_cast(I) >= SL->getLength()) ? 0 : SL->getCodeUnit(I);
+  return svalBuilder.makeIntVal(Code, ElemT);
+}
+
 SVal RegionStoreManager::getBindingForElement(RegionBindingsConstRef B,
   const ElementRegion* R) {
   // Check if the region has a binding.
@@ -1695,21 +1715,10 @@
 if (!Ctx.hasSameUnqualifiedType(T, R->getElementType()))
   return UnknownVal();
 
-const StringLiteral *Str = StrR->getStringLiteral();
 SVal Idx = R->getIndex();
 if (Optional CI = Idx.getAs()) {
-  int64_t i = CI->getValue().getSExtValue();
-  // Abort on string underrun.  This can be possible by arbitrary
-  // clients of getBindingForElement().
-  if (i < 0)
-return UndefinedVal();
-  int64_t length = Str->getLength();
-  // Technically, only i == length is guaranteed to be null.
-  // However, such overflows should be caught before reaching this point;
-  // the only time such an access would be made is if a string literal was
-  // used to initialize a larger array.
-  char c = (i >= length) ? '\0' : Str->getCodeUnit(i);
-  return svalBuilder.makeIntVal(c, T);
+  const StringLiteral *Str = StrR->getStringLiteral();
+  return getSValFromStringLiteralByIndex(Str, CI->getValue(), T);
 }
   } else if (isa(superR) || isa(superR)) {
 const VarRegion *VR = nullptr;
@@ -2237,10 +2246,11 @@
 RegionBindingsRef RegionStoreManager::bindArray(RegionBindingsConstRef B,
 const TypedValueRegion *R,
 SVal Init) {
-  // Ignore binding `InitListExpr` to arrays of const type,
-  // since we can directly retrieve values from initializer using
+  // Ignore binding `InitListExpr` and `StringLiteral` to arrays of const type,
+  // since we can directly retrieve values from initializers using
   // `getConstantValFromConstArrayInitializer`.For example:
   //   const int arr[42] = { 1, 2, 3 };
+  //   const char arr[42] = "123";
   // The init values of this array will never change, so we don't have to
   // store them additionally in the RegionStore.
   if (const auto *VR = dyn_cast(R)) {
@@ -2248,9 +2258,9 @@
 // Ignore only arrays which values can't change.
 if (VD->getType().isConstQualified()) {
   const Expr *Init = VD->getAnyInitializer();
-  // FIXME: Ignore `StringLiteral` and `CompoundLiteralExpr` as well when
-  // `getConstantValFromConstArrayInitializer` supports them.
-  if (isa_and_nonnull(Init))
+  // FIXME: Ignore `CompoundLiteralExpr` as well when
+  // `getConstantValFromConstArrayInitializer` supports it.
+  if (Init && (isa(Init) || isa(Init)))
 return B;
 }
   }


Index: clang/lib/StaticAnalyzer/Core/RegionStore.cpp
===
--- clang/lib/StaticAnalyzer/Core/RegionStore.cpp
+++ clang/lib/StaticAnalyzer/Core/RegionStore.cpp
@@ -443,6 +443,8 @@
   Optional getSValFromInitListExprByIndex(const InitListExpr *ILE,
 

[PATCH] D71734: [Modules] Handle tag types and complain about bad merges in C/Objective-C mode

2021-08-12 Thread Volodymyr Sapsai via Phabricator via cfe-commits
vsapsai planned changes to this revision.
vsapsai added a comment.

Need to detect mismatches in nested structs.


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D71734/new/

https://reviews.llvm.org/D71734

___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D107933: [clang] Expose unreachable fallthrough annotation warning

2021-08-12 Thread Nathan Chancellor via Phabricator via cfe-commits
nathanchance added a comment.

> In D107933#2942023 , @xbolva00 
> wrote:
>
>> 
>
> GCC does not warn (with common -Wall) for this case, right? I think Clang 
> should not as well.

Correct, GCC does not warn at all about unreachable fallthrough annotations as 
far as I am aware.

In D107933#2942102 , @dblaikie wrote:

> In D107933#2942023 , @xbolva00 
> wrote:
>
>> ImplicitFallthroughUnreachable could be enabled with -Wunreachable-code, if 
>> you think we should have it.
>
> Yeah, some of that was discussed on the bug: 
> https://bugs.llvm.org/show_bug.cgi?id=51094 & I'd still be in favor of that 
> sort of direction. I might go so far as to say: Maybe we should drop this 
> warning flag (and/or move it under -Wunreachable-code - questionable, I don't 
> think anyone's really using that, it's pretty noisy still, I think) entirely 
> even if no one's willing to reimplement it more robustly... not sure.

The kernel does not use `-Wunreachable-code` for this reason and several 
others; we have explored it in the past 
 and found that there 
were pretty much no instances where the warnings indicated a bug and kernel 
maintainers were irritated with some of the patches sent. So moving this 
warning under there (as `-Wunreachable-code-fallthrough`?) would work for us. I 
do not have a strong opinion though. I am more than happy to remove the warning 
entirely as well.


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D107933/new/

https://reviews.llvm.org/D107933

___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D107073: [analyzer] Disable direct binding from list initialization for constant arrays of local storage duration.

2021-08-12 Thread Denys Petrov via Phabricator via cfe-commits
ASDenysPetrov updated this revision to Diff 366081.
ASDenysPetrov added a comment.

Rebased.


CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D107073/new/

https://reviews.llvm.org/D107073

Files:
  clang/lib/StaticAnalyzer/Core/RegionStore.cpp
  clang/test/Analysis/initialization.c
  clang/test/Analysis/initialization.cpp

Index: clang/test/Analysis/initialization.cpp
===
--- clang/test/Analysis/initialization.cpp
+++ clang/test/Analysis/initialization.cpp
@@ -167,7 +167,7 @@
   clang_analyzer_eval(glob_arr3[3][1] == 0); // expected-warning{{TRUE}}
 }
 
-void negative_index1() {
+void glob_arr_negative_index1() {
   int x = 2, y = -2;
   clang_analyzer_eval(glob_arr3[x][y] == 3); // expected-warning{{TRUE}}
   x = 4;
@@ -175,12 +175,12 @@
   clang_analyzer_eval(glob_arr3[x][y] == 7); // expected-warning{{TRUE}}
 }
 
-void out_of_bound_index1() {
+void glob_arr_out_of_bound_index1() {
   int x = -3, y = 2;
   int res = glob_arr3[x][y]; // expected-warning{{garbage or undefined}}
 }
 
-void out_of_bound_index2() {
+void glob_arr_out_of_bound_index2() {
   int x = 3, y = 2;
   int res = glob_arr3[x][y]; // expected-warning{{garbage or undefined}}
 }
@@ -197,12 +197,101 @@
   clang_analyzer_eval(glob_arr4[7] == 0); // expected-warning{{TRUE}}
 }
 
-void out_of_bound_index3() {
+void glob_arr_out_of_bound_index3() {
   int x = -42;
   int res = glob_arr4[x]; // expected-warning{{garbage or undefined}}
 }
 
-void out_of_bound_index4() {
+void glob_arr_out_of_bound_index4() {
   int x = 42;
   int res = glob_arr4[x]; // expected-warning{{garbage or undefined}}
 }
+
+void local_arr_index1() {
+  const int local_arr[2][2][3] = {{{1, 2}}, {{7}}};
+  clang_analyzer_eval(local_arr[0][0][0] == 1); // expected-warning{{TRUE}}
+  clang_analyzer_eval(local_arr[0][0][1] == 2); // expected-warning{{TRUE}}
+  clang_analyzer_eval(local_arr[0][0][2] == 0); // expected-warning{{TRUE}}
+  clang_analyzer_eval(local_arr[0][1][0] == 0); // expected-warning{{TRUE}}
+  clang_analyzer_eval(local_arr[0][1][1] == 0); // expected-warning{{TRUE}}
+  clang_analyzer_eval(local_arr[0][1][2] == 0); // expected-warning{{TRUE}}
+  clang_analyzer_eval(local_arr[1][0][0] == 7); // expected-warning{{TRUE}}
+  clang_analyzer_eval(local_arr[1][0][1] == 0); // expected-warning{{TRUE}}
+  clang_analyzer_eval(local_arr[1][0][2] == 0); // expected-warning{{TRUE}}
+  clang_analyzer_eval(local_arr[1][1][0] == 0); // expected-warning{{TRUE}}
+  clang_analyzer_eval(local_arr[1][1][1] == 0); // expected-warning{{TRUE}}
+  clang_analyzer_eval(local_arr[1][1][2] == 0); // expected-warning{{TRUE}}
+}
+
+void local_arr_index2() {
+  int const local_arr[2][2][3] = {{{1, 2}, {}}, {{7, 8}, {10, 11, 12}}};
+  clang_analyzer_eval(local_arr[0][0][0] == 1);  // expected-warning{{TRUE}}
+  clang_analyzer_eval(local_arr[0][0][1] == 2);  // expected-warning{{TRUE}}
+  clang_analyzer_eval(local_arr[0][0][2] == 0);  // expected-warning{{TRUE}}
+  clang_analyzer_eval(local_arr[0][1][0] == 0);  // expected-warning{{TRUE}}
+  clang_analyzer_eval(local_arr[0][1][1] == 0);  // expected-warning{{TRUE}}
+  clang_analyzer_eval(local_arr[0][1][2] == 0);  // expected-warning{{TRUE}}
+  clang_analyzer_eval(local_arr[1][0][0] == 7);  // expected-warning{{TRUE}}
+  clang_analyzer_eval(local_arr[1][0][1] == 8);  // expected-warning{{TRUE}}
+  clang_analyzer_eval(local_arr[1][0][2] == 0);  // expected-warning{{TRUE}}
+  clang_analyzer_eval(local_arr[1][1][0] == 10); // expected-warning{{TRUE}}
+  clang_analyzer_eval(local_arr[1][1][1] == 11); // expected-warning{{TRUE}}
+  clang_analyzer_eval(local_arr[1][1][2] == 12); // expected-warning{{TRUE}}
+}
+
+void local_arr_index3() {
+  const int local_arr[4][2] = {{}, {3}, {}, {7}};
+  clang_analyzer_eval(local_arr[0][0] == 0); // expected-warning{{TRUE}}
+  clang_analyzer_eval(local_arr[0][1] == 0); // expected-warning{{TRUE}}
+  clang_analyzer_eval(local_arr[1][0] == 3); // expected-warning{{TRUE}}
+  clang_analyzer_eval(local_arr[1][1] == 0); // expected-warning{{TRUE}}
+  clang_analyzer_eval(local_arr[2][0] == 0); // expected-warning{{TRUE}}
+  clang_analyzer_eval(local_arr[2][1] == 0); // expected-warning{{TRUE}}
+  clang_analyzer_eval(local_arr[3][0] == 7); // expected-warning{{TRUE}}
+  clang_analyzer_eval(local_arr[3][1] == 0); // expected-warning{{TRUE}}
+}
+
+void local_arr_negative_index1() {
+  const int local_arr[4][2] = {{}, {3}, {}, {7}};
+  int x = 2, y = -2;
+  clang_analyzer_eval(local_arr[x][y] == 3); // expected-warning{{TRUE}}
+  x = 4;
+  y = -2;
+  clang_analyzer_eval(local_arr[x][y] == 7); // expected-warning{{TRUE}}
+}
+
+void local_arr_out_of_bound_index1() {
+  const int local_arr[4][2] = {{}, {3}, {}, {7}};
+  int x = -3, y = 2;
+  int res = local_arr[x][y]; // expected-warning{{garbage or undefined}}
+}
+
+void local_arr_out_of_bound_index2() {
+  const int local_arr[4][2] = {{}, {3}, {}, {7}};
+  int x = 3, y = 2;
+  int res = local_arr[x][y]; 

[PATCH] D106509: [OpenMP][OpenACC] Implement `ompx_hold` map type modifier extension in Clang (1/2)

2021-08-12 Thread Alexey Bataev via Phabricator via cfe-commits
ABataev added inline comments.



Comment at: clang/docs/ClangCommandLineReference.rst:2042-2044
+.. option:: -fopenmp-extensions, -fno-openmp-extensions
+
+Enable all Clang extensions for OpenMP directives and clauses.

Default value?



Comment at: clang/include/clang/Driver/Options.td:2383
+defm openmp_extensions: BoolFOption<"openmp-extensions",
+  LangOpts<"OpenMPExtensions">, DefaultFalse,
+  PosFlaghttps://reviews.llvm.org/D106509/new/

https://reviews.llvm.org/D106509

___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D106681: [analyzer] Retrieve a value from list initialization of constant multi-dimensional array.

2021-08-12 Thread Denys Petrov via Phabricator via cfe-commits
ASDenysPetrov updated this revision to Diff 366079.
ASDenysPetrov added a comment.

Rebased.


CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D106681/new/

https://reviews.llvm.org/D106681

Files:
  clang/lib/StaticAnalyzer/Core/MemRegion.cpp
  clang/lib/StaticAnalyzer/Core/RegionStore.cpp
  clang/test/Analysis/initialization.c
  clang/test/Analysis/initialization.cpp

Index: clang/test/Analysis/initialization.cpp
===
--- clang/test/Analysis/initialization.cpp
+++ clang/test/Analysis/initialization.cpp
@@ -1,4 +1,4 @@
-// RUN: %clang_cc1 -std=c++14 -triple i386-apple-darwin10 -analyze -analyzer-checker=core.uninitialized.Assign,core.builtin,debug.ExprInspection,core.uninitialized.UndefReturn -verify %s
+// RUN: %clang_cc1 -std=c++14 -triple i386-apple-darwin10 -analyze -analyzer-checker=core.uninitialized.Assign,core.builtin,debug.ExprInspection -verify %s
 
 void clang_analyzer_eval(int);
 
@@ -15,8 +15,7 @@
 int const arr[2][2] = {};
 void arr2init() {
   int i = 1;
-  // FIXME: Should recognize that it is 0.
-  clang_analyzer_eval(arr[i][0]); // expected-warning{{UNKNOWN}}
+  clang_analyzer_eval(arr[i][0]); // expected-warning{{FALSE}}
 }
 
 void direct_index1() {
@@ -124,8 +123,86 @@
   auto buf_p = rvp[4]; // no-warning (garbage or undefined)
 }
 
-const float floats[] = {
-0., 0.0235, 0.0470, 0.0706, 0.0941, 0.1176};
-float no_warn_garbage_value() {
-  return floats[0]; // no-warning (garbage or undefined)
+const int glob_arr1[2][2][3] = {{{1, 2}}, {{7}}};
+void glob_arr_index1() {
+  clang_analyzer_eval(glob_arr1[0][0][0] == 1); // expected-warning{{TRUE}}
+  clang_analyzer_eval(glob_arr1[0][0][1] == 2); // expected-warning{{TRUE}}
+  clang_analyzer_eval(glob_arr1[0][0][2] == 0); // expected-warning{{TRUE}}
+  clang_analyzer_eval(glob_arr1[0][1][0] == 0); // expected-warning{{TRUE}}
+  clang_analyzer_eval(glob_arr1[0][1][1] == 0); // expected-warning{{TRUE}}
+  clang_analyzer_eval(glob_arr1[0][1][2] == 0); // expected-warning{{TRUE}}
+  clang_analyzer_eval(glob_arr1[1][0][0] == 7); // expected-warning{{TRUE}}
+  clang_analyzer_eval(glob_arr1[1][0][1] == 0); // expected-warning{{TRUE}}
+  clang_analyzer_eval(glob_arr1[1][0][2] == 0); // expected-warning{{TRUE}}
+  clang_analyzer_eval(glob_arr1[1][1][0] == 0); // expected-warning{{TRUE}}
+  clang_analyzer_eval(glob_arr1[1][1][1] == 0); // expected-warning{{TRUE}}
+  clang_analyzer_eval(glob_arr1[1][1][2] == 0); // expected-warning{{TRUE}}
+}
+
+int const glob_arr2[2][2][3] = {{{1, 2}, {}}, {{7, 8}, {10, 11, 12}}};
+void glob_arr_index2() {
+  clang_analyzer_eval(glob_arr2[0][0][0] == 1);  // expected-warning{{TRUE}}
+  clang_analyzer_eval(glob_arr2[0][0][1] == 2);  // expected-warning{{TRUE}}
+  clang_analyzer_eval(glob_arr2[0][0][2] == 0);  // expected-warning{{TRUE}}
+  clang_analyzer_eval(glob_arr2[0][1][0] == 0);  // expected-warning{{TRUE}}
+  clang_analyzer_eval(glob_arr2[0][1][1] == 0);  // expected-warning{{TRUE}}
+  clang_analyzer_eval(glob_arr2[0][1][2] == 0);  // expected-warning{{TRUE}}
+  clang_analyzer_eval(glob_arr2[1][0][0] == 7);  // expected-warning{{TRUE}}
+  clang_analyzer_eval(glob_arr2[1][0][1] == 8);  // expected-warning{{TRUE}}
+  clang_analyzer_eval(glob_arr2[1][0][2] == 0);  // expected-warning{{TRUE}}
+  clang_analyzer_eval(glob_arr2[1][1][0] == 10); // expected-warning{{TRUE}}
+  clang_analyzer_eval(glob_arr2[1][1][1] == 11); // expected-warning{{TRUE}}
+  clang_analyzer_eval(glob_arr2[1][1][2] == 12); // expected-warning{{TRUE}}
+}
+
+const int glob_arr3[4][2] = {{}, {3}, {}, {7}};
+void glob_arr_index3() {
+  clang_analyzer_eval(glob_arr3[0][0] == 0); // expected-warning{{TRUE}}
+  clang_analyzer_eval(glob_arr3[0][1] == 0); // expected-warning{{TRUE}}
+  clang_analyzer_eval(glob_arr3[1][0] == 3); // expected-warning{{TRUE}}
+  clang_analyzer_eval(glob_arr3[1][1] == 0); // expected-warning{{TRUE}}
+  clang_analyzer_eval(glob_arr3[2][0] == 0); // expected-warning{{TRUE}}
+  clang_analyzer_eval(glob_arr3[2][1] == 0); // expected-warning{{TRUE}}
+  clang_analyzer_eval(glob_arr3[3][0] == 7); // expected-warning{{TRUE}}
+  clang_analyzer_eval(glob_arr3[3][1] == 0); // expected-warning{{TRUE}}
+}
+
+void negative_index1() {
+  int x = 2, y = -2;
+  clang_analyzer_eval(glob_arr3[x][y] == 3); // expected-warning{{TRUE}}
+  x = 4;
+  y = -2;
+  clang_analyzer_eval(glob_arr3[x][y] == 7); // expected-warning{{TRUE}}
+}
+
+void out_of_bound_index1() {
+  int x = -3, y = 2;
+  int res = glob_arr3[x][y]; // expected-warning{{garbage or undefined}}
+}
+
+void out_of_bound_index2() {
+  int x = 3, y = 2;
+  int res = glob_arr3[x][y]; // expected-warning{{garbage or undefined}}
+}
+
+const int glob_arr4[8] = {1, 2, 3, 4};
+void glob_arr_index4() {
+  clang_analyzer_eval(glob_arr4[0] == 1); // expected-warning{{TRUE}}
+  clang_analyzer_eval(glob_arr4[1] == 2); // expected-warning{{TRUE}}
+  clang_analyzer_eval(glob_arr4[2] == 3); // expected-warning{{TRUE}}
+  

[PATCH] D107667: [clang/test] Run thinlto-clang-diagnostic-handler-in-be.c on x86

2021-08-12 Thread Steven Wu via Phabricator via cfe-commits
steven_wu accepted this revision.
steven_wu added a comment.
This revision is now accepted and ready to land.

LGTM. Thanks


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D107667/new/

https://reviews.llvm.org/D107667

___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D107843: [X86] Add parentheses around casts in some of the X86 intrinsic headers.

2021-08-12 Thread Craig Topper via Phabricator via cfe-commits
craig.topper updated this revision to Diff 366071.
craig.topper added a comment.

Add test case to the bottom of sse41-builtins.c


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D107843/new/

https://reviews.llvm.org/D107843

Files:
  clang/lib/Headers/__wmmintrin_aes.h
  clang/lib/Headers/avx2intrin.h
  clang/lib/Headers/avxintrin.h
  clang/lib/Headers/emmintrin.h
  clang/lib/Headers/smmintrin.h
  clang/lib/Headers/tmmintrin.h
  clang/lib/Headers/xmmintrin.h
  clang/test/CodeGen/X86/sse41-builtins.c

Index: clang/test/CodeGen/X86/sse41-builtins.c
===
--- clang/test/CodeGen/X86/sse41-builtins.c
+++ clang/test/CodeGen/X86/sse41-builtins.c
@@ -393,3 +393,11 @@
   // CHECK: call i32 @llvm.x86.sse41.ptestz(<2 x i64> %{{.*}}, <2 x i64> %{{.*}})
   return _mm_testz_si128(x, y);
 }
+
+// Make sure brackets work after macro intrinsics.
+float pr51324(__m128 a) {
+  // CHECK-LABEL: pr51324
+  // CHECK: call <4 x float> @llvm.x86.sse41.round.ps(<4 x float> %{{.*}}, i32 0)
+  // CHECK: extractelement <4 x float> %{{.*}}, i32 0
+  return _mm_round_ps(a, 0)[0];
+}
Index: clang/lib/Headers/xmmintrin.h
===
--- clang/lib/Headers/xmmintrin.h
+++ clang/lib/Headers/xmmintrin.h
@@ -2181,7 +2181,7 @@
 ///3: Bits [63:48] are copied to the destination.
 /// \returns A 16-bit integer containing the extracted 16 bits of packed data.
 #define _mm_extract_pi16(a, n) \
-  (int)__builtin_ia32_vec_ext_v4hi((__v4hi)a, (int)n)
+  ((int)__builtin_ia32_vec_ext_v4hi((__v4hi)a, (int)n))
 
 /// Copies data from the 64-bit vector of [4 x i16] to the destination,
 ///and inserts the lower 16-bits of an integer operand at the 16-bit offset
@@ -2212,7 +2212,7 @@
 /// \returns A 64-bit integer vector containing the copied packed data from the
 ///operands.
 #define _mm_insert_pi16(a, d, n) \
-  (__m64)__builtin_ia32_vec_set_v4hi((__v4hi)a, (int)d, (int)n)
+  ((__m64)__builtin_ia32_vec_set_v4hi((__v4hi)a, (int)d, (int)n))
 
 /// Compares each of the corresponding packed 16-bit integer values of
 ///the 64-bit integer vectors, and writes the greater value to the
@@ -2359,7 +2359,7 @@
 ///11: assigned from bits [63:48] of \a a.
 /// \returns A 64-bit integer vector containing the shuffled values.
 #define _mm_shuffle_pi16(a, n) \
-  (__m64)__builtin_ia32_pshufw((__v4hi)(__m64)(a), (n))
+  ((__m64)__builtin_ia32_pshufw((__v4hi)(__m64)(a), (n)))
 
 /// Conditionally copies the values from each 8-bit element in the first
 ///64-bit integer vector operand to the specified memory location, as
@@ -2601,8 +2601,8 @@
 ///11: Bits [127:96] copied from the specified operand.
 /// \returns A 128-bit vector of [4 x float] containing the shuffled values.
 #define _mm_shuffle_ps(a, b, mask) \
-  (__m128)__builtin_ia32_shufps((__v4sf)(__m128)(a), (__v4sf)(__m128)(b), \
-(int)(mask))
+  ((__m128)__builtin_ia32_shufps((__v4sf)(__m128)(a), (__v4sf)(__m128)(b), \
+ (int)(mask)))
 
 /// Unpacks the high-order (index 2,3) values from two 128-bit vectors of
 ///[4 x float] and interleaves them into a 128-bit vector of [4 x float].
Index: clang/lib/Headers/tmmintrin.h
===
--- clang/lib/Headers/tmmintrin.h
+++ clang/lib/Headers/tmmintrin.h
@@ -145,8 +145,8 @@
 /// \returns A 128-bit integer vector containing the concatenated right-shifted
 ///value.
 #define _mm_alignr_epi8(a, b, n) \
-  (__m128i)__builtin_ia32_palignr128((__v16qi)(__m128i)(a), \
- (__v16qi)(__m128i)(b), (n))
+  ((__m128i)__builtin_ia32_palignr128((__v16qi)(__m128i)(a), \
+  (__v16qi)(__m128i)(b), (n)))
 
 /// Concatenates the two 64-bit integer vector operands, and right-shifts
 ///the result by the number of bytes specified in the immediate operand.
@@ -168,7 +168,7 @@
 /// \returns A 64-bit integer vector containing the concatenated right-shifted
 ///value.
 #define _mm_alignr_pi8(a, b, n) \
-  (__m64)__builtin_ia32_palignr((__v8qi)(__m64)(a), (__v8qi)(__m64)(b), (n))
+  ((__m64)__builtin_ia32_palignr((__v8qi)(__m64)(a), (__v8qi)(__m64)(b), (n)))
 
 /// Horizontally adds the adjacent pairs of values contained in 2 packed
 ///128-bit vectors of [8 x i16].
Index: clang/lib/Headers/smmintrin.h
===
--- clang/lib/Headers/smmintrin.h
+++ clang/lib/Headers/smmintrin.h
@@ -231,7 +231,7 @@
 ///  11: Truncated
 /// \returns A 128-bit vector of [4 x float] containing the rounded values.
 #define _mm_round_ps(X, M) \
-  (__m128)__builtin_ia32_roundps((__v4sf)(__m128)(X), (M))
+  ((__m128)__builtin_ia32_roundps((__v4sf)(__m128)(X), (M)))
 
 /// Copies three upper elements of the first 128-bit vector operand to
 ///the corresponding 

[PATCH] D97803: [clangd] Overload bundles are only deprecated if each overloads is.

2021-08-12 Thread Sam McCall via Phabricator via cfe-commits
sammccall added inline comments.



Comment at: clang-tools-extra/clangd/CodeComplete.cpp:410
+if (Completion.Deprecated) {
+  Completion.Deprecated =
+  (C.SemaResult &&

kbobyrev wrote:
> sammccall wrote:
> > kbobyrev wrote:
> > > The comment you added says "cleared" which means this should probably be 
> > > `|=` rather than `=`, right?
> > > 
> > > Also, I this looks longer but probably more readable at least for me.
> > > 
> > > Also, the sources might be `SemaResult`, `IndexResult` or 
> > > `IdentifierResult`, right? :( Otherwise could've been 
> > > `Completion.Deprecated |= C.SemaResult ? C.SemaResult->Availability == 
> > > CXAvailability_Deprecated : C.IndexResult->Flags & Symbol::Deprecated;`
> > > The comment you added says "cleared" which means this should probably be 
> > > |= rather than =, right?
> > 
> > No, `Deprecated` *starts out true* and gets set to false (cleared) if we 
> > see any non-deprecated entry. (computes AND)
> > 
> > Your version assumes it starts out false and sets it if we see any 
> > deprecated entry. (computes OR).
> > 
> > I agree the OR version reads better - it's wrong though :-)
> Ahh, okay, makes sense, thank you!
> 
> Nit: I think the version I suggested (with fixes `|=` vs `=`) is somewhat 
> easier to read and doesn't take much more space.
Done, though with `&=` instead of `=` otherwise the logic is subtly different 
(the second clobbers the first).
And because of &= we need an explicit cast to bool.


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D97803/new/

https://reviews.llvm.org/D97803

___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D107850: [WIP][asan] Implemented custom calling convention similar used by HWASan for X86. The feature should be code complete. The tests are coming in a later revision.

2021-08-12 Thread Kirill Stoimenov via Phabricator via cfe-commits
kstoimenov updated this revision to Diff 366069.
kstoimenov added a comment.

Started using R8  instead of RAX 
beacuse of some test failures. Also fixed the "Yes means No and No means Yes. 
Delete all files [Y]? " bug :-) for the load/store functions.


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D107850/new/

https://reviews.llvm.org/D107850

Files:
  clang/test/CodeGen/asan-use-callbacks.cpp
  llvm/include/llvm/IR/Intrinsics.td
  llvm/include/llvm/Transforms/Instrumentation/AddressSanitizer.h
  llvm/lib/Target/X86/X86AsmPrinter.cpp
  llvm/lib/Target/X86/X86AsmPrinter.h
  llvm/lib/Target/X86/X86InstrCompiler.td
  llvm/lib/Target/X86/X86MCInstLower.cpp
  llvm/lib/Target/X86/X86RegisterInfo.td
  llvm/lib/Transforms/Instrumentation/AddressSanitizer.cpp

Index: llvm/lib/Transforms/Instrumentation/AddressSanitizer.cpp
===
--- llvm/lib/Transforms/Instrumentation/AddressSanitizer.cpp
+++ llvm/lib/Transforms/Instrumentation/AddressSanitizer.cpp
@@ -348,6 +348,10 @@
 static cl::opt ClOpt("asan-opt", cl::desc("Optimize instrumentation"),
cl::Hidden, cl::init(true));
 
+static cl::opt ClOptimizeCallbacks("asan-optimize-callbacks",
+ cl::desc("Optimize callbacks"),
+ cl::Hidden, cl::init(false));
+
 static cl::opt ClOptSameTemp(
 "asan-opt-same-temp", cl::desc("Instrument the same temp just once"),
 cl::Hidden, cl::init(true));
@@ -623,6 +627,7 @@
 C = &(M.getContext());
 LongSize = M.getDataLayout().getPointerSizeInBits();
 IntptrTy = Type::getIntNTy(*C, LongSize);
+Int8PtrTy = Type::getInt8PtrTy(*C);
 TargetTriple = Triple(M.getTargetTriple());
 
 Mapping = getShadowMapping(TargetTriple, LongSize, this->CompileKernel);
@@ -673,6 +678,7 @@
  Value *SizeArgument, uint32_t Exp);
   void instrumentMemIntrinsic(MemIntrinsic *MI);
   Value *memToShadow(Value *Shadow, IRBuilder<> );
+  void encodeMemToShadowInfo(int64_t *AccessInfo);
   bool suppressInstrumentationSiteForDebug(int );
   bool instrumentFunction(Function , const TargetLibraryInfo *TLI);
   bool maybeInsertAsanInitAtFunctionEntry(Function );
@@ -713,6 +719,7 @@
   bool UseAfterScope;
   AsanDetectStackUseAfterReturnMode UseAfterReturn;
   Type *IntptrTy;
+  Type *Int8PtrTy;
   ShadowMapping Mapping;
   FunctionCallee AsanHandleNoReturnFunc;
   FunctionCallee AsanPtrCmpFunction, AsanPtrSubFunction;
@@ -1361,6 +1368,15 @@
 return IRB.CreateAdd(Shadow, ShadowBase);
 }
 
+void AddressSanitizer::encodeMemToShadowInfo(int64_t *AccessInfo) {
+  *AccessInfo +=
+  (Mapping.Scale << AsanAccessInfo::MappingScaleShift) +
+  (Mapping.OrShadowOffset << AsanAccessInfo::OrShadowOffsetShift);
+  if (LocalDynamicShadow || Mapping.InGlobal) {
+// TODO(kstoimenov): for now fail.
+  }
+}
+
 // Instrument memset/memmove/memcpy
 void AddressSanitizer::instrumentMemIntrinsic(MemIntrinsic *MI) {
   IRBuilder<> IRB(MI);
@@ -1742,12 +1758,25 @@
   size_t AccessSizeIndex = TypeSizeToSizeIndex(TypeSize);
 
   if (UseCalls) {
-if (Exp == 0)
-  IRB.CreateCall(AsanMemoryAccessCallback[IsWrite][0][AccessSizeIndex],
- AddrLong);
-else
-  IRB.CreateCall(AsanMemoryAccessCallback[IsWrite][1][AccessSizeIndex],
- {AddrLong, ConstantInt::get(IRB.getInt32Ty(), Exp)});
+if (ClOptimizeCallbacks) {
+  Value *Ptr8 = IRB.CreatePointerCast(Addr, Int8PtrTy);
+  Module *M = IRB.GetInsertBlock()->getParent()->getParent();
+  int64_t AccessInfo =
+  (IsWrite << AsanAccessInfo::IsWriteShift) +
+  (AccessSizeIndex << AsanAccessInfo::AccessSizeIndexShift);
+  encodeMemToShadowInfo();
+  IRB.CreateCall(
+  Intrinsic::getDeclaration(M, Intrinsic::asan_check_memaccess),
+  {Ptr8, ConstantInt::get(IRB.getInt64Ty(), Mapping.Offset),
+   ConstantInt::get(IRB.getInt32Ty(), AccessInfo)});
+} else {
+  if (Exp == 0)
+IRB.CreateCall(AsanMemoryAccessCallback[IsWrite][0][AccessSizeIndex],
+   AddrLong);
+  else
+IRB.CreateCall(AsanMemoryAccessCallback[IsWrite][1][AccessSizeIndex],
+   {AddrLong, ConstantInt::get(IRB.getInt32Ty(), Exp)});
+}
 return;
   }
 
Index: llvm/lib/Target/X86/X86RegisterInfo.td
===
--- llvm/lib/Target/X86/X86RegisterInfo.td
+++ llvm/lib/Target/X86/X86RegisterInfo.td
@@ -436,6 +436,12 @@
  (add RAX, RCX, RDX, RSI, RDI, R8, R9, R10, R11,
   RBX, R14, R15, R12, R13, RBP, RSP, RIP)>;
 
+// GR64 - 64-bit GPRs without R8 and RIP. Could be used when emitting code for
+// intrinsics, which use implict input registers.
+def GR64NoR8 : RegisterClass<"X86", [i64], 64,

[PATCH] D107703: [AST][clangd] Expose documentation of Attrs on hover.

2021-08-12 Thread Sam McCall via Phabricator via cfe-commits
This revision was landed with ongoing or failed builds.
This revision was automatically updated to reflect the committed changes.
sammccall marked 3 inline comments as done.
Closed by commit rG18f9e25ce1fa: [AST][clangd] Expose documentation of Attrs on 
hover. (authored by sammccall).

Changed prior to commit:
  https://reviews.llvm.org/D107703?vs=365601=366068#toc

Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D107703/new/

https://reviews.llvm.org/D107703

Files:
  clang-tools-extra/clangd/Hover.cpp
  clang-tools-extra/clangd/unittests/HoverTests.cpp
  clang/include/clang/AST/Attr.h
  clang/lib/AST/CMakeLists.txt
  clang/unittests/AST/AttrTest.cpp
  clang/unittests/AST/CMakeLists.txt
  clang/utils/TableGen/ClangAttrEmitter.cpp
  clang/utils/TableGen/TableGen.cpp
  clang/utils/TableGen/TableGenBackends.h

Index: clang/utils/TableGen/TableGenBackends.h
===
--- clang/utils/TableGen/TableGenBackends.h
+++ clang/utils/TableGen/TableGenBackends.h
@@ -61,6 +61,7 @@
llvm::raw_ostream );
 void EmitClangAttrNodeTraverse(llvm::RecordKeeper ,
llvm::raw_ostream );
+void EmitClangAttrDocTable(llvm::RecordKeeper , llvm::raw_ostream );
 
 void EmitClangDiagsDefs(llvm::RecordKeeper , llvm::raw_ostream ,
 const std::string );
Index: clang/utils/TableGen/TableGen.cpp
===
--- clang/utils/TableGen/TableGen.cpp
+++ clang/utils/TableGen/TableGen.cpp
@@ -30,6 +30,7 @@
   GenClangAttrSubjectMatchRulesParserStringSwitches,
   GenClangAttrImpl,
   GenClangAttrList,
+  GenClangAttrDocTable,
   GenClangAttrSubjectMatchRuleList,
   GenClangAttrPCHRead,
   GenClangAttrPCHWrite,
@@ -115,6 +116,8 @@
"Generate clang attribute implementations"),
 clEnumValN(GenClangAttrList, "gen-clang-attr-list",
"Generate a clang attribute list"),
+clEnumValN(GenClangAttrDocTable, "gen-clang-attr-doc-table",
+   "Generate a table of attribute documentation"),
 clEnumValN(GenClangAttrSubjectMatchRuleList,
"gen-clang-attr-subject-match-rule-list",
"Generate a clang attribute subject match rule list"),
@@ -280,6 +283,9 @@
   case GenClangAttrList:
 EmitClangAttrList(Records, OS);
 break;
+  case GenClangAttrDocTable:
+EmitClangAttrDocTable(Records, OS);
+break;
   case GenClangAttrSubjectMatchRuleList:
 EmitClangAttrSubjectMatchRuleList(Records, OS);
 break;
Index: clang/utils/TableGen/ClangAttrEmitter.cpp
===
--- clang/utils/TableGen/ClangAttrEmitter.cpp
+++ clang/utils/TableGen/ClangAttrEmitter.cpp
@@ -4210,6 +4210,42 @@
   getPragmaAttributeSupport(Records).generateParsingHelpers(OS);
 }
 
+void EmitClangAttrDocTable(RecordKeeper , raw_ostream ) {
+  emitSourceFileHeader("Clang attribute documentation", OS);
+
+  OS << R"cpp(
+  #include "clang/AST/Attr.h"
+  #include "llvm/ADT/StringRef.h"
+  )cpp";
+  std::vector Attrs = Records.getAllDerivedDefinitions("Attr");
+  for (const auto *A : Attrs) {
+if (!A->getValueAsBit("ASTNode"))
+  continue;
+std::vector Docs = A->getValueAsListOfDefs("Documentation");
+for (const auto *D : Docs) {
+  OS << "\nstatic const char AttrDoc_" << A->getName() << "[] = "
+ << "R\"reST("
+ << D->getValueAsOptionalString("Content").getValueOr("").trim()
+ << ")reST\";\n";
+  // Only look at the first documentation if there are several.
+  // (Currently there's only one such attr, revisit if this becomes common).
+  break;
+}
+  }
+  OS << R"cpp(
+  static const llvm::StringRef AttrDoc[] = {
+  #define ATTR(NAME) AttrDoc_##NAME,
+  #include "clang/Basic/AttrList.inc"
+  };
+
+  llvm::StringRef clang::Attr::getDocumentation(clang::attr::Kind K) {
+if(K < llvm::array_lengthof(AttrDoc))
+  return AttrDoc[K];
+return "";
+  }
+  )cpp";
+}
+
 enum class SpellingKind {
   GNU,
   CXX11,
Index: clang/unittests/AST/CMakeLists.txt
===
--- clang/unittests/AST/CMakeLists.txt
+++ clang/unittests/AST/CMakeLists.txt
@@ -15,6 +15,7 @@
   ASTTraverserTest.cpp
   ASTTypeTraitsTest.cpp
   ASTVectorTest.cpp
+  AttrTest.cpp
   CommentLexer.cpp
   CommentParser.cpp
   CommentTextTest.cpp
Index: clang/unittests/AST/AttrTest.cpp
===
--- /dev/null
+++ clang/unittests/AST/AttrTest.cpp
@@ -0,0 +1,24 @@
+//===- unittests/AST/AttrTests.cpp --- Attribute tests ===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//

[clang] 18f9e25 - [AST][clangd] Expose documentation of Attrs on hover.

2021-08-12 Thread Sam McCall via cfe-commits

Author: Sam McCall
Date: 2021-08-12T21:16:37+02:00
New Revision: 18f9e25ce1fa43f8663bd03f908ef9b27a0788f8

URL: 
https://github.com/llvm/llvm-project/commit/18f9e25ce1fa43f8663bd03f908ef9b27a0788f8
DIFF: 
https://github.com/llvm/llvm-project/commit/18f9e25ce1fa43f8663bd03f908ef9b27a0788f8.diff

LOG: [AST][clangd] Expose documentation of Attrs on hover.

This adds a method to Attr to get at the documentation programmatically.

Differential Revision: https://reviews.llvm.org/D107703

Added: 
clang/unittests/AST/AttrTest.cpp

Modified: 
clang-tools-extra/clangd/Hover.cpp
clang-tools-extra/clangd/unittests/HoverTests.cpp
clang/include/clang/AST/Attr.h
clang/lib/AST/CMakeLists.txt
clang/unittests/AST/CMakeLists.txt
clang/utils/TableGen/ClangAttrEmitter.cpp
clang/utils/TableGen/TableGen.cpp
clang/utils/TableGen/TableGenBackends.h

Removed: 




diff  --git a/clang-tools-extra/clangd/Hover.cpp 
b/clang-tools-extra/clangd/Hover.cpp
index 228cd192e0576..d16a2ebcbfd7e 100644
--- a/clang-tools-extra/clangd/Hover.cpp
+++ b/clang-tools-extra/clangd/Hover.cpp
@@ -731,7 +731,7 @@ llvm::Optional getHoverContents(const Attr *A, 
ParsedAST ) {
 llvm::raw_string_ostream OS(HI.Definition);
 A->printPretty(OS, AST.getASTContext().getPrintingPolicy());
   }
-  // FIXME: attributes have documentation, can we get at that?
+  HI.Documentation = Attr::getDocumentation(A->getKind()).str();
   return HI;
 }
 

diff  --git a/clang-tools-extra/clangd/unittests/HoverTests.cpp 
b/clang-tools-extra/clangd/unittests/HoverTests.cpp
index 5841e7166abfa..54a27b7483512 100644
--- a/clang-tools-extra/clangd/unittests/HoverTests.cpp
+++ b/clang-tools-extra/clangd/unittests/HoverTests.cpp
@@ -12,6 +12,7 @@
 #include "TestIndex.h"
 #include "TestTU.h"
 #include "index/MemIndex.h"
+#include "clang/AST/Attr.h"
 #include "clang/Basic/Specifiers.h"
 #include "clang/Index/IndexSymbol.h"
 #include "llvm/ADT/None.h"
@@ -2384,7 +2385,7 @@ TEST(Hover, All) {
  HI.Name = "nonnull";
  HI.Kind = index::SymbolKind::Unknown; // FIXME: no suitable value
  HI.Definition = "__attribute__((nonnull))";
- HI.Documentation = ""; // FIXME
+ HI.Documentation = Attr::getDocumentation(attr::NonNull).str();
}},
   };
 

diff  --git a/clang/include/clang/AST/Attr.h b/clang/include/clang/AST/Attr.h
index dbfecc1250490..651f98adc7330 100644
--- a/clang/include/clang/AST/Attr.h
+++ b/clang/include/clang/AST/Attr.h
@@ -109,6 +109,8 @@ class Attr : public AttributeCommonInfo {
 
   // Pretty print this attribute.
   void printPretty(raw_ostream , const PrintingPolicy ) const;
+
+  static StringRef getDocumentation(attr::Kind);
 };
 
 class TypeAttr : public Attr {

diff  --git a/clang/lib/AST/CMakeLists.txt b/clang/lib/AST/CMakeLists.txt
index 35099fd0dacf8..2cb74a40b9800 100644
--- a/clang/lib/AST/CMakeLists.txt
+++ b/clang/lib/AST/CMakeLists.txt
@@ -13,6 +13,11 @@ clang_tablegen(Opcodes.inc
   SOURCE Interp/Opcodes.td
   TARGET Opcodes)
 
+clang_tablegen(AttrDocTable.cpp -gen-clang-attr-doc-table
+  -I ${CMAKE_CURRENT_SOURCE_DIR}/../../include/
+  SOURCE ${CMAKE_CURRENT_SOURCE_DIR}/../../include/clang/Basic/Attr.td
+  TARGET ClangAttrDocTable)
+
 add_clang_library(clangAST
   APValue.cpp
   ASTConcept.cpp
@@ -24,6 +29,7 @@ add_clang_library(clangAST
   ASTImporterLookupTable.cpp
   ASTStructuralEquivalence.cpp
   ASTTypeTraits.cpp
+  AttrDocTable.cpp
   AttrImpl.cpp
   Comment.cpp
   CommentBriefParser.cpp

diff  --git a/clang/unittests/AST/AttrTest.cpp 
b/clang/unittests/AST/AttrTest.cpp
new file mode 100644
index 0..38e723f3ee090
--- /dev/null
+++ b/clang/unittests/AST/AttrTest.cpp
@@ -0,0 +1,24 @@
+//===- unittests/AST/AttrTests.cpp --- Attribute tests 
===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+
+#include "clang/AST/Attr.h"
+#include "clang/Basic/AttrKinds.h"
+#include "gmock/gmock.h"
+#include "gtest/gtest.h"
+
+using namespace clang;
+
+namespace {
+
+TEST(Attr, Doc) {
+  EXPECT_THAT(Attr::getDocumentation(attr::Used).str(),
+  testing::HasSubstr("The compiler must emit the definition even "
+ "if it appears to be unused"));
+}
+
+} // namespace

diff  --git a/clang/unittests/AST/CMakeLists.txt 
b/clang/unittests/AST/CMakeLists.txt
index b04e2bdc20e8b..e33c74d7ce720 100644
--- a/clang/unittests/AST/CMakeLists.txt
+++ b/clang/unittests/AST/CMakeLists.txt
@@ -15,6 +15,7 @@ add_clang_unittest(ASTTests
   ASTTraverserTest.cpp
   ASTTypeTraitsTest.cpp
   ASTVectorTest.cpp
+  AttrTest.cpp
   CommentLexer.cpp
   CommentParser.cpp
   CommentTextTest.cpp

diff  --git 

[PATCH] D107703: [AST][clangd] Expose documentation of Attrs on hover.

2021-08-12 Thread Sam McCall via Phabricator via cfe-commits
sammccall marked 9 inline comments as done.
sammccall added inline comments.



Comment at: clang/unittests/AST/AttrTest.cpp:19
+TEST(Attr, Doc) {
+  EXPECT_THAT(Attr::getDocumentation(attr::Used),
+  testing::HasSubstr("The compiler must emit the definition even "

aaron.ballman wrote:
> It seems this is failing the premerge CI -- I think you need a call to 
> `.str()` in here to convert the `StringRef` to a `std::string`?
Thanks - no idea why this only breaks MSVC, but gmock is a subtle beast...



Comment at: clang/utils/TableGen/ClangAttrEmitter.cpp:4237
+  static const llvm::StringRef AttrDoc[] = {
+  #define ATTR(NAME) AttrDoc_##NAME,
+  #include "clang/Basic/AttrList.inc"

aaron.ballman wrote:
> kadircet wrote:
> > i am not well-versed in tablegen, so sorry if i am being dense here, butt 
> > what happens to the attributes we skipped above (e.g. the ones without a 
> > `ASTNode` flag)?
> > 
> > Maybe we should be emitting a `... AttrDoc_X[] = "";` for all attributes, 
> > no matter what?
> The ones without an AST node don't get an `attr::Kind` enumeration generated 
> for them, so I believe this interface is safe.
Right, all those extra strings would just tickle -Wunused :-(

I'd love to have an API that can also be used for attrs with ASTNode=0 (many 
are documented!). However:
 - for the motivating use case (hover), we can only trigger when we find an AST 
node anyway (sadly)
 - the obvious alternative is AttributeCommonInfo::Kind, (i.e. ParsedAttr 
kind), which isn't actually better, just differently bad. e.g. there's one 
ParsedAttr kind for `interrupt`, but three target-specific `Attr` kinds, each 
of which is documented separately. For hover you want to get the right one, and 
ParsedAttr kind can't choose it.



Comment at: clang/utils/TableGen/ClangAttrEmitter.cpp:4231
+  // Only look at the first documentation if there are several.
+  // (As of now, only one attribute has multiple documentation entries).
+  break;

kadircet wrote:
> not sure if this comment will stay useful.
I want a comment to avoid a chesterton's fence:
 - the motivation for doing something lazy is that this is really rare
 - it's sensible to revisit this if it stops being rare

Reworded it to make this more explicit.


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D107703/new/

https://reviews.llvm.org/D107703

___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D107836: [Attributes]: refactor to expose ParsedAttrInfo::acceptsLangOpts. NFC

2021-08-12 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman accepted this revision.
aaron.ballman added a comment.
This revision is now accepted and ready to land.

LGTM! If @john.brawn has concerns, we can address them post commit.




Comment at: clang/include/clang/Sema/ParsedAttr.h:96
+  /// Check if this attribute is allowed by the language we are compiling.
+  virtual bool acceptsLangOpts(const LangOptions ) const { return true; }
+

sammccall wrote:
> aaron.ballman wrote:
> > sammccall wrote:
> > > aaron.ballman wrote:
> > > > Plugin attributes inherit from `ParsedAttrInfo`, not `ParsedAttr`, so 
> > > > one downside to this change is that plugin authors no longer have a way 
> > > > to diagnose language options with a custom diagnostic; all they can get 
> > > > is "attribute ignored".
> > > > 
> > > > Perhaps another approach is to add an output parameter so the overrider 
> > > > can signify whether the language options are valid or not (because it's 
> > > > plausible that the plugin wants to diagnose the language options but 
> > > > they're still valid enough that the attribute should be accepted)?
> > > > 
> > > > Plugin attributes inherit from ParsedAttrInfo, not ParsedAttr, so one 
> > > > downside to this change is that plugin authors no longer have a way to 
> > > > diagnose language options with a custom diagnostic; all they can get is 
> > > > "attribute ignored".
> > > 
> > > This is less flexible, indeed. What's not clear to me is:
> > >  - do we know of any real plugins where the ability to use a custom 
> > > diagnostic here is important? Hypothetical flexibility may not be worth 
> > > keeping.
> > >  - if custom diagnostics are needed, can they be emitted when the 
> > > attribute is handled instead?
> > >  - why we'd need this flexibility for LangOpts but not Target 
> > > (existsInTarget)
> > > 
> > > > Perhaps another approach is to add an output parameter so the overrider 
> > > > can signify whether the language options are valid or not (because it's 
> > > > plausible that the plugin wants to diagnose the language options but 
> > > > they're still valid enough that the attribute should be accepted)?
> > > 
> > > diagLangOpts already returns bool.
> > > 
> > > The blocking issue with the diagLangOpts signature for code-completion 
> > > purposes isn't actually the diagnostics (completion suppresses them), 
> > > it's rather that you have to construct a ParsedAttr  in order to emit 
> > > them, which isn't easy to do "out of thin air".
> > > do we know of any real plugins where the ability to use a custom 
> > > diagnostic here is important? Hypothetical flexibility may not be worth 
> > > keeping.
> > 
> > We don't know how plugins are being used and we have to assume Hryum's Law 
> > bites us just as much as anyone else. I'm fine potentially breaking plugins 
> > so long as we're still leaving them with the ability to do what they were 
> > previously doing. However, @john.brawn (the attribute plugin author) might 
> > know more here on the usage front.
> > 
> > > if custom diagnostics are needed, can they be emitted when the attribute 
> > > is handled instead?
> > 
> > Good question! I think that might work -- they get access to `Sema` and so 
> > they can check the language options and produce diagnostics from there. It 
> > might mean slight behavioral changes (if we used to bail early on a lang 
> > opt mismatch, it means we might get different diagnostics by the delay 
> > until the attribute is handled), but I think those are reasonable.
> > 
> > > why we'd need this flexibility for LangOpts but not Target 
> > > (existsInTarget)
> > 
> > Targets are a bit different -- you're in one target and that's it (so you 
> > either support the attribute for that target or not), but language options 
> > can have interactions between them (attribute may require something like 
> > CUDA to be enabled and it may also require some other CUDA-specific option 
> > to be enabled, and it wants to produce a nice diagnostic about that rather 
> > than just saying the attribute is ignored).
> > 
> > > The blocking issue with the diagLangOpts signature for code-completion 
> > > purposes isn't actually the diagnostics (completion suppresses them), 
> > > it's rather that you have to construct a ParsedAttr in order to emit 
> > > them, which isn't easy to do "out of thin air".
> > 
> > Ahh, I had missed that.
> > 
> > Given that the user can still do custom diagnostics when handling the 
> > attribute itself, I think this change is reasonable as-is. However, I think 
> > you should add a mention to the release notes that 1) the interface changed 
> > for plugin authors, and 2) the new approach to custom diagnostics for 
> > language options is to diagnose them when handling the attribute.
> > We don't know how plugins are being used and we have to assume Hryum's Law 
> > bites us just as much as anyone else. I'm fine potentially breaking plugins 
> > so long as we're still leaving them with the 

[PATCH] D107002: [PowerPC] Implement XL compatibility builtin __addex

2021-08-12 Thread Stefan Pintilie via Phabricator via cfe-commits
stefanp accepted this revision.
stefanp added a comment.

Thank you for adding the `DiagGroup`.
LGTM.


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D107002/new/

https://reviews.llvm.org/D107002

___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D107933: [clang] Expose unreachable fallthrough annotation warning

2021-08-12 Thread David Blaikie via Phabricator via cfe-commits
dblaikie added a comment.

In D107933#2942023 , @xbolva00 wrote:

> GCC does not warn (with common -Wall) for this case, right? I think Clang 
> should not as well.
>
> ImplicitFallthroughUnreachable could be enabled with -Wunreachable-code, if 
> you think we should have it.

Yeah, some of that was discussed on the bug: 
https://bugs.llvm.org/show_bug.cgi?id=51094 & I'd still be in favor of that 
sort of direction. I might go so far as to say: Maybe we should drop this 
warning flag (and/or move it under -Wunreachable-code - questionable, I don't 
think anyone's really using that, it's pretty noisy still, I think) entirely 
even if no one's willing to reimplement it more robustly... not sure.


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D107933/new/

https://reviews.llvm.org/D107933

___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[libunwind] 2f1ee56 - [unwind] Handle UNW_X86_64_RIP register

2021-08-12 Thread Vitaly Buka via cfe-commits

Author: Vitaly Buka
Date: 2021-08-12T12:08:07-07:00
New Revision: 2f1ee56f3cb8adb5aeadba3f66a8fc39fba1604d

URL: 
https://github.com/llvm/llvm-project/commit/2f1ee56f3cb8adb5aeadba3f66a8fc39fba1604d
DIFF: 
https://github.com/llvm/llvm-project/commit/2f1ee56f3cb8adb5aeadba3f66a8fc39fba1604d.diff

LOG: [unwind] Handle UNW_X86_64_RIP register

In some binaries, built with clang/lld, libunwind crashes
with "unsupported x86_64 register" for regNum == 16:

Differential Revision: https://reviews.llvm.org/D107919

Added: 


Modified: 
libunwind/src/Registers.hpp
libunwind/test/libunwind_01.pass.cpp

Removed: 




diff  --git a/libunwind/src/Registers.hpp b/libunwind/src/Registers.hpp
index aea84cc227217..8f1e4272049d8 100644
--- a/libunwind/src/Registers.hpp
+++ b/libunwind/src/Registers.hpp
@@ -339,7 +339,7 @@ inline bool Registers_x86_64::validRegister(int regNum) 
const {
 return true;
   if (regNum < 0)
 return false;
-  if (regNum > 15)
+  if (regNum > 16)
 return false;
   return true;
 }
@@ -347,6 +347,7 @@ inline bool Registers_x86_64::validRegister(int regNum) 
const {
 inline uint64_t Registers_x86_64::getRegister(int regNum) const {
   switch (regNum) {
   case UNW_REG_IP:
+  case UNW_X86_64_RIP:
 return _registers.__rip;
   case UNW_REG_SP:
 return _registers.__rsp;
@@ -389,6 +390,7 @@ inline uint64_t Registers_x86_64::getRegister(int regNum) 
const {
 inline void Registers_x86_64::setRegister(int regNum, uint64_t value) {
   switch (regNum) {
   case UNW_REG_IP:
+  case UNW_X86_64_RIP:
 _registers.__rip = value;
 return;
   case UNW_REG_SP:
@@ -449,6 +451,7 @@ inline void Registers_x86_64::setRegister(int regNum, 
uint64_t value) {
 inline const char *Registers_x86_64::getRegisterName(int regNum) {
   switch (regNum) {
   case UNW_REG_IP:
+  case UNW_X86_64_RIP:
 return "rip";
   case UNW_REG_SP:
 return "rsp";

diff  --git a/libunwind/test/libunwind_01.pass.cpp 
b/libunwind/test/libunwind_01.pass.cpp
index 191684d56fe92..277e3e6ded4f4 100644
--- a/libunwind/test/libunwind_01.pass.cpp
+++ b/libunwind/test/libunwind_01.pass.cpp
@@ -1,5 +1,6 @@
 #include 
 #include 
+#include 
 
 void backtrace(int lower_bound) {
   unw_context_t context;
@@ -55,10 +56,83 @@ void test_no_info() {
 abort();
 }
 
+void test_reg_names() {
+  unw_context_t context;
+  unw_getcontext();
+
+  unw_cursor_t cursor;
+  unw_init_local(, );
+
+  int max_reg_num = -100;
+#if defined(__i386__)
+  max_reg_num = 7;
+#elif defined(__x86_64__)
+  max_reg_num = 32;
+#endif
+
+  const char prefix[] = "unknown";
+  for (int i = -2; i < max_reg_num; ++i) {
+if (strncmp(prefix, unw_regname(, i), sizeof(prefix) - 1) == 0)
+  abort();
+  }
+
+  if (strncmp(prefix, unw_regname(, max_reg_num + 1),
+  sizeof(prefix) - 1) != 0)
+abort();
+}
+
+#if defined(__x86_64__)
+void test_reg_get_set() {
+  unw_context_t context;
+  unw_getcontext();
+
+  unw_cursor_t cursor;
+  unw_init_local(, );
+
+  for (int i = 0; i < 17; ++i) {
+const unw_word_t set_value = 7;
+if (unw_set_reg(, i, set_value) != UNW_ESUCCESS)
+  abort();
+
+unw_word_t get_value = 0;
+if (unw_get_reg(, i, _value) != UNW_ESUCCESS)
+  abort();
+
+if (set_value != get_value)
+  abort();
+  }
+}
+
+void test_fpreg_get_set() {
+  unw_context_t context;
+  unw_getcontext();
+
+  unw_cursor_t cursor;
+  unw_init_local(, );
+
+  // get/set is not implemented for x86_64 fpregs.
+  for (int i = 17; i < 33; ++i) {
+const unw_fpreg_t set_value = 7;
+if (unw_set_fpreg(, i, set_value) != UNW_EBADREG)
+  abort();
+
+unw_fpreg_t get_value = 0;
+if (unw_get_fpreg(, i, _value) != UNW_EBADREG)
+  abort();
+  }
+}
+#else
+void test_reg_get_set() {}
+void test_fpreg_get_set() {}
+#endif
+
 int main(int, char**) {
   test1(1);
   test2(1, 2);
   test3(1, 2, 3);
   test_no_info();
+  test_reg_names();
+  test_reg_get_set();
+  test_fpreg_get_set();
   return 0;
 }



___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D106509: [OpenMP][OpenACC] Implement `ompx_hold` map type modifier extension in Clang (1/2)

2021-08-12 Thread Joel E. Denny via Phabricator via cfe-commits
jdenny marked 4 inline comments as done.
jdenny added inline comments.



Comment at: clang/lib/Basic/OpenMPKinds.cpp:64
+  return OMPC_MAP_MODIFIER_unknown;
+if (!LangOpts.OpenMPExtensions && Type == OMPC_MAP_MODIFIER_ompx_hold)
   return OMPC_MAP_MODIFIER_unknown;

ABataev wrote:
> jdenny wrote:
> > ABataev wrote:
> > > jdenny wrote:
> > > > ABataev wrote:
> > > > > I would enable this since OpenMP 5.2, since in 5.2 `ompx_` is 
> > > > > officially allowed extension format.
> > > > Do you mean both `-fopenmp-version=52` and `-fopenmp-extensions` should 
> > > > be required to enable `ompx_hold`?
> > > > 
> > > > Or do you mean only `-fopenmp-version=52` should be required to enable 
> > > > `ompx_hold`, and we can drop the `-fopenmp-extensions` implementation?
> > > Second option. Actually, we can enable it if either `-fopenmp-version=52` 
> > > or `-fopenmp-extensions` is used, depends if we want to add a switch for 
> > > non-standard OpenMP extensions. If OpenMP 5.2 is on, we can just ignore 
> > > `-f[no]-openmp-extensions`. Thoughts?
> > Consider that, if `-fopenmp-version=52` is sufficient to enable all 
> > extensions using the `ompx_` prefix, then all such extensions will be 
> > enabled by default once OpenMP 5.2 is the default.  At that point, won't it 
> > be strange that standard OpenMP 5.3 or 6.0 features will be disabled by 
> > default while some features appearing in no standard will be enabled by 
> > default?
> > 
> > By that logic, it seems `-fopenmp-version=52` shouldn't be sufficient to 
> > enable extensions.  However, it seems overkill to have to specify both 
> > `-fopenmp-version=52` and `-fopenmp-extensions`.  I think 
> > `-fopenmp-extensions` is a clear enough request to enable the `ompx_` 
> > prefix regardless of the OpenMP version.
> Ok, let's move with `-fopenmp-extensions`
OK, thanks.


CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D106509/new/

https://reviews.llvm.org/D106509

___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D107836: [Attributes]: refactor to expose ParsedAttrInfo::acceptsLangOpts. NFC

2021-08-12 Thread Sam McCall via Phabricator via cfe-commits
sammccall added inline comments.



Comment at: clang/include/clang/Sema/ParsedAttr.h:96
+  /// Check if this attribute is allowed by the language we are compiling.
+  virtual bool acceptsLangOpts(const LangOptions ) const { return true; }
+

aaron.ballman wrote:
> sammccall wrote:
> > aaron.ballman wrote:
> > > Plugin attributes inherit from `ParsedAttrInfo`, not `ParsedAttr`, so one 
> > > downside to this change is that plugin authors no longer have a way to 
> > > diagnose language options with a custom diagnostic; all they can get is 
> > > "attribute ignored".
> > > 
> > > Perhaps another approach is to add an output parameter so the overrider 
> > > can signify whether the language options are valid or not (because it's 
> > > plausible that the plugin wants to diagnose the language options but 
> > > they're still valid enough that the attribute should be accepted)?
> > > 
> > > Plugin attributes inherit from ParsedAttrInfo, not ParsedAttr, so one 
> > > downside to this change is that plugin authors no longer have a way to 
> > > diagnose language options with a custom diagnostic; all they can get is 
> > > "attribute ignored".
> > 
> > This is less flexible, indeed. What's not clear to me is:
> >  - do we know of any real plugins where the ability to use a custom 
> > diagnostic here is important? Hypothetical flexibility may not be worth 
> > keeping.
> >  - if custom diagnostics are needed, can they be emitted when the attribute 
> > is handled instead?
> >  - why we'd need this flexibility for LangOpts but not Target 
> > (existsInTarget)
> > 
> > > Perhaps another approach is to add an output parameter so the overrider 
> > > can signify whether the language options are valid or not (because it's 
> > > plausible that the plugin wants to diagnose the language options but 
> > > they're still valid enough that the attribute should be accepted)?
> > 
> > diagLangOpts already returns bool.
> > 
> > The blocking issue with the diagLangOpts signature for code-completion 
> > purposes isn't actually the diagnostics (completion suppresses them), it's 
> > rather that you have to construct a ParsedAttr  in order to emit them, 
> > which isn't easy to do "out of thin air".
> > do we know of any real plugins where the ability to use a custom diagnostic 
> > here is important? Hypothetical flexibility may not be worth keeping.
> 
> We don't know how plugins are being used and we have to assume Hryum's Law 
> bites us just as much as anyone else. I'm fine potentially breaking plugins 
> so long as we're still leaving them with the ability to do what they were 
> previously doing. However, @john.brawn (the attribute plugin author) might 
> know more here on the usage front.
> 
> > if custom diagnostics are needed, can they be emitted when the attribute is 
> > handled instead?
> 
> Good question! I think that might work -- they get access to `Sema` and so 
> they can check the language options and produce diagnostics from there. It 
> might mean slight behavioral changes (if we used to bail early on a lang opt 
> mismatch, it means we might get different diagnostics by the delay until the 
> attribute is handled), but I think those are reasonable.
> 
> > why we'd need this flexibility for LangOpts but not Target (existsInTarget)
> 
> Targets are a bit different -- you're in one target and that's it (so you 
> either support the attribute for that target or not), but language options 
> can have interactions between them (attribute may require something like CUDA 
> to be enabled and it may also require some other CUDA-specific option to be 
> enabled, and it wants to produce a nice diagnostic about that rather than 
> just saying the attribute is ignored).
> 
> > The blocking issue with the diagLangOpts signature for code-completion 
> > purposes isn't actually the diagnostics (completion suppresses them), it's 
> > rather that you have to construct a ParsedAttr in order to emit them, which 
> > isn't easy to do "out of thin air".
> 
> Ahh, I had missed that.
> 
> Given that the user can still do custom diagnostics when handling the 
> attribute itself, I think this change is reasonable as-is. However, I think 
> you should add a mention to the release notes that 1) the interface changed 
> for plugin authors, and 2) the new approach to custom diagnostics for 
> language options is to diagnose them when handling the attribute.
> We don't know how plugins are being used and we have to assume Hryum's Law 
> bites us just as much as anyone else. I'm fine potentially breaking plugins 
> so long as we're still leaving them with the ability to do what they were 
> previously doing. However, @john.brawn (the attribute plugin author) might 
> know more here on the usage front.

Thanks! John, please let me know if you see this causing a problem - I'm sure 
we can find a solution but it's easier to find a good one if we know the 
requirements :-)

(This makes me curious: officially, 

[PATCH] D107836: [Attributes]: refactor to expose ParsedAttrInfo::acceptsLangOpts. NFC

2021-08-12 Thread Sam McCall via Phabricator via cfe-commits
sammccall updated this revision to Diff 366064.
sammccall added a comment.

Add release notes


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D107836/new/

https://reviews.llvm.org/D107836

Files:
  clang/docs/ReleaseNotes.rst
  clang/include/clang/Sema/ParsedAttr.h
  clang/lib/Sema/ParsedAttr.cpp
  clang/utils/TableGen/ClangAttrEmitter.cpp


Index: clang/utils/TableGen/ClangAttrEmitter.cpp
===
--- clang/utils/TableGen/ClangAttrEmitter.cpp
+++ clang/utils/TableGen/ClangAttrEmitter.cpp
@@ -3803,14 +3803,8 @@
   if (LangOpts.empty())
 return;
 
-  OS << "bool diagLangOpts(Sema , const ParsedAttr ) ";
-  OS << "const override {\n";
-  OS << "  auto  = S.LangOpts;\n";
-  OS << "  if (" << GenerateTestExpression(LangOpts) << ")\n";
-  OS << "return true;\n\n";
-  OS << "  S.Diag(Attr.getLoc(), diag::warn_attribute_ignored) ";
-  OS << "<< Attr;\n";
-  OS << "  return false;\n";
+  OS << "bool acceptsLangOpts(const LangOptions ) const override {\n";
+  OS << "  return " << GenerateTestExpression(LangOpts) << ";\n";
   OS << "}\n\n";
 }
 
Index: clang/lib/Sema/ParsedAttr.cpp
===
--- clang/lib/Sema/ParsedAttr.cpp
+++ clang/lib/Sema/ParsedAttr.cpp
@@ -180,7 +180,10 @@
 }
 
 bool ParsedAttr::diagnoseLangOpts(Sema ) const {
-  return getInfo().diagLangOpts(S, *this);
+  if (getInfo().acceptsLangOpts(S.getLangOpts()))
+return true;
+  S.Diag(getLoc(), diag::warn_attribute_ignored) << *this;
+  return false;
 }
 
 bool ParsedAttr::isTargetSpecificAttr() const {
Index: clang/include/clang/Sema/ParsedAttr.h
===
--- clang/include/clang/Sema/ParsedAttr.h
+++ clang/include/clang/Sema/ParsedAttr.h
@@ -92,11 +92,9 @@
const Decl *D) const {
 return true;
   }
-  /// Check if this attribute is allowed by the language we are compiling, and
-  /// issue a diagnostic if not.
-  virtual bool diagLangOpts(Sema , const ParsedAttr ) const {
-return true;
-  }
+  /// Check if this attribute is allowed by the language we are compiling.
+  virtual bool acceptsLangOpts(const LangOptions ) const { return true; }
+
   /// Check if this attribute is allowed when compiling for the given target.
   virtual bool existsInTarget(const TargetInfo ) const {
 return true;
Index: clang/docs/ReleaseNotes.rst
===
--- clang/docs/ReleaseNotes.rst
+++ clang/docs/ReleaseNotes.rst
@@ -86,7 +86,13 @@
 Attribute Changes in Clang
 --
 
-- ...
+- Attributes loaded as clang plugins which are sensitive to LangOpts must
+  now override ``acceptsLangOpts`` instead of ``diagLangOpts``.
+  Returning false will produce a generic "attribute ignored" diagnostic, as
+  with clang's built-in attributes.
+  If plugins want to provide richer diagnostics, they can do so when the
+  attribute is handled instead, e.g. in ``handleDeclAttribute``.
+  (This was changed in order to better support attributes in code completion).
 
 Windows Support
 ---


Index: clang/utils/TableGen/ClangAttrEmitter.cpp
===
--- clang/utils/TableGen/ClangAttrEmitter.cpp
+++ clang/utils/TableGen/ClangAttrEmitter.cpp
@@ -3803,14 +3803,8 @@
   if (LangOpts.empty())
 return;
 
-  OS << "bool diagLangOpts(Sema , const ParsedAttr ) ";
-  OS << "const override {\n";
-  OS << "  auto  = S.LangOpts;\n";
-  OS << "  if (" << GenerateTestExpression(LangOpts) << ")\n";
-  OS << "return true;\n\n";
-  OS << "  S.Diag(Attr.getLoc(), diag::warn_attribute_ignored) ";
-  OS << "<< Attr;\n";
-  OS << "  return false;\n";
+  OS << "bool acceptsLangOpts(const LangOptions ) const override {\n";
+  OS << "  return " << GenerateTestExpression(LangOpts) << ";\n";
   OS << "}\n\n";
 }
 
Index: clang/lib/Sema/ParsedAttr.cpp
===
--- clang/lib/Sema/ParsedAttr.cpp
+++ clang/lib/Sema/ParsedAttr.cpp
@@ -180,7 +180,10 @@
 }
 
 bool ParsedAttr::diagnoseLangOpts(Sema ) const {
-  return getInfo().diagLangOpts(S, *this);
+  if (getInfo().acceptsLangOpts(S.getLangOpts()))
+return true;
+  S.Diag(getLoc(), diag::warn_attribute_ignored) << *this;
+  return false;
 }
 
 bool ParsedAttr::isTargetSpecificAttr() const {
Index: clang/include/clang/Sema/ParsedAttr.h
===
--- clang/include/clang/Sema/ParsedAttr.h
+++ clang/include/clang/Sema/ParsedAttr.h
@@ -92,11 +92,9 @@
const Decl *D) const {
 return true;
   }
-  /// Check if this attribute is allowed by the language we are compiling, and
-  /// issue a diagnostic if not.
-  virtual bool diagLangOpts(Sema , const ParsedAttr ) const {
-return true;
-  }
+  

[PATCH] D107002: [PowerPC] Implement XL compatibility builtin __addex

2021-08-12 Thread Lei Huang via Phabricator via cfe-commits
lei updated this revision to Diff 366062.
lei added a comment.

Update diag id


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D107002/new/

https://reviews.llvm.org/D107002

Files:
  clang/include/clang/Basic/BuiltinsPPC.def
  clang/include/clang/Basic/DiagnosticSemaKinds.td
  clang/lib/Basic/Targets/PPC.cpp
  clang/lib/Sema/SemaChecking.cpp
  clang/test/CodeGen/builtins-ppc-xlcompat-pwr9-64bit.c
  clang/test/CodeGen/builtins-ppc-xlcompat-pwr9-error.c
  clang/test/CodeGen/builtins-ppc-xlcompat-pwr9-warning.c
  llvm/include/llvm/IR/IntrinsicsPowerPC.td
  llvm/lib/Target/PowerPC/P9InstrResources.td
  llvm/lib/Target/PowerPC/PPCInstr64Bit.td
  llvm/test/CodeGen/PowerPC/builtins-ppc-xlcompat-pwr9-64bit.ll

Index: llvm/test/CodeGen/PowerPC/builtins-ppc-xlcompat-pwr9-64bit.ll
===
--- llvm/test/CodeGen/PowerPC/builtins-ppc-xlcompat-pwr9-64bit.ll
+++ llvm/test/CodeGen/PowerPC/builtins-ppc-xlcompat-pwr9-64bit.ll
@@ -29,3 +29,14 @@
   ret double %0
 }
 declare double @llvm.ppc.insert.exp(double, i64)
+
+declare i64 @llvm.ppc.addex(i64, i64, i32 immarg)
+define dso_local i64 @call_addex_0(i64 %a, i64 %b) {
+; CHECK-LABEL: call_addex_0:
+; CHECK:   # %bb.0: # %entry
+; CHECK-NEXT:addex 3, 3, 4, 0
+; CHECK-NEXT:blr
+entry:
+  %0 = tail call i64 @llvm.ppc.addex(i64 %a, i64 %b, i32 0)
+  ret i64 %0
+}
Index: llvm/lib/Target/PowerPC/PPCInstr64Bit.td
===
--- llvm/lib/Target/PowerPC/PPCInstr64Bit.td
+++ llvm/lib/Target/PowerPC/PPCInstr64Bit.td
@@ -1670,6 +1670,13 @@
  "hashchkp $RB, $D_RA_XD", IIC_IntGeneral, []>;
 }
 
+let Interpretation64Bit = 1, isCodeGenOnly = 1, hasSideEffects = 1 in
+def ADDEX8 : Z23Form_RTAB5_CY2<31, 170, (outs g8rc:$rT),
+  (ins g8rc:$rA, g8rc:$rB, u2imm:$CY),
+  "addex $rT, $rA, $rB, $CY", IIC_IntGeneral,
+  [(set i64:$rT, (int_ppc_addex i64:$rA, i64:$rB,
+timm:$CY))]>;
+
 //===--===//
 // Instruction Patterns
 //
Index: llvm/lib/Target/PowerPC/P9InstrResources.td
===
--- llvm/lib/Target/PowerPC/P9InstrResources.td
+++ llvm/lib/Target/PowerPC/P9InstrResources.td
@@ -1430,5 +1430,6 @@
   DCBI,
   DCCCI,
   ICCCI,
-  ADDEX
+  ADDEX,
+  ADDEX8
 )> { let Unsupported = 1; }
Index: llvm/include/llvm/IR/IntrinsicsPowerPC.td
===
--- llvm/include/llvm/IR/IntrinsicsPowerPC.td
+++ llvm/include/llvm/IR/IntrinsicsPowerPC.td
@@ -1706,7 +1706,10 @@
   def int_ppc_fres
   : GCCBuiltin<"__builtin_ppc_fres">,
 Intrinsic <[llvm_float_ty], [llvm_float_ty], [IntrNoMem]>;
-  
+  def int_ppc_addex
+  : GCCBuiltin<"__builtin_ppc_addex">,
+Intrinsic<[llvm_i64_ty], [llvm_i64_ty, llvm_i64_ty, llvm_i32_ty],
+  [IntrNoMem, IntrHasSideEffects, ImmArg>]>;
   def int_ppc_fsel : GCCBuiltin<"__builtin_ppc_fsel">,
  Intrinsic<[llvm_double_ty], [llvm_double_ty, llvm_double_ty, 
   llvm_double_ty], [IntrNoMem]>;
Index: clang/test/CodeGen/builtins-ppc-xlcompat-pwr9-warning.c
===
--- /dev/null
+++ clang/test/CodeGen/builtins-ppc-xlcompat-pwr9-warning.c
@@ -0,0 +1,11 @@
+// REQUIRES: powerpc-registered-target
+// RUN: %clang_cc1 -triple powerpc64-unknown-unknown -target-cpu pwr9 \
+// RUN:   -verify %s
+
+extern unsigned long long ull;
+extern long long ll;
+
+void test_builtin_ppc_addex() {
+  long long res = __builtin_ppc_addex(ll, ll, 1); // expected-warning {{argument value 1 will result in undefined behaviour}}
+  unsigned long long res2 = __builtin_ppc_addex(ull, ull, 3); // expected-warning {{argument value 3 will result in undefined behaviour}}
+}
Index: clang/test/CodeGen/builtins-ppc-xlcompat-pwr9-error.c
===
--- clang/test/CodeGen/builtins-ppc-xlcompat-pwr9-error.c
+++ clang/test/CodeGen/builtins-ppc-xlcompat-pwr9-error.c
@@ -9,7 +9,18 @@
 // RUN:   -fsyntax-only -Wall -Werror -verify %s
 
 extern unsigned int ui;
+extern unsigned long long ull;
+extern long long ll;
 
 void test_builtin_ppc_cmprb() {
   int res = __builtin_ppc_cmprb(3, ui, ui); // expected-error {{argument value 3 is outside the valid range [0, 1]}}
 }
+
+#ifdef __PPC64__
+
+void test_builtin_ppc_addex() {
+  long long res = __builtin_ppc_addex(ll, ll, 4); // expected-error {{argument value 4 is outside the valid range [0, 3]}}
+  unsigned long long res2 = __builtin_ppc_addex(ull, ull, -1); // expected-error {{argument value -1 is outside the valid range [0, 3]}}
+}
+
+#endif

[PATCH] D107933: [clang] Expose unreachable fallthrough annotation warning

2021-08-12 Thread Dávid Bolvanský via Phabricator via cfe-commits
xbolva00 added a comment.

GCC does not warn (with common -Wall) for this case, right? I think Clang 
should not as well.

ImplicitFallthroughUnreachable could be enabled with -Wunreachable-code, if you 
think we should have it.


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D107933/new/

https://reviews.llvm.org/D107933

___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D106891: [AMDGPU] [Remarks] Emit optimization remarks for atomics generating CAS loop

2021-08-12 Thread Stanislav Mekhanoshin via Phabricator via cfe-commits
rampitec added inline comments.



Comment at: llvm/lib/CodeGen/AtomicExpandPass.cpp:631
+"at "
+ << (AI->getSyncScopeID() ? "system" : "single thread")
+ << " memory scope");

gandhi21299 wrote:
> rampitec wrote:
> > gandhi21299 wrote:
> > > rampitec wrote:
> > > > gandhi21299 wrote:
> > > > > rampitec wrote:
> > > > > > That does not help with target defined scope names, such as our 
> > > > > > "one-as" for example.
> > > > > How can I get target defined scope names?
> > > > It is right on the instruction:
> > > >   %result = atomicrmw fadd float addrspace(1)* %ptr, float 4.0 
> > > > syncscope("one-as") seq_cst
> > > > 
> > > Sorry, I meant from the LLVM API.
> > LLVMContext::getSyncScopeNames()
> I think that gives me all sync scopes available for the target. If not, which 
> sync scope in the vector corresponds to the instruction I am dealing with?
https://llvm.org/doxygen/MachineOperand_8cpp_source.html#l00474


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D106891/new/

https://reviews.llvm.org/D106891

___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D106891: [AMDGPU] [Remarks] Emit optimization remarks for atomics generating CAS loop

2021-08-12 Thread Anshil Gandhi via Phabricator via cfe-commits
gandhi21299 added inline comments.



Comment at: llvm/lib/CodeGen/AtomicExpandPass.cpp:631
+"at "
+ << (AI->getSyncScopeID() ? "system" : "single thread")
+ << " memory scope");

rampitec wrote:
> gandhi21299 wrote:
> > rampitec wrote:
> > > gandhi21299 wrote:
> > > > rampitec wrote:
> > > > > That does not help with target defined scope names, such as our 
> > > > > "one-as" for example.
> > > > How can I get target defined scope names?
> > > It is right on the instruction:
> > >   %result = atomicrmw fadd float addrspace(1)* %ptr, float 4.0 
> > > syncscope("one-as") seq_cst
> > > 
> > Sorry, I meant from the LLVM API.
> LLVMContext::getSyncScopeNames()
I think that gives me all sync scopes available for the target. If not, which 
sync scope in the vector corresponds to the instruction I am dealing with?


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D106891/new/

https://reviews.llvm.org/D106891

___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D107933: [clang] Expose unreachable fallthrough annotation warning

2021-08-12 Thread Nick Desaulniers via Phabricator via cfe-commits
nickdesaulniers added inline comments.



Comment at: clang/test/SemaCXX/switch-implicit-fallthrough.cpp:211-214
+case 224:
+  n += 400;
+case 225: // expected-warning{{unannotated fall-through between switch 
labels}} expected-note{{insert '[[clang::fallthrough]];' to silence this 
warning}} expected-note{{insert 'break;' to avoid fall-through}}
+;

These 4 lines don't add anything to the test coverage.  Remove them?


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D107933/new/

https://reviews.llvm.org/D107933

___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D107394: [AIX] "aligned" attribute does not decrease alignment

2021-08-12 Thread Steven Wan via Phabricator via cfe-commits
stevewan updated this revision to Diff 366051.
stevewan added a comment.

Rebase to latest main


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D107394/new/

https://reviews.llvm.org/D107394

Files:
  clang/lib/AST/RecordLayoutBuilder.cpp
  clang/test/Layout/aix-alignof-align-and-pack-attr.cpp


Index: clang/test/Layout/aix-alignof-align-and-pack-attr.cpp
===
--- clang/test/Layout/aix-alignof-align-and-pack-attr.cpp
+++ clang/test/Layout/aix-alignof-align-and-pack-attr.cpp
@@ -27,3 +27,23 @@
 
 // CHECK: @{{.*}}test3{{.*}}c{{.*}} = global %"struct.test3::C" 
zeroinitializer, align 16
 } // namespace test3
+
+namespace test4 {
+struct C {
+  struct CC {
+long double ld;
+  } __attribute__((aligned(2))) cc;
+} c;
+
+// CHECK: @{{.*}}test4{{.*}}c{{.*}} = global %"struct.test4::C" 
zeroinitializer, align 8
+} // namespace test4
+
+namespace test5 {
+struct C {
+  struct CC {
+long double ld;
+  } __attribute__((aligned(2), packed)) cc;
+} c;
+
+// CHECK: @{{.*}}test5{{.*}}c{{.*}} = global %"struct.test5::C" 
zeroinitializer, align 2
+} // namespace test5
Index: clang/lib/AST/RecordLayoutBuilder.cpp
===
--- clang/lib/AST/RecordLayoutBuilder.cpp
+++ clang/lib/AST/RecordLayoutBuilder.cpp
@@ -1968,6 +1968,12 @@
 }
   }
 
+  const Type *Ty = D->getType()->getBaseElementTypeUnsafe();
+  // When used as part of a typedef, the 'aligned' attribute can be used to
+  // decrease alignment.
+  bool AlignAttrCanDecreaseAlignment =
+  AlignIsRequired && Ty->getAs() != nullptr;
+
   // The AIX `power` alignment rules apply the natural alignment of the
   // "first member" if it is of a floating-point data type (or is an aggregate
   // whose recursively "first" member or element is such a type). The alignment
@@ -1978,7 +1984,7 @@
   // and zero-width bit-fields count as prior members; members of empty class
   // types marked `no_unique_address` are not considered to be prior members.
   CharUnits PreferredAlign = FieldAlign;
-  if (DefaultsToAIXPowerAlignment && !AlignIsRequired &&
+  if (DefaultsToAIXPowerAlignment && !AlignAttrCanDecreaseAlignment &&
   (FoundFirstNonOverlappingEmptyFieldForAIX || IsNaturalAlign)) {
 auto performBuiltinTypeAlignmentUpgrade = [&](const BuiltinType *BTy) {
   if (BTy->getKind() == BuiltinType::Double ||
@@ -1989,7 +1995,6 @@
   }
 };
 
-const Type *Ty = D->getType()->getBaseElementTypeUnsafe();
 if (const ComplexType *CTy = Ty->getAs()) {
   
performBuiltinTypeAlignmentUpgrade(CTy->getElementType()->castAs());
 } else if (const BuiltinType *BTy = Ty->getAs()) {


Index: clang/test/Layout/aix-alignof-align-and-pack-attr.cpp
===
--- clang/test/Layout/aix-alignof-align-and-pack-attr.cpp
+++ clang/test/Layout/aix-alignof-align-and-pack-attr.cpp
@@ -27,3 +27,23 @@
 
 // CHECK: @{{.*}}test3{{.*}}c{{.*}} = global %"struct.test3::C" zeroinitializer, align 16
 } // namespace test3
+
+namespace test4 {
+struct C {
+  struct CC {
+long double ld;
+  } __attribute__((aligned(2))) cc;
+} c;
+
+// CHECK: @{{.*}}test4{{.*}}c{{.*}} = global %"struct.test4::C" zeroinitializer, align 8
+} // namespace test4
+
+namespace test5 {
+struct C {
+  struct CC {
+long double ld;
+  } __attribute__((aligned(2), packed)) cc;
+} c;
+
+// CHECK: @{{.*}}test5{{.*}}c{{.*}} = global %"struct.test5::C" zeroinitializer, align 2
+} // namespace test5
Index: clang/lib/AST/RecordLayoutBuilder.cpp
===
--- clang/lib/AST/RecordLayoutBuilder.cpp
+++ clang/lib/AST/RecordLayoutBuilder.cpp
@@ -1968,6 +1968,12 @@
 }
   }
 
+  const Type *Ty = D->getType()->getBaseElementTypeUnsafe();
+  // When used as part of a typedef, the 'aligned' attribute can be used to
+  // decrease alignment.
+  bool AlignAttrCanDecreaseAlignment =
+  AlignIsRequired && Ty->getAs() != nullptr;
+
   // The AIX `power` alignment rules apply the natural alignment of the
   // "first member" if it is of a floating-point data type (or is an aggregate
   // whose recursively "first" member or element is such a type). The alignment
@@ -1978,7 +1984,7 @@
   // and zero-width bit-fields count as prior members; members of empty class
   // types marked `no_unique_address` are not considered to be prior members.
   CharUnits PreferredAlign = FieldAlign;
-  if (DefaultsToAIXPowerAlignment && !AlignIsRequired &&
+  if (DefaultsToAIXPowerAlignment && !AlignAttrCanDecreaseAlignment &&
   (FoundFirstNonOverlappingEmptyFieldForAIX || IsNaturalAlign)) {
 auto performBuiltinTypeAlignmentUpgrade = [&](const BuiltinType *BTy) {
   if (BTy->getKind() == BuiltinType::Double ||
@@ -1989,7 +1995,6 @@
   }
 };
 
-const Type *Ty = D->getType()->getBaseElementTypeUnsafe();
 if (const ComplexType 

[PATCH] D106030: [Clang] add support for error+warning fn attrs

2021-08-12 Thread Nick Desaulniers via Phabricator via cfe-commits
nickdesaulniers added inline comments.



Comment at: clang/lib/Sema/SemaDeclAttr.cpp:964-965
+bool match =
+(EA->isError() && NewAttrSpellingIndex < ErrorAttr::GNU_warning) ||
+(EA->isWarning() && NewAttrSpellingIndex >= ErrorAttr::GNU_warning);
+if (!match) {

aaron.ballman wrote:
> nickdesaulniers wrote:
> > aaron.ballman wrote:
> > > It's a bit tricky for me to tell from the patch -- are the enumerators in 
> > > the correct order that this logic still works for when the [[]] spelling 
> > > is used?
> > For reference, the generated `enum Spelling` looks like:
> > ```
> >  3611 public:   
> > 
> > 
> >  3612   enum Spelling { 
> > 
> > 
> >  3613 GNU_error = 0,
> > 
> > 
> >  3614 CXX11_gnu_error = 1,  
> > 
> > 
> >  3615 C2x_gnu_error = 2,
> > 
> > 
> >  3616 GNU_warning = 3,  
> > 
> > 
> >  3617 CXX11_gnu_warning = 4,
> > 
> > 
> >  3618 C2x_gnu_warning = 5,  
> > 
> > 
> >  3619   SpellingNotCalculated = 15  
> > 
> > 
> >  3620   
> > 
> > 
> >  3621   };
> > ```
> > while using `getAttributeSpellingListIndex` rather than 
> > `getNormalizedFullName` allows us to avoid a pair of string comparisons in 
> > favor of a pair of `unsigned` comparisons, we now have an issue because 
> > there are technically six spellings. (I guess it's not clear to me what's 
> > `CXX11_gnu_*` vs `C2x_gnu_*`?)  We could be explicit against checking all 
> > six rather than two comparisons.
> > 
> > Or I can use local variables with more helpful identifiers like:
> > 
> > ```
> > bool NewAttrIsError = NewAttrSpellingIndex < ErrorAttr::GNU_warning;
> > bool NewAttrIsWarning = NewAttrSpellingIndex >= ErrorAttr::GNU_warning;
> > bool Match = (EA->isError() && NewAttrIsError) || (EA->isWarning() && 
> > NewAttrIsWarning);
> > ```
> > 
> > WDYT?
> > (I guess it's not clear to me what's CXX11_gnu_* vs C2x_gnu_*?)
> 
> A bit of a historical thing. C2x `[[]]` and C++11 `[[]]` are modeled as 
> different spellings. This allows us to specify attributes with a `[[]]` 
> spelling in only one of the languages without having to do an awkward dance 
> involving language options. e.g., it makes it easier to support an attribute 
> spelled `__attribute__((foo))` and `[[vendor::foo]]` in C2x and spelled 
> `[[foo]]` in C++. it picks up the `gnu` bit in the spelling by virtue of 
> being an attribute with a `GCC` spelling -- IIRC, we needed to distinguish 
> between GCC and Clang there for some reason I no longer recall.
> 
> > WDYT?
> 
> I think the current approach is reasonable, but I think the previous approach 
> (doing the string compare) was more readable. If you have a preference for 
> using the string compare approach as it originally was, I'd be fine with that 
> now that I see how my suggestion is playing out in practice. If you'd prefer 
> to keep the current approach, I'd also be fine with that. Thank you for 
> trying this out, sorry for the hassle!
> now that I see how my suggestion is playing out in practice
> Thank you for trying this out, sorry for the hassle!

Ah, that's ok.  [[ https://www.youtube.com/watch?v=aPVLyB0Yc6I | Sometimes you 
eat the bar, sometimes the bar eats you. ]]  I've done that myself already in 
this patch when playing with llvm::Optional (and C++ default parameters).

Changed back to string comparison now.  I don't expect any of this code to be 
hot, ever.  Marking as done.



Comment at: 

[PATCH] D106030: [Clang] add support for error+warning fn attrs

2021-08-12 Thread Nick Desaulniers via Phabricator via cfe-commits
nickdesaulniers updated this revision to Diff 366050.
nickdesaulniers marked 4 inline comments as done.
nickdesaulniers added a comment.

- combine c++ w/ c test
- use -verify= rather than -D
- remove REQUIRES
- go back to string comparison


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D106030/new/

https://reviews.llvm.org/D106030

Files:
  clang/docs/ReleaseNotes.rst
  clang/include/clang/Basic/Attr.td
  clang/include/clang/Basic/AttrDocs.td
  clang/include/clang/Basic/DiagnosticFrontendKinds.td
  clang/include/clang/Basic/DiagnosticGroups.td
  clang/lib/CodeGen/CGCall.cpp
  clang/lib/CodeGen/CodeGenAction.cpp
  clang/lib/CodeGen/CodeGenModule.cpp
  clang/lib/Sema/SemaDecl.cpp
  clang/lib/Sema/SemaDeclAttr.cpp
  clang/test/CodeGen/attr-error.c
  clang/test/CodeGen/attr-warning.c
  clang/test/Frontend/backend-attribute-error-warning-optimize.c
  clang/test/Frontend/backend-attribute-error-warning.c
  clang/test/Misc/pragma-attribute-supported-attributes-list.test
  clang/test/Misc/serialized-diags-driver.c
  clang/test/Sema/attr-error.c
  clang/test/Sema/attr-warning.c
  llvm/docs/LangRef.rst
  llvm/include/llvm/IR/DiagnosticInfo.h
  llvm/lib/CodeGen/GlobalISel/IRTranslator.cpp
  llvm/lib/CodeGen/SelectionDAG/FastISel.cpp
  llvm/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp
  llvm/lib/IR/DiagnosticInfo.cpp
  llvm/test/CodeGen/X86/attr-dontcall.ll
  llvm/test/ThinLTO/X86/dontcall.ll

Index: llvm/test/ThinLTO/X86/dontcall.ll
===
--- /dev/null
+++ llvm/test/ThinLTO/X86/dontcall.ll
@@ -0,0 +1,33 @@
+; RUN: split-file %s %t
+; RUN: opt -module-summary %t/a.s -o %t/a.bc
+; RUN: opt -module-summary %t/b.s -o %t/b.bc
+; RUN: not llvm-lto2 run %t/a.bc %t/b.bc -o %t/out -save-temps 2>&1 \
+; RUN:   -r=%t/a.bc,callee,px \
+; RUN:   -r=%t/b.bc,callee,x  \
+; RUN:   -r=%t/b.bc,caller,px
+
+; TODO: As part of LTO, we check that types match, but *we don't yet check that
+; attributes match!!! What should happen if we remove "dontcall" from the
+; definition or declaration of @callee?
+
+; CHECK: call to callee marked "dontcall"
+
+;--- a.s
+target datalayout = "e-m:e-p270:32:32-p271:32:32-p272:64:64-i64:64-f80:128-n8:16:32:64-S128"
+target triple = "x86_64-unknown-linux-gnu"
+
+define i32 @callee() "dontcall" noinline {
+  ret i32 42
+}
+
+;--- b.s
+target datalayout = "e-m:e-p270:32:32-p271:32:32-p272:64:64-i64:64-f80:128-n8:16:32:64-S128"
+target triple = "x86_64-unknown-linux-gnu"
+
+declare i32 @callee() "dontcall"
+
+define i32 @caller() {
+entry:
+  %0 = call i32 @callee()
+  ret i32 %0
+}
Index: llvm/test/CodeGen/X86/attr-dontcall.ll
===
--- /dev/null
+++ llvm/test/CodeGen/X86/attr-dontcall.ll
@@ -0,0 +1,11 @@
+; RUN: not llc -global-isel=0 -fast-isel=0 -stop-after=finalize-isel %s 2>&1 | FileCheck %s
+; RUN: not llc -global-isel=0 -fast-isel=1 -stop-after=finalize-isel %s 2>&1 | FileCheck %s
+; RUN: not llc -global-isel=1 -fast-isel=0 -stop-after=irtranslator %s 2>&1 | FileCheck %s
+
+declare void @foo() "dontcall"
+define void @bar() {
+  call void @foo()
+  ret void
+}
+
+; CHECK: error: call to foo marked "dontcall"
Index: llvm/lib/IR/DiagnosticInfo.cpp
===
--- llvm/lib/IR/DiagnosticInfo.cpp
+++ llvm/lib/IR/DiagnosticInfo.cpp
@@ -401,3 +401,7 @@
 
 void OptimizationRemarkAnalysisFPCommute::anchor() {}
 void OptimizationRemarkAnalysisAliasing::anchor() {}
+
+void DiagnosticInfoDontCall::print(DiagnosticPrinter ) const {
+  DP << "call to " << getFunctionName() << " marked \"dontcall\"";
+}
Index: llvm/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp
===
--- llvm/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp
+++ llvm/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp
@@ -69,6 +69,7 @@
 #include "llvm/IR/DataLayout.h"
 #include "llvm/IR/DebugInfoMetadata.h"
 #include "llvm/IR/DerivedTypes.h"
+#include "llvm/IR/DiagnosticInfo.h"
 #include "llvm/IR/Function.h"
 #include "llvm/IR/GetElementPtrTypeIterator.h"
 #include "llvm/IR/InlineAsm.h"
@@ -7950,6 +7951,15 @@
   }
 
   if (Function *F = I.getCalledFunction()) {
+if (F->hasFnAttribute("dontcall")) {
+  unsigned LocCookie = 0;
+  if (MDNode *MD = I.getMetadata("srcloc"))
+LocCookie =
+mdconst::extract(MD->getOperand(0))->getZExtValue();
+  DiagnosticInfoDontCall D(F->getName(), LocCookie);
+  DAG.getContext()->diagnose(D);
+}
+
 if (F->isDeclaration()) {
   // Is this an LLVM intrinsic or a target-specific intrinsic?
   unsigned IID = F->getIntrinsicID();
Index: llvm/lib/CodeGen/SelectionDAG/FastISel.cpp
===
--- llvm/lib/CodeGen/SelectionDAG/FastISel.cpp
+++ llvm/lib/CodeGen/SelectionDAG/FastISel.cpp
@@ -75,6 +75,7 @@
 #include 

[PATCH] D107294: [clang-tidy] adds warning to suggest users replace symbols with words

2021-08-12 Thread Corentin Jabot via Phabricator via cfe-commits
cor3ntin added inline comments.



Comment at: 
clang-tools-extra/clang-tidy/readability/AlternativeTokensCheck.cpp:69
+  // Only insert spaces if there aren't already spaces between operators
+  StringRef SpaceBefore = std::isspace(lookahead(SM, Loc, -1)) ? "" : " ";
+  StringRef SpaceAfter =

aaron.ballman wrote:
> Hrmm, I feel like `std::isspace()` is not going to properly handle all the 
> Unicode whitespace, but I don't think we handle them all anyway as I notice 
> the lexer is using `isHorizontalWhitespace()`, `isVerticalWhitespace()`, and 
> `isWhitespace()` from `CharInfo.h`. Maybe we should use the same utility here 
> just to match the lexer? (I don't feel strongly, just tickled my spidey 
> senses.)
I just saw this comment randomly in my mail.
I agree we should not use `isspace` - it's also probably less efficient because 
of locale. And we don't want lexing to depend on the host locale.
And makes it easier to extend the set of supported whitespace if we ever do 
thatt


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D107294/new/

https://reviews.llvm.org/D107294

___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] f999312 - Recommit "[Matrix] Overload stride arg in matrix.columnwise.load/store."

2021-08-12 Thread Florian Hahn via cfe-commits

Author: Florian Hahn
Date: 2021-08-12T18:31:57+01:00
New Revision: f999312872b811b550533640b92ecb234cf5c642

URL: 
https://github.com/llvm/llvm-project/commit/f999312872b811b550533640b92ecb234cf5c642
DIFF: 
https://github.com/llvm/llvm-project/commit/f999312872b811b550533640b92ecb234cf5c642.diff

LOG: Recommit "[Matrix] Overload stride arg in matrix.columnwise.load/store."

This reverts the revert 28c04794df74ad3c38155a244729d1f8d57b9400.

The failing MLIR test that caused the revert should be fixed  in this
version.

Also includes a PPC test fix previously in 1f87c7c478a6.

Added: 


Modified: 
clang/test/CodeGen/matrix-type-builtins.c
clang/test/CodeGenCXX/matrix-type-builtins.cpp
clang/test/CodeGenObjC/matrix-type-builtins.m
llvm/docs/LangRef.rst
llvm/include/llvm/IR/Intrinsics.td
llvm/include/llvm/IR/MatrixBuilder.h
llvm/lib/Transforms/Scalar/LowerMatrixIntrinsics.cpp
llvm/test/Analysis/CostModel/PowerPC/matrix.ll
llvm/test/Transforms/LowerMatrixIntrinsics/strided-load-double.ll
llvm/test/Transforms/LowerMatrixIntrinsics/strided-store-double.ll
llvm/test/Verifier/matrix-intrinsics.ll
mlir/test/Target/LLVMIR/llvmir-intrinsics.mlir

Removed: 




diff  --git a/clang/test/CodeGen/matrix-type-builtins.c 
b/clang/test/CodeGen/matrix-type-builtins.c
index 67f5c78196878..ec0be85b7151e 100644
--- a/clang/test/CodeGen/matrix-type-builtins.c
+++ b/clang/test/CodeGen/matrix-type-builtins.c
@@ -1,4 +1,5 @@
-// RUN: %clang_cc1 -fenable-matrix -triple x86_64-apple-darwin %s -emit-llvm 
-disable-llvm-passes -o - | FileCheck %s
+// RUN: %clang_cc1 -fenable-matrix -triple x86_64-apple-darwin %s -emit-llvm 
-disable-llvm-passes -o - | FileCheck --check-prefixes=COMMON,CHECK64 %s
+// RUN: %clang_cc1 -fenable-matrix -triple i386-apple-darwin %s -emit-llvm 
-disable-llvm-passes -o - | FileCheck --check-prefixes=COMMON,CHECK32 %s
 
 // Also check we do not crash when running some middle-end passes. Most
 // importantly this includes the IR verifier, to ensure we emit valid IR.
@@ -15,30 +16,33 @@ typedef unsigned ux1x6_t __attribute__((matrix_type(1, 6)));
 typedef unsigned ux6x1_t __attribute__((matrix_type(6, 1)));
 
 void transpose_double_5x5(dx5x5_t *a) {
-  // CHECK-LABEL: define{{.*}} void @transpose_double_5x5(
-  // CHECK:[[A:%.*]] = load <25 x double>, <25 x double>* {{.*}}, 
align 8
-  // CHECK-NEXT:   [[TRANS:%.*]] = call <25 x double> 
@llvm.matrix.transpose.v25f64(<25 x double> [[A]], i32 5, i32 5)
-  // CHECK-NEXT:   [[AT_ADDR:%.*]] = bitcast [25 x double]* %a_t to <25 x 
double>*
-  // CHECK-NEXT:   store <25 x double> [[TRANS]], <25 x double>* [[AT_ADDR]], 
align 8
+  // COMMON-LABEL: define{{.*}} void @transpose_double_5x5(
+  // CHECK32:   [[A:%.*]] = load <25 x double>, <25 x double>* {{.*}}, 
align 4
+  // CHECK64:   [[A:%.*]] = load <25 x double>, <25 x double>* {{.*}}, 
align 8
+  // COMMON-NEXT:   [[TRANS:%.*]] = call <25 x double> 
@llvm.matrix.transpose.v25f64(<25 x double> [[A]], i32 5, i32 5)
+  // COMMON-NEXT:   [[AT_ADDR:%.*]] = bitcast [25 x double]* %a_t to <25 x 
double>*
+  // CHECK32-NEXT:  store <25 x double> [[TRANS]], <25 x double>* [[AT_ADDR]], 
align 4
+  // CHECK64-NEXT:  store <25 x double> [[TRANS]], <25 x double>* [[AT_ADDR]], 
align 8
+
   dx5x5_t a_t = __builtin_matrix_transpose(*a);
 }
 
 void transpose_float_3x2(fx3x2_t *a) {
-  // CHECK-LABEL: define{{.*}} void @transpose_float_3x2(
-  // CHECK:[[A:%.*]] = load <6 x float>, <6 x float>* {{.*}}, align 4
-  // CHECK-NEXT:   [[TRANS:%.*]] = call <6 x float> 
@llvm.matrix.transpose.v6f32(<6 x float> [[A]], i32 3, i32 2)
-  // CHECK-NEXT:   [[AT_ADDR:%.*]] = bitcast [6 x float]* %a_t to <6 x float>*
-  // CHECK-NEXT:   store <6 x float> [[TRANS]], <6 x float>* [[AT_ADDR]], 
align 4
+  // COMMON-LABEL: define{{.*}} void @transpose_float_3x2(
+  // COMMON:[[A:%.*]] = load <6 x float>, <6 x float>* {{.*}}, align 4
+  // COMMON-NEXT:   [[TRANS:%.*]] = call <6 x float> 
@llvm.matrix.transpose.v6f32(<6 x float> [[A]], i32 3, i32 2)
+  // COMMON-NEXT:   [[AT_ADDR:%.*]] = bitcast [6 x float]* %a_t to <6 x float>*
+  // COMMON-NEXT:   store <6 x float> [[TRANS]], <6 x float>* [[AT_ADDR]], 
align 4
 
   fx2x3_t a_t = __builtin_matrix_transpose(*a);
 }
 
 void transpose_int_20x4(ix20x4_t *a) {
-  // CHECK-LABEL: define{{.*}} void @transpose_int_20x4(
-  // CHECK: [[A:%.*]] = load <80 x i32>, <80 x i32>* {{.*}}, align 4
-  // CHECK-NEXT:[[TRANS:%.*]] = call <80 x i32> 
@llvm.matrix.transpose.v80i32(<80 x i32> [[A]], i32 20, i32 4)
-  // CHECK-NEXT:[[AT_ADDR:%.*]] = bitcast [80 x i32]* %a_t to <80 x i32>*
-  // CHECK-NEXT:store <80 x i32> [[TRANS]], <80 x i32>* [[AT_ADDR]], align 
4
+  // COMMON-LABEL: define{{.*}} void @transpose_int_20x4(
+  // COMMON: [[A:%.*]] = load <80 x i32>, <80 x i32>* {{.*}}, align 4
+  // COMMON-NEXT:[[TRANS:%.*]] = 

  1   2   3   >