[PATCH] D95714: [clang-tidy] fix modernize-use-nullptr false positive with spaceship operator comparisons

2021-02-08 Thread Conrad Poelman via Phabricator via cfe-commits
poelmanc updated this revision to Diff 322302.
poelmanc added a comment.

Capitalize `IsOrHasDescendant`, add `} namespace std` per HarborMaster feedback.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D95714

Files:
  clang-tools-extra/clang-tidy/modernize/UseNullptrCheck.cpp
  clang-tools-extra/test/clang-tidy/checkers/modernize-use-nullptr-cxx20.cpp


Index: 
clang-tools-extra/test/clang-tidy/checkers/modernize-use-nullptr-cxx20.cpp
===
--- /dev/null
+++ clang-tools-extra/test/clang-tidy/checkers/modernize-use-nullptr-cxx20.cpp
@@ -0,0 +1,34 @@
+// RUN: %check_clang_tidy -std=c++20 %s modernize-use-nullptr %t
+
+namespace std {
+struct strong_ordering {
+  int n;
+  constexpr operator int() const { return n; }
+  static const strong_ordering equal, greater, less;
+};
+constexpr strong_ordering strong_ordering::equal = {0};
+constexpr strong_ordering strong_ordering::greater = {1};
+constexpr strong_ordering strong_ordering::less = {-1};
+} // namespace std
+
+class A {
+public:
+  auto operator<=>(const A &other) const = default;
+};
+
+void test_cxx_rewritten_binary_ops() {
+  A a1, a2;
+  bool result;
+  // should not change next line to (a1 nullptr a2)
+  result = (a1 < a2);
+  // CHECK-FIXES: result = (a1 < a2);
+  // should not change next line to (a1 nullptr a2)
+  result = (a1 >= a2);
+  // CHECK-FIXES: result = (a1 >= a2);
+  int *ptr = 0;
+  // CHECK-FIXES: int *ptr = nullptr;
+  result = (a1 > (ptr == 0 ? a1 : a2));
+  // CHECK-FIXES: result = (a1 > (ptr == nullptr ? a1 : a2));
+  result = (a1 > ((a1 > (ptr == 0 ? a1 : a2)) ? a1 : a2));
+  // CHECK-FIXES: result = (a1 > ((a1 > (ptr == nullptr ? a1 : a2)) ? a1 : 
a2));
+}
Index: clang-tools-extra/clang-tidy/modernize/UseNullptrCheck.cpp
===
--- clang-tools-extra/clang-tidy/modernize/UseNullptrCheck.cpp
+++ clang-tools-extra/clang-tidy/modernize/UseNullptrCheck.cpp
@@ -41,12 +41,28 @@
   
