[PATCH] D106136: [Analyzer][solver] Fix equivalence class invariant violation in removeDeadBindings

2021-07-20 Thread Gabor Marton via Phabricator via cfe-commits
martong abandoned this revision.
martong added a comment.

In D106136#2883707 , @vsavchenko 
wrote:

> In D106136#2883100 , @martong wrote:
>
>> Thanks for taking your time to take a look. And I accept your statements. 
>> Nevertheless, let me explain my motivation.
>>
>> I thought that a class is trivial if it has only one member. And it seemed 
>> perfectly logical to not store equivalence classes with one member. I.e `a` 
>> equals to `a` does not hold any meaningful information it just takes 
>> precious memory. When we add a new constraint we take careful steps to avoid 
>> adding a new class with one member. However, when remove dead kicks in, 
>> suddenly we end up having classes stored with one member, which is a 
>> somewhat inconsistent design IMHO. Perhaps some better documentation could 
>> have helped.
>
> Representative symbol gives its equivalence class an ID.  We use this ID for 
> everything, for comparing and for mapping.  Since we live in a persistent 
> world, we can't just change this ID at some point, it will basically mean 
> that we want to replace a class with another class.  So, all maps where this 
> class participated (constraints, class, members, disequality) should remove 
> the old class and add the new class.  This is a huge burden.  You need to 
> carefully do all this, and bloat existing data structures.
>
> Trivial class is an optimization for the vast majority of symbols that never 
> get into any classes.  We still need to associate constraints with those.  
> This is where implicit Symbol to Class conversion comes in handy.
>
> Now let's imagine that something else is merged into it.  We are obliged to 
> officially map the symbol to its class, and the class to its members.  When 
> this happens, it goes into the data structure FOREVER.  And when in the 
> future, with only one member, instead of keeping something that we already 
> have from other versions of the data structure, you decide to remove the item 
> from the class map, you actually use more memory when it was there!  This is 
> how persistent data structures work, different versions of the same data 
> structure share data.  And I'm not even talking here about the fact that you 
> now need to replace the class with one ID with the class with another ID in 
> every relationship.
>
> You can probably measure memory footprint in your example and see it for 
> yourself.

Yeah, makes sense. Thanks for taking more time for further explanations. Still, 
IMHO, the definition of a **trivial class** needs a clear written documentation 
in the code itself, so other developers can easier understand and maintain this 
code. I am going to create an NFC patch that summarizes this discussion in a 
comment attached to the `isTrivial` function.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D106136

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


[PATCH] D106347: [PoC][RISCV] Encode arch information in a new module flag meatadata 'riscv-isa-bits'.

2021-07-20 Thread Zakk Chen via Phabricator via cfe-commits
khchen created this revision.
khchen added reviewers: jrtc27, MaskRay, kito-cheng.
Herald added subscribers: vkmr, frasercrmck, dexonsmith, evandro, luismarques, 
apazos, sameer.abuasal, s.egerton, Jim, benna, psnobl, jocewei, PkmX, the_o, 
brucehoult, MartinMosbeck, rogfer01, edward-jones, zzheng, shiva0217, niosHD, 
sabuasal, simoncook, johnrusso, rbar, asb, hiraditya.
khchen requested review of this revision.
Herald added projects: clang, LLVM.
Herald added subscribers: llvm-commits, cfe-commits.

1. Support a new link behavoir 'OR' for module flag metadata, use for 
riscv-isa-bits.

(This feature could be in separated patch if PoC patch is workable.)

2. riscv-isa-bits records the march information for a module.

RISCVAsmPrinter reads the riscv-isa-bits to generate corrent arch attribute
if -mattr is missing.

Currently RISC-V encodes arch information per function attribute, 
'target-features'.
so there are two issues we want to fix.

1. In IFUNC case (ex. https://godbolt.org/z/a1oTbacn9), the final arch

attribute information is ambiguous because one compilation unit have
different target-feature value in function attribute.
We could not just union of all target-features, because in IFUNC case,
the base arch string is excepted elf arch attribute.

2. During the LTO, clang driver will not pass -march option to LTO code

generator, because users maybe specify the incorrect -march value if
some linked external libraries have been compiled with different arch
extensions.

The probably way is adding a new module flag metadata, riscv-isa-bits, to
records -march info for one compilation unit, and each riscv-isa-bits
get combined (OR) when linking.

In this PoC patch, I think the potential issue is illegal arch combination
will report an error in code generation stage, not in linking stage.
(For example, zfinx is conflict with f/d/q, and Zceb and Zcec are conflict with 
d)
I'm not sure having a target dependence behaivor in bitcode linking does make
sense or not.

Thanks for @jrtc27, @MaskRay to address this issue in D102926 
 and D102925 
,
and @kito-cheng's reminder of exclusive extensions issue.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D106347

Files:
  clang/lib/CodeGen/CodeGenModule.cpp
  clang/lib/CodeGen/CodeGenTypeCache.h
  clang/test/CodeGen/RISCV/riscv-metadata-isa-bits-empty-target-feature.cpp
  clang/test/CodeGen/RISCV/riscv-metadata-isa-bits-ifunc.c
  clang/test/CodeGen/RISCV/riscv-metadata-isa-bits.c
  llvm/include/llvm/IR/Module.h
  llvm/include/llvm/Support/RISCVISAInfo.h
  llvm/lib/IR/Verifier.cpp
  llvm/lib/Linker/IRMover.cpp
  llvm/lib/Support/RISCVISAInfo.cpp
  llvm/lib/Target/RISCV/MCTargetDesc/RISCVTargetStreamer.cpp
  llvm/lib/Target/RISCV/MCTargetDesc/RISCVTargetStreamer.h
  llvm/lib/Target/RISCV/RISCVAsmPrinter.cpp
  llvm/test/CodeGen/RISCV/riscv-isa-bits.ll
  llvm/test/Linker/Inputs/module-flags-or-1.ll
  llvm/test/Linker/module-flags-or-1.ll

Index: llvm/test/Linker/module-flags-or-1.ll
===
--- /dev/null
+++ llvm/test/Linker/module-flags-or-1.ll
@@ -0,0 +1,18 @@
+; RUN: llvm-link %s %p/Inputs/module-flags-or-1.ll -S -o - | FileCheck %s
+
+; Test OR functionality of module flags.
+
+!0 = !{i32 8, !"or two small values", i32 8}
+; or 7FFF and 8000
+!1 = !{i32 8, !"or two big values-1", i256 9223372036854775807}
+; or 10011001 and 1010101010101010
+!2 = !{i32 8, !"or two big values-2", i256 1152921509170249729}
+!3 = !{i32 8, !"or small and big value", i32 8}
+!4 = !{i32 8, !"foo", i66 8}
+!llvm.module.flags = !{!0, !1, !2, !3, !4}
+
+;CHECK: !0 = !{i32 8, !"or two small values", i32 24}
+;CHECK: !1 = !{i32 8, !"or two big values-1", i256 -1}
+;CHECK: !2 = !{i32 8, !"or two big values-2", i256 1157442769704194065}
+;CHECK: !3 = !{i32 8, !"or small and big value", i256 24}
+;CHECK: !4 = !{i32 8, !"foo", i128 24}
Index: llvm/test/Linker/Inputs/module-flags-or-1.ll
===
--- /dev/null
+++ llvm/test/Linker/Inputs/module-flags-or-1.ll
@@ -0,0 +1,6 @@
+!0 = !{i32 8, !"or two small values", i32 16}
+!1 = !{i32 8, !"or two big values-1", i256 -9223372036854775808}
+!2 = !{i32 8, !"or two big values-2", i256 1157442765409226768}
+!3 = !{i32 8, !"or small and big value", i256 16}
+!4 = !{i32 8, !"foo", i44 16}
+!llvm.module.flags = !{!0, !1, !2, !3, !4}
Index: llvm/test/CodeGen/RISCV/riscv-isa-bits.ll
===
--- /dev/null
+++ llvm/test/CodeGen/RISCV/riscv-isa-bits.ll
@@ -0,0 +1,36 @@
+; RUN: llc -o - < %s | FileCheck %s
+; -mattr option would overwrite target-feature and module flag riscv-isa-bits
+; RUN: llc -o - -mattr=+f,+d < %s | FileCheck %s -check-prefix=ISA-F-D
+; RUN: llc --filetype=obj -o - < %s | llvm-readelf -A - \
+; RUN:   | FileCheck %s -check-prefix=OBJFILE
+
+; CHECK: .attr

[PATCH] D103873: [Clang][RISCV] Implement vsoxseg and vsuxseg.

2021-07-20 Thread Hsiangkai Wang via Phabricator via cfe-commits
HsiangKai updated this revision to Diff 360042.
HsiangKai added a comment.

Remove RV32 test cases.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D103873

Files:
  clang/include/clang/Basic/riscv_vector.td
  clang/test/CodeGen/RISCV/rvv-intrinsics-overloaded/vsoxseg.c
  clang/test/CodeGen/RISCV/rvv-intrinsics-overloaded/vsuxseg.c
  clang/test/CodeGen/RISCV/rvv-intrinsics/vsoxseg.c
  clang/test/CodeGen/RISCV/rvv-intrinsics/vsuxseg.c

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


[PATCH] D104904: [OpenMP][AMDGCN] Initial math headers support

2021-07-20 Thread Jon Chesterfield via Phabricator via cfe-commits
JonChesterfield accepted this revision.
JonChesterfield added a comment.
This revision is now accepted and ready to land.

D105221  so LGTM too


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D104904

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


[PATCH] D106296: [analyzer] Fix for faulty namespace test in SmartPtrModelling

2021-07-20 Thread Valeriy Savchenko via Phabricator via cfe-commits
vsavchenko added inline comments.



Comment at: clang/lib/StaticAnalyzer/Checkers/SmartPtrModeling.cpp:254-257
+  const auto *Decl = Call.getDecl();
+  if (!Decl)
+return false;
+  if (!Decl->getDeclContext()->isStdNamespace())

I think you can have a separate function:
```
bool isStdFunctionCall(const CallEvent &Call) {
  return Call.getDecl() && Call.getDecl()->getDeclContext()->isStdNamespace();
}
```
and then use it like this:
```
if (Call.getNumArgs() != 2 || !isStdFunctionCall(Call))
  return false;
```


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D106296

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


[PATCH] D106136: [Analyzer][solver] Fix equivalence class invariant violation in removeDeadBindings

2021-07-20 Thread Valeriy Savchenko via Phabricator via cfe-commits
vsavchenko added a comment.

In D106136#2889610 , @martong wrote:

> In D106136#2883707 , @vsavchenko 
> wrote:
>
>> In D106136#2883100 , @martong 
>> wrote:
>>
>>> Thanks for taking your time to take a look. And I accept your statements. 
>>> Nevertheless, let me explain my motivation.
>>>
>>> I thought that a class is trivial if it has only one member. And it seemed 
>>> perfectly logical to not store equivalence classes with one member. I.e `a` 
>>> equals to `a` does not hold any meaningful information it just takes 
>>> precious memory. When we add a new constraint we take careful steps to 
>>> avoid adding a new class with one member. However, when remove dead kicks 
>>> in, suddenly we end up having classes stored with one member, which is a 
>>> somewhat inconsistent design IMHO. Perhaps some better documentation could 
>>> have helped.
>>
>> Representative symbol gives its equivalence class an ID.  We use this ID for 
>> everything, for comparing and for mapping.  Since we live in a persistent 
>> world, we can't just change this ID at some point, it will basically mean 
>> that we want to replace a class with another class.  So, all maps where this 
>> class participated (constraints, class, members, disequality) should remove 
>> the old class and add the new class.  This is a huge burden.  You need to 
>> carefully do all this, and bloat existing data structures.
>>
>> Trivial class is an optimization for the vast majority of symbols that never 
>> get into any classes.  We still need to associate constraints with those.  
>> This is where implicit Symbol to Class conversion comes in handy.
>>
>> Now let's imagine that something else is merged into it.  We are obliged to 
>> officially map the symbol to its class, and the class to its members.  When 
>> this happens, it goes into the data structure FOREVER.  And when in the 
>> future, with only one member, instead of keeping something that we already 
>> have from other versions of the data structure, you decide to remove the 
>> item from the class map, you actually use more memory when it was there!  
>> This is how persistent data structures work, different versions of the same 
>> data structure share data.  And I'm not even talking here about the fact 
>> that you now need to replace the class with one ID with the class with 
>> another ID in every relationship.
>>
>> You can probably measure memory footprint in your example and see it for 
>> yourself.
>
> Yeah, makes sense. Thanks for taking more time for further explanations. 
> Still, IMHO, the definition of a **trivial class** needs a clear written 
> documentation in the code itself, so other developers can easier understand 
> and maintain this code. I am going to create an NFC patch that summarizes 
> this discussion in a comment attached to the `isTrivial` function.

That's a great idea!  Thanks!


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D106136

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


[PATCH] D106285: [Analyzer][solver] Fix inconsistent equivalence class data

2021-07-20 Thread Valeriy Savchenko via Phabricator via cfe-commits
vsavchenko added a comment.

Ah, I see now!  I think we could've put together a somewhat easier test knowing 
what's wrong, but it's not important at all.
Thanks for addressing this issue!


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D106285

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


[PATCH] D106296: [analyzer] Fix for faulty namespace test in SmartPtrModelling

2021-07-20 Thread Valeriy Savchenko via Phabricator via cfe-commits
vsavchenko added a comment.

Also, I tested this fix on a set of open-source projects and I don't see any 
problems.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D106296

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


[PATCH] D106349: [clang-format] respect AfterEnum for enums

2021-07-20 Thread Michael Zimmermann via Phabricator via cfe-commits
m1cha created this revision.
m1cha added a reviewer: MyDeveloperDay.
m1cha requested review of this revision.
Herald added a project: clang.

See the commit message for more details.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D106349

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


Index: clang/unittests/Format/FormatTest.cpp
===
--- clang/unittests/Format/FormatTest.cpp
+++ clang/unittests/Format/FormatTest.cpp
@@ -1344,6 +1344,14 @@
   Style.AllowShortEnumsOnASingleLine = true;
   verifyFormat("enum { A, B, C } ShortEnum1, ShortEnum2;", Style);
   Style.AllowShortEnumsOnASingleLine = false;
+  verifyFormat("enum {\n"
+   "  A,\n"
+   "  B,\n"
+   "  C\n"
+   "} ShortEnum1, ShortEnum2;",
+   Style);
+  Style.BreakBeforeBraces = FormatStyle::BS_Custom;
+  Style.BraceWrapping.AfterEnum = true;
   verifyFormat("enum\n"
"{\n"
"  A,\n"
Index: clang/lib/Format/UnwrappedLineParser.cpp
===
--- clang/lib/Format/UnwrappedLineParser.cpp
+++ clang/lib/Format/UnwrappedLineParser.cpp
@@ -707,6 +707,8 @@
 return Style.BraceWrapping.AfterUnion;
   if (InitialToken.is(tok::kw_struct))
 return Style.BraceWrapping.AfterStruct;
+  if (InitialToken.is(tok::kw_enum))
+return Style.BraceWrapping.AfterEnum;
   return false;
 }
 
@@ -2452,6 +2454,8 @@
 }
 
 bool UnwrappedLineParser::parseEnum() {
+  const FormatToken &InitialToken = *FormatTok;
+
   // Won't be 'enum' for NS_ENUMs.
   if (FormatTok->Tok.is(tok::kw_enum))
 nextToken();
@@ -2502,7 +2506,8 @@
 return true;
   }
 
-  if (!Style.AllowShortEnumsOnASingleLine)
+  if (!Style.AllowShortEnumsOnASingleLine &&
+  ShouldBreakBeforeBrace(Style, InitialToken))
 addUnwrappedLine();
   // Parse enum body.
   nextToken();


Index: clang/unittests/Format/FormatTest.cpp
===
--- clang/unittests/Format/FormatTest.cpp
+++ clang/unittests/Format/FormatTest.cpp
@@ -1344,6 +1344,14 @@
   Style.AllowShortEnumsOnASingleLine = true;
   verifyFormat("enum { A, B, C } ShortEnum1, ShortEnum2;", Style);
   Style.AllowShortEnumsOnASingleLine = false;
+  verifyFormat("enum {\n"
+   "  A,\n"
+   "  B,\n"
+   "  C\n"
+   "} ShortEnum1, ShortEnum2;",
+   Style);
+  Style.BreakBeforeBraces = FormatStyle::BS_Custom;
+  Style.BraceWrapping.AfterEnum = true;
   verifyFormat("enum\n"
"{\n"
"  A,\n"
Index: clang/lib/Format/UnwrappedLineParser.cpp
===
--- clang/lib/Format/UnwrappedLineParser.cpp
+++ clang/lib/Format/UnwrappedLineParser.cpp
@@ -707,6 +707,8 @@
 return Style.BraceWrapping.AfterUnion;
   if (InitialToken.is(tok::kw_struct))
 return Style.BraceWrapping.AfterStruct;
+  if (InitialToken.is(tok::kw_enum))
+return Style.BraceWrapping.AfterEnum;
   return false;
 }
 
@@ -2452,6 +2454,8 @@
 }
 
 bool UnwrappedLineParser::parseEnum() {
+  const FormatToken &InitialToken = *FormatTok;
+
   // Won't be 'enum' for NS_ENUMs.
   if (FormatTok->Tok.is(tok::kw_enum))
 nextToken();
@@ -2502,7 +2506,8 @@
 return true;
   }
 
-  if (!Style.AllowShortEnumsOnASingleLine)
+  if (!Style.AllowShortEnumsOnASingleLine &&
+  ShouldBreakBeforeBrace(Style, InitialToken))
 addUnwrappedLine();
   // Parse enum body.
   nextToken();
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D106349: [clang-format] respect AfterEnum for enums

2021-07-20 Thread Michael Zimmermann via Phabricator via cfe-commits
m1cha added a comment.

I just noticed that phabricator strips the commit message so here it is:

There is some similar looking code in `TokenAnnotator.cpp` but given that I've
never worked on clang-format before I don't know what the purpose of that code
is and how it's related to `UnwrappedLineParser.cpp`.

Either way, it fixes clang-format with `BraceWrapping.AfterEnum=true` and
`AllowShortEnumsOnASingleLine=false` to behave like the documentation says.

Before this patch:

  enum
  {
A,
B
  } myEnum;

After this patch:

  enum {
A,
B
  } myEnum;

According to the unittests which I had to modify this would change the LLVM
style. Please evaluate if you want to change the defaults or if you consider
the current style a bug.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D106349

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


[PATCH] D106296: [analyzer] Fix for faulty namespace test in SmartPtrModelling

2021-07-20 Thread Deep Majumder via Phabricator via cfe-commits
RedDocMD updated this revision to Diff 360051.
RedDocMD added a comment.

Refactored out check


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D106296

Files:
  clang/lib/StaticAnalyzer/Checkers/SmartPtrModeling.cpp
  clang/test/Analysis/smart-ptr.cpp


Index: clang/test/Analysis/smart-ptr.cpp
===
--- clang/test/Analysis/smart-ptr.cpp
+++ clang/test/Analysis/smart-ptr.cpp
@@ -536,3 +536,10 @@
 }
 
 #endif
+
+// The following test isn't really a "smart-ptr" test
+// It came up during a bug fix (D106296)
+void testCheckForFunctionsWithNoDecl(void (*bar)(bool, bool)) {
+  // This should NOT crash.
+  bar(true, false);
+}
Index: clang/lib/StaticAnalyzer/Checkers/SmartPtrModeling.cpp
===
--- clang/lib/StaticAnalyzer/Checkers/SmartPtrModeling.cpp
+++ clang/lib/StaticAnalyzer/Checkers/SmartPtrModeling.cpp
@@ -248,9 +248,15 @@
   return hasStdClassWithName(RD, BASIC_OSTREAM_NAMES);
 }
 
+static bool isStdFunctionCall(const CallEvent &Call) {
+  const auto *Decl = Call.getDecl();
+  if (!Decl)
+return false;
+  return Decl->getDeclContext()->isStdNamespace();
+}
+
 bool isStdOstreamOperatorCall(const CallEvent &Call) {
-  if (Call.getNumArgs() != 2 ||
-  !Call.getDecl()->getDeclContext()->isStdNamespace())
+  if (Call.getNumArgs() != 2 || !isStdFunctionCall(Call))
 return false;
   const auto *FC = dyn_cast(&Call);
   if (!FC)
@@ -265,6 +271,13 @@
  isStdBasicOstream(Call.getArgExpr(0));
 }
 
+static bool isPotentiallyComparisionOpCall(const CallEvent &Call) {
+  if (Call.getNumArgs() != 2 || !isStdFunctionCall(Call))
+return false;
+  return smartptr::isStdSmartPtr(Call.getArgExpr(0)) ||
+ smartptr::isStdSmartPtr(Call.getArgExpr(1));
+}
+
 bool SmartPtrModeling::evalCall(const CallEvent &Call,
 CheckerContext &C) const {
 
@@ -272,14 +285,11 @@
 
   // If any one of the arg is a unique_ptr, then
   // we can try this function
-  if (Call.getNumArgs() == 2 &&
-  Call.getDecl()->getDeclContext()->isStdNamespace())
-if (smartptr::isStdSmartPtr(Call.getArgExpr(0)) ||
-smartptr::isStdSmartPtr(Call.getArgExpr(1)))
-  if (handleComparisionOp(Call, C))
-return true;
-
-  if (isStdOstreamOperatorCall(Call))
+  if (ModelSmartPtrDereference && isPotentiallyComparisionOpCall(Call))
+if (handleComparisionOp(Call, C))
+  return true;
+
+  if (ModelSmartPtrDereference && isStdOstreamOperatorCall(Call))
 return handleOstreamOperator(Call, C);
 
   if (Call.isCalled(StdSwapCall)) {


Index: clang/test/Analysis/smart-ptr.cpp
===
--- clang/test/Analysis/smart-ptr.cpp
+++ clang/test/Analysis/smart-ptr.cpp
@@ -536,3 +536,10 @@
 }
 
 #endif
+
+// The following test isn't really a "smart-ptr" test
+// It came up during a bug fix (D106296)
+void testCheckForFunctionsWithNoDecl(void (*bar)(bool, bool)) {
+  // This should NOT crash.
+  bar(true, false);
+}
Index: clang/lib/StaticAnalyzer/Checkers/SmartPtrModeling.cpp
===
--- clang/lib/StaticAnalyzer/Checkers/SmartPtrModeling.cpp
+++ clang/lib/StaticAnalyzer/Checkers/SmartPtrModeling.cpp
@@ -248,9 +248,15 @@
   return hasStdClassWithName(RD, BASIC_OSTREAM_NAMES);
 }
 
+static bool isStdFunctionCall(const CallEvent &Call) {
+  const auto *Decl = Call.getDecl();
+  if (!Decl)
+return false;
+  return Decl->getDeclContext()->isStdNamespace();
+}
+
 bool isStdOstreamOperatorCall(const CallEvent &Call) {
-  if (Call.getNumArgs() != 2 ||
-  !Call.getDecl()->getDeclContext()->isStdNamespace())
+  if (Call.getNumArgs() != 2 || !isStdFunctionCall(Call))
 return false;
   const auto *FC = dyn_cast(&Call);
   if (!FC)
@@ -265,6 +271,13 @@
  isStdBasicOstream(Call.getArgExpr(0));
 }
 
