[clang] 307e853 - Add nomerge function attribute to clang

2020-05-21 Thread Zequan Wu via cfe-commits

Author: Zequan Wu
Date: 2020-05-21T15:28:27-07:00
New Revision: 307e85395485e1eff9533b2d7952b16f33ceae38

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

LOG: Add nomerge function attribute to clang

Added: 
clang/test/CodeGen/attr-nomerge.cpp
clang/test/Sema/attr-nomerge.cpp

Modified: 
clang/include/clang/Basic/Attr.td
clang/include/clang/Basic/AttrDocs.td
clang/include/clang/Basic/DiagnosticSemaKinds.td
clang/lib/CodeGen/CGCall.cpp
clang/lib/CodeGen/CGStmt.cpp
clang/lib/CodeGen/CodeGenFunction.h
clang/lib/Sema/SemaStmtAttr.cpp

Removed: 




diff  --git a/clang/include/clang/Basic/Attr.td 
b/clang/include/clang/Basic/Attr.td
index 833b862cfb5f..a691e2332ff7 100644
--- a/clang/include/clang/Basic/Attr.td
+++ b/clang/include/clang/Basic/Attr.td
@@ -1275,6 +1275,11 @@ def FallThrough : StmtAttr {
   let Documentation = [FallthroughDocs];
 }
 
+def NoMerge : StmtAttr {
+  let Spellings = [Clang<"nomerge">];
+  let Documentation = [NoMergeDocs];
+}
+
 def FastCall : DeclOrTypeAttr {
   let Spellings = [GCC<"fastcall">, Keyword<"__fastcall">,
Keyword<"_fastcall">];

diff  --git a/clang/include/clang/Basic/AttrDocs.td 
b/clang/include/clang/Basic/AttrDocs.td
index e3308cd74874..5222c92c42a0 100644
--- a/clang/include/clang/Basic/AttrDocs.td
+++ b/clang/include/clang/Basic/AttrDocs.td
@@ -350,6 +350,20 @@ that appears to be capable of returning to its caller.
   }];
 }
 
+def NoMergeDocs : Documentation {
+  let Category = DocCatFunction;
+  let Content = [{
+If a statement is marked ``nomerge`` and contains call experessions, those call
+expressions inside the statement will not be merged during optimization. This 
+attribute can be used to prevent the optimizer from obscuring the source
+location of certain calls. For example, it will prevent tail merging otherwise
+identical code sequences that raise an exception or terminate the program. Tail
+merging normally reduces the precision of source location information, making
+stack traces less useful for debugging. This attribute gives the user control
+over the tradeoff between code size and debug information precision.
+  }];
+}
+
 def AssertCapabilityDocs : Documentation {
   let Category = DocCatFunction;
   let Heading = "assert_capability, assert_shared_capability";

diff  --git a/clang/include/clang/Basic/DiagnosticSemaKinds.td 
b/clang/include/clang/Basic/DiagnosticSemaKinds.td
index d415802916b6..d387ad79596c 100644
--- a/clang/include/clang/Basic/DiagnosticSemaKinds.td
+++ b/clang/include/clang/Basic/DiagnosticSemaKinds.td
@@ -2762,6 +2762,10 @@ def warn_auto_var_is_id : Warning<
   InGroup>;
 
 // Attributes
+def warn_nomerge_attribute_ignored_in_stmt: Warning<
+  "%0 attribute is ignored because there exists no call expression inside the "
+  "statement">, 
+  InGroup;
 def err_nsobject_attribute : Error<
   "'NSObject' attribute is for pointer types only">;
 def err_attributes_are_not_compatible : Error<

diff  --git a/clang/lib/CodeGen/CGCall.cpp b/clang/lib/CodeGen/CGCall.cpp
index 6831f8248225..c324b9fa501e 100644
--- a/clang/lib/CodeGen/CGCall.cpp
+++ b/clang/lib/CodeGen/CGCall.cpp
@@ -4822,6 +4822,12 @@ RValue CodeGenFunction::EmitCall(const CGFunctionInfo 
&CallInfo,
 Attrs.addAttribute(getLLVMContext(), 
llvm::AttributeList::FunctionIndex,
llvm::Attribute::StrictFP);
 
+  // Add call-site nomerge attribute if exists.
+  if (InNoMergeAttributedStmt)
+Attrs =
+  Attrs.addAttribute(getLLVMContext(), llvm::AttributeList::FunctionIndex,
+ llvm::Attribute::NoMerge);
+
   // Apply some call-site-specific attributes.
   // TODO: work this into building the attribute set.
 

diff  --git a/clang/lib/CodeGen/CGStmt.cpp b/clang/lib/CodeGen/CGStmt.cpp
index ceecbd4dc137..cd2e3b424233 100644
--- a/clang/lib/CodeGen/CGStmt.cpp
+++ b/clang/lib/CodeGen/CGStmt.cpp
@@ -25,6 +25,7 @@
 #include "llvm/IR/InlineAsm.h"
 #include "llvm/IR/Intrinsics.h"
 #include "llvm/IR/MDBuilder.h"
+#include "llvm/Support/SaveAndRestore.h"
 
 using namespace clang;
 using namespace CodeGen;
@@ -608,6 +609,13 @@ void CodeGenFunction::EmitLabelStmt(const LabelStmt &S) {
 }
 
 void CodeGenFunction::EmitAttributedStmt(const AttributedStmt &S) {
+  bool nomerge = false;
+  for (const auto *A: S.getAttrs())
+if (A->getKind() == attr::NoMerge) {
+  nomerge = true;
+  break;
+}
+  SaveAndRestore save_nomerge(InNoMergeAttributedStmt, nomerge);
   EmitStmt(S.getSubStmt(), S.getAttrs());
 }
 

diff  --git a/clang/lib/CodeGen/CodeGenFunction.h 
b/clang/lib/CodeGen/CodeGenFunction.h
index 731317aac0dc..2b5871dbb116 100644
--- a/clang/lib/CodeGen/CodeGenFunction.h
+++ b/clang/lib/CodeGen/CodeGenFunction.h
@@ -595,6 +595,9 @@ class CodeG

[clang] b0a0f01 - Revert "Add nomerge function attribute to clang"

2020-05-21 Thread Zequan Wu via cfe-commits

Author: Zequan Wu
Date: 2020-05-21T16:13:18-07:00
New Revision: b0a0f01bc175b4c444052f871a89421889f8b5ce

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

LOG: Revert "Add nomerge function attribute to clang"

This reverts commit 307e85395485e1eff9533b2d7952b16f33ceae38.

Added: 


Modified: 
clang/include/clang/Basic/Attr.td
clang/include/clang/Basic/AttrDocs.td
clang/include/clang/Basic/DiagnosticSemaKinds.td
clang/lib/CodeGen/CGCall.cpp
clang/lib/CodeGen/CGStmt.cpp
clang/lib/CodeGen/CodeGenFunction.h
clang/lib/Sema/SemaStmtAttr.cpp

Removed: 
clang/test/CodeGen/attr-nomerge.cpp
clang/test/Sema/attr-nomerge.cpp



diff  --git a/clang/include/clang/Basic/Attr.td 
b/clang/include/clang/Basic/Attr.td
index a691e2332ff7..833b862cfb5f 100644
--- a/clang/include/clang/Basic/Attr.td
+++ b/clang/include/clang/Basic/Attr.td
@@ -1275,11 +1275,6 @@ def FallThrough : StmtAttr {
   let Documentation = [FallthroughDocs];
 }
 
-def NoMerge : StmtAttr {
-  let Spellings = [Clang<"nomerge">];
-  let Documentation = [NoMergeDocs];
-}
-
 def FastCall : DeclOrTypeAttr {
   let Spellings = [GCC<"fastcall">, Keyword<"__fastcall">,
Keyword<"_fastcall">];

diff  --git a/clang/include/clang/Basic/AttrDocs.td 
b/clang/include/clang/Basic/AttrDocs.td
index 5222c92c42a0..e3308cd74874 100644
--- a/clang/include/clang/Basic/AttrDocs.td
+++ b/clang/include/clang/Basic/AttrDocs.td
@@ -350,20 +350,6 @@ that appears to be capable of returning to its caller.
   }];
 }
 
-def NoMergeDocs : Documentation {
-  let Category = DocCatFunction;
-  let Content = [{
-If a statement is marked ``nomerge`` and contains call experessions, those call
-expressions inside the statement will not be merged during optimization. This 
-attribute can be used to prevent the optimizer from obscuring the source
-location of certain calls. For example, it will prevent tail merging otherwise
-identical code sequences that raise an exception or terminate the program. Tail
-merging normally reduces the precision of source location information, making
-stack traces less useful for debugging. This attribute gives the user control
-over the tradeoff between code size and debug information precision.
-  }];
-}
-
 def AssertCapabilityDocs : Documentation {
   let Category = DocCatFunction;
   let Heading = "assert_capability, assert_shared_capability";

diff  --git a/clang/include/clang/Basic/DiagnosticSemaKinds.td 
b/clang/include/clang/Basic/DiagnosticSemaKinds.td
index d387ad79596c..d415802916b6 100644
--- a/clang/include/clang/Basic/DiagnosticSemaKinds.td
+++ b/clang/include/clang/Basic/DiagnosticSemaKinds.td
@@ -2762,10 +2762,6 @@ def warn_auto_var_is_id : Warning<
   InGroup>;
 
 // Attributes
-def warn_nomerge_attribute_ignored_in_stmt: Warning<
-  "%0 attribute is ignored because there exists no call expression inside the "
-  "statement">, 
-  InGroup;
 def err_nsobject_attribute : Error<
   "'NSObject' attribute is for pointer types only">;
 def err_attributes_are_not_compatible : Error<

diff  --git a/clang/lib/CodeGen/CGCall.cpp b/clang/lib/CodeGen/CGCall.cpp
index c324b9fa501e..6831f8248225 100644
--- a/clang/lib/CodeGen/CGCall.cpp
+++ b/clang/lib/CodeGen/CGCall.cpp
@@ -4822,12 +4822,6 @@ RValue CodeGenFunction::EmitCall(const CGFunctionInfo 
&CallInfo,
 Attrs.addAttribute(getLLVMContext(), 
llvm::AttributeList::FunctionIndex,
llvm::Attribute::StrictFP);
 
-  // Add call-site nomerge attribute if exists.
-  if (InNoMergeAttributedStmt)
-Attrs =
-  Attrs.addAttribute(getLLVMContext(), llvm::AttributeList::FunctionIndex,
- llvm::Attribute::NoMerge);
-
   // Apply some call-site-specific attributes.
   // TODO: work this into building the attribute set.
 

diff  --git a/clang/lib/CodeGen/CGStmt.cpp b/clang/lib/CodeGen/CGStmt.cpp
index cd2e3b424233..ceecbd4dc137 100644
--- a/clang/lib/CodeGen/CGStmt.cpp
+++ b/clang/lib/CodeGen/CGStmt.cpp
@@ -25,7 +25,6 @@
 #include "llvm/IR/InlineAsm.h"
 #include "llvm/IR/Intrinsics.h"
 #include "llvm/IR/MDBuilder.h"
-#include "llvm/Support/SaveAndRestore.h"
 
 using namespace clang;
 using namespace CodeGen;
@@ -609,13 +608,6 @@ void CodeGenFunction::EmitLabelStmt(const LabelStmt &S) {
 }
 
 void CodeGenFunction::EmitAttributedStmt(const AttributedStmt &S) {
-  bool nomerge = false;
-  for (const auto *A: S.getAttrs())
-if (A->getKind() == attr::NoMerge) {
-  nomerge = true;
-  break;
-}
-  SaveAndRestore save_nomerge(InNoMergeAttributedStmt, nomerge);
   EmitStmt(S.getSubStmt(), S.getAttrs());
 }
 

diff  --git a/clang/lib/CodeGen/CodeGenFunction.h 
b/clang/lib/CodeGen/CodeGenFunction.h
index 2b5871dbb116..731317aac0dc 100644
--- a/clang/lib/CodeGen/CodeGenFunction.h
+

[clang] e36076e - [clang] Add nomerge function attribute to clang

2020-05-21 Thread Zequan Wu via cfe-commits

Author: Zequan Wu
Date: 2020-05-21T17:07:39-07:00
New Revision: e36076ee3a2ebc6013372d9b71e6bb09e8612366

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

LOG: [clang] Add nomerge function attribute to clang
Differential Revision: https://reviews.llvm.org/D79121

Added: 
clang/test/CodeGen/attr-nomerge.cpp
clang/test/Sema/attr-nomerge.cpp

Modified: 
clang/include/clang/Basic/Attr.td
clang/include/clang/Basic/AttrDocs.td
clang/include/clang/Basic/DiagnosticSemaKinds.td
clang/lib/CodeGen/CGCall.cpp
clang/lib/CodeGen/CGStmt.cpp
clang/lib/CodeGen/CodeGenFunction.h
clang/lib/Sema/SemaStmtAttr.cpp

Removed: 




diff  --git a/clang/include/clang/Basic/Attr.td 
b/clang/include/clang/Basic/Attr.td
index 833b862cfb5f..a691e2332ff7 100644
--- a/clang/include/clang/Basic/Attr.td
+++ b/clang/include/clang/Basic/Attr.td
@@ -1275,6 +1275,11 @@ def FallThrough : StmtAttr {
   let Documentation = [FallthroughDocs];
 }
 
+def NoMerge : StmtAttr {
+  let Spellings = [Clang<"nomerge">];
+  let Documentation = [NoMergeDocs];
+}
+
 def FastCall : DeclOrTypeAttr {
   let Spellings = [GCC<"fastcall">, Keyword<"__fastcall">,
Keyword<"_fastcall">];

diff  --git a/clang/include/clang/Basic/AttrDocs.td 
b/clang/include/clang/Basic/AttrDocs.td
index e3308cd74874..5222c92c42a0 100644
--- a/clang/include/clang/Basic/AttrDocs.td
+++ b/clang/include/clang/Basic/AttrDocs.td
@@ -350,6 +350,20 @@ that appears to be capable of returning to its caller.
   }];
 }
 