unless(hasImplicitDestinationType(qualType(substTemplateTypeParmType(,
   unless(hasSourceExpression(hasType(sugaredNullptrType();
 
+  auto IsOrHasDescendant = [](auto InnerMatcher) {
+return anyOf(InnerMatcher, hasDescendant(InnerMatcher));
+  };
+
   return traverse(
   TK_AsIs,
-  castExpr(anyOf(ImplicitCastToNull,
- explicitCastExpr(hasDescendant(ImplicitCastToNull))),
-   unless(hasAncestor(explicitCastExpr(
-  .bind(CastSequence));
+  anyOf(castExpr(anyOf(ImplicitCastToNull,
+   
explicitCastExpr(hasDescendant(ImplicitCastToNull))),
+ unless(hasAncestor(explicitCastExpr())),
+ unless(hasAncestor(cxxRewrittenBinaryOperator(
+.bind(CastSequence),
+cxxRewrittenBinaryOperator(
+// Match rewritten operators, but verify (in the check method)
+// that if an implicit cast is found, it is not from another
+// nested rewritten operator.
+expr().bind("matchBinopOperands"),
+hasEitherOperand(IsOrHasDescendant(
+implicitCastExpr(
+ImplicitCastToNull,
+hasAncestor(cxxRewrittenBinaryOperator().bind(
+"checkBinopOperands")))
+.bind(CastSequence));
 }
 
 bool isReplaceableRange(SourceLocation StartLoc, SourceLocation EndLoc,
@@ -480,6 +496,11 @@
   const auto *NullCast = Result.Nodes.getNodeAs(CastSequence);
   assert(NullCast && "Bad Callback. No node provided");
 
+  if (Result.Nodes.getNodeAs(
+  "matchBinopOperands") !=
+  Result.Nodes.getNodeAs("checkBinopOperands"))
+return;
+
   // Given an implicit null-ptr cast or an explicit cast with an implicit
   // null-to-pointer cast within use CastSequenceVisitor to identify sequences
   // of explicit casts that can be converted into 'nullptr'.


Index: clang-tools-extra/test/clang-tidy/checkers/modernize-use-nullptr-cxx20.cpp
===
--- /dev/null
+++ clang-tools-extra/test/clang-tidy/checkers/modernize-use-nullptr-cxx20.cpp
@@ -0,0 +1,34 @@
+// RUN: %check_clang_tidy -std=c++20 %s modernize-use-nullptr %t
+
+namespace std {
+struct strong_ordering {
+  int n;
+  constexpr operator int() const { return n; }
+  static const strong_ordering equal, greater, less;
+};
+constexpr strong_ordering strong_ordering::equal = {0};
+constexpr strong_ordering strong_ordering::greater = {1};
+constexpr strong_ordering strong_ordering::less = {-1};
+} // namespace std
+
+class A {
+public:
+  auto operator<=>(const A &other) const = default;
+};
+
+void test_cxx_rewritten_binary_ops() {
+  A a1, a2;
+  bool result;
+  // should not change next line to (a1 nullptr a2)
+  result = (a

[PATCH] D96248: [OpenMP][AMDGPU] Add support for linking libomptarget bitcode

2021-02-08 Thread Jon Chesterfield via Phabricator via cfe-commits
JonChesterfield added inline comments.



Comment at: clang/lib/Driver/ToolChains/AMDGPUOpenMP.cpp:193
   CC1Args.push_back("-emit-llvm-bc");
+
+  std::string BitcodeSuffix = "amdgcn-" + GpuArch.str();

tianshilei1992 wrote:
> JonChesterfield wrote:
> > Need `if (DriverArgs.hasArg(options::OPT_nogpulib)) return;` here or we 
> > can't build the deviceRTL without already having one on disk
> FWIW, NVPTX `deviceRTLs` is built by directly calling FE, not via clang 
> driver. `clang -fopenmp -fopenmp-targets=xxx` basically consists of two 
> passes, and therefore generates two IRs, which is not what we expect. I'm not 
> sure we really need the if statement.
That explains what I was missing about the ptx cmake I think. I've had to 
locally hack around clang creating a bundle, which llvm-link chokes on, because 
cuda-device-only et al are ignored by openmp.

I think this check is right - it means nogpulib will exclude the rtl on both 
GPUs. Nvptx already has it in the control flow.

Whether RTL cmake should bypass the driver is interesting, but I think separate 
to this patch.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D96248

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


[PATCH] D96248: [OpenMP][AMDGPU] Add support for linking libomptarget bitcode

2021-02-08 Thread Pushpinder Singh via Phabricator via cfe-commits
pdhaliwal updated this revision to Diff 322298.
pdhaliwal added a comment.

- Added check for nogpulib
- Fixed diagnostic message


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D96248

Files:
  clang/include/clang/Basic/DiagnosticDriverKinds.td
  clang/include/clang/Driver/Options.td
  clang/lib/Driver/ToolChains/AMDGPUOpenMP.cpp
  clang/lib/Driver/ToolChains/CommonArgs.cpp
  clang/lib/Driver/ToolChains/CommonArgs.h
  clang/lib/Driver/ToolChains/Cuda.cpp
  clang/test/Driver/Inputs/hip_dev_lib/libomptarget-amdgcn-gfx803.bc
  clang/test/Driver/Inputs/hip_dev_lib/libomptarget-amdgcn-gfx906.bc
  clang/test/Driver/amdgpu-openmp-toolchain.c
  clang/test/Driver/openmp-offload-gpu.c

Index: clang/test/Driver/openmp-offload-gpu.c
===
--- clang/test/Driver/openmp-offload-gpu.c
+++ clang/test/Driver/openmp-offload-gpu.c
@@ -177,7 +177,7 @@
 // RUN:   -fopenmp-relocatable-target -save-temps -no-canonical-prefixes %s 2>&1 \
 // RUN:   | FileCheck -check-prefix=CHK-BCLIB-WARN %s
 
-// CHK-BCLIB-WARN: No library 'libomptarget-nvptx-cuda_80-sm_20.bc' found in the default clang lib directory or in LIBRARY_PATH. Please use --libomptarget-nvptx-bc-path to specify nvptx bitcode library.
+// CHK-BCLIB-WARN: No library 'libomptarget-nvptx-cuda_80-sm_20.bc' found in the default clang lib directory or in LIBRARY_PATH. Please use --libomptarget-device-bc-path to specify device bitcode library.
 
 /// ###
 
Index: clang/test/Driver/amdgpu-openmp-toolchain.c
===
--- clang/test/Driver/amdgpu-openmp-toolchain.c
+++ clang/test/Driver/amdgpu-openmp-toolchain.c
@@ -1,11 +1,11 @@
 // REQUIRES: amdgpu-registered-target
-// RUN:   %clang -### --target=x86_64-unknown-linux-gnu -fopenmp -fopenmp-targets=amdgcn-amd-amdhsa -Xopenmp-target=amdgcn-amd-amdhsa -march=gfx906 %s 2>&1 \
+// RUN:   env LIBRARY_PATH=%S/Inputs/hip_dev_lib %clang -### --target=x86_64-unknown-linux-gnu -fopenmp -fopenmp-targets=amdgcn-amd-amdhsa -Xopenmp-target=amdgcn-amd-amdhsa -march=gfx906 %s 2>&1 \
 // RUN:   | FileCheck %s
 
 // verify the tools invocations
 // CHECK: clang{{.*}}"-cc1" "-triple" "x86_64-unknown-linux-gnu"{{.*}}"-x" "c"{{.*}}
 // CHECK: clang{{.*}}"-cc1" "-triple" "x86_64-unknown-linux-gnu"{{.*}}"-x" "ir"{{.*}}
-// CHECK: clang{{.*}}"-cc1"{{.*}}"-triple" "amdgcn-amd-amdhsa"{{.*}}"-target-cpu" "gfx906" "-fcuda-is-device" "-emit-llvm-bc"{{.*}}
+// CHECK: clang{{.*}}"-cc1"{{.*}}"-triple" "amdgcn-amd-amdhsa"{{.*}}"-target-cpu" "gfx906" "-fcuda-is-device" "-emit-llvm-bc" "-mlink-builtin-bitcode"{{.*}}libomptarget-amdgcn-gfx906.bc"{{.*}}
 // CHECK: llvm-link{{.*}}"-o" "{{.*}}amdgpu-openmp-toolchain-{{.*}}-gfx906-linked-{{.*}}.bc"
 // CHECK: llc{{.*}}amdgpu-openmp-toolchain-{{.*}}-gfx906-linked-{{.*}}.bc" "-mtriple=amdgcn-amd-amdhsa" "-mcpu=gfx906" "-filetype=obj" "-o"{{.*}}amdgpu-openmp-toolchain-{{.*}}-gfx906-{{.*}}.o"
 // CHECK: lld{{.*}}"-flavor" "gnu" "--no-undefined" "-shared" "-o"{{.*}}amdgpu-openmp-toolchain-{{.*}}.out" "{{.*}}amdgpu-openmp-toolchain-{{.*}}-gfx906-{{.*}}.o"
@@ -34,3 +34,9 @@
 // CHECK-PHASES: 15: assembler, {14}, object, (host-openmp)
 // CHECK-PHASES: 16: linker, {4, 15}, image, (host-openmp)
 
+// handling of --libomptarget-device-bc-path
+// RUN:   %clang -### --target=x86_64-unknown-linux-gnu -fopenmp -fopenmp-targets=amdgcn-amd-amdhsa -Xopenmp-target=amdgcn-amd-amdhsa -march=gfx803 --libomptarget-device-bc-path=%S/Inputs/hip_dev_lib/libomptarget-amdgcn-gfx803.bc %s 2>&1 | FileCheck %s --check-prefix=CHECK-LIBOMPTARGET
+// CHECK-LIBOMPTARGET: clang{{.*}}"-cc1"{{.*}}"-triple" "amdgcn-amd-amdhsa"{{.*}}"-target-cpu" "gfx803" "-fcuda-is-device" "-emit-llvm-bc" "-mlink-builtin-bitcode"{{.*}}Inputs/hip_dev_lib/libomptarget-amdgcn-gfx803.bc"{{.*}}
+
+// RUN:   %clang -### --target=x86_64-unknown-linux-gnu -fopenmp -fopenmp-targets=amdgcn-amd-amdhsa -Xopenmp-target=amdgcn-amd-amdhsa -march=gfx803 -nogpulib %s 2>&1 | FileCheck %s --check-prefix=CHECK-NOGPULIB
+// CHECK-NOGPULIB-NOT: clang{{.*}}"-cc1"{{.*}}"-triple" "amdgcn-amd-amdhsa"{{.*}}"-target-cpu" "gfx803" "-fcuda-is-device" "-emit-llvm-bc" "-mlink-builtin-bitcode"{{.*}}libomptarget-amdgcn-gfx803.bc"{{.*}}
Index: clang/lib/Driver/ToolChains/Cuda.cpp
===
--- clang/lib/Driver/ToolChains/Cuda.cpp
+++ clang/lib/Driver/ToolChains/Cuda.cpp
@@ -749,56 +749,9 @@
 CudaVersionToString(CudaInstallation.version(;
 
   if (DeviceOffloadingKind == Action::OFK_OpenMP) {
-SmallVector LibraryPaths;
-// Add user defined library paths from LIBRARY_PATH.
-llvm::Optional LibPath =
-llvm::sys::Process::GetEnv("LIBRARY_PATH");
-if (LibPath) {
-  SmallVector Frags;
-  const char EnvPathSeparatorStr[] = {llvm::sys::EnvPath

[PATCH] D96268: [-Wcompletion-handler] Support checks with builtins

2021-02-08 Thread Valeriy Savchenko via Phabricator via cfe-commits
vsavchenko added inline comments.



Comment at: clang/lib/Analysis/CalledOnceCheck.cpp:343
+case Builtin::BI__builtin_expect_with_probability: {
+  assert(CE->getNumArgs() >= 2);
+

NoQ wrote:
> Otherwise it's a compile error and analysis based warnings aren't run when 
> there are compile errors, right? If it was a normal function call there's no 
> way we would have gotten away with such assertion. Like, even if it was a 
> standard library function the user could still override that. But for 
> builtins I guess that should work.
Exactly, we have a somewhat similar assertion in the analyzer


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D96268

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


[PATCH] D93003: [libunwind][ELF] Hide unw_getcontext with LIBUNWIND_HIDE_SYMBOLS

2021-02-08 Thread Ryan Prichard via Phabricator via cfe-commits
rprichard added inline comments.



Comment at: libunwind/src/assembly.h:82
   .globl SYMBOL_NAME(aliasname) SEPARATOR  
\
-  WEAK_SYMBOL(aliasname) SEPARATOR 
\
+  EXPORT_SYMBOL(SYMBOL_NAME(aliasname)) SEPARATOR  
\
   SYMBOL_NAME(aliasname) = SYMBOL_NAME(name)

steven_wu wrote:
> rprichard wrote:
> > compnerd wrote:
> > > Does this not change the behaviour on MachO?  This symbol is now 
> > > `private_extern` rather than a `weak_reference`.  A weak reference will 
> > > be set to 0 by the loader if it is not found, and a `private_extern` is a 
> > > strong internal reference.
> > Is `.weak_reference` the right directive to use here, instead of 
> > `.weak_definition`? We're defining a symbol (`aliasname`) and setting its 
> > value to that of another symbol (`name`).
> > 
> > I think marking `unw_*` weak is intended to let some other strong 
> > definition override it. Its value won't ever be set to 0.
> > 
> > Currently on Mach-O, the hide-symbols flag hides almost everything 
> > (including `_Unwind_*`) but leaves all of the `unw_*` alias symbols as 
> > extern (and not private-extern) and not weak. With my change, they're still 
> > not weak, but they're private-extern.
> > 
> > libunwind's current assembly.h behavior for a weak alias:
> > 
> > .globl aliasname
> > .weak_reference aliasname
> > aliasname = name
> > 
> > The LLVM Mach-O assembler ignores the `.weak_reference` directive. If I 
> > change it to `.weak_definition`, it is still ignored. AFAICT, the LLVM 
> > assembler uses the WeakDef/WeakRef attributes from the `name` symbol.
> > 
> > e.g.
> > 
> > ```
> > $ cat test.S
> > .text
> > .space 0x42
> > 
> > // Define foo.
> > .globl foo
> > foo:
> > ret
> > 
> > // Define a weak alias, bar.
> > .globl bar
> > .weak_reference bar
> > bar = foo
> > 
> > $ ~/clang11/bin/clang test.S -c && ~/clang11/bin/llvm-readobj --syms test.o
> > 
> > File: test.o
> > Format: Mach-O 64-bit x86-64
> > Arch: x86_64
> > AddressSize: 64bit
> > Symbols [
> >   Symbol {
> > Name: bar (1)
> > Extern
> > Type: Section (0xE)
> > Section: __text (0x1)
> > RefType: UndefinedNonLazy (0x0)
> > Flags [ (0x0)
> > ]
> > Value: 0x42
> >   }
> >   Symbol {
> > Name: foo (5)
> > Extern
> > Type: Section (0xE)
> > Section: __text (0x1)
> > RefType: UndefinedNonLazy (0x0)
> > Flags [ (0x0)
> > ]
> > Value: 0x42
> >   }
> > ]
> > ```
> > 
> > The Flags are empty.
> > 
> > OTOH, if I flip things around:
> > 
> > ```
> > .text
> > .space 0x42
> > 
> > // Define a weak function, foo.
> > .globl foo
> > .weak_reference foo
> > foo:
> > ret
> > 
> > // Define an alias, bar.
> > .globl bar
> > bar = foo
> > ```
> > 
> > Now both symbols are WeakRef:
> > 
> > ```
> > File: test.o
> > Format: Mach-O 64-bit x86-64
> > Arch: x86_64
> > AddressSize: 64bit
> > Symbols [
> >   Symbol {
> > Name: bar (1)
> > Extern
> > Type: Section (0xE)
> > Section: __text (0x1)
> > RefType: UndefinedNonLazy (0x0)
> > Flags [ (0x40)
> >   WeakRef (0x40)
> > ]
> > Value: 0x42
> >   }
> >   Symbol {
> > Name: foo (5)
> > Extern
> > Type: Section (0xE)
> > Section: __text (0x1)
> > RefType: UndefinedNonLazy (0x0)
> > Flags [ (0x40)
> >   WeakRef (0x40)
> > ]
> > Value: 0x42
> >   }
> > ]
> > ```
> > 
> > I'm wondering if this LLVM behavior is actually correct, but I'm also 
> > unfamiliar with Mach-O. (i.e. We want to copy the symbol's address, but 
> > should we be copying the WeakRef/WeakDef flags?) It looks like the behavior 
> > is controlled in `MachObjectWriter::writeNlist`. `writeNlist` finds the 
> > aliased symbol and uses its flags:
> > ```
> >   // The Mach-O streamer uses the lowest 16-bits of the flags for the 'desc'
> >   // value.
> >   bool EncodeAsAltEntry =
> > IsAlias && cast(OrigSymbol).isAltEntry();
> >   
> > W.write(cast(Symbol)->getEncodedFlags(EncodeAsAltEntry));
> > ```
> > 
> > The PrivateExtern attribute, on the other hand, isn't part of these encoded 
> > flags:
> > ```
> >   if (Data.isPrivateExtern())
> > Type |= MachO::N_PEXT;
> > ```
> > `Data` continues to refer to the alias symbol rather than the aliased 
> > symbol. However, apparently the author isn't completely sure about things?
> > ```
> > // FIXME: Should this update Data as well?
> > ```
> > 
> > In libunwind, there is one usage of assembly.h's WEAK_ALIAS. 
> > UnwindRegistersSave.S defines a hidden non-weak __unw_getcontext function, 
> > and also a weak alias unw_getcontext. My patch's goal is to make 
> > unw_getcontext hidden or not-hidden depending on a CMake config variable.
> > 
> > Currently, on Mach-O and on Windows, `WEAK_ALIAS` doesn't actually make the 
> > alias weak. I'm just making it a 

[PATCH] D96315: [X86][AMX] Assemble new AMX interface to an experiment header file.

2021-02-08 Thread Pengfei Wang via Phabricator via cfe-commits
pengfei added a comment.

Hi @craig.topper, this patch is intent upon LLVM 12.0 release stablization, 
since the new AMX interface is on development and has some know issues. Do you 
think it is necessary and enough for the release? If it does, we can commit it 
to both trunk and 12.x branch.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D96315

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


[PATCH] D96082: [clang-tidy] Add 'readability-useless-return-value' check

2021-02-08 Thread Lukas Hänel via Phabricator via cfe-commits
LukasHanel added a comment.

In D96082#2549943 , @steveire wrote:

> In D96082#2545807 , @LukasHanel 
> wrote:
>
>> Hi, thanks for discussing my proposal!
>>
>> - Usefulness of the fix-it's
>
> I agree with @njames93 that this check is dangerous. Even if you extended it 
> to port callExprs, that would only work in translation units which can see 
> the definition.

Are you saying I should just remove the fix-its altogether?
Or, put them under some option that is off by default?

> In addition to that practical problem, there are some functions which 
> deliberately always return the same value and you don't have a way to 
> distinguish them other than by adding an option to ignore them. It might make 
> the checker a bit of a burden. The kinds of functions I'm referring to 
> include functions which give a name to an otherwise-magic number (`int 
> sentinalValue() { return 0; }`), virtual methods (I see you already handle 
> those), Visitors, dummy implementations of APIs which may not be implemented 
> on a platform, CRTP interfaces, there may be others.



>> Anyhow, last year I was refactoring our companies code base and often 
>> manually searched for functions that would be identified by such checker. 
>> And as you say, I did not implement the corner cases yet.
>
> Does this mean that you didn't try to run this tool on a real codebase? (ie 
> your company code is already changed and doesn't need it anymore). You may 
> run into the cross-TU issue if you run it on a codebase.

Running on my own code base is the next step. clang-tidy is not well integrated 
there yet.
Running on llvm-project, it got me to implement several filters:

- 
https://github.com/llvm/llvm-project/blob/main/llvm/lib/Demangle/MicrosoftDemangle.cpp#L923
 : assignment to std:tie()
- e.g. 
https://github.com/llvm/llvm-project/blob/main/llvm/include/llvm/CodeGen/FastISel.h#L473
 virtual methods

In addition, I saw the following:
https://github.com/llvm/llvm-project/blob/892e4567e1357ee10ef67ee6dfbe45aeded9d2dc/llvm/lib/Support/regcomp.c#L1180
Clearly not used most of the time, but the macro REQUIRE uses seterr() in an 
expression. However, a void function call creates a statement, not an 
expression.

doRegionSplit:
https://github.com/llvm/llvm-project/blob/892e4567e1357ee10ef67ee6dfbe45aeded9d2dc/llvm/lib/CodeGen/RegAllocGreedy.cpp#L1965
https://github.com/llvm/llvm-project/blob/892e4567e1357ee10ef67ee6dfbe45aeded9d2dc/llvm/lib/CodeGen/RegAllocGreedy.cpp#L1862
^ Replace here with `call(); return 0;`.
Like here:
https://github.com/llvm/llvm-project/blob/892e4567e1357ee10ef67ee6dfbe45aeded9d2dc/llvm/lib/CodeGen/RegAllocGreedy.cpp#L2826

https://github.com/llvm/llvm-project/blob/892e4567e1357ee10ef67ee6dfbe45aeded9d2dc/llvm/lib/CodeGen/CodeGenPrepare.cpp#L6887
Used 4 times in a private class, with an assert that warns about the single 
use. I guess it is a magic number with an assert, so somewhat useful, but still 
6 years that nobody added more transitions.

>> It seems some fixes are more of a gimmick and shouldn't be used without 
>> supervision.
>
> I think you might be right. Do you have a list of such checks? Maybe they 
> should be removed.

https://clang.llvm.org/extra/clang-tidy/checks/readability-inconsistent-declaration-parameter-name.html

> changing the parameter names, but its declaration in header file is not 
> updated.

For us it fixed things in the wrong order. The header file were polished 
doxygen resembling the user facing documentation or API standard.
In the function definition, we used parameter names that helped in the 
implementation. Those should be changed, not the ones in the header file. This 
should be an option IMHO.

https://clang.llvm.org/docs/DiagnosticsReference.html#wasm-operand-widths
Can be missing context, it changes % to %w, which is not always what you want.

https://clang.llvm.org/docs/DiagnosticsReference.html#wformat-type-confusion 
(not sure which one actually)
%08lx, --> %08llx, but then does it compile in 32-bit 64bit? Maybe should be 
replaced by PRIx64.

Well, mostly, I was set back by the broken formatting after fix-its, and also 
the sheer number of fix-its and related options.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D96082

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


[PATCH] D96315: [X86][AMX] Assemble new AMX interface to an experiment header file.

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



Comment at: clang/lib/Headers/amxintrin_experiment.h:12
+ * This file is experiment interface for AMX new programming model.
+ */
+

pengfei wrote:
> It's better to add such macros:
> ```
> #ifndef __AMXINTRIN_EXPERIMENT_H
> #define __AMXINTRIN_EXPERIMENT_H
> #ifdef __x86_64__
> ```
Sure. Thanks.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D96315

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


[PATCH] D96315: [X86][AMX] Assemble new AMX interface to an experiment header file.

2021-02-08 Thread LuoYuanke via Phabricator via cfe-commits
LuoYuanke updated this revision to Diff 322293.
LuoYuanke added a comment.

Address Pengfei's comments.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D96315

Files:
  clang/lib/Headers/CMakeLists.txt
  clang/lib/Headers/amxintrin.h
  clang/lib/Headers/amxintrin_experiment.h
  clang/test/CodeGen/X86/amx_api.c

Index: clang/test/CodeGen/X86/amx_api.c
===
--- clang/test/CodeGen/X86/amx_api.c
+++ clang/test/CodeGen/X86/amx_api.c
@@ -2,6 +2,7 @@
 // RUN: -target-feature +amx-bf16 -emit-llvm -o - -Werror -pedantic | FileCheck %s --check-prefixes=CHECK
 
 #include 
+#include 
 
 char buf[1024];
 #define STRIDE 32
Index: clang/lib/Headers/amxintrin_experiment.h
===
--- /dev/null
+++ clang/lib/Headers/amxintrin_experiment.h
@@ -0,0 +1,75 @@
+/*===-- amxintrin_experiment.h - AMX intrinsics -*- C/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 is experiment interface for AMX new programming model.
+ */
+
+#ifndef __AMXINTRIN_EXPERIMENT_H
+#define __AMXINTRIN_EXPERIMENT_H
+#ifdef __x86_64__
+
+#define __DEFAULT_FN_ATTRS_TILE\
+  __attribute__((__always_inline__, __nodebug__, __target__("amx-tile")))
+
+#define __DEFAULT_FN_ATTRS_INT8\
+  __attribute__((__always_inline__, __nodebug__, __target__("amx-int8")))
+
+typedef int _tile1024i __attribute__((__vector_size__(1024), __aligned__(64)));
+static __inline__ _tile1024i __DEFAULT_FN_ATTRS_INT8
+_tile_loadd_internal(unsigned short m, unsigned short n, const void *base,
+ __SIZE_TYPE__ stride) {
+  return __builtin_ia32_tileloadd64_internal(m, n, base,
+ (__SIZE_TYPE__)(stride));
+}
+
+static __inline__ _tile1024i __DEFAULT_FN_ATTRS_INT8
+_tile_dpbssd_internal(unsigned short m, unsigned short n, unsigned short k,
+  _tile1024i dst, _tile1024i src1, _tile1024i src2) {
+  return __builtin_ia32_tdpbssd_internal(m, n, k, dst, src1, src2);
+}
+
+static __inline__ void __DEFAULT_FN_ATTRS_INT8
+_tile_stored_internal(unsigned short m, unsigned short n, void *base,
+  __SIZE_TYPE__ stride, _tile1024i tile) {
+  return __builtin_ia32_tilestored64_internal(m, n, base,
+  (__SIZE_TYPE__)(stride), tile);
+}
+
+typedef struct __tile1024i_str {
+  const unsigned short row;
+  const unsigned short col;
+  _tile1024i tile;
+} __tile1024i;
+
+__DEFAULT_FN_ATTRS_TILE
+static void __tile_loadd(__tile1024i *dst, const void *base,
+ __SIZE_TYPE__ stride) {
+  dst->tile = _tile_loadd_internal(dst->row, dst->col, base, stride);
+}
+
+__DEFAULT_FN_ATTRS_INT8
+static void __tile_dpbssd(__tile1024i *dst, __tile1024i src1,
+  __tile1024i src2) {
+  dst->tile = _tile_dpbssd_internal(src1.row, src2.col, src1.col, dst->tile,
+src1.tile, src2.tile);
+}
+
+__DEFAULT_FN_ATTRS_TILE
+static void __tile_stored(void *base, __SIZE_TYPE__ stride, __tile1024i src) {
+  _tile_stored_internal(src.row, src.col, base, stride, src.tile);
+}
+
+__DEFAULT_FN_ATTRS_TILE
+static void __tile_zero(__tile1024i *dst) {
+  dst->tile = __builtin_ia32_tilezero_internal(dst->row, dst->col);
+}
+
+#endif /* __x86_64__ */
+#endif /* __AMXINTRIN_EXPERIMENT_H */
Index: clang/lib/Headers/amxintrin.h
===
--- clang/lib/Headers/amxintrin.h
+++ clang/lib/Headers/amxintrin.h
@@ -221,58 +221,5 @@
 #define _tile_dpbf16ps(dst, src0, src1)\
   __builtin_ia32_tdpbf16ps((dst), (src0), (src1))
 
-#define __DEFAULT_FN_ATTRS_INT8\
-  __attribute__((__always_inline__, __nodebug__, __target__("amx-int8")))
-
-typedef int _tile1024i __attribute__((__vector_size__(1024), __aligned__(64)));
-static __inline__ _tile1024i __DEFAULT_FN_ATTRS_INT8
-_tile_loadd_internal(unsigned short m, unsigned short n, const void *base,
- __SIZE_TYPE__ stride) {
-  return __builtin_ia32_tileloadd64_internal(m, n, base,
- (__SIZE_TYPE__)(stride));
-}
-
-static __inline__ _tile1024i __DEFAULT_FN_ATTRS_INT8
-_tile_dpbssd_internal(unsigned short m, unsigned short n, unsigned short k,
-  _tile1024i dst, _tile1024i src1, _tile1024i src2) {
-  return __builtin_ia32_tdpbssd_internal(m, n, k, dst, src1, src2);
-}
-
-static 

[PATCH] D96320: [ThinLTO, Sanitizers] Skip instrumentation by testing backend

2021-02-08 Thread Vitaly Buka via Phabricator via cfe-commits
vitalybuka created this revision.
Herald added subscribers: steven_wu, hiraditya, inglorion.
vitalybuka requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

Distributed ThinLTO has special case when backend fallback
to regular non-ThinLTO version. In that instrumentation must be
skipped as it's already applied by buildLTOPreLinkDefaultPipeline.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D96320

Files:
  clang/lib/CodeGen/BackendUtil.cpp
  clang/test/CodeGen/thinlto-distributed-backend-skip-sanitizer.ll

Index: clang/test/CodeGen/thinlto-distributed-backend-skip-sanitizer.ll
===
--- /dev/null
+++ clang/test/CodeGen/thinlto-distributed-backend-skip-sanitizer.ll
@@ -0,0 +1,109 @@
+; REQUIRES: x86-registered-target
+
+; Check that ThinLTO backend respects "SkipModuleByDistributedBackend"
+; flag which can be set by indexing.
+
+; RUN: opt -thinlto-bc -o %t.o %s
+
+; RUN: %clang_cc1 -triple x86_64-grtev4-linux-gnu -fmemory-profile=/dev/null \
+; RUN:   -fthinlto-index=/dev/null \
+; RUN:   -emit-llvm -o - -x ir %t.o | FileCheck %s --implicit-check-not=memprof
+
+; RUN: %clang_cc1 -triple x86_64-grtev4-linux-gnu -fsanitize=local-bounds \
+; RUN:   -fthinlto-index=/dev/null \
+; RUN:   -emit-llvm -o - -x ir %t.o | FileCheck %s --implicit-check-not=trap
+
+; RUN: %clang_cc1 -triple x86_64-grtev4-linux-gnu -fsanitize-coverage-type=1 \
+; RUN:   -fthinlto-index=/dev/null \
+; RUN:   -emit-llvm -o - -x ir %t.o | FileCheck %s --implicit-check-not=sanitizer_cov
+
+; RUN: %clang_cc1 -triple x86_64-grtev4-linux-gnu -fsanitize=address \
+; RUN:   -fthinlto-index=/dev/null \
+; RUN:   -emit-llvm -o - -x ir %t.o | FileCheck %s --implicit-check-not=asan
+
+; RUN: %clang_cc1 -triple x86_64-grtev4-linux-gnu -fsanitize=kernel-address \
+; RUN:   -fthinlto-index=/dev/null \
+; RUN:   -emit-llvm -o - -x ir %t.o | FileCheck %s --implicit-check-not=asan
+
+; RUN: %clang_cc1 -triple x86_64-grtev4-linux-gnu -fsanitize=hwaddress \
+; RUN:   -fthinlto-index=/dev/null \
+; RUN:   -emit-llvm -o - -x ir %t.o | FileCheck %s --implicit-check-not=asan
+
+; RUN: %clang_cc1 -triple x86_64-grtev4-linux-gnu -fsanitize=kernel-hwaddress \
+; RUN:   -fthinlto-index=/dev/null \
+; RUN:   -emit-llvm -o - -x ir %t.o | FileCheck %s --implicit-check-not=asan
+
+; RUN: %clang_cc1 -triple x86_64-grtev4-linux-gnu -fsanitize=thread \
+; RUN:   -fthinlto-index=/dev/null \
+; RUN:   -emit-llvm -o - -x ir %t.o | FileCheck %s --implicit-check-not=tsan
+
+; RUN: %clang_cc1 -triple x86_64-grtev4-linux-gnu -fsanitize=memory \
+; RUN:   -fthinlto-index=/dev/null \
+; RUN:   -emit-llvm -o - -x ir %t.o | FileCheck %s --implicit-check-not=msan
+
+; RUN: %clang_cc1 -triple x86_64-grtev4-linux-gnu -fsanitize=kernel-memory \
+; RUN:   -fthinlto-index=/dev/null \
+; RUN:   -emit-llvm -o - -x ir %t.o | FileCheck %s --implicit-check-not=msan
+
+; RUN: %clang_cc1 -triple x86_64-grtev4-linux-gnu -fsanitize=dataflow \
+; RUN:   -fthinlto-index=/dev/null \
+; RUN:   -emit-llvm -o - -x ir %t.o | FileCheck %s --implicit-check-not=dfsan
+
+; Lagacy PM
+; RUN: %clang_cc1 -triple x86_64-grtev4-linux-gnu -fmemory-profile=/dev/null \
+; RUN:   -fthinlto-index=/dev/null -flegacy-pass-manager \
+; RUN:   -emit-llvm -o - -x ir %t.o | FileCheck %s --implicit-check-not=memprof
+
+; RUN: %clang_cc1 -triple x86_64-grtev4-linux-gnu -fsanitize=local-bounds \
+; RUN:   -fthinlto-index=/dev/null -flegacy-pass-manager \
+; RUN:   -emit-llvm -o - -x ir %t.o | FileCheck %s --implicit-check-not=trap
+
+; RUN: %clang_cc1 -triple x86_64-grtev4-linux-gnu -fsanitize-coverage-type=1 \
+; RUN:   -fthinlto-index=/dev/null -flegacy-pass-manager \
+; RUN:   -emit-llvm -o - -x ir %t.o | FileCheck %s --implicit-check-not=sanitizer_cov
+
+; RUN: %clang_cc1 -triple x86_64-grtev4-linux-gnu -fsanitize=address \
+; RUN:   -fthinlto-index=/dev/null -flegacy-pass-manager \
+; RUN:   -emit-llvm -o - -x ir %t.o | FileCheck %s --implicit-check-not=asan
+
+; RUN: %clang_cc1 -triple x86_64-grtev4-linux-gnu -fsanitize=kernel-address \
+; RUN:   -fthinlto-index=/dev/null -flegacy-pass-manager \
+; RUN:   -emit-llvm -o - -x ir %t.o | FileCheck %s --implicit-check-not=asan
+
+; RUN: %clang_cc1 -triple x86_64-grtev4-linux-gnu -fsanitize=hwaddress \
+; RUN:   -fthinlto-index=/dev/null -flegacy-pass-manager \
+; RUN:   -emit-llvm -o - -x ir %t.o | FileCheck %s --implicit-check-not=asan
+
+; RUN: %clang_cc1 -triple x86_64-grtev4-linux-gnu -fsanitize=kernel-hwaddress \
+; RUN:   -fthinlto-index=/dev/null -flegacy-pass-manager \
+; RUN:   -emit-llvm -o - -x ir %t.o | FileCheck %s --implicit-check-not=asan
+
+; RUN: %clang_cc1 -triple x86_64-grtev4-linux-gnu -fsanitize=thread \
+; RUN:   -fthinlto-index=/dev/null -flegacy-pass-manager \
+; RUN:   -emit-llvm -o - -x ir %t.o | FileCheck %s --implicit-check-not=tsan
+
+; RUN: %clang_cc1 -triple x86_64-grtev4-linux-gnu -fsanitize=memory \
+; RUN:  

[PATCH] D93446: [RISCV] Add vadd with mask and without mask builtin.

2021-02-08 Thread Jim Lin via Phabricator via cfe-commits
Jim added inline comments.



Comment at: clang/include/clang/Basic/DiagnosticSemaKinds.td:11127
+def err_riscvv_builtin_not_useable : Error<
+   "builtin requires 'V' extension support to be enabled">;
 } // end of sema component.

Add blank line.
Is it "err_riscvv_builtin_not_enabled"?



Comment at: clang/lib/Basic/Targets/RISCV.cpp:89
+#define BUILTIN(ID, TYPE, ATTRS)   
\
+  {"__builtin_rvv_" #ID, TYPE, ATTRS, nullptr, ALL_LANGUAGES, nullptr},
+#include "clang/Basic/BuiltinsRISCV.def"

Builtins for other extension don't have "__builtin_rvv_" prefix.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D93446

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


[PATCH] D96315: [X86][AMX] Assemble new AMX interface to an experiment header file.

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



Comment at: clang/lib/Headers/amxintrin_experiment.h:12
+ * This file is experiment interface for AMX new programming model.
+ */
+

It's better to add such macros:
```
#ifndef __AMXINTRIN_EXPERIMENT_H
#define __AMXINTRIN_EXPERIMENT_H
#ifdef __x86_64__
```



Comment at: clang/test/CodeGen/X86/amx_api.c:4
 
-#include 
+#include 
 

Better to add `#include ` at the same time. Or to simplify, add it 
in `amxintrin_experiment.h`.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D96315

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


[PATCH] D96315: [X86][AMX] Assemble new AMX interface to an experiment header file.

2021-02-08 Thread LuoYuanke via Phabricator via cfe-commits
LuoYuanke created this revision.
Herald added subscribers: pengfei, mgorny.
LuoYuanke requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

Since the new AMX interface is not mature right now, we assemble the new
interface to an experiment file.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D96315

Files:
  clang/lib/Headers/CMakeLists.txt
  clang/lib/Headers/amxintrin.h
  clang/lib/Headers/amxintrin_experiment.h
  clang/test/CodeGen/X86/amx_api.c

Index: clang/test/CodeGen/X86/amx_api.c
===
--- clang/test/CodeGen/X86/amx_api.c
+++ clang/test/CodeGen/X86/amx_api.c
@@ -1,7 +1,7 @@
 // RUN: %clang_cc1 %s -ffreestanding -triple=x86_64-unknown-unknown  -target-feature +avx512f  -target-feature +amx-int8  \
 // RUN: -target-feature +amx-bf16 -emit-llvm -o - -Werror -pedantic | FileCheck %s --check-prefixes=CHECK
 
-#include 
+#include 
 
 char buf[1024];
 #define STRIDE 32
Index: clang/lib/Headers/amxintrin_experiment.h
===
--- /dev/null
+++ clang/lib/Headers/amxintrin_experiment.h
@@ -0,0 +1,68 @@
+/*===-- amxintrin_experiment.h - AMX intrinsics -*- C/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 is experiment interface for AMX new programming model.
+ */
+
+#define __DEFAULT_FN_ATTRS_TILE\
+  __attribute__((__always_inline__, __nodebug__, __target__("amx-tile")))
+
+#define __DEFAULT_FN_ATTRS_INT8\
+  __attribute__((__always_inline__, __nodebug__, __target__("amx-int8")))
+
+typedef int _tile1024i __attribute__((__vector_size__(1024), __aligned__(64)));
+static __inline__ _tile1024i __DEFAULT_FN_ATTRS_INT8
+_tile_loadd_internal(unsigned short m, unsigned short n, const void *base,
+ __SIZE_TYPE__ stride) {
+  return __builtin_ia32_tileloadd64_internal(m, n, base,
+ (__SIZE_TYPE__)(stride));
+}
+
+static __inline__ _tile1024i __DEFAULT_FN_ATTRS_INT8
+_tile_dpbssd_internal(unsigned short m, unsigned short n, unsigned short k,
+  _tile1024i dst, _tile1024i src1, _tile1024i src2) {
+  return __builtin_ia32_tdpbssd_internal(m, n, k, dst, src1, src2);
+}
+
+static __inline__ void __DEFAULT_FN_ATTRS_INT8
+_tile_stored_internal(unsigned short m, unsigned short n, void *base,
+  __SIZE_TYPE__ stride, _tile1024i tile) {
+  return __builtin_ia32_tilestored64_internal(m, n, base,
+  (__SIZE_TYPE__)(stride), tile);
+}
+
+typedef struct __tile1024i_str {
+  const unsigned short row;
+  const unsigned short col;
+  _tile1024i tile;
+} __tile1024i;
+
+__DEFAULT_FN_ATTRS_TILE
+static void __tile_loadd(__tile1024i *dst, const void *base,
+ __SIZE_TYPE__ stride) {
+  dst->tile = _tile_loadd_internal(dst->row, dst->col, base, stride);
+}
+
+__DEFAULT_FN_ATTRS_INT8
+static void __tile_dpbssd(__tile1024i *dst, __tile1024i src1,
+  __tile1024i src2) {
+  dst->tile = _tile_dpbssd_internal(src1.row, src2.col, src1.col, dst->tile,
+src1.tile, src2.tile);
+}
+
+__DEFAULT_FN_ATTRS_TILE
+static void __tile_stored(void *base, __SIZE_TYPE__ stride, __tile1024i src) {
+  _tile_stored_internal(src.row, src.col, base, stride, src.tile);
+}
+
+__DEFAULT_FN_ATTRS_TILE
+static void __tile_zero(__tile1024i *dst) {
+  dst->tile = __builtin_ia32_tilezero_internal(dst->row, dst->col);
+}
Index: clang/lib/Headers/amxintrin.h
===
--- clang/lib/Headers/amxintrin.h
+++ clang/lib/Headers/amxintrin.h
@@ -221,58 +221,5 @@
 #define _tile_dpbf16ps(dst, src0, src1)\
   __builtin_ia32_tdpbf16ps((dst), (src0), (src1))
 
-#define __DEFAULT_FN_ATTRS_INT8\
-  __attribute__((__always_inline__, __nodebug__, __target__("amx-int8")))
-
-typedef int _tile1024i __attribute__((__vector_size__(1024), __aligned__(64)));
-static __inline__ _tile1024i __DEFAULT_FN_ATTRS_INT8
-_tile_loadd_internal(unsigned short m, unsigned short n, const void *base,
- __SIZE_TYPE__ stride) {
-  return __builtin_ia32_tileloadd64_internal(m, n, base,
- (__SIZE_TYPE__)(stride));
-}
-
-static __inline__ _tile1024i __DEFAULT_FN_ATTRS_INT8
-_tile_dpbssd_internal(unsigned short m, unsigned short n, unsigned short k,
-  _tile1024i dst, _tile1024i src1, _t

[PATCH] D68682: format::cleanupAroundReplacements removes whole line when Removals leave previously non-blank line blank

2021-02-08 Thread Conrad Poelman via Phabricator via cfe-commits
poelmanc added a comment.

In D68682#2547906 , @kadircet wrote:

> It looks like premerge tests skipped your last diff with id 321451 
> (https://reviews.llvm.org/harbormaster/?after=87950). You can re-trigger by 
> uploading a new diff, in the meantime i would also file a bug to 
> https://github.com/google/llvm-premerge-checks/issues. mentioning your diff 
> id.

Thanks @kadircet, actually just reviewing the current bug list explained the 
problem: https://github.com/google/llvm-premerge-checks/issues/263, //Build is 
not triggered if diff repository is not set//. I wasn't selecting //rG 
 LLVM Github Monorepo// per 
instructions at https://llvm.org/docs/Phabricator.html that said //Leave the 
Repository field blank//.

HarborMaster has now run and passes all tests on Windows and Linux.

1. clang-format for a new test case in 
`clang-tools-extra/test/clang-tidy/checkers/readability-redundant-member-init.cpp`.
 That test case formatting matches real-world examples so I'm reluctant to 
change it - I believe it's clang-formatted but with different settings from 
llvm-project's.
2. clang-tidy finds 8 `int` vs `size_t` comparisons. While `int` feels safer 
when subtraction is involved (since one can `assert` variables stay positive), 
this particular code would work fine with `int` variables changed to `size_t`, 
or alternatively with `static_cast` to silence the warnings.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D68682

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


[PATCH] D93594: [X86] Pass to transform amx intrinsics to scalar operation.

2021-02-08 Thread Bing Yu via Phabricator via cfe-commits
yubing added inline comments.



Comment at: llvm/test/CodeGen/X86/AMX/amx-low-intrinsics.ll:77
+; CHECK-NEXT:[[TILEDPBSSD_UNROLL_ROWS_IV:%.*]] = phi i16 [ 0, 
[[ENTRY:%.*]] ], [ [[TILEDPBSSD_UNROLL_ROWS_STEP:%.*]], 
[[TILEDPBSSD_UNROLL_ROWS_LATCH:%.*]] ]
+; CHECK-NEXT:[[VEC_PHI_ROW:%.*]] = phi <256 x i32> [ [[C]], [[ENTRY]] ], [ 
[[TMP18:%.*]], [[TILEDPBSSD_UNROLL_ROWS_LATCH]] ]
+; CHECK-NEXT:br label [[TILEDPBSSD_UNROLL_ROWS_BODY:%.*]]

Sorry, there is a bug here. According to AMX's spec, dst's remaining part 
should be all zero.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D93594

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


[PATCH] D96215: [clang-tidy] Recognize captures as a form of aliasing.

2021-02-08 Thread Artem Dergachev via Phabricator via cfe-commits
NoQ added a comment.

In D96215#2548492 , @aaron.ballman 
wrote:

> Should structured bindings be treated similarly as well (not necessarily as 
> part of this patch)?

Umm, looks like we're both missing the elephant in the room: passing a variable 
into a function by reference.

  int &hidden_reference(int &x) {
return x;
  }
  
  void test_hidden_reference() {
int x = 0;
int &y = hidden_reference(x);
for (; x < 10; ++y) { // Warns ¯\_(ツ)_/¯
}
  }

With this taken care of, I hope structured bindings will be handled 
automatically because whatever's unwrapped couldn't have obtained a reference 
to our local variable without going through a function first (eg., the 
constructor). Unless there's some aggregate magic going on... but in this case, 
again, we have to take care of aggregate magic and structured bindings aren't 
at fault.


Repository:
  rCTE Clang Tools Extra

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

https://reviews.llvm.org/D96215

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


[PATCH] D95007: [CUDA][HIP] Add -fuse-cuid

2021-02-08 Thread Yaxun Liu via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
yaxunl marked 2 inline comments as done.
Closed by commit rG98c21289f1d2: [CUDA][HIP] Add -fuse-cuid (authored by 
yaxunl).
Herald added a project: clang.

Changed prior to commit:
  https://reviews.llvm.org/D95007?vs=322020&id=322268#toc

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D95007

Files:
  clang/include/clang/Basic/LangOptions.h
  clang/include/clang/Driver/Action.h
  clang/include/clang/Driver/Options.td
  clang/lib/Driver/Action.cpp
  clang/lib/Driver/Driver.cpp
  clang/lib/Driver/ToolChains/Clang.cpp
  clang/lib/Frontend/CompilerInvocation.cpp
  clang/test/Driver/hip-cuid-hash.hip
  clang/test/Driver/hip-cuid.hip

Index: clang/test/Driver/hip-cuid.hip
===
--- /dev/null
+++ clang/test/Driver/hip-cuid.hip
@@ -0,0 +1,93 @@
+// REQUIRES: clang-driver
+// REQUIRES: x86-registered-target
+// REQUIRES: amdgpu-registered-target
+
+// Check invalid -fuse-cuid= option.
+
+// RUN: not %clang -### -x hip \
+// RUN:   -target x86_64-unknown-linux-gnu \
+// RUN:   --offload-arch=gfx900 \
+// RUN:   --offload-arch=gfx906 \
+// RUN:   -c -nogpulib -fuse-cuid=invalid \
+// RUN:   %S/Inputs/hip_multiple_inputs/a.cu \
+// RUN:   %S/Inputs/hip_multiple_inputs/b.hip \
+// RUN: 2>&1 | FileCheck -check-prefixes=INVALID %s
+
+// Check random CUID generator.
+
+// RUN: %clang -### -x hip \
+// RUN:   -target x86_64-unknown-linux-gnu \
+// RUN:   --offload-arch=gfx900 \
+// RUN:   --offload-arch=gfx906 \
+// RUN:   -c -nogpulib -fuse-cuid=random \
+// RUN:   %S/Inputs/hip_multiple_inputs/a.cu \
+// RUN:   %S/Inputs/hip_multiple_inputs/b.hip \
+// RUN: 2>&1 | FileCheck -check-prefixes=COMMON,HEX %s
+
+// Check fixed CUID.
+
+// RUN: %clang -### -x hip \
+// RUN:   -target x86_64-unknown-linux-gnu \
+// RUN:   --offload-arch=gfx900 \
+// RUN:   --offload-arch=gfx906 \
+// RUN:   -c -nogpulib -cuid=xyz_123 \
+// RUN:   %S/Inputs/hip_multiple_inputs/a.cu \
+// RUN:   %S/Inputs/hip_multiple_inputs/b.hip \
+// RUN: 2>&1 | FileCheck -check-prefixes=COMMON,FIXED %s
+
+// Check fixed CUID override -fuse-cuid.
+
+// RUN: %clang -### -x hip \
+// RUN:   -target x86_64-unknown-linux-gnu \
+// RUN:   --offload-arch=gfx900 \
+// RUN:   --offload-arch=gfx906 \
+// RUN:   -c -nogpulib -fuse-cuid=random -cuid=xyz_123 \
+// RUN:   %S/Inputs/hip_multiple_inputs/a.cu \
+// RUN:   %S/Inputs/hip_multiple_inputs/b.hip \
+// RUN: 2>&1 | FileCheck -check-prefixes=COMMON,FIXED %s
+
+// Check hash CUID generator.
+
+// RUN: %clang -### -x hip \
+// RUN:   -target x86_64-unknown-linux-gnu \
+// RUN:   --offload-arch=gfx900 \
+// RUN:   --offload-arch=gfx906 \
+// RUN:   -c -nogpulib -fuse-cuid=hash \
+// RUN:   %S/Inputs/hip_multiple_inputs/a.cu \
+// RUN:   %S/Inputs/hip_multiple_inputs/b.hip \
+// RUN: 2>&1 | FileCheck -check-prefixes=COMMON,HEX %s
+
+// INVALID: invalid value 'invalid' in '-fuse-cuid=invalid'
+
+// COMMON: "{{.*}}clang{{.*}}" "-cc1"{{.*}} "-triple" "amdgcn-amd-amdhsa"
+// COMMON-SAME: "-target-cpu" "gfx900"
+// HEX-SAME: "-cuid=[[CUID:[0-9a-f]+]]"
+// FIXED-SAME: "-cuid=[[CUID:xyz_123]]"
+// COMMON-SAME: "{{.*}}a.cu"
+
+// COMMON: "{{.*}}clang{{.*}}" "-cc1"{{.*}} "-triple" "amdgcn-amd-amdhsa"
+// COMMON-SAME: "-target-cpu" "gfx906"
+// COMMON-SAME: "-cuid=[[CUID]]"
+// COMMON-SAME: "{{.*}}a.cu"
+
+// COMMON: "{{.*}}clang{{.*}}" "-cc1"{{.*}} "-triple" "x86_64-unknown-linux-gnu"
+// COMMON-SAME: "-cuid=[[CUID]]"
+// COMMON-SAME: "{{.*}}a.cu"
+
+// COMMON: "{{.*}}clang{{.*}}" "-cc1"{{.*}} "-triple" "amdgcn-amd-amdhsa"
+// COMMON-SAME: "-target-cpu" "gfx900"
+// HEX-NOT: "-cuid=[[CUID]]"
+// HEX-SAME: "-cuid=[[CUID2:[0-9a-f]+]]"
+// FIXED-SAME: "-cuid=[[CUID2:xyz_123]]"
+// COMMON-SAME: "{{.*}}b.hip"
+
+// COMMON: "{{.*}}clang{{.*}}" "-cc1"{{.*}} "-triple" "amdgcn-amd-amdhsa"
+// COMMON-SAME: "-target-cpu" "gfx906"
+// HEX-NOT: "-cuid=[[CUID]]"
+// COMMON-SAME: "-cuid=[[CUID2]]"
+// COMMON-SAME: "{{.*}}b.hip"
+
+// COMMON: "{{.*}}clang{{.*}}" "-cc1"{{.*}} "-triple" "x86_64-unknown-linux-gnu"
+// HEX-NOT: "-cuid=[[CUID]]"
+// COMMON-SAME: "-cuid=[[CUID2]]"
+// COMMON-SAME: "{{.*}}b.hip"
Index: clang/test/Driver/hip-cuid-hash.hip
===
--- /dev/null
+++ clang/test/Driver/hip-cuid-hash.hip
@@ -0,0 +1,35 @@
+// REQUIRES: clang-driver
+// REQUIRES: x86-registered-target
+// REQUIRES: amdgpu-registered-target
+
+// Check CUID generated by hash.
+// The same CUID is generated for the same file with the same options.
+
+// RUN: %clang -### -x hip -target x86_64-unknown-linux-gnu \
+// RUN:   --offload-arch=gfx906 -c -nogpulib -fuse-cuid=hash \
+// RUN:   %S/Inputs/hip_multiple_inputs/a.cu >%t.out 2>&1
+
+// RUN: %clang -### -x hip -target x86_64-unknown-linux-gnu \
+// RUN:   --offload-arch=gfx906 -c -nogpulib -fuse-cuid=hash \
+// RUN:   %S/Inputs/hip_multi

[clang] 98c2128 - [CUDA][HIP] Add -fuse-cuid

2021-02-08 Thread Yaxun Liu via cfe-commits

Author: Yaxun (Sam) Liu
Date: 2021-02-08T22:26:12-05:00
New Revision: 98c21289f1d239f39fa549ae01b17efffce6a7c0

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

LOG: [CUDA][HIP] Add -fuse-cuid

This patch added a distinct CUID for each input file, which is represented by 
InputAction.
clang initially creates an InputAction for each input file for the host 
compilation. In CUDA/HIP action
builder, each InputAction is given a CUID and cloned for each GPU arch, and the 
CUID is also cloned. In this way,
we guarantee the corresponding device and host compilation for the same file 
shared the
same CUID. On the other hand, different compilation units have different CUID.

-fuse-cuid=random|hash|none is added to control the method to generate CUID. 
The default
is hash. -cuid=X is also added to specify CUID explicitly, which overrides 
-fuse-cuid.

Reviewed by: Artem Belevich

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

Added: 
clang/test/Driver/hip-cuid-hash.hip
clang/test/Driver/hip-cuid.hip

Modified: 
clang/include/clang/Basic/LangOptions.h
clang/include/clang/Driver/Action.h
clang/include/clang/Driver/Options.td
clang/lib/Driver/Action.cpp
clang/lib/Driver/Driver.cpp
clang/lib/Driver/ToolChains/Clang.cpp
clang/lib/Frontend/CompilerInvocation.cpp

Removed: 




diff  --git a/clang/include/clang/Basic/LangOptions.h 
b/clang/include/clang/Basic/LangOptions.h
index d8bd2a8b52fc..0d14121bac7a 100644
--- a/clang/include/clang/Basic/LangOptions.h
+++ b/clang/include/clang/Basic/LangOptions.h
@@ -331,6 +331,12 @@ class LangOptions : public LangOptionsBase {
   /// host code generation.
   std::string OMPHostIRFile;
 
+  /// The user provided compilation unit ID, if non-empty. This is used to
+  /// externalize static variables which is needed to support accessing static
+  /// device variables in host code for single source offloading languages
+  /// like CUDA/HIP.
+  std::string CUID;
+
   /// Indicates whether the front-end is explicitly told that the
   /// input is a header file (i.e. -x c-header).
   bool IsHeaderFile = false;

diff  --git a/clang/include/clang/Driver/Action.h 
b/clang/include/clang/Driver/Action.h
index 27c95c6f89d4..ba84d886a6cf 100644
--- a/clang/include/clang/Driver/Action.h
+++ b/clang/include/clang/Driver/Action.h
@@ -214,14 +214,18 @@ class Action {
 
 class InputAction : public Action {
   const llvm::opt::Arg &Input;
-
+  std::string Id;
   virtual void anchor();
 
 public:
-  InputAction(const llvm::opt::Arg &Input, types::ID Type);
+  InputAction(const llvm::opt::Arg &Input, types::ID Type,
+  StringRef Id = StringRef());
 
   const llvm::opt::Arg &getInputArg() const { return Input; }
 
+  void setId(StringRef _Id) { Id = _Id.str(); }
+  StringRef getId() const { return Id; }
+
   static bool classof(const Action *A) {
 return A->getKind() == InputClass;
   }

diff  --git a/clang/include/clang/Driver/Options.td 
b/clang/include/clang/Driver/Options.td
index 49071a4c56d9..3f7519fb05f5 100644
--- a/clang/include/clang/Driver/Options.td
+++ b/clang/include/clang/Driver/Options.td
@@ -930,6 +930,18 @@ def gpu_max_threads_per_block_EQ : Joined<["--"], 
"gpu-max-threads-per-block=">,
 def gpu_instrument_lib_EQ : Joined<["--"], "gpu-instrument-lib=">,
   HelpText<"Instrument device library for HIP, which is a LLVM bitcode 
containing "
   "__cyg_profile_func_enter and __cyg_profile_func_exit">;
+def cuid_EQ : Joined<["-"], "cuid=">, Flags<[CC1Option]>,
+  HelpText<"An ID for compilation unit, which should be the same for the same "
+   "compilation unit but 
diff erent for 
diff erent compilation units. "
+   "It is used to externalize device-side static variables for single "
+   "source offloading languages CUDA and HIP so that they can be "
+   "accessed by the host code of the same compilation unit.">;
+def fuse_cuid_EQ : Joined<["-"], "fuse-cuid=">,
+  HelpText<"Method to generate ID's for compilation units for single source "
+   "offloading languages CUDA and HIP: 'hash' (ID's generated by 
hashing "
+   "file path and command line options) | 'random' (ID's generated as "
+   "random numbers) | 'none' (disabled). Default is 'hash'. This 
option "
+   "will be overriden by option '-cuid=[ID]' if it is specified." >;
 def libomptarget_nvptx_bc_path_EQ : Joined<["--"], 
"libomptarget-nvptx-bc-path=">, Group,
   HelpText<"Path to libomptarget-nvptx bitcode library">;
 def dD : Flag<["-"], "dD">, Group, Flags<[CC1Option]>,

diff  --git a/clang/lib/Driver/Action.cpp b/clang/lib/Driver/Action.cpp
index 2ec063d873be..e2d2f6c22de0 100644
--- a/clang/lib/Driver/Action.cpp
+++ b/clang/lib/Driver/Action.cpp
@@ -165,8 +165,8 @@ StringRef Action::Ge

[PATCH] D96268: [-Wcompletion-handler] Support checks with builtins

2021-02-08 Thread Artem Dergachev via Phabricator via cfe-commits
NoQ accepted this revision.
NoQ added a comment.
This revision is now accepted and ready to land.

Aha, yup, makes sense!




Comment at: clang/lib/Analysis/CalledOnceCheck.cpp:343
+case Builtin::BI__builtin_expect_with_probability: {
+  assert(CE->getNumArgs() >= 2);
+

Otherwise it's a compile error and analysis based warnings aren't run when 
there are compile errors, right? If it was a normal function call there's no 
way we would have gotten away with such assertion. Like, even if it was a 
standard library function the user could still override that. But for builtins 
I guess that should work.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D96268

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


[PATCH] D68682: format::cleanupAroundReplacements removes whole line when Removals leave previously non-blank line blank

2021-02-08 Thread Conrad Poelman via Phabricator via cfe-commits
poelmanc updated this revision to Diff 322265.
poelmanc added a comment.

Call `llvm::Annoation` constructor rather than `operator=` to fix linux build 
issue, fix some issues identified by clang-format and clang-tidy.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D68682

Files:
  clang-tools-extra/clang-tidy/readability/RedundantControlFlowCheck.cpp
  clang-tools-extra/test/clang-tidy/checkers/modernize-redundant-void-arg.cpp
  
clang-tools-extra/test/clang-tidy/checkers/readability-redundant-control-flow.cpp
  
clang-tools-extra/test/clang-tidy/checkers/readability-redundant-declaration.cpp
  
clang-tools-extra/test/clang-tidy/checkers/readability-redundant-member-init.cpp
  clang-tools-extra/test/clang-tidy/checkers/readability-simplify-bool-expr.cpp
  clang-tools-extra/unittests/clang-change-namespace/ChangeNamespaceTests.cpp
  clang/include/clang/Basic/CharInfo.h
  clang/include/clang/Format/Format.h
  clang/lib/AST/CommentLexer.cpp
  clang/lib/AST/CommentParser.cpp
  clang/lib/Format/Format.cpp
  clang/unittests/Format/CMakeLists.txt
  clang/unittests/Format/CleanupTest.cpp

Index: clang/unittests/Format/CleanupTest.cpp
===
--- clang/unittests/Format/CleanupTest.cpp
+++ clang/unittests/Format/CleanupTest.cpp
@@ -11,6 +11,7 @@
 #include "../Tooling/ReplacementTest.h"
 #include "clang/Tooling/Core/Replacement.h"
 
+#include "llvm/Testing/Support/Annotations.h"
 #include "gtest/gtest.h"
 
 using clang::tooling::ReplacementTest;
@@ -320,6 +321,11 @@
 return tooling::Replacement(FileName, Offset, Length, Text);
   }
 
+  tooling::Replacement createReplacement(llvm::Annotations::Range Range,
+ StringRef Text) {
+return createReplacement(Range.Begin, Range.End - Range.Begin, Text);
+  }
+
   tooling::Replacement createInsertion(StringRef IncludeDirective) {
 return createReplacement(UINT_MAX, 0, IncludeDirective);
   }
@@ -373,10 +379,12 @@
  "namespace C {\n"
  "namespace D { int i; }\n"
  "inline namespace E { namespace { int y; } }\n"
+ "\n"
  "int x= 0;"
  "}";
-  std::string Expected = "\n\nnamespace C {\n"
- "namespace D { int i; }\n\n"
+  std::string Expected = "\nnamespace C {\n"
+ "namespace D { int i; }\n"
+ "\n"
  "int x= 0;"
  "}";
   tooling::Replacements Replaces =
@@ -386,6 +394,104 @@
   EXPECT_EQ(Expected, formatAndApply(Code, Replaces));
 }
 
+TEST_F(CleanUpReplacementsTest, RemoveLineWhenAllNonWhitespaceRemoved) {
+  llvm::Annotations Code("namespace A {$r1[[ // Useless comment]]\n"
+ "  $r2[[int]] $r3[[x]]\t $r4[[=]] $r5[[0;]]\t\n"
+ "  int y\t = 0;$r6[[\t]]\n"
+ "} // namespace A\n");
+  std::string Expected = "namespace A {\n"
+ "  int y\t = 0;\n"
+ "} // namespace A\n";
+  tooling::Replacements Replaces =
+  toReplacements({createReplacement(Code.range("r1"), ""),
+  createReplacement(Code.range("r2"), ""),
+  createReplacement(Code.range("r3"), ""),
+  createReplacement(Code.range("r4"), ""),
+  createReplacement(Code.range("r5"), ""),
+  createReplacement(Code.range("r6"), "")});
+
+  EXPECT_EQ(Expected, apply(Code.code(), Replaces));
+}
+
+TEST_F(CleanUpReplacementsTest, RemoveLinesWhenAllNonWhitespaceRemoved) {
+  llvm::Annotations Code(R"cpp(struct A {
+  A()
+  $r3[[:]] $r1[[f()]]$r2[[,]]
+$r4[[g()]]
+  {}
+  int f = 0;
+  int g = 0;
+};)cpp");
+  std::string Expected = R"cpp(struct A {
+  A()
+  {}
+  int f = 0;
+  int g = 0;
+};)cpp";
+  tooling::Replacements Replaces =
+  toReplacements({createReplacement(Code.range("r1"), ""),
+  createReplacement(Code.range("r2"), ""),
+  createReplacement(Code.range("r3"), ""),
+  createReplacement(Code.range("r4"), "")});
+
+  EXPECT_EQ(Expected, apply(Code.code(), Replaces));
+}
+
+TEST_F(CleanUpReplacementsTest, KeepLinesWithInsertsOrReplacesEvenIfBlank) {
+  // Not using raw string literals so newlines and spaces are clear and explicit
+  llvm::Annotations Code("struct A {\n"
+ "  A() {}\n"
+ "$r3[[]]  $r1[[int]] $r2[[f;]]\n" // "  int f;\n"
+ "  \n"
+ "$r4[[  ]]\n"
+ "};");
+  std::string Expected = "struct A {\n"
+ "  A() {}\n"
+ "\n"
+ "\n"
+ "  \n"
+ "\t\n"
+  

[PATCH] D95007: [CUDA][HIP] Add -fuse-cuid

2021-02-08 Thread Yaxun Liu via Phabricator via cfe-commits
yaxunl marked 2 inline comments as done.
yaxunl added inline comments.



Comment at: clang/test/Driver/hip-cuid.hip:98
+
+// RUN: rm -rf %t.out
+

tra wrote:
> Is it necessary? The next 'RUN' command would overwrite the temp file anyways.
> Also, you don't have to call all temporary files `%t.out`.  You could use 
> `%t-1.out`, etc and leave the cleanup to the test driver.
will remove rm.



Comment at: clang/test/Driver/hip-cuid.hip:100-102
+// RUN: %clang -### -x hip -target x86_64-unknown-linux-gnu \
+// RUN:   --offload-arch=gfx906 -c -nogpulib -fuse-cuid=hash \
+// RUN:   %S/Inputs/hip_multiple_inputs/a.cu >%t.out 2>&1

tra wrote:
> Putting `RUN` down in the test file makes them easy to miss. Maybe these 
> should be in their own `hip-cuid-rdc.hip` test structured in a conventional 
> way -- RUN lines first, followed by checks.
will split the test


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

https://reviews.llvm.org/D95007

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


[PATCH] D96196: [Sema][NFC] Create Sema::BuildImplicitCast

2021-02-08 Thread Shafik Yaghmour via Phabricator via cfe-commits
shafik added inline comments.



Comment at: clang/lib/Sema/SemaCast.cpp:1060
   if (tcr != TC_Success && msg != 0) {
 if (SrcExpr.isInvalid()) // if conversion failed, don't report another 
error
   return;

Can we ever have this case w/ the added `if (SrcExpr.isInvalid())` above


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D96196

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


[clang] 21e8bb8 - PR48606: The lifetime of a constexpr heap allocation always started

2021-02-08 Thread Richard Smith via cfe-commits

Author: Richard Smith
Date: 2021-02-08T17:58:05-08:00
New Revision: 21e8bb83253e1a2f4b6fad9b53cafe8c530a38e2

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

LOG: PR48606: The lifetime of a constexpr heap allocation always started
during the same evaluation.

It looks like the only case for which this matters is determining
whether mutable subobjects of a heap allocation can be modified during
constant evaluation.

Added: 


Modified: 
clang/lib/AST/ExprConstant.cpp
clang/test/SemaCXX/cxx2a-constexpr-dynalloc.cpp

Removed: 




diff  --git a/clang/lib/AST/ExprConstant.cpp b/clang/lib/AST/ExprConstant.cpp
index 1ed9bbea84ee..d27f655011ae 100644
--- a/clang/lib/AST/ExprConstant.cpp
+++ b/clang/lib/AST/ExprConstant.cpp
@@ -3497,8 +3497,8 @@ static bool diagnoseMutableFields(EvalInfo &Info, const 
Expr *E, AccessKinds AK,
 static bool lifetimeStartedInEvaluation(EvalInfo &Info,
 APValue::LValueBase Base,
 bool MutableSubobject = false) {
-  // A temporary we created.
-  if (Base.getCallIndex())
+  // A temporary or transient heap allocation we created.
+  if (Base.getCallIndex() || Base.is())
 return true;
 
   switch (Info.IsEvaluatingDecl) {

diff  --git a/clang/test/SemaCXX/cxx2a-constexpr-dynalloc.cpp 
b/clang/test/SemaCXX/cxx2a-constexpr-dynalloc.cpp
index 3647526ff0af..097ca00640e9 100644
--- a/clang/test/SemaCXX/cxx2a-constexpr-dynalloc.cpp
+++ b/clang/test/SemaCXX/cxx2a-constexpr-dynalloc.cpp
@@ -176,3 +176,37 @@ constexpr bool construct_after_lifetime_2() {
   return true;
 }
 static_assert(construct_after_lifetime_2()); // expected-error {{}} 
expected-note {{in call}}
+
+namespace PR48606 {
+  struct A { mutable int n = 0; };
+
+  constexpr bool f() {
+A a;
+A *p = &a;
+p->~A();
+std::construct_at(p);
+return true;
+  }
+  static_assert(f());
+
+  constexpr bool g() {
+A *p = new A;
+p->~A();
+std::construct_at(p);
+delete p;
+return true;
+  }
+  static_assert(g());
+
+  constexpr bool h() {
+std::allocator alloc;
+A *p = alloc.allocate(1);
+std::construct_at(p);
+p->~A();
+std::construct_at(p);
+p->~A();
+alloc.deallocate(p);
+return true;
+  }
+  static_assert(h());
+}



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


[PATCH] D95714: [clang-tidy] fix modernize-use-nullptr false positive with spaceship operator comparisons

2021-02-08 Thread Conrad Poelman via Phabricator via cfe-commits
poelmanc updated this revision to Diff 322253.
poelmanc added a comment.

Thanks for your patience, this one should work, as I used my normal `git show 
HEAD -U99` workflow.

(The requested change was just to add a period to a comment, so as a short-cut 
I tried "Raw Diff" -> copy -> "Update Diff" -> paste into "Raw Diff" field, -> 
add the period -> Continue -> Save. "Raw Diff" didn't show full context, but it 
appeared to work based on the web interface. I guess not. 
`modernize-use-nullptr-cxx20.cpp` is a whole new file, in case that matters.)


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D95714

Files:
  clang-tools-extra/clang-tidy/modernize/UseNullptrCheck.cpp
  clang-tools-extra/test/clang-tidy/checkers/modernize-use-nullptr-cxx20.cpp


Index: 
clang-tools-extra/test/clang-tidy/checkers/modernize-use-nullptr-cxx20.cpp
===
--- /dev/null
+++ clang-tools-extra/test/clang-tidy/checkers/modernize-use-nullptr-cxx20.cpp
@@ -0,0 +1,34 @@
+// RUN: %check_clang_tidy -std=c++20 %s modernize-use-nullptr %t
+
+namespace std {
+struct strong_ordering {
+  int n;
+  constexpr operator int() const { return n; }
+  static const strong_ordering equal, greater, less;
+};
+constexpr strong_ordering strong_ordering::equal = {0};
+constexpr strong_ordering strong_ordering::greater = {1};
+constexpr strong_ordering strong_ordering::less = {-1};
+}
+
+class A {
+public:
+  auto operator<=>(const A &other) const = default;
+};
+
+void test_cxx_rewritten_binary_ops() {
+  A a1, a2;
+  bool result;
+  // should not change next line to (a1 nullptr a2)
+  result = (a1 < a2);
+  // CHECK-FIXES: result = (a1 < a2);
+  // should not change next line to (a1 nullptr a2)
+  result = (a1 >= a2);
+  // CHECK-FIXES: result = (a1 >= a2);
+  int *ptr = 0;
+  // CHECK-FIXES: int *ptr = nullptr;
+  result = (a1 > (ptr == 0 ? a1 : a2));
+  // CHECK-FIXES: result = (a1 > (ptr == nullptr ? a1 : a2));
+  result = (a1 > ((a1 > (ptr == 0 ? a1 : a2)) ? a1 : a2));
+  // CHECK-FIXES: result = (a1 > ((a1 > (ptr == nullptr ? a1 : a2)) ? a1 : 
a2));
+}
Index: clang-tools-extra/clang-tidy/modernize/UseNullptrCheck.cpp
===
--- clang-tools-extra/clang-tidy/modernize/UseNullptrCheck.cpp
+++ clang-tools-extra/clang-tidy/modernize/UseNullptrCheck.cpp
@@ -41,12 +41,28 @@
   
unless(hasImplicitDestinationType(qualType(substTemplateTypeParmType(,
   unless(hasSourceExpression(hasType(sugaredNullptrType();
 
+  auto isOrHasDescendant = [](auto InnerMatcher) {
+return anyOf(InnerMatcher, hasDescendant(InnerMatcher));
+  };
+
   return traverse(
   TK_AsIs,
-  castExpr(anyOf(ImplicitCastToNull,
- explicitCastExpr(hasDescendant(ImplicitCastToNull))),
-   unless(hasAncestor(explicitCastExpr(
-  .bind(CastSequence));
+  anyOf(castExpr(anyOf(ImplicitCastToNull,
+   
explicitCastExpr(hasDescendant(ImplicitCastToNull))),
+ unless(hasAncestor(explicitCastExpr())),
+ unless(hasAncestor(cxxRewrittenBinaryOperator(
+.bind(CastSequence),
+cxxRewrittenBinaryOperator(
+// Match rewritten operators, but verify (in the check method)
+// that if an implicit cast is found, it is not from another
+// nested rewritten operator.
+expr().bind("matchBinopOperands"),
+hasEitherOperand(isOrHasDescendant(
+implicitCastExpr(
+ImplicitCastToNull,
+hasAncestor(cxxRewrittenBinaryOperator().bind(
+"checkBinopOperands")))
+.bind(CastSequence));
 }
 
 bool isReplaceableRange(SourceLocation StartLoc, SourceLocation EndLoc,
@@ -480,6 +496,11 @@
   const auto *NullCast = Result.Nodes.getNodeAs(CastSequence);
   assert(NullCast && "Bad Callback. No node provided");
 
+  if (Result.Nodes.getNodeAs(
+  "matchBinopOperands") !=
+  Result.Nodes.getNodeAs("checkBinopOperands"))
+return;
+
   // Given an implicit null-ptr cast or an explicit cast with an implicit
   // null-to-pointer cast within use CastSequenceVisitor to identify sequences
   // of explicit casts that can be converted into 'nullptr'.


Index: clang-tools-extra/test/clang-tidy/checkers/modernize-use-nullptr-cxx20.cpp
===
--- /dev/null
+++ clang-tools-extra/test/clang-tidy/checkers/modernize-use-nullptr-cxx20.cpp
@@ -0,0 +1,34 @@
+// RUN: %check_clang_tidy -std=c++20 %s modernize-use-nullptr %t
+
+namespace std {
+struct strong_ordering {
+  int n;
+  constexpr operator int() const { return n; }
+  static const strong_ordering equal, greater, less;
+};
+constexpr strong_orderin

[clang] c945dc4 - PR48587: is_constant_evaluated() should not evaluate to true during a

2021-02-08 Thread Richard Smith via cfe-commits

Author: Richard Smith
Date: 2021-02-08T17:34:40-08:00
New Revision: c945dc4a5023d6a17d11fcda76509b94b36e34fc

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

LOG: PR48587: is_constant_evaluated() should not evaluate to true during a
variable's destruction if it didn't do so during construction.

The standard doesn't give any guidance as to what to do here, but this
approach seems reasonable and conservative, and has been proposed to the
standard committee.

Added: 


Modified: 
clang/lib/AST/ExprConstant.cpp
clang/test/CodeGenCXX/builtin-is-constant-evaluated.cpp

Removed: 




diff  --git a/clang/lib/AST/ExprConstant.cpp b/clang/lib/AST/ExprConstant.cpp
index b19f11208485..1ed9bbea84ee 100644
--- a/clang/lib/AST/ExprConstant.cpp
+++ b/clang/lib/AST/ExprConstant.cpp
@@ -14799,11 +14799,14 @@ bool Expr::EvaluateAsLValue(EvalResult &Result, const 
ASTContext &Ctx,
 
 static bool EvaluateDestruction(const ASTContext &Ctx, APValue::LValueBase 
Base,
 APValue DestroyedValue, QualType Type,
-SourceLocation Loc, Expr::EvalStatus &EStatus) 
{
-  EvalInfo Info(Ctx, EStatus, EvalInfo::EM_ConstantExpression);
+SourceLocation Loc, Expr::EvalStatus &EStatus,
+bool IsConstantDestruction) {
+  EvalInfo Info(Ctx, EStatus,
+IsConstantDestruction ? EvalInfo::EM_ConstantExpression
+  : EvalInfo::EM_ConstantFold);
   Info.setEvaluatingDecl(Base, DestroyedValue,
  EvalInfo::EvaluatingDeclKind::Dtor);
-  Info.InConstantContext = true;
+  Info.InConstantContext = IsConstantDestruction;
 
   LValue LVal;
   LVal.set(Base);
@@ -14857,7 +14860,8 @@ bool Expr::EvaluateAsConstantExpr(EvalResult &Result, 
const ASTContext &Ctx,
   // If this is a class template argument, it's required to have constant
   // destruction too.
   if (Kind == ConstantExprKind::ClassTemplateArgument &&
-  (!EvaluateDestruction(Ctx, Base, Result.Val, T, getBeginLoc(), Result) ||
+  (!EvaluateDestruction(Ctx, Base, Result.Val, T, getBeginLoc(), Result,
+true) ||
Result.HasSideEffects)) {
 // FIXME: Prefix a note to indicate that the problem is lack of constant
 // destruction.
@@ -14923,6 +14927,10 @@ bool VarDecl::evaluateDestruction(
   Expr::EvalStatus EStatus;
   EStatus.Diag = &Notes;
 
+  // Only treat the destruction as constant destruction if we formally have
+  // constant initialization (or are usable in a constant expression).
+  bool IsConstantDestruction = hasConstantInitialization();
+
   // Make a copy of the value for the destructor to mutate, if we know it.
   // Otherwise, treat the value as default-initialized; if the destructor works
   // anyway, then the destruction is constant (and must be essentially empty).
@@ -14933,7 +14941,8 @@ bool VarDecl::evaluateDestruction(
 return false;
 
   if (!EvaluateDestruction(getASTContext(), this, std::move(DestroyedValue),
-   getType(), getLocation(), EStatus) ||
+   getType(), getLocation(), EStatus,
+   IsConstantDestruction) ||
   EStatus.HasSideEffects)
 return false;
 

diff  --git a/clang/test/CodeGenCXX/builtin-is-constant-evaluated.cpp 
b/clang/test/CodeGenCXX/builtin-is-constant-evaluated.cpp
index 967c83496ab9..d30fefe55b4f 100644
--- a/clang/test/CodeGenCXX/builtin-is-constant-evaluated.cpp
+++ b/clang/test/CodeGenCXX/builtin-is-constant-evaluated.cpp
@@ -4,6 +4,7 @@
 // RUN: FileCheck -check-prefix=CHECK-DYN -input-file=%t.ll %s
 // RUN: FileCheck -check-prefix=CHECK-ARR -input-file=%t.ll %s
 // RUN: FileCheck -check-prefix=CHECK-FOLD -input-file=%t.ll %s
+// RUN: FileCheck -check-prefix=CHECK-DTOR -input-file=%t.ll %s
 
 using size_t = decltype(sizeof(int));
 
@@ -131,3 +132,94 @@ void test_ref_to_static_var() {
   // CHECK-FOLD: store i32* @_ZZ22test_ref_to_static_varvE10i_constant, i32** 
%r,
   int &r = __builtin_is_constant_evaluated() ? i_constant : i_non_constant;
 }
+
+int not_constexpr;
+
+// __builtin_is_constant_evaluated() should never evaluate to true during
+// destruction if it would not have done so during construction.
+//
+// FIXME: The standard doesn't say that it should ever return true when
+// evaluating a destructor call, even for a constexpr variable. That seems
+// obviously wrong.
+struct DestructorBCE {
+  int n;
+  constexpr DestructorBCE(int n) : n(n) {}
+  constexpr ~DestructorBCE() {
+if (!__builtin_is_constant_evaluated())
+  not_constexpr = 1;
+  }
+};
+
+// CHECK-DTOR-NOT: @_ZN13DestructorBCED{{.*}}@global_dtor_bce_1
+DestructorBCE global_dtor_bce_1(101);
+
+// CHECK-DTOR: load

[PATCH] D95168: [clang-format] Add InsertBraces option

2021-02-08 Thread Tiago Macarios via Phabricator via cfe-commits
tiagoma updated this revision to Diff 322240.
tiagoma added a comment.

Add support for do/while


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D95168

Files:
  clang/docs/ClangFormatStyleOptions.rst
  clang/include/clang/Format/Format.h
  clang/lib/Format/Format.cpp
  clang/unittests/Format/FormatTest.cpp

Index: clang/unittests/Format/FormatTest.cpp
===
--- clang/unittests/Format/FormatTest.cpp
+++ clang/unittests/Format/FormatTest.cpp
@@ -72,7 +72,10 @@
 EXPECT_EQ(Expected.str(), format(Expected, Style))
 << "Expected code is not stable";
 EXPECT_EQ(Expected.str(), format(Code, Style));
-if (Style.Language == FormatStyle::LK_Cpp) {
+// clang::format::internal::reformat does not run any of the options that
+// modify code for ObjC
+if (Style.Language == FormatStyle::LK_Cpp &&
+Style.InsertBraces == FormatStyle::BIS_Never) {
   // Objective-C++ is a superset of C++, so everything checked for C++
   // needs to be checked for Objective-C++ as well.
   FormatStyle ObjCStyle = Style;
@@ -15879,6 +15882,12 @@
   CHECK_PARSE("IndentExternBlock: false", IndentExternBlock,
   FormatStyle::IEBS_NoIndent);
 
+  Style.InsertBraces = FormatStyle::BIS_Never;
+  CHECK_PARSE("InsertBraces: Always", InsertBraces, FormatStyle::BIS_Always);
+  CHECK_PARSE("InsertBraces: WrapLikely", InsertBraces,
+  FormatStyle::BIS_WrapLikely);
+  CHECK_PARSE("InsertBraces: Never", InsertBraces, FormatStyle::BIS_Never);
+
   Style.BitFieldColonSpacing = FormatStyle::BFCS_None;
   CHECK_PARSE("BitFieldColonSpacing: Both", BitFieldColonSpacing,
   FormatStyle::BFCS_Both);
@@ -19050,6 +19059,215 @@
 "}",
 format(Source, Style));
 }
+
+TEST_F(FormatTest, InsertBraces) {
+  FormatStyle Style = getLLVMStyle();
+
+  StringRef IfSourceShort = "if (condition)\n"
+"  call_function(arg, arg);";
+  verifyFormat(IfSourceShort);
+
+  StringRef IfSourceLong = "if (condition)\n"
+   "  call_function(arg, arg, arg, arg, arg, arg);";
+  verifyFormat(IfSourceLong);
+
+  StringRef IfElseSourceShort = "if (condition)\n"
+"  a_function(arg, arg);\n"
+"else\n"
+"  another_function(arg, arg);";
+  verifyFormat(IfElseSourceShort);
+
+  StringRef IfElseSourceLong =
+  "if (condition)\n"
+  "  a_function(arg, arg, arg, arg, arg, arg);\n"
+  "else\n"
+  "  another_function(arg, arg, arg, arg, arg, arg);";
+  verifyFormat(IfElseSourceLong);
+
+  StringRef ForSourceShort = "for (auto val : container)\n"
+ "  call_function(arg, arg);";
+  verifyFormat(ForSourceShort);
+
+  StringRef ForSourceLong = "for (auto val : container)\n"
+"  call_function(arg, arg, arg, arg, arg, arg);";
+  verifyFormat(ForSourceLong);
+
+  StringRef WhileShort = "while (condition)\n"
+ "  call_function(arg, arg);";
+  verifyFormat(WhileShort);
+
+  StringRef WhileLong = "while (condition)\n"
+"  call_function(arg, arg, arg, arg, arg, arg);";
+  verifyFormat(WhileLong);
+
+  StringRef DoShort = "do\n"
+  "  call_function(arg, arg);\n"
+  "while (condition);";
+  verifyFormat(DoShort);
+
+  StringRef DoLong = "do\n"
+ "  call_function(arg, arg, arg, arg, arg, arg);\n"
+ "while (condition);";
+  verifyFormat(DoLong);
+
+  StringRef ChainedConditionals = "if (A)\n"
+  "  if (B)\n"
+  "callAB();\n"
+  "  else\n"
+  "callA();\n"
+  "else if (B)\n"
+  "  callB();\n"
+  "else\n"
+  "  call();";
+  verifyFormat(ChainedConditionals);
+
+  StringRef ChainedDoWhiles = "do\n"
+  "  while (arg++)\n"
+  "do\n"
+  "  while (arg++)\n"
+  "call_function(arg, arg);\n"
+  "while (condition);\n"
+  "while (condition);";
+  verifyFormat(ChainedDoWhiles);
+
+  StringRef IfWithMultilineComment =
+  "if /*condition*/ (condition) /*condition*/\n"
+  "  you_do_you();  /*condition*/";
+  verifyFormat(IfWithMultilineComment);
+
+  StringRef IfSinglelineCommentOnConditional = "if (condition) // my test\n"
+   "  you_do_you();";
+  verifyFormat(IfSinglelineCommentOnConditional);
+
+  Style.InsertBraces = FormatStyle::BI

[PATCH] D69560: [clang-tidy] Add 'bugprone-easily-swappable-parameters' check

2021-02-08 Thread Stephen Kelly via Phabricator via cfe-commits
steveire added a comment.

In D69560#2536597 , @whisperity wrote:

> In D69560#2536570 , @steveire wrote:
>
>> I haven't read through all the comments, but the word 'easily' implies 
>> 'desirable'. This check seems to be for finding params which are undesirably 
>> swappable, right?
>
> The `easily` was to mean that the swap can be done with little effort (i.e. 
> "in an easy fashion"?) and by accident.

I understand that. The problem is the name. The `signal-to-kill-thread` check 
is `bad`. The `erase` check is `inaccurate`. The `roundings` check is 
`incorrect`. The `operator-in-strlen-in-alloc` check is `misplaced`. Those are 
all words that indicate the negative. Your name indicates the positive 
("easily"). The name indicates that the swappable params are desirable.

Why "easily" instead of "suspicious", "spuriously" or any of the other words 
that are already used?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D69560

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


[clang] 52f312c - Fix failure in cuda-external-tools.cu

2021-02-08 Thread Yaxun Liu via cfe-commits

Author: Yaxun (Sam) Liu
Date: 2021-02-08T19:27:43-05:00
New Revision: 52f312c69e1049e1f3034baf7cb9d88875f45c9a

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

LOG: Fix failure in cuda-external-tools.cu

-fgpu-rdc is output in different order

Added: 


Modified: 
clang/test/Driver/cuda-external-tools.cu

Removed: 




diff  --git a/clang/test/Driver/cuda-external-tools.cu 
b/clang/test/Driver/cuda-external-tools.cu
index 5da6ffe0262e..f73363508efe 100644
--- a/clang/test/Driver/cuda-external-tools.cu
+++ b/clang/test/Driver/cuda-external-tools.cu
@@ -92,10 +92,10 @@
 // CHECK: "-cc1"
 // ARCH64-SAME: "-triple" "nvptx64-nvidia-cuda"
 // ARCH32-SAME: "-triple" "nvptx-nvidia-cuda"
-// RDC-SAME: "-fgpu-rdc"
-// CHECK-NOT: "-fgpu-rdc"
 // SM20-SAME: "-target-cpu" "sm_20"
 // SM35-SAME: "-target-cpu" "sm_35"
+// RDC-SAME: "-fgpu-rdc"
+// CHECK-NOT: "-fgpu-rdc"
 // SM20-SAME: "-o" "[[PTXFILE:[^"]*]]"
 // SM35-SAME: "-o" "[[PTXFILE:[^"]*]]"
 



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


[PATCH] D96082: [clang-tidy] Add 'readability-useless-return-value' check

2021-02-08 Thread Stephen Kelly via Phabricator via cfe-commits
steveire added a comment.

In D96082#2545807 , @LukasHanel wrote:

> Hi, thanks for discussing my proposal!
> Although I think it can stand as is, I was looking for feedback:
>
> - Is the name good?
> - Is the `readability` group  good? Or better in `misc`?
> - too slow, too fast?
> - More precision required?
> - Usefulness of the fix-it's

I agree with @njames93 that this check is dangerous. Even if you extended it to 
port callExprs, that would only work in translation units which can see the 
definition.

I have made checks to do that kind of thing (port from raw pointers to 
`unique_ptr`), but it involves running a check to generate a list of functions 
that will be ported in one step and doing the actual change (including 
callExprs across all TUs) in a second step.

A tool like this would have to something similar to be useful, but I don't 
think such a check should be upstream at this point. We don't have good 
infrastructure to record the signatures that will be changed. What I did was 
create/touch files to the filesystem named as function signatures in the first 
step, and in the second step read the list of files to know what signatures 
should be ported. Using the filesystem meant uniqueness and that a 
concurrently-running instances didn't encounter syncronization issues. Perhaps 
something like that could be made generic and upstreamed to support this kind 
of case.

In addition to that practical problem, there are some functions which 
deliberately always return the same value and you don't have a way to 
distinguish them other than by adding an option to ignore them. It might make 
the checker a bit of a burden. The kinds of functions I'm referring to include 
functions which give a name to an otherwise-magic number (`int sentinalValue() 
{ return 0; }`), virtual methods (I see you already handle those), Visitors, 
dummy implementations of APIs which may not be implemented on a platform, CRTP 
interfaces, there may be others.

Am I missing something?

> - Should I add options?
>
> Anyhow, last year I was refactoring our companies code base and often 
> manually searched for functions that would be identified by such checker. And 
> as you say, I did not implement the corner cases yet.

Does this mean that you didn't try to run this tool on a real codebase? (ie 
your company code is already changed and doesn't need it anymore). You may run 
into the cross-TU issue if you run it on a codebase.

> Clang-tidy is a really easy environment to write such checkers, Kudos to all 
> the contributors and maintainers.

Glad it's useful to you.

> On your comments:
>
> In D96082#2544836 , @njames93 wrote:
>
>> This check, more specifically the fixes, seem quite dangerous. Changing 
>> function signatures is highly likely to cause compilation issues.
>
> This seems to be a general issue with clang-tidy's fixes.
> It seems some fixes are more of a gimmick and shouldn't be used without 
> supervision.

I think you might be right. Do you have a list of such checks? Maybe they 
should be removed.

> I did not find any other checker that changed the function signature, is 
> there any guidance against this?

I don't think there are any because they don't work across TUs. If we don't 
have guidance on this, we should probably create some. My position is that the 
guidance should say that we shouldn't have such checks until we have the 
required infrastructure to implement them correctly.

>> For a starters this check doesn't appear to examine call sites of the 
>> function to ensure they don't use the return value.
>
> I have considered this, but it would double the complexity of the checker, so 
> I did not work on it yet.
> Yes, it is a good safety net.
> However, it could also hide two issues:
>
> 1. Inconsistent use (or not use) of the return value - it is actually a sign 
> of the return value being useless (Note: this is a common checker for 
> commercial static analyzers).

Indeed, this doesn't seem to be an issue. If the function returns a constant, 
then the behavior at the call site is known and can be simplified to operate 
the same way without checking the return value.

> - Propagation of the useless return value, let's say `b` checks useless 
> return value of `a`, and returns it, but `c` does not check return value of 
> `b`.
>
>   int a() { return 0; } // "useless"
>   int b() { return a(); } // "checked"
>   int c() {
>   b();  // not checked
>  // or even
>  int ret = b();// "checked"
>  if (ret) {
>  printf("something went wrong"); // or maybe the return value was 
> useless in the first place
>  }
>  //...
>   }
>
> Regarding the propagation, anyhow, such refactoring needs to be done in 
> steps: you fix one function, then the linter will highlight the next function.

Yes.


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://re

[PATCH] D96246: Make sure a module file with errors produced via '-fallow-pcm-with-compiler-errors' can be loaded when using implicit modules

2021-02-08 Thread Argyrios Kyrtzidis 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 rGa8cb39bab04c: Make sure a module file with errors produced 
via '-fallow-pcm-with-compiler… (authored by akyrtzi).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D96246

Files:
  clang/include/clang/Serialization/ASTReader.h
  clang/lib/Frontend/CompilerInstance.cpp
  clang/lib/Serialization/ASTReader.cpp
  clang/test/Modules/load-module-with-errors.m

Index: clang/test/Modules/load-module-with-errors.m
===
--- clang/test/Modules/load-module-with-errors.m
+++ clang/test/Modules/load-module-with-errors.m
@@ -1,3 +1,14 @@
+// Note: the run lines follow their respective tests, since line/column
+// matter in this test.
+
+// pcherror-error@* {{PCH file contains compiler errors}}
+@import error; // notallowerror-error {{could not build module 'error'}}
+// expected-no-diagnostics
+
+void test(Error *x) {
+  [x method];
+}
+
 // RUN: rm -rf %t
 // RUN: mkdir %t
 // RUN: mkdir %t/prebuilt
@@ -48,21 +59,27 @@
 // the verify would fail as it would be the PCH error instead)
 // RUN: %clang_cc1 -fsyntax-only -fmodules \
 // RUN:   -fmodules-cache-path=%t -fimplicit-module-maps -I %S/Inputs/error \
-// RUN:   -x objective-c -verify %s
+// RUN:   -x objective-c -verify=notallowerror %s
 
 // allow-pcm-with-compiler-errors should also allow errors in PCH
 // RUN: %clang_cc1 -fallow-pcm-with-compiler-errors -x objective-c \
 // RUN:   -o %t/check.pch -emit-pch %S/Inputs/error/error.h
 
-// pcherror-error@* {{PCH file contains compiler errors}}
-@import error; // expected-error {{could not build module 'error'}}
-
-void test(Error *x) {
-  [x method];
-}
-
 // CHECK: @interface Error
 // CHECK-NEXT: - (int)method;
 // CHECK-NEXT: - (id)method2;
 // CHECK-NEXT: @end
 // CHECK: void test(Error *x)
+
+// RUN: c-index-test -code-completion-at=%s:9:6 %s -fmodules -fmodules-cache-path=%t \
+// RUN:   -Xclang -fallow-pcm-with-compiler-errors -I %S/Inputs/error | FileCheck -check-prefix=COMPLETE %s
+// COMPLETE: ObjCInstanceMethodDecl:{ResultType int}{TypedText method}
+// COMPLETE: ObjCInstanceMethodDecl:{ResultType id}{TypedText method2}
+
+// RUN: c-index-test -test-load-source local %s -fmodules -fmodules-cache-path=%t \
+// RUN:   -Xclang -fallow-pcm-with-compiler-errors -I %S/Inputs/error | FileCheck -check-prefix=SOURCE %s
+// SOURCE: load-module-with-errors.m:8:6: FunctionDecl=test:8:6 (Definition) Extent=[8:1 - 10:2]
+// SOURCE: load-module-with-errors.m:8:18: ParmDecl=x:8:18 (Definition) Extent=[8:11 - 8:19]
+// SOURCE: load-module-with-errors.m:8:11: ObjCClassRef=Error:3:12 Extent=[8:11 - 8:16]
+// SOURCE: load-module-with-errors.m:8:21: CompoundStmt= Extent=[8:21 - 10:2]
+// SOURCE: load-module-with-errors.m:9:3: ObjCMessageExpr=method:4:8 Extent=[9:3 - 9:13]
Index: clang/lib/Serialization/ASTReader.cpp
===
--- clang/lib/Serialization/ASTReader.cpp
+++ clang/lib/Serialization/ASTReader.cpp
@@ -2751,8 +2751,9 @@
 
   bool hasErrors = Record[6];
   if (hasErrors && !DisableValidation) {
-// Always rebuild modules from the cache on an error
-if (F.Kind == MK_ImplicitModule)
+// If requested by the caller, mark modules on error as out-of-date.
+if (F.Kind == MK_ImplicitModule &&
+(ClientLoadCapabilities & ARR_TreatModuleWithErrorsAsOutOfDate))
   return OutOfDate;
 
 if (!AllowASTWithCompilerErrors) {
Index: clang/lib/Frontend/CompilerInstance.cpp
===
--- clang/lib/Frontend/CompilerInstance.cpp
+++ clang/lib/Frontend/CompilerInstance.cpp
@@ -1144,7 +1144,10 @@
   // module generation thread crashed.
   Instance.clearOutputFiles(/*EraseFiles=*/true);
 
-  return !Instance.getDiagnostics().hasErrorOccurred();
+  // If \p AllowPCMWithCompilerErrors is set return 'success' even if errors
+  // occurred.
+  return !Instance.getDiagnostics().hasErrorOccurred() ||
+ Instance.getFrontendOpts().AllowPCMWithCompilerErrors;
 }
 
 static const FileEntry *getPublicModuleMap(const FileEntry *File,
@@ -1697,7 +1700,8 @@
   // Try to load the module file. If we are not trying to load from the
   // module cache, we don't know how to rebuild modules.
   unsigned ARRFlags = Source == MS_ModuleCache
-  ? ASTReader::ARR_OutOfDate | ASTReader::ARR_Missing
+  ? ASTReader::ARR_OutOfDate | ASTReader::ARR_Missing |
+ASTReader::ARR_TreatModuleWithErrorsAsOutOfDate
   : Source == MS_PrebuiltModulePath
 ? 0
 : ASTReader::ARR_ConfigurationMismatch;
Index: clang/include/clang/Serialization/ASTR

[clang] a8cb39b - Make sure a module file with errors produced via '-fallow-pcm-with-compiler-errors' can be loaded when using implicit modules

2021-02-08 Thread Argyrios Kyrtzidis via cfe-commits

Author: Argyrios Kyrtzidis
Date: 2021-02-08T16:10:39-08:00
New Revision: a8cb39bab04c317c9886ec3a332f3b70ce27ae4f

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

LOG: Make sure a module file with errors produced via 
'-fallow-pcm-with-compiler-errors' can be loaded when using implicit modules

A module with errors would be marked as out-of-date, then the `compilerModule` 
action would produce it, but due to the error it would be treated as failure 
and the resulting PCM would not get used.

rdar://74087062

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

Added: 


Modified: 
clang/include/clang/Serialization/ASTReader.h
clang/lib/Frontend/CompilerInstance.cpp
clang/lib/Serialization/ASTReader.cpp
clang/test/Modules/load-module-with-errors.m

Removed: 




diff  --git a/clang/include/clang/Serialization/ASTReader.h 
b/clang/include/clang/Serialization/ASTReader.h
index d0d2a68114c7..0df687c05366 100644
--- a/clang/include/clang/Serialization/ASTReader.h
+++ b/clang/include/clang/Serialization/ASTReader.h
@@ -1543,7 +1543,11 @@ class ASTReader
 /// The client can handle an AST file that cannot load because it's
 /// compiled configuration doesn't match that of the context it was
 /// loaded into.
-ARR_ConfigurationMismatch = 0x8
+ARR_ConfigurationMismatch = 0x8,
+
+/// If a module file is marked with errors treat it as out-of-date so the
+/// caller can rebuild it.
+ARR_TreatModuleWithErrorsAsOutOfDate = 0x10
   };
 
   /// Load the AST file designated by the given file name.

diff  --git a/clang/lib/Frontend/CompilerInstance.cpp 
b/clang/lib/Frontend/CompilerInstance.cpp
index 956877d34680..7c2b2bf57917 100644
--- a/clang/lib/Frontend/CompilerInstance.cpp
+++ b/clang/lib/Frontend/CompilerInstance.cpp
@@ -1144,7 +1144,10 @@ compileModuleImpl(CompilerInstance &ImportingInstance, 
SourceLocation ImportLoc,
   // module generation thread crashed.
   Instance.clearOutputFiles(/*EraseFiles=*/true);
 
-  return !Instance.getDiagnostics().hasErrorOccurred();
+  // If \p AllowPCMWithCompilerErrors is set return 'success' even if errors
+  // occurred.
+  return !Instance.getDiagnostics().hasErrorOccurred() ||
+ Instance.getFrontendOpts().AllowPCMWithCompilerErrors;
 }
 
 static const FileEntry *getPublicModuleMap(const FileEntry *File,
@@ -1697,7 +1700,8 @@ ModuleLoadResult 
CompilerInstance::findOrCompileModuleAndReadAST(
   // Try to load the module file. If we are not trying to load from the
   // module cache, we don't know how to rebuild modules.
   unsigned ARRFlags = Source == MS_ModuleCache
-  ? ASTReader::ARR_OutOfDate | ASTReader::ARR_Missing
+  ? ASTReader::ARR_OutOfDate | ASTReader::ARR_Missing |
+ASTReader::ARR_TreatModuleWithErrorsAsOutOfDate
   : Source == MS_PrebuiltModulePath
 ? 0
 : ASTReader::ARR_ConfigurationMismatch;

diff  --git a/clang/lib/Serialization/ASTReader.cpp 
b/clang/lib/Serialization/ASTReader.cpp
index 99579f7956ed..e3d3938ac9d6 100644
--- a/clang/lib/Serialization/ASTReader.cpp
+++ b/clang/lib/Serialization/ASTReader.cpp
@@ -2751,8 +2751,9 @@ ASTReader::ReadControlBlock(ModuleFile &F,
 
   bool hasErrors = Record[6];
   if (hasErrors && !DisableValidation) {
-// Always rebuild modules from the cache on an error
-if (F.Kind == MK_ImplicitModule)
+// If requested by the caller, mark modules on error as out-of-date.
+if (F.Kind == MK_ImplicitModule &&
+(ClientLoadCapabilities & ARR_TreatModuleWithErrorsAsOutOfDate))
   return OutOfDate;
 
 if (!AllowASTWithCompilerErrors) {

diff  --git a/clang/test/Modules/load-module-with-errors.m 
b/clang/test/Modules/load-module-with-errors.m
index 3dceb545ad9c..3a951d2cdaa6 100644
--- a/clang/test/Modules/load-module-with-errors.m
+++ b/clang/test/Modules/load-module-with-errors.m
@@ -1,3 +1,14 @@
+// Note: the run lines follow their respective tests, since line/column
+// matter in this test.
+
+// pcherror-error@* {{PCH file contains compiler errors}}
+@import error; // notallowerror-error {{could not build module 'error'}}
+// expected-no-diagnostics
+
+void test(Error *x) {
+  [x method];
+}
+
 // RUN: rm -rf %t
 // RUN: mkdir %t
 // RUN: mkdir %t/prebuilt
@@ -48,21 +59,27 @@
 // the verify would fail as it would be the PCH error instead)
 // RUN: %clang_cc1 -fsyntax-only -fmodules \
 // RUN:   -fmodules-cache-path=%t -fimplicit-module-maps -I %S/Inputs/error \
-// RUN:   -x objective-c -verify %s
+// RUN:   -x objective-c -verify=notallowerror %s
 
 // allow-pcm-with-compiler-errors should also allow errors in PCH
 // RU

[PATCH] D96105: [CUDA][HIP] Pass -fgpu-rdc to host clang -cc1

2021-02-08 Thread Yaxun Liu via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG1dab94f9ede5: [CUDA][HIP] Pass -fgpu-rdc to host clang -cc1 
(authored by yaxunl).
Herald added a project: clang.

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D96105

Files:
  clang/lib/Driver/ToolChains/Clang.cpp
  clang/lib/Driver/ToolChains/Cuda.cpp
  clang/lib/Driver/ToolChains/HIP.cpp
  clang/test/Driver/hip-rdc-device-only.hip
  clang/test/Driver/hip-toolchain-rdc-separate.hip
  clang/test/Driver/hip-toolchain-rdc-static-lib.hip
  clang/test/Driver/hip-toolchain-rdc.hip

Index: clang/test/Driver/hip-toolchain-rdc.hip
===
--- clang/test/Driver/hip-toolchain-rdc.hip
+++ clang/test/Driver/hip-toolchain-rdc.hip
@@ -21,6 +21,7 @@
 // CHECK-SAME: "-aux-triple" "amdgcn-amd-amdhsa"
 // CHECK-SAME: "-emit-obj"
 // CHECK-SAME: {{.*}} "-main-file-name" "a.cu"
+// CHECK-SAME: "-fgpu-rdc"
 // CHECK-SAME: {{.*}} "-o" [[A_OBJ_HOST:".*o"]] "-x" "hip"
 // CHECK-SAME: {{.*}} [[A_SRC:".*a.cu"]]
 
@@ -28,6 +29,7 @@
 // CHECK-SAME: "-aux-triple" "amdgcn-amd-amdhsa"
 // CHECK-SAME: "-emit-obj"
 // CHECK-SAME: {{.*}} "-main-file-name" "b.hip"
+// CHECK-SAME: "-fgpu-rdc"
 // CHECK-SAME: {{.*}} "-o" [[B_OBJ_HOST:".*o"]] "-x" "hip"
 // CHECK-SAME: {{.*}} [[B_SRC:".*b.hip"]]
 
@@ -36,10 +38,11 @@
 // CHECK-SAME: "-aux-triple" "x86_64-unknown-linux-gnu"
 // CHECK-SAME: "-emit-llvm-bc"
 // CHECK-SAME: {{.*}} "-main-file-name" "a.cu"
-// CHECK-SAME: "-fcuda-is-device" "-fgpu-rdc" "-fcuda-allow-variadic-functions" "-fvisibility" "hidden"
+// CHECK-SAME: "-fcuda-is-device" "-fcuda-allow-variadic-functions" "-fvisibility" "hidden"
 // CHECK-SAME: "-fapply-global-visibility-to-externs"
 // CHECK-SAME: "{{.*}}lib1.bc" "{{.*}}lib2.bc"
 // CHECK-SAME: "-target-cpu" "gfx803"
+// CHECK-SAME: "-fgpu-rdc"
 // CHECK-SAME: {{.*}} "-o" [[A_BC1:".*bc"]] "-x" "hip"
 // CHECK-SAME: {{.*}} [[A_SRC]]
 
@@ -47,10 +50,11 @@
 // CHECK-SAME: "-aux-triple" "x86_64-unknown-linux-gnu"
 // CHECK-SAME: "-emit-llvm-bc"
 // CHECK-SAME: {{.*}} "-main-file-name" "b.hip"
-// CHECK-SAME: "-fcuda-is-device" "-fgpu-rdc" "-fcuda-allow-variadic-functions" "-fvisibility" "hidden"
+// CHECK-SAME: "-fcuda-is-device" "-fcuda-allow-variadic-functions" "-fvisibility" "hidden"
 // CHECK-SAME: "-fapply-global-visibility-to-externs"
 // CHECK-SAME: "{{.*}}lib1.bc" "{{.*}}lib2.bc"
 // CHECK-SAME: "-target-cpu" "gfx803"
+// CHECK-SAME: "-fgpu-rdc"
 // CHECK-SAME: {{.*}} "-o" [[B_BC1:".*bc"]] "-x" "hip"
 // CHECK-SAME: {{.*}} [[B_SRC]]
 
@@ -66,7 +70,7 @@
 // CHECK-SAME: "-aux-triple" "x86_64-unknown-linux-gnu"
 // CHECK-SAME: "-emit-llvm-bc"
 // CHECK-SAME: {{.*}} "-main-file-name" "a.cu"
-// CHECK-SAME: "-fcuda-is-device" "-fgpu-rdc"
+// CHECK-SAME: "-fcuda-is-device"
 // CHECK-SAME: "{{.*}}lib1.bc" "{{.*}}lib2.bc"
 // CHECK-SAME: "-target-cpu" "gfx900"
 // CHECK-SAME: {{.*}} "-o" [[A_BC2:".*bc"]] "-x" "hip"
@@ -76,9 +80,10 @@
 // CHECK-SAME: "-aux-triple" "x86_64-unknown-linux-gnu"
 // CHECK-SAME: "-emit-llvm-bc"
 // CHECK-SAME: {{.*}} "-main-file-name" "b.hip"
-// CHECK-SAME: "-fcuda-is-device" "-fgpu-rdc"
+// CHECK-SAME: "-fcuda-is-device"
 // CHECK-SAME: "{{.*}}lib1.bc" "{{.*}}lib2.bc"
 // CHECK-SAME: "-target-cpu" "gfx900"
+// CHECK-SAME: "-fgpu-rdc"
 // CHECK-SAME: {{.*}} "-o" [[B_BC2:".*bc"]] "-x" "hip"
 // CHECK-SAME: {{.*}} [[B_SRC]]
 
Index: clang/test/Driver/hip-toolchain-rdc-static-lib.hip
===
--- clang/test/Driver/hip-toolchain-rdc-static-lib.hip
+++ clang/test/Driver/hip-toolchain-rdc-static-lib.hip
@@ -15,6 +15,7 @@
 // CHECK-SAME: "-aux-triple" "amdgcn-amd-amdhsa"
 // CHECK-SAME: "-emit-obj"
 // CHECK-SAME: {{.*}} "-main-file-name" "a.cu"
+// CHECK-SAME: "-fgpu-rdc"
 // CHECK-SAME: {{.*}} "-o" [[A_OBJ_HOST:".*o"]] "-x" "hip"
 // CHECK-SAME: {{.*}} [[A_SRC:".*a.cu"]]
 
@@ -22,6 +23,7 @@
 // CHECK-SAME: "-aux-triple" "amdgcn-amd-amdhsa"
 // CHECK-SAME: "-emit-obj"
 // CHECK-SAME: {{.*}} "-main-file-name" "b.hip"
+// CHECK-SAME: "-fgpu-rdc"
 // CHECK-SAME: {{.*}} "-o" [[B_OBJ_HOST:".*o"]] "-x" "hip"
 // CHECK-SAME: {{.*}} [[B_SRC:".*b.hip"]]
 
@@ -30,8 +32,9 @@
 // CHECK-SAME: "-aux-triple" "x86_64-unknown-linux-gnu"
 // CHECK-SAME: "-emit-llvm-bc"
 // CHECK-SAME: {{.*}} "-main-file-name" "a.cu"
-// CHECK-SAME: "-fcuda-is-device" "-fgpu-rdc"
+// CHECK-SAME: "-fcuda-is-device"
 // CHECK-SAME: "-target-cpu" "gfx803"
+// CHECK-SAME: "-fgpu-rdc"
 // CHECK-SAME: {{.*}} "-o" [[A_BC1:".*bc"]] "-x" "hip"
 // CHECK-SAME: {{.*}} [[A_SRC]]
 
@@ -39,8 +42,9 @@
 // CHECK-SAME: "-aux-triple" "x86_64-unknown-linux-gnu"
 // CHECK-SAME: "-emit-llvm-bc"
 // CHECK-SAME: {{.*}} "-main-file-name" "b.hip"
-// CHECK-SAME: "-fcuda-is-device" "-fgpu-rdc"
+// CHECK-SAME: "-fcuda-is-device"
 // CHECK-SAME: "-target-cpu" "gfx803"
+// CHECK-SAME: "-fgpu-rdc"
 // CHECK-SAME: {{.*}} "-o" [[B_B

[clang] 1dab94f - [CUDA][HIP] Pass -fgpu-rdc to host clang -cc1

2021-02-08 Thread Yaxun Liu via cfe-commits

Author: Yaxun (Sam) Liu
Date: 2021-02-08T19:08:20-05:00
New Revision: 1dab94f9ede5d506d6ff9c61448a8e20d43e05a7

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

LOG: [CUDA][HIP] Pass -fgpu-rdc to host clang -cc1

Currently -fgpu-rdc is not passed to host clang -cc1.
This causes issue because -fgpu-rdc affects shadow
variable linkage in host compilation.

Reviewed by: Artem Belevich

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

Added: 


Modified: 
clang/lib/Driver/ToolChains/Clang.cpp
clang/lib/Driver/ToolChains/Cuda.cpp
clang/lib/Driver/ToolChains/HIP.cpp
clang/test/Driver/hip-rdc-device-only.hip
clang/test/Driver/hip-toolchain-rdc-separate.hip
clang/test/Driver/hip-toolchain-rdc-static-lib.hip
clang/test/Driver/hip-toolchain-rdc.hip

Removed: 




diff  --git a/clang/lib/Driver/ToolChains/Clang.cpp 
b/clang/lib/Driver/ToolChains/Clang.cpp
index 42338abf2e8a..e2d47df6f411 100644
--- a/clang/lib/Driver/ToolChains/Clang.cpp
+++ b/clang/lib/Driver/ToolChains/Clang.cpp
@@ -5692,6 +5692,8 @@ void Clang::ConstructJob(Compilation &C, const JobAction 
&JA,
   }
 
   if (IsCuda || IsHIP) {
+if (Args.hasFlag(options::OPT_fgpu_rdc, options::OPT_fno_gpu_rdc, false))
+  CmdArgs.push_back("-fgpu-rdc");
 if (Args.hasFlag(options::OPT_fgpu_defer_diag,
  options::OPT_fno_gpu_defer_diag, false))
   CmdArgs.push_back("-fgpu-defer-diag");

diff  --git a/clang/lib/Driver/ToolChains/Cuda.cpp 
b/clang/lib/Driver/ToolChains/Cuda.cpp
index d14776c5f5ba..9d050b944b5b 100644
--- a/clang/lib/Driver/ToolChains/Cuda.cpp
+++ b/clang/lib/Driver/ToolChains/Cuda.cpp
@@ -689,10 +689,6 @@ void CudaToolChain::addClangTargetOptions(
 if (DriverArgs.hasFlag(options::OPT_fcuda_approx_transcendentals,
options::OPT_fno_cuda_approx_transcendentals, 
false))
   CC1Args.push_back("-fcuda-approx-transcendentals");
-
-if (DriverArgs.hasFlag(options::OPT_fgpu_rdc, options::OPT_fno_gpu_rdc,
-   false))
-  CC1Args.push_back("-fgpu-rdc");
   }
 
   if (DriverArgs.hasArg(options::OPT_nogpulib))

diff  --git a/clang/lib/Driver/ToolChains/HIP.cpp 
b/clang/lib/Driver/ToolChains/HIP.cpp
index a84c0c257033..12aaecad7fab 100644
--- a/clang/lib/Driver/ToolChains/HIP.cpp
+++ b/clang/lib/Driver/ToolChains/HIP.cpp
@@ -261,10 +261,8 @@ void HIPToolChain::addClangTargetOptions(
  options::OPT_fno_cuda_approx_transcendentals, false))
 CC1Args.push_back("-fcuda-approx-transcendentals");
 
-  if (DriverArgs.hasFlag(options::OPT_fgpu_rdc, options::OPT_fno_gpu_rdc,
- false))
-CC1Args.push_back("-fgpu-rdc");
-  else
+  if (!DriverArgs.hasFlag(options::OPT_fgpu_rdc, options::OPT_fno_gpu_rdc,
+  false))
 CC1Args.append({"-mllvm", "-amdgpu-internalize-symbols"});
 
   StringRef MaxThreadsPerBlock =

diff  --git a/clang/test/Driver/hip-rdc-device-only.hip 
b/clang/test/Driver/hip-rdc-device-only.hip
index 541cbf848d66..d12e9e376023 100644
--- a/clang/test/Driver/hip-rdc-device-only.hip
+++ b/clang/test/Driver/hip-rdc-device-only.hip
@@ -52,9 +52,10 @@
 // EMITBC-SAME: "-emit-llvm-bc"
 // EMITLL-SAME: "-emit-llvm"
 // COMMON-SAME: {{.*}} "-main-file-name" "a.cu"
-// COMMON-SAME: "-fcuda-is-device" "-fgpu-rdc" 
"-fcuda-allow-variadic-functions" "-fvisibility" "hidden"
+// COMMON-SAME: "-fcuda-is-device" "-fcuda-allow-variadic-functions" 
"-fvisibility" "hidden"
 // COMMON-SAME: "-fapply-global-visibility-to-externs"
 // COMMON-SAME: "-target-cpu" "gfx803"
+// COMMON-SAME: "-fgpu-rdc"
 // EMITBC-SAME: {{.*}} "-o" {{"a.*bc"}} "-x" "hip"
 // EMITLL-SAME: {{.*}} "-o" {{"a.*ll"}} "-x" "hip"
 // CHECK-SAME: {{.*}} {{".*a.cu"}}
@@ -64,9 +65,10 @@
 // EMITBC-SAME: "-emit-llvm-bc"
 // EMITLL-SAME: "-emit-llvm"
 // COMMON-SAME: {{.*}} "-main-file-name" "a.cu"
-// COMMON-SAME: "-fcuda-is-device" "-fgpu-rdc" 
"-fcuda-allow-variadic-functions" "-fvisibility" "hidden"
+// COMMON-SAME: "-fcuda-is-device" "-fcuda-allow-variadic-functions" 
"-fvisibility" "hidden"
 // COMMON-SAME: "-fapply-global-visibility-to-externs"
 // COMMON-SAME: "-target-cpu" "gfx900"
+// COMMON-SAME: "-fgpu-rdc"
 // EMITBC-SAME: {{.*}} "-o" {{"a.*bc"}} "-x" "hip"
 // EMITLL-SAME: {{.*}} "-o" {{"a.*ll"}} "-x" "hip"
 // COMMON-SAME: {{.*}} {{".*a.cu"}}
@@ -76,9 +78,10 @@
 // EMITBC-SAME: "-emit-llvm-bc"
 // EMITLL-SAME: "-emit-llvm"
 // COMMON-SAME: {{.*}} "-main-file-name" "b.hip"
-// COMMON-SAME: "-fcuda-is-device" "-fgpu-rdc" 
"-fcuda-allow-variadic-functions" "-fvisibility" "hidden"
+// COMMON-SAME: "-fcuda-is-device" "-fcuda-allow-variadic-functions" 
"-fvisibility" "hidden"
 // COMMON-SAME: "-fapply-global-visibility-to-externs"
 // COMMON-SAME: "-target-cpu" "gfx803"
+/

[PATCH] D96248: [OpenMP][AMDGPU] Add support for linking libomptarget bitcode

2021-02-08 Thread Shilei Tian via Phabricator via cfe-commits
tianshilei1992 added a comment.

Generally LGTM.

In D96248#2549339 , @JonChesterfield 
wrote:

> The existing search logic looks in clang's lib and LIBRARY_PATH, I think we 
> should probably look in the runtime directory as well for running from the 
> build tree. That's separate to this change though.

I don't think it's necessary as we can add the runtime directory to 
`LIBRARY_PATH` when configuring `lit`.




Comment at: clang/lib/Driver/ToolChains/AMDGPUOpenMP.cpp:193
   CC1Args.push_back("-emit-llvm-bc");
+
+  std::string BitcodeSuffix = "amdgcn-" + GpuArch.str();

JonChesterfield wrote:
> Need `if (DriverArgs.hasArg(options::OPT_nogpulib)) return;` here or we can't 
> build the deviceRTL without already having one on disk
FWIW, NVPTX `deviceRTLs` is built by directly calling FE, not via clang driver. 
`clang -fopenmp -fopenmp-targets=xxx` basically consists of two passes, and 
therefore generates two IRs, which is not what we expect. I'm not sure we 
really need the if statement.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D96248

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


[PATCH] D94640: adds more checks to -Wfree-nonheap-object

2021-02-08 Thread Christopher Di Bella via Phabricator via cfe-commits
cjdb updated this revision to Diff 38.
cjdb marked 4 inline comments as done.
cjdb added a comment.
Herald added a subscriber: cfe-commits.

addresses comments


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D94640

Files:
  clang/lib/Sema/SemaChecking.cpp
  clang/test/Analysis/free.c
  clang/test/Analysis/free.cpp
  clang/test/Analysis/weak-functions.c

Index: clang/test/Analysis/weak-functions.c
===
--- clang/test/Analysis/weak-functions.c
+++ clang/test/Analysis/weak-functions.c
@@ -71,7 +71,9 @@
 void free(void *) __attribute__((weak_import));
 
 void t10 () {
-  free((void*)&t10); // expected-warning {{Argument to free() is the address of the function 't10', which is not memory allocated by malloc()}}
+  free((void*)&t10);
+  // expected-warning@-1{{Argument to free() is the address of the function 't10', which is not memory allocated by malloc()}}
+  // expected-warning@-2{{attempt to call free on non-heap object 't10'}}
 }
 
 //===--===
Index: clang/test/Analysis/free.cpp
===
--- /dev/null
+++ clang/test/Analysis/free.cpp
@@ -0,0 +1,210 @@
+// RUN: %clang_analyze_cc1 -fblocks -verify %s -analyzer-store=region \
+// RUN:   -analyzer-checker=core \
+// RUN:   -analyzer-checker=unix.Malloc
+//
+// RUN: %clang_analyze_cc1 -fblocks -verify %s -analyzer-store=region \
+// RUN:   -analyzer-checker=core \
+// RUN:   -analyzer-checker=unix.Malloc \
+// RUN:   -analyzer-config unix.DynamicMemoryModeling:Optimistic=true
+namespace std {
+  using size_t = decltype(sizeof(int));
+  void free(void *);
+}
+
+extern "C" void free(void *);
+extern "C" void *alloca(std::size_t);
+
+void t1a () {
+  int a[] = { 1 };
+  free(a);
+  // expected-warning@-1{{Argument to free() is the address of the local variable 'a', which is not memory allocated by malloc()}}
+  // expected-warning@-2{{attempt to call free on non-heap object 'a'}}
+}
+
+void t1b () {
+  int a[] = { 1 };
+  std::free(a);
+  // expected-warning@-1{{Argument to free() is the address of the local variable 'a', which is not memory allocated by malloc()}}
+  // expected-warning@-2{{attempt to call std::free on non-heap object 'a'}}
+}
+
+void t2a () {
+  int a = 1;
+  free(&a);
+  // expected-warning@-1{{Argument to free() is the address of the local variable 'a', which is not memory allocated by malloc()}}
+  // expected-warning@-2{{attempt to call free on non-heap object 'a'}}
+}
+
+void t2b () {
+  int a = 1;
+  std::free(&a);
+  // expected-warning@-1{{Argument to free() is the address of the local variable 'a', which is not memory allocated by malloc()}}
+  // expected-warning@-2{{attempt to call std::free on non-heap object 'a'}}
+}
+
+void t3a () {
+  static int a[] = { 1 };
+  free(a);
+  // expected-warning@-1{{Argument to free() is the address of the static variable 'a', which is not memory allocated by malloc()}}
+  // expected-warning@-2{{attempt to call free on non-heap object 'a'}}
+}
+
+void t3b () {
+  static int a[] = { 1 };
+  std::free(a);
+  // expected-warning@-1{{Argument to free() is the address of the static variable 'a', which is not memory allocated by malloc()}}
+  // expected-warning@-2{{attempt to call std::free on non-heap object 'a'}}
+}
+
+void t4a (char *x) {
+  free(x); // no-warning
+}
+
+void t4b (char *x) {
+  std::free(x); // no-warning
+}
+
+void t5a () {
+  extern char *ptr();
+  free(ptr()); // no-warning
+}
+
+void t5b () {
+  extern char *ptr();
+  std::free(ptr()); // no-warning
+}
+
+void t6a () {
+  free((void*)1000);
+  // expected-warning@-1{{Argument to free() is a constant address (1000), which is not memory allocated by malloc()}}
+  // expected-warning@-2{{attempt to call free on non-heap object '(void *)1000'}}
+}
+
+void t6b () {
+  std::free((void*)1000);
+  // expected-warning@-1{{Argument to free() is a constant address (1000), which is not memory allocated by malloc()}}
+  // expected-warning@-2{{attempt to call std::free on non-heap object '(void *)1000'}}
+}
+
+void t7a (char **x) {
+  free(*x); // no-warning
+}
+
+void t7b (char **x) {
+  std::free(*x); // no-warning
+}
+
+void t8a (char **x) {
+  // ugh
+  free((*x)+8); // no-warning
+}
+
+void t8b (char **x) {
+  // ugh
+  std::free((*x)+8); // no-warning
+}
+
+void t9a () {
+label:
+  free(&&label);
+  // expected-warning@-1{{Argument to free() is the address of the label 'label', which is not memory allocated by malloc()}}
+  // expected-warning@-2{{attempt to call free on non-heap object 'label'}}
+}
+
+void t9b () {
+label:
+  std::free(&&label);
+  // expected-warning@-1{{Argument to free() is the address of the label 'label', which is not memory allocated by malloc()}}
+  // expected-warning@-2{{attempt to call std::free on non-heap object 'label'}}
+}
+
+void t1

[PATCH] D94640: adds more checks to -Wfree-nonheap-object

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



Comment at: clang/lib/Sema/SemaChecking.cpp:10267-10277
+  if (const auto *Field = dyn_cast(D)) {
 S.Diag(UnaryExpr->getBeginLoc(), diag::warn_free_nonheap_object)
 << CalleeName << Field;
+return;
+  }
+
+  if (const auto *Func = dyn_cast(D)) {

aaron.ballman wrote:
> I think this simplifies things a bit (even though it's doing an `isa<>` 
> followed by a `cast<>`).
Wow, that's much nicer, thanks! :D



Comment at: clang/lib/Sema/SemaChecking.cpp:10286-10289
 if (const auto *Var = dyn_cast(Lvalue->getDecl()))
   return CheckFreeArgumentsOnLvalue(S, CalleeName, UnaryExpr, Var);
+if (const auto *Var = dyn_cast(Lvalue->getDecl()))
+  return CheckFreeArgumentsOnLvalue(S, CalleeName, UnaryExpr, Var);

aaron.ballman wrote:
> 
This one required a bit more work than the previous one because there are two 
overloads for `CheckFreeArgumentsOnLvalue`.



Comment at: clang/lib/Sema/SemaChecking.cpp:10312
+const CastExpr *Cast) {
+  auto const kind = Cast->getCastKind();
+  switch (kind) {

aaron.ballman wrote:
> Please spell out the type (also, we don't typically use top-level `const` 
> qualification on local variables or parameters).
Heh, this was only named for debugging purposes. I've consolidated it into the 
switch statement ;-)



Comment at: clang/lib/Sema/SemaChecking.cpp:10314
+  switch (kind) {
+  case clang::CK_IntegralToPointer: // [[fallthrough]];
+  case clang::CK_FunctionToPointerDecay: {

aaron.ballman wrote:
> 
Done, but why? I quite like making it clear that fallthrough is intentional.



Comment at: clang/lib/Sema/SemaChecking.cpp:10337
+  // Prefer something that doesn't involve a cast to make things simpler.
+  {
+const Expr *Arg = E->getArg(0)->IgnoreParenCasts();

aaron.ballman wrote:
> The extra compound scope doesn't add too much, so I'd remove it.
I find it improves readability and groups what the comment above it (now inline 
with `{`) is talking about.



Comment at: clang/lib/Sema/SemaChecking.cpp:10351
+
+if (const auto *Block = dyn_cast(Arg)) {
+  Diag(Block->getBeginLoc(), diag::warn_free_nonheap_object)

aaron.ballman wrote:
> Any reason not to handle `LambdaExpr` at the same time?
None, I hadn't considered it. I'm not sure I see the relationship bet



Comment at: clang/test/Analysis/free.c:84
+  // expected-warning@-1{{Argument to free() is a block, which is not memory 
allocated by malloc()}}
+  // expected-warning@-2{{attempt to call free on non-heap object : block 
expression}}
 }

aaron.ballman wrote:
> The formatting for this diagnostic is somewhat unfortunate in that it has the 
> leading space before the `:`. I think that changing the diagnostic to use a 
> `%select` would be an improvement.
I'm having a *lot* of difficulty getting `%select` to work. Here's what I've 
tried, but the space in `%select{ %2` is being ignored :(

```
: Warning<"attempt to call %0 on non-heap object%select{ %2|: block 
expression}1">,
```


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D94640

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


[PATCH] D95534: clang-cl: Invent a /winsysroot concept

2021-02-08 Thread Alexandre Ganea via Phabricator via cfe-commits
aganea added a comment.

In D95534#2534510 , @smeenai wrote:

> Now if only Windows could case-correct their SDKs so we didn't need VFS 
> overlays and symlinks for the linker...

I opened a ticket 

 but it was closed shortly after. Microsoft could easily fix the `#includes` 
but the `#pragma comment(lib, ..)` would require an additionnal layer of 
OLDNAMES.lib aka `/ALTERNATENAME` directives when dealing with external 
libraries, since they already have the (old) `#pragma comment(lib, ..)` 
directives already stamped in. Even after making these changes manually for a 
PoC, we still needed `clang-cl ... -Xclang -fixit -Wnonportable-include-path 
-Wnonportable-system-include-path` to fix some paths in third-party libraries - 
and discovered along the way that `-fixit` didn't work with PCH files in this 
specific case. All just a massive pain.

We ended up mounting a 'casefold' filesystem and now it cross-compiles like a 
charm! :-) (and incidentally it is a bit faster to build than on Windows, on 
the same hardware)


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D95534

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


[PATCH] D88833: [clang-tidy] Do not warn on pointer decays in system macros

2021-02-08 Thread Aryan Sefidi via Phabricator via cfe-commits
arysef added a comment.
Herald added a subscriber: nullptr.cpp.

Here are also some bugs that seem like they could be closed once this is 
merged: 
https://bugs.llvm.org/show_bug.cgi?id=28480
https://bugs.llvm.org/show_bug.cgi?id=32239

Also about the current behavior, it seems like this behavior happens even when 
it's a system header macro that is called directly (for example any time you 
use `assert`) rather than being one that is passed as a parameter. In those 
cases, the behavior seems undesired.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D88833

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


[PATCH] D95007: [CUDA][HIP] Add -fuse-cuid

2021-02-08 Thread Artem Belevich via Phabricator via cfe-commits
tra accepted this revision.
tra added a comment.
This revision is now accepted and ready to land.

Few test nits. LGTM in principle.




Comment at: clang/test/Driver/hip-cuid.hip:98
+
+// RUN: rm -rf %t.out
+

Is it necessary? The next 'RUN' command would overwrite the temp file anyways.
Also, you don't have to call all temporary files `%t.out`.  You could use 
`%t-1.out`, etc and leave the cleanup to the test driver.



Comment at: clang/test/Driver/hip-cuid.hip:100-102
+// RUN: %clang -### -x hip -target x86_64-unknown-linux-gnu \
+// RUN:   --offload-arch=gfx906 -c -nogpulib -fuse-cuid=hash \
+// RUN:   %S/Inputs/hip_multiple_inputs/a.cu >%t.out 2>&1

Putting `RUN` down in the test file makes them easy to miss. Maybe these should 
be in their own `hip-cuid-rdc.hip` test structured in a conventional way -- RUN 
lines first, followed by checks.


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

https://reviews.llvm.org/D95007

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


[PATCH] D96246: Make sure a module file with errors produced via '-fallow-pcm-with-compiler-errors' can be loaded when using implicit modules

2021-02-08 Thread Ben Barham via Phabricator via cfe-commits
bnbarham accepted this revision.
bnbarham added a comment.
This revision is now accepted and ready to land.

LGTM


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D96246

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


[PATCH] D96105: [CUDA][HIP] Pass -fgpu-rdc to host clang -cc1

2021-02-08 Thread Artem Belevich via Phabricator via cfe-commits
tra accepted this revision.
tra added inline comments.
This revision is now accepted and ready to land.



Comment at: clang/test/Driver/hip-rdc-device-only.hip:50-61
 // COMMON: [[CLANG:".*clang.*"]] "-cc1" "-mllvm" 
"--amdhsa-code-object-version={{[0-9]+}}" "-triple" "amdgcn-amd-amdhsa"
 // COMMON-SAME: "-aux-triple" "x86_64-unknown-linux-gnu"
 // EMITBC-SAME: "-emit-llvm-bc"
 // EMITLL-SAME: "-emit-llvm"
 // COMMON-SAME: {{.*}} "-main-file-name" "a.cu"
-// COMMON-SAME: "-fcuda-is-device" "-fgpu-rdc" 
"-fcuda-allow-variadic-functions" "-fvisibility" "hidden"
+// COMMON-SAME: "-fcuda-is-device" "-fcuda-allow-variadic-functions" 
"-fvisibility" "hidden"
 // COMMON-SAME: "-fapply-global-visibility-to-externs"

At some point we should probably convert `-SAME` to `-DAG` so we don't have to 
shuffle the options around every time they change order.


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

https://reviews.llvm.org/D96105

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


[PATCH] D86376: [HIP] Emit kernel symbol

2021-02-08 Thread Yaxun Liu via Phabricator via cfe-commits
yaxunl updated this revision to Diff 322213.
yaxunl retitled this revision from "[HIP] Simplify kernel launching" to "[HIP] 
Emit kernel symbol".
yaxunl edited the summary of this revision.
yaxunl added a comment.

Revised by Artem's comments.


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

https://reviews.llvm.org/D86376

Files:
  clang/lib/CodeGen/CGCUDANV.cpp
  clang/test/CodeGenCUDA/Inputs/cuda.h
  clang/test/CodeGenCUDA/cxx-call-kernel.cpp
  clang/test/CodeGenCUDA/kernel-dbg-info.cu
  clang/test/CodeGenCUDA/kernel-stub-name.cu
  clang/test/CodeGenCUDA/unnamed-types.cu

Index: clang/test/CodeGenCUDA/unnamed-types.cu
===
--- clang/test/CodeGenCUDA/unnamed-types.cu
+++ clang/test/CodeGenCUDA/unnamed-types.cu
@@ -54,7 +54,7 @@
   [] __device__ (float x) { return x + 5.f; });
 }
 // HOST: @__hip_register_globals
-// HOST: __hipRegisterFunction{{.*}}@_Z17__device_stub__k0IZZ2f1PfENKUlS0_E_clES0_EUlfE_EvS0_T_{{.*}}@0
-// HOST: __hipRegisterFunction{{.*}}@_Z17__device_stub__k1IZ2f1PfEUlfE_Z2f1S0_EUlffE_Z2f1S0_EUlfE0_EvS0_T_T0_T1_{{.*}}@1
+// HOST: __hipRegisterFunction{{.*}}@_Z2k0IZZ2f1PfENKUlS0_E_clES0_EUlfE_EvS0_T_{{.*}}@0
+// HOST: __hipRegisterFunction{{.*}}@_Z2k1IZ2f1PfEUlfE_Z2f1S0_EUlffE_Z2f1S0_EUlfE0_EvS0_T_T0_T1_{{.*}}@1
 // MSVC: __hipRegisterFunction{{.*}}@"??$k0@V@?0???R1?0??f1@@YAXPEAM@Z@QEBA@0@Z@@@YAXPEAMV@?0???R0?0??f1@@YAX0@Z@QEBA@0@Z@@Z{{.*}}@0
 // MSVC: __hipRegisterFunction{{.*}}@"??$k1@V@?0??f1@@YAXPEAM@Z@V@?0??2@YAX0@Z@V@?0??2@YAX0@Z@@@YAXPEAMV@?0??f1@@YAX0@Z@V@?0??1@YAX0@Z@V@?0??1@YAX0@Z@@Z{{.*}}@1
Index: clang/test/CodeGenCUDA/kernel-stub-name.cu
===
--- clang/test/CodeGenCUDA/kernel-stub-name.cu
+++ clang/test/CodeGenCUDA/kernel-stub-name.cu
@@ -6,6 +6,12 @@
 
 #include "Inputs/cuda.h"
 
+// Kernel handles
+
+// CHECK: @[[HCKERN:ckernel]] = constant i8* null
+// CHECK: @[[HNSKERN:_ZN2ns8nskernelEv]] = constant i8* null
+// CHECK: @[[HTKERN:_Z10kernelfuncIiEvv]] = linkonce_odr constant i8* null
+
 extern "C" __global__ void ckernel() {}
 
 namespace ns {
@@ -26,9 +32,9 @@
 // Non-template kernel stub functions
 
 // CHECK: define{{.*}}@[[CSTUB:__device_stub__ckernel]]
-// CHECK: call{{.*}}@hipLaunchByPtr{{.*}}@[[CSTUB]]
+// CHECK: call{{.*}}@hipLaunchByPtr{{.*}}@[[HCKERN]]
 // CHECK: define{{.*}}@[[NSSTUB:_ZN2ns23__device_stub__nskernelEv]]
-// CHECK: call{{.*}}@hipLaunchByPtr{{.*}}@[[NSSTUB]]
+// CHECK: call{{.*}}@hipLaunchByPtr{{.*}}@[[HNSKERN]]
 
 // CHECK-LABEL: define{{.*}}@_Z8hostfuncv()
 // CHECK: call void @[[CSTUB]]()
@@ -45,11 +51,11 @@
 // Template kernel stub functions
 
 // CHECK: define{{.*}}@[[TSTUB]]
-// CHECK: call{{.*}}@hipLaunchByPtr{{.*}}@[[TSTUB]]
+// CHECK: call{{.*}}@hipLaunchByPtr{{.*}}@[[HTKERN]]
 
 // CHECK: declare{{.*}}@[[DSTUB]]
 
 // CHECK-LABEL: define{{.*}}@__hip_register_globals
-// CHECK: call{{.*}}@__hipRegisterFunction{{.*}}@[[CSTUB]]{{.*}}@[[CKERN]]
-// CHECK: call{{.*}}@__hipRegisterFunction{{.*}}@[[NSSTUB]]{{.*}}@[[NSKERN]]
-// CHECK: call{{.*}}@__hipRegisterFunction{{.*}}@[[TSTUB]]{{.*}}@[[TKERN]]
+// CHECK: call{{.*}}@__hipRegisterFunction{{.*}}@[[HCKERN]]{{.*}}@[[CKERN]]
+// CHECK: call{{.*}}@__hipRegisterFunction{{.*}}@[[HNSKERN]]{{.*}}@[[NSKERN]]
+// CHECK: call{{.*}}@__hipRegisterFunction{{.*}}@[[HTKERN]]{{.*}}@[[TKERN]]
Index: clang/test/CodeGenCUDA/kernel-dbg-info.cu
===
--- clang/test/CodeGenCUDA/kernel-dbg-info.cu
+++ clang/test/CodeGenCUDA/kernel-dbg-info.cu
@@ -30,6 +30,9 @@
   *a = 1;
 }
 
+// Kernel symbol for launching kernel.
+// CHECK: @[[SYM:ckernel]] = constant i8* null
+
 // Device side kernel names
 // CHECK: @[[CKERN:[0-9]*]] = {{.*}} c"ckernel\00"
 
@@ -40,7 +43,7 @@
 // Make sure there is no !dbg between function attributes and '{'
 // CHECK: define{{.*}} void @[[CSTUB:__device_stub__ckernel]]{{.*}} #{{[0-9]+}} {
 // CHECK-NOT: call {{.*}}@hipLaunchByPtr{{.*}}!dbg
-// CHECK: call {{.*}}@hipLaunchByPtr{{.*}}@[[CSTUB]]
+// CHECK: call {{.*}}@hipLaunchByPtr{{.*}}@[[SYM]]
 // CHECK-NOT: ret {{.*}}!dbg
 
 // CHECK-LABEL: define {{.*}}@_Z8hostfuncPi{{.*}}!dbg
Index: clang/test/CodeGenCUDA/cxx-call-kernel.cpp
===
--- /dev/null
+++ clang/test/CodeGenCUDA/cxx-call-kernel.cpp
@@ -0,0 +1,19 @@
+// RUN: %clang_cc1 -x hip -emit-llvm-bc %s -o %t.hip.bc
+// RUN: %clang_cc1 -mlink-bitcode-file %t.hip.bc -DHIP_PLATFORM -emit-llvm \
+// RUN:   %s -o - | FileCheck %s
+
+#include "Inputs/cuda.h"
+
+// CHECK: @_Z2g1i = constant i8* null
+#if __HIP__
+__global__ void g1(int x) {}
+#else
+extern void g1(int x);
+
+// CHECK: call i32 @hipLaunchKernel{{.*}}@_Z2g1i
+void test() {
+  hipLaunchKernel((void*)g1, 1, 1, nullptr, 0, 0);
+}
+
+// CHECK: __hipRegisterFunction{{.*}}@_Z2g1i
+#endif
Index: clang/test/CodeGenCUDA/Inputs/cuda.h
=

[clang] 87dbdd2 - [FileCheck] Default --allow-unused-prefixes to false

2021-02-08 Thread Fangrui Song via cfe-commits

Author: Fangrui Song
Date: 2021-02-08T13:37:04-08:00
New Revision: 87dbdd2e3bb63b681f8cc3179ef5c2d5929bbf61

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

LOG: [FileCheck] Default --allow-unused-prefixes to false

Link: https://lists.llvm.org/pipermail/llvm-dev/2020-October/146162.html "[RFC] 
FileCheck: (dis)allowing unused prefixes"

If a downstream project using lit needs time for transition,
add the following to `lit.local.cfg`:

```
from lit.llvm.subst import ToolSubst

fc = ToolSubst('FileCheck', unresolved='fatal')
config.substitutions.insert(0, (fc.regex, 'FileCheck --allow-unused-prefixes'))
```

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

Added: 


Modified: 
clang/test/Driver/crash-report-null.test
clang/test/OpenMP/lit.local.cfg
clang/test/lit.cfg.py
llvm/test/FileCheck/allow-unused-prefixes.txt
llvm/test/FileCheck/lit.local.cfg
llvm/test/Other/opt-bisect-legacy-pass-manager.ll
llvm/test/Transforms/Attributor/lit.local.cfg
llvm/test/lit.cfg.py
llvm/utils/FileCheck/FileCheck.cpp

Removed: 
llvm/test/Reduce/lit.local.cfg



diff  --git a/clang/test/Driver/crash-report-null.test 
b/clang/test/Driver/crash-report-null.test
index 05309bf63f27..c5e3b3b0fc9c 100644
--- a/clang/test/Driver/crash-report-null.test
+++ b/clang/test/Driver/crash-report-null.test
@@ -1,7 +1,7 @@
 // RUN: env FORCE_CLANG_DIAGNOSTICS_CRASH=1 not %clang -fsyntax-only -x c 
/dev/null -lstdc++ 2>&1 | FileCheck %s
 
 // FIXME: Investigating. "fatal error: file 'nul' modified since it was first 
processed"
-// XFAIL: windows-gnu
+// UNSUPPORTED: system-windows
 
 // CHECK: PLEASE submit a bug report to {{.*}} and include the crash 
backtrace, preprocessed source, and associated run script.
 // CHECK: Preprocessed source(s) and associated run script(s) are located at:

diff  --git a/clang/test/OpenMP/lit.local.cfg b/clang/test/OpenMP/lit.local.cfg
index ac72c2de9777..c114693dd7ed 100644
--- a/clang/test/OpenMP/lit.local.cfg
+++ b/clang/test/OpenMP/lit.local.cfg
@@ -2,9 +2,4 @@
 from lit.llvm.subst import ToolSubst
 
 fc = ToolSubst('FileCheck', unresolved='fatal')
-# the parent introduced the opposite rule, so we replace it if we see it.
-if len(config.substitutions) > 0 and config.substitutions[0] == (fc.regex, 
'FileCheck --allow-unused-prefixes=false'):
-config.substitutions[0] = (
-fc.regex, 'FileCheck --allow-unused-prefixes=true')
-else:
-config.substitutions.insert(0, (fc.regex, 'FileCheck 
--allow-unused-prefixes=true'))
+config.substitutions.insert(0, (fc.regex, 'FileCheck --allow-unused-prefixes'))

diff  --git a/clang/test/lit.cfg.py b/clang/test/lit.cfg.py
index a47ebe74ddba..863ab444fb02 100644
--- a/clang/test/lit.cfg.py
+++ b/clang/test/lit.cfg.py
@@ -43,14 +43,6 @@
 
 llvm_config.use_clang()
 
-# FIXME: remove this when we flip the default value for --allow-unused-prefixes
-# to false.
-fc = ToolSubst('FileCheck', unresolved='fatal')
-# Insert this first. Then, we'll first update the blank FileCheck command; 
then,
-# the default substitution of FileCheck will replace it to its full path.
-config.substitutions.insert(0, (fc.regex,
-'FileCheck --allow-unused-prefixes=false'))
-
 config.substitutions.append(
 ('%src_include_dir', config.clang_src_dir + '/include'))
 

diff  --git a/llvm/test/FileCheck/allow-unused-prefixes.txt 
b/llvm/test/FileCheck/allow-unused-prefixes.txt
index 6903b0452882..6b15dc29273b 100644
--- a/llvm/test/FileCheck/allow-unused-prefixes.txt
+++ b/llvm/test/FileCheck/allow-unused-prefixes.txt
@@ -2,10 +2,7 @@
 ; RUN: %ProtectFileCheckOutput not FileCheck --allow-unused-prefixes=false 
--check-prefixes=P1,P2,P3 --input-file %S/Inputs/one-check.txt 
%S/Inputs/one-check.txt 2>&1 | FileCheck --check-prefix=MISSING-MORE %s
 ; RUN: FileCheck --allow-unused-prefixes=true  --check-prefixes=P1,P2 
--input-file %S/Inputs/one-check.txt %S/Inputs/one-check.txt 
 ; RUN: FileCheck --allow-unused-prefixes=false --allow-unused-prefixes=true 
--check-prefixes=P1,P2 --input-file %S/Inputs/one-check.txt 
%S/Inputs/one-check.txt
-
-;; Note: the default will be changed to 'false', at which time this run line
-;; should be changed accordingly.
-; RUN: FileCheck --check-prefixes=P1,P2 --input-file %S/Inputs/one-check.txt 
%S/Inputs/one-check.txt 
+; RUN: not FileCheck --check-prefixes=P1,P2 --input-file 
%S/Inputs/one-check.txt %S/Inputs/one-check.txt
 
 ; MISSING-ONE: error: no check strings found with prefix 'P2:' 
 ; MISSING-MORE: error: no check strings found with prefixes 'P2:', 'P3:'

diff  --git a/llvm/test/FileCheck/lit.local.cfg 
b/llvm/test/FileCheck/lit.local.cfg
index 74e4d89e416b..9164f683fc1b 100644
--- a/llvm/test/FileCheck/lit.local.cfg
+++ b/llvm/test/FileCheck/lit.local.cfg
@@ -54,12 +54,3 @@ config.t

[PATCH] D95849: [FileCheck] Default --allow-unused-prefixes to false

2021-02-08 Thread Fangrui 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 rG87dbdd2e3bb6: [FileCheck] Default --allow-unused-prefixes to 
false (authored by MaskRay).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D95849

Files:
  clang/test/Driver/crash-report-null.test
  clang/test/OpenMP/lit.local.cfg
  clang/test/lit.cfg.py
  llvm/test/FileCheck/allow-unused-prefixes.txt
  llvm/test/FileCheck/lit.local.cfg
  llvm/test/Other/opt-bisect-legacy-pass-manager.ll
  llvm/test/Reduce/lit.local.cfg
  llvm/test/Transforms/Attributor/lit.local.cfg
  llvm/test/lit.cfg.py
  llvm/utils/FileCheck/FileCheck.cpp

Index: llvm/utils/FileCheck/FileCheck.cpp
===
--- llvm/utils/FileCheck/FileCheck.cpp
+++ llvm/utils/FileCheck/FileCheck.cpp
@@ -78,7 +78,7 @@
  "checks that some error message does not occur, for example."));
 
 static cl::opt AllowUnusedPrefixes(
-"allow-unused-prefixes", cl::init(true), cl::ZeroOrMore,
+"allow-unused-prefixes", cl::init(false), cl::ZeroOrMore,
 cl::desc("Allow prefixes to be specified but not appear in the test."));
 
 static cl::opt MatchFullLines(
Index: llvm/test/lit.cfg.py
===
--- llvm/test/lit.cfg.py
+++ llvm/test/lit.cfg.py
@@ -83,20 +83,6 @@
 return found_dylibs[0]
 
 
-
-# FIXME: remove this when we flip the default value for --allow-unused-prefixes
-# to false.
-fc = ToolSubst('FileCheck', unresolved='fatal')
-# Insert this first. Then, we'll first update the blank FileCheck command; then,
-# the default substitution of FileCheck will replace it to its full path.
-config.substitutions.insert(0, (fc.regex,
-'FileCheck --allow-unused-prefixes=false'))
-# When addressing this fixme, replace %FileCheckRaw% with just FileCheck.
-config.substitutions.append(('%FileCheckRaw%', 'FileCheck'))
-# Also remove the lit.local.cfg under llvm/test/Reduce
-# and the pertinent FIXME in llvm/test/FileCheck
-
-
 llvm_config.use_default_substitutions()
 
 # Add site-specific substitutions.
@@ -162,8 +148,8 @@
 # FIXME: Why do we have both `lli` and `%lli` that do slightly different things?
 tools.extend([
 'dsymutil', 'lli', 'lli-child-target', 'llvm-ar', 'llvm-as',
-'llvm-addr2line', 'llvm-bcanalyzer', 'llvm-bitcode-strip', 'llvm-config', 
-'llvm-cov', 'llvm-cxxdump', 'llvm-cvtres', 'llvm-diff', 'llvm-dis', 
+'llvm-addr2line', 'llvm-bcanalyzer', 'llvm-bitcode-strip', 'llvm-config',
+'llvm-cov', 'llvm-cxxdump', 'llvm-cvtres', 'llvm-diff', 'llvm-dis',
 'llvm-dwarfdump', 'llvm-dlltool', 'llvm-exegesis', 'llvm-extract',
 'llvm-isel-fuzzer', 'llvm-ifs',
 'llvm-install-name-tool', 'llvm-jitlink', 'llvm-opt-fuzzer', 'llvm-lib',
Index: llvm/test/Transforms/Attributor/lit.local.cfg
===
--- llvm/test/Transforms/Attributor/lit.local.cfg
+++ llvm/test/Transforms/Attributor/lit.local.cfg
@@ -2,10 +2,4 @@
 from lit.llvm.subst import ToolSubst
 
 fc = ToolSubst('FileCheck', unresolved='fatal')
-# the parent introduced the opposite rule, so we replace it if we see it.
-if len(config.substitutions) > 0 and config.substitutions[0] == (fc.regex, 'FileCheck --allow-unused-prefixes=false'):
-config.substitutions[0] = (
-fc.regex, 'FileCheck --allow-unused-prefixes=true')
-else:
-config.substitutions.insert(0, (fc.regex, 
-'FileCheck --allow-unused-prefixes=true'))
+config.substitutions.insert(0, (fc.regex, 'FileCheck --allow-unused-prefixes'))
Index: llvm/test/Reduce/lit.local.cfg
===
--- llvm/test/Reduce/lit.local.cfg
+++ /dev/null
@@ -1,8 +0,0 @@
-# -*- Python -*- vim: set ft=python ts=4 sw=4 expandtab tw=79:
-# FIXME: remove this file when we flip the default for --allow-unused-prefixes.
-from lit.llvm.subst import ToolSubst
-
-fc = ToolSubst('FileCheck', unresolved='fatal')
-# the parent introduced the opposite rule, so we replace it if we see it.
-if len(config.substitutions) > 0 and config.substitutions[0] == (fc.regex, 'FileCheck --allow-unused-prefixes=false'):
-del config.substitutions[0]
Index: llvm/test/Other/opt-bisect-legacy-pass-manager.ll
===
--- llvm/test/Other/opt-bisect-legacy-pass-manager.ll
+++ llvm/test/Other/opt-bisect-legacy-pass-manager.ll
@@ -39,7 +39,7 @@
 ; f2() in f3().
 
 ; RUN: %python %S/opt-bisect-helper.py --start=0 --end=256 --optcmd=opt \
-; RUN: --filecheckcmd=%FileCheckRaw% --test=%s \
+; RUN: --filecheckcmd=FileCheck --test=%s \
 ; RUN: --prefix=CHECK-BISECT-INLINE-HELPER \

[PATCH] D75903: [AArch64][CodeGen] Fixing stack alignment of HFA arguments on AArch64 PCS

2021-02-08 Thread Reid Kleckner via Phabricator via cfe-commits
rnk added inline comments.



Comment at: llvm/docs/LangRef.rst:1220
+``alignstack()``
+This indicates the alignment that should be considered by the backend when
+assigning this parameter to a stack slot during calling convention

chill wrote:
> rnk wrote:
> > This seems like you are introducing a new meaning to `alignstack`, which 
> > according to the comments, only affects function SP alignment, not 
> > parameter alignment.
> > 
> > I'm assuming the reason you can't use the regular `align` attribute is that 
> > it is overloaded to mean two things: the alignment of the pointer when 
> > applied to a pointer, and the alignment of the argument memory when that 
> > pointer argument is marked `byval`. If you want to resolve this ambiguity, 
> > it seems like something that should be discussed on llvm-dev with a wider 
> > audience.
> Sorry, I couldn't quite get it, do you suggest we should be using the `align` 
> attribute instead of `alignstack`, if there  are no
> (major) objections on the llvm-dev list?
> 
> It certainly makes sense to me to use `align` as it already pertains to 
> individual argument alignment (even though it's for pointers only now).
> 
Mostly I think I meant that this will be a big change in the meaning of either 
the `align` or the `alignstack` attributes, and that should be hashed out on 
llvm-dev.

Right now `align` is kind of a hybrid between an optimization annotation 
attribute, like `dereferenceable` or `nonnull`, and an ABI attribute, like 
`byval` or `inreg`. When `align` is used with `byval`, it affects argument 
memory layout. When `byval` is not present, it is just an optimizer hint. IMO, 
ideally, we should separate those two roles.

I should be able to control the alignment of the memory used to pass a pointer 
argument, at the same time that I annotate which low bits of the pointer are 
known to be zero.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D75903

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


[PATCH] D96049: [Timer] On macOS count number of executed instructions

2021-02-08 Thread Jonas Devlieghere via Phabricator via cfe-commits
JDevlieghere accepted this revision.
JDevlieghere added a comment.
This revision is now accepted and ready to land.

Seems useful! LGTM.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D96049

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


[PATCH] D96248: [OpenMP][AMDGPU] Add support for linking libomptarget bitcode

2021-02-08 Thread Jon Chesterfield via Phabricator via cfe-commits
JonChesterfield added inline comments.



Comment at: clang/lib/Driver/ToolChains/AMDGPUOpenMP.cpp:193
   CC1Args.push_back("-emit-llvm-bc");
+
+  std::string BitcodeSuffix = "amdgcn-" + GpuArch.str();

Need `if (DriverArgs.hasArg(options::OPT_nogpulib)) return;` here or we can't 
build the deviceRTL without already having one on disk


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D96248

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


[PATCH] D92808: [ObjC][ARC] Use operand bundle 'clang.arc.rv' instead of explicitly emitting retainRV or claimRV calls in the IR

2021-02-08 Thread Akira Hatanaka via Phabricator via cfe-commits
ahatanak added a comment.

I do have a plan to modify the auto upgrader to use the bundles when it's 
possible to do so, but I'm currently not considering landing the changes I 
reverted since they were only needed to avoid duplicating constant strings. I 
don't think we can avoid duplicating the string unless 
`objcarc::getRVMarkerModuleFlagStr()` can be moved to a file in 
`llvm/include/llvm/IR`.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D92808

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


[PATCH] D96286: [clangd] Change TidyProvider cache to use a linked list approach

2021-02-08 Thread Nathan James via Phabricator via cfe-commits
njames93 added a comment.

A similar approach could be used for the config provider, however It may not 
make as much sense there. The directories are traversed in the opposite order 
and we will always attempt to read from each directory.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D96286

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


[PATCH] D96286: [clangd] Change TidyProvider cache to use a linked list approach

2021-02-08 Thread Nathan James via Phabricator via cfe-commits
njames93 created this revision.
njames93 added a reviewer: sammccall.
Herald added subscribers: usaxena95, kadircet, arphaman.
njames93 requested review of this revision.
Herald added subscribers: cfe-commits, MaskRay, ilya-biryukov.
Herald added a project: clang.

I know linked lists are the work of the devil, but it makes sense here.

Change the map in the DotClangTidyTree to store the FileCache as well as a link 
to its parent FileCache.
By storing a pointer to each items parent in the map, we no longer need to 
traverse the entire directory tree and populating a vector for each item.
Instead we just grab the tail from the map and (in all but the first run) it 
will contain links to the whole directory structure we need for querying.
This can save a lot of redundant work if the config file was in the tail 
directory but there was 15 parent directories above it.

This change should be NFC.

Depends on D96204  - Mainly for the test cases 
added, to ensure this isn't breakign behaviour.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D96286

Files:
  clang-tools-extra/clangd/TidyProvider.cpp

Index: clang-tools-extra/clangd/TidyProvider.cpp
===
--- clang-tools-extra/clangd/TidyProvider.cpp
+++ clang-tools-extra/clangd/TidyProvider.cpp
@@ -76,12 +76,24 @@
   }
 };
 
+llvm::SmallString<256> pathAppend(PathRef Path, llvm::StringRef Tail) {
+  llvm::SmallString<256> ConfigPath(Path);
+  llvm::sys::path::append(ConfigPath, Tail);
+  return ConfigPath;
+}
+
 // Access to combined config from .clang-tidy files governing a source file.
 // Each config file is cached and the caches are shared for affected sources.
 //
 // FIXME: largely duplicates config::Provider::fromAncestorRelativeYAMLFiles.
 // Potentially useful for compile_commands.json too. Extract?
 class DotClangTidyTree {
+  struct DirectoryNode {
+DirectoryNode(PathRef File) : Cache(File), Parent(nullptr) {}
+DotClangTidyCache Cache;
+DirectoryNode *Parent;
+  };
+
   const ThreadsafeFS &FS;
   std::string RelPath;
   std::chrono::steady_clock::duration MaxStaleness;
@@ -90,56 +102,92 @@
   // Keys are the ancestor directory, not the actual config path within it.
   // We only insert into this map, so pointers to values are stable forever.
   // Mutex guards the map itself, not the values (which are threadsafe).
-  mutable llvm::StringMap Cache;
-
-public:
-  DotClangTidyTree(const ThreadsafeFS &FS)
-  : FS(FS), RelPath(".clang-tidy"), MaxStaleness(std::chrono::seconds(5)) {}
-
-  void apply(tidy::ClangTidyOptions &Result, PathRef AbsPath) {
+  // We store values as linked lists pointing to their parent directories nodes,
+  // this saves quering the map for each component of a path.
+  mutable llvm::StringMap Cache;
+
+  /// Ensures there is a FileCache for each .clang-tidy file in the directory
+  /// tree up to \p AbsPath and returns a linked list structure pointing to the
+  /// first item.
+  /// \pre \p AbsPath is an absolute path to a file.
+  DirectoryNode *getNode(PathRef AbsPath) {
 namespace path = llvm::sys::path;
 assert(path::is_absolute(AbsPath));
 
 // Compute absolute paths to all ancestors (substrings of P.Path).
 // Ensure cache entries for each ancestor exist in the map.
+
+// AbsPath should be pointing to a file, get the directory.
 llvm::StringRef Parent = path::parent_path(AbsPath);
-llvm::SmallVector Caches;
-{
-  std::lock_guard Lock(Mu);
-  for (auto I = path::rbegin(Parent), E = path::rend(Parent); I != E; ++I) {
-assert(I->end() >= Parent.begin() && I->end() <= Parent.end() &&
-   "Canonical path components should be substrings");
-llvm::StringRef Ancestor(Parent.begin(), I->end() - Parent.begin());
+auto I = path::rbegin(Parent), E = path::rend(Parent);
+assert(I != E && "There should be at least 1 path component to traverse");
+llvm::StringRef Ancestor(Parent.begin(), I->end() - Parent.begin());
+
+std::lock_guard Lock(Mu);
+
+auto It = Cache.find(Ancestor);
+// This is the hot path. After invoking this method on a given path once,
+// The path will stay in the map for the life of this object, saving any
+// further lookup.
+if (LLVM_LIKELY(It != Cache.end()))
+  return &It->getValue();
+
+// Build the FileCache for this item and store a pointer to its parent node,
+// this will be filled in when we process the next component in the path.
+DirectoryNode *Result =
+&Cache.try_emplace(Ancestor, pathAppend(Ancestor, RelPath).str())
+ .first->getValue();
+DirectoryNode **ParentPtr = &Result->Parent;
+
+// Skip the first item as we have already processed it.
+++I;
+for (; I != E; ++I) {
+  assert(I->end() >= Parent.begin() && I->end() <= Parent.end() &&
+ "Canonical path components should be substrings");
+  llvm::StringRef Anc

[PATCH] D69560: [clang-tidy] Add 'bugprone-easily-swappable-parameters' check

2021-02-08 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman added inline comments.



Comment at: 
clang-tools-extra/clang-tidy/bugprone/EasilySwappableParametersCheck.cpp:177
+   const std::size_t StartIndex) {
+  const std::size_t NumParams = FD->getNumParams();
+  assert(StartIndex < NumParams && "out of bounds for start");

whisperity wrote:
> whisperity wrote:
> > aaron.ballman wrote:
> > > whisperity wrote:
> > > > aaron.ballman wrote:
> > > > > Some interesting test cases to consider: varargs functions and K&R C 
> > > > > functions
> > > > > K&R C functions
> > > > 
> > > > Call me too young, but I had to look up what a "K&R C function" is, and 
> > > > I am absolutely baffled how this unholy construct is still supported! 
> > > > **But:** thanks to Clang supporting it properly in the AST, the checker 
> > > > works out of the box!
> > > > 
> > > > Given
> > > > 
> > > > ```
> > > > int foo(a, b)
> > > >   int a;
> > > >   int b;
> > > > {
> > > >   return a + b;
> > > > }
> > > > ```
> > > > 
> > > > We get the following output:
> > > > 
> > > > ```
> > > > /tmp/knr.c:2:3: warning: 2 adjacent parameters of 'foo' of similar type 
> > > > ('int') are easily swapped by mistake 
> > > > [bugprone-easily-swappable-parameters]
> > > >   int a;
> > > >   ^
> > > > /tmp/knr.c:2:7: note: the first parameter in the range is 'a'
> > > >   int a;
> > > >   ^
> > > > /tmp/knr.c:3:7: note: the last parameter in the range is 'b'
> > > >   int b;
> > > >   ^
> > > > ```
> > > > 
> > > > (even the locations are consistent!)
> > > > 
> > > > Should I add a test case for this? We could use a specifically C test 
> > > > case either way eventually...
> > > > 
> > > > -
> > > > 
> > > > > varargs functions
> > > > 
> > > > This is a bit of terminology, but something tells me you meant the 
> > > > //variadic function// here, right? As opposed to type parameter packs.
> > > > 
> > > > Given
> > > > 
> > > > ```
> > > > int sum(int ints...) {
> > > >   return 0;
> > > > }
> > > > ```
> > > > 
> > > > the AST looks something like this:
> > > > 
> > > > ```
> > > > `-FunctionDecl 0x56372e29e258  line:1:5 sum 
> > > > 'int (int, ...)'
> > > >   |-ParmVarDecl 0x56372e29e188  col:13 ints 'int'
> > > > ```
> > > > 
> > > > Should we diagnose this? And if so, how? The variadic part is not 
> > > > represented (at least not at first glance?) in the AST. Understanding 
> > > > the insides of such a function would require either overapproximatic 
> > > > stuff and doing a looot of extra handling, or becoming flow 
> > > > sensitive... and we'd still need to understand all the `va_` standard 
> > > > functions' semantics either way.
> > > > Call me too young, but I had to look up what a "K&R C function" is, and 
> > > > I am absolutely baffled how this unholy construct is still supported!
> > > 
> > > Ah, to be innocent again, how I miss those days. :-D
> > > 
> > > > Should I add a test case for this? We could use a specifically C test 
> > > > case either way eventually...
> > > 
> > > I think it'd be a useful case, but the one I was specifically more 
> > > concerned with is:
> > > ```
> > > // N.B.: this is C-specific and does not apply to C++.
> > > void f();
> > > 
> > > int main(void) {
> > >   f(1, 2, 3.4, "this is why we can't have nice things");
> > > }
> > > ```
> > > where the function has no prototype and so is treated as a varargs call.
> > > 
> > > > This is a bit of terminology, but something tells me you meant the 
> > > > variadic function here, right? As opposed to type parameter packs.
> > > 
> > > Yes, sorry for being unclear, I am talking about variadic functions.
> > > 
> > > > Should we diagnose this? And if so, how? The variadic part is not 
> > > > represented (at least not at first glance?) in the AST. Understanding 
> > > > the insides of such a function would require either overapproximatic 
> > > > stuff and doing a looot of extra handling, or becoming flow 
> > > > sensitive... and we'd still need to understand all the va_ standard 
> > > > functions' semantics either way.
> > > 
> > > Well, that's what I'm wondering, really. The arguments are certainly easy 
> > > to swap because the type system can't help the user to identify swaps 
> > > without further information (like format specifier strings). However, the 
> > > checking code would be... highly unpleasant, I suspect. My intuition is 
> > > to say that we don't support functions without prototypes at all (we just 
> > > silently ignore them) and that we only check the typed parameters in a 
> > > variadic function declaration (e.g., we'll diagnose `void foo(int i, int 
> > > j, ...);` because of the sequential `int` parameters, but we won't 
> > > diagnose `void foo(int i, ...);` even if call sites look like `foo(1, 
> > > 2);`). WDYT?
> > It is definitely highly unpleasant, at one point I remember just glancing 
> > into the logic behind `printf()` related warnings in Sema and it was... 
> > odd, to say the l

[PATCH] D95204: [lld-macho] Switch default to new Darwin backend

2021-02-08 Thread Nico Weber via Phabricator via cfe-commits
thakis added inline comments.



Comment at: lld/tools/lld/lld.cpp:74
   .CasesLower("ld64", "ld64.lld", "darwin", Darwin)
-  .CasesLower("darwinnew", "ld64.lld.darwinnew", DarwinNew)
   .Default(Invalid);

very nit: You could keep darwinnew around for a bit too and make it mean the 
same thing as just ld64.lld. Then people could update to a new build, then do 
the (then) no-op change of replacing darwinnew with nothing. As is, updating 
toolchain and changing build files have to happen in the same change, which is 
always a bit annoying.

But since this was advertised as an unstable flag, it's not necessary, just 
kind of friendly. Up to you. (If you do this, consider reverting the change to 
the .gn file too.)


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D95204

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


[PATCH] D96285: [clang][Arm] Fix handling of -Wa,-implicit-it=

2021-02-08 Thread Nick Desaulniers via Phabricator via cfe-commits
nickdesaulniers created this revision.
nickdesaulniers added reviewers: DavidSpickett, ostannard.
Herald added a subscriber: danielkiss.
nickdesaulniers requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

Similiar to D95872 , this flag can be set for 
the assembler directly.
Move validation code into a reusable helper function.

Link: https://bugs.llvm.org/show_bug.cgi?id=49023
Link: https://github.com/ClangBuiltLinux/linux/issues/1270
Reported-by: Arnd Bergmann 
Signed-off-by: Nick Desaulniers 


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D96285

Files:
  clang/lib/Driver/ToolChains/Clang.cpp
  clang/test/Driver/arm-target-as-mimplicit-it.s


Index: clang/test/Driver/arm-target-as-mimplicit-it.s
===
--- /dev/null
+++ clang/test/Driver/arm-target-as-mimplicit-it.s
@@ -0,0 +1,33 @@
+/// Simple tests for valid input.
+/// -Wa,-implicit-it=
+// RUN: %clang -target arm-linux-gnueabi -### -Wa,-mimplicit-it=always %s 2>&1 
| FileCheck %s --check-prefix=ALWAYS
+// RUN: %clang -target arm-linux-gnueabi -### -Wa,-mimplicit-it=never %s 2>&1 
| FileCheck %s --check-prefix=NEVER
+// RUN: %clang -target arm-linux-gnueabi -### -Wa,-mimplicit-it=arm %s 2>&1 | 
FileCheck %s --check-prefix=ARM
+// RUN: %clang -target arm-linux-gnueabi -### -Wa,-mimplicit-it=thumb %s 2>&1 
| FileCheck %s --check-prefix=THUMB
+/// -Xassembler -mimplicit-it=
+// RUN: %clang -target arm-linux-gnueabi -### -Xassembler -mimplicit-it=always 
%s 2>&1 | FileCheck %s --check-prefix=ALWAYS
+// RUN: %clang -target arm-linux-gnueabi -### -Xassembler -mimplicit-it=never 
%s 2>&1 | FileCheck %s --check-prefix=NEVER
+// RUN: %clang -target arm-linux-gnueabi -### -Xassembler -mimplicit-it=arm %s 
2>&1 | FileCheck %s --check-prefix=ARM
+// RUN: %clang -target arm-linux-gnueabi -### -Xassembler -mimplicit-it=thumb 
%s 2>&1 | FileCheck %s --check-prefix=THUMB
+/// Test space seperated -Wa,- arguments.
+// RUN: %clang -target arm-linux-gnueabi -### -Wa,-mthumb 
-Wa,-mimplicit-it=always %s 2>&1 | FileCheck %s --check-prefix=ALWAYS
+// RUN: %clang -target arm-linux-gnueabi -### -Wa,-mthumb 
-Wa,-mimplicit-it=never %s 2>&1 | FileCheck %s --check-prefix=NEVER
+// RUN: %clang -target arm-linux-gnueabi -### -Wa,-mthumb 
-Wa,-mimplicit-it=arm %s 2>&1 | FileCheck %s --check-prefix=ARM
+// RUN: %clang -target arm-linux-gnueabi -### -Wa,-mthumb 
-Wa,-mimplicit-it=thumb %s 2>&1 | FileCheck %s --check-prefix=THUMB
+/// Test comma seperated -Wa,- arguments.
+// RUN: %clang -target arm-linux-gnueabi -### -Wa,-mthumb,-mimplicit-it=always 
%s 2>&1 | FileCheck %s --check-prefix=ALWAYS
+// RUN: %clang -target arm-linux-gnueabi -### -Wa,-mthumb,-mimplicit-it=never 
%s 2>&1 | FileCheck %s --check-prefix=NEVER
+// RUN: %clang -target arm-linux-gnueabi -### -Wa,-mthumb,-mimplicit-it=arm %s 
2>&1 | FileCheck %s --check-prefix=ARM
+// RUN: %clang -target arm-linux-gnueabi -### -Wa,-mthumb,-mimplicit-it=thumb 
%s 2>&1 | FileCheck %s --check-prefix=THUMB
+
+/// Test invalid input.
+// RUN: %clang -target arm-linux-gnueabi -### -Wa,-mimplicit-it=foo %s 2>&1 | 
FileCheck %s --check-prefix=INVALID
+// RUN: %clang -target arm-linux-gnueabi -### -Xassembler -mimplicit-it=foo %s 
2>&1 | FileCheck %s --check-prefix=XINVALID
+
+
+// ALWAYS: "-mllvm" "-arm-implicit-it=always"
+// NEVER: "-mllvm" "-arm-implicit-it=never"
+// ARM: "-mllvm" "-arm-implicit-it=arm"
+// THUMB: "-mllvm" "-arm-implicit-it=thumb"
+// INVALID: error: unsupported argument '-mimplicit-it=foo' to option 'Wa,'
+// XINVALID: error: unsupported argument '-mimplicit-it=foo' to option 
'Xassembler'
Index: clang/lib/Driver/ToolChains/Clang.cpp
===
--- clang/lib/Driver/ToolChains/Clang.cpp
+++ clang/lib/Driver/ToolChains/Clang.cpp
@@ -2304,6 +2304,17 @@
   DumpCompilationDatabase(C, "", Target, Output, Input, Args);
 }
 
+static bool AddImplicitITArgs(const ArgList &Args, ArgStringList &CmdArgs,
+  StringRef Value) {
+  if (Value == "always" || Value == "never" || Value == "arm" ||
+  Value == "thumb") {
+CmdArgs.push_back("-mllvm");
+CmdArgs.push_back(Args.MakeArgString("-arm-implicit-it=" + Value));
+return true;
+  }
+  return false;
+}
+
 static void CollectArgsForIntegratedAssembler(Compilation &C,
   const ArgList &Args,
   ArgStringList &CmdArgs,
@@ -2327,14 +2338,9 @@
   case llvm::Triple::thumbeb:
 if (Arg *A = Args.getLastArg(options::OPT_mimplicit_it_EQ)) {
   StringRef Value = A->getValue();
-  if (Value == "always" || Value == "never" || Value == "arm" ||
-  Value == "thumb") {
-CmdArgs.push_back("-mllvm");
-CmdArgs.push_back(Args.MakeArgString("-arm-implicit-it=" + Value));
-  } else {
+  if (!AddImplicitITArgs(

[PATCH] D92808: [ObjC][ARC] Use operand bundle 'clang.arc.rv' instead of explicitly emitting retainRV or claimRV calls in the IR

2021-02-08 Thread Duncan P. N. Exon Smith via Phabricator via cfe-commits
dexonsmith added a comment.

In D92808#2545873 , @ahatanak wrote:

> I ended up reverting the changes I made to `llvm/lib/IR/AutoUpgrade.cpp` as 
> the file was including `llvm/Analysis/ObjCARCUtil.h`, which was violating 
> layering.

Are you planning to land the upgrade another way?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D92808

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


[PATCH] D18961: Add a readability-deleted-default clang-tidy check.

2021-02-08 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman added a comment.

In D18961#2549303 , @njames93 wrote:

> Now that there is a stable warning in clang for this check that is enabled 
> without specifying any warning flags, Is there reason to think about retiring 
> this check?

I'd be fine with that. We may even have the time to get a deprecation note into 
Clang 12 so that we can remove this code in Clang 13 if we felt so inclined.


Repository:
  rL LLVM

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

https://reviews.llvm.org/D18961

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


[PATCH] D65249: [NFC] use C++11 in AlignOf.h, remove AlignedCharArray

2021-02-08 Thread Mandeep Singh Grang via Phabricator via cfe-commits
mgrang added a comment.
Herald added a subscriber: JDevlieghere.

Hi @jfb This patch results in a compiler crash when building a simple C program 
on a Windows X86 Debug build. I have filed this 
 issue to track it.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D65249

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


[PATCH] D77598: Integral template argument suffix and cast printing

2021-02-08 Thread Richard Smith - zygoloid via Phabricator via cfe-commits
rsmith added inline comments.



Comment at: clang/lib/AST/TemplateBase.cpp:110
+break;
+  default:
+if (T->isUnsignedIntegerType() && T->isWideCharType())

I think we should use the prettier printing for `wchar_t` / `char8_t` / 
`char16_t` / `char32_t` regardless of whether `IncludeType` is set, just like 
we do for `char`.



Comment at: clang/lib/AST/TemplateBase.cpp:112
+if (T->isUnsignedIntegerType() && T->isWideCharType())
+  Out << "L'" << Val << "'";
+else if (T->isUnsignedIntegerType() && T->isChar8Type()) {

This has the same problem that `u8` handling had: it will print the numeric 
value not the character.



Comment at: clang/lib/AST/TemplateBase.cpp:118-120
+} else if (T->isUnsignedIntegerType() && T->isChar16Type())
+  Out << "u'" << Val << "'";
+else if (T->isUnsignedIntegerType() && T->isChar32Type())

rsmith wrote:
> These two cases have the same problem that `u8` handling had: they will print 
> the numeric value not the character.
You don't need the `isUnsignedIntegerType()` checks here (4x).



Comment at: clang/lib/AST/TemplateBase.cpp:118-121
+} else if (T->isUnsignedIntegerType() && T->isChar16Type())
+  Out << "u'" << Val << "'";
+else if (T->isUnsignedIntegerType() && T->isChar32Type())
+  Out << "U'" << Val << "'";

These two cases have the same problem that `u8` handling had: they will print 
the numeric value not the character.



Comment at: clang/lib/AST/TemplateBase.cpp:128
+} else
+  Out << Val;
+  } else

Assuming this is reachable, we should include a cast here.



Comment at: clang/lib/AST/TemplateBase.cpp:442-450
+// FIXME: Do not always include the type.
+// For eg. the -ast-print of the following example -
+// struct A {
+//  template void f();
+// };
+// void g(A a) {
+//  a.f<0L, 0L>();

In the expression case, we've not resolved the template argument against a 
parameter, so there's no possibility to include or not include the type. I 
would remove this FIXME.



Comment at: clang/lib/AST/TypePrinter.cpp:1989
 OS << Comma;
-  printTo(ArgOS, Argument.getPackAsArray(), Policy, true, nullptr);
+  printTo(ArgOS, Argument.getPackAsArray(), Policy, true, TPL);
 } else {

rsmith wrote:
> This is wrong; we'll incorrectly assume that element `i` of the pack 
> corresponds to element `i` of the original template parameter list. We should 
> use the same template parameter for all elements of the pack. (For example, 
> you could pass in `I` and instruct the inner invocation of `printTo` to not 
> increment `I` as it goes.)
You need to pass in `I` here, or we'll assume that all elements of the pack 
correspond to the first template parameter.



Comment at: clang/test/CXX/lex/lex.literal/lex.ext/p12.cpp:21
 int f = UR"("тест 𐀀)"_x;
-int g = UR"("тест_𐀀)"_x; // expected-note {{in instantiation of function 
template specialization 'operator""_x' requested here}}
+int g = UR"("тест_𐀀)"_x; // expected-note {{in instantiation of function 
template specialization 'operator""_x' 
requested here}}

rsmith wrote:
> It would be useful to generate `u8'...'`, `u16'...'`, and `u32'...'` literals 
> at least whenever we think they'd contain printable characters.
Note the sample output here is wrong. We should ideally print

```
operator""_x
```

(with or without the `\` before the `"`), but if we don't have a good way to 
figure out which characters are printable, printing

```
operator""_x
```

would be an acceptable fallback. You should check if LLVM already has some way 
to determine if a given Unicode character is printable and use it if available. 
I think the diagnostics infrastructure may use something like this already.



Comment at: clang/test/CXX/lex/lex.literal/lex.ext/p13.cpp:7
+template  int operator""_x() { // #1 expected-warning 
{{string literal operator templates are a GNU extension}}
+  check chars;// expected-error 
{{implicit instantiation of undefined template 'check'}}
+  return 1;

(Per earlier comment, I think we should use the prettier printing for `char8_t` 
here, regardless of `IncludeType`.)



Comment at: clang/test/SemaCXX/cxx1z-ast-print.cpp:8
+// CHECK: int k = TypeSuffix().x + TypeSuffix().y;
+int k = TypeSuffix().x<0L> + TypeSuffix().y<0L>; // expected-warning 
{{instantiation of variable 'TypeSuffix::x<0>' required here, but no definition 
is available}} expected-note {{add an explicit instantiation declaration to 
suppress this warning if 'TypeSuffix::x<0>' is explicitly instantiated in 
another translation unit}} expected-warning {{instantiation of variable 
'TypeSuffix::y<0

[PATCH] D95055: [clang] Don't look into for C++ headers if they are found alongside the toolchain

2021-02-08 Thread Tom Stellard via Phabricator via cfe-commits
tstellar added a comment.

Sorry, it's too late for 11.1.0.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D95055

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


[PATCH] D95055: [clang] Don't look into for C++ headers if they are found alongside the toolchain

2021-02-08 Thread Duncan P. N. Exon Smith via Phabricator via cfe-commits
dexonsmith accepted this revision.
dexonsmith added a comment.
This revision is now accepted and ready to land.

LGTM. Sorry for missing this earlier!


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D95055

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


[PATCH] D96248: [OpenMP][AMDGPU] Add support for linking libomptarget bitcode

2021-02-08 Thread Jon Chesterfield via Phabricator via cfe-commits
JonChesterfield added a comment.

Looks like an existing problem, but for building openmp via runtimes, with this 
patch applied this doesn't look in the right place and errors:

'error: No library 'libomptarget-amdgcn-gfx906.bc' found in the default clang 
lib directory or in LIBRARY_PATH. Please use --libomptarget-nvptx-bc-path to 
specify nvptx bitcode libarary'

So ./clang/include/clang/Basic/DiagnosticDriverKinds.td entry 
err_drv_omp_offload_target_missingbcruntime should probably prefer to 'device' 
instead of 'nvptx' (error message change only), and we should look in 
'./runtimes/runtimes-bins/openmp/libomptarget/' as well as clang lib.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D96248

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


[PATCH] D92191: [clang-scan-deps] Add support for clang-cl

2021-02-08 Thread Duncan P. N. Exon Smith via Phabricator via cfe-commits
dexonsmith accepted this revision.
dexonsmith added a comment.
This revision is now accepted and ready to land.

LGTM. This is similar enough to the original patch I'm comfortable signing off, 
even though @Bigcheese hasn't had a chance to take a look.


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

https://reviews.llvm.org/D92191

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


[PATCH] D18961: Add a readability-deleted-default clang-tidy check.

2021-02-08 Thread Nathan James via Phabricator via cfe-commits
njames93 added a comment.
Herald added a subscriber: mgorny.

Now that there is a stable warning in clang for this check that is enabled 
without specifying any warning flags, Is there reason to think about retiring 
this check?


Repository:
  rL LLVM

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

https://reviews.llvm.org/D18961

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


[PATCH] D96269: [clang][cli] Look up program action argument in a table

2021-02-08 Thread Duncan P. N. Exon Smith via Phabricator via cfe-commits
dexonsmith accepted this revision.
dexonsmith added a comment.
This revision is now accepted and ready to land.

LGTM.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D96269

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


[PATCH] D96056: [clang][cli] Generate and round-trip CodeGen options

2021-02-08 Thread Duncan P. N. Exon Smith via Phabricator via cfe-commits
dexonsmith accepted this revision.
dexonsmith added a comment.
This revision is now accepted and ready to land.

LGTM.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D96056

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


[PATCH] D96155: [clang][cli] Generate and round-trip Frontend options

2021-02-08 Thread Duncan P. N. Exon Smith via Phabricator via cfe-commits
dexonsmith accepted this revision.
dexonsmith added a comment.
This revision is now accepted and ready to land.

LGTM, although the description seems incorrect:

> This patch implements generation of remaining preprocessor options and tests 
> it by performing parse-generate-parse round trip.

In fact, this patch is working with frontend options. Please fix for the commit 
message.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D96155

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


[PATCH] D96158: [clang][cli] Generate and round-trip Target options

2021-02-08 Thread Duncan P. N. Exon Smith via Phabricator via cfe-commits
dexonsmith accepted this revision.
dexonsmith added a comment.
This revision is now accepted and ready to land.

LGTM.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D96158

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


[PATCH] D96273: [clang][cli] Generate and round-trip DependencyOutput options

2021-02-08 Thread Duncan P. N. Exon Smith via Phabricator via cfe-commits
dexonsmith accepted this revision.
dexonsmith added a comment.
This revision is now accepted and ready to land.

LGTM.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D96273

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


[PATCH] D96149: [clang][cli] Store InputKind in FrontendOptions

2021-02-08 Thread Duncan P. N. Exon Smith via Phabricator via cfe-commits
dexonsmith accepted this revision.
dexonsmith added a comment.
This revision is now accepted and ready to land.

LGTM.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D96149

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


[PATCH] D96274: [clang][cli] Generate and round-trip Diagnostic options

2021-02-08 Thread Duncan P. N. Exon Smith via Phabricator via cfe-commits
dexonsmith requested changes to this revision.
dexonsmith added inline comments.
This revision now requires changes to proceed.



Comment at: clang/lib/Frontend/CompilerInvocation.cpp:745
+
+A->render(Args, Rendered);
   }

It's not obvious why this renders the args instead of calling 
`A->getAsString()` to get the literal command-line argument and putting it 
directly in DiagnosticsAsWritten. If that'll work, I suggest switching to that, 
since it's a bit more straightforward; if there's some reason you can't do 
that, please leave a comment explaining why.



Comment at: clang/lib/Frontend/CompilerInvocation.cpp:2230-2240
+  for (const auto &Warning : Opts.WarningsAsWritten) {
+// This option also maps to UndefPrefixes that generates it automatically.
+if (StringRef(Warning).startswith("-Wundef-prefix="))
+  continue;
+// TODO: Consider ignoring '-Wno-rewrite-macros' that maps to
+// NoRewriteMacros.
+Args.push_back(SA(Warning));

Does this mean that if some client is programmatically modifying the `Warnings` 
array (which is what `CompilerInstance` reads) they need to also update 
`WarningsAsWritten` array identically to get command-line generation to work?

If so, then this is a bit non-obvious / error-prone. Maybe these can 
encapsulated together:
```
struct DiagnosticArg {
  std::string Name;
  std::string AsWritten;
};
std::vector Warnings;
std::vector Remarks;
```


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D96274

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


[PATCH] D96278: [clang][cli] Extract FileSystem and Migrator options parsing/generation

2021-02-08 Thread Duncan P. N. Exon Smith via Phabricator via cfe-commits
dexonsmith accepted this revision.
dexonsmith added a comment.
This revision is now accepted and ready to land.

LGTM.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D96278

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


[PATCH] D96280: [WIP][clang][cli] Round-trip the whole CompilerInvocation

2021-02-08 Thread Duncan P. N. Exon Smith via Phabricator via cfe-commits
dexonsmith added a comment.

Mostly looks great; happy to see this come full circle and remove the 
round-tripping boilerplate. Just a couple of questions inline below.




Comment at: clang/lib/Frontend/CompilerInvocation.cpp:1940-1941
 case EDK_ProfileList:
-  GenerateArg(Args, OPT_fprofile_list_EQ, Dep.first, SA);
+  // Generated from LanguageOptions.
+  // GenerateArg(Args, OPT_fprofile_list_EQ, Dep.first, SA);
   break;

Was it intentional to comment this out? If so, probably better to delete the 
line of code.



Comment at: clang/lib/Frontend/CompilerInvocation.cpp:3438-3439
 
-  if (Opts.NoInlineDefine && Opts.Optimize)
-GenerateArg(Args, OPT_fno_inline, SA);
+  // if (Opts.NoInlineDefine && Opts.Optimize)
+  //   GenerateArg(Args, OPT_fno_inline, SA);
 

Was it intentional to comment out this code? If so, probably better to delete 
it.



Comment at: clang/lib/Frontend/CompilerInvocation.cpp:4534-4547
+  InputKind DashX = FrontendOpts.DashX;
+  if (DashX.getFormat() == InputKind::Precompiled ||
+  DashX.getLanguage() == Language::LLVM_IR) {
+if (LangOpts->ObjCAutoRefCount)
+  GenerateArg(Args, OPT_fobjc_arc, SA);
+if (LangOpts->PICLevel != 0)
+  GenerateArg(Args, OPT_pic_level, Twine(LangOpts->PICLevel), SA);

This change, like the commented out code I already pointed at, seems not 
strictly-related to changing round-tripping to happen at a higher level. Is 
there some reason it's tied to landing at the same time? (If that somehow 
avoids a bunch of refactoring that'll have to be undone after, fine by me, but 
otherwise it'd be nice to make this particular patch as clean as possible I 
think and land the more functional changes ahead of time.)

I also wonder if this special-case logic could/should be buried inside 
`GenerateLangArgs`, possibly by passing in `DashX` as an argument. (Maybe with 
a FIXME to handle via ShouldParseIf? E.g., maybe almost all lang options could 
be moved to a `let` scope that turns on ShouldParseIf with this logic, and 
these four are left outside of it. Up to you, whether you think that's a good 
idea.)


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D96280

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


[PATCH] D96246: Make sure a module file with errors produced via '-fallow-pcm-with-compiler-errors' can be loaded when using implicit modules

2021-02-08 Thread Argyrios Kyrtzidis via Phabricator via cfe-commits
akyrtzi updated this revision to Diff 322166.
akyrtzi added a comment.

clang-format change


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D96246

Files:
  clang/include/clang/Serialization/ASTReader.h
  clang/lib/Frontend/CompilerInstance.cpp
  clang/lib/Serialization/ASTReader.cpp
  clang/test/Modules/load-module-with-errors.m

Index: clang/test/Modules/load-module-with-errors.m
===
--- clang/test/Modules/load-module-with-errors.m
+++ clang/test/Modules/load-module-with-errors.m
@@ -1,3 +1,14 @@
+// Note: the run lines follow their respective tests, since line/column
+// matter in this test.
+
+// pcherror-error@* {{PCH file contains compiler errors}}
+@import error; // notallowerror-error {{could not build module 'error'}}
+// expected-no-diagnostics
+
+void test(Error *x) {
+  [x method];
+}
+
 // RUN: rm -rf %t
 // RUN: mkdir %t
 // RUN: mkdir %t/prebuilt
@@ -48,21 +59,27 @@
 // the verify would fail as it would be the PCH error instead)
 // RUN: %clang_cc1 -fsyntax-only -fmodules \
 // RUN:   -fmodules-cache-path=%t -fimplicit-module-maps -I %S/Inputs/error \
-// RUN:   -x objective-c -verify %s
+// RUN:   -x objective-c -verify=notallowerror %s
 
 // allow-pcm-with-compiler-errors should also allow errors in PCH
 // RUN: %clang_cc1 -fallow-pcm-with-compiler-errors -x objective-c \
 // RUN:   -o %t/check.pch -emit-pch %S/Inputs/error/error.h
 
-// pcherror-error@* {{PCH file contains compiler errors}}
-@import error; // expected-error {{could not build module 'error'}}
-
-void test(Error *x) {
-  [x method];
-}
-
 // CHECK: @interface Error
 // CHECK-NEXT: - (int)method;
 // CHECK-NEXT: - (id)method2;
 // CHECK-NEXT: @end
 // CHECK: void test(Error *x)
+
+// RUN: c-index-test -code-completion-at=%s:9:6 %s -fmodules -fmodules-cache-path=%t \
+// RUN:   -Xclang -fallow-pcm-with-compiler-errors -I %S/Inputs/error | FileCheck -check-prefix=COMPLETE %s
+// COMPLETE: ObjCInstanceMethodDecl:{ResultType int}{TypedText method}
+// COMPLETE: ObjCInstanceMethodDecl:{ResultType id}{TypedText method2}
+
+// RUN: c-index-test -test-load-source local %s -fmodules -fmodules-cache-path=%t \
+// RUN:   -Xclang -fallow-pcm-with-compiler-errors -I %S/Inputs/error | FileCheck -check-prefix=SOURCE %s
+// SOURCE: load-module-with-errors.m:8:6: FunctionDecl=test:8:6 (Definition) Extent=[8:1 - 10:2]
+// SOURCE: load-module-with-errors.m:8:18: ParmDecl=x:8:18 (Definition) Extent=[8:11 - 8:19]
+// SOURCE: load-module-with-errors.m:8:11: ObjCClassRef=Error:3:12 Extent=[8:11 - 8:16]
+// SOURCE: load-module-with-errors.m:8:21: CompoundStmt= Extent=[8:21 - 10:2]
+// SOURCE: load-module-with-errors.m:9:3: ObjCMessageExpr=method:4:8 Extent=[9:3 - 9:13]
Index: clang/lib/Serialization/ASTReader.cpp
===
--- clang/lib/Serialization/ASTReader.cpp
+++ clang/lib/Serialization/ASTReader.cpp
@@ -2751,8 +2751,9 @@
 
   bool hasErrors = Record[6];
   if (hasErrors && !DisableValidation) {
-// Always rebuild modules from the cache on an error
-if (F.Kind == MK_ImplicitModule)
+// If requested by the caller, mark modules on error as out-of-date.
+if (F.Kind == MK_ImplicitModule &&
+(ClientLoadCapabilities & ARR_TreatModuleWithErrorsAsOutOfDate))
   return OutOfDate;
 
 if (!AllowASTWithCompilerErrors) {
Index: clang/lib/Frontend/CompilerInstance.cpp
===
--- clang/lib/Frontend/CompilerInstance.cpp
+++ clang/lib/Frontend/CompilerInstance.cpp
@@ -1144,7 +1144,10 @@
   // module generation thread crashed.
   Instance.clearOutputFiles(/*EraseFiles=*/true);
 
-  return !Instance.getDiagnostics().hasErrorOccurred();
+  // If \p AllowPCMWithCompilerErrors is set return 'success' even if errors
+  // occurred.
+  return !Instance.getDiagnostics().hasErrorOccurred() ||
+ Instance.getFrontendOpts().AllowPCMWithCompilerErrors;
 }
 
 static const FileEntry *getPublicModuleMap(const FileEntry *File,
@@ -1697,7 +1700,8 @@
   // Try to load the module file. If we are not trying to load from the
   // module cache, we don't know how to rebuild modules.
   unsigned ARRFlags = Source == MS_ModuleCache
-  ? ASTReader::ARR_OutOfDate | ASTReader::ARR_Missing
+  ? ASTReader::ARR_OutOfDate | ASTReader::ARR_Missing |
+ASTReader::ARR_TreatModuleWithErrorsAsOutOfDate
   : Source == MS_PrebuiltModulePath
 ? 0
 : ASTReader::ARR_ConfigurationMismatch;
Index: clang/include/clang/Serialization/ASTReader.h
===
--- clang/include/clang/Serialization/ASTReader.h
+++ clang/include/clang/Serialization/ASTRead

[PATCH] D96032: [flang][driver] Add support for -fopenmp and -fopenacc

2021-02-08 Thread Andrzej Warzynski via Phabricator via cfe-commits
awarzynski accepted this revision.
awarzynski added a comment.
This revision is now accepted and ready to land.

Thank you for this patch @FarisRehman , it's great to see more tests being 
ported to the new driver!

Although this patches touches many files, it mostly just generalizes the `RUN` 
lines. With this change we can easily switch between `f18` and `flang-new` 
(depending on `FLANG_BUILD_NEW_DRIVER`), which is very helpful!

LGTM (could you moving `options::OPT_fopenmp, options::OPT_fopenacc` do a 
dedicated method before merging?)




Comment at: clang/include/clang/Driver/Options.td:4219-4220
 def ffixed_line_length_VALUE : Joined<["-"], "ffixed-line-length-">, 
Group, Alias;
+def fopenacc : Flag<["-"], "fopenacc">, Group,
+  HelpText<"Parse OpenACC pragmas and generate parallel code.">;
 

Could we follow `gcc` here:
```
gcc --help=fortran | grep openacc
  -fopenacc   Enable OpenACC.
```



Comment at: clang/lib/Driver/ToolChains/Flang.cpp:25-26
   Args.AddAllArgs(CmdArgs, {options::OPT_ffixed_form, options::OPT_ffree_form,
-options::OPT_ffixed_line_length_EQ});
+options::OPT_ffixed_line_length_EQ,
++options::OPT_fopenmp, options::OPT_fopenacc});
 }

`-fopenmp` and `-fopenacc` enable extensions, so they are not dialect options.



Comment at: flang/lib/Frontend/CompilerInvocation.cpp:350
+
+  // Add predefinitions based on language features enabled
+  if (frontendOptions.features_.IsEnabled(

[nit] `language` -> `extensions`


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D96032

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


[PATCH] D96175: [clang] Add support for attribute 'swift_async_error'

2021-02-08 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 modulo some testing requests. Thanks!




Comment at: clang/lib/Sema/SemaDeclAttr.cpp:5977
+checkSwiftAsyncErrorBlock(S, D, ErrorAttr, AsyncAttr);
+}
+

erik.pilkington wrote:
> aaron.ballman wrote:
> > Should there be a diagnostic to combine `swift_error` and 
> > `swift_async_error` on the same function? Similarly, should there be a 
> > diagnostic when adding `swift_async_error` to a function that isn't 
> > (eventually) marked `swift_async`?
> My understanding is that `swift_error` and `swift_async_error` don't conflict 
> with each other. `swift_error` describes how the non-async swift function 
> handles errors, whereas `swift_async_error` describes how the swift async 
> function handles errors. Since both swift functions are generated, I think it 
> can make sense to have both attributes on one ObjC function. 
> 
> I think it can make sense to have `swift_async_error` without `swift_async`, 
> since the swift importer infers some functions are async without the 
> `swift_async` attribute using heuristics based on parameter names. I guess we 
> could mimic those heuristics here to diagnose when `swift_async_error` 
> doesn't make sense alone, but ISTM that it makes more sense to do that check 
> in the swift importer.
Thanks for the information!

> I think it can make sense to have both attributes on one ObjC function.

Fine by me then! Can you add a test case with a comment showing that this is 
explicitly expected to be okay?

> I think it can make sense to have swift_async_error without swift_async

Also fine by me then! I don't think we need to go to great effort here to 
diagnose that (the swift importer can gain extra logic if that's useful). I 
think this is also worth a test case with a comment.

(In both cases, I'm thinking mostly about code archeology projects in the 
future to answer "did they think of" kind of questions.)


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

https://reviews.llvm.org/D96175

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


[PATCH] D89649: Fix __has_unique_object_representations with no_unique_address

2021-02-08 Thread Gabor Bencze via Phabricator via cfe-commits
gbencze added inline comments.



Comment at: clang/lib/AST/ASTContext.cpp:2582-2584
+int64_t BitfieldSize = Field->getBitWidthValue(Context);
+if (BitfieldSize > FieldSizeInBits)
+  return llvm::None;

steakhal wrote:
> Why do you return `None` here?
These bits were just extracted from `structHasUniqueObjectRepresentations`, the 
underlying logic was not changed here. (originally in line 2615)
I believe this handles the case "If the width of a bit-field is larger than the 
width of the bit-field's type (or, in case of an enumeration type, of its 
underlying type), the extra bits are padding bits" from [class.bit]



Comment at: clang/lib/AST/ASTContext.cpp:2595-2598
+template 
+static llvm::Optional structSubobjectsHaveUniqueObjectRepresentations(
+const RangeT &Subobjects, int64_t CurOffsetInBits, const ASTContext 
&Context,
+const clang::ASTRecordLayout &Layout) {

steakhal wrote:
> Why is this a template?
> Can't you just take the `field_range`?
> 
> By the same token, `structSubobjectsHaveUniqueObjectRepresentations` returns 
> an `optional int`. I'm confused.
This function is also called with (non virtual) base class subobjects, not just 
fields.
A `None` return value indicates that the subobjects do not have unique object 
representations, otherwise the size of the subobjects is returned. This allows 
us to detect for example padding between a base class and the first field. 



Comment at: clang/test/SemaCXX/has_unique_object_reps_no_unique_addr.cpp:42
+} // namespace TailPaddingReuse
+static_assert(__has_unique_object_representations(TailPaddingReuse::B));

steakhal wrote:
> Why is this outside of the namespace declaration?
Tbh I'm not sure. I can move it in the namespace if you think it'd be better 
there. 


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

https://reviews.llvm.org/D89649

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


[PATCH] D96175: [clang] Add support for attribute 'swift_async_error'

2021-02-08 Thread Erik Pilkington via Phabricator via cfe-commits
erik.pilkington added inline comments.



Comment at: clang/lib/Sema/SemaDeclAttr.cpp:5977
+checkSwiftAsyncErrorBlock(S, D, ErrorAttr, AsyncAttr);
+}
+

aaron.ballman wrote:
> Should there be a diagnostic to combine `swift_error` and `swift_async_error` 
> on the same function? Similarly, should there be a diagnostic when adding 
> `swift_async_error` to a function that isn't (eventually) marked 
> `swift_async`?
My understanding is that `swift_error` and `swift_async_error` don't conflict 
with each other. `swift_error` describes how the non-async swift function 
handles errors, whereas `swift_async_error` describes how the swift async 
function handles errors. Since both swift functions are generated, I think it 
can make sense to have both attributes on one ObjC function. 

I think it can make sense to have `swift_async_error` without `swift_async`, 
since the swift importer infers some functions are async without the 
`swift_async` attribute using heuristics based on parameter names. I guess we 
could mimic those heuristics here to diagnose when `swift_async_error` doesn't 
make sense alone, but ISTM that it makes more sense to do that check in the 
swift importer.


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

https://reviews.llvm.org/D96175

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


[PATCH] D96175: [clang] Add support for attribute 'swift_async_error'

2021-02-08 Thread Erik Pilkington via Phabricator via cfe-commits
erik.pilkington updated this revision to Diff 322152.
erik.pilkington marked 2 inline comments as done.
erik.pilkington added a comment.

Get rid of a useless `return`.


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

https://reviews.llvm.org/D96175

Files:
  clang/include/clang/Basic/Attr.td
  clang/include/clang/Basic/AttrDocs.td
  clang/include/clang/Basic/DiagnosticSemaKinds.td
  clang/lib/Sema/SemaDeclAttr.cpp
  clang/test/Misc/pragma-attribute-supported-attributes-list.test
  clang/test/SemaObjC/attr-swift-async-error.m

Index: clang/test/SemaObjC/attr-swift-async-error.m
===
--- /dev/null
+++ clang/test/SemaObjC/attr-swift-async-error.m
@@ -0,0 +1,90 @@
+// RUN: %clang_cc1 %s -fblocks -fsyntax-only -verify
+
+#define ASYNC(...) __attribute__((swift_async(__VA_ARGS__)))
+#define ASYNC_ERROR(...) __attribute__((swift_async_error(__VA_ARGS__)))
+
+ASYNC(swift_private, 1)
+ASYNC_ERROR(zero_argument, 1)
+void test_good(void (^handler)(int));
+
+ASYNC(swift_private, 2)
+ASYNC_ERROR(nonzero_argument, 2)
+void test_good2(double, void (^handler)(double, int, double));
+
+enum SomeEnum { SE_a, SE_b };
+
+ASYNC(swift_private, 1)
+ASYNC_ERROR(nonzero_argument, 1)
+void test_good3(void (^handler)(enum SomeEnum, double));
+
+ASYNC_ERROR(zero_argument, 1)
+ASYNC(swift_private, 1)
+void test_rev_order(void (^handler)(int));
+
+@class NSError;
+
+ASYNC(swift_private, 1)
+ASYNC_ERROR(nonnull_error)
+void test_nserror(void (^handler)(NSError *));
+
+typedef struct __attribute__((objc_bridge(NSError))) __CFError * CFErrorRef;
+
+ASYNC(swift_private, 1)
+ASYNC_ERROR(nonnull_error)
+void test_cferror(void (^handler)(CFErrorRef));
+
+ASYNC(swift_private, 1)
+ASYNC_ERROR(nonnull_error) // expected-error {{'swift_async_error' attribute with 'nonnull_error' convention can only be applied to a function with a completion handler with an error parameter}}
+void test_interror(void (^handler)(int));
+
+ASYNC(swift_private, 1)
+ASYNC_ERROR(zero_argument, 1) // expected-error {{'swift_async_error' attribute with 'zero_argument' convention must have an integral-typed parameter in completion handler at index 1, type here is 'double'}}
+void test_not_integral(void (^handler)(double));
+
+ASYNC(swift_private, 1)
+ASYNC_ERROR(none)
+void test_none(void (^)());
+
+ASYNC(none)
+ASYNC_ERROR(none)
+void test_double_none(void (^)());
+
+ASYNC(none)
+ASYNC_ERROR(none, 1) // expected-error {{'swift_async_error' attribute takes one argument}}
+void test_double_none_args();
+
+ASYNC(swift_private, 1)
+ASYNC_ERROR(nonnull_error, 1) // expected-error{{'swift_async_error' attribute takes one argument}}
+void test_args(void (^)(void));
+
+ASYNC(swift_private, 1)
+ASYNC_ERROR(zero_argument, 1, 1) // expected-error{{'swift_async_error' attribute takes no more than 2 arguments}}
+void test_args2(void (^)(int));
+
+ASYNC_ERROR(none) int x; // expected-warning{{'swift_async_error' attribute only applies to functions and Objective-C methods}}
+
+@interface ObjC
+-(void)m1:(void (^)(int))handler
+  ASYNC(swift_private, 1)
+  ASYNC_ERROR(zero_argument, 1);
+
+-(void)m2:(int)first withSecond:(void (^)(int))handler
+  ASYNC(swift_private, 2)
+  ASYNC_ERROR(nonzero_argument, 1);
+
+-(void)m3:(void (^)(void))block
+  ASYNC_ERROR(zero_argument, 1) // expected-error {{'swift_async_error' attribute parameter 2 is out of bounds}}
+  ASYNC(swift_private, 1);
+
+-(void)m4:(void (^)(double, int, float))handler
+  ASYNC(swift_private, 1)
+  ASYNC_ERROR(nonzero_argument, 1); // expected-error{{swift_async_error' attribute with 'nonzero_argument' convention must have an integral-typed parameter in completion handler at index 1, type here is 'double'}}
+
+-(void)m5:(void (^)(NSError *))handler
+  ASYNC(swift_private, 1)
+  ASYNC_ERROR(nonnull_error);
+
+-(void)m6:(void (^)(void *))handler
+  ASYNC(swift_private, 1)
+  ASYNC_ERROR(nonnull_error); // expected-error{{'swift_async_error' attribute with 'nonnull_error' convention can only be applied to a method with a completion handler with an error parameter}}
+@end
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
@@ -155,6 +155,7 @@
 // CHECK-NEXT: SetTypestate (SubjectMatchRule_function_is_member)
 // CHECK-NEXT: SpeculativeLoadHardening (SubjectMatchRule_function, SubjectMatchRule_objc_method)
 // CHECK-NEXT: SwiftAsync (SubjectMatchRule_function, SubjectMatchRule_objc_method)
+// CHECK-NEXT: SwiftAsyncError (SubjectMatchRule_function, SubjectMatchRule_objc_method)
 // CHECK-NEXT: SwiftAsyncName (SubjectMatchRule_objc_method, SubjectMatchRule_function)
 // CHECK-NEXT: SwiftBridgedTypedef (SubjectMatchRule_type_alias)
 // CHECK-NEXT: SwiftContext (SubjectMatchRule_variable_is_parameter)
Index: clang/lib/Sema/SemaDeclAtt

[PATCH] D96281: Add options to flag individual core increments and to ignore macros to cognitive complexity check.

2021-02-08 Thread Jens Massberg via Phabricator via cfe-commits
massberg created this revision.
massberg added reviewers: lebedev.ri, alexfh.
Herald added a subscriber: nullptr.cpp.
massberg requested review of this revision.
Herald added a project: clang.

Often you are only interested in the overall cognitive complexity of a
function and not every individual increment. Thus the flag
'FlagBasicIncrements' is added. If it is set to 'true', each increment
is flagged. Otherwise, only the complexity of function with complexity
of at least the threshold are flagged.

If a macro is used within the function, the code inside the macro
doesn't make the code less readable. Instead, for a reader a macro is
more like a function that is called. Thus the code inside a macro
shouldn't increase the complexity of the function in which it is called.
Thus the flag 'IgnoreMacros' is added. If set to 'true' code inside
macros isn't considered during analysis.
This isn't perfect, as now the code of a macro isn't considered at all,
even if it has a high cognitive complexity itself. It might be better if
a macro is considered in the analysis like a function and gets its own
cognitive complexity. Implementing such an analysis seems to be very
complex (if possible at all with the given AST), so we give the user the
option to either ignore macros completely or to let the expanded code
count to the calling function's complexity.

By default 'FlagBasisIncrements' is set to 'true' and 'IgnoreMacros' is
set to 'false', which is the original behavior of the check.

Added a new test for different flag combinations.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D96281

Files:
  clang-tools-extra/clang-tidy/readability/FunctionCognitiveComplexityCheck.cpp
  clang-tools-extra/clang-tidy/readability/FunctionCognitiveComplexityCheck.h
  
clang-tools-extra/docs/clang-tidy/checks/readability-function-cognitive-complexity.rst
  
clang-tools-extra/test/clang-tidy/checkers/readability-function-cognitive-complexity-flags.cpp

Index: clang-tools-extra/test/clang-tidy/checkers/readability-function-cognitive-complexity-flags.cpp
===
--- /dev/null
+++ clang-tools-extra/test/clang-tidy/checkers/readability-function-cognitive-complexity-flags.cpp
@@ -0,0 +1,64 @@
+// RUN: %check_clang_tidy %s readability-function-cognitive-complexity %t -- \
+// RUN:   -config='{CheckOptions: \
+// RUN: [{key: readability-function-cognitive-complexity.Threshold, \
+// RUN:   value: 0}, \
+// RUN:  {key: readability-function-cognitive-complexity.FlagBasicIncrements, \
+// RUN:   value: "false"} ]}'
+// RUN: %check_clang_tidy -check-suffix=THRESHOLD5 %s readability-function-cognitive-complexity %t -- \
+// RUN:   -config='{CheckOptions: \
+// RUN: [{key: readability-function-cognitive-complexity.Threshold, \
+// RUN:   value: 5}, \
+// RUN:  {key: readability-function-cognitive-complexity.FlagBasicIncrements, \
+// RUN:   value: "false"} ]}'
+// RUN: %check_clang_tidy -check-suffix=IGNORE-MACROS %s readability-function-cognitive-complexity %t -- \
+// RUN:   -config='{CheckOptions: \
+// RUN: [{key: readability-function-cognitive-complexity.Threshold, \
+// RUN:   value: 0}, \
+// RUN:  {key: readability-function-cognitive-complexity.IgnoreMacros, \
+// RUN:   value: "true"}, \
+// RUN:  {key: readability-function-cognitive-complexity.FlagBasicIncrements, \
+// RUN:   value: "false"} ]}'
+
+void func_of_complexity_4() {
+  // CHECK-NOTES: :[[@LINE-1]]:6: warning: function 'func_of_complexity_4' has cognitive complexity of 4 (threshold 0) [readability-function-cognitive-complexity]
+  // CHECK-NOTES-IGNORE-MACROS: :[[@LINE-2]]:6: warning: function 'func_of_complexity_4' has cognitive complexity of 4 (threshold 0) [readability-function-cognitive-complexity]
+  if (1) {
+if (1) {
+}
+  }
+  if (1) {
+  }
+}
+
+#define MacroOfComplexity10 \
+  if (1) {  \
+if (1) {\
+  if (1) {  \
+if (1) {\
+}   \
+  } \
+}   \
+  }
+
+void function_with_macro() {
+  // CHECK-NOTES: :[[@LINE-1]]:6: warning: function 'function_with_macro' has cognitive complexity of 11 (threshold 0) [readability-function-cognitive-complexity]
+  // CHECK-NOTES-THRESHOLD5: :[[@LINE-2]]:6: warning: function 'function_with_macro' has cognitive complexity of 11 (threshold 5) [readability-function-cognitive-complexity]
+  // CHECK-NOTES-IGNORE-MACROS: :[[@LINE-3]]:6: warning: function 'function_with_macro' has cognitive complexity of 1 (threshold 0) [readability-function-cognitive-complexity]
+
+  MacroOfComplexity10
+
+  if (1) {
+  }
+}
+
+#define uglyfunctionmacro(name) \
+  void name() { \
+if (true) { \
+  try { \

[PATCH] D96280: [WIP][clang][cli] Round-trip the whole CompilerInvocation

2021-02-08 Thread Jan Svoboda via Phabricator via cfe-commits
jansvoboda11 created this revision.
jansvoboda11 added reviewers: Bigcheese, dexonsmith.
jansvoboda11 requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

Finally, this patch moves from round-tripping one `CompilerInvocation` at a 
time to round-tripping the whole invocation.

This includes only the work to make it work. Any cleanup work will be done in a 
follow-up patch.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D96280

Files:
  clang/include/clang/Basic/DiagnosticDriverKinds.td
  clang/include/clang/Frontend/CompilerInvocation.h
  clang/lib/Frontend/CompilerInvocation.cpp

Index: clang/lib/Frontend/CompilerInvocation.cpp
===
--- clang/lib/Frontend/CompilerInvocation.cpp
+++ clang/lib/Frontend/CompilerInvocation.cpp
@@ -423,9 +423,11 @@
 
 static const StringRef GetInputKindName(InputKind IK);
 
-static void FixupInvocation(CompilerInvocation &Invocation,
-DiagnosticsEngine &Diags, const InputArgList &Args,
+static bool FixupInvocation(CompilerInvocation &Invocation,
+DiagnosticsEngine &Diags, const ArgList &Args,
 InputKind IK) {
+  unsigned NumErrorsBefore = Diags.getNumErrors();
+
   LangOptions &LangOpts = *Invocation.getLangOpts();
   CodeGenOptions &CodeGenOpts = Invocation.getCodeGenOpts();
   TargetOptions &TargetOpts = Invocation.getTargetOpts();
@@ -502,6 +504,8 @@
 Diags.Report(diag::err_drv_argument_only_allowed_with)
 << Args.getLastArg(OPT_fprofile_remapping_file_EQ)->getAsString(Args)
 << "-fno-legacy-pass-manager";
+
+  return Diags.getNumErrors() == NumErrorsBefore;
 }
 
 //===--===//
@@ -569,39 +573,39 @@
 Opt.getKind(), 0, Value);
 }
 
-// Parse subset of command line arguments into a member of CompilerInvocation.
-using ParseFn = llvm::function_ref;
+// Parse command line arguments into CompilerInvocation.
+using ParseFn =
+llvm::function_ref,
+DiagnosticsEngine &, const char *)>;
 
-// Generate part of command line arguments from a member of CompilerInvocation.
+// Generate command line arguments from CompilerInvocation.
 using GenerateFn = llvm::function_ref &,
 CompilerInvocation::StringAllocator)>;
 
-// Swap between dummy/real instance of a CompilerInvocation member.
-using SwapOptsFn = llvm::function_ref;
-
 // Performs round-trip of command line arguments if OriginalArgs contain
 // "-round-trip-args". Effectively runs the Parse function for a part of
 // CompilerInvocation on command line arguments that were already once parsed
 // and generated. This is used to check the Generate function produces arguments
 // that are semantically equivalent to those that were used to create
 // CompilerInvocation.
-static bool RoundTrip(ParseFn Parse, GenerateFn Generate, SwapOptsFn SwapOpts,
-  CompilerInvocation &Res, ArgList &OriginalArgs,
-  DiagnosticsEngine &Diags, StringRef OptsName) {
+static bool RoundTrip(ParseFn Parse, GenerateFn Generate,
+  CompilerInvocation &RealInvocation,
+  CompilerInvocation &DummyInvocation,
+  ArrayRef CommandLineArgs,
+  DiagnosticsEngine &Diags, const char *Argv0) {
   bool DoRoundTrip = false;
 #ifdef CLANG_ROUND_TRIP_CC1_ARGS
   DoRoundTrip = true;
 #endif
 
-  // If round-trip was not requested, simply run the parser with the original
-  // options and diagnostics.
+  // If round-trip was not requested, simply run the parser with the real
+  // invocation diagnostics.
   if (!DoRoundTrip)
-return Parse(Res, OriginalArgs, Diags);
+return Parse(RealInvocation, CommandLineArgs, Diags, Argv0);
 
   // Serializes quoted (and potentially escaped) arguments.
-  auto SerializeArgs = [](ArgStringList &Args) {
+  auto SerializeArgs = [](ArrayRef Args) {
 std::string Buffer;
 llvm::raw_string_ostream OS(Buffer);
 for (const char *Arg : Args) {
@@ -612,34 +616,28 @@
 return Buffer;
   };
 
-  OriginalArgs.clearQueriedOpts();
-
   // Setup a dummy DiagnosticsEngine.
   DiagnosticsEngine DummyDiags(new DiagnosticIDs(), new DiagnosticOptions());
   DummyDiags.setClient(new TextDiagnosticBuffer());
 
-  // Run the first parse on the original arguments with dummy options and
+  // Run the first parse on the original arguments with the dummy invocation and
   // diagnostics.
-  SwapOpts(Res);
-  if (!Parse(Res, OriginalArgs, DummyDiags) ||
+  if (!Parse(DummyInvocation, CommandLineArgs, DummyDiags, Argv0) ||
   DummyDiags.getNumWarnings() != 0) {
 // If the first parse did not succeed, it must be user mistake (invalid
 // command line arguments). We won't be able to generate arguments that
-// would reproduce the same result. Let's fail again wi

[PATCH] D96279: [OpenCL] Add cl_khr_subgroup_extended_types to TableGen BIFs

2021-02-08 Thread Sven van Haastregt via Phabricator via cfe-commits
svenvh created this revision.
svenvh added a reviewer: Anastasia.
svenvh added a project: clang.
Herald added a subscriber: yaxunl.
svenvh requested review of this revision.
Herald added a subscriber: cfe-commits.

Add the builtin functions brought by the cl_khr_subgroup_extended_types 
extension to `-fdeclare-opencl-builtins`.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D96279

Files:
  clang/lib/Sema/OpenCLBuiltins.td
  clang/test/SemaOpenCL/fdeclare-opencl-builtins.cl


Index: clang/test/SemaOpenCL/fdeclare-opencl-builtins.cl
===
--- clang/test/SemaOpenCL/fdeclare-opencl-builtins.cl
+++ clang/test/SemaOpenCL/fdeclare-opencl-builtins.cl
@@ -39,6 +39,7 @@
 
 // Enable extensions that are enabled in opencl-c-base.h.
 #if (defined(__OPENCL_CPP_VERSION__) || __OPENCL_C_VERSION__ >= 200)
+#define cl_khr_subgroup_extended_types 1
 #define cl_khr_subgroup_ballot 1
 #define cl_khr_subgroup_non_uniform_arithmetic 1
 #define cl_khr_subgroup_clustered_reduce 1
@@ -157,15 +158,18 @@
 #endif
 }
 
-kernel void extended_subgroup(global uint4 *out, global int *scalar) {
+kernel void extended_subgroup(global uint4 *out, global int *scalar, global 
char2 *c2) {
   out[0] = get_sub_group_eq_mask();
   scalar[0] = sub_group_non_uniform_scan_inclusive_or(3);
   scalar[1] = sub_group_clustered_reduce_logical_xor(2, 4);
+  *c2 = sub_group_broadcast(*c2, 2);
 #if __OPENCL_C_VERSION__ < CL_VERSION_2_0 && !defined(__OPENCL_CPP_VERSION__)
-  // expected-error@-4{{implicit declaration of function 
'get_sub_group_eq_mask' is invalid in OpenCL}}
-  // expected-error@-5{{implicit conversion changes signedness}}
-  // expected-error@-5{{implicit declaration of function 
'sub_group_non_uniform_scan_inclusive_or' is invalid in OpenCL}}
-  // expected-error@-5{{implicit declaration of function 
'sub_group_clustered_reduce_logical_xor' is invalid in OpenCL}}
+  // expected-error@-5{{implicit declaration of function 
'get_sub_group_eq_mask' is invalid in OpenCL}}
+  // expected-error@-6{{implicit conversion changes signedness}}
+  // expected-error@-6{{implicit declaration of function 
'sub_group_non_uniform_scan_inclusive_or' is invalid in OpenCL}}
+  // expected-error@-6{{implicit declaration of function 
'sub_group_clustered_reduce_logical_xor' is invalid in OpenCL}}
+  // expected-error@-6{{implicit declaration of function 'sub_group_broadcast' 
is invalid in OpenCL}}
+  // expected-error@-7{{implicit conversion loses integer precision}}
 #endif
 }
 
Index: clang/lib/Sema/OpenCLBuiltins.td
===
--- clang/lib/Sema/OpenCLBuiltins.td
+++ clang/lib/Sema/OpenCLBuiltins.td
@@ -53,6 +53,7 @@
 // FunctionExtension definitions.
 def FuncExtNone  : FunctionExtension<"">;
 def FuncExtKhrSubgroups  : 
FunctionExtension<"cl_khr_subgroups">;
+def FuncExtKhrSubgroupExtendedTypes  : 
FunctionExtension<"cl_khr_subgroup_extended_types">;
 def FuncExtKhrSubgroupNonUniformVote : 
FunctionExtension<"cl_khr_subgroup_non_uniform_vote">;
 def FuncExtKhrSubgroupBallot : 
FunctionExtension<"cl_khr_subgroup_ballot">;
 def FuncExtKhrSubgroupNonUniformArithmetic: 
FunctionExtension<"cl_khr_subgroup_non_uniform_arithmetic">;
@@ -381,6 +382,9 @@
 def FGenTypeN  : GenericType<"FGenTypeN", TLFloat, VecAndScalar>;
 // (u)int, (u)long, and all floats
 def IntLongFloatGenType1   : GenericType<"IntLongFloatGenType1", 
TLIntLongFloats, Vec1>;
+// (u)char and (u)short
+def CharShortGenType1  : GenericType<"CharShortGenType1",
+ TypeList<[Char, UChar, Short, UShort]>, Vec1>;
 
 // GenType definitions for every single base type (e.g. fp32 only).
 // Names are like: GenTypeFloatVecAndScalar.
@@ -1519,7 +1523,19 @@
 // OpenCL Extension v3.0 s38 - Extended Subgroup Functions
 
 // Section 38.4.1 - cl_khr_subgroup_extended_types
-// TODO
+let Extension = FuncExtKhrSubgroupExtendedTypes in {
+  // For sub_group_broadcast, add scalar char, uchar, short, and ushort 
support,
+  def : Builtin<"sub_group_broadcast", [CharShortGenType1, CharShortGenType1, 
UInt], Attr.Convergent>;
+  // gentype may additionally be one of the supported built-in vector data 
types.
+  def : Builtin<"sub_group_broadcast", [AGenTypeNNoScalar, AGenTypeNNoScalar, 
UInt], Attr.Convergent>;
+
+  foreach name = ["sub_group_reduce_", "sub_group_scan_exclusive_",
+  "sub_group_scan_inclusive_"] in {
+foreach op = ["add", "min", "max"] in {
+  def : Builtin;
+}
+  }
+}
 
 // Section 38.5.1 - cl_khr_subgroup_non_uniform_vote
 let Extension = FuncExtKhrSubgroupNonUniformVote in {


Index: clang/test/SemaOpenCL/fdeclare-opencl-builtins.cl
===
--- clang/test/SemaOpenCL/fdeclare-opencl-builtins.cl
+++ clang/test/SemaOpenCL/fdeclare-opencl-builtins.cl
@@ -39,6 +39,7 @@
 
 // Ena

[PATCH] D96278: [clang][cli] Extract FileSystem and Migrator options parsing/generation

2021-02-08 Thread Jan Svoboda via Phabricator via cfe-commits
jansvoboda11 created this revision.
jansvoboda11 added reviewers: Bigcheese, dexonsmith.
Herald added a subscriber: dang.
jansvoboda11 requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

This patch splits out the last two option groups (`Filesystem` and `Migrator`) 
into their own `Parse`/`Generate` functions.

This effectively removes the need for `parseSimpleArgs` and marshalling block 
in `CompilerInvocation::generateCC1CommandLine`.

The two new `Parse`/`Generate` functions are not part of the round-trip, 
because they contain no custom code and the very next patch starts 
round-tripping the whole `CompilerInvocation`.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D96278

Files:
  clang/include/clang/Driver/Options.td
  clang/include/clang/Frontend/CompilerInvocation.h
  clang/lib/Frontend/CompilerInvocation.cpp

Index: clang/lib/Frontend/CompilerInvocation.cpp
===
--- clang/lib/Frontend/CompilerInvocation.cpp
+++ clang/lib/Frontend/CompilerInvocation.cpp
@@ -2159,21 +2159,70 @@
   return Success;
 }
 
-bool CompilerInvocation::parseSimpleArgs(const ArgList &Args,
- DiagnosticsEngine &Diags) {
+static void GenerateFileSystemArgs(const FileSystemOptions &FileSystemOpts,
+   SmallVectorImpl &Args,
+   CompilerInvocation::StringAllocator SA) {
+#define FILE_SYSTEM_OPTION_WITH_MARSHALLING(   \
+PREFIX_TYPE, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM,\
+HELPTEXT, METAVAR, VALUES, SPELLING, SHOULD_PARSE, ALWAYS_EMIT, KEYPATH,   \
+DEFAULT_VALUE, IMPLIED_CHECK, IMPLIED_VALUE, NORMALIZER, DENORMALIZER, \
+MERGER, EXTRACTOR, TABLE_INDEX)\
+  GENERATE_OPTION_WITH_MARSHALLING(\
+  Args, SA, KIND, FLAGS, SPELLING, ALWAYS_EMIT, KEYPATH, DEFAULT_VALUE,\
+  IMPLIED_CHECK, IMPLIED_VALUE, DENORMALIZER, EXTRACTOR, TABLE_INDEX)
+#include "clang/Driver/Options.inc"
+#undef FILE_SYSTEM_OPTION_WITH_MARSHALLING
+}
+
+static bool ParseFileSystemArgs(FileSystemOptions &FileSystemOpts,
+const ArgList &Args, DiagnosticsEngine &Diags) {
   bool Success = true;
 
-#define OPTION_WITH_MARSHALLING(   \
+#define FILE_SYSTEM_OPTION_WITH_MARSHALLING(   \
 PREFIX_TYPE, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM,\
 HELPTEXT, METAVAR, VALUES, SPELLING, SHOULD_PARSE, ALWAYS_EMIT, KEYPATH,   \
 DEFAULT_VALUE, IMPLIED_CHECK, IMPLIED_VALUE, NORMALIZER, DENORMALIZER, \
 MERGER, EXTRACTOR, TABLE_INDEX)\
   PARSE_OPTION_WITH_MARSHALLING(Args, Diags, Success, ID, FLAGS, PARAM,\
-SHOULD_PARSE, this->KEYPATH, DEFAULT_VALUE,\
+SHOULD_PARSE, KEYPATH, DEFAULT_VALUE,  \
 IMPLIED_CHECK, IMPLIED_VALUE, NORMALIZER,  \
 MERGER, TABLE_INDEX)
 #include "clang/Driver/Options.inc"
-#undef OPTION_WITH_MARSHALLING
+#undef FILE_SYSTEM_OPTION_WITH_MARSHALLING
+
+  return Success;
+}
+
+static void GenerateMigratorArgs(const MigratorOptions &MigratorOpts,
+ SmallVectorImpl &Args,
+ CompilerInvocation::StringAllocator SA) {
+#define MIGRATOR_OPTION_WITH_MARSHALLING(  \
+PREFIX_TYPE, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM,\
+HELPTEXT, METAVAR, VALUES, SPELLING, SHOULD_PARSE, ALWAYS_EMIT, KEYPATH,   \
+DEFAULT_VALUE, IMPLIED_CHECK, IMPLIED_VALUE, NORMALIZER, DENORMALIZER, \
+MERGER, EXTRACTOR, TABLE_INDEX)\
+  GENERATE_OPTION_WITH_MARSHALLING(\
+  Args, SA, KIND, FLAGS, SPELLING, ALWAYS_EMIT, KEYPATH, DEFAULT_VALUE,\
+  IMPLIED_CHECK, IMPLIED_VALUE, DENORMALIZER, EXTRACTOR, TABLE_INDEX)
+#include "clang/Driver/Options.inc"
+#undef MIGRATOR_OPTION_WITH_MARSHALLING
+}
+
+static bool ParseMigratorArgs(MigratorOptions &MigratorOpts,
+  const ArgList &Args, DiagnosticsEngine &Diags) {
+  bool Success = true;
+
+#define MIGRATOR_OPTION_WITH_MARSHALLING(  \
+PREFIX_TYPE, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM,\
+HELPTEXT, METAVAR, VALUES, SPELLING, SHOULD_PARSE, ALWAYS_EMIT, KEYPATH,   \
+DEFAULT_VALUE, IMPLIED_CHECK, IMPLIED_VALUE, NORMALIZER, DENORMALIZER, \
+MERGER, EXTRACTOR, TABLE_INDEX)\
+  PARSE_OPTION_WITH_MARSHALLING(Args, Diags, Success

[PATCH] D96270: [release][docs] Update contributions to LLVM 12 for scalable vectors.

2021-02-08 Thread Sander de Smalen via Phabricator via cfe-commits
sdesmalen added inline comments.



Comment at: clang/docs/ReleaseNotes.rst:153
+  compiler should use fixed-width or scalable vectorization.  Fixed-width is
+  assumed by default.  Scalable vectorization is an experimental feature for
+  targets that support it, such as Arm targets that support the Scalable Vector

nit: insert empty line here.



Comment at: clang/docs/ReleaseNotes.rst:153
+  compiler should use fixed-width or scalable vectorization.  Fixed-width is
+  assumed by default.  Scalable vectorization is an experimental feature for
+  targets that support it, such as Arm targets that support the Scalable Vector

sdesmalen wrote:
> nit: insert empty line here.
nit: s/Scalable/Scalable or Vector length agnostic/



Comment at: clang/docs/ReleaseNotes.rst:154-155
+  assumed by default.  Scalable vectorization is an experimental feature for
+  targets that support it, such as Arm targets that support the Scalable Vector
+  Extension (SVE) feature. For more information please refer to the
+  Clang Language Extensions documentation.

nit: s/it, [...] feature./scalable vectors./


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D96270

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


[PATCH] D96274: [clang][cli] Generate and round-trip Diagnostic options

2021-02-08 Thread Jan Svoboda via Phabricator via cfe-commits
jansvoboda11 created this revision.
jansvoboda11 added reviewers: Bigcheese, dexonsmith.
Herald added a subscriber: dang.
jansvoboda11 requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

This patch implements generation of remaining diagnostic options and tests it 
by performing parse-generate-parse round trip.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D96274

Files:
  clang/include/clang/Basic/DiagnosticOptions.h
  clang/include/clang/Driver/Options.td
  clang/include/clang/Frontend/CompilerInvocation.h
  clang/lib/Frontend/CompilerInvocation.cpp

Index: clang/lib/Frontend/CompilerInvocation.cpp
===
--- clang/lib/Frontend/CompilerInvocation.cpp
+++ clang/lib/Frontend/CompilerInvocation.cpp
@@ -722,7 +722,10 @@
 
 static void addDiagnosticArgs(ArgList &Args, OptSpecifier Group,
   OptSpecifier GroupWithValue,
-  std::vector &Diagnostics) {
+  std::vector &Diagnostics,
+  std::vector &DiagnosticsAsWritten) {
+  ArgStringList Rendered;
+
   for (auto *A : Args.filtered(Group)) {
 if (A->getOption().getKind() == Option::FlagClass) {
   // The argument is a pure flag (such as OPT_Wall or OPT_Wdeprecated). Add
@@ -738,7 +741,13 @@
   for (const auto *Arg : A->getValues())
 Diagnostics.emplace_back(Arg);
 }
+
+A->render(Args, Rendered);
   }
+
+  DiagnosticsAsWritten.reserve(Rendered.size());
+  for (const char *Arg : Rendered)
+DiagnosticsAsWritten.emplace_back(Arg);
 }
 
 // Parse the Static Analyzer configuration. If \p Diags is set to nullptr,
@@ -2169,6 +2178,68 @@
   return Success;
 }
 
+void CompilerInvocation::GenerateDiagnosticArgs(
+const DiagnosticOptions &Opts, SmallVectorImpl &Args,
+StringAllocator SA, bool DefaultDiagColor) {
+  const DiagnosticOptions *DiagnosticOpts = &Opts;
+#define DIAG_OPTION_WITH_MARSHALLING(  \
+PREFIX_TYPE, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM,\
+HELPTEXT, METAVAR, VALUES, SPELLING, SHOULD_PARSE, ALWAYS_EMIT, KEYPATH,   \
+DEFAULT_VALUE, IMPLIED_CHECK, IMPLIED_VALUE, NORMALIZER, DENORMALIZER, \
+MERGER, EXTRACTOR, TABLE_INDEX)\
+  GENERATE_OPTION_WITH_MARSHALLING(\
+  Args, SA, KIND, FLAGS, SPELLING, ALWAYS_EMIT, KEYPATH, DEFAULT_VALUE,\
+  IMPLIED_CHECK, IMPLIED_VALUE, DENORMALIZER, EXTRACTOR, TABLE_INDEX)
+#include "clang/Driver/Options.inc"
+#undef DIAG_OPTION_WITH_MARSHALLING
+
+  if (!Opts.DiagnosticSerializationFile.empty())
+GenerateArg(Args, OPT_diagnostic_serialized_file,
+Opts.DiagnosticSerializationFile, SA);
+
+  if (Opts.ShowColors)
+GenerateArg(Args, OPT_fcolor_diagnostics, SA);
+
+  if (Opts.CLFallbackMode)
+GenerateArg(Args, OPT_fdiagnostics_format, "msvc-fallback", SA);
+
+  if (Opts.VerifyDiagnostics &&
+  llvm::is_contained(Opts.VerifyPrefixes, "expected"))
+GenerateArg(Args, OPT_verify, SA);
+
+  for (const auto &Prefix : Opts.VerifyPrefixes)
+if (Prefix != "expected")
+  GenerateArg(Args, OPT_verify_EQ, Prefix, SA);
+
+  DiagnosticLevelMask VIU = Opts.getVerifyIgnoreUnexpected();
+  if (VIU == DiagnosticLevelMask::None) {
+// This is the default, don't generate anything.
+  } else if (VIU == DiagnosticLevelMask::All) {
+GenerateArg(Args, OPT_verify_ignore_unexpected, SA);
+  } else {
+if (static_cast(VIU & DiagnosticLevelMask::Note) != 0)
+  GenerateArg(Args, OPT_verify_ignore_unexpected_EQ, "note", SA);
+if (static_cast(VIU & DiagnosticLevelMask::Remark) != 0)
+  GenerateArg(Args, OPT_verify_ignore_unexpected_EQ, "remark", SA);
+if (static_cast(VIU & DiagnosticLevelMask::Warning) != 0)
+  GenerateArg(Args, OPT_verify_ignore_unexpected_EQ, "warning", SA);
+if (static_cast(VIU & DiagnosticLevelMask::Error) != 0)
+  GenerateArg(Args, OPT_verify_ignore_unexpected_EQ, "error", SA);
+  }
+
+  for (const auto &Warning : Opts.WarningsAsWritten) {
+// This option also maps to UndefPrefixes that generates it automatically.
+if (StringRef(Warning).startswith("-Wundef-prefix="))
+  continue;
+// TODO: Consider ignoring '-Wno-rewrite-macros' that maps to
+// NoRewriteMacros.
+Args.push_back(SA(Warning));
+  }
+
+  for (const auto &Remark : Opts.RemarksAsWritten)
+Args.push_back(SA(Remark));
+}
+
 bool clang::ParseDiagnosticArgs(DiagnosticOptions &Opts, ArgList &Args,
 DiagnosticsEngine *Diags,
 bool DefaultDiagColor) {
@@ -2207,6 +2278,7 @@
 Opts.CLFallbackMode = true;
 
   Opts.VerifyDiagnostics = Args.hasArg(OPT_verify) || Args.hasArg(OPT_verify_EQ);
+  Opts.VerifyPrefixes = Args.getAllArgValues(OPT_verify_EQ);
  

[PATCH] D86376: [HIP] Simplify kernel launching

2021-02-08 Thread Yaxun Liu via Phabricator via cfe-commits
yaxunl added a comment.

In D86376#2239618 , @tra wrote:

> In D86376#2239391 , @yaxunl wrote:
>
>> For example, in HIP program, there is a kernel `void foo(int*)`. If a C++ 
>> program wants to launch it, the desirable way is
>>
>>   void foo(int*);
>>   hipLaunchKernel(foo, grids, blocks, args, shmem, stream);
>>
>> Due to the prefixed kernel stub name, currently the users have to use
>>
>>   void __device_stub_foo(int*);
>>   hipLaunchKernel(__device_stub_foo, grids, blocks, args, shmem, stream);
>
> Ah. That *is* painful. Perhaps we can have the cake and eat it here and do 
> something like this:
>
> Do generate a variable with the kernel name and use it for hipKernelLaunch(), 
> but also keep the stub and call it for `<<<>>>` launches, only instead of 
> using the stub itself registered as the GPU-side kernel identifier, use the 
> variable.
>
> This way, __device_stub_ will show up in the stack trace (no 
> debuggability regression), but direct calls to hipLaunchKenrel can use 
> unprefixed kernel name.
>
> WDYT?

Yes that should work. Will do.


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

https://reviews.llvm.org/D86376

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


[PATCH] D95714: [clang-tidy] fix modernize-use-nullptr false positive with spaceship operator comparisons

2021-02-08 Thread Nathan James via Phabricator via cfe-commits
njames93 added a comment.

I'm unable to cleanly apply this patch, looks like something was a bit off when 
you created the diff.

  ➜  llvm-project git:(main) ✗ arc patch D95714   
   INFO  Base commit is not in local repository; trying to fetch.
  Created and checked out branch arcpatch-D95714.
  Checking patch dev/null => 
clang-tools-extra/test/clang-tidy/checkers/modernize-use-nullptr-cxx20.cpp...
  error: dev/null: does not exist in index
  Checking patch clang-tools-extra/clang-tidy/modernize/UseNullptrCheck.cpp...
  Applied patch clang-tools-extra/clang-tidy/modernize/UseNullptrCheck.cpp 
cleanly.
  
   Patch Failed! 
  Usage Exception: Unable to apply patch!
  ➜  llvm-project git:(arcpatch-D95714) ✗ 

Can you try to reupload the diff, making sure you use full context as well.


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

https://reviews.llvm.org/D95714

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


[PATCH] D96273: [clang][cli] Generate and round-trip DependencyOutput options

2021-02-08 Thread Jan Svoboda via Phabricator via cfe-commits
jansvoboda11 created this revision.
jansvoboda11 added reviewers: Bigcheese, dexonsmith.
Herald added a subscriber: dang.
jansvoboda11 requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

This patch implements generation of remaining dependency output options and 
tests it by performing parse-generate-parse round trip.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D96273

Files:
  clang/include/clang/Driver/Options.td
  clang/include/clang/Frontend/DependencyOutputOptions.h
  clang/lib/Frontend/CompilerInvocation.cpp
  clang/lib/Frontend/DependencyFile.cpp
  clang/lib/Frontend/HeaderIncludeGen.cpp

Index: clang/lib/Frontend/HeaderIncludeGen.cpp
===
--- clang/lib/Frontend/HeaderIncludeGen.cpp
+++ clang/lib/Frontend/HeaderIncludeGen.cpp
@@ -119,7 +119,7 @@
   // as sanitizer blacklists. It's only important for cl.exe compatibility,
   // the GNU way to generate rules is -M / -MM / -MD / -MMD.
   for (const auto &Header : DepOpts.ExtraDeps)
-PrintHeaderInfo(OutputFile, Header, ShowDepth, 2, MSStyle);
+PrintHeaderInfo(OutputFile, Header.first, ShowDepth, 2, MSStyle);
   PP.addPPCallbacks(std::make_unique(
   &PP, ShowAllHeaders, OutputFile, DepOpts, OwnsOutputFile, ShowDepth,
   MSStyle));
Index: clang/lib/Frontend/DependencyFile.cpp
===
--- clang/lib/Frontend/DependencyFile.cpp
+++ clang/lib/Frontend/DependencyFile.cpp
@@ -182,7 +182,7 @@
   IncludeModuleFiles(Opts.IncludeModuleFiles),
   OutputFormat(Opts.OutputFormat), InputFileIndex(0) {
   for (const auto &ExtraDep : Opts.ExtraDeps) {
-if (addDependency(ExtraDep))
+if (addDependency(ExtraDep.first))
   ++InputFileIndex;
   }
 }
Index: clang/lib/Frontend/CompilerInvocation.cpp
===
--- clang/lib/Frontend/CompilerInvocation.cpp
+++ clang/lib/Frontend/CompilerInvocation.cpp
@@ -1942,19 +1942,76 @@
   Res, Args, Diags, "CodeGenOptions");
 }
 
-static void ParseDependencyOutputArgs(DependencyOutputOptions &Opts,
-  ArgList &Args) {
+static void
+GenerateDependencyOutputArgs(const DependencyOutputOptions &Opts,
+ SmallVectorImpl &Args,
+ CompilerInvocation::StringAllocator SA) {
+  const DependencyOutputOptions &DependencyOutputOpts = Opts;
+#define DEPENDENCY_OUTPUT_OPTION_WITH_MARSHALLING( \
+PREFIX_TYPE, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM,\
+HELPTEXT, METAVAR, VALUES, SPELLING, SHOULD_PARSE, ALWAYS_EMIT, KEYPATH,   \
+DEFAULT_VALUE, IMPLIED_CHECK, IMPLIED_VALUE, NORMALIZER, DENORMALIZER, \
+MERGER, EXTRACTOR, TABLE_INDEX)\
+  GENERATE_OPTION_WITH_MARSHALLING(\
+  Args, SA, KIND, FLAGS, SPELLING, ALWAYS_EMIT, KEYPATH, DEFAULT_VALUE,\
+  IMPLIED_CHECK, IMPLIED_VALUE, DENORMALIZER, EXTRACTOR, TABLE_INDEX)
+#include "clang/Driver/Options.inc"
+#undef DEPENDENCY_OUTPUT_OPTION_WITH_MARSHALLING
+
+  if (Opts.ShowIncludesDest != ShowIncludesDestination::None)
+GenerateArg(Args, OPT_show_includes, SA);
+
+  for (const auto &Dep : Opts.ExtraDeps) {
+switch (Dep.second) {
+case EDK_SanitizeBlacklist:
+  // Sanitizer blacklist arguments are generated from LanguageOptions.
+  continue;
+case EDK_ModuleFile:
+  // Module file arguments are generated from FrontendOptions and
+  // HeaderSearchOptions.
+  continue;
+case EDK_ProfileList:
+  GenerateArg(Args, OPT_fprofile_list_EQ, Dep.first, SA);
+  break;
+case EDK_DepFileEntry:
+  GenerateArg(Args, OPT_fdepfile_entry, Dep.first, SA);
+  break;
+}
+  }
+}
+
+static bool ParseDependencyOutputArgsImpl(
+DependencyOutputOptions &Opts, ArgList &Args,
+DiagnosticsEngine &Diags,
+frontend::ActionKind Action, bool ShowLineMarkers) {
+  unsigned NumErrorsBefore = Diags.getNumErrors();
+  bool Success = true;
+
+  DependencyOutputOptions &DependencyOutputOpts = Opts;
+#define DEPENDENCY_OUTPUT_OPTION_WITH_MARSHALLING( \
+PREFIX_TYPE, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM,\
+HELPTEXT, METAVAR, VALUES, SPELLING, SHOULD_PARSE, ALWAYS_EMIT, KEYPATH,   \
+DEFAULT_VALUE, IMPLIED_CHECK, IMPLIED_VALUE, NORMALIZER, DENORMALIZER, \
+MERGER, EXTRACTOR, TABLE_INDEX)\
+  PARSE_OPTION_WITH_MARSHALLING(Args, Diags, Success, ID, FLAGS, PARAM,\
+SHOULD_PARSE, KEYPATH, DEFAULT_VALUE,  \
+IMPLIED_CHECK, IMPLIED_VALUE, NORMALIZER,  \
+MERGER, TABLE_INDEX)
+#include "clang/Driver/Options.in

[PATCH] D96158: [clang][cli] Generate and round-trip Target options

2021-02-08 Thread Jan Svoboda via Phabricator via cfe-commits
jansvoboda11 updated this revision to Diff 322128.
jansvoboda11 added a comment.

Switch to static functions


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D96158

Files:
  clang/include/clang/Driver/Options.td
  clang/lib/Frontend/CompilerInvocation.cpp

Index: clang/lib/Frontend/CompilerInvocation.cpp
===
--- clang/lib/Frontend/CompilerInvocation.cpp
+++ clang/lib/Frontend/CompilerInvocation.cpp
@@ -4167,8 +4167,44 @@
   Res, Args, Diags, "PreprocessorOutputOptions");
 }
 
-static void ParseTargetArgs(TargetOptions &Opts, ArgList &Args,
-DiagnosticsEngine &Diags) {
+static void GenerateTargetArgs(const TargetOptions &Opts,
+   SmallVectorImpl &Args,
+   CompilerInvocation::StringAllocator SA) {
+  const TargetOptions *TargetOpts = &Opts;
+#define TARGET_OPTION_WITH_MARSHALLING(\
+PREFIX_TYPE, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM,\
+HELPTEXT, METAVAR, VALUES, SPELLING, SHOULD_PARSE, ALWAYS_EMIT, KEYPATH,   \
+DEFAULT_VALUE, IMPLIED_CHECK, IMPLIED_VALUE, NORMALIZER, DENORMALIZER, \
+MERGER, EXTRACTOR, TABLE_INDEX)\
+  GENERATE_OPTION_WITH_MARSHALLING(\
+  Args, SA, KIND, FLAGS, SPELLING, ALWAYS_EMIT, KEYPATH, DEFAULT_VALUE,\
+  IMPLIED_CHECK, IMPLIED_VALUE, DENORMALIZER, EXTRACTOR, TABLE_INDEX)
+#include "clang/Driver/Options.inc"
+#undef TARGET_OPTION_WITH_MARSHALLING
+
+  if (!Opts.SDKVersion.empty())
+GenerateArg(Args, OPT_target_sdk_version_EQ, Opts.SDKVersion.getAsString(),
+SA);
+}
+
+static bool ParseTargetArgsImpl(TargetOptions &Opts, ArgList &Args,
+DiagnosticsEngine &Diags) {
+  TargetOptions *TargetOpts = &Opts;
+  unsigned NumErrorsBefore = Diags.getNumErrors();
+  bool Success = true;
+
+#define TARGET_OPTION_WITH_MARSHALLING(\
+PREFIX_TYPE, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM,\
+HELPTEXT, METAVAR, VALUES, SPELLING, SHOULD_PARSE, ALWAYS_EMIT, KEYPATH,   \
+DEFAULT_VALUE, IMPLIED_CHECK, IMPLIED_VALUE, NORMALIZER, DENORMALIZER, \
+MERGER, EXTRACTOR, TABLE_INDEX)\
+  PARSE_OPTION_WITH_MARSHALLING(Args, Diags, Success, ID, FLAGS, PARAM,\
+SHOULD_PARSE, KEYPATH, DEFAULT_VALUE,  \
+IMPLIED_CHECK, IMPLIED_VALUE, NORMALIZER,  \
+MERGER, TABLE_INDEX)
+#include "clang/Driver/Options.inc"
+#undef TARGET_OPTION_WITH_MARSHALLING
+
   if (Arg *A = Args.getLastArg(options::OPT_target_sdk_version_EQ)) {
 llvm::VersionTuple Version;
 if (Version.tryParse(A->getValue()))
@@ -4177,6 +4213,27 @@
 else
   Opts.SDKVersion = Version;
   }
+
+  return Success && Diags.getNumErrors() == NumErrorsBefore;
+}
+
+static bool ParseTargetArgs(CompilerInvocation &Res, TargetOptions &Opts,
+ArgList &Args, DiagnosticsEngine &Diags) {
+  auto DummyOpts = std::make_shared();
+
+  return RoundTrip(
+  [](CompilerInvocation &Res, ArgList &Args,
+DiagnosticsEngine &Diags) {
+return ParseTargetArgsImpl(Res.getTargetOpts(), Args, Diags);
+  },
+  [](CompilerInvocation &Res, SmallVectorImpl &GeneratedArgs,
+ CompilerInvocation::StringAllocator SA) {
+GenerateTargetArgs(Res.getTargetOpts(), GeneratedArgs, SA);
+  },
+  [&DummyOpts](CompilerInvocation &Res) {
+Res.TargetOpts.swap(DummyOpts);
+  },
+  Res, Args, Diags, "TargetArgs");
 }
 
 bool CompilerInvocation::CreateFromArgs(CompilerInvocation &Res,
@@ -4227,7 +4284,7 @@
LangOpts.IsHeaderFile);
   // FIXME: We shouldn't have to pass the DashX option around here
   InputKind DashX = Res.getFrontendOpts().DashX;
-  ParseTargetArgs(Res.getTargetOpts(), Args, Diags);
+  ParseTargetArgs(Res, Res.getTargetOpts(), Args, Diags);
   llvm::Triple T(Res.getTargetOpts().Triple);
   ParseHeaderSearchArgs(Res, Res.getHeaderSearchOpts(), Args, Diags,
 Res.getFileSystemOpts().WorkingDir);
@@ -,6 +4501,7 @@
 
   GenerateAnalyzerArgs(*AnalyzerOpts, Args, SA);
   GenerateFrontendArgs(FrontendOpts, Args, SA, LangOpts->IsHeaderFile);
+  GenerateTargetArgs(*TargetOpts, Args, SA);
   GenerateHeaderSearchArgs(*HeaderSearchOpts, Args, SA);
   GenerateLangArgs(*LangOpts, Args, SA,  T);
   GenerateCodeGenArgs(CodeGenOpts, Args, SA, T, FrontendOpts.OutputFile,
Index: clang/include/clang/Driver/Options.td
===
--- clang/include/clang/Driver/Options.td
+++ clang/in

[PATCH] D96231: [X86] Always assign reassoc flag for intrinsics *reduce_add/mul_ps/pd.

2021-02-08 Thread Sanjay Patel via Phabricator via cfe-commits
spatel added inline comments.



Comment at: clang/lib/Headers/avx512fintrin.h:9352
 static __inline__ double __DEFAULT_FN_ATTRS512 _mm512_reduce_add_pd(__m512d 
__W) {
   return __builtin_ia32_reduce_fadd_pd512(0.0, __W);
 }

Ah - this is where the +0.0 is specified. This should be -0.0. We could still 
add 'nsz' flag to be safe.



Comment at: clang/lib/Headers/avx512fintrin.h:9362
   __W = _mm512_maskz_mov_pd(__M, __W);
   return __builtin_ia32_reduce_fadd_pd512(0.0, __W);
 }

This also should be changed to -0.0?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D96231

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


[PATCH] D96270: [release][docs] Update contributions to LLVM 12 for scalable vectors.

2021-02-08 Thread David Sherwood via Phabricator via cfe-commits
david-arm created this revision.
david-arm added reviewers: sdesmalen, willlovett, c-rhodes.
david-arm requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D96270

Files:
  clang/docs/ReleaseNotes.rst


Index: clang/docs/ReleaseNotes.rst
===
--- clang/docs/ReleaseNotes.rst
+++ clang/docs/ReleaseNotes.rst
@@ -144,6 +144,17 @@
 
 - ...
 
+Modified Pragmas in Clang
+-
+
+- The #pragma "clang loop vectorize_width" has been extended to support an
+  optional 'fixed|scalable' argument, which can be used to indicate that the
+  compiler should use fixed-width or scalable vectorization.  Fixed-width is
+  assumed by default.  Scalable vectorization is an experimental feature for
+  targets that support it, such as Arm targets that support the Scalable Vector
+  Extension (SVE) feature. For more information please refer to the
+  Clang Language Extensions documentation.
+
 Attribute Changes in Clang
 --
 


Index: clang/docs/ReleaseNotes.rst
===
--- clang/docs/ReleaseNotes.rst
+++ clang/docs/ReleaseNotes.rst
@@ -144,6 +144,17 @@
 
 - ...
 
+Modified Pragmas in Clang
+-
+
+- The #pragma "clang loop vectorize_width" has been extended to support an
+  optional 'fixed|scalable' argument, which can be used to indicate that the
+  compiler should use fixed-width or scalable vectorization.  Fixed-width is
+  assumed by default.  Scalable vectorization is an experimental feature for
+  targets that support it, such as Arm targets that support the Scalable Vector
+  Extension (SVE) feature. For more information please refer to the
+  Clang Language Extensions documentation.
+
 Attribute Changes in Clang
 --
 
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D93769: [clang] Add support for option -ffp-eval-method and extend #pragma float_control similarly

2021-02-08 Thread Melanie Blower via Phabricator via cfe-commits
mibintc added inline comments.



Comment at: clang/docs/LanguageExtensions.rst:3363
+
+When ``pragma float_control(source, off)`` or
+``pragma float_control(double, off)`` or

I'd like to add Intel ICL compatible syntax, but 'off' doesn't make too much 
sense to me. In the Intel compiler using'off' requires both 
ffp-exception-behavior to be ignore, and FENV_ACCESS to be off.  If that's true 
then setting float_control(source|double|extended, off) is allowable and the 
semantics of float evaluation method set to a 4th level "float eval fast" which 
is loosely described in the commentary as "don't care".  Ideally "float eval 
fast" would deliver the same results, in this context, as Microsoft's fp:fast 
command line option. I could make "off" an illegal setting, or warn that it's 
ignored. @andrew.w.kaylor  do you have any input here?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D93769

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


[PATCH] D96156: [clang][cli] Generate and round-trip PreprocessorOutput options

2021-02-08 Thread Jan Svoboda via Phabricator via cfe-commits
jansvoboda11 updated this revision to Diff 322124.
jansvoboda11 added a comment.

Switch from member functions to static ones


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D96156

Files:
  clang/include/clang/Driver/Options.td
  clang/lib/Frontend/CompilerInvocation.cpp

Index: clang/lib/Frontend/CompilerInvocation.cpp
===
--- clang/lib/Frontend/CompilerInvocation.cpp
+++ clang/lib/Frontend/CompilerInvocation.cpp
@@ -4095,15 +4095,76 @@
"PreprocessorOptions");
 }
 
-static void ParsePreprocessorOutputArgs(PreprocessorOutputOptions &Opts,
-ArgList &Args,
-frontend::ActionKind Action) {
-  if (isStrictlyPreprocessorAction(Action))
-Opts.ShowCPP = !Args.hasArg(OPT_dM);
-  else
-Opts.ShowCPP = 0;
+static void GeneratePreprocessorOutputArgs(
+const PreprocessorOutputOptions &Opts, SmallVectorImpl &Args,
+CompilerInvocation::StringAllocator SA, frontend::ActionKind Action) {
+  const PreprocessorOutputOptions &PreprocessorOutputOpts = Opts;
+
+#define PREPROCESSOR_OUTPUT_OPTION_WITH_MARSHALLING(   \
+PREFIX_TYPE, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM,\
+HELPTEXT, METAVAR, VALUES, SPELLING, SHOULD_PARSE, ALWAYS_EMIT, KEYPATH,   \
+DEFAULT_VALUE, IMPLIED_CHECK, IMPLIED_VALUE, NORMALIZER, DENORMALIZER, \
+MERGER, EXTRACTOR, TABLE_INDEX)\
+  GENERATE_OPTION_WITH_MARSHALLING(\
+  Args, SA, KIND, FLAGS, SPELLING, ALWAYS_EMIT, KEYPATH, DEFAULT_VALUE,\
+  IMPLIED_CHECK, IMPLIED_VALUE, DENORMALIZER, EXTRACTOR, TABLE_INDEX)
+#include "clang/Driver/Options.inc"
+#undef PREPROCESSOR_OUTPUT_OPTION_WITH_MARSHALLING
+
+  bool Generate_dM = isStrictlyPreprocessorAction(Action) && !Opts.ShowCPP;
+  if (Generate_dM)
+GenerateArg(Args, OPT_dM, SA);
+  if (!Generate_dM && Opts.ShowMacros)
+GenerateArg(Args, OPT_dD, SA);
+}
+
+static bool ParsePreprocessorOutputArgsImpl(PreprocessorOutputOptions &Opts,
+ArgList &Args,
+DiagnosticsEngine &Diags,
+frontend::ActionKind Action) {
+  PreprocessorOutputOptions &PreprocessorOutputOpts = Opts;
+  unsigned NumErrorsBefore = Diags.getNumErrors();
+  bool Success = true;
+
+#define PREPROCESSOR_OUTPUT_OPTION_WITH_MARSHALLING(   \
+PREFIX_TYPE, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM,\
+HELPTEXT, METAVAR, VALUES, SPELLING, SHOULD_PARSE, ALWAYS_EMIT, KEYPATH,   \
+DEFAULT_VALUE, IMPLIED_CHECK, IMPLIED_VALUE, NORMALIZER, DENORMALIZER, \
+MERGER, EXTRACTOR, TABLE_INDEX)\
+  PARSE_OPTION_WITH_MARSHALLING(Args, Diags, Success, ID, FLAGS, PARAM,\
+SHOULD_PARSE, KEYPATH, DEFAULT_VALUE,  \
+IMPLIED_CHECK, IMPLIED_VALUE, NORMALIZER,  \
+MERGER, TABLE_INDEX)
+#include "clang/Driver/Options.inc"
+#undef PREPROCESSOR_OUTPUT_OPTION_WITH_MARSHALLING
 
+  Opts.ShowCPP = isStrictlyPreprocessorAction(Action) && !Args.hasArg(OPT_dM);
   Opts.ShowMacros = Args.hasArg(OPT_dM) || Args.hasArg(OPT_dD);
+
+  return Success && Diags.getNumErrors() == NumErrorsBefore;
+}
+
+static bool ParsePreprocessorOutputArgs(CompilerInvocation &Res,
+PreprocessorOutputOptions &Opts,
+ArgList &Args, DiagnosticsEngine &Diags,
+frontend::ActionKind Action) {
+  PreprocessorOutputOptions DummyOpts;
+
+  return RoundTrip(
+  [Action](CompilerInvocation &Res, ArgList &Args,
+   DiagnosticsEngine &Diags) {
+return ParsePreprocessorOutputArgsImpl(Res.getPreprocessorOutputOpts(),
+   Args, Diags, Action);
+  },
+  [Action](CompilerInvocation &Res, SmallVectorImpl &Args,
+   CompilerInvocation::StringAllocator SA) {
+GeneratePreprocessorOutputArgs(Res.getPreprocessorOutputOpts(), Args,
+   SA, Action);
+  },
+  [&DummyOpts](CompilerInvocation &Res) {
+std::swap(DummyOpts, Res.getPreprocessorOutputOpts());
+  },
+  Res, Args, Diags, "PreprocessorOutputOptions");
 }
 
 static void ParseTargetArgs(TargetOptions &Opts, ArgList &Args,
@@ -4224,7 +4285,7 @@
   ParsePreprocessorArgs(Res, Res.getPreprocessorOpts(), Args, Diags,
 Res.getFrontendOpts().ProgramAction,
 Res.getFrontendOpts());
-  ParsePreprocessorOutputArgs(Res.getPreprocessorOutputOp

[PATCH] D96051: [OpenCL] Support enum and typedef args in TableGen BIFs

2021-02-08 Thread Sven van Haastregt via Phabricator via cfe-commits
svenvh updated this revision to Diff 322123.
svenvh added a comment.

Do not assume cast to Enum/TypedefDecl is always successful.


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

https://reviews.llvm.org/D96051

Files:
  clang/include/clang/Basic/DiagnosticSemaKinds.td
  clang/lib/Sema/OpenCLBuiltins.td
  clang/lib/Sema/SemaLookup.cpp
  clang/test/SemaOpenCL/fdeclare-opencl-builtins.cl
  clang/utils/TableGen/ClangOpenCLBuiltinEmitter.cpp

Index: clang/utils/TableGen/ClangOpenCLBuiltinEmitter.cpp
===
--- clang/utils/TableGen/ClangOpenCLBuiltinEmitter.cpp
+++ clang/utils/TableGen/ClangOpenCLBuiltinEmitter.cpp
@@ -48,7 +48,7 @@
 //Find out whether a string matches an existing OpenCL builtin function
 //name and return an index into BuiltinTable and the number of overloads.
 //
-//  * void OCL2Qual(ASTContext&, OpenCLTypeStruct, std::vector&)
+//  * void OCL2Qual(Sema&, OpenCLTypeStruct, std::vector&)
 //Convert an OpenCLTypeStruct type to a list of QualType instances.
 //One OpenCLTypeStruct can represent multiple types, primarily when using
 //GenTypes.
@@ -715,6 +715,9 @@
 void BuiltinNameEmitter::EmitQualTypeFinder() {
   OS << R"(
 
+static QualType getOpenCLEnumType(Sema &S, llvm::StringRef Name);
+static QualType getOpenCLTypedefType(Sema &S, llvm::StringRef Name);
+
 // Convert an OpenCLTypeStruct type to a list of QualTypes.
 // Generic types represent multiple types and vector sizes, thus a vector
 // is returned. The conversion is done in two steps:
@@ -723,8 +726,9 @@
 // or a single scalar type for non generic types.
 // Step 2: Qualifiers and other type properties such as vector size are
 // applied.
-static void OCL2Qual(ASTContext &Context, const OpenCLTypeStruct &Ty,
+static void OCL2Qual(Sema &S, const OpenCLTypeStruct &Ty,
  llvm::SmallVectorImpl &QT) {
+  ASTContext &Context = S.Context;
   // Number of scalar types in the GenType.
   unsigned GenTypeNumTypes;
   // Pointer to the list of vector sizes for the GenType.
Index: clang/test/SemaOpenCL/fdeclare-opencl-builtins.cl
===
--- clang/test/SemaOpenCL/fdeclare-opencl-builtins.cl
+++ clang/test/SemaOpenCL/fdeclare-opencl-builtins.cl
@@ -34,6 +34,9 @@
 typedef uint uint4 __attribute__((ext_vector_type(4)));
 typedef long long2 __attribute__((ext_vector_type(2)));
 
+typedef uint cl_mem_fence_flags;
+#define CLK_GLOBAL_MEM_FENCE 0x02
+
 // Enable extensions that are enabled in opencl-c-base.h.
 #if (defined(__OPENCL_CPP_VERSION__) || __OPENCL_C_VERSION__ >= 200)
 #define cl_khr_subgroup_ballot 1
@@ -52,6 +55,18 @@
   atom_cmpxchg((volatile __global unsigned int *)global_p, ui, ui);
 }
 
+// Only test enum arguments when the base header is included, because we need
+// the enum declarations.
+#if !defined(NO_HEADER) && (defined(__OPENCL_CPP_VERSION__) || __OPENCL_C_VERSION__ >= 200)
+kernel void test_enum_args(volatile global atomic_int *global_p, global int *expected) {
+  int desired;
+  atomic_compare_exchange_strong_explicit(global_p, expected, desired,
+  memory_order_acq_rel,
+  memory_order_relaxed,
+  memory_scope_work_group);
+}
+#endif
+
 kernel void basic_conversion() {
   double d;
   float f;
@@ -180,6 +195,8 @@
 kernel void basic_work_item() {
   uint ui;
 
+  barrier(CLK_GLOBAL_MEM_FENCE);
+
   get_enqueued_local_size(ui);
 #if !defined(__OPENCL_CPP_VERSION__) && __OPENCL_C_VERSION__ < CL_VERSION_2_0
 // expected-error@-2{{implicit declaration of function 'get_enqueued_local_size' is invalid in OpenCL}}
Index: clang/lib/Sema/SemaLookup.cpp
===
--- clang/lib/Sema/SemaLookup.cpp
+++ clang/lib/Sema/SemaLookup.cpp
@@ -677,9 +677,43 @@
 D->dump();
 }
 
+/// Diagnose a missing builtin type.
+static QualType diagOpenCLBuiltinTypeError(Sema &S, llvm::StringRef TypeClass,
+   llvm::StringRef Name) {
+  S.Diag(SourceLocation(), diag::err_opencl_type_not_found)
+  << TypeClass << Name;
+  return S.Context.VoidTy;
+}
+
+/// Lookup an OpenCL enum type.
+static QualType getOpenCLEnumType(Sema &S, llvm::StringRef Name) {
+  LookupResult Result(S, &S.Context.Idents.get(Name), SourceLocation(),
+  Sema::LookupTagName);
+  S.LookupName(Result, S.TUScope);
+  if (Result.empty())
+return diagOpenCLBuiltinTypeError(S, "enum", Name);
+  EnumDecl *Decl = Result.getAsSingle();
+  if (!Decl)
+return diagOpenCLBuiltinTypeError(S, "enum", Name);
+  return S.Context.getEnumType(Decl);
+}
+
+/// Lookup an OpenCL typedef type.
+static QualType getOpenCLTypedefType(Sema &S, llvm::StringRef Name) {
+  LookupResult Result(S, &S.Context.Idents.get(Name), SourceLocation(),
+  Sema::Looku

[PATCH] D96155: [clang][cli] Generate and round-trip Frontend options

2021-02-08 Thread Jan Svoboda via Phabricator via cfe-commits
jansvoboda11 added inline comments.



Comment at: clang/include/clang/Serialization/ModuleFileExtension.h:75
 
+  ModuleFileExtensionKind getKind() const { return Kind; }
+

I'm not sure what the best approach is here.

`ModuleFileExtension` is an abstract class. When parsing command line 
arguments, we may instantiate its (only) subclass `TestModuleFileExtension`.
To generate the argument, we can:
* Add a pure virtual function (e.g. `serialize`) to `ModuleFileExtension`, 
implement it in `TestModuleFileExtension` and use that in the generator. I'm 
not sure if introducing the concept of command line and serialization into 
argument makes sense. For clients subclassing `ModuleFileExtension`, 
serialization might not make sense.
* (The current approach): Add LLVM-style RTTI to the whole hierarchy, and only 
handle `TestModuleFileExtension` in the generator by invoking its (non-virtual) 
`serialize`.

WDYT would be the best approach here?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D96155

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


[PATCH] D95714: [clang-tidy] fix modernize-use-nullptr false positive with spaceship operator comparisons

2021-02-08 Thread Conrad Poelman via Phabricator via cfe-commits
poelmanc added a comment.

In D95714#2548735 , @njames93 wrote:

> LGTM, Same as last time for the commit?

That would be great, thanks!


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

https://reviews.llvm.org/D95714

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


[PATCH] D96231: [X86] Always assign reassoc flag for intrinsics *reduce_add/mul_ps/pd.

2021-02-08 Thread Sanjay Patel via Phabricator via cfe-commits
spatel added inline comments.



Comment at: clang/lib/CodeGen/CGBuiltin.cpp:13829
 CGM.getIntrinsic(Intrinsic::vector_reduce_fadd, Ops[1]->getType());
+Builder.getFastMathFlags().setAllowReassoc(true);
 return Builder.CreateCall(F, {Ops[0], Ops[1]});

I haven't looked at this part of the compiler in a long time, so I was 
wondering how we handle FMF scope. It looks like there is already an FMFGuard 
object in place -- CodeGenFunction::CGFPOptionsRAII(). So setting FMF here will 
not affect anything but this CreateCall(). 

Does that match your understanding? Should we have an extra regression test to 
make sure that does not change?

I am imagining something like:

```
double test_mm512_reduce_add_pd(__m512d __W, double ExtraAddOp) {
  double S = _mm512_reduce_add_pd(__W) + ExtraAddOp;
  return S;
}

```

Then we could confirm that `reassoc` is not applied to the `fadd` that follows 
the reduction call.



Comment at: clang/lib/CodeGen/CGBuiltin.cpp:13829
 CGM.getIntrinsic(Intrinsic::vector_reduce_fadd, Ops[1]->getType());
+Builder.getFastMathFlags().setAllowReassoc(true);
 return Builder.CreateCall(F, {Ops[0], Ops[1]});

spatel wrote:
> I haven't looked at this part of the compiler in a long time, so I was 
> wondering how we handle FMF scope. It looks like there is already an FMFGuard 
> object in place -- CodeGenFunction::CGFPOptionsRAII(). So setting FMF here 
> will not affect anything but this CreateCall(). 
> 
> Does that match your understanding? Should we have an extra regression test 
> to make sure that does not change?
> 
> I am imagining something like:
> 
> ```
> double test_mm512_reduce_add_pd(__m512d __W, double ExtraAddOp) {
>   double S = _mm512_reduce_add_pd(__W) + ExtraAddOp;
>   return S;
> }
> 
> ```
> 
> Then we could confirm that `reassoc` is not applied to the `fadd` that 
> follows the reduction call.
Currently (and we could say that this is an LLVM codegen bug), we will not 
generate the optimal/expected reduction with `reassoc` alone.

I think the x86 reduction definition is implicitly assuming that -0.0 is not 
meaningful here, so we should add `nsz` too.

The backend is expecting an explicit `nsz` on this op. Ie, I see this x86 asm 
currently with only `reassoc`:

```
vextractf64x4   $1, %zmm0, %ymm1
vaddpd  %zmm1, %zmm0, %zmm0
vextractf128$1, %ymm0, %xmm1
vaddpd  %xmm1, %xmm0, %xmm0
vpermilpd   $1, %xmm0, %xmm1  
vaddsd  %xmm1, %xmm0, %xmm0 
vxorpd  %xmm1, %xmm1, %xmm1   <--- create 0.0
vaddsd  %xmm1, %xmm0, %xmm0   <--- add it to the reduction result
```

Alternatively (and I'm not sure where it is specified), we could replace the 
default 0.0 argument with -0.0?



Comment at: clang/lib/Headers/avx512fintrin.h:9300
  * outputs. This class of vector operation forms the basis of many scientific
  * computations. In vector-reduction arithmetic, the evaluation off is
  * independent of the order of the input elements of V.

This is an existing text bug, but if we are changing this text, we might as 
well fix it in this patch - I'm not sure what "off" refers to here. Should that 
be "order"?



Comment at: clang/lib/Headers/avx512fintrin.h:9303
 
+ * For floating points type, we always assume the elements are reassociable 
even
+ * if -fast-math is off.

Typo: "floating-point types"



Comment at: clang/lib/Headers/avx512fintrin.h:9304
+ * For floating points type, we always assume the elements are reassociable 
even
+ * if -fast-math is off.
+

Also mention that sign of zero is indeterminate. We might use the LangRef text 
as a model for what to say here:
https://llvm.org/docs/LangRef.html#llvm-vector-reduce-fadd-intrinsic


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D96231

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


[PATCH] D96155: [clang][cli] Generate and round-trip Frontend options

2021-02-08 Thread Jan Svoboda via Phabricator via cfe-commits
jansvoboda11 updated this revision to Diff 322121.
jansvoboda11 added a comment.

Fix whitespace


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D96155

Files:
  clang/include/clang/Driver/Options.td
  clang/include/clang/Frontend/CommandLineSourceLoc.h
  clang/include/clang/Serialization/ModuleFileExtension.h
  clang/lib/Frontend/CompilerInvocation.cpp
  clang/lib/Frontend/TestModuleFileExtension.cpp
  clang/lib/Frontend/TestModuleFileExtension.h

Index: clang/lib/Frontend/TestModuleFileExtension.h
===
--- clang/lib/Frontend/TestModuleFileExtension.h
+++ clang/lib/Frontend/TestModuleFileExtension.h
@@ -48,7 +48,8 @@
   unsigned MinorVersion,
   bool Hashed,
   StringRef UserInfo)
-: BlockName(BlockName),
+: ModuleFileExtension(ModuleFileExtensionKind::MFEK_Test),
+  BlockName(BlockName),
   MajorVersion(MajorVersion), MinorVersion(MinorVersion),
   Hashed(Hashed), UserInfo(UserInfo) { }
   ~TestModuleFileExtension() override;
@@ -64,6 +65,14 @@
   createExtensionReader(const ModuleFileExtensionMetadata &Metadata,
 ASTReader &Reader, serialization::ModuleFile &Mod,
 const llvm::BitstreamCursor &Stream) override;
+
+  static bool classof(const ModuleFileExtension *E) {
+return E->getKind() == MFEK_Test;
+  }
+
+  /// Serialize the extension.
+  friend llvm::raw_ostream &
+  operator<<(llvm::raw_ostream &OS, const TestModuleFileExtension &Extension);
 };
 
 } // end namespace clang
Index: clang/lib/Frontend/TestModuleFileExtension.cpp
===
--- clang/lib/Frontend/TestModuleFileExtension.cpp
+++ clang/lib/Frontend/TestModuleFileExtension.cpp
@@ -127,3 +127,10 @@
   return std::unique_ptr(
 new TestModuleFileExtension::Reader(this, Stream));
 }
+
+llvm::raw_ostream &clang::operator<<(llvm::raw_ostream &OS,
+ const TestModuleFileExtension &Extension) {
+  return OS << Extension.BlockName << ":" << Extension.MajorVersion << ":"
+<< Extension.MinorVersion << ":" << Extension.Hashed << ":"
+<< Extension.UserInfo;
+}
Index: clang/lib/Frontend/CompilerInvocation.cpp
===
--- clang/lib/Frontend/CompilerInvocation.cpp
+++ clang/lib/Frontend/CompilerInvocation.cpp
@@ -386,7 +386,7 @@
 
 template 
 static T extractMaskValue(T KeyPath) {
-  return KeyPath & Value;
+  return ((KeyPath & Value) == Value) ? Value : T();
 }
 
 #define PARSE_OPTION_WITH_MARSHALLING(ARGS, DIAGS, SUCCESS, ID, FLAGS, PARAM,  \
@@ -2217,9 +2217,188 @@
   return None;
 }
 
-static bool ParseFrontendArgs(FrontendOptions &Opts, ArgList &Args,
-  DiagnosticsEngine &Diags, bool &IsHeaderFile) {
+/// Maps frontend action to command line option.
+static Optional
+getProgramActionOpt(frontend::ActionKind ProgramAction) {
+  for (const auto &ActionOpt : getFrontendActionTable())
+if (ActionOpt.first == ProgramAction)
+  return ActionOpt.second;
+
+  return None;
+}
+
+static void GenerateFrontendArgs(const FrontendOptions &Opts,
+ SmallVectorImpl &Args,
+ CompilerInvocation::StringAllocator SA,
+ bool IsHeader) {
+  const FrontendOptions &FrontendOpts = Opts;
+#define FRONTEND_OPTION_WITH_MARSHALLING(  \
+PREFIX_TYPE, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM,\
+HELPTEXT, METAVAR, VALUES, SPELLING, SHOULD_PARSE, ALWAYS_EMIT, KEYPATH,   \
+DEFAULT_VALUE, IMPLIED_CHECK, IMPLIED_VALUE, NORMALIZER, DENORMALIZER, \
+MERGER, EXTRACTOR, TABLE_INDEX)\
+  GENERATE_OPTION_WITH_MARSHALLING(\
+  Args, SA, KIND, FLAGS, SPELLING, ALWAYS_EMIT, KEYPATH, DEFAULT_VALUE,\
+  IMPLIED_CHECK, IMPLIED_VALUE, DENORMALIZER, EXTRACTOR, TABLE_INDEX)
+#include "clang/Driver/Options.inc"
+#undef FRONTEND_OPTION_WITH_MARSHALLING
+
+  Optional ProgramActionOpt =
+  getProgramActionOpt(Opts.ProgramAction);
+
+  // Generating a simple flag covers most frontend actions.
+  std::function GenerateProgramAction = [&]() {
+GenerateArg(Args, *ProgramActionOpt, SA);
+  };
+
+  if (!ProgramActionOpt) {
+// PluginAction is the only program action handled separately.
+assert(Opts.ProgramAction == frontend::PluginAction &&
+   "Frontend action without option.");
+GenerateProgramAction = [&]() {
+  GenerateArg(Args, OPT_plugin, Opts.ActionName, SA);
+};
+  }
+
+  // FIXME: Simplify the complex 'AST dump' command line.
+  if (Opts.ProgramAction

[PATCH] D96155: [clang][cli] Generate and round-trip Frontend options

2021-02-08 Thread Jan Svoboda via Phabricator via cfe-commits
jansvoboda11 updated this revision to Diff 322120.
jansvoboda11 added a comment.

Document getProgramActionOpt


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D96155

Files:
  clang/include/clang/Driver/Options.td
  clang/include/clang/Frontend/CommandLineSourceLoc.h
  clang/include/clang/Serialization/ModuleFileExtension.h
  clang/lib/Frontend/CompilerInvocation.cpp
  clang/lib/Frontend/TestModuleFileExtension.cpp
  clang/lib/Frontend/TestModuleFileExtension.h

Index: clang/lib/Frontend/TestModuleFileExtension.h
===
--- clang/lib/Frontend/TestModuleFileExtension.h
+++ clang/lib/Frontend/TestModuleFileExtension.h
@@ -48,7 +48,8 @@
   unsigned MinorVersion,
   bool Hashed,
   StringRef UserInfo)
-: BlockName(BlockName),
+: ModuleFileExtension(ModuleFileExtensionKind::MFEK_Test),
+  BlockName(BlockName),
   MajorVersion(MajorVersion), MinorVersion(MinorVersion),
   Hashed(Hashed), UserInfo(UserInfo) { }
   ~TestModuleFileExtension() override;
@@ -64,6 +65,14 @@
   createExtensionReader(const ModuleFileExtensionMetadata &Metadata,
 ASTReader &Reader, serialization::ModuleFile &Mod,
 const llvm::BitstreamCursor &Stream) override;
+
+  static bool classof(const ModuleFileExtension *E) {
+return E->getKind() == MFEK_Test;
+  }
+
+  /// Serialize the extension.
+  friend llvm::raw_ostream &
+  operator<<(llvm::raw_ostream &OS, const TestModuleFileExtension &Extension);
 };
 
 } // end namespace clang
Index: clang/lib/Frontend/TestModuleFileExtension.cpp
===
--- clang/lib/Frontend/TestModuleFileExtension.cpp
+++ clang/lib/Frontend/TestModuleFileExtension.cpp
@@ -127,3 +127,10 @@
   return std::unique_ptr(
 new TestModuleFileExtension::Reader(this, Stream));
 }
+
+llvm::raw_ostream &clang::operator<<(llvm::raw_ostream &OS,
+ const TestModuleFileExtension &Extension) {
+  return OS << Extension.BlockName << ":" << Extension.MajorVersion << ":"
+<< Extension.MinorVersion << ":" << Extension.Hashed << ":"
+<< Extension.UserInfo;
+}
Index: clang/lib/Frontend/CompilerInvocation.cpp
===
--- clang/lib/Frontend/CompilerInvocation.cpp
+++ clang/lib/Frontend/CompilerInvocation.cpp
@@ -386,7 +386,7 @@
 
 template 
 static T extractMaskValue(T KeyPath) {
-  return KeyPath & Value;
+  return ((KeyPath & Value) == Value) ? Value : T();
 }
 
 #define PARSE_OPTION_WITH_MARSHALLING(ARGS, DIAGS, SUCCESS, ID, FLAGS, PARAM,  \
@@ -2217,9 +2217,188 @@
   return None;
 }
 
-static bool ParseFrontendArgs(FrontendOptions &Opts, ArgList &Args,
-  DiagnosticsEngine &Diags, bool &IsHeaderFile) {
+/// Maps frontend action to command line option.
+static Optional
+getProgramActionOpt(frontend::ActionKind ProgramAction) {
+  for (const auto &ActionOpt : getFrontendActionTable())
+if (ActionOpt.first == ProgramAction)
+  return ActionOpt.second;
+
+  return None;
+}
+
+static void GenerateFrontendArgs(const FrontendOptions &Opts,
+ SmallVectorImpl &Args,
+ CompilerInvocation::StringAllocator SA,
+ bool IsHeader) {
+  const FrontendOptions &FrontendOpts = Opts;
+#define FRONTEND_OPTION_WITH_MARSHALLING(  \
+PREFIX_TYPE, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM,\
+HELPTEXT, METAVAR, VALUES, SPELLING, SHOULD_PARSE, ALWAYS_EMIT, KEYPATH,   \
+DEFAULT_VALUE, IMPLIED_CHECK, IMPLIED_VALUE, NORMALIZER, DENORMALIZER, \
+MERGER, EXTRACTOR, TABLE_INDEX)\
+  GENERATE_OPTION_WITH_MARSHALLING(\
+  Args, SA, KIND, FLAGS, SPELLING, ALWAYS_EMIT, KEYPATH, DEFAULT_VALUE,\
+  IMPLIED_CHECK, IMPLIED_VALUE, DENORMALIZER, EXTRACTOR, TABLE_INDEX)
+#include "clang/Driver/Options.inc"
+#undef FRONTEND_OPTION_WITH_MARSHALLING
+
+  Optional ProgramActionOpt =
+  getProgramActionOpt(Opts.ProgramAction);
+
+  // Generating a simple flag covers most frontend actions.
+  std::function GenerateProgramAction = [&]() {
+GenerateArg(Args, *ProgramActionOpt, SA);
+  };
+
+  if (!ProgramActionOpt) {
+// PluginAction is the only program action handled separately.
+assert(Opts.ProgramAction == frontend::PluginAction &&
+   "Frontend action without option.");
+GenerateProgramAction = [&]() {
+  GenerateArg(Args, OPT_plugin, Opts.ActionName, SA);
+};
+  }
+
+  // FIXME: Simplify the complex 'AST dump' command line.
+  if (Opts

[clang] 6b1e2fc - [FE] Manipulate the first byte of guard variable type in both load and store operation

2021-02-08 Thread Xiangling Liao via cfe-commits

Author: Xiangling Liao
Date: 2021-02-08T11:14:34-05:00
New Revision: 6b1e2fc89327a64c9300d543e00f12435c32dfcf

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

LOG: [FE] Manipulate the first byte of guard variable type in both load and 
store operation

As Itanium ABI[http://itanium-cxx-abi.github.io/cxx-abi/abi.html#once-ctor]
points out:

"The size of the guard variable is 64 bits. The first byte (i.e. the byte at
the address of the full variable) shall contain the value 0 prior to
initialization of the associated variable, and 1 after initialization is 
complete."

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

Added: 


Modified: 
clang/lib/CodeGen/ItaniumCXXABI.cpp
clang/test/CodeGenCXX/aix-static-init-temp-spec-and-inline-var.cpp
clang/test/CodeGenCXX/aix-static-init.cpp
clang/test/CodeGenCXX/cxx11-thread-local.cpp
clang/test/CodeGenCXX/global-init.cpp
clang/test/CodeGenCXX/static-data-member.cpp

Removed: 




diff  --git a/clang/lib/CodeGen/ItaniumCXXABI.cpp 
b/clang/lib/CodeGen/ItaniumCXXABI.cpp
index 50fb30a95cbb..b92801a516e9 100644
--- a/clang/lib/CodeGen/ItaniumCXXABI.cpp
+++ b/clang/lib/CodeGen/ItaniumCXXABI.cpp
@@ -2472,7 +2472,10 @@ void ItaniumCXXABI::EmitGuardedInit(CodeGenFunction &CGF,
 CGF.EmitNounwindRuntimeCall(getGuardReleaseFn(CGM, guardPtrTy),
 guardAddr.getPointer());
   } else {
-Builder.CreateStore(llvm::ConstantInt::get(guardTy, 1), guardAddr);
+// Store 1 into the first byte of the guard variable after initialization 
is
+// complete.
+Builder.CreateStore(llvm::ConstantInt::get(CGM.Int8Ty, 1),
+Builder.CreateElementBitCast(guardAddr, CGM.Int8Ty));
   }
 
   CGF.EmitBlock(EndBlock);

diff  --git 
a/clang/test/CodeGenCXX/aix-static-init-temp-spec-and-inline-var.cpp 
b/clang/test/CodeGenCXX/aix-static-init-temp-spec-and-inline-var.cpp
index f7e4c0a86b46..799b158bcf60 100644
--- a/clang/test/CodeGenCXX/aix-static-init-temp-spec-and-inline-var.cpp
+++ b/clang/test/CodeGenCXX/aix-static-init-temp-spec-and-inline-var.cpp
@@ -44,6 +44,9 @@ template <>
 A A::instance = bar();
 } // namespace test2
 
+// CHECK: @_ZGVN5test12t2E = linkonce_odr global i64 0, align 8
+// CHECK: @_ZGVN5test21AIvE8instanceE = weak_odr global i64 0, align 8
+// CHECK: @_ZGVN5test12t1IiEE = linkonce_odr global i64 0, align 8
 // CHECK: @llvm.global_ctors = appending global [4 x { i32, void ()*, i8* }] 
[{ i32, void ()*, i8* } { i32 65535, void ()* @__cxx_global_var_init.1, i8* 
null }, { i32, void ()*, i8* } { i32 65535, void ()* @__cxx_global_var_init.2, 
i8* null }, { i32, void ()*, i8* } { i32 65535, void ()* 
@__cxx_global_var_init.4, i8* null }, { i32, void ()*, i8* } { i32 65535, void 
()* @_GLOBAL__sub_I__, i8* null }]
 // CHECK: @llvm.global_dtors = appending global [4 x { i32, void ()*, i8* }] 
[{ i32, void ()*, i8* } { i32 65535, void ()* @__finalize__ZN5test12t2E, i8* 
null }, { i32, void ()*, i8* } { i32 65535, void ()* 
@__finalize__ZN5test21AIvE8instanceE, i8* null }, { i32, void ()*, i8* } { i32 
65535, void ()* @__finalize__ZN5test12t1IiEE, i8* null }, { i32, void ()*, i8* 
} { i32 65535, void ()* @_GLOBAL__D_a, i8* null }]
 
@@ -77,7 +80,7 @@ A A::instance = bar();
 
 // CHECK: define internal void @__cxx_global_var_init.1() [[ATTR:#[0-9]+]] {
 // CHECK: entry:
-// CHECK:   %0 = load atomic i8, i8* bitcast (i64* @_ZGVN5test12t2E to i8*) 
acquire
+// CHECK:   %0 = load atomic i8, i8* bitcast (i64* @_ZGVN5test12t2E to i8*) 
acquire, align 8
 // CHECK:   %guard.uninitialized = icmp eq i8 %0, 0
 // CHECK:   br i1 %guard.uninitialized, label %init.check, label %init.end
 
@@ -119,14 +122,14 @@ A A::instance = bar();
 
 // CHECK: define internal void @__cxx_global_var_init.2() [[ATTR:#[0-9]+]] {
 // CHECK: entry:
-// CHECK:   %0 = load i8, i8* bitcast (i64* @_ZGVN5test21AIvE8instanceE to i8*)
+// CHECK:   %0 = load i8, i8* bitcast (i64* @_ZGVN5test21AIvE8instanceE to 
i8*), align 8
 // CHECK:   %guard.uninitialized = icmp eq i8 %0, 0
 // CHECK:   br i1 %guard.uninitialized, label %init.check, label %init.end
 
 // CHECK: init.check:
 // CHECK:   call void @_ZN5test21AIvEC1Ev(%"struct.test2::A"* {{[^,]*}} 
@_ZN5test21AIvE8instanceE)
 // CHECK:   %1 = call i32 @atexit(void ()* @__dtor__ZN5test21AIvE8instanceE)
-// CHECK:   store i64 1, i64* @_ZGVN5test21AIvE8instanceE
+// CHECK:   store i8 1, i8* bitcast (i64* @_ZGVN5test21AIvE8instanceE to i8*), 
align 8
 // CHECK:   br label %init.end
 
 // CHECK: init.end:
@@ -182,7 +185,7 @@ A A::instance = bar();
 
 // CHECK: define internal void @__cxx_global_var_init.4() [[ATTR:#[0-9]+]] {
 // CHECK: entry:
-// CHECK:   %0 = load i8, i8* bitcast (i64* @_ZGVN5test12t1IiEE to i8*)
+// CHECK:   %0 = load i8, i8* bitcast (i64* @_ZGV

[PATCH] D95822: [FE] Manipulate the first byte of guard variable type in both load and store operation

2021-02-08 Thread Xiangling Liao via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG6b1e2fc89327: [FE] Manipulate the first byte of guard 
variable type in both load and store… (authored by Xiangling_L).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D95822

Files:
  clang/lib/CodeGen/ItaniumCXXABI.cpp
  clang/test/CodeGenCXX/aix-static-init-temp-spec-and-inline-var.cpp
  clang/test/CodeGenCXX/aix-static-init.cpp
  clang/test/CodeGenCXX/cxx11-thread-local.cpp
  clang/test/CodeGenCXX/global-init.cpp
  clang/test/CodeGenCXX/static-data-member.cpp

Index: clang/test/CodeGenCXX/static-data-member.cpp
===
--- clang/test/CodeGenCXX/static-data-member.cpp
+++ clang/test/CodeGenCXX/static-data-member.cpp
@@ -72,7 +72,7 @@
   // CHECK-NEXT: br i1 [[UNINITIALIZED]]
   // CHECK:  [[TMP:%.*]] = call i32 @_ZN5test33fooEv()
   // CHECK-NEXT: store i32 [[TMP]], i32* @_ZN5test31AIiE1xE, align 4
-  // CHECK-NEXT: store i64 1, i64* @_ZGVN5test31AIiE1xE
+  // CHECK-NEXT: store i8 1, i8* bitcast (i64* @_ZGVN5test31AIiE1xE to i8*)
   // CHECK-NEXT: br label
   // CHECK:  ret void
 }
Index: clang/test/CodeGenCXX/global-init.cpp
===
--- clang/test/CodeGenCXX/global-init.cpp
+++ clang/test/CodeGenCXX/global-init.cpp
@@ -78,10 +78,10 @@
   extern int foo();
 
   // This needs an initialization function and guard variables.
-  // CHECK: load i8, i8* bitcast (i64* @_ZGVN5test41xE
+  // CHECK: load i8, i8* bitcast (i64* @_ZGVN5test41xE to i8*)
   // CHECK: [[CALL:%.*]] = call i32 @_ZN5test43fooEv
   // CHECK-NEXT: store i32 [[CALL]], i32* @_ZN5test41xE
-  // CHECK-NEXT: store i64 1, i64* @_ZGVN5test41xE
+  // CHECK-NEXT: store i8 1, i8* bitcast (i64* @_ZGVN5test41xE to i8*)
   __attribute__((weak)) int x = foo();
 }
 
Index: clang/test/CodeGenCXX/cxx11-thread-local.cpp
===
--- clang/test/CodeGenCXX/cxx11-thread-local.cpp
+++ clang/test/CodeGenCXX/cxx11-thread-local.cpp
@@ -184,7 +184,7 @@
 // need init:
 // CHECK: call i32 @_Z1gv()
 // CHECK: store i32 %{{.*}}, i32* @_ZN1VIfE1mE, align 4
-// CHECK: store i64 1, i64* @_ZGVN1VIfE1mE
+// CHECK: store i8 1, i8* bitcast (i64* @_ZGVN1VIfE1mE to i8*)
 // CHECK: br label
 
 // LINUX: define internal void @[[XF_M_INIT]]()
@@ -197,7 +197,7 @@
 // need init:
 // LINUX: call {{.*}}__cxa_thread_atexit
 // DARWIN: call {{.*}}_tlv_atexit
-// CHECK: store i64 1, i64* @_ZGVN1XIfE1mE
+// CHECK: store i8 1, i8* bitcast (i64* @_ZGVN1XIfE1mE to i8*)
 // CHECK: br label
 
 // LINUX: declare i32 @__cxa_thread_atexit(void (i8*)*, i8*, i8*)
@@ -285,7 +285,7 @@
 // need init:
 // CHECK: call i32 @_Z1gv()
 // CHECK: store i32 %{{.*}}, i32* @_ZN1VIiE1mE, align 4
-// CHECK: store i64 1, i64* @_ZGVN1VIiE1mE
+// CHECK: store i8 1, i8* bitcast (i64* @_ZGVN1VIiE1mE to i8*)
 // CHECK: br label
 
 // LINUX: define internal void @[[X_M_INIT]]()
@@ -298,7 +298,7 @@
 // need init:
 // LINUX: call {{.*}}__cxa_thread_atexit
 // DARWIN: call {{.*}}_tlv_atexit
-// CHECK: store i64 1, i64* @_ZGVN1XIiE1mE
+// CHECK: store i8 1, i8* bitcast (i64* @_ZGVN1XIiE1mE to i8*)
 // CHECK: br label
 
 // CHECK: define {{.*}}@[[GLOBAL_INIT:.*]]()
Index: clang/test/CodeGenCXX/aix-static-init.cpp
===
--- clang/test/CodeGenCXX/aix-static-init.cpp
+++ clang/test/CodeGenCXX/aix-static-init.cpp
@@ -38,6 +38,7 @@
   }
 } // namespace test4
 
+// CHECK: @_ZGVZN5test41fEvE11staticLocal = internal global i64 0, align 8
 // CHECK: @llvm.global_ctors = appending global [1 x { i32, void ()*, i8* }] [{ i32, void ()*, i8* } { i32 65535, void ()* @_GLOBAL__sub_I__, i8* null }]
 // CHECK: @llvm.global_dtors = appending global [1 x { i32, void ()*, i8* }] [{ i32, void ()*, i8* } { i32 65535, void ()* @_GLOBAL__D_a, i8* null }]
 
@@ -135,7 +136,7 @@
 
 // CHECK: define void @_ZN5test41fEv() [[ATTR:#[0-9]+]] {
 // CHECK: entry:
-// CHECK:   %0 = load atomic i8, i8* bitcast (i64* @_ZGVZN5test41fEvE11staticLocal to i8*) acquire
+// CHECK:   %0 = load atomic i8, i8* bitcast (i64* @_ZGVZN5test41fEvE11staticLocal to i8*) acquire, align 8
 // CHECK:   %guard.uninitialized = icmp eq i8 %0, 0
 // CHECK:   br i1 %guard.uninitialized, label %init.check, label %init.end
 
Index: clang/test/CodeGenCXX/aix-static-init-temp-spec-and-inline-var.cpp
===
--- clang/test/CodeGenCXX/aix-static-init-temp-spec-and-inline-var.cpp
+++ clang/test/CodeGenCXX/aix-static-init-temp-spec-and-inline-var.cpp
@@ -44,6 +44,9 @@
 A A::instance = bar();
 } // namespace test2
 
+// CHECK: @_ZGVN5test12t2E = linkonce_odr global i64 0, align 8
+// CHECK: @_ZGVN5test21AIvE8instanceE = weak_odr global i64 0, align 8
+// CHECK: @_ZGVN5test12t1IiEE = linkonce_odr global i64 0, align 8
 /

[PATCH] D96056: [clang][cli] Generate and round-trip CodeGen options

2021-02-08 Thread Jan Svoboda via Phabricator via cfe-commits
jansvoboda11 updated this revision to Diff 322118.
jansvoboda11 added a comment.

Rebase


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D96056

Files:
  clang/include/clang/Basic/XRayInstr.h
  clang/include/clang/Driver/Options.td
  clang/include/clang/Frontend/CompilerInvocation.h
  clang/lib/Basic/XRayInstr.cpp
  clang/lib/Frontend/CompilerInvocation.cpp
  llvm/include/llvm/Option/OptParser.td

Index: llvm/include/llvm/Option/OptParser.td
===
--- llvm/include/llvm/Option/OptParser.td
+++ llvm/include/llvm/Option/OptParser.td
@@ -175,7 +175,7 @@
 class MarshallingInfoStringInt
   : MarshallingInfo {
   code Normalizer = "normalizeStringIntegral<"#type#">";
-  code Denormalizer = "denormalizeString";
+  code Denormalizer = "denormalizeString<"#type#">";
 }
 
 class MarshallingInfoStringVector
Index: clang/lib/Frontend/CompilerInvocation.cpp
===
--- clang/lib/Frontend/CompilerInvocation.cpp
+++ clang/lib/Frontend/CompilerInvocation.cpp
@@ -54,6 +54,7 @@
 #include "llvm/ADT/Hashing.h"
 #include "llvm/ADT/None.h"
 #include "llvm/ADT/Optional.h"
+#include "llvm/ADT/STLExtras.h"
 #include "llvm/ADT/SmallString.h"
 #include "llvm/ADT/SmallVector.h"
 #include "llvm/ADT/StringRef.h"
@@ -620,14 +621,17 @@
   // Run the first parse on the original arguments with dummy options and
   // diagnostics.
   SwapOpts(Res);
-  if (!Parse(Res, OriginalArgs, DummyDiags)) {
+  if (!Parse(Res, OriginalArgs, DummyDiags) ||
+  DummyDiags.getNumWarnings() != 0) {
 // If the first parse did not succeed, it must be user mistake (invalid
 // command line arguments). We won't be able to generate arguments that
 // would reproduce the same result. Let's fail again with the original
 // options and diagnostics, so all side-effects of parsing are visible.
+unsigned NumWarningsBefore = Diags.getNumWarnings();
 SwapOpts(Res);
-if (!Parse(Res, OriginalArgs, Diags))
-  return false;
+auto Success = Parse(Res, OriginalArgs, Diags);
+if (!Success || Diags.getNumWarnings() != NumWarningsBefore)
+  return Success;
 
 // Parse with original options and diagnostics succeeded even though it
 // shouldn't have. Something is off.
@@ -744,16 +748,11 @@
 
 static void getAllNoBuiltinFuncValues(ArgList &Args,
   std::vector &Funcs) {
-  SmallVector Values;
-  for (const auto &Arg : Args) {
-const Option &O = Arg->getOption();
-if (O.matches(options::OPT_fno_builtin_)) {
-  const char *FuncName = Arg->getValue();
-  if (Builtin::Context::isBuiltinFunc(FuncName))
-Values.push_back(FuncName);
-}
-  }
-  Funcs.insert(Funcs.end(), Values.begin(), Values.end());
+  std::vector Values = Args.getAllArgValues(OPT_fno_builtin_);
+  auto BuiltinEnd = llvm::partition(Values, [](const std::string FuncName) {
+return Builtin::Context::isBuiltinFunc(FuncName);
+  });
+  Funcs.insert(Funcs.end(), Values.begin(), BuiltinEnd);
 }
 
 static void GenerateAnalyzerArgs(AnalyzerOptions &Opts,
@@ -1233,6 +1232,15 @@
   }
 }
 
+static std::string serializeXRayInstrumentationBundle(const XRayInstrSet &S) {
+  llvm::SmallVector BundleParts;
+  serializeXRayInstrValue(S, BundleParts);
+  std::string Buffer;
+  llvm::raw_string_ostream OS(Buffer);
+  llvm::interleave(BundleParts, OS, [&OS](StringRef Part) { OS << Part; }, ",");
+  return OS.str();
+}
+
 // Set the profile kind using fprofile-instrument-use-path.
 static void setPGOUseInstrumentor(CodeGenOptions &Opts,
   const Twine &ProfileName) {
@@ -1254,12 +1262,258 @@
 Opts.setProfileUse(CodeGenOptions::ProfileClangInstr);
 }
 
-bool CompilerInvocation::ParseCodeGenArgs(CodeGenOptions &Opts, ArgList &Args,
-  InputKind IK,
-  DiagnosticsEngine &Diags,
-  const llvm::Triple &T,
-  const std::string &OutputFile,
-  const LangOptions &LangOptsRef) {
+void CompilerInvocation::GenerateCodeGenArgs(
+const CodeGenOptions &Opts, SmallVectorImpl &Args,
+StringAllocator SA, const llvm::Triple &T, const std::string &OutputFile,
+const LangOptions *LangOpts) {
+  const CodeGenOptions &CodeGenOpts = Opts;
+
+  if (Opts.OptimizationLevel == 0)
+GenerateArg(Args, OPT_O0, SA);
+  else
+GenerateArg(Args, OPT_O, Twine(Opts.OptimizationLevel), SA);
+
+#define CODEGEN_OPTION_WITH_MARSHALLING(   \
+PREFIX_TYPE, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM,\
+HELPTEXT, METAVAR, VALUES, SPELLING, SHOULD_PARSE, ALWAYS_EMIT, KEYPATH,   \
+DEFAULT_VALUE, IMPLIED_CHECK, IMPLIED_VALUE, NORMALIZER, DENORMALIZE

  1   2   >