[PATCH] D59980: [Attributor] Deduce memory behavior argument attributes

2019-03-29 Thread Johannes Doerfert via Phabricator via cfe-commits
jdoerfert updated this revision to Diff 192961.
jdoerfert added a comment.

Minor update


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D59980

Files:
  clang/test/CodeGen/arm-vfp16-arguments.c
  clang/test/CodeGen/systemz-inline-asm.c
  clang/test/CodeGenCXX/wasm-args-returns.cpp
  clang/test/CodeGenObjC/os_log.m
  clang/test/CodeGenOpenCL/amdgpu-abi-struct-coerce.cl
  clang/test/CodeGenOpenCL/amdgpu-call-kernel.cl
  clang/test/CodeGenOpenCL/kernels-have-spir-cc-by-default.cl
  llvm/include/llvm/Transforms/IPO/Attributor.h
  llvm/lib/Transforms/IPO/Attributor.cpp
  llvm/test/Transforms/FunctionAttrs/SCC1.ll
  llvm/test/Transforms/FunctionAttrs/arg_nocapture.ll
  llvm/test/Transforms/FunctionAttrs/arg_returned.ll
  llvm/test/Transforms/FunctionAttrs/nocapture.ll
  llvm/test/Transforms/FunctionAttrs/readattrs.ll

Index: llvm/test/Transforms/FunctionAttrs/readattrs.ll
===
--- llvm/test/Transforms/FunctionAttrs/readattrs.ll
+++ llvm/test/Transforms/FunctionAttrs/readattrs.ll
@@ -32,7 +32,7 @@
   ret void
 }
 
-; CHECK: define void @test5(i8** nocapture %p, i8* %q)
+; CHECK: define void @test5(i8** nocapture writeonly %p, i8* %q)
 ; Missed optz'n: we could make %q readnone, but don't break test6!
 define void @test5(i8** %p, i8* %q) {
   store i8* %q, i8** %p
@@ -40,7 +40,7 @@
 }
 
 declare void @test6_1()
-; CHECK: define void @test6_2(i8** nocapture %p, i8* %q)
+; CHECK: define void @test6_2(i8** nocapture writeonly %p, i8* %q)
 ; This is not a missed optz'n.
 define void @test6_2(i8** %p, i8* %q) {
   store i8* %q, i8** %p
@@ -48,7 +48,7 @@
   ret void
 }
 
-; CHECK: define void @test7_1(i32* inalloca nocapture %a)
+; CHECK: define void @test7_1(i32* inalloca nocapture readnone %a)
 ; inalloca parameters are always considered written
 define void @test7_1(i32* inalloca %a) {
   ret void
@@ -60,7 +60,7 @@
   ret i32* %p
 }
 
-; CHECK: define void @test8_2(i32* nocapture %p)
+; CHECK: define void @test8_2(i32* nocapture writeonly %p)
 define void @test8_2(i32* %p) {
 entry:
   %call = call i32* @test8_1(i32* %p)
Index: llvm/test/Transforms/FunctionAttrs/nocapture.ll
===
--- llvm/test/Transforms/FunctionAttrs/nocapture.ll
+++ llvm/test/Transforms/FunctionAttrs/nocapture.ll
@@ -134,15 +134,14 @@
 	ret void
 }
 
-; CHECK: define void @test1_1(i8* nocapture %x1_1, i8* nocapture %y1_1)
-; It would be acceptable to add readnone to %y1_1 and %y1_2.
+; CHECK: define void @test1_1(i8* nocapture readnone %x1_1, i8* nocapture readnone %y1_1)
 define void @test1_1(i8* %x1_1, i8* %y1_1) {
   call i8* @test1_2(i8* %x1_1, i8* %y1_1)
   store i32* null, i32** @g
   ret void
 }
 
-; CHECK: define i8* @test1_2(i8* nocapture %x1_2, i8* returned "no-capture-maybe-returned" %y1_2)
+; CHECK: define i8* @test1_2(i8* nocapture readnone %x1_2, i8* readnone returned "no-capture-maybe-returned" %y1_2)
 define i8* @test1_2(i8* %x1_2, i8* %y1_2) {
   call void @test1_1(i8* %x1_2, i8* %y1_2)
   store i32* null, i32** @g
@@ -156,7 +155,7 @@
   ret void
 }
 
-; CHECK: define void @test3(i8* nocapture %x3, i8* nocapture readnone %y3, i8* nocapture %z3)
+; CHECK: define void @test3(i8* nocapture readnone %x3, i8* nocapture readnone %y3, i8* nocapture readnone %z3)
 define void @test3(i8* %x3, i8* %y3, i8* %z3) {
   call void @test3(i8* %z3, i8* %y3, i8* %x3)
   store i32* null, i32** @g
@@ -237,7 +236,7 @@
   ret void
 }
 
-; CHECK: @nocaptureStrip(i8* nocapture %p)
+; CHECK: @nocaptureStrip(i8* nocapture writeonly %p)
 define void @nocaptureStrip(i8* %p) {
 entry:
   %b = call i8* @llvm.strip.invariant.group.p0i8(i8* %p)
Index: llvm/test/Transforms/FunctionAttrs/arg_returned.ll
===
--- llvm/test/Transforms/FunctionAttrs/arg_returned.ll
+++ llvm/test/Transforms/FunctionAttrs/arg_returned.ll
@@ -180,8 +180,8 @@
 ; FNATTR: define dso_local double* @ptr_scc_r1(double* %a, double* readnone %r, double* nocapture readnone %b) [[NoInlineNoUnwindReadnoneUwtable]]
 ; FNATTR: define dso_local double* @ptr_scc_r2(double* readnone %a, double* readnone %b, double* readnone %r) [[NoInlineNoUnwindReadnoneUwtable]]
 ;
-; ATTRIBUTOR: define dso_local double* @ptr_sink_r0(double* returned "no-capture-maybe-returned" %r) [[NoInlineNoRecurseNoUnwindReadnoneUwtable]]
-; ATTRIBUTOR: define dso_local double* @ptr_scc_r1(double* %a, double* returned %r, double* nocapture %b) [[NoInlineNoUnwindReadnoneUwtable]]
+; ATTRIBUTOR: define dso_local double* @ptr_sink_r0(double* readnone returned "no-capture-maybe-returned" %r) [[NoInlineNoRecurseNoUnwindReadnoneUwtable]]
+; ATTRIBUTOR: define dso_local double* @ptr_scc_r1(double* %a, double* returned %r, double* nocapture readnone %b) [[NoInlineNoUnwindReadnoneUwtable]]
 ; ATTRIBUTOR: define dso_local double* @ptr_scc_r2(double* %a, double* %b, 

[PATCH] D59806: [clang-tidy] Add a check for [super self] in initializers 

2019-03-29 Thread John McCall via Phabricator via cfe-commits
rjmccall added a comment.

In D59806#1448537 , @stephanemoore 
wrote:

> In D59806#1447929 , @jordan_rose 
> wrote:
>
> > I don't think there's ever a reason to call `[super self]`, and doing so 
> > through a macro could easily indicate a bug.
>
>
> Agreed.
>
> The only relatively common usage of -[NSObject self] that I am aware of is 
> through KVC, e.g., to construct a set of distinct objects using array 
> operators:


It's used idiomatically in ARC and GC as a way of preventing an object from 
being deallocated before a certain point, since the compiler cannot eliminate 
the call to `self`.  But that shouldn't affect this warning.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D59806



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


[PATCH] D59988: [PR41276] Generate address space cast of 'this' for objects attributed by an address space in C++

2019-03-29 Thread John McCall via Phabricator via cfe-commits
rjmccall added inline comments.



Comment at: lib/CodeGen/CGClass.cpp:2025
+ThisPtr =
+Builder.CreatePointerBitCastOrAddrSpaceCast(This.getPointer(), 
NewType);
   }

Anastasia wrote:
> I am a bit unsure if `performAddrSpaceCast` should be used, but considering 
> that we know that we are not casting a constant it should be fine?
> 
> If not any suggestions how to propagate `LangAS` of 'this' here. Some 
> thoughts I have are:
> - Try to list the conversion up in the call stack
> - Pass `LangAS` all the way to here
I feel like `This` should just be in the right address space for the 
constructor at the point `EmitCXXConstructorCall` is called.  We don't expect 
this function to do any other semantic conversions.  Or is this necessary to 
handle special-case use of things like trivial default / copy constructors?



Comment at: lib/Sema/SemaInit.cpp:7325
+  CastKind CK = (!(VK == VK_RValue && Ty->getPointeeType().isNull()) &&
+ Ty.getAddressSpace() != E->getType().getAddressSpace())
 ? CK_AddressSpaceConversion

If this function is being used to do pointee qualification conversions on 
pointer r-values, I think you need to look at whether the pointee address 
spaces are different, right?


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

https://reviews.llvm.org/D59988



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


[PATCH] D60023: [libcxx] [test] Fix inability to rebind poca_alloc in string.cons/copy_alloc.pass.cpp.

2019-03-29 Thread Billy Robert O'Neal III via Phabricator via cfe-commits
BillyONeal created this revision.
BillyONeal added reviewers: EricWF, ldionne, mclow.lists.
BillyONeal added a project: libc++.
Herald added subscribers: jdoerfert, dexonsmith.

copy_alloc.pass.cpp contains an allocator that tries to be rebindable; but if 
it actually does that it fails because the alloc_imp type is not rebindable (so 
you get failure to compile because alloc_imp* isn't convertible to 
alloc_imp*).

The fix is to make the members of alloc_impl templates instead of making 
alloc_imp itself a template.

This allows the test for MSVC++ because we need to rebind for _Container_proxy.


https://reviews.llvm.org/D60023

Files:
  test/std/strings/basic.string/string.cons/copy_alloc.pass.cpp


Index: test/std/strings/basic.string/string.cons/copy_alloc.pass.cpp
===
--- test/std/strings/basic.string/string.cons/copy_alloc.pass.cpp
+++ test/std/strings/basic.string/string.cons/copy_alloc.pass.cpp
@@ -18,12 +18,12 @@
 #include "min_allocator.h"
 
 #ifndef TEST_HAS_NO_EXCEPTIONS
-template 
 struct alloc_imp {
 bool active;
 
 alloc_imp() : active(true) {}
 
+template 
 T* allocate(std::size_t n)
 {
 if (active)
@@ -32,6 +32,7 @@
 throw std::bad_alloc();
 }
 
+template 
 void deallocate(T* p, std::size_t) { std::free(p); }
 void activate  ()  { active = true; }
 void deactivate()  { active = false; }
@@ -42,14 +43,14 @@
 typedef T value_type;
 typedef std::true_type propagate_on_container_copy_assignment;
 
-alloc_imp *imp;
+alloc_imp *imp;
 
-poca_alloc(alloc_imp *imp_) : imp (imp_) {}
+poca_alloc(alloc_imp *imp_) : imp (imp_) {}
 
 template 
 poca_alloc(const poca_alloc& other) : imp(other.imp) {}
 
-T*   allocate  (std::size_t n)   { return imp->allocate(n);}
+T*   allocate  (std::size_t n)   { return imp->allocate(n);}
 void deallocate(T* p, std::size_t n) { imp->deallocate(p, n); }
 };
 
@@ -112,8 +113,8 @@
 const char * p1 = "This is my first string";
 const char * p2 = "This is my second string";
 
-alloc_imp imp1;
-alloc_imp imp2;
+alloc_imp imp1;
+alloc_imp imp2;
 S s1(p1, A());
 S s2(p2, A());
 


Index: test/std/strings/basic.string/string.cons/copy_alloc.pass.cpp
===
--- test/std/strings/basic.string/string.cons/copy_alloc.pass.cpp
+++ test/std/strings/basic.string/string.cons/copy_alloc.pass.cpp
@@ -18,12 +18,12 @@
 #include "min_allocator.h"
 
 #ifndef TEST_HAS_NO_EXCEPTIONS
-template 
 struct alloc_imp {
 bool active;
 
 alloc_imp() : active(true) {}
 
+template 
 T* allocate(std::size_t n)
 {
 if (active)
@@ -32,6 +32,7 @@
 throw std::bad_alloc();
 }
 
+template 
 void deallocate(T* p, std::size_t) { std::free(p); }
 void activate  ()  { active = true; }
 void deactivate()  { active = false; }
@@ -42,14 +43,14 @@
 typedef T value_type;
 typedef std::true_type propagate_on_container_copy_assignment;
 
-alloc_imp *imp;
+alloc_imp *imp;
 
-poca_alloc(alloc_imp *imp_) : imp (imp_) {}
+poca_alloc(alloc_imp *imp_) : imp (imp_) {}
 
 template 
 poca_alloc(const poca_alloc& other) : imp(other.imp) {}
 
-T*   allocate  (std::size_t n)   { return imp->allocate(n);}
+T*   allocate  (std::size_t n)   { return imp->allocate(n);}
 void deallocate(T* p, std::size_t n) { imp->deallocate(p, n); }
 };
 
@@ -112,8 +113,8 @@
 const char * p1 = "This is my first string";
 const char * p2 = "This is my second string";
 
-alloc_imp imp1;
-alloc_imp imp2;
+alloc_imp imp1;
+alloc_imp imp2;
 S s1(p1, A());
 S s2(p2, A());
 
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D46140: [coroutines] Add std::experimental::task type

2019-03-29 Thread Lewis Baker via Phabricator via cfe-commits
lewissbaker updated this revision to Diff 192944.
lewissbaker marked 6 inline comments as done.
lewissbaker added a comment.

This updated diff should address most of @CaseyCarter's review comments.

For detailed changelog you can find individual changes here 
https://github.com/lewissbaker/libcxx/commits/coro_task

There are a few outstanding issues that still need some clarification on how to 
proceed:

- Should the task tests be taking a dependency on 
?
- How should I implement a precondition check for `__aligned_allocation_size` 
when it is declared constexpr?
- I've not yet implemented support for `task`. Is this something we 
should support?
- I've not yet handling allocators with fancy pointer types. If we are to 
support them is there a standard way to convert a fancy pointer to a `void*` to 
return from `promise_type::operator new()`? Does it even make sense to support 
them if the compiler is potentially going to be storing raw pointers to things 
inside the coroutine frame?


Repository:
  rCXX libc++

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

https://reviews.llvm.org/D46140

Files:
  include/CMakeLists.txt
  include/experimental/__memory
  include/experimental/coroutine
  include/experimental/memory_resource
  include/experimental/task
  include/module.modulemap
  test/std/experimental/task/awaitable_traits.hpp
  test/std/experimental/task/counted.hpp
  test/std/experimental/task/lit.local.cfg
  test/std/experimental/task/manual_reset_event.hpp
  test/std/experimental/task/sync_wait.hpp
  test/std/experimental/task/task.basic/task_custom_allocator.pass.cpp
  test/std/experimental/task/task.basic/task_of_value.pass.cpp
  test/std/experimental/task/task.basic/task_of_void.pass.cpp
  test/std/experimental/task/task.lifetime/task_parameter_lifetime.pass.cpp
  test/std/experimental/task/task.lifetime/task_return_value_lifetime.pass.cpp

Index: test/std/experimental/task/task.lifetime/task_return_value_lifetime.pass.cpp
===
--- /dev/null
+++ test/std/experimental/task/task.lifetime/task_return_value_lifetime.pass.cpp
@@ -0,0 +1,157 @@
+// -*- C++ -*-
+//===--===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is dual licensed under the MIT and the University of Illinois Open
+// Source Licenses. See LICENSE.TXT for details.
+//
+//===--===//
+
+// UNSUPPORTED: c++98, c++03, c++11, c++14
+
+#include 
+#include 
+#include 
+
+#include "../counted.hpp"
+#include "../sync_wait.hpp"
+
+void test_return_value_lifetime()
+{
+  counted::reset();
+
+  auto f = [](bool x) -> std::experimental::task
+  {
+if (x) {
+  counted c;
+  co_return std::move(c);
+}
+co_return {};
+  };
+
+  {
+auto t = f(true);
+
+assert(counted::active_instance_count() == 0);
+assert(counted::copy_constructor_count() == 0);
+assert(counted::move_constructor_count() == 0);
+
+{
+  auto c = ::sync_wait(std::move(t));
+  assert(c.id() == 1);
+
+  assert(counted::active_instance_count() == 2);
+  assert(counted::copy_constructor_count() == 0);
+  assert(counted::move_constructor_count() > 0);
+  assert(counted::default_constructor_count() == 1);
+}
+
+// The result value in 't' is still alive until 't' destructs.
+assert(counted::active_instance_count() == 1);
+  }
+
+  assert(counted::active_instance_count() == 0);
+
+  counted::reset();
+
+  {
+auto t = f(false);
+
+assert(counted::active_instance_count() == 0);
+assert(counted::copy_constructor_count() == 0);
+assert(counted::move_constructor_count() == 0);
+
+{
+  auto c = ::sync_wait(std::move(t));
+  assert(c.id() == 1);
+
+  assert(counted::active_instance_count() == 2);
+  assert(counted::copy_constructor_count() == 0);
+  assert(counted::move_constructor_count() > 0);
+  assert(counted::default_constructor_count() == 1);
+}
+
+// The result value in 't' is still alive until 't' destructs.
+assert(counted::active_instance_count() == 1);
+  }
+}
+
+struct my_error {};
+
+struct throws_on_destruction
+{
+  ~throws_on_destruction() noexcept(false)
+  {
+throw my_error{};
+  }
+};
+
+void test_uncaught_exception_thrown_after_co_return()
+{
+  counted::reset();
+
+  assert(counted::active_instance_count() == 0);
+  assert(counted::copy_constructor_count() == 0);
+  assert(counted::move_constructor_count() == 0);
+
+  {
+auto t = []() -> std::experimental::task
+{
+  throws_on_destruction d;
+  co_return counted{};
+}();
+
+try {
+  (void)::sync_wait(std::move(t));
+  assert(false);
+} catch (const my_error&) {
+}
+
+assert(counted::active_instance_count() == 0);
+assert(counted::copy_constructor_count() == 0);
+

[PATCH] D46140: [coroutines] Add std::experimental::task type

2019-03-29 Thread Lewis Baker via Phabricator via cfe-commits
lewissbaker marked 40 inline comments as done.
lewissbaker added a comment.

Thanks very much for the detailed review @CaseyCarter! Very much appreciated :)




Comment at: include/experimental/__memory:80
+{
+return (__s + __a - 1) & ~(__a - 1);
+}

CaseyCarter wrote:
> This is missing preconditions that `__a` is a power of 2, and that `__s <=  
> -__a`.
Is there a recommended way of documenting/implementing these preconditions on a 
constexpr function in libc++?

The previous version that lived in `` was not 
marked constexpr and so was able to use `_LIBCPP_ASSERT`.



Comment at: include/experimental/task:28
+#if defined(_LIBCPP_WARNING)
+_LIBCPP_WARNING(" cannot be used with this compiler")
+#else

CaseyCarter wrote:
> "requires a compiler with support for coroutines" would be more informative.
This messaging was copied from .

I'll update the message there as well.



Comment at: include/experimental/task:141
+
+void* __pointer = __charAllocator.allocate(
+__get_padded_frame_size_with_allocator<_CharAlloc>(__size));

CaseyCarter wrote:
> The return value of `allocate` isn't necessarily convertible to `void*`, it 
> could be a fancy pointer. We should either `static_assert(is_same_v allocator_traits<_CharAlloc>::void_pointer, void*>, "Piss off with your fancy 
> pointers");` or use `pointer_traits` here and in `__deallocFunc` to unfancy 
> and re-fancy the pointer.
I'm not quite sure how to go about using `pointer_traits` here when interacting 
with coroutines and allocators.

Under C++20 I guess I would do something like:
```
typename allocator_traits<_CharAlloc>::void_pointer __pointer = 
__charAllocator.allocate(...);
...
return _VSTD::to_address(__pointer);
```

I assume that `operator new()` still needs to return `void*` rather than the 
fancy pointer so we need the `to_address` call in there. Is there some fallback 
for `to_address()` for unfancying the pointer in earlier standard versions?

Maybe we should just go with the `static_assert()` for now?




Comment at: include/experimental/task:220
+public:
+  __task_promise() _NOEXCEPT : __state_(_State::__no_value) {}
+

CaseyCarter wrote:
> This mem-initializer for `__state_` is redundant with the default member 
> initializer on 306.
I'll remove the default member initializer on 306 then.

We can't `= default` the constructor here due to the union member containing 
types with non-trivial constructors/destructors.



Comment at: include/experimental/task:244
+exception_ptr(current_exception());
+__state_ = _State::__exception;
+#else

CaseyCarter wrote:
> Are you certain that `unhandled_exception` can't possibly be called after 
> storing a value? If so, this would leak the value.
Yes, I think there is a case where this could happen.

If we execute a `co_return someValue` which calls `promise.return_value()` and 
constructs `__value_`.
Then while executing the `goto final_suspend;` if any of the destructors of 
in-scope variables throw an exception which then escapes the coroutine body we 
could end up calling `unhandled_exception()` with `__value_` already having 
been constructed.

Similarly, the exception thrown from a destructor could be caught and then a 
new `co_return someOtherValue;` executed.
So we should probably be guarding against `__value_` containing a value inside 
`return_value()` as well.



Comment at: include/experimental/task:308
+  union {
+char __empty_;
+_Tp __value_;

CaseyCarter wrote:
> These `__empty_` members seem extraneous. 
The `__empty_` members were added at your request ;)

See https://reviews.llvm.org/D46140?id=144168#inline-403822

I can remove them if you think they're not necessary.



Comment at: include/experimental/task:309
+char __empty_;
+_Tp __value_;
+exception_ptr __exception_;

CaseyCarter wrote:
> Should we `static_assert` that `_Tp` is a destructible object type?
Sure, will do.

I wonder if we should make this a requirement in the wording of 
[P1056](https://wg21.link/P1056)?
What do you think @GorNishanov?



Comment at: include/experimental/task:373
+template <>
+class __task_promise final : public __task_promise_base {
+  using _Handle = coroutine_handle<__task_promise>;

CaseyCarter wrote:
> Do we care about `task`?
I don't feel strongly either way.

It's not something I've ever had a use for, but maybe it should be done for 
completeness?



Comment at: include/experimental/task:389
+
+  void __rvalue_result() { __throw_if_exception(); }
+

CaseyCarter wrote:
> Should these `__foovalue_result` members be `foo`-qualified to make them 
> harder to misuse?
I'm not sure if it makes it much safer.
We already have 'rvalue' in the method name which gives a hint to its 

[PATCH] D58367: [analyzer] NFC: Improve upon the concept of BugReporterVisitor.

2019-03-29 Thread Artem Dergachev via Phabricator via cfe-commits
NoQ reopened this revision.
NoQ added a comment.
This revision is now accepted and ready to land.

Re-reopen after the Diffusion auto-close.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D58367



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


[PATCH] D59914: [analyzer] MIGChecker: Add support for more deallocator APIs.

2019-03-29 Thread Phabricator via Phabricator via cfe-commits
This revision was not accepted when it landed; it landed in state "Needs 
Review".
This revision was automatically updated to reflect the committed changes.
Closed by commit rL357335: [analyzer] MIGChecker: Add support for more 
deallocator APIs. (authored by dergachev, committed by ).
Herald added a project: LLVM.
Herald added a subscriber: llvm-commits.

Changed prior to commit:
  https://reviews.llvm.org/D59914?vs=192553=192946#toc

Repository:
  rL LLVM

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

https://reviews.llvm.org/D59914

Files:
  cfe/trunk/lib/StaticAnalyzer/Checkers/MIGChecker.cpp
  cfe/trunk/test/Analysis/mig.mm

Index: cfe/trunk/test/Analysis/mig.mm
===
--- cfe/trunk/test/Analysis/mig.mm
+++ cfe/trunk/test/Analysis/mig.mm
@@ -15,11 +15,15 @@
 typedef unsigned vm_size_t;
 typedef void *ipc_space_t;
 typedef unsigned long io_user_reference_t;
+typedef struct ipc_port *ipc_port_t;
+typedef unsigned mach_port_t;
+typedef uint32_t UInt32;
 
 kern_return_t vm_deallocate(mach_port_name_t, vm_address_t, vm_size_t);
 kern_return_t mach_vm_deallocate(mach_port_name_t, vm_address_t, vm_size_t);
 void mig_deallocate(vm_address_t, vm_size_t);
 kern_return_t mach_port_deallocate(ipc_space_t, mach_port_name_t);
+void ipc_port_release(ipc_port_t);
 
 #define MIG_SERVER_ROUTINE __attribute__((mig_server_routine))
 
@@ -44,12 +48,17 @@
 class IOUserClient {
 public:
   static IOReturn releaseAsyncReference64(OSAsyncReference64);
+  static IOReturn releaseNotificationPort(mach_port_t port);
 
   MIG_SERVER_ROUTINE
-  virtual IOReturn externalMethod(uint32_t selector, IOExternalMethodArguments *arguments,
-  IOExternalMethodDispatch *dispatch = 0, OSObject *target = 0, void *reference = 0);
-};
+  virtual IOReturn externalMethod(
+  uint32_t selector, IOExternalMethodArguments *arguments,
+  IOExternalMethodDispatch *dispatch = 0, OSObject *target = 0,
+  void *reference = 0);
 
+  MIG_SERVER_ROUTINE
+  virtual IOReturn registerNotificationPort(mach_port_t, UInt32, UInt32);
+};
 
 // Tests.
 
@@ -182,6 +191,13 @@
  // expected-note@-1{{MIG callback fails with error after deallocating argument value}}
 }
 
+MIG_SERVER_ROUTINE
+kern_return_t test_ipc_port_release(ipc_port_t port) {
+  ipc_port_release(port); // expected-note{{Value passed through parameter 'port' is deallocated}}
+  return KERN_ERROR; // expected-warning{{MIG callback fails with error after deallocating argument value}}
+			   // expected-note@-1{{MIG callback fails with error after deallocating argument value}}
+}
+
 // Let's try the C++11 attribute spelling syntax as well.
 [[clang::mig_server_routine]]
 IOReturn test_releaseAsyncReference64(IOExternalMethodArguments *arguments) {
@@ -206,4 +222,10 @@
 return kIOReturnError;  // expected-warning{{MIG callback fails with error after deallocating argument value}}
 // expected-note@-1{{MIG callback fails with error after deallocating argument value}}
   }
+
+  IOReturn registerNotificationPort(mach_port_t port, UInt32 x, UInt32 y) {
+releaseNotificationPort(port); // expected-note{{Value passed through parameter 'port' is deallocated}}
+return kIOReturnError; // expected-warning{{MIG callback fails with error after deallocating argument value}}
+   // expected-note@-1{{MIG callback fails with error after deallocating argument value}}
+  }
 };
Index: cfe/trunk/lib/StaticAnalyzer/Checkers/MIGChecker.cpp
===
--- cfe/trunk/lib/StaticAnalyzer/Checkers/MIGChecker.cpp
+++ cfe/trunk/lib/StaticAnalyzer/Checkers/MIGChecker.cpp
@@ -54,11 +54,33 @@
   CALL(3, 1, "mach_vm_deallocate"),
   CALL(2, 0, "mig_deallocate"),
   CALL(2, 1, "mach_port_deallocate"),
+  CALL(1, 0, "device_deallocate"),
+  CALL(1, 0, "iokit_remove_connect_reference"),
+  CALL(1, 0, "iokit_remove_reference"),
+  CALL(1, 0, "iokit_release_port"),
+  CALL(1, 0, "ipc_port_release"),
+  CALL(1, 0, "ipc_port_release_sonce"),
+  CALL(1, 0, "ipc_voucher_attr_control_release"),
+  CALL(1, 0, "ipc_voucher_release"),
+  CALL(1, 0, "lock_set_dereference"),
+  CALL(1, 0, "memory_object_control_deallocate"),
+  CALL(1, 0, "pset_deallocate"),
+  CALL(1, 0, "semaphore_dereference"),
+  CALL(1, 0, "space_deallocate"),
+  CALL(1, 0, "space_inspect_deallocate"),
+  CALL(1, 0, "task_deallocate"),
+  CALL(1, 0, "task_inspect_deallocate"),
+  CALL(1, 0, "task_name_deallocate"),
+  CALL(1, 0, "thread_deallocate"),
+  CALL(1, 0, "thread_inspect_deallocate"),
+  CALL(1, 0, "upl_deallocate"),
+  CALL(1, 0, "vm_map_deallocate"),
   // E.g., if the checker sees a method 'releaseAsyncReference64()' that is
   // 

r357335 - [analyzer] MIGChecker: Add support for more deallocator APIs.

2019-03-29 Thread Artem Dergachev via cfe-commits
Author: dergachev
Date: Fri Mar 29 16:56:53 2019
New Revision: 357335

URL: http://llvm.org/viewvc/llvm-project?rev=357335=rev
Log:
[analyzer] MIGChecker: Add support for more deallocator APIs.

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

Modified:
cfe/trunk/lib/StaticAnalyzer/Checkers/MIGChecker.cpp
cfe/trunk/test/Analysis/mig.mm

Modified: cfe/trunk/lib/StaticAnalyzer/Checkers/MIGChecker.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/StaticAnalyzer/Checkers/MIGChecker.cpp?rev=357335=357334=357335=diff
==
--- cfe/trunk/lib/StaticAnalyzer/Checkers/MIGChecker.cpp (original)
+++ cfe/trunk/lib/StaticAnalyzer/Checkers/MIGChecker.cpp Fri Mar 29 16:56:53 
2019
@@ -54,11 +54,33 @@ class MIGChecker : public Checkerhttp://llvm.org/viewvc/llvm-project/cfe/trunk/test/Analysis/mig.mm?rev=357335=357334=357335=diff
==
--- cfe/trunk/test/Analysis/mig.mm (original)
+++ cfe/trunk/test/Analysis/mig.mm Fri Mar 29 16:56:53 2019
@@ -15,11 +15,15 @@ typedef unsigned vm_address_t;
 typedef unsigned vm_size_t;
 typedef void *ipc_space_t;
 typedef unsigned long io_user_reference_t;
+typedef struct ipc_port *ipc_port_t;
+typedef unsigned mach_port_t;
+typedef uint32_t UInt32;
 
 kern_return_t vm_deallocate(mach_port_name_t, vm_address_t, vm_size_t);
 kern_return_t mach_vm_deallocate(mach_port_name_t, vm_address_t, vm_size_t);
 void mig_deallocate(vm_address_t, vm_size_t);
 kern_return_t mach_port_deallocate(ipc_space_t, mach_port_name_t);
+void ipc_port_release(ipc_port_t);
 
 #define MIG_SERVER_ROUTINE __attribute__((mig_server_routine))
 
@@ -44,12 +48,17 @@ struct IOExternalMethodDispatch {};
 class IOUserClient {
 public:
   static IOReturn releaseAsyncReference64(OSAsyncReference64);
+  static IOReturn releaseNotificationPort(mach_port_t port);
 
   MIG_SERVER_ROUTINE
-  virtual IOReturn externalMethod(uint32_t selector, IOExternalMethodArguments 
*arguments,
-  IOExternalMethodDispatch *dispatch = 0, 
OSObject *target = 0, void *reference = 0);
-};
+  virtual IOReturn externalMethod(
+  uint32_t selector, IOExternalMethodArguments *arguments,
+  IOExternalMethodDispatch *dispatch = 0, OSObject *target = 0,
+  void *reference = 0);
 
+  MIG_SERVER_ROUTINE
+  virtual IOReturn registerNotificationPort(mach_port_t, UInt32, UInt32);
+};
 
 // Tests.
 
@@ -182,6 +191,13 @@ kern_return_t test_mig_deallocate(vm_add
  // expected-note@-1{{MIG callback fails with 
error after deallocating argument value}}
 }
 
+MIG_SERVER_ROUTINE
+kern_return_t test_ipc_port_release(ipc_port_t port) {
+  ipc_port_release(port); // expected-note{{Value passed through parameter 
'port' is deallocated}}
+  return KERN_ERROR; // expected-warning{{MIG callback fails with error after 
deallocating argument value}}
+  // 
expected-note@-1{{MIG callback fails with error after deallocating argument 
value}}
+}
+
 // Let's try the C++11 attribute spelling syntax as well.
 [[clang::mig_server_routine]]
 IOReturn test_releaseAsyncReference64(IOExternalMethodArguments *arguments) {
@@ -206,4 +222,10 @@ class MyClient: public IOUserClient {
 return kIOReturnError;  // 
expected-warning{{MIG callback fails with error after deallocating argument 
value}}
 // 
expected-note@-1{{MIG callback fails with error after deallocating argument 
value}}
   }
+
+  IOReturn registerNotificationPort(mach_port_t port, UInt32 x, UInt32 y) {
+releaseNotificationPort(port); // expected-note{{Value passed through 
parameter 'port' is deallocated}}
+return kIOReturnError; // expected-warning{{MIG callback fails with error 
after deallocating argument value}}
+   // expected-note@-1{{MIG callback fails with error 
after deallocating argument value}}
+  }
 };


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


Re: r357323 - [analyzer] Introduce a simplified API for adding custom path notes.

2019-03-29 Thread Artem Dergachev via cfe-commits

Yup, indeed, i reverted it in r357332.

Also, nice bot!

On 3/29/19 4:14 PM, Vitaly Buka wrote:

Bot detects memory leak probably after this patch

http://lab.llvm.org:8011/builders/sanitizer-x86_64-linux-fast/builds/30957/steps/check-clang%20asan/logs/stdio

= 
==22233==ERROR: LeakSanitizer: detected memory leaks Direct leak of 
1088 byte(s) in 17 object(s) allocated from: #0 0xc770f8 in operator 
new(unsigned long) 
/b/sanitizer-x86_64-linux-fast/build/llvm/projects/compiler-rt/lib/asan/asan_new_delete.cc:106 
#1 0x9c6feef in __libcpp_allocate 
/b/sanitizer-x86_64-linux-fast/build/libcxx_build_asan/include/c++/v1/new:238:10 
#2 0x9c6feef in allocate 
/b/sanitizer-x86_64-linux-fast/build/libcxx_build_asan/include/c++/v1/memory:1813 
#3 0x9c6feef in __value_func<(lambda at 
/b/sanitizer-x86_64-linux-fast/build/llvm/tools/clang/include/clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h:236:9), 
std::__1::allocator<(lambda at 
/b/sanitizer-x86_64-linux-fast/build/llvm/tools/clang/include/clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h:236:9)> 
> 
/b/sanitizer-x86_64-linux-fast/build/libcxx_build_asan/include/c++/v1/functional:1716 
#4 0x9c6feef in function<(lambda at 
/b/sanitizer-x86_64-linux-fast/build/llvm/tools/clang/include/clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h:236:9), 
void> 
/b/sanitizer-x86_64-linux-fast/build/libcxx_build_asan/include/c++/v1/functional:2290 
#5 0x9c6feef in 
clang::ento::CheckerContext::getNoteTag(std::__1::functionstd::__1::char_traits, std::__1::allocator > 
(clang::ento::BugReport&)>&&) 
/b/sanitizer-x86_64-linux-fast/build/llvm/tools/clang/include/clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h:236 
#6 0x9c6f061 in checkPostCall 
/b/sanitizer-x86_64-linux-fast/build/llvm/tools/clang/lib/StaticAnalyzer/Checkers/MIGChecker.cpp:165:24 
#7 0x9c6f061 in void 
clang::ento::check::PostCall::_checkCall<(anonymous 
namespace)::MIGChecker>(void*, clang::ento::CallEvent const&, 
clang::ento::CheckerContext&) 
/b/sanitizer-x86_64-linux-fast/build/llvm/tools/clang/include/clang/StaticAnalyzer/Core/Checker.h:183 
#8 0x9fbd78c in operator() 
/b/sanitizer-x86_64-linux-fast/build/llvm/tools/clang/include/clang/StaticAnalyzer/Core/CheckerManager.h:69:12 
#9 0x9fbd78c in runChecker 
/b/sanitizer-x86_64-linux-fast/build/llvm/tools/clang/lib/StaticAnalyzer/Core/CheckerManager.cpp:290 
#10 0x9fbd78c in expandGraphWithCheckers<(anonymous 
namespace)::CheckCallContext> 
/b/sanitizer-x86_64-linux-fast/build/llvm/tools/clang/lib/StaticAnalyzer/Core/CheckerManager.cpp:138 
#11 0x9fbd78c in 
clang::ento::CheckerManager::runCheckersForCallEvent(bool, 
clang::ento::ExplodedNodeSet&, clang::ento::ExplodedNodeSet const&, 
clang::ento::CallEvent const&, clang::ento::ExprEngine&, bool) 
/b/sanitizer-x86_64-linux-fast/build/llvm/tools/clang/lib/StaticAnalyzer/Core/CheckerManager.cpp:307 
#12 0xa07d1ef in runCheckersForPostCall 
/b/sanitizer-x86_64-linux-fast/build/llvm/tools/clang/include/clang/StaticAnalyzer/Core/CheckerManager.h:274:5 
#13 0xa07d1ef in 
clang::ento::ExprEngine::evalCall(clang::ento::ExplodedNodeSet&, 
clang::ento::ExplodedNode*, clang::ento::CallEvent const&) 
/b/sanitizer-x86_64-linux-fast/build/llvm/tools/clang/lib/StaticAnalyzer/Core/ExprEngineCallAndReturn.cpp:578 
#14 0xa07c657 in 
clang::ento::ExprEngine::VisitCallExpr(clang::CallExpr const*, 
clang::ento::ExplodedNode*, clang::ento::ExplodedNodeSet&) 
/b/sanitizer-x86_64-linux-fast/build/llvm/tools/clang/lib/StaticAnalyzer/Core/ExprEngineCallAndReturn.cpp:495:5 
#15 0xa01249f in clang::ento::ExprEngine::Visit(clang::Stmt const*, 
clang::ento::ExplodedNode*, clang::ento::ExplodedNodeSet&) 
/b/sanitizer-x86_64-linux-fast/build/llvm/tools/clang/lib/StaticAnalyzer/Core/ExprEngine.cpp:1539:7 
#16 0xa003888 in clang::ento::ExprEngine::ProcessStmt(clang::Stmt 
const*, clang::ento::ExplodedNode*) 
/b/sanitizer-x86_64-linux-fast/build/llvm/tools/clang/lib/StaticAnalyzer/Core/ExprEngine.cpp:743:5 
#17 0xa002d48 in 
clang::ento::ExprEngine::processCFGElement(clang::CFGElement, 
clang::ento::ExplodedNode*, unsigned int, 
clang::ento::NodeBuilderContext*) 
/b/sanitizer-x86_64-linux-fast/build/llvm/tools/clang/lib/StaticAnalyzer/Core/ExprEngine.cpp:590:7 
#18 0x9fdcdfe in 
clang::ento::CoreEngine::HandlePostStmt(clang::CFGBlock const*, 
unsigned int, clang::ento::ExplodedNode*) 
/b/sanitizer-x86_64-linux-fast/build/llvm/tools/clang/lib/StaticAnalyzer/Core/CoreEngine.cpp:438:12 
#19 0x9fdaa85 in 
clang::ento::CoreEngine::dispatchWorkItem(clang::ento::ExplodedNode*, 
clang::ProgramPoint, clang::ento::WorkListUnit const&) 
/b/sanitizer-x86_64-linux-fast/build/llvm/tools/clang/lib/StaticAnalyzer/Core/CoreEngine.cpp:192:7 
#20 0x9fd9941 in 
clang::ento::CoreEngine::ExecuteWorkList(clang::LocationContext 
const*, unsigned int, 
llvm::IntrusiveRefCntPtr) 

[PATCH] D59741: [lit] Set shlibpath_var on AIX

2019-03-29 Thread Hubert Tong via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rC357334: [lit] Set shlibpath_var on AIX (authored by 
hubert.reinterpretcast, committed by ).

Changed prior to commit:
  https://reviews.llvm.org/D59741?vs=192014=192942#toc

Repository:
  rC Clang

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

https://reviews.llvm.org/D59741

Files:
  test/Unit/lit.cfg.py


Index: test/Unit/lit.cfg.py
===
--- test/Unit/lit.cfg.py
+++ test/Unit/lit.cfg.py
@@ -42,6 +42,8 @@
 yield 'DYLD_LIBRARY_PATH'
 elif platform.system() == 'Windows':
 yield 'PATH'
+elif platform.system() == 'AIX':
+yield 'LIBPATH'
 
 for shlibpath_var in find_shlibpath_var():
 # in stand-alone builds, shlibdir is clang's build tree


Index: test/Unit/lit.cfg.py
===
--- test/Unit/lit.cfg.py
+++ test/Unit/lit.cfg.py
@@ -42,6 +42,8 @@
 yield 'DYLD_LIBRARY_PATH'
 elif platform.system() == 'Windows':
 yield 'PATH'
+elif platform.system() == 'AIX':
+yield 'LIBPATH'
 
 for shlibpath_var in find_shlibpath_var():
 # in stand-alone builds, shlibdir is clang's build tree
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


r357334 - [lit] Set shlibpath_var on AIX

2019-03-29 Thread Hubert Tong via cfe-commits
Author: hubert.reinterpretcast
Date: Fri Mar 29 16:33:04 2019
New Revision: 357334

URL: http://llvm.org/viewvc/llvm-project?rev=357334=rev
Log:
[lit] Set shlibpath_var on AIX

Summary:
When building the `check-all` target on AIX, lit produces
```
warning: unable to inject shared library path on 'AIX'
```

This patch addresses this. `LIBPATH` is the environment variable of
interest on AIX. Newer versions of AIX may consider `LD_LIBRARY_PATH`,
but only when `LIBPATH` is unset.

Reviewers: xingxue, jasonliu, sfertile, serge-sans-paille

Reviewed By: xingxue

Subscribers: jsji, cfe-commits, llvm-commits

Tags: #clang

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

Modified:
cfe/trunk/test/Unit/lit.cfg.py

Modified: cfe/trunk/test/Unit/lit.cfg.py
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/Unit/lit.cfg.py?rev=357334=357333=357334=diff
==
--- cfe/trunk/test/Unit/lit.cfg.py (original)
+++ cfe/trunk/test/Unit/lit.cfg.py Fri Mar 29 16:33:04 2019
@@ -42,6 +42,8 @@ def find_shlibpath_var():
 yield 'DYLD_LIBRARY_PATH'
 elif platform.system() == 'Windows':
 yield 'PATH'
+elif platform.system() == 'AIX':
+yield 'LIBPATH'
 
 for shlibpath_var in find_shlibpath_var():
 # in stand-alone builds, shlibdir is clang's build tree


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


[PATCH] D59802: [clang-tidy] Add new checker: llvm-avoid-cast-in-conditional

2019-03-29 Thread Don Hinton via Phabricator via cfe-commits
hintonda added a comment.

In D59802#1448574 , @hintonda wrote:

> - Added  matcher, and reordered tests.


Commandline ate my ticks... ;-(

Should be added `isMacroID` matcher.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D59802



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


[PATCH] D59806: [clang-tidy] Add a check for [super self] in initializers 

2019-03-29 Thread Stephane Moore via Phabricator via cfe-commits
stephanemoore marked 3 inline comments as done.
stephanemoore added inline comments.



Comment at: clang-tools-extra/clang-tidy/objc/SuperSelfCheck.cpp:112
+  << Message->getMethodDecl()
+  << FixItHint::CreateReplacement(Message->getSourceRange(),
+  StringRef("[super init]"));

stephanemoore wrote:
> aaron.ballman wrote:
> > This could be dangerous if the `[super self]` construct is in a macro, 
> > couldn't it? e.g.,
> > ```
> > #define DERP self
> > 
> > [super DERP];
> > ```
> Good point. Let me add some test cases and make sure this is handled properly.
Added some test cases where `[super self]` is expanded from macros.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D59806



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


[PATCH] D59802: [clang-tidy] Add new checker: llvm-avoid-cast-in-conditional

2019-03-29 Thread Don Hinton via Phabricator via cfe-commits
hintonda updated this revision to Diff 192939.
hintonda added a comment.

- Added  matcher, and reordered tests.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D59802

Files:
  clang-tools-extra/clang-tidy/llvm/AvoidCastInConditionalCheck.cpp
  clang-tools-extra/clang-tidy/llvm/AvoidCastInConditionalCheck.h
  clang-tools-extra/clang-tidy/llvm/CMakeLists.txt
  clang-tools-extra/clang-tidy/llvm/LLVMTidyModule.cpp
  clang-tools-extra/clang-tidy/utils/HeaderFileExtensionsUtils.h
  clang-tools-extra/docs/ReleaseNotes.rst
  clang-tools-extra/docs/clang-tidy/checks/list.rst
  clang-tools-extra/docs/clang-tidy/checks/llvm-avoid-cast-in-conditional.rst
  clang-tools-extra/test/clang-tidy/llvm-avoid-cast-in-conditional.cpp

Index: clang-tools-extra/test/clang-tidy/llvm-avoid-cast-in-conditional.cpp
===
--- /dev/null
+++ clang-tools-extra/test/clang-tidy/llvm-avoid-cast-in-conditional.cpp
@@ -0,0 +1,118 @@
+// RUN: %check_clang_tidy %s llvm-avoid-cast-in-conditional %t
+
+struct X;
+struct Y;
+struct Z {
+  int foo();
+  X *bar();
+};
+
+template 
+bool isa(Y *);
+template 
+X *cast(Y *);
+template 
+X *dyn_cast(Y *);
+template 
+X *dyn_cast_or_null(Y *);
+
+bool foo(Y *y, Z *z) {
+  if (auto x = cast(y))
+return true;
+  // CHECK-MESSAGES: :[[@LINE-2]]:16: warning: {{cast<> in conditional .*llvm-avoid-cast-in-conditional}}
+  // CHECK-FIXES: if (auto x = dyn_cast(y))
+
+  while (auto x = cast(y))
+break;
+  // CHECK-MESSAGES: :[[@LINE-2]]:19: warning:  {{cast<> in conditional .*llvm-avoid-cast-in-conditional}}
+  // CHECK-FIXES: while (auto x = dyn_cast(y))
+
+  if (cast(y))
+return true;
+  // CHECK-MESSAGES: :[[@LINE-2]]:7: warning:  {{cast<> in conditional .*llvm-avoid-cast-in-conditional}}
+  // CHECK-FIXES: if (isa(y))
+
+  while (cast(y))
+break;
+  // CHECK-MESSAGES: :[[@LINE-2]]:10: warning:  {{cast<> in conditional .*llvm-avoid-cast-in-conditional}}
+  // CHECK-FIXES: while (isa(y))
+
+  do {
+break;
+  } while (cast(y));
+  // CHECK-MESSAGES: :[[@LINE-1]]:12: warning:  {{cast<> in conditional .*llvm-avoid-cast-in-conditional}}
+  // CHECK-FIXES: while (isa(y));
+
+  if (dyn_cast(y))
+return true;
+  // CHECK-MESSAGES: :[[@LINE-2]]:7: warning:  {{.*dyn_cast<> not used .*llvm-avoid-cast-in-conditional}}
+  // CHECK-FIXES: if (isa(y))
+
+  while (dyn_cast(y))
+break;
+  // CHECK-MESSAGES: :[[@LINE-2]]:10: warning:  {{.*dyn_cast<> not used .*llvm-avoid-cast-in-conditional}}
+  // CHECK-FIXES: while (isa(y))
+
+  do {
+break;
+  } while (dyn_cast(y));
+  // CHECK-MESSAGES: :[[@LINE-1]]:12: warning:  {{.*dyn_cast<> not used .*llvm-avoid-cast-in-conditional}}
+  // CHECK-FIXES: while (isa(y));
+
+  if (z->bar() && isa(z->bar()))
+return true;
+  // CHECK-MESSAGES: :[[@LINE-2]]:7: warning:  {{method .* is called twice .*llvm-avoid-cast-in-conditional}}
+  // CHECK-FIXES: if (dyn_cast_or_null(z->bar()))
+
+  if (z->bar() && cast(z->bar()))
+return true;
+  // CHECK-MESSAGES: :[[@LINE-2]]:7: warning:  {{method .* is called twice .*llvm-avoid-cast-in-conditional}}
+  // CHECK-FIXES: if (dyn_cast_or_null(z->bar()))
+
+  if (z->bar() && dyn_cast(z->bar()))
+return true;
+  // CHECK-MESSAGES: :[[@LINE-2]]:7: warning:  {{method .* is called twice .*llvm-avoid-cast-in-conditional}}
+  // CHECK-FIXES: if (dyn_cast_or_null(z->bar()))
+
+  if (z->bar() && dyn_cast_or_null(z->bar()))
+return true;
+  // CHECK-MESSAGES: :[[@LINE-2]]:7: warning:  {{method .* is called twice .*llvm-avoid-cast-in-conditional}}
+  // CHECK-FIXES: if (dyn_cast_or_null(z->bar()))
+
+  bool b = z->bar() && cast(z->bar());
+  // CHECK-MESSAGES: :[[@LINE-1]]:12: warning:  {{method .* is called twice .*llvm-avoid-cast-in-conditional}}
+  // CHECK-FIXES: bool b = dyn_cast_or_null(z->bar());
+
+  // These don't trigger a warning.
+  if (auto x = cast(y)->foo())
+return true;
+  while (auto x = cast(y)->foo())
+break;
+  if (cast(y)->foo())
+return true;
+  while (cast(y)->foo())
+break;
+  if (y && isa(y))
+return true;
+  if (y && cast(z->bar()))
+return true;
+  if (z && cast(y)->foo())
+return true;
+  bool b2 = y && cast(z);
+
+#define CAST(T, Obj) cast(Obj)
+#define AUTO_VAR_CAST(X, Y, Z) auto X = cast(Z)
+#define ISA(T, Obj) isa(Obj)
+#define ISA_OR_NULL(T, Obj) Obj &(Obj)
+
+  if (auto x = CAST(X, y))
+return true;
+  if (AUTO_VAR_CAST(x, X, z))
+return true;
+  if (z->bar() && ISA(Y, z->bar()))
+return true;
+  if (ISA_OR_NULL(Y, z->bar()))
+return true;
+
+  return false;
+}
Index: clang-tools-extra/docs/clang-tidy/checks/llvm-avoid-cast-in-conditional.rst
===
--- /dev/null
+++ clang-tools-extra/docs/clang-tidy/checks/llvm-avoid-cast-in-conditional.rst
@@ -0,0 +1,28 @@
+.. title:: clang-tidy - llvm-avoid-cast-in-conditional
+

Re: r357323 - [analyzer] Introduce a simplified API for adding custom path notes.

2019-03-29 Thread Vitaly Buka via cfe-commits
Bot detects memory leak probably after this patch

http://lab.llvm.org:8011/builders/sanitizer-x86_64-linux-fast/builds/30957/steps/check-clang%20asan/logs/stdio



=
==22233==ERROR: LeakSanitizer: detected memory leaks

Direct leak of 1088 byte(s) in 17 object(s) allocated from:
#0 0xc770f8 in operator new(unsigned long)
/b/sanitizer-x86_64-linux-fast/build/llvm/projects/compiler-rt/lib/asan/asan_new_delete.cc:106
#1 0x9c6feef in __libcpp_allocate
/b/sanitizer-x86_64-linux-fast/build/libcxx_build_asan/include/c++/v1/new:238:10
#2 0x9c6feef in allocate
/b/sanitizer-x86_64-linux-fast/build/libcxx_build_asan/include/c++/v1/memory:1813
#3 0x9c6feef in __value_func<(lambda at
/b/sanitizer-x86_64-linux-fast/build/llvm/tools/clang/include/clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h:236:9),
std::__1::allocator<(lambda at
/b/sanitizer-x86_64-linux-fast/build/llvm/tools/clang/include/clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h:236:9)>
> /b/sanitizer-x86_64-linux-fast/build/libcxx_build_asan/include/c++/v1/functional:1716
#4 0x9c6feef in function<(lambda at
/b/sanitizer-x86_64-linux-fast/build/llvm/tools/clang/include/clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h:236:9),
void> 
/b/sanitizer-x86_64-linux-fast/build/libcxx_build_asan/include/c++/v1/functional:2290
#5 0x9c6feef in
clang::ento::CheckerContext::getNoteTag(std::__1::function, std::__1::allocator >
(clang::ento::BugReport&)>&&)
/b/sanitizer-x86_64-linux-fast/build/llvm/tools/clang/include/clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h:236
#6 0x9c6f061 in checkPostCall
/b/sanitizer-x86_64-linux-fast/build/llvm/tools/clang/lib/StaticAnalyzer/Checkers/MIGChecker.cpp:165:24
#7 0x9c6f061 in void
clang::ento::check::PostCall::_checkCall<(anonymous
namespace)::MIGChecker>(void*, clang::ento::CallEvent const&,
clang::ento::CheckerContext&)
/b/sanitizer-x86_64-linux-fast/build/llvm/tools/clang/include/clang/StaticAnalyzer/Core/Checker.h:183
#8 0x9fbd78c in operator()
/b/sanitizer-x86_64-linux-fast/build/llvm/tools/clang/include/clang/StaticAnalyzer/Core/CheckerManager.h:69:12
#9 0x9fbd78c in runChecker
/b/sanitizer-x86_64-linux-fast/build/llvm/tools/clang/lib/StaticAnalyzer/Core/CheckerManager.cpp:290
#10 0x9fbd78c in expandGraphWithCheckers<(anonymous
namespace)::CheckCallContext>
/b/sanitizer-x86_64-linux-fast/build/llvm/tools/clang/lib/StaticAnalyzer/Core/CheckerManager.cpp:138
#11 0x9fbd78c in
clang::ento::CheckerManager::runCheckersForCallEvent(bool,
clang::ento::ExplodedNodeSet&, clang::ento::ExplodedNodeSet const&,
clang::ento::CallEvent const&, clang::ento::ExprEngine&, bool)
/b/sanitizer-x86_64-linux-fast/build/llvm/tools/clang/lib/StaticAnalyzer/Core/CheckerManager.cpp:307
#12 0xa07d1ef in runCheckersForPostCall
/b/sanitizer-x86_64-linux-fast/build/llvm/tools/clang/include/clang/StaticAnalyzer/Core/CheckerManager.h:274:5
#13 0xa07d1ef in
clang::ento::ExprEngine::evalCall(clang::ento::ExplodedNodeSet&,
clang::ento::ExplodedNode*, clang::ento::CallEvent const&)
/b/sanitizer-x86_64-linux-fast/build/llvm/tools/clang/lib/StaticAnalyzer/Core/ExprEngineCallAndReturn.cpp:578
#14 0xa07c657 in
clang::ento::ExprEngine::VisitCallExpr(clang::CallExpr const*,
clang::ento::ExplodedNode*, clang::ento::ExplodedNodeSet&)
/b/sanitizer-x86_64-linux-fast/build/llvm/tools/clang/lib/StaticAnalyzer/Core/ExprEngineCallAndReturn.cpp:495:5
#15 0xa01249f in clang::ento::ExprEngine::Visit(clang::Stmt
const*, clang::ento::ExplodedNode*, clang::ento::ExplodedNodeSet&)
/b/sanitizer-x86_64-linux-fast/build/llvm/tools/clang/lib/StaticAnalyzer/Core/ExprEngine.cpp:1539:7
#16 0xa003888 in clang::ento::ExprEngine::ProcessStmt(clang::Stmt
const*, clang::ento::ExplodedNode*)
/b/sanitizer-x86_64-linux-fast/build/llvm/tools/clang/lib/StaticAnalyzer/Core/ExprEngine.cpp:743:5
#17 0xa002d48 in
clang::ento::ExprEngine::processCFGElement(clang::CFGElement,
clang::ento::ExplodedNode*, unsigned int,
clang::ento::NodeBuilderContext*)
/b/sanitizer-x86_64-linux-fast/build/llvm/tools/clang/lib/StaticAnalyzer/Core/ExprEngine.cpp:590:7
#18 0x9fdcdfe in
clang::ento::CoreEngine::HandlePostStmt(clang::CFGBlock const*,
unsigned int, clang::ento::ExplodedNode*)
/b/sanitizer-x86_64-linux-fast/build/llvm/tools/clang/lib/StaticAnalyzer/Core/CoreEngine.cpp:438:12
#19 0x9fdaa85 in
clang::ento::CoreEngine::dispatchWorkItem(clang::ento::ExplodedNode*,
clang::ProgramPoint, clang::ento::WorkListUnit const&)
/b/sanitizer-x86_64-linux-fast/build/llvm/tools/clang/lib/StaticAnalyzer/Core/CoreEngine.cpp:192:7
#20 0x9fd9941 in
clang::ento::CoreEngine::ExecuteWorkList(clang::LocationContext
const*, unsigned int,
llvm::IntrusiveRefCntPtr)
/b/sanitizer-x86_64-linux-fast/build/llvm/tools/clang/lib/StaticAnalyzer/Core/CoreEngine.cpp:148:5
#21 0x987ae4f in ExecuteWorkList

[PATCH] D59806: [clang-tidy] Add a check for [super self] in initializers 

2019-03-29 Thread Stephane Moore via Phabricator via cfe-commits
stephanemoore updated this revision to Diff 192938.
stephanemoore added a comment.

Add test cases with `[super self]` expanded from macros.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D59806

Files:
  clang-tools-extra/clang-tidy/objc/CMakeLists.txt
  clang-tools-extra/clang-tidy/objc/ObjCTidyModule.cpp
  clang-tools-extra/clang-tidy/objc/SuperSelfCheck.cpp
  clang-tools-extra/clang-tidy/objc/SuperSelfCheck.h
  clang-tools-extra/docs/ReleaseNotes.rst
  clang-tools-extra/docs/clang-tidy/checks/list.rst
  clang-tools-extra/docs/clang-tidy/checks/objc-super-self.rst
  clang-tools-extra/test/clang-tidy/objc-super-self.m

Index: clang-tools-extra/test/clang-tidy/objc-super-self.m
===
--- /dev/null
+++ clang-tools-extra/test/clang-tidy/objc-super-self.m
@@ -0,0 +1,69 @@
+// RUN: %check_clang_tidy %s objc-super-self %t
+
+@interface NSObject
+- (instancetype)init;
+- (instancetype)self;
+@end
+
+@interface NSObjectDerivedClass : NSObject
+@end
+
+@implementation NSObjectDerivedClass
+
+- (instancetype)init {
+  return [super self];
+// CHECK-MESSAGES: :[[@LINE-1]]:10: warning: suspicious invocation of 'self' in initializer; did you mean to invoke a superclass initializer? [objc-super-self]
+// CHECK-FIXES: return [super init];
+}
+
+- (instancetype)initWithObject:(NSObject *)obj {
+  self = [super self];
+// CHECK-MESSAGES: :[[@LINE-1]]:10: warning: suspicious invocation of 'self' in initializer; did you mean to invoke a superclass initializer? [objc-super-self]
+// CHECK-FIXES: self = [super init];
+  if (self) {
+// ...
+  }
+  return self;
+}
+
+#define INITIALIZE() [super self]
+
+- (instancetype)initWithObject:(NSObject *)objc a:(int)a {
+  return INITIALIZE();
+// CHECK-MESSAGES: :[[@LINE-1]]:10: warning: suspicious invocation of 'self' in initializer; did you mean to invoke a superclass initializer? [objc-super-self]
+// CHECK-FIXES: return [super init];
+}
+
+#define INITIALIZER_IMPL() return [super self]
+
+- (instancetype)initWithObject:(NSObject *)objc b:(int)b {
+  INITIALIZER_IMPL();
+// CHECK-MESSAGES: :[[@LINE-1]]:3: warning: suspicious invocation of 'self' in initializer; did you mean to invoke a superclass initializer? [objc-super-self]
+}
+
+- (instancetype)foo {
+  return [super self];
+}
+
+- (instancetype)bar {
+  return [self self];
+}
+
+@end
+
+@interface RootClass
+- (instancetype)init;
+- (instancetype)self;
+@end
+
+@interface NotNSObjectDerivedClass : RootClass
+@end
+
+@implementation NotNSObjectDerivedClass
+
+- (instancetype)init {
+  return [super self];
+}
+
+@end
+
Index: clang-tools-extra/docs/clang-tidy/checks/objc-super-self.rst
===
--- /dev/null
+++ clang-tools-extra/docs/clang-tidy/checks/objc-super-self.rst
@@ -0,0 +1,13 @@
+.. title:: clang-tidy - objc-super-self
+
+objc-super-self
+===
+
+Finds invocations of ``-self`` on super instances in initializers of subclasses
+of ``NSObject`` and recommends calling a superclass initializer instead.
+
+Invoking ``-self`` on super instances in initializers is a common programmer
+error when the programmer's original intent is to call a superclass
+initializer. Failing to call a superclass initializer breaks initializer
+chaining and can result in invalid object initialization.
+
Index: clang-tools-extra/docs/clang-tidy/checks/list.rst
===
--- clang-tools-extra/docs/clang-tidy/checks/list.rst
+++ clang-tools-extra/docs/clang-tidy/checks/list.rst
@@ -227,6 +227,7 @@
objc-avoid-spinlock
objc-forbidden-subclassing
objc-property-declaration
+   objc-super-self
openmp-exception-escape
openmp-use-default-none
performance-faster-string-find
Index: clang-tools-extra/docs/ReleaseNotes.rst
===
--- clang-tools-extra/docs/ReleaseNotes.rst
+++ clang-tools-extra/docs/ReleaseNotes.rst
@@ -108,6 +108,12 @@
   Checks whether there are underscores in googletest test and test case names in
   test macros, which is prohibited by the Googletest FAQ.
 
+- New :doc:`objc-super-self ` check.
+
+  Finds invocations of ``-self`` on super instances in initializers of
+  subclasses of ``NSObject`` and recommends calling a superclass initializer
+  instead.
+
 - New alias :doc:`cppcoreguidelines-explicit-virtual-functions
   ` to
   :doc:`modernize-use-override
Index: clang-tools-extra/clang-tidy/objc/SuperSelfCheck.h
===
--- /dev/null
+++ clang-tools-extra/clang-tidy/objc/SuperSelfCheck.h
@@ -0,0 +1,36 @@
+//===--- SuperSelfCheck.h - clang-tidy --*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open 

[PATCH] D58367: [analyzer] NFC: Improve upon the concept of BugReporterVisitor.

2019-03-29 Thread Artem Dergachev via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG4d6fb5789fca: Revert [analyzer] Introduce a simplified 
API for adding custom path notes. (authored by dergachev.a).

Changed prior to commit:
  https://reviews.llvm.org/D58367?vs=192932=192937#toc

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D58367

Files:
  clang/include/clang/Analysis/ProgramPoint.h
  clang/include/clang/StaticAnalyzer/Core/BugReporter/BugReporter.h
  clang/include/clang/StaticAnalyzer/Core/BugReporter/BugReporterVisitors.h
  clang/include/clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h
  clang/include/clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h
  clang/lib/StaticAnalyzer/Checkers/MIGChecker.cpp
  clang/lib/StaticAnalyzer/Core/BugReporter.cpp
  clang/lib/StaticAnalyzer/Core/BugReporterVisitors.cpp
  clang/lib/StaticAnalyzer/Core/ExprEngine.cpp
  clang/test/Analysis/mig.mm

Index: clang/test/Analysis/mig.mm
===
--- clang/test/Analysis/mig.mm
+++ clang/test/Analysis/mig.mm
@@ -91,14 +91,6 @@
  // expected-note@-1{{MIG callback fails with error after deallocating argument value. This is a use-after-free vulnerability because the caller will try to deallocate it again}}
 }
 
-MIG_SERVER_ROUTINE
-kern_return_t no_unrelated_notes(mach_port_name_t port, vm_address_t address, vm_size_t size) {
-  vm_deallocate(port, address, size); // no-note
-  1 / 0; // expected-warning{{Division by zero}}
- // expected-note@-1{{Division by zero}}
-  return KERN_SUCCESS;
-}
-
 // Make sure we find the bug when the object is destroyed within an
 // automatic destructor.
 MIG_SERVER_ROUTINE
Index: clang/lib/StaticAnalyzer/Core/ExprEngine.cpp
===
--- clang/lib/StaticAnalyzer/Core/ExprEngine.cpp
+++ clang/lib/StaticAnalyzer/Core/ExprEngine.cpp
@@ -201,9 +201,7 @@
   svalBuilder(StateMgr.getSValBuilder()),
   ObjCNoRet(mgr.getASTContext()),
   BR(mgr, *this),
-  VisitedCallees(VisitedCalleesIn),
-  HowToInline(HowToInlineIn),
-  NoteTags(G.getAllocator()) {
+  VisitedCallees(VisitedCalleesIn), HowToInline(HowToInlineIn) {
   unsigned TrimInterval = mgr.options.GraphTrimInterval;
   if (TrimInterval != 0) {
 // Enable eager node reclamation when constructing the ExplodedGraph.
Index: clang/lib/StaticAnalyzer/Core/BugReporterVisitors.cpp
===
--- clang/lib/StaticAnalyzer/Core/BugReporterVisitors.cpp
+++ clang/lib/StaticAnalyzer/Core/BugReporterVisitors.cpp
@@ -2472,30 +2472,6 @@
   return nullptr;
 }
 
-int NoteTag::Kind = 0;
-
-void TagVisitor::Profile(llvm::FoldingSetNodeID ) const {
-  static int Tag = 0;
-  ID.AddPointer();
-}
-
-std::shared_ptr
-TagVisitor::VisitNode(const ExplodedNode *N, BugReporterContext ,
-  BugReport ) {
-  ProgramPoint PP = N->getLocation();
-  const NoteTag *T = dyn_cast_or_null(PP.getTag());
-  if (!T)
-return nullptr;
-
-  if (Optional Msg = T->generateMessage(BRC, R)) {
-PathDiagnosticLocation Loc =
-PathDiagnosticLocation::create(PP, BRC.getSourceManager());
-return std::make_shared(Loc, *Msg);
-  }
-
-  return nullptr;
-}
-
 void FalsePositiveRefutationBRVisitor::Profile(
 llvm::FoldingSetNodeID ) const {
   static int Tag = 0;
Index: clang/lib/StaticAnalyzer/Core/BugReporter.cpp
===
--- clang/lib/StaticAnalyzer/Core/BugReporter.cpp
+++ clang/lib/StaticAnalyzer/Core/BugReporter.cpp
@@ -2612,7 +2612,6 @@
 R->addVisitor(llvm::make_unique());
 R->addVisitor(llvm::make_unique());
 R->addVisitor(llvm::make_unique());
-R->addVisitor(llvm::make_unique());
 
 BugReporterContext BRC(Reporter, ErrorGraph.BackMap);
 
Index: clang/lib/StaticAnalyzer/Checkers/MIGChecker.cpp
===
--- clang/lib/StaticAnalyzer/Checkers/MIGChecker.cpp
+++ clang/lib/StaticAnalyzer/Checkers/MIGChecker.cpp
@@ -80,10 +80,43 @@
 checkReturnAux(RS, C);
   }
 
+  class Visitor : public BugReporterVisitor {
+  public:
+void Profile(llvm::FoldingSetNodeID ) const {
+  static int X = 0;
+  ID.AddPointer();
+}
+
+std::shared_ptr VisitNode(const ExplodedNode *N,
+BugReporterContext , BugReport );
+  };
 };
 } // end anonymous namespace
 
-REGISTER_TRAIT_WITH_PROGRAMSTATE(ReleasedParameter, bool)
+// FIXME: It's a 'const ParmVarDecl *' but there's no ready-made GDM traits
+// specialization for this sort of types.
+REGISTER_TRAIT_WITH_PROGRAMSTATE(ReleasedParameter, const void *)
+
+std::shared_ptr
+MIGChecker::Visitor::VisitNode(const ExplodedNode *N, BugReporterContext ,
+   BugReport ) {
+  const auto *NewPVD = static_cast(
+  

[PATCH] D58367: [analyzer] NFC: Improve upon the concept of BugReporterVisitor.

2019-03-29 Thread Artem Dergachev via Phabricator via cfe-commits
NoQ reopened this revision.
NoQ marked an inline comment as done.
NoQ added a comment.
This revision is now accepted and ready to land.

Reverted in rC357332 !

http://lab.llvm.org:8011/builders/sanitizer-x86_64-linux-fast/builds/30957/steps/check-clang%20asan/logs/stdio

  =
  ==22233==ERROR: LeakSanitizer: detected memory leaks
  
  Direct leak of 1088 byte(s) in 17 object(s) allocated from:
  #0 0xc770f8 in operator new(unsigned long) 
/b/sanitizer-x86_64-linux-fast/build/llvm/projects/compiler-rt/lib/asan/asan_new_delete.cc:106
  #1 0x9c6feef in __libcpp_allocate 
/b/sanitizer-x86_64-linux-fast/build/libcxx_build_asan/include/c++/v1/new:238:10
  #2 0x9c6feef in allocate 
/b/sanitizer-x86_64-linux-fast/build/libcxx_build_asan/include/c++/v1/memory:1813
  #3 0x9c6feef in __value_func<(lambda at 
/b/sanitizer-x86_64-linux-fast/build/llvm/tools/clang/include/clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h:236:9),
 std::__1::allocator<(lambda at 
/b/sanitizer-x86_64-linux-fast/build/llvm/tools/clang/include/clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h:236:9)>
 > 
/b/sanitizer-x86_64-linux-fast/build/libcxx_build_asan/include/c++/v1/functional:1716
  #4 0x9c6feef in function<(lambda at 
/b/sanitizer-x86_64-linux-fast/build/llvm/tools/clang/include/clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h:236:9),
 void> 
/b/sanitizer-x86_64-linux-fast/build/libcxx_build_asan/include/c++/v1/functional:2290
  #5 0x9c6feef in 
clang::ento::CheckerContext::getNoteTag(std::__1::function, std::__1::allocator > 
(clang::ento::BugReport&)>&&) 
/b/sanitizer-x86_64-linux-fast/build/llvm/tools/clang/include/clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h:236
  #6 0x9c6f061 in checkPostCall 
/b/sanitizer-x86_64-linux-fast/build/llvm/tools/clang/lib/StaticAnalyzer/Checkers/MIGChecker.cpp:165:24
  #7 0x9c6f061 in void clang::ento::check::PostCall::_checkCall<(anonymous 
namespace)::MIGChecker>(void*, clang::ento::CallEvent const&, 
clang::ento::CheckerContext&) 
/b/sanitizer-x86_64-linux-fast/build/llvm/tools/clang/include/clang/StaticAnalyzer/Core/Checker.h:183
  #8 0x9fbd78c in operator() 
/b/sanitizer-x86_64-linux-fast/build/llvm/tools/clang/include/clang/StaticAnalyzer/Core/CheckerManager.h:69:12
  #9 0x9fbd78c in runChecker 
/b/sanitizer-x86_64-linux-fast/build/llvm/tools/clang/lib/StaticAnalyzer/Core/CheckerManager.cpp:290
  #10 0x9fbd78c in expandGraphWithCheckers<(anonymous 
namespace)::CheckCallContext> 
/b/sanitizer-x86_64-linux-fast/build/llvm/tools/clang/lib/StaticAnalyzer/Core/CheckerManager.cpp:138
  #11 0x9fbd78c in 
clang::ento::CheckerManager::runCheckersForCallEvent(bool, 
clang::ento::ExplodedNodeSet&, clang::ento::ExplodedNodeSet const&, 
clang::ento::CallEvent const&, clang::ento::ExprEngine&, bool) 
/b/sanitizer-x86_64-linux-fast/build/llvm/tools/clang/lib/StaticAnalyzer/Core/CheckerManager.cpp:307
  #12 0xa07d1ef in runCheckersForPostCall 
/b/sanitizer-x86_64-linux-fast/build/llvm/tools/clang/include/clang/StaticAnalyzer/Core/CheckerManager.h:274:5
  #13 0xa07d1ef in 
clang::ento::ExprEngine::evalCall(clang::ento::ExplodedNodeSet&, 
clang::ento::ExplodedNode*, clang::ento::CallEvent const&) 
/b/sanitizer-x86_64-linux-fast/build/llvm/tools/clang/lib/StaticAnalyzer/Core/ExprEngineCallAndReturn.cpp:578
  #14 0xa07c657 in clang::ento::ExprEngine::VisitCallExpr(clang::CallExpr 
const*, clang::ento::ExplodedNode*, clang::ento::ExplodedNodeSet&) 
/b/sanitizer-x86_64-linux-fast/build/llvm/tools/clang/lib/StaticAnalyzer/Core/ExprEngineCallAndReturn.cpp:495:5
  #15 0xa01249f in clang::ento::ExprEngine::Visit(clang::Stmt const*, 
clang::ento::ExplodedNode*, clang::ento::ExplodedNodeSet&) 
/b/sanitizer-x86_64-linux-fast/build/llvm/tools/clang/lib/StaticAnalyzer/Core/ExprEngine.cpp:1539:7
  #16 0xa003888 in clang::ento::ExprEngine::ProcessStmt(clang::Stmt const*, 
clang::ento::ExplodedNode*) 
/b/sanitizer-x86_64-linux-fast/build/llvm/tools/clang/lib/StaticAnalyzer/Core/ExprEngine.cpp:743:5
  #17 0xa002d48 in 
clang::ento::ExprEngine::processCFGElement(clang::CFGElement, 
clang::ento::ExplodedNode*, unsigned int, clang::ento::NodeBuilderContext*) 
/b/sanitizer-x86_64-linux-fast/build/llvm/tools/clang/lib/StaticAnalyzer/Core/ExprEngine.cpp:590:7
  #18 0x9fdcdfe in clang::ento::CoreEngine::HandlePostStmt(clang::CFGBlock 
const*, unsigned int, clang::ento::ExplodedNode*) 
/b/sanitizer-x86_64-linux-fast/build/llvm/tools/clang/lib/StaticAnalyzer/Core/CoreEngine.cpp:438:12
  #19 0x9fdaa85 in 
clang::ento::CoreEngine::dispatchWorkItem(clang::ento::ExplodedNode*, 
clang::ProgramPoint, clang::ento::WorkListUnit const&) 
/b/sanitizer-x86_64-linux-fast/build/llvm/tools/clang/lib/StaticAnalyzer/Core/CoreEngine.cpp:192:7
  #20 0x9fd9941 in 
clang::ento::CoreEngine::ExecuteWorkList(clang::LocationContext const*, 

r357332 - Revert "[analyzer] Introduce a simplified API for adding custom path notes."

2019-03-29 Thread Artem Dergachev via cfe-commits
Author: dergachev
Date: Fri Mar 29 16:11:10 2019
New Revision: 357332

URL: http://llvm.org/viewvc/llvm-project?rev=357332=rev
Log:
Revert "[analyzer] Introduce a simplified API for adding custom path notes."

This reverts commit r357323.

ASan leaks found by a buildbot :)

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

Modified:
cfe/trunk/include/clang/Analysis/ProgramPoint.h
cfe/trunk/include/clang/StaticAnalyzer/Core/BugReporter/BugReporter.h

cfe/trunk/include/clang/StaticAnalyzer/Core/BugReporter/BugReporterVisitors.h
cfe/trunk/include/clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h
cfe/trunk/include/clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h
cfe/trunk/lib/StaticAnalyzer/Checkers/MIGChecker.cpp
cfe/trunk/lib/StaticAnalyzer/Core/BugReporter.cpp
cfe/trunk/lib/StaticAnalyzer/Core/BugReporterVisitors.cpp
cfe/trunk/lib/StaticAnalyzer/Core/ExprEngine.cpp
cfe/trunk/test/Analysis/mig.mm

Modified: cfe/trunk/include/clang/Analysis/ProgramPoint.h
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Analysis/ProgramPoint.h?rev=357332=357331=357332=diff
==
--- cfe/trunk/include/clang/Analysis/ProgramPoint.h (original)
+++ cfe/trunk/include/clang/Analysis/ProgramPoint.h Fri Mar 29 16:11:10 2019
@@ -42,11 +42,12 @@ public:
   virtual ~ProgramPointTag();
   virtual StringRef getTagDescription() const = 0;
 
+protected:
   /// Used to implement 'isKind' in subclasses.
-  const void *getTagKind() const { return TagKind; }
+  const void *getTagKind() { return TagKind; }
 
 private:
-  const void *const TagKind;
+  const void *TagKind;
 };
 
 class SimpleProgramPointTag : public ProgramPointTag {

Modified: cfe/trunk/include/clang/StaticAnalyzer/Core/BugReporter/BugReporter.h
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/StaticAnalyzer/Core/BugReporter/BugReporter.h?rev=357332=357331=357332=diff
==
--- cfe/trunk/include/clang/StaticAnalyzer/Core/BugReporter/BugReporter.h 
(original)
+++ cfe/trunk/include/clang/StaticAnalyzer/Core/BugReporter/BugReporter.h Fri 
Mar 29 16:11:10 2019
@@ -592,60 +592,6 @@ public:
   NodeMapClosure& getNodeResolver() { return NMC; }
 };
 
-
-/// The tag upon which the TagVisitor reacts. Add these in order to display
-/// additional PathDiagnosticEventPieces along the path.
-class NoteTag : public ProgramPointTag {
-public:
-  using Callback =
-  std::function;
-
-private:
-  static int Kind;
-
-  const Callback Cb;
-
-  NoteTag(Callback &) : ProgramPointTag(), Cb(std::move(Cb)) {}
-
-public:
-  static bool classof(const ProgramPointTag *T) {
-return T->getTagKind() == 
-  }
-
-  Optional generateMessage(BugReporterContext ,
-BugReport ) const {
-std::string Msg = Cb(BRC, R);
-if (Msg.empty())
-  return None;
-
-return std::move(Msg);
-  }
-
-  StringRef getTagDescription() const override {
-// TODO: Remember a few examples of generated messages
-// and display them in the ExplodedGraph dump by
-// returning them from this function.
-return "Note Tag";
-  }
-
-  // Manage memory for NoteTag objects.
-  class Factory {
-llvm::BumpPtrAllocator 
-
-  public:
-Factory(llvm::BumpPtrAllocator ) : Alloc(Alloc) {}
-
-const NoteTag *makeNoteTag(Callback &) {
-  // We cannot use make_unique because we cannot access the private
-  // constructor from inside it.
-  NoteTag *Tag = Alloc.Allocate();
-  return new (Tag) NoteTag(std::move(Cb));
-}
-  };
-
-  friend class TagVisitor;
-};
-
 } // namespace ento
 
 } // namespace clang

Modified: 
cfe/trunk/include/clang/StaticAnalyzer/Core/BugReporter/BugReporterVisitors.h
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/StaticAnalyzer/Core/BugReporter/BugReporterVisitors.h?rev=357332=357331=357332=diff
==
--- 
cfe/trunk/include/clang/StaticAnalyzer/Core/BugReporter/BugReporterVisitors.h 
(original)
+++ 
cfe/trunk/include/clang/StaticAnalyzer/Core/BugReporter/BugReporterVisitors.h 
Fri Mar 29 16:11:10 2019
@@ -14,7 +14,6 @@
 #ifndef LLVM_CLANG_STATICANALYZER_CORE_BUGREPORTER_BUGREPORTERVISITORS_H
 #define LLVM_CLANG_STATICANALYZER_CORE_BUGREPORTER_BUGREPORTERVISITORS_H
 
-#include "clang/Analysis/ProgramPoint.h"
 #include "clang/Basic/LLVM.h"
 #include "clang/StaticAnalyzer/Core/PathSensitive/RangedConstraintManager.h"
 #include "clang/StaticAnalyzer/Core/PathSensitive/SVals.h"
@@ -329,17 +328,6 @@ public:
BugReport ) override;
 };
 
-
-/// The visitor detects NoteTags and displays the event notes they contain.
-class TagVisitor : public BugReporterVisitor {
-public:
-  void Profile(llvm::FoldingSetNodeID ) const override;
-
-  std::shared_ptr VisitNode(const ExplodedNode *N,
-  

[PATCH] D59901: [analyzer] PR41239: Fix a crash on invalid source location in NoStoreFuncVisitor.

2019-03-29 Thread Phabricator via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rL357329: [analyzer] PR41239: Fix a crash on invalid source 
location in… (authored by dergachev, committed by ).
Herald added a project: LLVM.
Herald added a subscriber: llvm-commits.

Changed prior to commit:
  https://reviews.llvm.org/D59901?vs=192512=192935#toc

Repository:
  rL LLVM

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

https://reviews.llvm.org/D59901

Files:
  cfe/trunk/lib/StaticAnalyzer/Core/BugReporterVisitors.cpp
  cfe/trunk/test/Analysis/diagnostics/no-store-func-path-notes.c


Index: cfe/trunk/test/Analysis/diagnostics/no-store-func-path-notes.c
===
--- cfe/trunk/test/Analysis/diagnostics/no-store-func-path-notes.c
+++ cfe/trunk/test/Analysis/diagnostics/no-store-func-path-notes.c
@@ -1,4 +1,5 @@
-// RUN: %clang_analyze_cc1 -x c -analyzer-checker=core -analyzer-output=text 
-verify %s
+// RUN: %clang_analyze_cc1 -w -x c -analyzer-checker=core 
-analyzer-output=text\
+// RUN: -verify %s
 
 typedef __typeof(sizeof(int)) size_t;
 void *memset(void *__s, int __c, size_t __n);
@@ -244,3 +245,12 @@
   return z; // expected-warning{{Undefined or garbage value returned to 
caller}}
 // expected-note@-1{{Undefined or garbage value returned to 
caller}}
 }
+
+void test_implicit_function_decl(int *x) {
+  if (x) {} // expected-note{{Assuming 'x' is null}}
+// expected-note@-1{{Taking false branch}}
+  implicit_function(x);
+  *x = 4; // expected-warning{{Dereference of null pointer (loaded from 
variable 'x')}}
+  // expected-note@-1{{Dereference of null pointer (loaded from 
variable 'x')}}
+}
+int implicit_function(int *y) {}
Index: cfe/trunk/lib/StaticAnalyzer/Core/BugReporterVisitors.cpp
===
--- cfe/trunk/lib/StaticAnalyzer/Core/BugReporterVisitors.cpp
+++ cfe/trunk/lib/StaticAnalyzer/Core/BugReporterVisitors.cpp
@@ -322,7 +322,7 @@
 CallEventRef<> Call =
 BR.getStateManager().getCallEventManager().getCaller(SCtx, State);
 
-if (SM.isInSystemHeader(Call->getDecl()->getSourceRange().getBegin()))
+if (Call->isInSystemHeader())
   return nullptr;
 
 // Region of interest corresponds to an IVar, exiting a method


Index: cfe/trunk/test/Analysis/diagnostics/no-store-func-path-notes.c
===
--- cfe/trunk/test/Analysis/diagnostics/no-store-func-path-notes.c
+++ cfe/trunk/test/Analysis/diagnostics/no-store-func-path-notes.c
@@ -1,4 +1,5 @@
-// RUN: %clang_analyze_cc1 -x c -analyzer-checker=core -analyzer-output=text -verify %s
+// RUN: %clang_analyze_cc1 -w -x c -analyzer-checker=core -analyzer-output=text\
+// RUN: -verify %s
 
 typedef __typeof(sizeof(int)) size_t;
 void *memset(void *__s, int __c, size_t __n);
@@ -244,3 +245,12 @@
   return z; // expected-warning{{Undefined or garbage value returned to caller}}
 // expected-note@-1{{Undefined or garbage value returned to caller}}
 }
+
+void test_implicit_function_decl(int *x) {
+  if (x) {} // expected-note{{Assuming 'x' is null}}
+// expected-note@-1{{Taking false branch}}
+  implicit_function(x);
+  *x = 4; // expected-warning{{Dereference of null pointer (loaded from variable 'x')}}
+  // expected-note@-1{{Dereference of null pointer (loaded from variable 'x')}}
+}
+int implicit_function(int *y) {}
Index: cfe/trunk/lib/StaticAnalyzer/Core/BugReporterVisitors.cpp
===
--- cfe/trunk/lib/StaticAnalyzer/Core/BugReporterVisitors.cpp
+++ cfe/trunk/lib/StaticAnalyzer/Core/BugReporterVisitors.cpp
@@ -322,7 +322,7 @@
 CallEventRef<> Call =
 BR.getStateManager().getCallEventManager().getCaller(SCtx, State);
 
-if (SM.isInSystemHeader(Call->getDecl()->getSourceRange().getBegin()))
+if (Call->isInSystemHeader())
   return nullptr;
 
 // Region of interest corresponds to an IVar, exiting a method
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


r357329 - [analyzer] PR41239: Fix a crash on invalid source location in NoStoreFuncVisitor.

2019-03-29 Thread Artem Dergachev via cfe-commits
Author: dergachev
Date: Fri Mar 29 15:57:49 2019
New Revision: 357329

URL: http://llvm.org/viewvc/llvm-project?rev=357329=rev
Log:
[analyzer] PR41239: Fix a crash on invalid source location in 
NoStoreFuncVisitor.

It turns out that SourceManager::isInSystemHeader() crashes when an invalid
source location is passed into it. Invalid source locations are relatively
common: not only they come from body farms, but also, say, any function in C
that didn't come with a forward declaration would have an implicit
forward declaration with invalid source locations.

There's a more comfy API for us to use in the Static Analyzer:
CallEvent::isInSystemHeader(), so just use that.

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

Modified:
cfe/trunk/lib/StaticAnalyzer/Core/BugReporterVisitors.cpp
cfe/trunk/test/Analysis/diagnostics/no-store-func-path-notes.c

Modified: cfe/trunk/lib/StaticAnalyzer/Core/BugReporterVisitors.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/StaticAnalyzer/Core/BugReporterVisitors.cpp?rev=357329=357328=357329=diff
==
--- cfe/trunk/lib/StaticAnalyzer/Core/BugReporterVisitors.cpp (original)
+++ cfe/trunk/lib/StaticAnalyzer/Core/BugReporterVisitors.cpp Fri Mar 29 
15:57:49 2019
@@ -322,7 +322,7 @@ public:
 CallEventRef<> Call =
 BR.getStateManager().getCallEventManager().getCaller(SCtx, State);
 
-if (SM.isInSystemHeader(Call->getDecl()->getSourceRange().getBegin()))
+if (Call->isInSystemHeader())
   return nullptr;
 
 // Region of interest corresponds to an IVar, exiting a method

Modified: cfe/trunk/test/Analysis/diagnostics/no-store-func-path-notes.c
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/Analysis/diagnostics/no-store-func-path-notes.c?rev=357329=357328=357329=diff
==
--- cfe/trunk/test/Analysis/diagnostics/no-store-func-path-notes.c (original)
+++ cfe/trunk/test/Analysis/diagnostics/no-store-func-path-notes.c Fri Mar 29 
15:57:49 2019
@@ -1,4 +1,5 @@
-// RUN: %clang_analyze_cc1 -x c -analyzer-checker=core -analyzer-output=text 
-verify %s
+// RUN: %clang_analyze_cc1 -w -x c -analyzer-checker=core 
-analyzer-output=text\
+// RUN: -verify %s
 
 typedef __typeof(sizeof(int)) size_t;
 void *memset(void *__s, int __c, size_t __n);
@@ -244,3 +245,12 @@ int useInitializeMaybeInStruct() {
   return z; // expected-warning{{Undefined or garbage value returned to 
caller}}
 // expected-note@-1{{Undefined or garbage value returned to 
caller}}
 }
+
+void test_implicit_function_decl(int *x) {
+  if (x) {} // expected-note{{Assuming 'x' is null}}
+// expected-note@-1{{Taking false branch}}
+  implicit_function(x);
+  *x = 4; // expected-warning{{Dereference of null pointer (loaded from 
variable 'x')}}
+  // expected-note@-1{{Dereference of null pointer (loaded from 
variable 'x')}}
+}
+int implicit_function(int *y) {}


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


[PATCH] D59901: [analyzer] PR41239: Fix a crash on invalid source location in NoStoreFuncVisitor.

2019-03-29 Thread Artem Dergachev via Phabricator via cfe-commits
NoQ added a comment.

This other example seems to work and looks relatively similar, just with a 
different checker causing the visitor to be attached.


Repository:
  rC Clang

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

https://reviews.llvm.org/D59901



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


[PATCH] D59861: [analyzer] NFC: Replace Taint API with a usual inter-checker communication API?

2019-03-29 Thread Phabricator via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rC357326: [analyzer] Move taint API from ProgramState to a 
separate header. NFC. (authored by dergachev, committed by ).

Changed prior to commit:
  https://reviews.llvm.org/D59861?vs=192919=192934#toc

Repository:
  rC Clang

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

https://reviews.llvm.org/D59861

Files:
  include/clang/StaticAnalyzer/Core/BugReporter/BugReporterVisitors.h
  include/clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h
  include/clang/StaticAnalyzer/Core/PathSensitive/TaintManager.h
  include/clang/StaticAnalyzer/Core/PathSensitive/TaintTag.h
  lib/StaticAnalyzer/Checkers/ArrayBoundCheckerV2.cpp
  lib/StaticAnalyzer/Checkers/CMakeLists.txt
  lib/StaticAnalyzer/Checkers/DivZeroChecker.cpp
  lib/StaticAnalyzer/Checkers/GenericTaintChecker.cpp
  lib/StaticAnalyzer/Checkers/Taint.cpp
  lib/StaticAnalyzer/Checkers/Taint.h
  lib/StaticAnalyzer/Checkers/TaintTesterChecker.cpp
  lib/StaticAnalyzer/Checkers/VLASizeChecker.cpp
  lib/StaticAnalyzer/Core/BugReporterVisitors.cpp
  lib/StaticAnalyzer/Core/CMakeLists.txt
  lib/StaticAnalyzer/Core/ProgramState.cpp
  lib/StaticAnalyzer/Core/TaintManager.cpp
  test/Analysis/taint-dumps.c

Index: lib/StaticAnalyzer/Core/BugReporterVisitors.cpp
===
--- lib/StaticAnalyzer/Core/BugReporterVisitors.cpp
+++ lib/StaticAnalyzer/Core/BugReporterVisitors.cpp
@@ -2412,26 +2412,6 @@
   return std::move(Piece);
 }
 
-std::shared_ptr
-TaintBugVisitor::VisitNode(const ExplodedNode *N,
-   BugReporterContext , BugReport &) {
-
-  // Find the ExplodedNode where the taint was first introduced
-  if (!N->getState()->isTainted(V) || N->getFirstPred()->getState()->isTainted(V))
-return nullptr;
-
-  const Stmt *S = PathDiagnosticLocation::getStmt(N);
-  if (!S)
-return nullptr;
-
-  const LocationContext *NCtx = N->getLocationContext();
-  PathDiagnosticLocation L =
-  PathDiagnosticLocation::createBegin(S, BRC.getSourceManager(), NCtx);
-  if (!L.isValid() || !L.asLocation().isValid())
-return nullptr;
-
-  return std::make_shared(L, "Taint originated here");
-}
 
 FalsePositiveRefutationBRVisitor::FalsePositiveRefutationBRVisitor()
 : Constraints(ConstraintRangeTy::Factory().getEmptyMap()) {}
Index: lib/StaticAnalyzer/Core/CMakeLists.txt
===
--- lib/StaticAnalyzer/Core/CMakeLists.txt
+++ lib/StaticAnalyzer/Core/CMakeLists.txt
@@ -45,7 +45,6 @@
   SValBuilder.cpp
   SVals.cpp
   SymbolManager.cpp
-  TaintManager.cpp
   WorkList.cpp
 
   LINK_LIBS
Index: lib/StaticAnalyzer/Core/ProgramState.cpp
===
--- lib/StaticAnalyzer/Core/ProgramState.cpp
+++ lib/StaticAnalyzer/Core/ProgramState.cpp
@@ -16,7 +16,6 @@
 #include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h"
 #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramStateTrait.h"
 #include "clang/StaticAnalyzer/Core/PathSensitive/SubEngine.h"
-#include "clang/StaticAnalyzer/Core/PathSensitive/TaintManager.h"
 #include "clang/StaticAnalyzer/Core/PathSensitive/DynamicTypeMap.h"
 #include "llvm/Support/raw_ostream.h"
 
@@ -458,9 +457,6 @@
   // Print out the tracked dynamic types.
   printDynamicTypeInfo(this, Out, NL, Sep);
 
-  // Print out tainted symbols.
-  printTaint(Out, NL);
-
   // Print checker-specific data.
   Mgr.getOwningEngine().printState(Out, this, NL, Sep, LC);
 }
@@ -474,22 +470,6 @@
   print(llvm::errs());
 }
 
-void ProgramState::printTaint(raw_ostream ,
-  const char *NL) const {
-  TaintMapImpl TM = get();
-
-  if (!TM.isEmpty())
-Out <<"Tainted symbols:" << NL;
-
-  for (TaintMapImpl::iterator I = TM.begin(), E = TM.end(); I != E; ++I) {
-Out << I->first << " : " << I->second << NL;
-  }
-}
-
-void ProgramState::dumpTaint() const {
-  printTaint(llvm::errs());
-}
-
 AnalysisManager& ProgramState::getAnalysisManager() const {
   return stateMgr->getOwningEngine().getAnalysisManager();
 }
@@ -657,166 +637,3 @@
   }
   return true;
 }
-
-ProgramStateRef ProgramState::addTaint(const Stmt *S,
-   const LocationContext *LCtx,
-   TaintTagType Kind) const {
-  if (const Expr *E = dyn_cast_or_null(S))
-S = E->IgnoreParens();
-
-  return addTaint(getSVal(S, LCtx), Kind);
-}
-
-ProgramStateRef ProgramState::addTaint(SVal V,
-   TaintTagType Kind) const {
-  SymbolRef Sym = V.getAsSymbol();
-  if (Sym)
-return addTaint(Sym, Kind);
-
-  // If the SVal represents a structure, try to mass-taint all values within the
-  // structure. For now it only works efficiently on lazy compound values that
-  // were conjured during a conservative evaluation of a function - either as
-  // return values of functions 

[PATCH] D59806: [clang-tidy] Add a check for [super self] in initializers 

2019-03-29 Thread Jordan Rose via Phabricator via cfe-commits
jordan_rose added a comment.

Ooh, I should have remembered "designated initializer". I guess it doesn't 
matter so much either way.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D59806



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


r357326 - [analyzer] Move taint API from ProgramState to a separate header. NFC.

2019-03-29 Thread Artem Dergachev via cfe-commits
Author: dergachev
Date: Fri Mar 29 15:49:30 2019
New Revision: 357326

URL: http://llvm.org/viewvc/llvm-project?rev=357326=rev
Log:
[analyzer] Move taint API from ProgramState to a separate header. NFC.

It is now an inter-checker communication API, similar to the one that
connects MallocChecker/CStringChecker/InnerPointerChecker: simply a set of
setters and getters for a state trait.

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

Added:
cfe/trunk/lib/StaticAnalyzer/Checkers/Taint.cpp
cfe/trunk/lib/StaticAnalyzer/Checkers/Taint.h
cfe/trunk/test/Analysis/taint-dumps.c
Removed:
cfe/trunk/include/clang/StaticAnalyzer/Core/PathSensitive/TaintManager.h
cfe/trunk/include/clang/StaticAnalyzer/Core/PathSensitive/TaintTag.h
cfe/trunk/lib/StaticAnalyzer/Core/TaintManager.cpp
Modified:

cfe/trunk/include/clang/StaticAnalyzer/Core/BugReporter/BugReporterVisitors.h
cfe/trunk/include/clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h
cfe/trunk/lib/StaticAnalyzer/Checkers/ArrayBoundCheckerV2.cpp
cfe/trunk/lib/StaticAnalyzer/Checkers/CMakeLists.txt
cfe/trunk/lib/StaticAnalyzer/Checkers/DivZeroChecker.cpp
cfe/trunk/lib/StaticAnalyzer/Checkers/GenericTaintChecker.cpp
cfe/trunk/lib/StaticAnalyzer/Checkers/TaintTesterChecker.cpp
cfe/trunk/lib/StaticAnalyzer/Checkers/VLASizeChecker.cpp
cfe/trunk/lib/StaticAnalyzer/Core/BugReporterVisitors.cpp
cfe/trunk/lib/StaticAnalyzer/Core/CMakeLists.txt
cfe/trunk/lib/StaticAnalyzer/Core/ProgramState.cpp

Modified: 
cfe/trunk/include/clang/StaticAnalyzer/Core/BugReporter/BugReporterVisitors.h
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/StaticAnalyzer/Core/BugReporter/BugReporterVisitors.h?rev=357326=357325=357326=diff
==
--- 
cfe/trunk/include/clang/StaticAnalyzer/Core/BugReporter/BugReporterVisitors.h 
(original)
+++ 
cfe/trunk/include/clang/StaticAnalyzer/Core/BugReporter/BugReporterVisitors.h 
Fri Mar 29 15:49:30 2019
@@ -307,20 +307,6 @@ public:
  BugReport ) override;
 };
 
-/// The bug visitor prints a diagnostic message at the location where a given
-/// variable was tainted.
-class TaintBugVisitor final : public BugReporterVisitor {
-private:
-  const SVal V;
-
-public:
-  TaintBugVisitor(const SVal V) : V(V) {}
-  void Profile(llvm::FoldingSetNodeID ) const override { ID.Add(V); }
-
-  std::shared_ptr VisitNode(const ExplodedNode *N,
- BugReporterContext ,
- BugReport ) override;
-};
 
 /// The bug visitor will walk all the nodes in a path and collect all the
 /// constraints. When it reaches the root node, will create a refutation

Modified: 
cfe/trunk/include/clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h?rev=357326=357325=357326=diff
==
--- cfe/trunk/include/clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h 
(original)
+++ cfe/trunk/include/clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h 
Fri Mar 29 15:49:30 2019
@@ -20,7 +20,6 @@
 #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState_Fwd.h"
 #include "clang/StaticAnalyzer/Core/PathSensitive/SValBuilder.h"
 #include "clang/StaticAnalyzer/Core/PathSensitive/Store.h"
-#include "clang/StaticAnalyzer/Core/PathSensitive/TaintTag.h"
 #include "llvm/ADT/FoldingSet.h"
 #include "llvm/ADT/ImmutableMap.h"
 #include "llvm/Support/Allocator.h"
@@ -43,7 +42,6 @@ typedef std::unique_ptr(*StoreManagerCreator)(
 ProgramStateManager &);
-typedef llvm::ImmutableMap TaintedSubRegions;
 
 
//===--===//
 // ProgramStateTrait - Traits used by the Generic Data Map of a ProgramState.
@@ -367,38 +365,6 @@ public:
   template  CB
   scanReachableSymbols(llvm::iterator_range Reachable) const;
 
-  /// Create a new state in which the statement is marked as tainted.
-  LLVM_NODISCARD ProgramStateRef
-  addTaint(const Stmt *S, const LocationContext *LCtx,
-   TaintTagType Kind = TaintTagGeneric) const;
-
-  /// Create a new state in which the value is marked as tainted.
-  LLVM_NODISCARD ProgramStateRef
-  addTaint(SVal V, TaintTagType Kind = TaintTagGeneric) const;
-
-  /// Create a new state in which the symbol is marked as tainted.
-  LLVM_NODISCARD ProgramStateRef addTaint(SymbolRef S,
-   TaintTagType Kind = TaintTagGeneric) const;
-
-  /// Create a new state in which the region symbol is marked as tainted.
-  LLVM_NODISCARD ProgramStateRef
-  addTaint(const MemRegion *R, TaintTagType Kind = TaintTagGeneric) const;
-
-  /// Create a new state in a which a sub-region of a given symbol is tainted.
-  /// This might 

[PATCH] D59857: [analyzer] PR37501: Disable the assertion for reverse-engineering logical op short circuits.

2019-03-29 Thread Phabricator via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rC357325: [analyzer] PR37501: Disable assertion for logical op 
short circuit evaluation. (authored by dergachev, committed by ).

Changed prior to commit:
  https://reviews.llvm.org/D59857?vs=192390=192933#toc

Repository:
  rC Clang

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

https://reviews.llvm.org/D59857

Files:
  lib/StaticAnalyzer/Core/ExprEngineC.cpp
  test/Analysis/logical-ops.c


Index: lib/StaticAnalyzer/Core/ExprEngineC.cpp
===
--- lib/StaticAnalyzer/Core/ExprEngineC.cpp
+++ lib/StaticAnalyzer/Core/ExprEngineC.cpp
@@ -627,6 +627,21 @@
 
 void ExprEngine::VisitLogicalExpr(const BinaryOperator* B, ExplodedNode *Pred,
   ExplodedNodeSet ) {
+  // This method acts upon CFG elements for logical operators && and ||
+  // and attaches the value (true or false) to them as expressions.
+  // It doesn't produce any state splits.
+  // If we made it that far, we're past the point when we modeled the short
+  // circuit. It means that we should have precise knowledge about whether
+  // we've short-circuited. If we did, we already know the value we need to
+  // bind. If we didn't, the value of the RHS (casted to the boolean type)
+  // is the answer.
+  // Currently this method tries to figure out whether we've short-circuited
+  // by looking at the ExplodedGraph. This method is imperfect because there
+  // could inevitably have been merges that would have resulted in multiple
+  // potential path traversal histories. We bail out when we fail.
+  // Due to this ambiguity, a more reliable solution would have been to
+  // track the short circuit operation history path-sensitively until
+  // we evaluate the respective logical operator.
   assert(B->getOpcode() == BO_LAnd ||
  B->getOpcode() == BO_LOr);
 
@@ -648,10 +663,20 @@
 ProgramPoint P = N->getLocation();
 assert(P.getAs()|| P.getAs());
 (void) P;
-assert(N->pred_size() == 1);
+if (N->pred_size() != 1) {
+  // We failed to track back where we came from.
+  Bldr.generateNode(B, Pred, state);
+  return;
+}
 N = *N->pred_begin();
   }
-  assert(N->pred_size() == 1);
+
+  if (N->pred_size() != 1) {
+// We failed to track back where we came from.
+Bldr.generateNode(B, Pred, state);
+return;
+  }
+
   N = *N->pred_begin();
   BlockEdge BE = N->getLocation().castAs();
   SVal X;
Index: test/Analysis/logical-ops.c
===
--- test/Analysis/logical-ops.c
+++ test/Analysis/logical-ops.c
@@ -1,4 +1,5 @@
-// RUN: %clang_analyze_cc1 -Wno-pointer-bool-conversion 
-analyzer-checker=core,debug.ExprInspection -verify -analyzer-config 
eagerly-assume=false %s
+// RUN: %clang_analyze_cc1 -w -analyzer-checker=core,debug.ExprInspection\
+// RUN:-analyzer-config eagerly-assume=false -verify %s
 
 void clang_analyzer_eval(int);
 
@@ -33,7 +34,21 @@
   return x >= start && x < end;
 }
 
-int undef(void) {} // expected-warning{{control reaches end of non-void 
function}}
+int undef(void) {}
 void useUndef(void) { 0 || undef(); }
 
 void testPointer(void) { (void) (1 && testPointer && 0); }
+
+char *global_ap, *global_bp, *global_cp;
+void ambiguous_backtrack_1() {
+  for (;;) {
+(global_bp - global_ap ? global_cp[global_bp - global_ap] : 0) || 1;
+global_bp++;
+  }
+}
+
+int global_a, global_b;
+void ambiguous_backtrack_2(int x) {
+  global_a = x >= 2 ? 1 : x;
+  global_b == x && 9 || 2;
+}


Index: lib/StaticAnalyzer/Core/ExprEngineC.cpp
===
--- lib/StaticAnalyzer/Core/ExprEngineC.cpp
+++ lib/StaticAnalyzer/Core/ExprEngineC.cpp
@@ -627,6 +627,21 @@
 
 void ExprEngine::VisitLogicalExpr(const BinaryOperator* B, ExplodedNode *Pred,
   ExplodedNodeSet ) {
+  // This method acts upon CFG elements for logical operators && and ||
+  // and attaches the value (true or false) to them as expressions.
+  // It doesn't produce any state splits.
+  // If we made it that far, we're past the point when we modeled the short
+  // circuit. It means that we should have precise knowledge about whether
+  // we've short-circuited. If we did, we already know the value we need to
+  // bind. If we didn't, the value of the RHS (casted to the boolean type)
+  // is the answer.
+  // Currently this method tries to figure out whether we've short-circuited
+  // by looking at the ExplodedGraph. This method is imperfect because there
+  // could inevitably have been merges that would have resulted in multiple
+  // potential path traversal histories. We bail out when we fail.
+  // Due to this ambiguity, a more reliable solution would have been to
+  // track the short circuit operation history path-sensitively until
+  // we evaluate the respective 

[PATCH] D59806: [clang-tidy] Add a check for [super self] in initializers 

2019-03-29 Thread Stephane Moore via Phabricator via cfe-commits
stephanemoore added a comment.

In D59806#1447929 , @jordan_rose wrote:

> I don't think there's ever a reason to call `[super self]`, and doing so 
> through a macro could easily indicate a bug.


Agreed.

The only relatively common usage of -[NSObject self] that I am aware of is 
through KVC, e.g., to construct a set of distinct objects using array operators:

  NSArray *uniqueObjects = [array 
valueForKeyPath:@"@distinctUnionOfObjects.self"]

I don't recall observing -[NSObject self] used in other situations.

> Diagnostic nitpick: the Objective-C term is "init method", not "initializer".

Good catch. Glancing through the project, I have the impression that there is 
some inconsistency in the terminology used by different diagnostics and 
documentation in the project. For example, the ARC documentation on method 
families 
 
and various tests use the term "init methods". In contrast, 
-Wobjc-designated-initializers 

 uses the term "initializer". The general pattern //seems// to be that 
documentation/diagnostics related to ARC use the term "init method" and 
diagnostics/documentation related to designated initializers use the term 
"initializer". I had assumed that "initializer" would be more intuitive to 
readers as this is the term typically used in Apple developer documentation, 
e.g., Concepts in Objective-C Programming > Object Initialization 
.

I believe that "initializer" will be more intuitive because of Apple 
documentation but I can change to "init method" if that is preferred. Please 
let me know what your preference is.




Comment at: clang-tools-extra/clang-tidy/objc/SuperSelfCheck.cpp:112
+  << Message->getMethodDecl()
+  << FixItHint::CreateReplacement(Message->getSourceRange(),
+  StringRef("[super init]"));

aaron.ballman wrote:
> This could be dangerous if the `[super self]` construct is in a macro, 
> couldn't it? e.g.,
> ```
> #define DERP self
> 
> [super DERP];
> ```
Good point. Let me add some test cases and make sure this is handled properly.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D59806



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


r357325 - [analyzer] PR37501: Disable assertion for logical op short circuit evaluation.

2019-03-29 Thread Artem Dergachev via cfe-commits
Author: dergachev
Date: Fri Mar 29 15:43:34 2019
New Revision: 357325

URL: http://llvm.org/viewvc/llvm-project?rev=357325=rev
Log:
[analyzer] PR37501: Disable assertion for logical op short circuit evaluation.

The transfer function for the CFG element that represents a logical operation
computes the value of the operation and does nothing else. The element
appears after all the short circuit decisions were made, so they don't need
to be made again at this point.

Because our expression evaluation is imprecise, it is often hard to
discriminate between:

  (1) we don't know the value of the RHS because we failed to evaluate it

and

  (2) we don't know the value of the RHS because it didn't need to be evaluated.

This is hard because it depends on our knowledge about the value of the LHS
(eg., if LHS is true, then RHS in (LHS || RHS) doesn't need to be computed)
but LHS itself may have been evaluated imprecisely and we don't know whether
it is true or not. Additionally, the Analyzer wouldn't necessarily even remember
what the value of the LHS was because theoretically it's not really necessary
to know it for any future evaluations.

In order to work around these issues, the transfer function for logical
operations consists in looking at the ExplodedGraph we've constructed so far
in order to figure out from which CFG direction did we arrive here.
Such post-factum backtracking that doesn't involve looking up LHS and RHS values
is usually possible. However sometimes it fails because when we deduplicate
exploded nodes with the same program point and the same program state we may end
up in a situation when we reached the same program point from two or more
different directions.

By removing the assertion, we admit that the procedure indeed sometimes fails to
work. When it fails, we also admit that we don't know the value of the logical
operator.

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

Modified:
cfe/trunk/lib/StaticAnalyzer/Core/ExprEngineC.cpp
cfe/trunk/test/Analysis/logical-ops.c

Modified: cfe/trunk/lib/StaticAnalyzer/Core/ExprEngineC.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/StaticAnalyzer/Core/ExprEngineC.cpp?rev=357325=357324=357325=diff
==
--- cfe/trunk/lib/StaticAnalyzer/Core/ExprEngineC.cpp (original)
+++ cfe/trunk/lib/StaticAnalyzer/Core/ExprEngineC.cpp Fri Mar 29 15:43:34 2019
@@ -627,6 +627,21 @@ void ExprEngine::VisitDeclStmt(const Dec
 
 void ExprEngine::VisitLogicalExpr(const BinaryOperator* B, ExplodedNode *Pred,
   ExplodedNodeSet ) {
+  // This method acts upon CFG elements for logical operators && and ||
+  // and attaches the value (true or false) to them as expressions.
+  // It doesn't produce any state splits.
+  // If we made it that far, we're past the point when we modeled the short
+  // circuit. It means that we should have precise knowledge about whether
+  // we've short-circuited. If we did, we already know the value we need to
+  // bind. If we didn't, the value of the RHS (casted to the boolean type)
+  // is the answer.
+  // Currently this method tries to figure out whether we've short-circuited
+  // by looking at the ExplodedGraph. This method is imperfect because there
+  // could inevitably have been merges that would have resulted in multiple
+  // potential path traversal histories. We bail out when we fail.
+  // Due to this ambiguity, a more reliable solution would have been to
+  // track the short circuit operation history path-sensitively until
+  // we evaluate the respective logical operator.
   assert(B->getOpcode() == BO_LAnd ||
  B->getOpcode() == BO_LOr);
 
@@ -648,10 +663,20 @@ void ExprEngine::VisitLogicalExpr(const
 ProgramPoint P = N->getLocation();
 assert(P.getAs()|| P.getAs());
 (void) P;
-assert(N->pred_size() == 1);
+if (N->pred_size() != 1) {
+  // We failed to track back where we came from.
+  Bldr.generateNode(B, Pred, state);
+  return;
+}
 N = *N->pred_begin();
   }
-  assert(N->pred_size() == 1);
+
+  if (N->pred_size() != 1) {
+// We failed to track back where we came from.
+Bldr.generateNode(B, Pred, state);
+return;
+  }
+
   N = *N->pred_begin();
   BlockEdge BE = N->getLocation().castAs();
   SVal X;

Modified: cfe/trunk/test/Analysis/logical-ops.c
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/Analysis/logical-ops.c?rev=357325=357324=357325=diff
==
--- cfe/trunk/test/Analysis/logical-ops.c (original)
+++ cfe/trunk/test/Analysis/logical-ops.c Fri Mar 29 15:43:34 2019
@@ -1,4 +1,5 @@
-// RUN: %clang_analyze_cc1 -Wno-pointer-bool-conversion 
-analyzer-checker=core,debug.ExprInspection -verify -analyzer-config 
eagerly-assume=false %s
+// RUN: %clang_analyze_cc1 -w -analyzer-checker=core,debug.ExprInspection\
+// RUN:

[PATCH] D58367: [analyzer] NFC: Improve upon the concept of BugReporterVisitor.

2019-03-29 Thread Phabricator via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rC357323: [analyzer] Introduce a simplified API for adding 
custom path notes. (authored by dergachev, committed by ).

Changed prior to commit:
  https://reviews.llvm.org/D58367?vs=192502=192932#toc

Repository:
  rC Clang

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

https://reviews.llvm.org/D58367

Files:
  include/clang/Analysis/ProgramPoint.h
  include/clang/StaticAnalyzer/Core/BugReporter/BugReporter.h
  include/clang/StaticAnalyzer/Core/BugReporter/BugReporterVisitors.h
  include/clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h
  include/clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h
  lib/StaticAnalyzer/Checkers/MIGChecker.cpp
  lib/StaticAnalyzer/Core/BugReporter.cpp
  lib/StaticAnalyzer/Core/BugReporterVisitors.cpp
  lib/StaticAnalyzer/Core/ExprEngine.cpp
  test/Analysis/mig.mm

Index: lib/StaticAnalyzer/Core/ExprEngine.cpp
===
--- lib/StaticAnalyzer/Core/ExprEngine.cpp
+++ lib/StaticAnalyzer/Core/ExprEngine.cpp
@@ -201,7 +201,9 @@
   svalBuilder(StateMgr.getSValBuilder()),
   ObjCNoRet(mgr.getASTContext()),
   BR(mgr, *this),
-  VisitedCallees(VisitedCalleesIn), HowToInline(HowToInlineIn) {
+  VisitedCallees(VisitedCalleesIn),
+  HowToInline(HowToInlineIn),
+  NoteTags(G.getAllocator()) {
   unsigned TrimInterval = mgr.options.GraphTrimInterval;
   if (TrimInterval != 0) {
 // Enable eager node reclamation when constructing the ExplodedGraph.
Index: lib/StaticAnalyzer/Core/BugReporterVisitors.cpp
===
--- lib/StaticAnalyzer/Core/BugReporterVisitors.cpp
+++ lib/StaticAnalyzer/Core/BugReporterVisitors.cpp
@@ -2492,6 +2492,30 @@
   return nullptr;
 }
 
+int NoteTag::Kind = 0;
+
+void TagVisitor::Profile(llvm::FoldingSetNodeID ) const {
+  static int Tag = 0;
+  ID.AddPointer();
+}
+
+std::shared_ptr
+TagVisitor::VisitNode(const ExplodedNode *N, BugReporterContext ,
+  BugReport ) {
+  ProgramPoint PP = N->getLocation();
+  const NoteTag *T = dyn_cast_or_null(PP.getTag());
+  if (!T)
+return nullptr;
+
+  if (Optional Msg = T->generateMessage(BRC, R)) {
+PathDiagnosticLocation Loc =
+PathDiagnosticLocation::create(PP, BRC.getSourceManager());
+return std::make_shared(Loc, *Msg);
+  }
+
+  return nullptr;
+}
+
 void FalsePositiveRefutationBRVisitor::Profile(
 llvm::FoldingSetNodeID ) const {
   static int Tag = 0;
Index: lib/StaticAnalyzer/Core/BugReporter.cpp
===
--- lib/StaticAnalyzer/Core/BugReporter.cpp
+++ lib/StaticAnalyzer/Core/BugReporter.cpp
@@ -2612,6 +2612,7 @@
 R->addVisitor(llvm::make_unique());
 R->addVisitor(llvm::make_unique());
 R->addVisitor(llvm::make_unique());
+R->addVisitor(llvm::make_unique());
 
 BugReporterContext BRC(Reporter, ErrorGraph.BackMap);
 
Index: lib/StaticAnalyzer/Checkers/MIGChecker.cpp
===
--- lib/StaticAnalyzer/Checkers/MIGChecker.cpp
+++ lib/StaticAnalyzer/Checkers/MIGChecker.cpp
@@ -80,43 +80,10 @@
 checkReturnAux(RS, C);
   }
 
-  class Visitor : public BugReporterVisitor {
-  public:
-void Profile(llvm::FoldingSetNodeID ) const {
-  static int X = 0;
-  ID.AddPointer();
-}
-
-std::shared_ptr VisitNode(const ExplodedNode *N,
-BugReporterContext , BugReport );
-  };
 };
 } // end anonymous namespace
 
-// FIXME: It's a 'const ParmVarDecl *' but there's no ready-made GDM traits
-// specialization for this sort of types.
-REGISTER_TRAIT_WITH_PROGRAMSTATE(ReleasedParameter, const void *)
-
-std::shared_ptr
-MIGChecker::Visitor::VisitNode(const ExplodedNode *N, BugReporterContext ,
-   BugReport ) {
-  const auto *NewPVD = static_cast(
-  N->getState()->get());
-  const auto *OldPVD = static_cast(
-  N->getFirstPred()->getState()->get());
-  if (OldPVD == NewPVD)
-return nullptr;
-
-  assert(NewPVD && "What is deallocated cannot be un-deallocated!");
-  SmallString<64> Str;
-  llvm::raw_svector_ostream OS(Str);
-  OS << "Value passed through parameter '" << NewPVD->getName()
- << "' is deallocated";
-
-  PathDiagnosticLocation Loc =
-  PathDiagnosticLocation::create(N->getLocation(), BRC.getSourceManager());
-  return std::make_shared(Loc, OS.str());
-}
+REGISTER_TRAIT_WITH_PROGRAMSTATE(ReleasedParameter, bool)
 
 static const ParmVarDecl *getOriginParam(SVal V, CheckerContext ) {
   SymbolRef Sym = V.getAsSymbol();
@@ -195,7 +162,16 @@
   if (!PVD)
 return;
 
-  C.addTransition(C.getState()->set(PVD));
+  const NoteTag *T = C.getNoteTag([this, PVD](BugReport ) -> std::string {
+if (() != )
+  return "";
+SmallString<64> Str;
+llvm::raw_svector_ostream OS(Str);
+OS << "Value passed through 

r357323 - [analyzer] Introduce a simplified API for adding custom path notes.

2019-03-29 Thread Artem Dergachev via cfe-commits
Author: dergachev
Date: Fri Mar 29 15:21:00 2019
New Revision: 357323

URL: http://llvm.org/viewvc/llvm-project?rev=357323=rev
Log:
[analyzer] Introduce a simplified API for adding custom path notes.

Almost all path-sensitive checkers need to tell the user when something specific
to that checker happens along the execution path but does not constitute a bug
on its own. For instance, a call to operator delete in C++ has consequences
that are specific to a use-after-free bug. Deleting an object is not a bug
on its own, but when the Analyzer finds an execution path on which a deleted
object is used, it'll have to explain to the user when exactly during that path
did the deallocation take place.

Historically such custom notes were added by implementing "bug report visitors".
These visitors were post-processing bug reports by visiting every ExplodedNode
along the path and emitting path notes whenever they noticed that a change that
is relevant to a bug report occurs within the program state. For example,
it emits a "memory is deallocated" note when it notices that a pointer changes
its state from "allocated" to "deleted".

The "visitor" approach is powerful and efficient but hard to use because
such preprocessing implies that the developer first models the effects
of the event (say, changes the pointer's state from "allocated" to "deleted"
as part of operator delete()'s transfer function) and then forgets what happened
and later tries to reverse-engineer itself and figure out what did it do
by looking at the report.

The proposed approach tries to avoid discarding the information that was
available when the transfer function was evaluated. Instead, it allows the
developer to capture all the necessary information into a closure that
will be automatically invoked later in order to produce the actual note.

This should reduce boilerplate and avoid very painful logic duplication.

On the technical side, the closure is a lambda that's put into a special kind of
a program point tag, and a special bug report visitor visits all nodes in the
report and invokes all note-producing closures it finds along the path.

For now it is up to the lambda to make sure that the note is actually relevant
to the report. For instance, a memory deallocation note would be irrelevant when
we're reporting a division by zero bug or if we're reporting a use-after-free
of a different, unrelated chunk of memory. The lambda can figure these thing out
by looking at the bug report object that's passed into it.

A single checker is refactored to make use of the new functionality: MIGChecker.
Its program state is trivial, making it an easy testing ground for the first
version of the API.

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

Modified:
cfe/trunk/include/clang/Analysis/ProgramPoint.h
cfe/trunk/include/clang/StaticAnalyzer/Core/BugReporter/BugReporter.h

cfe/trunk/include/clang/StaticAnalyzer/Core/BugReporter/BugReporterVisitors.h
cfe/trunk/include/clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h
cfe/trunk/include/clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h
cfe/trunk/lib/StaticAnalyzer/Checkers/MIGChecker.cpp
cfe/trunk/lib/StaticAnalyzer/Core/BugReporter.cpp
cfe/trunk/lib/StaticAnalyzer/Core/BugReporterVisitors.cpp
cfe/trunk/lib/StaticAnalyzer/Core/ExprEngine.cpp
cfe/trunk/test/Analysis/mig.mm

Modified: cfe/trunk/include/clang/Analysis/ProgramPoint.h
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Analysis/ProgramPoint.h?rev=357323=357322=357323=diff
==
--- cfe/trunk/include/clang/Analysis/ProgramPoint.h (original)
+++ cfe/trunk/include/clang/Analysis/ProgramPoint.h Fri Mar 29 15:21:00 2019
@@ -42,12 +42,11 @@ public:
   virtual ~ProgramPointTag();
   virtual StringRef getTagDescription() const = 0;
 
-protected:
   /// Used to implement 'isKind' in subclasses.
-  const void *getTagKind() { return TagKind; }
+  const void *getTagKind() const { return TagKind; }
 
 private:
-  const void *TagKind;
+  const void *const TagKind;
 };
 
 class SimpleProgramPointTag : public ProgramPointTag {

Modified: cfe/trunk/include/clang/StaticAnalyzer/Core/BugReporter/BugReporter.h
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/StaticAnalyzer/Core/BugReporter/BugReporter.h?rev=357323=357322=357323=diff
==
--- cfe/trunk/include/clang/StaticAnalyzer/Core/BugReporter/BugReporter.h 
(original)
+++ cfe/trunk/include/clang/StaticAnalyzer/Core/BugReporter/BugReporter.h Fri 
Mar 29 15:21:00 2019
@@ -592,6 +592,60 @@ public:
   NodeMapClosure& getNodeResolver() { return NMC; }
 };
 
+
+/// The tag upon which the TagVisitor reacts. Add these in order to display
+/// additional PathDiagnosticEventPieces along the path.
+class NoteTag : public ProgramPointTag {
+public:
+  using Callback =
+  std::function;
+

[PATCH] D59121: [analyzer] Fix macro names in diagnostics within bigger macros.

2019-03-29 Thread Csaba Dabis via Phabricator via cfe-commits
Charusso accepted this revision.
Charusso added a comment.

Nice catch!


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

https://reviews.llvm.org/D59121



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


[PATCH] D60013: [WebAssembly] Add mutable globals feature

2019-03-29 Thread Thomas Lively via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rL357321: [WebAssembly] Add mutable globals feature (authored 
by tlively, committed by ).

Changed prior to commit:
  https://reviews.llvm.org/D60013?vs=192911=192925#toc

Repository:
  rL LLVM

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

https://reviews.llvm.org/D60013

Files:
  cfe/trunk/include/clang/Driver/Options.td
  cfe/trunk/lib/Basic/Targets/WebAssembly.cpp
  cfe/trunk/lib/Basic/Targets/WebAssembly.h
  cfe/trunk/test/Preprocessor/wasm-target-features.c
  llvm/trunk/lib/Target/WebAssembly/WebAssembly.td
  llvm/trunk/lib/Target/WebAssembly/WebAssemblySubtarget.h
  llvm/trunk/test/CodeGen/WebAssembly/mutable-globals.ll

Index: llvm/trunk/test/CodeGen/WebAssembly/mutable-globals.ll
===
--- llvm/trunk/test/CodeGen/WebAssembly/mutable-globals.ll
+++ llvm/trunk/test/CodeGen/WebAssembly/mutable-globals.ll
@@ -0,0 +1,16 @@
+; RUN: llc < %s -mattr=+mutable-globals | FileCheck %s
+
+; Test that mutable globals is properly emitted into the target features section
+
+target datalayout = "e-m:e-p:32:32-i64:64-n32:64-S128"
+target triple = "wasm32-unknown-unknown"
+
+define void @foo() {
+  ret void
+}
+
+; CHECK-LABEL: .custom_section.target_features
+; CHECK-NEXT: .int8 1
+; CHECK-NEXT: .int8 43
+; CHECK-NEXT: .int8 15
+; CHECK-NEXT: .ascii "mutable-globals"
Index: llvm/trunk/lib/Target/WebAssembly/WebAssembly.td
===
--- llvm/trunk/lib/Target/WebAssembly/WebAssembly.td
+++ llvm/trunk/lib/Target/WebAssembly/WebAssembly.td
@@ -51,6 +51,10 @@
   SubtargetFeature<"bulk-memory", "HasBulkMemory", "true",
"Enable bulk memory operations">;
 
+def FeatureMutableGlobals :
+  SubtargetFeature<"mutable-globals", "HasMutableGlobals", "true",
+   "Enable mutable globals">;
+
 //===--===//
 // Architectures.
 //===--===//
Index: llvm/trunk/lib/Target/WebAssembly/WebAssemblySubtarget.h
===
--- llvm/trunk/lib/Target/WebAssembly/WebAssemblySubtarget.h
+++ llvm/trunk/lib/Target/WebAssembly/WebAssemblySubtarget.h
@@ -44,6 +44,7 @@
   bool HasSignExt = false;
   bool HasExceptionHandling = false;
   bool HasBulkMemory = false;
+  bool HasMutableGlobals = false;
 
   /// String name of used CPU.
   std::string CPUString;
@@ -97,6 +98,7 @@
   bool hasSignExt() const { return HasSignExt; }
   bool hasExceptionHandling() const { return HasExceptionHandling; }
   bool hasBulkMemory() const { return HasBulkMemory; }
+  bool hasMutableGlobals() const { return HasMutableGlobals; }
 
   /// Parses features string setting specified subtarget options. Definition of
   /// function is auto generated by tblgen.
Index: cfe/trunk/include/clang/Driver/Options.td
===
--- cfe/trunk/include/clang/Driver/Options.td
+++ cfe/trunk/include/clang/Driver/Options.td
@@ -2177,6 +2177,8 @@
 def mno_atomics : Flag<["-"], "mno-atomics">, Group;
 def mbulk_memory : Flag<["-"], "mbulk-memory">, Group;
 def mno_bulk_memory : Flag<["-"], "mno-bulk-memory">, Group;
+def mmutable_globals : Flag<["-"], "mmutable-globals">, Group;
+def mno_mutable_globals : Flag<["-"], "mno-mutable-globals">, Group;
 
 def mamdgpu_debugger_abi : Joined<["-"], "mamdgpu-debugger-abi=">,
   Flags<[HelpHidden]>,
Index: cfe/trunk/test/Preprocessor/wasm-target-features.c
===
--- cfe/trunk/test/Preprocessor/wasm-target-features.c
+++ cfe/trunk/test/Preprocessor/wasm-target-features.c
@@ -71,6 +71,15 @@
 // PTHREAD:#define __wasm_atomics__ 1{{$}}
 
 // RUN: %clang -E -dM %s -o - 2>&1 \
+// RUN: -target wasm32-unknown-unknown -mmutable-globals \
+// RUN:   | FileCheck %s -check-prefix=MUTABLE-GLOBALS
+// RUN: %clang -E -dM %s -o - 2>&1 \
+// RUN: -target wasm64-unknown-unknown -mmutable-globals \
+// RUN:   | FileCheck %s -check-prefix=MUTABLE-GLOBALS
+//
+// MUTABLE-GLOBALS:#define __wasm_mutable_globals__ 1{{$}}
+
+// RUN: %clang -E -dM %s -o - 2>&1 \
 // RUN: -target wasm32-unknown-unknown -mcpu=mvp \
 // RUN:   | FileCheck %s -check-prefix=MVP
 // RUN: %clang -E -dM %s -o - 2>&1 \
@@ -84,6 +93,7 @@
 // MVP-NOT:#define __wasm_exception_handling__
 // MVP-NOT:#define __wasm_bulk_memory__
 // MVP-NOT:#define __wasm_atomics__
+// MVP-NOT:#define __wasm_mutable_globals__
 
 // RUN: %clang -E -dM %s -o - 2>&1 \
 // RUN: -target wasm32-unknown-unknown -mcpu=bleeding-edge \
@@ -96,6 +106,7 @@
 // BLEEDING-EDGE-DAG:#define __wasm_sign_ext__ 1{{$}}
 // BLEEDING-EDGE-DAG:#define __wasm_simd128__ 1{{$}}
 // BLEEDING-EDGE-DAG:#define __wasm_atomics__ 1{{$}}
+// 

r357321 - [WebAssembly] Add mutable globals feature

2019-03-29 Thread Thomas Lively via cfe-commits
Author: tlively
Date: Fri Mar 29 15:00:18 2019
New Revision: 357321

URL: http://llvm.org/viewvc/llvm-project?rev=357321=rev
Log:
[WebAssembly] Add mutable globals feature

Summary:
This feature is not actually used for anything in the WebAssembly
backend, but adding it allows users to get it into the target features
sections of their objects, which makes these objects
future-compatible.

Reviewers: aheejin, dschuff

Subscribers: sbc100, jgravelle-google, hiraditya, sunfish, jdoerfert, 
cfe-commits, llvm-commits

Tags: #clang, #llvm

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

Modified:
cfe/trunk/include/clang/Driver/Options.td
cfe/trunk/lib/Basic/Targets/WebAssembly.cpp
cfe/trunk/lib/Basic/Targets/WebAssembly.h
cfe/trunk/test/Preprocessor/wasm-target-features.c

Modified: cfe/trunk/include/clang/Driver/Options.td
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Driver/Options.td?rev=357321=357320=357321=diff
==
--- cfe/trunk/include/clang/Driver/Options.td (original)
+++ cfe/trunk/include/clang/Driver/Options.td Fri Mar 29 15:00:18 2019
@@ -2177,6 +2177,8 @@ def matomics : Flag<["-"], "matomics">,
 def mno_atomics : Flag<["-"], "mno-atomics">, Group;
 def mbulk_memory : Flag<["-"], "mbulk-memory">, Group;
 def mno_bulk_memory : Flag<["-"], "mno-bulk-memory">, 
Group;
+def mmutable_globals : Flag<["-"], "mmutable-globals">, 
Group;
+def mno_mutable_globals : Flag<["-"], "mno-mutable-globals">, 
Group;
 
 def mamdgpu_debugger_abi : Joined<["-"], "mamdgpu-debugger-abi=">,
   Flags<[HelpHidden]>,

Modified: cfe/trunk/lib/Basic/Targets/WebAssembly.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Basic/Targets/WebAssembly.cpp?rev=357321=357320=357321=diff
==
--- cfe/trunk/lib/Basic/Targets/WebAssembly.cpp (original)
+++ cfe/trunk/lib/Basic/Targets/WebAssembly.cpp Fri Mar 29 15:00:18 2019
@@ -42,6 +42,7 @@ bool WebAssemblyTargetInfo::hasFeature(S
   .Case("exception-handling", HasExceptionHandling)
   .Case("bulk-memory", HasBulkMemory)
   .Case("atomics", HasAtomics)
+  .Case("mutable-globals", HasMutableGlobals)
   .Default(false);
 }
 
@@ -71,6 +72,8 @@ void WebAssemblyTargetInfo::getTargetDef
 Builder.defineMacro("__wasm_bulk_memory__");
   if (HasAtomics)
 Builder.defineMacro("__wasm_atomics__");
+  if (HasMutableGlobals)
+Builder.defineMacro("__wasm_mutable_globals__");
 }
 
 void WebAssemblyTargetInfo::setSIMDLevel(llvm::StringMap ,
@@ -94,6 +97,7 @@ bool WebAssemblyTargetInfo::initFeatureM
 Features["nontrapping-fptoint"] = true;
 Features["sign-ext"] = true;
 Features["atomics"] = true;
+Features["mutable-globals"] = true;
 setSIMDLevel(Features, SIMD128);
   }
   // Other targets do not consider user-configured features here, but while we
@@ -110,6 +114,8 @@ bool WebAssemblyTargetInfo::initFeatureM
 Features["bulk-memory"] = true;
   if (HasAtomics)
 Features["atomics"] = true;
+  if (HasMutableGlobals)
+Features["mutable-globals"] = true;
 
   return TargetInfo::initFeatureMap(Features, Diags, CPU, FeaturesVec);
 }
@@ -173,6 +179,14 @@ bool WebAssemblyTargetInfo::handleTarget
   HasAtomics = false;
   continue;
 }
+if (Feature == "+mutable-globals") {
+  HasMutableGlobals = true;
+  continue;
+}
+if (Feature == "-mutable-globals") {
+  HasMutableGlobals = false;
+  continue;
+}
 
 Diags.Report(diag::err_opt_not_valid_with_opt)
 << Feature << "-target-feature";

Modified: cfe/trunk/lib/Basic/Targets/WebAssembly.h
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Basic/Targets/WebAssembly.h?rev=357321=357320=357321=diff
==
--- cfe/trunk/lib/Basic/Targets/WebAssembly.h (original)
+++ cfe/trunk/lib/Basic/Targets/WebAssembly.h Fri Mar 29 15:00:18 2019
@@ -35,6 +35,7 @@ class LLVM_LIBRARY_VISIBILITY WebAssembl
   bool HasExceptionHandling = false;
   bool HasBulkMemory = false;
   bool HasAtomics = false;
+  bool HasMutableGlobals = false;
 
 public:
   explicit WebAssemblyTargetInfo(const llvm::Triple , const TargetOptions &)

Modified: cfe/trunk/test/Preprocessor/wasm-target-features.c
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/Preprocessor/wasm-target-features.c?rev=357321=357320=357321=diff
==
--- cfe/trunk/test/Preprocessor/wasm-target-features.c (original)
+++ cfe/trunk/test/Preprocessor/wasm-target-features.c Fri Mar 29 15:00:18 2019
@@ -71,6 +71,15 @@
 // PTHREAD:#define __wasm_atomics__ 1{{$}}
 
 // RUN: %clang -E -dM %s -o - 2>&1 \
+// RUN: -target wasm32-unknown-unknown -mmutable-globals \
+// RUN:   | FileCheck %s -check-prefix=MUTABLE-GLOBALS
+// RUN: %clang -E -dM %s -o - 2>&1 \
+// RUN: 

[PATCH] D59861: [analyzer] NFC: Replace Taint API with a usual inter-checker communication API?

2019-03-29 Thread Artem Dergachev via Phabricator via cfe-commits
NoQ updated this revision to Diff 192919.
NoQ added a comment.

Cleaned up formatting a bit.


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

https://reviews.llvm.org/D59861

Files:
  clang/include/clang/StaticAnalyzer/Core/BugReporter/BugReporterVisitors.h
  clang/include/clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h
  clang/include/clang/StaticAnalyzer/Core/PathSensitive/TaintManager.h
  clang/include/clang/StaticAnalyzer/Core/PathSensitive/TaintTag.h
  clang/lib/StaticAnalyzer/Checkers/ArrayBoundCheckerV2.cpp
  clang/lib/StaticAnalyzer/Checkers/CMakeLists.txt
  clang/lib/StaticAnalyzer/Checkers/DivZeroChecker.cpp
  clang/lib/StaticAnalyzer/Checkers/GenericTaintChecker.cpp
  clang/lib/StaticAnalyzer/Checkers/Taint.cpp
  clang/lib/StaticAnalyzer/Checkers/Taint.h
  clang/lib/StaticAnalyzer/Checkers/TaintTesterChecker.cpp
  clang/lib/StaticAnalyzer/Checkers/VLASizeChecker.cpp
  clang/lib/StaticAnalyzer/Core/BugReporterVisitors.cpp
  clang/lib/StaticAnalyzer/Core/CMakeLists.txt
  clang/lib/StaticAnalyzer/Core/ProgramState.cpp
  clang/lib/StaticAnalyzer/Core/TaintManager.cpp
  clang/test/Analysis/taint-dumps.c

Index: clang/test/Analysis/taint-dumps.c
===
--- /dev/null
+++ clang/test/Analysis/taint-dumps.c
@@ -0,0 +1,14 @@
+// RUN: %clang_analyze_cc1 -analyzer-checker=alpha.security.taint\
+// RUN:-analyzer-checker=debug.ExprInspection %s\
+// RUN:  2>&1 | FileCheck %s
+
+void clang_analyzer_printState();
+int getchar();
+
+// CHECK: Tainted symbols:
+// CHECK-NEXT: conj_$2{{.*}} : 0
+int test_taint_dumps() {
+  int x = getchar();
+  clang_analyzer_printState();
+  return x;
+}
Index: clang/lib/StaticAnalyzer/Core/TaintManager.cpp
===
--- clang/lib/StaticAnalyzer/Core/TaintManager.cpp
+++ /dev/null
@@ -1,22 +0,0 @@
-//== TaintManager.cpp -- -*- C++ -*--=//
-//
-// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
-// See https://llvm.org/LICENSE.txt for license information.
-// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
-//
-//===--===//
-
-#include "clang/StaticAnalyzer/Core/PathSensitive/TaintManager.h"
-
-using namespace clang;
-using namespace ento;
-
-void *ProgramStateTrait::GDMIndex() {
-  static int index = 0;
-  return 
-}
-
-void *ProgramStateTrait::GDMIndex() {
-  static int index;
-  return 
-}
Index: clang/lib/StaticAnalyzer/Core/ProgramState.cpp
===
--- clang/lib/StaticAnalyzer/Core/ProgramState.cpp
+++ clang/lib/StaticAnalyzer/Core/ProgramState.cpp
@@ -16,7 +16,6 @@
 #include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h"
 #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramStateTrait.h"
 #include "clang/StaticAnalyzer/Core/PathSensitive/SubEngine.h"
-#include "clang/StaticAnalyzer/Core/PathSensitive/TaintManager.h"
 #include "clang/StaticAnalyzer/Core/PathSensitive/DynamicTypeMap.h"
 #include "llvm/Support/raw_ostream.h"
 
@@ -458,9 +457,6 @@
   // Print out the tracked dynamic types.
   printDynamicTypeInfo(this, Out, NL, Sep);
 
-  // Print out tainted symbols.
-  printTaint(Out, NL);
-
   // Print checker-specific data.
   Mgr.getOwningEngine().printState(Out, this, NL, Sep, LC);
 }
@@ -474,22 +470,6 @@
   print(llvm::errs());
 }
 
-void ProgramState::printTaint(raw_ostream ,
-  const char *NL) const {
-  TaintMapImpl TM = get();
-
-  if (!TM.isEmpty())
-Out <<"Tainted symbols:" << NL;
-
-  for (TaintMapImpl::iterator I = TM.begin(), E = TM.end(); I != E; ++I) {
-Out << I->first << " : " << I->second << NL;
-  }
-}
-
-void ProgramState::dumpTaint() const {
-  printTaint(llvm::errs());
-}
-
 AnalysisManager& ProgramState::getAnalysisManager() const {
   return stateMgr->getOwningEngine().getAnalysisManager();
 }
@@ -657,166 +637,3 @@
   }
   return true;
 }
-
-ProgramStateRef ProgramState::addTaint(const Stmt *S,
-   const LocationContext *LCtx,
-   TaintTagType Kind) const {
-  if (const Expr *E = dyn_cast_or_null(S))
-S = E->IgnoreParens();
-
-  return addTaint(getSVal(S, LCtx), Kind);
-}
-
-ProgramStateRef ProgramState::addTaint(SVal V,
-   TaintTagType Kind) const {
-  SymbolRef Sym = V.getAsSymbol();
-  if (Sym)
-return addTaint(Sym, Kind);
-
-  // If the SVal represents a structure, try to mass-taint all values within the
-  // structure. For now it only works efficiently on lazy compound values that
-  // were conjured during a conservative evaluation of a function - either as
-  // return values of functions that return structures or arrays by value, or as
-  // values of structures or arrays 

[PATCH] D59121: [analyzer] Fix macro names in diagnostics within bigger macros.

2019-03-29 Thread Artem Dergachev via Phabricator via cfe-commits
NoQ updated this revision to Diff 192917.
NoQ added a comment.

Also, this is kinda weird. According to my logic, we should have written 
`Assuming 'i' is equal to 4294967295` because that's what the user will see in 
the macro popup. However, that's incorrect for the same reason: `i` is an int, 
while `4294967295` doesn't fit into an int, so they can never be equal. Writing 
`Assuming 'i' is equal to UINT32_MAX` is incorrect for the same reason, and the 
current message is the only one that's technically the truth.

Writing what exactly we're assuming is, in my opinion, more important than 
repeating what's literally written in the code.

Added a FIXME test to document this problem.


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

https://reviews.llvm.org/D59121

Files:
  clang/lib/StaticAnalyzer/Core/BugReporterVisitors.cpp
  clang/test/Analysis/diagnostics/macros.cpp

Index: clang/test/Analysis/diagnostics/macros.cpp
===
--- clang/test/Analysis/diagnostics/macros.cpp
+++ clang/test/Analysis/diagnostics/macros.cpp
@@ -3,7 +3,7 @@
 #include "../Inputs/system-header-simulator.h"
 #include "../Inputs/system-header-simulator-cxx.h"
 
-void testIntMacro(unsigned int i) {
+void testUnsignedIntMacro(unsigned int i) {
   if (i == UINT32_MAX) { // expected-note {{Assuming 'i' is equal to UINT32_MAX}}
  // expected-note@-1 {{Taking true branch}}
 char *p = NULL; // expected-note {{'p' initialized to a null pointer value}}
@@ -12,6 +12,20 @@
   }
 }
 
+
+// FIXME: 'i' can never be equal to UINT32_MAX - it doesn't even fit into its
+// type ('int'). This should say "Assuming 'i' is equal to -1".
+void testIntMacro(int i) {
+  if (i == UINT32_MAX) { // expected-note {{Assuming 'i' is equal to UINT32_MAX}}
+ // expected-note@-1 {{Taking true branch}}
+char *p = NULL; // expected-note {{'p' initialized to a null pointer value}}
+*p = 7;  // expected-warning {{Dereference of null pointer (loaded from variable 'p')}}
+ // expected-note@-1 {{Dereference of null pointer (loaded from variable 'p')}}
+  }
+}
+
+
+
 void testNULLMacro(int *p) {
   if (p == NULL) { // expected-note {{Assuming 'p' is equal to NULL}}
// expected-note@-1 {{Taking true branch}}
@@ -47,3 +61,14 @@
 // expected-note@-1 {{Dereference of null pointer (loaded from variable 'p')}}
   }
 }
+
+#define nested_null_split(x) if ((x) != UINT32_MAX) {}
+
+void testNestedNullSplitMacro(int i, int *p) {
+  nested_null_split(i); // expected-note {{Assuming 'i' is equal to -1}}
+// expected-note@-1 {{Taking false branch}}
+  if (!p) // expected-note {{Assuming 'p' is null}}
+  // expected-note@-1 {{Taking true branch}}
+*p = 1; // expected-warning {{Dereference of null pointer (loaded from variable 'p')}}
+// expected-note@-1 {{Dereference of null pointer (loaded from variable 'p')}}
+}
Index: clang/lib/StaticAnalyzer/Core/BugReporterVisitors.cpp
===
--- clang/lib/StaticAnalyzer/Core/BugReporterVisitors.cpp
+++ clang/lib/StaticAnalyzer/Core/BugReporterVisitors.cpp
@@ -1969,43 +1969,22 @@
   const Expr *OriginalExpr = Ex;
   Ex = Ex->IgnoreParenCasts();
 
-  // Use heuristics to determine if Ex is a macro expending to a literal and
-  // if so, use the macro's name.
-  SourceLocation LocStart = Ex->getBeginLoc();
-  SourceLocation LocEnd = Ex->getEndLoc();
-  if (LocStart.isMacroID() && LocEnd.isMacroID() &&
-  (isa(Ex) ||
-   isa(Ex) ||
-   isa(Ex) ||
-   isa(Ex) ||
-   isa(Ex))) {
-StringRef StartName = Lexer::getImmediateMacroNameForDiagnostics(LocStart,
-  BRC.getSourceManager(), BRC.getASTContext().getLangOpts());
-StringRef EndName = Lexer::getImmediateMacroNameForDiagnostics(LocEnd,
-  BRC.getSourceManager(), BRC.getASTContext().getLangOpts());
-bool beginAndEndAreTheSameMacro = StartName.equals(EndName);
-
-bool partOfParentMacro = false;
-if (ParentEx->getBeginLoc().isMacroID()) {
-  StringRef PName = Lexer::getImmediateMacroNameForDiagnostics(
-  ParentEx->getBeginLoc(), BRC.getSourceManager(),
-  BRC.getASTContext().getLangOpts());
-  partOfParentMacro = PName.equals(StartName);
-}
-
-if (beginAndEndAreTheSameMacro && !partOfParentMacro ) {
-  // Get the location of the macro name as written by the caller.
-  SourceLocation Loc = LocStart;
-  while (LocStart.isMacroID()) {
-Loc = LocStart;
-LocStart = BRC.getSourceManager().getImmediateMacroCallerLoc(LocStart);
+  if (isa(Ex) || isa(Ex) ||
+  isa(Ex) || isa(Ex) ||
+  isa(Ex)) {
+// Use heuristics to determine if the expression is a macro
+// expanding to a literal and if so, use the macro's name.
+SourceLocation BeginLoc = OriginalExpr->getBeginLoc();
+SourceLocation 

[PATCH] D59919: [Attributor] Deduce "returned" argument attribute

2019-03-29 Thread Johannes Doerfert via Phabricator via cfe-commits
jdoerfert updated this revision to Diff 192916.
jdoerfert added a comment.

Minor updates


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D59919

Files:
  clang/test/CodeGenOpenCL/as_type.cl
  llvm/include/llvm/Transforms/IPO/Attributor.h
  llvm/lib/Transforms/IPO/Attributor.cpp
  llvm/test/Transforms/FunctionAttrs/SCC1.ll
  llvm/test/Transforms/FunctionAttrs/arg_nocapture.ll
  llvm/test/Transforms/FunctionAttrs/arg_returned.ll

Index: llvm/test/Transforms/FunctionAttrs/arg_returned.ll
===
--- llvm/test/Transforms/FunctionAttrs/arg_returned.ll
+++ llvm/test/Transforms/FunctionAttrs/arg_returned.ll
@@ -1,4 +1,8 @@
-; RUN: opt -functionattrs -attributor -S < %s | FileCheck %s
+; RUN: opt -functionattrs -S < %s | FileCheck %s --check-prefix=FNATTR
+; RUN: opt -attributor -S < %s | FileCheck %s --check-prefix=ATTRIBUTOR
+; RUN: opt -attributor -functionattrs -S < %s | FileCheck %s --check-prefix=BOTH
+; RUN: opt -attributor -attributor-max-iterations=18 -S < %s | FileCheck %s --check-prefix=FEW_IT
+; RUN: opt -attributor -attributor-max-iterations=19 -functionattrs -S < %s | FileCheck %s --check-prefix=BOTH
 ;
 ; Test cases specifically designed for the "returned" argument attribute.
 ; We use FIXME's to indicate problems and missing attributes.
@@ -20,13 +24,20 @@
 
 ; TEST 1
 ;
-; CHECK: define dso_local i32 @sink_r0(i32 returned %r) [[NoInlineNoRecurseNoUnwindReadnoneUwtable:#[0-9]]]
+; BOTH: define dso_local i32 @sink_r0(i32 returned %r) [[NoInlineNoRecurseNoUnwindReadnoneUwtable:#[0-9]]]
+; BOTH: define dso_local i32 @scc_r1(i32 %a, i32 returned %r, i32 %b) [[NoInlineNoUnwindReadnoneUwtable:#[0-9]]]
+; BOTH: define dso_local i32 @scc_r2(i32 %a, i32 %b, i32 returned %r) [[NoInlineNoUnwindReadnoneUwtable]]
+; BOTH: define dso_local i32 @scc_rX(i32 %a, i32 %b, i32 %r) [[NoInlineNoUnwindReadnoneUwtable]]
 ;
-; FIXME: returned on %r missing:
-; CHECK: define dso_local i32 @scc_r1(i32 %a, i32 %r, i32 %b) [[NoInlineNoUnwindReadnoneUwtable:#[0-9]]]
+; FNATTR: define dso_local i32 @sink_r0(i32 returned %r) [[NoInlineNoRecurseNoUnwindReadnoneUwtable:#[0-9]]]
+; FNATTR: define dso_local i32 @scc_r1(i32 %a, i32 %r, i32 %b) [[NoInlineNoUnwindReadnoneUwtable:#[0-9]]]
+; FNATTR: define dso_local i32 @scc_r2(i32 %a, i32 %b, i32 %r) [[NoInlineNoUnwindReadnoneUwtable]]
+; FNATTR: define dso_local i32 @scc_rX(i32 %a, i32 %b, i32 %r) [[NoInlineNoUnwindReadnoneUwtable]]
 ;
-; FIXME: returned on %r missing:
-; CHECK: define dso_local i32 @scc_r2(i32 %a, i32 %b, i32 %r) [[NoInlineNoUnwindReadnoneUwtable]]
+; ATTRIBUTOR: define dso_local i32 @sink_r0(i32 returned %r) [[NoInlineNoRecurseNoUnwindReadnoneUwtable:#[0-9]]]
+; ATTRIBUTOR: define dso_local i32 @scc_r1(i32 %a, i32 returned %r, i32 %b) [[NoInlineNoUnwindReadnoneUwtable:#[0-9]]]
+; ATTRIBUTOR: define dso_local i32 @scc_r2(i32 %a, i32 %b, i32 returned %r) [[NoInlineNoUnwindReadnoneUwtable]]
+; ATTRIBUTOR: define dso_local i32 @scc_rX(i32 %a, i32 %b, i32 %r) [[NoInlineNoUnwindReadnoneUwtable]]
 ;
 ; int scc_r1(int a, int b, int r);
 ; int scc_r2(int a, int b, int r);
@@ -161,13 +172,17 @@
 
 ; TEST 2
 ;
-; CHECK: define dso_local double* @ptr_sink_r0(double* readnone returned %r) [[NoInlineNoRecurseNoUnwindReadnoneUwtable]]
+; BOTH: define dso_local double* @ptr_sink_r0(double* readnone returned %r) [[NoInlineNoRecurseNoUnwindReadnoneUwtable]]
+; BOTH: define dso_local double* @ptr_scc_r1(double* %a, double* readnone returned %r, double* nocapture readnone %b) [[NoInlineNoUnwindReadnoneUwtable]]
+; BOTH: define dso_local double* @ptr_scc_r2(double* readnone %a, double* readnone %b, double* readnone returned %r) [[NoInlineNoUnwindReadnoneUwtable]]
 ;
-; FIXME: returned on %r missing:
-; CHECK: define dso_local double* @ptr_scc_r1(double* %a, double* readnone %r, double* nocapture readnone %b) [[NoInlineNoUnwindReadnoneUwtable]]
+; FNATTR: define dso_local double* @ptr_sink_r0(double* readnone returned %r) [[NoInlineNoRecurseNoUnwindReadnoneUwtable]]
+; FNATTR: define dso_local double* @ptr_scc_r1(double* %a, double* readnone %r, double* nocapture readnone %b) [[NoInlineNoUnwindReadnoneUwtable]]
+; FNATTR: define dso_local double* @ptr_scc_r2(double* readnone %a, double* readnone %b, double* readnone %r) [[NoInlineNoUnwindReadnoneUwtable]]
 ;
-; FIXME: returned on %r missing:
-; CHECK: define dso_local double* @ptr_scc_r2(double* readnone %a, double* readnone %b, double* readnone %r) [[NoInlineNoUnwindReadnoneUwtable]]
+; ATTRIBUTOR: define dso_local double* @ptr_sink_r0(double* returned %r) [[NoInlineNoRecurseNoUnwindReadnoneUwtable]]
+; ATTRIBUTOR: define dso_local double* @ptr_scc_r1(double* %a, double* returned %r, double* %b) [[NoInlineNoUnwindReadnoneUwtable]]
+; ATTRIBUTOR: define dso_local double* @ptr_scc_r2(double* %a, double* %b, double* returned %r) [[NoInlineNoUnwindReadnoneUwtable]]
 ;
 ; double* ptr_scc_r1(double* 

[PATCH] D60013: [WebAssembly] Add mutable globals feature

2019-03-29 Thread Thomas Lively via Phabricator via cfe-commits
tlively created this revision.
tlively added reviewers: aheejin, dschuff.
Herald added subscribers: llvm-commits, cfe-commits, jdoerfert, sunfish, 
hiraditya, jgravelle-google, sbc100.
Herald added projects: clang, LLVM.

This feature is not actually used for anything in the WebAssembly
backend, but adding it allows users to get it into the target features
sections of their objects, which makes these objects
future-compatible.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D60013

Files:
  clang/include/clang/Driver/Options.td
  clang/lib/Basic/Targets/WebAssembly.cpp
  clang/lib/Basic/Targets/WebAssembly.h
  clang/test/Preprocessor/wasm-target-features.c
  llvm/lib/Target/WebAssembly/WebAssembly.td
  llvm/lib/Target/WebAssembly/WebAssemblySubtarget.h
  llvm/test/CodeGen/WebAssembly/mutable-globals.ll

Index: llvm/test/CodeGen/WebAssembly/mutable-globals.ll
===
--- /dev/null
+++ llvm/test/CodeGen/WebAssembly/mutable-globals.ll
@@ -0,0 +1,16 @@
+; RUN: llc < %s -mattr=+mutable-globals | FileCheck %s
+
+; Test that mutable globals is properly emitted into the target features section
+
+target datalayout = "e-m:e-p:32:32-i64:64-n32:64-S128"
+target triple = "wasm32-unknown-unknown"
+
+define void @foo() {
+  ret void
+}
+
+; CHECK-LABEL: .custom_section.target_features
+; CHECK-NEXT: .int8 1
+; CHECK-NEXT: .int8 43
+; CHECK-NEXT: .int8 15
+; CHECK-NEXT: .ascii "mutable-globals"
Index: llvm/lib/Target/WebAssembly/WebAssemblySubtarget.h
===
--- llvm/lib/Target/WebAssembly/WebAssemblySubtarget.h
+++ llvm/lib/Target/WebAssembly/WebAssemblySubtarget.h
@@ -44,6 +44,7 @@
   bool HasSignExt = false;
   bool HasExceptionHandling = false;
   bool HasBulkMemory = false;
+  bool HasMutableGlobals = false;
 
   /// String name of used CPU.
   std::string CPUString;
@@ -97,6 +98,7 @@
   bool hasSignExt() const { return HasSignExt; }
   bool hasExceptionHandling() const { return HasExceptionHandling; }
   bool hasBulkMemory() const { return HasBulkMemory; }
+  bool hasMutableGlobals() const { return HasMutableGlobals; }
 
   /// Parses features string setting specified subtarget options. Definition of
   /// function is auto generated by tblgen.
Index: llvm/lib/Target/WebAssembly/WebAssembly.td
===
--- llvm/lib/Target/WebAssembly/WebAssembly.td
+++ llvm/lib/Target/WebAssembly/WebAssembly.td
@@ -51,6 +51,10 @@
   SubtargetFeature<"bulk-memory", "HasBulkMemory", "true",
"Enable bulk memory operations">;
 
+def FeatureMutableGlobals :
+  SubtargetFeature<"mutable-globals", "HasMutableGlobals", "true",
+   "Enable mutable globals">;
+
 //===--===//
 // Architectures.
 //===--===//
Index: clang/test/Preprocessor/wasm-target-features.c
===
--- clang/test/Preprocessor/wasm-target-features.c
+++ clang/test/Preprocessor/wasm-target-features.c
@@ -70,6 +70,15 @@
 //
 // PTHREAD:#define __wasm_atomics__ 1{{$}}
 
+// RUN: %clang -E -dM %s -o - 2>&1 \
+// RUN: -target wasm32-unknown-unknown -mmutable-globals \
+// RUN:   | FileCheck %s -check-prefix=MUTABLE-GLOBALS
+// RUN: %clang -E -dM %s -o - 2>&1 \
+// RUN: -target wasm64-unknown-unknown -mmutable-globals \
+// RUN:   | FileCheck %s -check-prefix=MUTABLE-GLOBALS
+//
+// MUTABLE-GLOBALS:#define __wasm_mutable_globals__ 1{{$}}
+
 // RUN: %clang -E -dM %s -o - 2>&1 \
 // RUN: -target wasm32-unknown-unknown -mcpu=mvp \
 // RUN:   | FileCheck %s -check-prefix=MVP
@@ -84,6 +93,7 @@
 // MVP-NOT:#define __wasm_exception_handling__
 // MVP-NOT:#define __wasm_bulk_memory__
 // MVP-NOT:#define __wasm_atomics__
+// MVP-NOT:#define __wasm_mutable_globals__
 
 // RUN: %clang -E -dM %s -o - 2>&1 \
 // RUN: -target wasm32-unknown-unknown -mcpu=bleeding-edge \
@@ -96,6 +106,7 @@
 // BLEEDING-EDGE-DAG:#define __wasm_sign_ext__ 1{{$}}
 // BLEEDING-EDGE-DAG:#define __wasm_simd128__ 1{{$}}
 // BLEEDING-EDGE-DAG:#define __wasm_atomics__ 1{{$}}
+// BLEEDING-EDGE-DAG:#define __wasm_mutable_globals__ 1{{$}}
 // BLEEDING-EDGE-NOT:#define __wasm_unimplemented_simd128__ 1{{$}}
 
 // RUN: %clang -E -dM %s -o - 2>&1 \
Index: clang/lib/Basic/Targets/WebAssembly.h
===
--- clang/lib/Basic/Targets/WebAssembly.h
+++ clang/lib/Basic/Targets/WebAssembly.h
@@ -35,6 +35,7 @@
   bool HasExceptionHandling = false;
   bool HasBulkMemory = false;
   bool HasAtomics = false;
+  bool HasMutableGlobals = false;
 
 public:
   explicit WebAssemblyTargetInfo(const llvm::Triple , const TargetOptions &)
Index: clang/lib/Basic/Targets/WebAssembly.cpp

[PATCH] D59121: [analyzer] Fix macro names in diagnostics within bigger macros.

2019-03-29 Thread Csaba Dabis via Phabricator via cfe-commits
Charusso added a comment.

In D59121#1448386 , @NoQ wrote:

> Mmm, that *is* an `Assuming...` piece, i.e., this is the same code, just the 
> structure of macros is more complicated than usual.


You told me we would like to see a value when we hover over a name, which is 
cool. If I think about C and they do not C# over the complicated macros, I 
would like to C names of macros. It is up to you, but your first intention 
working with my code very well.


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

https://reviews.llvm.org/D59121



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


[PATCH] D59121: [analyzer] Fix macro names in diagnostics within bigger macros.

2019-03-29 Thread Artem Dergachev via Phabricator via cfe-commits
NoQ added a comment.

Mmm, that *is* an `Assuming...` piece, i.e., this is the same code, just the 
structure of macros is more complicated than usual.


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

https://reviews.llvm.org/D59121



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


[PATCH] D58573: [analyzer] Move UninitializedObject out of alpha

2019-03-29 Thread Artem Dergachev via Phabricator via cfe-commits
NoQ added a comment.

In D58573#1437749 , @Szelethus wrote:

> Ping, @NoQ, if we settled on `optin.cplusplus`, would you be fine with this 
> patch?


Yup, totally!


Repository:
  rC Clang

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

https://reviews.llvm.org/D58573



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


[PATCH] D59121: [analyzer] Fix macro names in diagnostics within bigger macros.

2019-03-29 Thread Csaba Dabis via Phabricator via cfe-commits
Charusso added a comment.

In D59121#1448367 , @NoQ wrote:

> On second thought, dunno. In the scan-build macro preview it wouldn't show 
> you UINT32_MAX anyway. Maybe let's keep this behavior.
>
> Cleaned up the patch a little bit.


Somehow on the `Assuming ...` pieces we write out the macro name, and my little 
code did that too. We could obtain the value but I think your first intention 
is the correct behaviour. Why are you not using my working example?


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

https://reviews.llvm.org/D59121



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


[PATCH] D59121: [analyzer] Fix macro names in diagnostics within bigger macros.

2019-03-29 Thread Artem Dergachev via Phabricator via cfe-commits
NoQ updated this revision to Diff 192906.
NoQ added a comment.

On second thought, dunno. In the scan-build macro preview it wouldn't show you 
UINT32_MAX anyway. Maybe let's keep this behavior.

Cleaned up the patch a little bit.


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

https://reviews.llvm.org/D59121

Files:
  clang/lib/StaticAnalyzer/Core/BugReporterVisitors.cpp
  clang/test/Analysis/diagnostics/macros.cpp


Index: clang/test/Analysis/diagnostics/macros.cpp
===
--- clang/test/Analysis/diagnostics/macros.cpp
+++ clang/test/Analysis/diagnostics/macros.cpp
@@ -47,3 +47,14 @@
 // expected-note@-1 {{Dereference of null pointer (loaded 
from variable 'p')}}
   }
 }
+
+#define nested_null_split(x) if ((x) != UINT32_MAX) {}
+
+void testNestedNullSplitMacro(int i, int *p) {
+  nested_null_split(i); // expected-note {{Assuming 'i' is equal to -1}}
+// expected-note@-1 {{Taking false branch}}
+  if (!p) // expected-note {{Assuming 'p' is null}}
+  // expected-note@-1 {{Taking true branch}}
+*p = 1; // expected-warning {{Dereference of null pointer (loaded from 
variable 'p')}}
+// expected-note@-1 {{Dereference of null pointer (loaded from 
variable 'p')}}
+}
Index: clang/lib/StaticAnalyzer/Core/BugReporterVisitors.cpp
===
--- clang/lib/StaticAnalyzer/Core/BugReporterVisitors.cpp
+++ clang/lib/StaticAnalyzer/Core/BugReporterVisitors.cpp
@@ -1969,43 +1969,22 @@
   const Expr *OriginalExpr = Ex;
   Ex = Ex->IgnoreParenCasts();
 
-  // Use heuristics to determine if Ex is a macro expending to a literal and
-  // if so, use the macro's name.
-  SourceLocation LocStart = Ex->getBeginLoc();
-  SourceLocation LocEnd = Ex->getEndLoc();
-  if (LocStart.isMacroID() && LocEnd.isMacroID() &&
-  (isa(Ex) ||
-   isa(Ex) ||
-   isa(Ex) ||
-   isa(Ex) ||
-   isa(Ex))) {
-StringRef StartName = Lexer::getImmediateMacroNameForDiagnostics(LocStart,
-  BRC.getSourceManager(), BRC.getASTContext().getLangOpts());
-StringRef EndName = Lexer::getImmediateMacroNameForDiagnostics(LocEnd,
-  BRC.getSourceManager(), BRC.getASTContext().getLangOpts());
-bool beginAndEndAreTheSameMacro = StartName.equals(EndName);
-
-bool partOfParentMacro = false;
-if (ParentEx->getBeginLoc().isMacroID()) {
-  StringRef PName = Lexer::getImmediateMacroNameForDiagnostics(
-  ParentEx->getBeginLoc(), BRC.getSourceManager(),
-  BRC.getASTContext().getLangOpts());
-  partOfParentMacro = PName.equals(StartName);
-}
-
-if (beginAndEndAreTheSameMacro && !partOfParentMacro ) {
-  // Get the location of the macro name as written by the caller.
-  SourceLocation Loc = LocStart;
-  while (LocStart.isMacroID()) {
-Loc = LocStart;
-LocStart = BRC.getSourceManager().getImmediateMacroCallerLoc(LocStart);
+  if (isa(Ex) || isa(Ex) ||
+  isa(Ex) || isa(Ex) ||
+  isa(Ex)) {
+// Use heuristics to determine if the expression is a macro
+// expanding to a literal and if so, use the macro's name.
+SourceLocation BeginLoc = OriginalExpr->getBeginLoc();
+SourceLocation EndLoc = OriginalExpr->getEndLoc();
+if (BeginLoc.isMacroID() && EndLoc.isMacroID()) {
+  SourceManager  = BRC.getSourceManager();
+  const LangOptions  = BRC.getASTContext().getLangOpts();
+  if (Lexer::isAtStartOfMacroExpansion(BeginLoc, SM, LO) &&
+  Lexer::isAtEndOfMacroExpansion(EndLoc, SM, LO)) {
+CharSourceRange R = Lexer::getAsCharRange({BeginLoc, EndLoc}, SM, LO);
+Out << Lexer::getSourceText(R, SM, LO);
+return false;
   }
-  StringRef MacroName = Lexer::getImmediateMacroNameForDiagnostics(
-Loc, BRC.getSourceManager(), BRC.getASTContext().getLangOpts());
-
-  // Return the macro name.
-  Out << MacroName;
-  return false;
 }
   }
 


Index: clang/test/Analysis/diagnostics/macros.cpp
===
--- clang/test/Analysis/diagnostics/macros.cpp
+++ clang/test/Analysis/diagnostics/macros.cpp
@@ -47,3 +47,14 @@
 // expected-note@-1 {{Dereference of null pointer (loaded from variable 'p')}}
   }
 }
+
+#define nested_null_split(x) if ((x) != UINT32_MAX) {}
+
+void testNestedNullSplitMacro(int i, int *p) {
+  nested_null_split(i); // expected-note {{Assuming 'i' is equal to -1}}
+// expected-note@-1 {{Taking false branch}}
+  if (!p) // expected-note {{Assuming 'p' is null}}
+  // expected-note@-1 {{Taking true branch}}
+*p = 1; // expected-warning {{Dereference of null pointer (loaded from variable 'p')}}
+// expected-note@-1 {{Dereference of null pointer (loaded from variable 'p')}}
+}
Index: clang/lib/StaticAnalyzer/Core/BugReporterVisitors.cpp

[clang-tools-extra] r357312 - [clang-tidy] Fix PR28406

2019-03-29 Thread Alexander Kornienko via cfe-commits
Author: alexfh
Date: Fri Mar 29 13:55:29 2019
New Revision: 357312

URL: http://llvm.org/viewvc/llvm-project?rev=357312=rev
Log:
[clang-tidy] Fix PR28406

Fix the crash resulting from a careless use of getLocWithOffset. At the
beginning of a macro expansion it produces an invalid SourceLocation that causes
an assertion failure later on.

Modified:
clang-tools-extra/trunk/clang-tidy/modernize/RedundantVoidArgCheck.cpp
clang-tools-extra/trunk/test/clang-tidy/modernize-redundant-void-arg.cpp

Modified: clang-tools-extra/trunk/clang-tidy/modernize/RedundantVoidArgCheck.cpp
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clang-tidy/modernize/RedundantVoidArgCheck.cpp?rev=357312=357311=357312=diff
==
--- clang-tools-extra/trunk/clang-tidy/modernize/RedundantVoidArgCheck.cpp 
(original)
+++ clang-tools-extra/trunk/clang-tidy/modernize/RedundantVoidArgCheck.cpp Fri 
Mar 29 13:55:29 2019
@@ -101,10 +101,15 @@ void RedundantVoidArgCheck::check(const
 void RedundantVoidArgCheck::processFunctionDecl(
 const MatchFinder::MatchResult , const FunctionDecl *Function) {
   if (Function->isThisDeclarationADefinition()) {
-const Stmt *Body = Function->getBody();
 SourceLocation Start = Function->getBeginLoc();
-SourceLocation End =
-Body ? Body->getBeginLoc().getLocWithOffset(-1) : 
Function->getEndLoc();
+SourceLocation End = Function->getEndLoc();
+if (const Stmt *Body = Function->getBody()) {
+  End = Body->getBeginLoc();
+  if (End.isMacroID() &&
+  Result.SourceManager->isAtStartOfImmediateMacroExpansion(End))
+End = Result.SourceManager->getExpansionLoc(End);
+  End = End.getLocWithOffset(-1);
+}
 removeVoidArgumentTokens(Result, SourceRange(Start, End),
  "function definition");
   } else {
@@ -172,10 +177,8 @@ void RedundantVoidArgCheck::removeVoidAr
 
 void RedundantVoidArgCheck::removeVoidToken(Token VoidToken,
 StringRef Diagnostic) {
-  SourceLocation VoidLoc(VoidToken.getLocation());
-  auto VoidRange =
-  CharSourceRange::getTokenRange(VoidLoc, VoidLoc.getLocWithOffset(3));
-  diag(VoidLoc, Diagnostic) << FixItHint::CreateRemoval(VoidRange);
+  SourceLocation VoidLoc = VoidToken.getLocation();
+  diag(VoidLoc, Diagnostic) << FixItHint::CreateRemoval(VoidLoc);
 }
 
 void RedundantVoidArgCheck::processTypedefNameDecl(

Modified: 
clang-tools-extra/trunk/test/clang-tidy/modernize-redundant-void-arg.cpp
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/test/clang-tidy/modernize-redundant-void-arg.cpp?rev=357312=357311=357312=diff
==
--- clang-tools-extra/trunk/test/clang-tidy/modernize-redundant-void-arg.cpp 
(original)
+++ clang-tools-extra/trunk/test/clang-tidy/modernize-redundant-void-arg.cpp 
Fri Mar 29 13:55:29 2019
@@ -489,6 +489,13 @@ void lambda_expression_with_macro_test()
   // CHECK-FIXES: []() BODY;
 }
 
+namespace qqq {
+void foo() BODY
+void bar(void) BODY;
+// CHECK-MESSAGES: :[[@LINE-1]]:10: warning: redundant void argument list in 
function definition
+// CHECK-FIXES: void bar() BODY;
+}
+
 struct S_1 {
   void g_1(void) const {
 // CHECK-MESSAGES: :[[@LINE-1]]:12: warning: redundant void argument list 
in function definition [modernize-redundant-void-arg]


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


[PATCH] D59712: [APSInt][OpenMP] Fix isNegative, etc. for unsigned types

2019-03-29 Thread Joel E. Denny via Phabricator via cfe-commits
jdenny added a comment.

Thanks.  Then the patch just needs someone to review from the ADT side.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D59712



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


[PATCH] D59712: [APSInt][OpenMP] Fix isNegative, etc. for unsigned types

2019-03-29 Thread Alexey Bataev via Phabricator via cfe-commits
ABataev added a comment.

I'm fine with the changes in the OpenMP tests


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D59712



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


[PATCH] D58675: [clang] Adds `-ftime-trace` option to clang that produces Chrome `chrome://tracing` compatible JSON profiling output dumps

2019-03-29 Thread Anton Afanasyev via Phabricator via cfe-commits
anton-afanasyev added a comment.

In D58675#1448112 , @rnk wrote:

> lgtm
>
> I think this is ready. We can adjust the overloads after the fact. I'd like 
> to get the feature in so we can make improvements independently.


Ok, so I'm to commit this and fix three points in the next commit(s):

1. Improve hashing (it's easy).
2. Use json utility.
3. Improve function_ref constructor and delete StringRef("...") explicit 
casting.


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

https://reviews.llvm.org/D58675



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


[PATCH] D58797: [Sema] Add some compile time _FORTIFY_SOURCE diagnostics

2019-03-29 Thread Erik Pilkington via Phabricator via cfe-commits
erik.pilkington added a comment.

In D58797#1447148 , @phosek wrote:

> This is triggering a Clang assertion failure in Fuchsia build:
>
>   clang/lib/AST/ExprConstant.cpp:5032: bool (anonymous 
> namespace)::ExprEvaluatorBase<(anonymous 
> namespace)::PointerExprEvaluator>::VisitMemberExpr(const clang::MemberExpr *) 
> [Derived = (anonymous namespace)::PointerExprEvaluator]: Assertion 
> `!E->isArrow() && "missing call to bound member function?"' failed.
>
>
> I've filed PR41286 which also has a reproducer.


Fixed in r357304, thanks.


Repository:
  rC Clang

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

https://reviews.llvm.org/D58797



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


r357304 - [Sema] Avoid sending a dependent expression to the constant evaluator.

2019-03-29 Thread Erik Pilkington via cfe-commits
Author: epilk
Date: Fri Mar 29 12:53:41 2019
New Revision: 357304

URL: http://llvm.org/viewvc/llvm-project?rev=357304=rev
Log:
[Sema] Avoid sending a dependent expression to the constant evaluator.

Fixes llvm.org/PR41286

Modified:
cfe/trunk/lib/Sema/SemaChecking.cpp
cfe/trunk/test/Sema/warn-fortify-source.c

Modified: cfe/trunk/lib/Sema/SemaChecking.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Sema/SemaChecking.cpp?rev=357304=357303=357304=diff
==
--- cfe/trunk/lib/Sema/SemaChecking.cpp (original)
+++ cfe/trunk/lib/Sema/SemaChecking.cpp Fri Mar 29 12:53:41 2019
@@ -307,6 +307,9 @@ void Sema::checkFortifiedBuiltinMemoryFu
   //  - Analyze the format string of sprintf to see how much of buffer is used.
   //  - Evaluate strlen of strcpy arguments, use as object size.
 
+  if (TheCall->isValueDependent() || TheCall->isTypeDependent())
+return;
+
   unsigned BuiltinID = FD->getBuiltinID(/*ConsiderWrappers=*/true);
   if (!BuiltinID)
 return;

Modified: cfe/trunk/test/Sema/warn-fortify-source.c
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/Sema/warn-fortify-source.c?rev=357304=357303=357304=diff
==
--- cfe/trunk/test/Sema/warn-fortify-source.c (original)
+++ cfe/trunk/test/Sema/warn-fortify-source.c Fri Mar 29 12:53:41 2019
@@ -1,9 +1,16 @@
 // RUN: %clang_cc1 -triple x86_64-apple-macosx10.14.0 %s -verify
 // RUN: %clang_cc1 -triple x86_64-apple-macosx10.14.0 %s -verify 
-DUSE_PASS_OBJECT_SIZE
 // RUN: %clang_cc1 -triple x86_64-apple-macosx10.14.0 %s -verify -DUSE_BUILTINS
+// RUN: %clang_cc1 -xc++ -triple x86_64-apple-macosx10.14.0 %s -verify
+// RUN: %clang_cc1 -xc++ -triple x86_64-apple-macosx10.14.0 %s -verify 
-DUSE_PASS_OBJECT_SIZE
+// RUN: %clang_cc1 -xc++ -triple x86_64-apple-macosx10.14.0 %s -verify 
-DUSE_BUILTINS
 
 typedef unsigned long size_t;
 
+#ifdef __cplusplus
+extern "C" {
+#endif
+
 #if defined(USE_PASS_OBJECT_SIZE)
 void *memcpy(void *dst, const void *src, size_t c);
 static void *memcpy(void *dst __attribute__((pass_object_size(1))), const void 
*src, size_t c) __attribute__((overloadable)) __asm__("merp");
@@ -16,6 +23,10 @@ static void *memcpy(void *const dst __at
 void *memcpy(void *dst, const void *src, size_t c);
 #endif
 
+#ifdef __cplusplus
+}
+#endif
+
 void call_memcpy() {
   char dst[10];
   char src[20];
@@ -84,3 +95,25 @@ void call_vsnprintf() {
   __builtin_vsnprintf(buf, 10, "merp", list);
   __builtin_vsnprintf(buf, 11, "merp", list); // expected-warning 
{{'vsnprintf' size argument is too large; destination buffer has size 10, but 
size argument is 11}}
 }
+
+#ifdef __cplusplus
+template  struct S {
+  void mf() const {
+__builtin_memset(const_cast(mv), 0, 0);
+  }
+
+  char mv[10];
+};
+
+template 
+void call_memcpy_dep() {
+  char bufferA[A];
+  char bufferB[B];
+  memcpy(bufferA, bufferB, 10); // expected-warning{{'memcpy' will always 
overflow; destination buffer has size 9, but size argument is 10}}
+}
+
+void call_call_memcpy() {
+  call_memcpy_dep<10, 9>();
+  call_memcpy_dep<9, 10>(); // expected-note {{in instantiation of function 
template specialization 'call_memcpy_dep<9, 10>' requested here}}
+}
+#endif


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


[PATCH] D59376: [LibTooling] Add Transformer, a library for source-to-source transformations.

2019-03-29 Thread Yitzhak Mandelbaum via Phabricator via cfe-commits
ymandel marked 19 inline comments as done.
ymandel added a comment.

Thanks for (more) helpful comments.  I think the code is a lot better now than 
it started out. :)

Also, converted `RewriteRule` to a simple struct as per our discussion.




Comment at: clang/include/clang/Tooling/Refactoring/Transformer.h:70
+//
+// * Explanation: explanation of the rewrite.
+//

ilya-biryukov wrote:
> NIT: maybe mention what it should be used for? we plan to show to to the user 
> (e.g. in the clang-tidy fix description), right?
Done. But, given that we don't use this field yet, I'm fine deleting it until a 
future revision. I'm also fine leaving it given that we know we'll be needing 
it later.



Comment at: clang/include/clang/Tooling/Refactoring/Transformer.h:89
+// \code
+//   RewriteRule R = buildRule(functionDecl(...)).replaceWith(...);
+// \endcode

ilya-biryukov wrote:
> Could you also add examples on how to apply the rewrite rule here?
> So that the users can have an idea about the full workflow when reading the 
> code.
Is this what you had in mind? Unlike clang-tidy, there is no neat 
infrastructure into which we can drop it.



Comment at: clang/include/clang/Tooling/Refactoring/Transformer.h:97
+  ast_matchers::internal::DynTypedMatcher Matcher;
+  // The (bound) id of the node whose source will be replaced.  This id should
+  // never be the empty string.

ilya-biryukov wrote:
> NIT: maybe assert this invariant in the constructor?
The constructor sets this field, so no need to assert.



Comment at: clang/include/clang/Tooling/Refactoring/Transformer.h:122
+  // The bound id of the node corresponding to the matcher.
+  static llvm::StringRef matchedNode() { return RootId; }
+

ilya-biryukov wrote:
> This method does not seem to be used anywhere.
> Are we missing the usages in this patch? Maybe remove it from the initial 
> implementation and re-add later when we have the callsites?
It was used above in makeMatcher.  But, it was overkill -- users can just 
reference RootId directly, so I've removed it.



Comment at: clang/include/clang/Tooling/Refactoring/Transformer.h:175
+  RewriteRuleBuilder &(std::string Explanation) && {
+return std::move(std::move(*this).because(text(std::move(Explanation;
+  }

ilya-biryukov wrote:
> NIT: the top-level `std::move` looks redundant, maybe remove it?
Yes, not sure why did that. thanks.



Comment at: clang/lib/Tooling/Refactoring/Transformer.cpp:133
+
+namespace clang {
+namespace tooling {

ilya-biryukov wrote:
> NIT: remove namespaces for consistency with the rest of the code.
> 
> (Probably a leftover from the previous version)
This is necessary as far as I can tell. W/o it, I get a linker failure (missing 
definition). Based on the declaration in the header, the compiler resolves the 
reference below to clang::tooling::applyRewriteRule() but this definition ends 
up in the global namespace.

I think the using decls only work for method definitions -- the type seems to 
resolve to be the one in the namespace. But free functions don't get the same 
treatment. Unless I"m doing something wrong?



Comment at: clang/lib/Tooling/Refactoring/Transformer.cpp:150
+  llvm::handleErrors(TargetOrErr.takeError(), [](StringError ) {
+return invalidArgumentError("Failure targeting node" +
+Rule.target() + ": " + E.getMessage());

ilya-biryukov wrote:
> NIT: consider simply propagating the original error up the stack in that case 
> to avoid boilerplate.
> Although adding the `.target()` information to the error might be useful, so 
> up to you.
integrated id into getTarget so we can avoid this error handling step.



Comment at: clang/lib/Tooling/Refactoring/Transformer.cpp:157
+  isOriginMacroBody(*Match.SourceManager, Target.getBegin()))
+return Transformation();
+

ilya-biryukov wrote:
> Why not return an error in case of macros too? Is there any use of the empty 
> transformation to the clients? 
> Alternatively, we might want to document this behavior (applyRewriteRule can 
> return empty transformations) and it's rationale.
I think the common case is that we simply want to skip macros -- there's 
nothing erroneous about them, they're just usually hard to deal w/ correctly.  
That said, we might want to change this to *never* return an error and just 
assert when things go wrong. The advantage of the current design is that 
callers can in principle ignore failed rewrites.

However, in practice, if the rewrite fails that means it had a bug, so it might 
be best to asssert().  Only real advantage, then, is that this is easier to 
test since it doesn't crash the program.

WDYT?



Comment at: 

[PATCH] D59712: [APSInt][OpenMP] Fix isNegative, etc. for unsigned types

2019-03-29 Thread Joel E. Denny via Phabricator via cfe-commits
jdenny added a comment.

Ping.  To be clear, my goal here was not to change the OpenMP behavior.  My 
goal was to fix APSInt behavior.  If people feel that the old OpenMP behavior 
is better somehow, we should surely find another way to implement that.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D59712



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


[PATCH] D44671: [libcxx] Enable static libcxxabi linking on Darwin

2019-03-29 Thread Petr Hosek via Phabricator via cfe-commits
phosek abandoned this revision.
phosek added a comment.
Herald added a subscriber: libcxx-commits.

This was already implemented in D59513 .


Repository:
  rCXX libc++

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

https://reviews.llvm.org/D44671



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


[PATCH] D59376: [LibTooling] Add Transformer, a library for source-to-source transformations.

2019-03-29 Thread Yitzhak Mandelbaum via Phabricator via cfe-commits
ymandel updated this revision to Diff 192889.
ymandel marked an inline comment as done.
ymandel added a comment.

- Assorted changes in response to comments.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D59376

Files:
  clang/include/clang/Tooling/Refactoring/Transformer.h
  clang/lib/Tooling/Refactoring/CMakeLists.txt
  clang/lib/Tooling/Refactoring/Transformer.cpp
  clang/unittests/Tooling/CMakeLists.txt
  clang/unittests/Tooling/TransformerTest.cpp

Index: clang/unittests/Tooling/TransformerTest.cpp
===
--- /dev/null
+++ clang/unittests/Tooling/TransformerTest.cpp
@@ -0,0 +1,388 @@
+//===- unittest/Tooling/TransformerTest.cpp ---===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+
+#include "clang/Tooling/Refactoring/Transformer.h"
+
+#include "clang/ASTMatchers/ASTMatchers.h"
+#include "clang/Tooling/Tooling.h"
+#include "gmock/gmock.h"
+#include "gtest/gtest.h"
+
+namespace clang {
+namespace tooling {
+namespace {
+using ast_matchers::anyOf;
+using ast_matchers::argumentCountIs;
+using ast_matchers::callee;
+using ast_matchers::callExpr;
+using ast_matchers::cxxMemberCallExpr;
+using ast_matchers::cxxMethodDecl;
+using ast_matchers::cxxRecordDecl;
+using ast_matchers::declRefExpr;
+using ast_matchers::expr;
+using ast_matchers::functionDecl;
+using ast_matchers::hasAnyName;
+using ast_matchers::hasArgument;
+using ast_matchers::hasDeclaration;
+using ast_matchers::hasElse;
+using ast_matchers::hasName;
+using ast_matchers::hasType;
+using ast_matchers::ifStmt;
+using ast_matchers::member;
+using ast_matchers::memberExpr;
+using ast_matchers::namedDecl;
+using ast_matchers::on;
+using ast_matchers::pointsTo;
+using ast_matchers::to;
+using ast_matchers::unless;
+
+using llvm::StringRef;
+
+constexpr char KHeaderContents[] = R"cc(
+  struct string {
+string(const char*);
+char* c_str();
+int size();
+  };
+  int strlen(const char*);
+
+  namespace proto {
+  struct PCFProto {
+int foo();
+  };
+  struct ProtoCommandLineFlag : PCFProto {
+PCFProto& GetProto();
+  };
+  }  // namespace proto
+)cc";
+
+ast_matchers::internal::Matcher
+isOrPointsTo(const clang::ast_matchers::DeclarationMatcher ) {
+  return anyOf(hasDeclaration(TypeMatcher), pointsTo(TypeMatcher));
+}
+
+std::string format(StringRef Code) {
+  const std::vector Ranges(1, Range(0, Code.size()));
+  auto Style = format::getLLVMStyle();
+  const auto Replacements = format::reformat(Style, Code, Ranges);
+  auto Formatted = applyAllReplacements(Code, Replacements);
+  if (!Formatted) {
+ADD_FAILURE() << "Could not format code: "
+  << llvm::toString(Formatted.takeError());
+return std::string();
+  }
+  return *Formatted;
+}
+
+void compareSnippets(StringRef Expected,
+ const llvm::Optional ) {
+  ASSERT_TRUE(MaybeActual) << "Rewrite failed. Expecting: " << Expected;
+  auto Actual = *MaybeActual;
+  std::string HL = "#include \"header.h\"\n";
+  auto I = Actual.find(HL);
+  if (I != std::string::npos)
+Actual.erase(I, HL.size());
+  EXPECT_EQ(format(Expected), format(Actual));
+}
+
+// FIXME: consider separating this class into its own file(s).
+class ClangRefactoringTestBase : public testing::Test {
+protected:
+  void appendToHeader(StringRef S) { FileContents[0].second += S; }
+
+  void addFile(StringRef Filename, StringRef Content) {
+FileContents.emplace_back(Filename, Content);
+  }
+
+  llvm::Optional rewrite(StringRef Input) {
+std::string Code = ("#include \"header.h\"\n" + Input).str();
+auto Factory = newFrontendActionFactory();
+if (!runToolOnCodeWithArgs(
+Factory->create(), Code, std::vector(), "input.cc",
+"clang-tool", std::make_shared(),
+FileContents)) {
+  return None;
+}
+auto ChangedCodeOrErr =
+applyAtomicChanges("input.cc", Code, Changes, ApplyChangesSpec());
+if (auto Err = ChangedCodeOrErr.takeError()) {
+  llvm::errs() << "Change failed: " << llvm::toString(std::move(Err))
+   << "\n";
+  return None;
+}
+return *ChangedCodeOrErr;
+  }
+
+  void testRule(RewriteRule Rule, StringRef Input, StringRef Expected) {
+Transformer T(std::move(Rule),
+  [this](const AtomicChange ) { Changes.push_back(C); });
+T.registerMatchers();
+compareSnippets(Expected, rewrite(Input));
+  }
+
+  clang::ast_matchers::MatchFinder MatchFinder;
+  AtomicChanges Changes;
+
+private:
+  FileContentMappings FileContents = {{"header.h", ""}};
+};
+
+class TransformerTest : public ClangRefactoringTestBase {
+protected:
+  

[PATCH] D58659: [Sema] Fix assertion when `auto` parameter in lambda has an attribute.

2019-03-29 Thread Volodymyr Sapsai via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rL357298: [Sema] Fix assertion when `auto` parameter in lambda 
has an attribute. (authored by vsapsai, committed by ).
Herald added a project: LLVM.
Herald added a subscriber: llvm-commits.

Changed prior to commit:
  https://reviews.llvm.org/D58659?vs=188283=192878#toc

Repository:
  rL LLVM

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

https://reviews.llvm.org/D58659

Files:
  cfe/trunk/lib/Sema/SemaType.cpp
  cfe/trunk/test/SemaCXX/auto-cxx0x.cpp


Index: cfe/trunk/lib/Sema/SemaType.cpp
===
--- cfe/trunk/lib/Sema/SemaType.cpp
+++ cfe/trunk/lib/Sema/SemaType.cpp
@@ -255,6 +255,23 @@
   return T;
 }
 
+/// Completely replace the \c auto in \p TypeWithAuto by
+/// \p Replacement. Also replace \p TypeWithAuto in \c TypeAttrPair if
+/// necessary.
+QualType ReplaceAutoType(QualType TypeWithAuto, QualType Replacement) {
+  QualType T = sema.ReplaceAutoType(TypeWithAuto, Replacement);
+  if (auto *AttrTy = TypeWithAuto->getAs()) {
+// Attributed type still should be an attributed type after 
replacement.
+auto *NewAttrTy = cast(T.getTypePtr());
+for (TypeAttrPair  : AttrsForTypes) {
+  if (A.first == AttrTy)
+A.first = NewAttrTy;
+}
+AttrsForTypesSorted = false;
+  }
+  return T;
+}
+
 /// Extract and remove the Attr* for a given attributed type.
 const Attr *takeAttrForAttributedType(const AttributedType *AT) {
   if (!AttrsForTypesSorted) {
@@ -2938,7 +2955,7 @@
 // template type parameter.
 // FIXME: Retain some type sugar to indicate that this was written
 // as 'auto'.
-T = SemaRef.ReplaceAutoType(
+T = state.ReplaceAutoType(
 T, QualType(CorrespondingTemplateParam->getTypeForDecl(), 0));
   }
   break;
Index: cfe/trunk/test/SemaCXX/auto-cxx0x.cpp
===
--- cfe/trunk/test/SemaCXX/auto-cxx0x.cpp
+++ cfe/trunk/test/SemaCXX/auto-cxx0x.cpp
@@ -15,3 +15,11 @@
   // expected-error@-2 {{'auto' not allowed in lambda parameter}}
 #endif
 }
+
+void rdar47689465() {
+  int x = 0;
+  [](auto __attribute__((noderef)) *){}();
+#if __cplusplus == 201103L
+  // expected-error@-2 {{'auto' not allowed in lambda parameter}}
+#endif
+}


Index: cfe/trunk/lib/Sema/SemaType.cpp
===
--- cfe/trunk/lib/Sema/SemaType.cpp
+++ cfe/trunk/lib/Sema/SemaType.cpp
@@ -255,6 +255,23 @@
   return T;
 }
 
+/// Completely replace the \c auto in \p TypeWithAuto by
+/// \p Replacement. Also replace \p TypeWithAuto in \c TypeAttrPair if
+/// necessary.
+QualType ReplaceAutoType(QualType TypeWithAuto, QualType Replacement) {
+  QualType T = sema.ReplaceAutoType(TypeWithAuto, Replacement);
+  if (auto *AttrTy = TypeWithAuto->getAs()) {
+// Attributed type still should be an attributed type after replacement.
+auto *NewAttrTy = cast(T.getTypePtr());
+for (TypeAttrPair  : AttrsForTypes) {
+  if (A.first == AttrTy)
+A.first = NewAttrTy;
+}
+AttrsForTypesSorted = false;
+  }
+  return T;
+}
+
 /// Extract and remove the Attr* for a given attributed type.
 const Attr *takeAttrForAttributedType(const AttributedType *AT) {
   if (!AttrsForTypesSorted) {
@@ -2938,7 +2955,7 @@
 // template type parameter.
 // FIXME: Retain some type sugar to indicate that this was written
 // as 'auto'.
-T = SemaRef.ReplaceAutoType(
+T = state.ReplaceAutoType(
 T, QualType(CorrespondingTemplateParam->getTypeForDecl(), 0));
   }
   break;
Index: cfe/trunk/test/SemaCXX/auto-cxx0x.cpp
===
--- cfe/trunk/test/SemaCXX/auto-cxx0x.cpp
+++ cfe/trunk/test/SemaCXX/auto-cxx0x.cpp
@@ -15,3 +15,11 @@
   // expected-error@-2 {{'auto' not allowed in lambda parameter}}
 #endif
 }
+
+void rdar47689465() {
+  int x = 0;
+  [](auto __attribute__((noderef)) *){}();
+#if __cplusplus == 201103L
+  // expected-error@-2 {{'auto' not allowed in lambda parameter}}
+#endif
+}
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


r357298 - [Sema] Fix assertion when `auto` parameter in lambda has an attribute.

2019-03-29 Thread Volodymyr Sapsai via cfe-commits
Author: vsapsai
Date: Fri Mar 29 11:47:07 2019
New Revision: 357298

URL: http://llvm.org/viewvc/llvm-project?rev=357298=rev
Log:
[Sema] Fix assertion when `auto` parameter in lambda has an attribute.

Fixes the assertion
> no Attr* for AttributedType*
> UNREACHABLE executed at llvm-project/clang/lib/Sema/SemaType.cpp:298!

In `TypeProcessingState::getAttributedType` we put into `AttrsForTypes`
types with `auto` but later in
`TypeProcessingState::takeAttrForAttributedType` we use transformed
types and that's why cannot find `Attr` corresponding to
`AttributedType`.

Fix by keeping `AttrsForTypes` up to date after replacing `AutoType`.

rdar://problem/47689465

Reviewers: rsmith, arphaman, aaron.ballman

Reviewed By: aaron.ballman

Subscribers: jkorous, dexonsmith, jdoerfert, cfe-commits

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


Modified:
cfe/trunk/lib/Sema/SemaType.cpp
cfe/trunk/test/SemaCXX/auto-cxx0x.cpp

Modified: cfe/trunk/lib/Sema/SemaType.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Sema/SemaType.cpp?rev=357298=357297=357298=diff
==
--- cfe/trunk/lib/Sema/SemaType.cpp (original)
+++ cfe/trunk/lib/Sema/SemaType.cpp Fri Mar 29 11:47:07 2019
@@ -255,6 +255,23 @@ namespace {
   return T;
 }
 
+/// Completely replace the \c auto in \p TypeWithAuto by
+/// \p Replacement. Also replace \p TypeWithAuto in \c TypeAttrPair if
+/// necessary.
+QualType ReplaceAutoType(QualType TypeWithAuto, QualType Replacement) {
+  QualType T = sema.ReplaceAutoType(TypeWithAuto, Replacement);
+  if (auto *AttrTy = TypeWithAuto->getAs()) {
+// Attributed type still should be an attributed type after 
replacement.
+auto *NewAttrTy = cast(T.getTypePtr());
+for (TypeAttrPair  : AttrsForTypes) {
+  if (A.first == AttrTy)
+A.first = NewAttrTy;
+}
+AttrsForTypesSorted = false;
+  }
+  return T;
+}
+
 /// Extract and remove the Attr* for a given attributed type.
 const Attr *takeAttrForAttributedType(const AttributedType *AT) {
   if (!AttrsForTypesSorted) {
@@ -2938,7 +2955,7 @@ static QualType GetDeclSpecTypeForDeclar
 // template type parameter.
 // FIXME: Retain some type sugar to indicate that this was written
 // as 'auto'.
-T = SemaRef.ReplaceAutoType(
+T = state.ReplaceAutoType(
 T, QualType(CorrespondingTemplateParam->getTypeForDecl(), 0));
   }
   break;

Modified: cfe/trunk/test/SemaCXX/auto-cxx0x.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/SemaCXX/auto-cxx0x.cpp?rev=357298=357297=357298=diff
==
--- cfe/trunk/test/SemaCXX/auto-cxx0x.cpp (original)
+++ cfe/trunk/test/SemaCXX/auto-cxx0x.cpp Fri Mar 29 11:47:07 2019
@@ -15,3 +15,11 @@ void g() {
   // expected-error@-2 {{'auto' not allowed in lambda parameter}}
 #endif
 }
+
+void rdar47689465() {
+  int x = 0;
+  [](auto __attribute__((noderef)) *){}();
+#if __cplusplus == 201103L
+  // expected-error@-2 {{'auto' not allowed in lambda parameter}}
+#endif
+}


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


[PATCH] D58659: [Sema] Fix assertion when `auto` parameter in lambda has an attribute.

2019-03-29 Thread Volodymyr Sapsai via Phabricator via cfe-commits
vsapsai added a comment.

Thanks for the review, Aaron.


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

https://reviews.llvm.org/D58659



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


[PATCH] D58675: [clang] Adds `-ftime-trace` option to clang that produces Chrome `chrome://tracing` compatible JSON profiling output dumps

2019-03-29 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

I think this is ready. We can adjust the overloads after the fact. I'd like to 
get the feature in so we can make improvements independently.




Comment at: clang/lib/Parse/ParseAST.cpp:154
   if (HaveLexer) {
+llvm::TimeTraceScope TimeScope("Frontend", StringRef(""));
 P.Initialize();

anton-afanasyev wrote:
> takuto.ikuta wrote:
> > anton-afanasyev wrote:
> > > takuto.ikuta wrote:
> > > > Remove StringRef?
> > > I use `StringRef("")` to explicitly cast to one of overloaded 
> > > `TimeScope(StringRef, StringRef)` and `TimeScope(StringRef, 
> > > fuction_ref(std::string()))`.
> > I think function_ref(std::string()) does not have constructor receiving 
> > StringRef, so I feel explicit cast is redundant.
> > 
> The compiler tries to use function_ref<..>(Callable&&, ...) constructor and 
> instantiates `function_ref::function_ref`, 
> so one gets error like:
> ```
> error: call to constructor of 'llvm::TimeTraceScope' is ambiguous
> llvm::TimeTraceScope TimeScope("Frontend", "");
>  ^ ~~
> .../include/llvm/Support/TimeProfiler.h:54:3: note: candidate constructor
>   TimeTraceScope(StringRef Name, StringRef Detail) {
>   ^
> .../include/llvm/Support/TimeProfiler.h:58:3: note: candidate constructor
>   TimeTraceScope(StringRef Name, llvm::function_ref Detail) {
>   ^
> 
> ```
Oh no. We are too clever for ourselves. :(

So, we'd need to make the enable_if logic in the function_ref constructor more 
clever to prevent it from being instantiated for non-callables.


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

https://reviews.llvm.org/D58675



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


[PATCH] D53344: [Driver] Use --warn-shared-textrel for Android.

2019-03-29 Thread Dan Albert via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rC357296: [Driver] Use --warn-shared-textrel for Android. 
(authored by danalbert, committed by ).

Changed prior to commit:
  https://reviews.llvm.org/D53344?vs=169903=192874#toc

Repository:
  rC Clang

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

https://reviews.llvm.org/D53344

Files:
  lib/Driver/ToolChains/Gnu.cpp
  test/Driver/linux-ld.c


Index: test/Driver/linux-ld.c
===
--- test/Driver/linux-ld.c
+++ test/Driver/linux-ld.c
@@ -1006,7 +1006,13 @@
 // CHECK-ANDROID-NOEXECSTACK-NOT: "-z" "execstack"
 // CHECK-ANDROID-NOEXECSTACK-NOT: "-z,execstack"
 // CHECK-ANDROID-NOEXECSTACK-NOT: "-zexecstack"
-//
+
++// RUN: %clang %s -### -o %t.o 2>&1 \
++// RUN: --target=armv7-linux-android21 \
++// RUN:   | FileCheck --check-prefix=CHECK-ANDROID-WARN-SHARED-TEXTREL %s
++// CHECK-ANDROID-WARN-SHARED-TEXTREL: "{{.*}}ld{{(.exe)?}}"
++// CHECK-ANDROID-WARN-SHARED-TEXTREL: "--warn-shared-textrel"
+
 // RUN: %clang %s -### -o %t.o 2>&1 --target=mips64-linux-gnuabin32 \
 // RUN:   | FileCheck --check-prefix=CHECK-MIPS64EL-GNUABIN32 %s
 // CHECK-MIPS64EL-GNUABIN32: "{{.*}}ld{{(.exe)?}}"
Index: lib/Driver/ToolChains/Gnu.cpp
===
--- lib/Driver/ToolChains/Gnu.cpp
+++ lib/Driver/ToolChains/Gnu.cpp
@@ -387,6 +387,11 @@
   CmdArgs.push_back("--fix-cortex-a53-843419");
   }
 
+  // Android does not allow shared text relocations. Emit a warning if the
+  // user's code contains any.
+  if (isAndroid)
+  CmdArgs.push_back("--warn-shared-textrel");
+
   for (const auto  : ToolChain.ExtraOpts)
 CmdArgs.push_back(Opt.c_str());
 


Index: test/Driver/linux-ld.c
===
--- test/Driver/linux-ld.c
+++ test/Driver/linux-ld.c
@@ -1006,7 +1006,13 @@
 // CHECK-ANDROID-NOEXECSTACK-NOT: "-z" "execstack"
 // CHECK-ANDROID-NOEXECSTACK-NOT: "-z,execstack"
 // CHECK-ANDROID-NOEXECSTACK-NOT: "-zexecstack"
-//
+
++// RUN: %clang %s -### -o %t.o 2>&1 \
++// RUN: --target=armv7-linux-android21 \
++// RUN:   | FileCheck --check-prefix=CHECK-ANDROID-WARN-SHARED-TEXTREL %s
++// CHECK-ANDROID-WARN-SHARED-TEXTREL: "{{.*}}ld{{(.exe)?}}"
++// CHECK-ANDROID-WARN-SHARED-TEXTREL: "--warn-shared-textrel"
+
 // RUN: %clang %s -### -o %t.o 2>&1 --target=mips64-linux-gnuabin32 \
 // RUN:   | FileCheck --check-prefix=CHECK-MIPS64EL-GNUABIN32 %s
 // CHECK-MIPS64EL-GNUABIN32: "{{.*}}ld{{(.exe)?}}"
Index: lib/Driver/ToolChains/Gnu.cpp
===
--- lib/Driver/ToolChains/Gnu.cpp
+++ lib/Driver/ToolChains/Gnu.cpp
@@ -387,6 +387,11 @@
   CmdArgs.push_back("--fix-cortex-a53-843419");
   }
 
+  // Android does not allow shared text relocations. Emit a warning if the
+  // user's code contains any.
+  if (isAndroid)
+  CmdArgs.push_back("--warn-shared-textrel");
+
   for (const auto  : ToolChain.ExtraOpts)
 CmdArgs.push_back(Opt.c_str());
 
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


r357296 - [Driver] Use --warn-shared-textrel for Android.

2019-03-29 Thread Dan Albert via cfe-commits
Author: danalbert
Date: Fri Mar 29 11:34:25 2019
New Revision: 357296

URL: http://llvm.org/viewvc/llvm-project?rev=357296=rev
Log:
[Driver] Use --warn-shared-textrel for Android.

Android does not allow shared text relocations. Enable the linker
warning to detect them by default.

Reviewers: srhines, pirama

Reviewed By: srhines

Subscribers: cfe-commits

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

Modified:
cfe/trunk/lib/Driver/ToolChains/Gnu.cpp
cfe/trunk/test/Driver/linux-ld.c

Modified: cfe/trunk/lib/Driver/ToolChains/Gnu.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Driver/ToolChains/Gnu.cpp?rev=357296=357295=357296=diff
==
--- cfe/trunk/lib/Driver/ToolChains/Gnu.cpp (original)
+++ cfe/trunk/lib/Driver/ToolChains/Gnu.cpp Fri Mar 29 11:34:25 2019
@@ -387,6 +387,11 @@ void tools::gnutools::Linker::ConstructJ
   CmdArgs.push_back("--fix-cortex-a53-843419");
   }
 
+  // Android does not allow shared text relocations. Emit a warning if the
+  // user's code contains any.
+  if (isAndroid)
+  CmdArgs.push_back("--warn-shared-textrel");
+
   for (const auto  : ToolChain.ExtraOpts)
 CmdArgs.push_back(Opt.c_str());
 

Modified: cfe/trunk/test/Driver/linux-ld.c
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/Driver/linux-ld.c?rev=357296=357295=357296=diff
==
--- cfe/trunk/test/Driver/linux-ld.c (original)
+++ cfe/trunk/test/Driver/linux-ld.c Fri Mar 29 11:34:25 2019
@@ -1006,7 +1006,13 @@
 // CHECK-ANDROID-NOEXECSTACK-NOT: "-z" "execstack"
 // CHECK-ANDROID-NOEXECSTACK-NOT: "-z,execstack"
 // CHECK-ANDROID-NOEXECSTACK-NOT: "-zexecstack"
-//
+
++// RUN: %clang %s -### -o %t.o 2>&1 \
++// RUN: --target=armv7-linux-android21 \
++// RUN:   | FileCheck --check-prefix=CHECK-ANDROID-WARN-SHARED-TEXTREL %s
++// CHECK-ANDROID-WARN-SHARED-TEXTREL: "{{.*}}ld{{(.exe)?}}"
++// CHECK-ANDROID-WARN-SHARED-TEXTREL: "--warn-shared-textrel"
+
 // RUN: %clang %s -### -o %t.o 2>&1 --target=mips64-linux-gnuabin32 \
 // RUN:   | FileCheck --check-prefix=CHECK-MIPS64EL-GNUABIN32 %s
 // CHECK-MIPS64EL-GNUABIN32: "{{.*}}ld{{(.exe)?}}"


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


[PATCH] D59827: [slh] x86 impl of ARM instrinsic for SLH

2019-03-29 Thread Zola Bridges via Phabricator via cfe-commits
zbrid updated this revision to Diff 192873.
zbrid marked an inline comment as done.
zbrid added a comment.

actually fix if statement


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D59827

Files:
  clang/include/clang/Basic/Builtins.def
  clang/include/clang/Basic/DiagnosticSemaKinds.td
  clang/include/clang/Sema/Sema.h
  clang/lib/CodeGen/CGBuiltin.cpp
  clang/lib/Frontend/InitPreprocessor.cpp
  clang/lib/Sema/SemaChecking.cpp
  clang/test/CodeGen/builtin-speculation-safe-value.c
  clang/test/Preprocessor/init.c
  llvm/docs/LangRef.rst
  llvm/include/llvm/CodeGen/ISDOpcodes.h
  llvm/include/llvm/IR/Intrinsics.td
  llvm/include/llvm/Target/TargetSelectionDAG.td
  llvm/lib/CodeGen/SelectionDAG/LegalizeIntegerTypes.cpp
  llvm/lib/CodeGen/SelectionDAG/LegalizeTypes.h
  llvm/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp
  llvm/lib/CodeGen/SelectionDAG/SelectionDAGDumper.cpp
  llvm/lib/Target/X86/X86ISelLowering.cpp
  llvm/lib/Target/X86/X86ISelLowering.h
  llvm/lib/Target/X86/X86InstrInfo.td
  llvm/lib/Target/X86/X86SpeculativeLoadHardening.cpp
  llvm/test/CodeGen/X86/speculative-load-hardening-intrinsic.ll

Index: llvm/test/CodeGen/X86/speculative-load-hardening-intrinsic.ll
===
--- /dev/null
+++ llvm/test/CodeGen/X86/speculative-load-hardening-intrinsic.ll
@@ -0,0 +1,71 @@
+; RUN: llc < %s -mtriple=x86_64-unknown-linux-gnu | FileCheck %s --check-prefix=X64
+
+; ModuleID = 'hello.cpp'
+source_filename = "hello.cpp"
+target datalayout = "e-m:e-i64:64-f80:128-n8:16:32:64-S128"
+target triple = "x86_64-unknown-linux-gnu"
+
+; Function Attrs: noinline nounwind optnone uwtable
+define dso_local i32 @_Z5foo32i(i32 %a) #0 {
+entry:
+  %a.addr = alloca i32, align 4
+  %b = alloca i32, align 4
+  %b_safe = alloca i32, align 4
+  %c = alloca i32, align 4
+  store i32 %a, i32* %a.addr, align 4
+  %0 = load i32, i32* %a.addr, align 4
+  %mul = mul nsw i32 %0, 100
+  store i32 %mul, i32* %b, align 4
+  %1 = load i32, i32* %b, align 4
+  %2 = call i32 @llvm.speculationsafevalue.i32(i32 %1)
+; X64: movl -12(%rbp), %eax
+; X64: lfence
+; X64: movl %eax, -8(%rbp)
+  store i32 %2, i32* %b_safe, align 4
+  %3 = load i32, i32* %b_safe, align 4
+  %add = add nsw i32 %3, 100
+  store i32 %add, i32* %c, align 4
+  %4 = load i32, i32* %c, align 4
+  ret i32 %4
+}
+
+; Function Attrs: nounwind
+declare i32 @llvm.speculationsafevalue.i32(i32) #1
+
+; Function Attrs: noinline nounwind optnone uwtable
+define dso_local i32 @_Z5foo64i(i32 %a) #0 {
+entry:
+  %a.addr = alloca i32, align 4
+  %b = alloca i64, align 8
+  %b_safe = alloca i64, align 8
+  %c = alloca i64, align 8
+  store i32 %a, i32* %a.addr, align 4
+  %0 = load i32, i32* %a.addr, align 4
+  %mul = mul nsw i32 %0, 100
+  %conv = sext i32 %mul to i64
+  store i64 %conv, i64* %b, align 8
+  %1 = load i64, i64* %b, align 8
+  %2 = call i64 @llvm.speculationsafevalue.i64(i64 %1)
+; X64: movq -32(%rbp), %rax
+; X64: lfence
+; X64: movq %rax, -24(%rbp)
+  store i64 %2, i64* %b_safe, align 8
+  %3 = load i64, i64* %b_safe, align 8
+  %add = add nsw i64 %3, 100
+  store i64 %add, i64* %c, align 8
+  %4 = load i64, i64* %c, align 8
+  %conv1 = trunc i64 %4 to i32
+  ret i32 %conv1
+}
+
+; Function Attrs: nounwind
+declare i64 @llvm.speculationsafevalue.i64(i64) #1
+
+attributes #0 = { noinline nounwind optnone uwtable "correctly-rounded-divide-sqrt-fp-math"="false" "disable-tail-calls"="false" "less-precise-fpmad"="false" "min-legal-vector-width"="0" "no-frame-pointer-elim"="true" "no-frame-pointer-elim-non-leaf" "no-infs-fp-math"="false" "no-jump-tables"="false" "no-nans-fp-math"="false" "no-signed-zeros-fp-math"="false" "no-trapping-math"="false" "stack-protector-buffer-size"="8" "target-cpu"="x86-64" "target-features"="+fxsr,+mmx,+sse,+sse2,+x87" "unsafe-fp-math"="false" "use-soft-float"="false" }
+attributes #1 = { nounwind }
+
+!llvm.module.flags = !{!0}
+!llvm.ident = !{!1}
+
+!0 = !{i32 1, !"wchar_size", i32 4}
+!1 = !{!"clang version 9.0.0 (https://github.com/llvm/llvm-project.git 6fd90b5505fe7cddd0fd798fe9608ea0e0325302)"}
Index: llvm/lib/Target/X86/X86SpeculativeLoadHardening.cpp
===
--- llvm/lib/Target/X86/X86SpeculativeLoadHardening.cpp
+++ llvm/lib/Target/X86/X86SpeculativeLoadHardening.cpp
@@ -212,6 +212,7 @@
   void hardenIndirectCallOrJumpInstr(
   MachineInstr ,
   SmallDenseMap );
+  bool lowerIntrinsic(MachineFunction );
 };
 
 } // end anonymous namespace
@@ -402,16 +403,20 @@
   LLVM_DEBUG(dbgs() << "** " << getPassName() << " : " << MF.getName()
 << " **\n");
 
-  // Only run if this pass is forced enabled or we detect the relevant function
-  // attribute requesting SLH.
-  if (!EnableSpeculativeLoadHardening &&
-  !MF.getFunction().hasFnAttribute(Attribute::SpeculativeLoadHardening))
-return 

[PATCH] D59827: [slh] x86 impl of ARM instrinsic for SLH

2019-03-29 Thread Zola Bridges via Phabricator via cfe-commits
zbrid marked 2 inline comments as done.
zbrid added inline comments.



Comment at: llvm/lib/Target/X86/X86SpeculativeLoadHardening.cpp:614-628
+  if (Opcode == X86::SpeculationSafeValue32) {
+BuildMI(MBB, NMBBI, DebugLoc(), TII->get(X86::LFENCE));
+++NumInstsInserted;
+++NumLFENCEsInserted;
+MRI->replaceRegWith(MI.getOperand(0).getReg(), 
MI.getOperand(1).getReg());
+MI.eraseFromParent();
+Modified = true;

kristof.beyls wrote:
> The lowering of the intrinsic on a 32 bit and a 64 bit value looks identical 
> to me, so the if statement isn't needed?
Good catch. 


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D59827



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


[PATCH] D59827: [slh] x86 impl of ARM instrinsic for SLH

2019-03-29 Thread Zola Bridges via Phabricator via cfe-commits
zbrid updated this revision to Diff 192870.
zbrid added a comment.

remove unnecessary if in x86 slh intrinsic lowering function


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D59827

Files:
  clang/include/clang/Basic/Builtins.def
  clang/include/clang/Basic/DiagnosticSemaKinds.td
  clang/include/clang/Sema/Sema.h
  clang/lib/CodeGen/CGBuiltin.cpp
  clang/lib/Frontend/InitPreprocessor.cpp
  clang/lib/Sema/SemaChecking.cpp
  clang/test/CodeGen/builtin-speculation-safe-value.c
  clang/test/Preprocessor/init.c
  llvm/docs/LangRef.rst
  llvm/include/llvm/CodeGen/ISDOpcodes.h
  llvm/include/llvm/IR/Intrinsics.td
  llvm/include/llvm/Target/TargetSelectionDAG.td
  llvm/lib/CodeGen/SelectionDAG/LegalizeIntegerTypes.cpp
  llvm/lib/CodeGen/SelectionDAG/LegalizeTypes.h
  llvm/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp
  llvm/lib/CodeGen/SelectionDAG/SelectionDAGDumper.cpp
  llvm/lib/Target/X86/X86ISelLowering.cpp
  llvm/lib/Target/X86/X86ISelLowering.h
  llvm/lib/Target/X86/X86InstrInfo.td
  llvm/lib/Target/X86/X86SpeculativeLoadHardening.cpp
  llvm/test/CodeGen/X86/speculative-load-hardening-intrinsic.ll

Index: llvm/test/CodeGen/X86/speculative-load-hardening-intrinsic.ll
===
--- /dev/null
+++ llvm/test/CodeGen/X86/speculative-load-hardening-intrinsic.ll
@@ -0,0 +1,71 @@
+; RUN: llc < %s -mtriple=x86_64-unknown-linux-gnu | FileCheck %s --check-prefix=X64
+
+; ModuleID = 'hello.cpp'
+source_filename = "hello.cpp"
+target datalayout = "e-m:e-i64:64-f80:128-n8:16:32:64-S128"
+target triple = "x86_64-unknown-linux-gnu"
+
+; Function Attrs: noinline nounwind optnone uwtable
+define dso_local i32 @_Z5foo32i(i32 %a) #0 {
+entry:
+  %a.addr = alloca i32, align 4
+  %b = alloca i32, align 4
+  %b_safe = alloca i32, align 4
+  %c = alloca i32, align 4
+  store i32 %a, i32* %a.addr, align 4
+  %0 = load i32, i32* %a.addr, align 4
+  %mul = mul nsw i32 %0, 100
+  store i32 %mul, i32* %b, align 4
+  %1 = load i32, i32* %b, align 4
+  %2 = call i32 @llvm.speculationsafevalue.i32(i32 %1)
+; X64: movl -12(%rbp), %eax
+; X64: lfence
+; X64: movl %eax, -8(%rbp)
+  store i32 %2, i32* %b_safe, align 4
+  %3 = load i32, i32* %b_safe, align 4
+  %add = add nsw i32 %3, 100
+  store i32 %add, i32* %c, align 4
+  %4 = load i32, i32* %c, align 4
+  ret i32 %4
+}
+
+; Function Attrs: nounwind
+declare i32 @llvm.speculationsafevalue.i32(i32) #1
+
+; Function Attrs: noinline nounwind optnone uwtable
+define dso_local i32 @_Z5foo64i(i32 %a) #0 {
+entry:
+  %a.addr = alloca i32, align 4
+  %b = alloca i64, align 8
+  %b_safe = alloca i64, align 8
+  %c = alloca i64, align 8
+  store i32 %a, i32* %a.addr, align 4
+  %0 = load i32, i32* %a.addr, align 4
+  %mul = mul nsw i32 %0, 100
+  %conv = sext i32 %mul to i64
+  store i64 %conv, i64* %b, align 8
+  %1 = load i64, i64* %b, align 8
+  %2 = call i64 @llvm.speculationsafevalue.i64(i64 %1)
+; X64: movq -32(%rbp), %rax
+; X64: lfence
+; X64: movq %rax, -24(%rbp)
+  store i64 %2, i64* %b_safe, align 8
+  %3 = load i64, i64* %b_safe, align 8
+  %add = add nsw i64 %3, 100
+  store i64 %add, i64* %c, align 8
+  %4 = load i64, i64* %c, align 8
+  %conv1 = trunc i64 %4 to i32
+  ret i32 %conv1
+}
+
+; Function Attrs: nounwind
+declare i64 @llvm.speculationsafevalue.i64(i64) #1
+
+attributes #0 = { noinline nounwind optnone uwtable "correctly-rounded-divide-sqrt-fp-math"="false" "disable-tail-calls"="false" "less-precise-fpmad"="false" "min-legal-vector-width"="0" "no-frame-pointer-elim"="true" "no-frame-pointer-elim-non-leaf" "no-infs-fp-math"="false" "no-jump-tables"="false" "no-nans-fp-math"="false" "no-signed-zeros-fp-math"="false" "no-trapping-math"="false" "stack-protector-buffer-size"="8" "target-cpu"="x86-64" "target-features"="+fxsr,+mmx,+sse,+sse2,+x87" "unsafe-fp-math"="false" "use-soft-float"="false" }
+attributes #1 = { nounwind }
+
+!llvm.module.flags = !{!0}
+!llvm.ident = !{!1}
+
+!0 = !{i32 1, !"wchar_size", i32 4}
+!1 = !{!"clang version 9.0.0 (https://github.com/llvm/llvm-project.git 6fd90b5505fe7cddd0fd798fe9608ea0e0325302)"}
Index: llvm/lib/Target/X86/X86SpeculativeLoadHardening.cpp
===
--- llvm/lib/Target/X86/X86SpeculativeLoadHardening.cpp
+++ llvm/lib/Target/X86/X86SpeculativeLoadHardening.cpp
@@ -212,6 +212,7 @@
   void hardenIndirectCallOrJumpInstr(
   MachineInstr ,
   SmallDenseMap );
+  bool lowerIntrinsic(MachineFunction );
 };
 
 } // end anonymous namespace
@@ -402,16 +403,20 @@
   LLVM_DEBUG(dbgs() << "** " << getPassName() << " : " << MF.getName()
 << " **\n");
 
-  // Only run if this pass is forced enabled or we detect the relevant function
-  // attribute requesting SLH.
-  if (!EnableSpeculativeLoadHardening &&
-  !MF.getFunction().hasFnAttribute(Attribute::SpeculativeLoadHardening))
-return false;
-

[PATCH] D57660: [Sema] SequenceChecker: Handle references, members and structured bindings.

2019-03-29 Thread Bruno Ricci via Phabricator via cfe-commits
riccibruno added a comment.
Herald added a subscriber: dexonsmith.

Ping.


Repository:
  rC Clang

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

https://reviews.llvm.org/D57660



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


[PATCH] D59725: Additions to creduce script

2019-03-29 Thread George Burgess IV via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rL357290: Various fixes and additions to 
creduce-clang-crash.py (authored by gbiv, committed by ).
Herald added a project: LLVM.
Herald added a subscriber: llvm-commits.

Changed prior to commit:
  https://reviews.llvm.org/D59725?vs=192846=192867#toc

Repository:
  rL LLVM

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

https://reviews.llvm.org/D59725

Files:
  cfe/trunk/utils/creduce-clang-crash.py

Index: cfe/trunk/utils/creduce-clang-crash.py
===
--- cfe/trunk/utils/creduce-clang-crash.py
+++ cfe/trunk/utils/creduce-clang-crash.py
@@ -1,8 +1,14 @@
 #!/usr/bin/env python
 """Calls C-Reduce to create a minimal reproducer for clang crashes.
+
+Output files:
+  *.reduced.sh -- crash reproducer with minimal arguments
+  *.reduced.cpp -- the reduced file
+  *.test.sh -- interestingness test for C-Reduce
 """
 
-from argparse import ArgumentParser
+from __future__ import print_function
+from argparse import ArgumentParser, RawTextHelpFormatter
 import os
 import re
 import stat
@@ -15,10 +21,14 @@
 from distutils.spawn import find_executable
 
 verbose = False
-llvm_bin = None
 creduce_cmd = None
+clang_cmd = None
 not_cmd = None
 
+def verbose_print(*args, **kwargs):
+  if verbose:
+print(*args, **kwargs)
+
 def check_file(fname):
   if not os.path.isfile(fname):
 sys.exit("ERROR: %s does not exist" % (fname))
@@ -33,166 +43,339 @@
 cmd = find_executable(cmd_path)
 if cmd:
   return cmd
-sys.exit("ERROR: executable %s not found" % (cmd_path))
+sys.exit("ERROR: executable `%s` not found" % (cmd_path))
 
   cmd = find_executable(cmd_name, path=cmd_dir)
   if cmd:
 return cmd
-  sys.exit("ERROR: %s not found in %s" % (cmd_name, cmd_dir))
 
-def quote_cmd(cmd):
-  return ' '.join(arg if arg.startswith('$') else pipes.quote(arg)
-  for arg in cmd)
+  if not cmd_dir:
+cmd_dir = "$PATH"
+  sys.exit("ERROR: `%s` not found in %s" % (cmd_name, cmd_dir))
 
-def get_crash_cmd(crash_script):
-  with open(crash_script) as f:
-# Assume clang call is on the last line of the script
-line = f.readlines()[-1]
-cmd = shlex.split(line)
-
-# Overwrite the script's clang with the user's clang path
-new_clang = check_cmd('clang', llvm_bin)
-cmd[0] = pipes.quote(new_clang)
-return cmd
+def quote_cmd(cmd):
+  return ' '.join(pipes.quote(arg) for arg in cmd)
 
-def has_expected_output(crash_cmd, expected_output):
-  p = subprocess.Popen(crash_cmd,
-   stdout=subprocess.PIPE,
-   stderr=subprocess.STDOUT)
-  crash_output, _ = p.communicate()
-  return all(msg in crash_output for msg in expected_output)
-
-def get_expected_output(crash_cmd):
-  p = subprocess.Popen(crash_cmd,
-   stdout=subprocess.PIPE,
-   stderr=subprocess.STDOUT)
-  crash_output, _ = p.communicate()
-
-  # If there is an assertion failure, use that;
-  # otherwise use the last five stack trace functions
-  assertion_re = r'Assertion `([^\']+)\' failed'
-  assertion_match = re.search(assertion_re, crash_output)
-  if assertion_match:
-return [assertion_match.group(1)]
-  else:
-stacktrace_re = r'#[0-9]+\s+0[xX][0-9a-fA-F]+\s*([^(]+)\('
-matches = re.findall(stacktrace_re, crash_output)
-return matches[-5:]
-
-def write_interestingness_test(testfile, crash_cmd, expected_output,
-   file_to_reduce):
-  filename = os.path.basename(file_to_reduce)
-  if filename not in crash_cmd:
-sys.exit("ERROR: expected %s to be in the crash command" % filename)
-
-  # Replace all instances of file_to_reduce with a command line variable
-  output = ['#!/bin/bash',
-'if [ -z "$1" ] ; then',
-'  f=%s' % (pipes.quote(filename)),
-'else',
-'  f="$1"',
-'fi']
-  cmd = ['$f' if s == filename else s for s in crash_cmd]
-
-  output.append('%s --crash %s >& t.log || exit 1' % (pipes.quote(not_cmd),
-  quote_cmd(cmd)))
-
-  for msg in expected_output:
-output.append('grep %s t.log || exit 1' % pipes.quote(msg))
-
-  with open(testfile, 'w') as f:
-f.write('\n'.join(output))
-  os.chmod(testfile, os.stat(testfile).st_mode | stat.S_IEXEC)
-
-def check_interestingness(testfile, file_to_reduce):
-  testfile = os.path.abspath(testfile)
-
-  # Check that the test considers the original file interesting
-  with open(os.devnull, 'w') as devnull:
-returncode = subprocess.call(testfile, stdout=devnull)
-  if returncode:
-sys.exit("The interestingness test does not pass for the original file.")
-
-  # Check that an empty file is not interesting
-  _, empty_file = tempfile.mkstemp()
-  with open(os.devnull, 'w') as devnull:
-returncode = subprocess.call([testfile, empty_file], stdout=devnull)
-  

r357290 - Various fixes and additions to creduce-clang-crash.py

2019-03-29 Thread George Burgess IV via cfe-commits
Author: gbiv
Date: Fri Mar 29 10:50:43 2019
New Revision: 357290

URL: http://llvm.org/viewvc/llvm-project?rev=357290=rev
Log:
Various fixes and additions to creduce-clang-crash.py

Some more additions to the script - mainly reducing the clang args after
the creduce run by removing them one by one and seeing if the crash
reproduces. Other things:

- remove the --crash flag when "fatal error" occurs
- fixed to read stack trace functions from the top
- run creduce on a copy of the original file

Patch by Amy Huang!

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

Modified:
cfe/trunk/utils/creduce-clang-crash.py

Modified: cfe/trunk/utils/creduce-clang-crash.py
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/utils/creduce-clang-crash.py?rev=357290=357289=357290=diff
==
--- cfe/trunk/utils/creduce-clang-crash.py (original)
+++ cfe/trunk/utils/creduce-clang-crash.py Fri Mar 29 10:50:43 2019
@@ -1,8 +1,14 @@
 #!/usr/bin/env python
 """Calls C-Reduce to create a minimal reproducer for clang crashes.
+
+Output files:
+  *.reduced.sh -- crash reproducer with minimal arguments
+  *.reduced.cpp -- the reduced file
+  *.test.sh -- interestingness test for C-Reduce
 """
 
-from argparse import ArgumentParser
+from __future__ import print_function
+from argparse import ArgumentParser, RawTextHelpFormatter
 import os
 import re
 import stat
@@ -15,10 +21,14 @@ import shutil
 from distutils.spawn import find_executable
 
 verbose = False
-llvm_bin = None
 creduce_cmd = None
+clang_cmd = None
 not_cmd = None
 
+def verbose_print(*args, **kwargs):
+  if verbose:
+print(*args, **kwargs)
+
 def check_file(fname):
   if not os.path.isfile(fname):
 sys.exit("ERROR: %s does not exist" % (fname))
@@ -33,166 +43,339 @@ def check_cmd(cmd_name, cmd_dir, cmd_pat
 cmd = find_executable(cmd_path)
 if cmd:
   return cmd
-sys.exit("ERROR: executable %s not found" % (cmd_path))
+sys.exit("ERROR: executable `%s` not found" % (cmd_path))
 
   cmd = find_executable(cmd_name, path=cmd_dir)
   if cmd:
 return cmd
-  sys.exit("ERROR: %s not found in %s" % (cmd_name, cmd_dir))
 
-def quote_cmd(cmd):
-  return ' '.join(arg if arg.startswith('$') else pipes.quote(arg)
-  for arg in cmd)
+  if not cmd_dir:
+cmd_dir = "$PATH"
+  sys.exit("ERROR: `%s` not found in %s" % (cmd_name, cmd_dir))
 
-def get_crash_cmd(crash_script):
-  with open(crash_script) as f:
-# Assume clang call is on the last line of the script
-line = f.readlines()[-1]
-cmd = shlex.split(line)
-
-# Overwrite the script's clang with the user's clang path
-new_clang = check_cmd('clang', llvm_bin)
-cmd[0] = pipes.quote(new_clang)
-return cmd
+def quote_cmd(cmd):
+  return ' '.join(pipes.quote(arg) for arg in cmd)
 
-def has_expected_output(crash_cmd, expected_output):
-  p = subprocess.Popen(crash_cmd,
-   stdout=subprocess.PIPE,
-   stderr=subprocess.STDOUT)
-  crash_output, _ = p.communicate()
-  return all(msg in crash_output for msg in expected_output)
-
-def get_expected_output(crash_cmd):
-  p = subprocess.Popen(crash_cmd,
-   stdout=subprocess.PIPE,
-   stderr=subprocess.STDOUT)
-  crash_output, _ = p.communicate()
-
-  # If there is an assertion failure, use that;
-  # otherwise use the last five stack trace functions
-  assertion_re = r'Assertion `([^\']+)\' failed'
-  assertion_match = re.search(assertion_re, crash_output)
-  if assertion_match:
-return [assertion_match.group(1)]
-  else:
-stacktrace_re = r'#[0-9]+\s+0[xX][0-9a-fA-F]+\s*([^(]+)\('
-matches = re.findall(stacktrace_re, crash_output)
-return matches[-5:]
-
-def write_interestingness_test(testfile, crash_cmd, expected_output,
-   file_to_reduce):
-  filename = os.path.basename(file_to_reduce)
-  if filename not in crash_cmd:
-sys.exit("ERROR: expected %s to be in the crash command" % filename)
-
-  # Replace all instances of file_to_reduce with a command line variable
-  output = ['#!/bin/bash',
-'if [ -z "$1" ] ; then',
-'  f=%s' % (pipes.quote(filename)),
-'else',
-'  f="$1"',
-'fi']
-  cmd = ['$f' if s == filename else s for s in crash_cmd]
-
-  output.append('%s --crash %s >& t.log || exit 1' % (pipes.quote(not_cmd),
-  quote_cmd(cmd)))
-
-  for msg in expected_output:
-output.append('grep %s t.log || exit 1' % pipes.quote(msg))
-
-  with open(testfile, 'w') as f:
-f.write('\n'.join(output))
-  os.chmod(testfile, os.stat(testfile).st_mode | stat.S_IEXEC)
-
-def check_interestingness(testfile, file_to_reduce):
-  testfile = os.path.abspath(testfile)
-
-  # Check that the test considers the original file interesting
-  with open(os.devnull, 'w') as devnull:
-returncode = 

[PATCH] D59008: [AMDGPU] Switch default dwarf version to 5

2019-03-29 Thread Scott Linder via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rC357285: [AMDGPU] Switch default DWARF version to 5 (authored 
by scott.linder, committed by ).

Repository:
  rC Clang

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

https://reviews.llvm.org/D59008

Files:
  lib/Driver/ToolChains/AMDGPU.h
  test/Driver/amdgpu-toolchain.c
  test/Driver/split-debug.c


Index: test/Driver/split-debug.c
===
--- test/Driver/split-debug.c
+++ test/Driver/split-debug.c
@@ -38,6 +38,9 @@
 // RUN: %clang -target x86_64-pc-freebsd12 -gsplit-dwarf -c -### %s 2> %t
 // RUN: FileCheck -check-prefix=CHECK-OPTION < %t %s
 //
+// RUN: %clang -target amdgcn-amd-amdhsa -gsplit-dwarf -c -### %s 2> %t
+// RUN: FileCheck -check-prefix=CHECK-OPTION < %t %s
+//
 // CHECK-OPTION: "-split-dwarf-file" "split-debug.dwo"
 
 // RUN: %clang -target x86_64-unknown-linux-gnu -gsplit-dwarf -S -### %s 2> %t
Index: test/Driver/amdgpu-toolchain.c
===
--- test/Driver/amdgpu-toolchain.c
+++ test/Driver/amdgpu-toolchain.c
@@ -3,4 +3,4 @@
 // AS_LINK: ld.lld{{.*}} "-shared"
 
 // RUN: %clang -### -g -target amdgcn--amdhsa -mcpu=kaveri %s 2>&1 | FileCheck 
-check-prefix=DWARF_VER %s
-// DWARF_VER: "-dwarf-version=2"
+// DWARF_VER: "-dwarf-version=5"
Index: lib/Driver/ToolChains/AMDGPU.h
===
--- lib/Driver/ToolChains/AMDGPU.h
+++ lib/Driver/ToolChains/AMDGPU.h
@@ -55,7 +55,7 @@
 public:
   AMDGPUToolChain(const Driver , const llvm::Triple ,
   const llvm::opt::ArgList );
-  unsigned GetDefaultDwarfVersion() const override { return 2; }
+  unsigned GetDefaultDwarfVersion() const override { return 5; }
   bool IsIntegratedAssemblerDefault() const override { return true; }
   llvm::opt::DerivedArgList *
   TranslateArgs(const llvm::opt::DerivedArgList , StringRef BoundArch,


Index: test/Driver/split-debug.c
===
--- test/Driver/split-debug.c
+++ test/Driver/split-debug.c
@@ -38,6 +38,9 @@
 // RUN: %clang -target x86_64-pc-freebsd12 -gsplit-dwarf -c -### %s 2> %t
 // RUN: FileCheck -check-prefix=CHECK-OPTION < %t %s
 //
+// RUN: %clang -target amdgcn-amd-amdhsa -gsplit-dwarf -c -### %s 2> %t
+// RUN: FileCheck -check-prefix=CHECK-OPTION < %t %s
+//
 // CHECK-OPTION: "-split-dwarf-file" "split-debug.dwo"
 
 // RUN: %clang -target x86_64-unknown-linux-gnu -gsplit-dwarf -S -### %s 2> %t
Index: test/Driver/amdgpu-toolchain.c
===
--- test/Driver/amdgpu-toolchain.c
+++ test/Driver/amdgpu-toolchain.c
@@ -3,4 +3,4 @@
 // AS_LINK: ld.lld{{.*}} "-shared"
 
 // RUN: %clang -### -g -target amdgcn--amdhsa -mcpu=kaveri %s 2>&1 | FileCheck -check-prefix=DWARF_VER %s
-// DWARF_VER: "-dwarf-version=2"
+// DWARF_VER: "-dwarf-version=5"
Index: lib/Driver/ToolChains/AMDGPU.h
===
--- lib/Driver/ToolChains/AMDGPU.h
+++ lib/Driver/ToolChains/AMDGPU.h
@@ -55,7 +55,7 @@
 public:
   AMDGPUToolChain(const Driver , const llvm::Triple ,
   const llvm::opt::ArgList );
-  unsigned GetDefaultDwarfVersion() const override { return 2; }
+  unsigned GetDefaultDwarfVersion() const override { return 5; }
   bool IsIntegratedAssemblerDefault() const override { return true; }
   llvm::opt::DerivedArgList *
   TranslateArgs(const llvm::opt::DerivedArgList , StringRef BoundArch,
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


r357285 - [AMDGPU] Switch default DWARF version to 5

2019-03-29 Thread Scott Linder via cfe-commits
Author: scott.linder
Date: Fri Mar 29 10:45:40 2019
New Revision: 357285

URL: http://llvm.org/viewvc/llvm-project?rev=357285=rev
Log:
[AMDGPU] Switch default DWARF version to 5

Effectively reverts r337612. The issues that cropped up with the last
attempt appear to have gone away.

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

Modified:
cfe/trunk/lib/Driver/ToolChains/AMDGPU.h
cfe/trunk/test/Driver/amdgpu-toolchain.c
cfe/trunk/test/Driver/split-debug.c

Modified: cfe/trunk/lib/Driver/ToolChains/AMDGPU.h
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Driver/ToolChains/AMDGPU.h?rev=357285=357284=357285=diff
==
--- cfe/trunk/lib/Driver/ToolChains/AMDGPU.h (original)
+++ cfe/trunk/lib/Driver/ToolChains/AMDGPU.h Fri Mar 29 10:45:40 2019
@@ -55,7 +55,7 @@ protected:
 public:
   AMDGPUToolChain(const Driver , const llvm::Triple ,
   const llvm::opt::ArgList );
-  unsigned GetDefaultDwarfVersion() const override { return 2; }
+  unsigned GetDefaultDwarfVersion() const override { return 5; }
   bool IsIntegratedAssemblerDefault() const override { return true; }
   llvm::opt::DerivedArgList *
   TranslateArgs(const llvm::opt::DerivedArgList , StringRef BoundArch,

Modified: cfe/trunk/test/Driver/amdgpu-toolchain.c
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/Driver/amdgpu-toolchain.c?rev=357285=357284=357285=diff
==
--- cfe/trunk/test/Driver/amdgpu-toolchain.c (original)
+++ cfe/trunk/test/Driver/amdgpu-toolchain.c Fri Mar 29 10:45:40 2019
@@ -3,4 +3,4 @@
 // AS_LINK: ld.lld{{.*}} "-shared"
 
 // RUN: %clang -### -g -target amdgcn--amdhsa -mcpu=kaveri %s 2>&1 | FileCheck 
-check-prefix=DWARF_VER %s
-// DWARF_VER: "-dwarf-version=2"
+// DWARF_VER: "-dwarf-version=5"

Modified: cfe/trunk/test/Driver/split-debug.c
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/Driver/split-debug.c?rev=357285=357284=357285=diff
==
--- cfe/trunk/test/Driver/split-debug.c (original)
+++ cfe/trunk/test/Driver/split-debug.c Fri Mar 29 10:45:40 2019
@@ -38,6 +38,9 @@
 // RUN: %clang -target x86_64-pc-freebsd12 -gsplit-dwarf -c -### %s 2> %t
 // RUN: FileCheck -check-prefix=CHECK-OPTION < %t %s
 //
+// RUN: %clang -target amdgcn-amd-amdhsa -gsplit-dwarf -c -### %s 2> %t
+// RUN: FileCheck -check-prefix=CHECK-OPTION < %t %s
+//
 // CHECK-OPTION: "-split-dwarf-file" "split-debug.dwo"
 
 // RUN: %clang -target x86_64-unknown-linux-gnu -gsplit-dwarf -S -### %s 2> %t


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


[PATCH] D59963: [clang-tidy] Add a module for the Linux kernel.

2019-03-29 Thread Tom Roeder via Phabricator via cfe-commits
tmroeder updated this revision to Diff 192860.
tmroeder added a comment.

Changed the module name to linuxkernel as suggested and updated the files to 
match.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D59963

Files:
  clang-tools-extra/clang-tidy/CMakeLists.txt
  clang-tools-extra/clang-tidy/ClangTidyForceLinker.h
  clang-tools-extra/clang-tidy/linuxkernel/CMakeLists.txt
  clang-tools-extra/clang-tidy/linuxkernel/LinuxKernelTidyModule.cpp
  clang-tools-extra/clang-tidy/plugin/CMakeLists.txt
  clang-tools-extra/clang-tidy/tool/CMakeLists.txt

Index: clang-tools-extra/clang-tidy/tool/CMakeLists.txt
===
--- clang-tools-extra/clang-tidy/tool/CMakeLists.txt
+++ clang-tools-extra/clang-tidy/tool/CMakeLists.txt
@@ -26,6 +26,7 @@
   clangTidyFuchsiaModule
   clangTidyGoogleModule
   clangTidyHICPPModule
+  clangTidyLinuxKernelModule
   clangTidyLLVMModule
   clangTidyMiscModule
   clangTidyModernizeModule
Index: clang-tools-extra/clang-tidy/plugin/CMakeLists.txt
===
--- clang-tools-extra/clang-tidy/plugin/CMakeLists.txt
+++ clang-tools-extra/clang-tidy/plugin/CMakeLists.txt
@@ -17,6 +17,7 @@
   clangTidyFuchsiaModule
   clangTidyGoogleModule
   clangTidyHICPPModule
+  clangTidyLinuxKernelModule
   clangTidyLLVMModule
   clangTidyMiscModule
   clangTidyModernizeModule
Index: clang-tools-extra/clang-tidy/linuxkernel/LinuxKernelTidyModule.cpp
===
--- /dev/null
+++ clang-tools-extra/clang-tidy/linuxkernel/LinuxKernelTidyModule.cpp
@@ -0,0 +1,34 @@
+//===--- LinuxKernelTidyModule.cpp - clang-tidy===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+
+#include "../ClangTidy.h"
+#include "../ClangTidyModule.h"
+#include "../ClangTidyModuleRegistry.h"
+
+namespace clang {
+namespace tidy {
+namespace linux {
+
+/// This module is for checks specific to the Linux kernel.
+class LinuxKernelModule : public ClangTidyModule {
+public:
+  void addCheckFactories(ClangTidyCheckFactories ) override {
+  }
+};
+// Register the LinuxKernelTidyModule using this statically initialized
+// variable.
+static ClangTidyModuleRegistry::Add
+X("linux-module", "Adds checks specific to the Linux kernel.");
+} // namespace linux
+
+// This anchor is used to force the linker to link in the generated object file
+// and thus register the LinuxKernelModule.
+volatile int LinuxKernelModuleAnchorSource = 0;
+
+} // namespace tidy
+} // namespace clang
Index: clang-tools-extra/clang-tidy/linuxkernel/CMakeLists.txt
===
--- /dev/null
+++ clang-tools-extra/clang-tidy/linuxkernel/CMakeLists.txt
@@ -0,0 +1,13 @@
+set(LLVM_LINK_COMPONENTS support)
+
+add_clang_library(clangTidyLinuxKernelModule
+  LinuxKernelTidyModule.cpp
+
+  LINK_LIBS
+  clangAST
+  clangASTMatchers
+  clangBasic
+  clangLex
+  clangTidy
+  clangTidyUtils
+  )
Index: clang-tools-extra/clang-tidy/ClangTidyForceLinker.h
===
--- clang-tools-extra/clang-tidy/ClangTidyForceLinker.h
+++ clang-tools-extra/clang-tidy/ClangTidyForceLinker.h
@@ -35,6 +35,11 @@
 static int LLVM_ATTRIBUTE_UNUSED BugproneModuleAnchorDestination =
 BugproneModuleAnchorSource;
 
+// This anchor is used to force the linker to link the LinuxKernelModule.
+extern volatile int LinuxKernelModuleAnchorSource;
+static int LLVM_ATTRIBUTE_UNUSED LinuxKernelModuleAnchorDestination =
+LinuxKernelModuleAnchorSource;
+
 // This anchor is used to force the linker to link the LLVMModule.
 extern volatile int LLVMModuleAnchorSource;
 static int LLVM_ATTRIBUTE_UNUSED LLVMModuleAnchorDestination =
Index: clang-tools-extra/clang-tidy/CMakeLists.txt
===
--- clang-tools-extra/clang-tidy/CMakeLists.txt
+++ clang-tools-extra/clang-tidy/CMakeLists.txt
@@ -44,6 +44,7 @@
 add_subdirectory(fuchsia)
 add_subdirectory(google)
 add_subdirectory(hicpp)
+add_subdirectory(linuxkernel)
 add_subdirectory(llvm)
 add_subdirectory(misc)
 add_subdirectory(modernize)
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D59963: [clang-tidy] Add a module for the Linux kernel.

2019-03-29 Thread Tom Roeder via Phabricator via cfe-commits
tmroeder marked 2 inline comments as done.
tmroeder added a comment.

In D59963#1447985 , @alexfh wrote:

> Looks reasonable in general, but we usually add modules with at least one 
> check. Let's do the same here.


OK, will do.




Comment at: clang-tools-extra/clang-tidy/linux/LinuxTidyModule.cpp:13
+
+using namespace clang::ast_matchers;
+

lebedev.ri wrote:
> You don't need this here.
Thanks. I've removed it now.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D59963



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


[PATCH] D59827: [slh] x86 impl of ARM instrinsic for SLH

2019-03-29 Thread Zola Bridges via Phabricator via cfe-commits
zbrid updated this revision to Diff 192857.
zbrid added a comment.

remove unnecessary requirement from builtin test


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D59827

Files:
  clang/include/clang/Basic/Builtins.def
  clang/include/clang/Basic/DiagnosticSemaKinds.td
  clang/include/clang/Sema/Sema.h
  clang/lib/CodeGen/CGBuiltin.cpp
  clang/lib/Frontend/InitPreprocessor.cpp
  clang/lib/Sema/SemaChecking.cpp
  clang/test/CodeGen/builtin-speculation-safe-value.c
  clang/test/Preprocessor/init.c
  llvm/docs/LangRef.rst
  llvm/include/llvm/CodeGen/ISDOpcodes.h
  llvm/include/llvm/IR/Intrinsics.td
  llvm/include/llvm/Target/TargetSelectionDAG.td
  llvm/lib/CodeGen/SelectionDAG/LegalizeIntegerTypes.cpp
  llvm/lib/CodeGen/SelectionDAG/LegalizeTypes.h
  llvm/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp
  llvm/lib/CodeGen/SelectionDAG/SelectionDAGDumper.cpp
  llvm/lib/Target/X86/X86ISelLowering.cpp
  llvm/lib/Target/X86/X86ISelLowering.h
  llvm/lib/Target/X86/X86InstrInfo.td
  llvm/lib/Target/X86/X86SpeculativeLoadHardening.cpp
  llvm/test/CodeGen/X86/speculative-load-hardening-intrinsic.ll

Index: llvm/test/CodeGen/X86/speculative-load-hardening-intrinsic.ll
===
--- /dev/null
+++ llvm/test/CodeGen/X86/speculative-load-hardening-intrinsic.ll
@@ -0,0 +1,71 @@
+; RUN: llc < %s -mtriple=x86_64-unknown-linux-gnu | FileCheck %s --check-prefix=X64
+
+; ModuleID = 'hello.cpp'
+source_filename = "hello.cpp"
+target datalayout = "e-m:e-i64:64-f80:128-n8:16:32:64-S128"
+target triple = "x86_64-unknown-linux-gnu"
+
+; Function Attrs: noinline nounwind optnone uwtable
+define dso_local i32 @_Z5foo32i(i32 %a) #0 {
+entry:
+  %a.addr = alloca i32, align 4
+  %b = alloca i32, align 4
+  %b_safe = alloca i32, align 4
+  %c = alloca i32, align 4
+  store i32 %a, i32* %a.addr, align 4
+  %0 = load i32, i32* %a.addr, align 4
+  %mul = mul nsw i32 %0, 100
+  store i32 %mul, i32* %b, align 4
+  %1 = load i32, i32* %b, align 4
+  %2 = call i32 @llvm.speculationsafevalue.i32(i32 %1)
+; X64: movl -12(%rbp), %eax
+; X64: lfence
+; X64: movl %eax, -8(%rbp)
+  store i32 %2, i32* %b_safe, align 4
+  %3 = load i32, i32* %b_safe, align 4
+  %add = add nsw i32 %3, 100
+  store i32 %add, i32* %c, align 4
+  %4 = load i32, i32* %c, align 4
+  ret i32 %4
+}
+
+; Function Attrs: nounwind
+declare i32 @llvm.speculationsafevalue.i32(i32) #1
+
+; Function Attrs: noinline nounwind optnone uwtable
+define dso_local i32 @_Z5foo64i(i32 %a) #0 {
+entry:
+  %a.addr = alloca i32, align 4
+  %b = alloca i64, align 8
+  %b_safe = alloca i64, align 8
+  %c = alloca i64, align 8
+  store i32 %a, i32* %a.addr, align 4
+  %0 = load i32, i32* %a.addr, align 4
+  %mul = mul nsw i32 %0, 100
+  %conv = sext i32 %mul to i64
+  store i64 %conv, i64* %b, align 8
+  %1 = load i64, i64* %b, align 8
+  %2 = call i64 @llvm.speculationsafevalue.i64(i64 %1)
+; X64: movq -32(%rbp), %rax
+; X64: lfence
+; X64: movq %rax, -24(%rbp)
+  store i64 %2, i64* %b_safe, align 8
+  %3 = load i64, i64* %b_safe, align 8
+  %add = add nsw i64 %3, 100
+  store i64 %add, i64* %c, align 8
+  %4 = load i64, i64* %c, align 8
+  %conv1 = trunc i64 %4 to i32
+  ret i32 %conv1
+}
+
+; Function Attrs: nounwind
+declare i64 @llvm.speculationsafevalue.i64(i64) #1
+
+attributes #0 = { noinline nounwind optnone uwtable "correctly-rounded-divide-sqrt-fp-math"="false" "disable-tail-calls"="false" "less-precise-fpmad"="false" "min-legal-vector-width"="0" "no-frame-pointer-elim"="true" "no-frame-pointer-elim-non-leaf" "no-infs-fp-math"="false" "no-jump-tables"="false" "no-nans-fp-math"="false" "no-signed-zeros-fp-math"="false" "no-trapping-math"="false" "stack-protector-buffer-size"="8" "target-cpu"="x86-64" "target-features"="+fxsr,+mmx,+sse,+sse2,+x87" "unsafe-fp-math"="false" "use-soft-float"="false" }
+attributes #1 = { nounwind }
+
+!llvm.module.flags = !{!0}
+!llvm.ident = !{!1}
+
+!0 = !{i32 1, !"wchar_size", i32 4}
+!1 = !{!"clang version 9.0.0 (https://github.com/llvm/llvm-project.git 6fd90b5505fe7cddd0fd798fe9608ea0e0325302)"}
Index: llvm/lib/Target/X86/X86SpeculativeLoadHardening.cpp
===
--- llvm/lib/Target/X86/X86SpeculativeLoadHardening.cpp
+++ llvm/lib/Target/X86/X86SpeculativeLoadHardening.cpp
@@ -212,6 +212,7 @@
   void hardenIndirectCallOrJumpInstr(
   MachineInstr ,
   SmallDenseMap );
+  bool lowerIntrinsic(MachineFunction );
 };
 
 } // end anonymous namespace
@@ -402,16 +403,20 @@
   LLVM_DEBUG(dbgs() << "** " << getPassName() << " : " << MF.getName()
 << " **\n");
 
-  // Only run if this pass is forced enabled or we detect the relevant function
-  // attribute requesting SLH.
-  if (!EnableSpeculativeLoadHardening &&
-  !MF.getFunction().hasFnAttribute(Attribute::SpeculativeLoadHardening))
-return false;
-
   

[PATCH] D59802: [clang-tidy] Add new checker: llvm-avoid-cast-in-conditional

2019-03-29 Thread Don Hinton via Phabricator via cfe-commits
hintonda updated this revision to Diff 192854.
hintonda added a comment.

- Improve warning message.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D59802

Files:
  clang-tools-extra/clang-tidy/llvm/AvoidCastInConditionalCheck.cpp
  clang-tools-extra/clang-tidy/llvm/AvoidCastInConditionalCheck.h
  clang-tools-extra/clang-tidy/llvm/CMakeLists.txt
  clang-tools-extra/clang-tidy/llvm/LLVMTidyModule.cpp
  clang-tools-extra/clang-tidy/utils/HeaderFileExtensionsUtils.h
  clang-tools-extra/docs/ReleaseNotes.rst
  clang-tools-extra/docs/clang-tidy/checks/list.rst
  clang-tools-extra/docs/clang-tidy/checks/llvm-avoid-cast-in-conditional.rst
  clang-tools-extra/test/clang-tidy/llvm-avoid-cast-in-conditional.cpp

Index: clang-tools-extra/test/clang-tidy/llvm-avoid-cast-in-conditional.cpp
===
--- /dev/null
+++ clang-tools-extra/test/clang-tidy/llvm-avoid-cast-in-conditional.cpp
@@ -0,0 +1,118 @@
+// RUN: %check_clang_tidy %s llvm-avoid-cast-in-conditional %t
+
+#define CAST(T, Obj) cast(Obj)
+#define ISA(T, Obj) isa(Obj)
+#define ISA_OR_NULL(T, Obj) Obj &(Obj)
+
+struct X;
+struct Y;
+struct Z {
+  int foo();
+  X *bar();
+};
+
+template 
+bool isa(Y *);
+template 
+X *cast(Y *);
+template 
+X *dyn_cast(Y *);
+template 
+X *dyn_cast_or_null(Y *);
+
+bool foo(Y *y, Z *z) {
+  if (auto x = cast(y))
+return true;
+  // CHECK-MESSAGES: :[[@LINE-2]]:16: warning: {{cast<> in conditional .*llvm-avoid-cast-in-conditional}}
+  // CHECK-FIXES: if (auto x = dyn_cast(y))
+
+  if (cast(y))
+return true;
+  // CHECK-MESSAGES: :[[@LINE-2]]:7: warning:  {{cast<> in conditional .*llvm-avoid-cast-in-conditional}}
+  // CHECK-FIXES: if (isa(y))
+
+  if (dyn_cast(y))
+return true;
+  // CHECK-MESSAGES: :[[@LINE-2]]:7: warning:  {{.*dyn_cast<> not used .*llvm-avoid-cast-in-conditional}}
+  // CHECK-FIXES: if (isa(y))
+
+  // These don't trigger a warning.
+  if (auto x = cast(y)->foo())
+return true;
+  if (cast(y)->foo())
+return true;
+
+  while (auto x = cast(y))
+break;
+  // CHECK-MESSAGES: :[[@LINE-2]]:19: warning:  {{cast<> in conditional .*llvm-avoid-cast-in-conditional}}
+  // CHECK-FIXES: while (auto x = dyn_cast(y))
+
+  while (cast(y))
+break;
+  // CHECK-MESSAGES: :[[@LINE-2]]:10: warning:  {{cast<> in conditional .*llvm-avoid-cast-in-conditional}}
+  // CHECK-FIXES: while (isa(y))
+
+  while (dyn_cast(y))
+break;
+  // CHECK-MESSAGES: :[[@LINE-2]]:10: warning:  {{.*dyn_cast<> not used .*llvm-avoid-cast-in-conditional}}
+  // CHECK-FIXES: while (isa(y))
+
+  // These don't trigger a warning.
+  while (auto x = cast(y)->foo())
+break;
+  while (cast(y)->foo())
+break;
+
+  do {
+break;
+  } while (cast(y));
+  // CHECK-MESSAGES: :[[@LINE-1]]:12: warning:  {{cast<> in conditional .*llvm-avoid-cast-in-conditional}}
+  // CHECK-FIXES: while (isa(y));
+
+  do {
+break;
+  } while (dyn_cast(y));
+  // CHECK-MESSAGES: :[[@LINE-1]]:12: warning:  {{.*dyn_cast<> not used .*llvm-avoid-cast-in-conditional}}
+  // CHECK-FIXES: while (isa(y));
+
+  if (z->bar() && isa(z->bar()))
+return true;
+  // CHECK-MESSAGES: :[[@LINE-2]]:7: warning:  {{method .* is called twice .*llvm-avoid-cast-in-conditional}}
+  // CHECK-FIXES: if (dyn_cast_or_null(z->bar()))
+
+  if (z->bar() && cast(z->bar()))
+return true;
+  // CHECK-MESSAGES: :[[@LINE-2]]:7: warning:  {{method .* is called twice .*llvm-avoid-cast-in-conditional}}
+  // CHECK-FIXES: if (dyn_cast_or_null(z->bar()))
+
+  if (z->bar() && dyn_cast(z->bar()))
+return true;
+  // CHECK-MESSAGES: :[[@LINE-2]]:7: warning:  {{method .* is called twice .*llvm-avoid-cast-in-conditional}}
+  // CHECK-FIXES: if (dyn_cast_or_null(z->bar()))
+
+  if (z->bar() && dyn_cast_or_null(z->bar()))
+return true;
+  // CHECK-MESSAGES: :[[@LINE-2]]:7: warning:  {{method .* is called twice .*llvm-avoid-cast-in-conditional}}
+  // CHECK-FIXES: if (dyn_cast_or_null(z->bar()))
+
+  bool b = z->bar() && cast(z->bar());
+  // CHECK-MESSAGES: :[[@LINE-1]]:12: warning:  {{method .* is called twice .*llvm-avoid-cast-in-conditional}}
+  // CHECK-FIXES: bool b = dyn_cast_or_null(z->bar());
+
+  // These don't trigger a warning.
+  if (auto x = CAST(X, y))
+return true;
+  if (z->bar() && ISA(Y, z->bar()))
+return true;
+  if (ISA_OR_NULL(Y, z->bar()))
+return true;
+  if (y && isa(y))
+return true;
+  if (y && cast(z->bar()))
+return true;
+  if (z && cast(y)->foo())
+return true;
+  bool b2 = y && cast(z);
+
+  return false;
+}
Index: clang-tools-extra/docs/clang-tidy/checks/llvm-avoid-cast-in-conditional.rst
===
--- /dev/null
+++ clang-tools-extra/docs/clang-tidy/checks/llvm-avoid-cast-in-conditional.rst
@@ -0,0 +1,28 @@
+.. title:: clang-tidy - llvm-avoid-cast-in-conditional
+
+llvm-avoid-cast-in-conditional

[PATCH] D59963: [clang-tidy] Add module for the Linux kernel.

2019-03-29 Thread Alexander Kornienko via Phabricator via cfe-commits
alexfh added a comment.

Looks reasonable in general, but we usually add modules with at least one 
check. Let's do the same here.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D59963



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


[PATCH] D59121: [analyzer] Fix macro names in diagnostics within bigger macros.

2019-03-29 Thread Artem Dergachev via Phabricator via cfe-commits
NoQ added a comment.

I think the right thing to do here is "look at the immediate macro; while it 
expands exactly to our original expression, look at what it is an expansion of; 
write down the last macro we've reached". My code now gives up whenever we stop 
expanding to the original expression, but it should write down the highest 
macro it has reached instead.


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

https://reviews.llvm.org/D59121



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


[PATCH] D59975: [fuchsia] Add clang-doc to Fuchsia distribution

2019-03-29 Thread Julie Hockett via Phabricator via cfe-commits
juliehockett closed this revision.
juliehockett added a comment.

Closed and submitted in r357275


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

https://reviews.llvm.org/D59975



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


[PATCH] D59827: [slh] x86 impl of ARM instrinsic for SLH

2019-03-29 Thread Zola Bridges via Phabricator via cfe-commits
zbrid updated this revision to Diff 192852.
zbrid added a comment.

fix test formatting; make target independent intrinsic; add doc


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D59827

Files:
  clang/include/clang/Basic/Builtins.def
  clang/include/clang/Basic/DiagnosticSemaKinds.td
  clang/include/clang/Sema/Sema.h
  clang/lib/CodeGen/CGBuiltin.cpp
  clang/lib/Frontend/InitPreprocessor.cpp
  clang/lib/Sema/SemaChecking.cpp
  clang/test/CodeGen/builtin-speculation-safe-value.c
  clang/test/Preprocessor/init.c
  llvm/docs/LangRef.rst
  llvm/include/llvm/CodeGen/ISDOpcodes.h
  llvm/include/llvm/IR/Intrinsics.td
  llvm/include/llvm/Target/TargetSelectionDAG.td
  llvm/lib/CodeGen/SelectionDAG/LegalizeIntegerTypes.cpp
  llvm/lib/CodeGen/SelectionDAG/LegalizeTypes.h
  llvm/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp
  llvm/lib/CodeGen/SelectionDAG/SelectionDAGDumper.cpp
  llvm/lib/Target/X86/X86ISelLowering.cpp
  llvm/lib/Target/X86/X86ISelLowering.h
  llvm/lib/Target/X86/X86InstrInfo.td
  llvm/lib/Target/X86/X86SpeculativeLoadHardening.cpp
  llvm/test/CodeGen/X86/speculative-load-hardening-intrinsic.ll

Index: llvm/test/CodeGen/X86/speculative-load-hardening-intrinsic.ll
===
--- /dev/null
+++ llvm/test/CodeGen/X86/speculative-load-hardening-intrinsic.ll
@@ -0,0 +1,71 @@
+; RUN: llc < %s -mtriple=x86_64-unknown-linux-gnu | FileCheck %s --check-prefix=X64
+
+; ModuleID = 'hello.cpp'
+source_filename = "hello.cpp"
+target datalayout = "e-m:e-i64:64-f80:128-n8:16:32:64-S128"
+target triple = "x86_64-unknown-linux-gnu"
+
+; Function Attrs: noinline nounwind optnone uwtable
+define dso_local i32 @_Z5foo32i(i32 %a) #0 {
+entry:
+  %a.addr = alloca i32, align 4
+  %b = alloca i32, align 4
+  %b_safe = alloca i32, align 4
+  %c = alloca i32, align 4
+  store i32 %a, i32* %a.addr, align 4
+  %0 = load i32, i32* %a.addr, align 4
+  %mul = mul nsw i32 %0, 100
+  store i32 %mul, i32* %b, align 4
+  %1 = load i32, i32* %b, align 4
+  %2 = call i32 @llvm.speculationsafevalue.i32(i32 %1)
+; X64: movl -12(%rbp), %eax
+; X64: lfence
+; X64: movl %eax, -8(%rbp)
+  store i32 %2, i32* %b_safe, align 4
+  %3 = load i32, i32* %b_safe, align 4
+  %add = add nsw i32 %3, 100
+  store i32 %add, i32* %c, align 4
+  %4 = load i32, i32* %c, align 4
+  ret i32 %4
+}
+
+; Function Attrs: nounwind
+declare i32 @llvm.speculationsafevalue.i32(i32) #1
+
+; Function Attrs: noinline nounwind optnone uwtable
+define dso_local i32 @_Z5foo64i(i32 %a) #0 {
+entry:
+  %a.addr = alloca i32, align 4
+  %b = alloca i64, align 8
+  %b_safe = alloca i64, align 8
+  %c = alloca i64, align 8
+  store i32 %a, i32* %a.addr, align 4
+  %0 = load i32, i32* %a.addr, align 4
+  %mul = mul nsw i32 %0, 100
+  %conv = sext i32 %mul to i64
+  store i64 %conv, i64* %b, align 8
+  %1 = load i64, i64* %b, align 8
+  %2 = call i64 @llvm.speculationsafevalue.i64(i64 %1)
+; X64: movq -32(%rbp), %rax
+; X64: lfence
+; X64: movq %rax, -24(%rbp)
+  store i64 %2, i64* %b_safe, align 8
+  %3 = load i64, i64* %b_safe, align 8
+  %add = add nsw i64 %3, 100
+  store i64 %add, i64* %c, align 8
+  %4 = load i64, i64* %c, align 8
+  %conv1 = trunc i64 %4 to i32
+  ret i32 %conv1
+}
+
+; Function Attrs: nounwind
+declare i64 @llvm.speculationsafevalue.i64(i64) #1
+
+attributes #0 = { noinline nounwind optnone uwtable "correctly-rounded-divide-sqrt-fp-math"="false" "disable-tail-calls"="false" "less-precise-fpmad"="false" "min-legal-vector-width"="0" "no-frame-pointer-elim"="true" "no-frame-pointer-elim-non-leaf" "no-infs-fp-math"="false" "no-jump-tables"="false" "no-nans-fp-math"="false" "no-signed-zeros-fp-math"="false" "no-trapping-math"="false" "stack-protector-buffer-size"="8" "target-cpu"="x86-64" "target-features"="+fxsr,+mmx,+sse,+sse2,+x87" "unsafe-fp-math"="false" "use-soft-float"="false" }
+attributes #1 = { nounwind }
+
+!llvm.module.flags = !{!0}
+!llvm.ident = !{!1}
+
+!0 = !{i32 1, !"wchar_size", i32 4}
+!1 = !{!"clang version 9.0.0 (https://github.com/llvm/llvm-project.git 6fd90b5505fe7cddd0fd798fe9608ea0e0325302)"}
Index: llvm/lib/Target/X86/X86SpeculativeLoadHardening.cpp
===
--- llvm/lib/Target/X86/X86SpeculativeLoadHardening.cpp
+++ llvm/lib/Target/X86/X86SpeculativeLoadHardening.cpp
@@ -212,6 +212,7 @@
   void hardenIndirectCallOrJumpInstr(
   MachineInstr ,
   SmallDenseMap );
+  bool lowerIntrinsic(MachineFunction );
 };
 
 } // end anonymous namespace
@@ -402,16 +403,20 @@
   LLVM_DEBUG(dbgs() << "** " << getPassName() << " : " << MF.getName()
 << " **\n");
 
-  // Only run if this pass is forced enabled or we detect the relevant function
-  // attribute requesting SLH.
-  if (!EnableSpeculativeLoadHardening &&
-  !MF.getFunction().hasFnAttribute(Attribute::SpeculativeLoadHardening))
-return 

[PATCH] D59974: [clang-doc] Build as clang_tool

2019-03-29 Thread Julie Hockett via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rL357274: [clang-doc] Build as clang_tool (authored by 
juliehockett, committed by ).
Herald added a project: LLVM.
Herald added a subscriber: llvm-commits.

Changed prior to commit:
  https://reviews.llvm.org/D59974?vs=192759=192850#toc

Repository:
  rL LLVM

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

https://reviews.llvm.org/D59974

Files:
  clang-tools-extra/trunk/clang-doc/tool/CMakeLists.txt


Index: clang-tools-extra/trunk/clang-doc/tool/CMakeLists.txt
===
--- clang-tools-extra/trunk/clang-doc/tool/CMakeLists.txt
+++ clang-tools-extra/trunk/clang-doc/tool/CMakeLists.txt
@@ -1,6 +1,6 @@
 include_directories(${CMAKE_CURRENT_SOURCE_DIR}/..)
 
-add_clang_executable(clang-doc
+add_clang_tool(clang-doc
   ClangDocMain.cpp
   )
 


Index: clang-tools-extra/trunk/clang-doc/tool/CMakeLists.txt
===
--- clang-tools-extra/trunk/clang-doc/tool/CMakeLists.txt
+++ clang-tools-extra/trunk/clang-doc/tool/CMakeLists.txt
@@ -1,6 +1,6 @@
 include_directories(${CMAKE_CURRENT_SOURCE_DIR}/..)
 
-add_clang_executable(clang-doc
+add_clang_tool(clang-doc
   ClangDocMain.cpp
   )
 
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


r357275 - [fuchsia] Add clang-doc to Fuchsia distribution

2019-03-29 Thread Julie Hockett via cfe-commits
Author: juliehockett
Date: Fri Mar 29 09:56:37 2019
New Revision: 357275

URL: http://llvm.org/viewvc/llvm-project?rev=357275=rev
Log:
[fuchsia] Add clang-doc to Fuchsia distribution

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

Modified:
cfe/trunk/cmake/caches/Fuchsia-stage2.cmake

Modified: cfe/trunk/cmake/caches/Fuchsia-stage2.cmake
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/cmake/caches/Fuchsia-stage2.cmake?rev=357275=357274=357275=diff
==
--- cfe/trunk/cmake/caches/Fuchsia-stage2.cmake (original)
+++ cfe/trunk/cmake/caches/Fuchsia-stage2.cmake Fri Mar 29 09:56:37 2019
@@ -185,6 +185,7 @@ set(LLVM_DISTRIBUTION_COMPONENTS
   lld
   LTO
   clang-apply-replacements
+  clang-doc
   clang-format
   clang-resource-headers
   clang-include-fixer


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


[clang-tools-extra] r357274 - [clang-doc] Build as clang_tool

2019-03-29 Thread Julie Hockett via cfe-commits
Author: juliehockett
Date: Fri Mar 29 09:56:36 2019
New Revision: 357274

URL: http://llvm.org/viewvc/llvm-project?rev=357274=rev
Log:
[clang-doc] Build as clang_tool

Instead of as clang_executable.

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

Modified:
clang-tools-extra/trunk/clang-doc/tool/CMakeLists.txt

Modified: clang-tools-extra/trunk/clang-doc/tool/CMakeLists.txt
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clang-doc/tool/CMakeLists.txt?rev=357274=357273=357274=diff
==
--- clang-tools-extra/trunk/clang-doc/tool/CMakeLists.txt (original)
+++ clang-tools-extra/trunk/clang-doc/tool/CMakeLists.txt Fri Mar 29 09:56:36 
2019
@@ -1,6 +1,6 @@
 include_directories(${CMAKE_CURRENT_SOURCE_DIR}/..)
 
-add_clang_executable(clang-doc
+add_clang_tool(clang-doc
   ClangDocMain.cpp
   )
 


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


[PATCH] D59725: Additions to creduce script

2019-03-29 Thread Amy Huang via Phabricator via cfe-commits
akhuang updated this revision to Diff 192846.
akhuang marked an inline comment as done.
akhuang added a comment.

Tmpfile was not being removed


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

https://reviews.llvm.org/D59725

Files:
  clang/utils/creduce-clang-crash.py

Index: clang/utils/creduce-clang-crash.py
===
--- clang/utils/creduce-clang-crash.py
+++ clang/utils/creduce-clang-crash.py
@@ -1,8 +1,14 @@
 #!/usr/bin/env python
 """Calls C-Reduce to create a minimal reproducer for clang crashes.
+
+Output files:
+  *.reduced.sh -- crash reproducer with minimal arguments
+  *.reduced.cpp -- the reduced file
+  *.test.sh -- interestingness test for C-Reduce
 """
 
-from argparse import ArgumentParser
+from __future__ import print_function
+from argparse import ArgumentParser, RawTextHelpFormatter
 import os
 import re
 import stat
@@ -15,10 +21,14 @@
 from distutils.spawn import find_executable
 
 verbose = False
-llvm_bin = None
 creduce_cmd = None
+clang_cmd = None
 not_cmd = None
 
+def verbose_print(*args, **kwargs):
+  if verbose:
+print(*args, **kwargs)
+
 def check_file(fname):
   if not os.path.isfile(fname):
 sys.exit("ERROR: %s does not exist" % (fname))
@@ -33,166 +43,339 @@
 cmd = find_executable(cmd_path)
 if cmd:
   return cmd
-sys.exit("ERROR: executable %s not found" % (cmd_path))
+sys.exit("ERROR: executable `%s` not found" % (cmd_path))
 
   cmd = find_executable(cmd_name, path=cmd_dir)
   if cmd:
 return cmd
-  sys.exit("ERROR: %s not found in %s" % (cmd_name, cmd_dir))
 
-def quote_cmd(cmd):
-  return ' '.join(arg if arg.startswith('$') else pipes.quote(arg)
-  for arg in cmd)
-
-def get_crash_cmd(crash_script):
-  with open(crash_script) as f:
-# Assume clang call is on the last line of the script
-line = f.readlines()[-1]
-cmd = shlex.split(line)
-
-# Overwrite the script's clang with the user's clang path
-new_clang = check_cmd('clang', llvm_bin)
-cmd[0] = pipes.quote(new_clang)
-return cmd
+  if not cmd_dir:
+cmd_dir = "$PATH"
+  sys.exit("ERROR: `%s` not found in %s" % (cmd_name, cmd_dir))
 
-def has_expected_output(crash_cmd, expected_output):
-  p = subprocess.Popen(crash_cmd,
-   stdout=subprocess.PIPE,
-   stderr=subprocess.STDOUT)
-  crash_output, _ = p.communicate()
-  return all(msg in crash_output for msg in expected_output)
-
-def get_expected_output(crash_cmd):
-  p = subprocess.Popen(crash_cmd,
-   stdout=subprocess.PIPE,
-   stderr=subprocess.STDOUT)
-  crash_output, _ = p.communicate()
-
-  # If there is an assertion failure, use that;
-  # otherwise use the last five stack trace functions
-  assertion_re = r'Assertion `([^\']+)\' failed'
-  assertion_match = re.search(assertion_re, crash_output)
-  if assertion_match:
-return [assertion_match.group(1)]
-  else:
-stacktrace_re = r'#[0-9]+\s+0[xX][0-9a-fA-F]+\s*([^(]+)\('
-matches = re.findall(stacktrace_re, crash_output)
-return matches[-5:]
-
-def write_interestingness_test(testfile, crash_cmd, expected_output,
-   file_to_reduce):
-  filename = os.path.basename(file_to_reduce)
-  if filename not in crash_cmd:
-sys.exit("ERROR: expected %s to be in the crash command" % filename)
-
-  # Replace all instances of file_to_reduce with a command line variable
-  output = ['#!/bin/bash',
-'if [ -z "$1" ] ; then',
-'  f=%s' % (pipes.quote(filename)),
-'else',
-'  f="$1"',
-'fi']
-  cmd = ['$f' if s == filename else s for s in crash_cmd]
-
-  output.append('%s --crash %s >& t.log || exit 1' % (pipes.quote(not_cmd),
-  quote_cmd(cmd)))
-
-  for msg in expected_output:
-output.append('grep %s t.log || exit 1' % pipes.quote(msg))
-
-  with open(testfile, 'w') as f:
-f.write('\n'.join(output))
-  os.chmod(testfile, os.stat(testfile).st_mode | stat.S_IEXEC)
-
-def check_interestingness(testfile, file_to_reduce):
-  testfile = os.path.abspath(testfile)
-
-  # Check that the test considers the original file interesting
-  with open(os.devnull, 'w') as devnull:
-returncode = subprocess.call(testfile, stdout=devnull)
-  if returncode:
-sys.exit("The interestingness test does not pass for the original file.")
-
-  # Check that an empty file is not interesting
-  _, empty_file = tempfile.mkstemp()
-  with open(os.devnull, 'w') as devnull:
-returncode = subprocess.call([testfile, empty_file], stdout=devnull)
-  os.remove(empty_file)
-  if not returncode:
-sys.exit("The interestingness test passes for an empty file.")
-
-def clang_preprocess(file_to_reduce, crash_cmd, expected_output):
-  _, tmpfile = tempfile.mkstemp()
-  shutil.copy(file_to_reduce, tmpfile)
-
-  cmd = crash_cmd + ['-E', '-P']
-  p = 

[PATCH] D59725: Additions to creduce script

2019-03-29 Thread Amy Huang via Phabricator via cfe-commits
akhuang marked 2 inline comments as done.
akhuang added inline comments.



Comment at: clang/utils/creduce-clang-crash.py:208
+print("\nTrying to preprocess the source file...")
+# use delete=False in case the tmpfile flag causes problems when copying
+with tempfile.NamedTemporaryFile(delete=False) as tmpfile:

arichardson wrote:
> I believe we are currently not deleting this temporary file.
> Can `delete=False` be removed since we are using `shutil.copy()` instead of a 
> move?
> 
Yeah, I think that should be fine. 


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

https://reviews.llvm.org/D59725



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


[PATCH] D59806: [clang-tidy] Add a check for [super self] in initializers 

2019-03-29 Thread Jordan Rose via Phabricator via cfe-commits
jordan_rose added a comment.

I don't think there's ever a reason to call `[super self]`, and doing so 
through a macro could easily indicate a bug.

Diagnostic nitpick: the Objective-C term is "init method", not "initializer".


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D59806



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


[PATCH] D59802: [clang-tidy] Add new checker: llvm-avoid-cast-in-conditional

2019-03-29 Thread Don Hinton via Phabricator via cfe-commits
hintonda added a comment.

In D59802#1447560 , @aaron.ballman 
wrote:

> In D59802#1445566 , @hintonda wrote:
>
> > I looked at the IR generated at `-O2`, and found that while `if 
> > (isa(y))` is a modest win over `if (dyn_cast(y)`,  `if 
> > (dyn_cast_or_null(y))` generates exactly the same IR that `if(y && 
> > isa(y))` does.  Also, if `y` is actually an expression that makes a 
> > function call, it's more expensive because it will make the call twice.
> >
> > So I don't seen any reason to replace `dyn_cast_or_null<>` in conditionals.
>
>
> Mostly because I think it's more clear with `isa<>` because that's really 
> what it's checking. However, I could see not doing an automatic transform in 
> the case where the expression argument is something expensive, like a 
> function call. I could also see this as an impetus for adding `isa_or_null<>` 
> as a separate commit.


My last patch only changes `if(y && isa(y))` if `y` is a 
`CXXMemberCallExpr`, so I hope that addresses your concern.




Comment at: 
clang-tools-extra/clang-tidy/llvm/AvoidCastInConditionalCheck.cpp:145
+
+diag(MatchedDecl->getBeginLoc(), "use dyn_cast_or_null")
+<< FixItHint::CreateReplacement(SourceRange(MatchedDecl->getBeginLoc(),

aaron.ballman wrote:
> This diagnostic doesn't tell the user what they've done wrong with the code 
> or why this is a better choice.
Yes, but I'm not yet sure what it should say.  Was sorta hoping for a 
suggestion.  


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D59802



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


[PATCH] D59827: [slh] x86 impl of ARM instrinsic for SLH

2019-03-29 Thread Zola Bridges via Phabricator via cfe-commits
zbrid updated this revision to Diff 192845.
zbrid added a comment.

update with clang-format


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D59827

Files:
  clang/include/clang/Basic/Builtins.def
  clang/include/clang/Basic/DiagnosticSemaKinds.td
  clang/include/clang/Sema/Sema.h
  clang/lib/CodeGen/CGBuiltin.cpp
  clang/lib/Frontend/InitPreprocessor.cpp
  clang/lib/Sema/SemaChecking.cpp
  clang/test/CodeGen/builtin-speculation-safe-value.c
  clang/test/Preprocessor/init.c
  llvm/include/llvm/CodeGen/ISDOpcodes.h
  llvm/include/llvm/IR/IntrinsicsX86.td
  llvm/include/llvm/Target/TargetSelectionDAG.td
  llvm/lib/CodeGen/SelectionDAG/LegalizeIntegerTypes.cpp
  llvm/lib/CodeGen/SelectionDAG/LegalizeTypes.h
  llvm/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp
  llvm/lib/CodeGen/SelectionDAG/SelectionDAGDumper.cpp
  llvm/lib/Target/X86/X86ISelLowering.cpp
  llvm/lib/Target/X86/X86ISelLowering.h
  llvm/lib/Target/X86/X86InstrInfo.td
  llvm/lib/Target/X86/X86SpeculativeLoadHardening.cpp
  llvm/test/CodeGen/X86/speculative-load-hardening-intrinsic.ll

Index: llvm/test/CodeGen/X86/speculative-load-hardening-intrinsic.ll
===
--- /dev/null
+++ llvm/test/CodeGen/X86/speculative-load-hardening-intrinsic.ll
@@ -0,0 +1,62 @@
+;
+RUN : llc < % s - mtriple = x86_64 - unknown - linux - gnu | FileCheck % s-- check - prefix = X64
+
+;
+ModuleID = 'hello.cpp' source_filename = "hello.cpp" target datalayout = "e-m:e-i64:64-f80:128-n8:16:32:64-S128" target triple = "x86_64-unknown-linux-gnu"
+
+;
+Function Attrs : noinline nounwind optnone uwtable
+ define dso_local i32 @_Z5foo32i(i32 % a) #0 {
+entry:
+  % a.addr = alloca i32, align 4 % b = alloca i32, align 4 % b_safe = alloca i32, align 4 % c = alloca i32, align 4 store i32 % a, i32 * % a.addr, align 4 % 0 = load i32, i32 * % a.addr, align 4 % mul = mul nsw i32 % 0, 100 store i32 % mul, i32 * % b, align 4 % 1 = load i32, i32 * % b, align 4 % 2 = call i32 @llvm.speculationsafevalue.i32(i32 % 1);
+X64:
+  movl - 12(% rbp), % eax;
+X64:
+  lfence;
+X64:
+  movl % eax, -8(% rbp) store i32 % 2, i32 * % b_safe, align 4 % 3 = load i32, i32 * % b_safe, align 4 % add = add nsw i32 % 3, 100 store i32 % add, i32 * % c, align 4 % 4 = load i32, i32 * % c, align 4 ret i32 % 4
+}
+
+;
+Function Attrs : nounwind
+ declare i32 @llvm.speculationsafevalue.i32(i32) #1
+
+;
+Function Attrs : noinline nounwind optnone uwtable
+ define dso_local i32 @_Z5foo64i(i32 % a) #0 {
+entry:
+  % a.addr = alloca i32, align 4 % b = alloca i64, align 8 % b_safe = alloca i64, align 8 % c = alloca i64, align 8 store i32 % a, i32 * % a.addr, align 4 % 0 = load i32, i32 * % a.addr, align 4 % mul = mul nsw i32 % 0, 100 % conv = sext i32 % mul to i64 store i64 % conv, i64 * % b, align 8 % 1 = load i64, i64 * % b, align 8 % 2 = call i64 @llvm.speculationsafevalue.i64(i64 % 1);
+X64:
+  movq - 32(% rbp), % rax;
+X64:
+  lfence;
+X64:
+  movq % rax, -24(% rbp) store i64 % 2, i64 * % b_safe, align 8 % 3 = load i64, i64 * % b_safe, align 8 % add = add nsw i64 % 3, 100 store i64 % add, i64 * % c, align 8 % 4 = load i64, i64 * % c, align 8 % conv1 = trunc i64 % 4 to i32 ret i32 % conv1
+}
+
+;
+Function Attrs : nounwind
+ declare i64 @llvm.speculationsafevalue.i64(i64) #1
+
+ attributes #0 = {noinline nounwind optnone uwtable "correctly-rounded-divide-sqrt-fp-math" = "false"
+  "disable-tail-calls" = "false"
+ "less-precise-fpmad" = "false"
+"min-legal-vector-width" = "0"
+   "no-frame-pointer-elim" = "true"
+ "no-frame-pointer-elim-non-leaf"
+ "no-infs-fp-math" = "false"
+  

[PATCH] D59802: [clang-tidy] Add new checker: llvm-avoid-cast-in-conditional

2019-03-29 Thread Don Hinton via Phabricator via cfe-commits
hintonda updated this revision to Diff 192844.
hintonda marked 3 inline comments as done.
hintonda added a comment.

- Address comments.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D59802

Files:
  clang-tools-extra/clang-tidy/llvm/AvoidCastInConditionalCheck.cpp
  clang-tools-extra/clang-tidy/llvm/AvoidCastInConditionalCheck.h
  clang-tools-extra/clang-tidy/llvm/CMakeLists.txt
  clang-tools-extra/clang-tidy/llvm/LLVMTidyModule.cpp
  clang-tools-extra/clang-tidy/utils/HeaderFileExtensionsUtils.h
  clang-tools-extra/docs/ReleaseNotes.rst
  clang-tools-extra/docs/clang-tidy/checks/list.rst
  clang-tools-extra/docs/clang-tidy/checks/llvm-avoid-cast-in-conditional.rst
  clang-tools-extra/test/clang-tidy/llvm-avoid-cast-in-conditional.cpp

Index: clang-tools-extra/test/clang-tidy/llvm-avoid-cast-in-conditional.cpp
===
--- /dev/null
+++ clang-tools-extra/test/clang-tidy/llvm-avoid-cast-in-conditional.cpp
@@ -0,0 +1,118 @@
+// RUN: %check_clang_tidy %s llvm-avoid-cast-in-conditional %t
+
+#define CAST(T, Obj) cast(Obj)
+#define ISA(T, Obj) isa(Obj)
+#define ISA_OR_NULL(T, Obj) Obj && isa(Obj)
+
+struct X;
+struct Y;
+struct Z {
+  int foo();
+  X *bar();
+};
+
+template 
+bool isa(Y *);
+template 
+X *cast(Y *);
+template 
+X *dyn_cast(Y *);
+template 
+X *dyn_cast_or_null(Y *);
+
+bool foo(Y *y, Z *z) {
+  if (auto x = cast(y))
+return true;
+  // CHECK-MESSAGES: :[[@LINE-2]]:16: warning: {{cast<> in conditional .*llvm-avoid-cast-in-conditional}}
+  // CHECK-FIXES: if (auto x = dyn_cast(y))
+
+  if (cast(y))
+return true;
+  // CHECK-MESSAGES: :[[@LINE-2]]:7: warning:  {{cast<> in conditional .*llvm-avoid-cast-in-conditional}}
+  // CHECK-FIXES: if (isa(y))
+
+  if (dyn_cast(y))
+return true;
+  // CHECK-MESSAGES: :[[@LINE-2]]:7: warning:  {{.*dyn_cast<> not used .*llvm-avoid-cast-in-conditional}}
+  // CHECK-FIXES: if (isa(y))
+
+  // These don't trigger a warning.
+  if (auto x = cast(y)->foo())
+return true;
+  if (cast(y)->foo())
+return true;
+
+  while (auto x = cast(y))
+break;
+  // CHECK-MESSAGES: :[[@LINE-2]]:19: warning:  {{cast<> in conditional .*llvm-avoid-cast-in-conditional}}
+  // CHECK-FIXES: while (auto x = dyn_cast(y))
+
+  while (cast(y))
+break;
+  // CHECK-MESSAGES: :[[@LINE-2]]:10: warning:  {{cast<> in conditional .*llvm-avoid-cast-in-conditional}}
+  // CHECK-FIXES: while (isa(y))
+
+  while (dyn_cast(y))
+break;
+  // CHECK-MESSAGES: :[[@LINE-2]]:10: warning:  {{.*dyn_cast<> not used .*llvm-avoid-cast-in-conditional}}
+  // CHECK-FIXES: while (isa(y))
+
+  // These don't trigger a warning.
+  while (auto x = cast(y)->foo())
+break;
+  while (cast(y)->foo())
+break;
+
+  do {
+break;
+  } while (cast(y));
+  // CHECK-MESSAGES: :[[@LINE-1]]:12: warning:  {{cast<> in conditional .*llvm-avoid-cast-in-conditional}}
+  // CHECK-FIXES: while (isa(y));
+
+  do {
+break;
+  } while (dyn_cast(y));
+  // CHECK-MESSAGES: :[[@LINE-1]]:12: warning:  {{.*dyn_cast<> not used .*llvm-avoid-cast-in-conditional}}
+  // CHECK-FIXES: while (isa(y));
+
+  if (z->bar() && isa(z->bar()))
+return true;
+  // CHECK-MESSAGES: :[[@LINE-2]]:7: warning:  {{.*use dyn_cast_or_null .*llvm-avoid-cast-in-conditional}}
+  // CHECK-FIXES: if (dyn_cast_or_null(z->bar()))
+
+  if (z->bar() && cast(z->bar()))
+return true;
+  // CHECK-MESSAGES: :[[@LINE-2]]:7: warning:  {{.*use dyn_cast_or_null .*llvm-avoid-cast-in-conditional}}
+  // CHECK-FIXES: if (dyn_cast_or_null(z->bar()))
+
+  if (z->bar() && dyn_cast(z->bar()))
+return true;
+  // CHECK-MESSAGES: :[[@LINE-2]]:7: warning:  {{.*use dyn_cast_or_null .*llvm-avoid-cast-in-conditional}}
+  // CHECK-FIXES: if (dyn_cast_or_null(z->bar()))
+
+  if (z->bar() && dyn_cast_or_null(z->bar()))
+return true;
+  // CHECK-MESSAGES: :[[@LINE-2]]:7: warning:  {{.*use dyn_cast_or_null .*llvm-avoid-cast-in-conditional}}
+  // CHECK-FIXES: if (dyn_cast_or_null(z->bar()))
+
+  bool b = z->bar() && cast(z->bar());
+  // CHECK-MESSAGES: :[[@LINE-1]]:12: warning:  {{.*use dyn_cast_or_null .*llvm-avoid-cast-in-conditional}}
+  // CHECK-FIXES: bool b = dyn_cast_or_null(z->bar());
+
+  // These don't trigger a warning.
+  if (auto x = CAST(X, y))
+return true;
+  if (z->bar() && ISA(Y, z->bar()))
+return true;
+  if (ISA_OR_NULL(Y, z->bar()))
+return true;
+  if (y && isa(y))
+return true;
+  if (y && cast(z->bar()))
+return true;
+  if (z && cast(y)->foo())
+return true;
+  bool b2 = y && cast(z);
+
+  return false;
+}
Index: clang-tools-extra/docs/clang-tidy/checks/llvm-avoid-cast-in-conditional.rst
===
--- /dev/null
+++ clang-tools-extra/docs/clang-tidy/checks/llvm-avoid-cast-in-conditional.rst
@@ -0,0 +1,28 @@
+.. title:: clang-tidy - llvm-avoid-cast-in-conditional
+

[PATCH] D59887: [Syntax] Introduce TokenBuffer, start clangToolingSyntax library

2019-03-29 Thread Ilya Biryukov via Phabricator via cfe-commits
ilya-biryukov updated this revision to Diff 192839.
ilya-biryukov marked 19 inline comments as done and 2 inline comments as done.
ilya-biryukov added a comment.

- Rename various things.
- Update doc comments.
- Search tokens in the tests by spelling, not by kind.
- Add more tests.
- Fix typos.
- Address other comments.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D59887

Files:
  clang/include/clang/Tooling/Syntax/TokenBuffer.h
  clang/lib/Tooling/CMakeLists.txt
  clang/lib/Tooling/Syntax/CMakeLists.txt
  clang/lib/Tooling/Syntax/TokenBuffer.cpp
  clang/unittests/Tooling/CMakeLists.txt
  clang/unittests/Tooling/Syntax/CMakeLists.txt
  clang/unittests/Tooling/Syntax/TokenBufferTest.cpp

Index: clang/unittests/Tooling/Syntax/TokenBufferTest.cpp
===
--- /dev/null
+++ clang/unittests/Tooling/Syntax/TokenBufferTest.cpp
@@ -0,0 +1,507 @@
+//===- TokenBufferTest.cpp ===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+
+#include "clang/Tooling/Syntax/TokenBuffer.h"
+#include "clang/AST/ASTConsumer.h"
+#include "clang/AST/Expr.h"
+#include "clang/Basic/Diagnostic.h"
+#include "clang/Basic/DiagnosticIDs.h"
+#include "clang/Basic/DiagnosticOptions.h"
+#include "clang/Basic/FileManager.h"
+#include "clang/Basic/FileSystemOptions.h"
+#include "clang/Basic/LLVM.h"
+#include "clang/Basic/LangOptions.h"
+#include "clang/Basic/SourceLocation.h"
+#include "clang/Basic/SourceManager.h"
+#include "clang/Basic/TokenKinds.def"
+#include "clang/Basic/TokenKinds.h"
+#include "clang/Frontend/CompilerInstance.h"
+#include "clang/Frontend/FrontendAction.h"
+#include "clang/Frontend/Utils.h"
+#include "clang/Lex/Lexer.h"
+#include "clang/Lex/PreprocessorOptions.h"
+#include "clang/Lex/Token.h"
+#include "clang/Tooling/Tooling.h"
+#include "llvm/ADT/ArrayRef.h"
+#include "llvm/ADT/IntrusiveRefCntPtr.h"
+#include "llvm/ADT/STLExtras.h"
+#include "llvm/ADT/StringRef.h"
+#include "llvm/Support/FormatVariadic.h"
+#include "llvm/Support/MemoryBuffer.h"
+#include "llvm/Support/VirtualFileSystem.h"
+#include "llvm/Support/raw_os_ostream.h"
+#include "llvm/Support/raw_ostream.h"
+#include "llvm/Testing/Support/Annotations.h"
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+
+using namespace clang;
+using namespace clang::syntax;
+
+using ::testing::AllOf;
+using ::testing::Contains;
+using ::testing::ElementsAre;
+using ::testing::IsEmpty;
+using ::testing::Matcher;
+using ::testing::Pointwise;
+
+// Debug printers.
+// FIXME: This should live somewhere else or be implemented as 'operator
+// <<(raw_ostream&, T)'.
+namespace clang {
+namespace tok {
+inline void PrintTo(TokenKind K, std::ostream *OS) {
+  *OS << tok::getTokenName(K);
+}
+} // namespace tok
+namespace syntax {
+inline void PrintTo(const syntax::Token , std::ostream *OS) {
+  PrintTo(T.kind(), OS);
+  OS->flush();
+}
+} // namespace syntax
+} // namespace clang
+
+namespace {
+// Matchers for clang::Token.
+MATCHER_P(Kind, K, "") { return arg.kind() == K; }
+MATCHER_P2(HasText, Text, SourceMgr, "") {
+  return arg.text(*SourceMgr) == Text;
+}
+MATCHER_P2(IsIdent, Text, SourceMgr, "") {
+  return arg.kind() == tok::identifier && arg.text(*SourceMgr) == Text;
+}
+/// Checks the start and end location of a token are equal to SourceRng.
+MATCHER_P(RangeIs, SourceRng, "") {
+  return arg.location() == SourceRng.first &&
+ arg.endLocation() == SourceRng.second;
+}
+/// Checks the passed tuple has two similar tokens, i.e. both are of the same
+/// kind and have the same text if they are identifiers.
+MATCHER_P(IsSameToken, SourceMgr, "") {
+  auto  = std::get<0>(arg);
+  auto  = std::get<1>(arg);
+  if (L.kind() != R.kind())
+return false;
+  return L.text(*SourceMgr) == L.text(*SourceMgr);
+}
+
+class TokenBufferTest : public ::testing::Test {
+public:
+  /// Run the clang frontend, collect the preprocessed tokens from the frontend
+  /// invocation and store them in this->Buffer.
+  /// This also clears SourceManager before running the compiler.
+  void recordTokens(llvm::StringRef Code) {
+class RecordTokens : public ASTFrontendAction {
+public:
+  explicit RecordTokens(TokenBuffer ) : Result(Result) {}
+
+  bool BeginSourceFileAction(CompilerInstance ) override {
+assert(!Collector && "expected only a single call to BeginSourceFile");
+Collector.emplace(CI.getPreprocessor());
+return true;
+  }
+  void EndSourceFileAction() override {
+assert(Collector && "BeginSourceFileAction was never called");
+Result = 

[PATCH] D59887: [Syntax] Introduce TokenBuffer, start clangToolingSyntax library

2019-03-29 Thread Ilya Biryukov via Phabricator via cfe-commits
ilya-biryukov added a comment.

Still have a few comments to address in `TokenCollector` and wrt to naming. But 
apart from this revision is ready for another round.




Comment at: clang/include/clang/Tooling/Syntax/TokenBuffer.h:120
+  /// the original source file. The tranformation may not be possible if the
+  /// tokens cross macro invocations in the middle, e.g.
+  ///#define FOO 1*2

gribozavr wrote:
> "The mapping fails if cross boundaries of macro expansions, that is, don't 
> correspond to a complete top-level macro invocation"
> 
> Consider adding examples.
> 
> ```
> Given this source file:
> 
> #define FIRST f1 f2 f3
> #define SECOND s1 s2 3
> 
> a FIRST b SECOND c  // expansion: a f1 f2 f3 b s1 s2 s3 c
> 
> toOffsetRange will map tokens like this:
> 
> input range => output range
> a => a
> s1 s2 s3 => SECOND
> a f1 f2 f3 => a FIRST
> a f1 => can't map
> s1 s2 => s1 s2 within the macro definition
> ```
> 
> Could you add these to tests as well?
Done. Note that we never map to tokens inside macro definition (the `s1 s2` 
example)



Comment at: clang/include/clang/Tooling/Syntax/TokenBuffer.h:191
+  /// i.e. after running Execute().
+  TokenBuffer consume() &&;
+

gribozavr wrote:
> gribozavr wrote:
> > "Finalizes token collection"
> > 
> > Of course a function called "consume" consumes the result :)
> LLVM_NODISCARD?
> Of course a function called "consume" consumes the result :)

Agreed :-)



Comment at: clang/lib/Tooling/Syntax/TokenBuffer.cpp:295
+MacroExpansion::tokens(const TokenBuffer ) const {
+  return B.tokens().slice(BeginExpansionToken,
+  EndExpansionToken - BeginExpansionToken);

gribozavr wrote:
> "ExpansionTokenBegin"?  "ExpansionTokenStartIndex"?
Went with `BeginExpandedToken`, `EndExpandedToken`.



Comment at: clang/unittests/Tooling/Syntax/TokenBufferTest.cpp:190
+for (unsigned I = 0; I < Actual.size(); ++I) {
+  auto  = Actual[I];
+  auto  = Expected[I];

Eugene.Zelenko wrote:
> Return type is not obvious, so auto should not be used.
The declarations of `Actual` and `Expected` are **really** close, both types 
are easy to infer



Comment at: clang/unittests/Tooling/Syntax/TokenBufferTest.cpp:429
+  Code = llvm::Annotations(R"cpp(
+$all[[int $a[[a]] = $numbers[[100 + 200]];]]
+  )cpp");

gribozavr wrote:
> Could we instead use some nonsensical code like "a1 a2 a3 FIRST a3 a4 a5 
> SECOND a6 a7 a8", and instead of `OfKind` we can make a helper that finds the 
> identifier with the given name?
Thanks. Much nicer with a function that finds by text.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D59887



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


[PATCH] D59998: [Sema] Remove unneeded call to LookupResult::resolveKind

2019-03-29 Thread Tom Rix via Phabricator via cfe-commits
trixirt created this revision.
trixirt added a reviewer: rjmccall.
trixirt added a project: clang.
Herald added a subscriber: cfe-commits.

>From code inspection it was noticed that CppNamespaceLookup's
caller CppLookupName calls LookupResult::resolveKind when
CppNamespaceLookup was successful or had an earlier success.


Repository:
  rC Clang

https://reviews.llvm.org/D59998

Files:
  lib/Sema/SemaLookup.cpp


Index: lib/Sema/SemaLookup.cpp
===
--- lib/Sema/SemaLookup.cpp
+++ lib/Sema/SemaLookup.cpp
@@ -948,7 +948,7 @@
 if (LookupDirect(S, R, UUE.getNominatedNamespace()))
   Found = true;
 
-  R.resolveKind();
+  // Defer resolution to the caller.
 
   return Found;
 }


Index: lib/Sema/SemaLookup.cpp
===
--- lib/Sema/SemaLookup.cpp
+++ lib/Sema/SemaLookup.cpp
@@ -948,7 +948,7 @@
 if (LookupDirect(S, R, UUE.getNominatedNamespace()))
   Found = true;
 
-  R.resolveKind();
+  // Defer resolution to the caller.
 
   return Found;
 }
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


Re: r357255 - clang-cl: Expose -fprofile-generate and -fcs-profile-generate (PR41252)

2019-03-29 Thread Hans Wennborg via cfe-commits
I guess it's not really needed, but I'm also not sure how much we want
users to have to rely on the /clang: flag.

On Fri, Mar 29, 2019 at 3:43 PM Nico Weber via cfe-commits
 wrote:
>
> Do we still need changes like this now that we have the /clang: switch?
>
> On Fri, Mar 29, 2019 at 10:02 AM Hans Wennborg via cfe-commits 
>  wrote:
>>
>> Author: hans
>> Date: Fri Mar 29 07:03:34 2019
>> New Revision: 357255
>>
>> URL: http://llvm.org/viewvc/llvm-project?rev=357255=rev
>> Log:
>> clang-cl: Expose -fprofile-generate and -fcs-profile-generate (PR41252)
>>
>> Modified:
>> cfe/trunk/include/clang/Driver/Options.td
>> cfe/trunk/test/Driver/cl-options.c
>>
>> Modified: cfe/trunk/include/clang/Driver/Options.td
>> URL: 
>> http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Driver/Options.td?rev=357255=357254=357255=diff
>> ==
>> --- cfe/trunk/include/clang/Driver/Options.td (original)
>> +++ cfe/trunk/include/clang/Driver/Options.td Fri Mar 29 07:03:34 2019
>> @@ -742,16 +742,16 @@ def fno_coverage_mapping : Flag<["-"], "
>>  Group, Flags<[DriverOption, CoreOption]>,
>>  HelpText<"Disable code coverage analysis">;
>>  def fprofile_generate : Flag<["-"], "fprofile-generate">,
>> -Group, Flags<[DriverOption]>,
>> +Group, Flags<[CoreOption]>,
>>  HelpText<"Generate instrumented code to collect execution counts into 
>> default.profraw (overridden by LLVM_PROFILE_FILE env var)">;
>>  def fprofile_generate_EQ : Joined<["-"], "fprofile-generate=">,
>> -Group, Flags<[DriverOption]>, MetaVarName<"">,
>> +Group, Flags<[CoreOption]>, MetaVarName<"">,
>>  HelpText<"Generate instrumented code to collect execution counts into 
>> /default.profraw (overridden by LLVM_PROFILE_FILE env var)">;
>>  def fcs_profile_generate : Flag<["-"], "fcs-profile-generate">,
>> -Group, Flags<[DriverOption]>,
>> +Group, Flags<[CoreOption]>,
>>  HelpText<"Generate instrumented code to collect context sensitive 
>> execution counts into default.profraw (overridden by LLVM_PROFILE_FILE env 
>> var)">;
>>  def fcs_profile_generate_EQ : Joined<["-"], "fcs-profile-generate=">,
>> -Group, Flags<[DriverOption]>, MetaVarName<"">,
>> +Group, Flags<[CoreOption]>, MetaVarName<"">,
>>  HelpText<"Generate instrumented code to collect context sensitive 
>> execution counts into /default.profraw (overridden by 
>> LLVM_PROFILE_FILE env var)">;
>>  def fprofile_use : Flag<["-"], "fprofile-use">, Group,
>>  Alias;
>> @@ -759,13 +759,13 @@ def fprofile_use_EQ : Joined<["-"], "fpr
>>  Group, Flags<[DriverOption]>, MetaVarName<"">,
>>  HelpText<"Use instrumentation data for profile-guided optimization. If 
>> pathname is a directory, it reads from /default.profdata. 
>> Otherwise, it reads from file .">;
>>  def fno_profile_instr_generate : Flag<["-"], "fno-profile-instr-generate">,
>> -Group, Flags<[DriverOption]>,
>> +Group, Flags<[CoreOption]>,
>>  HelpText<"Disable generation of profile instrumentation.">;
>>  def fno_profile_generate : Flag<["-"], "fno-profile-generate">,
>> -Group, Flags<[DriverOption]>,
>> +Group, Flags<[CoreOption]>,
>>  HelpText<"Disable generation of profile instrumentation.">;
>>  def fno_profile_instr_use : Flag<["-"], "fno-profile-instr-use">,
>> -Group, Flags<[DriverOption]>,
>> +Group, Flags<[CoreOption]>,
>>  HelpText<"Disable using instrumentation data for profile-guided 
>> optimization">;
>>  def fno_profile_use : Flag<["-"], "fno-profile-use">,
>>  Alias;
>>
>> Modified: cfe/trunk/test/Driver/cl-options.c
>> URL: 
>> http://llvm.org/viewvc/llvm-project/cfe/trunk/test/Driver/cl-options.c?rev=357255=357254=357255=diff
>> ==
>> --- cfe/trunk/test/Driver/cl-options.c (original)
>> +++ cfe/trunk/test/Driver/cl-options.c Fri Mar 29 07:03:34 2019
>> @@ -630,6 +630,13 @@
>>  // RUN: -no-canonical-prefixes \
>>  // RUN: -march=skylake \
>>  // RUN: -fbracket-depth=123 \
>> +// RUN: -fprofile-generate \
>> +// RUN: -fprofile-generate=dir \
>> +// RUN: -fno-profile-generate \
>> +// RUN: -fno-profile-instr-generate \
>> +// RUN: -fno-profile-instr-use \
>> +// RUN: -fcs-profile-generate \
>> +// RUN: -fcs-profile-generate=dir \
>>  // RUN: --version \
>>  // RUN: -Werror /Zs -- %s 2>&1
>>
>>
>>
>> ___
>> cfe-commits mailing list
>> cfe-commits@lists.llvm.org
>> https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
>
> ___
> cfe-commits mailing list
> cfe-commits@lists.llvm.org
> https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


Re: r357255 - clang-cl: Expose -fprofile-generate and -fcs-profile-generate (PR41252)

2019-03-29 Thread Nico Weber via cfe-commits
Do we still need changes like this now that we have the /clang: switch?

On Fri, Mar 29, 2019 at 10:02 AM Hans Wennborg via cfe-commits <
cfe-commits@lists.llvm.org> wrote:

> Author: hans
> Date: Fri Mar 29 07:03:34 2019
> New Revision: 357255
>
> URL: http://llvm.org/viewvc/llvm-project?rev=357255=rev
> Log:
> clang-cl: Expose -fprofile-generate and -fcs-profile-generate (PR41252)
>
> Modified:
> cfe/trunk/include/clang/Driver/Options.td
> cfe/trunk/test/Driver/cl-options.c
>
> Modified: cfe/trunk/include/clang/Driver/Options.td
> URL:
> http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Driver/Options.td?rev=357255=357254=357255=diff
>
> ==
> --- cfe/trunk/include/clang/Driver/Options.td (original)
> +++ cfe/trunk/include/clang/Driver/Options.td Fri Mar 29 07:03:34 2019
> @@ -742,16 +742,16 @@ def fno_coverage_mapping : Flag<["-"], "
>  Group, Flags<[DriverOption, CoreOption]>,
>  HelpText<"Disable code coverage analysis">;
>  def fprofile_generate : Flag<["-"], "fprofile-generate">,
> -Group, Flags<[DriverOption]>,
> +Group, Flags<[CoreOption]>,
>  HelpText<"Generate instrumented code to collect execution counts into
> default.profraw (overridden by LLVM_PROFILE_FILE env var)">;
>  def fprofile_generate_EQ : Joined<["-"], "fprofile-generate=">,
> -Group, Flags<[DriverOption]>, MetaVarName<"">,
> +Group, Flags<[CoreOption]>, MetaVarName<"">,
>  HelpText<"Generate instrumented code to collect execution counts into
> /default.profraw (overridden by LLVM_PROFILE_FILE env var)">;
>  def fcs_profile_generate : Flag<["-"], "fcs-profile-generate">,
> -Group, Flags<[DriverOption]>,
> +Group, Flags<[CoreOption]>,
>  HelpText<"Generate instrumented code to collect context sensitive
> execution counts into default.profraw (overridden by LLVM_PROFILE_FILE env
> var)">;
>  def fcs_profile_generate_EQ : Joined<["-"], "fcs-profile-generate=">,
> -Group, Flags<[DriverOption]>, MetaVarName<"">,
> +Group, Flags<[CoreOption]>, MetaVarName<"">,
>  HelpText<"Generate instrumented code to collect context sensitive
> execution counts into /default.profraw (overridden by
> LLVM_PROFILE_FILE env var)">;
>  def fprofile_use : Flag<["-"], "fprofile-use">, Group,
>  Alias;
> @@ -759,13 +759,13 @@ def fprofile_use_EQ : Joined<["-"], "fpr
>  Group, Flags<[DriverOption]>, MetaVarName<"">,
>  HelpText<"Use instrumentation data for profile-guided optimization.
> If pathname is a directory, it reads from /default.profdata.
> Otherwise, it reads from file .">;
>  def fno_profile_instr_generate : Flag<["-"],
> "fno-profile-instr-generate">,
> -Group, Flags<[DriverOption]>,
> +Group, Flags<[CoreOption]>,
>  HelpText<"Disable generation of profile instrumentation.">;
>  def fno_profile_generate : Flag<["-"], "fno-profile-generate">,
> -Group, Flags<[DriverOption]>,
> +Group, Flags<[CoreOption]>,
>  HelpText<"Disable generation of profile instrumentation.">;
>  def fno_profile_instr_use : Flag<["-"], "fno-profile-instr-use">,
> -Group, Flags<[DriverOption]>,
> +Group, Flags<[CoreOption]>,
>  HelpText<"Disable using instrumentation data for profile-guided
> optimization">;
>  def fno_profile_use : Flag<["-"], "fno-profile-use">,
>  Alias;
>
> Modified: cfe/trunk/test/Driver/cl-options.c
> URL:
> http://llvm.org/viewvc/llvm-project/cfe/trunk/test/Driver/cl-options.c?rev=357255=357254=357255=diff
>
> ==
> --- cfe/trunk/test/Driver/cl-options.c (original)
> +++ cfe/trunk/test/Driver/cl-options.c Fri Mar 29 07:03:34 2019
> @@ -630,6 +630,13 @@
>  // RUN: -no-canonical-prefixes \
>  // RUN: -march=skylake \
>  // RUN: -fbracket-depth=123 \
> +// RUN: -fprofile-generate \
> +// RUN: -fprofile-generate=dir \
> +// RUN: -fno-profile-generate \
> +// RUN: -fno-profile-instr-generate \
> +// RUN: -fno-profile-instr-use \
> +// RUN: -fcs-profile-generate \
> +// RUN: -fcs-profile-generate=dir \
>  // RUN: --version \
>  // RUN: -Werror /Zs -- %s 2>&1
>
>
>
> ___
> cfe-commits mailing list
> cfe-commits@lists.llvm.org
> https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
>
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D59815: [Driver] Enable -fsanitize-address-globals-dead-stripping by default on PS4.

2019-03-29 Thread Paul Robinson via Phabricator via cfe-commits
probinson accepted this revision.
probinson added a comment.
This revision is now accepted and ready to land.

LGTM


Repository:
  rC Clang

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

https://reviews.llvm.org/D59815



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


[PATCH] D59329: [LibTooling] Add NodeId, a strong type for AST-matcher node identifiers.

2019-03-29 Thread Ilya Biryukov via Phabricator via cfe-commits
ilya-biryukov added a comment.

Could you provide the rationale for having `NodeID` vs just using strings for 
the binds?
Is this just a more type-safe way to do the same thing or is that actually 
required to solve a particular problem?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D59329



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


r357255 - clang-cl: Expose -fprofile-generate and -fcs-profile-generate (PR41252)

2019-03-29 Thread Hans Wennborg via cfe-commits
Author: hans
Date: Fri Mar 29 07:03:34 2019
New Revision: 357255

URL: http://llvm.org/viewvc/llvm-project?rev=357255=rev
Log:
clang-cl: Expose -fprofile-generate and -fcs-profile-generate (PR41252)

Modified:
cfe/trunk/include/clang/Driver/Options.td
cfe/trunk/test/Driver/cl-options.c

Modified: cfe/trunk/include/clang/Driver/Options.td
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Driver/Options.td?rev=357255=357254=357255=diff
==
--- cfe/trunk/include/clang/Driver/Options.td (original)
+++ cfe/trunk/include/clang/Driver/Options.td Fri Mar 29 07:03:34 2019
@@ -742,16 +742,16 @@ def fno_coverage_mapping : Flag<["-"], "
 Group, Flags<[DriverOption, CoreOption]>,
 HelpText<"Disable code coverage analysis">;
 def fprofile_generate : Flag<["-"], "fprofile-generate">,
-Group, Flags<[DriverOption]>,
+Group, Flags<[CoreOption]>,
 HelpText<"Generate instrumented code to collect execution counts into 
default.profraw (overridden by LLVM_PROFILE_FILE env var)">;
 def fprofile_generate_EQ : Joined<["-"], "fprofile-generate=">,
-Group, Flags<[DriverOption]>, MetaVarName<"">,
+Group, Flags<[CoreOption]>, MetaVarName<"">,
 HelpText<"Generate instrumented code to collect execution counts into 
/default.profraw (overridden by LLVM_PROFILE_FILE env var)">;
 def fcs_profile_generate : Flag<["-"], "fcs-profile-generate">,
-Group, Flags<[DriverOption]>,
+Group, Flags<[CoreOption]>,
 HelpText<"Generate instrumented code to collect context sensitive 
execution counts into default.profraw (overridden by LLVM_PROFILE_FILE env 
var)">;
 def fcs_profile_generate_EQ : Joined<["-"], "fcs-profile-generate=">,
-Group, Flags<[DriverOption]>, MetaVarName<"">,
+Group, Flags<[CoreOption]>, MetaVarName<"">,
 HelpText<"Generate instrumented code to collect context sensitive 
execution counts into /default.profraw (overridden by 
LLVM_PROFILE_FILE env var)">;
 def fprofile_use : Flag<["-"], "fprofile-use">, Group,
 Alias;
@@ -759,13 +759,13 @@ def fprofile_use_EQ : Joined<["-"], "fpr
 Group, Flags<[DriverOption]>, MetaVarName<"">,
 HelpText<"Use instrumentation data for profile-guided optimization. If 
pathname is a directory, it reads from /default.profdata. Otherwise, 
it reads from file .">;
 def fno_profile_instr_generate : Flag<["-"], "fno-profile-instr-generate">,
-Group, Flags<[DriverOption]>,
+Group, Flags<[CoreOption]>,
 HelpText<"Disable generation of profile instrumentation.">;
 def fno_profile_generate : Flag<["-"], "fno-profile-generate">,
-Group, Flags<[DriverOption]>,
+Group, Flags<[CoreOption]>,
 HelpText<"Disable generation of profile instrumentation.">;
 def fno_profile_instr_use : Flag<["-"], "fno-profile-instr-use">,
-Group, Flags<[DriverOption]>,
+Group, Flags<[CoreOption]>,
 HelpText<"Disable using instrumentation data for profile-guided 
optimization">;
 def fno_profile_use : Flag<["-"], "fno-profile-use">,
 Alias;

Modified: cfe/trunk/test/Driver/cl-options.c
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/Driver/cl-options.c?rev=357255=357254=357255=diff
==
--- cfe/trunk/test/Driver/cl-options.c (original)
+++ cfe/trunk/test/Driver/cl-options.c Fri Mar 29 07:03:34 2019
@@ -630,6 +630,13 @@
 // RUN: -no-canonical-prefixes \
 // RUN: -march=skylake \
 // RUN: -fbracket-depth=123 \
+// RUN: -fprofile-generate \
+// RUN: -fprofile-generate=dir \
+// RUN: -fno-profile-generate \
+// RUN: -fno-profile-instr-generate \
+// RUN: -fno-profile-instr-use \
+// RUN: -fcs-profile-generate \
+// RUN: -fcs-profile-generate=dir \
 // RUN: --version \
 // RUN: -Werror /Zs -- %s 2>&1
 


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


[PATCH] D59879: [ARM][CMSE] Add commandline option and feature macro

2019-03-29 Thread Todd Snider via Phabricator via cfe-commits
snidertm added inline comments.



Comment at: lib/Basic/Targets/ARM.cpp:438
+} else if (Feature == "+8msecext") {
+  if ((CPUProfile != "M" && CPUProfile != "B") || ArchVersion != 8) {
+Diags.Report(diag::err_target_unsupported_mcmse) << CPU;

dmgreen wrote:
> snidertm wrote:
> > How does CPUProfile get a value of "B"? I thought any Cortex-M processor 
> > would set CPUProfile to "M". Is CMSE available on a processor besides 
> > Cortex-m33?
> "B" was going to be a very old name for v8m-baseline, looks like this one was 
> never cleaned up when that was changed. You can drop the != "B" check.
Do all v8 profile == 'M' processor variants support security extensions?


Repository:
  rC Clang

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

https://reviews.llvm.org/D59879



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


[clang-tools-extra] r357253 - Fix MSVC "not all control paths return a value" warning. NFCI.

2019-03-29 Thread Simon Pilgrim via cfe-commits
Author: rksimon
Date: Fri Mar 29 06:43:00 2019
New Revision: 357253

URL: http://llvm.org/viewvc/llvm-project?rev=357253=rev
Log:
Fix MSVC "not all control paths return a value" warning. NFCI.

Modified:
clang-tools-extra/trunk/clangd/Protocol.cpp

Modified: clang-tools-extra/trunk/clangd/Protocol.cpp
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clangd/Protocol.cpp?rev=357253=357252=357253=diff
==
--- clang-tools-extra/trunk/clangd/Protocol.cpp (original)
+++ clang-tools-extra/trunk/clangd/Protocol.cpp Fri Mar 29 06:43:00 2019
@@ -949,6 +949,7 @@ static const char *toString(OffsetEncodi
   case OffsetEncoding::UnsupportedEncoding:
 return "unknown";
   }
+  llvm_unreachable("Unknown clang.clangd.OffsetEncoding");
 }
 llvm::json::Value toJSON(const OffsetEncoding ) { return toString(OE); }
 bool fromJSON(const llvm::json::Value , OffsetEncoding ) {


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


[PATCH] D59631: [AArch64] Support selecting TPIDR_EL[1-3] as the thread base

2019-03-29 Thread Oliver Stannard via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rC357250: [AArch64] Support selecting TPIDR_EL[1-3] as the 
thread base (authored by olista01, committed by ).

Changed prior to commit:
  https://reviews.llvm.org/D59631?vs=191800=192814#toc

Repository:
  rC Clang

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

https://reviews.llvm.org/D59631

Files:
  include/clang/Driver/Options.td
  lib/Driver/ToolChains/Arch/AArch64.cpp
  test/Driver/clang-translation.c


Index: include/clang/Driver/Options.td
===
--- include/clang/Driver/Options.td
+++ include/clang/Driver/Options.td
@@ -2016,8 +2016,8 @@
   HelpText<"Disallow generation of data access to code sections (ARM only)">;
 def mno_execute_only : Flag<["-"], "mno-execute-only">, 
Group,
   HelpText<"Allow generation of data access to code sections (ARM only)">;
-def mtp_mode_EQ : Joined<["-"], "mtp=">, Group, 
Values<"soft, cp15">,
-  HelpText<"Read thread pointer from coprocessor register (ARM only)">;
+def mtp_mode_EQ : Joined<["-"], "mtp=">, Group, 
Values<"soft,cp15,el0,el1,el2,el3">,
+  HelpText<"Thread pointer access method (AArch32/AArch64 only)">;
 def mpure_code : Flag<["-"], "mpure-code">, Alias; // Alias for 
GCC compatibility
 def mno_pure_code : Flag<["-"], "mno-pure-code">, Alias;
 def mtvos_version_min_EQ : Joined<["-"], "mtvos-version-min=">, Group;
Index: test/Driver/clang-translation.c
===
--- test/Driver/clang-translation.c
+++ test/Driver/clang-translation.c
@@ -120,6 +120,36 @@
 // RUN: FileCheck -check-prefix=ARMv7_THREAD_POINTER_NON %s
 // ARMv7_THREAD_POINTER_NON-NOT: "-target-feature" "+read-tp-hard"
 
+// RUN: %clang -target aarch64-linux -### -S %s -arch armv8a 2>&1 | \
+// RUN: FileCheck -check-prefix=ARMv8_THREAD_POINTER_NON %s
+// ARMv8_THREAD_POINTER_NON-NOT: "-target-feature" "+tpidr-el1"
+// ARMv8_THREAD_POINTER_NON-NOT: "-target-feature" "+tpidr-el2"
+// ARMv8_THREAD_POINTER_NON-NOT: "-target-feature" "+tpidr-el3"
+
+// RUN: %clang -target aarch64-linux -### -S %s -arch armv8a -mtp=el0 2>&1 | \
+// RUN: FileCheck -check-prefix=ARMv8_THREAD_POINTER_EL0 %s
+// ARMv8_THREAD_POINTER_EL0-NOT: "-target-feature" "+tpidr-el1"
+// ARMv8_THREAD_POINTER_EL0-NOT: "-target-feature" "+tpidr-el2"
+// ARMv8_THREAD_POINTER_EL0-NOT: "-target-feature" "+tpidr-el3"
+
+// RUN: %clang -target aarch64-linux -### -S %s -arch armv8a -mtp=el1 2>&1 | \
+// RUN: FileCheck -check-prefix=ARMv8_THREAD_POINTER_EL1 %s
+// ARMv8_THREAD_POINTER_EL1: "-target-feature" "+tpidr-el1"
+// ARMv8_THREAD_POINTER_EL1-NOT: "-target-feature" "+tpidr-el2"
+// ARMv8_THREAD_POINTER_EL1-NOT: "-target-feature" "+tpidr-el3"
+
+// RUN: %clang -target aarch64-linux -### -S %s -arch armv8a -mtp=el2 2>&1 | \
+// RUN: FileCheck -check-prefix=ARMv8_THREAD_POINTER_EL2 %s
+// ARMv8_THREAD_POINTER_EL2-NOT: "-target-feature" "+tpidr-el1"
+// ARMv8_THREAD_POINTER_EL2: "-target-feature" "+tpidr-el2"
+// ARMv8_THREAD_POINTER_EL2-NOT: "-target-feature" "+tpidr-el3"
+
+// RUN: %clang -target aarch64-linux -### -S %s -arch armv8a -mtp=el3 2>&1 | \
+// RUN: FileCheck -check-prefix=ARMv8_THREAD_POINTER_EL3 %s
+// ARMv8_THREAD_POINTER_EL3-NOT: "-target-feature" "+tpidr-el1"
+// ARMv8_THREAD_POINTER_EL3-NOT: "-target-feature" "+tpidr-el2"
+// ARMv8_THREAD_POINTER_EL3: "-target-feature" "+tpidr-el3"
+
 // RUN: %clang -target powerpc64-unknown-linux-gnu \
 // RUN: -### -S %s -mcpu=G5 2>&1 | FileCheck -check-prefix=PPCG5 %s
 // PPCG5: clang
Index: lib/Driver/ToolChains/Arch/AArch64.cpp
===
--- lib/Driver/ToolChains/Arch/AArch64.cpp
+++ lib/Driver/ToolChains/Arch/AArch64.cpp
@@ -194,6 +194,18 @@
 Features.push_back("-neon");
   }
 
+  if (Arg *A = Args.getLastArg(options::OPT_mtp_mode_EQ)) {
+StringRef Mtp = A->getValue();
+if (Mtp == "el3")
+  Features.push_back("+tpidr-el3");
+else if (Mtp == "el2")
+  Features.push_back("+tpidr-el2");
+else if (Mtp == "el1")
+  Features.push_back("+tpidr-el1");
+else if (Mtp != "el0")
+  D.Diag(diag::err_drv_invalid_mtp) << A->getAsString(Args);
+  }
+
   // En/disable crc
   if (Arg *A = Args.getLastArg(options::OPT_mcrc, options::OPT_mnocrc)) {
 if (A->getOption().matches(options::OPT_mcrc))


Index: include/clang/Driver/Options.td
===
--- include/clang/Driver/Options.td
+++ include/clang/Driver/Options.td
@@ -2016,8 +2016,8 @@
   HelpText<"Disallow generation of data access to code sections (ARM only)">;
 def mno_execute_only : Flag<["-"], "mno-execute-only">, Group,
   HelpText<"Allow generation of data access to code sections (ARM only)">;
-def mtp_mode_EQ : Joined<["-"], "mtp=">, Group, Values<"soft, cp15">,
-  HelpText<"Read thread pointer from coprocessor register (ARM only)">;
+def mtp_mode_EQ : 

r357250 - [AArch64] Support selecting TPIDR_EL[1-3] as the thread base

2019-03-29 Thread Oliver Stannard via cfe-commits
Author: olista01
Date: Fri Mar 29 06:32:41 2019
New Revision: 357250

URL: http://llvm.org/viewvc/llvm-project?rev=357250=rev
Log:
[AArch64] Support selecting TPIDR_EL[1-3] as the thread base

Add an -mtp=el[0-3] option to select which of the AArch64 thread ID registers
will be used for the TLS base pointer.

This is a followup to rL356657 which added subtarget features to enable
accesses to the privileged thread ID registers.

Patch by Philip Derrin!

Differential revision: https://reviews.llvm.org/D59631


Modified:
cfe/trunk/include/clang/Driver/Options.td
cfe/trunk/lib/Driver/ToolChains/Arch/AArch64.cpp
cfe/trunk/test/Driver/clang-translation.c

Modified: cfe/trunk/include/clang/Driver/Options.td
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Driver/Options.td?rev=357250=357249=357250=diff
==
--- cfe/trunk/include/clang/Driver/Options.td (original)
+++ cfe/trunk/include/clang/Driver/Options.td Fri Mar 29 06:32:41 2019
@@ -2016,8 +2016,8 @@ def mexecute_only : Flag<["-"], "mexecut
   HelpText<"Disallow generation of data access to code sections (ARM only)">;
 def mno_execute_only : Flag<["-"], "mno-execute-only">, 
Group,
   HelpText<"Allow generation of data access to code sections (ARM only)">;
-def mtp_mode_EQ : Joined<["-"], "mtp=">, Group, 
Values<"soft, cp15">,
-  HelpText<"Read thread pointer from coprocessor register (ARM only)">;
+def mtp_mode_EQ : Joined<["-"], "mtp=">, Group, 
Values<"soft,cp15,el0,el1,el2,el3">,
+  HelpText<"Thread pointer access method (AArch32/AArch64 only)">;
 def mpure_code : Flag<["-"], "mpure-code">, Alias; // Alias for 
GCC compatibility
 def mno_pure_code : Flag<["-"], "mno-pure-code">, Alias;
 def mtvos_version_min_EQ : Joined<["-"], "mtvos-version-min=">, Group;

Modified: cfe/trunk/lib/Driver/ToolChains/Arch/AArch64.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Driver/ToolChains/Arch/AArch64.cpp?rev=357250=357249=357250=diff
==
--- cfe/trunk/lib/Driver/ToolChains/Arch/AArch64.cpp (original)
+++ cfe/trunk/lib/Driver/ToolChains/Arch/AArch64.cpp Fri Mar 29 06:32:41 2019
@@ -194,6 +194,18 @@ void aarch64::getAArch64TargetFeatures(c
 Features.push_back("-neon");
   }
 
+  if (Arg *A = Args.getLastArg(options::OPT_mtp_mode_EQ)) {
+StringRef Mtp = A->getValue();
+if (Mtp == "el3")
+  Features.push_back("+tpidr-el3");
+else if (Mtp == "el2")
+  Features.push_back("+tpidr-el2");
+else if (Mtp == "el1")
+  Features.push_back("+tpidr-el1");
+else if (Mtp != "el0")
+  D.Diag(diag::err_drv_invalid_mtp) << A->getAsString(Args);
+  }
+
   // En/disable crc
   if (Arg *A = Args.getLastArg(options::OPT_mcrc, options::OPT_mnocrc)) {
 if (A->getOption().matches(options::OPT_mcrc))

Modified: cfe/trunk/test/Driver/clang-translation.c
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/Driver/clang-translation.c?rev=357250=357249=357250=diff
==
--- cfe/trunk/test/Driver/clang-translation.c (original)
+++ cfe/trunk/test/Driver/clang-translation.c Fri Mar 29 06:32:41 2019
@@ -120,6 +120,36 @@
 // RUN: FileCheck -check-prefix=ARMv7_THREAD_POINTER_NON %s
 // ARMv7_THREAD_POINTER_NON-NOT: "-target-feature" "+read-tp-hard"
 
+// RUN: %clang -target aarch64-linux -### -S %s -arch armv8a 2>&1 | \
+// RUN: FileCheck -check-prefix=ARMv8_THREAD_POINTER_NON %s
+// ARMv8_THREAD_POINTER_NON-NOT: "-target-feature" "+tpidr-el1"
+// ARMv8_THREAD_POINTER_NON-NOT: "-target-feature" "+tpidr-el2"
+// ARMv8_THREAD_POINTER_NON-NOT: "-target-feature" "+tpidr-el3"
+
+// RUN: %clang -target aarch64-linux -### -S %s -arch armv8a -mtp=el0 2>&1 | \
+// RUN: FileCheck -check-prefix=ARMv8_THREAD_POINTER_EL0 %s
+// ARMv8_THREAD_POINTER_EL0-NOT: "-target-feature" "+tpidr-el1"
+// ARMv8_THREAD_POINTER_EL0-NOT: "-target-feature" "+tpidr-el2"
+// ARMv8_THREAD_POINTER_EL0-NOT: "-target-feature" "+tpidr-el3"
+
+// RUN: %clang -target aarch64-linux -### -S %s -arch armv8a -mtp=el1 2>&1 | \
+// RUN: FileCheck -check-prefix=ARMv8_THREAD_POINTER_EL1 %s
+// ARMv8_THREAD_POINTER_EL1: "-target-feature" "+tpidr-el1"
+// ARMv8_THREAD_POINTER_EL1-NOT: "-target-feature" "+tpidr-el2"
+// ARMv8_THREAD_POINTER_EL1-NOT: "-target-feature" "+tpidr-el3"
+
+// RUN: %clang -target aarch64-linux -### -S %s -arch armv8a -mtp=el2 2>&1 | \
+// RUN: FileCheck -check-prefix=ARMv8_THREAD_POINTER_EL2 %s
+// ARMv8_THREAD_POINTER_EL2-NOT: "-target-feature" "+tpidr-el1"
+// ARMv8_THREAD_POINTER_EL2: "-target-feature" "+tpidr-el2"
+// ARMv8_THREAD_POINTER_EL2-NOT: "-target-feature" "+tpidr-el3"
+
+// RUN: %clang -target aarch64-linux -### -S %s -arch armv8a -mtp=el3 2>&1 | \
+// RUN: FileCheck -check-prefix=ARMv8_THREAD_POINTER_EL3 %s
+// ARMv8_THREAD_POINTER_EL3-NOT: "-target-feature" "+tpidr-el1"
+// ARMv8_THREAD_POINTER_EL3-NOT: 

[PATCH] D59329: [LibTooling] Add NodeId, a strong type for AST-matcher node identifiers.

2019-03-29 Thread Ilya Biryukov via Phabricator via cfe-commits
ilya-biryukov added a subscriber: klimek.
ilya-biryukov added inline comments.



Comment at: clang/include/clang/Tooling/Refactoring/NodeId.h:29
+public:
+  explicit NodeId(std::string Id) : Id(std::move(Id)) {}
+

What are the use-cases for passing a custom id to this class?
If the purpose is to hide the IDs from the user, exposing this constructor 
seems to be against this goal.



Comment at: clang/lib/Tooling/Refactoring/NodeId.cpp:12
+
+namespace clang {
+namespace tooling {

NIT: change to `using namespace` for consistency



Comment at: clang/lib/Tooling/Refactoring/NodeId.cpp:24
+
+NodeId::NodeId() : NodeId(nextId()) {}
+

Suggestion from @klimek :

could we get the unique string by printing a pointer of `this` instead?
(And disallow copies and moves of this class for this to be correct)


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D59329



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


[PATCH] D58573: [analyzer] Move UninitializedObject out of alpha

2019-03-29 Thread Kristóf Umann via Phabricator via cfe-commits
Szelethus added a comment.

Ping^2


Repository:
  rC Clang

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

https://reviews.llvm.org/D58573



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


[PATCH] D59987: Add support for detection of devtoolset-8

2019-03-29 Thread Tom Stellard via Phabricator via cfe-commits
tstellar accepted this revision.
tstellar added a comment.
This revision is now accepted and ready to land.

LGTM.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D59987



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


[PATCH] D59376: [LibTooling] Add Transformer, a library for source-to-source transformations.

2019-03-29 Thread Ilya Biryukov via Phabricator via cfe-commits
ilya-biryukov marked 2 inline comments as done.
ilya-biryukov added a comment.

The only real question I have is about returning an error vs an empty 
transformation in of macros.
The rest are just NITs.

Thanks for the change! I'll get to the NodeId patch right away :-)




Comment at: clang/include/clang/Tooling/Refactoring/Transformer.h:170
+
+  RewriteRuleBuilder(const RewriteRuleBuilder &) = default;
+  RewriteRuleBuilder(RewriteRuleBuilder &&) = default;

ymandel wrote:
> ilya-biryukov wrote:
> > NIT: maybe remove the `=default` copy and move ctors and assignments?
> > They should be generated automatically anyway, right?
> Sure. I was going based on google's style recommendations, but personally i 
> prefer leaving them implicit.
+1. Means less boilterplate.



Comment at: clang/include/clang/Tooling/Refactoring/Transformer.h:70
+//
+// * Explanation: explanation of the rewrite.
+//

NIT: maybe mention what it should be used for? we plan to show to to the user 
(e.g. in the clang-tidy fix description), right?



Comment at: clang/include/clang/Tooling/Refactoring/Transformer.h:89
+// \code
+//   RewriteRule R = buildRule(functionDecl(...)).replaceWith(...);
+// \endcode

Could you also add examples on how to apply the rewrite rule here?
So that the users can have an idea about the full workflow when reading the 
code.



Comment at: clang/include/clang/Tooling/Refactoring/Transformer.h:97
+  ast_matchers::internal::DynTypedMatcher Matcher;
+  // The (bound) id of the node whose source will be replaced.  This id should
+  // never be the empty string.

NIT: maybe assert this invariant in the constructor?



Comment at: clang/include/clang/Tooling/Refactoring/Transformer.h:122
+  // The bound id of the node corresponding to the matcher.
+  static llvm::StringRef matchedNode() { return RootId; }
+

This method does not seem to be used anywhere.
Are we missing the usages in this patch? Maybe remove it from the initial 
implementation and re-add later when we have the callsites?



Comment at: clang/include/clang/Tooling/Refactoring/Transformer.h:175
+  RewriteRuleBuilder &(std::string Explanation) && {
+return std::move(std::move(*this).because(text(std::move(Explanation;
+  }

NIT: the top-level `std::move` looks redundant, maybe remove it?



Comment at: clang/lib/Tooling/Refactoring/Transformer.cpp:31
+
+using ::clang::ast_matchers::MatchFinder;
+using ::clang::ast_type_traits::ASTNodeKind;

NIT: we could leave out the trailing `::` for `clang` and `llvm`, they are 
well-known and unambiguous namespace names.



Comment at: clang/lib/Tooling/Refactoring/Transformer.cpp:42
+
+static bool isOriginMacroBody(const clang::SourceManager ,
+  clang::SourceLocation Loc) {

NIT: could you add a brief comment on what this function is expected to return?



Comment at: clang/lib/Tooling/Refactoring/Transformer.cpp:133
+
+namespace clang {
+namespace tooling {

NIT: remove namespaces for consistency with the rest of the code.

(Probably a leftover from the previous version)



Comment at: clang/lib/Tooling/Refactoring/Transformer.cpp:150
+  llvm::handleErrors(TargetOrErr.takeError(), [](StringError ) {
+return invalidArgumentError("Failure targeting node" +
+Rule.target() + ": " + E.getMessage());

NIT: consider simply propagating the original error up the stack in that case 
to avoid boilerplate.
Although adding the `.target()` information to the error might be useful, so up 
to you.



Comment at: clang/lib/Tooling/Refactoring/Transformer.cpp:157
+  isOriginMacroBody(*Match.SourceManager, Target.getBegin()))
+return Transformation();
+

Why not return an error in case of macros too? Is there any use of the empty 
transformation to the clients? 
Alternatively, we might want to document this behavior (applyRewriteRule can 
return empty transformations) and it's rationale.



Comment at: clang/lib/Tooling/Refactoring/Transformer.cpp:28
+
+namespace clang {
+namespace tooling {

ymandel wrote:
> ilya-biryukov wrote:
> > Other files in the tooling library seem to be adding `using namespace 
> > clang` instead of putting the declaration into a namespace.
> > Could you please change the new code to do the same for consistency?
> > 
> Done.  Agreed about being consistent. FWIW, I can't say I like this style.  
> Perhaps because I'm not used to it, but it feels too implicit.  It forces the 
> reader to figure out where each definition is being associated. Also, I 
> discovered it only works for method definitions. Free functions still need 

  1   2   >