[PATCH] D58880: [WIP] [Looking for API feedback] [clangd] Type hierarchy subtypes

2019-03-14 Thread Nathan Ridge via Phabricator via cfe-commits
nridge added a comment.

In D58880#1422494 , @kadircet wrote:

> Hi Nathan,
>
> I would also suggest splitting up current changes so that we can start 
> reviewing them, which might result in other changes in your planned changes 
> and help reduce duplicate work both on our and your side.
>  [...]
>
> As for splitting changes I would suggest something like:
>
> - RelationSlab
> - Serialization/Deserialization of the RelationSlab
> - Integrating RelationSlab with SymbolCollector
> - Adding queries to index structures(memindex, dex, mergedindex etc.)
> - Surfacing those queries through typehierarchy request


Thanks. The proposed split looks good to me. I've posted the first patch here: 
https://reviews.llvm.org/D59407


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D58880



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


[PATCH] D59407: [clangd] Add RelationSlab

2019-03-14 Thread Nathan Ridge via Phabricator via cfe-commits
nridge marked an inline comment as done.
nridge added inline comments.



Comment at: clang-tools-extra/clangd/index/Index.h:25
 
+enum class RelationKind { Subtype };
+

One thing I'm wondering about is: would it be better to just use 
`clang::index::SymbolRole` here (which has `Relation___Of` entries that cover 
what we're interested in) instead of having our own enum?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D59407



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


[PATCH] D59407: [clangd] Add RelationSlab

2019-03-14 Thread Nathan Ridge via Phabricator via cfe-commits
nridge created this revision.
nridge added a reviewer: kadircet.
Herald added subscribers: cfe-commits, arphaman, jkorous, MaskRay, ioeric, 
ilya-biryukov.
Herald added a project: clang.

RelationSlab is a new index data structure, similar to SymbolSlab and
RefSlab. RelationSlab stores relations between Symbols.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D59407

Files:
  clang-tools-extra/clangd/index/Index.cpp
  clang-tools-extra/clangd/index/Index.h

Index: clang-tools-extra/clangd/index/Index.h
===
--- clang-tools-extra/clangd/index/Index.h
+++ clang-tools-extra/clangd/index/Index.h
@@ -22,6 +22,71 @@
 namespace clang {
 namespace clangd {
 
+enum class RelationKind { Subtype };
+
+struct RelationKey {
+  SymbolID Symbol;
+  RelationKind Kind;
+
+  bool operator==(const RelationKey ) const {
+return Symbol == Other.Symbol && Kind == Other.Kind;
+  }
+
+private:
+  friend llvm::hash_code hash_value(const RelationKey ) {
+return llvm::hash_combine(Key.Symbol, static_cast(Key.Kind));
+  }
+};
+
+class RelationSlab {
+public:
+  using value_type = std::pair>;
+  using const_iterator = std::vector::const_iterator;
+  using iterator = const_iterator;
+
+  RelationSlab() = default;
+  RelationSlab(RelationSlab &) = default;
+  RelationSlab =(RelationSlab &) = default;
+
+  const_iterator begin() const { return Relations.begin(); }
+  const_iterator end() const { return Relations.end(); }
+  size_t size() const { return Relations.size(); }
+  size_t numRelations() const { return NumRelations; }
+  bool empty() const { return Relations.empty(); }
+
+  size_t bytes() const {
+return sizeof(*this) + Arena.getTotalMemory() +
+   sizeof(value_type) * Relations.size();
+  }
+
+  // RelationSlab::Builder is a mutable container that can 'freeze' to
+  // RelationSlab.
+  class Builder {
+  public:
+Builder() {}
+// Adds a relation to the slab. Deep copy: Strings will be owned by the
+// slab.
+void insert(const RelationKey , const SymbolID );
+// Consumes the builder to finalize the slab.
+RelationSlab build() &&;
+
+  private:
+llvm::BumpPtrAllocator Arena;
+llvm::DenseMap> Relations;
+  };
+
+private:
+  RelationSlab(std::vector Relations, llvm::BumpPtrAllocator Arena,
+   size_t NumRelations)
+  : Arena(std::move(Arena)), Relations(std::move(Relations)),
+NumRelations(NumRelations) {}
+
+  llvm::BumpPtrAllocator Arena;
+  std::vector Relations;
+  // Number of all relations.
+  size_t NumRelations = 0;
+};
+
 struct FuzzyFindRequest {
   /// \brief A query string for the fuzzy find. This is matched against symbols'
   /// un-qualified identifiers and should not contain qualifiers like "::".
@@ -136,4 +201,30 @@
 } // namespace clangd
 } // namespace clang
 
+namespace llvm {
+
+// Support RelationKeys as DenseMap keys.
+template <> struct DenseMapInfo {
+  static inline clang::clangd::RelationKey getEmptyKey() {
+return {DenseMapInfo::getEmptyKey(),
+clang::clangd::RelationKind::Subtype};
+  }
+
+  static inline clang::clangd::RelationKey getTombstoneKey() {
+return {DenseMapInfo::getTombstoneKey(),
+clang::clangd::RelationKind::Subtype};
+  }
+
+  static unsigned getHashValue(const clang::clangd::RelationKey ) {
+return hash_value(Key);
+  }
+
+  static bool isEqual(const clang::clangd::RelationKey ,
+  const clang::clangd::RelationKey ) {
+return LHS == RHS;
+  }
+};
+
+} // namespace llvm
+
 #endif // LLVM_CLANG_TOOLS_EXTRA_CLANGD_INDEX_INDEX_H
Index: clang-tools-extra/clangd/index/Index.cpp
===
--- clang-tools-extra/clangd/index/Index.cpp
+++ clang-tools-extra/clangd/index/Index.cpp
@@ -17,6 +17,28 @@
 namespace clang {
 namespace clangd {
 
+void RelationSlab::Builder::insert(const RelationKey , const SymbolID ) {
+  Relations[Key].push_back(S);
+}
+
+RelationSlab RelationSlab::Builder::build() && {
+  // Reallocate relations on the arena to reduce waste and indirections when
+  // reading.
+  std::vector>> Result;
+  Result.reserve(Relations.size());
+  size_t NumRelations = 0;
+  for (auto  : Relations) {
+auto  = Entry.second;
+
+NumRelations += Rels.size();
+auto *Array = Arena.Allocate(Rels.size());
+std::uninitialized_copy(Rels.begin(), Rels.end(), Array);
+Result.emplace_back(Entry.first,
+llvm::ArrayRef(Array, Rels.size()));
+  }
+  return RelationSlab(std::move(Result), std::move(Arena), NumRelations);
+}
+
 void SwapIndex::reset(std::unique_ptr Index) {
   // Keep the old index alive, so we don't destroy it under lock (may be slow).
   std::shared_ptr Pin;
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D59406: [analyzer] Teach scan-build to find /usr/bin/clang when installed in /usr/local/bin/

2019-03-14 Thread Devin Coughlin via Phabricator via cfe-commits
dcoughlin created this revision.
dcoughlin added a reviewer: NoQ.
Herald added subscribers: cfe-commits, Charusso, dkrupp, donat.nagy, Szelethus, 
mikhail.ramalho, a.sidorin, szepet, baloghadamsoftware, xazax.hun.
Herald added a project: clang.

Change scan-build to support the scenario where scan-build is installed in
/usr/local/bin/ but clang itself is installed in /usr/bin/.

rdar://problem/48914634


Repository:
  rC Clang

https://reviews.llvm.org/D59406

Files:
  tools/scan-build/bin/scan-build


Index: tools/scan-build/bin/scan-build
===
--- tools/scan-build/bin/scan-build
+++ tools/scan-build/bin/scan-build
@@ -1468,6 +1468,13 @@
 $Clang = Cwd::realpath("$RealBin/bin/clang") if (-f "$RealBin/bin/clang");
 if (!defined $Clang || ! -x $Clang) {
   $Clang = Cwd::realpath("$RealBin/clang") if (-f "$RealBin/clang");
+  if (!defined $Clang || ! -x $Clang) {
+# Look for a clang in the sibling bin of the parent of the bin 
directory. So
+# if scan-build is at /usr/local/bin/scan-build look for clang at 
/usr/bin/clang
+if (-f "$RealBin/../../bin/clang") {
+  $Clang = Cwd::realpath("$RealBin/../../bin/clang");
+}
+  }
 }
 if (!defined $Clang || ! -x $Clang) {
   return "error: Cannot find an executable 'clang' relative to" .


Index: tools/scan-build/bin/scan-build
===
--- tools/scan-build/bin/scan-build
+++ tools/scan-build/bin/scan-build
@@ -1468,6 +1468,13 @@
 $Clang = Cwd::realpath("$RealBin/bin/clang") if (-f "$RealBin/bin/clang");
 if (!defined $Clang || ! -x $Clang) {
   $Clang = Cwd::realpath("$RealBin/clang") if (-f "$RealBin/clang");
+  if (!defined $Clang || ! -x $Clang) {
+# Look for a clang in the sibling bin of the parent of the bin directory. So
+# if scan-build is at /usr/local/bin/scan-build look for clang at /usr/bin/clang
+if (-f "$RealBin/../../bin/clang") {
+  $Clang = Cwd::realpath("$RealBin/../../bin/clang");
+}
+  }
 }
 if (!defined $Clang || ! -x $Clang) {
   return "error: Cannot find an executable 'clang' relative to" .
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


r356231 - Remove an assert in template pack deduction during nested instantiation.

2019-03-14 Thread Richard Trieu via cfe-commits
Author: rtrieu
Date: Thu Mar 14 21:26:02 2019
New Revision: 356231

URL: http://llvm.org/viewvc/llvm-project?rev=356231=rev
Log:
Remove an assert in template pack deduction during nested instantiation.

Modified:
cfe/trunk/lib/Sema/SemaTemplateInstantiateDecl.cpp
cfe/trunk/test/SemaTemplate/pack-deduction.cpp

Modified: cfe/trunk/lib/Sema/SemaTemplateInstantiateDecl.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Sema/SemaTemplateInstantiateDecl.cpp?rev=356231=356230=356231=diff
==
--- cfe/trunk/lib/Sema/SemaTemplateInstantiateDecl.cpp (original)
+++ cfe/trunk/lib/Sema/SemaTemplateInstantiateDecl.cpp Thu Mar 14 21:26:02 2019
@@ -3804,25 +3804,25 @@ static bool addInstantiatedParametersToS
 Scope.MakeInstantiatedLocalArgPack(PatternParam);
 Optional NumArgumentsInExpansion
   = S.getNumArgumentsInExpansion(PatternParam->getType(), TemplateArgs);
-assert(NumArgumentsInExpansion &&
-   "should only be called when all template arguments are known");
-QualType PatternType =
-PatternParam->getType()->castAs()->getPattern();
-for (unsigned Arg = 0; Arg < *NumArgumentsInExpansion; ++Arg) {
-  ParmVarDecl *FunctionParam = Function->getParamDecl(FParamIdx);
-  FunctionParam->setDeclName(PatternParam->getDeclName());
-  if (!PatternDecl->getType()->isDependentType()) {
-Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(S, Arg);
-QualType T = S.SubstType(PatternType, TemplateArgs,
- FunctionParam->getLocation(),
- FunctionParam->getDeclName());
-if (T.isNull())
-  return true;
-FunctionParam->setType(T);
-  }
+if (NumArgumentsInExpansion) {
+  QualType PatternType =
+  PatternParam->getType()->castAs()->getPattern();
+  for (unsigned Arg = 0; Arg < *NumArgumentsInExpansion; ++Arg) {
+ParmVarDecl *FunctionParam = Function->getParamDecl(FParamIdx);
+FunctionParam->setDeclName(PatternParam->getDeclName());
+if (!PatternDecl->getType()->isDependentType()) {
+  Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(S, Arg);
+  QualType T = S.SubstType(PatternType, TemplateArgs,
+   FunctionParam->getLocation(),
+   FunctionParam->getDeclName());
+  if (T.isNull())
+return true;
+  FunctionParam->setType(T);
+}
 
-  Scope.InstantiatedLocalPackArg(PatternParam, FunctionParam);
-  ++FParamIdx;
+Scope.InstantiatedLocalPackArg(PatternParam, FunctionParam);
+++FParamIdx;
+  }
 }
   }
 

Modified: cfe/trunk/test/SemaTemplate/pack-deduction.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/SemaTemplate/pack-deduction.cpp?rev=356231=356230=356231=diff
==
--- cfe/trunk/test/SemaTemplate/pack-deduction.cpp (original)
+++ cfe/trunk/test/SemaTemplate/pack-deduction.cpp Thu Mar 14 21:26:02 2019
@@ -166,3 +166,22 @@ namespace substitution_vs_function_deduc
 A().g(f); // expected-error {{no match}}
   }
 }
+
+namespace Nested_Explicit_Specialization {
+template 
+struct Outer {
+
+  template 
+  struct Inner;
+
+  template <>
+  struct Inner<0> {
+template 
+void Test(Args...) {}
+  };
+};
+
+void Run() {
+  Outer::Inner<0>().Test(1,1);
+}
+}


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


[PATCH] D55044: [clang-tidy] check for Abseil make_unique

2019-03-14 Thread Andy Zhang via Phabricator via cfe-commits
axzhang updated this revision to Diff 190775.
axzhang added a comment.

Make fixes to the `UseLegacyFunction` option, renaming to `IgnoreListInit`.


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

https://reviews.llvm.org/D55044

Files:
  clang-tidy/abseil/AbseilTidyModule.cpp
  clang-tidy/modernize/MakeSmartPtrCheck.cpp
  clang-tidy/modernize/MakeSmartPtrCheck.h
  docs/ReleaseNotes.rst
  docs/clang-tidy/checks/abseil-make-unique.rst
  docs/clang-tidy/checks/list.rst
  docs/clang-tidy/checks/modernize-make-unique.rst
  test/clang-tidy/abseil-make-unique.cpp

Index: test/clang-tidy/abseil-make-unique.cpp
===
--- /dev/null
+++ test/clang-tidy/abseil-make-unique.cpp
@@ -0,0 +1,127 @@
+// RUN: %check_clang_tidy %s abseil-make-unique %t -- -- -std=c++11 \
+
+namespace std {
+
+template 
+class default_delete {};
+
+template >
+class unique_ptr {
+public:
+  unique_ptr() {}
+  unique_ptr(type *ptr) {}
+  unique_ptr(const unique_ptr ) = delete;
+  unique_ptr(unique_ptr &) {}
+  ~unique_ptr() {}
+  type *() { return *ptr; }
+  type *operator->() { return ptr; }
+  type *release() { return ptr; }
+  void reset() {}
+  void reset(type *pt) {}
+  void reset(type pt) {}
+  unique_ptr =(unique_ptr &&) { return *this; }
+  template 
+  unique_ptr =(unique_ptr &&) { return *this; }
+
+private:
+  type *ptr;
+};
+
+}  // namespace std
+
+class A {
+ int x;
+ int y;
+
+ public:
+   A(int _x, int _y): x(_x), y(_y) {}
+};
+
+struct Base {
+  Base();
+};
+
+struct Derived : public Base {
+  Derived();
+};
+
+int* returnPointer();
+void expectPointer(std::unique_ptr p);
+
+std::unique_ptr makeAndReturnPointer() {
+  return std::unique_ptr(new int(0));
+  // CHECK-MESSAGES: :[[@LINE-1]]:10: warning: use absl::make_unique instead [abseil-make-unique]
+  // CHECK-FIXES: return absl::make_unique(0);
+}
+
+void Positives() {
+  std::unique_ptr P1 = std::unique_ptr(new int(1));
+  // CHECK-MESSAGES: :[[@LINE-1]]:29: warning: use absl::make_unique instead [abseil-make-unique]
+  // CHECK-FIXES: std::unique_ptr P1 = absl::make_unique(1);
+
+  P1.reset(new int(2));
+  // CHECK-MESSAGES: :[[@LINE-1]]:6: warning: use absl::make_unique instead [abseil-make-unique]
+  // CHECK-FIXES: P1 = absl::make_unique(2);
+
+  // Non-primitive paramter
+  std::unique_ptr P2 = std::unique_ptr(new A(1, 2));
+  // CHECK-MESSAGES: :[[@LINE-1]]:27: warning: use absl::make_unique instead [abseil-make-unique]
+  // CHECK-FIXES: std::unique_ptr P2 = absl::make_unique(1, 2);
+
+  P2.reset(new A(3, 4));
+  // CHECK-MESSAGES: :[[@LINE-1]]:6: warning: use absl::make_unique instead [abseil-make-unique]
+  // CHECK-FIXES: P2 = absl::make_unique(3, 4);
+
+  // No arguments to new expression
+  std::unique_ptr P3 = std::unique_ptr(new int);
+  // CHECK-MESSAGES: :[[@LINE-1]]:29: warning: use absl::make_unique instead [abseil-make-unique]
+  // CHECK-FIXES: std::unique_ptr P3 = absl::make_unique();
+
+  P3.reset(new int);
+  // CHECK-MESSAGES: :[[@LINE-1]]:6: warning: use absl::make_unique instead [abseil-make-unique]
+  // CHECK-FIXES: P3 = absl::make_unique();
+
+  // Nested parentheses
+  std::unique_ptr P4 = std::unique_ptr((new int(3)));
+  // CHECK-MESSAGES: :[[@LINE-1]]:29: warning: use absl::make_unique instead [abseil-make-unique]
+  // CHECK-FIXES: std::unique_ptr P4 = absl::make_unique(3);
+
+  P4 = std::unique_ptr(((new int(4;
+  // CHECK-MESSAGES: :[[@LINE-1]]:8: warning: use absl::make_unique instead [abseil-make-unique]
+  // CHECK-FIXES: P4 = absl::make_unique(4);
+
+  P4.reset((new int(5)));
+  // CHECK-MESSAGES: :[[@LINE-1]]:6: warning: use absl::make_unique instead [abseil-make-unique]
+  // CHECK-FIXES: P4 = absl::make_unique(5);
+
+  // With auto
+  auto P5 = std::unique_ptr(new int());
+  // CHECK-MESSAGES: :[[@LINE-1]]:13: warning: use absl::make_unique instead [abseil-make-unique]
+  // CHECK-FIXES: auto P5 = absl::make_unique();
+
+  {
+// No std
+using namespace std;
+unique_ptr Q = unique_ptr(new int());
+// CHECK-MESSAGES: :[[@LINE-1]]:25: warning: use absl::make_unique instead [abseil-make-unique]
+// CHECK-FIXES: unique_ptr Q = absl::make_unique();
+
+Q = unique_ptr(new int());
+// CHECK-MESSAGES: :[[@LINE-1]]:9: warning: use absl::make_unique instead [abseil-make-unique]
+// CHECK-FIXES: Q = absl::make_unique();
+  }
+
+  // Create the unique_ptr as a parameter to a function
+  expectPointer(std::unique_ptr(new int()));
+  // CHECK-MESSAGES: :[[@LINE-1]]:17: warning: use absl::make_unique instead [abseil-make-unique]
+  // CHECK-FIXES: expectPointer(absl::make_unique());
+}
+
+void Negatives() {
+  // Only warn if explicitly allocating a new object
+  std::unique_ptr R = std::unique_ptr(returnPointer());
+  R.reset(returnPointer());
+
+  // Only replace if the template type is same as new type
+  auto Pderived = std::unique_ptr(new Derived());
+}
Index: docs/clang-tidy/checks/modernize-make-unique.rst

r356228 - Add missing override specifier [NFC]

2019-03-14 Thread Aaron Puchert via cfe-commits
Author: aaronpuchert
Date: Thu Mar 14 19:30:07 2019
New Revision: 356228

URL: http://llvm.org/viewvc/llvm-project?rev=356228=rev
Log:
Add missing override specifier [NFC]

This should fix a -Winconsistent-missing-override warning that is only
visible when Z3 is enabled.

Modified:
cfe/trunk/lib/StaticAnalyzer/Core/Z3ConstraintManager.cpp

Modified: cfe/trunk/lib/StaticAnalyzer/Core/Z3ConstraintManager.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/StaticAnalyzer/Core/Z3ConstraintManager.cpp?rev=356228=356227=356228=diff
==
--- cfe/trunk/lib/StaticAnalyzer/Core/Z3ConstraintManager.cpp (original)
+++ cfe/trunk/lib/StaticAnalyzer/Core/Z3ConstraintManager.cpp Thu Mar 14 
19:30:07 2019
@@ -102,7 +102,7 @@ public:
   Z3_dec_ref(Context.Context, reinterpret_cast(Sort));
   }
 
-  void Profile(llvm::FoldingSetNodeID ) const {
+  void Profile(llvm::FoldingSetNodeID ) const override {
 ID.AddInteger(
 Z3_get_ast_id(Context.Context, reinterpret_cast(Sort)));
   }


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


[PATCH] D59402: Fix-it hints for -Wmissing-{prototypes,variable-declarations}

2019-03-14 Thread Aaron Puchert via Phabricator via cfe-commits
aaronpuchert added inline comments.



Comment at: test/Sema/warn-missing-prototypes.c:7
 int f(int x) { return x; } // expected-warning{{no previous prototype for 
function 'f'}}
+// CHECK: fix-it:"{{.*}}":{[[@LINE-1]]:1-[[@LINE-1]]:1}:"static "
 

Maybe there shouldn't be a fix-it here, as there is a declaration, which is 
just not a prototype.



Comment at: test/Sema/warn-missing-prototypes.c:17-18
 
+extern int g3(int x) { return x; } // expected-warning{{no previous prototype 
for function 'g3'}}
+// CHECK-NOT: fix-it:"{{.*}}":{[[@LINE-1]]{{.*}}}:"{{.*}}"
+

As I wrote in the commit message: this could be fixed by replacing `extern` 
with `static`, but I don't think we have the `SourceLocation` for the storage 
class specifier available where the warning is emitted. Maybe I'm overlooking 
something though.


Repository:
  rC Clang

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

https://reviews.llvm.org/D59402



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


[PATCH] D59402: Fix-it hints for -Wmissing-{prototypes,variable-declarations}

2019-03-14 Thread Aaron Puchert via Phabricator via cfe-commits
aaronpuchert created this revision.
aaronpuchert added reviewers: bkramer, efriedma, rsmith.
Herald added subscribers: cfe-commits, jdoerfert.
Herald added a project: clang.

I've found that most often the proper way to fix this warning is to add
`static`, because if the code otherwise compiles and links, the function
or variable is apparently not needed outside of the TU.

There is no fix-it for the rare case of an "extern definition", because
that would require removing `extern` and I have no idea how to get the
source location of the storage class specifier from a VarDecl. I believe
this information is only available earlier in the AST construction from
DeclSpec::getStorageClassSpecLoc(), but we don't have that here.


Repository:
  rC Clang

https://reviews.llvm.org/D59402

Files:
  lib/Sema/SemaDecl.cpp
  test/Sema/warn-missing-prototypes.c
  test/Sema/warn-missing-variable-declarations.c
  test/SemaCXX/warn-missing-variable-declarations.cpp

Index: test/SemaCXX/warn-missing-variable-declarations.cpp
===
--- test/SemaCXX/warn-missing-variable-declarations.cpp
+++ test/SemaCXX/warn-missing-variable-declarations.cpp
@@ -1,11 +1,15 @@
-// RUN: %clang -Wmissing-variable-declarations -fsyntax-only -Xclang -verify -std=c++17 %s
+// RUN: %clang_cc1 -fsyntax-only -verify -Wmissing-variable-declarations -std=c++17 %s
+// RUN: %clang_cc1 -fsyntax-only -Wmissing-variable-declarations -fdiagnostics-parseable-fixits -std=c++17 %s 2>&1 | FileCheck %s
 
 // Variable declarations that should trigger a warning.
 int vbad1; // expected-warning{{no previous extern declaration for non-static variable 'vbad1'}}
+// CHECK: fix-it:"{{.*}}":{[[@LINE-1]]:1-[[@LINE-1]]:1}:"static "
 int vbad2 = 10; // expected-warning{{no previous extern declaration for non-static variable 'vbad2'}}
+// CHECK: fix-it:"{{.*}}":{[[@LINE-1]]:1-[[@LINE-1]]:1}:"static "
 
 namespace x {
   int vbad3; // expected-warning{{no previous extern declaration for non-static variable 'vbad3'}}
+  // CHECK: fix-it:"{{.*}}":{[[@LINE-1]]:3-[[@LINE-1]]:3}:"static "
 }
 
 // Variable declarations that should not trigger a warning.
@@ -58,7 +62,9 @@
 constexpr int constexpr_var = 0;
 inline constexpr int inline_constexpr_var = 0;
 extern const int extern_const_var = 0; // expected-warning {{no previous extern declaration}}
+// CHECK-NOT: fix-it:"{{.*}}":{[[@LINE-1]]{{.*}}}:"{{.*}}"
 extern constexpr int extern_constexpr_var = 0; // expected-warning {{no previous extern declaration}}
+// CHECK-NOT: fix-it:"{{.*}}":{[[@LINE-1]]{{.*}}}:"{{.*}}"
 
 template int var_template = 0;
 template constexpr int const_var_template = 0;
Index: test/Sema/warn-missing-variable-declarations.c
===
--- test/Sema/warn-missing-variable-declarations.c
+++ test/Sema/warn-missing-variable-declarations.c
@@ -1,6 +1,8 @@
 // RUN: %clang_cc1 -Wmissing-variable-declarations -fsyntax-only -verify %s
+// RUN: %clang_cc1 -fsyntax-only -Wmissing-variable-declarations -fdiagnostics-parseable-fixits %s 2>&1 | FileCheck %s
 
 int vbad1; // expected-warning{{no previous extern declaration for non-static variable 'vbad1'}}
+// CHECK: fix-it:"{{.*}}":{[[@LINE-1]]:1-[[@LINE-1]]:1}:"static "
 
 int vbad2;
 int vbad2 = 10; // expected-warning{{no previous extern declaration for non-static variable 'vbad2'}}
@@ -8,6 +10,7 @@
 struct {
   int mgood1;
 } vbad3; // expected-warning{{no previous extern declaration for non-static variable 'vbad3'}}
+// CHECK: fix-it:"{{.*}}":{[[@LINE-3]]:1-[[@LINE-3]]:1}:"static "
 
 int vbad4;
 int vbad4 = 10; // expected-warning{{no previous extern declaration for non-static variable 'vbad4'}}
Index: test/Sema/warn-missing-prototypes.c
===
--- test/Sema/warn-missing-prototypes.c
+++ test/Sema/warn-missing-prototypes.c
@@ -4,6 +4,7 @@
 int f();
 
 int f(int x) { return x; } // expected-warning{{no previous prototype for function 'f'}}
+// CHECK: fix-it:"{{.*}}":{[[@LINE-1]]:1-[[@LINE-1]]:1}:"static "
 
 static int g(int x) { return x; }
 
@@ -13,6 +14,9 @@
 
 int g2(int x) { return x; }
 
+extern int g3(int x) { return x; } // expected-warning{{no previous prototype for function 'g3'}}
+// CHECK-NOT: fix-it:"{{.*}}":{[[@LINE-1]]{{.*}}}:"{{.*}}"
+
 void test(void);
 
 int h3();
@@ -40,4 +44,4 @@
 void not_a_prototype_test(); // expected-note{{this declaration is not a prototype; add 'void' to make it a prototype for a zero-parameter function}}
 void not_a_prototype_test() { } // expected-warning{{no previous prototype for function 'not_a_prototype_test'}}
 
-// CHECK: fix-it:"{{.*}}":{40:27-40:27}:"void"
+// CHECK: fix-it:"{{.*}}":{[[@LINE-3]]:27-[[@LINE-3]]:27}:"void"
Index: lib/Sema/SemaDecl.cpp
===
--- lib/Sema/SemaDecl.cpp
+++ lib/Sema/SemaDecl.cpp
@@ -11805,7 +11805,11 @@
   prev = prev->getPreviousDecl();
 
 if 

[PATCH] D59319: [OpenMP][Offloading][1/3] A generic and simple target region interface

2019-03-14 Thread Johannes Doerfert via Phabricator via cfe-commits
jdoerfert updated this revision to Diff 190767.
jdoerfert marked 4 inline comments as done.
jdoerfert added a comment.

Add ident_t* to the interface functions


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D59319

Files:
  openmp/libomptarget/deviceRTLs/common/target_region.h
  openmp/libomptarget/deviceRTLs/nvptx/CMakeLists.txt
  openmp/libomptarget/deviceRTLs/nvptx/src/omp_data.cu
  openmp/libomptarget/deviceRTLs/nvptx/src/omptarget-nvptx.h
  openmp/libomptarget/deviceRTLs/nvptx/src/target_region.cu

Index: openmp/libomptarget/deviceRTLs/nvptx/src/target_region.cu
===
--- /dev/null
+++ openmp/libomptarget/deviceRTLs/nvptx/src/target_region.cu
@@ -0,0 +1,198 @@
+//===-- target_region.cu  CUDA impl. of the target region interface -*-===//
+//
+// 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
+//
+//===--===//
+//
+// This file contains the implementation of the common target region interface.
+//
+//===--===//
+
+// Include the native definitions first as certain defines might be needed in
+// the common interface definition below.
+#include "omptarget-nvptx.h"
+#include "interface.h"
+
+#include "../../common/target_region.h"
+
+/// The pointer used to share memory between team threads.
+extern __device__ __shared__ target_region_shared_buffer
+_target_region_shared_memory;
+
+EXTERN void *__kmpc_target_region_kernel_get_shared_memory() {
+  return _target_region_shared_memory.begin();
+}
+EXTERN void *__kmpc_target_region_kernel_get_private_memory() {
+  return _target_region_shared_memory.begin() +
+ _target_region_shared_memory.get_offset();
+}
+
+/// Simple generic state machine for worker threads.
+INLINE static void
+__kmpc_target_region_state_machine(ident_t *Ident, bool IsOMPRuntimeInitialized) {
+
+  do {
+void *WorkFn = 0;
+
+// Wait for the signal that we have a new work function.
+__kmpc_barrier_simple_spmd(Ident, 0);
+
+// Retrieve the work function from the runtime.
+bool IsActive = __kmpc_kernel_parallel(, IsOMPRuntimeInitialized);
+
+// If there is nothing more to do, break out of the state machine by
+// returning to the caller.
+if (!WorkFn)
+  return;
+
+if (IsActive) {
+  void *SharedVars = __kmpc_target_region_kernel_get_shared_memory();
+  void *PrivateVars = __kmpc_target_region_kernel_get_private_memory();
+
+  ((ParallelWorkFnTy)WorkFn)(SharedVars, PrivateVars);
+
+  __kmpc_kernel_end_parallel();
+}
+
+__kmpc_barrier_simple_spmd(Ident, 0);
+
+  } while (true);
+}
+
+/// Filter threads into masters and workers. If \p UseStateMachine is true,
+/// required workers will enter a state machine through and be trapped there.
+/// Master and surplus worker threads will return from this function immediately
+/// while required workers will only return once there is no more work. The
+/// return value indicates if the thread is a master (1), a surplus worker (0),
+/// or a finished required worker released from the state machine (-1).
+INLINE static int8_t
+__kmpc_target_region_thread_filter(ident_t *Ident, unsigned ThreadLimit,
+   bool UseStateMachine,
+   bool IsOMPRuntimeInitialized) {
+
+  unsigned TId = GetThreadIdInBlock();
+  bool IsWorker = TId < ThreadLimit;
+
+  if (IsWorker) {
+if (UseStateMachine)
+  __kmpc_target_region_state_machine(Ident, IsOMPRuntimeInitialized);
+return -1;
+  }
+
+  return TId == GetMasterThreadID();
+}
+
+EXTERN int8_t __kmpc_target_region_kernel_init(ident_t *Ident, bool UseSPMDMode,
+   bool UseStateMachine,
+   bool RequiresOMPRuntime,
+   bool RequiresDataSharing) {
+  unsigned NumThreads = GetNumberOfThreadsInBlock();
+
+  // Handle the SPMD case first.
+  if (UseSPMDMode) {
+
+__kmpc_spmd_kernel_init(NumThreads, RequiresOMPRuntime,
+RequiresDataSharing);
+
+if (RequiresDataSharing)
+  __kmpc_data_sharing_init_stack_spmd();
+
+return 1;
+  }
+
+  // Reserve one WARP in non-SPMD mode for the masters.
+  unsigned ThreadLimit = NumThreads - WARPSIZE;
+  int8_t FilterVal = __kmpc_target_region_thread_filter(
+  Ident, ThreadLimit, UseStateMachine, RequiresOMPRuntime);
+
+  // If the filter returns 1 the executing thread is a team master which will
+  // initialize the kernel in the following.
+  if (FilterVal == 1) {
+__kmpc_kernel_init(ThreadLimit, RequiresOMPRuntime);
+

[PATCH] D59319: [OpenMP][Offloading][1/3] A generic and simple target region interface

2019-03-14 Thread Johannes Doerfert via Phabricator via cfe-commits
jdoerfert added inline comments.



Comment at: openmp/libomptarget/deviceRTLs/common/target_region.h:100
+///
+EXTERN int8_t __kmpc_target_region_kernel_init(bool UseSPMDMode,
+   bool RequiresOMPRuntime,

jdoerfert wrote:
> ABataev wrote:
> > jdoerfert wrote:
> > > ABataev wrote:
> > > > jdoerfert wrote:
> > > > > ABataev wrote:
> > > > > > jdoerfert wrote:
> > > > > > > ABataev wrote:
> > > > > > > > Better to use `ident_loc` for passing info about execution mode 
> > > > > > > > and full/lightweight runtime.
> > > > > > > Could you please explain why you think that? Adding indirection 
> > > > > > > through a structure does not really seem beneficial to me.
> > > > > > Almost all function from libomp rely on `ident_loc`. The functions, 
> > > > > > which were added for NVPTX without this parameter had a lot of 
> > > > > > problems later and most of them were replaced with the functions 
> > > > > > with this parameter type. Plus, this parameter is used for 
> > > > > > OMPD/OMPT and it may be important for future OMPD/OMPT support.
> > > > > > Almost all function from libomp rely on ident_loc.
> > > > > 
> > > > > If you look at the implementation of this interface for NVPTX you 
> > > > > will see that the called functions do not take `ident_loc` values. 
> > > > > When you create the calls from the existing NVPTX code generation in 
> > > > > clang, the current code **does not use** `ident_loc` for similar 
> > > > > functions, see:
> > > > > `___kmpc_kernel_init(kmp_int32 thread_limit, int16_t 
> > > > > RequiresOMPRuntime)`,
> > > > > `__kmpc_kernel_deinit(int16_t IsOMPRuntimeInitialized)`,
> > > > > `__kmpc_spmd_kernel_init(kmp_int32 thread_limit, int16_t 
> > > > > RequiresOMPRuntime, int16_t RequiresDataSharing)`,
> > > > > `__kmpc_kernel_parallel(void **outlined_function, int16_t 
> > > > > IsOMPRuntimeInitialized)`,
> > > > > ...
> > > > > 
> > > > > 
> > > > > 
> > > > > > Plus, this parameter is used for OMPD/OMPT and it may be important 
> > > > > > for future OMPD/OMPT support.
> > > > > 
> > > > > If we at some point need to make the options permanent in an 
> > > > > `ident_loc` we can simply pass an `ident_loc` and require it to be 
> > > > > initialized by the call. Cluttering the user code with stores and 
> > > > > indirection is exactly what I do want to avoid.
> > > > 1. The new functions rely on `ident_loc`. We had to add those new 
> > > > functions because the old ones did not use it and it was bad design 
> > > > decision. Now we need to fix this. I suggest you do everything right 
> > > > from the very beginning rather than fixing this later by adding extra 
> > > > entry points to support OMPT/OMPD or something else, for example.
> > > > 2. No, you cannot simply change the interface of the library to keep 
> > > > the compatibility with the previous versions of the compiler/library. 
> > > > You will need to add the new entries.  
> > > Let's start this one again because I still haven't understood. Why do we 
> > > need to populate the `ident_loc` again? What information has to be in 
> > > there at which point? I want this to be clear because a lot of other 
> > > "design decisions" of the existing code base are in my opinion not 
> > > necessary and consequently missing here. That includes, for example, 
> > > various global variables. If we have a description of the problem you try 
> > > to solve with the `ident_loc` we might be able to find a way that cuts 
> > > down on state.
> > > 
> > > 
> > > Regarding the "compatibility", this is not a stable interface people can 
> > > rely on. Whatever is committed in this first patch __is not__ set in 
> > > stone. Also, we can _always_ add a `__kmpc_init_ident_loc()` function 
> > > after the fact.
> > Ident_loc holds the data about current source code location, execution mode 
> > and is full runtime required or not. Also, it is used in OMPT/OMPD support.
> > Regarding "compatibility" libraries must be most stable part of the 
> > compiler, because the user migbt need to link the old object file/library 
> > with the new one. Because of this the new versions of libraries must be 
> > compatible with old ones. And you need to maintain the deprecated parts to 
> > keep the compatibility with the previous versions. All these libs already 
> > have a lot of old code that because of the initial poor design and we need 
> > to maintain them. I would like to avoid this situation with this patch.
> > Ident_loc holds the data about current source code location, execution mode 
> > and is full runtime required or not. Also, it is used in OMPT/OMPD support.
> 
> We can store that information through a `__kmpc_init_ident_loc()` call 
> once needed.
> 
> 
> > Regarding "compatibility" libraries must be most stable part of the 
> > compiler, because the user migbt need to link the old object file/library 
> > with the new one. Because of this the new 

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

2019-03-14 Thread Artem Dergachev via Phabricator via cfe-commits
NoQ marked an inline comment as done.
NoQ added a comment.

In D58367#1425922 , @Szelethus wrote:

> Would `NoteTag`s be displayed in a dumped exploded graph?


That's a great question. Tags themselves are always printed out, together with 
their description, and description for note tags is defined by this patch as 
follows:

  StringRef getTagDescription() const override {
if (MemoizedMessage)
  return *MemoizedMessage;
else
  return "Untriggered Note Tag";
  }

This "tag description" thing is only visible in exploded graph dumps; it 
doesn't have any other meaning. It is clear that it's very appealing to not 
only mention that the tag is attached, but also to print out the message it 
would produce. However, it is impossible to obtain the message until the 
specific bug report is provided. Not only the report must already be emitted, 
but also it needs to be chosen to represent its class of equivalent bug reports.

For now it means that if you simply do the usual 
`-analyzer-viz-egraph-graphviz` thing or the `debug.ViewExplodedGraph` thing, 
the graph will be visualized *before* the note tag lambdas are invoked, and it 
won't be able to show you the text:

F8456827: Screen Shot 2019-03-14 at 5.35.34 PM.png 


However, if you take your debugger, break at the end of 
`BugReporter::FlushReport()` and execute `p ((GRBugReporter 
*)this)->Eng.ViewGraph(0)` (or `1` if you want it trimmed), it'll show you the 
exact message:

F8456835: Screen Shot 2019-03-14 at 5.33.55 PM.png 


I think it'd be great to delay `-analyzer-viz-egraph-graphviz` so that all note 
tags were resolved by the time the graph is printed.

Now, why was this a great question? This question was great because it helped 
me realize that the memoization is a broken idea because the same lambda may 
produce multiple different messages if it participates in multiple bug reports. 
Which means we need a more sophisticated memoization, i.e. `map>` or something like that (assuming that bug reports can 
actually be identified by pointers).

> In D58367#1402847 , @NoQ wrote:
> 
>> In D58367#1402796 , @Szelethus 
>> wrote:
>>
>> > 2. I guess most of the visitors could be changed to this format, do you 
>> > have plans to convert them? I'll happily land a hand, because it sounds 
>> > like a big chore. I guess that would also test this implementation fairly 
>> > well.
>>
>>
>> I don't have an immediate plan but i'll definitely convert visitors when i 
>> touch them and get annoyed. Also i believe that this new functionality is 
>> much more useful for //core// visitors than for checker visitors, simply 
>> because there's much more information to reverse-engineer in every visitor.
> 
> 
> As I understand it, this solution could be used to entirely get rid of the 
> current bugreporter visitor structure (at least for checkers), right? The 
> discussion seems to conclude that this is just as general, far easier to 
> understand, far easier to implement, and is basically better in every regard 
> without an (//edit: significant//) hit to performance? Because if so, I'm 
> definitely against supporting two concurrent implementations of the same 
> functionality -- in fact, we should even just forbid checkers to add custom 
> visitors.

I suspect so. Supporting two different implementations doesn't sounds scary 
because both of them are fairly easy (at least ever since George has eradicated 
the fix-point-iteration for mutually recursive visitors), but once note tags 
start landing and settling down, i'll definitely try to avoid accepting new 
visitors :)




Comment at: clang/lib/StaticAnalyzer/Checkers/MIGChecker.cpp:165
 
-  C.addTransition(C.getState()->set(PVD));
+  const NoteTag *T = C.getNoteTag([this, PVD](BugReport ) -> std::string {
+if (() != )

xazax.hun wrote:
> I am not very familiar with this check but wonder don't you miss an 
> "isInteresting" check somewhere? Where do we filter the notes that are 
> unrelated to the bug paths?
Yeah, this check is special; it only tracks a single boolean flag in the 
program state and doesn't have a notion of interesting symbols or regions. 
Which is kinda why i started with this checker - it's easier than other 
checkers with the new approach (and harder than other checkers with the old 
approach).


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] D59123: [analyzer] RetainCount: Fix a crash when a function follows retain/autorelease naming convention but takes no arguments.

2019-03-14 Thread Phabricator via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rC356223: [analyzer] RetainCount: A function isnt a 
CFRetain if it takes no arguments. (authored by dergachev, committed by ).

Changed prior to commit:
  https://reviews.llvm.org/D59123?vs=189807=190762#toc

Repository:
  rC Clang

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

https://reviews.llvm.org/D59123

Files:
  lib/Analysis/RetainSummaryManager.cpp
  test/Analysis/retain-release.mm


Index: test/Analysis/retain-release.mm
===
--- test/Analysis/retain-release.mm
+++ test/Analysis/retain-release.mm
@@ -503,3 +503,15 @@
 }
 
 }
+
+namespace yet_another_unexpected_signature_crash {
+
+CFTypeRef CFSomethingSomethingRetain();
+CFTypeRef CFSomethingSomethingAutorelease();
+
+void foo() {
+  CFSomethingSomethingRetain(); // no-crash
+  CFSomethingSomethingAutorelease(); // no-crash
+}
+
+}
Index: lib/Analysis/RetainSummaryManager.cpp
===
--- lib/Analysis/RetainSummaryManager.cpp
+++ lib/Analysis/RetainSummaryManager.cpp
@@ -722,12 +722,13 @@
   // These are not retain. They just return something and retain it.
   return None;
 }
-if (cocoa::isRefType(ResultTy, "CF", FName) ||
-cocoa::isRefType(ResultTy, "CG", FName) ||
-cocoa::isRefType(ResultTy, "CV", FName))
-  if (isRetain(FD, FName) || isAutorelease(FD, FName) ||
-  isMakeCollectable(FName))
-return BehaviorSummary::Identity;
+if (CE->getNumArgs() == 1 &&
+(cocoa::isRefType(ResultTy, "CF", FName) ||
+ cocoa::isRefType(ResultTy, "CG", FName) ||
+ cocoa::isRefType(ResultTy, "CV", FName)) &&
+(isRetain(FD, FName) || isAutorelease(FD, FName) ||
+ isMakeCollectable(FName)))
+  return BehaviorSummary::Identity;
 
 // safeMetaCast is called by OSDynamicCast.
 // We assume that OSDynamicCast is either an identity (cast is OK,


Index: test/Analysis/retain-release.mm
===
--- test/Analysis/retain-release.mm
+++ test/Analysis/retain-release.mm
@@ -503,3 +503,15 @@
 }
 
 }
+
+namespace yet_another_unexpected_signature_crash {
+
+CFTypeRef CFSomethingSomethingRetain();
+CFTypeRef CFSomethingSomethingAutorelease();
+
+void foo() {
+  CFSomethingSomethingRetain(); // no-crash
+  CFSomethingSomethingAutorelease(); // no-crash
+}
+
+}
Index: lib/Analysis/RetainSummaryManager.cpp
===
--- lib/Analysis/RetainSummaryManager.cpp
+++ lib/Analysis/RetainSummaryManager.cpp
@@ -722,12 +722,13 @@
   // These are not retain. They just return something and retain it.
   return None;
 }
-if (cocoa::isRefType(ResultTy, "CF", FName) ||
-cocoa::isRefType(ResultTy, "CG", FName) ||
-cocoa::isRefType(ResultTy, "CV", FName))
-  if (isRetain(FD, FName) || isAutorelease(FD, FName) ||
-  isMakeCollectable(FName))
-return BehaviorSummary::Identity;
+if (CE->getNumArgs() == 1 &&
+(cocoa::isRefType(ResultTy, "CF", FName) ||
+ cocoa::isRefType(ResultTy, "CG", FName) ||
+ cocoa::isRefType(ResultTy, "CV", FName)) &&
+(isRetain(FD, FName) || isAutorelease(FD, FName) ||
+ isMakeCollectable(FName)))
+  return BehaviorSummary::Identity;
 
 // safeMetaCast is called by OSDynamicCast.
 // We assume that OSDynamicCast is either an identity (cast is OK,
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


r356223 - [analyzer] RetainCount: A function isn't a CFRetain if it takes no arguments.

2019-03-14 Thread Artem Dergachev via cfe-commits
Author: dergachev
Date: Thu Mar 14 17:26:17 2019
New Revision: 356223

URL: http://llvm.org/viewvc/llvm-project?rev=356223=rev
Log:
[analyzer] RetainCount: A function isn't a CFRetain if it takes no arguments.

Don't crash when a function has a name that starts with "CF" and ends with
"Retain" but takes 0 arguments. In particular, don't try to treat it as if
it returns its first argument.

These problems are inevitable because the checker is naming-convention-based,
but at least we shouldn't crash.

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

Modified:
cfe/trunk/lib/Analysis/RetainSummaryManager.cpp
cfe/trunk/test/Analysis/retain-release.mm

Modified: cfe/trunk/lib/Analysis/RetainSummaryManager.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Analysis/RetainSummaryManager.cpp?rev=356223=356222=356223=diff
==
--- cfe/trunk/lib/Analysis/RetainSummaryManager.cpp (original)
+++ cfe/trunk/lib/Analysis/RetainSummaryManager.cpp Thu Mar 14 17:26:17 2019
@@ -722,12 +722,13 @@ RetainSummaryManager::canEval(const Call
   // These are not retain. They just return something and retain it.
   return None;
 }
-if (cocoa::isRefType(ResultTy, "CF", FName) ||
-cocoa::isRefType(ResultTy, "CG", FName) ||
-cocoa::isRefType(ResultTy, "CV", FName))
-  if (isRetain(FD, FName) || isAutorelease(FD, FName) ||
-  isMakeCollectable(FName))
-return BehaviorSummary::Identity;
+if (CE->getNumArgs() == 1 &&
+(cocoa::isRefType(ResultTy, "CF", FName) ||
+ cocoa::isRefType(ResultTy, "CG", FName) ||
+ cocoa::isRefType(ResultTy, "CV", FName)) &&
+(isRetain(FD, FName) || isAutorelease(FD, FName) ||
+ isMakeCollectable(FName)))
+  return BehaviorSummary::Identity;
 
 // safeMetaCast is called by OSDynamicCast.
 // We assume that OSDynamicCast is either an identity (cast is OK,

Modified: cfe/trunk/test/Analysis/retain-release.mm
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/Analysis/retain-release.mm?rev=356223=356222=356223=diff
==
--- cfe/trunk/test/Analysis/retain-release.mm (original)
+++ cfe/trunk/test/Analysis/retain-release.mm Thu Mar 14 17:26:17 2019
@@ -503,3 +503,15 @@ void test_cxx_method_escaping(S *s) {
 }
 
 }
+
+namespace yet_another_unexpected_signature_crash {
+
+CFTypeRef CFSomethingSomethingRetain();
+CFTypeRef CFSomethingSomethingAutorelease();
+
+void foo() {
+  CFSomethingSomethingRetain(); // no-crash
+  CFSomethingSomethingAutorelease(); // no-crash
+}
+
+}


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


[PATCH] D59054: [analyzer] C++17: PR40022: Support aggregate initialization with compound values in presence of base classes.

2019-03-14 Thread Phabricator via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rL356222: [analyzer] Support C++17 aggregates with bases 
without constructors. (authored by dergachev, committed by ).
Herald added a project: LLVM.
Herald added a subscriber: llvm-commits.

Changed prior to commit:
  https://reviews.llvm.org/D59054?vs=189791=190760#toc

Repository:
  rL LLVM

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

https://reviews.llvm.org/D59054

Files:
  cfe/trunk/lib/StaticAnalyzer/Core/RegionStore.cpp
  cfe/trunk/test/Analysis/array-struct-region.cpp

Index: cfe/trunk/test/Analysis/array-struct-region.cpp
===
--- cfe/trunk/test/Analysis/array-struct-region.cpp
+++ cfe/trunk/test/Analysis/array-struct-region.cpp
@@ -1,7 +1,21 @@
-// RUN: %clang_analyze_cc1 -analyzer-checker=core,alpha.core,debug.ExprInspection -verify -x c %s
-// RUN: %clang_analyze_cc1 -analyzer-checker=core,alpha.core,debug.ExprInspection -verify -x c++ -analyzer-config c++-inlining=constructors %s
-// RUN: %clang_analyze_cc1 -analyzer-checker=core,alpha.core,debug.ExprInspection -DINLINE -verify -x c %s
-// RUN: %clang_analyze_cc1 -analyzer-checker=core,alpha.core,debug.ExprInspection -DINLINE -verify -x c++ -analyzer-config c++-inlining=constructors %s
+// RUN: %clang_analyze_cc1 -analyzer-checker=core,alpha.core\
+// RUN:-analyzer-checker=debug.ExprInspection -verify\
+// RUN:-x c %s
+// RUN: %clang_analyze_cc1 -analyzer-checker=core,alpha.core\
+// RUN:-analyzer-checker=debug.ExprInspection -verify\
+// RUN:-x c++ -std=c++14 %s
+// RUN: %clang_analyze_cc1 -analyzer-checker=core,alpha.core\
+// RUN:-analyzer-checker=debug.ExprInspection -verify\
+// RUN:-x c++ -std=c++17 %s
+// RUN: %clang_analyze_cc1 -analyzer-checker=core,alpha.core\
+// RUN:-analyzer-checker=debug.ExprInspection -verify\
+// RUN:-DINLINE -x c %s
+// RUN: %clang_analyze_cc1 -analyzer-checker=core,alpha.core\
+// RUN:-analyzer-checker=debug.ExprInspection -verify\
+// RUN:-DINLINE -x c++ -std=c++14 %s
+// RUN: %clang_analyze_cc1 -analyzer-checker=core,alpha.core\
+// RUN:-analyzer-checker=debug.ExprInspection -verify\
+// RUN:-DINLINE -x c++ -std=c++17 %s
 
 void clang_analyzer_eval(int);
 
@@ -196,4 +210,49 @@
   }
 }
 
