[PATCH] D56900: [Fixed Point Arithmetic] Fixed Point and Integer Conversions

2019-01-17 Thread John McCall via Phabricator via cfe-commits
rjmccall added inline comments.



Comment at: clang/lib/AST/ExprConstant.cpp:9839
+return Success(Result, E);
+  }
+

Can most of this reasonably be a method on `APFixedPoint`?  (And likewise for 
`CK_IntegralToFixedPoint`.)  If nothing else, I suspect you are going to want 
these when it comes to things like the compound assignment operators, which do 
implicit conversions internally that aren't directly expressed in the AST.


Repository:
  rC Clang

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

https://reviews.llvm.org/D56900



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


[PATCH] D56900: [Fixed Point Arithmetic] Fixed Point and Integer Conversions

2019-01-17 Thread Leonard Chan via Phabricator via cfe-commits
leonardchan updated this revision to Diff 182456.

Repository:
  rC Clang

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

https://reviews.llvm.org/D56900

Files:
  clang/include/clang/AST/OperationKinds.def
  clang/include/clang/Basic/FixedPoint.h
  clang/lib/AST/Expr.cpp
  clang/lib/AST/ExprConstant.cpp
  clang/lib/CodeGen/CGExpr.cpp
  clang/lib/CodeGen/CGExprAgg.cpp
  clang/lib/CodeGen/CGExprComplex.cpp
  clang/lib/CodeGen/CGExprConstant.cpp
  clang/lib/CodeGen/CGExprScalar.cpp
  clang/lib/Edit/RewriteObjCFoundationAPI.cpp
  clang/lib/Sema/SemaChecking.cpp
  clang/lib/Sema/SemaExpr.cpp
  clang/lib/StaticAnalyzer/Core/ExprEngineC.cpp
  clang/test/Frontend/fixed_point_conversions.c
  clang/test/Frontend/fixed_point_errors.c
  clang/test/Frontend/fixed_point_unknown_conversions.c

Index: clang/test/Frontend/fixed_point_unknown_conversions.c
===
--- clang/test/Frontend/fixed_point_unknown_conversions.c
+++ clang/test/Frontend/fixed_point_unknown_conversions.c
@@ -22,28 +22,19 @@
   _Fract fract = accum; // ok
   _Accum *accum_ptr;
 
-  accum = b;   // expected-error{{conversion between fixed point and '_Bool' is not yet supported}}
-  accum = i;   // expected-error{{conversion between fixed point and 'int' is not yet supported}}
-  accum = i;   // expected-error{{conversion between fixed point and 'int' is not yet supported}}
   accum = f;   // expected-error{{conversion between fixed point and 'float' is not yet supported}}
   accum = d;   // expected-error{{conversion between fixed point and 'double' is not yet supported}}
   accum = dc;  // expected-error{{conversion between fixed point and '_Complex double' is not yet supported}}
   accum = ic;  // expected-error{{conversion between fixed point and '_Complex int' is not yet supported}}
   accum = s;   // expected-error{{assigning to '_Accum' from incompatible type 'struct S'}}
-  accum = e;   // expected-error{{conversion between fixed point and 'enum E' is not yet supported}}
   accum = ptr; // expected-error{{assigning to '_Accum' from incompatible type 'int *'}}
   accum_ptr = ptr; // expected-warning{{incompatible pointer types assigning to '_Accum *' from 'int *'}}
-  accum = i2;  // expected-error{{conversion between fixed point and 'int_t' (aka 'int') is not yet supported}}
 
-  c = accum;   // expected-error{{conversion between fixed point and 'char' is not yet supported}}
-  i = accum;   // expected-error{{conversion between fixed point and 'int' is not yet supported}}
   f = accum;   // expected-error{{conversion between fixed point and 'float' is not yet supported}}
   d = accum;   // expected-error{{conversion between fixed point and 'double' is not yet supported}}
   dc = accum;  // expected-error{{conversion between fixed point and '_Complex double' is not yet supported}}
   ic = accum;  // expected-error{{conversion between fixed point and '_Complex int' is not yet supported}}
   s = accum;   // expected-error{{assigning to 'struct S' from incompatible type '_Accum'}}
-  e = accum;   // expected-error{{conversion between fixed point and 'enum E' is not yet supported}}
   ptr = accum; // expected-error{{assigning to 'int *' from incompatible type '_Accum'}}
   ptr = accum_ptr; // expected-warning{{incompatible pointer types assigning to 'int *' from '_Accum *'}}
-  i2 = accum;  // expected-error{{conversion between fixed point and 'int' is not yet supported}}
 }
Index: clang/test/Frontend/fixed_point_errors.c
===
--- clang/test/Frontend/fixed_point_errors.c
+++ clang/test/Frontend/fixed_point_errors.c
@@ -233,8 +233,20 @@
  // expected-warning@-1{{type specifier missing, defaults to 'int'}}
 }
 
+// Ok conversions
+int i_const = -2.5hk;
+_Sat short _Accum sat_sa_const2 = 256.0k;
+_Sat unsigned short _Accum sat_usa_const = -1.0hk;
+short _Accum sa_const3 = 2;
+short _Accum sa_const4 = -2;
+
 // Overflow
 short _Accum sa_const = 256.0k;   // expected-warning{{implicit conversion from 256.0 cannot fit within the range of values for 'short _Accum'}}
 short _Fract sf_const = 1.0hk;// expected-warning{{implicit conversion from 1.0 cannot fit within the range of values for 'short _Fract'}}
 unsigned _Accum ua_const = -1.0k; // expected-warning{{implicit conversion from -1.0 cannot fit within the range of values for 'unsigned _Accum'}}
 short _Accum sa_const2 = 128.0k + 128.0k; // expected-warning{{implicit conversion from 256.0 cannot fit within the range of values for 'short _Accum'}}
+short s_const = 65536.0lk;// expected-warning{{implicit conversion from 65536.0 cannot fit within the range of values for 'short'}}
+unsigned u_const = -2.5hk;// expected-warning{{implicit conversion from -2.5 cannot fit within the range of values for 'unsigned int'}}
+char 

[PATCH] D56900: [Fixed Point Arithmetic] Fixed Point and Integer Conversions

2019-01-17 Thread Leonard Chan via Phabricator via cfe-commits
leonardchan created this revision.
leonardchan added reviewers: rjmccall, ebevhan, bjope.
leonardchan added a project: clang.

This patch includes the necessary code for converting between a fixed point 
type and integer. This also includes constant expression evaluation for 
conversions with these types.


Repository:
  rC Clang

https://reviews.llvm.org/D56900

Files:
  clang/include/clang/AST/OperationKinds.def
  clang/include/clang/Basic/FixedPoint.h
  clang/lib/AST/Expr.cpp
  clang/lib/AST/ExprConstant.cpp
  clang/lib/CodeGen/CGExpr.cpp
  clang/lib/CodeGen/CGExprAgg.cpp
  clang/lib/CodeGen/CGExprComplex.cpp
  clang/lib/CodeGen/CGExprConstant.cpp
  clang/lib/CodeGen/CGExprScalar.cpp
  clang/lib/Edit/RewriteObjCFoundationAPI.cpp
  clang/lib/Sema/SemaChecking.cpp
  clang/lib/Sema/SemaExpr.cpp
  clang/lib/StaticAnalyzer/Core/ExprEngineC.cpp
  clang/test/Frontend/fixed_point_conversions.c
  clang/test/Frontend/fixed_point_errors.c

Index: clang/test/Frontend/fixed_point_errors.c
===
--- clang/test/Frontend/fixed_point_errors.c
+++ clang/test/Frontend/fixed_point_errors.c
@@ -233,8 +233,20 @@
  // expected-warning@-1{{type specifier missing, defaults to 'int'}}
 }
 
+// Ok conversions
+int i_const = -2.5hk;
+_Sat short _Accum sat_sa_const2 = 256.0k;
+_Sat unsigned short _Accum sat_usa_const = -1.0hk;
+short _Accum sa_const3 = 2;
+short _Accum sa_const4 = -2;
+
 // Overflow
 short _Accum sa_const = 256.0k;   // expected-warning{{implicit conversion from 256.0 cannot fit within the range of values for 'short _Accum'}}
 short _Fract sf_const = 1.0hk;// expected-warning{{implicit conversion from 1.0 cannot fit within the range of values for 'short _Fract'}}
 unsigned _Accum ua_const = -1.0k; // expected-warning{{implicit conversion from -1.0 cannot fit within the range of values for 'unsigned _Accum'}}
 short _Accum sa_const2 = 128.0k + 128.0k; // expected-warning{{implicit conversion from 256.0 cannot fit within the range of values for 'short _Accum'}}
+short s_const = 65536.0lk;// expected-warning{{implicit conversion from 65536.0 cannot fit within the range of values for 'short'}}
+unsigned u_const = -2.5hk;// expected-warning{{implicit conversion from -2.5 cannot fit within the range of values for 'unsigned int'}}
+char c_const = 256.0uk;   // expected-warning{{implicit conversion from 256.0 cannot fit within the range of values for 'char'}}
+short _Accum sa_const5 = 256; // expected-warning{{implicit conversion from 256 cannot fit within the range of values for 'short _Accum'}}
+unsigned short _Accum usa_const2 = -2;// expected-warning{{implicit conversion from -2 cannot fit within the range of values for 'unsigned short _Accum'}}
Index: clang/test/Frontend/fixed_point_conversions.c
===
--- clang/test/Frontend/fixed_point_conversions.c
+++ clang/test/Frontend/fixed_point_conversions.c
@@ -16,14 +16,42 @@
 // SAME-DAG:@usa_const  = {{.*}}global i16 320, align 2
 // SAME-DAG:@ua_const   = {{.*}}global i32 81920, align 4
 
+// FixedPoint to integer
+int i_const = -128.0hk;  // DEFAULT-DAG: @i_const  = {{.*}}global i32 -128, align 4
+int i_const2 = 128.0hk;  // DEFAULT-DAG: @i_const2 = {{.*}}global i32 128, align 4
+int i_const3 = -128.0k;  // DEFAULT-DAG: @i_const3 = {{.*}}global i32 -128, align 4
+int i_const4 = 128.0k;   // DEFAULT-DAG: @i_const4 = {{.*}}global i32 128, align 4
+short s_const = -128.0k; // DEFAULT-DAG: @s_const  = {{.*}}global i16 -128, align 2
+short s_const2 = 128.0k; // DEFAULT-DAG: @s_const2 = {{.*}}global i16 128, align 2
+
+// Integer to fixed point
+short _Accum sa_const5 = 2;// DEFAULT-DAG: @sa_const5 = {{.*}}global i16 256, align 2
+short _Accum sa_const6 = -2;   // DEFAULT-DAG: @sa_const6 = {{.*}}global i16 -256, align 2
+short _Accum sa_const7 = -256; // DEFAULT-DAG: @sa_const7 = {{.*}}global i16 -32768, align 2
+
 // Signedness
 unsigned short _Accum usa_const2 = 2.5hk;
 // DEFAULT-DAG: @usa_const2  = {{.*}}global i16 640, align 2
 // SAME-DAG:@usa_const2  = {{.*}}global i16 320, align 2
 short _Accum sa_const3 = 2.5hk; // DEFAULT-DAG: @sa_const3 = {{.*}}global i16 320, align 2
 
+int i_const5 = 128.0uhk;
+unsigned int ui_const = 128.0hk;
+// DEFAULT-DAG: @i_const5  = {{.*}}global i32 128, align 4
+// DEFAULT-DAG: @ui_const  = {{.*}}global i32 128, align 4
+// SAME-DAG:@i_const5  = {{.*}}global i32 128, align 4
+// SAME-DAG:@ui_const  = {{.*}}global i32 128, align 4
+
+short _Accum sa_const9 = 2u; // DEFAULT-DAG: @sa_const9 = {{.*}}global i16 256, align 2
+unsigned short _Accum usa_const3 = 2;
+// DEFAULT-DAG: @usa_const3 = {{.*}}global i16 512, align 2
+// SAME-DAG:@usa_const3 = {{.*}}global i16 256, align 2
+
 // Overflow (this is undefined but allowed)
 short _Accum sa_const4 = 256.0k;
+unsigned int ui_const2 = -2.5hk;
+short 

[PATCH] D56899: [analyzer] pr37688: Fix a crash on trying to evaluate a deleted destructor of a union.

2019-01-17 Thread Artem Dergachev via Phabricator via cfe-commits
NoQ created this revision.
NoQ added reviewers: dcoughlin, xazax.hun, a.sidorin, george.karpenkov, 
rnkovacs, mikhail.ramalho, Szelethus, baloghadamsoftware.
Herald added subscribers: cfe-commits, dkrupp, donat.nagy, szepet.

This is a slow quick fix for https://bugs.llvm.org/show_bug.cgi?id=37688 - add 
a defensive check against an invalid destructor in the CFG.

Unions with fields with destructors have their own destructor implicitly 
deleted. Due to a bug in the CFG we're still trying to evaluate them at the end 
of the object's lifetime and crash because we are unable to find the 
declaration.

Add a FIXME test for the CFG that demonstrates the bug and a normal test that 
demonstrates that we've fixed the crash and are even trying to continue the 
analysis beyond that point.

I've no idea why did this require a noexcept specification. I also don't know 
why does it require that many levels of structure nestedness; it might be that 
Clang doesn't emit an error in this case but in fact the code is invalid - an 
error about attempting to rely upon a deleted destructor is emitted in many 
simpler cases.


Repository:
  rC Clang

https://reviews.llvm.org/D56899

Files:
  lib/StaticAnalyzer/Core/ExprEngineCXX.cpp
  test/Analysis/cfg.cpp
  test/Analysis/unions.cpp

Index: test/Analysis/unions.cpp
===
--- test/Analysis/unions.cpp
+++ test/Analysis/unions.cpp
@@ -1,6 +1,7 @@
 // RUN: %clang_analyze_cc1 -analyzer-checker=core,unix.Malloc,debug.ExprInspection %s -analyzer-config eagerly-assume=false -verify
 
 extern void clang_analyzer_eval(bool);
+extern void clang_analyzer_warnIfReached();
 extern "C" char *strdup(const char *s);
 
 namespace PR14054_reduced {
@@ -121,3 +122,22 @@
 y = 1 / y; // no-warning
 }
 } // end namespace assume_union_contents
+
+namespace pr37688_deleted_union_destructor {
+struct S { ~S(); };
+struct A {
+  ~A() noexcept {}
+  union {
+struct {
+  S s;
+} ss;
+  };
+};
+void foo() {
+  A a;
+} // no-crash
+void bar() {
+  foo();
+  clang_analyzer_warnIfReached(); // expected-warning{{REACHABLE}}
+}
+} // end namespace pr37688_deleted_union_destructor
Index: test/Analysis/cfg.cpp
===
--- test/Analysis/cfg.cpp
+++ test/Analysis/cfg.cpp
@@ -468,6 +468,37 @@
 }
 
 
+// FIXME: The destructor for 'a' shouldn't be there because it's deleted
+// in the union.
+// CHECK-LABEL: void foo()
+// CHECK:  [B2 (ENTRY)]
+// CHECK-NEXT:Succs (1): B1
+// CHECK:  [B1]
+// WARNINGS-NEXT:1:  (CXXConstructExpr, struct pr37688_deleted_union_destructor::A)
+// ANALYZER-NEXT:1:  (CXXConstructExpr, [B1.2], struct pr37688_deleted_union_destructor::A)
+// CHECK-NEXT:2: pr37688_deleted_union_destructor::A a;
+// CHECK-NEXT:3: [B1.2].~A() (Implicit destructor)
+// CHECK-NEXT:Preds (1): B2
+// CHECK-NEXT:Succs (1): B0
+// CHECK:  [B0 (EXIT)]
+// CHECK-NEXT:Preds (1): B1
+
+namespace pr37688_deleted_union_destructor {
+struct S { ~S(); };
+struct A {
+  ~A() noexcept {}
+  union {
+struct {
+  S s;
+} ss;
+  };
+};
+void foo() {
+  A a;
+}
+} // end namespace pr37688_deleted_union_destructor
+
+
 // CHECK-LABEL: template<> int *PR18472()
 // CHECK: [B2 (ENTRY)]
 // CHECK-NEXT:   Succs (1): B1
Index: lib/StaticAnalyzer/Core/ExprEngineCXX.cpp
===
--- lib/StaticAnalyzer/Core/ExprEngineCXX.cpp
+++ lib/StaticAnalyzer/Core/ExprEngineCXX.cpp
@@ -604,6 +604,7 @@
 ExplodedNode *Pred,
 ExplodedNodeSet ,
 const EvalCallOptions ) {
+  assert(S && "A destructor without a trigger!");
   const LocationContext *LCtx = Pred->getLocationContext();
   ProgramStateRef State = Pred->getState();
 
@@ -611,6 +612,19 @@
   assert(RecordDecl && "Only CXXRecordDecls should have destructors");
   const CXXDestructorDecl *DtorDecl = RecordDecl->getDestructor();
 
+  // FIXME: There should always be a Decl, otherwise the destructor call
+  // shouldn't have been added to the CFG in the first place.
+  if (!DtorDecl) {
+// Skip the invalid destructor. We cannot simply return because
+// it would interrupt the analysis instead.
+static SimpleProgramPointTag T("ExprEngine", "SkipInvalidDestructor");
+// FIXME: PostImplicitCall with a null decl may crash elsewhere anyway.
+PostImplicitCall PP(/*Decl=*/nullptr, S->getEndLoc(), LCtx, );
+NodeBuilder Bldr(Pred, Dst, *currBldrCtx);
+Bldr.generateNode(PP, Pred->getState(), Pred);
+return;
+  }
+
   CallEventManager  = getStateManager().getCallEventManager();
   CallEventRef Call =
 CEMgr.getCXXDestructorCall(DtorDecl, S, Dest, IsBaseDtor, State, LCtx);
@@ -629,7 +643,6 @@
I != E; ++I)
 defaultEvalCall(Bldr, *I, *Call, CallOpts);
 
-  ExplodedNodeSet DstPostCall;
   

[PATCH] D56891: [analyzer] Introduce proper diagnostic for freeing unowned object

2019-01-17 Thread George Karpenkov via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rC351514: [analyzer] Introduce proper diagnostic for freeing 
unowned object (authored by george.karpenkov, committed by ).
Herald added a subscriber: cfe-commits.

Changed prior to commit:
  https://reviews.llvm.org/D56891?vs=182431=182445#toc

Repository:
  rC Clang

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

https://reviews.llvm.org/D56891

Files:
  lib/StaticAnalyzer/Checkers/RetainCountChecker/RetainCountChecker.cpp
  lib/StaticAnalyzer/Checkers/RetainCountChecker/RetainCountChecker.h
  lib/StaticAnalyzer/Checkers/RetainCountChecker/RetainCountDiagnostics.cpp
  lib/StaticAnalyzer/Checkers/RetainCountChecker/RetainCountDiagnostics.h
  test/Analysis/osobject-retain-release.cpp

Index: lib/StaticAnalyzer/Checkers/RetainCountChecker/RetainCountDiagnostics.h
===
--- lib/StaticAnalyzer/Checkers/RetainCountChecker/RetainCountDiagnostics.h
+++ lib/StaticAnalyzer/Checkers/RetainCountChecker/RetainCountDiagnostics.h
@@ -30,6 +30,7 @@
 UseAfterRelease,
 ReleaseNotOwned,
 DeallocNotOwned,
+FreeNotOwned,
 OverAutorelease,
 ReturnNotOwnedForOwned,
 LeakWithinFunction,
Index: lib/StaticAnalyzer/Checkers/RetainCountChecker/RetainCountChecker.h
===
--- lib/StaticAnalyzer/Checkers/RetainCountChecker/RetainCountChecker.h
+++ lib/StaticAnalyzer/Checkers/RetainCountChecker/RetainCountChecker.h
@@ -255,6 +255,7 @@
   RefCountBug useAfterRelease{this, RefCountBug::UseAfterRelease};
   RefCountBug releaseNotOwned{this, RefCountBug::ReleaseNotOwned};
   RefCountBug deallocNotOwned{this, RefCountBug::DeallocNotOwned};
+  RefCountBug freeNotOwned{this, RefCountBug::FreeNotOwned};
   RefCountBug overAutorelease{this, RefCountBug::OverAutorelease};
   RefCountBug returnNotOwnedForOwned{this, RefCountBug::ReturnNotOwnedForOwned};
   RefCountBug leakWithinFunction{this, RefCountBug::LeakWithinFunction};
@@ -336,8 +337,8 @@
RefVal V, ArgEffect E, RefVal::Kind ,
CheckerContext ) const;
 
-
-  const RefCountBug (RefVal::Kind ErrorKind) const;
+  const RefCountBug (RefVal::Kind ErrorKind,
+SymbolRef Sym) const;
 
   void processNonLeakError(ProgramStateRef St, SourceRange ErrorRange,
RefVal::Kind ErrorKind, SymbolRef Sym,
Index: lib/StaticAnalyzer/Checkers/RetainCountChecker/RetainCountDiagnostics.cpp
===
--- lib/StaticAnalyzer/Checkers/RetainCountChecker/RetainCountDiagnostics.cpp
+++ lib/StaticAnalyzer/Checkers/RetainCountChecker/RetainCountDiagnostics.cpp
@@ -27,6 +27,8 @@
 return "Bad release";
   case DeallocNotOwned:
 return "-dealloc sent to non-exclusively owned object";
+  case FreeNotOwned:
+return "freeing non-exclusively owned object";
   case OverAutorelease:
 return "Object autoreleased too many times";
   case ReturnNotOwnedForOwned:
@@ -47,6 +49,8 @@
"not owned at this point by the caller";
   case DeallocNotOwned:
 return "-dealloc sent to object that may be referenced elsewhere";
+  case FreeNotOwned:
+return  "'free' called on an object that may be referenced elsewhere";
   case OverAutorelease:
 return "Object autoreleased too many times";
   case ReturnNotOwnedForOwned:
@@ -86,7 +90,8 @@
 /// Write information about the type state change to {@code os},
 /// return whether the note should be generated.
 static bool shouldGenerateNote(llvm::raw_string_ostream ,
-   const RefVal *PrevT, const RefVal ,
+   const RefVal *PrevT,
+   const RefVal ,
bool DeallocSent) {
   // Get the previous type state.
   RefVal PrevV = *PrevT;
@@ -416,6 +421,11 @@
 RefCountReportVisitor::VisitNode(const ExplodedNode *N,
   BugReporterContext , BugReport ) {
 
+  const auto  = static_cast(BR.getBugType());
+
+  bool IsFreeUnowned = BT.getBugType() == RefCountBug::FreeNotOwned ||
+   BT.getBugType() == RefCountBug::DeallocNotOwned;
+
   const SourceManager  = BRC.getSourceManager();
   CallEventManager  = BRC.getStateManager().getCallEventManager();
   if (auto CE = N->getLocationAs())
@@ -434,7 +444,8 @@
   const LocationContext *LCtx = N->getLocationContext();
 
   const RefVal* CurrT = getRefBinding(CurrSt, Sym);
-  if (!CurrT) return nullptr;
+  if (!CurrT)
+return nullptr;
 
   const RefVal  = *CurrT;
   const RefVal *PrevT = getRefBinding(PrevSt, Sym);
@@ -444,6 +455,12 @@
   std::string sbuf;
   llvm::raw_string_ostream os(sbuf);
 
+  if (PrevT && IsFreeUnowned && CurrV.isNotOwned() && PrevT->isOwned()) {
+os << "Object is now not exclusively owned";
+auto Pos = 

[PATCH] D56885: [analyzer] const-ify reference to bug type used in BugReporter

2019-01-17 Thread George Karpenkov via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rC351511: [analyzer] const-ify reference to bug type used in 
BugReporter (authored by george.karpenkov, committed by ).
Herald added a subscriber: cfe-commits.

Changed prior to commit:
  https://reviews.llvm.org/D56885?vs=182412=182443#toc

Repository:
  rC Clang

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

https://reviews.llvm.org/D56885

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

Index: include/clang/StaticAnalyzer/Core/BugReporter/BugReporter.h
===
--- include/clang/StaticAnalyzer/Core/BugReporter/BugReporter.h
+++ include/clang/StaticAnalyzer/Core/BugReporter/BugReporter.h
@@ -95,7 +95,7 @@
   friend class BugReportEquivClass;
   friend class BugReporter;
 
-  BugType& BT;
+  const BugType& BT;
   const Decl *DeclWithIssue = nullptr;
   std::string ShortDescription;
   std::string Description;
@@ -164,15 +164,15 @@
   void popInterestingSymbolsAndRegions();
 
 public:
-  BugReport(BugType& bt, StringRef desc, const ExplodedNode *errornode)
+  BugReport(const BugType& bt, StringRef desc, const ExplodedNode *errornode)
   : BT(bt), Description(desc), ErrorNode(errornode) {}
 
-  BugReport(BugType& bt, StringRef shortDesc, StringRef desc,
+  BugReport(const BugType& bt, StringRef shortDesc, StringRef desc,
 const ExplodedNode *errornode)
   : BT(bt), ShortDescription(shortDesc), Description(desc),
 ErrorNode(errornode) {}
 
-  BugReport(BugType , StringRef desc, PathDiagnosticLocation l)
+  BugReport(const BugType , StringRef desc, PathDiagnosticLocation l)
   : BT(bt), Description(desc), Location(l) {}
 
   /// Create a BugReport with a custom uniqueing location.
@@ -190,7 +190,7 @@
   virtual ~BugReport();
 
   const BugType& getBugType() const { return BT; }
-  BugType& getBugType() { return BT; }
+  //BugType& getBugType() { return BT; }
 
   /// True when the report has an execution path associated with it.
   ///
@@ -481,7 +481,7 @@
 return {};
   }
 
-  void Register(BugType *BT);
+  void Register(const BugType *BT);
 
   /// Add the given report to the set of reports tracked by BugReporter.
   ///
Index: lib/StaticAnalyzer/Core/BugReporter.cpp
===
--- lib/StaticAnalyzer/Core/BugReporter.cpp
+++ lib/StaticAnalyzer/Core/BugReporter.cpp
@@ -1247,7 +1247,7 @@
 
 static std::unique_ptr
 generateEmptyDiagnosticForReport(BugReport *R, SourceManager ) {
-  BugType  = R->getBugType();
+  const BugType  = R->getBugType();
   return llvm::make_unique(
   R->getBugType().getCheckName(), R->getDeclWithIssue(),
   R->getBugType().getName(), R->getDescription(),
@@ -2684,7 +2684,7 @@
   return Out;
 }
 
-void BugReporter::Register(BugType *BT) {
+void BugReporter::Register(const BugType *BT) {
   BugTypes = F.add(BugTypes, BT);
 }
 
@@ -2718,7 +2718,7 @@
   R->Profile(ID);
 
   // Lookup the equivance class.  If there isn't one, create it.
-  BugType& BT = R->getBugType();
+  const BugType& BT = R->getBugType();
   Register();
   void *InsertPos;
   BugReportEquivClass* EQ = EQClasses.FindNodeOrInsertPos(ID, InsertPos);
@@ -2836,7 +2836,7 @@
  SmallVectorImpl ) {
   BugReportEquivClass::iterator I = EQ.begin(), E = EQ.end();
   assert(I != E);
-  BugType& BT = I->getBugType();
+  const BugType& BT = I->getBugType();
 
   // If we don't need to suppress any of the nodes because they are
   // post-dominated by a sink, simply add all the nodes in the equivalence class
Index: lib/StaticAnalyzer/Checkers/RetainCountChecker/RetainCountDiagnostics.h
===
--- lib/StaticAnalyzer/Checkers/RetainCountChecker/RetainCountDiagnostics.h
+++ lib/StaticAnalyzer/Checkers/RetainCountChecker/RetainCountDiagnostics.h
@@ -51,7 +51,7 @@
   StringRef endText);
 
   llvm::iterator_range getRanges() override {
-const RefCountBug& BugTy = static_cast(getBugType());
+const RefCountBug& BugTy = static_cast(getBugType());
 if (!BugTy.isLeak())
   return BugReport::getRanges();
 return llvm::make_range(ranges_iterator(), ranges_iterator());
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D56884: [analyzer] Extend BugType constructor to accept "SuppressOnSink" as a parameter

2019-01-17 Thread George Karpenkov via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rC351510: [analyzer] Extend BugType constructor to accept 
SuppressOnSink as a parameter (authored by george.karpenkov, 
committed by ).
Herald added a subscriber: cfe-commits.

Changed prior to commit:
  https://reviews.llvm.org/D56884?vs=182434=182442#toc

Repository:
  rC Clang

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

https://reviews.llvm.org/D56884

Files:
  include/clang/StaticAnalyzer/Core/BugReporter/BugType.h
  lib/StaticAnalyzer/Checkers/IteratorChecker.cpp
  lib/StaticAnalyzer/Checkers/MallocChecker.cpp
  lib/StaticAnalyzer/Checkers/RetainCountChecker/RetainCountChecker.cpp
  lib/StaticAnalyzer/Checkers/RetainCountChecker/RetainCountDiagnostics.h
  lib/StaticAnalyzer/Checkers/SimpleStreamChecker.cpp
  lib/StaticAnalyzer/Checkers/ValistChecker.cpp

Index: lib/StaticAnalyzer/Checkers/RetainCountChecker/RetainCountDiagnostics.h
===
--- lib/StaticAnalyzer/Checkers/RetainCountChecker/RetainCountDiagnostics.h
+++ lib/StaticAnalyzer/Checkers/RetainCountChecker/RetainCountDiagnostics.h
@@ -26,8 +26,10 @@
 
 class RefCountBug : public BugType {
 protected:
-  RefCountBug(const CheckerBase *checker, StringRef name)
-  : BugType(checker, name, categories::MemoryRefCount) {}
+  RefCountBug(const CheckerBase *checker, StringRef name,
+  bool SuppressOnSink=false)
+  : BugType(checker, name, categories::MemoryRefCount,
+SuppressOnSink) {}
 
 public:
   virtual const char *getDescription() const = 0;
Index: lib/StaticAnalyzer/Checkers/RetainCountChecker/RetainCountChecker.cpp
===
--- lib/StaticAnalyzer/Checkers/RetainCountChecker/RetainCountChecker.cpp
+++ lib/StaticAnalyzer/Checkers/RetainCountChecker/RetainCountChecker.cpp
@@ -92,10 +92,10 @@
 
 class Leak : public RefCountBug {
 public:
-  Leak(const CheckerBase *checker, StringRef name) : RefCountBug(checker, name) {
-// Leaks should not be reported if they are post-dominated by a sink.
-setSuppressOnSink(true);
-  }
+  // Leaks should not be reported if they are post-dominated by a sink.
+  Leak(const CheckerBase *checker, StringRef name)
+  : RefCountBug(checker, name,
+/*SuppressOnSink=*/true) {}
 
   const char *getDescription() const override { return ""; }
 
Index: lib/StaticAnalyzer/Checkers/SimpleStreamChecker.cpp
===
--- lib/StaticAnalyzer/Checkers/SimpleStreamChecker.cpp
+++ lib/StaticAnalyzer/Checkers/SimpleStreamChecker.cpp
@@ -109,10 +109,10 @@
   DoubleCloseBugType.reset(
   new BugType(this, "Double fclose", "Unix Stream API Error"));
 
-  LeakBugType.reset(
-  new BugType(this, "Resource Leak", "Unix Stream API Error"));
   // Sinks are higher importance bugs as well as calls to assert() or exit(0).
-  LeakBugType->setSuppressOnSink(true);
+  LeakBugType.reset(
+  new BugType(this, "Resource Leak", "Unix Stream API Error",
+  /*SuppressOnSink=*/true));
 }
 
 void SimpleStreamChecker::checkPostCall(const CallEvent ,
Index: lib/StaticAnalyzer/Checkers/IteratorChecker.cpp
===
--- lib/StaticAnalyzer/Checkers/IteratorChecker.cpp
+++ lib/StaticAnalyzer/Checkers/IteratorChecker.cpp
@@ -399,14 +399,14 @@
 
 IteratorChecker::IteratorChecker() {
   OutOfRangeBugType.reset(
-  new BugType(this, "Iterator out of range", "Misuse of STL APIs"));
-  OutOfRangeBugType->setSuppressOnSink(true);
+  new BugType(this, "Iterator out of range", "Misuse of STL APIs",
+  /*SuppressOnSink=*/true));
   MismatchedBugType.reset(
-  new BugType(this, "Iterator(s) mismatched", "Misuse of STL APIs"));
-  MismatchedBugType->setSuppressOnSink(true);
+  new BugType(this, "Iterator(s) mismatched", "Misuse of STL APIs",
+  /*SuppressOnSink=*/true));
   InvalidatedBugType.reset(
-  new BugType(this, "Iterator invalidated", "Misuse of STL APIs"));
-  InvalidatedBugType->setSuppressOnSink(true);
+  new BugType(this, "Iterator invalidated", "Misuse of STL APIs",
+  /*SuppressOnSink=*/true));
 }
 
 void IteratorChecker::checkPreCall(const CallEvent ,
Index: lib/StaticAnalyzer/Checkers/ValistChecker.cpp
===
--- lib/StaticAnalyzer/Checkers/ValistChecker.cpp
+++ lib/StaticAnalyzer/Checkers/ValistChecker.cpp
@@ -276,8 +276,8 @@
   new BugType(CheckNames[CK_Unterminated].getName().empty()
   ? CheckNames[CK_Uninitialized]
   : CheckNames[CK_Unterminated],
-  "Leaked va_list", categories::MemoryError));
-  BT_leakedvalist->setSuppressOnSink(true);
+  "Leaked va_list", categories::MemoryError,
+  

[PATCH] D56896: Update property prefix regex to allow numbers.

2019-01-17 Thread Yan Zhang via Phabricator via cfe-commits
Wizard created this revision.
Herald added subscribers: cfe-commits, jfb.

Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D56896

Files:
  clang-tidy/objc/PropertyDeclarationCheck.cpp
  test/clang-tidy/objc-property-declaration.m


Index: test/clang-tidy/objc-property-declaration.m
===
--- test/clang-tidy/objc-property-declaration.m
+++ test/clang-tidy/objc-property-declaration.m
@@ -46,9 +46,10 @@
 @property(strong, nonatomic) NSString *URLStr;
 @property(assign, nonatomic) int abc_camelCase;
 @property(strong, nonatomic) NSString *abc_URL;
+@property(strong, nonatomic) NSString *opac2_sourceComponent;
 @end
 
 @interface Foo ()
 @property(assign, nonatomic) int abc_inClassExtension;
 // CHECK-MESSAGES: :[[@LINE-1]]:34: warning: property name 
'abc_inClassExtension' not using lowerCamelCase style or not prefixed in a 
category, according to the Apple Coding Guidelines [objc-property-declaration]
 @end
\ No newline at end of file
Index: clang-tidy/objc/PropertyDeclarationCheck.cpp
===
--- clang-tidy/objc/PropertyDeclarationCheck.cpp
+++ clang-tidy/objc/PropertyDeclarationCheck.cpp
@@ -81,7 +81,8 @@
 }
 
 bool hasCategoryPropertyPrefix(llvm::StringRef PropertyName) {
-  auto RegexExp = llvm::Regex("^[a-zA-Z]+_[a-zA-Z0-9][a-zA-Z0-9_]+$");
+  auto RegexExp =
+  llvm::Regex("^[a-zA-Z][a-zA-Z0-9]*_[a-zA-Z0-9][a-zA-Z0-9_]+$");
   return RegexExp.match(PropertyName);
 }
 
@@ -92,8 +93,7 @@
   if (Prefix.lower() != Prefix) {
 return false;
   }
-  auto RegexExp =
-  llvm::Regex(llvm::StringRef(validPropertyNameRegex(false)));
+  auto RegexExp = llvm::Regex(llvm::StringRef(validPropertyNameRegex(false)));
   return RegexExp.match(PropertyName.substr(Start + 1));
 }
 }  // namespace
@@ -110,13 +110,12 @@
   // this check should only be applied to ObjC sources.
   if (!getLangOpts().ObjC) return;
 
-  Finder->addMatcher(
-  objcPropertyDecl(
-  // the property name should be in Lower Camel Case like
-  // 'lowerCamelCase'
-  unless(matchesName(validPropertyNameRegex(true
-  .bind("property"),
-  this);
+  Finder->addMatcher(objcPropertyDecl(
+ // the property name should be in Lower Camel Case 
like
+ // 'lowerCamelCase'
+ unless(matchesName(validPropertyNameRegex(true
+ .bind("property"),
+ this);
 }
 
 void PropertyDeclarationCheck::check(const MatchFinder::MatchResult ) {


Index: test/clang-tidy/objc-property-declaration.m
===
--- test/clang-tidy/objc-property-declaration.m
+++ test/clang-tidy/objc-property-declaration.m
@@ -46,9 +46,10 @@
 @property(strong, nonatomic) NSString *URLStr;
 @property(assign, nonatomic) int abc_camelCase;
 @property(strong, nonatomic) NSString *abc_URL;
+@property(strong, nonatomic) NSString *opac2_sourceComponent;
 @end
 
 @interface Foo ()
 @property(assign, nonatomic) int abc_inClassExtension;
 // CHECK-MESSAGES: :[[@LINE-1]]:34: warning: property name 'abc_inClassExtension' not using lowerCamelCase style or not prefixed in a category, according to the Apple Coding Guidelines [objc-property-declaration]
 @end
\ No newline at end of file
Index: clang-tidy/objc/PropertyDeclarationCheck.cpp
===
--- clang-tidy/objc/PropertyDeclarationCheck.cpp
+++ clang-tidy/objc/PropertyDeclarationCheck.cpp
@@ -81,7 +81,8 @@
 }
 
 bool hasCategoryPropertyPrefix(llvm::StringRef PropertyName) {
-  auto RegexExp = llvm::Regex("^[a-zA-Z]+_[a-zA-Z0-9][a-zA-Z0-9_]+$");
+  auto RegexExp =
+  llvm::Regex("^[a-zA-Z][a-zA-Z0-9]*_[a-zA-Z0-9][a-zA-Z0-9_]+$");
   return RegexExp.match(PropertyName);
 }
 
@@ -92,8 +93,7 @@
   if (Prefix.lower() != Prefix) {
 return false;
   }
-  auto RegexExp =
-  llvm::Regex(llvm::StringRef(validPropertyNameRegex(false)));
+  auto RegexExp = llvm::Regex(llvm::StringRef(validPropertyNameRegex(false)));
   return RegexExp.match(PropertyName.substr(Start + 1));
 }
 }  // namespace
@@ -110,13 +110,12 @@
   // this check should only be applied to ObjC sources.
   if (!getLangOpts().ObjC) return;
 
-  Finder->addMatcher(
-  objcPropertyDecl(
-  // the property name should be in Lower Camel Case like
-  // 'lowerCamelCase'
-  unless(matchesName(validPropertyNameRegex(true
-  .bind("property"),
-  this);
+  Finder->addMatcher(objcPropertyDecl(
+ // the property name should be in Lower Camel Case like
+ // 'lowerCamelCase'
+ unless(matchesName(validPropertyNameRegex(true
+ .bind("property"),
+ this);
 }
 
 void PropertyDeclarationCheck::check(const MatchFinder::MatchResult ) 

[PATCH] D56820: [analyzer] [RetainCountChecker] Produce a correct message when OSTypeAlloc is used

2019-01-17 Thread George Karpenkov via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rC351509: [analyzer] [RetainCountChecker] Produce a correct 
message when OSTypeAlloc is… (authored by george.karpenkov, committed by ).
Herald added a subscriber: cfe-commits.

Changed prior to commit:
  https://reviews.llvm.org/D56820?vs=182194=182441#toc

Repository:
  rC Clang

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

https://reviews.llvm.org/D56820

Files:
  lib/StaticAnalyzer/Checkers/RetainCountChecker/RetainCountDiagnostics.cpp
  test/Analysis/os_object_base.h
  test/Analysis/osobject-retain-release.cpp


Index: test/Analysis/os_object_base.h
===
--- test/Analysis/os_object_base.h
+++ test/Analysis/os_object_base.h
@@ -47,7 +47,7 @@
 };
 
 struct OSMetaClass : public OSMetaClassBase {
-  virtual OSObject * alloc();
+  virtual OSObject * alloc() const;
   virtual ~OSMetaClass(){}
 };
 
Index: test/Analysis/osobject-retain-release.cpp
===
--- test/Analysis/osobject-retain-release.cpp
+++ test/Analysis/osobject-retain-release.cpp
@@ -627,3 +627,10 @@
   }
   obj->release();
 }
+
+void test_ostypealloc_correct_diagnostic_name() {
+  OSArray *arr = OSTypeAlloc(OSArray); // expected-note{{Call to method 
'OSMetaClass::alloc' returns an OSObject of type 'OSArray' with a +1 retain 
count}}
+  arr->retain(); // expected-note{{Reference count incremented. The object now 
has a +2 retain count}}
+  arr->release(); // expected-note{{Reference count decremented. The object 
now has a +1 retain count}}
+} // expected-note{{Object leaked: object allocated and stored into 'arr' is 
not referenced later in this execution path and has a retain count of +1}}
+  // expected-warning@-1{{Potential leak of an object stored into 'arr'}}
Index: lib/StaticAnalyzer/Checkers/RetainCountChecker/RetainCountDiagnostics.cpp
===
--- lib/StaticAnalyzer/Checkers/RetainCountChecker/RetainCountDiagnostics.cpp
+++ lib/StaticAnalyzer/Checkers/RetainCountChecker/RetainCountDiagnostics.cpp
@@ -132,6 +132,32 @@
   return None;
 }
 
+Optional findMetaClassAlloc(const Expr *Callee) {
+  if (const auto *ME = dyn_cast(Callee)) {
+if (ME->getMemberDecl()->getNameAsString() != "alloc")
+  return None;
+const Expr *This = ME->getBase()->IgnoreParenImpCasts();
+if (const auto *DRE = dyn_cast(This)) {
+  const ValueDecl *VD = DRE->getDecl();
+  if (VD->getNameAsString() != "metaClass")
+return None;
+
+  if (const auto *RD = dyn_cast(VD->getDeclContext()))
+return RD->getNameAsString();
+
+}
+  }
+  return None;
+}
+
+std::string findAllocatedObjectName(const Stmt *S,
+QualType QT) {
+  if (const auto *CE = dyn_cast(S))
+if (auto Out = findMetaClassAlloc(CE->getCallee()))
+  return *Out;
+  return getPrettyTypeName(QT);
+}
+
 static void generateDiagnosticsForCallLike(ProgramStateRef CurrSt,
const LocationContext *LCtx,
const RefVal , SymbolRef ,
@@ -189,7 +215,7 @@
 os << "a Core Foundation object of type '"
<< Sym->getType().getAsString() << "' with a ";
   } else if (CurrV.getObjKind() == ObjKind::OS) {
-os << "an OSObject of type '" << getPrettyTypeName(Sym->getType())
+os << "an OSObject of type '" << findAllocatedObjectName(S, Sym->getType())
<< "' with a ";
   } else if (CurrV.getObjKind() == ObjKind::Generalized) {
 os << "an object of type '" << Sym->getType().getAsString()


Index: test/Analysis/os_object_base.h
===
--- test/Analysis/os_object_base.h
+++ test/Analysis/os_object_base.h
@@ -47,7 +47,7 @@
 };
 
 struct OSMetaClass : public OSMetaClassBase {
-  virtual OSObject * alloc();
+  virtual OSObject * alloc() const;
   virtual ~OSMetaClass(){}
 };
 
Index: test/Analysis/osobject-retain-release.cpp
===
--- test/Analysis/osobject-retain-release.cpp
+++ test/Analysis/osobject-retain-release.cpp
@@ -627,3 +627,10 @@
   }
   obj->release();
 }
+
+void test_ostypealloc_correct_diagnostic_name() {
+  OSArray *arr = OSTypeAlloc(OSArray); // expected-note{{Call to method 'OSMetaClass::alloc' returns an OSObject of type 'OSArray' with a +1 retain count}}
+  arr->retain(); // expected-note{{Reference count incremented. The object now has a +2 retain count}}
+  arr->release(); // expected-note{{Reference count decremented. The object now has a +1 retain count}}
+} // expected-note{{Object leaked: object allocated and stored into 'arr' is not referenced later in this execution path and has a retain count of +1}}
+  // expected-warning@-1{{Potential leak of an object stored into 'arr'}}
Index: 

r351514 - [analyzer] Introduce proper diagnostic for freeing unowned object

2019-01-17 Thread George Karpenkov via cfe-commits
Author: george.karpenkov
Date: Thu Jan 17 19:13:53 2019
New Revision: 351514

URL: http://llvm.org/viewvc/llvm-project?rev=351514=rev
Log:
[analyzer] Introduce proper diagnostic for freeing unowned object

Insert a note when the object becomes not (exclusively) owned.

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

Modified:

cfe/trunk/lib/StaticAnalyzer/Checkers/RetainCountChecker/RetainCountChecker.cpp

cfe/trunk/lib/StaticAnalyzer/Checkers/RetainCountChecker/RetainCountChecker.h

cfe/trunk/lib/StaticAnalyzer/Checkers/RetainCountChecker/RetainCountDiagnostics.cpp

cfe/trunk/lib/StaticAnalyzer/Checkers/RetainCountChecker/RetainCountDiagnostics.h
cfe/trunk/test/Analysis/osobject-retain-release.cpp

Modified: 
cfe/trunk/lib/StaticAnalyzer/Checkers/RetainCountChecker/RetainCountChecker.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/StaticAnalyzer/Checkers/RetainCountChecker/RetainCountChecker.cpp?rev=351514=351513=351514=diff
==
--- 
cfe/trunk/lib/StaticAnalyzer/Checkers/RetainCountChecker/RetainCountChecker.cpp 
(original)
+++ 
cfe/trunk/lib/StaticAnalyzer/Checkers/RetainCountChecker/RetainCountChecker.cpp 
Thu Jan 17 19:13:53 2019
@@ -803,13 +803,16 @@ ProgramStateRef RetainCountChecker::upda
 }
 
 const RefCountBug &
-RetainCountChecker::errorKindToBugKind(RefVal::Kind ErrorKind) const {
+RetainCountChecker::errorKindToBugKind(RefVal::Kind ErrorKind,
+   SymbolRef Sym) const {
   switch (ErrorKind) {
 case RefVal::ErrorUseAfterRelease:
   return useAfterRelease;
 case RefVal::ErrorReleaseNotOwned:
   return releaseNotOwned;
 case RefVal::ErrorDeallocNotOwned:
+  if (Sym->getType()->getPointeeCXXRecordDecl())
+return freeNotOwned;
   return deallocNotOwned;
 default:
   llvm_unreachable("Unhandled error.");
@@ -836,7 +839,8 @@ void RetainCountChecker::processNonLeakE
 return;
 
   auto report = llvm::make_unique(
-  errorKindToBugKind(ErrorKind), C.getASTContext().getLangOpts(), N, Sym);
+  errorKindToBugKind(ErrorKind, Sym),
+  C.getASTContext().getLangOpts(), N, Sym);
   report->addRange(ErrorRange);
   C.emitReport(std::move(report));
 }

Modified: 
cfe/trunk/lib/StaticAnalyzer/Checkers/RetainCountChecker/RetainCountChecker.h
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/StaticAnalyzer/Checkers/RetainCountChecker/RetainCountChecker.h?rev=351514=351513=351514=diff
==
--- 
cfe/trunk/lib/StaticAnalyzer/Checkers/RetainCountChecker/RetainCountChecker.h 
(original)
+++ 
cfe/trunk/lib/StaticAnalyzer/Checkers/RetainCountChecker/RetainCountChecker.h 
Thu Jan 17 19:13:53 2019
@@ -255,6 +255,7 @@ class RetainCountChecker
   RefCountBug useAfterRelease{this, RefCountBug::UseAfterRelease};
   RefCountBug releaseNotOwned{this, RefCountBug::ReleaseNotOwned};
   RefCountBug deallocNotOwned{this, RefCountBug::DeallocNotOwned};
+  RefCountBug freeNotOwned{this, RefCountBug::FreeNotOwned};
   RefCountBug overAutorelease{this, RefCountBug::OverAutorelease};
   RefCountBug returnNotOwnedForOwned{this, 
RefCountBug::ReturnNotOwnedForOwned};
   RefCountBug leakWithinFunction{this, RefCountBug::LeakWithinFunction};
@@ -336,8 +337,8 @@ public:
RefVal V, ArgEffect E, RefVal::Kind ,
CheckerContext ) const;
 
-
-  const RefCountBug (RefVal::Kind ErrorKind) const;
+  const RefCountBug (RefVal::Kind ErrorKind,
+SymbolRef Sym) const;
 
   void processNonLeakError(ProgramStateRef St, SourceRange ErrorRange,
RefVal::Kind ErrorKind, SymbolRef Sym,

Modified: 
cfe/trunk/lib/StaticAnalyzer/Checkers/RetainCountChecker/RetainCountDiagnostics.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/StaticAnalyzer/Checkers/RetainCountChecker/RetainCountDiagnostics.cpp?rev=351514=351513=351514=diff
==
--- 
cfe/trunk/lib/StaticAnalyzer/Checkers/RetainCountChecker/RetainCountDiagnostics.cpp
 (original)
+++ 
cfe/trunk/lib/StaticAnalyzer/Checkers/RetainCountChecker/RetainCountDiagnostics.cpp
 Thu Jan 17 19:13:53 2019
@@ -27,6 +27,8 @@ StringRef RefCountBug::bugTypeToName(Ref
 return "Bad release";
   case DeallocNotOwned:
 return "-dealloc sent to non-exclusively owned object";
+  case FreeNotOwned:
+return "freeing non-exclusively owned object";
   case OverAutorelease:
 return "Object autoreleased too many times";
   case ReturnNotOwnedForOwned:
@@ -47,6 +49,8 @@ StringRef RefCountBug::getDescription()
"not owned at this point by the caller";
   case DeallocNotOwned:
 return "-dealloc sent to object that may be referenced elsewhere";
+  case FreeNotOwned:
+return  "'free' called on an object that may be 

r351513 - [analyzer] Extend the PathDiagnosticLocation constructor to handle CallExitEnd

2019-01-17 Thread George Karpenkov via cfe-commits
Author: george.karpenkov
Date: Thu Jan 17 19:13:40 2019
New Revision: 351513

URL: http://llvm.org/viewvc/llvm-project?rev=351513=rev
Log:
[analyzer] Extend the PathDiagnosticLocation constructor to handle CallExitEnd

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

Modified:

cfe/trunk/lib/StaticAnalyzer/Checkers/RetainCountChecker/RetainCountDiagnostics.cpp
cfe/trunk/lib/StaticAnalyzer/Core/BugReporterVisitors.cpp
cfe/trunk/lib/StaticAnalyzer/Core/PathDiagnostic.cpp

Modified: 
cfe/trunk/lib/StaticAnalyzer/Checkers/RetainCountChecker/RetainCountDiagnostics.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/StaticAnalyzer/Checkers/RetainCountChecker/RetainCountDiagnostics.cpp?rev=351513=351512=351513=diff
==
--- 
cfe/trunk/lib/StaticAnalyzer/Checkers/RetainCountChecker/RetainCountDiagnostics.cpp
 (original)
+++ 
cfe/trunk/lib/StaticAnalyzer/Checkers/RetainCountChecker/RetainCountDiagnostics.cpp
 Thu Jan 17 19:13:40 2019
@@ -408,15 +408,7 @@ annotateConsumedSummaryMismatch(const Ex
   if (os.str().empty())
 return nullptr;
 
-  // FIXME: remove the code duplication with NoStoreFuncVisitor.
-  PathDiagnosticLocation L;
-  if (const ReturnStmt *RS = CallExitLoc.getReturnStmt()) {
-L = PathDiagnosticLocation::createBegin(RS, SM, N->getLocationContext());
-  } else {
-L = PathDiagnosticLocation(
-Call->getRuntimeDefinition().getDecl()->getSourceRange().getEnd(), SM);
-  }
-
+  PathDiagnosticLocation L = PathDiagnosticLocation::create(CallExitLoc, SM);
   return std::make_shared(L, os.str());
 }
 

Modified: cfe/trunk/lib/StaticAnalyzer/Core/BugReporterVisitors.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/StaticAnalyzer/Core/BugReporterVisitors.cpp?rev=351513=351512=351513=diff
==
--- cfe/trunk/lib/StaticAnalyzer/Core/BugReporterVisitors.cpp (original)
+++ cfe/trunk/lib/StaticAnalyzer/Core/BugReporterVisitors.cpp Thu Jan 17 
19:13:40 2019
@@ -308,9 +308,8 @@ public:
 if (RegionOfInterest->isSubRegionOf(SelfRegion) &&
 potentiallyWritesIntoIvar(Call->getRuntimeDefinition().getDecl(),
   IvarR->getDecl()))
-  return notModifiedDiagnostics(Ctx, *CallExitLoc, Call, {}, 
SelfRegion,
-"self", /*FirstIsReferenceType=*/false,
-1);
+  return notModifiedDiagnostics(N, {}, SelfRegion, "self",
+/*FirstIsReferenceType=*/false, 1);
   }
 }
 
@@ -318,8 +317,7 @@ public:
   const MemRegion *ThisR = CCall->getCXXThisVal().getAsRegion();
   if (RegionOfInterest->isSubRegionOf(ThisR)
   && !CCall->getDecl()->isImplicit())
-return notModifiedDiagnostics(Ctx, *CallExitLoc, Call, {}, ThisR,
-  "this",
+return notModifiedDiagnostics(N, {}, ThisR, "this",
   /*FirstIsReferenceType=*/false, 1);
 
   // Do not generate diagnostics for not modified parameters in
@@ -338,18 +336,17 @@ public:
   QualType T = PVD->getType();
   while (const MemRegion *R = S.getAsRegion()) {
 if (RegionOfInterest->isSubRegionOf(R) && !isPointerToConst(T))
-  return notModifiedDiagnostics(Ctx, *CallExitLoc, Call, {}, R,
-ParamName, ParamIsReferenceType,
-IndirectionLevel);
+  return notModifiedDiagnostics(N, {}, R, ParamName,
+ParamIsReferenceType, 
IndirectionLevel);
 
 QualType PT = T->getPointeeType();
 if (PT.isNull() || PT->isVoidType()) break;
 
 if (const RecordDecl *RD = PT->getAsRecordDecl())
   if (auto P = findRegionOfInterestInRecord(RD, State, R))
-return notModifiedDiagnostics(
-  Ctx, *CallExitLoc, Call, *P, RegionOfInterest, ParamName,
-  ParamIsReferenceType, IndirectionLevel);
+return notModifiedDiagnostics(N, *P, RegionOfInterest, ParamName,
+  ParamIsReferenceType,
+  IndirectionLevel);
 
 S = State->getSVal(R, PT);
 T = PT;
@@ -523,19 +520,12 @@ private:
 
   /// \return Diagnostics piece for region not modified in the current 
function.
   std::shared_ptr
-  notModifiedDiagnostics(const LocationContext *Ctx, CallExitBegin 
,
- CallEventRef<> Call, const RegionVector ,
+  notModifiedDiagnostics(const ExplodedNode *N, const RegionVector ,
  const MemRegion *MatchedRegion, StringRef 
FirstElement,
  bool FirstIsReferenceType, unsigned IndirectionLevel) 
{
 
-PathDiagnosticLocation L;
-if (const ReturnStmt *RS = 

r351511 - [analyzer] const-ify reference to bug type used in BugReporter

2019-01-17 Thread George Karpenkov via cfe-commits
Author: george.karpenkov
Date: Thu Jan 17 19:13:14 2019
New Revision: 351511

URL: http://llvm.org/viewvc/llvm-project?rev=351511=rev
Log:
[analyzer] const-ify reference to bug type used in BugReporter

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

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

cfe/trunk/lib/StaticAnalyzer/Checkers/RetainCountChecker/RetainCountDiagnostics.h
cfe/trunk/lib/StaticAnalyzer/Core/BugReporter.cpp

Modified: cfe/trunk/include/clang/StaticAnalyzer/Core/BugReporter/BugReporter.h
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/StaticAnalyzer/Core/BugReporter/BugReporter.h?rev=351511=351510=351511=diff
==
--- cfe/trunk/include/clang/StaticAnalyzer/Core/BugReporter/BugReporter.h 
(original)
+++ cfe/trunk/include/clang/StaticAnalyzer/Core/BugReporter/BugReporter.h Thu 
Jan 17 19:13:14 2019
@@ -95,7 +95,7 @@ protected:
   friend class BugReportEquivClass;
   friend class BugReporter;
 
-  BugType& BT;
+  const BugType& BT;
   const Decl *DeclWithIssue = nullptr;
   std::string ShortDescription;
   std::string Description;
@@ -164,15 +164,15 @@ private:
   void popInterestingSymbolsAndRegions();
 
 public:
-  BugReport(BugType& bt, StringRef desc, const ExplodedNode *errornode)
+  BugReport(const BugType& bt, StringRef desc, const ExplodedNode *errornode)
   : BT(bt), Description(desc), ErrorNode(errornode) {}
 
-  BugReport(BugType& bt, StringRef shortDesc, StringRef desc,
+  BugReport(const BugType& bt, StringRef shortDesc, StringRef desc,
 const ExplodedNode *errornode)
   : BT(bt), ShortDescription(shortDesc), Description(desc),
 ErrorNode(errornode) {}
 
-  BugReport(BugType , StringRef desc, PathDiagnosticLocation l)
+  BugReport(const BugType , StringRef desc, PathDiagnosticLocation l)
   : BT(bt), Description(desc), Location(l) {}
 
   /// Create a BugReport with a custom uniqueing location.
@@ -190,7 +190,7 @@ public:
   virtual ~BugReport();
 
   const BugType& getBugType() const { return BT; }
-  BugType& getBugType() { return BT; }
+  //BugType& getBugType() { return BT; }
 
   /// True when the report has an execution path associated with it.
   ///
@@ -481,7 +481,7 @@ public:
 return {};
   }
 
-  void Register(BugType *BT);
+  void Register(const BugType *BT);
 
   /// Add the given report to the set of reports tracked by BugReporter.
   ///

Modified: 
cfe/trunk/lib/StaticAnalyzer/Checkers/RetainCountChecker/RetainCountDiagnostics.h
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/StaticAnalyzer/Checkers/RetainCountChecker/RetainCountDiagnostics.h?rev=351511=351510=351511=diff
==
--- 
cfe/trunk/lib/StaticAnalyzer/Checkers/RetainCountChecker/RetainCountDiagnostics.h
 (original)
+++ 
cfe/trunk/lib/StaticAnalyzer/Checkers/RetainCountChecker/RetainCountDiagnostics.h
 Thu Jan 17 19:13:14 2019
@@ -51,7 +51,7 @@ public:
   StringRef endText);
 
   llvm::iterator_range getRanges() override {
-const RefCountBug& BugTy = static_cast(getBugType());
+const RefCountBug& BugTy = static_cast(getBugType());
 if (!BugTy.isLeak())
   return BugReport::getRanges();
 return llvm::make_range(ranges_iterator(), ranges_iterator());

Modified: cfe/trunk/lib/StaticAnalyzer/Core/BugReporter.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/StaticAnalyzer/Core/BugReporter.cpp?rev=351511=351510=351511=diff
==
--- cfe/trunk/lib/StaticAnalyzer/Core/BugReporter.cpp (original)
+++ cfe/trunk/lib/StaticAnalyzer/Core/BugReporter.cpp Thu Jan 17 19:13:14 2019
@@ -1247,7 +1247,7 @@ static void generatePathDiagnosticsForNo
 
 static std::unique_ptr
 generateEmptyDiagnosticForReport(BugReport *R, SourceManager ) {
-  BugType  = R->getBugType();
+  const BugType  = R->getBugType();
   return llvm::make_unique(
   R->getBugType().getCheckName(), R->getDeclWithIssue(),
   R->getBugType().getName(), R->getDescription(),
@@ -2684,7 +2684,7 @@ GRBugReporter::generatePathDiagnostics(
   return Out;
 }
 
-void BugReporter::Register(BugType *BT) {
+void BugReporter::Register(const BugType *BT) {
   BugTypes = F.add(BugTypes, BT);
 }
 
@@ -2718,7 +2718,7 @@ void BugReporter::emitReport(std::unique
   R->Profile(ID);
 
   // Lookup the equivance class.  If there isn't one, create it.
-  BugType& BT = R->getBugType();
+  const BugType& BT = R->getBugType();
   Register();
   void *InsertPos;
   BugReportEquivClass* EQ = EQClasses.FindNodeOrInsertPos(ID, InsertPos);
@@ -2836,7 +2836,7 @@ FindReportInEquivalenceClass(BugReportEq
  SmallVectorImpl ) {
   BugReportEquivClass::iterator I = EQ.begin(), E = EQ.end();
   assert(I != E);
-  BugType& BT = I->getBugType();
+  const BugType& BT = I->getBugType();
 
   

r351512 - [analyzer] [NFC] Clean up messy handling of bug categories in RetainCountChecker

2019-01-17 Thread George Karpenkov via cfe-commits
Author: george.karpenkov
Date: Thu Jan 17 19:13:27 2019
New Revision: 351512

URL: http://llvm.org/viewvc/llvm-project?rev=351512=rev
Log:
[analyzer] [NFC] Clean up messy handling of bug categories in RetainCountChecker

https://reviews.llvm.org/D56887

Modified:

cfe/trunk/lib/StaticAnalyzer/Checkers/RetainCountChecker/RetainCountChecker.cpp

cfe/trunk/lib/StaticAnalyzer/Checkers/RetainCountChecker/RetainCountChecker.h

cfe/trunk/lib/StaticAnalyzer/Checkers/RetainCountChecker/RetainCountDiagnostics.cpp

cfe/trunk/lib/StaticAnalyzer/Checkers/RetainCountChecker/RetainCountDiagnostics.h

Modified: 
cfe/trunk/lib/StaticAnalyzer/Checkers/RetainCountChecker/RetainCountChecker.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/StaticAnalyzer/Checkers/RetainCountChecker/RetainCountChecker.cpp?rev=351512=351511=351512=diff
==
--- 
cfe/trunk/lib/StaticAnalyzer/Checkers/RetainCountChecker/RetainCountChecker.cpp 
(original)
+++ 
cfe/trunk/lib/StaticAnalyzer/Checkers/RetainCountChecker/RetainCountChecker.cpp 
Thu Jan 17 19:13:27 2019
@@ -29,6 +29,10 @@ const RefVal *getRefBinding(ProgramState
   return State->get(Sym);
 }
 
+} // end namespace retaincountchecker
+} // end namespace ento
+} // end namespace clang
+
 static ProgramStateRef setRefBinding(ProgramStateRef State, SymbolRef Sym,
  RefVal Val) {
   assert(Sym != nullptr);
@@ -39,73 +43,6 @@ static ProgramStateRef removeRefBinding(
   return State->remove(Sym);
 }
 
-class UseAfterRelease : public RefCountBug {
-public:
-  UseAfterRelease(const CheckerBase *checker)
-  : RefCountBug(checker, "Use-after-release") {}
-
-  const char *getDescription() const override {
-return "Reference-counted object is used after it is released";
-  }
-};
-
-class BadRelease : public RefCountBug {
-public:
-  BadRelease(const CheckerBase *checker) : RefCountBug(checker, "Bad release") 
{}
-
-  const char *getDescription() const override {
-return "Incorrect decrement of the reference count of an object that is "
-   "not owned at this point by the caller";
-  }
-};
-
-class DeallocNotOwned : public RefCountBug {
-public:
-  DeallocNotOwned(const CheckerBase *checker)
-  : RefCountBug(checker, "-dealloc sent to non-exclusively owned object") 
{}
-
-  const char *getDescription() const override {
-return "-dealloc sent to object that may be referenced elsewhere";
-  }
-};
-
-class OverAutorelease : public RefCountBug {
-public:
-  OverAutorelease(const CheckerBase *checker)
-  : RefCountBug(checker, "Object autoreleased too many times") {}
-
-  const char *getDescription() const override {
-return "Object autoreleased too many times";
-  }
-};
-
-class ReturnedNotOwnedForOwned : public RefCountBug {
-public:
-  ReturnedNotOwnedForOwned(const CheckerBase *checker)
-  : RefCountBug(checker, "Method should return an owned object") {}
-
-  const char *getDescription() const override {
-return "Object with a +0 retain count returned to caller where a +1 "
-   "(owning) retain count is expected";
-  }
-};
-
-class Leak : public RefCountBug {
-public:
-  // Leaks should not be reported if they are post-dominated by a sink.
-  Leak(const CheckerBase *checker, StringRef name)
-  : RefCountBug(checker, name,
-/*SuppressOnSink=*/true) {}
-
-  const char *getDescription() const override { return ""; }
-
-  bool isLeak() const override { return true; }
-};
-
-} // end namespace retaincountchecker
-} // end namespace ento
-} // end namespace clang
-
 void RefVal::print(raw_ostream ) const {
   if (!T.isNull())
 Out << "Tracked " << T.getAsString() << " | ";
@@ -414,20 +351,6 @@ void RetainCountChecker::checkPostCall(c
   checkSummary(*Summ, Call, C);
 }
 
-RefCountBug *
-RetainCountChecker::getLeakWithinFunctionBug(const LangOptions ) const {
-  if (!leakWithinFunction)
-leakWithinFunction.reset(new Leak(this, "Leak"));
-  return leakWithinFunction.get();
-}
-
-RefCountBug *
-RetainCountChecker::getLeakAtReturnBug(const LangOptions ) const {
-  if (!leakAtReturn)
-leakAtReturn.reset(new Leak(this, "Leak of returned object"));
-  return leakAtReturn.get();
-}
-
 /// GetReturnType - Used to get the return type of a message expression or
 ///  function call with the intention of affixing that type to a tracked 
symbol.
 ///  While the return type can be queried directly from RetEx, when
@@ -879,6 +802,20 @@ ProgramStateRef RetainCountChecker::upda
   return setRefBinding(state, sym, V);
 }
 
+const RefCountBug &
+RetainCountChecker::errorKindToBugKind(RefVal::Kind ErrorKind) const {
+  switch (ErrorKind) {
+case RefVal::ErrorUseAfterRelease:
+  return useAfterRelease;
+case RefVal::ErrorReleaseNotOwned:
+  return releaseNotOwned;
+case RefVal::ErrorDeallocNotOwned:
+  return deallocNotOwned;
+default:
+  llvm_unreachable("Unhandled error.");
+ 

r351509 - [analyzer] [RetainCountChecker] Produce a correct message when OSTypeAlloc is used

2019-01-17 Thread George Karpenkov via cfe-commits
Author: george.karpenkov
Date: Thu Jan 17 19:12:48 2019
New Revision: 351509

URL: http://llvm.org/viewvc/llvm-project?rev=351509=rev
Log:
[analyzer] [RetainCountChecker] Produce a correct message when OSTypeAlloc is 
used

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

Modified:

cfe/trunk/lib/StaticAnalyzer/Checkers/RetainCountChecker/RetainCountDiagnostics.cpp
cfe/trunk/test/Analysis/os_object_base.h
cfe/trunk/test/Analysis/osobject-retain-release.cpp

Modified: 
cfe/trunk/lib/StaticAnalyzer/Checkers/RetainCountChecker/RetainCountDiagnostics.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/StaticAnalyzer/Checkers/RetainCountChecker/RetainCountDiagnostics.cpp?rev=351509=351508=351509=diff
==
--- 
cfe/trunk/lib/StaticAnalyzer/Checkers/RetainCountChecker/RetainCountDiagnostics.cpp
 (original)
+++ 
cfe/trunk/lib/StaticAnalyzer/Checkers/RetainCountChecker/RetainCountDiagnostics.cpp
 Thu Jan 17 19:12:48 2019
@@ -132,6 +132,32 @@ static Optional findArgIdxOfSy
   return None;
 }
 
+Optional findMetaClassAlloc(const Expr *Callee) {
+  if (const auto *ME = dyn_cast(Callee)) {
+if (ME->getMemberDecl()->getNameAsString() != "alloc")
+  return None;
+const Expr *This = ME->getBase()->IgnoreParenImpCasts();
+if (const auto *DRE = dyn_cast(This)) {
+  const ValueDecl *VD = DRE->getDecl();
+  if (VD->getNameAsString() != "metaClass")
+return None;
+
+  if (const auto *RD = dyn_cast(VD->getDeclContext()))
+return RD->getNameAsString();
+
+}
+  }
+  return None;
+}
+
+std::string findAllocatedObjectName(const Stmt *S,
+QualType QT) {
+  if (const auto *CE = dyn_cast(S))
+if (auto Out = findMetaClassAlloc(CE->getCallee()))
+  return *Out;
+  return getPrettyTypeName(QT);
+}
+
 static void generateDiagnosticsForCallLike(ProgramStateRef CurrSt,
const LocationContext *LCtx,
const RefVal , SymbolRef ,
@@ -189,7 +215,7 @@ static void generateDiagnosticsForCallLi
 os << "a Core Foundation object of type '"
<< Sym->getType().getAsString() << "' with a ";
   } else if (CurrV.getObjKind() == ObjKind::OS) {
-os << "an OSObject of type '" << getPrettyTypeName(Sym->getType())
+os << "an OSObject of type '" << findAllocatedObjectName(S, Sym->getType())
<< "' with a ";
   } else if (CurrV.getObjKind() == ObjKind::Generalized) {
 os << "an object of type '" << Sym->getType().getAsString()

Modified: cfe/trunk/test/Analysis/os_object_base.h
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/Analysis/os_object_base.h?rev=351509=351508=351509=diff
==
--- cfe/trunk/test/Analysis/os_object_base.h (original)
+++ cfe/trunk/test/Analysis/os_object_base.h Thu Jan 17 19:12:48 2019
@@ -47,7 +47,7 @@ struct OSObject : public OSMetaClassBase
 };
 
 struct OSMetaClass : public OSMetaClassBase {
-  virtual OSObject * alloc();
+  virtual OSObject * alloc() const;
   virtual ~OSMetaClass(){}
 };
 

Modified: cfe/trunk/test/Analysis/osobject-retain-release.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/Analysis/osobject-retain-release.cpp?rev=351509=351508=351509=diff
==
--- cfe/trunk/test/Analysis/osobject-retain-release.cpp (original)
+++ cfe/trunk/test/Analysis/osobject-retain-release.cpp Thu Jan 17 19:12:48 2019
@@ -627,3 +627,10 @@ void test_smart_ptr_no_leak() {
   }
   obj->release();
 }
+
+void test_ostypealloc_correct_diagnostic_name() {
+  OSArray *arr = OSTypeAlloc(OSArray); // expected-note{{Call to method 
'OSMetaClass::alloc' returns an OSObject of type 'OSArray' with a +1 retain 
count}}
+  arr->retain(); // expected-note{{Reference count incremented. The object now 
has a +2 retain count}}
+  arr->release(); // expected-note{{Reference count decremented. The object 
now has a +1 retain count}}
+} // expected-note{{Object leaked: object allocated and stored into 'arr' is 
not referenced later in this execution path and has a retain count of +1}}
+  // expected-warning@-1{{Potential leak of an object stored into 'arr'}}


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


r351510 - [analyzer] Extend BugType constructor to accept "SuppressOnSink" as a parameter

2019-01-17 Thread George Karpenkov via cfe-commits
Author: george.karpenkov
Date: Thu Jan 17 19:13:01 2019
New Revision: 351510

URL: http://llvm.org/viewvc/llvm-project?rev=351510=rev
Log:
[analyzer] Extend BugType constructor to accept "SuppressOnSink" as a parameter

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

Modified:
cfe/trunk/include/clang/StaticAnalyzer/Core/BugReporter/BugType.h
cfe/trunk/lib/StaticAnalyzer/Checkers/IteratorChecker.cpp
cfe/trunk/lib/StaticAnalyzer/Checkers/MallocChecker.cpp

cfe/trunk/lib/StaticAnalyzer/Checkers/RetainCountChecker/RetainCountChecker.cpp

cfe/trunk/lib/StaticAnalyzer/Checkers/RetainCountChecker/RetainCountDiagnostics.h
cfe/trunk/lib/StaticAnalyzer/Checkers/SimpleStreamChecker.cpp
cfe/trunk/lib/StaticAnalyzer/Checkers/ValistChecker.cpp

Modified: cfe/trunk/include/clang/StaticAnalyzer/Core/BugReporter/BugType.h
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/StaticAnalyzer/Core/BugReporter/BugType.h?rev=351510=351509=351510=diff
==
--- cfe/trunk/include/clang/StaticAnalyzer/Core/BugReporter/BugType.h (original)
+++ cfe/trunk/include/clang/StaticAnalyzer/Core/BugReporter/BugType.h Thu Jan 
17 19:13:01 2019
@@ -38,12 +38,14 @@ private:
   virtual void anchor();
 
 public:
-  BugType(CheckName Check, StringRef Name, StringRef Cat)
+  BugType(CheckName Check, StringRef Name, StringRef Cat,
+  bool SuppressOnSink=false)
   : Check(Check), Name(Name), Category(Cat), Checker(nullptr),
-SuppressOnSink(false) {}
-  BugType(const CheckerBase *Checker, StringRef Name, StringRef Cat)
+SuppressOnSink(SuppressOnSink) {}
+  BugType(const CheckerBase *Checker, StringRef Name, StringRef Cat,
+  bool SuppressOnSink=false)
   : Check(Checker->getCheckName()), Name(Name), Category(Cat),
-Checker(Checker), SuppressOnSink(false) {}
+Checker(Checker), SuppressOnSink(SuppressOnSink) {}
   virtual ~BugType() = default;
 
   StringRef getName() const { return Name; }
@@ -64,7 +66,6 @@ public:
   ///  type should be suppressed if the end node of the report is 
post-dominated
   ///  by a sink node.
   bool isSuppressOnSink() const { return SuppressOnSink; }
-  void setSuppressOnSink(bool x) { SuppressOnSink = x; }
 };
 
 class BuiltinBug : public BugType {

Modified: cfe/trunk/lib/StaticAnalyzer/Checkers/IteratorChecker.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/StaticAnalyzer/Checkers/IteratorChecker.cpp?rev=351510=351509=351510=diff
==
--- cfe/trunk/lib/StaticAnalyzer/Checkers/IteratorChecker.cpp (original)
+++ cfe/trunk/lib/StaticAnalyzer/Checkers/IteratorChecker.cpp Thu Jan 17 
19:13:01 2019
@@ -399,14 +399,14 @@ bool isZero(ProgramStateRef State, const
 
 IteratorChecker::IteratorChecker() {
   OutOfRangeBugType.reset(
-  new BugType(this, "Iterator out of range", "Misuse of STL APIs"));
-  OutOfRangeBugType->setSuppressOnSink(true);
+  new BugType(this, "Iterator out of range", "Misuse of STL APIs",
+  /*SuppressOnSink=*/true));
   MismatchedBugType.reset(
-  new BugType(this, "Iterator(s) mismatched", "Misuse of STL APIs"));
-  MismatchedBugType->setSuppressOnSink(true);
+  new BugType(this, "Iterator(s) mismatched", "Misuse of STL APIs",
+  /*SuppressOnSink=*/true));
   InvalidatedBugType.reset(
-  new BugType(this, "Iterator invalidated", "Misuse of STL APIs"));
-  InvalidatedBugType->setSuppressOnSink(true);
+  new BugType(this, "Iterator invalidated", "Misuse of STL APIs",
+  /*SuppressOnSink=*/true));
 }
 
 void IteratorChecker::checkPreCall(const CallEvent ,

Modified: cfe/trunk/lib/StaticAnalyzer/Checkers/MallocChecker.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/StaticAnalyzer/Checkers/MallocChecker.cpp?rev=351510=351509=351510=diff
==
--- cfe/trunk/lib/StaticAnalyzer/Checkers/MallocChecker.cpp (original)
+++ cfe/trunk/lib/StaticAnalyzer/Checkers/MallocChecker.cpp Thu Jan 17 19:13:01 
2019
@@ -2301,14 +2301,14 @@ void MallocChecker::reportLeak(SymbolRef
 
   assert(N);
   if (!BT_Leak[*CheckKind]) {
-BT_Leak[*CheckKind].reset(new BugType(CheckNames[*CheckKind], "Memory 
leak",
-  categories::MemoryError));
 // Leaks should not be reported if they are post-dominated by a sink:
 // (1) Sinks are higher importance bugs.
 // (2) NoReturnFunctionChecker uses sink nodes to represent paths ending
 // with __noreturn functions such as assert() or exit(). We choose not
 // to report leaks on such paths.
-BT_Leak[*CheckKind]->setSuppressOnSink(true);
+BT_Leak[*CheckKind].reset(new BugType(CheckNames[*CheckKind], "Memory 
leak",
+  categories::MemoryError,
+  

r351508 - [analyzer] [RetainCountChecker] Smart pointer support.

2019-01-17 Thread George Karpenkov via cfe-commits
Author: george.karpenkov
Date: Thu Jan 17 19:12:35 2019
New Revision: 351508

URL: http://llvm.org/viewvc/llvm-project?rev=351508=rev
Log:
[analyzer] [RetainCountChecker] Smart pointer support.

rdar://47323216

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

Added:
cfe/trunk/test/Analysis/os_object_base.h
cfe/trunk/test/Analysis/os_smart_ptr.h
Modified:
cfe/trunk/include/clang/StaticAnalyzer/Core/RetainSummaryManager.h

cfe/trunk/lib/StaticAnalyzer/Checkers/RetainCountChecker/RetainCountChecker.cpp
cfe/trunk/lib/StaticAnalyzer/Core/RetainSummaryManager.cpp
cfe/trunk/test/Analysis/osobject-retain-release.cpp
cfe/trunk/test/Analysis/test-separate-retaincount.cpp

Modified: cfe/trunk/include/clang/StaticAnalyzer/Core/RetainSummaryManager.h
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/StaticAnalyzer/Core/RetainSummaryManager.h?rev=351508=351507=351508=diff
==
--- cfe/trunk/include/clang/StaticAnalyzer/Core/RetainSummaryManager.h 
(original)
+++ cfe/trunk/include/clang/StaticAnalyzer/Core/RetainSummaryManager.h Thu Jan 
17 19:12:35 2019
@@ -685,6 +685,10 @@ public:
   Optional canEval(const CallExpr *CE, const FunctionDecl *FD,
 bool );
 
+  /// \return Whether the type corresponds to a known smart pointer
+  /// implementation (that is, everything about it is inlineable).
+  static bool isKnownSmartPointer(QualType QT);
+
   bool isTrustedReferenceCountImplementation(const FunctionDecl *FD);
 
   const RetainSummary *getSummary(const CallEvent ,

Modified: 
cfe/trunk/lib/StaticAnalyzer/Checkers/RetainCountChecker/RetainCountChecker.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/StaticAnalyzer/Checkers/RetainCountChecker/RetainCountChecker.cpp?rev=351508=351507=351508=diff
==
--- 
cfe/trunk/lib/StaticAnalyzer/Checkers/RetainCountChecker/RetainCountChecker.cpp 
(original)
+++ 
cfe/trunk/lib/StaticAnalyzer/Checkers/RetainCountChecker/RetainCountChecker.cpp 
Thu Jan 17 19:12:35 2019
@@ -529,6 +529,13 @@ void RetainCountChecker::processSummaryO
   C.addTransition(state);
 }
 
+static bool isSmartPtrField(const MemRegion *MR) {
+  const auto *TR = dyn_cast(
+cast(MR)->getSuperRegion());
+  return TR && RetainSummaryManager::isKnownSmartPointer(TR->getValueType());
+}
+
+
 /// A value escapes in these possible cases:
 ///
 /// - binding to something that is not a memory region.
@@ -536,10 +543,15 @@ void RetainCountChecker::processSummaryO
 /// - binding to a variable that has a destructor attached using CleanupAttr
 ///
 /// We do not currently model what happens when a symbol is
-/// assigned to a struct field, so be conservative here and let the symbol go.
+/// assigned to a struct field, unless it is a known smart pointer
+/// implementation, about which we know that it is inlined.
 /// FIXME: This could definitely be improved upon.
 static bool shouldEscapeRegion(const MemRegion *R) {
+  if (isSmartPtrField(R))
+return false;
+
   const auto *VR = dyn_cast(R);
+
   if (!R->hasStackStorage() || !VR)
 return true;
 

Modified: cfe/trunk/lib/StaticAnalyzer/Core/RetainSummaryManager.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/StaticAnalyzer/Core/RetainSummaryManager.cpp?rev=351508=351507=351508=diff
==
--- cfe/trunk/lib/StaticAnalyzer/Core/RetainSummaryManager.cpp (original)
+++ cfe/trunk/lib/StaticAnalyzer/Core/RetainSummaryManager.cpp Thu Jan 17 
19:12:35 2019
@@ -146,7 +146,7 @@ static bool isSubclass(const Decl *D,
 }
 
 static bool isOSObjectSubclass(const Decl *D) {
-  return isSubclass(D, "OSObject");
+  return isSubclass(D, "OSMetaClassBase");
 }
 
 static bool isOSObjectDynamicCast(StringRef S) {
@@ -199,6 +199,20 @@ static bool isOSObjectRelated(const CXXM
   return false;
 }
 
+bool
+RetainSummaryManager::isKnownSmartPointer(QualType QT) {
+  QT = QT.getCanonicalType();
+  const auto *RD = QT->getAsCXXRecordDecl();
+  if (!RD)
+return false;
+  const IdentifierInfo *II = RD->getIdentifier();
+  if (II && II->getName() == "smart_ptr")
+if (const auto *ND = dyn_cast(RD->getDeclContext()))
+  if (ND->getNameAsString() == "os")
+return true;
+  return false;
+}
+
 const RetainSummary *
 RetainSummaryManager::getSummaryForOSObject(const FunctionDecl *FD,
 StringRef FName, QualType RetTy) {

Added: cfe/trunk/test/Analysis/os_object_base.h
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/Analysis/os_object_base.h?rev=351508=auto
==
--- cfe/trunk/test/Analysis/os_object_base.h (added)
+++ cfe/trunk/test/Analysis/os_object_base.h Thu Jan 17 19:12:35 2019
@@ -0,0 +1,54 @@
+#ifndef _OS_BASE_H
+#define _OS_BASE_H
+

[PATCH] D56892: Add a priority field to availability attributes to prioritize explicit attributes from declaration over attributes from '#pragma clang attribute'

2019-01-17 Thread Alex Lorenz via Phabricator via cfe-commits
arphaman updated this revision to Diff 182432.
arphaman added a comment.

Reverse the priority numbering direction as suggested by @dexonsmith .

Now the lower priority is the most important, and the less important priorities 
have a higher numerical value.


Repository:
  rC Clang

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

https://reviews.llvm.org/D56892

Files:
  include/clang/Basic/Attr.td
  include/clang/Sema/ParsedAttr.h
  include/clang/Sema/Sema.h
  lib/Sema/SemaAttr.cpp
  lib/Sema/SemaDecl.cpp
  lib/Sema/SemaDeclAttr.cpp
  test/SemaObjC/attr-availability-priority.m

Index: test/SemaObjC/attr-availability-priority.m
===
--- /dev/null
+++ test/SemaObjC/attr-availability-priority.m
@@ -0,0 +1,53 @@
+// RUN: %clang_cc1 -triple arm64-apple-tvos12.0 -fsyntax-only -verify %s
+
+void explicit() __attribute__((availability(tvos, introduced=11.0, deprecated=12.0))); // expected-note {{marked deprecated here}}
+void inferred() __attribute__((availability(ios, introduced=11.0, deprecated=12.0))); // expected-note {{marked deprecated here}}
+void explicitOverInferred()
+__attribute__((availability(ios, introduced=11.0, deprecated=12.0)))
+__attribute__((availability(tvos, introduced=11.0)));
+void explicitOverInferred2()
+__attribute__((availability(tvos, introduced=11.0)))
+__attribute__((availability(ios, introduced=11.0, deprecated=12.0)));
+
+void simpleUsage() {
+  explicit(); // expected-warning{{'explicit' is deprecated: first deprecated in tvOS 12.0}}
+  inferred(); // expected-warning{{'inferred' is deprecated: first deprecated in tvOS 12.0}}
+  // ok, not deprecated for tvOS.
+  explicitOverInferred();
+  explicitOverInferred2();
+}
+
+#pragma clang attribute push (__attribute__((availability(tvos, introduced=11.0, deprecated=12.0))), apply_to=function)
+
+void explicitFromPragma(); // expected-note {{marked deprecated here}}
+void explicitWinsOverExplicitFromPragma() __attribute__((availability(tvos, introduced=11.0)));
+void implicitLosesOverExplicitFromPragma() __attribute__((availability(ios, introduced=11.0))); // expected-note {{marked deprecated here}}
+
+#pragma clang attribute pop
+
+#pragma clang attribute push (__attribute__((availability(ios, introduced=11.0, deprecated=12.0))), apply_to=function)
+
+void implicitFromPragma(); // expected-note {{marked deprecated here}}
+void explicitWinsOverImplicitFromPragma() __attribute__((availability(tvos, introduced=11.0)));
+void implicitWinsOverImplicitFromPragma() __attribute__((availability(ios, introduced=11.0)));
+
+#pragma clang attribute pop
+
+#pragma clang attribute push (__attribute__((availability(tvos, introduced=11.0, deprecated=12.0))), apply_to=function)
+#pragma clang attribute push (__attribute__((availability(ios, introduced=11.0, deprecated=11.3))), apply_to=function)
+
+void pragmaExplicitWinsOverPragmaImplicit(); // expected-note {{marked deprecated here}}
+
+#pragma clang attribute pop
+#pragma clang attribute pop
+
+void pragmaUsage() {
+  explicitFromPragma(); // expected-warning {{'explicitFromPragma' is deprecated: first deprecated in tvOS 12.0}}
+  explicitWinsOverExplicitFromPragma(); // ok
+  implicitLosesOverExplicitFromPragma(); // expected-warning {{'implicitLosesOverExplicitFromPragma' is deprecated: first deprecated in tvOS 12.0}}
+
+  implicitFromPragma(); // expected-warning {{'implicitFromPragma' is deprecated: first deprecated in tvOS 12.0}}
+  explicitWinsOverImplicitFromPragma(); // ok
+  implicitWinsOverImplicitFromPragma(); // ok
+  pragmaExplicitWinsOverPragmaImplicit(); // expected-warning {{'pragmaExplicitWinsOverPragmaImplicit' is deprecated: first deprecated in tvOS 12.0}}
+}
Index: lib/Sema/SemaDeclAttr.cpp
===
--- lib/Sema/SemaDeclAttr.cpp
+++ lib/Sema/SemaDeclAttr.cpp
@@ -2284,18 +2284,11 @@
   return false;
 }
 
-AvailabilityAttr *Sema::mergeAvailabilityAttr(NamedDecl *D, SourceRange Range,
-  IdentifierInfo *Platform,
-  bool Implicit,
-  VersionTuple Introduced,
-  VersionTuple Deprecated,
-  VersionTuple Obsoleted,
-  bool IsUnavailable,
-  StringRef Message,
-  bool IsStrict,
-  StringRef Replacement,
-  AvailabilityMergeKind AMK,
-  unsigned AttrSpellingListIndex) {
+AvailabilityAttr *Sema::mergeAvailabilityAttr(
+NamedDecl *D, SourceRange Range, IdentifierInfo *Platform, bool Implicit,
+VersionTuple Introduced, VersionTuple Deprecated, VersionTuple 

[PATCH] D56892: Add a priority field to availability attributes to prioritize explicit attributes from declaration over attributes from '#pragma clang attribute'

2019-01-17 Thread Alex Lorenz via Phabricator via cfe-commits
arphaman created this revision.
arphaman added reviewers: erik.pilkington, aaron.ballman.
Herald added subscribers: dexonsmith, jkorous.

We have an issue when using `#pragma clang attribute` with availability 
attributes:

- The explicit attribute that's specified next to the declaration is not 
guaranteed to be preferred over the attribute specified in the pragma.

This patch fixes this by introducing a `priority` field to the availability 
attribute to control how they're merged. Attributes with higher priority are 
applied over attributes with lower priority for the same platform. The 
implicitly inferred attributes are given the lower priority. This ensures that:

1. explicit attributes are preferred over all other attributes.
2. implicitly inferred attributes that are inferred from an explicit attribute 
are discarded if there's an explicit attribute or an attribute specified using 
a `#pragma` for the same platform.
3. implicitly inferred attributes that are inferred from an attribute in the 
`#pragma` are not used if there's an explicit, explicit `#pragma`, or an 
implicit attribute inferred from an explicit attribute for the declaration.

This is the resulting ranking:

`platform availability > platform availability from pragma > inferred 
availability > inferred availability from pragma`

rdar://46390243


Repository:
  rC Clang

https://reviews.llvm.org/D56892

Files:
  include/clang/Basic/Attr.td
  include/clang/Sema/ParsedAttr.h
  include/clang/Sema/Sema.h
  lib/Sema/SemaAttr.cpp
  lib/Sema/SemaDecl.cpp
  lib/Sema/SemaDeclAttr.cpp
  test/SemaObjC/attr-availability-priority.m

Index: test/SemaObjC/attr-availability-priority.m
===
--- /dev/null
+++ test/SemaObjC/attr-availability-priority.m
@@ -0,0 +1,53 @@
+// RUN: %clang_cc1 -triple arm64-apple-tvos12.0 -fsyntax-only -verify %s
+
+void explicit() __attribute__((availability(tvos, introduced=11.0, deprecated=12.0))); // expected-note {{marked deprecated here}}
+void inferred() __attribute__((availability(ios, introduced=11.0, deprecated=12.0))); // expected-note {{marked deprecated here}}
+void explicitOverInferred()
+__attribute__((availability(ios, introduced=11.0, deprecated=12.0)))
+__attribute__((availability(tvos, introduced=11.0)));
+void explicitOverInferred2()
+__attribute__((availability(tvos, introduced=11.0)))
+__attribute__((availability(ios, introduced=11.0, deprecated=12.0)));
+
+void simpleUsage() {
+  explicit(); // expected-warning{{'explicit' is deprecated: first deprecated in tvOS 12.0}}
+  inferred(); // expected-warning{{'inferred' is deprecated: first deprecated in tvOS 12.0}}
+  // ok, not deprecated for tvOS.
+  explicitOverInferred();
+  explicitOverInferred2();
+}
+
+#pragma clang attribute push (__attribute__((availability(tvos, introduced=11.0, deprecated=12.0))), apply_to=function)
+
+void explicitFromPragma(); // expected-note {{marked deprecated here}}
+void explicitWinsOverExplicitFromPragma() __attribute__((availability(tvos, introduced=11.0)));
+void implicitLosesOverExplicitFromPragma() __attribute__((availability(ios, introduced=11.0))); // expected-note {{marked deprecated here}}
+
+#pragma clang attribute pop
+
+#pragma clang attribute push (__attribute__((availability(ios, introduced=11.0, deprecated=12.0))), apply_to=function)
+
+void implicitFromPragma(); // expected-note {{marked deprecated here}}
+void explicitWinsOverImplicitFromPragma() __attribute__((availability(tvos, introduced=11.0)));
+void implicitWinsOverImplicitFromPragma() __attribute__((availability(ios, introduced=11.0)));
+
+#pragma clang attribute pop
+
+#pragma clang attribute push (__attribute__((availability(tvos, introduced=11.0, deprecated=12.0))), apply_to=function)
+#pragma clang attribute push (__attribute__((availability(ios, introduced=11.0, deprecated=11.3))), apply_to=function)
+
+void pragmaExplicitWinsOverPragmaImplicit(); // expected-note {{marked deprecated here}}
+
+#pragma clang attribute pop
+#pragma clang attribute pop
+
+void pragmaUsage() {
+  explicitFromPragma(); // expected-warning {{'explicitFromPragma' is deprecated: first deprecated in tvOS 12.0}}
+  explicitWinsOverExplicitFromPragma(); // ok
+  implicitLosesOverExplicitFromPragma(); // expected-warning {{'implicitLosesOverExplicitFromPragma' is deprecated: first deprecated in tvOS 12.0}}
+
+  implicitFromPragma(); // expected-warning {{'implicitFromPragma' is deprecated: first deprecated in tvOS 12.0}}
+  explicitWinsOverImplicitFromPragma(); // ok
+  implicitWinsOverImplicitFromPragma(); // ok
+  pragmaExplicitWinsOverPragmaImplicit(); // expected-warning {{'pragmaExplicitWinsOverPragmaImplicit' is deprecated: first deprecated in tvOS 12.0}}
+}
Index: lib/Sema/SemaDeclAttr.cpp
===
--- lib/Sema/SemaDeclAttr.cpp
+++ lib/Sema/SemaDeclAttr.cpp
@@ -2284,18 +2284,11 @@
   return false;
 }
 
-AvailabilityAttr 

[PATCH] D55850: [OpenCL] Allow address spaces as method qualifiers

2019-01-17 Thread John McCall via Phabricator via cfe-commits
rjmccall added inline comments.



Comment at: lib/Parse/ParseDecl.cpp:6170
+  }
+}
+  }

Anastasia wrote:
> rjmccall wrote:
> > Does this not need to diagnose redundant qualifiers?  Why is this path 
> > required in addition to the path in SemaType, anyway?
> We discussed earlier to collect addr space qualifiers for completeness: 
> https://reviews.llvm.org/D55850#inline-495037
> 
> Without this change the following doesn't work for addr spaces correctly:
>   auto fGlob() __global -> decltype(this);
> I added a test that check this now in 
> **test/SemaOpenCLCXX/address-space-of-this-class-scope.cl**.
> 
> Here we only collect the quals to be applied to 'this'. If there are multiple 
> address space specified on a method it will be diagnosed in SemaType.cpp. I 
> think we probably don't need to give the same diagnostic twice?
> 
Okay, if this is already diagnosed, it isn't a problem.  Please leave a comment 
to that effect.


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

https://reviews.llvm.org/D55850



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


[PATCH] D56735: [OpenCL] Fix overloading ranking rules to work correctly for address space conversions

2019-01-17 Thread John McCall via Phabricator via cfe-commits
rjmccall accepted this revision.
rjmccall added a comment.
This revision is now accepted and ready to land.

Thanks!


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

https://reviews.llvm.org/D56735



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


r351505 - [analyzer] A speculative fix for buildbot failures in the new SymbolReaperTest.

2019-01-17 Thread Artem Dergachev via cfe-commits
Author: dergachev
Date: Thu Jan 17 17:37:14 2019
New Revision: 351505

URL: http://llvm.org/viewvc/llvm-project?rev=351505=rev
Log:
[analyzer] A speculative fix for buildbot failures in the new SymbolReaperTest.

I expect an xvalue to be easier to convert.

Modified:
cfe/trunk/unittests/StaticAnalyzer/SymbolReaperTest.cpp

Modified: cfe/trunk/unittests/StaticAnalyzer/SymbolReaperTest.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/unittests/StaticAnalyzer/SymbolReaperTest.cpp?rev=351505=351504=351505=diff
==
--- cfe/trunk/unittests/StaticAnalyzer/SymbolReaperTest.cpp (original)
+++ cfe/trunk/unittests/StaticAnalyzer/SymbolReaperTest.cpp Thu Jan 17 17:37:14 
2019
@@ -105,8 +105,7 @@ public:
   SuperRegionLivenessAction() {}
   std::unique_ptr CreateASTConsumer(CompilerInstance ,
  StringRef File) override {
-auto Consumer = llvm::make_unique(Compiler);
-return Consumer;
+return llvm::make_unique(Compiler);
   }
 };
 


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


[PATCH] D54945: This commit adds a chapter about clang-tidy integrations

2019-01-17 Thread Eugene Zelenko via Phabricator via cfe-commits
Eugene.Zelenko added a comment.

I requested merge of updated documentation into 8.0 branch in PR40369.


Repository:
  rL LLVM

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

https://reviews.llvm.org/D54945



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


[PATCH] D56824: [analyzer] MoveChecker: add ".assign" to the list of common reinitializing methods.

2019-01-17 Thread Phabricator via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rC351500: [analyzer] MoveChecker: Add one more common 
resetting method, append. (authored by dergachev, committed by ).

Repository:
  rC Clang

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

https://reviews.llvm.org/D56824

Files:
  lib/StaticAnalyzer/Checkers/MoveChecker.cpp
  test/Analysis/use-after-move.cpp


Index: lib/StaticAnalyzer/Checkers/MoveChecker.cpp
===
--- lib/StaticAnalyzer/Checkers/MoveChecker.cpp
+++ lib/StaticAnalyzer/Checkers/MoveChecker.cpp
@@ -502,9 +502,9 @@
 std::string MethodName = MethodDec->getName().lower();
 // TODO: Some of these methods (eg., resize) are not always resetting
 // the state, so we should consider looking at the arguments.
-if (MethodName == "reset" || MethodName == "clear" ||
-MethodName == "destroy" || MethodName == "resize" ||
-MethodName == "shrink")
+if (MethodName == "assign" || MethodName == "clear" ||
+MethodName == "destroy" || MethodName == "reset" ||
+MethodName == "resize" || MethodName == "shrink")
   return true;
   }
   return false;
Index: test/Analysis/use-after-move.cpp
===
--- test/Analysis/use-after-move.cpp
+++ test/Analysis/use-after-move.cpp
@@ -89,6 +89,7 @@
   void destroy();
   void clear();
   void resize(std::size_t);
+  void assign(const A &);
   bool empty() const;
   bool isEmpty() const;
   operator bool() const;
@@ -531,6 +532,13 @@
 a.foo();   // no-warning
 a.b.foo(); // no-warning
   }
+  {
+A a;
+A b = std::move(a);
+a.assign(A()); // no-warning
+a.foo();   // no-warning
+a.b.foo(); // no-warning
+  }
 }
 
 // Moves or uses that occur as part of template arguments.


Index: lib/StaticAnalyzer/Checkers/MoveChecker.cpp
===
--- lib/StaticAnalyzer/Checkers/MoveChecker.cpp
+++ lib/StaticAnalyzer/Checkers/MoveChecker.cpp
@@ -502,9 +502,9 @@
 std::string MethodName = MethodDec->getName().lower();
 // TODO: Some of these methods (eg., resize) are not always resetting
 // the state, so we should consider looking at the arguments.
-if (MethodName == "reset" || MethodName == "clear" ||
-MethodName == "destroy" || MethodName == "resize" ||
-MethodName == "shrink")
+if (MethodName == "assign" || MethodName == "clear" ||
+MethodName == "destroy" || MethodName == "reset" ||
+MethodName == "resize" || MethodName == "shrink")
   return true;
   }
   return false;
Index: test/Analysis/use-after-move.cpp
===
--- test/Analysis/use-after-move.cpp
+++ test/Analysis/use-after-move.cpp
@@ -89,6 +89,7 @@
   void destroy();
   void clear();
   void resize(std::size_t);
+  void assign(const A &);
   bool empty() const;
   bool isEmpty() const;
   operator bool() const;
@@ -531,6 +532,13 @@
 a.foo();   // no-warning
 a.b.foo(); // no-warning
   }
+  {
+A a;
+A b = std::move(a);
+a.assign(A()); // no-warning
+a.foo();   // no-warning
+a.b.foo(); // no-warning
+  }
 }
 
 // Moves or uses that occur as part of template arguments.
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


r351500 - [analyzer] MoveChecker: Add one more common resetting method, "append".

2019-01-17 Thread Artem Dergachev via cfe-commits
Author: dergachev
Date: Thu Jan 17 16:16:25 2019
New Revision: 351500

URL: http://llvm.org/viewvc/llvm-project?rev=351500=rev
Log:
[analyzer] MoveChecker: Add one more common resetting method, "append".

This is especially crucial for reports related to use-after-move of
standard library objects.

rdar://problem/47338505

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

Modified:
cfe/trunk/lib/StaticAnalyzer/Checkers/MoveChecker.cpp
cfe/trunk/test/Analysis/use-after-move.cpp

Modified: cfe/trunk/lib/StaticAnalyzer/Checkers/MoveChecker.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/StaticAnalyzer/Checkers/MoveChecker.cpp?rev=351500=351499=351500=diff
==
--- cfe/trunk/lib/StaticAnalyzer/Checkers/MoveChecker.cpp (original)
+++ cfe/trunk/lib/StaticAnalyzer/Checkers/MoveChecker.cpp Thu Jan 17 16:16:25 
2019
@@ -502,9 +502,9 @@ bool MoveChecker::isStateResetMethod(con
 std::string MethodName = MethodDec->getName().lower();
 // TODO: Some of these methods (eg., resize) are not always resetting
 // the state, so we should consider looking at the arguments.
-if (MethodName == "reset" || MethodName == "clear" ||
-MethodName == "destroy" || MethodName == "resize" ||
-MethodName == "shrink")
+if (MethodName == "assign" || MethodName == "clear" ||
+MethodName == "destroy" || MethodName == "reset" ||
+MethodName == "resize" || MethodName == "shrink")
   return true;
   }
   return false;

Modified: cfe/trunk/test/Analysis/use-after-move.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/Analysis/use-after-move.cpp?rev=351500=351499=351500=diff
==
--- cfe/trunk/test/Analysis/use-after-move.cpp (original)
+++ cfe/trunk/test/Analysis/use-after-move.cpp Thu Jan 17 16:16:25 2019
@@ -89,6 +89,7 @@ public:
   void destroy();
   void clear();
   void resize(std::size_t);
+  void assign(const A &);
   bool empty() const;
   bool isEmpty() const;
   operator bool() const;
@@ -531,6 +532,13 @@ void moveStateResetFunctionsTest() {
 a.foo();   // no-warning
 a.b.foo(); // no-warning
   }
+  {
+A a;
+A b = std::move(a);
+a.assign(A()); // no-warning
+a.foo();   // no-warning
+a.b.foo(); // no-warning
+  }
 }
 
 // Moves or uses that occur as part of template arguments.


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


r351499 - [analyzer] Make sure base-region and its sub-regions are either all alive or all dead.

2019-01-17 Thread Artem Dergachev via cfe-commits
Author: dergachev
Date: Thu Jan 17 16:08:56 2019
New Revision: 351499

URL: http://llvm.org/viewvc/llvm-project?rev=351499=rev
Log:
[analyzer] Make sure base-region and its sub-regions are either all alive or 
all dead.

SymbolReaper now realizes that our liveness analysis isn't sharp enough
to discriminate between liveness of, say, variables and their fields.
Surprisingly, this didn't quite work before: having a variable live only
through Environment (eg., calling a C++ method on a local variable
as the last action ever performed on that variable) would not keep the
region value symbol of a field of that variable alive.

It would have been broken in the opposite direction as well, but both
Environment and RegionStore use the scanReachableSymbols mechanism for finding
live symbols regions within their values, and due to that they accidentally
end up marking the whole chain of super-regions as live when at least one
sub-region is known to be live.

It is now a direct responsibility of SymbolReaper to maintain this invariant,
and a unit test was added in order to make sure it stays that way.

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

rdar://problem/46914108

Added:
cfe/trunk/test/Analysis/symbol-reaper.cpp
cfe/trunk/unittests/StaticAnalyzer/SymbolReaperTest.cpp
Modified:
cfe/trunk/include/clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h
cfe/trunk/lib/StaticAnalyzer/Core/ExprEngine.cpp
cfe/trunk/lib/StaticAnalyzer/Core/SymbolManager.cpp
cfe/trunk/test/Analysis/diagnostics/dtors.cpp
cfe/trunk/unittests/StaticAnalyzer/CMakeLists.txt

Modified: cfe/trunk/include/clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h?rev=351499=351498=351499=diff
==
--- cfe/trunk/include/clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h 
(original)
+++ cfe/trunk/include/clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h Thu 
Jan 17 16:08:56 2019
@@ -131,6 +131,9 @@ private:
   /// SymMgr - Object that manages the symbol information.
   SymbolManager 
 
+  /// MRMgr - MemRegionManager object that creates memory regions.
+  MemRegionManager 
+
   /// svalBuilder - SValBuilder object that creates SVals from expressions.
   SValBuilder 
 
@@ -180,6 +183,10 @@ public:
 
   AnalysisManager () override { return AMgr; }
 
+  AnalysisDeclContextManager () {
+return AMgr.getAnalysisDeclContextManager();
+  }
+
   CheckerManager () const {
 return *AMgr.getCheckerManager();
   }
@@ -387,9 +394,9 @@ public:
 return StateMgr.getBasicVals();
   }
 
-  // FIXME: Remove when we migrate over to just using ValueManager.
   SymbolManager () { return SymMgr; }
-  const SymbolManager () const { return SymMgr; }
+  MemRegionManager () { return MRMgr; }
+
 
   // Functions for external checking of whether we have unfinished work
   bool wasBlocksExhausted() const { return Engine.wasBlocksExhausted(); }

Modified: cfe/trunk/lib/StaticAnalyzer/Core/ExprEngine.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/StaticAnalyzer/Core/ExprEngine.cpp?rev=351499=351498=351499=diff
==
--- cfe/trunk/lib/StaticAnalyzer/Core/ExprEngine.cpp (original)
+++ cfe/trunk/lib/StaticAnalyzer/Core/ExprEngine.cpp Thu Jan 17 16:08:56 2019
@@ -198,7 +198,9 @@ ExprEngine::ExprEngine(cross_tu::CrossTr
mgr.getConstraintManagerCreator(), G.getAllocator(),
this),
   SymMgr(StateMgr.getSymbolManager()),
-  svalBuilder(StateMgr.getSValBuilder()), ObjCNoRet(mgr.getASTContext()),
+  MRMgr(StateMgr.getRegionManager()),
+  svalBuilder(StateMgr.getSValBuilder()),
+  ObjCNoRet(mgr.getASTContext()),
   BR(mgr, *this),
   VisitedCallees(VisitedCalleesIn), HowToInline(HowToInlineIn) {
   unsigned TrimInterval = mgr.options.GraphTrimInterval;

Modified: cfe/trunk/lib/StaticAnalyzer/Core/SymbolManager.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/StaticAnalyzer/Core/SymbolManager.cpp?rev=351499=351498=351499=diff
==
--- cfe/trunk/lib/StaticAnalyzer/Core/SymbolManager.cpp (original)
+++ cfe/trunk/lib/StaticAnalyzer/Core/SymbolManager.cpp Thu Jan 17 16:08:56 2019
@@ -405,7 +405,7 @@ void SymbolReaper::markLive(SymbolRef sy
 }
 
 void SymbolReaper::markLive(const MemRegion *region) {
-  RegionRoots.insert(region);
+  RegionRoots.insert(region->getBaseRegion());
   markElementIndicesLive(region);
 }
 
@@ -426,11 +426,15 @@ void SymbolReaper::markInUse(SymbolRef s
 }
 
 bool SymbolReaper::isLiveRegion(const MemRegion *MR) {
+  // TODO: For now, liveness of a memory region is equivalent to liveness of 
its
+  // base region. In fact we can do a bit better: say, if a particular 
FieldDecl
+  // is not used later in the path, 

[PATCH] D56632: [analyzer] Track region liveness only through base regions.

2019-01-17 Thread Phabricator via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rC351499: [analyzer] Make sure base-region and its sub-regions 
are either all alive or… (authored by dergachev, committed by ).

Repository:
  rC Clang

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

https://reviews.llvm.org/D56632

Files:
  include/clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h
  lib/StaticAnalyzer/Core/ExprEngine.cpp
  lib/StaticAnalyzer/Core/SymbolManager.cpp
  test/Analysis/diagnostics/dtors.cpp
  test/Analysis/symbol-reaper.cpp
  unittests/StaticAnalyzer/CMakeLists.txt
  unittests/StaticAnalyzer/SymbolReaperTest.cpp

Index: lib/StaticAnalyzer/Core/SymbolManager.cpp
===
--- lib/StaticAnalyzer/Core/SymbolManager.cpp
+++ lib/StaticAnalyzer/Core/SymbolManager.cpp
@@ -405,7 +405,7 @@
 }
 
 void SymbolReaper::markLive(const MemRegion *region) {
-  RegionRoots.insert(region);
+  RegionRoots.insert(region->getBaseRegion());
   markElementIndicesLive(region);
 }
 
@@ -426,11 +426,15 @@
 }
 
 bool SymbolReaper::isLiveRegion(const MemRegion *MR) {
+  // TODO: For now, liveness of a memory region is equivalent to liveness of its
+  // base region. In fact we can do a bit better: say, if a particular FieldDecl
+  // is not used later in the path, we can diagnose a leak of a value within
+  // that field earlier than, say, the variable that contains the field dies.
+  MR = MR->getBaseRegion();
+
   if (RegionRoots.count(MR))
 return true;
 
-  MR = MR->getBaseRegion();
-
   if (const auto *SR = dyn_cast(MR))
 return isLive(SR->getSymbol());
 
Index: lib/StaticAnalyzer/Core/ExprEngine.cpp
===
--- lib/StaticAnalyzer/Core/ExprEngine.cpp
+++ lib/StaticAnalyzer/Core/ExprEngine.cpp
@@ -198,7 +198,9 @@
mgr.getConstraintManagerCreator(), G.getAllocator(),
this),
   SymMgr(StateMgr.getSymbolManager()),
-  svalBuilder(StateMgr.getSValBuilder()), ObjCNoRet(mgr.getASTContext()),
+  MRMgr(StateMgr.getRegionManager()),
+  svalBuilder(StateMgr.getSValBuilder()),
+  ObjCNoRet(mgr.getASTContext()),
   BR(mgr, *this),
   VisitedCallees(VisitedCalleesIn), HowToInline(HowToInlineIn) {
   unsigned TrimInterval = mgr.options.GraphTrimInterval;
Index: unittests/StaticAnalyzer/SymbolReaperTest.cpp
===
--- unittests/StaticAnalyzer/SymbolReaperTest.cpp
+++ unittests/StaticAnalyzer/SymbolReaperTest.cpp
@@ -0,0 +1,121 @@
+//===- unittests/StaticAnalyzer/SymbolReaperTest.cpp --===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===--===//
+
+#include "clang/ASTMatchers/ASTMatchFinder.h"
+#include "clang/Frontend/CompilerInstance.h"
+#include "clang/StaticAnalyzer/Core/BugReporter/BugReporter.h"
+#include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
+#include "clang/CrossTU/CrossTranslationUnit.h"
+#include "clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h"
+#include "clang/StaticAnalyzer/Frontend/AnalysisConsumer.h"
+#include "clang/Tooling/Tooling.h"
+#include "gtest/gtest.h"
+
+namespace clang {
+namespace ento {
+namespace {
+
+using namespace ast_matchers;
+
+// A re-usable consumer that constructs ExprEngine out of CompilerInvocation.
+// TODO: Actually re-use it when we write our second test.
+class ExprEngineConsumer : public ASTConsumer {
+protected:
+  CompilerInstance 
+
+private:
+  // We need to construct all of these in order to construct ExprEngine.
+  CheckerManager ChkMgr;
+  cross_tu::CrossTranslationUnitContext CTU;
+  PathDiagnosticConsumers Consumers;
+  AnalysisManager AMgr;
+  SetOfConstDecls VisitedCallees;
+  FunctionSummariesTy FS;
+
+protected:
+  ExprEngine Eng;
+
+  // Find a declaration in the current AST by name. This has nothing to do
+  // with ExprEngine but turns out to be handy.
+  // TODO: There's probably a better place for it.
+  template 
+  const T *findDeclByName(const Decl *Where, StringRef Name) {
+auto Matcher = decl(hasDescendant(namedDecl(hasName(Name)).bind("d")));
+auto Matches = match(Matcher, *Where, Eng.getContext());
+assert(Matches.size() == 1 && "Ambiguous name!");
+const T *Node = selectFirst("d", Matches);
+assert(Node && "Name not found!");
+return Node;
+  }
+
+public:
+  ExprEngineConsumer(CompilerInstance )
+  : C(C), ChkMgr(C.getASTContext(), *C.getAnalyzerOpts()), CTU(C),
+Consumers(),
+AMgr(C.getASTContext(), C.getDiagnostics(), Consumers,
+ CreateRegionStoreManager, CreateRangeConstraintManager, ,
+ *C.getAnalyzerOpts()),
+VisitedCallees(), FS(),
+Eng(CTU, AMgr, , , 

[PATCH] D56632: [analyzer] Track region liveness only through base regions.

2019-01-17 Thread Artem Dergachev via Phabricator via cfe-commits
NoQ added a comment.

In D56632#1359215 , @NoQ wrote:

> In D56632#1356163 , 
> @baloghadamsoftware wrote:
>
> > Did you measure decrease in the false-positive rate or an increase in the 
> > true-positive rate on real code? I expect some.
>
>
> In progress :)


Moderately surprisingly, i found no changes at all. I guess it's pretty rare 
that the object dies out from Environment last in such manner while its 
original field symbol values are still important. Still worth fixing though - 
might have been worse, you never know... also peace of mind.


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

https://reviews.llvm.org/D56632



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


r351495 - Make integral-o-pointer conversions in SFINAE illegal.

2019-01-17 Thread Erich Keane via cfe-commits
Author: erichkeane
Date: Thu Jan 17 15:11:15 2019
New Revision: 351495

URL: http://llvm.org/viewvc/llvm-project?rev=351495=rev
Log:
Make integral-o-pointer conversions in SFINAE illegal.

As reported in PR40362, allowing the conversion from an integral to a
pointer type (despite being illegal in the C++ standard) will cause
surprsing results when testing for certain behaviors in SFINAE.  This
patch converts the error to a SFINAE Error and adds a test to ensure
that it is still a warning in non-SFINAE but an error in it.

Change-Id: I1f475637fa4d83217ae37dc6b5dbf653e118fae4

Added:
cfe/trunk/test/SemaCXX/int-ptr-cast-SFINAE.cpp   (with props)
Modified:
cfe/trunk/include/clang/Basic/DiagnosticSemaKinds.td

Modified: cfe/trunk/include/clang/Basic/DiagnosticSemaKinds.td
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Basic/DiagnosticSemaKinds.td?rev=351495=351494=351495=diff
==
--- cfe/trunk/include/clang/Basic/DiagnosticSemaKinds.td (original)
+++ cfe/trunk/include/clang/Basic/DiagnosticSemaKinds.td Thu Jan 17 15:11:15 
2019
@@ -6817,7 +6817,7 @@ def ext_typecheck_convert_int_pointer :
   "; take the address with &|"
   "; remove *|"
   "; remove &}3">,
-  InGroup;
+  InGroup, SFINAEFailure;
 def ext_typecheck_convert_pointer_void_func : Extension<
   "%select{%diff{assigning to $ from $|assigning to different types}0,1"
   "|%diff{passing $ to parameter of type $|"

Added: cfe/trunk/test/SemaCXX/int-ptr-cast-SFINAE.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/SemaCXX/int-ptr-cast-SFINAE.cpp?rev=351495=auto
==
--- cfe/trunk/test/SemaCXX/int-ptr-cast-SFINAE.cpp (added)
+++ cfe/trunk/test/SemaCXX/int-ptr-cast-SFINAE.cpp Thu Jan 17 15:11:15 2019
@@ -0,0 +1,22 @@
+// RUN: %clang_cc1 -fsyntax-only -verify %s
+// RUN: %clang_cc1 -fsyntax-only -verify %s -std=c++17
+
+void foo(int* a, int *b) {
+  a -= b; // expected-warning {{incompatible integer to pointer conversion 
assigning to 'int *' from 'long'}}
+}
+
+template T declval();
+struct true_type { static const bool value = true; };
+struct false_type { static const bool value = false; };
+template struct select { using type = T; };
+template struct select { using type = U; 
};
+
+
+template
+typename select<(sizeof(declval() -= declval(), 1) != 1), true_type, 
false_type>::type test(...);
+template false_type test(...);
+
+template
+static const auto has_minus_assign = decltype(test())::value;
+
+static_assert(has_minus_assign, "failed"); // expected-error 
{{static_assert failed due to requirement 'has_minus_assign' "failed"}}

Propchange: cfe/trunk/test/SemaCXX/int-ptr-cast-SFINAE.cpp
--
svn:eol-style = native

Propchange: cfe/trunk/test/SemaCXX/int-ptr-cast-SFINAE.cpp
--
svn:keywords = "Author Date Id Rev URL"

Propchange: cfe/trunk/test/SemaCXX/int-ptr-cast-SFINAE.cpp
--
svn:mime-type = text/plain


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


[PATCH] D56571: [RFC prototype] Implementation of asm-goto support in clang

2019-01-17 Thread Nick Desaulniers via Phabricator via cfe-commits
nickdesaulniers added a comment.

Also of note: glib, a super popular library used across many Linux distro's 
will benefit from the implementation of asm goto (I will send them a patch to 
fix their version detection once we land in Clang): 
https://github.com/GNOME/glib/blob/1ba843b8a0585f20438d5617521f247071c6d94c/glib/gbitlock.c#L181


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

https://reviews.llvm.org/D56571



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


[PATCH] D56879: [Sema] Suppress a warning about a forward-declared fixed enum in C mode

2019-01-17 Thread Erik Pilkington via Phabricator via cfe-commits
erik.pilkington created this revision.
erik.pilkington added reviewers: rsmith, aaron.ballman, arphaman.
Herald added subscribers: dexonsmith, jkorous.

As of r343360, we support fixed-enums in C. This lead to some warnings in 
project headers where a fixed enum is forward declared then later defined. In 
C++, this is fine, the forward declaration is treated as a complete type even 
though the definition isn't present. We use this rule in C too, but still warn 
about the forward declaration anyways. This patch suppresses the warning.

rdar://problem/47356469

Thanks for taking a look!
Erik


Repository:
  rC Clang

https://reviews.llvm.org/D56879

Files:
  clang/lib/Sema/SemaDecl.cpp
  clang/test/Sema/fixed-enum.c


Index: clang/test/Sema/fixed-enum.c
===
--- clang/test/Sema/fixed-enum.c
+++ clang/test/Sema/fixed-enum.c
@@ -10,9 +10,29 @@
 #elif defined(CXX03)
 // expected-warning@-4{{enumeration types with a fixed underlying type are a 
C++11 extension}}
 #elif defined(OBJC)
-// expected-no-diagnostics
+// No diagnostic
 #elif defined(C11)
 // expected-warning@-8{{enumeration types with a fixed underlying type are a 
Clang extension}}
 #elif defined(MS)
 // expected-warning@-10{{enumeration types with a fixed underlying type are a 
Microsoft extension}}
 #endif
+
+// Don't warn about the forward declaration in any language mode.
+enum Fwd : int;
+enum Fwd : int { e2 };
+#ifndef OBJC
+// expected-warning@-3 {{enumeration types with a fixed underlying type}}
+// expected-warning@-3 {{enumeration types with a fixed underlying type}}
+#endif
+
+// Always error on the incompatible redeclaration.
+enum BadFwd : int;
+#ifndef OBJC
+// expected-warning@-2 {{enumeration types with a fixed underlying type}}
+#endif
+// expected-note@-4 {{previous declaration is here}}
+enum BadFwd : char { e3 };
+#ifndef OBJC
+// expected-warning@-2 {{enumeration types with a fixed underlying type}}
+#endif
+// expected-error@-4 {{enumeration redeclared with different underlying type 
'char' (was 'int')}}
Index: clang/lib/Sema/SemaDecl.cpp
===
--- clang/lib/Sema/SemaDecl.cpp
+++ clang/lib/Sema/SemaDecl.cpp
@@ -14743,8 +14743,7 @@
 // If this is an undefined enum, warn.
 if (TUK != TUK_Definition && !Invalid) {
   TagDecl *Def;
-  if (IsFixed && (getLangOpts().CPlusPlus11 || getLangOpts().ObjC) &&
-  cast(New)->isFixed()) {
+  if (IsFixed && cast(New)->isFixed()) {
 // C++0x: 7.2p2: opaque-enum-declaration.
 // Conflicts are diagnosed above. Do nothing.
   }


Index: clang/test/Sema/fixed-enum.c
===
--- clang/test/Sema/fixed-enum.c
+++ clang/test/Sema/fixed-enum.c
@@ -10,9 +10,29 @@
 #elif defined(CXX03)
 // expected-warning@-4{{enumeration types with a fixed underlying type are a C++11 extension}}
 #elif defined(OBJC)
-// expected-no-diagnostics
+// No diagnostic
 #elif defined(C11)
 // expected-warning@-8{{enumeration types with a fixed underlying type are a Clang extension}}
 #elif defined(MS)
 // expected-warning@-10{{enumeration types with a fixed underlying type are a Microsoft extension}}
 #endif
+
+// Don't warn about the forward declaration in any language mode.
+enum Fwd : int;
+enum Fwd : int { e2 };
+#ifndef OBJC
+// expected-warning@-3 {{enumeration types with a fixed underlying type}}
+// expected-warning@-3 {{enumeration types with a fixed underlying type}}
+#endif
+
+// Always error on the incompatible redeclaration.
+enum BadFwd : int;
+#ifndef OBJC
+// expected-warning@-2 {{enumeration types with a fixed underlying type}}
+#endif
+// expected-note@-4 {{previous declaration is here}}
+enum BadFwd : char { e3 };
+#ifndef OBJC
+// expected-warning@-2 {{enumeration types with a fixed underlying type}}
+#endif
+// expected-error@-4 {{enumeration redeclared with different underlying type 'char' (was 'int')}}
Index: clang/lib/Sema/SemaDecl.cpp
===
--- clang/lib/Sema/SemaDecl.cpp
+++ clang/lib/Sema/SemaDecl.cpp
@@ -14743,8 +14743,7 @@
 // If this is an undefined enum, warn.
 if (TUK != TUK_Definition && !Invalid) {
   TagDecl *Def;
-  if (IsFixed && (getLangOpts().CPlusPlus11 || getLangOpts().ObjC) &&
-  cast(New)->isFixed()) {
+  if (IsFixed && cast(New)->isFixed()) {
 // C++0x: 7.2p2: opaque-enum-declaration.
 // Conflicts are diagnosed above. Do nothing.
   }
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D56868: Add -fset-visibility-for-decls for -cc1

2019-01-17 Thread John McCall via Phabricator via cfe-commits
rjmccall added inline comments.



Comment at: include/clang/Driver/CC1Options.td:707
+def fset_visibility_for_decls : Flag<["-"], "fset-visibility-for-decls">,
+  HelpText<"Apply global symbol visibility to declarations without an explicit 
visibility">;
 def ftemplate_depth : Separate<["-"], "ftemplate-depth">,

"Declaration" doesn't unambiguously mean "non-definition" in language parlance;
maybe something like "external declaration" in both help text and the option 
name?
So maybe `-fextern-visibility`?


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

https://reviews.llvm.org/D56868



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


[PATCH] D56836: [mips] Include whole lpthread when using both -pthread and -static

2019-01-17 Thread Simon Atanasyan via Phabricator via cfe-commits
atanasyan added a comment.

In D56836#1361528 , @abeserminji wrote:

> I am not sure if -static option passed as --cflag to lnt runtest enters the 
> LDFLAGS. I guess it doesn't. 
>  But if there is a way to check which options are passed as --cflags, we 
> might be able to add -Wl, -whole-archive -lpthread -Wl -no-whole-archive only 
> in case when static is used.
>  That would be my preferable option in this situation, but I couldn't find 
> any clues on how to do that.


You are right, LDFLAGS does not contain the `-static`. But if you pass linker 
options to the CMake by the `CMAKE_EXE_LINKER_FLAGS` variable, the following 
code should help.

  --- a/SingleSource/UnitTests/C++11/CMakeLists.txt
  +++ b/SingleSource/UnitTests/C++11/CMakeLists.txt
  @@ -1,3 +1,9 @@
   list(APPEND CXXFLAGS -std=c++11 -pthread)
   list(APPEND LDFLAGS -lstdc++ -pthread)
  +
  +file(GLOB Source RELATIVE ${CMAKE_CURRENT_SOURCE_DIR} *.c *.cpp)
  +if(${CMAKE_EXE_LINKER_FLAGS} MATCHES "-static")
  +  list(REMOVE_ITEM Source stdthreadbug.cpp)
  +endif()
  +
   llvm_singlesource()


Repository:
  rC Clang

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

https://reviews.llvm.org/D56836



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


[PATCH] D56878: [mips] Add '-mrelax-pic-calls', '-mno-relax-pic-calls'

2019-01-17 Thread Vladimir Stefanovic via Phabricator via cfe-commits
vstefanovic created this revision.
vstefanovic added a reviewer: atanasyan.
Herald added subscribers: jrtc27, arichardson, sdardis.

These two options enable/disable emission of R_{MICRO}MIPS_JALR fixups along
with PIC calls. The linker may then try to turn PIC calls into direct jumps.
By default, these fixups do get emitted by the backend, use
'-mno-relax-pic-calls' to omit them.


Repository:
  rC Clang

https://reviews.llvm.org/D56878

Files:
  include/clang/Driver/Options.td
  lib/Driver/ToolChains/Clang.cpp
  test/Driver/mips-features.c


Index: test/Driver/mips-features.c
===
--- test/Driver/mips-features.c
+++ test/Driver/mips-features.c
@@ -444,3 +444,15 @@
 // RUN: -mginv -mno-ginv 2>&1 \
 // RUN:   | FileCheck --check-prefix=CHECK-NO-GINV %s
 // CHECK-NO-GINV: "-target-feature" "-ginv"
+//
+// -mrelax-pic-calls
+// RUN: %clang -target mips-unknown-linux-gnu -### -c %s \
+// RUN: -mno-relax-pic-calls -mrelax-pic-calls 2>&1 \
+// RUN:   | FileCheck --check-prefix=CHECK-RELAX-PIC-CALLS %s
+// CHECK-RELAX-PIC-CALLS-NOT: "-mllvm" "-mips-jalr-reloc=0"
+//
+// -mno-relax-pic-calls
+// RUN: %clang -target mips-unknown-linux-gnu -### -c %s \
+// RUN: -mrelax-pic-calls -mno-relax-pic-calls 2>&1 \
+// RUN:   | FileCheck --check-prefix=CHECK-NO-RELAX-PIC-CALLS %s
+// CHECK-NO-RELAX-PIC-CALLS: "-mllvm" "-mips-jalr-reloc=0"
Index: lib/Driver/ToolChains/Clang.cpp
===
--- lib/Driver/ToolChains/Clang.cpp
+++ lib/Driver/ToolChains/Clang.cpp
@@ -1712,6 +1712,14 @@
 } else
   D.Diag(diag::warn_target_unsupported_compact_branches) << CPUName;
   }
+
+  if (Arg *A = Args.getLastArg(options::OPT_mrelax_pic_calls,
+   options::OPT_mno_relax_pic_calls)) {
+if (A->getOption().matches(options::OPT_mno_relax_pic_calls)) {
+  CmdArgs.push_back("-mllvm");
+  CmdArgs.push_back(Args.MakeArgString("-mips-jalr-reloc=0"));
+}
+  }
 }
 
 void Clang::AddPPCTargetArgs(const ArgList ,
Index: include/clang/Driver/Options.td
===
--- include/clang/Driver/Options.td
+++ include/clang/Driver/Options.td
@@ -2402,6 +2402,14 @@
 def mno_odd_spreg : Flag<["-"], "mno-odd-spreg">, Group,
   HelpText<"Disable odd single-precision floating point registers">,
   Flags<[HelpHidden]>;
+def mrelax_pic_calls : Flag<["-"], "mrelax-pic-calls">,
+  Group,
+  HelpText<"Try turning PIC calls (j{al}r{c} $25) into direct calls "
+  "(MIPS only)">, Flags<[HelpHidden]>;
+def mno_relax_pic_calls : Flag<["-"], "mno-relax-pic-calls">,
+  Group,
+  HelpText<"Do not try turning PIC calls (j{al}r{c} $25) into direct calls "
+  "(MIPS only)">, Flags<[HelpHidden]>;
 def mglibc : Flag<["-"], "mglibc">, Group, Flags<[HelpHidden]>;
 def muclibc : Flag<["-"], "muclibc">, Group, Flags<[HelpHidden]>;
 def module_file_info : Flag<["-"], "module-file-info">, 
Flags<[DriverOption,CC1Option]>, Group,


Index: test/Driver/mips-features.c
===
--- test/Driver/mips-features.c
+++ test/Driver/mips-features.c
@@ -444,3 +444,15 @@
 // RUN: -mginv -mno-ginv 2>&1 \
 // RUN:   | FileCheck --check-prefix=CHECK-NO-GINV %s
 // CHECK-NO-GINV: "-target-feature" "-ginv"
+//
+// -mrelax-pic-calls
+// RUN: %clang -target mips-unknown-linux-gnu -### -c %s \
+// RUN: -mno-relax-pic-calls -mrelax-pic-calls 2>&1 \
+// RUN:   | FileCheck --check-prefix=CHECK-RELAX-PIC-CALLS %s
+// CHECK-RELAX-PIC-CALLS-NOT: "-mllvm" "-mips-jalr-reloc=0"
+//
+// -mno-relax-pic-calls
+// RUN: %clang -target mips-unknown-linux-gnu -### -c %s \
+// RUN: -mrelax-pic-calls -mno-relax-pic-calls 2>&1 \
+// RUN:   | FileCheck --check-prefix=CHECK-NO-RELAX-PIC-CALLS %s
+// CHECK-NO-RELAX-PIC-CALLS: "-mllvm" "-mips-jalr-reloc=0"
Index: lib/Driver/ToolChains/Clang.cpp
===
--- lib/Driver/ToolChains/Clang.cpp
+++ lib/Driver/ToolChains/Clang.cpp
@@ -1712,6 +1712,14 @@
 } else
   D.Diag(diag::warn_target_unsupported_compact_branches) << CPUName;
   }
+
+  if (Arg *A = Args.getLastArg(options::OPT_mrelax_pic_calls,
+   options::OPT_mno_relax_pic_calls)) {
+if (A->getOption().matches(options::OPT_mno_relax_pic_calls)) {
+  CmdArgs.push_back("-mllvm");
+  CmdArgs.push_back(Args.MakeArgString("-mips-jalr-reloc=0"));
+}
+  }
 }
 
 void Clang::AddPPCTargetArgs(const ArgList ,
Index: include/clang/Driver/Options.td
===
--- include/clang/Driver/Options.td
+++ include/clang/Driver/Options.td
@@ -2402,6 +2402,14 @@
 def mno_odd_spreg : Flag<["-"], "mno-odd-spreg">, Group,
   HelpText<"Disable odd single-precision floating point registers">,
   Flags<[HelpHidden]>;
+def mrelax_pic_calls : Flag<["-"], "mrelax-pic-calls">,
+  Group,
+  

r351487 - Fix cleanup registration for lambda captures.

2019-01-17 Thread Richard Smith via cfe-commits
Author: rsmith
Date: Thu Jan 17 14:05:50 2019
New Revision: 351487

URL: http://llvm.org/viewvc/llvm-project?rev=351487=rev
Log:
Fix cleanup registration for lambda captures.

Lambda captures should be destroyed if an exception is thrown only if
the construction of the complete lambda-expression has not completed.
(If the lambda-expression has been fully constructed, any exception will
invoke its destructor, which will destroy the captures.)

This is directly modeled after how we handle the equivalent situation in
InitListExprs.

Note that EmitLambdaLValue was unreachable because in C++11 onwards the
frontend never creates the awkward situation where a prvalue expression
(such as a lambda) is used in an lvalue context (such as the left-hand
side of a class member access).

Added:
cfe/trunk/test/CodeGenCXX/cxx1y-init-captures-eh.cpp
Modified:
cfe/trunk/lib/CodeGen/CGExpr.cpp
cfe/trunk/lib/CodeGen/CGExprAgg.cpp
cfe/trunk/lib/CodeGen/CGExprCXX.cpp
cfe/trunk/lib/CodeGen/CodeGenFunction.h

Modified: cfe/trunk/lib/CodeGen/CGExpr.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/CodeGen/CGExpr.cpp?rev=351487=351486=351487=diff
==
--- cfe/trunk/lib/CodeGen/CGExpr.cpp (original)
+++ cfe/trunk/lib/CodeGen/CGExpr.cpp Thu Jan 17 14:05:50 2019
@@ -1287,8 +1287,6 @@ LValue CodeGenFunction::EmitLValue(const
 return EmitCXXBindTemporaryLValue(cast(E));
   case Expr::CXXUuidofExprClass:
 return EmitCXXUuidofLValue(cast(E));
-  case Expr::LambdaExprClass:
-return EmitLambdaLValue(cast(E));
 
   case Expr::ExprWithCleanupsClass: {
 const auto *cleanups = cast(E);
@@ -4548,13 +4546,6 @@ CodeGenFunction::EmitCXXBindTemporaryLVa
   return MakeAddrLValue(Slot.getAddress(), E->getType(), 
AlignmentSource::Decl);
 }
 
-LValue
-CodeGenFunction::EmitLambdaLValue(const LambdaExpr *E) {
-  AggValueSlot Slot = CreateAggTemp(E->getType(), "temp.lvalue");
-  EmitLambdaExpr(E, Slot);
-  return MakeAddrLValue(Slot.getAddress(), E->getType(), 
AlignmentSource::Decl);
-}
-
 LValue CodeGenFunction::EmitObjCMessageExprLValue(const ObjCMessageExpr *E) {
   RValue RV = EmitObjCMessageExpr(E);
 

Modified: cfe/trunk/lib/CodeGen/CGExprAgg.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/CodeGen/CGExprAgg.cpp?rev=351487=351486=351487=diff
==
--- cfe/trunk/lib/CodeGen/CGExprAgg.cpp (original)
+++ cfe/trunk/lib/CodeGen/CGExprAgg.cpp Thu Jan 17 14:05:50 2019
@@ -1264,7 +1264,52 @@ void AggExprEmitter::VisitCXXInheritedCt
 void
 AggExprEmitter::VisitLambdaExpr(LambdaExpr *E) {
   AggValueSlot Slot = EnsureSlot(E->getType());
-  CGF.EmitLambdaExpr(E, Slot);
+  LValue SlotLV = CGF.MakeAddrLValue(Slot.getAddress(), E->getType());
+
+  // We'll need to enter cleanup scopes in case any of the element
+  // initializers throws an exception.
+  SmallVector Cleanups;
+  llvm::Instruction *CleanupDominator = nullptr;
+
+  CXXRecordDecl::field_iterator CurField = E->getLambdaClass()->field_begin();
+  for (LambdaExpr::const_capture_init_iterator i = E->capture_init_begin(),
+   e = E->capture_init_end();
+   i != e; ++i, ++CurField) {
+// Emit initialization
+LValue LV = CGF.EmitLValueForFieldInitialization(SlotLV, *CurField);
+if (CurField->hasCapturedVLAType()) {
+  CGF.EmitLambdaVLACapture(CurField->getCapturedVLAType(), LV);
+  continue;
+}
+
+EmitInitializationToLValue(*i, LV);
+
+// Push a destructor if necessary.
+if (QualType::DestructionKind DtorKind =
+CurField->getType().isDestructedType()) {
+  assert(LV.isSimple());
+  if (CGF.needsEHCleanup(DtorKind)) {
+if (!CleanupDominator)
+  CleanupDominator = CGF.Builder.CreateAlignedLoad(
+  CGF.Int8Ty,
+  llvm::Constant::getNullValue(CGF.Int8PtrTy),
+  CharUnits::One()); // placeholder
+
+CGF.pushDestroy(EHCleanup, LV.getAddress(), CurField->getType(),
+CGF.getDestroyer(DtorKind), false);
+Cleanups.push_back(CGF.EHStack.stable_begin());
+  }
+}
+  }
+
+  // Deactivate all the partial cleanups in reverse order, which
+  // generally means popping them.
+  for (unsigned i = Cleanups.size(); i != 0; --i)
+CGF.DeactivateCleanupBlock(Cleanups[i-1], CleanupDominator);
+
+  // Destroy the placeholder if we made one.
+  if (CleanupDominator)
+CleanupDominator->eraseFromParent();
 }
 
 void AggExprEmitter::VisitExprWithCleanups(ExprWithCleanups *E) {

Modified: cfe/trunk/lib/CodeGen/CGExprCXX.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/CodeGen/CGExprCXX.cpp?rev=351487=351486=351487=diff
==
--- cfe/trunk/lib/CodeGen/CGExprCXX.cpp (original)
+++ cfe/trunk/lib/CodeGen/CGExprCXX.cpp Thu Jan 17 14:05:50 2019
@@ 

[PATCH] D56871: [AMDGPU] Require at least protected visibility for certain symbols

2019-01-17 Thread Scott Linder via Phabricator via cfe-commits
scott.linder updated this revision to Diff 182394.
scott.linder added a comment.

Add missing flag to tests


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

https://reviews.llvm.org/D56871

Files:
  lib/CodeGen/CodeGenModule.cpp
  lib/CodeGen/TargetInfo.cpp
  test/CodeGenOpenCL/visibility.cl

Index: test/CodeGenOpenCL/visibility.cl
===
--- /dev/null
+++ test/CodeGenOpenCL/visibility.cl
@@ -0,0 +1,77 @@
+// RUN: %clang_cc1 -std=cl2.0 -fset-visibility-for-decls -fvisibility default -triple amdgcn-unknown-unknown -S -emit-llvm -o - %s | FileCheck --check-prefix=FVIS-DEFAULT %s
+// RUN: %clang_cc1 -std=cl2.0 -fset-visibility-for-decls -fvisibility protected -triple amdgcn-unknown-unknown -S -emit-llvm -o - %s | FileCheck --check-prefix=FVIS-PROTECTED %s
+// RUN: %clang_cc1 -std=cl2.0 -fset-visibility-for-decls -fvisibility hidden -triple amdgcn-unknown-unknown -S -emit-llvm -o - %s | FileCheck --check-prefix=FVIS-HIDDEN %s
+
+// REQUIRES: amdgpu-registered-target
+
+// FVIS-DEFAULT:  @glob = local_unnamed_addr
+// FVIS-PROTECTED: @glob = protected local_unnamed_addr
+// FVIS-HIDDEN: @glob = hidden local_unnamed_addr
+int glob = 0;
+// FVIS-DEFAULT:  @glob_hidden = hidden local_unnamed_addr
+// FVIS-PROTECTED: @glob_hidden = hidden local_unnamed_addr
+// FVIS-HIDDEN: @glob_hidden = hidden local_unnamed_addr
+__attribute__((visibility("hidden"))) int glob_hidden = 0;
+// FVIS-DEFAULT:  @glob_protected = protected local_unnamed_addr
+// FVIS-PROTECTED: @glob_protected = protected local_unnamed_addr
+// FVIS-HIDDEN: @glob_protected = protected local_unnamed_addr
+__attribute__((visibility("protected"))) int glob_protected = 0;
+// FVIS-DEFAULT:  @glob_default = local_unnamed_addr
+// FVIS-PROTECTED: @glob_default = local_unnamed_addr
+// FVIS-HIDDEN: @glob_default = local_unnamed_addr
+__attribute__((visibility("default"))) int glob_default = 0;
+
+// FVIS-DEFAULT:  @ext = external local_unnamed_addr
+// FVIS-PROTECTED: @ext = external protected local_unnamed_addr
+// FVIS-HIDDEN: @ext = external hidden local_unnamed_addr
+extern int ext;
+// FVIS-DEFAULT:  @ext_hidden = external hidden local_unnamed_addr
+// FVIS-PROTECTED: @ext_hidden = external hidden local_unnamed_addr
+// FVIS-HIDDEN: @ext_hidden = external hidden local_unnamed_addr
+__attribute__((visibility("hidden"))) extern int ext_hidden;
+// FVIS-DEFAULT:  @ext_protected = external protected local_unnamed_addr
+// FVIS-PROTECTED: @ext_protected = external protected local_unnamed_addr
+// FVIS-HIDDEN: @ext_protected = external protected local_unnamed_addr
+__attribute__((visibility("protected"))) extern int ext_protected;
+// FVIS-DEFAULT:  @ext_default = external local_unnamed_addr
+// FVIS-PROTECTED: @ext_default = external local_unnamed_addr
+// FVIS-HIDDEN: @ext_default = external local_unnamed_addr
+__attribute__((visibility("default"))) extern int ext_default;
+
+// FVIS-DEFAULT: define amdgpu_kernel void @kern()
+// FVIS-PROTECTED: define protected amdgpu_kernel void @kern()
+// FVIS-HIDDEN: define protected amdgpu_kernel void @kern()
+kernel void kern() {}
+// FVIS-DEFAULT: define protected amdgpu_kernel void @kern_hidden()
+// FVIS-PROTECTED: define protected amdgpu_kernel void @kern_hidden()
+// FVIS-HIDDEN: define protected amdgpu_kernel void @kern_hidden()
+__attribute__((visibility("hidden"))) kernel void kern_hidden() {}
+// FVIS-DEFAULT: define protected amdgpu_kernel void @kern_protected()
+// FVIS-PROTECTED: define protected amdgpu_kernel void @kern_protected()
+// FVIS-HIDDEN: define protected amdgpu_kernel void @kern_protected()
+__attribute__((visibility("protected"))) kernel void kern_protected() {}
+// FVIS-DEFAULT: define amdgpu_kernel void @kern_default()
+// FVIS-PROTECTED: define amdgpu_kernel void @kern_default()
+// FVIS-HIDDEN: define amdgpu_kernel void @kern_default()
+__attribute__((visibility("default"))) kernel void kern_default() {}
+
+// FVIS-DEFAULT: define void @func()
+// FVIS-PROTECTED: define protected void @func()
+// FVIS-HIDDEN: define hidden void @func()
+void func() {}
+// FVIS-DEFAULT: define hidden void @func_hidden()
+// FVIS-PROTECTED: define hidden void @func_hidden()
+// FVIS-HIDDEN: define hidden void @func_hidden()
+__attribute__((visibility("hidden"))) void func_hidden() {}
+// FVIS-DEFAULT: define protected void @func_protected()
+// FVIS-PROTECTED: define protected void @func_protected()
+// FVIS-HIDDEN: define protected void @func_protected()
+__attribute__((visibility("protected"))) void func_protected() {}
+// FVIS-DEFAULT: define void @func_default()
+// FVIS-PROTECTED: define void @func_default()
+// FVIS-HIDDEN: define void @func_default()
+__attribute__((visibility("default"))) void func_default() {}
+
+void use() {
+glob = ext + ext_hidden + ext_protected + ext_default;
+}
Index: lib/CodeGen/TargetInfo.cpp
===
--- lib/CodeGen/TargetInfo.cpp

[PATCH] D56731: Add -Wctad-maybe-unsupported to diagnose CTAD on types with no user defined deduction guides.

2019-01-17 Thread Eric Fiselier via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rC351484: Add -Wctad-maybe-unsupported to diagnose CTAD on 
types with no user defined… (authored by EricWF, committed by ).

Repository:
  rC Clang

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

https://reviews.llvm.org/D56731

Files:
  include/clang/Basic/DiagnosticGroups.td
  include/clang/Basic/DiagnosticSemaKinds.td
  lib/Sema/SemaInit.cpp
  test/SemaCXX/cxx1z-class-template-argument-deduction.cpp

Index: include/clang/Basic/DiagnosticSemaKinds.td
===
--- include/clang/Basic/DiagnosticSemaKinds.td
+++ include/clang/Basic/DiagnosticSemaKinds.td
@@ -2129,6 +2129,12 @@
   "class template argument deduction is incompatible with C++ standards "
   "before C++17%select{|; for compatibility, use explicit type name %1}0">,
   InGroup, DefaultIgnore;
+def warn_ctad_maybe_unsupported : Warning<
+  "%0 may not intend to support class template argument deduction">,
+  InGroup, DefaultIgnore;
+def note_suppress_ctad_maybe_unsupported : Note<
+  "add a deduction guide to suppress this warning">;
+
 
 // C++14 deduced return types
 def err_auto_fn_deduction_failure : Error<
Index: include/clang/Basic/DiagnosticGroups.td
===
--- include/clang/Basic/DiagnosticGroups.td
+++ include/clang/Basic/DiagnosticGroups.td
@@ -1050,3 +1050,5 @@
 
 // A group for cross translation unit static analysis related warnings.
 def CrossTU : DiagGroup<"ctu">;
+
+def CTADMaybeUnsupported : DiagGroup<"ctad-maybe-unsupported">;
Index: test/SemaCXX/cxx1z-class-template-argument-deduction.cpp
===
--- test/SemaCXX/cxx1z-class-template-argument-deduction.cpp
+++ test/SemaCXX/cxx1z-class-template-argument-deduction.cpp
@@ -409,6 +409,86 @@
 
 }
 
+#pragma clang diagnostic push
+#pragma clang diagnostic warning "-Wctad-maybe-unsupported"
+namespace test_implicit_ctad_warning {
+
+template 
+struct Tag {};
+
+template 
+struct NoExplicit { // expected-note {{add a deduction guide to suppress this warning}}
+  NoExplicit(T) {}
+  NoExplicit(T, int) {}
+};
+
+// expected-warning@+1 {{'NoExplicit' may not intend to support class template argument deduction}}
+NoExplicit ne(42);
+
+template 
+struct HasExplicit {
+  HasExplicit(U) {}
+  HasExplicit(U, int) {}
+};
+template  HasExplicit(U, int) -> HasExplicit>;
+
+HasExplicit he(42);
+
+// Motivating examples from (taken from Stephan Lavavej's 2018 Cppcon talk)
+template 
+struct AmateurPair { // expected-note {{add a deduction guide to suppress this warning}}
+  T first;
+  U second;
+  explicit AmateurPair(const T , const U ) {}
+};
+// expected-warning@+1 {{'AmateurPair' may not intend to support class template argument deduction}}
+AmateurPair p1(42, "hello world"); // deduces to Pair
+
+template 
+struct AmateurPair2 { // expected-note {{add a deduction guide to suppress this warning}}
+  T first;
+  U second;
+  explicit AmateurPair2(T t, U u) {}
+};
+// expected-warning@+1 {{'AmateurPair2' may not intend to support class template argument deduction}}
+AmateurPair2 p2(42, "hello world"); // deduces to Pair2
+
+template 
+struct ProPair {
+  T first; U second;
+explicit ProPair(T const& t, U  const& u)  {}
+};
+template
+ProPair(T1, T2) -> ProPair;
+ProPair p3(42, "hello world"); // deduces to ProPair
+static_assert(__is_same(decltype(p3), ProPair));
+
+// Test that user-defined explicit guides suppress the warning even if they
+// aren't used as candidates.
+template 
+struct TestExplicitCtor {
+  TestExplicitCtor(T) {}
+};
+template 
+explicit TestExplicitCtor(TestExplicitCtor const&) -> TestExplicitCtor;
+TestExplicitCtor ce1{42};
+TestExplicitCtor ce2 = ce1;
+static_assert(__is_same(decltype(ce2), TestExplicitCtor), "");
+
+struct allow_ctad_t {
+  allow_ctad_t() = delete;
+};
+
+template 
+struct TestSuppression {
+  TestSuppression(T) {}
+};
+TestSuppression(allow_ctad_t)->TestSuppression;
+TestSuppression ta("abc");
+static_assert(__is_same(decltype(ta), TestSuppression), "");
+}
+#pragma clang diagnostic pop
+
 #else
 
 // expected-no-diagnostics
Index: lib/Sema/SemaInit.cpp
===
--- lib/Sema/SemaInit.cpp
+++ lib/Sema/SemaInit.cpp
@@ -9264,9 +9264,14 @@
   OverloadCandidateSet Candidates(Kind.getLocation(),
   OverloadCandidateSet::CSK_Normal);
   OverloadCandidateSet::iterator Best;
+
+  bool HasAnyDeductionGuide = false;
+
   auto tryToResolveOverload =
   [&](bool OnlyListConstructors) -> OverloadingResult {
 Candidates.clear(OverloadCandidateSet::CSK_Normal);
+HasAnyDeductionGuide = false;
+
 for (auto I = Guides.begin(), E = Guides.end(); I != E; ++I) {
   NamedDecl *D = (*I)->getUnderlyingDecl();
   if (D->isInvalidDecl())
@@ -9278,6 +9283,9 @@
   if (!GD)
 

r351484 - Add -Wctad-maybe-unsupported to diagnose CTAD on types with no user defined deduction guides.

2019-01-17 Thread Eric Fiselier via cfe-commits
Author: ericwf
Date: Thu Jan 17 13:44:24 2019
New Revision: 351484

URL: http://llvm.org/viewvc/llvm-project?rev=351484=rev
Log:
Add -Wctad-maybe-unsupported to diagnose CTAD on types with no user defined 
deduction guides.

Summary:
Some style guides want to allow using CTAD only on types that "opt-in"; i.e. on 
types that are designed to support it and not just types that *happen* to work 
with it.

This patch implements the `-Wctad-maybe-unsupported` warning, which is off by 
default, which warns when CTAD is used on a type that does not define any 
deduction guides.

The following pattern can be used to suppress the warning in cases where the 
type intentionally doesn't define any deduction guides:

```
struct allow_ctad_t;

template 
struct TestSuppression {
  TestSuppression(T) {}
};
TestSuppression(allow_ctad_t)->TestSuppression; // guides with incomplete 
parameter types are never considered.
```

Reviewers: rsmith, james.dennett, gromer

Reviewed By: rsmith

Subscribers: jdennett, Quuxplusone, lebedev.ri, cfe-commits

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

Modified:
cfe/trunk/include/clang/Basic/DiagnosticGroups.td
cfe/trunk/include/clang/Basic/DiagnosticSemaKinds.td
cfe/trunk/lib/Sema/SemaInit.cpp
cfe/trunk/test/SemaCXX/cxx1z-class-template-argument-deduction.cpp

Modified: cfe/trunk/include/clang/Basic/DiagnosticGroups.td
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Basic/DiagnosticGroups.td?rev=351484=351483=351484=diff
==
--- cfe/trunk/include/clang/Basic/DiagnosticGroups.td (original)
+++ cfe/trunk/include/clang/Basic/DiagnosticGroups.td Thu Jan 17 13:44:24 2019
@@ -1050,3 +1050,5 @@ def NoDeref : DiagGroup<"noderef">;
 
 // A group for cross translation unit static analysis related warnings.
 def CrossTU : DiagGroup<"ctu">;
+
+def CTADMaybeUnsupported : DiagGroup<"ctad-maybe-unsupported">;

Modified: cfe/trunk/include/clang/Basic/DiagnosticSemaKinds.td
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Basic/DiagnosticSemaKinds.td?rev=351484=351483=351484=diff
==
--- cfe/trunk/include/clang/Basic/DiagnosticSemaKinds.td (original)
+++ cfe/trunk/include/clang/Basic/DiagnosticSemaKinds.td Thu Jan 17 13:44:24 
2019
@@ -2129,6 +2129,12 @@ def warn_cxx14_compat_class_template_arg
   "class template argument deduction is incompatible with C++ standards "
   "before C++17%select{|; for compatibility, use explicit type name %1}0">,
   InGroup, DefaultIgnore;
+def warn_ctad_maybe_unsupported : Warning<
+  "%0 may not intend to support class template argument deduction">,
+  InGroup, DefaultIgnore;
+def note_suppress_ctad_maybe_unsupported : Note<
+  "add a deduction guide to suppress this warning">;
+
 
 // C++14 deduced return types
 def err_auto_fn_deduction_failure : Error<

Modified: cfe/trunk/lib/Sema/SemaInit.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Sema/SemaInit.cpp?rev=351484=351483=351484=diff
==
--- cfe/trunk/lib/Sema/SemaInit.cpp (original)
+++ cfe/trunk/lib/Sema/SemaInit.cpp Thu Jan 17 13:44:24 2019
@@ -9264,9 +9264,14 @@ QualType Sema::DeduceTemplateSpecializat
   OverloadCandidateSet Candidates(Kind.getLocation(),
   OverloadCandidateSet::CSK_Normal);
   OverloadCandidateSet::iterator Best;
+
+  bool HasAnyDeductionGuide = false;
+
   auto tryToResolveOverload =
   [&](bool OnlyListConstructors) -> OverloadingResult {
 Candidates.clear(OverloadCandidateSet::CSK_Normal);
+HasAnyDeductionGuide = false;
+
 for (auto I = Guides.begin(), E = Guides.end(); I != E; ++I) {
   NamedDecl *D = (*I)->getUnderlyingDecl();
   if (D->isInvalidDecl())
@@ -9278,6 +9283,9 @@ QualType Sema::DeduceTemplateSpecializat
   if (!GD)
 continue;
 
+  if (!GD->isImplicit())
+HasAnyDeductionGuide = true;
+
   // C++ [over.match.ctor]p1: (non-list copy-initialization from non-class)
   //   For copy-initialization, the candidate functions are all the
   //   converting constructors (12.3.1) of that class.
@@ -9430,5 +9438,15 @@ QualType Sema::DeduceTemplateSpecializat
   Diag(TSInfo->getTypeLoc().getBeginLoc(),
diag::warn_cxx14_compat_class_template_argument_deduction)
   << TSInfo->getTypeLoc().getSourceRange() << 1 << DeducedType;
+
+  // Warn if CTAD was used on a type that does not have any user-defined
+  // deduction guides.
+  if (!HasAnyDeductionGuide) {
+Diag(TSInfo->getTypeLoc().getBeginLoc(),
+ diag::warn_ctad_maybe_unsupported)
+<< TemplateName;
+Diag(Template->getLocation(), diag::note_suppress_ctad_maybe_unsupported);
+  }
+
   return DeducedType;
 }

Modified: cfe/trunk/test/SemaCXX/cxx1z-class-template-argument-deduction.cpp
URL: 

[PATCH] D56868: Add -fset-visibility-for-decls for -cc1

2019-01-17 Thread Scott Linder via Phabricator via cfe-commits
scott.linder updated this revision to Diff 182390.
scott.linder retitled this revision from "Add -f[no-]set-visibility-for-decls" 
to "Add -fset-visibility-for-decls for -cc1".
scott.linder added a comment.

Remove driver options


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

https://reviews.llvm.org/D56868

Files:
  include/clang/Basic/LangOptions.def
  include/clang/Driver/CC1Options.td
  lib/CodeGen/CodeGenModule.cpp
  lib/Driver/ToolChains/AMDGPU.cpp
  lib/Driver/ToolChains/HIP.cpp
  lib/Frontend/CompilerInvocation.cpp
  test/CodeGen/set-visibility-for-decls.c
  test/Driver/amdgpu-visibility.cl
  test/Driver/hip-toolchain-no-rdc.hip
  test/Driver/hip-toolchain-rdc.hip

Index: test/Driver/hip-toolchain-rdc.hip
===
--- test/Driver/hip-toolchain-rdc.hip
+++ test/Driver/hip-toolchain-rdc.hip
@@ -12,10 +12,11 @@
 // RUN:   %S/Inputs/hip_multiple_inputs/b.hip \
 // RUN: 2>&1 | FileCheck %s
 
-// CHECK: [[CLANG:".*clang.*"]] "-cc1" "-triple" "amdgcn-amd-amdhsa" 
+// CHECK: [[CLANG:".*clang.*"]] "-cc1" "-triple" "amdgcn-amd-amdhsa"
 // CHECK-SAME: "-aux-triple" "x86_64-unknown-linux-gnu" "-emit-llvm-bc"
 // CHECK-SAME: {{.*}} "-main-file-name" "a.cu" {{.*}} "-target-cpu" "gfx803"
 // CHECK-SAME: "-fcuda-is-device" "-fgpu-rdc" "-fvisibility" "hidden"
+// CHECK-SAME: "-fset-visibility-for-decls"
 // CHECK-SAME: {{.*}} "-o" [[A_BC:".*bc"]] "-x" "hip"
 // CHECK-SAME: {{.*}} [[A_SRC:".*a.cu"]]
 
@@ -23,6 +24,7 @@
 // CHECK-SAME: "-aux-triple" "x86_64-unknown-linux-gnu" "-emit-llvm-bc"
 // CHECK-SAME: {{.*}} "-main-file-name" "b.hip" {{.*}} "-target-cpu" "gfx803"
 // CHECK-SAME: "-fcuda-is-device" "-fgpu-rdc" "-fvisibility" "hidden"
+// CHECK-SAME: "-fset-visibility-for-decls"
 // CHECK-SAME: {{.*}} "-o" [[B_BC:".*bc"]] "-x" "hip"
 // CHECK-SAME: {{.*}} [[B_SRC:".*b.hip"]]
 
Index: test/Driver/hip-toolchain-no-rdc.hip
===
--- test/Driver/hip-toolchain-no-rdc.hip
+++ test/Driver/hip-toolchain-no-rdc.hip
@@ -20,6 +20,7 @@
 // CHECK-SAME: "-aux-triple" "x86_64-unknown-linux-gnu" "-emit-llvm-bc"
 // CHECK-SAME: {{.*}} "-main-file-name" "a.cu" {{.*}} "-target-cpu" "gfx803"
 // CHECK-SAME: "-fcuda-is-device" "-fvisibility" "hidden"
+// CHECK-SAME: "-fset-visibility-for-decls"
 // CHECK-SAME: {{.*}} "-o" [[A_BC_803:".*bc"]] "-x" "hip"
 // CHECK-SAME: {{.*}} [[A_SRC:".*a.cu"]]
 
@@ -47,6 +48,7 @@
 // CHECK-SAME: "-aux-triple" "x86_64-unknown-linux-gnu" "-emit-llvm-bc"
 // CHECK-SAME: {{.*}} "-main-file-name" "a.cu" {{.*}} "-target-cpu" "gfx900"
 // CHECK-SAME: "-fcuda-is-device" "-fvisibility" "hidden"
+// CHECK-SAME: "-fset-visibility-for-decls"
 // CHECK-SAME: {{.*}} "-o" [[A_BC_900:".*bc"]] "-x" "hip"
 // CHECK-SAME: {{.*}} [[A_SRC]]
 
@@ -89,6 +91,7 @@
 // CHECK-SAME: "-aux-triple" "x86_64-unknown-linux-gnu" "-emit-llvm-bc"
 // CHECK-SAME: {{.*}} "-main-file-name" "b.hip" {{.*}} "-target-cpu" "gfx803"
 // CHECK-SAME: "-fcuda-is-device" "-fvisibility" "hidden"
+// CHECK-SAME: "-fset-visibility-for-decls"
 // CHECK-SAME: {{.*}} "-o" [[B_BC_803:".*bc"]] "-x" "hip"
 // CHECK-SAME: {{.*}} [[B_SRC:".*b.hip"]]
 
@@ -116,6 +119,7 @@
 // CHECK-SAME: "-aux-triple" "x86_64-unknown-linux-gnu" "-emit-llvm-bc"
 // CHECK-SAME: {{.*}} "-main-file-name" "b.hip" {{.*}} "-target-cpu" "gfx900"
 // CHECK-SAME: "-fcuda-is-device" "-fvisibility" "hidden"
+// CHECK-SAME: "-fset-visibility-for-decls"
 // CHECK-SAME: {{.*}} "-o" [[B_BC_900:".*bc"]] "-x" "hip"
 // CHECK-SAME: {{.*}} [[B_SRC]]
 
Index: test/Driver/amdgpu-visibility.cl
===
--- test/Driver/amdgpu-visibility.cl
+++ test/Driver/amdgpu-visibility.cl
@@ -2,6 +2,14 @@
 // RUN: %clang -### -target amdgcn-amd-amdhsa -x cl -c -emit-llvm -fvisibility=protected  %s 2>&1 | FileCheck -check-prefix=OVERRIDE-PROTECTED  %s
 // RUN: %clang -### -target amdgcn-amd-amdhsa -x cl -c -emit-llvm -fvisibility-ms-compat  %s 2>&1 | FileCheck -check-prefix=OVERRIDE-MS  %s
 
-// DEFAULT: "-fvisibility" "hidden"
+// DEFAULT-DAG: "-fvisibility" "hidden"
+// DEFAULT-DAG: "-fset-visibility-for-decls"
+
+// OVERRIDE-PROTECTED-NOT: "-fset-visibility-for-decls"
 // OVERRIDE-PROTECTED: "-fvisibility" "protected"
-// OVERRIDE-MS:  "-fvisibility" "hidden" "-ftype-visibility" "default"
+// OVERRIDE-PROTECTED-NOT: "-fset-visibility-for-decls"
+
+// OVERRIDE-MS-NOT: "-fset-visibility-for-decls"
+// OVERRIDE-MS-DAG: "-fvisibility" "hidden"
+// OVERRIDE-MS-DAG: "-ftype-visibility" "default"
+// OVERRIDE-MS-NOT: "-fset-visibility-for-decls"
Index: test/CodeGen/set-visibility-for-decls.c
===
--- /dev/null
+++ test/CodeGen/set-visibility-for-decls.c
@@ -0,0 +1,42 @@
+// RUN: %clang_cc1 %s -std=c11 -triple=x86_64-pc-linux -fvisibility hidden -fset-visibility-for-decls -emit-llvm -o - | FileCheck --check-prefix=CHECK-HIDDEN %s
+// RUN: %clang_cc1 %s 

[PATCH] D56733: [OPENMP] update release note for implemented OMP 5.0 features

2019-01-17 Thread Gheorghe-Teodor Bercea via Phabricator via cfe-commits
gtbercea added inline comments.



Comment at: docs/OpenMPSupport.rst:62
+  
+- Simplified code generation for distribute and parallel in SPMD mode.
+

Simplified SPMD code generation for `distribute parallel for` when the new 
default schedules are applicable.


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

https://reviews.llvm.org/D56733



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


[PATCH] D56160: [clang-tidy] modernize-use-trailing-return check

2019-01-17 Thread Bernhard Manfred Gruber via Phabricator via cfe-commits
bernhardmgruber added a comment.

Thank you @JonasToth for providing more feedback! I will add a few more tests 
with templates. Maybe I should even try to run the check on Boost and see what 
happens.

In the meantime I might need some help: I tried running the check on LLVM last 
weekend using the run-clang-tidy.py file. The script eventually crashed with a 
segmentation fault (after 1.5 days, running on CentOS 7, 30GiB RAM) with no 
modifications of the source tree. I ran again and exported the fixes, but 
again, python failed to merge the yaml files and crashed (probably because it 
went out of memory). After manual merging, I ran clang-apply-replacements and 
it took a while, but then I also had zero modifications on my LLVM working 
copy. clang-apply-replacements reported a few overlapping refactorings and 
missing files, but that's it. What am I doing wrong?

And btw, is there an easy way to get a compilation database on Windows?

Many thanks!




Comment at: clang-tidy/modernize/UseTrailingReturnCheck.cpp:118
+  if (Info.hasMacroDefinition()) {
+diag(F.getLocation(), Message); // CV qualifiers in macros
+return {};

JonasToth wrote:
> Please improve that comment and here I would prefer a non-trailing comment, 
> too.
> Especially formulate whats with CV and macros, the meaning has to be guessed 
> (and can be guessed wrong).
replaced by "The CV qualifiers of the return type are inside macros"



Comment at: clang-tidy/modernize/UseTrailingReturnCheck.cpp:133
+  bool ExtendedLeft = false;
+  for (size_t i = 0; i < Tokens.size(); i++) {
+// if we found the beginning of the return type, include const and volatile

JonasToth wrote:
> please use uppercase `i` and `j` names for consistency.
i considered this with respect to the style guide, but it just looked far to 
unfamiliar to me. done.



Comment at: clang-tidy/modernize/UseTrailingReturnCheck.cpp:162
+  functionDecl(unless(anyOf(hasTrailingReturn(), returns(voidType()),
+returns(autoType()), cxxConversionDecl(),
+cxxMethodDecl(isImplicit()

JonasToth wrote:
> Shouldn't you include `returns(decltypeType())` as well?
good question! i have a unit test of the form `decltype(auto) f();` and it 
seems to be already excluded by `returns(autoType())`. but i could add your 
suggestion as well to make it more explicit that (for now) we will not rewrite 
functions returning `decltype(auto)`.



Comment at: test/clang-tidy/modernize-use-trailing-return.cpp:269
+auto l1 = [](int arg) {};
+auto l2 = [](int arg) -> double {};

JonasToth wrote:
> These tests are missing the great template fun :)
> 
> Lets start with those two examples:
> 
> ```
> template 
> [[maybe_unused]] typename Container::value_type const volatile&& 
> myFunnyFunction(Container& C) noexcept;
> ```
> 
> and
> 
> ```
> #define MAYBE_UNUSED_MACRO [[maybe_unused]]
> template 
> MAYBE_UNUSED_MACRO typename Container::value_type const volatile** const 
> myFunnyFunction(Container& C) noexcept;
> ```
> 
> Its not necessarily nice code, but I am sure something like this is somewhere 
> in boost for example ;)
You remind me of Jason Turner at CppCon 2018 who said, we should pick a toy 
project, for which we are sure we can handle it, because complexity will 
manifest itself in the details. This is exactly what is happening now.

Thank you for input, I added it to my tests!


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

https://reviews.llvm.org/D56160



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


[PATCH] D53153: [OpenCL] Mark kernel functions with default visibility

2019-01-17 Thread Scott Linder via Phabricator via cfe-commits
scott.linder added a comment.

That sounds reasonable to me. I had already posted a patch with the Driver 
options, but I will update it to only include the -cc1 version.


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

https://reviews.llvm.org/D53153



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


[PATCH] D56160: [clang-tidy] modernize-use-trailing-return check

2019-01-17 Thread Bernhard Manfred Gruber via Phabricator via cfe-commits
bernhardmgruber updated this revision to Diff 182385.
bernhardmgruber marked 19 inline comments as done.
bernhardmgruber added a comment.

Addressed most of the new review comments (mainly uppercasing start of 
comments).


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

https://reviews.llvm.org/D56160

Files:
  clang-tidy/modernize/CMakeLists.txt
  clang-tidy/modernize/ModernizeTidyModule.cpp
  clang-tidy/modernize/UseTrailingReturnCheck.cpp
  clang-tidy/modernize/UseTrailingReturnCheck.h
  docs/ReleaseNotes.rst
  docs/clang-tidy/checks/list.rst
  docs/clang-tidy/checks/modernize-use-trailing-return.rst
  test/clang-tidy/modernize-use-trailing-return.cpp

Index: test/clang-tidy/modernize-use-trailing-return.cpp
===
--- /dev/null
+++ test/clang-tidy/modernize-use-trailing-return.cpp
@@ -0,0 +1,283 @@
+// RUN: %check_clang_tidy %s modernize-use-trailing-return %t -- -- --std=c++14 -fdeclspec
+
+namespace std {
+template 
+class vector;
+
+class string;
+}
+
+//
+// Functions
+//
+
+int f();
+// CHECK-MESSAGES: :[[@LINE-1]]:5: warning: use a trailing return type for this function [modernize-use-trailing-return]
+// CHECK-FIXES: {{^}}auto f() -> int;{{$}}
+int f(int);
+// CHECK-MESSAGES: :[[@LINE-1]]:5: warning: use a trailing return type for this function [modernize-use-trailing-return]
+// CHECK-FIXES: {{^}}auto f(int) -> int;{{$}}
+int f(int arg);
+// CHECK-MESSAGES: :[[@LINE-1]]:5: warning: use a trailing return type for this function [modernize-use-trailing-return]
+// CHECK-FIXES: {{^}}auto f(int arg) -> int;{{$}}
+int f(int arg1, int arg2, int arg3);
+// CHECK-MESSAGES: :[[@LINE-1]]:5: warning: use a trailing return type for this function [modernize-use-trailing-return]
+// CHECK-FIXES: {{^}}auto f(int arg1, int arg2, int arg3) -> int;{{$}}
+int f(int arg1, int arg2, int arg3, ...);
+// CHECK-MESSAGES: :[[@LINE-1]]:5: warning: use a trailing return type for this function [modernize-use-trailing-return]
+// CHECK-FIXES: {{^}}auto f(int arg1, int arg2, int arg3, ...) -> int;{{$}}
+template  int f(T t);
+// CHECK-MESSAGES: :[[@LINE-1]]:27: warning: use a trailing return type for this function [modernize-use-trailing-return]
+// CHECK-FIXES: {{^}}template  auto f(T t) -> int;{{$}}
+
+//
+// Functions with formatting
+//
+
+int a1() { return 42; }
+// CHECK-MESSAGES: :[[@LINE-1]]:5: warning: use a trailing return type for this function [modernize-use-trailing-return]
+// CHECK-FIXES: {{^}}auto a1() -> int { return 42; }{{$}}
+int a2() {
+return 42;
+}
+// CHECK-MESSAGES: :[[@LINE-3]]:5: warning: use a trailing return type for this function [modernize-use-trailing-return]
+// CHECK-FIXES: {{^}}auto a2() -> int {{{$}}
+int a3()
+{
+return 42;
+}
+// CHECK-MESSAGES: :[[@LINE-4]]:5: warning: use a trailing return type for this function [modernize-use-trailing-return]
+// CHECK-FIXES: {{^}}auto a3() -> int{{$}}
+int a4(int   arg   )   ;
+// CHECK-MESSAGES: :[[@LINE-1]]:5: warning: use a trailing return type for this function [modernize-use-trailing-return]
+// CHECK-FIXES: {{^}}auto a4(int   arg   ) -> int   ;{{$}}
+int a5
+// CHECK-MESSAGES: :[[@LINE-1]]:5: warning: use a trailing return type for this function [modernize-use-trailing-return]
+// CHECK-FIXES: {{^}}auto a5{{$}}
+(int arg);
+// CHECK-FIXES: {{^}}(int arg) -> int;{{$}}
+
+//
+// Functions with qualifiers and specifiers
+//
+
+inline int d1(int arg);
+// CHECK-MESSAGES: :[[@LINE-1]]:12: warning: use a trailing return type for this function [modernize-use-trailing-return]
+// CHECK-FIXES: {{^}}inline auto d1(int arg) -> int;{{$}}
+extern "C" int d2(int arg);
+// CHECK-MESSAGES: :[[@LINE-1]]:16: warning: use a trailing return type for this function [modernize-use-trailing-return]
+// CHECK-FIXES: {{^}}extern "C" auto d2(int arg) -> int;{{$}}
+inline int d3(int arg) noexcept(true);
+// CHECK-MESSAGES: :[[@LINE-1]]:12: warning: use a trailing return type for this function [modernize-use-trailing-return]
+// CHECK-FIXES: {{^}}inline auto d3(int arg) -> int noexcept(true);{{$}}
+inline int d4(int arg) try { } catch(...) { }
+// CHECK-MESSAGES: :[[@LINE-1]]:12: warning: use a trailing return type for this function [modernize-use-trailing-return]
+// CHECK-FIXES: {{^}}inline auto d4(int arg) -> int try { } catch(...) { }{{$}}
+
+//
+// Functions in namespaces
+//
+
+namespace N {
+int e1();
+}
+// CHECK-MESSAGES: :[[@LINE-2]]:9: warning: use a trailing return type for this function [modernize-use-trailing-return]
+// CHECK-FIXES: {{^}}auto e1() -> int;{{$}}
+int N::e1() {}
+// CHECK-MESSAGES: :[[@LINE-1]]:8: warning: use a trailing return type for this function [modernize-use-trailing-return]
+// CHECK-FIXES: {{^}}auto N::e1() -> int {}{{$}}
+
+//
+// Functions with complex return types
+//
+
+inline volatile const std::vector e2();
+// CHECK-MESSAGES: :[[@LINE-1]]:48: warning: use a trailing return type for this function 

[PATCH] D53153: [OpenCL] Mark kernel functions with default visibility

2019-01-17 Thread John McCall via Phabricator via cfe-commits
rjmccall added a comment.

I don't want this to be a driver option because I don't want to design a 
general-purpose feature for this right now, nor do I want to gradually accrete 
a general-purpose feature around a random collection of needs accumulated from 
other features.  Let's just leave it as a -cc1 option.  You can very easily 
make the driver recognize when it's performing device compilation and 
automatically pass the -cc1 flag down.


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

https://reviews.llvm.org/D53153



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


[PATCH] D56733: [OPENMP] update release note for implemented OMP 5.0 features

2019-01-17 Thread Gheorghe-Teodor Bercea via Phabricator via cfe-commits
gtbercea added a comment.

In D56733#1362182 , @kkwli0 wrote:

> In D56733#1360221 , @gtbercea wrote:
>
> > Could we add the changes in D56790  to 
> > this diff?
>
>
> Sure, I will do that.


Thanks a lot!


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

https://reviews.llvm.org/D56733



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


[PATCH] D56733: [OPENMP] update release note for implemented OMP 5.0 features

2019-01-17 Thread Kelvin Li via Phabricator via cfe-commits
kkwli0 updated this revision to Diff 182384.
kkwli0 added a reviewer: gtbercea.
kkwli0 added a comment.

Add changes in D56790 .


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

https://reviews.llvm.org/D56733

Files:
  docs/OpenMPSupport.rst
  docs/ReleaseNotes.rst

Index: docs/ReleaseNotes.rst
===
--- docs/ReleaseNotes.rst
+++ docs/ReleaseNotes.rst
@@ -133,7 +133,36 @@
 OpenMP Support in Clang
 --
 
-- ...
+- OpenMP 5.0 features
+
+  - Support relational-op != (not-equal) as one of the canonical forms of random
+access iterator.
+  - Added support for mapping of the lambdas in target regions.
+  - Added parsing/sema analysis for the requires directive.
+  - Support nested declare target directives.
+  - Make the `this` pointer implicitly mapped as `map(this[:1])`.
+  - Added the `close` *map-type-modifier*.
+
+- Various bugfixes and improvements.
+
+New features supported for Cuda devices:
+
+- Added support for the reductions across the teams.
+
+- Extended number of constructs that can be executed in SPMD mode.
+
+- Fixed support for lastprivate/reduction variables in SPMD constructs.
+
+- New collapse clause scheme to avoid expensive remainder operations.
+
+- New default schedule for distribute and parallel constructs.
+
+- Simplified code generation for distribute and parallel in SPMD mode.
+
+- Flag (``-fopenmp_optimistic_collapse``) for user to limit collapsed
+  loop counter width when safe to do so.
+
+- General performance improvement.
 
 CUDA Support in Clang
 -
Index: docs/OpenMPSupport.rst
===
--- docs/OpenMPSupport.rst
+++ docs/OpenMPSupport.rst
@@ -17,60 +17,50 @@
 OpenMP Support
 ==
 
-Clang fully supports OpenMP 4.5. Clang supports offloading to X86_64, AArch64,
-PPC64[LE] and has `basic support for Cuda devices`_.
-
-Standalone directives
-=
-
-* #pragma omp [for] simd: :good:`Complete`.
-
-* #pragma omp declare simd: :partial:`Partial`.  We support parsing/semantic
-  analysis + generation of special attributes for X86 target, but still
-  missing the LLVM pass for vectorization.
-
-* #pragma omp taskloop [simd]: :good:`Complete`.
-
-* #pragma omp target [enter|exit] data: :good:`Complete`.
-
-* #pragma omp target update: :good:`Complete`.
-
-* #pragma omp target: :good:`Complete`.
+Clang supports the following OpenMP 5.0 features
 
-* #pragma omp declare target: :good:`Complete`.
+* The `reduction`-based clauses in the `task` and `target`-based directives.
 
-* #pragma omp teams: :good:`Complete`.
+* Support relational-op != (not-equal) as one of the canonical forms of random
+  access iterator.
 
-* #pragma omp distribute [simd]: :good:`Complete`.
+* Support for mapping of the lambdas in target regions.
 
-* #pragma omp distribute parallel for [simd]: :good:`Complete`.
+* Parsing/sema analysis for the requires directive.
 
-Combined directives
-===
+* Nested declare target directives.
 
-* #pragma omp parallel for simd: :good:`Complete`.
+* Make the `this` pointer implicitly mapped as `map(this[:1])`.
 
-* #pragma omp target parallel: :good:`Complete`.
+* The `close` *map-type-modifier*.
 
-* #pragma omp target parallel for [simd]: :good:`Complete`.
-
-* #pragma omp target simd: :good:`Complete`.
-
-* #pragma omp target teams: :good:`Complete`.
-
-* #pragma omp teams distribute [simd]: :good:`Complete`.
-
-* #pragma omp target teams distribute [simd]: :good:`Complete`.
-
-* #pragma omp teams distribute parallel for [simd]: :good:`Complete`.
-
-* #pragma omp target teams distribute parallel for [simd]: :good:`Complete`.
+Clang fully supports OpenMP 4.5. Clang supports offloading to X86_64, AArch64,
+PPC64[LE] and has `basic support for Cuda devices`_.
 
-Clang does not support any constructs/updates from OpenMP 5.0 except
-for `reduction`-based clauses in the `task` and `target`-based directives.
+* #pragma omp declare simd: :partial:`Partial`.  We support parsing/semantic
+  analysis + generation of special attributes for X86 target, but still
+  missing the LLVM pass for vectorization.
 
 In addition, the LLVM OpenMP runtime `libomp` supports the OpenMP Tools
-Interface (OMPT) on x86, x86_64, AArch64, and PPC64 on Linux, Windows, and mac OS.
+Interface (OMPT) on x86, x86_64, AArch64, and PPC64 on Linux, Windows, and macOS.
+
+General improvements
+
+- New collapse clause scheme to avoid expensive remainder operations.
+  Compute loop index variables after collapsing a loop nest via the
+  collapse clause by replacing the expensive remainder operation with
+  multiplications and additions.
+
+- The default schedules for the `distribute` and `for` constructs in a
+  parallel region and in SPMD mode have changed to ensure coalesced
+  accesses. For the `distribute` construct, a 

[PATCH] D56733: [OPENMP] update release note for implemented OMP 5.0 features

2019-01-17 Thread Kelvin Li via Phabricator via cfe-commits
kkwli0 added a comment.

In D56733#1360221 , @gtbercea wrote:

> Could we add the changes in D56790  to this 
> diff?


Sure, I will do that.


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

https://reviews.llvm.org/D56733



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


Re: r351478 - Fix -Wsign-compare in new tests

2019-01-17 Thread Aaron Ballman via cfe-commits
On Thu, Jan 17, 2019 at 3:56 PM Reid Kleckner via cfe-commits
 wrote:
>
> Author: rnk
> Date: Thu Jan 17 12:52:46 2019
> New Revision: 351478
>
> URL: http://llvm.org/viewvc/llvm-project?rev=351478=rev
> Log:
> Fix -Wsign-compare in new tests

Thank you for the warning fix -- I wasn't seeing the diagnostics with MSVC.

~Aaron

>
> Modified:
> cfe/trunk/unittests/Lex/PPCallbacksTest.cpp
>
> Modified: cfe/trunk/unittests/Lex/PPCallbacksTest.cpp
> URL: 
> http://llvm.org/viewvc/llvm-project/cfe/trunk/unittests/Lex/PPCallbacksTest.cpp?rev=351478=351477=351478=diff
> ==
> --- cfe/trunk/unittests/Lex/PPCallbacksTest.cpp (original)
> +++ cfe/trunk/unittests/Lex/PPCallbacksTest.cpp Thu Jan 17 12:52:46 2019
> @@ -432,25 +432,25 @@ TEST_F(PPCallbacksTest, OpenCLExtensionP
>
>  TEST_F(PPCallbacksTest, DirectiveExprRanges) {
>const auto  = DirectiveExprRange("#if FLUZZY_FLOOF\n#endif\n");
> -  EXPECT_EQ(Results1.size(), 1);
> +  EXPECT_EQ(Results1.size(), 1U);
>EXPECT_EQ(
>GetSourceStringToEnd(CharSourceRange(Results1[0].ConditionRange, 
> false)),
>"FLUZZY_FLOOF");
>
>const auto  = DirectiveExprRange("#if 1 + 4 < 7\n#endif\n");
> -  EXPECT_EQ(Results2.size(), 1);
> +  EXPECT_EQ(Results2.size(), 1U);
>EXPECT_EQ(
>GetSourceStringToEnd(CharSourceRange(Results2[0].ConditionRange, 
> false)),
>"1 + 4 < 7");
>
>const auto  = DirectiveExprRange("#if 1 + \\\n  2\n#endif\n");
> -  EXPECT_EQ(Results3.size(), 1);
> +  EXPECT_EQ(Results3.size(), 1U);
>EXPECT_EQ(
>GetSourceStringToEnd(CharSourceRange(Results3[0].ConditionRange, 
> false)),
>"1 + \\\n  2");
>
>const auto  = DirectiveExprRange("#if 0\n#elif FLOOFY\n#endif\n");
> -  EXPECT_EQ(Results4.size(), 2);
> +  EXPECT_EQ(Results4.size(), 2U);
>EXPECT_EQ(
>GetSourceStringToEnd(CharSourceRange(Results4[0].ConditionRange, 
> false)),
>"0");
> @@ -459,7 +459,7 @@ TEST_F(PPCallbacksTest, DirectiveExprRan
>"FLOOFY");
>
>const auto  = DirectiveExprRange("#if 1\n#elif FLOOFY\n#endif\n");
> -  EXPECT_EQ(Results5.size(), 2);
> +  EXPECT_EQ(Results5.size(), 2U);
>EXPECT_EQ(
>GetSourceStringToEnd(CharSourceRange(Results5[0].ConditionRange, 
> false)),
>"1");
> @@ -469,14 +469,14 @@ TEST_F(PPCallbacksTest, DirectiveExprRan
>
>const auto  =
>DirectiveExprRange("#if defined(FLUZZY_FLOOF)\n#endif\n");
> -  EXPECT_EQ(Results6.size(), 1);
> +  EXPECT_EQ(Results6.size(), 1U);
>EXPECT_EQ(
>GetSourceStringToEnd(CharSourceRange(Results6[0].ConditionRange, 
> false)),
>"defined(FLUZZY_FLOOF)");
>
>const auto  =
>DirectiveExprRange("#if 1\n#elif defined(FLOOFY)\n#endif\n");
> -  EXPECT_EQ(Results7.size(), 2);
> +  EXPECT_EQ(Results7.size(), 2U);
>EXPECT_EQ(
>GetSourceStringToEnd(CharSourceRange(Results7[0].ConditionRange, 
> false)),
>"1");
>
>
> ___
> cfe-commits mailing list
> cfe-commits@lists.llvm.org
> http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


r351478 - Fix -Wsign-compare in new tests

2019-01-17 Thread Reid Kleckner via cfe-commits
Author: rnk
Date: Thu Jan 17 12:52:46 2019
New Revision: 351478

URL: http://llvm.org/viewvc/llvm-project?rev=351478=rev
Log:
Fix -Wsign-compare in new tests

Modified:
cfe/trunk/unittests/Lex/PPCallbacksTest.cpp

Modified: cfe/trunk/unittests/Lex/PPCallbacksTest.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/unittests/Lex/PPCallbacksTest.cpp?rev=351478=351477=351478=diff
==
--- cfe/trunk/unittests/Lex/PPCallbacksTest.cpp (original)
+++ cfe/trunk/unittests/Lex/PPCallbacksTest.cpp Thu Jan 17 12:52:46 2019
@@ -432,25 +432,25 @@ TEST_F(PPCallbacksTest, OpenCLExtensionP
 
 TEST_F(PPCallbacksTest, DirectiveExprRanges) {
   const auto  = DirectiveExprRange("#if FLUZZY_FLOOF\n#endif\n");
-  EXPECT_EQ(Results1.size(), 1);
+  EXPECT_EQ(Results1.size(), 1U);
   EXPECT_EQ(
   GetSourceStringToEnd(CharSourceRange(Results1[0].ConditionRange, false)),
   "FLUZZY_FLOOF");
 
   const auto  = DirectiveExprRange("#if 1 + 4 < 7\n#endif\n");
-  EXPECT_EQ(Results2.size(), 1);
+  EXPECT_EQ(Results2.size(), 1U);
   EXPECT_EQ(
   GetSourceStringToEnd(CharSourceRange(Results2[0].ConditionRange, false)),
   "1 + 4 < 7");
 
   const auto  = DirectiveExprRange("#if 1 + \\\n  2\n#endif\n");
-  EXPECT_EQ(Results3.size(), 1);
+  EXPECT_EQ(Results3.size(), 1U);
   EXPECT_EQ(
   GetSourceStringToEnd(CharSourceRange(Results3[0].ConditionRange, false)),
   "1 + \\\n  2");
 
   const auto  = DirectiveExprRange("#if 0\n#elif FLOOFY\n#endif\n");
-  EXPECT_EQ(Results4.size(), 2);
+  EXPECT_EQ(Results4.size(), 2U);
   EXPECT_EQ(
   GetSourceStringToEnd(CharSourceRange(Results4[0].ConditionRange, false)),
   "0");
@@ -459,7 +459,7 @@ TEST_F(PPCallbacksTest, DirectiveExprRan
   "FLOOFY");
 
   const auto  = DirectiveExprRange("#if 1\n#elif FLOOFY\n#endif\n");
-  EXPECT_EQ(Results5.size(), 2);
+  EXPECT_EQ(Results5.size(), 2U);
   EXPECT_EQ(
   GetSourceStringToEnd(CharSourceRange(Results5[0].ConditionRange, false)),
   "1");
@@ -469,14 +469,14 @@ TEST_F(PPCallbacksTest, DirectiveExprRan
 
   const auto  =
   DirectiveExprRange("#if defined(FLUZZY_FLOOF)\n#endif\n");
-  EXPECT_EQ(Results6.size(), 1);
+  EXPECT_EQ(Results6.size(), 1U);
   EXPECT_EQ(
   GetSourceStringToEnd(CharSourceRange(Results6[0].ConditionRange, false)),
   "defined(FLUZZY_FLOOF)");
 
   const auto  =
   DirectiveExprRange("#if 1\n#elif defined(FLOOFY)\n#endif\n");
-  EXPECT_EQ(Results7.size(), 2);
+  EXPECT_EQ(Results7.size(), 2U);
   EXPECT_EQ(
   GetSourceStringToEnd(CharSourceRange(Results7[0].ConditionRange, false)),
   "1");


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


[PATCH] D49754: Add -m(no-)spe, and e500 CPU definitions and support to clang

2019-01-17 Thread Justin Hibbits via Phabricator via cfe-commits
jhibbits added a comment.

Hi @vit9696, thanks for that, it was a straightforward fix.  I'll post an 
update shortly for D54583 , if arcanist 
cooperates.  The short of it is I need two indices for arguments, since one is 
for logical arguments the other is for physical register allocation.  I was 
only using 1, based on physical register allocation.


Repository:
  rC Clang

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

https://reviews.llvm.org/D49754



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


[PATCH] D56823: [analyzer] Do not try to body-farm bodies for Objective-C properties with custom accessors.

2019-01-17 Thread Artem Dergachev via Phabricator via cfe-commits
NoQ added a comment.

Yeah, i'll be testing this.


Repository:
  rC Clang

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

https://reviews.llvm.org/D56823



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


[PATCH] D56532: [clang-tidy] Add the abseil-duration-conversion-cast check

2019-01-17 Thread Hyrum Wright via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rL351473: [clang-tidy] Add abseil-duration-conversion-cast 
check (authored by hwright, committed by ).
Herald added a subscriber: llvm-commits.

Changed prior to commit:
  https://reviews.llvm.org/D56532?vs=182043=182374#toc

Repository:
  rL LLVM

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

https://reviews.llvm.org/D56532

Files:
  clang-tools-extra/trunk/clang-tidy/abseil/AbseilTidyModule.cpp
  clang-tools-extra/trunk/clang-tidy/abseil/CMakeLists.txt
  clang-tools-extra/trunk/clang-tidy/abseil/DurationConversionCastCheck.cpp
  clang-tools-extra/trunk/clang-tidy/abseil/DurationConversionCastCheck.h
  clang-tools-extra/trunk/docs/ReleaseNotes.rst
  
clang-tools-extra/trunk/docs/clang-tidy/checks/abseil-duration-conversion-cast.rst
  clang-tools-extra/trunk/docs/clang-tidy/checks/list.rst
  clang-tools-extra/trunk/test/clang-tidy/abseil-duration-conversion-cast.cpp

Index: clang-tools-extra/trunk/clang-tidy/abseil/AbseilTidyModule.cpp
===
--- clang-tools-extra/trunk/clang-tidy/abseil/AbseilTidyModule.cpp
+++ clang-tools-extra/trunk/clang-tidy/abseil/AbseilTidyModule.cpp
@@ -11,6 +11,7 @@
 #include "../ClangTidyModule.h"
 #include "../ClangTidyModuleRegistry.h"
 #include "DurationComparisonCheck.h"
+#include "DurationConversionCastCheck.h"
 #include "DurationDivisionCheck.h"
 #include "DurationFactoryFloatCheck.h"
 #include "DurationFactoryScaleCheck.h"
@@ -32,6 +33,8 @@
   void addCheckFactories(ClangTidyCheckFactories ) override {
 CheckFactories.registerCheck(
 "abseil-duration-comparison");
+CheckFactories.registerCheck(
+"abseil-duration-conversion-cast");
 CheckFactories.registerCheck(
 "abseil-duration-division");
 CheckFactories.registerCheck(
Index: clang-tools-extra/trunk/clang-tidy/abseil/CMakeLists.txt
===
--- clang-tools-extra/trunk/clang-tidy/abseil/CMakeLists.txt
+++ clang-tools-extra/trunk/clang-tidy/abseil/CMakeLists.txt
@@ -3,6 +3,7 @@
 add_clang_library(clangTidyAbseilModule
   AbseilTidyModule.cpp
   DurationComparisonCheck.cpp
+  DurationConversionCastCheck.cpp
   DurationDivisionCheck.cpp
   DurationFactoryFloatCheck.cpp
   DurationFactoryScaleCheck.cpp
Index: clang-tools-extra/trunk/clang-tidy/abseil/DurationConversionCastCheck.h
===
--- clang-tools-extra/trunk/clang-tidy/abseil/DurationConversionCastCheck.h
+++ clang-tools-extra/trunk/clang-tidy/abseil/DurationConversionCastCheck.h
@@ -0,0 +1,36 @@
+//===--- DurationConversionCastCheck.h - clang-tidy -*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===--===//
+
+#ifndef LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_ABSEIL_DURATIONCONVERSIONCASTCHECK_H
+#define LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_ABSEIL_DURATIONCONVERSIONCASTCHECK_H
+
+#include "../ClangTidy.h"
+
+namespace clang {
+namespace tidy {
+namespace abseil {
+
+/// Checks for casts of ``absl::Duration`` conversion functions, and recommends
+/// the right conversion function instead.
+///
+/// For the user-facing documentation see:
+/// http://clang.llvm.org/extra/clang-tidy/checks/abseil-duration-conversion-cast.html
+class DurationConversionCastCheck : public ClangTidyCheck {
+public:
+  DurationConversionCastCheck(StringRef Name, ClangTidyContext *Context)
+  : ClangTidyCheck(Name, Context) {}
+  void registerMatchers(ast_matchers::MatchFinder *Finder) override;
+  void check(const ast_matchers::MatchFinder::MatchResult ) override;
+};
+
+} // namespace abseil
+} // namespace tidy
+} // namespace clang
+
+#endif // LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_ABSEIL_DURATIONCONVERSIONCASTCHECK_H
Index: clang-tools-extra/trunk/clang-tidy/abseil/DurationConversionCastCheck.cpp
===
--- clang-tools-extra/trunk/clang-tidy/abseil/DurationConversionCastCheck.cpp
+++ clang-tools-extra/trunk/clang-tidy/abseil/DurationConversionCastCheck.cpp
@@ -0,0 +1,85 @@
+//===--- DurationConversionCastCheck.cpp - clang-tidy -===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===--===//
+
+#include "DurationConversionCastCheck.h"
+#include "DurationRewriter.h"
+#include "clang/AST/ASTContext.h"
+#include "clang/ASTMatchers/ASTMatchFinder.h"
+#include "clang/Tooling/FixIt.h"
+
+using namespace clang::ast_matchers;
+
+namespace clang {
+namespace tidy {

[clang-tools-extra] r351473 - [clang-tidy] Add abseil-duration-conversion-cast check

2019-01-17 Thread Hyrum Wright via cfe-commits
Author: hwright
Date: Thu Jan 17 12:37:35 2019
New Revision: 351473

URL: http://llvm.org/viewvc/llvm-project?rev=351473=rev
Log:
[clang-tidy] Add abseil-duration-conversion-cast check

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

Added:
clang-tools-extra/trunk/clang-tidy/abseil/DurationConversionCastCheck.cpp
clang-tools-extra/trunk/clang-tidy/abseil/DurationConversionCastCheck.h

clang-tools-extra/trunk/docs/clang-tidy/checks/abseil-duration-conversion-cast.rst
clang-tools-extra/trunk/test/clang-tidy/abseil-duration-conversion-cast.cpp
Modified:
clang-tools-extra/trunk/clang-tidy/abseil/AbseilTidyModule.cpp
clang-tools-extra/trunk/clang-tidy/abseil/CMakeLists.txt
clang-tools-extra/trunk/docs/ReleaseNotes.rst
clang-tools-extra/trunk/docs/clang-tidy/checks/list.rst

Modified: clang-tools-extra/trunk/clang-tidy/abseil/AbseilTidyModule.cpp
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clang-tidy/abseil/AbseilTidyModule.cpp?rev=351473=351472=351473=diff
==
--- clang-tools-extra/trunk/clang-tidy/abseil/AbseilTidyModule.cpp (original)
+++ clang-tools-extra/trunk/clang-tidy/abseil/AbseilTidyModule.cpp Thu Jan 17 
12:37:35 2019
@@ -11,6 +11,7 @@
 #include "../ClangTidyModule.h"
 #include "../ClangTidyModuleRegistry.h"
 #include "DurationComparisonCheck.h"
+#include "DurationConversionCastCheck.h"
 #include "DurationDivisionCheck.h"
 #include "DurationFactoryFloatCheck.h"
 #include "DurationFactoryScaleCheck.h"
@@ -32,6 +33,8 @@ public:
   void addCheckFactories(ClangTidyCheckFactories ) override {
 CheckFactories.registerCheck(
 "abseil-duration-comparison");
+CheckFactories.registerCheck(
+"abseil-duration-conversion-cast");
 CheckFactories.registerCheck(
 "abseil-duration-division");
 CheckFactories.registerCheck(

Modified: clang-tools-extra/trunk/clang-tidy/abseil/CMakeLists.txt
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clang-tidy/abseil/CMakeLists.txt?rev=351473=351472=351473=diff
==
--- clang-tools-extra/trunk/clang-tidy/abseil/CMakeLists.txt (original)
+++ clang-tools-extra/trunk/clang-tidy/abseil/CMakeLists.txt Thu Jan 17 
12:37:35 2019
@@ -3,6 +3,7 @@ set(LLVM_LINK_COMPONENTS support)
 add_clang_library(clangTidyAbseilModule
   AbseilTidyModule.cpp
   DurationComparisonCheck.cpp
+  DurationConversionCastCheck.cpp
   DurationDivisionCheck.cpp
   DurationFactoryFloatCheck.cpp
   DurationFactoryScaleCheck.cpp

Added: clang-tools-extra/trunk/clang-tidy/abseil/DurationConversionCastCheck.cpp
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clang-tidy/abseil/DurationConversionCastCheck.cpp?rev=351473=auto
==
--- clang-tools-extra/trunk/clang-tidy/abseil/DurationConversionCastCheck.cpp 
(added)
+++ clang-tools-extra/trunk/clang-tidy/abseil/DurationConversionCastCheck.cpp 
Thu Jan 17 12:37:35 2019
@@ -0,0 +1,85 @@
+//===--- DurationConversionCastCheck.cpp - clang-tidy 
-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===--===//
+
+#include "DurationConversionCastCheck.h"
+#include "DurationRewriter.h"
+#include "clang/AST/ASTContext.h"
+#include "clang/ASTMatchers/ASTMatchFinder.h"
+#include "clang/Tooling/FixIt.h"
+
+using namespace clang::ast_matchers;
+
+namespace clang {
+namespace tidy {
+namespace abseil {
+
+void DurationConversionCastCheck::registerMatchers(MatchFinder *Finder) {
+  auto CallMatcher = ignoringImpCasts(callExpr(
+  callee(functionDecl(DurationConversionFunction()).bind("func_decl")),
+  hasArgument(0, expr().bind("arg";
+
+  Finder->addMatcher(
+  expr(anyOf(
+  
cxxStaticCastExpr(hasSourceExpression(CallMatcher)).bind("cast_expr"),
+  cStyleCastExpr(hasSourceExpression(CallMatcher)).bind("cast_expr"),
+  cxxFunctionalCastExpr(hasSourceExpression(CallMatcher))
+  .bind("cast_expr"))),
+  this);
+}
+
+void DurationConversionCastCheck::check(
+const MatchFinder::MatchResult ) {
+  const auto *MatchedCast =
+  Result.Nodes.getNodeAs("cast_expr");
+
+  if (!isNotInMacro(Result, MatchedCast))
+return;
+
+  const auto *FuncDecl = Result.Nodes.getNodeAs("func_decl");
+  const auto *Arg = Result.Nodes.getNodeAs("arg");
+  StringRef ConversionFuncName = FuncDecl->getName();
+
+  llvm::Optional Scale = getScaleForInverse(ConversionFuncName);
+  if (!Scale)
+return;
+
+  // Casting a double to an integer.
+  if (MatchedCast->getTypeAsWritten()->isIntegerType() &&
+  ConversionFuncName.contains("Double")) {
+llvm::StringRef 

[PATCH] D56823: [analyzer] Do not try to body-farm bodies for Objective-C properties with custom accessors.

2019-01-17 Thread George Karpenkov via Phabricator via cfe-commits
george.karpenkov added a comment.

LG, but it sounds like something which can skew results a lot (?)


Repository:
  rC Clang

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

https://reviews.llvm.org/D56823



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


Re: r351209 - Revert "Correct the source range returned from preprocessor callbacks."

2019-01-17 Thread Aaron Ballman via cfe-commits
On Tue, Jan 15, 2019 at 12:23 PM Benjamin Kramer via cfe-commits
 wrote:
>
> Author: d0k
> Date: Tue Jan 15 09:20:05 2019
> New Revision: 351209
>
> URL: http://llvm.org/viewvc/llvm-project?rev=351209=rev
> Log:
> Revert "Correct the source range returned from preprocessor callbacks."
>
> This reverts commit r350891. Also add a test case that would return an
> empty string with r350891.

Thank you for this! I've fixed and commit in r351470.

~Aaron

>
> Modified:
> cfe/trunk/include/clang/Lex/Preprocessor.h
> cfe/trunk/lib/Lex/PPDirectives.cpp
> cfe/trunk/lib/Lex/PPExpressions.cpp
> cfe/trunk/unittests/Lex/PPCallbacksTest.cpp
>
> Modified: cfe/trunk/include/clang/Lex/Preprocessor.h
> URL: 
> http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Lex/Preprocessor.h?rev=351209=351208=351209=diff
> ==
> --- cfe/trunk/include/clang/Lex/Preprocessor.h (original)
> +++ cfe/trunk/include/clang/Lex/Preprocessor.h Tue Jan 15 09:20:05 2019
> @@ -1816,8 +1816,8 @@ public:
>void CheckEndOfDirective(const char *DirType, bool EnableMacros = false);
>
>/// Read and discard all tokens remaining on the current line until
> -  /// the tok::eod token is found. Returns the range of the skipped tokens.
> -  SourceRange DiscardUntilEndOfDirective();
> +  /// the tok::eod token is found.
> +  void DiscardUntilEndOfDirective();
>
>/// Returns true if the preprocessor has seen a use of
>/// __DATE__ or __TIME__ in the file so far.
> @@ -1982,9 +1982,6 @@ private:
>
>  /// True if the expression contained identifiers that were undefined.
>  bool IncludedUndefinedIds;
> -
> -/// The source range for the expression.
> -SourceRange ExprRange;
>};
>
>/// Evaluate an integer constant expression that may occur after a
>
> Modified: cfe/trunk/lib/Lex/PPDirectives.cpp
> URL: 
> http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Lex/PPDirectives.cpp?rev=351209=351208=351209=diff
> ==
> --- cfe/trunk/lib/Lex/PPDirectives.cpp (original)
> +++ cfe/trunk/lib/Lex/PPDirectives.cpp Tue Jan 15 09:20:05 2019
> @@ -79,18 +79,12 @@ Preprocessor::AllocateVisibilityMacroDir
>
>  /// Read and discard all tokens remaining on the current line until
>  /// the tok::eod token is found.
> -SourceRange Preprocessor::DiscardUntilEndOfDirective() {
> +void Preprocessor::DiscardUntilEndOfDirective() {
>Token Tmp;
> -  SourceRange Res;
> -
> -  LexUnexpandedToken(Tmp);
> -  Res.setBegin(Tmp.getLocation());
> -  while (Tmp.isNot(tok::eod)) {
> -assert(Tmp.isNot(tok::eof) && "EOF seen while discarding directive 
> tokens");
> +  do {
>  LexUnexpandedToken(Tmp);
> -  }
> -  Res.setEnd(Tmp.getLocation());
> -  return Res;
> +assert(Tmp.isNot(tok::eof) && "EOF seen while discarding directive 
> tokens");
> +  } while (Tmp.isNot(tok::eod));
>  }
>
>  /// Enumerates possible cases of #define/#undef a reserved identifier.
> @@ -544,19 +538,19 @@ void Preprocessor::SkipExcludedCondition
>  if (CondInfo.WasSkipping || CondInfo.FoundNonSkip) {
>DiscardUntilEndOfDirective();
>  } else {
> +  const SourceLocation CondBegin = CurPPLexer->getSourceLocation();
>// Restore the value of LexingRawMode so that identifiers are
>// looked up, etc, inside the #elif expression.
>assert(CurPPLexer->LexingRawMode && "We have to be skipping 
> here!");
>CurPPLexer->LexingRawMode = false;
>IdentifierInfo *IfNDefMacro = nullptr;
> -  DirectiveEvalResult DER = EvaluateDirectiveExpression(IfNDefMacro);
> -  const bool CondValue = DER.Conditional;
> +  const bool CondValue = 
> EvaluateDirectiveExpression(IfNDefMacro).Conditional;
>CurPPLexer->LexingRawMode = true;
>if (Callbacks) {
> -Callbacks->Elif(
> -Tok.getLocation(), DER.ExprRange,
> -(CondValue ? PPCallbacks::CVK_True : PPCallbacks::CVK_False),
> -CondInfo.IfLoc);
> +const SourceLocation CondEnd = CurPPLexer->getSourceLocation();
> +Callbacks->Elif(Tok.getLocation(),
> +SourceRange(CondBegin, CondEnd),
> +(CondValue ? PPCallbacks::CVK_True : 
> PPCallbacks::CVK_False), CondInfo.IfLoc);
>}
>// If this condition is true, enter it!
>if (CondValue) {
> @@ -1122,24 +1116,19 @@ void Preprocessor::HandleLineDirective()
>  ; // ok
>else if (StrTok.isNot(tok::string_literal)) {
>  Diag(StrTok, diag::err_pp_line_invalid_filename);
> -DiscardUntilEndOfDirective();
> -return;
> +return DiscardUntilEndOfDirective();
>} else if (StrTok.hasUDSuffix()) {
>  Diag(StrTok, diag::err_invalid_string_udl);
> -DiscardUntilEndOfDirective();
> -return;
> +return 

[clang-tools-extra] r351471 - Revert r351208 (which was a revert of r350892).

2019-01-17 Thread Aaron Ballman via cfe-commits
Author: aaronballman
Date: Thu Jan 17 12:21:44 2019
New Revision: 351471

URL: http://llvm.org/viewvc/llvm-project?rev=351471=rev
Log:
Revert r351208 (which was a revert of r350892).

This corresponds to the fix to Clang in r351470.

Modified:
clang-tools-extra/trunk/test/modularize/ProblemsInconsistent.modularize
clang-tools-extra/trunk/test/pp-trace/pp-trace-conditional.cpp
clang-tools-extra/trunk/test/pp-trace/pp-trace-macro.cpp

Modified: 
clang-tools-extra/trunk/test/modularize/ProblemsInconsistent.modularize
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/test/modularize/ProblemsInconsistent.modularize?rev=351471=351470=351471=diff
==
--- clang-tools-extra/trunk/test/modularize/ProblemsInconsistent.modularize 
(original)
+++ clang-tools-extra/trunk/test/modularize/ProblemsInconsistent.modularize Thu 
Jan 17 12:21:44 2019
@@ -60,16 +60,6 @@ Inputs/InconsistentHeader2.h
 # CHECK-NEXT: {{.*}}{{[/\\]}}Inputs{{[/\\]}}InconsistentHeader2.h
 # CHECK-NEXT:   {{.*}}{{[/\\]}}Inputs{{[/\\]}}InconsistentSubHeader.h
 # CHECK-NEXT: (no macro definition)
-# CHECK-NEXT: {{.*}}{{[/\\]}}Inputs{{[/\\]}}InconsistentSubHeader.h:11:2
-# CHECK-NEXT: #if SYMBOL == 1
-# CHECK-NEXT: ^
-# CHECK-NEXT: error: Conditional expression instance 'SYMBOL == 1' has 
different values in this header, depending on how it was included.
-# CHECK-NEXT:   'SYMBOL == 1' expanded to: 'true' with respect to these 
inclusion paths:
-# CHECK-NEXT: {{.*}}{{[/\\]}}Inputs{{[/\\]}}InconsistentHeader1.h
-# CHECK-NEXT:   {{.*}}{{[/\\]}}Inputs{{[/\\]}}InconsistentSubHeader.h
-# CHECK-NEXT:   'SYMBOL == 1' expanded to: 'false' with respect to these 
inclusion paths:
-# CHECK-NEXT: {{.*}}{{[/\\]}}Inputs{{[/\\]}}InconsistentHeader2.h
-# CHECK-NEXT:   {{.*}}{{[/\\]}}Inputs{{[/\\]}}InconsistentSubHeader.h
 # CHECK-NEXT: {{.*}}{{[/\\]}}Inputs{{[/\\]}}InconsistentSubHeader.h:2:2
 # CHECK-NEXT: #ifdef SYMBOL1
 # CHECK-NEXT: ^

Modified: clang-tools-extra/trunk/test/pp-trace/pp-trace-conditional.cpp
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/test/pp-trace/pp-trace-conditional.cpp?rev=351471=351470=351471=diff
==
--- clang-tools-extra/trunk/test/pp-trace/pp-trace-conditional.cpp (original)
+++ clang-tools-extra/trunk/test/pp-trace/pp-trace-conditional.cpp Thu Jan 17 
12:21:44 2019
@@ -79,14 +79,14 @@
 // CHECK-NEXT:   MacroDirective: MD_Define
 // CHECK:  - Callback: If
 // CHECK-NEXT:   Loc: "{{.*}}{{[/\\]}}pp-trace-conditional.cpp:3:2"
-// CHECK-NEXT:   ConditionRange: 
["{{.*}}{{[/\\]}}pp-trace-conditional.cpp:3:4", 
"{{.*}}{{[/\\]}}pp-trace-conditional.cpp:4:1"]
+// CHECK-NEXT:   ConditionRange: 
["{{.*}}{{[/\\]}}pp-trace-conditional.cpp:3:5", 
"{{.*}}{{[/\\]}}pp-trace-conditional.cpp:3:5"]
 // CHECK-NEXT:   ConditionValue: CVK_True
 // CHECK-NEXT: - Callback: Endif
 // CHECK-NEXT:   Loc: "{{.*}}{{[/\\]}}pp-trace-conditional.cpp:4:2"
 // CHECK-NEXT:   IfLoc: "{{.*}}{{[/\\]}}pp-trace-conditional.cpp:3:2"
 // CHECK-NEXT: - Callback: If
 // CHECK-NEXT:   Loc: "{{.*}}{{[/\\]}}pp-trace-conditional.cpp:6:2"
-// CHECK-NEXT:   ConditionRange: 
["{{.*}}{{[/\\]}}pp-trace-conditional.cpp:6:4", 
"{{.*}}{{[/\\]}}pp-trace-conditional.cpp:7:1"]
+// CHECK-NEXT:   ConditionRange: 
["{{.*}}{{[/\\]}}pp-trace-conditional.cpp:6:5", 
"{{.*}}{{[/\\]}}pp-trace-conditional.cpp:6:5"]
 // CHECK-NEXT:   ConditionValue: CVK_False
 // CHECK-NEXT: - Callback: Endif
 // CHECK-NEXT:   Loc: "{{.*}}{{[/\\]}}pp-trace-conditional.cpp:7:2"
@@ -95,7 +95,7 @@
 // CHECK-NEXT:   Range: ["{{.*}}{{[/\\]}}pp-trace-conditional.cpp:6:1", 
"{{.*}}{{[/\\]}}pp-trace-conditional.cpp:7:2"]
 // CHECK-NEXT: - Callback: If
 // CHECK-NEXT:   Loc: "{{.*}}{{[/\\]}}pp-trace-conditional.cpp:9:2"
-// CHECK-NEXT:   ConditionRange: 
["{{.*}}{{[/\\]}}pp-trace-conditional.cpp:9:4", 
"{{.*}}{{[/\\]}}pp-trace-conditional.cpp:10:1"]
+// CHECK-NEXT:   ConditionRange: 
["{{.*}}{{[/\\]}}pp-trace-conditional.cpp:9:5", 
"{{.*}}{{[/\\]}}pp-trace-conditional.cpp:9:5"]
 // CHECK-NEXT:   ConditionValue: CVK_True
 // CHECK-NEXT: - Callback: Else
 // CHECK-NEXT:   Loc: "{{.*}}{{[/\\]}}pp-trace-conditional.cpp:10:2"
@@ -107,7 +107,7 @@
 // CHECK-NEXT:   Range: ["{{.*}}{{[/\\]}}pp-trace-conditional.cpp:10:1", 
"{{.*}}{{[/\\]}}pp-trace-conditional.cpp:11:2"]
 // CHECK-NEXT: - Callback: If
 // CHECK-NEXT:   Loc: "{{.*}}{{[/\\]}}pp-trace-conditional.cpp:13:2"
-// CHECK-NEXT:   ConditionRange: 
["{{.*}}{{[/\\]}}pp-trace-conditional.cpp:13:4", 
"{{.*}}{{[/\\]}}pp-trace-conditional.cpp:14:1"]
+// CHECK-NEXT:   ConditionRange: 
["{{.*}}{{[/\\]}}pp-trace-conditional.cpp:13:5", 
"{{.*}}{{[/\\]}}pp-trace-conditional.cpp:13:5"]
 // CHECK-NEXT:   ConditionValue: CVK_False
 // CHECK-NEXT: - Callback: Else
 // CHECK-NEXT:   Loc: "{{.*}}{{[/\\]}}pp-trace-conditional.cpp:14:2"
@@ -119,11 +119,11 @@
 // CHECK-NEXT:   IfLoc: 

r351470 - Revert r351209 (which was a revert of r350891) with a fix.

2019-01-17 Thread Aaron Ballman via cfe-commits
Author: aaronballman
Date: Thu Jan 17 12:21:34 2019
New Revision: 351470

URL: http://llvm.org/viewvc/llvm-project?rev=351470=rev
Log:
Revert r351209 (which was a revert of r350891) with a fix.

The test case had a parse error that was causing the condition string to be 
misreported. We now have better fallback code for error cases.

Modified:
cfe/trunk/include/clang/Lex/Preprocessor.h
cfe/trunk/lib/Lex/PPDirectives.cpp
cfe/trunk/lib/Lex/PPExpressions.cpp
cfe/trunk/unittests/Lex/PPCallbacksTest.cpp

Modified: cfe/trunk/include/clang/Lex/Preprocessor.h
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Lex/Preprocessor.h?rev=351470=351469=351470=diff
==
--- cfe/trunk/include/clang/Lex/Preprocessor.h (original)
+++ cfe/trunk/include/clang/Lex/Preprocessor.h Thu Jan 17 12:21:34 2019
@@ -1816,8 +1816,8 @@ public:
   void CheckEndOfDirective(const char *DirType, bool EnableMacros = false);
 
   /// Read and discard all tokens remaining on the current line until
-  /// the tok::eod token is found.
-  void DiscardUntilEndOfDirective();
+  /// the tok::eod token is found. Returns the range of the skipped tokens.
+  SourceRange DiscardUntilEndOfDirective();
 
   /// Returns true if the preprocessor has seen a use of
   /// __DATE__ or __TIME__ in the file so far.
@@ -1982,6 +1982,9 @@ private:
 
 /// True if the expression contained identifiers that were undefined.
 bool IncludedUndefinedIds;
+
+/// The source range for the expression.
+SourceRange ExprRange;
   };
 
   /// Evaluate an integer constant expression that may occur after a

Modified: cfe/trunk/lib/Lex/PPDirectives.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Lex/PPDirectives.cpp?rev=351470=351469=351470=diff
==
--- cfe/trunk/lib/Lex/PPDirectives.cpp (original)
+++ cfe/trunk/lib/Lex/PPDirectives.cpp Thu Jan 17 12:21:34 2019
@@ -76,18 +76,24 @@ Preprocessor::AllocateVisibilityMacroDir
bool isPublic) {
   return new (BP) VisibilityMacroDirective(Loc, isPublic);
 }
-
-/// Read and discard all tokens remaining on the current line until
-/// the tok::eod token is found.
-void Preprocessor::DiscardUntilEndOfDirective() {
-  Token Tmp;
-  do {
-LexUnexpandedToken(Tmp);
-assert(Tmp.isNot(tok::eof) && "EOF seen while discarding directive 
tokens");
-  } while (Tmp.isNot(tok::eod));
-}
-
-/// Enumerates possible cases of #define/#undef a reserved identifier.
+
+/// Read and discard all tokens remaining on the current line until
+/// the tok::eod token is found.
+SourceRange Preprocessor::DiscardUntilEndOfDirective() {
+  Token Tmp;
+  SourceRange Res;
+
+  LexUnexpandedToken(Tmp);
+  Res.setBegin(Tmp.getLocation());
+  while (Tmp.isNot(tok::eod)) {
+assert(Tmp.isNot(tok::eof) && "EOF seen while discarding directive 
tokens");
+LexUnexpandedToken(Tmp);
+  }
+  Res.setEnd(Tmp.getLocation());
+  return Res;
+}
+
+/// Enumerates possible cases of #define/#undef a reserved identifier.
 enum MacroDiag {
   MD_NoWarn,//> Not a reserved identifier
   MD_KeywordDef,//> Macro hides keyword, enabled by default
@@ -535,25 +541,25 @@ void Preprocessor::SkipExcludedCondition
 
 // If this is in a skipping block or if we're already handled this #if
 // block, don't bother parsing the condition.
-if (CondInfo.WasSkipping || CondInfo.FoundNonSkip) {
-  DiscardUntilEndOfDirective();
-} else {
-  const SourceLocation CondBegin = CurPPLexer->getSourceLocation();
-  // Restore the value of LexingRawMode so that identifiers are
-  // looked up, etc, inside the #elif expression.
-  assert(CurPPLexer->LexingRawMode && "We have to be skipping here!");
-  CurPPLexer->LexingRawMode = false;
-  IdentifierInfo *IfNDefMacro = nullptr;
-  const bool CondValue = 
EvaluateDirectiveExpression(IfNDefMacro).Conditional;
-  CurPPLexer->LexingRawMode = true;
-  if (Callbacks) {
-const SourceLocation CondEnd = CurPPLexer->getSourceLocation();
-Callbacks->Elif(Tok.getLocation(),
-SourceRange(CondBegin, CondEnd),
-(CondValue ? PPCallbacks::CVK_True : 
PPCallbacks::CVK_False), CondInfo.IfLoc);
-  }
-  // If this condition is true, enter it!
-  if (CondValue) {
+if (CondInfo.WasSkipping || CondInfo.FoundNonSkip) {
+  DiscardUntilEndOfDirective();
+} else {
+  // Restore the value of LexingRawMode so that identifiers are
+  // looked up, etc, inside the #elif expression.
+  assert(CurPPLexer->LexingRawMode && "We have to be skipping here!");
+  CurPPLexer->LexingRawMode = false;
+  IdentifierInfo *IfNDefMacro = nullptr;
+  

[PATCH] D54945: This commit adds a chapter about clang-tidy integrations

2019-01-17 Thread Eugene Zelenko via Phabricator via cfe-commits
Eugene.Zelenko added a comment.

I fixed links.


Repository:
  rL LLVM

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

https://reviews.llvm.org/D54945



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


[PATCH] D54945: This commit adds a chapter about clang-tidy integrations

2019-01-17 Thread Eugene Zelenko via Phabricator via cfe-commits
Eugene.Zelenko added a comment.

By the word, I noticed that HTTP was used and replaced it with HTTPS in 
Contributing.rst. Will be good idea to do the same in other documentation.


Repository:
  rL LLVM

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

https://reviews.llvm.org/D54945



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


Re: [PATCH] D35068: [analyzer] Detect usages of unsafe I/O functions

2019-01-17 Thread Roman Lebedev via cfe-commits
Please also note that "safe" functions are C11 Annex K, and it is Optional.
I believe glibc does not implement it, and has no intention of implementing it.
By memory, i'm not sure any library other than Microsoft's does provide it.

On Thu, Jan 17, 2019 at 9:17 PM Kristóf Umann via Phabricator
 wrote:
>
> Szelethus requested changes to this revision.
> Szelethus added a comment.
> This revision now requires changes to proceed.
>
> In D35068#811436 , @NoQ wrote:
>
> > I wonder how noisy this check is - did you test it on large codebases? 
> > Because these functions are popular, and in many cases it'd be fine to use 
> > insecure functions, i wonder if it's worth it to have this check on by 
> > default. Like, if it's relatively quiet - it's fine, but if it'd constitute 
> > 90% of the analyzer's warnings on popular projects, that'd probably not be 
> > fine.
>
>
>
>
> In D35068#1049530 , 
> @george.karpenkov wrote:
>
> > @koldaniel Have you evaluated this checker? On which codebases? Were the 
> > warnings real security issues, or were they mostly spurious? The code seems 
> > fine, but I'm not sure whether it should be in `security` or in `alpha`.
>
>
> Sorry, didn't read the discussion, there are some fair points in the quoted 
> comments.
>
> In D35068#1069880 , @koldaniel wrote:
>
> > I've evaluated this checker on LLVM+Clang, there were only a few (about 15) 
> > warnings,  because of the C11 flag check at the beginning of the checker 
> > body. However, if this check was removed, number of the warnings would be 
> > increased significantly. I wouldn't say the findings were real security 
> > issues, most of the warnings were about usages of deprecated functions, 
> > which has not been considered unsecure (but which may cause problems if the 
> > code is modified in an improper way in the future).
>
>
> My problem is that LLVM+Clang isn't really a C (neither a C11) project, and I 
> think judging this checker on it is a little misleading. Could you please 
> test it on some C11 projects? I think tmux uses C11.
>
> In D35068#1361195 , @xazax.hun wrote:
>
> > I think this is quiet coding guideline specific check which is useful for a 
> > set of  security critical projects. As this is an opt in kind of check, I 
> > think it does no harm to have it upstream.
>
>
> I do generally agree with this statement, but I'd be more comfortable either 
> landing it in alpha or seeing some other results.
>
>
> CHANGES SINCE LAST ACTION
>   https://reviews.llvm.org/D35068/new/
>
> https://reviews.llvm.org/D35068
>
>
>
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang-tools-extra] r351468 - [Documentation] Fix another link in docs/clang-tidy/Contributing.rst.

2019-01-17 Thread Eugene Zelenko via cfe-commits
Author: eugenezelenko
Date: Thu Jan 17 12:00:23 2019
New Revision: 351468

URL: http://llvm.org/viewvc/llvm-project?rev=351468=rev
Log:
[Documentation] Fix another link in docs/clang-tidy/Contributing.rst.

Modified:
clang-tools-extra/trunk/docs/clang-tidy/Contributing.rst

Modified: clang-tools-extra/trunk/docs/clang-tidy/Contributing.rst
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/docs/clang-tidy/Contributing.rst?rev=351468=351467=351468=diff
==
--- clang-tools-extra/trunk/docs/clang-tidy/Contributing.rst (original)
+++ clang-tools-extra/trunk/docs/clang-tidy/Contributing.rst Thu Jan 17 
12:00:23 2019
@@ -422,12 +422,15 @@ To test a check it's best to try it out
 are the natural targets as you already have the source code around. The most
 convenient way to run :program:`clang-tidy` is with a compile command database;
 CMake can automatically generate one, for a description of how to enable it see
-`How To Setup Tooling For LLVM`_. Once ``compile_commands.json`` is in place 
and
-a working version of :program:`clang-tidy` is in ``PATH`` the entire code base
-can be analyzed with ``clang-tidy/tool/run-clang-tidy.py``. The script executes
-:program:`clang-tidy` with the default set of checks on every translation unit
-in the compile command database and displays the resulting warnings and errors.
-The script provides multiple configuration flags.
+`How To Setup Clang Tooling For LLVM`_. Once ``compile_commands.json`` is in
+place and a working version of :program:`clang-tidy` is in ``PATH`` the entire
+code base can be analyzed with ``clang-tidy/tool/run-clang-tidy.py``. The 
script
+executes :program:`clang-tidy` with the default set of checks on every
+translation unit in the compile command database and displays the resulting
+warnings and errors. The script provides multiple configuration flags.
+
+.. _How To Setup Clang Tooling For LLVM: 
https://clang.llvm.org/docs/HowToSetupToolingForLLVM.html
+
 
 * The default set of checks can be overridden using the ``-checks`` argument,
   taking the identical format as :program:`clang-tidy` does. For example


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


[PATCH] D56852: [AArch64] Use LLU for 64-bit crc32 arguments

2019-01-17 Thread Eli Friedman via Phabricator via cfe-commits
efriedma added a comment.

While you're here, can you also fix `__builtin_arm_rbit64`, 
`__builtin_arm_rsr64`, and `__builtin_arm_wsr64`?




Comment at: include/clang/Basic/BuiltinsAArch64.def:54
+BUILTIN(__builtin_arm_crc32d, "UiUiLLUi", "nc")
+BUILTIN(__builtin_arm_crc32cd, "UiUiLLUi", "nc")
 

rnk wrote:
> If we can't change the signature on Linux (I don't see any reason why 
> couldn't, though) we can use the 'W' builtin code to indicate that it's 
> `long` on LP64 and `long long` on LLP64.
Changing the signature would be fine, I think (we don't expect people to use 
these directly, and even if they did it wouldn't make any practical difference 
outside of obscure edge cases).  But probably better to match the ACLE 
signature for the sake of clarity.


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

https://reviews.llvm.org/D56852



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


[clang-tools-extra] r351467 - [Documentation] Another attempt to fix link in docs/clang-tidy/Contributing.rst. Use HTTPS for links.

2019-01-17 Thread Eugene Zelenko via cfe-commits
Author: eugenezelenko
Date: Thu Jan 17 11:47:44 2019
New Revision: 351467

URL: http://llvm.org/viewvc/llvm-project?rev=351467=rev
Log:
[Documentation] Another attempt to fix link in 
docs/clang-tidy/Contributing.rst. Use HTTPS for links.

Modified:
clang-tools-extra/trunk/docs/clang-tidy/Contributing.rst

Modified: clang-tools-extra/trunk/docs/clang-tidy/Contributing.rst
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/docs/clang-tidy/Contributing.rst?rev=351467=351466=351467=diff
==
--- clang-tools-extra/trunk/docs/clang-tidy/Contributing.rst (original)
+++ clang-tools-extra/trunk/docs/clang-tidy/Contributing.rst Thu Jan 17 
11:47:44 2019
@@ -32,9 +32,9 @@ If CMake is configured with ``CLANG_ENAB
 ``clang-analyzer-*`` checks or the ``mpi-*`` checks.
 
 
-.. _AST Matchers: http://clang.llvm.org/docs/LibASTMatchers.html
-.. _PPCallbacks: http://clang.llvm.org/doxygen/classclang_1_1PPCallbacks.html
-.. _clang-check: http://clang.llvm.org/docs/ClangCheck.html
+.. _AST Matchers: https://clang.llvm.org/docs/LibASTMatchers.html
+.. _PPCallbacks: https://clang.llvm.org/doxygen/classclang_1_1PPCallbacks.html
+.. _clang-check: https://clang.llvm.org/docs/ClangCheck.html
 
 
 Choosing the Right Place for your Check
@@ -66,8 +66,9 @@ CMake.
 Once you are done, change to the ``llvm/tools/clang/tools/extra`` directory, 
and
 let's start!
 
-.. _Getting Started with the LLVM System: 
http://llvm.org/docs/GettingStarted.html
-.. _Using Clang Tools: http://clang.llvm.org/docs/ClangTools.html
+.. _Getting Started with the LLVM System: 
https://llvm.org/docs/GettingStarted.html
+.. _Using Clang Tools: https://clang.llvm.org/docs/ClangTools.html
+.. _How To Setup Clang Tooling For LLVM: 
https://clang.llvm.org/docs/HowToSetupToolingForLLVM.html
 
 
 The Directory Structure
@@ -120,13 +121,13 @@ Started with LLVM`_ document for instruc
 the `LLVM Coding Standards`_ document to familiarize yourself with the coding
 style used in the project. For code reviews we mostly use `LLVM Phabricator`_.
 
-.. _Getting Started with LLVM: http://llvm.org/docs/GettingStarted.html
-.. _LLVM Coding Standards: http://llvm.org/docs/CodingStandards.html
-.. _LLVM Phabricator: http://llvm.org/docs/Phabricator.html
+.. _Getting Started with LLVM: https://llvm.org/docs/GettingStarted.html
+.. _LLVM Coding Standards: https://llvm.org/docs/CodingStandards.html
+.. _LLVM Phabricator: https://llvm.org/docs/Phabricator.html
 
 Next, you need to decide which module the check belongs to. Modules
 are located in subdirectories of `clang-tidy/
-`_
+`_
 and contain checks targeting a certain aspect of code quality (performance,
 readability, etc.), certain coding style or standard (Google, LLVM, CERT, etc.)
 or a widely used API (e.g. MPI). Their names are same as user-facing check
@@ -209,9 +210,9 @@ can further inspect them and report diag
 
 (If you want to see an example of a useful check, look at
 `clang-tidy/google/ExplicitConstructorCheck.h
-`_
+`_
 and `clang-tidy/google/ExplicitConstructorCheck.cpp
-`_).
+`_).
 
 
 Registering your Check
@@ -409,9 +410,9 @@ most frequent pitfalls are macros and te
macro expansions/template instantiations, but easily break some other
expansions/instantiations.
 
-.. _lit: http://llvm.org/docs/CommandGuide/lit.html
-.. _FileCheck: http://llvm.org/docs/CommandGuide/FileCheck.html
-.. _test/clang-tidy/google-readability-casting.cpp: 
http://reviews.llvm.org/diffusion/L/browse/clang-tools-extra/trunk/test/clang-tidy/google-readability-casting.cpp
+.. _lit: https://llvm.org/docs/CommandGuide/lit.html
+.. _FileCheck: https://llvm.org/docs/CommandGuide/FileCheck.html
+.. _test/clang-tidy/google-readability-casting.cpp: 
https://reviews.llvm.org/diffusion/L/browse/clang-tools-extra/trunk/test/clang-tidy/google-readability-casting.cpp
 
 
 Running clang-tidy on LLVM


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


[PATCH] D52891: [AMDGPU] Add -fvisibility-amdgpu-non-kernel-functions

2019-01-17 Thread Scott Linder via Phabricator via cfe-commits
scott.linder abandoned this revision.
scott.linder added a comment.

Will be superseded by either https://reviews.llvm.org/D53153 or 
https://reviews.llvm.org/D56871


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

https://reviews.llvm.org/D52891



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


[clang-tools-extra] r351466 - [Documentation] Fix link in docs/clang-tidy/Contributing.rst.

2019-01-17 Thread Eugene Zelenko via cfe-commits
Author: eugenezelenko
Date: Thu Jan 17 11:35:39 2019
New Revision: 351466

URL: http://llvm.org/viewvc/llvm-project?rev=351466=rev
Log:
[Documentation] Fix link in docs/clang-tidy/Contributing.rst.

Modified:
clang-tools-extra/trunk/docs/clang-tidy/Contributing.rst

Modified: clang-tools-extra/trunk/docs/clang-tidy/Contributing.rst
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/docs/clang-tidy/Contributing.rst?rev=351466=351465=351466=diff
==
--- clang-tools-extra/trunk/docs/clang-tidy/Contributing.rst (original)
+++ clang-tools-extra/trunk/docs/clang-tidy/Contributing.rst Thu Jan 17 
11:35:39 2019
@@ -59,8 +59,9 @@ Preparing your Workspace
 
 
 If you are new to LLVM development, you should read the `Getting Started with
-the LLVM System`_, `Using Clang Tools`_ and `How To Setup Tooling For LLVM`_
-documents to check out and build LLVM, Clang and Clang Extra Tools with CMake.
+the LLVM System`_, `Using Clang Tools`_ and `How To Setup Clang Tooling For
+LLVM`_ documents to check out and build LLVM, Clang and Clang Extra Tools with
+CMake.
 
 Once you are done, change to the ``llvm/tools/clang/tools/extra`` directory, 
and
 let's start!


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


[PATCH] D56871: [AMDGPU] Require at least protected visibility for certain symbols

2019-01-17 Thread Scott Linder via Phabricator via cfe-commits
scott.linder created this revision.
scott.linder added reviewers: b-sumner, arsenm, kzhuravl, t-tye, yaxunl.
Herald added subscribers: cfe-commits, tpr, dstuttard, wdng.

This allows the global visibility controls to be restrictive while still 
populating the dynamic symbol table where required. Depends in-part on a patch 
to apply global symbol visibility to declarations, although this patch is 
conservatively correct without that change.


Repository:
  rC Clang

https://reviews.llvm.org/D56871

Files:
  lib/CodeGen/CodeGenModule.cpp
  lib/CodeGen/TargetInfo.cpp
  test/CodeGenOpenCL/visibility.cl

Index: test/CodeGenOpenCL/visibility.cl
===
--- /dev/null
+++ test/CodeGenOpenCL/visibility.cl
@@ -0,0 +1,77 @@
+// RUN: %clang_cc1 -std=cl2.0 -fvisibility default -triple amdgcn-unknown-unknown -S -emit-llvm -o - %s | FileCheck --check-prefix=FVIS-DEFAULT %s
+// RUN: %clang_cc1 -std=cl2.0 -fvisibility protected -triple amdgcn-unknown-unknown -S -emit-llvm -o - %s | FileCheck --check-prefix=FVIS-PROTECTED %s
+// RUN: %clang_cc1 -std=cl2.0 -fvisibility hidden -triple amdgcn-unknown-unknown -S -emit-llvm -o - %s | FileCheck --check-prefix=FVIS-HIDDEN %s
+
+// REQUIRES: amdgpu-registered-target
+
+// FVIS-DEFAULT:  @glob = local_unnamed_addr
+// FVIS-PROTECTED: @glob = protected local_unnamed_addr
+// FVIS-HIDDEN: @glob = hidden local_unnamed_addr
+int glob = 0;
+// FVIS-DEFAULT:  @glob_hidden = hidden local_unnamed_addr
+// FVIS-PROTECTED: @glob_hidden = hidden local_unnamed_addr
+// FVIS-HIDDEN: @glob_hidden = hidden local_unnamed_addr
+__attribute__((visibility("hidden"))) int glob_hidden = 0;
+// FVIS-DEFAULT:  @glob_protected = protected local_unnamed_addr
+// FVIS-PROTECTED: @glob_protected = protected local_unnamed_addr
+// FVIS-HIDDEN: @glob_protected = protected local_unnamed_addr
+__attribute__((visibility("protected"))) int glob_protected = 0;
+// FVIS-DEFAULT:  @glob_default = local_unnamed_addr
+// FVIS-PROTECTED: @glob_default = local_unnamed_addr
+// FVIS-HIDDEN: @glob_default = local_unnamed_addr
+__attribute__((visibility("default"))) int glob_default = 0;
+
+// FVIS-DEFAULT:  @ext = external local_unnamed_addr
+// FVIS-PROTECTED: @ext = external local_unnamed_addr
+// FVIS-HIDDEN: @ext = external local_unnamed_addr
+extern int ext;
+// FVIS-DEFAULT:  @ext_hidden = external hidden local_unnamed_addr
+// FVIS-PROTECTED: @ext_hidden = external hidden local_unnamed_addr
+// FVIS-HIDDEN: @ext_hidden = external hidden local_unnamed_addr
+__attribute__((visibility("hidden"))) extern int ext_hidden;
+// FVIS-DEFAULT:  @ext_protected = external protected local_unnamed_addr
+// FVIS-PROTECTED: @ext_protected = external protected local_unnamed_addr
+// FVIS-HIDDEN: @ext_protected = external protected local_unnamed_addr
+__attribute__((visibility("protected"))) extern int ext_protected;
+// FVIS-DEFAULT:  @ext_default = external local_unnamed_addr
+// FVIS-PROTECTED: @ext_default = external local_unnamed_addr
+// FVIS-HIDDEN: @ext_default = external local_unnamed_addr
+__attribute__((visibility("default"))) extern int ext_default;
+
+// FVIS-DEFAULT: define amdgpu_kernel void @kern()
+// FVIS-PROTECTED: define protected amdgpu_kernel void @kern()
+// FVIS-HIDDEN: define protected amdgpu_kernel void @kern()
+kernel void kern() {}
+// FVIS-DEFAULT: define protected amdgpu_kernel void @kern_hidden()
+// FVIS-PROTECTED: define protected amdgpu_kernel void @kern_hidden()
+// FVIS-HIDDEN: define protected amdgpu_kernel void @kern_hidden()
+__attribute__((visibility("hidden"))) kernel void kern_hidden() {}
+// FVIS-DEFAULT: define protected amdgpu_kernel void @kern_protected()
+// FVIS-PROTECTED: define protected amdgpu_kernel void @kern_protected()
+// FVIS-HIDDEN: define protected amdgpu_kernel void @kern_protected()
+__attribute__((visibility("protected"))) kernel void kern_protected() {}
+// FVIS-DEFAULT: define amdgpu_kernel void @kern_default()
+// FVIS-PROTECTED: define amdgpu_kernel void @kern_default()
+// FVIS-HIDDEN: define amdgpu_kernel void @kern_default()
+__attribute__((visibility("default"))) kernel void kern_default() {}
+
+// FVIS-DEFAULT: define void @func()
+// FVIS-PROTECTED: define protected void @func()
+// FVIS-HIDDEN: define hidden void @func()
+void func() {}
+// FVIS-DEFAULT: define hidden void @func_hidden()
+// FVIS-PROTECTED: define hidden void @func_hidden()
+// FVIS-HIDDEN: define hidden void @func_hidden()
+__attribute__((visibility("hidden"))) void func_hidden() {}
+// FVIS-DEFAULT: define protected void @func_protected()
+// FVIS-PROTECTED: define protected void @func_protected()
+// FVIS-HIDDEN: define protected void @func_protected()
+__attribute__((visibility("protected"))) void func_protected() {}
+// FVIS-DEFAULT: define void @func_default()
+// FVIS-PROTECTED: define void @func_default()
+// FVIS-HIDDEN: define void @func_default()
+__attribute__((visibility("default"))) void func_default() {}
+
+void use() {
+ 

[PATCH] D56852: [AArch64] Use LLU for 64-bit crc32 arguments

2019-01-17 Thread Reid Kleckner via Phabricator via cfe-commits
rnk added inline comments.



Comment at: include/clang/Basic/BuiltinsAArch64.def:54
+BUILTIN(__builtin_arm_crc32d, "UiUiLLUi", "nc")
+BUILTIN(__builtin_arm_crc32cd, "UiUiLLUi", "nc")
 

If we can't change the signature on Linux (I don't see any reason why couldn't, 
though) we can use the 'W' builtin code to indicate that it's `long` on LP64 
and `long long` on LLP64.


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

https://reviews.llvm.org/D56852



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


[PATCH] D54141: [clang-tidy] add deduplication support for run-clang-tidy.py

2019-01-17 Thread Jonas Toth via Phabricator via cfe-commits
JonasToth updated this revision to Diff 182359.
JonasToth added a comment.
Herald added a reviewer: serge-sans-paille.

- make the script more useable in my buildbot context
- reduce the test-files
- fix unicode issues I encountered while using


Repository:
  rCTE Clang Tools Extra

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

https://reviews.llvm.org/D54141

Files:
  clang-tidy/tool/run-clang-tidy.py
  clang-tidy/tool/run_clang_tidy.py
  clang-tidy/tool/test_input/out_csa_cmake.log
  clang-tidy/tool/test_input/out_performance_cmake.log
  clang-tidy/tool/test_log_parser.py
  docs/ReleaseNotes.rst

Index: docs/ReleaseNotes.rst
===
--- docs/ReleaseNotes.rst
+++ docs/ReleaseNotes.rst
@@ -69,6 +69,9 @@
 
 - ...
 
+- `run-clang-tidy.py` support deduplication of `clang-tidy` diagnostics
+  to reduce the amount of output with the optional `-deduplicate` flag.
+
 Improvements to include-fixer
 -
 
Index: clang-tidy/tool/test_log_parser.py
===
--- /dev/null
+++ clang-tidy/tool/test_log_parser.py
@@ -0,0 +1,236 @@
+#!/usr/bin/env python
+# -*- coding: utf-8 -*-
+
+import unittest
+from run_clang_tidy import Diagnostic, Deduplication
+from run_clang_tidy import ParseClangTidyDiagnostics, _is_valid_diag_match
+
+
+class TestDiagnostics(unittest.TestCase):
+"""Test fingerprinting diagnostic messages"""
+
+def test_construction(self):
+d = Diagnostic("/home/user/project/my_file.h", 24, 4,
+   "warning: Do not do this thing [warning-category]")
+self.assertIsNotNone(d)
+self.assertEqual(str(d),
+ "/home/user/project/my_file.h:24:4: warning: Do not do this thing [warning-category]")
+
+d.add_additional_line("  MyCodePiece();")
+d.add_additional_line("  ^")
+
+self.assertEqual(str(d),
+ "/home/user/project/my_file.h:24:4: warning: Do not do this thing [warning-category]"
+ "\n  MyCodePiece();"
+ "\n  ^")
+
+
+class TestDeduplication(unittest.TestCase):
+"""Test the `DiagEssence` based deduplication of diagnostic messages."""
+
+def test_construction(self):
+self.assertIsNotNone(Deduplication())
+
+def test_dedup(self):
+dedup = Deduplication()
+d = Diagnostic("/home/user/project/my_file.h", 24, 4,
+   "warning: Do not do this thing [warning-category]")
+self.assertTrue(dedup.insert_and_query(d))
+self.assertFalse(dedup.insert_and_query(d))
+
+d2 = Diagnostic("/home/user/project/my_file.h", 24, 4,
+"warning: Do not do this thing [warning-category]")
+d2.add_additional_line("  MyCodePiece();")
+d2.add_additional_line("  ^")
+self.assertTrue(dedup.insert_and_query(d2))
+self.assertFalse(dedup.insert_and_query(d2))
+
+d3 = Diagnostic("/home/user/project/my_file.h", 24, 4,
+"warning: Do not do this thing [warning-category]")
+self.assertFalse(dedup.insert_and_query(d3))
+
+class TestLinewiseParsing(unittest.TestCase):
+def test_construction(self):
+self.assertIsNotNone(ParseClangTidyDiagnostics())
+
+def test_valid_diags_regex(self):
+pp = ParseClangTidyDiagnostics()
+
+warning = "/home/user/project/my_file.h:123:1: warning: don't do it [no]"
+m = pp._diag_re.match(warning)
+self.assertTrue(m)
+self.assertTrue(_is_valid_diag_match(m.groups()))
+
+error = "/home/user/project/my_file.h:1:110: error: wrong! [not-ok]"
+m = pp._diag_re.match(error)
+self.assertTrue(m)
+self.assertTrue(_is_valid_diag_match(m.groups()))
+
+hybrid = "/home/user/project/boo.cpp:30:42: error: wrong! [not-ok,bad]"
+m = pp._diag_re.match(hybrid)
+self.assertTrue(m)
+self.assertTrue(_is_valid_diag_match(m.groups()))
+
+note = "/home/user/project/my_file.h:1:110: note: alksdj"
+m = pp._diag_re.match(note)
+self.assertFalse(m)
+
+garbage = "not a path:not_a_number:110: gibberish"
+m = pp._diag_re.match(garbage)
+self.assertFalse(m)
+
+def test_single_diagnostics(self):
+pp = ParseClangTidyDiagnostics()
+example_warning = [
+"/project/git/Source/kwsys/Terminal.c:53:21: warning: use of a signed integer operand with a binary bitwise operator [hicpp-signed-bitwise]",
+]
+pp._parse_lines(example_warning)
+self.assertEqual(
+str(pp.get_diags()[0]),
+"/project/git/Source/kwsys/Terminal.c:53:21: warning: use of a signed integer operand with a binary bitwise operator [hicpp-signed-bitwise]"
+)
+
+def test_no_diag(self):
+pp = ParseClangTidyDiagnostics()
+

[PATCH] D56731: Add -Wimplicit-ctad warning to diagnose CTAD on types with no user defined deduction guides.

2019-01-17 Thread Richard Smith - zygoloid via Phabricator via cfe-commits
rsmith accepted this revision.
rsmith added inline comments.



Comment at: include/clang/Basic/DiagnosticSemaKinds.td:2129
+def warn_class_template_argument_deduction_no_user_defined_guides : Warning<
+  "using class template argument deduction for %0 that has no user-defined 
deduction guides" >,
+  InGroup, DefaultIgnore;

EricWF wrote:
> rsmith wrote:
> > gromer wrote:
> > > EricWF wrote:
> > > > rsmith wrote:
> > > > > gromer wrote:
> > > > > > I'd prefer a phrasing more along the lines of "using class template 
> > > > > > argument deduction for %0 that might not intentionally support it". 
> > > > > > That gives us more room to do things like add an attribute later if 
> > > > > > necessary, and it helps the user understand why this warning 
> > > > > > indicates a potential problem.
> > > > > I like that approach; something like "using class template argument 
> > > > > deduction for %0 that might not intend to support it" -- or perhaps 
> > > > > more directly "%0 might not intend to support class template argument 
> > > > > deduction" -- along with a note describing how to syntactically 
> > > > > suppress the warning (w"add a deduction guide to suppress this 
> > > > > warning" or "use the [[clang::ctad]] attribute to suppress this 
> > > > > warning" or whatever we decide is best).
> > > > This sounds like a reasonable change to me. Done.
> > > > 
> > > > I'm not sure an attribute is needed at this point; AFAIK there is no 
> > > > case where a user defined guide can't be added. Even if it's just a 
> > > > dummy guide to suppress the warning. For example:
> > > > 
> > > > ```
> > > > 
> > > > struct allow_ctad_t {
> > > >   allow_ctad_t() = delete;
> > > > };
> > > > 
> > > > template 
> > > > struct TestSuppression {
> > > >   TestSuppression(int, T) {}
> > > > };
> > > > TestSuppression(allow_ctad_t) -> TestSuppression;
> > > > ```
> > > > 
> > > > Also, before we add an attribute, we want to be sure that it's not 
> > > > harmful to allowing users to suppress the warning without actually 
> > > > addressing the root problem (tha implicit CTAD results are often 
> > > > surprising). I would like to see real world examples of types that 
> > > > don't need user-defined guides to work.
> > > > 
> > > > I'm not sure an attribute is needed at this point
> > > 
> > > I agree; I just want to keep the option open in case we decide we need 
> > > one later.
> > `TestSuppression(allow_ctad_t) -> TestSuppression;` doesn't always 
> > work:
> > 
> > ```
> > struct X { X(); };
> > template struct TestSuppression {
> >   TestSuppression(T);
> > };
> > TestSuppression(allow_ctad_t) -> TestSuppression;
> > TestSuppression x({}); // ok without deduction guide, ill-formed with
> > ```
> > 
> > I think this should work reliably (note that the incomplete parameter type 
> > makes the deduction guide always non-viable):
> > 
> > ```TestSuppression(struct AllowCTAD) -> TestSuppression;```
> > 
> > ... and maybe we should suggest that in our note, perhaps with a fix-it 
> > hint pointing immediately after the class template definition?
> I'm a bit skeptical of a diagnostic pointing at white space at the end of 
> classes. If we could produce a actionable fixit, then maybe, but what do we 
> put on the right hand side of `->`?
Yeah, the "what goes on the right-hand side" problem is troublesome. What I'm 
worried about is that people will read the note and add a deduction guide that 
breaks their deduction semantics, or get annoyed with us because it's not 
obvious how to add a deduction guide without breaking their deduction semantics 
or duplicating deduction rules from the constructors.

OK, let's go with this for now and see how users react.


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

https://reviews.llvm.org/D56731



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


[PATCH] D45444: [clang-tidy] implement new check for const-correctness

2019-01-17 Thread Jonas Toth via Phabricator via cfe-commits
JonasToth updated this revision to Diff 182356.
JonasToth added a comment.

- avoid bitrot


Repository:
  rCTE Clang Tools Extra

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

https://reviews.llvm.org/D45444

Files:
  clang-tidy/cppcoreguidelines/CMakeLists.txt
  clang-tidy/cppcoreguidelines/ConstCorrectnessCheck.cpp
  clang-tidy/cppcoreguidelines/ConstCorrectnessCheck.h
  clang-tidy/cppcoreguidelines/CppCoreGuidelinesTidyModule.cpp
  docs/ReleaseNotes.rst
  docs/clang-tidy/checks/cppcoreguidelines-const-correctness.rst
  docs/clang-tidy/checks/list.rst
  test/clang-tidy/cppcoreguidelines-const-correctness-pointer-as-values.cpp
  test/clang-tidy/cppcoreguidelines-const-correctness-values.cpp

Index: test/clang-tidy/cppcoreguidelines-const-correctness-values.cpp
===
--- /dev/null
+++ test/clang-tidy/cppcoreguidelines-const-correctness-values.cpp
@@ -0,0 +1,563 @@
+// RUN: %check_clang_tidy %s cppcoreguidelines-const-correctness %t
+
+// --- Provide test samples for primitive builtins -
+// - every 'p_*' variable is a 'potential_const_*' variable
+// - every 'np_*' variable is a 'non_potential_const_*' variable
+
+bool global;
+char np_global = 0; // globals can't be known to be const
+
+namespace foo {
+int scoped;
+float np_scoped = 1; // namespace variables are like globals
+} // namespace foo
+
+// Lambdas should be ignored, because they do not follow the normal variable
+// semantic (e.g. the type is only known to the compiler).
+void lambdas() {
+  auto Lambda = [](int i) { return i < 0; };
+}
+
+void some_function(double, wchar_t);
+
+void some_function(double np_arg0, wchar_t np_arg1) {
+  int p_local0 = 2;
+  // CHECK-MESSAGES: [[@LINE-1]]:3: warning: variable 'p_local0' of type 'int' can be declared 'const'
+
+  int np_local0;
+  const int np_local1 = 42;
+
+  unsigned int np_local2 = 3;
+  np_local2 <<= 4;
+
+  int np_local3 = 4;
+  ++np_local3;
+  int np_local4 = 4;
+  np_local4++;
+
+  int np_local5 = 4;
+  --np_local5;
+  int np_local6 = 4;
+  np_local6--;
+}
+
+void nested_scopes() {
+  int p_local0 = 2;
+  // CHECK-MESSAGES: [[@LINE-1]]:3: warning: variable 'p_local0' of type 'int' can be declared 'const'
+  int np_local0 = 42;
+
+  {
+int p_local1 = 42;
+// CHECK-MESSAGES: [[@LINE-1]]:5: warning: variable 'p_local1' of type 'int' can be declared 'const'
+np_local0 *= 2;
+  }
+}
+
+void some_lambda_environment_capture_all_by_reference(double np_arg0) {
+  int np_local0 = 0;
+  int p_local0 = 1;
+  // CHECK-MESSAGES: [[@LINE-1]]:3: warning: variable 'p_local0' of type 'int' can be declared 'const'
+
+  int np_local2;
+  const int np_local3 = 2;
+
+  // Capturing all variables by reference prohibits making them const.
+  [&]() { ++np_local0; };
+
+  int p_local1 = 0;
+  // CHECK-MESSAGES: [[@LINE-1]]:3: warning: variable 'p_local1' of type 'int' can be declared 'const'
+}
+
+void some_lambda_environment_capture_all_by_value(double np_arg0) {
+  int np_local0 = 0;
+  int p_local0 = 1;
+  // CHECK-MESSAGES: [[@LINE-1]]:3: warning: variable 'p_local0' of type 'int' can be declared 'const'
+
+  int np_local1;
+  const int np_local2 = 2;
+
+  // Capturing by value has no influence on them.
+  [=]() { (void)p_local0; };
+
+  np_local0 += 10;
+}
+
+void function_inout_pointer(int *inout);
+void function_in_pointer(const int *in);
+
+void some_pointer_taking(int *out) {
+  int np_local0 = 42;
+  const int *const p0_np_local0 = _local0;
+  int *const p1_np_local0 = _local0;
+
+  int np_local1 = 42;
+  const int *const p0_np_local1 = _local1;
+  int *const p1_np_local1 = _local1;
+  *p1_np_local0 = 43;
+
+  int np_local2 = 42;
+  function_inout_pointer(_local2);
+
+  // Prevents const.
+  int np_local3 = 42;
+  out = _local3; // This returns and invalid address, its just about the AST
+
+  int p_local1 = 42;
+  // CHECK-MESSAGES: [[@LINE-1]]:3: warning: variable 'p_local1' of type 'int' can be declared 'const'
+  const int *const p0_p_local1 = _local1;
+
+  int p_local2 = 42;
+  // CHECK-MESSAGES: [[@LINE-1]]:3: warning: variable 'p_local2' of type 'int' can be declared 'const'
+  function_in_pointer(_local2);
+}
+
+void function_inout_ref(int );
+void function_in_ref(const int );
+
+void some_reference_taking() {
+  int np_local0 = 42;
+  const int _np_local0 = np_local0;
+  int _np_local0 = np_local0;
+  r1_np_local0 = 43;
+  const int _np_local0 = r1_np_local0;
+
+  int np_local1 = 42;
+  function_inout_ref(np_local1);
+
+  int p_local0 = 42;
+  // CHECK-MESSAGES: [[@LINE-1]]:3: warning: variable 'p_local0' of type 'int' can be declared 'const'
+  const int _p_local0 = p_local0;
+
+  int p_local1 = 42;
+  // CHECK-MESSAGES: [[@LINE-1]]:3: warning: variable 'p_local1' of type 'int' can be declared 'const'
+  function_in_ref(p_local1);
+}
+
+double *non_const_pointer_return() {
+  double p_local0 = 0.0;
+  // CHECK-MESSAGES: [[@LINE-1]]:3: warning: variable 'p_local0' of type 'double' can be 

[PATCH] D54943: [clang-tidy] implement const-transformation for cppcoreguidelines-const-correctness

2019-01-17 Thread Jonas Toth via Phabricator via cfe-commits
JonasToth updated this revision to Diff 182355.
JonasToth added a comment.

- accidentally wrong patch uploaded


Repository:
  rCTE Clang Tools Extra

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

https://reviews.llvm.org/D54943

Files:
  clang-tidy/cppcoreguidelines/CMakeLists.txt
  clang-tidy/cppcoreguidelines/ConstCorrectnessCheck.cpp
  clang-tidy/cppcoreguidelines/ConstCorrectnessCheck.h
  clang-tidy/cppcoreguidelines/CppCoreGuidelinesTidyModule.cpp
  clang-tidy/performance/ForRangeCopyCheck.cpp
  clang-tidy/performance/UnnecessaryCopyInitialization.cpp
  clang-tidy/performance/UnnecessaryValueParamCheck.cpp
  clang-tidy/utils/FixItHintUtils.cpp
  clang-tidy/utils/FixItHintUtils.h
  clang-tidy/utils/LexerUtils.cpp
  clang-tidy/utils/LexerUtils.h
  docs/ReleaseNotes.rst
  docs/clang-tidy/checks/cppcoreguidelines-const-correctness.rst
  docs/clang-tidy/checks/list.rst
  test/clang-tidy/cppcoreguidelines-const-correctness-pointer-as-values.cpp
  
test/clang-tidy/cppcoreguidelines-const-correctness-transform-pointer-as-values.cpp
  test/clang-tidy/cppcoreguidelines-const-correctness-transform-values.cpp
  test/clang-tidy/cppcoreguidelines-const-correctness-values.cpp
  unittests/clang-tidy/AddConstTest.cpp
  unittests/clang-tidy/CMakeLists.txt

Index: unittests/clang-tidy/CMakeLists.txt
===
--- unittests/clang-tidy/CMakeLists.txt
+++ unittests/clang-tidy/CMakeLists.txt
@@ -7,6 +7,7 @@
 include_directories(${CLANG_LINT_SOURCE_DIR})
 
 add_extra_unittest(ClangTidyTests
+  AddConstTest.cpp
   ClangTidyDiagnosticConsumerTest.cpp
   ClangTidyOptionsTest.cpp
   IncludeInserterTest.cpp
Index: unittests/clang-tidy/AddConstTest.cpp
===
--- /dev/null
+++ unittests/clang-tidy/AddConstTest.cpp
@@ -0,0 +1,857 @@
+#include "../clang-tidy/utils/FixItHintUtils.h"
+#include "ClangTidyTest.h"
+#include "clang/ASTMatchers/ASTMatchFinder.h"
+#include "clang/ASTMatchers/ASTMatchers.h"
+#include "clang/Tooling/Tooling.h"
+#include "gtest/gtest.h"
+
+namespace clang {
+namespace tidy {
+
+namespace {
+using namespace clang::ast_matchers;
+using namespace utils::fixit;
+
+template 
+class ConstTransform : public ClangTidyCheck {
+public:
+  ConstTransform(StringRef CheckName, ClangTidyContext *Context)
+  : ClangTidyCheck(CheckName, Context) {}
+
+  void registerMatchers(MatchFinder *Finder) override {
+Finder->addMatcher(varDecl(hasName("target")).bind("var"), this);
+  }
+
+  void check(const MatchFinder::MatchResult ) override {
+const auto *D = Result.Nodes.getNodeAs("var");
+using utils::fixit::changeVarDeclToConst;
+Optional Fix = changeVarDeclToConst(*D, CT, CP, Result.Context);
+auto Diag = diag(D->getBeginLoc(), "doing const transformation");
+if (Fix)
+  Diag << *Fix;
+  }
+};
+} // namespace
+
+namespace test {
+using PointeeLTransform =
+ConstTransform;
+using PointeeRTransform =
+ConstTransform;
+
+using ValueLTransform = ConstTransform;
+using ValueRTransform = ConstTransform;
+
+// 
+// Test Value-like types. Everything with indirection is done later.
+// 
+
+// TODO: Template-code
+
+TEST(Values, Builtin) {
+  StringRef Snippet = "int target = 0;";
+
+  EXPECT_EQ("const int target = 0;", runCheckOnCode(Snippet));
+  EXPECT_EQ("const int target = 0;",
+runCheckOnCode(Snippet));
+
+  EXPECT_EQ("int const target = 0;", runCheckOnCode(Snippet));
+  EXPECT_EQ("int const target = 0;",
+runCheckOnCode(Snippet));
+}
+TEST(Values, TypedefBuiltin) {
+  StringRef T = "typedef int MyInt;";
+  StringRef S = "MyInt target = 0;";
+  auto Cat = [](StringRef S) { return (T + S).str(); };
+
+  EXPECT_EQ(Cat("const MyInt target = 0;"),
+runCheckOnCode(Cat(S)));
+  EXPECT_EQ(Cat("const MyInt target = 0;"),
+runCheckOnCode(Cat(S)));
+
+  EXPECT_EQ(Cat("MyInt const target = 0;"),
+runCheckOnCode(Cat(S)));
+  EXPECT_EQ(Cat("MyInt const target = 0;"),
+runCheckOnCode(Cat(S)));
+}
+TEST(Values, TypedefBuiltinPointer) {
+  StringRef T = "typedef int* MyInt;";
+  StringRef S = "MyInt target = nullptr;";
+  auto Cat = [](StringRef S) { return (T + S).str(); };
+
+  EXPECT_EQ(Cat("const MyInt target = nullptr;"),
+runCheckOnCode(Cat(S)));
+  EXPECT_EQ(Cat("const MyInt target = nullptr;"),
+runCheckOnCode(Cat(S)));
+
+  EXPECT_EQ(Cat("MyInt const target = nullptr;"),
+runCheckOnCode(Cat(S)));
+  EXPECT_EQ(Cat("MyInt const target = nullptr;"),
+runCheckOnCode(Cat(S)));
+}
+TEST(Values, AutoValue) {
+  StringRef T = "int f() { return 42; }\n";
+  StringRef S = "auto target = f();";
+  auto Cat = [](StringRef S) { return (T + S).str(); };
+
+  EXPECT_EQ(Cat("const auto target = f();"),
+   

[PATCH] D54943: [clang-tidy] implement const-transformation for cppcoreguidelines-const-correctness

2019-01-17 Thread Jonas Toth via Phabricator via cfe-commits
JonasToth updated this revision to Diff 182354.
JonasToth added a comment.

avoid bitrot


Repository:
  rCTE Clang Tools Extra

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

https://reviews.llvm.org/D54943

Files:
  clang-tidy/cppcoreguidelines/CMakeLists.txt
  clang-tidy/cppcoreguidelines/ConstCorrectnessCheck.cpp
  clang-tidy/cppcoreguidelines/ConstCorrectnessCheck.h
  clang-tidy/cppcoreguidelines/CppCoreGuidelinesTidyModule.cpp
  docs/ReleaseNotes.rst
  docs/clang-tidy/checks/cppcoreguidelines-const-correctness.rst
  docs/clang-tidy/checks/list.rst
  test/clang-tidy/cppcoreguidelines-const-correctness-pointer-as-values.cpp
  test/clang-tidy/cppcoreguidelines-const-correctness-values.cpp

Index: test/clang-tidy/cppcoreguidelines-const-correctness-values.cpp
===
--- /dev/null
+++ test/clang-tidy/cppcoreguidelines-const-correctness-values.cpp
@@ -0,0 +1,563 @@
+// RUN: %check_clang_tidy %s cppcoreguidelines-const-correctness %t
+
+// --- Provide test samples for primitive builtins -
+// - every 'p_*' variable is a 'potential_const_*' variable
+// - every 'np_*' variable is a 'non_potential_const_*' variable
+
+bool global;
+char np_global = 0; // globals can't be known to be const
+
+namespace foo {
+int scoped;
+float np_scoped = 1; // namespace variables are like globals
+} // namespace foo
+
+// Lambdas should be ignored, because they do not follow the normal variable
+// semantic (e.g. the type is only known to the compiler).
+void lambdas() {
+  auto Lambda = [](int i) { return i < 0; };
+}
+
+void some_function(double, wchar_t);
+
+void some_function(double np_arg0, wchar_t np_arg1) {
+  int p_local0 = 2;
+  // CHECK-MESSAGES: [[@LINE-1]]:3: warning: variable 'p_local0' of type 'int' can be declared 'const'
+
+  int np_local0;
+  const int np_local1 = 42;
+
+  unsigned int np_local2 = 3;
+  np_local2 <<= 4;
+
+  int np_local3 = 4;
+  ++np_local3;
+  int np_local4 = 4;
+  np_local4++;
+
+  int np_local5 = 4;
+  --np_local5;
+  int np_local6 = 4;
+  np_local6--;
+}
+
+void nested_scopes() {
+  int p_local0 = 2;
+  // CHECK-MESSAGES: [[@LINE-1]]:3: warning: variable 'p_local0' of type 'int' can be declared 'const'
+  int np_local0 = 42;
+
+  {
+int p_local1 = 42;
+// CHECK-MESSAGES: [[@LINE-1]]:5: warning: variable 'p_local1' of type 'int' can be declared 'const'
+np_local0 *= 2;
+  }
+}
+
+void some_lambda_environment_capture_all_by_reference(double np_arg0) {
+  int np_local0 = 0;
+  int p_local0 = 1;
+  // CHECK-MESSAGES: [[@LINE-1]]:3: warning: variable 'p_local0' of type 'int' can be declared 'const'
+
+  int np_local2;
+  const int np_local3 = 2;
+
+  // Capturing all variables by reference prohibits making them const.
+  [&]() { ++np_local0; };
+
+  int p_local1 = 0;
+  // CHECK-MESSAGES: [[@LINE-1]]:3: warning: variable 'p_local1' of type 'int' can be declared 'const'
+}
+
+void some_lambda_environment_capture_all_by_value(double np_arg0) {
+  int np_local0 = 0;
+  int p_local0 = 1;
+  // CHECK-MESSAGES: [[@LINE-1]]:3: warning: variable 'p_local0' of type 'int' can be declared 'const'
+
+  int np_local1;
+  const int np_local2 = 2;
+
+  // Capturing by value has no influence on them.
+  [=]() { (void)p_local0; };
+
+  np_local0 += 10;
+}
+
+void function_inout_pointer(int *inout);
+void function_in_pointer(const int *in);
+
+void some_pointer_taking(int *out) {
+  int np_local0 = 42;
+  const int *const p0_np_local0 = _local0;
+  int *const p1_np_local0 = _local0;
+
+  int np_local1 = 42;
+  const int *const p0_np_local1 = _local1;
+  int *const p1_np_local1 = _local1;
+  *p1_np_local0 = 43;
+
+  int np_local2 = 42;
+  function_inout_pointer(_local2);
+
+  // Prevents const.
+  int np_local3 = 42;
+  out = _local3; // This returns and invalid address, its just about the AST
+
+  int p_local1 = 42;
+  // CHECK-MESSAGES: [[@LINE-1]]:3: warning: variable 'p_local1' of type 'int' can be declared 'const'
+  const int *const p0_p_local1 = _local1;
+
+  int p_local2 = 42;
+  // CHECK-MESSAGES: [[@LINE-1]]:3: warning: variable 'p_local2' of type 'int' can be declared 'const'
+  function_in_pointer(_local2);
+}
+
+void function_inout_ref(int );
+void function_in_ref(const int );
+
+void some_reference_taking() {
+  int np_local0 = 42;
+  const int _np_local0 = np_local0;
+  int _np_local0 = np_local0;
+  r1_np_local0 = 43;
+  const int _np_local0 = r1_np_local0;
+
+  int np_local1 = 42;
+  function_inout_ref(np_local1);
+
+  int p_local0 = 42;
+  // CHECK-MESSAGES: [[@LINE-1]]:3: warning: variable 'p_local0' of type 'int' can be declared 'const'
+  const int _p_local0 = p_local0;
+
+  int p_local1 = 42;
+  // CHECK-MESSAGES: [[@LINE-1]]:3: warning: variable 'p_local1' of type 'int' can be declared 'const'
+  function_in_ref(p_local1);
+}
+
+double *non_const_pointer_return() {
+  double p_local0 = 0.0;
+  // CHECK-MESSAGES: [[@LINE-1]]:3: warning: variable 'p_local0' of type 'double' can be 

[PATCH] D40854: [clang-tidy] WIP implement cppcoreguidelines check for mixed integer arithmetic

2019-01-17 Thread Jonas Toth via Phabricator via cfe-commits
JonasToth updated this revision to Diff 182353.
JonasToth added a comment.

- avoid bitrot


Repository:
  rCTE Clang Tools Extra

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

https://reviews.llvm.org/D40854

Files:
  clang-tidy/cppcoreguidelines/CMakeLists.txt
  clang-tidy/cppcoreguidelines/CppCoreGuidelinesTidyModule.cpp
  clang-tidy/cppcoreguidelines/MixedIntArithmeticCheck.cpp
  clang-tidy/cppcoreguidelines/MixedIntArithmeticCheck.h
  docs/ReleaseNotes.rst
  docs/clang-tidy/checks/cppcoreguidelines-mixed-int-arithmetic.rst
  docs/clang-tidy/checks/list.rst
  test/clang-tidy/cppcoreguidelines-mixed-int-arithmetic.cpp

Index: test/clang-tidy/cppcoreguidelines-mixed-int-arithmetic.cpp
===
--- /dev/null
+++ test/clang-tidy/cppcoreguidelines-mixed-int-arithmetic.cpp
@@ -0,0 +1,188 @@
+// RUN: %check_clang_tidy %s cppcoreguidelines-mixed-int-arithmetic %t
+
+enum UnsignedEnum : unsigned char {
+  UEnum1,
+  UEnum2
+};
+
+enum SignedEnum : signed char {
+  SEnum1,
+  SEnum2
+};
+
+unsigned char returnUnsignedCharacter() { return 42; }
+unsigned returnUnsignedNumber() { return 42u; }
+long returnBigNumber() { return 42; }
+float unrelatedThing() { return 42.f; }
+SignedEnum returnSignedEnum() { return SEnum1; }
+UnsignedEnum returnUnsignedEnum() { return UEnum1; }
+
+void mixed_binary() {
+  unsigned int UInt1 = 42;
+  signed int SInt1 = 42;
+  UnsignedEnum UE1 = UEnum1;
+  SignedEnum SE1 = SEnum1;
+  float UnrelatedFloat = 42.f;
+
+  // Test traditional integer types.
+  auto R1 = UInt1 + SInt1;
+  // CHECK-MESSAGES: [[@LINE-1]]:13: warning: mixed signed and unsigned arithmetic; prefer signed integers and use unsigned types only for modulo arithmetic
+  // CHECK-MESSAGES: [[@LINE-2]]:21: note: signed operand
+  // CHECK-MESSAGES: [[@LINE-3]]:13: note: unsigned operand
+
+  int R2 = UInt1 - SInt1;
+  // CHECK-MESSAGES: [[@LINE-1]]:12: warning: mixed signed and unsigned arithmetic; prefer signed integers and use unsigned types only for modulo arithmetic
+  // CHECK-MESSAGES: [[@LINE-2]]:20: note: signed operand
+  // CHECK-MESSAGES: [[@LINE-3]]:12: note: unsigned operand
+
+  unsigned int R3 = UInt1 * SInt1;
+  // CHECK-MESSAGES: [[@LINE-1]]:21: warning: mixed signed and unsigned arithmetic; prefer signed integers and use unsigned types only for modulo arithmetic
+  // CHECK-MESSAGES: [[@LINE-2]]:29: note: signed operand
+  // CHECK-MESSAGES: [[@LINE-3]]:21: note: unsigned operand
+
+  unsigned int R4 = UInt1 / returnBigNumber();
+  // CHECK-MESSAGES: [[@LINE-1]]:21: warning: mixed signed and unsigned arithmetic; prefer signed integers and use unsigned types only for modulo arithmetic
+  // CHECK-MESSAGES: [[@LINE-2]]:29: note: signed operand
+  // CHECK-MESSAGES: [[@LINE-3]]:21: note: unsigned operand
+
+  char R5 = returnUnsignedCharacter() + SInt1;
+  // CHECK-MESSAGES: [[@LINE-1]]:13: warning: mixed signed and unsigned arithmetic; prefer signed integers and use unsigned types only for modulo arithmetic
+  // CHECK-MESSAGES: [[@LINE-2]]:41: note: signed operand
+  // CHECK-MESSAGES: [[@LINE-3]]:13: note: unsigned operand
+
+  auto R6 = SInt1 - 10u;
+  // CHECK-MESSAGES: [[@LINE-1]]:13: warning: mixed signed and unsigned arithmetic; prefer signed integers and use unsigned types only for modulo arithmetic
+  // CHECK-MESSAGES: [[@LINE-2]]:13: note: signed operand
+  // CHECK-MESSAGES: [[@LINE-3]]:21: note: unsigned operand
+
+  auto R7 = UInt1 * 10;
+  // CHECK-MESSAGES: [[@LINE-1]]:13: warning: mixed signed and unsigned arithmetic; prefer signed integers and use unsigned types only for modulo arithmetic
+  // CHECK-MESSAGES: [[@LINE-2]]:21: note: signed operand
+  // CHECK-MESSAGES: [[@LINE-3]]:13: note: unsigned operand
+
+  auto R8 = 10u / returnBigNumber();
+  // CHECK-MESSAGES: [[@LINE-1]]:13: warning: mixed signed and unsigned arithmetic; prefer signed integers and use unsigned types only for modulo arithmetic
+  // CHECK-MESSAGES: [[@LINE-2]]:19: note: signed operand
+  // CHECK-MESSAGES: [[@LINE-3]]:13: note: unsigned operand
+
+  auto R9 = 10 + returnUnsignedCharacter();
+  // CHECK-MESSAGES: [[@LINE-1]]:13: warning: mixed signed and unsigned arithmetic; prefer signed integers and use unsigned types only for modulo arithmetic
+  // CHECK-MESSAGES: [[@LINE-2]]:13: note: signed operand
+  // CHECK-MESSAGES: [[@LINE-3]]:18: note: unsigned operand
+
+  // Test enum types.
+  char R10 = returnUnsignedEnum() - SInt1;
+  // CHECK-MESSAGES: [[@LINE-1]]:14: warning: mixed signed and unsigned arithmetic; prefer signed integers and use unsigned types only for modulo arithmetic
+  // CHECK-MESSAGES: [[@LINE-2]]:37: note: signed operand
+  // CHECK-MESSAGES: [[@LINE-3]]:14: note: unsigned operand
+
+  unsigned char R11 = returnSignedEnum() * UInt1;
+  // CHECK-MESSAGES: [[@LINE-1]]:23: warning: mixed signed and unsigned arithmetic; prefer signed integers and use unsigned types only for modulo arithmetic
+  // CHECK-MESSAGES: 

[PATCH] D54395: [clang-tidy] implement utility-function to add 'const' to variables

2019-01-17 Thread Jonas Toth via Phabricator via cfe-commits
JonasToth updated this revision to Diff 182345.
JonasToth added a comment.

- generalize to DeclSpec::TQ
- add dependent type-tests with `typename`


Repository:
  rCTE Clang Tools Extra

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

https://reviews.llvm.org/D54395

Files:
  clang-tidy/performance/ForRangeCopyCheck.cpp
  clang-tidy/performance/UnnecessaryCopyInitialization.cpp
  clang-tidy/performance/UnnecessaryValueParamCheck.cpp
  clang-tidy/utils/FixItHintUtils.cpp
  clang-tidy/utils/FixItHintUtils.h
  clang-tidy/utils/LexerUtils.cpp
  clang-tidy/utils/LexerUtils.h
  unittests/clang-tidy/AddConstTest.cpp
  unittests/clang-tidy/CMakeLists.txt

Index: unittests/clang-tidy/CMakeLists.txt
===
--- unittests/clang-tidy/CMakeLists.txt
+++ unittests/clang-tidy/CMakeLists.txt
@@ -7,6 +7,7 @@
 include_directories(${CLANG_LINT_SOURCE_DIR})
 
 add_extra_unittest(ClangTidyTests
+  AddConstTest.cpp
   ClangTidyDiagnosticConsumerTest.cpp
   ClangTidyOptionsTest.cpp
   IncludeInserterTest.cpp
Index: unittests/clang-tidy/AddConstTest.cpp
===
--- /dev/null
+++ unittests/clang-tidy/AddConstTest.cpp
@@ -0,0 +1,908 @@
+#include "../clang-tidy/utils/FixItHintUtils.h"
+#include "ClangTidyTest.h"
+#include "clang/ASTMatchers/ASTMatchFinder.h"
+#include "clang/ASTMatchers/ASTMatchers.h"
+#include "clang/Tooling/Tooling.h"
+#include "gtest/gtest.h"
+
+namespace clang {
+namespace tidy {
+
+namespace {
+using namespace clang::ast_matchers;
+using namespace utils::fixit;
+
+template 
+class ConstTransform : public ClangTidyCheck {
+public:
+  ConstTransform(StringRef CheckName, ClangTidyContext *Context)
+  : ClangTidyCheck(CheckName, Context) {}
+
+  void registerMatchers(MatchFinder *Finder) override {
+Finder->addMatcher(varDecl(hasName("target")).bind("var"), this);
+  }
+
+  void check(const MatchFinder::MatchResult ) override {
+const auto *D = Result.Nodes.getNodeAs("var");
+using utils::fixit::addQualifierToVarDecl;
+Optional Fix = addQualifierToVarDecl(*D, DeclSpec::TQ::TQ_const,
+CT, CP, Result.Context);
+auto Diag = diag(D->getBeginLoc(), "doing const transformation");
+if (Fix)
+  Diag << *Fix;
+  }
+};
+} // namespace
+
+namespace test {
+using PointeeLTransform =
+ConstTransform;
+using PointeeRTransform =
+ConstTransform;
+
+using ValueLTransform =
+ConstTransform;
+using ValueRTransform =
+ConstTransform;
+
+// 
+// Test Value-like types. Everything with indirection is done later.
+// 
+
+// TODO: Template-code
+
+TEST(Values, Builtin) {
+  StringRef Snippet = "int target = 0;";
+
+  EXPECT_EQ("const int target = 0;", runCheckOnCode(Snippet));
+  EXPECT_EQ("const int target = 0;",
+runCheckOnCode(Snippet));
+
+  EXPECT_EQ("int const target = 0;", runCheckOnCode(Snippet));
+  EXPECT_EQ("int const target = 0;",
+runCheckOnCode(Snippet));
+}
+TEST(Values, TypedefBuiltin) {
+  StringRef T = "typedef int MyInt;";
+  StringRef S = "MyInt target = 0;";
+  auto Cat = [](StringRef S) { return (T + S).str(); };
+
+  EXPECT_EQ(Cat("const MyInt target = 0;"),
+runCheckOnCode(Cat(S)));
+  EXPECT_EQ(Cat("const MyInt target = 0;"),
+runCheckOnCode(Cat(S)));
+
+  EXPECT_EQ(Cat("MyInt const target = 0;"),
+runCheckOnCode(Cat(S)));
+  EXPECT_EQ(Cat("MyInt const target = 0;"),
+runCheckOnCode(Cat(S)));
+}
+TEST(Values, TypedefBuiltinPointer) {
+  StringRef T = "typedef int* MyInt;";
+  StringRef S = "MyInt target = nullptr;";
+  auto Cat = [](StringRef S) { return (T + S).str(); };
+
+  EXPECT_EQ(Cat("const MyInt target = nullptr;"),
+runCheckOnCode(Cat(S)));
+  EXPECT_EQ(Cat("const MyInt target = nullptr;"),
+runCheckOnCode(Cat(S)));
+
+  EXPECT_EQ(Cat("MyInt const target = nullptr;"),
+runCheckOnCode(Cat(S)));
+  EXPECT_EQ(Cat("MyInt const target = nullptr;"),
+runCheckOnCode(Cat(S)));
+}
+TEST(Values, AutoValue) {
+  StringRef T = "int f() { return 42; }\n";
+  StringRef S = "auto target = f();";
+  auto Cat = [](StringRef S) { return (T + S).str(); };
+
+  EXPECT_EQ(Cat("const auto target = f();"),
+runCheckOnCode(Cat(S)));
+  EXPECT_EQ(Cat("const auto target = f();"),
+runCheckOnCode(Cat(S)));
+
+  EXPECT_EQ(Cat("auto const target = f();"),
+runCheckOnCode(Cat(S)));
+  EXPECT_EQ(Cat("auto const target = f();"),
+runCheckOnCode(Cat(S)));
+}
+TEST(Values, AutoPointer) {
+  StringRef T = "int* f() { return nullptr; }\n";
+  StringRef S = "auto target = f();";
+  auto Cat = [](StringRef S) { return (T + S).str(); };
+
+  EXPECT_EQ(Cat("const auto target = f();"),
+  

[PATCH] D56532: [clang-tidy] Add the abseil-duration-conversion-cast check

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

LGTM!


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

https://reviews.llvm.org/D56532



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


[PATCH] D55447: [Sema] Fix Modified Type in address_space AttributedType

2019-01-17 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.

This LGTM, but you should wait a bit to see if @rsmith would like to weigh in. 
If you don't hear back by mid-next week, go ahead and commit.


Repository:
  rC Clang

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

https://reviews.llvm.org/D55447



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


[PATCH] D54945: This commit adds a chapter about clang-tidy integrations

2019-01-17 Thread Eugene Zelenko via Phabricator via cfe-commits
Eugene.Zelenko added a comment.

clang-tools-sphinx-docs bot is failing because of:

Warning, treated as error:
/home/buildbot/llvm-build-dir/clang-tools-sphinx-docs/llvm/src/tools/clang/tools/extra/docs/clang-tidy/Contributing.rst:61:
 ERROR: Unknown target name: "how to setup tooling for llvm".

Frankly I don't know what is proper way to handle cross-module documentation 
links.


Repository:
  rL LLVM

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

https://reviews.llvm.org/D54945



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


[PATCH] D54945: This commit adds a chapter about clang-tidy integrations

2019-01-17 Thread Phabricator via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rL351463: [Documentation] Add a chapter about Clang-tidy 
integrations. (authored by eugenezelenko, committed by ).
Herald added a subscriber: llvm-commits.

Changed prior to commit:
  https://reviews.llvm.org/D54945?vs=181528=182341#toc

Repository:
  rL LLVM

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

https://reviews.llvm.org/D54945

Files:
  clang-tools-extra/trunk/docs/clang-tidy/Contributing.rst
  clang-tools-extra/trunk/docs/clang-tidy/Integrations.rst
  clang-tools-extra/trunk/docs/clang-tidy/index.rst

Index: clang-tools-extra/trunk/docs/clang-tidy/index.rst
===
--- clang-tools-extra/trunk/docs/clang-tidy/index.rst
+++ clang-tools-extra/trunk/docs/clang-tidy/index.rst
@@ -10,6 +10,8 @@
:maxdepth: 1
 
The list of clang-tidy checks 
+   Clang-tidy IDE/Editor Integrations 
+   Getting Involved 
 
 :program:`clang-tidy` is a clang-based C++ "linter" tool. Its purpose is to
 provide an extensible framework for diagnosing and fixing typical programming
@@ -310,511 +312,3 @@
 
 .. _LibTooling: http://clang.llvm.org/docs/LibTooling.html
 .. _How To Setup Tooling For LLVM: http://clang.llvm.org/docs/HowToSetupToolingForLLVM.html
-
-
-Getting Involved
-
-
-:program:`clang-tidy` has several own checks and can run Clang static analyzer
-checks, but its power is in the ability to easily write custom checks.
-
-Checks are organized in modules, which can be linked into :program:`clang-tidy`
-with minimal or no code changes in :program:`clang-tidy`.
-
-Checks can plug into the analysis on the preprocessor level using `PPCallbacks`_
-or on the AST level using `AST Matchers`_. When an error is found, checks can
-report them in a way similar to how Clang diagnostics work. A fix-it hint can be
-attached to a diagnostic message.
-
-The interface provided by :program:`clang-tidy` makes it easy to write useful
-and precise checks in just a few lines of code. If you have an idea for a good
-check, the rest of this document explains how to do this.
-
-There are a few tools particularly useful when developing clang-tidy checks:
-  * ``add_new_check.py`` is a script to automate the process of adding a new
-check, it will create the check, update the CMake file and create a test;
-  * ``rename_check.py`` does what the script name suggests, renames an existing
-check;
-  * :program:`clang-query` is invaluable for interactive prototyping of AST
-matchers and exploration of the Clang AST;
-  * `clang-check`_ with the ``-ast-dump`` (and optionally ``-ast-dump-filter``)
-provides a convenient way to dump AST of a C++ program.
-
-If CMake is configured with ``CLANG_ENABLE_STATIC_ANALYZER``,
-:program:`clang-tidy` will not be built with support for the 
-``clang-analyzer-*`` checks or the ``mpi-*`` checks.
-
-
-.. _AST Matchers: http://clang.llvm.org/docs/LibASTMatchers.html
-.. _PPCallbacks: http://clang.llvm.org/doxygen/classclang_1_1PPCallbacks.html
-.. _clang-check: http://clang.llvm.org/docs/ClangCheck.html
-
-
-Choosing the Right Place for your Check

-
-If you have an idea of a check, you should decide whether it should be
-implemented as a:
-
-+ *Clang diagnostic*: if the check is generic enough, targets code patterns that
-  most probably are bugs (rather than style or readability issues), can be
-  implemented effectively and with extremely low false positive rate, it may
-  make a good Clang diagnostic.
-
-+ *Clang static analyzer check*: if the check requires some sort of control flow
-  analysis, it should probably be implemented as a static analyzer check.
-
-+ *clang-tidy check* is a good choice for linter-style checks, checks that are
-  related to a certain coding style, checks that address code readability, etc.
-
-
-Preparing your Workspace
-
-
-If you are new to LLVM development, you should read the `Getting Started with
-the LLVM System`_, `Using Clang Tools`_ and `How To Setup Tooling For LLVM`_
-documents to check out and build LLVM, Clang and Clang Extra Tools with CMake.
-
-Once you are done, change to the ``llvm/tools/clang/tools/extra`` directory, and
-let's start!
-
-.. _Getting Started with the LLVM System: http://llvm.org/docs/GettingStarted.html
-.. _Using Clang Tools: http://clang.llvm.org/docs/ClangTools.html
-
-
-The Directory Structure

-
-:program:`clang-tidy` source code resides in the
-``llvm/tools/clang/tools/extra`` directory and is structured as follows:
-
-::
-
-  clang-tidy/   # Clang-tidy core.
-  |-- ClangTidy.h   # Interfaces for users and checks.
-  |-- ClangTidyModule.h # Interface for clang-tidy modules.
-  |-- ClangTidyModuleRegistry.h # Interface for registering of modules.
- ...
-  |-- google/   # Google 

[clang-tools-extra] r351463 - [Documentation] Add a chapter about Clang-tidy integrations.

2019-01-17 Thread Eugene Zelenko via cfe-commits
Author: eugenezelenko
Date: Thu Jan 17 10:31:34 2019
New Revision: 351463

URL: http://llvm.org/viewvc/llvm-project?rev=351463=rev
Log:
[Documentation] Add a chapter about Clang-tidy integrations.

Patch by Marina Kalashina.

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

Added:
clang-tools-extra/trunk/docs/clang-tidy/Contributing.rst
clang-tools-extra/trunk/docs/clang-tidy/Integrations.rst
Modified:
clang-tools-extra/trunk/docs/clang-tidy/index.rst

Added: clang-tools-extra/trunk/docs/clang-tidy/Contributing.rst
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/docs/clang-tidy/Contributing.rst?rev=351463=auto
==
--- clang-tools-extra/trunk/docs/clang-tidy/Contributing.rst (added)
+++ clang-tools-extra/trunk/docs/clang-tidy/Contributing.rst Thu Jan 17 
10:31:34 2019
@@ -0,0 +1,507 @@
+
+Getting Involved
+
+
+:program:`clang-tidy` has several own checks and can run Clang static analyzer
+checks, but its power is in the ability to easily write custom checks.
+
+Checks are organized in modules, which can be linked into :program:`clang-tidy`
+with minimal or no code changes in :program:`clang-tidy`.
+
+Checks can plug into the analysis on the preprocessor level using 
`PPCallbacks`_
+or on the AST level using `AST Matchers`_. When an error is found, checks can
+report them in a way similar to how Clang diagnostics work. A fix-it hint can 
be
+attached to a diagnostic message.
+
+The interface provided by :program:`clang-tidy` makes it easy to write useful
+and precise checks in just a few lines of code. If you have an idea for a good
+check, the rest of this document explains how to do this.
+
+There are a few tools particularly useful when developing clang-tidy checks:
+  * ``add_new_check.py`` is a script to automate the process of adding a new
+check, it will create the check, update the CMake file and create a test;
+  * ``rename_check.py`` does what the script name suggests, renames an existing
+check;
+  * :program:`clang-query` is invaluable for interactive prototyping of AST
+matchers and exploration of the Clang AST;
+  * `clang-check`_ with the ``-ast-dump`` (and optionally ``-ast-dump-filter``)
+provides a convenient way to dump AST of a C++ program.
+
+If CMake is configured with ``CLANG_ENABLE_STATIC_ANALYZER``,
+:program:`clang-tidy` will not be built with support for the
+``clang-analyzer-*`` checks or the ``mpi-*`` checks.
+
+
+.. _AST Matchers: http://clang.llvm.org/docs/LibASTMatchers.html
+.. _PPCallbacks: http://clang.llvm.org/doxygen/classclang_1_1PPCallbacks.html
+.. _clang-check: http://clang.llvm.org/docs/ClangCheck.html
+
+
+Choosing the Right Place for your Check
+---
+
+If you have an idea of a check, you should decide whether it should be
+implemented as a:
+
++ *Clang diagnostic*: if the check is generic enough, targets code patterns 
that
+  most probably are bugs (rather than style or readability issues), can be
+  implemented effectively and with extremely low false positive rate, it may
+  make a good Clang diagnostic.
+
++ *Clang static analyzer check*: if the check requires some sort of control 
flow
+  analysis, it should probably be implemented as a static analyzer check.
+
++ *clang-tidy check* is a good choice for linter-style checks, checks that are
+  related to a certain coding style, checks that address code readability, etc.
+
+
+Preparing your Workspace
+
+
+If you are new to LLVM development, you should read the `Getting Started with
+the LLVM System`_, `Using Clang Tools`_ and `How To Setup Tooling For LLVM`_
+documents to check out and build LLVM, Clang and Clang Extra Tools with CMake.
+
+Once you are done, change to the ``llvm/tools/clang/tools/extra`` directory, 
and
+let's start!
+
+.. _Getting Started with the LLVM System: 
http://llvm.org/docs/GettingStarted.html
+.. _Using Clang Tools: http://clang.llvm.org/docs/ClangTools.html
+
+
+The Directory Structure
+---
+
+:program:`clang-tidy` source code resides in the
+``llvm/tools/clang/tools/extra`` directory and is structured as follows:
+
+::
+
+  clang-tidy/   # Clang-tidy core.
+  |-- ClangTidy.h   # Interfaces for users and checks.
+  |-- ClangTidyModule.h # Interface for clang-tidy modules.
+  |-- ClangTidyModuleRegistry.h # Interface for registering of modules.
+ ...
+  |-- google/   # Google clang-tidy module.
+  |-+
+|-- GoogleTidyModule.cpp
+|-- GoogleTidyModule.h
+  ...
+  |-- llvm/ # LLVM clang-tidy module.
+  |-+
+|-- LLVMTidyModule.cpp
+|-- LLVMTidyModule.h
+  ...
+  |-- objc/ # Objective-C clang-tidy module.
+  |-+
+|-- ObjCTidyModule.cpp
+|-- ObjCTidyModule.h
+  ...
+  |-- tool/   

[PATCH] D49754: Add -m(no-)spe, and e500 CPU definitions and support to clang

2019-01-17 Thread vit9696 via Phabricator via cfe-commits
vit9696 added a comment.

You are right, had to modify it like this to get the crash with FreeBSD triple:

  void f1(long double v, void *a)
  {
  }
  
  void f2(void* v, __builtin_va_list arg)
  {
f1(__builtin_va_arg(arg, long double), 0);
  }


Repository:
  rC Clang

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

https://reviews.llvm.org/D49754



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


[PATCH] D56802: [CodeGenObjC] Treat ivar offsets variables as constant if they refer to ivars of a direct subclass of NSObject with an @implementation

2019-01-17 Thread Phabricator via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rC351461: [CodeGenObjC] Use a constant value for non-fragile 
ivar offsets when possible (authored by epilk, committed by ).

Changed prior to commit:
  https://reviews.llvm.org/D56802?vs=182214=182336#toc

Repository:
  rC Clang

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

https://reviews.llvm.org/D56802

Files:
  lib/CodeGen/CGObjCMac.cpp
  test/CodeGenObjC/constant-non-fragile-ivar-offset.m
  test/CodeGenObjC/optimize-ivar-offset-load.m
  test/CodeGenObjC/reorder-synthesized-ivars.m

Index: lib/CodeGen/CGObjCMac.cpp
===
--- lib/CodeGen/CGObjCMac.cpp
+++ lib/CodeGen/CGObjCMac.cpp
@@ -1550,6 +1550,15 @@
 return false;
   }
 
+  bool isClassLayoutKnownStatically(const ObjCInterfaceDecl *ID) {
+// NSObject is a fixed size. If we can see the @implementation of a class
+// which inherits from NSObject then we know that all it's offsets also must
+// be fixed. FIXME: Can we do this if see a chain of super classes with
+// implementations leading to NSObject?
+return ID->getImplementation() && ID->getSuperClass() &&
+   ID->getSuperClass()->getName() == "NSObject";
+  }
+
 public:
   CGObjCNonFragileABIMac(CodeGen::CodeGenModule );
 
@@ -6702,6 +6711,12 @@
   IvarOffsetGV->setVisibility(llvm::GlobalValue::DefaultVisibility);
   }
 
+  // If ID's layout is known, then make the global constant. This serves as a
+  // useful assertion: we'll never use this variable to calculate ivar offsets,
+  // so if the runtime tries to patch it then we should crash.
+  if (isClassLayoutKnownStatically(ID))
+IvarOffsetGV->setConstant(true);
+
   if (CGM.getTriple().isOSBinFormatMachO())
 IvarOffsetGV->setSection("__DATA, __objc_ivar");
   return IvarOffsetGV;
@@ -6990,17 +7005,24 @@
   Offset);
 }
 
-llvm::Value *CGObjCNonFragileABIMac::EmitIvarOffset(
-  CodeGen::CodeGenFunction ,
-  const ObjCInterfaceDecl *Interface,
-  const ObjCIvarDecl *Ivar) {
-  llvm::Value *IvarOffsetValue = ObjCIvarOffsetVariable(Interface, Ivar);
-  IvarOffsetValue = CGF.Builder.CreateAlignedLoad(IvarOffsetValue,
-  CGF.getSizeAlign(), "ivar");
-  if (IsIvarOffsetKnownIdempotent(CGF, Ivar))
-cast(IvarOffsetValue)
-->setMetadata(CGM.getModule().getMDKindID("invariant.load"),
-  llvm::MDNode::get(VMContext, None));
+llvm::Value *
+CGObjCNonFragileABIMac::EmitIvarOffset(CodeGen::CodeGenFunction ,
+   const ObjCInterfaceDecl *Interface,
+   const ObjCIvarDecl *Ivar) {
+  llvm::Value *IvarOffsetValue;
+  if (isClassLayoutKnownStatically(Interface)) {
+IvarOffsetValue = llvm::ConstantInt::get(
+ObjCTypes.IvarOffsetVarTy,
+ComputeIvarBaseOffset(CGM, Interface->getImplementation(), Ivar));
+  } else {
+llvm::GlobalVariable *GV = ObjCIvarOffsetVariable(Interface, Ivar);
+IvarOffsetValue =
+CGF.Builder.CreateAlignedLoad(GV, CGF.getSizeAlign(), "ivar");
+if (IsIvarOffsetKnownIdempotent(CGF, Ivar))
+  cast(IvarOffsetValue)
+  ->setMetadata(CGM.getModule().getMDKindID("invariant.load"),
+llvm::MDNode::get(VMContext, None));
+  }
 
   // This could be 32bit int or 64bit integer depending on the architecture.
   // Cast it to 64bit integer value, if it is a 32bit integer ivar offset value
Index: test/CodeGenObjC/constant-non-fragile-ivar-offset.m
===
--- test/CodeGenObjC/constant-non-fragile-ivar-offset.m
+++ test/CodeGenObjC/constant-non-fragile-ivar-offset.m
@@ -0,0 +1,38 @@
+// RUN: %clang_cc1 -triple x86_64-apple-macosx10.14.0 -emit-llvm %s -o - | FileCheck %s
+
+// CHECK: @"OBJC_IVAR_$_StaticLayout.static_layout_ivar" = hidden constant i64 20
+// CHECK: @"OBJC_IVAR_$_NotStaticLayout.not_static_layout_ivar" = hidden global i64 12
+
+@interface NSObject {
+  int these, will, never, change, ever;
+}
+@end
+
+@interface StaticLayout : NSObject
+@end
+
+@implementation StaticLayout {
+  int static_layout_ivar;
+}
+-(void)meth {
+  static_layout_ivar = 0;
+  // CHECK-NOT: load i64, i64* @"OBJC_IVAR_$_StaticLayout
+}
+@end
+
+@interface NotNSObject {
+  int these, might, change;
+}
+@end
+
+@interface NotStaticLayout : NotNSObject
+@end
+
+@implementation NotStaticLayout {
+  int not_static_layout_ivar;
+}
+-(void)meth {
+  not_static_layout_ivar = 0;
+  // CHECK: load i64, i64* @"OBJC_IVAR_$_NotStaticLayout.not_static_layout_ivar
+}
+@end
Index: test/CodeGenObjC/optimize-ivar-offset-load.m
===
--- test/CodeGenObjC/optimize-ivar-offset-load.m
+++ test/CodeGenObjC/optimize-ivar-offset-load.m
@@ -1,17 +1,17 @@
 // RUN: %clang_cc1 -triple x86_64-apple-darwin10  -O0 

r351461 - [CodeGenObjC] Use a constant value for non-fragile ivar offsets when possible

2019-01-17 Thread Erik Pilkington via cfe-commits
Author: epilk
Date: Thu Jan 17 10:18:53 2019
New Revision: 351461

URL: http://llvm.org/viewvc/llvm-project?rev=351461=rev
Log:
[CodeGenObjC] Use a constant value for non-fragile ivar offsets when possible

If a class inherits from NSObject and has an implementation, then we
can assume that ivar offsets won't need to be updated by the runtime.
This allows us to index into the object using a constant value and
avoid loading from the ivar offset variable.

This patch was adapted from one written by Pete Cooper.

rdar://problem/10132568

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

Added:
cfe/trunk/test/CodeGenObjC/constant-non-fragile-ivar-offset.m
Modified:
cfe/trunk/lib/CodeGen/CGObjCMac.cpp
cfe/trunk/test/CodeGenObjC/optimize-ivar-offset-load.m
cfe/trunk/test/CodeGenObjC/reorder-synthesized-ivars.m

Modified: cfe/trunk/lib/CodeGen/CGObjCMac.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/CodeGen/CGObjCMac.cpp?rev=351461=351460=351461=diff
==
--- cfe/trunk/lib/CodeGen/CGObjCMac.cpp (original)
+++ cfe/trunk/lib/CodeGen/CGObjCMac.cpp Thu Jan 17 10:18:53 2019
@@ -1550,6 +1550,15 @@ private:
 return false;
   }
 
+  bool isClassLayoutKnownStatically(const ObjCInterfaceDecl *ID) {
+// NSObject is a fixed size. If we can see the @implementation of a class
+// which inherits from NSObject then we know that all it's offsets also 
must
+// be fixed. FIXME: Can we do this if see a chain of super classes with
+// implementations leading to NSObject?
+return ID->getImplementation() && ID->getSuperClass() &&
+   ID->getSuperClass()->getName() == "NSObject";
+  }
+
 public:
   CGObjCNonFragileABIMac(CodeGen::CodeGenModule );
 
@@ -6702,6 +6711,12 @@ CGObjCNonFragileABIMac::EmitIvarOffsetVa
   IvarOffsetGV->setVisibility(llvm::GlobalValue::DefaultVisibility);
   }
 
+  // If ID's layout is known, then make the global constant. This serves as a
+  // useful assertion: we'll never use this variable to calculate ivar offsets,
+  // so if the runtime tries to patch it then we should crash.
+  if (isClassLayoutKnownStatically(ID))
+IvarOffsetGV->setConstant(true);
+
   if (CGM.getTriple().isOSBinFormatMachO())
 IvarOffsetGV->setSection("__DATA, __objc_ivar");
   return IvarOffsetGV;
@@ -6990,17 +7005,24 @@ LValue CGObjCNonFragileABIMac::EmitObjCV
   Offset);
 }
 
-llvm::Value *CGObjCNonFragileABIMac::EmitIvarOffset(
-  CodeGen::CodeGenFunction ,
-  const ObjCInterfaceDecl *Interface,
-  const ObjCIvarDecl *Ivar) {
-  llvm::Value *IvarOffsetValue = ObjCIvarOffsetVariable(Interface, Ivar);
-  IvarOffsetValue = CGF.Builder.CreateAlignedLoad(IvarOffsetValue,
-  CGF.getSizeAlign(), "ivar");
-  if (IsIvarOffsetKnownIdempotent(CGF, Ivar))
-cast(IvarOffsetValue)
-->setMetadata(CGM.getModule().getMDKindID("invariant.load"),
-  llvm::MDNode::get(VMContext, None));
+llvm::Value *
+CGObjCNonFragileABIMac::EmitIvarOffset(CodeGen::CodeGenFunction ,
+   const ObjCInterfaceDecl *Interface,
+   const ObjCIvarDecl *Ivar) {
+  llvm::Value *IvarOffsetValue;
+  if (isClassLayoutKnownStatically(Interface)) {
+IvarOffsetValue = llvm::ConstantInt::get(
+ObjCTypes.IvarOffsetVarTy,
+ComputeIvarBaseOffset(CGM, Interface->getImplementation(), Ivar));
+  } else {
+llvm::GlobalVariable *GV = ObjCIvarOffsetVariable(Interface, Ivar);
+IvarOffsetValue =
+CGF.Builder.CreateAlignedLoad(GV, CGF.getSizeAlign(), "ivar");
+if (IsIvarOffsetKnownIdempotent(CGF, Ivar))
+  cast(IvarOffsetValue)
+  ->setMetadata(CGM.getModule().getMDKindID("invariant.load"),
+llvm::MDNode::get(VMContext, None));
+  }
 
   // This could be 32bit int or 64bit integer depending on the architecture.
   // Cast it to 64bit integer value, if it is a 32bit integer ivar offset value

Added: cfe/trunk/test/CodeGenObjC/constant-non-fragile-ivar-offset.m
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/CodeGenObjC/constant-non-fragile-ivar-offset.m?rev=351461=auto
==
--- cfe/trunk/test/CodeGenObjC/constant-non-fragile-ivar-offset.m (added)
+++ cfe/trunk/test/CodeGenObjC/constant-non-fragile-ivar-offset.m Thu Jan 17 
10:18:53 2019
@@ -0,0 +1,38 @@
+// RUN: %clang_cc1 -triple x86_64-apple-macosx10.14.0 -emit-llvm %s -o - | 
FileCheck %s
+
+// CHECK: @"OBJC_IVAR_$_StaticLayout.static_layout_ivar" = hidden constant i64 
20
+// CHECK: @"OBJC_IVAR_$_NotStaticLayout.not_static_layout_ivar" = hidden 
global i64 12
+
+@interface NSObject {
+  int these, will, never, change, ever;
+}
+@end
+
+@interface StaticLayout : NSObject
+@end
+
+@implementation StaticLayout {
+  int static_layout_ivar;
+}
+-(void)meth {
+ 

Re: r351459 - [ObjC] Follow-up r350768 and allow the use of unavailable methods that are

2019-01-17 Thread Alex L via cfe-commits
Hi Hans,

Could you please cherry-pick this change into the release branch?

Cheers,
Alex

On Thu, 17 Jan 2019 at 10:16, Alex Lorenz via cfe-commits <
cfe-commits@lists.llvm.org> wrote:

> Author: arphaman
> Date: Thu Jan 17 10:12:45 2019
> New Revision: 351459
>
> URL: http://llvm.org/viewvc/llvm-project?rev=351459=rev
> Log:
> [ObjC] Follow-up r350768 and allow the use of unavailable methods that are
> declared in a parent class from within the @implementation context
>
> This commit extends r350768 and allows the use of methods marked as
> unavailable
> that are declared in a parent class/category from within the
> @implementation of
> the class where the method is marked as unavailable.
> This allows users to call init that's marked as unavailable even if they
> don't
> define it.
>
> rdar://47134898
>
> Differential Revision: https://reviews.llvm.org/D56816
>
> Modified:
> cfe/trunk/lib/Sema/SemaDeclAttr.cpp
> cfe/trunk/test/SemaObjC/call-unavailable-init-in-self.m
> cfe/trunk/test/SemaObjC/infer-availability-from-init.m
>
> Modified: cfe/trunk/lib/Sema/SemaDeclAttr.cpp
> URL:
> http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Sema/SemaDeclAttr.cpp?rev=351459=351458=351459=diff
>
> ==
> --- cfe/trunk/lib/Sema/SemaDeclAttr.cpp (original)
> +++ cfe/trunk/lib/Sema/SemaDeclAttr.cpp Thu Jan 17 10:12:45 2019
> @@ -7365,13 +7365,11 @@ ShouldDiagnoseAvailabilityInContext(Sema
>  return true;
>  } else if (K == AR_Unavailable) {
>// It is perfectly fine to refer to an 'unavailable' Objective-C
> method
> -  // when it's actually defined and is referenced from within the
> -  // @implementation itself. In this context, we interpret
> unavailable as a
> -  // form of access control.
> +  // when it is referenced from within the @implementation itself. In
> this
> +  // context, we interpret unavailable as a form of access control.
>if (const auto *MD = dyn_cast(OffendingDecl)) {
>  if (const auto *Impl = dyn_cast(C)) {
> -  if (MD->getClassInterface() == Impl->getClassInterface() &&
> -  MD->isDefined())
> +  if (MD->getClassInterface() == Impl->getClassInterface())
>  return true;
>  }
>}
>
> Modified: cfe/trunk/test/SemaObjC/call-unavailable-init-in-self.m
> URL:
> http://llvm.org/viewvc/llvm-project/cfe/trunk/test/SemaObjC/call-unavailable-init-in-self.m?rev=351459=351458=351459=diff
>
> ==
> --- cfe/trunk/test/SemaObjC/call-unavailable-init-in-self.m (original)
> +++ cfe/trunk/test/SemaObjC/call-unavailable-init-in-self.m Thu Jan 17
> 10:12:45 2019
> @@ -5,13 +5,24 @@
>  + (instancetype)new;
>  + (instancetype)alloc;
>
> +- (void)declaredInSuper;
> +
> +@end
> +
> +@interface NSObject (Category)
> +
> +- (void)declaredInSuperCategory;
> +
>  @end
>
>  @interface Sub: NSObject
>
>  - (instancetype)init __attribute__((unavailable)); // expected-note 4
> {{'init' has been explicitly marked unavailable here}}
>
> -- (void)notImplemented __attribute__((unavailable)); // expected-note
> {{'notImplemented' has been explicitly marked unavailable here}}
> +- (void)notImplemented __attribute__((unavailable));
> +
> +- (void)declaredInSuper __attribute__((unavailable));
> +- (void)declaredInSuperCategory __attribute__((unavailable));
>
>  @end
>
> @@ -34,7 +45,14 @@
>  }
>
>  - (void)reportUseOfUnimplemented {
> -  [self notImplemented]; // expected-error {{'notImplemented' is
> unavailable}}
> +  [self notImplemented];
> +}
> +
> +- (void)allowSuperCallUsingSelf {
> +  [self declaredInSuper];
> +  [[Sub alloc] declaredInSuper];
> +  [self declaredInSuperCategory];
> +  [[Sub alloc] declaredInSuperCategory];
>  }
>
>  @end
>
> Modified: cfe/trunk/test/SemaObjC/infer-availability-from-init.m
> URL:
> http://llvm.org/viewvc/llvm-project/cfe/trunk/test/SemaObjC/infer-availability-from-init.m?rev=351459=351458=351459=diff
>
> ==
> --- cfe/trunk/test/SemaObjC/infer-availability-from-init.m (original)
> +++ cfe/trunk/test/SemaObjC/infer-availability-from-init.m Thu Jan 17
> 10:12:45 2019
> @@ -47,12 +47,12 @@ void usenotmyobject() {
>  }
>
>  @interface FromSelf : NSObject
> --(instancetype)init __attribute__((unavailable)); // expected-note
> {{'init' has been explicitly marked unavailable here}}
> +-(instancetype)init __attribute__((unavailable));
>  +(FromSelf*)another_one;
>  @end
>
>  @implementation FromSelf
>  +(FromSelf*)another_one {
> -  [self new]; // expected-error{{'new' is unavailable}}
> +  [self new];
>  }
>  @end
>
>
> ___
> cfe-commits mailing list
> cfe-commits@lists.llvm.org
> http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
>
___
cfe-commits mailing list

[PATCH] D35068: [analyzer] Detect usages of unsafe I/O functions

2019-01-17 Thread Kristóf Umann via Phabricator via cfe-commits
Szelethus requested changes to this revision.
Szelethus added a comment.
This revision now requires changes to proceed.

In D35068#811436 , @NoQ wrote:

> I wonder how noisy this check is - did you test it on large codebases? 
> Because these functions are popular, and in many cases it'd be fine to use 
> insecure functions, i wonder if it's worth it to have this check on by 
> default. Like, if it's relatively quiet - it's fine, but if it'd constitute 
> 90% of the analyzer's warnings on popular projects, that'd probably not be 
> fine.




In D35068#1049530 , @george.karpenkov 
wrote:

> @koldaniel Have you evaluated this checker? On which codebases? Were the 
> warnings real security issues, or were they mostly spurious? The code seems 
> fine, but I'm not sure whether it should be in `security` or in `alpha`.


Sorry, didn't read the discussion, there are some fair points in the quoted 
comments.

In D35068#1069880 , @koldaniel wrote:

> I've evaluated this checker on LLVM+Clang, there were only a few (about 15) 
> warnings,  because of the C11 flag check at the beginning of the checker 
> body. However, if this check was removed, number of the warnings would be 
> increased significantly. I wouldn't say the findings were real security 
> issues, most of the warnings were about usages of deprecated functions, which 
> has not been considered unsecure (but which may cause problems if the code is 
> modified in an improper way in the future).


My problem is that LLVM+Clang isn't really a C (neither a C11) project, and I 
think judging this checker on it is a little misleading. Could you please test 
it on some C11 projects? I think tmux uses C11.

In D35068#1361195 , @xazax.hun wrote:

> I think this is quiet coding guideline specific check which is useful for a 
> set of  security critical projects. As this is an opt in kind of check, I 
> think it does no harm to have it upstream.


I do generally agree with this statement, but I'd be more comfortable either 
landing it in alpha or seeing some other results.


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

https://reviews.llvm.org/D35068



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


r351459 - [ObjC] Follow-up r350768 and allow the use of unavailable methods that are

2019-01-17 Thread Alex Lorenz via cfe-commits
Author: arphaman
Date: Thu Jan 17 10:12:45 2019
New Revision: 351459

URL: http://llvm.org/viewvc/llvm-project?rev=351459=rev
Log:
[ObjC] Follow-up r350768 and allow the use of unavailable methods that are
declared in a parent class from within the @implementation context

This commit extends r350768 and allows the use of methods marked as unavailable
that are declared in a parent class/category from within the @implementation of
the class where the method is marked as unavailable.
This allows users to call init that's marked as unavailable even if they don't
define it.

rdar://47134898

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

Modified:
cfe/trunk/lib/Sema/SemaDeclAttr.cpp
cfe/trunk/test/SemaObjC/call-unavailable-init-in-self.m
cfe/trunk/test/SemaObjC/infer-availability-from-init.m

Modified: cfe/trunk/lib/Sema/SemaDeclAttr.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Sema/SemaDeclAttr.cpp?rev=351459=351458=351459=diff
==
--- cfe/trunk/lib/Sema/SemaDeclAttr.cpp (original)
+++ cfe/trunk/lib/Sema/SemaDeclAttr.cpp Thu Jan 17 10:12:45 2019
@@ -7365,13 +7365,11 @@ ShouldDiagnoseAvailabilityInContext(Sema
 return true;
 } else if (K == AR_Unavailable) {
   // It is perfectly fine to refer to an 'unavailable' Objective-C method
-  // when it's actually defined and is referenced from within the
-  // @implementation itself. In this context, we interpret unavailable as a
-  // form of access control.
+  // when it is referenced from within the @implementation itself. In this
+  // context, we interpret unavailable as a form of access control.
   if (const auto *MD = dyn_cast(OffendingDecl)) {
 if (const auto *Impl = dyn_cast(C)) {
-  if (MD->getClassInterface() == Impl->getClassInterface() &&
-  MD->isDefined())
+  if (MD->getClassInterface() == Impl->getClassInterface())
 return true;
 }
   }

Modified: cfe/trunk/test/SemaObjC/call-unavailable-init-in-self.m
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/SemaObjC/call-unavailable-init-in-self.m?rev=351459=351458=351459=diff
==
--- cfe/trunk/test/SemaObjC/call-unavailable-init-in-self.m (original)
+++ cfe/trunk/test/SemaObjC/call-unavailable-init-in-self.m Thu Jan 17 10:12:45 
2019
@@ -5,13 +5,24 @@
 + (instancetype)new;
 + (instancetype)alloc;
 
+- (void)declaredInSuper;
+
+@end
+
+@interface NSObject (Category)
+
+- (void)declaredInSuperCategory;
+
 @end
 
 @interface Sub: NSObject
 
 - (instancetype)init __attribute__((unavailable)); // expected-note 4 {{'init' 
has been explicitly marked unavailable here}}
 
-- (void)notImplemented __attribute__((unavailable)); // expected-note 
{{'notImplemented' has been explicitly marked unavailable here}}
+- (void)notImplemented __attribute__((unavailable));
+
+- (void)declaredInSuper __attribute__((unavailable));
+- (void)declaredInSuperCategory __attribute__((unavailable));
 
 @end
 
@@ -34,7 +45,14 @@
 }
 
 - (void)reportUseOfUnimplemented {
-  [self notImplemented]; // expected-error {{'notImplemented' is unavailable}}
+  [self notImplemented];
+}
+
+- (void)allowSuperCallUsingSelf {
+  [self declaredInSuper];
+  [[Sub alloc] declaredInSuper];
+  [self declaredInSuperCategory];
+  [[Sub alloc] declaredInSuperCategory];
 }
 
 @end

Modified: cfe/trunk/test/SemaObjC/infer-availability-from-init.m
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/SemaObjC/infer-availability-from-init.m?rev=351459=351458=351459=diff
==
--- cfe/trunk/test/SemaObjC/infer-availability-from-init.m (original)
+++ cfe/trunk/test/SemaObjC/infer-availability-from-init.m Thu Jan 17 10:12:45 
2019
@@ -47,12 +47,12 @@ void usenotmyobject() {
 }
 
 @interface FromSelf : NSObject
--(instancetype)init __attribute__((unavailable)); // expected-note {{'init' 
has been explicitly marked unavailable here}}
+-(instancetype)init __attribute__((unavailable));
 +(FromSelf*)another_one;
 @end
 
 @implementation FromSelf
 +(FromSelf*)another_one {
-  [self new]; // expected-error{{'new' is unavailable}}
+  [self new];
 }
 @end


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


[PATCH] D56816: [ObjC] Follow-up r350768 and allow the use of unavailable methods that are declared in a parent class from within the @implementation context

2019-01-17 Thread Alex Lorenz via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rC351459: [ObjC] Follow-up r350768 and allow the use of 
unavailable methods that are (authored by arphaman, committed by ).

Changed prior to commit:
  https://reviews.llvm.org/D56816?vs=182191=182334#toc

Repository:
  rC Clang

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

https://reviews.llvm.org/D56816

Files:
  lib/Sema/SemaDeclAttr.cpp
  test/SemaObjC/call-unavailable-init-in-self.m
  test/SemaObjC/infer-availability-from-init.m


Index: test/SemaObjC/infer-availability-from-init.m
===
--- test/SemaObjC/infer-availability-from-init.m
+++ test/SemaObjC/infer-availability-from-init.m
@@ -47,12 +47,12 @@
 }
 
 @interface FromSelf : NSObject
--(instancetype)init __attribute__((unavailable)); // expected-note {{'init' 
has been explicitly marked unavailable here}}
+-(instancetype)init __attribute__((unavailable));
 +(FromSelf*)another_one;
 @end
 
 @implementation FromSelf
 +(FromSelf*)another_one {
-  [self new]; // expected-error{{'new' is unavailable}}
+  [self new];
 }
 @end
Index: test/SemaObjC/call-unavailable-init-in-self.m
===
--- test/SemaObjC/call-unavailable-init-in-self.m
+++ test/SemaObjC/call-unavailable-init-in-self.m
@@ -5,13 +5,24 @@
 + (instancetype)new;
 + (instancetype)alloc;
 
+- (void)declaredInSuper;
+
+@end
+
+@interface NSObject (Category)
+
+- (void)declaredInSuperCategory;
+
 @end
 
 @interface Sub: NSObject
 
 - (instancetype)init __attribute__((unavailable)); // expected-note 4 {{'init' 
has been explicitly marked unavailable here}}
 
-- (void)notImplemented __attribute__((unavailable)); // expected-note 
{{'notImplemented' has been explicitly marked unavailable here}}
+- (void)notImplemented __attribute__((unavailable));
+
+- (void)declaredInSuper __attribute__((unavailable));
+- (void)declaredInSuperCategory __attribute__((unavailable));
 
 @end
 
@@ -34,7 +45,14 @@
 }
 
 - (void)reportUseOfUnimplemented {
-  [self notImplemented]; // expected-error {{'notImplemented' is unavailable}}
+  [self notImplemented];
+}
+
+- (void)allowSuperCallUsingSelf {
+  [self declaredInSuper];
+  [[Sub alloc] declaredInSuper];
+  [self declaredInSuperCategory];
+  [[Sub alloc] declaredInSuperCategory];
 }
 
 @end
Index: lib/Sema/SemaDeclAttr.cpp
===
--- lib/Sema/SemaDeclAttr.cpp
+++ lib/Sema/SemaDeclAttr.cpp
@@ -7365,13 +7365,11 @@
 return true;
 } else if (K == AR_Unavailable) {
   // It is perfectly fine to refer to an 'unavailable' Objective-C method
-  // when it's actually defined and is referenced from within the
-  // @implementation itself. In this context, we interpret unavailable as a
-  // form of access control.
+  // when it is referenced from within the @implementation itself. In this
+  // context, we interpret unavailable as a form of access control.
   if (const auto *MD = dyn_cast(OffendingDecl)) {
 if (const auto *Impl = dyn_cast(C)) {
-  if (MD->getClassInterface() == Impl->getClassInterface() &&
-  MD->isDefined())
+  if (MD->getClassInterface() == Impl->getClassInterface())
 return true;
 }
   }


Index: test/SemaObjC/infer-availability-from-init.m
===
--- test/SemaObjC/infer-availability-from-init.m
+++ test/SemaObjC/infer-availability-from-init.m
@@ -47,12 +47,12 @@
 }
 
 @interface FromSelf : NSObject
--(instancetype)init __attribute__((unavailable)); // expected-note {{'init' has been explicitly marked unavailable here}}
+-(instancetype)init __attribute__((unavailable));
 +(FromSelf*)another_one;
 @end
 
 @implementation FromSelf
 +(FromSelf*)another_one {
-  [self new]; // expected-error{{'new' is unavailable}}
+  [self new];
 }
 @end
Index: test/SemaObjC/call-unavailable-init-in-self.m
===
--- test/SemaObjC/call-unavailable-init-in-self.m
+++ test/SemaObjC/call-unavailable-init-in-self.m
@@ -5,13 +5,24 @@
 + (instancetype)new;
 + (instancetype)alloc;
 
+- (void)declaredInSuper;
+
+@end
+
+@interface NSObject (Category)
+
+- (void)declaredInSuperCategory;
+
 @end
 
 @interface Sub: NSObject
 
 - (instancetype)init __attribute__((unavailable)); // expected-note 4 {{'init' has been explicitly marked unavailable here}}
 
-- (void)notImplemented __attribute__((unavailable)); // expected-note {{'notImplemented' has been explicitly marked unavailable here}}
+- (void)notImplemented __attribute__((unavailable));
+
+- (void)declaredInSuper __attribute__((unavailable));
+- (void)declaredInSuperCategory __attribute__((unavailable));
 
 @end
 
@@ -34,7 +45,14 @@
 }
 
 - (void)reportUseOfUnimplemented {
-  [self notImplemented]; // expected-error 

[PATCH] D49754: Add -m(no-)spe, and e500 CPU definitions and support to clang

2019-01-17 Thread Justin Hibbits via Phabricator via cfe-commits
jhibbits added a comment.

Hi @vit9696 it does crash with the linux target (powerpc-gnu-linux), but is 
fine with powerpc-gnu-freebsd.


Repository:
  rC Clang

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

https://reviews.llvm.org/D49754



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


[PATCH] D49754: Add -m(no-)spe, and e500 CPU definitions and support to clang

2019-01-17 Thread vit9696 via Phabricator via cfe-commits
vit9696 added a comment.

Actually I am not sure about Linux, since this is bare metal, and I just used 
what fited. However, it does not look like 128-bit or 64-bit long doubles are 
related.
I retried to compile the test case with powerpc-gnu-freebsd target (and even 
made a compile-time assertion to ensure that long double is now 64-bit), yet it 
still crashed in a similar way.
Might it be another LLVM 7 vs LLVM 8 difference? Does it crash for you with 
Linux target?


Repository:
  rC Clang

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

https://reviews.llvm.org/D49754



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


[PATCH] D35068: [analyzer] Detect usages of unsafe I/O functions

2019-01-17 Thread Kristóf Umann via Phabricator via cfe-commits
Szelethus added inline comments.



Comment at: test/Analysis/security-syntax-checks.m:253
+  FILE *file;
+  sprintf(buf, "a"); // expected-warning{{Call to function 'sprintf' is 
insecure as it does not provide security checks introduced in the C11 standard. 
Replace with analogous functions that support length arguments or provides 
boundary checks such as 'sprintf_s' in case of C11}}
+  scanf("%d", ); // expected-warning{{Call to function 'scanf' is insecure 
as it does not provide security checks introduced in the C11 standard. Replace 
with analogous functions that support length arguments or provides boundary 
checks such as 'scanf_s' in case of C11}}

Szelethus wrote:
> When using `{{}}`, you actually supply a regex as an argument, and the output 
> of the analyzer is matched against it. My point is, could you instead just 
> write
> ```
> // expected-warning{{Call to function 'sprintf' is insecure}}
> ```
> to improve readability?
Or whatever the shortest string is needed to know whether the expected output 
it there.


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

https://reviews.llvm.org/D35068



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


[PATCH] D35068: [analyzer] Detect usages of unsafe I/O functions

2019-01-17 Thread Kristóf Umann via Phabricator via cfe-commits
Szelethus accepted this revision.
Szelethus added a comment.

Overall I think this looks great, thanks! I left some inlines that would be 
nice to fix before commiting, but all of them are minor nits.

Would it be possible for you to commit the clang-formatting and the actual 
logic separately?




Comment at: include/clang/StaticAnalyzer/Checkers/Checkers.td:393
+  def DeprecatedOrUnsafeBufferHandling : 
Checker<"DeprecatedOrUnsafeBufferHandling">,
+HelpText<"Warn on uses of unsecure or deprecated buffer manipulating 
functions">,
+DescFile<"CheckSecuritySyntaxOnly.cpp">;

Lately we started paying attention to the 80 column limit in `Checkers.td`. 
Could you please break this line?



Comment at: lib/StaticAnalyzer/Checkers/CheckSecuritySyntaxOnly.cpp:583
+// Use of 'sprintf', 'vsprintf', 'scanf', 'wscanf',
+//'fscanf',
+//'fwscanf', 'vscanf', 'vwscanf', 'vfscanf', 'vfwscanf', 'sscanf',

This is out of place.



Comment at: lib/StaticAnalyzer/Checkers/CheckSecuritySyntaxOnly.cpp:591
+//===--===//
+void WalkAST::checkDeprecatedOrUnsafeBufferHandling(const CallExpr *CE,
+const FunctionDecl *FD) {

Could you please add an extra newline?



Comment at: lib/StaticAnalyzer/Checkers/CheckSecuritySyntaxOnly.cpp:598
 
//===--===//
-
 void WalkAST::checkCall_rand(const CallExpr *CE, const FunctionDecl *FD) {

I think this newline should stay.



Comment at: lib/StaticAnalyzer/Checkers/CheckSecuritySyntaxOnly.cpp:603-610
+  int ArgIndex =
+  llvm::StringSwitch(Name)
+  .Cases("scanf", "wscanf", "vscanf", "vwscanf", 0)
+  .Cases("sprintf", "vsprintf", "fscanf", "fwscanf", "vfscanf",
+ "vfwscanf", "sscanf", "swscanf", "vsscanf", "vswscanf", 1)
+  .Cases("swprintf", "snprintf", "vswprintf", "vsnprintf", "memcpy",
+ "memmove", "memset", "strncpy", "strncat", DEPR_ONLY)

I wonder whether using `CallDescription` would be (way) more efficient here. 
Comparing `IndentifierInfo`s would also be better I guess.

I'm a little unsure about performance implications here, it might not be worth 
the chore to refactor this.



Comment at: lib/StaticAnalyzer/Checkers/CheckSecuritySyntaxOnly.cpp:627-630
+  SmallString<128> buf1;
+  SmallString<512> buf2;
+  llvm::raw_svector_ostream out1(buf1);
+  llvm::raw_svector_ostream out2(buf2);

Could you please start these variable names with a capital letter?



Comment at: test/Analysis/security-syntax-checks.m:253
+  FILE *file;
+  sprintf(buf, "a"); // expected-warning{{Call to function 'sprintf' is 
insecure as it does not provide security checks introduced in the C11 standard. 
Replace with analogous functions that support length arguments or provides 
boundary checks such as 'sprintf_s' in case of C11}}
+  scanf("%d", ); // expected-warning{{Call to function 'scanf' is insecure 
as it does not provide security checks introduced in the C11 standard. Replace 
with analogous functions that support length arguments or provides boundary 
checks such as 'scanf_s' in case of C11}}

When using `{{}}`, you actually supply a regex as an argument, and the output 
of the analyzer is matched against it. My point is, could you instead just write
```
// expected-warning{{Call to function 'sprintf' is insecure}}
```
to improve readability?


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

https://reviews.llvm.org/D35068



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


[PATCH] D49754: Add -m(no-)spe, and e500 CPU definitions and support to clang

2019-01-17 Thread Justin Hibbits via Phabricator via cfe-commits
jhibbits added a comment.

Hi @vit9696 ,

This looks to be caused by using 128-bit long double on the platform.  Does 
linux really use 128-bit long doubles on ppc32?  FreeBSD uses 64-bit long 
double, so compiling that with '-target powerpc-gnu-freebsd' works fine.  I'm 
not sure how to handle the 128-bit values.


Repository:
  rC Clang

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

https://reviews.llvm.org/D49754



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


[PATCH] D56818: TLS: Respect visibility for thread_local variables on Darwin (PR40327)

2019-01-17 Thread Vlad Tsyrklevich via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rC351457: TLS: Respect visibility for thread_local variables 
on Darwin (PR40327) (authored by vlad.tsyrklevich, committed by ).
Herald added a subscriber: cfe-commits.

Changed prior to commit:
  https://reviews.llvm.org/D56818?vs=182171=182327#toc

Repository:
  rC Clang

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

https://reviews.llvm.org/D56818

Files:
  lib/CodeGen/ItaniumCXXABI.cpp
  test/CodeGenCXX/cxx11-thread-local-visibility.cpp
  test/CodeGenCXX/cxx11-thread-local.cpp


Index: lib/CodeGen/ItaniumCXXABI.cpp
===
--- lib/CodeGen/ItaniumCXXABI.cpp
+++ lib/CodeGen/ItaniumCXXABI.cpp
@@ -2463,10 +2463,12 @@
 CGM.SetLLVMFunctionAttributesForDefinition(nullptr, Wrapper);
 
   // Always resolve references to the wrapper at link time.
-  if (!Wrapper->hasLocalLinkage() && !(isThreadWrapperReplaceable(VD, CGM) &&
-  !llvm::GlobalVariable::isLinkOnceLinkage(Wrapper->getLinkage()) &&
-  !llvm::GlobalVariable::isWeakODRLinkage(Wrapper->getLinkage(
-Wrapper->setVisibility(llvm::GlobalValue::HiddenVisibility);
+  if (!Wrapper->hasLocalLinkage())
+if (!isThreadWrapperReplaceable(VD, CGM) ||
+llvm::GlobalVariable::isLinkOnceLinkage(Wrapper->getLinkage()) ||
+llvm::GlobalVariable::isWeakODRLinkage(Wrapper->getLinkage()) ||
+VD->getVisibility() == HiddenVisibility)
+  Wrapper->setVisibility(llvm::GlobalValue::HiddenVisibility);
 
   if (isThreadWrapperReplaceable(VD, CGM)) {
 Wrapper->setCallingConv(llvm::CallingConv::CXX_FAST_TLS);
Index: test/CodeGenCXX/cxx11-thread-local.cpp
===
--- test/CodeGenCXX/cxx11-thread-local.cpp
+++ test/CodeGenCXX/cxx11-thread-local.cpp
@@ -318,7 +318,7 @@
 // CHECK-NOT: call void @[[V_M_INIT]]()
 
 
-// LIUNX: define weak_odr hidden i32* @_ZTW1a() {
+// LINUX: define weak_odr hidden i32* @_ZTW1a()
 // DARWIN: define cxx_fast_tlscc i32* @_ZTW1a()
 // LINUX:   call void @_ZTH1a()
 // DARWIN: call cxx_fast_tlscc void @_ZTH1a()
Index: test/CodeGenCXX/cxx11-thread-local-visibility.cpp
===
--- test/CodeGenCXX/cxx11-thread-local-visibility.cpp
+++ test/CodeGenCXX/cxx11-thread-local-visibility.cpp
@@ -0,0 +1,17 @@
+// RUN: %clang_cc1 -std=c++11 -emit-llvm %s -o - -triple x86_64-linux-gnu | 
FileCheck --check-prefix=LINUX %s
+// RUN: %clang_cc1 -std=c++11 -emit-llvm %s -o - -triple x86_64-apple-darwin12 
| FileCheck --check-prefix=DARWIN %s
+
+// Regression test for PR40327
+
+// LINUX: @default_tls = thread_local global i32
+// LINUX: @hidden_tls = hidden thread_local global i32
+// LINUX: define weak_odr hidden i32* @_ZTW11default_tls()
+// LINUX: define weak_odr hidden i32* @_ZTW10hidden_tls()
+//
+// DARWIN: @default_tls = internal thread_local global i32
+// DARWIN: @hidden_tls = internal thread_local global i32
+// DARWIN: define cxx_fast_tlscc i32* @_ZTW11default_tls()
+// DARWIN: define hidden cxx_fast_tlscc i32* @_ZTW10hidden_tls()
+
+__attribute__((visibility("default"))) thread_local int default_tls;
+__attribute__((visibility("hidden"))) thread_local int hidden_tls;


Index: lib/CodeGen/ItaniumCXXABI.cpp
===
--- lib/CodeGen/ItaniumCXXABI.cpp
+++ lib/CodeGen/ItaniumCXXABI.cpp
@@ -2463,10 +2463,12 @@
 CGM.SetLLVMFunctionAttributesForDefinition(nullptr, Wrapper);
 
   // Always resolve references to the wrapper at link time.
-  if (!Wrapper->hasLocalLinkage() && !(isThreadWrapperReplaceable(VD, CGM) &&
-  !llvm::GlobalVariable::isLinkOnceLinkage(Wrapper->getLinkage()) &&
-  !llvm::GlobalVariable::isWeakODRLinkage(Wrapper->getLinkage(
-Wrapper->setVisibility(llvm::GlobalValue::HiddenVisibility);
+  if (!Wrapper->hasLocalLinkage())
+if (!isThreadWrapperReplaceable(VD, CGM) ||
+llvm::GlobalVariable::isLinkOnceLinkage(Wrapper->getLinkage()) ||
+llvm::GlobalVariable::isWeakODRLinkage(Wrapper->getLinkage()) ||
+VD->getVisibility() == HiddenVisibility)
+  Wrapper->setVisibility(llvm::GlobalValue::HiddenVisibility);
 
   if (isThreadWrapperReplaceable(VD, CGM)) {
 Wrapper->setCallingConv(llvm::CallingConv::CXX_FAST_TLS);
Index: test/CodeGenCXX/cxx11-thread-local.cpp
===
--- test/CodeGenCXX/cxx11-thread-local.cpp
+++ test/CodeGenCXX/cxx11-thread-local.cpp
@@ -318,7 +318,7 @@
 // CHECK-NOT: call void @[[V_M_INIT]]()
 
 
-// LIUNX: define weak_odr hidden i32* @_ZTW1a() {
+// LINUX: define weak_odr hidden i32* @_ZTW1a()
 // DARWIN: define cxx_fast_tlscc i32* @_ZTW1a()
 // LINUX:   call void @_ZTH1a()
 // DARWIN: call cxx_fast_tlscc void @_ZTH1a()
Index: test/CodeGenCXX/cxx11-thread-local-visibility.cpp

r351457 - TLS: Respect visibility for thread_local variables on Darwin (PR40327)

2019-01-17 Thread Vlad Tsyrklevich via cfe-commits
Author: vlad.tsyrklevich
Date: Thu Jan 17 09:53:45 2019
New Revision: 351457

URL: http://llvm.org/viewvc/llvm-project?rev=351457=rev
Log:
TLS: Respect visibility for thread_local variables on Darwin (PR40327)

Summary:
Teach clang to mark thread wrappers for thread_local variables with
hidden visibility when the original variable is marked with hidden
visibility. This is necessary on Darwin which exposes the thread wrapper
instead of the thread variable. The thread wrapper would previously
always be created with default visibility unless it had
linkonce*/weak_odr linkage.

Reviewers: rjmccall

Reviewed By: rjmccall

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

Added:
cfe/trunk/test/CodeGenCXX/cxx11-thread-local-visibility.cpp
Modified:
cfe/trunk/lib/CodeGen/ItaniumCXXABI.cpp
cfe/trunk/test/CodeGenCXX/cxx11-thread-local.cpp

Modified: cfe/trunk/lib/CodeGen/ItaniumCXXABI.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/CodeGen/ItaniumCXXABI.cpp?rev=351457=351456=351457=diff
==
--- cfe/trunk/lib/CodeGen/ItaniumCXXABI.cpp (original)
+++ cfe/trunk/lib/CodeGen/ItaniumCXXABI.cpp Thu Jan 17 09:53:45 2019
@@ -2463,10 +2463,12 @@ ItaniumCXXABI::getOrCreateThreadLocalWra
 CGM.SetLLVMFunctionAttributesForDefinition(nullptr, Wrapper);
 
   // Always resolve references to the wrapper at link time.
-  if (!Wrapper->hasLocalLinkage() && !(isThreadWrapperReplaceable(VD, CGM) &&
-  !llvm::GlobalVariable::isLinkOnceLinkage(Wrapper->getLinkage()) &&
-  !llvm::GlobalVariable::isWeakODRLinkage(Wrapper->getLinkage(
-Wrapper->setVisibility(llvm::GlobalValue::HiddenVisibility);
+  if (!Wrapper->hasLocalLinkage())
+if (!isThreadWrapperReplaceable(VD, CGM) ||
+llvm::GlobalVariable::isLinkOnceLinkage(Wrapper->getLinkage()) ||
+llvm::GlobalVariable::isWeakODRLinkage(Wrapper->getLinkage()) ||
+VD->getVisibility() == HiddenVisibility)
+  Wrapper->setVisibility(llvm::GlobalValue::HiddenVisibility);
 
   if (isThreadWrapperReplaceable(VD, CGM)) {
 Wrapper->setCallingConv(llvm::CallingConv::CXX_FAST_TLS);

Added: cfe/trunk/test/CodeGenCXX/cxx11-thread-local-visibility.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/CodeGenCXX/cxx11-thread-local-visibility.cpp?rev=351457=auto
==
--- cfe/trunk/test/CodeGenCXX/cxx11-thread-local-visibility.cpp (added)
+++ cfe/trunk/test/CodeGenCXX/cxx11-thread-local-visibility.cpp Thu Jan 17 
09:53:45 2019
@@ -0,0 +1,17 @@
+// RUN: %clang_cc1 -std=c++11 -emit-llvm %s -o - -triple x86_64-linux-gnu | 
FileCheck --check-prefix=LINUX %s
+// RUN: %clang_cc1 -std=c++11 -emit-llvm %s -o - -triple x86_64-apple-darwin12 
| FileCheck --check-prefix=DARWIN %s
+
+// Regression test for PR40327
+
+// LINUX: @default_tls = thread_local global i32
+// LINUX: @hidden_tls = hidden thread_local global i32
+// LINUX: define weak_odr hidden i32* @_ZTW11default_tls()
+// LINUX: define weak_odr hidden i32* @_ZTW10hidden_tls()
+//
+// DARWIN: @default_tls = internal thread_local global i32
+// DARWIN: @hidden_tls = internal thread_local global i32
+// DARWIN: define cxx_fast_tlscc i32* @_ZTW11default_tls()
+// DARWIN: define hidden cxx_fast_tlscc i32* @_ZTW10hidden_tls()
+
+__attribute__((visibility("default"))) thread_local int default_tls;
+__attribute__((visibility("hidden"))) thread_local int hidden_tls;

Modified: cfe/trunk/test/CodeGenCXX/cxx11-thread-local.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/CodeGenCXX/cxx11-thread-local.cpp?rev=351457=351456=351457=diff
==
--- cfe/trunk/test/CodeGenCXX/cxx11-thread-local.cpp (original)
+++ cfe/trunk/test/CodeGenCXX/cxx11-thread-local.cpp Thu Jan 17 09:53:45 2019
@@ -318,7 +318,7 @@ void set_anon_i() {
 // CHECK-NOT: call void @[[V_M_INIT]]()
 
 
-// LIUNX: define weak_odr hidden i32* @_ZTW1a() {
+// LINUX: define weak_odr hidden i32* @_ZTW1a()
 // DARWIN: define cxx_fast_tlscc i32* @_ZTW1a()
 // LINUX:   call void @_ZTH1a()
 // DARWIN: call cxx_fast_tlscc void @_ZTH1a()


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


[PATCH] D53153: [OpenCL] Mark kernel functions with default visibility

2019-01-17 Thread Scott Linder via Phabricator via cfe-commits
scott.linder added a comment.

I think we need the option to be in the driver, not just -cc1. We are moving 
towards the clang driver being the authority on how we do offline compilation 
for AMDGPU, and hiding this in cc1 doesn't help us.

I also don't think this is unreasonable to expose in general. As you note the 
behavior of `-fvisibility` wrt. declarations is just a practical measure, and 
even in the world of e.g. x86 it seems like there are cases where the option is 
useful.


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

https://reviews.llvm.org/D53153



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


[PATCH] D56267: [clangd] Interfaces for writing code actions

2019-01-17 Thread Ilya Biryukov via Phabricator via cfe-commits
ilya-biryukov added a comment.

This should be ready for another round of review. Let me know if I missed any 
of the older comments.
There are two more things that I'd like to do before this lands:

- go through the docs again and update/simplify them to make sure they're in 
sync with the new interface,
- publish the tests I have, they're not 100% ready yet, so I'm keeping the, 
local for now. This could be a separate change, though I don't think this 
should matter much if the rest is dealt with.


Repository:
  rCTE Clang Tools Extra

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

https://reviews.llvm.org/D56267



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


[PATCH] D53928: Enable builtins necessary for SLEEF [AArch64] vectorized trigonometry libm functions

2019-01-17 Thread Hal Finkel via Phabricator via cfe-commits
hfinkel accepted this revision.
hfinkel added a comment.
This revision is now accepted and ready to land.

LGTM

Please, in the future, make sure you post full-context patches.


Repository:
  rC Clang

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

https://reviews.llvm.org/D53928



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


[PATCH] D56856: [tooling] Add a new argument adjuster for deleting plugin related command line args

2019-01-17 Thread Ilya Biryukov via Phabricator via cfe-commits
ilya-biryukov accepted this revision.
ilya-biryukov added a comment.
This revision is now accepted and ready to land.

LGTM after the nits are fixed


Repository:
  rC Clang

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

https://reviews.llvm.org/D56856



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


[PATCH] D56267: [clangd] Interfaces for writing code actions

2019-01-17 Thread Ilya Biryukov via Phabricator via cfe-commits
ilya-biryukov added inline comments.



Comment at: clangd/ClangdLSPServer.cpp:346
+  {ExecuteCommandParams::CLANGD_APPLY_FIX_COMMAND,
+   ExecuteCommandParams::CLANGD_APPLY_CODE_ACTION}},
  }},

sammccall wrote:
> Seems a bit more direct to give each one its own command name? Maybe under a 
> namespace like refactor/swapIfBranches
I'm not sure what we're winning here.

Currently we have: `command:{ name: "applyCodeAction", args: 
["swap-if-branches", "…"] }`
In the proposed approach we'd have: `command: { name: "swap-if-branches", args: 
[…] }`

The latter would definitely mean more fiddling at least to communicate the list 
of supported actions. Both approaches don't seem to require any changes on the 
client side, even though they affect the messages we send over the protocol.



Comment at: clangd/ClangdLSPServer.cpp:662
+std::vector Actions = std::move(FixIts);
+auto toCodeAction = [&](PreparedAction &) -> CodeAction {
+  CodeAction CA;

sammccall wrote:
> This seems like it could just be a helper function... what does it capture?
> I think it might belong next to PreparedActions just like we have 
> `toLSPDiags` in `Diag.h` - it's not ideal dependency-wise, but inlining 
> everything into ClangdLSPServer seems dubious too. Happy to discuss offline...
I've moved it into a helper function, moved away from using a lambda.
However, kept it in `ClangdLSPServer.cpp`, `Diag.h` does feel like the wrong 
place for it, it would be nice to find a better place for both functions.



Comment at: clangd/refactor/Tweak.cpp:62
+  }
+  // Ensure deterministic order of the results.
+  llvm::sort(Available,

sammccall wrote:
> (nit: I'd make this `operator<` of `Tweak`? e.g. if priority is added, it 
> should be private)
My personal preference would be to keep it in .cpp file to avoid complicating 
the public interface with a function and a friend declaration for 
`prepareTweaks` (let me know if I misinterpreted your proposal).
Let me know if you have strong preference wrt to this one



Comment at: clangd/refactor/Tweak.h:78
+/// Contains all actions supported by clangd.
+typedef llvm::Registry TweakRegistry;
+

sammccall wrote:
> nit: can we move this to the cpp file and out of the public interface?
> (or keep the registry public, but drop prepareTweak[s] and just make callers 
> do it)
Done.
I don't think that makes a big difference, though: hiding the typedef would 
hide the fact we're using the `Registry`, though. We still have 
`REGISTER_TWEAK` that mentions it in the public interface.


Repository:
  rCTE Clang Tools Extra

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

https://reviews.llvm.org/D56267



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


[PATCH] D56611: [clangd] A code action to swap branches of an if statement

2019-01-17 Thread Ilya Biryukov via Phabricator via cfe-commits
ilya-biryukov updated this revision to Diff 182321.
ilya-biryukov added a comment.

- Remove the header file


Repository:
  rCTE Clang Tools Extra

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

https://reviews.llvm.org/D56611

Files:
  clangd/refactor/tweaks/CMakeLists.txt
  clangd/refactor/tweaks/SwapIfBranches.cpp

Index: clangd/refactor/tweaks/SwapIfBranches.cpp
===
--- /dev/null
+++ clangd/refactor/tweaks/SwapIfBranches.cpp
@@ -0,0 +1,119 @@
+//===--- SwapIfBranches.cpp --*- C++-*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===--===//
+#include "ClangdUnit.h"
+#include "Logger.h"
+#include "SourceCode.h"
+#include "refactor/Tweak.h"
+#include "clang/AST/ASTContext.h"
+#include "clang/AST/RecursiveASTVisitor.h"
+#include "clang/AST/Stmt.h"
+#include "clang/Basic/LangOptions.h"
+#include "clang/Basic/SourceLocation.h"
+#include "clang/Basic/SourceManager.h"
+#include "clang/Lex/Lexer.h"
+#include "clang/Tooling/Core/Replacement.h"
+#include "llvm/ADT/None.h"
+#include "llvm/ADT/Optional.h"
+#include "llvm/ADT/StringRef.h"
+#include "llvm/Support/Casting.h"
+#include "llvm/Support/Error.h"
+
+namespace clang {
+namespace clangd {
+namespace {
+/// Swaps the 'then' and 'else' branch of the if statement.
+/// Before:
+///   if (foo) { return 10; } else { continue; }
+/// After:
+///   if (foo) { continue; } else { return 10; }
+class SwapIfBranches : public Tweak {
+public:
+  TweakID id() const override {
+return llvm::StringLiteral("swap-if-branches");
+  }
+
+  bool prepare(const Selection ) override;
+  Expected apply(const Selection ) override;
+  std::string title() const override;
+
+private:
+  tooling::Replacements Result;
+};
+REGISTER_TWEAK(SwapIfBranches);
+
+class FindIfUnderCursor : public RecursiveASTVisitor {
+public:
+  FindIfUnderCursor(ASTContext , SourceLocation CursorLoc, IfStmt *)
+  : Ctx(Ctx), CursorLoc(CursorLoc), Result(Result) {}
+
+  bool VisitIfStmt(IfStmt *If) {
+auto R = toHalfOpenFileRange(Ctx.getSourceManager(), Ctx.getLangOpts(),
+ SourceRange(If->getIfLoc()));
+if (!R)
+  return true;
+if (!halfOpenRangeContains(Ctx.getSourceManager(), *R, CursorLoc))
+  return true;
+Result = If;
+return false;
+  }
+
+private:
+  ASTContext 
+  SourceLocation CursorLoc;
+  IfStmt *
+};
+} // namespace
+
+bool SwapIfBranches::prepare(const Selection ) {
+
+  auto  = Inputs.AST.getASTContext();
+  auto  = Ctx.getSourceManager();
+  IfStmt *If = nullptr;
+  FindIfUnderCursor(Ctx, Inputs.Cursor, If).TraverseAST(Ctx);
+  if (!If)
+return false;
+
+  // avoid dealing with single-statement brances, they require careful handling
+  // to avoid changing semantics of the code (i.e. dangling else).
+  if (!llvm::dyn_cast_or_null(If->getThen()) ||
+  !llvm::dyn_cast_or_null(If->getElse()))
+return false;
+
+  auto ThenRng = toHalfOpenFileRange(SrcMgr, Ctx.getLangOpts(),
+ If->getThen()->getSourceRange());
+  if (!ThenRng)
+return false;
+  auto ElseRng = toHalfOpenFileRange(SrcMgr, Ctx.getLangOpts(),
+ If->getElse()->getSourceRange());
+  if (!ElseRng)
+return false;
+
+  llvm::StringRef ThenCode = toSourceCode(SrcMgr, *ThenRng);
+  llvm::StringRef ElseCode = toSourceCode(SrcMgr, *ElseRng);
+
+  if (auto Err = Result.add(tooling::Replacement(SrcMgr, ThenRng->getBegin(),
+ ThenCode.size(), ElseCode))) {
+llvm::consumeError(std::move(Err));
+return false;
+  }
+  if (auto Err = Result.add(tooling::Replacement(SrcMgr, ElseRng->getBegin(),
+ ElseCode.size(), ThenCode))) {
+llvm::consumeError(std::move(Err));
+return false;
+  }
+  return true;
+}
+
+Expected SwapIfBranches::apply(const Selection ) {
+  return Result;
+}
+
+std::string SwapIfBranches::title() const { return "Swap if branches"; }
+} // namespace clangd
+} // namespace clang
Index: clangd/refactor/tweaks/CMakeLists.txt
===
--- clangd/refactor/tweaks/CMakeLists.txt
+++ clangd/refactor/tweaks/CMakeLists.txt
@@ -9,4 +9,5 @@
 # clangd/tool/CMakeLists.txt for an example.
 add_clang_library(clangDaemonTweaks OBJECT
   QualifyName.cpp
+  SwapIfBranches.cpp
   )
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D56610: [clangd] A code action to qualify an unqualified name

2019-01-17 Thread Ilya Biryukov via Phabricator via cfe-commits
ilya-biryukov updated this revision to Diff 182320.
ilya-biryukov added a comment.

- Remove the header file


Repository:
  rCTE Clang Tools Extra

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

https://reviews.llvm.org/D56610

Files:
  clangd/SourceCode.cpp
  clangd/SourceCode.h
  clangd/refactor/tweaks/CMakeLists.txt
  clangd/refactor/tweaks/QualifyName.cpp

Index: clangd/refactor/tweaks/QualifyName.cpp
===
--- /dev/null
+++ clangd/refactor/tweaks/QualifyName.cpp
@@ -0,0 +1,180 @@
+//===--- QualifyName.cpp -*- C++-*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===--===//
+#include "AST.h"
+#include "ClangdUnit.h"
+#include "SourceCode.h"
+#include "refactor/Tweak.h"
+#include "clang/AST/RecursiveASTVisitor.h"
+#include "clang/AST/TypeLoc.h"
+#include "clang/Basic/SourceLocation.h"
+#include "clang/Tooling/Tooling.h"
+#include "llvm/Support/Error.h"
+
+namespace clang {
+namespace clangd {
+namespace {
+/// Fully qualifies a name under a cursor.
+/// Before:
+///   using namespace std;
+///   ^vector foo;
+/// After:
+///   std::vector foo;
+class QualifyName : public Tweak {
+public:
+  TweakID id() const override { return llvm::StringLiteral("qualify-name"); }
+
+  bool prepare(const Selection ) override;
+  Expected apply(const Selection ) override;
+  std::string title() const override;
+
+private:
+  SourceLocation InsertLoc;
+  std::string Qualifier;
+};
+
+REGISTER_TWEAK(QualifyName);
+
+struct Reference {
+  SourceLocation Begin;
+  NamedDecl *Target = nullptr;
+
+  operator bool() const { return Target != nullptr; }
+};
+
+NamedDecl *toReferencedDecl(NestedNameSpecifier *NNS) {
+  switch (NNS->getKind()) {
+  case clang::NestedNameSpecifier::Namespace:
+return NNS->getAsNamespace();
+  case clang::NestedNameSpecifier::NamespaceAlias:
+return NNS->getAsNamespaceAlias();
+  case clang::NestedNameSpecifier::TypeSpec:
+  case clang::NestedNameSpecifier::TypeSpecWithTemplate:
+return nullptr; // FIXME: handle this situation, retrieve the thing
+// referenced inside a type.
+  case clang::NestedNameSpecifier::Identifier:
+  case clang::NestedNameSpecifier::Super:
+  case clang::NestedNameSpecifier::Global: // FIXME: could return
+   // TranslationUnitDecl.
+return nullptr;
+return nullptr;
+  }
+  llvm_unreachable("unhandled NestedNameSpecifier kind.");
+}
+
+class LocateInsertLoc : public RecursiveASTVisitor {
+public:
+  LocateInsertLoc(ASTContext , SourceLocation CursorLoc,
+  Reference )
+  : Ctx(Ctx), CursorLoc(CursorLoc), UnqualRef(UnqualRef) {}
+
+  bool shouldWalkTypesOfTypeLocs() const { return false; }
+
+  // FIXME: RAT does not have VisitNestedNameSpecifierLoc. Should we add that?
+  bool TraverseNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS) {
+if (!RecursiveASTVisitor::TraverseNestedNameSpecifierLoc(NNS))
+  return false;
+return VisitNestedNameSpecifierLoc(NNS);
+  }
+
+  bool VisitNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS) {
+if (NNS.getPrefix())
+  return true; // we want only unqualified names.
+auto  = Ctx.getSourceManager();
+auto Rng = toHalfOpenFileRange(SM, Ctx.getLangOpts(), NNS.getSourceRange());
+if (!Rng)
+  return true;
+if (!halfOpenRangeContains(SM, *Rng, CursorLoc))
+  return true;
+auto *Target = toReferencedDecl(NNS.getNestedNameSpecifier());
+if (!Target)
+  return true; // continue traversal to recurse into types, if any.
+UnqualRef.Begin = Rng->getBegin();
+UnqualRef.Target = Target;
+return false; // we found the insertion point.
+  }
+
+  bool VisitDeclRefExpr(DeclRefExpr *E) {
+if (E->hasQualifier())
+  return true; // we want only unqualified names.
+auto  = Ctx.getSourceManager();
+auto Rng = toHalfOpenFileRange(SM, Ctx.getLangOpts(), E->getSourceRange());
+if (!Rng)
+  return true;
+if (!halfOpenRangeContains(SM, *Rng, CursorLoc))
+  return true;
+UnqualRef.Begin = Rng->getBegin();
+UnqualRef.Target = E->getFoundDecl();
+return false;
+  }
+
+  bool VisitTagTypeLoc(TagTypeLoc Loc) {
+auto  = Ctx.getSourceManager();
+auto Rng = toHalfOpenFileRange(SM, Ctx.getLangOpts(), Loc.getSourceRange());
+if (!Rng)
+  return true;
+if (!halfOpenRangeContains(SM, *Rng, CursorLoc))
+  return true;
+UnqualRef.Begin = Rng->getBegin();
+UnqualRef.Target = Loc.getDecl();
+return false;
+  }
+
+  bool VisitTypedefTypeLoc(TypedefTypeLoc Loc) {
+auto  = Ctx.getSourceManager();
+auto Rng = toHalfOpenFileRange(SM, Ctx.getLangOpts(), Loc.getSourceRange());
+if (!Rng)
+  return 

[PATCH] D56612: [clangd] A code action to remove 'using namespace'

2019-01-17 Thread Ilya Biryukov via Phabricator via cfe-commits
ilya-biryukov updated this revision to Diff 182322.
ilya-biryukov added a comment.

- Remove the header file


Repository:
  rCTE Clang Tools Extra

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

https://reviews.llvm.org/D56612

Files:
  clangd/AST.cpp
  clangd/AST.h
  clangd/refactor/tweaks/CMakeLists.txt
  clangd/refactor/tweaks/RemoveUsingNamespace.cpp

Index: clangd/refactor/tweaks/RemoveUsingNamespace.cpp
===
--- /dev/null
+++ clangd/refactor/tweaks/RemoveUsingNamespace.cpp
@@ -0,0 +1,206 @@
+//===--- RemoveUsingNamespace.cpp *- C++-*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===--===//
+#include "AST.h"
+#include "ClangdUnit.h"
+#include "SourceCode.h"
+#include "refactor/Tweak.h"
+#include "clang/AST/RecursiveASTVisitor.h"
+#include "clang/Tooling/Core/Replacement.h"
+#include "clang/Tooling/Refactoring/RecursiveSymbolVisitor.h"
+#include "llvm/ADT/ScopeExit.h"
+
+namespace clang {
+namespace clangd {
+namespace {
+/// Removes the 'using namespace' under the cursor and qualifies all accesses in
+/// the current file. E.g.,
+///   using namespace std;
+///   vector foo(std::map);
+/// Would become:
+///   std::vector foo(std::map);
+class RemoveUsingNamespace : public Tweak {
+public:
+  TweakID id() const override {
+return llvm::StringLiteral("remove-using-namespace");
+  }
+
+  bool prepare(const Selection ) override;
+  Expected apply(const Selection ) override;
+  std::string title() const override;
+
+private:
+  UsingDirectiveDecl *TargetDirective = nullptr;
+};
+REGISTER_TWEAK(RemoveUsingNamespace);
+
+class FindNodeUnderCursor : public RecursiveASTVisitor {
+public:
+  FindNodeUnderCursor(SourceLocation SearchedLoc, UsingDirectiveDecl *)
+  : SearchedLoc(SearchedLoc), Result(Result) {}
+
+  bool VisitUsingDirectiveDecl(UsingDirectiveDecl *D) {
+if (D->getUsingLoc() != SearchedLoc)
+  return true;
+
+Result = D;
+return false;
+  }
+
+private:
+  SourceLocation SearchedLoc;
+  UsingDirectiveDecl *
+};
+
+class FindSameUsings : public RecursiveASTVisitor {
+public:
+  FindSameUsings(UsingDirectiveDecl ,
+ std::vector )
+  : TargetNS(Target.getNominatedNamespace()),
+TargetCtx(Target.getDeclContext()), Results(Results) {}
+
+  bool VisitUsingDirectiveDecl(UsingDirectiveDecl *D) {
+if (D->getNominatedNamespace() != TargetNS ||
+D->getDeclContext() != TargetCtx)
+  return true;
+
+Results.push_back(D);
+return true;
+  }
+
+private:
+  NamespaceDecl *TargetNS;
+  DeclContext *TargetCtx;
+  std::vector 
+};
+
+class FindIdentsToQualify
+: public tooling::RecursiveSymbolVisitor {
+public:
+  FindIdentsToQualify(ASTContext , NamespaceDecl ,
+  std::vector )
+  : RecursiveSymbolVisitor(Ctx.getSourceManager(), Ctx.getLangOpts()),
+Ctx(Ctx), TargetNS(TargetNS), ResultIdents(ResultIdents) {}
+
+  bool visitSymbolOccurrence(const NamedDecl *D,
+ llvm::ArrayRef NameRanges) {
+if (!D || D->getCanonicalDecl() == TargetNS.getCanonicalDecl())
+  return true;
+if (!D->getDeclName().isIdentifier() ||
+D->getDeclName().getNameKind() == DeclarationName::CXXOperatorName)
+  return true; // do not add qualifiers for non-idents, e.g. 'operator+'.
+// Check the symbol is unqualified and references something inside our
+// namespace.
+// FIXME: add a check it's unqualified.
+if (!TargetNS.InEnclosingNamespaceSetOf(D->getDeclContext()))
+  return true;
+// FIXME: handle more tricky cases, e.g. we don't need the qualifier if we
+//have the using decls for some entities, we might have qualified
+//references that need updating too.
+for (auto R : NameRanges) {
+  if (!Ctx.getSourceManager().isWrittenInMainFile(R.getBegin()))
+continue; // we can't fix refences outside our file.
+  // FIXME: this might be a conflict that we need to report.
+  ResultIdents.push_back(R.getBegin());
+}
+return true;
+  }
+
+  bool TraverseDecl(Decl *D) {
+if (!Ctx.getSourceManager().isWrittenInMainFile(D->getLocation()) &&
+!isa(D))
+  return true; // skip decls outside main file.
+return RecursiveSymbolVisitor::TraverseDecl(D);
+  }
+
+private:
+  ASTContext 
+  NamespaceDecl 
+  std::vector 
+};
+
+// Produces an edit to remove 'using namespace xxx::yyy' and the trailing
+// semicolon.
+llvm::Expected
+removeUsingDirective(ASTContext , UsingDirectiveDecl *D) {
+  auto  = Ctx.getSourceManager();
+  auto R =
+  Lexer::getAsCharRange(D->getSourceRange(), SrcMgr, Ctx.getLangOpts());
+  if (R.isInvalid())
+return 

  1   2   >