[PATCH] D75041: [clang-tidy] Extend 'bugprone-easily-swappable-parameters' with mixability because of implicit conversions

2021-06-03 Thread Whisperity via Phabricator via cfe-commits
whisperity added inline comments.



Comment at: 
clang-tools-extra/clang-tidy/bugprone/EasilySwappableParametersCheck.cpp:657-667
+  // Certain kinds unfortunately need to be side-stepped for canonical type
+  // matching.
+  if (LType->getAs() || RType->getAs()) {
+// Unfortunately, the canonical type of a function pointer becomes the
+// same even if exactly one is "noexcept" and the other isn't, making us
+// give a false positive report irrespective of implicit conversions.
+LLVM_DEBUG(llvm::dbgs()

martong wrote:
> aaron.ballman wrote:
> > whisperity wrote:
> > > @aaron.ballman Getting ahead of the curve here. I understand this is 
> > > ugly. Unfortunately, no matter how much I read the standard, I don't get 
> > > anything of "canonical type" mentioned, it seems to me this concept is 
> > > something inherent to the model of Clang.
> > > 
> > > Basically why this is here: imagine a `void (*)() noexcept` and a `void 
> > > (*)()`. One's `noexcept`, the other isn't. Inside the AST, this is a 
> > > `ParenType` of a `PointerType` to a `FunctionProtoType`. There exists a 
> > > //one-way// implicit conversion from the `noexcept` to the non-noexcept 
> > > ("noexceptness can be discarded", similarly to how "constness can be 
> > > gained")
> > > Unfortunately, because this is a one-way implicit conversion, it won't 
> > > return on the code path earlier for implicit conversions.
> > > 
> > > Now because of this, the recursive descent in our code will reach the 
> > > point when the two innermost `FunctionProtoType`s are in our hands. As a 
> > > fallback case, we simply ask Clang "Hey, do //you// think these two are 
> > > the same?". And for some weird reason, Clang will say "Yes."... While one 
> > > of them is a `noexcept` function and the other one isn't.
> > > 
> > > I do not know the innards of the AST well enough to even have a glimpse 
> > > of whether or not this is a bug. So that's the reason why I went ahead 
> > > and implemented this side-stepping logic. Basically, as the comment says, 
> > > it'lll **force** the information of "No matter what you do, do NOT 
> > > consider these mixable!" back up the recursion chain, and handle it 
> > > appropriately later.
> > > Unfortunately, no matter how much I read the standard, I don't get 
> > > anything of "canonical type" mentioned, it seems to me this concept is 
> > > something inherent to the model of Clang.
> > 
> > It is more of a Clang-centric concept. Basically, a canonical type is one 
> > that's had all of the typedefs stripped off it.
> > 
> > > Now because of this, the recursive descent in our code will reach the 
> > > point when the two innermost FunctionProtoTypes are in our hands. As a 
> > > fallback case, we simply ask Clang "Hey, do you think these two are the 
> > > same?". And for some weird reason, Clang will say "Yes."... While one of 
> > > them is a noexcept function and the other one isn't.
> > 
> > I think a confounding factor in this area is that `noexcept` did not used 
> > to be part of the function type until one day it started being a part of 
> > the function type. So my guess is that this is fallout from this sort of 
> > thing: https://godbolt.org/z/EYfj8z (which may be worth keeping in mind 
> > when working on the check).
> About `noexcept`: we've faced a similar problem in the `ASTImporter` library. 
> We could not import a noexcept function's definition if we already had one 
> without the noexcept specifier. 
> 
> Thus, in `ASTStructuralEquivalence.cpp` we do differentiate the function 
> types based on their noexcept specifier (and we even check the noexcept 
> expression).:
> ```
> TEST_F(StructuralEquivalenceFunctionTest, Noexcept) {
>   auto t = makeNamedDecls("void foo();",
>   "void foo() noexcept;", Lang_CXX11);
>   EXPECT_FALSE(testStructuralMatch(t));
> }
> TEST_F(StructuralEquivalenceFunctionTest, NoexceptNonMatch) {
>   auto t = makeNamedDecls("void foo() noexcept(false);",
>   "void foo() noexcept(true);", Lang_CXX11);
>   EXPECT_FALSE(testStructuralMatch(t));
> }
> ```
> 
> May be in these special cases it would worth to reuse the 
> ASTStructuralEquivalenceContext class?
Definitely, good catch, @martong, thank you very much! @aaron.ballman, what do 
you think? If I see this right, `StructuralEquivalenceContext` is part of 
`libClangAST` so should be readily available.

The only issue I'm seeing is that this class takes non-**`const`** `ASTContext` 
and `Decl` nodes...


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D75041

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


[PATCH] D102822: [Clang][CodeGen] Set the size of llvm.lifetime to unknown for scalable types.

2021-06-03 Thread Sander de Smalen via Phabricator via cfe-commits
sdesmalen added inline comments.



Comment at: clang/lib/CodeGen/CGDecl.cpp:1327
+  if (Size.isScalable())
+Size = llvm::TypeSize::Fixed(-1);
+

Instead of updating `Size` here, can you change line 1332 to be:

  llvm::Value *SizeV = llvm::ConstantInt::get(Int64Ty, Size.isScalable() ? -1 : 
Size.getFixedValue())



Comment at: clang/lib/CodeGen/CGDecl.cpp:1332
  "Pointer should be in alloca address space");
   llvm::Value *SizeV = llvm::ConstantInt::get(Int64Ty, Size);
   Addr = Builder.CreateBitCast(Addr, AllocaInt8PtrTy);

Does `ConstantInt` take `TypeSize Size` as argument?



Comment at: clang/lib/CodeGen/CGDecl.cpp:1558
   emission.SizeForLifetimeMarkers =
-  size.isScalable() ? EmitLifetimeStart(-1, 
AllocaAddr.getPointer())
-: EmitLifetimeStart(size.getFixedSize(),
-AllocaAddr.getPointer());
+  EmitLifetimeStart(size, AllocaAddr.getPointer());
 }

nit: Given you have to update this line, maybe also to capitalize `size -> 
Size`?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D102822

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


[PATCH] D102760: [llvm] Let SmallVector construct from any Iterable

2021-06-03 Thread Clement Courbet via Phabricator via cfe-commits
courbet added inline comments.



Comment at: clang/include/clang/Basic/Module.h:98
 public:
+  Module(const Module &) = default;
+

gchatelet wrote:
> gchatelet wrote:
> > fhahn wrote:
> > > how is this related?
> > > how is this related?
> > 
> > I'm glad you ask! I'm still investigating the errors that led to this 
> > addition (and the one in `llvm/tools/llvm-xray/xray-converter.cpp`) but I 
> > suspect this is due to the recursive nature of these classes.
> > Both `Module` and `StackIdData` contains self-referencing `SmallVector`. It 
> > is unclear to me why the compiler is trying to instantiate the newly added 
> > `SmallVector` constructor //during// type declaration.
> > 
> > I'll post the compiler errors below the additions.
> ```
> FAILED: tools/clang/lib/Lex/CMakeFiles/obj.clangLex.dir/HeaderSearch.cpp.o 
> /redacted/build-llvm/download/clang/bin/clang++ 
> --sysroot=/redacted/build-llvm/download/sysroot -DGTEST_HAS_RTTI=0 
> -D_GNU_SOURCE -D__STDC_CONSTANT_MACROS -D__STDC_FORMAT_MACROS 
> -D__STDC_LIMIT_MACROS -Itools/clang/lib/Lex 
> -I/redacted/git/llvm-project/clang/lib/Lex 
> -I/redacted/git/llvm-project/clang/include -Itools/clang/include -Iinclude 
> -I/redacted/git/llvm-project/llvm/include -fPIC -fvisibility-inlines-hidden 
> -Werror=date-time -Werror=unguarded-availability-new -Wall -Wextra 
> -Wno-unused-parameter -Wwrite-strings -Wcast-qual 
> -Wmissing-field-initializers -pedantic -Wno-long-long 
> -Wc++98-compat-extra-semi -Wimplicit-fallthrough -Wcovered-switch-default 
> -Wno-noexcept-type -Wnon-virtual-dtor -Wdelete-non-virtual-dtor 
> -Wsuggest-override -Wstring-conversion -Wmisleading-indentation 
> -fdiagnostics-color -ffunction-sections -fdata-sections -fno-common 
> -Woverloaded-virtual -Wno-nested-anon-types -O3 -DNDEBUG  -fno-exceptions 
> -fno-rtti -std=c++14 -MD -MT 
> tools/clang/lib/Lex/CMakeFiles/obj.clangLex.dir/HeaderSearch.cpp.o -MF 
> tools/clang/lib/Lex/CMakeFiles/obj.clangLex.dir/HeaderSearch.cpp.o.d -o 
> tools/clang/lib/Lex/CMakeFiles/obj.clangLex.dir/HeaderSearch.cpp.o -c 
> /redacted/git/llvm-project/clang/lib/Lex/HeaderSearch.cpp
> In file included from 
> /redacted/git/llvm-project/clang/lib/Lex/HeaderSearch.cpp:13:
> In file included from 
> /redacted/git/llvm-project/clang/include/clang/Lex/HeaderSearch.h:16:
> In file included from 
> /redacted/git/llvm-project/clang/include/clang/Basic/SourceLocation.h:19:
> /redacted/git/llvm-project/llvm/include/llvm/Support/PointerLikeTypeTraits.h:61:28:
>  error: invalid application of 'alignof' to an incomplete type 'clang::Module'
>   detail::ConstantLog2::value;
>^~
> /redacted/git/llvm-project/llvm/include/llvm/ADT/IterableTraits.h:23:33: 
> note: in instantiation of template class 
> 'llvm::PointerLikeTypeTraits' requested here
> std::next(std::declval()),
> ^
> /redacted/git/llvm-project/llvm/include/llvm/ADT/IterableTraits.h:36:39: 
> note: while substituting explicitly-specified template arguments into 
> function template 'is_forward_iterator' 
> struct is_forward_iterator : decltype(detail::is_forward_iterator(0)) {};
>   ^
> /redacted/git/llvm-project/llvm/include/llvm/ADT/IterableTraits.h:46:42: 
> note: in instantiation of template class 'llvm::is_forward_iterator llvm::PointerIntPair *>' requested here
>  llvm::is_forward_iterator{});
>  ^
> /redacted/git/llvm-project/llvm/include/llvm/ADT/IterableTraits.h:51:37: 
> note: while substituting deduced template arguments into function template 
> 'is_range_iterable' [with T = const 
> llvm::SmallVector, 2> &, I = 
> (no value)]
> struct is_range_iterable : decltype(detail::is_range_iterable(0)) {};
> ^
> /redacted/git/llvm-project/llvm/include/llvm/ADT/SmallVector.h:1194:30: note: 
> in instantiation of template class 'llvm::is_range_iterable llvm::SmallVector, 2> &>' 
> requested here
>   std::enable_if_t::value, bool> = true)
>  ^
> /redacted/git/llvm-project/llvm/include/llvm/ADT/SmallVector.h:1168:22: note: 
> while substituting deduced template arguments into function template 
> 'SmallVector' [with Iterable = const 
> llvm::SmallVector, 2> &]
> class LLVM_GSL_OWNER SmallVector : public SmallVectorImpl,
>  ^
> /redacted/git/llvm-project/clang/include/clang/Basic/Module.h:96:7: note: 
> while declaring the implicit copy constructor for 'Module'
> class Module {
>   ^
> /redacted/git/llvm-project/clang/include/clang/Basic/Module.h:96:7: note: 
> definition of 'clang::Module' is not complete until the closing '}'
> 1 error generated.
> ```
For reference, the issue is that `std::next` takes its parameter by value: 
https://godbolt.org/z/531f3f86s.

(though I'm not sure we want to move forward with this patch given 
@Quuxplusone's comments)



[PATCH] D103452: [clang] Fix reading long doubles with va_arg on x86_64 mingw

2021-06-03 Thread Martin Storsjö via Phabricator via cfe-commits
mstorsjo added inline comments.



Comment at: clang/lib/CodeGen/TargetInfo.cpp:4364-4365
 
   // MS x64 ABI requirement: "Any argument that doesn't fit in 8 bytes, or is
   // not 1, 2, 4, or 8 bytes, must be passed by reference."
   if (isAggregateTypeForABI(Ty) || Ty->isMemberPointerType()) {

mstorsjo wrote:
> rnk wrote:
> > I wonder if we should make the check more general. There are other cases to 
> > consider, like `__int128`. How does GCC pass other large types through 
> > varargs? It looks to me like clang passes those indirectly, so we could go 
> > ahead and check the type size directly without these aggregate checks.
> > 
> > Separately, I think `X86_64ABIInfo::EmitMSVAArg` has a bug, it always 
> > passes false for indirect, but it should match this code here exactly. 
> > Ideally, they would share an implementation.
> I'll have a look at what GCC does for `__int128` yeah.
> 
> Yes, `X86_64ABIInfo::EmitMSVAArg` is lacking, I've got a separate patch 
> fixing that one up to be posted after this one (but this patch fixes an 
> actual issue I've run into, the other one is more of a correctness thing).
> 
> The open question about that one, is what to do about `long double`. If using 
> `__attribute__((ms_abi))` and `__builtin_ms_va_list` on a non-windows 
> platform, we don't know if they're meaning to interact with the MS or GNU ABI 
> regarding `long double`s.
> 
> On one hand, one would mostly be using those constructs to reimplement 
> Windows API (i.e. implementing wine or something similar), and in that case, 
> only the MS behaviour is of interest. On the other hand, mapping `va_arg(ap, 
> long double)` to the GNU case doesn't take anything away for the user either, 
> because if you want a MSVC long double, you can just do `va_arg(ap, double)`. 
> Then finally, I guess there's no guarantee that the platform where doing that 
> even has an exactly matching long double?
GCC does the same for `__int128` in varargs as it does for `long double`, so 
that does indeed simplify the code a fair bit.

And I also realized it's not a problem wrt `long double` and the 
`__builtin_ms_va_list`; if the caller does `va_arg(ap, long double)`, that has 
to be handled according to whatever the size of `long double` is on platform, 
which hopefully would match what GCC uses on windows.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D103452

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


[PATCH] D99675: [llvm][clang] Create new intrinsic llvm.arith.fence to control FP optimization at expression level

2021-06-03 Thread LuoYuanke via Phabricator via cfe-commits
LuoYuanke added a comment.

We may add description on the intrinsic in docs/LangRef.rst.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D99675

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


[PATCH] D103434: [analyzer] Allow visitors to run callbacks on completion

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



Comment at: 
clang/include/clang/StaticAnalyzer/Core/BugReporter/BugReporterVisitors.h:95
+  /// This method is run once the \ref Stop method is called.
+  virtual void OnStop(const ExplodedNode *Curr, BugReporterContext &BRC,
+  PathSensitiveBugReport &BR) const = 0;

According to the conventions, should use `stop` and `onStop` instead of `Stop`, 
`OnStop`?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D103434

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


[PATCH] D101868: [clang-format] Adds a formatter for aligning arrays of structs

2021-06-03 Thread Björn Schäpers via Phabricator via cfe-commits
HazardyKnusperkeks added inline comments.



Comment at: clang/lib/Format/TokenAnnotator.cpp:737-740
+const auto End = Contexts.rbegin() + 2;
+auto Last = Contexts.rbegin();
+unsigned Depth = 0;
+for (; Last != End; Last = std::next(Last)) {

I actually meant so. Because now this is even safe if the iterators are not 
random access anymore in the future.



Comment at: clang/lib/Format/WhitespaceManager.cpp:1136-1137
+auto j = i - 1;
+for (; j > 0 && Changes[j].NewlinesBefore == 0; --j) {
+}
+EndSpaces = Changes[j].Spaces;

I don't know how to do this in LLVM style, but maybe so?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D101868

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


[PATCH] D103589: [Format] Fix incorrect pointer detection

2021-06-03 Thread Björn Schäpers via Phabricator via cfe-commits
HazardyKnusperkeks accepted this revision.
HazardyKnusperkeks added a comment.

Seems reasonable. :)


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D103589

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


[clang] e237168 - Revert "[Fuchsia] Use libc++abi on Windows in Fuchsia toolchain"

2021-06-03 Thread Petr Hosek via cfe-commits

Author: Petr Hosek
Date: 2021-06-03T01:18:22-07:00
New Revision: e237168341ed9688ee70277465a488b6f4b8ba03

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

LOG: Revert "[Fuchsia] Use libc++abi on Windows in Fuchsia toolchain"

This reverts commit b5dd421a3afa0290fddf61073274e2a4aa9a which
broke Fuchsia downstream builders.

Added: 


Modified: 
clang/cmake/caches/Fuchsia-stage2.cmake

Removed: 




diff  --git a/clang/cmake/caches/Fuchsia-stage2.cmake 
b/clang/cmake/caches/Fuchsia-stage2.cmake
index 982307732327..a1e27477afa7 100644
--- a/clang/cmake/caches/Fuchsia-stage2.cmake
+++ b/clang/cmake/caches/Fuchsia-stage2.cmake
@@ -83,15 +83,13 @@ if(WIN32)
   list(APPEND RUNTIME_TARGETS "${target}")
   set(RUNTIMES_${target}_CMAKE_SYSTEM_NAME Windows CACHE STRING "")
   set(RUNTIMES_${target}_CMAKE_BUILD_TYPE RelWithDebInfo CACHE STRING "")
-  set(RUNTIMES_${target}_LIBCXXABI_ENABLE_SHARED OFF CACHE BOOL "")
   set(RUNTIMES_${target}_LIBCXX_ABI_VERSION 2 CACHE STRING "")
-  set(RUNTIMES_${target}_LIBCXX_CXX_ABI "libcxxabi" CACHE STRING "")
   set(RUNTIMES_${target}_LIBCXX_ENABLE_EXPERIMENTAL_LIBRARY OFF CACHE BOOL "")
   set(RUNTIMES_${target}_LIBCXX_ENABLE_FILESYSTEM OFF CACHE BOOL "")
   set(RUNTIMES_${target}_LIBCXX_ENABLE_ABI_LINKER_SCRIPT OFF CACHE BOOL "")
   set(RUNTIMES_${target}_LIBCXX_ENABLE_SHARED OFF CACHE BOOL "")
   set(RUNTIMES_${target}_LIBCXX_NO_VCRUNTIME ON CACHE BOOL "")
-  set(RUNTIMES_${target}_LLVM_ENABLE_RUNTIMES "compiler-rt;libcxx;libcxxabi" 
CACHE STRING "")
+  set(RUNTIMES_${target}_LLVM_ENABLE_RUNTIMES "compiler-rt;libcxx" CACHE 
STRING "")
 endif()
 
 foreach(target 
aarch64-unknown-linux-gnu;armv7-unknown-linux-gnueabihf;i386-unknown-linux-gnu;x86_64-unknown-linux-gnu)



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


[PATCH] D103440: [WIP][analyzer] Introduce range-based reasoning for addition operator

2021-06-03 Thread Valeriy Savchenko via Phabricator via cfe-commits
vsavchenko added a comment.

I also would like to see tests where the ranges are not going all the way to 
either `INT_MIN` or `INT_MAX` (if we talk about `int`), but overflow still 
might happen, and cases where overflow might happen, but we still can identify 
the overflowing results precisely (e.g. the result is `[INT_MIN, INT_MIN + 10] 
and [INT_MAX - 5, INT_MAX])




Comment at: clang/test/Analysis/constant-folding.c:279
+if (c == INT_MIN && d == INT_MIN) {
+  clang_analyzer_eval((c + d) == 0); // expected-warning{{TRUE}}
+}

Good!



Comment at: clang/test/Analysis/constant-folding.c:282
+
+if (c >= -20 && d >= -40) {
+  clang_analyzer_eval((c + d) < -1); // expected-warning{{TRUE}}

Great, it's good to check negative numbers.
I have one note here.  The fact that we don't have a testing framework and use 
this approach of inspecting the actual analysis has an interesting implication.

```
if (a == 10) { // here we split path into 2 paths: one where a == 10, and one 
where a != 10;
   // one goes inside of if, one doesn't
  . . .
}
if (a >= 5) { // here we split into 3 paths: a == 10, a < 5, and a in [5, 9] 
and [11, INT_MAX] (aka a >= 5 and a != 10).
  // 1 path was infeasible: a == 10 and a < 5
  // Two of these paths go inside of the if, one doesn't
  . . .
  clang_analyzer_eval(a == 10); // it will produce two results: TRUE and FALSE
}
clang_analyzer_eval(a == 10); // it will produce three results: TRUE, FALSE, 
and FALSE
```

We don't want to test how path splitting works in these particular tests (they 
are about solver and constant folding after all), that's why we try to have 
only one path going through each `clang_analyzer_eval(...)`

In this example, you still have residual paths where `c != INT_MIN`, `c == 
INT_MIN and d != INT_MIN`, and `c == INT_MIN and d == INT_MIN`.



Comment at: clang/test/Analysis/constant-folding.c:304-305
+  if (c > 0 && d > 0) {
+clang_analyzer_eval((c + d) > 1); // expected-warning{{TRUE}}
+clang_analyzer_eval((c + d) < -1); // expected-warning{{TRUE}}
+  }

How can these two statements be TRUE at the same time?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D103440

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


[PATCH] D103595: [clang] Correct MarkFunctionReferenced for local class

2021-06-03 Thread Fütő Gergely via Phabricator via cfe-commits
futogergely created this revision.
futogergely added a reviewer: rsmith.
futogergely requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

Minor correction after commit 4a941e25f2b57f85eef00a9cbfbc2569639570ad.

If during the instantiation of a local class a method of the
local class is referenced, don't try to instantiate it.

PR48839


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D103595

Files:
  clang/lib/Sema/SemaExpr.cpp
  clang/test/SemaTemplate/instantiate-local-class.cpp


Index: clang/test/SemaTemplate/instantiate-local-class.cpp
===
--- clang/test/SemaTemplate/instantiate-local-class.cpp
+++ clang/test/SemaTemplate/instantiate-local-class.cpp
@@ -504,3 +504,24 @@
   }
   template void f();
 }
+
+namespace PR48839 {
+  template 
+  void construct() {
+T(0);
+  }
+
+  template 
+  void tester() {
+struct d {
+  void test() {
+construct();
+}
+constexpr d(T b) : a(b) {}
+
+T a;
+};
+  }
+
+  void g() { tester(); }
+}
Index: clang/lib/Sema/SemaExpr.cpp
===
--- clang/lib/Sema/SemaExpr.cpp
+++ clang/lib/Sema/SemaExpr.cpp
@@ -17057,10 +17057,12 @@
   PointOfInstantiation = Loc;
 }
 
+const bool isLocalClass =
+isa(Func->getDeclContext()) &&
+cast(Func->getDeclContext())->isLocalClass();
 if (FirstInstantiation || TSK != TSK_ImplicitInstantiation ||
-Func->isConstexpr()) {
-  if (isa(Func->getDeclContext()) &&
-  cast(Func->getDeclContext())->isLocalClass() &&
+(!isLocalClass && Func->isConstexpr())) {
+  if (isLocalClass &&
   CodeSynthesisContexts.size())
 PendingLocalImplicitInstantiations.push_back(
 std::make_pair(Func, PointOfInstantiation));


Index: clang/test/SemaTemplate/instantiate-local-class.cpp
===
--- clang/test/SemaTemplate/instantiate-local-class.cpp
+++ clang/test/SemaTemplate/instantiate-local-class.cpp
@@ -504,3 +504,24 @@
   }
   template void f();
 }
+
+namespace PR48839 {
+  template 
+  void construct() {
+T(0);
+  }
+
+  template 
+  void tester() {
+struct d {
+  void test() {
+construct();
+}
+constexpr d(T b) : a(b) {}
+
+T a;
+};
+  }
+
+  void g() { tester(); }
+}
Index: clang/lib/Sema/SemaExpr.cpp
===
--- clang/lib/Sema/SemaExpr.cpp
+++ clang/lib/Sema/SemaExpr.cpp
@@ -17057,10 +17057,12 @@
   PointOfInstantiation = Loc;
 }
 
+const bool isLocalClass =
+isa(Func->getDeclContext()) &&
+cast(Func->getDeclContext())->isLocalClass();
 if (FirstInstantiation || TSK != TSK_ImplicitInstantiation ||
-Func->isConstexpr()) {
-  if (isa(Func->getDeclContext()) &&
-  cast(Func->getDeclContext())->isLocalClass() &&
+(!isLocalClass && Func->isConstexpr())) {
+  if (isLocalClass &&
   CodeSynthesisContexts.size())
 PendingLocalImplicitInstantiations.push_back(
 std::make_pair(Func, PointOfInstantiation));
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D103595: [clang] Correct MarkFunctionReferenced for local class

2021-06-03 Thread Fütő Gergely via Phabricator via cfe-commits
futogergely updated this revision to Diff 349480.
futogergely added a comment.

formatting in instantiate-local-class.cpp


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

https://reviews.llvm.org/D103595

Files:
  clang/lib/Sema/SemaExpr.cpp
  clang/test/SemaTemplate/instantiate-local-class.cpp


Index: clang/test/SemaTemplate/instantiate-local-class.cpp
===
--- clang/test/SemaTemplate/instantiate-local-class.cpp
+++ clang/test/SemaTemplate/instantiate-local-class.cpp
@@ -504,3 +504,24 @@
   }
   template void f();
 }
+
+namespace PR48839 {
+  template 
+  void construct() {
+T(0);
+  }
+
+  template 
+  void tester() {
+struct d {
+  void test() {
+construct();
+  }
+  constexpr d(T b) : a(b) {}
+
+  T a;
+};
+  }
+
+  void g() { tester(); }
+}
Index: clang/lib/Sema/SemaExpr.cpp
===
--- clang/lib/Sema/SemaExpr.cpp
+++ clang/lib/Sema/SemaExpr.cpp
@@ -17057,10 +17057,12 @@
   PointOfInstantiation = Loc;
 }
 
+const bool isLocalClass =
+isa(Func->getDeclContext()) &&
+cast(Func->getDeclContext())->isLocalClass();
 if (FirstInstantiation || TSK != TSK_ImplicitInstantiation ||
-Func->isConstexpr()) {
-  if (isa(Func->getDeclContext()) &&
-  cast(Func->getDeclContext())->isLocalClass() &&
+(!isLocalClass && Func->isConstexpr())) {
+  if (isLocalClass &&
   CodeSynthesisContexts.size())
 PendingLocalImplicitInstantiations.push_back(
 std::make_pair(Func, PointOfInstantiation));


Index: clang/test/SemaTemplate/instantiate-local-class.cpp
===
--- clang/test/SemaTemplate/instantiate-local-class.cpp
+++ clang/test/SemaTemplate/instantiate-local-class.cpp
@@ -504,3 +504,24 @@
   }
   template void f();
 }
+
+namespace PR48839 {
+  template 
+  void construct() {
+T(0);
+  }
+
+  template 
+  void tester() {
+struct d {
+  void test() {
+construct();
+  }
+  constexpr d(T b) : a(b) {}
+
+  T a;
+};
+  }
+
+  void g() { tester(); }
+}
Index: clang/lib/Sema/SemaExpr.cpp
===
--- clang/lib/Sema/SemaExpr.cpp
+++ clang/lib/Sema/SemaExpr.cpp
@@ -17057,10 +17057,12 @@
   PointOfInstantiation = Loc;
 }
 
+const bool isLocalClass =
+isa(Func->getDeclContext()) &&
+cast(Func->getDeclContext())->isLocalClass();
 if (FirstInstantiation || TSK != TSK_ImplicitInstantiation ||
-Func->isConstexpr()) {
-  if (isa(Func->getDeclContext()) &&
-  cast(Func->getDeclContext())->isLocalClass() &&
+(!isLocalClass && Func->isConstexpr())) {
+  if (isLocalClass &&
   CodeSynthesisContexts.size())
 PendingLocalImplicitInstantiations.push_back(
 std::make_pair(Func, PointOfInstantiation));
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] 178ad93 - [clang][clangd] Use reverse header map lookup in suggestPathToFileForDiagnostics

2021-06-03 Thread Dmitry Polukhin via cfe-commits

Author: Dmitry Polukhin
Date: 2021-06-03T01:37:55-07:00
New Revision: 178ad93e3f1f2381f05baea300873ee5998ac288

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

LOG: [clang][clangd] Use reverse header map lookup in 
suggestPathToFileForDiagnostics

Summary:
suggestPathToFileForDiagnostics is actively used in clangd for converting
an absolute path to a header file to a header name as it should be spelled
in the sources. Current approach converts absolute path to relative path.
This diff implements missing logic that makes a reverse lookup from the
relative path to the key in the header map that should be used in the sources.

Prerequisite diff: https://reviews.llvm.org/D103229

Test Plan: check-clang

Reviewers: dexonsmith, bruno, rsmith

Subscribers: cfe-commits

Tasks:

Tags: #clang

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

Added: 


Modified: 
clang/include/clang/Lex/HeaderMap.h
clang/lib/Lex/HeaderMap.cpp
clang/lib/Lex/HeaderSearch.cpp
clang/unittests/Lex/HeaderSearchTest.cpp

Removed: 




diff  --git a/clang/include/clang/Lex/HeaderMap.h 
b/clang/include/clang/Lex/HeaderMap.h
index accb061e51ba3..53108b00bd16d 100644
--- a/clang/include/clang/Lex/HeaderMap.h
+++ b/clang/include/clang/Lex/HeaderMap.h
@@ -16,6 +16,7 @@
 #include "clang/Basic/FileManager.h"
 #include "clang/Basic/LLVM.h"
 #include "llvm/ADT/Optional.h"
+#include "llvm/ADT/StringMap.h"
 #include "llvm/Support/Compiler.h"
 #include "llvm/Support/MemoryBuffer.h"
 #include 
@@ -29,6 +30,7 @@ struct HMapHeader;
 class HeaderMapImpl {
   std::unique_ptr FileBuffer;
   bool NeedsBSwap;
+  mutable llvm::StringMap ReverseMap;
 
 public:
   HeaderMapImpl(std::unique_ptr File, bool 
NeedsBSwap)
@@ -48,6 +50,9 @@ class HeaderMapImpl {
   /// Print the contents of this headermap to stderr.
   void dump() const;
 
+  /// Return key for specifed path.
+  StringRef reverseLookupFilename(StringRef DestPath) const;
+
 private:
   unsigned getEndianAdjustedWord(unsigned X) const;
   const HMapHeader &getHeader() const;
@@ -79,9 +84,10 @@ class HeaderMap : private HeaderMapImpl {
   /// ".." and a filename "../file.h" this would be "../../file.h".
   Optional LookupFile(StringRef Filename, FileManager &FM) const;
 
-  using HeaderMapImpl::lookupFilename;
-  using HeaderMapImpl::getFileName;
   using HeaderMapImpl::dump;
+  using HeaderMapImpl::getFileName;
+  using HeaderMapImpl::lookupFilename;
+  using HeaderMapImpl::reverseLookupFilename;
 };
 
 } // end namespace clang.

diff  --git a/clang/lib/Lex/HeaderMap.cpp b/clang/lib/Lex/HeaderMap.cpp
index d44ef29c05d13..4b60cfa7b52dd 100644
--- a/clang/lib/Lex/HeaderMap.cpp
+++ b/clang/lib/Lex/HeaderMap.cpp
@@ -240,3 +240,32 @@ StringRef HeaderMapImpl::lookupFilename(StringRef Filename,
 return StringRef(DestPath.begin(), DestPath.size());
   }
 }
+
+StringRef HeaderMapImpl::reverseLookupFilename(StringRef DestPath) const {
+  if (!ReverseMap.empty())
+return ReverseMap.lookup(DestPath);
+
+  const HMapHeader &Hdr = getHeader();
+  unsigned NumBuckets = getEndianAdjustedWord(Hdr.NumBuckets);
+  StringRef RetKey;
+  for (unsigned i = 0; i != NumBuckets; ++i) {
+HMapBucket B = getBucket(i);
+if (B.Key == HMAP_EmptyBucketKey)
+  continue;
+
+Optional Key = getString(B.Key);
+Optional Prefix = getString(B.Prefix);
+Optional Suffix = getString(B.Suffix);
+if (LLVM_LIKELY(Key && Prefix && Suffix)) {
+  SmallVector Buf;
+  Buf.append(Prefix->begin(), Prefix->end());
+  Buf.append(Suffix->begin(), Suffix->end());
+  StringRef Value(Buf.begin(), Buf.size());
+  ReverseMap[Value] = *Key;
+
+  if (DestPath == Value)
+RetKey = *Key;
+}
+  }
+  return RetKey;
+}

diff  --git a/clang/lib/Lex/HeaderSearch.cpp b/clang/lib/Lex/HeaderSearch.cpp
index 99c92e91aad51..9970c3c99a27f 100644
--- a/clang/lib/Lex/HeaderSearch.cpp
+++ b/clang/lib/Lex/HeaderSearch.cpp
@@ -1834,7 +1834,7 @@ std::string HeaderSearch::suggestPathToFileForDiagnostics(
   };
 
   for (unsigned I = 0; I != SearchDirs.size(); ++I) {
-// FIXME: Support this search within frameworks and header maps.
+// FIXME: Support this search within frameworks.
 if (!SearchDirs[I].isNormalDir())
   continue;
 
@@ -1848,6 +1848,19 @@ std::string 
HeaderSearch::suggestPathToFileForDiagnostics(
   if (!BestPrefixLength && CheckDir(path::parent_path(MainFile)) && IsSystem)
 *IsSystem = false;
 
+  // Try resolving resulting filename via reverse search in header maps,
+  // key from header name is user prefered name for the include file.
+  StringRef Filename = File.drop_front(BestPrefixLength);
+  for (unsigned I = 0; I != SearchDirs.size(); ++I) {
+if (!SearchDirs[I].isHeaderMap())
+  continue;
 
-  return path::convert_to_sl

[PATCH] D103142: [clang][clangd] Use reverse header map lookup in suggestPathToFileForDiagnostics

2021-06-03 Thread Dmitry Polukhin via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG178ad93e3f1f: [clang][clangd] Use reverse header map lookup 
in suggestPathToFileForDiagnostics (authored by DmitryPolukhin).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D103142

Files:
  clang/include/clang/Lex/HeaderMap.h
  clang/lib/Lex/HeaderMap.cpp
  clang/lib/Lex/HeaderSearch.cpp
  clang/unittests/Lex/HeaderSearchTest.cpp

Index: clang/unittests/Lex/HeaderSearchTest.cpp
===
--- clang/unittests/Lex/HeaderSearchTest.cpp
+++ clang/unittests/Lex/HeaderSearchTest.cpp
@@ -7,6 +7,7 @@
 //===--===//
 
 #include "clang/Lex/HeaderSearch.h"
+#include "HeaderMapTestUtils.h"
 #include "clang/Basic/Diagnostic.h"
 #include "clang/Basic/DiagnosticOptions.h"
 #include "clang/Basic/FileManager.h"
@@ -45,6 +46,21 @@
 Search.AddSearchPath(DL, /*isAngled=*/false);
   }
 
+  void addHeaderMap(llvm::StringRef Filename,
+std::unique_ptr Buf) {
+VFS->addFile(Filename, 0, std::move(Buf), /*User=*/None, /*Group=*/None,
+ llvm::sys::fs::file_type::regular_file);
+auto FE = FileMgr.getFile(Filename, true);
+assert(FE);
+
+// Test class supports only one HMap at a time.
+assert(!HMap);
+HMap = HeaderMap::Create(*FE, FileMgr);
+auto DL =
+DirectoryLookup(HMap.get(), SrcMgr::C_User, /*isFramework=*/false);
+Search.AddSearchPath(DL, /*isAngled=*/false);
+  }
+
   IntrusiveRefCntPtr VFS;
   FileSystemOptions FileMgrOpts;
   FileManager FileMgr;
@@ -55,6 +71,7 @@
   std::shared_ptr TargetOpts;
   IntrusiveRefCntPtr Target;
   HeaderSearch Search;
+  std::unique_ptr HMap;
 };
 
 TEST_F(HeaderSearchTest, NoSearchDir) {
@@ -136,5 +153,31 @@
 "y/z/t.h");
 }
 
+// Helper struct with null terminator character to make MemoryBuffer happy.
+template 
+struct NullTerminatedFile : public FileTy {
+  PaddingTy Padding = 0;
+};
+
+TEST_F(HeaderSearchTest, HeaderMapReverseLookup) {
+  typedef NullTerminatedFile, char> FileTy;
+  FileTy File;
+  File.init();
+
+  test::HMapFileMockMaker Maker(File);
+  auto a = Maker.addString("d.h");
+  auto b = Maker.addString("b/");
+  auto c = Maker.addString("c.h");
+  Maker.addBucket("d.h", a, b, c);
+
+  addHeaderMap("/x/y/z.hmap", File.getBuffer());
+  addSearchDir("/a");
+
+  EXPECT_EQ(Search.suggestPathToFileForDiagnostics("/a/b/c.h",
+   /*WorkingDir=*/"",
+   /*MainFile=*/""),
+"d.h");
+}
+
 } // namespace
 } // namespace clang
Index: clang/lib/Lex/HeaderSearch.cpp
===
--- clang/lib/Lex/HeaderSearch.cpp
+++ clang/lib/Lex/HeaderSearch.cpp
@@ -1834,7 +1834,7 @@
   };
 
   for (unsigned I = 0; I != SearchDirs.size(); ++I) {
-// FIXME: Support this search within frameworks and header maps.
+// FIXME: Support this search within frameworks.
 if (!SearchDirs[I].isNormalDir())
   continue;
 
@@ -1848,6 +1848,19 @@
   if (!BestPrefixLength && CheckDir(path::parent_path(MainFile)) && IsSystem)
 *IsSystem = false;
 
+  // Try resolving resulting filename via reverse search in header maps,
+  // key from header name is user prefered name for the include file.
+  StringRef Filename = File.drop_front(BestPrefixLength);
+  for (unsigned I = 0; I != SearchDirs.size(); ++I) {
+if (!SearchDirs[I].isHeaderMap())
+  continue;
 
-  return path::convert_to_slash(File.drop_front(BestPrefixLength));
+StringRef SpelledFilename =
+SearchDirs[I].getHeaderMap()->reverseLookupFilename(Filename);
+if (!SpelledFilename.empty()) {
+  Filename = SpelledFilename;
+  break;
+}
+  }
+  return path::convert_to_slash(Filename);
 }
Index: clang/lib/Lex/HeaderMap.cpp
===
--- clang/lib/Lex/HeaderMap.cpp
+++ clang/lib/Lex/HeaderMap.cpp
@@ -240,3 +240,32 @@
 return StringRef(DestPath.begin(), DestPath.size());
   }
 }
+
+StringRef HeaderMapImpl::reverseLookupFilename(StringRef DestPath) const {
+  if (!ReverseMap.empty())
+return ReverseMap.lookup(DestPath);
+
+  const HMapHeader &Hdr = getHeader();
+  unsigned NumBuckets = getEndianAdjustedWord(Hdr.NumBuckets);
+  StringRef RetKey;
+  for (unsigned i = 0; i != NumBuckets; ++i) {
+HMapBucket B = getBucket(i);
+if (B.Key == HMAP_EmptyBucketKey)
+  continue;
+
+Optional Key = getString(B.Key);
+Optional Prefix = getString(B.Prefix);
+Optional Suffix = getString(B.Suffix);
+if (LLVM_LIKELY(Key && Prefix && Suffix)) {
+  SmallVector Buf;
+  Buf.append(Prefix->begin(), Prefix->end());
+  Buf.append(Suffix->begin(), Suffix->end());
+  StringRef Value(Buf.begin(), Buf.

[PATCH] D103142: [clang][clangd] Use reverse header map lookup in suggestPathToFileForDiagnostics

2021-06-03 Thread Dmitry Polukhin via Phabricator via cfe-commits
DmitryPolukhin added a comment.

@bruno and @dexonsmith thank you for the review!


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D103142

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


[PATCH] D103028: [clang][ARM] Remove arm2/3/6/7m CPU names

2021-06-03 Thread David Spickett via Phabricator via cfe-commits
DavidSpickett updated this revision to Diff 349487.
DavidSpickett added a comment.

Clang format


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D103028

Files:
  clang/test/Misc/target-invalid-cpu-note.c
  llvm/include/llvm/Support/ARMTargetParser.def
  llvm/unittests/Support/TargetParserTest.cpp


Index: llvm/unittests/Support/TargetParserTest.cpp
===
--- llvm/unittests/Support/TargetParserTest.cpp
+++ llvm/unittests/Support/TargetParserTest.cpp
@@ -124,10 +124,6 @@
 ARMCPUTestParams("invalid", "invalid", "invalid", ARM::AEK_NONE, ""),
 ARMCPUTestParams("generic", "invalid", "none", ARM::AEK_NONE, ""),
 
-ARMCPUTestParams("arm2", "armv2", "none", ARM::AEK_NONE, "2"),
-ARMCPUTestParams("arm3", "armv2a", "none", ARM::AEK_NONE, "2A"),
-ARMCPUTestParams("arm6", "armv3", "none", ARM::AEK_NONE, "3"),
-ARMCPUTestParams("arm7m", "armv3m", "none", ARM::AEK_NONE, "3M"),
 ARMCPUTestParams("arm8", "armv4", "none", ARM::AEK_NONE, "4"),
 ARMCPUTestParams("arm810", "armv4", "none", ARM::AEK_NONE, "4"),
 ARMCPUTestParams("strongarm", "armv4", "none", ARM::AEK_NONE, "4"),
@@ -388,7 +384,7 @@
  ARM::AEK_HWDIVARM | ARM::AEK_HWDIVTHUMB | 
ARM::AEK_DSP,
  "7-S")));
 
-static constexpr unsigned NumARMCPUArchs = 90;
+static constexpr unsigned NumARMCPUArchs = 86;
 
 TEST(TargetParserTest, testARMCPUArchList) {
   SmallVector List;
@@ -420,17 +416,13 @@
 
 TEST(TargetParserTest, testARMArch) {
   EXPECT_TRUE(
-  testARMArch("armv2", "arm2", "v2",
-  ARMBuildAttrs::CPUArch::Pre_v4));
+  testARMArch("armv2", "generic", "v2", ARMBuildAttrs::CPUArch::Pre_v4));
   EXPECT_TRUE(
-  testARMArch("armv2a", "arm3", "v2a",
-  ARMBuildAttrs::CPUArch::Pre_v4));
+  testARMArch("armv2a", "generic", "v2a", ARMBuildAttrs::CPUArch::Pre_v4));
   EXPECT_TRUE(
-  testARMArch("armv3", "arm6", "v3",
-  ARMBuildAttrs::CPUArch::Pre_v4));
+  testARMArch("armv3", "generic", "v3", ARMBuildAttrs::CPUArch::Pre_v4));
   EXPECT_TRUE(
-  testARMArch("armv3m", "arm7m", "v3m",
-  ARMBuildAttrs::CPUArch::Pre_v4));
+  testARMArch("armv3m", "generic", "v3m", ARMBuildAttrs::CPUArch::Pre_v4));
   EXPECT_TRUE(
   testARMArch("armv4", "strongarm", "v4",
   ARMBuildAttrs::CPUArch::v4));
@@ -535,10 +527,6 @@
 }
 
 TEST(TargetParserTest, testARMExtension) {
-  EXPECT_FALSE(testARMExtension("arm2", ARM::ArchKind::INVALID, "thumb"));
-  EXPECT_FALSE(testARMExtension("arm3", ARM::ArchKind::INVALID, "thumb"));
-  EXPECT_FALSE(testARMExtension("arm6", ARM::ArchKind::INVALID, "thumb"));
-  EXPECT_FALSE(testARMExtension("arm7m", ARM::ArchKind::INVALID, "thumb"));
   EXPECT_FALSE(testARMExtension("strongarm", ARM::ArchKind::INVALID, "dsp"));
   EXPECT_FALSE(testARMExtension("arm7tdmi", ARM::ArchKind::INVALID, "dsp"));
   EXPECT_FALSE(testARMExtension("arm10tdmi",
Index: llvm/include/llvm/Support/ARMTargetParser.def
===
--- llvm/include/llvm/Support/ARMTargetParser.def
+++ llvm/include/llvm/Support/ARMTargetParser.def
@@ -201,10 +201,6 @@
 #ifndef ARM_CPU_NAME
 #define ARM_CPU_NAME(NAME, ID, DEFAULT_FPU, IS_DEFAULT, DEFAULT_EXT)
 #endif
-ARM_CPU_NAME("arm2", ARMV2, FK_NONE, true, ARM::AEK_NONE)
-ARM_CPU_NAME("arm3", ARMV2A, FK_NONE, true, ARM::AEK_NONE)
-ARM_CPU_NAME("arm6", ARMV3, FK_NONE, true, ARM::AEK_NONE)
-ARM_CPU_NAME("arm7m", ARMV3M, FK_NONE, true, ARM::AEK_NONE)
 ARM_CPU_NAME("arm8", ARMV4, FK_NONE, false, ARM::AEK_NONE)
 ARM_CPU_NAME("arm810", ARMV4, FK_NONE, false, ARM::AEK_NONE)
 ARM_CPU_NAME("strongarm", ARMV4, FK_NONE, true, ARM::AEK_NONE)
Index: clang/test/Misc/target-invalid-cpu-note.c
===
--- clang/test/Misc/target-invalid-cpu-note.c
+++ clang/test/Misc/target-invalid-cpu-note.c
@@ -1,7 +1,7 @@
 // RUN: not %clang_cc1 -triple armv5--- -target-cpu not-a-cpu -fsyntax-only %s 
2>&1 | FileCheck %s --check-prefix ARM
 // ARM: error: unknown target CPU 'not-a-cpu'
 // ARM: note: valid target CPU values are:
-// ARM-SAME: arm2
+// ARM-SAME: arm8
 
 // RUN: not %clang_cc1 -triple arm64--- -target-cpu not-a-cpu -fsyntax-only %s 
2>&1 | FileCheck %s --check-prefix AARCH64
 // AARCH64: error: unknown target CPU 'not-a-cpu'


Index: llvm/unittests/Support/TargetParserTest.cpp
===
--- llvm/unittests/Support/TargetParserTest.cpp
+++ llvm/unittests/Support/TargetParserTest.cpp
@@ -124,10 +124,6 @@
 ARMCPUTestParams("invalid", "invalid", "invalid", ARM::AEK_NONE, ""),
 ARMCPUTestParams("generic", "invalid", "none", ARM::AEK_NONE, ""),
 
-ARMCPUTestPara

[PATCH] D103028: [clang][ARM] Remove arm2/3/6/7m CPU names

2021-06-03 Thread David Spickett 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 rGf4543dce5db5: [clang][ARM] Remove arm2/3/6/7m CPU names 
(authored by DavidSpickett).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D103028

Files:
  clang/test/Misc/target-invalid-cpu-note.c
  llvm/include/llvm/Support/ARMTargetParser.def
  llvm/unittests/Support/TargetParserTest.cpp


Index: llvm/unittests/Support/TargetParserTest.cpp
===
--- llvm/unittests/Support/TargetParserTest.cpp
+++ llvm/unittests/Support/TargetParserTest.cpp
@@ -124,10 +124,6 @@
 ARMCPUTestParams("invalid", "invalid", "invalid", ARM::AEK_NONE, ""),
 ARMCPUTestParams("generic", "invalid", "none", ARM::AEK_NONE, ""),
 
-ARMCPUTestParams("arm2", "armv2", "none", ARM::AEK_NONE, "2"),
-ARMCPUTestParams("arm3", "armv2a", "none", ARM::AEK_NONE, "2A"),
-ARMCPUTestParams("arm6", "armv3", "none", ARM::AEK_NONE, "3"),
-ARMCPUTestParams("arm7m", "armv3m", "none", ARM::AEK_NONE, "3M"),
 ARMCPUTestParams("arm8", "armv4", "none", ARM::AEK_NONE, "4"),
 ARMCPUTestParams("arm810", "armv4", "none", ARM::AEK_NONE, "4"),
 ARMCPUTestParams("strongarm", "armv4", "none", ARM::AEK_NONE, "4"),
@@ -388,7 +384,7 @@
  ARM::AEK_HWDIVARM | ARM::AEK_HWDIVTHUMB | 
ARM::AEK_DSP,
  "7-S")));
 
-static constexpr unsigned NumARMCPUArchs = 90;
+static constexpr unsigned NumARMCPUArchs = 86;
 
 TEST(TargetParserTest, testARMCPUArchList) {
   SmallVector List;
@@ -420,17 +416,13 @@
 
 TEST(TargetParserTest, testARMArch) {
   EXPECT_TRUE(
-  testARMArch("armv2", "arm2", "v2",
-  ARMBuildAttrs::CPUArch::Pre_v4));
+  testARMArch("armv2", "generic", "v2", ARMBuildAttrs::CPUArch::Pre_v4));
   EXPECT_TRUE(
-  testARMArch("armv2a", "arm3", "v2a",
-  ARMBuildAttrs::CPUArch::Pre_v4));
+  testARMArch("armv2a", "generic", "v2a", ARMBuildAttrs::CPUArch::Pre_v4));
   EXPECT_TRUE(
-  testARMArch("armv3", "arm6", "v3",
-  ARMBuildAttrs::CPUArch::Pre_v4));
+  testARMArch("armv3", "generic", "v3", ARMBuildAttrs::CPUArch::Pre_v4));
   EXPECT_TRUE(
-  testARMArch("armv3m", "arm7m", "v3m",
-  ARMBuildAttrs::CPUArch::Pre_v4));
+  testARMArch("armv3m", "generic", "v3m", ARMBuildAttrs::CPUArch::Pre_v4));
   EXPECT_TRUE(
   testARMArch("armv4", "strongarm", "v4",
   ARMBuildAttrs::CPUArch::v4));
@@ -535,10 +527,6 @@
 }
 
 TEST(TargetParserTest, testARMExtension) {
-  EXPECT_FALSE(testARMExtension("arm2", ARM::ArchKind::INVALID, "thumb"));
-  EXPECT_FALSE(testARMExtension("arm3", ARM::ArchKind::INVALID, "thumb"));
-  EXPECT_FALSE(testARMExtension("arm6", ARM::ArchKind::INVALID, "thumb"));
-  EXPECT_FALSE(testARMExtension("arm7m", ARM::ArchKind::INVALID, "thumb"));
   EXPECT_FALSE(testARMExtension("strongarm", ARM::ArchKind::INVALID, "dsp"));
   EXPECT_FALSE(testARMExtension("arm7tdmi", ARM::ArchKind::INVALID, "dsp"));
   EXPECT_FALSE(testARMExtension("arm10tdmi",
Index: llvm/include/llvm/Support/ARMTargetParser.def
===
--- llvm/include/llvm/Support/ARMTargetParser.def
+++ llvm/include/llvm/Support/ARMTargetParser.def
@@ -201,10 +201,6 @@
 #ifndef ARM_CPU_NAME
 #define ARM_CPU_NAME(NAME, ID, DEFAULT_FPU, IS_DEFAULT, DEFAULT_EXT)
 #endif
-ARM_CPU_NAME("arm2", ARMV2, FK_NONE, true, ARM::AEK_NONE)
-ARM_CPU_NAME("arm3", ARMV2A, FK_NONE, true, ARM::AEK_NONE)
-ARM_CPU_NAME("arm6", ARMV3, FK_NONE, true, ARM::AEK_NONE)
-ARM_CPU_NAME("arm7m", ARMV3M, FK_NONE, true, ARM::AEK_NONE)
 ARM_CPU_NAME("arm8", ARMV4, FK_NONE, false, ARM::AEK_NONE)
 ARM_CPU_NAME("arm810", ARMV4, FK_NONE, false, ARM::AEK_NONE)
 ARM_CPU_NAME("strongarm", ARMV4, FK_NONE, true, ARM::AEK_NONE)
Index: clang/test/Misc/target-invalid-cpu-note.c
===
--- clang/test/Misc/target-invalid-cpu-note.c
+++ clang/test/Misc/target-invalid-cpu-note.c
@@ -1,7 +1,7 @@
 // RUN: not %clang_cc1 -triple armv5--- -target-cpu not-a-cpu -fsyntax-only %s 
2>&1 | FileCheck %s --check-prefix ARM
 // ARM: error: unknown target CPU 'not-a-cpu'
 // ARM: note: valid target CPU values are:
-// ARM-SAME: arm2
+// ARM-SAME: arm8
 
 // RUN: not %clang_cc1 -triple arm64--- -target-cpu not-a-cpu -fsyntax-only %s 
2>&1 | FileCheck %s --check-prefix AARCH64
 // AARCH64: error: unknown target CPU 'not-a-cpu'


Index: llvm/unittests/Support/TargetParserTest.cpp
===
--- llvm/unittests/Support/TargetParserTest.cpp
+++ llvm/unittests/Support/TargetParserTest.cpp
@@ -124,10 +124,6 @@
 ARMCPUTestParams("invalid", "inval

[clang] f4543dc - [clang][ARM] Remove arm2/3/6/7m CPU names

2021-06-03 Thread David Spickett via cfe-commits

Author: David Spickett
Date: 2021-06-03T08:55:44Z
New Revision: f4543dce5db585f2b37f39145ad3fa34b6c75b0e

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

LOG: [clang][ARM] Remove arm2/3/6/7m CPU names

These legacy CPUs are known to clang but not llvm.
Their use was ignored by llvm and it would print a
warning saying it did not recognise them.

However because some of them are default CPUs for their
architecture, you would get those warnings even if you didn't
choose a cpu explicitly.
(now those architectures will default to a "generic" CPU)

Information is thin on the ground for these older chips
so this is the best I could find:
https://en.wikichip.org/wiki/acorn/microarchitectures/arm2
https://en.wikichip.org/wiki/acorn/microarchitectures/arm3
https://en.wikichip.org/wiki/arm_holdings/microarchitectures/arm6
https://en.wikichip.org/wiki/arm_holdings/microarchitectures/arm7

Final part of fixing https://bugs.llvm.org/show_bug.cgi?id=50454.

Reviewed By: efriedma

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

Added: 


Modified: 
clang/test/Misc/target-invalid-cpu-note.c
llvm/include/llvm/Support/ARMTargetParser.def
llvm/unittests/Support/TargetParserTest.cpp

Removed: 




diff  --git a/clang/test/Misc/target-invalid-cpu-note.c 
b/clang/test/Misc/target-invalid-cpu-note.c
index b25325a412d23..6d5e0df9acc92 100644
--- a/clang/test/Misc/target-invalid-cpu-note.c
+++ b/clang/test/Misc/target-invalid-cpu-note.c
@@ -1,7 +1,7 @@
 // RUN: not %clang_cc1 -triple armv5--- -target-cpu not-a-cpu -fsyntax-only %s 
2>&1 | FileCheck %s --check-prefix ARM
 // ARM: error: unknown target CPU 'not-a-cpu'
 // ARM: note: valid target CPU values are:
-// ARM-SAME: arm2
+// ARM-SAME: arm8
 
 // RUN: not %clang_cc1 -triple arm64--- -target-cpu not-a-cpu -fsyntax-only %s 
2>&1 | FileCheck %s --check-prefix AARCH64
 // AARCH64: error: unknown target CPU 'not-a-cpu'

diff  --git a/llvm/include/llvm/Support/ARMTargetParser.def 
b/llvm/include/llvm/Support/ARMTargetParser.def
index 6ce857a43e000..14b169a6e 100644
--- a/llvm/include/llvm/Support/ARMTargetParser.def
+++ b/llvm/include/llvm/Support/ARMTargetParser.def
@@ -201,10 +201,6 @@ ARM_HW_DIV_NAME("arm,thumb", (ARM::AEK_HWDIVARM | 
ARM::AEK_HWDIVTHUMB))
 #ifndef ARM_CPU_NAME
 #define ARM_CPU_NAME(NAME, ID, DEFAULT_FPU, IS_DEFAULT, DEFAULT_EXT)
 #endif
-ARM_CPU_NAME("arm2", ARMV2, FK_NONE, true, ARM::AEK_NONE)
-ARM_CPU_NAME("arm3", ARMV2A, FK_NONE, true, ARM::AEK_NONE)
-ARM_CPU_NAME("arm6", ARMV3, FK_NONE, true, ARM::AEK_NONE)
-ARM_CPU_NAME("arm7m", ARMV3M, FK_NONE, true, ARM::AEK_NONE)
 ARM_CPU_NAME("arm8", ARMV4, FK_NONE, false, ARM::AEK_NONE)
 ARM_CPU_NAME("arm810", ARMV4, FK_NONE, false, ARM::AEK_NONE)
 ARM_CPU_NAME("strongarm", ARMV4, FK_NONE, true, ARM::AEK_NONE)

diff  --git a/llvm/unittests/Support/TargetParserTest.cpp 
b/llvm/unittests/Support/TargetParserTest.cpp
index fd1ed7a0839b6..ab864b86aaf7c 100644
--- a/llvm/unittests/Support/TargetParserTest.cpp
+++ b/llvm/unittests/Support/TargetParserTest.cpp
@@ -124,10 +124,6 @@ INSTANTIATE_TEST_SUITE_P(
 ARMCPUTestParams("invalid", "invalid", "invalid", ARM::AEK_NONE, ""),
 ARMCPUTestParams("generic", "invalid", "none", ARM::AEK_NONE, ""),
 
-ARMCPUTestParams("arm2", "armv2", "none", ARM::AEK_NONE, "2"),
-ARMCPUTestParams("arm3", "armv2a", "none", ARM::AEK_NONE, "2A"),
-ARMCPUTestParams("arm6", "armv3", "none", ARM::AEK_NONE, "3"),
-ARMCPUTestParams("arm7m", "armv3m", "none", ARM::AEK_NONE, "3M"),
 ARMCPUTestParams("arm8", "armv4", "none", ARM::AEK_NONE, "4"),
 ARMCPUTestParams("arm810", "armv4", "none", ARM::AEK_NONE, "4"),
 ARMCPUTestParams("strongarm", "armv4", "none", ARM::AEK_NONE, "4"),
@@ -388,7 +384,7 @@ INSTANTIATE_TEST_SUITE_P(
  ARM::AEK_HWDIVARM | ARM::AEK_HWDIVTHUMB | 
ARM::AEK_DSP,
  "7-S")));
 
-static constexpr unsigned NumARMCPUArchs = 90;
+static constexpr unsigned NumARMCPUArchs = 86;
 
 TEST(TargetParserTest, testARMCPUArchList) {
   SmallVector List;
@@ -420,17 +416,13 @@ bool testARMArch(StringRef Arch, StringRef DefaultCPU, 
StringRef SubArch,
 
 TEST(TargetParserTest, testARMArch) {
   EXPECT_TRUE(
-  testARMArch("armv2", "arm2", "v2",
-  ARMBuildAttrs::CPUArch::Pre_v4));
+  testARMArch("armv2", "generic", "v2", ARMBuildAttrs::CPUArch::Pre_v4));
   EXPECT_TRUE(
-  testARMArch("armv2a", "arm3", "v2a",
-  ARMBuildAttrs::CPUArch::Pre_v4));
+  testARMArch("armv2a", "generic", "v2a", ARMBuildAttrs::CPUArch::Pre_v4));
   EXPECT_TRUE(
-  testARMArch("armv3", "arm6", "v3",
-  ARMBuildAttrs::CPUArch::Pre_v4));
+  testARMArch("armv3", "generic", 

[PATCH] D103452: [clang] Fix reading long doubles with va_arg on x86_64 mingw

2021-06-03 Thread Martin Storsjö via Phabricator via cfe-commits
mstorsjo updated this revision to Diff 349491.
mstorsjo added a comment.

Updated to not require the types to be either `isAggregateTypeForABI(Ty)` or 
`Ty->isMemberPointerType()`, just check the size of the type, added a testcase 
for `__int128` (which I tested against GCC).


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D103452

Files:
  clang/lib/CodeGen/TargetInfo.cpp
  clang/test/CodeGen/mingw-long-double.c
  clang/test/CodeGen/win64-i128.c


Index: clang/test/CodeGen/win64-i128.c
===
--- clang/test/CodeGen/win64-i128.c
+++ clang/test/CodeGen/win64-i128.c
@@ -14,3 +14,14 @@
 
 // GNU64: define dso_local <2 x i64> @bar(i128* %0, i128* %1)
 // MSC64: define dso_local <2 x i64> @bar(i128* %0, i128* %1)
+
+void vararg(int a, ...) {
+  // GNU64-LABEL: define{{.*}} void @vararg
+  // MSC64-LABEL: define{{.*}} void @vararg
+  __builtin_va_list ap;
+  __builtin_va_start(ap, a);
+  int128_t i = __builtin_va_arg(ap, int128_t);
+  // GNU64: bitcast i8* %argp.cur to i128**
+  // MSC64: bitcast i8* %argp.cur to i128**
+  __builtin_va_end(ap);
+}
Index: clang/test/CodeGen/mingw-long-double.c
===
--- clang/test/CodeGen/mingw-long-double.c
+++ clang/test/CodeGen/mingw-long-double.c
@@ -45,3 +45,16 @@
 // GNU32: declare dso_local void @__mulxc3
 // GNU64: declare dso_local void @__mulxc3
 // MSC64: declare dso_local void @__muldc3
+
+void VarArgLD(int a, ...) {
+  // GNU32-LABEL: define{{.*}} void @VarArgLD
+  // GNU64-LABEL: define{{.*}} void @VarArgLD
+  // MSC64-LABEL: define{{.*}} void @VarArgLD
+  __builtin_va_list ap;
+  __builtin_va_start(ap, a);
+  long double LD = __builtin_va_arg(ap, long double);
+  // GNU32: bitcast i8* %argp.cur to x86_fp80*
+  // GNU64: bitcast i8* %argp.cur to x86_fp80**
+  // MSC64: bitcast i8* %argp.cur to double*
+  __builtin_va_end(ap);
+}
Index: clang/lib/CodeGen/TargetInfo.cpp
===
--- clang/lib/CodeGen/TargetInfo.cpp
+++ clang/lib/CodeGen/TargetInfo.cpp
@@ -4358,15 +4358,10 @@
 
 Address WinX86_64ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
 QualType Ty) const {
-
-  bool IsIndirect = false;
-
   // MS x64 ABI requirement: "Any argument that doesn't fit in 8 bytes, or is
   // not 1, 2, 4, or 8 bytes, must be passed by reference."
-  if (isAggregateTypeForABI(Ty) || Ty->isMemberPointerType()) {
-uint64_t Width = getContext().getTypeSize(Ty);
-IsIndirect = Width > 64 || !llvm::isPowerOf2_64(Width);
-  }
+  uint64_t Width = getContext().getTypeSize(Ty);
+  bool IsIndirect = Width > 64 || !llvm::isPowerOf2_64(Width);
 
   return emitVoidPtrVAArg(CGF, VAListAddr, Ty, IsIndirect,
   CGF.getContext().getTypeInfoInChars(Ty),


Index: clang/test/CodeGen/win64-i128.c
===
--- clang/test/CodeGen/win64-i128.c
+++ clang/test/CodeGen/win64-i128.c
@@ -14,3 +14,14 @@
 
 // GNU64: define dso_local <2 x i64> @bar(i128* %0, i128* %1)
 // MSC64: define dso_local <2 x i64> @bar(i128* %0, i128* %1)
+
+void vararg(int a, ...) {
+  // GNU64-LABEL: define{{.*}} void @vararg
+  // MSC64-LABEL: define{{.*}} void @vararg
+  __builtin_va_list ap;
+  __builtin_va_start(ap, a);
+  int128_t i = __builtin_va_arg(ap, int128_t);
+  // GNU64: bitcast i8* %argp.cur to i128**
+  // MSC64: bitcast i8* %argp.cur to i128**
+  __builtin_va_end(ap);
+}
Index: clang/test/CodeGen/mingw-long-double.c
===
--- clang/test/CodeGen/mingw-long-double.c
+++ clang/test/CodeGen/mingw-long-double.c
@@ -45,3 +45,16 @@
 // GNU32: declare dso_local void @__mulxc3
 // GNU64: declare dso_local void @__mulxc3
 // MSC64: declare dso_local void @__muldc3
+
+void VarArgLD(int a, ...) {
+  // GNU32-LABEL: define{{.*}} void @VarArgLD
+  // GNU64-LABEL: define{{.*}} void @VarArgLD
+  // MSC64-LABEL: define{{.*}} void @VarArgLD
+  __builtin_va_list ap;
+  __builtin_va_start(ap, a);
+  long double LD = __builtin_va_arg(ap, long double);
+  // GNU32: bitcast i8* %argp.cur to x86_fp80*
+  // GNU64: bitcast i8* %argp.cur to x86_fp80**
+  // MSC64: bitcast i8* %argp.cur to double*
+  __builtin_va_end(ap);
+}
Index: clang/lib/CodeGen/TargetInfo.cpp
===
--- clang/lib/CodeGen/TargetInfo.cpp
+++ clang/lib/CodeGen/TargetInfo.cpp
@@ -4358,15 +4358,10 @@
 
 Address WinX86_64ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
 QualType Ty) const {
-
-  bool IsIndirect = false;
-
   // MS x64 ABI requirement: "Any argument that doesn't fit in 8 bytes, or is
   // not 1, 2, 4, or 8 bytes, must be passed by reference."
-  if (isAggregateTypeForABI(Ty) || Ty->isMemberPointerTyp

[clang] dcd7664 - Add -fno-visibility-inlines-hidden option

2021-06-03 Thread Yi Kong via cfe-commits

Author: Yi Kong
Date: 2021-06-03T17:07:53+08:00
New Revision: dcd7664f92d30f93a4c7d48314d653e044093784

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

LOG: Add -fno-visibility-inlines-hidden option

This allows overriding -fvisibility-inlines-hidden.

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

Added: 
clang/test/Driver/visibility-inlines-hidden.cpp

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

Removed: 




diff  --git a/clang/include/clang/Driver/Options.td 
b/clang/include/clang/Driver/Options.td
index 076ce3f85fa8e..4945538ec0f01 100644
--- a/clang/include/clang/Driver/Options.td
+++ b/clang/include/clang/Driver/Options.td
@@ -2675,9 +2675,10 @@ def fvisibility_externs_nodllstorageclass_EQ : 
Joined<["-"], "fvisibility-extern
   ShouldParseIf;
 def fvisibility_EQ : Joined<["-"], "fvisibility=">, Group,
   HelpText<"Set the default symbol visibility for all global declarations">, 
Values<"hidden,default">;
-def fvisibility_inlines_hidden : Flag<["-"], "fvisibility-inlines-hidden">, 
Group,
-  HelpText<"Give inline C++ member functions hidden visibility by default">,
-  Flags<[CC1Option]>, MarshallingInfoFlag>;
+defm visibility_inlines_hidden : BoolFOption<"visibility-inlines-hidden",
+  LangOpts<"InlineVisibilityHidden">, DefaultFalse,
+  PosFlag,
+  NegFlag>;
 defm visibility_inlines_hidden_static_local_var : 
BoolFOption<"visibility-inlines-hidden-static-local-var",
   LangOpts<"VisibilityInlinesHiddenStaticLocalVar">, DefaultFalse,
   PosFlaggetAsString(Args) << TripleStr;
   }
 
-  Args.AddLastArg(CmdArgs, options::OPT_fvisibility_inlines_hidden);
+
+  if (Args.hasFlag(options::OPT_fvisibility_inlines_hidden,
+options::OPT_fno_visibility_inlines_hidden, false))
+CmdArgs.push_back("-fvisibility-inlines-hidden");
+
   Args.AddLastArg(CmdArgs, 
options::OPT_fvisibility_inlines_hidden_static_local_var,

options::OPT_fno_visibility_inlines_hidden_static_local_var);
   Args.AddLastArg(CmdArgs, options::OPT_fvisibility_global_new_delete_hidden);

diff  --git a/clang/test/Driver/visibility-inlines-hidden.cpp 
b/clang/test/Driver/visibility-inlines-hidden.cpp
new file mode 100644
index 0..643618c673393
--- /dev/null
+++ b/clang/test/Driver/visibility-inlines-hidden.cpp
@@ -0,0 +1,7 @@
+// RUN: %clang -### -S -fno-visibility-inlines-hidden 
-fvisibility-inlines-hidden %s 2>&1 | \
+// RUN:   FileCheck -check-prefix=CHECK-1 %s
+// CHECK-1: "-fvisibility-inlines-hidden"
+
+// RUN: %clang -### -S -fvisibility-inlines-hidden 
-fno-visibility-inlines-hidden %s 2>&1 | \
+// RUN:   FileCheck -check-prefix=CHECK-2 %s
+// CHECK-2-NOT: "-fvisibility-inlines-hidden"



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


[PATCH] D103537: [clang][driver] Add -fno-visibility-inlines-hidden option

2021-06-03 Thread Yi Kong 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 rGdcd7664f92d3: Add -fno-visibility-inlines-hidden option 
(authored by kongyi).
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

Changed prior to commit:
  https://reviews.llvm.org/D103537?vs=349470&id=349492#toc

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D103537

Files:
  clang/include/clang/Driver/Options.td
  clang/lib/Driver/ToolChains/Clang.cpp
  clang/test/Driver/visibility-inlines-hidden.cpp


Index: clang/test/Driver/visibility-inlines-hidden.cpp
===
--- /dev/null
+++ clang/test/Driver/visibility-inlines-hidden.cpp
@@ -0,0 +1,7 @@
+// RUN: %clang -### -S -fno-visibility-inlines-hidden 
-fvisibility-inlines-hidden %s 2>&1 | \
+// RUN:   FileCheck -check-prefix=CHECK-1 %s
+// CHECK-1: "-fvisibility-inlines-hidden"
+
+// RUN: %clang -### -S -fvisibility-inlines-hidden 
-fno-visibility-inlines-hidden %s 2>&1 | \
+// RUN:   FileCheck -check-prefix=CHECK-2 %s
+// CHECK-2-NOT: "-fvisibility-inlines-hidden"
Index: clang/lib/Driver/ToolChains/Clang.cpp
===
--- clang/lib/Driver/ToolChains/Clang.cpp
+++ clang/lib/Driver/ToolChains/Clang.cpp
@@ -5644,7 +5644,11 @@
   << A->getAsString(Args) << TripleStr;
   }
 
-  Args.AddLastArg(CmdArgs, options::OPT_fvisibility_inlines_hidden);
+
+  if (Args.hasFlag(options::OPT_fvisibility_inlines_hidden,
+options::OPT_fno_visibility_inlines_hidden, false))
+CmdArgs.push_back("-fvisibility-inlines-hidden");
+
   Args.AddLastArg(CmdArgs, 
options::OPT_fvisibility_inlines_hidden_static_local_var,

options::OPT_fno_visibility_inlines_hidden_static_local_var);
   Args.AddLastArg(CmdArgs, options::OPT_fvisibility_global_new_delete_hidden);
Index: clang/include/clang/Driver/Options.td
===
--- clang/include/clang/Driver/Options.td
+++ clang/include/clang/Driver/Options.td
@@ -2675,9 +2675,10 @@
   ShouldParseIf;
 def fvisibility_EQ : Joined<["-"], "fvisibility=">, Group,
   HelpText<"Set the default symbol visibility for all global declarations">, 
Values<"hidden,default">;
-def fvisibility_inlines_hidden : Flag<["-"], "fvisibility-inlines-hidden">, 
Group,
-  HelpText<"Give inline C++ member functions hidden visibility by default">,
-  Flags<[CC1Option]>, MarshallingInfoFlag>;
+defm visibility_inlines_hidden : BoolFOption<"visibility-inlines-hidden",
+  LangOpts<"InlineVisibilityHidden">, DefaultFalse,
+  PosFlag,
+  NegFlag>;
 defm visibility_inlines_hidden_static_local_var : 
BoolFOption<"visibility-inlines-hidden-static-local-var",
   LangOpts<"VisibilityInlinesHiddenStaticLocalVar">, DefaultFalse,
   PosFlagIndex: clang/test/Driver/visibility-inlines-hidden.cpp
===
--- /dev/null
+++ clang/test/Driver/visibility-inlines-hidden.cpp
@@ -0,0 +1,7 @@
+// RUN: %clang -### -S -fno-visibility-inlines-hidden -fvisibility-inlines-hidden %s 2>&1 | \
+// RUN:   FileCheck -check-prefix=CHECK-1 %s
+// CHECK-1: "-fvisibility-inlines-hidden"
+
+// RUN: %clang -### -S -fvisibility-inlines-hidden -fno-visibility-inlines-hidden %s 2>&1 | \
+// RUN:   FileCheck -check-prefix=CHECK-2 %s
+// CHECK-2-NOT: "-fvisibility-inlines-hidden"
Index: clang/lib/Driver/ToolChains/Clang.cpp
===
--- clang/lib/Driver/ToolChains/Clang.cpp
+++ clang/lib/Driver/ToolChains/Clang.cpp
@@ -5644,7 +5644,11 @@
   << A->getAsString(Args) << TripleStr;
   }
 
-  Args.AddLastArg(CmdArgs, options::OPT_fvisibility_inlines_hidden);
+
+  if (Args.hasFlag(options::OPT_fvisibility_inlines_hidden,
+options::OPT_fno_visibility_inlines_hidden, false))
+CmdArgs.push_back("-fvisibility-inlines-hidden");
+
   Args.AddLastArg(CmdArgs, options::OPT_fvisibility_inlines_hidden_static_local_var,
options::OPT_fno_visibility_inlines_hidden_static_local_var);
   Args.AddLastArg(CmdArgs, options::OPT_fvisibility_global_new_delete_hidden);
Index: clang/include/clang/Driver/Options.td
===
--- clang/include/clang/Driver/Options.td
+++ clang/include/clang/Driver/Options.td
@@ -2675,9 +2675,10 @@
   ShouldParseIf;
 def fvisibility_EQ : Joined<["-"], "fvisibility=">, Group,
   HelpText<"Set the default symbol visibility for all global declarations">, Values<"hidden,default">;
-def fvisibility_inlines_hidden : Flag<["-"], "fvisibility-inlines-hidden">, Group,
-  HelpText<"Give inline C++ member functions hidden visibility by default">,
-  Flags<[CC1Option]>, MarshallingInfoFlag>;
+defm visibility_inlin

[PATCH] D103231: [clang][AST] Set correct DeclContext in ASTImporter lookup table for ParmVarDecl.

2021-06-03 Thread Balázs Kéri via Phabricator via cfe-commits
balazske updated this revision to Diff 349496.
balazske marked an inline comment as done.
balazske added a comment.

Added `contains` for correct check of `ASTImporterLookupTable` content.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D103231

Files:
  clang/include/clang/AST/ASTImporterLookupTable.h
  clang/lib/AST/ASTImporter.cpp
  clang/lib/AST/ASTImporterLookupTable.cpp
  clang/unittests/AST/ASTImporterTest.cpp

Index: clang/unittests/AST/ASTImporterTest.cpp
===
--- clang/unittests/AST/ASTImporterTest.cpp
+++ clang/unittests/AST/ASTImporterTest.cpp
@@ -5375,6 +5375,33 @@
   CheckError(FromFooC);
 }
 
+TEST_P(ErrorHandlingTest, ODRViolationWithinParmVarDecls) {
+  // Importing of 'f' and parameter 'P' should cause an ODR error.
+  // The error happens after the ParmVarDecl for 'P' was already created.
+  // This is a special case because the ParmVarDecl has a temporary DeclContext.
+  // Expected is no crash at error handling of ASTImporter.
+  constexpr auto ToTUCode = R"(
+  struct X {
+char A;
+  };
+  )";
+  constexpr auto FromTUCode = R"(
+  struct X {
+enum Y { Z };
+  };
+  void f(int P = X::Z);
+  )";
+  Decl *ToTU = getToTuDecl(ToTUCode, Lang_CXX11);
+  static_cast(ToTU);
+  Decl *FromTU = getTuDecl(FromTUCode, Lang_CXX11);
+  auto *FromF = FirstDeclMatcher().match(
+  FromTU, functionDecl(hasName("f")));
+  ASSERT_TRUE(FromF);
+
+  auto *ImportedF = Import(FromF, Lang_CXX11);
+  EXPECT_FALSE(ImportedF);
+}
+
 TEST_P(ASTImporterOptionSpecificTestBase, LambdaInFunctionBody) {
   Decl *FromTU = getTuDecl(
   R"(
@@ -6192,6 +6219,21 @@
   ASSERT_TRUE(ToD);
 }
 
+TEST_P(ImportFunctions, ParmVarDeclDeclContext) {
+  constexpr auto FromTUCode = R"(
+  void f(int P);
+  )";
+  Decl *FromTU = getTuDecl(FromTUCode, Lang_CXX11);
+  auto *FromF = FirstDeclMatcher().match(
+  FromTU, functionDecl(hasName("f")));
+  ASSERT_TRUE(FromF);
+
+  auto *ImportedF = Import(FromF, Lang_CXX11);
+  EXPECT_TRUE(ImportedF);
+  EXPECT_TRUE(SharedStatePtr->getLookupTable()->contains(
+  ImportedF, ImportedF->getParamDecl(0)));
+}
+
 // FIXME Move these tests out of ASTImporterTest. For that we need to factor
 // out the ASTImporter specific pars from ASTImporterOptionSpecificTestBase
 // into a new test Fixture. Then we should lift up this Fixture to its own
Index: clang/lib/AST/ASTImporterLookupTable.cpp
===
--- clang/lib/AST/ASTImporterLookupTable.cpp
+++ clang/lib/AST/ASTImporterLookupTable.cpp
@@ -117,6 +117,17 @@
 remove(ReDC, ND);
 }
 
+void ASTImporterLookupTable::update(NamedDecl *ND, DeclContext *OldDC) {
+  assert(OldDC != ND->getDeclContext());
+  if (contains(ND->getDeclContext(), ND)) {
+assert(!contains(OldDC, ND));
+return;
+  }
+
+  remove(OldDC, ND);
+  add(ND);
+}
+
 ASTImporterLookupTable::LookupResult
 ASTImporterLookupTable::lookup(DeclContext *DC, DeclarationName Name) const {
   auto DCI = LookupTable.find(DC->getPrimaryContext());
@@ -131,6 +142,10 @@
   return NamesI->second;
 }
 
+bool ASTImporterLookupTable::contains(DeclContext *DC, NamedDecl *ND) const {
+  return 0 < lookup(DC, ND->getDeclName()).count(ND);
+}
+
 void ASTImporterLookupTable::dump(DeclContext *DC) const {
   auto DCI = LookupTable.find(DC->getPrimaryContext());
   if (DCI == LookupTable.end())
Index: clang/lib/AST/ASTImporter.cpp
===
--- clang/lib/AST/ASTImporter.cpp
+++ clang/lib/AST/ASTImporter.cpp
@@ -3503,6 +3503,8 @@
   for (auto *Param : Parameters) {
 Param->setOwningFunction(ToFunction);
 ToFunction->addDeclInternal(Param);
+if (ASTImporterLookupTable *LT = Importer.SharedState->getLookupTable())
+  LT->update(Param, Importer.getToContext().getTranslationUnitDecl());
   }
   ToFunction->setParams(Parameters);
 
Index: clang/include/clang/AST/ASTImporterLookupTable.h
===
--- clang/include/clang/AST/ASTImporterLookupTable.h
+++ clang/include/clang/AST/ASTImporterLookupTable.h
@@ -63,8 +63,24 @@
   ASTImporterLookupTable(TranslationUnitDecl &TU);
   void add(NamedDecl *ND);
   void remove(NamedDecl *ND);
+  // Sometimes a declaration is created first with a temporarily value of decl
+  // context (often the translation unit) and later moved to the final context.
+  // This happens for declarations that are created before the final declaration
+  // context. In such cases the lookup table needs to be updated.
+  // (The declaration is in these cases not added to the temporary decl context,
+  // only its parent is set.)
+  // FIXME: It would be better to not add the declaration to the temporary
+  // context at all in the lookup table, but this requires big change in
+  // ASTImporter.
+  // 

[PATCH] D103386: [PowerPC] Fix x86 vector intrinsics wrapper compilation under C++

2021-06-03 Thread Bjorn Pettersson via Phabricator via cfe-commits
bjope added inline comments.



Comment at: clang/test/CodeGen/ppc-xmmintrin.c:10
 // RUN:   -fno-discard-value-names -mllvm -disable-llvm-optzns -o - | 
llvm-cxxfilt -n | FileCheck %s --check-prefixes=CHECK,CHECK-LE
+// RUN: %clang -x c++ -fsyntax-only -target powerpc64le-unknown-linux-gnu 
-mcpu=pwr8 -ffreestanding -DNO_WARN_X86_INTRINSICS %s \
+// RUN:   -fno-discard-value-names -mllvm -disable-llvm-optzns

qiucf wrote:
> bjope wrote:
> > Unfortunately I get some failures with this. Maybe because of an unstandard 
> > build setup.
> > 
> > We've started to use `-DCLANG_DEFAULT_RTLIB=compiler-rt 
> > -DCLANG_DEFAULT_CXX_STDLIB=libc++` when building clang. And we also use 
> > `-DLLVM_ENABLE_PER_TARGET_RUNTIME_DIR=ON`. Not sure if that is a setup that 
> > is asking for trouble. Anyway, when running this test case we end up with
> > 
> > ```
> > : 'RUN: at line 10';   /workspace/llvm/build/bin/clang -x c++ -fsyntax-only 
> > -target powerpc64le-unknown-linux-gnu -mcpu=pwr8 -ffreestanding 
> > -DNO_WARN_X86_INTRINSICS /workspace/clang/test/CodeGen/ppc-xmmintrin.c
> > -fno-discard-value-names -mllvm -disable-llvm-optzns
> > --
> > Exit Code: 1
> > 
> > Command Output (stderr):
> > --
> > In file included from /workspace/clang/test/CodeGen/ppc-xmmintrin.c:13:
> > In file included from 
> > /workspace/llvm/build/lib/clang/13.0.0/include/ppc_wrappers/xmmintrin.h:42:
> > In file included from 
> > /workspace/llvm/build/lib/clang/13.0.0/include/altivec.h:44:
> > In file included from 
> > /workspace/llvm/build/bin/../include/c++/v1/stddef.h:39:
> > /workspace/llvm/build/bin/../include/c++/v1/__config:13:10: fatal error: 
> > '__config_site' file not found
> > #include <__config_site>
> >  ^~~
> > 1 error generated.
> > ```
> > 
> > Not sure really how to solve that.
> > 
> > Maybe we should stop building like that?
> > 
> > Or there is a bug somewhere (such as that we only get the __config_site 
> > headers in target specific dirs for targets that we actually build runtimes 
> > for, maybe something that was missing in https://reviews.llvm.org/D97572)?
> > (Maybe @phosek  could comment on that?)
> > 
> > Or this test case is missing some options to make it a bit more independent 
> > on the runtimes build setup?
> > 
> The tests relies on some system stuff. Is the failure related to this change? 
> (or exposed by `-x c++` option?)
Well, i guess it was exposed by `-x c++` (in combination with D975729).

I don't really understand how things are supposed to work given the pre-target 
specific `__config_site`.

Since I only build libcxx for `x86_64-unknown-linux-gnu`, I only get a 
`__config_site` file for that specific triple inside 
`bin/../include/x86_64-unknown-linux-gnu/c++/v1/__config_site` in the build 
result. But a test case like this one, using a different triple, ends up 
including `bin/../include/c++/v1/stddef.h`, that wants wants to include 
`<__config_site>`, but it won't find any such include for the 
powerpc64le-unknown-linux-gnu triple.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D103386

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


[PATCH] D103603: [Sema][RISCV] Allow ?: to select Typedef BuiltinType in C

2021-06-03 Thread ShihPo Hung via Phabricator via cfe-commits
arcbbb created this revision.
arcbbb added reviewers: rsandifo-arm, efriedma, sdesmalen, rovka, rjmccall, 
rengolin, HsiangKai, craig.topper.
Herald added subscribers: vkmr, frasercrmck, evandro, luismarques, apazos, 
sameer.abuasal, s.egerton, Jim, benna, psnobl, jocewei, PkmX, the_o, 
brucehoult, MartinMosbeck, rogfer01, edward-jones, zzheng, jrtc27, shiva0217, 
kito-cheng, niosHD, sabuasal, simoncook, johnrusso, rbar, asb.
arcbbb requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

This patch solves an error such as:

  incompatible operand types ('vbool4_t' (aka '__rvv_bool4_t') and 
'__rvv_bool4_t')

when one of the value is a TypedefType of the other value in ?:.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D103603

Files:
  clang/lib/Sema/SemaExpr.cpp
  clang/test/Sema/riscv-types.c


Index: clang/test/Sema/riscv-types.c
===
--- clang/test/Sema/riscv-types.c
+++ clang/test/Sema/riscv-types.c
@@ -134,3 +134,12 @@
   // CHECK: __rvv_int8mf2_t x43;
   __rvv_int8mf2_t x43;
 }
+
+typedef __rvv_bool4_t vbool4_t;
+__rvv_bool4_t get_rvv_bool4();
+vbool4_t get_vbool4_t();
+
+void func1(int sel) {
+  // CHECK: vbool4_t t0 = sel ? get_rvv_bool4() : get_vbool4_t();
+  vbool4_t t0 = sel ? get_rvv_bool4() : get_vbool4_t();
+}
Index: clang/lib/Sema/SemaExpr.cpp
===
--- clang/lib/Sema/SemaExpr.cpp
+++ clang/lib/Sema/SemaExpr.cpp
@@ -8393,8 +8393,10 @@
 
   // Allow ?: operations in which both operands have the same
   // built-in sizeless type.
-  if (LHSTy->isSizelessBuiltinType() && LHSTy == RHSTy)
+  if (LHSTy->isSizelessBuiltinType() &&
+  (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy))) {
 return LHSTy;
+  }
 
   // Emit a better diagnostic if one of the expressions is a null pointer
   // constant and the other is not a pointer type. In this case, the user most


Index: clang/test/Sema/riscv-types.c
===
--- clang/test/Sema/riscv-types.c
+++ clang/test/Sema/riscv-types.c
@@ -134,3 +134,12 @@
   // CHECK: __rvv_int8mf2_t x43;
   __rvv_int8mf2_t x43;
 }
+
+typedef __rvv_bool4_t vbool4_t;
+__rvv_bool4_t get_rvv_bool4();
+vbool4_t get_vbool4_t();
+
+void func1(int sel) {
+  // CHECK: vbool4_t t0 = sel ? get_rvv_bool4() : get_vbool4_t();
+  vbool4_t t0 = sel ? get_rvv_bool4() : get_vbool4_t();
+}
Index: clang/lib/Sema/SemaExpr.cpp
===
--- clang/lib/Sema/SemaExpr.cpp
+++ clang/lib/Sema/SemaExpr.cpp
@@ -8393,8 +8393,10 @@
 
   // Allow ?: operations in which both operands have the same
   // built-in sizeless type.
-  if (LHSTy->isSizelessBuiltinType() && LHSTy == RHSTy)
+  if (LHSTy->isSizelessBuiltinType() &&
+  (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy))) {
 return LHSTy;
+  }
 
   // Emit a better diagnostic if one of the expressions is a null pointer
   // constant and the other is not a pointer type. In this case, the user most
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D103595: [clang] Correct MarkFunctionReferenced for local class

2021-06-03 Thread Fütő Gergely via Phabricator via cfe-commits
futogergely updated this revision to Diff 349508.
futogergely added a comment.

clang-format


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

https://reviews.llvm.org/D103595

Files:
  clang/lib/Sema/SemaExpr.cpp
  clang/test/SemaTemplate/instantiate-local-class.cpp


Index: clang/test/SemaTemplate/instantiate-local-class.cpp
===
--- clang/test/SemaTemplate/instantiate-local-class.cpp
+++ clang/test/SemaTemplate/instantiate-local-class.cpp
@@ -504,3 +504,24 @@
   }
   template void f();
 }
+
+namespace PR48839 {
+template 
+void construct() {
+  T(0);
+}
+
+template 
+void tester() {
+  struct d {
+void test() {
+  construct();
+}
+constexpr d(T b) : a(b) {}
+
+T a;
+  };
+}
+
+void g() { tester(); }
+} // namespace PR48839
Index: clang/lib/Sema/SemaExpr.cpp
===
--- clang/lib/Sema/SemaExpr.cpp
+++ clang/lib/Sema/SemaExpr.cpp
@@ -17057,11 +17057,12 @@
   PointOfInstantiation = Loc;
 }
 
+const bool isLocalClass =
+isa(Func->getDeclContext()) &&
+cast(Func->getDeclContext())->isLocalClass();
 if (FirstInstantiation || TSK != TSK_ImplicitInstantiation ||
-Func->isConstexpr()) {
-  if (isa(Func->getDeclContext()) &&
-  cast(Func->getDeclContext())->isLocalClass() &&
-  CodeSynthesisContexts.size())
+(!isLocalClass && Func->isConstexpr())) {
+  if (isLocalClass && CodeSynthesisContexts.size())
 PendingLocalImplicitInstantiations.push_back(
 std::make_pair(Func, PointOfInstantiation));
   else if (Func->isConstexpr())


Index: clang/test/SemaTemplate/instantiate-local-class.cpp
===
--- clang/test/SemaTemplate/instantiate-local-class.cpp
+++ clang/test/SemaTemplate/instantiate-local-class.cpp
@@ -504,3 +504,24 @@
   }
   template void f();
 }
+
+namespace PR48839 {
+template 
+void construct() {
+  T(0);
+}
+
+template 
+void tester() {
+  struct d {
+void test() {
+  construct();
+}
+constexpr d(T b) : a(b) {}
+
+T a;
+  };
+}
+
+void g() { tester(); }
+} // namespace PR48839
Index: clang/lib/Sema/SemaExpr.cpp
===
--- clang/lib/Sema/SemaExpr.cpp
+++ clang/lib/Sema/SemaExpr.cpp
@@ -17057,11 +17057,12 @@
   PointOfInstantiation = Loc;
 }
 
+const bool isLocalClass =
+isa(Func->getDeclContext()) &&
+cast(Func->getDeclContext())->isLocalClass();
 if (FirstInstantiation || TSK != TSK_ImplicitInstantiation ||
-Func->isConstexpr()) {
-  if (isa(Func->getDeclContext()) &&
-  cast(Func->getDeclContext())->isLocalClass() &&
-  CodeSynthesisContexts.size())
+(!isLocalClass && Func->isConstexpr())) {
+  if (isLocalClass && CodeSynthesisContexts.size())
 PendingLocalImplicitInstantiations.push_back(
 std::make_pair(Func, PointOfInstantiation));
   else if (Func->isConstexpr())
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D103605: [analyzer] Introduce a new interface for tracking

2021-06-03 Thread Valeriy Savchenko via Phabricator via cfe-commits
vsavchenko created this revision.
vsavchenko added reviewers: NoQ, xazax.hun, martong, steakhal, Szelethus, 
manas, RedDocMD.
Herald added subscribers: ASDenysPetrov, dkrupp, donat.nagy, mikhail.ramalho, 
a.sidorin, rnkovacs, szepet, baloghadamsoftware.
vsavchenko requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

Tracking values through expressions and the stores is fundamental
for producing clear diagnostics.  However, the main components
participating in this process, namely `trackExpressionValue` and
`FindLastStoreBRVisitor`, became pretty bloated.  They have an
interesting dynamic between them (and some other visitors) that
one might call a "chain reaction". `trackExpressionValue` adds
`FindLastStoreBRVisitor`, and the latter calls `trackExpressionValue`.

Because of this design, individual checkers couldn't affect what's
going to happen somewhere in the middle of that chain.  Whether they
want to produce a more informative note or keep the overall tracking
going by utilizing some of the domain expertise.  This all lead to two
biggest problems that I see:

- Some checkers don't use it This should probably never be the case for 
path-sensitive checks.
- Some checkers incorporated their logic directly into those components This 
doesn't make the maintenance easier, breaks multiple architecture principles, 
and makes the code harder to read adn understand, thus, increasing the 
probability of the first case.

This commit introduces a prototype for a new interface that will be
responsible for tracking.  My main idea here was to make operations
that I want have as a checker developer easy to implement and hook
directly into the tracking process.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D103605

Files:
  clang/include/clang/StaticAnalyzer/Core/BugReporter/BugReporterVisitors.h
  clang/lib/StaticAnalyzer/Core/BugReporterVisitors.cpp

Index: clang/lib/StaticAnalyzer/Core/BugReporterVisitors.cpp
===
--- clang/lib/StaticAnalyzer/Core/BugReporterVisitors.cpp
+++ clang/lib/StaticAnalyzer/Core/BugReporterVisitors.cpp
@@ -65,6 +65,7 @@
 
 using namespace clang;
 using namespace ento;
+using namespace bugreporter;
 
 //===--===//
 // Utility functions.
@@ -2045,6 +2046,55 @@
   }
 }
 
+//===--===//
+//Tracker implementation
+//===--===//
+
+Tracker::Tracker(PathSensitiveBugReport &Report,
+ const StackFrameContext *Origin)
+: Report(Report), Origin(Origin) {
+  // TODO: split trackExpressionValue and FindLastStoreBRVisitor into handlers
+  //   and add them here.
+}
+
+Tracker::Result Tracker::track(const Expr *E, const ExplodedNode *N,
+   TrackingOptions Opts) {
+  if (!E || !N)
+return {};
+
+  const Expr *Inner = peelOffOuterExpr(E, N);
+  const ExplodedNode *LVNode = findNodeForExpression(N, Inner);
+  if (!LVNode)
+return {};
+
+  Result CombinedResult;
+  // Iterate through the handlers in the order according to their priorities.
+  for (ExpressionHandlerPtr &Handler : ExpressionHandlers) {
+CombinedResult.combineWith(Handler->handle(Inner, LVNode, Opts));
+if (CombinedResult.WasInterrupted)
+  break;
+  }
+
+  return CombinedResult;
+}
+
+Tracker::Result Tracker::track(KnownSVal V, const MemRegion *R,
+   const ExplodedNode *N, TrackingOptions Opts) {
+  // TODO: support this operation after dismantling FindLastStoreBRVisitor
+  return {};
+}
+
+PathDiagnosticPieceRef Tracker::handle(StoreInfo SI, TrackingOptions Opts) {
+  // Iterate through the handlers in the order according to their priorities.
+  for (StoreHandlerPtr &Handler : StoreHandlers) {
+if (PathDiagnosticPieceRef Result = Handler->handle(SI, Opts))
+  // If the handler produced a non-null piece, return it.
+  // There is no need in asking other handlers.
+  return Result;
+  }
+  return {};
+}
+
 bool bugreporter::trackExpressionValue(const ExplodedNode *InputNode,
const Expr *E,
PathSensitiveBugReport &report,
Index: clang/include/clang/StaticAnalyzer/Core/BugReporter/BugReporterVisitors.h
===
--- clang/include/clang/StaticAnalyzer/Core/BugReporter/BugReporterVisitors.h
+++ clang/include/clang/StaticAnalyzer/Core/BugReporter/BugReporterVisitors.h
@@ -21,7 +21,9 @@
 #include "llvm/ADT/FoldingSet.h"
 #include "llvm/ADT/STLExtras.h"
 #include "llvm/ADT/StringRef.h"
+#include 
 #include 
+#include 
 
 namespace clang {
 
@@ -99,6 +101,230 @@
   Condition
 };
 
+/// Defines a set of options altering tracking behavior.
+stru

[PATCH] D101156: [Clang] Support a user-defined __dso_handle

2021-06-03 Thread Andrew Savonichev via Phabricator via cfe-commits
asavonic added a comment.

ping


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D101156

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


[PATCH] D103603: [Sema][RISCV] Allow ?: to select Typedef BuiltinType in C

2021-06-03 Thread Kito Cheng via Phabricator via cfe-commits
kito-cheng added a comment.

Testcase for AArch64/SVE:

  #include 
  
  svint8_t a();
  __SVInt8_t b();
  
  svint8_t foo(int cond){
return cond ? a(): b();
  }


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D103603

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


[PATCH] D103603: [Sema][RISCV] Allow ?: to select Typedef BuiltinType in C

2021-06-03 Thread Kito Cheng via Phabricator via cfe-commits
kito-cheng added a comment.

The testcase I provided in last comment could be compile successfully with 
aarch64-gcc, but failed on clang.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D103603

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


[PATCH] D103605: [analyzer] Introduce a new interface for tracking

2021-06-03 Thread Valeriy Savchenko via Phabricator via cfe-commits
vsavchenko updated this revision to Diff 349511.
vsavchenko added a comment.

Add docstring for StoreHandler


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D103605

Files:
  clang/include/clang/StaticAnalyzer/Core/BugReporter/BugReporterVisitors.h
  clang/lib/StaticAnalyzer/Core/BugReporterVisitors.cpp

Index: clang/lib/StaticAnalyzer/Core/BugReporterVisitors.cpp
===
--- clang/lib/StaticAnalyzer/Core/BugReporterVisitors.cpp
+++ clang/lib/StaticAnalyzer/Core/BugReporterVisitors.cpp
@@ -65,6 +65,7 @@
 
 using namespace clang;
 using namespace ento;
+using namespace bugreporter;
 
 //===--===//
 // Utility functions.
@@ -2045,6 +2046,55 @@
   }
 }
 
+//===--===//
+//Tracker implementation
+//===--===//
+
+Tracker::Tracker(PathSensitiveBugReport &Report,
+ const StackFrameContext *Origin)
+: Report(Report), Origin(Origin) {
+  // TODO: split trackExpressionValue and FindLastStoreBRVisitor into handlers
+  //   and add them here.
+}
+
+Tracker::Result Tracker::track(const Expr *E, const ExplodedNode *N,
+   TrackingOptions Opts) {
+  if (!E || !N)
+return {};
+
+  const Expr *Inner = peelOffOuterExpr(E, N);
+  const ExplodedNode *LVNode = findNodeForExpression(N, Inner);
+  if (!LVNode)
+return {};
+
+  Result CombinedResult;
+  // Iterate through the handlers in the order according to their priorities.
+  for (ExpressionHandlerPtr &Handler : ExpressionHandlers) {
+CombinedResult.combineWith(Handler->handle(Inner, LVNode, Opts));
+if (CombinedResult.WasInterrupted)
+  break;
+  }
+
+  return CombinedResult;
+}
+
+Tracker::Result Tracker::track(KnownSVal V, const MemRegion *R,
+   const ExplodedNode *N, TrackingOptions Opts) {
+  // TODO: support this operation after dismantling FindLastStoreBRVisitor
+  return {};
+}
+
+PathDiagnosticPieceRef Tracker::handle(StoreInfo SI, TrackingOptions Opts) {
+  // Iterate through the handlers in the order according to their priorities.
+  for (StoreHandlerPtr &Handler : StoreHandlers) {
+if (PathDiagnosticPieceRef Result = Handler->handle(SI, Opts))
+  // If the handler produced a non-null piece, return it.
+  // There is no need in asking other handlers.
+  return Result;
+  }
+  return {};
+}
+
 bool bugreporter::trackExpressionValue(const ExplodedNode *InputNode,
const Expr *E,
PathSensitiveBugReport &report,
Index: clang/include/clang/StaticAnalyzer/Core/BugReporter/BugReporterVisitors.h
===
--- clang/include/clang/StaticAnalyzer/Core/BugReporter/BugReporterVisitors.h
+++ clang/include/clang/StaticAnalyzer/Core/BugReporter/BugReporterVisitors.h
@@ -21,7 +21,9 @@
 #include "llvm/ADT/FoldingSet.h"
 #include "llvm/ADT/STLExtras.h"
 #include "llvm/ADT/StringRef.h"
+#include 
 #include 
+#include 
 
 namespace clang {
 
@@ -99,6 +101,231 @@
   Condition
 };
 
+/// Defines a set of options altering tracking behavior.
+struct TrackingOptions {
+  /// Specifies the kind of tracking.
+  TrackingKind Kind = TrackingKind::Thorough;
+  /// Specifies whether we should employ false positive suppression
+  /// (inlined defensive checks, returned null).
+  bool EnableNullFPSuppression = true;
+};
+
+struct StoreInfo {
+  enum Kind {
+/// The value got stored into the region during initialization:
+///   int x = 42;
+Initialization,
+/// The value got stored into the region during assignment:
+///   int x;
+///   x = 42;
+Assignment,
+/// The value got stored into the region as block capture.
+/// Block data is modeled as a separate region, thus whenever
+/// the analyzer sees a captured variable, its value is copied
+/// into a special block region.
+BlockCapture
+  };
+
+  /// The type of store operation.
+  Kind StoreKind;
+  /// The expression where the value comes from.
+  /// NOTE: might be null.
+  Expr *SourceOfTheValue;
+  /// Symbolic value that is being stored.
+  SVal Value;
+  /// Memory regions involved in the store operation.
+  ///   Dest <- Origin
+  /// NOTE: Origin might be null, when the stored value doesn't come
+  ///   from another region.
+  const MemRegion *Dest, *Origin;
+};
+
+class ExpressionHandler;
+class StoreHandler;
+
+/// A generalized component for tracking expressions, values, and stores.
+///
+/// Tracker aimes at providing a sensible set of default behaviors that can be
+/// used by any checker, while providing mechanisms to hook into any part of the
+/// tracking proc

[PATCH] D103603: [Sema][RISCV] Allow ?: to select Typedef BuiltinType in C

2021-06-03 Thread Richard Sandiford via Phabricator via cfe-commits
rsandifo-arm added a comment.

Thanks for the fix.  I agree this is the right behaviour FWIW.  I held off 
approving it in case there's another idiom that's preferred when comparing 
canonical types.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D103603

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


[PATCH] D103434: [analyzer] Allow visitors to run callbacks on completion

2021-06-03 Thread Valeriy Savchenko via Phabricator via cfe-commits
vsavchenko added a comment.

I was thinking a lot about this problem after our last call, and even though 
`StoppableVisitor` helps to solve the problem that we have, it is extremely 
unclear when this callback is called and should be called.
I decided to restore the balance (and rid of all younglings, maybe) and put 
together this interface: D103605 .  I still 
need to migrate the existing code into the new architecture, but it can be done 
incrementally.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D103434

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


[PATCH] D103603: [Sema][RISCV] Allow ?: to select Typedef BuiltinType in C

2021-06-03 Thread Fraser Cormack via Phabricator via cfe-commits
frasercrmck added a comment.

In D103603#2795899 , @kito-cheng 
wrote:

> Testcase for AArch64/SVE:
>
>   #include 
>   
>   svint8_t a();
>   __SVInt8_t b();
>   
>   svint8_t foo(int cond){
> return cond ? a(): b();
>   }

Could that AArch64 test also be part of this patch?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D103603

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


[PATCH] D103434: [analyzer] Allow visitors to run callbacks on completion

2021-06-03 Thread Deep Majumder via Phabricator via cfe-commits
RedDocMD added a comment.

In D103434#2795940 , @vsavchenko 
wrote:

> I was thinking a lot about this problem after our last call, and even though 
> `StoppableVisitor` helps to solve the problem that we have, it is extremely 
> unclear when this callback is called and should be called.
> I decided to restore the balance (and rid of all younglings, maybe) and put 
> together this interface: D103605 .  I still 
> need to migrate the existing code into the new architecture, but it can be 
> done incrementally.

Right. I then perhaps should focus now on D98726 
, and then return to `GetNoteEmitter`.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D103434

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


[PATCH] D100581: [Clang] -Wunused-but-set-parameter and -Wunused-but-set-variable

2021-06-03 Thread Michael Benfield via Phabricator via cfe-commits
mbenfield added a comment.

In D100581#2792854 , @Abpostelnicu 
wrote:

> I think there is a false positive with this @george.burgess.iv:
> In this 
> 
>  we have the warning triggered: 
> mozglue/baseprofiler/core/platform-linux-android.cpp:216:9: error: variable 
> 'r' set but not used [-Werror,-Wunused-but-set-variable]
>
>   SigHandlerCoordinator() {
> PodZero(&mUContext);
> int r = sem_init(&mMessage2, /* pshared */ 0, 0);
> r |= sem_init(&mMessage3, /* pshared */ 0, 0);
> r |= sem_init(&mMessage4, /* pshared */ 0, 0);
> MOZ_ASSERT(r == 0);
>   }

Indeed as pointed out above I think this is a true positive unfortunately.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D100581

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


[PATCH] D100581: [Clang] -Wunused-but-set-parameter and -Wunused-but-set-variable

2021-06-03 Thread Stephan Bergmann via Phabricator via cfe-commits
sberg added a comment.

Is it intentional that this warns about volatile variables as in

  void f(char * p) {
  volatile char c = 0;
  c ^= *p;
  }

(I see that GCC warns about volatile too, at least when you replace the `^=` 
with `=`, so assume the answer is "yes", but would just like to see that 
confirmed (ideally with a test case even?).)


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D100581

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


[PATCH] D91442: [clang][Driver] Handle risvc in Baremetal.cpp.

2021-06-03 Thread Jessica Clarke via Phabricator via cfe-commits
jrtc27 added inline comments.



Comment at: clang/lib/Driver/Driver.cpp:5216-5220
+if (toolchains::RISCVToolChain::hasGCCToolchain(*this, Args))
+  TC =
+  std::make_unique(*this, Target, 
Args);
+else
+  TC = std::make_unique(*this, Target, Args);

This has broken our use downstream. We construct a normal bare-metal 
non-multilib baremetal sysroot, no GCC involved, passed explicitly with 
--sysroot. However, BareMetal's findRISCVMultilibs unconditionally appends 
multilib paths for anything other than IMAC (always ILP32/LP64) (well, it still 
appends the path, just the multilib path is curiously empty), without filtering 
out ones that don't exist like Gnu.cpp. I assume the empty string for IMAC is a 
hack to allow most normal uses of bare-metal toolchains to work, but it breaks 
if you want hard float support (or fewer extensions).

I suspect this is best fixed by filtering out non-existent directories from 
findRISCVMultilibs (and at the same time, fixing IMAC to have a non-empty path, 
since RISCVToolChain has one for it, and we no longer need the hacky, 
insufficient workaround)?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D91442

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


[PATCH] D103603: [Sema][RISCV] Allow ?: to select Typedef BuiltinType in C

2021-06-03 Thread Jessica Clarke via Phabricator via cfe-commits
jrtc27 requested changes to this revision.
jrtc27 added inline comments.
This revision now requires changes to proceed.



Comment at: clang/lib/Sema/SemaExpr.cpp:8397
+  if (LHSTy->isSizelessBuiltinType() &&
+  (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy))) {
 return LHSTy;

This is Context.hasSameType, and the braces are unnecessary.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D103603

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


[PATCH] D103452: [clang] Fix reading long doubles with va_arg on x86_64 mingw

2021-06-03 Thread Martin Storsjö via Phabricator via cfe-commits
mstorsjo updated this revision to Diff 349517.
mstorsjo added a comment.

Updated the CodeGenCXX/ext-int.cpp testcase.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D103452

Files:
  clang/lib/CodeGen/TargetInfo.cpp
  clang/test/CodeGen/mingw-long-double.c
  clang/test/CodeGen/win64-i128.c
  clang/test/CodeGenCXX/ext-int.cpp

Index: clang/test/CodeGenCXX/ext-int.cpp
===
--- clang/test/CodeGenCXX/ext-int.cpp
+++ clang/test/CodeGenCXX/ext-int.cpp
@@ -164,10 +164,11 @@
   // LIN: store i92 %[[LOAD1]], i92*
 
   // WIN: %[[CUR1:.+]] = load i8*, i8** %[[ARGS]]
-  // WIN: %[[NEXT1:.+]] = getelementptr inbounds i8, i8* %[[CUR1]], i64 16
+  // WIN: %[[NEXT1:.+]] = getelementptr inbounds i8, i8* %[[CUR1]], i64 8
   // WIN: store i8* %[[NEXT1]], i8** %[[ARGS]]
-  // WIN: %[[BC1:.+]] = bitcast i8* %[[CUR1]] to i92*
-  // WIN: %[[LOADV1:.+]] = load i92, i92* %[[BC1]]
+  // WIN: %[[BC1:.+]] = bitcast i8* %[[CUR1]] to i92**
+  // WIN: %[[LOADP1:.+]] = load i92*, i92** %[[BC1]]
+  // WIN: %[[LOADV1:.+]] = load i92, i92* %[[LOADP1]]
   // WIN: store i92 %[[LOADV1]], i92*
 
   _ExtInt(31) B = __builtin_va_arg(args, _ExtInt(31));
@@ -215,10 +216,11 @@
   // LIN: store i129 %[[LOAD4]], i129*
 
   // WIN: %[[CUR4:.+]] = load i8*, i8** %[[ARGS]]
-  // WIN: %[[NEXT4:.+]] = getelementptr inbounds i8, i8* %[[CUR4]], i64 24
+  // WIN: %[[NEXT4:.+]] = getelementptr inbounds i8, i8* %[[CUR4]], i64 8
   // WIN: store i8* %[[NEXT4]], i8** %[[ARGS]]
-  // WIN: %[[BC4:.+]] = bitcast i8* %[[CUR4]] to i129*
-  // WIN: %[[LOADV4:.+]] = load i129, i129* %[[BC4]]
+  // WIN: %[[BC4:.+]] = bitcast i8* %[[CUR4]] to i129**
+  // WIN: %[[LOADP4:.+]] = load i129*, i129** %[[BC4]]
+  // WIN: %[[LOADV4:.+]] = load i129, i129* %[[LOADP4]]
   // WIN: store i129 %[[LOADV4]], i129*
 
   _ExtInt(16777200) E = __builtin_va_arg(args, _ExtInt(16777200));
@@ -232,10 +234,11 @@
   // LIN: store i16777200 %[[LOAD5]], i16777200*
 
   // WIN: %[[CUR5:.+]] = load i8*, i8** %[[ARGS]]
-  // WIN: %[[NEXT5:.+]] = getelementptr inbounds i8, i8* %[[CUR5]], i64 2097152
+  // WIN: %[[NEXT5:.+]] = getelementptr inbounds i8, i8* %[[CUR5]], i64 8
   // WIN: store i8* %[[NEXT5]], i8** %[[ARGS]]
-  // WIN: %[[BC5:.+]] = bitcast i8* %[[CUR5]] to i16777200*
-  // WIN: %[[LOADV5:.+]] = load i16777200, i16777200* %[[BC5]]
+  // WIN: %[[BC5:.+]] = bitcast i8* %[[CUR5]] to i16777200**
+  // WIN: %[[LOADP5:.+]] = load i16777200*, i16777200** %[[BC5]]
+  // WIN: %[[LOADV5:.+]] = load i16777200, i16777200* %[[LOADP5]]
   // WIN: store i16777200 %[[LOADV5]], i16777200*
 
   __builtin_va_end(args);
Index: clang/test/CodeGen/win64-i128.c
===
--- clang/test/CodeGen/win64-i128.c
+++ clang/test/CodeGen/win64-i128.c
@@ -14,3 +14,14 @@
 
 // GNU64: define dso_local <2 x i64> @bar(i128* %0, i128* %1)
 // MSC64: define dso_local <2 x i64> @bar(i128* %0, i128* %1)
+
+void vararg(int a, ...) {
+  // GNU64-LABEL: define{{.*}} void @vararg
+  // MSC64-LABEL: define{{.*}} void @vararg
+  __builtin_va_list ap;
+  __builtin_va_start(ap, a);
+  int128_t i = __builtin_va_arg(ap, int128_t);
+  // GNU64: bitcast i8* %argp.cur to i128**
+  // MSC64: bitcast i8* %argp.cur to i128**
+  __builtin_va_end(ap);
+}
Index: clang/test/CodeGen/mingw-long-double.c
===
--- clang/test/CodeGen/mingw-long-double.c
+++ clang/test/CodeGen/mingw-long-double.c
@@ -45,3 +45,16 @@
 // GNU32: declare dso_local void @__mulxc3
 // GNU64: declare dso_local void @__mulxc3
 // MSC64: declare dso_local void @__muldc3
+
+void VarArgLD(int a, ...) {
+  // GNU32-LABEL: define{{.*}} void @VarArgLD
+  // GNU64-LABEL: define{{.*}} void @VarArgLD
+  // MSC64-LABEL: define{{.*}} void @VarArgLD
+  __builtin_va_list ap;
+  __builtin_va_start(ap, a);
+  long double LD = __builtin_va_arg(ap, long double);
+  // GNU32: bitcast i8* %argp.cur to x86_fp80*
+  // GNU64: bitcast i8* %argp.cur to x86_fp80**
+  // MSC64: bitcast i8* %argp.cur to double*
+  __builtin_va_end(ap);
+}
Index: clang/lib/CodeGen/TargetInfo.cpp
===
--- clang/lib/CodeGen/TargetInfo.cpp
+++ clang/lib/CodeGen/TargetInfo.cpp
@@ -4358,15 +4358,10 @@
 
 Address WinX86_64ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
 QualType Ty) const {
-
-  bool IsIndirect = false;
-
   // MS x64 ABI requirement: "Any argument that doesn't fit in 8 bytes, or is
   // not 1, 2, 4, or 8 bytes, must be passed by reference."
-  if (isAggregateTypeForABI(Ty) || Ty->isMemberPointerType()) {
-uint64_t Width = getContext().getTypeSize(Ty);
-IsIndirect = Width > 64 || !llvm::isPowerOf2_64(Width);
-  }
+  uint64_t Width = getContext().getTypeSize(Ty);
+  bool IsIndirect = Width > 64 || !llvm::isPowerOf2_64(Width);

[PATCH] D91442: [clang][Driver] Handle risvc in Baremetal.cpp.

2021-06-03 Thread Hafiz Abid Qadeer via Phabricator via cfe-commits
abidh added inline comments.



Comment at: clang/lib/Driver/Driver.cpp:5216-5220
+if (toolchains::RISCVToolChain::hasGCCToolchain(*this, Args))
+  TC =
+  std::make_unique(*this, Target, 
Args);
+else
+  TC = std::make_unique(*this, Target, Args);

jrtc27 wrote:
> This has broken our use downstream. We construct a normal bare-metal 
> non-multilib baremetal sysroot, no GCC involved, passed explicitly with 
> --sysroot. However, BareMetal's findRISCVMultilibs unconditionally appends 
> multilib paths for anything other than IMAC (always ILP32/LP64) (well, it 
> still appends the path, just the multilib path is curiously empty), without 
> filtering out ones that don't exist like Gnu.cpp. I assume the empty string 
> for IMAC is a hack to allow most normal uses of bare-metal toolchains to 
> work, but it breaks if you want hard float support (or fewer extensions).
> 
> I suspect this is best fixed by filtering out non-existent directories from 
> findRISCVMultilibs (and at the same time, fixing IMAC to have a non-empty 
> path, since RISCVToolChain has one for it, and we no longer need the hacky, 
> insufficient workaround)?
IIRC the empty path was probably there to keep the non-multilib toolchain 
working. I don't mind if we remove the empty path for IMAC and all multilibs 
have non-empty paths.

I am not sure on filtering out non-existing folder though. It is a bit 
different from GNU.cpp in that we may not be using a pre-built sysroot and use 
the just-built compiler for building the runtime too. Also I am wondering what 
should happen if user wants a multilib whose runtime bits are not present in 
the toolchain. 


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D91442

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


[PATCH] D103589: [Format] Fix incorrect pointer detection

2021-06-03 Thread Marek Kurdej via Phabricator via cfe-commits
curdeius accepted this revision.
curdeius added a comment.
This revision is now accepted and ready to land.

LGTM. Thanks for fixing this!
Do you have commit rights or you need somebody to land it for you?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D103589

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


[PATCH] D91442: [clang][Driver] Handle risvc in Baremetal.cpp.

2021-06-03 Thread Jessica Clarke via Phabricator via cfe-commits
jrtc27 added inline comments.



Comment at: clang/lib/Driver/Driver.cpp:5216-5220
+if (toolchains::RISCVToolChain::hasGCCToolchain(*this, Args))
+  TC =
+  std::make_unique(*this, Target, 
Args);
+else
+  TC = std::make_unique(*this, Target, Args);

abidh wrote:
> jrtc27 wrote:
> > This has broken our use downstream. We construct a normal bare-metal 
> > non-multilib baremetal sysroot, no GCC involved, passed explicitly with 
> > --sysroot. However, BareMetal's findRISCVMultilibs unconditionally appends 
> > multilib paths for anything other than IMAC (always ILP32/LP64) (well, it 
> > still appends the path, just the multilib path is curiously empty), without 
> > filtering out ones that don't exist like Gnu.cpp. I assume the empty string 
> > for IMAC is a hack to allow most normal uses of bare-metal toolchains to 
> > work, but it breaks if you want hard float support (or fewer extensions).
> > 
> > I suspect this is best fixed by filtering out non-existent directories from 
> > findRISCVMultilibs (and at the same time, fixing IMAC to have a non-empty 
> > path, since RISCVToolChain has one for it, and we no longer need the hacky, 
> > insufficient workaround)?
> IIRC the empty path was probably there to keep the non-multilib toolchain 
> working. I don't mind if we remove the empty path for IMAC and all multilibs 
> have non-empty paths.
> 
> I am not sure on filtering out non-existing folder though. It is a bit 
> different from GNU.cpp in that we may not be using a pre-built sysroot and 
> use the just-built compiler for building the runtime too. Also I am wondering 
> what should happen if user wants a multilib whose runtime bits are not 
> present in the toolchain. 
Well we need to detect multilib vs non-multilib sysroots *somehow*, and 
everywhere else that gets done based on file or directory existence. If you 
want a multilib but don't have it, falling back on the non-multilib path and 
failing (either with incompatibility errors or missing files) seems fine to me.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D91442

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


[PATCH] D103082: [AArch64][SVE] Improve codegen for dupq SVE ACLE intrinsics

2021-06-03 Thread Bradley Smith via Phabricator via cfe-commits
bsmith updated this revision to Diff 349525.
bsmith added a comment.

- Use !isZero() in place of getZExtValue() != 0
- Add end to end tests for ptrue transformation


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D103082

Files:
  clang/lib/CodeGen/CGBuiltin.cpp
  clang/test/CodeGen/aarch64-sve-intrinsics/acle_sve_dupq-bfloat.c
  clang/test/CodeGen/aarch64-sve-intrinsics/acle_sve_dupq.c
  clang/test/CodeGen/aarch64-sve-intrinsics/acle_sve_dupq_const.c
  llvm/include/llvm/IR/IntrinsicsAArch64.td
  llvm/lib/Target/AArch64/AArch64TargetTransformInfo.cpp
  llvm/test/Transforms/InstCombine/AArch64/sve-intrinsic-opts-cmpne.ll

Index: llvm/test/Transforms/InstCombine/AArch64/sve-intrinsic-opts-cmpne.ll
===
--- /dev/null
+++ llvm/test/Transforms/InstCombine/AArch64/sve-intrinsic-opts-cmpne.ll
@@ -0,0 +1,397 @@
+; RUN: opt -S -instcombine < %s | FileCheck %s
+
+target triple = "aarch64-unknown-linux-gnu"
+
+; DUPQ b8
+
+define  @dupq_b_0() #0 {
+; CHECK-LABEL: @dupq_b_0(
+; CHECK: ret  zeroinitializer
+  %1 = tail call  @llvm.aarch64.sve.ptrue.nxv16i1(i32 31)
+  %2 = tail call  @llvm.experimental.vector.insert.nxv16i8.v16i8( undef,
+<16 x i8> , i64 0)
+  %3 = tail call  @llvm.aarch64.sve.dupq.lane.nxv16i8( %2 , i64 0)
+  %4 = tail call  @llvm.aarch64.sve.dup.x.nxv2i64(i64 0)
+  %5 = tail call  @llvm.aarch64.sve.cmpne.wide.nxv16i8( %1,  %3,  %4)
+  ret  %5
+}
+
+define  @dupq_b_d() #0 {
+; CHECK-LABEL: @dupq_b_d(
+; CHECK: %1 = call  @llvm.aarch64.sve.ptrue.nxv2i1(i32 31)
+; CHECK-NEXT: %2 = call  @llvm.aarch64.sve.convert.to.svbool.nxv2i1( %1)
+; CHECK-NEXT: ret  %2
+  %1 = tail call  @llvm.aarch64.sve.ptrue.nxv16i1(i32 31)
+  %2 = tail call  @llvm.experimental.vector.insert.nxv16i8.v16i8( undef,
+<16 x i8> , i64 0)
+  %3 = tail call  @llvm.aarch64.sve.dupq.lane.nxv16i8( %2 , i64 0)
+  %4 = tail call  @llvm.aarch64.sve.dup.x.nxv2i64(i64 0)
+  %5 = tail call  @llvm.aarch64.sve.cmpne.wide.nxv16i8( %1,  %3,  %4)
+  ret  %5
+}
+
+define  @dupq_b_w() #0 {
+; CHECK-LABEL: @dupq_b_w(
+; CHECK: %1 = call  @llvm.aarch64.sve.ptrue.nxv4i1(i32 31)
+; CHECK-NEXT: %2 = call  @llvm.aarch64.sve.convert.to.svbool.nxv4i1( %1)
+; CHECK-NEXT: ret  %2
+  %1 = tail call  @llvm.aarch64.sve.ptrue.nxv16i1(i32 31)
+  %2 = tail call  @llvm.experimental.vector.insert.nxv16i8.v16i8( undef,
+<16 x i8> , i64 0)
+  %3 = tail call  @llvm.aarch64.sve.dupq.lane.nxv16i8( %2 , i64 0)
+  %4 = tail call  @llvm.aarch64.sve.dup.x.nxv2i64(i64 0)
+  %5 = tail call  @llvm.aarch64.sve.cmpne.wide.nxv16i8( %1,  %3,  %4)
+  ret  %5
+}
+
+define  @dupq_b_h() #0 {
+; CHECK-LABEL: @dupq_b_h(
+; CHECK: %1 = call  @llvm.aarch64.sve.ptrue.nxv8i1(i32 31)
+; CHECK-NEXT: %2 = call  @llvm.aarch64.sve.convert.to.svbool.nxv8i1( %1)
+; CHECK-NEXT: ret  %2
+  %1 = tail call  @llvm.aarch64.sve.ptrue.nxv16i1(i32 31)
+  %2 = tail call  @llvm.experimental.vector.insert.nxv16i8.v16i8( undef,
+<16 x i8> , i64 0)
+  %3 = tail call  @llvm.aarch64.sve.dupq.lane.nxv16i8( %2 , i64 0)
+  %4 = tail call  @llvm.aarch64.sve.dup.x.nxv2i64(i64 0)
+  %5 = tail call  @llvm.aarch64.sve.cmpne.wide.nxv16i8( %1,  %3,  %4)
+  ret  %5
+}
+
+define  @dupq_b_b() #0 {
+; CHECK-LABEL: @dupq_b_b(
+; CHECK: %1 = call  @llvm.aarch64.sve.ptrue.nxv16i1(i32 31)
+; CHECK-NEXT: ret  %1
+  %1 = tail call  @llvm.aarch64.sve.ptrue.nxv16i1(i32 31)
+  %2 = tail call  @llvm.experimental.vector.insert.nxv16i8.v16i8( undef,
+<16 x i8> , i64 0)
+  %3 = tail call  @llvm.aarch64.sve.dupq.lane.nxv16i8( %2 , i64 0)
+  %4 = tail call  @llvm.aarch64.sve.dup.x.nxv2i64(i64 0)
+  %5 = tail call  @llvm.aarch64.sve.cmpne.wide.nxv16i8( %1,  %3,  %4)
+  ret  %5
+}
+
+; DUPQ b16
+
+define  @dupq_h_0() #0 {
+; CHECK-LABEL: @dupq_h_0(
+; CHECK: ret  zeroinitializer
+  %1 = tail call  @llvm.aarch64.sve.ptrue.nxv8i1(i32 31)
+  %2 = tail call  @llvm.experimental.vector.insert.nxv8i16.v8i16( undef,
+<8 x i16> , i64 0)
+  %3 = tail call  @llvm.aarch64.sve.dupq.lane.nxv8i16( %2 , i64 0)
+  %4 = tail call  @llvm.aarch64.sve.dup.x.nxv2i64(i64 0)
+  %5 = tail call  @llvm.aarch64.sve.cmpne.wide.nxv8i16( %1,  %3,  %4)
+  ret  %5
+}
+
+define  @dupq_h_d() #0 {
+; CHECK-LABEL: @dupq_h_d(
+; CHECK: %1 = call  @llvm.aarch64.sve.ptrue.nxv2i1(i32 31)
+; CHECK-NEXT: %2 = call  @llvm.aarch64.sve.convert.to.svbool.nxv2i1( %1)
+; CHECK-NEXT: %3 = call  @llvm.aarch64.sve.convert.from.svbool.nxv8i1( %2)
+; CHECK-NEXT: ret  %3
+  %1 = tail call  @llvm.aarch64.sve.ptrue.nxv8i1(i32 31)
+  %2 = tail call  @llvm.experimental.vector.insert.nxv8i16.v8i16( undef,
+<8 x i16> , i64 0)
+  %3 = tail call  @llvm.aarch64.sve.dupq.lane.nxv8i16( %2 , i64 0)
+  %4 = tail call  @llvm.aarch64.sve.dup.x.nxv2i64(i64 0)
+  %5 = tail call  @llvm.aarch64.sve.cmpne.wide.nxv8i16( %1,  %3,  %4)
+  ret  %5
+}
+
+define  @dupq_h_w() #0 {
+; CHECK-LABEL: @dupq_h_w(
+; CHECK: %1 = call  @llvm.aarch64.sve.ptrue.nxv4

[PATCH] D103611: Correct the behavior of va_arg checking in C++

2021-06-03 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman created this revision.
aaron.ballman added reviewers: rsmith, eli.friedman, rjmccall.
aaron.ballman requested review of this revision.
Herald added a project: clang.

Clang checks whether the type given to `va_arg` will automatically cause 
undefined behavior, but this check was issuing false positives for enumerations 
in C++. The issue turned out to be because `typesAreCompatible()` in C++ checks 
whether the types are *the same*, so this falls back on the type merging logic 
to see whether the types are mergable or not in both C and C++.

This issue was found by a user on code like:

  typedef enum {
CURLINFO_NONE,
CURLINFO_EFFECTIVE_URL,
CURLINFO_LASTONE = 60
  } CURLINFO;
  
  ...
  
  __builtin_va_arg(list, CURLINFO); // warn about CURLINFO promoting to 'int' 
being UB in C++ but not C

Given that C++ defers to C for the rules around `va_arg`, the behavior should 
be the same in both C and C++ and not diagnose because `int` and `CURLINFO` are 
compatible types.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D103611

Files:
  clang/lib/Sema/SemaExpr.cpp
  clang/test/SemaCXX/varargs.cpp


Index: clang/test/SemaCXX/varargs.cpp
===
--- clang/test/SemaCXX/varargs.cpp
+++ clang/test/SemaCXX/varargs.cpp
@@ -1,4 +1,4 @@
-// RUN: %clang_cc1 -std=c++03 -verify %s
+// RUN: %clang_cc1 -std=c++03 -Wno-c++11-extensions -verify %s
 // RUN: %clang_cc1 -std=c++11 -verify %s
 
 __builtin_va_list ap;
@@ -28,6 +28,30 @@
   };
 }
 
+// Ensure the correct behavior for promotable type UB checking.
+void promotable(int a, ...) {
+  enum Unscoped { One };
+  (void)__builtin_va_arg(ap, Unscoped); // ok
+
+  enum class Scoped { Two };
+  (void)__builtin_va_arg(ap, Scoped); // ok
+
+  enum Fixed : int { Three };
+  (void)__builtin_va_arg(ap, Fixed); // ok
+
+  enum FixedSmall : char { Four };
+  (void)__builtin_va_arg(ap, FixedSmall); // expected-warning {{second 
argument to 'va_arg' is of promotable type 'FixedSmall'; this va_arg has 
undefined behavior because arguments will be promoted to 'int'}}
+
+  enum FixedLarge : long long { Five };
+  (void)__builtin_va_arg(ap, FixedLarge); // ok
+
+  // Ensure that qualifiers are ignored.
+  (void)__builtin_va_arg(ap, const volatile int);  // ok
+
+  // Ensure that signed vs unsigned doesn't matter either.
+  (void)__builtin_va_arg(ap, unsigned int);
+}
+
 #if __cplusplus >= 201103L
 // We used to have bugs identifying the correct enclosing function scope in a
 // lambda.
Index: clang/lib/Sema/SemaExpr.cpp
===
--- clang/lib/Sema/SemaExpr.cpp
+++ clang/lib/Sema/SemaExpr.cpp
@@ -15750,7 +15750,27 @@
 QualType PromoteType;
 if (TInfo->getType()->isPromotableIntegerType()) {
   PromoteType = Context.getPromotedIntegerType(TInfo->getType());
-  if (Context.typesAreCompatible(PromoteType, TInfo->getType()))
+  // [cstdarg.syn]p1 defers the C++ behavior to what the C standard says,
+  // and C2x 7.16.1.1p2 says, in part:
+  //   If type is not compatible with the type of the actual next argument
+  //   (as promoted according to the default argument promotions), the
+  //   behavior is undefined, except for the following cases:
+  // - both types are pointers to qualified or unqualified versions of
+  //   compatible types;
+  // - one type is a signed integer type, the other type is the
+  //   corresponding unsigned integer type, and the value is
+  //   representable in both types;
+  // - one type is pointer to qualified or unqualified void and the
+  //   other is a pointer to a qualified or unqualified character type.
+  // Given that type compatibility is the primary requirement (ignoring
+  // qualifications), you would think we could call typesAreCompatible() to
+  // test this. However, in C++, that checks for *same type*, which causes
+  // false positives when passing an enumeration type to va_arg. Instead,
+  // attempt to merge the types and see how well that works.
+  QualType Merged =
+  Context.mergeTypes(PromoteType, TInfo->getType(),
+ /*OfBlockPointer*/ false, /*Unqualified*/ true);
+  if (!Merged.isNull())
 PromoteType = QualType();
 }
 if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float))


Index: clang/test/SemaCXX/varargs.cpp
===
--- clang/test/SemaCXX/varargs.cpp
+++ clang/test/SemaCXX/varargs.cpp
@@ -1,4 +1,4 @@
-// RUN: %clang_cc1 -std=c++03 -verify %s
+// RUN: %clang_cc1 -std=c++03 -Wno-c++11-extensions -verify %s
 // RUN: %clang_cc1 -std=c++11 -verify %s
 
 __builtin_va_list ap;
@@ -28,6 +28,30 @@
   };
 }
 
+// Ensure the correct behavior for promotable type UB checking.
+void promotable(int a, ...) {
+  enum Unscoped { One };
+  (void)__builtin_va

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

2021-06-03 Thread Whisperity via Phabricator via cfe-commits
whisperity added a comment.

There was a bit of talk on Twitter recently about strong typing which reminded 
me of this checker! 😁 I'll fix all issues in one go once we're through with all 
the comments, I'd like to see the full picture of what needs to be done.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D69560

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


[PATCH] D80344: [Windows SEH]: HARDWARE EXCEPTION HANDLING (MSVC -EHa) - Part 1

2021-06-03 Thread Pengfei Wang via Phabricator via cfe-commits
pengfei added a comment.

We found another crush: https://godbolt.org/z/vcbvddEKr


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D80344

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


[PATCH] D103231: [clang][AST] Set correct DeclContext in ASTImporter lookup table for ParmVarDecl.

2021-06-03 Thread Gabor Marton via Phabricator via cfe-commits
martong added a comment.

In D103231#2795794 , @balazske wrote:

> Added `contains` for correct check of `ASTImporterLookupTable` content.

Okay, that looks good, but I just realized we should not have "bare" 
assertions. Could you please add some explanatory textual description for the 
new assertions?




Comment at: clang/lib/AST/ASTImporterLookupTable.cpp:121
+void ASTImporterLookupTable::update(NamedDecl *ND, DeclContext *OldDC) {
+  assert(OldDC != ND->getDeclContext());
+  if (contains(ND->getDeclContext(), ND)) {

Could you please add some explanatory textual description for the new 
`assert`ions?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D103231

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


[PATCH] D103039: [AST] fully-qualify template args of outer types in getFullyQualifiedType

2021-06-03 Thread Victor Kuznetsov via Phabricator via cfe-commits
victordk added a comment.

In D103039#2793776 , @saugustine 
wrote:

> This is a long-standing bug that needed to be fixed. Thank you!

Could you commit the patch? I don't think I have commit access.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D103039

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


[PATCH] D80344: [Windows SEH]: HARDWARE EXCEPTION HANDLING (MSVC -EHa) - Part 1

2021-06-03 Thread Zahira Ammarguellat via Phabricator via cfe-commits
zahiraam added a comment.

In D80344#2796066 , @pengfei wrote:

> We found another crush: https://godbolt.org/z/vcbvddEKr

Even smaller https://godbolt.org/z/dbrGjGbaf


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D80344

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


[PATCH] D103612: [flang][driver] Add `-fno-unparse-typed-exprs`

2021-06-03 Thread Andrzej Warzynski via Phabricator via cfe-commits
awarzynski created this revision.
Herald added a reviewer: sscalpone.
Herald added a subscriber: dang.
awarzynski requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

This patch adds new option for the new Flang driver:
`-fno-unparse-typed-exprs`. The semantics are similar to
`-funparse-typed-exprs-to-f18-fc` from `f18`. For consistency, the
latter is replaced with `-fno-unparse-typed-exprs`.

The new option controls the behaviour of the unparser (i.e. the action
corresponding to `-fdebug-unparse`). The default behaviour is to always
unparse typed expressions. The new flag can be used to turn this off.

Note that the semantics in `f18` had to be updated so that the behaviour
is consistent across all calls to `Unparse`.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D103612

Files:
  clang/include/clang/Driver/Options.td
  flang/include/flang/Frontend/CompilerInvocation.h
  flang/lib/Frontend/CompilerInvocation.cpp
  flang/lib/Frontend/FrontendActions.cpp
  flang/lib/Frontend/FrontendOptions.cpp
  flang/test/Driver/unparse-typed-exprs.f95
  flang/tools/f18/f18.cpp
  flang/tools/f18/flang

Index: flang/tools/f18/flang
===
--- flang/tools/f18/flang
+++ flang/tools/f18/flang
@@ -8,7 +8,7 @@
 #======#
 
 wd=$(cd $(dirname "$0")/.. && pwd)
-opts="-module-suffix .f18.mod "
+opts="-fno-unparse-typed-exprs -module-suffix .f18.mod "
 if ! $wd/bin/f18 $opts "$@"
 then status=$?
  echo flang: in $PWD, f18 failed with exit status $status: $wd/bin/f18 $opts "$@" >&2
Index: flang/tools/f18/f18.cpp
===
--- flang/tools/f18/f18.cpp
+++ flang/tools/f18/f18.cpp
@@ -105,7 +105,7 @@
   bool debugModuleWriter{false};
   bool defaultReal8{false};
   bool measureTree{false};
-  bool unparseTypedExprsToF18_FC{false};
+  bool unparseTypedExprs{true};
   std::vector F18_FCArgs;
   const char *prefix{nullptr};
   bool getDefinition{false};
@@ -322,7 +322,8 @@
 Unparse(llvm::outs(), parseTree, driver.encoding, true /*capitalize*/,
 options.features.IsEnabled(
 Fortran::common::LanguageFeature::BackslashEscapes),
-nullptr /* action before each statement */, &asFortran);
+nullptr /* action before each statement */,
+driver.unparseTypedExprs ? &asFortran : nullptr);
 return {};
   }
   if (driver.dumpPreFirTree) {
@@ -353,11 +354,11 @@
 options.features.IsEnabled(
 Fortran::common::LanguageFeature::BackslashEscapes),
 nullptr /* action before each statement */,
-driver.unparseTypedExprsToF18_FC ? &asFortran : nullptr);
+driver.unparseTypedExprs ? &asFortran : nullptr);
   }
 
   RunOtherCompiler(driver, tmpSourcePath.data(), relo.data());
-  filesToDelete.emplace_back(tmpSourcePath);
+  // filesToDelete.emplace_back(tmpSourcePath);
   if (!driver.compileOnly && driver.outputPath.empty()) {
 filesToDelete.push_back(relo);
   }
@@ -578,8 +579,8 @@
 } else if (arg == "-funparse-with-symbols" ||
 arg == "-fdebug-unparse-with-symbols") {
   driver.dumpUnparseWithSymbols = true;
-} else if (arg == "-funparse-typed-exprs-to-f18-fc") {
-  driver.unparseTypedExprsToF18_FC = true;
+} else if (arg == "-fno-unparse-typed-exprs") {
+  driver.unparseTypedExprs = false;
 } else if (arg == "-fparse-only" || arg == "-fsyntax-only") {
   driver.syntaxOnly = true;
 } else if (arg == "-c") {
Index: flang/test/Driver/unparse-typed-exprs.f95
===
--- /dev/null
+++ flang/test/Driver/unparse-typed-exprs.f95
@@ -0,0 +1,34 @@
+! Tests `-fno-unparse-typed-exprs-to-f18-fc` frontend option
+
+!--
+! RUN lines
+!--
+! RUN: %flang_fc1 -fdebug-unparse  %s | FileCheck %s --check-prefix=UNPARSED_TYPED_EXPR
+! RUN: %flang_fc1 -fdebug-unparse -fno-unparse-typed-exprs %s | FileCheck %s --check-prefix=AS_FORTRAN
+
+!--
+! EXPECTED OUTPUT: default
+!--
+! UNPARSED_TYPED_EXPR: PROGRAM test_allocated
+! UNPARSED_TYPED_EXPR-NEXT:  INTEGER :: i = 4_4
+! UNPARSED_TYPED_EXPR-NEXT:  REAL(KIND=4_4), ALLOCATABLE :: x(:)
+! UNPARSED_TYPED_EXPR-NEXT:  IF (.NOT.allocated(x)) ALLOCATE(x(i))
+! UNPARSED_TYPED_EXPR-NEXT: END PROGRAM test_allocated
+
+!-
+! EXPECTED OUTPUT: unparsed as Fortran
+!--
+! AS_FORTRAN: PROGRAM test_allocated
+! AS_FORTRAN-NEXT:  INTEGER :: i = 4
+! AS_FORTRAN-NEXT:  REAL(KIND=4), ALLOCATABLE :: x(:)
+! AS_FORTRAN-NEXT:  IF (.NOT.allocated(x)) ALLOCATE(x(i))
+! AS_FORTRAN-NEXT: END PROGRAM test_allocated
+
+!--
+! INPUT
+!--
+program test_allocated
+  integer :: i = 4
+  real(4),

[PATCH] D103605: [analyzer] Introduce a new interface for tracking

2021-06-03 Thread Valeriy Savchenko via Phabricator via cfe-commits
vsavchenko updated this revision to Diff 349529.
vsavchenko added a comment.

Tweak some parts of the interface


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D103605

Files:
  clang/include/clang/StaticAnalyzer/Core/BugReporter/BugReporterVisitors.h
  clang/lib/StaticAnalyzer/Core/BugReporterVisitors.cpp

Index: clang/lib/StaticAnalyzer/Core/BugReporterVisitors.cpp
===
--- clang/lib/StaticAnalyzer/Core/BugReporterVisitors.cpp
+++ clang/lib/StaticAnalyzer/Core/BugReporterVisitors.cpp
@@ -65,6 +65,7 @@
 
 using namespace clang;
 using namespace ento;
+using namespace bugreporter;
 
 //===--===//
 // Utility functions.
@@ -2045,6 +2046,54 @@
   }
 }
 
+//===--===//
+//Tracker implementation
+//===--===//
+
+Tracker::Tracker(PathSensitiveBugReport &Report) : Report(Report) {
+  // TODO: split trackExpressionValue and FindLastStoreBRVisitor into handlers
+  //   and add them here.
+}
+
+Tracker::Result Tracker::track(const Expr *E, const ExplodedNode *N,
+   TrackingOptions Opts) {
+  if (!E || !N)
+return {};
+
+  const Expr *Inner = peelOffOuterExpr(E, N);
+  const ExplodedNode *LVNode = findNodeForExpression(N, Inner);
+  if (!LVNode)
+return {};
+
+  Result CombinedResult;
+  // Iterate through the handlers in the order according to their priorities.
+  for (ExpressionHandlerPtr &Handler : ExpressionHandlers) {
+CombinedResult.combineWith(Handler->handle(Inner, N, LVNode, Opts));
+if (CombinedResult.WasInterrupted)
+  break;
+  }
+
+  return CombinedResult;
+}
+
+Tracker::Result Tracker::track(KnownSVal V, const MemRegion *R,
+   const ExplodedNode *N, TrackingOptions Opts,
+   const StackFrameContext *Origin) {
+  // TODO: support this operation after dismantling FindLastStoreBRVisitor
+  return {};
+}
+
+PathDiagnosticPieceRef Tracker::handle(StoreInfo SI, TrackingOptions Opts) {
+  // Iterate through the handlers in the order according to their priorities.
+  for (StoreHandlerPtr &Handler : StoreHandlers) {
+if (PathDiagnosticPieceRef Result = Handler->handle(SI, Opts))
+  // If the handler produced a non-null piece, return it.
+  // There is no need in asking other handlers.
+  return Result;
+  }
+  return {};
+}
+
 bool bugreporter::trackExpressionValue(const ExplodedNode *InputNode,
const Expr *E,
PathSensitiveBugReport &report,
Index: clang/include/clang/StaticAnalyzer/Core/BugReporter/BugReporterVisitors.h
===
--- clang/include/clang/StaticAnalyzer/Core/BugReporter/BugReporterVisitors.h
+++ clang/include/clang/StaticAnalyzer/Core/BugReporter/BugReporterVisitors.h
@@ -21,7 +21,9 @@
 #include "llvm/ADT/FoldingSet.h"
 #include "llvm/ADT/STLExtras.h"
 #include "llvm/ADT/StringRef.h"
+#include 
 #include 
+#include 
 
 namespace clang {
 
@@ -99,6 +101,231 @@
   Condition
 };
 
+/// Defines a set of options altering tracking behavior.
+struct TrackingOptions {
+  /// Specifies the kind of tracking.
+  TrackingKind Kind = TrackingKind::Thorough;
+  /// Specifies whether we should employ false positive suppression
+  /// (inlined defensive checks, returned null).
+  bool EnableNullFPSuppression = true;
+};
+
+struct StoreInfo {
+  enum Kind {
+/// The value got stored into the region during initialization:
+///   int x = 42;
+Initialization,
+/// The value got stored into the region during assignment:
+///   int x;
+///   x = 42;
+Assignment,
+/// The value got stored into the region as block capture.
+/// Block data is modeled as a separate region, thus whenever
+/// the analyzer sees a captured variable, its value is copied
+/// into a special block region.
+BlockCapture
+  };
+
+  /// The type of store operation.
+  Kind StoreKind;
+  /// The expression where the value comes from.
+  /// NOTE: might be null.
+  Expr *SourceOfTheValue;
+  /// Symbolic value that is being stored.
+  SVal Value;
+  /// Memory regions involved in the store operation.
+  ///   Dest <- Origin
+  /// NOTE: Origin might be null, when the stored value doesn't come
+  ///   from another region.
+  const MemRegion *Dest, *Origin;
+};
+
+class ExpressionHandler;
+class StoreHandler;
+
+/// A generalized component for tracking expressions, values, and stores.
+///
+/// Tracker aimes at providing a sensible set of default behaviors that can be
+/// used by any checker, while providing mechanisms to hook into any part of the
+/// tracking proce

[PATCH] D103613: [flang][driver] Add support for `-module-suffix`

2021-06-03 Thread Andrzej Warzynski via Phabricator via cfe-commits
awarzynski created this revision.
Herald added a reviewer: sscalpone.
Herald added a subscriber: dang.
awarzynski requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

This option is required in order to call `flang-new` from the `flang`
bash script.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D103613

Files:
  clang/include/clang/Driver/Options.td
  flang/include/flang/Frontend/CompilerInvocation.h
  flang/lib/Frontend/CompilerInvocation.cpp
  flang/test/Driver/module-suffix.f90
  flang/tools/f18/f18.cpp

Index: flang/tools/f18/f18.cpp
===
--- flang/tools/f18/f18.cpp
+++ flang/tools/f18/f18.cpp
@@ -357,7 +357,7 @@
   }
 
   RunOtherCompiler(driver, tmpSourcePath.data(), relo.data());
-  filesToDelete.emplace_back(tmpSourcePath);
+  // filesToDelete.emplace_back(tmpSourcePath);
   if (!driver.compileOnly && driver.outputPath.empty()) {
 filesToDelete.push_back(relo);
   }
Index: flang/test/Driver/module-suffix.f90
===
--- /dev/null
+++ flang/test/Driver/module-suffix.f90
@@ -0,0 +1,16 @@
+! Tests `-module-suffix` frontend option
+
+!--
+! RUN lines
+!--
+! RUN: rm -rf %t && mkdir -p %t/dir-flang/
+! RUN: cd %t && %flang_fc1 -fsyntax-only -module-suffix .mod-suffix-for-testing -module-dir %t/dir-flang %s
+! RUN: ls %t/dir-flang/testmodule.mod-suffix-for-testing && not ls %t/dir-flang/testmodule.mod
+
+!--
+! INPUT
+!--
+module testmodule
+  type::t2
+  end type
+end
Index: flang/lib/Frontend/CompilerInvocation.cpp
===
--- flang/lib/Frontend/CompilerInvocation.cpp
+++ flang/lib/Frontend/CompilerInvocation.cpp
@@ -392,6 +392,12 @@
 res.SetDebugModuleDir(true);
   }
 
+  // -module-suffix
+  if (const auto *moduleSuffix =
+  args.getLastArg(clang::driver::options::OPT_module_suffix)) {
+res.SetModuleFileSuffix(moduleSuffix->getValue());
+  }
+
   return diags.getNumErrors() == numErrorsBefore;
 }
 
@@ -639,5 +645,6 @@
   semanticsContext_->set_moduleDirectory(moduleDir())
   .set_searchDirectories(fortranOptions.searchDirectories)
   .set_warnOnNonstandardUsage(enableConformanceChecks())
-  .set_warningsAreErrors(warnAsErr());
+  .set_warningsAreErrors(warnAsErr())
+  .set_moduleFileSuffix(moduleFileSuffix());
 }
Index: flang/include/flang/Frontend/CompilerInvocation.h
===
--- flang/include/flang/Frontend/CompilerInvocation.h
+++ flang/include/flang/Frontend/CompilerInvocation.h
@@ -69,6 +69,8 @@
   // of options.
   std::string moduleDir_ = ".";
 
+  std::string moduleFileSuffix_ = ".mod";
+
   bool debugModuleDir_ = false;
 
   bool warnAsErr_ = false;
@@ -97,6 +99,9 @@
   std::string &moduleDir() { return moduleDir_; }
   const std::string &moduleDir() const { return moduleDir_; }
 
+  std::string &moduleFileSuffix() { return moduleFileSuffix_; }
+  const std::string &moduleFileSuffix() const { return moduleFileSuffix_; }
+
   bool &debugModuleDir() { return debugModuleDir_; }
   const bool &debugModuleDir() const { return debugModuleDir_; }
 
@@ -129,6 +134,10 @@
   /// Useful setters
   void SetModuleDir(std::string &moduleDir) { moduleDir_ = moduleDir; }
 
+  void SetModuleFileSuffix(const char *moduleFileSuffix) {
+moduleFileSuffix_ = std::string(moduleFileSuffix);
+  }
+
   void SetDebugModuleDir(bool flag) { debugModuleDir_ = flag; }
 
   void SetWarnAsErr(bool flag) { warnAsErr_ = flag; }
Index: clang/include/clang/Driver/Options.td
===
--- clang/include/clang/Driver/Options.td
+++ clang/include/clang/Driver/Options.td
@@ -4521,6 +4521,9 @@
 def fget_symbols_sources : Flag<["-"], "fget-symbols-sources">, Group,
   HelpText<"Dump symbols and their source code locations">;
 
+def module_suffix : Separate<["-"], "module-suffix">,  Group, MetaVarName<"">,
+  HelpText<"Specify the suffix to use for module files (`.mod` is the default value)">;
+
 }
 
 //===--===//
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D103605: [analyzer] Introduce a new interface for tracking

2021-06-03 Thread Gabor Marton via Phabricator via cfe-commits
martong added a comment.

Great initiative! You haven't mention `markInteresting` functions, but I think 
it would be really important to incorporate that functionality here as well. 
IMHO, `markInteresting` shouldn't have been part of the public API ever, 
Checkers should have been calling only the trackExpressionValue (as internally 
that calls markInteresting anyway).




Comment at: 
clang/include/clang/StaticAnalyzer/Core/BugReporter/BugReporterVisitors.h:113
+
+struct StoreInfo {
+  enum Kind {

I think we should document this class' responsibility with a terse sentence.



Comment at: 
clang/include/clang/StaticAnalyzer/Core/BugReporter/BugReporterVisitors.h:231
+  template 
+  void addExpressionHandlerToTheTop(Args &&... ConstructorArgs) {
+addExpressionHandlerToTheTop(std::make_unique(

This naming is a bit too bloated to me, what do you think about this:
```
enum class Position { Front, Back };
addExpressionHandler(Front, ...) {
```


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D103605

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


[PATCH] D75041: [clang-tidy] Extend 'bugprone-easily-swappable-parameters' with mixability because of implicit conversions

2021-06-03 Thread Gabor Marton via Phabricator via cfe-commits
martong added inline comments.



Comment at: 
clang-tools-extra/clang-tidy/bugprone/EasilySwappableParametersCheck.cpp:122
 
 #define FB(Name, K) MIX_##Name = (1ull << (K##ull - 1ull))
 

FB stands for FunnyBitmask? Could you please either describe that in a comment 
or just spell it out?



Comment at: 
clang-tools-extra/clang-tidy/bugprone/EasilySwappableParametersCheck.cpp:182
+  /// The intermediate type after the first Standard Conversion Sequence.
+  QualType AfterPreStd;
+

Maybe it's just me, but AfterPre sounds ambiguous and AfterPost seems redundant.



Comment at: 
clang-tools-extra/clang-tidy/bugprone/EasilySwappableParametersCheck.cpp:210
+  /// the conversion sequence. This method does **NOT** return Begin and End.
+  SmallVector getInvolvedTypesInSequence() const {
+SmallVector Ret;

So, we can never return with a vector with size > 4?



Comment at: 
clang-tools-extra/clang-tidy/bugprone/EasilySwappableParametersCheck.h:42
 
-  /// Whether to consider an unqualified and a qualified type mixable.
+  /// Whether to consider differently qualified versions of the same type
+  /// mixable.

"qualified"
Do you consider `volatile` here as well, or just `const`?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D75041

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


[PATCH] D103605: [analyzer] Introduce a new interface for tracking

2021-06-03 Thread Valeriy Savchenko via Phabricator via cfe-commits
vsavchenko added a comment.

In D103605#2796111 , @martong wrote:

> Great initiative! You haven't mention `markInteresting` functions, but I 
> think it would be really important to incorporate that functionality here as 
> well. IMHO, `markInteresting` shouldn't have been part of the public API 
> ever, Checkers should have been calling only the trackExpressionValue (as 
> internally that calls markInteresting anyway).

Oh, yes, interesting-ness doesn't provide a very clear interface for the 
feedback loop that I'm trying to adjust.  From the perspective of the use "mark 
interesting whatever your checker is interested in and the core will figure it 
out", it's fine.  It has a clear message and you simply expect the engine to do 
its magic.  The problem comes when you try to catch something interesting from 
your own checker-specific visitor.  In that use case, you, first of all, really 
need to understand how trackers traverse the graph and what they might consider 
interesting, and rely on the fact that you will get the right interesting 
thingy.  So, the predicate checking for interesting-ness available to the 
users, is not very helpful IMO.




Comment at: 
clang/include/clang/StaticAnalyzer/Core/BugReporter/BugReporterVisitors.h:113
+
+struct StoreInfo {
+  enum Kind {

martong wrote:
> I think we should document this class' responsibility with a terse sentence.
Sure



Comment at: 
clang/include/clang/StaticAnalyzer/Core/BugReporter/BugReporterVisitors.h:231
+  template 
+  void addExpressionHandlerToTheTop(Args &&... ConstructorArgs) {
+addExpressionHandlerToTheTop(std::make_unique(

martong wrote:
> This naming is a bit too bloated to me, what do you think about this:
> ```
> enum class Position { Front, Back };
> addExpressionHandler(Front, ...) {
> ```
Maybe `addHighPriorityHandler` and `addLowPriorityHandler`? There is probably 
no reason to put `Expression` and `Store` into the actual name.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D103605

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


[PATCH] D75041: [clang-tidy] Extend 'bugprone-easily-swappable-parameters' with mixability because of implicit conversions

2021-06-03 Thread Whisperity via Phabricator via cfe-commits
whisperity added inline comments.



Comment at: 
clang-tools-extra/clang-tidy/bugprone/EasilySwappableParametersCheck.cpp:657-667
+  // Certain kinds unfortunately need to be side-stepped for canonical type
+  // matching.
+  if (LType->getAs() || RType->getAs()) {
+// Unfortunately, the canonical type of a function pointer becomes the
+// same even if exactly one is "noexcept" and the other isn't, making us
+// give a false positive report irrespective of implicit conversions.
+LLVM_DEBUG(llvm::dbgs()

whisperity wrote:
> martong wrote:
> > aaron.ballman wrote:
> > > whisperity wrote:
> > > > @aaron.ballman Getting ahead of the curve here. I understand this is 
> > > > ugly. Unfortunately, no matter how much I read the standard, I don't 
> > > > get anything of "canonical type" mentioned, it seems to me this concept 
> > > > is something inherent to the model of Clang.
> > > > 
> > > > Basically why this is here: imagine a `void (*)() noexcept` and a `void 
> > > > (*)()`. One's `noexcept`, the other isn't. Inside the AST, this is a 
> > > > `ParenType` of a `PointerType` to a `FunctionProtoType`. There exists a 
> > > > //one-way// implicit conversion from the `noexcept` to the non-noexcept 
> > > > ("noexceptness can be discarded", similarly to how "constness can be 
> > > > gained")
> > > > Unfortunately, because this is a one-way implicit conversion, it won't 
> > > > return on the code path earlier for implicit conversions.
> > > > 
> > > > Now because of this, the recursive descent in our code will reach the 
> > > > point when the two innermost `FunctionProtoType`s are in our hands. As 
> > > > a fallback case, we simply ask Clang "Hey, do //you// think these two 
> > > > are the same?". And for some weird reason, Clang will say "Yes."... 
> > > > While one of them is a `noexcept` function and the other one isn't.
> > > > 
> > > > I do not know the innards of the AST well enough to even have a glimpse 
> > > > of whether or not this is a bug. So that's the reason why I went ahead 
> > > > and implemented this side-stepping logic. Basically, as the comment 
> > > > says, it'lll **force** the information of "No matter what you do, do 
> > > > NOT consider these mixable!" back up the recursion chain, and handle it 
> > > > appropriately later.
> > > > Unfortunately, no matter how much I read the standard, I don't get 
> > > > anything of "canonical type" mentioned, it seems to me this concept is 
> > > > something inherent to the model of Clang.
> > > 
> > > It is more of a Clang-centric concept. Basically, a canonical type is one 
> > > that's had all of the typedefs stripped off it.
> > > 
> > > > Now because of this, the recursive descent in our code will reach the 
> > > > point when the two innermost FunctionProtoTypes are in our hands. As a 
> > > > fallback case, we simply ask Clang "Hey, do you think these two are the 
> > > > same?". And for some weird reason, Clang will say "Yes."... While one 
> > > > of them is a noexcept function and the other one isn't.
> > > 
> > > I think a confounding factor in this area is that `noexcept` did not used 
> > > to be part of the function type until one day it started being a part of 
> > > the function type. So my guess is that this is fallout from this sort of 
> > > thing: https://godbolt.org/z/EYfj8z (which may be worth keeping in mind 
> > > when working on the check).
> > About `noexcept`: we've faced a similar problem in the `ASTImporter` 
> > library. We could not import a noexcept function's definition if we already 
> > had one without the noexcept specifier. 
> > 
> > Thus, in `ASTStructuralEquivalence.cpp` we do differentiate the function 
> > types based on their noexcept specifier (and we even check the noexcept 
> > expression).:
> > ```
> > TEST_F(StructuralEquivalenceFunctionTest, Noexcept) {
> >   auto t = makeNamedDecls("void foo();",
> >   "void foo() noexcept;", Lang_CXX11);
> >   EXPECT_FALSE(testStructuralMatch(t));
> > }
> > TEST_F(StructuralEquivalenceFunctionTest, NoexceptNonMatch) {
> >   auto t = makeNamedDecls("void foo() noexcept(false);",
> >   "void foo() noexcept(true);", Lang_CXX11);
> >   EXPECT_FALSE(testStructuralMatch(t));
> > }
> > ```
> > 
> > May be in these special cases it would worth to reuse the 
> > ASTStructuralEquivalenceContext class?
> Definitely, good catch, @martong, thank you very much! @aaron.ballman, what 
> do you think? If I see this right, `StructuralEquivalenceContext` is part of 
> `libClangAST` so should be readily available.
> 
> The only issue I'm seeing is that this class takes non-**`const`** 
> `ASTContext` and `Decl` nodes...
Well, I started looking into putting up `const` whereever possible into the 
aforementioned type, but I hit a hurdle. When checking equivalence of records, 
the algorithm tries to ASTImport-complete the definition of a record if it's 
not fully defined yet... which is **n

[PATCH] D75041: [clang-tidy] Extend 'bugprone-easily-swappable-parameters' with mixability because of implicit conversions

2021-06-03 Thread Whisperity via Phabricator via cfe-commits
whisperity added inline comments.



Comment at: 
clang-tools-extra/clang-tidy/bugprone/EasilySwappableParametersCheck.cpp:122
 
 #define FB(Name, K) MIX_##Name = (1ull << (K##ull - 1ull))
 

martong wrote:
> FB stands for FunnyBitmask? Could you please either describe that in a 
> comment or just spell it out?
FlagBit. @alexfh suggested in the base check to use hexa literals. I'm not too 
sold about that, but maybe we can cut the macro out and keep the bit shift 
instructions in. Given that the check has more or less earned its final form 
(for now), we know how many bits we need!



Comment at: 
clang-tools-extra/clang-tidy/bugprone/EasilySwappableParametersCheck.cpp:182
+  /// The intermediate type after the first Standard Conversion Sequence.
+  QualType AfterPreStd;
+

martong wrote:
> Maybe it's just me, but AfterPre sounds ambiguous and AfterPost seems 
> redundant.
Should I use "AfterFirstStandard" or "AfterFirstStd"?

AfterPost isn't redundant. An implicit conversion sequence might be of **3 
steps**. Consider in a hypothetical `void f(Complex x, const double d)`.

`Complex` ---(PRE: std qual adjustment)--> `const Complex` ---(UD: user defined 
conv)--> `double` ---(POST: std qual adjustment)--> `const double`

And because in case of many conversions a lot of combinations need to be 
checked, we can't have `AfterPost` be the same as `End`. First, because of the 
combinations, second, because of the //other// things the check is doing.

`void g(ComplexTypedef CT, ConstDoubleTypedef CDT);`

In this case, `Start` and `End` are the typedefs, and the inner sequence is the 
same as before. And in order to generate the diagnostic, we also need to have 
**both** pieces of information.



Comment at: 
clang-tools-extra/clang-tidy/bugprone/EasilySwappableParametersCheck.cpp:210
+  /// the conversion sequence. This method does **NOT** return Begin and End.
+  SmallVector getInvolvedTypesInSequence() const {
+SmallVector Ret;

martong wrote:
> So, we can never return with a vector with size > 4?
`N` in `SmallVector` only specifies the pre-allocated smallness size. 
AFAIK, if you have >N elements, it will just put the vector out onto the heap.



Comment at: 
clang-tools-extra/clang-tidy/bugprone/EasilySwappableParametersCheck.h:42
 
-  /// Whether to consider an unqualified and a qualified type mixable.
+  /// Whether to consider differently qualified versions of the same type
+  /// mixable.

martong wrote:
> "qualified"
> Do you consider `volatile` here as well, or just `const`?
Const, volatile, and in C mode, restrict, too.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D75041

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


[PATCH] D103615: [Clang] Add option for vector compare compatibility.

2021-06-03 Thread Stefan Pintilie via Phabricator via cfe-commits
stefanp created this revision.
stefanp added reviewers: nemanjai, lei, rsmith.
Herald added subscribers: dexonsmith, dang.
stefanp requested review of this revision.
Herald added a project: clang.

Added the option -vector-abi-compat=[default,gcc,xl]. The default behavior for
clang is for all vector compares to return a scalar unless the vectors being
compared are vector bool or vector pixel. In that case the compare returns a
vector. With the gcc case all vector compares return vectors and in the xl case
all vector compares return scalars.

This patch does not change the default behavior of clang.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D103615

Files:
  clang/include/clang/Basic/LangOptions.def
  clang/include/clang/Basic/LangOptions.h
  clang/include/clang/Driver/Options.td
  clang/lib/Driver/ToolChains/Clang.cpp
  clang/lib/Sema/SemaExpr.cpp
  clang/test/CodeGen/vector-compat-pixel-bool-ternary.c
  clang/test/CodeGen/vector-compat-pixel-bool.c
  clang/test/CodeGen/vector-compat-ternary.c
  clang/test/CodeGen/vector-compat.c

Index: clang/test/CodeGen/vector-compat.c
===
--- /dev/null
+++ clang/test/CodeGen/vector-compat.c
@@ -0,0 +1,160 @@
+// NOTE: Assertions have been autogenerated by utils/update_cc_test_checks.py
+// Com: not %clang_cc1 -target-feature +altivec -target-feature +vsx \
+// Com:   -vector-abi-compat=default -triple powerpc-unknown-unknown -S -emit-llvm %s -o - 2>&1 | FileCheck %s --check-prefix=ERROR
+// RUN: %clang_cc1 -target-feature +altivec -target-feature +vsx \
+// RUN:   -vector-abi-compat=gcc -triple powerpc-unknown-unknown -S -emit-llvm %s -o - | FileCheck %s
+// com: not %clang_cc1 -target-feature +altivec -target-feature +vsx \
+// com:   -vector-abi-compat=xl -triple powerpc-unknown-unknown -S -emit-llvm %s -o - 2>&1 | FileCheck %s --check-prefix=ERROR
+
+// CHECK-LABEL: @ui8(
+// CHECK-NEXT:  entry:
+// CHECK-NEXT:[[A_ADDR:%.*]] = alloca <16 x i8>, align 16
+// CHECK-NEXT:[[B_ADDR:%.*]] = alloca <16 x i8>, align 16
+// CHECK-NEXT:store <16 x i8> [[A:%.*]], <16 x i8>* [[A_ADDR]], align 16
+// CHECK-NEXT:store <16 x i8> [[B:%.*]], <16 x i8>* [[B_ADDR]], align 16
+// CHECK-NEXT:[[TMP0:%.*]] = load <16 x i8>, <16 x i8>* [[A_ADDR]], align 16
+// CHECK-NEXT:[[TMP1:%.*]] = load <16 x i8>, <16 x i8>* [[B_ADDR]], align 16
+// CHECK-NEXT:[[CMP:%.*]] = icmp eq <16 x i8> [[TMP0]], [[TMP1]]
+// CHECK-NEXT:[[SEXT:%.*]] = sext <16 x i1> [[CMP]] to <16 x i8>
+// CHECK-NEXT:ret <16 x i8> [[SEXT]]
+//
+// ERROR: returning 'int' from a function with incompatible result type
+vector unsigned char ui8(vector unsigned char a, vector unsigned char b) {
+  return a == b;
+}
+
+// CHECK-LABEL: @si8(
+// CHECK-NEXT:  entry:
+// CHECK-NEXT:[[A_ADDR:%.*]] = alloca <16 x i8>, align 16
+// CHECK-NEXT:[[B_ADDR:%.*]] = alloca <16 x i8>, align 16
+// CHECK-NEXT:store <16 x i8> [[A:%.*]], <16 x i8>* [[A_ADDR]], align 16
+// CHECK-NEXT:store <16 x i8> [[B:%.*]], <16 x i8>* [[B_ADDR]], align 16
+// CHECK-NEXT:[[TMP0:%.*]] = load <16 x i8>, <16 x i8>* [[A_ADDR]], align 16
+// CHECK-NEXT:[[TMP1:%.*]] = load <16 x i8>, <16 x i8>* [[B_ADDR]], align 16
+// CHECK-NEXT:[[CMP:%.*]] = icmp eq <16 x i8> [[TMP0]], [[TMP1]]
+// CHECK-NEXT:[[SEXT:%.*]] = sext <16 x i1> [[CMP]] to <16 x i8>
+// CHECK-NEXT:ret <16 x i8> [[SEXT]]
+//
+// ERROR: returning 'int' from a function with incompatible result type
+vector signed char si8(vector signed char a, vector signed char b) {
+  return a == b;
+}
+
+// CHECK-LABEL: @ui16(
+// CHECK-NEXT:  entry:
+// CHECK-NEXT:[[A_ADDR:%.*]] = alloca <8 x i16>, align 16
+// CHECK-NEXT:[[B_ADDR:%.*]] = alloca <8 x i16>, align 16
+// CHECK-NEXT:store <8 x i16> [[A:%.*]], <8 x i16>* [[A_ADDR]], align 16
+// CHECK-NEXT:store <8 x i16> [[B:%.*]], <8 x i16>* [[B_ADDR]], align 16
+// CHECK-NEXT:[[TMP0:%.*]] = load <8 x i16>, <8 x i16>* [[A_ADDR]], align 16
+// CHECK-NEXT:[[TMP1:%.*]] = load <8 x i16>, <8 x i16>* [[B_ADDR]], align 16
+// CHECK-NEXT:[[CMP:%.*]] = icmp eq <8 x i16> [[TMP0]], [[TMP1]]
+// CHECK-NEXT:[[SEXT:%.*]] = sext <8 x i1> [[CMP]] to <8 x i16>
+// CHECK-NEXT:ret <8 x i16> [[SEXT]]
+//
+// ERROR: returning 'int' from a function with incompatible result type
+vector unsigned short ui16(vector unsigned short a, vector unsigned short b) {
+  return a == b;
+}
+
+// CHECK-LABEL: @si16(
+// CHECK-NEXT:  entry:
+// CHECK-NEXT:[[A_ADDR:%.*]] = alloca <8 x i16>, align 16
+// CHECK-NEXT:[[B_ADDR:%.*]] = alloca <8 x i16>, align 16
+// CHECK-NEXT:store <8 x i16> [[A:%.*]], <8 x i16>* [[A_ADDR]], align 16
+// CHECK-NEXT:store <8 x i16> [[B:%.*]], <8 x i16>* [[B_ADDR]], align 16
+// CHECK-NEXT:[[TMP0:%.*]] = load <8 x i16>, <8 x i16>* [[A_ADDR]], align 16
+// CHECK-NEXT:[[TMP1:%.*]] = load <8 x i16>, <8 x i16>* [[B_ADDR]], align 16
+// CHECK-NEXT:[[CMP:%.*]] = icmp eq <8 x

[PATCH] D103605: [analyzer] Introduce a new interface for tracking

2021-06-03 Thread Valeriy Savchenko via Phabricator via cfe-commits
vsavchenko updated this revision to Diff 349537.
vsavchenko added a comment.

Address review comments


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D103605

Files:
  clang/include/clang/StaticAnalyzer/Core/BugReporter/BugReporterVisitors.h
  clang/lib/StaticAnalyzer/Core/BugReporterVisitors.cpp

Index: clang/lib/StaticAnalyzer/Core/BugReporterVisitors.cpp
===
--- clang/lib/StaticAnalyzer/Core/BugReporterVisitors.cpp
+++ clang/lib/StaticAnalyzer/Core/BugReporterVisitors.cpp
@@ -65,6 +65,7 @@
 
 using namespace clang;
 using namespace ento;
+using namespace bugreporter;
 
 //===--===//
 // Utility functions.
@@ -2045,6 +2046,54 @@
   }
 }
 
+//===--===//
+//Tracker implementation
+//===--===//
+
+Tracker::Tracker(PathSensitiveBugReport &Report) : Report(Report) {
+  // TODO: split trackExpressionValue and FindLastStoreBRVisitor into handlers
+  //   and add them here.
+}
+
+Tracker::Result Tracker::track(const Expr *E, const ExplodedNode *N,
+   TrackingOptions Opts) {
+  if (!E || !N)
+return {};
+
+  const Expr *Inner = peelOffOuterExpr(E, N);
+  const ExplodedNode *LVNode = findNodeForExpression(N, Inner);
+  if (!LVNode)
+return {};
+
+  Result CombinedResult;
+  // Iterate through the handlers in the order according to their priorities.
+  for (ExpressionHandlerPtr &Handler : ExpressionHandlers) {
+CombinedResult.combineWith(Handler->handle(Inner, N, LVNode, Opts));
+if (CombinedResult.WasInterrupted)
+  break;
+  }
+
+  return CombinedResult;
+}
+
+Tracker::Result Tracker::track(KnownSVal V, const MemRegion *R,
+   TrackingOptions Opts,
+   const StackFrameContext *Origin) {
+  // TODO: support this operation after dismantling FindLastStoreBRVisitor
+  return {};
+}
+
+PathDiagnosticPieceRef Tracker::handle(StoreInfo SI, TrackingOptions Opts) {
+  // Iterate through the handlers in the order according to their priorities.
+  for (StoreHandlerPtr &Handler : StoreHandlers) {
+if (PathDiagnosticPieceRef Result = Handler->handle(SI, Opts))
+  // If the handler produced a non-null piece, return it.
+  // There is no need in asking other handlers.
+  return Result;
+  }
+  return {};
+}
+
 bool bugreporter::trackExpressionValue(const ExplodedNode *InputNode,
const Expr *E,
PathSensitiveBugReport &report,
Index: clang/include/clang/StaticAnalyzer/Core/BugReporter/BugReporterVisitors.h
===
--- clang/include/clang/StaticAnalyzer/Core/BugReporter/BugReporterVisitors.h
+++ clang/include/clang/StaticAnalyzer/Core/BugReporter/BugReporterVisitors.h
@@ -21,7 +21,9 @@
 #include "llvm/ADT/FoldingSet.h"
 #include "llvm/ADT/STLExtras.h"
 #include "llvm/ADT/StringRef.h"
+#include 
 #include 
+#include 
 
 namespace clang {
 
@@ -99,6 +101,218 @@
   Condition
 };
 
+/// Defines a set of options altering tracking behavior.
+struct TrackingOptions {
+  /// Specifies the kind of tracking.
+  TrackingKind Kind = TrackingKind::Thorough;
+  /// Specifies whether we should employ false positive suppression
+  /// (inlined defensive checks, returned null).
+  bool EnableNullFPSuppression = true;
+};
+
+/// Describes an event when the value got stored into a memory region.
+struct StoreInfo {
+  enum Kind {
+/// The value got stored into the region during initialization:
+///   int x = 42;
+Initialization,
+/// The value got stored into the region during assignment:
+///   int x;
+///   x = 42;
+Assignment,
+/// The value got stored into the region as block capture.
+/// Block data is modeled as a separate region, thus whenever
+/// the analyzer sees a captured variable, its value is copied
+/// into a special block region.
+BlockCapture
+  };
+
+  /// The type of store operation.
+  Kind StoreKind;
+  /// The expression where the value comes from.
+  /// NOTE: might be null.
+  Expr *SourceOfTheValue;
+  /// Symbolic value that is being stored.
+  SVal Value;
+  /// Memory regions involved in the store operation.
+  ///   Dest <- Origin
+  /// NOTE: Origin might be null, when the stored value doesn't come
+  ///   from another region.
+  const MemRegion *Dest, *Origin;
+};
+
+class ExpressionHandler;
+class StoreHandler;
+
+/// A generalized component for tracking expressions, values, and stores.
+///
+/// Tracker aimes at providing a sensible set of default behaviors that can be
+/// used by any checker, while providing mechanisms to hook i

[PATCH] D103605: [analyzer] Introduce a new interface for tracking

2021-06-03 Thread Valeriy Savchenko via Phabricator via cfe-commits
vsavchenko marked an inline comment as done.
vsavchenko added inline comments.



Comment at: 
clang/include/clang/StaticAnalyzer/Core/BugReporter/BugReporterVisitors.h:231
+  template 
+  void addExpressionHandlerToTheTop(Args &&... ConstructorArgs) {
+addExpressionHandlerToTheTop(std::make_unique(

vsavchenko wrote:
> martong wrote:
> > This naming is a bit too bloated to me, what do you think about this:
> > ```
> > enum class Position { Front, Back };
> > addExpressionHandler(Front, ...) {
> > ```
> Maybe `addHighPriorityHandler` and `addLowPriorityHandler`? There is probably 
> no reason to put `Expression` and `Store` into the actual name.
What do you think about this solution?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D103605

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


[PATCH] D76287: [analysis][analyzer] Introduce the skeleton of a reaching definitions calculator

2021-06-03 Thread Whisperity via Phabricator via cfe-commits
whisperity resigned from this revision.
whisperity added a comment.
Herald added a subscriber: manas.

What about this patch? I'm removing my reviewer bit just so it doesn't appear 
in my list anymore, but if there are any updates, I'll keep myself as a 
subscriber. 🙂


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D76287

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


[PATCH] D103616: [analyzer] Reimplement trackExpressionValue as ExpressionHandler

2021-06-03 Thread Valeriy Savchenko via Phabricator via cfe-commits
vsavchenko created this revision.
vsavchenko added reviewers: NoQ, xazax.hun, martong, steakhal, Szelethus, 
manas, RedDocMD.
Herald added subscribers: ASDenysPetrov, dkrupp, donat.nagy, mikhail.ramalho, 
a.sidorin, rnkovacs, szepet, baloghadamsoftware.
vsavchenko requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

This commit moves trackExpressionValue into the Tracker interface
as DefaultExpressionHandler.  It still can be split into smaller
handlers, but that can be a future change.

Additionally, this commit doesn't remove the original trackExpressionValue
interface, so it's not too big.  One of the next commits will address it.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D103616

Files:
  clang/lib/StaticAnalyzer/Core/BugReporterVisitors.cpp

Index: clang/lib/StaticAnalyzer/Core/BugReporterVisitors.cpp
===
--- clang/lib/StaticAnalyzer/Core/BugReporterVisitors.cpp
+++ clang/lib/StaticAnalyzer/Core/BugReporterVisitors.cpp
@@ -2050,7 +2050,168 @@
 //Tracker implementation
 //===--===//
 
+class DefaultExpressionHandler final : public ExpressionHandler {
+public:
+  using ExpressionHandler::ExpressionHandler;
+
+  Tracker::Result handle(const Expr *Inner, const ExplodedNode *InputNode,
+ const ExplodedNode *LVNode,
+ TrackingOptions Opts) override {
+ProgramStateRef LVState = LVNode->getState();
+const StackFrameContext *SFC = LVNode->getStackFrame();
+PathSensitiveBugReport &Report = getParentTracker().getReport();
+Tracker::Result Result;
+
+// We only track expressions if we believe that they are important. Chances
+// are good that control dependencies to the tracking point are also
+// important because of this, let's explain why we believe control reached
+// this point.
+// TODO: Shouldn't we track control dependencies of every bug location,
+// rather than only tracked expressions?
+if (LVState->getAnalysisManager()
+.getAnalyzerOptions()
+.ShouldTrackConditions) {
+  Report.addVisitor(InputNode);
+  Result.FoundSomethingToTrack = true;
+}
+
+// The message send could be nil due to the receiver being nil.
+// At this point in the path, the receiver should be live since we are at
+// the message send expr. If it is nil, start tracking it.
+if (const Expr *Receiver =
+NilReceiverBRVisitor::getNilReceiver(Inner, LVNode))
+  Result.combineWith(getParentTracker().track(Receiver, LVNode, Opts));
+
+// Track the index if this is an array subscript.
+if (const auto *Arr = dyn_cast(Inner))
+  Result.combineWith(getParentTracker().track(
+  Arr->getIdx(), LVNode,
+  {Opts.Kind, /*EnableNullFPSuppression*/ false}));
+
+// See if the expression we're interested refers to a variable.
+// If so, we can track both its contents and constraints on its value.
+if (ExplodedGraph::isInterestingLValueExpr(Inner)) {
+  SVal LVal = LVNode->getSVal(Inner);
+
+  const MemRegion *RR = getLocationRegionIfReference(Inner, LVNode);
+  bool LVIsNull = LVState->isNull(LVal).isConstrainedTrue();
+
+  // If this is a C++ reference to a null pointer, we are tracking the
+  // pointer. In addition, we should find the store at which the reference
+  // got initialized.
+  if (RR && !LVIsNull)
+if (auto KV = LVal.getAs())
+  Result.combineWith(getParentTracker().track(*KV, RR, Opts, SFC));
+
+  // In case of C++ references, we want to differentiate between a null
+  // reference and reference to null pointer.
+  // If the LVal is null, check if we are dealing with null reference.
+  // For those, we want to track the location of the reference.
+  const MemRegion *R =
+  (RR && LVIsNull) ? RR : LVNode->getSVal(Inner).getAsRegion();
+
+  if (R) {
+
+// Mark both the variable region and its contents as interesting.
+SVal V = LVState->getRawSVal(loc::MemRegionVal(R));
+Report.addVisitor(cast(R), Opts.Kind);
+
+// When we got here, we do have something to track, and we will
+// interrupt.
+Result.FoundSomethingToTrack = true;
+Result.WasInterrupted = true;
+
+MacroNullReturnSuppressionVisitor::addMacroVisitorIfNecessary(
+LVNode, R, Opts.EnableNullFPSuppression, Report, V);
+
+Report.markInteresting(V, Opts.Kind);
+Report.addVisitor(R);
+
+// If the contents are symbolic and null, find out when they became
+// null.
+if (V.getAsLocSymbol(/*IncludeBaseRegions=*/true))
+  if (LVState->isNull(V).isConstrainedTrue())
+Report.addVisitor(V.castAs(),
+fa

[PATCH] D103587: [AIX] Transfer predefined macros

2021-06-03 Thread Chris Bowler via Phabricator via cfe-commits
cebowleratibm requested changes to this revision.
cebowleratibm added a comment.
This revision now requires changes to proceed.

Please rework the test update into init-ppc.c




Comment at: clang/lib/Basic/Targets/PPC.cpp:95
   Builder.defineMacro("_ARCH_PPC");
+  Builder.defineMacro("__THW_PPC__");
   Builder.defineMacro("__powerpc__");

The XL compilers define this macro for Power but GCC does not.  The macro is 
redundant and I recommend we not carry it forward to Linux.  There's probably a 
case to define it on AIX where the prevalent XL compilers have always defined 
it.



Comment at: clang/test/Preprocessor/init-aix.c:1
+// RUN: %clang_cc1 -E -dM < /dev/null | FileCheck -match-full-lines 
-check-prefix AIX %s
+// AIX:#define __THW_PPC__ 1

There are some AIX macro tests already in init-ppc.c.  Note the target triple 
should be specified or this test will break when run on a non AIX host.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D103587

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


[PATCH] D103457: [analyzer] Add forwarding `addVisitor` method

2021-06-03 Thread Valeriy Savchenko 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 rG92d03c20ea71: [analyzer] Add forwarding `addVisitor` method 
(authored by vsavchenko).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D103457

Files:
  clang/include/clang/StaticAnalyzer/Core/BugReporter/BugReporter.h
  clang/lib/StaticAnalyzer/Checkers/MallocChecker.cpp
  clang/lib/StaticAnalyzer/Checkers/NullabilityChecker.cpp
  
clang/lib/StaticAnalyzer/Checkers/RetainCountChecker/RetainCountDiagnostics.cpp
  clang/lib/StaticAnalyzer/Core/BugReporter.cpp
  clang/lib/StaticAnalyzer/Core/BugReporterVisitors.cpp

Index: clang/lib/StaticAnalyzer/Core/BugReporterVisitors.cpp
===
--- clang/lib/StaticAnalyzer/Core/BugReporterVisitors.cpp
+++ clang/lib/StaticAnalyzer/Core/BugReporterVisitors.cpp
@@ -852,10 +852,10 @@
 bool EnableNullFPSuppression, PathSensitiveBugReport &BR,
 const SVal V) {
 AnalyzerOptions &Options = N->getState()->getAnalysisManager().options;
-if (EnableNullFPSuppression &&
-Options.ShouldSuppressNullReturnPaths && V.getAs())
-  BR.addVisitor(std::make_unique(
-  R->getAs(), V));
+if (EnableNullFPSuppression && Options.ShouldSuppressNullReturnPaths &&
+V.getAs())
+  BR.addVisitor(R->getAs(),
+   V);
   }
 
   void* getTag() const {
@@ -1011,14 +1011,12 @@
 AnalyzerOptions &Options = State->getAnalysisManager().options;
 
 bool EnableNullFPSuppression = false;
-if (InEnableNullFPSuppression &&
-Options.ShouldSuppressNullReturnPaths)
+if (InEnableNullFPSuppression && Options.ShouldSuppressNullReturnPaths)
   if (Optional RetLoc = RetVal.getAs())
 EnableNullFPSuppression = State->isNull(*RetLoc).isConstrainedTrue();
 
-BR.addVisitor(std::make_unique(CalleeContext,
-   EnableNullFPSuppression,
-   Options, TKind));
+BR.addVisitor(CalleeContext, EnableNullFPSuppression,
+ Options, TKind);
   }
 
   PathDiagnosticPieceRef visitNodeInitial(const ExplodedNode *N,
@@ -1589,8 +1587,8 @@
   dyn_cast_or_null(V.getAsRegion())) {
   if (const VarRegion *OriginalR = BDR->getOriginalRegion(VR)) {
 if (auto KV = State->getSVal(OriginalR).getAs())
-  BR.addVisitor(std::make_unique(
-  *KV, OriginalR, EnableNullFPSuppression, TKind, OriginSFC));
+  BR.addVisitor(
+  *KV, OriginalR, EnableNullFPSuppression, TKind, OriginSFC);
   }
 }
   }
@@ -2070,8 +2068,7 @@
   // TODO: Shouldn't we track control dependencies of every bug location, rather
   // than only tracked expressions?
   if (LVState->getAnalysisManager().getAnalyzerOptions().ShouldTrackConditions)
-report.addVisitor(std::make_unique(
-  InputNode));
+report.addVisitor(InputNode);
 
   // The message send could be nil due to the receiver being nil.
   // At this point in the path, the receiver should be live since we are at the
@@ -2098,8 +2095,8 @@
 // got initialized.
 if (RR && !LVIsNull)
   if (auto KV = LVal.getAs())
-report.addVisitor(std::make_unique(
-*KV, RR, EnableNullFPSuppression, TKind, SFC));
+report.addVisitor(
+*KV, RR, EnableNullFPSuppression, TKind, SFC);
 
 // In case of C++ references, we want to differentiate between a null
 // reference and reference to null pointer.
@@ -2112,20 +2109,19 @@
 
   // Mark both the variable region and its contents as interesting.
   SVal V = LVState->getRawSVal(loc::MemRegionVal(R));
-  report.addVisitor(
-  std::make_unique(cast(R), TKind));
+  report.addVisitor(cast(R), TKind);
 
   MacroNullReturnSuppressionVisitor::addMacroVisitorIfNecessary(
   LVNode, R, EnableNullFPSuppression, report, V);
 
   report.markInteresting(V, TKind);
-  report.addVisitor(std::make_unique(R));
+  report.addVisitor(R);
 
   // If the contents are symbolic and null, find out when they became null.
   if (V.getAsLocSymbol(/*IncludeBaseRegions=*/true))
 if (LVState->isNull(V).isConstrainedTrue())
-  report.addVisitor(std::make_unique(
-  V.castAs(), false));
+  report.addVisitor(V.castAs(),
+  false);
 
   // Add visitor, which will suppress inline defensive checks.
   if (auto DV = V.getAs())
@@ -2135,14 +2131,13 @@
   // was evaluated. InputNode may as well be too early here, because
   // the symbol is already dead; this, however, is fine because we can
   // still find the node in which it

[clang] 92d03c2 - [analyzer] Add forwarding `addVisitor` method

2021-06-03 Thread Valeriy Savchenko via cfe-commits

Author: Valeriy Savchenko
Date: 2021-06-03T17:10:16+03:00
New Revision: 92d03c20ea71479c78a29da09e377e040d37c3a5

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

LOG: [analyzer] Add forwarding `addVisitor` method

The majority of all `addVisitor` callers follow the same pattern:
  addVisitor(std::make_unique(arg1, arg2, ...));

This patches introduces additional overload for `addVisitor` to simplify
that pattern:
  addVisitor(arg1, arg2, ...);

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

Added: 


Modified: 
clang/include/clang/StaticAnalyzer/Core/BugReporter/BugReporter.h
clang/lib/StaticAnalyzer/Checkers/MallocChecker.cpp
clang/lib/StaticAnalyzer/Checkers/NullabilityChecker.cpp

clang/lib/StaticAnalyzer/Checkers/RetainCountChecker/RetainCountDiagnostics.cpp
clang/lib/StaticAnalyzer/Core/BugReporter.cpp
clang/lib/StaticAnalyzer/Core/BugReporterVisitors.cpp

Removed: 




diff  --git a/clang/include/clang/StaticAnalyzer/Core/BugReporter/BugReporter.h 
b/clang/include/clang/StaticAnalyzer/Core/BugReporter/BugReporter.h
index 27bc0dda1f1ce..0b12ff7075780 100644
--- a/clang/include/clang/StaticAnalyzer/Core/BugReporter/BugReporter.h
+++ b/clang/include/clang/StaticAnalyzer/Core/BugReporter/BugReporter.h
@@ -489,11 +489,16 @@ class PathSensitiveBugReport : public BugReport {
   ///
   /// The visitors should be used when the default trace is not sufficient.
   /// For example, they allow constructing a more elaborate trace.
-  /// \sa registerConditionVisitor(), registerTrackNullOrUndefValue(),
-  /// registerFindLastStore(), registerNilReceiverVisitor(), and
-  /// registerVarDeclsLastStore().
+  /// @{
   void addVisitor(std::unique_ptr visitor);
 
+  template 
+  void addVisitor(Args &&... ConstructorArgs) {
+addVisitor(
+std::make_unique(std::forward(ConstructorArgs)...));
+  }
+  /// @}
+
   /// Remove all visitors attached to this bug report.
   void clearVisitors();
 

diff  --git a/clang/lib/StaticAnalyzer/Checkers/MallocChecker.cpp 
b/clang/lib/StaticAnalyzer/Checkers/MallocChecker.cpp
index 1f3a1e1ac7773..e0f0dc35e7a71 100644
--- a/clang/lib/StaticAnalyzer/Checkers/MallocChecker.cpp
+++ b/clang/lib/StaticAnalyzer/Checkers/MallocChecker.cpp
@@ -2123,7 +2123,7 @@ void 
MallocChecker::HandleMismatchedDealloc(CheckerContext &C,
   os.str(), N);
 R->markInteresting(Sym);
 R->addRange(Range);
-R->addVisitor(std::make_unique(Sym));
+R->addVisitor(Sym);
 C.emitReport(std::move(R));
   }
 }
@@ -2216,7 +2216,7 @@ void MallocChecker::HandleUseAfterFree(CheckerContext &C, 
SourceRange Range,
 
 R->markInteresting(Sym);
 R->addRange(Range);
-R->addVisitor(std::make_unique(Sym));
+R->addVisitor(Sym);
 
 if (AF == AF_InnerBuffer)
   R->addVisitor(allocation_state::getInnerPointerBRVisitor(Sym));
@@ -2252,7 +2252,7 @@ void MallocChecker::HandleDoubleFree(CheckerContext &C, 
SourceRange Range,
 R->markInteresting(Sym);
 if (PrevSym)
   R->markInteresting(PrevSym);
-R->addVisitor(std::make_unique(Sym));
+R->addVisitor(Sym);
 C.emitReport(std::move(R));
   }
 }
@@ -2278,7 +2278,7 @@ void MallocChecker::HandleDoubleDelete(CheckerContext &C, 
SymbolRef Sym) const {
 *BT_DoubleDelete, "Attempt to delete released memory", N);
 
 R->markInteresting(Sym);
-R->addVisitor(std::make_unique(Sym));
+R->addVisitor(Sym);
 C.emitReport(std::move(R));
   }
 }
@@ -2308,7 +2308,7 @@ void MallocChecker::HandleUseZeroAlloc(CheckerContext &C, 
SourceRange Range,
 R->addRange(Range);
 if (Sym) {
   R->markInteresting(Sym);
-  R->addVisitor(std::make_unique(Sym));
+  R->addVisitor(Sym);
 }
 C.emitReport(std::move(R));
   }
@@ -2578,7 +2578,7 @@ void MallocChecker::HandleLeak(SymbolRef Sym, 
ExplodedNode *N,
   *BT_Leak[*CheckKind], os.str(), N, LocUsedForUniqueing,
   AllocNode->getLocationContext()->getDecl());
   R->markInteresting(Sym);
-  R->addVisitor(std::make_unique(Sym, true));
+  R->addVisitor(Sym, true);
   C.emitReport(std::move(R));
 }
 

diff  --git a/clang/lib/StaticAnalyzer/Checkers/NullabilityChecker.cpp 
b/clang/lib/StaticAnalyzer/Checkers/NullabilityChecker.cpp
index bc7a8a3b12a1d..fe8f7e7bf69e7 100644
--- a/clang/lib/StaticAnalyzer/Checkers/NullabilityChecker.cpp
+++ b/clang/lib/StaticAnalyzer/Checkers/NullabilityChecker.cpp
@@ -170,7 +170,7 @@ class NullabilityChecker
 auto R = std::make_unique(*BT, Msg, N);
 if (Region) {
   R->markInteresting(Region);
-  R->addVisitor(std::make_unique(Region));
+  R->addVisitor(Region);
 }
 if (ValueExpr) {
   R->addRange(ValueExpr->getSourceRange());

diff  --git 
a/clang/lib/StaticAnalyzer/Checkers/Ret

[PATCH] D103618: [analyzer] Change FindLastStoreBRVisitor to use Tracker

2021-06-03 Thread Valeriy Savchenko via Phabricator via cfe-commits
vsavchenko created this revision.
vsavchenko added reviewers: NoQ, xazax.hun, martong, steakhal, Szelethus, 
manas, RedDocMD.
Herald added subscribers: ASDenysPetrov, dkrupp, donat.nagy, mikhail.ramalho, 
a.sidorin, rnkovacs, szepet, baloghadamsoftware.
vsavchenko requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

Additionally, this commit completely removes any uses of
FindLastStoreBRVisitor from the analyzer except for the
one in Tracker.

The next step is actually removing this class altogether
from the header file.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D103618

Files:
  clang/include/clang/StaticAnalyzer/Core/BugReporter/BugReporterVisitors.h
  
clang/lib/StaticAnalyzer/Checkers/RetainCountChecker/RetainCountDiagnostics.cpp
  clang/lib/StaticAnalyzer/Checkers/UndefCapturedBlockVarChecker.cpp
  clang/lib/StaticAnalyzer/Core/BugReporterVisitors.cpp

Index: clang/lib/StaticAnalyzer/Core/BugReporterVisitors.cpp
===
--- clang/lib/StaticAnalyzer/Core/BugReporterVisitors.cpp
+++ clang/lib/StaticAnalyzer/Core/BugReporterVisitors.cpp
@@ -1488,8 +1488,8 @@
 if (!IsParam)
   InitE = InitE->IgnoreParenCasts();
 
-bugreporter::trackExpressionValue(StoreSite, InitE, BR, TKind,
-  EnableNullFPSuppression);
+getParentTracker().track(InitE, StoreSite,
+ {TKind, EnableNullFPSuppression});
   }
 
   // Let's try to find the region where the value came from.
@@ -1588,8 +1588,8 @@
   dyn_cast_or_null(V.getAsRegion())) {
   if (const VarRegion *OriginalR = BDR->getOriginalRegion(VR)) {
 if (auto KV = State->getSVal(OriginalR).getAs())
-  BR.addVisitor(
-  *KV, OriginalR, EnableNullFPSuppression, TKind, OriginSFC);
+  getParentTracker().track(
+  *KV, OriginalR, {TKind, EnableNullFPSuppression}, OriginSFC);
   }
 }
   }
@@ -2240,8 +2240,8 @@
 Tracker::Result Tracker::track(KnownSVal V, const MemRegion *R,
TrackingOptions Opts,
const StackFrameContext *Origin) {
-  Report.addVisitor(V, R, Opts.EnableNullFPSuppression,
-Opts.Kind, Origin);
+  Report.addVisitor(
+  *this, V, R, Opts.EnableNullFPSuppression, Opts.Kind, Origin);
   return {true, false};
 }
 
Index: clang/lib/StaticAnalyzer/Checkers/UndefCapturedBlockVarChecker.cpp
===
--- clang/lib/StaticAnalyzer/Checkers/UndefCapturedBlockVarChecker.cpp
+++ clang/lib/StaticAnalyzer/Checkers/UndefCapturedBlockVarChecker.cpp
@@ -86,9 +86,9 @@
 auto R = std::make_unique(*BT, os.str(), N);
 if (const Expr *Ex = FindBlockDeclRefExpr(BE->getBody(), VD))
   R->addRange(Ex->getSourceRange());
-R->addVisitor(std::make_unique(
-*V, VR, /*EnableNullFPSuppression*/ false,
-bugreporter::TrackingKind::Thorough));
+bugreporter::Tracker(*R).track(*V, VR,
+   {bugreporter::TrackingKind::Thorough,
+/*EnableNullFPSuppression*/ false});
 R->disablePathPruning();
 // need location of block
 C.emitReport(std::move(R));
Index: clang/lib/StaticAnalyzer/Checkers/RetainCountChecker/RetainCountDiagnostics.cpp
===
--- clang/lib/StaticAnalyzer/Checkers/RetainCountChecker/RetainCountDiagnostics.cpp
+++ clang/lib/StaticAnalyzer/Checkers/RetainCountChecker/RetainCountDiagnostics.cpp
@@ -980,13 +980,12 @@
 // got from one to another.
 //
 // NOTE: We use the actual SVal stored in AllocBindingToReport here because
-//   FindLastStoreBRVisitor compares SVal's and it can get trickier for
-//   something like derived regions if we want to construct SVal from
-//   Sym. Instead, we take the value that is definitely stored in that
-//   region, thus guaranteeing that FindLastStoreBRVisitor will work.
-addVisitor(
-AllVarBindings[0].second.castAs(), AllocBindingToReport,
-false, bugreporter::TrackingKind::Thorough);
+//   Tracker compares SVal's and it can get trickier for something like
+//   derived regions if we want to construct SVal from Sym.
+//   Instead, we take the value that is definitely stored in that
+//   region, thus guaranteeing that Tracker will work.
+bugreporter::Tracker(*this).track(
+AllVarBindings[0].second.castAs(), AllocBindingToReport);
   } else {
 AllocBindingToReport = AllocFirstBinding;
   }
Index: clang/include/clang/StaticAnalyzer/Core/BugReporter/BugReporterVisitors.h
===
--- clang/includ

[PATCH] D103605: [analyzer] Introduce a new interface for tracking

2021-06-03 Thread Valeriy Savchenko via Phabricator via cfe-commits
vsavchenko updated this revision to Diff 349548.
vsavchenko added a comment.

Minor change


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D103605

Files:
  clang/include/clang/StaticAnalyzer/Core/BugReporter/BugReporterVisitors.h
  clang/lib/StaticAnalyzer/Core/BugReporterVisitors.cpp

Index: clang/lib/StaticAnalyzer/Core/BugReporterVisitors.cpp
===
--- clang/lib/StaticAnalyzer/Core/BugReporterVisitors.cpp
+++ clang/lib/StaticAnalyzer/Core/BugReporterVisitors.cpp
@@ -65,6 +65,7 @@
 
 using namespace clang;
 using namespace ento;
+using namespace bugreporter;
 
 //===--===//
 // Utility functions.
@@ -2045,6 +2046,54 @@
   }
 }
 
+//===--===//
+//Tracker implementation
+//===--===//
+
+Tracker::Tracker(PathSensitiveBugReport &Report) : Report(Report) {
+  // TODO: split trackExpressionValue and FindLastStoreBRVisitor into handlers
+  //   and add them here.
+}
+
+Tracker::Result Tracker::track(const Expr *E, const ExplodedNode *N,
+   TrackingOptions Opts) {
+  if (!E || !N)
+return {};
+
+  const Expr *Inner = peelOffOuterExpr(E, N);
+  const ExplodedNode *LVNode = findNodeForExpression(N, Inner);
+  if (!LVNode)
+return {};
+
+  Result CombinedResult;
+  // Iterate through the handlers in the order according to their priorities.
+  for (ExpressionHandlerPtr &Handler : ExpressionHandlers) {
+CombinedResult.combineWith(Handler->handle(Inner, N, LVNode, Opts));
+if (CombinedResult.WasInterrupted)
+  break;
+  }
+
+  return CombinedResult;
+}
+
+Tracker::Result Tracker::track(KnownSVal V, const MemRegion *R,
+   TrackingOptions Opts,
+   const StackFrameContext *Origin) {
+  // TODO: support this operation after dismantling FindLastStoreBRVisitor
+  return {};
+}
+
+PathDiagnosticPieceRef Tracker::handle(StoreInfo SI, TrackingOptions Opts) {
+  // Iterate through the handlers in the order according to their priorities.
+  for (StoreHandlerPtr &Handler : StoreHandlers) {
+if (PathDiagnosticPieceRef Result = Handler->handle(SI, Opts))
+  // If the handler produced a non-null piece, return it.
+  // There is no need in asking other handlers.
+  return Result;
+  }
+  return {};
+}
+
 bool bugreporter::trackExpressionValue(const ExplodedNode *InputNode,
const Expr *E,
PathSensitiveBugReport &report,
Index: clang/include/clang/StaticAnalyzer/Core/BugReporter/BugReporterVisitors.h
===
--- clang/include/clang/StaticAnalyzer/Core/BugReporter/BugReporterVisitors.h
+++ clang/include/clang/StaticAnalyzer/Core/BugReporter/BugReporterVisitors.h
@@ -21,7 +21,9 @@
 #include "llvm/ADT/FoldingSet.h"
 #include "llvm/ADT/STLExtras.h"
 #include "llvm/ADT/StringRef.h"
+#include 
 #include 
+#include 
 
 namespace clang {
 
@@ -99,6 +101,218 @@
   Condition
 };
 
+/// Defines a set of options altering tracking behavior.
+struct TrackingOptions {
+  /// Specifies the kind of tracking.
+  TrackingKind Kind = TrackingKind::Thorough;
+  /// Specifies whether we should employ false positive suppression
+  /// (inlined defensive checks, returned null).
+  bool EnableNullFPSuppression = true;
+};
+
+/// Describes an event when the value got stored into a memory region.
+struct StoreInfo {
+  enum Kind {
+/// The value got stored into the region during initialization:
+///   int x = 42;
+Initialization,
+/// The value got stored into the region during assignment:
+///   int x;
+///   x = 42;
+Assignment,
+/// The value got stored into the region as block capture.
+/// Block data is modeled as a separate region, thus whenever
+/// the analyzer sees a captured variable, its value is copied
+/// into a special block region.
+BlockCapture
+  };
+
+  /// The type of store operation.
+  Kind StoreKind;
+  /// The expression where the value comes from.
+  /// NOTE: might be null.
+  Expr *SourceOfTheValue;
+  /// Symbolic value that is being stored.
+  SVal Value;
+  /// Memory regions involved in the store operation.
+  ///   Dest <- Origin
+  /// NOTE: Origin might be null, when the stored value doesn't come
+  ///   from another region.
+  const MemRegion *Dest, *Origin;
+};
+
+class ExpressionHandler;
+class StoreHandler;
+
+/// A generalized component for tracking expressions, values, and stores.
+///
+/// Tracker aimes at providing a sensible set of default behaviors that can be
+/// used by any checker, while providing mechanisms to hook into any par

[PATCH] D103616: [analyzer] Reimplement trackExpressionValue as ExpressionHandler

2021-06-03 Thread Valeriy Savchenko via Phabricator via cfe-commits
vsavchenko updated this revision to Diff 349549.
vsavchenko added a comment.

Rebase


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D103616

Files:
  clang/lib/StaticAnalyzer/Core/BugReporterVisitors.cpp

Index: clang/lib/StaticAnalyzer/Core/BugReporterVisitors.cpp
===
--- clang/lib/StaticAnalyzer/Core/BugReporterVisitors.cpp
+++ clang/lib/StaticAnalyzer/Core/BugReporterVisitors.cpp
@@ -2050,7 +2050,168 @@
 //Tracker implementation
 //===--===//
 
+class DefaultExpressionHandler final : public ExpressionHandler {
+public:
+  using ExpressionHandler::ExpressionHandler;
+
+  Tracker::Result handle(const Expr *Inner, const ExplodedNode *InputNode,
+ const ExplodedNode *LVNode,
+ TrackingOptions Opts) override {
+ProgramStateRef LVState = LVNode->getState();
+const StackFrameContext *SFC = LVNode->getStackFrame();
+PathSensitiveBugReport &Report = getParentTracker().getReport();
+Tracker::Result Result;
+
+// We only track expressions if we believe that they are important. Chances
+// are good that control dependencies to the tracking point are also
+// important because of this, let's explain why we believe control reached
+// this point.
+// TODO: Shouldn't we track control dependencies of every bug location,
+// rather than only tracked expressions?
+if (LVState->getAnalysisManager()
+.getAnalyzerOptions()
+.ShouldTrackConditions) {
+  Report.addVisitor(InputNode);
+  Result.FoundSomethingToTrack = true;
+}
+
+// The message send could be nil due to the receiver being nil.
+// At this point in the path, the receiver should be live since we are at
+// the message send expr. If it is nil, start tracking it.
+if (const Expr *Receiver =
+NilReceiverBRVisitor::getNilReceiver(Inner, LVNode))
+  Result.combineWith(getParentTracker().track(Receiver, LVNode, Opts));
+
+// Track the index if this is an array subscript.
+if (const auto *Arr = dyn_cast(Inner))
+  Result.combineWith(getParentTracker().track(
+  Arr->getIdx(), LVNode,
+  {Opts.Kind, /*EnableNullFPSuppression*/ false}));
+
+// See if the expression we're interested refers to a variable.
+// If so, we can track both its contents and constraints on its value.
+if (ExplodedGraph::isInterestingLValueExpr(Inner)) {
+  SVal LVal = LVNode->getSVal(Inner);
+
+  const MemRegion *RR = getLocationRegionIfReference(Inner, LVNode);
+  bool LVIsNull = LVState->isNull(LVal).isConstrainedTrue();
+
+  // If this is a C++ reference to a null pointer, we are tracking the
+  // pointer. In addition, we should find the store at which the reference
+  // got initialized.
+  if (RR && !LVIsNull)
+if (auto KV = LVal.getAs())
+  Result.combineWith(getParentTracker().track(*KV, RR, Opts, SFC));
+
+  // In case of C++ references, we want to differentiate between a null
+  // reference and reference to null pointer.
+  // If the LVal is null, check if we are dealing with null reference.
+  // For those, we want to track the location of the reference.
+  const MemRegion *R =
+  (RR && LVIsNull) ? RR : LVNode->getSVal(Inner).getAsRegion();
+
+  if (R) {
+
+// Mark both the variable region and its contents as interesting.
+SVal V = LVState->getRawSVal(loc::MemRegionVal(R));
+Report.addVisitor(cast(R), Opts.Kind);
+
+// When we got here, we do have something to track, and we will
+// interrupt.
+Result.FoundSomethingToTrack = true;
+Result.WasInterrupted = true;
+
+MacroNullReturnSuppressionVisitor::addMacroVisitorIfNecessary(
+LVNode, R, Opts.EnableNullFPSuppression, Report, V);
+
+Report.markInteresting(V, Opts.Kind);
+Report.addVisitor(R);
+
+// If the contents are symbolic and null, find out when they became
+// null.
+if (V.getAsLocSymbol(/*IncludeBaseRegions=*/true))
+  if (LVState->isNull(V).isConstrainedTrue())
+Report.addVisitor(V.castAs(),
+false);
+
+// Add visitor, which will suppress inline defensive checks.
+if (auto DV = V.getAs())
+  if (!DV->isZeroConstant() && Opts.EnableNullFPSuppression)
+// Note that LVNode may be too late (i.e., too far from the
+// InputNode) because the lvalue may have been computed before the
+// inlined call was evaluated. InputNode may as well be too early
+// here, because the symbol is already dead; this, however, is fine
+// because we can still find the nod

[PATCH] D103618: [analyzer] Change FindLastStoreBRVisitor to use Tracker

2021-06-03 Thread Valeriy Savchenko via Phabricator via cfe-commits
vsavchenko updated this revision to Diff 349550.
vsavchenko added a comment.

Rebase


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D103618

Files:
  clang/include/clang/StaticAnalyzer/Core/BugReporter/BugReporterVisitors.h
  
clang/lib/StaticAnalyzer/Checkers/RetainCountChecker/RetainCountDiagnostics.cpp
  clang/lib/StaticAnalyzer/Checkers/UndefCapturedBlockVarChecker.cpp
  clang/lib/StaticAnalyzer/Core/BugReporterVisitors.cpp

Index: clang/lib/StaticAnalyzer/Core/BugReporterVisitors.cpp
===
--- clang/lib/StaticAnalyzer/Core/BugReporterVisitors.cpp
+++ clang/lib/StaticAnalyzer/Core/BugReporterVisitors.cpp
@@ -1488,8 +1488,8 @@
 if (!IsParam)
   InitE = InitE->IgnoreParenCasts();
 
-bugreporter::trackExpressionValue(StoreSite, InitE, BR, TKind,
-  EnableNullFPSuppression);
+getParentTracker().track(InitE, StoreSite,
+ {TKind, EnableNullFPSuppression});
   }
 
   // Let's try to find the region where the value came from.
@@ -1588,8 +1588,8 @@
   dyn_cast_or_null(V.getAsRegion())) {
   if (const VarRegion *OriginalR = BDR->getOriginalRegion(VR)) {
 if (auto KV = State->getSVal(OriginalR).getAs())
-  BR.addVisitor(
-  *KV, OriginalR, EnableNullFPSuppression, TKind, OriginSFC);
+  getParentTracker().track(
+  *KV, OriginalR, {TKind, EnableNullFPSuppression}, OriginSFC);
   }
 }
   }
@@ -2240,8 +2240,8 @@
 Tracker::Result Tracker::track(KnownSVal V, const MemRegion *R,
TrackingOptions Opts,
const StackFrameContext *Origin) {
-  Report.addVisitor(V, R, Opts.EnableNullFPSuppression,
-Opts.Kind, Origin);
+  Report.addVisitor(
+  *this, V, R, Opts.EnableNullFPSuppression, Opts.Kind, Origin);
   return {true, false};
 }
 
Index: clang/lib/StaticAnalyzer/Checkers/UndefCapturedBlockVarChecker.cpp
===
--- clang/lib/StaticAnalyzer/Checkers/UndefCapturedBlockVarChecker.cpp
+++ clang/lib/StaticAnalyzer/Checkers/UndefCapturedBlockVarChecker.cpp
@@ -86,9 +86,9 @@
 auto R = std::make_unique(*BT, os.str(), N);
 if (const Expr *Ex = FindBlockDeclRefExpr(BE->getBody(), VD))
   R->addRange(Ex->getSourceRange());
-R->addVisitor(std::make_unique(
-*V, VR, /*EnableNullFPSuppression*/ false,
-bugreporter::TrackingKind::Thorough));
+bugreporter::Tracker(*R).track(*V, VR,
+   {bugreporter::TrackingKind::Thorough,
+/*EnableNullFPSuppression*/ false});
 R->disablePathPruning();
 // need location of block
 C.emitReport(std::move(R));
Index: clang/lib/StaticAnalyzer/Checkers/RetainCountChecker/RetainCountDiagnostics.cpp
===
--- clang/lib/StaticAnalyzer/Checkers/RetainCountChecker/RetainCountDiagnostics.cpp
+++ clang/lib/StaticAnalyzer/Checkers/RetainCountChecker/RetainCountDiagnostics.cpp
@@ -980,13 +980,12 @@
 // got from one to another.
 //
 // NOTE: We use the actual SVal stored in AllocBindingToReport here because
-//   FindLastStoreBRVisitor compares SVal's and it can get trickier for
-//   something like derived regions if we want to construct SVal from
-//   Sym. Instead, we take the value that is definitely stored in that
-//   region, thus guaranteeing that FindLastStoreBRVisitor will work.
-addVisitor(
-AllVarBindings[0].second.castAs(), AllocBindingToReport,
-false, bugreporter::TrackingKind::Thorough);
+//   Tracker compares SVal's and it can get trickier for something like
+//   derived regions if we want to construct SVal from Sym.
+//   Instead, we take the value that is definitely stored in that
+//   region, thus guaranteeing that Tracker will work.
+bugreporter::Tracker(*this).track(
+AllVarBindings[0].second.castAs(), AllocBindingToReport);
   } else {
 AllocBindingToReport = AllocFirstBinding;
   }
Index: clang/include/clang/StaticAnalyzer/Core/BugReporter/BugReporterVisitors.h
===
--- clang/include/clang/StaticAnalyzer/Core/BugReporter/BugReporterVisitors.h
+++ clang/include/clang/StaticAnalyzer/Core/BugReporter/BugReporterVisitors.h
@@ -313,6 +313,18 @@
   Tracker &getParentTracker() { return ParentTracker; }
 };
 
+/// Visitor that tracks expressions and values.
+class TrackingBugReporterVisitor : public BugReporterVisitor {
+private:
+  Tracker &ParentTracker;
+
+public:
+  TrackingBugReporterVisitor(Tracker &Paren

[PATCH] D103618: [analyzer] Change FindLastStoreBRVisitor to use Tracker

2021-06-03 Thread Valeriy Savchenko via Phabricator via cfe-commits
vsavchenko added a comment.

This one is completely wrong though.  Visitor can definitely outlive Tracker, 
unlike handlers.  I need to use some reference-counting solution here.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D103618

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


[PATCH] D103286: [clang-format] Add PPIndentWidth option

2021-06-03 Thread Björn Schäpers via Phabricator via cfe-commits
HazardyKnusperkeks added inline comments.



Comment at: clang/include/clang/Format/Format.h:2674
+  /// \endcode
+  signed PPIndentWidth;
+

I've replaced this with `int`, because `signed` results in an exception from 
`dump_format_style.py`.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D103286

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


[PATCH] D80344: [Windows SEH]: HARDWARE EXCEPTION HANDLING (MSVC -EHa) - Part 1

2021-06-03 Thread Alexandre Ganea via Phabricator via cfe-commits
aganea added a comment.

In D80344#2792355 , @tentzen wrote:

> Thank you for reporting this .  From the callstack it does not seem related 
> to this patch.

It was actually `git bisect` which pointed to me to this patch, it could be a 
side-effect of it.

> Could you share the repro case @__compile.rsp temp.i with me?

Will surely do, I don't have a simple repro yet.

I'm also seeing a 3rd issue, different from the ones reported above, but it 
might all be the same thing:

  clang-cl: /mnt/llvm-project/clang/lib/CodeGen/CGCleanup.cpp:1322: void 
EmitSehScope(clang::CodeGen::CodeGenFunction &, llvm::FunctionCallee &): 
Assertion `BB && InvokeDest' failed.
  PLEASE submit a bug report to https://bugs.llvm.org/ and include the crash 
backtrace, preprocessed source, and associated run script.
  Stack dump:
  0.  Program arguments: /mnt/llvm-project/stage0/bin/clang-cl 
@/mnt/llvm-project/__test/__compile.rsp temp.i
  1.  (edited).cpp:1025:1 : current parser token 
'static_assert'
  2.  (edited).cpp:56:1 : LLVM IR generation of 
declaration '(edited)'
  3.  (edited).cpp:91:18: Generating code for declaration '(edited)'
   #0 0x05903223 llvm::sys::PrintStackTrace(llvm::raw_ostream&, int) 
(/mnt/llvm-project/stage0/bin/clang-cl+0x5903223)
   #1 0x05900f6e llvm::sys::RunSignalHandlers() 
(/mnt/llvm-project/stage0/bin/clang-cl+0x5900f6e)
   #2 0x059025cd llvm::sys::CleanupOnSignal(unsigned long) 
(/mnt/llvm-project/stage0/bin/clang-cl+0x59025cd)
   #3 0x05876bc3 (anonymous 
namespace)::CrashRecoveryContextImpl::HandleCrash(int, unsigned long) 
CrashRecoveryContext.cpp:0:0
   #4 0x05876d2e CrashRecoverySignalHandler(int) 
CrashRecoveryContext.cpp:0:0
   #5 0x7f88cc4d73c0 __restore_rt 
(/lib/x86_64-linux-gnu/libpthread.so.0+0x153c0)
   #6 0x7f88cbf8818b raise (/lib/x86_64-linux-gnu/libc.so.6+0x4618b)
   #7 0x7f88cbf67859 abort (/lib/x86_64-linux-gnu/libc.so.6+0x25859)
   #8 0x7f88cbf67729 (/lib/x86_64-linux-gnu/libc.so.6+0x25729)
   #9 0x7f88cbf78f36 (/lib/x86_64-linux-gnu/libc.so.6+0x36f36)
  #10 0x05c91e05 EmitSehScope(clang::CodeGen::CodeGenFunction&, 
llvm::FunctionCallee&) CGCleanup.cpp:0:0
  #11 0x05c8c918 
clang::CodeGen::EHScopeStack::pushCleanup(clang::CodeGen::CleanupKind, unsigned 
long) (/mnt/llvm-project/stage0/bin/clang-cl+0x5c8c918)
  #12 0x05bf80ef void 
clang::CodeGen::CodeGenFunction::pushFullExprCleanup(clang::CodeGen::CleanupKind, 
clang::CodeGen::Address, llvm::Value*) CGCall.cpp:0:0
  #13 0x05cb937c 
clang::CodeGen::CodeGenFunction::EmitMaterializeTemporaryExpr(clang::MaterializeTemporaryExpr
 const*) (/mnt/llvm-project/stage0/bin/clang-cl+0x5cb937c)
  #14 0x05cb76a3 
clang::CodeGen::CodeGenFunction::EmitLValue(clang::Expr const*) 
(/mnt/llvm-project/stage0/bin/clang-cl+0x5cb76a3)
  #15 0x05cbba94 
clang::CodeGen::CodeGenFunction::EmitReferenceBindingToExpr(clang::Expr const*) 
(/mnt/llvm-project/stage0/bin/clang-cl+0x5cbba94)
  #16 0x05bf0114 
clang::CodeGen::CodeGenFunction::EmitCallArg(clang::CodeGen::CallArgList&, 
clang::Expr const*, clang::QualType) 
(/mnt/llvm-project/stage0/bin/clang-cl+0x5bf0114)
  #17 0x05bef273 
clang::CodeGen::CodeGenFunction::EmitCallArgs(clang::CodeGen::CallArgList&, 
clang::CodeGen::CodeGenFunction::PrototypeWrapper, 
llvm::iterator_range >, 
clang::CodeGen::CodeGenFunction::AbstractCallee, unsigned int, 
clang::CodeGen::CodeGenFunction::EvaluationOrder) 
(/mnt/llvm-project/stage0/bin/clang-cl+0x5bef273)
  #18 0x05e1368d 
commonEmitCXXMemberOrOperatorCall(clang::CodeGen::CodeGenFunction&, 
clang::CXXMethodDecl const*, llvm::Value*, llvm::Value*, clang::QualType, 
clang::CallExpr const*, clang::CodeGen::CallArgList&, 
clang::CodeGen::CallArgList*) CGExprCXX.cpp:0:0
  #19 0x05e13383 
clang::CodeGen::CodeGenFunction::EmitCXXMemberOrOperatorCall(clang::CXXMethodDecl
 const*, clang::CodeGen::CGCallee const&, clang::CodeGen::ReturnValueSlot, 
llvm::Value*, llvm::Value*, clang::QualType, clang::CallExpr const*, 
clang::CodeGen::CallArgList*) (/mnt/llvm-project/stage0/bin/clang-cl+0x5e13383)
  #20 0x05e15afa 
clang::CodeGen::CodeGenFunction::EmitCXXMemberOrOperatorMemberCallExpr(clang::CallExpr
 const*, clang::CXXMethodDecl const*, clang::CodeGen::ReturnValueSlot, bool, 
clang::NestedNameSpecifier*, bool, clang::Expr const*) 
(/mnt/llvm-project/stage0/bin/clang-cl+0x5e15afa)
  #21 0x05e16330 
clang::CodeGen::CodeGenFunction::EmitCXXOperatorMemberCallExpr(clang::CXXOperatorCallExpr
 const*, clang::CXXMethodDecl const*, clang::CodeGen::ReturnValueSlot) 
(/mnt/llvm-project/stage0/bin/clang-cl+0x5e16330)
  #22 0x05cd51f7 
clang::CodeGen::CodeGenFunction::EmitCallExpr(clang::CallExpr const*, 
clang::CodeGen::ReturnValueSlot) 
(/mnt/llvm-project/stage0/bin/clang-cl+0x5cd51f7)
  #23 0x05cc27e1 
clang::CodeGen::CodeGenFunction::EmitCallExprLValue(clang:

[PATCH] D103587: [AIX] Transfer predefined macros

2021-06-03 Thread Jake Egan via Phabricator via cfe-commits
Jake-Egan updated this revision to Diff 349557.
Jake-Egan edited the summary of this revision.
Jake-Egan added a comment.

Removed __THW_PPC__ and moved tests to init-ppc.c


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D103587

Files:
  clang/lib/Basic/Targets/OSTargets.h
  clang/lib/Basic/Targets/PPC.cpp
  clang/test/Preprocessor/init-aix.c
  clang/test/Preprocessor/init-ppc.c


Index: clang/test/Preprocessor/init-ppc.c
===
--- clang/test/Preprocessor/init-ppc.c
+++ clang/test/Preprocessor/init-ppc.c
@@ -541,6 +541,9 @@
 // PPC-AIX:#define __SIZE_MAX__ 4294967295UL
 // PPC-AIX:#define __SIZE_TYPE__ long unsigned int
 // PPC-AIX:#define __SIZE_WIDTH__ 32
+// PPC-AIX-NOT:#define __STDC_NO_ATOMICS__ 1
+// PPC-AIX-NOT:#define __STDC_NO_THREADS__ 1
+// PPC-AIX:#define __TOS_AIX__ 1
 // PPC-AIX:#define __UINT16_C_SUFFIX__
 // PPC-AIX:#define __UINT16_MAX__ 65535
 // PPC-AIX:#define __UINT16_TYPE__ unsigned short
@@ -723,6 +726,13 @@
 // RUN: %clang_cc1 -E -dM -ffreestanding -triple=powerpc-ibm-aix7.1.0.0 
-fno-signed-char < /dev/null | FileCheck -match-full-lines -check-prefix 
PPC-AIX-NOTHREADSAFE %s
 // PPC-AIX-NOTHREADSAFE-NOT:#define _THREAD_SAFE 1
 
+// RUN: %clang_cc1 -x c -std=c11 -E -dM -ffreestanding 
-triple=powerpc-ibm-aix7.1.0.0 -fno-signed-char < /dev/null | FileCheck 
-match-full-lines -check-prefix PPC-AIX-STDC %s
+// RUN: %clang_cc1 -x c -std=c1x -E -dM -ffreestanding 
-triple=powerpc-ibm-aix7.1.0.0 -fno-signed-char < /dev/null | FileCheck 
-match-full-lines -check-prefix PPC-AIX-STDC %s
+// RUN: %clang_cc1 -x c -std=iso9899:2011 -E -dM -ffreestanding 
-triple=powerpc-ibm-aix7.10.0 -fno-signed-char  < /dev/null | FileCheck 
-match-full-lines -check-prefix PPC-AIX-STDC %s
+// RUN: %clang_cc1 -x c -std=gnu11 -E -dM -ffreestanding 
-triple=powerpc-ibm-aix7.1.0.0 -fno-signed-char  < /dev/null | FileCheck 
-match-full-lines -check-prefix PPC-AIX-STDC %s
+// PPC-AIX-STDC:#define __STDC_NO_ATOMICS__ 1
+// PPC-AIX-STDC:#define __STDC_NO_THREADS__ 1
+
 // RUN: %clang_cc1 -E -dM -ffreestanding -triple=powerpc-unknown-linux-gnu 
-fno-signed-char < /dev/null | FileCheck -match-full-lines -check-prefix 
PPC-LINUX %s
 //
 // PPC-LINUX:#define _ARCH_PPC 1
Index: clang/test/Preprocessor/init-aix.c
===
--- clang/test/Preprocessor/init-aix.c
+++ /dev/null
@@ -1,12 +0,0 @@
-// RUN: %clang_cc1 -E -dM < /dev/null | FileCheck -match-full-lines 
-check-prefix AIX %s
-// AIX:#define __THW_PPC__ 1
-// AIX:#define __TOS_AIX__ 1
-// AIX-NOT:#define __STDC_NO_ATOMICS__ 1
-// AIX-NOT:#define __STDC_NO_THREADS__ 1
-//
-// RUN: %clang_cc1 -x c -std=c11 -E -dM < /dev/null | FileCheck 
-match-full-lines -check-prefix AIX-STDC %s
-// RUN: %clang_cc1 -x c -std=c1x -E -dM < /dev/null | FileCheck 
-match-full-lines -check-prefix AIX-STDC %s
-// RUN: %clang_cc1 -x c -std=iso9899:2011 -E -dM < /dev/null | FileCheck 
-match-full-lines -check-prefix AIX-STDC %s
-// RUN: %clang_cc1 -x c -std=gnu11 -E -dM < /dev/null | FileCheck 
-match-full-lines -check-prefix AIX-STDC %s
-// AIX-STDC:#define __STDC_NO_ATOMICS__ 1
-// AIX-STDC:#define __STDC_NO_THREADS__ 1
Index: clang/lib/Basic/Targets/PPC.cpp
===
--- clang/lib/Basic/Targets/PPC.cpp
+++ clang/lib/Basic/Targets/PPC.cpp
@@ -92,7 +92,6 @@
   Builder.defineMacro("__ppc__");
   Builder.defineMacro("__PPC__");
   Builder.defineMacro("_ARCH_PPC");
-  Builder.defineMacro("__THW_PPC__");
   Builder.defineMacro("__powerpc__");
   Builder.defineMacro("__POWERPC__");
   if (PointerWidth == 64) {
Index: clang/lib/Basic/Targets/OSTargets.h
===
--- clang/lib/Basic/Targets/OSTargets.h
+++ clang/lib/Basic/Targets/OSTargets.h
@@ -674,11 +674,11 @@
 Builder.defineMacro("_IBMR2");
 Builder.defineMacro("_POWER");
 
-Builder.defineMacro("__TOS_AIX__");
 Builder.defineMacro("_AIX");
+Builder.defineMacro("__TOS_AIX__");
 
 if (Opts.LangStd == LangStandard::lang_c11 ||
-Opts.LangStd == LangStandard::lang_gnu11){
+Opts.LangStd == LangStandard::lang_gnu11) {
   Builder.defineMacro("__STDC_NO_ATOMICS__");
   Builder.defineMacro("__STDC_NO_THREADS__");
 }


Index: clang/test/Preprocessor/init-ppc.c
===
--- clang/test/Preprocessor/init-ppc.c
+++ clang/test/Preprocessor/init-ppc.c
@@ -541,6 +541,9 @@
 // PPC-AIX:#define __SIZE_MAX__ 4294967295UL
 // PPC-AIX:#define __SIZE_TYPE__ long unsigned int
 // PPC-AIX:#define __SIZE_WIDTH__ 32
+// PPC-AIX-NOT:#define __STDC_NO_ATOMICS__ 1
+// PPC-AIX-NOT:#define __STDC_NO_THREADS__ 1
+// PPC-AIX:#define __TOS_AIX__ 1
 // PPC-AIX:#define __UINT16_C_SUFFIX__
 // PPC-AIX:#define __UINT16_MAX__ 65535
 // PPC-AIX:#define __UINT16_

[PATCH] D103618: [analyzer] Change FindLastStoreBRVisitor to use Tracker

2021-06-03 Thread Valeriy Savchenko via Phabricator via cfe-commits
vsavchenko updated this revision to Diff 349563.
vsavchenko added a comment.

Fix dangling reference problem


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D103618

Files:
  clang/include/clang/StaticAnalyzer/Core/BugReporter/BugReporterVisitors.h
  
clang/lib/StaticAnalyzer/Checkers/RetainCountChecker/RetainCountDiagnostics.cpp
  clang/lib/StaticAnalyzer/Checkers/UndefCapturedBlockVarChecker.cpp
  clang/lib/StaticAnalyzer/Core/BugReporterVisitors.cpp

Index: clang/lib/StaticAnalyzer/Core/BugReporterVisitors.cpp
===
--- clang/lib/StaticAnalyzer/Core/BugReporterVisitors.cpp
+++ clang/lib/StaticAnalyzer/Core/BugReporterVisitors.cpp
@@ -1488,8 +1488,8 @@
 if (!IsParam)
   InitE = InitE->IgnoreParenCasts();
 
-bugreporter::trackExpressionValue(StoreSite, InitE, BR, TKind,
-  EnableNullFPSuppression);
+getParentTracker().track(InitE, StoreSite,
+ {TKind, EnableNullFPSuppression});
   }
 
   // Let's try to find the region where the value came from.
@@ -1588,8 +1588,8 @@
   dyn_cast_or_null(V.getAsRegion())) {
   if (const VarRegion *OriginalR = BDR->getOriginalRegion(VR)) {
 if (auto KV = State->getSVal(OriginalR).getAs())
-  BR.addVisitor(
-  *KV, OriginalR, EnableNullFPSuppression, TKind, OriginSFC);
+  getParentTracker().track(
+  *KV, OriginalR, {TKind, EnableNullFPSuppression}, OriginSFC);
   }
 }
   }
@@ -2240,8 +2240,8 @@
 Tracker::Result Tracker::track(KnownSVal V, const MemRegion *R,
TrackingOptions Opts,
const StackFrameContext *Origin) {
-  Report.addVisitor(V, R, Opts.EnableNullFPSuppression,
-Opts.Kind, Origin);
+  Report.addVisitor(
+  this, V, R, Opts.EnableNullFPSuppression, Opts.Kind, Origin);
   return {true, false};
 }
 
@@ -2262,11 +2262,18 @@
bugreporter::TrackingKind TKind,
bool EnableNullFPSuppression) {
 
-  return Tracker(report)
-  .track(E, InputNode, {TKind, EnableNullFPSuppression})
+  return Tracker::create(report)
+  ->track(E, InputNode, {TKind, EnableNullFPSuppression})
   .FoundSomethingToTrack;
 }
 
+void bugreporter::trackStoredValue(KnownSVal V, const MemRegion *R,
+   PathSensitiveBugReport &Report,
+   TrackingOptions Opts,
+   const StackFrameContext *Origin) {
+  Tracker::create(Report)->track(V, R, Opts, Origin);
+}
+
 //===--===//
 // Implementation of NulReceiverBRVisitor.
 //===--===//
Index: clang/lib/StaticAnalyzer/Checkers/UndefCapturedBlockVarChecker.cpp
===
--- clang/lib/StaticAnalyzer/Checkers/UndefCapturedBlockVarChecker.cpp
+++ clang/lib/StaticAnalyzer/Checkers/UndefCapturedBlockVarChecker.cpp
@@ -86,9 +86,9 @@
 auto R = std::make_unique(*BT, os.str(), N);
 if (const Expr *Ex = FindBlockDeclRefExpr(BE->getBody(), VD))
   R->addRange(Ex->getSourceRange());
-R->addVisitor(std::make_unique(
-*V, VR, /*EnableNullFPSuppression*/ false,
-bugreporter::TrackingKind::Thorough));
+bugreporter::trackStoredValue(*V, VR, *R,
+  {bugreporter::TrackingKind::Thorough,
+   /*EnableNullFPSuppression*/ false});
 R->disablePathPruning();
 // need location of block
 C.emitReport(std::move(R));
Index: clang/lib/StaticAnalyzer/Checkers/RetainCountChecker/RetainCountDiagnostics.cpp
===
--- clang/lib/StaticAnalyzer/Checkers/RetainCountChecker/RetainCountDiagnostics.cpp
+++ clang/lib/StaticAnalyzer/Checkers/RetainCountChecker/RetainCountDiagnostics.cpp
@@ -980,13 +980,12 @@
 // got from one to another.
 //
 // NOTE: We use the actual SVal stored in AllocBindingToReport here because
-//   FindLastStoreBRVisitor compares SVal's and it can get trickier for
+//   trackStoredValue compares SVal's and it can get trickier for
 //   something like derived regions if we want to construct SVal from
 //   Sym. Instead, we take the value that is definitely stored in that
-//   region, thus guaranteeing that FindLastStoreBRVisitor will work.
-addVisitor(
-AllVarBindings[0].second.castAs(), AllocBindingToReport,
-false, bugreporter::TrackingKind::Thorough);
+//   region, thus gu

[PATCH] D100581: [Clang] -Wunused-but-set-parameter and -Wunused-but-set-variable

2021-06-03 Thread Michael Benfield via Phabricator via cfe-commits
mbenfield added a comment.

In D100581#2795966 , @sberg wrote:

> Is it intentional that this warns about volatile variables as in

Yes, volatile was intentional. Alright, I will add a test for this case.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D100581

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


[PATCH] D103605: [analyzer] Introduce a new interface for tracking

2021-06-03 Thread Gabor Marton via Phabricator via cfe-commits
martong added a comment.

In D103605#2796141 , @vsavchenko 
wrote:

> In D103605#2796111 , @martong wrote:
>
>> Great initiative! You haven't mention `markInteresting` functions, but I 
>> think it would be really important to incorporate that functionality here as 
>> well. IMHO, `markInteresting` shouldn't have been part of the public API 
>> ever, Checkers should have been calling only the trackExpressionValue (as 
>> internally that calls markInteresting anyway).
>
> Oh, yes, interesting-ness doesn't provide a very clear interface for the 
> feedback loop that I'm trying to adjust.  From the perspective of the use 
> "mark interesting whatever your checker is interested in and the core will 
> figure it out", it's fine.  It has a clear message and you simply expect the 
> engine to do its magic.  The problem comes when you try to catch something 
> interesting from your own checker-specific visitor.  In that use case, you, 
> first of all, really need to understand how trackers traverse the graph and 
> what they might consider interesting, and rely on the fact that you will get 
> the right interesting thingy.  So, the predicate checking for 
> interesting-ness available to the users, is not very helpful IMO.

What I mean is that probably we should have the following function(s) provided 
for the user:

  Result track(SVal InterestingSVal, );
  Result track(const MemRegion* InterestingRegion, );
  Result track(SymbolRef InterestingSym, );

Or even better,  only `track(SVal InterestingSVal, )` would be enough to be 
public. Then we could deprecate `markInteresting` and all Checkers should use 
your new Tracker interface. As I see, both trackExpressionValue and 
markInteresting serves the same purpose: i.e. to do a backward slicing in the 
ExplodedGraph to select interesing/important nodes that should be presented to 
the user.




Comment at: 
clang/include/clang/StaticAnalyzer/Core/BugReporter/BugReporterVisitors.h:231
+  template 
+  void addExpressionHandlerToTheTop(Args &&... ConstructorArgs) {
+addExpressionHandlerToTheTop(std::make_unique(

vsavchenko wrote:
> vsavchenko wrote:
> > martong wrote:
> > > This naming is a bit too bloated to me, what do you think about this:
> > > ```
> > > enum class Position { Front, Back };
> > > addExpressionHandler(Front, ...) {
> > > ```
> > Maybe `addHighPriorityHandler` and `addLowPriorityHandler`? There is 
> > probably no reason to put `Expression` and `Store` into the actual name.
> What do you think about this solution?
Sounds good.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D103605

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


[PATCH] D103587: [AIX] Transfer predefined macros

2021-06-03 Thread Jake Egan via Phabricator via cfe-commits
Jake-Egan updated this revision to Diff 349564.
Jake-Egan marked an inline comment as done.
Jake-Egan added a comment.

Fix formatting


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D103587

Files:
  clang/lib/Basic/Targets/OSTargets.h
  clang/test/Preprocessor/init-ppc.c


Index: clang/test/Preprocessor/init-ppc.c
===
--- clang/test/Preprocessor/init-ppc.c
+++ clang/test/Preprocessor/init-ppc.c
@@ -541,6 +541,9 @@
 // PPC-AIX:#define __SIZE_MAX__ 4294967295UL
 // PPC-AIX:#define __SIZE_TYPE__ long unsigned int
 // PPC-AIX:#define __SIZE_WIDTH__ 32
+// PPC-AIX-NOT:#define __STDC_NO_ATOMICS__ 1
+// PPC-AIX-NOT:#define __STDC_NO_THREADS__ 1
+// PPC-AIX:#define __TOS_AIX__ 1
 // PPC-AIX:#define __UINT16_C_SUFFIX__
 // PPC-AIX:#define __UINT16_MAX__ 65535
 // PPC-AIX:#define __UINT16_TYPE__ unsigned short
@@ -723,6 +726,13 @@
 // RUN: %clang_cc1 -E -dM -ffreestanding -triple=powerpc-ibm-aix7.1.0.0 
-fno-signed-char < /dev/null | FileCheck -match-full-lines -check-prefix 
PPC-AIX-NOTHREADSAFE %s
 // PPC-AIX-NOTHREADSAFE-NOT:#define _THREAD_SAFE 1
 
+// RUN: %clang_cc1 -x c -std=c11 -E -dM -ffreestanding 
-triple=powerpc-ibm-aix7.1.0.0 -fno-signed-char < /dev/null | FileCheck 
-match-full-lines -check-prefix PPC-AIX-STDC %s
+// RUN: %clang_cc1 -x c -std=c1x -E -dM -ffreestanding 
-triple=powerpc-ibm-aix7.1.0.0 -fno-signed-char < /dev/null | FileCheck 
-match-full-lines -check-prefix PPC-AIX-STDC %s
+// RUN: %clang_cc1 -x c -std=iso9899:2011 -E -dM -ffreestanding 
-triple=powerpc-ibm-aix7.10.0 -fno-signed-char  < /dev/null | FileCheck 
-match-full-lines -check-prefix PPC-AIX-STDC %s
+// RUN: %clang_cc1 -x c -std=gnu11 -E -dM -ffreestanding 
-triple=powerpc-ibm-aix7.1.0.0 -fno-signed-char  < /dev/null | FileCheck 
-match-full-lines -check-prefix PPC-AIX-STDC %s
+// PPC-AIX-STDC:#define __STDC_NO_ATOMICS__ 1
+// PPC-AIX-STDC:#define __STDC_NO_THREADS__ 1
+
 // RUN: %clang_cc1 -E -dM -ffreestanding -triple=powerpc-unknown-linux-gnu 
-fno-signed-char < /dev/null | FileCheck -match-full-lines -check-prefix 
PPC-LINUX %s
 //
 // PPC-LINUX:#define _ARCH_PPC 1
Index: clang/lib/Basic/Targets/OSTargets.h
===
--- clang/lib/Basic/Targets/OSTargets.h
+++ clang/lib/Basic/Targets/OSTargets.h
@@ -675,6 +675,13 @@
 Builder.defineMacro("_POWER");
 
 Builder.defineMacro("_AIX");
+Builder.defineMacro("__TOS_AIX__");
+
+if (Opts.LangStd == LangStandard::lang_c11 ||
+Opts.LangStd == LangStandard::lang_gnu11) {
+  Builder.defineMacro("__STDC_NO_ATOMICS__");
+  Builder.defineMacro("__STDC_NO_THREADS__");
+}
 
 if (Opts.EnableAIXExtendedAltivecABI)
   Builder.defineMacro("__EXTABI__");


Index: clang/test/Preprocessor/init-ppc.c
===
--- clang/test/Preprocessor/init-ppc.c
+++ clang/test/Preprocessor/init-ppc.c
@@ -541,6 +541,9 @@
 // PPC-AIX:#define __SIZE_MAX__ 4294967295UL
 // PPC-AIX:#define __SIZE_TYPE__ long unsigned int
 // PPC-AIX:#define __SIZE_WIDTH__ 32
+// PPC-AIX-NOT:#define __STDC_NO_ATOMICS__ 1
+// PPC-AIX-NOT:#define __STDC_NO_THREADS__ 1
+// PPC-AIX:#define __TOS_AIX__ 1
 // PPC-AIX:#define __UINT16_C_SUFFIX__
 // PPC-AIX:#define __UINT16_MAX__ 65535
 // PPC-AIX:#define __UINT16_TYPE__ unsigned short
@@ -723,6 +726,13 @@
 // RUN: %clang_cc1 -E -dM -ffreestanding -triple=powerpc-ibm-aix7.1.0.0 -fno-signed-char < /dev/null | FileCheck -match-full-lines -check-prefix PPC-AIX-NOTHREADSAFE %s
 // PPC-AIX-NOTHREADSAFE-NOT:#define _THREAD_SAFE 1
 
+// RUN: %clang_cc1 -x c -std=c11 -E -dM -ffreestanding -triple=powerpc-ibm-aix7.1.0.0 -fno-signed-char < /dev/null | FileCheck -match-full-lines -check-prefix PPC-AIX-STDC %s
+// RUN: %clang_cc1 -x c -std=c1x -E -dM -ffreestanding -triple=powerpc-ibm-aix7.1.0.0 -fno-signed-char < /dev/null | FileCheck -match-full-lines -check-prefix PPC-AIX-STDC %s
+// RUN: %clang_cc1 -x c -std=iso9899:2011 -E -dM -ffreestanding -triple=powerpc-ibm-aix7.10.0 -fno-signed-char  < /dev/null | FileCheck -match-full-lines -check-prefix PPC-AIX-STDC %s
+// RUN: %clang_cc1 -x c -std=gnu11 -E -dM -ffreestanding -triple=powerpc-ibm-aix7.1.0.0 -fno-signed-char  < /dev/null | FileCheck -match-full-lines -check-prefix PPC-AIX-STDC %s
+// PPC-AIX-STDC:#define __STDC_NO_ATOMICS__ 1
+// PPC-AIX-STDC:#define __STDC_NO_THREADS__ 1
+
 // RUN: %clang_cc1 -E -dM -ffreestanding -triple=powerpc-unknown-linux-gnu -fno-signed-char < /dev/null | FileCheck -match-full-lines -check-prefix PPC-LINUX %s
 //
 // PPC-LINUX:#define _ARCH_PPC 1
Index: clang/lib/Basic/Targets/OSTargets.h
===
--- clang/lib/Basic/Targets/OSTargets.h
+++ clang/lib/Basic/Targets/OSTargets.h
@@ -675,6 +675,13 @@
 Builder.defineMacro("_POWER");
 
 Builder.defineMacro("_AI

[PATCH] D103516: [clang][deps] Customize PCM path via -build-dir argument

2021-06-03 Thread Michael Spencer via Phabricator via cfe-commits
Bigcheese accepted this revision.
Bigcheese added a comment.
This revision is now accepted and ready to land.

lgtm with a few minor changes.




Comment at: clang/tools/clang-scan-deps/ClangScanDeps.cpp:168-169
+"build-dir",
+llvm::cl::desc("With '-generate-modules-path-args', put the PCM files in"
+   "the provided directory instead of the module cache."),
+llvm::cl::cat(DependencyScannerCategory));

This was a bit confusing at first. I think it would be better to say that the 
paths that it returns are using this directory as a base. clang-scan-deps 
doesn't actually put files in here itself, it just returns paths that use it.



Comment at: clang/tools/clang-scan-deps/ClangScanDeps.cpp:419
   Modules;
+  std::unordered_map
+  PCMPaths;

This doesn't need to use the `IndexedModuleID`. It can just use `ModuleID`.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D103516

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


[PATCH] D103605: [analyzer] Introduce a new interface for tracking

2021-06-03 Thread Valeriy Savchenko via Phabricator via cfe-commits
vsavchenko added a comment.

In D103605#2796425 , @martong wrote:

> In D103605#2796141 , @vsavchenko 
> wrote:
>
>> In D103605#2796111 , @martong 
>> wrote:
>>
>>> Great initiative! You haven't mention `markInteresting` functions, but I 
>>> think it would be really important to incorporate that functionality here 
>>> as well. IMHO, `markInteresting` shouldn't have been part of the public API 
>>> ever, Checkers should have been calling only the trackExpressionValue (as 
>>> internally that calls markInteresting anyway).
>>
>> Oh, yes, interesting-ness doesn't provide a very clear interface for the 
>> feedback loop that I'm trying to adjust.  From the perspective of the use 
>> "mark interesting whatever your checker is interested in and the core will 
>> figure it out", it's fine.  It has a clear message and you simply expect the 
>> engine to do its magic.  The problem comes when you try to catch something 
>> interesting from your own checker-specific visitor.  In that use case, you, 
>> first of all, really need to understand how trackers traverse the graph and 
>> what they might consider interesting, and rely on the fact that you will get 
>> the right interesting thingy.  So, the predicate checking for 
>> interesting-ness available to the users, is not very helpful IMO.
>
> What I mean is that probably we should have the following function(s) 
> provided for the user:
>
>   Result track(SVal InterestingSVal, );
>   Result track(const MemRegion* InterestingRegion, );
>   Result track(SymbolRef InterestingSym, );
>
> Or even better,  only `track(SVal InterestingSVal, )` would be enough to 
> be public. Then we could deprecate `markInteresting` and all Checkers should 
> use your new Tracker interface. As I see, both trackExpressionValue and 
> markInteresting serves the same purpose: i.e. to do a backward slicing in the 
> ExplodedGraph to select interesing/important nodes that should be presented 
> to the user.

We need to define semantics for those a bit better I think.  Not that 
`trackExpressionValue` or `FindLastStoreBRVisitor` are defined very well!  But 
I want to approach it incrementally and first of all make those two extendable.
But of course, whatever tracks something (want to perform backward slicing) 
should probably go through the tracker in the future.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D103605

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


[PATCH] D103623: [Clang] Test case for -Wunused-but-set-variable, warn for volatile.

2021-06-03 Thread Michael Benfield via Phabricator via cfe-commits
mbenfield created this revision.
mbenfield added a reviewer: sberg.
mbenfield requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

This was requested by sberg.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D103623

Files:
  clang/test/Sema/warn-unused-but-set-variables.c


Index: clang/test/Sema/warn-unused-but-set-variables.c
===
--- clang/test/Sema/warn-unused-but-set-variables.c
+++ clang/test/Sema/warn-unused-but-set-variables.c
@@ -23,6 +23,10 @@
   int a;
   w = (a = 0);
 
+  // Following gcc, warn for a volatile variable.
+  volatile int b; // expected-warning{{variable 'b' set but not used}}
+  b = 0;
+
   int x;
   x = 0;
   return x;


Index: clang/test/Sema/warn-unused-but-set-variables.c
===
--- clang/test/Sema/warn-unused-but-set-variables.c
+++ clang/test/Sema/warn-unused-but-set-variables.c
@@ -23,6 +23,10 @@
   int a;
   w = (a = 0);
 
+  // Following gcc, warn for a volatile variable.
+  volatile int b; // expected-warning{{variable 'b' set but not used}}
+  b = 0;
+
   int x;
   x = 0;
   return x;
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D103563: [HIP] Fix amdgcn builtin for long type

2021-06-03 Thread Yaxun Liu via Phabricator via cfe-commits
yaxunl updated this revision to Diff 349566.
yaxunl edited the summary of this revision.
yaxunl added a comment.
Herald added a subscriber: Anastasia.

fixed regressions with OpenCL. Use fixed length 64 bit int type instead of long 
long type


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

https://reviews.llvm.org/D103563

Files:
  clang/include/clang/Basic/BuiltinsAMDGPU.def
  clang/test/CodeGenCUDA/builtins-amdgcn.cu

Index: clang/test/CodeGenCUDA/builtins-amdgcn.cu
===
--- clang/test/CodeGenCUDA/builtins-amdgcn.cu
+++ clang/test/CodeGenCUDA/builtins-amdgcn.cu
@@ -1,4 +1,11 @@
-// RUN: %clang_cc1 -triple amdgcn -fcuda-is-device -emit-llvm %s -o - | FileCheck %s
+// RUN: %clang_cc1 -triple amdgcn-amd-amdhsa -target-cpu gfx906 \
+// RUN:  -aux-triple x86_64-unknown-linux-gnu -fcuda-is-device -emit-llvm %s \
+// RUN:  -o - | FileCheck %s
+
+// RUN: %clang_cc1 -triple amdgcn-amd-amdhsa -target-cpu gfx906 \
+// RUN:  -aux-triple x86_64-pc-windows-msvc -fcuda-is-device -emit-llvm %s \
+// RUN:  -o - | FileCheck %s
+
 #include "Inputs/cuda.h"
 
 // CHECK-LABEL: @_Z16use_dispatch_ptrPi(
@@ -22,3 +29,32 @@
 __global__ void endpgm() {
   __builtin_amdgcn_endpgm();
 }
+
+// Check the 64 bit argument is correctly passed to the intrinsic without truncation or assertion.
+
+// CHECK-LABEL: @_Z14test_uicmp_i64
+// CHECK:  store i64* %out, i64** %out.addr.ascast
+// CHECK-NEXT:  store i64 %a, i64* %a.addr.ascast
+// CHECK-NEXT:  store i64 %b, i64* %b.addr.ascast
+// CHECK-NEXT:  %[[V0:.*]] = load i64, i64* %a.addr.ascast
+// CHECK-NEXT:  %[[V1:.*]] = load i64, i64* %b.addr.ascast
+// CHECK-NEXT:  %[[V2:.*]] = call i64 @llvm.amdgcn.icmp.i64.i64(i64 %0, i64 %1, i32 35)
+// CHECK-NEXT:  %[[V3:.*]] = load i64*, i64** %out.addr.ascast
+// CHECK-NEXT:  store i64 %[[V2]], i64* %[[V3]]
+// CHECK-NEXT:  ret void
+__global__ void test_uicmp_i64(unsigned long long *out, unsigned long long a, unsigned long long b)
+{
+  *out = __builtin_amdgcn_uicmpl(a, b, 30+5);
+}
+
+// Check the 64 bit return value is correctly returned without truncation or assertion.
+
+// CHECK-LABEL: @_Z14test_s_memtime
+// CHECK: %[[V1:.*]] = call i64 @llvm.amdgcn.s.memtime()
+// CHECK-NEXT: %[[PTR:.*]] = load i64*, i64** %out.addr.ascast
+// CHECK-NEXT:  store i64 %[[V1]], i64* %[[PTR]]
+// CHECK-NEXT:  ret void
+__global__ void test_s_memtime(unsigned long long* out)
+{
+  *out = __builtin_amdgcn_s_memtime();
+}
Index: clang/include/clang/Basic/BuiltinsAMDGPU.def
===
--- clang/include/clang/Basic/BuiltinsAMDGPU.def
+++ clang/include/clang/Basic/BuiltinsAMDGPU.def
@@ -9,6 +9,11 @@
 // This file defines the AMDGPU-specific builtin function database. Users of
 // this file must define the BUILTIN macro to make use of this information.
 //
+// Note: (unsigned) long int type should be avoided in builtin definitions
+// since it has different size on Linux (64 bit) and Windows (32 bit).
+// (unsigned) long long int type should also be avoided, which is 64 bit for
+// C/C++/HIP but is 128 bit for OpenCL. Use `W` as width modifier in builtin
+// definitions since it is fixed for 64 bit.
 //===--===//
 
 // The format of this database matches clang/Basic/Builtins.def.
@@ -44,14 +49,14 @@
 BUILTIN(__builtin_amdgcn_mbcnt_hi, "UiUiUi", "nc")
 BUILTIN(__builtin_amdgcn_mbcnt_lo, "UiUiUi", "nc")
 
-TARGET_BUILTIN(__builtin_amdgcn_s_memtime, "LUi", "n", "s-memtime-inst")
+TARGET_BUILTIN(__builtin_amdgcn_s_memtime, "WUi", "n", "s-memtime-inst")
 
 //===--===//
 // Instruction builtins.
 //===--===//
 BUILTIN(__builtin_amdgcn_s_getreg, "UiIi", "n")
 BUILTIN(__builtin_amdgcn_s_setreg, "vIiUi", "n")
-BUILTIN(__builtin_amdgcn_s_getpc, "LUi", "n")
+BUILTIN(__builtin_amdgcn_s_getpc, "WUi", "n")
 BUILTIN(__builtin_amdgcn_s_waitcnt, "vIi", "n")
 BUILTIN(__builtin_amdgcn_s_sendmsg, "vIiUi", "n")
 BUILTIN(__builtin_amdgcn_s_sendmsghalt, "vIiUi", "n")
@@ -111,12 +116,12 @@
 BUILTIN(__builtin_amdgcn_s_sleep, "vIi", "n")
 BUILTIN(__builtin_amdgcn_s_incperflevel, "vIi", "n")
 BUILTIN(__builtin_amdgcn_s_decperflevel, "vIi", "n")
-BUILTIN(__builtin_amdgcn_uicmp, "LUiUiUiIi", "nc")
-BUILTIN(__builtin_amdgcn_uicmpl, "LUiLUiLUiIi", "nc")
-BUILTIN(__builtin_amdgcn_sicmp, "LUiiiIi", "nc")
-BUILTIN(__builtin_amdgcn_sicmpl, "LUiLiLiIi", "nc")
-BUILTIN(__builtin_amdgcn_fcmp, "LUiddIi", "nc")
-BUILTIN(__builtin_amdgcn_fcmpf, "LUiffIi", "nc")
+BUILTIN(__builtin_amdgcn_uicmp, "WUiUiUiIi", "nc")
+BUILTIN(__builtin_amdgcn_uicmpl, "WUiWUiWUiIi", "nc")
+BUILTIN(__builtin_amdgcn_sicmp, "WUiiiIi", "nc")
+BUILTIN(__builtin_amdgcn_sicmpl, "WUiWiWiIi", "nc")
+BUILTIN(__builtin_amdgcn_fcmp, "WUiddIi", "nc")
+BUILTIN(__builtin_amdgcn_fcmpf, "WUiffIi", "nc")
 BUIL

[clang] 3e333cc - [clang-format] Fix PointerAlignmentRight with AlignConsecutiveDeclarations

2021-06-03 Thread Björn Schäpers via cfe-commits

Author: Gerhard Gappmeier
Date: 2021-06-03T17:55:11+02:00
New Revision: 3e333cc82e42e1e2ecc974d896489eebe1a5edc2

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

LOG: [clang-format] Fix PointerAlignmentRight with AlignConsecutiveDeclarations

This re-applies the old patch D27651, which was never landed, into the
latest "main" branch, without understanding the code. I just applied
the changes "mechanically" and made it compiling again.

This makes the right pointer alignment working as expected.
Fixes https://llvm.org/PR27353

For instance

const char* const* v1;
float const* v2;
SomeVeryLongType const& v3;

was formatted as

const char *const * v1;
float const *   v2;
SomeVeryLongType const &v3;

This patch keep the *s or &s aligned to the right, next to their variable.
The above example is now formatted as

const char *const  *v1;
float const*v2;
SomeVeryLongType const &v3;

It is a pity that this still does not work with clang-format in 2021,
even though there was a fix available in 2016. IMHO right pointer alignment
is the default case in C, because syntactically the pointer belongs to the
variable.

See

int* a, b, c; // wrong, just the 1st variable is a pointer

vs.

int *a, *b, *c; // right

Prominent example is the Linux kernel coding style.

Some styles argue the left pointer alignment is better and declaration
lists as shown above should be avoided. That's ok, as different projects
can use different styles, but this important style should work too.

I hope that somebody that has a better understanding about the code,
can take over this patch and land it into main.

For now I must maintain this fork to make it working for our projects.

Cheers,
Gerhard.

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

Added: 


Modified: 
clang/docs/ReleaseNotes.rst
clang/lib/Format/WhitespaceManager.cpp
clang/unittests/Format/FormatTest.cpp

Removed: 




diff  --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 11bcac075c241..6d3582a6297d6 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -259,6 +259,9 @@ clang-format
 - ``git-clang-format`` no longer formats changes to symbolic links. (Fixes
   https://llvm.org/PR46992.)
 
+- Makes ``PointerAligment: Right`` working with 
``AlignConsecutiveDeclarations``.
+  (Fixes https://llvm.org/PR27353)
+
 libclang
 
 

diff  --git a/clang/lib/Format/WhitespaceManager.cpp 
b/clang/lib/Format/WhitespaceManager.cpp
index e78c5c4df5866..515cb7941e785 100644
--- a/clang/lib/Format/WhitespaceManager.cpp
+++ b/clang/lib/Format/WhitespaceManager.cpp
@@ -262,7 +262,8 @@ void WhitespaceManager::calculateLineBreakInformation() {
 // Align a single sequence of tokens, see AlignTokens below.
 template 
 static void
-AlignTokenSequence(unsigned Start, unsigned End, unsigned Column, F &&Matches,
+AlignTokenSequence(const FormatStyle &Style, unsigned Start, unsigned End,
+   unsigned Column, F &&Matches,
SmallVector &Changes) {
   bool FoundMatchOnLine = false;
   int Shift = 0;
@@ -365,9 +366,22 @@ AlignTokenSequence(unsigned Start, unsigned End, unsigned 
Column, F &&Matches,
   Changes[i].Spaces += Shift;
 
 assert(Shift >= 0);
+
 Changes[i].StartOfTokenColumn += Shift;
 if (i + 1 != Changes.size())
   Changes[i + 1].PreviousEndOfTokenColumn += Shift;
+
+// If PointerAlignment is PAS_Right, keep *s or &s next to the token
+if (Style.PointerAlignment == FormatStyle::PAS_Right &&
+Changes[i].Spaces != 0) {
+  for (int Previous = i - 1;
+   Previous >= 0 &&
+   Changes[Previous].Tok->getType() == TT_PointerOrReference;
+   --Previous) {
+Changes[Previous + 1].Spaces -= Shift;
+Changes[Previous].Spaces += Shift;
+  }
+}
   }
 }
 
@@ -437,8 +451,8 @@ static unsigned AlignTokens(
   // containing any matching token to be aligned and located after such token.
   auto AlignCurrentSequence = [&] {
 if (StartOfSequence > 0 && StartOfSequence < EndOfSequence)
-  AlignTokenSequence(StartOfSequence, EndOfSequence, MinColumn, Matches,
- Changes);
+  AlignTokenSequence(Style, StartOfSequence, EndOfSequence, MinColumn,
+ Matches, Changes);
 MinColumn = 0;
 MaxColumn = UINT_MAX;
 StartOfSequence = 0;
@@ -728,12 +742,6 @@ void WhitespaceManager::alignConsecutiveDeclarations() {
   if (Style.AlignConsecutiveDeclarations == FormatStyle::ACS_None)
 return;
 
-  // FIXME: Currently we don't handle properly the PointerAlignment: Right
-  // The * and & are not aligned and are left dangling. Something has to be 
done
-  // about it, but it raises the question of alignment of code like:

[clang] 6f605b8 - [clang-format] Add PPIndentWidth option

2021-06-03 Thread Björn Schäpers via cfe-commits

Author: Gerhard Gappmeier
Date: 2021-06-03T17:55:11+02:00
New Revision: 6f605b8d0bc1c19dccc7a6c248b4fa60e6f7fde3

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

LOG: [clang-format] Add PPIndentWidth option

This allows to set a different indent width for preprocessor statements.

Example:

 #ifdef __linux_
 # define FOO
 #endif

int main(void)
{
return 0;
}

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

Added: 


Modified: 
clang/docs/ClangFormatStyleOptions.rst
clang/docs/ReleaseNotes.rst
clang/include/clang/Format/Format.h
clang/lib/Format/Format.cpp
clang/lib/Format/UnwrappedLineFormatter.cpp
clang/unittests/Format/FormatTest.cpp

Removed: 




diff  --git a/clang/docs/ClangFormatStyleOptions.rst 
b/clang/docs/ClangFormatStyleOptions.rst
index bbe2807c2e23a..9686830c3bd3e 100644
--- a/clang/docs/ClangFormatStyleOptions.rst
+++ b/clang/docs/ClangFormatStyleOptions.rst
@@ -3033,6 +3033,21 @@ the configuration (without a prefix: ``Auto``).
   Add a space in front of an Objective-C protocol list, i.e. use
   ``Foo `` instead of ``Foo``.
 
+**PPIndentWidth** (``int``)
+  The number of columns to use for indentation of preprocessor statements.
+  When set to -1 (default) ``IndentWidth`` is used also for preprocessor
+  statements.
+
+  .. code-block:: c++
+
+ PPIndentWidth: 1
+
+ #ifdef __linux__
+ # define FOO
+ #else
+ # define BAR
+ #endif
+
 **PenaltyBreakAssignment** (``unsigned``)
   The penalty for breaking around an assignment operator.
 

diff  --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 6d3582a6297d6..f5835dd2f7c63 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -233,6 +233,9 @@ clang-format
 - Option ``IndentAccessModifiers`` has been added to be able to give access
   modifiers their own indentation level inside records.
 
+- Option ``PPIndentWidth`` has been added to be able to configure pre-processor
+  indentation independent from regular code.
+
 - Option ``ShortNamespaceLines`` has been added to give better control
   over ``FixNamespaceComments`` when determining a namespace length.
 

diff  --git a/clang/include/clang/Format/Format.h 
b/clang/include/clang/Format/Format.h
index c30e357b5d0dd..503f0e446bff3 100644
--- a/clang/include/clang/Format/Format.h
+++ b/clang/include/clang/Format/Format.h
@@ -2666,6 +2666,20 @@ struct FormatStyle {
   /// Pointer and reference alignment style.
   PointerAlignmentStyle PointerAlignment;
 
+  /// The number of columns to use for indentation of preprocessor statements.
+  /// When set to -1 (default) ``IndentWidth`` is used also for preprocessor
+  /// statements.
+  /// \code
+  ///PPIndentWidth: 1
+  ///
+  ///#ifdef __linux__
+  ///# define FOO
+  ///#else
+  ///# define BAR
+  ///#endif
+  /// \endcode
+  int PPIndentWidth;
+
   /// See documentation of ``RawStringFormats``.
   struct RawStringFormat {
 /// The language of this raw string.

diff  --git a/clang/lib/Format/Format.cpp b/clang/lib/Format/Format.cpp
index c85ecd970ff15..8d16f299d3aef 100644
--- a/clang/lib/Format/Format.cpp
+++ b/clang/lib/Format/Format.cpp
@@ -665,6 +665,7 @@ template <> struct MappingTraits {
 IO.mapOptional("PenaltyIndentedWhitespace",
Style.PenaltyIndentedWhitespace);
 IO.mapOptional("PointerAlignment", Style.PointerAlignment);
+IO.mapOptional("PPIndentWidth", Style.PPIndentWidth);
 IO.mapOptional("RawStringFormats", Style.RawStringFormats);
 IO.mapOptional("ReflowComments", Style.ReflowComments);
 IO.mapOptional("ShortNamespaceLines", Style.ShortNamespaceLines);
@@ -1022,6 +1023,7 @@ FormatStyle getLLVMStyle(FormatStyle::LanguageKind 
Language) {
   LLVMStyle.IndentRequires = false;
   LLVMStyle.IndentWrappedFunctionNames = false;
   LLVMStyle.IndentWidth = 2;
+  LLVMStyle.PPIndentWidth = -1;
   LLVMStyle.InsertTrailingCommas = FormatStyle::TCS_None;
   LLVMStyle.JavaScriptQuotes = FormatStyle::JSQS_Leave;
   LLVMStyle.JavaScriptWrapImports = true;

diff  --git a/clang/lib/Format/UnwrappedLineFormatter.cpp 
b/clang/lib/Format/UnwrappedLineFormatter.cpp
index 2b1b15de8bbf1..41fbb16f0db12 100644
--- a/clang/lib/Format/UnwrappedLineFormatter.cpp
+++ b/clang/lib/Format/UnwrappedLineFormatter.cpp
@@ -57,7 +57,9 @@ class LevelIndentTracker {
 while (IndentForLevel.size() <= Line.Level)
   IndentForLevel.push_back(-1);
 if (Line.InPPDirective) {
-  Indent = Line.Level * Style.IndentWidth + AdditionalIndent;
+  unsigned IndentWidth =
+  (Style.PPIndentWidth >= 0) ? Style.PPIndentWidth : Style.IndentWidth;
+  Indent = Line.Level * IndentWidth + AdditionalIndent;
 } else {
   IndentForLevel.resize(Line.Level + 1);
  

[PATCH] D103245: [clang-format] Fix PointerAlignmentRight with AlignConsecutiveDeclarations

2021-06-03 Thread Björn Schäpers via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG3e333cc82e42: [clang-format] Fix PointerAlignmentRight with 
AlignConsecutiveDeclarations (authored by gergap, committed by 
HazardyKnusperkeks).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D103245

Files:
  clang/docs/ReleaseNotes.rst
  clang/lib/Format/WhitespaceManager.cpp
  clang/unittests/Format/FormatTest.cpp

Index: clang/unittests/Format/FormatTest.cpp
===
--- clang/unittests/Format/FormatTest.cpp
+++ clang/unittests/Format/FormatTest.cpp
@@ -14915,6 +14915,7 @@
   FormatStyle Alignment = getLLVMStyle();
   Alignment.AlignConsecutiveMacros = FormatStyle::ACS_Consecutive;
   Alignment.AlignConsecutiveDeclarations = FormatStyle::ACS_None;
+  Alignment.PointerAlignment = FormatStyle::PAS_Right;
   verifyFormat("float const a = 5;\n"
"int oneTwoThree = 123;",
Alignment);
@@ -14950,8 +14951,8 @@
   verifyFormat("int  oneTwoThree{0}; // comment\n"
"unsigned oneTwo; // comment",
Alignment);
-  verifyFormat("unsigned int *  a;\n"
-   "int *   b;\n"
+  verifyFormat("unsigned int   *a;\n"
+   "int*b;\n"
"unsigned int Const *c;\n"
"unsigned int const *d;\n"
"unsigned int Const &e;\n"
@@ -15073,9 +15074,11 @@
"  doublebar();\n"
"};\n",
Alignment);
+
+  // PAS_Right
   EXPECT_EQ("void SomeFunction(int parameter = 0) {\n"
 "  int const i   = 1;\n"
-"  int * j   = 2;\n"
+"  int  *j   = 2;\n"
 "  int   big = 1;\n"
 "\n"
 "  unsigned oneTwoThree = 123;\n"
@@ -15096,6 +15099,161 @@
"int ll=1;\n"
"}",
Alignment));
+  EXPECT_EQ("void SomeFunction(int parameter = 0) {\n"
+"  int const i   = 1;\n"
+"  int **j   = 2, ***k;\n"
+"  int  &k   = i;\n"
+"  int &&l   = i + j;\n"
+"  int   big = 1;\n"
+"\n"
+"  unsigned oneTwoThree = 123;\n"
+"  int  oneTwo  = 12;\n"
+"  method();\n"
+"  float k  = 2;\n"
+"  int   ll = 1;\n"
+"}",
+format("void SomeFunction(int parameter= 0) {\n"
+   " int const  i= 1;\n"
+   "  int **j=2,***k;\n"
+   "int &k=i;\n"
+   "int &&l=i+j;\n"
+   " int big  =  1;\n"
+   "\n"
+   "unsigned oneTwoThree  =123;\n"
+   "int oneTwo = 12;\n"
+   "  method();\n"
+   "float k= 2;\n"
+   "int ll=1;\n"
+   "}",
+   Alignment));
+  // variables are aligned at their name, pointers are at the right most
+  // position
+  verifyFormat("int   *a;\n"
+   "int  **b;\n"
+   "int ***c;\n"
+   "intfoobar;\n",
+   Alignment);
+
+  // PAS_Left
+  FormatStyle AlignmentLeft = Alignment;
+  AlignmentLeft.PointerAlignment = FormatStyle::PAS_Left;
+  EXPECT_EQ("void SomeFunction(int parameter = 0) {\n"
+"  int const i   = 1;\n"
+"  int*  j   = 2;\n"
+"  int   big = 1;\n"
+"\n"
+"  unsigned oneTwoThree = 123;\n"
+"  int  oneTwo  = 12;\n"
+"  method();\n"
+"  float k  = 2;\n"
+"  int   ll = 1;\n"
+"}",
+format("void SomeFunction(int parameter= 0) {\n"
+   " int const  i= 1;\n"
+   "  int *j=2;\n"
+   " int big  =  1;\n"
+   "\n"
+   "unsigned oneTwoThree  =123;\n"
+   "int oneTwo = 12;\n"
+   "  method();\n"
+   "float k= 2;\n"
+   "int ll=1;\n"
+   "}",
+   AlignmentLeft));
+  EXPECT_EQ("void SomeFunction(int parameter = 0) {\n"
+"  int const i   = 1;\n"
+"  int** j   = 2;\n"
+"  int&  k   = i;\n"
+"  int&& l   = i + j;\n"
+"  int   big = 1;\n"
+"\n"
+"  unsigned oneTwoThree = 123;\n"
+"  int  oneTwo  = 12;\n"
+"  method();\n"
+"  float k  = 2;\n"
+"  int   ll = 1;\n"
+"}",
+format("void SomeFunction(int parameter= 0) {\n"
+   " int const  i= 1;\n"
+   "  int **j=2;\n"
+   "int &k=i;\n"
+ 

[PATCH] D103286: [clang-format] Add PPIndentWidth option

2021-06-03 Thread Björn Schäpers via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG6f605b8d0bc1: [clang-format] Add PPIndentWidth option 
(authored by gergap, committed by HazardyKnusperkeks).

Changed prior to commit:
  https://reviews.llvm.org/D103286?vs=348955&id=349569#toc

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D103286

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

Index: clang/unittests/Format/FormatTest.cpp
===
--- clang/unittests/Format/FormatTest.cpp
+++ clang/unittests/Format/FormatTest.cpp
@@ -3453,6 +3453,48 @@
   verifyFormat("a\f\\");
 }
 
+TEST_F(FormatTest, IndentsPPDirectiveWithPPIndentWidth) {
+  FormatStyle style = getChromiumStyle(FormatStyle::LK_Cpp);
+  style.IndentWidth = 4;
+  style.PPIndentWidth = 1;
+
+  style.IndentPPDirectives = FormatStyle::PPDIS_None;
+  verifyFormat("#ifdef __linux__\n"
+   "void foo() {\n"
+   "int x = 0;\n"
+   "}\n"
+   "#define FOO\n"
+   "#endif\n"
+   "void bar() {\n"
+   "int y = 0;\n"
+   "}\n",
+   style);
+
+  style.IndentPPDirectives = FormatStyle::PPDIS_AfterHash;
+  verifyFormat("#ifdef __linux__\n"
+   "void foo() {\n"
+   "int x = 0;\n"
+   "}\n"
+   "# define FOO foo\n"
+   "#endif\n"
+   "void bar() {\n"
+   "int y = 0;\n"
+   "}\n",
+   style);
+
+  style.IndentPPDirectives = FormatStyle::PPDIS_BeforeHash;
+  verifyFormat("#ifdef __linux__\n"
+   "void foo() {\n"
+   "int x = 0;\n"
+   "}\n"
+   " #define FOO foo\n"
+   "#endif\n"
+   "void bar() {\n"
+   "int y = 0;\n"
+   "}\n",
+   style);
+}
+
 TEST_F(FormatTest, IndentsPPDirectiveInReducedSpace) {
   verifyFormat("#define A(BB)", getLLVMStyleWithColumns(13));
   verifyFormat("#define A( \\\nBB)", getLLVMStyleWithColumns(12));
Index: clang/lib/Format/UnwrappedLineFormatter.cpp
===
--- clang/lib/Format/UnwrappedLineFormatter.cpp
+++ clang/lib/Format/UnwrappedLineFormatter.cpp
@@ -57,7 +57,9 @@
 while (IndentForLevel.size() <= Line.Level)
   IndentForLevel.push_back(-1);
 if (Line.InPPDirective) {
-  Indent = Line.Level * Style.IndentWidth + AdditionalIndent;
+  unsigned IndentWidth =
+  (Style.PPIndentWidth >= 0) ? Style.PPIndentWidth : Style.IndentWidth;
+  Indent = Line.Level * IndentWidth + AdditionalIndent;
 } else {
   IndentForLevel.resize(Line.Level + 1);
   Indent = getIndent(IndentForLevel, Line.Level);
Index: clang/lib/Format/Format.cpp
===
--- clang/lib/Format/Format.cpp
+++ clang/lib/Format/Format.cpp
@@ -665,6 +665,7 @@
 IO.mapOptional("PenaltyIndentedWhitespace",
Style.PenaltyIndentedWhitespace);
 IO.mapOptional("PointerAlignment", Style.PointerAlignment);
+IO.mapOptional("PPIndentWidth", Style.PPIndentWidth);
 IO.mapOptional("RawStringFormats", Style.RawStringFormats);
 IO.mapOptional("ReflowComments", Style.ReflowComments);
 IO.mapOptional("ShortNamespaceLines", Style.ShortNamespaceLines);
@@ -1022,6 +1023,7 @@
   LLVMStyle.IndentRequires = false;
   LLVMStyle.IndentWrappedFunctionNames = false;
   LLVMStyle.IndentWidth = 2;
+  LLVMStyle.PPIndentWidth = -1;
   LLVMStyle.InsertTrailingCommas = FormatStyle::TCS_None;
   LLVMStyle.JavaScriptQuotes = FormatStyle::JSQS_Leave;
   LLVMStyle.JavaScriptWrapImports = true;
Index: clang/include/clang/Format/Format.h
===
--- clang/include/clang/Format/Format.h
+++ clang/include/clang/Format/Format.h
@@ -2666,6 +2666,20 @@
   /// Pointer and reference alignment style.
   PointerAlignmentStyle PointerAlignment;
 
+  /// The number of columns to use for indentation of preprocessor statements.
+  /// When set to -1 (default) ``IndentWidth`` is used also for preprocessor
+  /// statements.
+  /// \code
+  ///PPIndentWidth: 1
+  ///
+  ///#ifdef __linux__
+  ///# define FOO
+  ///#else
+  ///# define BAR
+  ///#endif
+  /// \endcode
+  int PPIndentWidth;
+
   /// See documentation of ``RawStringFormats``.
   struct RawStringFormat {
 /// The language of this raw string.
Index: clang/docs/ReleaseNotes.rst
===
--- clang/docs/ReleaseNotes.rst
+++ clang/docs/ReleaseNotes.rst
@@ -233,6 +23

[PATCH] D103624: [analyzer] Hide and rename FindLastStoreBRVisitor

2021-06-03 Thread Valeriy Savchenko via Phabricator via cfe-commits
vsavchenko created this revision.
vsavchenko added reviewers: NoQ, xazax.hun, martong, steakhal, Szelethus, 
manas, RedDocMD.
Herald added subscribers: ASDenysPetrov, dkrupp, donat.nagy, mikhail.ramalho, 
a.sidorin, rnkovacs, szepet, baloghadamsoftware.
vsavchenko requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

This component should not be used directly at this point and it is
simply an implementation detail, that's why StoreSiteFinder is
out of the header file.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D103624

Files:
  clang/include/clang/StaticAnalyzer/Core/BugReporter/BugReporterVisitors.h
  clang/lib/StaticAnalyzer/Core/BugReporterVisitors.cpp

Index: clang/lib/StaticAnalyzer/Core/BugReporterVisitors.cpp
===
--- clang/lib/StaticAnalyzer/Core/BugReporterVisitors.cpp
+++ clang/lib/StaticAnalyzer/Core/BugReporterVisitors.cpp
@@ -1219,10 +1219,53 @@
 } // end of anonymous namespace
 
 //===--===//
-// Implementation of FindLastStoreBRVisitor.
+//   StoreSiteFinder
 //===--===//
 
-void FindLastStoreBRVisitor::Profile(llvm::FoldingSetNodeID &ID) const {
+/// Finds last store into the given region,
+/// which is different from a given symbolic value.
+class StoreSiteFinder final : public TrackingBugReporterVisitor {
+  const MemRegion *R;
+  SVal V;
+  bool Satisfied = false;
+
+  /// If the visitor is tracking the value directly responsible for the
+  /// bug, we are going to employ false positive suppression.
+  bool EnableNullFPSuppression;
+
+  using TrackingKind = bugreporter::TrackingKind;
+  TrackingKind TKind;
+  const StackFrameContext *OriginSFC;
+
+public:
+  /// \param V We're searching for the store where \c R received this value.
+  /// \param R The region we're tracking.
+  /// \param TKind May limit the amount of notes added to the bug report.
+  /// \param OriginSFC Only adds notes when the last store happened in a
+  ///different stackframe to this one. Disregarded if the tracking kind
+  ///is thorough.
+  ///This is useful, because for non-tracked regions, notes about
+  ///changes to its value in a nested stackframe could be pruned, and
+  ///this visitor can prevent that without polluting the bugpath too
+  ///much.
+  StoreSiteFinder(bugreporter::TrackerRef ParentTracker, KnownSVal V,
+  const MemRegion *R, bool InEnableNullFPSuppression,
+  TrackingKind TKind,
+  const StackFrameContext *OriginSFC = nullptr)
+  : TrackingBugReporterVisitor(ParentTracker), R(R), V(V),
+EnableNullFPSuppression(InEnableNullFPSuppression), TKind(TKind),
+OriginSFC(OriginSFC) {
+assert(R);
+  }
+
+  void Profile(llvm::FoldingSetNodeID &ID) const override;
+
+  PathDiagnosticPieceRef VisitNode(const ExplodedNode *N,
+   BugReporterContext &BRC,
+   PathSensitiveBugReport &BR) override;
+};
+
+void StoreSiteFinder::Profile(llvm::FoldingSetNodeID &ID) const {
   static int tag = 0;
   ID.AddPointer(&tag);
   ID.AddPointer(R);
@@ -1393,10 +1436,9 @@
   }
 }
 
-PathDiagnosticPieceRef
-FindLastStoreBRVisitor::VisitNode(const ExplodedNode *Succ,
-  BugReporterContext &BRC,
-  PathSensitiveBugReport &BR) {
+PathDiagnosticPieceRef StoreSiteFinder::VisitNode(const ExplodedNode *Succ,
+  BugReporterContext &BRC,
+  PathSensitiveBugReport &BR) {
   if (Satisfied)
 return nullptr;
 
@@ -2240,8 +2282,8 @@
 Tracker::Result Tracker::track(KnownSVal V, const MemRegion *R,
TrackingOptions Opts,
const StackFrameContext *Origin) {
-  Report.addVisitor(
-  this, V, R, Opts.EnableNullFPSuppression, Opts.Kind, Origin);
+  Report.addVisitor(this, V, R, Opts.EnableNullFPSuppression,
+ Opts.Kind, Origin);
   return {true, false};
 }
 
Index: clang/include/clang/StaticAnalyzer/Core/BugReporter/BugReporterVisitors.h
===
--- clang/include/clang/StaticAnalyzer/Core/BugReporter/BugReporterVisitors.h
+++ clang/include/clang/StaticAnalyzer/Core/BugReporter/BugReporterVisitors.h
@@ -373,50 +373,6 @@
 
 } // namespace bugreporter
 
-/// Finds last store into the given region,
-/// which is different from a given symbolic value.
-class FindLastStoreBRVisitor final
-: public bugreporter::TrackingBugReporterVisitor {
-  const MemRegion *R;
-  SVal V;
-  bool Satisfied = false;
-
-  /// If the visitor is tracking the value direc

[PATCH] D103563: [HIP] Fix amdgcn builtin for long type

2021-06-03 Thread Yaxun Liu via Phabricator via cfe-commits
yaxunl added a comment.

I got regressions in OpenCL tests since long long int is 128 bit in OpenCL. I 
switched to use `W` as width modifier in builtin definitions since `W` is for 
fixed-length 64 bit int type.


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

https://reviews.llvm.org/D103563

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


[PATCH] D103519: [clang][deps] Support object files

2021-06-03 Thread Michael Spencer via Phabricator via cfe-commits
Bigcheese accepted this revision.
Bigcheese added a comment.
This revision is now accepted and ready to land.

lgtm




Comment at: 
clang/lib/Tooling/DependencyScanning/DependencyScanningWorker.cpp:161-162
+  std::make_unique());
+  PCHContainerOps->registerWriter(
+  std::make_unique());
+

This should have a comment that we don't actually write out any PCHs, but this 
is still needed due to how things are currently implemented.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D103519

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


[PATCH] D103628: [analyzer] Turn ReturnVisitor into a tracking visitor

2021-06-03 Thread Valeriy Savchenko via Phabricator via cfe-commits
vsavchenko created this revision.
vsavchenko added reviewers: NoQ, xazax.hun, martong, steakhal, Szelethus, 
manas, RedDocMD.
Herald added subscribers: ASDenysPetrov, dkrupp, donat.nagy, mikhail.ramalho, 
a.sidorin, rnkovacs, szepet, baloghadamsoftware.
vsavchenko requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

Whenever Tracker spawns a visitor that needs to call tracker
back, we have to use TrackingBugReporterVisitor in order to maintain
all the hooks that the checker might've used.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D103628

Files:
  clang/lib/StaticAnalyzer/Core/BugReporterVisitors.cpp


Index: clang/lib/StaticAnalyzer/Core/BugReporterVisitors.cpp
===
--- clang/lib/StaticAnalyzer/Core/BugReporterVisitors.cpp
+++ clang/lib/StaticAnalyzer/Core/BugReporterVisitors.cpp
@@ -906,7 +906,7 @@
 ///
 /// This visitor is intended to be used when another visitor discovers that an
 /// interesting value comes from an inlined function call.
-class ReturnVisitor : public BugReporterVisitor {
+class ReturnVisitor : public TrackingBugReporterVisitor {
   const StackFrameContext *CalleeSFC;
   enum {
 Initial,
@@ -920,10 +920,11 @@
   bugreporter::TrackingKind TKind;
 
 public:
-  ReturnVisitor(const StackFrameContext *Frame, bool Suppressed,
-AnalyzerOptions &Options, bugreporter::TrackingKind TKind)
-  : CalleeSFC(Frame), EnableNullFPSuppression(Suppressed),
-Options(Options), TKind(TKind) {}
+  ReturnVisitor(TrackerRef ParentTracker, const StackFrameContext *Frame,
+bool Suppressed, AnalyzerOptions &Options,
+bugreporter::TrackingKind TKind)
+  : TrackingBugReporterVisitor(ParentTracker), CalleeSFC(Frame),
+EnableNullFPSuppression(Suppressed), Options(Options), TKind(TKind) {}
 
   static void *getTag() {
 static int Tag = 0;
@@ -943,7 +944,8 @@
   /// node, looking for when the given statement was processed. If it turns out
   /// the statement is a call that was inlined, we add the visitor to the
   /// bug report, so it can print a note later.
-  static void addVisitorIfNecessary(const ExplodedNode *Node, const Stmt *S,
+  static void addVisitorIfNecessary(TrackerRef ParentTracker,
+const ExplodedNode *Node, const Stmt *S,
 PathSensitiveBugReport &BR,
 bool InEnableNullFPSuppression,
 bugreporter::TrackingKind TKind) {
@@ -1016,8 +1018,8 @@
   if (Optional RetLoc = RetVal.getAs())
 EnableNullFPSuppression = State->isNull(*RetLoc).isConstrainedTrue();
 
-BR.addVisitor(CalleeContext, EnableNullFPSuppression,
- Options, TKind);
+BR.addVisitor(ParentTracker, CalleeContext,
+ EnableNullFPSuppression, Options, TKind);
   }
 
   PathDiagnosticPieceRef visitNodeInitial(const ExplodedNode *N,
@@ -1066,8 +1068,7 @@
 RetE = RetE->IgnoreParenCasts();
 
 // Let's track the return value.
-bugreporter::trackExpressionValue(
-N, RetE, BR, TKind, EnableNullFPSuppression);
+getParentTracker().track(RetE, N, {TKind, EnableNullFPSuppression});
 
 // Build an appropriate message based on the return value.
 SmallString<64> Msg;
@@ -1183,7 +1184,9 @@
   if (!State->isNull(*ArgV).isConstrainedTrue())
 continue;
 
-  if (trackExpressionValue(N, ArgE, BR, TKind, EnableNullFPSuppression))
+  if (getParentTracker()
+  .track(ArgE, N, {TKind, EnableNullFPSuppression})
+  .FoundSomethingToTrack)
 ShouldInvalidate = false;
 
   // If we /can't/ track the null pointer, we should err on the side of
@@ -2199,8 +2202,9 @@
 // track the constraints on its contents.
 SVal V = LVState->getSValAsScalarOrLoc(Inner, 
LVNode->getLocationContext());
 
-ReturnVisitor::addVisitorIfNecessary(
-LVNode, Inner, Report, Opts.EnableNullFPSuppression, Opts.Kind);
+ReturnVisitor::addVisitorIfNecessary(&getParentTracker(), LVNode, Inner,
+ Report, Opts.EnableNullFPSuppression,
+ Opts.Kind);
 
 // Is it a symbolic value?
 if (auto L = V.getAs()) {


Index: clang/lib/StaticAnalyzer/Core/BugReporterVisitors.cpp
===
--- clang/lib/StaticAnalyzer/Core/BugReporterVisitors.cpp
+++ clang/lib/StaticAnalyzer/Core/BugReporterVisitors.cpp
@@ -906,7 +906,7 @@
 ///
 /// This visitor is intended to be used when another visitor discovers that an
 /// interesting value comes from an inlined function call.
-class ReturnVisitor : public BugReporterVisitor {
+class ReturnVisitor : public TrackingBugReporterVisitor {
   const StackFrameContext *CalleeSFC;
   enum {
 Initial

[PATCH] D103231: [clang][AST] Set correct DeclContext in ASTImporter lookup table for ParmVarDecl.

2021-06-03 Thread Balázs Kéri via Phabricator via cfe-commits
balazske updated this revision to Diff 349583.
balazske added a comment.

Added assert messages.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D103231

Files:
  clang/include/clang/AST/ASTImporterLookupTable.h
  clang/lib/AST/ASTImporter.cpp
  clang/lib/AST/ASTImporterLookupTable.cpp
  clang/unittests/AST/ASTImporterTest.cpp

Index: clang/unittests/AST/ASTImporterTest.cpp
===
--- clang/unittests/AST/ASTImporterTest.cpp
+++ clang/unittests/AST/ASTImporterTest.cpp
@@ -5375,6 +5375,33 @@
   CheckError(FromFooC);
 }
 
+TEST_P(ErrorHandlingTest, ODRViolationWithinParmVarDecls) {
+  // Importing of 'f' and parameter 'P' should cause an ODR error.
+  // The error happens after the ParmVarDecl for 'P' was already created.
+  // This is a special case because the ParmVarDecl has a temporary DeclContext.
+  // Expected is no crash at error handling of ASTImporter.
+  constexpr auto ToTUCode = R"(
+  struct X {
+char A;
+  };
+  )";
+  constexpr auto FromTUCode = R"(
+  struct X {
+enum Y { Z };
+  };
+  void f(int P = X::Z);
+  )";
+  Decl *ToTU = getToTuDecl(ToTUCode, Lang_CXX11);
+  static_cast(ToTU);
+  Decl *FromTU = getTuDecl(FromTUCode, Lang_CXX11);
+  auto *FromF = FirstDeclMatcher().match(
+  FromTU, functionDecl(hasName("f")));
+  ASSERT_TRUE(FromF);
+
+  auto *ImportedF = Import(FromF, Lang_CXX11);
+  EXPECT_FALSE(ImportedF);
+}
+
 TEST_P(ASTImporterOptionSpecificTestBase, LambdaInFunctionBody) {
   Decl *FromTU = getTuDecl(
   R"(
@@ -6192,6 +6219,21 @@
   ASSERT_TRUE(ToD);
 }
 
+TEST_P(ImportFunctions, ParmVarDeclDeclContext) {
+  constexpr auto FromTUCode = R"(
+  void f(int P);
+  )";
+  Decl *FromTU = getTuDecl(FromTUCode, Lang_CXX11);
+  auto *FromF = FirstDeclMatcher().match(
+  FromTU, functionDecl(hasName("f")));
+  ASSERT_TRUE(FromF);
+
+  auto *ImportedF = Import(FromF, Lang_CXX11);
+  EXPECT_TRUE(ImportedF);
+  EXPECT_TRUE(SharedStatePtr->getLookupTable()->contains(
+  ImportedF, ImportedF->getParamDecl(0)));
+}
+
 // FIXME Move these tests out of ASTImporterTest. For that we need to factor
 // out the ASTImporter specific pars from ASTImporterOptionSpecificTestBase
 // into a new test Fixture. Then we should lift up this Fixture to its own
Index: clang/lib/AST/ASTImporterLookupTable.cpp
===
--- clang/lib/AST/ASTImporterLookupTable.cpp
+++ clang/lib/AST/ASTImporterLookupTable.cpp
@@ -117,6 +117,19 @@
 remove(ReDC, ND);
 }
 
+void ASTImporterLookupTable::update(NamedDecl *ND, DeclContext *OldDC) {
+  assert(OldDC != ND->getDeclContext() &&
+ "DeclContext should be changed before update");
+  if (contains(ND->getDeclContext(), ND)) {
+assert(!contains(OldDC, ND) &&
+   "Decl should not be found in the old context if already in the new");
+return;
+  }
+
+  remove(OldDC, ND);
+  add(ND);
+}
+
 ASTImporterLookupTable::LookupResult
 ASTImporterLookupTable::lookup(DeclContext *DC, DeclarationName Name) const {
   auto DCI = LookupTable.find(DC->getPrimaryContext());
@@ -131,6 +144,10 @@
   return NamesI->second;
 }
 
+bool ASTImporterLookupTable::contains(DeclContext *DC, NamedDecl *ND) const {
+  return 0 < lookup(DC, ND->getDeclName()).count(ND);
+}
+
 void ASTImporterLookupTable::dump(DeclContext *DC) const {
   auto DCI = LookupTable.find(DC->getPrimaryContext());
   if (DCI == LookupTable.end())
Index: clang/lib/AST/ASTImporter.cpp
===
--- clang/lib/AST/ASTImporter.cpp
+++ clang/lib/AST/ASTImporter.cpp
@@ -3503,6 +3503,8 @@
   for (auto *Param : Parameters) {
 Param->setOwningFunction(ToFunction);
 ToFunction->addDeclInternal(Param);
+if (ASTImporterLookupTable *LT = Importer.SharedState->getLookupTable())
+  LT->update(Param, Importer.getToContext().getTranslationUnitDecl());
   }
   ToFunction->setParams(Parameters);
 
Index: clang/include/clang/AST/ASTImporterLookupTable.h
===
--- clang/include/clang/AST/ASTImporterLookupTable.h
+++ clang/include/clang/AST/ASTImporterLookupTable.h
@@ -63,8 +63,24 @@
   ASTImporterLookupTable(TranslationUnitDecl &TU);
   void add(NamedDecl *ND);
   void remove(NamedDecl *ND);
+  // Sometimes a declaration is created first with a temporarily value of decl
+  // context (often the translation unit) and later moved to the final context.
+  // This happens for declarations that are created before the final declaration
+  // context. In such cases the lookup table needs to be updated.
+  // (The declaration is in these cases not added to the temporary decl context,
+  // only its parent is set.)
+  // FIXME: It would be better to not add the declaration to the temporary
+  // context at all in the lookup table, but thi

[PATCH] D103452: [clang] Fix reading long doubles with va_arg on x86_64 mingw

2021-06-03 Thread Reid Kleckner via Phabricator via cfe-commits
rnk accepted this revision.
rnk added a comment.
This revision is now accepted and ready to land.

lgtm




Comment at: clang/test/CodeGen/mingw-long-double.c:56-58
+  // GNU32: bitcast i8* %argp.cur to x86_fp80*
+  // GNU64: bitcast i8* %argp.cur to x86_fp80**
+  // MSC64: bitcast i8* %argp.cur to double*

These tests will stop working after opaque pointers happens, which I hope comes 
in the next year. If you look for a load of the pointer type, that should be 
resilient to opaque pointers.



Comment at: clang/test/CodeGen/win64-i128.c:25
+  // GNU64: bitcast i8* %argp.cur to i128**
+  // MSC64: bitcast i8* %argp.cur to i128**
+  __builtin_va_end(ap);

ditto


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D103452

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


[PATCH] D103524: [clang][deps] Handle precompiled headers' AST files

2021-06-03 Thread Michael Spencer via Phabricator via cfe-commits
Bigcheese accepted this revision.
Bigcheese added a comment.
This revision is now accepted and ready to land.

lgtm.




Comment at: clang/test/ClangScanDeps/modules-pch.c:7
 // RUN: %clang -x c-header %t/pch.h -fmodules -gmodules -fimplicit-module-maps 
\
-// RUN:   -fmodules-cache-path=%t/cache -o %t/pch.h.gch
+// RUN:   -fmodules-cache-path=%t/cache -o %t/pch.h.gch -fno-implicit-modules 
-fno-implicit-module-maps
 

Is this needed for this commit?



Comment at: clang/test/ClangScanDeps/modules-pch.c:14
 // RUN: clang-scan-deps -compilation-database %t/cdb_tu.json -format 
experimental-full \
-// RUN:   -generate-modules-path-args -build-dir %t/build
+// RUN:   -generate-modules-path-args -build-dir %t/build -mode preprocess >> 
%t/result_tu.json
+// RUN: cat %t/result_tu.json | FileCheck %s -check-prefix=CHECK-TU

You should mention that PCHs don't work with minimization yet.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D103524

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


[PATCH] D103630: [analyzer] Refactor trackRValueExpression into ExpressionHandler

2021-06-03 Thread Valeriy Savchenko via Phabricator via cfe-commits
vsavchenko created this revision.
vsavchenko added reviewers: NoQ, xazax.hun, martong, steakhal, Szelethus, 
manas, RedDocMD.
Herald added subscribers: ASDenysPetrov, dkrupp, donat.nagy, mikhail.ramalho, 
a.sidorin, rnkovacs, szepet, baloghadamsoftware.
vsavchenko requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D103630

Files:
  clang/lib/StaticAnalyzer/Core/BugReporterVisitors.cpp

Index: clang/lib/StaticAnalyzer/Core/BugReporterVisitors.cpp
===
--- clang/lib/StaticAnalyzer/Core/BugReporterVisitors.cpp
+++ clang/lib/StaticAnalyzer/Core/BugReporterVisitors.cpp
@@ -2053,44 +2053,6 @@
   return N;
 }
 
-/// Attempts to add visitors to track an RValue expression back to its point of
-/// origin. Works similarly to trackExpressionValue, but accepts only RValues.
-static void trackRValueExpression(const ExplodedNode *InputNode, const Expr *E,
-  PathSensitiveBugReport &report,
-  bugreporter::TrackingKind TKind,
-  bool EnableNullFPSuppression) {
-  assert(E->isRValue() && "The expression is not an rvalue!");
-  const ExplodedNode *RVNode = findNodeForExpression(InputNode, E);
-  if (!RVNode)
-return;
-  ProgramStateRef RVState = RVNode->getState();
-  SVal V = RVState->getSValAsScalarOrLoc(E, RVNode->getLocationContext());
-  const auto *BO = dyn_cast(E);
-  if (!BO)
-return;
-  if (!V.isZeroConstant())
-return;
-  if (!BO->isMultiplicativeOp())
-return;
-
-  SVal RHSV = RVState->getSVal(BO->getRHS(), RVNode->getLocationContext());
-  SVal LHSV = RVState->getSVal(BO->getLHS(), RVNode->getLocationContext());
-
-  // Track both LHS and RHS of a multiplication.
-  if (BO->getOpcode() == BO_Mul) {
-if (LHSV.isZeroConstant())
-  trackExpressionValue(InputNode, BO->getLHS(), report, TKind,
-   EnableNullFPSuppression);
-if (RHSV.isZeroConstant())
-  trackExpressionValue(InputNode, BO->getRHS(), report, TKind,
-   EnableNullFPSuppression);
-  } else { // Track only the LHS of a division or a modulo.
-if (LHSV.isZeroConstant())
-  trackExpressionValue(InputNode, BO->getLHS(), report, TKind,
-   EnableNullFPSuppression);
-  }
-}
-
 //===--===//
 //Tracker implementation
 //===--===//
@@ -2247,17 +2209,61 @@
   }
 }
 
-if (Inner->isRValue())
-  // TODO: Incorporate as Handler
-  trackRValueExpression(LVNode, Inner, Report, Opts.Kind,
-Opts.EnableNullFPSuppression);
-
 return Result;
   }
 };
 
+/// Attempts to add visitors to track an RValue expression back to its point of
+/// origin.
+class RValueHandler final : public ExpressionHandler {
+public:
+  using ExpressionHandler::ExpressionHandler;
+
+  Tracker::Result handle(const Expr *E, const ExplodedNode *InputNode,
+ const ExplodedNode *ExprNode,
+ TrackingOptions Opts) override {
+if (!E->isRValue())
+  return {};
+
+const ExplodedNode *RVNode = findNodeForExpression(ExprNode, E);
+if (!RVNode)
+  return {};
+
+ProgramStateRef RVState = RVNode->getState();
+SVal V = RVState->getSValAsScalarOrLoc(E, RVNode->getLocationContext());
+const auto *BO = dyn_cast(E);
+
+if (!BO || !BO->isMultiplicativeOp() || !V.isZeroConstant())
+  return {};
+
+SVal RHSV = RVState->getSVal(BO->getRHS(), RVNode->getLocationContext());
+SVal LHSV = RVState->getSVal(BO->getLHS(), RVNode->getLocationContext());
+
+// Track both LHS and RHS of a multiplication.
+Tracker::Result CombinedResult;
+Tracker &Parent = getParentTracker();
+
+const auto track = [&CombinedResult, &Parent, ExprNode, Opts](Expr *Inner) {
+  CombinedResult.combineWith(Parent.track(Inner, ExprNode, Opts));
+};
+
+if (BO->getOpcode() == BO_Mul) {
+  if (LHSV.isZeroConstant())
+track(BO->getLHS());
+  if (RHSV.isZeroConstant())
+track(BO->getRHS());
+} else { // Track only the LHS of a division or a modulo.
+  if (LHSV.isZeroConstant())
+track(BO->getLHS());
+}
+
+return CombinedResult;
+  }
+};
+
 Tracker::Tracker(PathSensitiveBugReport &Report) : Report(Report) {
   addHighPriorityHandler();
+  addLowPriorityHandler();
   // TODO: split trackExpressionValue and FindLastStoreBRVisitor into handlers
   //   and add them here.
 }
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] 983565a - [ADT] Move DenseMapInfo for ArrayRef/StringRef into respective headers (NFC)

2021-06-03 Thread Nikita Popov via cfe-commits

Author: Nikita Popov
Date: 2021-06-03T18:34:36+02:00
New Revision: 983565a6fe4a9f40c7caf82b65c650c20dbcc104

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

LOG: [ADT] Move DenseMapInfo for ArrayRef/StringRef into respective headers 
(NFC)

This is a followup to D103422. The DenseMapInfo implementations for
ArrayRef and StringRef are moved into the ArrayRef.h and StringRef.h
headers, which means that these two headers no longer need to be
included by DenseMapInfo.h.

This required adding a few additional includes, as many files were
relying on various things pulled in by ArrayRef.h.

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

Added: 


Modified: 
clang/include/clang/AST/ComparisonCategories.h
llvm/include/llvm/ADT/ArrayRef.h
llvm/include/llvm/ADT/DenseMapInfo.h
llvm/include/llvm/ADT/StringRef.h
llvm/include/llvm/IR/PassInstrumentation.h
llvm/include/llvm/Support/Threading.h
llvm/lib/CodeGen/AsmPrinter/WinException.h
llvm/lib/CodeGen/MBFIWrapper.cpp
llvm/lib/MC/StringTableBuilder.cpp
llvm/lib/Support/SmallPtrSet.cpp
llvm/lib/Target/AMDGPU/AMDGPUGlobalISelUtils.h
llvm/tools/llvm-c-test/echo.cpp
mlir/include/mlir/IR/AffineExpr.h
mlir/include/mlir/IR/DialectInterface.h
mlir/include/mlir/Support/InterfaceSupport.h
mlir/include/mlir/Support/StorageUniquer.h

Removed: 




diff  --git a/clang/include/clang/AST/ComparisonCategories.h 
b/clang/include/clang/AST/ComparisonCategories.h
index 70a78964b8a0c..b41e934142ee4 100644
--- a/clang/include/clang/AST/ComparisonCategories.h
+++ b/clang/include/clang/AST/ComparisonCategories.h
@@ -19,6 +19,7 @@
 #include "llvm/ADT/DenseMap.h"
 #include 
 #include 
+#include 
 
 namespace llvm {
   class StringRef;

diff  --git a/llvm/include/llvm/ADT/ArrayRef.h 
b/llvm/include/llvm/ADT/ArrayRef.h
index bc656109c221e..2df49223c9879 100644
--- a/llvm/include/llvm/ADT/ArrayRef.h
+++ b/llvm/include/llvm/ADT/ArrayRef.h
@@ -26,6 +26,8 @@
 
 namespace llvm {
 
+  template struct DenseMapInfo;
+
   /// ArrayRef - Represent a constant reference to an array (0 or more elements
   /// consecutively in memory), i.e. a start pointer and a length.  It allows
   /// various APIs to take consecutive elements easily and conveniently.
@@ -569,6 +571,35 @@ namespace llvm {
 return hash_combine_range(S.begin(), S.end());
   }
 
+  // Provide DenseMapInfo for ArrayRefs.
+  template  struct DenseMapInfo> {
+static inline ArrayRef getEmptyKey() {
+  return ArrayRef(
+  reinterpret_cast(~static_cast(0)), size_t(0));
+}
+
+static inline ArrayRef getTombstoneKey() {
+  return ArrayRef(
+  reinterpret_cast(~static_cast(1)), size_t(0));
+}
+
+static unsigned getHashValue(ArrayRef Val) {
+  assert(Val.data() != getEmptyKey().data() &&
+ "Cannot hash the empty key!");
+  assert(Val.data() != getTombstoneKey().data() &&
+ "Cannot hash the tombstone key!");
+  return (unsigned)(hash_value(Val));
+}
+
+static bool isEqual(ArrayRef LHS, ArrayRef RHS) {
+  if (RHS.data() == getEmptyKey().data())
+return LHS.data() == getEmptyKey().data();
+  if (RHS.data() == getTombstoneKey().data())
+return LHS.data() == getTombstoneKey().data();
+  return LHS == RHS;
+}
+  };
+
 } // end namespace llvm
 
 #endif // LLVM_ADT_ARRAYREF_H

diff  --git a/llvm/include/llvm/ADT/DenseMapInfo.h 
b/llvm/include/llvm/ADT/DenseMapInfo.h
index 332208ae1ffb6..d276acbfa6a67 100644
--- a/llvm/include/llvm/ADT/DenseMapInfo.h
+++ b/llvm/include/llvm/ADT/DenseMapInfo.h
@@ -13,9 +13,7 @@
 #ifndef LLVM_ADT_DENSEMAPINFO_H
 #define LLVM_ADT_DENSEMAPINFO_H
 
-#include "llvm/ADT/ArrayRef.h"
 #include "llvm/ADT/Hashing.h"
-#include "llvm/ADT/StringRef.h"
 #include 
 #include 
 #include 
@@ -284,62 +282,6 @@ template  struct 
DenseMapInfo> {
   }
 };
 
-// Provide DenseMapInfo for StringRefs.
-template <> struct DenseMapInfo {
-  static inline StringRef getEmptyKey() {
-return StringRef(reinterpret_cast(~static_cast(0)),
- 0);
-  }
-
-  static inline StringRef getTombstoneKey() {
-return StringRef(reinterpret_cast(~static_cast(1)),
- 0);
-  }
-
-  static unsigned getHashValue(StringRef Val) {
-assert(Val.data() != getEmptyKey().data() && "Cannot hash the empty key!");
-assert(Val.data() != getTombstoneKey().data() &&
-   "Cannot hash the tombstone key!");
-return (unsigned)(hash_value(Val));
-  }
-
-  static bool isEqual(StringRef LHS, StringRef RHS) {
-if (RHS.data() == getEmptyKey().data())
-  return LHS.data() == getEmptyKey().data();
-if (RHS.data() == getTombstoneKey().data())
-  return LHS.data() == getTombstoneKey().data();
-return LHS =

[PATCH] D103491: [ADT] Move DenseMapInfo for ArrayRef/StringRef into respective headers (NFC)

2021-06-03 Thread Nikita Popov via Phabricator via cfe-commits
This revision was landed with ongoing or failed builds.
This revision was automatically updated to reflect the committed changes.
Closed by commit rG983565a6fe4a: [ADT] Move DenseMapInfo for ArrayRef/StringRef 
into respective headers (NFC) (authored by nikic).

Changed prior to commit:
  https://reviews.llvm.org/D103491?vs=349093&id=349588#toc

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D103491

Files:
  clang/include/clang/AST/ComparisonCategories.h
  llvm/include/llvm/ADT/ArrayRef.h
  llvm/include/llvm/ADT/DenseMapInfo.h
  llvm/include/llvm/ADT/StringRef.h
  llvm/include/llvm/IR/PassInstrumentation.h
  llvm/include/llvm/Support/Threading.h
  llvm/lib/CodeGen/AsmPrinter/WinException.h
  llvm/lib/CodeGen/MBFIWrapper.cpp
  llvm/lib/MC/StringTableBuilder.cpp
  llvm/lib/Support/SmallPtrSet.cpp
  llvm/lib/Target/AMDGPU/AMDGPUGlobalISelUtils.h
  llvm/tools/llvm-c-test/echo.cpp
  mlir/include/mlir/IR/AffineExpr.h
  mlir/include/mlir/IR/DialectInterface.h
  mlir/include/mlir/Support/InterfaceSupport.h
  mlir/include/mlir/Support/StorageUniquer.h

Index: mlir/include/mlir/Support/StorageUniquer.h
===
--- mlir/include/mlir/Support/StorageUniquer.h
+++ mlir/include/mlir/Support/StorageUniquer.h
@@ -12,7 +12,9 @@
 #include "mlir/Support/LLVM.h"
 #include "mlir/Support/LogicalResult.h"
 #include "mlir/Support/TypeID.h"
+#include "llvm/ADT/ArrayRef.h"
 #include "llvm/ADT/DenseSet.h"
+#include "llvm/ADT/StringRef.h"
 #include "llvm/Support/Allocator.h"
 
 namespace mlir {
Index: mlir/include/mlir/Support/InterfaceSupport.h
===
--- mlir/include/mlir/Support/InterfaceSupport.h
+++ mlir/include/mlir/Support/InterfaceSupport.h
@@ -14,6 +14,7 @@
 #define MLIR_SUPPORT_INTERFACESUPPORT_H
 
 #include "mlir/Support/TypeID.h"
+#include "llvm/ADT/ArrayRef.h"
 #include "llvm/ADT/DenseMap.h"
 #include "llvm/Support/TypeName.h"
 
Index: mlir/include/mlir/IR/DialectInterface.h
===
--- mlir/include/mlir/IR/DialectInterface.h
+++ mlir/include/mlir/IR/DialectInterface.h
@@ -11,6 +11,7 @@
 
 #include "mlir/Support/TypeID.h"
 #include "llvm/ADT/DenseSet.h"
+#include "llvm/ADT/STLExtras.h"
 
 namespace mlir {
 class Dialect;
Index: mlir/include/mlir/IR/AffineExpr.h
===
--- mlir/include/mlir/IR/AffineExpr.h
+++ mlir/include/mlir/IR/AffineExpr.h
@@ -17,6 +17,7 @@
 #include "mlir/Support/LLVM.h"
 #include "llvm/ADT/DenseMapInfo.h"
 #include "llvm/Support/Casting.h"
+#include 
 #include 
 
 namespace mlir {
Index: llvm/tools/llvm-c-test/echo.cpp
===
--- llvm/tools/llvm-c-test/echo.cpp
+++ llvm/tools/llvm-c-test/echo.cpp
@@ -18,6 +18,7 @@
 #include "llvm-c/DebugInfo.h"
 #include "llvm-c/Target.h"
 #include "llvm/ADT/DenseMap.h"
+#include "llvm/ADT/SmallVector.h"
 #include "llvm/Support/ErrorHandling.h"
 
 #include 
Index: llvm/lib/Target/AMDGPU/AMDGPUGlobalISelUtils.h
===
--- llvm/lib/Target/AMDGPU/AMDGPUGlobalISelUtils.h
+++ llvm/lib/Target/AMDGPU/AMDGPUGlobalISelUtils.h
@@ -9,6 +9,7 @@
 #ifndef LLVM_LIB_TARGET_AMDGPU_AMDGPUGLOBALISELUTILS_H
 #define LLVM_LIB_TARGET_AMDGPU_AMDGPUGLOBALISELUTILS_H
 
+#include "llvm/ADT/ArrayRef.h"
 #include "llvm/CodeGen/Register.h"
 #include 
 
Index: llvm/lib/Support/SmallPtrSet.cpp
===
--- llvm/lib/Support/SmallPtrSet.cpp
+++ llvm/lib/Support/SmallPtrSet.cpp
@@ -13,8 +13,9 @@
 
 #include "llvm/ADT/SmallPtrSet.h"
 #include "llvm/ADT/DenseMapInfo.h"
-#include "llvm/Support/MathExtras.h"
 #include "llvm/Support/ErrorHandling.h"
+#include "llvm/Support/MathExtras.h"
+#include "llvm/Support/MemAlloc.h"
 #include 
 #include 
 #include 
Index: llvm/lib/MC/StringTableBuilder.cpp
===
--- llvm/lib/MC/StringTableBuilder.cpp
+++ llvm/lib/MC/StringTableBuilder.cpp
@@ -7,6 +7,7 @@
 //===--===//
 
 #include "llvm/MC/StringTableBuilder.h"
+#include "llvm/ADT/ArrayRef.h"
 #include "llvm/ADT/CachedHashString.h"
 #include "llvm/ADT/SmallString.h"
 #include "llvm/ADT/StringRef.h"
Index: llvm/lib/CodeGen/MBFIWrapper.cpp
===
--- llvm/lib/CodeGen/MBFIWrapper.cpp
+++ llvm/lib/CodeGen/MBFIWrapper.cpp
@@ -11,8 +11,9 @@
 //
 //===--===//
 
-#include "llvm/CodeGen/MBFIWrapper.h"
+#include "llvm/ADT/Optional.h"
 #include "llvm/CodeGen/MachineBlockFrequencyInfo.h"
+#include "llvm/CodeGen/MBFIWrapper.h"
 
 using namespace llvm;
 
Index: llvm/lib/CodeGen/

[PATCH] D101868: [clang-format] Adds a formatter for aligning arrays of structs

2021-06-03 Thread Fred Grim via Phabricator via cfe-commits
feg208 updated this revision to Diff 349589.
feg208 marked 2 inline comments as done.
feg208 added a comment.

Grabs up some review comments and adds lit test


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D101868

Files:
  clang/docs/ClangFormatStyleOptions.rst
  clang/docs/ReleaseNotes.rst
  clang/include/clang/Format/Format.h
  clang/lib/Format/Format.cpp
  clang/lib/Format/FormatToken.h
  clang/lib/Format/TokenAnnotator.cpp
  clang/lib/Format/TokenAnnotator.h
  clang/lib/Format/WhitespaceManager.cpp
  clang/lib/Format/WhitespaceManager.h
  clang/test/Format/struct-array-initializer.cpp
  clang/unittests/Format/FormatTest.cpp

Index: clang/unittests/Format/FormatTest.cpp
===
--- clang/unittests/Format/FormatTest.cpp
+++ clang/unittests/Format/FormatTest.cpp
@@ -16401,6 +16401,229 @@
getLLVMStyle());
 }
 
+TEST_F(FormatTest, CatchAlignArrayOfStructures) {
+  auto Style = getLLVMStyle();
+  Style.AlignArrayOfStructures = true;
+  Style.AlignConsecutiveAssignments =
+  FormatStyle::AlignConsecutiveStyle::ACS_Consecutive;
+  Style.AlignConsecutiveDeclarations =
+  FormatStyle::AlignConsecutiveStyle::ACS_Consecutive;
+  verifyFormat("struct test demo[] = {\n"
+   "{56,23, \"hello\"},\n"
+   "{-1, 93463, \"world\"},\n"
+   "{ 7, 5,\"!!\"}\n"
+   "};\n",
+   Style);
+
+  verifyFormat("struct test demo[] = {\n"
+   "{56,23, \"hello\"}, // first line\n"
+   "{-1, 93463, \"world\"}, // second line\n"
+   "{ 7, 5,\"!!\"}  // third line\n"
+   "};\n",
+   Style);
+
+  verifyFormat("struct test demo[4] = {\n"
+   "{ 56,23, 21,   \"oh\"}, // first line\n"
+   "{ -1, 93463, 22,   \"my\"}, // second line\n"
+   "{  7, 5,  1, \"goodness\"}  // third line\n"
+   "{234, 5,  1, \"gracious\"}  // fourth line\n"
+   "};\n",
+   Style);
+
+  verifyFormat("struct test demo[3] = {\n"
+   "{56,23, \"hello\"},\n"
+   "{-1, 93463, \"world\"},\n"
+   "{ 7, 5,\"!!\"}\n"
+   "};\n",
+   Style);
+  verifyFormat("struct test demo[3] = {\n"
+   "{int{56},23, \"hello\"},\n"
+   "{int{-1}, 93463, \"world\"},\n"
+   "{ int{7}, 5,\"!!\"}\n"
+   "};\n",
+   Style);
+  verifyFormat("struct test demo[] = {\n"
+   "{56,23, \"hello\"},\n"
+   "{-1, 93463, \"world\"},\n"
+   "{ 7, 5,\"!!\"},\n"
+   "};\n",
+   Style);
+  verifyFormat("test demo[] = {\n"
+   "{56,23, \"hello\"},\n"
+   "{-1, 93463, \"world\"},\n"
+   "{ 7, 5,\"!!\"},\n"
+   "};\n",
+   Style);
+  verifyFormat("demo = std::array{\n"
+   "test{56,23, \"hello\"},\n"
+   "test{-1, 93463, \"world\"},\n"
+   "test{ 7, 5,\"!!\"},\n"
+   "};\n",
+   Style);
+  verifyFormat("test demo[] = {\n"
+   "{56,23, \"hello\"},\n"
+   "#if X\n"
+   "{-1, 93463, \"world\"},\n"
+   "#endif\n"
+   "{ 7, 5,\"!!\"}\n"
+   "};\n",
+   Style);
+
+  verifyFormat(
+  "test demo[] = {\n"
+  "{ 7,23,\n"
+  " \"hello world i am a very long line that really, in any\"\n"
+  " \"just world, ought to be split over multiple lines\"},\n"
+  "{-1, 93463,  \"world\"},\n"
+  "{56, 5, \"!!\"}\n"
+  "};\n",
+  Style);
+  verifyFormat("return GradForUnaryCwise(g, {\n"
+   "{{\"sign\"}, \"Sign\",  "
+   "  {\"x\", \"dy\"}},\n"
+   "{  {\"dx\"},  \"Mul\", {\"dy\""
+   ", \"sign\"}},\n"
+   "});\n",
+   Style);
+
+  Style.ColumnLimit = 0;
+  EXPECT_EQ(
+  "test demo[] = {\n"
+  "{56,23, \"hello world i am a very long line that really, "
+  "in any just world, ought to be split over multiple lines\"},\n"
+  "{-1, 93463,  "
+  " \"world\"},\n"
+  "{ 7, 5,  "
+  "\"!!\"},\n"
+  "};",
+  format("test demo[] = {{56, 23, \"hello world i am a very long line "
+   

[PATCH] D101868: [clang-format] Adds a formatter for aligning arrays of structs

2021-06-03 Thread Fred Grim via Phabricator via cfe-commits
feg208 added a comment.

Got both of these




Comment at: clang/lib/Format/TokenAnnotator.cpp:737-740
+const auto End = Contexts.rbegin() + 2;
+auto Last = Contexts.rbegin();
+unsigned Depth = 0;
+for (; Last != End; Last = std::next(Last)) {

HazardyKnusperkeks wrote:
> I actually meant so. Because now this is even safe if the iterators are not 
> random access anymore in the future.
Oh I see. I sort of wondered about that but it didn't seem like a hill to die 
on.



Comment at: clang/lib/Format/WhitespaceManager.cpp:1136-1137
+auto j = i - 1;
+for (; j > 0 && Changes[j].NewlinesBefore == 0; --j) {
+}
+EndSpaces = Changes[j].Spaces;

HazardyKnusperkeks wrote:
> I don't know how to do this in LLVM style, but maybe so?
So long as clang-format doesn't complain I am fine either way


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D101868

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


[PATCH] D103631: [analyzer] Turn TrackControlDependencyCond into a tracking visitor

2021-06-03 Thread Valeriy Savchenko via Phabricator via cfe-commits
vsavchenko created this revision.
vsavchenko added reviewers: NoQ, xazax.hun, martong, steakhal, Szelethus, 
manas, RedDocMD.
Herald added subscribers: ASDenysPetrov, dkrupp, donat.nagy, mikhail.ramalho, 
a.sidorin, rnkovacs, szepet, baloghadamsoftware.
vsavchenko requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D103631

Files:
  clang/lib/StaticAnalyzer/Core/BugReporterVisitors.cpp


Index: clang/lib/StaticAnalyzer/Core/BugReporterVisitors.cpp
===
--- clang/lib/StaticAnalyzer/Core/BugReporterVisitors.cpp
+++ clang/lib/StaticAnalyzer/Core/BugReporterVisitors.cpp
@@ -1855,14 +1855,17 @@
 /// An error is emitted at line 3. This visitor realizes that the branch
 /// on line 2 is a control dependency of line 3, and tracks it's condition via
 /// trackExpressionValue().
-class TrackControlDependencyCondBRVisitor final : public BugReporterVisitor {
+class TrackControlDependencyCondBRVisitor final
+: public TrackingBugReporterVisitor {
   const ExplodedNode *Origin;
   ControlDependencyCalculator ControlDeps;
   llvm::SmallSet VisitedBlocks;
 
 public:
-  TrackControlDependencyCondBRVisitor(const ExplodedNode *O)
-  : Origin(O), ControlDeps(&O->getCFG()) {}
+  TrackControlDependencyCondBRVisitor(TrackerRef ParentTracker,
+  const ExplodedNode *O)
+  : TrackingBugReporterVisitor(ParentTracker), Origin(O),
+ControlDeps(&O->getCFG()) {}
 
   void Profile(llvm::FoldingSetNodeID &ID) const override {
 static int x = 0;
@@ -1960,9 +1963,9 @@
   // isn't sufficient, because a new visitor is created for each tracked
   // expression, hence the BugReport level set.
   if (BR.addTrackedCondition(N)) {
-bugreporter::trackExpressionValue(
-N, Condition, BR, bugreporter::TrackingKind::Condition,
-/*EnableNullFPSuppression=*/false);
+getParentTracker().track(Condition, N,
+ {bugreporter::TrackingKind::Condition,
+  /*EnableNullFPSuppression=*/false});
 return constructDebugPieceForTrackedCondition(Condition, N, BRC);
   }
 }
@@ -2078,7 +2081,8 @@
 if (LVState->getAnalysisManager()
 .getAnalyzerOptions()
 .ShouldTrackConditions) {
-  Report.addVisitor(InputNode);
+  Report.addVisitor(
+  &getParentTracker(), InputNode);
   Result.FoundSomethingToTrack = true;
 }
 


Index: clang/lib/StaticAnalyzer/Core/BugReporterVisitors.cpp
===
--- clang/lib/StaticAnalyzer/Core/BugReporterVisitors.cpp
+++ clang/lib/StaticAnalyzer/Core/BugReporterVisitors.cpp
@@ -1855,14 +1855,17 @@
 /// An error is emitted at line 3. This visitor realizes that the branch
 /// on line 2 is a control dependency of line 3, and tracks it's condition via
 /// trackExpressionValue().
-class TrackControlDependencyCondBRVisitor final : public BugReporterVisitor {
+class TrackControlDependencyCondBRVisitor final
+: public TrackingBugReporterVisitor {
   const ExplodedNode *Origin;
   ControlDependencyCalculator ControlDeps;
   llvm::SmallSet VisitedBlocks;
 
 public:
-  TrackControlDependencyCondBRVisitor(const ExplodedNode *O)
-  : Origin(O), ControlDeps(&O->getCFG()) {}
+  TrackControlDependencyCondBRVisitor(TrackerRef ParentTracker,
+  const ExplodedNode *O)
+  : TrackingBugReporterVisitor(ParentTracker), Origin(O),
+ControlDeps(&O->getCFG()) {}
 
   void Profile(llvm::FoldingSetNodeID &ID) const override {
 static int x = 0;
@@ -1960,9 +1963,9 @@
   // isn't sufficient, because a new visitor is created for each tracked
   // expression, hence the BugReport level set.
   if (BR.addTrackedCondition(N)) {
-bugreporter::trackExpressionValue(
-N, Condition, BR, bugreporter::TrackingKind::Condition,
-/*EnableNullFPSuppression=*/false);
+getParentTracker().track(Condition, N,
+ {bugreporter::TrackingKind::Condition,
+  /*EnableNullFPSuppression=*/false});
 return constructDebugPieceForTrackedCondition(Condition, N, BRC);
   }
 }
@@ -2078,7 +2081,8 @@
 if (LVState->getAnalysisManager()
 .getAnalyzerOptions()
 .ShouldTrackConditions) {
-  Report.addVisitor(InputNode);
+  Report.addVisitor(
+  &getParentTracker(), InputNode);
   Result.FoundSomethingToTrack = true;
 }
 
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D103563: [HIP] Fix amdgcn builtin for long type

2021-06-03 Thread Artem Belevich via Phabricator via cfe-commits
tra accepted this revision.
tra added a comment.

Still LGTM.


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

https://reviews.llvm.org/D103563

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


[PATCH] D103613: [flang][driver] Add support for `-module-suffix`

2021-06-03 Thread Andrzej Warzynski via Phabricator via cfe-commits
awarzynski updated this revision to Diff 349595.
awarzynski added a comment.

Minor tweaks (different suffix in test, updated help text)


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D103613

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

Index: flang/test/Driver/module-suffix.f90
===
--- /dev/null
+++ flang/test/Driver/module-suffix.f90
@@ -0,0 +1,16 @@
+! Tests `-module-suffix` frontend option
+
+!--
+! RUN lines
+!--
+! RUN: rm -rf %t && mkdir -p %t/dir-flang/
+! RUN: cd %t && %flang_fc1 -fsyntax-only -module-suffix .f18.mod -module-dir %t/dir-flang %s
+! RUN: ls %t/dir-flang/testmodule.f18.mod && not ls %t/dir-flang/testmodule.mod
+
+!--
+! INPUT
+!--
+module testmodule
+  type::t2
+  end type
+end
Index: flang/test/Driver/driver-help.f90
===
--- flang/test/Driver/driver-help.f90
+++ flang/test/Driver/driver-help.f90
@@ -106,6 +106,7 @@
 ! HELP-FC1-NEXT: -help  Display available options
 ! HELP-FC1-NEXT: -IAdd directory to the end of the list of include search paths
 ! HELP-FC1-NEXT: -module-dir   Put MODULE files in 
+! HELP-FC1-NEXT: -module-suffix  Use  as the suffix for module files (the default value is `.mod`)
 ! HELP-FC1-NEXT: -nocpp Disable predefined and command line preprocessor macros
 ! HELP-FC1-NEXT: -o   Write output to 
 ! HELP-FC1-NEXT: -pedantic  Warn on language extensions
Index: flang/lib/Frontend/CompilerInvocation.cpp
===
--- flang/lib/Frontend/CompilerInvocation.cpp
+++ flang/lib/Frontend/CompilerInvocation.cpp
@@ -392,6 +392,12 @@
 res.SetDebugModuleDir(true);
   }
 
+  // -module-suffix
+  if (const auto *moduleSuffix =
+  args.getLastArg(clang::driver::options::OPT_module_suffix)) {
+res.SetModuleFileSuffix(moduleSuffix->getValue());
+  }
+
   return diags.getNumErrors() == numErrorsBefore;
 }
 
@@ -639,5 +645,6 @@
   semanticsContext_->set_moduleDirectory(moduleDir())
   .set_searchDirectories(fortranOptions.searchDirectories)
   .set_warnOnNonstandardUsage(enableConformanceChecks())
-  .set_warningsAreErrors(warnAsErr());
+  .set_warningsAreErrors(warnAsErr())
+  .set_moduleFileSuffix(moduleFileSuffix());
 }
Index: flang/include/flang/Frontend/CompilerInvocation.h
===
--- flang/include/flang/Frontend/CompilerInvocation.h
+++ flang/include/flang/Frontend/CompilerInvocation.h
@@ -69,6 +69,8 @@
   // of options.
   std::string moduleDir_ = ".";
 
+  std::string moduleFileSuffix_ = ".mod";
+
   bool debugModuleDir_ = false;
 
   bool warnAsErr_ = false;
@@ -97,6 +99,9 @@
   std::string &moduleDir() { return moduleDir_; }
   const std::string &moduleDir() const { return moduleDir_; }
 
+  std::string &moduleFileSuffix() { return moduleFileSuffix_; }
+  const std::string &moduleFileSuffix() const { return moduleFileSuffix_; }
+
   bool &debugModuleDir() { return debugModuleDir_; }
   const bool &debugModuleDir() const { return debugModuleDir_; }
 
@@ -129,6 +134,10 @@
   /// Useful setters
   void SetModuleDir(std::string &moduleDir) { moduleDir_ = moduleDir; }
 
+  void SetModuleFileSuffix(const char *moduleFileSuffix) {
+moduleFileSuffix_ = std::string(moduleFileSuffix);
+  }
+
   void SetDebugModuleDir(bool flag) { debugModuleDir_ = flag; }
 
   void SetWarnAsErr(bool flag) { warnAsErr_ = flag; }
Index: clang/include/clang/Driver/Options.td
===
--- clang/include/clang/Driver/Options.td
+++ clang/include/clang/Driver/Options.td
@@ -4521,6 +4521,9 @@
 def fget_symbols_sources : Flag<["-"], "fget-symbols-sources">, Group,
   HelpText<"Dump symbols and their source code locations">;
 
+def module_suffix : Separate<["-"], "module-suffix">,  Group, MetaVarName<"">,
+  HelpText<"Use  as the suffix for module files (the default value is `.mod`)">;
+
 }
 
 //===--===//
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


  1   2   >