+def NoMergeDocs : Documentation {
+  let Category = DocCatFunction;
+  let Content = [{
+If a statement is marked ``nomerge`` and contains call experessions, those call
+expressions inside the statement will not be merged during optimization. This 
+attribute can be used to prevent the optimizer from obscuring the source
+location of certain calls. For example, it will prevent tail merging otherwise
+identical code sequences that raise an exception or terminate the program. Tail
+merging normally reduces the precision of source location information, making
+stack traces less useful for debugging. This attribute gives the user control
+over the tradeoff between code size and debug information precision.
+  }];
+}
+
 def AssertCapabilityDocs : Documentation {
   let Category = DocCatFunction;
   let Heading = "assert_capability, assert_shared_capability";

diff  --git a/clang/include/clang/Basic/DiagnosticSemaKinds.td 
b/clang/include/clang/Basic/DiagnosticSemaKinds.td
index d415802916b6..845e329033c3 100644
--- a/clang/include/clang/Basic/DiagnosticSemaKinds.td
+++ b/clang/include/clang/Basic/DiagnosticSemaKinds.td
@@ -2762,6 +2762,10 @@ def warn_auto_var_is_id : Warning<
   InGroup>;
 
 // Attributes
+def warn_nomerge_attribute_ignored_in_stmt: Warning<
+  "%0 attribute is ignored because there exists no call expression inside the "
+  "statement">,
+  InGroup;
 def err_nsobject_attribute : Error<
   "'NSObject' attribute is for pointer types only">;
 def err_attributes_are_not_compatible : Error<

diff  --git a/clang/lib/CodeGen/CGCall.cpp b/clang/lib/CodeGen/CGCall.cpp
index 6831f8248225..c324b9fa501e 100644
--- a/clang/lib/CodeGen/CGCall.cpp
+++ b/clang/lib/CodeGen/CGCall.cpp
@@ -4822,6 +4822,12 @@ RValue CodeGenFunction::EmitCall(const CGFunctionInfo 
&CallInfo,
 Attrs.addAttribute(getLLVMContext(), 
llvm::AttributeList::FunctionIndex,
llvm::Attribute::StrictFP);
 
+  // Add call-site nomerge attribute if exists.
+  if (InNoMergeAttributedStmt)
+Attrs =
+  Attrs.addAttribute(getLLVMContext(), llvm::AttributeList::FunctionIndex,
+ llvm::Attribute::NoMerge);
+
   // Apply some call-site-specific attributes.
   // TODO: work this into building the attribute set.
 

diff  --git a/clang/lib/CodeGen/CGStmt.cpp b/clang/lib/CodeGen/CGStmt.cpp
index ceecbd4dc137..3559e77fc764 100644
--- a/clang/lib/CodeGen/CGStmt.cpp
+++ b/clang/lib/CodeGen/CGStmt.cpp
@@ -25,6 +25,7 @@
 #include "llvm/IR/InlineAsm.h"
 #include "llvm/IR/Intrinsics.h"
 #include "llvm/IR/MDBuilder.h"
+#include "llvm/Support/SaveAndRestore.h"
 
 using namespace clang;
 using namespace CodeGen;
@@ -608,6 +609,13 @@ void CodeGenFunction::EmitLabelStmt(const LabelStmt &S) {
 }
 
 void CodeGenFunction::EmitAttributedStmt(const AttributedStmt &S) {
+  bool nomerge = false;
+  for (const auto *A : S.getAttrs())
+if (A->getKind() == attr::NoMerge) {
+  nomerge = true;
+  break;
+}
+  SaveAndRestore save_nomerge(InNoMergeAttributedStmt, nomerge);
   EmitStmt(S.getSubStmt(), S.getAttrs());
 }
 

diff  --git a/clang/lib/CodeGen/CodeGenFunction.h 
b/clang/lib/CodeGen/CodeGenFunction.h
index 731317aac0dc..2b5871dbb116 100644
--- a/clang/lib/CodeGen/CodeGenFunction.h
+++ b/clan

[clang] 170b686 - [Clang] Add a new warning to warn when passing uninitialized variables as const reference parameters to a function

2020-06-02 Thread Zequan Wu via cfe-commits

Author: Zequan Wu
Date: 2020-06-02T10:21:02-07:00
New Revision: 170b6869b563dd3393d99f3e03d389b9058d5f24

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

LOG: [Clang] Add a new warning to warn when passing uninitialized variables as 
const reference parameters to a function

Summary:
Add a new warning -Wuninitialized-const-reference as a subgroup of 
-Wuninitialized to address a bug filed here: 
https://bugs.llvm.org/show_bug.cgi?id=45624

This warning is controlled by -Wuninitialized and can be disabled by 
-Wno-uninitialized-const-reference.
The warning is diagnosed when passing uninitialized variables as const 
reference parameters to a function.

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

Added: 
clang/test/SemaCXX/warn-uninitialized-const-reference.cpp

Modified: 
clang/include/clang/Analysis/Analyses/UninitializedValues.h
clang/include/clang/Basic/DiagnosticGroups.td
clang/include/clang/Basic/DiagnosticSemaKinds.td
clang/lib/Analysis/UninitializedValues.cpp
clang/lib/Sema/AnalysisBasedWarnings.cpp
clang/test/Misc/warning-wall.c
clang/test/SemaCXX/uninit-variables.cpp
clang/test/SemaCXX/uninitialized.cpp

Removed: 




diff  --git a/clang/include/clang/Analysis/Analyses/UninitializedValues.h 
b/clang/include/clang/Analysis/Analyses/UninitializedValues.h
index 479be1fec048..a2b37deddcec 100644
--- a/clang/include/clang/Analysis/Analyses/UninitializedValues.h
+++ b/clang/include/clang/Analysis/Analyses/UninitializedValues.h
@@ -110,6 +110,10 @@ class UninitVariablesHandler {
   virtual void handleUseOfUninitVariable(const VarDecl *vd,
  const UninitUse &use) {}
 
+  /// Called when the uninitialized variable is used as const refernce 
argument.
+  virtual void handleConstRefUseOfUninitVariable(const VarDecl *vd,
+ const UninitUse &use) {}
+
   /// Called when the uninitialized variable analysis detects the
   /// idiom 'int x = x'.  All other uses of 'x' within the initializer
   /// are handled by handleUseOfUninitVariable.

diff  --git a/clang/include/clang/Basic/DiagnosticGroups.td 
b/clang/include/clang/Basic/DiagnosticGroups.td
index 3f0521615a5e..451310a8c3a6 100644
--- a/clang/include/clang/Basic/DiagnosticGroups.td
+++ b/clang/include/clang/Basic/DiagnosticGroups.td
@@ -624,8 +624,10 @@ def Unicode  : DiagGroup<"unicode">;
 def UninitializedMaybe : DiagGroup<"conditional-uninitialized">;
 def UninitializedSometimes : DiagGroup<"sometimes-uninitialized">;
 def UninitializedStaticSelfInit : DiagGroup<"static-self-init">;
+def UninitializedConstReference : DiagGroup<"uninitialized-const-reference">;
 def Uninitialized  : DiagGroup<"uninitialized", [UninitializedSometimes,
- UninitializedStaticSelfInit]>;
+ UninitializedStaticSelfInit,
+ UninitializedConstReference]>;
 def IgnoredPragmaIntrinsic : DiagGroup<"ignored-pragma-intrinsic">;
 // #pragma optimize is often used to avoid to work around MSVC codegen bugs or
 // to disable inlining. It's not completely clear what alternative to suggest

diff  --git a/clang/include/clang/Basic/DiagnosticSemaKinds.td 
b/clang/include/clang/Basic/DiagnosticSemaKinds.td
index dd45b21724d2..5138b69eee74 100644
--- a/clang/include/clang/Basic/DiagnosticSemaKinds.td
+++ b/clang/include/clang/Basic/DiagnosticSemaKinds.td
@@ -2111,6 +2111,10 @@ def err_list_init_in_parens : Error<
   "cannot initialize %select{non-class|reference}0 type %1 with a "
   "parenthesized initializer list">;
 
+def warn_uninit_const_reference : Warning<
+  "variable %0 is uninitialized when passed as a const reference argument "
+  "here">, InGroup, DefaultIgnore;
+
 def warn_unsequenced_mod_mod : Warning<
   "multiple unsequenced modifications to %0">, InGroup;
 def warn_unsequenced_mod_use : Warning<

diff  --git a/clang/lib/Analysis/UninitializedValues.cpp 
b/clang/lib/Analysis/UninitializedValues.cpp
index ba64fbb81884..facda6ee616e 100644
--- a/clang/lib/Analysis/UninitializedValues.cpp
+++ b/clang/lib/Analysis/UninitializedValues.cpp
@@ -268,6 +268,7 @@ class ClassifyRefs : public StmtVisitor {
 Init,
 Use,
 SelfInit,
+ConstRefUse,
 Ignore
   };
 
@@ -413,14 +414,16 @@ void ClassifyRefs::VisitCallExpr(CallExpr *CE) {
 return;
   }
 
-  // If a value is passed by const pointer or by const reference to a function,
+  // If a value is passed by const pointer to a function,
   // we should not assume that it is initialized by the call, and we
   // conservatively do not assume that it is used.
+  // If a value is passed by const reference to a function,
+  // it should

[clang] abd4515 - [Coverage] Add comment to skipped regions

2020-07-21 Thread Zequan Wu via cfe-commits

Author: Zequan Wu
Date: 2020-07-21T17:34:18-07:00
New Revision: abd45154bdb6b76c5b480455eacc8c75b08242aa

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

LOG: [Coverage] Add comment to skipped regions

Bug filled here: https://bugs.llvm.org/show_bug.cgi?id=45757.
Add comment to skipped regions so we don't track execution count for lines 
containing only comments.

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

Added: 
compiler-rt/test/profile/coverage_comments.cpp

Modified: 
clang/include/clang/Lex/Preprocessor.h
clang/lib/CodeGen/CodeGenAction.cpp
clang/lib/CodeGen/CoverageMappingGen.cpp
clang/lib/CodeGen/CoverageMappingGen.h
clang/lib/Lex/Preprocessor.cpp
clang/test/CoverageMapping/break.c
clang/test/CoverageMapping/builtinmacro.c
clang/test/CoverageMapping/classtemplate.cpp
clang/test/CoverageMapping/comment-in-macro.c
clang/test/CoverageMapping/continue.c
clang/test/CoverageMapping/coroutine.cpp
clang/test/CoverageMapping/deferred-region.cpp
clang/test/CoverageMapping/if.cpp
clang/test/CoverageMapping/includehell.cpp
clang/test/CoverageMapping/label.cpp
clang/test/CoverageMapping/logical.cpp
clang/test/CoverageMapping/loops.cpp
clang/test/CoverageMapping/macro-expressions.cpp
clang/test/CoverageMapping/macroparams2.c
clang/test/CoverageMapping/macros.c
clang/test/CoverageMapping/macroscopes.cpp
clang/test/CoverageMapping/moremacros.c
clang/test/CoverageMapping/objc.m
clang/test/CoverageMapping/pr32679.cpp
clang/test/CoverageMapping/preprocessor.c
clang/test/CoverageMapping/return.c
clang/test/CoverageMapping/switch.cpp
clang/test/CoverageMapping/switchmacro.c
clang/test/CoverageMapping/test.c
clang/test/CoverageMapping/trycatch.cpp
clang/test/CoverageMapping/unreachable-macro.c
clang/test/CoverageMapping/while.c
clang/test/lit.cfg.py
compiler-rt/test/profile/Inputs/instrprof-comdat.h

Removed: 




diff  --git a/clang/include/clang/Lex/Preprocessor.h 
b/clang/include/clang/Lex/Preprocessor.h
index 5cd017fa925f..b0dd363555ab 100644
--- a/clang/include/clang/Lex/Preprocessor.h
+++ b/clang/include/clang/Lex/Preprocessor.h
@@ -419,6 +419,9 @@ class Preprocessor {
   /// The number of (LexLevel 0) preprocessor tokens.
   unsigned TokenCount = 0;
 
+  /// Preprocess every token regardless of LexLevel.
+  bool PreprocessToken = false;
+
   /// The maximum number of (LexLevel 0) tokens before issuing a -Wmax-tokens
   /// warning, or zero for unlimited.
   unsigned MaxTokens = 0;
@@ -1038,6 +1041,8 @@ class Preprocessor {
 OnToken = std::move(F);
   }
 
+  void setPreprocessToken(bool Preprocess) { PreprocessToken = Preprocess; }
+
   bool isMacroDefined(StringRef Id) {
 return isMacroDefined(&Identifiers.get(Id));
   }

diff  --git a/clang/lib/CodeGen/CodeGenAction.cpp 
b/clang/lib/CodeGen/CodeGenAction.cpp
index 55925110708e..5a6ce0f5dbd5 100644
--- a/clang/lib/CodeGen/CodeGenAction.cpp
+++ b/clang/lib/CodeGen/CodeGenAction.cpp
@@ -990,11 +990,9 @@ CodeGenAction::CreateASTConsumer(CompilerInstance &CI, 
StringRef InFile) {
 
   CoverageSourceInfo *CoverageInfo = nullptr;
   // Add the preprocessor callback only when the coverage mapping is generated.
-  if (CI.getCodeGenOpts().CoverageMapping) {
-CoverageInfo = new CoverageSourceInfo;
-CI.getPreprocessor().addPPCallbacks(
-
std::unique_ptr(CoverageInfo));
-  }
+  if (CI.getCodeGenOpts().CoverageMapping)
+CoverageInfo = CodeGen::CoverageMappingModuleGen::setUpCoverageCallbacks(
+CI.getPreprocessor());
 
   std::unique_ptr Result(new BackendConsumer(
   BA, CI.getDiagnostics(), CI.getHeaderSearchOpts(),

diff  --git a/clang/lib/CodeGen/CoverageMappingGen.cpp 
b/clang/lib/CodeGen/CoverageMappingGen.cpp
index 78b268f423cb..6729c7f381f5 100644
--- a/clang/lib/CodeGen/CoverageMappingGen.cpp
+++ b/clang/lib/CodeGen/CoverageMappingGen.cpp
@@ -35,8 +35,40 @@ using namespace clang;
 using namespace CodeGen;
 using namespace llvm::coverage;
 
+CoverageSourceInfo *
+CoverageMappingModuleGen::setUpCoverageCallbacks(Preprocessor &PP) {
+  CoverageSourceInfo *CoverageInfo = new CoverageSourceInfo;
+  PP.addPPCallbacks(std::unique_ptr(CoverageInfo));
+  PP.addCommentHandler(CoverageInfo);
+  PP.setPreprocessToken(true);
+  PP.setTokenWatcher([CoverageInfo](clang::Token Tok) {
+// Update previous token location.
+CoverageInfo->PrevTokLoc = Tok.getLocation();
+CoverageInfo->updateNextTokLoc(Tok.getLocation());
+  });
+  return CoverageInfo;
+}
+
 void CoverageSourceInfo::SourceRangeSkipped(SourceRange Range, SourceLocation) 
{
-  SkippedRanges.push_back(Range);
+  SkippedRanges.push_back({Range});
+}
+
+bool CoverageSourceInfo::

[clang] 3930c4e - [Coverage] fix failed test case.

2020-07-21 Thread Zequan Wu via cfe-commits

Author: Zequan Wu
Date: 2020-07-21T19:16:18-07:00
New Revision: 3930c4e7d1aa486ccb4245214c0b383f40574a52

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

LOG: [Coverage] fix failed test case.

Added: 


Modified: 
clang/test/CoverageMapping/includehell.cpp

Removed: 




diff  --git a/clang/test/CoverageMapping/includehell.cpp 
b/clang/test/CoverageMapping/includehell.cpp
index 33656a7d34d5..c92f12e5e80d 100644
--- a/clang/test/CoverageMapping/includehell.cpp
+++ b/clang/test/CoverageMapping/includehell.cpp
@@ -1,5 +1,5 @@
-// RUN: %strip_comments > %t.stripped.cpp
-// RUN: %clang_cc1 -I/%S -fprofile-instrument=clang -fcoverage-mapping 
-dump-coverage-mapping -emit-llvm-only -main-file-name includehell.cpp 
%t.stripped.cpp > %tmapping
+// RUN: %clang_cc1 -fprofile-instrument=clang -fcoverage-mapping 
-dump-coverage-mapping -emit-llvm-only -main-file-name includehell.cpp %s > 
%tmapping
+
 int main() {
   int x = 0;
 



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


[clang] b46176b - Reland [Coverage] Add comment to skipped regions

2020-07-28 Thread Zequan Wu via cfe-commits

Author: Zequan Wu
Date: 2020-07-28T13:20:57-07:00
New Revision: b46176bbb094610460667edad950a9c99f844118

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

LOG: Reland [Coverage] Add comment to skipped regions

Bug filled here: https://bugs.llvm.org/show_bug.cgi?id=45757.
Add comment to skipped regions so we don't track execution count for lines 
containing only comments.

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

Added: 
compiler-rt/test/profile/coverage_comments.cpp

Modified: 
clang/include/clang/Lex/Preprocessor.h
clang/lib/CodeGen/CodeGenAction.cpp
clang/lib/CodeGen/CoverageMappingGen.cpp
clang/lib/CodeGen/CoverageMappingGen.h
clang/lib/Lex/Preprocessor.cpp
clang/test/CoverageMapping/break.c
clang/test/CoverageMapping/builtinmacro.c
clang/test/CoverageMapping/classtemplate.cpp
clang/test/CoverageMapping/comment-in-macro.c
clang/test/CoverageMapping/continue.c
clang/test/CoverageMapping/coroutine.cpp
clang/test/CoverageMapping/deferred-region.cpp
clang/test/CoverageMapping/if.cpp
clang/test/CoverageMapping/includehell.cpp
clang/test/CoverageMapping/label.cpp
clang/test/CoverageMapping/logical.cpp
clang/test/CoverageMapping/loops.cpp
clang/test/CoverageMapping/macro-expressions.cpp
clang/test/CoverageMapping/macroparams2.c
clang/test/CoverageMapping/macros.c
clang/test/CoverageMapping/macroscopes.cpp
clang/test/CoverageMapping/moremacros.c
clang/test/CoverageMapping/objc.m
clang/test/CoverageMapping/pr32679.cpp
clang/test/CoverageMapping/preprocessor.c
clang/test/CoverageMapping/return.c
clang/test/CoverageMapping/switch.cpp
clang/test/CoverageMapping/switchmacro.c
clang/test/CoverageMapping/test.c
clang/test/CoverageMapping/trycatch.cpp
clang/test/CoverageMapping/unreachable-macro.c
clang/test/CoverageMapping/while.c
clang/test/lit.cfg.py
compiler-rt/test/profile/Inputs/instrprof-comdat.h
compiler-rt/test/profile/instrprof-set-file-object-merging.c

Removed: 




diff  --git a/clang/include/clang/Lex/Preprocessor.h 
b/clang/include/clang/Lex/Preprocessor.h
index 5cd017fa925f..b0dd363555ab 100644
--- a/clang/include/clang/Lex/Preprocessor.h
+++ b/clang/include/clang/Lex/Preprocessor.h
@@ -419,6 +419,9 @@ class Preprocessor {
   /// The number of (LexLevel 0) preprocessor tokens.
   unsigned TokenCount = 0;
 
+  /// Preprocess every token regardless of LexLevel.
+  bool PreprocessToken = false;
+
   /// The maximum number of (LexLevel 0) tokens before issuing a -Wmax-tokens
   /// warning, or zero for unlimited.
   unsigned MaxTokens = 0;
@@ -1038,6 +1041,8 @@ class Preprocessor {
 OnToken = std::move(F);
   }
 
+  void setPreprocessToken(bool Preprocess) { PreprocessToken = Preprocess; }
+
   bool isMacroDefined(StringRef Id) {
 return isMacroDefined(&Identifiers.get(Id));
   }

diff  --git a/clang/lib/CodeGen/CodeGenAction.cpp 
b/clang/lib/CodeGen/CodeGenAction.cpp
index 55925110708e..5a6ce0f5dbd5 100644
--- a/clang/lib/CodeGen/CodeGenAction.cpp
+++ b/clang/lib/CodeGen/CodeGenAction.cpp
@@ -990,11 +990,9 @@ CodeGenAction::CreateASTConsumer(CompilerInstance &CI, 
StringRef InFile) {
 
   CoverageSourceInfo *CoverageInfo = nullptr;
   // Add the preprocessor callback only when the coverage mapping is generated.
-  if (CI.getCodeGenOpts().CoverageMapping) {
-CoverageInfo = new CoverageSourceInfo;
-CI.getPreprocessor().addPPCallbacks(
-
std::unique_ptr(CoverageInfo));
-  }
+  if (CI.getCodeGenOpts().CoverageMapping)
+CoverageInfo = CodeGen::CoverageMappingModuleGen::setUpCoverageCallbacks(
+CI.getPreprocessor());
 
   std::unique_ptr Result(new BackendConsumer(
   BA, CI.getDiagnostics(), CI.getHeaderSearchOpts(),

diff  --git a/clang/lib/CodeGen/CoverageMappingGen.cpp 
b/clang/lib/CodeGen/CoverageMappingGen.cpp
index 78b268f423cb..9a7096b8d1d0 100644
--- a/clang/lib/CodeGen/CoverageMappingGen.cpp
+++ b/clang/lib/CodeGen/CoverageMappingGen.cpp
@@ -35,8 +35,35 @@ using namespace clang;
 using namespace CodeGen;
 using namespace llvm::coverage;
 
+CoverageSourceInfo *
+CoverageMappingModuleGen::setUpCoverageCallbacks(Preprocessor &PP) {
+  CoverageSourceInfo *CoverageInfo = new CoverageSourceInfo();
+  PP.addPPCallbacks(std::unique_ptr(CoverageInfo));
+  PP.addCommentHandler(CoverageInfo);
+  PP.setPreprocessToken(true);
+  PP.setTokenWatcher([CoverageInfo](clang::Token Tok) {
+// Update previous token location.
+CoverageInfo->PrevTokLoc = Tok.getLocation();
+CoverageInfo->updateNextTokLoc(Tok.getLocation());
+  });
+  return CoverageInfo;
+}
+
 void CoverageSourceInfo::SourceRangeSkipped(SourceRange Range, SourceLocation) 
{
-  SkippedRanges.push_back(Ra

[clang] e408cba - [AST] Mangle LambdaContextDecl for top level decl

2020-06-10 Thread Zequan Wu via cfe-commits

Author: Zequan Wu
Date: 2020-06-10T09:44:09-07:00
New Revision: e408cba84f8a9471bb26deca8d9aac049a924847

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

LOG: [AST] Mangle LambdaContextDecl for top level decl

Summary:

Bug filed here: https://bugs.llvm.org/show_bug.cgi?id=45213

To resolve it, we let the checks for mangling LambdaContextDecl to be analogous 
to ItaniumMangle strategy: 
https://github.com/llvm/llvm-project/blob/master/clang/lib/AST/ItaniumMangle.cpp#L1829

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

Added: 


Modified: 
clang/lib/AST/MicrosoftMangle.cpp
clang/test/CodeGenCXX/mangle-ms-cxx17.cpp

Removed: 




diff  --git a/clang/lib/AST/MicrosoftMangle.cpp 
b/clang/lib/AST/MicrosoftMangle.cpp
index ca628b3501f6..529f301e4696 100644
--- a/clang/lib/AST/MicrosoftMangle.cpp
+++ b/clang/lib/AST/MicrosoftMangle.cpp
@@ -947,12 +947,12 @@ void MicrosoftCXXNameMangler::mangleUnqualifiedName(const 
NamedDecl *ND,
 
   mangleSourceName(Name);
 
-  // If the context of a closure type is an initializer for a class
-  // member (static or nonstatic), it is encoded in a qualified name.
+  // If the context is a variable or a class member and not a 
parameter,
+  // it is encoded in a qualified name.
   if (LambdaManglingNumber && LambdaContextDecl) {
 if ((isa(LambdaContextDecl) ||
  isa(LambdaContextDecl)) &&
-LambdaContextDecl->getDeclContext()->isRecord()) {
+!isa(LambdaContextDecl)) {
   mangleUnqualifiedName(cast(LambdaContextDecl));
 }
   }

diff  --git a/clang/test/CodeGenCXX/mangle-ms-cxx17.cpp 
b/clang/test/CodeGenCXX/mangle-ms-cxx17.cpp
index 897f0d6c9b17..751fcc46a7ce 100644
--- a/clang/test/CodeGenCXX/mangle-ms-cxx17.cpp
+++ b/clang/test/CodeGenCXX/mangle-ms-cxx17.cpp
@@ -19,3 +19,11 @@ double b;
 
 // CHECK-DAG: "?$S4@@3US@@B"
 const auto [x2, y2] = f();
+
+// CHECK-DAG: "?i1@@3V@0@B"
+inline const auto i1 = [](auto x) { return 0; };
+// CHECK-DAG: "?i2@@3V@0@B"
+inline const auto i2 = [](auto x) { return 1; };
+// CHECK-DAG: "??$?RH@@i1@@QBE?A?@@H@Z"
+// CHECK-DAG: "??$?RH@@i2@@QBE?A?@@H@Z"
+int g() {return i1(1) + i2(1); }



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


[clang] 0547040 - [SemaCXX] Fix false positive of -Wuninitialized-const-reference in empty function body.

2020-07-06 Thread Zequan Wu via cfe-commits

Author: Zequan Wu
Date: 2020-07-06T10:52:05-07:00
New Revision: 054704082b461418d3dac3a379792cdaf52d40b3

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

LOG: [SemaCXX] Fix false positive of -Wuninitialized-const-reference in empty 
function body.

Summary:
Some libraries use empty function to ignore unused variable warnings, which 
gets a new warning from `-Wuninitialized-const-reference`, discussed here 
https://reviews.llvm.org/D79895#2107604.
This patch should fix that.

Reviewers: hans, nick, aaron.ballman

Reviewed By: aaron.ballman

Subscribers: aaron.ballman, riccibruno, cfe-commits

Tags: #clang

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

Added: 


Modified: 
clang/lib/Analysis/UninitializedValues.cpp
clang/test/SemaCXX/warn-uninitialized-const-reference.cpp

Removed: 




diff  --git a/clang/lib/Analysis/UninitializedValues.cpp 
b/clang/lib/Analysis/UninitializedValues.cpp
index 3d44d1c070fe..67cd39728c35 100644
--- a/clang/lib/Analysis/UninitializedValues.cpp
+++ b/clang/lib/Analysis/UninitializedValues.cpp
@@ -405,6 +405,15 @@ static bool isPointerToConst(const QualType &QT) {
   return QT->isAnyPointerType() && QT->getPointeeType().isConstQualified();
 }
 
+static bool hasTrivialBody(CallExpr *CE) {
+  if (FunctionDecl *FD = CE->getDirectCallee()) {
+if (FunctionTemplateDecl *FTD = FD->getPrimaryTemplate())
+  return FTD->getTemplatedDecl()->hasTrivialBody();
+return FD->hasTrivialBody();
+  }
+  return false;
+}
+
 void ClassifyRefs::VisitCallExpr(CallExpr *CE) {
   // Classify arguments to std::move as used.
   if (CE->isCallToStdMove()) {
@@ -413,7 +422,7 @@ void ClassifyRefs::VisitCallExpr(CallExpr *CE) {
   classify(CE->getArg(0), Use);
 return;
   }
-
+  bool isTrivialBody = hasTrivialBody(CE);
   // If a value is passed by const pointer to a function,
   // we should not assume that it is initialized by the call, and we
   // conservatively do not assume that it is used.
@@ -423,7 +432,7 @@ void ClassifyRefs::VisitCallExpr(CallExpr *CE) {
I != E; ++I) {
 if ((*I)->isGLValue()) {
   if ((*I)->getType().isConstQualified())
-classify((*I), ConstRefUse);
+classify((*I), isTrivialBody ? Ignore : ConstRefUse);
 } else if (isPointerToConst((*I)->getType())) {
   const Expr *Ex = stripCasts(DC->getParentASTContext(), *I);
   const auto *UO = dyn_cast(Ex);

diff  --git a/clang/test/SemaCXX/warn-uninitialized-const-reference.cpp 
b/clang/test/SemaCXX/warn-uninitialized-const-reference.cpp
index 292793ba483a..d24b561441d8 100644
--- a/clang/test/SemaCXX/warn-uninitialized-const-reference.cpp
+++ b/clang/test/SemaCXX/warn-uninitialized-const-reference.cpp
@@ -1,4 +1,4 @@
-// RUN: %clang_cc1 -fsyntax-only -Wuninitialized-const-reference -verify %s
+// RUN: %clang_cc1 -fsyntax-only -fcxx-exceptions -fexceptions 
-Wuninitialized-const-reference -verify %s
 
 class A {
 public:
@@ -9,6 +9,16 @@ class A {
   bool operator!=(const A &);
 };
 
+template 
+void ignore_template(const T &) {}
+void ignore(const int &i) {}
+void dont_ignore_non_empty(const int &i) { ; } // Calling this won't silence 
the warning for you
+void dont_ignore_block(const int &i) {
+  {}
+} // Calling this won't silence the warning for you
+void ignore_function_try_block_maybe_who_knows(const int &) try {
+} catch (...) {
+}
 A const_ref_use_A(const A &a);
 int const_ref_use(const int &i);
 A const_use_A(const A a);
@@ -33,4 +43,13 @@ void f(int a) {
   if (a < 42)
 m = 1;
   const_ref_use(m);
+
+  int l;
+  ignore_template(l); // This is a pattern to avoid "unused variable" warnings 
(e.g. boost::ignore_unused).
+  ignore(l);
+  dont_ignore_non_empty(l); // expected-warning {{variable 'l' is 
uninitialized when passed as a const reference argument here}}
+  int l1;
+  dont_ignore_block(l1); // expected-warning {{variable 'l1' is uninitialized 
when passed as a const reference argument here}}
+  int l2;
+  ignore_function_try_block_maybe_who_knows(l2); // expected-warning 
{{variable 'l2' is uninitialized when passed as a const reference argument 
here}}
 }



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


[clang] c92a8c0 - [LPM] Port CGProfilePass from NPM to LPM

2020-07-09 Thread Zequan Wu via cfe-commits

Author: Zequan Wu
Date: 2020-07-09T13:03:42-07:00
New Revision: c92a8c0a0f68fbbb23e3fdde071007e63a552e82

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

LOG: [LPM] Port CGProfilePass from NPM to LPM

Reviewers: hans, chandlerc!, asbirlea, nikic

Reviewed By: hans, nikic

Subscribers: steven_wu, dexonsmith, nikic, echristo, void, zhizhouy, 
cfe-commits, aeubanks, MaskRay, jvesely, nhaehnle, hiraditya, kerbowa, 
llvm-commits

Tags: #llvm, #clang

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

Added: 


Modified: 
clang/include/clang/Basic/CodeGenOptions.def
clang/lib/CodeGen/BackendUtil.cpp
clang/lib/Frontend/CompilerInvocation.cpp
llvm/include/llvm/InitializePasses.h
llvm/include/llvm/Transforms/IPO.h
llvm/include/llvm/Transforms/IPO/PassManagerBuilder.h
llvm/include/llvm/Transforms/Instrumentation/CGProfile.h
llvm/lib/Passes/PassBuilder.cpp
llvm/lib/Transforms/IPO/PassManagerBuilder.cpp
llvm/lib/Transforms/Instrumentation/CGProfile.cpp
llvm/lib/Transforms/Instrumentation/Instrumentation.cpp
llvm/test/CodeGen/AMDGPU/opt-pipeline.ll
llvm/test/Instrumentation/cgprofile.ll
llvm/test/Other/opt-O2-pipeline.ll
llvm/test/Other/opt-O3-pipeline.ll
llvm/test/Other/opt-Os-pipeline.ll

Removed: 
llvm/test/Other/new-pm-cgprofile.ll



diff  --git a/clang/include/clang/Basic/CodeGenOptions.def 
b/clang/include/clang/Basic/CodeGenOptions.def
index d465e00d4c70..f3e43919eeca 100644
--- a/clang/include/clang/Basic/CodeGenOptions.def
+++ b/clang/include/clang/Basic/CodeGenOptions.def
@@ -252,7 +252,6 @@ CODEGENOPT(UnwindTables  , 1, 0) ///< Emit unwind 
tables.
 CODEGENOPT(VectorizeLoop , 1, 0) ///< Run loop vectorizer.
 CODEGENOPT(VectorizeSLP  , 1, 0) ///< Run SLP vectorizer.
 CODEGENOPT(ProfileSampleAccurate, 1, 0) ///< Sample profile is accurate.
-CODEGENOPT(CallGraphProfile  , 1, 0) ///< Run call graph profile.
 
   /// Attempt to use register sized accesses to bit-fields in structures, when
   /// possible.

diff  --git a/clang/lib/CodeGen/BackendUtil.cpp 
b/clang/lib/CodeGen/BackendUtil.cpp
index 9e6d5e4593d3..3ada1aaa4ed8 100644
--- a/clang/lib/CodeGen/BackendUtil.cpp
+++ b/clang/lib/CodeGen/BackendUtil.cpp
@@ -620,6 +620,7 @@ void EmitAssemblyHelper::CreatePasses(legacy::PassManager 
&MPM,
   PMBuilder.SizeLevel = CodeGenOpts.OptimizeSize;
   PMBuilder.SLPVectorize = CodeGenOpts.VectorizeSLP;
   PMBuilder.LoopVectorize = CodeGenOpts.VectorizeLoop;
+  PMBuilder.CallGraphProfile = !CodeGenOpts.DisableIntegratedAS;
 
   PMBuilder.DisableUnrollLoops = !CodeGenOpts.UnrollLoops;
   // Loop interleaving in the loop vectorizer has historically been set to be
@@ -1144,7 +1145,7 @@ void EmitAssemblyHelper::EmitAssemblyWithNewPassManager(
   PTO.LoopInterleaving = CodeGenOpts.UnrollLoops;
   PTO.LoopVectorization = CodeGenOpts.VectorizeLoop;
   PTO.SLPVectorization = CodeGenOpts.VectorizeSLP;
-  PTO.CallGraphProfile = CodeGenOpts.CallGraphProfile;
+  PTO.CallGraphProfile = !CodeGenOpts.DisableIntegratedAS;
   PTO.Coroutines = LangOpts.Coroutines;
 
   PassInstrumentationCallbacks PIC;
@@ -1562,7 +1563,7 @@ static void runThinLTOBackend(
   Conf.PTO.LoopInterleaving = CGOpts.UnrollLoops;
   Conf.PTO.LoopVectorization = CGOpts.VectorizeLoop;
   Conf.PTO.SLPVectorization = CGOpts.VectorizeSLP;
-  Conf.PTO.CallGraphProfile = CGOpts.CallGraphProfile;
+  Conf.PTO.CallGraphProfile = !CGOpts.DisableIntegratedAS;
 
   // Context sensitive profile.
   if (CGOpts.hasProfileCSIRInstr()) {

diff  --git a/clang/lib/Frontend/CompilerInvocation.cpp 
b/clang/lib/Frontend/CompilerInvocation.cpp
index 6f6af917e3a3..fd34c6b8a955 100644
--- a/clang/lib/Frontend/CompilerInvocation.cpp
+++ b/clang/lib/Frontend/CompilerInvocation.cpp
@@ -860,7 +860,6 @@ static bool ParseCodeGenArgs(CodeGenOptions &Opts, ArgList 
&Args, InputKind IK,
   Opts.RerollLoops = Args.hasArg(OPT_freroll_loops);
 
   Opts.DisableIntegratedAS = Args.hasArg(OPT_fno_integrated_as);
-  Opts.CallGraphProfile = !Opts.DisableIntegratedAS;
   Opts.Autolink = !Args.hasArg(OPT_fno_autolink);
   Opts.SampleProfileFile =
   std::string(Args.getLastArgValue(OPT_fprofile_sample_use_EQ));

diff  --git a/llvm/include/llvm/InitializePasses.h 
b/llvm/include/llvm/InitializePasses.h
index f0d5accf13c5..06e8507036ac 100644
--- a/llvm/include/llvm/InitializePasses.h
+++ b/llvm/include/llvm/InitializePasses.h
@@ -103,6 +103,7 @@ void initializeCFGViewerLegacyPassPass(PassRegistry&);
 void initializeCFIInstrInserterPass(PassRegistry&);
 void initializeCFLAndersAAWrapperPassPass(PassRegistry&);
 void initializeCFLSteensAAWrapperPassPass(PassRegistry&);
+void initializeCGProfileLegacyPassPass(PassRegistry &);
 void initializeCallGraphDOTPrinterPass(PassRegistry&);
 void initializeCallGra

[clang] 672ae62 - [Lexer] Fix missing coverage line after #endif

2020-07-09 Thread Zequan Wu via cfe-commits

Author: Zequan Wu
Date: 2020-07-09T15:15:40-07:00
New Revision: 672ae621e91ff5cdefb2535bdd530641536685ea

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

LOG: [Lexer] Fix missing coverage line after #endif

Summary: bug reported here: https://bugs.llvm.org/show_bug.cgi?id=46660

Reviewers: vsk, efriedma, arphaman

Reviewed By: vsk

Subscribers: dexonsmith, cfe-commits

Tags: #clang

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

Added: 


Modified: 
clang/lib/Lex/PPDirectives.cpp
clang/test/CoverageMapping/preprocessor.c

Removed: 




diff  --git a/clang/lib/Lex/PPDirectives.cpp b/clang/lib/Lex/PPDirectives.cpp
index 396ba529fc9a..17dc64b93a99 100644
--- a/clang/lib/Lex/PPDirectives.cpp
+++ b/clang/lib/Lex/PPDirectives.cpp
@@ -432,6 +432,7 @@ void 
Preprocessor::SkipExcludedConditionalBlock(SourceLocation HashTokenLoc,
 // Skip to the next '#endif' / '#else' / '#elif'.
 CurLexer->skipOver(*SkipLength);
   }
+  SourceLocation endifLoc;
   while (true) {
 CurLexer->Lex(Tok);
 
@@ -538,7 +539,7 @@ void 
Preprocessor::SkipExcludedConditionalBlock(SourceLocation HashTokenLoc,
   // Restore the value of LexingRawMode so that trailing comments
   // are handled correctly, if we've reached the outermost block.
   CurPPLexer->LexingRawMode = false;
-  CheckEndOfDirective("endif");
+  endifLoc = CheckEndOfDirective("endif");
   CurPPLexer->LexingRawMode = true;
   if (Callbacks)
 Callbacks->Endif(Tok.getLocation(), CondInfo.IfLoc);
@@ -621,7 +622,9 @@ void 
Preprocessor::SkipExcludedConditionalBlock(SourceLocation HashTokenLoc,
   // by the end of the preamble; we'll resume parsing after the preamble.
   if (Callbacks && (Tok.isNot(tok::eof) || !isRecordingPreamble()))
 Callbacks->SourceRangeSkipped(
-SourceRange(HashTokenLoc, CurPPLexer->getSourceLocation()),
+SourceRange(HashTokenLoc, endifLoc.isValid()
+  ? endifLoc
+  : CurPPLexer->getSourceLocation()),
 Tok.getLocation());
 }
 

diff  --git a/clang/test/CoverageMapping/preprocessor.c 
b/clang/test/CoverageMapping/preprocessor.c
index b3ebc7bd4ec0..9225c9f162a2 100644
--- a/clang/test/CoverageMapping/preprocessor.c
+++ b/clang/test/CoverageMapping/preprocessor.c
@@ -3,7 +3,7 @@
  // CHECK: func
 void func() {// CHECK: File 0, [[@LINE]]:13 -> [[@LINE+5]]:2 = #0
   int i = 0;
-#ifdef MACRO // CHECK-NEXT: Skipped,File 0, [[@LINE]]:1 -> [[@LINE+3]]:1 = 0
+#ifdef MACRO // CHECK-NEXT: Skipped,File 0, [[@LINE]]:1 -> [[@LINE+2]]:7 = 0
   int x = i;
 #endif
 }
@@ -11,7 +11,7 @@ void func() {// CHECK: File 0, [[@LINE]]:13 -> 
[[@LINE+5]]:2 = #0
  // CHECK: main
 int main() { // CHECK-NEXT: File 0, [[@LINE]]:12 -> {{[0-9]+}}:2 = #0
   int i = 0;
-#  if 0// CHECK-NEXT: Skipped,File 0, [[@LINE]]:1 -> [[@LINE+5]]:1 
= 0
+#  if 0// CHECK-NEXT: Skipped,File 0, [[@LINE]]:1 -> 
[[@LINE+4]]:29 = 0
   if(i == 0) {
 i = 1;
   }
@@ -22,44 +22,44 @@ int main() { // CHECK-NEXT: File 0, [[@LINE]]:12 -> 
{{[0-9]+}}:2 = #0
   if(i == 0) {   // CHECK: File 0, [[@LINE]]:14 -> [[@LINE+2]]:4 = #1
 i = 1;
   }
-#else// CHECK-NEXT: Skipped,File 0, [[@LINE]]:1 -> [[@LINE+6]]:1 = 0
+#else// CHECK-NEXT: Skipped,File 0, [[@LINE]]:1 -> [[@LINE+5]]:7 = 0
   if(i == 1) {
 i = 0;
   }
 }
 #endif
 
-  // CHECK-NEXT: Skipped,File 0, [[@LINE+1]]:1 -> [[@LINE+5]]:1
+  // CHECK-NEXT: Skipped,File 0, [[@LINE+1]]:1 -> [[@LINE+4]]:24
 #\
   if 0
 #\
   endif // also skipped
 
 #if 1
-  // CHECK-NEXT: Skipped,File 0, [[@LINE+1]]:1 -> [[@LINE+4]]:1
+  // CHECK-NEXT: Skipped,File 0, [[@LINE+1]]:1 -> [[@LINE+3]]:7
 #\
   elif 0
 #endif
 
 #if 1
-  // CHECK-NEXT: Skipped,File 0, [[@LINE+1]]:1 -> [[@LINE+4]]:1
+  // CHECK-NEXT: Skipped,File 0, [[@LINE+1]]:1 -> [[@LINE+3]]:7
 #\
   else
 #endif
 
-  // CHECK-NEXT: Skipped,File 0, [[@LINE+1]]:1 -> [[@LINE+5]]:1
+  // CHECK-NEXT: Skipped,File 0, [[@LINE+1]]:1 -> [[@LINE+4]]:8
 #\
   ifdef NOT_DEFINED
 #\
   endif
 
-  // CHECK-NEXT: Skipped,File 0, [[@LINE+1]]:1 -> [[@LINE+5]]:1
+  // CHECK-NEXT: Skipped,File 0, [[@LINE+1]]:1 -> [[@LINE+4]]:8
 #\
   ifndef __FILE__
 #\
   endif
 
-  // CHECK-NEXT: Skipped,File 0, [[@LINE+1]]:1 -> [[@LINE+7]]:1
+  // CHECK-NEXT: Skipped,File 0, [[@LINE+1]]:1 -> [[@LINE+6]]:26
 #\
   ifdef NOT_DEFINED
 #\



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


[clang] 8be204f - Revert "[Lexer] Fix missing coverage line after #endif"

2020-07-09 Thread Zequan Wu via cfe-commits

Author: Zequan Wu
Date: 2020-07-09T15:51:02-07:00
New Revision: 8be204fe75caac4ce6ed1e2cf5659011476bde79

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

LOG: Revert "[Lexer] Fix missing coverage line after #endif"

This reverts commit 672ae621e91ff5cdefb2535bdd530641536685ea.

Added: 


Modified: 
clang/lib/Lex/PPDirectives.cpp
clang/test/CoverageMapping/preprocessor.c

Removed: 




diff  --git a/clang/lib/Lex/PPDirectives.cpp b/clang/lib/Lex/PPDirectives.cpp
index 17dc64b93a99..396ba529fc9a 100644
--- a/clang/lib/Lex/PPDirectives.cpp
+++ b/clang/lib/Lex/PPDirectives.cpp
@@ -432,7 +432,6 @@ void 
Preprocessor::SkipExcludedConditionalBlock(SourceLocation HashTokenLoc,
 // Skip to the next '#endif' / '#else' / '#elif'.
 CurLexer->skipOver(*SkipLength);
   }
-  SourceLocation endifLoc;
   while (true) {
 CurLexer->Lex(Tok);
 
@@ -539,7 +538,7 @@ void 
Preprocessor::SkipExcludedConditionalBlock(SourceLocation HashTokenLoc,
   // Restore the value of LexingRawMode so that trailing comments
   // are handled correctly, if we've reached the outermost block.
   CurPPLexer->LexingRawMode = false;
-  endifLoc = CheckEndOfDirective("endif");
+  CheckEndOfDirective("endif");
   CurPPLexer->LexingRawMode = true;
   if (Callbacks)
 Callbacks->Endif(Tok.getLocation(), CondInfo.IfLoc);
@@ -622,9 +621,7 @@ void 
Preprocessor::SkipExcludedConditionalBlock(SourceLocation HashTokenLoc,
   // by the end of the preamble; we'll resume parsing after the preamble.
   if (Callbacks && (Tok.isNot(tok::eof) || !isRecordingPreamble()))
 Callbacks->SourceRangeSkipped(
-SourceRange(HashTokenLoc, endifLoc.isValid()
-  ? endifLoc
-  : CurPPLexer->getSourceLocation()),
+SourceRange(HashTokenLoc, CurPPLexer->getSourceLocation()),
 Tok.getLocation());
 }
 

diff  --git a/clang/test/CoverageMapping/preprocessor.c 
b/clang/test/CoverageMapping/preprocessor.c
index 9225c9f162a2..b3ebc7bd4ec0 100644
--- a/clang/test/CoverageMapping/preprocessor.c
+++ b/clang/test/CoverageMapping/preprocessor.c
@@ -3,7 +3,7 @@
  // CHECK: func
 void func() {// CHECK: File 0, [[@LINE]]:13 -> [[@LINE+5]]:2 = #0
   int i = 0;
-#ifdef MACRO // CHECK-NEXT: Skipped,File 0, [[@LINE]]:1 -> [[@LINE+2]]:7 = 0
+#ifdef MACRO // CHECK-NEXT: Skipped,File 0, [[@LINE]]:1 -> [[@LINE+3]]:1 = 0
   int x = i;
 #endif
 }
@@ -11,7 +11,7 @@ void func() {// CHECK: File 0, [[@LINE]]:13 -> 
[[@LINE+5]]:2 = #0
  // CHECK: main
 int main() { // CHECK-NEXT: File 0, [[@LINE]]:12 -> {{[0-9]+}}:2 = #0
   int i = 0;
-#  if 0// CHECK-NEXT: Skipped,File 0, [[@LINE]]:1 -> 
[[@LINE+4]]:29 = 0
+#  if 0// CHECK-NEXT: Skipped,File 0, [[@LINE]]:1 -> [[@LINE+5]]:1 
= 0
   if(i == 0) {
 i = 1;
   }
@@ -22,44 +22,44 @@ int main() { // CHECK-NEXT: File 0, [[@LINE]]:12 -> 
{{[0-9]+}}:2 = #0
   if(i == 0) {   // CHECK: File 0, [[@LINE]]:14 -> [[@LINE+2]]:4 = #1
 i = 1;
   }
-#else// CHECK-NEXT: Skipped,File 0, [[@LINE]]:1 -> [[@LINE+5]]:7 = 0
+#else// CHECK-NEXT: Skipped,File 0, [[@LINE]]:1 -> [[@LINE+6]]:1 = 0
   if(i == 1) {
 i = 0;
   }
 }
 #endif
 
-  // CHECK-NEXT: Skipped,File 0, [[@LINE+1]]:1 -> [[@LINE+4]]:24
+  // CHECK-NEXT: Skipped,File 0, [[@LINE+1]]:1 -> [[@LINE+5]]:1
 #\
   if 0
 #\
   endif // also skipped
 
 #if 1
-  // CHECK-NEXT: Skipped,File 0, [[@LINE+1]]:1 -> [[@LINE+3]]:7
+  // CHECK-NEXT: Skipped,File 0, [[@LINE+1]]:1 -> [[@LINE+4]]:1
 #\
   elif 0
 #endif
 
 #if 1
-  // CHECK-NEXT: Skipped,File 0, [[@LINE+1]]:1 -> [[@LINE+3]]:7
+  // CHECK-NEXT: Skipped,File 0, [[@LINE+1]]:1 -> [[@LINE+4]]:1
 #\
   else
 #endif
 
-  // CHECK-NEXT: Skipped,File 0, [[@LINE+1]]:1 -> [[@LINE+4]]:8
+  // CHECK-NEXT: Skipped,File 0, [[@LINE+1]]:1 -> [[@LINE+5]]:1
 #\
   ifdef NOT_DEFINED
 #\
   endif
 
-  // CHECK-NEXT: Skipped,File 0, [[@LINE+1]]:1 -> [[@LINE+4]]:8
+  // CHECK-NEXT: Skipped,File 0, [[@LINE+1]]:1 -> [[@LINE+5]]:1
 #\
   ifndef __FILE__
 #\
   endif
 
-  // CHECK-NEXT: Skipped,File 0, [[@LINE+1]]:1 -> [[@LINE+6]]:26
+  // CHECK-NEXT: Skipped,File 0, [[@LINE+1]]:1 -> [[@LINE+7]]:1
 #\
   ifdef NOT_DEFINED
 #\



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


[clang] dcd76c0 - [Lexer] Fix missing coverage line after #endif

2020-07-10 Thread Zequan Wu via cfe-commits

Author: Zequan Wu
Date: 2020-07-10T09:05:20-07:00
New Revision: dcd76c0c0716a4417110423718c7cae4b516b4d0

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

LOG: [Lexer] Fix missing coverage line after #endif

Summary: bug reported here: https://bugs.llvm.org/show_bug.cgi?id=46660

Reviewers: vsk, efriedma, arphaman

Reviewed By: vsk

Subscribers: dexonsmith, cfe-commits

Tags: #clang

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

Added: 


Modified: 
clang-tools-extra/clangd/SemanticHighlighting.cpp
clang/lib/Lex/PPDirectives.cpp
clang/test/CoverageMapping/preprocessor.c

Removed: 




diff  --git a/clang-tools-extra/clangd/SemanticHighlighting.cpp 
b/clang-tools-extra/clangd/SemanticHighlighting.cpp
index d2470da60140..ed75ce80999c 100644
--- a/clang-tools-extra/clangd/SemanticHighlighting.cpp
+++ b/clang-tools-extra/clangd/SemanticHighlighting.cpp
@@ -224,7 +224,7 @@ class HighlightingsBuilder {
   // Create one token for each line in the skipped range, so it works
   // with line-based 
diff ing.
   assert(R.start.line <= R.end.line);
-  for (int Line = R.start.line; Line < R.end.line; ++Line) {
+  for (int Line = R.start.line; Line <= R.end.line; ++Line) {
 // Don't bother computing the offset for the end of the line, just use
 // zero. The client will treat this highlighting kind specially, and
 // highlight the entire line visually (i.e. not just to where the text

diff  --git a/clang/lib/Lex/PPDirectives.cpp b/clang/lib/Lex/PPDirectives.cpp
index 396ba529fc9a..053ef1d2dd18 100644
--- a/clang/lib/Lex/PPDirectives.cpp
+++ b/clang/lib/Lex/PPDirectives.cpp
@@ -432,6 +432,7 @@ void 
Preprocessor::SkipExcludedConditionalBlock(SourceLocation HashTokenLoc,
 // Skip to the next '#endif' / '#else' / '#elif'.
 CurLexer->skipOver(*SkipLength);
   }
+  SourceLocation endLoc;
   while (true) {
 CurLexer->Lex(Tok);
 
@@ -538,7 +539,7 @@ void 
Preprocessor::SkipExcludedConditionalBlock(SourceLocation HashTokenLoc,
   // Restore the value of LexingRawMode so that trailing comments
   // are handled correctly, if we've reached the outermost block.
   CurPPLexer->LexingRawMode = false;
-  CheckEndOfDirective("endif");
+  endLoc = CheckEndOfDirective("endif");
   CurPPLexer->LexingRawMode = true;
   if (Callbacks)
 Callbacks->Endif(Tok.getLocation(), CondInfo.IfLoc);
@@ -565,7 +566,7 @@ void 
Preprocessor::SkipExcludedConditionalBlock(SourceLocation HashTokenLoc,
   // Restore the value of LexingRawMode so that trailing comments
   // are handled correctly.
   CurPPLexer->LexingRawMode = false;
-  CheckEndOfDirective("else");
+  endLoc = CheckEndOfDirective("else");
   CurPPLexer->LexingRawMode = true;
   if (Callbacks)
 Callbacks->Else(Tok.getLocation(), CondInfo.IfLoc);
@@ -621,7 +622,9 @@ void 
Preprocessor::SkipExcludedConditionalBlock(SourceLocation HashTokenLoc,
   // by the end of the preamble; we'll resume parsing after the preamble.
   if (Callbacks && (Tok.isNot(tok::eof) || !isRecordingPreamble()))
 Callbacks->SourceRangeSkipped(
-SourceRange(HashTokenLoc, CurPPLexer->getSourceLocation()),
+SourceRange(HashTokenLoc, endLoc.isValid()
+  ? endLoc
+  : CurPPLexer->getSourceLocation()),
 Tok.getLocation());
 }
 

diff  --git a/clang/test/CoverageMapping/preprocessor.c 
b/clang/test/CoverageMapping/preprocessor.c
index b3ebc7bd4ec0..9225c9f162a2 100644
--- a/clang/test/CoverageMapping/preprocessor.c
+++ b/clang/test/CoverageMapping/preprocessor.c
@@ -3,7 +3,7 @@
  // CHECK: func
 void func() {// CHECK: File 0, [[@LINE]]:13 -> [[@LINE+5]]:2 = #0
   int i = 0;
-#ifdef MACRO // CHECK-NEXT: Skipped,File 0, [[@LINE]]:1 -> [[@LINE+3]]:1 = 0
+#ifdef MACRO // CHECK-NEXT: Skipped,File 0, [[@LINE]]:1 -> [[@LINE+2]]:7 = 0
   int x = i;
 #endif
 }
@@ -11,7 +11,7 @@ void func() {// CHECK: File 0, [[@LINE]]:13 -> 
[[@LINE+5]]:2 = #0
  // CHECK: main
 int main() { // CHECK-NEXT: File 0, [[@LINE]]:12 -> {{[0-9]+}}:2 = #0
   int i = 0;
-#  if 0// CHECK-NEXT: Skipped,File 0, [[@LINE]]:1 -> [[@LINE+5]]:1 
= 0
+#  if 0// CHECK-NEXT: Skipped,File 0, [[@LINE]]:1 -> 
[[@LINE+4]]:29 = 0
   if(i == 0) {
 i = 1;
   }
@@ -22,44 +22,44 @@ int main() { // CHECK-NEXT: File 0, [[@LINE]]:12 -> 
{{[0-9]+}}:2 = #0
   if(i == 0) {   // CHECK: File 0, [[@LINE]]:14 -> [[@LINE+2]]:4 = #1
 i = 1;
   }
-#else// CHECK-NEXT: Skipped,File 0, [[@LINE]]:1 -> [[@LINE+6]]:1 = 0
+#else// CHECK-NEXT: Skipped,File 0, [[@

[clang] 1fbb719 - [LPM] Port CGProfilePass from NPM to LPM

2020-07-10 Thread Zequan Wu via cfe-commits

Author: Zequan Wu
Date: 2020-07-10T09:04:51-07:00
New Revision: 1fbb719470c6e0395abaab66c68fae3b8ae405d0

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

LOG: [LPM] Port CGProfilePass from NPM to LPM

Reviewers: hans, chandlerc!, asbirlea, nikic

Reviewed By: hans, nikic

Subscribers: steven_wu, dexonsmith, nikic, echristo, void, zhizhouy, 
cfe-commits, aeubanks, MaskRay, jvesely, nhaehnle, hiraditya, kerbowa, 
llvm-commits

Tags: #llvm, #clang

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

Added: 


Modified: 
clang/include/clang/Basic/CodeGenOptions.def
clang/lib/CodeGen/BackendUtil.cpp
clang/lib/Frontend/CompilerInvocation.cpp
llvm/include/llvm/InitializePasses.h
llvm/include/llvm/Transforms/IPO.h
llvm/include/llvm/Transforms/IPO/PassManagerBuilder.h
llvm/include/llvm/Transforms/Instrumentation/CGProfile.h
llvm/lib/Passes/PassBuilder.cpp
llvm/lib/Transforms/IPO/PassManagerBuilder.cpp
llvm/lib/Transforms/Instrumentation/CGProfile.cpp
llvm/lib/Transforms/Instrumentation/Instrumentation.cpp
llvm/test/CodeGen/AMDGPU/opt-pipeline.ll
llvm/test/Instrumentation/cgprofile.ll
llvm/test/Other/opt-O2-pipeline.ll
llvm/test/Other/opt-O3-pipeline.ll
llvm/test/Other/opt-Os-pipeline.ll

Removed: 
llvm/test/Other/new-pm-cgprofile.ll



diff  --git a/clang/include/clang/Basic/CodeGenOptions.def 
b/clang/include/clang/Basic/CodeGenOptions.def
index 67c0b4203420..c7e01eb12851 100644
--- a/clang/include/clang/Basic/CodeGenOptions.def
+++ b/clang/include/clang/Basic/CodeGenOptions.def
@@ -254,7 +254,6 @@ CODEGENOPT(UnwindTables  , 1, 0) ///< Emit unwind 
tables.
 CODEGENOPT(VectorizeLoop , 1, 0) ///< Run loop vectorizer.
 CODEGENOPT(VectorizeSLP  , 1, 0) ///< Run SLP vectorizer.
 CODEGENOPT(ProfileSampleAccurate, 1, 0) ///< Sample profile is accurate.
-CODEGENOPT(CallGraphProfile  , 1, 0) ///< Run call graph profile.
 
   /// Attempt to use register sized accesses to bit-fields in structures, when
   /// possible.

diff  --git a/clang/lib/CodeGen/BackendUtil.cpp 
b/clang/lib/CodeGen/BackendUtil.cpp
index 9e6d5e4593d3..dce0940670a2 100644
--- a/clang/lib/CodeGen/BackendUtil.cpp
+++ b/clang/lib/CodeGen/BackendUtil.cpp
@@ -620,6 +620,9 @@ void EmitAssemblyHelper::CreatePasses(legacy::PassManager 
&MPM,
   PMBuilder.SizeLevel = CodeGenOpts.OptimizeSize;
   PMBuilder.SLPVectorize = CodeGenOpts.VectorizeSLP;
   PMBuilder.LoopVectorize = CodeGenOpts.VectorizeLoop;
+  // Only enable CGProfilePass when using integrated assembler, since
+  // non-integrated assemblers don't recognize .cgprofile section.
+  PMBuilder.CallGraphProfile = !CodeGenOpts.DisableIntegratedAS;
 
   PMBuilder.DisableUnrollLoops = !CodeGenOpts.UnrollLoops;
   // Loop interleaving in the loop vectorizer has historically been set to be
@@ -1144,7 +1147,9 @@ void EmitAssemblyHelper::EmitAssemblyWithNewPassManager(
   PTO.LoopInterleaving = CodeGenOpts.UnrollLoops;
   PTO.LoopVectorization = CodeGenOpts.VectorizeLoop;
   PTO.SLPVectorization = CodeGenOpts.VectorizeSLP;
-  PTO.CallGraphProfile = CodeGenOpts.CallGraphProfile;
+  // Only enable CGProfilePass when using integrated assembler, since
+  // non-integrated assemblers don't recognize .cgprofile section.
+  PTO.CallGraphProfile = !CodeGenOpts.DisableIntegratedAS;
   PTO.Coroutines = LangOpts.Coroutines;
 
   PassInstrumentationCallbacks PIC;
@@ -1562,7 +1567,9 @@ static void runThinLTOBackend(
   Conf.PTO.LoopInterleaving = CGOpts.UnrollLoops;
   Conf.PTO.LoopVectorization = CGOpts.VectorizeLoop;
   Conf.PTO.SLPVectorization = CGOpts.VectorizeSLP;
-  Conf.PTO.CallGraphProfile = CGOpts.CallGraphProfile;
+  // Only enable CGProfilePass when using integrated assembler, since
+  // non-integrated assemblers don't recognize .cgprofile section.
+  Conf.PTO.CallGraphProfile = !CGOpts.DisableIntegratedAS;
 
   // Context sensitive profile.
   if (CGOpts.hasProfileCSIRInstr()) {

diff  --git a/clang/lib/Frontend/CompilerInvocation.cpp 
b/clang/lib/Frontend/CompilerInvocation.cpp
index e24de29a309e..863c6b3ca4f3 100644
--- a/clang/lib/Frontend/CompilerInvocation.cpp
+++ b/clang/lib/Frontend/CompilerInvocation.cpp
@@ -860,7 +860,6 @@ static bool ParseCodeGenArgs(CodeGenOptions &Opts, ArgList 
&Args, InputKind IK,
   Opts.RerollLoops = Args.hasArg(OPT_freroll_loops);
 
   Opts.DisableIntegratedAS = Args.hasArg(OPT_fno_integrated_as);
-  Opts.CallGraphProfile = !Opts.DisableIntegratedAS;
   Opts.Autolink = !Args.hasArg(OPT_fno_autolink);
   Opts.SampleProfileFile =
   std::string(Args.getLastArgValue(OPT_fprofile_sample_use_EQ));

diff  --git a/llvm/include/llvm/InitializePasses.h 
b/llvm/include/llvm/InitializePasses.h
index f0d5accf13c5..06e8507036ac 100644
--- a/llvm/include/llvm/InitializePasses.h
+++ b/ll

[clang] c354b2e - [Clang] Add note for bad conversion when expression is pointer to forward-declared type

2020-08-07 Thread Zequan Wu via cfe-commits

Author: Zequan Wu
Date: 2020-08-07T11:06:08-07:00
New Revision: c354b2e3bfe6709ffd78d0fcd017b7e5be7a7a23

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

LOG: [Clang] Add note for bad conversion when expression is pointer to 
forward-declared type

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

Added: 
clang/test/SemaCXX/pointer-forward-declared-class-conversion.cpp

Modified: 
clang/include/clang/Basic/DiagnosticSemaKinds.td
clang/lib/Sema/SemaInit.cpp
clang/test/Modules/namespaces.cpp
clang/test/SemaCXX/elaborated-type-specifier.cpp

Removed: 




diff  --git a/clang/include/clang/Basic/DiagnosticSemaKinds.td 
b/clang/include/clang/Basic/DiagnosticSemaKinds.td
index 2f4eb428dfad..7185a4d6cab0 100644
--- a/clang/include/clang/Basic/DiagnosticSemaKinds.td
+++ b/clang/include/clang/Basic/DiagnosticSemaKinds.td
@@ -2005,6 +2005,8 @@ def err_init_conversion_failed : Error<
   "|: 
diff erent return type%
diff { ($ vs $)|}5,6"
   "|: 
diff erent qualifiers (%5 vs %6)"
   "|: 
diff erent exception specifications}4">;
+def note_forward_class_conversion : Note<"%0 is not defined, but forward "
+  "declared here; conversion would be valid if it's derived from %1">;
 
 def err_lvalue_to_rvalue_ref : Error<"rvalue reference %
diff {to type $ cannot "
   "bind to lvalue of type $|cannot bind to incompatible lvalue}0,1">;

diff  --git a/clang/lib/Sema/SemaInit.cpp b/clang/lib/Sema/SemaInit.cpp
index e2f67e9fd59b..f4cfae0f7d85 100644
--- a/clang/lib/Sema/SemaInit.cpp
+++ b/clang/lib/Sema/SemaInit.cpp
@@ -8707,6 +8707,16 @@ static void emitBadConversionNotes(Sema &S, const 
InitializedEntity &entity,
 if (entity.getKind() == InitializedEntity::EK_Result)
   S.EmitRelatedResultTypeNoteForReturn(destType);
   }
+  QualType fromType = op->getType();
+  auto *fromDecl = fromType.getTypePtr()->getPointeeCXXRecordDecl();
+  auto *destDecl = destType.getTypePtr()->getPointeeCXXRecordDecl();
+  if (fromDecl && destDecl && fromDecl->getDeclKind() == Decl::CXXRecord &&
+  destDecl->getDeclKind() == Decl::CXXRecord &&
+  !fromDecl->isInvalidDecl() && !destDecl->isInvalidDecl() &&
+  !fromDecl->hasDefinition())
+S.Diag(fromDecl->getLocation(), diag::note_forward_class_conversion)
+<< S.getASTContext().getTagDeclType(fromDecl)
+<< S.getASTContext().getTagDeclType(destDecl);
 }
 
 static void diagnoseListInit(Sema &S, const InitializedEntity &Entity,

diff  --git a/clang/test/Modules/namespaces.cpp 
b/clang/test/Modules/namespaces.cpp
index 5c0e18325b0a..315b1cdeda0a 100644
--- a/clang/test/Modules/namespaces.cpp
+++ b/clang/test/Modules/namespaces.cpp
@@ -78,7 +78,8 @@ void testAnonymousNotMerged() {
 
 // expected-note@Inputs/namespaces-right.h:60 {{passing argument to parameter 
here}}
 // expected-note@Inputs/namespaces-right.h:67 {{passing argument to parameter 
here}}
-
+// expected-note@Inputs/namespaces-left.h:63 {{'N11::(anonymous 
namespace)::Foo' is not defined, but forward declared here; conversion would be 
valid if it's derived from 'N11::(anonymous namespace)::Foo'}}
+// expected-note@Inputs/namespaces-left.h:70 {{'N12::(anonymous 
namespace)::Foo' is not defined, but forward declared here; conversion would be 
valid if it's derived from 'N12::(anonymous namespace)::Foo'}}
 // Test that bringing in one name from an overload set does not hide the rest.
 void testPartialImportOfOverloadSet() {
   void (*p)() = N13::p;

diff  --git a/clang/test/SemaCXX/elaborated-type-specifier.cpp 
b/clang/test/SemaCXX/elaborated-type-specifier.cpp
index 3701dd7ba630..06037d865d26 100644
--- a/clang/test/SemaCXX/elaborated-type-specifier.cpp
+++ b/clang/test/SemaCXX/elaborated-type-specifier.cpp
@@ -26,7 +26,7 @@ namespace NS {
 }
 
 void test_X_elab(NS::X x) {
-  struct S4 *s4 = 0;
+  struct S4 *s4 = 0; // expected-note{{'S4' is not defined, but forward 
declared here; conversion would be valid if it's derived from 'NS::S4'}}
   x.test_elab2(s4); // expected-error{{cannot initialize a parameter of type 
'NS::S4 *' with an lvalue of type 'struct S4 *'}}
 }
 

diff  --git a/clang/test/SemaCXX/pointer-forward-declared-class-conversion.cpp 
b/clang/test/SemaCXX/pointer-forward-declared-class-conversion.cpp
new file mode 100644
index ..606517b51aac
--- /dev/null
+++ b/clang/test/SemaCXX/pointer-forward-declared-class-conversion.cpp
@@ -0,0 +1,11 @@
+// RUN: %clang_cc1 -fsyntax-only -verify %s
+
+class A1 {};
+class B1; // expected-note{{'B1' is not defined, but forward declared here; 
conversion would be valid if it's derived from 'A1'}}
+B1 *b1;
+A1 *a1 = b1; // expected-error{{cannot initialize a variable of type 'A1 *' 
with an lvalue of type 'B1 *'}}
+
+template  class A2 {};
+template  class B2;
+B2 *b2;
+A2 *a2 = b2; // expected-error

[clang] 94c6cea - [AST] add parenthesis locations for IfStmt and SwitchStmt

2020-08-10 Thread Zequan Wu via cfe-commits

Author: Zequan Wu
Date: 2020-08-10T19:19:51-07:00
New Revision: 94c6ceab539efe26a1707124e803f444139c1b12

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

LOG: [AST] add parenthesis locations for IfStmt and SwitchStmt

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

Added: 


Modified: 
clang/include/clang/AST/Stmt.h
clang/include/clang/Sema/Sema.h
clang/lib/AST/ASTImporter.cpp
clang/lib/AST/Stmt.cpp
clang/lib/Analysis/BodyFarm.cpp
clang/lib/Parse/ParseStmt.cpp
clang/lib/Sema/SemaDeclCXX.cpp
clang/lib/Sema/SemaStmt.cpp
clang/lib/Sema/TreeTransform.h
clang/lib/Serialization/ASTReaderStmt.cpp
clang/lib/Serialization/ASTWriterStmt.cpp

Removed: 




diff  --git a/clang/include/clang/AST/Stmt.h b/clang/include/clang/AST/Stmt.h
index 13f265223ac1..726c61cb0126 100644
--- a/clang/include/clang/AST/Stmt.h
+++ b/clang/include/clang/AST/Stmt.h
@@ -1895,6 +1895,8 @@ class IfStmt final
   //Present if and only if hasElseStorage().
   enum { InitOffset = 0, ThenOffsetFromCond = 1, ElseOffsetFromCond = 2 };
   enum { NumMandatoryStmtPtr = 2 };
+  SourceLocation LParenLoc;
+  SourceLocation RParenLoc;
 
   unsigned numTrailingObjects(OverloadToken) const {
 return NumMandatoryStmtPtr + hasElseStorage() + hasVarStorage() +
@@ -1915,7 +1917,8 @@ class IfStmt final
 
   /// Build an if/then/else statement.
   IfStmt(const ASTContext &Ctx, SourceLocation IL, bool IsConstexpr, Stmt 
*Init,
- VarDecl *Var, Expr *Cond, Stmt *Then, SourceLocation EL, Stmt *Else);
+ VarDecl *Var, Expr *Cond, SourceLocation LParenLoc,
+ SourceLocation RParenLoc, Stmt *Then, SourceLocation EL, Stmt *Else);
 
   /// Build an empty if/then/else statement.
   explicit IfStmt(EmptyShell Empty, bool HasElse, bool HasVar, bool HasInit);
@@ -1924,7 +1927,8 @@ class IfStmt final
   /// Create an IfStmt.
   static IfStmt *Create(const ASTContext &Ctx, SourceLocation IL,
 bool IsConstexpr, Stmt *Init, VarDecl *Var, Expr *Cond,
-Stmt *Then, SourceLocation EL = SourceLocation(),
+SourceLocation LPL, SourceLocation RPL, Stmt *Then,
+SourceLocation EL = SourceLocation(),
 Stmt *Else = nullptr);
 
   /// Create an empty IfStmt optionally with storage for an else statement,
@@ -2054,6 +2058,10 @@ class IfStmt final
   return getElse()->getEndLoc();
 return getThen()->getEndLoc();
   }
+  SourceLocation getLParenLoc() const { return LParenLoc; }
+  void setLParenLoc(SourceLocation Loc) { LParenLoc = Loc; }
+  SourceLocation getRParenLoc() const { return RParenLoc; }
+  void setRParenLoc(SourceLocation Loc) { RParenLoc = Loc; }
 
   // Iterators over subexpressions.  The iterators will include iterating
   // over the initialization expression referenced by the condition variable.
@@ -2101,6 +2109,8 @@ class SwitchStmt final : public Stmt,
   //Always present.
   enum { InitOffset = 0, BodyOffsetFromCond = 1 };
   enum { NumMandatoryStmtPtr = 2 };
+  SourceLocation LParenLoc;
+  SourceLocation RParenLoc;
 
   unsigned numTrailingObjects(OverloadToken) const {
 return NumMandatoryStmtPtr + hasInitStorage() + hasVarStorage();
@@ -2114,7 +2124,8 @@ class SwitchStmt final : public Stmt,
   unsigned bodyOffset() const { return condOffset() + BodyOffsetFromCond; }
 
   /// Build a switch statement.
-  SwitchStmt(const ASTContext &Ctx, Stmt *Init, VarDecl *Var, Expr *Cond);
+  SwitchStmt(const ASTContext &Ctx, Stmt *Init, VarDecl *Var, Expr *Cond,
+ SourceLocation LParenLoc, SourceLocation RParenLoc);
 
   /// Build a empty switch statement.
   explicit SwitchStmt(EmptyShell Empty, bool HasInit, bool HasVar);
@@ -2122,7 +2133,8 @@ class SwitchStmt final : public Stmt,
 public:
   /// Create a switch statement.
   static SwitchStmt *Create(const ASTContext &Ctx, Stmt *Init, VarDecl *Var,
-Expr *Cond);
+Expr *Cond, SourceLocation LParenLoc,
+SourceLocation RParenLoc);
 
   /// Create an empty switch statement optionally with storage for
   /// an init expression and a condition variable.
@@ -2210,6 +,10 @@ class SwitchStmt final : public Stmt,
 
   SourceLocation getSwitchLoc() const { return SwitchStmtBits.SwitchLoc; }
   void setSwitchLoc(SourceLocation L) { SwitchStmtBits.SwitchLoc = L; }
+  SourceLocation getLParenLoc() const { return LParenLoc; }
+  void setLParenLoc(SourceLocation Loc) { LParenLoc = Loc; }
+  SourceLocation getRParenLoc() const { return RParenLoc; }
+  void setRParenLoc(SourceLocation Loc) { RParenLoc = Loc; }
 
   void setBody(Stmt *S, SourceLocation SL) {
 setBody(S);

diff  --git a/clang/include/clang/Sema

[clang] 4aaa977 - [Sema] Fix missing warning on initializer lists on field initializers with overloaded operators

2020-08-10 Thread Zequan Wu via cfe-commits

Author: Zequan Wu
Date: 2020-08-10T19:32:59-07:00
New Revision: 4aaa97700377a811dbcaf88a81ec068a5b517a4d

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

LOG: [Sema] Fix missing warning on initializer lists on field initializers with 
overloaded operators

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

Added: 


Modified: 
clang/lib/Sema/SemaDeclCXX.cpp
clang/test/SemaCXX/uninitialized.cpp

Removed: 




diff  --git a/clang/lib/Sema/SemaDeclCXX.cpp b/clang/lib/Sema/SemaDeclCXX.cpp
index 057062a7372f..ea3f6786d151 100644
--- a/clang/lib/Sema/SemaDeclCXX.cpp
+++ b/clang/lib/Sema/SemaDeclCXX.cpp
@@ -3577,8 +3577,10 @@ namespace {
 Base = SubME->getBase();
   }
 
-  if (!isa(Base->IgnoreParenImpCasts()))
+  if (!isa(Base->IgnoreParenImpCasts())) {
+Visit(Base);
 return;
+  }
 
   if (AddressOf && AllPODFields)
 return;

diff  --git a/clang/test/SemaCXX/uninitialized.cpp 
b/clang/test/SemaCXX/uninitialized.cpp
index cdfcb2a9cbed..0c7b13a56ee8 100644
--- a/clang/test/SemaCXX/uninitialized.cpp
+++ b/clang/test/SemaCXX/uninitialized.cpp
@@ -1303,6 +1303,20 @@ namespace init_list {
   d3{ d3.b, num } // expected-warning{{uninitialized}}
 {}
   };
+  
+  struct E {
+E();
+E foo();
+E* operator->();
+  };
+
+  struct F { F(E); };
+
+  struct EFComposed {
+F f;
+E e;
+EFComposed() : f{ e->foo() }, e() {} // expected-warning{{uninitialized}}
+  };
 }
 
 namespace template_class {



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


[clang] a31c89c - [Coverage] Enable emitting gap area between macros

2020-08-12 Thread Zequan Wu via cfe-commits

Author: Zequan Wu
Date: 2020-08-12T16:25:27-07:00
New Revision: a31c89c1b7a0a2fd3e2c0b8a587a60921abf4abd

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

LOG: [Coverage] Enable emitting gap area between macros

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

Added: 


Modified: 
clang/lib/CodeGen/CoverageMappingGen.cpp
clang/test/CoverageMapping/if.cpp
clang/test/CoverageMapping/macro-expressions.cpp
clang/test/CoverageMapping/macroparams2.c
clang/test/CoverageMapping/macros.c
clang/test/CoverageMapping/macroscopes.cpp
clang/test/CoverageMapping/moremacros.c

Removed: 




diff  --git a/clang/lib/CodeGen/CoverageMappingGen.cpp 
b/clang/lib/CodeGen/CoverageMappingGen.cpp
index 9a7096b8d1d0..e6e1b2111935 100644
--- a/clang/lib/CodeGen/CoverageMappingGen.cpp
+++ b/clang/lib/CodeGen/CoverageMappingGen.cpp
@@ -864,22 +864,13 @@ struct CounterCoverageMappingBuilder
   /// Find a valid gap range between \p AfterLoc and \p BeforeLoc.
   Optional findGapAreaBetween(SourceLocation AfterLoc,
SourceLocation BeforeLoc) {
-// If the start and end locations of the gap are both within the same macro
-// file, the range may not be in source order.
-if (AfterLoc.isMacroID() || BeforeLoc.isMacroID())
-  return None;
+AfterLoc = SM.getExpansionLoc(AfterLoc);
+BeforeLoc = SM.getExpansionLoc(BeforeLoc);
 if (!SM.isWrittenInSameFile(AfterLoc, BeforeLoc))
   return None;
 return {{AfterLoc, BeforeLoc}};
   }
 
-  /// Find the source range after \p AfterStmt and before \p BeforeStmt.
-  Optional findGapAreaBetween(const Stmt *AfterStmt,
-   const Stmt *BeforeStmt) {
-return findGapAreaBetween(getPreciseTokenLocEnd(getEnd(AfterStmt)),
-  getStart(BeforeStmt));
-  }
-
   /// Emit a gap region between \p StartLoc and \p EndLoc with the given count.
   void fillGapAreaWithCount(SourceLocation StartLoc, SourceLocation EndLoc,
 Counter Count) {
@@ -1044,7 +1035,8 @@ struct CounterCoverageMappingBuilder
 adjustForOutOfOrderTraversal(getEnd(S));
 
 // The body count applies to the area immediately after the increment.
-auto Gap = findGapAreaBetween(S->getCond(), S->getBody());
+auto Gap = findGapAreaBetween(getPreciseTokenLocEnd(S->getRParenLoc()),
+  getStart(S->getBody()));
 if (Gap)
   fillGapAreaWithCount(Gap->getBegin(), Gap->getEnd(), BodyCount);
 
@@ -1261,7 +1253,8 @@ struct CounterCoverageMappingBuilder
 propagateCounts(ParentCount, S->getCond());
 
 // The 'then' count applies to the area immediately after the condition.
-auto Gap = findGapAreaBetween(S->getCond(), S->getThen());
+auto Gap = findGapAreaBetween(getPreciseTokenLocEnd(S->getRParenLoc()),
+  getStart(S->getThen()));
 if (Gap)
   fillGapAreaWithCount(Gap->getBegin(), Gap->getEnd(), ThenCount);
 
@@ -1271,7 +1264,8 @@ struct CounterCoverageMappingBuilder
 Counter ElseCount = subtractCounters(ParentCount, ThenCount);
 if (const Stmt *Else = S->getElse()) {
   // The 'else' count applies to the area immediately after the 'then'.
-  Gap = findGapAreaBetween(S->getThen(), Else);
+  Gap = findGapAreaBetween(getPreciseTokenLocEnd(getEnd(S->getThen())),
+   getStart(Else));
   if (Gap)
 fillGapAreaWithCount(Gap->getBegin(), Gap->getEnd(), ElseCount);
   extendRegion(Else);

diff  --git a/clang/test/CoverageMapping/if.cpp 
b/clang/test/CoverageMapping/if.cpp
index 8ffc09d29a3c..5cbc974aaf04 100644
--- a/clang/test/CoverageMapping/if.cpp
+++ b/clang/test/CoverageMapping/if.cpp
@@ -44,10 +44,3 @@ int main() {// CHECK: File 0, 
[[@LINE]]:12 -> {{[0-9]+}}:2 =
 
   return 0;
 }
-
-#define FOO true
-
-// CHECK-LABEL: _Z7ternaryv:
-void ternary() {
-  true ? FOO : FOO; // CHECK-NOT: Gap,{{.*}}, [[@LINE]]:8 ->
-}

diff  --git a/clang/test/CoverageMapping/macro-expressions.cpp 
b/clang/test/CoverageMapping/macro-expressions.cpp
index 60afc5238b9e..6ac82523fef8 100644
--- a/clang/test/CoverageMapping/macro-expressions.cpp
+++ b/clang/test/CoverageMapping/macro-expressions.cpp
@@ -57,7 +57,8 @@ void foo(int i) {
   // CHECK: File 0, [[@LINE+1]]:10 -> [[@LINE+1]]:12 = #1
   if (0) {}
 
-  // CHECK-NEXT: Expansion,File 0, [[@LINE+2]]:7 -> [[@LINE+2]]:11 = #0
+  // CHECK-NEXT: Expansion,File 0, [[@LINE+3]]:7 -> [[@LINE+3]]:11 = #0
+  // CHECK-NEXT: Gap,File 0, [[@LINE+2]]:15 -> [[@LINE+2]]:16 = #2
   // CHECK-NEXT: File 0, [[@LINE+1]]:16 -> [[@LINE+1]]:18 = #2
   if (EXPR(i)) {}
   // CHECK-NEXT: Expansion,File 0, [[@LINE+2]]:9 -> [[@LINE+2]]:14 = (#0 + #3)
@@

[clang] 84fffa6 - [Coverage] Adjust skipped regions only if {Prev,Next}TokLoc is in the same file as regions' {start, end}Loc

2020-08-18 Thread Zequan Wu via cfe-commits

Author: Zequan Wu
Date: 2020-08-18T13:26:19-07:00
New Revision: 84fffa67283139954b7764328966b5f766db1003

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

LOG: [Coverage] Adjust skipped regions only if {Prev,Next}TokLoc is in the same 
file as regions' {start, end}Loc

Fix a bug if {Prev, Next}TokLoc is in different file from skipped regions' 
{start, end}Loc

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

Added: 
clang/test/CoverageMapping/Inputs/comment.h
clang/test/CoverageMapping/comment.cpp

Modified: 
clang/lib/CodeGen/CoverageMappingGen.cpp

Removed: 




diff  --git a/clang/lib/CodeGen/CoverageMappingGen.cpp 
b/clang/lib/CodeGen/CoverageMappingGen.cpp
index e6e1b2111935..8277804d27c0 100644
--- a/clang/lib/CodeGen/CoverageMappingGen.cpp
+++ b/clang/lib/CodeGen/CoverageMappingGen.cpp
@@ -44,7 +44,8 @@ CoverageMappingModuleGen::setUpCoverageCallbacks(Preprocessor 
&PP) {
   PP.setTokenWatcher([CoverageInfo](clang::Token Tok) {
 // Update previous token location.
 CoverageInfo->PrevTokLoc = Tok.getLocation();
-CoverageInfo->updateNextTokLoc(Tok.getLocation());
+if (Tok.getKind() != clang::tok::eod)
+  CoverageInfo->updateNextTokLoc(Tok.getLocation());
   });
   return CoverageInfo;
 }
@@ -305,20 +306,24 @@ class CoverageMappingBuilder {
   /// non-comment token. If shrinking the skipped range would make it empty,
   /// this returns None.
   Optional adjustSkippedRange(SourceManager &SM,
-  SpellingRegion SR,
+  SourceLocation LocStart,
+  SourceLocation LocEnd,
   SourceLocation PrevTokLoc,
   SourceLocation NextTokLoc) {
+SpellingRegion SR{SM, LocStart, LocEnd};
 // If Range begin location is invalid, it's not a comment region.
 if (PrevTokLoc.isInvalid())
   return SR;
 unsigned PrevTokLine = SM.getSpellingLineNumber(PrevTokLoc);
 unsigned NextTokLine = SM.getSpellingLineNumber(NextTokLoc);
 SpellingRegion newSR(SR);
-if (SR.LineStart == PrevTokLine) {
+if (SM.isWrittenInSameFile(LocStart, PrevTokLoc) &&
+SR.LineStart == PrevTokLine) {
   newSR.LineStart = SR.LineStart + 1;
   newSR.ColumnStart = 1;
 }
-if (SR.LineEnd == NextTokLine) {
+if (SM.isWrittenInSameFile(LocEnd, NextTokLoc) &&
+SR.LineEnd == NextTokLine) {
   newSR.LineEnd = SR.LineEnd - 1;
   newSR.ColumnEnd = SR.ColumnStart + 1;
 }
@@ -354,14 +359,13 @@ class CoverageMappingBuilder {
   auto CovFileID = getCoverageFileID(LocStart);
   if (!CovFileID)
 continue;
-  SpellingRegion SR{SM, LocStart, LocEnd};
-  if (Optional res =
-  adjustSkippedRange(SM, SR, I.PrevTokLoc, I.NextTokLoc))
-SR = res.getValue();
-  else
+  Optional SR =
+  adjustSkippedRange(SM, LocStart, LocEnd, I.PrevTokLoc, I.NextTokLoc);
+  if (!SR.hasValue())
 continue;
   auto Region = CounterMappingRegion::makeSkipped(
-  *CovFileID, SR.LineStart, SR.ColumnStart, SR.LineEnd, SR.ColumnEnd);
+  *CovFileID, SR->LineStart, SR->ColumnStart, SR->LineEnd,
+  SR->ColumnEnd);
   // Make sure that we only collect the regions that are inside
   // the source code of this function.
   if (Region.LineStart >= FileLineRanges[*CovFileID].first &&

diff  --git a/clang/test/CoverageMapping/Inputs/comment.h 
b/clang/test/CoverageMapping/Inputs/comment.h
new file mode 100644
index ..eec5833c2bd0
--- /dev/null
+++ b/clang/test/CoverageMapping/Inputs/comment.h
@@ -0,0 +1,6 @@
+
+
+
+
+
+x = 0;

diff  --git a/clang/test/CoverageMapping/comment.cpp 
b/clang/test/CoverageMapping/comment.cpp
new file mode 100644
index ..f8e4b4912e18
--- /dev/null
+++ b/clang/test/CoverageMapping/comment.cpp
@@ -0,0 +1,13 @@
+// RUN: %clang_cc1 -fprofile-instrument=clang -fcoverage-mapping 
-dump-coverage-mapping -emit-llvm-only %s | FileCheck %s
+
+int f() {
+  int x = 0;
+#include "Inputs/comment.h" /*
+*/
+  return x;
+}
+
+// CHECK: File 0, 3:9 -> 8:2 = #0
+// CHECK-NEXT: Expansion,File 0, 5:10 -> 5:28 = #0
+// CHECK-NEXT: Skipped,File 0, 6:1 -> 6:7 = 0
+// CHECK-NEXT: File 1, 1:1 -> 7:1 = #0



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


[clang] [lldb] [mlir] [compiler-rt] [llvm] [clang-tools-extra] [flang] [Profile] Add binary profile correlation to offload profile metadata at runtime. (PR #69493)

2023-11-06 Thread Zequan Wu via cfe-commits

ZequanWu wrote:

Ping.

https://github.com/llvm/llvm-project/pull/69493
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [compiler-rt] [llvm] [Profile] Refactor profile correlation. (PR #70856)

2023-11-08 Thread Zequan Wu via cfe-commits

ZequanWu wrote:

> If you omit the data and names sections from the object files, then 
> __llvm_profile_end_data() - __llvm_profile_begin_data() and 
> __llvm_profile_end_names() - __llvm_profile_begin_names() are both 0 and 
> there's no need for [special casing this in the 
> runtime](https://github.com/llvm/llvm-project/blob/24b11ba24da3e65f718391ccc85d4d22a081e893/compiler-rt/lib/profile/InstrProfilingBuffer.c#L59).

>From my experiments, I found that for debug info correlation 
>`__llvm_profile_end_data()` - `__llvm_profile_begin_data()` and 
>`__llvm_profile_end_names()` - `__llvm_profile_begin_names()` are both 0 at 
>runtime because `{__start_/__stop_}{__llvm_prf_names/data}` symbols are null 
>if there is no `__llvm_prf_names/data`. 

But for binary correlation, even though `__llvm_prf_names/data` don't have 
`SHF_ALLOC` flag so they are not loaded into memory, 
`__llvm_profile_end_data()` - `__llvm_profile_begin_data()` and 
`__llvm_profile_end_names()` - `__llvm_profile_begin_names()` still produces 
the size of name and data sections, that's why we need a bit in the global 
profile version variable to indicate they are empty at runtime. I feel like 
this is a bug in lld as __start_/__stop_ symbols for non allocated sections 
should be null. Even if we have a way to fix that, we still need the mode bit 
at llvm-profile merging step to indicate if the raw profile need debug 
info/binary to correlate. However, we can get ride of the runtime checking 
`__llvm_profile_has_correlation` to allow code compiled w/wo debug-info linked 
together works well.

https://github.com/llvm/llvm-project/pull/70856
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[compiler-rt] [clang-tools-extra] [llvm] [flang] [mlir] [clang] [lldb] [Profile] Add binary profile correlation to offload profile metadata at runtime. (PR #69493)

2023-11-10 Thread Zequan Wu via cfe-commits

ZequanWu wrote:

There are some discussions about this outside the PR:
https://github.com/llvm/llvm-project/pull/70856#issuecomment-1791465183
https://discourse.llvm.org/t/rfc-add-binary-profile-correlation-to-not-load-profile-metadata-sections-into-memory-at-runtime/74565/8

Some further discussion/pre-work needed before proceeding with this PR.

https://github.com/llvm/llvm-project/pull/69493
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[llvm] [compiler-rt] [clang] [Profile] Refactor profile correlation. (PR #70856)

2023-11-10 Thread Zequan Wu via cfe-commits

ZequanWu wrote:

Chatted with @MaskRay offline, we come to an agreement that it's not good to 
use relying on the bit in __llvm_profile_raw_version to decide whether or not 
to dump data/name sections at runtime for the reasons mentioned above. Sent a 
PR: #71996

> Even if we have a way to fix that, we still need the mode bit at llvm-profile 
> merging step to indicate if the raw profile need debug info/binary to 
> correlate. However, we can get ride of the runtime checking 
> __llvm_profile_has_correlation to allow code compiled w/wo debug-info linked 
> together works well.

I take back this word. When we do `llvm-profdata merge`, we use `-debug-info` 
to provide debug info file for correlation and the same could apply to binary 
correlation, a different flag. So, we know which correlation mode we are using.

https://github.com/llvm/llvm-project/pull/70856
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] Supports viewing class member variables in lambda when using the vs debugger (PR #71564)

2023-11-14 Thread Zequan Wu via cfe-commits


@@ -0,0 +1,48 @@
+// RUN: %clang_cl --target=x86_64-windows-msvc /c /Z7 -o %t.obj -- %s
+// RUN: llvm-pdbutil dump -all %t.obj | FileCheck %s
+
+class Foo {
+ public:
+  void foo() {
+int aa = 4;
+int bb = 5;
+int cc = 6;
+auto f = [=] {
+  int aaa = a + aa;
+  int bbb = b + bb;
+  int ccc = c + cc;
+};
+f();
+  }
+
+ private:
+  int a = 1;
+  int b = 2;
+  int c = 3;
+};
+
+int main() {
+  Foo f;
+  f.foo();
+
+  return 0;
+}
+
+// CHECK:   Types (.debug$T)
+// CHECK-NEXT: 
+// CHECK:[[FooIndex:0x[^ ]*]] | LF_CLASS [size = 36] `Foo`
+// CHECK: unique name: `.?AVFoo@@`
+// CHECK:[[FooIndex:0x[^ ]*]] | LF_FIELDLIST [size = 52]

ZequanWu wrote:

Nit: You are creating multiple `FooIndex` but not using it. The purpose of 
regex string substitution is to capture a pattern that will show up later. 
Different patterns should have different names. Here, it could be 
`[[FooFieldIndex:0x[^ ]*]]` In order to use the patterns later, use 
`0x[[FooFieldIndex]]`. Same applies to other indexes.

https://github.com/llvm/llvm-project/pull/71564
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[mlir] [llvm] [lldb] [flang] [clang] [compiler-rt] [clang-tools-extra] [Profile] Add binary profile correlation for code coverage. (PR #69493)

2023-12-05 Thread Zequan Wu via cfe-commits

ZequanWu wrote:

> Can you break up all the changes to tests that replace 
> `-debug-info-correlate` with `--profile-correlate=debug-info` into a separate 
> PR to reduce the size of this PR?

Done.

https://github.com/llvm/llvm-project/pull/69493
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [flang] [llvm] [clang-tools-extra] [mlir] [lldb] [compiler-rt] [Profile] Add binary profile correlation for code coverage. (PR #69493)

2023-12-05 Thread Zequan Wu via cfe-commits


@@ -702,6 +708,8 @@ serializeValueProfDataFrom(ValueProfRecordClosure *Closure,
 #define INSTR_PROF_COVMAP_COMMON __llvm_covmap
 #define INSTR_PROF_COVFUN_COMMON __llvm_covfun
 #define INSTR_PROF_ORDERFILE_COMMON __llvm_orderfile

ZequanWu wrote:

Done.

https://github.com/llvm/llvm-project/pull/69493
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[flang] [clang-tools-extra] [compiler-rt] [lldb] [llvm] [mlir] [clang] [Profile] Add binary profile correlation to offload profile metadata at runtime. (PR #69493)

2023-11-15 Thread Zequan Wu via cfe-commits

https://github.com/ZequanWu edited 
https://github.com/llvm/llvm-project/pull/69493
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[compiler-rt] [clang] [llvm] [clang-tools-extra] [lldb] [mlir] [flang] [Profile] Add binary profile correlation to offload profile metadata at runtime. (PR #69493)

2023-11-15 Thread Zequan Wu via cfe-commits


@@ -0,0 +1,11 @@
+; RUN: opt < %s -passes=instrprof -profile-correlate=binary -S | FileCheck %s

ZequanWu wrote:

Moved the test to `coverage.ll`

https://github.com/llvm/llvm-project/pull/69493
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang-tools-extra] [compiler-rt] [lldb] [llvm] [clang] [flang] [mlir] [Profile] Add binary profile correlation to offload profile metadata at runtime. (PR #69493)

2023-11-15 Thread Zequan Wu via cfe-commits


@@ -0,0 +1,9 @@
+// RUN: %clang_cc1  -fprofile-instrument=clang -fcoverage-mapping -emit-llvm 
-o - %s | FileCheck %s
+// RUN: %clang_cc1 -mllvm -profile-correlate=binary -fprofile-instrument=clang 
-fcoverage-mapping -emit-llvm -o - %s | FileCheck %s 
--check-prefix=BIN-CORRELATE

ZequanWu wrote:

Not applicable. Removed changes in Clang.

https://github.com/llvm/llvm-project/pull/69493
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[llvm] [clang] [flang] [clang-tools-extra] [lldb] [compiler-rt] [mlir] [Profile] Add binary profile correlation to offload profile metadata at runtime. (PR #69493)

2023-11-15 Thread Zequan Wu via cfe-commits


@@ -0,0 +1,46 @@
+// REQUIRES: linux || windows

ZequanWu wrote:

I think lld is not require, removed `-fuse-ld=lld`.

https://github.com/llvm/llvm-project/pull/69493
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[flang] [lldb] [compiler-rt] [llvm] [clang-tools-extra] [clang] [mlir] [Profile] Add binary profile correlation to offload profile metadata at runtime. (PR #69493)

2023-11-15 Thread Zequan Wu via cfe-commits


@@ -1829,6 +1833,22 @@ void CoverageMappingModuleGen::emit() {
  llvm::GlobalValue::InternalLinkage, NamesArrVal,
  llvm::getCoverageUnusedNamesVarName());
   }
+  const StringRef VarName(INSTR_PROF_QUOTE(INSTR_PROF_RAW_VERSION_VAR));
+  llvm::Type *IntTy64 = llvm::Type::getInt64Ty(Ctx);
+  uint64_t ProfileVersion = INSTR_PROF_RAW_VERSION;
+  if (llvm::ProfileCorrelate == llvm::InstrProfCorrelator::BINARY)
+ProfileVersion |= VARIANT_MASK_BIN_CORRELATE;
+  auto *VersionVariable = new llvm::GlobalVariable(
+  CGM.getModule(), llvm::Type::getInt64Ty(Ctx), true,
+  llvm::GlobalValue::WeakAnyLinkage,
+  llvm::Constant::getIntegerValue(IntTy64, llvm::APInt(64, 
ProfileVersion)),
+  VarName);
+  VersionVariable->setVisibility(llvm::GlobalValue::HiddenVisibility);
+  llvm::Triple TT(CGM.getModule().getTargetTriple());
+  if (TT.supportsCOMDAT()) {

ZequanWu wrote:

Not applicable. Removed changes in Clang.

https://github.com/llvm/llvm-project/pull/69493
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[lldb] [mlir] [llvm] [clang] [compiler-rt] [flang] [clang-tools-extra] [Profile] Add binary profile correlation to offload profile metadata at runtime. (PR #69493)

2023-11-15 Thread Zequan Wu via cfe-commits


@@ -46,14 +73,38 @@ const char *InstrProfCorrelator::NumCountersAttributeName = 
"Num Counters";
 
 llvm::Expected>
 InstrProfCorrelator::Context::get(std::unique_ptr Buffer,
-  const object::ObjectFile &Obj) {
+  const object::ObjectFile &Obj,
+  ProfCorrelatorKind FileKind) {
+  auto C = std::make_unique();
   auto CountersSection = getInstrProfSection(Obj, IPSK_cnts);
   if (auto Err = CountersSection.takeError())
 return std::move(Err);
-  auto C = std::make_unique();
+  if (FileKind == InstrProfCorrelator::BINARY) {
+auto DataSection = getInstrProfSection(Obj, IPSK_data);
+if (auto Err = DataSection.takeError())
+  return std::move(Err);
+auto DataOrErr = DataSection->getContents();
+if (!DataOrErr)
+  return DataOrErr.takeError();
+auto NameSection = getInstrProfSection(Obj, IPSK_name);
+if (auto Err = NameSection.takeError())
+  return std::move(Err);
+auto NameOrErr = NameSection->getContents();
+if (!NameOrErr)
+  return NameOrErr.takeError();
+C->DataStart = DataOrErr->data();
+C->DataEnd = DataOrErr->data() + DataOrErr->size();
+C->NameStart = NameOrErr->data();
+C->NameSize = NameOrErr->size();
+  }
   C->Buffer = std::move(Buffer);
   C->CountersSectionStart = CountersSection->getAddress();
   C->CountersSectionEnd = C->CountersSectionStart + CountersSection->getSize();
+  // In COFF object file, there's a null byte at the beginning of the counter
+  // section which doesn't exist in raw profile.
+  if (Obj.getTripleObjectFormat() == Triple::COFF)
+C->CountersSectionStart++;

ZequanWu wrote:

Done.

https://github.com/llvm/llvm-project/pull/69493
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [flang] [llvm] [clang-tools-extra] [lldb] [compiler-rt] [mlir] [Profile] Add binary profile correlation to offload profile metadata at runtime. (PR #69493)

2023-11-15 Thread Zequan Wu via cfe-commits

https://github.com/ZequanWu commented:

>  "binary" is ambiguous. I wonder whether object file correlation is better. 
> llvm-symbolizer has an option --obj=xxx.
llvm-symbolizer's `--obj` could take an pre-linking object file. But here we 
need to take post-linked binary for merging.

https://github.com/llvm/llvm-project/pull/69493
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[flang] [compiler-rt] [lldb] [llvm] [mlir] [clang] [clang-tools-extra] [Profile] Add binary profile correlation to offload profile metadata at runtime. (PR #69493)

2023-11-15 Thread Zequan Wu via cfe-commits


@@ -1331,6 +1336,18 @@ static int merge_main(int argc, const char *argv[]) {
"(default: 1)"));
 
   cl::ParseCommandLineOptions(argc, argv, "LLVM profile data merger\n");
+  if (!DebugInfoFilename.empty() && !BinaryFilename.empty()) {
+exitWithError("Expected only one of -debug-info, -binary-file");
+  }
+  std::string CorrelateFilename = "";

ZequanWu wrote:

Done.

https://github.com/llvm/llvm-project/pull/69493
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[compiler-rt] [flang] [mlir] [llvm] [clang] [clang-tools-extra] [lldb] [Profile] Add binary profile correlation to offload profile metadata at runtime. (PR #69493)

2023-11-15 Thread Zequan Wu via cfe-commits


@@ -1331,6 +1336,18 @@ static int merge_main(int argc, const char *argv[]) {
"(default: 1)"));
 
   cl::ParseCommandLineOptions(argc, argv, "LLVM profile data merger\n");
+  if (!DebugInfoFilename.empty() && !BinaryFilename.empty()) {
+exitWithError("Expected only one of -debug-info, -binary-file");

ZequanWu wrote:

Done.

https://github.com/llvm/llvm-project/pull/69493
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[lldb] [clang-tools-extra] [clang] [mlir] [flang] [llvm] [compiler-rt] [Profile] Add binary profile correlation to offload profile metadata at runtime. (PR #69493)

2023-11-15 Thread Zequan Wu via cfe-commits


@@ -1341,20 +1344,26 @@ void 
InstrProfiling::createDataVariable(InstrProfCntrInstBase *Inc,
   }
   auto *Data =
   new GlobalVariable(*M, DataTy, false, Linkage, nullptr, DataVarName);
-  // Reference the counter variable with a label difference (link-time
-  // constant).
-  auto *RelativeCounterPtr =
-  ConstantExpr::getSub(ConstantExpr::getPtrToInt(CounterPtr, IntPtrTy),
-   ConstantExpr::getPtrToInt(Data, IntPtrTy));
-
-  // Bitmaps are relative to the same data variable as profile counters.
+  Constant *RelativeCounterPtr;
   GlobalVariable *BitmapPtr = PD.RegionBitmaps;
   Constant *RelativeBitmapPtr = ConstantInt::get(IntPtrTy, 0);
-
-  if (BitmapPtr != nullptr) {
-RelativeBitmapPtr =
-ConstantExpr::getSub(ConstantExpr::getPtrToInt(BitmapPtr, IntPtrTy),
+  // By default counter ptr and bitmap ptr are address relative to data 
section.

ZequanWu wrote:

Done.

https://github.com/llvm/llvm-project/pull/69493
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[compiler-rt] [flang] [llvm] [lldb] [clang-tools-extra] [clang] [mlir] [Profile] Add binary profile correlation to offload profile metadata at runtime. (PR #69493)

2023-11-15 Thread Zequan Wu via cfe-commits


@@ -195,8 +195,14 @@ OPTIONS
 .. option:: --debug-info=
 
  Specify the executable or ``.dSYM`` that contains debug info for the raw 
profile.
- When ``-debug-info-correlate`` was used for instrumentation, use this option
- to correlate the raw profile.
+ When ``-profile-correlate=debug-info`` was used for instrumentation, use this

ZequanWu wrote:

Done.

https://github.com/llvm/llvm-project/pull/69493
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang-tools-extra] [mlir] [clang] [lldb] [compiler-rt] [llvm] [flang] [Profile] Add binary profile correlation to offload profile metadata at runtime. (PR #69493)

2023-11-15 Thread Zequan Wu via cfe-commits


@@ -0,0 +1,46 @@
+// REQUIRES: linux || windows
+// Default
+// RUN: %clang -o %t.normal -fprofile-instr-generate -fcoverage-mapping 
-fuse-ld=lld %S/Inputs/instrprof-debug-info-correlate-main.cpp 
%S/Inputs/instrprof-debug-info-correlate-foo.cpp
+// RUN: env LLVM_PROFILE_FILE=%t.profraw %run %t.normal
+// RUN: llvm-profdata merge -o %t.normal.profdata %t.profraw
+// RUN: llvm-cov report --instr-profile=%t.normal.profdata %t.normal > 
%t.normal.report
+// RUN: llvm-cov show --instr-profile=%t.normal.profdata %t.normal > 
%t.normal.show
+
+// With -profile-correlate=binary flag
+// RUN: %clang -o %t-1.exe -fprofile-instr-generate -fcoverage-mapping -mllvm 
-profile-correlate=binary -fuse-ld=lld 
%S/Inputs/instrprof-debug-info-correlate-main.cpp 
%S/Inputs/instrprof-debug-info-correlate-foo.cpp

ZequanWu wrote:

On Windows, it expands to `.tmp.exe`.

https://github.com/llvm/llvm-project/pull/69493
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang-tools-extra] [mlir] [clang] [lldb] [compiler-rt] [llvm] [flang] [Profile] Add binary profile correlation for code coverage. (PR #69493)

2023-11-15 Thread Zequan Wu via cfe-commits

https://github.com/ZequanWu edited 
https://github.com/llvm/llvm-project/pull/69493
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[flang] [compiler-rt] [mlir] [llvm] [clang] [clang-tools-extra] [lldb] [Profile] Add binary profile correlation for code coverage. (PR #69493)

2023-11-15 Thread Zequan Wu via cfe-commits

https://github.com/ZequanWu edited 
https://github.com/llvm/llvm-project/pull/69493
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[llvm] [compiler-rt] [clang-tools-extra] [lldb] [clang] [flang] [mlir] [Profile] Add binary profile correlation for code coverage. (PR #69493)

2023-11-15 Thread Zequan Wu via cfe-commits

https://github.com/ZequanWu edited 
https://github.com/llvm/llvm-project/pull/69493
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] Supports viewing class member variables in lambda when using the vs debugger (PR #71564)

2023-11-16 Thread Zequan Wu via cfe-commits


@@ -0,0 +1,48 @@
+// RUN: %clang_cl --target=x86_64-windows-msvc /c /Z7 -o %t.obj -- %s

ZequanWu wrote:

I think you are missing `-gcodeview` in the command line to emit the debug 
info. The change should reflect on a metadata. `llvm/test/DebugInfo/COFF` is 
the place to test the phase when IR being lowered to object file.  
`clang/test/CodeGenCXX` is for testing C++ code to IR.

https://github.com/llvm/llvm-project/pull/71564
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] Supports viewing class member variables in lambda when using the vs debugger (PR #71564)

2023-11-16 Thread Zequan Wu via cfe-commits

https://github.com/ZequanWu approved this pull request.


https://github.com/llvm/llvm-project/pull/71564
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[llvm] [clang-tools-extra] [lldb] [compiler-rt] [flang] [clang] [mlir] [Profile] Add binary profile correlation for code coverage. (PR #69493)

2023-11-16 Thread Zequan Wu via cfe-commits

ZequanWu wrote:

> Some further discussion/pre-work needed before proceeding with this PR.

These two discussions are addressed and this is ready to be reviewed.

1. Support for merging with multiple correlation files will be done in a 
separate change.
2. Removed the `VARIANT_MASK_BIN_CORRELATE` and runtime check for it to 
determine if name/data sections should be skipped. Instead, new section names 
are used (`__llvm_covdata` and `__llvm_covnames`).

https://github.com/llvm/llvm-project/pull/69493
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [Profile] Refactor profile correlation. (PR #70712)

2023-10-30 Thread Zequan Wu via cfe-commits

https://github.com/ZequanWu created 
https://github.com/llvm/llvm-project/pull/70712

Refactor some code from https://github.com/llvm/llvm-project/pull/69493. 

Rebase of https://github.com/llvm/llvm-project/pull/69656 on top of main as it 
was messed up.

>From e33d4e7d8324e8efb6f0c0ff5f3426a2e0a51ee1 Mon Sep 17 00:00:00 2001
From: Zequan Wu 
Date: Mon, 30 Oct 2023 15:45:08 -0400
Subject: [PATCH] Refactor profile correlation.

---
 clang/lib/CodeGen/BackendUtil.cpp |  14 ++-
 compiler-rt/lib/profile/InstrProfiling.c  |   4 +
 compiler-rt/lib/profile/InstrProfiling.h  |   6 ++
 .../lib/profile/InstrProfilingBuffer.c|  11 ++
 compiler-rt/lib/profile/InstrProfilingMerge.c |  11 +-
 .../lib/profile/InstrProfilingWriter.c|  21 ++--
 .../Darwin/instrprof-debug-info-correlate.c   |   4 +-
 .../instrprof-debug-info-correlate-warnings.c |   2 +-
 .../Linux/instrprof-debug-info-correlate.c|   6 +-
 .../instrprof-show-debug-info-correlation.c   |   6 +-
 llvm/docs/CommandGuide/llvm-profdata.rst  |   4 +-
 .../llvm/ProfileData/InstrProfCorrelator.h|  13 ++-
 .../llvm/ProfileData/InstrProfReader.h|   2 +
 .../Instrumentation/PGOInstrumentation.h  |   2 -
 .../CodeGen/TargetLoweringObjectFileImpl.cpp  |  19 
 llvm/lib/ProfileData/InstrProfCorrelator.cpp  | 100 +++---
 llvm/lib/ProfileData/InstrProfReader.cpp  |   4 +-
 .../Instrumentation/InstrProfiling.cpp|  18 ++--
 .../Instrumentation/PGOInstrumentation.cpp|   6 +-
 .../debug-info-correlate-coverage.ll  |   2 +-
 .../InstrProfiling/debug-info-correlate.ll|   2 +-
 llvm/tools/llvm-profdata/llvm-profdata.cpp|   9 +-
 22 files changed, 176 insertions(+), 90 deletions(-)

diff --git a/clang/lib/CodeGen/BackendUtil.cpp 
b/clang/lib/CodeGen/BackendUtil.cpp
index 70accce456d3c07..83b81a38a768523 100644
--- a/clang/lib/CodeGen/BackendUtil.cpp
+++ b/clang/lib/CodeGen/BackendUtil.cpp
@@ -42,6 +42,7 @@
 #include "llvm/Passes/PassBuilder.h"
 #include "llvm/Passes/PassPlugin.h"
 #include "llvm/Passes/StandardInstrumentations.h"
+#include "llvm/ProfileData/InstrProfCorrelator.h"
 #include "llvm/Support/BuryPointer.h"
 #include "llvm/Support/CommandLine.h"
 #include "llvm/Support/MemoryBuffer.h"
@@ -55,6 +56,7 @@
 #include "llvm/Target/TargetOptions.h"
 #include "llvm/TargetParser/SubtargetFeature.h"
 #include "llvm/TargetParser/Triple.h"
+#include "llvm/Transforms/HipStdPar/HipStdPar.h"
 #include "llvm/Transforms/IPO/EmbedBitcodePass.h"
 #include "llvm/Transforms/IPO/LowerTypeTests.h"
 #include "llvm/Transforms/IPO/ThinLTOBitcodeWriter.h"
@@ -78,7 +80,6 @@
 #include "llvm/Transforms/Scalar/EarlyCSE.h"
 #include "llvm/Transforms/Scalar/GVN.h"
 #include "llvm/Transforms/Scalar/JumpThreading.h"
-#include "llvm/Transforms/HipStdPar/HipStdPar.h"
 #include "llvm/Transforms/Utils/Debugify.h"
 #include "llvm/Transforms/Utils/EntryExitInstrumenter.h"
 #include "llvm/Transforms/Utils/ModuleUtils.h"
@@ -98,13 +99,18 @@ extern cl::opt PrintPipelinePasses;
 static cl::opt ClSanitizeOnOptimizerEarlyEP(
 "sanitizer-early-opt-ep", cl::Optional,
 cl::desc("Insert sanitizers on OptimizerEarlyEP."), cl::init(false));
-}
+
+extern cl::opt DebugInfoCorrelate;
+extern cl::opt ProfileCorrelate;
+} // namespace llvm
 
 namespace {
 
 // Default filename used for profile generation.
 std::string getDefaultProfileGenName() {
-  return DebugInfoCorrelate ? "default_%m.proflite" : "default_%m.profraw";
+  return DebugInfoCorrelate || ProfileCorrelate != InstrProfCorrelator::NONE
+ ? "default_%m.proflite"
+ : "default_%m.profraw";
 }
 
 class EmitAssemblyHelper {
@@ -197,7 +203,7 @@ class EmitAssemblyHelper {
   void EmitAssembly(BackendAction Action,
 std::unique_ptr OS);
 };
-}
+} // namespace
 
 static SanitizerCoverageOptions
 getSancovOptsFromCGOpts(const CodeGenOptions &CGOpts) {
diff --git a/compiler-rt/lib/profile/InstrProfiling.c 
b/compiler-rt/lib/profile/InstrProfiling.c
index da04d8ebdec95bb..7d69e37815c948f 100644
--- a/compiler-rt/lib/profile/InstrProfiling.c
+++ b/compiler-rt/lib/profile/InstrProfiling.c
@@ -89,3 +89,7 @@ COMPILER_RT_VISIBILITY void 
__llvm_profile_reset_counters(void) {
   }
   lprofSetProfileDumped(0);
 }
+
+inline int hasCorrelation() {
+  return (__llvm_profile_get_version() & VARIANT_MASK_DBG_CORRELATE) != 0ULL;
+}
diff --git a/compiler-rt/lib/profile/InstrProfiling.h 
b/compiler-rt/lib/profile/InstrProfiling.h
index e143149fca82707..b8104af5f12b910 100644
--- a/compiler-rt/lib/profile/InstrProfiling.h
+++ b/compiler-rt/lib/profile/InstrProfiling.h
@@ -261,6 +261,9 @@ uint64_t __llvm_profile_get_magic(void);
 /*! \brief Get the version of the file format. */
 uint64_t __llvm_profile_get_version(void);
 
+/*! \brief If the binary is compiled with profile correlation. */
+int hasCorrelation();
+
 /*! \brief Get the number of entries in the profile data section. */
 uint64_t __llvm_profile_get_num_data(const __llvm_p

[llvm] [compiler-rt] [clang] [Profile] Refactor profile correlation. (PR #70712)

2023-10-31 Thread Zequan Wu via cfe-commits

ZequanWu wrote:

I think it's fine to land as this is already reviewed & approved at 
https://github.com/llvm/llvm-project/pull/69656

https://github.com/llvm/llvm-project/pull/70712
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[llvm] [compiler-rt] [clang] [Profile] Refactor profile correlation. (PR #70712)

2023-10-31 Thread Zequan Wu via cfe-commits

https://github.com/ZequanWu closed 
https://github.com/llvm/llvm-project/pull/70712
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[compiler-rt] [clang] [llvm] [Profile] Refactor profile correlation. (PR #70712)

2023-10-31 Thread Zequan Wu via cfe-commits

ZequanWu wrote:

Reverted at db7a1ed9a22fadacfa651e88d0f75f365d44af9a.

The 
[build](https://lab.llvm.org/buildbot/#/builders/139/builds/52535/steps/6/logs/stdio)
 shows bunch linking failures, but I can build those failed targets locally.

https://github.com/llvm/llvm-project/pull/70712
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[compiler-rt] [clang] [llvm] [Profile] Refactor profile correlation. (PR #70712)

2023-10-31 Thread Zequan Wu via cfe-commits

ZequanWu wrote:

I can repro the linking failures when using the same cmake invocation. 

Here is the full command:
```
$ /usr/bin/c++ -std=c++11 -Wno-documentation-deprecated-sync -fPIC 
-fno-semantic-interposition -fvisibility-inlines-hidden -Werror=date-time 
-fno-lifetime-dse -Wall -Wextra -Wno-unused-parameter -Wwrite-strings 
-Wcast-qual -Wno-missing-field-initializers -pedantic -Wno-long-long 
-Wimplicit-fallthrough -Wno-maybe-uninitialized -Wno-nonnull 
-Wno-class-memaccess -Wno-redundant-move -Wno-pessimizing-move 
-Wno-noexcept-type -Wdelete-non-virtual-dtor -Wsuggest-override -Wno-comment 
-Wno-misleading-indentation -Wctad-maybe-unsupported -fdiagnostics-color 
-ffunction-sections -fdata-sections -O3 -DNDEBUG -Wl,--gc-sections 
unittests/IR/CMakeFiles/IRTests.dir/AbstractCallSiteTest.cpp.o 
unittests/IR/CMakeFiles/IRTests.dir/AsmWriterTest.cpp.o 
unittests/IR/CMakeFiles/IRTests.dir/AttributesTest.cpp.o 
unittests/IR/CMakeFiles/IRTests.dir/BasicBlockTest.cpp.o 
unittests/IR/CMakeFiles/IRTests.dir/CFGBuilder.cpp.o 
unittests/IR/CMakeFiles/IRTests.dir/ConstantRangeTest.cpp.o 
unittests/IR/CMakeFiles/IRTests.dir/ConstantsTest.cpp.o 
unittests/IR/CMakeFiles/IRTests.dir/DataLayoutTest.cpp.o 
unittests/IR/CMakeFiles/IRTests.dir/DebugInfoTest.cpp.o 
unittests/IR/CMakeFiles/IRTests.dir/DebugTypeODRUniquingTest.cpp.o 
unittests/IR/CMakeFiles/IRTests.dir/DemandedBitsTest.cpp.o 
unittests/IR/CMakeFiles/IRTests.dir/DominatorTreeTest.cpp.o 
unittests/IR/CMakeFiles/IRTests.dir/DominatorTreeBatchUpdatesTest.cpp.o 
unittests/IR/CMakeFiles/IRTests.dir/FunctionTest.cpp.o 
unittests/IR/CMakeFiles/IRTests.dir/PassBuilderCallbacksTest.cpp.o 
unittests/IR/CMakeFiles/IRTests.dir/IRBuilderTest.cpp.o 
unittests/IR/CMakeFiles/IRTests.dir/InstructionsTest.cpp.o 
unittests/IR/CMakeFiles/IRTests.dir/IntrinsicsTest.cpp.o 
unittests/IR/CMakeFiles/IRTests.dir/LegacyPassManagerTest.cpp.o 
unittests/IR/CMakeFiles/IRTests.dir/MDBuilderTest.cpp.o 
unittests/IR/CMakeFiles/IRTests.dir/ManglerTest.cpp.o 
unittests/IR/CMakeFiles/IRTests.dir/MetadataTest.cpp.o 
unittests/IR/CMakeFiles/IRTests.dir/ModuleTest.cpp.o 
unittests/IR/CMakeFiles/IRTests.dir/ModuleSummaryIndexTest.cpp.o 
unittests/IR/CMakeFiles/IRTests.dir/PassManagerTest.cpp.o 
unittests/IR/CMakeFiles/IRTests.dir/PatternMatch.cpp.o 
unittests/IR/CMakeFiles/IRTests.dir/ShuffleVectorInstTest.cpp.o 
unittests/IR/CMakeFiles/IRTests.dir/StructuralHashTest.cpp.o 
unittests/IR/CMakeFiles/IRTests.dir/TimePassesTest.cpp.o 
unittests/IR/CMakeFiles/IRTests.dir/TypesTest.cpp.o 
unittests/IR/CMakeFiles/IRTests.dir/UseTest.cpp.o 
unittests/IR/CMakeFiles/IRTests.dir/UserTest.cpp.o 
unittests/IR/CMakeFiles/IRTests.dir/ValueHandleTest.cpp.o 
unittests/IR/CMakeFiles/IRTests.dir/ValueMapTest.cpp.o 
unittests/IR/CMakeFiles/IRTests.dir/ValueTest.cpp.o 
unittests/IR/CMakeFiles/IRTests.dir/VectorBuilderTest.cpp.o 
unittests/IR/CMakeFiles/IRTests.dir/VectorTypesTest.cpp.o 
unittests/IR/CMakeFiles/IRTests.dir/VerifierTest.cpp.o 
unittests/IR/CMakeFiles/IRTests.dir/VPIntrinsicTest.cpp.o 
unittests/IR/CMakeFiles/IRTests.dir/CoreBindings.cpp.o -o unittests/IR/IRTests  
lib/libLLVMAnalysis.a  lib/libLLVMAsmParser.a  lib/libLLVMCore.a  
lib/libLLVMSupport.a  lib/libLLVMPasses.a  lib/libLLVMTargetParser.a  
lib/libLLVMTransformUtils.a  lib/libLLVMScalarOpts.a  lib/libLLVMSupport.a  
lib/libllvm_gtest_main.a  lib/libllvm_gtest.a  lib/libLLVMTestingSupport.a  
lib/libLLVMCodeGen.a  lib/libLLVMCodeGenTypes.a  lib/libLLVMCoroutines.a  
lib/libLLVMHipStdPar.a  lib/libLLVMipo.a  lib/libLLVMBitWriter.a  
lib/libLLVMFrontendOpenMP.a  lib/libLLVMScalarOpts.a  
lib/libLLVMAggressiveInstCombine.a  lib/libLLVMFrontendOffloading.a  
lib/libLLVMLinker.a  lib/libLLVMInstCombine.a  lib/libLLVMIRPrinter.a  
lib/libLLVMObjCARCOpts.a  lib/libLLVMTarget.a  lib/libLLVMVectorize.a  
lib/libLLVMInstrumentation.a  lib/libLLVMTransformUtils.a  
lib/libLLVMAnalysis.a  lib/libLLVMProfileData.a  lib/libLLVMSymbolize.a  
lib/libLLVMDebugInfoPDB.a  lib/libLLVMDebugInfoMSF.a  lib/libLLVMDebugInfoBTF.a 
 lib/libLLVMDebugInfoDWARF.a  lib/libLLVMObject.a  lib/libLLVMIRReader.a  
lib/libLLVMAsmParser.a  lib/libLLVMBitReader.a  lib/libLLVMCore.a  
lib/libLLVMRemarks.a  lib/libLLVMBitstreamReader.a  lib/libLLVMMCParser.a  
lib/libLLVMTextAPI.a  lib/libLLVMMC.a  lib/libLLVMBinaryFormat.a  
lib/libLLVMTargetParser.a  lib/libLLVMDebugInfoCodeView.a  lib/libllvm_gtest.a  
lib/libLLVMSupport.a  lib/libLLVMDemangle.a  -lrt  -ldl  -lm  
/usr/lib/x86_64-linux-gnu/libz.so  /usr/lib/x86_64-linux-gnu/libzstd.so  
/usr/lib/x86_64-linux-gnu/libtinfo.so  -lpthread

/usr/bin/ld: lib/libLLVMInstrumentation.a(InstrProfiling.cpp.o): in function 
`llvm::InstrProfiling::lowerValueProfileInst(llvm::InstrProfValueProfileInst*) 
[clone .localalias]':
InstrProfiling.cpp:(.text._ZN4llvm14InstrProfiling21lowerValueProfileInstEPNS_25InstrProfValueProfileInstE+0x1a):
 undefined reference to `llvm::DebugInfoCorrelate'
/usr/bin/ld: 
InstrProfiling.cpp:(.text._ZN4llvm14Ins

[clang] [clang-tools-extra] [llvm] [llvm-profdata] Emit warning when counter value is greater than 2^56. (PR #69513)

2023-10-31 Thread Zequan Wu via cfe-commits

https://github.com/ZequanWu updated 
https://github.com/llvm/llvm-project/pull/69513

>From 9a1af6e1d47ab622979796f2319edec8a9c77928 Mon Sep 17 00:00:00 2001
From: Zequan Wu 
Date: Wed, 18 Oct 2023 16:28:30 -0400
Subject: [PATCH 1/6] [llvm-profdata] Emit error when counter value is greater
 than 2^56.

---
 llvm/lib/ProfileData/InstrProfReader.cpp| 13 +++--
 .../malformed-num-counters-zero.test| 17 +++--
 2 files changed, 26 insertions(+), 4 deletions(-)

diff --git a/llvm/lib/ProfileData/InstrProfReader.cpp 
b/llvm/lib/ProfileData/InstrProfReader.cpp
index a920a31d0a4b229..d62a816cdeed4e6 100644
--- a/llvm/lib/ProfileData/InstrProfReader.cpp
+++ b/llvm/lib/ProfileData/InstrProfReader.cpp
@@ -38,6 +38,9 @@
 
 using namespace llvm;
 
+// Maxium counter value 2^56.
+static uint64_t MaxCounterValue = 0xff;
+
 // Extracts the variant information from the top 32 bits in the version and
 // returns an enum specifying the variants present.
 static InstrProfKind getProfileKindFromVersion(uint64_t Version) {
@@ -676,8 +679,14 @@ Error RawInstrProfReader::readRawCounts(
   // A value of zero signifies the block is covered.
   Record.Counts.push_back(*Ptr == 0 ? 1 : 0);
 } else {
-  const auto *CounterValue = reinterpret_cast(Ptr);
-  Record.Counts.push_back(swap(*CounterValue));
+  uint64_t CounterValue = swap(*reinterpret_cast(Ptr));
+  if (CounterValue > MaxCounterValue)
+return error(instrprof_error::malformed,
+ ("counter value " + Twine(CounterValue) +
+  " is greater than " + Twine(MaxCounterValue))
+ .str());
+
+  Record.Counts.push_back(CounterValue);
 }
   }
 
diff --git a/llvm/test/tools/llvm-profdata/malformed-num-counters-zero.test 
b/llvm/test/tools/llvm-profdata/malformed-num-counters-zero.test
index b718cf0fd8e9723..011c1cbf73af3bb 100644
--- a/llvm/test/tools/llvm-profdata/malformed-num-counters-zero.test
+++ b/llvm/test/tools/llvm-profdata/malformed-num-counters-zero.test
@@ -35,11 +35,24 @@ RUN: printf '\1\0\0\0\0\0\0\0' >> %t.profraw
 RUN: printf '\0\0\4\0\1\0\0\0' >> %t.profraw
 RUN: printf '\0\0\0\0\0\0\0\0' >> %t.profraw
 RUN: printf '\0\0\0\0\0\0\0\0' >> %t.profraw
+
+// Make a copy for another test.
+RUN: cp %t.profraw %t1.profraw
+
 // Make NumCounters = 0 so that we get "number of counters is zero" error 
message
 RUN: printf '\0\0\0\0\0\0\0\0' >> %t.profraw
 
 RUN: printf '\023\0\0\0\0\0\0\0' >> %t.profraw
 RUN: printf '\3\0foo\0\0\0' >> %t.profraw
 
-RUN: not llvm-profdata show %t.profraw 2>&1 | FileCheck %s
-CHECK: malformed instrumentation profile data: number of counters is zero
+RUN: not llvm-profdata show %t.profraw 2>&1 | FileCheck %s --check-prefix=ZERO
+ZERO: malformed instrumentation profile data: number of counters is zero
+
+// Test a counter value greater than 2^56.
+RUN: printf '\1\0\0\0\0\0\0\0' >> %t1.profraw
+
+RUN: printf '\0\0\0\0\0\0\0\1' >> %t1.profraw
+RUN: printf '\3\0foo\0\0\0' >> %t1.profraw
+
+RUN: not llvm-profdata show %t1.profraw 2>&1 | FileCheck %s --check-prefix=MAX
+MAX: malformed instrumentation profile data: counter value 72057594037927936 
is greater than 72057594037927935

>From 5d4c2ce9b8f5c49041bcbdf12f7890f75e4754c7 Mon Sep 17 00:00:00 2001
From: Zequan Wu 
Date: Thu, 19 Oct 2023 15:41:38 -0400
Subject: [PATCH 2/6] address comments

---
 llvm/include/llvm/ProfileData/InstrProfReader.h|  3 +++
 llvm/lib/ProfileData/InstrProfReader.cpp   | 10 +++---
 .../llvm-profdata/malformed-num-counters-zero.test |  6 +++---
 3 files changed, 9 insertions(+), 10 deletions(-)

diff --git a/llvm/include/llvm/ProfileData/InstrProfReader.h 
b/llvm/include/llvm/ProfileData/InstrProfReader.h
index 5f54cbeb1b01eda..e62ee42d09f4145 100644
--- a/llvm/include/llvm/ProfileData/InstrProfReader.h
+++ b/llvm/include/llvm/ProfileData/InstrProfReader.h
@@ -341,6 +341,9 @@ class RawInstrProfReader : public InstrProfReader {
   /// Start address of binary id length and data pairs.
   const uint8_t *BinaryIdsStart;
 
+  // Maxium counter value 2^56.
+  static const uint64_t MaxCounterValue = (1ULL << 56);
+
 public:
   RawInstrProfReader(std::unique_ptr DataBuffer,
  const InstrProfCorrelator *Correlator)
diff --git a/llvm/lib/ProfileData/InstrProfReader.cpp 
b/llvm/lib/ProfileData/InstrProfReader.cpp
index d62a816cdeed4e6..3a1d5ef3a9d827e 100644
--- a/llvm/lib/ProfileData/InstrProfReader.cpp
+++ b/llvm/lib/ProfileData/InstrProfReader.cpp
@@ -27,6 +27,7 @@
 #include "llvm/Support/MemoryBuffer.h"
 #include "llvm/Support/SwapByteOrder.h"
 #include "llvm/Support/VirtualFileSystem.h"
+#include "llvm/Support/WithColor.h"
 #include 
 #include 
 #include 
@@ -38,9 +39,6 @@
 
 using namespace llvm;
 
-// Maxium counter value 2^56.
-static uint64_t MaxCounterValue = 0xff;
-
 // Extracts the variant information from the top 32 bits in the version and
 // returns an enum specify

[clang] [clang-tools-extra] [llvm] [llvm-profdata] Emit warning when counter value is greater than 2^56. (PR #69513)

2023-10-31 Thread Zequan Wu via cfe-commits

ZequanWu wrote:

Ping.

https://github.com/llvm/llvm-project/pull/69513
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [llvm] [compiler-rt] [Profile] Refactor profile correlation. (PR #70856)

2023-10-31 Thread Zequan Wu via cfe-commits

https://github.com/ZequanWu created 
https://github.com/llvm/llvm-project/pull/70856

Refactor some code from https://github.com/llvm/llvm-project/pull/69493.

#70712 was reverted due to linking failures. So, I removed 
`-profile-correlate=` flag and kept `-debug-info-correlate` in this change. 

>From e33d4e7d8324e8efb6f0c0ff5f3426a2e0a51ee1 Mon Sep 17 00:00:00 2001
From: Zequan Wu 
Date: Mon, 30 Oct 2023 15:45:08 -0400
Subject: [PATCH 1/4] Refactor profile correlation.

---
 clang/lib/CodeGen/BackendUtil.cpp |  14 ++-
 compiler-rt/lib/profile/InstrProfiling.c  |   4 +
 compiler-rt/lib/profile/InstrProfiling.h  |   6 ++
 .../lib/profile/InstrProfilingBuffer.c|  11 ++
 compiler-rt/lib/profile/InstrProfilingMerge.c |  11 +-
 .../lib/profile/InstrProfilingWriter.c|  21 ++--
 .../Darwin/instrprof-debug-info-correlate.c   |   4 +-
 .../instrprof-debug-info-correlate-warnings.c |   2 +-
 .../Linux/instrprof-debug-info-correlate.c|   6 +-
 .../instrprof-show-debug-info-correlation.c   |   6 +-
 llvm/docs/CommandGuide/llvm-profdata.rst  |   4 +-
 .../llvm/ProfileData/InstrProfCorrelator.h|  13 ++-
 .../llvm/ProfileData/InstrProfReader.h|   2 +
 .../Instrumentation/PGOInstrumentation.h  |   2 -
 .../CodeGen/TargetLoweringObjectFileImpl.cpp  |  19 
 llvm/lib/ProfileData/InstrProfCorrelator.cpp  | 100 +++---
 llvm/lib/ProfileData/InstrProfReader.cpp  |   4 +-
 .../Instrumentation/InstrProfiling.cpp|  18 ++--
 .../Instrumentation/PGOInstrumentation.cpp|   6 +-
 .../debug-info-correlate-coverage.ll  |   2 +-
 .../InstrProfiling/debug-info-correlate.ll|   2 +-
 llvm/tools/llvm-profdata/llvm-profdata.cpp|   9 +-
 22 files changed, 176 insertions(+), 90 deletions(-)

diff --git a/clang/lib/CodeGen/BackendUtil.cpp 
b/clang/lib/CodeGen/BackendUtil.cpp
index 70accce456d3c07..83b81a38a768523 100644
--- a/clang/lib/CodeGen/BackendUtil.cpp
+++ b/clang/lib/CodeGen/BackendUtil.cpp
@@ -42,6 +42,7 @@
 #include "llvm/Passes/PassBuilder.h"
 #include "llvm/Passes/PassPlugin.h"
 #include "llvm/Passes/StandardInstrumentations.h"
+#include "llvm/ProfileData/InstrProfCorrelator.h"
 #include "llvm/Support/BuryPointer.h"
 #include "llvm/Support/CommandLine.h"
 #include "llvm/Support/MemoryBuffer.h"
@@ -55,6 +56,7 @@
 #include "llvm/Target/TargetOptions.h"
 #include "llvm/TargetParser/SubtargetFeature.h"
 #include "llvm/TargetParser/Triple.h"
+#include "llvm/Transforms/HipStdPar/HipStdPar.h"
 #include "llvm/Transforms/IPO/EmbedBitcodePass.h"
 #include "llvm/Transforms/IPO/LowerTypeTests.h"
 #include "llvm/Transforms/IPO/ThinLTOBitcodeWriter.h"
@@ -78,7 +80,6 @@
 #include "llvm/Transforms/Scalar/EarlyCSE.h"
 #include "llvm/Transforms/Scalar/GVN.h"
 #include "llvm/Transforms/Scalar/JumpThreading.h"
-#include "llvm/Transforms/HipStdPar/HipStdPar.h"
 #include "llvm/Transforms/Utils/Debugify.h"
 #include "llvm/Transforms/Utils/EntryExitInstrumenter.h"
 #include "llvm/Transforms/Utils/ModuleUtils.h"
@@ -98,13 +99,18 @@ extern cl::opt PrintPipelinePasses;
 static cl::opt ClSanitizeOnOptimizerEarlyEP(
 "sanitizer-early-opt-ep", cl::Optional,
 cl::desc("Insert sanitizers on OptimizerEarlyEP."), cl::init(false));
-}
+
+extern cl::opt DebugInfoCorrelate;
+extern cl::opt ProfileCorrelate;
+} // namespace llvm
 
 namespace {
 
 // Default filename used for profile generation.
 std::string getDefaultProfileGenName() {
-  return DebugInfoCorrelate ? "default_%m.proflite" : "default_%m.profraw";
+  return DebugInfoCorrelate || ProfileCorrelate != InstrProfCorrelator::NONE
+ ? "default_%m.proflite"
+ : "default_%m.profraw";
 }
 
 class EmitAssemblyHelper {
@@ -197,7 +203,7 @@ class EmitAssemblyHelper {
   void EmitAssembly(BackendAction Action,
 std::unique_ptr OS);
 };
-}
+} // namespace
 
 static SanitizerCoverageOptions
 getSancovOptsFromCGOpts(const CodeGenOptions &CGOpts) {
diff --git a/compiler-rt/lib/profile/InstrProfiling.c 
b/compiler-rt/lib/profile/InstrProfiling.c
index da04d8ebdec95bb..7d69e37815c948f 100644
--- a/compiler-rt/lib/profile/InstrProfiling.c
+++ b/compiler-rt/lib/profile/InstrProfiling.c
@@ -89,3 +89,7 @@ COMPILER_RT_VISIBILITY void 
__llvm_profile_reset_counters(void) {
   }
   lprofSetProfileDumped(0);
 }
+
+inline int hasCorrelation() {
+  return (__llvm_profile_get_version() & VARIANT_MASK_DBG_CORRELATE) != 0ULL;
+}
diff --git a/compiler-rt/lib/profile/InstrProfiling.h 
b/compiler-rt/lib/profile/InstrProfiling.h
index e143149fca82707..b8104af5f12b910 100644
--- a/compiler-rt/lib/profile/InstrProfiling.h
+++ b/compiler-rt/lib/profile/InstrProfiling.h
@@ -261,6 +261,9 @@ uint64_t __llvm_profile_get_magic(void);
 /*! \brief Get the version of the file format. */
 uint64_t __llvm_profile_get_version(void);
 
+/*! \brief If the binary is compiled with profile correlation. */
+int hasCorrelation();
+
 /*! \brief Get the number of entries in the profile data section. */
 uint64

[clang] [llvm] [clang-tools-extra] [llvm-profdata] Emit warning when counter value is greater than 2^56. (PR #69513)

2023-10-31 Thread Zequan Wu via cfe-commits

https://github.com/ZequanWu updated 
https://github.com/llvm/llvm-project/pull/69513

>From 9a1af6e1d47ab622979796f2319edec8a9c77928 Mon Sep 17 00:00:00 2001
From: Zequan Wu 
Date: Wed, 18 Oct 2023 16:28:30 -0400
Subject: [PATCH 1/7] [llvm-profdata] Emit error when counter value is greater
 than 2^56.

---
 llvm/lib/ProfileData/InstrProfReader.cpp| 13 +++--
 .../malformed-num-counters-zero.test| 17 +++--
 2 files changed, 26 insertions(+), 4 deletions(-)

diff --git a/llvm/lib/ProfileData/InstrProfReader.cpp 
b/llvm/lib/ProfileData/InstrProfReader.cpp
index a920a31d0a4b229..d62a816cdeed4e6 100644
--- a/llvm/lib/ProfileData/InstrProfReader.cpp
+++ b/llvm/lib/ProfileData/InstrProfReader.cpp
@@ -38,6 +38,9 @@
 
 using namespace llvm;
 
+// Maxium counter value 2^56.
+static uint64_t MaxCounterValue = 0xff;
+
 // Extracts the variant information from the top 32 bits in the version and
 // returns an enum specifying the variants present.
 static InstrProfKind getProfileKindFromVersion(uint64_t Version) {
@@ -676,8 +679,14 @@ Error RawInstrProfReader::readRawCounts(
   // A value of zero signifies the block is covered.
   Record.Counts.push_back(*Ptr == 0 ? 1 : 0);
 } else {
-  const auto *CounterValue = reinterpret_cast(Ptr);
-  Record.Counts.push_back(swap(*CounterValue));
+  uint64_t CounterValue = swap(*reinterpret_cast(Ptr));
+  if (CounterValue > MaxCounterValue)
+return error(instrprof_error::malformed,
+ ("counter value " + Twine(CounterValue) +
+  " is greater than " + Twine(MaxCounterValue))
+ .str());
+
+  Record.Counts.push_back(CounterValue);
 }
   }
 
diff --git a/llvm/test/tools/llvm-profdata/malformed-num-counters-zero.test 
b/llvm/test/tools/llvm-profdata/malformed-num-counters-zero.test
index b718cf0fd8e9723..011c1cbf73af3bb 100644
--- a/llvm/test/tools/llvm-profdata/malformed-num-counters-zero.test
+++ b/llvm/test/tools/llvm-profdata/malformed-num-counters-zero.test
@@ -35,11 +35,24 @@ RUN: printf '\1\0\0\0\0\0\0\0' >> %t.profraw
 RUN: printf '\0\0\4\0\1\0\0\0' >> %t.profraw
 RUN: printf '\0\0\0\0\0\0\0\0' >> %t.profraw
 RUN: printf '\0\0\0\0\0\0\0\0' >> %t.profraw
+
+// Make a copy for another test.
+RUN: cp %t.profraw %t1.profraw
+
 // Make NumCounters = 0 so that we get "number of counters is zero" error 
message
 RUN: printf '\0\0\0\0\0\0\0\0' >> %t.profraw
 
 RUN: printf '\023\0\0\0\0\0\0\0' >> %t.profraw
 RUN: printf '\3\0foo\0\0\0' >> %t.profraw
 
-RUN: not llvm-profdata show %t.profraw 2>&1 | FileCheck %s
-CHECK: malformed instrumentation profile data: number of counters is zero
+RUN: not llvm-profdata show %t.profraw 2>&1 | FileCheck %s --check-prefix=ZERO
+ZERO: malformed instrumentation profile data: number of counters is zero
+
+// Test a counter value greater than 2^56.
+RUN: printf '\1\0\0\0\0\0\0\0' >> %t1.profraw
+
+RUN: printf '\0\0\0\0\0\0\0\1' >> %t1.profraw
+RUN: printf '\3\0foo\0\0\0' >> %t1.profraw
+
+RUN: not llvm-profdata show %t1.profraw 2>&1 | FileCheck %s --check-prefix=MAX
+MAX: malformed instrumentation profile data: counter value 72057594037927936 
is greater than 72057594037927935

>From 5d4c2ce9b8f5c49041bcbdf12f7890f75e4754c7 Mon Sep 17 00:00:00 2001
From: Zequan Wu 
Date: Thu, 19 Oct 2023 15:41:38 -0400
Subject: [PATCH 2/7] address comments

---
 llvm/include/llvm/ProfileData/InstrProfReader.h|  3 +++
 llvm/lib/ProfileData/InstrProfReader.cpp   | 10 +++---
 .../llvm-profdata/malformed-num-counters-zero.test |  6 +++---
 3 files changed, 9 insertions(+), 10 deletions(-)

diff --git a/llvm/include/llvm/ProfileData/InstrProfReader.h 
b/llvm/include/llvm/ProfileData/InstrProfReader.h
index 5f54cbeb1b01eda..e62ee42d09f4145 100644
--- a/llvm/include/llvm/ProfileData/InstrProfReader.h
+++ b/llvm/include/llvm/ProfileData/InstrProfReader.h
@@ -341,6 +341,9 @@ class RawInstrProfReader : public InstrProfReader {
   /// Start address of binary id length and data pairs.
   const uint8_t *BinaryIdsStart;
 
+  // Maxium counter value 2^56.
+  static const uint64_t MaxCounterValue = (1ULL << 56);
+
 public:
   RawInstrProfReader(std::unique_ptr DataBuffer,
  const InstrProfCorrelator *Correlator)
diff --git a/llvm/lib/ProfileData/InstrProfReader.cpp 
b/llvm/lib/ProfileData/InstrProfReader.cpp
index d62a816cdeed4e6..3a1d5ef3a9d827e 100644
--- a/llvm/lib/ProfileData/InstrProfReader.cpp
+++ b/llvm/lib/ProfileData/InstrProfReader.cpp
@@ -27,6 +27,7 @@
 #include "llvm/Support/MemoryBuffer.h"
 #include "llvm/Support/SwapByteOrder.h"
 #include "llvm/Support/VirtualFileSystem.h"
+#include "llvm/Support/WithColor.h"
 #include 
 #include 
 #include 
@@ -38,9 +39,6 @@
 
 using namespace llvm;
 
-// Maxium counter value 2^56.
-static uint64_t MaxCounterValue = 0xff;
-
 // Extracts the variant information from the top 32 bits in the version and
 // returns an enum specify

[clang] [llvm] [clang-tools-extra] [llvm-profdata] Emit warning when counter value is greater than 2^56. (PR #69513)

2023-10-31 Thread Zequan Wu via cfe-commits

https://github.com/ZequanWu closed 
https://github.com/llvm/llvm-project/pull/69513
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [llvm] [compiler-rt] [Profile] Refactor profile correlation. (PR #70856)

2023-10-31 Thread Zequan Wu via cfe-commits

ZequanWu wrote:

Sorry for so many noise regarding this change.

https://github.com/llvm/llvm-project/pull/70856
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[llvm] [clang] [clang-tools-extra] [llvm-profdata] Emit warning when counter value is greater than 2^56. (PR #69513)

2023-11-01 Thread Zequan Wu via cfe-commits

ZequanWu wrote:

> Just to double check: the commit message says "emit warning", but it should 
> error by default, right?

Yes, -failure-mode=any is default, which throws an error if there is any.

https://github.com/llvm/llvm-project/pull/69513
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [compiler-rt] [llvm] [Profile] Refactor profile correlation. (PR #70856)

2023-11-01 Thread Zequan Wu via cfe-commits

ZequanWu wrote:

> Sounds fine to me, but I guess I don't understand why `-profile-correlate=` 
> doesn't work. Do you still plan to add the flag later?

I haven't found a way to share information (whether of not binary correlation 
is enabled) between CodeGen(TargetLoweringObjectFileImpl.cpp) and 
Instrumentation(InstrProfiling.cpp) components. The explanation is 
here: 
https://discourse.llvm.org/t/rfc-add-binary-profile-correlation-to-not-load-profile-metadata-sections-into-memory-at-runtime/74565#use-temporary-section-names-6.

https://github.com/llvm/llvm-project/pull/70856
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[compiler-rt] [llvm] [clang] [Profile] Refactor profile correlation. (PR #70856)

2023-11-01 Thread Zequan Wu via cfe-commits

https://github.com/ZequanWu closed 
https://github.com/llvm/llvm-project/pull/70856
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[compiler-rt] [llvm] [clang] [Profile] Refactor profile correlation. (PR #70856)

2023-11-02 Thread Zequan Wu via cfe-commits

ZequanWu wrote:

> @ZequanWu this seems to cause issues on macOS: 
> https://green.lab.llvm.org/green/job/clang-stage1-RA/36184/console
> 
> ```
> Profile-x86_64 :: Darwin/instrprof-debug-info-correlate.c
> Profile-x86_64 :: instrprof-darwin-
> Profile-x86_64h :: Darwin/instrprof-debug-info-correlate.c
> Profile-x86_64h :: instrprof-darwin-exports.c
> ```
> 
> are failing, could you please take a look or revert?

It should be fixed by 
https://github.com/llvm/llvm-project/commit/56e205a89cbb114750f2bd3f5cfbd19e209d018a.

https://github.com/llvm/llvm-project/pull/70856
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [llvm] [compiler-rt] [Profile] Refactor profile correlation. (PR #70856)

2023-11-02 Thread Zequan Wu via cfe-commits

ZequanWu wrote:

> > Sounds fine to me, but I guess I don't understand why `-profile-correlate=` 
> > doesn't work. Do you still plan to add the flag later?
> 
> I haven't found a way to share information (whether of not binary correlation 
> is enabled) between CodeGen(TargetLoweringObjectFileImpl.cpp) and 
> Instrumentation(InstrProfiling.cpp) components. The explanation is here: 
> https://discourse.llvm.org/t/rfc-add-binary-profile-correlation-to-not-load-profile-metadata-sections-into-memory-at-runtime/74565#use-temporary-section-names-6.

Oh, actually, we can have -profile-correlate flag just need to define it at 
InstrProfCorrelator.cpp (ProfileData component), which is less desired but 
working as discussed at 
https://github.com/llvm/llvm-project/pull/69656#discussion_r1372179620. 

https://github.com/llvm/llvm-project/pull/70856
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [llvm] [compiler-rt] [Profile] Refactor profile correlation. (PR #70856)

2023-11-02 Thread Zequan Wu via cfe-commits


@@ -261,6 +261,9 @@ uint64_t __llvm_profile_get_magic(void);
 /*! \brief Get the version of the file format. */
 uint64_t __llvm_profile_get_version(void);
 
+/*! \brief If the binary is compiled with profile correlation. */
+int hasCorrelation();

ZequanWu wrote:

Renamed to `__llvm_profile_has_correlation` at 
https://github.com/llvm/llvm-project/commit/7fa9930847bbef4319c2d2e9c782eb5c8e6b1892

https://github.com/llvm/llvm-project/pull/70856
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[compiler-rt] [llvm] [clang] [Profile] Refactor profile correlation. (PR #70856)

2023-11-02 Thread Zequan Wu via cfe-commits


@@ -89,3 +89,7 @@ COMPILER_RT_VISIBILITY void 
__llvm_profile_reset_counters(void) {
   }
   lprofSetProfileDumped(0);
 }
+
+inline int hasCorrelation() {

ZequanWu wrote:

COMPILER_RT_VISIBILITY is added at 
https://github.com/llvm/llvm-project/commit/56e205a89cbb114750f2bd3f5cfbd19e209d018a.

https://github.com/llvm/llvm-project/pull/70856
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [llvm] [mlir] [flang] [compiler-rt] [clang-tools-extra] [lldb] [Profile] Add binary profile correlation to offload profile metadata at runtime. (PR #69493)

2023-11-02 Thread Zequan Wu via cfe-commits

https://github.com/ZequanWu updated 
https://github.com/llvm/llvm-project/pull/69493

>From 3a394ce5d4d7d91251337bd0a2c1c1a074eb37e6 Mon Sep 17 00:00:00 2001
From: Zequan Wu 
Date: Tue, 17 Oct 2023 19:24:12 -0400
Subject: [PATCH 1/5] [Profile] Add binary profile correlation.

---
 clang/lib/CodeGen/BackendUtil.cpp |  10 +-
 clang/lib/CodeGen/CoverageMappingGen.cpp  |  20 ++
 .../CodeGen/coverage-profile-raw-version.c|   9 +
 compiler-rt/include/profile/InstrProfData.inc |   2 +
 compiler-rt/lib/profile/InstrProfiling.h  |   3 +
 .../lib/profile/InstrProfilingBuffer.c|  14 ++
 compiler-rt/lib/profile/InstrProfilingMerge.c |   8 +-
 .../profile/InstrProfilingPlatformWindows.c   |   2 -
 .../lib/profile/InstrProfilingWriter.c|  24 +--
 compiler-rt/test/CMakeLists.txt   |   5 +-
 .../Darwin/instrprof-debug-info-correlate.c   |   4 +-
 .../instrprof-debug-info-correlate-warnings.c |   2 +-
 .../Linux/instrprof-debug-info-correlate.c|   6 +-
 .../instrprof-show-debug-info-correlation.c   |   6 +-
 .../test/profile/instrprof-binary-correlate.c |  29 +++
 llvm/include/llvm/ProfileData/InstrProf.h |   6 +-
 .../llvm/ProfileData/InstrProfCorrelator.h|  59 -
 .../llvm/ProfileData/InstrProfData.inc|   2 +
 .../llvm/ProfileData/InstrProfReader.h|  10 +
 .../Instrumentation/PGOInstrumentation.h  |   2 -
 .../CodeGen/TargetLoweringObjectFileImpl.cpp  |  23 +-
 .../Coverage/CoverageMappingReader.cpp|  28 ++-
 llvm/lib/ProfileData/InstrProf.cpp|   8 +-
 llvm/lib/ProfileData/InstrProfCorrelator.cpp  | 203 ++
 llvm/lib/ProfileData/InstrProfReader.cpp  |   8 +-
 .../Instrumentation/InstrProfiling.cpp|  31 +--
 .../Instrumentation/PGOInstrumentation.cpp|   3 +-
 .../debug-info-correlate-coverage.ll  |   2 +-
 .../InstrProfiling/debug-info-correlate.ll|   2 +-
 llvm/tools/llvm-profdata/llvm-profdata.cpp|  37 +++-
 30 files changed, 436 insertions(+), 132 deletions(-)
 create mode 100644 clang/test/CodeGen/coverage-profile-raw-version.c
 create mode 100644 compiler-rt/test/profile/instrprof-binary-correlate.c

diff --git a/clang/lib/CodeGen/BackendUtil.cpp 
b/clang/lib/CodeGen/BackendUtil.cpp
index 70accce456d3c07..dad3c9a145b5049 100644
--- a/clang/lib/CodeGen/BackendUtil.cpp
+++ b/clang/lib/CodeGen/BackendUtil.cpp
@@ -42,6 +42,7 @@
 #include "llvm/Passes/PassBuilder.h"
 #include "llvm/Passes/PassPlugin.h"
 #include "llvm/Passes/StandardInstrumentations.h"
+#include "llvm/ProfileData/InstrProfCorrelator.h"
 #include "llvm/Support/BuryPointer.h"
 #include "llvm/Support/CommandLine.h"
 #include "llvm/Support/MemoryBuffer.h"
@@ -98,13 +99,16 @@ extern cl::opt PrintPipelinePasses;
 static cl::opt ClSanitizeOnOptimizerEarlyEP(
 "sanitizer-early-opt-ep", cl::Optional,
 cl::desc("Insert sanitizers on OptimizerEarlyEP."), cl::init(false));
-}
+
+extern cl::opt ProfileCorrelate;
+} // namespace llvm
 
 namespace {
 
 // Default filename used for profile generation.
 std::string getDefaultProfileGenName() {
-  return DebugInfoCorrelate ? "default_%m.proflite" : "default_%m.profraw";
+  return ProfileCorrelate.getNumOccurrences() ? "default_%m.proflite"
+  : "default_%m.profraw";
 }
 
 class EmitAssemblyHelper {
@@ -197,7 +201,7 @@ class EmitAssemblyHelper {
   void EmitAssembly(BackendAction Action,
 std::unique_ptr OS);
 };
-}
+} // namespace
 
 static SanitizerCoverageOptions
 getSancovOptsFromCGOpts(const CodeGenOptions &CGOpts) {
diff --git a/clang/lib/CodeGen/CoverageMappingGen.cpp 
b/clang/lib/CodeGen/CoverageMappingGen.cpp
index 76ed10091b025be..daff0d1d50923f5 100644
--- a/clang/lib/CodeGen/CoverageMappingGen.cpp
+++ b/clang/lib/CodeGen/CoverageMappingGen.cpp
@@ -31,6 +31,10 @@
 // is textually included.
 #define COVMAP_V3
 
+namespace llvm {
+extern cl::opt ProfileCorrelate;
+} // namespace llvm
+
 static llvm::cl::opt EmptyLineCommentCoverage(
 "emptyline-comment-coverage",
 llvm::cl::desc("Emit emptylines and comment lines as skipped regions (only 
"
@@ -1831,6 +1835,22 @@ void CoverageMappingModuleGen::emit() {
  llvm::GlobalValue::InternalLinkage, NamesArrVal,
  llvm::getCoverageUnusedNamesVarName());
   }
+  const StringRef VarName(INSTR_PROF_QUOTE(INSTR_PROF_RAW_VERSION_VAR));
+  llvm::Type *IntTy64 = llvm::Type::getInt64Ty(Ctx);
+  uint64_t ProfileVersion = INSTR_PROF_RAW_VERSION;
+  if (llvm::ProfileCorrelate == llvm::InstrProfCorrelator::BINARY)
+ProfileVersion |= VARIANT_MASK_BIN_CORRELATE;
+  auto *VersionVariable = new llvm::GlobalVariable(
+  CGM.getModule(), llvm::Type::getInt64Ty(Ctx), true,
+  llvm::GlobalValue::WeakAnyLinkage,
+  llvm::Constant::getIntegerValue(IntTy64, llvm::APInt(64, 
ProfileVersion)),
+  VarName);
+  VersionVariable->setVisibility(llvm::GlobalValue::HiddenVisibility);
+  llvm::Triple T

[llvm] [lldb] [mlir] [flang] [clang-tools-extra] [clang] [compiler-rt] [Profile] Add binary profile correlation to offload profile metadata at runtime. (PR #69493)

2023-11-02 Thread Zequan Wu via cfe-commits

https://github.com/ZequanWu updated 
https://github.com/llvm/llvm-project/pull/69493

>From 3a394ce5d4d7d91251337bd0a2c1c1a074eb37e6 Mon Sep 17 00:00:00 2001
From: Zequan Wu 
Date: Tue, 17 Oct 2023 19:24:12 -0400
Subject: [PATCH 1/6] [Profile] Add binary profile correlation.

---
 clang/lib/CodeGen/BackendUtil.cpp |  10 +-
 clang/lib/CodeGen/CoverageMappingGen.cpp  |  20 ++
 .../CodeGen/coverage-profile-raw-version.c|   9 +
 compiler-rt/include/profile/InstrProfData.inc |   2 +
 compiler-rt/lib/profile/InstrProfiling.h  |   3 +
 .../lib/profile/InstrProfilingBuffer.c|  14 ++
 compiler-rt/lib/profile/InstrProfilingMerge.c |   8 +-
 .../profile/InstrProfilingPlatformWindows.c   |   2 -
 .../lib/profile/InstrProfilingWriter.c|  24 +--
 compiler-rt/test/CMakeLists.txt   |   5 +-
 .../Darwin/instrprof-debug-info-correlate.c   |   4 +-
 .../instrprof-debug-info-correlate-warnings.c |   2 +-
 .../Linux/instrprof-debug-info-correlate.c|   6 +-
 .../instrprof-show-debug-info-correlation.c   |   6 +-
 .../test/profile/instrprof-binary-correlate.c |  29 +++
 llvm/include/llvm/ProfileData/InstrProf.h |   6 +-
 .../llvm/ProfileData/InstrProfCorrelator.h|  59 -
 .../llvm/ProfileData/InstrProfData.inc|   2 +
 .../llvm/ProfileData/InstrProfReader.h|  10 +
 .../Instrumentation/PGOInstrumentation.h  |   2 -
 .../CodeGen/TargetLoweringObjectFileImpl.cpp  |  23 +-
 .../Coverage/CoverageMappingReader.cpp|  28 ++-
 llvm/lib/ProfileData/InstrProf.cpp|   8 +-
 llvm/lib/ProfileData/InstrProfCorrelator.cpp  | 203 ++
 llvm/lib/ProfileData/InstrProfReader.cpp  |   8 +-
 .../Instrumentation/InstrProfiling.cpp|  31 +--
 .../Instrumentation/PGOInstrumentation.cpp|   3 +-
 .../debug-info-correlate-coverage.ll  |   2 +-
 .../InstrProfiling/debug-info-correlate.ll|   2 +-
 llvm/tools/llvm-profdata/llvm-profdata.cpp|  37 +++-
 30 files changed, 436 insertions(+), 132 deletions(-)
 create mode 100644 clang/test/CodeGen/coverage-profile-raw-version.c
 create mode 100644 compiler-rt/test/profile/instrprof-binary-correlate.c

diff --git a/clang/lib/CodeGen/BackendUtil.cpp 
b/clang/lib/CodeGen/BackendUtil.cpp
index 70accce456d3c07..dad3c9a145b5049 100644
--- a/clang/lib/CodeGen/BackendUtil.cpp
+++ b/clang/lib/CodeGen/BackendUtil.cpp
@@ -42,6 +42,7 @@
 #include "llvm/Passes/PassBuilder.h"
 #include "llvm/Passes/PassPlugin.h"
 #include "llvm/Passes/StandardInstrumentations.h"
+#include "llvm/ProfileData/InstrProfCorrelator.h"
 #include "llvm/Support/BuryPointer.h"
 #include "llvm/Support/CommandLine.h"
 #include "llvm/Support/MemoryBuffer.h"
@@ -98,13 +99,16 @@ extern cl::opt PrintPipelinePasses;
 static cl::opt ClSanitizeOnOptimizerEarlyEP(
 "sanitizer-early-opt-ep", cl::Optional,
 cl::desc("Insert sanitizers on OptimizerEarlyEP."), cl::init(false));
-}
+
+extern cl::opt ProfileCorrelate;
+} // namespace llvm
 
 namespace {
 
 // Default filename used for profile generation.
 std::string getDefaultProfileGenName() {
-  return DebugInfoCorrelate ? "default_%m.proflite" : "default_%m.profraw";
+  return ProfileCorrelate.getNumOccurrences() ? "default_%m.proflite"
+  : "default_%m.profraw";
 }
 
 class EmitAssemblyHelper {
@@ -197,7 +201,7 @@ class EmitAssemblyHelper {
   void EmitAssembly(BackendAction Action,
 std::unique_ptr OS);
 };
-}
+} // namespace
 
 static SanitizerCoverageOptions
 getSancovOptsFromCGOpts(const CodeGenOptions &CGOpts) {
diff --git a/clang/lib/CodeGen/CoverageMappingGen.cpp 
b/clang/lib/CodeGen/CoverageMappingGen.cpp
index 76ed10091b025be..daff0d1d50923f5 100644
--- a/clang/lib/CodeGen/CoverageMappingGen.cpp
+++ b/clang/lib/CodeGen/CoverageMappingGen.cpp
@@ -31,6 +31,10 @@
 // is textually included.
 #define COVMAP_V3
 
+namespace llvm {
+extern cl::opt ProfileCorrelate;
+} // namespace llvm
+
 static llvm::cl::opt EmptyLineCommentCoverage(
 "emptyline-comment-coverage",
 llvm::cl::desc("Emit emptylines and comment lines as skipped regions (only 
"
@@ -1831,6 +1835,22 @@ void CoverageMappingModuleGen::emit() {
  llvm::GlobalValue::InternalLinkage, NamesArrVal,
  llvm::getCoverageUnusedNamesVarName());
   }
+  const StringRef VarName(INSTR_PROF_QUOTE(INSTR_PROF_RAW_VERSION_VAR));
+  llvm::Type *IntTy64 = llvm::Type::getInt64Ty(Ctx);
+  uint64_t ProfileVersion = INSTR_PROF_RAW_VERSION;
+  if (llvm::ProfileCorrelate == llvm::InstrProfCorrelator::BINARY)
+ProfileVersion |= VARIANT_MASK_BIN_CORRELATE;
+  auto *VersionVariable = new llvm::GlobalVariable(
+  CGM.getModule(), llvm::Type::getInt64Ty(Ctx), true,
+  llvm::GlobalValue::WeakAnyLinkage,
+  llvm::Constant::getIntegerValue(IntTy64, llvm::APInt(64, 
ProfileVersion)),
+  VarName);
+  VersionVariable->setVisibility(llvm::GlobalValue::HiddenVisibility);
+  llvm::Triple T

[compiler-rt] [llvm] [clang] [Profile] Refactor profile correlation. (PR #70856)

2023-11-02 Thread Zequan Wu via cfe-commits

ZequanWu wrote:

> I'm a bit concerned about the use of hasCorrelation. We require the runtime 
> to check the flag and omit the data and names section if set which introduces 
> a potential issue: since we emit the version in every TU and u se COMDAT to 
> deduplicate them, but that means that if you link together TUs compiled with 
> and without -debug-info-correlate/-profile-correlate= (that is having 
> different flags), you would end up with different results depending on which 
> section was selected by the linker. This may not be an issue if you always 
> compile all code yourself using the same set of flags, but might be an issue 
> when you combine libraries coming from different sources.

I understand your concern. I think that's the limitation of these modes. You 
need to either compile all code with 
`-debug-info-correlate`/`-profile-correlate=` consistently or not. So, these 
modes are not suitable for projects which link with libraries compiled without 
the flags.

> What I think would be a better design is to just omit the respective sections 
> altogether when -debug-info-correlate/-profile-correlate= is enabled.

I don't understand how this solves the problem you described above. Can you 
elaborate a bit more? We still need to decide if we need to omit data and names 
sections at runtime right?

https://github.com/llvm/llvm-project/pull/70856
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [llvm] [lldb] [mlir] [compiler-rt] [clang-tools-extra] [flang] [Profile] Add binary profile correlation for code coverage. (PR #69493)

2023-12-12 Thread Zequan Wu via cfe-commits


@@ -1829,6 +1833,22 @@ void CoverageMappingModuleGen::emit() {
  llvm::GlobalValue::InternalLinkage, NamesArrVal,
  llvm::getCoverageUnusedNamesVarName());
   }
+  const StringRef VarName(INSTR_PROF_QUOTE(INSTR_PROF_RAW_VERSION_VAR));
+  llvm::Type *IntTy64 = llvm::Type::getInt64Ty(Ctx);
+  uint64_t ProfileVersion = INSTR_PROF_RAW_VERSION;
+  if (llvm::ProfileCorrelate == llvm::InstrProfCorrelator::BINARY)
+ProfileVersion |= VARIANT_MASK_BIN_CORRELATE;

ZequanWu wrote:

ditto

https://github.com/llvm/llvm-project/pull/69493
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [compiler-rt] [flang] [llvm] [lldb] [mlir] [clang-tools-extra] [Profile] Add binary profile correlation for code coverage. (PR #69493)

2023-12-12 Thread Zequan Wu via cfe-commits


@@ -0,0 +1,9 @@
+// RUN: %clang_cc1  -fprofile-instrument=clang -fcoverage-mapping -emit-llvm 
-o - %s | FileCheck %s
+// RUN: %clang_cc1 -mllvm -profile-correlate=binary -fprofile-instrument=clang 
-fcoverage-mapping -emit-llvm -o - %s | FileCheck %s 
--check-prefix=BIN-CORRELATE
+
+// CHECK: @__llvm_profile_raw_version = {{.*}} i64 9

ZequanWu wrote:

ditto

https://github.com/llvm/llvm-project/pull/69493
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[llvm] [compiler-rt] [lldb] [clang] [mlir] [flang] [clang-tools-extra] [Profile] Add binary profile correlation for code coverage. (PR #69493)

2023-12-12 Thread Zequan Wu via cfe-commits


@@ -1829,6 +1833,22 @@ void CoverageMappingModuleGen::emit() {
  llvm::GlobalValue::InternalLinkage, NamesArrVal,
  llvm::getCoverageUnusedNamesVarName());
   }
+  const StringRef VarName(INSTR_PROF_QUOTE(INSTR_PROF_RAW_VERSION_VAR));

ZequanWu wrote:

I already reverted changes in Clang because `VARIANT_MASK_BIN_CORRELATE` flag 
is no longer necessary: 
https://github.com/llvm/llvm-project/pull/69493#issuecomment-1815324995

https://github.com/llvm/llvm-project/pull/69493
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [llvm] [mlir] [lldb] [clang-tools-extra] [compiler-rt] [flang] [Profile] Add binary profile correlation for code coverage. (PR #69493)

2023-12-14 Thread Zequan Wu via cfe-commits

https://github.com/ZequanWu closed 
https://github.com/llvm/llvm-project/pull/69493
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[llvm] [mlir] [lldb] [clang-tools-extra] [compiler-rt] [clang] [flang] [Profile] Add binary profile correlation for code coverage. (PR #69493)

2023-12-14 Thread Zequan Wu via cfe-commits

ZequanWu wrote:

> Seems like a mismatch on the diff, so maybe the check is too stringent.
> 
> If this will take a while to fix, would you mind reverting until it can be 
> addressed?

It passed for me locally on x64. Maybe I should use `diff <(llvm-profdata show 
--all-functions --counts %t.normal.profdata) <(llvm-profdata show 
--all-functions --counts %t.d4.profdata)` like it does on debug-info correlate 
test:
https://github.com/llvm/llvm-project/blob/29e043cb5c2efaad7fb203fb8240a91b77ca0c5b/compiler-rt/test/profile/Linux/instrprof-debug-info-correlate.c#L10

Sent a possible fix at: 
https://github.com/llvm/llvm-project/commit/f34325307eb36d6032ccea3773e3e0c1746b7f98,
 hope that fixes it.



https://github.com/llvm/llvm-project/pull/69493
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang-tools-extra] [compiler-rt] [clang] [llvm] [flang] [lldb] [mlir] [Profile] Add binary profile correlation for code coverage. (PR #69493)

2023-12-14 Thread Zequan Wu via cfe-commits

ZequanWu wrote:

> Well, seems like someone broke ToT w/ a compiler error. I'll let you know if 
> the forward fix fails to address the issue.

The latest build passed: 
https://luci-milo.appspot.com/ui/p/fuchsia/builders/toolchain.ci/clang-linux-x64/b8761696377585255057/overview.

https://github.com/llvm/llvm-project/pull/69493
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [compiler-rt] [llvm] [InstrProf] Single byte counters in coverage (PR #75425)

2023-12-15 Thread Zequan Wu via cfe-commits


@@ -569,16 +577,26 @@ struct CounterCoverageMappingBuilder
 
   /// Return a counter for the subtraction of \c RHS from \c LHS
   Counter subtractCounters(Counter LHS, Counter RHS, bool Simplify = true) {
+if (llvm::EnableSingleByteCoverage)
+  assert(
+  0 &&
+  "cannot subtract counters when single byte coverage mode is 
enabled");

ZequanWu wrote:

This can be simplifies to `assert(!llvm::EnableSingleByteCoverage && "cannot 
subtract counters when single byte coverage mode is enabled")`. Same for the 
following asserts.

https://github.com/llvm/llvm-project/pull/75425
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[compiler-rt] [clang] [llvm] [InstrProf] Single byte counters in coverage (PR #75425)

2023-12-15 Thread Zequan Wu via cfe-commits


@@ -234,8 +246,20 @@ struct MapRegionCounters : public 
RecursiveASTVisitor {
 if (Hash.getHashVersion() == PGO_HASH_V1)
   return Base::TraverseIfStmt(If);
 
+// When single byte coverage mode is enabled, add a counter to then and
+// else.
+for (Stmt *CS : If->children()) {
+  if (!CS || !llvm::EnableSingleByteCoverage)

ZequanWu wrote:

Maybe hoist `llvm::EnableSingleByteCoverage` outside the loop as this is not 
going to change. Same for the following.

https://github.com/llvm/llvm-project/pull/75425
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[llvm] [mlir] [clang-tools-extra] [clang] [lldb] [compiler-rt] [flang] [Profile] Add binary profile correlation for code coverage. (PR #69493)

2023-11-28 Thread Zequan Wu via cfe-commits

ZequanWu wrote:

Ping.

https://github.com/llvm/llvm-project/pull/69493
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [llvm] [compiler-rt] [clang-tools-extra] [Profile] Allow profile merging with multiple correlate files. (PR #75957)

2023-12-20 Thread Zequan Wu via cfe-commits

https://github.com/ZequanWu updated 
https://github.com/llvm/llvm-project/pull/75957

>From d72f0e1ad7759bad81767418604d27f11d74d6de Mon Sep 17 00:00:00 2001
From: Zequan Wu 
Date: Tue, 19 Dec 2023 12:32:15 -0500
Subject: [PATCH 1/3] [Profile] Allow profile merging with multiple correlate
 files.

---
 .../Linux/instrprof-correlation-mixed.test|  33 
 .../Linux/instrprof-debug-info-correlate.c|  19 ++
 .../llvm/ProfileData/InstrProfCorrelator.h| 124 ++---
 .../llvm/ProfileData/InstrProfReader.h|  17 +-
 llvm/lib/Object/BuildID.cpp   |  18 ++
 llvm/lib/ProfileData/InstrProfCorrelator.cpp  | 164 +-
 llvm/lib/ProfileData/InstrProfReader.cpp  |  26 ++-
 llvm/tools/llvm-profdata/llvm-profdata.cpp|  84 +
 8 files changed, 358 insertions(+), 127 deletions(-)
 create mode 100644 
compiler-rt/test/profile/Linux/instrprof-correlation-mixed.test

diff --git a/compiler-rt/test/profile/Linux/instrprof-correlation-mixed.test 
b/compiler-rt/test/profile/Linux/instrprof-correlation-mixed.test
new file mode 100644
index 00..8cc4611eec4f0b
--- /dev/null
+++ b/compiler-rt/test/profile/Linux/instrprof-correlation-mixed.test
@@ -0,0 +1,33 @@
+// REQUIRES: lld-available
+// Test llvm-profdata merging with multiple correlation files mixing different 
correlation modes.
+
+// RUN: %clang_pgogen -o %t.normal -mllvm --disable-vp=true 
%S/../Inputs/instrprof-debug-info-correlate-main.cpp 
%S/../Inputs/instrprof-debug-info-correlate-foo.cpp
+// RUN: env LLVM_PROFILE_FILE=%t.profraw %run %t.normal
+// RUN: llvm-profdata merge -o %t.normal.profdata %t.profraw
+
+// Compiling with differnt configs.
+// RUN: %clang_pgogen -o %t -mllvm --disable-vp=true 
%S/../Inputs/instrprof-debug-info-correlate-main.cpp -c -o %t-main.o
+// RUN: %clang_pgogen -o %t -g -mllvm --debug-info-correlate -mllvm 
--disable-vp=true %S/../Inputs/instrprof-debug-info-correlate-main.cpp -c -o 
%t-main.debug.o
+// RUN: %clang_pgogen -o %t -g -mllvm --debug-info-correlate -mllvm 
--disable-vp=true %S/../Inputs/instrprof-debug-info-correlate-foo.cpp -fpic 
-shared -Wl,--build-id -o %t-libfoo.debug.so
+// RUN: %clang_pgogen -o %t -mllvm -profile-correlate=binary -mllvm 
--disable-vp=true %S/../Inputs/instrprof-debug-info-correlate-foo.cpp -fpic 
-shared -Wl,--build-id -o %t-libfoo.binary.so
+
+// Test mixing default raw profile and lightweight raw profile generated with 
debug info correlate.
+// The raw profiles are mixed in %t.proflite.
+// RUN: %clang_pgogen -o %t %t-main.o %t-libfoo.debug.so -Wl,--build-id -o %t
+// RUN: env LLVM_PROFILE_FILE=%t.proflite %run %t
+// RUN: llvm-profdata merge -o %t.profdata --debug-info=%t-libfoo.debug.so 
%t.proflite
+// RUN: diff <(llvm-profdata show --all-functions --counts %t.normal.profdata) 
<(llvm-profdata show --all-functions --counts %t.profdata)
+// Two separate raw profiles.
+// RUN: rm -rf %t.dir && mkdir %t.dir
+// RUN: env LLVM_PROFILE_FILE=%t.dir/raw%m.proflite %run %t
+// RUN: llvm-profdata merge -o %t.profdata --debug-info=%t-libfoo.debug.so 
%t.dir
+// RUN: diff <(llvm-profdata show --all-functions --counts %t.normal.profdata) 
<(llvm-profdata show --all-functions --counts %t.profdata)
+
+// Test lightweight raw profiles generated with debug info correlate and 
binary correlate.
+// Note we can not mix different correlation modes in static linking because 
when merging, the same correlate file can not be used for more than one 
correaltion mode.
+// Two separate lightweight raw profiles.
+// RUN: %clang_pgogen -o %t -g %t-main.debug.o %t-libfoo.binary.so 
-Wl,--build-id -o %t
+// RUN: rm -rf %t.dir && mkdir %t.dir
+// RUN: env LLVM_PROFILE_FILE=%t.dir/raw%m.proflite %run %t
+// RUN: llvm-profdata merge -o %t.profdata --debug-info=%t 
--binary-file=%t-libfoo.binary.so %t.dir
+// RUN: diff <(llvm-profdata show --all-functions --counts %t.normal.profdata) 
<(llvm-profdata show --all-functions --counts %t.profdata)
diff --git a/compiler-rt/test/profile/Linux/instrprof-debug-info-correlate.c 
b/compiler-rt/test/profile/Linux/instrprof-debug-info-correlate.c
index a918d7b6299005..47dbf3c87e68f1 100644
--- a/compiler-rt/test/profile/Linux/instrprof-debug-info-correlate.c
+++ b/compiler-rt/test/profile/Linux/instrprof-debug-info-correlate.c
@@ -25,6 +25,25 @@
 
 // RUN: diff <(llvm-profdata show --all-functions --counts 
%t.cov.normal.profdata) <(llvm-profdata show --all-functions --counts 
%t.cov.profdata)
 
+// Test debug info correlate with build id.
+
+// Both binaries are built with build id.
+// RUN: %clang_pgogen -o %t -g -mllvm --debug-info-correlate -mllvm 
--disable-vp=true %S/../Inputs/instrprof-debug-info-correlate-foo.cpp -c -fpic 
-shared -Wl,--build-id -o %t-libfoo.so
+// RUN: %clang_pgogen -o %t -g -mllvm --debug-info-correlate -mllvm 
--disable-vp=true %S/../Inputs/instrprof-debug-info-correlate-main.cpp 
%t-libfoo.so -Wl,--build-id -o %t
+// RUN: env LLVM_PROFILE_FILE=%t.proflite %run %t
+// RUN: llvm-profdata merg

[llvm] [compiler-rt] [clang] [clang-tools-extra] [Profile] Allow profile merging with multiple correlate files. (PR #75957)

2023-12-20 Thread Zequan Wu via cfe-commits

https://github.com/ZequanWu updated 
https://github.com/llvm/llvm-project/pull/75957

>From d72f0e1ad7759bad81767418604d27f11d74d6de Mon Sep 17 00:00:00 2001
From: Zequan Wu 
Date: Tue, 19 Dec 2023 12:32:15 -0500
Subject: [PATCH 1/4] [Profile] Allow profile merging with multiple correlate
 files.

---
 .../Linux/instrprof-correlation-mixed.test|  33 
 .../Linux/instrprof-debug-info-correlate.c|  19 ++
 .../llvm/ProfileData/InstrProfCorrelator.h| 124 ++---
 .../llvm/ProfileData/InstrProfReader.h|  17 +-
 llvm/lib/Object/BuildID.cpp   |  18 ++
 llvm/lib/ProfileData/InstrProfCorrelator.cpp  | 164 +-
 llvm/lib/ProfileData/InstrProfReader.cpp  |  26 ++-
 llvm/tools/llvm-profdata/llvm-profdata.cpp|  84 +
 8 files changed, 358 insertions(+), 127 deletions(-)
 create mode 100644 
compiler-rt/test/profile/Linux/instrprof-correlation-mixed.test

diff --git a/compiler-rt/test/profile/Linux/instrprof-correlation-mixed.test 
b/compiler-rt/test/profile/Linux/instrprof-correlation-mixed.test
new file mode 100644
index 00..8cc4611eec4f0b
--- /dev/null
+++ b/compiler-rt/test/profile/Linux/instrprof-correlation-mixed.test
@@ -0,0 +1,33 @@
+// REQUIRES: lld-available
+// Test llvm-profdata merging with multiple correlation files mixing different 
correlation modes.
+
+// RUN: %clang_pgogen -o %t.normal -mllvm --disable-vp=true 
%S/../Inputs/instrprof-debug-info-correlate-main.cpp 
%S/../Inputs/instrprof-debug-info-correlate-foo.cpp
+// RUN: env LLVM_PROFILE_FILE=%t.profraw %run %t.normal
+// RUN: llvm-profdata merge -o %t.normal.profdata %t.profraw
+
+// Compiling with differnt configs.
+// RUN: %clang_pgogen -o %t -mllvm --disable-vp=true 
%S/../Inputs/instrprof-debug-info-correlate-main.cpp -c -o %t-main.o
+// RUN: %clang_pgogen -o %t -g -mllvm --debug-info-correlate -mllvm 
--disable-vp=true %S/../Inputs/instrprof-debug-info-correlate-main.cpp -c -o 
%t-main.debug.o
+// RUN: %clang_pgogen -o %t -g -mllvm --debug-info-correlate -mllvm 
--disable-vp=true %S/../Inputs/instrprof-debug-info-correlate-foo.cpp -fpic 
-shared -Wl,--build-id -o %t-libfoo.debug.so
+// RUN: %clang_pgogen -o %t -mllvm -profile-correlate=binary -mllvm 
--disable-vp=true %S/../Inputs/instrprof-debug-info-correlate-foo.cpp -fpic 
-shared -Wl,--build-id -o %t-libfoo.binary.so
+
+// Test mixing default raw profile and lightweight raw profile generated with 
debug info correlate.
+// The raw profiles are mixed in %t.proflite.
+// RUN: %clang_pgogen -o %t %t-main.o %t-libfoo.debug.so -Wl,--build-id -o %t
+// RUN: env LLVM_PROFILE_FILE=%t.proflite %run %t
+// RUN: llvm-profdata merge -o %t.profdata --debug-info=%t-libfoo.debug.so 
%t.proflite
+// RUN: diff <(llvm-profdata show --all-functions --counts %t.normal.profdata) 
<(llvm-profdata show --all-functions --counts %t.profdata)
+// Two separate raw profiles.
+// RUN: rm -rf %t.dir && mkdir %t.dir
+// RUN: env LLVM_PROFILE_FILE=%t.dir/raw%m.proflite %run %t
+// RUN: llvm-profdata merge -o %t.profdata --debug-info=%t-libfoo.debug.so 
%t.dir
+// RUN: diff <(llvm-profdata show --all-functions --counts %t.normal.profdata) 
<(llvm-profdata show --all-functions --counts %t.profdata)
+
+// Test lightweight raw profiles generated with debug info correlate and 
binary correlate.
+// Note we can not mix different correlation modes in static linking because 
when merging, the same correlate file can not be used for more than one 
correaltion mode.
+// Two separate lightweight raw profiles.
+// RUN: %clang_pgogen -o %t -g %t-main.debug.o %t-libfoo.binary.so 
-Wl,--build-id -o %t
+// RUN: rm -rf %t.dir && mkdir %t.dir
+// RUN: env LLVM_PROFILE_FILE=%t.dir/raw%m.proflite %run %t
+// RUN: llvm-profdata merge -o %t.profdata --debug-info=%t 
--binary-file=%t-libfoo.binary.so %t.dir
+// RUN: diff <(llvm-profdata show --all-functions --counts %t.normal.profdata) 
<(llvm-profdata show --all-functions --counts %t.profdata)
diff --git a/compiler-rt/test/profile/Linux/instrprof-debug-info-correlate.c 
b/compiler-rt/test/profile/Linux/instrprof-debug-info-correlate.c
index a918d7b6299005..47dbf3c87e68f1 100644
--- a/compiler-rt/test/profile/Linux/instrprof-debug-info-correlate.c
+++ b/compiler-rt/test/profile/Linux/instrprof-debug-info-correlate.c
@@ -25,6 +25,25 @@
 
 // RUN: diff <(llvm-profdata show --all-functions --counts 
%t.cov.normal.profdata) <(llvm-profdata show --all-functions --counts 
%t.cov.profdata)
 
+// Test debug info correlate with build id.
+
+// Both binaries are built with build id.
+// RUN: %clang_pgogen -o %t -g -mllvm --debug-info-correlate -mllvm 
--disable-vp=true %S/../Inputs/instrprof-debug-info-correlate-foo.cpp -c -fpic 
-shared -Wl,--build-id -o %t-libfoo.so
+// RUN: %clang_pgogen -o %t -g -mllvm --debug-info-correlate -mllvm 
--disable-vp=true %S/../Inputs/instrprof-debug-info-correlate-main.cpp 
%t-libfoo.so -Wl,--build-id -o %t
+// RUN: env LLVM_PROFILE_FILE=%t.proflite %run %t
+// RUN: llvm-profdata merg

[compiler-rt] [llvm] [clang] [clang-tools-extra] [Profile] Allow profile merging with multiple correlate files. (PR #75957)

2023-12-20 Thread Zequan Wu via cfe-commits


@@ -0,0 +1,33 @@
+// REQUIRES: lld-available

ZequanWu wrote:

Added by mistake. Removed.

https://github.com/llvm/llvm-project/pull/75957
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[compiler-rt] [clang] [clang-tools-extra] [llvm] [Profile] Allow profile merging with multiple correlate files. (PR #75957)

2023-12-20 Thread Zequan Wu via cfe-commits


@@ -0,0 +1,33 @@
+// REQUIRES: lld-available

ZequanWu wrote:

The added test in `Linux/instrprof-debug-info-correlate.c` requires build id. 
Does darwin linker ld64 or ld64.lld have the option to emit build id into 
binary? I don't find such flag.

https://github.com/llvm/llvm-project/pull/75957
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[compiler-rt] [llvm] [clang] [clang-tools-extra] [Profile] Allow profile merging with multiple correlate files. (PR #75957)

2023-12-20 Thread Zequan Wu via cfe-commits


@@ -25,6 +25,25 @@
 
 // RUN: diff <(llvm-profdata show --all-functions --counts 
%t.cov.normal.profdata) <(llvm-profdata show --all-functions --counts 
%t.cov.profdata)
 
+// Test debug info correlate with build id.

ZequanWu wrote:

The added test in `Linux/instrprof-debug-info-correlate.c` requires build id in 
the binaries. Does ld64 or ld64.lld have a flag to emit build id in binaries? I 
don't find such flag.

https://github.com/llvm/llvm-project/pull/75957
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [llvm] [compiler-rt] [clang-tools-extra] [Profile] Allow profile merging with multiple correlate files. (PR #75957)

2023-12-20 Thread Zequan Wu via cfe-commits


@@ -118,18 +118,18 @@ cl::opt ProfiledBinary(
 "profiled-binary", cl::init(""),
 cl::desc("Path to binary from which the profile was collected."),
 cl::sub(ShowSubcommand), cl::sub(MergeSubcommand));
-cl::opt DebugInfoFilename(
-"debug-info", cl::init(""),
+cl::list DebugInfoFilenames(
+"debug-info",
 cl::desc(
 "For show, read and extract profile metadata from debug info and show "
 "the functions it found. For merge, use the provided debug info to "
 "correlate the raw profile."),
 cl::sub(ShowSubcommand), cl::sub(MergeSubcommand));
-cl::opt
-BinaryFilename("binary-file", cl::init(""),
-   cl::desc("For merge, use the provided unstripped bianry to "
-"correlate the raw profile."),
-   cl::sub(MergeSubcommand));
+cl::list
+BinaryFilenames("binary-file",
+cl::desc("For merge, use the provided unstripped bianry to 
"
+ "correlate the raw profile."),
+cl::sub(MergeSubcommand));

ZequanWu wrote:

> It looks like we are switching from passing a single correlation file to a 
> list of correlation files. Is that so that we can pass all raw profiles into 
> a single llvm-profdata merge command?

Yes, that's the purpose. 

> Presumably we should know which binaries produce which raw profiles.

This isn't always the case. When there are shared libraries producing raw 
profiles and `LLVM_PROFILE_FILE=default-%4m.profraw`, we will get bunch of 
`default-{hash}.profraw` produced by all shared libraries and main executable. 
There's no way to differentiate which raw profiles are generated by which 
binaries. @gulfemsavrun also has use case for this situation: 
https://discourse.llvm.org/t/rfc-add-binary-profile-correlation-to-not-load-profile-metadata-sections-into-memory-at-runtime/74565/8?u=zequanwu

https://github.com/llvm/llvm-project/pull/75957
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[llvm] [compiler-rt] [clang] [clang-tools-extra] [Profile] Allow profile merging with multiple correlate files. (PR #75957)

2023-12-20 Thread Zequan Wu via cfe-commits


@@ -481,3 +509,49 @@ Error 
BinaryInstrProfCorrelator::correlateProfileNameImpl() {
   this->Names.append(this->Ctx->NameStart, this->Ctx->NameSize);
   return Error::success();
 }
+
+llvm::Expected> 
InstrProfCorrelators::get(
+ArrayRef>
+CorrelateInputs,
+uint32_t MaxWarnings) {
+  StringMap> CorrelatorMap;
+  StringMap FileMap;
+  auto WarnCounter =
+  std::make_unique(MaxWarnings);
+  std::unique_ptr CorrelateLock = std::make_unique();
+  std::unique_ptr WarnLock = std::make_unique();
+  for (const auto &Input : CorrelateInputs) {
+std::unique_ptr Correlator;
+if (auto Err = InstrProfCorrelator::get(Input.first, Input.second,
+*CorrelateLock.get(),
+*WarnLock.get(), WarnCounter.get())
+   .moveInto(Correlator))
+  return Err;
+std::string BuildID = toHex(Correlator->getBuildID());
+FileMap.try_emplace(BuildID, Input.first);
+bool Inserted =
+CorrelatorMap.try_emplace(BuildID, std::move(Correlator)).second;
+if (!Inserted && WarnCounter->shouldEmitWarning()) {
+  std::lock_guard Guard(*WarnLock);
+  WithColor::warning() << format(
+  "Duplicate build id (%s) found for %s and %s\n", BuildID.c_str(),
+  FileMap[BuildID].str().c_str(), Input.first.str().c_str());
+}
+  }
+  return std::make_unique(
+  std::move(CorrelatorMap), std::move(CorrelateLock), std::move(WarnLock),
+  std::move(WarnCounter));
+}
+
+llvm::Expected
+InstrProfCorrelators::getCorrelator(object::BuildIDRef BuildID) const {
+  std::string BuildIDStr = toHex(BuildID);
+  auto I = CorrelatorMap.find(BuildIDStr);
+  if (I == CorrelatorMap.end())
+return make_error(
+instrprof_error::unable_to_correlate_profile,
+"missing correlator file with build id " + BuildIDStr + "\n");
+  if (auto Err = I->getValue()->correlateProfileData())

ZequanWu wrote:

Part of the reason for doing "lazy correlation" is to allow parsing multiple 
correlate files parallelly, because when merging, llvm-profdata will parallelly 
read raw profiles. But I just noticed that there's mistake in the 
implementation (all Correlators share the same CorrelateLock so only one can 
correlate at a time) and we can do it in llvm-profdata.cpp later probably.

Removed mutex and atomics and call `correlateProfileData()` upfront when 
creating `InstrProfCorrelators`

https://github.com/llvm/llvm-project/pull/75957
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[compiler-rt] [clang] [llvm] [clang-tools-extra] [Profile] Allow profile merging with multiple correlate files. (PR #75957)

2024-01-02 Thread Zequan Wu via cfe-commits


@@ -481,3 +509,49 @@ Error 
BinaryInstrProfCorrelator::correlateProfileNameImpl() {
   this->Names.append(this->Ctx->NameStart, this->Ctx->NameSize);
   return Error::success();
 }
+
+llvm::Expected> 
InstrProfCorrelators::get(
+ArrayRef>
+CorrelateInputs,
+uint32_t MaxWarnings) {
+  StringMap> CorrelatorMap;
+  StringMap FileMap;
+  auto WarnCounter =
+  std::make_unique(MaxWarnings);
+  std::unique_ptr CorrelateLock = std::make_unique();
+  std::unique_ptr WarnLock = std::make_unique();
+  for (const auto &Input : CorrelateInputs) {
+std::unique_ptr Correlator;
+if (auto Err = InstrProfCorrelator::get(Input.first, Input.second,
+*CorrelateLock.get(),
+*WarnLock.get(), WarnCounter.get())
+   .moveInto(Correlator))
+  return Err;
+std::string BuildID = toHex(Correlator->getBuildID());
+FileMap.try_emplace(BuildID, Input.first);
+bool Inserted =
+CorrelatorMap.try_emplace(BuildID, std::move(Correlator)).second;
+if (!Inserted && WarnCounter->shouldEmitWarning()) {
+  std::lock_guard Guard(*WarnLock);
+  WithColor::warning() << format(
+  "Duplicate build id (%s) found for %s and %s\n", BuildID.c_str(),
+  FileMap[BuildID].str().c_str(), Input.first.str().c_str());
+}
+  }
+  return std::make_unique(
+  std::move(CorrelatorMap), std::move(CorrelateLock), std::move(WarnLock),
+  std::move(WarnCounter));
+}
+
+llvm::Expected
+InstrProfCorrelators::getCorrelator(object::BuildIDRef BuildID) const {
+  std::string BuildIDStr = toHex(BuildID);
+  auto I = CorrelatorMap.find(BuildIDStr);
+  if (I == CorrelatorMap.end())
+return make_error(
+instrprof_error::unable_to_correlate_profile,
+"missing correlator file with build id " + BuildIDStr + "\n");
+  if (auto Err = I->getValue()->correlateProfileData())

ZequanWu wrote:

Right now, the parsing of correlation files is done before the parallelization 
starts. For each raw profiles, it parallelly associate parsed correlation info 
with lightweight raw profiles (which basically returns pointers to constant 
data and constant names)

> I guess we would still need an atomic counter to make sure we don't emit too 
> many warnings.

The warnings are only emitted at the time when parsing the correlation files 
which is before the parallelization starts. So, at least for now, we don't need 
atomic counter. If we want to parallelly parse correlation files, then we need 
lock or atomic counter to handle warning emissions.

https://github.com/llvm/llvm-project/pull/75957
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[compiler-rt] [clang] [llvm] [clang-tools-extra] [Profile] Allow profile merging with multiple correlate files. (PR #75957)

2024-01-02 Thread Zequan Wu via cfe-commits


@@ -118,18 +118,18 @@ cl::opt ProfiledBinary(
 "profiled-binary", cl::init(""),
 cl::desc("Path to binary from which the profile was collected."),
 cl::sub(ShowSubcommand), cl::sub(MergeSubcommand));
-cl::opt DebugInfoFilename(
-"debug-info", cl::init(""),
+cl::list DebugInfoFilenames(
+"debug-info",
 cl::desc(
 "For show, read and extract profile metadata from debug info and show "
 "the functions it found. For merge, use the provided debug info to "
 "correlate the raw profile."),
 cl::sub(ShowSubcommand), cl::sub(MergeSubcommand));
-cl::opt
-BinaryFilename("binary-file", cl::init(""),
-   cl::desc("For merge, use the provided unstripped bianry to "
-"correlate the raw profile."),
-   cl::sub(MergeSubcommand));
+cl::list
+BinaryFilenames("binary-file",
+cl::desc("For merge, use the provided unstripped bianry to 
"
+ "correlate the raw profile."),
+cl::sub(MergeSubcommand));

ZequanWu wrote:

> Another option would be to extend the pattern strings to support %b to expand 
> to the binary id or the binary name. Do you think that would work?

If the binary is built with binary id embedded, the raw profiles will also have 
binary id embedded. So there's no need to make `%b` expand to the binary id. 
The point for accepting multiple correlation files is to avoid some customizing 
scripts which associate raw profiles with different binaries. 

The output indexed profile file will contain profile information for multiple 
binaries. I'm not sure if this will cause problems/inconvenience for 
processing. What's your thoughts on this @gulfemsavrun @petrhosek?

https://github.com/llvm/llvm-project/pull/75957
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang-tools-extra] [llvm] [compiler-rt] [clang] [Profile] Allow profile merging with multiple correlate files. (PR #75957)

2024-01-10 Thread Zequan Wu via cfe-commits

ZequanWu wrote:

Ping.


https://github.com/llvm/llvm-project/pull/75957
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [Clang] Wide delimiters ('{{{') for expect strings (PR #77326)

2024-01-10 Thread Zequan Wu via cfe-commits

ZequanWu wrote:

Hi, this breaks our build. I don't know how to update the expectation to match

Current expectation:
  DCHECK_OK(foo);  // 
expected-error@components/reporting/util/status_macros.h:* 
{{{CHECK,DCHECK,ASSERT,EXPECT}_OK do not accept a type other than Status or 
StatusOr.}}



https://github.com/llvm/llvm-project/pull/77326
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [Clang] Wide delimiters ('{{{') for expect strings (PR #77326)

2024-01-10 Thread Zequan Wu via cfe-commits

ZequanWu wrote:

> @ZequanWu would either of these work for you?
> 
> ```c++
>  DCHECK_OK(foo); // 
> expected-error@components/reporting/util/status_macros.h:* 
> {{{CHECK,DCHECK,ASSERT,EXPECT}_OK do not accept a type other than Status or 
> StatusOr.}}}
> ```
> 
> or
> 
> ```c++
>  DCHECK_OK(foo); // 
> expected-error-re@components/reporting/util/status_macros.h:* 
> {{{CHECK,DCHECK,ASSERT,EXPECT}_OK do not accept a type other than Status or 
> StatusOr.}}
> ```

Thanks, it's a simple fix, just adding a space between 2nd and 3rd braces:
```
DCHECK_OK(foo);  // expected-error@components/reporting/util/status_macros.h:* 
{{ {CHECK,DCHECK,ASSERT,EXPECT}_OK do not accept a type other than Status or 
StatusOr.}}
```

https://github.com/llvm/llvm-project/pull/77326
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[libcxx] [clang] [llvm] [compiler-rt] [mlir] [asan] Enable StackSafetyAnalysis by default (PR #77210)

2024-01-11 Thread Zequan Wu via cfe-commits

ZequanWu wrote:

Heads up! This causes clang crash:
cmd:
```
clang++ "-cc1" "-triple" "x86_64-apple-macosx10.15.0" 
"-Wundef-prefix=TARGET_OS_" "-Werror=undef-prefix" 
"-Wdeprecated-objc-isa-usage" "-Werror=deprecated-objc-isa-usage" "-emit-obj" 
"-femit-dwarf-unwind=no-compact-unwind" "-disable-free" 
"-clear-ast-before-backend" "-main-file-name" "glslang_lex_autogen.cpp" 
"-mrelocation-model" "pic" "-pic-level" "2" "-fmerge-all-constants" 
"-fno-delete-null-pointer-checks" "-mframe-pointer=all" "-relaxed-aliasing" 
"-ffp-contract=off" "-fno-rounding-math" "-funwind-tables=2" 
"-target-sdk-version=14.0" "-fcompatibility-qualified-id-block-type-checking" 
"-fvisibility-inlines-hidden-static-local-var" 
"-fbuiltin-headers-in-system-modules" "-target-cpu" "penryn" "-tune-cpu" 
"generic" "-debug-info-kind=line-tables-only" "-dwarf-version=4" 
"-debugger-tuning=lldb" 
"-fdebug-compilation-dir=/Volumes/Work/s/w/ir/cache/builder/src/out/Release" 
"-target-linker-version" "820.1" "-mllvm" 
"-crash-diagnostics-dir=../../tools/clang/crashreports" 
"-fcoverage-compilation-dir=/Volumes/Work/s/w/ir/cache/builder/src/out/Release" 
"-nostdinc++" "-D" "ANGLE_ENABLE_ESSL" "-D" "ANGLE_ENABLE_GLSL" "-D" 
"MEMORY_TOOL_REPLACES_ALLOCATOR" "-D" "ADDRESS_SANITIZER" "-D" 
"__STDC_CONSTANT_MACROS" "-D" "__STDC_FORMAT_MACROS" "-D" 
"_LIBCPP_HARDENING_MODE=_LIBCPP_HARDENING_MODE_EXTENSIVE" "-D" 
"CR_XCODE_VERSION=1500" "-D" 
"CR_CLANG_REVISION=\"llvmorg-18-init-16856-gd1ecd12f-0\"" "-D" 
"_LIBCPP_DISABLE_VISIBILITY_ANNOTATIONS" "-D" 
"_LIBCXXABI_DISABLE_VISIBILITY_ANNOTATIONS" "-D" 
"CR_LIBCXX_REVISION=e4aac3ace5ad6e3737740daee3afeaa9c9ab0360" "-D" "NDEBUG" 
"-D" "NVALGRIND" "-D" "DYNAMIC_ANNOTATIONS_ENABLED=0" "-D" 
"ANGLE_OUTSIDE_WEBKIT" "-D" "ANGLE_DELEGATE_WORKERS=1" "-D" "ANGLE_USE_ABSEIL" 
"-D" "ABSL_ALLOCATOR_NOTHROW=1" "-D" "__DATE__=" "-D" "__TIME__=" "-D" 
"__TIMESTAMP__=" "-O2" "-Wall" "-Wextra" "-Wimplicit-fallthrough" 
"-Wextra-semi" "-Wunreachable-code-aggressive" "-Wthread-safety" 
"-Wunguarded-availability" "-Wno-missing-field-initializers" 
"-Wno-unused-parameter" "-Wno-psabi" "-Wloop-analysis" 
"-Wno-unneeded-internal-declaration" "-Wenum-compare-conditional" 
"-Wno-ignored-pragma-optimize" "-Wno-deprecated-builtins" 
"-Wno-bitfield-constant-conversion" "-Wno-deprecated-this-capture" 
"-Wno-invalid-offsetof" "-Wno-vla-extension" 
"-Wno-thread-safety-reference-return" "-Wshadow" "-Wno-builtin-macro-redefined" 
"-Wheader-hygiene" "-Wstring-conversion" "-Wtautological-overlap-compare" 
"-Wexit-time-destructors" "-Wglobal-constructors" "-Wbad-function-cast" 
"-Wconditional-uninitialized" "-Wextra-semi-stmt" "-Wfloat-conversion" 
"-Winconsistent-missing-destructor-override" "-Wmissing-field-initializers" 
"-Wnewline-eof" "-Wnon-virtual-dtor" "-Wredundant-parens" "-Wreturn-std-move" 
"-Wshadow" "-Wshadow-field" "-Wtautological-type-limit-compare" 
"-Wundefined-reinterpret-cast" "-Wunneeded-internal-declaration" 
"-Wunused-but-set-variable" "-Wsuggest-destructor-override" 
"-Wsuggest-override" "-Wparentheses" "-Wrange-loop-analysis" 
"-Wstrict-prototypes" "-Wunreachable-code-aggressive" "-Wshorten-64-to-32" 
"-Wno-c++11-narrowing-const-reference" "-Wno-trigraphs" "-std=c++20" 
"-fdeprecated-macro" "-ferror-limit" "19" "-fvisibility=hidden" 
"-fvisibility-inlines-hidden" "-fsanitize=address" 
"-fno-sanitize-memory-param-retval" "-fsanitize-address-use-after-scope" 
"-fsanitize-address-globals-dead-stripping" "-fno-assume-sane-operator-new" 
"-stack-protector" "1" "-fblocks" "-fencode-extended-block-signature" 
"-fno-rtti" "-fregister-global-dtors-with-atexit" "-fgnuc-version=4.2.1" 
"-fno-implicit-modules" "-fmax-type-align=16" "-Qn" "-fcolor-diagnostics" 
"-vectorize-loops" "-vectorize-slp" "-mllvm" "-instcombine-lower-dbg-declare=0" 
"-mllvm" "-split-threshold-for-reg-with-hint=0" "-fcomplete-member-pointers" 
"-D__GCC_HAVE_DWARF2_CFI_ASM=1" "-x" "c++" "glslang_lex_autogen-7bfb0a.cpp"
```
Attached source code: 
[glslang_lex_autogen-7bfb0a.txt](https://github.com/llvm/llvm-project/files/13906543/glslang_lex_autogen-7bfb0a.txt)
 (Since it doesn't allow me to attach file ends with .cpp, I changed the suffix 
to .txt)


https://github.com/llvm/llvm-project/pull/77210
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[llvm] [libcxx] [compiler-rt] [clang] [mlir] [asan] Enable StackSafetyAnalysis by default (PR #77210)

2024-01-11 Thread Zequan Wu via cfe-commits

ZequanWu wrote:

Reverted at e7f794875169811f3801fad6d40bb9fe833e1a69. Will file an issue to 
track it once reducing is done.

https://github.com/llvm/llvm-project/pull/77210
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] 581dc3c - Revert "Lower `@llvm.global_dtors` using `__cxa_atexit` on MachO"

2022-03-23 Thread Zequan Wu via cfe-commits

Author: Zequan Wu
Date: 2022-03-23T16:11:54-07:00
New Revision: 581dc3c729c619fe636325a79279fabb2acdc1ce

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

LOG: Revert "Lower `@llvm.global_dtors` using `__cxa_atexit` on MachO"

This reverts commit 22570bac694396514fff18dec926558951643fa6.

Added: 
llvm/lib/Target/WebAssembly/WebAssemblyLowerGlobalDtors.cpp

Modified: 
clang/lib/CodeGen/BackendUtil.cpp
llvm/docs/Passes.rst
llvm/include/llvm/CodeGen/CommandFlags.h
llvm/include/llvm/CodeGen/TargetLoweringObjectFileImpl.h
llvm/include/llvm/InitializePasses.h
llvm/include/llvm/LinkAllPasses.h
llvm/include/llvm/Target/TargetOptions.h
llvm/include/llvm/Transforms/Instrumentation/AddressSanitizerOptions.h
llvm/include/llvm/Transforms/Utils.h
llvm/lib/CodeGen/CodeGen.cpp
llvm/lib/CodeGen/CommandFlags.cpp
llvm/lib/CodeGen/TargetLoweringObjectFileImpl.cpp
llvm/lib/CodeGen/TargetPassConfig.cpp
llvm/lib/Passes/PassBuilder.cpp
llvm/lib/Passes/PassRegistry.def
llvm/lib/Target/WebAssembly/CMakeLists.txt
llvm/lib/Target/WebAssembly/WebAssembly.h
llvm/lib/Target/WebAssembly/WebAssemblyTargetMachine.cpp
llvm/lib/Transforms/Utils/CMakeLists.txt
llvm/lib/Transforms/Utils/Utils.cpp
llvm/test/CodeGen/ARM/ctors_dtors.ll
llvm/test/CodeGen/X86/2011-08-29-InitOrder.ll

Removed: 
llvm/include/llvm/Transforms/Utils/LowerGlobalDtors.h
llvm/lib/Transforms/Utils/LowerGlobalDtors.cpp
llvm/test/Transforms/LowerGlobalDestructors/lower-global-dtors.ll



diff  --git a/clang/lib/CodeGen/BackendUtil.cpp 
b/clang/lib/CodeGen/BackendUtil.cpp
index eaf34eedcb2bb..0cffc34a02cc4 100644
--- a/clang/lib/CodeGen/BackendUtil.cpp
+++ b/clang/lib/CodeGen/BackendUtil.cpp
@@ -546,8 +546,6 @@ static bool initTargetOptions(DiagnosticsEngine &Diags,
   Options.BinutilsVersion =
   llvm::TargetMachine::parseBinutilsVersion(CodeGenOpts.BinutilsVersion);
   Options.UseInitArray = CodeGenOpts.UseInitArray;
-  Options.LowerGlobalDtorsViaCxaAtExit =
-  CodeGenOpts.RegisterGlobalDtorsWithAtExit;
   Options.DisableIntegratedAS = CodeGenOpts.DisableIntegratedAS;
   Options.CompressDebugSections = CodeGenOpts.getCompressDebugSections();
   Options.RelaxELFRelocations = CodeGenOpts.RelaxELFRelocations;

diff  --git a/llvm/docs/Passes.rst b/llvm/docs/Passes.rst
index 7c0666992e8f5..92f06496b4ef9 100644
--- a/llvm/docs/Passes.rst
+++ b/llvm/docs/Passes.rst
@@ -876,14 +876,6 @@ This pass expects :ref:`LICM ` to be run 
before it to hoist
 invariant conditions out of the loop, to make the unswitching opportunity
 obvious.
 
-``-lower-global-dtors``: Lower global destructors
-
-
-This pass lowers global module destructors (``llvm.global_dtors``) by creating
-wrapper functions that are registered as global constructors in
-``llvm.global_ctors`` and which contain a call to ``__cxa_atexit`` to register
-their destructor functions.
-
 ``-loweratomic``: Lower atomic intrinsics to non-atomic form
 
 

diff  --git a/llvm/include/llvm/CodeGen/CommandFlags.h 
b/llvm/include/llvm/CodeGen/CommandFlags.h
index 9281ed723854c..feb5de5415269 100644
--- a/llvm/include/llvm/CodeGen/CommandFlags.h
+++ b/llvm/include/llvm/CodeGen/CommandFlags.h
@@ -93,8 +93,6 @@ std::string getTrapFuncName();
 
 bool getUseCtors();
 
-bool getLowerGlobalDtorsViaCxaAtExit();
-
 bool getRelaxELFRelocations();
 
 bool getDataSections();

diff  --git a/llvm/include/llvm/CodeGen/TargetLoweringObjectFileImpl.h 
b/llvm/include/llvm/CodeGen/TargetLoweringObjectFileImpl.h
index 26bda8d5d239d..2a35987507446 100644
--- a/llvm/include/llvm/CodeGen/TargetLoweringObjectFileImpl.h
+++ b/llvm/include/llvm/CodeGen/TargetLoweringObjectFileImpl.h
@@ -119,9 +119,6 @@ class TargetLoweringObjectFileMachO : public 
TargetLoweringObjectFile {
 
   void Initialize(MCContext &Ctx, const TargetMachine &TM) override;
 
-  MCSection *getStaticDtorSection(unsigned Priority,
-  const MCSymbol *KeySym) const override;
-
   /// Emit the module flags that specify the garbage collection information.
   void emitModuleMetadata(MCStreamer &Streamer, Module &M) const override;
 

diff  --git a/llvm/include/llvm/InitializePasses.h 
b/llvm/include/llvm/InitializePasses.h
index 82aafe2744184..3a98bacef81d0 100644
--- a/llvm/include/llvm/InitializePasses.h
+++ b/llvm/include/llvm/InitializePasses.h
@@ -274,7 +274,6 @@ void initializeLowerAtomicLegacyPassPass(PassRegistry&);
 void initializeLowerConstantIntrinsicsPass(PassRegistry&);
 void initializeLowerEmuTLSPass(PassRegistry&);
 void initializeLowerExpectIntrinsicPass(PassRegistry&);
-void initializeLowerGlobalDtorsLegacyPas

[clang] d54c4df - [clang-format] Fix namespace format when the name is followed by a macro

2022-03-10 Thread Zequan Wu via cfe-commits

Author: Zequan Wu
Date: 2022-03-10T15:00:32-08:00
New Revision: d54c4df31470044a66605ebb8a2f936e8dd552af

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

LOG: [clang-format] Fix namespace format when the name is followed by a macro

Example:
```
$ cat a.cpp
namespace my_namespace::yeah API_AVAILABLE(macos(10.15)) {
void test() {}
}

$ clang-format a.cpp
namespace my_namespace::yeah API_AVAILABLE(macos(10.15)) {
void test() {}
}// namespace my_namespace::yeahAPI_AVAILABLE(macos(10.15))
```
After:
```
$ clang-format a.cpp
namespace my_namespace::yeah API_AVAILABLE(macos(10.15)) {
void test() {}
}// namespace my_namespace::yeah
```

Reviewed By: MyDeveloperDay, owenpan, curdeius

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

Added: 


Modified: 
clang/lib/Format/NamespaceEndCommentsFixer.cpp
clang/unittests/Format/NamespaceEndCommentsFixerTest.cpp

Removed: 




diff  --git a/clang/lib/Format/NamespaceEndCommentsFixer.cpp 
b/clang/lib/Format/NamespaceEndCommentsFixer.cpp
index e527402e33074..2615a499f7abf 100644
--- a/clang/lib/Format/NamespaceEndCommentsFixer.cpp
+++ b/clang/lib/Format/NamespaceEndCommentsFixer.cpp
@@ -13,6 +13,7 @@
 
//===--===//
 
 #include "NamespaceEndCommentsFixer.h"
+#include "clang/Basic/TokenKinds.h"
 #include "llvm/Support/Debug.h"
 #include "llvm/Support/Regex.h"
 
@@ -22,6 +23,40 @@ namespace clang {
 namespace format {
 
 namespace {
+// Iterates all tokens starting from StartTok to EndTok and apply Fn to all
+// tokens between them including StartTok and EndTok. Returns the token after
+// EndTok.
+const FormatToken *
+processTokens(const FormatToken *Tok, tok::TokenKind StartTok,
+  tok::TokenKind EndTok,
+  llvm::function_ref Fn) {
+  if (!Tok || Tok->isNot(StartTok))
+return Tok;
+  int NestLevel = 0;
+  do {
+if (Tok->is(StartTok))
+  ++NestLevel;
+else if (Tok->is(EndTok))
+  --NestLevel;
+if (Fn)
+  Fn(Tok);
+Tok = Tok->getNextNonComment();
+  } while (Tok && NestLevel > 0);
+  return Tok;
+}
+
+const FormatToken *skipAttribute(const FormatToken *Tok) {
+  if (!Tok)
+return nullptr;
+  if (Tok->is(tok::kw___attribute)) {
+Tok = Tok->getNextNonComment();
+Tok = processTokens(Tok, tok::l_paren, tok::r_paren, nullptr);
+  } else if (Tok->is(tok::l_square)) {
+Tok = processTokens(Tok, tok::l_square, tok::r_square, nullptr);
+  }
+  return Tok;
+}
+
 // Computes the name of a namespace given the namespace token.
 // Returns "" for anonymous namespace.
 std::string computeName(const FormatToken *NamespaceTok) {
@@ -39,48 +74,69 @@ std::string computeName(const FormatToken *NamespaceTok) {
   name += Tok->TokenText;
   Tok = Tok->getNextNonComment();
 }
-  } else {
-// Skip attributes.
-if (Tok && Tok->is(tok::l_square)) {
-  for (int NestLevel = 1; NestLevel > 0;) {
-Tok = Tok->getNextNonComment();
-if (!Tok)
-  break;
-if (Tok->is(tok::l_square))
-  ++NestLevel;
-else if (Tok->is(tok::r_square))
-  --NestLevel;
-  }
-  if (Tok)
-Tok = Tok->getNextNonComment();
-}
+return name;
+  }
+  Tok = skipAttribute(Tok);
 
-// Use the string after `namespace` as a name candidate until `{` or `::` 
or
-// `(`. If the name is empty, use the candicate.
-std::string FirstNSName;
-// For `namespace [[foo]] A::B::inline C {` or
-// `namespace MACRO1 MACRO2 A::B::inline C {`, returns "A::B::inline C".
-// Peek for the first '::' (or '{' or '(')) and then return all tokens from
-// one token before that up until the '{'. A '(' might be a macro with
-// arguments.
-const FormatToken *FirstNSTok = Tok;
-while (Tok && !Tok->isOneOf(tok::l_brace, tok::coloncolon, tok::l_paren)) {
+  std::string FirstNSName;
+  // For `namespace [[foo]] A::B::inline C {` or
+  // `namespace MACRO1 MACRO2 A::B::inline C {`, returns "A::B::inline C".
+  // Peek for the first '::' (or '{' or '(')) and then return all tokens from
+  // one token before that up until the '{'. A '(' might be a macro with
+  // arguments.
+  const FormatToken *FirstNSTok = nullptr;
+  while (Tok && !Tok->isOneOf(tok::l_brace, tok::coloncolon, tok::l_paren)) {
+if (FirstNSTok)
   FirstNSName += FirstNSTok->TokenText;
-  FirstNSTok = Tok;
-  Tok = Tok->getNextNonComment();
-}
+FirstNSTok = Tok;
+Tok = Tok->getNextNonComment();
+  }
 
+  if (FirstNSTok)
 Tok = FirstNSTok;
-while (Tok && !Tok->is(tok::l_brace)) {
-  name += Tok->TokenText;
-  if (Tok->is(tok::kw_inline))
+  Tok = skipAttribute(Tok);
+
+  FirstNSTok = nullptr;
+  // Add everything from '(' to ')'.
+  auto AddToken

[clang-tools-extra] 217f267 - Revert "[pseudo] Split greatergreater token."

2022-03-18 Thread Zequan Wu via cfe-commits

Author: Zequan Wu
Date: 2022-03-18T10:15:48-07:00
New Revision: 217f267efe3082438e698e2f08566b9df8c530fa

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

LOG: Revert "[pseudo] Split greatergreater token."

This reverts commit f66d3758bda99e9f57bfdad168212feda18792ae.

It breaks windows bot.

Added: 


Modified: 
clang-tools-extra/pseudo/include/clang-pseudo/Token.h
clang-tools-extra/pseudo/lib/Lex.cpp
clang-tools-extra/pseudo/lib/cxx.bnf
clang-tools-extra/pseudo/unittests/TokenTest.cpp

Removed: 




diff  --git a/clang-tools-extra/pseudo/include/clang-pseudo/Token.h 
b/clang-tools-extra/pseudo/include/clang-pseudo/Token.h
index 4563477b2c4fe..24b6729151e61 100644
--- a/clang-tools-extra/pseudo/include/clang-pseudo/Token.h
+++ b/clang-tools-extra/pseudo/include/clang-pseudo/Token.h
@@ -180,8 +180,7 @@ enum class LexFlags : uint8_t {
   NeedsCleaning = 1 << 1,
 };
 
-/// Derives a token stream by decoding escapes, interpreting raw_identifiers 
and
-/// splitting the greatergreater token.
+/// Derives a token stream by decoding escapes and interpreting 
raw_identifiers.
 ///
 /// Tokens containing UCNs, escaped newlines, trigraphs etc are decoded and
 /// their backing data is owned by the returned stream.

diff  --git a/clang-tools-extra/pseudo/lib/Lex.cpp 
b/clang-tools-extra/pseudo/lib/Lex.cpp
index e99bf3a63e5e1..f5a239533c532 100644
--- a/clang-tools-extra/pseudo/lib/Lex.cpp
+++ b/clang-tools-extra/pseudo/lib/Lex.cpp
@@ -98,21 +98,9 @@ TokenStream cook(const TokenStream &Code, const LangOptions 
&LangOpts) {
   Tok.Length = Text.size();
   Tok.Flags &= ~static_cast(LexFlags::NeedsCleaning);
 }
-
-if (Tok.Kind == tok::raw_identifier) {
-  // Cook raw_identifiers into identifier, keyword, etc.
+// Cook raw_identifiers into identifier, keyword, etc.
+if (Tok.Kind == tok::raw_identifier)
   Tok.Kind = Identifiers.get(Tok.text()).getTokenID();
-} else if (Tok.Kind == tok::greatergreater) {
-  // Split the greatergreater token.
-  // FIXME: split lessless token to support Cuda triple angle brackets <<<.
-  assert(Tok.text() == ">>");
-  Tok.Kind = tok::greater;
-  Tok.Length = 1;
-  Result.push(Tok);
-  // Line is wrong if the first greater is followed by an escaped newline!
-  Tok.Data = Tok.text().data() + 1;
-}
-
 Result.push(std::move(Tok));
   }
 

diff  --git a/clang-tools-extra/pseudo/lib/cxx.bnf 
b/clang-tools-extra/pseudo/lib/cxx.bnf
index cf664b8e13e55..48bf4621eefe5 100644
--- a/clang-tools-extra/pseudo/lib/cxx.bnf
+++ b/clang-tools-extra/pseudo/lib/cxx.bnf
@@ -13,9 +13,6 @@
 #  - the file merely describes the core C++ grammar. Preprocessor directives 
and
 #lexical conversions are omitted as we reuse clang's lexer and run a fake
 #preprocessor;
-#  - grammar rules with the >> token are adjusted, the greatergreater token is
-#split into two > tokens, to make the GLR parser aware of nested templates
-#and right shift operator;
 #
 # Guidelines:
 #   - nonterminals are lower_case; terminals (aka tokens) correspond to
@@ -99,7 +96,7 @@ fold-operator := %
 fold-operator := ^
 fold-operator := |
 fold-operator := <<
-fold-operator := greatergreater
+fold-operator := >>
 fold-operator := +=
 fold-operator := -=
 fold-operator := *=
@@ -205,7 +202,7 @@ additive-expression := additive-expression - 
multiplicative-expression
 # expr.shift
 shift-expression := additive-expression
 shift-expression := shift-expression << additive-expression
-shift-expression := shift-expression greatergreater additive-expression
+shift-expression := shift-expression >> additive-expression
 # expr.spaceship
 compare-expression := shift-expression
 compare-expression := compare-expression <=> shift-expression
@@ -618,7 +615,7 @@ operator-name := <=>
 operator-name := ^^
 operator-name := ||
 operator-name := <<
-operator-name := greatergreater
+operator-name := >>
 operator-name := <<=
 operator-name := >>=
 operator-name := ++
@@ -740,8 +737,3 @@ contextual-zero := NUMERIC_CONSTANT
 module-keyword := IDENTIFIER
 import-keyword := IDENTIFIER
 export-keyword := IDENTIFIER
-
-#! greatergreater token -- clang lexer always lexes it as a single token, we
-#! split it into two tokens to make the GLR parser aware of the nested-template
-#! case.
-greatergreater := > >

diff  --git a/clang-tools-extra/pseudo/unittests/TokenTest.cpp 
b/clang-tools-extra/pseudo/unittests/TokenTest.cpp
index b17f8c93c1763..1357d23501193 100644
--- a/clang-tools-extra/pseudo/unittests/TokenTest.cpp
+++ b/clang-tools-extra/pseudo/unittests/TokenTest.cpp
@@ -171,25 +171,6 @@ no_indent \
 }));
 }
 
-TEST(TokenTest, SplitGreaterGreater) {
-  LangOptions Opts;
-  std::string Code = R"cpp(
->> // split

[clang] d870a57 - [SemaCXX] Set promotion type for enum if its type is promotable to integer type even if it has no definition.

2022-07-21 Thread Zequan Wu via cfe-commits

Author: Zequan Wu
Date: 2022-07-21T11:23:21-07:00
New Revision: d870a575631d2cedab2ff237af8edd17916edc64

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

LOG: [SemaCXX] Set promotion type for enum if its type is promotable to integer 
type even if it has no definition.

EnumDecl's promotion type is set either to the parsed type or calculated type
after completing its definition. When it's bool type and has no definition,
its promotion type is bool which is not allowed by clang.

Fixes #56560.

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

Added: 


Modified: 
clang/docs/ReleaseNotes.rst
clang/lib/Sema/SemaDecl.cpp
clang/test/CXX/conv/conv.prom/p4.cpp

Removed: 




diff  --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index cb64cd21fe853..d65fcdbeaa62d 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -192,6 +192,8 @@ Bug Fixes
   Fixes `Issue 56310 `_.
 - Clang will now look through type sugar when checking a member function is a
   move assignment operator. Fixes `Issue 56456 
`_.
+- Fixed a crash when a variable with a bool enum type that has no definition
+  used in comparison operators. Fixes `Issue 56560 
`_.
 
 Improvements to Clang's diagnostics
 ^^^

diff  --git a/clang/lib/Sema/SemaDecl.cpp b/clang/lib/Sema/SemaDecl.cpp
index 736c299f38bb8..8d2fc5331a0df 100644
--- a/clang/lib/Sema/SemaDecl.cpp
+++ b/clang/lib/Sema/SemaDecl.cpp
@@ -16209,7 +16209,10 @@ Decl *Sema::ActOnTag(Scope *S, unsigned TagSpec, 
TagUseKind TUK,
   ED->setIntegerTypeSourceInfo(TI);
 else
   ED->setIntegerType(QualType(EnumUnderlying.get(), 0));
-ED->setPromotionType(ED->getIntegerType());
+QualType EnumTy = ED->getIntegerType();
+ED->setPromotionType(EnumTy->isPromotableIntegerType()
+ ? Context.getPromotedIntegerType(EnumTy)
+ : EnumTy);
   }
 } else { // struct/union
   New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
@@ -16831,8 +16834,11 @@ Decl *Sema::ActOnTag(Scope *S, unsigned TagSpec, 
TagUseKind TUK,
   if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast())
 ED->setIntegerTypeSourceInfo(TI);
   else
-ED->setIntegerType(QualType(EnumUnderlying.get(), 0));
-  ED->setPromotionType(ED->getIntegerType());
+ED->setIntegerType(QualType(EnumUnderlying.get(), 0));
+  QualType EnumTy = ED->getIntegerType();
+  ED->setPromotionType(EnumTy->isPromotableIntegerType()
+   ? Context.getPromotedIntegerType(EnumTy)
+   : EnumTy);
   assert(ED->isComplete() && "enum with type should be complete");
 }
   } else {

diff  --git a/clang/test/CXX/conv/conv.prom/p4.cpp 
b/clang/test/CXX/conv/conv.prom/p4.cpp
index 8c86d2a1838da..be422f362d6e3 100644
--- a/clang/test/CXX/conv/conv.prom/p4.cpp
+++ b/clang/test/CXX/conv/conv.prom/p4.cpp
@@ -26,3 +26,10 @@ enum B2 : bool {
   // FIXME: DR1407 will make this ill-formed
   e = +false_ // desired-error {{conversion from 'int' to 'bool'}}
 };
+
+namespace GH56560 {
+enum GH56560_1 : bool;
+bool GH56560_2(GH56560_1 a, GH56560_1 b) {
+return a == b;
+}
+} // namespace GH56560



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


[clang] [llvm] Use timeTraceAsyncProfilerBegin for Source span (PR #83961)

2024-03-13 Thread Zequan Wu via cfe-commits

ZequanWu wrote:

> > > > IIUC, the approach you choose here is to let `SemaPPCallbacks` control 
> > > > the "entered file stack" and allow it to remove element (which is file) 
> > > > from middle of the internal stack in `TimeTraceProfiler`, but this 
> > > > creates async event which is not designed for this purpose.
> > > > Can we let `SemaPPCallbacks` track the last push file into the stack 
> > > > and when exit file, pop all the elements from the stack until we popped 
> > > > the last pushed file?
> > > 
> > > 
> > > As I wrote in [#56554 
> > > (comment)](https://github.com/llvm/llvm-project/issues/56554#issuecomment-1975812398),
> > >  file level span and syntax tree level span should be handled 
> > > asynchronously. So using such implementation produces incorrect trace in 
> > > other edge cases.
> > 
> > 
> > Can we choose to expose a handle (maybe an unique id for each entry) from 
> > `TimeTraceProfiler` instead of exposing the internal entry?
> 
> I think pointer to `TimeTraceProfilerEntry` is already like handle as 
> definition of the struct is not written in header file. Having another handle 
> for that seems unnecessary indirection layer to me. Or better to change the 
> name of struct?

Okay, make sense. Looks good for me.
Adding @MaskRay to review in case he has something to say.

https://github.com/llvm/llvm-project/pull/83961
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] Use timeTraceAsyncProfilerBegin for Source span (PR #83961)

2024-03-25 Thread Zequan Wu via cfe-commits

https://github.com/ZequanWu approved this pull request.


https://github.com/llvm/llvm-project/pull/83961
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] Use timeTraceAsyncProfilerBegin for Source span (PR #83961)

2024-03-25 Thread Zequan Wu via cfe-commits

https://github.com/ZequanWu edited 
https://github.com/llvm/llvm-project/pull/83961
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] Use timeTraceAsyncProfilerBegin for Source span (PR #83961)

2024-03-25 Thread Zequan Wu via cfe-commits


@@ -102,23 +104,24 @@ struct llvm::TimeTraceProfiler {
 llvm::get_thread_name(ThreadName);
   }
 
-  void begin(std::string Name, llvm::function_ref Detail) {
-Stack.emplace_back(ClockType::now(), TimePointType(), std::move(Name),
-   Detail());
+  TimeTraceProfilerEntry *begin(std::string Name,
+llvm::function_ref Detail,
+bool AsyncEvent = false) {
+Stack.emplace_back(std::make_unique(
+ClockType::now(), TimePointType(), std::move(Name), Detail(),
+AsyncEvent));
+return Stack.back().get();
   }
 
   void end() {
+TimeTraceProfilerEntry *E = Stack.back().get();

ZequanWu wrote:

Yeah. But usually assertions goes before use. `end()` uses `Stack.back()` which 
assumes stack is non-empty.

https://github.com/llvm/llvm-project/pull/83961
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [llvm] Use timeTraceAsyncProfilerBegin for Source span (PR #83961)

2024-03-11 Thread Zequan Wu via cfe-commits


@@ -102,23 +104,24 @@ struct llvm::TimeTraceProfiler {
 llvm::get_thread_name(ThreadName);
   }
 
-  void begin(std::string Name, llvm::function_ref Detail) {
-Stack.emplace_back(ClockType::now(), TimePointType(), std::move(Name),
-   Detail());
+  TimeTraceProfilerEntry *begin(std::string Name,
+llvm::function_ref Detail,
+bool AsyncEvent = false) {
+Stack.emplace_back(std::make_unique(
+ClockType::now(), TimePointType(), std::move(Name), Detail(),
+AsyncEvent));
+return Stack.back().get();
   }
 
   void end() {
+TimeTraceProfilerEntry *E = Stack.back().get();

ZequanWu wrote:

If we extract end(TimeTraceProfilerEntry &E) to a separate function, probably 
want to move the assertion to here as well

https://github.com/llvm/llvm-project/pull/83961
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [llvm] Use timeTraceAsyncProfilerBegin for Source span (PR #83961)

2024-03-11 Thread Zequan Wu via cfe-commits

https://github.com/ZequanWu edited 
https://github.com/llvm/llvm-project/pull/83961
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [llvm] Use timeTraceAsyncProfilerBegin for Source span (PR #83961)

2024-03-11 Thread Zequan Wu via cfe-commits

https://github.com/ZequanWu commented:

IIUC, the approach you choose here is to let `SemaPPCallbacks` control the 
"entered file stack" and allow it to remove element (which is file) from middle 
of the internal stack in `TimeTraceProfiler`, but this creates async event 
which is not designed for this purpose.

Can we let `SemaPPCallbacks` track the last push file into the stack and when 
exit file, pop all the elements from the stack until we popped the last pushed 
file?



https://github.com/llvm/llvm-project/pull/83961
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [llvm] Use timeTraceAsyncProfilerBegin for Source span (PR #83961)

2024-03-11 Thread Zequan Wu via cfe-commits


@@ -132,15 +135,18 @@ struct llvm::TimeTraceProfiler {
 // happens to be the ones that don't have any currently open entries above
 // itself.
 if (llvm::none_of(llvm::drop_begin(llvm::reverse(Stack)),
-  [&](const TimeTraceProfilerEntry &Val) {
-return Val.Name == E.Name;
+  [&](const std::unique_ptr &Val) {
+return Val->Name == E.Name;
   })) {
   auto &CountAndTotal = CountAndTotalPerName[E.Name];
   CountAndTotal.first++;
   CountAndTotal.second += Duration;
-}
+};

ZequanWu wrote:

Unnecessary change.
```suggestion
}
```

https://github.com/llvm/llvm-project/pull/83961
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


  1   2   3   >