+#if __cplusplus >= 201703L
+namespace aggregate_inheritance_cxx17 {
+struct A {
+  int x;
+};
+
+struct B {
+  int y;
+};
+
+struct C: B {
+  int z;
+};
+
+struct D: A, C {
+  int w;
+};
+
+void foo() {
+  D d{1, 2, 3, 4};
+  clang_analyzer_eval(d.x == 1); // expected-warning{{TRUE}}
+  clang_analyzer_eval(d.y == 2); // expected-warning{{TRUE}}
+  clang_analyzer_eval(d.z == 3); // expected-warning{{TRUE}}
+  clang_analyzer_eval(d.w == 4); // expected-warning{{TRUE}}
+}
+} // namespace aggregate_inheritance_cxx17
+#endif
+
+namespace flex_array_inheritance_cxx17 {
+struct A {
+  int flexible_array[];
+};
+
+struct B {
+  long cookie;
+};
+
+struct C : B {
+  A a;
+};
+
+void foo() {
+  C c{}; // no-crash
+}
+} // namespace flex_array_inheritance_cxx17
 #endif
Index: cfe/trunk/lib/StaticAnalyzer/Core/RegionStore.cpp
===
--- cfe/trunk/lib/StaticAnalyzer/Core/RegionStore.cpp
+++ cfe/trunk/lib/StaticAnalyzer/Core/RegionStore.cpp
@@ -2334,12 +2334,57 @@
   if (V.isUnknown() || !V.getAs())
 return bindAggregate(B, R, UnknownVal());
 
+  // The raw CompoundVal is essentially a symbolic InitListExpr: an (immutable)
+  // list of other values. It appears pretty much only when there's an actual
+  // initializer list expression in the program, and the analyzer tries to
+  // unwrap it as soon as possible.
+  // This code is where such unwrap happens: when the compound value is put into
+  // the object that it was supposed to initialize (it's an *initializer* list,
+  // after all), instead of binding the whole value to the whole object, we bind
+  // sub-values to sub-objects. Sub-values may themselves be compound values,
+  // and in this case the procedure becomes recursive.
+  // FIXME: The annoying part about compound values is that they don't carry
+  // any sort of information about which value corresponds to which sub-object.
+  // It's simply a list of values in the middle of nowhere; we expect to match
+  // them to sub-objects, essentially, "by index": first value binds to
+  // the first field, second value binds to the second field, etc.
+  // It would have been much safer to organize non-lazy compound values as
+  // a mapping from fields/bases to values.
   const nonloc::CompoundVal& CV = V.castAs();
   nonloc::CompoundVal::iterator VI = CV.begin(), VE = CV.end();
 
-  RecordDecl::field_iterator FI, FE;
   RegionBindingsRef NewB(B);
 
+  // In 

r356222 - [analyzer] Support C++17 aggregates with bases without constructors.

2019-03-14 Thread Artem Dergachev via cfe-commits
Author: dergachev
Date: Thu Mar 14 17:22:59 2019
New Revision: 356222

URL: http://llvm.org/viewvc/llvm-project?rev=356222=rev
Log:
[analyzer] Support C++17 aggregates with bases without constructors.

RegionStore now knows how to bind a nonloc::CompoundVal that represents the
value of an aggregate initializer when it has its initial segment of sub-values
correspond to base classes.

Additionally, fixes the crash from pr40022.

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

Modified:
cfe/trunk/lib/StaticAnalyzer/Core/RegionStore.cpp
cfe/trunk/test/Analysis/array-struct-region.cpp

Modified: cfe/trunk/lib/StaticAnalyzer/Core/RegionStore.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/StaticAnalyzer/Core/RegionStore.cpp?rev=356222=356221=356222=diff
==
--- cfe/trunk/lib/StaticAnalyzer/Core/RegionStore.cpp (original)
+++ cfe/trunk/lib/StaticAnalyzer/Core/RegionStore.cpp Thu Mar 14 17:22:59 2019
@@ -2334,12 +2334,57 @@ RegionBindingsRef RegionStoreManager::bi
   if (V.isUnknown() || !V.getAs())
 return bindAggregate(B, R, UnknownVal());
 
+  // The raw CompoundVal is essentially a symbolic InitListExpr: an (immutable)
+  // list of other values. It appears pretty much only when there's an actual
+  // initializer list expression in the program, and the analyzer tries to
+  // unwrap it as soon as possible.
+  // This code is where such unwrap happens: when the compound value is put 
into
+  // the object that it was supposed to initialize (it's an *initializer* list,
+  // after all), instead of binding the whole value to the whole object, we 
bind
+  // sub-values to sub-objects. Sub-values may themselves be compound values,
+  // and in this case the procedure becomes recursive.
+  // FIXME: The annoying part about compound values is that they don't carry
+  // any sort of information about which value corresponds to which sub-object.
+  // It's simply a list of values in the middle of nowhere; we expect to match
+  // them to sub-objects, essentially, "by index": first value binds to
+  // the first field, second value binds to the second field, etc.
+  // It would have been much safer to organize non-lazy compound values as
+  // a mapping from fields/bases to values.
   const nonloc::CompoundVal& CV = V.castAs();
   nonloc::CompoundVal::iterator VI = CV.begin(), VE = CV.end();
 
-  RecordDecl::field_iterator FI, FE;
   RegionBindingsRef NewB(B);
 