+static bool isPotentiallyComparisionOpCall(const CallEvent &Call) {
+  if (Call.getNumArgs() != 2 || !isStdFunctionCall(Call))
+return false;
+  return smartptr::isStdSmartPtr(Call.getArgExpr(0)) ||
+ smartptr::isStdSmartPtr(Call.getArgExpr(1));
+}
+
 bool SmartPtrModeling::evalCall(const CallEvent &Call,
 CheckerContext &C) const {
 
@@ -272,14 +285,11 @@
 
   // If any one of the arg is a unique_ptr, then
   // we can try this function
-  if (Call.getNumArgs() == 2 &&
-  Call.getDecl()->getDeclContext()->isStdNamespace())
-if (smartptr::isStdSmartPtr(Call.getArgExpr(0)) ||
-smartptr::isStdSmartPtr(Call.getArgExpr(1)))
-  if (handleComparisionOp(Call, C))
-return true;
-
-  if (isStdOstreamOperatorCall(Call))
+  if (ModelSmartPtrDereference && isPotentiallyComparisionOpCall(Call))
+if (handleComparisionOp(Call, C))
+  return true;
+
+  if (ModelSmartPtrDereference && isStdOstreamOpera

[PATCH] D105491: [clang] Use i64 for the !srcloc metadata on asm IR nodes.

2021-07-20 Thread Simon Tatham via Phabricator via cfe-commits
simon_tatham added a comment.

I looked into this yesterday, and realised that I don't actually know what the 
use case //is// for emitting `!srcloc` metadata in an IR file.

It's more or less ignored by llc, as far as I can see: if there's a 
late-breaking error in the inline asm string, you just get a "note: !srcloc = 
" alongside the main error.

And if the IR file is read back in by a second invocation of clang, then the 
frontend callback //does// get the !srcloc back from the IR, but it can't 
relate that to the original source code, because the new clang's SourceManager 
doesn't know anything about the C source files that the IR was made from. In 
the example test I just did by hand, the error message cites a location in the 
IR file that corresponds to the byte position of the error in the original C, 
which is more or less useless.

So I think this mechanism is only actually useful when the whole compilation is 
happening within a single invocation of clang, so that the !srcloc finds its 
way back to a SourceManager that still has all the actual source code in mind. 
As soon as IR files are exported and re-imported, the best we can hope for is 
"no crash".

But I can add a couple of tests along those lines for i32 and i64 versions of 
!srcloc, if that's helpful.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D105491

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


[PATCH] D106296: [analyzer] Fix for faulty namespace test in SmartPtrModelling

2021-07-20 Thread Valeriy Savchenko via Phabricator via cfe-commits
vsavchenko added inline comments.



Comment at: clang/lib/StaticAnalyzer/Checkers/SmartPtrModeling.cpp:252-255
+  const auto *Decl = Call.getDecl();
+  if (!Decl)
+return false;
+  return Decl->getDeclContext()->isStdNamespace();

Can we use a one-liner that I suggested?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D106296

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


[PATCH] D105703: [hwasan] Use stack safety analysis.

2021-07-20 Thread Florian Mayer via Phabricator via cfe-commits
fmayer updated this revision to Diff 360054.
fmayer marked an inline comment as done.
fmayer added a comment.

format


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D105703

Files:
  clang/lib/CodeGen/BackendUtil.cpp
  clang/test/CodeGen/hwasan-stack-safety-analysis.c
  llvm/include/llvm/Transforms/Instrumentation/HWAddressSanitizer.h
  llvm/lib/Transforms/Instrumentation/HWAddressSanitizer.cpp
  llvm/test/Instrumentation/HWAddressSanitizer/stack-safety-analysis.ll

Index: llvm/test/Instrumentation/HWAddressSanitizer/stack-safety-analysis.ll
===
--- /dev/null
+++ llvm/test/Instrumentation/HWAddressSanitizer/stack-safety-analysis.ll
@@ -0,0 +1,42 @@
+; RUN: opt -hwasan -hwasan-use-stack-safety=1 -hwasan-generate-tags-with-calls -S < %s | FileCheck %s --check-prefixes=SAFETY
+; RUN: opt -hwasan -hwasan-use-stack-safety=0 -hwasan-generate-tags-with-calls -S < %s | FileCheck %s --check-prefixes=NOSAFETY
+
+target datalayout = "e-m:e-i8:8:32-i16:16:32-i64:64-i128:128-n32:64-S128"
+target triple = "aarch64-unknown-linux-gnu"
+
+; Check a safe alloca to ensure it does not get a tag.
+define i32 @test_load(i32* %a) sanitize_hwaddress {
+entry:
+  ; NOSAFETY: call {{.*}}__hwasan_generate_tag
+  ; SAFETY-NOT: call {{.*}}__hwasan_generate_tag
+  %buf.sroa.0 = alloca i8, align 4
+  call void @llvm.lifetime.start.p0i8(i64 1, i8* nonnull %buf.sroa.0)
+  store volatile i8 0, i8* %buf.sroa.0, align 4, !tbaa !8
+  call void @llvm.lifetime.end.p0i8(i64 1, i8* nonnull %buf.sroa.0)
+  ret i32 0
+}
+
+; Check a non-safe alloca to ensure it gets a tag.
+define i32 @test_use(i32* %a) sanitize_hwaddress {
+entry:
+  ; NOSAFETY: call {{.*}}__hwasan_generate_tag
+  ; SAFETY: call {{.*}}__hwasan_generate_tag
+  %buf.sroa.0 = alloca i8, align 4
+  call void @use(i8* nonnull %buf.sroa.0)
+  call void @llvm.lifetime.start.p0i8(i64 1, i8* nonnull %buf.sroa.0)
+  store volatile i8 0, i8* %buf.sroa.0, align 4, !tbaa !8
+  call void @llvm.lifetime.end.p0i8(i64 1, i8* nonnull %buf.sroa.0)
+  ret i32 0
+}
+
+; Function Attrs: argmemonly mustprogress nofree nosync nounwind willreturn
+declare void @llvm.lifetime.start.p0i8(i64 immarg, i8* nocapture)
+
+; Function Attrs: argmemonly mustprogress nofree nosync nounwind willreturn
+declare void @llvm.lifetime.end.p0i8(i64 immarg, i8* nocapture)
+
+declare void @use(i8* nocapture)
+
+!8 = !{!9, !9, i64 0}
+!9 = !{!"omnipotent char", !10, i64 0}
+!10 = !{!"Simple C/C++ TBAA"}
Index: llvm/lib/Transforms/Instrumentation/HWAddressSanitizer.cpp
===
--- llvm/lib/Transforms/Instrumentation/HWAddressSanitizer.cpp
+++ llvm/lib/Transforms/Instrumentation/HWAddressSanitizer.cpp
@@ -17,6 +17,7 @@
 #include "llvm/ADT/StringExtras.h"
 #include "llvm/ADT/StringRef.h"
 #include "llvm/ADT/Triple.h"
+#include "llvm/Analysis/StackSafetyAnalysis.h"
 #include "llvm/BinaryFormat/ELF.h"
 #include "llvm/IR/Attributes.h"
 #include "llvm/IR/BasicBlock.h"
@@ -109,6 +110,11 @@
cl::desc("instrument stack (allocas)"),
cl::Hidden, cl::init(true));
 
+static cl::opt
+ClUseStackSafety("hwasan-use-stack-safety", cl::Hidden, cl::init(true),
+ cl::Hidden, cl::desc("Use Stack Safety analysis results"),
+ cl::Optional);
+
 static cl::opt ClUARRetagToZero(
 "hwasan-uar-retag-to-zero",
 cl::desc("Clear alloca tags before returning from the function to allow "
@@ -216,11 +222,22 @@
 #endif
 }
 
+bool shouldUseStackSafetyAnalysis(const Triple &TargetTriple,
+  bool DisableOptimization) {
+  auto StackSafety = ClUseStackSafety.getNumOccurrences()
+ ? ClUseStackSafety
+ : !DisableOptimization;
+  return shouldInstrumentStack(TargetTriple) && StackSafety;
+// No one should use the option directly.
+#pragma GCC poison ClUseStackSafety
+}
 /// An instrumentation pass implementing detection of addressability bugs
 /// using tagged pointers.
 class HWAddressSanitizer {
 public:
-  HWAddressSanitizer(Module &M, bool CompileKernel, bool Recover) : M(M) {
+  HWAddressSanitizer(Module &M, bool CompileKernel, bool Recover,
+ const StackSafetyGlobalInfo *SSI)
+  : M(M), SSI(SSI) {
 this->Recover = ClRecover.getNumOccurrences() > 0 ? ClRecover : Recover;
 this->CompileKernel = ClEnableKhwasan.getNumOccurrences() > 0
   ? ClEnableKhwasan
@@ -229,6 +246,8 @@
 initializeModule();
   }
 
+  void setSSI(const StackSafetyGlobalInfo *S) { SSI = S; }
+
   bool sanitizeFunction(Function &F);
   void initializeModule();
   void createHwasanCtorComdat();
@@ -281,6 +300,7 @@
 private:
   LLVMContext *C;
   Module &M;
+  const StackSafetyGlobalInfo *SSI;
   Triple TargetTriple;
   Fun

[PATCH] D104797: [WebAssembly] Implementation of global.get/set for reftypes in LLVM IR

2021-07-20 Thread Paulo Matos via Phabricator via cfe-commits
pmatos updated this revision to Diff 360055.
pmatos added a comment.

Rebase on top of main and add non-integral address spaces to emscripten OS


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D104797

Files:
  clang/lib/Basic/Targets/WebAssembly.h
  clang/test/CodeGen/target-data.c
  llvm/include/llvm/CodeGen/TargetLowering.h
  llvm/include/llvm/CodeGen/ValueTypes.h
  llvm/lib/CodeGen/CodeGenPrepare.cpp
  llvm/lib/CodeGen/MachineOperand.cpp
  llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp
  llvm/lib/CodeGen/TargetLoweringBase.cpp
  llvm/lib/CodeGen/ValueTypes.cpp
  llvm/lib/Target/WebAssembly/Utils/WebAssemblyUtilities.cpp
  llvm/lib/Target/WebAssembly/Utils/WebAssemblyUtilities.h
  llvm/lib/Target/WebAssembly/WebAssemblyFastISel.cpp
  llvm/lib/Target/WebAssembly/WebAssemblyISD.def
  llvm/lib/Target/WebAssembly/WebAssemblyISelDAGToDAG.cpp
  llvm/lib/Target/WebAssembly/WebAssemblyISelLowering.cpp
  llvm/lib/Target/WebAssembly/WebAssemblyISelLowering.h
  llvm/lib/Target/WebAssembly/WebAssemblyInstrTable.td
  llvm/lib/Target/WebAssembly/WebAssemblyMCInstLower.cpp
  llvm/lib/Target/WebAssembly/WebAssemblyTargetMachine.cpp
  llvm/test/CodeGen/WebAssembly/externref-globalget.ll
  llvm/test/CodeGen/WebAssembly/externref-globalset.ll
  llvm/test/CodeGen/WebAssembly/externref-inttoptr.ll
  llvm/test/CodeGen/WebAssembly/externref-ptrtoint.ll
  llvm/test/CodeGen/WebAssembly/externref-undef.ll
  llvm/test/CodeGen/WebAssembly/externref-unsized-load.ll
  llvm/test/CodeGen/WebAssembly/externref-unsized-store.ll
  llvm/test/CodeGen/WebAssembly/funcref-call.ll
  llvm/test/CodeGen/WebAssembly/funcref-globalget.ll
  llvm/test/CodeGen/WebAssembly/funcref-globalset.ll

Index: llvm/test/CodeGen/WebAssembly/funcref-globalset.ll
===
--- /dev/null
+++ llvm/test/CodeGen/WebAssembly/funcref-globalset.ll
@@ -0,0 +1,20 @@
+; RUN: llc < %s --mtriple=wasm32-unknown-unknown -asm-verbose=false -mattr=+reference-types | FileCheck %s
+
+%func = type opaque
+%funcref = type %func addrspace(20)* ;; addrspace 20 is nonintegral
+
+@funcref_global = local_unnamed_addr addrspace(1) global %funcref undef
+
+define void @set_funcref_global(%funcref %g) {
+  ;; this generates a global.set of @funcref_global
+  store %funcref %g, %funcref addrspace(1)* @funcref_global
+  ret void
+}
+
+; CHECK-LABEL: set_funcref_global:
+; CHECK-NEXT: functype   set_funcref_global (funcref) -> ()
+; CHECK-NEXT: local.get  0
+; CHECK-NEXT: global.set funcref_global
+; CHECK-NEXT: end_function
+
+; CHECK: .globl funcref_global
Index: llvm/test/CodeGen/WebAssembly/funcref-globalget.ll
===
--- /dev/null
+++ llvm/test/CodeGen/WebAssembly/funcref-globalget.ll
@@ -0,0 +1,19 @@
+; RUN: llc < %s --mtriple=wasm32-unknown-unknown -asm-verbose=false -mattr=+reference-types | FileCheck %s
+
+%func = type opaque
+%funcref = type %func addrspace(20)* ;; addrspace 20 is nonintegral
+
+@funcref_global = local_unnamed_addr addrspace(1) global %funcref undef
+
+define %funcref @return_funcref_global() {
+  ;; this generates a global.get of @funcref_global
+  %ref = load %funcref, %funcref addrspace(1)* @funcref_global
+  ret %funcref %ref
+}
+
+; CHECK-LABEL: return_funcref_global:
+; CHECK-NEXT: .functype   return_funcref_global () -> (funcref)
+; CHECK-NEXT: global.get funcref_global
+; CHECK-NEXT: end_function
+
+; CHECK: .globl funcref_global
Index: llvm/test/CodeGen/WebAssembly/funcref-call.ll
===
--- /dev/null
+++ llvm/test/CodeGen/WebAssembly/funcref-call.ll
@@ -0,0 +1,24 @@
+; RUN: llc < %s --mtriple=wasm32-unknown-unknown -asm-verbose=false -mattr=+reference-types | FileCheck %s
+
+%func = type void ()
+%funcref = type %func addrspace(20)* ;; addrspace 20 is nonintegral
+
+define void @call_funcref(%funcref %ref) {
+  call addrspace(20) void %ref() 
+  ret void
+}
+
+; CHECK: .tabletype __funcref_call_table, funcref, 1
+
+; CHECK-LABEL: call_funcref:
+; CHECK-NEXT: functype   call_funcref (funcref) -> ()
+; CHECK-NEXT: i32.const 0
+; CHECK-NEXT: local.get 0
+; CHECK-NEXT: table.set __funcref_call_table
+; CHECK-NEXT: local.get 0
+; CHECK-NEXT: call_indirect __funcref_call_table, () -> ()
+; CHECK-NEXT: i32.const 0
+; CHECK-NEXT: ref.null func
+; CHECK-NEXT: table.set __funcref_call_table
+; CHECK-NEXT: end_function
+
Index: llvm/test/CodeGen/WebAssembly/externref-unsized-store.ll
===
--- /dev/null
+++ llvm/test/CodeGen/WebAssembly/externref-unsized-store.ll
@@ -0,0 +1,11 @@
+; RUN: not llc --mtriple=wasm32-unknown-unknown -asm-verbose=false -mattr=+reference-types < %s 2>&1 | FileCheck %s --check-prefix=CHECK-ERROR
+
+%extern = type opaque
+%externref = type %extern addrspace(10)*
+
+define void @store_extern(%externref %r

[clang] e9c63ed - [hwasan] Use stack safety analysis.

2021-07-20 Thread Florian Mayer via cfe-commits

Author: Florian Mayer
Date: 2021-07-20T10:06:35+01:00
New Revision: e9c63ed10b3bdf6eb3fa76d1a3eb403d6fc6a118

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

LOG: [hwasan] Use stack safety analysis.

This avoids unnecessary instrumentation.

Reviewed By: eugenis, vitalybuka

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

Added: 
clang/test/CodeGen/hwasan-stack-safety-analysis.c
llvm/test/Instrumentation/HWAddressSanitizer/stack-safety-analysis.ll

Modified: 
clang/lib/CodeGen/BackendUtil.cpp
llvm/include/llvm/Transforms/Instrumentation/HWAddressSanitizer.h
llvm/lib/Transforms/Instrumentation/HWAddressSanitizer.cpp

Removed: 




diff  --git a/clang/lib/CodeGen/BackendUtil.cpp 
b/clang/lib/CodeGen/BackendUtil.cpp
index 9aa67ed2a67ba..481f5347d978b 100644
--- a/clang/lib/CodeGen/BackendUtil.cpp
+++ b/clang/lib/CodeGen/BackendUtil.cpp
@@ -314,14 +314,19 @@ static void addHWAddressSanitizerPasses(const 
PassManagerBuilder &Builder,
   static_cast(Builder);
   const CodeGenOptions &CGOpts = BuilderWrapper.getCGOpts();
   bool Recover = CGOpts.SanitizeRecover.has(SanitizerKind::HWAddress);
-  PM.add(
-  createHWAddressSanitizerLegacyPassPass(/*CompileKernel*/ false, 
Recover));
+  PM.add(createHWAddressSanitizerLegacyPassPass(
+  /*CompileKernel*/ false, Recover,
+  /*DisableOptimization*/ CGOpts.OptimizationLevel == 0));
 }
 
 static void addKernelHWAddressSanitizerPasses(const PassManagerBuilder 
&Builder,
-legacy::PassManagerBase &PM) {
+  legacy::PassManagerBase &PM) {
+  const PassManagerBuilderWrapper &BuilderWrapper =
+  static_cast(Builder);
+  const CodeGenOptions &CGOpts = BuilderWrapper.getCGOpts();
   PM.add(createHWAddressSanitizerLegacyPassPass(
-  /*CompileKernel*/ true, /*Recover*/ true));
+  /*CompileKernel*/ true, /*Recover*/ true,
+  /*DisableOptimization*/ CGOpts.OptimizationLevel == 0));
 }
 
 static void addGeneralOptsForMemorySanitizer(const PassManagerBuilder &Builder,
@@ -1164,7 +1169,9 @@ static void addSanitizers(const Triple &TargetTriple,
 auto HWASanPass = [&](SanitizerMask Mask, bool CompileKernel) {
   if (LangOpts.Sanitize.has(Mask)) {
 bool Recover = CodeGenOpts.SanitizeRecover.has(Mask);
-MPM.addPass(HWAddressSanitizerPass(CompileKernel, Recover));
+MPM.addPass(HWAddressSanitizerPass(
+CompileKernel, Recover,
+/*DisableOptimization=*/CodeGenOpts.OptimizationLevel == 0));
   }
 };
 HWASanPass(SanitizerKind::HWAddress, false);

diff  --git a/clang/test/CodeGen/hwasan-stack-safety-analysis.c 
b/clang/test/CodeGen/hwasan-stack-safety-analysis.c
new file mode 100644
index 0..5c4f34027bacd
--- /dev/null
+++ b/clang/test/CodeGen/hwasan-stack-safety-analysis.c
@@ -0,0 +1,15 @@
+// RUN: %clang -fsanitize=hwaddress -target aarch64-linux-gnu -S -emit-llvm 
-mllvm -hwasan-use-stack-safety=true -mllvm -hwasan-generate-tags-with-calls 
-O2 %s -o - | FileCheck %s --check-prefix=SAFETY
+// RUN: %clang -fsanitize=hwaddress -target aarch64-linux-gnu -S -emit-llvm 
-mllvm -hwasan-use-stack-safety=false -mllvm -hwasan-generate-tags-with-calls 
-O2 %s -o - | FileCheck %s --check-prefix=NOSAFETY
+
+// Default when optimizing, but not with O0.
+// RUN: %clang -fsanitize=hwaddress -target aarch64-linux-gnu -S -emit-llvm 
-mllvm -hwasan-generate-tags-with-calls -O2 %s -o - | FileCheck %s 
--check-prefix=SAFETY
+// RUN: %clang -fsanitize=hwaddress -target aarch64-linux-gnu -S -emit-llvm 
-mllvm -hwasan-generate-tags-with-calls -O0 %s -o - | FileCheck %s 
--check-prefix=NOSAFETY
+
+int main(int argc, char **argv) {
+  char buf[10];
+  volatile char *x = buf;
+  *x = 0;
+  return buf[0];
+  // NOSAFETY: __hwasan_generate_tag
+  // SAFETY-NOT: __hwasan_generate_tag
+}

diff  --git a/llvm/include/llvm/Transforms/Instrumentation/HWAddressSanitizer.h 
b/llvm/include/llvm/Transforms/Instrumentation/HWAddressSanitizer.h
index 76e02f06435c3..2e4f3338030a4 100644
--- a/llvm/include/llvm/Transforms/Instrumentation/HWAddressSanitizer.h
+++ b/llvm/include/llvm/Transforms/Instrumentation/HWAddressSanitizer.h
@@ -25,17 +25,21 @@ namespace llvm {
 class HWAddressSanitizerPass : public PassInfoMixin {
 public:
   explicit HWAddressSanitizerPass(bool CompileKernel = false,
-  bool Recover = false);
+  bool Recover = false,
+  bool DisableOptimization = false);
   PreservedAnalyses run(Module &M, ModuleAnalysisManager &MAM);
   static bool isRequired() { return true; }
 
 private:
   bool CompileKernel;
   bool Recover;
+  bool DisableOptimization;
 };
 
-FunctionPass *createHWAdd

[PATCH] D105703: [hwasan] Use stack safety analysis.

2021-07-20 Thread Florian Mayer via Phabricator via cfe-commits
This revision was landed with ongoing or failed builds.
This revision was automatically updated to reflect the committed changes.
Closed by commit rGe9c63ed10b3b: [hwasan] Use stack safety analysis. (authored 
by fmayer).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D105703

Files:
  clang/lib/CodeGen/BackendUtil.cpp
  clang/test/CodeGen/hwasan-stack-safety-analysis.c
  llvm/include/llvm/Transforms/Instrumentation/HWAddressSanitizer.h
  llvm/lib/Transforms/Instrumentation/HWAddressSanitizer.cpp
  llvm/test/Instrumentation/HWAddressSanitizer/stack-safety-analysis.ll

Index: llvm/test/Instrumentation/HWAddressSanitizer/stack-safety-analysis.ll
===
--- /dev/null
+++ llvm/test/Instrumentation/HWAddressSanitizer/stack-safety-analysis.ll
@@ -0,0 +1,42 @@
+; RUN: opt -hwasan -hwasan-use-stack-safety=1 -hwasan-generate-tags-with-calls -S < %s | FileCheck %s --check-prefixes=SAFETY
+; RUN: opt -hwasan -hwasan-use-stack-safety=0 -hwasan-generate-tags-with-calls -S < %s | FileCheck %s --check-prefixes=NOSAFETY
+
+target datalayout = "e-m:e-i8:8:32-i16:16:32-i64:64-i128:128-n32:64-S128"
+target triple = "aarch64-unknown-linux-gnu"
+
+; Check a safe alloca to ensure it does not get a tag.
+define i32 @test_load(i32* %a) sanitize_hwaddress {
+entry:
+  ; NOSAFETY: call {{.*}}__hwasan_generate_tag
+  ; SAFETY-NOT: call {{.*}}__hwasan_generate_tag
+  %buf.sroa.0 = alloca i8, align 4
+  call void @llvm.lifetime.start.p0i8(i64 1, i8* nonnull %buf.sroa.0)
+  store volatile i8 0, i8* %buf.sroa.0, align 4, !tbaa !8
+  call void @llvm.lifetime.end.p0i8(i64 1, i8* nonnull %buf.sroa.0)
+  ret i32 0
+}
+
+; Check a non-safe alloca to ensure it gets a tag.
+define i32 @test_use(i32* %a) sanitize_hwaddress {
+entry:
+  ; NOSAFETY: call {{.*}}__hwasan_generate_tag
+  ; SAFETY: call {{.*}}__hwasan_generate_tag
+  %buf.sroa.0 = alloca i8, align 4
+  call void @use(i8* nonnull %buf.sroa.0)
+  call void @llvm.lifetime.start.p0i8(i64 1, i8* nonnull %buf.sroa.0)
+  store volatile i8 0, i8* %buf.sroa.0, align 4, !tbaa !8
+  call void @llvm.lifetime.end.p0i8(i64 1, i8* nonnull %buf.sroa.0)
+  ret i32 0
+}
+
+; Function Attrs: argmemonly mustprogress nofree nosync nounwind willreturn
+declare void @llvm.lifetime.start.p0i8(i64 immarg, i8* nocapture)
+
+; Function Attrs: argmemonly mustprogress nofree nosync nounwind willreturn
+declare void @llvm.lifetime.end.p0i8(i64 immarg, i8* nocapture)
+
+declare void @use(i8* nocapture)
+
+!8 = !{!9, !9, i64 0}
+!9 = !{!"omnipotent char", !10, i64 0}
+!10 = !{!"Simple C/C++ TBAA"}
Index: llvm/lib/Transforms/Instrumentation/HWAddressSanitizer.cpp
===
--- llvm/lib/Transforms/Instrumentation/HWAddressSanitizer.cpp
+++ llvm/lib/Transforms/Instrumentation/HWAddressSanitizer.cpp
@@ -17,6 +17,7 @@
 #include "llvm/ADT/StringExtras.h"
 #include "llvm/ADT/StringRef.h"
 #include "llvm/ADT/Triple.h"
+#include "llvm/Analysis/StackSafetyAnalysis.h"
 #include "llvm/BinaryFormat/ELF.h"
 #include "llvm/IR/Attributes.h"
 #include "llvm/IR/BasicBlock.h"
@@ -109,6 +110,11 @@
cl::desc("instrument stack (allocas)"),
cl::Hidden, cl::init(true));
 
+static cl::opt
+ClUseStackSafety("hwasan-use-stack-safety", cl::Hidden, cl::init(true),
+ cl::Hidden, cl::desc("Use Stack Safety analysis results"),
+ cl::Optional);
+
 static cl::opt ClUARRetagToZero(
 "hwasan-uar-retag-to-zero",
 cl::desc("Clear alloca tags before returning from the function to allow "
@@ -216,11 +222,22 @@
 #endif
 }
 
+bool shouldUseStackSafetyAnalysis(const Triple &TargetTriple,
+  bool DisableOptimization) {
+  auto StackSafety = ClUseStackSafety.getNumOccurrences()
+ ? ClUseStackSafety
+ : !DisableOptimization;
+  return shouldInstrumentStack(TargetTriple) && StackSafety;
+// No one should use the option directly.
+#pragma GCC poison ClUseStackSafety
+}
 /// An instrumentation pass implementing detection of addressability bugs
 /// using tagged pointers.
 class HWAddressSanitizer {
 public:
-  HWAddressSanitizer(Module &M, bool CompileKernel, bool Recover) : M(M) {
+  HWAddressSanitizer(Module &M, bool CompileKernel, bool Recover,
+ const StackSafetyGlobalInfo *SSI)
+  : M(M), SSI(SSI) {
 this->Recover = ClRecover.getNumOccurrences() > 0 ? ClRecover : Recover;
 this->CompileKernel = ClEnableKhwasan.getNumOccurrences() > 0
   ? ClEnableKhwasan
@@ -229,6 +246,8 @@
 initializeModule();
   }
 
+  void setSSI(const StackSafetyGlobalInfo *S) { SSI = S; }
+
   bool sanitizeFunction(Function &F);
   void initializeModule();
   void createHwasanCtorComdat();
@@ -281,6 +300,7 @@
 privat

[PATCH] D106266: [C++4OpenCL] Add run line standard aliases clc++1.0 and CLC++1.0

2021-07-20 Thread Justas Janickas via Phabricator via cfe-commits
Topotuna updated this revision to Diff 360059.
Topotuna added a comment.

`clc++` made no longer deprecated


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

https://reviews.llvm.org/D106266

Files:
  clang/docs/UsersManual.rst
  clang/include/clang/Basic/LangStandards.def
  clang/include/clang/Driver/Options.td
  clang/lib/Frontend/CompilerInvocation.cpp
  clang/test/Driver/autocomplete.c
  clang/test/Driver/unknown-std.cl
  lldb/source/Plugins/TypeSystem/Clang/TypeSystemClang.cpp

Index: lldb/source/Plugins/TypeSystem/Clang/TypeSystemClang.cpp
===
--- lldb/source/Plugins/TypeSystem/Clang/TypeSystemClang.cpp
+++ lldb/source/Plugins/TypeSystem/Clang/TypeSystemClang.cpp
@@ -478,7 +478,7 @@
   LangStd = LangStandard::lang_opencl10;
   break;
 case clang::Language::OpenCLCXX:
-  LangStd = LangStandard::lang_openclcpp;
+  LangStd = LangStandard::lang_openclcpp10;
   break;
 case clang::Language::CUDA:
   LangStd = LangStandard::lang_cuda;
Index: clang/test/Driver/unknown-std.cl
===
--- clang/test/Driver/unknown-std.cl
+++ clang/test/Driver/unknown-std.cl
@@ -11,7 +11,7 @@
 // CHECK-NEXT: note: use 'cl1.2' for 'OpenCL 1.2' standard
 // CHECK-NEXT: note: use 'cl2.0' for 'OpenCL 2.0' standard
 // CHECK-NEXT: note: use 'cl3.0' for 'OpenCL 3.0' standard
-// CHECK-NEXT: note: use 'clc++' for 'C++ for OpenCL' standard
+// CHECK-NEXT: note: use 'clc++1.0' or 'clc++' for 'C++ for OpenCL 1.0' standard
 
 // Make sure that no other output is present.
 // CHECK-NOT: {{^.+$}}
Index: clang/test/Driver/autocomplete.c
===
--- clang/test/Driver/autocomplete.c
+++ clang/test/Driver/autocomplete.c
@@ -49,6 +49,8 @@
 // CLSTDALL-NEXT: CL3.0
 // CLSTDALL-NEXT: clc++
 // CLSTDALL-NEXT: CLC++
+// CLSTDALL-NEXT: clc++1.0
+// CLSTDALL-NEXT: CLC++1.0
 // RUN: %clang --autocomplete=-fno-sanitize-coverage=,f | FileCheck %s -check-prefix=FNOSANICOVER
 // FNOSANICOVER: func
 // RUN: %clang --autocomplete=-fno-sanitize-coverage= | FileCheck %s -check-prefix=FNOSANICOVERALL
Index: clang/lib/Frontend/CompilerInvocation.cpp
===
--- clang/lib/Frontend/CompilerInvocation.cpp
+++ clang/lib/Frontend/CompilerInvocation.cpp
@@ -3088,7 +3088,7 @@
   LangStd = LangStandard::lang_opencl10;
   break;
 case Language::OpenCLCXX:
-  LangStd = LangStandard::lang_openclcpp;
+  LangStd = LangStandard::lang_openclcpp10;
   break;
 case Language::CUDA:
   LangStd = LangStandard::lang_cuda;
@@ -3161,7 +3161,7 @@
 Opts.OpenCLVersion = 200;
   else if (LangStd == LangStandard::lang_opencl30)
 Opts.OpenCLVersion = 300;
-  else if (LangStd == LangStandard::lang_openclcpp)
+  else if (LangStd == LangStandard::lang_openclcpp10)
 Opts.OpenCLCPlusPlusVersion = 100;
 
   // OpenCL has some additional defaults.
@@ -3311,7 +3311,7 @@
   case LangStandard::lang_opencl12:
   case LangStandard::lang_opencl20:
   case LangStandard::lang_opencl30:
-  case LangStandard::lang_openclcpp:
+  case LangStandard::lang_openclcpp10:
 StdOpt = OPT_cl_std_EQ;
 break;
   default:
@@ -3605,7 +3605,8 @@
 .Cases("cl1.2", "CL1.2", LangStandard::lang_opencl12)
 .Cases("cl2.0", "CL2.0", LangStandard::lang_opencl20)
 .Cases("cl3.0", "CL3.0", LangStandard::lang_opencl30)
-.Cases("clc++", "CLC++", LangStandard::lang_openclcpp)
+.Cases("clc++", "CLC++", LangStandard::lang_openclcpp10)
+.Cases("clc++1.0", "CLC++1.0", LangStandard::lang_openclcpp10)
 .Default(LangStandard::lang_unspecified);
 
 if (OpenCLLangStd == LangStandard::lang_unspecified) {
Index: clang/include/clang/Driver/Options.td
===
--- clang/include/clang/Driver/Options.td
+++ clang/include/clang/Driver/Options.td
@@ -843,7 +843,7 @@
   HelpText<"OpenCL only. Allow use of less precise no signed zeros computations in the generated binary.">,
   MarshallingInfoFlag>;
 def cl_std_EQ : Joined<["-"], "cl-std=">, Group, Flags<[CC1Option]>,
-  HelpText<"OpenCL language standard to compile for.">, Values<"cl,CL,cl1.0,CL1.0,cl1.1,CL1.1,cl1.2,CL1.2,cl2.0,CL2.0,cl3.0,CL3.0,clc++,CLC++">;
+  HelpText<"OpenCL language standard to compile for.">, Values<"cl,CL,cl1.0,CL1.0,cl1.1,CL1.1,cl1.2,CL1.2,cl2.0,CL2.0,cl3.0,CL3.0,clc++,CLC++,clc++1.0,CLC++1.0">;
 def cl_denorms_are_zero : Flag<["-"], "cl-denorms-are-zero">, Group,
   HelpText<"OpenCL only. Allow denormals to be flushed to zero.">;
 def cl_fp32_correctly_rounded_divide_sqrt : Flag<["-"], "cl-fp32-correctly-rounded-divide-sqrt">, Group, Flags<[CC1Option]>,
Index: clang/include/clang/Basic/LangStandards.def
===
--- clang/include/clang/Basic/LangStandards.def
++

[PATCH] D106266: [C++4OpenCL] Add run line standard aliases clc++1.0 and CLC++1.0

2021-07-20 Thread Justas Janickas via Phabricator via cfe-commits
Topotuna added inline comments.



Comment at: clang/include/clang/Basic/LangStandards.def:187
  Digraphs | HexFloat | OpenCL)
+LANGSTANDARD_ALIAS_DEPR(openclcpp10, "clc++")
 

Anastasia wrote:
> I am not sure we should move it into the deprecated category yet... for now 
> let's just use `LANGSTANDARD_ALIAS`.
You are right. I tried to closely follow how `cl1.0` version is regarded on 
line 169, but it is a slightly different case because `cl` has more than one 
version already.



Comment at: clang/test/Driver/unknown-std.cl:14
 // CHECK-NEXT: note: use 'cl3.0' for 'OpenCL 3.0' standard
-// CHECK-NEXT: note: use 'clc++' for 'C++ for OpenCL' standard
+// CHECK-NEXT: note: use 'clc++1.0' for 'C++ for OpenCL 1.0' standard
 

Anastasia wrote:
> does it not print `clc++` anymore?
The error messages here are derived from language definitions in file 
`Basic/LangStandards.def`, so both files need to be modified accordingly.


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

https://reviews.llvm.org/D106266

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


[clang] 63fd109 - [clang][deps] Normalize ignored filenames in minimizing file system

2021-07-20 Thread Jan Svoboda via cfe-commits

Author: Jan Svoboda
Date: 2021-07-20T11:31:31+02:00
New Revision: 63fd109d3aa6db48e38e1c78f6084ad257f2c37d

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

LOG: [clang][deps] Normalize ignored filenames in minimizing file system

This patch normalizes filenames in `DependencyScanningWorkerFilesystem` so that 
lookup of ignored files works correctly on Windows (where `/` and `\` are 
equivalent).

Reviewed By: dexonsmith

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

Added: 


Modified: 

clang/include/clang/Tooling/DependencyScanning/DependencyScanningFilesystem.h
clang/lib/Tooling/DependencyScanning/DependencyScanningFilesystem.cpp
clang/lib/Tooling/DependencyScanning/DependencyScanningWorker.cpp

Removed: 




diff  --git 
a/clang/include/clang/Tooling/DependencyScanning/DependencyScanningFilesystem.h 
b/clang/include/clang/Tooling/DependencyScanning/DependencyScanningFilesystem.h
index 82dc0b8fdb579..b213f388dadc0 100644
--- 
a/clang/include/clang/Tooling/DependencyScanning/DependencyScanningFilesystem.h
+++ 
b/clang/include/clang/Tooling/DependencyScanning/DependencyScanningFilesystem.h
@@ -153,10 +153,12 @@ class DependencyScanningWorkerFilesystem : public 
llvm::vfs::ProxyFileSystem {
   llvm::ErrorOr>
   openFileForRead(const Twine &Path) override;
 
-  /// The set of files that should not be minimized.
-  llvm::StringSet<> IgnoredFiles;
+  void clearIgnoredFiles() { IgnoredFiles.clear(); }
+  void ignoreFile(StringRef Filename);
 
 private:
+  bool shouldIgnoreFile(StringRef Filename);
+
   void setCachedEntry(StringRef Filename, const CachedFileSystemEntry *Entry) {
 bool IsInserted = Cache.try_emplace(Filename, Entry).second;
 (void)IsInserted;
@@ -179,6 +181,8 @@ class DependencyScanningWorkerFilesystem : public 
llvm::vfs::ProxyFileSystem {
   /// excluded conditional directive skip mappings that are used by the
   /// currently active preprocessor.
   ExcludedPreprocessorDirectiveSkipMapping *PPSkipMappings;
+  /// The set of files that should not be minimized.
+  llvm::StringSet<> IgnoredFiles;
 };
 
 } // end namespace dependencies

diff  --git 
a/clang/lib/Tooling/DependencyScanning/DependencyScanningFilesystem.cpp 
b/clang/lib/Tooling/DependencyScanning/DependencyScanningFilesystem.cpp
index 1c10b7d727a58..88b835e159f3c 100644
--- a/clang/lib/Tooling/DependencyScanning/DependencyScanningFilesystem.cpp
+++ b/clang/lib/Tooling/DependencyScanning/DependencyScanningFilesystem.cpp
@@ -149,6 +149,19 @@ static bool shouldCacheStatFailures(StringRef Filename) {
   return shouldMinimize(Filename); // Only cache stat failures on source files.
 }
 
+void DependencyScanningWorkerFilesystem::ignoreFile(StringRef RawFilename) {
+  llvm::SmallString<256> Filename;
+  llvm::sys::path::native(RawFilename, Filename);
+  IgnoredFiles.insert(Filename);
+}
+
+bool DependencyScanningWorkerFilesystem::shouldIgnoreFile(
+StringRef RawFilename) {
+  llvm::SmallString<256> Filename;
+  llvm::sys::path::native(RawFilename, Filename);
+  return IgnoredFiles.contains(Filename);
+}
+
 llvm::ErrorOr
 DependencyScanningWorkerFilesystem::getOrCreateFileSystemEntry(
 const StringRef Filename) {
@@ -159,7 +172,7 @@ 
DependencyScanningWorkerFilesystem::getOrCreateFileSystemEntry(
   // FIXME: Handle PCM/PCH files.
   // FIXME: Handle module map files.
 
-  bool KeepOriginalSource = IgnoredFiles.count(Filename) ||
+  bool KeepOriginalSource = shouldIgnoreFile(Filename) ||
 !shouldMinimize(Filename);
   DependencyScanningFilesystemSharedCache::SharedFileSystemEntry
   &SharedCacheEntry = SharedCache.get(Filename);

diff  --git a/clang/lib/Tooling/DependencyScanning/DependencyScanningWorker.cpp 
b/clang/lib/Tooling/DependencyScanning/DependencyScanningWorker.cpp
index cd3463aa13e60..54581043c4f73 100644
--- a/clang/lib/Tooling/DependencyScanning/DependencyScanningWorker.cpp
+++ b/clang/lib/Tooling/DependencyScanning/DependencyScanningWorker.cpp
@@ -128,11 +128,11 @@ class DependencyScanningAction : public 
tooling::ToolAction {
   // Add any filenames that were explicity passed in the build settings and
   // that might be opened, as we want to ensure we don't run source
   // minimization on them.
-  DepFS->IgnoredFiles.clear();
+  DepFS->clearIgnoredFiles();
   for (const auto &Entry : CI.getHeaderSearchOpts().UserEntries)
-DepFS->IgnoredFiles.insert(Entry.Path);
+DepFS->ignoreFile(Entry.Path);
   for (const auto &Entry : CI.getHeaderSearchOpts().VFSOverlayFiles)
-DepFS->IgnoredFiles.insert(Entry);
+DepFS->ignoreFile(Entry);
 
   // Support for virtual file system overlays on top of the caching
   // filesystem.



_

[PATCH] D106064: [clang][deps] Normalize ignored filenames in minimizing file system

2021-07-20 Thread Jan Svoboda via Phabricator via cfe-commits
This revision was landed with ongoing or failed builds.
This revision was automatically updated to reflect the committed changes.
Closed by commit rG63fd109d3aa6: [clang][deps] Normalize ignored filenames in 
minimizing file system (authored by jansvoboda11).

Changed prior to commit:
  https://reviews.llvm.org/D106064?vs=358947&id=360060#toc

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D106064

Files:
  clang/include/clang/Tooling/DependencyScanning/DependencyScanningFilesystem.h
  clang/lib/Tooling/DependencyScanning/DependencyScanningFilesystem.cpp
  clang/lib/Tooling/DependencyScanning/DependencyScanningWorker.cpp


Index: clang/lib/Tooling/DependencyScanning/DependencyScanningWorker.cpp
===
--- clang/lib/Tooling/DependencyScanning/DependencyScanningWorker.cpp
+++ clang/lib/Tooling/DependencyScanning/DependencyScanningWorker.cpp
@@ -128,11 +128,11 @@
   // Add any filenames that were explicity passed in the build settings and
   // that might be opened, as we want to ensure we don't run source
   // minimization on them.
-  DepFS->IgnoredFiles.clear();
+  DepFS->clearIgnoredFiles();
   for (const auto &Entry : CI.getHeaderSearchOpts().UserEntries)
-DepFS->IgnoredFiles.insert(Entry.Path);
+DepFS->ignoreFile(Entry.Path);
   for (const auto &Entry : CI.getHeaderSearchOpts().VFSOverlayFiles)
-DepFS->IgnoredFiles.insert(Entry);
+DepFS->ignoreFile(Entry);
 
   // Support for virtual file system overlays on top of the caching
   // filesystem.
Index: clang/lib/Tooling/DependencyScanning/DependencyScanningFilesystem.cpp
===
--- clang/lib/Tooling/DependencyScanning/DependencyScanningFilesystem.cpp
+++ clang/lib/Tooling/DependencyScanning/DependencyScanningFilesystem.cpp
@@ -149,6 +149,19 @@
   return shouldMinimize(Filename); // Only cache stat failures on source files.
 }
 
+void DependencyScanningWorkerFilesystem::ignoreFile(StringRef RawFilename) {
+  llvm::SmallString<256> Filename;
+  llvm::sys::path::native(RawFilename, Filename);
+  IgnoredFiles.insert(Filename);
+}
+
+bool DependencyScanningWorkerFilesystem::shouldIgnoreFile(
+StringRef RawFilename) {
+  llvm::SmallString<256> Filename;
+  llvm::sys::path::native(RawFilename, Filename);
+  return IgnoredFiles.contains(Filename);
+}
+
 llvm::ErrorOr
 DependencyScanningWorkerFilesystem::getOrCreateFileSystemEntry(
 const StringRef Filename) {
@@ -159,7 +172,7 @@
   // FIXME: Handle PCM/PCH files.
   // FIXME: Handle module map files.
 
-  bool KeepOriginalSource = IgnoredFiles.count(Filename) ||
+  bool KeepOriginalSource = shouldIgnoreFile(Filename) ||
 !shouldMinimize(Filename);
   DependencyScanningFilesystemSharedCache::SharedFileSystemEntry
   &SharedCacheEntry = SharedCache.get(Filename);
Index: 
clang/include/clang/Tooling/DependencyScanning/DependencyScanningFilesystem.h
===
--- 
clang/include/clang/Tooling/DependencyScanning/DependencyScanningFilesystem.h
+++ 
clang/include/clang/Tooling/DependencyScanning/DependencyScanningFilesystem.h
@@ -153,10 +153,12 @@
   llvm::ErrorOr>
   openFileForRead(const Twine &Path) override;
 
-  /// The set of files that should not be minimized.
-  llvm::StringSet<> IgnoredFiles;
+  void clearIgnoredFiles() { IgnoredFiles.clear(); }
+  void ignoreFile(StringRef Filename);
 
 private:
+  bool shouldIgnoreFile(StringRef Filename);
+
   void setCachedEntry(StringRef Filename, const CachedFileSystemEntry *Entry) {
 bool IsInserted = Cache.try_emplace(Filename, Entry).second;
 (void)IsInserted;
@@ -179,6 +181,8 @@
   /// excluded conditional directive skip mappings that are used by the
   /// currently active preprocessor.
   ExcludedPreprocessorDirectiveSkipMapping *PPSkipMappings;
+  /// The set of files that should not be minimized.
+  llvm::StringSet<> IgnoredFiles;
 };
 
 } // end namespace dependencies


Index: clang/lib/Tooling/DependencyScanning/DependencyScanningWorker.cpp
===
--- clang/lib/Tooling/DependencyScanning/DependencyScanningWorker.cpp
+++ clang/lib/Tooling/DependencyScanning/DependencyScanningWorker.cpp
@@ -128,11 +128,11 @@
   // Add any filenames that were explicity passed in the build settings and
   // that might be opened, as we want to ensure we don't run source
   // minimization on them.
-  DepFS->IgnoredFiles.clear();
+  DepFS->clearIgnoredFiles();
   for (const auto &Entry : CI.getHeaderSearchOpts().UserEntries)
-DepFS->IgnoredFiles.insert(Entry.Path);
+DepFS->ignoreFile(Entry.Path);
   for (const auto &Entry : CI.getHeaderSearchOpts().VFSOverlayFiles)
-DepFS->IgnoredFiles.insert(Entry);

[clang] 5f08219 - Revert "[hwasan] Use stack safety analysis."

2021-07-20 Thread Florian Mayer via cfe-commits

Author: Florian Mayer
Date: 2021-07-20T10:36:46+01:00
New Revision: 5f08219322456b867605e4a19003f58ee418758f

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

LOG: Revert "[hwasan] Use stack safety analysis."

This reverts commit e9c63ed10b3bdf6eb3fa76d1a3eb403d6fc6a118.

Added: 


Modified: 
clang/lib/CodeGen/BackendUtil.cpp
llvm/include/llvm/Transforms/Instrumentation/HWAddressSanitizer.h
llvm/lib/Transforms/Instrumentation/HWAddressSanitizer.cpp

Removed: 
clang/test/CodeGen/hwasan-stack-safety-analysis.c
llvm/test/Instrumentation/HWAddressSanitizer/stack-safety-analysis.ll



diff  --git a/clang/lib/CodeGen/BackendUtil.cpp 
b/clang/lib/CodeGen/BackendUtil.cpp
index 481f5347d978b..9aa67ed2a67ba 100644
--- a/clang/lib/CodeGen/BackendUtil.cpp
+++ b/clang/lib/CodeGen/BackendUtil.cpp
@@ -314,19 +314,14 @@ static void addHWAddressSanitizerPasses(const 
PassManagerBuilder &Builder,
   static_cast(Builder);
   const CodeGenOptions &CGOpts = BuilderWrapper.getCGOpts();
   bool Recover = CGOpts.SanitizeRecover.has(SanitizerKind::HWAddress);
-  PM.add(createHWAddressSanitizerLegacyPassPass(
-  /*CompileKernel*/ false, Recover,
-  /*DisableOptimization*/ CGOpts.OptimizationLevel == 0));
+  PM.add(
+  createHWAddressSanitizerLegacyPassPass(/*CompileKernel*/ false, 
Recover));
 }
 
 static void addKernelHWAddressSanitizerPasses(const PassManagerBuilder 
&Builder,
-  legacy::PassManagerBase &PM) {
-  const PassManagerBuilderWrapper &BuilderWrapper =
-  static_cast(Builder);
-  const CodeGenOptions &CGOpts = BuilderWrapper.getCGOpts();
+legacy::PassManagerBase &PM) {
   PM.add(createHWAddressSanitizerLegacyPassPass(
-  /*CompileKernel*/ true, /*Recover*/ true,
-  /*DisableOptimization*/ CGOpts.OptimizationLevel == 0));
+  /*CompileKernel*/ true, /*Recover*/ true));
 }
 
 static void addGeneralOptsForMemorySanitizer(const PassManagerBuilder &Builder,
@@ -1169,9 +1164,7 @@ static void addSanitizers(const Triple &TargetTriple,
 auto HWASanPass = [&](SanitizerMask Mask, bool CompileKernel) {
   if (LangOpts.Sanitize.has(Mask)) {
 bool Recover = CodeGenOpts.SanitizeRecover.has(Mask);
-MPM.addPass(HWAddressSanitizerPass(
-CompileKernel, Recover,
-/*DisableOptimization=*/CodeGenOpts.OptimizationLevel == 0));
+MPM.addPass(HWAddressSanitizerPass(CompileKernel, Recover));
   }
 };
 HWASanPass(SanitizerKind::HWAddress, false);

diff  --git a/clang/test/CodeGen/hwasan-stack-safety-analysis.c 
b/clang/test/CodeGen/hwasan-stack-safety-analysis.c
deleted file mode 100644
index 5c4f34027bacd..0
--- a/clang/test/CodeGen/hwasan-stack-safety-analysis.c
+++ /dev/null
@@ -1,15 +0,0 @@
-// RUN: %clang -fsanitize=hwaddress -target aarch64-linux-gnu -S -emit-llvm 
-mllvm -hwasan-use-stack-safety=true -mllvm -hwasan-generate-tags-with-calls 
-O2 %s -o - | FileCheck %s --check-prefix=SAFETY
-// RUN: %clang -fsanitize=hwaddress -target aarch64-linux-gnu -S -emit-llvm 
-mllvm -hwasan-use-stack-safety=false -mllvm -hwasan-generate-tags-with-calls 
-O2 %s -o - | FileCheck %s --check-prefix=NOSAFETY
-
-// Default when optimizing, but not with O0.
-// RUN: %clang -fsanitize=hwaddress -target aarch64-linux-gnu -S -emit-llvm 
-mllvm -hwasan-generate-tags-with-calls -O2 %s -o - | FileCheck %s 
--check-prefix=SAFETY
-// RUN: %clang -fsanitize=hwaddress -target aarch64-linux-gnu -S -emit-llvm 
-mllvm -hwasan-generate-tags-with-calls -O0 %s -o - | FileCheck %s 
--check-prefix=NOSAFETY
-
-int main(int argc, char **argv) {
-  char buf[10];
-  volatile char *x = buf;
-  *x = 0;
-  return buf[0];
-  // NOSAFETY: __hwasan_generate_tag
-  // SAFETY-NOT: __hwasan_generate_tag
-}

diff  --git a/llvm/include/llvm/Transforms/Instrumentation/HWAddressSanitizer.h 
b/llvm/include/llvm/Transforms/Instrumentation/HWAddressSanitizer.h
index 2e4f3338030a4..76e02f06435c3 100644
--- a/llvm/include/llvm/Transforms/Instrumentation/HWAddressSanitizer.h
+++ b/llvm/include/llvm/Transforms/Instrumentation/HWAddressSanitizer.h
@@ -25,21 +25,17 @@ namespace llvm {
 class HWAddressSanitizerPass : public PassInfoMixin {
 public:
   explicit HWAddressSanitizerPass(bool CompileKernel = false,
-  bool Recover = false,
-  bool DisableOptimization = false);
+  bool Recover = false);
   PreservedAnalyses run(Module &M, ModuleAnalysisManager &MAM);
   static bool isRequired() { return true; }
 
 private:
   bool CompileKernel;
   bool Recover;
-  bool DisableOptimization;
 };
 
-FunctionPass *
-createHWAddressSanitizerLegacyPassPass(bool CompileKernel = false,

[PATCH] D105819: [analyzer] MallocChecker: Add a visitor to leave a note on functions that could have, but did not change ownership on leaked memory

2021-07-20 Thread Kristóf Umann via Phabricator via cfe-commits
Szelethus added a comment.

An ever so gentle ping :^)


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

https://reviews.llvm.org/D105819

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


[PATCH] D105703: [hwasan] Use stack safety analysis.

2021-07-20 Thread Florian Mayer via Phabricator via cfe-commits
fmayer reopened this revision.
fmayer added a comment.
This revision is now accepted and ready to land.

Made some buildbot unhappy again. Sorry :(


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D105703

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


[PATCH] D106333: [AArch64][SVE] Handle svbool_t VLST <-> VLAT/GNUT conversion

2021-07-20 Thread JunMa via Phabricator via cfe-commits
junparser added a comment.

In D106333#2889168 , @junparser wrote:

> @efriedma with this patch,  all of conversion between VLST and VLAT should 
> have same vector size(getElementType() * getElementCount()). The regression 
> in D105097  will be fixed by using bitcast 
> + vector.insert/extract directly

OK, actually this is wrong due to vscale representation in llvm ir.  However, 
we can still use bitcast as long as we can handle <32*i1> <64*i1>... in 
backend? any suggestion about this? @efriedma


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D106333

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


[PATCH] D106296: [analyzer] Fix for faulty namespace test in SmartPtrModelling

2021-07-20 Thread Deep Majumder via Phabricator via cfe-commits
RedDocMD updated this revision to Diff 360061.
RedDocMD added a comment.

More refactor


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D106296

Files:
  clang/lib/StaticAnalyzer/Checkers/SmartPtrModeling.cpp
  clang/test/Analysis/smart-ptr.cpp


Index: clang/test/Analysis/smart-ptr.cpp
===
--- clang/test/Analysis/smart-ptr.cpp
+++ clang/test/Analysis/smart-ptr.cpp
@@ -536,3 +536,10 @@
 }
 
 #endif
+
+// The following test isn't really a "smart-ptr" test
+// It came up during a bug fix (D106296)
+void testCheckForFunctionsWithNoDecl(void (*bar)(bool, bool)) {
+  // This should NOT crash.
+  bar(true, false);
+}
Index: clang/lib/StaticAnalyzer/Checkers/SmartPtrModeling.cpp
===
--- clang/lib/StaticAnalyzer/Checkers/SmartPtrModeling.cpp
+++ clang/lib/StaticAnalyzer/Checkers/SmartPtrModeling.cpp
@@ -248,9 +248,12 @@
   return hasStdClassWithName(RD, BASIC_OSTREAM_NAMES);
 }
 
+static bool isStdFunctionCall(const CallEvent &Call) {
+  return Call.getDecl() && Call.getDecl() ->getDeclContext()->isStdNamespace();
+}
+
 bool isStdOstreamOperatorCall(const CallEvent &Call) {
-  if (Call.getNumArgs() != 2 ||
-  !Call.getDecl()->getDeclContext()->isStdNamespace())
+  if (Call.getNumArgs() != 2 || !isStdFunctionCall(Call))
 return false;
   const auto *FC = dyn_cast(&Call);
   if (!FC)
@@ -265,6 +268,13 @@
  isStdBasicOstream(Call.getArgExpr(0));
 }
 
+static bool isPotentiallyComparisionOpCall(const CallEvent &Call) {
+  if (Call.getNumArgs() != 2 || !isStdFunctionCall(Call))
+return false;
+  return smartptr::isStdSmartPtr(Call.getArgExpr(0)) ||
+ smartptr::isStdSmartPtr(Call.getArgExpr(1));
+}
+
 bool SmartPtrModeling::evalCall(const CallEvent &Call,
 CheckerContext &C) const {
 
@@ -272,14 +282,11 @@
 
   // If any one of the arg is a unique_ptr, then
   // we can try this function
-  if (Call.getNumArgs() == 2 &&
-  Call.getDecl()->getDeclContext()->isStdNamespace())
-if (smartptr::isStdSmartPtr(Call.getArgExpr(0)) ||
-smartptr::isStdSmartPtr(Call.getArgExpr(1)))
-  if (handleComparisionOp(Call, C))
-return true;
-
-  if (isStdOstreamOperatorCall(Call))
+  if (ModelSmartPtrDereference && isPotentiallyComparisionOpCall(Call))
+if (handleComparisionOp(Call, C))
+  return true;
+
+  if (ModelSmartPtrDereference && isStdOstreamOperatorCall(Call))
 return handleOstreamOperator(Call, C);
 
   if (Call.isCalled(StdSwapCall)) {


Index: clang/test/Analysis/smart-ptr.cpp
===
--- clang/test/Analysis/smart-ptr.cpp
+++ clang/test/Analysis/smart-ptr.cpp
@@ -536,3 +536,10 @@
 }
 
 #endif
+
+// The following test isn't really a "smart-ptr" test
+// It came up during a bug fix (D106296)
+void testCheckForFunctionsWithNoDecl(void (*bar)(bool, bool)) {
+  // This should NOT crash.
+  bar(true, false);
+}
Index: clang/lib/StaticAnalyzer/Checkers/SmartPtrModeling.cpp
===
--- clang/lib/StaticAnalyzer/Checkers/SmartPtrModeling.cpp
+++ clang/lib/StaticAnalyzer/Checkers/SmartPtrModeling.cpp
@@ -248,9 +248,12 @@
   return hasStdClassWithName(RD, BASIC_OSTREAM_NAMES);
 }
 
+static bool isStdFunctionCall(const CallEvent &Call) {
+  return Call.getDecl() && Call.getDecl() ->getDeclContext()->isStdNamespace();
+}
+
 bool isStdOstreamOperatorCall(const CallEvent &Call) {
-  if (Call.getNumArgs() != 2 ||
-  !Call.getDecl()->getDeclContext()->isStdNamespace())
+  if (Call.getNumArgs() != 2 || !isStdFunctionCall(Call))
 return false;
   const auto *FC = dyn_cast(&Call);
   if (!FC)
@@ -265,6 +268,13 @@
  isStdBasicOstream(Call.getArgExpr(0));
 }
 
+static bool isPotentiallyComparisionOpCall(const CallEvent &Call) {
+  if (Call.getNumArgs() != 2 || !isStdFunctionCall(Call))
+return false;
+  return smartptr::isStdSmartPtr(Call.getArgExpr(0)) ||
+ smartptr::isStdSmartPtr(Call.getArgExpr(1));
+}
+
 bool SmartPtrModeling::evalCall(const CallEvent &Call,
 CheckerContext &C) const {
 
@@ -272,14 +282,11 @@
 
   // If any one of the arg is a unique_ptr, then
   // we can try this function
-  if (Call.getNumArgs() == 2 &&
-  Call.getDecl()->getDeclContext()->isStdNamespace())
-if (smartptr::isStdSmartPtr(Call.getArgExpr(0)) ||
-smartptr::isStdSmartPtr(Call.getArgExpr(1)))
-  if (handleComparisionOp(Call, C))
-return true;
-
-  if (isStdOstreamOperatorCall(Call))
+  if (ModelSmartPtrDereference && isPotentiallyComparisionOpCall(Call))
+if (handleComparisionOp(Call, C))
+  return true;
+
+  if (ModelSmartPtrDereference && isStdOstreamOperatorCall(Call))
 return handleOstreamOperator(Call, C);
 
   if (Call.isCalled(StdSwapCa

[PATCH] D106296: [analyzer] Fix for faulty namespace test in SmartPtrModelling

2021-07-20 Thread Deep Majumder via Phabricator via cfe-commits
RedDocMD added inline comments.



Comment at: clang/lib/StaticAnalyzer/Checkers/SmartPtrModeling.cpp:252-255
+  const auto *Decl = Call.getDecl();
+  if (!Decl)
+return false;
+  return Decl->getDeclContext()->isStdNamespace();

vsavchenko wrote:
> Can we use a one-liner that I suggested?
Sure


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D106296

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


[PATCH] D106296: [analyzer] Fix for faulty namespace test in SmartPtrModelling

2021-07-20 Thread Valeriy Savchenko via Phabricator via cfe-commits
vsavchenko added inline comments.



Comment at: clang/lib/StaticAnalyzer/Checkers/SmartPtrModeling.cpp:252
+static bool isStdFunctionCall(const CallEvent &Call) {
+  return Call.getDecl() && Call.getDecl() ->getDeclContext()->isStdNamespace();
+}

nit: there's an extra space here.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D106296

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


[PATCH] D106262: [clang][analyzer] Use generic note tag in alpha.unix.Stream .

2021-07-20 Thread Kristóf Umann via Phabricator via cfe-commits
Szelethus added inline comments.



Comment at: clang/lib/StaticAnalyzer/Checkers/StreamChecker.cpp:380-391
+if (BT == &BT_UseAfterClose)
+  Message = "Stream closed here";
+else if (BT == &BT_UseAfterOpenFailed)
+  Message = "Assuming opening the stream fails here";
+else if (BT == &BT_IndeterminatePosition)
+  Message = "Assuming this stream operation fails";
+else if (BT == &BT_StreamEof)

I have ambivalent feelings on this. I see what you are shooting for: display a 
specific `NoteTag` only for a specific `BugType`, though I wonder whether 
whether some of these notes would be nice for more than one. The only test case 
that changed seems to support my theory, or at least I like it better.



Comment at: clang/test/Analysis/stream-note.c:36-41
-  FILE *F = fopen("file", "r"); // expected-note {{Stream opened here}}
+  FILE *F = fopen("file", "r");
   if (!F)
 // expected-note@-1 {{'F' is non-null}}
 // expected-note@-2 {{Taking false branch}}
 return;
-  F = freopen(0, "w", F); // expected-note {{Stream reopened here}}

I think I preferred this, honestly.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D106262

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


[PATCH] D106296: [analyzer] Fix for faulty namespace test in SmartPtrModelling

2021-07-20 Thread Deep Majumder via Phabricator via cfe-commits
RedDocMD added inline comments.



Comment at: clang/lib/StaticAnalyzer/Checkers/SmartPtrModeling.cpp:252
+static bool isStdFunctionCall(const CallEvent &Call) {
+  return Call.getDecl() && Call.getDecl() ->getDeclContext()->isStdNamespace();
+}

vsavchenko wrote:
> nit: there's an extra space here.
Wow, I didn't know this is even valid syntax 😂


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D106296

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


[PATCH] D106296: [analyzer] Fix for faulty namespace test in SmartPtrModelling

2021-07-20 Thread Deep Majumder via Phabricator via cfe-commits
RedDocMD updated this revision to Diff 360064.
RedDocMD added a comment.

Removed unnecessary white space


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D106296

Files:
  clang/lib/StaticAnalyzer/Checkers/SmartPtrModeling.cpp
  clang/test/Analysis/smart-ptr.cpp


Index: clang/test/Analysis/smart-ptr.cpp
===
--- clang/test/Analysis/smart-ptr.cpp
+++ clang/test/Analysis/smart-ptr.cpp
@@ -536,3 +536,10 @@
 }
 
 #endif
+
+// The following test isn't really a "smart-ptr" test
+// It came up during a bug fix (D106296)
+void testCheckForFunctionsWithNoDecl(void (*bar)(bool, bool)) {
+  // This should NOT crash.
+  bar(true, false);
+}
Index: clang/lib/StaticAnalyzer/Checkers/SmartPtrModeling.cpp
===
--- clang/lib/StaticAnalyzer/Checkers/SmartPtrModeling.cpp
+++ clang/lib/StaticAnalyzer/Checkers/SmartPtrModeling.cpp
@@ -248,9 +248,12 @@
   return hasStdClassWithName(RD, BASIC_OSTREAM_NAMES);
 }
 
+static bool isStdFunctionCall(const CallEvent &Call) {
+  return Call.getDecl() && Call.getDecl()->getDeclContext()->isStdNamespace();
+}
+
 bool isStdOstreamOperatorCall(const CallEvent &Call) {
-  if (Call.getNumArgs() != 2 ||
-  !Call.getDecl()->getDeclContext()->isStdNamespace())
+  if (Call.getNumArgs() != 2 || !isStdFunctionCall(Call))
 return false;
   const auto *FC = dyn_cast(&Call);
   if (!FC)
@@ -265,6 +268,13 @@
  isStdBasicOstream(Call.getArgExpr(0));
 }
 
+static bool isPotentiallyComparisionOpCall(const CallEvent &Call) {
+  if (Call.getNumArgs() != 2 || !isStdFunctionCall(Call))
+return false;
+  return smartptr::isStdSmartPtr(Call.getArgExpr(0)) ||
+ smartptr::isStdSmartPtr(Call.getArgExpr(1));
+}
+
 bool SmartPtrModeling::evalCall(const CallEvent &Call,
 CheckerContext &C) const {
 
@@ -272,14 +282,11 @@
 
   // If any one of the arg is a unique_ptr, then
   // we can try this function
-  if (Call.getNumArgs() == 2 &&
-  Call.getDecl()->getDeclContext()->isStdNamespace())
-if (smartptr::isStdSmartPtr(Call.getArgExpr(0)) ||
-smartptr::isStdSmartPtr(Call.getArgExpr(1)))
-  if (handleComparisionOp(Call, C))
-return true;
-
-  if (isStdOstreamOperatorCall(Call))
+  if (ModelSmartPtrDereference && isPotentiallyComparisionOpCall(Call))
+if (handleComparisionOp(Call, C))
+  return true;
+
+  if (ModelSmartPtrDereference && isStdOstreamOperatorCall(Call))
 return handleOstreamOperator(Call, C);
 
   if (Call.isCalled(StdSwapCall)) {


Index: clang/test/Analysis/smart-ptr.cpp
===
--- clang/test/Analysis/smart-ptr.cpp
+++ clang/test/Analysis/smart-ptr.cpp
@@ -536,3 +536,10 @@
 }
 
 #endif
+
+// The following test isn't really a "smart-ptr" test
+// It came up during a bug fix (D106296)
+void testCheckForFunctionsWithNoDecl(void (*bar)(bool, bool)) {
+  // This should NOT crash.
+  bar(true, false);
+}
Index: clang/lib/StaticAnalyzer/Checkers/SmartPtrModeling.cpp
===
--- clang/lib/StaticAnalyzer/Checkers/SmartPtrModeling.cpp
+++ clang/lib/StaticAnalyzer/Checkers/SmartPtrModeling.cpp
@@ -248,9 +248,12 @@
   return hasStdClassWithName(RD, BASIC_OSTREAM_NAMES);
 }
 
+static bool isStdFunctionCall(const CallEvent &Call) {
+  return Call.getDecl() && Call.getDecl()->getDeclContext()->isStdNamespace();
+}
+
 bool isStdOstreamOperatorCall(const CallEvent &Call) {
-  if (Call.getNumArgs() != 2 ||
-  !Call.getDecl()->getDeclContext()->isStdNamespace())
+  if (Call.getNumArgs() != 2 || !isStdFunctionCall(Call))
 return false;
   const auto *FC = dyn_cast(&Call);
   if (!FC)
@@ -265,6 +268,13 @@
  isStdBasicOstream(Call.getArgExpr(0));
 }
 
+static bool isPotentiallyComparisionOpCall(const CallEvent &Call) {
+  if (Call.getNumArgs() != 2 || !isStdFunctionCall(Call))
+return false;
+  return smartptr::isStdSmartPtr(Call.getArgExpr(0)) ||
+ smartptr::isStdSmartPtr(Call.getArgExpr(1));
+}
+
 bool SmartPtrModeling::evalCall(const CallEvent &Call,
 CheckerContext &C) const {
 
@@ -272,14 +282,11 @@
 
   // If any one of the arg is a unique_ptr, then
   // we can try this function
-  if (Call.getNumArgs() == 2 &&
-  Call.getDecl()->getDeclContext()->isStdNamespace())
-if (smartptr::isStdSmartPtr(Call.getArgExpr(0)) ||
-smartptr::isStdSmartPtr(Call.getArgExpr(1)))
-  if (handleComparisionOp(Call, C))
-return true;
-
-  if (isStdOstreamOperatorCall(Call))
+  if (ModelSmartPtrDereference && isPotentiallyComparisionOpCall(Call))
+if (handleComparisionOp(Call, C))
+  return true;
+
+  if (ModelSmartPtrDereference && isStdOstreamOperatorCall(Call))
 return handleOstreamOperator(Call, C);
 
   if (Call.is

[PATCH] D106005: [Docs] Define matrix initialisation in MatrixTypes documentation

2021-07-20 Thread Florian Hahn via Phabricator via cfe-commits
fhahn added inline comments.



Comment at: clang/docs/MatrixTypes.rst:271
+-
+An empty value of a matrix type M can be initialised using this syntax:
+

is there a reason we need to allow 'empty' initialisation? What does it mean? 


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D106005

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


[PATCH] D106333: [AArch64][SVE] Handle svbool_t VLST <-> VLAT/GNUT conversion

2021-07-20 Thread Paul Walker via Phabricator via cfe-commits
paulwalker-arm added a comment.

In D106333#2889168 , @junparser wrote:

> @efriedma with this patch,  all of conversion between VLST and VLAT should 
> have same vector size(getElementType() * getElementCount()). The regression 
> in D105097  will be fixed by using bitcast 
> + vector.insert/extract directly

I hope I've not got the wrong end of the stick here but the above is our 
intention.  As in, Arm is looking at replacing the "via memory predicate 
casting" with a method that uses vector_of_i8s vector insert/extract with the 
necessary bitcasting.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D106333

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


[PATCH] D106111: opencl-c.h: add initial CL 3.0 conditionals for atomic operations.

2021-07-20 Thread Anton Zabaznov via Phabricator via cfe-commits
azabaznov added a comment.

You also need to guard //memory_order_seq_cst// enum entry. Note that 
//memory_order_acq_rel// is always defined as it can be used in 
//atomic_work_item_fence()// built-in function, AFAIR in all other cases if 
//memory_order_acq_rel// is used without //__opencl_c_atomic_order_acq_rel// 
feature it is undefined behavior.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D106111

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


[PATCH] D106296: [analyzer] Fix for faulty namespace test in SmartPtrModelling

2021-07-20 Thread Valeriy Savchenko via Phabricator via cfe-commits
vsavchenko accepted this revision.
vsavchenko added a comment.

Great, LGTM!
But let's wait for @xazax.hun anyways


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D106296

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


[clang] bc1a297 - [clang][deps] Separate filesystem caches for minimized and original files

2021-07-20 Thread Jan Svoboda via cfe-commits

Author: Jan Svoboda
Date: 2021-07-20T12:08:46+02:00
New Revision: bc1a2979fc70d954ae97122205c71c8404a1b17e

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

LOG: [clang][deps] Separate filesystem caches for minimized and original files

This patch separates the local and global caches of 
`DependencyScanningFilesystem` into two buckets: minimized files and original 
files. This is necessary to deal with precompiled modules/headers.

Consider a single worker with its instance of filesystem:
1. Build system uses the worker to scan dependencies of module A => filesystem 
cache gets populated with minimized input files.
2. Build system uses the results to explicitly build module A => explicitly 
built module captures the state of the real filesystem (containing 
non-minimized input files).
3. Build system uses the prebuilt module A as an explicit precompiled 
dependency for another compile job B.
4. Build system uses the same worker to scan dependencies for job B => worker 
uses implicit modular build to discover dependencies, which validates the 
filesystem state embedded in the prebuilt module (non-minimized files) to the 
current view of the filesystem (minimized files), resulting in validation 
failures.

This problem can be avoided in step 4 by collecting input files from the 
precompiled module and marking them as "ignored" in the minimizing filesystem. 
This way, the validation should succeed, since we should be always dealing with 
the original (non-minized) input files. However, the filesystem already 
minimized the input files in step 1 and put it in the cache, which gets used in 
step 4 as well even though it's marked ignored (do not minimize). This patch 
essentially fixes this oversight by making the `"file is minimized"` part of 
the cache key (from high level).

Depends on D106064.

Reviewed By: dexonsmith

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

Added: 


Modified: 

clang/include/clang/Tooling/DependencyScanning/DependencyScanningFilesystem.h
clang/lib/Tooling/DependencyScanning/DependencyScanningFilesystem.cpp
clang/unittests/Tooling/CMakeLists.txt
clang/unittests/Tooling/DependencyScannerTest.cpp

Removed: 




diff  --git 
a/clang/include/clang/Tooling/DependencyScanning/DependencyScanningFilesystem.h 
b/clang/include/clang/Tooling/DependencyScanning/DependencyScanningFilesystem.h
index b213f388dadc0..c52da3305f7c1 100644
--- 
a/clang/include/clang/Tooling/DependencyScanning/DependencyScanningFilesystem.h
+++ 
b/clang/include/clang/Tooling/DependencyScanning/DependencyScanningFilesystem.h
@@ -103,7 +103,8 @@ class CachedFileSystemEntry {
 };
 
 /// This class is a shared cache, that caches the 'stat' and 'open' calls to 
the
-/// underlying real file system.
+/// underlying real file system. It distinguishes between minimized and 
original
+/// files.
 ///
 /// It is sharded based on the hash of the key to reduce the lock contention 
for
 /// the worker threads.
@@ -114,21 +115,62 @@ class DependencyScanningFilesystemSharedCache {
 CachedFileSystemEntry Value;
   };
 
-  DependencyScanningFilesystemSharedCache();
-
   /// Returns a cache entry for the corresponding key.
   ///
   /// A new cache entry is created if the key is not in the cache. This is a
   /// thread safe call.
-  SharedFileSystemEntry &get(StringRef Key);
+  SharedFileSystemEntry &get(StringRef Key, bool Minimized);
 
 private:
-  struct CacheShard {
-std::mutex CacheLock;
-llvm::StringMap Cache;
+  class SingleCache {
+  public:
+SingleCache();
+
+SharedFileSystemEntry &get(StringRef Key);
+
+  private:
+struct CacheShard {
+  std::mutex CacheLock;
+  llvm::StringMap Cache;
+};
+std::unique_ptr CacheShards;
+unsigned NumShards;
   };
-  std::unique_ptr CacheShards;
-  unsigned NumShards;
+
+  SingleCache CacheMinimized;
+  SingleCache CacheOriginal;
+};
+
+/// This class is a local cache, that caches the 'stat' and 'open' calls to the
+/// underlying real file system. It distinguishes between minimized and 
original
+/// files.
+class DependencyScanningFilesystemLocalCache {
+private:
+  using SingleCache =
+  llvm::StringMap;
+
+  SingleCache CacheMinimized;
+  SingleCache CacheOriginal;
+
+  SingleCache &selectCache(bool Minimized) {
+return Minimized ? CacheMinimized : CacheOriginal;
+  }
+
+public:
+  void setCachedEntry(StringRef Filename, bool Minimized,
+  const CachedFileSystemEntry *Entry) {
+SingleCache &Cache = selectCache(Minimized);
+bool IsInserted = Cache.try_emplace(Filename, Entry).second;
+(void)IsInserted;
+assert(IsInserted && "local cache is updated more than once");
+  }
+
+  const CachedFileSystemEntry *getCachedEntry(StringRef Filename,
+ 

[PATCH] D106146: [clang][deps] Separate filesystem caches for minimized and original files

2021-07-20 Thread Jan Svoboda via Phabricator via cfe-commits
This revision was landed with ongoing or failed builds.
This revision was automatically updated to reflect the committed changes.
Closed by commit rGbc1a2979fc70: [clang][deps] Separate filesystem caches for 
minimized and original files (authored by jansvoboda11).

Changed prior to commit:
  https://reviews.llvm.org/D106146?vs=359294&id=360065#toc

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D106146

Files:
  clang/include/clang/Tooling/DependencyScanning/DependencyScanningFilesystem.h
  clang/lib/Tooling/DependencyScanning/DependencyScanningFilesystem.cpp
  clang/unittests/Tooling/CMakeLists.txt
  clang/unittests/Tooling/DependencyScannerTest.cpp

Index: clang/unittests/Tooling/DependencyScannerTest.cpp
===
--- clang/unittests/Tooling/DependencyScannerTest.cpp
+++ clang/unittests/Tooling/DependencyScannerTest.cpp
@@ -15,6 +15,7 @@
 #include "clang/Frontend/FrontendActions.h"
 #include "clang/Tooling/CompilationDatabase.h"
 #include "clang/Tooling/Tooling.h"
+#include "clang/Tooling/DependencyScanning/DependencyScanningFilesystem.h"
 #include "llvm/ADT/STLExtras.h"
 #include "llvm/Support/FormatVariadic.h"
 #include "llvm/Support/Path.h"
@@ -203,5 +204,35 @@
   EXPECT_EQ(convert_to_slash(Deps[5]), "/root/symlink.h");
 }
 
+namespace dependencies {
+TEST(DependencyScanningFilesystem, IgnoredFilesHaveSeparateCache) {
+  auto VFS = llvm::makeIntrusiveRefCnt();
+  VFS->addFile("/mod.h", 0, llvm::MemoryBuffer::getMemBuffer("// hi there!\n"));
+
+  DependencyScanningFilesystemSharedCache SharedCache;
+  auto Mappings = std::make_unique();
+  DependencyScanningWorkerFilesystem DepFS(SharedCache, VFS, Mappings.get());
+
+  auto StatusMinimized0 = DepFS.status("/mod.h");
+  DepFS.ignoreFile("/mod.h");
+  auto StatusFull1 = DepFS.status("/mod.h");
+  DepFS.clearIgnoredFiles();
+
+  auto StatusMinimized2 = DepFS.status("/mod.h");
+  DepFS.ignoreFile("/mod.h");
+  auto StatusFull3 = DepFS.status("/mod.h");
+
+  EXPECT_TRUE(StatusMinimized0);
+  EXPECT_EQ(StatusMinimized0->getSize(), 0u);
+  EXPECT_TRUE(StatusFull1);
+  EXPECT_EQ(StatusFull1->getSize(), 13u);
+
+  EXPECT_TRUE(StatusMinimized2);
+  EXPECT_EQ(StatusMinimized2->getSize(), 0u);
+  EXPECT_TRUE(StatusFull3);
+  EXPECT_EQ(StatusFull3->getSize(), 13u);
+}
+
+} // end namespace dependencies
 } // end namespace tooling
 } // end namespace clang
Index: clang/unittests/Tooling/CMakeLists.txt
===
--- clang/unittests/Tooling/CMakeLists.txt
+++ clang/unittests/Tooling/CMakeLists.txt
@@ -68,6 +68,7 @@
   clangAST
   clangASTMatchers
   clangBasic
+  clangDependencyScanning
   clangFormat
   clangFrontend
   clangLex
Index: clang/lib/Tooling/DependencyScanning/DependencyScanningFilesystem.cpp
===
--- clang/lib/Tooling/DependencyScanning/DependencyScanningFilesystem.cpp
+++ clang/lib/Tooling/DependencyScanning/DependencyScanningFilesystem.cpp
@@ -99,8 +99,7 @@
   return Result;
 }
 
-DependencyScanningFilesystemSharedCache::
-DependencyScanningFilesystemSharedCache() {
+DependencyScanningFilesystemSharedCache::SingleCache::SingleCache() {
   // This heuristic was chosen using a empirical testing on a
   // reasonably high core machine (iMacPro 18 cores / 36 threads). The cache
   // sharding gives a performance edge by reducing the lock contention.
@@ -111,18 +110,20 @@
   CacheShards = std::make_unique(NumShards);
 }
 
-/// Returns a cache entry for the corresponding key.
-///
-/// A new cache entry is created if the key is not in the cache. This is a
-/// thread safe call.
 DependencyScanningFilesystemSharedCache::SharedFileSystemEntry &
-DependencyScanningFilesystemSharedCache::get(StringRef Key) {
+DependencyScanningFilesystemSharedCache::SingleCache::get(StringRef Key) {
   CacheShard &Shard = CacheShards[llvm::hash_value(Key) % NumShards];
   std::unique_lock LockGuard(Shard.CacheLock);
   auto It = Shard.Cache.try_emplace(Key);
   return It.first->getValue();
 }
 
+DependencyScanningFilesystemSharedCache::SharedFileSystemEntry &
+DependencyScanningFilesystemSharedCache::get(StringRef Key, bool Minimized) {
+  SingleCache &Cache = Minimized ? CacheMinimized : CacheOriginal;
+  return Cache.get(Key);
+}
+
 /// Whitelist file extensions that should be minimized, treating no extension as
 /// a source file that should be minimized.
 ///
@@ -165,17 +166,17 @@
 llvm::ErrorOr
 DependencyScanningWorkerFilesystem::getOrCreateFileSystemEntry(
 const StringRef Filename) {
-  if (const CachedFileSystemEntry *Entry = getCachedEntry(Filename)) {
+  bool ShouldMinimize =
+  !IgnoredFiles.count(Filename) && shouldMinimize(Filename);
+
+  if (const auto *Entry = Cache.getCachedEntry(Filename, ShouldMinimize))
 return Entry;
-  }
 
   // FIXME: Handle PCM/PCH files.
   // FIXME: Handle modu

[PATCH] D106333: [AArch64][SVE] Handle svbool_t VLST <-> VLAT/GNUT conversion

2021-07-20 Thread JunMa via Phabricator via cfe-commits
junparser added a comment.

In D106333#2889859 , @paulwalker-arm 
wrote:

> In D106333#2889168 , @junparser 
> wrote:
>
>> @efriedma with this patch,  all of conversion between VLST and VLAT should 
>> have same vector size(getElementType() * getElementCount()). The regression 
>> in D105097  will be fixed by using bitcast 
>> + vector.insert/extract directly
>
> I hope I've not got the wrong end of the stick here but the above is our 
> intention.  As in, Arm is looking at replacing the "via memory predicate 
> casting" with a method that uses vector_of_i8s vector insert/extract with the 
> necessary bitcasting.  Before doing this we just had to fix up a bunch of 
> failing INSERT_SUBVECTOR cases when it comes to the illegal types this idiom 
> introduces.

Good to know this.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D106333

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


[clang] e564fd9 - [clang][deps] Avoid minimizing PCH input files

2021-07-20 Thread Jan Svoboda via cfe-commits

Author: Jan Svoboda
Date: 2021-07-20T12:20:10+02:00
New Revision: e564fd93ab85d1810e0d83e961ccc8b99025ff34

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

LOG: [clang][deps] Avoid minimizing PCH input files

This patch avoid minimizing input files that contributed to a PCH or its 
modules. This prevents the implicit modular build to fail on unexpected file 
size. Depends on D106146.

Reviewed By: dexonsmith

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

Added: 


Modified: 
clang/lib/Tooling/DependencyScanning/DependencyScanningWorker.cpp
clang/test/ClangScanDeps/modules-pch.c

Removed: 




diff  --git a/clang/lib/Tooling/DependencyScanning/DependencyScanningWorker.cpp 
b/clang/lib/Tooling/DependencyScanning/DependencyScanningWorker.cpp
index 54581043c4f73..d651ff23b387a 100644
--- a/clang/lib/Tooling/DependencyScanning/DependencyScanningWorker.cpp
+++ b/clang/lib/Tooling/DependencyScanning/DependencyScanningWorker.cpp
@@ -46,25 +46,73 @@ class DependencyConsumerForwarder : public 
DependencyFileGenerator {
   DependencyConsumer &C;
 };
 
-/// A listener that collects the names and paths to imported modules.
-class ImportCollectingListener : public ASTReaderListener {
-  using PrebuiltModuleFilesT =
-  decltype(HeaderSearchOptions::PrebuiltModuleFiles);
-
+/// A listener that collects the imported modules and optionally the input
+/// files.
+class PrebuiltModuleListener : public ASTReaderListener {
 public:
-  ImportCollectingListener(PrebuiltModuleFilesT &PrebuiltModuleFiles)
-  : PrebuiltModuleFiles(PrebuiltModuleFiles) {}
+  PrebuiltModuleListener(llvm::StringMap &PrebuiltModuleFiles,
+ llvm::StringSet<> &InputFiles, bool VisitInputFiles)
+  : PrebuiltModuleFiles(PrebuiltModuleFiles), InputFiles(InputFiles),
+VisitInputFiles(VisitInputFiles) {}
 
   bool needsImportVisitation() const override { return true; }
+  bool needsInputFileVisitation() override { return VisitInputFiles; }
+  bool needsSystemInputFileVisitation() override { return VisitInputFiles; }
 
   void visitImport(StringRef ModuleName, StringRef Filename) override {
-PrebuiltModuleFiles[std::string(ModuleName)] = std::string(Filename);
+PrebuiltModuleFiles.insert({ModuleName, Filename.str()});
+  }
+
+  bool visitInputFile(StringRef Filename, bool isSystem, bool isOverridden,
+  bool isExplicitModule) override {
+InputFiles.insert(Filename);
+return true;
   }
 
 private:
-  PrebuiltModuleFilesT &PrebuiltModuleFiles;
+  llvm::StringMap &PrebuiltModuleFiles;
+  llvm::StringSet<> &InputFiles;
+  bool VisitInputFiles;
 };
 
+using PrebuiltModuleFilesT = 
decltype(HeaderSearchOptions::PrebuiltModuleFiles);
+
+/// Visit the given prebuilt module and collect all of the modules it
+/// transitively imports and contributing input files.
+static void visitPrebuiltModule(StringRef PrebuiltModuleFilename,
+CompilerInstance &CI,
+PrebuiltModuleFilesT &ModuleFiles,
+llvm::StringSet<> &InputFiles,
+bool VisitInputFiles) {
+  // Maps the names of modules that weren't yet visited to their PCM path.
+  llvm::StringMap ModuleFilesWorklist;
+  // Contains PCM paths of all visited modules.
+  llvm::StringSet<> VisitedModuleFiles;
+
+  PrebuiltModuleListener Listener(ModuleFilesWorklist, InputFiles,
+  VisitInputFiles);
+
+  auto GatherModuleFileInfo = [&](StringRef ASTFile) {
+ASTReader::readASTFileControlBlock(
+ASTFile, CI.getFileManager(), CI.getPCHContainerReader(),
+/*FindModuleFileExtensions=*/false, Listener,
+/*ValidateDiagnosticOptions=*/false);
+  };
+
+  GatherModuleFileInfo(PrebuiltModuleFilename);
+  while (!ModuleFilesWorklist.empty()) {
+auto WorklistItemIt = ModuleFilesWorklist.begin();
+
+if (!VisitedModuleFiles.contains(WorklistItemIt->getValue())) {
+  VisitedModuleFiles.insert(WorklistItemIt->getValue());
+  GatherModuleFileInfo(WorklistItemIt->getValue());
+  ModuleFiles[WorklistItemIt->getKey().str()] = WorklistItemIt->getValue();
+}
+
+ModuleFilesWorklist.erase(WorklistItemIt);
+  }
+}
+
 /// Transform arbitrary file name into an object-like file name.
 static std::string makeObjFileName(StringRef FileName) {
   SmallString<128> ObjFileName(FileName);
@@ -122,13 +170,33 @@ class DependencyScanningAction : public 
tooling::ToolAction {
 
 Compiler.getPreprocessorOpts().AllowPCHWithDifferentModulesCachePath = 
true;
 
-// Use the dependency scanning optimized file system if we can.
+FileMgr->getFileSystemOpts().WorkingDir = std::string(WorkingDirectory);
+Compiler.setFileManager(FileMg

[PATCH] D104536: [clang][deps] Avoid minimizing PCH input files

2021-07-20 Thread Jan Svoboda via Phabricator via cfe-commits
This revision was landed with ongoing or failed builds.
This revision was automatically updated to reflect the committed changes.
Closed by commit rGe564fd93ab85: [clang][deps] Avoid minimizing PCH input files 
(authored by jansvoboda11).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D104536

Files:
  clang/lib/Tooling/DependencyScanning/DependencyScanningWorker.cpp
  clang/test/ClangScanDeps/modules-pch.c

Index: clang/test/ClangScanDeps/modules-pch.c
===
--- clang/test/ClangScanDeps/modules-pch.c
+++ clang/test/ClangScanDeps/modules-pch.c
@@ -6,7 +6,7 @@
 // RUN: sed "s|DIR|%/t|g" %S/Inputs/modules-pch/cdb_pch.json > %t/cdb.json
 // RUN: echo -%t > %t/result_pch.json
 // RUN: clang-scan-deps -compilation-database %t/cdb.json -format experimental-full \
-// RUN:   -generate-modules-path-args -module-files-dir %t/build -mode preprocess >> %t/result_pch.json
+// RUN:   -generate-modules-path-args -module-files-dir %t/build >> %t/result_pch.json
 // RUN: cat %t/result_pch.json | sed 's:\?:/:g' | FileCheck %s -check-prefix=CHECK-PCH
 //
 // Check we didn't build the PCH during dependency scanning.
@@ -127,9 +127,8 @@
 //
 // RUN: sed "s|DIR|%/t|g" %S/Inputs/modules-pch/cdb_tu.json > %t/cdb.json
 // RUN: echo -%t > %t/result_tu.json
-// FIXME: Make this work with '-mode preprocess-minimized-sources'.
 // RUN: clang-scan-deps -compilation-database %t/cdb.json -format experimental-full \
-// RUN:   -generate-modules-path-args -module-files-dir %t/build -mode preprocess >> %t/result_tu.json
+// RUN:   -generate-modules-path-args -module-files-dir %t/build >> %t/result_tu.json
 // RUN: cat %t/result_tu.json | sed 's:\?:/:g' | FileCheck %s -check-prefix=CHECK-TU
 //
 // CHECK-TU:  -[[PREFIX:.*]]
@@ -193,7 +192,7 @@
 // RUN: sed "s|DIR|%/t|g" %S/Inputs/modules-pch/cdb_tu_with_common.json > %t/cdb.json
 // RUN: echo -%t > %t/result_tu_with_common.json
 // RUN: clang-scan-deps -compilation-database %t/cdb.json -format experimental-full \
-// RUN:   -generate-modules-path-args -module-files-dir %t/build -mode preprocess >> %t/result_tu_with_common.json
+// RUN:   -generate-modules-path-args -module-files-dir %t/build >> %t/result_tu_with_common.json
 // RUN: cat %t/result_tu_with_common.json | sed 's:\?:/:g' | FileCheck %s -check-prefix=CHECK-TU-WITH-COMMON
 //
 // CHECK-TU-WITH-COMMON:  -[[PREFIX:.*]]
Index: clang/lib/Tooling/DependencyScanning/DependencyScanningWorker.cpp
===
--- clang/lib/Tooling/DependencyScanning/DependencyScanningWorker.cpp
+++ clang/lib/Tooling/DependencyScanning/DependencyScanningWorker.cpp
@@ -46,25 +46,73 @@
   DependencyConsumer &C;
 };
 
-/// A listener that collects the names and paths to imported modules.
-class ImportCollectingListener : public ASTReaderListener {
-  using PrebuiltModuleFilesT =
-  decltype(HeaderSearchOptions::PrebuiltModuleFiles);
-
+/// A listener that collects the imported modules and optionally the input
+/// files.
+class PrebuiltModuleListener : public ASTReaderListener {
 public:
-  ImportCollectingListener(PrebuiltModuleFilesT &PrebuiltModuleFiles)
-  : PrebuiltModuleFiles(PrebuiltModuleFiles) {}
+  PrebuiltModuleListener(llvm::StringMap &PrebuiltModuleFiles,
+ llvm::StringSet<> &InputFiles, bool VisitInputFiles)
+  : PrebuiltModuleFiles(PrebuiltModuleFiles), InputFiles(InputFiles),
+VisitInputFiles(VisitInputFiles) {}
 
   bool needsImportVisitation() const override { return true; }
+  bool needsInputFileVisitation() override { return VisitInputFiles; }
+  bool needsSystemInputFileVisitation() override { return VisitInputFiles; }
 
   void visitImport(StringRef ModuleName, StringRef Filename) override {
-PrebuiltModuleFiles[std::string(ModuleName)] = std::string(Filename);
+PrebuiltModuleFiles.insert({ModuleName, Filename.str()});
+  }
+
+  bool visitInputFile(StringRef Filename, bool isSystem, bool isOverridden,
+  bool isExplicitModule) override {
+InputFiles.insert(Filename);
+return true;
   }
 
 private:
-  PrebuiltModuleFilesT &PrebuiltModuleFiles;
+  llvm::StringMap &PrebuiltModuleFiles;
+  llvm::StringSet<> &InputFiles;
+  bool VisitInputFiles;
 };
 
+using PrebuiltModuleFilesT = decltype(HeaderSearchOptions::PrebuiltModuleFiles);
+
+/// Visit the given prebuilt module and collect all of the modules it
+/// transitively imports and contributing input files.
+static void visitPrebuiltModule(StringRef PrebuiltModuleFilename,
+CompilerInstance &CI,
+PrebuiltModuleFilesT &ModuleFiles,
+llvm::StringSet<> &InputFiles,
+bool VisitInputFiles) {
+  // Maps the names of modules that weren't yet visited to their PCM path.
+  llvm:

[PATCH] D106339: Add support to generate Sphinx DOCX documentation

2021-07-20 Thread Tony Tye via Phabricator via cfe-commits
t-tye created this revision.
t-tye added a reviewer: scott.linder.
Herald added subscribers: libcxx-commits, mgorny.
Herald added a reviewer: bollu.
Herald added a reviewer: MaskRay.
Herald added a reviewer: sscalpone.
Herald added a project: libunwind.
Herald added a reviewer: libunwind.
t-tye requested review of this revision.
Herald added a reviewer: jdoerfert.
Herald added subscribers: cfe-commits, llvm-commits, openmp-commits, 
lldb-commits, sstefan1.
Herald added projects: clang, LLDB, libc++, OpenMP, LLVM, clang-tools-extra.
Herald added a reviewer: libc++.

Add support for Sphinx docx builder. Requires Sphinx docx builder to be
installed using `pip install docxbuilder`.

Added `SPHINX_OUTPUT_DOCX` CMake variable to control generation of docx
documentation. Defaults to `OFF`.

Added `_INSTALL_SPHINX_DOCX_DIR` CMake variable to control where docx
files are installed. Defaults to `share/doc//.docx`.

Documented new CMake variables in `llvm/docs/CMake.rst`.

Updated description of building documentation is `lld/docs/sphinx_intro.rst`,
`lldb/docs/resources/build.rst`, `llvm/docs/README.txt`, and
`openmp/docs/README.txt`,

Update `clang/docs/CMakeLists.txt` for Sphinx man and docx builders to ensure
.td generated .rst files are available to prevent warnings of missing rst files.
Minor CMake cleanups.

Added `docx` as an additional target for the documentation make.bat scripts.

Added `docx` as an additional target rule in the Makefile.sphinx files.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D106339

Files:
  clang-tools-extra/docs/CMakeLists.txt
  clang-tools-extra/docs/conf.py
  clang-tools-extra/docs/make.bat
  clang/docs/CMakeLists.txt
  clang/docs/Makefile.sphinx
  clang/docs/analyzer/conf.py
  clang/docs/analyzer/make.bat
  clang/docs/conf.py
  clang/docs/make.bat
  flang/docs/CMakeLists.txt
  flang/docs/conf.py
  libcxx/docs/CMakeLists.txt
  libcxx/docs/Makefile.sphinx
  libcxx/docs/conf.py
  libunwind/docs/CMakeLists.txt
  libunwind/docs/conf.py
  lld/docs/CMakeLists.txt
  lld/docs/conf.py
  lld/docs/make.bat
  lld/docs/sphinx_intro.rst
  lldb/docs/CMakeLists.txt
  lldb/docs/conf.py
  lldb/docs/resources/build.rst
  llvm/cmake/modules/AddSphinxTarget.cmake
  llvm/cmake/modules/FindSphinx.cmake
  llvm/docs/CMake.rst
  llvm/docs/CMakeLists.txt
  llvm/docs/Makefile.sphinx
  llvm/docs/README.txt
  llvm/docs/conf.py
  llvm/docs/make.bat
  openmp/docs/CMakeLists.txt
  openmp/docs/README.txt
  openmp/docs/conf.py
  polly/docs/CMakeLists.txt
  polly/docs/conf.py

Index: polly/docs/conf.py
===
--- polly/docs/conf.py
+++ polly/docs/conf.py
@@ -28,6 +28,9 @@
 # coming with Sphinx (named 'sphinx.ext.*') or your custom ones.
 extensions = ['sphinx.ext.todo', 'sphinx.ext.mathjax']
 
+if tags.has('builder-docx'):
+extensions.append('docxbuilder')
+
 # Add any paths that contain templates here, relative to this directory.
 templates_path = ['_templates']
 
Index: polly/docs/CMakeLists.txt
===
--- polly/docs/CMakeLists.txt
+++ polly/docs/CMakeLists.txt
@@ -98,6 +98,9 @@
 if (${SPHINX_OUTPUT_MAN})
   add_sphinx_target(man polly)
 endif()
+if (${SPHINX_OUTPUT_DOCX})
+  add_sphinx_target(docx polly)
+endif()
   endif()
 endif()
 
Index: openmp/docs/conf.py
===
--- openmp/docs/conf.py
+++ openmp/docs/conf.py
@@ -28,6 +28,9 @@
 # coming with Sphinx (named 'sphinx.ext.*') or your custom ones.
 extensions = ['sphinx.ext.todo', 'sphinx.ext.mathjax', 'sphinx.ext.intersphinx']
 
+if tags.has('builder-docx'):
+extensions.append('docxbuilder')
+
 # Add any paths that contain templates here, relative to this directory.
 templates_path = ['_templates']
 
Index: openmp/docs/README.txt
===
--- openmp/docs/README.txt
+++ openmp/docs/README.txt
@@ -1,5 +1,5 @@
 OpenMP LLVM Documentation
-==
+=
 
 OpenMP LLVM's documentation is written in reStructuredText, a lightweight
 plaintext markup language (file extension `.rst`). While the
@@ -14,11 +14,15 @@
 cd 
 cmake -DLLVM_ENABLE_SPHINX=true -DSPHINX_OUTPUT_HTML=true 
 make
-$BROWSER /projects/openmp/docs//html/index.html
+$BROWSER /projects/openmp/docs/html/index.html
 
-The mapping between reStructuredText files and generated documentation is
-`docs/Foo.rst` <-> `/projects/openmp/docs//html/Foo.html` <->
-`https://openmp.llvm.org/docs/Foo.html`.
+The correspondence between reStructuredText files and generated HTML pages is:
+
+LLVM project
+`llvm/docs/Foo.rst` <-> `/docs/html/Foo.html` <-> `/share/doc/llvm/html/Foo.html` <-> `https://llvm.org/docs/Foo.html`
+
+Other projects
+`/docs/Foo.rst` <-> `/tools//docs/html/Foo.html` <-> `/share/doc//html/Foo.html`<-> `https://.llvm.org/docs/Foo.html`
 
 If you are interes

[PATCH] D105703: [hwasan] Use stack safety analysis.

2021-07-20 Thread Florian Mayer via Phabricator via cfe-commits
fmayer updated this revision to Diff 360076.
fmayer added a comment.

fix required analysis logic


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D105703

Files:
  clang/lib/CodeGen/BackendUtil.cpp
  clang/test/CodeGen/hwasan-stack-safety-analysis.c
  llvm/include/llvm/Transforms/Instrumentation/HWAddressSanitizer.h
  llvm/lib/Transforms/Instrumentation/HWAddressSanitizer.cpp
  llvm/test/Instrumentation/HWAddressSanitizer/stack-safety-analysis.ll

Index: llvm/test/Instrumentation/HWAddressSanitizer/stack-safety-analysis.ll
===
--- /dev/null
+++ llvm/test/Instrumentation/HWAddressSanitizer/stack-safety-analysis.ll
@@ -0,0 +1,42 @@
+; RUN: opt -hwasan -hwasan-use-stack-safety=1 -hwasan-generate-tags-with-calls -S < %s | FileCheck %s --check-prefixes=SAFETY
+; RUN: opt -hwasan -hwasan-use-stack-safety=0 -hwasan-generate-tags-with-calls -S < %s | FileCheck %s --check-prefixes=NOSAFETY
+
+target datalayout = "e-m:e-i8:8:32-i16:16:32-i64:64-i128:128-n32:64-S128"
+target triple = "aarch64-unknown-linux-gnu"
+
+; Check a safe alloca to ensure it does not get a tag.
+define i32 @test_load(i32* %a) sanitize_hwaddress {
+entry:
+  ; NOSAFETY: call {{.*}}__hwasan_generate_tag
+  ; SAFETY-NOT: call {{.*}}__hwasan_generate_tag
+  %buf.sroa.0 = alloca i8, align 4
+  call void @llvm.lifetime.start.p0i8(i64 1, i8* nonnull %buf.sroa.0)
+  store volatile i8 0, i8* %buf.sroa.0, align 4, !tbaa !8
+  call void @llvm.lifetime.end.p0i8(i64 1, i8* nonnull %buf.sroa.0)
+  ret i32 0
+}
+
+; Check a non-safe alloca to ensure it gets a tag.
+define i32 @test_use(i32* %a) sanitize_hwaddress {
+entry:
+  ; NOSAFETY: call {{.*}}__hwasan_generate_tag
+  ; SAFETY: call {{.*}}__hwasan_generate_tag
+  %buf.sroa.0 = alloca i8, align 4
+  call void @use(i8* nonnull %buf.sroa.0)
+  call void @llvm.lifetime.start.p0i8(i64 1, i8* nonnull %buf.sroa.0)
+  store volatile i8 0, i8* %buf.sroa.0, align 4, !tbaa !8
+  call void @llvm.lifetime.end.p0i8(i64 1, i8* nonnull %buf.sroa.0)
+  ret i32 0
+}
+
+; Function Attrs: argmemonly mustprogress nofree nosync nounwind willreturn
+declare void @llvm.lifetime.start.p0i8(i64 immarg, i8* nocapture)
+
+; Function Attrs: argmemonly mustprogress nofree nosync nounwind willreturn
+declare void @llvm.lifetime.end.p0i8(i64 immarg, i8* nocapture)
+
+declare void @use(i8* nocapture)
+
+!8 = !{!9, !9, i64 0}
+!9 = !{!"omnipotent char", !10, i64 0}
+!10 = !{!"Simple C/C++ TBAA"}
Index: llvm/lib/Transforms/Instrumentation/HWAddressSanitizer.cpp
===
--- llvm/lib/Transforms/Instrumentation/HWAddressSanitizer.cpp
+++ llvm/lib/Transforms/Instrumentation/HWAddressSanitizer.cpp
@@ -17,6 +17,7 @@
 #include "llvm/ADT/StringExtras.h"
 #include "llvm/ADT/StringRef.h"
 #include "llvm/ADT/Triple.h"
+#include "llvm/Analysis/StackSafetyAnalysis.h"
 #include "llvm/BinaryFormat/ELF.h"
 #include "llvm/IR/Attributes.h"
 #include "llvm/IR/BasicBlock.h"
@@ -109,6 +110,11 @@
cl::desc("instrument stack (allocas)"),
cl::Hidden, cl::init(true));
 
+static cl::opt
+ClUseStackSafety("hwasan-use-stack-safety", cl::Hidden, cl::init(true),
+ cl::Hidden, cl::desc("Use Stack Safety analysis results"),
+ cl::Optional);
+
 static cl::opt ClUARRetagToZero(
 "hwasan-uar-retag-to-zero",
 cl::desc("Clear alloca tags before returning from the function to allow "
@@ -216,11 +222,20 @@
 #endif
 }
 
+bool shouldUseStackSafetyAnalysis(const Triple &TargetTriple,
+  bool DisableOptimization) {
+  auto StackSafety = ClUseStackSafety.getNumOccurrences()
+ ? ClUseStackSafety
+ : !DisableOptimization;
+  return shouldInstrumentStack(TargetTriple) && StackSafety;
+}
 /// An instrumentation pass implementing detection of addressability bugs
 /// using tagged pointers.
 class HWAddressSanitizer {
 public:
-  HWAddressSanitizer(Module &M, bool CompileKernel, bool Recover) : M(M) {
+  HWAddressSanitizer(Module &M, bool CompileKernel, bool Recover,
+ const StackSafetyGlobalInfo *SSI)
+  : M(M), SSI(SSI) {
 this->Recover = ClRecover.getNumOccurrences() > 0 ? ClRecover : Recover;
 this->CompileKernel = ClEnableKhwasan.getNumOccurrences() > 0
   ? ClEnableKhwasan
@@ -229,6 +244,8 @@
 initializeModule();
   }
 
+  void setSSI(const StackSafetyGlobalInfo *S) { SSI = S; }
+
   bool sanitizeFunction(Function &F);
   void initializeModule();
   void createHwasanCtorComdat();
@@ -281,6 +298,7 @@
 private:
   LLVMContext *C;
   Module &M;
+  const StackSafetyGlobalInfo *SSI;
   Triple TargetTriple;
   FunctionCallee HWAsanMemmove, HWAsanMemcpy, HWAsanMemset;
   FunctionCallee HWAsanHandleVfork;
@@ -351,

[PATCH] D104536: [clang][deps] Avoid minimizing PCH input files

2021-07-20 Thread Nico Weber via Phabricator via cfe-commits
thakis added a comment.

Looks like this breaks tests on Windows: http://45.33.8.238/win/42264/step_7.txt

Please take a look, and revert for now if it takes a while to fix.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D104536

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


[clang] c94a345 - [clang][deps] Fix test by checking ignored files correctly

2021-07-20 Thread Jan Svoboda via cfe-commits

Author: Jan Svoboda
Date: 2021-07-20T13:20:56+02:00
New Revision: c94a345a5c693b6c12a41e8f50e3fe96d1311991

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

LOG: [clang][deps] Fix test by checking ignored files correctly

After a rebase, bc1a2979fc70d954ae97122205c71c8404a1b17e accidentally changed 
`shouldIgnoreFile(Filename)` to incorrect `IgnoredFiles.count(Filename)`. This 
avoided using native filenames, which the patch intended to solve in the first 
place.

Failing Windows builds:
* https://lab.llvm.org/buildbot#builders/123/builds/5147
* https://lab.llvm.org/buildbot#builders/86/builds/17177

Added: 


Modified: 
clang/lib/Tooling/DependencyScanning/DependencyScanningFilesystem.cpp

Removed: 




diff  --git 
a/clang/lib/Tooling/DependencyScanning/DependencyScanningFilesystem.cpp 
b/clang/lib/Tooling/DependencyScanning/DependencyScanningFilesystem.cpp
index 166d4a25363c..40e8bd2b8776 100644
--- a/clang/lib/Tooling/DependencyScanning/DependencyScanningFilesystem.cpp
+++ b/clang/lib/Tooling/DependencyScanning/DependencyScanningFilesystem.cpp
@@ -166,8 +166,7 @@ bool DependencyScanningWorkerFilesystem::shouldIgnoreFile(
 llvm::ErrorOr
 DependencyScanningWorkerFilesystem::getOrCreateFileSystemEntry(
 const StringRef Filename) {
-  bool ShouldMinimize =
-  !IgnoredFiles.count(Filename) && shouldMinimize(Filename);
+  bool ShouldMinimize = !shouldIgnoreFile(Filename) && 
shouldMinimize(Filename);
 
   if (const auto *Entry = Cache.getCachedEntry(Filename, ShouldMinimize))
 return Entry;



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


[PATCH] D104536: [clang][deps] Avoid minimizing PCH input files

2021-07-20 Thread Jan Svoboda via Phabricator via cfe-commits
jansvoboda11 added a comment.

In D104536#288 , @thakis wrote:

> Looks like this breaks tests on Windows: 
> http://45.33.8.238/win/42264/step_7.txt
>
> Please take a look, and revert for now if it takes a while to fix.

Thanks, that was a bad rebase. Should be fixed in 
c94a345a5c693b6c12a41e8f50e3fe96d1311991 
.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D104536

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


[PATCH] D105926: [PowerPC] Extra test case for LDARX

2021-07-20 Thread Kai Luo via Phabricator via cfe-commits
lkail added inline comments.



Comment at: clang/test/CodeGen/builtins-ppc-xlcompat-check-ldarx-opt.ll:1
+; NOTE: Assertions have been autogenerated by utils/update_llc_test_checks.py
+; RUN: llc -verify-machineinstrs -mtriple=powerpc64le-unknown-linux-gnu \

This looks problematic, we should not generate `llc`'s output in clang's test.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D105926

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


[PATCH] D105926: [PowerPC] Extra test case for LDARX

2021-07-20 Thread Kai Luo via Phabricator via cfe-commits
lkail requested changes to this revision.
lkail added a comment.
This revision now requires changes to proceed.

Looks we should put it in `llvm/test/CodeGen/PowerPC`.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D105926

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


[clang-tools-extra] 4190017 - [clangd] Add tests covering existing header-guard behavior. NFC

2021-07-20 Thread Sam McCall via cfe-commits

Author: Sam McCall
Date: 2021-07-20T14:12:23+02:00
New Revision: 419001724542d4b0d3423a71f0d42857af6a6227

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

LOG: [clangd] Add tests covering existing header-guard behavior. NFC

A few different mechanisms here that will need some work to untangle:
 - self-include in a preamble being an error even if the file is ifdef-guarded
 - the is-include-guarded flag not being propagated from preamble to main ast
 - preambles containing the first half on an include guard discard that info

For now just record current behavior.

Relevant to:
- https://github.com/clangd/clangd/issues/811
- https://github.com/clangd/clangd/issues/377
- https://github.com/clangd/clangd/issues/262

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

Added: 


Modified: 
clang-tools-extra/clangd/unittests/ParsedASTTests.cpp

Removed: 




diff  --git a/clang-tools-extra/clangd/unittests/ParsedASTTests.cpp 
b/clang-tools-extra/clangd/unittests/ParsedASTTests.cpp
index 5435648cd9be1..1c960c8944cbf 100644
--- a/clang-tools-extra/clangd/unittests/ParsedASTTests.cpp
+++ b/clang-tools-extra/clangd/unittests/ParsedASTTests.cpp
@@ -46,6 +46,7 @@ namespace {
 using ::testing::AllOf;
 using ::testing::ElementsAre;
 using ::testing::ElementsAreArray;
+using ::testing::IsEmpty;
 
 MATCHER_P(DeclNamed, Name, "") {
   if (NamedDecl *ND = dyn_cast(arg))
@@ -633,6 +634,260 @@ TEST(ParsedASTTest, PatchesDeletedIncludes) {
 testPath("foo.cpp";
 }
 
+// Returns Code guarded by #ifndef guards
+std::string guard(llvm::StringRef Code) {
+  static int GuardID = 0;
+  std::string GuardName = ("GUARD_" + llvm::Twine(++GuardID)).str();
+  return llvm::formatv("#ifndef {0}\n#define {0}\n{1}\n#endif\n", GuardName,
+   Code);
+}
+
+std::string once(llvm::StringRef Code) {
+  return llvm::formatv("#pragma once\n{0}\n", Code);
+}
+
+bool mainIsGuarded(const ParsedAST &AST) {
+  const auto &SM = AST.getSourceManager();
+  const FileEntry *MainFE = SM.getFileEntryForID(SM.getMainFileID());
+  return AST.getPreprocessor()
+  .getHeaderSearchInfo()
+  .isFileMultipleIncludeGuarded(MainFE);
+}
+
+MATCHER_P(Diag, Desc, "") {
+  return llvm::StringRef(arg.Message).contains(Desc);
+}
+
+// Check our understanding of whether the main file is header guarded or not.
+TEST(ParsedASTTest, HeaderGuards) {
+  TestTU TU;
+  TU.ImplicitHeaderGuard = false;
+
+  TU.Code = ";";
+  EXPECT_FALSE(mainIsGuarded(TU.build()));
+
+  TU.Code = guard(";");
+  EXPECT_FALSE(mainIsGuarded(TU.build())); // FIXME: true
+
+  TU.Code = once(";");
+  EXPECT_FALSE(mainIsGuarded(TU.build())); // FIXME: true
+
+  TU.Code = R"cpp(
+;
+#pragma once
+  )cpp";
+  EXPECT_FALSE(mainIsGuarded(TU.build())); // FIXME: true
+
+  TU.Code = R"cpp(
+;
+#ifndef GUARD
+#define GUARD
+;
+#endif
+  )cpp";
+  EXPECT_FALSE(mainIsGuarded(TU.build()));
+}
+
+// Check our handling of files that include themselves.
+// Ideally we allow this if the file has header guards.
+//
+// Note: the semicolons (empty statements) are significant!
+// - they force the preamble to end and the body to begin. Directives can have
+//   
diff erent effects in the preamble vs main file (which we try to hide).
+// - if the preamble would otherwise cover the whole file, a trailing semicolon
+//   forces their sizes to be 
diff erent. This is significant because the file
+//   size is part of the lookup key for HeaderFileInfo, and we don't want to
+//   rely on the preamble's HFI being looked up when parsing the main file.
+TEST(ParsedASTTest, HeaderGuardsSelfInclude) {
+  TestTU TU;
+  TU.ImplicitHeaderGuard = false;
+  TU.Filename = "self.h";
+
+  TU.Code = R"cpp(
+#include "self.h" // error-ok
+;
+  )cpp";
+  auto AST = TU.build();
+  EXPECT_THAT(*AST.getDiagnostics(),
+  ElementsAre(Diag("recursively when building a preamble")));
+  EXPECT_FALSE(mainIsGuarded(AST));
+
+  TU.Code = R"cpp(
+;
+#include "self.h" // error-ok
+  )cpp";
+  AST = TU.build();
+  EXPECT_THAT(*AST.getDiagnostics(), ElementsAre(Diag("nested too deeply")));
+  EXPECT_FALSE(mainIsGuarded(AST));
+
+  TU.Code = R"cpp(
+#pragma once
+#include "self.h"
+;
+  )cpp";
+  AST = TU.build();
+  EXPECT_THAT(*AST.getDiagnostics(), IsEmpty());
+  EXPECT_FALSE(mainIsGuarded(AST)); // FIXME: true
+
+  TU.Code = R"cpp(
+#pragma once
+;
+#include "self.h"
+  )cpp";
+  AST = TU.build();
+  EXPECT_THAT(*AST.getDiagnostics(), IsEmpty());
+  EXPECT_TRUE(mainIsGuarded(AST));
+
+  TU.Code = R"cpp(
+;
+#pragma once
+#include "self.h"
+  )cpp";
+  AST = TU.build();
+  EXPECT_THAT(*AST.getDiagnostics(), IsEmpty());
+  EXPECT_TRUE(mainIsGuarded(AST));
+
+  TU.Code = R"cpp(
+#ifndef G

[PATCH] D106201: [clangd] Add tests covering existing header-guard behavior. NFC

2021-07-20 Thread Sam McCall via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG419001724542: [clangd] Add tests covering existing 
header-guard behavior. NFC (authored by sammccall).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D106201

Files:
  clang-tools-extra/clangd/unittests/ParsedASTTests.cpp

Index: clang-tools-extra/clangd/unittests/ParsedASTTests.cpp
===
--- clang-tools-extra/clangd/unittests/ParsedASTTests.cpp
+++ clang-tools-extra/clangd/unittests/ParsedASTTests.cpp
@@ -46,6 +46,7 @@
 using ::testing::AllOf;
 using ::testing::ElementsAre;
 using ::testing::ElementsAreArray;
+using ::testing::IsEmpty;
 
 MATCHER_P(DeclNamed, Name, "") {
   if (NamedDecl *ND = dyn_cast(arg))
@@ -633,6 +634,260 @@
 testPath("foo.cpp";
 }
 
+// Returns Code guarded by #ifndef guards
+std::string guard(llvm::StringRef Code) {
+  static int GuardID = 0;
+  std::string GuardName = ("GUARD_" + llvm::Twine(++GuardID)).str();
+  return llvm::formatv("#ifndef {0}\n#define {0}\n{1}\n#endif\n", GuardName,
+   Code);
+}
+
+std::string once(llvm::StringRef Code) {
+  return llvm::formatv("#pragma once\n{0}\n", Code);
+}
+
+bool mainIsGuarded(const ParsedAST &AST) {
+  const auto &SM = AST.getSourceManager();
+  const FileEntry *MainFE = SM.getFileEntryForID(SM.getMainFileID());
+  return AST.getPreprocessor()
+  .getHeaderSearchInfo()
+  .isFileMultipleIncludeGuarded(MainFE);
+}
+
+MATCHER_P(Diag, Desc, "") {
+  return llvm::StringRef(arg.Message).contains(Desc);
+}
+
+// Check our understanding of whether the main file is header guarded or not.
+TEST(ParsedASTTest, HeaderGuards) {
+  TestTU TU;
+  TU.ImplicitHeaderGuard = false;
+
+  TU.Code = ";";
+  EXPECT_FALSE(mainIsGuarded(TU.build()));
+
+  TU.Code = guard(";");
+  EXPECT_FALSE(mainIsGuarded(TU.build())); // FIXME: true
+
+  TU.Code = once(";");
+  EXPECT_FALSE(mainIsGuarded(TU.build())); // FIXME: true
+
+  TU.Code = R"cpp(
+;
+#pragma once
+  )cpp";
+  EXPECT_FALSE(mainIsGuarded(TU.build())); // FIXME: true
+
+  TU.Code = R"cpp(
+;
+#ifndef GUARD
+#define GUARD
+;
+#endif
+  )cpp";
+  EXPECT_FALSE(mainIsGuarded(TU.build()));
+}
+
+// Check our handling of files that include themselves.
+// Ideally we allow this if the file has header guards.
+//
+// Note: the semicolons (empty statements) are significant!
+// - they force the preamble to end and the body to begin. Directives can have
+//   different effects in the preamble vs main file (which we try to hide).
+// - if the preamble would otherwise cover the whole file, a trailing semicolon
+//   forces their sizes to be different. This is significant because the file
+//   size is part of the lookup key for HeaderFileInfo, and we don't want to
+//   rely on the preamble's HFI being looked up when parsing the main file.
+TEST(ParsedASTTest, HeaderGuardsSelfInclude) {
+  TestTU TU;
+  TU.ImplicitHeaderGuard = false;
+  TU.Filename = "self.h";
+
+  TU.Code = R"cpp(
+#include "self.h" // error-ok
+;
+  )cpp";
+  auto AST = TU.build();
+  EXPECT_THAT(*AST.getDiagnostics(),
+  ElementsAre(Diag("recursively when building a preamble")));
+  EXPECT_FALSE(mainIsGuarded(AST));
+
+  TU.Code = R"cpp(
+;
+#include "self.h" // error-ok
+  )cpp";
+  AST = TU.build();
+  EXPECT_THAT(*AST.getDiagnostics(), ElementsAre(Diag("nested too deeply")));
+  EXPECT_FALSE(mainIsGuarded(AST));
+
+  TU.Code = R"cpp(
+#pragma once
+#include "self.h"
+;
+  )cpp";
+  AST = TU.build();
+  EXPECT_THAT(*AST.getDiagnostics(), IsEmpty());
+  EXPECT_FALSE(mainIsGuarded(AST)); // FIXME: true
+
+  TU.Code = R"cpp(
+#pragma once
+;
+#include "self.h"
+  )cpp";
+  AST = TU.build();
+  EXPECT_THAT(*AST.getDiagnostics(), IsEmpty());
+  EXPECT_TRUE(mainIsGuarded(AST));
+
+  TU.Code = R"cpp(
+;
+#pragma once
+#include "self.h"
+  )cpp";
+  AST = TU.build();
+  EXPECT_THAT(*AST.getDiagnostics(), IsEmpty());
+  EXPECT_TRUE(mainIsGuarded(AST));
+
+  TU.Code = R"cpp(
+#ifndef GUARD
+#define GUARD
+#include "self.h" // error-ok: FIXME, this would be nice to support
+#endif
+;
+  )cpp";
+  AST = TU.build();
+  EXPECT_THAT(*AST.getDiagnostics(),
+  ElementsAre(Diag("recursively when building a preamble")));
+  EXPECT_FALSE(mainIsGuarded(AST)); // FIXME: true
+
+  TU.Code = R"cpp(
+#ifndef GUARD
+#define GUARD
+;
+#include "self.h"
+#endif
+  )cpp";
+  AST = TU.build();
+  EXPECT_THAT(*AST.getDiagnostics(), IsEmpty());
+  EXPECT_FALSE(mainIsGuarded(AST)); // FIXME: true
+
+  // Guarded too late...
+  TU.Code = R"cpp(
+#include "self.h" // error-ok
+#ifndef GUARD
+#define GUARD
+;
+#endif
+  )cpp";
+  AST = TU.build();
+  EXPECT_THAT(*AST.getDiagnostics(),
+  ElementsAre(Diag("recursively whe

[clang-tools-extra] 69c04ef - [clangd] Propagate header-guarded flag from preamble to main AST

2021-07-20 Thread Sam McCall via cfe-commits

Author: Sam McCall
Date: 2021-07-20T14:21:39+02:00
New Revision: 69c04ef95a3529614b694d7e2fd57ee817076e86

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

LOG: [clangd] Propagate header-guarded flag from preamble to main AST

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

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

Added: 


Modified: 
clang-tools-extra/clangd/ParsedAST.cpp
clang-tools-extra/clangd/Preamble.cpp
clang-tools-extra/clangd/Preamble.h
clang-tools-extra/clangd/unittests/ParsedASTTests.cpp

Removed: 




diff  --git a/clang-tools-extra/clangd/ParsedAST.cpp 
b/clang-tools-extra/clangd/ParsedAST.cpp
index 2520062eed9b5..a60b9b6fe486a 100644
--- a/clang-tools-extra/clangd/ParsedAST.cpp
+++ b/clang-tools-extra/clangd/ParsedAST.cpp
@@ -309,6 +309,16 @@ ParsedAST::build(llvm::StringRef Filename, const 
ParseInputs &Inputs,
 MainInput.getFile());
 return None;
   }
+  // If we saw an include guard in the preamble section of the main file,
+  // mark the main-file as include-guarded.
+  // This information is part of the HeaderFileInfo but is not loaded from the
+  // preamble as the file's size is part of its identity and may have changed.
+  // (The rest of HeaderFileInfo is not relevant for our purposes).
+  if (Preamble && Preamble->MainIsIncludeGuarded) {
+const SourceManager &SM = Clang->getSourceManager();
+const FileEntry *MainFE = SM.getFileEntryForID(SM.getMainFileID());
+Clang->getPreprocessor().getHeaderSearchInfo().MarkFileIncludeOnce(MainFE);
+  }
 
   // Set up ClangTidy. Must happen after BeginSourceFile() so ASTContext 
exists.
   // Clang-tidy has some limitations to ensure reasonable performance:

diff  --git a/clang-tools-extra/clangd/Preamble.cpp 
b/clang-tools-extra/clangd/Preamble.cpp
index 9173dcda513a6..bc8c51bcc8588 100644
--- a/clang-tools-extra/clangd/Preamble.cpp
+++ b/clang-tools-extra/clangd/Preamble.cpp
@@ -75,11 +75,20 @@ class CppFilePreambleCallbacks : public PreambleCallbacks {
 
   CanonicalIncludes takeCanonicalIncludes() { return std::move(CanonIncludes); 
}
 
+  bool isMainFileIncludeGuarded() const { return IsMainFileIncludeGuarded; }
+
   void AfterExecute(CompilerInstance &CI) override {
-if (!ParsedCallback)
-  return;
-trace::Span Tracer("Running PreambleCallback");
-ParsedCallback(CI.getASTContext(), CI.getPreprocessorPtr(), CanonIncludes);
+if (ParsedCallback) {
+  trace::Span Tracer("Running PreambleCallback");
+  ParsedCallback(CI.getASTContext(), CI.getPreprocessorPtr(),
+ CanonIncludes);
+}
+
+const SourceManager &SM = CI.getSourceManager();
+const FileEntry *MainFE = SM.getFileEntryForID(SM.getMainFileID());
+IsMainFileIncludeGuarded =
+
CI.getPreprocessor().getHeaderSearchInfo().isFileMultipleIncludeGuarded(
+MainFE);
   }
 
   void BeforeExecute(CompilerInstance &CI) override {
@@ -121,6 +130,7 @@ class CppFilePreambleCallbacks : public PreambleCallbacks {
   IncludeStructure Includes;
   CanonicalIncludes CanonIncludes;
   MainFileMacros Macros;
+  bool IsMainFileIncludeGuarded = false;
   std::unique_ptr IWYUHandler = nullptr;
   const clang::LangOptions *LangOpts = nullptr;
   const SourceManager *SourceMgr = nullptr;
@@ -365,7 +375,7 @@ buildPreamble(PathRef FileName, CompilerInvocation CI,
   // to read back. We rely on dynamic index for the comments instead.
   CI.getPreprocessorOpts().WriteCommentListToPCH = false;
 
-  CppFilePreambleCallbacks SerializedDeclsCollector(FileName, 
PreambleCallback);
+  CppFilePreambleCallbacks CapturedInfo(FileName, PreambleCallback);
   auto VFS = Inputs.TFS->view(Inputs.CompileCommand.Directory);
   llvm::SmallString<32> AbsFileName(FileName);
   VFS->makeAbsolute(AbsFileName);
@@ -373,8 +383,7 @@ buildPreamble(PathRef FileName, CompilerInvocation CI,
   auto BuiltPreamble = PrecompiledPreamble::Build(
   CI, ContentsBuffer.get(), Bounds, *PreambleDiagsEngine,
   StatCache->getProducingFS(VFS),
-  std::make_shared(), StoreInMemory,
-  SerializedDeclsCollector);
+  std::make_shared(), StoreInMemory, CapturedInfo);
 
   // When building the AST for the main file, we do want the function
   // bodies.
@@ -384,16 +393,17 @@ buildPreamble(PathRef FileName, CompilerInvocation CI,
 vlog("Built preamble of size {0} for file {1} version {2}",
  BuiltPreamble->getSize(), FileName, Inputs.Version);
 std::vector Diags = PreambleDiagnostics.take();
-return std::make_shared(
+auto Result = std::make_shared(
 Inputs, std::move(*BuiltPreamble), std::move(Diags),
-SerializedDeclsCollector.takeIncludes(),
-SerializedDeclsCollector.takeMacros(), std::move(StatCache),
-SerializedDeclsCollect

[PATCH] D106203: [clangd] Propagate header-guarded flag from preamble to main AST

2021-07-20 Thread Sam McCall via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG69c04ef95a35: [clangd] Propagate header-guarded flag from 
preamble to main AST (authored by sammccall).

Changed prior to commit:
  https://reviews.llvm.org/D106203?vs=359499&id=360093#toc

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D106203

Files:
  clang-tools-extra/clangd/ParsedAST.cpp
  clang-tools-extra/clangd/Preamble.cpp
  clang-tools-extra/clangd/Preamble.h
  clang-tools-extra/clangd/unittests/ParsedASTTests.cpp

Index: clang-tools-extra/clangd/unittests/ParsedASTTests.cpp
===
--- clang-tools-extra/clangd/unittests/ParsedASTTests.cpp
+++ clang-tools-extra/clangd/unittests/ParsedASTTests.cpp
@@ -670,7 +670,7 @@
   EXPECT_FALSE(mainIsGuarded(TU.build())); // FIXME: true
 
   TU.Code = once(";");
-  EXPECT_FALSE(mainIsGuarded(TU.build())); // FIXME: true
+  EXPECT_TRUE(mainIsGuarded(TU.build()));
 
   TU.Code = R"cpp(
 ;
@@ -727,7 +727,7 @@
   )cpp";
   AST = TU.build();
   EXPECT_THAT(*AST.getDiagnostics(), IsEmpty());
-  EXPECT_FALSE(mainIsGuarded(AST)); // FIXME: true
+  EXPECT_TRUE(mainIsGuarded(AST));
 
   TU.Code = R"cpp(
 #pragma once
@@ -757,7 +757,7 @@
   AST = TU.build();
   EXPECT_THAT(*AST.getDiagnostics(),
   ElementsAre(Diag("recursively when building a preamble")));
-  EXPECT_FALSE(mainIsGuarded(AST)); // FIXME: true
+  EXPECT_TRUE(mainIsGuarded(AST));
 
   TU.Code = R"cpp(
 #ifndef GUARD
@@ -814,7 +814,7 @@
   AST = TU.build();
   EXPECT_THAT(*AST.getDiagnostics(),
   ElementsAre(Diag("recursively when building a preamble")));
-  EXPECT_FALSE(mainIsGuarded(AST)); // FIXME: true
+  EXPECT_TRUE(mainIsGuarded(AST));
 
   TU.Code = R"cpp(
 #include "self.h" // error-ok
@@ -863,9 +863,7 @@
   // need to transfer it to the main file's HeaderFileInfo.
   TU.Code = once(Interface);
   AST = TU.build();
-  // FIXME: empty
-  EXPECT_THAT(*AST.getDiagnostics(),
-  ElementsAre(Diag("in included file: redefinition of 'Traits'")));
+  EXPECT_THAT(*AST.getDiagnostics(), IsEmpty());
   EXPECT_TRUE(mainIsGuarded(AST));
 
   // Editing the implementation file, which is not include guarded.
Index: clang-tools-extra/clangd/Preamble.h
===
--- clang-tools-extra/clangd/Preamble.h
+++ clang-tools-extra/clangd/Preamble.h
@@ -69,6 +69,9 @@
   // When reusing a preamble, this cache can be consumed to save IO.
   std::unique_ptr StatCache;
   CanonicalIncludes CanonIncludes;
+  // Whether there was a (possibly-incomplete) include-guard on the main file.
+  // We need to propagate this information "by hand" to subsequent parses.
+  bool MainIsIncludeGuarded = false;
 };
 
 using PreambleParsedCallback =
Index: clang-tools-extra/clangd/Preamble.cpp
===
--- clang-tools-extra/clangd/Preamble.cpp
+++ clang-tools-extra/clangd/Preamble.cpp
@@ -75,11 +75,20 @@
 
   CanonicalIncludes takeCanonicalIncludes() { return std::move(CanonIncludes); }
 
+  bool isMainFileIncludeGuarded() const { return IsMainFileIncludeGuarded; }
+
   void AfterExecute(CompilerInstance &CI) override {
-if (!ParsedCallback)
-  return;
-trace::Span Tracer("Running PreambleCallback");
-ParsedCallback(CI.getASTContext(), CI.getPreprocessorPtr(), CanonIncludes);
+if (ParsedCallback) {
+  trace::Span Tracer("Running PreambleCallback");
+  ParsedCallback(CI.getASTContext(), CI.getPreprocessorPtr(),
+ CanonIncludes);
+}
+
+const SourceManager &SM = CI.getSourceManager();
+const FileEntry *MainFE = SM.getFileEntryForID(SM.getMainFileID());
+IsMainFileIncludeGuarded =
+CI.getPreprocessor().getHeaderSearchInfo().isFileMultipleIncludeGuarded(
+MainFE);
   }
 
   void BeforeExecute(CompilerInstance &CI) override {
@@ -121,6 +130,7 @@
   IncludeStructure Includes;
   CanonicalIncludes CanonIncludes;
   MainFileMacros Macros;
+  bool IsMainFileIncludeGuarded = false;
   std::unique_ptr IWYUHandler = nullptr;
   const clang::LangOptions *LangOpts = nullptr;
   const SourceManager *SourceMgr = nullptr;
@@ -365,7 +375,7 @@
   // to read back. We rely on dynamic index for the comments instead.
   CI.getPreprocessorOpts().WriteCommentListToPCH = false;
 
-  CppFilePreambleCallbacks SerializedDeclsCollector(FileName, PreambleCallback);
+  CppFilePreambleCallbacks CapturedInfo(FileName, PreambleCallback);
   auto VFS = Inputs.TFS->view(Inputs.CompileCommand.Directory);
   llvm::SmallString<32> AbsFileName(FileName);
   VFS->makeAbsolute(AbsFileName);
@@ -373,8 +383,7 @@
   auto BuiltPreamble = PrecompiledPreamble::Build(
   CI, ContentsBuffer.get(), Bounds, *PreambleDiagsEngine,
   StatCache->getProducingFS(VFS),
-  std::make_shared(), StoreInMemory,
-

[clang-tools-extra] eb03fa1 - [clang-tidy] Don't suggest "inline" fix for main function in

2021-07-20 Thread Haojian Wu via cfe-commits

Author: Haojian Wu
Date: 2021-07-20T14:24:38+02:00
New Revision: eb03fa1d2c05bad5a5f75a89d47b4b31d84bb90b

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

LOG: [clang-tidy] Don't suggest "inline" fix for main function in
definitions-in-headers check.

Added: 


Modified: 
clang-tools-extra/clang-tidy/misc/DefinitionsInHeadersCheck.cpp
clang-tools-extra/test/clang-tidy/checkers/misc-definitions-in-headers.hpp

Removed: 




diff  --git a/clang-tools-extra/clang-tidy/misc/DefinitionsInHeadersCheck.cpp 
b/clang-tools-extra/clang-tidy/misc/DefinitionsInHeadersCheck.cpp
index 820bb3bebd913..882d254c6d9ea 100644
--- a/clang-tools-extra/clang-tidy/misc/DefinitionsInHeadersCheck.cpp
+++ b/clang-tools-extra/clang-tidy/misc/DefinitionsInHeadersCheck.cpp
@@ -127,6 +127,9 @@ void DefinitionsInHeadersCheck::check(const 
MatchFinder::MatchResult &Result) {
  "in a header file; function definitions in header files can lead to "
  "ODR violations")
 << IsFullSpec << FD;
+// inline is not allowed for main function.
+if (FD->isMain())
+  return;
 diag(FD->getLocation(), /*FixDescription=*/"make as 'inline'",
  DiagnosticIDs::Note)
 << FixItHint::CreateInsertion(FD->getInnerLocStart(), "inline ");

diff  --git 
a/clang-tools-extra/test/clang-tidy/checkers/misc-definitions-in-headers.hpp 
b/clang-tools-extra/test/clang-tidy/checkers/misc-definitions-in-headers.hpp
index 7b017391d5acb..c2a4a81ae3e16 100644
--- a/clang-tools-extra/test/clang-tidy/checkers/misc-definitions-in-headers.hpp
+++ b/clang-tools-extra/test/clang-tidy/checkers/misc-definitions-in-headers.hpp
@@ -192,3 +192,7 @@ template <>
 const int f12() { return 0; }
 // CHECK-MESSAGES: :[[@LINE-1]]:11: warning: full function template 
specialization 'f12' defined in a header file;
 // CHECK-FIXES: inline const int f12() { return 0; }
+
+int main() {}
+// CHECK-MESSAGES: :[[@LINE-1]]:5: warning: function 'main' defined in a 
header file;
+// CHECK-FIXES: {{^}}int main() {



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


[clang] fd22785 - [Lex] Consider a PCH header-guarded even with #endif truncated

2021-07-20 Thread Sam McCall via cfe-commits

Author: Sam McCall
Date: 2021-07-20T14:25:36+02:00
New Revision: fd2278505482bd9db21423b0620be6afe04feb60

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

LOG: [Lex] Consider a PCH header-guarded even with #endif truncated

This seems to be a more useful behavior for tools that use preambles.
I believe it doesn't affect real compiles: the PCH is only included once
when used, and recursive inclusion of the main-file *within* the PCH
isn't supported in any case.

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

Added: 


Modified: 
clang-tools-extra/clangd/unittests/ParsedASTTests.cpp
clang/lib/Lex/Lexer.cpp

Removed: 




diff  --git a/clang-tools-extra/clangd/unittests/ParsedASTTests.cpp 
b/clang-tools-extra/clangd/unittests/ParsedASTTests.cpp
index 365dbc581c201..ef0199a11ed90 100644
--- a/clang-tools-extra/clangd/unittests/ParsedASTTests.cpp
+++ b/clang-tools-extra/clangd/unittests/ParsedASTTests.cpp
@@ -667,7 +667,7 @@ TEST(ParsedASTTest, HeaderGuards) {
   EXPECT_FALSE(mainIsGuarded(TU.build()));
 
   TU.Code = guard(";");
-  EXPECT_FALSE(mainIsGuarded(TU.build())); // FIXME: true
+  EXPECT_TRUE(mainIsGuarded(TU.build()));
 
   TU.Code = once(";");
   EXPECT_TRUE(mainIsGuarded(TU.build()));
@@ -768,7 +768,7 @@ TEST(ParsedASTTest, HeaderGuardsSelfInclude) {
   )cpp";
   AST = TU.build();
   EXPECT_THAT(*AST.getDiagnostics(), IsEmpty());
-  EXPECT_FALSE(mainIsGuarded(AST)); // FIXME: true
+  EXPECT_TRUE(mainIsGuarded(AST));
 
   // Guarded too late...
   TU.Code = R"cpp(
@@ -858,7 +858,7 @@ TEST(ParsedASTTest, HeaderGuardsImplIface) {
   TU.AdditionalFiles = {{"impl.h", Implementation}};
   auto AST = TU.build();
   EXPECT_THAT(*AST.getDiagnostics(), IsEmpty());
-  EXPECT_FALSE(mainIsGuarded(AST)); // FIXME: true
+  EXPECT_TRUE(mainIsGuarded(AST));
   // Slightly harder: the `#pragma once` is part of the preamble, and we
   // need to transfer it to the main file's HeaderFileInfo.
   TU.Code = once(Interface);

diff  --git a/clang/lib/Lex/Lexer.cpp b/clang/lib/Lex/Lexer.cpp
index 2cc4cae533d07..ac0489e58407f 100644
--- a/clang/lib/Lex/Lexer.cpp
+++ b/clang/lib/Lex/Lexer.cpp
@@ -2793,6 +2793,11 @@ bool Lexer::LexEndOfFile(Token &Result, const char 
*CurPtr) {
 
   if (PP->isRecordingPreamble() && PP->isInPrimaryFile()) {
 PP->setRecordedPreambleConditionalStack(ConditionalStack);
+// If the preamble cuts off the end of a header guard, consider it guarded.
+// The guard is valid for the preamble content itself, and for tools the
+// most useful answer is "yes, this file has a header guard".
+if (!ConditionalStack.empty())
+  MIOpt.ExitTopLevelConditional();
 ConditionalStack.clear();
   }
 



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


[PATCH] D106204: [Lex] Consider a PCH header-guarded even with #endif truncated

2021-07-20 Thread Sam McCall via Phabricator via cfe-commits
This revision was landed with ongoing or failed builds.
This revision was automatically updated to reflect the committed changes.
Closed by commit rGfd2278505482: [Lex] Consider a PCH header-guarded even with 
#endif truncated (authored by sammccall).

Changed prior to commit:
  https://reviews.llvm.org/D106204?vs=359503&id=360095#toc

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D106204

Files:
  clang-tools-extra/clangd/unittests/ParsedASTTests.cpp
  clang/lib/Lex/Lexer.cpp


Index: clang/lib/Lex/Lexer.cpp
===
--- clang/lib/Lex/Lexer.cpp
+++ clang/lib/Lex/Lexer.cpp
@@ -2793,6 +2793,11 @@
 
   if (PP->isRecordingPreamble() && PP->isInPrimaryFile()) {
 PP->setRecordedPreambleConditionalStack(ConditionalStack);
+// If the preamble cuts off the end of a header guard, consider it guarded.
+// The guard is valid for the preamble content itself, and for tools the
+// most useful answer is "yes, this file has a header guard".
+if (!ConditionalStack.empty())
+  MIOpt.ExitTopLevelConditional();
 ConditionalStack.clear();
   }
 
Index: clang-tools-extra/clangd/unittests/ParsedASTTests.cpp
===
--- clang-tools-extra/clangd/unittests/ParsedASTTests.cpp
+++ clang-tools-extra/clangd/unittests/ParsedASTTests.cpp
@@ -667,7 +667,7 @@
   EXPECT_FALSE(mainIsGuarded(TU.build()));
 
   TU.Code = guard(";");
-  EXPECT_FALSE(mainIsGuarded(TU.build())); // FIXME: true
+  EXPECT_TRUE(mainIsGuarded(TU.build()));
 
   TU.Code = once(";");
   EXPECT_TRUE(mainIsGuarded(TU.build()));
@@ -768,7 +768,7 @@
   )cpp";
   AST = TU.build();
   EXPECT_THAT(*AST.getDiagnostics(), IsEmpty());
-  EXPECT_FALSE(mainIsGuarded(AST)); // FIXME: true
+  EXPECT_TRUE(mainIsGuarded(AST));
 
   // Guarded too late...
   TU.Code = R"cpp(
@@ -858,7 +858,7 @@
   TU.AdditionalFiles = {{"impl.h", Implementation}};
   auto AST = TU.build();
   EXPECT_THAT(*AST.getDiagnostics(), IsEmpty());
-  EXPECT_FALSE(mainIsGuarded(AST)); // FIXME: true
+  EXPECT_TRUE(mainIsGuarded(AST));
   // Slightly harder: the `#pragma once` is part of the preamble, and we
   // need to transfer it to the main file's HeaderFileInfo.
   TU.Code = once(Interface);


Index: clang/lib/Lex/Lexer.cpp
===
--- clang/lib/Lex/Lexer.cpp
+++ clang/lib/Lex/Lexer.cpp
@@ -2793,6 +2793,11 @@
 
   if (PP->isRecordingPreamble() && PP->isInPrimaryFile()) {
 PP->setRecordedPreambleConditionalStack(ConditionalStack);
+// If the preamble cuts off the end of a header guard, consider it guarded.
+// The guard is valid for the preamble content itself, and for tools the
+// most useful answer is "yes, this file has a header guard".
+if (!ConditionalStack.empty())
+  MIOpt.ExitTopLevelConditional();
 ConditionalStack.clear();
   }
 
Index: clang-tools-extra/clangd/unittests/ParsedASTTests.cpp
===
--- clang-tools-extra/clangd/unittests/ParsedASTTests.cpp
+++ clang-tools-extra/clangd/unittests/ParsedASTTests.cpp
@@ -667,7 +667,7 @@
   EXPECT_FALSE(mainIsGuarded(TU.build()));
 
   TU.Code = guard(";");
-  EXPECT_FALSE(mainIsGuarded(TU.build())); // FIXME: true
+  EXPECT_TRUE(mainIsGuarded(TU.build()));
 
   TU.Code = once(";");
   EXPECT_TRUE(mainIsGuarded(TU.build()));
@@ -768,7 +768,7 @@
   )cpp";
   AST = TU.build();
   EXPECT_THAT(*AST.getDiagnostics(), IsEmpty());
-  EXPECT_FALSE(mainIsGuarded(AST)); // FIXME: true
+  EXPECT_TRUE(mainIsGuarded(AST));
 
   // Guarded too late...
   TU.Code = R"cpp(
@@ -858,7 +858,7 @@
   TU.AdditionalFiles = {{"impl.h", Implementation}};
   auto AST = TU.build();
   EXPECT_THAT(*AST.getDiagnostics(), IsEmpty());
-  EXPECT_FALSE(mainIsGuarded(AST)); // FIXME: true
+  EXPECT_TRUE(mainIsGuarded(AST));
   // Slightly harder: the `#pragma once` is part of the preamble, and we
   // need to transfer it to the main file's HeaderFileInfo.
   TU.Code = once(Interface);
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D102343: [clang][patch][FPEnv} Initialization of C++ globals not strictfp aware

2021-07-20 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman added inline comments.



Comment at: clang/include/clang/AST/Decl.h:1993
const DeclarationNameInfo &NameInfo, QualType T,
-   TypeSourceInfo *TInfo, StorageClass S, bool isInlineSpecified,
-   ConstexprSpecKind ConstexprKind,
+   TypeSourceInfo *TInfo, StorageClass S, bool UsesFPIntrin,
+   bool isInlineSpecified, ConstexprSpecKind ConstexprKind,

I have no idea if others agree, but I have a slight preference for putting 
`UsesFPIntrin` towards the end of the parameter list (here and in the Create 
methods) -- this flag seems less important than the constexpr kind or whether 
inline is specified (and, it helpfully avoids putting two `bool` parameters 
next to one another).

If you agree, perhaps it could be moved to before `TrailingRequiresClause`?



Comment at: clang/include/clang/AST/Decl.h:2598
+  /// Determine whether the function was declared in source context
+  /// that requires constrained FP intrinsics
+  bool UsesFPIntrin() const { return FunctionDeclBits.UsesFPIntrin; }





Comment at: clang/include/clang/AST/Decl.h:2602
+  /// Set whether the function was declared in source context
+  /// that requires constrained FP intrinsics
+  void setUsesFPIntrin(bool I) { FunctionDeclBits.UsesFPIntrin = I; }





Comment at: clang/lib/CodeGen/CodeGenFunction.cpp:939
+  llvm::RoundingMode RM = getLangOpts().getFPRoundingMode();
+  auto fpExceptionBehavior =
+  ToConstrainedExceptMD(getLangOpts().getFPExceptionMode());

Please spell out the type rather than use `auto`, also, should probably be `FP` 
rather than `fp` per the usual naming conventions.



Comment at: clang/lib/CodeGen/CodeGenFunction.cpp:700
   CurCodeDecl = D;
-  if (const auto *FD = dyn_cast_or_null(D))
-if (FD->usesSEHTry())
-  CurSEHParent = FD;
+  const FunctionDecl *FD = dyn_cast_or_null(D);
+  if (FD && FD->usesSEHTry())

mibintc wrote:
> there's a whole bunch of places in this func that creates FD, I changed them 
> into a single place. hope that's OK, or i could pull it out as a pre-patch if 
> you prefer
I think it'd be better to separate these changes into an NFC patch (feel free 
to land it without review; I've checked the changes here and they look correct 
and NFC).


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D102343

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


[PATCH] D106347: [PoC][RISCV] Encode arch information in a new module flag meatadata 'riscv-isa-bits'.

2021-07-20 Thread Jessica Clarke via Phabricator via cfe-commits
jrtc27 added a comment.

Why can't we just save target-features itself as a module flag instead of 
inventing yet another equivalent encoding?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D106347

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


[PATCH] D105881: [flang][driver] Switch to `BoolFOption` for boolean options

2021-07-20 Thread Andrzej Warzynski via Phabricator via cfe-commits
awarzynski added a comment.

Apologies, it has taken me a bit longer to get back to this. @jansvoboda11 , 
now I'm realising the key disadvantage of using `OptInFFlag/OptOutFFlag` - it's 
impossible to express the `opt-in`/`opt-out` semantics in TableGen. In fact, 
only the contents of `clang -cc1 --help` are being tweaked by using 
`OptInFFlag/OptOutFFlag`. Basically:

- for `OptInFFlang`, only `-ffoo` is printed with `-clang -cc1 --help` (the 
help text for `-ffno-foo` becomes irrelevant)
- for `OptOutFFlang`, only `-fno-foo` is printed with `-clang -cc1 --help` (the 
help text for `-ffoo` is irrelevant)

IIUC, this is achieved through `flags` (`CC1Option` vs `[]`). In Flang, we rely 
on the fact that "no help text? don't include it in `flang-new -fc1 --help`" 
instead. This behavior is implemented in `clangDriver` and applies to all 
drivers that use it (so this is nothing specific to Flang). This way, we can 
always mark Flang options with the relevant flags (e.g. `FC1Option`). In other 
words, we can claim them and make it clear that other drivers can ignore them. 
In general, I think that Options.td would become a bit cleaner and easier to 
reason about if all options specified all their flags. That wouldn't be easy to 
achieve though!

I'm just about send an updated patch. It takes into account the points that I 
raised above ^^^. It also fixes the failing tests reported by @PeteSteinfeld. 
Does this new approach work for Clang (I quickly tested `clang -cc1 --help` and 
see no difference)?

It would be nicer to have the `opt-in`/`opt-out` semantics for Flang in 
TableGen through something similar to `BoolFOption`. No need for this just now 
- one step at a time :)


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D105881

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


[PATCH] D105491: [clang] Use i64 for the !srcloc metadata on asm IR nodes.

2021-07-20 Thread Simon Tatham via Phabricator via cfe-commits
simon_tatham updated this revision to Diff 360098.
simon_tatham edited the summary of this revision.
simon_tatham added a comment.

Added an i64 `!srcloc` to the only existing test of them I could find.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D105491

Files:
  clang/lib/CodeGen/CGStmt.cpp
  llvm/include/llvm/IR/DiagnosticInfo.h
  llvm/include/llvm/IR/LLVMContext.h
  llvm/lib/CodeGen/AsmPrinter/AsmPrinterInlineAsm.cpp
  llvm/lib/CodeGen/MachineInstr.cpp
  llvm/lib/IR/LLVMContext.cpp
  llvm/test/MC/ARM/inline-asm-srcloc.ll

Index: llvm/test/MC/ARM/inline-asm-srcloc.ll
===
--- llvm/test/MC/ARM/inline-asm-srcloc.ll
+++ llvm/test/MC/ARM/inline-asm-srcloc.ll
@@ -20,6 +20,8 @@
 ; CHECK: note: !srcloc = 181
   call void asm sideeffect " .word -foo", ""() #1, !srcloc !5
 ; CHECK: note: !srcloc = 257
+  call void asm sideeffect " .word -stoat", ""() #1, !srcloc !6
+; CHECK: note: !srcloc = 534
   ret void
 }
 
@@ -35,3 +37,4 @@
 !3 = !{i32 107}
 !4 = !{i32 181}
 !5 = !{i32 257}
+!6 = !{i64 534}
Index: llvm/lib/IR/LLVMContext.cpp
===
--- llvm/lib/IR/LLVMContext.cpp
+++ llvm/lib/IR/LLVMContext.cpp
@@ -248,7 +248,7 @@
 exit(1);
 }
 
-void LLVMContext::emitError(unsigned LocCookie, const Twine &ErrorStr) {
+void LLVMContext::emitError(uint64_t LocCookie, const Twine &ErrorStr) {
   diagnose(DiagnosticInfoInlineAsm(LocCookie, ErrorStr));
 }
 
Index: llvm/lib/CodeGen/MachineInstr.cpp
===
--- llvm/lib/CodeGen/MachineInstr.cpp
+++ llvm/lib/CodeGen/MachineInstr.cpp
@@ -2083,7 +2083,7 @@
 
 void MachineInstr::emitError(StringRef Msg) const {
   // Find the source location cookie.
-  unsigned LocCookie = 0;
+  uint64_t LocCookie = 0;
   const MDNode *LocMD = nullptr;
   for (unsigned i = getNumOperands(); i != 0; --i) {
 if (getOperand(i-1).isMetadata() &&
Index: llvm/lib/CodeGen/AsmPrinter/AsmPrinterInlineAsm.cpp
===
--- llvm/lib/CodeGen/AsmPrinter/AsmPrinterInlineAsm.cpp
+++ llvm/lib/CodeGen/AsmPrinter/AsmPrinterInlineAsm.cpp
@@ -130,7 +130,7 @@
 
 static void EmitMSInlineAsmStr(const char *AsmStr, const MachineInstr *MI,
MachineModuleInfo *MMI, AsmPrinter *AP,
-   unsigned LocCookie, raw_ostream &OS) {
+   uint64_t LocCookie, raw_ostream &OS) {
   // Switch to the inline assembly variant.
   OS << "\t.intel_syntax\n\t";
 
@@ -272,7 +272,7 @@
 
 static void EmitGCCInlineAsmStr(const char *AsmStr, const MachineInstr *MI,
 MachineModuleInfo *MMI, const MCAsmInfo *MAI,
-AsmPrinter *AP, unsigned LocCookie,
+AsmPrinter *AP, uint64_t LocCookie,
 raw_ostream &OS) {
   int CurVariant = -1;// The number of the {.|.|.} region we are in.
   const char *LastEmitted = AsmStr; // One past the last character emitted.
@@ -483,7 +483,7 @@
 
   // Get the !srcloc metadata node if we have it, and decode the loc cookie from
   // it.
-  unsigned LocCookie = 0;
+  uint64_t LocCookie = 0;
   const MDNode *LocMD = nullptr;
   for (unsigned i = MI->getNumOperands(); i != 0; --i) {
 if (MI->getOperand(i-1).isMetadata() &&
Index: llvm/include/llvm/IR/LLVMContext.h
===
--- llvm/include/llvm/IR/LLVMContext.h
+++ llvm/include/llvm/IR/LLVMContext.h
@@ -290,7 +290,7 @@
   /// be prepared to drop the erroneous construct on the floor and "not crash".
   /// The generated code need not be correct.  The error message will be
   /// implicitly prefixed with "error: " and should not end with a ".".
-  void emitError(unsigned LocCookie, const Twine &ErrorStr);
+  void emitError(uint64_t LocCookie, const Twine &ErrorStr);
   void emitError(const Instruction *I, const Twine &ErrorStr);
   void emitError(const Twine &ErrorStr);
 
Index: llvm/include/llvm/IR/DiagnosticInfo.h
===
--- llvm/include/llvm/IR/DiagnosticInfo.h
+++ llvm/include/llvm/IR/DiagnosticInfo.h
@@ -131,7 +131,7 @@
 class DiagnosticInfoInlineAsm : public DiagnosticInfo {
 private:
   /// Optional line information. 0 if not set.
-  unsigned LocCookie = 0;
+  uint64_t LocCookie = 0;
   /// Message to be reported.
   const Twine &MsgStr;
   /// Optional origin of the problem.
@@ -149,7 +149,7 @@
   /// \p MsgStr gives the message.
   /// This class does not copy \p MsgStr, therefore the reference must be valid
   /// for the whole life time of the Diagnostic.
-  DiagnosticInfoInlineAsm(unsigned LocCookie, const Twine &MsgStr,
+  DiagnosticInfoInlineAsm(uint64_t LocCookie, const Twine &MsgStr,
   

[PATCH] D105492: [clang] Introduce SourceLocation::[U]IntTy typedefs.

2021-07-20 Thread Simon Tatham via Phabricator via cfe-commits
simon_tatham updated this revision to Diff 360099.
simon_tatham retitled this revision from "[clang] Introduce 
SourceLocation::[U]IntType typedefs." to "[clang] Introduce 
SourceLocation::[U]IntTy typedefs.".
simon_tatham added a comment.

Renamed types to [U]IntTy. This will affect some of the dependent patches too, 
but I agree that saving two characters is worthwhile – these names are long 
enough already :-)


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D105492

Files:
  clang/include/clang/AST/DeclarationName.h
  clang/include/clang/Basic/SourceLocation.h
  clang/include/clang/Basic/SourceManager.h
  clang/include/clang/Lex/Token.h
  clang/include/clang/Serialization/ASTBitCodes.h
  clang/include/clang/Serialization/ASTReader.h
  clang/include/clang/Serialization/ASTWriter.h
  clang/include/clang/Serialization/ModuleFile.h
  clang/lib/ARCMigrate/TransEmptyStatementsAndDealloc.cpp
  clang/lib/AST/NestedNameSpecifier.cpp
  clang/lib/Basic/SourceLocation.cpp
  clang/lib/Basic/SourceManager.cpp
  clang/lib/CodeGen/CGOpenMPRuntime.cpp
  clang/lib/Lex/Lexer.cpp
  clang/lib/Lex/ModuleMap.cpp
  clang/lib/Lex/PPCaching.cpp
  clang/lib/Lex/TokenLexer.cpp
  clang/lib/Serialization/ASTReader.cpp
  clang/lib/Serialization/ASTWriter.cpp
  clang/tools/libclang/CIndex.cpp

Index: clang/tools/libclang/CIndex.cpp
===
--- clang/tools/libclang/CIndex.cpp
+++ clang/tools/libclang/CIndex.cpp
@@ -1983,7 +1983,8 @@
 return static_cast(data[0]);
   }
   SourceLocation getLoc() const {
-return SourceLocation::getFromRawEncoding((unsigned)(uintptr_t)data[1]);
+return SourceLocation::getFromRawEncoding(
+(SourceLocation::UIntTy)(uintptr_t)data[1]);
   }
 };
 class EnqueueVisitor : public ConstStmtVisitor {
Index: clang/lib/Serialization/ASTWriter.cpp
===
--- clang/lib/Serialization/ASTWriter.cpp
+++ clang/lib/Serialization/ASTWriter.cpp
@@ -2041,7 +2041,7 @@
   Record.push_back(Expansion.isExpansionTokenRange());
 
   // Compute the token length for this macro expansion.
-  unsigned NextOffset = SourceMgr.getNextLocalOffset();
+  SourceLocation::UIntTy NextOffset = SourceMgr.getNextLocalOffset();
   if (I + 1 != N)
 NextOffset = SourceMgr.getLocalSLocEntry(I + 1).getOffset();
   Record.push_back(NextOffset - SLoc->getOffset() - 1);
@@ -4640,7 +4640,7 @@
 // another module after it or have more than one entity inside it.
 uint32_t None = std::numeric_limits::max();
 
-auto writeBaseIDOrNone = [&](uint32_t BaseID, bool ShouldWrite) {
+auto writeBaseIDOrNone = [&](auto BaseID, bool ShouldWrite) {
   assert(BaseID < std::numeric_limits::max() && "base id too high");
   if (ShouldWrite)
 LE.write(BaseID);
@@ -5027,8 +5027,8 @@
 }
 
 void ASTWriter::AddSourceLocation(SourceLocation Loc, RecordDataImpl &Record) {
-  uint32_t Raw = Loc.getRawEncoding();
-  Record.push_back((Raw << 1) | (Raw >> 31));
+  SourceLocation::UIntTy Raw = Loc.getRawEncoding();
+  Record.push_back((Raw << 1) | (Raw >> (8 * sizeof(Raw) - 1)));
 }
 
 void ASTWriter::AddSourceRange(SourceRange Range, RecordDataImpl &Record) {
Index: clang/lib/Serialization/ASTReader.cpp
===
--- clang/lib/Serialization/ASTReader.cpp
+++ clang/lib/Serialization/ASTReader.cpp
@@ -1482,7 +1482,7 @@
   }
 
   BitstreamCursor &SLocEntryCursor = F->SLocEntryCursor;
-  unsigned BaseOffset = F->SLocEntryBaseOffset;
+  SourceLocation::UIntTy BaseOffset = F->SLocEntryBaseOffset;
 
   ++NumSLocEntriesRead;
   Expected MaybeEntry = SLocEntryCursor.advance();
@@ -3409,7 +3409,7 @@
 case SOURCE_LOCATION_OFFSETS: {
   F.SLocEntryOffsets = (const uint32_t *)Blob.data();
   F.LocalNumSLocEntries = Record[0];
-  unsigned SLocSpaceSize = Record[1];
+  SourceLocation::UIntTy SLocSpaceSize = Record[1];
   F.SLocEntryOffsetsBase = Record[2] + F.SourceManagerBlockStartOffset;
   std::tie(F.SLocEntryBaseID, F.SLocEntryBaseOffset) =
   SourceMgr.AllocateLoadedSLocEntries(F.LocalNumSLocEntries,
@@ -3427,7 +3427,7 @@
   F.FirstLoc = SourceLocation::getFromRawEncoding(F.SLocEntryBaseOffset);
 
   // SLocEntryBaseOffset is lower than MaxLoadedOffset and decreasing.
-  assert((F.SLocEntryBaseOffset & (1U << 31U)) == 0);
+  assert((F.SLocEntryBaseOffset & SourceLocation::MacroIDBit) == 0);
   GlobalSLocOffsetMap.insert(
   std::make_pair(SourceManager::MaxLoadedOffset - F.SLocEntryBaseOffset
- SLocSpaceSize,&F));
@@ -3436,8 +3436,8 @@
   // Invalid stays invalid.
   F.SLocRemap.insertOrReplace(std::make_pair(0U, 0));
   // This module. Base was 2 when being compiled.
-  F.SLocRemap.insertOrReplace(std::make_pair(2U,
- 

[PATCH] D105881: [flang][driver] Switch to `BoolFOption` for boolean options

2021-07-20 Thread Andrzej Warzynski via Phabricator via cfe-commits
awarzynski updated this revision to Diff 360100.
awarzynski added a comment.

Switch from `BoolFOption` to `OptInFFlag`/`OptOutFFlag`

I've refactored `OptInFFlag`/`OptOutFFlag` a tiny bit and created 
specialisations for `clang -cc1` (`OptInCC1FFlag`/`OptOutCC1FFlag`). I have 
added some comments in Options.td to clarify the semantics of 
`OptInFFlag`/`OptOutFFlag`. Does this make sense to you?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D105881

Files:
  clang/include/clang/Driver/Options.td
  flang/lib/Frontend/CompilerInvocation.cpp
  flang/test/Driver/driver-help-hidden.f90
  flang/test/Driver/driver-help.f90

Index: flang/test/Driver/driver-help.f90
===
--- flang/test/Driver/driver-help.f90
+++ flang/test/Driver/driver-help.f90
@@ -40,7 +40,6 @@
 ! HELP-NEXT:Specify where to find the compiled intrinsic modules
 ! HELP-NEXT: -flarge-sizes  Use INTEGER(KIND=8) for the result type in size-related intrinsics
 ! HELP-NEXT: -flogical-abbreviations Enable logical abbreviations
-! HELP-NEXT: -fno-color-diagnostics Disable colors in diagnostics
 ! HELP-NEXT: -fopenacc  Enable OpenACC
 ! HELP-NEXT: -fopenmp   Parse OpenMP pragmas and generate parallel code.
 ! HELP-NEXT: -fxor-operator Enable .XOR. as a synonym of .NEQV.
@@ -68,6 +67,8 @@
 ! HELP-FC1-NEXT: -E Only run the preprocessor
 ! HELP-FC1-NEXT: -falternative-parameter-statement
 ! HELP-FC1-NEXT: Enable the old style PARAMETER statement
+! HELP-FC1-NEXT: -fanalyzed-objects-for-unparse
+! HELP-FC1-NEXT:Use the analyzed objects when unparsing
 ! HELP-FC1-NEXT: -fbackslashSpecify that backslash in string introduces an escape character
 ! HELP-FC1-NEXT: -fdebug-dump-all   Dump symbols and the parse tree after the semantic checks
 ! HELP-FC1-NEXT: -fdebug-dump-parse-tree-no-sema
Index: flang/test/Driver/driver-help-hidden.f90
===
--- flang/test/Driver/driver-help-hidden.f90
+++ flang/test/Driver/driver-help-hidden.f90
@@ -40,7 +40,6 @@
 ! CHECK-NEXT:Specify where to find the compiled intrinsic modules
 ! CHECK-NEXT: -flarge-sizes  Use INTEGER(KIND=8) for the result type in size-related intrinsics
 ! CHECK-NEXT: -flogical-abbreviations Enable logical abbreviations
-! CHECK-NEXT: -fno-color-diagnostics Disable colors in diagnostics
 ! CHECK-NEXT: -fopenacc  Enable OpenACC
 ! CHECK-NEXT: -fopenmp   Parse OpenMP pragmas and generate parallel code.
 ! CHECK-NEXT: -fxor-operator Enable .XOR. as a synonym of .NEQV.
Index: flang/lib/Frontend/CompilerInvocation.cpp
===
--- flang/lib/Frontend/CompilerInvocation.cpp
+++ flang/lib/Frontend/CompilerInvocation.cpp
@@ -277,33 +277,27 @@
 }
   }
 
-  if (const llvm::opt::Arg *arg =
-  args.getLastArg(clang::driver::options::OPT_fimplicit_none,
-  clang::driver::options::OPT_fno_implicit_none)) {
-opts.features_.Enable(
-Fortran::common::LanguageFeature::ImplicitNoneTypeAlways,
-arg->getOption().matches(clang::driver::options::OPT_fimplicit_none));
-  }
-  if (const llvm::opt::Arg *arg =
-  args.getLastArg(clang::driver::options::OPT_fbackslash,
-  clang::driver::options::OPT_fno_backslash)) {
-opts.features_.Enable(Fortran::common::LanguageFeature::BackslashEscapes,
-arg->getOption().matches(clang::driver::options::OPT_fbackslash));
-  }
-  if (const llvm::opt::Arg *arg =
-  args.getLastArg(clang::driver::options::OPT_flogical_abbreviations,
-  clang::driver::options::OPT_fno_logical_abbreviations)) {
-opts.features_.Enable(
-Fortran::common::LanguageFeature::LogicalAbbreviations,
-arg->getOption().matches(
-clang::driver::options::OPT_flogical_abbreviations));
-  }
-  if (const llvm::opt::Arg *arg =
-  args.getLastArg(clang::driver::options::OPT_fxor_operator,
-  clang::driver::options::OPT_fno_xor_operator)) {
-opts.features_.Enable(Fortran::common::LanguageFeature::XOROperator,
-arg->getOption().matches(clang::driver::options::OPT_fxor_operator));
-  }
+  // -f{no-}implicit-none
+  opts.features_.Enable(
+  Fortran::common::LanguageFeature::ImplicitNoneTypeAlways,
+  args.hasFlag(clang::driver::options::OPT_fimplicit_none,
+  clang::driver::options::OPT_fno_implicit_none, false));
+
+  // -f{no-}backslash
+  opts.features_.Enable(Fortran::common::LanguageFeature::BackslashEscapes,
+  args.hasFlag(clang::driver::options::OPT_fbackslash,
+  clang::driver::options::OPT_fno_backslash, false));
+
+  // -f{no-}logical-abbreviations
+  opts.features_.Enable(Fortran::common::LanguageF

[PATCH] D105498: [clang] Remove assumption about SourceLocation alignment.

2021-07-20 Thread Simon Tatham via Phabricator via cfe-commits
simon_tatham updated this revision to Diff 360101.
simon_tatham edited the summary of this revision.
simon_tatham added a comment.

Split up the allocations as suggested.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D105498

Files:
  clang/include/clang/AST/DeclObjC.h
  clang/lib/AST/DeclObjC.cpp

Index: clang/lib/AST/DeclObjC.cpp
===
--- clang/lib/AST/DeclObjC.cpp
+++ clang/lib/AST/DeclObjC.cpp
@@ -28,6 +28,7 @@
 #include "llvm/ADT/SmallVector.h"
 #include "llvm/Support/Casting.h"
 #include "llvm/Support/ErrorHandling.h"
+#include "llvm/Support/MathExtras.h"
 #include "llvm/Support/raw_ostream.h"
 #include 
 #include 
@@ -867,21 +868,21 @@
 }
 
 void ObjCMethodDecl::setParamsAndSelLocs(ASTContext &C,
- ArrayRef Params,
- ArrayRef SelLocs) {
-  ParamsAndSelLocs = nullptr;
-  NumParams = Params.size();
-  if (Params.empty() && SelLocs.empty())
-return;
-
-  static_assert(alignof(ParmVarDecl *) >= alignof(SourceLocation),
-"Alignment not sufficient for SourceLocation");
+ ArrayRef ParamsIn,
+ ArrayRef SelLocsIn) {
+  Params = nullptr;
+  NumParams = ParamsIn.size();
+  SelLocs = nullptr;
+
+  if (!ParamsIn.empty()) {
+Params = C.Allocate(ParamsIn.size());
+std::copy(ParamsIn.begin(), ParamsIn.end(), Params);
+  }
 
-  unsigned Size = sizeof(ParmVarDecl *) * NumParams +
-  sizeof(SourceLocation) * SelLocs.size();
-  ParamsAndSelLocs = C.Allocate(Size);
-  std::copy(Params.begin(), Params.end(), getParams());
-  std::copy(SelLocs.begin(), SelLocs.end(), getStoredSelLocs());
+  if (!SelLocsIn.empty()) {
+SelLocs = C.Allocate(SelLocsIn.size());
+std::copy(SelLocsIn.begin(), SelLocsIn.end(), SelLocs);
+  }
 }
 
 void ObjCMethodDecl::getSelectorLocs(
Index: clang/include/clang/AST/DeclObjC.h
===
--- clang/include/clang/AST/DeclObjC.h
+++ clang/include/clang/AST/DeclObjC.h
@@ -150,11 +150,13 @@
   /// Type source information for the return type.
   TypeSourceInfo *ReturnTInfo;
 
-  /// Array of ParmVarDecls for the formal parameters of this method
-  /// and optionally followed by selector locations.
-  void *ParamsAndSelLocs = nullptr;
+  /// Array of the formal parameters of this method.
+  ParmVarDecl **Params = nullptr;
   unsigned NumParams = 0;
 
+  /// Source locations for the selector identifiers.
+  SourceLocation *SelLocs = nullptr;
+
   /// List of attributes for this method declaration.
   SourceLocation DeclEndLoc; // the location of the ';' or '{'.
 
@@ -190,22 +192,20 @@
 return getSelLocsKind() != SelLoc_NonStandard;
   }
 
-  /// Get a pointer to the stored selector identifiers locations array.
-  /// No locations will be stored if HasStandardSelLocs is true.
-  SourceLocation *getStoredSelLocs() {
-return reinterpret_cast(getParams() + NumParams);
-  }
-  const SourceLocation *getStoredSelLocs() const {
-return reinterpret_cast(getParams() + NumParams);
+  size_t getStoredSelLocsOffset() const {
+return llvm::alignTo(sizeof(ParmVarDecl *) *
+  NumParams);
   }
 
   /// Get a pointer to the stored selector identifiers locations array.
   /// No locations will be stored if HasStandardSelLocs is true.
-  ParmVarDecl **getParams() {
-return reinterpret_cast(ParamsAndSelLocs);
-  }
+  SourceLocation *getStoredSelLocs() { return SelLocs; }
+  const SourceLocation *getStoredSelLocs() const { return SelLocs; }
+
+  /// Get a pointer to the parameter array.
+  ParmVarDecl **getParams() { return Params; }
   const ParmVarDecl *const *getParams() const {
-return reinterpret_cast(ParamsAndSelLocs);
+return const_cast(Params);
   }
 
   /// Get the number of stored selector identifiers locations.
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D105498: [clang] Remove assumption about SourceLocation alignment.

2021-07-20 Thread Simon Tatham via Phabricator via cfe-commits
simon_tatham updated this revision to Diff 360104.
simon_tatham added a comment.

... and removed an unused function from the previous version.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D105498

Files:
  clang/include/clang/AST/DeclObjC.h
  clang/lib/AST/DeclObjC.cpp


Index: clang/lib/AST/DeclObjC.cpp
===
--- clang/lib/AST/DeclObjC.cpp
+++ clang/lib/AST/DeclObjC.cpp
@@ -28,6 +28,7 @@
 #include "llvm/ADT/SmallVector.h"
 #include "llvm/Support/Casting.h"
 #include "llvm/Support/ErrorHandling.h"
+#include "llvm/Support/MathExtras.h"
 #include "llvm/Support/raw_ostream.h"
 #include 
 #include 
@@ -867,21 +868,21 @@
 }
 
 void ObjCMethodDecl::setParamsAndSelLocs(ASTContext &C,
- ArrayRef Params,
- ArrayRef SelLocs) {
-  ParamsAndSelLocs = nullptr;
-  NumParams = Params.size();
-  if (Params.empty() && SelLocs.empty())
-return;
-
-  static_assert(alignof(ParmVarDecl *) >= alignof(SourceLocation),
-"Alignment not sufficient for SourceLocation");
+ ArrayRef ParamsIn,
+ ArrayRef SelLocsIn) {
+  Params = nullptr;
+  NumParams = ParamsIn.size();
+  SelLocs = nullptr;
+
+  if (!ParamsIn.empty()) {
+Params = C.Allocate(ParamsIn.size());
+std::copy(ParamsIn.begin(), ParamsIn.end(), Params);
+  }
 
-  unsigned Size = sizeof(ParmVarDecl *) * NumParams +
-  sizeof(SourceLocation) * SelLocs.size();
-  ParamsAndSelLocs = C.Allocate(Size);
-  std::copy(Params.begin(), Params.end(), getParams());
-  std::copy(SelLocs.begin(), SelLocs.end(), getStoredSelLocs());
+  if (!SelLocsIn.empty()) {
+SelLocs = C.Allocate(SelLocsIn.size());
+std::copy(SelLocsIn.begin(), SelLocsIn.end(), SelLocs);
+  }
 }
 
 void ObjCMethodDecl::getSelectorLocs(
Index: clang/include/clang/AST/DeclObjC.h
===
--- clang/include/clang/AST/DeclObjC.h
+++ clang/include/clang/AST/DeclObjC.h
@@ -150,11 +150,13 @@
   /// Type source information for the return type.
   TypeSourceInfo *ReturnTInfo;
 
-  /// Array of ParmVarDecls for the formal parameters of this method
-  /// and optionally followed by selector locations.
-  void *ParamsAndSelLocs = nullptr;
+  /// Array of the formal parameters of this method.
+  ParmVarDecl **Params = nullptr;
   unsigned NumParams = 0;
 
+  /// Source locations for the selector identifiers.
+  SourceLocation *SelLocs = nullptr;
+
   /// List of attributes for this method declaration.
   SourceLocation DeclEndLoc; // the location of the ';' or '{'.
 
@@ -192,20 +194,13 @@
 
   /// Get a pointer to the stored selector identifiers locations array.
   /// No locations will be stored if HasStandardSelLocs is true.
-  SourceLocation *getStoredSelLocs() {
-return reinterpret_cast(getParams() + NumParams);
-  }
-  const SourceLocation *getStoredSelLocs() const {
-return reinterpret_cast(getParams() + NumParams);
-  }
+  SourceLocation *getStoredSelLocs() { return SelLocs; }
+  const SourceLocation *getStoredSelLocs() const { return SelLocs; }
 
-  /// Get a pointer to the stored selector identifiers locations array.
-  /// No locations will be stored if HasStandardSelLocs is true.
-  ParmVarDecl **getParams() {
-return reinterpret_cast(ParamsAndSelLocs);
-  }
+  /// Get a pointer to the parameter array.
+  ParmVarDecl **getParams() { return Params; }
   const ParmVarDecl *const *getParams() const {
-return reinterpret_cast(ParamsAndSelLocs);
+return const_cast(Params);
   }
 
   /// Get the number of stored selector identifiers locations.


Index: clang/lib/AST/DeclObjC.cpp
===
--- clang/lib/AST/DeclObjC.cpp
+++ clang/lib/AST/DeclObjC.cpp
@@ -28,6 +28,7 @@
 #include "llvm/ADT/SmallVector.h"
 #include "llvm/Support/Casting.h"
 #include "llvm/Support/ErrorHandling.h"
+#include "llvm/Support/MathExtras.h"
 #include "llvm/Support/raw_ostream.h"
 #include 
 #include 
@@ -867,21 +868,21 @@
 }
 
 void ObjCMethodDecl::setParamsAndSelLocs(ASTContext &C,
- ArrayRef Params,
- ArrayRef SelLocs) {
-  ParamsAndSelLocs = nullptr;
-  NumParams = Params.size();
-  if (Params.empty() && SelLocs.empty())
-return;
-
-  static_assert(alignof(ParmVarDecl *) >= alignof(SourceLocation),
-"Alignment not sufficient for SourceLocation");
+ ArrayRef ParamsIn,
+ ArrayRef SelLocsIn) {
+  Params = nullptr;
+  NumParams = ParamsIn.size();
+  SelLocs = nullptr;
+
+  if (!ParamsIn.empty()) {
+Params = C.Allocate(ParamsIn.size());
+std::copy(ParamsIn.begin(), ParamsIn.end(), Params

[PATCH] D106262: [clang][analyzer] Use generic note tag in alpha.unix.Stream .

2021-07-20 Thread Balázs Kéri via Phabricator via cfe-commits
balazske added inline comments.



Comment at: clang/lib/StaticAnalyzer/Checkers/StreamChecker.cpp:380-391
+if (BT == &BT_UseAfterClose)
+  Message = "Stream closed here";
+else if (BT == &BT_UseAfterOpenFailed)
+  Message = "Assuming opening the stream fails here";
+else if (BT == &BT_IndeterminatePosition)
+  Message = "Assuming this stream operation fails";
+else if (BT == &BT_StreamEof)

Szelethus wrote:
> I have ambivalent feelings on this. I see what you are shooting for: display 
> a specific `NoteTag` only for a specific `BugType`, though I wonder whether 
> whether some of these notes would be nice for more than one. The only test 
> case that changed seems to support my theory, or at least I like it better.
I will update the patch so that it supports multiple bug types in one note and 
bug type specific message. This will be done together with the adding of the 
new notes so there will be test for the new functionality.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D106262

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


[PATCH] D105498: [clang] Remove assumption about SourceLocation alignment.

2021-07-20 Thread Simon Tatham via Phabricator via cfe-commits
simon_tatham added inline comments.



Comment at: clang/lib/AST/DeclObjC.cpp:31
 #include "llvm/Support/ErrorHandling.h"
+#include "llvm/Support/MathExtras.h"
 #include "llvm/Support/raw_ostream.h"

Oops, before anyone else points it out, this `#include` is also now unnecessary.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D105498

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


[PATCH] D105498: [clang] Remove assumption about SourceLocation alignment.

2021-07-20 Thread Tomas Matheson via Phabricator via cfe-commits
tmatheson accepted this revision.
tmatheson added a subscriber: efriedma.
tmatheson added a comment.
This revision is now accepted and ready to land.

LGTM, but it would be good to have someone else comment on the increased number 
of allocations (maybe @rsmith or @efriedma?)




Comment at: clang/include/clang/AST/DeclObjC.h:208
   const ParmVarDecl *const *getParams() const {
-return reinterpret_cast(ParamsAndSelLocs);
+return const_cast(Params);
   }

I don't think you need the `const_cast`


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D105498

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


[PATCH] D105194: [PowerPC] Add PowerPC cmpb builtin and emit target indepedent code for XL compatibility

2021-07-20 Thread Victor Huang via Phabricator via cfe-commits
NeHuang updated this revision to Diff 360109.
NeHuang added a comment.

clang-format


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D105194

Files:
  clang/include/clang/Basic/BuiltinsPPC.def
  clang/lib/Basic/Targets/PPC.cpp
  clang/lib/CodeGen/CGBuiltin.cpp
  clang/test/CodeGen/builtins-ppc-xlcompat-compare.c
  llvm/include/llvm/IR/IntrinsicsPowerPC.td
  llvm/lib/Target/PowerPC/PPCInstr64Bit.td
  llvm/lib/Target/PowerPC/PPCInstrInfo.td
  llvm/test/CodeGen/PowerPC/builtins-ppc-xlcompat-cmpb-32.ll
  llvm/test/CodeGen/PowerPC/builtins-ppc-xlcompat-cmpb-64.ll

Index: llvm/test/CodeGen/PowerPC/builtins-ppc-xlcompat-cmpb-64.ll
===
--- /dev/null
+++ llvm/test/CodeGen/PowerPC/builtins-ppc-xlcompat-cmpb-64.ll
@@ -0,0 +1,16 @@
+; NOTE: Assertions have been autogenerated by utils/update_llc_test_checks.py
+; RUN: llc -verify-machineinstrs -mtriple=powerpc64-unknown-unknown -mcpu=pwr7 < %s | FileCheck %s
+; RUN: llc -verify-machineinstrs -mtriple=powerpc64le-unknown-unknown -mcpu=pwr8 < %s | FileCheck %s
+; RUN: llc -verify-machineinstrs -mtriple=powerpc64-unknown-aix -mcpu=pwr7 < %s | FileCheck %s
+
+define i64 @test_cmpb(i64 %a, i64 %b) {
+; CHECK-LABEL: test_cmpb:
+; CHECK:   # %bb.0: # %entry
+; CHECK-NEXT:cmpb 3, 3, 4
+; CHECK-NEXT:blr
+entry:
+  %cmpb = tail call i64 @llvm.ppc.cmpb.i64.i64.i64(i64 %a, i64 %b)
+  ret i64 %cmpb
+}
+
+declare i64 @llvm.ppc.cmpb.i64.i64.i64(i64, i64)
Index: llvm/test/CodeGen/PowerPC/builtins-ppc-xlcompat-cmpb-32.ll
===
--- /dev/null
+++ llvm/test/CodeGen/PowerPC/builtins-ppc-xlcompat-cmpb-32.ll
@@ -0,0 +1,27 @@
+; NOTE: Assertions have been autogenerated by utils/update_llc_test_checks.py
+; RUN: llc -verify-machineinstrs -mtriple=powerpc-unknown-aix \
+; RUN:   --ppc-asm-full-reg-names -mcpu=pwr7 < %s | FileCheck %s
+
+define i64 @test_cmpb(i64 %a, i64 %b) {
+; CHECK-LABEL: test_cmpb:
+; CHECK:   # %bb.0: # %entry
+; CHECK-NEXT:cmpb 4, 4, 6
+; CHECK-NEXT:cmpb 3, 3, 5
+; CHECK-NEXT:blr
+entry:
+  %0 = trunc i64 %a to i32
+  %1 = trunc i64 %b to i32
+  %2 = lshr i64 %a, 32
+  %3 = trunc i64 %2 to i32
+  %4 = lshr i64 %b, 32
+  %5 = trunc i64 %4 to i32
+  %cmpb = tail call i32 @llvm.ppc.cmpb.i32.i32.i32(i32 %0, i32 %1)
+  %6 = zext i32 %cmpb to i64
+  %cmpb1 = tail call i32 @llvm.ppc.cmpb.i32.i32.i32(i32 %3, i32 %5)
+  %7 = zext i32 %cmpb1 to i64
+  %8 = shl nuw i64 %7, 32
+  %9 = or i64 %8, %6
+  ret i64 %9
+}
+
+declare i32 @llvm.ppc.cmpb.i32.i32.i32(i32, i32)
Index: llvm/lib/Target/PowerPC/PPCInstrInfo.td
===
--- llvm/lib/Target/PowerPC/PPCInstrInfo.td
+++ llvm/lib/Target/PowerPC/PPCInstrInfo.td
@@ -5291,6 +5291,8 @@
   (i32 (MULHW $a, $b))>;
 def : Pat<(i32 (int_ppc_mulhwu gprc:$a, gprc:$b)),
   (i32 (MULHWU $a, $b))>;
+def : Pat<(i32 (int_ppc_cmpb gprc:$a, gprc:$b)),
+  (i32 (CMPB $a, $b))>;
 
 def : Pat<(int_ppc_load2r ForceXForm:$ptr),
   (LHBRX ForceXForm:$ptr)>;
Index: llvm/lib/Target/PowerPC/PPCInstr64Bit.td
===
--- llvm/lib/Target/PowerPC/PPCInstr64Bit.td
+++ llvm/lib/Target/PowerPC/PPCInstr64Bit.td
@@ -1796,6 +1796,9 @@
   (STDBRX g8rc:$a, ForceXForm:$ptr)>;
 }
 
+def : Pat<(i64 (int_ppc_cmpb g8rc:$a, g8rc:$b)),
+  (i64 (CMPB8 $a, $b))>;
+
 let Predicates = [IsISA3_0] in {
 // DARN (deliver random number)
 // L=0 for 32-bit, L=1 for conditioned random, L=2 for raw random
Index: llvm/include/llvm/IR/IntrinsicsPowerPC.td
===
--- llvm/include/llvm/IR/IntrinsicsPowerPC.td
+++ llvm/include/llvm/IR/IntrinsicsPowerPC.td
@@ -1576,6 +1576,9 @@
   def int_ppc_setb
   : GCCBuiltin<"__builtin_ppc_setb">,
 Intrinsic<[llvm_i64_ty], [llvm_i64_ty, llvm_i64_ty], [IntrNoMem]>;
+  def int_ppc_cmpb
+  : Intrinsic<[llvm_anyint_ty], [llvm_anyint_ty, llvm_anyint_ty],
+  [IntrNoMem]>;
   // multiply
   def int_ppc_mulhd
   : GCCBuiltin<"__builtin_ppc_mulhd">,
Index: clang/test/CodeGen/builtins-ppc-xlcompat-compare.c
===
--- /dev/null
+++ clang/test/CodeGen/builtins-ppc-xlcompat-compare.c
@@ -0,0 +1,44 @@
+// REQUIRES: powerpc-registered-target
+// RUN: %clang_cc1 -triple powerpc64-unknown-unknown \
+// RUN:   -emit-llvm %s -o - -target-cpu pwr7 | FileCheck %s --check-prefix=CHECK-64B
+// RUN: %clang_cc1 -triple powerpc64le-unknown-unknown \
+// RUN:   -emit-llvm %s -o - -target-cpu pwr8 | FileCheck %s --check-prefix=CHECK-64B
+// RUN: %clang_cc1 -triple powerpc-unknown-aix \
+// RUN:   -emit-llvm %s -o - -target-cpu pwr7 | FileCheck %s --check-prefix=CHECK-32B
+// RUN: %clang_cc1 -triple powerpc64-unknown-aix \
+// RUN:   -

[PATCH] D103986: [PowerPC] Floating Point Builtins for XL Compat.

2021-07-20 Thread Lei Huang via Phabricator via cfe-commits
lei added a comment.

please rebase to ToT


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D103986

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


[clang] 02cd937 - [PowerPC][Builtins] Added a number of builtins for compatibility with XL.

2021-07-20 Thread Stefan Pintilie via cfe-commits

Author: Stefan Pintilie
Date: 2021-07-20T08:57:55-05:00
New Revision: 02cd937945f8f044aa52b7967531be2b77b27431

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

LOG: [PowerPC][Builtins] Added a number of builtins for compatibility with XL.

Added a number of different builtins that exist in the XL compiler. Most of
these builtins already exist in clang under a different name.

Reviewed By: nemanjai, #powerpc

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

Added: 
clang/test/CodeGen/builtins-ppc-xlcompat-cipher.c
clang/test/CodeGen/builtins-ppc-xlcompat-cmplx.c
clang/test/CodeGen/builtins-ppc-xlcompat-darn.c
clang/test/CodeGen/builtins-ppc-xlcompat-expect.c
clang/test/CodeGen/builtins-ppc-xlcompat-macros.c

Modified: 
clang/include/clang/Basic/BuiltinsPPC.def
clang/lib/Basic/Targets/PPC.cpp
clang/lib/CodeGen/CGBuiltin.cpp
clang/lib/Sema/SemaChecking.cpp
clang/test/CodeGen/builtins-ppc-xlcompat-error.c
clang/test/CodeGen/builtins-ppc-xlcompat-popcnt.c
clang/test/CodeGen/builtins-ppc-xlcompat-rotate.c

Removed: 




diff  --git a/clang/include/clang/Basic/BuiltinsPPC.def 
b/clang/include/clang/Basic/BuiltinsPPC.def
index a3665e2a7754b..07e000d4f710d 100644
--- a/clang/include/clang/Basic/BuiltinsPPC.def
+++ b/clang/include/clang/Basic/BuiltinsPPC.def
@@ -75,6 +75,8 @@ BUILTIN(__builtin_ppc_fctudz, "dd", "")
 BUILTIN(__builtin_ppc_fctuwz, "dd", "")
 BUILTIN(__builtin_ppc_swdiv_nochk, "ddd", "")
 BUILTIN(__builtin_ppc_swdivs_nochk, "fff", "")
+BUILTIN(__builtin_ppc_alignx, "vIivC*", "nc")
+BUILTIN(__builtin_ppc_rdlam, "UWiUWiUWiUWIi", "nc")
 // Compare
 BUILTIN(__builtin_ppc_cmpeqb, "LLiLLiLLi", "")
 BUILTIN(__builtin_ppc_cmprb, "iCIiii", "")

diff  --git a/clang/lib/Basic/Targets/PPC.cpp b/clang/lib/Basic/Targets/PPC.cpp
index e22cbd8a13f7a..b713fce8906c1 100644
--- a/clang/lib/Basic/Targets/PPC.cpp
+++ b/clang/lib/Basic/Targets/PPC.cpp
@@ -168,6 +168,46 @@ static void defineXLCompatMacros(MacroBuilder &Builder) {
   Builder.defineMacro("__fres", "__builtin_ppc_fres");
   Builder.defineMacro("__swdiv_nochk", "__builtin_ppc_swdiv_nochk");
   Builder.defineMacro("__swdivs_nochk", "__builtin_ppc_swdivs_nochk");
+  Builder.defineMacro("__alloca", "__builtin_alloca");
+  Builder.defineMacro("__vcipher", "__builtin_altivec_crypto_vcipher");
+  Builder.defineMacro("__vcipherlast", "__builtin_altivec_crypto_vcipherlast");
+  Builder.defineMacro("__vncipher", "__builtin_altivec_crypto_vncipher");
+  Builder.defineMacro("__vncipherlast",
+  "__builtin_altivec_crypto_vncipherlast");
+  Builder.defineMacro("__vpermxor", "__builtin_altivec_crypto_vpermxor");
+  Builder.defineMacro("__vpmsumb", "__builtin_altivec_crypto_vpmsumb");
+  Builder.defineMacro("__vpmsumd", "__builtin_altivec_crypto_vpmsumd");
+  Builder.defineMacro("__vpmsumh", "__builtin_altivec_crypto_vpmsumh");
+  Builder.defineMacro("__vpmsumw", "__builtin_altivec_crypto_vpmsumw");
+  Builder.defineMacro("__divde", "__builtin_divde");
+  Builder.defineMacro("__divwe", "__builtin_divwe");
+  Builder.defineMacro("__divdeu", "__builtin_divdeu");
+  Builder.defineMacro("__divweu", "__builtin_divweu");
+  Builder.defineMacro("__alignx", "__builtin_ppc_alignx");
+  Builder.defineMacro("__bcopy", "bcopy");
+  Builder.defineMacro("__bpermd", "__builtin_bpermd");
+  Builder.defineMacro("__cntlz4", "__builtin_clz");
+  Builder.defineMacro("__cntlz8", "__builtin_clzll");
+  Builder.defineMacro("__cmplx", "__builtin_complex");
+  Builder.defineMacro("__cmplxf", "__builtin_complex");
+  Builder.defineMacro("__cnttz4", "__builtin_ctz");
+  Builder.defineMacro("__cnttz8", "__builtin_ctzll");
+  Builder.defineMacro("__darn", "__builtin_darn");
+  Builder.defineMacro("__darn_32", "__builtin_darn_32");
+  Builder.defineMacro("__darn_raw", "__builtin_darn_raw");
+  Builder.defineMacro("__dcbf", "__builtin_dcbf");
+  Builder.defineMacro("__fmadd", "__builtin_fma");
+  Builder.defineMacro("__fmadds", "__builtin_fmaf");
+  Builder.defineMacro("__labs", "__builtin_labs");
+  Builder.defineMacro("__llabs", "__builtin_llabs");
+  Builder.defineMacro("__popcnt4", "__builtin_popcount");
+  Builder.defineMacro("__popcnt8", "__builtin_popcountll");
+  Builder.defineMacro("__readflm", "__builtin_readflm");
+  Builder.defineMacro("__rotatel4", "__builtin_rotateleft32");
+  Builder.defineMacro("__rotatel8", "__builtin_rotateleft64");
+  Builder.defineMacro("__rdlam", "__builtin_ppc_rdlam");
+  Builder.defineMacro("__setflm", "__builtin_setflm");
+  Builder.defineMacro("__setrnd", "__builtin_setrnd");
 }
 
 /// PPCTargetInfo::getTargetDefines - Return a set of the PowerPC-specific

diff  --git a/clang/lib/CodeGen/CGBuiltin.cpp b/clang/lib/CodeGen/CGBuiltin.cpp
index 89e22ab75d4c3..d9958fe527cbd 

[PATCH] D104386: [PowerPC][Builtins] Added a number of builtins for compatibility with XL.

2021-07-20 Thread Stefan Pintilie via Phabricator via cfe-commits
This revision was landed with ongoing or failed builds.
This revision was automatically updated to reflect the committed changes.
Closed by commit rG02cd937945f8: [PowerPC][Builtins] Added a number of builtins 
for compatibility with XL. (authored by stefanp).

Changed prior to commit:
  https://reviews.llvm.org/D104386?vs=359459&id=360111#toc

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D104386

Files:
  clang/include/clang/Basic/BuiltinsPPC.def
  clang/lib/Basic/Targets/PPC.cpp
  clang/lib/CodeGen/CGBuiltin.cpp
  clang/lib/Sema/SemaChecking.cpp
  clang/test/CodeGen/builtins-ppc-xlcompat-cipher.c
  clang/test/CodeGen/builtins-ppc-xlcompat-cmplx.c
  clang/test/CodeGen/builtins-ppc-xlcompat-darn.c
  clang/test/CodeGen/builtins-ppc-xlcompat-error.c
  clang/test/CodeGen/builtins-ppc-xlcompat-expect.c
  clang/test/CodeGen/builtins-ppc-xlcompat-macros.c
  clang/test/CodeGen/builtins-ppc-xlcompat-popcnt.c
  clang/test/CodeGen/builtins-ppc-xlcompat-rotate.c

Index: clang/test/CodeGen/builtins-ppc-xlcompat-rotate.c
===
--- clang/test/CodeGen/builtins-ppc-xlcompat-rotate.c
+++ clang/test/CodeGen/builtins-ppc-xlcompat-rotate.c
@@ -55,3 +55,30 @@
   /*shift = 31, mask = 0x1FF = 511*/
   unsigned int res = __builtin_ppc_rlwnm(ui, 31, 0x1FF);
 }
+
+// CHECK-LABEL: @testrotatel4(
+// CHECK: [[TMP:%.*]] = call i32 @llvm.fshl.i32(i32 {{%.*}}, i32 {{%.*}}, i32 {{%.*}})
+// CHECK-NEXT:ret i32 [[TMP]]
+//
+unsigned int testrotatel4(unsigned int rs, unsigned int shift) {
+  return __rotatel4(rs, shift);
+}
+
+// CHECK-LABEL: @testrotatel8(
+// CHECK: [[TMP:%.*]] = call i64 @llvm.fshl.i64(i64 {{%.*}}, i64 {{%.*}}, i64 {{%.*}})
+// CHECK-NEXT:ret i64 [[TMP]]
+//
+unsigned long long testrotatel8(unsigned long long rs, unsigned long long shift) {
+  return __rotatel8(rs, shift);
+}
+
+// CHECK-LABEL: @testrdlam(
+// CHECK: [[TMP0:%.*]] = call i64 @llvm.fshl.i64(i64 {{%.*}}, i64 {{%.*}}, i64 {{%.*}})
+// CHECK-NEXT:[[TMP1:%.*]] = and i64 [[TMP0]], 7
+// CHECK-NEXT:ret i64 [[TMP1]]
+//
+unsigned long long testrdlam(unsigned long long rs, unsigned int shift) {
+  // The third parameter is a mask that must be a constant that represents a
+  // contiguous bit field.
+  return __rdlam(rs, shift, 7);
+}
Index: clang/test/CodeGen/builtins-ppc-xlcompat-popcnt.c
===
--- clang/test/CodeGen/builtins-ppc-xlcompat-popcnt.c
+++ clang/test/CodeGen/builtins-ppc-xlcompat-popcnt.c
@@ -1,4 +1,4 @@
-// REQUIRES: powerpc-registered-target.
+// REQUIRES: powerpc-registered-target
 // RUN: %clang_cc1 -triple powerpc64-unknown-unknown \
 // RUN:   -emit-llvm %s -o - -target-cpu pwr7 | FileCheck %s
 // RUN: %clang_cc1 -triple powerpc64le-unknown-unknown \
@@ -12,9 +12,7 @@
 extern unsigned long long ull;
 
 // CHECK-LABEL: @test_builtin_ppc_poppar4(
-// CHECK: [[TMP0:%.*]] = load i32, i32* @ui, align 4
-// CHECK-NEXT:[[TMP1:%.*]] = load i32, i32* @ui, align 4
-// CHECK-NEXT:[[TMP2:%.*]] = call i32 @llvm.ctpop.i32(i32 [[TMP1]])
+// CHECK: [[TMP2:%.*]] = call i32 @llvm.ctpop.i32(i32 {{.*}})
 // CHECK-NEXT:[[TMP3:%.*]] = and i32 [[TMP2]], 1
 // CHECK-NEXT:ret i32 [[TMP3]]
 //
@@ -23,9 +21,7 @@
 }
 
 // CHECK-LABEL: @test_builtin_ppc_poppar8(
-// CHECK: [[TMP0:%.*]] = load i64, i64* @ull, align 8
-// CHECK-NEXT:[[TMP1:%.*]] = load i64, i64* @ull, align 8
-// CHECK-NEXT:[[TMP2:%.*]] = call i64 @llvm.ctpop.i64(i64 [[TMP1]])
+// CHECK: [[TMP2:%.*]] = call i64 @llvm.ctpop.i64(i64 {{.*}})
 // CHECK-NEXT:[[TMP3:%.*]] = and i64 [[TMP2]], 1
 // CHECK-NEXT:[[CAST:%.*]] = trunc i64 [[TMP3]] to i32
 // CHECK-NEXT:ret i32 [[CAST]]
@@ -33,3 +29,54 @@
 int test_builtin_ppc_poppar8() {
  return __builtin_ppc_poppar8(ull);
 }
+
+// CHECK-LABEL: @testcntlz4(
+// CHECK: [[TMP:%.*]] = call i32 @llvm.ctlz.i32(i32 {{%.*}}, i1 false)
+// CHECK-NEXT:ret i32 [[TMP]]
+//
+unsigned int testcntlz4(unsigned int value) {
+  return __cntlz4(value);
+}
+
+// CHECK-LABEL: @testcntlz8(
+// CHECK: [[TMP:%.*]] = call i64 @llvm.ctlz.i64(i64 {{%.*}}, i1 false)
+// CHECK-NEXT:[[CAST:%.*]] = trunc i64 [[TMP]] to i32
+// CHECK-NEXT:ret i32 [[CAST]]
+//
+unsigned int testcntlz8(unsigned long long value) {
+  return __cntlz8(value);
+}
+
+// CHECK-LABEL: @testcnttz4(
+// CHECK: [[TMP:%.*]] = call i32 @llvm.cttz.i32(i32 {{%.*}}, i1 false)
+// CHECK-NEXT:ret i32 [[TMP]]
+//
+unsigned int testcnttz4(unsigned int value) {
+  return __cnttz4(value);
+}
+
+// CHECK-LABEL: @testcnttz8(
+// CHECK: [[TMP:%.*]] = call i64 @llvm.cttz.i64(i64 {{%.*}}, i1 false)
+// CHECK-NEXT:[[CAST:%.*]] = trunc i64 [[TMP]] to i32
+// CHECK-NEXT:ret i32 [[CAST]]
+//
+unsigned int testcnttz8(unsigned long long value) {
+  return __cnttz8(value);
+}
+
+// CH

[PATCH] D105498: [clang] Remove assumption about SourceLocation alignment.

2021-07-20 Thread Simon Tatham via Phabricator via cfe-commits
simon_tatham added inline comments.



Comment at: clang/include/clang/AST/DeclObjC.h:208
   const ParmVarDecl *const *getParams() const {
-return reinterpret_cast(ParamsAndSelLocs);
+return const_cast(Params);
   }

tmatheson wrote:
> I don't think you need the `const_cast`
I put it in because I got a compile error otherwise!

It's because of the double indirection. You don't need a cast to turn a `Foo *` 
into a `const Foo *`. But here, we're turning a `Foo *` into a `const Bar *`, 
where `Foo` and `Bar` are pointer types to things of different constness.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D105498

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


[PATCH] D106296: [analyzer] Fix for faulty namespace test in SmartPtrModelling

2021-07-20 Thread Gábor Horváth via Phabricator via cfe-commits
xazax.hun accepted this revision.
xazax.hun 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/D106296/new/

https://reviews.llvm.org/D106296

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


[PATCH] D105926: [PowerPC] Extra test case for LDARX

2021-07-20 Thread Albion Fung via Phabricator via cfe-commits
Conanap updated this revision to Diff 360114.
Conanap added a comment.
Herald added a project: LLVM.
Herald added a subscriber: llvm-commits.

Moved to llvm/test/CodeGen/PowerPC


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D105926

Files:
  llvm/test/CodeGen/PowerPC/builtins-ppc-xlcompat-check-ldarx-opt.ll


Index: llvm/test/CodeGen/PowerPC/builtins-ppc-xlcompat-check-ldarx-opt.ll
===
--- /dev/null
+++ llvm/test/CodeGen/PowerPC/builtins-ppc-xlcompat-check-ldarx-opt.ll
@@ -0,0 +1,88 @@
+; NOTE: Assertions have been autogenerated by utils/update_llc_test_checks.py
+; RUN: llc -verify-machineinstrs -mtriple=powerpc64le-unknown-linux-gnu \
+; RUN:   -mcpu=pwr8 < %s | FileCheck %s --check-prefix=CHECK
+; RUN: llc -verify-machineinstrs -mtriple=powerpc64-unknown-linux-gnu \
+; RUN:   -mcpu=pwr8 < %s | FileCheck %s --check-prefix=CHECK
+; RUN: llc -verify-machineinstrs -mtriple=powerpc64-unknown-aix \
+; RUN:   -mcpu=pwr8 < %s | FileCheck %s --check-prefix=CHECK-AIX
+
+; Function Attrs: nounwind uwtable
+define dso_local signext i32 @main() local_unnamed_addr {
+; CHECK-LABEL: main:
+; CHECK:   # %bb.0: # %entry
+; CHECK-NEXT:li 3, -1
+; CHECK-NEXT:li 4, 0
+; CHECK-NEXT:std 3, -8(1)
+; CHECK-NEXT:addi 3, 1, -8
+; CHECK-NEXT:.p2align 5
+; CHECK-NEXT:  .LBB0_1: # %do.body
+; CHECK-NEXT:#
+; CHECK-NEXT:#APP
+; CHECK-NEXT:ldarx 5, 0, 3
+; CHECK-NEXT:#NO_APP
+; CHECK-NEXT:stdcx. 4, 0, 3
+; CHECK-NEXT:mfocrf 5, 128
+; CHECK-NEXT:srwi 5, 5, 28
+; CHECK-NEXT:cmplwi 5, 0
+; CHECK-NEXT:beq 0, .LBB0_1
+; CHECK-NEXT:  # %bb.2: # %do.end
+; CHECK-NEXT:ld 3, -8(1)
+; CHECK-NEXT:li 4, 55
+; CHECK-NEXT:cmpldi 3, 0
+; CHECK-NEXT:li 3, 66
+; CHECK-NEXT:iseleq 3, 4, 3
+; CHECK-NEXT:blr
+;
+; CHECK-AIX-LABEL: main:
+; CHECK-AIX:   # %bb.0: # %entry
+; CHECK-AIX-NEXT:li 3, -1
+; CHECK-AIX-NEXT:li 4, 0
+; CHECK-AIX-NEXT:std 3, -8(1)
+; CHECK-AIX-NEXT:addi 3, 1, -8
+; CHECK-AIX-NEXT:.align 5
+; CHECK-AIX-NEXT:  L..BB0_1: # %do.body
+; CHECK-AIX-NEXT:#
+; CHECK-AIX-NEXT:#APP
+; CHECK-AIX-NEXT:ldarx 5, 0, 3
+; CHECK-AIX-NEXT:#NO_APP
+; CHECK-AIX-NEXT:stdcx. 4, 0, 3
+; CHECK-AIX-NEXT:mfocrf 5, 128
+; CHECK-AIX-NEXT:srwi 5, 5, 28
+; CHECK-AIX-NEXT:cmplwi 5, 0
+; CHECK-AIX-NEXT:beq 0, L..BB0_1
+; CHECK-AIX-NEXT:  # %bb.2: # %do.end
+; CHECK-AIX-NEXT:ld 3, -8(1)
+; CHECK-AIX-NEXT:li 4, 55
+; CHECK-AIX-NEXT:cmpldi 3, 0
+; CHECK-AIX-NEXT:li 3, 66
+; CHECK-AIX-NEXT:iseleq 3, 4, 3
+; CHECK-AIX-NEXT:blr
+entry:
+  %x64 = alloca i64, align 8
+  %0 = bitcast i64* %x64 to i8*
+  call void @llvm.lifetime.start.p0i8(i64 8, i8* nonnull %0)
+  store i64 -1, i64* %x64, align 8
+  br label %do.body
+
+do.body:  ; preds = %do.body, %entry
+  %1 = call i64 asm sideeffect "ldarx $0, ${1:y}", "=r,*Z,~{memory}"(i64* 
nonnull %x64)
+  %2 = call i32 @llvm.ppc.stdcx(i8* nonnull %0, i64 0)
+  %tobool.not = icmp eq i32 %2, 0
+  br i1 %tobool.not, label %do.body, label %do.end
+
+do.end:   ; preds = %do.body
+  %3 = load i64, i64* %x64, align 8
+  %cmp = icmp eq i64 %3, 0
+  %. = select i1 %cmp, i32 55, i32 66
+  call void @llvm.lifetime.end.p0i8(i64 8, i8* nonnull %0)
+  ret i32 %.
+}
+
+; Function Attrs: argmemonly mustprogress nofree nosync nounwind willreturn
+declare void @llvm.lifetime.start.p0i8(i64 immarg, i8* nocapture)
+
+; Function Attrs: nounwind writeonly
+declare i32 @llvm.ppc.stdcx(i8*, i64)
+
+; Function Attrs: argmemonly mustprogress nofree nosync nounwind willreturn
+declare void @llvm.lifetime.end.p0i8(i64 immarg, i8* nocapture)


Index: llvm/test/CodeGen/PowerPC/builtins-ppc-xlcompat-check-ldarx-opt.ll
===
--- /dev/null
+++ llvm/test/CodeGen/PowerPC/builtins-ppc-xlcompat-check-ldarx-opt.ll
@@ -0,0 +1,88 @@
+; NOTE: Assertions have been autogenerated by utils/update_llc_test_checks.py
+; RUN: llc -verify-machineinstrs -mtriple=powerpc64le-unknown-linux-gnu \
+; RUN:   -mcpu=pwr8 < %s | FileCheck %s --check-prefix=CHECK
+; RUN: llc -verify-machineinstrs -mtriple=powerpc64-unknown-linux-gnu \
+; RUN:   -mcpu=pwr8 < %s | FileCheck %s --check-prefix=CHECK
+; RUN: llc -verify-machineinstrs -mtriple=powerpc64-unknown-aix \
+; RUN:   -mcpu=pwr8 < %s | FileCheck %s --check-prefix=CHECK-AIX
+
+; Function Attrs: nounwind uwtable
+define dso_local signext i32 @main() local_unnamed_addr {
+; CHECK-LABEL: main:
+; CHECK:   # %bb.0: # %entry
+; CHECK-NEXT:li 3, -1
+; CHECK-NEXT:li 4, 0
+; CHECK-NEXT:std 3, -8(1)
+; CHECK-NEXT:addi 3, 1, -8
+; CHECK-NEXT:.p2align 5
+; CHECK-NEXT:  .LBB0_1: # %do.body
+; CHECK-NEXT:#
+; CHECK-NEXT:#APP
+; CHECK-NEXT:ldarx 5, 0, 3
+; CHECK-

[PATCH] D106296: [analyzer] Fix for faulty namespace test in SmartPtrModelling

2021-07-20 Thread Gábor Horváth via Phabricator via cfe-commits
xazax.hun added inline comments.



Comment at: clang/lib/StaticAnalyzer/Checkers/SmartPtrModeling.cpp:291
   // we can try this function
-  if (Call.getNumArgs() == 2 &&
-  Call.getDecl()->getDeclContext()->isStdNamespace())
-if (smartptr::isStdSmartPtr(Call.getArgExpr(0)) ||
-smartptr::isStdSmartPtr(Call.getArgExpr(1)))
-  if (handleComparisionOp(Call, C))
-return true;
-
-  if (isStdOstreamOperatorCall(Call))
+  if (ModelSmartPtrDereference && isPotentiallyComparisionOpCall(Call))
+if (handleComparisionOp(Call, C))

RedDocMD wrote:
> xazax.hun wrote:
> > I'd prefer not repeating the `ModelSmartPtrDereference` check.
> I don't think we can do that, since the `isBoolConversion()` check has a 
> branch which is executed when `ModelSmartPtrDereference` is false.
That function is way below. I was just thinking about merging the first two 
check. 


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D106296

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


[PATCH] D106361: [clang-tidy] Fix crash and handle AttributedTypes in 'bugprone-easily-swappable-parameters'

2021-07-20 Thread Whisperity via Phabricator via cfe-commits
whisperity created this revision.
whisperity added reviewers: aaron.ballman, vabridgers.
whisperity added a project: clang-tools-extra.
Herald added subscribers: martong, gamesh411, Szelethus, rnkovacs, xazax.hun.
whisperity requested review of this revision.
Herald added a subscriber: cfe-commits.

A downstream user identified a way to crash the check by running on code that 
involve `AttributedType`s. This patch fixes the check to first and foremost not 
crash, but also improves the logic handling qualifiers.

If the types contain any additional (not just CVR) qualifiers that are not the 
same, they will not be deemed mixable. The logic for CVR mixing, and the 
**`QualifiersMix`** check option remain unchanged.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D106361

Files:
  clang-tools-extra/clang-tidy/bugprone/EasilySwappableParametersCheck.cpp
  
clang-tools-extra/test/clang-tidy/checkers/bugprone-easily-swappable-parameters-len2.cpp
  
clang-tools-extra/test/clang-tidy/checkers/bugprone-easily-swappable-parameters-qualifiermixing.cpp

Index: clang-tools-extra/test/clang-tidy/checkers/bugprone-easily-swappable-parameters-qualifiermixing.cpp
===
--- clang-tools-extra/test/clang-tidy/checkers/bugprone-easily-swappable-parameters-qualifiermixing.cpp
+++ clang-tools-extra/test/clang-tidy/checkers/bugprone-easily-swappable-parameters-qualifiermixing.cpp
@@ -63,7 +63,7 @@
 // CHECK-MESSAGES: :[[@LINE-1]]:31: warning: 2 adjacent parameters of 'qualifiedThroughTypedef1' of similar type are
 // CHECK-MESSAGES: :[[@LINE-2]]:35: note: the first parameter in the range is 'I'
 // CHECK-MESSAGES: :[[@LINE-3]]:43: note: the last parameter in the range is 'CI'
-// CHECK-MESSAGES: :[[@LINE-4]]:31: note: after resolving type aliases, 'int' and 'CInt' share a common type
+// CHECK-MESSAGES: :[[@LINE-4]]:31: note: after resolving type aliases, 'int' and 'CInt' share a core type
 // CHECK-MESSAGES: :[[@LINE-5]]:38: note: 'int' and 'CInt' parameters accept and bind the same kind of values
 
 void qualifiedThroughTypedef2(CInt CI1, const int CI2) {}
@@ -76,7 +76,7 @@
 // CHECK-MESSAGES: :[[@LINE-1]]:31: warning: 3 adjacent parameters of 'qualifiedThroughTypedef3' of similar type are
 // CHECK-MESSAGES: :[[@LINE-2]]:36: note: the first parameter in the range is 'CI1'
 // CHECK-MESSAGES: :[[@LINE-3]]:69: note: the last parameter in the range is 'CI3'
-// CHECK-MESSAGES: :[[@LINE-4]]:31: note: after resolving type aliases, the common type of 'CInt' and 'const MyInt1' is 'const int'
+// CHECK-MESSAGES: :[[@LINE-4]]:31: note: after resolving type aliases, the core type of 'CInt' and 'const MyInt1' is 'const int'
 // CHECK-MESSAGES: :[[@LINE-5]]:31: note: after resolving type aliases, 'CInt' and 'const int' are the same
 // CHECK-MESSAGES: :[[@LINE-6]]:41: note: after resolving type aliases, 'const MyInt1' and 'const int' are the same
 
@@ -84,21 +84,21 @@
 // CHECK-MESSAGES: :[[@LINE-1]]:31: warning: 3 adjacent parameters of 'qualifiedThroughTypedef4' of similar type are
 // CHECK-MESSAGES: :[[@LINE-2]]:36: note: the first parameter in the range is 'CI1'
 // CHECK-MESSAGES: :[[@LINE-3]]:72: note: the last parameter in the range is 'CI3'
-// CHECK-MESSAGES: :[[@LINE-4]]:31: note: after resolving type aliases, the common type of 'CInt' and 'const MyInt1' is 'const int'
-// CHECK-MESSAGES: :[[@LINE-5]]:31: note: after resolving type aliases, the common type of 'CInt' and 'const MyInt2' is 'const int'
-// CHECK-MESSAGES: :[[@LINE-6]]:41: note: after resolving type aliases, the common type of 'const MyInt1' and 'const MyInt2' is 'const int'
+// CHECK-MESSAGES: :[[@LINE-4]]:31: note: after resolving type aliases, the core type of 'CInt' and 'const MyInt1' is 'const int'
+// CHECK-MESSAGES: :[[@LINE-5]]:31: note: after resolving type aliases, the core type of 'CInt' and 'const MyInt2' is 'const int'
+// CHECK-MESSAGES: :[[@LINE-6]]:41: note: after resolving type aliases, the core type of 'const MyInt1' and 'const MyInt2' is 'const int'
 
 void qualifiedThroughTypedef5(CMyInt1 CMI1, CMyInt2 CMI2) {}
 // CHECK-MESSAGES: :[[@LINE-1]]:31: warning: 2 adjacent parameters of 'qualifiedThroughTypedef5' of similar type are
 // CHECK-MESSAGES: :[[@LINE-2]]:39: note: the first parameter in the range is 'CMI1'
 // CHECK-MESSAGES: :[[@LINE-3]]:53: note: the last parameter in the range is 'CMI2'
-// CHECK-MESSAGES: :[[@LINE-4]]:31: note: after resolving type aliases, the common type of 'CMyInt1' and 'CMyInt2' is 'const int'
+// CHECK-MESSAGES: :[[@LINE-4]]:31: note: after resolving type aliases, the core type of 'CMyInt1' and 'CMyInt2' is 'const int'
 
 void qualifiedThroughTypedef6(CMyInt1 CMI1, int I) {}
 // CHECK-MESSAGES: :[[@LINE-1]]:31: warning: 2 adjacent parameters of 'qualifiedThroughTypedef6' of similar type are
 // CHECK-MESSAGES: :[[@LINE-2]]:39: note: the first parameter in the range is 'CMI1'
 // CHECK-MESSAGES: :[[@LINE-3]]:49: note: the last parameter 

[clang] 9cb00b9 - Reland Produce warning for performing pointer arithmetic on a null pointer.

2021-07-20 Thread Jamie Schmeiser via cfe-commits

Author: Jamie Schmeiser
Date: 2021-07-20T10:12:20-04:00
New Revision: 9cb00b9ecbe74d19389a5818d61ddee328afe031

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

LOG: Reland Produce warning for performing pointer arithmetic on a null pointer.

Summary:
Test and produce warning for subtracting a pointer from null or subtracting
null from a pointer.

This reland adds the functionality that the warning is no longer reusing an
existing warning, it has different wording for C vs C++ to refect the fact
that nullptr-nullptr has defined behaviour in C++,  it is suppressed
when the warning is triggered by a system header and adds
-Wnull-pointer-subtraction to allow the warning to be controlled.  -Wextra
implies -Wnull-pointer-subtraction.

Author: Jamie Schmeiser 
Reviewed By: efriedma (Eli Friedman), nickdesaulniers (Nick Desaulniers)
Differential Revision: https://reviews.llvm.org/D98798

Added: 
clang/test/Sema/Inputs/pointer-subtraction.h
clang/test/Sema/pointer-subtraction.c
clang/test/Sema/pointer-subtraction.cpp

Modified: 
clang/docs/ReleaseNotes.rst
clang/include/clang/Basic/DiagnosticGroups.td
clang/include/clang/Basic/DiagnosticSemaKinds.td
clang/lib/Sema/SemaExpr.cpp

Removed: 




diff  --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index f26c484c5bace..a6f43bcaa4bb3 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -76,6 +76,9 @@ New Compiler Flags
   file contains frame size information for each function defined in the source
   file.
 
+- ``-Wnull-pointer-subtraction`` emits warning when user code may have
+  undefined behaviour due to subtraction involving a null pointer.
+
 Deprecated Compiler Flags
 -
 
@@ -92,6 +95,7 @@ Modified Compiler Flags
   instead. ``-B``'s other GCC-compatible semantics are preserved:
   ``$prefix/$triple-$file`` and ``$prefix$file`` are searched for executables,
   libraries, includes, and data files used by the compiler.
+- ``-Wextra`` now also implies ``-Wnull-pointer-subtraction.``
 
 Removed Compiler Flags
 -

diff  --git a/clang/include/clang/Basic/DiagnosticGroups.td 
b/clang/include/clang/Basic/DiagnosticGroups.td
index eb1b5641bfdf5..4b4928a7a00e6 100644
--- a/clang/include/clang/Basic/DiagnosticGroups.td
+++ b/clang/include/clang/Basic/DiagnosticGroups.td
@@ -487,6 +487,7 @@ def ClassVarargs : DiagGroup<"class-varargs", 
[NonPODVarargs]>;
 def : DiagGroup<"nonportable-cfstrings">;
 def NonVirtualDtor : DiagGroup<"non-virtual-dtor">;
 def NullPointerArithmetic : DiagGroup<"null-pointer-arithmetic">;
+def NullPointerSubtraction : DiagGroup<"null-pointer-subtraction">;
 def : DiagGroup<"effc++", [NonVirtualDtor]>;
 def OveralignedType : DiagGroup<"over-aligned">;
 def OldStyleCast : DiagGroup<"old-style-cast">;
@@ -932,6 +933,7 @@ def Extra : DiagGroup<"extra", [
 UnusedParameter,
 UnusedButSetParameter,
 NullPointerArithmetic,
+NullPointerSubtraction,
 EmptyInitStatement,
 StringConcatation,
 FUseLdPath,

diff  --git a/clang/include/clang/Basic/DiagnosticSemaKinds.td 
b/clang/include/clang/Basic/DiagnosticSemaKinds.td
index 823a36a597c58..792313fed2a9f 100644
--- a/clang/include/clang/Basic/DiagnosticSemaKinds.td
+++ b/clang/include/clang/Basic/DiagnosticSemaKinds.td
@@ -6390,6 +6390,9 @@ def warn_pointer_arith_null_ptr : Warning<
 def warn_gnu_null_ptr_arith : Warning<
   "arithmetic on a null pointer treated as a cast from integer to pointer is a 
GNU extension">,
   InGroup, DefaultIgnore;
+def warn_pointer_sub_null_ptr : Warning<
+  "performing pointer subtraction with a null pointer %select{has|may have}0 
undefined behavior">,
+  InGroup, DefaultIgnore;
 def err_kernel_invalidates_sycl_unique_stable_name
 : Error<"kernel instantiation changes the result of an evaluated "
 "'__builtin_sycl_unique_stable_name'">;

diff  --git a/clang/lib/Sema/SemaExpr.cpp b/clang/lib/Sema/SemaExpr.cpp
index f1c49eb082c20..dcb162952d137 100644
--- a/clang/lib/Sema/SemaExpr.cpp
+++ b/clang/lib/Sema/SemaExpr.cpp
@@ -10432,6 +10432,22 @@ static void diagnoseArithmeticOnNullPointer(Sema &S, 
SourceLocation Loc,
   << S.getLangOpts().CPlusPlus << Pointer->getSourceRange();
 }
 
+/// Diagnose invalid subraction on a null pointer.
+///
+static void diagnoseSubtractionOnNullPointer(Sema &S, SourceLocation Loc,
+ Expr *Pointer, bool BothNull) {
+  // Null - null is valid in C++ [expr.add]p7
+  if (BothNull && S.getLangOpts().CPlusPlus)
+return;
+
+  // Is this s a macro from a system header?
+  if (S.Diags.getSuppressSystemWarnings() && S.SourceMgr.isInSystemMacro(Loc))
+return;
+
+  S.Diag(Loc, diag::warn_pointer_sub_null_ptr)
+  << S.getLang

[PATCH] D98798: Produce warning for performing pointer arithmetic on a null pointer.

2021-07-20 Thread Jamie Schmeiser 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 rG9cb00b9ecbe7: Reland Produce warning for performing pointer 
arithmetic on a null pointer. (authored by jamieschmeiser).

Changed prior to commit:
  https://reviews.llvm.org/D98798?vs=346751&id=360116#toc

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D98798

Files:
  clang/docs/ReleaseNotes.rst
  clang/include/clang/Basic/DiagnosticGroups.td
  clang/include/clang/Basic/DiagnosticSemaKinds.td
  clang/lib/Sema/SemaExpr.cpp
  clang/test/Sema/Inputs/pointer-subtraction.h
  clang/test/Sema/pointer-subtraction.c
  clang/test/Sema/pointer-subtraction.cpp

Index: clang/test/Sema/pointer-subtraction.cpp
===
--- /dev/null
+++ clang/test/Sema/pointer-subtraction.cpp
@@ -0,0 +1,19 @@
+// RUN: %clang_cc1 %s -fsyntax-only -verify -pedantic -Wextra -std=c++11 -isystem %S/Inputs
+// RUN: %clang_cc1 %s -fsyntax-only -verify -pedantic -Wnull-pointer-subtraction -std=c++11 -isystem %S/Inputs
+// RUN: %clang_cc1 %s -fsyntax-only -verify -pedantic -Wextra -std=c++11 -isystem %S/Inputs -Wsystem-headers -DSYSTEM_WARNINGS
+// RUN: %clang_cc1 %s -fsyntax-only -verify -pedantic -Wnull-pointer-subtraction -std=c++11 -isystem %S/Inputs -Wsystem-headers -DSYSTEM_WARNINGS
+
+#include 
+
+void a() {
+  char *f = (char *)0;
+  f = (char *)((char *)0 - f); // expected-warning {{performing pointer subtraction with a null pointer may have undefined behavior}}
+  f = (char *)(f - (char *)0); // expected-warning {{performing pointer subtraction with a null pointer may have undefined behavior}}
+  f = (char *)((char *)0 - (char *)0); // valid in C++
+
+#ifndef SYSTEM_WARNINGS
+  SYSTEM_MACRO(f);
+#else
+  SYSTEM_MACRO(f); // expected-warning {{performing pointer subtraction with a null pointer may have undefined behavior}}
+#endif
+}
Index: clang/test/Sema/pointer-subtraction.c
===
--- /dev/null
+++ clang/test/Sema/pointer-subtraction.c
@@ -0,0 +1,19 @@
+// RUN: %clang_cc1 %s -fsyntax-only -verify -pedantic -Wextra -std=c11 -isystem %S/Inputs
+// RUN: %clang_cc1 %s -fsyntax-only -verify -pedantic -Wnull-pointer-subtraction -std=c11 -isystem %S/Inputs
+// RUN: %clang_cc1 %s -fsyntax-only -verify -pedantic -Wextra -std=c11 -isystem %S/Inputs -Wsystem-headers -DSYSTEM_WARNINGS
+// RUN: %clang_cc1 %s -fsyntax-only -verify -pedantic -Wnull-pointer-subtraction -std=c11 -isystem %S/Inputs -Wsystem-headers -DSYSTEM_WARNINGS
+
+#include 
+
+void a() {
+  char *f = (char *)0;
+  f = (char *)((char *)0 - f); // expected-warning {{performing pointer subtraction with a null pointer has undefined behavior}}
+  f = (char *)(f - (char *)0); // expected-warning {{performing pointer subtraction with a null pointer has undefined behavior}}
+  f = (char *)((char *)0 - (char *)0); // expected-warning {{performing pointer subtraction with a null pointer has undefined behavior}} expected-warning {{performing pointer subtraction with a null pointer has undefined behavior}}
+
+#ifndef SYSTEM_WARNINGS
+  SYSTEM_MACRO(f);
+#else
+  SYSTEM_MACRO(f); // expected-warning {{performing pointer subtraction with a null pointer has undefined behavior}}
+#endif
+}
Index: clang/test/Sema/Inputs/pointer-subtraction.h
===
--- /dev/null
+++ clang/test/Sema/Inputs/pointer-subtraction.h
@@ -0,0 +1 @@
+#define SYSTEM_MACRO(x) (x) = (char *)((char *)0 - (x))
Index: clang/lib/Sema/SemaExpr.cpp
===
--- clang/lib/Sema/SemaExpr.cpp
+++ clang/lib/Sema/SemaExpr.cpp
@@ -10432,6 +10432,22 @@
   << S.getLangOpts().CPlusPlus << Pointer->getSourceRange();
 }
 
+/// Diagnose invalid subraction on a null pointer.
+///
+static void diagnoseSubtractionOnNullPointer(Sema &S, SourceLocation Loc,
+ Expr *Pointer, bool BothNull) {
+  // Null - null is valid in C++ [expr.add]p7
+  if (BothNull && S.getLangOpts().CPlusPlus)
+return;
+
+  // Is this s a macro from a system header?
+  if (S.Diags.getSuppressSystemWarnings() && S.SourceMgr.isInSystemMacro(Loc))
+return;
+
+  S.Diag(Loc, diag::warn_pointer_sub_null_ptr)
+  << S.getLangOpts().CPlusPlus << Pointer->getSourceRange();
+}
+
 /// Diagnose invalid arithmetic on two function pointers.
 static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc,
 Expr *LHS, Expr *RHS) {
@@ -10863,7 +10879,16 @@
LHS.get(), RHS.get()))
 return QualType();
 
-  // FIXME: Add warnings for nullptr - ptr.
+  bool LHSIsNullPtr = LHS.get()->Ignor

[PATCH] D92928: [analyzer] Highlight arrows for currently selected event

2021-07-20 Thread Denys Petrov via Phabricator via cfe-commits
ASDenysPetrov added a comment.

I've made some debugging with IE. Let's keep the diagnostics IE friendly. We 
might not know how many users work with IE in real.




Comment at: clang/lib/StaticAnalyzer/Core/HTMLDiagnostics.cpp:1275-1283
 var scrollTo = function(el) {
 querySelectorAllArray(".selected").forEach(function(s) {
 s.classList.remove("selected");
 });
 el.classList.add("selected");
 window.scrollBy(0, el.getBoundingClientRect().top -
 (window.innerHeight / 2));

IE doesn't support `classList` for elements.



Comment at: clang/lib/StaticAnalyzer/Core/HTMLDiagnostics.cpp:1318-1320
   if (event.key == "j") {
 navigateTo(/*up=*/false);
   } else if (event.key == "k") {

Let's make this more sofisticated, as it only works for English keyboard layout 
with Caps //off//.



Comment at: clang/lib/StaticAnalyzer/Core/HTMLDiagnostics.cpp:1335-1338
+function range(lower, upper) {
+  const size = upper - lower;
+  return Array.from(new Array(size), (x, i) => i + lower);
+}

IE doesn't support `Array.from/fill` functions.



Comment at: clang/lib/StaticAnalyzer/Core/HTMLDiagnostics.cpp:1357
+var arrow = document.querySelector("#arrow" + index);
+arrow.classList.add("selected");
+  });




Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D92928

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


[PATCH] D105498: [clang] Remove assumption about SourceLocation alignment.

2021-07-20 Thread Simon Tatham via Phabricator via cfe-commits
simon_tatham updated this revision to Diff 360123.
simon_tatham added a comment.

Addressed two nits.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D105498

Files:
  clang/include/clang/AST/DeclObjC.h
  clang/lib/AST/DeclObjC.cpp


Index: clang/lib/AST/DeclObjC.cpp
===
--- clang/lib/AST/DeclObjC.cpp
+++ clang/lib/AST/DeclObjC.cpp
@@ -867,21 +867,21 @@
 }
 
 void ObjCMethodDecl::setParamsAndSelLocs(ASTContext &C,
- ArrayRef Params,
- ArrayRef SelLocs) {
-  ParamsAndSelLocs = nullptr;
-  NumParams = Params.size();
-  if (Params.empty() && SelLocs.empty())
-return;
-
-  static_assert(alignof(ParmVarDecl *) >= alignof(SourceLocation),
-"Alignment not sufficient for SourceLocation");
+ ArrayRef ParamsIn,
+ ArrayRef SelLocsIn) {
+  Params = nullptr;
+  NumParams = ParamsIn.size();
+  SelLocs = nullptr;
+
+  if (!ParamsIn.empty()) {
+Params = C.Allocate(ParamsIn.size());
+std::copy(ParamsIn.begin(), ParamsIn.end(), Params);
+  }
 
-  unsigned Size = sizeof(ParmVarDecl *) * NumParams +
-  sizeof(SourceLocation) * SelLocs.size();
-  ParamsAndSelLocs = C.Allocate(Size);
-  std::copy(Params.begin(), Params.end(), getParams());
-  std::copy(SelLocs.begin(), SelLocs.end(), getStoredSelLocs());
+  if (!SelLocsIn.empty()) {
+SelLocs = C.Allocate(SelLocsIn.size());
+std::copy(SelLocsIn.begin(), SelLocsIn.end(), SelLocs);
+  }
 }
 
 void ObjCMethodDecl::getSelectorLocs(
Index: clang/include/clang/AST/DeclObjC.h
===
--- clang/include/clang/AST/DeclObjC.h
+++ clang/include/clang/AST/DeclObjC.h
@@ -150,11 +150,13 @@
   /// Type source information for the return type.
   TypeSourceInfo *ReturnTInfo;
 
-  /// Array of ParmVarDecls for the formal parameters of this method
-  /// and optionally followed by selector locations.
-  void *ParamsAndSelLocs = nullptr;
+  /// Array of the formal parameters of this method.
+  ParmVarDecl **Params = nullptr;
   unsigned NumParams = 0;
 
+  /// Source locations for the selector identifiers.
+  SourceLocation *SelLocs = nullptr;
+
   /// List of attributes for this method declaration.
   SourceLocation DeclEndLoc; // the location of the ';' or '{'.
 
@@ -192,21 +194,12 @@
 
   /// Get a pointer to the stored selector identifiers locations array.
   /// No locations will be stored if HasStandardSelLocs is true.
-  SourceLocation *getStoredSelLocs() {
-return reinterpret_cast(getParams() + NumParams);
-  }
-  const SourceLocation *getStoredSelLocs() const {
-return reinterpret_cast(getParams() + NumParams);
-  }
+  SourceLocation *getStoredSelLocs() { return SelLocs; }
+  const SourceLocation *getStoredSelLocs() const { return SelLocs; }
 
-  /// Get a pointer to the stored selector identifiers locations array.
-  /// No locations will be stored if HasStandardSelLocs is true.
-  ParmVarDecl **getParams() {
-return reinterpret_cast(ParamsAndSelLocs);
-  }
-  const ParmVarDecl *const *getParams() const {
-return reinterpret_cast(ParamsAndSelLocs);
-  }
+  /// Get a pointer to the parameter array.
+  ParmVarDecl **getParams() { return Params; }
+  const ParmVarDecl *const *getParams() const { return Params; }
 
   /// Get the number of stored selector identifiers locations.
   /// No locations will be stored if HasStandardSelLocs is true.


Index: clang/lib/AST/DeclObjC.cpp
===
--- clang/lib/AST/DeclObjC.cpp
+++ clang/lib/AST/DeclObjC.cpp
@@ -867,21 +867,21 @@
 }
 
 void ObjCMethodDecl::setParamsAndSelLocs(ASTContext &C,
- ArrayRef Params,
- ArrayRef SelLocs) {
-  ParamsAndSelLocs = nullptr;
-  NumParams = Params.size();
-  if (Params.empty() && SelLocs.empty())
-return;
-
-  static_assert(alignof(ParmVarDecl *) >= alignof(SourceLocation),
-"Alignment not sufficient for SourceLocation");
+ ArrayRef ParamsIn,
+ ArrayRef SelLocsIn) {
+  Params = nullptr;
+  NumParams = ParamsIn.size();
+  SelLocs = nullptr;
+
+  if (!ParamsIn.empty()) {
+Params = C.Allocate(ParamsIn.size());
+std::copy(ParamsIn.begin(), ParamsIn.end(), Params);
+  }
 
-  unsigned Size = sizeof(ParmVarDecl *) * NumParams +
-  sizeof(SourceLocation) * SelLocs.size();
-  ParamsAndSelLocs = C.Allocate(Size);
-  std::copy(Params.begin(), Params.end(), getParams());
-  std::copy(SelLocs.begin(), SelLocs.end(), getStoredSelLocs());
+  if (!SelLocsIn.empty()) {
+SelLocs = C.Allocate(SelLocsIn.size());
+std::copy(SelLocsIn.begin(), Se

[PATCH] D92928: [analyzer] Highlight arrows for currently selected event

2021-07-20 Thread Denys Petrov via Phabricator via cfe-commits
ASDenysPetrov added a comment.

P.S. Sorry. My prev comments get dimmed, since I've playing with history 
commints, but they still are relevant.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D92928

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


[PATCH] D105498: [clang] Remove assumption about SourceLocation alignment.

2021-07-20 Thread Simon Tatham via Phabricator via cfe-commits
simon_tatham added inline comments.



Comment at: clang/include/clang/AST/DeclObjC.h:208
   const ParmVarDecl *const *getParams() const {
-return reinterpret_cast(ParamsAndSelLocs);
+return const_cast(Params);
   }

simon_tatham wrote:
> tmatheson wrote:
> > I don't think you need the `const_cast`
> I put it in because I got a compile error otherwise!
> 
> It's because of the double indirection. You don't need a cast to turn a `Foo 
> *` into a `const Foo *`. But here, we're turning a `Foo *` into a `const Bar 
> *`, where `Foo` and `Bar` are pointer types to things of different constness.
... ok, no, removing the `const_cast` now, I don't get a compile error. In that 
case there must have been something else weird about the version of the code 
where I had to add it, but I can't reconstruct what.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D105498

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


[PATCH] D106339: Add support to generate Sphinx DOCX documentation

2021-07-20 Thread Louis Dionne via Phabricator via cfe-commits
ldionne requested changes to this revision.
ldionne added a comment.
This revision now requires changes to proceed.

What's the benefit of having docx documentation? We generate HTML 
documentation, which ends up in the website, and that seems strictly superior 
to generating docx. What do you need it for?

The libc++ changes are almost trivial so I would not object to the change on 
that basis, however in general I think it's better to avoid adding support for 
things we won't be using on a regular basis.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D106339

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


[PATCH] D106262: [clang][analyzer] Use generic note tag in alpha.unix.Stream .

2021-07-20 Thread Balázs Kéri via Phabricator via cfe-commits
balazske updated this revision to Diff 360124.
balazske added a comment.

Support multiple bug types in the note tag function.
Add the note tag to every place and update tests.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D106262

Files:
  clang/lib/StaticAnalyzer/Checkers/StreamChecker.cpp
  clang/test/Analysis/stream-note.c

Index: clang/test/Analysis/stream-note.c
===
--- clang/test/Analysis/stream-note.c
+++ clang/test/Analysis/stream-note.c
@@ -33,12 +33,12 @@
 // expected-note@-2 {{Opened stream never closed. Potential resource leak}}
 
 void check_note_freopen() {
-  FILE *F = fopen("file", "r"); // expected-note {{Stream opened here}}
+  FILE *F = fopen("file", "r");
   if (!F)
 // expected-note@-1 {{'F' is non-null}}
 // expected-note@-2 {{Taking false branch}}
 return;
-  F = freopen(0, "w", F); // expected-note {{Stream reopened here}}
+  F = freopen(0, "w", F); // expected-note {{Stream opened here}}
   if (!F)
 // expected-note@-1 {{'F' is non-null}}
 // expected-note@-2 {{Taking false branch}}
@@ -47,6 +47,30 @@
 // expected-warning@-1 {{Opened stream never closed. Potential resource leak}}
 // expected-note@-2 {{Opened stream never closed. Potential resource leak}}
 
+void check_note_fopen_fail() {
+  FILE *F = fopen("file", "r"); // expected-note {{Assuming opening the stream fails here}} expected-note {{Assuming pointer value is null}} expected-note {{'F' initialized here}}
+  fclose(F);// expected-warning {{Stream pointer might be NULL}}
+  // expected-note@-1 {{Stream pointer might be NULL}}
+}
+
+void check_note_freopen_fail() {
+  FILE *F = fopen("file", "r");
+  if (!F) // expected-note {{'F' is non-null}} expected-note {{Taking false branch}}
+return;
+  freopen(0, "w", F); // expected-note {{Assuming opening the stream fails here}}
+  fclose(F);  // expected-warning {{Stream might be invalid after (re-)opening it has failed. Can cause undefined behaviour}}
+  // expected-note@-1 {{Stream might be invalid after (re-)opening it has failed. Can cause undefined behaviour}}
+}
+
+void check_note_freopen_fail_null() {
+  FILE *F = fopen("file", "r");
+  if (!F) // expected-note {{'F' is non-null}} expected-note {{Taking false branch}}
+return;
+  F = freopen(0, "w", F); // expected-note {{Null pointer value stored to 'F'}}
+  fclose(F);  // expected-warning {{Stream pointer might be NULL}}
+  // expected-note@-1 {{Stream pointer might be NULL}}
+}
+
 void check_note_leak_2(int c) {
   FILE *F1 = fopen("foo1.c", "r"); // expected-note {{Stream opened here}}
   if (!F1)
@@ -80,7 +104,7 @@
 
 void check_track_null() {
   FILE *F;
-  F = fopen("foo1.c", "r"); // expected-note {{Value assigned to 'F'}} expected-note {{Assuming pointer value is null}}
+  F = fopen("foo1.c", "r"); // expected-note {{Value assigned to 'F'}} expected-note {{Assuming pointer value is null}} expected-note {{Assuming opening the stream fails here}}
   if (F != NULL) {  // expected-note {{Taking false branch}} expected-note {{'F' is equal to NULL}}
 fclose(F);
 return;
@@ -145,3 +169,62 @@
   }
   fclose(F);
 }
+
+void check_indeterminate_notes_only_at_last_failure() {
+  FILE *F;
+  char Buf[10];
+  F = fopen("foo1.c", "r");
+  if (!F) // expected-note {{Taking false branch}} expected-note {{'F' is non-null}}
+return;
+  fread(Buf, 1, 1, F);
+  if (ferror(F)) { // expected-note {{Taking true branch}}
+F = freopen(0, "w", F);
+if (!F) // expected-note {{Taking false branch}} expected-note {{'F' is non-null}}
+  return;
+fread(Buf, 1, 1, F);   // expected-note {{Assuming this stream operation fails}}
+if (ferror(F)) {   // expected-note {{Taking true branch}}
+  fread(Buf, 1, 1, F); // expected-warning {{File position of the stream might be 'indeterminate' after a failed operation. Can cause undefined behavior}}
+  // expected-note@-1 {{File position of the stream might be 'indeterminate' after a failed operation. Can cause undefined behavior}}
+}
+  }
+  fclose(F);
+}
+
+void check_indeterminate_notes_fseek() {
+  FILE *F;
+  char Buf[10];
+  F = fopen("foo1.c", "r");
+  if (!F) // expected-note {{Taking false branch}} expected-note {{'F' is non-null}}
+return;
+  fseek(F, 1, SEEK_SET); // expected-note {{Assuming this stream operation fails}}
+  if (!feof(F))  // expected-note {{Taking true branch}}
+fread(Buf, 1, 1, F); // expected-warning {{File position of the stream might be 'indeterminate' after a failed operation. Can cause undefined behavior}}
+  // expected-note@-1 {{File position of the stream might be 'indeterminate' after a failed operation. Can cause undefined behavior}}
+  fclose(F);
+}
+
+void check_indeterminate_notes_fwrite() {
+  FILE *F;
+  char Buf[10];
+  F = fopen("foo1.c", "r");
+  if (!F) // expected-note {{

[PATCH] D103986: [PowerPC] Floating Point Builtins for XL Compat.

2021-07-20 Thread Quinn Pham via Phabricator via cfe-commits
quinnp updated this revision to Diff 360128.
quinnp added a comment.

Rebasing patch. Moving macro definitions from a header file to a src file.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D103986

Files:
  clang/include/clang/Basic/BuiltinsPPC.def
  clang/lib/Basic/Targets/PPC.cpp
  clang/lib/CodeGen/CGBuiltin.cpp
  clang/test/CodeGen/builtins-ppc-xlcompat-fp.c
  llvm/include/llvm/IR/IntrinsicsPowerPC.td
  llvm/lib/Target/PowerPC/PPCISelDAGToDAG.cpp
  llvm/lib/Target/PowerPC/PPCInstrInfo.td
  llvm/lib/Target/PowerPC/PPCInstrVSX.td
  llvm/test/CodeGen/builtins-ppc-xlcompat-fp.ll

Index: llvm/test/CodeGen/builtins-ppc-xlcompat-fp.ll
===
--- /dev/null
+++ llvm/test/CodeGen/builtins-ppc-xlcompat-fp.ll
@@ -0,0 +1,101 @@
+; NOTE: Assertions have been autogenerated by utils/update_llc_test_checks.py
+; RUN: llc -verify-machineinstrs -mtriple=powerpc64-unknown-unknown \
+; RUN:   -mcpu=pwr7 < %s | FileCheck %s --check-prefix=CHECK-PWR7
+; RUN: llc -verify-machineinstrs -mtriple=powerpc64le-unknown-unknown \
+; RUN:   -mcpu=pwr8 < %s | FileCheck %s --check-prefix=CHECK-PWR8
+; RUN: llc -verify-machineinstrs -mtriple=powerpc-unknown-aix \
+; RUN:   -mcpu=pwr8 < %s | FileCheck %s --check-prefix=CHECK-PWR8
+; RUN: llc -verify-machineinstrs -mtriple=powerpc64le-unknown-unknown \
+; RUN:   -mattr=-vsx -mcpu=pwr8 < %s | FileCheck %s --check-prefix=CHECK-NOVSX
+
+define dso_local double @test_fsel(double %a, double %b, double %c) local_unnamed_addr {
+; CHECK-PWR7-LABEL: test_fsel:
+; CHECK-PWR7:   # %bb.0: # %entry
+; CHECK-PWR7-NEXT:fsel 1, 1, 2, 3
+; CHECK-PWR7-NEXT:blr
+;
+; CHECK-PWR8-LABEL: test_fsel:
+; CHECK-PWR8:   # %bb.0: # %entry
+; CHECK-PWR8-NEXT:fsel 1, 1, 2, 3
+; CHECK-PWR8-NEXT:blr
+;
+; CHECK-NOVSX-LABEL: test_fsel:
+; CHECK-NOVSX:   # %bb.0: # %entry
+; CHECK-NOVSX-NEXT:fsel 1, 1, 2, 3
+; CHECK-NOVSX-NEXT:blr
+
+entry:
+  %0 = tail call double @llvm.ppc.fsel(double %a, double %b, double %c)
+  ret double %0
+}
+
+declare double @llvm.ppc.fsel(double, double, double)
+
+define dso_local float @test_fsels(float %a, float %b, float %c) local_unnamed_addr {
+; CHECK-PWR7-LABEL: test_fsels:
+; CHECK-PWR7:   # %bb.0: # %entry
+; CHECK-PWR7-NEXT:fsel 1, 1, 2, 3
+; CHECK-PWR7-NEXT:blr
+;
+; CHECK-PWR8-LABEL: test_fsels:
+; CHECK-PWR8:   # %bb.0: # %entry
+; CHECK-PWR8-NEXT:fsel 1, 1, 2, 3
+; CHECK-PWR8-NEXT:blr
+;
+; CHECK-NOVSX-LABEL: test_fsels:
+; CHECK-NOVSX:   # %bb.0: # %entry
+; CHECK-NOVSX-NEXT:fsel 1, 1, 2, 3
+; CHECK-NOVSX-NEXT:blr
+
+entry:
+  %0 = tail call float @llvm.ppc.fsels(float %a, float %b, float %c)
+  ret float %0
+}
+
+declare float @llvm.ppc.fsels(float, float, float)
+
+define dso_local double @test_frsqrte(double %a) local_unnamed_addr {
+; CHECK-PWR7-LABEL: test_frsqrte:
+; CHECK-PWR7:   # %bb.0: # %entry
+; CHECK-PWR7-NEXT:xsrsqrtedp 1, 1
+; CHECK-PWR7-NEXT:blr
+;
+; CHECK-PWR8-LABEL: test_frsqrte:
+; CHECK-PWR8:   # %bb.0: # %entry
+; CHECK-PWR8-NEXT:xsrsqrtedp 1, 1
+; CHECK-PWR8-NEXT:blr
+;
+; CHECK-NOVSX-LABEL: test_frsqrte:
+; CHECK-NOVSX:   # %bb.0: # %entry
+; CHECK-NOVSX-NEXT:frsqrte 1, 1
+; CHECK-NOVSX-NEXT:blr
+
+entry:
+  %0 = tail call double @llvm.ppc.frsqrte(double %a)
+  ret double %0
+}
+
+declare double @llvm.ppc.frsqrte(double)
+
+define dso_local float @test_frsqrtes(float %a) local_unnamed_addr {
+; CHECK-PWR7-LABEL: test_frsqrtes:
+; CHECK-PWR7:   # %bb.0: # %entry
+; CHECK-PWR7-NEXT:frsqrtes 1, 1
+; CHECK-PWR7-NEXT:blr
+;
+; CHECK-PWR8-LABEL: test_frsqrtes:
+; CHECK-PWR8:   # %bb.0: # %entry
+; CHECK-PWR8-NEXT:xsrsqrtesp 1, 1
+; CHECK-PWR8-NEXT:blr
+;
+; CHECK-NOVSX-LABEL: test_frsqrtes:
+; CHECK-NOVSX:   # %bb.0: # %entry
+; CHECK-NOVSX-NEXT:frsqrtes 1, 1
+; CHECK-NOVSX-NEXT:blr
+
+entry:
+  %0 = tail call float @llvm.ppc.frsqrtes(float %a)
+  ret float %0
+}
+
+declare float @llvm.ppc.frsqrtes(float)
Index: llvm/lib/Target/PowerPC/PPCInstrVSX.td
===
--- llvm/lib/Target/PowerPC/PPCInstrVSX.td
+++ llvm/lib/Target/PowerPC/PPCInstrVSX.td
@@ -2857,6 +2857,7 @@
 def : Pat<(int_ppc_fnmsub f64:$A, f64:$B, f64:$C), (XSNMSUBMDP $A, $B, $C)>;
 def : Pat<(int_ppc_fnmadd f64:$A, f64:$B, f64:$C), (XSNMADDMDP $A, $B, $C)>;
 def : Pat<(int_ppc_fre f64:$A), (XSREDP $A)>;
+def : Pat<(int_ppc_frsqrte vsfrc:$XB), (XSRSQRTEDP $XB)>;
 } // HasVSX
 
 // Any big endian VSX subtarget.
@@ -3264,6 +3265,7 @@
   (XSXSIGDP (COPY_TO_REGCLASS $A, VSFRC))>;
 def : Pat<(f64 (int_ppc_insert_exp f64:$A, i64:$B)),
   (COPY_TO_REGCLASS (XSIEXPDP (COPY_TO_REGCLASS $A, G8RC), $B), F8RC)>;
+def : Pat<(int_ppc_frsqrtes vssrc:$XB), (XSRSQRTESP $XB)>;
 } // HasVSX, HasP8Vector
 
 // Any big endian Power8 VSX subtarget.
Index: llvm/l

[PATCH] D105926: [PowerPC] Extra test case for LDARX

2021-07-20 Thread Kai Luo via Phabricator via cfe-commits
lkail accepted this revision.
lkail 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/D105926/new/

https://reviews.llvm.org/D105926

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


[clang] fd855c2 - [PowerPC] Restore FastMathFlags of Builder for Vector FDiv Builtins

2021-07-20 Thread Kamau Bridgeman via cfe-commits

Author: Quinn Pham
Date: 2021-07-20T09:41:00-05:00
New Revision: fd855c24c72ce01573d726317acaaefc9809d9dc

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

LOG: [PowerPC] Restore FastMathFlags of Builder for Vector FDiv Builtins

This patch fixes `__builtin_ppc_recipdivf`, `__builtin_ppc_recipdivd`,
`__builtin_ppc_rsqrtf`, and `__builtin_ppc_rsqrtd`. FastMathFlags are
set to fast immediately before emitting these builtins. Now the flags
are restored to their previous values after the builtins are emitted.

Reviewed By: nemanjai, #powerpc

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

Added: 
clang/test/CodeGen/builtins-ppc-fastmath.c

Modified: 
clang/lib/CodeGen/CGBuiltin.cpp

Removed: 




diff  --git a/clang/lib/CodeGen/CGBuiltin.cpp b/clang/lib/CodeGen/CGBuiltin.cpp
index d9958fe527cb..44aabfd47735 100644
--- a/clang/lib/CodeGen/CGBuiltin.cpp
+++ b/clang/lib/CodeGen/CGBuiltin.cpp
@@ -15280,6 +15280,7 @@ Value *CodeGenFunction::EmitPPCBuiltinExpr(unsigned 
BuiltinID,
   case PPC::BI__builtin_ppc_recipdivd:
   case PPC::BI__builtin_ppc_rsqrtf:
   case PPC::BI__builtin_ppc_rsqrtd: {
+FastMathFlags FMF = Builder.getFastMathFlags();
 Builder.getFastMathFlags().setFast();
 llvm::Type *ResultType = ConvertType(E->getType());
 Value *X = EmitScalarExpr(E->getArg(0));
@@ -15287,11 +15288,15 @@ Value *CodeGenFunction::EmitPPCBuiltinExpr(unsigned 
BuiltinID,
 if (BuiltinID == PPC::BI__builtin_ppc_recipdivf ||
 BuiltinID == PPC::BI__builtin_ppc_recipdivd) {
   Value *Y = EmitScalarExpr(E->getArg(1));
-  return Builder.CreateFDiv(X, Y, "recipdiv");
+  Value *FDiv = Builder.CreateFDiv(X, Y, "recipdiv");
+  Builder.getFastMathFlags() &= (FMF);
+  return FDiv;
 }
 auto *One = ConstantFP::get(ResultType, 1.0);
 llvm::Function *F = CGM.getIntrinsic(Intrinsic::sqrt, ResultType);
-return Builder.CreateFDiv(One, Builder.CreateCall(F, X), "rsqrt");
+Value *FDiv = Builder.CreateFDiv(One, Builder.CreateCall(F, X), "rsqrt");
+Builder.getFastMathFlags() &= (FMF);
+return FDiv;
   }
   case PPC::BI__builtin_ppc_alignx: {
 ConstantInt *AlignmentCI = cast(Ops[0]);

diff  --git a/clang/test/CodeGen/builtins-ppc-fastmath.c 
b/clang/test/CodeGen/builtins-ppc-fastmath.c
new file mode 100644
index ..5e7aa55715ce
--- /dev/null
+++ b/clang/test/CodeGen/builtins-ppc-fastmath.c
@@ -0,0 +1,70 @@
+// REQUIRES: powerpc-registered-target
+// RUN: %clang_cc1 -triple powerpc64-unknown-unknown \
+// RUN:   -emit-llvm %s -o - -target-cpu pwr7 | FileCheck %s
+// RUN: %clang_cc1 -triple powerpc64le-unknown-unknown \
+// RUN:   -emit-llvm %s -o - -target-cpu pwr8 | FileCheck %s
+// RUN: %clang_cc1 -triple powerpc64-unknown-aix \
+// RUN:   -emit-llvm %s -o - -target-cpu pwr7 | FileCheck %s
+// RUN: %clang_cc1 -triple powerpc-unknown-aix \
+// RUN:   -emit-llvm %s -o - -target-cpu pwr7 | FileCheck %s
+
+extern vector float a;
+extern vector float b;
+extern vector float c;
+extern vector double d;
+extern vector double e;
+extern vector double f;
+
+// CHECK-LABEL: @test_flags_recipdivf(
+// CHECK:[[TMP0:%.*]] = load <4 x float>, <4 x float>* @a, align 16
+// CHECK-NEXT:[[TMP1:%.*]] = load <4 x float>, <4 x float>* @b, align 16
+// CHECK-NEXT:[[TMP2:%.*]] = load <4 x float>, <4 x float>* @a, align 16
+// CHECK-NEXT:[[TMP3:%.*]] = load <4 x float>, <4 x float>* @b, align 16
+// CHECK-NEXT:[[RECIPDIV:%.*]] = fdiv fast <4 x float> [[TMP2]], [[TMP3]]
+// CHECK-NEXT:[[TMP4:%.*]] = load <4 x float>, <4 x float>* @c, align 16
+// CHECK-NEXT:[[ADD:%.*]] = fadd <4 x float> [[RECIPDIV]], [[TMP4]]
+// CHECK-NEXT:ret <4 x float> [[ADD]]
+//
+vector float test_flags_recipdivf() {
+  return __builtin_ppc_recipdivf(a, b) + c;
+}
+
+// CHECK-LABEL: @test_flags_recipdivd(
+// CHECK:[[TMP0:%.*]] = load <2 x double>, <2 x double>* @d, align 16
+// CHECK-NEXT:[[TMP1:%.*]] = load <2 x double>, <2 x double>* @e, align 16
+// CHECK-NEXT:[[TMP2:%.*]] = load <2 x double>, <2 x double>* @d, align 16
+// CHECK-NEXT:[[TMP3:%.*]] = load <2 x double>, <2 x double>* @e, align 16
+// CHECK-NEXT:[[RECIPDIV:%.*]] = fdiv fast <2 x double> [[TMP2]], [[TMP3]]
+// CHECK-NEXT:[[TMP4:%.*]] = load <2 x double>, <2 x double>* @f, align 16
+// CHECK-NEXT:[[ADD:%.*]] = fadd <2 x double> [[RECIPDIV]], [[TMP4]]
+// CHECK-NEXT:ret <2 x double> [[ADD]]
+//
+vector double test_flags_recipdivd() {
+  return __builtin_ppc_recipdivd(d, e) + f;
+}
+
+// CHECK-LABEL: @test_flags_rsqrtf(
+// CHECK:[[TMP0:%.*]] = load <4 x float>, <4 x float>* @a, align 16
+// CHECK-NEXT:[[TMP1:%.*]] = load <4 x float>, <4 x float>* @a, align 16
+// CHECK-NEXT:[[TMP2:%.*]] = call fast <4 x float> @llvm.sqrt.v4f32(<4 x 

[PATCH] D105984: [PowerPC] Restore FastMathFlags of Builder for Vector FDiv Builtins

2021-07-20 Thread Kamau Bridgeman via Phabricator via cfe-commits
This revision was landed with ongoing or failed builds.
This revision was automatically updated to reflect the committed changes.
Closed by commit rGfd855c24c72c: [PowerPC] Restore FastMathFlags of Builder for 
Vector FDiv Builtins (authored by quinnp, committed by kamaub).

Changed prior to commit:
  https://reviews.llvm.org/D105984?vs=359338&id=360129#toc

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D105984

Files:
  clang/lib/CodeGen/CGBuiltin.cpp
  clang/test/CodeGen/builtins-ppc-fastmath.c

Index: clang/test/CodeGen/builtins-ppc-fastmath.c
===
--- /dev/null
+++ clang/test/CodeGen/builtins-ppc-fastmath.c
@@ -0,0 +1,70 @@
+// REQUIRES: powerpc-registered-target
+// RUN: %clang_cc1 -triple powerpc64-unknown-unknown \
+// RUN:   -emit-llvm %s -o - -target-cpu pwr7 | FileCheck %s
+// RUN: %clang_cc1 -triple powerpc64le-unknown-unknown \
+// RUN:   -emit-llvm %s -o - -target-cpu pwr8 | FileCheck %s
+// RUN: %clang_cc1 -triple powerpc64-unknown-aix \
+// RUN:   -emit-llvm %s -o - -target-cpu pwr7 | FileCheck %s
+// RUN: %clang_cc1 -triple powerpc-unknown-aix \
+// RUN:   -emit-llvm %s -o - -target-cpu pwr7 | FileCheck %s
+
+extern vector float a;
+extern vector float b;
+extern vector float c;
+extern vector double d;
+extern vector double e;
+extern vector double f;
+
+// CHECK-LABEL: @test_flags_recipdivf(
+// CHECK:[[TMP0:%.*]] = load <4 x float>, <4 x float>* @a, align 16
+// CHECK-NEXT:[[TMP1:%.*]] = load <4 x float>, <4 x float>* @b, align 16
+// CHECK-NEXT:[[TMP2:%.*]] = load <4 x float>, <4 x float>* @a, align 16
+// CHECK-NEXT:[[TMP3:%.*]] = load <4 x float>, <4 x float>* @b, align 16
+// CHECK-NEXT:[[RECIPDIV:%.*]] = fdiv fast <4 x float> [[TMP2]], [[TMP3]]
+// CHECK-NEXT:[[TMP4:%.*]] = load <4 x float>, <4 x float>* @c, align 16
+// CHECK-NEXT:[[ADD:%.*]] = fadd <4 x float> [[RECIPDIV]], [[TMP4]]
+// CHECK-NEXT:ret <4 x float> [[ADD]]
+//
+vector float test_flags_recipdivf() {
+  return __builtin_ppc_recipdivf(a, b) + c;
+}
+
+// CHECK-LABEL: @test_flags_recipdivd(
+// CHECK:[[TMP0:%.*]] = load <2 x double>, <2 x double>* @d, align 16
+// CHECK-NEXT:[[TMP1:%.*]] = load <2 x double>, <2 x double>* @e, align 16
+// CHECK-NEXT:[[TMP2:%.*]] = load <2 x double>, <2 x double>* @d, align 16
+// CHECK-NEXT:[[TMP3:%.*]] = load <2 x double>, <2 x double>* @e, align 16
+// CHECK-NEXT:[[RECIPDIV:%.*]] = fdiv fast <2 x double> [[TMP2]], [[TMP3]]
+// CHECK-NEXT:[[TMP4:%.*]] = load <2 x double>, <2 x double>* @f, align 16
+// CHECK-NEXT:[[ADD:%.*]] = fadd <2 x double> [[RECIPDIV]], [[TMP4]]
+// CHECK-NEXT:ret <2 x double> [[ADD]]
+//
+vector double test_flags_recipdivd() {
+  return __builtin_ppc_recipdivd(d, e) + f;
+}
+
+// CHECK-LABEL: @test_flags_rsqrtf(
+// CHECK:[[TMP0:%.*]] = load <4 x float>, <4 x float>* @a, align 16
+// CHECK-NEXT:[[TMP1:%.*]] = load <4 x float>, <4 x float>* @a, align 16
+// CHECK-NEXT:[[TMP2:%.*]] = call fast <4 x float> @llvm.sqrt.v4f32(<4 x float> [[TMP1]])
+// CHECK-NEXT:[[RSQRT:%.*]] = fdiv fast <4 x float> , [[TMP2]]
+// CHECK-NEXT:[[TMP3:%.*]] = load <4 x float>, <4 x float>* @b, align 16
+// CHECK-NEXT:[[ADD:%.*]] = fadd <4 x float> [[RSQRT]], [[TMP3]]
+// CHECK-NEXT:ret <4 x float> [[ADD]]
+//
+vector float test_flags_rsqrtf() {
+  return __builtin_ppc_rsqrtf(a) + b;
+}
+
+// CHECK-LABEL: @test_flags_rsqrtd(
+// CHECK:[[TMP0:%.*]] = load <2 x double>, <2 x double>* @d, align 16
+// CHECK-NEXT:[[TMP1:%.*]] = load <2 x double>, <2 x double>* @d, align 16
+// CHECK-NEXT:[[TMP2:%.*]] = call fast <2 x double> @llvm.sqrt.v2f64(<2 x double> [[TMP1]])
+// CHECK-NEXT:[[RSQRT:%.*]] = fdiv fast <2 x double> , [[TMP2]]
+// CHECK-NEXT:[[TMP3:%.*]] = load <2 x double>, <2 x double>* @e, align 16
+// CHECK-NEXT:[[ADD:%.*]] = fadd <2 x double> [[RSQRT]], [[TMP3]]
+// CHECK-NEXT:ret <2 x double> [[ADD]]
+//
+vector double test_flags_rsqrtd() {
+  return __builtin_ppc_rsqrtd(d) + e;
+}
Index: clang/lib/CodeGen/CGBuiltin.cpp
===
--- clang/lib/CodeGen/CGBuiltin.cpp
+++ clang/lib/CodeGen/CGBuiltin.cpp
@@ -15280,6 +15280,7 @@
   case PPC::BI__builtin_ppc_recipdivd:
   case PPC::BI__builtin_ppc_rsqrtf:
   case PPC::BI__builtin_ppc_rsqrtd: {
+FastMathFlags FMF = Builder.getFastMathFlags();
 Builder.getFastMathFlags().setFast();
 llvm::Type *ResultType = ConvertType(E->getType());
 Value *X = EmitScalarExpr(E->getArg(0));
@@ -15287,11 +15288,15 @@
 if (BuiltinID == PPC::BI__builtin_ppc_recipdivf ||
 BuiltinID == PPC::BI__builtin_ppc_recipdivd) {
   Value *Y = EmitScalarExpr(E->getArg(1));
-  return Builder.CreateFDiv(X, Y, "recipdiv");
+  Value *FDiv = Builder.CreateFDiv(X, Y, "recipdiv");
+  Builder.getFastMathFlags() &= (FMF);

[PATCH] D104743: [UpdateCCTestChecks] Implement --global-hex-value-regex

2021-07-20 Thread Joel E. Denny via Phabricator via cfe-commits
jdenny updated this revision to Diff 360131.
jdenny added a comment.

Applied @jdoerfert's suggestion: generalize to all integer values.


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

https://reviews.llvm.org/D104743

Files:
  clang/test/utils/update_cc_test_checks/Inputs/global-hex-value-regex.c
  
clang/test/utils/update_cc_test_checks/Inputs/global-hex-value-regex.c.expected
  clang/test/utils/update_cc_test_checks/global-hex-value-regex.test
  llvm/utils/UpdateTestChecks/common.py

Index: llvm/utils/UpdateTestChecks/common.py
===
--- llvm/utils/UpdateTestChecks/common.py
+++ llvm/utils/UpdateTestChecks/common.py
@@ -38,10 +38,13 @@
   help='Add a prefix to FileCheck IR value names to avoid conflicts with scripted names')
   parser.add_argument('--global-value-regex', nargs='+', default=[],
   help='List of regular expressions that a global value declaration must match to generate a check (has no effect if checking globals is not enabled)')
+  parser.add_argument('--global-hex-value-regex', nargs='+', default=[],
+  help='List of regular expressions such that, for matching global value declarations, literal integer values should be encoded in hex in the associated FileCheck directives')
   args = parser.parse_args()
-  global _verbose, _global_value_regex
+  global _verbose, _global_value_regex, _global_hex_value_regex
   _verbose = args.verbose
   _global_value_regex = args.global_value_regex
+  _global_hex_value_regex = args.global_hex_value_regex
   return args
 
 
@@ -607,6 +610,12 @@
   for i, line in enumerate(lines):
 # An IR variable named '%.' matches the FileCheck regex string.
 line = line.replace('%.', '%dot')
+for regex in _global_hex_value_regex:
+  if re.match('^@' + regex + ' = ', line):
+line = re.sub(r'\bi([0-9]+) ([0-9]+)',
+lambda m : 'i' + m.group(1) + ' [[#' + hex(int(m.group(2))) + ']]',
+line)
+break
 # Ignore any comments, since the check lines will too.
 scrubbed_line = SCRUB_IR_COMMENT_RE.sub(r'', line)
 lines[i] = scrubbed_line
Index: clang/test/utils/update_cc_test_checks/global-hex-value-regex.test
===
--- /dev/null
+++ clang/test/utils/update_cc_test_checks/global-hex-value-regex.test
@@ -0,0 +1,19 @@
+RUN: rm -rf %t && mkdir %t
+
+# Check --global-hex-value-regex.
+RUN: cp %S/Inputs/global-hex-value-regex.c %t/test.c
+RUN: %update_cc_test_checks %t/test.c --check-globals \
+RUN: --global-value-regex "foo\..*" "bar\..*" \
+RUN: --global-hex-value-regex ".*\.hex"
+RUN: diff -u %S/Inputs/global-hex-value-regex.c.expected %t/test.c
+
+# Check that the generated directives actually work correctly.
+RUN: cp %S/Inputs/lit.cfg.example %t/lit.cfg
+# Show lit failures while avoiding confusing FileCheck input dump nesting.
+RUN: %lit %t
+# Lit was successful.  Sanity-check the results with deterministic test order.
+RUN: rm %t/.lit_test_times.txt
+RUN: %lit %t 2>&1 | FileCheck %s
+
+CHECK: Testing: 1 tests
+CHECK: PASS: {{.*}} test.c
Index: clang/test/utils/update_cc_test_checks/Inputs/global-hex-value-regex.c.expected
===
--- /dev/null
+++ clang/test/utils/update_cc_test_checks/Inputs/global-hex-value-regex.c.expected
@@ -0,0 +1,25 @@
+// NOTE: Assertions have been autogenerated by utils/update_cc_test_checks.py UTC_ARGS: --check-globals --global-value-regex "foo\..*" "bar\..*" --global-hex-value-regex ".*\.hex"
+// RUN: %clang_cc1 -triple x86_64-pc-linux-gnu -emit-llvm -o - %s | FileCheck %s
+
+//.
+// CHECK: @foo.hex = internal global i32 [[#0x10]], align 4
+// CHECK: @foo.dec = internal global i32 10, align 4
+// CHECK: @bar.hex = internal global i32 [[#0x20]], align 4
+// CHECK: @bar.dec = internal global i32 20, align 4
+//.
+// CHECK-LABEL: @foo(
+// CHECK-NEXT:  entry:
+// CHECK-NEXT:ret void
+//
+void foo() {
+  static int hex = 0x10;
+  static int dec = 10;
+}
+// CHECK-LABEL: @bar(
+// CHECK-NEXT:  entry:
+// CHECK-NEXT:ret void
+//
+void bar() {
+  static int hex = 0x20;
+  static int dec = 20;
+}
Index: clang/test/utils/update_cc_test_checks/Inputs/global-hex-value-regex.c
===
--- /dev/null
+++ clang/test/utils/update_cc_test_checks/Inputs/global-hex-value-regex.c
@@ -0,0 +1,10 @@
+// RUN: %clang_cc1 -triple x86_64-pc-linux-gnu -emit-llvm -o - %s | FileCheck %s
+
+void foo() {
+  static int hex = 0x10;
+  static int dec = 10;
+}
+void bar() {
+  static int hex = 0x20;
+  static int dec = 20;
+}
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D106260: [OpenCL] Add support of __opencl_c_3d_image_writes feature macro

2021-07-20 Thread Anastasia Stulova via Phabricator via cfe-commits
Anastasia added inline comments.



Comment at: clang/include/clang/Basic/DiagnosticSemaKinds.td:10092
 "use of type 'double' requires %select{cl_khr_fp64|cl_khr_fp64 and 
__opencl_c_fp64}0 support">;
+def err_opencl_3d_image_writes_requires_extensions : Error<
+"use of type '__write_only image3d_t' requires 
%select{cl_khr_3d_image_writes|cl_khr_3d_image_writes and "

it seems like we keep expanding similar diagnostics which flows against the 
design policy. Could you try to unify with 
`err_opencl_double_requires_extension` or even with 
`err_opencl_requires_extension`?

Perhaps we could create a mechanism to print custom strings for extensions that 
alias features or it can be done in the follow-up patches too?



Comment at: clang/lib/Sema/SemaType.cpp:1732-1734
+// __opencl_c_3d_image_writes feature. OpenCL C v3.0 API s4.2 - For devices
+// that support OpenCL 3.0, cl_khr_3d_image_writes must be returned when 
and
+// only when the optional feature is supported

azabaznov wrote:
> Note this. Is it OK to refer to API spec here?
I am guessing you want to explain that corresponding features and extensions 
must be in sync?

It makes sense, but it feels like we are missing something in the kernel 
language spec then...


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D106260

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


[PATCH] D92928: [analyzer] Highlight arrows for currently selected event

2021-07-20 Thread Valeriy Savchenko via Phabricator via cfe-commits
vsavchenko added a comment.

Maybe I'm missing something, but do we really need to care about IE?  The last 
version was released in 2013, and even Microsoft itself stops supporting IE.  
Why should we care?  Is there anyone who uses old deprecated browser that is 
not maintained?  `classList` thing was here for almost 4 years and no one 
seemed to care.  Am I missing something here?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D92928

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


[PATCH] D105881: [flang][driver] Switch to `BoolFOption` for boolean options

2021-07-20 Thread Pete Steinfeld via Phabricator via cfe-commits
PeteSteinfeld accepted this revision.
PeteSteinfeld added a comment.
This revision is now accepted and ready to land.

All builds, tests, and looks good.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D105881

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


[PATCH] D104743: [UpdateCCTestChecks] Implement --global-hex-value-regex

2021-07-20 Thread Johannes Doerfert via Phabricator via cfe-commits
jdoerfert accepted this revision.
jdoerfert added a comment.
This revision is now accepted and ready to land.

LG, sure why not.


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

https://reviews.llvm.org/D104743

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


[PATCH] D92928: [analyzer] Highlight arrows for currently selected event

2021-07-20 Thread Valeriy Savchenko via Phabricator via cfe-commits
vsavchenko added a comment.

I want to say that I really appreciate the effort you put into finding all the 
workarounds for IE, but it makes adding new features here incredibly painful 
because IE doesn't seem to support anything.  And the majority of developers 
(on Linux and on MacOS) have literally no way to test it.  What we gain from 
supporting IE for non-existing users, we lose in the ability to actually 
improve this code!


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D92928

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


[clang] ea864c9 - [clang][patch][NFC] Refactor calculation of FunctionDecl to avoid duplicate code

2021-07-20 Thread Melanie Blower via cfe-commits

Author: Melanie Blower
Date: 2021-07-20T11:01:22-04:00
New Revision: ea864c9933021030e33411da79b5155a78b33325

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

LOG: [clang][patch][NFC] Refactor calculation of FunctionDecl to avoid 
duplicate code

Added: 


Modified: 
clang/lib/CodeGen/CodeGenFunction.cpp

Removed: 




diff  --git a/clang/lib/CodeGen/CodeGenFunction.cpp 
b/clang/lib/CodeGen/CodeGenFunction.cpp
index 91480b0824a2..a2384456ea94 100644
--- a/clang/lib/CodeGen/CodeGenFunction.cpp
+++ b/clang/lib/CodeGen/CodeGenFunction.cpp
@@ -710,9 +710,9 @@ void CodeGenFunction::StartFunction(GlobalDecl GD, QualType 
RetTy,
 
   DidCallStackSave = false;
   CurCodeDecl = D;
-  if (const auto *FD = dyn_cast_or_null(D))
-if (FD->usesSEHTry())
-  CurSEHParent = FD;
+  const FunctionDecl *FD = dyn_cast_or_null(D);
+  if (FD && FD->usesSEHTry())
+CurSEHParent = FD;
   CurFuncDecl = (D ? D->getNonClosureContext() : nullptr);
   FnRetTy = RetTy;
   CurFn = Fn;
@@ -803,10 +803,9 @@ void CodeGenFunction::StartFunction(GlobalDecl GD, 
QualType RetTy,
   // are not aware of how to move the extra UBSan instructions across the split
   // coroutine boundaries.
   if (D && SanOpts.has(SanitizerKind::Null))
-if (const auto *FD = dyn_cast(D))
-  if (FD->getBody() &&
-  FD->getBody()->getStmtClass() == Stmt::CoroutineBodyStmtClass)
-SanOpts.Mask &= ~SanitizerKind::Null;
+if (FD && FD->getBody() &&
+FD->getBody()->getStmtClass() == Stmt::CoroutineBodyStmtClass)
+  SanOpts.Mask &= ~SanitizerKind::Null;
 
   // Apply xray attributes to the function (as a string, for now)
   bool AlwaysXRayAttr = false;
@@ -896,32 +895,27 @@ void CodeGenFunction::StartFunction(GlobalDecl GD, 
QualType RetTy,
   if (D && D->hasAttr())
 Fn->addFnAttr(llvm::Attribute::NoProfile);
 
-  if (getLangOpts().OpenCL) {
+  if (FD && getLangOpts().OpenCL) {
 // Add metadata for a kernel function.
-if (const FunctionDecl *FD = dyn_cast_or_null(D))
-  EmitOpenCLKernelMetadata(FD, Fn);
+EmitOpenCLKernelMetadata(FD, Fn);
   }
 
   // If we are checking function types, emit a function type signature as
   // prologue data.
-  if (getLangOpts().CPlusPlus && SanOpts.has(SanitizerKind::Function)) {
-if (const FunctionDecl *FD = dyn_cast_or_null(D)) {
-  if (llvm::Constant *PrologueSig = getPrologueSignature(CGM, FD)) {
-// Remove any (C++17) exception specifications, to allow calling e.g. a
-// noexcept function through a non-noexcept pointer.
-auto ProtoTy =
-  getContext().getFunctionTypeWithExceptionSpec(FD->getType(),
-EST_None);
-llvm::Constant *FTRTTIConst =
-CGM.GetAddrOfRTTIDescriptor(ProtoTy, /*ForEH=*/true);
-llvm::Constant *FTRTTIConstEncoded =
-EncodeAddrForUseInPrologue(Fn, FTRTTIConst);
-llvm::Constant *PrologueStructElems[] = {PrologueSig,
- FTRTTIConstEncoded};
-llvm::Constant *PrologueStructConst =
-llvm::ConstantStruct::getAnon(PrologueStructElems, 
/*Packed=*/true);
-Fn->setPrologueData(PrologueStructConst);
-  }
+  if (FD && getLangOpts().CPlusPlus && SanOpts.has(SanitizerKind::Function)) {
+if (llvm::Constant *PrologueSig = getPrologueSignature(CGM, FD)) {
+  // Remove any (C++17) exception specifications, to allow calling e.g. a
+  // noexcept function through a non-noexcept pointer.
+  auto ProtoTy = getContext().getFunctionTypeWithExceptionSpec(
+  FD->getType(), EST_None);
+  llvm::Constant *FTRTTIConst =
+  CGM.GetAddrOfRTTIDescriptor(ProtoTy, /*ForEH=*/true);
+  llvm::Constant *FTRTTIConstEncoded =
+  EncodeAddrForUseInPrologue(Fn, FTRTTIConst);
+  llvm::Constant *PrologueStructElems[] = {PrologueSig, 
FTRTTIConstEncoded};
+  llvm::Constant *PrologueStructConst =
+  llvm::ConstantStruct::getAnon(PrologueStructElems, /*Packed=*/true);
+  Fn->setPrologueData(PrologueStructConst);
 }
   }
 
@@ -948,14 +942,12 @@ void CodeGenFunction::StartFunction(GlobalDecl GD, 
QualType RetTy,
   // kernels cannot include RTTI information, exception classes,
   // recursive code, virtual functions or make use of C++ libraries that
   // are not compiled for the device.
-  if (const FunctionDecl *FD = dyn_cast_or_null(D)) {
-if ((getLangOpts().CPlusPlus && FD->isMain()) || getLangOpts().OpenCL ||
-getLangOpts().SYCLIsDevice ||
-(getLangOpts().CUDA && FD->hasAttr()))
-  Fn->addFnAttr(llvm::Attribute::NoRecurse);
-  }
+  if (FD && ((getLangOpts().CPlusPlus && FD->isMain()) ||
+ getLangOpts().OpenCL || getLangOpts().SYCLIs

[PATCH] D106361: [clang-tidy] Fix crash and handle AttributedTypes in 'bugprone-easily-swappable-parameters'

2021-07-20 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman added a comment.

The rename from `CommonType` to `CoreType` could probably be done as a separate 
NFC to make the review a bit easier, if we decide that's a good terminology 
switch. I'm not certain switching from `common` to `core` makes things more 
clear though; what's the distinction trying to be made?




Comment at: 
clang-tools-extra/clang-tidy/bugprone/EasilySwappableParametersCheck.cpp:476-477
+
+QualType NewCoreType = CoreType;
+NewCoreType.addFastQualifiers(Quals.getFastQualifiers());
+NewCoreType.getQualifiers().addQualifiers(Quals);





Comment at: 
clang-tools-extra/clang-tidy/bugprone/EasilySwappableParametersCheck.cpp:2201
 DiagText = "after resolving type aliases, '%0' and '%1' share a "
-   "common type";
+   "core type";
   else

I don't know that "core type" is a term of art that will convey much meaning to 
users in a diagnostic message. Do we need to change the wording of the 
diagnostic?



Comment at: 
clang-tools-extra/test/clang-tidy/checkers/bugprone-easily-swappable-parameters-len2.cpp:362-364
+// FIXME: The last diagnostic line is a bit bad: the core type should be a
+// pointer type -- it is not clear right now, how it would be possible to
+// properly wire a logic in that fixes it.

Yeah, the diagnostic here is a bit unfortunate. This was an existing deficiency 
with the check though, right? I assume it also impacts references and not just 
pointers?



Comment at: 
clang-tools-extra/test/clang-tidy/checkers/bugprone-easily-swappable-parameters-qualifiermixing.cpp:122
+// CHECK-MESSAGES: :[[@LINE-3]]:73: note: the last parameter in the range is 
'Two'
+// CHECK-MESSAGES: :[[@LINE-5]]:23: note: after resolving type aliases, the 
core type of '__attribute__((address_space(256))) int *' and 'const 
__attribute__((address_space(256))) MyInt1 *' is 'int'
+// CHECK-MESSAGES: :[[@LINE-5]]:23: note: '__attribute__((address_space(256))) 
int *' and 'const __attribute__((address_space(256))) MyInt1 *' parameters 
accept and bind the same kind of values

Should probably have a FIXME comment here as well given the lack of a pointer.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D106361

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


[PATCH] D106084: [DebugInfo] Switch to using constructor homing (-debug-info-kind=constructor) by default when debug info is enabled

2021-07-20 Thread Paul Robinson via Phabricator via cfe-commits
probinson added a comment.

> (hence the renaming of "limited" a long time ago to "standalone-debug" to 
> create a policy/philosophy around what goes in each category).

Sorry, what?  I thought -fstandalone-debug meant FullDebugInfo, and AFAICT 
that's still how the driver handles it?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D106084

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


[PATCH] D92928: [analyzer] Highlight arrows for currently selected event

2021-07-20 Thread Denys Petrov via Phabricator via cfe-commits
ASDenysPetrov added a comment.

In D92928#2890448 , @vsavchenko wrote:

> IE doesn't seem to support anything.  And the majority of developers (on 
> Linux and on MacOS) have literally no way to test it.  What we gain from 
> supporting IE for non-existing users, we lose in the ability to actually 
> improve this code!

Oh, I absolutely agree with every of your statements. I'm not really excited to 
test and adjust this stuff for IE. But I occasionally got requests from users 
which use IE and, //get ready//, the internal browser of Visual Studio :D which 
exploits IE core. So I kindly ask you to keep the JS IE friendly at least for a 
while. We don't really make changes too often here.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D92928

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


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

2021-07-20 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.

In D93769#2887857 , @mibintc wrote:

> I've rebased and applied clang-format. I'd like to push this, looking for 
> your +1, thank you!

I've marked with my LGTM, but I'd still really appreciate a double-check from 
someone with more experience in floating-point before we land.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D93769

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


[PATCH] D106084: [DebugInfo] Switch to using constructor homing (-debug-info-kind=constructor) by default when debug info is enabled

2021-07-20 Thread Paul Robinson via Phabricator via cfe-commits
probinson added a comment.

> Wouldn't the current "limited" behavior have problems for this shared 
> libraries situation too? Sounds like in that case -fstandalone-debug should 
> be used.

@jmorse am I remembering correctly, that we require dllimport-style 
annotations, so "limited" actually includes these types even if they aren't 
constructed locally?  I am vague on the details here.  But if ctor homing and 
limited both will consider a dllimport-ed type as requiring a full description, 
that's not a reason to pick one over the other.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D106084

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


[clang] 2f5b2ea - [UpdateCCTestChecks] Implement --global-value-regex

2021-07-20 Thread Joel E. Denny via cfe-commits

Author: Joel E. Denny
Date: 2021-07-20T11:23:20-04:00
New Revision: 2f5b2ea6cd854edfa2722ae0b5acf604a333e785

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

LOG: [UpdateCCTestChecks] Implement --global-value-regex

`--check-globals` activates checks for all global values, and
`--global-value-regex` filters them.  For example, I'd like to use it
in OpenMP offload codegen tests to check only global variables like
`.offload_maptypes*`.

Reviewed By: jdoerfert

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

Added: 
clang/test/utils/update_cc_test_checks/Inputs/global-value-regex.c
clang/test/utils/update_cc_test_checks/Inputs/global-value-regex.c.expected
clang/test/utils/update_cc_test_checks/global-value-regex.test

Modified: 
llvm/utils/UpdateTestChecks/common.py

Removed: 




diff  --git 
a/clang/test/utils/update_cc_test_checks/Inputs/global-value-regex.c 
b/clang/test/utils/update_cc_test_checks/Inputs/global-value-regex.c
new file mode 100644
index 0..cacaac63b0368
--- /dev/null
+++ b/clang/test/utils/update_cc_test_checks/Inputs/global-value-regex.c
@@ -0,0 +1,8 @@
+// RUN: %clang_cc1 -triple x86_64-pc-linux-gnu -emit-llvm -o - %s | FileCheck 
%s
+
+void foo() {
+  static int i, j;
+}
+void bar() {
+  static int i, j;
+}

diff  --git 
a/clang/test/utils/update_cc_test_checks/Inputs/global-value-regex.c.expected 
b/clang/test/utils/update_cc_test_checks/Inputs/global-value-regex.c.expected
new file mode 100644
index 0..b0f74c5381984
--- /dev/null
+++ 
b/clang/test/utils/update_cc_test_checks/Inputs/global-value-regex.c.expected
@@ -0,0 +1,21 @@
+// NOTE: Assertions have been autogenerated by utils/update_cc_test_checks.py 
UTC_ARGS: --check-globals --global-value-regex "foo\.."
+// RUN: %clang_cc1 -triple x86_64-pc-linux-gnu -emit-llvm -o - %s | FileCheck 
%s
+
+//.
+// CHECK: @foo.i = internal global i32 0, align 4
+// CHECK: @foo.j = internal global i32 0, align 4
+//.
+// CHECK-LABEL: @foo(
+// CHECK-NEXT:  entry:
+// CHECK-NEXT:ret void
+//
+void foo() {
+  static int i, j;
+}
+// CHECK-LABEL: @bar(
+// CHECK-NEXT:  entry:
+// CHECK-NEXT:ret void
+//
+void bar() {
+  static int i, j;
+}

diff  --git a/clang/test/utils/update_cc_test_checks/global-value-regex.test 
b/clang/test/utils/update_cc_test_checks/global-value-regex.test
new file mode 100644
index 0..33103e101794d
--- /dev/null
+++ b/clang/test/utils/update_cc_test_checks/global-value-regex.test
@@ -0,0 +1,18 @@
+RUN: rm -rf %t && mkdir %t
+
+# Check --global-value-regex.
+RUN: cp %S/Inputs/global-value-regex.c %t/test.c
+RUN: %update_cc_test_checks %t/test.c --check-globals \
+RUN:   --global-value-regex "foo\.."
+RUN: 
diff  -u %S/Inputs/global-value-regex.c.expected %t/test.c
+
+# Check that the generated directives actually work correctly.
+RUN: cp %S/Inputs/lit.cfg.example %t/lit.cfg
+# Show lit failures while avoiding confusing FileCheck input dump nesting.
+RUN: %lit %t
+# Lit was successful.  Sanity-check the results with deterministic test order.
+RUN: rm %t/.lit_test_times.txt
+RUN: %lit %t 2>&1 | FileCheck %s
+
+CHECK: Testing: 1 tests
+CHECK: PASS: {{.*}} test.c

diff  --git a/llvm/utils/UpdateTestChecks/common.py 
b/llvm/utils/UpdateTestChecks/common.py
index ff48e3b9f678e..29d22401cf73d 100644
--- a/llvm/utils/UpdateTestChecks/common.py
+++ b/llvm/utils/UpdateTestChecks/common.py
@@ -36,9 +36,12 @@ def parse_commandline_args(parser):
   help='List of regular expressions to replace matching 
value names')
   parser.add_argument('--prefix-filecheck-ir-name', default='',
   help='Add a prefix to FileCheck IR value names to avoid 
conflicts with scripted names')
+  parser.add_argument('--global-value-regex', nargs='+', default=[],
+  help='List of regular expressions that a global value 
declaration must match to generate a check (has no effect if checking globals 
is not enabled)')
   args = parser.parse_args()
-  global _verbose
+  global _verbose, _global_value_regex
   _verbose = args.verbose
+  _global_value_regex = args.global_value_regex
   return args
 
 
@@ -796,13 +799,27 @@ def add_global_checks(glob_val_dict, comment_marker, 
prefix_list, output_lines,
 if not glob_val_dict[checkprefix][nameless_value.check_prefix]:
   continue
 
-output_lines.append(comment_marker + SEPARATOR)
-
+check_lines = []
 global_vars_seen_before = [key for key in global_vars_seen.keys()]
 for line in glob_val_dict[checkprefix][nameless_value.check_prefix]:
+  if _global_value_regex:
+matched = False
+for regex in _global_value_regex:
+  if re.match('^@' + regex + ' = ', line):
+matched =

[clang] 5b0a948 - [UpdateCCTestChecks] Implement --global-hex-value-regex

2021-07-20 Thread Joel E. Denny via cfe-commits

Author: Joel E. Denny
Date: 2021-07-20T11:23:20-04:00
New Revision: 5b0a948a81e695f044e88659be18a28256b1e309

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

LOG: [UpdateCCTestChecks] Implement --global-hex-value-regex

For example, in OpenMP offload codegen tests, global variables like
`.offload_maptypes*` are much easier to read in hex.

Reviewed By: jdoerfert

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

Added: 
clang/test/utils/update_cc_test_checks/Inputs/global-hex-value-regex.c

clang/test/utils/update_cc_test_checks/Inputs/global-hex-value-regex.c.expected
clang/test/utils/update_cc_test_checks/global-hex-value-regex.test

Modified: 
llvm/utils/UpdateTestChecks/common.py

Removed: 




diff  --git 
a/clang/test/utils/update_cc_test_checks/Inputs/global-hex-value-regex.c 
b/clang/test/utils/update_cc_test_checks/Inputs/global-hex-value-regex.c
new file mode 100644
index 0..ad4c109c45ec5
--- /dev/null
+++ b/clang/test/utils/update_cc_test_checks/Inputs/global-hex-value-regex.c
@@ -0,0 +1,10 @@
+// RUN: %clang_cc1 -triple x86_64-pc-linux-gnu -emit-llvm -o - %s | FileCheck 
%s
+
+void foo() {
+  static int hex = 0x10;
+  static int dec = 10;
+}
+void bar() {
+  static int hex = 0x20;
+  static int dec = 20;
+}

diff  --git 
a/clang/test/utils/update_cc_test_checks/Inputs/global-hex-value-regex.c.expected
 
b/clang/test/utils/update_cc_test_checks/Inputs/global-hex-value-regex.c.expected
new file mode 100644
index 0..3018d0261adf9
--- /dev/null
+++ 
b/clang/test/utils/update_cc_test_checks/Inputs/global-hex-value-regex.c.expected
@@ -0,0 +1,25 @@
+// NOTE: Assertions have been autogenerated by utils/update_cc_test_checks.py 
UTC_ARGS: --check-globals --global-value-regex "foo\..*" "bar\..*" 
--global-hex-value-regex ".*\.hex"
+// RUN: %clang_cc1 -triple x86_64-pc-linux-gnu -emit-llvm -o - %s | FileCheck 
%s
+
+//.
+// CHECK: @foo.hex = internal global i32 [[#0x10]], align 4
+// CHECK: @foo.dec = internal global i32 10, align 4
+// CHECK: @bar.hex = internal global i32 [[#0x20]], align 4
+// CHECK: @bar.dec = internal global i32 20, align 4
+//.
+// CHECK-LABEL: @foo(
+// CHECK-NEXT:  entry:
+// CHECK-NEXT:ret void
+//
+void foo() {
+  static int hex = 0x10;
+  static int dec = 10;
+}
+// CHECK-LABEL: @bar(
+// CHECK-NEXT:  entry:
+// CHECK-NEXT:ret void
+//
+void bar() {
+  static int hex = 0x20;
+  static int dec = 20;
+}

diff  --git 
a/clang/test/utils/update_cc_test_checks/global-hex-value-regex.test 
b/clang/test/utils/update_cc_test_checks/global-hex-value-regex.test
new file mode 100644
index 0..6ff06b4028d82
--- /dev/null
+++ b/clang/test/utils/update_cc_test_checks/global-hex-value-regex.test
@@ -0,0 +1,19 @@
+RUN: rm -rf %t && mkdir %t
+
+# Check --global-hex-value-regex.
+RUN: cp %S/Inputs/global-hex-value-regex.c %t/test.c
+RUN: %update_cc_test_checks %t/test.c --check-globals \
+RUN: --global-value-regex "foo\..*" "bar\..*" \
+RUN: --global-hex-value-regex ".*\.hex"
+RUN: 
diff  -u %S/Inputs/global-hex-value-regex.c.expected %t/test.c
+
+# Check that the generated directives actually work correctly.
+RUN: cp %S/Inputs/lit.cfg.example %t/lit.cfg
+# Show lit failures while avoiding confusing FileCheck input dump nesting.
+RUN: %lit %t
+# Lit was successful.  Sanity-check the results with deterministic test order.
+RUN: rm %t/.lit_test_times.txt
+RUN: %lit %t 2>&1 | FileCheck %s
+
+CHECK: Testing: 1 tests
+CHECK: PASS: {{.*}} test.c

diff  --git a/llvm/utils/UpdateTestChecks/common.py 
b/llvm/utils/UpdateTestChecks/common.py
index 29d22401cf73d..aa9b845f05fdc 100644
--- a/llvm/utils/UpdateTestChecks/common.py
+++ b/llvm/utils/UpdateTestChecks/common.py
@@ -38,10 +38,13 @@ def parse_commandline_args(parser):
   help='Add a prefix to FileCheck IR value names to avoid 
conflicts with scripted names')
   parser.add_argument('--global-value-regex', nargs='+', default=[],
   help='List of regular expressions that a global value 
declaration must match to generate a check (has no effect if checking globals 
is not enabled)')
+  parser.add_argument('--global-hex-value-regex', nargs='+', default=[],
+  help='List of regular expressions such that, for 
matching global value declarations, literal integer values should be encoded in 
hex in the associated FileCheck directives')
   args = parser.parse_args()
-  global _verbose, _global_value_regex
+  global _verbose, _global_value_regex, _global_hex_value_regex
   _verbose = args.verbose
   _global_value_regex = args.global_value_regex
+  _global_hex_value_regex = args.global_hex_value_regex
   return args
 
 
@@ -607,6 +610,12 @@ def transform_line_vars(match):
   for i, line in enumerate(lines):

  1   2   3   >