[PATCH] D124570: Revert "[analyzer][NFC] Refactor GenericTaintChecker to use CallDescriptionMap"

2022-04-29 Thread Balázs Benics via Phabricator via cfe-commits
steakhal added a comment.

In D124570#3480996 , @t-rasmud wrote:

> Abandoning this patch because it was a downstream problem and I incorrectly 
> diagnosed it on the open source branch.

Oh, I see. Yeey, so it's still an NFC :D


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124570

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


[PATCH] D119544: Deferred Concept Instantiation Implementation

2022-04-29 Thread Chuanqi Xu via Phabricator via cfe-commits
ChuanqiXu added a comment.

Oh, I'm busy with coroutines these days. Thanks for reminding me for this. LGTM 
to me basically. Only comments for style left.




Comment at: clang/lib/Sema/SemaConcept.cpp:70
+assert((!LHS.isInvalid() && !RHS.isInvalid()) && "not good expressions?");
+assert(LHS.isUsable() && RHS.isUsable() && "Side not usable?");
+// We should just be able to 'normalize' these to the builtin Binary

I feel like the usage of the API could be further simplified.



Comment at: clang/lib/Sema/SemaConcept.cpp:338-340
+  // Backfill the 'converted' list with nulls so we can keep the Converted
+  Converted.append(ConstraintExprs.size() - Converted.size(), nullptr);
+  // and unconverted lists in sync. [temp.constr.op] p2





Comment at: clang/lib/Sema/SemaConcept.cpp:365-370
+  for (unsigned Depth = 0; Depth < TemplateArgsList.getNumSubstitutedLevels();
+   ++Depth) {
+for (unsigned Index = 0;
+ Index < TemplateArgsList.getNumSubstitutedArgs(Depth); ++Index)
+  FlattenedArgs.push_back(TemplateArgsList(Depth, Index));
+  }

I think it is a chance to add range style interfaces for 
MultiLevelTemplateArgumentList. So that we could use range-based loop here.



Comment at: clang/lib/Sema/SemaConcept.cpp:432-476
+if (TemplateArgs) {
+  MultiLevelTemplateArgumentList JustTemplArgs(
+  *FD->getTemplateSpecializationArgs());
+  if (addInstantiatedParametersToScope(
+  FD, PrimaryTemplate->getTemplatedDecl(), Scope, JustTemplArgs))
+return true;
+}

The suggested change works. I feel it is not identical with the original. Is it 
correct or do we miss something in the test?



Comment at: clang/lib/Sema/SemaTemplateInstantiateDecl.cpp:2173
 Function->setInstantiationOfMemberFunction(D, TSK_ImplicitInstantiation);
+  } else if (!isFriend) {
+// If this is not a function template, and this is not a friend (that is,

The check here is not straightforward. Here we want to check if the Function is 
local declared function. But what we check here is about friendness. I am not 
100% sure if it is right and other reader might be confusing too. I would 
suggest to check it directly. e.g, check if one of its DeclContext is 
FunctionDecl.



Comment at: clang/lib/Sema/TreeTransform.h:13003
   if (Expr *TRC = E->getCallOperator()->getTrailingRequiresClause())
-// FIXME: Concepts: Substitution into requires clause should only happen
-//  when checking satisfaction.
-NewTrailingRequiresClause = getDerived().TransformExpr(TRC);
+NewTrailingRequiresClause = TRC;
 

I think we could eliminate `NewTrailingRequiresClause`



Comment at: clang/test/SemaTemplate/concepts.cpp:275-276
+template 
+constexpr bool constraint = PR54443::is_same::type,
+ int>::value;
+

Better to rename `constraint` to something like `IsInt`


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

https://reviews.llvm.org/D119544

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


[clang] db1cec3 - [X86] Fix CodeGen Module Flag for -mibt-seal

2022-04-29 Thread Phoebe Wang via cfe-commits

Author: Joao Moreira
Date: 2022-04-29T15:37:28+08:00
New Revision: db1cec371c00722ce42683e0dc8a2021186332c5

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

LOG: [X86] Fix CodeGen Module Flag for -mibt-seal

When assertions are enabled, clang will perform RoundTrip for 
CompilerInvocation argument generation. ibt-seal flags are currently missing in 
this argument generation, and because of that, the feature doesn't get enabled 
for these cases. Performing RoundTrip is the default for assert builds, 
rendering the feature broken in these scenarios.

This patch fixes this and adds a test to properly verify that modules are  
being generated with the flag when -mibt-seal is used.

Please, add any known relevant reviewer which I may have missed.

[1] - https://reviews.llvm.org/D116070

Reviewed By: pengfei, gftg, aaron.ballman, nickdesaulniers

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

Added: 


Modified: 
clang/lib/Frontend/CompilerInvocation.cpp
clang/test/CodeGen/X86/x86-cf-protection.c

Removed: 




diff  --git a/clang/lib/Frontend/CompilerInvocation.cpp 
b/clang/lib/Frontend/CompilerInvocation.cpp
index fcb73bc858a43..66072875765dc 100644
--- a/clang/lib/Frontend/CompilerInvocation.cpp
+++ b/clang/lib/Frontend/CompilerInvocation.cpp
@@ -1504,6 +1504,9 @@ void CompilerInvocation::GenerateCodeGenArgs(
   else if (Opts.CFProtectionBranch)
 GenerateArg(Args, OPT_fcf_protection_EQ, "branch", SA);
 
+  if (Opts.IBTSeal)
+GenerateArg(Args, OPT_mibt_seal, SA);
+
   for (const auto &F : Opts.LinkBitcodeFiles) {
 bool Builtint = F.LinkFlags == llvm::Linker::Flags::LinkOnlyNeeded &&
 F.PropagateAttrs && F.Internalize;

diff  --git a/clang/test/CodeGen/X86/x86-cf-protection.c 
b/clang/test/CodeGen/X86/x86-cf-protection.c
index 7197dacc4ba0b..815ef3f8479e2 100644
--- a/clang/test/CodeGen/X86/x86-cf-protection.c
+++ b/clang/test/CodeGen/X86/x86-cf-protection.c
@@ -1,8 +1,14 @@
 // RUN: %clang -target i386-unknown-unknown -x c -E -dM -o - 
-fcf-protection=return %s | FileCheck %s --check-prefix=RETURN
 // RUN: %clang -target i386-unknown-unknown -x c -E -dM -o - 
-fcf-protection=branch %s | FileCheck %s --check-prefix=BRANCH
 // RUN: %clang -target i386-unknown-unknown -x c -E -dM -o - 
-fcf-protection=full %s   | FileCheck %s --check-prefix=FULL
+// RUN: %clang -target i386-unknown-unknown -o - -emit-llvm -S 
-fcf-protection=branch -mibt-seal -flto %s | FileCheck %s 
--check-prefixes=CFPROT,IBTSEAL
+// RUN: %clang -target i386-unknown-unknown -o - -emit-llvm -S 
-fcf-protection=branch -flto %s | FileCheck %s --check-prefixes=CFPROT,NOIBTSEAL
+// RUN: %clang -target i386-unknown-unknown -o - -emit-llvm -S 
-fcf-protection=branch -mibt-seal %s | FileCheck %s 
--check-prefixes=CFPROT,NOIBTSEAL
 
 // RETURN: #define __CET__ 2
 // BRANCH: #define __CET__ 1
 // FULL: #define __CET__ 3
+// CFPROT: "cf-protection-branch", i32 1
+// IBTSEAL: "ibt-seal", i32 1
+// NOIBTSEAL-NOT: "ibt-seal", i32 1
 void foo() {}



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


[PATCH] D118052: [X86] Fix CodeGen Module Flag for -mibt-seal

2022-04-29 Thread Phoebe Wang via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rGdb1cec371c00: [X86] Fix CodeGen Module Flag for -mibt-seal 
(authored by joaomoreira, committed by pengfei).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D118052

Files:
  clang/lib/Frontend/CompilerInvocation.cpp
  clang/test/CodeGen/X86/x86-cf-protection.c


Index: clang/test/CodeGen/X86/x86-cf-protection.c
===
--- clang/test/CodeGen/X86/x86-cf-protection.c
+++ clang/test/CodeGen/X86/x86-cf-protection.c
@@ -1,8 +1,14 @@
 // RUN: %clang -target i386-unknown-unknown -x c -E -dM -o - 
-fcf-protection=return %s | FileCheck %s --check-prefix=RETURN
 // RUN: %clang -target i386-unknown-unknown -x c -E -dM -o - 
-fcf-protection=branch %s | FileCheck %s --check-prefix=BRANCH
 // RUN: %clang -target i386-unknown-unknown -x c -E -dM -o - 
-fcf-protection=full %s   | FileCheck %s --check-prefix=FULL
+// RUN: %clang -target i386-unknown-unknown -o - -emit-llvm -S 
-fcf-protection=branch -mibt-seal -flto %s | FileCheck %s 
--check-prefixes=CFPROT,IBTSEAL
+// RUN: %clang -target i386-unknown-unknown -o - -emit-llvm -S 
-fcf-protection=branch -flto %s | FileCheck %s --check-prefixes=CFPROT,NOIBTSEAL
+// RUN: %clang -target i386-unknown-unknown -o - -emit-llvm -S 
-fcf-protection=branch -mibt-seal %s | FileCheck %s 
--check-prefixes=CFPROT,NOIBTSEAL
 
 // RETURN: #define __CET__ 2
 // BRANCH: #define __CET__ 1
 // FULL: #define __CET__ 3
+// CFPROT: "cf-protection-branch", i32 1
+// IBTSEAL: "ibt-seal", i32 1
+// NOIBTSEAL-NOT: "ibt-seal", i32 1
 void foo() {}
Index: clang/lib/Frontend/CompilerInvocation.cpp
===
--- clang/lib/Frontend/CompilerInvocation.cpp
+++ clang/lib/Frontend/CompilerInvocation.cpp
@@ -1504,6 +1504,9 @@
   else if (Opts.CFProtectionBranch)
 GenerateArg(Args, OPT_fcf_protection_EQ, "branch", SA);
 
+  if (Opts.IBTSeal)
+GenerateArg(Args, OPT_mibt_seal, SA);
+
   for (const auto &F : Opts.LinkBitcodeFiles) {
 bool Builtint = F.LinkFlags == llvm::Linker::Flags::LinkOnlyNeeded &&
 F.PropagateAttrs && F.Internalize;


Index: clang/test/CodeGen/X86/x86-cf-protection.c
===
--- clang/test/CodeGen/X86/x86-cf-protection.c
+++ clang/test/CodeGen/X86/x86-cf-protection.c
@@ -1,8 +1,14 @@
 // RUN: %clang -target i386-unknown-unknown -x c -E -dM -o - -fcf-protection=return %s | FileCheck %s --check-prefix=RETURN
 // RUN: %clang -target i386-unknown-unknown -x c -E -dM -o - -fcf-protection=branch %s | FileCheck %s --check-prefix=BRANCH
 // RUN: %clang -target i386-unknown-unknown -x c -E -dM -o - -fcf-protection=full %s   | FileCheck %s --check-prefix=FULL
+// RUN: %clang -target i386-unknown-unknown -o - -emit-llvm -S -fcf-protection=branch -mibt-seal -flto %s | FileCheck %s --check-prefixes=CFPROT,IBTSEAL
+// RUN: %clang -target i386-unknown-unknown -o - -emit-llvm -S -fcf-protection=branch -flto %s | FileCheck %s --check-prefixes=CFPROT,NOIBTSEAL
+// RUN: %clang -target i386-unknown-unknown -o - -emit-llvm -S -fcf-protection=branch -mibt-seal %s | FileCheck %s --check-prefixes=CFPROT,NOIBTSEAL
 
 // RETURN: #define __CET__ 2
 // BRANCH: #define __CET__ 1
 // FULL: #define __CET__ 3
+// CFPROT: "cf-protection-branch", i32 1
+// IBTSEAL: "ibt-seal", i32 1
+// NOIBTSEAL-NOT: "ibt-seal", i32 1
 void foo() {}
Index: clang/lib/Frontend/CompilerInvocation.cpp
===
--- clang/lib/Frontend/CompilerInvocation.cpp
+++ clang/lib/Frontend/CompilerInvocation.cpp
@@ -1504,6 +1504,9 @@
   else if (Opts.CFProtectionBranch)
 GenerateArg(Args, OPT_fcf_protection_EQ, "branch", SA);
 
+  if (Opts.IBTSeal)
+GenerateArg(Args, OPT_mibt_seal, SA);
+
   for (const auto &F : Opts.LinkBitcodeFiles) {
 bool Builtint = F.LinkFlags == llvm::Linker::Flags::LinkOnlyNeeded &&
 F.PropagateAttrs && F.Internalize;
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D118052: [X86] Fix CodeGen Module Flag for -mibt-seal

2022-04-29 Thread Phoebe Wang via Phabricator via cfe-commits
pengfei added a comment.

In D118052#3480564 , @joaomoreira 
wrote:

> I think there are no more untied knots... @pengfei, do you think this is 
> ready to merge? If yes, can you please merge it? tks!

Sure.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D118052

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


[clang] 4e545bd - [SimplifyCFG] Thread branches on same condition in more cases (PR54980)

2022-04-29 Thread Nikita Popov via cfe-commits

Author: Nikita Popov
Date: 2022-04-29T09:44:05+02:00
New Revision: 4e545bdb355a470d601e9bb7f7b2693c99e61a3e

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

LOG: [SimplifyCFG] Thread branches on same condition in more cases (PR54980)

SimplifyCFG implements basic jump threading, if a branch is
performed on a phi node with constant operands. However,
InstCombine canonicalizes such phis to the condition value of a
previous branch, if possible. SimplifyCFG does support this as
well, but only in the very limited case where the same condition
is used in a direct predecessor -- notably, this does not include
the common diamond pattern (i.e. two consecutive if/elses on the
same condition).

This patch extends the code to look back a limited number of
blocks to find a branch on the same value, rather than only
looking at the direct predecessor.

Fixes https://github.com/llvm/llvm-project/issues/54980.

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

Added: 


Modified: 
clang/test/CodeGenObjC/exceptions.m
clang/test/CodeGenObjCXX/exceptions-legacy.mm
llvm/lib/Transforms/Utils/SimplifyCFG.cpp
llvm/test/CodeGen/AArch64/arm64-andCmpBrToTBZ.ll
llvm/test/Transforms/GVNSink/sink-common-code.ll
llvm/test/Transforms/SimplifyCFG/X86/sink-common-code.ll
llvm/test/Transforms/SimplifyCFG/jump-threading.ll
llvm/test/Transforms/SimplifyCFG/wc-widen-block.ll

Removed: 




diff  --git a/clang/test/CodeGenObjC/exceptions.m 
b/clang/test/CodeGenObjC/exceptions.m
index e01965edd73f2..302e8af51ed8e 100644
--- a/clang/test/CodeGenObjC/exceptions.m
+++ b/clang/test/CodeGenObjC/exceptions.m
@@ -25,11 +25,12 @@ void f1(void) {
 // CHECK-NEXT: icmp
 // CHECK-NEXT: br i1
 @try {
-// CHECK:  call void asm sideeffect "", "=*m"
 // CHECK:  call void asm sideeffect "", "*m"
 // CHECK-NEXT: call void @foo()
   foo();
 // CHECK:  call void @objc_exception_try_exit
+// CHECK:  try.handler:
+// CHECK:  call void asm sideeffect "", "=*m"
 
 } @finally {
   break;
@@ -53,12 +54,6 @@ int f2(void) {
   // CHECK-NEXT:   [[CAUGHT:%.*]] = icmp eq i32 [[SETJMP]], 0
   // CHECK-NEXT:   br i1 [[CAUGHT]]
   @try {
-// Landing pad.  Note that we elide the re-enter.
-// CHECK:  call void asm sideeffect "", "=*m,=*m"(i32* nonnull 
elementtype(i32) [[X]]
-// CHECK-NEXT: call i8* @objc_exception_extract
-// CHECK-NEXT: [[T1:%.*]] = load i32, i32* [[X]]
-// CHECK-NEXT: [[T2:%.*]] = add nsw i32 [[T1]], -1
-
 // CHECK: store i32 6, i32* [[X]]
 x++;
 // CHECK-NEXT: call void asm sideeffect "", "*m,*m"(i32* nonnull 
elementtype(i32) [[X]]
@@ -67,6 +62,12 @@ int f2(void) {
 // CHECK-NEXT: [[T:%.*]] = load i32, i32* [[X]]
 foo();
   } @catch (id) {
+// Landing pad.  Note that we elide the re-enter.
+// CHECK:  call void asm sideeffect "", "=*m,=*m"(i32* nonnull 
elementtype(i32) [[X]]
+// CHECK-NEXT: call i8* @objc_exception_extract
+// CHECK-NEXT: [[T1:%.*]] = load i32, i32* [[X]]
+// CHECK-NEXT: [[T2:%.*]] = add nsw i32 [[T1]], -1
+
 x--;
   }
 

diff  --git a/clang/test/CodeGenObjCXX/exceptions-legacy.mm 
b/clang/test/CodeGenObjCXX/exceptions-legacy.mm
index 9d9e4e4b86df6..4166f635deecf 100644
--- a/clang/test/CodeGenObjCXX/exceptions-legacy.mm
+++ b/clang/test/CodeGenObjCXX/exceptions-legacy.mm
@@ -63,20 +63,19 @@ void test1(id obj, bool *failed) {
 //   Body.
 // CHECK:  invoke void @_Z3foov()
 
-//   Catch handler.  Reload of 'failed' address is unnecessary.
-// CHECK:  [[T0:%.*]] = load i8*, i8**
-// CHECK-NEXT: store i8 1, i8* [[T0]],
-// CHECK-NEXT: br label
-
 //   Leave the @try.
 // CHECK:  call void @objc_exception_try_exit([[BUF_T]]* nonnull [[BUF]])
 // CHECK-NEXT: br label
 // CHECK:  ret void
 
-
 //   Real EH cleanup.
 // CHECK:  [[T0:%.*]] = landingpad
 // CHECK-NEXT:cleanup
 // CHECK-NEXT: call void @objc_exception_try_exit([[BUF_T]]* nonnull [[BUF]])
 // CHECK-NEXT: resume
 
+//   Catch handler.  Reload of 'failed' address is unnecessary.
+// CHECK:  [[T0:%.*]] = load i8*, i8**
+// CHECK-NEXT: store i8 1, i8* [[T0]],
+// CHECK-NEXT: br label
+

diff  --git a/llvm/lib/Transforms/Utils/SimplifyCFG.cpp 
b/llvm/lib/Transforms/Utils/SimplifyCFG.cpp
index d2b7b71e611d5..cd47a1e7e456a 100644
--- a/llvm/lib/Transforms/Utils/SimplifyCFG.cpp
+++ b/llvm/lib/Transforms/Utils/SimplifyCFG.cpp
@@ -2975,8 +2975,10 @@ static bool 
BlockIsSimpleEnoughToThreadThrough(BasicBlock *BB) {
   return true;
 }
 
-static ConstantInt *getKnownValueOnEdge(Value *V, BasicBlock *From,
-BasicBlock *To) {
+static ConstantInt *
+getKnownValueOnEdge(Value *V, BasicBlock *From, BasicBlock *To,
+   

[PATCH] D124159: [SimplifyCFG] Thread branches on same condition in more cases (PR54980)

2022-04-29 Thread Nikita Popov 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 rG4e545bdb355a: [SimplifyCFG] Thread branches on same 
condition in more cases (PR54980) (authored by nikic).
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124159

Files:
  clang/test/CodeGenObjC/exceptions.m
  clang/test/CodeGenObjCXX/exceptions-legacy.mm
  llvm/lib/Transforms/Utils/SimplifyCFG.cpp
  llvm/test/CodeGen/AArch64/arm64-andCmpBrToTBZ.ll
  llvm/test/Transforms/GVNSink/sink-common-code.ll
  llvm/test/Transforms/SimplifyCFG/X86/sink-common-code.ll
  llvm/test/Transforms/SimplifyCFG/jump-threading.ll
  llvm/test/Transforms/SimplifyCFG/wc-widen-block.ll

Index: llvm/test/Transforms/SimplifyCFG/wc-widen-block.ll
===
--- llvm/test/Transforms/SimplifyCFG/wc-widen-block.ll
+++ llvm/test/Transforms/SimplifyCFG/wc-widen-block.ll
@@ -269,17 +269,18 @@
 define i32 @neg_loop(i1 %cond_0, i1 %cond_1) {
 ; CHECK-LABEL: @neg_loop(
 ; CHECK-NEXT:  entry:
-; CHECK-NEXT:br label [[GUARDED:%.*]]
+; CHECK-NEXT:call void @unknown()
+; CHECK-NEXT:br i1 [[COND_1:%.*]], label [[LOOP:%.*]], label [[DEOPT2:%.*]], !prof [[PROF0]]
+; CHECK:   loop.critedge:
+; CHECK-NEXT:call void @unknown()
+; CHECK-NEXT:br label [[LOOP]]
 ; CHECK:   loop:
 ; CHECK-NEXT:[[WIDENABLE_COND:%.*]] = call i1 @llvm.experimental.widenable.condition()
 ; CHECK-NEXT:[[EXIPLICIT_GUARD_COND:%.*]] = and i1 [[COND_0:%.*]], [[WIDENABLE_COND]]
-; CHECK-NEXT:br i1 [[EXIPLICIT_GUARD_COND]], label [[GUARDED]], label [[DEOPT:%.*]], !prof [[PROF0]]
+; CHECK-NEXT:br i1 [[EXIPLICIT_GUARD_COND]], label [[LOOP_CRITEDGE:%.*]], label [[DEOPT:%.*]], !prof [[PROF0]]
 ; CHECK:   deopt:
 ; CHECK-NEXT:[[DEOPTRET:%.*]] = call i32 (...) @llvm.experimental.deoptimize.i32() [ "deopt"() ]
 ; CHECK-NEXT:ret i32 [[DEOPTRET]]
-; CHECK:   guarded:
-; CHECK-NEXT:call void @unknown()
-; CHECK-NEXT:br i1 [[COND_1:%.*]], label [[LOOP:%.*]], label [[DEOPT2:%.*]], !prof [[PROF0]]
 ; CHECK:   deopt2:
 ; CHECK-NEXT:[[DEOPTRET2:%.*]] = call i32 (...) @llvm.experimental.deoptimize.i32() [ "deopt"() ]
 ; CHECK-NEXT:ret i32 [[DEOPTRET2]]
Index: llvm/test/Transforms/SimplifyCFG/jump-threading.ll
===
--- llvm/test/Transforms/SimplifyCFG/jump-threading.ll
+++ llvm/test/Transforms/SimplifyCFG/jump-threading.ll
@@ -144,16 +144,10 @@
 ; CHECK-NEXT:br i1 [[C:%.*]], label [[IF:%.*]], label [[ELSE:%.*]]
 ; CHECK:   if:
 ; CHECK-NEXT:call void @foo()
-; CHECK-NEXT:br label [[JOIN:%.*]]
-; CHECK:   else:
-; CHECK-NEXT:call void @bar()
-; CHECK-NEXT:br label [[JOIN]]
-; CHECK:   join:
-; CHECK-NEXT:br i1 [[C]], label [[IF2:%.*]], label [[ELSE2:%.*]]
-; CHECK:   if2:
 ; CHECK-NEXT:call void @foo()
 ; CHECK-NEXT:br label [[JOIN2:%.*]]
-; CHECK:   else2:
+; CHECK:   else:
+; CHECK-NEXT:call void @bar()
 ; CHECK-NEXT:call void @bar()
 ; CHECK-NEXT:br label [[JOIN2]]
 ; CHECK:   join2:
@@ -189,17 +183,12 @@
 ; CHECK-NEXT:br i1 [[C:%.*]], label [[IF:%.*]], label [[ELSE:%.*]]
 ; CHECK:   if:
 ; CHECK-NEXT:call void @foo()
-; CHECK-NEXT:br label [[JOIN:%.*]]
-; CHECK:   else:
-; CHECK-NEXT:call void @bar()
-; CHECK-NEXT:br label [[JOIN]]
-; CHECK:   join:
 ; CHECK-NEXT:call void @use.i1(i1 [[C]])
-; CHECK-NEXT:br i1 [[C]], label [[IF2:%.*]], label [[ELSE2:%.*]]
-; CHECK:   if2:
 ; CHECK-NEXT:call void @foo()
 ; CHECK-NEXT:br label [[JOIN2:%.*]]
-; CHECK:   else2:
+; CHECK:   else:
+; CHECK-NEXT:call void @bar()
+; CHECK-NEXT:call void @use.i1(i1 [[C]])
 ; CHECK-NEXT:call void @bar()
 ; CHECK-NEXT:br label [[JOIN2]]
 ; CHECK:   join2:
@@ -236,17 +225,11 @@
 ; CHECK-NEXT:br i1 [[C:%.*]], label [[IF:%.*]], label [[ELSE:%.*]]
 ; CHECK:   if:
 ; CHECK-NEXT:call void @foo()
-; CHECK-NEXT:br label [[JOIN:%.*]]
-; CHECK:   else:
-; CHECK-NEXT:call void @bar()
-; CHECK-NEXT:br label [[JOIN]]
-; CHECK:   join:
-; CHECK-NEXT:br i1 [[C]], label [[IF2:%.*]], label [[ELSE2:%.*]]
-; CHECK:   if2:
 ; CHECK-NEXT:call void @use.i1(i1 [[C]])
 ; CHECK-NEXT:call void @foo()
 ; CHECK-NEXT:br label [[JOIN2:%.*]]
-; CHECK:   else2:
+; CHECK:   else:
+; CHECK-NEXT:call void @bar()
 ; CHECK-NEXT:call void @use.i1(i1 [[C]])
 ; CHECK-NEXT:call void @bar()
 ; CHECK-NEXT:br label [[JOIN2]]
Index: llvm/test/Transforms/SimplifyCFG/X86/sink-common-code.ll
===
--- llvm/test/Transforms/SimplifyCFG/X86/sink-common-code.ll
+++ llvm/test/Transforms/SimplifyCF

[PATCH] D124621: CPP-2461 [Analyzer] Fix assumptions about const field with member-initializer

2022-04-29 Thread Marco Antognini via Phabricator via cfe-commits
mantognini created this revision.
Herald added subscribers: manas, steakhal, ASDenysPetrov, martong, dkrupp, 
donat.nagy, Szelethus, mikhail.ramalho, a.sidorin, szepet, baloghadamsoftware, 
xazax.hun.
Herald added a project: All.
mantognini added reviewers: dcoughlin, NoQ, r.stahl, xazax.hun.
mantognini published this revision for review.
mantognini added a comment.
Herald added subscribers: cfe-commits, rnkovacs.
Herald added a project: clang.

One thing I'm not sure about and couldn't easily find in the doc is how to 
reference in the commit message the bug (https://llvm.org/PR48534) this patch 
fixes. Is it good as is?


Essentially, having a default member initializer for a constant member
does not necessarily imply the member will have the given default value.

Fix PR48534.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D124621

Files:
  clang/lib/StaticAnalyzer/Core/RegionStore.cpp
  clang/test/Analysis/cxx-member-initializer-const-field.cpp

Index: clang/test/Analysis/cxx-member-initializer-const-field.cpp
===
--- /dev/null
+++ clang/test/Analysis/cxx-member-initializer-const-field.cpp
@@ -0,0 +1,120 @@
+// RUN: %clang_analyze_cc1 -analyzer-checker=core -verify %s
+
+// This tests false-positive issues related to PR48534.
+//
+// Essentially, having a default member initializer for a constant member does
+// not necessarily imply the member will have the given default value.
+
+struct WithConstructor {
+  int *const ptr = nullptr;
+  WithConstructor(int *x) : ptr(x) {}
+
+  static auto compliant() {
+WithConstructor c(new int);
+return *(c.ptr); // no warning
+  }
+
+  static auto compliantWithParam(WithConstructor c) {
+return *(c.ptr); // no warning
+  }
+
+  static auto issue() {
+WithConstructor c(nullptr);
+return *(c.ptr); // expected-warning{{Dereference of null pointer (loaded from field 'ptr')}}
+  }
+};
+
+struct RegularAggregate {
+  int *const ptr = nullptr;
+
+  static int compliant() {
+RegularAggregate c{new int};
+return *(c.ptr); // no warning
+  }
+
+  static int issue() {
+RegularAggregate c;
+return *(c.ptr); // expected-warning{{Dereference of null pointer (loaded from field 'ptr')}}
+  }
+};
+
+struct WithConstructorAndArithmetic {
+  int const i = 0;
+  WithConstructorAndArithmetic(int x) : i(x + 1) {}
+
+  static int compliant(int y) {
+WithConstructorAndArithmetic c(0);
+return y / c.i; // no warning
+  }
+
+  static int issue(int y) {
+WithConstructorAndArithmetic c(-1);
+return y / c.i; // expected-warning{{Division by zero}}
+  }
+};
+
+struct WithConstructorDeclarationOnly {
+  int const i = 0;
+  WithConstructorDeclarationOnly(int x); // definition not visible.
+
+  static int compliant1(int y) {
+WithConstructorDeclarationOnly c(0);
+return y / c.i; // no warning
+  }
+
+  static int compliant2(int y) {
+WithConstructorDeclarationOnly c(-1);
+return y / c.i; // no warning
+  }
+};
+
+// NonAggregateFP is not an aggregate (j is a private non-static field) and has no custom constructor.
+// So we know i and j will always be 0 and 42, respectively.
+// That being said, this is not implemented because it is deemed too rare to be worth the complexity.
+struct NonAggregateFP {
+public:
+  int const i = 0;
+
+private:
+  int const j = 42;
+
+public:
+  static int falsePositive1(NonAggregateFP c) {
+return 10 / c.i; // Currently, no warning.
+  }
+
+  static int falsePositive2(NonAggregateFP c) {
+return 10 / (c.j - 42); // Currently, no warning.
+  }
+};
+
+struct NonAggregate {
+public:
+  int const i = 0;
+
+private:
+  int const j = 42;
+
+  NonAggregate(NonAggregate const &); // not provided, could set i and j to arbitrary values.
+
+public:
+  static int compliant1(NonAggregate c) {
+return 10 / c.i; // no warning
+  }
+
+  static int compliant2(NonAggregate c) {
+return 10 / (c.j - 42); // no warning
+  }
+};
+
+struct WithStaticMember {
+  static int const i = 0;
+
+  static int issue1(WithStaticMember c) {
+return 10 / c.i; // expected-warning{{division by zero is undefined}} expected-warning{{Division by zero}}
+  }
+
+  static int issue2() {
+return 10 / WithStaticMember::i; // expected-warning{{division by zero is undefined}} expected-warning{{Division by zero}}
+  }
+};
Index: clang/lib/StaticAnalyzer/Core/RegionStore.cpp
===
--- clang/lib/StaticAnalyzer/Core/RegionStore.cpp
+++ clang/lib/StaticAnalyzer/Core/RegionStore.cpp
@@ -1983,15 +1983,9 @@
   if (const Optional &V = B.getDirectBinding(R))
 return *V;
 
-  // Is the field declared constant and has an in-class initializer?
+  // If the containing record was initialized, try to get its constant value.
   const FieldDecl *FD = R->getDecl();
   QualType Ty = FD->getType();
-  if (Ty.isConstQualified())
-if (const Expr *Init = FD->getInClassInitializer())
-  if (Opti

[PATCH] D124658: CSA Normalize SymIntExpr so the RHS is positive when possible

2022-04-29 Thread Tomasz Kamiński via Phabricator via cfe-commits
tomasz-kaminski-sonarsource created this revision.
tomasz-kaminski-sonarsource added reviewers: vsavchenko, NoQ, steakhal.
Herald added a subscriber: martong.
Herald added a project: All.
tomasz-kaminski-sonarsource requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

This PR changes the SymIntExpr so the expression that uses
negative value as RHS, for example: x +/- (-N), are modeled as
as x -/+ N. This avoid producing very large RHS in case when the
symbol is cased to unsigned number, and as consequence makes the
value more robust in presence of cast.
This change is not apllied if N is lowest negative value for
which negation would not be representable.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D124658

Files:
  clang/lib/StaticAnalyzer/Core/SimpleSValBuilder.cpp
  clang/test/Analysis/additive-op-on-sym-int-expr.c
  clang/test/Analysis/expr-inspection.c

Index: clang/test/Analysis/expr-inspection.c
===
--- clang/test/Analysis/expr-inspection.c
+++ clang/test/Analysis/expr-inspection.c
@@ -11,7 +11,7 @@
 
 void foo(int x) {
   clang_analyzer_dump(x); // expected-warning{{reg_$0}}
-  clang_analyzer_dump(x + (-1)); // expected-warning{{(reg_$0) + -1}}
+  clang_analyzer_dump(x + (-1)); // expected-warning{{(reg_$0) - 1}}
   int y = 1;
   for (; y < 3; ++y) {
 clang_analyzer_numTimesReached(); // expected-warning{{2}}
Index: clang/test/Analysis/additive-op-on-sym-int-expr.c
===
--- /dev/null
+++ clang/test/Analysis/additive-op-on-sym-int-expr.c
@@ -0,0 +1,53 @@
+// RUN: %clang_analyze_cc1 -analyzer-checker=core,debug.ExprInspection -analyzer-config eagerly-assume=false -verify %s
+
+void clang_analyzer_dump(int);
+void clang_analyzer_dumpL(long);
+void clang_analyzer_warnIfReached();
+
+void testInspect(int x) {
+  if ((x < 10) || (x > 100)) {
+return;
+  }
+
+  int i = x + 1;
+  long l = i - 10U;
+  clang_analyzer_dump(i);   // expected-warning {{(reg_$0) + 1}}
+  clang_analyzer_dumpL(l);  // expected-warning {{(reg_$0) - 9U}}
+  clang_analyzer_dumpL(l + 0L); // expected-warning {{(reg_$0) - 9}}
+  if ((l - 1000) > 0) {
+clang_analyzer_warnIfReached();
+  }
+  if (l > 1000) {
+clang_analyzer_warnIfReached();
+  }
+  if (l > 1000L) {
+clang_analyzer_warnIfReached();
+  }
+  if ((l + 0L) > 1000) {
+clang_analyzer_warnIfReached();
+  }
+
+  i = x - 1;
+  l = i + 10U;
+  clang_analyzer_dump(i);  // expected-warning {{(reg_$0) - 1}}
+  clang_analyzer_dumpL(l); // expected-warning {{(reg_$0) + 9U}}
+
+  l = -1l;
+  i = l;
+  clang_analyzer_dump(x + i); // expected-warning {{(reg_$0) - 1}}
+}
+
+void testMin(int i, long long l) {
+  clang_analyzer_dump(i + (-1));  // expected-warning {{(reg_$0) - 1}}
+  clang_analyzer_dump(i - (-1));  // expected-warning {{(reg_$0) + 1}}
+  clang_analyzer_dumpL(l + (-1)); // expected-warning {{(reg_$1) - 1}}
+  clang_analyzer_dumpL(l - (-1)); // expected-warning {{(reg_$1) + 1}}
+
+  int intMin = 1 << (sizeof(int) * 8 - 1); // INT_MIN, negative value is not representable
+  // Do not normalize representation if negation would not be representable
+  clang_analyzer_dump(i + intMin); // expected-warning {{(reg_$0) + -2147483648}}
+  clang_analyzer_dump(i - intMin); // expected-warning {{(reg_$0) - -2147483648}}
+  // Produced value has higher bit with (long) so negation if representable
+  clang_analyzer_dumpL(l + intMin); // expected-warning {{(reg_$1) - 2147483648}}
+  clang_analyzer_dumpL(l - intMin); // expected-warning {{(reg_$1) + 2147483648}}
+}
Index: clang/lib/StaticAnalyzer/Core/SimpleSValBuilder.cpp
===
--- clang/lib/StaticAnalyzer/Core/SimpleSValBuilder.cpp
+++ clang/lib/StaticAnalyzer/Core/SimpleSValBuilder.cpp
@@ -197,8 +197,30 @@
   if (RHS.isSigned() && !SymbolType->isSignedIntegerOrEnumerationType())
 ConvertedRHS = &BasicVals.Convert(SymbolType, RHS);
 }
-  } else
+  } else if (BinaryOperator::isAdditiveOp(op)) {
+// Change a+(-N) into a-N, and a-(-N) into a+N
+// Adjust addition/subtraction of negative value, to
+// subtraction/addition of the negated value.
+if (!RHS.isNegative()) {
+  ConvertedRHS = &BasicVals.Convert(resultTy, RHS);
+} else {
+  APSIntType resultIntTy = BasicVals.getAPSIntType(resultTy);
+  assert(resultIntTy.getBitWidth() >= RHS.getBitWidth() &&
+ "The result operation type must have at least the same "
+ "number of bits as its operands.");
+
+  llvm::APSInt ConvertedRHSValue = resultIntTy.convert(RHS);
+  // Check if the negation of the RHS is representable,
+  // i.e., the resultTy is signed, and it is not the lowest
+  // representable negative value.
+  if (ConvertedRHSValue > resultIntTy.getMinValue()) {
+ConvertedRHS = &BasicVals.getValue(-Conv

[PATCH] D124658: CSA Normalize SymIntExpr so the RHS is positive when possible

2022-04-29 Thread Tomasz Kamiński via Phabricator via cfe-commits
tomasz-kaminski-sonarsource added a comment.

Without the changes, out of the following unsatisfiable conditions:
A) `(l - 1000) > 0`
B) `l > 1000`
C) `l > 1000L`
D) `(l + 0L) > 1000`
CSA was considering A and B to satisable. The `l` is `(long)(x + 1 - 10U)` and 
`x` is in range `[10, 100]` so no overflow happens.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124658

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


[PATCH] D124638: [clang] Track how headers get included generally during lookup time

2022-04-29 Thread Jan Svoboda via Phabricator via cfe-commits
jansvoboda11 requested changes to this revision.
jansvoboda11 added a comment.
This revision now requires changes to proceed.

Can you describe how come the check is not reliable without this patch? It 
might be worth fixing the underlying reason for the unreliability first.




Comment at: clang/include/clang/Lex/HeaderSearch.h:121
+  /// Alias that this header is known as.
+  llvm::SmallString<64> Alias;
+

I think `HeaderFileInfo` is supposed to be very small, hence the bit packing. 
Adding `SmallString` here might negatively impact performance. See 
https://reviews.llvm.org/D104344#inline-1039503

Note that `HeaderFileInfo` used to track aliases, but does not anymore: 
https://reviews.llvm.org/D123885


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124638

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


[PATCH] D124638: [clang] Track how headers get included generally during lookup time

2022-04-29 Thread Thorsten via Phabricator via cfe-commits
tschuett added inline comments.



Comment at: clang/lib/Lex/HeaderSearch.cpp:1036
+
+// This file is a system header or C++ unfriendly if the dir is.
 HFI.DirInfo = CurDir->getDirCharacteristic();

Why did the comment move?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124638

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


[PATCH] D124659: [analyzer][docs] Document alpha.security.cert.pos.34c limitations

2022-04-29 Thread Balázs Benics via Phabricator via cfe-commits
steakhal created this revision.
steakhal added reviewers: martong, NoQ.
Herald added subscribers: manas, ASDenysPetrov, dkrupp, donat.nagy, Szelethus, 
mikhail.ramalho, a.sidorin, rnkovacs, szepet, baloghadamsoftware, xazax.hun.
Herald added a project: All.
steakhal 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/D124659

Files:
  clang/docs/analyzer/checkers.rst


Index: clang/docs/analyzer/checkers.rst
===
--- clang/docs/analyzer/checkers.rst
+++ clang/docs/analyzer/checkers.rst
@@ -2268,6 +2268,25 @@
 return putenv(env); // putenv function should not be called with auto 
variables
   }
 
+Limitations:
+
+   - Technically, one can pass automatic variables to ``putenv``,
+ but one needs to ensure that the given environment key stays
+ alive until it's removed or overwritten.
+ Since the analyzer cannot keep track of which envvars get overwritten
+ and when, it needs to be slightly more aggressive and warn for such
+ cases too, leading in some cases to false-positive reports like this:
+
+ .. code-block:: c
+
+void baz() {
+  char env[] = "NAME=value";
+  putenv(env); // false-positive warning: putenv function should not 
be called...
+  // More code...
+  putenv((char *)"NAME=anothervalue");
+  // This putenv call overwrites the previous entry, thus that can no 
longer dangle.
+} // 'env' array becomes dead only here.
+
 alpha.security.cert.env
 ^^^
 


Index: clang/docs/analyzer/checkers.rst
===
--- clang/docs/analyzer/checkers.rst
+++ clang/docs/analyzer/checkers.rst
@@ -2268,6 +2268,25 @@
 return putenv(env); // putenv function should not be called with auto variables
   }
 
+Limitations:
+
+   - Technically, one can pass automatic variables to ``putenv``,
+ but one needs to ensure that the given environment key stays
+ alive until it's removed or overwritten.
+ Since the analyzer cannot keep track of which envvars get overwritten
+ and when, it needs to be slightly more aggressive and warn for such
+ cases too, leading in some cases to false-positive reports like this:
+
+ .. code-block:: c
+
+void baz() {
+  char env[] = "NAME=value";
+  putenv(env); // false-positive warning: putenv function should not be called...
+  // More code...
+  putenv((char *)"NAME=anothervalue");
+  // This putenv call overwrites the previous entry, thus that can no longer dangle.
+} // 'env' array becomes dead only here.
+
 alpha.security.cert.env
 ^^^
 
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D124659: [analyzer][docs] Document alpha.security.cert.pos.34c limitations

2022-04-29 Thread Balázs Benics via Phabricator via cfe-commits
steakhal added a comment.

PS: the html docs compile and look great.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124659

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


[PATCH] D124621: CPP-2461 [Analyzer] Fix assumptions about const field with member-initializer

2022-04-29 Thread Balázs Benics via Phabricator via cfe-commits
steakhal accepted this revision.
steakhal added a comment.
This revision is now accepted and ready to land.

LGTM

In D124621#3481906 , @mantognini 
wrote:

> One thing I'm not sure about and couldn't easily find in the doc is how to 
> reference in the commit message the bug (https://llvm.org/PR48534) this patch 
> fixes. Is it good as is?

AFAIK we should prefer GitHub issue numbers to the old BugZilla numbers.
Could you please update all references of `48534` -> `47878`.

In addition, I think `Fixes #47878` should work in the commit message, and 
automatically close the given GitHub issue.

Please wait for another accept. If you don't get one let's say for a week, just 
commit it as-is.

BTW have you measured the observable impact of this patch on large codebases? 
Do you have any stats?




Comment at: clang/test/Analysis/cxx-member-initializer-const-field.cpp:83
+  static int falsePositive1(NonAggregateFP c) {
+return 10 / c.i; // Currently, no warning.
+  }





Comment at: clang/test/Analysis/cxx-member-initializer-const-field.cpp:87
+  static int falsePositive2(NonAggregateFP c) {
+return 10 / (c.j - 42); // Currently, no warning.
+  }




Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124621

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


[PATCH] D124621: CPP-2461 [Analyzer] Fix assumptions about const field with member-initializer

2022-04-29 Thread Balázs Benics via Phabricator via cfe-commits
steakhal added a comment.

Noq wrote 
https://github.com/llvm/llvm-project/issues/47878#issuecomment-981036634

> Aha, uhm, yeah, i see. The static analyzer indeed thinks that a combination 
> of "const" and a field initializer causes the field to forever stay that way. 
> **We'll need to undo this relatively recently added shortcut.**

What "recently added shortcut" did he mention? Could you please refer to that 
commit in the patch summary, please?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124621

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


[PATCH] D103096: [analyzer] Implement cast for ranges of symbolic integers

2022-04-29 Thread Gabor Marton via Phabricator via cfe-commits
martong added a comment.

Giving it some more thought, the `SymCastMap = Map` should 
be keyed as well with an equivalence class : `SymCastMap = 
Map`. This is the only way to use the equivalence 
info correctly when we process the casts.




Comment at: clang/lib/StaticAnalyzer/Core/RangeConstraintManager.cpp:889-890
 
+REGISTER_MAP_FACTORY_WITH_PROGRAMSTATE(CastMap, uint32_t /*bitwidth*/, 
RangeSet)
+REGISTER_MAP_WITH_PROGRAMSTATE(SymCastMap, SymbolRef, CastMap)
+

NoQ wrote:
> These maps will need to be cleaned up when symbols become dead (as in 
> `RangeConstraintManager::removeDeadBindings()`).
Yes, the same way as we clean up e.g. the `DisequalityMap`.


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

https://reviews.llvm.org/D103096

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


[PATCH] D124613: In MSVC compatibility mode, friend function declarations behave as function declarations

2022-04-29 Thread Fred Tingaud via Phabricator via cfe-commits
frederic-tingaud-sonarsource added a comment.

@rnk I don't have the rights to merge. Could you do it when you have the time?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124613

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


[PATCH] D124659: [analyzer][docs] Document alpha.security.cert.pos.34c limitations

2022-04-29 Thread Gabor Marton via Phabricator via cfe-commits
martong accepted this revision.
martong 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/D124659/new/

https://reviews.llvm.org/D124659

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


[PATCH] D124164: [include-cleaner] Include-cleaner library structure, and simplistic AST walking.

2022-04-29 Thread Sam McCall via Phabricator via cfe-commits
sammccall marked 2 inline comments as done.
sammccall added inline comments.



Comment at: clang-tools-extra/include-cleaner/lib/WalkAST.cpp:18
+class ASTWalker : public RecursiveASTVisitor {
+  DeclCallback Callback;
+

CJ-Johnson wrote:
> Apologies for my ignorance of LLVM style. Should this be named with a 
> trailing underscore? And should it be a private field?
no, LLVM members are named the same way as locals and classes. (Yes, it's 
awful).

It is already a private field: members of classes are private by default (the 
difference between classes and structs). Google style requires private members 
to be after public ones (and thus `private:` is always present), but LLVM 
doesn't require this.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124164

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


[clang] 41ac245 - [include-cleaner] Include-cleaner library structure, and simplistic AST walking.

2022-04-29 Thread Sam McCall via cfe-commits

Author: Sam McCall
Date: 2022-04-29T11:04:11+02:00
New Revision: 41ac245c10fc256c96c45cb874918a3bd5665369

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

LOG: [include-cleaner] Include-cleaner library structure, and simplistic AST 
walking.

Include-cleaner is a library that uses the clang AST and preprocessor to
determine which headers are used. It will be used in clang-tidy, in
clangd, in a standalone tool at least for testing, and in out-of-tree tools.

Roughly, it walks the AST, finds referenced decls, maps these to
used sourcelocations, then to FileEntrys, then matching these against #includes.
However there are many wrinkles: dealing with macros, standard library
symbols, umbrella headers, IWYU directives etc.

It is not built on the C++20 modules concept of usage, to allow:
 - use with existing non-modules codebases
 - a flexible API embeddable in clang-tidy, clangd, and other tools
 - avoiding a chicken-and-egg problem where include cleanups are needed
   before modules can be adopted

This library is based on existing functionality in clangd that provides
an unused-include warning. However it has design changes:
 - it accommodates diagnosing missing includes too (this means tracking
   where references come from, not just the set of targets)
 - it more clearly separates the different mappings
   (symbol => location => header => include) for better testing
 - it handles special cases like standard library symbols and IWYU directives
   more elegantly by adding unified Location and Header types instead of
   side-tables
 - it will support some customization of policy where necessary (e.g.
   for style questions of what constitutes a use, or to allow
   both missing-include and unused-include modes to be conservative)

This patch adds the basic directory structure under clang-tools-extra
and a skeleton version of the AST traversal, which will be the central
piece.
A more end-to-end prototype is in https://reviews.llvm.org/D122677

RFC: 
https://discourse.llvm.org/t/rfc-lifting-include-cleaner-missing-unused-include-detection-out-of-clangd/61228

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

Added: 
clang-tools-extra/include-cleaner/CMakeLists.txt
clang-tools-extra/include-cleaner/README.md
clang-tools-extra/include-cleaner/lib/AnalysisInternal.h
clang-tools-extra/include-cleaner/lib/CMakeLists.txt
clang-tools-extra/include-cleaner/lib/WalkAST.cpp
clang-tools-extra/include-cleaner/test/CMakeLists.txt
clang-tools-extra/include-cleaner/test/Unit/lit.cfg.py
clang-tools-extra/include-cleaner/test/Unit/lit.site.cfg.py.in
clang-tools-extra/include-cleaner/test/lit.cfg.py
clang-tools-extra/include-cleaner/test/lit.site.cfg.py.in
clang-tools-extra/include-cleaner/unittests/CMakeLists.txt
clang-tools-extra/include-cleaner/unittests/WalkASTTest.cpp

Modified: 
clang-tools-extra/CMakeLists.txt
clang/include/clang/Testing/TestAST.h
clang/lib/Testing/TestAST.cpp

Removed: 




diff  --git a/clang-tools-extra/CMakeLists.txt 
b/clang-tools-extra/CMakeLists.txt
index 285e5529e6fc6..4c1d4ada567f9 100644
--- a/clang-tools-extra/CMakeLists.txt
+++ b/clang-tools-extra/CMakeLists.txt
@@ -14,6 +14,7 @@ add_subdirectory(clang-doc)
 add_subdirectory(clang-include-fixer)
 add_subdirectory(clang-move)
 add_subdirectory(clang-query)
+add_subdirectory(include-cleaner)
 add_subdirectory(pp-trace)
 add_subdirectory(pseudo)
 add_subdirectory(tool-template)

diff  --git a/clang-tools-extra/include-cleaner/CMakeLists.txt 
b/clang-tools-extra/include-cleaner/CMakeLists.txt
new file mode 100644
index 0..0550b02f603b5
--- /dev/null
+++ b/clang-tools-extra/include-cleaner/CMakeLists.txt
@@ -0,0 +1,5 @@
+add_subdirectory(lib)
+if(CLANG_INCLUDE_TESTS)
+  add_subdirectory(test)
+  add_subdirectory(unittests)
+endif()

diff  --git a/clang-tools-extra/include-cleaner/README.md 
b/clang-tools-extra/include-cleaner/README.md
new file mode 100644
index 0..e69de29bb2d1d

diff  --git a/clang-tools-extra/include-cleaner/lib/AnalysisInternal.h 
b/clang-tools-extra/include-cleaner/lib/AnalysisInternal.h
new file mode 100644
index 0..8b0c73fe7997b
--- /dev/null
+++ b/clang-tools-extra/include-cleaner/lib/AnalysisInternal.h
@@ -0,0 +1,47 @@
+//===--- AnalysisInternal.h - Analysis building blocks - 
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 provides smaller, testable pieces of the used-header analysis.
+// We find the headers by chainin

[PATCH] D124164: [include-cleaner] Include-cleaner library structure, and simplistic AST walking.

2022-04-29 Thread Sam McCall via Phabricator via cfe-commits
This revision was landed with ongoing or failed builds.
This revision was automatically updated to reflect the committed changes.
sammccall marked an inline comment as done.
Closed by commit rG41ac245c10fc: [include-cleaner] Include-cleaner library 
structure, and simplistic AST walking. (authored by sammccall).

Changed prior to commit:
  https://reviews.llvm.org/D124164?vs=424168&id=425991#toc

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124164

Files:
  clang-tools-extra/CMakeLists.txt
  clang-tools-extra/include-cleaner/CMakeLists.txt
  clang-tools-extra/include-cleaner/README.md
  clang-tools-extra/include-cleaner/lib/AnalysisInternal.h
  clang-tools-extra/include-cleaner/lib/CMakeLists.txt
  clang-tools-extra/include-cleaner/lib/WalkAST.cpp
  clang-tools-extra/include-cleaner/test/CMakeLists.txt
  clang-tools-extra/include-cleaner/test/Unit/lit.cfg.py
  clang-tools-extra/include-cleaner/test/Unit/lit.site.cfg.py.in
  clang-tools-extra/include-cleaner/test/lit.cfg.py
  clang-tools-extra/include-cleaner/test/lit.site.cfg.py.in
  clang-tools-extra/include-cleaner/unittests/CMakeLists.txt
  clang-tools-extra/include-cleaner/unittests/WalkASTTest.cpp
  clang/include/clang/Testing/TestAST.h
  clang/lib/Testing/TestAST.cpp

Index: clang/lib/Testing/TestAST.cpp
===
--- clang/lib/Testing/TestAST.cpp
+++ clang/lib/Testing/TestAST.cpp
@@ -105,6 +105,10 @@
   auto VFS = llvm::makeIntrusiveRefCnt();
   VFS->addFile(Filename, /*ModificationTime=*/0,
llvm::MemoryBuffer::getMemBufferCopy(In.Code, Filename));
+  for (const auto &Extra : In.ExtraFiles)
+VFS->addFile(
+Extra.getKey(), /*ModificationTime=*/0,
+llvm::MemoryBuffer::getMemBufferCopy(Extra.getValue(), Extra.getKey()));
   Clang->createFileManager(VFS);
 
   // Running the FrontendAction creates the other components: SourceManager,
Index: clang/include/clang/Testing/TestAST.h
===
--- clang/include/clang/Testing/TestAST.h
+++ clang/include/clang/Testing/TestAST.h
@@ -45,6 +45,10 @@
   /// Extra argv to pass to clang -cc1.
   std::vector ExtraArgs = {};
 
+  /// Extra virtual files that are available to be #included.
+  /// Keys are plain filenames ("foo.h"), values are file content.
+  llvm::StringMap ExtraFiles = {};
+
   /// By default, error diagnostics during parsing are reported as gtest errors.
   /// To suppress this, set ErrorOK or include "error-ok" in a comment in Code.
   /// In either case, all diagnostics appear in TestAST::diagnostics().
Index: clang-tools-extra/include-cleaner/unittests/WalkASTTest.cpp
===
--- /dev/null
+++ clang-tools-extra/include-cleaner/unittests/WalkASTTest.cpp
@@ -0,0 +1,110 @@
+#include "AnalysisInternal.h"
+#include "clang/AST/ASTContext.h"
+#include "clang/Basic/FileManager.h"
+#include "clang/Frontend/TextDiagnostic.h"
+#include "clang/Testing/TestAST.h"
+#include "llvm/Support/Error.h"
+#include "llvm/Testing/Support/Annotations.h"
+#include "gtest/gtest.h"
+
+namespace clang {
+namespace include_cleaner {
+namespace {
+
+// Specifies a test of which symbols are referenced by a piece of code.
+//
+// Example:
+//   Target:  int ^foo();
+//   Referencing: int x = ^foo();
+// There must be exactly one referencing location marked.
+void testWalk(llvm::StringRef TargetCode, llvm::StringRef ReferencingCode) {
+  llvm::Annotations Target(TargetCode);
+  llvm::Annotations Referencing(ReferencingCode);
+
+  TestInputs Inputs(Referencing.code());
+  Inputs.ExtraFiles["target.h"] = Target.code().str();
+  Inputs.ExtraArgs.push_back("-include");
+  Inputs.ExtraArgs.push_back("target.h");
+  TestAST AST(Inputs);
+  const auto &SM = AST.sourceManager();
+
+  // We're only going to record references from the nominated point,
+  // to the target file.
+  FileID ReferencingFile = SM.getMainFileID();
+  SourceLocation ReferencingLoc =
+  SM.getComposedLoc(ReferencingFile, Referencing.point());
+  FileID TargetFile = SM.translateFile(
+  llvm::cantFail(AST.fileManager().getFileRef("target.h")));
+
+  // Perform the walk, and capture the offsets of the referenced targets.
+  std::vector ReferencedOffsets;
+  for (Decl *D : AST.context().getTranslationUnitDecl()->decls()) {
+if (ReferencingFile != SM.getDecomposedExpansionLoc(D->getLocation()).first)
+  continue;
+walkAST(*D, [&](SourceLocation Loc, NamedDecl &ND) {
+  if (SM.getFileLoc(Loc) != ReferencingLoc)
+return;
+  auto NDLoc = SM.getDecomposedLoc(SM.getFileLoc(ND.getLocation()));
+  if (NDLoc.first != TargetFile)
+return;
+  ReferencedOffsets.push_back(NDLoc.second);
+});
+  }
+  llvm::sort(ReferencedOffsets);
+
+  // Compare results to the expected points.
+  // For each difference, show the target point in c

[PATCH] D121838: Generalize "check-all" umbrella targets, use for check-clang-tools

2022-04-29 Thread Sam McCall via Phabricator via cfe-commits
sammccall updated this revision to Diff 425995.
sammccall added a comment.

re-trigger CI


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D121838

Files:
  clang-tools-extra/CMakeLists.txt
  clang-tools-extra/test/CMakeLists.txt
  clang/CMakeLists.txt
  clang/bindings/python/tests/CMakeLists.txt
  clang/runtime/CMakeLists.txt
  compiler-rt/test/CMakeLists.txt
  llvm/CMakeLists.txt
  llvm/cmake/modules/AddLLVM.cmake
  llvm/runtimes/CMakeLists.txt
  runtimes/CMakeLists.txt
  runtimes/Tests.cmake.in

Index: runtimes/Tests.cmake.in
===
--- runtimes/Tests.cmake.in
+++ runtimes/Tests.cmake.in
@@ -1,3 +1,3 @@
-set(SUB_LIT_TESTSUITES @RUNTIMES_LIT_TESTSUITES@)
-set(SUB_LIT_PARAMS @RUNTIMES_LIT_PARAMS@)
-set(SUB_LIT_EXTRA_ARGS @RUNTIMES_LIT_EXTRA_ARGS@)
+set(SUB_LIT_TESTSUITES @LLVM_RUNTIMES_LIT_TESTSUITES@)
+set(SUB_LIT_PARAMS @LLVM_RUNTIMES_LIT_PARAMS@)
+set(SUB_LIT_EXTRA_ARGS @LLVM_RUNTIMES_LIT_EXTRA_ARGS@)
Index: runtimes/CMakeLists.txt
===
--- runtimes/CMakeLists.txt
+++ runtimes/CMakeLists.txt
@@ -176,6 +176,8 @@
 set(LIT_ARGS_DEFAULT "${LIT_ARGS_DEFAULT} --no-progress-bar")
   endif()
   set(LLVM_LIT_ARGS "${LIT_ARGS_DEFAULT}" CACHE STRING "Default options for lit")
+
+  umbrella_lit_testsuite_begin(check-runtimes)
 endif()
 
 # llvm-libgcc incorporates both compiler-rt and libunwind as subprojects with very
@@ -200,36 +202,13 @@
 foreach(entry ${runtimes})
   get_filename_component(projName ${entry} NAME)
 
-  # Between each sub-project we want to cache and clear the LIT properties
-  set_property(GLOBAL PROPERTY LLVM_LIT_TESTSUITES)
-  set_property(GLOBAL PROPERTY LLVM_LIT_PARAMS)
-  set_property(GLOBAL PROPERTY LLVM_LIT_DEPENDS)
-  set_property(GLOBAL PROPERTY LLVM_LIT_EXTRA_ARGS)
-
   add_subdirectory(${entry} ${projName})
-
-  get_property(LLVM_LIT_TESTSUITES GLOBAL PROPERTY LLVM_LIT_TESTSUITES)
-  get_property(LLVM_LIT_PARAMS GLOBAL PROPERTY LLVM_LIT_PARAMS)
-  get_property(LLVM_LIT_DEPENDS GLOBAL PROPERTY LLVM_LIT_DEPENDS)
-  get_property(LLVM_LIT_EXTRA_ARGS GLOBAL PROPERTY LLVM_LIT_EXTRA_ARGS)
-
-  list(APPEND RUNTIMES_LIT_TESTSUITES ${LLVM_LIT_TESTSUITES})
-  list(APPEND RUNTIMES_LIT_PARAMS ${LLVM_LIT_PARAMS})
-  list(APPEND RUNTIMES_LIT_DEPENDS ${LLVM_LIT_DEPENDS})
-  list(APPEND RUNTIMES_LIT_EXTRA_ARGS ${LLVM_LIT_EXTRA_ARGS})
 endforeach()
 
 if(LLVM_INCLUDE_TESTS)
   # Add a global check rule now that all subdirectories have been traversed
   # and we know the total set of lit testsuites.
-  add_lit_target(check-runtimes
-"Running all regression tests"
-${RUNTIMES_LIT_TESTSUITES}
-PARAMS ${RUNTIMES_LIT_PARAMS}
-DEPENDS ${RUNTIMES_LIT_DEPENDS}
-ARGS ${RUNTIMES_LIT_EXTRA_ARGS}
-)
-  add_custom_target(runtimes-test-depends DEPENDS ${RUNTIMES_LIT_DEPENDS})
+  umbrella_lit_testsuite_end(check-runtimes)
 
   if (NOT HAVE_LLVM_LIT)
 # If built by manually invoking cmake on this directory, we don't have
Index: llvm/runtimes/CMakeLists.txt
===
--- llvm/runtimes/CMakeLists.txt
+++ llvm/runtimes/CMakeLists.txt
@@ -222,9 +222,9 @@
   if(LLVM_INCLUDE_TESTS)
 include(${LLVM_BINARY_DIR}/runtimes/Tests.cmake OPTIONAL)
 set_property(DIRECTORY APPEND PROPERTY CMAKE_CONFIGURE_DEPENDS ${LLVM_BINARY_DIR}/runtimes/Tests.cmake)
-set_property(GLOBAL APPEND PROPERTY LLVM_LIT_TESTSUITES ${SUB_LIT_TESTSUITES})
-set_property(GLOBAL APPEND PROPERTY LLVM_LIT_PARAMS ${SUB_LIT_PARAMS})
-set_property(GLOBAL APPEND PROPERTY LLVM_LIT_EXTRA_ARGS ${SUB_LIT_EXTRA_ARGS})
+set_property(GLOBAL APPEND PROPERTY LLVM_ALL_LIT_TESTSUITES ${SUB_LIT_TESTSUITES})
+set_property(GLOBAL APPEND PROPERTY LLVM_ALL_LIT_PARAMS ${SUB_LIT_PARAMS})
+set_property(GLOBAL APPEND PROPERTY LLVM_ALL_LIT_EXTRA_ARGS ${SUB_LIT_EXTRA_ARGS})
 list(APPEND test_targets runtimes-test-depends check-runtimes)
   endif()
 
@@ -304,9 +304,9 @@
   if(LLVM_INCLUDE_TESTS)
 include(${LLVM_BINARY_DIR}/runtimes/${name}/Tests.cmake OPTIONAL)
 set_property(DIRECTORY APPEND PROPERTY CMAKE_CONFIGURE_DEPENDS ${LLVM_BINARY_DIR}/runtimes/${name}/Tests.cmake)
-set_property(GLOBAL APPEND PROPERTY LLVM_LIT_TESTSUITES ${SUB_LIT_TESTSUITES})
-set_property(GLOBAL APPEND PROPERTY LLVM_LIT_PARAMS ${SUB_LIT_PARAMS})
-set_property(GLOBAL APPEND PROPERTY LLVM_LIT_EXTRA_ARGS ${SUB_LIT_EXTRA_ARGS})
+set_property(GLOBAL APPEND PROPERTY LLVM_ALL_LIT_TESTSUITES ${SUB_LIT_TESTSUITES})
+set_property(GLOBAL APPEND PROPERTY LLVM_ALL_LIT_PARAMS ${SUB_LIT_PARAMS})
+set_property(GLOBAL APPEND PROPERTY LLVM_ALL_LIT_EXTRA_ARGS ${SUB_LIT_EXTRA_ARGS})
 set(runtimes-test-depends-${name} runtimes-test-depends)
 set(check-runtimes-${name} check-runtimes)
 list(APPEND ${name}_test_targets runtimes-test-depends-${name} check-runtimes-$

[PATCH] D103096: [analyzer] Implement cast for ranges of symbolic integers

2022-04-29 Thread Gabor Marton via Phabricator via cfe-commits
martong added inline comments.



Comment at: clang/lib/StaticAnalyzer/Core/RangeConstraintManager.cpp:1289-1291
+  auto It = llvm::find_if(*CM, [MinBitWidth](CastMap::value_type &Item) {
+return Item.first >= MinBitWidth;
+  });

There might be a problem here because the iteration of the map is 
non-deterministic. We should probably have a copy that is sorted, or the 
container should be sorted (sorted immutable list maybe?).

Your tests below passed probably because the cast chains are too small. Could 
you please have a test, where the chain is really long (20 maybe) and shuffled.
(My thanks for @steakhal for this additional comment.)



Comment at: clang/lib/StaticAnalyzer/Core/RangeConstraintManager.cpp:2300-2303
+for (auto &Item : *CM) {
+  // Stop after reaching a bigger bitwidth.
+  if (Item.first > MinBitWidth)
+break;

Same here.



Comment at: clang/test/Analysis/symbol-integral-cast.cpp:31
+  if (!s) {
+if (x == 65537)
+  clang_analyzer_warnIfReached(); // no-warning




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

https://reviews.llvm.org/D103096

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


[PATCH] D123763: [randstruct] Enforce using a designated init for a randomized struct

2022-04-29 Thread Ties Stuij via Phabricator via cfe-commits
stuij added inline comments.



Comment at: clang/lib/Sema/SemaInit.cpp:2171
 
 if (Field == FieldEnd) {
   // We've run out of fields. We're done.

@void Unfortunately this end of fields check will break the non-designated 
initializer check below.

I GDB'ed through a failure of the below test, and if I'm understanding this 
correctly, the `CheckDesignatedInitializer` invocation above will move `Field` 
to the next available field in the struct. If there is none, we will break out 
of the loop and never reach the code below (On an AArch64 Linux host the field 
was placed last in the struct).

Instead I get a different error:

error: 'error' diagnostics expected but not seen:
  File /Users/zeno/code/llvm/clean/clang/test/Sema/init-randomized-struct.c 
Line 46: a randomized struct can only be initialized with a designated 
initializer
error: 'error' diagnostics seen but not expected:
  File /Users/zeno/code/llvm/clean/clang/test/Sema/init-randomized-struct.c 
Line 46: excess elements in struct initializer
2 errors generated.

You can replicate this on other build setups by varying the value of 
-frandomoze-layout-seed. On x86_64 Linux and on Aarch64 OSX this worked for me 
(in seed value of lit test, change `f` to `d`):
-frandomize-layout-seed=1234567890abcded

Also, I know this was talked about before, and I know a fix is planned, but 
just to add my two cents: yes, it would be great if the `std::shuffle` could be 
changed to `llvm::shuffle`, also because we're expecting to produced the same 
code across different platforms for safety (compliance) reasons.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D123763

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


[PATCH] D124666: In MSVC compatibility mode, handle unqualified templated base class initialization

2022-04-29 Thread Fred Tingaud via Phabricator via cfe-commits
frederic-tingaud-sonarsource created this revision.
frederic-tingaud-sonarsource added a reviewer: rnk.
Herald added a project: All.
frederic-tingaud-sonarsource requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

Before C++20, MSVC was supporting not mentioning the template argument of the 
base class when initializing a class inheriting a templated base class.
So the following code compiled correctly:

  template 
  class Base {
  };
  
  template 
  class Derived : public Base {
  public:
Derived() : Base() {}
  };
  
  void test() {
  Derived d;
  }

See https://godbolt.org/z/Pxxe7nccx for a conformance view.

This patch adds support for such construct when in MSVC compatibility mode.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D124666

Files:
  clang/include/clang/Basic/DiagnosticSemaKinds.td
  clang/lib/Sema/SemaDeclCXX.cpp
  clang/test/SemaTemplate/ms-unqualified-base-class.cpp

Index: clang/test/SemaTemplate/ms-unqualified-base-class.cpp
===
--- /dev/null
+++ clang/test/SemaTemplate/ms-unqualified-base-class.cpp
@@ -0,0 +1,80 @@
+// RUN: %clang_cc1 -std=c++17 -fms-compatibility -fsyntax-only -verify=before,expected %s
+// RUN: %clang_cc1 -std=c++17 -fms-compatibility -fdelayed-template-parsing -fsyntax-only -verify=before,expected %s
+// RUN: %clang_cc1 -std=c++20 -fms-compatibility -fsyntax-only -verify=after,expected %s
+// RUN: %clang_cc1 -std=c++20 -fms-compatibility -fdelayed-template-parsing -fsyntax-only -verify=after,expected %s
+
+template 
+class Base {
+};
+
+template 
+class Derived : public Base {
+public:
+  // after-error@+1 {{member initializer 'Base' does not name a non-static data member or base class}}
+  Derived() : Base() {} // before-warning {{unqualified base initializer of class templates is a Microsoft extension}}
+};
+
+template struct AggregateBase {
+  T i;
+};
+
+template
+struct  AggregateDerived : public AggregateBase {
+  int i;
+
+  // after-error@+1 {{member initializer 'AggregateBase' does not name a non-static data member or base class}}
+  AggregateDerived(T j) : AggregateBase{ 4 }, i{ j } {} // before-warning {{unqualified base initializer of class templates is a Microsoft extension}}
+  int f() {
+return i + AggregateBase::i; // expected-warning {{use of undeclared identifier 'AggregateBase'; unqualified lookup into dependent bases of class template 'AggregateDerived' is a Microsoft extension}}
+  }
+};
+
+template struct MultiTypesBase {
+};
+
+template
+struct MultiTypesDerived : public MultiTypesBase {
+  // after-error@+1 {{member initializer 'MultiTypesBase' does not name a non-static data member or base class}}
+  MultiTypesDerived() : MultiTypesBase{} {} // before-warning {{unqualified base initializer of class templates is a Microsoft extension}}
+};
+
+template struct IntegerBase {
+};
+
+template
+struct IntegerDerived : public IntegerBase {
+  // after-error@+1 {{member initializer 'IntegerBase' does not name a non-static data member or base class}}
+  IntegerDerived() : IntegerBase{} {} // before-warning {{unqualified base initializer of class templates is a Microsoft extension}}
+};
+
+template struct ConformingBase {
+  T i;
+};
+
+template
+struct  ConformingDerived : public ConformingBase {
+  int i;
+
+  ConformingDerived(T j) : ConformingBase{ 4 }, i{ j } {}
+  int f() {
+return i + ConformingBase::i;
+  }
+};
+
+int main() {
+  int I;
+  Derived t;
+
+  AggregateDerived AD{ 2 };
+  AD.AggregateBase::i = 3;
+  I = AD.f();
+
+  MultiTypesDerived MTD;
+
+  IntegerDerived<4> ID;
+
+  ConformingDerived CD{ 2 };
+  I = CD.f();
+
+  return I;
+}
Index: clang/lib/Sema/SemaDeclCXX.cpp
===
--- clang/lib/Sema/SemaDeclCXX.cpp
+++ clang/lib/Sema/SemaDeclCXX.cpp
@@ -4345,6 +4345,15 @@
 }
   }
 
+  if (getLangOpts().MSVCCompat && !getLangOpts().CPlusPlus20) {
+auto UnqualifiedBase = R.getAsSingle();
+if (UnqualifiedBase) {
+  Diag(IdLoc, diag::ext_unqualified_base_class)
+<< SourceRange(IdLoc, Init->getSourceRange().getEnd());
+  BaseType = UnqualifiedBase->getInjectedClassNameSpecialization();
+}
+  }
+
   if (!TyD && BaseType.isNull()) {
 Diag(IdLoc, diag::err_mem_init_not_member_or_class)
   << MemberOrBase << SourceRange(IdLoc,Init->getSourceRange().getEnd());
Index: clang/include/clang/Basic/DiagnosticSemaKinds.td
===
--- clang/include/clang/Basic/DiagnosticSemaKinds.td
+++ clang/include/clang/Basic/DiagnosticSemaKinds.td
@@ -5508,6 +5508,9 @@
 def ext_found_later_in_class : ExtWarn<
   "use of member %0 before its declaration is a Microsoft extension">,
   InGroup;
+def ext_unqualified_base_class : ExtWarn<
+  "unqualified base initializer of class templates is a Microsoft extensi

[PATCH] D124556: [NFC] Prevent shadowing a variable declared in `if`

2022-04-29 Thread Ken Matsui via Phabricator via cfe-commits
ken-matsui added a comment.

Thank you!


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124556

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


[PATCH] D124667: [flang][driver] Add support for consuming LLVM IR/BC files

2022-04-29 Thread Andrzej Warzynski via Phabricator via cfe-commits
awarzynski created this revision.
awarzynski added reviewers: rovka, kiranchandramohan, Leporacanthicus, 
unterumarmung, ekieri.
Herald added a subscriber: mgorny.
Herald added a reviewer: sscalpone.
Herald added projects: Flang, All.
awarzynski requested review of this revision.
Herald added subscribers: cfe-commits, jdoerfert, MaskRay.
Herald added a project: clang.

This change is mostly about making sure that Flang's driver recognises
LLVM IR and BC as supported as supported file formats. To this end,
`isFortran` is extended and renamed as `isSupportedByFlang` (the latter
better reflects the new functionality).

Some new tests are added to verify that the target triple is overridden
by the frontend driver's default or the value specified with `-triple`.
Strictly speaking, this is not a functionality that's added here.
However, this patch enables us to write such tests and hence I'm
including them here.

Depends on D124664 
Depends on D124665 


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D124667

Files:
  clang/include/clang/Driver/Types.h
  clang/lib/Driver/Driver.cpp
  clang/lib/Driver/Types.cpp
  flang/lib/Frontend/CMakeLists.txt
  flang/lib/Frontend/FrontendActions.cpp
  flang/lib/Frontend/FrontendOptions.cpp
  flang/test/Driver/emit-asm-from-llvm-bc.ll
  flang/test/Driver/emit-asm-from-llvm.ll
  flang/test/Driver/missing-triple.ll
  flang/test/Driver/override-triple.ll
  flang/test/lit.cfg.py

Index: flang/test/lit.cfg.py
===
--- flang/test/lit.cfg.py
+++ flang/test/lit.cfg.py
@@ -27,7 +27,8 @@
 # suffixes: A list of file extensions to treat as test files.
 config.suffixes = ['.c', '.cpp', '.f', '.F', '.ff', '.FOR', '.for', '.f77', '.f90', '.F90',
'.ff90', '.f95', '.F95', '.ff95', '.fpp', '.FPP', '.cuf'
-   '.CUF', '.f18', '.F18', '.fir', '.f03', '.F03', '.f08', '.F08']
+   '.CUF', '.f18', '.F18', '.fir', '.f03', '.F03', '.f08',
+   '.F08', '.ll']
 
 config.substitutions.append(('%PATH%', config.environment['PATH']))
 config.substitutions.append(('%llvmshlibdir', config.llvm_shlib_dir))
Index: flang/test/Driver/override-triple.ll
===
--- /dev/null
+++ flang/test/Driver/override-triple.ll
@@ -0,0 +1,25 @@
+; Verify that the module triple is overridden by the driver - even in the presence
+; of a module triple.
+; NOTE: At the time of writing, the tested behaviour was consistent with Clang
+
+;-
+; RUN COMMANDS
+;-
+; RUN: %flang_fc1 -S %s -o - 2>&1 | FileCheck %s
+; RUN: %flang -S  %s -o - 2>&1 | FileCheck %s
+
+;
+; EXPECTED OUTPUT
+;
+; CHECK: warning: overriding the module target triple with {{.*}}
+
+;--
+; INPUT
+;--
+; For the triple to be overridden by the driver, it needs to be different to the host triple.
+; Use a random string to guaranteed that.
+target triple = "invalid-triple"
+
+define void @foo() {
+  ret void
+}
Index: flang/test/Driver/missing-triple.ll
===
--- /dev/null
+++ flang/test/Driver/missing-triple.ll
@@ -0,0 +1,21 @@
+; Verify that the module triple is overridden by the driver - even when the
+; module triple is missing.
+; NOTE: At the time of writing, the tested behaviour was consistent with Clang
+
+;-
+; RUN COMMANDS
+;-
+; RUN: %flang_fc1 -S %s -o - 2>&1 | FileCheck %s
+; RUN: %flang -S  %s -o - 2>&1 | FileCheck %s
+
+;
+; EXPECTED OUTPUT
+;
+; CHECK: warning: overriding the module target triple with {{.*}}
+
+;--
+; INPUT
+;--
+define void @foo() {
+  ret void
+}
Index: flang/test/Driver/emit-asm-from-llvm.ll
===
--- /dev/null
+++ flang/test/Driver/emit-asm-from-llvm.ll
@@ -0,0 +1,23 @@
+; Verify that the driver can consume LLVM IR files. The expected assembly is ;
+; fairly generic (verified on AArch64 an X86_64), but we may need to tweak when
+; testing on other platforms. Note that that the actual output doesn't matter
+; as long as it's in Assembly format.
+
+;-
+; RUN COMMANDS
+;-
+; RUN: %flang_fc1 -S %s -o - | FileCheck %s
+; RUN: %flang -S  %s -o - | FileCheck %s
+
+;
+; EXPECTED OUTPUT
+;
+; CHECK-LABEL: foo:
+; CHECK: ret
+
+;--
+; INPUT
+;--
+define void @foo() {
+  ret void
+}
Index: flang/test/Driver/emit-asm-from-llvm-bc.ll
===
--- /dev/null
+++ flang/test/Driver/emit-asm-from-llvm-bc.ll
@@ -0,0 +1,30 @@
+; Verify that the driver can consume LLVM BC files. The expected assembly is
+; fairly (tested on AArch64 an X86_64), but we may need to tweak when testing
+; on other platforms. Note that that 

[PATCH] D124164: [include-cleaner] Include-cleaner library structure, and simplistic AST walking.

2022-04-29 Thread Simon Pilgrim via Phabricator via cfe-commits
RKSimon added a comment.

@sammccall It looks like this is causing a link error on some PPC builds: 
https://lab.llvm.org/buildbot/#/builders/57/builds/17387


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124164

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


[clang-tools-extra] 97b6c92 - [include-cleaner] Add missing deps from unittests

2022-04-29 Thread via cfe-commits

Author: Sam McCall
Date: 2022-04-29T13:08:28+02:00
New Revision: 97b6c92dcd56937bc27de7c4c08381fc71c402e7

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

LOG: [include-cleaner] Add missing deps from unittests

Added: 


Modified: 
clang-tools-extra/include-cleaner/unittests/CMakeLists.txt

Removed: 




diff  --git a/clang-tools-extra/include-cleaner/unittests/CMakeLists.txt 
b/clang-tools-extra/include-cleaner/unittests/CMakeLists.txt
index fe33c3bcd137..0cbbefcdd611 100644
--- a/clang-tools-extra/include-cleaner/unittests/CMakeLists.txt
+++ b/clang-tools-extra/include-cleaner/unittests/CMakeLists.txt
@@ -14,7 +14,9 @@ target_include_directories(ClangIncludeCleanerTests
 
 clang_target_link_libraries(ClangIncludeCleanerTests
   PRIVATE
+  clangAST
   clangBasic
+  clangFrontend
   )
 
 target_link_libraries(ClangIncludeCleanerTests



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


[PATCH] D124164: [include-cleaner] Include-cleaner library structure, and simplistic AST walking.

2022-04-29 Thread Sam McCall via Phabricator via cfe-commits
sammccall added a comment.

In D124164#3482261 , @RKSimon wrote:

> @sammccall It looks like this is causing a link error on some PPC builds: 
> https://lab.llvm.org/buildbot/#/builders/57/builds/17387

Thanks, added missing deps in 97b6c92dcd56937bc27de7c4c08381fc71c402e7 
, will 
watch the builder


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124164

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


[PATCH] D123544: [randstruct] Automatically randomize a structure of function pointers

2022-04-29 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


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D123544

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


[PATCH] D124658: [analyzer] Canonicalize SymIntExpr so the RHS is positive when possible

2022-04-29 Thread Balázs Benics via Phabricator via cfe-commits
steakhal added a comment.

It looks good at first glance.

For the review, it would be nice to see which `clang_analyzer_dumps` and 
`reachables` change with the patch.
Could you mark the ones which have different results depending on whether you 
apply your fix or not?
E.g put a `no-warning` where we previously had a report, but now we don't.

In D124658#3481929 , 
@tomasz-kaminski-sonarsource wrote:

> Without the changes, out of the following unsatisfiable conditions:
> A) `(l - 1000) > 0`
> B) `l > 1000`
> C) `l > 1000L`
> D) `(l + 0L) > 1000`
> CSA was considering A and B to satisable. The `l` is `(long)(x + 1 - 10U)` 
> and `x` is in range `[10, 100]` so no overflow happens.

Ah, I see. It would be still nice to see a comment in the test :D

PS: we tend to use regular expression matching for masking out the number in 
the symbol dump: `expected-warning-re {{(reg_${{[0-9]+}}) - 1}}`




Comment at: clang/lib/StaticAnalyzer/Core/SimpleSValBuilder.cpp:204
+// subtraction/addition of the negated value.
+if (!RHS.isNegative()) {
+  ConvertedRHS = &BasicVals.Convert(resultTy, RHS);

I would rather swap these branches though, to leave the default case (aka. 
this) to the end.



Comment at: clang/lib/StaticAnalyzer/Core/SimpleSValBuilder.cpp:212-219
+  llvm::APSInt ConvertedRHSValue = resultIntTy.convert(RHS);
+  // Check if the negation of the RHS is representable,
+  // i.e., the resultTy is signed, and it is not the lowest
+  // representable negative value.
+  if (ConvertedRHSValue > resultIntTy.getMinValue()) {
+ConvertedRHS = &BasicVals.getValue(-ConvertedRHSValue);
+op = (op == BO_Add) ? BO_Sub : BO_Add;

Somehow I miss a check for signedness here.
Why do you think it would be only triggered for signed types?

I have a guess, that since we already handled `x +-0`, SymIntExprs like `x - 
(-0)` cannot exist here, thus cannot trigger this condition spuriously. I 
cannot think of any ther example that could cause this misbehaving. So in that 
sense `ConvertedRHSValue > resultIntTy.getMinValue()` implies *at this place* 
that `ConvertedRHSValue.isSigned()`.
I would rather see this redundant check here to make the correctness reasoning 
local though.



Comment at: clang/lib/StaticAnalyzer/Core/SimpleSValBuilder.cpp:661-667
+  // If the op and lop agrees, then we just need to
+  // sum the constants. Otherwise, we change to operation
+  // type if substraction would produce negative value
+  // (and cause overflow for unsigned integers),
+  // as consequence x+1U-10 produces x-9U, instead
+  // of x+4294967287U, that would be produced without this
+  // additional check.

It feels like this is a completely different problem compared to the 
//simplification of X - (-N) to X + N//.
If this is the case, I would rather split that part into a separate patch 
instead.



Comment at: clang/test/Analysis/additive-op-on-sym-int-expr.c:1
+// RUN: %clang_analyze_cc1 -analyzer-checker=core,debug.ExprInspection 
-analyzer-config eagerly-assume=false -verify %s
+

You assume that `int` has 8 bytes and that 1 byte is 8 bits. Pin the target 
triple.



Comment at: clang/test/Analysis/additive-op-on-sym-int-expr.c:11
+  }
+
+  int i = x + 1;





Comment at: clang/test/Analysis/additive-op-on-sym-int-expr.c:35-36
+
+  l = -1l;
+  i = l;
+  clang_analyzer_dump(x + i); // expected-warning {{(reg_$0) - 1}}

You could simply assign the right value directly to `i` AFAIK.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124658

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


[PATCH] D122895: [C89/C2x] Improve diagnostics around strict prototypes in C

2022-04-29 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman added a comment.

In D122895#3481564 , @manojgupta 
wrote:

> Some of our users are not very happy with the churn probably caused by this 
> change where the declaration has the "void" argument but the later definition 
> does not have explicit "void".
>
>   void foo(void);
>   
>   void foo() 
>   {
>   }
>
> GCC  does not warn about this usage: https://godbolt.org/z/zPP8qjc98
>
> Any opinions?

Thank you for the feedback! I think it's debatable whether this is a bug or 
not, but it's an interesting case that I may think about a bit further before 
making any final decisions. My current thinking is...

We turned `-Wstrict-prototypes` into a pedantic warning specifically telling 
the user about K&R C function usage everywhere it occurs, and from that 
perspective `void f() {}` is correct to diagnose pedantically as the signature 
is specifically a K&R C one. However, the composite type between `void f(void)` 
(with a parameter list) and `void f() {}` (with an empty identifier list) is a 
function with a prototype of `void(void)` (per C99 6.2.7p3). Thus, a call to 
the function through the declaration can pass no arguments, and a call to the 
function through the definition can pass no arguments, and so it also seems 
reasonable to not diagnose.

(We added `-Wdeprecated-non-prototype` to cover the case where there's a 
behavioral change to the code in C2x, which diagnoses `void f(int);` and `void 
f(i) int i; {}` (this code will break in C2x), so despite the similarity with 
your case, it's a different diagnostic entirely.)

FWIW, GCC's behavior isn't particularly interesting because we're knowingly 
diverging from their strategy with the warning, so it's not too surprising that 
our behavior is different.

I think what sells it for me not being a bug is that we issue that warning when 
determining the function *type* when forming the declaration which happens 
before doing function merging. At the point where we issue this warning, we 
don't have enough information to know whether the function will eventually have 
a composite type with a prototype or not (we don't even have enough information 
to know whether it's for a function declaration or not; it could be for a 
typedef, etc), so suppressing the diagnostic would be rather difficult. And 
because it's a pedantic warning specifically, I think it's defensible that 
we're issuing the diagnostic.

Is disabling the pedantic warning an option for your users?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D122895

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


[PATCH] D124666: In MSVC compatibility mode, handle unqualified templated base class initialization

2022-04-29 Thread Fred Tingaud via Phabricator via cfe-commits
frederic-tingaud-sonarsource updated this revision to Diff 426021.

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

https://reviews.llvm.org/D124666

Files:
  clang/include/clang/Basic/DiagnosticSemaKinds.td
  clang/lib/Sema/SemaDeclCXX.cpp
  clang/test/SemaTemplate/ms-unqualified-base-class.cpp

Index: clang/test/SemaTemplate/ms-unqualified-base-class.cpp
===
--- /dev/null
+++ clang/test/SemaTemplate/ms-unqualified-base-class.cpp
@@ -0,0 +1,80 @@
+// RUN: %clang_cc1 -std=c++17 -fms-compatibility -fsyntax-only -verify=before,expected %s
+// RUN: %clang_cc1 -std=c++17 -fms-compatibility -fdelayed-template-parsing -fsyntax-only -verify=before,expected %s
+// RUN: %clang_cc1 -std=c++20 -fms-compatibility -fsyntax-only -verify=after,expected %s
+// RUN: %clang_cc1 -std=c++20 -fms-compatibility -fdelayed-template-parsing -fsyntax-only -verify=after,expected %s
+
+template 
+class Base {
+};
+
+template 
+class Derived : public Base {
+public:
+  // after-error@+1 {{member initializer 'Base' does not name a non-static data member or base class}}
+  Derived() : Base() {} // before-warning {{unqualified base initializer of class templates is a Microsoft extension}}
+};
+
+template struct AggregateBase {
+  T i;
+};
+
+template
+struct  AggregateDerived : public AggregateBase {
+  int i;
+
+  // after-error@+1 {{member initializer 'AggregateBase' does not name a non-static data member or base class}}
+  AggregateDerived(T j) : AggregateBase{ 4 }, i{ j } {} // before-warning {{unqualified base initializer of class templates is a Microsoft extension}}
+  int f() {
+return i + AggregateBase::i; // expected-warning {{use of undeclared identifier 'AggregateBase'; unqualified lookup into dependent bases of class template 'AggregateDerived' is a Microsoft extension}}
+  }
+};
+
+template  struct MultiTypesBase {
+};
+
+template 
+struct MultiTypesDerived : public MultiTypesBase {
+  // after-error@+1 {{member initializer 'MultiTypesBase' does not name a non-static data member or base class}}
+  MultiTypesDerived() : MultiTypesBase{} {} // before-warning {{unqualified base initializer of class templates is a Microsoft extension}}
+};
+
+template  struct IntegerBase {
+};
+
+template 
+struct IntegerDerived : public IntegerBase {
+  // after-error@+1 {{member initializer 'IntegerBase' does not name a non-static data member or base class}}
+  IntegerDerived() : IntegerBase{} {} // before-warning {{unqualified base initializer of class templates is a Microsoft extension}}
+};
+
+template struct ConformingBase {
+  T i;
+};
+
+template
+struct  ConformingDerived : public ConformingBase {
+  int i;
+
+  ConformingDerived(T j) : ConformingBase{ 4 }, i{ j } {}
+  int f() {
+return i + ConformingBase::i;
+  }
+};
+
+int main() {
+  int I;
+  Derived t;
+
+  AggregateDerived AD{ 2 };
+  AD.AggregateBase::i = 3;
+  I = AD.f();
+
+  MultiTypesDerived MTD;
+
+  IntegerDerived<4> ID;
+
+  ConformingDerived CD{ 2 };
+  I = CD.f();
+
+  return I;
+}
Index: clang/lib/Sema/SemaDeclCXX.cpp
===
--- clang/lib/Sema/SemaDeclCXX.cpp
+++ clang/lib/Sema/SemaDeclCXX.cpp
@@ -4345,6 +4345,15 @@
 }
   }
 
+  if (getLangOpts().MSVCCompat && !getLangOpts().CPlusPlus20) {
+auto UnqualifiedBase = R.getAsSingle();
+if (UnqualifiedBase) {
+  Diag(IdLoc, diag::ext_unqualified_base_class)
+<< SourceRange(IdLoc, Init->getSourceRange().getEnd());
+  BaseType = UnqualifiedBase->getInjectedClassNameSpecialization();
+}
+  }
+
   if (!TyD && BaseType.isNull()) {
 Diag(IdLoc, diag::err_mem_init_not_member_or_class)
   << MemberOrBase << SourceRange(IdLoc,Init->getSourceRange().getEnd());
Index: clang/include/clang/Basic/DiagnosticSemaKinds.td
===
--- clang/include/clang/Basic/DiagnosticSemaKinds.td
+++ clang/include/clang/Basic/DiagnosticSemaKinds.td
@@ -5508,6 +5508,9 @@
 def ext_found_later_in_class : ExtWarn<
   "use of member %0 before its declaration is a Microsoft extension">,
   InGroup;
+def ext_unqualified_base_class : ExtWarn<
+  "unqualified base initializer of class templates is a Microsoft extension">,
+  InGroup;
 def note_dependent_member_use : Note<
   "must qualify identifier to find this declaration in dependent base class">;
 def err_not_found_by_two_phase_lookup : Error<"call to function %0 that is neither "
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D124669: [flang][driver] Add support for -save-temps

2022-04-29 Thread Andrzej Warzynski via Phabricator via cfe-commits
awarzynski created this revision.
awarzynski added reviewers: rovka, kiranchandramohan, Leporacanthicus, 
unterumarmung, ekieri, schweitz, jeanPerier, peixin, shraiysh.
Herald added a reviewer: sscalpone.
Herald added projects: Flang, All.
awarzynski requested review of this revision.
Herald added subscribers: cfe-commits, jdoerfert.
Herald added a project: clang.

This patch adds support for `-save-temps` in `flang-new`, Flang's
compiler driver. The semantics of this option are inherited from Clang.

The file extension for temporary Fortran preprocessed files is set to
`i`. This is identical to what Clang uses for C (or C++) preprocessed
files. I have tried researching what other compilers do here, but I
couldn't find any definitive answers. One GFortran thread [1] suggests
that indeed it is not clear what the right approach should be.

Normally, various phases in Clang/Flang are combined. The `-save-temps`
option works by forcing the compiler to run every phase separately. As
there is no integrated assembler driver in Flang, user will have to use
`-save-temps` together with `-fno-integrated-as`. Otherwise, an
invocation to the integrated assembler would be generated generated,
which is going to fail (i.e. something equivalent to `clang -cc1as` from
Clang).

There are no specific plans for implementing an integrated assembler for
Flang for now. One possible solution would be to share it entirely with
Clang.

[1] https://gcc.gnu.org/bugzilla//show_bug.cgi?id=81615

Depends on D124664 
Depends on D124665 
Depends on D124667 


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D124669

Files:
  clang/include/clang/Driver/Options.td
  clang/include/clang/Driver/Types.def
  flang/test/Driver/driver-help-hidden.f90
  flang/test/Driver/driver-help.f90
  flang/test/Driver/save-temps.f90

Index: flang/test/Driver/save-temps.f90
===
--- /dev/null
+++ flang/test/Driver/save-temps.f90
@@ -0,0 +1,53 @@
+! Tests for the `-save-temps` flag. As `flang` does not implement `-fc1as` (i.e. a driver for the intergrated assembly), we need to
+! use `-fno-integrated-as` here.
+
+!--
+! Basic case: `-save-temps`
+!--
+! RUN: %flang -save-temps -fno-integrated-as %s -### 2>&1 | FileCheck %s
+! CHECK: "-o" "save-temps.i"
+! CHECK-NEXT: "-o" "save-temps.bc"
+! CHECK-NEXT: "-o" "save-temps.s"
+! CHECK-NEXT: "-o" "save-temps.o"
+! CHECK-NEXT: "-o" "a.out"
+
+!--
+! `-save-temps=cwd`
+!--
+! This should work the same as -save-temps above
+
+! RUN: %flang -save-temps=cwd -fno-integrated-as  %s -### 2>&1 | FileCheck %s -check-prefix=CWD
+! CWD: "-o" "save-temps.i"
+! CWD-NEXT: "-o" "save-temps.bc"
+! CWD-NEXT: "-o" "save-temps.s"
+! CWD-NEXT: "-o" "save-temps.o"
+! CWD-NEXT: "-o" "a.out"
+
+!--
+! `-save-temps=obj`
+!--
+! Check that temp files are saved in the same directory as the output file
+! regardless of whether -o is specified.
+
+! RUN: %flang -save-temps=obj -fno-integrated-as -o obj/dir/a.out %s -### 2>&1 | FileCheck %s -check-prefix=CHECK-OBJ
+! CHECK-OBJ: "-o" "obj/dir/save-temps.i"
+! CHECK-OBJ-NEXT: "-o" "obj/dir/save-temps.bc"
+! CHECK-OBJ-NEXT: "-o" "obj/dir/save-temps.s"
+! CHECK-OBJ-NEXT: "-o" "obj/dir/save-temps.o"
+! CHECK-OBJ-NEXT: "-o" "obj/dir/a.out"
+
+! RUN: %flang -save-temps=obj -fno-integrated-as %s -### 2>&1 | FileCheck %s -check-prefix=CHECK-OBJ-NOO
+! CHECK-OBJ-NOO: "-o" "save-temps.i"
+! CHECK-OBJ-NOO-NEXT: "-o" "save-temps.bc"
+! CHECK-OBJ-NOO-NEXT: "-o" "save-temps.s"
+! CHECK-OBJ-NOO-NEXT: "-o" "save-temps.o"
+! CHECK-OBJ-NOO-NEXT: "-o" "a.out"
+
+!--
+! `-S` without `-save-temps`
+!--
+! Check for a single `flang -fc1` invocation when NOT using -save-temps.
+! RUN: %flang -S %s -### 2>&1 | FileCheck %s -check-prefix=NO-TEMPS
+! NO-TEMPS: "-fc1"
+! NO-TEMPS-SAME: "-S"
+! NO-TEMPS-SAME: "-o" "save-temps.s"
Index: flang/test/Driver/driver-help.f90
===
--- flang/test/Driver/driver-help.f90
+++ flang/test/Driver/driver-help.f90
@@ -42,6 +42,7 @@
 ! HELP-NEXT: -flogical-abbreviations Enable logical abbreviations
 ! HELP-NEXT: -fno-automatic Implies the SAVE attribute for non-automatic local objects in subprograms unless RECURSIVE
 ! HELP-NEXT: -fno-color-diagnostics  Disable colors in diagnostics
+! HELP-NEXT: -fno-integrated-as  Disable the integrated assembler
 ! HELP-NEXT: -fopenacc  Enable OpenACC
 ! HELP-NEXT: -fopenmp   Parse OpenMP pragmas and generate parallel code.
 ! HELP-NEXT: -fxor-operator Enable .XOR. as a synonym of .NEQV.
@@ -56,6 +57,8 @@
 ! HELP-NEXT: -print-effective-triple Print the effective target triple
 ! HELP-N

[PATCH] D124666: In MSVC compatibility mode, handle unqualified templated base class initialization

2022-04-29 Thread Fred Tingaud via Phabricator via cfe-commits
frederic-tingaud-sonarsource updated this revision to Diff 426022.

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

https://reviews.llvm.org/D124666

Files:
  clang/include/clang/Basic/DiagnosticSemaKinds.td
  clang/lib/Sema/SemaDeclCXX.cpp
  clang/test/SemaTemplate/ms-unqualified-base-class.cpp

Index: clang/test/SemaTemplate/ms-unqualified-base-class.cpp
===
--- /dev/null
+++ clang/test/SemaTemplate/ms-unqualified-base-class.cpp
@@ -0,0 +1,80 @@
+// RUN: %clang_cc1 -std=c++17 -fms-compatibility -fsyntax-only -verify=before,expected %s
+// RUN: %clang_cc1 -std=c++17 -fms-compatibility -fdelayed-template-parsing -fsyntax-only -verify=before,expected %s
+// RUN: %clang_cc1 -std=c++20 -fms-compatibility -fsyntax-only -verify=after,expected %s
+// RUN: %clang_cc1 -std=c++20 -fms-compatibility -fdelayed-template-parsing -fsyntax-only -verify=after,expected %s
+
+template 
+class Base {
+};
+
+template 
+class Derived : public Base {
+public:
+  // after-error@+1 {{member initializer 'Base' does not name a non-static data member or base class}}
+  Derived() : Base() {} // before-warning {{unqualified base initializer of class templates is a Microsoft extension}}
+};
+
+template  struct AggregateBase {
+  T i;
+};
+
+template 
+struct AggregateDerived : public AggregateBase {
+  int i;
+
+  // after-error@+1 {{member initializer 'AggregateBase' does not name a non-static data member or base class}}
+  AggregateDerived(T j) : AggregateBase{4}, i{j} {} // before-warning {{unqualified base initializer of class templates is a Microsoft extension}}
+  int f() {
+return i + AggregateBase::i; // expected-warning {{use of undeclared identifier 'AggregateBase'; unqualified lookup into dependent bases of class template 'AggregateDerived' is a Microsoft extension}}
+  }
+};
+
+template  struct MultiTypesBase {
+};
+
+template 
+struct MultiTypesDerived : public MultiTypesBase {
+  // after-error@+1 {{member initializer 'MultiTypesBase' does not name a non-static data member or base class}}
+  MultiTypesDerived() : MultiTypesBase{} {} // before-warning {{unqualified base initializer of class templates is a Microsoft extension}}
+};
+
+template  struct IntegerBase {
+};
+
+template 
+struct IntegerDerived : public IntegerBase {
+  // after-error@+1 {{member initializer 'IntegerBase' does not name a non-static data member or base class}}
+  IntegerDerived() : IntegerBase{} {} // before-warning {{unqualified base initializer of class templates is a Microsoft extension}}
+};
+
+template  struct ConformingBase {
+  T i;
+};
+
+template 
+struct ConformingDerived : public ConformingBase {
+  int i;
+
+  ConformingDerived(T j) : ConformingBase{4}, i{j} {}
+  int f() {
+return i + ConformingBase::i;
+  }
+};
+
+int main() {
+  int I;
+  Derived t;
+
+  AggregateDerived AD{2};
+  AD.AggregateBase::i = 3;
+  I = AD.f();
+
+  MultiTypesDerived MTD;
+
+  IntegerDerived<4> ID;
+
+  ConformingDerived CD{2};
+  I = CD.f();
+
+  return I;
+}
Index: clang/lib/Sema/SemaDeclCXX.cpp
===
--- clang/lib/Sema/SemaDeclCXX.cpp
+++ clang/lib/Sema/SemaDeclCXX.cpp
@@ -4345,6 +4345,15 @@
 }
   }
 
+  if (getLangOpts().MSVCCompat && !getLangOpts().CPlusPlus20) {
+auto UnqualifiedBase = R.getAsSingle();
+if (UnqualifiedBase) {
+  Diag(IdLoc, diag::ext_unqualified_base_class)
+  << SourceRange(IdLoc, Init->getSourceRange().getEnd());
+  BaseType = UnqualifiedBase->getInjectedClassNameSpecialization();
+}
+  }
+
   if (!TyD && BaseType.isNull()) {
 Diag(IdLoc, diag::err_mem_init_not_member_or_class)
   << MemberOrBase << SourceRange(IdLoc,Init->getSourceRange().getEnd());
Index: clang/include/clang/Basic/DiagnosticSemaKinds.td
===
--- clang/include/clang/Basic/DiagnosticSemaKinds.td
+++ clang/include/clang/Basic/DiagnosticSemaKinds.td
@@ -5508,6 +5508,9 @@
 def ext_found_later_in_class : ExtWarn<
   "use of member %0 before its declaration is a Microsoft extension">,
   InGroup;
+def ext_unqualified_base_class : ExtWarn<
+  "unqualified base initializer of class templates is a Microsoft extension">,
+  InGroup;
 def note_dependent_member_use : Note<
   "must qualify identifier to find this declaration in dependent base class">;
 def err_not_found_by_two_phase_lookup : Error<"call to function %0 that is neither "
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D124634: ExtractAPI: Use %clang_cc1 and -verify in enum.c

2022-04-29 Thread Daniel Grumberg via Phabricator via cfe-commits
dang accepted this revision.
dang 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/D124634/new/

https://reviews.llvm.org/D124634

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


[PATCH] D123924: [clang-apply-replacements] Added an option to ignore insert conflict.

2022-04-29 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman added a comment.

I don't know enough about this code base to feel comfortable signing off on it, 
but the changes look reasonable to me FWIW.


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

https://reviews.llvm.org/D123924

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


[PATCH] D124434: [Clang][Test] Run tests in C++14 mode explicitly.

2022-04-29 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman added a comment.

In D124434#3480915 , @dblaikie wrote:

> I guess coming back to your other point about restructing the way all this 
> testing works (be a pity to gate the default change on this work as it sounds 
> like a big project) - yeah, it'd be nice to be able to declare a test as 
> "language version neutral" or "in this version and above" (or, I guess "only 
> in these versions and no others") - and have some mode in the lit build that 
> can then handle running it in all known versions - and maybe the developer 
> default could be "run in the most recent shipped version only" for speed (if 
> the speed is noticable) and leave it to buildbots to run in all the language 
> versions.

Yeah, that's basically what I was envisioning; it may make build bots slower, 
but any expansion of test coverage leads to that outcome, so I don't see it as 
being a bad thing so long as we keep the developer experience reasonable. We 
might want to do something on the build bots to help folks know "to reproduce, 
you may need to run lit with this extra parameter so all tests are run" or some 
other marker to help folks who break a buildbot know what's going on.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124434

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


[PATCH] D124658: [analyzer] Canonicalize SymIntExpr so the RHS is positive when possible

2022-04-29 Thread Gabor Marton via Phabricator via cfe-commits
martong added a comment.

> This avoid producing very large RHS in case when the symbol is cased to 
> unsigned number, and as consequence makes the value more robust in presence 
> of cast.

Could you please elaborate on this? I understand that you'd like to simplify 
certain binary operations by merging the RHS and the operand, however, I don't 
see what are the empirical problems that this patch supposed to fix. E.g. did 
you encounter a crash without the fix, or was it the mentioned infeasible state 
(`(l - 1000) > 0`) that caused a false positive? If that is the case, I believe 
the huge cast patch  is going to solve it. 
Could you please check if those infeasible cases are solved by the mentioned 
D103096  (you have to set 
`support-symbolic-integer-casts=true`) ?




Comment at: clang/test/Analysis/additive-op-on-sym-int-expr.c:18
+  if ((l - 1000) > 0) {
+clang_analyzer_warnIfReached();
+  }

And same below for the other infeasible cases.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124658

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


[PATCH] D124534: Add a diagnostic for line directive of a gnu extension

2022-04-29 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman added a comment.

In D124534#3481264 , @ken-matsui 
wrote:

> Hi, @aaron.ballman
>
> Thanks for your kind reviews!
> I’ve updated the code, but is this what you’d expected?

It looks like the precommit CI pipeline can't test your patch -- I think you 
may have uploaded just the changes since last time rather than the full set of 
changes against the tree. I don't think we're quite there yet, but we're not 
too far off either, I think. Thank you for continuing to work on this!




Comment at: clang/include/clang/Basic/DiagnosticGroups.td:1114-1116
 GNUImaginaryConstant, GNUIncludeNext,
 GNULabelsAsValue, GNUNullPointerArithmetic,
 GNUPointerArith, RedeclaredClassMember,

You'll likely also need to re-flow the line to the usual 80-col limit.



Comment at: clang/lib/Lex/PPDirectives.cpp:1356
+
+PP.Diag(FlagTok, diag::ext_pp_gnu_line_directive);
   } else if (FlagVal == 2) {

I speculate that this change is wrong.

The goal here is to diagnose any time there's a GNU line marker and now we're 
only trigging the diagnostic when the line marker's value is 1; that misses 
diagnostics when the marker value is something else.

That's why I suggested warning each place we return `false` from this function 
-- those are the situations when the line marker is syntactically correct and 
we're going to make use of it in the caller. (We don't want to warn about use 
of a line marker when we're going to generate an error anyway.)


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124534

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


[PATCH] D123460: [OpenMP] Make generating offloading entries more generic

2022-04-29 Thread Joseph Huber 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 rG643c9b22ef52: [OpenMP] Make generating offloading entries 
more generic (authored by jhuber6).

Changed prior to commit:
  https://reviews.llvm.org/D123460?vs=421794&id=426033#toc

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D123460

Files:
  clang/lib/CodeGen/CGOpenMPRuntime.cpp
  clang/lib/CodeGen/CGOpenMPRuntime.h
  llvm/include/llvm/Frontend/OpenMP/OMPIRBuilder.h
  llvm/include/llvm/Frontend/OpenMP/OMPKinds.def
  llvm/lib/Frontend/OpenMP/OMPIRBuilder.cpp

Index: llvm/lib/Frontend/OpenMP/OMPIRBuilder.cpp
===
--- llvm/lib/Frontend/OpenMP/OMPIRBuilder.cpp
+++ llvm/lib/Frontend/OpenMP/OMPIRBuilder.cpp
@@ -753,6 +753,44 @@
   return Builder.saveIP();
 }
 
+void OpenMPIRBuilder::emitOffloadingEntry(Constant *Addr, StringRef Name,
+  uint64_t Size, int32_t Flags,
+  StringRef SectionName) {
+  Type *Int8PtrTy = Type::getInt8PtrTy(M.getContext());
+  Type *Int32Ty = Type::getInt32Ty(M.getContext());
+  Type *SizeTy = M.getDataLayout().getIntPtrType(M.getContext());
+
+  Constant *AddrName = ConstantDataArray::getString(M.getContext(), Name);
+
+  // Create the constant string used to look up the symbol in the device.
+  auto *Str =
+  new llvm::GlobalVariable(M, AddrName->getType(), /*isConstant=*/true,
+   llvm::GlobalValue::InternalLinkage, AddrName,
+   ".omp_offloading.entry_name");
+  Str->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
+
+  // Construct the offloading entry.
+  Constant *EntryData[] = {
+  ConstantExpr::getPointerBitCastOrAddrSpaceCast(Addr, Int8PtrTy),
+  ConstantExpr::getPointerBitCastOrAddrSpaceCast(Str, Int8PtrTy),
+  ConstantInt::get(SizeTy, Size),
+  ConstantInt::get(Int32Ty, Flags),
+  ConstantInt::get(Int32Ty, 0),
+  };
+  Constant *EntryInitializer =
+  ConstantStruct::get(OpenMPIRBuilder::OffloadEntry, EntryData);
+
+  auto *Entry = new GlobalVariable(
+  M, OpenMPIRBuilder::OffloadEntry,
+  /* isConstant = */ true, GlobalValue::WeakAnyLinkage, EntryInitializer,
+  ".omp_offloading.entry." + Name, nullptr, GlobalValue::NotThreadLocal,
+  M.getDataLayout().getDefaultGlobalsAddressSpace());
+
+  // The entry has to be created in the section the linker expects it to be.
+  Entry->setSection(SectionName);
+  Entry->setAlignment(Align(1));
+}
+
 void OpenMPIRBuilder::emitCancelationCheckImpl(Value *CancelFlag,
omp::Directive CanceledDirective,
FinalizeCallbackTy ExitCB) {
Index: llvm/include/llvm/Frontend/OpenMP/OMPKinds.def
===
--- llvm/include/llvm/Frontend/OpenMP/OMPKinds.def
+++ llvm/include/llvm/Frontend/OpenMP/OMPKinds.def
@@ -86,6 +86,8 @@
   OMP_STRUCT_TYPE(VarName, "struct." #Name, __VA_ARGS__)
 
 __OMP_STRUCT_TYPE(Ident, ident_t, Int32, Int32, Int32, Int32, Int8Ptr)
+__OMP_STRUCT_TYPE(OffloadEntry, __tgt_offload_entry, Int8Ptr, Int8Ptr, SizeTy,
+  Int32, Int32)
 __OMP_STRUCT_TYPE(AsyncInfo, __tgt_async_info, Int8Ptr)
 
 #undef __OMP_STRUCT_TYPE
Index: llvm/include/llvm/Frontend/OpenMP/OMPIRBuilder.h
===
--- llvm/include/llvm/Frontend/OpenMP/OMPIRBuilder.h
+++ llvm/include/llvm/Frontend/OpenMP/OMPIRBuilder.h
@@ -779,6 +779,27 @@
   /// Value.
   GlobalValue *createGlobalFlag(unsigned Value, StringRef Name);
 
+  /// Create an offloading section struct used to register this global at
+  /// runtime.
+  ///
+  /// Type struct __tgt_offload_entry{
+  ///   void*addr;  // Pointer to the offload entry info.
+  ///   // (function or global)
+  ///   char*name;  // Name of the function or global.
+  ///   size_t  size;   // Size of the entry info (0 if it a function).
+  ///   int32_t flags;
+  ///   int32_t reserved;
+  /// };
+  ///
+  /// \param Addr The pointer to the global being registered.
+  /// \param Name The symbol name associated with the global.
+  /// \param Size The size in bytes of the global (0 for functions).
+  /// \param Flags Flags associated with the entry.
+  /// \param SectionName The section this entry will be placed at.
+  void emitOffloadingEntry(Constant *Addr, StringRef Name, uint64_t Size,
+   int32_t Flags,
+   StringRef SectionName = "omp_offloading_entries");
+
   /// Generate control flow and cleanup for cancellation.
   ///
   /// \param CancelFlag Flag indicating if the cancellation is performed.
Index: clang/lib/CodeGen/CGOpenMPRuntime.h
==

[clang] 643c9b2 - [OpenMP] Make generating offloading entries more generic

2022-04-29 Thread Joseph Huber via cfe-commits

Author: Joseph Huber
Date: 2022-04-29T09:14:31-04:00
New Revision: 643c9b22ef527be8532d7b75ccf64180fa060339

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

LOG: [OpenMP] Make generating offloading entries more generic

This patch moves the logic for generating the offloading entries to the
OpenMPIRBuilder. This makes it easier to re-use in other places, such as
for OpenMP support in Flang or using the same method for generating
offloading entires for other languages like Cuda.

Reviewed By: tianshilei1992

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

Added: 


Modified: 
clang/lib/CodeGen/CGOpenMPRuntime.cpp
clang/lib/CodeGen/CGOpenMPRuntime.h
llvm/include/llvm/Frontend/OpenMP/OMPIRBuilder.h
llvm/include/llvm/Frontend/OpenMP/OMPKinds.def
llvm/lib/Frontend/OpenMP/OMPIRBuilder.cpp

Removed: 




diff  --git a/clang/lib/CodeGen/CGOpenMPRuntime.cpp 
b/clang/lib/CodeGen/CGOpenMPRuntime.cpp
index 5cc1fdb56aa54..391245e3b54bb 100644
--- a/clang/lib/CodeGen/CGOpenMPRuntime.cpp
+++ b/clang/lib/CodeGen/CGOpenMPRuntime.cpp
@@ -1329,51 +1329,6 @@ llvm::Function 
*CGOpenMPRuntime::emitTaskOutlinedFunction(
   return Res;
 }
 
-static void buildStructValue(ConstantStructBuilder &Fields, CodeGenModule &CGM,
- const RecordDecl *RD, const CGRecordLayout &RL,
- ArrayRef Data) {
-  llvm::StructType *StructTy = RL.getLLVMType();
-  unsigned PrevIdx = 0;
-  ConstantInitBuilder CIBuilder(CGM);
-  const auto *DI = Data.begin();
-  for (const FieldDecl *FD : RD->fields()) {
-unsigned Idx = RL.getLLVMFieldNo(FD);
-// Fill the alignment.
-for (unsigned I = PrevIdx; I < Idx; ++I)
-  Fields.add(llvm::Constant::getNullValue(StructTy->getElementType(I)));
-PrevIdx = Idx + 1;
-Fields.add(*DI);
-++DI;
-  }
-}
-
-template 
-static llvm::GlobalVariable *
-createGlobalStruct(CodeGenModule &CGM, QualType Ty, bool IsConstant,
-   ArrayRef Data, const Twine &Name,
-   As &&... Args) {
-  const auto *RD = cast(Ty->getAsTagDecl());
-  const CGRecordLayout &RL = CGM.getTypes().getCGRecordLayout(RD);
-  ConstantInitBuilder CIBuilder(CGM);
-  ConstantStructBuilder Fields = CIBuilder.beginStruct(RL.getLLVMType());
-  buildStructValue(Fields, CGM, RD, RL, Data);
-  return Fields.finishAndCreateGlobal(
-  Name, CGM.getContext().getAlignOfGlobalVarInChars(Ty), IsConstant,
-  std::forward(Args)...);
-}
-
-template 
-static void
-createConstantGlobalStructAndAddToParent(CodeGenModule &CGM, QualType Ty,
- ArrayRef Data,
- T &Parent) {
-  const auto *RD = cast(Ty->getAsTagDecl());
-  const CGRecordLayout &RL = CGM.getTypes().getCGRecordLayout(RD);
-  ConstantStructBuilder Fields = Parent.beginStruct(RL.getLLVMType());
-  buildStructValue(Fields, CGM, RD, RL, Data);
-  Fields.finishAndAddTo(Parent);
-}
-
 void CGOpenMPRuntime::setLocThreadIdInsertPt(CodeGenFunction &CGF,
  bool AtCurrentPoint) {
   auto &Elem = OpenMPLocThreadIDMap.FindAndConstruct(CGF.CurFn);
@@ -3136,32 +3091,7 @@ void CGOpenMPRuntime::OffloadEntriesInfoManagerTy::
 void CGOpenMPRuntime::createOffloadEntry(
 llvm::Constant *ID, llvm::Constant *Addr, uint64_t Size, int32_t Flags,
 llvm::GlobalValue::LinkageTypes Linkage) {
-  StringRef Name = Addr->getName();
-  llvm::Module &M = CGM.getModule();
-  llvm::LLVMContext &C = M.getContext();
-
-  // Create constant string with the name.
-  llvm::Constant *StrPtrInit = llvm::ConstantDataArray::getString(C, Name);
-
-  std::string StringName = getName({"omp_offloading", "entry_name"});
-  auto *Str = new llvm::GlobalVariable(
-  M, StrPtrInit->getType(), /*isConstant=*/true,
-  llvm::GlobalValue::InternalLinkage, StrPtrInit, StringName);
-  Str->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
-
-  llvm::Constant *Data[] = {
-  llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(ID, CGM.VoidPtrTy),
-  llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(Str, CGM.Int8PtrTy),
-  llvm::ConstantInt::get(CGM.SizeTy, Size),
-  llvm::ConstantInt::get(CGM.Int32Ty, Flags),
-  llvm::ConstantInt::get(CGM.Int32Ty, 0)};
-  std::string EntryName = getName({"omp_offloading", "entry", ""});
-  llvm::GlobalVariable *Entry = createGlobalStruct(
-  CGM, getTgtOffloadEntryQTy(), /*IsConstant=*/true, Data,
-  Twine(EntryName).concat(Name), llvm::GlobalValue::WeakAnyLinkage);
-
-  // The entry has to be created in the section the linker expects it to be.
-  Entry->setSection("omp_offloading_entries");
+  OMPBuilder.emitOffloadingEntry(ID, Addr->getName(), Size, Flags);
 }
 
 void CGOpenMPRuntime::createOffloadEntri

[clang] ca6bbe0 - [OpenMP] Make clang argument handling for the new driver more generic

2022-04-29 Thread Joseph Huber via cfe-commits

Author: Joseph Huber
Date: 2022-04-29T09:14:35-04:00
New Revision: ca6bbe008512c9dc6a1ac242466a9d42288daff8

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

LOG: [OpenMP] Make clang argument handling for the new driver more generic

In preparation for accepting other offloading kinds with the new driver,
this patch makes the way we handle offloading actions more generic. A
new field to get the associated device action's toolchain is used rather
than manually iterating a list. This makes building the arguments easier
and makes sure that we doin't rely on any implicit ordering.

Reviewed By: yaxunl

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

Added: 


Modified: 
clang/include/clang/Driver/Action.h
clang/lib/Driver/Action.cpp
clang/lib/Driver/ToolChains/Clang.cpp

Removed: 




diff  --git a/clang/include/clang/Driver/Action.h 
b/clang/include/clang/Driver/Action.h
index 36410150c2797..f8a96619c4f61 100644
--- a/clang/include/clang/Driver/Action.h
+++ b/clang/include/clang/Driver/Action.h
@@ -128,6 +128,9 @@ class Action {
   /// The Offloading architecture associated with this action.
   const char *OffloadingArch = nullptr;
 
+  /// The Offloading toolchain associated with this device action.
+  const ToolChain *OffloadingToolChain = nullptr;
+
   Action(ActionClass Kind, types::ID Type) : Action(Kind, ActionList(), Type) 
{}
   Action(ActionClass Kind, Action *Input, types::ID Type)
   : Action(Kind, ActionList({Input}), Type) {}
@@ -184,7 +187,8 @@ class Action {
 
   /// Set the device offload info of this action and propagate it to its
   /// dependences.
-  void propagateDeviceOffloadInfo(OffloadKind OKind, const char *OArch);
+  void propagateDeviceOffloadInfo(OffloadKind OKind, const char *OArch,
+  const ToolChain *OToolChain);
 
   /// Append the host offload info of this action and propagate it to its
   /// dependences.
@@ -205,10 +209,13 @@ class Action {
 
   OffloadKind getOffloadingDeviceKind() const { return OffloadingDeviceKind; }
   const char *getOffloadingArch() const { return OffloadingArch; }
+  const ToolChain *getOffloadingToolChain() const {
+return OffloadingToolChain;
+  }
 
   /// Check if this action have any offload kinds. Note that host offload kinds
   /// are only set if the action is a dependence to a host offload action.
-  bool isHostOffloading(OffloadKind OKind) const {
+  bool isHostOffloading(unsigned int OKind) const {
 return ActiveOffloadKindMask & OKind;
   }
   bool isDeviceOffloading(OffloadKind OKind) const {

diff  --git a/clang/lib/Driver/Action.cpp b/clang/lib/Driver/Action.cpp
index 21691c4ac4b98..8f4403ff42b65 100644
--- a/clang/lib/Driver/Action.cpp
+++ b/clang/lib/Driver/Action.cpp
@@ -54,7 +54,8 @@ const char *Action::getClassName(ActionClass AC) {
   llvm_unreachable("invalid class");
 }
 
-void Action::propagateDeviceOffloadInfo(OffloadKind OKind, const char *OArch) {
+void Action::propagateDeviceOffloadInfo(OffloadKind OKind, const char *OArch,
+const ToolChain *OToolChain) {
   // Offload action set its own kinds on their dependences.
   if (Kind == OffloadClass)
 return;
@@ -67,9 +68,10 @@ void Action::propagateDeviceOffloadInfo(OffloadKind OKind, 
const char *OArch) {
   assert(!ActiveOffloadKindMask && "Setting a device kind in a host action??");
   OffloadingDeviceKind = OKind;
   OffloadingArch = OArch;
+  OffloadingToolChain = OToolChain;
 
   for (auto *A : Inputs)
-A->propagateDeviceOffloadInfo(OffloadingDeviceKind, OArch);
+A->propagateDeviceOffloadInfo(OffloadingDeviceKind, OArch, OToolChain);
 }
 
 void Action::propagateHostOffloadInfo(unsigned OKinds, const char *OArch) {
@@ -91,7 +93,8 @@ void Action::propagateOffloadInfo(const Action *A) {
 propagateHostOffloadInfo(HK, A->getOffloadingArch());
   else
 propagateDeviceOffloadInfo(A->getOffloadingDeviceKind(),
-   A->getOffloadingArch());
+   A->getOffloadingArch(),
+   A->getOffloadingToolChain());
 }
 
 std::string Action::getOffloadingKindPrefix() const {
@@ -192,6 +195,7 @@ OffloadAction::OffloadAction(const DeviceDependences 
&DDeps, types::ID Ty)
   DevToolChains(DDeps.getToolChains()) {
   auto &OKinds = DDeps.getOffloadKinds();
   auto &BArchs = DDeps.getBoundArchs();
+  auto &OTCs = DDeps.getToolChains();
 
   // If all inputs agree on the same kind, use it also for this action.
   if (llvm::all_of(OKinds, [&](OffloadKind K) { return K == OKinds.front(); }))
@@ -203,7 +207,7 @@ OffloadAction::OffloadAction(const DeviceDependences 
&DDeps, types::ID Ty)
 
   // Propagate info to the dependencies.
   for (unsigned i = 0, e = getInputs().size(

[clang] 4e2b5a6 - [Clang] Make enabling the new driver more generic

2022-04-29 Thread Joseph Huber via cfe-commits

Author: Joseph Huber
Date: 2022-04-29T09:14:39-04:00
New Revision: 4e2b5a6693e299fcb8671d4dbb69c993d181b29f

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

LOG: [Clang] Make enabling the new driver more generic

In preparation for allowing other offloading kinds to use the new driver
a new opt-in flag `-foffload-new-driver` is added. This is distinct from
the existing `-fopenmp-new-driver` because OpenMP will soon use the new
driver by default while the others should not.

Reviewed By: yaxunl, tra

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

Added: 


Modified: 
clang/include/clang/Driver/Options.td
clang/lib/Driver/Driver.cpp
clang/lib/Driver/ToolChains/Clang.cpp

Removed: 




diff  --git a/clang/include/clang/Driver/Options.td 
b/clang/include/clang/Driver/Options.td
index d2097427ed71..6f70e28a211e 100644
--- a/clang/include/clang/Driver/Options.td
+++ b/clang/include/clang/Driver/Options.td
@@ -2534,10 +2534,14 @@ defm openmp_optimistic_collapse : 
BoolFOption<"openmp-optimistic-collapse",
   PosFlag, NegFlag, 
BothFlags<[NoArgumentUnused, HelpHidden]>>;
 def static_openmp: Flag<["-"], "static-openmp">,
   HelpText<"Use the static host OpenMP runtime while linking.">;
+def offload_new_driver : Flag<["--"], "offload-new-driver">, 
Flags<[CC1Option]>, Group,
+  HelpText<"Use the new driver for offloading compilation.">;
+def no_offload_new_driver : Flag<["--"], "no-offload-new-driver">, 
Flags<[CC1Option]>, Group,
+  HelpText<"Don't Use the new driver for offloading compilation.">;
 def fopenmp_new_driver : Flag<["-"], "fopenmp-new-driver">, 
Flags<[CC1Option]>, Group,
   HelpText<"Use the new driver for OpenMP offloading.">;
 def fno_openmp_new_driver : Flag<["-"], "fno-openmp-new-driver">, 
Flags<[CC1Option]>, Group,
-  HelpText<"Don't use the new driver for OpenMP offloading.">;
+  Alias, HelpText<"Don't use the new driver for OpenMP 
offloading.">;
 def fno_optimize_sibling_calls : Flag<["-"], "fno-optimize-sibling-calls">, 
Group, Flags<[CC1Option]>,
   HelpText<"Disable tail call optimization, keeping the call stack accurate">,
   MarshallingInfoFlag>;

diff  --git a/clang/lib/Driver/Driver.cpp b/clang/lib/Driver/Driver.cpp
index 487e2e1e0b3f..d0c5c3b6b49d 100644
--- a/clang/lib/Driver/Driver.cpp
+++ b/clang/lib/Driver/Driver.cpp
@@ -3976,17 +3976,19 @@ void Driver::BuildActions(Compilation &C, 
DerivedArgList &Args,
   // Builder to be used to build offloading actions.
   OffloadingActionBuilder OffloadBuilder(C, Args, Inputs);
 
+  bool UseNewOffloadingDriver =
+  (C.isOffloadingHostKind(Action::OFK_OpenMP) &&
+   Args.hasFlag(options::OPT_fopenmp_new_driver,
+options::OPT_no_offload_new_driver, true)) ||
+  Args.hasFlag(options::OPT_offload_new_driver,
+   options::OPT_no_offload_new_driver, false);
+
   // Construct the actions to perform.
   HeaderModulePrecompileJobAction *HeaderModuleAction = nullptr;
   ExtractAPIJobAction *ExtractAPIAction = nullptr;
   ActionList LinkerInputs;
   ActionList MergerInputs;
 
-  bool UseNewOffloadingDriver =
-  C.isOffloadingHostKind(Action::OFK_OpenMP) &&
-  Args.hasFlag(options::OPT_fopenmp_new_driver,
-   options::OPT_fno_openmp_new_driver, true);
-
   for (auto &I : Inputs) {
 types::ID InputType = I.first;
 const Arg *InputArg = I.second;
@@ -4114,8 +4116,7 @@ void Driver::BuildActions(Compilation &C, DerivedArgList 
&Args,
 // Check if this Linker Job should emit a static library.
 if (ShouldEmitStaticLibrary(Args)) {
   LA = C.MakeAction(LinkerInputs, types::TY_Image);
-} else if (UseNewOffloadingDriver &&
-   C.getActiveOffloadKinds() != Action::OFK_None) {
+} else if (UseNewOffloadingDriver) {
   LA = C.MakeAction(LinkerInputs, types::TY_Image);
   LA->propagateHostOffloadInfo(C.getActiveOffloadKinds(),
/*BoundArch=*/nullptr);

diff  --git a/clang/lib/Driver/ToolChains/Clang.cpp 
b/clang/lib/Driver/ToolChains/Clang.cpp
index 3fc8dd0ecf24..450fc1abc4ce 100644
--- a/clang/lib/Driver/ToolChains/Clang.cpp
+++ b/clang/lib/Driver/ToolChains/Clang.cpp
@@ -4389,8 +4389,11 @@ void Clang::ConstructJob(Compilation &C, const JobAction 
&JA,
   bool IsDeviceOffloadAction = !(JA.isDeviceOffloading(Action::OFK_None) ||
  JA.isDeviceOffloading(Action::OFK_Host));
   bool IsHostOffloadingAction =
-  JA.isHostOffloading(Action::OFK_OpenMP) &&
-  !Args.hasArg(options::OPT_fno_openmp_new_driver);
+  (JA.isHostOffloading(Action::OFK_OpenMP) &&
+   Args.hasFlag(options::OPT_fopenmp_new_driver,
+options::OPT_no_offload_new_driver, true)) ||
+  Args.hasFlag(options::OPT_offload_new_driver,
+  

[PATCH] D123313: [OpenMP] Make clang argument handling for the new driver more generic

2022-04-29 Thread Joseph Huber 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 rGca6bbe008512: [OpenMP] Make clang argument handling for the 
new driver more generic (authored by jhuber6).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D123313

Files:
  clang/include/clang/Driver/Action.h
  clang/lib/Driver/Action.cpp
  clang/lib/Driver/ToolChains/Clang.cpp

Index: clang/lib/Driver/ToolChains/Clang.cpp
===
--- clang/lib/Driver/ToolChains/Clang.cpp
+++ clang/lib/Driver/ToolChains/Clang.cpp
@@ -4384,11 +4384,13 @@
   bool IsHIP = JA.isOffloading(Action::OFK_HIP);
   bool IsHIPDevice = JA.isDeviceOffloading(Action::OFK_HIP);
   bool IsOpenMPDevice = JA.isDeviceOffloading(Action::OFK_OpenMP);
-  bool IsOpenMPHost = JA.isHostOffloading(Action::OFK_OpenMP);
   bool IsHeaderModulePrecompile = isa(JA);
   bool IsExtractAPI = isa(JA);
   bool IsDeviceOffloadAction = !(JA.isDeviceOffloading(Action::OFK_None) ||
  JA.isDeviceOffloading(Action::OFK_Host));
+  bool IsHostOffloadingAction =
+  JA.isHostOffloading(Action::OFK_OpenMP) &&
+  !Args.hasArg(options::OPT_fno_openmp_new_driver);
   bool IsUsingLTO = D.isUsingLTO(IsDeviceOffloadAction);
   auto LTOMode = D.getLTOMode(IsDeviceOffloadAction);
 
@@ -4415,7 +4417,7 @@
 
   InputInfoList ModuleHeaderInputs;
   InputInfoList ExtractAPIInputs;
-  InputInfoList OpenMPHostInputs;
+  InputInfoList HostOffloadingInputs;
   const InputInfo *CudaDeviceInput = nullptr;
   const InputInfo *OpenMPDeviceInput = nullptr;
   for (const InputInfo &I : Inputs) {
@@ -4438,12 +4440,12 @@
 << types::getTypeName(ExpectedInputType);
   }
   ExtractAPIInputs.push_back(I);
+} else if (IsHostOffloadingAction) {
+  HostOffloadingInputs.push_back(I);
 } else if ((IsCuda || IsHIP) && !CudaDeviceInput) {
   CudaDeviceInput = &I;
 } else if (IsOpenMPDevice && !OpenMPDeviceInput) {
   OpenMPDeviceInput = &I;
-} else if (IsOpenMPHost) {
-  OpenMPHostInputs.push_back(I);
 } else {
   llvm_unreachable("unexpectedly given multiple inputs");
 }
@@ -6948,24 +6950,23 @@
 }
   }
 
-  // Host-side OpenMP offloading recieves the device object files and embeds it
-  // in a named section including the associated target triple and architecture.
-  if (IsOpenMPHost && !OpenMPHostInputs.empty()) {
-auto InputFile = OpenMPHostInputs.begin();
-auto OpenMPTCs = C.getOffloadToolChains();
-for (auto TI = OpenMPTCs.first, TE = OpenMPTCs.second; TI != TE;
- ++TI, ++InputFile) {
-  const ToolChain *TC = TI->second;
-  const ArgList &TCArgs = C.getArgsForToolChain(TC, "", Action::OFK_OpenMP);
-  StringRef File =
-  C.getArgs().MakeArgString(TC->getInputFilename(*InputFile));
+  // Host-side offloading recieves the device object files and embeds it in a
+  // named section including the associated target triple and architecture.
+  for (const InputInfo Input : HostOffloadingInputs) {
+const Action *OffloadAction = Input.getAction();
+const ToolChain *TC = OffloadAction->getOffloadingToolChain();
+const ArgList &TCArgs =
+C.getArgsForToolChain(TC, OffloadAction->getOffloadingArch(),
+  OffloadAction->getOffloadingDeviceKind());
+StringRef File = C.getArgs().MakeArgString(TC->getInputFilename(Input));
+StringRef Arch = (OffloadAction->getOffloadingArch())
+ ? OffloadAction->getOffloadingArch()
+ : TCArgs.getLastArgValue(options::OPT_march_EQ);
 
-  CmdArgs.push_back(
-  Args.MakeArgString("-fembed-offload-object=" + File + "," +
- Action::GetOffloadKindName(Action::OFK_OpenMP) +
- "," + TC->getTripleString() + "," +
- TCArgs.getLastArgValue(options::OPT_march_EQ)));
-}
+CmdArgs.push_back(Args.MakeArgString(
+"-fembed-offload-object=" + File + "," +
+Action::GetOffloadKindName(OffloadAction->getOffloadingDeviceKind()) +
+"," + TC->getTripleString() + "," + Arch));
   }
 
   if (Triple.isAMDGPU()) {
Index: clang/lib/Driver/Action.cpp
===
--- clang/lib/Driver/Action.cpp
+++ clang/lib/Driver/Action.cpp
@@ -54,7 +54,8 @@
   llvm_unreachable("invalid class");
 }
 
-void Action::propagateDeviceOffloadInfo(OffloadKind OKind, const char *OArch) {
+void Action::propagateDeviceOffloadInfo(OffloadKind OKind, const char *OArch,
+const ToolChain *OToolChain) {
   // Offload action set its own kinds on their dependences.
   if (Kind == OffloadClass)
 return;
@@ -67,9 +68,10 @@
   assert(!ActiveOffloadKindMask && "Setting a device kind in a host 

[clang] c5e5b54 - [CUDA] Add driver support for compiling CUDA with the new driver

2022-04-29 Thread Joseph Huber via cfe-commits

Author: Joseph Huber
Date: 2022-04-29T09:14:44-04:00
New Revision: c5e5b54350fecd4b44c60eb4e982c13de5307aee

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

LOG: [CUDA] Add driver support for compiling CUDA with the new driver

This patch adds the basic support for the clang driver to compile and link CUDA
using the new offloading driver. This requires handling the CUDA offloading kind
and embedding the generated files into the host. This will allow us to link
OpenMP code with CUDA code in the linker wrapper. More support will be required
to create functional CUDA / HIP binaries using this method.

Depends on D120270 D120271 D120934

Reviewed By: tra

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

Added: 
clang/test/Driver/cuda-openmp-driver.cu

Modified: 
clang/include/clang/Basic/Cuda.h
clang/include/clang/Basic/DiagnosticDriverKinds.td
clang/lib/Driver/Driver.cpp
clang/lib/Driver/ToolChains/Clang.cpp
clang/test/Driver/cuda-phases.cu

Removed: 




diff  --git a/clang/include/clang/Basic/Cuda.h 
b/clang/include/clang/Basic/Cuda.h
index cfd960ff4443..147b04eb5745 100644
--- a/clang/include/clang/Basic/Cuda.h
+++ b/clang/include/clang/Basic/Cuda.h
@@ -100,6 +100,9 @@ enum class CudaArch {
   Generic, // A processor model named 'generic' if the target backend defines a
// public one.
   LAST,
+
+  CudaDefault = CudaArch::SM_35,
+  HIPDefault = CudaArch::GFX803,
 };
 
 static inline bool IsNVIDIAGpuArch(CudaArch A) {

diff  --git a/clang/include/clang/Basic/DiagnosticDriverKinds.td 
b/clang/include/clang/Basic/DiagnosticDriverKinds.td
index 80f16749fdc1..7ab7a8c0cd17 100644
--- a/clang/include/clang/Basic/DiagnosticDriverKinds.td
+++ b/clang/include/clang/Basic/DiagnosticDriverKinds.td
@@ -63,6 +63,8 @@ def err_drv_no_cuda_libdevice : Error<
   "cannot find libdevice for %0; provide path to 
diff erent CUDA installation "
   "via '--cuda-path', or pass '-nocudalib' to build without linking with "
   "libdevice">;
+def err_drv_no_rdc_new_driver : Error<
+  "Using '--offload-new-driver' requires '-fgpu-rdc'">;
 
 def err_drv_no_rocm_device_lib : Error<
   "cannot find ROCm device library%select{| for %1|for ABI version %1}0; 
provide its path via "

diff  --git a/clang/lib/Driver/Driver.cpp b/clang/lib/Driver/Driver.cpp
index d0c5c3b6b49d..3209264bb4c8 100644
--- a/clang/lib/Driver/Driver.cpp
+++ b/clang/lib/Driver/Driver.cpp
@@ -4210,6 +4210,101 @@ void Driver::BuildActions(Compilation &C, 
DerivedArgList &Args,
   Args.ClaimAllArgs(options::OPT_cuda_compile_host_device);
 }
 
+/// Returns the canonical name for the offloading architecture when using HIP 
or
+/// CUDA.
+static StringRef getCanonicalArchString(Compilation &C,
+llvm::opt::DerivedArgList &Args,
+StringRef ArchStr,
+Action::OffloadKind Kind) {
+  if (Kind == Action::OFK_Cuda) {
+CudaArch Arch = StringToCudaArch(ArchStr);
+if (Arch == CudaArch::UNKNOWN || !IsNVIDIAGpuArch(Arch)) {
+  C.getDriver().Diag(clang::diag::err_drv_cuda_bad_gpu_arch) << ArchStr;
+  return StringRef();
+}
+return Args.MakeArgStringRef(CudaArchToString(Arch));
+  } else if (Kind == Action::OFK_HIP) {
+llvm::StringMap Features;
+// getHIPOffloadTargetTriple() is known to return valid value as it has
+// been called successfully in the CreateOffloadingDeviceToolChains().
+auto Arch = parseTargetID(
+*getHIPOffloadTargetTriple(C.getDriver(), C.getInputArgs()), ArchStr,
+&Features);
+if (!Arch) {
+  C.getDriver().Diag(clang::diag::err_drv_bad_target_id) << ArchStr;
+  C.setContainsError();
+  return StringRef();
+}
+return Args.MakeArgStringRef(
+getCanonicalTargetID(Arch.getValue(), Features));
+  }
+  return StringRef();
+}
+
+/// Checks if the set offloading architectures does not conflict. Returns the
+/// incompatible pair if a conflict occurs.
+static llvm::Optional>
+getConflictOffloadArchCombination(const llvm::DenseSet &Archs,
+  Action::OffloadKind Kind) {
+  if (Kind != Action::OFK_HIP)
+return None;
+
+  std::set ArchSet;
+  llvm::copy(Archs, std::inserter(ArchSet, ArchSet.begin()));
+  return getConflictTargetIDCombination(ArchSet);
+}
+
+/// Returns the set of bound architectures active for this compilation kind.
+/// This function returns a set of bound architectures, if there are no bound
+/// architctures we return a set containing only the empty string.
+static llvm::DenseSet
+getOffloadArchs(Compilation &C, llvm::opt::DerivedArgList &Args,
+Action::OffloadKind Kind) {
+
+  // If this is OpenMP offloading we don't use a bound architecture.

[PATCH] D123325: [Clang] Make enabling the new driver more generic

2022-04-29 Thread Joseph Huber 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 rG4e2b5a6693e2: [Clang] Make enabling the new driver more 
generic (authored by jhuber6).

Changed prior to commit:
  https://reviews.llvm.org/D123325?vs=425879&id=426035#toc

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D123325

Files:
  clang/include/clang/Driver/Options.td
  clang/lib/Driver/Driver.cpp
  clang/lib/Driver/ToolChains/Clang.cpp


Index: clang/lib/Driver/ToolChains/Clang.cpp
===
--- clang/lib/Driver/ToolChains/Clang.cpp
+++ clang/lib/Driver/ToolChains/Clang.cpp
@@ -4389,8 +4389,11 @@
   bool IsDeviceOffloadAction = !(JA.isDeviceOffloading(Action::OFK_None) ||
  JA.isDeviceOffloading(Action::OFK_Host));
   bool IsHostOffloadingAction =
-  JA.isHostOffloading(Action::OFK_OpenMP) &&
-  !Args.hasArg(options::OPT_fno_openmp_new_driver);
+  (JA.isHostOffloading(Action::OFK_OpenMP) &&
+   Args.hasFlag(options::OPT_fopenmp_new_driver,
+options::OPT_no_offload_new_driver, true)) ||
+  Args.hasFlag(options::OPT_offload_new_driver,
+   options::OPT_no_offload_new_driver, false);
   bool IsUsingLTO = D.isUsingLTO(IsDeviceOffloadAction);
   auto LTOMode = D.getLTOMode(IsDeviceOffloadAction);
 
@@ -4686,7 +4689,9 @@
   // Only AMDGPU supports device-side LTO.
   if (IsDeviceOffloadAction &&
   !Args.hasFlag(options::OPT_fopenmp_new_driver,
-options::OPT_fno_openmp_new_driver, true) &&
+options::OPT_no_offload_new_driver, true) &&
+  !Args.hasFlag(options::OPT_offload_new_driver,
+options::OPT_no_offload_new_driver, false) &&
   !Triple.isAMDGPU()) {
 D.Diag(diag::err_drv_unsupported_opt_for_target)
 << Args.getLastArg(options::OPT_foffload_lto,
Index: clang/lib/Driver/Driver.cpp
===
--- clang/lib/Driver/Driver.cpp
+++ clang/lib/Driver/Driver.cpp
@@ -3976,17 +3976,19 @@
   // Builder to be used to build offloading actions.
   OffloadingActionBuilder OffloadBuilder(C, Args, Inputs);
 
+  bool UseNewOffloadingDriver =
+  (C.isOffloadingHostKind(Action::OFK_OpenMP) &&
+   Args.hasFlag(options::OPT_fopenmp_new_driver,
+options::OPT_no_offload_new_driver, true)) ||
+  Args.hasFlag(options::OPT_offload_new_driver,
+   options::OPT_no_offload_new_driver, false);
+
   // Construct the actions to perform.
   HeaderModulePrecompileJobAction *HeaderModuleAction = nullptr;
   ExtractAPIJobAction *ExtractAPIAction = nullptr;
   ActionList LinkerInputs;
   ActionList MergerInputs;
 
-  bool UseNewOffloadingDriver =
-  C.isOffloadingHostKind(Action::OFK_OpenMP) &&
-  Args.hasFlag(options::OPT_fopenmp_new_driver,
-   options::OPT_fno_openmp_new_driver, true);
-
   for (auto &I : Inputs) {
 types::ID InputType = I.first;
 const Arg *InputArg = I.second;
@@ -4114,8 +4116,7 @@
 // Check if this Linker Job should emit a static library.
 if (ShouldEmitStaticLibrary(Args)) {
   LA = C.MakeAction(LinkerInputs, types::TY_Image);
-} else if (UseNewOffloadingDriver &&
-   C.getActiveOffloadKinds() != Action::OFK_None) {
+} else if (UseNewOffloadingDriver) {
   LA = C.MakeAction(LinkerInputs, types::TY_Image);
   LA->propagateHostOffloadInfo(C.getActiveOffloadKinds(),
/*BoundArch=*/nullptr);
Index: clang/include/clang/Driver/Options.td
===
--- clang/include/clang/Driver/Options.td
+++ clang/include/clang/Driver/Options.td
@@ -2534,10 +2534,14 @@
   PosFlag, NegFlag, 
BothFlags<[NoArgumentUnused, HelpHidden]>>;
 def static_openmp: Flag<["-"], "static-openmp">,
   HelpText<"Use the static host OpenMP runtime while linking.">;
+def offload_new_driver : Flag<["--"], "offload-new-driver">, 
Flags<[CC1Option]>, Group,
+  HelpText<"Use the new driver for offloading compilation.">;
+def no_offload_new_driver : Flag<["--"], "no-offload-new-driver">, 
Flags<[CC1Option]>, Group,
+  HelpText<"Don't Use the new driver for offloading compilation.">;
 def fopenmp_new_driver : Flag<["-"], "fopenmp-new-driver">, 
Flags<[CC1Option]>, Group,
   HelpText<"Use the new driver for OpenMP offloading.">;
 def fno_openmp_new_driver : Flag<["-"], "fno-openmp-new-driver">, 
Flags<[CC1Option]>, Group,
-  HelpText<"Don't use the new driver for OpenMP offloading.">;
+  Alias, HelpText<"Don't use the new driver for OpenMP 
offloading.">;
 def fno_optimize_sibling_calls : Flag<["-"], "fno-optimize-sibling-calls">, 
Group, Flags<[CC1Option]>,
   HelpText<"Disable tail call optimization, 

[PATCH] D120272: [CUDA] Add driver support for compiling CUDA with the new driver

2022-04-29 Thread Joseph Huber 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 rGc5e5b54350fe: [CUDA] Add driver support for compiling CUDA 
with the new driver (authored by jhuber6).

Changed prior to commit:
  https://reviews.llvm.org/D120272?vs=425261&id=426036#toc

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D120272

Files:
  clang/include/clang/Basic/Cuda.h
  clang/include/clang/Basic/DiagnosticDriverKinds.td
  clang/lib/Driver/Driver.cpp
  clang/lib/Driver/ToolChains/Clang.cpp
  clang/test/Driver/cuda-openmp-driver.cu
  clang/test/Driver/cuda-phases.cu

Index: clang/test/Driver/cuda-phases.cu
===
--- clang/test/Driver/cuda-phases.cu
+++ clang/test/Driver/cuda-phases.cu
@@ -217,3 +217,32 @@
 // DASM2-DAG: [[P8:[0-9]+]]: backend, {[[P7]]}, assembler, (device-[[T]], [[ARCH2]])
 // DASM2-DAG: [[P9:[0-9]+]]: offload, "device-[[T]] ([[TRIPLE]]:[[ARCH2]])" {[[P8]]}, assembler
 // DASM2-NOT: host
+
+//
+// Test the phases generated when using the new offloading driver.
+//
+// RUN: %clang -### -target powerpc64le-ibm-linux-gnu -ccc-print-phases --offload-new-driver \
+// RUN: --offload-arch=sm_52 --offload-arch=sm_70 %s 2>&1 | FileCheck --check-prefix=NEW_DRIVER %s
+// NEW_DRIVER: 0: input, "[[INPUT:.*]]", cuda, (host-cuda)
+// NEW_DRIVER: 1: preprocessor, {0}, cuda-cpp-output, (host-cuda)
+// NEW_DRIVER: 2: compiler, {1}, ir, (host-cuda)
+// NEW_DRIVER: 3: input, "[[INPUT]]", cuda, (device-cuda, sm_52)
+// NEW_DRIVER: 4: preprocessor, {3}, cuda-cpp-output, (device-cuda, sm_52)
+// NEW_DRIVER: 5: compiler, {4}, ir, (device-cuda, sm_52)
+// NEW_DRIVER: 6: backend, {5}, assembler, (device-cuda, sm_52)
+// NEW_DRIVER: 7: assembler, {6}, object, (device-cuda, sm_52)
+// NEW_DRIVER: 8: offload, "device-cuda (nvptx64-nvidia-cuda:sm_52)" {7}, object
+// NEW_DRIVER: 9: offload, "device-cuda (nvptx64-nvidia-cuda:sm_52)" {6}, assembler
+// NEW_DRIVER: 10: linker, {8, 9}, cuda-fatbin, (device-cuda, sm_52)
+// NEW_DRIVER: 11: input, "[[INPUT]]", cuda, (device-cuda, sm_70)
+// NEW_DRIVER: 12: preprocessor, {11}, cuda-cpp-output, (device-cuda, sm_70)
+// NEW_DRIVER: 13: compiler, {12}, ir, (device-cuda, sm_70)
+// NEW_DRIVER: 14: backend, {13}, assembler, (device-cuda, sm_70)
+// NEW_DRIVER: 15: assembler, {14}, object, (device-cuda, sm_70)
+// NEW_DRIVER: 16: offload, "device-cuda (nvptx64-nvidia-cuda:sm_70)" {15}, object
+// NEW_DRIVER: 17: offload, "device-cuda (nvptx64-nvidia-cuda:sm_70)" {14}, assembler
+// NEW_DRIVER: 18: linker, {16, 17}, cuda-fatbin, (device-cuda, sm_70)
+// NEW_DRIVER: 19: offload, "host-cuda (powerpc64le-ibm-linux-gnu)" {2}, "device-cuda (nvptx64-nvidia-cuda:sm_52)" {10}, "device-cuda (nvptx64-nvidia-cuda:sm_70)" {18}, ir
+// NEW_DRIVER: 20: backend, {19}, assembler, (host-cuda)
+// NEW_DRIVER: 21: assembler, {20}, object, (host-cuda)
+// NEW_DRIVER: 22: clang-linker-wrapper, {21}, image, (host-cuda)
Index: clang/test/Driver/cuda-openmp-driver.cu
===
--- /dev/null
+++ clang/test/Driver/cuda-openmp-driver.cu
@@ -0,0 +1,18 @@
+// REQUIRES: x86-registered-target
+// REQUIRES: nvptx-registered-target
+
+// RUN: %clang -### -target x86_64-linux-gnu -nocudalib -ccc-print-bindings -fgpu-rdc \
+// RUN:--offload-new-driver --offload-arch=sm_35 --offload-arch=sm_70 %s 2>&1 \
+// RUN: | FileCheck -check-prefix BINDINGS %s
+
+// BINDINGS: "nvptx64-nvidia-cuda" - "clang", inputs: ["[[INPUT:.+]]"], output: "[[PTX_SM_35:.+]]"
+// BINDINGS-NEXT: "nvptx64-nvidia-cuda" - "NVPTX::Assembler", inputs: ["[[PTX_SM_35]]"], output: "[[CUBIN_SM_35:.+]]"
+// BINDINGS-NEXT: "nvptx64-nvidia-cuda" - "NVPTX::Linker", inputs: ["[[CUBIN_SM_35]]", "[[PTX_SM_35]]"], output: "[[FATBIN_SM_35:.+]]"
+// BINDINGS-NEXT: "nvptx64-nvidia-cuda" - "clang", inputs: ["[[INPUT]]"], output: "[[PTX_SM_70:.+]]"
+// BINDINGS-NEXT: "nvptx64-nvidia-cuda" - "NVPTX::Assembler", inputs: ["[[PTX_SM_70:.+]]"], output: "[[CUBIN_SM_70:.+]]"
+// BINDINGS-NEXT: "nvptx64-nvidia-cuda" - "NVPTX::Linker", inputs: ["[[CUBIN_SM_70]]", "[[PTX_SM_70:.+]]"], output: "[[FATBIN_SM_70:.+]]"
+// BINDINGS-NEXT: "x86_64-unknown-linux-gnu" - "clang", inputs: ["[[INPUT]]", "[[FATBIN_SM_35]]", "[[FATBIN_SM_70]]"], output: "[[HOST_OBJ:.+]]"
+// BINDINGS-NEXT: "x86_64-unknown-linux-gnu" - "Offload::Linker", inputs: ["[[HOST_OBJ]]"], output: "a.out"
+
+// RUN: %clang -### -nocudalib --offload-new-driver %s 2>&1 | FileCheck -check-prefix RDC %s
+// RDC: error: Using '--offload-new-driver' requires '-fgpu-rdc'
Index: clang/lib/Driver/ToolChains/Clang.cpp
===
--- clang/lib/Driver/ToolChains/Clang.cpp
+++ clang/lib/Driver/ToolChains/Clang.cpp
@@ -6236,6 +6236,9 @@
   }
 
   if (IsCuda || IsHIP) {
+if (!Args.hasFlag(options::OPT_f

[PATCH] D123773: [clang][analyzer][ctu] Make CTU a two phase analysis

2022-04-29 Thread Gabor Marton via Phabricator via cfe-commits
martong updated this revision to Diff 426037.
martong added a comment.

- Add more explanatory comments to the values of ctu-phase1-inlining
- Fix typo in comments in ctu-on-demand-parsing tests
- Remove stale comment, config options are desribed elsewhere


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D123773

Files:
  clang/include/clang/CrossTU/CrossTranslationUnit.h
  clang/include/clang/StaticAnalyzer/Core/AnalyzerOptions.def
  clang/include/clang/StaticAnalyzer/Core/AnalyzerOptions.h
  clang/include/clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h
  clang/include/clang/StaticAnalyzer/Core/PathSensitive/CoreEngine.h
  clang/include/clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h
  clang/lib/CrossTU/CrossTranslationUnit.cpp
  clang/lib/StaticAnalyzer/Core/AnalyzerOptions.cpp
  clang/lib/StaticAnalyzer/Core/CallEvent.cpp
  clang/lib/StaticAnalyzer/Core/CoreEngine.cpp
  clang/lib/StaticAnalyzer/Core/ExprEngineCallAndReturn.cpp
  clang/lib/StaticAnalyzer/Frontend/AnalysisConsumer.cpp
  clang/test/Analysis/Inputs/ctu-onego-existingdef-other.cpp
  
clang/test/Analysis/Inputs/ctu-onego-existingdef-other.cpp.externalDefMap.ast-dump.txt
  clang/test/Analysis/Inputs/ctu-onego-indirect-other.cpp
  
clang/test/Analysis/Inputs/ctu-onego-indirect-other.cpp.externalDefMap.ast-dump.txt
  clang/test/Analysis/Inputs/ctu-onego-small-other.cpp
  
clang/test/Analysis/Inputs/ctu-onego-small-other.cpp.externalDefMap.ast-dump.txt
  clang/test/Analysis/Inputs/ctu-onego-toplevel-other.cpp
  
clang/test/Analysis/Inputs/ctu-onego-toplevel-other.cpp.externalDefMap.ast-dump.txt
  clang/test/Analysis/analyzer-config.c
  clang/test/Analysis/ctu-implicit.c
  clang/test/Analysis/ctu-main.c
  clang/test/Analysis/ctu-main.cpp
  clang/test/Analysis/ctu-on-demand-parsing.c
  clang/test/Analysis/ctu-on-demand-parsing.cpp
  clang/test/Analysis/ctu-onego-existingdef.cpp
  clang/test/Analysis/ctu-onego-indirect.cpp
  clang/test/Analysis/ctu-onego-small.cpp
  clang/test/Analysis/ctu-onego-toplevel.cpp

Index: clang/test/Analysis/ctu-onego-toplevel.cpp
===
--- /dev/null
+++ clang/test/Analysis/ctu-onego-toplevel.cpp
@@ -0,0 +1,54 @@
+// RUN: rm -rf %t && mkdir %t
+// RUN: mkdir -p %t/ctudir
+// RUN: %clang_cc1 -std=c++14 -triple x86_64-pc-linux-gnu \
+// RUN:   -emit-pch -o %t/ctudir/ctu-onego-toplevel-other.cpp.ast %S/Inputs/ctu-onego-toplevel-other.cpp
+// RUN: cp %S/Inputs/ctu-onego-toplevel-other.cpp.externalDefMap.ast-dump.txt %t/ctudir/externalDefMap.txt
+
+// RUN: %clang_analyze_cc1 -std=c++14 -triple x86_64-pc-linux-gnu \
+// RUN:   -analyzer-checker=core,debug.ExprInspection \
+// RUN:   -analyzer-config eagerly-assume=false \
+// RUN:   -analyzer-config experimental-enable-naive-ctu-analysis=true \
+// RUN:   -analyzer-config ctu-dir=%t/ctudir \
+// RUN:   -analyzer-config ctu-phase1-inlining=none \
+// RUN:   -verify=ctu %s
+
+// RUN: %clang_analyze_cc1 -std=c++14 -triple x86_64-pc-linux-gnu \
+// RUN:   -analyzer-checker=core,debug.ExprInspection \
+// RUN:   -analyzer-config eagerly-assume=false \
+// RUN:   -analyzer-config experimental-enable-naive-ctu-analysis=true \
+// RUN:   -analyzer-config ctu-dir=%t/ctudir \
+// RUN:   -analyzer-config ctu-phase1-inlining=none \
+// RUN:   -analyzer-config display-ctu-progress=true \
+// RUN:   -analyzer-display-progress \
+// RUN:   -verify=ctu %s 2>&1 | FileCheck %s
+//
+// CallGraph: c->b
+// topological sort: c, b
+// Note that `other` calls into `b` but that is not visible in the CallGraph
+// b/c that happens in another TU.
+
+// During the onego CTU analysis, we start with c() as top level function.
+// Then we visit b() as non-toplevel during the processing of the FWList, thus
+// that would not be visited as toplevel without special care.
+
+// `c` is analyzed as toplevel and during that the other TU is loaded:
+// CHECK: ANALYZE (Path,  Inline_Regular): {{.*}} c(int){{.*}}CTU loaded AST file
+// next, `b` is analyzed as toplevel:
+// CHECK: ANALYZE (Path,  Inline_Regular): {{.*}} b(int)
+
+void b(int x);
+void other(int y);
+void c(int y) {
+  other(y);
+  return;
+  // The below call is here to form the proper CallGraph, but will not be
+  // analyzed.
+  b(1);
+}
+
+void b(int x) {
+  if (x == 0)
+(void)(1 / x);
+// ctu-warning@-1{{Division by zero}}
+// We receive the above warning only if `b` is analyzed as top-level.
+}
Index: clang/test/Analysis/ctu-onego-small.cpp
===
--- /dev/null
+++ clang/test/Analysis/ctu-onego-small.cpp
@@ -0,0 +1,51 @@
+// RUN: rm -rf %t && mkdir %t
+// RUN: mkdir -p %t/ctudir
+// RUN: %clang_cc1 -std=c++14 -triple x86_64-pc-linux-gnu \
+// RUN:   -emit-pch -o %t/ctudir/ctu-onego-small-other.cpp.ast %S/Inputs/ctu-onego-small-other.cpp
+// RUN: cp %S/Inputs/ctu-onego-small-other.cpp.externalDefMap.ast-dump.txt %t/ctudir/e

[PATCH] D111548: [Clang] Add the `annotate_type` attribute

2022-04-29 Thread Martin Böhme via Phabricator via cfe-commits
mboehme added inline comments.



Comment at: clang/test/SemaCXX/annotate-type.cpp:2
+// RUN: %clang_cc1 %s -std=c++17 -fsyntax-only -verify
+
+struct S1 {

aaron.ballman wrote:
> mboehme wrote:
> > aaron.ballman wrote:
> > > mboehme wrote:
> > > > aaron.ballman wrote:
> > > > > mboehme wrote:
> > > > > > aaron.ballman wrote:
> > > > > > > Can you also add some test coverage for applying the attribute to 
> > > > > > > a declaration instead of a type or not giving it any arguments? 
> > > > > > > Also, should test arguments which are not a constant expression.
> > > > > > I've added tests as you suggested, though I put most of them in 
> > > > > > Sema/annotate-type.c, as they're not specific to C++.
> > > > > > 
> > > > > > Thanks for prompting me to do this -- the tests caused me to notice 
> > > > > > and fix a number of bugs.
> > > > > > 
> > > > > > I haven't managed to diagnose the case when the attribute appears 
> > > > > > at the beginning of the declaration. It seems to me that, at the 
> > > > > > point where I've added the check, this case is indistinguishable 
> > > > > > from an attribute that appears on the type. In both cases, the 
> > > > > > `TAL` is `TAL_DeclSpec`, and the attribute is contained in 
> > > > > > `DeclSpec::getAttributes()`. This is because 
> > > > > > `Parser::ParseSimpleDeclaration` forwards the declaration 
> > > > > > attributes to the `DeclSpec`:
> > > > > > 
> > > > > > https://github.com/llvm/llvm-project/blob/main/clang/lib/Parse/ParseDecl.cpp#L1851
> > > > > > 
> > > > > > I believe if I wanted to prohibit this case, I would need to add a 
> > > > > > check to `Parser::ParseStatementOrDeclaration` and prohibit any 
> > > > > > occurrences of `annotate_type` there. However, this seems the wrong 
> > > > > > place to do this because it doesn't contain any specific processing 
> > > > > > for other attributes.
> > > > > > 
> > > > > > I've noticed that Clang also doesn't prohibit other type attributes 
> > > > > > (even ones with C++ 11 syntax) from being applied to declarations. 
> > > > > > For example: https://godbolt.org/z/Yj1zWY7nn
> > > > > > 
> > > > > > How do you think I should proceed here? I think the underlying 
> > > > > > issue is that Clang doesn't always distinguish cleanly between 
> > > > > > declaration attributes and type attributes, and fixing this might 
> > > > > > be nontrivial.
> > > > > > How do you think I should proceed here? I think the underlying 
> > > > > > issue is that Clang doesn't always distinguish cleanly between 
> > > > > > declaration attributes and type attributes, and fixing this might 
> > > > > > be nontrivial.
> > > > > 
> > > > > This is a general issue with attribute processing. I would imagine 
> > > > > that SemaDeclAttr.cpp should be able to diagnose that case when the 
> > > > > attribute only applies to types and not declarations, but it'd take 
> > > > > some investigation for me to be sure.
> > > > > 
> > > > > Because this issue isn't new to your situation, I'd recommend filing 
> > > > > an issue about the general problem and then we can solve that later.
> > > > I've done some more investigation myself, and I think I've come up with 
> > > > a solution; actually, two potential solutions. I have draft patches for 
> > > > both of these; I wanted to run these by you here first, so I haven't 
> > > > opened a bug yet.
> > > > 
> > > > I'd appreciate your input on how you'd prefer me to proceed with this. 
> > > > I do think it makes sense to do this work now because otherwise, people 
> > > > will start putting `annotate_type` in places where it doesn't belong, 
> > > > and then we'll have to keep supporting that in the future.
> > > > 
> > > > **My preferred solution**
> > > > 
> > > > https://reviews.llvm.org/D124081
> > > > 
> > > > This adds a function `DiagnoseCXX11NonDeclAttrs()` and calls it in all 
> > > > places where we should reject attributes that can't be put on 
> > > > declarations. (As part of this work, I noticed that `gsl::suppress` 
> > > > should be a `DeclOrStmtAttr`, not just a `StmtAttr`.)
> > > > 
> > > > Advantages:
> > > > - Not very invasive.
> > > > Disadvantages:
> > > > - Need to make sure we call `DiagnoseCXX11NonDeclAttrs()` everywhere 
> > > > that non-declaration attributes should be rejected. (Not sure if I've 
> > > > identified all of those places yet?)
> > > > 
> > > > **Alternative solution**
> > > > 
> > > > https://reviews.llvm.org/D124083
> > > > 
> > > > This adds an `appertainsTo` parameter to `ParseCXX11Attributes()` and 
> > > > other "parse attributes" functions that call it. This parameter 
> > > > specifies whether the attributes in the place where they're currently 
> > > > being parsed appertain to a declaration, statement or type. If 
> > > > `ParseCXX11Attributes()` encounters an attribute that is not compatible 
> > > > with `appertainsTo`, it outputs a diagnostic.
> > > > 
> > > > Advantages:
> > > > - Every call to `ParseCXX1

[PATCH] D116280: [clang] adds unary type trait checks as compiler built-ins

2022-04-29 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 whatever changes are needed based on feedback from the original 
review (I noticed Richard has some suggestions there which may impact this 
review).


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D116280

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


[clang] 23c10e8 - [clang] Eliminate TypeProcessingState::trivial.

2022-04-29 Thread Martin Boehme via cfe-commits

Author: Martin Boehme
Date: 2022-04-29T15:34:30+02:00
New Revision: 23c10e8d0f97dc38c9f620541c7f3ffd04bef905

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

LOG: [clang] Eliminate TypeProcessingState::trivial.

This flag is redundant -- it's true iff `savedAttrs` is empty.

Querying `savedAttrs.empty()` should not take any more time than querying the
`trivial` flag, so this should not have a performance impact either.

I noticed this while working on https://reviews.llvm.org/D111548.

Reviewed By: aaron.ballman

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

Added: 


Modified: 
clang/lib/Sema/SemaType.cpp

Removed: 




diff  --git a/clang/lib/Sema/SemaType.cpp b/clang/lib/Sema/SemaType.cpp
index c0a2af7c98eb..6f34e4237bcb 100644
--- a/clang/lib/Sema/SemaType.cpp
+++ b/clang/lib/Sema/SemaType.cpp
@@ -166,12 +166,6 @@ namespace {
 /// DeclSpec.
 unsigned chunkIndex;
 
-/// Whether there are non-trivial modifications to the decl spec.
-bool trivial;
-
-/// Whether we saved the attributes in the decl spec.
-bool hasSavedAttrs;
-
 /// The original set of attributes on the DeclSpec.
 SmallVector savedAttrs;
 
@@ -200,8 +194,7 @@ namespace {
   public:
 TypeProcessingState(Sema &sema, Declarator &declarator)
 : sema(sema), declarator(declarator),
-  chunkIndex(declarator.getNumTypeObjects()), trivial(true),
-  hasSavedAttrs(false), parsedNoDeref(false) {}
+  chunkIndex(declarator.getNumTypeObjects()), parsedNoDeref(false) {}
 
 Sema &getSema() const {
   return sema;
@@ -233,13 +226,12 @@ namespace {
 /// Save the current set of attributes on the DeclSpec.
 void saveDeclSpecAttrs() {
   // Don't try to save them multiple times.
-  if (hasSavedAttrs) return;
+  if (!savedAttrs.empty())
+return;
 
   DeclSpec &spec = getMutableDeclSpec();
   llvm::append_range(savedAttrs,
  llvm::make_pointer_range(spec.getAttributes()));
-  trivial &= savedAttrs.empty();
-  hasSavedAttrs = true;
 }
 
 /// Record that we had nowhere to put the given type attribute.
@@ -330,23 +322,18 @@ namespace {
 bool didParseNoDeref() const { return parsedNoDeref; }
 
 ~TypeProcessingState() {
-  if (trivial) return;
+  if (savedAttrs.empty())
+return;
 
-  restoreDeclSpecAttrs();
+  getMutableDeclSpec().getAttributes().clearListOnly();
+  for (ParsedAttr *AL : savedAttrs)
+getMutableDeclSpec().getAttributes().addAtEnd(AL);
 }
 
   private:
 DeclSpec &getMutableDeclSpec() const {
   return const_cast(declarator.getDeclSpec());
 }
-
-void restoreDeclSpecAttrs() {
-  assert(hasSavedAttrs);
-
-  getMutableDeclSpec().getAttributes().clearListOnly();
-  for (ParsedAttr *AL : savedAttrs)
-getMutableDeclSpec().getAttributes().addAtEnd(AL);
-}
   };
 } // end anonymous namespace
 



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


[PATCH] D123783: [clang] Eliminate TypeProcessingState::trivial.

2022-04-29 Thread Martin Böhme via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
mboehme marked an inline comment as done.
Closed by commit rG23c10e8d0f97: [clang] Eliminate 
TypeProcessingState::trivial. (authored by mboehme).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D123783

Files:
  clang/lib/Sema/SemaType.cpp


Index: clang/lib/Sema/SemaType.cpp
===
--- clang/lib/Sema/SemaType.cpp
+++ clang/lib/Sema/SemaType.cpp
@@ -166,12 +166,6 @@
 /// DeclSpec.
 unsigned chunkIndex;
 
-/// Whether there are non-trivial modifications to the decl spec.
-bool trivial;
-
-/// Whether we saved the attributes in the decl spec.
-bool hasSavedAttrs;
-
 /// The original set of attributes on the DeclSpec.
 SmallVector savedAttrs;
 
@@ -200,8 +194,7 @@
   public:
 TypeProcessingState(Sema &sema, Declarator &declarator)
 : sema(sema), declarator(declarator),
-  chunkIndex(declarator.getNumTypeObjects()), trivial(true),
-  hasSavedAttrs(false), parsedNoDeref(false) {}
+  chunkIndex(declarator.getNumTypeObjects()), parsedNoDeref(false) {}
 
 Sema &getSema() const {
   return sema;
@@ -233,13 +226,12 @@
 /// Save the current set of attributes on the DeclSpec.
 void saveDeclSpecAttrs() {
   // Don't try to save them multiple times.
-  if (hasSavedAttrs) return;
+  if (!savedAttrs.empty())
+return;
 
   DeclSpec &spec = getMutableDeclSpec();
   llvm::append_range(savedAttrs,
  llvm::make_pointer_range(spec.getAttributes()));
-  trivial &= savedAttrs.empty();
-  hasSavedAttrs = true;
 }
 
 /// Record that we had nowhere to put the given type attribute.
@@ -330,23 +322,18 @@
 bool didParseNoDeref() const { return parsedNoDeref; }
 
 ~TypeProcessingState() {
-  if (trivial) return;
+  if (savedAttrs.empty())
+return;
 
-  restoreDeclSpecAttrs();
+  getMutableDeclSpec().getAttributes().clearListOnly();
+  for (ParsedAttr *AL : savedAttrs)
+getMutableDeclSpec().getAttributes().addAtEnd(AL);
 }
 
   private:
 DeclSpec &getMutableDeclSpec() const {
   return const_cast(declarator.getDeclSpec());
 }
-
-void restoreDeclSpecAttrs() {
-  assert(hasSavedAttrs);
-
-  getMutableDeclSpec().getAttributes().clearListOnly();
-  for (ParsedAttr *AL : savedAttrs)
-getMutableDeclSpec().getAttributes().addAtEnd(AL);
-}
   };
 } // end anonymous namespace
 


Index: clang/lib/Sema/SemaType.cpp
===
--- clang/lib/Sema/SemaType.cpp
+++ clang/lib/Sema/SemaType.cpp
@@ -166,12 +166,6 @@
 /// DeclSpec.
 unsigned chunkIndex;
 
-/// Whether there are non-trivial modifications to the decl spec.
-bool trivial;
-
-/// Whether we saved the attributes in the decl spec.
-bool hasSavedAttrs;
-
 /// The original set of attributes on the DeclSpec.
 SmallVector savedAttrs;
 
@@ -200,8 +194,7 @@
   public:
 TypeProcessingState(Sema &sema, Declarator &declarator)
 : sema(sema), declarator(declarator),
-  chunkIndex(declarator.getNumTypeObjects()), trivial(true),
-  hasSavedAttrs(false), parsedNoDeref(false) {}
+  chunkIndex(declarator.getNumTypeObjects()), parsedNoDeref(false) {}
 
 Sema &getSema() const {
   return sema;
@@ -233,13 +226,12 @@
 /// Save the current set of attributes on the DeclSpec.
 void saveDeclSpecAttrs() {
   // Don't try to save them multiple times.
-  if (hasSavedAttrs) return;
+  if (!savedAttrs.empty())
+return;
 
   DeclSpec &spec = getMutableDeclSpec();
   llvm::append_range(savedAttrs,
  llvm::make_pointer_range(spec.getAttributes()));
-  trivial &= savedAttrs.empty();
-  hasSavedAttrs = true;
 }
 
 /// Record that we had nowhere to put the given type attribute.
@@ -330,23 +322,18 @@
 bool didParseNoDeref() const { return parsedNoDeref; }
 
 ~TypeProcessingState() {
-  if (trivial) return;
+  if (savedAttrs.empty())
+return;
 
-  restoreDeclSpecAttrs();
+  getMutableDeclSpec().getAttributes().clearListOnly();
+  for (ParsedAttr *AL : savedAttrs)
+getMutableDeclSpec().getAttributes().addAtEnd(AL);
 }
 
   private:
 DeclSpec &getMutableDeclSpec() const {
   return const_cast(declarator.getDeclSpec());
 }
-
-void restoreDeclSpecAttrs() {
-  assert(hasSavedAttrs);
-
-  getMutableDeclSpec().getAttributes().clearListOnly();
-  for (ParsedAttr *AL : savedAttrs)
-getMutableDeclSpec().getAttributes().addAtEnd(AL);
-}
   };
 } // end anonymous namespace
 
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi

[PATCH] D124556: [NFC] Prevent shadowing a variable declared in `if`

2022-04-29 Thread Hubert Tong via Phabricator via cfe-commits
hubert.reinterpretcast added a comment.

In D124556#3482224 , @ken-matsui 
wrote:

> Thank you!

Thanks in turn.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124556

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


[PATCH] D85528: [analyzer] Fix cast evaluation on scoped enums in ExprEngine

2022-04-29 Thread Gabor Marton via Phabricator via cfe-commits
martong accepted this revision.
martong added a comment.
This revision is now accepted and ready to land.

LGTM! Thanks!


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

https://reviews.llvm.org/D85528

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


[clang] 9e7c996 - Additionally set f32 mode with denormal-fp-math

2022-04-29 Thread David Candler via cfe-commits

Author: David Candler
Date: 2022-04-29T15:06:32+01:00
New Revision: 9e7c9967c3fd573ef53b145e24e6a1e6ba930c82

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

LOG: Additionally set f32 mode with denormal-fp-math

When the denormal-fp-math option is used, this should set the
denormal handling mode for all floating point types. However,
currently 32-bit float types can ignore this setting as there is a
variant of the option, denormal-fp-math-f32, specifically for that type
which takes priority when checking the mode based on type and remains
at the default of IEEE. From the description, denormal-fp-math would
be expected to set the mode for floats unless overridden by the f32
variant, and code in the front end only emits the f32 option if it is
different to the general one, so setting just denormal-fp-math should
be valid.

This patch changes the denormal-fp-math option to also set the f32
mode. If denormal-fp-math-f32 is also specified, this is then
overridden as expected, but if it is absent floats will be set to the
mode specified by the former option, rather than remain on the default.

Reviewed By: arsenm

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

Added: 
clang/test/CodeGen/denormalfpmode-f32.c

Modified: 
clang/lib/Driver/ToolChains/Clang.cpp
clang/lib/Frontend/CompilerInvocation.cpp

Removed: 




diff  --git a/clang/lib/Driver/ToolChains/Clang.cpp 
b/clang/lib/Driver/ToolChains/Clang.cpp
index 0e34d125873b..b5f9e0a13a6f 100644
--- a/clang/lib/Driver/ToolChains/Clang.cpp
+++ b/clang/lib/Driver/ToolChains/Clang.cpp
@@ -2884,6 +2884,7 @@ static void RenderFloatingPointOptions(const ToolChain 
&TC, const Driver &D,
 
 case options::OPT_fdenormal_fp_math_EQ:
   DenormalFPMath = llvm::parseDenormalFPAttribute(A->getValue());
+  DenormalFP32Math = DenormalFPMath;
   if (!DenormalFPMath.isValid()) {
 D.Diag(diag::err_drv_invalid_value)
 << A->getAsString(Args) << A->getValue();

diff  --git a/clang/lib/Frontend/CompilerInvocation.cpp 
b/clang/lib/Frontend/CompilerInvocation.cpp
index 66072875765d..b35e3f4fd78a 100644
--- a/clang/lib/Frontend/CompilerInvocation.cpp
+++ b/clang/lib/Frontend/CompilerInvocation.cpp
@@ -1526,7 +1526,8 @@ void CompilerInvocation::GenerateCodeGenArgs(
   if (Opts.FPDenormalMode != llvm::DenormalMode::getIEEE())
 GenerateArg(Args, OPT_fdenormal_fp_math_EQ, Opts.FPDenormalMode.str(), SA);
 
-  if (Opts.FP32DenormalMode != llvm::DenormalMode::getIEEE())
+  if ((Opts.FPDenormalMode != Opts.FP32DenormalMode) ||
+  (Opts.FP32DenormalMode != llvm::DenormalMode::getIEEE()))
 GenerateArg(Args, OPT_fdenormal_fp_math_f32_EQ, 
Opts.FP32DenormalMode.str(),
 SA);
 
@@ -1879,6 +1880,7 @@ bool CompilerInvocation::ParseCodeGenArgs(CodeGenOptions 
&Opts, ArgList &Args,
   if (Arg *A = Args.getLastArg(OPT_fdenormal_fp_math_EQ)) {
 StringRef Val = A->getValue();
 Opts.FPDenormalMode = llvm::parseDenormalFPAttribute(Val);
+Opts.FP32DenormalMode = Opts.FPDenormalMode;
 if (!Opts.FPDenormalMode.isValid())
   Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args) << Val;
   }

diff  --git a/clang/test/CodeGen/denormalfpmode-f32.c 
b/clang/test/CodeGen/denormalfpmode-f32.c
new file mode 100644
index ..f89202bcc9ed
--- /dev/null
+++ b/clang/test/CodeGen/denormalfpmode-f32.c
@@ -0,0 +1,35 @@
+// RUN: %clang_cc1 -S %s -emit-llvm -o - | FileCheck %s 
--check-prefixes=CHECK-ATTR,CHECK-NONE,CHECK-F32-NONE
+// RUN: %clang_cc1 -S -fdenormal-fp-math=ieee %s -emit-llvm -o - | FileCheck 
%s --check-prefixes=CHECK-ATTR,CHECK-NONE,CHECK-F32-NONE
+// RUN: %clang_cc1 -S -fdenormal-fp-math=preserve-sign %s -emit-llvm -o - | 
FileCheck %s --check-prefixes=CHECK-ATTR,CHECK-PS,CHECK-F32-NONE
+// RUN: %clang_cc1 -S -fdenormal-fp-math=positive-zero %s -emit-llvm -o - | 
FileCheck %s --check-prefixes=CHECK-ATTR,CHECK-PZ,CHECK-F32-NONE
+
+// RUN: %clang_cc1 -S -fdenormal-fp-math-f32=ieee %s -emit-llvm -o - | 
FileCheck %s --check-prefixes=CHECK-ATTR,CHECK-NONE,CHECK-F32-NONE
+// RUN: %clang_cc1 -S -fdenormal-fp-math=ieee -fdenormal-fp-math-f32=ieee %s 
-emit-llvm -o - | FileCheck %s 
--check-prefixes=CHECK-ATTR,CHECK-NONE,CHECK-F32-NONE
+// RUN: %clang_cc1 -S -fdenormal-fp-math=preserve-sign 
-fdenormal-fp-math-f32=ieee %s -emit-llvm -o - | FileCheck %s 
--check-prefixes=CHECK-ATTR,CHECK-PS,CHECK-F32-IEEE
+// RUN: %clang_cc1 -S -fdenormal-fp-math=positive-zero 
-fdenormal-fp-math-f32=ieee %s -emit-llvm -o - | FileCheck %s 
--check-prefixes=CHECK-ATTR,CHECK-PZ,CHECK-F32-IEEE
+
+// RUN: %clang_cc1 -S -fdenormal-fp-math-f32=preserve-sign %s -emit-llvm -o - 
| FileCheck %s --check-prefixes=CHECK-ATTR,CHECK-NONE,CHECK-F32-PS
+// RUN: %clang_cc1 -S -fdenormal-fp-math=ieee 
-fdenorma

[PATCH] D122589: Additionally set f32 mode with denormal-fp-math

2022-04-29 Thread David Candler via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG9e7c9967c3fd: Additionally set f32 mode with 
denormal-fp-math (authored by dcandler).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D122589

Files:
  clang/lib/Driver/ToolChains/Clang.cpp
  clang/lib/Frontend/CompilerInvocation.cpp
  clang/test/CodeGen/denormalfpmode-f32.c


Index: clang/test/CodeGen/denormalfpmode-f32.c
===
--- /dev/null
+++ clang/test/CodeGen/denormalfpmode-f32.c
@@ -0,0 +1,35 @@
+// RUN: %clang_cc1 -S %s -emit-llvm -o - | FileCheck %s 
--check-prefixes=CHECK-ATTR,CHECK-NONE,CHECK-F32-NONE
+// RUN: %clang_cc1 -S -fdenormal-fp-math=ieee %s -emit-llvm -o - | FileCheck 
%s --check-prefixes=CHECK-ATTR,CHECK-NONE,CHECK-F32-NONE
+// RUN: %clang_cc1 -S -fdenormal-fp-math=preserve-sign %s -emit-llvm -o - | 
FileCheck %s --check-prefixes=CHECK-ATTR,CHECK-PS,CHECK-F32-NONE
+// RUN: %clang_cc1 -S -fdenormal-fp-math=positive-zero %s -emit-llvm -o - | 
FileCheck %s --check-prefixes=CHECK-ATTR,CHECK-PZ,CHECK-F32-NONE
+
+// RUN: %clang_cc1 -S -fdenormal-fp-math-f32=ieee %s -emit-llvm -o - | 
FileCheck %s --check-prefixes=CHECK-ATTR,CHECK-NONE,CHECK-F32-NONE
+// RUN: %clang_cc1 -S -fdenormal-fp-math=ieee -fdenormal-fp-math-f32=ieee %s 
-emit-llvm -o - | FileCheck %s 
--check-prefixes=CHECK-ATTR,CHECK-NONE,CHECK-F32-NONE
+// RUN: %clang_cc1 -S -fdenormal-fp-math=preserve-sign 
-fdenormal-fp-math-f32=ieee %s -emit-llvm -o - | FileCheck %s 
--check-prefixes=CHECK-ATTR,CHECK-PS,CHECK-F32-IEEE
+// RUN: %clang_cc1 -S -fdenormal-fp-math=positive-zero 
-fdenormal-fp-math-f32=ieee %s -emit-llvm -o - | FileCheck %s 
--check-prefixes=CHECK-ATTR,CHECK-PZ,CHECK-F32-IEEE
+
+// RUN: %clang_cc1 -S -fdenormal-fp-math-f32=preserve-sign %s -emit-llvm -o - 
| FileCheck %s --check-prefixes=CHECK-ATTR,CHECK-NONE,CHECK-F32-PS
+// RUN: %clang_cc1 -S -fdenormal-fp-math=ieee 
-fdenormal-fp-math-f32=preserve-sign %s -emit-llvm -o - | FileCheck %s 
--check-prefixes=CHECK-ATTR,CHECK-NONE,CHECK-F32-PS
+// RUN: %clang_cc1 -S -fdenormal-fp-math=preserve-sign 
-fdenormal-fp-math-f32=preserve-sign %s -emit-llvm -o - | FileCheck %s 
--check-prefixes=CHECK-ATTR,CHECK-PS,CHECK-F32-NONE
+// RUN: %clang_cc1 -S -fdenormal-fp-math=positive-zero 
-fdenormal-fp-math-f32=preserve-sign %s -emit-llvm -o - | FileCheck %s 
--check-prefixes=CHECK-ATTR,CHECK-PZ,CHECK-F32-PS
+
+// RUN: %clang_cc1 -S -fdenormal-fp-math-f32=positive-zero %s -emit-llvm -o - 
| FileCheck %s --check-prefixes=CHECK-ATTR,CHECK-NONE,CHECK-F32-PZ
+// RUN: %clang_cc1 -S -fdenormal-fp-math=ieee 
-fdenormal-fp-math-f32=positive-zero %s -emit-llvm -o - | FileCheck %s 
--check-prefixes=CHECK-ATTR,CHECK-NONE,CHECK-F32-PZ
+// RUN: %clang_cc1 -S -fdenormal-fp-math=preserve-sign 
-fdenormal-fp-math-f32=positive-zero %s -emit-llvm -o - | FileCheck %s 
--check-prefixes=CHECK-ATTR,CHECK-PS,CHECK-F32-PZ
+// RUN: %clang_cc1 -S -fdenormal-fp-math=positive-zero 
-fdenormal-fp-math-f32=positive-zero %s -emit-llvm -o - | FileCheck %s 
--check-prefixes=CHECK-ATTR,CHECK-PZ,CHECK-F32-NONE
+
+// CHECK-LABEL: main
+
+// CHECK-ATTR: attributes #0 =
+// CHECK-NONE-NOT:"denormal-fp-math"
+// CHECK-IEEE: "denormal-fp-math"="ieee,ieee"
+// CHECK-PS: "denormal-fp-math"="preserve-sign,preserve-sign"
+// CHECK-PZ: "denormal-fp-math"="positive-zero,positive-zero"
+// CHECK-F32-NONE-NOT:"denormal-fp-math-f32"
+// CHECK-F32-IEEE: "denormal-fp-math-f32"="ieee,ieee"
+// CHECK-F32-PS: "denormal-fp-math-f32"="preserve-sign,preserve-sign"
+// CHECK-F32-PZ: "denormal-fp-math-f32"="positive-zero,positive-zero"
+
+int main(void) {
+  return 0;
+}
Index: clang/lib/Frontend/CompilerInvocation.cpp
===
--- clang/lib/Frontend/CompilerInvocation.cpp
+++ clang/lib/Frontend/CompilerInvocation.cpp
@@ -1526,7 +1526,8 @@
   if (Opts.FPDenormalMode != llvm::DenormalMode::getIEEE())
 GenerateArg(Args, OPT_fdenormal_fp_math_EQ, Opts.FPDenormalMode.str(), SA);
 
-  if (Opts.FP32DenormalMode != llvm::DenormalMode::getIEEE())
+  if ((Opts.FPDenormalMode != Opts.FP32DenormalMode) ||
+  (Opts.FP32DenormalMode != llvm::DenormalMode::getIEEE()))
 GenerateArg(Args, OPT_fdenormal_fp_math_f32_EQ, 
Opts.FP32DenormalMode.str(),
 SA);
 
@@ -1879,6 +1880,7 @@
   if (Arg *A = Args.getLastArg(OPT_fdenormal_fp_math_EQ)) {
 StringRef Val = A->getValue();
 Opts.FPDenormalMode = llvm::parseDenormalFPAttribute(Val);
+Opts.FP32DenormalMode = Opts.FPDenormalMode;
 if (!Opts.FPDenormalMode.isValid())
   Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args) << Val;
   }
Index: clang/lib/Driver/ToolChains/Clang.cpp
===
--- clang/lib/Driver/ToolChains/Clang.cpp
+++ clang/lib/Driver/ToolChains/Clang.cpp
@@ -2884,6 +2884,7 @@
 
 case 

[PATCH] D124658: [analyzer] Canonicalize SymIntExpr so the RHS is positive when possible

2022-04-29 Thread Tomasz Kamiński via Phabricator via cfe-commits
tomasz-kaminski-sonarsource marked 2 inline comments as done.
tomasz-kaminski-sonarsource added a comment.

> Could you please elaborate on this? I understand that you'd like to simplify 
> certain binary operations by merging the RHS and the operand, however, I 
> don't see what are the empirical problems that this patch supposed to fix. 
> E.g. did you encounter a crash without the fix, or was it the mentioned 
> infeasible state (`(l - 1000) > 0`) that caused a false positive?

Yes, the patch is aiming to fix false positives raised from unfeasible paths, 
that were guarded by conditions that encountered this problem.

> If that is the case, I believe the huge cast patch 
>  is going to solve it. Could you please 
> check if those infeasible cases are solved by the mentioned D103096 
>  (you have to set 
> `support-symbolic-integer-casts=true`) ?

Indeed all false positives that I am fixing with this patch would be also fixed 
by proper modeling of the cast of the integers. 
However this patch:

- does not in any way affect the correctness of the symbol values, or the 
upcoming patch
- fixes them even without that `support-symbolic-integer-casts` enabled, and 
with nearly zero performance impact (two additional comparisons)




Comment at: clang/lib/StaticAnalyzer/Core/SimpleSValBuilder.cpp:204
+// subtraction/addition of the negated value.
+if (!RHS.isNegative()) {
+  ConvertedRHS = &BasicVals.Convert(resultTy, RHS);

steakhal wrote:
> I would rather swap these branches though, to leave the default case (aka. 
> this) to the end.
I folded the `RHS.isNegative()` into the if for the 
`BinaryOperator::isAssociative(op)`, as same conversion is performed in final 
else branch.



Comment at: clang/lib/StaticAnalyzer/Core/SimpleSValBuilder.cpp:212-219
+  llvm::APSInt ConvertedRHSValue = resultIntTy.convert(RHS);
+  // Check if the negation of the RHS is representable,
+  // i.e., the resultTy is signed, and it is not the lowest
+  // representable negative value.
+  if (ConvertedRHSValue > resultIntTy.getMinValue()) {
+ConvertedRHS = &BasicVals.getValue(-ConvertedRHSValue);
+op = (op == BO_Add) ? BO_Sub : BO_Add;

steakhal wrote:
> Somehow I miss a check for signedness here.
> Why do you think it would be only triggered for signed types?
> 
> I have a guess, that since we already handled `x +-0`, SymIntExprs like `x - 
> (-0)` cannot exist here, thus cannot trigger this condition spuriously. I 
> cannot think of any ther example that could cause this misbehaving. So in 
> that sense `ConvertedRHSValue > resultIntTy.getMinValue()` implies *at this 
> place* that `ConvertedRHSValue.isSigned()`.
> I would rather see this redundant check here to make the correctness 
> reasoning local though.
The integer representation does not have negative zeros (the standard and clang 
assume two's complement). However, this condition does need to check for the 
signedness of the types. What I mean is that if the `RHS` is negative, but 
`ConvertedRHSValue` the branch will trigger and we will change `x - INT_MIN` to 
`x + (INT_MAX + 1)U` which is ok, as a negation of `INT_MIN` is representable 
as an unsigned type of same or lager bit with.




Comment at: clang/lib/StaticAnalyzer/Core/SimpleSValBuilder.cpp:212-219
+  llvm::APSInt ConvertedRHSValue = resultIntTy.convert(RHS);
+  // Check if the negation of the RHS is representable,
+  // i.e., the resultTy is signed, and it is not the lowest
+  // representable negative value.
+  if (ConvertedRHSValue > resultIntTy.getMinValue()) {
+ConvertedRHS = &BasicVals.getValue(-ConvertedRHSValue);
+op = (op == BO_Add) ? BO_Sub : BO_Add;

tomasz-kaminski-sonarsource wrote:
> steakhal wrote:
> > Somehow I miss a check for signedness here.
> > Why do you think it would be only triggered for signed types?
> > 
> > I have a guess, that since we already handled `x +-0`, SymIntExprs like `x 
> > - (-0)` cannot exist here, thus cannot trigger this condition spuriously. I 
> > cannot think of any ther example that could cause this misbehaving. So in 
> > that sense `ConvertedRHSValue > resultIntTy.getMinValue()` implies *at this 
> > place* that `ConvertedRHSValue.isSigned()`.
> > I would rather see this redundant check here to make the correctness 
> > reasoning local though.
> The integer representation does not have negative zeros (the standard and 
> clang assume two's complement). However, this condition does need to check 
> for the signedness of the types. What I mean is that if the `RHS` is 
> negative, but `ConvertedRHSValue` the branch will trigger and we will change 
> `x - INT_MIN` to `x + (INT_MAX + 1)U` which is ok, as a negation of `INT_MIN` 
> is representable as an unsigned type of same or lager bit with.
> 
However, I was not able to r

[PATCH] D124220: [OpenMP] Add options to only compile the host or device when offloading

2022-04-29 Thread Joseph Huber via Phabricator via cfe-commits
jhuber6 updated this revision to Diff 426049.
jhuber6 added a comment.

Rebase after landing the cuda support for the new driver.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124220

Files:
  clang/include/clang/Driver/Options.td
  clang/lib/Driver/Driver.cpp
  clang/test/Driver/cuda-openmp-driver.cu
  clang/test/Driver/openmp-offload-gpu-new.c

Index: clang/test/Driver/openmp-offload-gpu-new.c
===
--- clang/test/Driver/openmp-offload-gpu-new.c
+++ clang/test/Driver/openmp-offload-gpu-new.c
@@ -3,7 +3,6 @@
 ///
 
 // REQUIRES: x86-registered-target
-// REQUIRES: powerpc-registered-target
 // REQUIRES: nvptx-registered-target
 // REQUIRES: amdgpu-registered-target
 
@@ -50,3 +49,18 @@
 // RUN:   | FileCheck -check-prefix=DRIVER_EMBEDDING %s
 
 // DRIVER_EMBEDDING: -fembed-offload-object=[[CUBIN:.*\.cubin]],openmp,nvptx64-nvidia-cuda,sm_70
+
+// RUN:   %clang -### --target=x86_64-unknown-linux-gnu -ccc-print-bindings -fopenmp -fopenmp-targets=nvptx64-nvidia-cuda \
+// RUN: --offload-host-only -nogpulib %s 2>&1 | FileCheck %s --check-prefix=CHECK-HOST-ONLY
+// CHECK-HOST-ONLY: "x86_64-unknown-linux-gnu" - "clang", inputs: ["[[INPUT:.*]]"], output: "[[OUTPUT:.*]]"
+// CHECK-HOST-ONLY: "x86_64-unknown-linux-gnu" - "Offload::Linker", inputs: ["[[OUTPUT]]"], output: "a.out"
+
+// RUN:   %clang -### --target=x86_64-unknown-linux-gnu -ccc-print-bindings -fopenmp -fopenmp-targets=nvptx64-nvidia-cuda \
+// RUN: --offload-device-only -nogpulib %s 2>&1 | FileCheck %s --check-prefix=CHECK-DEVICE-ONLY
+// CHECK-DEVICE-ONLY: "x86_64-unknown-linux-gnu" - "clang", inputs: ["[[INPUT:.*]]"], output: "[[HOST_BC:.*]]"
+// CHECK-DEVICE-ONLY: "nvptx64-nvidia-cuda" - "clang", inputs: ["[[INPUT]]", "[[HOST_BC]]"], output: "[[DEVICE_ASM:.*]]"
+// CHECK-DEVICE-ONLY: "nvptx64-nvidia-cuda" - "NVPTX::Assembler", inputs: ["[[DEVICE_ASM]]"], output: "{{.*}}-openmp-nvptx64-nvidia-cuda.o"
+
+// RUN:   %clang -### --target=x86_64-unknown-linux-gnu -ccc-print-bindings -fopenmp -fopenmp-targets=nvptx64-nvidia-cuda \
+// RUN: --offload-device-only -E -nogpulib %s 2>&1 | FileCheck %s --check-prefix=CHECK-DEVICE-ONLY-PP
+// CHECK-DEVICE-ONLY-PP: "nvptx64-nvidia-cuda" - "clang", inputs: ["[[INPUT:.*]]"], output: "-"
Index: clang/test/Driver/cuda-openmp-driver.cu
===
--- clang/test/Driver/cuda-openmp-driver.cu
+++ clang/test/Driver/cuda-openmp-driver.cu
@@ -16,3 +16,18 @@
 
 // RUN: %clang -### -nocudalib --offload-new-driver %s 2>&1 | FileCheck -check-prefix RDC %s
 // RDC: error: Using '--offload-new-driver' requires '-fgpu-rdc'
+
+// RUN: %clang -### -target x86_64-linux-gnu -nocudalib -ccc-print-bindings -fgpu-rdc \
+// RUN:--offload-new-driver --offload-arch=sm_35 --offload-arch=sm_70 %s 2>&1 \
+// RUN: | FileCheck -check-prefix BINDINGS-HOST %s
+
+// BINDINGS-HOST: # "x86_64-unknown-linux-gnu" - "clang", inputs: ["[[INPUT:.+]]"], output: "[[OUTPUT:.+]]"
+// BINDINGS-HOST: # "x86_64-unknown-linux-gnu" - "Offload::Linker", inputs: ["[[OUTPUT]]"], output: "a.out"
+
+// RUN: %clang -### -target x86_64-linux-gnu -nocudalib -ccc-print-bindings -fgpu-rdc \
+// RUN:--offload-new-driver --offload-arch=sm_35 --offload-arch=sm_70 %s 2>&1 \
+// RUN: | FileCheck -check-prefix BINDINGS-DEVICE %s
+
+// BINDINGS-DEVICE: # "nvptx64-nvidia-cuda" - "clang", inputs: ["[[INPUT:.+]]"], output: "[[PTX:.+]]"
+// BINDINGS-DEVICE: # "nvptx64-nvidia-cuda" - "NVPTX::Assembler", inputs: ["[[PTX]]"], output: "[[CUBIN:.+]]"
+// BINDINGS-DEVICE: # "nvptx64-nvidia-cuda" - "NVPTX::Linker", inputs: ["[[CUBIN]]", "[[PTX]]"], output: "{{.*}}.fatbin"
Index: clang/lib/Driver/Driver.cpp
===
--- clang/lib/Driver/Driver.cpp
+++ clang/lib/Driver/Driver.cpp
@@ -2868,14 +2868,14 @@
   : C.getSingleOffloadToolChain());
 
   Arg *PartialCompilationArg = Args.getLastArg(
-  options::OPT_cuda_host_only, options::OPT_cuda_device_only,
-  options::OPT_cuda_compile_host_device);
-  CompileHostOnly = PartialCompilationArg &&
-PartialCompilationArg->getOption().matches(
-options::OPT_cuda_host_only);
-  CompileDeviceOnly = PartialCompilationArg &&
-  PartialCompilationArg->getOption().matches(
-  options::OPT_cuda_device_only);
+  options::OPT_offload_host_only, options::OPT_offload_device_only,
+  options::OPT_offload_host_device);
+  CompileHostOnly =
+  PartialCompilationArg && PartialCompilationArg->getOption().matches(
+   options::OPT_offload_host_only);
+  CompileDeviceOnly =
+  PartialCompilationArg && PartialCompilationArg->getOption().matches(
+  

[PATCH] D120273: [OpenMP] Allow CUDA to be linked with OpenMP using the new driver

2022-04-29 Thread Joseph Huber via Phabricator via cfe-commits
jhuber6 updated this revision to Diff 426050.
jhuber6 added a comment.

Adding test


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D120273

Files:
  clang/test/Driver/linker-wrapper.c
  clang/tools/clang-linker-wrapper/ClangLinkerWrapper.cpp

Index: clang/tools/clang-linker-wrapper/ClangLinkerWrapper.cpp
===
--- clang/tools/clang-linker-wrapper/ClangLinkerWrapper.cpp
+++ clang/tools/clang-linker-wrapper/ClangLinkerWrapper.cpp
@@ -160,6 +160,10 @@
 /// section will contain one or more offloading binaries stored contiguously.
 #define OFFLOAD_SECTION_MAGIC_STR ".llvm.offloading"
 
+/// The magic offset for the first object inside CUDA's fatbinary. This can be
+/// different but it should work for what is passed here.
+static constexpr unsigned FatbinaryOffset = 0x50;
+
 /// Information for a device offloading file extracted from the host.
 struct DeviceFile {
   DeviceFile(StringRef Kind, StringRef TheTriple, StringRef Arch,
@@ -173,7 +177,10 @@
 };
 
 namespace llvm {
-/// Helper that allows DeviceFile to be used as a key in a DenseMap.
+/// Helper that allows DeviceFile to be used as a key in a DenseMap. For now we
+/// assume device files with matching architectures and triples but different
+/// offloading kinds should be handlded together, this may not be true in the
+/// future.
 template <> struct DenseMapInfo {
   static DeviceFile getEmptyKey() {
 return {DenseMapInfo::getEmptyKey(),
@@ -953,13 +960,37 @@
 MemoryBuffer::getFileOrSTDIN(File);
 if (std::error_code EC = BufferOrErr.getError())
   return createFileError(File, EC);
+MemoryBufferRef Buffer = **BufferOrErr;
 
 file_magic Type = identify_magic((*BufferOrErr)->getBuffer());
-if (Type != file_magic::bitcode) {
+switch (Type) {
+case file_magic::bitcode: {
+  Expected> InputFileOrErr =
+  llvm::lto::InputFile::create(Buffer);
+  if (!InputFileOrErr)
+return InputFileOrErr.takeError();
+
+  // Save the input file and the buffer associated with its memory.
+  BitcodeFiles.push_back(std::move(*InputFileOrErr));
+  SavedBuffers.push_back(std::move(*BufferOrErr));
+  continue;
+}
+case file_magic::cuda_fatbinary: {
+  // Cuda fatbinaries made by Clang almost almost have an object eighty
+  // bytes from the beginning. This should be sufficient to identify the
+  // symbols.
+  Buffer = MemoryBufferRef(
+  (*BufferOrErr)->getBuffer().drop_front(FatbinaryOffset), "FatBinary");
+  LLVM_FALLTHROUGH;
+}
+case file_magic::elf_relocatable:
+case file_magic::elf_shared_object:
+case file_magic::macho_object:
+case file_magic::coff_object: {
   Expected> ObjFile =
-  ObjectFile::createObjectFile(**BufferOrErr, Type);
+  ObjectFile::createObjectFile(Buffer);
   if (!ObjFile)
-return ObjFile.takeError();
+continue;
 
   NewInputFiles.push_back(File.str());
   for (auto &Sym : (*ObjFile)->symbols()) {
@@ -973,15 +1004,10 @@
 else
   UsedInSharedLib.insert(Saver.save(*Name));
   }
-} else {
-  Expected> InputFileOrErr =
-  llvm::lto::InputFile::create(**BufferOrErr);
-  if (!InputFileOrErr)
-return InputFileOrErr.takeError();
-
-  // Save the input file and the buffer associated with its memory.
-  BitcodeFiles.push_back(std::move(*InputFileOrErr));
-  SavedBuffers.push_back(std::move(*BufferOrErr));
+  continue;
+}
+default:
+  continue;
 }
   }
 
Index: clang/test/Driver/linker-wrapper.c
===
--- clang/test/Driver/linker-wrapper.c
+++ clang/test/Driver/linker-wrapper.c
@@ -40,3 +40,11 @@
 
 // LTO: ptxas{{.*}}-m64 -o {{.*}}.cubin -O2 --gpu-name sm_70 {{.*}}.s
 // LTO-NOT: nvlink
+
+// RUN: %clang -cc1 %s -triple x86_64-unknown-linux-gnu -emit-obj -o %t.o \
+// RUN:   -fembed-offload-object=%S/Inputs/dummy-elf.o,openmp,nvptx64-nvida-cuda,sm_70 \
+// RUN:   -fembed-offload-object=%S/Inputs/dummy-elf.o,cuda,nvptx64-nvida-cuda,sm_70
+// RUN: clang-linker-wrapper --host-triple x86_64-unknown-linux-gnu --dry-run -linker-path \
+// RUN:   /usr/bin/ld -- %t.o -o a.out 2>&1 | FileCheck %s --check-prefix=CUDA_OMP_LINK
+
+// CUDA_OMP_LINK: nvlink{{.*}}-m64 -o {{.*}}.out -arch sm_70 {{.*}}.o {{.*}}.o
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D123471: [CUDA] Create offloading entries when using the new driver

2022-04-29 Thread Joseph Huber via Phabricator via cfe-commits
jhuber6 updated this revision to Diff 426051.
jhuber6 added a comment.
Herald added a subscriber: mattd.

Rebase


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D123471

Files:
  clang/include/clang/Basic/LangOptions.def
  clang/include/clang/Driver/Options.td
  clang/lib/CodeGen/CGCUDANV.cpp
  clang/lib/CodeGen/CGCUDARuntime.h
  clang/lib/Driver/ToolChains/Clang.cpp
  clang/test/CodeGenCUDA/offloading-entries.cu

Index: clang/test/CodeGenCUDA/offloading-entries.cu
===
--- /dev/null
+++ clang/test/CodeGenCUDA/offloading-entries.cu
@@ -0,0 +1,33 @@
+// NOTE: Assertions have been autogenerated by utils/update_cc_test_checks.py UTC_ARGS: --check-globals
+// RUN: %clang_cc1 -std=c++11 -triple x86_64-unknown-linux-gnu \
+// RUN:   --offload-new-driver -emit-llvm -o - -x cuda  %s | FileCheck \
+// RUN:   --check-prefix=HOST %s
+
+#include "Inputs/cuda.h"
+
+//.
+// HOST: @x = internal global i32 undef, align 4
+//.
+// HOST-LABEL: @_Z18__device_stub__foov(
+// HOST-NEXT:  entry:
+// HOST-NEXT:[[TMP0:%.*]] = call i32 @cudaLaunch(ptr @_Z18__device_stub__foov)
+// HOST-NEXT:br label [[SETUP_END:%.*]]
+// HOST:   setup.end:
+// HOST-NEXT:ret void
+//
+__global__ void foo() {}
+// HOST-LABEL: @_Z18__device_stub__barv(
+// HOST-NEXT:  entry:
+// HOST-NEXT:[[TMP0:%.*]] = call i32 @cudaLaunch(ptr @_Z18__device_stub__barv)
+// HOST-NEXT:br label [[SETUP_END:%.*]]
+// HOST:   setup.end:
+// HOST-NEXT:ret void
+//
+__global__ void bar() {}
+__device__ int x = 1;
+//.
+// HOST: attributes #0 = { noinline norecurse nounwind optnone "frame-pointer"="none" "min-legal-vector-width"="0" "no-trapping-math"="true" "stack-protector-buffer-size"="8" "target-features"="+cx8,+mmx,+sse,+sse2,+x87" }
+//.
+// HOST: !0 = !{i32 1, !"wchar_size", i32 4}
+// HOST: !1 = !{!"clang version 15.0.0"}
+//.
Index: clang/lib/Driver/ToolChains/Clang.cpp
===
--- clang/lib/Driver/ToolChains/Clang.cpp
+++ clang/lib/Driver/ToolChains/Clang.cpp
@@ -6069,6 +6069,10 @@
options::OPT_fno_openmp_extensions);
   }
 
+  // Forward the new driver to change offloading code generation.
+  if (Args.hasArg(options::OPT_offload_new_driver))
+CmdArgs.push_back("--offload-new-driver");
+
   SanitizeArgs.addArgs(TC, Args, CmdArgs, InputType);
 
   const XRayArgs &XRay = TC.getXRayArgs();
Index: clang/lib/CodeGen/CGCUDARuntime.h
===
--- clang/lib/CodeGen/CGCUDARuntime.h
+++ clang/lib/CodeGen/CGCUDARuntime.h
@@ -52,6 +52,24 @@
   Texture,  // Builtin texture
 };
 
+/// The kind flag of the target region entry.
+enum OffloadRegionEntryKindFlag : uint32_t {
+  /// Mark the region entry as a kernel.
+  OffloadRegionKernelEntry = 0x0,
+};
+
+/// The kind flag of the global variable entry.
+enum OffloadVarEntryKindFlag : uint32_t {
+  /// Mark the entry as a global variable.
+  OffloadGlobalVarEntry = 0x0,
+  /// Mark the entry as a managed global variable.
+  OffloadGlobalManagedEntry = 0x1,
+  /// Mark the entry as a surface variable.
+  OffloadGlobalSurfaceEntry = 0x2,
+  /// Mark the entry as a texture variable.
+  OffloadGlobalTextureEntry = 0x4,
+};
+
   private:
 unsigned Kind : 2;
 unsigned Extern : 1;
Index: clang/lib/CodeGen/CGCUDANV.cpp
===
--- clang/lib/CodeGen/CGCUDANV.cpp
+++ clang/lib/CodeGen/CGCUDANV.cpp
@@ -158,6 +158,8 @@
   llvm::Function *makeModuleDtorFunction();
   /// Transform managed variables for device compilation.
   void transformManagedVars();
+  /// Create offloading entries to register globals in RDC mode.
+  void createOffloadingEntries();
 
 public:
   CGNVCUDARuntime(CodeGenModule &CGM);
@@ -211,7 +213,8 @@
 CGNVCUDARuntime::CGNVCUDARuntime(CodeGenModule &CGM)
 : CGCUDARuntime(CGM), Context(CGM.getLLVMContext()),
   TheModule(CGM.getModule()),
-  RelocatableDeviceCode(CGM.getLangOpts().GPURelocatableDeviceCode),
+  RelocatableDeviceCode(CGM.getLangOpts().GPURelocatableDeviceCode ||
+CGM.getLangOpts().OffloadingNewDriver),
   DeviceMC(InitDeviceMC(CGM)) {
   CodeGen::CodeGenTypes &Types = CGM.getTypes();
   ASTContext &Ctx = CGM.getContext();
@@ -1110,6 +1113,40 @@
   }
 }
 
+// Creates offloading entries for all the kernels and globals that must be
+// registered. The linker will provide a pointer to this section so we can
+// register the symbols with the linked device image.
+void CGNVCUDARuntime::createOffloadingEntries() {
+  llvm::OpenMPIRBuilder OMPBuilder(CGM.getModule());
+  OMPBuilder.initialize();
+
+  StringRef Section = "cuda_offloading_entries";
+  for (KernelInfo &I : EmittedKernels)
+OMPBuilder.emitOffloa

[PATCH] D124650: [clang-tidy] Simplify boolean expressions by DeMorgan's theorem

2022-04-29 Thread Eugene Zelenko via Phabricator via cfe-commits
Eugene.Zelenko added inline comments.



Comment at: clang-tools-extra/docs/ReleaseNotes.rst:139
 
+- Expanded :doc:`readability-simplify-boolean-expr
+  ` to simplify 
expressions

Please use alphabetical order for such entries.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124650

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


[PATCH] D120273: [OpenMP] Allow CUDA to be linked with OpenMP using the new driver

2022-04-29 Thread Johannes Doerfert via Phabricator via cfe-commits
jdoerfert accepted this revision.
jdoerfert added a comment.
This revision is now accepted and ready to land.

LG


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D120273

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


[PATCH] D122895: [C89/C2x] Improve diagnostics around strict prototypes in C

2022-04-29 Thread Tom Honermann via Phabricator via cfe-commits
tahonermann added a comment.

> I think it's debatable whether this is a bug or not

For C99 through C17, I kind of agree, but for C2x (where the warning is still 
issued with `-Wstrict-prototypes`), my understanding is that `void foo(void)` 
and `void foo()` are equivalent; there is no unprototyped declaration. I think 
the diagnostic should at least be suppressed for C2x since we don't want to 
encourage programmers to explicitly add `void` when targeting that standard.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D122895

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


[PATCH] D124500: [clang-tidy] Support expressions of literals in modernize-macro-to-enum

2022-04-29 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman added inline comments.



Comment at: 
clang-tools-extra/clang-tidy/modernize/IntegralLiteralExpressionMatcher.cpp:25
+
+  // not a hexadecimal floating-point literal
+  if (Token.getLength() > 2 && Begin[0] == '0' && std::toupper(Begin[1]) == 
'X')

(Same suggestion elsewhere -- just double check that all the comments are full 
sentences with capitalization and punctuation.)



Comment at: 
clang-tools-extra/clang-tidy/modernize/IntegralLiteralExpressionMatcher.cpp:32-33
+  // not a decimal floating-point literal
+  return std::none_of(
+  Begin, End, [](char C) { return C == '.' || std::toupper(C) == 'E'; });
+}

Do we need to care about integer suffixes that make a non-integer type, like: 
https://godbolt.org/z/vx3xbGa41



Comment at: 
clang-tools-extra/clang-tidy/modernize/IntegralLiteralExpressionMatcher.cpp:99
+
+  if (!Current->isLiteral() || isStringLiteral(Current->getKind()) ||
+  !isIntegralConstant(*Current)) {

I know this is code moved from elsewhere, but I suppose we never considered the 
odd edge case where a user does something like `"foo"[0]` as a really awful 
integer constant. :-D



Comment at: 
clang-tools-extra/clang-tidy/modernize/IntegralLiteralExpressionMatcher.cpp:185
+
+  if (Current->is(tok::TokenKind::question)) {
+if (!advance())

There is GNU extension in this space: https://godbolt.org/z/PrWY3T6hY



Comment at: 
clang-tools-extra/clang-tidy/modernize/IntegralLiteralExpressionMatcher.cpp:204
+  return true;
+}
+

Comma operator?



Comment at: 
clang-tools-extra/clang-tidy/modernize/IntegralLiteralExpressionMatcher.h:9
+
+#pragma once
+

We don't use #pragma once (not portable, not reliable).



Comment at: 
clang-tools-extra/clang-tidy/modernize/IntegralLiteralExpressionMatcher.h:18-20
+// Parses an array of tokens and returns true if they conform to the rules of
+// C++ for whole expressions involving integral literals.  Follows the operator
+// precedence rules of C++.

Oh boy, I'm not super excited about having another parser to maintain...

It'd be nice if we had a ParserUtils.cpp/h file that made it easier to go from 
an arbitrary array of tokens to AST nodes + success/failure information on 
parsing the tokens. It's not strictly needed for what you're trying to 
accomplish here, but it would be a much more general interface and it would 
remove the support burden from adding another parser that's out of Clang's tree.



Comment at: 
clang-tools-extra/test/clang-tidy/checkers/modernize-macro-to-enum.cpp:26
+#define EXPR11 (1 + (2))
+#define EXPR12 ((1) + (2 + 0) + (1 * 1) + (1 / 1) + (1 | 1 ) + (1 & 1) + (1 << 
1) + (1 >> 1) + (1 % 2) + (1 ^ 1))
+// CHECK-MESSAGES: :[[@LINE-12]]:1: warning: replace macro with enum 
[modernize-macro-to-enum]

Other interesting tests I'd expect we could convert into an enum (at least 
theoretically):
```
#define A 12 + +1
#define B 12 - -1
#define C (1, 2, 3)
#define D 100 ? : 8
#define E 100 ? 100 : 8
#define F 'f'
#define G "foo"[0]
#define H 1 && 2
#define I 1 || 2
```



Comment at: clang-tools-extra/unittests/clang-tidy/ModernizeModuleTest.cpp:66
+{false, "1.23"},
+{false, "0x1p3"},
+{false, R"("string")"},

```
12i
.0
```




Comment at: clang-tools-extra/unittests/clang-tidy/ModernizeModuleTest.cpp:99
+{true, "1&&1"},
+{true, "1||1"},
+// invalid binary operator

```
100 ? : 10
1, 2
```



Comment at: clang-tools-extra/unittests/clang-tidy/ModernizeModuleTest.cpp:134
+{false, "1?1:"},
+{false, "1?:1"},
+

This one is valid


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

https://reviews.llvm.org/D124500

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


[PATCH] D122895: [C89/C2x] Improve diagnostics around strict prototypes in C

2022-04-29 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman added a comment.

In D122895#3482555 , @tahonermann 
wrote:

>> I think it's debatable whether this is a bug or not
>
> For C99 through C17, I kind of agree, but for C2x (where the warning is still 
> issued with `-Wstrict-prototypes`), my understanding is that `void foo(void)` 
> and `void foo()` are equivalent; there is no unprototyped declaration. I 
> think the diagnostic should at least be suppressed for C2x since we don't 
> want to encourage programmers to explicitly add `void` when targeting that 
> standard.

Good catch... `-Wstrict-prototypes` should be a noop in C2x mode! I'll work on 
fixing that.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D122895

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


[PATCH] D124658: [analyzer] Canonicalize SymIntExpr so the RHS is positive when possible

2022-04-29 Thread Tomasz Kamiński via Phabricator via cfe-commits
tomasz-kaminski-sonarsource updated this revision to Diff 426056.
tomasz-kaminski-sonarsource added a comment.

Uploading updated diff with suggested fixes.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124658

Files:
  clang/lib/StaticAnalyzer/Core/SimpleSValBuilder.cpp
  clang/test/Analysis/additive-op-on-sym-int-expr.c
  clang/test/Analysis/expr-inspection.c

Index: clang/test/Analysis/expr-inspection.c
===
--- clang/test/Analysis/expr-inspection.c
+++ clang/test/Analysis/expr-inspection.c
@@ -11,7 +11,7 @@
 
 void foo(int x) {
   clang_analyzer_dump(x); // expected-warning{{reg_$0}}
-  clang_analyzer_dump(x + (-1)); // expected-warning{{(reg_$0) + -1}}
+  clang_analyzer_dump(x + (-1)); // expected-warning{{(reg_$0) - 1}}
   int y = 1;
   for (; y < 3; ++y) {
 clang_analyzer_numTimesReached(); // expected-warning{{2}}
Index: clang/test/Analysis/additive-op-on-sym-int-expr.c
===
--- /dev/null
+++ clang/test/Analysis/additive-op-on-sym-int-expr.c
@@ -0,0 +1,58 @@
+// RUN: %clang_analyze_cc1 -triple=x86_64-unknown-linux -analyzer-checker=core,debug.ExprInspection -analyzer-config eagerly-assume=false -verify %s
+
+void clang_analyzer_dump(int);
+void clang_analyzer_dumpL(long);
+void clang_analyzer_warnIfReached();
+
+void testInspect(int x) {
+  if ((x < 10) || (x > 100)) {
+return;
+  }
+  // x: [10, 100]
+
+  int i = x + 1;
+  long l = i - 10U;
+  clang_analyzer_dump(i);   // expected-warning-re {{(reg_${{[0-9]+}}) + 1 }}
+  clang_analyzer_dumpL(l);  // expected-warning-re {{(reg_${{[0-9]+}}) - 9U }} instead of + 4294967287U
+  clang_analyzer_dumpL(l + 0L); // expected-warning-re {{(reg_${{[0-9]+}}) - 9 }}  instead of + 4294967287
+
+  if ((l - 1000) > 0) {
+clang_analyzer_warnIfReached(); // no-warning
+  }
+  if (l > 1000) {
+clang_analyzer_warnIfReached(); // no-warning
+  }
+  if (l > 1000L) {
+clang_analyzer_warnIfReached(); // no-warning
+  }
+  if ((l + 0L) > 1000) {
+clang_analyzer_warnIfReached(); // no-warning
+  }
+
+  i = x - 1;
+  l = i + 10U;
+  clang_analyzer_dumpL(l); // expected-warning-re {{(reg_${{[0-9]+}}) + 9U }} instead of - 4294967287U
+
+  i = x + (-1);
+  l = i - 10U;
+  clang_analyzer_dumpL(l); // expected-warning-re {{(reg_${{[0-9]+}}) + 9U }} instead of + 4294967285U
+
+  i = x + 1U;
+  l = i - 10U;
+  clang_analyzer_dumpL(l); // expected-warning-re {{(reg_${{[0-9]+}}) - 9U }} instead of + 4294967287U
+}
+
+void testMin(int i, long l) {
+  clang_analyzer_dump(i + (-1));  // expected-warning-re {{(reg_${{[0-9]+}}) - 1 }} instead of + -1
+  clang_analyzer_dump(i - (-1));  // expected-warning-re {{(reg_${{[0-9]+}}) + 1 }} instead of - -1
+  clang_analyzer_dumpL(l + (-1)); // expected-warning-re {{(reg_${{[0-9]+}}) - 1 }} instead of + -1
+  clang_analyzer_dumpL(l - (-1)); // expected-warning-re {{(reg_${{[0-9]+}}) + 1 }} instead of - -1
+
+  int intMin = 1 << (sizeof(int) * 8 - 1); // INT_MIN, negative value is not representable
+  // Do not normalize representation if negation would not be representable
+  clang_analyzer_dump(i + intMin); // expected-warning-re {{(reg_${{[0-9]+}}) + -2147483648 }}
+  clang_analyzer_dump(i - intMin); // expected-warning-re {{(reg_${{[0-9]+}}) - -2147483648 }}
+  // Produced value has higher bit with (long) so negation if representable
+  clang_analyzer_dumpL(l + intMin); // expected-warning-re {{(reg_${{[0-9]+}}) - 2147483648 }} instead of + -2147483648
+  clang_analyzer_dumpL(l - intMin); // expected-warning-re {{(reg_${{[0-9]+}}) + 2147483648 }} instead of - -2147483648
+}
Index: clang/lib/StaticAnalyzer/Core/SimpleSValBuilder.cpp
===
--- clang/lib/StaticAnalyzer/Core/SimpleSValBuilder.cpp
+++ clang/lib/StaticAnalyzer/Core/SimpleSValBuilder.cpp
@@ -197,8 +197,27 @@
   if (RHS.isSigned() && !SymbolType->isSignedIntegerOrEnumerationType())
 ConvertedRHS = &BasicVals.Convert(SymbolType, RHS);
 }
-  } else
+  } else if (BinaryOperator::isAdditiveOp(op) && RHS.isNegative()) {
+// Change a+(-N) into a-N, and a-(-N) into a+N
+// Adjust addition/subtraction of negative value, to
+// subtraction/addition of the negated value.
+APSIntType resultIntTy = BasicVals.getAPSIntType(resultTy);
+assert(resultIntTy.getBitWidth() >= RHS.getBitWidth() &&
+   "The result operation type must have at least the same "
+   "number of bits as its operands.");
+
+llvm::APSInt ConvertedRHSValue = resultIntTy.convert(RHS);
+// Check if the negation of the RHS is representable,
+// i.e., the resultTy is signed, and it is not the lowest
+// representable negative value.
+if (ConvertedRHSValue > resultIntTy.getMinValue()) {
+  ConvertedRHS = &BasicVals.getValue(-ConvertedRHSValue);
+  op = (o

[PATCH] D119544: Deferred Concept Instantiation Implementation

2022-04-29 Thread Erich Keane via Phabricator via cfe-commits
erichkeane marked 11 inline comments as done.
erichkeane added inline comments.



Comment at: clang/lib/Sema/SemaConcept.cpp:70
+assert((!LHS.isInvalid() && !RHS.isInvalid()) && "not good expressions?");
+assert(LHS.isUsable() && RHS.isUsable() && "Side not usable?");
+// We should just be able to 'normalize' these to the builtin Binary

ChuanqiXu wrote:
> I feel like the usage of the API could be further simplified.
Heh, the suggestion is inverted slightly (those should be `!isUsable`) which 
caught me for a while :)  Either way, I think it is a good suggestion.



Comment at: clang/lib/Sema/SemaConcept.cpp:432-476
+if (TemplateArgs) {
+  MultiLevelTemplateArgumentList JustTemplArgs(
+  *FD->getTemplateSpecializationArgs());
+  if (addInstantiatedParametersToScope(
+  FD, PrimaryTemplate->getTemplatedDecl(), Scope, JustTemplArgs))
+return true;
+}

ChuanqiXu wrote:
> The suggested change works. I feel it is not identical with the original. Is 
> it correct or do we miss something in the test?
The very top condition is not exactly the same I think, but in a way that I 
don't believe matters now that this function isn't recursive.

Otherwise I think this is a vast improvement, so I'll keep it!



Comment at: clang/lib/Sema/SemaTemplateInstantiateDecl.cpp:2173
 Function->setInstantiationOfMemberFunction(D, TSK_ImplicitInstantiation);
+  } else if (!isFriend) {
+// If this is not a function template, and this is not a friend (that is,

ChuanqiXu wrote:
> The check here is not straightforward. Here we want to check if the Function 
> is local declared function. But what we check here is about friendness. I am 
> not 100% sure if it is right and other reader might be confusing too. I would 
> suggest to check it directly. e.g, check if one of its DeclContext is 
> FunctionDecl.
I cannot come up with a better one here.  Really the condition here is "this is 
not one of the above conditions, and is still not a friend function".  A friend 
could ALSO have a `DeclContext` of a `FunctionDecl` as well, so I don't have a 
good idea of what we could do.


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

https://reviews.llvm.org/D119544

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


[PATCH] D124674: [analyzer] Indicate if a parent state is infeasible

2022-04-29 Thread Gabor Marton via Phabricator via cfe-commits
martong created this revision.
martong added reviewers: NoQ, steakhal, ASDenysPetrov, Szelethus, xazax.hun.
Herald added subscribers: manas, gamesh411, dkrupp, donat.nagy, 
mikhail.ramalho, a.sidorin, rnkovacs, szepet, baloghadamsoftware.
Herald added a project: All.
martong requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

In some cases a parent State is already infeasible, but we recognize
this only if an additonal constraint is added. This patch is the first
of a series to address this issue. In this patch `assumeDual` is changed
to clone the parent State but with an `Infeasible` flag set, and this
infeasible-parent is returned both for the true and false case. Then
when we add a new transition in the exploded graph and the destination
is marked as infeasible, the node will be a sink node.

Related bug:
https://github.com/llvm/llvm-project/issues/50883
Actually, this patch does not solve that bug in the solver, rather with
this patch we can handle the general parent-infeasible cases.

Next step would be to change the State API and require all checkers to
use the `assume*Dual` API and deprecate the simple `assume` calls.

Hopefully, the next patch will introduce `assumeInBoundDual` and will
solve the CRASH we have here:
https://github.com/llvm/llvm-project/issues/54272


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D124674

Files:
  clang/include/clang/StaticAnalyzer/Core/PathSensitive/ConstraintManager.h
  clang/include/clang/StaticAnalyzer/Core/PathSensitive/CoreEngine.h
  clang/include/clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h
  clang/lib/StaticAnalyzer/Core/ConstraintManager.cpp
  clang/lib/StaticAnalyzer/Core/ProgramState.cpp
  clang/test/Analysis/sink-infeasible.c

Index: clang/test/Analysis/sink-infeasible.c
===
--- /dev/null
+++ clang/test/Analysis/sink-infeasible.c
@@ -0,0 +1,59 @@
+// RUN: %clang_analyze_cc1 %s \
+// RUN:   -analyzer-checker=core \
+// RUN:   -analyzer-checker=debug.ExprInspection \
+// RUN:   -analyzer-config eagerly-assume=false \
+// RUN:   -verify
+
+// Here we test that if it turns out that the parent state is infeasible then
+// both children States (more precisely the ExplodedNodes) are marked as a
+// Sink.
+// We rely on an existing defect of the underlying constraint solver. However,
+// in the future we might strengthen the solver to discover the infeasibility
+// right when we create the parent state. At that point this test will fail,
+// and either we shall find another solver weakness to have this test case
+// functioning, or we shall simply remove this test.
+
+void clang_analyzer_warnIfReached();
+void clang_analyzer_eval(int);
+
+int a, b, c, d, e;
+void f() {
+
+  if (a == 0)
+return;
+
+  if (e != c)
+return;
+
+  d = e - c;
+  b = d;
+  a -= d;
+
+  if (a != 0)
+return;
+
+  clang_analyzer_warnIfReached(); // expected-warning{{REACHABLE}}
+
+  /* The BASELINE passes these checks ('wrning' is used to avoid lit to match)
+  // The parent state is already infeasible, look at this contradiction:
+  clang_analyzer_eval(b > 0);  // expected-wrning{{FALSE}}
+  clang_analyzer_eval(b <= 0); // expected-wrning{{FALSE}}
+  // Crashes with expensive checks.
+  if (b > 0) {
+clang_analyzer_warnIfReached(); // no-warning, OK
+return;
+  }
+  // Should not be reachable.
+  clang_analyzer_warnIfReached(); // expected-wrning{{REACHABLE}}
+  */
+
+  // The parent state is already infeasible, but we realize that only if b is
+  // constrained.
+  clang_analyzer_eval(b > 0);  // expected-warning{{UNKNOWN}}
+  clang_analyzer_eval(b <= 0); // expected-warning{{UNKNOWN}}
+  if (b > 0) {
+clang_analyzer_warnIfReached(); // no-warning
+return;
+  }
+  clang_analyzer_warnIfReached(); // no-warning
+}
Index: clang/lib/StaticAnalyzer/Core/ProgramState.cpp
===
--- clang/lib/StaticAnalyzer/Core/ProgramState.cpp
+++ clang/lib/StaticAnalyzer/Core/ProgramState.cpp
@@ -55,7 +55,7 @@
 
 ProgramState::ProgramState(const ProgramState &RHS)
 : stateMgr(RHS.stateMgr), Env(RHS.Env), store(RHS.store), GDM(RHS.GDM),
-  refCount(0) {
+  Infeasible(RHS.Infeasible), refCount(0) {
   stateMgr->getStoreManager().incrementReferenceCount(store);
 }
 
@@ -429,6 +429,12 @@
   return getStateManager().getPersistentState(NewSt);
 }
 
+ProgramStateRef ProgramState::cloneAsInfeasible() const {
+  ProgramState NewSt(*this);
+  NewSt.Infeasible = true;
+  return getStateManager().getPersistentState(NewSt);
+}
+
 void ProgramState::setStore(const StoreRef &newStore) {
   Store newStoreStore = newStore.getStore();
   if (newStoreStore)
Index: clang/lib/StaticAnalyzer/Core/ConstraintManager.cpp
===
--- clang/lib/StaticAnalyzer/Core/ConstraintManager.cpp
+++ clang/lib/StaticAnalyzer/Core/ConstraintMan

[PATCH] D119544: Deferred Concept Instantiation Implementation

2022-04-29 Thread Erich Keane via Phabricator via cfe-commits
erichkeane updated this revision to Diff 426060.
erichkeane marked 3 inline comments as done.
erichkeane added a comment.

Make all the changes that @ChuanqiXu suggested.  Thank you again so much for 
your help during this!

I intend to commit this my Monday-AM unless someone comments differently.


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

https://reviews.llvm.org/D119544

Files:
  clang/docs/ReleaseNotes.rst
  clang/include/clang/AST/Decl.h
  clang/include/clang/AST/DeclBase.h
  clang/include/clang/Sema/Sema.h
  clang/include/clang/Sema/Template.h
  clang/lib/AST/ASTImporter.cpp
  clang/lib/AST/Decl.cpp
  clang/lib/AST/DeclBase.cpp
  clang/lib/ExtractAPI/ExtractAPIConsumer.cpp
  clang/lib/Sema/SemaConcept.cpp
  clang/lib/Sema/SemaTemplate.cpp
  clang/lib/Sema/SemaTemplateDeduction.cpp
  clang/lib/Sema/SemaTemplateInstantiate.cpp
  clang/lib/Sema/SemaTemplateInstantiateDecl.cpp
  clang/lib/Sema/TreeTransform.h
  clang/lib/Serialization/ASTReaderDecl.cpp
  clang/lib/Serialization/ASTWriterDecl.cpp
  clang/test/CXX/temp/temp.constr/temp.constr.constr/non-function-templates.cpp
  clang/test/SemaTemplate/concepts.cpp
  clang/test/SemaTemplate/deferred-concept-inst.cpp
  clang/test/SemaTemplate/instantiate-requires-clause.cpp
  clang/test/SemaTemplate/trailing-return-short-circuit.cpp

Index: clang/test/SemaTemplate/trailing-return-short-circuit.cpp
===
--- /dev/null
+++ clang/test/SemaTemplate/trailing-return-short-circuit.cpp
@@ -0,0 +1,62 @@
+// RUN: %clang_cc1 -std=c++20 -verify %s
+
+template 
+  requires(sizeof(T) > 2) || T::value // #FOO_REQ
+void Foo(T){};// #FOO
+
+template 
+void TrailingReturn(T)   // #TRAILING
+  requires(sizeof(T) > 2) || // #TRAILING_REQ
+  T::value   // #TRAILING_REQ_VAL
+{};
+template 
+struct HasValue {
+  static constexpr bool value = B;
+};
+static_assert(sizeof(HasValue) <= 2);
+
+template 
+struct HasValueLarge {
+  static constexpr bool value = B;
+  int I;
+};
+static_assert(sizeof(HasValueLarge) > 2);
+
+void usage() {
+  // Passes the 1st check, short-circuit so the 2nd ::value is not evaluated.
+  Foo(1.0);
+  TrailingReturn(1.0);
+
+  // Fails the 1st check, but has a ::value, so the check happens correctly.
+  Foo(HasValue{});
+  TrailingReturn(HasValue{});
+
+  // Passes the 1st check, but would have passed the 2nd one.
+  Foo(HasValueLarge{});
+  TrailingReturn(HasValueLarge{});
+
+  // Fails the 1st check, fails 2nd because there is no ::value.
+  Foo(true);
+  // expected-error@-1{{no matching function for call to 'Foo'}}
+  // expected-note@#FOO{{candidate template ignored: constraints not satisfied [with T = bool]}}
+  // expected-note@#FOO_REQ{{because 'sizeof(_Bool) > 2' (1 > 2) evaluated to false}}
+  // expected-note@#FOO_REQ{{because substituted constraint expression is ill-formed: type 'bool' cannot be used prior to '::' because it has no members}}
+
+  TrailingReturn(true);
+  // expected-error@-1{{no matching function for call to 'TrailingReturn'}}
+  // expected-note@#TRAILING{{candidate template ignored: constraints not satisfied [with T = bool]}}
+  // expected-note@#TRAILING_REQ{{because 'sizeof(_Bool) > 2' (1 > 2) evaluated to false}}
+  // expected-note@#TRAILING_REQ_VAL{{because substituted constraint expression is ill-formed: type 'bool' cannot be used prior to '::' because it has no members}}
+
+  // Fails the 1st check, fails 2nd because ::value is false.
+  Foo(HasValue{});
+  // expected-error@-1 {{no matching function for call to 'Foo'}}
+  // expected-note@#FOO{{candidate template ignored: constraints not satisfied [with T = HasValue]}}
+  // expected-note@#FOO_REQ{{because 'sizeof(HasValue) > 2' (1 > 2) evaluated to false}}
+  // expected-note@#FOO_REQ{{and 'HasValue::value' evaluated to false}}
+  TrailingReturn(HasValue{});
+  // expected-error@-1 {{no matching function for call to 'TrailingReturn'}}
+  // expected-note@#TRAILING{{candidate template ignored: constraints not satisfied [with T = HasValue]}}
+  // expected-note@#TRAILING_REQ{{because 'sizeof(HasValue) > 2' (1 > 2) evaluated to false}}
+  // expected-note@#TRAILING_REQ_VAL{{and 'HasValue::value' evaluated to false}}
+}
Index: clang/test/SemaTemplate/instantiate-requires-clause.cpp
===
--- clang/test/SemaTemplate/instantiate-requires-clause.cpp
+++ clang/test/SemaTemplate/instantiate-requires-clause.cpp
@@ -1,4 +1,4 @@
-// RUN: %clang_cc1 -std=c++2a -x c++ %s -verify
+// RUN: %clang_cc1 -std=c++2a -x c++ %s -Wno-unused-value -verify
 
 template  requires ((sizeof(Args) == 1), ...)
 // expected-note@-1 {{because '(sizeof(int) == 1) , (sizeof(char) == 1) , (sizeof(int) == 1)' evaluated to false}}
@@ -40,6 +40,20 @@
 
 static_assert(S::f(1));
 
+// Similar to the 'S' test, but tries to use 'U' in the requires clause.
+template 
+struct S1 {
+  // expected-note@+3 {{candidate template

[PATCH] D124674: [analyzer] Indicate if a parent state is infeasible

2022-04-29 Thread Gabor Marton via Phabricator via cfe-commits
martong added inline comments.



Comment at: 
clang/include/clang/StaticAnalyzer/Core/PathSensitive/ConstraintManager.h:96-97
-
-// If StTrue is infeasible, asserting the falseness of Cond is unnecessary
-// because the existing constraints already establish this.
-if (!StTrue) {

This statement is false because our constraint solver is not precise.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124674

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


[clang] 47d6625 - [OpenMP] Add options to only compile the host or device when offloading

2022-04-29 Thread Joseph Huber via cfe-commits

Author: Joseph Huber
Date: 2022-04-29T11:22:21-04:00
New Revision: 47d66255701a5cfeab6c05e3642a2cccf7a4c09f

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

LOG: [OpenMP] Add options to only compile the host or device when offloading

OpenMP recently moved to the new offloading driver, this had the effect
of making it more difficult to inspect intermediate code for the device.
This patch adds `-foffload-host-only` and `-foffload-device-only` to
control which sides get compiled. This will allow users to more easily
inspect output without needing the temp files.

Reviewed By: tra

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

Added: 


Modified: 
clang/include/clang/Driver/Options.td
clang/lib/Driver/Driver.cpp
clang/test/Driver/cuda-openmp-driver.cu
clang/test/Driver/openmp-offload-gpu-new.c

Removed: 




diff  --git a/clang/include/clang/Driver/Options.td 
b/clang/include/clang/Driver/Options.td
index 6f70e28a211e..15b94ee5425e 100644
--- a/clang/include/clang/Driver/Options.td
+++ b/clang/include/clang/Driver/Options.td
@@ -906,14 +906,6 @@ def fconvergent_functions : Flag<["-"], 
"fconvergent-functions">, Group
 def gpu_use_aux_triple_only : Flag<["--"], "gpu-use-aux-triple-only">,
   InternalDriverOpt, HelpText<"Prepare '-aux-triple' only without populating "
   "'-aux-target-cpu' and '-aux-target-feature'.">;
-def cuda_device_only : Flag<["--"], "cuda-device-only">,
-  HelpText<"Compile CUDA code for device only">;
-def cuda_host_only : Flag<["--"], "cuda-host-only">,
-  HelpText<"Compile CUDA code for host only.  Has no effect on non-CUDA "
-   "compilations.">;
-def cuda_compile_host_device : Flag<["--"], "cuda-compile-host-device">,
-  HelpText<"Compile CUDA code for both host and device (default).  Has no "
-   "effect on non-CUDA compilations.">;
 def cuda_include_ptx_EQ : Joined<["--"], "cuda-include-ptx=">, 
Flags<[NoXarchOption]>,
   HelpText<"Include PTX for the following GPU architecture (e.g. sm_35) or 
'all'. May be specified more than once.">;
 def no_cuda_include_ptx_EQ : Joined<["--"], "no-cuda-include-ptx=">, 
Flags<[NoXarchOption]>,
@@ -2538,6 +2530,19 @@ def offload_new_driver : Flag<["--"], 
"offload-new-driver">, Flags<[CC1Option]>,
   HelpText<"Use the new driver for offloading compilation.">;
 def no_offload_new_driver : Flag<["--"], "no-offload-new-driver">, 
Flags<[CC1Option]>, Group,
   HelpText<"Don't Use the new driver for offloading compilation.">;
+def offload_device_only : Flag<["--"], "offload-device-only">,
+  HelpText<"Only compile for the offloading device.">;
+def offload_host_only : Flag<["--"], "offload-host-only">,
+  HelpText<"Only compile for the offloading host.">;
+def offload_host_device : Flag<["--"], "offload-host-device">,
+  HelpText<"Only compile for the offloading host.">;
+def cuda_device_only : Flag<["--"], "cuda-device-only">, 
Alias,
+  HelpText<"Compile CUDA code for device only">;
+def cuda_host_only : Flag<["--"], "cuda-host-only">, Alias,
+  HelpText<"Compile CUDA code for host only. Has no effect on non-CUDA 
compilations.">;
+def cuda_compile_host_device : Flag<["--"], "cuda-compile-host-device">, 
Alias,
+  HelpText<"Compile CUDA code for both host and device (default). Has no "
+   "effect on non-CUDA compilations.">;
 def fopenmp_new_driver : Flag<["-"], "fopenmp-new-driver">, 
Flags<[CC1Option]>, Group,
   HelpText<"Use the new driver for OpenMP offloading.">;
 def fno_openmp_new_driver : Flag<["-"], "fno-openmp-new-driver">, 
Flags<[CC1Option]>, Group,

diff  --git a/clang/lib/Driver/Driver.cpp b/clang/lib/Driver/Driver.cpp
index 3209264bb4c8..068ab8956db0 100644
--- a/clang/lib/Driver/Driver.cpp
+++ b/clang/lib/Driver/Driver.cpp
@@ -2868,14 +2868,14 @@ class OffloadingActionBuilder final {
   : C.getSingleOffloadToolChain());
 
   Arg *PartialCompilationArg = Args.getLastArg(
-  options::OPT_cuda_host_only, options::OPT_cuda_device_only,
-  options::OPT_cuda_compile_host_device);
-  CompileHostOnly = PartialCompilationArg &&
-PartialCompilationArg->getOption().matches(
-options::OPT_cuda_host_only);
-  CompileDeviceOnly = PartialCompilationArg &&
-  PartialCompilationArg->getOption().matches(
-  options::OPT_cuda_device_only);
+  options::OPT_offload_host_only, options::OPT_offload_device_only,
+  options::OPT_offload_host_device);
+  CompileHostOnly =
+  PartialCompilationArg && PartialCompilationArg->getOption().matches(
+   options::OPT_offload_host_only);
+  CompileDeviceOnly =
+  PartialCompilationArg && PartialCo

[PATCH] D124220: [OpenMP] Add options to only compile the host or device when offloading

2022-04-29 Thread Joseph Huber via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG47d66255701a: [OpenMP] Add options to only compile the host 
or device when offloading (authored by jhuber6).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124220

Files:
  clang/include/clang/Driver/Options.td
  clang/lib/Driver/Driver.cpp
  clang/test/Driver/cuda-openmp-driver.cu
  clang/test/Driver/openmp-offload-gpu-new.c

Index: clang/test/Driver/openmp-offload-gpu-new.c
===
--- clang/test/Driver/openmp-offload-gpu-new.c
+++ clang/test/Driver/openmp-offload-gpu-new.c
@@ -3,7 +3,6 @@
 ///
 
 // REQUIRES: x86-registered-target
-// REQUIRES: powerpc-registered-target
 // REQUIRES: nvptx-registered-target
 // REQUIRES: amdgpu-registered-target
 
@@ -50,3 +49,18 @@
 // RUN:   | FileCheck -check-prefix=DRIVER_EMBEDDING %s
 
 // DRIVER_EMBEDDING: -fembed-offload-object=[[CUBIN:.*\.cubin]],openmp,nvptx64-nvidia-cuda,sm_70
+
+// RUN:   %clang -### --target=x86_64-unknown-linux-gnu -ccc-print-bindings -fopenmp -fopenmp-targets=nvptx64-nvidia-cuda \
+// RUN: --offload-host-only -nogpulib %s 2>&1 | FileCheck %s --check-prefix=CHECK-HOST-ONLY
+// CHECK-HOST-ONLY: "x86_64-unknown-linux-gnu" - "clang", inputs: ["[[INPUT:.*]]"], output: "[[OUTPUT:.*]]"
+// CHECK-HOST-ONLY: "x86_64-unknown-linux-gnu" - "Offload::Linker", inputs: ["[[OUTPUT]]"], output: "a.out"
+
+// RUN:   %clang -### --target=x86_64-unknown-linux-gnu -ccc-print-bindings -fopenmp -fopenmp-targets=nvptx64-nvidia-cuda \
+// RUN: --offload-device-only -nogpulib %s 2>&1 | FileCheck %s --check-prefix=CHECK-DEVICE-ONLY
+// CHECK-DEVICE-ONLY: "x86_64-unknown-linux-gnu" - "clang", inputs: ["[[INPUT:.*]]"], output: "[[HOST_BC:.*]]"
+// CHECK-DEVICE-ONLY: "nvptx64-nvidia-cuda" - "clang", inputs: ["[[INPUT]]", "[[HOST_BC]]"], output: "[[DEVICE_ASM:.*]]"
+// CHECK-DEVICE-ONLY: "nvptx64-nvidia-cuda" - "NVPTX::Assembler", inputs: ["[[DEVICE_ASM]]"], output: "{{.*}}-openmp-nvptx64-nvidia-cuda.o"
+
+// RUN:   %clang -### --target=x86_64-unknown-linux-gnu -ccc-print-bindings -fopenmp -fopenmp-targets=nvptx64-nvidia-cuda \
+// RUN: --offload-device-only -E -nogpulib %s 2>&1 | FileCheck %s --check-prefix=CHECK-DEVICE-ONLY-PP
+// CHECK-DEVICE-ONLY-PP: "nvptx64-nvidia-cuda" - "clang", inputs: ["[[INPUT:.*]]"], output: "-"
Index: clang/test/Driver/cuda-openmp-driver.cu
===
--- clang/test/Driver/cuda-openmp-driver.cu
+++ clang/test/Driver/cuda-openmp-driver.cu
@@ -16,3 +16,18 @@
 
 // RUN: %clang -### -nocudalib --offload-new-driver %s 2>&1 | FileCheck -check-prefix RDC %s
 // RDC: error: Using '--offload-new-driver' requires '-fgpu-rdc'
+
+// RUN: %clang -### -target x86_64-linux-gnu -nocudalib -ccc-print-bindings -fgpu-rdc \
+// RUN:--offload-new-driver --offload-arch=sm_35 --offload-arch=sm_70 %s 2>&1 \
+// RUN: | FileCheck -check-prefix BINDINGS-HOST %s
+
+// BINDINGS-HOST: # "x86_64-unknown-linux-gnu" - "clang", inputs: ["[[INPUT:.+]]"], output: "[[OUTPUT:.+]]"
+// BINDINGS-HOST: # "x86_64-unknown-linux-gnu" - "Offload::Linker", inputs: ["[[OUTPUT]]"], output: "a.out"
+
+// RUN: %clang -### -target x86_64-linux-gnu -nocudalib -ccc-print-bindings -fgpu-rdc \
+// RUN:--offload-new-driver --offload-arch=sm_35 --offload-arch=sm_70 %s 2>&1 \
+// RUN: | FileCheck -check-prefix BINDINGS-DEVICE %s
+
+// BINDINGS-DEVICE: # "nvptx64-nvidia-cuda" - "clang", inputs: ["[[INPUT:.+]]"], output: "[[PTX:.+]]"
+// BINDINGS-DEVICE: # "nvptx64-nvidia-cuda" - "NVPTX::Assembler", inputs: ["[[PTX]]"], output: "[[CUBIN:.+]]"
+// BINDINGS-DEVICE: # "nvptx64-nvidia-cuda" - "NVPTX::Linker", inputs: ["[[CUBIN]]", "[[PTX]]"], output: "{{.*}}.fatbin"
Index: clang/lib/Driver/Driver.cpp
===
--- clang/lib/Driver/Driver.cpp
+++ clang/lib/Driver/Driver.cpp
@@ -2868,14 +2868,14 @@
   : C.getSingleOffloadToolChain());
 
   Arg *PartialCompilationArg = Args.getLastArg(
-  options::OPT_cuda_host_only, options::OPT_cuda_device_only,
-  options::OPT_cuda_compile_host_device);
-  CompileHostOnly = PartialCompilationArg &&
-PartialCompilationArg->getOption().matches(
-options::OPT_cuda_host_only);
-  CompileDeviceOnly = PartialCompilationArg &&
-  PartialCompilationArg->getOption().matches(
-  options::OPT_cuda_device_only);
+  options::OPT_offload_host_only, options::OPT_offload_device_only,
+  options::OPT_offload_host_device);
+  CompileHostOnly =
+  PartialCompilationArg && PartialCompilationArg->getOption().matches(
+   options::OPT_offload_host_only);
+  CompileDeviceOnly =
+  PartialCompilationAr

[PATCH] D124510: [RISCV] Precommit test for D124509

2022-04-29 Thread Zakk Chen via Phabricator via cfe-commits
khchen accepted this revision.
khchen added a comment.
This revision is now accepted and ready to land.

LGTM. Thanks!


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124510

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


[PATCH] D122895: [C89/C2x] Improve diagnostics around strict prototypes in C

2022-04-29 Thread Manoj Gupta via Phabricator via cfe-commits
manojgupta added a comment.

  Is disabling the pedantic warning an option for your users?

Disabling it wholesale is not an option since they actually want this warning  
(the older version). But we agreed to disable it specifically for the code 
where the warning was getting fired.
One instance is https://review.coreboot.org/c/coreboot/+/63936 .

I have been fixing our codebase to clean this and clean the instances. But it 
takes a lot of time and effort. Plus it takes a long time to clean one failure 
before I can find others  (public CLs) 
https://chromium-review.googlesource.com/q/Wstrict-prototypes+owner:manojgupta


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D122895

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


[clang] d9c64d3 - [OpenMP] Allow CUDA to be linked with OpenMP using the new driver

2022-04-29 Thread Joseph Huber via cfe-commits

Author: Joseph Huber
Date: 2022-04-29T11:38:40-04:00
New Revision: d9c64d33b98be695fc78a65624242033058ed117

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

LOG: [OpenMP] Allow CUDA to be linked with OpenMP using the new driver

After basic support for embedding and handling CUDA files was added to
the new driver, we should be able to call CUDA functions from OpenMP
code. This patch makes the necessary changes to successfuly link in CUDA
programs that were compiled using the new driver. With this patch it
should be possible to compile device-only CUDA code (no kernels) and
call it from OpenMP as follows:

```
$ clang++ cuda.cu -fopenmp-new-driver -offload-arch=sm_70 -c
$ clang++ openmp.cpp cuda.o -fopenmp-new-driver -fopenmp 
-fopenmp-targets=nvptx64 -Xopenmp-target=nvptx64 -march=sm_70
```

Currently this requires using a host variant to suppress the generation
of a CPU-side fallback call.

Depends on D120272

Reviewed By: jdoerfert

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

Added: 


Modified: 
clang/test/Driver/linker-wrapper.c
clang/tools/clang-linker-wrapper/ClangLinkerWrapper.cpp

Removed: 




diff  --git a/clang/test/Driver/linker-wrapper.c 
b/clang/test/Driver/linker-wrapper.c
index 7920fe8c1a99..a180a792284e 100644
--- a/clang/test/Driver/linker-wrapper.c
+++ b/clang/test/Driver/linker-wrapper.c
@@ -40,3 +40,11 @@
 
 // LTO: ptxas{{.*}}-m64 -o {{.*}}.cubin -O2 --gpu-name sm_70 {{.*}}.s
 // LTO-NOT: nvlink
+
+// RUN: %clang -cc1 %s -triple x86_64-unknown-linux-gnu -emit-obj -o %t.o \
+// RUN:   
-fembed-offload-object=%S/Inputs/dummy-elf.o,openmp,nvptx64-nvida-cuda,sm_70 \
+// RUN:   
-fembed-offload-object=%S/Inputs/dummy-elf.o,cuda,nvptx64-nvida-cuda,sm_70
+// RUN: clang-linker-wrapper --host-triple x86_64-unknown-linux-gnu --dry-run 
-linker-path \
+// RUN:   /usr/bin/ld -- %t.o -o a.out 2>&1 | FileCheck %s 
--check-prefix=CUDA_OMP_LINK
+
+// CUDA_OMP_LINK: nvlink{{.*}}-m64 -o {{.*}}.out -arch sm_70 {{.*}}.o {{.*}}.o

diff  --git a/clang/tools/clang-linker-wrapper/ClangLinkerWrapper.cpp 
b/clang/tools/clang-linker-wrapper/ClangLinkerWrapper.cpp
index 09381d93f17d..c2c1fa738be6 100644
--- a/clang/tools/clang-linker-wrapper/ClangLinkerWrapper.cpp
+++ b/clang/tools/clang-linker-wrapper/ClangLinkerWrapper.cpp
@@ -160,6 +160,10 @@ static codegen::RegisterCodeGenFlags CodeGenFlags;
 /// section will contain one or more offloading binaries stored contiguously.
 #define OFFLOAD_SECTION_MAGIC_STR ".llvm.offloading"
 
+/// The magic offset for the first object inside CUDA's fatbinary. This can be
+/// 
diff erent but it should work for what is passed here.
+static constexpr unsigned FatbinaryOffset = 0x50;
+
 /// Information for a device offloading file extracted from the host.
 struct DeviceFile {
   DeviceFile(StringRef Kind, StringRef TheTriple, StringRef Arch,
@@ -173,7 +177,10 @@ struct DeviceFile {
 };
 
 namespace llvm {
-/// Helper that allows DeviceFile to be used as a key in a DenseMap.
+/// Helper that allows DeviceFile to be used as a key in a DenseMap. For now we
+/// assume device files with matching architectures and triples but 
diff erent
+/// offloading kinds should be handlded together, this may not be true in the
+/// future.
 template <> struct DenseMapInfo {
   static DeviceFile getEmptyKey() {
 return {DenseMapInfo::getEmptyKey(),
@@ -953,13 +960,37 @@ Error linkBitcodeFiles(SmallVectorImpl 
&InputFiles,
 MemoryBuffer::getFileOrSTDIN(File);
 if (std::error_code EC = BufferOrErr.getError())
   return createFileError(File, EC);
+MemoryBufferRef Buffer = **BufferOrErr;
 
 file_magic Type = identify_magic((*BufferOrErr)->getBuffer());
-if (Type != file_magic::bitcode) {
+switch (Type) {
+case file_magic::bitcode: {
+  Expected> InputFileOrErr =
+  llvm::lto::InputFile::create(Buffer);
+  if (!InputFileOrErr)
+return InputFileOrErr.takeError();
+
+  // Save the input file and the buffer associated with its memory.
+  BitcodeFiles.push_back(std::move(*InputFileOrErr));
+  SavedBuffers.push_back(std::move(*BufferOrErr));
+  continue;
+}
+case file_magic::cuda_fatbinary: {
+  // Cuda fatbinaries made by Clang almost almost have an object eighty
+  // bytes from the beginning. This should be sufficient to identify the
+  // symbols.
+  Buffer = MemoryBufferRef(
+  (*BufferOrErr)->getBuffer().drop_front(FatbinaryOffset), 
"FatBinary");
+  LLVM_FALLTHROUGH;
+}
+case file_magic::elf_relocatable:
+case file_magic::elf_shared_object:
+case file_magic::macho_object:
+case file_magic::coff_object: {
   Expected> ObjFile =
-  ObjectFile::createObjectFile(**BufferOrErr, Type);
+  ObjectFile::create

[PATCH] D120273: [OpenMP] Allow CUDA to be linked with OpenMP using the new driver

2022-04-29 Thread Joseph Huber via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rGd9c64d33b98b: [OpenMP] Allow CUDA to be linked with OpenMP 
using the new driver (authored by jhuber6).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D120273

Files:
  clang/test/Driver/linker-wrapper.c
  clang/tools/clang-linker-wrapper/ClangLinkerWrapper.cpp

Index: clang/tools/clang-linker-wrapper/ClangLinkerWrapper.cpp
===
--- clang/tools/clang-linker-wrapper/ClangLinkerWrapper.cpp
+++ clang/tools/clang-linker-wrapper/ClangLinkerWrapper.cpp
@@ -160,6 +160,10 @@
 /// section will contain one or more offloading binaries stored contiguously.
 #define OFFLOAD_SECTION_MAGIC_STR ".llvm.offloading"
 
+/// The magic offset for the first object inside CUDA's fatbinary. This can be
+/// different but it should work for what is passed here.
+static constexpr unsigned FatbinaryOffset = 0x50;
+
 /// Information for a device offloading file extracted from the host.
 struct DeviceFile {
   DeviceFile(StringRef Kind, StringRef TheTriple, StringRef Arch,
@@ -173,7 +177,10 @@
 };
 
 namespace llvm {
-/// Helper that allows DeviceFile to be used as a key in a DenseMap.
+/// Helper that allows DeviceFile to be used as a key in a DenseMap. For now we
+/// assume device files with matching architectures and triples but different
+/// offloading kinds should be handlded together, this may not be true in the
+/// future.
 template <> struct DenseMapInfo {
   static DeviceFile getEmptyKey() {
 return {DenseMapInfo::getEmptyKey(),
@@ -953,13 +960,37 @@
 MemoryBuffer::getFileOrSTDIN(File);
 if (std::error_code EC = BufferOrErr.getError())
   return createFileError(File, EC);
+MemoryBufferRef Buffer = **BufferOrErr;
 
 file_magic Type = identify_magic((*BufferOrErr)->getBuffer());
-if (Type != file_magic::bitcode) {
+switch (Type) {
+case file_magic::bitcode: {
+  Expected> InputFileOrErr =
+  llvm::lto::InputFile::create(Buffer);
+  if (!InputFileOrErr)
+return InputFileOrErr.takeError();
+
+  // Save the input file and the buffer associated with its memory.
+  BitcodeFiles.push_back(std::move(*InputFileOrErr));
+  SavedBuffers.push_back(std::move(*BufferOrErr));
+  continue;
+}
+case file_magic::cuda_fatbinary: {
+  // Cuda fatbinaries made by Clang almost almost have an object eighty
+  // bytes from the beginning. This should be sufficient to identify the
+  // symbols.
+  Buffer = MemoryBufferRef(
+  (*BufferOrErr)->getBuffer().drop_front(FatbinaryOffset), "FatBinary");
+  LLVM_FALLTHROUGH;
+}
+case file_magic::elf_relocatable:
+case file_magic::elf_shared_object:
+case file_magic::macho_object:
+case file_magic::coff_object: {
   Expected> ObjFile =
-  ObjectFile::createObjectFile(**BufferOrErr, Type);
+  ObjectFile::createObjectFile(Buffer);
   if (!ObjFile)
-return ObjFile.takeError();
+continue;
 
   NewInputFiles.push_back(File.str());
   for (auto &Sym : (*ObjFile)->symbols()) {
@@ -973,15 +1004,10 @@
 else
   UsedInSharedLib.insert(Saver.save(*Name));
   }
-} else {
-  Expected> InputFileOrErr =
-  llvm::lto::InputFile::create(**BufferOrErr);
-  if (!InputFileOrErr)
-return InputFileOrErr.takeError();
-
-  // Save the input file and the buffer associated with its memory.
-  BitcodeFiles.push_back(std::move(*InputFileOrErr));
-  SavedBuffers.push_back(std::move(*BufferOrErr));
+  continue;
+}
+default:
+  continue;
 }
   }
 
Index: clang/test/Driver/linker-wrapper.c
===
--- clang/test/Driver/linker-wrapper.c
+++ clang/test/Driver/linker-wrapper.c
@@ -40,3 +40,11 @@
 
 // LTO: ptxas{{.*}}-m64 -o {{.*}}.cubin -O2 --gpu-name sm_70 {{.*}}.s
 // LTO-NOT: nvlink
+
+// RUN: %clang -cc1 %s -triple x86_64-unknown-linux-gnu -emit-obj -o %t.o \
+// RUN:   -fembed-offload-object=%S/Inputs/dummy-elf.o,openmp,nvptx64-nvida-cuda,sm_70 \
+// RUN:   -fembed-offload-object=%S/Inputs/dummy-elf.o,cuda,nvptx64-nvida-cuda,sm_70
+// RUN: clang-linker-wrapper --host-triple x86_64-unknown-linux-gnu --dry-run -linker-path \
+// RUN:   /usr/bin/ld -- %t.o -o a.out 2>&1 | FileCheck %s --check-prefix=CUDA_OMP_LINK
+
+// CUDA_OMP_LINK: nvlink{{.*}}-m64 -o {{.*}}.out -arch sm_70 {{.*}}.o {{.*}}.o
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D124462: [Analyzer] Fix clang::ento::taint::dumpTaint definition

2022-04-29 Thread Marco Antognini via Phabricator via cfe-commits
mantognini added a comment.

In D124462#3480348 , @aaron.ballman 
wrote:

> In D124462#3480219 , @steakhal 
> wrote:
>
>> Thanks for the stats.
>> @aaron.ballman WDYT, where should we put the `LLVM_DUMP_METHOD` ?
>
> The documentation for the attribute says function definitions, but I don't 
> think it matters in terms of the semantics of the attributes. I'd probably 
> put it on the definition in this case because the goal is to keep the 
> function around at runtime but it doesn't impact the interface of the call or 
> how users would use it at compile time.
>
> I noticed that we seem to be pretty bad about this advice however:
>
>   /// Note that you should also surround dump() functions with
>   /// `#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)` so they do always
>   /// get stripped in release builds.

I don't have a strong opinion on where `LLVM_DUMP_METHOD` should be and whether 
this means writing it twice as I can see arguments for both approaches.

In addition to not ifdef-out those functions, I note that many `dump` or 
`dumpToStream` functions in `Analysis` (and LLVM in general) don't have the 
`LLVM_DUMP_METHOD` macro at all.

So I'm tempted to say the overall situation should be improved in a separate 
effort, and this patch can focus only on the orthogonal linking issue. WDYT?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124462

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


[PATCH] D124679: [clangd] More precisely enable clang warnings through ClangTidy options

2022-04-29 Thread Sam McCall via Phabricator via cfe-commits
sammccall created this revision.
sammccall added a reviewer: kadircet.
Herald added subscribers: usaxena95, arphaman.
Herald added a project: All.
sammccall requested review of this revision.
Herald added subscribers: cfe-commits, MaskRay, ilya-biryukov.
Herald added projects: clang, clang-tools-extra.

clang-tidy's behavior is to add the -W flags, and then map all clang diagnostics
to "clang-diagnostic-foo" pseudo-check-names, then use Checks to filter those.

Previous to this patch, we were handling -W flags but not filtering the
diagnostics, assuming both sets of information encoded the same thing.

However this intersection is nontrivial when diagnostic group hierarchy is
involved. e.g. -Wunused + clang-diagnostic-unused-function should not enable
unused label warnings.

This patch more closely emulates clang-tidy's behavior, while not going to
the extreme of generating tidy check names for all clang diagnostics and
filtering them with regexes.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D124679

Files:
  clang-tools-extra/clangd/ParsedAST.cpp
  clang-tools-extra/clangd/unittests/DiagnosticsTests.cpp
  clang/include/clang/Basic/DiagnosticIDs.h
  clang/lib/Basic/DiagnosticIDs.cpp

Index: clang/lib/Basic/DiagnosticIDs.cpp
===
--- clang/lib/Basic/DiagnosticIDs.cpp
+++ clang/lib/Basic/DiagnosticIDs.cpp
@@ -628,13 +628,27 @@
   return OptionTable[static_cast(Group)].getName();
 }
 
+llvm::Optional
+DiagnosticIDs::getGroupForWarningOption(StringRef Name) {
+  const auto *Found = llvm::partition_point(
+  OptionTable, [=](const WarningOption &O) { return O.getName() < Name; });
+  if (Found == std::end(OptionTable) || Found->getName() != Name)
+return llvm::None;
+  return static_cast(Found - OptionTable);
+}
+
+llvm::Optional DiagnosticIDs::getGroupForDiag(unsigned DiagID) {
+  if (const StaticDiagInfoRec *Info = GetDiagInfo(DiagID))
+return static_cast(Info->getOptionGroupIndex());
+  return llvm::None;
+}
+
 /// getWarningOptionForDiag - Return the lowest-level warning option that
 /// enables the specified diagnostic.  If there is no -Wfoo flag that controls
 /// the diagnostic, this returns null.
 StringRef DiagnosticIDs::getWarningOptionForDiag(unsigned DiagID) {
-  if (const StaticDiagInfoRec *Info = GetDiagInfo(DiagID))
-return getWarningOptionForGroup(
-static_cast(Info->getOptionGroupIndex()));
+  if (auto G = getGroupForDiag(DiagID))
+return getWarningOptionForGroup(*G);
   return StringRef();
 }
 
@@ -683,12 +697,10 @@
 bool
 DiagnosticIDs::getDiagnosticsInGroup(diag::Flavor Flavor, StringRef Group,
  SmallVectorImpl &Diags) const {
-  auto Found = llvm::partition_point(
-  OptionTable, [=](const WarningOption &O) { return O.getName() < Group; });
-  if (Found == std::end(OptionTable) || Found->getName() != Group)
-return true; // Option not found.
-
-  return ::getDiagnosticsInGroup(Flavor, Found, Diags);
+  if (llvm::Optional G = getGroupForWarningOption(Group))
+return ::getDiagnosticsInGroup(
+Flavor, &OptionTable[static_cast(*G)], Diags);
+  return true;
 }
 
 void DiagnosticIDs::getAllDiagnostics(diag::Flavor Flavor,
Index: clang/include/clang/Basic/DiagnosticIDs.h
===
--- clang/include/clang/Basic/DiagnosticIDs.h
+++ clang/include/clang/Basic/DiagnosticIDs.h
@@ -231,6 +231,14 @@
   /// "deprecated-declarations".
   static StringRef getWarningOptionForGroup(diag::Group);
 
+  /// Given a group ID, returns the flag that toggles the group.
+  /// For example, for "deprecated-declarations", returns
+  /// Group::DeprecatedDeclarations.
+  static llvm::Optional getGroupForWarningOption(StringRef);
+
+  /// Return the lowest-level group that contains the specified diagnostic.
+  static llvm::Optional getGroupForDiag(unsigned DiagID);
+
   /// Return the lowest-level warning option that enables the specified
   /// diagnostic.
   ///
Index: clang-tools-extra/clangd/unittests/DiagnosticsTests.cpp
===
--- clang-tools-extra/clangd/unittests/DiagnosticsTests.cpp
+++ clang-tools-extra/clangd/unittests/DiagnosticsTests.cpp
@@ -517,13 +517,16 @@
   diagSeverity(DiagnosticsEngine::Error);
 }
 
-TidyProvider addClangArgs(std::vector ExtraArgs) {
-  return [ExtraArgs = std::move(ExtraArgs)](tidy::ClangTidyOptions &Opts,
-llvm::StringRef) {
+TidyProvider addClangArgs(std::vector ExtraArgs,
+  llvm::StringRef Checks) {
+  return [ExtraArgs = std::move(ExtraArgs), Checks = Checks.str()](
+ tidy::ClangTidyOptions &Opts, llvm::StringRef) {
 if (!Opts.ExtraArgs)
   Opts.ExtraArgs.emplace();
 for (llvm::StringRef Arg : ExtraArgs)
   Opts.ExtraArgs->emplace_back(Arg);
+if (!Checks.empty())
+  Opts.Checks = Ch

[PATCH] D124621: CPP-2461 [Analyzer] Fix assumptions about const field with member-initializer

2022-04-29 Thread Marco Antognini via Phabricator via cfe-commits
mantognini updated this revision to Diff 426077.
mantognini added a comment.

Update commit message and add FIXMEs


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124621

Files:
  clang/lib/StaticAnalyzer/Core/RegionStore.cpp
  clang/test/Analysis/cxx-member-initializer-const-field.cpp

Index: clang/test/Analysis/cxx-member-initializer-const-field.cpp
===
--- /dev/null
+++ clang/test/Analysis/cxx-member-initializer-const-field.cpp
@@ -0,0 +1,120 @@
+// RUN: %clang_analyze_cc1 -analyzer-checker=core -verify %s
+
+// This tests false-positive issues related to PR48534.
+//
+// Essentially, having a default member initializer for a constant member does
+// not necessarily imply the member will have the given default value.
+
+struct WithConstructor {
+  int *const ptr = nullptr;
+  WithConstructor(int *x) : ptr(x) {}
+
+  static auto compliant() {
+WithConstructor c(new int);
+return *(c.ptr); // no warning
+  }
+
+  static auto compliantWithParam(WithConstructor c) {
+return *(c.ptr); // no warning
+  }
+
+  static auto issue() {
+WithConstructor c(nullptr);
+return *(c.ptr); // expected-warning{{Dereference of null pointer (loaded from field 'ptr')}}
+  }
+};
+
+struct RegularAggregate {
+  int *const ptr = nullptr;
+
+  static int compliant() {
+RegularAggregate c{new int};
+return *(c.ptr); // no warning
+  }
+
+  static int issue() {
+RegularAggregate c;
+return *(c.ptr); // expected-warning{{Dereference of null pointer (loaded from field 'ptr')}}
+  }
+};
+
+struct WithConstructorAndArithmetic {
+  int const i = 0;
+  WithConstructorAndArithmetic(int x) : i(x + 1) {}
+
+  static int compliant(int y) {
+WithConstructorAndArithmetic c(0);
+return y / c.i; // no warning
+  }
+
+  static int issue(int y) {
+WithConstructorAndArithmetic c(-1);
+return y / c.i; // expected-warning{{Division by zero}}
+  }
+};
+
+struct WithConstructorDeclarationOnly {
+  int const i = 0;
+  WithConstructorDeclarationOnly(int x); // definition not visible.
+
+  static int compliant1(int y) {
+WithConstructorDeclarationOnly c(0);
+return y / c.i; // no warning
+  }
+
+  static int compliant2(int y) {
+WithConstructorDeclarationOnly c(-1);
+return y / c.i; // no warning
+  }
+};
+
+// NonAggregateFP is not an aggregate (j is a private non-static field) and has no custom constructor.
+// So we know i and j will always be 0 and 42, respectively.
+// That being said, this is not implemented because it is deemed too rare to be worth the complexity.
+struct NonAggregateFP {
+public:
+  int const i = 0;
+
+private:
+  int const j = 42;
+
+public:
+  static int falsePositive1(NonAggregateFP c) {
+return 10 / c.i; // FIXME: Currently, no warning.
+  }
+
+  static int falsePositive2(NonAggregateFP c) {
+return 10 / (c.j - 42); // FIXME: Currently, no warning.
+  }
+};
+
+struct NonAggregate {
+public:
+  int const i = 0;
+
+private:
+  int const j = 42;
+
+  NonAggregate(NonAggregate const &); // not provided, could set i and j to arbitrary values.
+
+public:
+  static int compliant1(NonAggregate c) {
+return 10 / c.i; // no warning
+  }
+
+  static int compliant2(NonAggregate c) {
+return 10 / (c.j - 42); // no warning
+  }
+};
+
+struct WithStaticMember {
+  static int const i = 0;
+
+  static int issue1(WithStaticMember c) {
+return 10 / c.i; // expected-warning{{division by zero is undefined}} expected-warning{{Division by zero}}
+  }
+
+  static int issue2() {
+return 10 / WithStaticMember::i; // expected-warning{{division by zero is undefined}} expected-warning{{Division by zero}}
+  }
+};
Index: clang/lib/StaticAnalyzer/Core/RegionStore.cpp
===
--- clang/lib/StaticAnalyzer/Core/RegionStore.cpp
+++ clang/lib/StaticAnalyzer/Core/RegionStore.cpp
@@ -1983,15 +1983,9 @@
   if (const Optional &V = B.getDirectBinding(R))
 return *V;
 
-  // Is the field declared constant and has an in-class initializer?
+  // If the containing record was initialized, try to get its constant value.
   const FieldDecl *FD = R->getDecl();
   QualType Ty = FD->getType();
-  if (Ty.isConstQualified())
-if (const Expr *Init = FD->getInClassInitializer())
-  if (Optional V = svalBuilder.getConstantVal(Init))
-return *V;
-
-  // If the containing record was initialized, try to get its constant value.
   const MemRegion* superR = R->getSuperRegion();
   if (const auto *VR = dyn_cast(superR)) {
 const VarDecl *VD = VR->getDecl();
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D124674: [analyzer] Indicate if a parent state is infeasible

2022-04-29 Thread Balázs Benics via Phabricator via cfe-commits
steakhal added a comment.

Finally, we have this!

Can we have this https://godbolt.org/z/oferc6P5Y in addition to the one you 
proposed?
I find it more readable.

What performance hit will we suffer from this change?
Please do a differential analysis.




Comment at: 
clang/include/clang/StaticAnalyzer/Core/PathSensitive/ConstraintManager.h:93
   /// assumed to be true or false, respectively.
-  ProgramStatePair assumeDual(ProgramStateRef State, DefinedSVal Cond) {
-ProgramStateRef StTrue = assume(State, Cond, true);
-
-// If StTrue is infeasible, asserting the falseness of Cond is unnecessary
-// because the existing constraints already establish this.
-if (!StTrue) {
-#ifdef EXPENSIVE_CHECKS
-  assert(assume(State, Cond, false) && "System is over constrained.");
-#endif
-  return ProgramStatePair((ProgramStateRef)nullptr, State);
-}
-
-ProgramStateRef StFalse = assume(State, Cond, false);
-if (!StFalse) {
-  // We are careful to return the original state, /not/ StTrue,
-  // because we want to avoid having callers generate a new node
-  // in the ExplodedGraph.
-  return ProgramStatePair(State, (ProgramStateRef)nullptr);
-}
-
-return ProgramStatePair(StTrue, StFalse);
-  }
+  ProgramStatePair assumeDual(ProgramStateRef State, DefinedSVal Cond);
 

I would leave a note here that these two states might be equal in a very rare 
case (*); but one should not depend on that.



Comment at: 
clang/include/clang/StaticAnalyzer/Core/PathSensitive/CoreEngine.h:293
  ExplodedNode *Pred) {
-return generateNodeImpl(PP, State, Pred, false);
+return generateNodeImpl(PP, State, Pred, State->isInfeasible());
   }





Comment at: 
clang/include/clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h:86
   GenericDataMap   GDM;  // Custom data stored by a client of this class.
+  bool Infeasible = false;
   unsigned refCount;

For the record, back then we had such flag. IDK when did we remove it, but we 
had it for sure.



Comment at: 
clang/include/clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h:113-115
+  ProgramStateRef cloneAsInfeasible() const;
+  bool isInfeasible() const { return Infeasible; }
+

These should not be public. Make friends if required.



Comment at: clang/lib/StaticAnalyzer/Core/ConstraintManager.cpp:51
+ProgramStateRef StFalse = assume(State, Cond, false);
+if (!StFalse) { // both infeasible
+  ProgramStateRef Infeasible = State->cloneAsInfeasible();

Should we mark this `LLVM_UNLIKELY(cond)`?
I would expect this function to be quite hot, and infeasible states rare.

Could we measure this one?



Comment at: clang/lib/StaticAnalyzer/Core/ConstraintManager.cpp:52-54
+  ProgramStateRef Infeasible = State->cloneAsInfeasible();
+  assert(Infeasible->isInfeasible());
+  return ProgramStatePair(Infeasible, Infeasible);

Add here some comments on why we return (`Infeasible`,`Infeasible`).
I would rather see `StInfeasible` to better discriminate what we are talking 
about. We already use `StTrue` and `StFalse` in this context though.



Comment at: clang/test/Analysis/sink-infeasible.c:37-48
+  /* The BASELINE passes these checks ('wrning' is used to avoid lit to match)
+  // The parent state is already infeasible, look at this contradiction:
+  clang_analyzer_eval(b > 0);  // expected-wrning{{FALSE}}
+  clang_analyzer_eval(b <= 0); // expected-wrning{{FALSE}}
+  // Crashes with expensive checks.
+  if (b > 0) {
+clang_analyzer_warnIfReached(); // no-warning, OK

You could use a non-default check prefix.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124674

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


[PATCH] D124621: CPP-2461 [Analyzer] Fix assumptions about const field with member-initializer

2022-04-29 Thread Marco Antognini via Phabricator via cfe-commits
mantognini marked 2 inline comments as done.
mantognini added a comment.

In D124621#3481973 , @steakhal wrote:

> LGTM
>
> In D124621#3481906 , @mantognini 
> wrote:
>
>> One thing I'm not sure about and couldn't easily find in the doc is how to 
>> reference in the commit message the bug (https://llvm.org/PR48534) this 
>> patch fixes. Is it good as is?
>
> AFAIK we should prefer GitHub issue numbers to the old BugZilla numbers.
> Could you please update all references of `48534` -> `47878`.
>
> In addition, I think `Fixes #47878` should work in the commit message, and 
> automatically close the given GitHub issue.

Thanks for the feedback!

> BTW have you measured the observable impact of this patch on large codebases? 
> Do you have any stats?

I can't share the data but I can say it fixes some user reports. :-)

In D124621#3481981 , @steakhal wrote:

> Noq wrote 
> https://github.com/llvm/llvm-project/issues/47878#issuecomment-981036634
>
>> Aha, uhm, yeah, i see. The static analyzer indeed thinks that a combination 
>> of "const" and a field initializer causes the field to forever stay that 
>> way. **We'll need to undo this relatively recently added shortcut.**
>
> What "recently added shortcut" did he mention? Could you please refer to that 
> commit in the patch summary, please?

I think @NoQ refers to https://reviews.llvm.org/D45774 but I'll wait for a week 
or so for confirmation in case there's more to it.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124621

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


[PATCH] D124679: [clangd] More precisely enable clang warnings through ClangTidy options

2022-04-29 Thread Kadir Cetinkaya via Phabricator via cfe-commits
kadircet accepted this revision.
kadircet added a comment.
This revision is now accepted and ready to land.

thanks, lgtm!




Comment at: clang-tools-extra/clangd/ParsedAST.cpp:240
+// Note that unlike -Wunused, clang-diagnostics-unused does not imply
+// subcategories like clang-diagnostics-unused function.
+//

s/clang-diagnostics-unused function/clang-diagnostics-unused-function/



Comment at: clang-tools-extra/clangd/ParsedAST.cpp:254
+  TidyDiagnosticGroups(llvm::StringRef Checks) {
+constexpr llvm::StringLiteral CDPrefix = "clang-diagnostic-";
+

`static constexpr`


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124679

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


[PATCH] D124534: Add a diagnostic for line directive of a gnu extension

2022-04-29 Thread Ken Matsui via Phabricator via cfe-commits
ken-matsui added inline comments.



Comment at: clang/lib/Lex/PPDirectives.cpp:1356
+
+PP.Diag(FlagTok, diag::ext_pp_gnu_line_directive);
   } else if (FlagVal == 2) {

aaron.ballman wrote:
> I speculate that this change is wrong.
> 
> The goal here is to diagnose any time there's a GNU line marker and now we're 
> only trigging the diagnostic when the line marker's value is 1; that misses 
> diagnostics when the marker value is something else.
> 
> That's why I suggested warning each place we return `false` from this 
> function -- those are the situations when the line marker is syntactically 
> correct and we're going to make use of it in the caller. (We don't want to 
> warn about use of a line marker when we're going to generate an error anyway.)
@aaron.ballman 

Thank you!

Just to confirm, do I need to remove the call of `Diag` after `GetLineValue` 
and put `Diag`s into all branches of returning `false` in this function?
If so, I think putting `Diag` after the call of this function would be better.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124534

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


[PATCH] D124462: [Analyzer] Fix clang::ento::taint::dumpTaint definition

2022-04-29 Thread Balázs Benics via Phabricator via cfe-commits
steakhal accepted this revision.
steakhal added a comment.
This revision is now accepted and ready to land.

In D124462#3482728 , @mantognini 
wrote:

> In D124462#3480348 , @aaron.ballman 
> wrote:
>
>> In D124462#3480219 , @steakhal 
>> wrote:
>>
>>> Thanks for the stats.
>>> @aaron.ballman WDYT, where should we put the `LLVM_DUMP_METHOD` ?
>>
>> The documentation for the attribute says function definitions, but I don't 
>> think it matters in terms of the semantics of the attributes. I'd probably 
>> put it on the definition in this case because the goal is to keep the 
>> function around at runtime but it doesn't impact the interface of the call 
>> or how users would use it at compile time.
>>
>> I noticed that we seem to be pretty bad about this advice however:
>>
>>   /// Note that you should also surround dump() functions with
>>   /// `#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)` so they do always
>>   /// get stripped in release builds.
>
> I don't have a strong opinion on where `LLVM_DUMP_METHOD` should be and 
> whether this means writing it twice as I can see arguments for both 
> approaches.
>
> In addition to not ifdef-out those functions, I note that many `dump` or 
> `dumpToStream` functions in `Analysis` (and LLVM in general) don't have the 
> `LLVM_DUMP_METHOD` macro at all.

This is because in some cases it makes sense to preserve such dumps, e.g. the 
CFG dump might be useful not only for debugging but for others as well. Or the 
liveness analysis stuff and a lot more.

For this case specifically, one should not dump these taint metadata in release 
builds IMO. I've done some measurements to inspect the size increase for 
preserving some dump methods, and at the time I could not see much difference 
at all.
Check D124442 , D124443 
. They have not landed yet, but I'm planning 
to land them in the close future.

> So I'm tempted to say the overall situation should be improved in a separate 
> effort, and this patch can focus only on the orthogonal linking issue. WDYT?

Definitely. We should consolidate the situation but at another time.
LGTM, given that you add the `LLVM_DUMP_METHOD` to any of the declarations.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124462

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


[PATCH] D124621: [Analyzer] Fix assumptions about const field with member-initializer

2022-04-29 Thread Balázs Benics via Phabricator via cfe-commits
steakhal accepted this revision.
steakhal added a comment.

In D124621#3482782 , @mantognini 
wrote:

> In D124621#3481973 , @steakhal 
> wrote:
>
>> BTW have you measured the observable impact of this patch on large 
>> codebases? Do you have any stats?
>
> I can't share the data but I can say it fixes some user reports. :-)

For the upcoming patches, it would be nice to test the patches on a small set 
of open-source projects for exactly this reason.
I think there is a `clang/utils/analyzer/SATest.py` script helping you on this 
part.
It seems we have quite a few projects on the testset 
`clang/utils/analyzer/projects/projects.json`.
We are not using it, because we have a different internal testing 
infrastructure, but it's definitely better than nothing.

> I think @NoQ refers to https://reviews.llvm.org/D45774 but I'll wait for a 
> week or so for confirmation in case there's more to it.

Cool!




Comment at: clang/lib/StaticAnalyzer/Core/RegionStore.cpp:1982-1984
   // Check if the region has a binding.
   if (const Optional &V = B.getDirectBinding(R))
 return *V;

@NoQ I was always puzzled why don't we check if we have default bindings after 
checking direct bindings.
Do you have anything about that?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124621

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


[clang] 813e521 - [AMDGPU] Add gfx11 subtarget ELF definition

2022-04-29 Thread Joe Nash via cfe-commits

Author: Joe Nash
Date: 2022-04-29T12:27:17-04:00
New Revision: 813e521e55b11165138b071f446eda94b14570dc

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

LOG: [AMDGPU] Add gfx11 subtarget ELF definition

This is the first patch of a series to upstream support for the new
subtarget.

Contributors:
Jay Foad 
Konstantin Zhuravlyov 

Patch 1/N for upstreaming AMDGPU gfx11 architectures.

Reviewed By: foad, kzhuravl, #amdgpu

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

Added: 


Modified: 
clang/test/Misc/target-invalid-cpu-note.c
llvm/docs/AMDGPUUsage.rst
llvm/include/llvm/BinaryFormat/ELF.h
llvm/include/llvm/Support/TargetParser.h
llvm/lib/Object/ELFObjectFile.cpp
llvm/lib/ObjectYAML/ELFYAML.cpp
llvm/lib/Support/TargetParser.cpp
llvm/lib/Target/AMDGPU/MCTargetDesc/AMDGPUTargetStreamer.cpp
llvm/test/Object/AMDGPU/elf-header-flags-mach.yaml
llvm/test/tools/llvm-readobj/ELF/amdgpu-elf-headers.test
llvm/tools/llvm-readobj/ELFDumper.cpp

Removed: 




diff  --git a/clang/test/Misc/target-invalid-cpu-note.c 
b/clang/test/Misc/target-invalid-cpu-note.c
index 8b9409336d1cb..4248090cb9feb 100644
--- a/clang/test/Misc/target-invalid-cpu-note.c
+++ b/clang/test/Misc/target-invalid-cpu-note.c
@@ -37,7 +37,7 @@
 
 // RUN: not %clang_cc1 -triple amdgcn--- -target-cpu not-a-cpu -fsyntax-only 
%s 2>&1 | FileCheck %s --check-prefix AMDGCN
 // AMDGCN: error: unknown target CPU 'not-a-cpu'
-// AMDGCN-NEXT: note: valid target CPU values are: gfx600, tahiti, gfx601, 
pitcairn, verde, gfx602, hainan, oland, gfx700, kaveri, gfx701, hawaii, gfx702, 
gfx703, kabini, mullins, gfx704, bonaire, gfx705, gfx801, carrizo, gfx802, 
iceland, tonga, gfx803, fiji, polaris10, polaris11, gfx805, tongapro, gfx810, 
stoney, gfx900, gfx902, gfx904, gfx906, gfx908, gfx909, gfx90a, gfx90c, gfx940, 
gfx1010, gfx1011, gfx1012, gfx1013, gfx1030, gfx1031, gfx1032, gfx1033, 
gfx1034, gfx1035, gfx1036{{$}}
+// AMDGCN-NEXT: note: valid target CPU values are: gfx600, tahiti, gfx601, 
pitcairn, verde, gfx602, hainan, oland, gfx700, kaveri, gfx701, hawaii, gfx702, 
gfx703, kabini, mullins, gfx704, bonaire, gfx705, gfx801, carrizo, gfx802, 
iceland, tonga, gfx803, fiji, polaris10, polaris11, gfx805, tongapro, gfx810, 
stoney, gfx900, gfx902, gfx904, gfx906, gfx908, gfx909, gfx90a, gfx90c, gfx940, 
gfx1010, gfx1011, gfx1012, gfx1013, gfx1030, gfx1031, gfx1032, gfx1033, 
gfx1034, gfx1035, gfx1036, gfx1100, gfx1101, gfx1102, gfx1103{{$}}
 
 // RUN: not %clang_cc1 -triple wasm64--- -target-cpu not-a-cpu -fsyntax-only 
%s 2>&1 | FileCheck %s --check-prefix WEBASM
 // WEBASM: error: unknown target CPU 'not-a-cpu'

diff  --git a/llvm/docs/AMDGPUUsage.rst b/llvm/docs/AMDGPUUsage.rst
index e962674867df5..1cc342f85c659 100644
--- a/llvm/docs/AMDGPUUsage.rst
+++ b/llvm/docs/AMDGPUUsage.rst
@@ -444,6 +444,36 @@ Every processor supports every OS ABI (see 
:ref:`amdgpu-os`) with the following

 Add product

 names.
 
+ **GCN GFX11** [AMD-GCN-GFX11]_
+ 
---
+ ``gfx1100`` ``amdgcn``   dGPU  - cumode  - 
Architected   - *pal-amdpal*  *TBA*
+- wavefrontsize64   flat
+
scratch   .. TODO::
+  - Packed
+
work-item   Add product
+IDs
 names.
+
+ ``gfx1101`` ``amdgcn``   dGPU  - cumode  - 
Architected   *TBA*
+- wavefrontsize64   flat
+
scratch   .. TODO::
+  - Packed
+
work-item   Add product
+IDs
 names.
+
+ ``gfx1102`` ``amdgcn``   dGPU  - cumode  - 
Architected   *TBA*
+- wavefrontsize64   flat
+ 

[PATCH] D124536: [AMDGPU] Add gfx11 subtarget ELF definition

2022-04-29 Thread Joe Nash 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 rG813e521e55b1: [AMDGPU] Add gfx11 subtarget ELF definition 
(authored by Joe_Nash).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124536

Files:
  clang/test/Misc/target-invalid-cpu-note.c
  llvm/docs/AMDGPUUsage.rst
  llvm/include/llvm/BinaryFormat/ELF.h
  llvm/include/llvm/Support/TargetParser.h
  llvm/lib/Object/ELFObjectFile.cpp
  llvm/lib/ObjectYAML/ELFYAML.cpp
  llvm/lib/Support/TargetParser.cpp
  llvm/lib/Target/AMDGPU/MCTargetDesc/AMDGPUTargetStreamer.cpp
  llvm/test/Object/AMDGPU/elf-header-flags-mach.yaml
  llvm/test/tools/llvm-readobj/ELF/amdgpu-elf-headers.test
  llvm/tools/llvm-readobj/ELFDumper.cpp

Index: llvm/tools/llvm-readobj/ELFDumper.cpp
===
--- llvm/tools/llvm-readobj/ELFDumper.cpp
+++ llvm/tools/llvm-readobj/ELFDumper.cpp
@@ -1539,6 +1539,10 @@
   LLVM_READOBJ_ENUM_ENT(ELF, EF_AMDGPU_MACH_AMDGCN_GFX1034),
   LLVM_READOBJ_ENUM_ENT(ELF, EF_AMDGPU_MACH_AMDGCN_GFX1035),
   LLVM_READOBJ_ENUM_ENT(ELF, EF_AMDGPU_MACH_AMDGCN_GFX1036),
+  LLVM_READOBJ_ENUM_ENT(ELF, EF_AMDGPU_MACH_AMDGCN_GFX1100),
+  LLVM_READOBJ_ENUM_ENT(ELF, EF_AMDGPU_MACH_AMDGCN_GFX1101),
+  LLVM_READOBJ_ENUM_ENT(ELF, EF_AMDGPU_MACH_AMDGCN_GFX1102),
+  LLVM_READOBJ_ENUM_ENT(ELF, EF_AMDGPU_MACH_AMDGCN_GFX1103),
   LLVM_READOBJ_ENUM_ENT(ELF, EF_AMDGPU_FEATURE_XNACK_V3),
   LLVM_READOBJ_ENUM_ENT(ELF, EF_AMDGPU_FEATURE_SRAMECC_V3)
 };
@@ -1595,6 +1599,10 @@
   LLVM_READOBJ_ENUM_ENT(ELF, EF_AMDGPU_MACH_AMDGCN_GFX1034),
   LLVM_READOBJ_ENUM_ENT(ELF, EF_AMDGPU_MACH_AMDGCN_GFX1035),
   LLVM_READOBJ_ENUM_ENT(ELF, EF_AMDGPU_MACH_AMDGCN_GFX1036),
+  LLVM_READOBJ_ENUM_ENT(ELF, EF_AMDGPU_MACH_AMDGCN_GFX1100),
+  LLVM_READOBJ_ENUM_ENT(ELF, EF_AMDGPU_MACH_AMDGCN_GFX1101),
+  LLVM_READOBJ_ENUM_ENT(ELF, EF_AMDGPU_MACH_AMDGCN_GFX1102),
+  LLVM_READOBJ_ENUM_ENT(ELF, EF_AMDGPU_MACH_AMDGCN_GFX1103),
   LLVM_READOBJ_ENUM_ENT(ELF, EF_AMDGPU_FEATURE_XNACK_ANY_V4),
   LLVM_READOBJ_ENUM_ENT(ELF, EF_AMDGPU_FEATURE_XNACK_OFF_V4),
   LLVM_READOBJ_ENUM_ENT(ELF, EF_AMDGPU_FEATURE_XNACK_ON_V4),
Index: llvm/test/tools/llvm-readobj/ELF/amdgpu-elf-headers.test
===
--- llvm/test/tools/llvm-readobj/ELF/amdgpu-elf-headers.test
+++ llvm/test/tools/llvm-readobj/ELF/amdgpu-elf-headers.test
@@ -337,6 +337,42 @@
 # RUN: yaml2obj %s -o %t -DABI_VERSION=16 -DFLAG_NAME=EF_AMDGPU_MACH_AMDGCN_GFX90A
 # RUN: llvm-readobj -h %t | FileCheck %s --check-prefixes=ALL,UNKNOWN-ABI-VERSION --match-full-lines -DABI_VERSION=16 -DFILE=%t -DFLAG_VALUE=0x3F
 
+# RUN: yaml2obj %s -o %t -DABI_VERSION=0 -DFLAG_NAME=EF_AMDGPU_MACH_AMDGCN_GFX1100
+# RUN: llvm-readobj -h %t | FileCheck %s --check-prefixes=ALL,KNOWN-ABI-VERSION,SINGLE-FLAG --match-full-lines -DABI_VERSION=0 -DFILE=%t -DFLAG_NAME=EF_AMDGPU_MACH_AMDGCN_GFX1100 -DFLAG_VALUE=0x41
+
+# RUN: yaml2obj %s -o %t -DABI_VERSION=1 -DFLAG_NAME=EF_AMDGPU_MACH_AMDGCN_GFX1100
+# RUN: llvm-readobj -h %t | FileCheck %s --check-prefixes=ALL,KNOWN-ABI-VERSION,SINGLE-FLAG --match-full-lines -DABI_VERSION=1 -DFILE=%t -DFLAG_NAME=EF_AMDGPU_MACH_AMDGCN_GFX1100 -DFLAG_VALUE=0x41
+
+# RUN: yaml2obj %s -o %t -DABI_VERSION=2 -DFLAG_NAME=EF_AMDGPU_MACH_AMDGCN_GFX1100
+# RUN: llvm-readobj -h %t | FileCheck %s --check-prefixes=ALL,KNOWN-ABI-VERSION,SINGLE-FLAG --match-full-lines -DABI_VERSION=2 -DFILE=%t -DFLAG_NAME=EF_AMDGPU_MACH_AMDGCN_GFX1100 -DFLAG_VALUE=0x41
+
+# RUN: yaml2obj %s -o %t -DABI_VERSION=0 -DFLAG_NAME=EF_AMDGPU_MACH_AMDGCN_GFX1101
+# RUN: llvm-readobj -h %t | FileCheck %s --check-prefixes=ALL,KNOWN-ABI-VERSION,SINGLE-FLAG --match-full-lines -DABI_VERSION=0 -DFILE=%t -DFLAG_NAME=EF_AMDGPU_MACH_AMDGCN_GFX1101 -DFLAG_VALUE=0x46
+
+# RUN: yaml2obj %s -o %t -DABI_VERSION=1 -DFLAG_NAME=EF_AMDGPU_MACH_AMDGCN_GFX1101
+# RUN: llvm-readobj -h %t | FileCheck %s --check-prefixes=ALL,KNOWN-ABI-VERSION,SINGLE-FLAG --match-full-lines -DABI_VERSION=1 -DFILE=%t -DFLAG_NAME=EF_AMDGPU_MACH_AMDGCN_GFX1101 -DFLAG_VALUE=0x46
+
+# RUN: yaml2obj %s -o %t -DABI_VERSION=2 -DFLAG_NAME=EF_AMDGPU_MACH_AMDGCN_GFX1101
+# RUN: llvm-readobj -h %t | FileCheck %s --check-prefixes=ALL,KNOWN-ABI-VERSION,SINGLE-FLAG --match-full-lines -DABI_VERSION=2 -DFILE=%t -DFLAG_NAME=EF_AMDGPU_MACH_AMDGCN_GFX1101 -DFLAG_VALUE=0x46
+
+# RUN: yaml2obj %s -o %t -DABI_VERSION=0 -DFLAG_NAME=EF_AMDGPU_MACH_AMDGCN_GFX1102
+# RUN: llvm-readobj -h %t | FileCheck %s --check-prefixes=ALL,KNOWN-ABI-VERSION,SINGLE-FLAG --match-full-lines -DABI_VERSION=0 -DFILE=%t -DFLAG_NAME=EF_AMDGPU_MACH_AMDGCN_GFX1102 -DFLAG_VALUE=0x47
+
+# RUN: yaml2obj %s -o %t -DABI_VERSION=1 -DFLAG_NAME=EF_AMDGPU_MACH_AMDGCN_GFX1102
+# RUN: llvm-readobj -h %t | FileCheck %s --check-prefixes=ALL,KNOWN-ABI-VERSION,SINGLE-FLAG --match-full-lines -DABI_VERSION=1 -DFILE=%t -DF

[PATCH] D122895: [C89/C2x] Improve diagnostics around strict prototypes in C

2022-04-29 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman added a comment.

In D122895#3482707 , @manojgupta 
wrote:

>   Is disabling the pedantic warning an option for your users?
>
> Disabling it wholesale is not an option since they actually want this warning 
>  (the older version). But we agreed to disable it specifically for the code 
> where the warning was getting fired.
> One instance is https://review.coreboot.org/c/coreboot/+/63936 .
>
> I have been fixing our codebase to clean this and clean the instances. But it 
> takes a lot of time and effort. Plus it takes a long time to clean one 
> failure before I can find others  (public CLs) 
> https://chromium-review.googlesource.com/q/Wstrict-prototypes+owner:manojgupta

Out of curiosity, are you using K&R C functions in your code base (definitions 
with an identifier list or a declaration with empty parens)? Basically, I'm 
wondering if you'd be able to enable `-fno-knr-function`?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D122895

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


[clang] 9c8a883 - [Clang][Docs] Add new offloading flags to the clang documentation

2022-04-29 Thread Joseph Huber via cfe-commits

Author: Joseph Huber
Date: 2022-04-29T13:07:11-04:00
New Revision: 9c8a88382d86c731db3c5c92d8ecd6ef296329ab

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

LOG: [Clang][Docs] Add new offloading flags to the clang documentation

Summary:
Some previous patches introduced the `--offload-new-driver` flag, which
is a generic way to enable the new driver, and the `--offload-host-only`
and `--offload-device-only` flags which allow users to compile for one
side, making it easier to inspect intermediate code for offloading
compilations. This patch just documents them in the command line
reference.

Added: 


Modified: 
clang/docs/ClangCommandLineReference.rst

Removed: 




diff  --git a/clang/docs/ClangCommandLineReference.rst 
b/clang/docs/ClangCommandLineReference.rst
index 33f9a55f6248..384b092389c8 100644
--- a/clang/docs/ClangCommandLineReference.rst
+++ b/clang/docs/ClangCommandLineReference.rst
@@ -238,6 +238,22 @@ Flush denormal floating point values to zero in CUDA/HIP 
device mode.
 
 Specify comma-separated list of triples OpenMP offloading targets to be 
supported
 
+.. option:: -fopenmp-new-driver, -fno-openmp-new-driver
+
+Use the new driver for OpenMP offloading.
+
+.. option:: --offload-new-driver, --no-offload-new-driver
+
+Use the new driver for offloading compilation.
+
+.. option:: --offload-host-only
+
+Only compile for the host when offloading.
+
+.. option:: --offload-device-only
+
+Only compile for the device when offloading.
+
 .. option:: -force\_cpusubtype\_ALL
 
 .. program:: clang1
@@ -801,10 +817,6 @@ Generate Interface Stub Files, emit merged text not binary.
 
 Extract API information
 
-.. option:: -fopenmp-new-driver, fno-openmp-new-driver
-
-Use the new driver for OpenMP offloading.
-
 .. option:: -fsyntax-only
 
 .. option:: -module-file-info



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


[PATCH] D124650: [clang-tidy] Simplify boolean expressions by DeMorgan's theorem

2022-04-29 Thread Richard via Phabricator via cfe-commits
LegalizeAdulthood updated this revision to Diff 426111.
LegalizeAdulthood added a comment.

Sort changes by check name in docs


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

https://reviews.llvm.org/D124650

Files:
  clang-tools-extra/clang-tidy/readability/SimplifyBooleanExprCheck.cpp
  clang-tools-extra/clang-tidy/readability/SimplifyBooleanExprCheck.h
  clang-tools-extra/docs/ReleaseNotes.rst
  clang-tools-extra/docs/clang-tidy/checks/readability-simplify-boolean-expr.rst
  
clang-tools-extra/test/clang-tidy/checkers/readability-simplify-bool-expr-demorgan.cpp

Index: clang-tools-extra/test/clang-tidy/checkers/readability-simplify-bool-expr-demorgan.cpp
===
--- /dev/null
+++ clang-tools-extra/test/clang-tidy/checkers/readability-simplify-bool-expr-demorgan.cpp
@@ -0,0 +1,24 @@
+// RUN: %check_clang_tidy %s readability-simplify-boolean-expr %t -- -config="{CheckOptions: [{key: "readability-simplify-boolean-expr.SimplifyDeMorgan", value: true}]}" --
+
+bool a1 = false;
+bool a2 = false;
+
+bool aa = !(!a1 || a2);
+bool ab = !(a1 || !a2);
+bool ac = !(!a1 || !a2);
+// CHECK-MESSAGES: :[[@LINE-3]]:11: warning: boolean expression can be simplified by DeMorgan's theorem [readability-simplify-boolean-expr]
+// CHECK-MESSAGES: :[[@LINE-3]]:11: warning: boolean expression can be simplified by DeMorgan's theorem [readability-simplify-boolean-expr]
+// CHECK-MESSAGES: :[[@LINE-3]]:11: warning: boolean expression can be simplified by DeMorgan's theorem [readability-simplify-boolean-expr]
+// CHECK-FIXES: {{^bool aa = a1 && !a2;$}}
+// CHECK-FIXES-NEXT: {{^bool ab = !a1 && a2;$}}
+// CHECK-FIXES-NEXT: {{^bool ac = a1 && a2;$}}
+
+bool ba = !(!a1 && a2);
+bool bb = !(a1 && !a2);
+bool bc = !(!a1 && !a2);
+// CHECK-MESSAGES: :[[@LINE-3]]:11: warning: boolean expression can be simplified by DeMorgan's theorem [readability-simplify-boolean-expr]
+// CHECK-MESSAGES: :[[@LINE-3]]:11: warning: boolean expression can be simplified by DeMorgan's theorem [readability-simplify-boolean-expr]
+// CHECK-MESSAGES: :[[@LINE-3]]:11: warning: boolean expression can be simplified by DeMorgan's theorem [readability-simplify-boolean-expr]
+// CHECK-FIXES: {{^bool ba = a1 }}||{{ !a2;$}}
+// CHECK-FIXES-NEXT: {{^bool bb = !a1 }}||{{ a2;$}}
+// CHECK-FIXES-NEXT: {{^bool bc = a1 }}||{{ a2;$}}
Index: clang-tools-extra/docs/clang-tidy/checks/readability-simplify-boolean-expr.rst
===
--- clang-tools-extra/docs/clang-tidy/checks/readability-simplify-boolean-expr.rst
+++ clang-tools-extra/docs/clang-tidy/checks/readability-simplify-boolean-expr.rst
@@ -4,7 +4,8 @@
 =
 
 Looks for boolean expressions involving boolean constants and simplifies
-them to use the appropriate boolean expression directly.
+them to use the appropriate boolean expression directly.  Simplifies
+boolean expressions by application of DeMorgan's Theorem.
 
 Examples:
 
@@ -27,6 +28,12 @@
 ``if (e) b = false; else b = true;``   ``b = !e;``
 ``if (e) return true; return false;``  ``return e;``
 ``if (e) return false; return true;``  ``return !e;``
+``!(!a || b)`` ``a && !b``
+``!(a || !b)`` ``!a && b``
+``!(!a || !b)````a && b``
+``!(!a && b)`` ``a || !b``
+``!(a && !b)`` ``!a || b``
+``!(!a && !b)````a || b``
 ===  
 
 The resulting expression ``e`` is modified as follows:
@@ -84,3 +91,8 @@
 
If `true`, conditional boolean assignments at the end of an ``if/else
if`` chain will be transformed. Default is `false`.
+
+.. option:: SimplifyDeMorgan
+
+   If `true`, DeMorgan's Theorem will be applied to simplify negated
+   conjunctions and disjunctions.  Default is `true`.
Index: clang-tools-extra/docs/ReleaseNotes.rst
===
--- clang-tools-extra/docs/ReleaseNotes.rst
+++ clang-tools-extra/docs/ReleaseNotes.rst
@@ -136,6 +136,12 @@
 Changes in existing checks
 ^^
 
+- Fixed nonsensical suggestion of :doc:`altera-struct-pack-align
+  ` check for empty structs.
+
+- Fixed some false positives in :doc:`bugprone-infinite-loop
+  ` involving dependent expressions.
+
 - Fixed a crash in :doc:`bugprone-sizeof-expression
   ` when `sizeof(...)` is
   compared against a `__int128_t`.
@@ -158,26 +164,24 @@
   ` involving assignments in
   conditions. This fixes `Issue 35853 `_.
 
-- Fixed a crash in :doc:`readability-const-return-type
-  ` when a pure virtual function
-  overrided has a const return type. Removed the fix for a virtual function.
-
-- Fixed a false positive in :doc:`readability-non-const-

[clang] ef87865 - Silence -Wstrict-prototype diagnostics in C2x mode

2022-04-29 Thread Aaron Ballman via cfe-commits

Author: Aaron Ballman
Date: 2022-04-29T13:37:33-04:00
New Revision: ef87865b98fa25af1d2c045bab1268b2a1503374

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

LOG: Silence -Wstrict-prototype diagnostics in C2x mode

This also disables the diagnostic when the user passes -fno-knr-functions.

Added: 
clang/test/Sema/c2x-warn-strict-prototypes.c

Modified: 
clang/docs/ReleaseNotes.rst
clang/lib/Sema/SemaType.cpp

Removed: 




diff  --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 652ef45b24df..91944e0b11ef 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -149,14 +149,17 @@ Improvements to Clang's diagnostics
   now only diagnose deprecated declarations and definitions of functions
   without a prototype where the behavior in C2x will remain correct. This
   diagnostic remains off by default but is now enabled via ``-pedantic`` due to
-  it being a deprecation warning. ``-Wdeprecated-non-prototype`` will diagnose
-  cases where the deprecated declarations or definitions of a function without
-  a prototype will change behavior in C2x. Additionally, it will diagnose calls
-  which pass arguments to a function without a prototype. This warning is
-  enabled only when the ``-Wdeprecated-non-prototype`` option is enabled at the
-  function declaration site, which allows a developer to disable the diagnostic
-  for all callers at the point of declaration. This diagnostic is grouped under
-  the ``-Wstrict-prototypes`` warning group, but is enabled by default.
+  it being a deprecation warning. ``-Wstrict-prototypes`` has no effect in C2x
+  or when ``-fno-knr-functions`` is enabled. ``-Wdeprecated-non-prototype``
+  will diagnose cases where the deprecated declarations or definitions of a
+  function without a prototype will change behavior in C2x. Additionally, it
+  will diagnose calls which pass arguments to a function without a prototype.
+  This warning is enabled only when the ``-Wdeprecated-non-prototype`` option
+  is enabled at the function declaration site, which allows a developer to
+  disable the diagnostic for all callers at the point of declaration. This
+  diagnostic is grouped under the ``-Wstrict-prototypes`` warning group, but is
+  enabled by default. ``-Wdeprecated-non-prototype`` has no effect in C2x or
+  when ``-fno-knr-functions`` is enabled.
 - Clang now appropriately issues an error in C when a definition of a function
   without a prototype and with no arguments is an invalid redeclaration of a
   function with a prototype. e.g., ``void f(int); void f() {}`` is now properly

diff  --git a/clang/lib/Sema/SemaType.cpp b/clang/lib/Sema/SemaType.cpp
index 6f34e4237bcb..a037956d5e49 100644
--- a/clang/lib/Sema/SemaType.cpp
+++ b/clang/lib/Sema/SemaType.cpp
@@ -5564,7 +5564,7 @@ static TypeSourceInfo 
*GetFullTypeForDeclarator(TypeProcessingState &state,
   //   of the parameters is supplied.
   // See ActOnFinishFunctionBody() and MergeFunctionDecl() for handling of
   // function declarations whose behavior changes in C2x.
-  if (!LangOpts.CPlusPlus) {
+  if (!LangOpts.requiresStrictPrototypes()) {
 bool IsBlock = false;
 for (const DeclaratorChunk &DeclType : D.type_objects()) {
   switch (DeclType.Kind) {

diff  --git a/clang/test/Sema/c2x-warn-strict-prototypes.c 
b/clang/test/Sema/c2x-warn-strict-prototypes.c
new file mode 100644
index ..f3efa1a3aa49
--- /dev/null
+++ b/clang/test/Sema/c2x-warn-strict-prototypes.c
@@ -0,0 +1,9 @@
+// RUN: %clang_cc1 -fsyntax-only -Wstrict-prototypes -verify -std=c2x %s
+// RUN: %clang_cc1 -fsyntax-only -Wstrict-prototypes -verify 
-fno-knr-functions %s
+// expected-no-diagnostics
+
+void foo();
+void bar() {}
+
+void baz(void);
+void baz() {}



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


[PATCH] D122895: [C89/C2x] Improve diagnostics around strict prototypes in C

2022-04-29 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman added a comment.

In D122895#3482575 , @aaron.ballman 
wrote:

> In D122895#3482555 , @tahonermann 
> wrote:
>
>>> I think it's debatable whether this is a bug or not
>>
>> For C99 through C17, I kind of agree, but for C2x (where the warning is 
>> still issued with `-Wstrict-prototypes`), my understanding is that `void 
>> foo(void)` and `void foo()` are equivalent; there is no unprototyped 
>> declaration. I think the diagnostic should at least be suppressed for C2x 
>> since we don't want to encourage programmers to explicitly add `void` when 
>> targeting that standard.
>
> Good catch... `-Wstrict-prototypes` should be a noop in C2x mode! I'll work 
> on fixing that.

I fixed that issue in ef87865b98fa25af1d2c045bab1268b2a1503374 
, thanks 
for catching it.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D122895

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


[PATCH] D124500: [clang-tidy] Support expressions of literals in modernize-macro-to-enum

2022-04-29 Thread Richard via Phabricator via cfe-commits
LegalizeAdulthood marked 2 inline comments as done.
LegalizeAdulthood added inline comments.



Comment at: 
clang-tools-extra/clang-tidy/modernize/IntegralLiteralExpressionMatcher.cpp:32-33
+  // not a decimal floating-point literal
+  return std::none_of(
+  Begin, End, [](char C) { return C == '.' || std::toupper(C) == 'E'; });
+}

aaron.ballman wrote:
> Do we need to care about integer suffixes that make a non-integer type, like: 
> https://godbolt.org/z/vx3xbGa41
I don't think those will be parsed as literal tokens by the preprocessor, but 
I'll check.



Comment at: 
clang-tools-extra/clang-tidy/modernize/IntegralLiteralExpressionMatcher.cpp:99
+
+  if (!Current->isLiteral() || isStringLiteral(Current->getKind()) ||
+  !isIntegralConstant(*Current)) {

aaron.ballman wrote:
> I know this is code moved from elsewhere, but I suppose we never considered 
> the odd edge case where a user does something like `"foo"[0]` as a really 
> awful integer constant. :-D
It's always possible to write crazy contorted code and have a check not 
recognize it.  I don't think it's worthwhile to spend time trying to handle 
torture cases unless we can find data that shows it's prevalent in real world 
code.

If I was doing a code review and saw this:
```
enum {
FOO = "foo"[0]
};
```
I'd flag that in a code review as bogus, whereas if I saw:
```
enum {
FOO = 'f'
};
```
That would be acceptable, which is why character literals are accepted as an 
integral literal initializer for an enum in this check.



Comment at: 
clang-tools-extra/clang-tidy/modernize/IntegralLiteralExpressionMatcher.cpp:185
+
+  if (Current->is(tok::TokenKind::question)) {
+if (!advance())

aaron.ballman wrote:
> There is GNU extension in this space: https://godbolt.org/z/PrWY3T6hY
Do you have a link for the extension?



Comment at: 
clang-tools-extra/clang-tidy/modernize/IntegralLiteralExpressionMatcher.cpp:204
+  return true;
+}
+

aaron.ballman wrote:
> Comma operator?
Remember that the use case here is identifying expressions that are 
initializers for an enum.  If you were doing a code review and you saw this:
```
enum {
FOO = (2, 3)
};
```
Would you be OK with that?  I wouldn't.  Clang even warns about it: 
https://godbolt.org/z/Y641cb8Y9

Therefore I deliberately left comma operator out of the grammar.



Comment at: 
clang-tools-extra/test/clang-tidy/checkers/modernize-macro-to-enum.cpp:26
+#define EXPR11 (1 + (2))
+#define EXPR12 ((1) + (2 + 0) + (1 * 1) + (1 / 1) + (1 | 1 ) + (1 & 1) + (1 << 
1) + (1 >> 1) + (1 % 2) + (1 ^ 1))
+// CHECK-MESSAGES: :[[@LINE-12]]:1: warning: replace macro with enum 
[modernize-macro-to-enum]

aaron.ballman wrote:
> Other interesting tests I'd expect we could convert into an enum (at least 
> theoretically):
> ```
> #define A 12 + +1
> #define B 12 - -1
> #define C (1, 2, 3)
> #define D 100 ? : 8
> #define E 100 ? 100 : 8
> #define F 'f'
> #define G "foo"[0]
> #define H 1 && 2
> #define I 1 || 2
> ```
Most of these (except comma operator and string subscript, see my comments 
earlier) are covered in the unit test for the matcher.  I'll add tests for 
these:

```
12 + +1
12 - -1
100 ? : 8
```



Comment at: clang-tools-extra/unittests/clang-tidy/ModernizeModuleTest.cpp:66
+{false, "1.23"},
+{false, "0x1p3"},
+{false, R"("string")"},

aaron.ballman wrote:
> ```
> 12i
> .0
> ```
> 
`.0` is already covered by the case `1.23`.  I'm not home brewing tokenization, 
but using the Lexer to do that.

`12i` I need to investigate to find out what the Lexer does.


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

https://reviews.llvm.org/D124500

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


[PATCH] D124211: Add __builtin_call_kcfi_unchecked

2022-04-29 Thread Sami Tolvanen via Phabricator via cfe-commits
samitolvanen updated this revision to Diff 426116.
samitolvanen marked 2 inline comments as done.
samitolvanen added a comment.

- Renamed the builtin.
- Addressed Nick's comments.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124211

Files:
  clang/docs/LanguageExtensions.rst
  clang/include/clang/AST/Expr.h
  clang/include/clang/AST/Stmt.h
  clang/include/clang/Basic/Builtins.def
  clang/include/clang/Basic/DiagnosticSemaKinds.td
  clang/lib/CodeGen/CGBuiltin.cpp
  clang/lib/CodeGen/CGExpr.cpp
  clang/lib/Sema/SemaChecking.cpp
  clang/test/CodeGen/builtin-kcfi-call-unchecked.cpp
  clang/test/SemaCXX/builtins.cpp

Index: clang/test/SemaCXX/builtins.cpp
===
--- clang/test/SemaCXX/builtins.cpp
+++ clang/test/SemaCXX/builtins.cpp
@@ -43,6 +43,35 @@
   S *ptmp = __builtin_addressof(S{}); // expected-error {{taking the address of a temporary}}
 }
 
+namespace kcfi_call_unchecked {
+int a(void) { return 0; }
+struct S {
+  int f(void) { return 1; }
+  static int g(void) { return 2; }
+} s;
+static int n;
+int &b(int (*p)(void)) {
+  n += p();
+  return n;
+}
+int (*p1)(void) = a;
+int (*p2)(void) = &S::g;
+int &(*p3)(int (*)(void)) = b;
+
+void test() {
+  __builtin_kcfi_call_unchecked(p1());
+  __builtin_kcfi_call_unchecked(p2());
+  __builtin_kcfi_call_unchecked(p3(p1));
+  __builtin_kcfi_call_unchecked(p1); // expected-error {{argument to __builtin_kcfi_call_unchecked must be an indirect call expression}}
+  __builtin_kcfi_call_unchecked(p1, p2); // expected-error {{too many arguments to function call, expected 1, have 2}}
+  __builtin_kcfi_call_unchecked(a());// expected-error {{argument to __builtin_kcfi_call_unchecked must be an indirect call expression}}
+  __builtin_kcfi_call_unchecked(s.f());  // expected-error {{argument to __builtin_kcfi_call_unchecked must be an indirect call expression}}
+  __builtin_kcfi_call_unchecked(S::g()); // expected-error {{argument to __builtin_kcfi_call_unchecked must be an indirect call expression}}
+  static_assert(__is_same(decltype(__builtin_kcfi_call_unchecked(p1())), int), "");
+  static_assert(__is_same(decltype(__builtin_kcfi_call_unchecked(p3(p1))), int &), "");
+}
+} // namespace kcfi_call_unchecked
+
 namespace function_start {
 void a(void) {}
 int n;
Index: clang/test/CodeGen/builtin-kcfi-call-unchecked.cpp
===
--- /dev/null
+++ clang/test/CodeGen/builtin-kcfi-call-unchecked.cpp
@@ -0,0 +1,42 @@
+// RUN: %clang_cc1 -triple x86_64-unknown-linux-gnu -emit-llvm -fsanitize=kcfi -o - %s | FileCheck %s
+
+#if !__has_builtin(__builtin_kcfi_call_unchecked)
+#error "missing __builtin_kcfi_call_unchecked"
+#endif
+
+// CHECK: define{{.*}} i32 @_Z1av(){{.*}} prefix i32 [[#%d,HASH1:]]
+int a(void) { return 0; }
+
+class A {
+public:
+  static void a();
+};
+
+// CHECK: define{{.*}} void @_ZN1A1aEv(){{.*}} prefix i32 [[#%d,HASH2:]]
+void A::a() {}
+
+void h(void) {
+  // CHECK: store ptr @_Z1av, ptr %
+  // CHECK: %[[#P1:]] = load ptr, ptr %
+  // CHECK: call void @llvm.kcfi.check(ptr %[[#P1]], i32 [[#HASH1]])
+  // CHECK: call{{.*}} i32 %[[#P1]]()
+  ({ a; })();
+
+  // CHECK: store ptr @_Z1av, ptr %
+  // CHECK: %[[#P2:]] = load ptr, ptr %
+  // CHECK-NOT: call void @llvm.kcfi.check
+  // CHECK: call{{.*}} i32 %[[#P2]]()
+  __builtin_kcfi_call_unchecked(({ a; })());
+
+  // CHECK: store ptr @_ZN1A1aEv, ptr %
+  // CHECK: %[[#P3:]] = load ptr, ptr %
+  // CHECK: call void @llvm.kcfi.check(ptr %[[#P3]], i32 [[#HASH2]])
+  // CHECK: call void %[[#P3]]()
+  ({ &A::a; })();
+
+  // CHECK: store ptr @_ZN1A1aEv, ptr %
+  // CHECK: %[[#P4:]] = load ptr, ptr %
+  // CHECK-NOT: call void @llvm.kcfi.check
+  // CHECK: call void %[[#P4]]()
+  __builtin_kcfi_call_unchecked(({ &A::a; })());
+}
Index: clang/lib/Sema/SemaChecking.cpp
===
--- clang/lib/Sema/SemaChecking.cpp
+++ clang/lib/Sema/SemaChecking.cpp
@@ -429,6 +429,39 @@
   return false;
 }
 
+static bool SemaBuiltinKCFICallUnchecked(Sema &S, CallExpr *BuiltinCall) {
+  if (checkArgCount(S, BuiltinCall, 1))
+return true;
+
+  auto *Call = dyn_cast(BuiltinCall->getArg(0));
+
+  if (!Call || !Call->getCallee()
+->IgnoreImpCasts()
+->getType()
+->isFunctionPointerType()) {
+S.Diag(BuiltinCall->getBeginLoc(), diag::err_kcfi_unchecked_argument)
+<< BuiltinCall->getSourceRange();
+return true;
+  }
+
+  QualType ReturnTy = Call->getCallReturnType(S.Context);
+  QualType BuiltinTy = S.Context.getFunctionType(
+  ReturnTy, {ReturnTy}, FunctionProtoType::ExtProtoInfo());
+
+  Expr *Builtin = S.ImpCastExprToType(
+   BuiltinCall->getCallee()->IgnoreImpCasts(),
+   S.Context.getPointerType(BuiltinTy), CK_BuiltinFnToFnPtr)
+   

[PATCH] D124688: [clangd] parse all make_unique-like functions in preamble

2022-04-29 Thread Tobias Ribizel via Phabricator via cfe-commits
upsj created this revision.
upsj added a reviewer: nridge.
Herald added subscribers: usaxena95, kadircet, arphaman.
Herald added a project: All.
upsj requested review of this revision.
Herald added subscribers: cfe-commits, MaskRay, ilya-biryukov.
Herald added a project: clang-tools-extra.

I am working on support for forwarding parameter names in make_unique-like 
functions, first for inlay hints, later maybe for signature help.
For that to work generically, I'd like to parse all of these functions in the 
preamble. Not sure how this impacts performance on large codebases though.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D124688

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


Index: clang-tools-extra/clangd/Preamble.cpp
===
--- clang-tools-extra/clangd/Preamble.cpp
+++ clang-tools-extra/clangd/Preamble.cpp
@@ -137,14 +137,42 @@
   }
 
   bool shouldSkipFunctionBody(Decl *D) override {
-// Generally we skip function bodies in preambles for speed.
-// We can make exceptions for functions that are cheap to parse and
-// instantiate, widely used, and valuable (e.g. commonly produce errors).
-if (const auto *FT = llvm::dyn_cast(D)) {
-  if (const auto *II = FT->getDeclName().getAsIdentifierInfo())
-// std::make_unique is trivial, and we diagnose bad constructor calls.
-if (II->isStr("make_unique") && FT->isInStdNamespace())
-  return false;
+// Find functions with variadic template arguments:
+// Any templated function...
+if (auto *FT = llvm::dyn_cast(D)) {
+  // ... with a template parameter pack...
+  if (FT->getTemplateParameters()->hasParameterPack()) {
+auto PackIt = std::find_if(
+FT->getInjectedTemplateArgs().begin(),
+FT->getInjectedTemplateArgs().end(), [](const auto &Arg) {
+  return Arg.getKind() == TemplateArgument::Pack;
+});
+assert(PackIt != FT->getInjectedTemplateArgs().end() &&
+   "Can't find parameter pack in argument list!");
+const auto &Pack = PackIt->getPackAsArray();
+
+// ... that is a type parameter pack...
+if (Pack.size() == 1 && Pack[0].getKind() == TemplateArgument::Type) {
+  const auto *PackType =
+  Pack[0].getAsType().getNonPackExpansionType().getTypePtr();
+  const auto *FD = FT->getAsFunction();
+  const auto NumParams = FD->getNumParams();
+  if (NumParams > 0) {
+const auto *LastParam = FD->getParamDecl(NumParams - 1);
+// ... with its type matching the last parameter (pack) of the
+// function (minus references)...
+if (LastParam->isParameterPack()) {
+  if (LastParam->getType()
+  .getNonPackExpansionType()
+  .getNonReferenceType()
+  .getTypePtr() == PackType) {
+// ... we need to parse the body
+return false;
+  }
+}
+  }
+}
+  }
 }
 return true;
   }


Index: clang-tools-extra/clangd/Preamble.cpp
===
--- clang-tools-extra/clangd/Preamble.cpp
+++ clang-tools-extra/clangd/Preamble.cpp
@@ -137,14 +137,42 @@
   }
 
   bool shouldSkipFunctionBody(Decl *D) override {
-// Generally we skip function bodies in preambles for speed.
-// We can make exceptions for functions that are cheap to parse and
-// instantiate, widely used, and valuable (e.g. commonly produce errors).
-if (const auto *FT = llvm::dyn_cast(D)) {
-  if (const auto *II = FT->getDeclName().getAsIdentifierInfo())
-// std::make_unique is trivial, and we diagnose bad constructor calls.
-if (II->isStr("make_unique") && FT->isInStdNamespace())
-  return false;
+// Find functions with variadic template arguments:
+// Any templated function...
+if (auto *FT = llvm::dyn_cast(D)) {
+  // ... with a template parameter pack...
+  if (FT->getTemplateParameters()->hasParameterPack()) {
+auto PackIt = std::find_if(
+FT->getInjectedTemplateArgs().begin(),
+FT->getInjectedTemplateArgs().end(), [](const auto &Arg) {
+  return Arg.getKind() == TemplateArgument::Pack;
+});
+assert(PackIt != FT->getInjectedTemplateArgs().end() &&
+   "Can't find parameter pack in argument list!");
+const auto &Pack = PackIt->getPackAsArray();
+
+// ... that is a type parameter pack...
+if (Pack.size() == 1 && Pack[0].getKind() == TemplateArgument::Type) {
+  const auto *PackType =
+  Pack[0].getAsType().getNonPackExpansionType().getTypePtr();
+  const auto *FD = FT->getAsFunction();
+  const auto NumParams = FD->getNumParams();
+  if (NumParams > 0) {
+const auto *LastParam 

[clang] 6f79700 - [randstruct] Automatically randomize a structure of function pointers

2022-04-29 Thread Bill Wendling via cfe-commits

Author: Bill Wendling
Date: 2022-04-29T11:05:09-07:00
New Revision: 6f79700830292d86afec5f3cf5143b00e6f3f1fd

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

LOG: [randstruct] Automatically randomize a structure of function pointers

Strutures of function pointers are a good surface area for attacks. We
should therefore randomize them unless explicitly told not to.

Reviewed By: aaron.ballman, MaskRay

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

Added: 


Modified: 
clang/lib/Sema/SemaDecl.cpp
clang/unittests/AST/RandstructTest.cpp

Removed: 




diff  --git a/clang/lib/Sema/SemaDecl.cpp b/clang/lib/Sema/SemaDecl.cpp
index a13a34a9fa59..da6d35ca98a4 100644
--- a/clang/lib/Sema/SemaDecl.cpp
+++ b/clang/lib/Sema/SemaDecl.cpp
@@ -18057,8 +18057,25 @@ void Sema::ActOnFields(Scope *S, SourceLocation 
RecLoc, Decl *EnclosingDecl,
 // Handle attributes before checking the layout.
 ProcessDeclAttributeList(S, Record, Attrs);
 
-// Maybe randomize the record's decls.
-if (!getLangOpts().CPlusPlus && Record->hasAttr() &&
+// Check to see if a FieldDecl is a pointer to a function.
+auto IsFunctionPointer = [&](const Decl *D) {
+  const FieldDecl *FD = dyn_cast(D);
+  if (!FD)
+return false;
+  QualType FieldType = FD->getType().getDesugaredType(Context);
+  if (isa(FieldType)) {
+QualType PointeeType = cast(FieldType)->getPointeeType();
+return PointeeType.getDesugaredType(Context)->isFunctionType();
+  }
+  return false;
+};
+
+// Maybe randomize the record's decls. We automatically randomize a record
+// of function pointers, unless it has the "no_randomize_layout" attribute.
+if (!getLangOpts().CPlusPlus &&
+(Record->hasAttr() ||
+ (!Record->hasAttr() &&
+  llvm::all_of(Record->decls(), IsFunctionPointer))) &&
 !Record->isUnion() && !getLangOpts().RandstructSeed.empty() &&
 !Record->isRandomized()) {
   SmallVector NewDeclOrdering;

diff  --git a/clang/unittests/AST/RandstructTest.cpp 
b/clang/unittests/AST/RandstructTest.cpp
index 394900d8f6eb..c22d866ed4fa 100644
--- a/clang/unittests/AST/RandstructTest.cpp
+++ b/clang/unittests/AST/RandstructTest.cpp
@@ -583,5 +583,49 @@ TEST(RANDSTRUCT_TEST, AnonymousStructsAndUnionsReferenced) 
{
   EXPECT_EQ(OriginalDeclCount, declCount(RD));
 }
 
+TEST(RANDSTRUCT_TEST, AutoRandomizeStructOfFunctionPointers) {
+  const std::unique_ptr AST = makeAST(R"c(
+typedef void (*func_ptr)();
+
+struct test {
+  func_ptr a;
+  func_ptr b;
+  func_ptr c;
+  func_ptr d;
+  func_ptr e;
+  func_ptr f;
+  func_ptr g;
+};
+  )c");
+
+  EXPECT_FALSE(AST->getDiagnostics().hasErrorOccurred());
+
+  const RecordDecl *RD = getRecordDeclFromAST(AST->getASTContext(), "test");
+
+  EXPECT_TRUE(RD->isRandomized());
+}
+
+TEST(RANDSTRUCT_TEST, DisableAutoRandomizeStructOfFunctionPointers) {
+  const std::unique_ptr AST = makeAST(R"c(
+typedef void (*func_ptr)();
+
+struct test {
+  func_ptr a;
+  func_ptr b;
+  func_ptr c;
+  func_ptr d;
+  func_ptr e;
+  func_ptr f;
+  func_ptr g;
+} __attribute__((no_randomize_layout));
+  )c");
+
+  EXPECT_FALSE(AST->getDiagnostics().hasErrorOccurred());
+
+  const RecordDecl *RD = getRecordDeclFromAST(AST->getASTContext(), "test");
+
+  EXPECT_FALSE(RD->isRandomized());
+}
+
 } // namespace ast_matchers
 } // namespace clang



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


[PATCH] D123544: [randstruct] Automatically randomize a structure of function pointers

2022-04-29 Thread Bill Wendling via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG6f7970083029: [randstruct] Automatically randomize a 
structure of function pointers (authored by void).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D123544

Files:
  clang/lib/Sema/SemaDecl.cpp
  clang/unittests/AST/RandstructTest.cpp


Index: clang/unittests/AST/RandstructTest.cpp
===
--- clang/unittests/AST/RandstructTest.cpp
+++ clang/unittests/AST/RandstructTest.cpp
@@ -583,5 +583,49 @@
   EXPECT_EQ(OriginalDeclCount, declCount(RD));
 }
 
+TEST(RANDSTRUCT_TEST, AutoRandomizeStructOfFunctionPointers) {
+  const std::unique_ptr AST = makeAST(R"c(
+typedef void (*func_ptr)();
+
+struct test {
+  func_ptr a;
+  func_ptr b;
+  func_ptr c;
+  func_ptr d;
+  func_ptr e;
+  func_ptr f;
+  func_ptr g;
+};
+  )c");
+
+  EXPECT_FALSE(AST->getDiagnostics().hasErrorOccurred());
+
+  const RecordDecl *RD = getRecordDeclFromAST(AST->getASTContext(), "test");
+
+  EXPECT_TRUE(RD->isRandomized());
+}
+
+TEST(RANDSTRUCT_TEST, DisableAutoRandomizeStructOfFunctionPointers) {
+  const std::unique_ptr AST = makeAST(R"c(
+typedef void (*func_ptr)();
+
+struct test {
+  func_ptr a;
+  func_ptr b;
+  func_ptr c;
+  func_ptr d;
+  func_ptr e;
+  func_ptr f;
+  func_ptr g;
+} __attribute__((no_randomize_layout));
+  )c");
+
+  EXPECT_FALSE(AST->getDiagnostics().hasErrorOccurred());
+
+  const RecordDecl *RD = getRecordDeclFromAST(AST->getASTContext(), "test");
+
+  EXPECT_FALSE(RD->isRandomized());
+}
+
 } // namespace ast_matchers
 } // namespace clang
Index: clang/lib/Sema/SemaDecl.cpp
===
--- clang/lib/Sema/SemaDecl.cpp
+++ clang/lib/Sema/SemaDecl.cpp
@@ -18057,8 +18057,25 @@
 // Handle attributes before checking the layout.
 ProcessDeclAttributeList(S, Record, Attrs);
 
-// Maybe randomize the record's decls.
-if (!getLangOpts().CPlusPlus && Record->hasAttr() &&
+// Check to see if a FieldDecl is a pointer to a function.
+auto IsFunctionPointer = [&](const Decl *D) {
+  const FieldDecl *FD = dyn_cast(D);
+  if (!FD)
+return false;
+  QualType FieldType = FD->getType().getDesugaredType(Context);
+  if (isa(FieldType)) {
+QualType PointeeType = cast(FieldType)->getPointeeType();
+return PointeeType.getDesugaredType(Context)->isFunctionType();
+  }
+  return false;
+};
+
+// Maybe randomize the record's decls. We automatically randomize a record
+// of function pointers, unless it has the "no_randomize_layout" attribute.
+if (!getLangOpts().CPlusPlus &&
+(Record->hasAttr() ||
+ (!Record->hasAttr() &&
+  llvm::all_of(Record->decls(), IsFunctionPointer))) &&
 !Record->isUnion() && !getLangOpts().RandstructSeed.empty() &&
 !Record->isRandomized()) {
   SmallVector NewDeclOrdering;


Index: clang/unittests/AST/RandstructTest.cpp
===
--- clang/unittests/AST/RandstructTest.cpp
+++ clang/unittests/AST/RandstructTest.cpp
@@ -583,5 +583,49 @@
   EXPECT_EQ(OriginalDeclCount, declCount(RD));
 }
 
+TEST(RANDSTRUCT_TEST, AutoRandomizeStructOfFunctionPointers) {
+  const std::unique_ptr AST = makeAST(R"c(
+typedef void (*func_ptr)();
+
+struct test {
+  func_ptr a;
+  func_ptr b;
+  func_ptr c;
+  func_ptr d;
+  func_ptr e;
+  func_ptr f;
+  func_ptr g;
+};
+  )c");
+
+  EXPECT_FALSE(AST->getDiagnostics().hasErrorOccurred());
+
+  const RecordDecl *RD = getRecordDeclFromAST(AST->getASTContext(), "test");
+
+  EXPECT_TRUE(RD->isRandomized());
+}
+
+TEST(RANDSTRUCT_TEST, DisableAutoRandomizeStructOfFunctionPointers) {
+  const std::unique_ptr AST = makeAST(R"c(
+typedef void (*func_ptr)();
+
+struct test {
+  func_ptr a;
+  func_ptr b;
+  func_ptr c;
+  func_ptr d;
+  func_ptr e;
+  func_ptr f;
+  func_ptr g;
+} __attribute__((no_randomize_layout));
+  )c");
+
+  EXPECT_FALSE(AST->getDiagnostics().hasErrorOccurred());
+
+  const RecordDecl *RD = getRecordDeclFromAST(AST->getASTContext(), "test");
+
+  EXPECT_FALSE(RD->isRandomized());
+}
+
 } // namespace ast_matchers
 } // namespace clang
Index: clang/lib/Sema/SemaDecl.cpp
===
--- clang/lib/Sema/SemaDecl.cpp
+++ clang/lib/Sema/SemaDecl.cpp
@@ -18057,8 +18057,25 @@
 // Handle attributes before checking the layout.
 ProcessDeclAttributeList(S, Record, Attrs);
 
-// Maybe randomize the record's decls.
-if (!getLangOpts().CPlusPlus && Record->hasAttr() &&
+// Check to see if a FieldDecl is a pointer to a function.
+auto IsFunctionPointer = [&](const Decl *D

  1   2   >