[PATCH] D83115: [Analyzer] Report every bug if only uniqueing location differs.

2020-07-13 Thread Artem Dergachev via Phabricator via cfe-commits
NoQ accepted this revision.
NoQ added inline comments.
This revision is now accepted and ready to land.



Comment at: clang/lib/Analysis/PathDiagnostic.cpp:1136-1137
   ID.Add(getLocation());
+  ID.Add(getUniqueingLoc());
+  ID.AddPointer(getUniqueingLoc().isValid() ? getUniqueingDecl() : nullptr);
   ID.AddString(BugType);

Szelethus wrote:
> This looks a bit odd -- why do we need both of these?
> 
> Also, didn't we use uniqueing location in the `BugReportEquivClass` or 
> whatever its called? Why do we need to add this here as well? I would like 
> some technical explanation.
As of now it probably does nothing. But technically we allow our users to set a 
completely arbitrary uniqueing decl that doesn't necessarily correspond to the 
uniqueing location, so we'll probably need to take it into account.

Generally, uniqueing decls are for uniqueing and otherwise identifying bugs 
regardless of slight changes in the source code. Currently this means issue 
hashes.



Comment at: clang/test/Analysis/malloc.c:793
   int *p = malloc(12);
   p = malloc(12);
+} // expected-warning {{Potential leak of memory pointed to by}}\

Szelethus wrote:
> On an unrelated note, shouldn't one of the notes be here? @NoQ, is this the 
> same issue as the one you raised with zombie symbols? 
> http://lists.llvm.org/pipermail/cfe-dev/2016-March/047922.html
The warning about the first malloc indeed probably required the zombie symbol 
bug to be fixed. That said, the warning isn't really guaranteed to be on that 
line, because there's no guarantee that dead symbol collection runs 
*immediately* after the overwrite (which causes the symbol to become dead), and 
the overwrite is in fact the last thing that happens in this function.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D83115



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


[PATCH] D82470: [OpenMP][IRBuilder] Support allocas in nested parallel regions

2020-07-13 Thread Fady Ghanim via Phabricator via cfe-commits
fghanim added a comment.

Thanks for the update. Just a couple of Nits, and a quick note




Comment at: llvm/include/llvm/Frontend/OpenMP/OMPIRBuilder.h:288
   struct OutlineInfo {
-SmallVector Blocks;
 using PostOutlineCBTy = std::function;

Nit: isn't this supposed to be part of one of the other patches you split of 
this?



Comment at: llvm/lib/Frontend/OpenMP/OMPIRBuilder.cpp:433
 
-  Builder.SetInsertPoint(OuterFn->getEntryBlock().getFirstNonPHI());
-  AllocaInst *TIDAddr = Builder.CreateAlloca(Int32, nullptr, "tid.addr");
-  AllocaInst *ZeroAddr = Builder.CreateAlloca(Int32, nullptr, "zero.addr");
+  IRBuilder<> AllocaBuilder(AllocaIP.getBlock(), AllocaIP.getPoint());
+

Here and elsewhere: You seem to have forgotten to undo the changes introduced 
by using a separate `AllocaBuilder`?

Also, Nit: before using `AllocaIP`, either add an assert that it is not empty, 
or alternatively, add logic to just set it to entry block of `outerfn` if it is



Comment at: llvm/lib/Frontend/OpenMP/OMPIRBuilder.cpp:490
   // of the outlined function.
-  InsertPointTy AllocaIP(PRegEntryBB,
- PRegEntryBB->getTerminator()->getIterator());
-  Builder.restoreIP(AllocaIP);
+  AllocaIP =
+  InsertPointTy(PRegEntryBB, PRegEntryBB->getTerminator()->getIterator());

NIT: I think it would be better to give each a different name, to avoid 
unnecessary confusion. maybe `OuterAllocaIP` and `innerAllocaIP`? Also, we 
don't overwrite the `outerAllocaIP` in case it's needed later?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D82470



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


[PATCH] D67420: [analyzer] NFC: Separate PathDiagnosticConsumer options from AnalyzerOptions.

2020-07-13 Thread Artem Dergachev via Phabricator via cfe-commits
NoQ added a comment.

@vsavchenko and others just joining: The backstory and the overall plan are in 
this thread: http://lists.llvm.org/pipermail/cfe-dev/2019-August/063092.html. 
Continued at http://lists.llvm.org/pipermail/cfe-dev/2019-September/063229.html.


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

https://reviews.llvm.org/D67420



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


[PATCH] D67420: [analyzer] NFC: Separate PathDiagnosticConsumer options from AnalyzerOptions.

2020-07-13 Thread Artem Dergachev via Phabricator via cfe-commits
NoQ added a reviewer: vsavchenko.
NoQ added inline comments.



Comment at: clang/include/clang/Analysis/PathDiagnostic.h:81
+  /// because deterministic mode is always superior when done right, but
+  /// for some consumers is experimental and needs to be off by default.
+  bool ShouldWriteStableReportFilename;

Szelethus wrote:
> gribozavr wrote:
> > "but for some consumers is experimental" -- parse error. What is 
> > experimental?
> I suspect you copied these from the `.def` file, did you change the 
> descriptions there too?
Nope, these were hand-written. I tried to make sure they don't mention any 
static analyzer specific things.


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

https://reviews.llvm.org/D67420



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


[PATCH] D67420: [analyzer] NFC: Separate PathDiagnosticConsumer options from AnalyzerOptions.

2020-07-13 Thread Artem Dergachev via Phabricator via cfe-commits
NoQ updated this revision to Diff 277652.
NoQ marked 2 inline comments as done.
NoQ added a comment.
Herald added subscribers: ASDenysPetrov, martong.

Rebase!! This work was on hiatus but i plan to continue.

Address a review comment.

There are two new path diagnostic options since the last patch that correspond 
to the optional behaviors of the text consumer that were introduced since last 
revision:

- `ShouldApplyFixIts`;
- `ShouldDisplayDiagnosticName`.


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

https://reviews.llvm.org/D67420

Files:
  clang/include/clang/Analysis/PathDiagnostic.h
  clang/include/clang/StaticAnalyzer/Core/AnalyzerOptions.h
  clang/include/clang/StaticAnalyzer/Core/PathDiagnosticConsumers.h
  clang/lib/StaticAnalyzer/Core/HTMLDiagnostics.cpp
  clang/lib/StaticAnalyzer/Core/PlistDiagnostics.cpp
  clang/lib/StaticAnalyzer/Core/SarifDiagnostics.cpp
  clang/lib/StaticAnalyzer/Core/TextDiagnostics.cpp
  clang/lib/StaticAnalyzer/Frontend/AnalysisConsumer.cpp

Index: clang/lib/StaticAnalyzer/Frontend/AnalysisConsumer.cpp
===
--- clang/lib/StaticAnalyzer/Frontend/AnalysisConsumer.cpp
+++ clang/lib/StaticAnalyzer/Frontend/AnalysisConsumer.cpp
@@ -150,7 +150,7 @@
   break;
 #define ANALYSIS_DIAGNOSTICS(NAME, CMDFLAG, DESC, CREATEFN)\
   case PD_##NAME:  \
-CREATEFN(*Opts.get(), PathConsumers, OutDir, PP, CTU); \
+CREATEFN(Opts->getDiagOpts(), PathConsumers, OutDir, PP, CTU); \
 break;
 #include "clang/StaticAnalyzer/Core/Analyses.def"
 default:
Index: clang/lib/StaticAnalyzer/Core/TextDiagnostics.cpp
===
--- clang/lib/StaticAnalyzer/Core/TextDiagnostics.cpp
+++ clang/lib/StaticAnalyzer/Core/TextDiagnostics.cpp
@@ -34,20 +34,14 @@
 /// type to the standard error, or to to compliment many others. Emits detailed
 /// diagnostics in textual format for the 'text' output type.
 class TextDiagnostics : public PathDiagnosticConsumer {
+  PathDiagnosticConsumerOptions DiagOpts;
   DiagnosticsEngine 
   const LangOptions 
-  const bool IncludePath = false;
-  const bool ShouldEmitAsError = false;
-  const bool ApplyFixIts = false;
-  const bool ShouldDisplayCheckerName = false;
 
 public:
-  TextDiagnostics(DiagnosticsEngine , const LangOptions ,
-  bool ShouldIncludePath, const AnalyzerOptions )
-  : DiagEng(DiagEng), LO(LO), IncludePath(ShouldIncludePath),
-ShouldEmitAsError(AnOpts.AnalyzerWerror),
-ApplyFixIts(AnOpts.ShouldApplyFixIts),
-ShouldDisplayCheckerName(AnOpts.ShouldDisplayCheckerNameForText) {}
+  TextDiagnostics(PathDiagnosticConsumerOptions DiagOpts,
+  DiagnosticsEngine , const LangOptions )
+  : DiagOpts(std::move(DiagOpts)), DiagEng(DiagEng), LO(LO) {}
   ~TextDiagnostics() override {}
 
   StringRef getName() const override { return "TextDiagnostics"; }
@@ -56,13 +50,13 @@
   bool supportsCrossFileDiagnostics() const override { return true; }
 
   PathGenerationScheme getGenerationScheme() const override {
-return IncludePath ? Minimal : None;
+return DiagOpts.ShouldDisplayPathNotes ? Minimal : None;
   }
 
   void FlushDiagnosticsImpl(std::vector ,
 FilesMade *filesMade) override {
 unsigned WarnID =
-ShouldEmitAsError
+DiagOpts.ShouldDisplayWarningsAsErrors
 ? DiagEng.getCustomDiagID(DiagnosticsEngine::Error, "%0")
 : DiagEng.getCustomDiagID(DiagnosticsEngine::Warning, "%0");
 unsigned NoteID = DiagEng.getCustomDiagID(DiagnosticsEngine::Note, "%0");
@@ -72,7 +66,7 @@
 auto reportPiece = [&](unsigned ID, FullSourceLoc Loc, StringRef String,
ArrayRef Ranges,
ArrayRef Fixits) {
-  if (!ApplyFixIts) {
+  if (!DiagOpts.ShouldApplyFixIts) {
 DiagEng.Report(Loc, ID) << String << Ranges << Fixits;
 return;
   }
@@ -92,9 +86,10 @@
  E = Diags.end();
  I != E; ++I) {
   const PathDiagnostic *PD = *I;
-  std::string WarningMsg =
-  (ShouldDisplayCheckerName ? " [" + PD->getCheckerName() + "]" : "")
-  .str();
+  std::string WarningMsg = (DiagOpts.ShouldDisplayDiagnosticName
+? " [" + PD->getCheckerName() + "]"
+: "")
+   .str();
 
   reportPiece(WarnID, PD->getLocation().asLocation(),
   (PD->getShortDescription() + WarningMsg).str(),
@@ -110,7 +105,7 @@
 Piece->getFixits());
   }
 
-  if (!IncludePath)
+  if (!DiagOpts.ShouldDisplayPathNotes)
 continue;
 
   // Then, add the path notes if necessary.
@@ -125,7 +120,7 @@
   }
 }
 
-if (!ApplyFixIts || 

[PATCH] D82431: [PowerPC][Power10] Implement Test LSB by Byte Builtins in LLVM/Clang

2020-07-13 Thread Amy Kwan via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG62f5ba624bfb: [PowerPC][Power10] Implement Test LSB by Byte 
Builtins in LLVM/Clang (authored by amyk).

Changed prior to commit:
  https://reviews.llvm.org/D82431?vs=274667=277646#toc

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D82431

Files:
  clang/include/clang/Basic/BuiltinsPPC.def
  clang/lib/Headers/altivec.h
  clang/test/CodeGen/builtins-ppc-p10vector.c
  llvm/include/llvm/IR/IntrinsicsPowerPC.td
  llvm/lib/Target/PowerPC/PPCInstrPrefix.td
  llvm/test/CodeGen/PowerPC/builtins-ppc-p10vsx.ll

Index: llvm/test/CodeGen/PowerPC/builtins-ppc-p10vsx.ll
===
--- /dev/null
+++ llvm/test/CodeGen/PowerPC/builtins-ppc-p10vsx.ll
@@ -0,0 +1,35 @@
+; NOTE: Assertions have been autogenerated by utils/update_llc_test_checks.py
+; RUN: llc -verify-machineinstrs -mtriple=powerpc64le-unknown-linux-gnu \
+; RUN:   -mcpu=pwr10 -ppc-asm-full-reg-names -ppc-vsr-nums-as-vr < %s | \
+; RUN:   FileCheck %s
+
+; These test cases aims to test the builtins for the Power10 VSX vector
+; instructions introduced in ISA 3.1.
+
+declare i32 @llvm.ppc.vsx.xvtlsbb(<16 x i8>, i1)
+
+define signext i32 @test_vec_test_lsbb_all_ones(<16 x i8> %vuca) {
+; CHECK-LABEL: test_vec_test_lsbb_all_ones:
+; CHECK:   # %bb.0: # %entry
+; CHECK-NEXT:xvtlsbb cr0, v2
+; CHECK-NEXT:mfocrf r3, 128
+; CHECK-NEXT:srwi r3, r3, 31
+; CHECK-NEXT:extsw r3, r3
+; CHECK-NEXT:blr
+entry:
+  %0 = tail call i32 @llvm.ppc.vsx.xvtlsbb(<16 x i8> %vuca, i1 1)
+  ret i32 %0
+}
+
+define signext i32 @test_vec_test_lsbb_all_zeros(<16 x i8> %vuca) {
+; CHECK-LABEL: test_vec_test_lsbb_all_zeros:
+; CHECK:   # %bb.0: # %entry
+; CHECK-NEXT:xvtlsbb cr0, v2
+; CHECK-NEXT:mfocrf r3, 128
+; CHECK-NEXT:rlwinm r3, r3, 3, 31, 31
+; CHECK-NEXT:extsw r3, r3
+; CHECK-NEXT:blr
+entry:
+  %0 = tail call i32 @llvm.ppc.vsx.xvtlsbb(<16 x i8> %vuca, i1 0)
+  ret i32 %0
+}
Index: llvm/lib/Target/PowerPC/PPCInstrPrefix.td
===
--- llvm/lib/Target/PowerPC/PPCInstrPrefix.td
+++ llvm/lib/Target/PowerPC/PPCInstrPrefix.td
@@ -396,6 +396,25 @@
   let Inst{63} = XT{5};
 }
 
+// [PO BF / XO2 B XO BX /]
+class XX2_BF3_XO5_XB6_XO9 opcode, bits<5> xo2, bits<9> xo, dag OOL,
+  dag IOL, string asmstr, InstrItinClass itin,
+  list pattern>
+  : I {
+  bits<3> BF;
+  bits<6> XB;
+
+  let Pattern = pattern;
+
+  let Inst{6-8}   = BF;
+  let Inst{9-10}  = 0;
+  let Inst{11-15} = xo2;
+  let Inst{16-20} = XB{4-0};
+  let Inst{21-29} = xo;
+  let Inst{30}= XB{5};
+  let Inst{31}= 0;
+}
+
 multiclass MLS_DForm_R_SI34_RTA5_MEM_p opcode, dag OOL, dag IOL,
dag PCRel_IOL, string asmstr,
InstrItinClass itin> {
@@ -943,6 +962,9 @@
  [(set v16i8:$vD,
(int_ppc_altivec_vclrrb v16i8:$vA, i32:$rB))]>;
 
+  def XVTLSBB : XX2_BF3_XO5_XB6_XO9<60, 2, 475, (outs crrc:$BF), (ins vsrc:$XB),
+"xvtlsbb $BF, $XB", IIC_VecGeneral, []>;
+
   // The XFormMemOp flag for the following 8 instructions is set on
   // the instruction format.
   let mayLoad = 1, mayStore = 0 in {
@@ -960,8 +982,6 @@
   }
 }
 
-
-
 // Anonymous Patterns //
 let Predicates = [IsISA3_1] in {
   def : Pat<(v16i8 (int_ppc_vsx_xxgenpcvbm v16i8:$VRB, imm:$IMM)),
@@ -972,6 +992,10 @@
 (v4i32 (COPY_TO_REGCLASS (XXGENPCVWM $VRB, imm:$IMM), VRRC))>;
   def : Pat<(v2i64 (int_ppc_vsx_xxgenpcvdm v2i64:$VRB, imm:$IMM)),
 (v2i64 (COPY_TO_REGCLASS (XXGENPCVDM $VRB, imm:$IMM), VRRC))>;
+  def : Pat<(i32 (int_ppc_vsx_xvtlsbb v16i8:$XB, -1)),
+(EXTRACT_SUBREG (XVTLSBB (COPY_TO_REGCLASS $XB, VSRC)), sub_lt)>;
+  def : Pat<(i32 (int_ppc_vsx_xvtlsbb v16i8:$XB, 0)),
+(EXTRACT_SUBREG (XVTLSBB (COPY_TO_REGCLASS $XB, VSRC)), sub_eq)>;
 }
 
 let AddedComplexity = 400, Predicates = [PrefixInstrs] in {
Index: llvm/include/llvm/IR/IntrinsicsPowerPC.td
===
--- llvm/include/llvm/IR/IntrinsicsPowerPC.td
+++ llvm/include/llvm/IR/IntrinsicsPowerPC.td
@@ -1067,6 +1067,9 @@
   PowerPC_VSX_Intrinsic<"xxinsertw",[llvm_v4i32_ty],
 [llvm_v4i32_ty,llvm_v2i64_ty,llvm_i32_ty],
 [IntrNoMem]>;
+def int_ppc_vsx_xvtlsbb :
+  PowerPC_VSX_Intrinsic<"xvtlsbb", [llvm_i32_ty],
+[llvm_v16i8_ty, llvm_i1_ty], [IntrNoMem]>;
 def int_ppc_vsx_xxeval :
   PowerPC_VSX_Intrinsic<"xxeval", [llvm_v2i64_ty],
[llvm_v2i64_ty, llvm_v2i64_ty,
Index: 

[clang] 62f5ba6 - [PowerPC][Power10] Implement Test LSB by Byte Builtins in LLVM/Clang

2020-07-13 Thread Amy Kwan via cfe-commits

Author: Amy Kwan
Date: 2020-07-13T22:47:47-05:00
New Revision: 62f5ba624bfba5ccf4446737ad2bfb1fc013b376

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

LOG: [PowerPC][Power10] Implement Test LSB by Byte Builtins in LLVM/Clang

This patch implements builtins for the Test LSB by Byte instruction introduced
in Power10.

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

Added: 
llvm/test/CodeGen/PowerPC/builtins-ppc-p10vsx.ll

Modified: 
clang/include/clang/Basic/BuiltinsPPC.def
clang/lib/Headers/altivec.h
clang/test/CodeGen/builtins-ppc-p10vector.c
llvm/include/llvm/IR/IntrinsicsPowerPC.td
llvm/lib/Target/PowerPC/PPCInstrPrefix.td

Removed: 




diff  --git a/clang/include/clang/Basic/BuiltinsPPC.def 
b/clang/include/clang/Basic/BuiltinsPPC.def
index d0df5fcd1552..6b291e6b0806 100644
--- a/clang/include/clang/Basic/BuiltinsPPC.def
+++ b/clang/include/clang/Basic/BuiltinsPPC.def
@@ -467,6 +467,8 @@ BUILTIN(__builtin_vsx_xxsldwi, "v.", "t")
 
 BUILTIN(__builtin_vsx_xxeval, "V2ULLiV2ULLiV2ULLiV2ULLiIi", "")
 
+BUILTIN(__builtin_vsx_xvtlsbb, "iV16Ucb", "")
+
 // P10 Vector Permute Extended built-in.
 BUILTIN(__builtin_vsx_xxpermx, "V16UcV16UcV16UcV16UcIi", "")
 

diff  --git a/clang/lib/Headers/altivec.h b/clang/lib/Headers/altivec.h
index 9a4009216930..ac5f43836316 100644
--- a/clang/lib/Headers/altivec.h
+++ b/clang/lib/Headers/altivec.h
@@ -17146,6 +17146,20 @@ vec_splati_ins(vector float __a, const unsigned int 
__b, const float __c) {
 #endif
   return __a;
 }
+
+/* vec_test_lsbb_all_ones */
+
+static __inline__ int __ATTRS_o_ai
+vec_test_lsbb_all_ones(vector unsigned char __a) {
+  return __builtin_vsx_xvtlsbb(__a, 1);
+}
+
+/* vec_test_lsbb_all_zeros */
+
+static __inline__ int __ATTRS_o_ai
+vec_test_lsbb_all_zeros(vector unsigned char __a) {
+  return __builtin_vsx_xvtlsbb(__a, 0);
+}
 #endif /* __VSX__ */
 #endif /* __POWER10_VECTOR__ */
 

diff  --git a/clang/test/CodeGen/builtins-ppc-p10vector.c 
b/clang/test/CodeGen/builtins-ppc-p10vector.c
index 22b4e7a6f3ec..c51c24f25986 100644
--- a/clang/test/CodeGen/builtins-ppc-p10vector.c
+++ b/clang/test/CodeGen/builtins-ppc-p10vector.c
@@ -581,3 +581,15 @@ vector float test_vec_vec_splati_ins_f(void) {
   // CHECK: ret <4 x float>
   return vec_splati_ins(vfa, 0, 1.0f);
 }
+
+int test_vec_test_lsbb_all_ones(void) {
+  // CHECK: @llvm.ppc.vsx.xvtlsbb(<16 x i8> %{{.+}}, i1 true
+  // CHECK-NEXT: ret i32
+  return vec_test_lsbb_all_ones(vuca);
+}
+
+int test_vec_test_lsbb_all_zeros(void) {
+  // CHECK: @llvm.ppc.vsx.xvtlsbb(<16 x i8> %{{.+}}, i1 false
+  // CHECK-NEXT: ret i32
+  return vec_test_lsbb_all_zeros(vuca);
+}

diff  --git a/llvm/include/llvm/IR/IntrinsicsPowerPC.td 
b/llvm/include/llvm/IR/IntrinsicsPowerPC.td
index 12f4a3ce8e28..614a29049686 100644
--- a/llvm/include/llvm/IR/IntrinsicsPowerPC.td
+++ b/llvm/include/llvm/IR/IntrinsicsPowerPC.td
@@ -1067,6 +1067,9 @@ def int_ppc_vsx_xxinsertw :
   PowerPC_VSX_Intrinsic<"xxinsertw",[llvm_v4i32_ty],
 [llvm_v4i32_ty,llvm_v2i64_ty,llvm_i32_ty],
 [IntrNoMem]>;
+def int_ppc_vsx_xvtlsbb :
+  PowerPC_VSX_Intrinsic<"xvtlsbb", [llvm_i32_ty],
+[llvm_v16i8_ty, llvm_i1_ty], [IntrNoMem]>;
 def int_ppc_vsx_xxeval :
   PowerPC_VSX_Intrinsic<"xxeval", [llvm_v2i64_ty],
[llvm_v2i64_ty, llvm_v2i64_ty,

diff  --git a/llvm/lib/Target/PowerPC/PPCInstrPrefix.td 
b/llvm/lib/Target/PowerPC/PPCInstrPrefix.td
index 2d12a72e29ae..2bab73418e10 100644
--- a/llvm/lib/Target/PowerPC/PPCInstrPrefix.td
+++ b/llvm/lib/Target/PowerPC/PPCInstrPrefix.td
@@ -396,6 +396,25 @@ class 8RR_XX4Form_IMM3_XTABC6 opcode, bits<2> xo, 
dag OOL, dag IOL,
   let Inst{63} = XT{5};
 }
 
+// [PO BF / XO2 B XO BX /]
+class XX2_BF3_XO5_XB6_XO9 opcode, bits<5> xo2, bits<9> xo, dag OOL,
+  dag IOL, string asmstr, InstrItinClass itin,
+  list pattern>
+  : I {
+  bits<3> BF;
+  bits<6> XB;
+
+  let Pattern = pattern;
+
+  let Inst{6-8}   = BF;
+  let Inst{9-10}  = 0;
+  let Inst{11-15} = xo2;
+  let Inst{16-20} = XB{4-0};
+  let Inst{21-29} = xo;
+  let Inst{30}= XB{5};
+  let Inst{31}= 0;
+}
+
 multiclass MLS_DForm_R_SI34_RTA5_MEM_p opcode, dag OOL, dag IOL,
dag PCRel_IOL, string asmstr,
InstrItinClass itin> {
@@ -943,6 +962,9 @@ let Predicates = [IsISA3_1] in {
  [(set v16i8:$vD,
(int_ppc_altivec_vclrrb v16i8:$vA, i32:$rB))]>;
 
+  def XVTLSBB : XX2_BF3_XO5_XB6_XO9<60, 2, 475, (outs crrc:$BF), (ins 
vsrc:$XB),
+"xvtlsbb $BF, $XB", IIC_VecGeneral, []>;
+
   // The 

[PATCH] D82822: [OpenMP][FIX] Consistently use OpenMPIRBuilder if requested

2020-07-13 Thread Johannes Doerfert via Phabricator via cfe-commits
jdoerfert updated this revision to Diff 277635.
jdoerfert added a comment.

Rebase


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D82822

Files:
  clang/lib/CodeGen/CGOpenMPRuntime.cpp
  clang/test/OpenMP/cancel_codegen.cpp
  clang/test/OpenMP/irbuilder_nested_parallel_for.c
  clang/test/OpenMP/task_codegen.cpp

Index: clang/test/OpenMP/task_codegen.cpp
===
--- clang/test/OpenMP/task_codegen.cpp
+++ clang/test/OpenMP/task_codegen.cpp
@@ -33,12 +33,11 @@
   char b;
   S s[2];
   int arr[10][a];
-// CHECK: [[GTID:%.+]] = call i32 @__kmpc_global_thread_num([[IDENT_T]]* @{{.+}})
 // CHECK: [[B_REF:%.+]] = getelementptr inbounds [[STRUCT_SHAREDS]], [[STRUCT_SHAREDS]]* [[CAPTURES:%.+]], i32 0, i32 0
 // CHECK: store i8* [[B]], i8** [[B_REF]]
 // CHECK: [[S_REF:%.+]] = getelementptr inbounds [[STRUCT_SHAREDS]], [[STRUCT_SHAREDS]]* [[CAPTURES]], i32 0, i32 1
 // CHECK: store [2 x [[STRUCT_S]]]* [[S]], [2 x [[STRUCT_S]]]** [[S_REF]]
-// CHECK: [[ORIG_TASK_PTR:%.+]] = call i8* @__kmpc_omp_task_alloc([[IDENT_T]]* @{{.+}}, i32 [[GTID]], i32 33, i64 40, i64 16, i32 (i32, i8*)* bitcast (i32 (i32, [[KMP_TASK_T]]{{.*}}*)* [[TASK_ENTRY1:@.+]] to i32 (i32, i8*)*))
+// CHECK: [[ORIG_TASK_PTR:%.+]] = call i8* @__kmpc_omp_task_alloc([[IDENT_T]]* @{{.+}}, i32 {{%.*}}, i32 33, i64 40, i64 16, i32 (i32, i8*)* bitcast (i32 (i32, [[KMP_TASK_T]]{{.*}}*)* [[TASK_ENTRY1:@.+]] to i32 (i32, i8*)*))
 // CHECK: [[SHAREDS_REF_PTR:%.+]] = getelementptr inbounds [[KMP_TASK_T]], [[KMP_TASK_T]]* [[TASK_PTR:%.+]], i32 0, i32 0
 // CHECK: [[SHAREDS_REF:%.+]] = load i8*, i8** [[SHAREDS_REF_PTR]]
 // CHECK: [[BITCAST:%.+]] = bitcast [[STRUCT_SHAREDS]]* [[CAPTURES]] to i8*
@@ -46,7 +45,7 @@
 // CHECK: [[PRIORITY_REF_PTR:%.+]] = getelementptr inbounds [[KMP_TASK_T]], [[KMP_TASK_T]]* [[TASK_PTR]], i32 0, i32 4
 // CHECK: [[PRIORITY:%.+]] = bitcast %union{{.+}}* [[PRIORITY_REF_PTR]] to i32*
 // CHECK: store i32 {{.+}}, i32* [[PRIORITY]]
-// CHECK: call i32 @__kmpc_omp_task([[IDENT_T]]* @{{.+}}, i32 [[GTID]], i8* [[ORIG_TASK_PTR]])
+// CHECK: call i32 @__kmpc_omp_task([[IDENT_T]]* @{{.+}}, i32 {{%.*}}, i8* [[ORIG_TASK_PTR]])
 #pragma omp task shared(a, b, s) priority(b)
   {
 a = 15;
@@ -55,7 +54,7 @@
   }
 // CHECK: [[S_REF:%.+]] = getelementptr inbounds [[STRUCT_SHAREDS1]], [[STRUCT_SHAREDS1]]* [[CAPTURES:%.+]], i32 0, i32 0
 // CHECK: store [2 x [[STRUCT_S]]]* [[S]], [2 x [[STRUCT_S]]]** [[S_REF]]
-// CHECK: [[ORIG_TASK_PTR:%.+]] = call i8* @__kmpc_omp_task_alloc([[IDENT_T]]* @{{[^,]+}}, i32 [[GTID]], i32 1, i64 40, i64 8,
+// CHECK: [[ORIG_TASK_PTR:%.+]] = call i8* @__kmpc_omp_task_alloc([[IDENT_T]]* @{{[^,]+}}, i32 {{%.*}}, i32 1, i64 40, i64 8,
 // CHECK: [[SHAREDS_REF_PTR:%.+]] = getelementptr inbounds [[KMP_TASK_T]], [[KMP_TASK_T]]* [[TASK_PTR:%.+]], i32 0, i32 0
 // CHECK: [[SHAREDS_REF:%.+]] = load i8*, i8** [[SHAREDS_REF_PTR]]
 // CHECK: [[BITCAST:%.+]] = bitcast [[STRUCT_SHAREDS1]]* [[CAPTURES]] to i8*
@@ -101,20 +100,20 @@
 // CHECK: [[T0:%.*]] = getelementptr inbounds [[KMP_DEPEND_INFO]], [[KMP_DEPEND_INFO]]* %{{[^,]+}}, i32 0, i32 2
 // CHECK: store i8 1, i8* [[T0]]
 // CHECK: bitcast [[KMP_DEPEND_INFO]]* [[DEP_BASE]] to i8*
-// CHECK: call i32 @__kmpc_omp_task_with_deps([[IDENT_T]]* @{{.+}}, i32 [[GTID]], i8* [[ORIG_TASK_PTR]], i32 4, i8* %{{[^,]+}}, i32 0, i8* null)
+// CHECK: call i32 @__kmpc_omp_task_with_deps([[IDENT_T]]* @{{.+}}, i32 {{%.*}}, i8* [[ORIG_TASK_PTR]], i32 4, i8* %{{[^,]+}}, i32 0, i8* null)
 #pragma omp task shared(a, s) depend(in : a, b, s, arr[:])
   {
 a = 15;
 s[1].a = 10;
   }
-// CHECK: [[ORIG_TASK_PTR:%.+]] = call i8* @__kmpc_omp_task_alloc([[IDENT_T]]* @{{.+}}, i32 [[GTID]], i32 0, i64 40, i64 1, i32 (i32, i8*)* bitcast (i32 (i32, [[KMP_TASK_T]]{{.*}}*)* [[TASK_ENTRY2:@.+]] to i32 (i32, i8*)*))
-// CHECK: call i32 @__kmpc_omp_task([[IDENT_T]]* @{{.+}}, i32 [[GTID]], i8* [[ORIG_TASK_PTR]])
+// CHECK: [[ORIG_TASK_PTR:%.+]] = call i8* @__kmpc_omp_task_alloc([[IDENT_T]]* @{{.+}}, i32 {{%.*}}, i32 0, i64 40, i64 1, i32 (i32, i8*)* bitcast (i32 (i32, [[KMP_TASK_T]]{{.*}}*)* [[TASK_ENTRY2:@.+]] to i32 (i32, i8*)*))
+// CHECK: call i32 @__kmpc_omp_task([[IDENT_T]]* @{{.+}}, i32 {{%.*}}, i8* [[ORIG_TASK_PTR]])
 #pragma omp task untied
   {
 #pragma omp critical
 a = 1;
   }
-// CHECK: [[ORIG_TASK_PTR:%.+]] = call i8* @__kmpc_omp_task_alloc([[IDENT_T]]* @{{.+}}, i32 [[GTID]], i32 0, i64 40, i64 1,
+// CHECK: [[ORIG_TASK_PTR:%.+]] = call i8* @__kmpc_omp_task_alloc([[IDENT_T]]* @{{.+}}, i32 {{%.*}}, i32 0, i64 40, i64 1,
 // CHECK: getelementptr inbounds [2 x [[STRUCT_S]]], [2 x [[STRUCT_S]]]* [[S]], i64 0, i64 0
 // CHECK: getelementptr inbounds [[KMP_DEPEND_INFO]], [[KMP_DEPEND_INFO]]* %{{[^,]+}}, i32 0, i32 0
 // CHECK: ptrtoint [[STRUCT_S]]* %{{.+}} to i64
@@ -146,12 +145,12 @@
 // CHECK: getelementptr inbounds [[KMP_DEPEND_INFO]], [[KMP_DEPEND_INFO]]* 

[PATCH] D82470: [OpenMP][IRBuilder] Support allocas in nested parallel regions

2020-07-13 Thread Johannes Doerfert via Phabricator via cfe-commits
jdoerfert added a comment.

Used an extra argument now. Please let me know if this is OK.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D82470



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


[PATCH] D82470: [OpenMP][IRBuilder] Support allocas in nested parallel regions

2020-07-13 Thread Johannes Doerfert via Phabricator via cfe-commits
jdoerfert updated this revision to Diff 277634.
jdoerfert added a comment.

Rebase


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D82470

Files:
  clang/lib/CodeGen/CGStmtOpenMP.cpp
  llvm/include/llvm/Frontend/OpenMP/OMPIRBuilder.h
  llvm/lib/Frontend/OpenMP/OMPIRBuilder.cpp
  llvm/unittests/Frontend/OpenMPIRBuilderTest.cpp

Index: llvm/unittests/Frontend/OpenMPIRBuilderTest.cpp
===
--- llvm/unittests/Frontend/OpenMPIRBuilderTest.cpp
+++ llvm/unittests/Frontend/OpenMPIRBuilderTest.cpp
@@ -6,13 +6,14 @@
 //
 //===--===//
 
+#include "llvm/Frontend/OpenMP/OMPConstants.h"
 #include "llvm/Frontend/OpenMP/OMPIRBuilder.h"
 #include "llvm/IR/BasicBlock.h"
 #include "llvm/IR/DIBuilder.h"
 #include "llvm/IR/Function.h"
+#include "llvm/IR/InstIterator.h"
 #include "llvm/IR/LLVMContext.h"
 #include "llvm/IR/Module.h"
-#include "llvm/Frontend/OpenMP/OMPConstants.h"
 #include "llvm/IR/Verifier.h"
 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
 #include "gtest/gtest.h"
@@ -360,9 +361,11 @@
 
   auto FiniCB = [&](InsertPointTy CodeGenIP) { ++NumFinalizationPoints; };
 
+  IRBuilder<>::InsertPoint AllocaIP(>getEntryBlock(),
+F->getEntryBlock().getFirstInsertionPt());
   IRBuilder<>::InsertPoint AfterIP =
-  OMPBuilder.CreateParallel(Loc, BodyGenCB, PrivCB, FiniCB, nullptr,
-nullptr, OMP_PROC_BIND_default, false);
+  OMPBuilder.CreateParallel(Loc, AllocaIP, BodyGenCB, PrivCB, FiniCB,
+nullptr, nullptr, OMP_PROC_BIND_default, false);
   EXPECT_EQ(NumBodiesGenerated, 1U);
   EXPECT_EQ(NumPrivatizedVars, 1U);
   EXPECT_EQ(NumFinalizationPoints, 1U);
@@ -400,6 +403,205 @@
   EXPECT_EQ(ForkCI->getArgOperand(3), F->arg_begin());
 }
 
+TEST_F(OpenMPIRBuilderTest, ParallelNested) {
+  using InsertPointTy = OpenMPIRBuilder::InsertPointTy;
+  OpenMPIRBuilder OMPBuilder(*M);
+  OMPBuilder.initialize();
+  F->setName("func");
+  IRBuilder<> Builder(BB);
+
+  OpenMPIRBuilder::LocationDescription Loc({Builder.saveIP(), DL});
+
+  unsigned NumInnerBodiesGenerated = 0;
+  unsigned NumOuterBodiesGenerated = 0;
+  unsigned NumFinalizationPoints = 0;
+
+  auto InnerBodyGenCB = [&](InsertPointTy AllocaIP, InsertPointTy CodeGenIP,
+BasicBlock ) {
+++NumInnerBodiesGenerated;
+  };
+
+  auto PrivCB = [&](InsertPointTy AllocaIP, InsertPointTy CodeGenIP,
+Value , Value *) -> InsertPointTy {
+// Trivial copy (=firstprivate).
+Builder.restoreIP(AllocaIP);
+Type *VTy = VPtr.getType()->getPointerElementType();
+Value *V = Builder.CreateLoad(VTy, , VPtr.getName() + ".reload");
+ReplacementValue = Builder.CreateAlloca(VTy, 0, VPtr.getName() + ".copy");
+Builder.restoreIP(CodeGenIP);
+Builder.CreateStore(V, ReplacementValue);
+return CodeGenIP;
+  };
+
+  auto FiniCB = [&](InsertPointTy CodeGenIP) { ++NumFinalizationPoints; };
+
+  auto OuterBodyGenCB = [&](InsertPointTy AllocaIP, InsertPointTy CodeGenIP,
+BasicBlock ) {
+++NumOuterBodiesGenerated;
+Builder.restoreIP(CodeGenIP);
+BasicBlock *CGBB = CodeGenIP.getBlock();
+BasicBlock *NewBB = SplitBlock(CGBB, &*CodeGenIP.getPoint());
+CGBB->getTerminator()->eraseFromParent();
+;
+
+IRBuilder<>::InsertPoint AfterIP = OMPBuilder.CreateParallel(
+InsertPointTy(CGBB, CGBB->end()), AllocaIP, InnerBodyGenCB, PrivCB,
+FiniCB, nullptr, nullptr, OMP_PROC_BIND_default, false);
+
+Builder.restoreIP(AfterIP);
+Builder.CreateBr(NewBB);
+  };
+
+  IRBuilder<>::InsertPoint AllocaIP(>getEntryBlock(),
+F->getEntryBlock().getFirstInsertionPt());
+  IRBuilder<>::InsertPoint AfterIP =
+  OMPBuilder.CreateParallel(Loc, AllocaIP, OuterBodyGenCB, PrivCB, FiniCB,
+nullptr, nullptr, OMP_PROC_BIND_default, false);
+
+  EXPECT_EQ(NumInnerBodiesGenerated, 1U);
+  EXPECT_EQ(NumOuterBodiesGenerated, 1U);
+  EXPECT_EQ(NumFinalizationPoints, 2U);
+
+  Builder.restoreIP(AfterIP);
+  Builder.CreateRetVoid();
+
+  OMPBuilder.finalize();
+
+  EXPECT_EQ(M->size(), 5U);
+  for (Function  : *M) {
+if (F ==  || OutlinedFn.isDeclaration())
+  continue;
+EXPECT_FALSE(verifyModule(*M, ()));
+EXPECT_TRUE(OutlinedFn.hasFnAttribute(Attribute::NoUnwind));
+EXPECT_TRUE(OutlinedFn.hasFnAttribute(Attribute::NoRecurse));
+EXPECT_TRUE(OutlinedFn.hasParamAttribute(0, Attribute::NoAlias));
+EXPECT_TRUE(OutlinedFn.hasParamAttribute(1, Attribute::NoAlias));
+
+EXPECT_TRUE(OutlinedFn.hasInternalLinkage());
+EXPECT_EQ(OutlinedFn.arg_size(), 2U);
+
+EXPECT_EQ(OutlinedFn.getNumUses(), 1U);
+User *Usr = OutlinedFn.user_back();
+ASSERT_TRUE(isa(Usr));
+

[PATCH] D83713: [WebAssembly] Triple::wasm64 related cleanup

2020-07-13 Thread Wouter van Oortmerssen via Phabricator via cfe-commits
aardappel updated this revision to Diff 277627.
aardappel added a comment.

Made LLD `is64` optional, so we can know if is set consistently.


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

https://reviews.llvm.org/D83713

Files:
  clang/lib/Driver/ToolChain.cpp
  lld/wasm/Config.h
  lld/wasm/Driver.cpp
  lld/wasm/InputChunks.cpp
  lld/wasm/InputFiles.cpp
  lld/wasm/SyntheticSections.cpp
  lld/wasm/Writer.cpp
  llvm/include/llvm/Object/Wasm.h
  llvm/lib/Object/WasmObjectFile.cpp

Index: llvm/lib/Object/WasmObjectFile.cpp
===
--- llvm/lib/Object/WasmObjectFile.cpp
+++ llvm/lib/Object/WasmObjectFile.cpp
@@ -957,6 +957,8 @@
   break;
 case wasm::WASM_EXTERNAL_MEMORY:
   Im.Memory = readLimits(Ctx);
+  if (Im.Memory.Flags & wasm::WASM_LIMITS_FLAG_IS_64)
+HasMemory64 = true;
   break;
 case wasm::WASM_EXTERNAL_TABLE:
   Im.Table = readTable(Ctx);
@@ -1019,7 +1021,10 @@
   uint32_t Count = readVaruint32(Ctx);
   Memories.reserve(Count);
   while (Count--) {
-Memories.push_back(readLimits(Ctx));
+auto Limits = readLimits(Ctx);
+if (Limits.Flags & wasm::WASM_LIMITS_FLAG_IS_64)
+  HasMemory64 = true;
+Memories.push_back(Limits);
   }
   if (Ctx.Ptr != Ctx.End)
 return make_error("Memory section ended prematurely",
@@ -1576,11 +1581,15 @@
   return section_iterator(SectionRef(Ref, this));
 }
 
-uint8_t WasmObjectFile::getBytesInAddress() const { return 4; }
+uint8_t WasmObjectFile::getBytesInAddress() const {
+  return HasMemory64 ? 8 : 4;
+}
 
 StringRef WasmObjectFile::getFileFormatName() const { return "WASM"; }
 
-Triple::ArchType WasmObjectFile::getArch() const { return Triple::wasm32; }
+Triple::ArchType WasmObjectFile::getArch() const {
+  return HasMemory64 ? Triple::wasm64 : Triple::wasm32;
+}
 
 SubtargetFeatures WasmObjectFile::getFeatures() const {
   return SubtargetFeatures();
Index: llvm/include/llvm/Object/Wasm.h
===
--- llvm/include/llvm/Object/Wasm.h
+++ llvm/include/llvm/Object/Wasm.h
@@ -282,6 +282,7 @@
   bool HasLinkingSection = false;
   bool HasDylinkSection = false;
   bool SeenCodeSection = false;
+  bool HasMemory64 = false;
   wasm::WasmLinkingData LinkingData;
   uint32_t NumImportedGlobals = 0;
   uint32_t NumImportedFunctions = 0;
Index: lld/wasm/Writer.cpp
===
--- lld/wasm/Writer.cpp
+++ lld/wasm/Writer.cpp
@@ -304,7 +304,8 @@
   if (WasmSym::heapBase)
 WasmSym::heapBase->setVirtualAddress(memoryPtr);
 
-  uint64_t maxMemorySetting = 1ULL << (config->is64 ? 48 : 32);
+  uint64_t maxMemorySetting = 1ULL
+  << (config->is64.getValueOr(false) ? 48 : 32);
 
   if (config->initialMemory != 0) {
 if (config->initialMemory != alignTo(config->initialMemory, WasmPageSize))
Index: lld/wasm/SyntheticSections.cpp
===
--- lld/wasm/SyntheticSections.cpp
+++ lld/wasm/SyntheticSections.cpp
@@ -139,7 +139,7 @@
 }
 if (config->sharedMemory)
   import.Memory.Flags |= WASM_LIMITS_FLAG_IS_SHARED;
-if (config->is64)
+if (config->is64.getValueOr(false))
   import.Memory.Flags |= WASM_LIMITS_FLAG_IS_64;
 writeImport(os, import);
   }
@@ -236,7 +236,7 @@
 flags |= WASM_LIMITS_FLAG_HAS_MAX;
   if (config->sharedMemory)
 flags |= WASM_LIMITS_FLAG_IS_SHARED;
-  if (config->is64)
+  if (config->is64.getValueOr(false))
 flags |= WASM_LIMITS_FLAG_IS_64;
   writeUleb128(os, flags, "memory limits flags");
   writeUleb128(os, numMemoryPages, "initial pages");
Index: lld/wasm/InputFiles.cpp
===
--- lld/wasm/InputFiles.cpp
+++ lld/wasm/InputFiles.cpp
@@ -576,10 +576,16 @@
   obj = check(lto::InputFile::create(MemoryBufferRef(
   mb.getBuffer(), saver.save(archiveName + mb.getBufferIdentifier();
   Triple t(obj->getTargetTriple());
-  if (t.getArch() != Triple::wasm32) {
-error(toString(this) + ": machine type must be wasm32");
+  if (!t.isWasm()) {
+error(toString(this) + ": machine type must be wasm32 or wasm64");
 return;
   }
+  bool is64 = t.getArch() == Triple::wasm64;
+  if (config->is64.hasValue() && *config->is64 != is64) {
+error(toString(this) + ": machine type for all bitcode files must match");
+return;
+  }
+  config->is64 = is64;
   std::vector keptComdats;
   for (StringRef s : obj->getComdatTable())
 keptComdats.push_back(symtab->addComdat(s));
Index: lld/wasm/InputChunks.cpp
===
--- lld/wasm/InputChunks.cpp
+++ lld/wasm/InputChunks.cpp
@@ -335,10 +335,12 @@
   LLVM_DEBUG(dbgs() << "generating runtime relocations: " << getName()
 << " count=" << relocations.size() << "\n");
 
-  unsigned opcode_ptr_const =
-  

[PATCH] D83494: [libFuzzer] Link libFuzzer's own interceptors when other compiler runtimes are not linked.

2020-07-13 Thread Dokyung Song via Phabricator via cfe-commits
dokyungs updated this revision to Diff 277625.
dokyungs added a comment.

Use unique output file name for each subtest, and add no-asan subtest in 
memcmp64.test


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D83494

Files:
  clang/include/clang/Driver/SanitizerArgs.h
  clang/lib/Driver/SanitizerArgs.cpp
  clang/lib/Driver/ToolChains/CommonArgs.cpp
  compiler-rt/lib/fuzzer/CMakeLists.txt
  compiler-rt/lib/fuzzer/FuzzerDefs.h
  compiler-rt/lib/fuzzer/FuzzerInterceptors.cpp
  compiler-rt/lib/fuzzer/FuzzerPlatform.h
  compiler-rt/test/fuzzer/memcmp.test
  compiler-rt/test/fuzzer/memcmp64.test
  compiler-rt/test/fuzzer/strcmp.test
  compiler-rt/test/fuzzer/strncmp.test
  compiler-rt/test/fuzzer/strstr.test

Index: compiler-rt/test/fuzzer/strstr.test
===
--- compiler-rt/test/fuzzer/strstr.test
+++ compiler-rt/test/fuzzer/strstr.test
@@ -1,5 +1,9 @@
 UNSUPPORTED: freebsd
 RUN: %cpp_compiler %S/StrstrTest.cpp -o %t-StrstrTest
-RUN: not %run %t-StrstrTest   -seed=1 -runs=200   2>&1 | FileCheck %s
-CHECK: BINGO
+RUN: not %run %t-StrstrTest   -seed=1 -runs=200   2>&1 | FileCheck %s --check-prefix=CHECK1
+CHECK1: BINGO
+
+RUN: %cpp_compiler -fno-sanitize=address -fno-builtin-strstr %S/StrstrTest.cpp -o %t-NoAsanStrstrTest
+RUN: not %run %t-StrstrTest   -seed=1 -runs=200   2>&1 | FileCheck %s --check-prefix=CHECK2
+CHECK2: BINGO
 
Index: compiler-rt/test/fuzzer/strncmp.test
===
--- compiler-rt/test/fuzzer/strncmp.test
+++ compiler-rt/test/fuzzer/strncmp.test
@@ -1,5 +1,9 @@
 UNSUPPORTED: freebsd
 RUN: %cpp_compiler %S/StrncmpTest.cpp -o %t-StrncmpTest
-RUN: not %run %t-StrncmpTest  -seed=2 -runs=1000   2>&1 | FileCheck %s
-CHECK: BINGO
+RUN: not %run %t-StrncmpTest  -seed=2 -runs=1000   2>&1 | FileCheck %s --check-prefix=CHECK1
+CHECK1: BINGO
+
+RUN: %cpp_compiler -fno-sanitize=address -fno-builtin-strncmp %S/StrncmpTest.cpp -o %t-NoAsanStrncmpTest
+RUN: not %run %t-StrncmpTest  -seed=2 -runs=1000   2>&1 | FileCheck %s --check-prefix=CHECK2
+CHECK2: BINGO
 
Index: compiler-rt/test/fuzzer/strcmp.test
===
--- compiler-rt/test/fuzzer/strcmp.test
+++ compiler-rt/test/fuzzer/strcmp.test
@@ -1,5 +1,8 @@
 UNSUPPORTED: freebsd
 RUN: %cpp_compiler %S/StrcmpTest.cpp -o %t-StrcmpTest
-RUN: not %run %t-StrcmpTest   -seed=1 -runs=200   2>&1 | FileCheck %s
-CHECK: BINGO
+RUN: not %run %t-StrcmpTest   -seed=1 -runs=200   2>&1 | FileCheck %s --check-prefix=CHECK1
+CHECK1: BINGO
 
+RUN: %cpp_compiler -fno-sanitize=address -fno-builtin-strcmp %S/StrcmpTest.cpp -o %t-NoAsanStrcmpTest
+RUN: not %run %t-StrcmpTest   -seed=1 -runs=200   2>&1 | FileCheck %s --check-prefix=CHECK2
+CHECK2: BINGO
Index: compiler-rt/test/fuzzer/memcmp64.test
===
--- compiler-rt/test/fuzzer/memcmp64.test
+++ compiler-rt/test/fuzzer/memcmp64.test
@@ -1,4 +1,8 @@
 UNSUPPORTED: freebsd
 RUN: %cpp_compiler %S/Memcmp64BytesTest.cpp -o %t-Memcmp64BytesTest
-RUN: not %run %t-Memcmp64BytesTest-seed=1 -runs=100   2>&1 | FileCheck %s
-CHECK: BINGO
+RUN: not %run %t-Memcmp64BytesTest-seed=1 -runs=100   2>&1 | FileCheck %s --check-prefix=CHECK1
+CHECK1: BINGO
+
+RUN: %cpp_compiler -fno-sanitize=address -fno-builtin-memcmp %S/Memcmp64BytesTest.cpp -o %t-NoAsanMemcmp64BytesTest
+RUN: not %run %t-Memcmp64BytesTest-seed=1 -runs=100   2>&1 | FileCheck %s --check-prefix=CHECK2
+CHECK2: BINGO
Index: compiler-rt/test/fuzzer/memcmp.test
===
--- compiler-rt/test/fuzzer/memcmp.test
+++ compiler-rt/test/fuzzer/memcmp.test
@@ -1,4 +1,8 @@
 UNSUPPORTED: freebsd
 RUN: %cpp_compiler %S/MemcmpTest.cpp -o %t-MemcmpTest
-RUN: not %run %t-MemcmpTest   -seed=1 -runs=1000   2>&1 | FileCheck %s
-CHECK: BINGO
+RUN: not %run %t-MemcmpTest   -seed=1 -runs=1000   2>&1 | FileCheck %s --check-prefix=CHECK1
+CHECK1: BINGO
+
+RUN: %cpp_compiler -fno-sanitize=address -fno-builtin-memcmp %S/MemcmpTest.cpp -o %t-NoAsanMemcmpTest
+RUN: not %run %t-MemcmpTest   -seed=1 -runs=1000   2>&1 | FileCheck %s --check-prefix=CHECK2
+CHECK2: BINGO
Index: compiler-rt/lib/fuzzer/FuzzerPlatform.h
===
--- compiler-rt/lib/fuzzer/FuzzerPlatform.h
+++ compiler-rt/lib/fuzzer/FuzzerPlatform.h
@@ -1,25 +1,16 @@
-//===- FuzzerDefs.h - Internal header for the Fuzzer *- C++ -* ===//
+//===-- FuzzerInterceptors.cpp ===//
 //
 // Part of the LLVM Project, under the Apache License v2.0 with LLVM 

[PATCH] D83494: [libFuzzer] Link libFuzzer's own interceptors when other compiler runtimes are not linked.

2020-07-13 Thread Dokyung Song via Phabricator via cfe-commits
dokyungs updated this revision to Diff 277624.
dokyungs added a comment.

strncmp test should include -fno-builtin-strncmp, not -fno-builtin-strcmp


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D83494

Files:
  clang/include/clang/Driver/SanitizerArgs.h
  clang/lib/Driver/SanitizerArgs.cpp
  clang/lib/Driver/ToolChains/CommonArgs.cpp
  compiler-rt/lib/fuzzer/CMakeLists.txt
  compiler-rt/lib/fuzzer/FuzzerDefs.h
  compiler-rt/lib/fuzzer/FuzzerInterceptors.cpp
  compiler-rt/lib/fuzzer/FuzzerPlatform.h
  compiler-rt/test/fuzzer/memcmp.test
  compiler-rt/test/fuzzer/strcmp.test
  compiler-rt/test/fuzzer/strncmp.test
  compiler-rt/test/fuzzer/strstr.test

Index: compiler-rt/test/fuzzer/strstr.test
===
--- compiler-rt/test/fuzzer/strstr.test
+++ compiler-rt/test/fuzzer/strstr.test
@@ -1,5 +1,9 @@
 UNSUPPORTED: freebsd
 RUN: %cpp_compiler %S/StrstrTest.cpp -o %t-StrstrTest
-RUN: not %run %t-StrstrTest   -seed=1 -runs=200   2>&1 | FileCheck %s
-CHECK: BINGO
+RUN: not %run %t-StrstrTest   -seed=1 -runs=200   2>&1 | FileCheck %s --check-prefix=CHECK1
+CHECK1: BINGO
+
+RUN: %cpp_compiler -fno-sanitize=address -fno-builtin-strstr %S/StrstrTest.cpp -o %t-NoAsanStrstrTest
+RUN: not %run %t-StrstrTest   -seed=1 -runs=200   2>&1 | FileCheck %s --check-prefix=CHECK2
+CHECK2: BINGO
 
Index: compiler-rt/test/fuzzer/strncmp.test
===
--- compiler-rt/test/fuzzer/strncmp.test
+++ compiler-rt/test/fuzzer/strncmp.test
@@ -1,5 +1,9 @@
 UNSUPPORTED: freebsd
 RUN: %cpp_compiler %S/StrncmpTest.cpp -o %t-StrncmpTest
-RUN: not %run %t-StrncmpTest  -seed=2 -runs=1000   2>&1 | FileCheck %s
-CHECK: BINGO
+RUN: not %run %t-StrncmpTest  -seed=2 -runs=1000   2>&1 | FileCheck %s --check-prefix=CHECK1
+CHECK1: BINGO
+
+RUN: %cpp_compiler -fno-sanitize=address -fno-builtin-strncmp %S/StrncmpTest.cpp -o %t-NoAsanStrncmpTest
+RUN: not %run %t-StrncmpTest  -seed=2 -runs=1000   2>&1 | FileCheck %s --check-prefix=CHECK2
+CHECK2: BINGO
 
Index: compiler-rt/test/fuzzer/strcmp.test
===
--- compiler-rt/test/fuzzer/strcmp.test
+++ compiler-rt/test/fuzzer/strcmp.test
@@ -1,5 +1,8 @@
 UNSUPPORTED: freebsd
 RUN: %cpp_compiler %S/StrcmpTest.cpp -o %t-StrcmpTest
-RUN: not %run %t-StrcmpTest   -seed=1 -runs=200   2>&1 | FileCheck %s
-CHECK: BINGO
+RUN: not %run %t-StrcmpTest   -seed=1 -runs=200   2>&1 | FileCheck %s --check-prefix=CHECK1
+CHECK1: BINGO
 
+RUN: %cpp_compiler -fno-sanitize=address -fno-builtin-strcmp %S/StrcmpTest.cpp -o %t-StrcmpTest
+RUN: not %run %t-StrcmpTest   -seed=1 -runs=200   2>&1 | FileCheck %s --check-prefix=CHECK2
+CHECK2: BINGO
Index: compiler-rt/test/fuzzer/memcmp.test
===
--- compiler-rt/test/fuzzer/memcmp.test
+++ compiler-rt/test/fuzzer/memcmp.test
@@ -1,4 +1,8 @@
 UNSUPPORTED: freebsd
 RUN: %cpp_compiler %S/MemcmpTest.cpp -o %t-MemcmpTest
-RUN: not %run %t-MemcmpTest   -seed=1 -runs=1000   2>&1 | FileCheck %s
-CHECK: BINGO
+RUN: not %run %t-MemcmpTest   -seed=1 -runs=1000   2>&1 | FileCheck %s --check-prefix=CHECK1
+CHECK1: BINGO
+
+RUN: %cpp_compiler -fno-sanitize=address -fno-builtin-memcmp %S/MemcmpTest.cpp -o %t-MemcmpTest
+RUN: not %run %t-MemcmpTest   -seed=1 -runs=1000   2>&1 | FileCheck %s --check-prefix=CHECK2
+CHECK2: BINGO
Index: compiler-rt/lib/fuzzer/FuzzerPlatform.h
===
--- compiler-rt/lib/fuzzer/FuzzerPlatform.h
+++ compiler-rt/lib/fuzzer/FuzzerPlatform.h
@@ -1,25 +1,16 @@
-//===- FuzzerDefs.h - Internal header for the Fuzzer *- C++ -* ===//
+//===-- FuzzerInterceptors.cpp ===//
 //
 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
 // See https://llvm.org/LICENSE.txt for license information.
 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
 //
 //===--===//
-// Basic definitions.
+//
+// Common platform macros.
 //===--===//
 
-#ifndef LLVM_FUZZER_DEFS_H
-#define LLVM_FUZZER_DEFS_H
-
-#include 
-#include 
-#include 
-#include 
-#include 
-#include 
-#include 
-#include 
-
+#ifndef LLVM_FUZZER_PLATFORM_H
+#define LLVM_FUZZER_PLATFORM_H
 
 // Platform detection.
 #ifdef __linux__
@@ -106,7 +97,7 @@
 #endif
 
 #ifndef __has_attribute
-#  define __has_attribute(x) 0
+#define __has_attribute(x) 0
 #endif
 
 #define LIBFUZZER_POSIX\
@@ -114,26 

[PATCH] D83702: [AIX]Generate debug info for static init related functions

2020-07-13 Thread David Blaikie via Phabricator via cfe-commits
dblaikie added inline comments.



Comment at: clang/lib/CodeGen/CGDeclCXX.cpp:248-250
   CGF.StartFunction(GlobalDecl(, DynamicInitKind::AtExit),
-CGM.getContext().VoidTy, fn, FI, FunctionArgList());
+CGM.getContext().VoidTy, fn, FI, FunctionArgList(),
+VD.getLocation(), VD.getInit()->getExprLoc());

hubert.reinterpretcast wrote:
> dblaikie wrote:
> > Any ideas why this is only showing up for AIX & not other targets, given 
> > this code looks to be generic, not AIX-specific?
> Yes, because the AIX implementation generates a direct call to the stub 
> function on the finalization path when it finds that a stub was still 
> registered with `atexit`.
> 
> That would explain why other platforms to not encounter this message:
> ```
> inlinable function call in a function with debug info must have a !dbg 
> location
> ```
> 
Ah, fair enough - thanks for the context!



Comment at: clang/test/CodeGenCXX/aix-static-init-debug-info.cpp:9-19
+int a = 0;
+
+class X {
+public:
+  X() {
+a = 1;
+  }

dblaikie wrote:
> This could probably be simplified to:
> ```
> struct X {
>   X();
>   ~X();
> };
> ```
> 
> This would still produce a global ctor and dtor without the superfluous 
> variable, etc.
Could you simplify the test a bit like this? If it's only about the global 
/dtor/, perhaps omit the ctor in X too.

& which exact call in the test is the important one? Perhaps just test that?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D83702



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


[PATCH] D83494: [libFuzzer] Link libFuzzer's own interceptors when other compiler runtimes are not linked.

2020-07-13 Thread Dokyung Song via Phabricator via cfe-commits
dokyungs marked 9 inline comments as done.
dokyungs added inline comments.



Comment at: compiler-rt/lib/fuzzer/FuzzerInterceptors.cpp:116
+
+extern "C++" ATTRIBUTE_INTERFACE char *strstr(char *s1, const char *s2) {
+  char *result = REAL(strstr)(s1, s2);

morehouse wrote:
> Why `extern "C++"`?  I don't think we want that here.
Removed by not including `#include `.



Comment at: compiler-rt/lib/fuzzer/FuzzerInterceptors.cpp:123
+
+extern "C++" ATTRIBUTE_INTERFACE char *strcasestr(char *s1, const char *s2) {
+  char *result = REAL(strcasestr)(s1, s2);

morehouse wrote:
> Also why `extern "C++"` here?
Removed by not including `#include `.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D83494



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


[PATCH] D83494: [libFuzzer] Link libFuzzer's own interceptors when other compiler runtimes are not linked.

2020-07-13 Thread Dokyung Song via Phabricator via cfe-commits
dokyungs updated this revision to Diff 277620.
dokyungs added a comment.
Herald added a subscriber: krytarowski.

Addressed Matt's comments.

A major change in this round that needs explanation is introduction of 
FuzzerPlatform.h. Previously I defined `strstr` and `strcasestr` with `extern 
"C++"` to workaround conflicting definition errors resulting from including 
. But since including it is not necessary when compiling this 
interceptor module, this patch now separates out platform related macros from 
FuzzerDef.h into FuzzerPlatform.h, and the module includes FuzzerPlatform.h, 
not FuzzerDef.h.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D83494

Files:
  clang/include/clang/Driver/SanitizerArgs.h
  clang/lib/Driver/SanitizerArgs.cpp
  clang/lib/Driver/ToolChains/CommonArgs.cpp
  compiler-rt/lib/fuzzer/CMakeLists.txt
  compiler-rt/lib/fuzzer/FuzzerDefs.h
  compiler-rt/lib/fuzzer/FuzzerInterceptors.cpp
  compiler-rt/lib/fuzzer/FuzzerPlatform.h
  compiler-rt/test/fuzzer/memcmp.test
  compiler-rt/test/fuzzer/strcmp.test
  compiler-rt/test/fuzzer/strncmp.test
  compiler-rt/test/fuzzer/strstr.test

Index: compiler-rt/test/fuzzer/strstr.test
===
--- compiler-rt/test/fuzzer/strstr.test
+++ compiler-rt/test/fuzzer/strstr.test
@@ -1,5 +1,9 @@
 UNSUPPORTED: freebsd
 RUN: %cpp_compiler %S/StrstrTest.cpp -o %t-StrstrTest
-RUN: not %run %t-StrstrTest   -seed=1 -runs=200   2>&1 | FileCheck %s
-CHECK: BINGO
+RUN: not %run %t-StrstrTest   -seed=1 -runs=200   2>&1 | FileCheck %s --check-prefix=CHECK1
+CHECK1: BINGO
+
+RUN: %cpp_compiler -fno-sanitize=address -fno-builtin-strstr %S/StrstrTest.cpp -o %t-NoAsanStrstrTest
+RUN: not %run %t-StrstrTest   -seed=1 -runs=200   2>&1 | FileCheck %s --check-prefix=CHECK2
+CHECK2: BINGO
 
Index: compiler-rt/test/fuzzer/strncmp.test
===
--- compiler-rt/test/fuzzer/strncmp.test
+++ compiler-rt/test/fuzzer/strncmp.test
@@ -1,5 +1,9 @@
 UNSUPPORTED: freebsd
 RUN: %cpp_compiler %S/StrncmpTest.cpp -o %t-StrncmpTest
-RUN: not %run %t-StrncmpTest  -seed=2 -runs=1000   2>&1 | FileCheck %s
-CHECK: BINGO
+RUN: not %run %t-StrncmpTest  -seed=2 -runs=1000   2>&1 | FileCheck %s --check-prefix=CHECK1
+CHECK1: BINGO
+
+RUN: %cpp_compiler -fno-sanitize=address -fno-builtin-strcmp %S/StrncmpTest.cpp -o %t-NoAsanStrncmpTest
+RUN: not %run %t-StrncmpTest  -seed=2 -runs=1000   2>&1 | FileCheck %s --check-prefix=CHECK2
+CHECK2: BINGO
 
Index: compiler-rt/test/fuzzer/strcmp.test
===
--- compiler-rt/test/fuzzer/strcmp.test
+++ compiler-rt/test/fuzzer/strcmp.test
@@ -1,5 +1,8 @@
 UNSUPPORTED: freebsd
 RUN: %cpp_compiler %S/StrcmpTest.cpp -o %t-StrcmpTest
-RUN: not %run %t-StrcmpTest   -seed=1 -runs=200   2>&1 | FileCheck %s
-CHECK: BINGO
+RUN: not %run %t-StrcmpTest   -seed=1 -runs=200   2>&1 | FileCheck %s --check-prefix=CHECK1
+CHECK1: BINGO
 
+RUN: %cpp_compiler -fno-sanitize=address -fno-builtin-strcmp %S/StrcmpTest.cpp -o %t-StrcmpTest
+RUN: not %run %t-StrcmpTest   -seed=1 -runs=200   2>&1 | FileCheck %s --check-prefix=CHECK2
+CHECK2: BINGO
Index: compiler-rt/test/fuzzer/memcmp.test
===
--- compiler-rt/test/fuzzer/memcmp.test
+++ compiler-rt/test/fuzzer/memcmp.test
@@ -1,4 +1,8 @@
 UNSUPPORTED: freebsd
 RUN: %cpp_compiler %S/MemcmpTest.cpp -o %t-MemcmpTest
-RUN: not %run %t-MemcmpTest   -seed=1 -runs=1000   2>&1 | FileCheck %s
-CHECK: BINGO
+RUN: not %run %t-MemcmpTest   -seed=1 -runs=1000   2>&1 | FileCheck %s --check-prefix=CHECK1
+CHECK1: BINGO
+
+RUN: %cpp_compiler -fno-sanitize=address -fno-builtin-memcmp %S/MemcmpTest.cpp -o %t-MemcmpTest
+RUN: not %run %t-MemcmpTest   -seed=1 -runs=1000   2>&1 | FileCheck %s --check-prefix=CHECK2
+CHECK2: BINGO
Index: compiler-rt/lib/fuzzer/FuzzerPlatform.h
===
--- compiler-rt/lib/fuzzer/FuzzerPlatform.h
+++ compiler-rt/lib/fuzzer/FuzzerPlatform.h
@@ -1,25 +1,16 @@
-//===- FuzzerDefs.h - Internal header for the Fuzzer *- C++ -* ===//
+//===-- FuzzerInterceptors.cpp ===//
 //
 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
 // See https://llvm.org/LICENSE.txt for license information.
 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
 //
 //===--===//
-// Basic definitions.
+//
+// Common platform macros.
 //===--===//
 
-#ifndef 

[PATCH] D83702: [AIX]Generate debug info for static init related functions

2020-07-13 Thread Hubert Tong via Phabricator via cfe-commits
hubert.reinterpretcast added inline comments.



Comment at: clang/lib/CodeGen/CGDeclCXX.cpp:248-250
   CGF.StartFunction(GlobalDecl(, DynamicInitKind::AtExit),
-CGM.getContext().VoidTy, fn, FI, FunctionArgList());
+CGM.getContext().VoidTy, fn, FI, FunctionArgList(),
+VD.getLocation(), VD.getInit()->getExprLoc());

dblaikie wrote:
> Any ideas why this is only showing up for AIX & not other targets, given this 
> code looks to be generic, not AIX-specific?
Yes, because the AIX implementation generates a direct call to the stub 
function on the finalization path when it finds that a stub was still 
registered with `atexit`.

That would explain why other platforms to not encounter this message:
```
inlinable function call in a function with debug info must have a !dbg location
```



Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D83702



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


[clang] 746b8c4 - Basic support for flexible array members in constant evaluation.

2020-07-13 Thread Richard Smith via cfe-commits

Author: Richard Smith
Date: 2020-07-13T16:57:53-07:00
New Revision: 746b8c400bd3f975b49f4092aa6ecd30ade7cfa5

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

LOG: Basic support for flexible array members in constant evaluation.

We don't allow runtime-sized flexible array members, nor initialization
of flexible array members, but it seems reasonable to support the most
basic case where the flexible array member is empty.

Added: 


Modified: 
clang/lib/AST/ExprConstant.cpp
clang/test/SemaCXX/constant-expression-cxx11.cpp

Removed: 




diff  --git a/clang/lib/AST/ExprConstant.cpp b/clang/lib/AST/ExprConstant.cpp
index a4dc0ccad1e0..d20c2382b6ac 100644
--- a/clang/lib/AST/ExprConstant.cpp
+++ b/clang/lib/AST/ExprConstant.cpp
@@ -9929,8 +9929,18 @@ namespace {
 bool ZeroInitialization(const Expr *E) {
   const ConstantArrayType *CAT =
   Info.Ctx.getAsConstantArrayType(E->getType());
-  if (!CAT)
+  if (!CAT) {
+if (const IncompleteArrayType *IAT =
+Info.Ctx.getAsIncompleteArrayType(E->getType())) {
+  // We can be asked to zero-initialize a flexible array member; this
+  // is represented as an ImplicitValueInitExpr of incomplete array
+  // type. In this case, the array has zero elements.
+  Result = APValue(APValue::UninitArray(), 0, 0);
+  return true;
+}
+// FIXME: We could handle VLAs here.
 return Error(E);
+  }
 
   Result = APValue(APValue::UninitArray(), 0,
CAT->getSize().getZExtValue());

diff  --git a/clang/test/SemaCXX/constant-expression-cxx11.cpp 
b/clang/test/SemaCXX/constant-expression-cxx11.cpp
index 78e9fef96c8d..b69bcb2fef9d 100644
--- a/clang/test/SemaCXX/constant-expression-cxx11.cpp
+++ b/clang/test/SemaCXX/constant-expression-cxx11.cpp
@@ -2322,3 +2322,22 @@ namespace array_size {
 f3(a);
   }
 }
+
+namespace flexible_array {
+  struct A { int x; char arr[]; }; // expected-warning {{C99}} expected-note 
{{here}}
+  constexpr A a = {1};
+  static_assert(a.x == 1, "");
+  static_assert( != nullptr, "");
+  static_assert(a.arr[0], ""); // expected-error {{constant expression}} 
expected-note {{array member without known bound}}
+  static_assert(a.arr[1], ""); // expected-error {{constant expression}} 
expected-note {{array member without known bound}}
+
+  constexpr A b[] = {{1}, {2}, {3}}; // expected-warning {{flexible array 
member}}
+  static_assert(b[0].x == 1, "");
+  static_assert(b[1].x == 2, "");
+  static_assert(b[2].x == 3, "");
+  static_assert(b[2].arr[0], ""); // expected-error {{constant expression}} 
expected-note {{array member without known bound}}
+
+  // If we ever start to accept this, we'll need to ensure we can
+  // constant-evaluate it properly.
+  constexpr A c = {1, 2, 3}; // expected-error {{initialization of flexible 
array member}}
+}



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


[PATCH] D83592: [Parser] Add comment to skipped regions

2020-07-13 Thread Zequan Wu via Phabricator via cfe-commits
zequanwu added a comment.

For those test cases, I could either moving the comments inside a function to 
outside or change `CHECK-NEXT` to `CHECK`

In D83592#2148833 , @vsk wrote:

> Before updating any tests, maybe it's worth doing a quick experiment with 
> comments placed in different contexts, to see whether adding these skipped 
> regions is really sufficient. For example, given:
>
>   1|  for (auto x : collection) {
>   2|// Explain the loop.
>   3|  }
>
>
> The loop region covers lines 1-3. If we skip the comment range on line 2, 
> does an execution count from the loop region still get picked up? I'd expect 
> it to. It's possible that we need more information from the preprocessor 
> about whether the line is fully comment/whitespace-only.


Here is what I got:

  $ clang -fcoverage-mapping -fprofile-instr-generate /tmp/a.c -Xclang 
-dump-coverage-mapping && ./a.out && llvm-profdata merge -sparse 
default.profraw -o a.profdata && llvm-cov show ./a.out -instr-profile=a.profdata
  main:
File 0, 1:12 -> 6:2 = #0
File 0, 2:19 -> 2:25 = (#0 + #1)
File 0, 2:27 -> 2:30 = #1
Gap,File 0, 2:31 -> 2:32 = #1
File 0, 2:32 -> 4:4 = #1
Skipped,File 0, 3:5 -> 3:15 = 0
  1|  1|int main() {
  2| 11|  for (int i = 0; i < 10; i++) {
  3|   |// comment
  4| 10|  }
  5|  1|  return 0;
  6|  1|}

For those failed test cases, they are caused by extra `Skipped, File ...` lines 
which invalidate some `CHECK-NEXT`. 
I could either change `CHECK-NEXT` to `CHECK` or moving those checks inside 
function to above the function, since comments outside functions will not be 
tracked.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D83592



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


[PATCH] D83660: [analyzer] Fix a crash for dereferencing an empty llvm::Optional variable in SMTConstraintManager.h.

2020-07-13 Thread Artem Dergachev via Phabricator via cfe-commits
NoQ added reviewers: vsavchenko, steakhal.
NoQ added a comment.

Looks like a copy-paste error indeed.

@OikawaKirie do you accidentally have a test case to reproduce the crash, so 
that we could add it to our regression test suite? 'Cause traditionally we add 
a test to every patch.

Note that SMT-backed constraint managers aren't an actual supported mode; it's 
an experimental project that isn't yet supposed to be used anywhere and 
probably won't be ever officially supported, unless reworked dramatically.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D83660



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


[PATCH] D83592: [Parser] Add comment to skipped regions

2020-07-13 Thread Vedant Kumar via Phabricator via cfe-commits
vsk added a comment.

Before updating any tests, maybe it's worth doing a quick experiment with 
comments placed in different contexts, to see whether adding these skipped 
regions is really sufficient. For example, given:

  1|  for (auto x : collection) {
  2|// Explain the loop.
  3|  }

The loop region covers lines 1-3. If we skip the comment range on line 2, does 
an execution count from the loop region still get picked up? I'd expect it to. 
It's possible that we need more information from the preprocessor about whether 
the line is fully comment/whitespace-only.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D83592



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


[PATCH] D82356: Fix bad doxygen result for class clang::ento::CallEvent and its derived classes

2020-07-13 Thread Artem Dergachev via Phabricator via cfe-commits
NoQ added a comment.

Sorry!! I was sure i pushed this. Thank you Valeriy.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D82356



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


[PATCH] D83539: [analyzer][tests] Introduce analyzer benchmarking framework

2020-07-13 Thread Artem Dergachev via Phabricator via cfe-commits
NoQ accepted this revision.
NoQ added a comment.
This revision is now accepted and ready to land.

Box-and-whisker diagrams 




Comment at: clang/utils/analyzer/SATestBenchmark.py:18
+
+import pandas as pd
+from typing import List, Tuple

@Szelethus ???



Comment at: clang/utils/analyzer/SATestBenchmark.py:139-140
+import matplotlib
+import seaborn as sns
+from matplotlib import pyplot as plt
+

Why shorten? It's not that we're saving a lot of typing, and i think it's 
easier to read when package names are recognizable.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D83539



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


[PATCH] D83611: [clang][NFC] Add 'override' keyword to virtual function overrides

2020-07-13 Thread David Blaikie via Phabricator via cfe-commits
dblaikie accepted this revision.
dblaikie added a comment.
This revision is now accepted and ready to land.

Looks good - thanks!

(I can't actually find where the instructions are on how to request commit 
access these days - but should you find them, I thin it'd be fine for you to 
have commit access for committing changes like this)


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D83611



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


[PATCH] D83286: [analyzer][solver] Track symbol disequalities

2020-07-13 Thread Artem Dergachev via Phabricator via cfe-commits
NoQ accepted this revision.
NoQ added a comment.
This revision is now accepted and ready to land.

Data 

Maybe spend a few minutes remeasuring `libsoundio` more carefully, just in 
case? Also i really wish we had per-TU data of that kind, to see if any 
particular TUs have regressed significantly.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D83286



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


[clang] 9d5a8b7 - Fix a missing update that C compiles default to gnu17.

2020-07-13 Thread Stephen Hines via cfe-commits

Author: Stephen Hines
Date: 2020-07-13T16:35:54-07:00
New Revision: 9d5a8b7edb28707879b8e2a37d14a4cf6dbcbefa

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

LOG: Fix a missing update that C compiles default to gnu17.

https://reviews.llvm.org/D75383 switched the C default to gnu17, but
missed this instance.

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

Added: 


Modified: 
clang/docs/CommandGuide/clang.rst

Removed: 




diff  --git a/clang/docs/CommandGuide/clang.rst 
b/clang/docs/CommandGuide/clang.rst
index 5978650c3288..2cca04fb31f1 100644
--- a/clang/docs/CommandGuide/clang.rst
+++ b/clang/docs/CommandGuide/clang.rst
@@ -146,7 +146,7 @@ Language Selection and Mode Options
 
ISO C 2017 with GNU extensions
 
- The default C language standard is ``gnu11``, except on PS4, where it is
+ The default C language standard is ``gnu17``, except on PS4, where it is
  ``gnu99``.
 
  Supported values for the C++ language are:



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


[PATCH] D83592: [Parser] Add comment to skipped regions

2020-07-13 Thread Zequan Wu via Phabricator via cfe-commits
zequanwu updated this revision to Diff 277611.
zequanwu added a comment.

Accidentally uploaded binary.. removed now.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D83592

Files:
  clang/lib/CodeGen/CodeGenAction.cpp
  clang/lib/CodeGen/CoverageMappingGen.cpp
  clang/lib/CodeGen/CoverageMappingGen.h


Index: clang/lib/CodeGen/CoverageMappingGen.h
===
--- clang/lib/CodeGen/CoverageMappingGen.h
+++ clang/lib/CodeGen/CoverageMappingGen.h
@@ -16,6 +16,7 @@
 #include "clang/Basic/LLVM.h"
 #include "clang/Basic/SourceLocation.h"
 #include "clang/Lex/PPCallbacks.h"
+#include "clang/Lex/Preprocessor.h"
 #include "llvm/ADT/DenseMap.h"
 #include "llvm/IR/GlobalValue.h"
 #include "llvm/Support/raw_ostream.h"
@@ -32,12 +33,14 @@
 /// Stores additional source code information like skipped ranges which
 /// is required by the coverage mapping generator and is obtained from
 /// the preprocessor.
-class CoverageSourceInfo : public PPCallbacks {
+class CoverageSourceInfo : public PPCallbacks, public CommentHandler {
   std::vector SkippedRanges;
 public:
   ArrayRef getSkippedRanges() const { return SkippedRanges; }
 
   void SourceRangeSkipped(SourceRange Range, SourceLocation EndifLoc) override;
+
+  bool HandleComment(Preprocessor , SourceRange Range) override;
 };
 
 namespace CodeGen {
@@ -66,6 +69,8 @@
  uint64_t FilenamesRef);
 
 public:
+  static CoverageSourceInfo *setUpCoverageCallbacks(Preprocessor );
+
   CoverageMappingModuleGen(CodeGenModule , CoverageSourceInfo )
   : CGM(CGM), SourceInfo(SourceInfo) {}
 
Index: clang/lib/CodeGen/CoverageMappingGen.cpp
===
--- clang/lib/CodeGen/CoverageMappingGen.cpp
+++ clang/lib/CodeGen/CoverageMappingGen.cpp
@@ -35,10 +35,23 @@
 using namespace CodeGen;
 using namespace llvm::coverage;
 
+CoverageSourceInfo *
+CoverageMappingModuleGen::setUpCoverageCallbacks(Preprocessor ) {
+  CoverageSourceInfo *CoverageInfo = new CoverageSourceInfo;
+  PP.addPPCallbacks(std::unique_ptr(CoverageInfo));
+  PP.addCommentHandler(CoverageInfo);
+  return CoverageInfo;
+}
+
 void CoverageSourceInfo::SourceRangeSkipped(SourceRange Range, SourceLocation) 
{
   SkippedRanges.push_back(Range);
 }
 
+bool CoverageSourceInfo::HandleComment(Preprocessor &, SourceRange Range) {
+  SkippedRanges.push_back(Range);
+  return false;
+}
+
 namespace {
 
 /// A region of source code that can be mapped to a counter.
Index: clang/lib/CodeGen/CodeGenAction.cpp
===
--- clang/lib/CodeGen/CodeGenAction.cpp
+++ clang/lib/CodeGen/CodeGenAction.cpp
@@ -990,11 +990,9 @@
 
   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(),


Index: clang/lib/CodeGen/CoverageMappingGen.h
===
--- clang/lib/CodeGen/CoverageMappingGen.h
+++ clang/lib/CodeGen/CoverageMappingGen.h
@@ -16,6 +16,7 @@
 #include "clang/Basic/LLVM.h"
 #include "clang/Basic/SourceLocation.h"
 #include "clang/Lex/PPCallbacks.h"
+#include "clang/Lex/Preprocessor.h"
 #include "llvm/ADT/DenseMap.h"
 #include "llvm/IR/GlobalValue.h"
 #include "llvm/Support/raw_ostream.h"
@@ -32,12 +33,14 @@
 /// Stores additional source code information like skipped ranges which
 /// is required by the coverage mapping generator and is obtained from
 /// the preprocessor.
-class CoverageSourceInfo : public PPCallbacks {
+class CoverageSourceInfo : public PPCallbacks, public CommentHandler {
   std::vector SkippedRanges;
 public:
   ArrayRef getSkippedRanges() const { return SkippedRanges; }
 
   void SourceRangeSkipped(SourceRange Range, SourceLocation EndifLoc) override;
+
+  bool HandleComment(Preprocessor , SourceRange Range) override;
 };
 
 namespace CodeGen {
@@ -66,6 +69,8 @@
  uint64_t FilenamesRef);
 
 public:
+  static CoverageSourceInfo *setUpCoverageCallbacks(Preprocessor );
+
   CoverageMappingModuleGen(CodeGenModule , CoverageSourceInfo )
   : CGM(CGM), SourceInfo(SourceInfo) {}
 
Index: clang/lib/CodeGen/CoverageMappingGen.cpp
===
--- clang/lib/CodeGen/CoverageMappingGen.cpp
+++ clang/lib/CodeGen/CoverageMappingGen.cpp
@@ -35,10 +35,23 @@
 using namespace 

[PATCH] D83726: Fix a missing update that C compiles default to gnu17.

2020-07-13 Thread Stephen Hines via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG9d5a8b7edb28: Fix a missing update that C compiles default 
to gnu17. (authored by srhines).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D83726

Files:
  clang/docs/CommandGuide/clang.rst


Index: clang/docs/CommandGuide/clang.rst
===
--- clang/docs/CommandGuide/clang.rst
+++ clang/docs/CommandGuide/clang.rst
@@ -146,7 +146,7 @@
 
ISO C 2017 with GNU extensions
 
- The default C language standard is ``gnu11``, except on PS4, where it is
+ The default C language standard is ``gnu17``, except on PS4, where it is
  ``gnu99``.
 
  Supported values for the C++ language are:


Index: clang/docs/CommandGuide/clang.rst
===
--- clang/docs/CommandGuide/clang.rst
+++ clang/docs/CommandGuide/clang.rst
@@ -146,7 +146,7 @@
 
ISO C 2017 with GNU extensions
 
- The default C language standard is ``gnu11``, except on PS4, where it is
+ The default C language standard is ``gnu17``, except on PS4, where it is
  ``gnu99``.
 
  Supported values for the C++ language are:
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D83702: [AIX]Generate debug info for static init related functions

2020-07-13 Thread David Blaikie via Phabricator via cfe-commits
dblaikie added inline comments.



Comment at: clang/lib/CodeGen/CGDeclCXX.cpp:248-250
   CGF.StartFunction(GlobalDecl(, DynamicInitKind::AtExit),
-CGM.getContext().VoidTy, fn, FI, FunctionArgList());
+CGM.getContext().VoidTy, fn, FI, FunctionArgList(),
+VD.getLocation(), VD.getInit()->getExprLoc());

Any ideas why this is only showing up for AIX & not other targets, given this 
code looks to be generic, not AIX-specific?



Comment at: clang/test/CodeGenCXX/aix-static-init-debug-info.cpp:9-19
+int a = 0;
+
+class X {
+public:
+  X() {
+a = 1;
+  }

This could probably be simplified to:
```
struct X {
  X();
  ~X();
};
```

This would still produce a global ctor and dtor without the superfluous 
variable, etc.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D83702



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


[PATCH] D83592: [Parser] Add comment to skipped regions

2020-07-13 Thread Zequan Wu via Phabricator via cfe-commits
zequanwu updated this revision to Diff 277606.
zequanwu added a comment.

Remove old code.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D83592

Files:
  a.out
  a.profdata
  clang/lib/CodeGen/CodeGenAction.cpp
  clang/lib/CodeGen/CoverageMappingGen.cpp
  clang/lib/CodeGen/CoverageMappingGen.h
  default.profraw


Index: clang/lib/CodeGen/CoverageMappingGen.h
===
--- clang/lib/CodeGen/CoverageMappingGen.h
+++ clang/lib/CodeGen/CoverageMappingGen.h
@@ -16,6 +16,7 @@
 #include "clang/Basic/LLVM.h"
 #include "clang/Basic/SourceLocation.h"
 #include "clang/Lex/PPCallbacks.h"
+#include "clang/Lex/Preprocessor.h"
 #include "llvm/ADT/DenseMap.h"
 #include "llvm/IR/GlobalValue.h"
 #include "llvm/Support/raw_ostream.h"
@@ -32,12 +33,14 @@
 /// Stores additional source code information like skipped ranges which
 /// is required by the coverage mapping generator and is obtained from
 /// the preprocessor.
-class CoverageSourceInfo : public PPCallbacks {
+class CoverageSourceInfo : public PPCallbacks, public CommentHandler {
   std::vector SkippedRanges;
 public:
   ArrayRef getSkippedRanges() const { return SkippedRanges; }
 
   void SourceRangeSkipped(SourceRange Range, SourceLocation EndifLoc) override;
+
+  bool HandleComment(Preprocessor , SourceRange Range) override;
 };
 
 namespace CodeGen {
@@ -66,6 +69,8 @@
  uint64_t FilenamesRef);
 
 public:
+  static CoverageSourceInfo *setUpCoverageCallbacks(Preprocessor );
+
   CoverageMappingModuleGen(CodeGenModule , CoverageSourceInfo )
   : CGM(CGM), SourceInfo(SourceInfo) {}
 
Index: clang/lib/CodeGen/CoverageMappingGen.cpp
===
--- clang/lib/CodeGen/CoverageMappingGen.cpp
+++ clang/lib/CodeGen/CoverageMappingGen.cpp
@@ -35,10 +35,23 @@
 using namespace CodeGen;
 using namespace llvm::coverage;
 
+CoverageSourceInfo *
+CoverageMappingModuleGen::setUpCoverageCallbacks(Preprocessor ) {
+  CoverageSourceInfo *CoverageInfo = new CoverageSourceInfo;
+  PP.addPPCallbacks(std::unique_ptr(CoverageInfo));
+  PP.addCommentHandler(CoverageInfo);
+  return CoverageInfo;
+}
+
 void CoverageSourceInfo::SourceRangeSkipped(SourceRange Range, SourceLocation) 
{
   SkippedRanges.push_back(Range);
 }
 
+bool CoverageSourceInfo::HandleComment(Preprocessor &, SourceRange Range) {
+  SkippedRanges.push_back(Range);
+  return false;
+}
+
 namespace {
 
 /// A region of source code that can be mapped to a counter.
Index: clang/lib/CodeGen/CodeGenAction.cpp
===
--- clang/lib/CodeGen/CodeGenAction.cpp
+++ clang/lib/CodeGen/CodeGenAction.cpp
@@ -990,11 +990,9 @@
 
   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(),


Index: clang/lib/CodeGen/CoverageMappingGen.h
===
--- clang/lib/CodeGen/CoverageMappingGen.h
+++ clang/lib/CodeGen/CoverageMappingGen.h
@@ -16,6 +16,7 @@
 #include "clang/Basic/LLVM.h"
 #include "clang/Basic/SourceLocation.h"
 #include "clang/Lex/PPCallbacks.h"
+#include "clang/Lex/Preprocessor.h"
 #include "llvm/ADT/DenseMap.h"
 #include "llvm/IR/GlobalValue.h"
 #include "llvm/Support/raw_ostream.h"
@@ -32,12 +33,14 @@
 /// Stores additional source code information like skipped ranges which
 /// is required by the coverage mapping generator and is obtained from
 /// the preprocessor.
-class CoverageSourceInfo : public PPCallbacks {
+class CoverageSourceInfo : public PPCallbacks, public CommentHandler {
   std::vector SkippedRanges;
 public:
   ArrayRef getSkippedRanges() const { return SkippedRanges; }
 
   void SourceRangeSkipped(SourceRange Range, SourceLocation EndifLoc) override;
+
+  bool HandleComment(Preprocessor , SourceRange Range) override;
 };
 
 namespace CodeGen {
@@ -66,6 +69,8 @@
  uint64_t FilenamesRef);
 
 public:
+  static CoverageSourceInfo *setUpCoverageCallbacks(Preprocessor );
+
   CoverageMappingModuleGen(CodeGenModule , CoverageSourceInfo )
   : CGM(CGM), SourceInfo(SourceInfo) {}
 
Index: clang/lib/CodeGen/CoverageMappingGen.cpp
===
--- clang/lib/CodeGen/CoverageMappingGen.cpp
+++ clang/lib/CodeGen/CoverageMappingGen.cpp
@@ -35,10 +35,23 @@
 using 

[PATCH] D83592: [Parser] Add comment to skipped regions

2020-07-13 Thread Zequan Wu via Phabricator via cfe-commits
zequanwu marked an inline comment as done.
zequanwu added inline comments.



Comment at: llvm/lib/ProfileData/Coverage/CoverageMappingWriter.cpp:152
+static MutableArrayRef
+mergeSkippedRegions(MutableArrayRef MappingRegions) {
+  SmallVector MergedRegions;

vsk wrote:
> zequanwu wrote:
> > vsk wrote:
> > > This seems like a lot of complexity to add to handle a narrow case. Is it 
> > > necessary to merge skipped regions early in the process? Note that llvm's 
> > > SegmentBuilder takes care of merging regions at the very end.
> > Merging at here is to avoid duplicate output for option 
> > `-dump-coverage-mapping`. Like the following example to avoid `Skipped,File 
> > 0, 2:3 -> 4:9 = 0` and `Skipped,File 0, 2:15 -> 2:25 = 0` to be outputted 
> > at the same time. They should be merged into 1 region `Skipped,File 0, 2:3 
> > -> 4:9 = 0`
> > ```
> > File 0, 1:12 -> 6:2 = #0
> >  Skipped,File 0, 2:3 -> 4:9 = 0
> >  Skipped,File 0, 2:15 -> 2:25 = 0
> >1|  1|int main() {
> >2|   |  #ifdef TEST // comment
> >3|   |  int x = 1;
> >4|   |  #endif
> >5|  1|  return 0;
> >6|  1|}
> > ```
> > So, we need to do it early.
> I see that there are duplicate 'Skipped' regions emitted in this case, but 
> I'm not sure what problems this causes. For testing, we could check that both 
> skipped regions are emitted, or perhaps only check that the outermost skipped 
> region is emitted and ignore others. Is there some other kind of hard error 
> (like an assert) caused by having nested skipped regions? If not, perhaps 
> it's not worth it to merge them.
No, it doesn't cause any error.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D83592



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


[PATCH] D83592: [Parser] Add comment to skipped regions

2020-07-13 Thread Zequan Wu via Phabricator via cfe-commits
zequanwu updated this revision to Diff 277605.
zequanwu added a comment.

Vedant, thanks for your suggestions.

- Remove merging function.
- Address comments.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D83592

Files:
  clang/include/clang/Lex/PPCallbacks.h
  clang/lib/CodeGen/CodeGenAction.cpp
  clang/lib/CodeGen/CoverageMappingGen.cpp
  clang/lib/CodeGen/CoverageMappingGen.h
  clang/lib/Parse/Parser.cpp

Index: clang/lib/Parse/Parser.cpp
===
--- clang/lib/Parse/Parser.cpp
+++ clang/lib/Parse/Parser.cpp
@@ -34,6 +34,7 @@
   explicit ActionCommentHandler(Sema ) : S(S) { }
 
   bool HandleComment(Preprocessor , SourceRange Comment) override {
+PP.getPPCallbacks()->CommentSkipped(Comment);
 S.ActOnComment(Comment);
 return false;
   }
Index: clang/lib/CodeGen/CoverageMappingGen.h
===
--- clang/lib/CodeGen/CoverageMappingGen.h
+++ clang/lib/CodeGen/CoverageMappingGen.h
@@ -16,6 +16,7 @@
 #include "clang/Basic/LLVM.h"
 #include "clang/Basic/SourceLocation.h"
 #include "clang/Lex/PPCallbacks.h"
+#include "clang/Lex/Preprocessor.h"
 #include "llvm/ADT/DenseMap.h"
 #include "llvm/IR/GlobalValue.h"
 #include "llvm/Support/raw_ostream.h"
@@ -32,12 +33,14 @@
 /// Stores additional source code information like skipped ranges which
 /// is required by the coverage mapping generator and is obtained from
 /// the preprocessor.
-class CoverageSourceInfo : public PPCallbacks {
+class CoverageSourceInfo : public PPCallbacks, public CommentHandler {
   std::vector SkippedRanges;
 public:
   ArrayRef getSkippedRanges() const { return SkippedRanges; }
 
   void SourceRangeSkipped(SourceRange Range, SourceLocation EndifLoc) override;
+
+  bool HandleComment(Preprocessor , SourceRange Range) override;
 };
 
 namespace CodeGen {
@@ -66,6 +69,8 @@
  uint64_t FilenamesRef);
 
 public:
+  static CoverageSourceInfo *setUpCoverageCallbacks(Preprocessor );
+
   CoverageMappingModuleGen(CodeGenModule , CoverageSourceInfo )
   : CGM(CGM), SourceInfo(SourceInfo) {}
 
Index: clang/lib/CodeGen/CoverageMappingGen.cpp
===
--- clang/lib/CodeGen/CoverageMappingGen.cpp
+++ clang/lib/CodeGen/CoverageMappingGen.cpp
@@ -35,10 +35,23 @@
 using namespace CodeGen;
 using namespace llvm::coverage;
 
+CoverageSourceInfo *
+CoverageMappingModuleGen::setUpCoverageCallbacks(Preprocessor ) {
+  CoverageSourceInfo *CoverageInfo = new CoverageSourceInfo;
+  PP.addPPCallbacks(std::unique_ptr(CoverageInfo));
+  PP.addCommentHandler(CoverageInfo);
+  return CoverageInfo;
+}
+
 void CoverageSourceInfo::SourceRangeSkipped(SourceRange Range, SourceLocation) {
   SkippedRanges.push_back(Range);
 }
 
+bool CoverageSourceInfo::HandleComment(Preprocessor &, SourceRange Range) {
+  SkippedRanges.push_back(Range);
+  return false;
+}
+
 namespace {
 
 /// A region of source code that can be mapped to a counter.
Index: clang/lib/CodeGen/CodeGenAction.cpp
===
--- clang/lib/CodeGen/CodeGenAction.cpp
+++ clang/lib/CodeGen/CodeGenAction.cpp
@@ -990,11 +990,9 @@
 
   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(),
Index: clang/include/clang/Lex/PPCallbacks.h
===
--- clang/include/clang/Lex/PPCallbacks.h
+++ clang/include/clang/Lex/PPCallbacks.h
@@ -319,6 +319,10 @@
   virtual void SourceRangeSkipped(SourceRange Range, SourceLocation EndifLoc) {
   }
 
+  /// Hood called when the source range is comment, which should be skipped.
+  /// \param Range The SourceRange that is comment.
+  virtual void CommentSkipped(SourceRange Range) {}
+
   enum ConditionValueKind {
 CVK_NotEvaluated, CVK_False, CVK_True
   };
@@ -565,6 +569,11 @@
 Second->SourceRangeSkipped(Range, EndifLoc);
   }
 
+  void CommentSkipped(SourceRange Range) override {
+First->CommentSkipped(Range);
+Second->CommentSkipped(Range);
+  }
+
   /// Hook called whenever an \#if is seen.
   void If(SourceLocation Loc, SourceRange ConditionRange,
   ConditionValueKind ConditionValue) override {
___
cfe-commits mailing list
cfe-commits@lists.llvm.org

[PATCH] D83188: [clang-tidy] bugprone-bool-pointer-implicit-conversion doesn't handle members

2020-07-13 Thread Alex Cameron via Phabricator via cfe-commits
tetsuo-cpp added a comment.

Friendly ping!


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

https://reviews.llvm.org/D83188



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


[PATCH] D83701: [analyzer][tests] Add 5 more projects for testing

2020-07-13 Thread Artem Dergachev via Phabricator via cfe-commits
NoQ accepted this revision.
NoQ added a subscriber: danielmarjamaki.
NoQ added inline comments.
This revision is now accepted and ready to land.



Comment at: clang/utils/analyzer/projects/projects.json:107-113
+  {
+"name": "cppcheck",
+"mode": 1,
+"source": "git",
+"origin": "https://github.com/danmar/cppcheck.git;,
+"commit": "5fa3d53"
+  },

A wonderful recursion indeed. //*tags @danielmarjamaki*//


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D83701



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


[PATCH] D71739: [AssumeBundles] Use operand bundles to encode alignment assumptions

2020-07-13 Thread Tyker via Phabricator via cfe-commits
This revision was not accepted when it landed; it landed in state "Needs 
Review".
This revision was automatically updated to reflect the committed changes.
Closed by commit rG8d09f20798ac: [AssumeBundles] Use operand bundles to encode 
alignment assumptions (authored by Tyker).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D71739

Files:
  clang/lib/CodeGen/CodeGenFunction.cpp
  clang/test/CodeGen/align_value.cpp
  clang/test/CodeGen/alloc-align-attr.c
  clang/test/CodeGen/assume-aligned-and-alloc-align-attributes.c
  clang/test/CodeGen/builtin-align-array.c
  clang/test/CodeGen/builtin-align.c
  clang/test/CodeGen/builtin-assume-aligned.c
  
clang/test/CodeGen/catch-alignment-assumption-attribute-align_value-on-lvalue.cpp
  
clang/test/CodeGen/catch-alignment-assumption-attribute-align_value-on-paramvar.cpp
  
clang/test/CodeGen/catch-alignment-assumption-attribute-alloc_align-on-function-variable.cpp
  
clang/test/CodeGen/catch-alignment-assumption-attribute-alloc_align-on-function.cpp
  
clang/test/CodeGen/catch-alignment-assumption-attribute-assume_aligned-on-function-two-params.cpp
  
clang/test/CodeGen/catch-alignment-assumption-attribute-assume_aligned-on-function.cpp
  
clang/test/CodeGen/catch-alignment-assumption-builtin_assume_aligned-three-params-variable.cpp
  
clang/test/CodeGen/catch-alignment-assumption-builtin_assume_aligned-three-params.cpp
  
clang/test/CodeGen/catch-alignment-assumption-builtin_assume_aligned-two-params.cpp
  clang/test/CodeGen/catch-alignment-assumption-openmp.cpp
  clang/test/CodeGen/non-power-of-2-alignment-assumptions.c
  clang/test/OpenMP/simd_codegen.cpp
  clang/test/OpenMP/simd_metadata.c
  clang/test/OpenMP/target_teams_distribute_parallel_for_simd_codegen.cpp
  llvm/include/llvm/IR/IRBuilder.h
  llvm/include/llvm/Transforms/Scalar/AlignmentFromAssumptions.h
  llvm/lib/Analysis/AssumeBundleQueries.cpp
  llvm/lib/IR/IRBuilder.cpp
  llvm/lib/IR/Verifier.cpp
  llvm/lib/Transforms/InstCombine/InstCombineCalls.cpp
  llvm/lib/Transforms/Scalar/AlignmentFromAssumptions.cpp
  llvm/test/Transforms/AlignmentFromAssumptions/simple.ll
  llvm/test/Transforms/AlignmentFromAssumptions/simple32.ll
  llvm/test/Transforms/Inline/align.ll
  llvm/test/Transforms/InstCombine/assume.ll
  llvm/test/Transforms/PhaseOrdering/inlining-alignment-assumptions.ll
  llvm/test/Verifier/assume-bundles.ll
  llvm/unittests/Analysis/AssumeBundleQueriesTest.cpp

Index: llvm/unittests/Analysis/AssumeBundleQueriesTest.cpp
===
--- llvm/unittests/Analysis/AssumeBundleQueriesTest.cpp
+++ llvm/unittests/Analysis/AssumeBundleQueriesTest.cpp
@@ -546,3 +546,41 @@
   ASSERT_EQ(AR[0].Index, 1u);
   ASSERT_EQ(AR[0].Assume, &*First);
 }
+
+TEST(AssumeQueryAPI, Alignment) {
+  LLVMContext C;
+  SMDiagnostic Err;
+  std::unique_ptr Mod = parseAssemblyString(
+  "declare void @llvm.assume(i1)\n"
+  "define void @test(i32* %P, i32* %P1, i32* %P2, i32 %I3, i1 %B) {\n"
+  "call void @llvm.assume(i1 true) [\"align\"(i32* %P, i32 8, i32 %I3)]\n"
+  "call void @llvm.assume(i1 true) [\"align\"(i32* %P1, i32 %I3, i32 "
+  "%I3)]\n"
+  "call void @llvm.assume(i1 true) [\"align\"(i32* %P2, i32 16, i32 8)]\n"
+  "ret void\n}\n",
+  Err, C);
+  if (!Mod)
+Err.print("AssumeQueryAPI", errs());
+
+  Function *F = Mod->getFunction("test");
+  BasicBlock::iterator Start = F->begin()->begin();
+  IntrinsicInst *II;
+  RetainedKnowledge RK;
+  II = cast(&*Start);
+  RK = getKnowledgeFromBundle(*II, II->bundle_op_info_begin()[0]);
+  ASSERT_EQ(RK.AttrKind, Attribute::Alignment);
+  ASSERT_EQ(RK.WasOn, F->getArg(0));
+  ASSERT_EQ(RK.ArgValue, 1u);
+  Start++;
+  II = cast(&*Start);
+  RK = getKnowledgeFromBundle(*II, II->bundle_op_info_begin()[0]);
+  ASSERT_EQ(RK.AttrKind, Attribute::Alignment);
+  ASSERT_EQ(RK.WasOn, F->getArg(1));
+  ASSERT_EQ(RK.ArgValue, 1u);
+  Start++;
+  II = cast(&*Start);
+  RK = getKnowledgeFromBundle(*II, II->bundle_op_info_begin()[0]);
+  ASSERT_EQ(RK.AttrKind, Attribute::Alignment);
+  ASSERT_EQ(RK.WasOn, F->getArg(2));
+  ASSERT_EQ(RK.ArgValue, 8u);
+}
Index: llvm/test/Verifier/assume-bundles.ll
===
--- llvm/test/Verifier/assume-bundles.ll
+++ llvm/test/Verifier/assume-bundles.ll
@@ -1,3 +1,4 @@
+; NOTE: Assertions have been autogenerated by utils/update_test_checks.py
 ; RUN: not opt -verify < %s 2>&1 | FileCheck %s
 
 declare void @llvm.assume(i1)
@@ -6,14 +7,21 @@
 ; CHECK: tags must be valid attribute names
   call void @llvm.assume(i1 true) ["adazdazd"()]
 ; CHECK: the second argument should be a constant integral value
-  call void @llvm.assume(i1 true) ["align"(i32* %P, i32 %P1)]
+  call void @llvm.assume(i1 true) ["dereferenceable"(i32* %P, i32 %P1)]
 ; CHECK: to many arguments
-  call void @llvm.assume(i1 true) ["align"(i32* %P, i32 8, i32 8)]
+  

[PATCH] D83592: [Parser] Add comment to skipped regions

2020-07-13 Thread Vedant Kumar via Phabricator via cfe-commits
vsk added a comment.

In D83592#2148638 , @zequanwu wrote:

> In D83592#2148376 , @vsk wrote:
>
> > taking advantage of the existing CommentHandler interface? To simplify 
> > things, we can add a static method like 
> > 'CoverageMappingGen::setupPreprocessorCallbacks(Preprocessor &)' and call 
> > that from CodeGenAction::CreateASTConsumer.
>
>
> Sorry, I don't quite understand this. I am already using 
> `ActionCommentHandler` to handle this one inside `HandleComment`.


ActionCommentHandler seems a bit specific to Sema. This is what I had in mind: 
https://github.com/vedantk/llvm-project/commit/5101dd5dcd92742805069dba6b3d6d6846ef3755.




Comment at: llvm/lib/ProfileData/Coverage/CoverageMappingWriter.cpp:152
+static MutableArrayRef
+mergeSkippedRegions(MutableArrayRef MappingRegions) {
+  SmallVector MergedRegions;

zequanwu wrote:
> vsk wrote:
> > This seems like a lot of complexity to add to handle a narrow case. Is it 
> > necessary to merge skipped regions early in the process? Note that llvm's 
> > SegmentBuilder takes care of merging regions at the very end.
> Merging at here is to avoid duplicate output for option 
> `-dump-coverage-mapping`. Like the following example to avoid `Skipped,File 
> 0, 2:3 -> 4:9 = 0` and `Skipped,File 0, 2:15 -> 2:25 = 0` to be outputted at 
> the same time. They should be merged into 1 region `Skipped,File 0, 2:3 -> 
> 4:9 = 0`
> ```
> File 0, 1:12 -> 6:2 = #0
>  Skipped,File 0, 2:3 -> 4:9 = 0
>  Skipped,File 0, 2:15 -> 2:25 = 0
>1|  1|int main() {
>2|   |  #ifdef TEST // comment
>3|   |  int x = 1;
>4|   |  #endif
>5|  1|  return 0;
>6|  1|}
> ```
> So, we need to do it early.
I see that there are duplicate 'Skipped' regions emitted in this case, but I'm 
not sure what problems this causes. For testing, we could check that both 
skipped regions are emitted, or perhaps only check that the outermost skipped 
region is emitted and ignore others. Is there some other kind of hard error 
(like an assert) caused by having nested skipped regions? If not, perhaps it's 
not worth it to merge them.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D83592



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


[PATCH] D83713: [WebAssembly] Triple::wasm64 related cleanup

2020-07-13 Thread Sam Clegg via Phabricator via cfe-commits
sbc100 accepted this revision.
sbc100 added inline comments.
This revision is now accepted and ready to land.



Comment at: lld/wasm/InputFiles.cpp:583
   }
+  config->is64 = t.getArch() == Triple::wasm64;
   std::vector keptComdats;

Should we error out here if you try to link two files of different arch?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D83713



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


[PATCH] D83501: [clangd][ObjC] Improve xrefs for protocols and classes

2020-07-13 Thread David Goldman via Phabricator via cfe-commits
dgoldman updated this revision to Diff 277601.
dgoldman added a comment.

Rebase


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D83501

Files:
  clang-tools-extra/clangd/FindTarget.cpp
  clang-tools-extra/clangd/XRefs.cpp
  clang-tools-extra/clangd/index/SymbolCollector.cpp
  clang-tools-extra/clangd/unittests/FindTargetTests.cpp
  clang-tools-extra/clangd/unittests/SymbolCollectorTests.cpp
  clang-tools-extra/clangd/unittests/XRefsTests.cpp

Index: clang-tools-extra/clangd/unittests/XRefsTests.cpp
===
--- clang-tools-extra/clangd/unittests/XRefsTests.cpp
+++ clang-tools-extra/clangd/unittests/XRefsTests.cpp
@@ -674,7 +674,57 @@
   enum class E { [[A]], B };
   E e = E::A^;
 };
-  )cpp"};
+  )cpp",
+
+  R"objc(
+@protocol Dog;
+@protocol $decl[[Dog]]
+- (void)bark;
+@end
+id getDoggo() {
+  return 0;
+}
+  )objc",
+
+  R"objc(
+@interface Cat
+@end
+@implementation Cat
+@end
+@interface $decl[[Cat]] (Exte^nsion)
+- (void)meow;
+@end
+@implementation $def[[Cat]] (Extension)
+- (void)meow {}
+@end
+  )objc",
+
+  R"objc(
+@class $decl[[Foo]];
+Fo^o * getFoo() {
+  return 0;
+}
+  )objc",
+
+  R"objc(
+@class Foo;
+@interface $decl[[Foo]]
+@end
+Fo^o * getFoo() {
+  return 0;
+}
+  )objc",
+
+  R"objc(
+@class Foo;
+@interface $decl[[Foo]]
+@end
+@implementation $def[[Foo]]
+@end
+Fo^o * getFoo() {
+  return 0;
+}
+  )objc"};
   for (const char *Test : Tests) {
 Annotations T(Test);
 llvm::Optional WantDecl;
@@ -692,6 +742,7 @@
 // FIXME: Auto-completion in a template requires disabling delayed template
 // parsing.
 TU.ExtraArgs.push_back("-fno-delayed-template-parsing");
+TU.ExtraArgs.push_back("-xobjective-c++");
 
 auto AST = TU.build();
 auto Results = locateSymbolAt(AST, T.point());
@@ -709,6 +760,131 @@
   }
 }
 
+TEST(LocateSymbol, AllMulti) {
+  // Ranges in tests:
+  //   $declN is the declaration location
+  //   $defN is the definition location (if absent, symbol has no definition)
+  //
+  // NOTE:
+  //   N starts at 0.
+  //   Due to limitations in clang's Annotations, you can't annotate the same
+  //   text with multiple ranges, e.g. `$def0$def1[[Foo]]` is invalid.
+  struct ExpectedRanges {
+Range WantDecl;
+llvm::Optional WantDef;
+  };
+  const char *Tests[] = {
+  R"objc(
+  @interface $decl0[[Cat]]
+  @end
+  @implementation $def0[[Cat]]
+  @end
+  @interface $decl1[[Ca^t]] (Extension)
+  - (void)meow;
+  @end
+  @implementation $def1[[Cat]] (Extension)
+  - (void)meow {}
+  @end
+)objc",
+
+  R"objc(
+  @interface $decl0[[Cat]]
+  @end
+  @implementation $def0[[Cat]]
+  @end
+  @interface $decl1[[Cat]] (Extension)
+  - (void)meow;
+  @end
+  @implementation $def1[[Ca^t]] (Extension)
+  - (void)meow {}
+  @end
+)objc",
+  };
+  for (const char *Test : Tests) {
+Annotations T(Test);
+std::vector Ranges;
+for (int i = 0; true; i++) {
+  bool HasDecl = !T.ranges("decl" + std::to_string(i)).empty();
+  bool HasDef = !T.ranges("def" + std::to_string(i)).empty();
+  if (!HasDecl && !HasDef)
+break;
+  ExpectedRanges Range;
+  if (HasDecl)
+Range.WantDecl = T.range("decl" + std::to_string(i));
+  if (HasDef)
+Range.WantDef = T.range("def" + std::to_string(i));
+  Ranges.push_back(Range);
+}
+
+TestTU TU;
+TU.Code = std::string(T.code());
+TU.ExtraArgs.push_back("-xobjective-c++");
+
+auto AST = TU.build();
+auto Results = locateSymbolAt(AST, T.point());
+
+ASSERT_THAT(Results, ::testing::SizeIs(Ranges.size())) << Test;
+for (size_t i = 0; i < Ranges.size(); i++) {
+  EXPECT_EQ(Results[i].PreferredDeclaration.range, Ranges[i].WantDecl)
+  << "(i = " << i << ")" << Test;
+  llvm::Optional GotDef;
+  if (Results[i].Definition)
+GotDef = Results[i].Definition->range;
+  EXPECT_EQ(GotDef, Ranges[i].WantDef) << "(i = " << i << ")" << Test;
+}
+  }
+}
+
+TEST(LocateSymbol, MultipleDeclsWithSameDefinition) {
+  // Ranges in tests:
+  //   $def is the shared definition location
+  //   $declN is one of the declaration locations
+  //
+  // NOTE:
+  //   N starts at 0.
+  const char *Tests[] = {
+  R"objc(
+  @interface $decl0[[Cat]]
+  @end
+  @interface $decl1[[Ca^t]] ()
+  - (void)meow;
+  @end
+  @implementation $def[[Cat]]
+  - (void)meow {}
+  @end
+)objc",
+  };
+  for (const char *Test : Tests) {
+

[PATCH] D83501: [clangd][ObjC] Improve xrefs for protocols and classes

2020-07-13 Thread David Goldman via Phabricator via cfe-commits
dgoldman marked 4 inline comments as done.
dgoldman added a comment.

In D83501#2146892 , @sammccall wrote:

> In D83501#2144283 , @dgoldman wrote:
>
> > Looking further into the indexing support, I've questions:
> >
> > - How `targetDecl` should behave for these objc container types
>
>
> (Hmm, targetDecl doesn't seem to canonicalize decls anywhere, which might be 
> a bug, but it's unrelated to objc)
>
> The main thing is that AIUI @implementation is one thing, as far as clang's 
> concerned, while @class+@interface are another.
>  i.e. getCanonicalDecl() and USR generation both split them into equivalence 
> classes {@implementation} and {@class, @interface}. Is that right?


I believe they share the same USR but besides that, yes that's correct.

> In that case the thing targetDecl needs to do is "jump" from the 
> implementation to the interface, because we're pretending they're the same 
> decl.
>  It doesn't need to jump from the @class to the @interface, semantic 
> canonicalization doesn't belong there. (In fact it may need to do the 
> opposite, since targetDecl might be relying on implicitly canonicalizing with 
> clang's semantics).

SGTM, done.

>> - Similarly for SymbolCollector (guessing in 
>> `SymbolCollector::handleDeclOccurrence` ?)
> 
> Right - this is where most of the real canonicalization happens.
>  You need to ensure that:
> 
> - isPreferred is true for @interface, so that when we see both @class and 
> @interface we'll take the latter as our preferred declaration
> - addDefinition gets called for @implementation, so that the definition 
> location is set correctly. Also the SymbolID used in this case must be based 
> on the USR of the interface, so we're considering them a single symbol. 
> (Either addDeclaration should not be called in this case, or it should be 
> called with the @implementation again somehow). I think that should be 
> enough...

Gone ahead and implemented this. It seems OK. I think the only thing that might 
be missing here is class extensions:

  @interface Foo
  @end
  @interface Foo ()
  - (void)bar;
  @end
  @implementation Foo
  - (void)bar {}
  @end

I implemented goto-definition from Foo() --> Foo impl in Xrefs, on the 
symbolcollector side I don't think there's anything to do?




Comment at: clang-tools-extra/clangd/XRefs.cpp:276
getDeclAtPosition(AST, CurLoc, Relations, NodeKind)) {
 // Special case: void foo() ^override: jump to the overridden method.
 if (const auto *CMD = llvm::dyn_cast(D)) {

sammccall wrote:
> dgoldman wrote:
> > sammccall wrote:
> > > dgoldman wrote:
> > > > sammccall wrote:
> > > > > dgoldman wrote:
> > > > > > Think it would make sense to special case ObjCInterfaceDecl here to 
> > > > > > get at both the interface definition + implementation if available?
> > > > > Rather than returning both results, I think it's more consistent to 
> > > > > return them as a declaration/definition pair.
> > > > > 
> > > > > (This means special-casing ObjCImplDecl in namedDecl or at least 
> > > > > getDeclAsPosition, so you always end up with the ObjCInterfaceDecl 
> > > > > instead)
> > > > Whoops, meant to comment here but it was lost. I'm not sure what you 
> > > > meant here. Should this be done here inside the for loop or in 
> > > > getDeclAtPosition?
> > > > 
> > > > Are you saying that given:
> > > > 
> > > > ```
> > > > @interface Foo // A
> > > > @end
> > > > @implementation Foo // B
> > > > @end
> > > > ```
> > > > B --> A here
> > > > 
> > > > and similarly
> > > > 
> > > > ```
> > > > @interface Foo // A
> > > > @end
> > > > @interface Foo (Ext) // B
> > > > @end
> > > > @implementation Foo (Ext) // C
> > > > @end
> > > > ```
> > > > B --> A
> > > > C --> B (and A? it's unclear how this should map over, e.g. maybe Foo 
> > > > loc --> A, Ext --> B)
> > > In the first example, selecting either A or B should yield one 
> > > LocatedSymbol with {Decl=A, Def=B}. This shouldn't require any 
> > > special-casing.
> > > 
> > > The second example is very similar to template specialization, with 
> > > exceptions:
> > >  - there's always a Decl/Def pair you may want to navigate between, 
> > > whereas in templates there rarely is, so we have ambiguity
> > >  - there's no AST like there is for template names and args, just a bag 
> > > of tokens
> > > 
> > > I'd suggest, given `@interface Foo (Ext)`:
> > >  - we produce a LocatedSymbol with {Decl=@interface Foo(Ext), 
> > > Def=@implementation  Foo(Ext)} - this is the default behavior
> > >  - if the cursor is exactly on the token `Foo`, we also produce a 
> > > LocatedSymbol with {Decl=@interface Foo, Def=@implementation Foo} - this 
> > > is similar to the template special case
> > >  - if the cursor is exactly on the token Ext... are categories 
> > > explicitly/separately declared anywhere? I guess not. If they are, we 
> > > could special case this too.

[PATCH] D83726: Fix a missing update that C compiles default to gnu17.

2020-07-13 Thread Nick Desaulniers via Phabricator via cfe-commits
nickdesaulniers accepted this revision.
nickdesaulniers added a comment.
This revision is now accepted and ready to land.

bah!

  $ find . -name \*.rst | xargs grep -n gnu11
  ./clang/docs/UsersManual.rst:2462:The supported modes for C are c89, gnu89, 
c99, gnu99, c11, gnu11, c17, gnu17,
  ./clang/docs/CommandGuide/clang.rst:136:  | ``gnu11``
  ./clang/docs/CommandGuide/clang.rst:149: The default C language standard is 
``gnu11``, except on PS4, where it is
  ./clang/docs/ReleaseNotes.rst:165:  upgraded from gnu11 to gnu17.
  ./clang/docs/LanguageExtensions.rst:1019:features are enabled with the 
``-std=c11`` or ``-std=gnu11`` option when

Thanks for cleaning up my mess. The rest of these instance look fine to me.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D83726



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


[PATCH] D83726: Fix a missing update that C compiles default to gnu17.

2020-07-13 Thread Stephen Hines via Phabricator via cfe-commits
srhines created this revision.
srhines added a reviewer: nickdesaulniers.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

https://reviews.llvm.org/D75383 switched the C default to gnu17, but
missed this instance.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D83726

Files:
  clang/docs/CommandGuide/clang.rst


Index: clang/docs/CommandGuide/clang.rst
===
--- clang/docs/CommandGuide/clang.rst
+++ clang/docs/CommandGuide/clang.rst
@@ -146,7 +146,7 @@
 
ISO C 2017 with GNU extensions
 
- The default C language standard is ``gnu11``, except on PS4, where it is
+ The default C language standard is ``gnu17``, except on PS4, where it is
  ``gnu99``.
 
  Supported values for the C++ language are:


Index: clang/docs/CommandGuide/clang.rst
===
--- clang/docs/CommandGuide/clang.rst
+++ clang/docs/CommandGuide/clang.rst
@@ -146,7 +146,7 @@
 
ISO C 2017 with GNU extensions
 
- The default C language standard is ``gnu11``, except on PS4, where it is
+ The default C language standard is ``gnu17``, except on PS4, where it is
  ``gnu99``.
 
  Supported values for the C++ language are:
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D83592: [Parser] Add comment to skipped regions

2020-07-13 Thread Zequan Wu via Phabricator via cfe-commits
zequanwu marked an inline comment as done.
zequanwu added a comment.

In D83592#2148376 , @vsk wrote:

> taking advantage of the existing CommentHandler interface? To simplify 
> things, we can add a static method like 
> 'CoverageMappingGen::setupPreprocessorCallbacks(Preprocessor &)' and call 
> that from CodeGenAction::CreateASTConsumer.


Sorry, I don't quite understand this. I am already using `ActionCommentHandler` 
to handle this one inside `HandleComment`.




Comment at: llvm/lib/ProfileData/Coverage/CoverageMappingWriter.cpp:152
+static MutableArrayRef
+mergeSkippedRegions(MutableArrayRef MappingRegions) {
+  SmallVector MergedRegions;

vsk wrote:
> This seems like a lot of complexity to add to handle a narrow case. Is it 
> necessary to merge skipped regions early in the process? Note that llvm's 
> SegmentBuilder takes care of merging regions at the very end.
Merging at here is to avoid duplicate output for option 
`-dump-coverage-mapping`. Like the following example to avoid `Skipped,File 0, 
2:3 -> 4:9 = 0` and `Skipped,File 0, 2:15 -> 2:25 = 0` to be outputted at the 
same time. They should be merged into 1 region `Skipped,File 0, 2:3 -> 4:9 = 0`
```
File 0, 1:12 -> 6:2 = #0
 Skipped,File 0, 2:3 -> 4:9 = 0
 Skipped,File 0, 2:15 -> 2:25 = 0
   1|  1|int main() {
   2|   |  #ifdef TEST // comment
   3|   |  int x = 1;
   4|   |  #endif
   5|  1|  return 0;
   6|  1|}
```
So, we need to do it early.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D83592



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


[PATCH] D83723: [OpenMP] Generalize CGOpenMPRuntimeNVPTX as CGOpenMPRuntimeGPU

2020-07-13 Thread Jon Chesterfield via Phabricator via cfe-commits
JonChesterfield added a comment.

This is indeed the direction I had in mind. Broad strokes look right. I 
probably wouldn't notice an accidental change amidst the whitespace reshuffle. 
Very happy to read through line by line if you can split the whitespace change 
out.




Comment at: clang/lib/CodeGen/CGOpenMPRuntimeGPU.h:377
   /// Choose a default value for the dist_schedule clause.
-  void getDefaultDistScheduleAndChunk(CodeGenFunction ,
-  const OMPLoopDirective , OpenMPDistScheduleClauseKind ,
-  llvm::Value *) const override;
+  void
+  getDefaultDistScheduleAndChunk(CodeGenFunction ,

It's worth avoiding whitespace-only changes in a large diff, even when it 
brings the code in line with clang-format's rules. Signal to noise is 
challenging enough without it.

Please would you leave the whitespace-only changes out? I usually open the diff 
in a friendly GUI and eyeball each segment to see if it can be dropped.

Feel free to fix the whitespace before or after.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D83723



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


[PATCH] D83616: [clang] Add 'override' to virtual function overrides generated by ClangAttrEmitter

2020-07-13 Thread Logan Smith via Phabricator via cfe-commits
logan-5 added a comment.

Thanks! I would appreciate any help committing this.

I have a few of these kinds of NFC `override` patches in flight, and I'd love 
to be able to commit them myself and not bother people. I wonder what the 
process of gaining commit access looks like? I've been a contributor for about 
a year, with maybe a dozen or so patches landed.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D83616



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


[PATCH] D83494: [libFuzzer] Link libFuzzer's own interceptors when other compiler runtimes are not linked.

2020-07-13 Thread Matt Morehouse via Phabricator via cfe-commits
morehouse added inline comments.



Comment at: compiler-rt/lib/fuzzer/FuzzerInterceptors.cpp:14
+
+#if LIBFUZZER_LINUX
+

We should include FuzzerDefs.h to use this, not FuzzerBuiltins.h.



Comment at: compiler-rt/lib/fuzzer/FuzzerInterceptors.cpp:25
+
+typedef unsigned long uptr;
+

Any reason not to use `uintptr_t` instead?



Comment at: compiler-rt/lib/fuzzer/FuzzerInterceptors.cpp:41
+// We don't want to intercept the wrapper and have it point to itself.
+if ((uptr)addr == wrapper_addr)
+  addr = nullptr;

Nit:  I think we should prefer C++ constructs, so `reinterpret_cast` 
here.



Comment at: compiler-rt/lib/fuzzer/FuzzerInterceptors.cpp:116
+
+extern "C++" ATTRIBUTE_INTERFACE char *strstr(char *s1, const char *s2) {
+  char *result = REAL(strstr)(s1, s2);

Why `extern "C++"`?  I don't think we want that here.



Comment at: compiler-rt/lib/fuzzer/FuzzerInterceptors.cpp:123
+
+extern "C++" ATTRIBUTE_INTERFACE char *strcasestr(char *s1, const char *s2) {
+  char *result = REAL(strcasestr)(s1, s2);

Also why `extern "C++"` here?



Comment at: compiler-rt/lib/fuzzer/FuzzerInterceptors.cpp:140
+  REAL(memcmp) =
+  reinterpret_cast(GetFuncAddr("memcmp", (uptr)));
+  REAL(strncmp) =

Nit:  `reinterpret_cast()`



Comment at: compiler-rt/lib/fuzzer/FuzzerInterceptors.cpp:159
+*__local_fuzzer_preinit)(void) = __fuzzer_init;
+}
+

Nit: Please add this comment:
```
} // extern "C"
```



Comment at: compiler-rt/test/fuzzer/no-asan-strstr.test:5
+CHECK: BINGO
+

Since these "no-asan" cases are pretty small, can we just add them to the 
existing `*cmp` tests?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D83494



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


[PATCH] D83717: [clang-tidy] Add check fo SEI CERT item ENV32-C

2020-07-13 Thread Endre Fülöp via Phabricator via cfe-commits
gamesh411 updated this revision to Diff 277590.
gamesh411 added a comment.

mention iterator header


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D83717

Files:
  clang-tools-extra/clang-tidy/cert/CERTTidyModule.cpp
  clang-tools-extra/clang-tidy/cert/CMakeLists.txt
  clang-tools-extra/clang-tidy/cert/ExitHandlerCheck.cpp
  clang-tools-extra/clang-tidy/cert/ExitHandlerCheck.h
  clang-tools-extra/docs/ReleaseNotes.rst
  clang-tools-extra/docs/clang-tidy/checks/cert-env32-c.rst
  clang-tools-extra/docs/clang-tidy/checks/list.rst
  clang-tools-extra/test/clang-tidy/checkers/cert-env32-c.c
  llvm/utils/gn/secondary/clang-tools-extra/clang-tidy/cert/BUILD.gn

Index: llvm/utils/gn/secondary/clang-tools-extra/clang-tidy/cert/BUILD.gn
===
--- llvm/utils/gn/secondary/clang-tools-extra/clang-tidy/cert/BUILD.gn
+++ llvm/utils/gn/secondary/clang-tools-extra/clang-tidy/cert/BUILD.gn
@@ -19,6 +19,7 @@
 "CommandProcessorCheck.cpp",
 "DefaultOperatorNewAlignmentCheck.cpp",
 "DontModifyStdNamespaceCheck.cpp",
+"ExitHandlerCheck.cpp",
 "FloatLoopCounter.cpp",
 "LimitedRandomnessCheck.cpp",
 "MutatingCopyCheck.cpp",
Index: clang-tools-extra/test/clang-tidy/checkers/cert-env32-c.c
===
--- /dev/null
+++ clang-tools-extra/test/clang-tidy/checkers/cert-env32-c.c
@@ -0,0 +1,256 @@
+// RUN: %check_clang_tidy %s cert-env32-c %t
+
+// --
+// EXIT FUNCTIONS
+// --
+
+// No handlers are invoked when _Exit is called.
+void _Exit(int __status);
+
+// Handlers registered by atexit are invoked in reverse order when exit is
+// called.
+void exit(int __status);
+
+// Handlers registered by at_quick_exit are invoked in reverse order when
+// quick_exit is called.
+void quick_exit(int __status);
+
+// 
+// HANDLER REGISTRATION
+// 
+
+// Register handlers to run when exit is called.
+int atexit(void (*__func)(void));
+
+// Register handlers to run when exit is called.
+int at_quick_exit(void (*__func)(void));
+
+// --
+// Setjmp/longjmp
+// --
+// C99 requires jmp_buf to be an array type.
+typedef int jmp_buf[1];
+int setjmp(jmp_buf);
+void longjmp(jmp_buf, int);
+
+// Compliant solutions
+
+void cleanup1() {
+  // do cleanup
+}
+
+void cleanup2() {
+  // do cleanup
+}
+
+void test_atexit_single_compliant() {
+  (void)atexit(cleanup1);
+}
+
+void test_atexit_multiple_compliant() {
+  (void)atexit(cleanup1);
+  (void)atexit(cleanup2);
+}
+
+void test_at_quick_exit_single_compliant() {
+  (void)at_quick_exit(cleanup1);
+}
+
+void test_at_quick_exit_multiple_compliant() {
+  (void)at_quick_exit(cleanup1);
+  (void)at_quick_exit(cleanup2);
+}
+
+// Non-compliant solutions calling _Exit
+
+void call__Exit() {
+  _Exit(0);
+}
+
+void call_call__Exit() {
+  call__Exit();
+}
+
+extern int unknown__Exit_flag;
+
+void call__Exit_conditionally() {
+  if (unknown__Exit_flag)
+call__Exit();
+}
+
+void call_call__Exit_conditionally() {
+  call__Exit_conditionally();
+}
+
+void test__Exit_called_directly() {
+  (void)atexit(call__Exit);
+  // CHECK-MESSAGES: :[[@LINE-1]]:9: warning: exit-handler potentially calls an exit function. Handlers should terminate by returning [cert-env32-c]
+  (void)at_quick_exit(call__Exit);
+  // CHECK-MESSAGES: :[[@LINE-1]]:9: warning: exit-handler potentially calls an exit function. Handlers should terminate by returning [cert-env32-c]
+};
+
+void test__Exit_called_indirectly() {
+  (void)atexit(call_call__Exit);
+  // CHECK-MESSAGES: :[[@LINE-1]]:9: warning: exit-handler potentially calls an exit function. Handlers should terminate by returning [cert-env32-c]
+  (void)at_quick_exit(call_call__Exit);
+  // CHECK-MESSAGES: :[[@LINE-1]]:9: warning: exit-handler potentially calls an exit function. Handlers should terminate by returning [cert-env32-c]
+};
+
+void test_conditional__Exit_called_directly() {
+  (void)atexit(call__Exit_conditionally);
+  // CHECK-MESSAGES: :[[@LINE-1]]:9: warning: exit-handler potentially calls an exit function. Handlers should terminate by returning [cert-env32-c]
+  (void)at_quick_exit(call__Exit_conditionally);
+  // CHECK-MESSAGES: :[[@LINE-1]]:9: warning: exit-handler potentially calls an exit function. Handlers should terminate by returning [cert-env32-c]
+};
+
+void test_conditional__Exit_called_indirectly() {
+  (void)atexit(call_call__Exit_conditionally);
+  // CHECK-MESSAGES: :[[@LINE-1]]:9: warning: exit-handler potentially calls an exit function. Handlers should terminate by returning [cert-env32-c]
+  (void)at_quick_exit(call_call__Exit_conditionally);
+  // CHECK-MESSAGES: :[[@LINE-1]]:9: warning: exit-handler potentially calls an exit function. Handlers should terminate by returning [cert-env32-c]
+};
+
+// Non-compliant solutions calling exit
+
+void 

[PATCH] D83717: [clang-tidy] Add check fo SEI CERT item ENV32-C

2020-07-13 Thread Endre Fülöp via Phabricator via cfe-commits
gamesh411 updated this revision to Diff 277588.
gamesh411 added a comment.

use std::copy algorithm
polish


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D83717

Files:
  clang-tools-extra/clang-tidy/cert/CERTTidyModule.cpp
  clang-tools-extra/clang-tidy/cert/CMakeLists.txt
  clang-tools-extra/clang-tidy/cert/ExitHandlerCheck.cpp
  clang-tools-extra/clang-tidy/cert/ExitHandlerCheck.h
  clang-tools-extra/docs/ReleaseNotes.rst
  clang-tools-extra/docs/clang-tidy/checks/cert-env32-c.rst
  clang-tools-extra/docs/clang-tidy/checks/list.rst
  clang-tools-extra/test/clang-tidy/checkers/cert-env32-c.c
  llvm/utils/gn/secondary/clang-tools-extra/clang-tidy/cert/BUILD.gn

Index: llvm/utils/gn/secondary/clang-tools-extra/clang-tidy/cert/BUILD.gn
===
--- llvm/utils/gn/secondary/clang-tools-extra/clang-tidy/cert/BUILD.gn
+++ llvm/utils/gn/secondary/clang-tools-extra/clang-tidy/cert/BUILD.gn
@@ -19,6 +19,7 @@
 "CommandProcessorCheck.cpp",
 "DefaultOperatorNewAlignmentCheck.cpp",
 "DontModifyStdNamespaceCheck.cpp",
+"ExitHandlerCheck.cpp",
 "FloatLoopCounter.cpp",
 "LimitedRandomnessCheck.cpp",
 "MutatingCopyCheck.cpp",
Index: clang-tools-extra/test/clang-tidy/checkers/cert-env32-c.c
===
--- /dev/null
+++ clang-tools-extra/test/clang-tidy/checkers/cert-env32-c.c
@@ -0,0 +1,256 @@
+// RUN: %check_clang_tidy %s cert-env32-c %t
+
+// --
+// EXIT FUNCTIONS
+// --
+
+// No handlers are invoked when _Exit is called.
+void _Exit(int __status);
+
+// Handlers registered by atexit are invoked in reverse order when exit is
+// called.
+void exit(int __status);
+
+// Handlers registered by at_quick_exit are invoked in reverse order when
+// quick_exit is called.
+void quick_exit(int __status);
+
+// 
+// HANDLER REGISTRATION
+// 
+
+// Register handlers to run when exit is called.
+int atexit(void (*__func)(void));
+
+// Register handlers to run when exit is called.
+int at_quick_exit(void (*__func)(void));
+
+// --
+// Setjmp/longjmp
+// --
+// C99 requires jmp_buf to be an array type.
+typedef int jmp_buf[1];
+int setjmp(jmp_buf);
+void longjmp(jmp_buf, int);
+
+// Compliant solutions
+
+void cleanup1() {
+  // do cleanup
+}
+
+void cleanup2() {
+  // do cleanup
+}
+
+void test_atexit_single_compliant() {
+  (void)atexit(cleanup1);
+}
+
+void test_atexit_multiple_compliant() {
+  (void)atexit(cleanup1);
+  (void)atexit(cleanup2);
+}
+
+void test_at_quick_exit_single_compliant() {
+  (void)at_quick_exit(cleanup1);
+}
+
+void test_at_quick_exit_multiple_compliant() {
+  (void)at_quick_exit(cleanup1);
+  (void)at_quick_exit(cleanup2);
+}
+
+// Non-compliant solutions calling _Exit
+
+void call__Exit() {
+  _Exit(0);
+}
+
+void call_call__Exit() {
+  call__Exit();
+}
+
+extern int unknown__Exit_flag;
+
+void call__Exit_conditionally() {
+  if (unknown__Exit_flag)
+call__Exit();
+}
+
+void call_call__Exit_conditionally() {
+  call__Exit_conditionally();
+}
+
+void test__Exit_called_directly() {
+  (void)atexit(call__Exit);
+  // CHECK-MESSAGES: :[[@LINE-1]]:9: warning: exit-handler potentially calls an exit function. Handlers should terminate by returning [cert-env32-c]
+  (void)at_quick_exit(call__Exit);
+  // CHECK-MESSAGES: :[[@LINE-1]]:9: warning: exit-handler potentially calls an exit function. Handlers should terminate by returning [cert-env32-c]
+};
+
+void test__Exit_called_indirectly() {
+  (void)atexit(call_call__Exit);
+  // CHECK-MESSAGES: :[[@LINE-1]]:9: warning: exit-handler potentially calls an exit function. Handlers should terminate by returning [cert-env32-c]
+  (void)at_quick_exit(call_call__Exit);
+  // CHECK-MESSAGES: :[[@LINE-1]]:9: warning: exit-handler potentially calls an exit function. Handlers should terminate by returning [cert-env32-c]
+};
+
+void test_conditional__Exit_called_directly() {
+  (void)atexit(call__Exit_conditionally);
+  // CHECK-MESSAGES: :[[@LINE-1]]:9: warning: exit-handler potentially calls an exit function. Handlers should terminate by returning [cert-env32-c]
+  (void)at_quick_exit(call__Exit_conditionally);
+  // CHECK-MESSAGES: :[[@LINE-1]]:9: warning: exit-handler potentially calls an exit function. Handlers should terminate by returning [cert-env32-c]
+};
+
+void test_conditional__Exit_called_indirectly() {
+  (void)atexit(call_call__Exit_conditionally);
+  // CHECK-MESSAGES: :[[@LINE-1]]:9: warning: exit-handler potentially calls an exit function. Handlers should terminate by returning [cert-env32-c]
+  (void)at_quick_exit(call_call__Exit_conditionally);
+  // CHECK-MESSAGES: :[[@LINE-1]]:9: warning: exit-handler potentially calls an exit function. Handlers should terminate by returning [cert-env32-c]
+};
+
+// Non-compliant solutions calling exit
+

[PATCH] D83497: [PowerPC][Power10] Fix VINS* (vector insert byte/half/word) instructions to have i32 arguments.

2020-07-13 Thread Baptiste Saleil via Phabricator via cfe-commits
bsaleil accepted this revision as: bsaleil.
bsaleil added a comment.

LGTM


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D83497



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


[PATCH] D71491: [ubsan] Check implicit casts in ObjC for-in statements

2020-07-13 Thread Vedant Kumar via Phabricator via cfe-commits
This revision was not accepted when it landed; it landed in state "Needs 
Review".
This revision was automatically updated to reflect the committed changes.
Closed by commit rG8c4a65b9b2ca: [ubsan] Check implicit casts in ObjC for-in 
statements (authored by vsk).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D71491

Files:
  clang/docs/UndefinedBehaviorSanitizer.rst
  clang/include/clang/Basic/Sanitizers.def
  clang/lib/CodeGen/CGObjC.cpp
  clang/lib/CodeGen/CodeGenFunction.h
  clang/lib/Driver/SanitizerArgs.cpp
  clang/lib/Driver/ToolChains/Darwin.cpp
  clang/test/CodeGenObjC/for-in.m
  compiler-rt/lib/ubsan/ubsan_checks.inc
  compiler-rt/lib/ubsan/ubsan_handlers.cpp
  compiler-rt/lib/ubsan/ubsan_handlers.h
  compiler-rt/lib/ubsan/ubsan_value.cpp
  compiler-rt/lib/ubsan/ubsan_value.h
  compiler-rt/lib/ubsan_minimal/ubsan_minimal_handlers.cpp
  compiler-rt/test/ubsan/TestCases/Misc/objc-cast.m

Index: compiler-rt/test/ubsan/TestCases/Misc/objc-cast.m
===
--- /dev/null
+++ compiler-rt/test/ubsan/TestCases/Misc/objc-cast.m
@@ -0,0 +1,27 @@
+// REQUIRES: darwin
+//
+// RUN: %clang -framework Foundation -fsanitize=objc-cast %s -O1 -o %t
+// RUN: %run %t 2>&1 | FileCheck %s
+//
+// RUN: %clang -framework Foundation -fsanitize=objc-cast -fno-sanitize-recover=objc-cast %s -O1 -o %t.trap
+// RUN: not %run %t.trap 2>&1 | FileCheck %s
+
+#include 
+
+int main() {
+  NSArray *arrayOfInt = [NSArray arrayWithObjects:@1, @2, @3, (void *)0];
+  // CHECK: objc-cast.m:[[@LINE+1]]:{{.*}}: runtime error: invalid ObjC cast, object is a '__NSCFNumber', but expected a 'NSString'
+  for (NSString *str in arrayOfInt) {
+NSLog(@"%@", str);
+  }
+
+  NSArray *arrayOfStr = [NSArray arrayWithObjects:@"a", @"b", @"c", (void *)0];
+  for (NSString *str in arrayOfStr) {
+NSLog(@"%@", str);
+  }
+
+  // The diagnostic should only be printed once.
+  // CHECK-NOT: runtime error
+
+  return 0;
+}
Index: compiler-rt/lib/ubsan_minimal/ubsan_minimal_handlers.cpp
===
--- compiler-rt/lib/ubsan_minimal/ubsan_minimal_handlers.cpp
+++ compiler-rt/lib/ubsan_minimal/ubsan_minimal_handlers.cpp
@@ -109,6 +109,7 @@
 HANDLER(float_cast_overflow, "float-cast-overflow")
 HANDLER(load_invalid_value, "load-invalid-value")
 HANDLER(invalid_builtin, "invalid-builtin")
+HANDLER(invalid_objc_cast, "invalid-objc-cast")
 HANDLER(function_type_mismatch, "function-type-mismatch")
 HANDLER(implicit_conversion, "implicit-conversion")
 HANDLER(nonnull_arg, "nonnull-arg")
Index: compiler-rt/lib/ubsan/ubsan_value.h
===
--- compiler-rt/lib/ubsan/ubsan_value.h
+++ compiler-rt/lib/ubsan/ubsan_value.h
@@ -135,6 +135,9 @@
 /// \brief An opaque handle to a value.
 typedef uptr ValueHandle;
 
+/// Returns the class name of the given ObjC object, or null if the name
+/// cannot be found.
+const char *getObjCClassName(ValueHandle Pointer);
 
 /// \brief Representation of an operand value provided by the instrumented code.
 ///
Index: compiler-rt/lib/ubsan/ubsan_value.cpp
===
--- compiler-rt/lib/ubsan/ubsan_value.cpp
+++ compiler-rt/lib/ubsan/ubsan_value.cpp
@@ -16,9 +16,57 @@
 #include "ubsan_value.h"
 #include "sanitizer_common/sanitizer_common.h"
 #include "sanitizer_common/sanitizer_libc.h"
+#include "sanitizer_common/sanitizer_mutex.h"
+
+// TODO(dliew): Prefer '__APPLE__' here over 'SANITIZER_MAC', as the latter is
+// unclear. rdar://58124919 tracks using a more obviously portable guard.
+#if defined(__APPLE__)
+#include 
+#endif
 
 using namespace __ubsan;
 
+typedef const char *(*ObjCGetClassNameTy)(void *);
+
+const char *__ubsan::getObjCClassName(ValueHandle Pointer) {
+#if defined(__APPLE__)
+  // We need to query the ObjC runtime for some information, but do not want
+  // to introduce a static dependency from the ubsan runtime onto ObjC. Try to
+  // grab a handle to the ObjC runtime used by the process.
+  static bool AttemptedDlopen = false;
+  static void *ObjCHandle = nullptr;
+  static void *ObjCObjectGetClassName = nullptr;
+
+  // Prevent threads from racing to dlopen().
+  static __sanitizer::StaticSpinMutex Lock;
+  {
+__sanitizer::SpinMutexLock Guard();
+
+if (!AttemptedDlopen) {
+  ObjCHandle = dlopen(
+  "/usr/lib/libobjc.A.dylib",
+  RTLD_LAZY // Only bind symbols when used.
+  | RTLD_LOCAL  // Only make symbols available via the handle.
+  | RTLD_NOLOAD // Do not load the dylib, just grab a handle if the
+// image is already loaded.
+  | RTLD_FIRST  // Only search the image pointed-to by the handle.
+  );
+  AttemptedDlopen = true;
+  if (!ObjCHandle)
+return nullptr;
+  

[clang] 8c4a65b - [ubsan] Check implicit casts in ObjC for-in statements

2020-07-13 Thread Vedant Kumar via cfe-commits

Author: Vedant Kumar
Date: 2020-07-13T15:11:18-07:00
New Revision: 8c4a65b9b2ca6961139beca92de37eea479f00fa

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

LOG: [ubsan] Check implicit casts in ObjC for-in statements

Check that the implicit cast from `id` used to construct the element
variable in an ObjC for-in statement is valid.

This check is included as part of a new `objc-cast` sanitizer, outside
of the main 'undefined' group, as (IIUC) the behavior it's checking for
is not technically UB.

The check can be extended to cover other kinds of invalid casts in ObjC.

Partially addresses: rdar://12903059, rdar://9542496

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

Added: 
compiler-rt/test/ubsan/TestCases/Misc/objc-cast.m

Modified: 
clang/docs/UndefinedBehaviorSanitizer.rst
clang/include/clang/Basic/Sanitizers.def
clang/lib/CodeGen/CGObjC.cpp
clang/lib/CodeGen/CodeGenFunction.h
clang/lib/Driver/SanitizerArgs.cpp
clang/lib/Driver/ToolChains/Darwin.cpp
clang/test/CodeGenObjC/for-in.m
compiler-rt/lib/ubsan/ubsan_checks.inc
compiler-rt/lib/ubsan/ubsan_handlers.cpp
compiler-rt/lib/ubsan/ubsan_handlers.h
compiler-rt/lib/ubsan/ubsan_value.cpp
compiler-rt/lib/ubsan/ubsan_value.h
compiler-rt/lib/ubsan_minimal/ubsan_minimal_handlers.cpp

Removed: 




diff  --git a/clang/docs/UndefinedBehaviorSanitizer.rst 
b/clang/docs/UndefinedBehaviorSanitizer.rst
index 0a27810150db..76676dfce95b 100644
--- a/clang/docs/UndefinedBehaviorSanitizer.rst
+++ b/clang/docs/UndefinedBehaviorSanitizer.rst
@@ -127,6 +127,10 @@ Available checks are:
  is annotated with ``_Nonnull``.
   -  ``-fsanitize=nullability-return``: Returning null from a function with
  a return type annotated with ``_Nonnull``.
+  -  ``-fsanitize=objc-cast``: Invalid implicit cast of an ObjC object pointer
+ to an incompatible type. This is often unintentional, but is not undefined
+ behavior, therefore the check is not a part of the ``undefined`` group.
+ Currently only supported on Darwin.
   -  ``-fsanitize=object-size``: An attempt to potentially use bytes which
  the optimizer can determine are not part of the object being accessed.
  This will also detect some types of undefined behavior that may not

diff  --git a/clang/include/clang/Basic/Sanitizers.def 
b/clang/include/clang/Basic/Sanitizers.def
index 0037cc2146f2..2912bdd44b2d 100644
--- a/clang/include/clang/Basic/Sanitizers.def
+++ b/clang/include/clang/Basic/Sanitizers.def
@@ -156,6 +156,8 @@ SANITIZER_GROUP("implicit-integer-arithmetic-value-change",
 ImplicitIntegerArithmeticValueChange,
 ImplicitIntegerSignChange | ImplicitSignedIntegerTruncation)
 
+SANITIZER("objc-cast", ObjCCast)
+
 // FIXME:
 //SANITIZER_GROUP("implicit-integer-conversion", ImplicitIntegerConversion,
 //ImplicitIntegerArithmeticValueChange |

diff  --git a/clang/lib/CodeGen/CGObjC.cpp b/clang/lib/CodeGen/CGObjC.cpp
index 158a548e66c1..cd2b84f5dd20 100644
--- a/clang/lib/CodeGen/CGObjC.cpp
+++ b/clang/lib/CodeGen/CGObjC.cpp
@@ -1836,6 +1836,40 @@ void CodeGenFunction::EmitObjCForCollectionStmt(const 
ObjCForCollectionStmt ){
   llvm::Value *CurrentItem =
 Builder.CreateAlignedLoad(CurrentItemPtr, getPointerAlign());
 
+  if (SanOpts.has(SanitizerKind::ObjCCast)) {
+// Before using an item from the collection, check that the implicit cast
+// from id to the element type is valid. This is done with instrumentation
+// roughly corresponding to:
+//
+//   if (![item isKindOfClass:expectedCls]) { /* emit diagnostic */ }
+const ObjCObjectPointerType *ObjPtrTy =
+elementType->getAsObjCInterfacePointerType();
+const ObjCInterfaceType *InterfaceTy =
+ObjPtrTy ? ObjPtrTy->getInterfaceType() : nullptr;
+if (InterfaceTy) {
+  SanitizerScope SanScope(this);
+  auto  = CGM.getContext();
+  assert(InterfaceTy->getDecl() && "No decl for ObjC interface type");
+  Selector IsKindOfClassSel = GetUnarySelector("isKindOfClass", C);
+  CallArgList IsKindOfClassArgs;
+  llvm::Value *Cls =
+  CGM.getObjCRuntime().GetClass(*this, InterfaceTy->getDecl());
+  IsKindOfClassArgs.add(RValue::get(Cls), C.getObjCClassType());
+  llvm::Value *IsClass =
+  CGM.getObjCRuntime()
+  .GenerateMessageSend(*this, ReturnValueSlot(), C.BoolTy,
+   IsKindOfClassSel, CurrentItem,
+   IsKindOfClassArgs)
+  .getScalarVal();
+  llvm::Constant *StaticData[] = {
+  EmitCheckSourceLocation(S.getBeginLoc()),
+  EmitCheckTypeDescriptor(QualType(InterfaceTy, 0))};
+  EmitCheck({{IsClass, 

[PATCH] D83501: [clangd][ObjC] Improve xrefs for protocols and classes

2020-07-13 Thread David Goldman via Phabricator via cfe-commits
dgoldman updated this revision to Diff 277582.
dgoldman marked an inline comment as done.
dgoldman added a comment.

Fixes for ObjC in SymbolCollector as well as XRefs

- Make sure ObjC indexing doesn't use the forward decls and doesn't treat the 
impl as the canonical decl
- Don't treat ObjC protocol forward declarations as true declarations
- Also AddDecl for ObjC interfaces when the interface name in a category is 
selected


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D83501

Files:
  clang-tools-extra/clangd/XRefs.cpp
  clang-tools-extra/clangd/index/SymbolCollector.cpp
  clang-tools-extra/clangd/unittests/SymbolCollectorTests.cpp
  clang-tools-extra/clangd/unittests/XRefsTests.cpp

Index: clang-tools-extra/clangd/unittests/XRefsTests.cpp
===
--- clang-tools-extra/clangd/unittests/XRefsTests.cpp
+++ clang-tools-extra/clangd/unittests/XRefsTests.cpp
@@ -677,8 +677,8 @@
   )cpp",
 
   R"objc(
-@protocol $decl[[Dog]];
-@protocol $def[[Dog]]
+@protocol Dog;
+@protocol $decl[[Dog]]
 - (void)bark;
 @end
 id getDoggo() {
@@ -689,7 +689,9 @@
   R"objc(
 @interface Cat
 @end
-@interface $decl[[Ca^t]] (Extension)
+@implementation Cat
+@end
+@interface $decl[[Cat]] (Exte^nsion)
 - (void)meow;
 @end
 @implementation $def[[Cat]] (Extension)
@@ -758,6 +760,131 @@
   }
 }
 
+TEST(LocateSymbol, AllMulti) {
+  // Ranges in tests:
+  //   $declN is the declaration location
+  //   $defN is the definition location (if absent, symbol has no definition)
+  //
+  // NOTE:
+  //   N starts at 0.
+  //   Due to limitations in clang's Annotations, you can't annotate the same
+  //   text with multiple ranges, e.g. `$def0$def1[[Foo]]` is invalid.
+  struct ExpectedRanges {
+Range WantDecl;
+llvm::Optional WantDef;
+  };
+  const char *Tests[] = {
+  R"objc(
+  @interface $decl0[[Cat]]
+  @end
+  @implementation $def0[[Cat]]
+  @end
+  @interface $decl1[[Ca^t]] (Extension)
+  - (void)meow;
+  @end
+  @implementation $def1[[Cat]] (Extension)
+  - (void)meow {}
+  @end
+)objc",
+
+  R"objc(
+  @interface $decl0[[Cat]]
+  @end
+  @implementation $def0[[Cat]]
+  @end
+  @interface $decl1[[Cat]] (Extension)
+  - (void)meow;
+  @end
+  @implementation $def1[[Ca^t]] (Extension)
+  - (void)meow {}
+  @end
+)objc",
+  };
+  for (const char *Test : Tests) {
+Annotations T(Test);
+std::vector Ranges;
+for (int i = 0; true; i++) {
+  bool HasDecl = !T.ranges("decl" + std::to_string(i)).empty();
+  bool HasDef = !T.ranges("def" + std::to_string(i)).empty();
+  if (!HasDecl && !HasDef)
+break;
+  ExpectedRanges Range;
+  if (HasDecl)
+Range.WantDecl = T.range("decl" + std::to_string(i));
+  if (HasDef)
+Range.WantDef = T.range("def" + std::to_string(i));
+  Ranges.push_back(Range);
+}
+
+TestTU TU;
+TU.Code = std::string(T.code());
+TU.ExtraArgs.push_back("-xobjective-c++");
+
+auto AST = TU.build();
+auto Results = locateSymbolAt(AST, T.point());
+
+ASSERT_THAT(Results, ::testing::SizeIs(Ranges.size())) << Test;
+for (size_t i = 0; i < Ranges.size(); i++) {
+  EXPECT_EQ(Results[i].PreferredDeclaration.range, Ranges[i].WantDecl)
+  << "(i = " << i << ")" << Test;
+  llvm::Optional GotDef;
+  if (Results[i].Definition)
+GotDef = Results[i].Definition->range;
+  EXPECT_EQ(GotDef, Ranges[i].WantDef) << "(i = " << i << ")" << Test;
+}
+  }
+}
+
+TEST(LocateSymbol, MultipleDeclsWithSameDefinition) {
+  // Ranges in tests:
+  //   $def is the shared definition location
+  //   $declN is one of the declaration locations
+  //
+  // NOTE:
+  //   N starts at 0.
+  const char *Tests[] = {
+  R"objc(
+  @interface $decl0[[Cat]]
+  @end
+  @interface $decl1[[Ca^t]] ()
+  - (void)meow;
+  @end
+  @implementation $def[[Cat]]
+  - (void)meow {}
+  @end
+)objc",
+  };
+  for (const char *Test : Tests) {
+Annotations T(Test);
+std::vector DeclRanges;
+Range WantDef;
+for (int i = 0; true; i++) {
+  bool HasDecl = !T.ranges("decl" + std::to_string(i)).empty();
+  if (!HasDecl)
+break;
+  DeclRanges.push_back(T.range("decl" + std::to_string(i)));
+}
+WantDef = T.range("def");
+
+TestTU TU;
+TU.Code = std::string(T.code());
+TU.ExtraArgs.push_back("-xobjective-c++");
+
+auto AST = TU.build();
+auto Results = locateSymbolAt(AST, T.point());
+
+ASSERT_THAT(Results, ::testing::SizeIs(DeclRanges.size())) << Test;
+for (size_t i = 0; i < DeclRanges.size(); i++) {
+  EXPECT_EQ(Results[i].PreferredDeclaration.range, DeclRanges[i])
+ 

[PATCH] D83717: [clang-tidy] Add check fo SEI CERT item ENV32-C

2020-07-13 Thread Endre Fülöp via Phabricator via cfe-commits
gamesh411 updated this revision to Diff 277581.
gamesh411 added a comment.

fix test diag location changes resulting from autoformatting


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D83717

Files:
  clang-tools-extra/clang-tidy/cert/CERTTidyModule.cpp
  clang-tools-extra/clang-tidy/cert/CMakeLists.txt
  clang-tools-extra/clang-tidy/cert/ExitHandlerCheck.cpp
  clang-tools-extra/clang-tidy/cert/ExitHandlerCheck.h
  clang-tools-extra/docs/ReleaseNotes.rst
  clang-tools-extra/docs/clang-tidy/checks/cert-env32-c.rst
  clang-tools-extra/docs/clang-tidy/checks/list.rst
  clang-tools-extra/test/clang-tidy/checkers/cert-env32-c.c
  llvm/utils/gn/secondary/clang-tools-extra/clang-tidy/cert/BUILD.gn

Index: llvm/utils/gn/secondary/clang-tools-extra/clang-tidy/cert/BUILD.gn
===
--- llvm/utils/gn/secondary/clang-tools-extra/clang-tidy/cert/BUILD.gn
+++ llvm/utils/gn/secondary/clang-tools-extra/clang-tidy/cert/BUILD.gn
@@ -19,6 +19,7 @@
 "CommandProcessorCheck.cpp",
 "DefaultOperatorNewAlignmentCheck.cpp",
 "DontModifyStdNamespaceCheck.cpp",
+"ExitHandlerCheck.cpp",
 "FloatLoopCounter.cpp",
 "LimitedRandomnessCheck.cpp",
 "MutatingCopyCheck.cpp",
Index: clang-tools-extra/test/clang-tidy/checkers/cert-env32-c.c
===
--- /dev/null
+++ clang-tools-extra/test/clang-tidy/checkers/cert-env32-c.c
@@ -0,0 +1,256 @@
+// RUN: %check_clang_tidy %s cert-env32-c %t
+
+// --
+// EXIT FUNCTIONS
+// --
+
+// No handlers are invoked when _Exit is called.
+void _Exit(int __status);
+
+// Handlers registered by atexit are invoked in reverse order when exit is
+// called.
+void exit(int __status);
+
+// Handlers registered by at_quick_exit are invoked in reverse order when
+// quick_exit is called.
+void quick_exit(int __status);
+
+// 
+// HANDLER REGISTRATION
+// 
+
+// Register handlers to run when exit is called.
+int atexit(void (*__func)(void));
+
+// Register handlers to run when exit is called.
+int at_quick_exit(void (*__func)(void));
+
+// --
+// Setjmp/longjmp
+// --
+// C99 requires jmp_buf to be an array type.
+typedef int jmp_buf[1];
+int setjmp(jmp_buf);
+void longjmp(jmp_buf, int);
+
+// Compliant solutions
+
+void cleanup1() {
+  // do cleanup
+}
+
+void cleanup2() {
+  // do cleanup
+}
+
+void test_atexit_single_compliant() {
+  (void)atexit(cleanup1);
+}
+
+void test_atexit_multiple_compliant() {
+  (void)atexit(cleanup1);
+  (void)atexit(cleanup2);
+}
+
+void test_at_quick_exit_single_compliant() {
+  (void)at_quick_exit(cleanup1);
+}
+
+void test_at_quick_exit_multiple_compliant() {
+  (void)at_quick_exit(cleanup1);
+  (void)at_quick_exit(cleanup2);
+}
+
+// Non-compliant solutions calling _Exit
+
+void call__Exit() {
+  _Exit(0);
+}
+
+void call_call__Exit() {
+  call__Exit();
+}
+
+extern int unknown__Exit_flag;
+
+void call__Exit_conditionally() {
+  if (unknown__Exit_flag)
+call__Exit();
+}
+
+void call_call__Exit_conditionally() {
+  call__Exit_conditionally();
+}
+
+void test__Exit_called_directly() {
+  (void)atexit(call__Exit);
+  // CHECK-MESSAGES: :[[@LINE-1]]:9: warning: exit-handler potentially calls an exit function. Handlers should terminate by returning [cert-env32-c]
+  (void)at_quick_exit(call__Exit);
+  // CHECK-MESSAGES: :[[@LINE-1]]:9: warning: exit-handler potentially calls an exit function. Handlers should terminate by returning [cert-env32-c]
+};
+
+void test__Exit_called_indirectly() {
+  (void)atexit(call_call__Exit);
+  // CHECK-MESSAGES: :[[@LINE-1]]:9: warning: exit-handler potentially calls an exit function. Handlers should terminate by returning [cert-env32-c]
+  (void)at_quick_exit(call_call__Exit);
+  // CHECK-MESSAGES: :[[@LINE-1]]:9: warning: exit-handler potentially calls an exit function. Handlers should terminate by returning [cert-env32-c]
+};
+
+void test_conditional__Exit_called_directly() {
+  (void)atexit(call__Exit_conditionally);
+  // CHECK-MESSAGES: :[[@LINE-1]]:9: warning: exit-handler potentially calls an exit function. Handlers should terminate by returning [cert-env32-c]
+  (void)at_quick_exit(call__Exit_conditionally);
+  // CHECK-MESSAGES: :[[@LINE-1]]:9: warning: exit-handler potentially calls an exit function. Handlers should terminate by returning [cert-env32-c]
+};
+
+void test_conditional__Exit_called_indirectly() {
+  (void)atexit(call_call__Exit_conditionally);
+  // CHECK-MESSAGES: :[[@LINE-1]]:9: warning: exit-handler potentially calls an exit function. Handlers should terminate by returning [cert-env32-c]
+  (void)at_quick_exit(call_call__Exit_conditionally);
+  // CHECK-MESSAGES: :[[@LINE-1]]:9: warning: exit-handler potentially calls an exit function. Handlers should terminate by returning [cert-env32-c]
+};
+
+// Non-compliant 

[PATCH] D81442: [PowerPC] Add clang options to control MMA support

2020-07-13 Thread Baptiste Saleil via Phabricator via cfe-commits
bsaleil updated this revision to Diff 277580.
bsaleil added a comment.
Herald added subscribers: llvm-commits, hiraditya.

Also add target options with this patch


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D81442

Files:
  clang/include/clang/Driver/Options.td
  clang/lib/Basic/Targets/PPC.cpp
  clang/lib/Basic/Targets/PPC.h
  clang/test/Driver/ppc-dependent-options.cpp
  clang/test/Preprocessor/init-ppc64.c
  llvm/lib/Target/PowerPC/PPC.td
  llvm/lib/Target/PowerPC/PPCInstrPrefix.td
  llvm/lib/Target/PowerPC/PPCScheduleP9.td
  llvm/lib/Target/PowerPC/PPCSubtarget.cpp
  llvm/lib/Target/PowerPC/PPCSubtarget.h

Index: llvm/lib/Target/PowerPC/PPCSubtarget.h
===
--- llvm/lib/Target/PowerPC/PPCSubtarget.h
+++ llvm/lib/Target/PowerPC/PPCSubtarget.h
@@ -108,6 +108,7 @@
   bool HasP10Vector;
   bool HasPrefixInstrs;
   bool HasPCRelativeMemops;
+  bool HasMMA;
   bool HasFCPSGN;
   bool HasFSQRT;
   bool HasFRE, HasFRES, HasFRSQRTE, HasFRSQRTES;
@@ -267,6 +268,7 @@
   bool hasP10Vector() const { return HasP10Vector; }
   bool hasPrefixInstrs() const { return HasPrefixInstrs; }
   bool hasPCRelativeMemops() const { return HasPCRelativeMemops; }
+  bool hasMMA() const { return HasMMA; }
   bool pairedVectorMemops() const { return PairedVectorMemops; }
   bool hasMFOCRF() const { return HasMFOCRF; }
   bool hasISEL() const { return HasISEL; }
Index: llvm/lib/Target/PowerPC/PPCSubtarget.cpp
===
--- llvm/lib/Target/PowerPC/PPCSubtarget.cpp
+++ llvm/lib/Target/PowerPC/PPCSubtarget.cpp
@@ -78,6 +78,7 @@
   HasP8Crypto = false;
   HasP9Vector = false;
   HasP9Altivec = false;
+  HasMMA = false;
   HasP10Vector = false;
   HasPrefixInstrs = false;
   HasPCRelativeMemops = false;
Index: llvm/lib/Target/PowerPC/PPCScheduleP9.td
===
--- llvm/lib/Target/PowerPC/PPCScheduleP9.td
+++ llvm/lib/Target/PowerPC/PPCScheduleP9.td
@@ -43,8 +43,8 @@
   // Do not support QPX (Quad Processing eXtension), SPE (Signal Processing
   // Engine), prefixed instructions on Power 9, PC relative mem ops, or
   // instructions introduced in ISA 3.1.
-  let UnsupportedFeatures = [HasQPX, HasSPE, PrefixInstrs, PairedVectorMemops,
- PCRelativeMemops, IsISA3_1];
+  let UnsupportedFeatures = [HasQPX, HasSPE, PrefixInstrs, MMA,
+ PairedVectorMemops, PCRelativeMemops, IsISA3_1];
 
 }
 
Index: llvm/lib/Target/PowerPC/PPCInstrPrefix.td
===
--- llvm/lib/Target/PowerPC/PPCInstrPrefix.td
+++ llvm/lib/Target/PowerPC/PPCInstrPrefix.td
@@ -428,6 +428,7 @@
 def PrefixInstrs : Predicate<"Subtarget->hasPrefixInstrs()">;
 def IsISA3_1 : Predicate<"Subtarget->isISA3_1()">;
 def PairedVectorMemops : Predicate<"PPCSubTarget->pairedVectorMemops()">;
+def MMA : Predicate<"PPCSubTarget->hasMMA()">;
 
 let Predicates = [PrefixInstrs] in {
   let Interpretation64Bit = 1, isCodeGenOnly = 1 in {
Index: llvm/lib/Target/PowerPC/PPC.td
===
--- llvm/lib/Target/PowerPC/PPC.td
+++ llvm/lib/Target/PowerPC/PPC.td
@@ -241,6 +241,10 @@
   SubtargetFeature<"paired-vector-memops", "PairedVectorMemops", "true",
"32Byte load and store instructions",
[FeatureISA3_0]>;
+def FeatureMMA : SubtargetFeature<"mma", "HasMMA", "true",
+  "Enable MMA instructions",
+  [FeatureP8Vector, FeatureP9Altivec,
+   FeaturePairedVectorMemops]>;
 
 def FeaturePredictableSelectIsExpensive :
   SubtargetFeature<"predictable-select-expensive",
@@ -346,7 +350,8 @@
   // still exist with the exception of those we know are Power9 specific.
   list P10AdditionalFeatures =
 [DirectivePwr10, FeatureISA3_1, FeaturePrefixInstrs,
- FeaturePCRelativeMemops, FeatureP10Vector, FeaturePairedVectorMemops];
+ FeaturePCRelativeMemops, FeatureP10Vector, FeatureMMA,
+ FeaturePairedVectorMemops];
   list P10SpecificFeatures = [];
   list P10InheritableFeatures =
 !listconcat(P9InheritableFeatures, P10AdditionalFeatures);
Index: clang/test/Preprocessor/init-ppc64.c
===
--- clang/test/Preprocessor/init-ppc64.c
+++ clang/test/Preprocessor/init-ppc64.c
@@ -643,6 +643,7 @@
 // PPCPOWER10:#define _ARCH_PWR7 1
 // PPCPOWER10:#define _ARCH_PWR8 1
 // PPCPOWER10:#define _ARCH_PWR9 1
+// PPCPOWER10:#define __MMA__ 1
 //
 // RUN: %clang_cc1 -E -dM -ffreestanding -triple=powerpc64-none-none -target-cpu future -fno-signed-char < /dev/null | FileCheck -match-full-lines -check-prefix PPCFUTURE %s
 //
@@ -660,6 +661,10 @@
 // PPCFUTURE:#define _ARCH_PWR8 1
 // 

[PATCH] D83492: [OpenMP] Use common interface to access GPU Grid Values

2020-07-13 Thread Saiyedul Islam via Phabricator via cfe-commits
saiislam added a comment.

In D83492#2142086 , @JonChesterfield 
wrote:

> Changing to getGridValue would be useful for sharing parts of this with 
> amdgcn.
>
> The aomp toolchain handles codegen for amdgcn by adding if (isAMDGCN) to this 
> file. Until such time as tregions obsoletes this code, I think we should go 
> with layers instead of scattered conditionals.
>
> I.e. rename CGOpenMPRuntimeNVPTX to CGOpenMPRuntimeGPU which contains code 
> that is common to nvptx and amdgcn. That probably uses getGridValue() as a 
> way to abstract over minor differences. Derive CGOpenMPRuntimeAMDGCN and 
> CGOpenMPRuntimeNVPTX from CGOpenMPRuntimeGPU to implement (virtual) functions 
> which are different between the two.


Here is an implementation: D83723  . It also 
provides target specific implementation of getNVPTXWarpSize() as proof of 
concept.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D83492



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


[clang] 724afa5 - [analyzer] Inline StringSet that's defined in a header

2020-07-13 Thread Benjamin Kramer via cfe-commits

Author: Benjamin Kramer
Date: 2020-07-13T23:51:05+02:00
New Revision: 724afa5a331372ff1684f2bffa6976887490cbaf

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

LOG: [analyzer] Inline StringSet that's defined in a header

That's just asking for ODR violations. Also drop a call to lower()
that's not needed.

Added: 


Modified: 
clang/lib/StaticAnalyzer/Checkers/SmartPtr.h
clang/lib/StaticAnalyzer/Checkers/SmartPtrModeling.cpp

Removed: 




diff  --git a/clang/lib/StaticAnalyzer/Checkers/SmartPtr.h 
b/clang/lib/StaticAnalyzer/Checkers/SmartPtr.h
index 89b8965e4c9a..ec43a23e30a9 100644
--- a/clang/lib/StaticAnalyzer/Checkers/SmartPtr.h
+++ b/clang/lib/StaticAnalyzer/Checkers/SmartPtr.h
@@ -20,13 +20,6 @@ namespace clang {
 namespace ento {
 namespace smartptr {
 
-/// Set of STL smart pointer class which we are trying to model.
-const llvm::StringSet<> StdSmartPtrs = {
-"shared_ptr",
-"unique_ptr",
-"weak_ptr",
-};
-
 /// Returns true if the event call is on smart pointer.
 bool isStdSmartPtrCall(const CallEvent );
 

diff  --git a/clang/lib/StaticAnalyzer/Checkers/SmartPtrModeling.cpp 
b/clang/lib/StaticAnalyzer/Checkers/SmartPtrModeling.cpp
index 91f289078814..bcc7d4103c1c 100644
--- a/clang/lib/StaticAnalyzer/Checkers/SmartPtrModeling.cpp
+++ b/clang/lib/StaticAnalyzer/Checkers/SmartPtrModeling.cpp
@@ -73,7 +73,8 @@ bool isStdSmartPtrCall(const CallEvent ) {
 return false;
 
   if (RecordDecl->getDeclName().isIdentifier()) {
-return smartptr::StdSmartPtrs.count(RecordDecl->getName().lower());
+StringRef Name = RecordDecl->getName();
+return Name == "shared_ptr" || Name == "unique_ptr" || Name == "weak_ptr";
   }
   return false;
 }



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


[PATCH] D83722: [PowerPC] Add options to control paired vector memops support

2020-07-13 Thread Baptiste Saleil via Phabricator via cfe-commits
bsaleil created this revision.
bsaleil added reviewers: PowerPC, power-llvm-team, nemanjai, lei, saghir, amyk, 
stefanp.
bsaleil added projects: LLVM, clang, PowerPC.
Herald added subscribers: llvm-commits, cfe-commits, dang, steven.zhang, 
shchenz, hiraditya.

This patch adds frontend and backend options to enable and disable the PowerPC 
paired vector memory operations added in ISA 3.1.
Instructions using these options will be added in subsequent patches.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D83722

Files:
  clang/include/clang/Driver/Options.td
  clang/lib/Basic/Targets/PPC.cpp
  clang/lib/Basic/Targets/PPC.h
  clang/test/Driver/ppc-dependent-options.cpp
  llvm/lib/Target/PowerPC/PPC.td
  llvm/lib/Target/PowerPC/PPCInstrPrefix.td
  llvm/lib/Target/PowerPC/PPCScheduleP9.td
  llvm/lib/Target/PowerPC/PPCSubtarget.cpp
  llvm/lib/Target/PowerPC/PPCSubtarget.h

Index: llvm/lib/Target/PowerPC/PPCSubtarget.h
===
--- llvm/lib/Target/PowerPC/PPCSubtarget.h
+++ llvm/lib/Target/PowerPC/PPCSubtarget.h
@@ -146,6 +146,7 @@
   bool VectorsUseTwoUnits;
   bool UsePPCPreRASchedStrategy;
   bool UsePPCPostRASchedStrategy;
+  bool PairedVectorMemops;
   bool PredictableSelectIsExpensive;
 
   POPCNTDKind HasPOPCNTD;
@@ -266,6 +267,7 @@
   bool hasP10Vector() const { return HasP10Vector; }
   bool hasPrefixInstrs() const { return HasPrefixInstrs; }
   bool hasPCRelativeMemops() const { return HasPCRelativeMemops; }
+  bool pairedVectorMemops() const { return PairedVectorMemops; }
   bool hasMFOCRF() const { return HasMFOCRF; }
   bool hasISEL() const { return HasISEL; }
   bool hasBPERMD() const { return HasBPERMD; }
Index: llvm/lib/Target/PowerPC/PPCSubtarget.cpp
===
--- llvm/lib/Target/PowerPC/PPCSubtarget.cpp
+++ llvm/lib/Target/PowerPC/PPCSubtarget.cpp
@@ -122,6 +122,7 @@
   VectorsUseTwoUnits = false;
   UsePPCPreRASchedStrategy = false;
   UsePPCPostRASchedStrategy = false;
+  PairedVectorMemops = false;
   PredictableSelectIsExpensive = false;
 
   HasPOPCNTD = POPCNTD_Unavailable;
Index: llvm/lib/Target/PowerPC/PPCScheduleP9.td
===
--- llvm/lib/Target/PowerPC/PPCScheduleP9.td
+++ llvm/lib/Target/PowerPC/PPCScheduleP9.td
@@ -43,8 +43,8 @@
   // Do not support QPX (Quad Processing eXtension), SPE (Signal Processing
   // Engine), prefixed instructions on Power 9, PC relative mem ops, or
   // instructions introduced in ISA 3.1.
-  let UnsupportedFeatures = [HasQPX, HasSPE, PrefixInstrs, PCRelativeMemops,
- IsISA3_1];
+  let UnsupportedFeatures = [HasQPX, HasSPE, PrefixInstrs, PairedVectorMemops,
+ PCRelativeMemops, IsISA3_1];
 
 }
 
Index: llvm/lib/Target/PowerPC/PPCInstrPrefix.td
===
--- llvm/lib/Target/PowerPC/PPCInstrPrefix.td
+++ llvm/lib/Target/PowerPC/PPCInstrPrefix.td
@@ -427,6 +427,7 @@
 
 def PrefixInstrs : Predicate<"Subtarget->hasPrefixInstrs()">;
 def IsISA3_1 : Predicate<"Subtarget->isISA3_1()">;
+def PairedVectorMemops : Predicate<"PPCSubTarget->pairedVectorMemops()">;
 
 let Predicates = [PrefixInstrs] in {
   let Interpretation64Bit = 1, isCodeGenOnly = 1 in {
Index: llvm/lib/Target/PowerPC/PPC.td
===
--- llvm/lib/Target/PowerPC/PPC.td
+++ llvm/lib/Target/PowerPC/PPC.td
@@ -237,6 +237,10 @@
   SubtargetFeature<"pcrelative-memops", "HasPCRelativeMemops", "true",
"Enable PC relative Memory Ops",
[FeatureISA3_0]>;
+def FeaturePairedVectorMemops:
+  SubtargetFeature<"paired-vector-memops", "PairedVectorMemops", "true",
+   "32Byte load and store instructions",
+   [FeatureISA3_0]>;
 
 def FeaturePredictableSelectIsExpensive :
   SubtargetFeature<"predictable-select-expensive",
@@ -342,7 +346,7 @@
   // still exist with the exception of those we know are Power9 specific.
   list P10AdditionalFeatures =
 [DirectivePwr10, FeatureISA3_1, FeaturePrefixInstrs,
- FeaturePCRelativeMemops, FeatureP10Vector];
+ FeaturePCRelativeMemops, FeatureP10Vector, FeaturePairedVectorMemops];
   list P10SpecificFeatures = [];
   list P10InheritableFeatures =
 !listconcat(P9InheritableFeatures, P10AdditionalFeatures);
Index: clang/test/Driver/ppc-dependent-options.cpp
===
--- clang/test/Driver/ppc-dependent-options.cpp
+++ clang/test/Driver/ppc-dependent-options.cpp
@@ -55,6 +55,10 @@
 // RUN: FileCheck %s -check-prefix=CHECK-NVSX-FLT128
 
 // RUN: not %clang -target powerpc64le-unknown-unknown -fsyntax-only \
+// RUN: -mcpu=power10 -std=c++11 -mno-vsx -mpaired-vector-memops %s 2>&1 | \
+// RUN: FileCheck %s -check-prefix=CHECK-NVSX-PAIRED-VEC-MEMOPS
+
+// RUN: not %clang -target 

[PATCH] D83717: [clang-tidy] Add check fo SEI CERT item ENV32-C

2020-07-13 Thread Endre Fülöp via Phabricator via cfe-commits
gamesh411 updated this revision to Diff 277575.
gamesh411 added a comment.

simplify VisitCallExpr


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D83717

Files:
  clang-tools-extra/clang-tidy/cert/CERTTidyModule.cpp
  clang-tools-extra/clang-tidy/cert/CMakeLists.txt
  clang-tools-extra/clang-tidy/cert/ExitHandlerCheck.cpp
  clang-tools-extra/clang-tidy/cert/ExitHandlerCheck.h
  clang-tools-extra/docs/ReleaseNotes.rst
  clang-tools-extra/docs/clang-tidy/checks/cert-env32-c.rst
  clang-tools-extra/docs/clang-tidy/checks/list.rst
  clang-tools-extra/test/clang-tidy/checkers/cert-env32-c.c
  llvm/utils/gn/secondary/clang-tools-extra/clang-tidy/cert/BUILD.gn

Index: llvm/utils/gn/secondary/clang-tools-extra/clang-tidy/cert/BUILD.gn
===
--- llvm/utils/gn/secondary/clang-tools-extra/clang-tidy/cert/BUILD.gn
+++ llvm/utils/gn/secondary/clang-tools-extra/clang-tidy/cert/BUILD.gn
@@ -19,6 +19,7 @@
 "CommandProcessorCheck.cpp",
 "DefaultOperatorNewAlignmentCheck.cpp",
 "DontModifyStdNamespaceCheck.cpp",
+"ExitHandlerCheck.cpp",
 "FloatLoopCounter.cpp",
 "LimitedRandomnessCheck.cpp",
 "MutatingCopyCheck.cpp",
Index: clang-tools-extra/test/clang-tidy/checkers/cert-env32-c.c
===
--- /dev/null
+++ clang-tools-extra/test/clang-tidy/checkers/cert-env32-c.c
@@ -0,0 +1,256 @@
+// RUN: %check_clang_tidy %s cert-env32-c %t
+
+// --
+// EXIT FUNCTIONS
+// --
+
+// No handlers are invoked when _Exit is called.
+void _Exit(int __status);
+
+// Handlers registered by atexit are invoked in reverse order when exit is
+// called.
+void exit(int __status);
+
+// Handlers registered by at_quick_exit are invoked in reverse order when
+// quick_exit is called.
+void quick_exit(int __status);
+
+// 
+// HANDLER REGISTRATION
+// 
+
+// Register handlers to run when exit is called.
+int atexit(void (*__func)(void));
+
+// Register handlers to run when exit is called.
+int at_quick_exit(void (*__func)(void));
+
+// --
+// Setjmp/longjmp
+// --
+// C99 requires jmp_buf to be an array type.
+typedef int jmp_buf[1];
+int setjmp(jmp_buf);
+void longjmp(jmp_buf, int);
+
+// Compliant solutions
+
+void cleanup1() {
+  // do cleanup
+}
+
+void cleanup2() {
+  // do cleanup
+}
+
+void test_atexit_single_compliant() {
+  (void)atexit(cleanup1);
+}
+
+void test_atexit_multiple_compliant() {
+  (void)atexit(cleanup1);
+  (void)atexit(cleanup2);
+}
+
+void test_at_quick_exit_single_compliant() {
+  (void)at_quick_exit(cleanup1);
+}
+
+void test_at_quick_exit_multiple_compliant() {
+  (void)at_quick_exit(cleanup1);
+  (void)at_quick_exit(cleanup2);
+}
+
+// Non-compliant solutions calling _Exit
+
+void call__Exit() {
+  _Exit(0);
+}
+
+void call_call__Exit() {
+  call__Exit();
+}
+
+extern int unknown__Exit_flag;
+
+void call__Exit_conditionally() {
+  if (unknown__Exit_flag)
+call__Exit();
+}
+
+void call_call__Exit_conditionally() {
+  call__Exit_conditionally();
+}
+
+void test__Exit_called_directly() {
+  (void)atexit(call__Exit);
+  // CHECK-MESSAGES: :[[@LINE-1]]:11: warning: exit-handler potentially calls an exit function. Handlers should terminate by returning [cert-env32-c]
+  (void)at_quick_exit(call__Exit);
+  // CHECK-MESSAGES: :[[@LINE-1]]:11: warning: exit-handler potentially calls an exit function. Handlers should terminate by returning [cert-env32-c]
+};
+
+void test__Exit_called_indirectly() {
+  (void)atexit(call_call__Exit);
+  // CHECK-MESSAGES: :[[@LINE-1]]:11: warning: exit-handler potentially calls an exit function. Handlers should terminate by returning [cert-env32-c]
+  (void)at_quick_exit(call_call__Exit);
+  // CHECK-MESSAGES: :[[@LINE-1]]:11: warning: exit-handler potentially calls an exit function. Handlers should terminate by returning [cert-env32-c]
+};
+
+void test_conditional__Exit_called_directly() {
+  (void)atexit(call__Exit_conditionally);
+  // CHECK-MESSAGES: :[[@LINE-1]]:11: warning: exit-handler potentially calls an exit function. Handlers should terminate by returning [cert-env32-c]
+  (void)at_quick_exit(call__Exit_conditionally);
+  // CHECK-MESSAGES: :[[@LINE-1]]:11: warning: exit-handler potentially calls an exit function. Handlers should terminate by returning [cert-env32-c]
+};
+
+void test_conditional__Exit_called_indirectly() {
+  (void)atexit(call_call__Exit_conditionally);
+  // CHECK-MESSAGES: :[[@LINE-1]]:11: warning: exit-handler potentially calls an exit function. Handlers should terminate by returning [cert-env32-c]
+  (void)at_quick_exit(call_call__Exit_conditionally);
+  // CHECK-MESSAGES: :[[@LINE-1]]:11: warning: exit-handler potentially calls an exit function. Handlers should terminate by returning [cert-env32-c]
+};
+
+// Non-compliant solutions calling exit
+

[PATCH] D83717: [clang-tidy] Add check fo SEI CERT item ENV32-C

2020-07-13 Thread Endre Fülöp via Phabricator via cfe-commits
gamesh411 updated this revision to Diff 277571.
gamesh411 added a comment.

update includes


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D83717

Files:
  clang-tools-extra/clang-tidy/cert/CERTTidyModule.cpp
  clang-tools-extra/clang-tidy/cert/CMakeLists.txt
  clang-tools-extra/clang-tidy/cert/ExitHandlerCheck.cpp
  clang-tools-extra/clang-tidy/cert/ExitHandlerCheck.h
  clang-tools-extra/docs/ReleaseNotes.rst
  clang-tools-extra/docs/clang-tidy/checks/cert-env32-c.rst
  clang-tools-extra/docs/clang-tidy/checks/list.rst
  clang-tools-extra/test/clang-tidy/checkers/cert-env32-c.c
  llvm/utils/gn/secondary/clang-tools-extra/clang-tidy/cert/BUILD.gn

Index: llvm/utils/gn/secondary/clang-tools-extra/clang-tidy/cert/BUILD.gn
===
--- llvm/utils/gn/secondary/clang-tools-extra/clang-tidy/cert/BUILD.gn
+++ llvm/utils/gn/secondary/clang-tools-extra/clang-tidy/cert/BUILD.gn
@@ -19,6 +19,7 @@
 "CommandProcessorCheck.cpp",
 "DefaultOperatorNewAlignmentCheck.cpp",
 "DontModifyStdNamespaceCheck.cpp",
+"ExitHandlerCheck.cpp",
 "FloatLoopCounter.cpp",
 "LimitedRandomnessCheck.cpp",
 "MutatingCopyCheck.cpp",
Index: clang-tools-extra/test/clang-tidy/checkers/cert-env32-c.c
===
--- /dev/null
+++ clang-tools-extra/test/clang-tidy/checkers/cert-env32-c.c
@@ -0,0 +1,256 @@
+// RUN: %check_clang_tidy %s cert-env32-c %t
+
+// --
+// EXIT FUNCTIONS
+// --
+
+// No handlers are invoked when _Exit is called.
+void _Exit(int __status);
+
+// Handlers registered by atexit are invoked in reverse order when exit is
+// called.
+void exit(int __status);
+
+// Handlers registered by at_quick_exit are invoked in reverse order when
+// quick_exit is called.
+void quick_exit(int __status);
+
+// 
+// HANDLER REGISTRATION
+// 
+
+// Register handlers to run when exit is called.
+int atexit(void (*__func)(void));
+
+// Register handlers to run when exit is called.
+int at_quick_exit(void (*__func)(void));
+
+// --
+// Setjmp/longjmp
+// --
+// C99 requires jmp_buf to be an array type.
+typedef int jmp_buf[1];
+int setjmp(jmp_buf);
+void longjmp(jmp_buf, int);
+
+// Compliant solutions
+
+void cleanup1() {
+  // do cleanup
+}
+
+void cleanup2() {
+  // do cleanup
+}
+
+void test_atexit_single_compliant() {
+  (void)atexit(cleanup1);
+}
+
+void test_atexit_multiple_compliant() {
+  (void)atexit(cleanup1);
+  (void)atexit(cleanup2);
+}
+
+void test_at_quick_exit_single_compliant() {
+  (void)at_quick_exit(cleanup1);
+}
+
+void test_at_quick_exit_multiple_compliant() {
+  (void)at_quick_exit(cleanup1);
+  (void)at_quick_exit(cleanup2);
+}
+
+// Non-compliant solutions calling _Exit
+
+void call__Exit() {
+  _Exit(0);
+}
+
+void call_call__Exit() {
+  call__Exit();
+}
+
+extern int unknown__Exit_flag;
+
+void call__Exit_conditionally() {
+  if (unknown__Exit_flag)
+call__Exit();
+}
+
+void call_call__Exit_conditionally() {
+  call__Exit_conditionally();
+}
+
+void test__Exit_called_directly() {
+  (void)atexit(call__Exit);
+  // CHECK-MESSAGES: :[[@LINE-1]]:11: warning: exit-handler potentially calls an exit function. Handlers should terminate by returning [cert-env32-c]
+  (void)at_quick_exit(call__Exit);
+  // CHECK-MESSAGES: :[[@LINE-1]]:11: warning: exit-handler potentially calls an exit function. Handlers should terminate by returning [cert-env32-c]
+};
+
+void test__Exit_called_indirectly() {
+  (void)atexit(call_call__Exit);
+  // CHECK-MESSAGES: :[[@LINE-1]]:11: warning: exit-handler potentially calls an exit function. Handlers should terminate by returning [cert-env32-c]
+  (void)at_quick_exit(call_call__Exit);
+  // CHECK-MESSAGES: :[[@LINE-1]]:11: warning: exit-handler potentially calls an exit function. Handlers should terminate by returning [cert-env32-c]
+};
+
+void test_conditional__Exit_called_directly() {
+  (void)atexit(call__Exit_conditionally);
+  // CHECK-MESSAGES: :[[@LINE-1]]:11: warning: exit-handler potentially calls an exit function. Handlers should terminate by returning [cert-env32-c]
+  (void)at_quick_exit(call__Exit_conditionally);
+  // CHECK-MESSAGES: :[[@LINE-1]]:11: warning: exit-handler potentially calls an exit function. Handlers should terminate by returning [cert-env32-c]
+};
+
+void test_conditional__Exit_called_indirectly() {
+  (void)atexit(call_call__Exit_conditionally);
+  // CHECK-MESSAGES: :[[@LINE-1]]:11: warning: exit-handler potentially calls an exit function. Handlers should terminate by returning [cert-env32-c]
+  (void)at_quick_exit(call_call__Exit_conditionally);
+  // CHECK-MESSAGES: :[[@LINE-1]]:11: warning: exit-handler potentially calls an exit function. Handlers should terminate by returning [cert-env32-c]
+};
+
+// Non-compliant solutions calling exit
+
+void 

[PATCH] D83717: [clang-tidy] Add check fo SEI CERT item ENV32-C

2020-07-13 Thread Endre Fülöp via Phabricator via cfe-commits
gamesh411 created this revision.
Herald added subscribers: llvm-commits, cfe-commits, martong, steakhal, 
Szelethus, dkrupp, xazax.hun, whisperity, mgorny.
Herald added projects: clang, LLVM.

Add check for the SEI CERT item ENV32-C which dictates that exit handler
functions should terminate by returning as opposed to calling exit-functions
or jumping out of the handler function body with 'longjmp'. The handler
registration functions 'atexit and 'at_quick_exit',  exit functions '_Exit',
'exit', 'quick_exit are checked.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D83717

Files:
  clang-tools-extra/clang-tidy/cert/CERTTidyModule.cpp
  clang-tools-extra/clang-tidy/cert/CMakeLists.txt
  clang-tools-extra/clang-tidy/cert/ExitHandlerCheck.cpp
  clang-tools-extra/clang-tidy/cert/ExitHandlerCheck.h
  clang-tools-extra/docs/ReleaseNotes.rst
  clang-tools-extra/docs/clang-tidy/checks/cert-env32-c.rst
  clang-tools-extra/docs/clang-tidy/checks/list.rst
  clang-tools-extra/test/clang-tidy/checkers/cert-env32-c.c
  llvm/utils/gn/secondary/clang-tools-extra/clang-tidy/cert/BUILD.gn

Index: llvm/utils/gn/secondary/clang-tools-extra/clang-tidy/cert/BUILD.gn
===
--- llvm/utils/gn/secondary/clang-tools-extra/clang-tidy/cert/BUILD.gn
+++ llvm/utils/gn/secondary/clang-tools-extra/clang-tidy/cert/BUILD.gn
@@ -19,6 +19,7 @@
 "CommandProcessorCheck.cpp",
 "DefaultOperatorNewAlignmentCheck.cpp",
 "DontModifyStdNamespaceCheck.cpp",
+"ExitHandlerCheck.cpp",
 "FloatLoopCounter.cpp",
 "LimitedRandomnessCheck.cpp",
 "MutatingCopyCheck.cpp",
Index: clang-tools-extra/test/clang-tidy/checkers/cert-env32-c.c
===
--- /dev/null
+++ clang-tools-extra/test/clang-tidy/checkers/cert-env32-c.c
@@ -0,0 +1,256 @@
+// RUN: %check_clang_tidy %s cert-env32-c %t
+
+// --
+// EXIT FUNCTIONS
+// --
+
+// No handlers are invoked when _Exit is called.
+void _Exit(int __status);
+
+// Handlers registered by atexit are invoked in reverse order when exit is
+// called.
+void exit(int __status);
+
+// Handlers registered by at_quick_exit are invoked in reverse order when
+// quick_exit is called.
+void quick_exit(int __status);
+
+// 
+// HANDLER REGISTRATION
+// 
+
+// Register handlers to run when exit is called.
+int atexit(void (*__func)(void));
+
+// Register handlers to run when exit is called.
+int at_quick_exit(void (*__func)(void));
+
+// --
+// Setjmp/longjmp
+// --
+// C99 requires jmp_buf to be an array type.
+typedef int jmp_buf[1];
+int setjmp(jmp_buf);
+void longjmp(jmp_buf, int);
+
+// Compliant solutions
+
+void cleanup1() {
+  // do cleanup
+}
+
+void cleanup2() {
+  // do cleanup
+}
+
+void test_atexit_single_compliant() {
+  (void)atexit(cleanup1);
+}
+
+void test_atexit_multiple_compliant() {
+  (void)atexit(cleanup1);
+  (void)atexit(cleanup2);
+}
+
+void test_at_quick_exit_single_compliant() {
+  (void)at_quick_exit(cleanup1);
+}
+
+void test_at_quick_exit_multiple_compliant() {
+  (void)at_quick_exit(cleanup1);
+  (void)at_quick_exit(cleanup2);
+}
+
+// Non-compliant solutions calling _Exit
+
+void call__Exit() {
+  _Exit(0);
+}
+
+void call_call__Exit() {
+  call__Exit();
+}
+
+extern int unknown__Exit_flag;
+
+void call__Exit_conditionally() {
+  if (unknown__Exit_flag)
+call__Exit();
+}
+
+void call_call__Exit_conditionally() {
+  call__Exit_conditionally();
+}
+
+void test__Exit_called_directly() {
+  (void)atexit(call__Exit);
+  // CHECK-MESSAGES: :[[@LINE-1]]:11: warning: exit-handler potentially calls an exit function. Handlers should terminate by returning [cert-env32-c]
+  (void)at_quick_exit(call__Exit);
+  // CHECK-MESSAGES: :[[@LINE-1]]:11: warning: exit-handler potentially calls an exit function. Handlers should terminate by returning [cert-env32-c]
+};
+
+void test__Exit_called_indirectly() {
+  (void)atexit(call_call__Exit);
+  // CHECK-MESSAGES: :[[@LINE-1]]:11: warning: exit-handler potentially calls an exit function. Handlers should terminate by returning [cert-env32-c]
+  (void)at_quick_exit(call_call__Exit);
+  // CHECK-MESSAGES: :[[@LINE-1]]:11: warning: exit-handler potentially calls an exit function. Handlers should terminate by returning [cert-env32-c]
+};
+
+void test_conditional__Exit_called_directly() {
+  (void)atexit(call__Exit_conditionally);
+  // CHECK-MESSAGES: :[[@LINE-1]]:11: warning: exit-handler potentially calls an exit function. Handlers should terminate by returning [cert-env32-c]
+  (void)at_quick_exit(call__Exit_conditionally);
+  // CHECK-MESSAGES: :[[@LINE-1]]:11: warning: exit-handler potentially calls an exit function. Handlers should terminate by returning [cert-env32-c]
+};
+
+void test_conditional__Exit_called_indirectly() {
+  (void)atexit(call_call__Exit_conditionally);
+  // CHECK-MESSAGES: :[[@LINE-1]]:11: warning: 

[PATCH] D83553: [PATCH 3/4][Sema][AArch64] Add codegen for arm_sve_vector_bits attribute

2020-07-13 Thread Eli Friedman via Phabricator via cfe-commits
efriedma added a comment.

> If you mean alloca's for single vectors

I was really referring to the IR values themselves, not the memory 
representation.  Since the width of the vectors is known, you could emit IR 
without any mention of scalable types at all (assuming the backend was extended 
to handle the intrinsics).

The choice of vscale'ed types for variables is also interesting, though. Thanks 
for the explanation.


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

https://reviews.llvm.org/D83553



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


[PATCH] D83681: [clang] Diagnose a misplaced lambda capture-default.

2020-07-13 Thread Bruno Ricci via Phabricator via cfe-commits
riccibruno updated this revision to Diff 277561.
riccibruno added a comment.

clang-format the tests


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D83681

Files:
  clang/include/clang/Basic/DiagnosticParseKinds.td
  clang/lib/Parse/ParseExprCXX.cpp
  clang/test/Parser/lambda-misplaced-capture-default.cpp


Index: clang/test/Parser/lambda-misplaced-capture-default.cpp
===
--- /dev/null
+++ clang/test/Parser/lambda-misplaced-capture-default.cpp
@@ -0,0 +1,25 @@
+// RUN: %clang_cc1 -std=c++17 -Wno-unused-value -fsyntax-only -verify %s
+
+namespace misplaced_capture_default {
+void Test() {
+  int i = 0;
+  [&, i, &] {};   // expected-error {{expected variable name or 'this' in 
lambda capture list}}
+  [&, i, = ] {};  // expected-error {{expected variable name or 'this' in 
lambda capture list}}
+  [=, , &] {};  // expected-error {{expected variable name or 'this' in 
lambda capture list}}
+  [=, , = ] {}; // expected-error {{expected variable name or 'this' in 
lambda capture list}}
+
+  [i, &] {}; // expected-error {{misplaced capture default}}
+ // expected-note@-1 {{capture default must be first}}
+
+  [i, = ] {}; // expected-error {{misplaced capture default}}
+  // expected-note@-1 {{capture default must be first}}
+
+  [i, = x] {}; // expected-error {{expected variable name or 'this' in lambda 
capture list}}
+
+  [i, &, x = 2] {}; // expected-error {{misplaced capture default}}
+// expected-note@-1 {{capture default must be first}}
+
+  [i, =, x = 2] {}; // expected-error {{misplaced capture default}}
+// expected-note@-1 {{capture default must be first}}
+}
+} // namespace misplaced_capture_default
Index: clang/lib/Parse/ParseExprCXX.cpp
===
--- clang/lib/Parse/ParseExprCXX.cpp
+++ clang/lib/Parse/ParseExprCXX.cpp
@@ -926,6 +926,17 @@
 } else if (Tok.is(tok::kw_this)) {
   Kind = LCK_This;
   Loc = ConsumeToken();
+} else if (Tok.isOneOf(tok::amp, tok::equal) &&
+   NextToken().isOneOf(tok::comma, tok::r_square) &&
+   Intro.Default == LCD_None) {
+  // We have a lone "&" or "=" which is either a misplaced capture-default
+  // or the start of a capture (in the "&" case) with the rest of the
+  // capture missing. Both are an error but a misplaced capture-default
+  // is more likely if we don't already have a capture default.
+  return Invalid([&] {
+Diag(Tok.getLocation(), diag::err_misplaced_capture_default);
+Diag(T.getOpenLocation(), diag::note_capture_default_first);
+  });
 } else {
   TryConsumeToken(tok::ellipsis, EllipsisLocs[0]);
 
Index: clang/include/clang/Basic/DiagnosticParseKinds.td
===
--- clang/include/clang/Basic/DiagnosticParseKinds.td
+++ clang/include/clang/Basic/DiagnosticParseKinds.td
@@ -934,6 +934,10 @@
   "the name of the capture">;
 def err_lambda_capture_multiple_ellipses : Error<
   "multiple ellipses in pack capture">;
+def err_misplaced_capture_default : Error<
+  "misplaced capture default">;
+def note_capture_default_first : Note<
+  "capture default must be first">;
 // C++17 lambda expressions
 def err_expected_star_this_capture : Error<
   "expected 'this' following '*' in lambda capture list">;


Index: clang/test/Parser/lambda-misplaced-capture-default.cpp
===
--- /dev/null
+++ clang/test/Parser/lambda-misplaced-capture-default.cpp
@@ -0,0 +1,25 @@
+// RUN: %clang_cc1 -std=c++17 -Wno-unused-value -fsyntax-only -verify %s
+
+namespace misplaced_capture_default {
+void Test() {
+  int i = 0;
+  [&, i, &] {};   // expected-error {{expected variable name or 'this' in lambda capture list}}
+  [&, i, = ] {};  // expected-error {{expected variable name or 'this' in lambda capture list}}
+  [=, , &] {};  // expected-error {{expected variable name or 'this' in lambda capture list}}
+  [=, , = ] {}; // expected-error {{expected variable name or 'this' in lambda capture list}}
+
+  [i, &] {}; // expected-error {{misplaced capture default}}
+ // expected-note@-1 {{capture default must be first}}
+
+  [i, = ] {}; // expected-error {{misplaced capture default}}
+  // expected-note@-1 {{capture default must be first}}
+
+  [i, = x] {}; // expected-error {{expected variable name or 'this' in lambda capture list}}
+
+  [i, &, x = 2] {}; // expected-error {{misplaced capture default}}
+// expected-note@-1 {{capture default must be first}}
+
+  [i, =, x = 2] {}; // expected-error {{misplaced capture default}}
+// expected-note@-1 {{capture default must be first}}
+}
+} // namespace misplaced_capture_default
Index: 

[PATCH] D83061: [OpenMP] Implement TR8 `present` map type modifier in Clang (1/2)

2020-07-13 Thread Joel E. Denny via Phabricator via cfe-commits
jdenny added a comment.

Ping.  Maybe we can start with the simplest question from the review summary:

> The Clang codegen test files are difficult to maintain because of their 
> sizes, but I tried to insert `present` tests into them anyway to be 
> consistent with the existing `always` and `close` tests. I'd like to move all 
> `present` codegen tests to separate test files. Any objections?


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

https://reviews.llvm.org/D83061



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


[PATCH] D83592: [Parser] Add comment to skipped regions

2020-07-13 Thread Vedant Kumar via Phabricator via cfe-commits
vsk added a comment.

@zequanwu thanks for working on this. Instead of threading CommentSkipped 
through PPCallbacks, wdyt of taking advantage of the existing CommentHandler 
interface? To simplify things, we can add a static method like 
'CoverageMappingGen::setupPreprocessorCallbacks(Preprocessor &)' and call that 
from CodeGenAction::CreateASTConsumer.




Comment at: llvm/lib/ProfileData/Coverage/CoverageMappingWriter.cpp:152
+static MutableArrayRef
+mergeSkippedRegions(MutableArrayRef MappingRegions) {
+  SmallVector MergedRegions;

This seems like a lot of complexity to add to handle a narrow case. Is it 
necessary to merge skipped regions early in the process? Note that llvm's 
SegmentBuilder takes care of merging regions at the very end.



Comment at: llvm/lib/ProfileData/Coverage/CoverageMappingWriter.cpp:183
+
+  return MergedRegions;
+}

This is stack use after free, right? This needs to release ownership of the 
'MergedRegions' container.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D83592



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


[PATCH] D83713: [WebAssembly] Triple::wasm64 related cleanup

2020-07-13 Thread Wouter van Oortmerssen via Phabricator via cfe-commits
aardappel created this revision.
aardappel added reviewers: dschuff, sbc100.
Herald added subscribers: llvm-commits, cfe-commits, sunfish, aheejin, 
hiraditya, jgravelle-google.
Herald added projects: clang, LLVM.

A few cases that didn't cover Triple::wasm64 correctly.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D83713

Files:
  clang/lib/Driver/ToolChain.cpp
  lld/wasm/InputFiles.cpp
  llvm/include/llvm/Object/Wasm.h
  llvm/lib/Object/WasmObjectFile.cpp


Index: llvm/lib/Object/WasmObjectFile.cpp
===
--- llvm/lib/Object/WasmObjectFile.cpp
+++ llvm/lib/Object/WasmObjectFile.cpp
@@ -957,6 +957,7 @@
   break;
 case wasm::WASM_EXTERNAL_MEMORY:
   Im.Memory = readLimits(Ctx);
+  if (Im.Memory.Flags & wasm::WASM_LIMITS_FLAG_IS_64) HasMemory64 = true;
   break;
 case wasm::WASM_EXTERNAL_TABLE:
   Im.Table = readTable(Ctx);
@@ -1019,7 +1020,9 @@
   uint32_t Count = readVaruint32(Ctx);
   Memories.reserve(Count);
   while (Count--) {
-Memories.push_back(readLimits(Ctx));
+auto Limits = readLimits(Ctx);
+if (Limits.Flags & wasm::WASM_LIMITS_FLAG_IS_64) HasMemory64 = true;
+Memories.push_back(Limits);
   }
   if (Ctx.Ptr != Ctx.End)
 return make_error("Memory section ended prematurely",
@@ -1576,11 +1579,15 @@
   return section_iterator(SectionRef(Ref, this));
 }
 
-uint8_t WasmObjectFile::getBytesInAddress() const { return 4; }
+uint8_t WasmObjectFile::getBytesInAddress() const {
+  return HasMemory64 ? 8 : 4;
+}
 
 StringRef WasmObjectFile::getFileFormatName() const { return "WASM"; }
 
-Triple::ArchType WasmObjectFile::getArch() const { return Triple::wasm32; }
+Triple::ArchType WasmObjectFile::getArch() const {
+  return HasMemory64 ? Triple::wasm64 : Triple::wasm32;
+}
 
 SubtargetFeatures WasmObjectFile::getFeatures() const {
   return SubtargetFeatures();
Index: llvm/include/llvm/Object/Wasm.h
===
--- llvm/include/llvm/Object/Wasm.h
+++ llvm/include/llvm/Object/Wasm.h
@@ -282,6 +282,7 @@
   bool HasLinkingSection = false;
   bool HasDylinkSection = false;
   bool SeenCodeSection = false;
+  bool HasMemory64 = false;
   wasm::WasmLinkingData LinkingData;
   uint32_t NumImportedGlobals = 0;
   uint32_t NumImportedFunctions = 0;
Index: lld/wasm/InputFiles.cpp
===
--- lld/wasm/InputFiles.cpp
+++ lld/wasm/InputFiles.cpp
@@ -576,10 +576,11 @@
   obj = check(lto::InputFile::create(MemoryBufferRef(
   mb.getBuffer(), saver.save(archiveName + mb.getBufferIdentifier();
   Triple t(obj->getTargetTriple());
-  if (t.getArch() != Triple::wasm32) {
-error(toString(this) + ": machine type must be wasm32");
+  if (!t.isWasm()) {
+error(toString(this) + ": machine type must be wasm32 or wasm64");
 return;
   }
+  config->is64 = t.getArch() == Triple::wasm64;
   std::vector keptComdats;
   for (StringRef s : obj->getComdatTable())
 keptComdats.push_back(symtab->addComdat(s));
Index: clang/lib/Driver/ToolChain.cpp
===
--- clang/lib/Driver/ToolChain.cpp
+++ clang/lib/Driver/ToolChain.cpp
@@ -632,8 +632,7 @@
Triple.getArch() == llvm::Triple::armeb ||
Triple.getArch() == llvm::Triple::thumb ||
Triple.getArch() == llvm::Triple::thumbeb ||
-   Triple.getArch() == llvm::Triple::wasm32 ||
-   Triple.getArch() == llvm::Triple::wasm64;
+   Triple.isWasm();
   } else if (Model == "posix")
 return true;
 
@@ -1000,8 +999,7 @@
   if (getTriple().getArch() == llvm::Triple::x86 ||
   getTriple().getArch() == llvm::Triple::x86_64 ||
   getTriple().getArch() == llvm::Triple::arm ||
-  getTriple().getArch() == llvm::Triple::wasm32 ||
-  getTriple().getArch() == llvm::Triple::wasm64 || getTriple().isAArch64())
+  getTriple().isWasm() || getTriple().isAArch64())
 Res |= SanitizerKind::CFIICall;
   if (getTriple().getArch() == llvm::Triple::x86_64 || getTriple().isAArch64())
 Res |= SanitizerKind::ShadowCallStack;


Index: llvm/lib/Object/WasmObjectFile.cpp
===
--- llvm/lib/Object/WasmObjectFile.cpp
+++ llvm/lib/Object/WasmObjectFile.cpp
@@ -957,6 +957,7 @@
   break;
 case wasm::WASM_EXTERNAL_MEMORY:
   Im.Memory = readLimits(Ctx);
+  if (Im.Memory.Flags & wasm::WASM_LIMITS_FLAG_IS_64) HasMemory64 = true;
   break;
 case wasm::WASM_EXTERNAL_TABLE:
   Im.Table = readTable(Ctx);
@@ -1019,7 +1020,9 @@
   uint32_t Count = readVaruint32(Ctx);
   Memories.reserve(Count);
   while (Count--) {
-Memories.push_back(readLimits(Ctx));
+auto Limits = readLimits(Ctx);
+if (Limits.Flags & wasm::WASM_LIMITS_FLAG_IS_64) HasMemory64 = true;
+Memories.push_back(Limits);
   }
   if (Ctx.Ptr != Ctx.End)
 return 

[PATCH] D83616: [clang] Add 'override' to virtual function overrides generated by ClangAttrEmitter

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

LGTM, thanks!


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D83616



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


[PATCH] D83494: [libFuzzer] Link libFuzzer's own interceptors when other compiler runtimes are not linked.

2020-07-13 Thread Mitch Phillips via Phabricator via cfe-commits
hctim added a comment.

In D83494#2148180 , @morehouse wrote:

> In D83494#2148164 , @dokyungs wrote:
>
> > Right. Apparently with `-O2` many calls to `memcmp`-like functions are 
> > removed. I just wondered, though, what makes more sense: disabling such 
> > optimization when building (i) with sancov, or (ii) with 
> > `-fsanitize=fuzzer`? If we go for (i), would it make sense to do it in the 
> > SanitizerCoverage module pass like other sanitizers do? What do you think? 
> > Also, can it be addressed in a follow-up patch?
>
>
> My opinion is to make it part of `-fsanitize=fuzzer`, or maybe disable parts 
> of the builtin optimization pass for functions with the `OptForFuzzing` 
> attribute.
>
> And I think a follow-up patch is easier to review.


Agreed with Matt on all of the above.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D83494



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


[PATCH] D83592: [Parser] Add comment to skipped regions

2020-07-13 Thread Zequan Wu via Phabricator via cfe-commits
zequanwu updated this revision to Diff 277538.
zequanwu added a comment.
Herald added subscribers: llvm-commits, hiraditya.
Herald added a project: LLVM.

Merge overlapped `SkippedRegion`.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D83592

Files:
  clang/include/clang/Lex/PPCallbacks.h
  clang/lib/CodeGen/CoverageMappingGen.cpp
  clang/lib/CodeGen/CoverageMappingGen.h
  clang/lib/Parse/Parser.cpp
  llvm/lib/ProfileData/Coverage/CoverageMappingWriter.cpp

Index: llvm/lib/ProfileData/Coverage/CoverageMappingWriter.cpp
===
--- llvm/lib/ProfileData/Coverage/CoverageMappingWriter.cpp
+++ llvm/lib/ProfileData/Coverage/CoverageMappingWriter.cpp
@@ -148,6 +148,41 @@
   encodeULEB128(encodeCounter(Expressions, C), OS);
 }
 
+static MutableArrayRef
+mergeSkippedRegions(MutableArrayRef MappingRegions) {
+  SmallVector MergedRegions;
+  for (size_t I = 0; I < MappingRegions.size() - 1; I++) {
+CounterMappingRegion First = MappingRegions[I];
+CounterMappingRegion Second = MappingRegions[I+1];
+if (First.FileID != Second.FileID ||
+First.Kind != CounterMappingRegion::SkippedRegion ||
+First.Kind != Second.Kind) {
+  MergedRegions.push_back(First);
+  continue;
+}
+
+if (First.LineEnd > Second.LineEnd ||
+(First.LineEnd == Second.LineEnd &&
+ First.ColumnEnd >= Second.ColumnEnd)) {
+  // When second region is inside first region, discard second region.
+  MergedRegions.push_back(First);
+  I++;
+} else if (Second.LineStart >= First.LineStart &&
+   Second.LineStart <= First.LineEnd) {
+  // When the start location of second region is inside first region and the
+  // end location is outside first region.
+  MergedRegions.push_back(CounterMappingRegion::makeSkipped(
+  First.FileID, First.LineStart, First.ColumnStart, Second.LineEnd,
+  Second.ColumnEnd));
+} else {
+  // When there is no overlapping.
+  MergedRegions.push_back(First);
+}
+  }
+
+  return MergedRegions;
+}
+
 void CoverageMappingWriter::write(raw_ostream ) {
   // Check that we don't have any bogus regions.
   assert(all_of(MappingRegions,
@@ -167,6 +202,9 @@
 return LHS.Kind < RHS.Kind;
   });
 
+  // Merge overlapped regions.
+  MappingRegions = mergeSkippedRegions(MappingRegions);
+
   // Write out the fileid -> filename mapping.
   encodeULEB128(VirtualFileMapping.size(), OS);
   for (const auto  : VirtualFileMapping)
Index: clang/lib/Parse/Parser.cpp
===
--- clang/lib/Parse/Parser.cpp
+++ clang/lib/Parse/Parser.cpp
@@ -34,6 +34,7 @@
   explicit ActionCommentHandler(Sema ) : S(S) { }
 
   bool HandleComment(Preprocessor , SourceRange Comment) override {
+PP.getPPCallbacks()->CommentSkipped(Comment);
 S.ActOnComment(Comment);
 return false;
   }
Index: clang/lib/CodeGen/CoverageMappingGen.h
===
--- clang/lib/CodeGen/CoverageMappingGen.h
+++ clang/lib/CodeGen/CoverageMappingGen.h
@@ -38,6 +38,8 @@
   ArrayRef getSkippedRanges() const { return SkippedRanges; }
 
   void SourceRangeSkipped(SourceRange Range, SourceLocation EndifLoc) override;
+
+  void CommentSkipped(SourceRange Range) override;
 };
 
 namespace CodeGen {
Index: clang/lib/CodeGen/CoverageMappingGen.cpp
===
--- clang/lib/CodeGen/CoverageMappingGen.cpp
+++ clang/lib/CodeGen/CoverageMappingGen.cpp
@@ -39,6 +39,10 @@
   SkippedRanges.push_back(Range);
 }
 
+void CoverageSourceInfo::CommentSkipped(SourceRange Range) {
+  SkippedRanges.push_back(Range);
+}
+
 namespace {
 
 /// A region of source code that can be mapped to a counter.
Index: clang/include/clang/Lex/PPCallbacks.h
===
--- clang/include/clang/Lex/PPCallbacks.h
+++ clang/include/clang/Lex/PPCallbacks.h
@@ -319,6 +319,10 @@
   virtual void SourceRangeSkipped(SourceRange Range, SourceLocation EndifLoc) {
   }
 
+  /// Hood called when the source range is comment, which should be skipped.
+  /// \param Range The SourceRange that is comment.
+  virtual void CommentSkipped(SourceRange Range) {}
+
   enum ConditionValueKind {
 CVK_NotEvaluated, CVK_False, CVK_True
   };
@@ -565,6 +569,11 @@
 Second->SourceRangeSkipped(Range, EndifLoc);
   }
 
+  void CommentSkipped(SourceRange Range) override {
+First->CommentSkipped(Range);
+Second->CommentSkipped(Range);
+  }
+
   /// Hook called whenever an \#if is seen.
   void If(SourceLocation Loc, SourceRange ConditionRange,
   ConditionValueKind ConditionValue) override {
___
cfe-commits mailing list
cfe-commits@lists.llvm.org

[PATCH] D83494: [libFuzzer] Link libFuzzer's own interceptors when other compiler runtimes are not linked.

2020-07-13 Thread Dokyung Song via Phabricator via cfe-commits
dokyungs updated this revision to Diff 277530.
dokyungs added a comment.

Fixed a few LINT warnings by defining some macros that resemble the ones used 
in other sanitizer interception code.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D83494

Files:
  clang/include/clang/Driver/SanitizerArgs.h
  clang/lib/Driver/SanitizerArgs.cpp
  clang/lib/Driver/ToolChains/CommonArgs.cpp
  compiler-rt/lib/fuzzer/CMakeLists.txt
  compiler-rt/lib/fuzzer/FuzzerInterceptors.cpp
  compiler-rt/test/fuzzer/no-asan-memcmp.test
  compiler-rt/test/fuzzer/no-asan-strcmp.test
  compiler-rt/test/fuzzer/no-asan-strncmp.test
  compiler-rt/test/fuzzer/no-asan-strstr.test

Index: compiler-rt/test/fuzzer/no-asan-strstr.test
===
--- /dev/null
+++ compiler-rt/test/fuzzer/no-asan-strstr.test
@@ -0,0 +1,5 @@
+UNSUPPORTED: freebsd
+RUN: %cpp_compiler -fno-sanitize=address -fno-builtin-strstr %S/StrstrTest.cpp -o %t-StrstrTest
+RUN: not %run %t-StrstrTest   -seed=1 -runs=200   2>&1 | FileCheck %s
+CHECK: BINGO
+
Index: compiler-rt/test/fuzzer/no-asan-strncmp.test
===
--- /dev/null
+++ compiler-rt/test/fuzzer/no-asan-strncmp.test
@@ -0,0 +1,4 @@
+UNSUPPORTED: freebsd
+RUN: %cpp_compiler -fno-sanitize=address -fno-builtin-strncmp  %S/StrncmpTest.cpp -o %t-StrncmpTest
+RUN: not %run %t-StrncmpTest  -seed=2 -runs=1000   2>&1 | FileCheck %s
+CHECK: BINGO
Index: compiler-rt/test/fuzzer/no-asan-strcmp.test
===
--- /dev/null
+++ compiler-rt/test/fuzzer/no-asan-strcmp.test
@@ -0,0 +1,5 @@
+UNSUPPORTED: freebsd
+RUN: %cpp_compiler -fno-sanitize=address -fno-builtin-strcmp %S/StrcmpTest.cpp -o %t-StrcmpTest
+RUN: not %run %t-StrcmpTest   -seed=1 -runs=200   2>&1 | FileCheck %s
+CHECK: BINGO
+
Index: compiler-rt/test/fuzzer/no-asan-memcmp.test
===
--- /dev/null
+++ compiler-rt/test/fuzzer/no-asan-memcmp.test
@@ -0,0 +1,4 @@
+UNSUPPORTED: freebsd
+RUN: %cpp_compiler -fno-sanitize=address -fno-builtin-memcmp %S/MemcmpTest.cpp -o %t-MemcmpTest
+RUN: not %run %t-MemcmpTest   -seed=1 -runs=1000   2>&1 | FileCheck %s
+CHECK: BINGO
Index: compiler-rt/lib/fuzzer/FuzzerInterceptors.cpp
===
--- /dev/null
+++ compiler-rt/lib/fuzzer/FuzzerInterceptors.cpp
@@ -0,0 +1,161 @@
+//===-- FuzzerInterceptors.cpp ===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+// Intercept certain libc functions to aid fuzzing.
+// Linked only when other RTs that define their own interceptors are not linked.
+//===--===//
+
+#include "FuzzerBuiltins.h"
+
+#if LIBFUZZER_LINUX
+
+#define PTR_TO_REAL(x) real_##x
+#define REAL(x) __interception::PTR_TO_REAL(x)
+#define FUNC_TYPE(x) x##_type
+#define DEFINE_REAL(ret_type, func, ...)   \
+  typedef ret_type (*FUNC_TYPE(func))(__VA_ARGS__);\
+  namespace __interception {   \
+  FUNC_TYPE(func) PTR_TO_REAL(func);   \
+  }
+
+typedef unsigned long uptr;
+
+#include  // for dlsym()
+
+static void *GetFuncAddr(const char *name, uptr wrapper_addr) {
+  void *addr = dlsym(RTLD_NEXT, name);
+  if (!addr) {
+// If the lookup using RTLD_NEXT failed, the sanitizer runtime library is
+// later in the library search order than the DSO that we are trying to
+// intercept, which means that we cannot intercept this function. We still
+// want the address of the real definition, though, so look it up using
+// RTLD_DEFAULT.
+addr = dlsym(RTLD_DEFAULT, name);
+
+// In case `name' is not loaded, dlsym ends up finding the actual wrapper.
+// We don't want to intercept the wrapper and have it point to itself.
+if ((uptr)addr == wrapper_addr)
+  addr = nullptr;
+  }
+  return addr;
+}
+
+extern "C" {
+
+// NOLINTNEXTLINE
+void __sanitizer_weak_hook_memcmp(void *, const void *, const void *, size_t,
+  int);
+// NOLINTNEXTLINE
+void __sanitizer_weak_hook_strncmp(void *, const char *, const char *, size_t,
+   int);
+// NOLINTNEXTLINE
+void __sanitizer_weak_hook_strcmp(void *, const char *, const char *, int);
+// NOLINTNEXTLINE
+void __sanitizer_weak_hook_strncasecmp(void *, const char *, const 

[PATCH] D83438: [AST] Fix potential nullptr dereference in Expr::HasSideEffects

2020-07-13 Thread Jan Korous via Phabricator via cfe-commits
jkorous added a comment.

Sounds like a good idea.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D83438



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


[PATCH] D83438: [AST] Fix potential nullptr dereference in Expr::HasSideEffects

2020-07-13 Thread Bruno Ricci via Phabricator via cfe-commits
riccibruno added a comment.

I think that adding an unittest for such a simple fix is a bit heavy handed. 
What about just exercising this code path. For example:

  void Test(int N) {
int arr[N];
decltype([]{}) *p; // expected-error {{lambda expression in an 
unevaluated operand}}
  }


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D83438



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


[PATCH] D83494: [libFuzzer] Link libFuzzer's own interceptors when other compiler runtimes are not linked.

2020-07-13 Thread Matt Morehouse via Phabricator via cfe-commits
morehouse added a comment.

In D83494#2148164 , @dokyungs wrote:

> In D83494#2148043 , @hctim wrote:
>
> > In D83494#2147608 , @dokyungs 
> > wrote:
> >
> > > Builtin libfunc optimizations may transform memcmp and strcmp-like 
> > > functions. To disable such optimizations, -fno-builtin= flag was 
> > > additionally added in compiling new test cases. FWIW, the original test 
> > > cases didn't require such flags since other sanitizers including ASan 
> > > disables those optimizations in their LLVM pass by dropping libfunc 
> > > attribute in the call instructions.
> >
> >
> > It sounds like we need to add `-fno-builtin` in the clang driver when 
> > building with sancov as well. Otherwise, users won't get any benefit of 
> > this patch without doing `clang++ -fsanitize=fuzzer my_fuzz_target.cpp 
> > -fno-builtin-strstr -fno-builtin-strncmp  -fno-builtin-strcmp  
> > -fno-builtin-memcmp`?
>
>
> Right. Apparently with `-O2` many calls to `memcmp`-like functions are 
> removed. I just wondered, though, what makes more sense: disabling such 
> optimization when building (i) with sancov, or (ii) with `-fsanitize=fuzzer`? 
> If we go for (i), would it make sense to do it in the SanitizerCoverage 
> module pass like other sanitizers do? What do you think? Also, can it be 
> addressed in a follow-up patch?


My opinion is to make it part of `-fsanitize=fuzzer`, or maybe disable parts of 
the builtin optimization pass for functions with the `OptForFuzzing` attribute.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D83494



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


[PATCH] D83707: [OpenMP][NFC] Emit remarks during GPU state machine optimization

2020-07-13 Thread Johannes Doerfert via Phabricator via cfe-commits
jdoerfert updated this revision to Diff 277524.
jdoerfert added a comment.

simplify test


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D83707

Files:
  clang/test/OpenMP/remarks_parallel_in_target_state_machine.c
  llvm/lib/Transforms/IPO/OpenMPOpt.cpp

Index: llvm/lib/Transforms/IPO/OpenMPOpt.cpp
===
--- llvm/lib/Transforms/IPO/OpenMPOpt.cpp
+++ llvm/lib/Transforms/IPO/OpenMPOpt.cpp
@@ -1033,6 +1033,7 @@
 // Check if the function is uses in a __kmpc_kernel_prepare_parallel call at
 // all.
 bool UnknownUse = false;
+bool KernelPrepareUse = false;
 unsigned NumDirectCalls = 0;
 
 SmallVector ToBeReplacedStateMachineUses;
@@ -1049,31 +1050,81 @@
   }
   if (OpenMPOpt::getCallIfRegularCall(*U.getUser(),
   )) {
+KernelPrepareUse = true;
 ToBeReplacedStateMachineUses.push_back();
 return;
   }
   UnknownUse = true;
 });
 
-// If this ever hits, we should investigate.
-if (UnknownUse || NumDirectCalls != 1)
+// Do not emit a remark if we haven't seen a __kmpc_kernel_prepare_parallel
+// use.
+if (!KernelPrepareUse)
   continue;
 
-// TODO: This is not a necessary restriction and should be lifted.
-if (ToBeReplacedStateMachineUses.size() != 2)
+{
+  auto Remark = [&](OptimizationRemark OR) {
+return OR
+   << "Found parallel region that is called through a state machine"
+   << ore::NV("OpenMPParallelRegion", F->getName())
+   << " in non-SPMD target region. This can lead to excessive "
+  "register usage in unrelated kernels in the same translation "
+  "unit due to spurious call edges assumed by ptxas.";
+  };
+  emitRemarkOnFunction(F, "OpenMPParallelRegionInNonSPMD", Remark);
+}
+
+// If this ever hits, we should investigate.
+// TODO: Checking the number of uses is not a necessary restriction and
+// should be lifted.
+if (UnknownUse || NumDirectCalls != 1 ||
+ToBeReplacedStateMachineUses.size() != 2) {
+  {
+auto Remark = [&](OptimizationRemark OR) {
+  return OR << "Parallel region "
+<< ore::NV("OpenMPParallelRegion", F->getName()) << " has "
+<< (UnknownUse ? "unknown" : "unexpected")
+<< " uses; will not attempt to rewrite the state machine.";
+};
+emitRemarkOnFunction(F, "OpenMPParallelRegionInNonSPMD", Remark);
+  }
   continue;
+}
 
 // Even if we have __kmpc_kernel_prepare_parallel calls, we (for now) give
 // up if the function is not called from a unique kernel.
 Kernel K = getUniqueKernelFor(*F);
-if (!K)
+if (!K) {
+  {
+auto Remark = [&](OptimizationRemark OR) {
+  return OR << "Parallel region "
+<< ore::NV("OpenMPParallelRegion", F->getName())
+<< " is not known to be called from a single target region "
+   "only, maybe the surrounding function has external "
+   "linkage?; "
+   "will not attempt to rewrite the state machine use.";
+};
+emitRemarkOnFunction(F, "OpenMPParallelRegionInMultipleKernesl",
+ Remark);
+  }
   continue;
+}
 
 // We now know F is a parallel body function called only from the kernel K.
 // We also identified the state machine uses in which we replace the
 // function pointer by a new global symbol for identification purposes. This
 // ensures only direct calls to the function are left.
 
+{
+  auto Remark = [&](OptimizationRemark OR) {
+return OR << "Replace state machine uses of parallel region "
+  << ore::NV("OpenMPParallelRegion", F->getName())
+  << " called from kernel "
+  << ore::NV("OpenMPParallelRegionKernel", K->getName()) << ".";
+  };
+  emitRemarkOnFunction(F, "OpenMPParallelRegionInNonSPMD", Remark);
+}
+
 Module  = *F->getParent();
 Type *Int8Ty = Type::getInt8Ty(M.getContext());
 
Index: clang/test/OpenMP/remarks_parallel_in_target_state_machine.c
===
--- /dev/null
+++ clang/test/OpenMP/remarks_parallel_in_target_state_machine.c
@@ -0,0 +1,33 @@
+// RUN: %clang_cc1 -verify=host -Rpass=openmp -fopenmp -x c++ -triple powerpc64le-unknown-unknown -fopenmp-targets=nvptx64-nvidia-cuda -emit-llvm-bc %s -o %t-ppc-host.bc
+// RUN: %clang_cc1 -verify  -Rpass=openmp -fopenmp -O2 -x c++ -triple nvptx64-unknown-unknown -fopenmp-targets=nvptx64-nvidia-cuda -emit-llvm %s -fopenmp-is-device -fopenmp-host-ir-file-path %t-ppc-host.bc -o 

[PATCH] D83707: [OpenMP][NFC] Emit remarks during GPU state machine optimization

2020-07-13 Thread Ye Luo via Phabricator via cfe-commits
ye-luo added inline comments.



Comment at: clang/test/OpenMP/remarks_parallel_in_target_state_machine.c:12
+#pragma omp parallel // #1
+// expected-remark@#1 {{Found parallel region that is called through a 
state machine__omp_outlined__2_wrapper in non-SPMD target region. This can lead 
to excessive register usage in unrelated kernels in the same translation unit 
due to spurious call edges assumed by ptxas.}}
+// expected-remark@#1 {{Parallel region __omp_outlined__2_wrapper is not 
known to be called from a single target region only, maybe the surrounding 
function has external linkage?; will not attempt to rewrite the state machine 
use.}}

Add a space "machine__omp_outlined__2_wrapper" to "machine 
__omp_outlined__2_wrapper"


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D83707



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


[PATCH] D83494: [libFuzzer] Link libFuzzer's own interceptors when other compiler runtimes are not linked.

2020-07-13 Thread Dokyung Song via Phabricator via cfe-commits
dokyungs added a comment.

In D83494#2148043 , @hctim wrote:

> In D83494#2147608 , @dokyungs wrote:
>
> > Builtin libfunc optimizations may transform memcmp and strcmp-like 
> > functions. To disable such optimizations, -fno-builtin= flag was 
> > additionally added in compiling new test cases. FWIW, the original test 
> > cases didn't require such flags since other sanitizers including ASan 
> > disables those optimizations in their LLVM pass by dropping libfunc 
> > attribute in the call instructions.
>
>
> It sounds like we need to add `-fno-builtin` in the clang driver when 
> building with sancov as well. Otherwise, users won't get any benefit of this 
> patch without doing `clang++ -fsanitize=fuzzer my_fuzz_target.cpp 
> -fno-builtin-strstr -fno-builtin-strncmp  -fno-builtin-strcmp  
> -fno-builtin-memcmp`?


Right. Apparently with `-O2` many calls to `memcmp`-like functions are removed. 
I just wondered, though, what makes more sense: disabling such optimization 
when building (i) with sancov, or (ii) with `-fsanitize=fuzzer`? If we go for 
(i), would it make sense to do it in the SanitizerCoverage module pass like 
other sanitizers do? What do you think? Also, can it be addressed in a 
follow-up patch?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D83494



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


[PATCH] D83592: [Parser] Add comment to skipped regions

2020-07-13 Thread Zequan Wu via Phabricator via cfe-commits
zequanwu added a comment.

In D83592#2147881 , @hans wrote:

> > Not sure if this is good idea to untrack comments, it breaks many tests 
> > under CoverageMapping.
>
> I didn't look, but I'm surprised there are many coverage tests that have 
> comments in them. If the comments are not important for those tests, maybe 
> they could be removed? As long as we keep one that tracks the intended 
> behavior of coverage on comments.


The comments in those coverage tests are used for FileCheck, like `//CHECK::`. 
So, we can't remove those ones.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D83592



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


[PATCH] D83592: [Parser] Add comment to skipped regions

2020-07-13 Thread Zequan Wu via Phabricator via cfe-commits
zequanwu added inline comments.
Herald added a subscriber: wuzish.



Comment at: clang/lib/Parse/Parser.cpp:37
   bool HandleComment(Preprocessor , SourceRange Comment) override {
+PP.getPPCallbacks()->SourceRangeSkipped(Comment, Comment.getEnd());
 S.ActOnComment(Comment);

hans wrote:
> I don't think this is the right way to do it. It seems this callback is 
> intended for #if macros that exclude part of the file from preprocessing.
I believe we want to classify comments as `SkippedRegion`, 
https://github.com/llvm/llvm-project/blob/master/llvm/include/llvm/ProfileData/Coverage/CoverageMapping.h#L217.
 
Added a new method `CommentSkipped` to add comment range to skipped ranges. 


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D83592



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


[PATCH] D83592: [Parser] Add comment to skipped regions

2020-07-13 Thread Zequan Wu via Phabricator via cfe-commits
zequanwu updated this revision to Diff 277518.
zequanwu marked an inline comment as done.
zequanwu added a comment.
Herald added subscribers: kbarton, nemanjai.

Classfiying comments as `SkippedRegion`, 
https://github.com/llvm/llvm-project/blob/master/llvm/include/llvm/ProfileData/Coverage/CoverageMapping.h#L217
This will result overlapping `SkippedRegion` for comments and macro. Maybe, we 
shuold merge the overlapped `SkippedRegion` at the end.
Example:

  File 0, 1:12 -> 6:2 = #0
   Skipped,File 0, 2:3 -> 4:9 = 0
   Skipped,File 0, 2:15 -> 2:25 = 0
 1|  1|int main() {
 2|   |  #ifdef TEST // comment
 3|   |  int x = 1;
 4|   |  #endif
 5|  1|  return 0;
 6|  1|}


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D83592

Files:
  clang/include/clang/Lex/PPCallbacks.h
  clang/lib/CodeGen/CoverageMappingGen.cpp
  clang/lib/CodeGen/CoverageMappingGen.h
  clang/lib/Parse/Parser.cpp


Index: clang/lib/Parse/Parser.cpp
===
--- clang/lib/Parse/Parser.cpp
+++ clang/lib/Parse/Parser.cpp
@@ -34,6 +34,7 @@
   explicit ActionCommentHandler(Sema ) : S(S) { }
 
   bool HandleComment(Preprocessor , SourceRange Comment) override {
+PP.getPPCallbacks()->CommentSkipped(Comment);
 S.ActOnComment(Comment);
 return false;
   }
Index: clang/lib/CodeGen/CoverageMappingGen.h
===
--- clang/lib/CodeGen/CoverageMappingGen.h
+++ clang/lib/CodeGen/CoverageMappingGen.h
@@ -38,6 +38,8 @@
   ArrayRef getSkippedRanges() const { return SkippedRanges; }
 
   void SourceRangeSkipped(SourceRange Range, SourceLocation EndifLoc) override;
+
+  void CommentSkipped(SourceRange Range) override;
 };
 
 namespace CodeGen {
Index: clang/lib/CodeGen/CoverageMappingGen.cpp
===
--- clang/lib/CodeGen/CoverageMappingGen.cpp
+++ clang/lib/CodeGen/CoverageMappingGen.cpp
@@ -39,6 +39,10 @@
   SkippedRanges.push_back(Range);
 }
 
+void CoverageSourceInfo::CommentSkipped(SourceRange Range) {
+  SkippedRanges.push_back(Range);
+}
+
 namespace {
 
 /// A region of source code that can be mapped to a counter.
Index: clang/include/clang/Lex/PPCallbacks.h
===
--- clang/include/clang/Lex/PPCallbacks.h
+++ clang/include/clang/Lex/PPCallbacks.h
@@ -319,6 +319,10 @@
   virtual void SourceRangeSkipped(SourceRange Range, SourceLocation EndifLoc) {
   }
 
+  /// Hood called when the source range is comment, which should be skipped.
+  /// \param Range The SourceRange that is comment.
+  virtual void CommentSkipped(SourceRange Range) {}
+
   enum ConditionValueKind {
 CVK_NotEvaluated, CVK_False, CVK_True
   };
@@ -565,6 +569,11 @@
 Second->SourceRangeSkipped(Range, EndifLoc);
   }
 
+  void CommentSkipped(SourceRange Range) override {
+First->CommentSkipped(Range);
+Second->CommentSkipped(Range);
+  }
+
   /// Hook called whenever an \#if is seen.
   void If(SourceLocation Loc, SourceRange ConditionRange,
   ConditionValueKind ConditionValue) override {


Index: clang/lib/Parse/Parser.cpp
===
--- clang/lib/Parse/Parser.cpp
+++ clang/lib/Parse/Parser.cpp
@@ -34,6 +34,7 @@
   explicit ActionCommentHandler(Sema ) : S(S) { }
 
   bool HandleComment(Preprocessor , SourceRange Comment) override {
+PP.getPPCallbacks()->CommentSkipped(Comment);
 S.ActOnComment(Comment);
 return false;
   }
Index: clang/lib/CodeGen/CoverageMappingGen.h
===
--- clang/lib/CodeGen/CoverageMappingGen.h
+++ clang/lib/CodeGen/CoverageMappingGen.h
@@ -38,6 +38,8 @@
   ArrayRef getSkippedRanges() const { return SkippedRanges; }
 
   void SourceRangeSkipped(SourceRange Range, SourceLocation EndifLoc) override;
+
+  void CommentSkipped(SourceRange Range) override;
 };
 
 namespace CodeGen {
Index: clang/lib/CodeGen/CoverageMappingGen.cpp
===
--- clang/lib/CodeGen/CoverageMappingGen.cpp
+++ clang/lib/CodeGen/CoverageMappingGen.cpp
@@ -39,6 +39,10 @@
   SkippedRanges.push_back(Range);
 }
 
+void CoverageSourceInfo::CommentSkipped(SourceRange Range) {
+  SkippedRanges.push_back(Range);
+}
+
 namespace {
 
 /// A region of source code that can be mapped to a counter.
Index: clang/include/clang/Lex/PPCallbacks.h
===
--- clang/include/clang/Lex/PPCallbacks.h
+++ clang/include/clang/Lex/PPCallbacks.h
@@ -319,6 +319,10 @@
   virtual void SourceRangeSkipped(SourceRange Range, SourceLocation EndifLoc) {
   }
 
+  /// Hood called when the source range is comment, which should be skipped.
+  /// \param Range The SourceRange that is comment.

[PATCH] D83707: [OpenMP][NFC] Emit remarks during GPU state machine optimization

2020-07-13 Thread Johannes Doerfert via Phabricator via cfe-commits
jdoerfert created this revision.
jdoerfert added reviewers: jhuber6, fghanim, JonChesterfield, grokos, 
AndreyChurbanov, ye-luo, tianshilei1992, ggeorgakoudis.
Herald added subscribers: llvm-commits, cfe-commits, sstefan1, guansong, bollu, 
hiraditya, yaxunl.
Herald added projects: clang, LLVM.

Since D83271  we can optimize the GPU state 
machine to avoid spurious
call edges that increase the register usage of kernels. With this patch
we inform the user why and if this optimization is happening and when it
is not.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D83707

Files:
  clang/test/OpenMP/remarks_parallel_in_target_state_machine.c
  llvm/lib/Transforms/IPO/OpenMPOpt.cpp

Index: llvm/lib/Transforms/IPO/OpenMPOpt.cpp
===
--- llvm/lib/Transforms/IPO/OpenMPOpt.cpp
+++ llvm/lib/Transforms/IPO/OpenMPOpt.cpp
@@ -1033,6 +1033,7 @@
 // Check if the function is uses in a __kmpc_kernel_prepare_parallel call at
 // all.
 bool UnknownUse = false;
+bool KernelPrepareUse = false;
 unsigned NumDirectCalls = 0;
 
 SmallVector ToBeReplacedStateMachineUses;
@@ -1049,31 +1050,81 @@
   }
   if (OpenMPOpt::getCallIfRegularCall(*U.getUser(),
   )) {
+KernelPrepareUse = true;
 ToBeReplacedStateMachineUses.push_back();
 return;
   }
   UnknownUse = true;
 });
 
-// If this ever hits, we should investigate.
-if (UnknownUse || NumDirectCalls != 1)
+// Do not emit a remark if we haven't seen a __kmpc_kernel_prepare_parallel
+// use.
+if (!KernelPrepareUse)
   continue;
 
-// TODO: This is not a necessary restriction and should be lifted.
-if (ToBeReplacedStateMachineUses.size() != 2)
+{
+  auto Remark = [&](OptimizationRemark OR) {
+return OR
+   << "Found parallel region that is called through a state machine"
+   << ore::NV("OpenMPParallelRegion", F->getName())
+   << " in non-SPMD target region. This can lead to excessive "
+  "register usage in unrelated kernels in the same translation "
+  "unit due to spurious call edges assumed by ptxas.";
+  };
+  emitRemarkOnFunction(F, "OpenMPParallelRegionInNonSPMD", Remark);
+}
+
+// If this ever hits, we should investigate.
+// TODO: Checking the number of uses is not a necessary restriction and
+// should be lifted.
+if (UnknownUse || NumDirectCalls != 1 ||
+ToBeReplacedStateMachineUses.size() != 2) {
+  {
+auto Remark = [&](OptimizationRemark OR) {
+  return OR << "Parallel region "
+<< ore::NV("OpenMPParallelRegion", F->getName()) << " has "
+<< (UnknownUse ? "unknown" : "unexpected")
+<< " uses; will not attempt to rewrite the state machine.";
+};
+emitRemarkOnFunction(F, "OpenMPParallelRegionInNonSPMD", Remark);
+  }
   continue;
+}
 
 // Even if we have __kmpc_kernel_prepare_parallel calls, we (for now) give
 // up if the function is not called from a unique kernel.
 Kernel K = getUniqueKernelFor(*F);
-if (!K)
+if (!K) {
+  {
+auto Remark = [&](OptimizationRemark OR) {
+  return OR << "Parallel region "
+<< ore::NV("OpenMPParallelRegion", F->getName())
+<< " is not known to be called from a single target region "
+   "only, maybe the surrounding function has external "
+   "linkage?; "
+   "will not attempt to rewrite the state machine use.";
+};
+emitRemarkOnFunction(F, "OpenMPParallelRegionInMultipleKernesl",
+ Remark);
+  }
   continue;
+}
 
 // We now know F is a parallel body function called only from the kernel K.
 // We also identified the state machine uses in which we replace the
 // function pointer by a new global symbol for identification purposes. This
 // ensures only direct calls to the function are left.
 
+{
+  auto Remark = [&](OptimizationRemark OR) {
+return OR << "Replace state machine uses of parallel region "
+  << ore::NV("OpenMPParallelRegion", F->getName())
+  << " called from kernel "
+  << ore::NV("OpenMPParallelRegionKernel", K->getName()) << ".";
+  };
+  emitRemarkOnFunction(F, "OpenMPParallelRegionInNonSPMD", Remark);
+}
+
 Module  = *F->getParent();
 Type *Int8Ty = Type::getInt8Ty(M.getContext());
 
Index: clang/test/OpenMP/remarks_parallel_in_target_state_machine.c
===
--- /dev/null
+++ clang/test/OpenMP/remarks_parallel_in_target_state_machine.c
@@ -0,0 +1,38 @@
+// RUN: %clang_cc1

[clang-tools-extra] 9d3e9a3 - [clangd] Remove const_cast. NFC

2020-07-13 Thread Sam McCall via cfe-commits

Author: Sam McCall
Date: 2020-07-13T20:44:11+02:00
New Revision: 9d3e9a3e3c10cf7ff961df8e107c7cb0e1bc447c

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

LOG: [clangd] Remove const_cast. NFC

Added: 


Modified: 
clang-tools-extra/clangd/CompileCommands.cpp
clang-tools-extra/clangd/Config.h

Removed: 




diff  --git a/clang-tools-extra/clangd/CompileCommands.cpp 
b/clang-tools-extra/clangd/CompileCommands.cpp
index 0b27e0e3e828..4b6955576942 100644
--- a/clang-tools-extra/clangd/CompileCommands.cpp
+++ b/clang-tools-extra/clangd/CompileCommands.cpp
@@ -183,8 +183,7 @@ CommandMangler CommandMangler::forTests() {
 }
 
 void CommandMangler::adjust(std::vector ) const {
-  // FIXME: remove const_cast once unique_function is const-compatible.
-  for (auto  : const_cast(Config::current()).CompileFlags.Edits)
+  for (auto  : Config::current().CompileFlags.Edits)
 Edit(Cmd);
 
   // Check whether the flag exists, either as -flag or -flag=*

diff  --git a/clang-tools-extra/clangd/Config.h 
b/clang-tools-extra/clangd/Config.h
index 878c9e8549b5..d2c3ef37abd5 100644
--- a/clang-tools-extra/clangd/Config.h
+++ b/clang-tools-extra/clangd/Config.h
@@ -52,8 +52,8 @@ struct Config {
   /// Controls how the compile command for the current file is determined.
   struct {
 // Edits to apply to the compile command, in sequence.
-// FIXME: these functions need to be const-callable. For now, const_cast.
-std::vector &)>> Edits;
+std::vector &) const>>
+Edits;
   } CompileFlags;
 };
 



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


[PATCH] D83705: [clangd] Config: CompileFlags.Remove

2020-07-13 Thread Sam McCall via Phabricator via cfe-commits
sammccall created this revision.
sammccall added a reviewer: hokein.
Herald added subscribers: cfe-commits, usaxena95, kadircet, arphaman, jkorous, 
MaskRay, ilya-biryukov.
Herald added a project: clang.

While here, add documentation to CompileFlags and CompileFlags.Add.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D83705

Files:
  clang-tools-extra/clangd/CompileCommands.h
  clang-tools-extra/clangd/ConfigCompile.cpp
  clang-tools-extra/clangd/ConfigFragment.h
  clang-tools-extra/clangd/ConfigYAML.cpp
  clang-tools-extra/clangd/unittests/ConfigCompileTests.cpp

Index: clang-tools-extra/clangd/unittests/ConfigCompileTests.cpp
===
--- clang-tools-extra/clangd/unittests/ConfigCompileTests.cpp
+++ clang-tools-extra/clangd/unittests/ConfigCompileTests.cpp
@@ -91,10 +91,12 @@
 
 TEST_F(ConfigCompileTests, CompileCommands) {
   Frag.CompileFlags.Add.emplace_back("-foo");
-  std::vector Argv = {"clang", "a.cc"};
+  Frag.CompileFlags.Remove.emplace_back("--include-directory=");
+  std::vector Argv = {"clang", "-I", "bar/", "a.cc"};
   EXPECT_TRUE(compileAndApply());
-  EXPECT_THAT(Conf.CompileFlags.Edits, SizeIs(1));
-  Conf.CompileFlags.Edits.front()(Argv);
+  EXPECT_THAT(Conf.CompileFlags.Edits, SizeIs(2));
+  for (auto  : Conf.CompileFlags.Edits)
+Edit(Argv);
   EXPECT_THAT(Argv, ElementsAre("clang", "a.cc", "-foo"));
 }
 
Index: clang-tools-extra/clangd/ConfigYAML.cpp
===
--- clang-tools-extra/clangd/ConfigYAML.cpp
+++ clang-tools-extra/clangd/ConfigYAML.cpp
@@ -63,6 +63,10 @@
   if (auto Values = scalarValues(N))
 F.Add = std::move(*Values);
 });
+Dict.handle("Remove", [&](Node ) {
+  if (auto Values = scalarValues(N))
+F.Remove = std::move(*Values);
+});
 Dict.parse(N);
   }
 
Index: clang-tools-extra/clangd/ConfigFragment.h
===
--- clang-tools-extra/clangd/ConfigFragment.h
+++ clang-tools-extra/clangd/ConfigFragment.h
@@ -117,9 +117,32 @@
   };
   IfBlock If;
 
+  /// Conditions in the CompileFlags block affect how a file is parsed.
+  ///
+  /// clangd emulates how clang would interpret a file.
+  /// By default, it behaves roughly like `clang $FILENAME`, but real projects
+  /// usually require setting the include path (with the `-I` flag), defining
+  /// preprocessor symbols, configuring warnings etc.
+  /// Often, a compilation database specifies these compile commands. clangd
+  /// searches for compile_commands.json in parents of the source file.
+  ///
+  /// This section modifies how the compile command is constructed.
   struct CompileFlagsBlock {
+/// List of flags to append to the compile command.
 std::vector> Add;
-  } CompileFlags;
+/// List of flags to remove from the compile command.
+///
+/// - If the value is a recognized clang flag (like "-I") then it will be
+///   removed along with any arguments. Synonyms like --include-dir= wil
+///   also be removed.
+/// - Otherwise, if the value ends in * (like "-DFOO=*") then any argument
+///   with the prefix wil be removed.
+/// - Otherwise any argument exactly matching the value is removed.
+///
+/// In all cases, -Xclang is also removed where needed.
+std::vector> Remove;
+  };
+  CompileFlagsBlock CompileFlags;
 };
 
 } // namespace config
Index: clang-tools-extra/clangd/ConfigCompile.cpp
===
--- clang-tools-extra/clangd/ConfigCompile.cpp
+++ clang-tools-extra/clangd/ConfigCompile.cpp
@@ -23,6 +23,7 @@
 //
 //===--===//
 
+#include "CompileCommands.h"
 #include "Config.h"
 #include "ConfigFragment.h"
 #include "support/Logger.h"
@@ -122,6 +123,19 @@
   }
 
   void compile(Fragment::CompileFlagsBlock &) {
+if (!F.Remove.empty()) {
+  auto Remove = std::make_shared();
+  for (auto  : F.Remove)
+Remove->strip(*A);
+  Out.Apply.push_back([Remove(std::shared_ptr(
+  std::move(Remove)))](Config ) {
+C.CompileFlags.Edits.push_back(
+[Remove](std::vector ) {
+  Remove->process(Args);
+});
+  });
+}
+
 if (!F.Add.empty()) {
   std::vector Add;
   for (auto  : F.Add)
Index: clang-tools-extra/clangd/CompileCommands.h
===
--- clang-tools-extra/clangd/CompileCommands.h
+++ clang-tools-extra/clangd/CompileCommands.h
@@ -66,6 +66,12 @@
 // The table-building strategy may not make sense outside clangd.
 class ArgStripper {
 public:
+  ArgStripper() = default;
+  ArgStripper(ArgStripper &&) = default;
+  ArgStripper(const ArgStripper &) = delete;
+  ArgStripper =(ArgStripper &&) = default;
+  ArgStripper =(const ArgStripper &) = delete;
+
   // 

[PATCH] D83494: [libFuzzer] Link libFuzzer's own interceptors when other compiler runtimes are not linked.

2020-07-13 Thread Mitch Phillips via Phabricator via cfe-commits
hctim added a comment.

In D83494#2147608 , @dokyungs wrote:

> Builtin libfunc optimizations may transform memcmp and strcmp-like functions. 
> To disable such optimizations, -fno-builtin= flag was additionally added in 
> compiling new test cases. FWIW, the original test cases didn't require such 
> flags since other sanitizers including ASan disables those optimizations in 
> their LLVM pass by dropping libfunc attribute in the call instructions.


It sounds like we need to add `-fno-builtin` in the clang driver when building 
with sancov as well. Otherwise, users won't get any benefit of this patch 
without doing `clang++ -fsanitize=fuzzer my_fuzz_target.cpp -fno-builtin-strstr 
-fno-builtin-strncmp  -fno-builtin-strcmp  -fno-builtin-memcmp`?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D83494



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


[PATCH] D81958: [clangd] Add library to semantically strip flags by name.

2020-07-13 Thread Sam McCall via Phabricator via cfe-commits
sammccall updated this revision to Diff 277508.
sammccall added a comment.

Sigh, last upload was supposed to be a new patch, not clobber this one.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D81958

Files:
  clang-tools-extra/clangd/CompileCommands.cpp
  clang-tools-extra/clangd/CompileCommands.h
  clang-tools-extra/clangd/unittests/CompileCommandsTests.cpp

Index: clang-tools-extra/clangd/unittests/CompileCommandsTests.cpp
===
--- clang-tools-extra/clangd/unittests/CompileCommandsTests.cpp
+++ clang-tools-extra/clangd/unittests/CompileCommandsTests.cpp
@@ -207,6 +207,120 @@
   EXPECT_THAT(Cmd, ElementsAre(_, "FOO.CC", "--hello", "-fsyntax-only"));
 }
 
+static std::string strip(llvm::StringRef Arg, llvm::StringRef Argv) {
+  llvm::SmallVector Parts;
+  llvm::SplitString(Argv, Parts);
+  std::vector Args = {Parts.begin(), Parts.end()};
+  ArgStripper S;
+  S.strip(Arg);
+  S.process(Args);
+  return llvm::join(Args, " ");
+}
+
+TEST(ArgStripperTest, Spellings) {
+  // May use alternate prefixes.
+  EXPECT_EQ(strip("-pedantic", "clang -pedantic foo.cc"), "clang foo.cc");
+  EXPECT_EQ(strip("-pedantic", "clang --pedantic foo.cc"), "clang foo.cc");
+  EXPECT_EQ(strip("--pedantic", "clang -pedantic foo.cc"), "clang foo.cc");
+  EXPECT_EQ(strip("--pedantic", "clang --pedantic foo.cc"), "clang foo.cc");
+  // May use alternate names.
+  EXPECT_EQ(strip("-x", "clang -x c++ foo.cc"), "clang foo.cc");
+  EXPECT_EQ(strip("-x", "clang --language=c++ foo.cc"), "clang foo.cc");
+  EXPECT_EQ(strip("--language=", "clang -x c++ foo.cc"), "clang foo.cc");
+  EXPECT_EQ(strip("--language=", "clang --language=c++ foo.cc"),
+"clang foo.cc");
+}
+
+TEST(ArgStripperTest, UnknownFlag) {
+  EXPECT_EQ(strip("-xyzzy", "clang -xyzzy foo.cc"), "clang foo.cc");
+  EXPECT_EQ(strip("-xyz*", "clang -xyzzy foo.cc"), "clang foo.cc");
+  EXPECT_EQ(strip("-xyzzy", "clang -Xclang -xyzzy foo.cc"), "clang foo.cc");
+}
+
+TEST(ArgStripperTest, Xclang) {
+  // Flags may be -Xclang escaped.
+  EXPECT_EQ(strip("-ast-dump", "clang -Xclang -ast-dump foo.cc"),
+"clang foo.cc");
+  // Args may be -Xclang escaped.
+  EXPECT_EQ(strip("-add-plugin", "clang -Xclang -add-plugin -Xclang z foo.cc"),
+"clang foo.cc");
+}
+
+TEST(ArgStripperTest, ClangCL) {
+  // /I is a synonym for -I in clang-cl mode only.
+  // Not stripped by default.
+  EXPECT_EQ(strip("-I", "clang -I /usr/inc /Interesting/file.cc"),
+"clang /Interesting/file.cc");
+  // Stripped when invoked as clang-cl.
+  EXPECT_EQ(strip("-I", "clang-cl -I /usr/inc /Interesting/file.cc"),
+"clang-cl");
+  // Stripped when invoked as CL.EXE
+  EXPECT_EQ(strip("-I", "CL.EXE -I /usr/inc /Interesting/file.cc"), "CL.EXE");
+  // Stripped when passed --driver-mode=cl.
+  EXPECT_EQ(strip("-I", "cc -I /usr/inc /Interesting/file.cc --driver-mode=cl"),
+"cc --driver-mode=cl");
+}
+
+TEST(ArgStripperTest, ArgStyles) {
+  // Flag
+  EXPECT_EQ(strip("-Qn", "clang -Qn foo.cc"), "clang foo.cc");
+  EXPECT_EQ(strip("-Qn", "clang -QnZ foo.cc"), "clang -QnZ foo.cc");
+  // Joined
+  EXPECT_EQ(strip("-std=", "clang -std= foo.cc"), "clang foo.cc");
+  EXPECT_EQ(strip("-std=", "clang -std=c++11 foo.cc"), "clang foo.cc");
+  // Separate
+  EXPECT_EQ(strip("-mllvm", "clang -mllvm X foo.cc"), "clang foo.cc");
+  EXPECT_EQ(strip("-mllvm", "clang -mllvmX foo.cc"), "clang -mllvmX foo.cc");
+  // RemainingArgsJoined
+  EXPECT_EQ(strip("/link", "clang-cl /link b c d foo.cc"), "clang-cl");
+  EXPECT_EQ(strip("/link", "clang-cl /linka b c d foo.cc"), "clang-cl");
+  // CommaJoined
+  EXPECT_EQ(strip("-Wl,", "clang -Wl,x,y foo.cc"), "clang foo.cc");
+  EXPECT_EQ(strip("-Wl,", "clang -Wl, foo.cc"), "clang foo.cc");
+  // MultiArg
+  EXPECT_EQ(strip("-segaddr", "clang -segaddr a b foo.cc"), "clang foo.cc");
+  EXPECT_EQ(strip("-segaddr", "clang -segaddra b foo.cc"),
+"clang -segaddra b foo.cc");
+  // JoinedOrSeparate
+  EXPECT_EQ(strip("-G", "clang -GX foo.cc"), "clang foo.cc");
+  EXPECT_EQ(strip("-G", "clang -G X foo.cc"), "clang foo.cc");
+  // JoinedAndSeparate
+  EXPECT_EQ(strip("-plugin-arg-", "clang -cc1 -plugin-arg-X Y foo.cc"),
+"clang -cc1 foo.cc");
+  EXPECT_EQ(strip("-plugin-arg-", "clang -cc1 -plugin-arg- Y foo.cc"),
+"clang -cc1 foo.cc");
+}
+
+TEST(ArgStripperTest, EndOfList) {
+  // When we hit the end-of-args prematurely, we don't crash.
+  // We consume the incomplete args if we've matched the target option.
+  EXPECT_EQ(strip("-I", "clang -Xclang"), "clang -Xclang");
+  EXPECT_EQ(strip("-I", "clang -Xclang -I"), "clang");
+  EXPECT_EQ(strip("-I", "clang -I -Xclang"), "clang");
+  EXPECT_EQ(strip("-I", "clang -I"), "clang");
+}
+
+TEST(ArgStripperTest, Multiple) {
+  ArgStripper S;
+  S.strip("-o");
+  S.strip("-c");
+  std::vector Args = {"clang", "-o", 

[PATCH] D81958: [clangd] Add library to semantically strip flags by name.

2020-07-13 Thread Sam McCall via Phabricator via cfe-commits
sammccall updated this revision to Diff 277507.
sammccall added a comment.

[clangd] Config: CompileFlags.Remove

While here, add documentation to CompileFlags and CompileFlags.Add.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D81958

Files:
  clang-tools-extra/clangd/CompileCommands.cpp
  clang-tools-extra/clangd/CompileCommands.h
  clang-tools-extra/clangd/ConfigCompile.cpp
  clang-tools-extra/clangd/ConfigFragment.h
  clang-tools-extra/clangd/ConfigYAML.cpp
  clang-tools-extra/clangd/unittests/CompileCommandsTests.cpp
  clang-tools-extra/clangd/unittests/ConfigCompileTests.cpp

Index: clang-tools-extra/clangd/unittests/ConfigCompileTests.cpp
===
--- clang-tools-extra/clangd/unittests/ConfigCompileTests.cpp
+++ clang-tools-extra/clangd/unittests/ConfigCompileTests.cpp
@@ -91,10 +91,12 @@
 
 TEST_F(ConfigCompileTests, CompileCommands) {
   Frag.CompileFlags.Add.emplace_back("-foo");
-  std::vector Argv = {"clang", "a.cc"};
+  Frag.CompileFlags.Remove.emplace_back("--include-directory=");
+  std::vector Argv = {"clang", "-I", "bar/", "a.cc"};
   EXPECT_TRUE(compileAndApply());
-  EXPECT_THAT(Conf.CompileFlags.Edits, SizeIs(1));
-  Conf.CompileFlags.Edits.front()(Argv);
+  EXPECT_THAT(Conf.CompileFlags.Edits, SizeIs(2));
+  for (auto  : Conf.CompileFlags.Edits)
+Edit(Argv);
   EXPECT_THAT(Argv, ElementsAre("clang", "a.cc", "-foo"));
 }
 
Index: clang-tools-extra/clangd/unittests/CompileCommandsTests.cpp
===
--- clang-tools-extra/clangd/unittests/CompileCommandsTests.cpp
+++ clang-tools-extra/clangd/unittests/CompileCommandsTests.cpp
@@ -207,6 +207,120 @@
   EXPECT_THAT(Cmd, ElementsAre(_, "FOO.CC", "--hello", "-fsyntax-only"));
 }
 
+static std::string strip(llvm::StringRef Arg, llvm::StringRef Argv) {
+  llvm::SmallVector Parts;
+  llvm::SplitString(Argv, Parts);
+  std::vector Args = {Parts.begin(), Parts.end()};
+  ArgStripper S;
+  S.strip(Arg);
+  S.process(Args);
+  return llvm::join(Args, " ");
+}
+
+TEST(ArgStripperTest, Spellings) {
+  // May use alternate prefixes.
+  EXPECT_EQ(strip("-pedantic", "clang -pedantic foo.cc"), "clang foo.cc");
+  EXPECT_EQ(strip("-pedantic", "clang --pedantic foo.cc"), "clang foo.cc");
+  EXPECT_EQ(strip("--pedantic", "clang -pedantic foo.cc"), "clang foo.cc");
+  EXPECT_EQ(strip("--pedantic", "clang --pedantic foo.cc"), "clang foo.cc");
+  // May use alternate names.
+  EXPECT_EQ(strip("-x", "clang -x c++ foo.cc"), "clang foo.cc");
+  EXPECT_EQ(strip("-x", "clang --language=c++ foo.cc"), "clang foo.cc");
+  EXPECT_EQ(strip("--language=", "clang -x c++ foo.cc"), "clang foo.cc");
+  EXPECT_EQ(strip("--language=", "clang --language=c++ foo.cc"),
+"clang foo.cc");
+}
+
+TEST(ArgStripperTest, UnknownFlag) {
+  EXPECT_EQ(strip("-xyzzy", "clang -xyzzy foo.cc"), "clang foo.cc");
+  EXPECT_EQ(strip("-xyz*", "clang -xyzzy foo.cc"), "clang foo.cc");
+  EXPECT_EQ(strip("-xyzzy", "clang -Xclang -xyzzy foo.cc"), "clang foo.cc");
+}
+
+TEST(ArgStripperTest, Xclang) {
+  // Flags may be -Xclang escaped.
+  EXPECT_EQ(strip("-ast-dump", "clang -Xclang -ast-dump foo.cc"),
+"clang foo.cc");
+  // Args may be -Xclang escaped.
+  EXPECT_EQ(strip("-add-plugin", "clang -Xclang -add-plugin -Xclang z foo.cc"),
+"clang foo.cc");
+}
+
+TEST(ArgStripperTest, ClangCL) {
+  // /I is a synonym for -I in clang-cl mode only.
+  // Not stripped by default.
+  EXPECT_EQ(strip("-I", "clang -I /usr/inc /Interesting/file.cc"),
+"clang /Interesting/file.cc");
+  // Stripped when invoked as clang-cl.
+  EXPECT_EQ(strip("-I", "clang-cl -I /usr/inc /Interesting/file.cc"),
+"clang-cl");
+  // Stripped when invoked as CL.EXE
+  EXPECT_EQ(strip("-I", "CL.EXE -I /usr/inc /Interesting/file.cc"), "CL.EXE");
+  // Stripped when passed --driver-mode=cl.
+  EXPECT_EQ(strip("-I", "cc -I /usr/inc /Interesting/file.cc --driver-mode=cl"),
+"cc --driver-mode=cl");
+}
+
+TEST(ArgStripperTest, ArgStyles) {
+  // Flag
+  EXPECT_EQ(strip("-Qn", "clang -Qn foo.cc"), "clang foo.cc");
+  EXPECT_EQ(strip("-Qn", "clang -QnZ foo.cc"), "clang -QnZ foo.cc");
+  // Joined
+  EXPECT_EQ(strip("-std=", "clang -std= foo.cc"), "clang foo.cc");
+  EXPECT_EQ(strip("-std=", "clang -std=c++11 foo.cc"), "clang foo.cc");
+  // Separate
+  EXPECT_EQ(strip("-mllvm", "clang -mllvm X foo.cc"), "clang foo.cc");
+  EXPECT_EQ(strip("-mllvm", "clang -mllvmX foo.cc"), "clang -mllvmX foo.cc");
+  // RemainingArgsJoined
+  EXPECT_EQ(strip("/link", "clang-cl /link b c d foo.cc"), "clang-cl");
+  EXPECT_EQ(strip("/link", "clang-cl /linka b c d foo.cc"), "clang-cl");
+  // CommaJoined
+  EXPECT_EQ(strip("-Wl,", "clang -Wl,x,y foo.cc"), "clang foo.cc");
+  EXPECT_EQ(strip("-Wl,", "clang -Wl, foo.cc"), "clang foo.cc");
+  // MultiArg
+  EXPECT_EQ(strip("-segaddr", "clang 

[clang] fdb6953 - [AST] Fix potential nullptr dereference in Expr::HasSideEffects

2020-07-13 Thread Jan Korous via cfe-commits

Author: Jan Korous
Date: 2020-07-13T11:08:51-07:00
New Revision: fdb69539bcd250f6e4f49197c9b8149a7542e3ff

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

LOG: [AST] Fix potential nullptr dereference in Expr::HasSideEffects

Array returned by LambdaExpr::capture_inits() can contain nullptrs.

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

Added: 
clang/unittests/AST/HasSideEffectsTest.cpp

Modified: 
clang/include/clang/AST/ExprCXX.h
clang/lib/AST/Expr.cpp
clang/unittests/AST/CMakeLists.txt

Removed: 




diff  --git a/clang/include/clang/AST/ExprCXX.h 
b/clang/include/clang/AST/ExprCXX.h
index 178f4db77061..6f0b68479b9d 100644
--- a/clang/include/clang/AST/ExprCXX.h
+++ b/clang/include/clang/AST/ExprCXX.h
@@ -1931,6 +1931,7 @@ class LambdaExpr final : public Expr,
 
   /// Const iterator that walks over the capture initialization
   /// arguments.
+  /// FIXME: This interface is prone to being used incorrectly.
   using const_capture_init_iterator = Expr *const *;
 
   /// Retrieve the initialization expressions for this lambda's captures.

diff  --git a/clang/lib/AST/Expr.cpp b/clang/lib/AST/Expr.cpp
index 343a271c3394..399e7e13c445 100644
--- a/clang/lib/AST/Expr.cpp
+++ b/clang/lib/AST/Expr.cpp
@@ -3629,7 +3629,7 @@ bool Expr::HasSideEffects(const ASTContext ,
   case LambdaExprClass: {
 const LambdaExpr *LE = cast(this);
 for (Expr *E : LE->capture_inits())
-  if (E->HasSideEffects(Ctx, IncludePossibleEffects))
+  if (E && E->HasSideEffects(Ctx, IncludePossibleEffects))
 return true;
 return false;
   }

diff  --git a/clang/unittests/AST/CMakeLists.txt 
b/clang/unittests/AST/CMakeLists.txt
index 2e750ac9ea92..185995d5b5a2 100644
--- a/clang/unittests/AST/CMakeLists.txt
+++ b/clang/unittests/AST/CMakeLists.txt
@@ -26,6 +26,7 @@ add_clang_unittest(ASTTests
   DeclTest.cpp
   EvaluateAsRValueTest.cpp
   ExternalASTSourceTest.cpp
+  HasSideEffectsTest.cpp
   NamedDeclPrinterTest.cpp
   RecursiveASTVisitorTest.cpp
   SizelessTypesTest.cpp

diff  --git a/clang/unittests/AST/HasSideEffectsTest.cpp 
b/clang/unittests/AST/HasSideEffectsTest.cpp
new file mode 100644
index ..842afd8d7a9c
--- /dev/null
+++ b/clang/unittests/AST/HasSideEffectsTest.cpp
@@ -0,0 +1,86 @@
+//===- unittest/AST/HasSideEffectsTest.cpp 
===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+
+#include "clang/AST/RecursiveASTVisitor.h"
+#include "clang/AST/ASTConsumer.h"
+#include "clang/AST/ASTContext.h"
+#include "clang/AST/Attr.h"
+#include "clang/Frontend/FrontendAction.h"
+#include "clang/Tooling/Tooling.h"
+#include "llvm/ADT/FunctionExtras.h"
+#include "llvm/ADT/STLExtras.h"
+#include "gmock/gmock.h"
+#include "gtest/gtest.h"
+#include 
+
+using namespace clang;
+
+namespace {
+class ProcessASTAction : public clang::ASTFrontendAction {
+public:
+  ProcessASTAction(llvm::unique_function Process)
+  : Process(std::move(Process)) {
+assert(this->Process);
+  }
+
+  std::unique_ptr CreateASTConsumer(CompilerInstance ,
+ StringRef InFile) {
+class Consumer : public ASTConsumer {
+public:
+  Consumer(llvm::function_ref Process)
+  : Process(Process) {}
+
+  void HandleTranslationUnit(ASTContext ) override { Process(Ctx); }
+
+private:
+  llvm::function_ref Process;
+};
+
+return std::make_unique(Process);
+  }
+
+private:
+  llvm::unique_function Process;
+};
+
+class RunHasSideEffects
+: public RecursiveASTVisitor {
+public:
+  RunHasSideEffects(ASTContext& Ctx)
+  : Ctx(Ctx) {}
+
+  bool VisitLambdaExpr(LambdaExpr *LE) {
+LE->HasSideEffects(Ctx);
+return true;
+  }
+
+  ASTContext& Ctx;
+};
+} // namespace
+
+TEST(HasSideEffectsTest, All) {
+  llvm::StringRef Code = R"cpp(
+void Test() {
+  int msize = 4;
+  float arr[msize];
+  [] {};
+}
+  )cpp";
+
+  ASSERT_NO_FATAL_FAILURE(
+clang::tooling::runToolOnCode(
+  std::make_unique(
+  [&](clang::ASTContext ) {
+  RunHasSideEffects Visitor(Ctx);
+  Visitor.TraverseAST(Ctx);
+  }
+  ),
+  Code)
+  );
+
+}



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


[PATCH] D83438: [AST] Fix potential nullptr dereference in Expr::HasSideEffects

2020-07-13 Thread Jan Korous via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rGfdb69539bcd2: [AST] Fix potential nullptr dereference in 
Expr::HasSideEffects (authored by jkorous).
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D83438

Files:
  clang/include/clang/AST/ExprCXX.h
  clang/lib/AST/Expr.cpp
  clang/unittests/AST/CMakeLists.txt
  clang/unittests/AST/HasSideEffectsTest.cpp

Index: clang/unittests/AST/HasSideEffectsTest.cpp
===
--- /dev/null
+++ clang/unittests/AST/HasSideEffectsTest.cpp
@@ -0,0 +1,86 @@
+//===- unittest/AST/HasSideEffectsTest.cpp ===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+
+#include "clang/AST/RecursiveASTVisitor.h"
+#include "clang/AST/ASTConsumer.h"
+#include "clang/AST/ASTContext.h"
+#include "clang/AST/Attr.h"
+#include "clang/Frontend/FrontendAction.h"
+#include "clang/Tooling/Tooling.h"
+#include "llvm/ADT/FunctionExtras.h"
+#include "llvm/ADT/STLExtras.h"
+#include "gmock/gmock.h"
+#include "gtest/gtest.h"
+#include 
+
+using namespace clang;
+
+namespace {
+class ProcessASTAction : public clang::ASTFrontendAction {
+public:
+  ProcessASTAction(llvm::unique_function Process)
+  : Process(std::move(Process)) {
+assert(this->Process);
+  }
+
+  std::unique_ptr CreateASTConsumer(CompilerInstance ,
+ StringRef InFile) {
+class Consumer : public ASTConsumer {
+public:
+  Consumer(llvm::function_ref Process)
+  : Process(Process) {}
+
+  void HandleTranslationUnit(ASTContext ) override { Process(Ctx); }
+
+private:
+  llvm::function_ref Process;
+};
+
+return std::make_unique(Process);
+  }
+
+private:
+  llvm::unique_function Process;
+};
+
+class RunHasSideEffects
+: public RecursiveASTVisitor {
+public:
+  RunHasSideEffects(ASTContext& Ctx)
+  : Ctx(Ctx) {}
+
+  bool VisitLambdaExpr(LambdaExpr *LE) {
+LE->HasSideEffects(Ctx);
+return true;
+  }
+
+  ASTContext& Ctx;
+};
+} // namespace
+
+TEST(HasSideEffectsTest, All) {
+  llvm::StringRef Code = R"cpp(
+void Test() {
+  int msize = 4;
+  float arr[msize];
+  [] {};
+}
+  )cpp";
+
+  ASSERT_NO_FATAL_FAILURE(
+clang::tooling::runToolOnCode(
+  std::make_unique(
+  [&](clang::ASTContext ) {
+  RunHasSideEffects Visitor(Ctx);
+  Visitor.TraverseAST(Ctx);
+  }
+  ),
+  Code)
+  );
+
+}
Index: clang/unittests/AST/CMakeLists.txt
===
--- clang/unittests/AST/CMakeLists.txt
+++ clang/unittests/AST/CMakeLists.txt
@@ -26,6 +26,7 @@
   DeclTest.cpp
   EvaluateAsRValueTest.cpp
   ExternalASTSourceTest.cpp
+  HasSideEffectsTest.cpp
   NamedDeclPrinterTest.cpp
   RecursiveASTVisitorTest.cpp
   SizelessTypesTest.cpp
Index: clang/lib/AST/Expr.cpp
===
--- clang/lib/AST/Expr.cpp
+++ clang/lib/AST/Expr.cpp
@@ -3629,7 +3629,7 @@
   case LambdaExprClass: {
 const LambdaExpr *LE = cast(this);
 for (Expr *E : LE->capture_inits())
-  if (E->HasSideEffects(Ctx, IncludePossibleEffects))
+  if (E && E->HasSideEffects(Ctx, IncludePossibleEffects))
 return true;
 return false;
   }
Index: clang/include/clang/AST/ExprCXX.h
===
--- clang/include/clang/AST/ExprCXX.h
+++ clang/include/clang/AST/ExprCXX.h
@@ -1931,6 +1931,7 @@
 
   /// Const iterator that walks over the capture initialization
   /// arguments.
+  /// FIXME: This interface is prone to being used incorrectly.
   using const_capture_init_iterator = Expr *const *;
 
   /// Retrieve the initialization expressions for this lambda's captures.
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D83701: [analyzer][tests] Add 5 more projects for testing

2020-07-13 Thread Valeriy Savchenko via Phabricator via cfe-commits
vsavchenko added a comment.
Herald added a subscriber: wuzish.

@NoQ, @Szelethus I included projects that you mentioned in a previous review.
@Szelethus it looks like **tmux** has quite a few of dependencies after all 


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D83701



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


[PATCH] D83702: [AIX]Generate debug info for static init related functions

2020-07-13 Thread Xiangling Liao via Phabricator via cfe-commits
Xiangling_L created this revision.
Xiangling_L added reviewers: hubert.reinterpretcast, yusra.syeda, jasonliu.
Herald added subscribers: cfe-commits, aprantl.
Herald added a project: clang.

Set the debug location for static init related functions on AIX(__dtor and 
__finalize) so we can generate valid debug info by invoking `-g` with clang or 
`-debug-info-kind=limited` with clang_cc1.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D83702

Files:
  clang/lib/CodeGen/CGDeclCXX.cpp
  clang/lib/CodeGen/ItaniumCXXABI.cpp
  clang/test/CodeGenCXX/aix-static-init-debug-info.cpp

Index: clang/test/CodeGenCXX/aix-static-init-debug-info.cpp
===
--- /dev/null
+++ clang/test/CodeGenCXX/aix-static-init-debug-info.cpp
@@ -0,0 +1,70 @@
+// RUN: %clang_cc1 -triple powerpc-ibm-aix-xcoff -emit-llvm -x c++ \
+// RUN: -debug-info-kind=limited -fno-use-cxa-atexit < %s | \
+// RUN:   FileCheck --check-prefixes=CHECK,CHECK64 %s
+
+// RUN: %clang_cc1 -triple powerpc64-ibm-aix-xcoff -emit-llvm -x c++ \
+// RUN: -debug-info-kind=limited -fno-use-cxa-atexit < %s | \
+// RUN:   FileCheck --check-prefixes=CHECK,CHECK64 %s
+
+int a = 0;
+
+class X {
+public:
+  X() {
+a = 1;
+  }
+  ~X() {
+a = -1;
+  }
+};
+
+X v;
+
+// CHECK: define internal void @__cxx_global_var_init() [[ATTR:#[0-9]+]] !dbg ![[DBGVAR19:[0-9]+]] {
+// CHECK: entry:
+// CHECK:   call void @_ZN1XC1Ev(%class.X* @v), !dbg ![[DBGVAR22:[0-9]+]]
+// CHECK:   %0 = call i32 @atexit(void ()* @__dtor_v) [[ATTR:#[0-9]+]], !dbg ![[DBGVAR22]]
+// CHECK:   ret void, !dbg ![[DBGVAR22]]
+// CHECK: }
+
+// CHECK: define internal void @__dtor_v() [[ATTR:#[0-9]+]] !dbg ![[DBGVAR34:[0-9]+]] {
+// CHECK: entry:
+// CHECK:   call void @_ZN1XD1Ev(%class.X* @v), !dbg ![[DBGVAR35:[0-9]+]]
+// CHECK:   ret void, !dbg ![[DBGVAR35]]
+// CHECK: }
+
+// CHECK: define internal void @__finalize_v() [[ATTR:#[0-9]+]] !dbg ![[DBGVAR36:[0-9]+]] {
+// CHECK: entry:
+// CHECK:   %0 = call i32 @unatexit(void ()* @__dtor_v) [[ATTR:#[0-9]+]], !dbg ![[DBGVAR38:[0-9]+]]
+// CHECK:   %needs_destruct = icmp eq i32 %0, 0, !dbg ![[DBGVAR38]]
+// CHECK:   br i1 %needs_destruct, label %destruct.call, label %destruct.end, !dbg ![[DBGVAR38]]
+
+// CHECK: destruct.call:
+// CHECK:   call void @__dtor_v(), !dbg ![[DBGVAR38]]
+// CHECK:   br label %destruct.end, !dbg ![[DBGVAR38]]
+
+// CHECK: destruct.end:
+// CHECK:   ret void, !dbg ![[DBGVAR38]]
+// CHECK: }
+
+// CHECK: define void @__sinit8000_clang_9da80ccf074143d177aee39644eda39d() [[ATTR:#[0-9]+]] !dbg ![[DBGVAR51:[0-9]+]] {
+// CHECK: entry:
+// CHECK:   call void @__cxx_global_var_init(), !dbg ![[DBGVAR52:[0-9]+]]
+// CHECK:   ret void
+// CHECK: }
+
+// CHECK: define void @__sterm8000_clang_9da80ccf074143d177aee39644eda39d() [[ATTR:#[0-9]+]] !dbg ![[DBGVAR53:[0-9]+]] {
+// CHECK: entry:
+// CHECK:   call void @__finalize_v(), !dbg ![[DBGVAR54:[0-9]+]]
+// CHECK:   ret void
+// CHECK: }
+
+
+// CHECK: ![[DBGVAR19]] = distinct !DISubprogram(name: "__cxx_global_var_init", scope: !{{[0-9]+}}, file: !{{[0-9]+}}, line: 21, type: !{{[0-9]+}}, scopeLine: 21, spFlags: DISPFlagLocalToUnit | DISPFlagDefinition, unit: !{{[0-9]+}}, retainedNodes:  !{{[0-9]+}})
+// CHECK: ![[DBGVAR22]] = !DILocation(line: 21, column: 3, scope: ![[DBGVAR19]])
+// CHECK: ![[DBGVAR36]] = distinct !DISubprogram(linkageName: "__finalize_v", scope: !{{[0-9]+}}, file: !{{[0-9]+}}, line: 21, type: !{{[0-9]+}}, scopeLine: 21, flags: DIFlagArtificial, spFlags: DISPFlagLocalToUnit | DISPFlagDefinition, unit: !{{[0-9]+}}, retainedNodes: !{{[0-9]+}})
+// CHECK: ![[DBGVAR38]] = !DILocation(line: 21, column: 3, scope: ![[DBGVAR36]])
+// CHECK: ![[DBGVAR51]] = distinct !DISubprogram(linkageName: "__sinit8000_clang_9da80ccf074143d177aee39644eda39d", scope: !{{[0-9]+}}, file: !{{[0-9]+}}, type: !{{[0-9]+}}, flags: DIFlagArtificial, spFlags: DISPFlagDefinition, unit: !{{[0-9]+}}, retainedNodes: !{{[0-9]+}})
+// CHECK: ![[DBGVAR52]] = !DILocation(line: 0, scope: ![[DBGVAR51]])
+// CHECK: ![[DBGVAR53]] = distinct !DISubprogram(linkageName: "__sterm8000_clang_9da80ccf074143d177aee39644eda39d", scope: !{{[0-9]+}}, file: !{{[0-9]+}}, type: !{{[0-9]+}}, flags: DIFlagArtificial, spFlags: DISPFlagDefinition, unit: !{{[0-9]+}}, retainedNodes: !{{[0-9]+}})
+// CHECK: ![[DBGVAR54]] = !DILocation(line: 0, scope: ![[DBGVAR53]])
Index: clang/lib/CodeGen/ItaniumCXXABI.cpp
===
--- clang/lib/CodeGen/ItaniumCXXABI.cpp
+++ clang/lib/CodeGen/ItaniumCXXABI.cpp
@@ -4567,7 +4567,8 @@
   CodeGenFunction CGF(CGM);
 
   CGF.StartFunction(GlobalDecl(), CGM.getContext().VoidTy, StermFinalizer, FI,
-FunctionArgList());
+FunctionArgList(), D.getLocation(),
+D.getInit()->getExprLoc());
 
   // The unatexit subroutine unregisters __dtor functions that were previously
   // registered by the atexit 

[PATCH] D83701: [analyzer][tests] Add 5 more projects for testing

2020-07-13 Thread Valeriy Savchenko via Phabricator via cfe-commits
vsavchenko created this revision.
vsavchenko added reviewers: NoQ, Szelethus, xazax.hun, dcoughlin.
Herald added subscribers: cfe-commits, sstefan1, ASDenysPetrov, Charusso, 
dkrupp, donat.nagy, mikhail.ramalho, a.sidorin, rnkovacs, szepet, 
baloghadamsoftware, kbarton, nemanjai.
Herald added a reviewer: jdoerfert.
Herald added a project: clang.

Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D83701

Files:
  clang/utils/analyzer/Dockerfile
  clang/utils/analyzer/entrypoint.py
  clang/utils/analyzer/projects/capnproto/cleanup_run_static_analyzer.sh
  clang/utils/analyzer/projects/capnproto/run_static_analyzer.cmd
  clang/utils/analyzer/projects/cppcheck/cleanup_run_static_analyzer.sh
  clang/utils/analyzer/projects/cppcheck/run_static_analyzer.cmd
  clang/utils/analyzer/projects/faiss/cleanup_run_static_analyzer.sh
  clang/utils/analyzer/projects/faiss/run_static_analyzer.cmd
  clang/utils/analyzer/projects/harfbuzz/cleanup_run_static_analyzer.sh
  clang/utils/analyzer/projects/harfbuzz/run_static_analyzer.cmd
  clang/utils/analyzer/projects/projects.json
  clang/utils/analyzer/projects/tmux/cleanup_run_static_analyzer.sh
  clang/utils/analyzer/projects/tmux/run_static_analyzer.cmd

Index: clang/utils/analyzer/projects/tmux/run_static_analyzer.cmd
===
--- /dev/null
+++ clang/utils/analyzer/projects/tmux/run_static_analyzer.cmd
@@ -0,0 +1,2 @@
+./autogen.sh
+./configure && make
Index: clang/utils/analyzer/projects/tmux/cleanup_run_static_analyzer.sh
===
--- /dev/null
+++ clang/utils/analyzer/projects/tmux/cleanup_run_static_analyzer.sh
@@ -0,0 +1,2 @@
+make distclean
+exit 0
Index: clang/utils/analyzer/projects/projects.json
===
--- clang/utils/analyzer/projects/projects.json
+++ clang/utils/analyzer/projects/projects.json
@@ -103,5 +103,40 @@
 "source": "git",
 "origin": "https://github.com/google/re2.git;,
 "commit": "2b25567"
+  },
+  {
+"name": "cppcheck",
+"mode": 1,
+"source": "git",
+"origin": "https://github.com/danmar/cppcheck.git;,
+"commit": "5fa3d53"
+  },
+  {
+"name": "harfbuzz",
+"mode": 1,
+"source": "git",
+"origin": "https://github.com/harfbuzz/harfbuzz.git;,
+"commit": "f8d345e"
+  },
+  {
+"name": "capnproto",
+"mode": 1,
+"source": "git",
+"origin": "https://github.com/capnproto/capnproto.git;,
+"commit": "8be1c9f"
+  },
+  {
+"name": "tmux",
+"mode": 1,
+"source": "git",
+"origin": "https://github.com/tmux/tmux.git;,
+"commit": "a5f99e1"
+  },
+  {
+"name": "faiss",
+"mode": 1,
+"source": "git",
+"origin": "https://github.com/facebookresearch/faiss.git;,
+"commit": "9e5d5b7"
   }
 ]
Index: clang/utils/analyzer/projects/harfbuzz/run_static_analyzer.cmd
===
--- /dev/null
+++ clang/utils/analyzer/projects/harfbuzz/run_static_analyzer.cmd
@@ -0,0 +1,2 @@
+cmake . -DCMAKE_BUILD_TYPE=Debug -Bbuild -GNinja
+cmake --build build
Index: clang/utils/analyzer/projects/harfbuzz/cleanup_run_static_analyzer.sh
===
--- /dev/null
+++ clang/utils/analyzer/projects/harfbuzz/cleanup_run_static_analyzer.sh
@@ -0,0 +1 @@
+rm -rf ./build
Index: clang/utils/analyzer/projects/faiss/run_static_analyzer.cmd
===
--- /dev/null
+++ clang/utils/analyzer/projects/faiss/run_static_analyzer.cmd
@@ -0,0 +1,2 @@
+./configure --without-cuda
+make
Index: clang/utils/analyzer/projects/faiss/cleanup_run_static_analyzer.sh
===
--- /dev/null
+++ clang/utils/analyzer/projects/faiss/cleanup_run_static_analyzer.sh
@@ -0,0 +1 @@
+make clean
Index: clang/utils/analyzer/projects/cppcheck/run_static_analyzer.cmd
===
--- /dev/null
+++ clang/utils/analyzer/projects/cppcheck/run_static_analyzer.cmd
@@ -0,0 +1,2 @@
+cmake . -DCMAKE_BUILD_TYPE=Debug -DCMAKE_DISABLE_PRECOMPILE_HEADERS=ON -Bbuild -GNinja
+cmake --build build
Index: clang/utils/analyzer/projects/cppcheck/cleanup_run_static_analyzer.sh
===
--- /dev/null
+++ clang/utils/analyzer/projects/cppcheck/cleanup_run_static_analyzer.sh
@@ -0,0 +1 @@
+rm -rf ./build
Index: clang/utils/analyzer/projects/capnproto/run_static_analyzer.cmd
===
--- /dev/null
+++ clang/utils/analyzer/projects/capnproto/run_static_analyzer.cmd
@@ -0,0 +1,2 @@
+cmake . -DCMAKE_BUILD_TYPE=Debug -Bbuild -GNinja
+cmake --build build
Index: clang/utils/analyzer/projects/capnproto/cleanup_run_static_analyzer.sh

[PATCH] D83700: Fix test for the hasExternalFormalLinkage matcher

2020-07-13 Thread Dmitri Gribenko via Phabricator via cfe-commits
gribozavr created this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

Names of local variables have no linkage (see C++20 [basic.link] p8).

Names of variables in unnamed namespace have internal linkage (see C++20
[basic.link] p4).


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D83700

Files:
  clang/unittests/ASTMatchers/ASTMatchersNarrowingTest.cpp


Index: clang/unittests/ASTMatchers/ASTMatchersNarrowingTest.cpp
===
--- clang/unittests/ASTMatchers/ASTMatchersNarrowingTest.cpp
+++ clang/unittests/ASTMatchers/ASTMatchersNarrowingTest.cpp
@@ -2534,19 +2534,16 @@
 }
 
 TEST(HasExternalFormalLinkage, Basic) {
-  EXPECT_TRUE(matches("int a = 0;", namedDecl(hasExternalFormalLinkage(;
-  EXPECT_TRUE(
-  notMatches("static int a = 0;", namedDecl(hasExternalFormalLinkage(;
+  EXPECT_TRUE(matches("int a = 0;",
+  namedDecl(hasName("a"), hasExternalFormalLinkage(;
+  EXPECT_TRUE(notMatches("static int a = 0;",
+ namedDecl(hasName("a"), hasExternalFormalLinkage(;
   EXPECT_TRUE(notMatches("static void f(void) { int a = 0; }",
- namedDecl(hasExternalFormalLinkage(;
-  EXPECT_TRUE(matches("void f(void) { int a = 0; }",
-  namedDecl(hasExternalFormalLinkage(;
-
-  // Despite having internal semantic linkage, the anonymous namespace member
-  // has external linkage because the member has a unique name in all
-  // translation units.
-  EXPECT_TRUE(matches("namespace { int a = 0; }",
-  namedDecl(hasExternalFormalLinkage(;
+ namedDecl(hasName("a"), hasExternalFormalLinkage(;
+  EXPECT_TRUE(notMatches("void f(void) { int a = 0; }",
+ namedDecl(hasName("a"), hasExternalFormalLinkage(;
+  EXPECT_TRUE(notMatches("namespace { int a = 0; }",
+ namedDecl(hasName("a"), hasExternalFormalLinkage(;
 }
 
 TEST(HasDefaultArgument, Basic) {


Index: clang/unittests/ASTMatchers/ASTMatchersNarrowingTest.cpp
===
--- clang/unittests/ASTMatchers/ASTMatchersNarrowingTest.cpp
+++ clang/unittests/ASTMatchers/ASTMatchersNarrowingTest.cpp
@@ -2534,19 +2534,16 @@
 }
 
 TEST(HasExternalFormalLinkage, Basic) {
-  EXPECT_TRUE(matches("int a = 0;", namedDecl(hasExternalFormalLinkage(;
-  EXPECT_TRUE(
-  notMatches("static int a = 0;", namedDecl(hasExternalFormalLinkage(;
+  EXPECT_TRUE(matches("int a = 0;",
+  namedDecl(hasName("a"), hasExternalFormalLinkage(;
+  EXPECT_TRUE(notMatches("static int a = 0;",
+ namedDecl(hasName("a"), hasExternalFormalLinkage(;
   EXPECT_TRUE(notMatches("static void f(void) { int a = 0; }",
- namedDecl(hasExternalFormalLinkage(;
-  EXPECT_TRUE(matches("void f(void) { int a = 0; }",
-  namedDecl(hasExternalFormalLinkage(;
-
-  // Despite having internal semantic linkage, the anonymous namespace member
-  // has external linkage because the member has a unique name in all
-  // translation units.
-  EXPECT_TRUE(matches("namespace { int a = 0; }",
-  namedDecl(hasExternalFormalLinkage(;
+ namedDecl(hasName("a"), hasExternalFormalLinkage(;
+  EXPECT_TRUE(notMatches("void f(void) { int a = 0; }",
+ namedDecl(hasName("a"), hasExternalFormalLinkage(;
+  EXPECT_TRUE(notMatches("namespace { int a = 0; }",
+ namedDecl(hasName("a"), hasExternalFormalLinkage(;
 }
 
 TEST(HasDefaultArgument, Basic) {
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D83592: [Parser] Add comment to skipped regions

2020-07-13 Thread Hans Wennborg via Phabricator via cfe-commits
hans added a comment.

> Not sure if this is good idea to untrack comments, it breaks many tests under 
> CoverageMapping.

I didn't look, but I'm surprised there are many coverage tests that have 
comments in them. If the comments are not important for those tests, maybe they 
could be removed? As long as we keep one that tracks the intended behavior of 
coverage on comments.




Comment at: clang/lib/Parse/Parser.cpp:37
   bool HandleComment(Preprocessor , SourceRange Comment) override {
+PP.getPPCallbacks()->SourceRangeSkipped(Comment, Comment.getEnd());
 S.ActOnComment(Comment);

I don't think this is the right way to do it. It seems this callback is 
intended for #if macros that exclude part of the file from preprocessing.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D83592



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


[PATCH] D82880: Fix PR35677: UB on __int128_t or __uint128_t template parameters.

2020-07-13 Thread David Stone via Phabricator via cfe-commits
davidstone marked an inline comment as done.
davidstone added inline comments.



Comment at: clang/lib/AST/StmtPrinter.cpp:1159
+  case BuiltinType::UInt128:
+OS << "Ui128";
+break;

aaron.ballman wrote:
> riccibruno wrote:
> > riccibruno wrote:
> > > davidstone wrote:
> > > > riccibruno wrote:
> > > > > `i128` and `Ui128` are not valid integer literal suffix. The output 
> > > > > of `StmtPrinter` is intended to be valid C++. Unfortunately here I 
> > > > > think that your only choice is to print the high and low parts 
> > > > > separately. 
> > > > I'm confused. i8, Ui8, i16, and Ui16 are also not valid C++ suffixes, 
> > > > but just a few lines up we use those. What am I missing here?
> > > The literal suffixes `[u]i8, [u]i16, [u]i32, and [u]i64` are an MSVC 
> > > extension (see `NumericLiteralParser::NumericLiteralParser` in 
> > > `Lex/LiteralSupport.cpp`).
> > > 
> > > This does not explain why they are used even in non-ms compatibility mode
> > > but at least there is some reason for their existence.
> > > 
> > > However I don't think that MSVC supports 128-bits integers (?), and clang 
> > > certainly
> > > does not support `[u]i128` so there is no reason to use them.
> > > 
> > > @aaron.ballman Do you know why are these suffixes used outside of 
> > > ms-compatibility mode?
> > > This does not explain why they are used even in non-ms compatibility mode
> > > but at least there is some reason for their existence.
> > 
> > Let's just ask the author @majnemer 
> > @aaron.ballman Do you know why are these suffixes used outside of 
> > ms-compatibility mode?
> 
> Our pretty printing is *supposed* to generate valid code, but we get it wrong 
> fairly often and I don't think we've ever promised (let alone tested) that 
> you can use this output to compile code (and get the same results). I think 
> that's more of a stretch goal. That said, the pretty printer should probably 
> be looking at the language options to decide whether it wants to output those 
> suffixes or not.
> 
> As for historical context, I think the thread starting here is relevant: 
> http://lists.llvm.org/pipermail/cfe-dev/2012-September/024423.html
So what is the next step for this patch?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D82880



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


[PATCH] D83406: Remove NormalizerRetTy and use the decltype of the KeyPath instead

2020-07-13 Thread Michael Spencer via Phabricator via cfe-commits
Bigcheese accepted this revision.
Bigcheese added a comment.
This revision is now accepted and ready to land.

lgtm


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D83406



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


[PATCH] D83690: Port Migator option flags to new option parsing system

2020-07-13 Thread Michael Spencer via Phabricator via cfe-commits
Bigcheese accepted this revision.
Bigcheese added a comment.
This revision is now accepted and ready to land.

lgtm


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D83690



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


[PATCH] D83698: Port Target option flags to new option parsing system

2020-07-13 Thread Daniel Grumberg via Phabricator via cfe-commits
dang created this revision.
dang added a reviewer: Bigcheese.
Herald added subscribers: cfe-commits, dexonsmith.
Herald added a project: clang.

Depends on D83697 


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D83698

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


Index: clang/lib/Frontend/CompilerInvocation.cpp
===
--- clang/lib/Frontend/CompilerInvocation.cpp
+++ clang/lib/Frontend/CompilerInvocation.cpp
@@ -3576,9 +3576,6 @@
   Opts.LinkerVersion =
   std::string(Args.getLastArgValue(OPT_target_linker_version));
   Opts.OpenCLExtensionsAsWritten = Args.getAllArgValues(OPT_cl_ext_EQ);
-  Opts.ForceEnableInt128 = Args.hasArg(OPT_fforce_enable_int128);
-  Opts.NVPTXUseShortPointers = Args.hasFlag(
-  options::OPT_fcuda_short_ptr, options::OPT_fno_cuda_short_ptr, false);
   if (Arg *A = Args.getLastArg(options::OPT_target_sdk_version_EQ)) {
 llvm::VersionTuple Version;
 if (Version.tryParse(A->getValue()))
Index: clang/include/clang/Driver/Options.td
===
--- clang/include/clang/Driver/Options.td
+++ clang/include/clang/Driver/Options.td
@@ -560,6 +560,21 @@
 
 } // Flags = [CC1Option, CC1AsOption, NoDriverOption]
 
+// Target Options
+
+defm cuda_short_ptr : BooleanMarshalledFFlag<"cuda-short-ptr", 
"TargetOpts->NVPTXUseShortPointers", "false",
+  "Use 32-bit pointers for accessing const/local/shared address spaces">;
+defm force_enable_int128 : OptInFFlag<"force-enable-int128", "Enable", 
"Disable", " support for int128_t type", [], "TargetOpts->ForceEnableInt128">;
+
+let Flags = [CC1Option, CC1AsOption, NoDriverOption] in {
+
+def triple : Separate<["-"], "triple">,
+  HelpText<"Specify target triple (e.g. i686-apple-darwin9)">,
+  MarshallingInfoString<"TargetOpts->Triple", 
"llvm::Triple::normalize(llvm::sys::getDefaultTargetTriple())">,
+  AlwaysEmit, Normalizer<"normalizeTriple">, DenormalizeString;
+
+} // Flags = [CC1Option, CC1AsOption, NoDriverOption]
+
 // Standard Options
 
 def _HASH_HASH_HASH : Flag<["-"], "###">, Flags<[DriverOption, CoreOption]>,
@@ -833,8 +848,6 @@
   "Generate relocatable device code, also known as separate compilation mode", 
"", "">;
 def : Flag<["-"], "fcuda-rdc">, Alias;
 def : Flag<["-"], "fno-cuda-rdc">, Alias;
-defm cuda_short_ptr : OptInFFlag<"cuda-short-ptr",
-  "Use 32-bit pointers for accessing const/local/shared address spaces">;
 def rocm_path_EQ : Joined<["--"], "rocm-path=">, Group,
   HelpText<"ROCm installation path, used for finding and automatically linking 
required bitcode libraries.">;
 def rocm_device_lib_path_EQ : Joined<["--"], "rocm-device-lib-path=">, 
Group,
@@ -1155,7 +1168,6 @@
 def fsignaling_math : Flag<["-"], "fsignaling-math">, Group;
 def fno_signaling_math : Flag<["-"], "fno-signaling-math">, Group;
 defm jump_tables : OptOutFFlag<"jump-tables", "Use", "Do not use", " jump 
tables for lowering switches">;
-defm force_enable_int128 : OptInFFlag<"force-enable-int128", "Enable", 
"Disable", " support for int128_t type">;
 defm keep_static_consts : OptInFFlag<"keep-static-consts", "Keep", "Don't 
keep", " static const variables if unused", [DriverOption]>;
 defm fixed_point : OptInFFlag<"fixed-point", "Enable", "Disable", " fixed 
point types">;
 defm cxx_static_destructors : OptOutFFlag<"c++-static-destructors", "",


Index: clang/lib/Frontend/CompilerInvocation.cpp
===
--- clang/lib/Frontend/CompilerInvocation.cpp
+++ clang/lib/Frontend/CompilerInvocation.cpp
@@ -3576,9 +3576,6 @@
   Opts.LinkerVersion =
   std::string(Args.getLastArgValue(OPT_target_linker_version));
   Opts.OpenCLExtensionsAsWritten = Args.getAllArgValues(OPT_cl_ext_EQ);
-  Opts.ForceEnableInt128 = Args.hasArg(OPT_fforce_enable_int128);
-  Opts.NVPTXUseShortPointers = Args.hasFlag(
-  options::OPT_fcuda_short_ptr, options::OPT_fno_cuda_short_ptr, false);
   if (Arg *A = Args.getLastArg(options::OPT_target_sdk_version_EQ)) {
 llvm::VersionTuple Version;
 if (Version.tryParse(A->getValue()))
Index: clang/include/clang/Driver/Options.td
===
--- clang/include/clang/Driver/Options.td
+++ clang/include/clang/Driver/Options.td
@@ -560,6 +560,21 @@
 
 } // Flags = [CC1Option, CC1AsOption, NoDriverOption]
 
+// Target Options
+
+defm cuda_short_ptr : BooleanMarshalledFFlag<"cuda-short-ptr", "TargetOpts->NVPTXUseShortPointers", "false",
+  "Use 32-bit pointers for accessing const/local/shared address spaces">;
+defm force_enable_int128 : OptInFFlag<"force-enable-int128", "Enable", "Disable", " support for int128_t type", [], "TargetOpts->ForceEnableInt128">;
+
+let Flags = [CC1Option, CC1AsOption, NoDriverOption] in {
+
+def triple : Separate<["-"], "triple">,
+  HelpText<"Specify target triple 

[PATCH] D83696: [OPENMP]Fix PR46688: cast the type of the allocated variable to the initial one.

2020-07-13 Thread Alexey Bataev via Phabricator via cfe-commits
ABataev created this revision.
ABataev added a reviewer: jdoerfert.
Herald added subscribers: guansong, yaxunl, jholewinski.
Herald added a project: clang.

If the original variable is marked for allocation in the different
address space using #pragma omp allocate, need to cast the allocated
variable to its original type with the original address space.
Otherwise, the compiler may crash trying to bitcast the type of the new
allocated variable to the original type in some cases, like passing this
variable as an argument in function calls.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D83696

Files:
  clang/lib/CodeGen/CGOpenMPRuntimeNVPTX.cpp
  clang/test/OpenMP/nvptx_allocate_codegen.cpp


Index: clang/test/OpenMP/nvptx_allocate_codegen.cpp
===
--- clang/test/OpenMP/nvptx_allocate_codegen.cpp
+++ clang/test/OpenMP/nvptx_allocate_codegen.cpp
@@ -101,7 +101,7 @@
 // CHECK: alloca float,
 // CHECK-NOT: alloca double,
 // CHECK: load float, float* %
-// CHECK: store double {{.+}}, double addrspace(3)* @bar_b,
+// CHECK: store double {{.+}}, double* addrspacecast (double addrspace(3)* 
@bar_b to double*),
 }
 
 #pragma omp end declare target
Index: clang/lib/CodeGen/CGOpenMPRuntimeNVPTX.cpp
===
--- clang/lib/CodeGen/CGOpenMPRuntimeNVPTX.cpp
+++ clang/lib/CodeGen/CGOpenMPRuntimeNVPTX.cpp
@@ -4770,6 +4770,7 @@
 const VarDecl *VD) {
   if (VD && VD->hasAttr()) {
 const auto *A = VD->getAttr();
+auto AS = LangAS::Default;
 switch (A->getAllocatorType()) {
   // Use the default allocator here as by default local vars are
   // threadlocal.
@@ -4783,42 +4784,30 @@
 case OMPAllocateDeclAttr::OMPUserDefinedMemAlloc:
   // TODO: implement aupport for user-defined allocators.
   return Address::invalid();
-case OMPAllocateDeclAttr::OMPConstMemAlloc: {
-  llvm::Type *VarTy = CGF.ConvertTypeForMem(VD->getType());
-  auto *GV = new llvm::GlobalVariable(
-  CGM.getModule(), VarTy, /*isConstant=*/false,
-  llvm::GlobalValue::InternalLinkage,
-  llvm::Constant::getNullValue(VarTy), VD->getName(),
-  /*InsertBefore=*/nullptr, llvm::GlobalValue::NotThreadLocal,
-  CGM.getContext().getTargetAddressSpace(LangAS::cuda_constant));
-  CharUnits Align = CGM.getContext().getDeclAlign(VD);
-  GV->setAlignment(Align.getAsAlign());
-  return Address(GV, Align);
-}
-case OMPAllocateDeclAttr::OMPPTeamMemAlloc: {
-  llvm::Type *VarTy = CGF.ConvertTypeForMem(VD->getType());
-  auto *GV = new llvm::GlobalVariable(
-  CGM.getModule(), VarTy, /*isConstant=*/false,
-  llvm::GlobalValue::InternalLinkage,
-  llvm::Constant::getNullValue(VarTy), VD->getName(),
-  /*InsertBefore=*/nullptr, llvm::GlobalValue::NotThreadLocal,
-  CGM.getContext().getTargetAddressSpace(LangAS::cuda_shared));
-  CharUnits Align = CGM.getContext().getDeclAlign(VD);
-  GV->setAlignment(Align.getAsAlign());
-  return Address(GV, Align);
-}
+case OMPAllocateDeclAttr::OMPConstMemAlloc:
+  AS = LangAS::cuda_constant;
+  break;
+case OMPAllocateDeclAttr::OMPPTeamMemAlloc:
+  AS = LangAS::cuda_shared;
+  break;
 case OMPAllocateDeclAttr::OMPLargeCapMemAlloc:
-case OMPAllocateDeclAttr::OMPCGroupMemAlloc: {
-  llvm::Type *VarTy = CGF.ConvertTypeForMem(VD->getType());
-  auto *GV = new llvm::GlobalVariable(
-  CGM.getModule(), VarTy, /*isConstant=*/false,
-  llvm::GlobalValue::InternalLinkage,
-  llvm::Constant::getNullValue(VarTy), VD->getName());
-  CharUnits Align = CGM.getContext().getDeclAlign(VD);
-  GV->setAlignment(Align.getAsAlign());
-  return Address(GV, Align);
-}
+case OMPAllocateDeclAttr::OMPCGroupMemAlloc:
+  break;
 }
+llvm::Type *VarTy = CGF.ConvertTypeForMem(VD->getType());
+auto *GV = new llvm::GlobalVariable(
+CGM.getModule(), VarTy, /*isConstant=*/false,
+llvm::GlobalValue::InternalLinkage, 
llvm::Constant::getNullValue(VarTy),
+VD->getName(),
+/*InsertBefore=*/nullptr, llvm::GlobalValue::NotThreadLocal,
+CGM.getContext().getTargetAddressSpace(AS));
+CharUnits Align = CGM.getContext().getDeclAlign(VD);
+GV->setAlignment(Align.getAsAlign());
+return Address(
+CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
+GV, VarTy->getPointerTo(CGM.getContext().getTargetAddressSpace(
+VD->getType().getAddressSpace(,
+Align);
   }
 
   if (getDataSharingMode(CGM) != CGOpenMPRuntimeNVPTX::Generic)


Index: clang/test/OpenMP/nvptx_allocate_codegen.cpp
===
--- clang/test/OpenMP/nvptx_allocate_codegen.cpp
+++ 

[PATCH] D83697: Port Frontend option flags to new option parsing system

2020-07-13 Thread Daniel Grumberg via Phabricator via cfe-commits
dang created this revision.
dang added a reviewer: Bigcheese.
Herald added subscribers: cfe-commits, jfb, dexonsmith.
Herald added a project: clang.

Depends on D83695 


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D83697

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

Index: clang/lib/Frontend/CompilerInvocation.cpp
===
--- clang/lib/Frontend/CompilerInvocation.cpp
+++ clang/lib/Frontend/CompilerInvocation.cpp
@@ -289,9 +289,11 @@
   LangOptions  = *Invocation.getLangOpts();
   DiagnosticOptions  = Invocation.getDiagnosticOpts();
   CodeGenOptions  = Invocation.getCodeGenOpts();
+  FrontendOptions  = Invocation.getFrontendOpts();
   CodeGenOpts.XRayInstrumentFunctions = LangOpts.XRayInstrument;
   CodeGenOpts.XRayAlwaysEmitCustomEvents = LangOpts.XRayAlwaysEmitCustomEvents;
   CodeGenOpts.XRayAlwaysEmitTypedEvents = LangOpts.XRayAlwaysEmitTypedEvents;
+  FrontendOpts.GenerateGlobalModuleIndex = FrontendOpts.UseGlobalModuleIndex;
 
   llvm::sys::Process::UseANSIEscapeCodes(DiagOpts.UseANSIEscapeCodes);
 }
@@ -1941,32 +1943,16 @@
   Diags.Report(diag::err_drv_invalid_value)
 << A->getAsString(Args) << A->getValue();
   }
-  Opts.DisableFree = Args.hasArg(OPT_disable_free);
 
   Opts.OutputFile = std::string(Args.getLastArgValue(OPT_o));
   Opts.Plugins = Args.getAllArgValues(OPT_load);
-  Opts.RelocatablePCH = Args.hasArg(OPT_relocatable_pch);
-  Opts.ShowHelp = Args.hasArg(OPT_help);
-  Opts.ShowStats = Args.hasArg(OPT_print_stats);
-  Opts.ShowTimers = Args.hasArg(OPT_ftime_report);
-  Opts.PrintSupportedCPUs = Args.hasArg(OPT_print_supported_cpus);
-  Opts.TimeTrace = Args.hasArg(OPT_ftime_trace);
   Opts.TimeTraceGranularity = getLastArgIntValue(
   Args, OPT_ftime_trace_granularity_EQ, Opts.TimeTraceGranularity, Diags);
-  Opts.ShowVersion = Args.hasArg(OPT_version);
   Opts.ASTMergeFiles = Args.getAllArgValues(OPT_ast_merge);
   Opts.LLVMArgs = Args.getAllArgValues(OPT_mllvm);
-  Opts.FixWhatYouCan = Args.hasArg(OPT_fix_what_you_can);
-  Opts.FixOnlyWarnings = Args.hasArg(OPT_fix_only_warnings);
-  Opts.FixAndRecompile = Args.hasArg(OPT_fixit_recompile);
-  Opts.FixToTemporaries = Args.hasArg(OPT_fixit_to_temp);
   Opts.ASTDumpDecls = Args.hasArg(OPT_ast_dump, OPT_ast_dump_EQ);
   Opts.ASTDumpAll = Args.hasArg(OPT_ast_dump_all, OPT_ast_dump_all_EQ);
   Opts.ASTDumpFilter = std::string(Args.getLastArgValue(OPT_ast_dump_filter));
-  Opts.ASTDumpLookups = Args.hasArg(OPT_ast_dump_lookups);
-  Opts.ASTDumpDeclTypes = Args.hasArg(OPT_ast_dump_decl_types);
-  Opts.UseGlobalModuleIndex = !Args.hasArg(OPT_fno_modules_global_index);
-  Opts.GenerateGlobalModuleIndex = Opts.UseGlobalModuleIndex;
   Opts.ModuleMapFiles = Args.getAllArgValues(OPT_fmodule_map_file);
   // Only the -fmodule-file= form.
   for (const auto *A : Args.filtered(OPT_fmodule_file)) {
@@ -1975,28 +1961,11 @@
   Opts.ModuleFiles.push_back(std::string(Val));
   }
   Opts.ModulesEmbedFiles = Args.getAllArgValues(OPT_fmodules_embed_file_EQ);
-  Opts.ModulesEmbedAllFiles = Args.hasArg(OPT_fmodules_embed_all_files);
-  Opts.IncludeTimestamps = !Args.hasArg(OPT_fno_pch_timestamp);
-  Opts.UseTemporary = !Args.hasArg(OPT_fno_temp_file);
-  Opts.IsSystemModule = Args.hasArg(OPT_fsystem_module);
 
   if (Opts.ProgramAction != frontend::GenerateModule && Opts.IsSystemModule)
 Diags.Report(diag::err_drv_argument_only_allowed_with) << "-fsystem-module"
<< "-emit-module";
 
-  Opts.CodeCompleteOpts.IncludeMacros
-= Args.hasArg(OPT_code_completion_macros);
-  Opts.CodeCompleteOpts.IncludeCodePatterns
-= Args.hasArg(OPT_code_completion_patterns);
-  Opts.CodeCompleteOpts.IncludeGlobals
-= !Args.hasArg(OPT_no_code_completion_globals);
-  Opts.CodeCompleteOpts.IncludeNamespaceLevelDecls
-= !Args.hasArg(OPT_no_code_completion_ns_level_decls);
-  Opts.CodeCompleteOpts.IncludeBriefComments
-= Args.hasArg(OPT_code_completion_brief_comments);
-  Opts.CodeCompleteOpts.IncludeFixIts
-= Args.hasArg(OPT_code_completion_with_fixits);
-
   Opts.OverrideRecordLayoutsFile =
   std::string(Args.getLastArgValue(OPT_foverride_record_layout_EQ));
   Opts.AuxTriple = std::string(Args.getLastArgValue(OPT_aux_triple));
@@ -2010,8 +1979,6 @@
   std::string(Args.getLastArgValue(OPT_mt_migrate_directory));
   Opts.ARCMTMigrateReportOut =
   std::string(Args.getLastArgValue(OPT_arcmt_migrate_report_output));
-  Opts.ARCMTMigrateEmitARCErrors
-= Args.hasArg(OPT_arcmt_migrate_emit_arc_errors);
 
   Opts.ObjCMTWhiteListPath =
   std::string(Args.getLastArgValue(OPT_objcmt_whitelist_dir_path));
Index: clang/include/clang/Driver/Options.td
===
--- clang/include/clang/Driver/Options.td
+++ clang/include/clang/Driver/Options.td
@@ -315,9 

[PATCH] D83695: Port Diagnostic option flags to new option parsing system

2020-07-13 Thread Daniel Grumberg via Phabricator via cfe-commits
dang created this revision.
dang added a reviewer: Bigcheese.
Herald added subscribers: cfe-commits, dexonsmith.
Herald added a project: clang.

Depends on D83694 


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D83695

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

Index: clang/lib/Frontend/CompilerInvocation.cpp
===
--- clang/lib/Frontend/CompilerInvocation.cpp
+++ clang/lib/Frontend/CompilerInvocation.cpp
@@ -1632,16 +1632,11 @@
   if (Arg *A =
   Args.getLastArg(OPT_diagnostic_serialized_file, OPT__serialize_diags))
 Opts.DiagnosticSerializationFile = A->getValue();
-  Opts.IgnoreWarnings = Args.hasArg(OPT_w);
-  Opts.NoRewriteMacros = Args.hasArg(OPT_Wno_rewrite_macros);
-  Opts.Pedantic = Args.hasArg(OPT_pedantic);
-  Opts.PedanticErrors = Args.hasArg(OPT_pedantic_errors);
   Opts.ShowCarets = !Args.hasArg(OPT_fno_caret_diagnostics);
   Opts.ShowColors = parseShowColorsArgs(Args, DefaultDiagColor);
   Opts.ShowColumn = !Args.hasArg(OPT_fno_show_column);
   Opts.ShowFixits = !Args.hasArg(OPT_fno_diagnostics_fixit_info);
   Opts.ShowLocation = !Args.hasArg(OPT_fno_show_source_location);
-  Opts.AbsolutePath = Args.hasArg(OPT_fdiagnostics_absolute_paths);
   Opts.ShowOptionNames = !Args.hasArg(OPT_fno_diagnostics_show_option);
 
   // Default behavior is to not to show note include stacks.
@@ -1700,9 +1695,6 @@
   << Format;
   }
 
-  Opts.ShowSourceRanges = Args.hasArg(OPT_fdiagnostics_print_source_range_info);
-  Opts.ShowParseableFixits = Args.hasArg(OPT_fdiagnostics_parseable_fixits);
-  Opts.ShowPresumedLoc = !Args.hasArg(OPT_fno_diagnostics_use_presumed_location);
   Opts.VerifyDiagnostics = Args.hasArg(OPT_verify) || Args.hasArg(OPT_verify_EQ);
   Opts.VerifyPrefixes = Args.getAllArgValues(OPT_verify_EQ);
   if (Args.hasArg(OPT_verify))
@@ -1722,8 +1714,6 @@
   if (Args.hasArg(OPT_verify_ignore_unexpected))
 DiagMask = DiagnosticLevelMask::All;
   Opts.setVerifyIgnoreUnexpected(DiagMask);
-  Opts.ElideType = !Args.hasArg(OPT_fno_elide_type);
-  Opts.ShowTemplateTree = Args.hasArg(OPT_fdiagnostics_show_template_tree);
   Opts.ErrorLimit = getLastArgIntValue(Args, OPT_ferror_limit, 0, Diags);
   Opts.MacroBacktraceLimit =
   getLastArgIntValue(Args, OPT_fmacro_backtrace_limit,
Index: clang/include/clang/Driver/Options.td
===
--- clang/include/clang/Driver/Options.td
+++ clang/include/clang/Driver/Options.td
@@ -417,6 +417,47 @@
 
 } // Flags = [CC1Option, NoDriverOption]
 
+// Diagnostic Options
+
+def fdiagnostics_parseable_fixits : Flag<["-"], "fdiagnostics-parseable-fixits">, Group,
+Flags<[CoreOption, CC1Option]>, HelpText<"Print fix-its in machine parseable form">,
+MarshallingInfoFlag<"DiagnosticOpts->ShowParseableFixits", "false">;
+def fansi_escape_codes : Flag<["-"], "fansi-escape-codes">, Group,
+  Flags<[CoreOption, CC1Option]>, HelpText<"Use ANSI escape codes for diagnostics">,
+  MarshallingInfoFlag<"DiagnosticOpts->UseANSIEscapeCodes", "false">;
+def fdiagnostics_print_source_range_info : Flag<["-"], "fdiagnostics-print-source-range-info">,
+Group,  Flags<[CC1Option]>,
+HelpText<"Print source range spans in numeric form">,
+MarshallingInfoFlag<"DiagnosticOpts->ShowSourceRanges", "false">;
+def fdiagnostics_show_template_tree : Flag<["-"], "fdiagnostics-show-template-tree">,
+Group, Flags<[CC1Option]>,
+HelpText<"Print a template comparison tree for differing templates">,
+MarshallingInfoFlag<"DiagnosticOpts->ShowTemplateTree", "false">;
+def fno_elide_type : Flag<["-"], "fno-elide-type">, Group,
+Flags<[CC1Option]>,
+HelpText<"Do not elide types when printing diagnostics">,
+MarshallingInfoFlag<"DiagnosticOpts->ElideType", "true">, IsNegative;
+def fdiagnostics_absolute_paths : Flag<["-"], "fdiagnostics-absolute-paths">, Group,
+  Flags<[CC1Option, CoreOption]>, HelpText<"Print absolute paths in diagnostics">,
+  MarshallingInfoFlag<"DiagnosticOpts->AbsolutePath", "false">;
+def pedantic_errors : Flag<["-", "--"], "pedantic-errors">, Group, Flags<[CC1Option]>,
+  MarshallingInfoFlag<"DiagnosticOpts->PedanticErrors", "false">;
+def pedantic : Flag<["-", "--"], "pedantic">, Group, Flags<[CC1Option]>,
+  MarshallingInfoFlag<"DiagnosticOpts->Pedantic", "false">;
+def w : Flag<["-"], "w">, HelpText<"Suppress all warnings">, Flags<[CC1Option]>,
+  MarshallingInfoFlag<"DiagnosticOpts->IgnoreWarnings", "false">;
+
+let Flags = [CC1Option, NoDriverOption] in {
+
+def fno_diagnostics_use_presumed_location : Flag<["-"], "fno-diagnostics-use-presumed-location">,
+  HelpText<"Ignore #line directives when displaying diagnostic locations">,
+  MarshallingInfoFlag<"DiagnosticOpts->ShowPresumedLoc", "true">, IsNegative;
+def Wno_rewrite_macros : Flag<["-"], "Wno-rewrite-macros">,
+  HelpText<"Silence ObjC 

[PATCH] D83694: Port DependencyOutput option flags to new option parsing system

2020-07-13 Thread Daniel Grumberg via Phabricator via cfe-commits
dang created this revision.
dang added a reviewer: Bigcheese.
Herald added subscribers: cfe-commits, dexonsmith.
Herald added a project: clang.

Depends on D83693 


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D83694

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

Index: clang/lib/Frontend/CompilerInvocation.cpp
===
--- clang/lib/Frontend/CompilerInvocation.cpp
+++ clang/lib/Frontend/CompilerInvocation.cpp
@@ -138,10 +138,11 @@
   return !Args.hasArg(Opt);
 }
 
+template 
 void denormalizeSimpleFlag(SmallVectorImpl ,
const char *Spelling,
CompilerInvocation::StringAllocator SA,
-   unsigned TableIndex, unsigned Value) {
+   unsigned TableIndex, T Value) {
   Args.push_back(Spelling);
 }
 
@@ -1521,13 +1522,8 @@
   ArgList ) {
   Opts.OutputFile = std::string(Args.getLastArgValue(OPT_dependency_file));
   Opts.Targets = Args.getAllArgValues(OPT_MT);
-  Opts.IncludeSystemHeaders = Args.hasArg(OPT_sys_header_deps);
-  Opts.IncludeModuleFiles = Args.hasArg(OPT_module_file_deps);
-  Opts.UsePhonyTargets = Args.hasArg(OPT_MP);
-  Opts.ShowHeaderIncludes = Args.hasArg(OPT_H);
   Opts.HeaderIncludeOutputFile =
   std::string(Args.getLastArgValue(OPT_header_include_file));
-  Opts.AddMissingHeaderDeps = Args.hasArg(OPT_MG);
   if (Args.hasArg(OPT_show_includes)) {
 // Writing both /showIncludes and preprocessor output to stdout
 // would produce interleaved output, so use stderr for /showIncludes.
@@ -1542,8 +1538,6 @@
   Opts.DOTOutputFile = std::string(Args.getLastArgValue(OPT_dependency_dot));
   Opts.ModuleDependencyOutputDir =
   std::string(Args.getLastArgValue(OPT_module_dependency_dir));
-  if (Args.hasArg(OPT_MV))
-Opts.OutputFormat = DependencyOutputFormat::NMake;
   // Add sanitizer blacklists as extra dependencies.
   // They won't be discovered by the regular preprocessor, so
   // we let make / ninja to know about this implicit dependency.
Index: clang/include/clang/Driver/Options.td
===
--- clang/include/clang/Driver/Options.td
+++ clang/include/clang/Driver/Options.td
@@ -390,6 +390,33 @@
 def fparse_all_comments : Flag<["-"], "fparse-all-comments">, Group, Flags<[CC1Option]>,
   MarshallingInfoFlag<"LangOpts->CommentOpts.ParseAllComments", "false">;
 
+// Dependency Output Options
+
+def MV : Flag<["-"], "MV">, Group, Flags<[CC1Option]>,
+HelpText<"Use NMake/Jom format for the depfile">,
+MarshallingInfoFlag<"DependencyOutputOpts.OutputFormat", "DependencyOutputFormat::Make">,
+Normalizer<"(normalizeFlagToValue)">;
+def H : Flag<["-"], "H">, Flags<[CC1Option]>, Group,
+HelpText<"Show header includes and nesting depth">,
+MarshallingInfoFlag<"DependencyOutputOpts.ShowHeaderIncludes", "false">;
+def MG : Flag<["-"], "MG">, Group, Flags<[CC1Option]>,
+HelpText<"Add missing headers to depfile">,
+MarshallingInfoFlag<"DependencyOutputOpts.AddMissingHeaderDeps", "false">;
+def MP : Flag<["-"], "MP">, Group, Flags<[CC1Option]>,
+HelpText<"Create phony target for each dependency (other than main file)">,
+MarshallingInfoFlag<"DependencyOutputOpts.UsePhonyTargets", "false">;
+
+let Flags = [CC1Option, NoDriverOption] in {
+
+def sys_header_deps : Flag<["-"], "sys-header-deps">,
+  HelpText<"Include system headers in dependency output">,
+  MarshallingInfoFlag<"DependencyOutputOpts.IncludeSystemHeaders", "false">;
+def module_file_deps : Flag<["-"], "module-file-deps">,
+  HelpText<"Include module files in dependency output">,
+  MarshallingInfoFlag<"DependencyOutputOpts.IncludeModuleFiles", "false">;
+
+} // Flags = [CC1Option, NoDriverOption]
+
 // Standard Options
 
 def _HASH_HASH_HASH : Flag<["-"], "###">, Flags<[DriverOption, CoreOption]>,
@@ -414,8 +441,6 @@
 MetaVarName<"">, HelpText<"Put objects of at most  bytes "
 "into small data section (MIPS / Hexagon)">;
 def G_EQ : Joined<["-"], "G=">, Flags<[DriverOption]>, Group, Alias;
-def H : Flag<["-"], "H">, Flags<[CC1Option]>, Group,
-HelpText<"Show header includes and nesting depth">;
 def I_ : Flag<["-"], "I-">, Group,
 HelpText<"Restrict all prior -I flags to double-quoted inclusion and "
  "remove current directory from include path">;
@@ -435,18 +460,12 @@
 def MF : JoinedOrSeparate<["-"], "MF">, Group,
 HelpText<"Write depfile output from -MMD, -MD, -MM, or -M to ">,
 MetaVarName<"">;
-def MG : Flag<["-"], "MG">, Group, Flags<[CC1Option]>,
-HelpText<"Add missing headers to depfile">;
 def MJ : JoinedOrSeparate<["-"], "MJ">, Group,
 HelpText<"Write a compilation database entry per input">;
-def MP : Flag<["-"], "MP">, Group, Flags<[CC1Option]>,
-HelpText<"Create phony target for each 

[PATCH] D83693: Port analyzer flags to new option parsing system

2020-07-13 Thread Daniel Grumberg via Phabricator via cfe-commits
dang created this revision.
dang added a reviewer: Bigcheese.
Herald added subscribers: cfe-commits, ASDenysPetrov, dkrupp, donat.nagy, 
Szelethus, dexonsmith, a.sidorin, baloghadamsoftware.
Herald added a project: clang.

Depends on D83691 


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D83693

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

Index: clang/lib/Frontend/CompilerInvocation.cpp
===
--- clang/lib/Frontend/CompilerInvocation.cpp
+++ clang/lib/Frontend/CompilerInvocation.cpp
@@ -466,44 +466,19 @@
 }
   }
 
-  Opts.ShowCheckerHelp = Args.hasArg(OPT_analyzer_checker_help);
-  Opts.ShowCheckerHelpAlpha = Args.hasArg(OPT_analyzer_checker_help_alpha);
-  Opts.ShowCheckerHelpDeveloper =
-  Args.hasArg(OPT_analyzer_checker_help_developer);
-
-  Opts.ShowCheckerOptionList = Args.hasArg(OPT_analyzer_checker_option_help);
-  Opts.ShowCheckerOptionAlphaList =
-  Args.hasArg(OPT_analyzer_checker_option_help_alpha);
-  Opts.ShowCheckerOptionDeveloperList =
-  Args.hasArg(OPT_analyzer_checker_option_help_developer);
-
-  Opts.ShowConfigOptionsList = Args.hasArg(OPT_analyzer_config_help);
-  Opts.ShowEnabledCheckerList = Args.hasArg(OPT_analyzer_list_enabled_checkers);
   Opts.ShouldEmitErrorsOnInvalidConfigValue =
-  /* negated */!llvm::StringSwitch(
-   Args.getLastArgValue(OPT_analyzer_config_compatibility_mode))
-.Case("true", true)
-.Case("false", false)
-.Default(false);
-  Opts.DisableAllCheckers = Args.hasArg(OPT_analyzer_disable_all_checks);
-
-  Opts.visualizeExplodedGraphWithGraphViz =
-Args.hasArg(OPT_analyzer_viz_egraph_graphviz);
+  /* negated */ !llvm::StringSwitch(
+  Args.getLastArgValue(OPT_analyzer_config_compatibility_mode))
+  .Case("true", true)
+  .Case("false", false)
+  .Default(false);
+
   Opts.DumpExplodedGraphTo =
   std::string(Args.getLastArgValue(OPT_analyzer_dump_egraph));
-  Opts.NoRetryExhausted = Args.hasArg(OPT_analyzer_disable_retry_exhausted);
-  Opts.AnalyzerWerror = Args.hasArg(OPT_analyzer_werror);
-  Opts.AnalyzeAll = Args.hasArg(OPT_analyzer_opt_analyze_headers);
-  Opts.AnalyzerDisplayProgress = Args.hasArg(OPT_analyzer_display_progress);
-  Opts.AnalyzeNestedBlocks =
-Args.hasArg(OPT_analyzer_opt_analyze_nested_blocks);
   Opts.AnalyzeSpecificFunction =
   std::string(Args.getLastArgValue(OPT_analyze_function));
-  Opts.UnoptimizedCFG = Args.hasArg(OPT_analysis_UnoptimizedCFG);
-  Opts.TrimGraph = Args.hasArg(OPT_trim_egraph);
   Opts.maxBlockVisitOnPath =
   getLastArgIntValue(Args, OPT_analyzer_max_loop, 4, Diags);
-  Opts.PrintStats = Args.hasArg(OPT_analyzer_stats);
   Opts.InlineMaxStackDepth =
   getLastArgIntValue(Args, OPT_analyzer_inline_max_stack_depth,
  Opts.InlineMaxStackDepth, Diags);
Index: clang/include/clang/Driver/Options.td
===
--- clang/include/clang/Driver/Options.td
+++ clang/include/clang/Driver/Options.td
@@ -3513,7 +3513,8 @@
 //===--===//
 
 def analysis_UnoptimizedCFG : Flag<["-"], "unoptimized-cfg">,
-  HelpText<"Generate unoptimized CFGs for all analyses">;
+  HelpText<"Generate unoptimized CFGs for all analyses">,
+  MarshallingInfoFlag<"AnalyzerOpts->UnoptimizedCFG", "false">;
 def analysis_CFGAddImplicitDtors : Flag<["-"], "cfg-add-implicit-dtors">,
   HelpText<"Add C++ implicit destructors to CFGs for all analyses">;
 
@@ -3536,18 +3537,23 @@
 def analyzer_purge_EQ : Joined<["-"], "analyzer-purge=">, Alias;
 
 def analyzer_opt_analyze_headers : Flag<["-"], "analyzer-opt-analyze-headers">,
-  HelpText<"Force the static analyzer to analyze functions defined in header files">;
+  HelpText<"Force the static analyzer to analyze functions defined in header files">,
+  MarshallingInfoFlag<"AnalyzerOpts->AnalyzeAll", "false">;
 def analyzer_opt_analyze_nested_blocks : Flag<["-"], "analyzer-opt-analyze-nested-blocks">,
-  HelpText<"Analyze the definitions of blocks in addition to functions">;
+  HelpText<"Analyze the definitions of blocks in addition to functions">,
+  MarshallingInfoFlag<"AnalyzerOpts->AnalyzeNestedBlocks", "false">;
 def analyzer_display_progress : Flag<["-"], "analyzer-display-progress">,
-  HelpText<"Emit verbose output about the analyzer's progress">;
+  HelpText<"Emit verbose output about the analyzer's progress">,
+  MarshallingInfoFlag<"AnalyzerOpts->AnalyzerDisplayProgress", "false">;
 def analyze_function : Separate<["-"], "analyze-function">,
   HelpText<"Run analysis on specific function (for C++ include parameters in name)">;
 def analyze_function_EQ : Joined<["-"], "analyze-function=">, Alias;
 def trim_egraph : Flag<["-"], "trim-egraph">,
-  HelpText<"Only show error-related paths 

[PATCH] D83691: Port Comment option flags to new parsing system

2020-07-13 Thread Daniel Grumberg via Phabricator via cfe-commits
dang created this revision.
dang added a reviewer: Bigcheese.
Herald added subscribers: cfe-commits, dexonsmith.
Herald added a project: clang.

Depends on D83690 


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D83691

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


Index: clang/lib/Frontend/CompilerInvocation.cpp
===
--- clang/lib/Frontend/CompilerInvocation.cpp
+++ clang/lib/Frontend/CompilerInvocation.cpp
@@ -697,7 +697,6 @@
 
 static void ParseCommentArgs(CommentOptions , ArgList ) {
   Opts.BlockCommandNames = Args.getAllArgValues(OPT_fcomment_block_commands);
-  Opts.ParseAllComments = Args.hasArg(OPT_fparse_all_comments);
 }
 
 /// Create a new Regex instance out of the string value in \p RpassArg.
Index: clang/include/clang/Driver/Options.td
===
--- clang/include/clang/Driver/Options.td
+++ clang/include/clang/Driver/Options.td
@@ -385,6 +385,11 @@
 // Make sure all other -ccc- options are rejected.
 def ccc_ : Joined<["-"], "ccc-">, Group, Flags<[Unsupported]>;
 
+// Comment Options
+
+def fparse_all_comments : Flag<["-"], "fparse-all-comments">, 
Group, Flags<[CC1Option]>,
+  MarshallingInfoFlag<"LangOpts->CommentOpts.ParseAllComments", "false">;
+
 // Standard Options
 
 def _HASH_HASH_HASH : Flag<["-"], "###">, Flags<[DriverOption, CoreOption]>,
@@ -891,7 +896,6 @@
 def fcomment_block_commands : CommaJoined<["-"], "fcomment-block-commands=">, 
Group, Flags<[CC1Option]>,
   HelpText<"Treat each comma separated argument in  as a documentation 
comment block command">,
   MetaVarName<"">;
-def fparse_all_comments : Flag<["-"], "fparse-all-comments">, 
Group, Flags<[CC1Option]>;
 def frecord_command_line : Flag<["-"], "frecord-command-line">,
   Group;
 def fno_record_command_line : Flag<["-"], "fno-record-command-line">,


Index: clang/lib/Frontend/CompilerInvocation.cpp
===
--- clang/lib/Frontend/CompilerInvocation.cpp
+++ clang/lib/Frontend/CompilerInvocation.cpp
@@ -697,7 +697,6 @@
 
 static void ParseCommentArgs(CommentOptions , ArgList ) {
   Opts.BlockCommandNames = Args.getAllArgValues(OPT_fcomment_block_commands);
-  Opts.ParseAllComments = Args.hasArg(OPT_fparse_all_comments);
 }
 
 /// Create a new Regex instance out of the string value in \p RpassArg.
Index: clang/include/clang/Driver/Options.td
===
--- clang/include/clang/Driver/Options.td
+++ clang/include/clang/Driver/Options.td
@@ -385,6 +385,11 @@
 // Make sure all other -ccc- options are rejected.
 def ccc_ : Joined<["-"], "ccc-">, Group, Flags<[Unsupported]>;
 
+// Comment Options
+
+def fparse_all_comments : Flag<["-"], "fparse-all-comments">, Group, Flags<[CC1Option]>,
+  MarshallingInfoFlag<"LangOpts->CommentOpts.ParseAllComments", "false">;
+
 // Standard Options
 
 def _HASH_HASH_HASH : Flag<["-"], "###">, Flags<[DriverOption, CoreOption]>,
@@ -891,7 +896,6 @@
 def fcomment_block_commands : CommaJoined<["-"], "fcomment-block-commands=">, Group, Flags<[CC1Option]>,
   HelpText<"Treat each comma separated argument in  as a documentation comment block command">,
   MetaVarName<"">;
-def fparse_all_comments : Flag<["-"], "fparse-all-comments">, Group, Flags<[CC1Option]>;
 def frecord_command_line : Flag<["-"], "frecord-command-line">,
   Group;
 def fno_record_command_line : Flag<["-"], "fno-record-command-line">,
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


  1   2   3   >