+  // In C++17 aggregates may have base classes, handle those as well.
+  // They appear before fields in the initializer list / compound value.
+  if (const auto *CRD = dyn_cast(RD)) {
+assert(CRD->isAggregate() &&
+   "Non-aggregates are constructed with a constructor!");
+
+for (const auto  : CRD->bases()) {
+  // (Multiple inheritance is fine though.)
+  assert(!B.isVirtual() && "Aggregates cannot have virtual base classes!");
+
+  if (VI == VE)
+break;
+
+  QualType BTy = B.getType();
+  assert(BTy->isStructureOrClassType() && "Base classes must be classes!");
+
+  const CXXRecordDecl *BRD = BTy->getAsCXXRecordDecl();
+  assert(BRD && "Base classes must be C++ classes!");
+
+  const CXXBaseObjectRegion *BR =
+  MRMgr.getCXXBaseObjectRegion(BRD, R, /*IsVirtual=*/false);
+
+  NewB = bindStruct(NewB, BR, *VI);
+
+  ++VI;
+}
+  }
+
+  RecordDecl::field_iterator FI, FE;
+
   for (FI = RD->field_begin(), FE = RD->field_end(); FI != FE; ++FI) {
 
 if (VI == VE)

Modified: cfe/trunk/test/Analysis/array-struct-region.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/Analysis/array-struct-region.cpp?rev=356222=356221=356222=diff
==
--- cfe/trunk/test/Analysis/array-struct-region.cpp (original)
+++ cfe/trunk/test/Analysis/array-struct-region.cpp Thu Mar 14 17:22:59 2019
@@ -1,7 +1,21 @@
-// RUN: %clang_analyze_cc1 
-analyzer-checker=core,alpha.core,debug.ExprInspection -verify -x c %s
-// RUN: %clang_analyze_cc1 
-analyzer-checker=core,alpha.core,debug.ExprInspection -verify -x c++ 
-analyzer-config c++-inlining=constructors %s
-// RUN: %clang_analyze_cc1 
-analyzer-checker=core,alpha.core,debug.ExprInspection -DINLINE -verify -x c %s
-// RUN: %clang_analyze_cc1 
-analyzer-checker=core,alpha.core,debug.ExprInspection -DINLINE -verify -x c++ 
-analyzer-config c++-inlining=constructors %s
+// RUN: %clang_analyze_cc1 -analyzer-checker=core,alpha.core\
+// RUN:-analyzer-checker=debug.ExprInspection -verify\
+// RUN:-x c %s
+// RUN: %clang_analyze_cc1 -analyzer-checker=core,alpha.core\
+// RUN:-analyzer-checker=debug.ExprInspection -verify\
+// RUN:-x c++ -std=c++14 %s
+// RUN: %clang_analyze_cc1 -analyzer-checker=core,alpha.core\
+// RUN:-analyzer-checker=debug.ExprInspection -verify\
+// RUN:  

[PATCH] D59283: Fixed global constant/variable naming check on C++ class for ObjC++ files.

2019-03-14 Thread Yan Zhang via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rL356220: Fixed global constant/variable naming check on C++ 
class for ObjC++ files. (authored by Wizard, committed by ).
Herald added a project: LLVM.
Herald added a subscriber: llvm-commits.

Repository:
  rL LLVM

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

https://reviews.llvm.org/D59283

Files:
  clang-tools-extra/trunk/clang-tidy/google/GlobalVariableDeclarationCheck.cpp
  
clang-tools-extra/trunk/test/clang-tidy/google-objc-global-variable-declaration.mm


Index: 
clang-tools-extra/trunk/test/clang-tidy/google-objc-global-variable-declaration.mm
===
--- 
clang-tools-extra/trunk/test/clang-tidy/google-objc-global-variable-declaration.mm
+++ 
clang-tools-extra/trunk/test/clang-tidy/google-objc-global-variable-declaration.mm
@@ -0,0 +1,10 @@
+// RUN: %check_clang_tidy %s google-objc-global-variable-declaration %t
+
+@class NSString;
+static NSString* const myConstString = @"hello";
+// CHECK-MESSAGES: :[[@LINE-1]]:24: warning: const global variable 
'myConstString' must have a name which starts with an appropriate prefix 
[google-objc-global-variable-declaration]
+// CHECK-FIXES: static NSString* const kMyConstString = @"hello";
+
+class MyTest {
+static int not_objc_style;
+};
Index: 
clang-tools-extra/trunk/clang-tidy/google/GlobalVariableDeclarationCheck.cpp
===
--- clang-tools-extra/trunk/clang-tidy/google/GlobalVariableDeclarationCheck.cpp
+++ clang-tools-extra/trunk/clang-tidy/google/GlobalVariableDeclarationCheck.cpp
@@ -79,12 +79,16 @@
 void GlobalVariableDeclarationCheck::check(
 const MatchFinder::MatchResult ) {
   if (const auto *Decl = Result.Nodes.getNodeAs("global_var")) {
+if (Decl->isStaticDataMember())
+  return;
 diag(Decl->getLocation(),
  "non-const global variable '%0' must have a name which starts with "
  "'g[A-Z]'")
 << Decl->getName() << generateFixItHint(Decl, false);
   }
   if (const auto *Decl = Result.Nodes.getNodeAs("global_const")) {
+if (Decl->isStaticDataMember())
+  return;
 diag(Decl->getLocation(),
  "const global variable '%0' must have a name which starts with "
  "an appropriate prefix")


Index: clang-tools-extra/trunk/test/clang-tidy/google-objc-global-variable-declaration.mm
===
--- clang-tools-extra/trunk/test/clang-tidy/google-objc-global-variable-declaration.mm
+++ clang-tools-extra/trunk/test/clang-tidy/google-objc-global-variable-declaration.mm
@@ -0,0 +1,10 @@
+// RUN: %check_clang_tidy %s google-objc-global-variable-declaration %t
+
+@class NSString;
+static NSString* const myConstString = @"hello";
+// CHECK-MESSAGES: :[[@LINE-1]]:24: warning: const global variable 'myConstString' must have a name which starts with an appropriate prefix [google-objc-global-variable-declaration]
+// CHECK-FIXES: static NSString* const kMyConstString = @"hello";
+
+class MyTest {
+static int not_objc_style;
+};
Index: clang-tools-extra/trunk/clang-tidy/google/GlobalVariableDeclarationCheck.cpp
===
--- clang-tools-extra/trunk/clang-tidy/google/GlobalVariableDeclarationCheck.cpp
+++ clang-tools-extra/trunk/clang-tidy/google/GlobalVariableDeclarationCheck.cpp
@@ -79,12 +79,16 @@
 void GlobalVariableDeclarationCheck::check(
 const MatchFinder::MatchResult ) {
   if (const auto *Decl = Result.Nodes.getNodeAs("global_var")) {
+if (Decl->isStaticDataMember())
+  return;
 diag(Decl->getLocation(),
  "non-const global variable '%0' must have a name which starts with "
  "'g[A-Z]'")
 << Decl->getName() << generateFixItHint(Decl, false);
   }
   if (const auto *Decl = Result.Nodes.getNodeAs("global_const")) {
+if (Decl->isStaticDataMember())
+  return;
 diag(Decl->getLocation(),
  "const global variable '%0' must have a name which starts with "
  "an appropriate prefix")
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang-tools-extra] r356220 - Fixed global constant/variable naming check on C++ class for ObjC++ files.

2019-03-14 Thread Yan Zhang via cfe-commits
Author: wizard
Date: Thu Mar 14 17:17:41 2019
New Revision: 356220

URL: http://llvm.org/viewvc/llvm-project?rev=356220=rev
Log:
Fixed global constant/variable naming check on C++ class for ObjC++ files.

Subscribers: cfe-commits

Tags: #clang

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

Added:

clang-tools-extra/trunk/test/clang-tidy/google-objc-global-variable-declaration.mm
Modified:
clang-tools-extra/trunk/clang-tidy/google/GlobalVariableDeclarationCheck.cpp

Modified: 
clang-tools-extra/trunk/clang-tidy/google/GlobalVariableDeclarationCheck.cpp
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clang-tidy/google/GlobalVariableDeclarationCheck.cpp?rev=356220=356219=356220=diff
==
--- 
clang-tools-extra/trunk/clang-tidy/google/GlobalVariableDeclarationCheck.cpp 
(original)
+++ 
clang-tools-extra/trunk/clang-tidy/google/GlobalVariableDeclarationCheck.cpp 
Thu Mar 14 17:17:41 2019
@@ -79,12 +79,16 @@ void GlobalVariableDeclarationCheck::reg
 void GlobalVariableDeclarationCheck::check(
 const MatchFinder::MatchResult ) {
   if (const auto *Decl = Result.Nodes.getNodeAs("global_var")) {
+if (Decl->isStaticDataMember())
+  return;
 diag(Decl->getLocation(),
  "non-const global variable '%0' must have a name which starts with "
  "'g[A-Z]'")
 << Decl->getName() << generateFixItHint(Decl, false);
   }
   if (const auto *Decl = Result.Nodes.getNodeAs("global_const")) {
+if (Decl->isStaticDataMember())
+  return;
 diag(Decl->getLocation(),
  "const global variable '%0' must have a name which starts with "
  "an appropriate prefix")

Added: 
clang-tools-extra/trunk/test/clang-tidy/google-objc-global-variable-declaration.mm
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/test/clang-tidy/google-objc-global-variable-declaration.mm?rev=356220=auto
==
--- 
clang-tools-extra/trunk/test/clang-tidy/google-objc-global-variable-declaration.mm
 (added)
+++ 
clang-tools-extra/trunk/test/clang-tidy/google-objc-global-variable-declaration.mm
 Thu Mar 14 17:17:41 2019
@@ -0,0 +1,10 @@
+// RUN: %check_clang_tidy %s google-objc-global-variable-declaration %t
+
+@class NSString;
+static NSString* const myConstString = @"hello";
+// CHECK-MESSAGES: :[[@LINE-1]]:24: warning: const global variable 
'myConstString' must have a name which starts with an appropriate prefix 
[google-objc-global-variable-declaration]
+// CHECK-FIXES: static NSString* const kMyConstString = @"hello";
+
+class MyTest {
+static int not_objc_style;
+};


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


[PATCH] D55683: [analyzer] Tests for scan-build?

2019-03-14 Thread Artem Dergachev via Phabricator via cfe-commits
NoQ planned changes to this revision.
NoQ added a comment.
Herald added a subscriber: Charusso.
Herald added a project: clang.

This doesn't seem to work anymore.
Also why did i even use `$PATH`?


Repository:
  rC Clang

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

https://reviews.llvm.org/D55683



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


[PATCH] D56370: [clangd] Add support for type hierarchy (super types only for now)

2019-03-14 Thread Nathan Ridge via Phabricator via cfe-commits
nridge updated this revision to Diff 190755.
nridge marked an inline comment as done.
nridge added a comment.

Address latest review comments


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D56370

Files:
  clang-tools-extra/clangd/ClangdLSPServer.cpp
  clang-tools-extra/clangd/ClangdLSPServer.h
  clang-tools-extra/clangd/ClangdServer.cpp
  clang-tools-extra/clangd/ClangdServer.h
  clang-tools-extra/clangd/FindSymbols.cpp
  clang-tools-extra/clangd/FindSymbols.h
  clang-tools-extra/clangd/Protocol.cpp
  clang-tools-extra/clangd/Protocol.h
  clang-tools-extra/clangd/XRefs.cpp
  clang-tools-extra/clangd/XRefs.h
  clang-tools-extra/clangd/index/SymbolCollector.cpp
  clang-tools-extra/clangd/index/SymbolCollector.h
  clang-tools-extra/test/clangd/initialize-params.test
  clang-tools-extra/test/clangd/type-hierarchy.test
  clang-tools-extra/unittests/clangd/CMakeLists.txt
  clang-tools-extra/unittests/clangd/Matchers.h
  clang-tools-extra/unittests/clangd/TypeHierarchyTests.cpp

Index: clang-tools-extra/unittests/clangd/TypeHierarchyTests.cpp
===
--- /dev/null
+++ clang-tools-extra/unittests/clangd/TypeHierarchyTests.cpp
@@ -0,0 +1,462 @@
+//===-- TypeHierarchyTests.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 "Annotations.h"
+#include "ClangdUnit.h"
+#include "Compiler.h"
+#include "Matchers.h"
+#include "SyncAPI.h"
+#include "TestFS.h"
+#include "TestTU.h"
+#include "XRefs.h"
+#include "index/FileIndex.h"
+#include "index/SymbolCollector.h"
+#include "clang/AST/DeclCXX.h"
+#include "clang/AST/DeclTemplate.h"
+#include "clang/Index/IndexingAction.h"
+#include "llvm/Support/Path.h"
+#include "llvm/Support/ScopedPrinter.h"
+#include "gmock/gmock.h"
+#include "gtest/gtest.h"
+
+namespace clang {
+namespace clangd {
+namespace {
+
+using testing::AllOf;
+using testing::ElementsAre;
+using testing::Eq;
+using testing::Field;
+using testing::IsEmpty;
+using testing::Matcher;
+using testing::Pointee;
+using testing::UnorderedElementsAreArray;
+
+// GMock helpers for matching TypeHierarchyItem.
+MATCHER_P(WithName, N, "") { return arg.name == N; }
+MATCHER_P(WithKind, Kind, "") { return arg.kind == Kind; }
+MATCHER_P(SelectionRangeIs, R, "") { return arg.selectionRange == R; }
+template 
+testing::Matcher Parents(ParentMatchers... ParentsM) {
+  return Field(::parents, HasValue(ElementsAre(ParentsM...)));
+}
+
+TEST(FindRecordTypeAt, TypeOrVariable) {
+  Annotations Source(R"cpp(
+struct Ch^ild2 {
+  int c;
+};
+
+int main() {
+  Ch^ild2 ch^ild2;
+  ch^ild2.c = 1;
+}
+)cpp");
+
+  TestTU TU = TestTU::withCode(Source.code());
+  auto AST = TU.build();
+
+  ASSERT_TRUE(AST.getDiagnostics().empty());
+
+  for (Position Pt : Source.points()) {
+const CXXRecordDecl *RD = findRecordTypeAt(AST, Pt);
+EXPECT_EQ((AST, "Child2"), static_cast(RD));
+  }
+}
+
+TEST(FindRecordTypeAt, Method) {
+  Annotations Source(R"cpp(
+struct Child2 {
+  void met^hod ();
+  void met^hod (int x);
+};
+
+int main() {
+  Child2 child2;
+  child2.met^hod(5);
+}
+)cpp");
+
+  TestTU TU = TestTU::withCode(Source.code());
+  auto AST = TU.build();
+
+  ASSERT_TRUE(AST.getDiagnostics().empty());
+
+  for (Position Pt : Source.points()) {
+const CXXRecordDecl *RD = findRecordTypeAt(AST, Pt);
+EXPECT_EQ((AST, "Child2"), static_cast(RD));
+  }
+}
+
+TEST(FindRecordTypeAt, Field) {
+  Annotations Source(R"cpp(
+struct Child2 {
+  int fi^eld;
+};
+
+int main() {
+  Child2 child2;
+  child2.fi^eld = 5;
+}
+)cpp");
+
+  TestTU TU = TestTU::withCode(Source.code());
+  auto AST = TU.build();
+
+  ASSERT_TRUE(AST.getDiagnostics().empty());
+
+  for (Position Pt : Source.points()) {
+const CXXRecordDecl *RD = findRecordTypeAt(AST, Pt);
+// A field does not unambiguously specify a record type
+// (possible associated reocrd types could be the field's type,
+// or the type of the record that the field is a member of).
+EXPECT_EQ(nullptr, RD);
+  }
+}
+
+TEST(TypeParents, SimpleInheritance) {
+  Annotations Source(R"cpp(
+struct Parent {
+  int a;
+};
+
+struct Child1 : Parent {
+  int b;
+};
+
+struct Child2 : Child1 {
+  int c;
+};
+)cpp");
+
+  TestTU TU = TestTU::withCode(Source.code());
+  auto AST = TU.build();
+
+  ASSERT_TRUE(AST.getDiagnostics().empty());
+
+  const CXXRecordDecl *Parent =
+  dyn_cast((AST, "Parent"));
+  const CXXRecordDecl *Child1 =
+  dyn_cast((AST, "Child1"));
+  const CXXRecordDecl *Child2 =
+  dyn_cast((AST, "Child2"));
+
+  EXPECT_THAT(typeParents(Parent), ElementsAre());
+  EXPECT_THAT(typeParents(Child1), ElementsAre(Parent));
+  

[PATCH] D56370: [clangd] Add support for type hierarchy (super types only for now)

2019-03-14 Thread Nathan Ridge via Phabricator via cfe-commits
nridge marked 7 inline comments as done.
nridge added inline comments.



Comment at: clang-tools-extra/clangd/XRefs.h:62
+/// Find the record type references at \p Pos.
+const CXXRecordDecl *findRecordTypeAt(ParsedAST , Position Pos);
+

ilya-biryukov wrote:
> This method looks like an implementation detail and does not align with other 
> methods in `XRefs.h` which are high-level methods that implement LSP 
> functionality.
> 
> It would be more appropriate to move it to `AST.h` or directly into the 
> `XRefs.cpp`. WDYT?
@sammccall asked for this method to be exposed in the header and some of the 
tests written in terms of it.



Comment at: clang-tools-extra/clangd/index/SymbolCollector.h:154
+// the SourceManager.
+std::string toURI(const SourceManager , llvm::StringRef Path,
+  llvm::StringRef FallbackDir);

ioeric wrote:
> why are we pulling this into the header? This still seems to be only used in 
> SymbolCollector.cpp.
You're right. This is a leftover from an earlier version of the patch.



Comment at: clang-tools-extra/test/clangd/type-hierarchy.test:1
+# RUN: clangd -lit-test < %s | FileCheck -strict-whitespace %s
+{"jsonrpc":"2.0","id":0,"method":"initialize","params":{"processId":123,"rootPath":"clangd","capabilities":{},"trace":"off"}}

kadircet wrote:
> why strict-whitespace?
That's what the other lit tests seem to do, I just copied it :)


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D56370



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


[PATCH] D59394: [Sema] De-duplicate some availability checking logic

2019-03-14 Thread Louis Dionne via Phabricator via cfe-commits
ldionne accepted this revision.
ldionne added a comment.
This revision is now accepted and ready to land.

I can confirm this fixed my original problem. It's also close to the patch I 
attempted writing myself earlier this week -- but this one is better of course.


Repository:
  rC Clang

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

https://reviews.llvm.org/D59394



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


[PATCH] D59283: Fixed global constant/variable naming check on C++ class for ObjC++ files.

2019-03-14 Thread Yan Zhang via Phabricator via cfe-commits
Wizard updated this revision to Diff 190750.
Wizard added a comment.

add new line


Repository:
  rCTE Clang Tools Extra

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

https://reviews.llvm.org/D59283

Files:
  clang-tidy/google/GlobalVariableDeclarationCheck.cpp
  test/clang-tidy/google-objc-global-variable-declaration.mm


Index: test/clang-tidy/google-objc-global-variable-declaration.mm
===
--- /dev/null
+++ test/clang-tidy/google-objc-global-variable-declaration.mm
@@ -0,0 +1,10 @@
+// RUN: %check_clang_tidy %s google-objc-global-variable-declaration %t
+
+@class NSString;
+static NSString* const myConstString = @"hello";
+// CHECK-MESSAGES: :[[@LINE-1]]:24: warning: const global variable 
'myConstString' must have a name which starts with an appropriate prefix 
[google-objc-global-variable-declaration]
+// CHECK-FIXES: static NSString* const kMyConstString = @"hello";
+
+class MyTest {
+static int not_objc_style;
+};
Index: clang-tidy/google/GlobalVariableDeclarationCheck.cpp
===
--- clang-tidy/google/GlobalVariableDeclarationCheck.cpp
+++ clang-tidy/google/GlobalVariableDeclarationCheck.cpp
@@ -79,12 +79,16 @@
 void GlobalVariableDeclarationCheck::check(
 const MatchFinder::MatchResult ) {
   if (const auto *Decl = Result.Nodes.getNodeAs("global_var")) {
+if (Decl->isStaticDataMember())
+  return;
 diag(Decl->getLocation(),
  "non-const global variable '%0' must have a name which starts with "
  "'g[A-Z]'")
 << Decl->getName() << generateFixItHint(Decl, false);
   }
   if (const auto *Decl = Result.Nodes.getNodeAs("global_const")) {
+if (Decl->isStaticDataMember())
+  return;
 diag(Decl->getLocation(),
  "const global variable '%0' must have a name which starts with "
  "an appropriate prefix")


Index: test/clang-tidy/google-objc-global-variable-declaration.mm
===
--- /dev/null
+++ test/clang-tidy/google-objc-global-variable-declaration.mm
@@ -0,0 +1,10 @@
+// RUN: %check_clang_tidy %s google-objc-global-variable-declaration %t
+
+@class NSString;
+static NSString* const myConstString = @"hello";
+// CHECK-MESSAGES: :[[@LINE-1]]:24: warning: const global variable 'myConstString' must have a name which starts with an appropriate prefix [google-objc-global-variable-declaration]
+// CHECK-FIXES: static NSString* const kMyConstString = @"hello";
+
+class MyTest {
+static int not_objc_style;
+};
Index: clang-tidy/google/GlobalVariableDeclarationCheck.cpp
===
--- clang-tidy/google/GlobalVariableDeclarationCheck.cpp
+++ clang-tidy/google/GlobalVariableDeclarationCheck.cpp
@@ -79,12 +79,16 @@
 void GlobalVariableDeclarationCheck::check(
 const MatchFinder::MatchResult ) {
   if (const auto *Decl = Result.Nodes.getNodeAs("global_var")) {
+if (Decl->isStaticDataMember())
+  return;
 diag(Decl->getLocation(),
  "non-const global variable '%0' must have a name which starts with "
  "'g[A-Z]'")
 << Decl->getName() << generateFixItHint(Decl, false);
   }
   if (const auto *Decl = Result.Nodes.getNodeAs("global_const")) {
+if (Decl->isStaticDataMember())
+  return;
 diag(Decl->getLocation(),
  "const global variable '%0' must have a name which starts with "
  "an appropriate prefix")
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D59394: [Sema] De-duplicate some availability checking logic

2019-03-14 Thread Erik Pilkington via Phabricator via cfe-commits
erik.pilkington created this revision.
erik.pilkington added reviewers: rsmith, aaron.ballman, ldionne, dexonsmith.
Herald added subscribers: jdoerfert, jkorous.
Herald added a project: clang.

Right now, we emit unavailable errors for calls to functions during overload 
resolution, and for references to all other declarations in DiagnoseUseOfDecl. 
The early checks during overload resolution aren't as good as the 
DiagnoseAvailabilityOfDecl based checks, as they error on the code from 
PR40991. Fix this by removing the early checking.

llvm.org/PR40991
rdar://48564179

Thanks for taking a look!
Erik


Repository:
  rC Clang

https://reviews.llvm.org/D59394

Files:
  clang/include/clang/Basic/DiagnosticSemaKinds.td
  clang/include/clang/Sema/Sema.h
  clang/lib/Sema/SemaExpr.cpp
  clang/lib/Sema/SemaExprCXX.cpp
  clang/lib/Sema/SemaInit.cpp
  clang/lib/Sema/SemaOverload.cpp
  clang/test/Sema/enable_if.c
  clang/test/Sema/overloadable.c
  clang/test/SemaCXX/attr-unavailable.cpp
  clang/test/SemaCXX/coroutines.cpp
  clang/test/SemaObjCXX/overload.mm
  clang/test/SemaTemplate/instantiate-expr-4.cpp

Index: clang/test/SemaTemplate/instantiate-expr-4.cpp
===
--- clang/test/SemaTemplate/instantiate-expr-4.cpp
+++ clang/test/SemaTemplate/instantiate-expr-4.cpp
@@ -106,12 +106,12 @@
 struct New3 {
   New3();
 
-  void *operator new[](__SIZE_TYPE__) __attribute__((unavailable)); // expected-note{{explicitly made unavailable}}
+  void *operator new[](__SIZE_TYPE__) __attribute__((unavailable)); // expected-note{{explicitly marked unavailable here}}
 };
 
 template
 void* object_creator() {
-  return new C(); // expected-error{{call to unavailable function 'operator new[]'}}
+  return new C(); // expected-error{{'operator new[]' is unavailable}}
 }
 
 template void *object_creator(); // expected-note{{instantiation}}
Index: clang/test/SemaObjCXX/overload.mm
===
--- clang/test/SemaObjCXX/overload.mm
+++ clang/test/SemaObjCXX/overload.mm
@@ -111,11 +111,11 @@
 
 // rdar://problem/8592139
 namespace test6 {
-  void foo(id); // expected-note{{candidate function}}
-  void foo(A*) __attribute__((unavailable)); // expected-note {{explicitly made unavailable}}
+  void foo(id);
+  void foo(A*) __attribute__((unavailable)); // expected-note {{marked unavailable here}}
 
   void test(B *b) {
-foo(b); // expected-error {{call to unavailable function 'foo'}}
+foo(b); // expected-error {{'foo' is unavailable}}
   }
 }
 
Index: clang/test/SemaCXX/coroutines.cpp
===
--- clang/test/SemaCXX/coroutines.cpp
+++ clang/test/SemaCXX/coroutines.cpp
@@ -598,26 +598,26 @@
 
 struct bad_promise_base {
 private:
-  void return_void();
+  void return_void(); // expected-note 2 {{declared private here}}
 };
 struct bad_promise_8 : bad_promise_base {
   coro get_return_object();
   suspend_always initial_suspend();
   suspend_always final_suspend();
-  void unhandled_exception() __attribute__((unavailable)); // expected-note 2 {{made unavailable}}
-  void unhandled_exception() const;// expected-note 2 {{candidate}}
-  void unhandled_exception(void *) const;  // expected-note 2 {{requires 1 argument, but 0 were provided}}
+  void unhandled_exception() __attribute__((unavailable)); // expected-note 2 {{marked unavailable here}}
+  void unhandled_exception() const;
+  void unhandled_exception(void *) const;
 };
 coro calls_unhandled_exception() {
-  // expected-error@-1 {{call to unavailable member function 'unhandled_exception'}}
-  // FIXME: also warn about private 'return_void' here. Even though building
-  // the call to unhandled_exception has already failed.
+  // expected-error@-1 {{'unhandled_exception' is unavailable}}
+  // expected-error@-2 {{'return_void' is a private member}}
   co_await a;
 }
 
 template 
 coro calls_unhandled_exception_dependent(T) {
-  // expected-error@-1 {{call to unavailable member function 'unhandled_exception'}}
+  // expected-error@-1 {{'unhandled_exception' is unavailable}}
+  // expected-error@-2 {{'return_void' is a private member}}
   co_await a;
 }
 template coro calls_unhandled_exception_dependent(bad_promise_8); // expected-note {{in instantiation}}
@@ -626,14 +626,13 @@
   coro get_return_object();
   suspend_always initial_suspend();
   suspend_always final_suspend();
-  void await_transform(void *);// expected-note {{candidate}}
-  awaitable await_transform(int) __attribute__((unavailable)); // expected-note {{explicitly made unavailable}}
+  void await_transform(void *);
+  awaitable await_transform(int) __attribute__((unavailable)); // expected-note {{explicitly marked unavailable}}
   void return_void();
   void unhandled_exception();
 };
 coro calls_await_transform() {
-  co_await 42; // expected-error {{call to unavailable member 

[PATCH] D58418: [clang][DirectoryWatcher] Upstream DirectoryWatcher

2019-03-14 Thread Nico Weber via Phabricator via cfe-commits
thakis added a comment.

Why is this needed for index-while-building? My mental model for 
index-while-building is that that streams out build index metadata as part of 
the regular compile. Why does that require watching directories?


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

https://reviews.llvm.org/D58418



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


[PATCH] D58418: [clang][DirectoryWatcher] Upstream DirectoryWatcher

2019-03-14 Thread Jan Korous via Phabricator via cfe-commits
jkorous updated this revision to Diff 190744.
jkorous added a comment.

Remove duplicate comment


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

https://reviews.llvm.org/D58418

Files:
  clang/include/clang/DirectoryWatcher/DirectoryWatcher.h
  clang/lib/CMakeLists.txt
  clang/lib/DirectoryWatcher/CMakeLists.txt
  clang/lib/DirectoryWatcher/Config.inc.in
  clang/lib/DirectoryWatcher/DirectoryWatcher-linux.inc.h
  clang/lib/DirectoryWatcher/DirectoryWatcher-mac.inc.h
  clang/lib/DirectoryWatcher/DirectoryWatcher.cpp
  clang/unittests/CMakeLists.txt
  clang/unittests/DirectoryWatcher/CMakeLists.txt
  clang/unittests/DirectoryWatcher/DirectoryWatcherTest.cpp

Index: clang/unittests/DirectoryWatcher/DirectoryWatcherTest.cpp
===
--- /dev/null
+++ clang/unittests/DirectoryWatcher/DirectoryWatcherTest.cpp
@@ -0,0 +1,327 @@
+//===- unittests/DirectoryWatcher/DirectoryWatcherTest.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/DirectoryWatcher/DirectoryWatcher.h"
+#include "llvm/Support/FileSystem.h"
+#include "llvm/Support/Path.h"
+#include "gtest/gtest.h"
+#include 
+#include 
+#include 
+
+using namespace llvm;
+using namespace llvm::sys;
+using namespace llvm::sys::fs;
+using namespace clang;
+
+namespace {
+
+class EventCollection {
+  SmallVector Events;
+
+public:
+  EventCollection() = default;
+  explicit EventCollection(ArrayRef events) {
+append(events);
+  }
+
+  void append(ArrayRef events) {
+Events.append(events.begin(), events.end());
+  }
+
+  bool empty() const { return Events.empty(); }
+  size_t size() const { return Events.size(); }
+  void clear() { Events.clear(); }
+
+  bool hasEvents(ArrayRef filenames,
+ ArrayRef kinds,
+ ArrayRef stats) const {
+assert(filenames.size() == kinds.size());
+assert(filenames.size() == stats.size());
+SmallVector evts = Events;
+bool hadError = false;
+for (unsigned i = 0, e = filenames.size(); i < e; ++i) {
+  StringRef fname = filenames[i];
+  DirectoryWatcher::EventKind kind = kinds[i];
+  auto it = std::find_if(evts.begin(), evts.end(),
+ [&](const DirectoryWatcher::Event ) -> bool {
+   return path::filename(evt.Filename) == fname;
+ });
+  if (it == evts.end()) {
+hadError = err(Twine("expected filename '" + fname + "' not found"));
+continue;
+  }
+  if (it->Kind != kind) {
+hadError = err(Twine("filename '" + fname + "' has event kind " +
+ std::to_string((int)it->Kind) + ", expected ") +
+   std::to_string((int)kind));
+  }
+  evts.erase(it);
+}
+for (const auto  : evts) {
+  hadError = err(Twine("unexpected filename '" +
+   path::filename(evt.Filename) + "' found"));
+}
+return !hadError;
+  }
+
+  bool hasAdded(ArrayRef filenames,
+ArrayRef stats) const {
+std::vector kinds{
+filenames.size(), DirectoryWatcher::EventKind::Added};
+return hasEvents(filenames, kinds, stats);
+  }
+
+  bool hasRemoved(ArrayRef filenames) const {
+std::vector kinds{
+filenames.size(), DirectoryWatcher::EventKind::Removed};
+std::vector stats{filenames.size(), file_status{}};
+return hasEvents(filenames, kinds, stats);
+  }
+
+private:
+  bool err(Twine msg) const {
+SmallString<128> buf;
+llvm::errs() << msg.toStringRef(buf) << '\n';
+return true;
+  }
+};
+
+struct EventOccurrence {
+  std::vector Events;
+  bool IsInitial;
+};
+
+class DirectoryWatcherTest
+: public std::enable_shared_from_this {
+  std::string WatchedDir;
+  std::string TempDir;
+  std::unique_ptr DirWatcher;
+
+  std::condition_variable Condition;
+  std::mutex Mutex;
+  std::deque EvtOccurs;
+
+public:
+  void init() {
+SmallString<128> pathBuf;
+std::error_code EC = createUniqueDirectory("dirwatcher", pathBuf);
+ASSERT_FALSE(EC);
+TempDir = pathBuf.str();
+path::append(pathBuf, "watch");
+WatchedDir = pathBuf.str();
+EC = create_directory(WatchedDir);
+ASSERT_FALSE(EC);
+  }
+
+  ~DirectoryWatcherTest() {
+stopWatching();
+remove_directories(TempDir);
+  }
+
+public:
+  StringRef getWatchedDir() const { return WatchedDir; }
+
+  void addFile(StringRef filename, file_status ) {
+SmallString<128> pathBuf;
+pathBuf = TempDir;
+path::append(pathBuf, filename);
+Expected ft =
+openNativeFileForWrite(pathBuf, CD_CreateNew, OF_None);
+ASSERT_TRUE((bool)ft);
+closeFile(*ft);
+
+SmallString<128> newPath;
+

[PATCH] D59336: [clang-tidy] Disable google-runtime-int in Objective-C++ 

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

In D59336#1429564 , @aaron.ballman 
wrote:

> This is missing test cases that demonstrate the behavior is what we expect it 
> to be for ObjC++ code vs C++ code.


Added tests for Objective-C and Objective-C++.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D59336



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


[PATCH] D59336: [clang-tidy] Disable google-runtime-int in Objective-C++ 

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

Add google-runtime-int tests for Objective-C and Objective-C++.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D59336

Files:
  clang-tools-extra/clang-tidy/google/IntegerTypesCheck.cpp
  clang-tools-extra/docs/ReleaseNotes.rst
  clang-tools-extra/test/clang-tidy/google-runtime-int.m
  clang-tools-extra/test/clang-tidy/google-runtime-int.mm

Index: clang-tools-extra/test/clang-tidy/google-runtime-int.mm
===
--- /dev/null
+++ clang-tools-extra/test/clang-tidy/google-runtime-int.mm
@@ -0,0 +1,31 @@
+// RUN: clang-tidy -checks=-*,google-runtime-int %s -- -x objective-c++ 2>&1 | not grep 'warning:\|error:'
+
+typedef long NSInteger;
+typedef unsigned long NSUInteger;
+
+@interface NSString
+@property(readonly) NSInteger integerValue;
+@property(readonly) long long longLongValue;
+@property(readonly) NSUInteger length;
+@end
+
+NSInteger Foo(NSString *s) {
+  return [s integerValue];
+}
+
+long long Bar(NSString *s) {
+  return [s longLongValue];
+}
+
+NSUInteger Baz(NSString *s) {
+  return [s length];
+}
+
+unsigned short NSSwapShort(unsigned short inv);
+
+long DoSomeMath(long a, short b) {
+  short c = NSSwapShort(b);
+  long a2 = a * 5L;
+  return a2 + c;
+}
+
Index: clang-tools-extra/test/clang-tidy/google-runtime-int.m
===
--- /dev/null
+++ clang-tools-extra/test/clang-tidy/google-runtime-int.m
@@ -0,0 +1,31 @@
+// RUN: clang-tidy -checks=-*,google-runtime-int %s 2>&1 -- -x objective-c | not grep 'warning:\|error:'
+
+typedef long NSInteger;
+typedef unsigned long NSUInteger;
+
+@interface NSString
+@property(readonly) NSInteger integerValue;
+@property(readonly) long long longLongValue;
+@property(readonly) NSUInteger length;
+@end
+
+NSInteger Foo(NSString *s) {
+  return [s integerValue];
+}
+
+long long Bar(NSString *s) {
+  return [s longLongValue];
+}
+
+NSUInteger Baz(NSString *s) {
+  return [s length];
+}
+
+unsigned short NSSwapShort(unsigned short inv);
+
+long DoSomeMath(long a, short b) {
+  short c = NSSwapShort(b);
+  long a2 = a * 5L;
+  return a2 + c;
+}
+
Index: clang-tools-extra/docs/ReleaseNotes.rst
===
--- clang-tools-extra/docs/ReleaseNotes.rst
+++ clang-tools-extra/docs/ReleaseNotes.rst
@@ -115,6 +115,9 @@
   `CommentUserDefiniedLiterals`, `CommentStringLiterals`,
   `CommentCharacterLiterals` & `CommentNullPtrs` options.
 
+- The :doc:`google-runtime-int `
+  check has been disabled in Objective-C++.
+
 - The `Acronyms` and `IncludeDefaultAcronyms` options for the
   :doc:`objc-property-declaration `
   check have been removed.
Index: clang-tools-extra/clang-tidy/google/IntegerTypesCheck.cpp
===
--- clang-tools-extra/clang-tidy/google/IntegerTypesCheck.cpp
+++ clang-tools-extra/clang-tidy/google/IntegerTypesCheck.cpp
@@ -54,7 +54,9 @@
 
 void IntegerTypesCheck::registerMatchers(MatchFinder *Finder) {
   // Find all TypeLocs. The relevant Style Guide rule only applies to C++.
-  if (!getLangOpts().CPlusPlus)
+  // This check is also not applied in Objective-C++ sources as Objective-C
+  // often uses built-in integer types other than `int`.
+  if (!getLangOpts().CPlusPlus || getLangOpts().ObjC)
 return;
   // Match any integer types, unless they are passed to a printf-based API:
   //
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D54881: [clang-format] Prevent Clang-Format from editing leading whitespace on lines outside of the format range

2019-03-14 Thread Russell McClellan via Phabricator via cfe-commits
russellmcc added a comment.

Bump!  Still waiting feedback on this.


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

https://reviews.llvm.org/D54881



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


[PATCH] D40988: Clang-format: add finer-grained options for putting all arguments on one line

2019-03-14 Thread Russell McClellan via Phabricator via cfe-commits
russellmcc added a comment.

Bump!  Still looking for help here - thanks for the consideration.


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

https://reviews.llvm.org/D40988



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


[PATCH] D59076: [coroutines][PR40978] Emit error for co_yield within catch block

2019-03-14 Thread Brian Gesiak via Phabricator via cfe-commits
modocache updated this revision to Diff 190740.
modocache added a comment.

OK, I've responded to all your review comments -- thank you! Please give this 
another look when you get a chance. I would like to emit note diagnostics 
pointing to the catch blocks, but I've left that as a FIXME for now.


Repository:
  rC Clang

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

https://reviews.llvm.org/D59076

Files:
  include/clang/Basic/DiagnosticSemaKinds.td
  include/clang/Sema/Scope.h
  lib/Parse/ParseStmt.cpp
  lib/Sema/Scope.cpp
  lib/Sema/SemaCoroutine.cpp
  test/SemaCXX/coroutines.cpp

Index: test/SemaCXX/coroutines.cpp
===
--- test/SemaCXX/coroutines.cpp
+++ test/SemaCXX/coroutines.cpp
@@ -314,13 +314,23 @@
   }
 };
 
+namespace std { class type_info; }
+
 void unevaluated() {
-  decltype(co_await a); // expected-error {{cannot be used in an unevaluated context}}
-  sizeof(co_await a); // expected-error {{cannot be used in an unevaluated context}}
-  typeid(co_await a); // expected-error {{cannot be used in an unevaluated context}}
-  decltype(co_yield a); // expected-error {{cannot be used in an unevaluated context}}
-  sizeof(co_yield a); // expected-error {{cannot be used in an unevaluated context}}
-  typeid(co_yield a); // expected-error {{cannot be used in an unevaluated context}}
+  decltype(co_await a); // expected-error {{'co_await' cannot be used in an unevaluated context}}
+// expected-warning@-1 {{declaration does not declare anything}}
+  sizeof(co_await a); // expected-error {{'co_await' cannot be used in an unevaluated context}}
+  // expected-error@-1 {{invalid application of 'sizeof' to an incomplete type 'void'}}
+  typeid(co_await a); // expected-error {{'co_await' cannot be used in an unevaluated context}}
+  // expected-warning@-1 {{expression with side effects has no effect in an unevaluated context}}
+  // expected-warning@-2 {{expression result unused}}
+  decltype(co_yield 1); // expected-error {{'co_yield' cannot be used in an unevaluated context}}
+// expected-warning@-1 {{declaration does not declare anything}}
+  sizeof(co_yield 2); // expected-error {{'co_yield' cannot be used in an unevaluated context}}
+  // expected-error@-1 {{invalid application of 'sizeof' to an incomplete type 'void'}}
+  typeid(co_yield 3); // expected-error {{'co_yield' cannot be used in an unevaluated context}}
+  // expected-warning@-1 {{expression with side effects has no effect in an unevaluated context}}
+  // expected-warning@-2 {{expression result unused}}
 }
 
 // [expr.await]p2: "An await-expression shall not appear in a default argument."
@@ -328,6 +338,47 @@
 // not allowed. A user may not understand that this is "outside a function."
 void default_argument(int arg = co_await 0) {} // expected-error {{'co_await' cannot be used outside a function}}
 
+void await_in_catch_coroutine() {
+  try {
+  } catch (...) { // FIXME: Emit a note diagnostic pointing out the try handler on this line.
+[]() -> void { co_await a; }(); // OK
+co_await a; // expected-error {{'co_await' cannot be used in the handler of a try block}}
+  }
+}
+
+void await_nested_in_catch_coroutine() {
+  try {
+  } catch (...) { // FIXME: Emit a note diagnostic pointing out the try handler on this line.
+try {
+  co_await a; // expected-error {{'co_await' cannot be used in the handler of a try block}}
+  []() -> void { co_await a; }(); // OK
+} catch (...) {
+  co_return 123;
+}
+  }
+}
+
+void await_in_lambda_in_catch_coroutine() {
+  try {
+  } catch (...) {
+[]() -> void { co_await a; }(); // OK
+  }
+}
+
+void yield_in_catch_coroutine() {
+  try {
+  } catch (...) {
+co_yield 1; // expected-error {{'co_yield' cannot be used in the handler of a try block}}
+  }
+}
+
+void return_in_catch_coroutine() {
+  try {
+  } catch (...) {
+co_return 123; // OK
+  }
+}
+
 constexpr auto constexpr_deduced_return_coroutine() {
   co_yield 0; // expected-error {{'co_yield' cannot be used in a constexpr function}}
   // expected-error@-1 {{'co_yield' cannot be used in a function with a deduced return type}}
Index: lib/Sema/SemaCoroutine.cpp
===
--- lib/Sema/SemaCoroutine.cpp
+++ lib/Sema/SemaCoroutine.cpp
@@ -185,21 +185,8 @@
 
 static bool isValidCoroutineContext(Sema , SourceLocation Loc,
 StringRef Keyword) {
-  // 'co_await' and 'co_yield' are not permitted in unevaluated operands,
-  // such as subexpressions of \c sizeof.
-  //
-  // [expr.await]p2, emphasis added: "An await-expression shall appear only in
-  // a *potentially evaluated* expression within the compound-statement of a
-  // function-body outside of a handler [...] A context within 

[PATCH] D58404: [clang-format] Add basic support for formatting C# files

2019-03-14 Thread MyDeveloperDay via Phabricator via cfe-commits
MyDeveloperDay updated this revision to Diff 190737.
MyDeveloperDay added a comment.

Remove  non related clang-format changes
run git clang-format
Add a Microsoft style (trying to match most closely the more traditional 
Microsoft style used for C#)
This will allow, CSharp to be added to the config by



Language: CSharp
BasedOnStyle: Microsoft
.


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

https://reviews.llvm.org/D58404

Files:
  docs/ClangFormat.rst
  docs/ClangFormatStyleOptions.rst
  docs/ReleaseNotes.rst
  include/clang/Basic/LangOptions.def
  include/clang/Basic/TokenKinds.def
  include/clang/Basic/TokenKinds.h
  include/clang/Format/Format.h
  lib/Format/ContinuationIndenter.cpp
  lib/Format/Format.cpp
  lib/Format/FormatToken.h
  lib/Format/FormatTokenLexer.cpp
  lib/Format/FormatTokenLexer.h
  lib/Format/TokenAnnotator.cpp
  lib/Format/UnwrappedLineFormatter.cpp
  lib/Format/UnwrappedLineParser.cpp
  lib/Lex/Lexer.cpp
  lib/Lex/LiteralSupport.cpp
  lib/Lex/TokenConcatenation.cpp
  lib/Rewrite/HTMLRewrite.cpp
  tools/clang-format/ClangFormat.cpp
  unittests/Format/CMakeLists.txt
  unittests/Format/FormatTestCSharp.cpp

Index: unittests/Format/FormatTestCSharp.cpp
===
--- /dev/null
+++ unittests/Format/FormatTestCSharp.cpp
@@ -0,0 +1,180 @@
+//===- unittest/Format/FormatTestCSharp.cpp - Formatting tests for CSharp -===//
+//
+// 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 "FormatTestUtils.h"
+#include "clang/Format/Format.h"
+#include "llvm/Support/Debug.h"
+#include "gtest/gtest.h"
+
+#define DEBUG_TYPE "format-test"
+
+namespace clang {
+namespace format {
+
+class FormatTestCSharp : public ::testing::Test {
+protected:
+  static std::string format(llvm::StringRef Code, unsigned Offset,
+unsigned Length, const FormatStyle ) {
+LLVM_DEBUG(llvm::errs() << "---\n");
+LLVM_DEBUG(llvm::errs() << Code << "\n\n");
+std::vector Ranges(1, tooling::Range(Offset, Length));
+tooling::Replacements Replaces = reformat(Style, Code, Ranges);
+auto Result = applyAllReplacements(Code, Replaces);
+EXPECT_TRUE(static_cast(Result));
+LLVM_DEBUG(llvm::errs() << "\n" << *Result << "\n\n");
+return *Result;
+  }
+
+  static std::string
+  format(llvm::StringRef Code,
+ const FormatStyle  = getGoogleStyle(FormatStyle::LK_CSharp)) {
+return format(Code, 0, Code.size(), Style);
+  }
+
+  static FormatStyle getStyleWithColumns(unsigned ColumnLimit) {
+FormatStyle Style = getGoogleStyle(FormatStyle::LK_CSharp);
+Style.ColumnLimit = ColumnLimit;
+return Style;
+  }
+
+  static void verifyFormat(
+  llvm::StringRef Code,
+  const FormatStyle  = getGoogleStyle(FormatStyle::LK_CSharp)) {
+EXPECT_EQ(Code.str(), format(Code, Style)) << "Expected code is not stable";
+EXPECT_EQ(Code.str(), format(test::messUp(Code), Style));
+  }
+};
+
+TEST_F(FormatTestCSharp, CSharpClass) {
+  verifyFormat("public class SomeClass {\n"
+   "  void f() {}\n"
+   "  int g() { return 0; }\n"
+   "  void h() {\n"
+   "while (true) f();\n"
+   "for (;;) f();\n"
+   "if (true) f();\n"
+   "  }\n"
+   "}");
+}
+
+TEST_F(FormatTestCSharp, AccessModifiers) {
+  verifyFormat("public String toString() {}");
+  verifyFormat("private String toString() {}");
+  verifyFormat("protected String toString() {}");
+  verifyFormat("internal String toString() {}");
+
+  verifyFormat("public override String toString() {}");
+  verifyFormat("private override String toString() {}");
+  verifyFormat("protected override String toString() {}");
+  verifyFormat("internal override String toString() {}");
+
+  verifyFormat("internal static String toString() {}");
+}
+
+TEST_F(FormatTestCSharp, NoStringLiteralBreaks) {
+  verifyFormat("foo("
+   "\"a"
+   "aa\");");
+}
+
+TEST_F(FormatTestCSharp, CSharpVerbatiumStringLiterals) {
+  verifyFormat("foo(@\"\\abc\\\");");
+  // @"ABC\" + ToString("B") - handle embedded \ in literal string at
+  // the end
+  verifyFormat("string s = @\"ABC\\\" + ToString(\"B\");");
+
+  verifyFormat("string s = @\"ABC\"\"DEF\"\"GHI\"");
+  verifyFormat("string s = @\"ABC\"\"DEF\"\"\"");
+  verifyFormat("string s = @\"ABC\"\"DEF\"\"\" + abc");
+}
+
+TEST_F(FormatTestCSharp, CSharpInterpolatedStringLiterals) {
+  verifyFormat("foo($\"{aaa}\");");
+  verifyFormat("foo($\"{A}\");");
+  verifyFormat(
+  "foo($\"{A}"
+  

[PATCH] D59319: [OpenMP][Offloading][1/3] A generic and simple target region interface

2019-03-14 Thread Johannes Doerfert via Phabricator via cfe-commits
jdoerfert marked 3 inline comments as done.
jdoerfert added inline comments.



Comment at: openmp/libomptarget/deviceRTLs/common/target_region.h:100
+///
+EXTERN int8_t __kmpc_target_region_kernel_init(bool UseSPMDMode,
+   bool RequiresOMPRuntime,

ABataev wrote:
> jdoerfert wrote:
> > ABataev wrote:
> > > jdoerfert wrote:
> > > > ABataev wrote:
> > > > > jdoerfert wrote:
> > > > > > ABataev wrote:
> > > > > > > Better to use `ident_loc` for passing info about execution mode 
> > > > > > > and full/lightweight runtime.
> > > > > > Could you please explain why you think that? Adding indirection 
> > > > > > through a structure does not really seem beneficial to me.
> > > > > Almost all function from libomp rely on `ident_loc`. The functions, 
> > > > > which were added for NVPTX without this parameter had a lot of 
> > > > > problems later and most of them were replaced with the functions with 
> > > > > this parameter type. Plus, this parameter is used for OMPD/OMPT and 
> > > > > it may be important for future OMPD/OMPT support.
> > > > > Almost all function from libomp rely on ident_loc.
> > > > 
> > > > If you look at the implementation of this interface for NVPTX you will 
> > > > see that the called functions do not take `ident_loc` values. When you 
> > > > create the calls from the existing NVPTX code generation in clang, the 
> > > > current code **does not use** `ident_loc` for similar functions, see:
> > > > `___kmpc_kernel_init(kmp_int32 thread_limit, int16_t 
> > > > RequiresOMPRuntime)`,
> > > > `__kmpc_kernel_deinit(int16_t IsOMPRuntimeInitialized)`,
> > > > `__kmpc_spmd_kernel_init(kmp_int32 thread_limit, int16_t 
> > > > RequiresOMPRuntime, int16_t RequiresDataSharing)`,
> > > > `__kmpc_kernel_parallel(void **outlined_function, int16_t 
> > > > IsOMPRuntimeInitialized)`,
> > > > ...
> > > > 
> > > > 
> > > > 
> > > > > Plus, this parameter is used for OMPD/OMPT and it may be important 
> > > > > for future OMPD/OMPT support.
> > > > 
> > > > If we at some point need to make the options permanent in an 
> > > > `ident_loc` we can simply pass an `ident_loc` and require it to be 
> > > > initialized by the call. Cluttering the user code with stores and 
> > > > indirection is exactly what I do want to avoid.
> > > 1. The new functions rely on `ident_loc`. We had to add those new 
> > > functions because the old ones did not use it and it was bad design 
> > > decision. Now we need to fix this. I suggest you do everything right from 
> > > the very beginning rather than fixing this later by adding extra entry 
> > > points to support OMPT/OMPD or something else, for example.
> > > 2. No, you cannot simply change the interface of the library to keep the 
> > > compatibility with the previous versions of the compiler/library. You 
> > > will need to add the new entries.  
> > Let's start this one again because I still haven't understood. Why do we 
> > need to populate the `ident_loc` again? What information has to be in there 
> > at which point? I want this to be clear because a lot of other "design 
> > decisions" of the existing code base are in my opinion not necessary and 
> > consequently missing here. That includes, for example, various global 
> > variables. If we have a description of the problem you try to solve with 
> > the `ident_loc` we might be able to find a way that cuts down on state.
> > 
> > 
> > Regarding the "compatibility", this is not a stable interface people can 
> > rely on. Whatever is committed in this first patch __is not__ set in stone. 
> > Also, we can _always_ add a `__kmpc_init_ident_loc()` function after 
> > the fact.
> Ident_loc holds the data about current source code location, execution mode 
> and is full runtime required or not. Also, it is used in OMPT/OMPD support.
> Regarding "compatibility" libraries must be most stable part of the compiler, 
> because the user migbt need to link the old object file/library with the new 
> one. Because of this the new versions of libraries must be compatible with 
> old ones. And you need to maintain the deprecated parts to keep the 
> compatibility with the previous versions. All these libs already have a lot 
> of old code that because of the initial poor design and we need to maintain 
> them. I would like to avoid this situation with this patch.
> Ident_loc holds the data about current source code location, execution mode 
> and is full runtime required or not. Also, it is used in OMPT/OMPD support.

We can store that information through a `__kmpc_init_ident_loc()` call once 
needed.


> Regarding "compatibility" libraries must be most stable part of the compiler, 
> because the user migbt need to link the old object file/library with the new 
> one. Because of this the new versions of libraries must be compatible with 
> old ones. And you need to maintain the deprecated parts to keep the 
> compatibility with the previous 

[PATCH] D59387: Make getFullyQualifiedName qualify both the pointee and class type for member ptr types

2019-03-14 Thread Sterling Augustine via Phabricator via cfe-commits
saugustine accepted this revision.
saugustine added a comment.
This revision is now accepted and ready to land.

This looks correct to me, thanks for the fix.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D59387



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


r356208 - Reland the rest of "Add AIX Target Info"

2019-03-14 Thread Jason Liu via cfe-commits
Author: jasonliu
Date: Thu Mar 14 14:54:30 2019
New Revision: 356208

URL: http://llvm.org/viewvc/llvm-project?rev=356208=rev
Log:
Reland the rest of "Add AIX Target Info"

llvm-svn 356197 relanded previously failing test case max_align.c.
This commit will reland the rest of llvm-svn 356060 commit.

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

Added:
cfe/trunk/test/Sema/varargs-aix.c
Modified:
cfe/trunk/lib/Basic/Targets.cpp
cfe/trunk/lib/Basic/Targets/OSTargets.h
cfe/trunk/lib/Basic/Targets/PPC.cpp
cfe/trunk/lib/Basic/Targets/PPC.h
cfe/trunk/test/Driver/types.c
cfe/trunk/test/Preprocessor/init.c

Modified: cfe/trunk/lib/Basic/Targets.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Basic/Targets.cpp?rev=356208=356207=356208=diff
==
--- cfe/trunk/lib/Basic/Targets.cpp (original)
+++ cfe/trunk/lib/Basic/Targets.cpp Thu Mar 14 14:54:30 2019
@@ -332,6 +332,8 @@ TargetInfo *AllocateTarget(const llvm::T
   return new OpenBSDTargetInfo(Triple, Opts);
 case llvm::Triple::RTEMS:
   return new RTEMSTargetInfo(Triple, Opts);
+case llvm::Triple::AIX:
+  return new AIXPPC32TargetInfo(Triple, Opts);
 default:
   return new PPC32TargetInfo(Triple, Opts);
 }
@@ -348,6 +350,8 @@ TargetInfo *AllocateTarget(const llvm::T
   return new FreeBSDTargetInfo(Triple, Opts);
 case llvm::Triple::NetBSD:
   return new NetBSDTargetInfo(Triple, Opts);
+case llvm::Triple::AIX:
+  return new AIXPPC64TargetInfo(Triple, Opts);
 default:
   return new PPC64TargetInfo(Triple, Opts);
 }

Modified: cfe/trunk/lib/Basic/Targets/OSTargets.h
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Basic/Targets/OSTargets.h?rev=356208=356207=356208=diff
==
--- cfe/trunk/lib/Basic/Targets/OSTargets.h (original)
+++ cfe/trunk/lib/Basic/Targets/OSTargets.h Thu Mar 14 14:54:30 2019
@@ -613,6 +613,53 @@ public:
   }
 };
 
+// AIX Target
+template 
+class AIXTargetInfo : public OSTargetInfo {
+protected:
+  void getOSDefines(const LangOptions , const llvm::Triple ,
+MacroBuilder ) const override {
+DefineStd(Builder, "unix", Opts);
+Builder.defineMacro("_IBMR2");
+Builder.defineMacro("_POWER");
+
+// FIXME: Define AIX OS-Version Macros.
+Builder.defineMacro("_AIX");
+
+// FIXME: Do not define _LONG_LONG when -fno-long-long is specified.
+Builder.defineMacro("_LONG_LONG");
+
+if (Opts.POSIXThreads) {
+  Builder.defineMacro("_THREAD_SAFE");
+}
+
+if (this->PointerWidth == 64) {
+  Builder.defineMacro("__64BIT__");
+}
+
+// Define _WCHAR_T when it is a fundamental type
+// (i.e., for C++ without -fno-wchar).
+if (Opts.CPlusPlus && Opts.WChar) {
+  Builder.defineMacro("_WCHAR_T");
+}
+  }
+
+public:
+  AIXTargetInfo(const llvm::Triple , const TargetOptions )
+  : OSTargetInfo(Triple, Opts) {
+if (this->PointerWidth == 64) {
+  this->WCharType = this->UnsignedInt;
+} else {
+  this->WCharType = this->UnsignedShort;
+}
+this->UseZeroLengthBitfieldAlignment = true;
+  }
+
+  // AIX sets FLT_EVAL_METHOD to be 1.
+  unsigned getFloatEvalMethod() const override { return 1; }
+  bool hasInt128Type() const override { return false; }
+};
+
 // Windows target
 template 
 class LLVM_LIBRARY_VISIBILITY WindowsTargetInfo : public OSTargetInfo {

Modified: cfe/trunk/lib/Basic/Targets/PPC.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Basic/Targets/PPC.cpp?rev=356208=356207=356208=diff
==
--- cfe/trunk/lib/Basic/Targets/PPC.cpp (original)
+++ cfe/trunk/lib/Basic/Targets/PPC.cpp Thu Mar 14 14:54:30 2019
@@ -100,7 +100,9 @@ void PPCTargetInfo::getTargetDefines(con
 Builder.defineMacro("_CALL_LINUX", "1");
 
   // Subtarget options.
-  Builder.defineMacro("__NATURAL_ALIGNMENT__");
+  if (!getTriple().isOSAIX()){
+Builder.defineMacro("__NATURAL_ALIGNMENT__");
+  }
   Builder.defineMacro("__REGISTER_PREFIX__", "");
 
   // FIXME: Should be controlled by command line option.

Modified: cfe/trunk/lib/Basic/Targets/PPC.h
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Basic/Targets/PPC.h?rev=356208=356207=356208=diff
==
--- cfe/trunk/lib/Basic/Targets/PPC.h (original)
+++ cfe/trunk/lib/Basic/Targets/PPC.h Thu Mar 14 14:54:30 2019
@@ -325,6 +325,12 @@ public:
   PtrDiffType = SignedInt;
   IntPtrType = SignedInt;
   break;
+case llvm::Triple::AIX:
+  SizeType = UnsignedLong;
+  PtrDiffType = SignedLong;
+  IntPtrType = SignedLong;
+  SuitableAlign = 64;
+  break;
 default:
   break;
 }
@@ -333,6 +339,8 @@ public:
 case llvm::Triple::FreeBSD:
 case llvm::Triple::NetBSD:
  

[PATCH] D59388: Basic: Return a reference from FileManager::getVirtualFileSystem, NFC

2019-03-14 Thread Duncan P. N. Exon Smith via Phabricator via cfe-commits
dexonsmith created this revision.
dexonsmith added reviewers: arphaman, Bigcheese, bruno.
Herald added subscribers: jdoerfert, kadircet, jkorous, ioeric.
Herald added a reviewer: martong.
Herald added a reviewer: shafik.

FileManager constructs a VFS in its constructor if it isn't passed one,
and there's no way to reset it.  Make that contract clear by returning a
reference from its accessor.


https://reviews.llvm.org/D59388

Files:
  clang-tools-extra/clang-move/ClangMove.cpp
  clang-tools-extra/clang-tidy/ClangTidy.cpp
  clang-tools-extra/clangd/SourceCode.cpp
  clang/include/clang/Basic/FileManager.h
  clang/include/clang/Frontend/CompilerInstance.h
  clang/lib/Frontend/ASTUnit.cpp
  clang/lib/Frontend/CompilerInstance.cpp
  clang/lib/Frontend/FrontendAction.cpp
  clang/lib/Lex/HeaderSearch.cpp
  clang/lib/Lex/ModuleMap.cpp
  clang/lib/Lex/PPLexerChange.cpp
  clang/lib/Sema/SemaCodeComplete.cpp
  clang/lib/Tooling/Tooling.cpp
  clang/unittests/AST/ASTImporterTest.cpp

Index: clang/unittests/AST/ASTImporterTest.cpp
===
--- clang/unittests/AST/ASTImporterTest.cpp
+++ clang/unittests/AST/ASTImporterTest.cpp
@@ -44,7 +44,7 @@
   assert(ToAST);
   ASTContext  = ToAST->getASTContext();
   auto *OFS = static_cast(
-  ToCtx.getSourceManager().getFileManager().getVirtualFileSystem().get());
+  ().getFileManager().getVirtualFileSystem());
   auto *MFS = static_cast(
   OFS->overlays_begin()->get());
   MFS->addFile(FileName, 0, std::move(Buffer));
Index: clang/lib/Tooling/Tooling.cpp
===
--- clang/lib/Tooling/Tooling.cpp
+++ clang/lib/Tooling/Tooling.cpp
@@ -301,7 +301,7 @@
   DiagConsumer ? DiagConsumer : , false);
 
   const std::unique_ptr Driver(
-  newDriver(, BinaryName, Files->getVirtualFileSystem()));
+  newDriver(, BinaryName, >getVirtualFileSystem()));
   // The "input file not found" diagnostics from the driver are useful.
   // The driver is only aware of the VFS working directory, but some clients
   // change this at the FileManager level instead.
Index: clang/lib/Sema/SemaCodeComplete.cpp
===
--- clang/lib/Sema/SemaCodeComplete.cpp
+++ clang/lib/Sema/SemaCodeComplete.cpp
@@ -8378,7 +8378,8 @@
   // We need the native slashes for the actual file system interactions.
   SmallString<128> NativeRelDir = StringRef(RelDir);
   llvm::sys::path::native(NativeRelDir);
-  auto FS = getSourceManager().getFileManager().getVirtualFileSystem();
+  llvm::vfs::FileSystem  =
+  getSourceManager().getFileManager().getVirtualFileSystem();
 
   ResultBuilder Results(*this, CodeCompleter->getAllocator(),
 CodeCompleter->getCodeCompletionTUInfo(),
@@ -8424,7 +8425,7 @@
 
 std::error_code EC;
 unsigned Count = 0;
-for (auto It = FS->dir_begin(Dir, EC);
+for (auto It = FS.dir_begin(Dir, EC);
  !EC && It != llvm::vfs::directory_iterator(); It.increment(EC)) {
   if (++Count == 2500) // If we happen to hit a huge directory,
 break; // bail out early so we're not too slow.
Index: clang/lib/Lex/PPLexerChange.cpp
===
--- clang/lib/Lex/PPLexerChange.cpp
+++ clang/lib/Lex/PPLexerChange.cpp
@@ -270,7 +270,7 @@
 
   ModuleMap  = getHeaderSearchInfo().getModuleMap();
   const DirectoryEntry *Dir = Mod.getUmbrellaDir().Entry;
-  llvm::vfs::FileSystem  = *FileMgr.getVirtualFileSystem();
+  llvm::vfs::FileSystem  = FileMgr.getVirtualFileSystem();
   std::error_code EC;
   for (llvm::vfs::recursive_directory_iterator Entry(FS, Dir->getName(), EC),
End;
Index: clang/lib/Lex/ModuleMap.cpp
===
--- clang/lib/Lex/ModuleMap.cpp
+++ clang/lib/Lex/ModuleMap.cpp
@@ -1021,7 +1021,7 @@
 = StringRef(FrameworkDir->getName());
   llvm::sys::path::append(SubframeworksDirName, "Frameworks");
   llvm::sys::path::native(SubframeworksDirName);
-  llvm::vfs::FileSystem  = *FileMgr.getVirtualFileSystem();
+  llvm::vfs::FileSystem  = FileMgr.getVirtualFileSystem();
   for (llvm::vfs::directory_iterator
Dir = FS.dir_begin(SubframeworksDirName, EC),
DirEnd;
@@ -2397,7 +2397,7 @@
 std::error_code EC;
 SmallVector Headers;
 llvm::vfs::FileSystem  =
-*SourceMgr.getFileManager().getVirtualFileSystem();
+SourceMgr.getFileManager().getVirtualFileSystem();
 for (llvm::vfs::recursive_directory_iterator I(FS, Dir->getName(), EC), E;
  I != E && !EC; I.increment(EC)) {
   if (const FileEntry *FE = SourceMgr.getFileManager().getFile(I->path())) {
Index: clang/lib/Lex/HeaderSearch.cpp
===
--- clang/lib/Lex/HeaderSearch.cpp
+++ clang/lib/Lex/HeaderSearch.cpp
@@ -1579,7 +1579,7 @@
 

[PATCH] D59319: [OpenMP][Offloading][1/3] A generic and simple target region interface

2019-03-14 Thread Alexey Bataev via Phabricator via cfe-commits
ABataev added inline comments.



Comment at: openmp/libomptarget/deviceRTLs/common/target_region.h:27
+
+/// The target region _kernel_ interface for GPUs
+///

jdoerfert wrote:
> ABataev wrote:
> > jdoerfert wrote:
> > > ABataev wrote:
> > > > jdoerfert wrote:
> > > > > ABataev wrote:
> > > > > > All exported functions are declared in the `interface.h` file. I 
> > > > > > don't think we need an extra interface file here
> > > > > `interface.h`, or to be more precise for people that do not know, 
> > > > > `deviceRTLs/nvptx/src/interface.h`, is nvptx specific. This file, 
> > > > > `deviceRTLs/common/target_region.h`, is by design target agnostic and 
> > > > > not placed _under_ the nvptx subfolder. If you are willing to move 
> > > > > `interface.h` into a common space and remove the nvptx specific 
> > > > > functions we can merge the two. Otherwise, I have strong reservations 
> > > > > agains that and good reason not to do it.
> > > > I see that currently it is written in Cuda. It means, it targets NVidia 
> > > > GPUs, at least at the moment. I'm fine to put this header file into the 
> > > > common directory, if you're sure that this is really target agnostic. 
> > > > But maybe just for a start we should put it to NVPTX directory? Later, 
> > > > when you or somebody else will add support for other GPUs and he/she 
> > > > will find out that these functions are really target agnostic, they can 
> > > > be moved into the common directory?
> > > > I see that currently it is written in Cuda. It means, it targets NVidia 
> > > > GPUs, at least at the moment
> > > 
> > > How do you see that? (I hope we both talk about this file, correct?)
> > > 
> > > 
> > > > But maybe just for a start we should put it to NVPTX directory?
> > > 
> > > Why? What is the benefit? If we want it to be agnostic, regardless of the 
> > > current state, it should be developed _outside_ of the target specific 
> > > directories.
> > > 
> > I'm not talking about this particular file, just like I said we can put it 
> > into `common` subdirectory. I'm talking about the implementation files. 
> > They all are written in Cuda, no?
> > But it is not proved yet that this solution is target agnostic. Did you 
> > test it for AMD?
> > I'm not talking about this particular file, just like I said we can put it 
> > into common subdirectory.
> 
> OK. It is (the only file in the common folder for now).
> 
> 
> > I'm talking about the implementation files. They all are written in Cuda, 
> > no?
> 
> Yes, Cuda, and placed under the nvptx folder for that reason. That is what 
> you want, correct?
> 
> 
> > But it is not proved yet that this solution is target agnostic. Did you 
> > test it for AMD?
> 
> What do you mean by solution? I do not have a second implementation of the 
> interface but nothing up to the implementation of the interface is target 
> aware. By construction, this means it will work for anything we can implement 
> the interface in. 
> 
> Why do you fight so hard against this? What exactly do you want to change 
> here? Given the last comment, and assuming I understand you correctly, the 
> files are all exactly where you want them to be. That the wording sometimes 
> states "target agnostic" is a sign of intent, even if for some currently 
> unknown reason it would not hold true.
> 
> 
I'm trying to understand what is the best layout for your solution. 



Comment at: openmp/libomptarget/deviceRTLs/common/target_region.h:100
+///
+EXTERN int8_t __kmpc_target_region_kernel_init(bool UseSPMDMode,
+   bool RequiresOMPRuntime,

jdoerfert wrote:
> ABataev wrote:
> > jdoerfert wrote:
> > > ABataev wrote:
> > > > jdoerfert wrote:
> > > > > ABataev wrote:
> > > > > > Better to use `ident_loc` for passing info about execution mode and 
> > > > > > full/lightweight runtime.
> > > > > Could you please explain why you think that? Adding indirection 
> > > > > through a structure does not really seem beneficial to me.
> > > > Almost all function from libomp rely on `ident_loc`. The functions, 
> > > > which were added for NVPTX without this parameter had a lot of problems 
> > > > later and most of them were replaced with the functions with this 
> > > > parameter type. Plus, this parameter is used for OMPD/OMPT and it may 
> > > > be important for future OMPD/OMPT support.
> > > > Almost all function from libomp rely on ident_loc.
> > > 
> > > If you look at the implementation of this interface for NVPTX you will 
> > > see that the called functions do not take `ident_loc` values. When you 
> > > create the calls from the existing NVPTX code generation in clang, the 
> > > current code **does not use** `ident_loc` for similar functions, see:
> > > `___kmpc_kernel_init(kmp_int32 thread_limit, int16_t RequiresOMPRuntime)`,
> > > `__kmpc_kernel_deinit(int16_t IsOMPRuntimeInitialized)`,
> > > `__kmpc_spmd_kernel_init(kmp_int32 

[PATCH] D59387: Make getFullyQualifiedName qualify both the pointee and class type for member ptr types

2019-03-14 Thread Benjamin Kramer via Phabricator via cfe-commits
bkramer created this revision.
bkramer added reviewers: saugustine, ilya-biryukov.
Herald added a subscriber: jlebar.
Herald added a project: clang.

We already handle pointers and references, member ptrs are just another
special case. Fixes PR40732.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D59387

Files:
  clang/lib/AST/QualTypeNames.cpp
  clang/unittests/Tooling/QualTypeNamesTest.cpp


Index: clang/unittests/Tooling/QualTypeNamesTest.cpp
===
--- clang/unittests/Tooling/QualTypeNamesTest.cpp
+++ clang/unittests/Tooling/QualTypeNamesTest.cpp
@@ -194,6 +194,7 @@
   GlobalNsPrefix.ExpectedQualTypeNames["ZVal"] = "::A::B::Y::Z";
   GlobalNsPrefix.ExpectedQualTypeNames["GlobalZVal"] = "::Z";
   GlobalNsPrefix.ExpectedQualTypeNames["CheckK"] = "D::aStruct";
+  GlobalNsPrefix.ExpectedQualTypeNames["YZMPtr"] = "::A::B::X ::A::B::Y::Z::*";
   GlobalNsPrefix.runOver(
   "namespace A {\n"
   "  namespace B {\n"
@@ -205,8 +206,9 @@
   "template \n"
   "using Alias = CCC;\n"
   "Alias IntAliasVal;\n"
-  "struct Y { struct Z {}; };\n"
+  "struct Y { struct Z { X YZIPtr; }; };\n"
   "Y::Z ZVal;\n"
+  "X Y::Z::*YZMPtr;\n"
   "  }\n"
   "}\n"
   "struct Z {};\n"
Index: clang/lib/AST/QualTypeNames.cpp
===
--- clang/lib/AST/QualTypeNames.cpp
+++ clang/lib/AST/QualTypeNames.cpp
@@ -379,6 +379,19 @@
 return QT;
   }
 
+  if (auto *MemberPT = dyn_cast(QT.getTypePtr())) {
+// Get the qualifiers.
+Qualifiers Quals = QT.getQualifiers();
+// Fully qualify the pointee and class types.
+QT = getFullyQualifiedType(QT->getPointeeType(), Ctx, WithGlobalNsPrefix);
+QualType Class = getFullyQualifiedType(QualType(MemberPT->getClass(), 0),
+   Ctx, WithGlobalNsPrefix);
+QT = Ctx.getMemberPointerType(QT, Class.getTypePtr());
+// Add back the qualifiers.
+QT = Ctx.getQualifiedType(QT, Quals);
+return QT;
+  }
+
   // In case of myType& we need to strip the reference first, fully
   // qualify and attach the reference once again.
   if (isa(QT.getTypePtr())) {


Index: clang/unittests/Tooling/QualTypeNamesTest.cpp
===
--- clang/unittests/Tooling/QualTypeNamesTest.cpp
+++ clang/unittests/Tooling/QualTypeNamesTest.cpp
@@ -194,6 +194,7 @@
   GlobalNsPrefix.ExpectedQualTypeNames["ZVal"] = "::A::B::Y::Z";
   GlobalNsPrefix.ExpectedQualTypeNames["GlobalZVal"] = "::Z";
   GlobalNsPrefix.ExpectedQualTypeNames["CheckK"] = "D::aStruct";
+  GlobalNsPrefix.ExpectedQualTypeNames["YZMPtr"] = "::A::B::X ::A::B::Y::Z::*";
   GlobalNsPrefix.runOver(
   "namespace A {\n"
   "  namespace B {\n"
@@ -205,8 +206,9 @@
   "template \n"
   "using Alias = CCC;\n"
   "Alias IntAliasVal;\n"
-  "struct Y { struct Z {}; };\n"
+  "struct Y { struct Z { X YZIPtr; }; };\n"
   "Y::Z ZVal;\n"
+  "X Y::Z::*YZMPtr;\n"
   "  }\n"
   "}\n"
   "struct Z {};\n"
Index: clang/lib/AST/QualTypeNames.cpp
===
--- clang/lib/AST/QualTypeNames.cpp
+++ clang/lib/AST/QualTypeNames.cpp
@@ -379,6 +379,19 @@
 return QT;
   }
 
+  if (auto *MemberPT = dyn_cast(QT.getTypePtr())) {
+// Get the qualifiers.
+Qualifiers Quals = QT.getQualifiers();
+// Fully qualify the pointee and class types.
+QT = getFullyQualifiedType(QT->getPointeeType(), Ctx, WithGlobalNsPrefix);
+QualType Class = getFullyQualifiedType(QualType(MemberPT->getClass(), 0),
+   Ctx, WithGlobalNsPrefix);
+QT = Ctx.getMemberPointerType(QT, Class.getTypePtr());
+// Add back the qualifiers.
+QT = Ctx.getQualifiedType(QT, Quals);
+return QT;
+  }
+
   // In case of myType& we need to strip the reference first, fully
   // qualify and attach the reference once again.
   if (isa(QT.getTypePtr())) {
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D59377: Frontend: Remove CompilerInstance::VirtualFileSystem, NFC

2019-03-14 Thread Duncan P. N. Exon Smith via Phabricator via cfe-commits
dexonsmith updated this revision to Diff 190726.
dexonsmith added a comment.

I slightly simplified the code for CompilerInstance::createFileManager 
(replaced with an `assert`), since I noticed that FileManager always constructs 
its own VFS if it isn't passed one.


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

https://reviews.llvm.org/D59377

Files:
  clang-tools-extra/clangd/Compiler.cpp
  clang/include/clang/Frontend/CompilerInstance.h
  clang/lib/Frontend/ASTUnit.cpp
  clang/lib/Frontend/CompilerInstance.cpp
  clang/lib/StaticAnalyzer/Frontend/ModelInjector.cpp
  lldb/source/Plugins/ExpressionParser/Clang/ClangExpressionParser.cpp
  lldb/source/Plugins/ExpressionParser/Clang/ClangModulesDeclVendor.cpp

Index: lldb/source/Plugins/ExpressionParser/Clang/ClangModulesDeclVendor.cpp
===
--- lldb/source/Plugins/ExpressionParser/Clang/ClangModulesDeclVendor.cpp
+++ lldb/source/Plugins/ExpressionParser/Clang/ClangModulesDeclVendor.cpp
@@ -671,7 +671,7 @@
   }
 
   // Make sure clang uses the same VFS as LLDB.
-  instance->setVirtualFileSystem(FileSystem::Instance().GetVirtualFileSystem());
+  instance->createFileManager(FileSystem::Instance().GetVirtualFileSystem());
   instance->setDiagnostics(diagnostics_engine.get());
   instance->setInvocation(invocation);
 
Index: lldb/source/Plugins/ExpressionParser/Clang/ClangExpressionParser.cpp
===
--- lldb/source/Plugins/ExpressionParser/Clang/ClangExpressionParser.cpp
+++ lldb/source/Plugins/ExpressionParser/Clang/ClangExpressionParser.cpp
@@ -309,8 +309,7 @@
   }
 
   // Make sure clang uses the same VFS as LLDB.
-  m_compiler->setVirtualFileSystem(
-  FileSystem::Instance().GetVirtualFileSystem());
+  m_compiler->createFileManager(FileSystem::Instance().GetVirtualFileSystem());
 
   lldb::LanguageType frame_lang =
   expr.Language(); // defaults to lldb::eLanguageTypeUnknown
Index: clang/lib/StaticAnalyzer/Frontend/ModelInjector.cpp
===
--- clang/lib/StaticAnalyzer/Frontend/ModelInjector.cpp
+++ clang/lib/StaticAnalyzer/Frontend/ModelInjector.cpp
@@ -82,8 +82,6 @@
 
   Instance.getDiagnostics().setSourceManager();
 
-  Instance.setVirtualFileSystem(());
-
   // The instance wants to take ownership, however DisableFree frontend option
   // is set to true to avoid double free issues
   Instance.setFileManager(());
Index: clang/lib/Frontend/CompilerInstance.cpp
===
--- clang/lib/Frontend/CompilerInstance.cpp
+++ clang/lib/Frontend/CompilerInstance.cpp
@@ -89,10 +89,6 @@
 
 void CompilerInstance::setFileManager(FileManager *Value) {
   FileMgr = Value;
-  if (Value)
-VirtualFileSystem = Value->getVirtualFileSystem();
-  else
-VirtualFileSystem.reset();
 }
 
 void CompilerInstance::setSourceManager(SourceManager *Value) {
@@ -297,13 +293,14 @@
 
 // File Manager
 
-FileManager *CompilerInstance::createFileManager() {
-  if (!hasVirtualFileSystem()) {
-IntrusiveRefCntPtr VFS =
-createVFSFromCompilerInvocation(getInvocation(), getDiagnostics());
-setVirtualFileSystem(VFS);
-  }
-  FileMgr = new FileManager(getFileSystemOpts(), VirtualFileSystem);
+FileManager *CompilerInstance::createFileManager(
+IntrusiveRefCntPtr VFS) {
+  if (!VFS)
+VFS = FileMgr ? FileMgr->getVirtualFileSystem()
+  : createVFSFromCompilerInvocation(getInvocation(),
+getDiagnostics());
+  assert(VFS && "FileManager has no VFS?");
+  FileMgr = new FileManager(getFileSystemOpts(), std::move(VFS));
   return FileMgr.get();
 }
 
@@ -1101,8 +1098,6 @@
ImportingInstance.getDiagnosticClient()),
  /*ShouldOwnClient=*/true);
 
-  Instance.setVirtualFileSystem(());
-
   // Note that this module is part of the module build stack, so that we
   // can detect cycles in the module graph.
   Instance.setFileManager(());
Index: clang/lib/Frontend/ASTUnit.cpp
===
--- clang/lib/Frontend/ASTUnit.cpp
+++ clang/lib/Frontend/ASTUnit.cpp
@@ -1078,28 +1078,29 @@
   if (!Invocation)
 return true;
 
+  if (VFS && FileMgr)
+assert(VFS == FileMgr->getVirtualFileSystem() &&
+   "VFS passed to Parse and VFS in FileMgr are different");
+
   auto CCInvocation = std::make_shared(*Invocation);
   if (OverrideMainBuffer) {
 assert(Preamble &&
"No preamble was built, but OverrideMainBuffer is not null");
-IntrusiveRefCntPtr OldVFS = VFS;
 Preamble->AddImplicitPreamble(*CCInvocation, VFS, OverrideMainBuffer.get());
-if (OldVFS != VFS && FileMgr) {
-  assert(OldVFS == FileMgr->getVirtualFileSystem() &&
- "VFS passed to Parse and VFS in FileMgr are different");
-  

[PATCH] D59076: [coroutines][PR40978] Emit error for co_yield within catch block

2019-03-14 Thread Brian Gesiak via Phabricator via cfe-commits
modocache updated this revision to Diff 190727.
modocache added a comment.

Remove unused function parameter.


Repository:
  rC Clang

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

https://reviews.llvm.org/D59076

Files:
  include/clang/Basic/DiagnosticSemaKinds.td
  include/clang/Sema/Scope.h
  lib/Parse/ParseStmt.cpp
  lib/Sema/Scope.cpp
  lib/Sema/SemaCoroutine.cpp
  test/SemaCXX/coroutines.cpp

Index: test/SemaCXX/coroutines.cpp
===
--- test/SemaCXX/coroutines.cpp
+++ test/SemaCXX/coroutines.cpp
@@ -328,6 +328,47 @@
 // not allowed. A user may not understand that this is "outside a function."
 void default_argument(int arg = co_await 0) {} // expected-error {{'co_await' cannot be used outside a function}}
 
+void await_in_catch_coroutine() {
+  try { // Expect a note diagnostic here.
+  } catch (...) {
+[]() -> void { co_await a; }(); // OK
+co_await a; // expected-error {{'co_await' cannot be used in the handler of a try block}}
+  }
+}
+
+void await_nested_in_catch_coroutine() {
+  try { // Expect a note diagnostic here.
+  } catch (...) {
+try {
+  co_await a; // expected-error {{'co_await' cannot be used in the handler of a try block}}
+  []() -> void { co_await a; }(); // OK
+} catch (...) {
+  co_return 123;
+}
+  }
+}
+
+void await_in_lambda_in_catch_coroutine() {
+  try {
+  } catch (...) {
+[]() -> void { co_await a; }(); // OK
+  }
+}
+
+void yield_in_catch_coroutine() {
+  try {
+  } catch (...) {
+co_yield a; // expected-error {{'co_yield' cannot be used in the handler of a try block}}
+  }
+}
+
+void return_in_catch_coroutine() {
+  try {
+  } catch (...) {
+co_return 123; // OK
+  }
+}
+
 constexpr auto constexpr_deduced_return_coroutine() {
   co_yield 0; // expected-error {{'co_yield' cannot be used in a constexpr function}}
   // expected-error@-1 {{'co_yield' cannot be used in a function with a deduced return type}}
Index: lib/Sema/SemaCoroutine.cpp
===
--- lib/Sema/SemaCoroutine.cpp
+++ lib/Sema/SemaCoroutine.cpp
@@ -185,21 +185,8 @@
 
 static bool isValidCoroutineContext(Sema , SourceLocation Loc,
 StringRef Keyword) {
-  // 'co_await' and 'co_yield' are not permitted in unevaluated operands,
-  // such as subexpressions of \c sizeof.
-  //
-  // [expr.await]p2, emphasis added: "An await-expression shall appear only in
-  // a *potentially evaluated* expression within the compound-statement of a
-  // function-body outside of a handler [...] A context within a function where
-  // an await-expression can appear is called a suspension context of the
-  // function." And per [expr.yield]p1: "A yield-expression shall appear only
-  // within a suspension context of a function."
-  if (S.isUnevaluatedContext()) {
-S.Diag(Loc, diag::err_coroutine_unevaluated_context) << Keyword;
-return false;
-  }
-
-  // Per [expr.await]p2, any other usage must be within a function.
+  // [expr.await]p2 dictates that 'co_await' and 'co_yield' must be used within
+  // a function body.
   // FIXME: This also covers [expr.await]p2: "An await-expression shall not
   // appear in a default argument." But the diagnostic QoI here could be
   // improved to inform the user that default arguments specifically are not
@@ -668,8 +655,58 @@
   return true;
 }
 
+// Recursively walks up the scope hierarchy until either a 'catch' or a function
+// scope is found, whichever comes first.
+static bool isWithinCatchScope(Scope *S) {
+  // 'co_await' and 'co_yield' keywords are disallowed within catch blocks, but
+  // lambdas that use 'co_await' are allowed. The loop below ends when a
+  // function scope is found in order to ensure the following behavior:
+  //
+  // void foo() {  // <- function scope
+  //   try {   //
+  // co_await x;   // <- 'co_await' is OK within a function scope
+  //   } catch {   // <- catch scope
+  // co_await x;   // <- 'co_await' is not OK within a catch scope
+  // []() {// <- function scope
+  //   co_await x; // <- 'co_await' is OK within a function scope
+  // }();
+  //   }
+  // }
+  while (S && !(S->getFlags() & Scope::FnScope)) {
+if (S->getFlags() & Scope::CatchScope)
+  return true;
+S = S->getParent();
+  }
+  return false;
+}
+
+// [expr.await]p2, emphasis added: "An await-expression shall appear only in
+// a *potentially evaluated* expression within the compound-statement of a
+// function-body *outside of a handler* [...] A context within a function
+// where an await-expression can appear is called a suspension context of the
+// function."
+static bool isValidSuspensionContext(Sema , SourceLocation Loc,
+ StringRef Keyword) {
+  // First emphasis of [expr.await]p2: must be a potentially evaluated context.
+  // That is, 'co_await' and 'co_yield' 

[PATCH] D59076: [coroutines][PR40978] Emit error for co_yield within catch block

2019-03-14 Thread Brian Gesiak via Phabricator via cfe-commits
modocache updated this revision to Diff 190718.
modocache added a comment.

Thank you for the reviews! This revision fixes the nested try/catch behavior. I 
still need to modify this such that semantic analysis continues for the rest of 
the function body.


Repository:
  rC Clang

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

https://reviews.llvm.org/D59076

Files:
  include/clang/Basic/DiagnosticSemaKinds.td
  include/clang/Sema/Scope.h
  lib/Parse/ParseStmt.cpp
  lib/Sema/Scope.cpp
  lib/Sema/SemaCoroutine.cpp
  test/SemaCXX/coroutines.cpp

Index: test/SemaCXX/coroutines.cpp
===
--- test/SemaCXX/coroutines.cpp
+++ test/SemaCXX/coroutines.cpp
@@ -328,6 +328,47 @@
 // not allowed. A user may not understand that this is "outside a function."
 void default_argument(int arg = co_await 0) {} // expected-error {{'co_await' cannot be used outside a function}}
 
+void await_in_catch_coroutine() {
+  try { // Expect a note diagnostic here.
+  } catch (...) {
+[]() -> void { co_await a; }(); // OK
+co_await a; // expected-error {{'co_await' cannot be used in the handler of a try block}}
+  }
+}
+
+void await_nested_in_catch_coroutine() {
+  try { // Expect a note diagnostic here.
+  } catch (...) {
+try {
+  co_await a; // expected-error {{'co_await' cannot be used in the handler of a try block}}
+  []() -> void { co_await a; }(); // OK
+} catch (...) {
+  co_return 123;
+}
+  }
+}
+
+void await_in_lambda_in_catch_coroutine() {
+  try {
+  } catch (...) {
+[]() -> void { co_await a; }(); // OK
+  }
+}
+
+void yield_in_catch_coroutine() {
+  try {
+  } catch (...) {
+co_yield a; // expected-error {{'co_yield' cannot be used in the handler of a try block}}
+  }
+}
+
+void return_in_catch_coroutine() {
+  try {
+  } catch (...) {
+co_return 123; // OK
+  }
+}
+
 constexpr auto constexpr_deduced_return_coroutine() {
   co_yield 0; // expected-error {{'co_yield' cannot be used in a constexpr function}}
   // expected-error@-1 {{'co_yield' cannot be used in a function with a deduced return type}}
Index: lib/Sema/SemaCoroutine.cpp
===
--- lib/Sema/SemaCoroutine.cpp
+++ lib/Sema/SemaCoroutine.cpp
@@ -185,21 +185,8 @@
 
 static bool isValidCoroutineContext(Sema , SourceLocation Loc,
 StringRef Keyword) {
-  // 'co_await' and 'co_yield' are not permitted in unevaluated operands,
-  // such as subexpressions of \c sizeof.
-  //
-  // [expr.await]p2, emphasis added: "An await-expression shall appear only in
-  // a *potentially evaluated* expression within the compound-statement of a
-  // function-body outside of a handler [...] A context within a function where
-  // an await-expression can appear is called a suspension context of the
-  // function." And per [expr.yield]p1: "A yield-expression shall appear only
-  // within a suspension context of a function."
-  if (S.isUnevaluatedContext()) {
-S.Diag(Loc, diag::err_coroutine_unevaluated_context) << Keyword;
-return false;
-  }
-
-  // Per [expr.await]p2, any other usage must be within a function.
+  // [expr.await]p2 dictates that 'co_await' and 'co_yield' must be used within
+  // a function body.
   // FIXME: This also covers [expr.await]p2: "An await-expression shall not
   // appear in a default argument." But the diagnostic QoI here could be
   // improved to inform the user that default arguments specifically are not
@@ -668,8 +655,59 @@
   return true;
 }
 
+// Recursively walks up the scope hierarchy until either a 'catch' or a function
+// scope is found, whichever comes first.
+static bool isWithinCatchScope(Scope *S) {
+  // 'co_await' and 'co_yield' keywords are disallowed within catch blocks, but
+  // lambdas that use 'co_await' are allowed. The loop below ends when a
+  // function scope is found in order to ensure the following behavior:
+  //
+  // void foo() {  // <- function scope
+  //   try {   //
+  // co_await x;   // <- 'co_await' is OK within a function scope
+  //   } catch {   // <- catch scope
+  // co_await x;   // <- 'co_await' is not OK within a catch scope
+  // []() {// <- function scope
+  //   co_await x; // <- 'co_await' is OK within a function scope
+  // }();
+  //   }
+  // }
+  while (S && !(S->getFlags() & Scope::FnScope)) {
+if (S->getFlags() & Scope::CatchScope)
+  return true;
+S = S->getParent();
+  }
+  return false;
+}
+
+// [expr.await]p2, emphasis added: "An await-expression shall appear only in
+// a *potentially evaluated* expression within the compound-statement of a
+// function-body *outside of a handler* [...] A context within a function
+// where an await-expression can appear is called a suspension context of the
+// function."
+static bool isValidSuspensionContext(Sema , SourceLocation Loc,
+

[PATCH] D59319: [OpenMP][Offloading][1/3] A generic and simple target region interface

2019-03-14 Thread Johannes Doerfert via Phabricator via cfe-commits
jdoerfert updated this revision to Diff 190717.
jdoerfert marked 4 inline comments as done.
jdoerfert added a comment.

Replace more char* with void*


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D59319

Files:
  openmp/libomptarget/deviceRTLs/common/target_region.h
  openmp/libomptarget/deviceRTLs/nvptx/CMakeLists.txt
  openmp/libomptarget/deviceRTLs/nvptx/src/omp_data.cu
  openmp/libomptarget/deviceRTLs/nvptx/src/omptarget-nvptx.h
  openmp/libomptarget/deviceRTLs/nvptx/src/target_region.cu

Index: openmp/libomptarget/deviceRTLs/nvptx/src/target_region.cu
===
--- /dev/null
+++ openmp/libomptarget/deviceRTLs/nvptx/src/target_region.cu
@@ -0,0 +1,197 @@
+//===-- target_region.cu  CUDA impl. of the target region interface -*-===//
+//
+// 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
+//
+//===--===//
+//
+// This file contains the implementation of the common target region interface.
+//
+//===--===//
+
+// Include the native definitions first as certain defines might be needed in
+// the common interface definition below.
+#include "omptarget-nvptx.h"
+#include "interface.h"
+
+#include "../../common/target_region.h"
+
+/// The pointer used to share memory between team threads.
+extern __device__ __shared__ target_region_shared_buffer
+_target_region_shared_memory;
+
+EXTERN void *__kmpc_target_region_kernel_get_shared_memory() {
+  return _target_region_shared_memory.begin();
+}
+EXTERN void *__kmpc_target_region_kernel_get_private_memory() {
+  return _target_region_shared_memory.begin() +
+ _target_region_shared_memory.get_offset();
+}
+
+/// Simple generic state machine for worker threads.
+INLINE static void
+__kmpc_target_region_state_machine(bool IsOMPRuntimeInitialized) {
+
+  do {
+void *WorkFn = 0;
+
+// Wait for the signal that we have a new work function.
+__kmpc_barrier_simple_spmd(NULL, 0);
+
+// Retrieve the work function from the runtime.
+bool IsActive = __kmpc_kernel_parallel(, IsOMPRuntimeInitialized);
+
+// If there is nothing more to do, break out of the state machine by
+// returning to the caller.
+if (!WorkFn)
+  return;
+
+if (IsActive) {
+  void *SharedVars = __kmpc_target_region_kernel_get_shared_memory();
+  void *PrivateVars = __kmpc_target_region_kernel_get_private_memory();
+
+  ((ParallelWorkFnTy)WorkFn)(SharedVars, PrivateVars);
+
+  __kmpc_kernel_end_parallel();
+}
+
+__kmpc_barrier_simple_spmd(NULL, 0);
+
+  } while (true);
+}
+
+/// Filter threads into masters and workers. If \p UseStateMachine is true,
+/// required workers will enter a state machine through and be trapped there.
+/// Master and surplus worker threads will return from this function immediately
+/// while required workers will only return once there is no more work. The
+/// return value indicates if the thread is a master (1), a surplus worker (0),
+/// or a finished required worker released from the state machine (-1).
+INLINE static int8_t
+__kmpc_target_region_thread_filter(unsigned ThreadLimit, bool UseStateMachine,
+   bool IsOMPRuntimeInitialized) {
+
+  unsigned TId = GetThreadIdInBlock();
+  bool IsWorker = TId < ThreadLimit;
+
+  if (IsWorker) {
+if (UseStateMachine)
+  __kmpc_target_region_state_machine(IsOMPRuntimeInitialized);
+return -1;
+  }
+
+  return TId == GetMasterThreadID();
+}
+
+EXTERN int8_t __kmpc_target_region_kernel_init(bool UseSPMDMode,
+   bool UseStateMachine,
+   bool RequiresOMPRuntime,
+   bool RequiresDataSharing) {
+  unsigned NumThreads = GetNumberOfThreadsInBlock();
+
+  // Handle the SPMD case first.
+  if (UseSPMDMode) {
+
+__kmpc_spmd_kernel_init(NumThreads, RequiresOMPRuntime,
+RequiresDataSharing);
+
+if (RequiresDataSharing)
+  __kmpc_data_sharing_init_stack_spmd();
+
+return 1;
+  }
+
+  // Reserve one WARP in non-SPMD mode for the masters.
+  unsigned ThreadLimit = NumThreads - WARPSIZE;
+  int8_t FilterVal = __kmpc_target_region_thread_filter(
+  ThreadLimit, UseStateMachine, RequiresOMPRuntime);
+
+  // If the filter returns 1 the executing thread is a team master which will
+  // initialize the kernel in the following.
+  if (FilterVal == 1) {
+__kmpc_kernel_init(ThreadLimit, RequiresOMPRuntime);
+__kmpc_data_sharing_init_stack();
+_target_region_shared_memory.init();
+  }
+
+  return FilterVal;
+}
+
+EXTERN void 

[PATCH] D59319: [OpenMP][Offloading][1/3] A generic and simple target region interface

2019-03-14 Thread Johannes Doerfert via Phabricator via cfe-commits
jdoerfert marked 2 inline comments as done.
jdoerfert added inline comments.



Comment at: openmp/libomptarget/deviceRTLs/common/target_region.h:27
+
+/// The target region _kernel_ interface for GPUs
+///

ABataev wrote:
> jdoerfert wrote:
> > ABataev wrote:
> > > jdoerfert wrote:
> > > > ABataev wrote:
> > > > > All exported functions are declared in the `interface.h` file. I 
> > > > > don't think we need an extra interface file here
> > > > `interface.h`, or to be more precise for people that do not know, 
> > > > `deviceRTLs/nvptx/src/interface.h`, is nvptx specific. This file, 
> > > > `deviceRTLs/common/target_region.h`, is by design target agnostic and 
> > > > not placed _under_ the nvptx subfolder. If you are willing to move 
> > > > `interface.h` into a common space and remove the nvptx specific 
> > > > functions we can merge the two. Otherwise, I have strong reservations 
> > > > agains that and good reason not to do it.
> > > I see that currently it is written in Cuda. It means, it targets NVidia 
> > > GPUs, at least at the moment. I'm fine to put this header file into the 
> > > common directory, if you're sure that this is really target agnostic. But 
> > > maybe just for a start we should put it to NVPTX directory? Later, when 
> > > you or somebody else will add support for other GPUs and he/she will find 
> > > out that these functions are really target agnostic, they can be moved 
> > > into the common directory?
> > > I see that currently it is written in Cuda. It means, it targets NVidia 
> > > GPUs, at least at the moment
> > 
> > How do you see that? (I hope we both talk about this file, correct?)
> > 
> > 
> > > But maybe just for a start we should put it to NVPTX directory?
> > 
> > Why? What is the benefit? If we want it to be agnostic, regardless of the 
> > current state, it should be developed _outside_ of the target specific 
> > directories.
> > 
> I'm not talking about this particular file, just like I said we can put it 
> into `common` subdirectory. I'm talking about the implementation files. They 
> all are written in Cuda, no?
> But it is not proved yet that this solution is target agnostic. Did you test 
> it for AMD?
> I'm not talking about this particular file, just like I said we can put it 
> into common subdirectory.

OK. It is (the only file in the common folder for now).


> I'm talking about the implementation files. They all are written in Cuda, no?

Yes, Cuda, and placed under the nvptx folder for that reason. That is what you 
want, correct?


> But it is not proved yet that this solution is target agnostic. Did you test 
> it for AMD?

What do you mean by solution? I do not have a second implementation of the 
interface but nothing up to the implementation of the interface is target 
aware. By construction, this means it will work for anything we can implement 
the interface in. 

Why do you fight so hard against this? What exactly do you want to change here? 
Given the last comment, and assuming I understand you correctly, the files are 
all exactly where you want them to be. That the wording sometimes states 
"target agnostic" is a sign of intent, even if for some currently unknown 
reason it would not hold true.





Comment at: openmp/libomptarget/deviceRTLs/common/target_region.h:100
+///
+EXTERN int8_t __kmpc_target_region_kernel_init(bool UseSPMDMode,
+   bool RequiresOMPRuntime,

ABataev wrote:
> jdoerfert wrote:
> > ABataev wrote:
> > > jdoerfert wrote:
> > > > ABataev wrote:
> > > > > Better to use `ident_loc` for passing info about execution mode and 
> > > > > full/lightweight runtime.
> > > > Could you please explain why you think that? Adding indirection through 
> > > > a structure does not really seem beneficial to me.
> > > Almost all function from libomp rely on `ident_loc`. The functions, which 
> > > were added for NVPTX without this parameter had a lot of problems later 
> > > and most of them were replaced with the functions with this parameter 
> > > type. Plus, this parameter is used for OMPD/OMPT and it may be important 
> > > for future OMPD/OMPT support.
> > > Almost all function from libomp rely on ident_loc.
> > 
> > If you look at the implementation of this interface for NVPTX you will see 
> > that the called functions do not take `ident_loc` values. When you create 
> > the calls from the existing NVPTX code generation in clang, the current 
> > code **does not use** `ident_loc` for similar functions, see:
> > `___kmpc_kernel_init(kmp_int32 thread_limit, int16_t RequiresOMPRuntime)`,
> > `__kmpc_kernel_deinit(int16_t IsOMPRuntimeInitialized)`,
> > `__kmpc_spmd_kernel_init(kmp_int32 thread_limit, int16_t 
> > RequiresOMPRuntime, int16_t RequiresDataSharing)`,
> > `__kmpc_kernel_parallel(void **outlined_function, int16_t 
> > IsOMPRuntimeInitialized)`,
> > ...
> > 
> > 
> > 
> > > Plus, this parameter is used for 

[PATCH] D58514: Avoid needlessly copying blocks that initialize or are assigned to local auto variables to the heap

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

In D58514#1429758 , @wuhao5 wrote:

> > Can I ask why you want a weak reference to a block in the first place?  It 
> > seems basically useless — blocks can certainly appear in reference cycles, 
> > but I don't know why you'd ever try to break that cycle with the block 
> > instead of somewhere else.
>
> The simplified version:
>
> auto b = ^{
>
>   if (check) {
> dispatch_after(queue, 1, b);
>   } else {
>// done.
>   }
>
> };
>  dispatch_after(queue, 1, b);


Okay, so really just a block self-reference.  We could really just add a 
feature for that that would avoid both the complexity and the expense of the 
self-capture dance.


Repository:
  rC Clang

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

https://reviews.llvm.org/D58514



___
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-14 Thread George Burgess IV via Phabricator via cfe-commits
george.burgess.iv added a comment.

This LGTM; feel free to submit after Aaron stamps this.

Thanks again!




Comment at: clang/lib/Sema/SemaExpr.cpp:5929
 
+checkFortifiedBuiltinMemoryFunction(FDecl, TheCall);
+

erik.pilkington wrote:
> george.burgess.iv wrote:
> > Why isn't this in CheckBuiltinFunctionCall?
> For the same reason I added the `bool` parameter to `getBuiltinCallee`, we 
> don't usually consider calls to `__attribute__((overloadable))` be builtins, 
> so we never reach `CheckBuiltinFunctionCall` for them. We're planning on 
> using that attribute though:
> 
> ```
> int sprintf(__attribute__((pass_object_size(_FORTIFY_LEVEL))) char *buffer, 
> const char *format, ...) 
>   __attribute__((overloadable)) 
> __asm__("___sprintf_pass_object_size_chk");
> ```
SGTM


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


r356198 - [OPENMP]Fix crash for the ordered(n) clause.

2019-03-14 Thread Alexey Bataev via cfe-commits
Author: abataev
Date: Thu Mar 14 13:36:00 2019
New Revision: 356198

URL: http://llvm.org/viewvc/llvm-project?rev=356198=rev
Log:
[OPENMP]Fix crash for the ordered(n) clause.

If the doacross lop construct is used and the loop counter is declare
outside of the loop, the compiler might crash trying to get the address
of the loop counter. Patch fixes this problem.

Modified:
cfe/trunk/lib/CodeGen/CGStmtOpenMP.cpp
cfe/trunk/lib/Sema/SemaOpenMP.cpp
cfe/trunk/test/OpenMP/ordered_doacross_codegen.cpp

Modified: cfe/trunk/lib/CodeGen/CGStmtOpenMP.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/CodeGen/CGStmtOpenMP.cpp?rev=356198=356197=356198=diff
==
--- cfe/trunk/lib/CodeGen/CGStmtOpenMP.cpp (original)
+++ cfe/trunk/lib/CodeGen/CGStmtOpenMP.cpp Thu Mar 14 13:36:00 2019
@@ -1529,8 +1529,9 @@ void CodeGenFunction::EmitOMPPrivateLoop
  I < E; ++I) {
   const auto *DRE = cast(C->getLoopCounter(I));
   const auto *VD = cast(DRE->getDecl());
-  // Override only those variables that are really emitted already.
-  if (LocalDeclMap.count(VD)) {
+  // Override only those variables that can be captured to avoid 
re-emission
+  // of the variables declared within the loops.
+  if (DRE->refersToEnclosingVariableOrCapture()) {
 (void)LoopScope.addPrivate(VD, [this, DRE, VD]() {
   return CreateMemTemp(DRE->getType(), VD->getName());
 });

Modified: cfe/trunk/lib/Sema/SemaOpenMP.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Sema/SemaOpenMP.cpp?rev=356198=356197=356198=diff
==
--- cfe/trunk/lib/Sema/SemaOpenMP.cpp (original)
+++ cfe/trunk/lib/Sema/SemaOpenMP.cpp Thu Mar 14 13:36:00 2019
@@ -4758,8 +4758,7 @@ DeclRefExpr *OpenMPIterationSpaceChecker
   Captures.insert(std::make_pair(LCRef, Ref));
 return Ref;
   }
-  return buildDeclRefExpr(SemaRef, VD, VD->getType().getNonReferenceType(),
-  DefaultLoc);
+  return cast(LCRef);
 }
 
 Expr *OpenMPIterationSpaceChecker::buildPrivateCounterVar() const {

Modified: cfe/trunk/test/OpenMP/ordered_doacross_codegen.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/OpenMP/ordered_doacross_codegen.cpp?rev=356198=356197=356198=diff
==
--- cfe/trunk/test/OpenMP/ordered_doacross_codegen.cpp (original)
+++ cfe/trunk/test/OpenMP/ordered_doacross_codegen.cpp Thu Mar 14 13:36:00 2019
@@ -16,6 +16,17 @@ extern int n;
 int a[10], b[10], c[10], d[10];
 void foo();
 
+// CHECK-LABEL:bar
+void bar() {
+  int i,j;
+// CHECK: call void @__kmpc_doacross_init(
+// CHECK: call void @__kmpc_doacross_fini(
+#pragma omp parallel for ordered(2)
+  for (i = 0; i < n; ++i)
+  for (j = 0; j < n; ++j)
+a[i] = b[i] + 1;
+}
+
 // CHECK-LABEL: @main()
 int main() {
   int i;
@@ -35,7 +46,7 @@ int main() {
 // CHECK: call void @__kmpc_doacross_init([[IDENT]], i32 [[GTID]], i32 1, i8* 
[[CAST]])
 // CHECK: call void @__kmpc_for_static_init_4(
 #pragma omp for ordered(1)
-  for (i = 0; i < n; ++i) {
+  for (int i = 0; i < n; ++i) {
 a[i] = b[i] + 1;
 foo();
 // CHECK: invoke void [[FOO:.+]](


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


r356197 - Reland part of "Add AIX Target Info"

2019-03-14 Thread Jason Liu via cfe-commits
Author: jasonliu
Date: Thu Mar 14 13:27:39 2019
New Revision: 356197

URL: http://llvm.org/viewvc/llvm-project?rev=356197=rev
Log:
Reland part of "Add AIX Target Info"

This patch reland the test case max_align.c which is failing at
Windows and PS4 platform in the previous commit.

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

original llvm-svn: 356060

Added:
cfe/trunk/test/Headers/max_align.c

Added: cfe/trunk/test/Headers/max_align.c
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/Headers/max_align.c?rev=356197=auto
==
--- cfe/trunk/test/Headers/max_align.c (added)
+++ cfe/trunk/test/Headers/max_align.c Thu Mar 14 13:27:39 2019
@@ -0,0 +1,12 @@
+// RUN: %clang_cc1 -fsyntax-only -std=c11 -verify %s
+// expected-no-diagnostics
+
+// XFAIL: windows-
+
+#ifndef __BIGGEST_ALIGNMENT__
+#error __BIGGEST_ALIGNMENT__ not defined
+#endif
+
+#include 
+
+_Static_assert(__BIGGEST_ALIGNMENT__ == _Alignof(max_align_t), "");


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


[PATCH] D59319: [OpenMP][Offloading][1/3] A generic and simple target region interface

2019-03-14 Thread Alexey Bataev via Phabricator via cfe-commits
ABataev added inline comments.



Comment at: openmp/libomptarget/deviceRTLs/common/target_region.h:27
+
+/// The target region _kernel_ interface for GPUs
+///

jdoerfert wrote:
> ABataev wrote:
> > jdoerfert wrote:
> > > ABataev wrote:
> > > > All exported functions are declared in the `interface.h` file. I don't 
> > > > think we need an extra interface file here
> > > `interface.h`, or to be more precise for people that do not know, 
> > > `deviceRTLs/nvptx/src/interface.h`, is nvptx specific. This file, 
> > > `deviceRTLs/common/target_region.h`, is by design target agnostic and not 
> > > placed _under_ the nvptx subfolder. If you are willing to move 
> > > `interface.h` into a common space and remove the nvptx specific functions 
> > > we can merge the two. Otherwise, I have strong reservations agains that 
> > > and good reason not to do it.
> > I see that currently it is written in Cuda. It means, it targets NVidia 
> > GPUs, at least at the moment. I'm fine to put this header file into the 
> > common directory, if you're sure that this is really target agnostic. But 
> > maybe just for a start we should put it to NVPTX directory? Later, when you 
> > or somebody else will add support for other GPUs and he/she will find out 
> > that these functions are really target agnostic, they can be moved into the 
> > common directory?
> > I see that currently it is written in Cuda. It means, it targets NVidia 
> > GPUs, at least at the moment
> 
> How do you see that? (I hope we both talk about this file, correct?)
> 
> 
> > But maybe just for a start we should put it to NVPTX directory?
> 
> Why? What is the benefit? If we want it to be agnostic, regardless of the 
> current state, it should be developed _outside_ of the target specific 
> directories.
> 
I'm not talking about this particular file, just like I said we can put it into 
`common` subdirectory. I'm talking about the implementation files. They all are 
written in Cuda, no?
But it is not proved yet that this solution is target agnostic. Did you test it 
for AMD?



Comment at: openmp/libomptarget/deviceRTLs/common/target_region.h:100
+///
+EXTERN int8_t __kmpc_target_region_kernel_init(bool UseSPMDMode,
+   bool RequiresOMPRuntime,

jdoerfert wrote:
> ABataev wrote:
> > jdoerfert wrote:
> > > ABataev wrote:
> > > > Better to use `ident_loc` for passing info about execution mode and 
> > > > full/lightweight runtime.
> > > Could you please explain why you think that? Adding indirection through a 
> > > structure does not really seem beneficial to me.
> > Almost all function from libomp rely on `ident_loc`. The functions, which 
> > were added for NVPTX without this parameter had a lot of problems later and 
> > most of them were replaced with the functions with this parameter type. 
> > Plus, this parameter is used for OMPD/OMPT and it may be important for 
> > future OMPD/OMPT support.
> > Almost all function from libomp rely on ident_loc.
> 
> If you look at the implementation of this interface for NVPTX you will see 
> that the called functions do not take `ident_loc` values. When you create the 
> calls from the existing NVPTX code generation in clang, the current code 
> **does not use** `ident_loc` for similar functions, see:
> `___kmpc_kernel_init(kmp_int32 thread_limit, int16_t RequiresOMPRuntime)`,
> `__kmpc_kernel_deinit(int16_t IsOMPRuntimeInitialized)`,
> `__kmpc_spmd_kernel_init(kmp_int32 thread_limit, int16_t RequiresOMPRuntime, 
> int16_t RequiresDataSharing)`,
> `__kmpc_kernel_parallel(void **outlined_function, int16_t 
> IsOMPRuntimeInitialized)`,
> ...
> 
> 
> 
> > Plus, this parameter is used for OMPD/OMPT and it may be important for 
> > future OMPD/OMPT support.
> 
> If we at some point need to make the options permanent in an `ident_loc` we 
> can simply pass an `ident_loc` and require it to be initialized by the call. 
> Cluttering the user code with stores and indirection is exactly what I do 
> want to avoid.
1. The new functions rely on `ident_loc`. We had to add those new functions 
because the old ones did not use it and it was bad design decision. Now we need 
to fix this. I suggest you do everything right from the very beginning rather 
than fixing this later by adding extra entry points to support OMPT/OMPD or 
something else, for example.
2. No, you cannot simply change the interface of the library to keep the 
compatibility with the previous versions of the compiler/library. You will need 
to add the new entries.  



Comment at: openmp/libomptarget/deviceRTLs/nvptx/src/omp_data.cu:70
+
+__device__ __shared__ target_region_shared_buffer _target_region_shared_memory;
+

jdoerfert wrote:
> ABataev wrote:
> > It would be good to store it the global memory rather than in the shared to 
> > save th 

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

2019-03-14 Thread Anton Afanasyev via Phabricator via cfe-commits
anton-afanasyev marked 5 inline comments as done.
anton-afanasyev added inline comments.



Comment at: clang/lib/Parse/ParseAST.cpp:172
+  {
+llvm::TimeTraceScope scope("Backend", "");
+Consumer->HandleTranslationUnit(S.getASTContext());

rnk wrote:
> I think you may want to move this to `clang::EmitBackendOutput`, which is 
> closer to real "backend-y" actions. I don't think there's any other heavy 
> lifting that happens in HandleTranslationUnit, it looks like diagnostic 
> teardown and setup for calling EmitBackendOutput.
Yes, thanks.



Comment at: clang/lib/Sema/Sema.cpp:98
+if (llvm::TimeTraceProfilerEnabled()) {
+  auto fe = SM.getFileEntryForID(SM.getFileID(Loc));
+  llvm::TimeTraceProfilerBegin(

rnk wrote:
> This doesn't match the LLVM naming and auto usage conventions: 
> https://llvm.org/docs/CodingStandards.html#use-auto-type-deduction-to-make-code-more-readable
> 
> Yes, there is an active debate about changing the way we name variables, but 
> please just match what we have for now.
Ok



Comment at: llvm/lib/IR/LegacyPassManager.cpp:1632-1634
+  bool profileTime = llvm::TimeTraceProfilerEnabled();
+  if (profileTime)
+llvm::TimeTraceProfilerBegin("OptFunction", F.getName().data());

rnk wrote:
> Someone is going to have to figure out where the equivalent annotations 
> should live in the new passmanager. I wasn't able to find it just by looking 
> myself, so I won't ask you to do it. I guess it's in 
> llvm/include/llvm/IR/PassManager.h.
Ok, I'm to look for it.



Comment at: llvm/lib/Support/TimeProfiler.cpp:28
+
+static std::string EscapeString(const char *src) {
+  std::string os;

rnk wrote:
> Here and else where things should be named the LLVM way for consistency:
> https://llvm.org/docs/CodingStandards.html#name-types-functions-variables-and-enumerators-properly
> `escapeString`, `Src`, etc. Tedious, I know.
Ok



Comment at: llvm/lib/Support/TimeProfiler.h:1
+//===- llvm/Support/TimeProfiler.h - Hierarchical Time Profiler -*- C++ 
-*-===//
+//

rnk wrote:
> I applied this patch locally to try it, and I noticed this header should be 
> in llvm/include/llvm/Support, not llvm/lib/Support.
Oops, you're right, this is accidentally moved in patch! Thanks.


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] D59319: [OpenMP][Offloading][1/3] A generic and simple target region interface

2019-03-14 Thread Johannes Doerfert via Phabricator via cfe-commits
jdoerfert added inline comments.



Comment at: openmp/libomptarget/deviceRTLs/common/target_region.h:27
+
+/// The target region _kernel_ interface for GPUs
+///

ABataev wrote:
> jdoerfert wrote:
> > ABataev wrote:
> > > All exported functions are declared in the `interface.h` file. I don't 
> > > think we need an extra interface file here
> > `interface.h`, or to be more precise for people that do not know, 
> > `deviceRTLs/nvptx/src/interface.h`, is nvptx specific. This file, 
> > `deviceRTLs/common/target_region.h`, is by design target agnostic and not 
> > placed _under_ the nvptx subfolder. If you are willing to move 
> > `interface.h` into a common space and remove the nvptx specific functions 
> > we can merge the two. Otherwise, I have strong reservations agains that and 
> > good reason not to do it.
> I see that currently it is written in Cuda. It means, it targets NVidia GPUs, 
> at least at the moment. I'm fine to put this header file into the common 
> directory, if you're sure that this is really target agnostic. But maybe just 
> for a start we should put it to NVPTX directory? Later, when you or somebody 
> else will add support for other GPUs and he/she will find out that these 
> functions are really target agnostic, they can be moved into the common 
> directory?
> I see that currently it is written in Cuda. It means, it targets NVidia GPUs, 
> at least at the moment

How do you see that? (I hope we both talk about this file, correct?)


> But maybe just for a start we should put it to NVPTX directory?

Why? What is the benefit? If we want it to be agnostic, regardless of the 
current state, it should be developed _outside_ of the target specific 
directories.




Comment at: openmp/libomptarget/deviceRTLs/common/target_region.h:100
+///
+EXTERN int8_t __kmpc_target_region_kernel_init(bool UseSPMDMode,
+   bool RequiresOMPRuntime,

ABataev wrote:
> jdoerfert wrote:
> > ABataev wrote:
> > > Better to use `ident_loc` for passing info about execution mode and 
> > > full/lightweight runtime.
> > Could you please explain why you think that? Adding indirection through a 
> > structure does not really seem beneficial to me.
> Almost all function from libomp rely on `ident_loc`. The functions, which 
> were added for NVPTX without this parameter had a lot of problems later and 
> most of them were replaced with the functions with this parameter type. Plus, 
> this parameter is used for OMPD/OMPT and it may be important for future 
> OMPD/OMPT support.
> Almost all function from libomp rely on ident_loc.

If you look at the implementation of this interface for NVPTX you will see that 
the called functions do not take `ident_loc` values. When you create the calls 
from the existing NVPTX code generation in clang, the current code **does not 
use** `ident_loc` for similar functions, see:
`___kmpc_kernel_init(kmp_int32 thread_limit, int16_t RequiresOMPRuntime)`,
`__kmpc_kernel_deinit(int16_t IsOMPRuntimeInitialized)`,
`__kmpc_spmd_kernel_init(kmp_int32 thread_limit, int16_t RequiresOMPRuntime, 
int16_t RequiresDataSharing)`,
`__kmpc_kernel_parallel(void **outlined_function, int16_t 
IsOMPRuntimeInitialized)`,
...



> Plus, this parameter is used for OMPD/OMPT and it may be important for future 
> OMPD/OMPT support.

If we at some point need to make the options permanent in an `ident_loc` we can 
simply pass an `ident_loc` and require it to be initialized by the call. 
Cluttering the user code with stores and indirection is exactly what I do want 
to avoid.



Comment at: openmp/libomptarget/deviceRTLs/common/target_region.h:124
+/// unpacking code.
+typedef void (*ParallelWorkFnTy)(char * /* SharedValues */,
+ char * /* PrivateValues */);

ABataev wrote:
> We used `void *` for buffers usually, I think it is better to use `void *` 
> here too instead of `char *`.
Thanks, fixed.



Comment at: openmp/libomptarget/deviceRTLs/nvptx/src/omp_data.cu:70
+
+__device__ __shared__ target_region_shared_buffer _target_region_shared_memory;
+

ABataev wrote:
> It would be good to store it the global memory rather than in the shared to 
> save th shared memory. Also, we already are using several shared memory 
> buffers for different purposes, it would be good to merge them somehow to 
> reduce pressure on shared memory.
I would have reused your buffer but it is for reasons unclear to me, not a 
byte-wise buffer but an array of `void *` and also used as such. Using it as a 
byte-wise buffer might cause problems or at least confusion. Changing it to a 
byte-wise buffer would be fine with me. I don't need a separate buffer but just 
one with the functionality implemented in this one.



Comment at: 

[PATCH] D59319: [OpenMP][Offloading][1/3] A generic and simple target region interface

2019-03-14 Thread Johannes Doerfert via Phabricator via cfe-commits
jdoerfert updated this revision to Diff 190710.
jdoerfert marked 6 inline comments as done.
jdoerfert added a comment.

Change char* to void*


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D59319

Files:
  openmp/libomptarget/deviceRTLs/common/target_region.h
  openmp/libomptarget/deviceRTLs/nvptx/CMakeLists.txt
  openmp/libomptarget/deviceRTLs/nvptx/src/omp_data.cu
  openmp/libomptarget/deviceRTLs/nvptx/src/omptarget-nvptx.h
  openmp/libomptarget/deviceRTLs/nvptx/src/target_region.cu

Index: openmp/libomptarget/deviceRTLs/nvptx/src/target_region.cu
===
--- /dev/null
+++ openmp/libomptarget/deviceRTLs/nvptx/src/target_region.cu
@@ -0,0 +1,197 @@
+//===-- target_region.cu  CUDA impl. of the target region interface -*-===//
+//
+// 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
+//
+//===--===//
+//
+// This file contains the implementation of the common target region interface.
+//
+//===--===//
+
+// Include the native definitions first as certain defines might be needed in
+// the common interface definition below.
+#include "omptarget-nvptx.h"
+#include "interface.h"
+
+#include "../../common/target_region.h"
+
+/// The pointer used to share memory between team threads.
+extern __device__ __shared__ target_region_shared_buffer
+_target_region_shared_memory;
+
+EXTERN char *__kmpc_target_region_kernel_get_shared_memory() {
+  return _target_region_shared_memory.begin();
+}
+EXTERN char *__kmpc_target_region_kernel_get_private_memory() {
+  return _target_region_shared_memory.begin() +
+ _target_region_shared_memory.get_offset();
+}
+
+/// Simple generic state machine for worker threads.
+INLINE static void
+__kmpc_target_region_state_machine(bool IsOMPRuntimeInitialized) {
+
+  do {
+void *WorkFn = 0;
+
+// Wait for the signal that we have a new work function.
+__kmpc_barrier_simple_spmd(NULL, 0);
+
+// Retrieve the work function from the runtime.
+bool IsActive = __kmpc_kernel_parallel(, IsOMPRuntimeInitialized);
+
+// If there is nothing more to do, break out of the state machine by
+// returning to the caller.
+if (!WorkFn)
+  return;
+
+if (IsActive) {
+  char *SharedVars = __kmpc_target_region_kernel_get_shared_memory();
+  char *PrivateVars = __kmpc_target_region_kernel_get_private_memory();
+
+  ((ParallelWorkFnTy)WorkFn)(SharedVars, PrivateVars);
+
+  __kmpc_kernel_end_parallel();
+}
+
+__kmpc_barrier_simple_spmd(NULL, 0);
+
+  } while (true);
+}
+
+/// Filter threads into masters and workers. If \p UseStateMachine is true,
+/// required workers will enter a state machine through and be trapped there.
+/// Master and surplus worker threads will return from this function immediately
+/// while required workers will only return once there is no more work. The
+/// return value indicates if the thread is a master (1), a surplus worker (0),
+/// or a finished required worker released from the state machine (-1).
+INLINE static int8_t
+__kmpc_target_region_thread_filter(unsigned ThreadLimit, bool UseStateMachine,
+   bool IsOMPRuntimeInitialized) {
+
+  unsigned TId = GetThreadIdInBlock();
+  bool IsWorker = TId < ThreadLimit;
+
+  if (IsWorker) {
+if (UseStateMachine)
+  __kmpc_target_region_state_machine(IsOMPRuntimeInitialized);
+return -1;
+  }
+
+  return TId == GetMasterThreadID();
+}
+
+EXTERN int8_t __kmpc_target_region_kernel_init(bool UseSPMDMode,
+   bool UseStateMachine,
+   bool RequiresOMPRuntime,
+   bool RequiresDataSharing) {
+  unsigned NumThreads = GetNumberOfThreadsInBlock();
+
+  // Handle the SPMD case first.
+  if (UseSPMDMode) {
+
+__kmpc_spmd_kernel_init(NumThreads, RequiresOMPRuntime,
+RequiresDataSharing);
+
+if (RequiresDataSharing)
+  __kmpc_data_sharing_init_stack_spmd();
+
+return 1;
+  }
+
+  // Reserve one WARP in non-SPMD mode for the masters.
+  unsigned ThreadLimit = NumThreads - WARPSIZE;
+  int8_t FilterVal = __kmpc_target_region_thread_filter(
+  ThreadLimit, UseStateMachine, RequiresOMPRuntime);
+
+  // If the filter returns 1 the executing thread is a team master which will
+  // initialize the kernel in the following.
+  if (FilterVal == 1) {
+__kmpc_kernel_init(ThreadLimit, RequiresOMPRuntime);
+__kmpc_data_sharing_init_stack();
+_target_region_shared_memory.init();
+  }
+
+  return FilterVal;
+}
+
+EXTERN void 

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

2019-03-14 Thread Reid Kleckner via Phabricator via cfe-commits
rnk added inline comments.



Comment at: llvm/lib/IR/LegacyPassManager.cpp:1686
 
+  llvm::TimeTraceScope timeScope("OptModule", M.getName().data());
   for (Function  : M)

I think these OptModule and OptFunction labels may need some improvement. For a 
backend-heavy compilation like LLVM's X86ISelLowering.cpp, these labels aren't 
as good as they could be: {F8455962}
I think it's fine to leave that for later, though.


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] D56990: Bugfix for Replacement of tied operand of inline asm

2019-03-14 Thread Eli Friedman via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rC356196: [CodeGen] Consider tied operands when adjusting 
inline asm operands. (authored by efriedma, committed by ).

Repository:
  rC Clang

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

https://reviews.llvm.org/D56990

Files:
  lib/CodeGen/CGStmt.cpp
  test/CodeGen/asm-inout.c


Index: test/CodeGen/asm-inout.c
===
--- test/CodeGen/asm-inout.c
+++ test/CodeGen/asm-inout.c
@@ -46,3 +46,12 @@
   asm ("pmulhuw %1, %0\n\t" : "+y" (__A) : "y" (__B));
   return __A;
 }
+
+// CHECK: @test6
+int test6(void) {
+  typedef unsigned char __attribute__((vector_size(8))) _m64u8;
+  _m64u8 __attribute__((aligned(16))) Mu8_0, __attribute__((aligned(16))) 
Mu8_1;
+  // CHECK: call x86_mmx asm "nop", "=y,0,~{dirflag},~{fpsr},~{flags}"(x86_mmx 
%1)
+  asm ("nop" : "=y"(Mu8_1 ) : "0"(Mu8_0 ));
+  return 0;
+}
Index: lib/CodeGen/CGStmt.cpp
===
--- lib/CodeGen/CGStmt.cpp
+++ lib/CodeGen/CGStmt.cpp
@@ -1939,6 +1939,9 @@
   std::vector InOutArgs;
   std::vector InOutArgTypes;
 
+  // Keep track of out constraints for tied input operand.
+  std::vector OutputConstraints;
+
   // An inline asm can be marked readonly if it meets the following conditions:
   //  - it doesn't have any sideeffects
   //  - it doesn't clobber memory
@@ -1961,7 +1964,7 @@
 OutputConstraint = AddVariableConstraints(OutputConstraint, *OutExpr,
   getTarget(), CGM, S,
   Info.earlyClobber());
-
+OutputConstraints.push_back(OutputConstraint);
 LValue Dest = EmitLValue(OutExpr);
 if (!Constraints.empty())
   Constraints += ',';
@@ -2079,6 +2082,7 @@
 InputConstraint, *InputExpr->IgnoreParenNoopCasts(getContext()),
 getTarget(), CGM, S, false /* No EarlyClobber */);
 
+std::string ReplaceConstraint (InputConstraint);
 llvm::Value *Arg = EmitAsmInput(Info, InputExpr, Constraints);
 
 // If this input argument is tied to a larger output result, extend the
@@ -2106,9 +2110,11 @@
   Arg = Builder.CreateFPExt(Arg, OutputTy);
 }
   }
+  // Deal with the tied operands' constraint code in adjustInlineAsmType.
+  ReplaceConstraint = OutputConstraints[Output];
 }
 if (llvm::Type* AdjTy =
-  getTargetHooks().adjustInlineAsmType(*this, InputConstraint,
+  getTargetHooks().adjustInlineAsmType(*this, ReplaceConstraint,
Arg->getType()))
   Arg = Builder.CreateBitCast(Arg, AdjTy);
 else


Index: test/CodeGen/asm-inout.c
===
--- test/CodeGen/asm-inout.c
+++ test/CodeGen/asm-inout.c
@@ -46,3 +46,12 @@
   asm ("pmulhuw %1, %0\n\t" : "+y" (__A) : "y" (__B));
   return __A;
 }
+
+// CHECK: @test6
+int test6(void) {
+  typedef unsigned char __attribute__((vector_size(8))) _m64u8;
+  _m64u8 __attribute__((aligned(16))) Mu8_0, __attribute__((aligned(16))) Mu8_1;
+  // CHECK: call x86_mmx asm "nop", "=y,0,~{dirflag},~{fpsr},~{flags}"(x86_mmx %1)
+  asm ("nop" : "=y"(Mu8_1 ) : "0"(Mu8_0 ));
+  return 0;
+}
Index: lib/CodeGen/CGStmt.cpp
===
--- lib/CodeGen/CGStmt.cpp
+++ lib/CodeGen/CGStmt.cpp
@@ -1939,6 +1939,9 @@
   std::vector InOutArgs;
   std::vector InOutArgTypes;
 
+  // Keep track of out constraints for tied input operand.
+  std::vector OutputConstraints;
+
   // An inline asm can be marked readonly if it meets the following conditions:
   //  - it doesn't have any sideeffects
   //  - it doesn't clobber memory
@@ -1961,7 +1964,7 @@
 OutputConstraint = AddVariableConstraints(OutputConstraint, *OutExpr,
   getTarget(), CGM, S,
   Info.earlyClobber());
-
+OutputConstraints.push_back(OutputConstraint);
 LValue Dest = EmitLValue(OutExpr);
 if (!Constraints.empty())
   Constraints += ',';
@@ -2079,6 +2082,7 @@
 InputConstraint, *InputExpr->IgnoreParenNoopCasts(getContext()),
 getTarget(), CGM, S, false /* No EarlyClobber */);
 
+std::string ReplaceConstraint (InputConstraint);
 llvm::Value *Arg = EmitAsmInput(Info, InputExpr, Constraints);
 
 // If this input argument is tied to a larger output result, extend the
@@ -2106,9 +2110,11 @@
   Arg = Builder.CreateFPExt(Arg, OutputTy);
 }
   }
+  // Deal with the tied operands' constraint code in adjustInlineAsmType.
+  ReplaceConstraint = OutputConstraints[Output];
 }
 if (llvm::Type* AdjTy =
-  getTargetHooks().adjustInlineAsmType(*this, InputConstraint,
+  getTargetHooks().adjustInlineAsmType(*this, ReplaceConstraint,
   

r356196 - [CodeGen] Consider tied operands when adjusting inline asm operands.

2019-03-14 Thread Eli Friedman via cfe-commits
Author: efriedma
Date: Thu Mar 14 12:46:51 2019
New Revision: 356196

URL: http://llvm.org/viewvc/llvm-project?rev=356196=rev
Log:
[CodeGen] Consider tied operands when adjusting inline asm operands.

The constraint "0" in the following asm did not consider the its
relationship with "=y" when try to replace the type of the operands.

asm ("nop" : "=y"(Mu8_1 ) : "0"(Mu8_0 ));

Patch by Xiang Zhang.

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



Modified:
cfe/trunk/lib/CodeGen/CGStmt.cpp
cfe/trunk/test/CodeGen/asm-inout.c

Modified: cfe/trunk/lib/CodeGen/CGStmt.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/CodeGen/CGStmt.cpp?rev=356196=356195=356196=diff
==
--- cfe/trunk/lib/CodeGen/CGStmt.cpp (original)
+++ cfe/trunk/lib/CodeGen/CGStmt.cpp Thu Mar 14 12:46:51 2019
@@ -1939,6 +1939,9 @@ void CodeGenFunction::EmitAsmStmt(const
   std::vector InOutArgs;
   std::vector InOutArgTypes;
 
+  // Keep track of out constraints for tied input operand.
+  std::vector OutputConstraints;
+
   // An inline asm can be marked readonly if it meets the following conditions:
   //  - it doesn't have any sideeffects
   //  - it doesn't clobber memory
@@ -1961,7 +1964,7 @@ void CodeGenFunction::EmitAsmStmt(const
 OutputConstraint = AddVariableConstraints(OutputConstraint, *OutExpr,
   getTarget(), CGM, S,
   Info.earlyClobber());
-
+OutputConstraints.push_back(OutputConstraint);
 LValue Dest = EmitLValue(OutExpr);
 if (!Constraints.empty())
   Constraints += ',';
@@ -2079,6 +2082,7 @@ void CodeGenFunction::EmitAsmStmt(const
 InputConstraint, *InputExpr->IgnoreParenNoopCasts(getContext()),
 getTarget(), CGM, S, false /* No EarlyClobber */);
 
+std::string ReplaceConstraint (InputConstraint);
 llvm::Value *Arg = EmitAsmInput(Info, InputExpr, Constraints);
 
 // If this input argument is tied to a larger output result, extend the
@@ -2106,9 +2110,11 @@ void CodeGenFunction::EmitAsmStmt(const
   Arg = Builder.CreateFPExt(Arg, OutputTy);
 }
   }
+  // Deal with the tied operands' constraint code in adjustInlineAsmType.
+  ReplaceConstraint = OutputConstraints[Output];
 }
 if (llvm::Type* AdjTy =
-  getTargetHooks().adjustInlineAsmType(*this, InputConstraint,
+  getTargetHooks().adjustInlineAsmType(*this, ReplaceConstraint,
Arg->getType()))
   Arg = Builder.CreateBitCast(Arg, AdjTy);
 else

Modified: cfe/trunk/test/CodeGen/asm-inout.c
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/CodeGen/asm-inout.c?rev=356196=356195=356196=diff
==
--- cfe/trunk/test/CodeGen/asm-inout.c (original)
+++ cfe/trunk/test/CodeGen/asm-inout.c Thu Mar 14 12:46:51 2019
@@ -46,3 +46,12 @@ __m64 test5(__m64 __A, __m64 __B) {
   asm ("pmulhuw %1, %0\n\t" : "+y" (__A) : "y" (__B));
   return __A;
 }
+
+// CHECK: @test6
+int test6(void) {
+  typedef unsigned char __attribute__((vector_size(8))) _m64u8;
+  _m64u8 __attribute__((aligned(16))) Mu8_0, __attribute__((aligned(16))) 
Mu8_1;
+  // CHECK: call x86_mmx asm "nop", "=y,0,~{dirflag},~{fpsr},~{flags}"(x86_mmx 
%1)
+  asm ("nop" : "=y"(Mu8_1 ) : "0"(Mu8_0 ));
+  return 0;
+}


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


[PATCH] D59279: [Analyzer] Checker for non-determinism caused by iteration of unordered container of pointers

2019-03-14 Thread Mandeep Singh Grang via Phabricator via cfe-commits
mgrang added a comment.

I was trying to write another checker for hashing of pointers. Basically, I 
wanted to match all instances where the keys of std::map are pointers. Writing 
an AST matcher for std::map is straightforward. However, I am not sure how to 
check for pointer keys after matching std::map.

The following matches std::map. But I need to match std::map. 
So I was thinking something on the lines of 
templateArgument(hasType(pointerType())).

  auto ContainersM = anyOf(
   hasName("std::map"),
   hasName("std::unordered_map")
 );
  
  auto HashContainerM = varDecl(hasType(cxxRecordDecl(ContainersM)))


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

https://reviews.llvm.org/D59279



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


[PATCH] D52150: [clang-format] BeforeHash added to IndentPPDirectives

2019-03-14 Thread MyDeveloperDay via Phabricator via cfe-commits
MyDeveloperDay added a comment.

@to-miz do you have permission to commit?


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

https://reviews.llvm.org/D52150



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


[PATCH] D55170: [clang-format]: Add NonEmptyParentheses spacing option

2019-03-14 Thread MyDeveloperDay via Phabricator via cfe-commits
MyDeveloperDay requested changes to this revision.
MyDeveloperDay added a comment.
This revision now requires changes to proceed.

Pulling this revision down to build it caused build issues with missing 
SBBLO_Always, could you investigate before committing?




Comment at: lib/Format/TokenAnnotator.cpp:2607
+!Left.opensScope() &&
+(Style.SpaceBeforeCpp11BracedList == FormatStyle::SBBLO_Always ||
+ (Style.SpaceBeforeCpp11BracedList == FormatStyle::SBBLO_NonEmpty &&

Where are these SBBLO defined? I cannot find them in Format.h from what I can 
SpaceBeforeCpp11BracedList  is a bool


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

https://reviews.llvm.org/D55170



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


[PATCH] D59382: Rename directory housing clang-change-namespace to be eponymous

2019-03-14 Thread Nico Weber via Phabricator via cfe-commits
thakis created this revision.
thakis added a reviewer: ioeric.
Herald added a subscriber: mgorny.

Makes the name of this directory consistent with the names of the other 
directories in clang-tools-extra.


https://reviews.llvm.org/D59382

Files:
  clang-tools-extra/CMakeLists.txt
  clang-tools-extra/change-namespace/CMakeLists.txt
  clang-tools-extra/change-namespace/ChangeNamespace.cpp
  clang-tools-extra/change-namespace/ChangeNamespace.h
  clang-tools-extra/change-namespace/tool/CMakeLists.txt
  clang-tools-extra/change-namespace/tool/ClangChangeNamespace.cpp
  clang-tools-extra/clang-change-namespace/CMakeLists.txt
  clang-tools-extra/clang-change-namespace/ChangeNamespace.cpp
  clang-tools-extra/clang-change-namespace/ChangeNamespace.h
  clang-tools-extra/clang-change-namespace/tool/CMakeLists.txt
  clang-tools-extra/clang-change-namespace/tool/ClangChangeNamespace.cpp
  clang-tools-extra/test/change-namespace/Inputs/fake-std.h
  clang-tools-extra/test/change-namespace/lambda-function.cpp
  clang-tools-extra/test/change-namespace/macro.cpp
  clang-tools-extra/test/change-namespace/simple-move.cpp
  clang-tools-extra/test/change-namespace/white-list.cpp
  clang-tools-extra/test/clang-change-namespace/Inputs/fake-std.h
  clang-tools-extra/test/clang-change-namespace/lambda-function.cpp
  clang-tools-extra/test/clang-change-namespace/macro.cpp
  clang-tools-extra/test/clang-change-namespace/simple-move.cpp
  clang-tools-extra/test/clang-change-namespace/white-list.cpp
  clang-tools-extra/unittests/CMakeLists.txt
  clang-tools-extra/unittests/change-namespace/CMakeLists.txt
  clang-tools-extra/unittests/change-namespace/ChangeNamespaceTests.cpp
  clang-tools-extra/unittests/clang-change-namespace/CMakeLists.txt
  clang-tools-extra/unittests/clang-change-namespace/ChangeNamespaceTests.cpp


Index: clang-tools-extra/unittests/clang-change-namespace/CMakeLists.txt
===
--- clang-tools-extra/unittests/clang-change-namespace/CMakeLists.txt
+++ clang-tools-extra/unittests/clang-change-namespace/CMakeLists.txt
@@ -3,7 +3,7 @@
   )
 
 get_filename_component(CHANGE_NAMESPACE_SOURCE_DIR
-  ${CMAKE_CURRENT_SOURCE_DIR}/../../change-namespace REALPATH)
+  ${CMAKE_CURRENT_SOURCE_DIR}/../../clang-change-namespace REALPATH)
 include_directories(
   ${CHANGE_NAMESPACE_SOURCE_DIR}
   )
Index: clang-tools-extra/unittests/CMakeLists.txt
===
--- clang-tools-extra/unittests/CMakeLists.txt
+++ clang-tools-extra/unittests/CMakeLists.txt
@@ -14,8 +14,8 @@
   endif()
 endif()
 
-add_subdirectory(change-namespace)
 add_subdirectory(clang-apply-replacements)
+add_subdirectory(clang-change-namespace)
 add_subdirectory(clang-doc)
 add_subdirectory(clang-move)
 add_subdirectory(clang-query)
Index: clang-tools-extra/CMakeLists.txt
===
--- clang-tools-extra/CMakeLists.txt
+++ clang-tools-extra/CMakeLists.txt
@@ -9,7 +9,7 @@
 add_subdirectory(clang-tidy)
 add_subdirectory(clang-tidy-vs)
 
-add_subdirectory(change-namespace)
+add_subdirectory(clang-change-namespace)
 add_subdirectory(clang-doc)
 add_subdirectory(clang-query)
 add_subdirectory(clang-move)


Index: clang-tools-extra/unittests/clang-change-namespace/CMakeLists.txt
===
--- clang-tools-extra/unittests/clang-change-namespace/CMakeLists.txt
+++ clang-tools-extra/unittests/clang-change-namespace/CMakeLists.txt
@@ -3,7 +3,7 @@
   )
 
 get_filename_component(CHANGE_NAMESPACE_SOURCE_DIR
-  ${CMAKE_CURRENT_SOURCE_DIR}/../../change-namespace REALPATH)
+  ${CMAKE_CURRENT_SOURCE_DIR}/../../clang-change-namespace REALPATH)
 include_directories(
   ${CHANGE_NAMESPACE_SOURCE_DIR}
   )
Index: clang-tools-extra/unittests/CMakeLists.txt
===
--- clang-tools-extra/unittests/CMakeLists.txt
+++ clang-tools-extra/unittests/CMakeLists.txt
@@ -14,8 +14,8 @@
   endif()
 endif()
 
-add_subdirectory(change-namespace)
 add_subdirectory(clang-apply-replacements)
+add_subdirectory(clang-change-namespace)
 add_subdirectory(clang-doc)
 add_subdirectory(clang-move)
 add_subdirectory(clang-query)
Index: clang-tools-extra/CMakeLists.txt
===
--- clang-tools-extra/CMakeLists.txt
+++ clang-tools-extra/CMakeLists.txt
@@ -9,7 +9,7 @@
 add_subdirectory(clang-tidy)
 add_subdirectory(clang-tidy-vs)
 
-add_subdirectory(change-namespace)
+add_subdirectory(clang-change-namespace)
 add_subdirectory(clang-doc)
 add_subdirectory(clang-query)
 add_subdirectory(clang-move)
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D58514: Avoid needlessly copying blocks that initialize or are assigned to local auto variables to the heap

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

In D58514#1429713 , @rjmccall wrote:

> In D58514#1429652 , @erik.pilkington 
> wrote:
>
> > In D58514#1429606 , @rjmccall 
> > wrote:
> >
> > > There is no way in the existing ABI for copying a block to cause other 
> > > references to the block to become references to the heap block.  We do do 
> > > that for `__block` variables, but not for block objects themselves.
> >
> >
> > Do you think thats worth doing? We could add a forwarding pointer to the 
> > end of a block literal on the stack (after all the captures) and flip an 
> > unused bit to track it, preserving ABI. Seems like now that we're delaying 
> > `_Block_copy`ies this might be a bigger issue.
>
>
> We've always delayed `_Block_copy` in a bunch of places.  Now we're just 
> delaying it in a place that ARC used to be more conservative about.
>
> I guess we could actually make forwarding work at some code-size cost 
> (functions that emitted forwardable blocks would have to zero the forwarding 
> slot and release it when destroying the stack copy).  But it'd just silently 
> do nothing without a runtime update, so it'd be somewhat treacherous, 
> especially after a couple of releases: e.g. if we made the runtime change in 
> macOS 20 Eugene O'Neill National Historic Site, and Chromium eventually only 
> ran tests on macOS 20 and higher but still supported deploying to macOS 19 
> San Francisco Maritime National Historical Park, then Chromium might not 
> catch that it was still necessary to include an explicit copy here.


Lol, we're really running out of names, eh? We could still do a version of this 
without the O'Neill/Maritime problem, to optimize the performance on the 
following:

  void f(int (^blk)()) {
  // implicitly copy the block somehow...
  }
  
  int main() {
  int cap;
  auto p = ^{ return cap; };
  for (int i = 0; i != N; ++i)
  f(p);
  }

Where we used to do 1 _Block_copy, but now we do N. If we stored a strong 
reference to the heap block in the stack block, then made _Block_copy just hand 
back the first heap block it allocated, we could save that cost. That way we 
could still preserve the crash here, then maybe once macOS Maritime is at EOL 
we could adopt the forwarding behaviour. WDYT?


Repository:
  rC Clang

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

https://reviews.llvm.org/D58514



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


[PATCH] D57532: [Index] Make sure c-index-test finds libc++ on Mac

2019-03-14 Thread Nico Weber via Phabricator via cfe-commits
thakis added a comment.
Herald added a subscriber: jdoerfert.

ilya-biryukov, ping? :-)


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D57532



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


[PATCH] D58514: Avoid needlessly copying blocks that initialize or are assigned to local auto variables to the heap

2019-03-14 Thread Hao Wu via Phabricator via cfe-commits
wuhao5 added a comment.

> Can I ask why you want a weak reference to a block in the first place?  It 
> seems basically useless — blocks can certainly appear in reference cycles, 
> but I don't know why you'd ever try to break that cycle with the block 
> instead of somewhere else.

The simplified version:

auto b = ^{

  if (check) {
dispatch_after(queue, 1, b);
  } else {
   // done.
  }

};
dispatch_after(queue, 1, b);


Repository:
  rC Clang

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

https://reviews.llvm.org/D58514



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


[PATCH] D58514: Avoid needlessly copying blocks that initialize or are assigned to local auto variables to the heap

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

In D58514#1429652 , @erik.pilkington 
wrote:

> In D58514#1429606 , @rjmccall wrote:
>
> > There is no way in the existing ABI for copying a block to cause other 
> > references to the block to become references to the heap block.  We do do 
> > that for `__block` variables, but not for block objects themselves.
>
>
> Do you think thats worth doing? We could add a forwarding pointer to the end 
> of a block literal on the stack (after all the captures) and flip an unused 
> bit to track it, preserving ABI. Seems like now that we're delaying 
> `_Block_copy`ies this might be a bigger issue.


We've always delayed `_Block_copy` in a bunch of places.  Now we're just 
delaying it in a place that ARC used to be more conservative about.

I guess we could actually make forwarding work at some code-size cost 
(functions that emitted forwardable blocks would have to zero the forwarding 
slot and release it when destroying the stack copy).  But it'd just silently do 
nothing without a runtime update, so it'd be somewhat treacherous, especially 
after a couple of releases: e.g. if we made the runtime change in macOS 20 
Eugene O'Neill National Historic Site, and Chromium eventually only ran tests 
on macOS 20 and higher but still supported deploying to macOS 19 San Francisco 
Maritime National Historical Park, then Chromium might not catch that it was 
still necessary to include an explicit copy here.


Repository:
  rC Clang

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

https://reviews.llvm.org/D58514



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


[PATCH] D58896: Suppress -Wchar-subscripts if the index is a literal char

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

In D58896#1428816 , @edward-jones 
wrote:

> In D58896#1419964 , @aaron.ballman 
> wrote:
>
> > Do you have some evidence that the current behavior is causing a lot of 
> > false positives in the wild? For ASCII character literals, I can sort of 
> > guess at why people might want to do this, but for things like wide 
> > character literals, or character literals relying on the current code page, 
> > etc, I'm less convinced.
>
>
> I don't know about the false positive rate,  just the one report on twitter 
> which triggered me to submit this change. As for wide character literals I 
> was under the impression that they would be promoted to integers and wouldn't 
> have triggered the -Wchar-subscript anyway?


Ordinary character literals are promoted as well, aren't they? `'a'` has type 
`char`, and that should promote up to `int`. My point was that you are 
silencing the warning on any character literal, not just ordinary character 
literals. However, I see now that `-Wchar-subscript` is very serious about 
`char`, rather than any character type, so I guess you don't need to 
distinguish between character literal kinds because the type system already 
deals with that for you.

LGTM!


Repository:
  rC Clang

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

https://reviews.llvm.org/D58896



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


[PATCH] D59327: [Sema] Fix a use-after-free of a _Nonnull ParsedAttr

2019-03-14 Thread Phabricator via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rL356187: [Sema] Fix a use-after-free of a _Nonnull ParsedAttr 
(authored by epilk, committed by ).
Herald added a project: LLVM.
Herald added a subscriber: llvm-commits.

Changed prior to commit:
  https://reviews.llvm.org/D59327?vs=190489=190691#toc

Repository:
  rL LLVM

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

https://reviews.llvm.org/D59327

Files:
  cfe/trunk/lib/Sema/SemaType.cpp
  cfe/trunk/test/SemaObjC/nonnull.m


Index: cfe/trunk/lib/Sema/SemaType.cpp
===
--- cfe/trunk/lib/Sema/SemaType.cpp
+++ cfe/trunk/lib/Sema/SemaType.cpp
@@ -4221,7 +4221,7 @@
   auto inferPointerNullability =
   [&](SimplePointerKind pointerKind, SourceLocation pointerLoc,
   SourceLocation pointerEndLoc,
-  ParsedAttributesView ) -> ParsedAttr * {
+  ParsedAttributesView , AttributePool ) -> ParsedAttr * {
 // We've seen a pointer.
 if (NumPointersRemaining > 0)
   --NumPointersRemaining;
@@ -4235,11 +4235,9 @@
   ParsedAttr::Syntax syntax = inferNullabilityCS
   ? ParsedAttr::AS_ContextSensitiveKeyword
   : ParsedAttr::AS_Keyword;
-  ParsedAttr *nullabilityAttr =
-  state.getDeclarator().getAttributePool().create(
-  S.getNullabilityKeyword(*inferNullability),
-  SourceRange(pointerLoc), nullptr, SourceLocation(), nullptr, 0,
-  syntax);
+  ParsedAttr *nullabilityAttr = Pool.create(
+  S.getNullabilityKeyword(*inferNullability), SourceRange(pointerLoc),
+  nullptr, SourceLocation(), nullptr, 0, syntax);
 
   attrs.addAtEnd(nullabilityAttr);
 
@@ -4298,7 +4296,8 @@
 if (auto *attr = inferPointerNullability(
 pointerKind, D.getDeclSpec().getTypeSpecTypeLoc(),
 D.getDeclSpec().getEndLoc(),
-D.getMutableDeclSpec().getAttributes())) {
+D.getMutableDeclSpec().getAttributes(),
+D.getMutableDeclSpec().getAttributePool())) {
   T = state.getAttributedType(
   createNullabilityAttr(Context, *attr, *inferNullability), T, T);
 }
@@ -4338,7 +4337,8 @@
 
   // Handle pointer nullability.
   inferPointerNullability(SimplePointerKind::BlockPointer, DeclType.Loc,
-  DeclType.EndLoc, DeclType.getAttrs());
+  DeclType.EndLoc, DeclType.getAttrs(),
+  state.getDeclarator().getAttributePool());
 
   T = S.BuildBlockPointerType(T, D.getIdentifierLoc(), Name);
   if (DeclType.Cls.TypeQuals || LangOpts.OpenCL) {
@@ -4360,7 +4360,8 @@
 
   // Handle pointer nullability
   inferPointerNullability(SimplePointerKind::Pointer, DeclType.Loc,
-  DeclType.EndLoc, DeclType.getAttrs());
+  DeclType.EndLoc, DeclType.getAttrs(),
+  state.getDeclarator().getAttributePool());
 
   if (LangOpts.ObjC && T->getAs()) {
 T = Context.getObjCObjectPointerType(T);
@@ -4892,7 +4893,8 @@
 
   // Handle pointer nullability.
   inferPointerNullability(SimplePointerKind::MemberPointer, DeclType.Loc,
-  DeclType.EndLoc, DeclType.getAttrs());
+  DeclType.EndLoc, DeclType.getAttrs(),
+  state.getDeclarator().getAttributePool());
 
   if (SS.isInvalid()) {
 // Avoid emitting extra errors if we already errored on the scope.
Index: cfe/trunk/test/SemaObjC/nonnull.m
===
--- cfe/trunk/test/SemaObjC/nonnull.m
+++ cfe/trunk/test/SemaObjC/nonnull.m
@@ -125,3 +125,9 @@
 }
 
 void (^PR23117)(int *) = ^(int *p1) __attribute__((nonnull(1))) {};
+
+typedef int *intptr;
+#pragma clang assume_nonnull begin
+intptr a, b;
+intptr c, (*d)();
+#pragma clang assume_nonnull end


Index: cfe/trunk/lib/Sema/SemaType.cpp
===
--- cfe/trunk/lib/Sema/SemaType.cpp
+++ cfe/trunk/lib/Sema/SemaType.cpp
@@ -4221,7 +4221,7 @@
   auto inferPointerNullability =
   [&](SimplePointerKind pointerKind, SourceLocation pointerLoc,
   SourceLocation pointerEndLoc,
-  ParsedAttributesView ) -> ParsedAttr * {
+  ParsedAttributesView , AttributePool ) -> ParsedAttr * {
 // We've seen a pointer.
 if (NumPointersRemaining > 0)
   --NumPointersRemaining;
@@ -4235,11 +4235,9 @@
   ParsedAttr::Syntax syntax = inferNullabilityCS
   ? ParsedAttr::AS_ContextSensitiveKeyword
   : ParsedAttr::AS_Keyword;
-  ParsedAttr *nullabilityAttr =
-  state.getDeclarator().getAttributePool().create(
-

r356187 - [Sema] Fix a use-after-free of a _Nonnull ParsedAttr

2019-03-14 Thread Erik Pilkington via cfe-commits
Author: epilk
Date: Thu Mar 14 11:38:02 2019
New Revision: 356187

URL: http://llvm.org/viewvc/llvm-project?rev=356187=rev
Log:
[Sema] Fix a use-after-free of a _Nonnull ParsedAttr

We were allocating the implicit attribute in the declarator's attribute pool,
but putting into the declaration specifier's ParsedAttributesView. If there are
multiple declarators, then we'll use the attribute from the declaration
specifier after clearing out the declarators attribute pool. Fix this by
allocating the attribute in the declaration specifier's pool.

rdar://48529718

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

Modified:
cfe/trunk/lib/Sema/SemaType.cpp
cfe/trunk/test/SemaObjC/nonnull.m

Modified: cfe/trunk/lib/Sema/SemaType.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Sema/SemaType.cpp?rev=356187=356186=356187=diff
==
--- cfe/trunk/lib/Sema/SemaType.cpp (original)
+++ cfe/trunk/lib/Sema/SemaType.cpp Thu Mar 14 11:38:02 2019
@@ -4221,7 +4221,7 @@ static TypeSourceInfo *GetFullTypeForDec
   auto inferPointerNullability =
   [&](SimplePointerKind pointerKind, SourceLocation pointerLoc,
   SourceLocation pointerEndLoc,
-  ParsedAttributesView ) -> ParsedAttr * {
+  ParsedAttributesView , AttributePool ) -> ParsedAttr * {
 // We've seen a pointer.
 if (NumPointersRemaining > 0)
   --NumPointersRemaining;
@@ -4235,11 +4235,9 @@ static TypeSourceInfo *GetFullTypeForDec
   ParsedAttr::Syntax syntax = inferNullabilityCS
   ? ParsedAttr::AS_ContextSensitiveKeyword
   : ParsedAttr::AS_Keyword;
-  ParsedAttr *nullabilityAttr =
-  state.getDeclarator().getAttributePool().create(
-  S.getNullabilityKeyword(*inferNullability),
-  SourceRange(pointerLoc), nullptr, SourceLocation(), nullptr, 0,
-  syntax);
+  ParsedAttr *nullabilityAttr = Pool.create(
+  S.getNullabilityKeyword(*inferNullability), SourceRange(pointerLoc),
+  nullptr, SourceLocation(), nullptr, 0, syntax);
 
   attrs.addAtEnd(nullabilityAttr);
 
@@ -4298,7 +4296,8 @@ static TypeSourceInfo *GetFullTypeForDec
 if (auto *attr = inferPointerNullability(
 pointerKind, D.getDeclSpec().getTypeSpecTypeLoc(),
 D.getDeclSpec().getEndLoc(),
-D.getMutableDeclSpec().getAttributes())) {
+D.getMutableDeclSpec().getAttributes(),
+D.getMutableDeclSpec().getAttributePool())) {
   T = state.getAttributedType(
   createNullabilityAttr(Context, *attr, *inferNullability), T, T);
 }
@@ -4338,7 +4337,8 @@ static TypeSourceInfo *GetFullTypeForDec
 
   // Handle pointer nullability.
   inferPointerNullability(SimplePointerKind::BlockPointer, DeclType.Loc,
-  DeclType.EndLoc, DeclType.getAttrs());
+  DeclType.EndLoc, DeclType.getAttrs(),
+  state.getDeclarator().getAttributePool());
 
   T = S.BuildBlockPointerType(T, D.getIdentifierLoc(), Name);
   if (DeclType.Cls.TypeQuals || LangOpts.OpenCL) {
@@ -4360,7 +4360,8 @@ static TypeSourceInfo *GetFullTypeForDec
 
   // Handle pointer nullability
   inferPointerNullability(SimplePointerKind::Pointer, DeclType.Loc,
-  DeclType.EndLoc, DeclType.getAttrs());
+  DeclType.EndLoc, DeclType.getAttrs(),
+  state.getDeclarator().getAttributePool());
 
   if (LangOpts.ObjC && T->getAs()) {
 T = Context.getObjCObjectPointerType(T);
@@ -4892,7 +4893,8 @@ static TypeSourceInfo *GetFullTypeForDec
 
   // Handle pointer nullability.
   inferPointerNullability(SimplePointerKind::MemberPointer, DeclType.Loc,
-  DeclType.EndLoc, DeclType.getAttrs());
+  DeclType.EndLoc, DeclType.getAttrs(),
+  state.getDeclarator().getAttributePool());
 
   if (SS.isInvalid()) {
 // Avoid emitting extra errors if we already errored on the scope.

Modified: cfe/trunk/test/SemaObjC/nonnull.m
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/SemaObjC/nonnull.m?rev=356187=356186=356187=diff
==
--- cfe/trunk/test/SemaObjC/nonnull.m (original)
+++ cfe/trunk/test/SemaObjC/nonnull.m Thu Mar 14 11:38:02 2019
@@ -125,3 +125,9 @@ void PR18795_helper() {
 }
 
 void (^PR23117)(int *) = ^(int *p1) __attribute__((nonnull(1))) {};
+
+typedef int *intptr;
+#pragma clang assume_nonnull begin
+intptr a, b;
+intptr c, (*d)();
+#pragma clang assume_nonnull end


___
cfe-commits mailing list
cfe-commits@lists.llvm.org

[PATCH] D59377: Frontend: Remove CompilerInstance::VirtualFileSystem, NFC

2019-03-14 Thread Duncan P. N. Exon Smith via Phabricator via cfe-commits
dexonsmith created this revision.
Herald added subscribers: jdoerfert, kadircet, arphaman, jkorous.

Remove CompilerInstance::VirtualFileSystem and
CompilerInstance::setVirtualFileSystem, instead relying on the VFS in
the FileManager.  CompilerInstance and its clients already went to some
trouble to make these match.  Now they are guaranteed to match.

As part of this, I added a VFS parameter (defaults to nullptr) to
CompilerInstance::createFileManager to avoid repeating construction
logic in clients that just want to customize the VFS.


https://reviews.llvm.org/D59377

Files:
  clang-tools-extra/clangd/Compiler.cpp
  clang/include/clang/Frontend/CompilerInstance.h
  clang/lib/Frontend/ASTUnit.cpp
  clang/lib/Frontend/CompilerInstance.cpp
  clang/lib/StaticAnalyzer/Frontend/ModelInjector.cpp
  lldb/source/Plugins/ExpressionParser/Clang/ClangExpressionParser.cpp
  lldb/source/Plugins/ExpressionParser/Clang/ClangModulesDeclVendor.cpp

Index: lldb/source/Plugins/ExpressionParser/Clang/ClangModulesDeclVendor.cpp
===
--- lldb/source/Plugins/ExpressionParser/Clang/ClangModulesDeclVendor.cpp
+++ lldb/source/Plugins/ExpressionParser/Clang/ClangModulesDeclVendor.cpp
@@ -671,7 +671,7 @@
   }
 
   // Make sure clang uses the same VFS as LLDB.
-  instance->setVirtualFileSystem(FileSystem::Instance().GetVirtualFileSystem());
+  instance->createFileManager(FileSystem::Instance().GetVirtualFileSystem());
   instance->setDiagnostics(diagnostics_engine.get());
   instance->setInvocation(invocation);
 
Index: lldb/source/Plugins/ExpressionParser/Clang/ClangExpressionParser.cpp
===
--- lldb/source/Plugins/ExpressionParser/Clang/ClangExpressionParser.cpp
+++ lldb/source/Plugins/ExpressionParser/Clang/ClangExpressionParser.cpp
@@ -309,8 +309,7 @@
   }
 
   // Make sure clang uses the same VFS as LLDB.
-  m_compiler->setVirtualFileSystem(
-  FileSystem::Instance().GetVirtualFileSystem());
+  m_compiler->createFileManager(FileSystem::Instance().GetVirtualFileSystem());
 
   lldb::LanguageType frame_lang =
   expr.Language(); // defaults to lldb::eLanguageTypeUnknown
Index: clang/lib/StaticAnalyzer/Frontend/ModelInjector.cpp
===
--- clang/lib/StaticAnalyzer/Frontend/ModelInjector.cpp
+++ clang/lib/StaticAnalyzer/Frontend/ModelInjector.cpp
@@ -82,8 +82,6 @@
 
   Instance.getDiagnostics().setSourceManager();
 
-  Instance.setVirtualFileSystem(());
-
   // The instance wants to take ownership, however DisableFree frontend option
   // is set to true to avoid double free issues
   Instance.setFileManager(());
Index: clang/lib/Frontend/CompilerInstance.cpp
===
--- clang/lib/Frontend/CompilerInstance.cpp
+++ clang/lib/Frontend/CompilerInstance.cpp
@@ -89,10 +89,6 @@
 
 void CompilerInstance::setFileManager(FileManager *Value) {
   FileMgr = Value;
-  if (Value)
-VirtualFileSystem = Value->getVirtualFileSystem();
-  else
-VirtualFileSystem.reset();
 }
 
 void CompilerInstance::setSourceManager(SourceManager *Value) {
@@ -297,13 +293,13 @@
 
 // File Manager
 
-FileManager *CompilerInstance::createFileManager() {
-  if (!hasVirtualFileSystem()) {
-IntrusiveRefCntPtr VFS =
-createVFSFromCompilerInvocation(getInvocation(), getDiagnostics());
-setVirtualFileSystem(VFS);
-  }
-  FileMgr = new FileManager(getFileSystemOpts(), VirtualFileSystem);
+FileManager *CompilerInstance::createFileManager(
+IntrusiveRefCntPtr VFS) {
+  if (!VFS && FileMgr)
+VFS = FileMgr->getVirtualFileSystem(); // May be nullptr...
+  if (!VFS)
+VFS = createVFSFromCompilerInvocation(getInvocation(), getDiagnostics());
+  FileMgr = new FileManager(getFileSystemOpts(), std::move(VFS));
   return FileMgr.get();
 }
 
@@ -1101,8 +1097,6 @@
ImportingInstance.getDiagnosticClient()),
  /*ShouldOwnClient=*/true);
 
-  Instance.setVirtualFileSystem(());
-
   // Note that this module is part of the module build stack, so that we
   // can detect cycles in the module graph.
   Instance.setFileManager(());
Index: clang/lib/Frontend/ASTUnit.cpp
===
--- clang/lib/Frontend/ASTUnit.cpp
+++ clang/lib/Frontend/ASTUnit.cpp
@@ -1078,28 +1078,29 @@
   if (!Invocation)
 return true;
 
+  if (VFS && FileMgr)
+assert(VFS == FileMgr->getVirtualFileSystem() &&
+   "VFS passed to Parse and VFS in FileMgr are different");
+
   auto CCInvocation = std::make_shared(*Invocation);
   if (OverrideMainBuffer) {
 assert(Preamble &&
"No preamble was built, but OverrideMainBuffer is not null");
-IntrusiveRefCntPtr OldVFS = VFS;
 Preamble->AddImplicitPreamble(*CCInvocation, VFS, OverrideMainBuffer.get());
-if (OldVFS != VFS && FileMgr) {
-

[PATCH] D33841: [clang-tidy] redundant keyword check

2019-03-14 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman added inline comments.



Comment at: clang-tidy/readability/RedundantExternCheck.cpp:27
+void RedundantExternCheck::check(const MatchFinder::MatchResult ) {
+  auto* FD =
+  Result.Nodes.getNodeAs("redundant_extern");

Formatting is incorrect (elsewhere too). You should run the patch through 
clang-format.



Comment at: clang-tidy/readability/RedundantExternCheck.cpp:32
+
+  if(!(FD->getStorageClass() == SC_Extern))
+return;

`FD->getStorageClass() != SC_Extern`



Comment at: clang-tidy/readability/RedundantExternCheck.cpp:35
+
+  auto Diag = diag(FD->getBeginLoc(), "redundant 'extern' keyword");
+

How about "redundant 'extern' storage class specifier"?



Comment at: test/clang-tidy/readability-redundant-extern.cpp:37
+
+void another_file_scope(int _extern);

More tests that I figured out:
```
namespace {
extern void f(); // 'extern' is not redundant
}

namespace a {
namespace {
namespace b {
extern void f(); // 'extern' is not redundant
}
}
}

// Note, the above are consequences of http://eel.is/c++draft/basic.link#6

#define FOO_EXTERN extern
typedef int extern_int;

extern_int FOO_EXTERN foo(); // 'extern' is redundant, but hopefully we don't 
try to fixit this to be '_int FOO_EXTERN foo();'

// The above is a weird consequence of how specifiers are parsed in C and C++
```


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

https://reviews.llvm.org/D33841



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


[PATCH] D58514: Avoid needlessly copying blocks that initialize or are assigned to local auto variables to the heap

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

In D58514#1429662 , @wuhao5 wrote:

> > The specified user model of blocks is that they stay on the stack until 
> > they get copied, and there can be multiple such copies.  ARC just automates 
> > that process.  So the address of a block is not consistent before you've 
> > forced a copy.
> > 
> > I tend to agree that a better user model would have been for blocks to be 
> > allocated in one place, without any of this copying business, and for the 
> > compiler to make an intelligent decision about stack vs. heap based on how 
> > the block is used.  That's the model we've used for closures in Swift.  But 
> > that  would've required the compiler to have a better ability to propagate 
> > information about how the block was used, which Clang isn't really set up 
> > for, and it would've required `noescape` annotations to be introduced and 
> > used reliably throughout the SDK, which seemed like a big request at the 
> > time.  So it's not how it works.
> > 
> > There is no way in the existing ABI for copying a block to cause other 
> > references to the block to become references to the heap block.  We do do 
> > that for `__block` variables, but not for block objects themselves.
>
> I see - this makes sense. Right that I'd expect the compiler would know more 
> about where the block is being used and make the variable consistent. my 
> other worry is, although not realistically, that there can be other projects 
> to use this weak/strong pointer trick to do a recursive block invocation. it 
> becomes to me a bit counter-intuitive that I will need to know more about how 
> block and where it should be copied, which currently we don't have to worry 
> about it at all.
>
> Right now we force an explicit copy before using it, but still like to 
> request that this would be handled by Clang at some later point :)


Can I ask why you want a weak reference to a block in the first place?  It 
seems basically useless — blocks can certainly appear in reference cycles, but 
I don't know why you'd ever try to break that cycle with the block instead of 
somewhere else.


Repository:
  rC Clang

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

https://reviews.llvm.org/D58514



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


[PATCH] D59094: [ARM] Fix bug 39982 - pcs("aapcs-vfp") is not consistent

2019-03-14 Thread Eli Friedman via Phabricator via cfe-commits
efriedma added a comment.

Looking more carefully, I guess none of the other places actually distinguish 
between ARMABIInfo::AAPCS_VFP and ARMABIInfo::AAPCS, so I guess the current 
change is sufficient given the calling-convention attributes that are likely to 
be used in practice.

Please pull the IsEffectivelyAAPCS_VFP out into a separate helper function on 
ARMABIInfo.


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

https://reviews.llvm.org/D59094



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


[PATCH] D58514: Avoid needlessly copying blocks that initialize or are assigned to local auto variables to the heap

2019-03-14 Thread Hao Wu via Phabricator via cfe-commits
wuhao5 added a comment.

> The specified user model of blocks is that they stay on the stack until they 
> get copied, and there can be multiple such copies.  ARC just automates that 
> process.  So the address of a block is not consistent before you've forced a 
> copy.
> 
> I tend to agree that a better user model would have been for blocks to be 
> allocated in one place, without any of this copying business, and for the 
> compiler to make an intelligent decision about stack vs. heap based on how 
> the block is used.  That's the model we've used for closures in Swift.  But 
> that  would've required the compiler to have a better ability to propagate 
> information about how the block was used, which Clang isn't really set up 
> for, and it would've required `noescape` annotations to be introduced and 
> used reliably throughout the SDK, which seemed like a big request at the 
> time.  So it's not how it works.
> 
> There is no way in the existing ABI for copying a block to cause other 
> references to the block to become references to the heap block.  We do do 
> that for `__block` variables, but not for block objects themselves.

I see - this makes sense. Right that I'd expect the compiler would know more 
about where the block is being used and make the variable consistent. my other 
worry is, although not realistically, that there can be other projects to use 
this weak/strong pointer trick to do a recursive block invocation. it becomes 
to me a bit counter-intuitive that I will need to know more about how block and 
where it should be copied, which currently we don't have to worry about it at 
all.

Right now we force an explicit copy before using it, but still like to request 
that this would be handled by Clang at some later point :)


Repository:
  rC Clang

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

https://reviews.llvm.org/D58514



___
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-14 Thread Yitzhak Mandelbaum via Phabricator via cfe-commits
ymandel created this revision.
ymandel added a reviewer: ilya-biryukov.
Herald added subscribers: cfe-commits, jdoerfert, jfb, mgorny.
Herald added a project: clang.
ymandel added a parent revision: D59329: [LibTooling] Add NodeId, a strong type 
for AST-matcher node identifiers..

Adds a basic version of Transformer, a library supporting the concise 
specification of clang-based source-to-source transformations.  A full 
discussion of the end goal can be found on the cfe-dev list with subject "[RFC] 
Easier source-to-source transformations with clang tooling".


Repository:
  rG LLVM Github Monorepo

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,428 @@
+//===- 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 ::clang::ast_matchers::anyOf;
+using ::clang::ast_matchers::argumentCountIs;
+using ::clang::ast_matchers::callee;
+using ::clang::ast_matchers::callExpr;
+using ::clang::ast_matchers::cxxMemberCallExpr;
+using ::clang::ast_matchers::cxxMethodDecl;
+using ::clang::ast_matchers::cxxRecordDecl;
+using ::clang::ast_matchers::declRefExpr;
+using ::clang::ast_matchers::expr;
+using ::clang::ast_matchers::functionDecl;
+using ::clang::ast_matchers::hasAnyName;
+using ::clang::ast_matchers::hasArgument;
+using ::clang::ast_matchers::hasDeclaration;
+using ::clang::ast_matchers::hasElse;
+using ::clang::ast_matchers::hasName;
+using ::clang::ast_matchers::hasType;
+using ::clang::ast_matchers::ifStmt;
+using ::clang::ast_matchers::member;
+using ::clang::ast_matchers::memberExpr;
+using ::clang::ast_matchers::namedDecl;
+using ::clang::ast_matchers::on;
+using ::clang::ast_matchers::pointsTo;
+using ::clang::ast_matchers::to;
+using ::clang::ast_matchers::unless;
+
+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";
+} // namespace
+
+static clang::ast_matchers::internal::Matcher
+isOrPointsTo(const DeclarationMatcher ) {
+  return anyOf(hasDeclaration(TypeMatcher), pointsTo(TypeMatcher));
+}
+
+static std::string format(llvm::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(llvm::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(llvm::StringRef S) { FileContents[0].second += S; }
+
+  void addFile(llvm::StringRef Filename, llvm::StringRef Content) {
+FileContents.emplace_back(Filename, Content);
+  }
+
+  llvm::Optional rewrite(llvm::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: " << 

[PATCH] D58514: Avoid needlessly copying blocks that initialize or are assigned to local auto variables to the heap

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

In D58514#1429606 , @rjmccall wrote:

> There is no way in the existing ABI for copying a block to cause other 
> references to the block to become references to the heap block.  We do do 
> that for `__block` variables, but not for block objects themselves.


Do you think thats worth doing? We could add a forwarding pointer to the end of 
a block literal on the stack (after all the captures) and flip an unused bit to 
track it, preserving ABI. Seems like now that we're delaying `_Block_copy`ies 
this might be a bigger issue.


Repository:
  rC Clang

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

https://reviews.llvm.org/D58514



___
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-14 Thread Reid Kleckner via Phabricator via cfe-commits
rnk added inline comments.



Comment at: llvm/lib/Support/TimeProfiler.h:1
+//===- llvm/Support/TimeProfiler.h - Hierarchical Time Profiler -*- C++ 
-*-===//
+//

I applied this patch locally to try it, and I noticed this header should be in 
llvm/include/llvm/Support, not llvm/lib/Support.


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] D59347: [DebugInfo] Combine Trivial and NonTrivial flags

2019-03-14 Thread David Blaikie via Phabricator via cfe-commits
dblaikie added a comment.

Would it be simpler/better to revert all the FlagTrivial work? & use the 
FlagNonTrivial+composite type to imply trivial? (since FlagnonTrivial has been 
in-tree longer)


Repository:
  rC Clang

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

https://reviews.llvm.org/D59347



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


[PATCH] D58530: Add PragmaHandler for MSVC pragma execution_character_set

2019-03-14 Thread Reid Kleckner via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rL356185: Add PragmaHandler for MSVC pragma 
execution_character_set (authored by rnk, committed by ).
Herald added a project: LLVM.
Herald added a subscriber: llvm-commits.

Changed prior to commit:
  https://reviews.llvm.org/D58530?vs=189629=190684#toc

Repository:
  rL LLVM

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

https://reviews.llvm.org/D58530

Files:
  cfe/trunk/include/clang/Basic/DiagnosticLexKinds.td
  cfe/trunk/include/clang/Lex/PPCallbacks.h
  cfe/trunk/lib/Frontend/PrintPreprocessedOutput.cpp
  cfe/trunk/lib/Lex/Pragma.cpp
  cfe/trunk/test/Preprocessor/pragma_microsoft.c
  clang-tools-extra/trunk/pp-trace/PPCallbacksTracker.cpp
  clang-tools-extra/trunk/pp-trace/PPCallbacksTracker.h

Index: clang-tools-extra/trunk/pp-trace/PPCallbacksTracker.h
===
--- clang-tools-extra/trunk/pp-trace/PPCallbacksTracker.h
+++ clang-tools-extra/trunk/pp-trace/PPCallbacksTracker.h
@@ -134,6 +134,9 @@
  llvm::ArrayRef Ids) override;
   void PragmaWarningPush(clang::SourceLocation Loc, int Level) override;
   void PragmaWarningPop(clang::SourceLocation Loc) override;
+  void PragmaExecCharsetPush(clang::SourceLocation Loc,
+ clang::StringRef Str) override;
+  void PragmaExecCharsetPop(clang::SourceLocation Loc) override;
   void MacroExpands(const clang::Token ,
 const clang::MacroDefinition , clang::SourceRange Range,
 const clang::MacroArgs *Args) override;
Index: clang-tools-extra/trunk/pp-trace/PPCallbacksTracker.cpp
===
--- clang-tools-extra/trunk/pp-trace/PPCallbacksTracker.cpp
+++ clang-tools-extra/trunk/pp-trace/PPCallbacksTracker.cpp
@@ -297,6 +297,22 @@
   appendArgument("Loc", Loc);
 }
 
+// Callback invoked when a #pragma execution_character_set(push) directive
+// is read.
+void PPCallbacksTracker::PragmaExecCharsetPush(clang::SourceLocation Loc,
+   clang::StringRef Str) {
+  beginCallback("PragmaExecCharsetPush");
+  appendArgument("Loc", Loc);
+  appendArgument("Charset", Str);
+}
+
+// Callback invoked when a #pragma execution_character_set(pop) directive
+// is read.
+void PPCallbacksTracker::PragmaExecCharsetPop(clang::SourceLocation Loc) {
+  beginCallback("PragmaExecCharsetPop");
+  appendArgument("Loc", Loc);
+}
+
 // Called by Preprocessor::HandleMacroExpandedIdentifier when a
 // macro invocation is found.
 void
Index: cfe/trunk/lib/Lex/Pragma.cpp
===
--- cfe/trunk/lib/Lex/Pragma.cpp
+++ cfe/trunk/lib/Lex/Pragma.cpp
@@ -1368,6 +1368,70 @@
   }
 };
 
+/// "\#pragma execution_character_set(...)". MSVC supports this pragma only
+/// for "UTF-8". We parse it and ignore it if UTF-8 is provided and warn
+/// otherwise to avoid -Wunknown-pragma warnings.
+struct PragmaExecCharsetHandler : public PragmaHandler {
+  PragmaExecCharsetHandler() : PragmaHandler("execution_character_set") {}
+
+  void HandlePragma(Preprocessor , PragmaIntroducerKind Introducer,
+Token ) override {
+// Parse things like:
+// execution_character_set(push, "UTF-8")
+// execution_character_set(pop)
+SourceLocation DiagLoc = Tok.getLocation();
+PPCallbacks *Callbacks = PP.getPPCallbacks();
+
+PP.Lex(Tok);
+if (Tok.isNot(tok::l_paren)) {
+  PP.Diag(Tok, diag::warn_pragma_exec_charset_expected) << "(";
+  return;
+}
+
+PP.Lex(Tok);
+IdentifierInfo *II = Tok.getIdentifierInfo();
+
+if (II && II->isStr("push")) {
+  // #pragma execution_character_set( push[ , string ] )
+  PP.Lex(Tok);
+  if (Tok.is(tok::comma)) {
+PP.Lex(Tok);
+
+std::string ExecCharset;
+if (!PP.FinishLexStringLiteral(Tok, ExecCharset,
+   "pragma execution_character_set",
+   /*MacroExpansion=*/false))
+  return;
+
+// MSVC supports either of these, but nothing else.
+if (ExecCharset != "UTF-8" && ExecCharset != "utf-8") {
+  PP.Diag(Tok, diag::warn_pragma_exec_charset_push_invalid) << ExecCharset;
+  return;
+}
+  }
+  if (Callbacks)
+Callbacks->PragmaExecCharsetPush(DiagLoc, "UTF-8");
+} else if (II && II->isStr("pop")) {
+  // #pragma execution_character_set( pop )
+  PP.Lex(Tok);
+  if (Callbacks)
+Callbacks->PragmaExecCharsetPop(DiagLoc);
+} else {
+  PP.Diag(Tok, diag::warn_pragma_exec_charset_spec_invalid);
+  return;
+}
+
+if (Tok.isNot(tok::r_paren)) {
+  PP.Diag(Tok, diag::warn_pragma_exec_charset_expected) << ")";
+  return;
+}
+
+PP.Lex(Tok);
+if (Tok.isNot(tok::eod))
+  PP.Diag(Tok, 

[PATCH] D59371: [LibTooling] Add Stencil library for format-string style codegen.

2019-03-14 Thread Yitzhak Mandelbaum via Phabricator via cfe-commits
ymandel updated this revision to Diff 190683.
ymandel added a comment.

Build fixes.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D59371

Files:
  clang/include/clang/Tooling/Refactoring/Stencil.h
  clang/lib/Tooling/Refactoring/CMakeLists.txt
  clang/lib/Tooling/Refactoring/Stencil.cpp
  clang/unittests/Tooling/CMakeLists.txt
  clang/unittests/Tooling/StencilTest.cpp

Index: clang/unittests/Tooling/StencilTest.cpp
===
--- /dev/null
+++ clang/unittests/Tooling/StencilTest.cpp
@@ -0,0 +1,250 @@
+//===- unittest/Tooling/StencilTest.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/Stencil.h"
+#include "clang/ASTMatchers/ASTMatchers.h"
+#include "clang/Tooling/FixIt.h"
+#include "clang/Tooling/Tooling.h"
+#include "gmock/gmock.h"
+#include "gtest/gtest.h"
+
+namespace clang {
+namespace tooling {
+namespace {
+
+using ::clang::ast_matchers::compoundStmt;
+using ::clang::ast_matchers::decl;
+using ::clang::ast_matchers::declStmt;
+using ::clang::ast_matchers::expr;
+using ::clang::ast_matchers::hasAnySubstatement;
+using ::clang::ast_matchers::hasCondition;
+using ::clang::ast_matchers::hasDescendant;
+using ::clang::ast_matchers::hasElse;
+using ::clang::ast_matchers::hasInitializer;
+using ::clang::ast_matchers::hasName;
+using ::clang::ast_matchers::hasReturnValue;
+using ::clang::ast_matchers::hasSingleDecl;
+using ::clang::ast_matchers::hasThen;
+using ::clang::ast_matchers::ifStmt;
+using ::clang::ast_matchers::ignoringImplicit;
+using ::clang::ast_matchers::returnStmt;
+using ::clang::ast_matchers::stmt;
+using ::clang::ast_matchers::varDecl;
+
+using MatchResult = ::clang::ast_matchers::MatchFinder::MatchResult;
+
+using ::clang::tooling::stencil_generators::node;
+using ::clang::tooling::stencil_generators::text;
+
+using ::testing::Eq;
+
+// In tests, we can't directly match on llvm::Expected since its accessors
+// mutate the object. So, we collapse it to an Optional.
+llvm::Optional toOptional(llvm::Expected V) {
+  if (V)
+return *V;
+  ADD_FAILURE() << "Losing error in conversion to IsSomething: "
+<< llvm::toString(V.takeError());
+  return llvm::None;
+}
+
+// A very simple matcher for llvm::Optional values.
+MATCHER_P(IsSomething, ValueMatcher, "") {
+  if (!arg)
+return false;
+  return ::testing::ExplainMatchResult(ValueMatcher, *arg, result_listener);
+}
+
+// Create a valid translation-unit from a statement.
+std::string wrapSnippet(llvm::Twine StatementCode) {
+  return ("auto stencil_test_snippet = []{" + StatementCode + "};").str();
+}
+
+clang::ast_matchers::DeclarationMatcher
+wrapMatcher(const clang::ast_matchers::StatementMatcher ) {
+  return varDecl(hasName("stencil_test_snippet"),
+ hasDescendant(compoundStmt(hasAnySubstatement(Matcher;
+}
+
+struct TestMatch {
+  // The AST unit from which `result` is built. We bundle it because it backs
+  // the result. Users are not expected to access it.
+  std::unique_ptr AstUnit;
+  // The result to use in the test. References `ast_unit`.
+  MatchResult Result;
+};
+
+// Matches `Matcher` against the statement `StatementCode` and returns the
+// result. Handles putting the statement inside a function and modifying the
+// matcher correspondingly. `Matcher` should match `StatementCode` exactly --
+// that is, produce exactly one match.
+llvm::Optional
+matchStmt(llvm::Twine StatementCode,
+  clang::ast_matchers::StatementMatcher Matcher) {
+  auto AstUnit = buildASTFromCode(wrapSnippet(StatementCode));
+  if (AstUnit == nullptr) {
+ADD_FAILURE() << "AST construction failed";
+return llvm::None;
+  }
+  clang::ASTContext  = AstUnit->getASTContext();
+  auto Matches = clang::ast_matchers::match(wrapMatcher(Matcher), Context);
+  // We expect a single, exact match for the statement.
+  if (Matches.size() != 1) {
+ADD_FAILURE() << "Wrong number of matches: " << Matches.size();
+return llvm::None;
+  }
+  return TestMatch{std::move(AstUnit), MatchResult(Matches[0], )};
+}
+
+class StencilTest : public ::testing::Test {
+protected:
+  // Verifies that the given stencil fails when evaluated on a valid match
+  // result. Binds a statement to "stmt", a (non-member) ctor-initializer to
+  // "init", an expression to "expr" and a (nameless) declaration to "decl".
+  void testError(const Stencil ,
+ testing::Matcher Matcher) {
+using ::clang::ast_matchers::cxxConstructExpr;
+using ::clang::ast_matchers::cxxCtorInitializer;
+using ::clang::ast_matchers::hasDeclaration;
+using 

[clang-tools-extra] r356185 - Add PragmaHandler for MSVC pragma execution_character_set

2019-03-14 Thread Reid Kleckner via cfe-commits
Author: rnk
Date: Thu Mar 14 11:12:17 2019
New Revision: 356185

URL: http://llvm.org/viewvc/llvm-project?rev=356185=rev
Log:
Add PragmaHandler for MSVC pragma execution_character_set

__pragma(execution_character_set(push, "UTF-8")) is used in
TraceLoggingProvider.h. This commit implements a no-op handler for
compatability, similar to how the flag -fexec_charset is handled.

Patch by Matt Gardner!

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

Modified:
clang-tools-extra/trunk/pp-trace/PPCallbacksTracker.cpp
clang-tools-extra/trunk/pp-trace/PPCallbacksTracker.h

Modified: clang-tools-extra/trunk/pp-trace/PPCallbacksTracker.cpp
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/pp-trace/PPCallbacksTracker.cpp?rev=356185=356184=356185=diff
==
--- clang-tools-extra/trunk/pp-trace/PPCallbacksTracker.cpp (original)
+++ clang-tools-extra/trunk/pp-trace/PPCallbacksTracker.cpp Thu Mar 14 11:12:17 
2019
@@ -297,6 +297,22 @@ void PPCallbacksTracker::PragmaWarningPo
   appendArgument("Loc", Loc);
 }
 
+// Callback invoked when a #pragma execution_character_set(push) directive
+// is read.
+void PPCallbacksTracker::PragmaExecCharsetPush(clang::SourceLocation Loc,
+   clang::StringRef Str) {
+  beginCallback("PragmaExecCharsetPush");
+  appendArgument("Loc", Loc);
+  appendArgument("Charset", Str);
+}
+
+// Callback invoked when a #pragma execution_character_set(pop) directive
+// is read.
+void PPCallbacksTracker::PragmaExecCharsetPop(clang::SourceLocation Loc) {
+  beginCallback("PragmaExecCharsetPop");
+  appendArgument("Loc", Loc);
+}
+
 // Called by Preprocessor::HandleMacroExpandedIdentifier when a
 // macro invocation is found.
 void

Modified: clang-tools-extra/trunk/pp-trace/PPCallbacksTracker.h
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/pp-trace/PPCallbacksTracker.h?rev=356185=356184=356185=diff
==
--- clang-tools-extra/trunk/pp-trace/PPCallbacksTracker.h (original)
+++ clang-tools-extra/trunk/pp-trace/PPCallbacksTracker.h Thu Mar 14 11:12:17 
2019
@@ -134,6 +134,9 @@ public:
  llvm::ArrayRef Ids) override;
   void PragmaWarningPush(clang::SourceLocation Loc, int Level) override;
   void PragmaWarningPop(clang::SourceLocation Loc) override;
+  void PragmaExecCharsetPush(clang::SourceLocation Loc,
+ clang::StringRef Str) override;
+  void PragmaExecCharsetPop(clang::SourceLocation Loc) override;
   void MacroExpands(const clang::Token ,
 const clang::MacroDefinition , clang::SourceRange Range,
 const clang::MacroArgs *Args) override;


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


r356185 - Add PragmaHandler for MSVC pragma execution_character_set

2019-03-14 Thread Reid Kleckner via cfe-commits
Author: rnk
Date: Thu Mar 14 11:12:17 2019
New Revision: 356185

URL: http://llvm.org/viewvc/llvm-project?rev=356185=rev
Log:
Add PragmaHandler for MSVC pragma execution_character_set

__pragma(execution_character_set(push, "UTF-8")) is used in
TraceLoggingProvider.h. This commit implements a no-op handler for
compatability, similar to how the flag -fexec_charset is handled.

Patch by Matt Gardner!

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

Modified:
cfe/trunk/include/clang/Basic/DiagnosticLexKinds.td
cfe/trunk/include/clang/Lex/PPCallbacks.h
cfe/trunk/lib/Frontend/PrintPreprocessedOutput.cpp
cfe/trunk/lib/Lex/Pragma.cpp
cfe/trunk/test/Preprocessor/pragma_microsoft.c

Modified: cfe/trunk/include/clang/Basic/DiagnosticLexKinds.td
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Basic/DiagnosticLexKinds.td?rev=356185=356184=356185=diff
==
--- cfe/trunk/include/clang/Basic/DiagnosticLexKinds.td (original)
+++ cfe/trunk/include/clang/Basic/DiagnosticLexKinds.td Thu Mar 14 11:12:17 2019
@@ -506,6 +506,17 @@ def warn_pragma_warning_expected_number
   ExtWarn<"#pragma warning expected a warning number">,
   InGroup;
 
+// - #pragma execution_character_set(...)
+def warn_pragma_exec_charset_expected :
+  ExtWarn<"#pragma execution_character_set expected '%0'">,
+  InGroup;
+def warn_pragma_exec_charset_spec_invalid :
+  ExtWarn<"#pragma execution_character_set expected 'push' or 'pop'">,
+  InGroup;
+def warn_pragma_exec_charset_push_invalid :
+   ExtWarn<"#pragma execution_character_set invalid value '%0', only 'UTF-8' 
is supported">,
+   InGroup;
+
 def err__Pragma_malformed : Error<
   "_Pragma takes a parenthesized string literal">;
 def err_pragma_message_malformed : Error<

Modified: cfe/trunk/include/clang/Lex/PPCallbacks.h
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Lex/PPCallbacks.h?rev=356185=356184=356185=diff
==
--- cfe/trunk/include/clang/Lex/PPCallbacks.h (original)
+++ cfe/trunk/include/clang/Lex/PPCallbacks.h Thu Mar 14 11:12:17 2019
@@ -239,6 +239,14 @@ public:
   virtual void PragmaWarningPop(SourceLocation Loc) {
   }
 
+  /// Callback invoked when a \#pragma execution_character_set(push) directive
+  /// is read.
+  virtual void PragmaExecCharsetPush(SourceLocation Loc, StringRef Str) {}
+
+  /// Callback invoked when a \#pragma execution_character_set(pop) directive
+  /// is read.
+  virtual void PragmaExecCharsetPop(SourceLocation Loc) {}
+
   /// Callback invoked when a \#pragma clang assume_nonnull begin directive
   /// is read.
   virtual void PragmaAssumeNonNullBegin(SourceLocation Loc) {}
@@ -477,6 +485,16 @@ public:
 Second->PragmaWarningPop(Loc);
   }
 
+  void PragmaExecCharsetPush(SourceLocation Loc, StringRef Str) override {
+First->PragmaExecCharsetPush(Loc, Str);
+Second->PragmaExecCharsetPush(Loc, Str);
+  }
+
+  void PragmaExecCharsetPop(SourceLocation Loc) override {
+First->PragmaExecCharsetPop(Loc);
+Second->PragmaExecCharsetPop(Loc);
+  }
+
   void PragmaAssumeNonNullBegin(SourceLocation Loc) override {
 First->PragmaAssumeNonNullBegin(Loc);
 Second->PragmaAssumeNonNullBegin(Loc);

Modified: cfe/trunk/lib/Frontend/PrintPreprocessedOutput.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Frontend/PrintPreprocessedOutput.cpp?rev=356185=356184=356185=diff
==
--- cfe/trunk/lib/Frontend/PrintPreprocessedOutput.cpp (original)
+++ cfe/trunk/lib/Frontend/PrintPreprocessedOutput.cpp Thu Mar 14 11:12:17 2019
@@ -143,6 +143,8 @@ public:
  ArrayRef Ids) override;
   void PragmaWarningPush(SourceLocation Loc, int Level) override;
   void PragmaWarningPop(SourceLocation Loc) override;
+  void PragmaExecCharsetPush(SourceLocation Loc, StringRef Str) override;
+  void PragmaExecCharsetPop(SourceLocation Loc) override;
   void PragmaAssumeNonNullBegin(SourceLocation Loc) override;
   void PragmaAssumeNonNullEnd(SourceLocation Loc) override;
 
@@ -553,6 +555,24 @@ void PrintPPOutputPPCallbacks::PragmaWar
   setEmittedDirectiveOnThisLine();
 }
 
+void PrintPPOutputPPCallbacks::PragmaExecCharsetPush(SourceLocation Loc,
+ StringRef Str) {
+  startNewLineIfNeeded();
+  MoveToLine(Loc);
+  OS << "#pragma character_execution_set(push";
+  if (!Str.empty())
+OS << ", " << Str;
+  OS << ')';
+  setEmittedDirectiveOnThisLine();
+}
+
+void PrintPPOutputPPCallbacks::PragmaExecCharsetPop(SourceLocation Loc) {
+  startNewLineIfNeeded();
+  MoveToLine(Loc);
+  OS << "#pragma character_execution_set(pop)";
+  setEmittedDirectiveOnThisLine();
+}
+
 void PrintPPOutputPPCallbacks::
 PragmaAssumeNonNullBegin(SourceLocation Loc) {
   startNewLineIfNeeded();

Modified: cfe/trunk/lib/Lex/Pragma.cpp
URL: 

[PATCH] D56554: [ELF] Add '-z nognustack' opt to suppress emitting PT_GNU_STACK

2019-03-14 Thread Michał Górny via Phabricator via cfe-commits
mgorny updated this revision to Diff 190681.
mgorny marked 2 inline comments as done.
mgorny added a comment.
Herald added a project: LLVM.

Implemented @ruiu's suggestions.


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

https://reviews.llvm.org/D56554

Files:
  lld/ELF/Config.h
  lld/ELF/Driver.cpp
  lld/ELF/Writer.cpp
  lld/docs/ld.lld.1
  lld/test/ELF/gnustack.s

Index: lld/test/ELF/gnustack.s
===
--- lld/test/ELF/gnustack.s
+++ lld/test/ELF/gnustack.s
@@ -10,6 +10,9 @@
 # RUN: ld.lld %t1 -o %t -z noexecstack
 # RUN: llvm-readobj --program-headers -s %t | FileCheck --check-prefix=RW %s
 
+# RUN: ld.lld %t1 -o %t -z nognustack
+# RUN: llvm-readobj --program-headers -s %t | FileCheck --check-prefix=NOGNUSTACK %s
+
 # RW:  Type: PT_GNU_STACK
 # RW-NEXT: Offset: 0x0
 # RW-NEXT: VirtualAddress: 0x0
@@ -35,5 +38,7 @@
 # RWX-NEXT: ]
 # RWX-NEXT: Alignment: 0
 
+# NOGNUSTACK-NOT: Type: PT_GNU_STACK
+
 .globl _start
 _start:
Index: lld/docs/ld.lld.1
===
--- lld/docs/ld.lld.1
+++ lld/docs/ld.lld.1
@@ -578,6 +578,10 @@
 .Dv DF_1_NOOPEN
 flag to indicate that the object may not be opened by
 .Xr dlopen 3 .
+.It Cm nognustack
+Do not emit the
+.Dv PT_GNU_STACK
+segment.
 .It Cm norelro
 Do not indicate that portions of the object shold be mapped read-only
 after initial relocation processing.
Index: lld/ELF/Writer.cpp
===
--- lld/ELF/Writer.cpp
+++ lld/ELF/Writer.cpp
@@ -2019,14 +2019,16 @@
   if (OutputSection *Cmd = findSection(".openbsd.randomdata"))
 AddHdr(PT_OPENBSD_RANDOMIZE, Cmd->getPhdrFlags())->add(Cmd);
 
-  // PT_GNU_STACK is a special section to tell the loader to make the
-  // pages for the stack non-executable. If you really want an executable
-  // stack, you can pass -z execstack, but that's not recommended for
-  // security reasons.
-  unsigned Perm = PF_R | PF_W;
-  if (Config->ZExecstack)
-Perm |= PF_X;
-  AddHdr(PT_GNU_STACK, Perm)->p_memsz = Config->ZStackSize;
+  if (Config->ZGnustack != GnuStackKind::None) {
+// PT_GNU_STACK is a special section to tell the loader to make the
+// pages for the stack non-executable. If you really want an executable
+// stack, you can pass -z execstack, but that's not recommended for
+// security reasons.
+unsigned Perm = PF_R | PF_W;
+if (Config->ZGnustack == GnuStackKind::Exec)
+  Perm |= PF_X;
+AddHdr(PT_GNU_STACK, Perm)->p_memsz = Config->ZStackSize;
+  }
 
   // PT_OPENBSD_WXNEEDED is a OpenBSD-specific header to mark the executable
   // is expected to perform W^X violations, such as calling mprotect(2) or
Index: lld/ELF/Driver.cpp
===
--- lld/ELF/Driver.cpp
+++ lld/ELF/Driver.cpp
@@ -344,6 +344,20 @@
   return Default;
 }
 
+static GnuStackKind getZGnuStack(opt::InputArgList ) {
+  for (auto *Arg : Args.filtered_reverse(OPT_z)) {
+if (StringRef("execstack") == Arg->getValue())
+  return GnuStackKind::Exec;
+if (StringRef("noexecstack") == Arg->getValue())
+  return GnuStackKind::NoExec;
+if (StringRef("nognustack") == Arg->getValue())
+  return GnuStackKind::None;
+  }
+
+  // default
+  return GnuStackKind::NoExec;
+}
+
 static bool isKnownZFlag(StringRef S) {
   return S == "combreloc" || S == "copyreloc" || S == "defs" ||
  S == "execstack" || S == "global" || S == "hazardplt" ||
@@ -351,10 +365,11 @@
  S == "keep-text-section-prefix" || S == "lazy" || S == "muldefs" ||
  S == "nocombreloc" || S == "nocopyreloc" || S == "nodefaultlib" ||
  S == "nodelete" || S == "nodlopen" || S == "noexecstack" ||
- S == "nokeep-text-section-prefix" || S == "norelro" || S == "notext" ||
- S == "now" || S == "origin" || S == "relro" || S == "retpolineplt" ||
- S == "rodynamic" || S == "text" || S == "wxneeded" ||
- S.startswith("max-page-size=") || S.startswith("stack-size=");
+ S == "nognustack" || S == "nokeep-text-section-prefix" ||
+ S == "norelro" || S == "notext" || S == "now" || S == "origin" ||
+ S == "relro" || S == "retpolineplt" || S == "rodynamic" ||
+ S == "text" || S == "wxneeded" || S.startswith("max-page-size=") ||
+ S.startswith("stack-size=");
 }
 
 // Report an error for an unknown -z option.
@@ -873,8 +888,8 @@
   Args.hasFlag(OPT_warn_symbol_ordering, OPT_no_warn_symbol_ordering, true);
   Config->ZCombreloc = getZFlag(Args, "combreloc", "nocombreloc", true);
   Config->ZCopyreloc = getZFlag(Args, "copyreloc", "nocopyreloc", true);
-  Config->ZExecstack = getZFlag(Args, "execstack", "noexecstack", false);
   Config->ZGlobal = hasZOption(Args, "global");
+  Config->ZGnustack = getZGnuStack(Args);
   Config->ZHazardplt = hasZOption(Args, "hazardplt");
   Config->ZInitfirst = hasZOption(Args, 

[PATCH] D56554: [ELF] Add '-z nognustack' opt to suppress emitting PT_GNU_STACK

2019-03-14 Thread Michał Górny via Phabricator via cfe-commits
mgorny marked 5 inline comments as done.
mgorny added inline comments.



Comment at: ELF/Config.h:191
   bool ZGlobal;
+  GnuStackKind ZGnustack;
   bool ZHazardplt;

ruiu wrote:
> Members are (roughly) sorted alphabetically, so move this below the last 
> boolean member.
I don't really comprehend the sort key here but done ;-).



Comment at: ELF/Driver.cpp:369
  S == "nodelete" || S == "nodlopen" || S == "noexecstack" ||
+ S == "nognustack" ||
  S == "nokeep-text-section-prefix" || S == "norelro" || S == "notext" 
||

ruiu wrote:
> If you have clang-format, please run it on this file.
File or function? Because the former would add some irrelevant changes to the 
diff, so if at all, I'd rather do it separately. File I've kept unformatted to 
make the patch easier to read. I've reformatted it now.


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

https://reviews.llvm.org/D56554



___
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-14 Thread Yitzhak Mandelbaum via Phabricator via cfe-commits
ymandel updated this revision to Diff 190679.
ymandel added a comment.

"Revert" to original diff.  This undoes the previous diff, which associated 
with the wrong revision.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D59329

Files:
  clang/include/clang/Tooling/Refactoring/NodeId.h
  clang/lib/Tooling/Refactoring/CMakeLists.txt
  clang/lib/Tooling/Refactoring/NodeId.cpp

Index: clang/lib/Tooling/Refactoring/NodeId.cpp
===
--- /dev/null
+++ clang/lib/Tooling/Refactoring/NodeId.cpp
@@ -0,0 +1,27 @@
+//===--- NodeId.cpp - NodeId implementation -*- 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/Tooling/Refactoring/NodeId.h"
+#include 
+
+namespace clang {
+namespace tooling {
+
+// For guaranteeing unique ids on NodeId creation.
+static size_t nextId() {
+  // Start with a relatively high number to avoid bugs if the user mixes
+  // explicitly-numbered ids with those generated with `NextId()`. Similarly, we
+  // choose a number that allows generated ids to be easily recognized.
+  static std::atomic Next();
+  return Next.fetch_add(1, std::memory_order_relaxed);
+}
+
+NodeId::NodeId() : NodeId(nextId()) {}
+
+} // namespace tooling
+} // namespace clang
Index: clang/lib/Tooling/Refactoring/CMakeLists.txt
===
--- clang/lib/Tooling/Refactoring/CMakeLists.txt
+++ clang/lib/Tooling/Refactoring/CMakeLists.txt
@@ -12,6 +12,7 @@
   Rename/USRFinder.cpp
   Rename/USRFindingAction.cpp
   Rename/USRLocFinder.cpp
+  NodeId.cpp
 
   LINK_LIBS
   clangAST
Index: clang/include/clang/Tooling/Refactoring/NodeId.h
===
--- /dev/null
+++ clang/include/clang/Tooling/Refactoring/NodeId.h
@@ -0,0 +1,85 @@
+//===--- NodeId.h - NodeId class --*- 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
+//
+//===--===//
+///
+/// \file This file defines abstractions for the bound identifiers used in AST
+/// matchers.
+///
+//===--===//
+
+#ifndef LLVM_CLANG_TOOLING_REFACTOR_NODE_ID_H_
+#define LLVM_CLANG_TOOLING_REFACTOR_NODE_ID_H_
+
+#include "clang/ASTMatchers/ASTMatchFinder.h"
+#include "llvm/ADT/StringRef.h"
+#include 
+
+namespace clang {
+namespace tooling {
+
+/// A strong type for AST node identifiers.  The standard API uses StringRefs
+/// for identifiers.  The strong type allows us to distinguish ids from
+/// arbitrary text snippets in various APIs.
+class NodeId {
+public:
+  explicit NodeId(std::string Id) : Id(std::move(Id)) {}
+
+  /// Creates a NodeId whose name is based on \p Id. Guarantees that unique ids
+  /// map to unique NodeIds.
+  explicit NodeId(size_t Id) : Id("id" + std::to_string(Id)) {}
+
+  /// Creates a NodeId with a generated name. The name is guaranteed to be
+  /// unique with respect to other generated names.
+  NodeId();
+
+  llvm::StringRef id() const { return Id; }
+
+  /// Gets the AST node in \p Result corresponding to this NodeId, if
+  /// any. Otherwise, returns null.
+  template 
+  const Node *
+  getNodeAs(const ast_matchers::MatchFinder::MatchResult ) const {
+return Result.Nodes.getNodeAs(Id);
+  }
+
+private:
+  std::string Id;
+};
+
+/// Refinement of NodeId that identifies the intended node type for the id. This
+/// additional information allows us to select appropriate overloads or
+/// constrain use of various combinators. It also allows us to distinguish when
+/// a \c Expr node is intended as a \c Stmt, which influences the intended
+/// source range for the node.  \p Node is the AST node type corresponding to
+/// this id.
+template  class TypedNodeId : public NodeId {
+public:
+  using NodeId::NodeId;
+  using MatcherType = ast_matchers::internal::Matcher;
+
+  /// Creates a matcher corresponding to the AST-node type of this id and bound
+  /// to this id. Intended for settings where the type of matcher is
+  /// obvious/uninteresting. For example,
+  ///
+  ///   ExprId Arg;
+  ///   auto Matcher = callExpr(callee(isFunctionNamed("foo")),
+  ///   hasArgument(0, Arg.bind()));
+  MatcherType bind() const {
+return ast_matchers::internal::BindableMatcher(
+   ast_matchers::internal::TrueMatcher())
+.bind(id());
+  }
+};
+
+using 

[PATCH] D58514: Avoid needlessly copying blocks that initialize or are assigned to local auto variables to the heap

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

In D58514#1429514 , @wuhao5 wrote:

> Hey guys, this is Hao, I am working with Chrome team to sort this issue out.
>
> In D58514#1428606 , @rjmccall wrote:
>
> > I remember this coming up 7-8 years ago.  I intentionally decided against 
> > doing a copy/release when assigning to `__weak` because if the block wasn't 
> > already guaranteed to be copied then it was probably better to crash than 
> > to silently assign a value that's about to be deallocated.  Note that 
> > copying the block we assign into `wb` doesn't change anything about the 
> > block stored in `b`.
> >
> > I don't know why Chromium is building a weak reference to a block in the 
> > first place, but assuming they have a good reason to be doing it, they 
> > should fix their code to force a copy before forming a weak reference.
>
>
> The culprit code is here 
> 
>
> it's true that it can be copied before assigning to the weak var, and I 
> understand the reasoning behind. however, my question is: just from the code 
> itself, each variable has the proper scope and assignment, if the block copy 
> happen automatically, just like what we should expect ARC would do, should it 
> not mutate itself to something else. to be more precise, should the block 
> assigned to the weak var be the same after the block is copied? (and in the 
> code, the block should be moved to the heap after calling -addObject: a few 
> line below.)
>
> so in the end of day, as a user, should we expect the compiler would move the 
> block from stack to heap in time and the variable we hold is consistent?


The specified user model of blocks is that they stay on the stack until they 
get copied, and there can be multiple such copies.  ARC just automates that 
process.  So the address of a block is not consistent before you've forced a 
copy.

I tend to agree that a better user model would have been for blocks to be 
allocated in one place, without any of this copying business, and for the 
compiler to make an intelligent decision about stack vs. heap based on how the 
block is used.  That's the model we've used for closures in Swift.  But that  
would've required the compiler to have a better ability to propagate 
information about how the block was used, which Clang isn't really set up for, 
and it would've required `noescape` annotations to be introduced and used 
reliably throughout the SDK, which seemed like a big request at the time.  So 
it's not how it works.

There is no way in the existing ABI for copying a block to cause other 
references to the block to become references to the heap block.  We do do that 
for `__block` variables, but not for block objects themselves.


Repository:
  rC Clang

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

https://reviews.llvm.org/D58514



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


[PATCH] D55044: [clang-tidy] check for Abseil make_unique

2019-03-14 Thread Andy Zhang via Phabricator via cfe-commits
axzhang updated this revision to Diff 190676.
axzhang added a comment.

Updated diff with full context.


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

https://reviews.llvm.org/D55044

Files:
  clang-tidy/abseil/AbseilTidyModule.cpp
  clang-tidy/modernize/MakeSmartPtrCheck.cpp
  clang-tidy/modernize/MakeSmartPtrCheck.h
  docs/ReleaseNotes.rst
  docs/clang-tidy/checks/abseil-make-unique.rst
  docs/clang-tidy/checks/list.rst
  docs/clang-tidy/checks/modernize-make-unique.rst
  test/clang-tidy/abseil-make-unique.cpp

Index: test/clang-tidy/abseil-make-unique.cpp
===
--- /dev/null
+++ test/clang-tidy/abseil-make-unique.cpp
@@ -0,0 +1,127 @@
+// RUN: %check_clang_tidy %s abseil-make-unique %t -- -- -std=c++11 \
+
+namespace std {
+
+template 
+class default_delete {};
+
+template >
+class unique_ptr {
+public:
+  unique_ptr() {}
+  unique_ptr(type *ptr) {}
+  unique_ptr(const unique_ptr ) = delete;
+  unique_ptr(unique_ptr &) {}
+  ~unique_ptr() {}
+  type *() { return *ptr; }
+  type *operator->() { return ptr; }
+  type *release() { return ptr; }
+  void reset() {}
+  void reset(type *pt) {}
+  void reset(type pt) {}
+  unique_ptr =(unique_ptr &&) { return *this; }
+  template 
+  unique_ptr =(unique_ptr &&) { return *this; }
+
+private:
+  type *ptr;
+};
+
+}  // namespace std
+
+class A {
+ int x;
+ int y;
+
+ public:
+   A(int _x, int _y): x(_x), y(_y) {}
+};
+
+struct Base {
+  Base();
+};
+
+struct Derived : public Base {
+  Derived();
+};
+
+int* returnPointer();
+void expectPointer(std::unique_ptr p);
+
+std::unique_ptr makeAndReturnPointer() {
+  return std::unique_ptr(new int(0));
+  // CHECK-MESSAGES: :[[@LINE-1]]:10: warning: use absl::make_unique instead [abseil-make-unique]
+  // CHECK-FIXES: return absl::make_unique(0);
+}
+
+void Positives() {
+  std::unique_ptr P1 = std::unique_ptr(new int(1));
+  // CHECK-MESSAGES: :[[@LINE-1]]:29: warning: use absl::make_unique instead [abseil-make-unique]
+  // CHECK-FIXES: std::unique_ptr P1 = absl::make_unique(1);
+
+  P1.reset(new int(2));
+  // CHECK-MESSAGES: :[[@LINE-1]]:6: warning: use absl::make_unique instead [abseil-make-unique]
+  // CHECK-FIXES: P1 = absl::make_unique(2);
+
+  // Non-primitive paramter
+  std::unique_ptr P2 = std::unique_ptr(new A(1, 2));
+  // CHECK-MESSAGES: :[[@LINE-1]]:27: warning: use absl::make_unique instead [abseil-make-unique]
+  // CHECK-FIXES: std::unique_ptr P2 = absl::make_unique(1, 2);
+
+  P2.reset(new A(3, 4));
+  // CHECK-MESSAGES: :[[@LINE-1]]:6: warning: use absl::make_unique instead [abseil-make-unique]
+  // CHECK-FIXES: P2 = absl::make_unique(3, 4);
+
+  // No arguments to new expression
+  std::unique_ptr P3 = std::unique_ptr(new int);
+  // CHECK-MESSAGES: :[[@LINE-1]]:29: warning: use absl::make_unique instead [abseil-make-unique]
+  // CHECK-FIXES: std::unique_ptr P3 = absl::make_unique();
+
+  P3.reset(new int);
+  // CHECK-MESSAGES: :[[@LINE-1]]:6: warning: use absl::make_unique instead [abseil-make-unique]
+  // CHECK-FIXES: P3 = absl::make_unique();
+
+  // Nested parentheses
+  std::unique_ptr P4 = std::unique_ptr((new int(3)));
+  // CHECK-MESSAGES: :[[@LINE-1]]:29: warning: use absl::make_unique instead [abseil-make-unique]
+  // CHECK-FIXES: std::unique_ptr P4 = absl::make_unique(3);
+
+  P4 = std::unique_ptr(((new int(4;
+  // CHECK-MESSAGES: :[[@LINE-1]]:8: warning: use absl::make_unique instead [abseil-make-unique]
+  // CHECK-FIXES: P4 = absl::make_unique(4);
+
+  P4.reset((new int(5)));
+  // CHECK-MESSAGES: :[[@LINE-1]]:6: warning: use absl::make_unique instead [abseil-make-unique]
+  // CHECK-FIXES: P4 = absl::make_unique(5);
+
+  // With auto
+  auto P5 = std::unique_ptr(new int());
+  // CHECK-MESSAGES: :[[@LINE-1]]:13: warning: use absl::make_unique instead [abseil-make-unique]
+  // CHECK-FIXES: auto P5 = absl::make_unique();
+
+  {
+// No std
+using namespace std;
+unique_ptr Q = unique_ptr(new int());
+// CHECK-MESSAGES: :[[@LINE-1]]:25: warning: use absl::make_unique instead [abseil-make-unique]
+// CHECK-FIXES: unique_ptr Q = absl::make_unique();
+
+Q = unique_ptr(new int());
+// CHECK-MESSAGES: :[[@LINE-1]]:9: warning: use absl::make_unique instead [abseil-make-unique]
+// CHECK-FIXES: Q = absl::make_unique();
+  }
+
+  // Create the unique_ptr as a parameter to a function
+  expectPointer(std::unique_ptr(new int()));
+  // CHECK-MESSAGES: :[[@LINE-1]]:17: warning: use absl::make_unique instead [abseil-make-unique]
+  // CHECK-FIXES: expectPointer(absl::make_unique());
+}
+
+void Negatives() {
+  // Only warn if explicitly allocating a new object
+  std::unique_ptr R = std::unique_ptr(returnPointer());
+  R.reset(returnPointer());
+
+  // Only replace if the template type is same as new type
+  auto Pderived = std::unique_ptr(new Derived());
+}
Index: docs/clang-tidy/checks/modernize-make-unique.rst

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

2019-03-14 Thread Yitzhak Mandelbaum via Phabricator via cfe-commits
ymandel updated this revision to Diff 190675.
ymandel added a comment.
Herald added a subscriber: jdoerfert.

Build-related fixes.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D59329

Files:
  clang/include/clang/Tooling/Refactoring/NodeId.h
  clang/include/clang/Tooling/Refactoring/Stencil.h
  clang/lib/Tooling/Refactoring/CMakeLists.txt
  clang/lib/Tooling/Refactoring/NodeId.cpp
  clang/lib/Tooling/Refactoring/Stencil.cpp
  clang/unittests/Tooling/CMakeLists.txt
  clang/unittests/Tooling/StencilTest.cpp

Index: clang/unittests/Tooling/StencilTest.cpp
===
--- /dev/null
+++ clang/unittests/Tooling/StencilTest.cpp
@@ -0,0 +1,250 @@
+//===- unittest/Tooling/StencilTest.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/Stencil.h"
+#include "clang/ASTMatchers/ASTMatchers.h"
+#include "clang/Tooling/FixIt.h"
+#include "clang/Tooling/Tooling.h"
+#include "gmock/gmock.h"
+#include "gtest/gtest.h"
+
+namespace clang {
+namespace tooling {
+namespace {
+
+using ::clang::ast_matchers::compoundStmt;
+using ::clang::ast_matchers::decl;
+using ::clang::ast_matchers::declStmt;
+using ::clang::ast_matchers::expr;
+using ::clang::ast_matchers::hasAnySubstatement;
+using ::clang::ast_matchers::hasCondition;
+using ::clang::ast_matchers::hasDescendant;
+using ::clang::ast_matchers::hasElse;
+using ::clang::ast_matchers::hasInitializer;
+using ::clang::ast_matchers::hasName;
+using ::clang::ast_matchers::hasReturnValue;
+using ::clang::ast_matchers::hasSingleDecl;
+using ::clang::ast_matchers::hasThen;
+using ::clang::ast_matchers::ifStmt;
+using ::clang::ast_matchers::ignoringImplicit;
+using ::clang::ast_matchers::returnStmt;
+using ::clang::ast_matchers::stmt;
+using ::clang::ast_matchers::varDecl;
+
+using MatchResult = ::clang::ast_matchers::MatchFinder::MatchResult;
+
+using ::clang::tooling::stencil_generators::node;
+using ::clang::tooling::stencil_generators::text;
+
+using ::testing::Eq;
+
+// In tests, we can't directly match on llvm::Expected since its accessors
+// mutate the object. So, we collapse it to an Optional.
+llvm::Optional toOptional(llvm::Expected V) {
+  if (V)
+return *V;
+  ADD_FAILURE() << "Losing error in conversion to IsSomething: "
+<< llvm::toString(V.takeError());
+  return llvm::None;
+}
+
+// A very simple matcher for llvm::Optional values.
+MATCHER_P(IsSomething, ValueMatcher, "") {
+  if (!arg)
+return false;
+  return ::testing::ExplainMatchResult(ValueMatcher, *arg, result_listener);
+}
+
+// Create a valid translation-unit from a statement.
+std::string wrapSnippet(llvm::Twine StatementCode) {
+  return ("auto stencil_test_snippet = []{" + StatementCode + "};").str();
+}
+
+clang::ast_matchers::DeclarationMatcher
+wrapMatcher(const clang::ast_matchers::StatementMatcher ) {
+  return varDecl(hasName("stencil_test_snippet"),
+ hasDescendant(compoundStmt(hasAnySubstatement(Matcher;
+}
+
+struct TestMatch {
+  // The AST unit from which `result` is built. We bundle it because it backs
+  // the result. Users are not expected to access it.
+  std::unique_ptr AstUnit;
+  // The result to use in the test. References `ast_unit`.
+  MatchResult Result;
+};
+
+// Matches `Matcher` against the statement `StatementCode` and returns the
+// result. Handles putting the statement inside a function and modifying the
+// matcher correspondingly. `Matcher` should match `StatementCode` exactly --
+// that is, produce exactly one match.
+llvm::Optional
+matchStmt(llvm::Twine StatementCode,
+  clang::ast_matchers::StatementMatcher Matcher) {
+  auto AstUnit = buildASTFromCode(wrapSnippet(StatementCode));
+  if (AstUnit == nullptr) {
+ADD_FAILURE() << "AST construction failed";
+return llvm::None;
+  }
+  clang::ASTContext  = AstUnit->getASTContext();
+  auto Matches = clang::ast_matchers::match(wrapMatcher(Matcher), Context);
+  // We expect a single, exact match for the statement.
+  if (Matches.size() != 1) {
+ADD_FAILURE() << "Wrong number of matches: " << Matches.size();
+return llvm::None;
+  }
+  return TestMatch{std::move(AstUnit), MatchResult(Matches[0], )};
+}
+
+class StencilTest : public ::testing::Test {
+protected:
+  // Verifies that the given stencil fails when evaluated on a valid match
+  // result. Binds a statement to "stmt", a (non-member) ctor-initializer to
+  // "init", an expression to "expr" and a (nameless) declaration to "decl".
+  void testError(const Stencil ,
+ testing::Matcher Matcher) {
+using 

[PATCH] D59316: [HIP-Clang] propagate -mllvm options to opt and llc

2019-03-14 Thread Yaxun Liu via Phabricator via cfe-commits
yaxunl accepted this revision.
yaxunl added a comment.
This revision is now accepted and ready to land.

LGTM. Thanks!


Repository:
  rC Clang

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

https://reviews.llvm.org/D59316



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


[PATCH] D59316: [HIP-Clang] propagate -mllvm options to opt and llc

2019-03-14 Thread Yaxun Liu via Phabricator via cfe-commits
yaxunl added a comment.

Here we are looking at the code which emulates a "linker" for HIP toolchain. 
The offloading action builder requests the offloading toolchain have a linker, 
but amdgpu does not have a real linker (ISA level linker), so we have to 
emulate that. If we have an ISA level linker we can get rid of all these stuff, 
but I don't think that will happen in short time.


Repository:
  rC Clang

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

https://reviews.llvm.org/D59316



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


[PATCH] D58579: [Sema] SequenceChecker: C++17 sequencing rule for call expression.

2019-03-14 Thread Bruno Ricci via Phabricator via cfe-commits
riccibruno updated this revision to Diff 190671.
riccibruno added a comment.

Don't visit the pre-argument expression(s). A pre-argument expression is only 
present for `CUDAKernelCallExpr`, and it is just a `CallExpr` for the 
configuration call, which I don't think we need to visit. This makes the usage 
of CallExpr::arguments() possible and results in cleaner code.


Repository:
  rC Clang

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

https://reviews.llvm.org/D58579

Files:
  lib/Sema/SemaChecking.cpp
  test/SemaCXX/warn-unsequenced.cpp


Index: test/SemaCXX/warn-unsequenced.cpp
===
--- test/SemaCXX/warn-unsequenced.cpp
+++ test/SemaCXX/warn-unsequenced.cpp
@@ -15,7 +15,6 @@
   int n;
 };
 
-// TODO: Implement the C++17 sequencing rules.
 void test() {
   int a;
   int xs[10];
@@ -256,6 +255,17 @@
   p[i++] = (i = 42); // cxx11-warning {{multiple unsequenced modifications to 
'i'}}
   p++[i++] = (i = p ? i++ : i++); // cxx11-warning {{unsequenced modification 
and access to 'p'}}
   // cxx11-warning@-1 {{multiple unsequenced 
modifications to 'i'}}
+
+  (i++, f)(i++, 42); // cxx11-warning {{multiple unsequenced modifications to 
'i'}}
+  (i++ + i++, f)(42, 42); // cxx11-warning {{multiple unsequenced 
modifications to 'i'}}
+  // cxx17-warning@-1 {{multiple unsequenced 
modifications to 'i'}}
+  int (*pf)(int, int);
+  (pf = f)(pf != nullptr, pf != nullptr); // cxx11-warning {{unsequenced 
modification and access to 'pf'}}
+  pf((pf = f) != nullptr, 42); // cxx11-warning {{unsequenced modification and 
access to 'pf'}}
+  f((pf = f, 42), (pf = f, 42)); // cxx11-warning {{multiple unsequenced 
modifications to 'pf'}}
+ // cxx17-warning@-1 {{multiple unsequenced 
modifications to 'pf'}}
+  pf((pf = f) != nullptr, pf == nullptr); // cxx11-warning {{unsequenced 
modification and access to 'pf'}}
+  // cxx17-warning@-1 {{unsequenced 
modification and access to 'pf'}}
 }
 
 namespace members {
Index: lib/Sema/SemaChecking.cpp
===
--- lib/Sema/SemaChecking.cpp
+++ lib/Sema/SemaChecking.cpp
@@ -12529,6 +12529,11 @@
   }
 
   void VisitCallExpr(const CallExpr *CE) {
+// FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions.
+
+if (CE->isUnevaluatedBuiltinCall(Context))
+  return;
+
 // C++11 [intro.execution]p15:
 //   When calling a function [...], every value computation and side effect
 //   associated with any argument expression, or with the postfix 
expression
@@ -12536,9 +12541,40 @@
 //   expression or statement in the body of the function [and thus before
 //   the value computation of its result].
 SequencedSubexpression Sequenced(*this);
-Base::VisitCallExpr(CE);
 
-// FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions.
+// C++17 [expr.call]p5
+//   The postfix-expression is sequenced before each expression in the
+//   expression-list and any default argument. [...]
+SequenceTree::Seq CalleeRegion;
+SequenceTree::Seq OtherRegion;
+if (SemaRef.getLangOpts().CPlusPlus17) {
+  CalleeRegion = Tree.allocate(Region);
+  OtherRegion = Tree.allocate(Region);
+} else {
+  CalleeRegion = Region;
+  OtherRegion = Region;
+}
+SequenceTree::Seq OldRegion = Region;
+
+// Visit the callee expression first.
+Region = CalleeRegion;
+if (SemaRef.getLangOpts().CPlusPlus17) {
+  SequencedSubexpression Sequenced(*this);
+  Visit(CE->getCallee());
+} else {
+  Visit(CE->getCallee());
+}
+
+// Then visit the argument expressions.
+Region = OtherRegion;
+for (const Expr *Argument : CE->arguments())
+  Visit(Argument);
+
+Region = OldRegion;
+if (SemaRef.getLangOpts().CPlusPlus17) {
+  Tree.merge(CalleeRegion);
+  Tree.merge(OtherRegion);
+}
   }
 
   void VisitCXXConstructExpr(const CXXConstructExpr *CCE) {


Index: test/SemaCXX/warn-unsequenced.cpp
===
--- test/SemaCXX/warn-unsequenced.cpp
+++ test/SemaCXX/warn-unsequenced.cpp
@@ -15,7 +15,6 @@
   int n;
 };
 
-// TODO: Implement the C++17 sequencing rules.
 void test() {
   int a;
   int xs[10];
@@ -256,6 +255,17 @@
   p[i++] = (i = 42); // cxx11-warning {{multiple unsequenced modifications to 'i'}}
   p++[i++] = (i = p ? i++ : i++); // cxx11-warning {{unsequenced modification and access to 'p'}}
   // cxx11-warning@-1 {{multiple unsequenced modifications to 'i'}}
+
+  (i++, f)(i++, 42); // cxx11-warning {{multiple unsequenced modifications to 'i'}}
+  (i++ + i++, f)(42, 42); // cxx11-warning {{multiple unsequenced modifications to 'i'}}
+  // cxx17-warning@-1 {{multiple unsequenced modifications to 

[PATCH] D59336: [clang-tidy] Disable google-runtime-int in Objective-C++ 

2019-03-14 Thread Roman Lebedev via Phabricator via cfe-commits
lebedev.ri added a comment.

In D59336#1429564 , @aaron.ballman 
wrote:

> This is missing test cases that demonstrate the behavior is what we expect it 
> to be for ObjC++ code vs C++ code.


Looks like phab has again consumed the email comments.
Might be a good idea to add the backlogged test coverage too.

https://lists.llvm.org/pipermail/cfe-commits/Week-of-Mon-20190311/264471.html

>> test?
> 
> I was uncertain whether or not this change required new tests. A previous 
> change which disabled this check in languages other than C++ did not include 
> additional tests:
>  
> https://github.com/llvm/llvm-project/commit/ec3e5d6fd87862eb77a2b0320d79b9a4427d39df#diff-a491be84e1b831aeaea56c39b5eb898c
>  If there is a preference to add tests for this change, I can do so.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D59336



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


[PATCH] D59336: [clang-tidy] Disable google-runtime-int in Objective-C++ 

2019-03-14 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman requested changes to this revision.
aaron.ballman added a comment.
This revision now requires changes to proceed.

This is missing test cases that demonstrate the behavior is what we expect it 
to be for ObjC++ code vs C++ code.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D59336



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


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

2019-03-14 Thread Bruno Ricci via Phabricator via cfe-commits
riccibruno added a comment.

Added some context in the description of the patch. 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] D58514: Avoid needlessly copying blocks that initialize or are assigned to local auto variables to the heap

2019-03-14 Thread Hao Wu via Phabricator via cfe-commits
wuhao5 added a comment.

Hey guys, this is Hao, I am working with Chrome team to sort this issue out.

In D58514#1428606 , @rjmccall wrote:

> I remember this coming up 7-8 years ago.  I intentionally decided against 
> doing a copy/release when assigning to `__weak` because if the block wasn't 
> already guaranteed to be copied then it was probably better to crash than to 
> silently assign a value that's about to be deallocated.  Note that copying 
> the block we assign into `wb` doesn't change anything about the block stored 
> in `b`.
>
> I don't know why Chromium is building a weak reference to a block in the 
> first place, but assuming they have a good reason to be doing it, they should 
> fix their code to force a copy before forming a weak reference.


The culprit code is here 


it's true that it can be copied before assigning to the weak var, and I 
understand the reasoning behind. however, my question is: just from the code 
itself, each variable has the proper scope and assignment, if the block copy 
happen automatically, just like what we should expect ARC would do, should it 
not mutate itself to something else. to be more precise, should the block 
assigned to the weak var be the same after the block is copied? (and in the 
code, the block should be moved to the heap after calling -addObject: a few 
line below.)

so in the end of day, as a user, should we expect the compiler would move the 
block from stack to heap in time and the variable we hold is consistent?


Repository:
  rC Clang

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

https://reviews.llvm.org/D58514



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


[PATCH] D59371: [LibTooling] Add Stencil library for format-string style codegen.

2019-03-14 Thread Yitzhak Mandelbaum via Phabricator via cfe-commits
ymandel created this revision.
ymandel added a reviewer: ilya-biryukov.
ymandel added a project: clang.
Herald added subscribers: jdoerfert, jfb, mgorny.

This file defines the *Stencil* abstraction: a code-generating object, 
parameterized by named references to (bound) AST nodes.  Given a match result, 
a stencil can be evaluated to a string of source code.

A stencil is similar in spirit to a format string: it is composed of a series 
of raw text strings, references to nodes (the parameters) and helper 
code-generation operations.

See thread on cfe-dev list with subject "[RFC] Easier source-to-source 
transformations with clang tooling" for background.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D59371

Files:
  clang/include/clang/Tooling/Refactoring/Stencil.h
  clang/lib/Tooling/Refactoring/CMakeLists.txt
  clang/lib/Tooling/Refactoring/Stencil.cpp
  clang/unittests/Tooling/CMakeLists.txt
  clang/unittests/Tooling/StencilTest.cpp

Index: clang/unittests/Tooling/StencilTest.cpp
===
--- /dev/null
+++ clang/unittests/Tooling/StencilTest.cpp
@@ -0,0 +1,250 @@
+//===- unittest/Tooling/StencilTest.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/Stencil.h"
+#include "clang/ASTMatchers/ASTMatchers.h"
+#include "clang/Tooling/FixIt.h"
+#include "clang/Tooling/Tooling.h"
+#include "gmock/gmock.h"
+#include "gtest/gtest.h"
+
+namespace clang {
+namespace tooling {
+namespace {
+
+using ::clang::ast_matchers::compoundStmt;
+using ::clang::ast_matchers::decl;
+using ::clang::ast_matchers::declStmt;
+using ::clang::ast_matchers::expr;
+using ::clang::ast_matchers::hasAnySubstatement;
+using ::clang::ast_matchers::hasCondition;
+using ::clang::ast_matchers::hasDescendant;
+using ::clang::ast_matchers::hasElse;
+using ::clang::ast_matchers::hasInitializer;
+using ::clang::ast_matchers::hasName;
+using ::clang::ast_matchers::hasReturnValue;
+using ::clang::ast_matchers::hasSingleDecl;
+using ::clang::ast_matchers::hasThen;
+using ::clang::ast_matchers::ifStmt;
+using ::clang::ast_matchers::ignoringImplicit;
+using ::clang::ast_matchers::returnStmt;
+using ::clang::ast_matchers::stmt;
+using ::clang::ast_matchers::varDecl;
+
+using MatchResult = ::clang::ast_matchers::MatchFinder::MatchResult;
+
+using ::clang::tooling::stencil_generators::node;
+using ::clang::tooling::stencil_generators::text;
+
+using ::testing::Eq;
+
+// In tests, we can't directly match on llvm::Expected since its accessors
+// mutate the object. So, we collapse it to an Optional.
+llvm::Optional toOptional(llvm::Expected V) {
+  if (V)
+return *V;
+  ADD_FAILURE() << "Losing error in conversion to IsSomething: "
+<< llvm::toString(V.takeError());
+  return llvm::None;
+}
+
+// A very simple matcher for llvm::Optional values.
+MATCHER_P(IsSomething, ValueMatcher, "") {
+  if (!arg)
+return false;
+  return ::testing::ExplainMatchResult(ValueMatcher, *arg, result_listener);
+}
+
+// Create a valid translation-unit from a statement.
+std::string wrapSnippet(llvm::Twine StatementCode) {
+  return ("auto stencil_test_snippet = []{" + StatementCode + "};").str();
+}
+
+clang::ast_matchers::DeclarationMatcher
+wrapMatcher(const clang::ast_matchers::StatementMatcher ) {
+  return varDecl(hasName("stencil_test_snippet"),
+ hasDescendant(compoundStmt(hasAnySubstatement(Matcher;
+}
+
+struct TestMatch {
+  // The AST unit from which `result` is built. We bundle it because it backs
+  // the result. Users are not expected to access it.
+  std::unique_ptr AstUnit;
+  // The result to use in the test. References `ast_unit`.
+  MatchResult Result;
+};
+
+// Matches `Matcher` against the statement `StatementCode` and returns the
+// result. Handles putting the statement inside a function and modifying the
+// matcher correspondingly. `Matcher` should match `StatementCode` exactly --
+// that is, produce exactly one match.
+llvm::Optional
+matchStmt(llvm::Twine StatementCode,
+  clang::ast_matchers::StatementMatcher Matcher) {
+  auto AstUnit = buildASTFromCode(wrapSnippet(StatementCode));
+  if (AstUnit == nullptr) {
+ADD_FAILURE() << "AST construction failed";
+return llvm::None;
+  }
+  clang::ASTContext  = AstUnit->getASTContext();
+  auto Matches = clang::ast_matchers::match(wrapMatcher(Matcher), Context);
+  // We expect a single, exact match for the statement.
+  if (Matches.size() != 1) {
+ADD_FAILURE() << "Wrong number of matches: " << Matches.size();
+return llvm::None;
+  }
+  return TestMatch{std::move(AstUnit), MatchResult(Matches[0], )};
+}
+
+class StencilTest : public 

[PATCH] D59219: [PR41007][OpenCL] Allow printf and toolchain reserved variadic functions in C++

2019-03-14 Thread Anastasia Stulova via Phabricator via cfe-commits
Anastasia marked an inline comment as done.
Anastasia added inline comments.



Comment at: cfe/trunk/test/SemaOpenCL/extensions.cl:31
 // RUN: %clang_cc1 %s -triple amdgcn-unknown-unknown -verify -pedantic 
-fsyntax-only -cl-std=CL2.0 -finclude-default-header
-// RUN: %clang_cc1 %s -triple spir-unknown-unknown -verify -pedantic 
-fsyntax-only -cl-std=c++
+// RUN: %clang_cc1 %s -triple spir-unknown-unknown -verify -pedantic 
-fsyntax-only -cl-std=c++ -finclude-default-header
 

bader wrote:
> Shoudn't we move this test to test/SemaOpenCLCXX?
> Does `-finclude-default-header` include opencl-c.h? I think it's an overkill 
> to test that OpenCL C++ allows printf. Ideally we should minimize number of 
> times we parsing 11500+ lines header in LIT tests.
> Shoudn't we move this test to test/SemaOpenCLCXX?

Right now test/SemaOpenCLCXX and other corresponding folders contain only 
functionality specific to C++.

In test/SemaOpenCL we will keep tests that are OpenCL C compatible even though 
we are parsing some of them in C++ mode too. We could create a common folder 
but I don't see much value in this. Let me know if you have other thoughts.



> Does -finclude-default-header include opencl-c.h? I think it's an overkill to 
> test that OpenCL C++ allows printf. Ideally we should minimize number of 
> times we parsing 11500+ lines header in LIT tests.


Yes, I perfectly agree. I would like to make sure that the header is parsed 
successfully in C++ mode. So it is not just for `printf`. There are a few other 
places where we parse the header, I can move this into them if you prefer. May 
be test/Driver/include-default-header.cl would make more sense to show the 
intent?


Repository:
  rL LLVM

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

https://reviews.llvm.org/D59219



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


[PATCH] D59094: [ARM] Fix bug 39982 - pcs("aapcs-vfp") is not consistent

2019-03-14 Thread Carey Williams via Phabricator via cfe-commits
carwil updated this revision to Diff 190653.
carwil marked an inline comment as done.
carwil added a comment.

I got bit a confused earlier. That does actually seem like correct behaviour 
(once we're no longer able to treat the struct as a homogeneous aggregate).
I've tightened up the conditional a bit as it wouldn't have previously 
accounted for the case where you had mfloat-abi=hard with an AAPCS (non VFP) 
attribute. Although in this instance, the backend does seem to be 
correcting/ignoring that, it's still best we don't blindly rely on such 
behaviour.

I've also re-structured the conditional and added some comments so it's 
(hopefully) a little bit clearer what's going on.

I believe this fixes the bug at hand. There's some other calls to getABIKind 
referencing AAPCS16_VFP, but that doesn't have a direct translation to an 
LLVM/FI CallingConvention (that I can see). Seems there is a lot of different 
ways to check various ABI/CC's and none of them seem able to give you the full 
picture at any point.


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

https://reviews.llvm.org/D59094

Files:
  clang/lib/CodeGen/TargetInfo.cpp
  clang/test/CodeGenCXX/arm-pcs.cpp

Index: clang/test/CodeGenCXX/arm-pcs.cpp
===
--- /dev/null
+++ clang/test/CodeGenCXX/arm-pcs.cpp
@@ -0,0 +1,51 @@
+// Covers a bug fix for ABI selection with homogenous aggregates:
+//  See: https://bugs.llvm.org/show_bug.cgi?id=39982
+
+// REQUIRES: arm-registered-target
+// RUN: %clang -mfloat-abi=hard --target=armv7-unknown-linux-gnueabi -O3 -S -o - %s | FileCheck %s -check-prefixes=HARD,CHECK
+// RUN: %clang -mfloat-abi=softfp --target=armv7-unknown-linux-gnueabi -O3 -S -o - %s | FileCheck %s -check-prefixes=SOFTFP,CHECK
+// RUN: %clang -mfloat-abi=soft --target=armv7-unknown-linux-gnueabi -O3 -S -o - %s | FileCheck %s -check-prefixes=SOFT,CHECK
+
+struct S {
+  float f;
+  float d;
+  float c;
+  float t;
+};
+
+// Variadic functions should always marshal for the base standard.
+// See section 5.5 (Parameter Passing) of the AAPCS.
+float __attribute__((pcs("aapcs-vfp"))) variadic(S s, ...) {
+  // CHECK-NOT: vmov s{{[0-9]+}}, s{{[0-9]+}}
+  // CHECK: mov r{{[0-9]+}}, r{{[0-9]+}}
+  return s.d;
+}
+
+float no_attribute(S s) {
+  // SOFT: mov r{{[0-9]+}}, r{{[0-9]+}}
+  // SOFTFP: mov r{{[0-9]+}}, r{{[0-9]+}}
+  // HARD: vmov.f32 s{{[0-9]+}}, s{{[0-9]+}}
+  return s.d;
+}
+
+float __attribute__((pcs("aapcs-vfp"))) baz(float x, float y) {
+  // CHECK-NOT: mov s{{[0-9]+}}, r{{[0-9]+}}
+  // SOFT: mov r{{[0-9]+}}, r{{[0-9]+}}
+  // SOFTFP: vmov.f32 s{{[0-9]+}}, s{{[0-9]+}}
+  // HARD: vmov.f32 s{{[0-9]+}}, s{{[0-9]+}}
+  return y;
+}
+
+float __attribute__((pcs("aapcs-vfp"))) foo(S s) {
+  // CHECK-NOT: mov s{{[0-9]+}}, r{{[0-9]+}}
+  // SOFT: mov r{{[0-9]+}}, r{{[0-9]+}}
+  // SOFTFP: vmov.f32 s{{[0-9]+}}, s{{[0-9]+}}
+  // HARD: vmov.f32 s{{[0-9]+}}, s{{[0-9]+}}
+  return s.d;
+}
+
+float __attribute__((pcs("aapcs"))) bar(S s) {
+  // CHECK-NOT: vmov.f32 s{{[0-9]+}}, s{{[0-9]+}}
+  // CHECK: mov r{{[0-9]+}}, r{{[0-9]+}}
+  return s.d;
+}
Index: clang/lib/CodeGen/TargetInfo.cpp
===
--- clang/lib/CodeGen/TargetInfo.cpp
+++ clang/lib/CodeGen/TargetInfo.cpp
@@ -10,7 +10,6 @@
 // definition used to handle ABI compliancy.
 //
 //===--===//
-
 #include "TargetInfo.h"
 #include "ABIInfo.h"
 #include "CGBlocks.h"
@@ -5591,8 +5590,10 @@
   ABIKind getABIKind() const { return Kind; }
 
 private:
-  ABIArgInfo classifyReturnType(QualType RetTy, bool isVariadic) const;
-  ABIArgInfo classifyArgumentType(QualType RetTy, bool isVariadic) const;
+  ABIArgInfo classifyReturnType(QualType RetTy, bool isVariadic,
+unsigned functionCallConv) const;
+  ABIArgInfo classifyArgumentType(QualType RetTy, bool isVariadic,
+  unsigned functionCallConv) const;
   ABIArgInfo classifyHomogeneousAggregate(QualType Ty, const Type *Base,
   uint64_t Members) const;
   ABIArgInfo coerceIllegalVector(QualType Ty) const;
@@ -5722,11 +5723,13 @@
 
 void ARMABIInfo::computeInfo(CGFunctionInfo ) const {
   if (!::classifyReturnType(getCXXABI(), FI, *this))
-FI.getReturnInfo() =
-classifyReturnType(FI.getReturnType(), FI.isVariadic());
+FI.getReturnInfo() = classifyReturnType(FI.getReturnType(), FI.isVariadic(),
+FI.getCallingConvention());
 
   for (auto  : FI.arguments())
-I.info = classifyArgumentType(I.type, FI.isVariadic());
+I.info = classifyArgumentType(I.type, FI.isVariadic(),
+  FI.getCallingConvention());
+
 
   // Always honor user-specified calling convention.
   if (FI.getCallingConvention() != llvm::CallingConv::C)
@@ -5805,8 +5808,8 @@
   return 

[PATCH] D58673: [ASTImporter] Fix redecl failures of ClassTemplateSpec

2019-03-14 Thread Gabor Marton via Phabricator via cfe-commits
martong marked an inline comment as done.
martong added a comment.

@shafik Ping


Repository:
  rC Clang

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

https://reviews.llvm.org/D58673



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


[PATCH] D58668: [ASTImporter] Fix redecl failures of FunctionTemplateSpec

2019-03-14 Thread Gabor Marton via Phabricator via cfe-commits
martong added a comment.

@shafik Ping.


Repository:
  rC Clang

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

https://reviews.llvm.org/D58668



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


[PATCH] D59354: [clangd] Print arguments in template specializations

2019-03-14 Thread Kadir Cetinkaya via Phabricator via cfe-commits
kadircet marked an inline comment as done.
kadircet added inline comments.



Comment at: clang/lib/AST/TypePrinter.cpp:1646
+break;
+  case TemplateArgument::ArgKind::Type:
+A.getTypeSourceInfo()->getType().print(OS, PP);

ilya-biryukov wrote:
> Maybe simplify the switch to:
> ```
> if (A.getKind() == TemplateArgument::ArgKind::Type) {
> A.getTypeSourceInfo()->getType().print(OS, PP);
> return;
> }
> A.getArgument().print(PP, OS);
> ```
> 
It was rather to catch any changes in the ArgKind at compile-time, still can do 
if you think this should not cause any problems


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D59354



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


[PATCH] D59214: [clang][OpeMP] Model OpenMP structured-block in AST (PR40563)

2019-03-14 Thread Roman Lebedev via Phabricator via cfe-commits
lebedev.ri added a comment.

In D59214#1429422 , @riccibruno wrote:

> In D59214#1429400 , @lebedev.ri 
> wrote:
>
> > In D59214#1429384 , @riccibruno 
> > wrote:
> >
> > > IIRC, last time I looked only 4 statement/expression classes currently 
> > > have some abbreviation defined.
> >
> >
> > Yep, that is what i'm seeing in this diff.
> >
> > In D59214#1429384 , @riccibruno 
> > wrote:
> >
> > > It would probably be useful to have someone go systematically through the 
> > > list of classes and fix this.
> >
> >
> > Yeah, i suspect that might be **really** beneficial.
>
>
> Especially given that more people are going to use modules now that they are 
> in the process of being standardized.


Ah, good point, filed https://bugs.llvm.org/show_bug.cgi?id=41072


Repository:
  rC Clang

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

https://reviews.llvm.org/D59214



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


[PATCH] D28462: clang-format: Add new style option AlignConsecutiveMacros

2019-03-14 Thread Nick Renieris via Phabricator via cfe-commits
VelocityRa marked 11 inline comments as done.
VelocityRa added a comment.

Waiting for further feedback before pushing an update.




Comment at: lib/Format/WhitespaceManager.cpp:436
+static void
+AlignTokenSequenceAll(unsigned Start, unsigned End, unsigned Column,
+  F &,

klimek wrote:
> I don't think the 'All' postfix in the name is helpful. What are you trying 
> to say with that name?
I'm not particularly fond of `All` either, suggestions welcome.

As the comment above explains, `All` refers to the fact that it operates on all 
tokens, instead of being limited to certain cases like `AlignTokenSequence` is. 
Maybe I should name //this// one `AlignTokenSequence` and the other one 
`AlignTokenSequenceOuterScope`, or something.



Comment at: lib/Format/WhitespaceManager.cpp:437
+AlignTokenSequenceAll(unsigned Start, unsigned End, unsigned Column,
+  F &,
+  SmallVector ) {

klimek wrote:
> Why an rvalue ref? Also, this is used only once, so why make this a template?
It's an rvalue ref, because that's also the case for `AlignTokenSequence` 
(wasn't sure why, so I left it as is).
It's used only once, but the function is more generic that way, no? That's the 
point of its generic name.
Tell me if I should change it.



Comment at: lib/Format/WhitespaceManager.cpp:442
+
+  for (unsigned i = Start; i != End; ++i) {
+if (Changes[i].NewlinesBefore > 0) {

klimek wrote:
> llvm style: use an upper case I for index vars.
Ok, I assume your style changed because this is copied from 
`AlignTokenSequence`.



Comment at: lib/Format/WhitespaceManager.cpp:473
+
+  // Line number of the start and the end of the current token sequence.
+  unsigned StartOfSequence = 0;

klimek wrote:
> These are indices into Matches, not line numbers, right?
Correct. My bad.



Comment at: lib/Format/WhitespaceManager.cpp:500
+if (Changes[i].NewlinesBefore != 0) {
+  EndOfSequence = i;
+  // If there is a blank line, or if the last line didn't contain any

klimek wrote:
> Why set EndOfSequence outside the if below?
It's from `AlignTokens`. I think it's because due to some of the loop logic, it 
ends up not checking up to the point of the the last token.
Without setting this and calling `AlignCurrentSequence()` once more at the end, 
the last line of a macro group does not get properly aligned, the tests fail.



Comment at: lib/Format/WhitespaceManager.cpp:512
+
+// If there is more than one matching token per line, end the sequence.
+if (FoundMatchOnLine)

klimek wrote:
> What's the reason for this?
I don't remember, but it was unnecessary apparently. The tests pass without 
this check.


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

https://reviews.llvm.org/D28462



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


[PATCH] D59214: [clang][OpeMP] Model OpenMP structured-block in AST (PR40563)

2019-03-14 Thread Bruno Ricci via Phabricator via cfe-commits
riccibruno added a comment.

In D59214#1429400 , @lebedev.ri wrote:

> In D59214#1429384 , @riccibruno 
> wrote:
>
> > IIRC, last time I looked only 4 statement/expression classes currently have 
> > some abbreviation defined.
>
>
> Yep, that is what i'm seeing in this diff.
>
> In D59214#1429384 , @riccibruno 
> wrote:
>
> > It would probably be useful to have someone go systematically through the 
> > list of classes and fix this.
>
>
> Yeah, i suspect that might be **really** beneficial.


Especially given that more people are going to use modules now that they are in 
the process of being standardized.


Repository:
  rC Clang

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

https://reviews.llvm.org/D59214



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


  1   2   >