[PATCH] D39080: [libcxx] [test] Tolerate even more [[nodiscard]] in the STL.

2017-10-18 Thread Billy Robert O'Neal III via Phabricator via cfe-commits
BillyONeal created this revision.

STL reviewed my [[nodiscard]] changes and suggested a ton more places. These 
are the associated test changes in libcxx.


https://reviews.llvm.org/D39080

Files:
  test/std/algorithms/alg.nonmodifying/alg.search/search_n.pass.cpp
  test/std/algorithms/alg.nonmodifying/alg.search/search_n_pred.pass.cpp
  test/std/containers/associative/map/map.access/at.pass.cpp
  test/std/containers/unord/unord.map/unord.map.elem/at.pass.cpp
  test/std/numerics/rand/rand.adapt/rand.adapt.disc/assign.pass.cpp
  test/std/numerics/rand/rand.adapt/rand.adapt.disc/copy.pass.cpp
  test/std/numerics/rand/rand.adapt/rand.adapt.disc/discard.pass.cpp
  test/std/numerics/rand/rand.adapt/rand.adapt.ibits/assign.pass.cpp
  test/std/numerics/rand/rand.adapt/rand.adapt.ibits/copy.pass.cpp
  test/std/numerics/rand/rand.adapt/rand.adapt.ibits/discard.pass.cpp
  test/std/numerics/rand/rand.adapt/rand.adapt.shuf/assign.pass.cpp
  test/std/numerics/rand/rand.adapt/rand.adapt.shuf/copy.pass.cpp
  test/std/numerics/rand/rand.adapt/rand.adapt.shuf/ctor_engine_copy.pass.cpp
  test/std/numerics/rand/rand.adapt/rand.adapt.shuf/ctor_engine_move.pass.cpp
  test/std/numerics/rand/rand.adapt/rand.adapt.shuf/discard.pass.cpp
  test/std/numerics/rand/rand.device/eval.pass.cpp
  test/std/numerics/rand/rand.eng/rand.eng.lcong/discard.pass.cpp
  test/std/numerics/rand/rand.eng/rand.eng.mers/assign.pass.cpp
  test/std/numerics/rand/rand.eng/rand.eng.mers/copy.pass.cpp
  test/std/numerics/rand/rand.eng/rand.eng.mers/discard.pass.cpp
  test/std/numerics/rand/rand.eng/rand.eng.sub/assign.pass.cpp
  test/std/numerics/rand/rand.eng/rand.eng.sub/copy.pass.cpp
  test/std/numerics/rand/rand.eng/rand.eng.sub/discard.pass.cpp
  test/std/re/re.alg/re.alg.search/grep.pass.cpp
  test/std/thread/thread.mutex/thread.lock.algorithm/try_lock.pass.cpp
  
test/std/thread/thread.mutex/thread.lock/thread.lock.shared/thread.lock.shared.locking/try_lock.pass.cpp
  
test/std/thread/thread.mutex/thread.lock/thread.lock.shared/thread.lock.shared.locking/try_lock_for.pass.cpp
  
test/std/thread/thread.mutex/thread.lock/thread.lock.shared/thread.lock.shared.locking/try_lock_until.pass.cpp
  
test/std/thread/thread.mutex/thread.lock/thread.lock.unique/thread.lock.unique.locking/try_lock.pass.cpp
  
test/std/thread/thread.mutex/thread.lock/thread.lock.unique/thread.lock.unique.locking/try_lock_for.pass.cpp
  
test/std/thread/thread.mutex/thread.lock/thread.lock.unique/thread.lock.unique.locking/try_lock_until.pass.cpp
  test/std/utilities/any/any.nonmembers/any.cast/any_cast_reference.pass.cpp
  
test/std/utilities/memory/default.allocator/allocator.members/allocate.size.pass.cpp
  
test/std/utilities/memory/util.smartptr/util.smartptr.enab/enable_shared_from_this.pass.cpp
  
test/std/utilities/memory/util.smartptr/util.smartptr.weak/util.smartptr.ownerless/owner_less.pass.cpp

Index: test/std/utilities/memory/util.smartptr/util.smartptr.weak/util.smartptr.ownerless/owner_less.pass.cpp
===
--- test/std/utilities/memory/util.smartptr/util.smartptr.weak/util.smartptr.ownerless/owner_less.pass.cpp
+++ test/std/utilities/memory/util.smartptr/util.smartptr.weak/util.smartptr.ownerless/owner_less.pass.cpp
@@ -112,11 +112,11 @@
 std::weak_ptr wp1;
 
 std::owner_less<> cmp;
-cmp(sp1, sp2);
-cmp(sp1, wp1);
-cmp(sp1, sp3);
-cmp(wp1, sp1);
-cmp(wp1, wp1);
+assert(!cmp(sp1, sp2));
+assert(!cmp(sp1, wp1));
+assert(!cmp(sp1, sp3));
+assert(!cmp(wp1, sp1));
+assert(!cmp(wp1, wp1));
 ASSERT_NOEXCEPT(cmp(sp1, sp1));
 ASSERT_NOEXCEPT(cmp(sp1, wp1));
 ASSERT_NOEXCEPT(cmp(wp1, sp1));
Index: test/std/utilities/memory/util.smartptr/util.smartptr.enab/enable_shared_from_this.pass.cpp
===
--- test/std/utilities/memory/util.smartptr/util.smartptr.enab/enable_shared_from_this.pass.cpp
+++ test/std/utilities/memory/util.smartptr/util.smartptr.enab/enable_shared_from_this.pass.cpp
@@ -134,7 +134,7 @@
 
 #ifndef TEST_HAS_NO_EXCEPTIONS
 try {
-ptr->shared_from_this();
+(void)ptr->shared_from_this();
 assert(false);
 } catch (std::bad_weak_ptr const&) {
 } catch (...) { assert(false); }
Index: test/std/utilities/memory/default.allocator/allocator.members/allocate.size.pass.cpp
===
--- test/std/utilities/memory/default.allocator/allocator.members/allocate.size.pass.cpp
+++ test/std/utilities/memory/default.allocator/allocator.members/allocate.size.pass.cpp
@@ -23,7 +23,7 @@
 {
 std::allocator a;
 try {
-a.allocate(count);
+(void)a.allocate(count);
 assert(false);
 } catch (const std::exception &) {
 }
Index: test/std/utilities/any/any.nonmembers/any.cast/any_cast_reference.pass.cpp
=

[PATCH] D39079: New clang option -fno-plt to avoid PLT for external calls

2017-10-18 Thread Sriraman Tallam via Phabricator via cfe-commits
tmsriram created this revision.

New clang option -fno-plt which avoids the PLT and lazy binding while making 
external calls.

GCC supports -fno-plt, 
https://gcc.gnu.org/ml/gcc-patches/2015-05/msg1.html. This patch adds this 
to clang which marks all externally defined functions with the "nolazybind" 
attribute.  This LLVM patch skips the PLT for calls to these functions, 
https://reviews.llvm.org/D39065.


https://reviews.llvm.org/D39079

Files:
  include/clang/Driver/Options.td
  include/clang/Frontend/CodeGenOptions.def
  lib/CodeGen/CGCall.cpp
  lib/Driver/ToolChains/Clang.cpp
  lib/Frontend/CompilerInvocation.cpp


Index: lib/Frontend/CompilerInvocation.cpp
===
--- lib/Frontend/CompilerInvocation.cpp
+++ lib/Frontend/CompilerInvocation.cpp
@@ -650,6 +650,7 @@
   Args.hasArg(OPT_mincremental_linker_compatible);
   Opts.PIECopyRelocations =
   Args.hasArg(OPT_mpie_copy_relocations);
+  Opts.NoPLT = Args.hasArg(OPT_fno_plt);
   Opts.OmitLeafFramePointer = Args.hasArg(OPT_momit_leaf_frame_pointer);
   Opts.SaveTempLabels = Args.hasArg(OPT_msave_temp_labels);
   Opts.NoDwarfDirectoryAsm = Args.hasArg(OPT_fno_dwarf_directory_asm);
Index: lib/Driver/ToolChains/Clang.cpp
===
--- lib/Driver/ToolChains/Clang.cpp
+++ lib/Driver/ToolChains/Clang.cpp
@@ -3386,6 +3386,10 @@
 CmdArgs.push_back("-mpie-copy-relocations");
   }
 
+  if (Args.hasFlag(options::OPT_fno_plt, options::OPT_fplt, false)) {
+CmdArgs.push_back("-fno-plt");
+  }
+
   // -fhosted is default.
   // TODO: Audit uses of KernelOrKext and see where it'd be more appropriate to
   // use Freestanding.
Index: lib/CodeGen/CGCall.cpp
===
--- lib/CodeGen/CGCall.cpp
+++ lib/CodeGen/CGCall.cpp
@@ -1852,6 +1852,16 @@
   !(TargetDecl && TargetDecl->hasAttr()))
 FuncAttrs.addAttribute("split-stack");
 
+  // Add NonLazyBind attribute to function declarations when -fno-plt
+  // is used.
+  if (TargetDecl && CodeGenOpts.NoPLT) {
+if (auto *Fn = dyn_cast(TargetDecl)) {
+  if (!Fn->isDefined() && !AttrOnCallSite) {
+FuncAttrs.addAttribute(llvm::Attribute::NonLazyBind);
+  }
+}
+  }
+
   if (!AttrOnCallSite) {
 bool DisableTailCalls =
 CodeGenOpts.DisableTailCalls ||
Index: include/clang/Frontend/CodeGenOptions.def
===
--- include/clang/Frontend/CodeGenOptions.def
+++ include/clang/Frontend/CodeGenOptions.def
@@ -294,6 +294,8 @@
 /// Whether to emit .debug_gnu_pubnames section instead of .debug_pubnames.
 CODEGENOPT(GnuPubnames, 1, 0)
 
+CODEGENOPT(NoPLT, 1, 0)
+
 #undef CODEGENOPT
 #undef ENUM_CODEGENOPT
 #undef VALUE_CODEGENOPT
Index: include/clang/Driver/Options.td
===
--- include/clang/Driver/Options.td
+++ include/clang/Driver/Options.td
@@ -1363,6 +1363,10 @@
 def fno_pic : Flag<["-"], "fno-pic">, Group;
 def fpie : Flag<["-"], "fpie">, Group;
 def fno_pie : Flag<["-"], "fno-pie">, Group;
+def fplt : Flag<["-"], "fplt">, Group, Flags<[CC1Option]>,
+  HelpText<"Use the PLT to make function calls">;
+def fno_plt : Flag<["-"], "fno-plt">, Group, Flags<[CC1Option]>,
+  HelpText<"Do not use the PLT to make function calls">;
 def fropi : Flag<["-"], "fropi">, Group;
 def fno_ropi : Flag<["-"], "fno-ropi">, Group;
 def frwpi : Flag<["-"], "frwpi">, Group;


Index: lib/Frontend/CompilerInvocation.cpp
===
--- lib/Frontend/CompilerInvocation.cpp
+++ lib/Frontend/CompilerInvocation.cpp
@@ -650,6 +650,7 @@
   Args.hasArg(OPT_mincremental_linker_compatible);
   Opts.PIECopyRelocations =
   Args.hasArg(OPT_mpie_copy_relocations);
+  Opts.NoPLT = Args.hasArg(OPT_fno_plt);
   Opts.OmitLeafFramePointer = Args.hasArg(OPT_momit_leaf_frame_pointer);
   Opts.SaveTempLabels = Args.hasArg(OPT_msave_temp_labels);
   Opts.NoDwarfDirectoryAsm = Args.hasArg(OPT_fno_dwarf_directory_asm);
Index: lib/Driver/ToolChains/Clang.cpp
===
--- lib/Driver/ToolChains/Clang.cpp
+++ lib/Driver/ToolChains/Clang.cpp
@@ -3386,6 +3386,10 @@
 CmdArgs.push_back("-mpie-copy-relocations");
   }
 
+  if (Args.hasFlag(options::OPT_fno_plt, options::OPT_fplt, false)) {
+CmdArgs.push_back("-fno-plt");
+  }
+
   // -fhosted is default.
   // TODO: Audit uses of KernelOrKext and see where it'd be more appropriate to
   // use Freestanding.
Index: lib/CodeGen/CGCall.cpp
===
--- lib/CodeGen/CGCall.cpp
+++ lib/CodeGen/CGCall.cpp
@@ -1852,6 +1852,16 @@
   !(TargetDecl && TargetDecl->hasAttr()))
 FuncAttrs.addAttribute("split-stack");
 
+  // Add NonLazyBind attribute to function declarations when -fno-plt
+  // is used.
+  if (T

[PATCH] D39071: [Hexagon] Fix the memory-leak in r316102

2017-10-18 Thread Sumanth Gundapaneni via Phabricator via cfe-commits
sgundapa abandoned this revision.
sgundapa added a comment.

This patch is already merged in a different commit


Repository:
  rL LLVM

https://reviews.llvm.org/D39071



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


[PATCH] D39075: Fix nodiscard for volatile references

2017-10-18 Thread Erich Keane via Phabricator via cfe-commits
erichkeane updated this revision to Diff 119535.
erichkeane added a comment.

Added function-pointer test.


https://reviews.llvm.org/D39075

Files:
  lib/AST/Expr.cpp
  test/CXX/dcl.dcl/dcl.attr/dcl.attr.nodiscard/p2.cpp


Index: lib/AST/Expr.cpp
===
--- lib/AST/Expr.cpp
+++ lib/AST/Expr.cpp
@@ -2298,7 +2298,8 @@
 const DeclRefExpr *DRE =
 dyn_cast(CE->getSubExpr()->IgnoreParens());
 if (!(DRE && isa(DRE->getDecl()) &&
-  cast(DRE->getDecl())->hasLocalStorage())) {
+  cast(DRE->getDecl())->hasLocalStorage()) &&
+!isa(CE->getSubExpr()->IgnoreParens())) {
   return CE->getSubExpr()->isUnusedResultAWarning(WarnE, Loc,
   R1, R2, Ctx);
 }
Index: test/CXX/dcl.dcl/dcl.attr/dcl.attr.nodiscard/p2.cpp
===
--- test/CXX/dcl.dcl/dcl.attr/dcl.attr.nodiscard/p2.cpp
+++ test/CXX/dcl.dcl/dcl.attr/dcl.attr.nodiscard/p2.cpp
@@ -9,21 +9,33 @@
 E get_e();
 
 [[nodiscard]] int get_i();
+[[nodiscard]] volatile int &get_vi();
 
 void f() {
   get_s(); // expected-warning {{ignoring return value of function declared 
with 'nodiscard' attribute}}
   get_i(); // expected-warning {{ignoring return value of function declared 
with 'nodiscard' attribute}}
+  get_vi(); // expected-warning {{ignoring return value of function declared 
with 'nodiscard' attribute}}
   get_e(); // expected-warning {{ignoring return value of function declared 
with 'nodiscard' attribute}}
 
   // Okay, warnings are not encouraged
   get_s_ref();
   (void)get_s();
   (void)get_i();
+  (void)get_vi();
   (void)get_e();
 }
 
+[[nodiscard]] volatile char &(*fp)();
+void g() {
+  fp(); // expected-warning {{ignoring return value of function declared with 
'nodiscard' attribute}}
+
+  // OK, warning suppressed.
+  (void)fp();
+}
 #ifdef EXT
 // expected-warning@4 {{use of the 'nodiscard' attribute is a C++17 extension}}
 // expected-warning@8 {{use of the 'nodiscard' attribute is a C++17 extension}}
 // expected-warning@11 {{use of the 'nodiscard' attribute is a C++17 
extension}}
+// expected-warning@12 {{use of the 'nodiscard' attribute is a C++17 
extension}}
+// expected-warning@28 {{use of the 'nodiscard' attribute is a C++17 
extension}}
 #endif


Index: lib/AST/Expr.cpp
===
--- lib/AST/Expr.cpp
+++ lib/AST/Expr.cpp
@@ -2298,7 +2298,8 @@
 const DeclRefExpr *DRE =
 dyn_cast(CE->getSubExpr()->IgnoreParens());
 if (!(DRE && isa(DRE->getDecl()) &&
-  cast(DRE->getDecl())->hasLocalStorage())) {
+  cast(DRE->getDecl())->hasLocalStorage()) &&
+!isa(CE->getSubExpr()->IgnoreParens())) {
   return CE->getSubExpr()->isUnusedResultAWarning(WarnE, Loc,
   R1, R2, Ctx);
 }
Index: test/CXX/dcl.dcl/dcl.attr/dcl.attr.nodiscard/p2.cpp
===
--- test/CXX/dcl.dcl/dcl.attr/dcl.attr.nodiscard/p2.cpp
+++ test/CXX/dcl.dcl/dcl.attr/dcl.attr.nodiscard/p2.cpp
@@ -9,21 +9,33 @@
 E get_e();
 
 [[nodiscard]] int get_i();
+[[nodiscard]] volatile int &get_vi();
 
 void f() {
   get_s(); // expected-warning {{ignoring return value of function declared with 'nodiscard' attribute}}
   get_i(); // expected-warning {{ignoring return value of function declared with 'nodiscard' attribute}}
+  get_vi(); // expected-warning {{ignoring return value of function declared with 'nodiscard' attribute}}
   get_e(); // expected-warning {{ignoring return value of function declared with 'nodiscard' attribute}}
 
   // Okay, warnings are not encouraged
   get_s_ref();
   (void)get_s();
   (void)get_i();
+  (void)get_vi();
   (void)get_e();
 }
 
+[[nodiscard]] volatile char &(*fp)();
+void g() {
+  fp(); // expected-warning {{ignoring return value of function declared with 'nodiscard' attribute}}
+
+  // OK, warning suppressed.
+  (void)fp();
+}
 #ifdef EXT
 // expected-warning@4 {{use of the 'nodiscard' attribute is a C++17 extension}}
 // expected-warning@8 {{use of the 'nodiscard' attribute is a C++17 extension}}
 // expected-warning@11 {{use of the 'nodiscard' attribute is a C++17 extension}}
+// expected-warning@12 {{use of the 'nodiscard' attribute is a C++17 extension}}
+// expected-warning@28 {{use of the 'nodiscard' attribute is a C++17 extension}}
 #endif
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D39064: implement __has_unique_object_representations

2017-10-18 Thread Erich Keane via Phabricator via cfe-commits
erichkeane added inline comments.



Comment at: lib/Parse/ParseExpr.cpp:719
 ///   '__is_union'
+///   '__has_unique_object_representations'   [MS]
 ///

STL_MSFT wrote:
> Should this be marked as MS if it's cross-vendor?
Ah, right :)  I didn't discover the GCC version until later, and must have 
forgotten this.



Comment at: test/SemaCXX/type-traits.cpp:2403
+static_assert(has_unique_object_representations::value, "yes, all 
integral types");
+static_assert(has_unique_object_representations::value, "and pointer to 
members");
+static_assert(has_unique_object_representations::value, "and 
pointer to members");

STL_MSFT wrote:
> char is a pointer to member! What a world. (ditto below)
What a world indeed!


https://reviews.llvm.org/D39064



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


[PATCH] D39075: Fix nodiscard for volatile references

2017-10-18 Thread Erich Keane via Phabricator via cfe-commits
erichkeane added inline comments.



Comment at: lib/AST/Expr.cpp:2302
+  cast(DRE->getDecl())->hasLocalStorage()) &&
+!isa(CE->getSubExpr()->IgnoreParens())) {
   return CE->getSubExpr()->isUnusedResultAWarning(WarnE, Loc,

aaron.ballman wrote:
> Does this properly handle calls through function pointers (which usually have 
> implicit casts)?
> ```
> [[nodiscard]] volatile char &(*fp)();
> void g() {
>   (void)fp(); // No diagnostic here, either?
> }
> ```
I added this test, and it seems to work correctly.  Patch with additional test 
incoming.


https://reviews.llvm.org/D39075



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


r316136 - Don't suppress instantiation of definitions for variables subject to explicit

2017-10-18 Thread Richard Smith via cfe-commits
Author: rsmith
Date: Wed Oct 18 15:45:01 2017
New Revision: 316136

URL: http://llvm.org/viewvc/llvm-project?rev=316136&view=rev
Log:
Don't suppress instantiation of definitions for variables subject to explicit
instantiation declarations if they are usable from constant expressions.

We are permitted to instantiate in these cases, and required to do so in order
to have an initializer available for use within constant evaluation.

Added:
cfe/trunk/test/SemaTemplate/cxx17-inline-variables.cpp
Modified:
cfe/trunk/lib/Sema/SemaExpr.cpp
cfe/trunk/lib/Sema/SemaTemplateInstantiateDecl.cpp
cfe/trunk/test/CodeGenCXX/dllimport-members.cpp
cfe/trunk/test/SemaTemplate/extern-templates.cpp

Modified: cfe/trunk/lib/Sema/SemaExpr.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Sema/SemaExpr.cpp?rev=316136&r1=316135&r2=316136&view=diff
==
--- cfe/trunk/lib/Sema/SemaExpr.cpp (original)
+++ cfe/trunk/lib/Sema/SemaExpr.cpp Wed Oct 18 15:45:01 2017
@@ -14823,9 +14823,10 @@ static void DoMarkVarDeclReferenced(Sema
   TemplateSpecializationKind TSK = Var->getTemplateSpecializationKind();
 
   bool OdrUseContext = isOdrUseContext(SemaRef);
+  bool UsableInConstantExpr =
+  Var->isUsableInConstantExpressions(SemaRef.Context);
   bool NeedDefinition =
-  OdrUseContext || (isEvaluatableContext(SemaRef) &&
-Var->isUsableInConstantExpressions(SemaRef.Context));
+  OdrUseContext || (isEvaluatableContext(SemaRef) && UsableInConstantExpr);
 
   VarTemplateSpecializationDecl *VarSpec =
   dyn_cast(Var);
@@ -14844,14 +14845,19 @@ static void DoMarkVarDeclReferenced(Sema
   // instantiations of variable templates, except for those that could be used
   // in a constant expression.
   if (NeedDefinition && isTemplateInstantiation(TSK)) {
-bool TryInstantiating = TSK == TSK_ImplicitInstantiation;
+// Per C++17 [temp.explicit]p10, we may instantiate despite an explicit
+// instantiation declaration if a variable is usable in a constant
+// expression (among other cases).
+bool TryInstantiating =
+TSK == TSK_ImplicitInstantiation ||
+(TSK == TSK_ExplicitInstantiationDeclaration && UsableInConstantExpr);
 
 if (TryInstantiating && !isa(Var)) {
   if (Var->getPointOfInstantiation().isInvalid()) {
 // This is a modification of an existing AST node. Notify listeners.
 if (ASTMutationListener *L = SemaRef.getASTMutationListener())
   L->StaticDataMemberInstantiated(Var);
-  } else if (!Var->isUsableInConstantExpressions(SemaRef.Context))
+  } else if (!UsableInConstantExpr)
 // Don't bother trying to instantiate it again, unless we might need
 // its initializer before we get to the end of the TU.
 TryInstantiating = false;
@@ -14870,7 +14876,7 @@ static void DoMarkVarDeclReferenced(Sema
 
   // Do not instantiate specializations that are still type-dependent.
   if (IsNonDependent) {
-if (Var->isUsableInConstantExpressions(SemaRef.Context)) {
+if (UsableInConstantExpr) {
   // Do not defer instantiations of variables which could be used in a
   // constant expression.
   SemaRef.InstantiateVariableDefinition(PointOfInstantiation, Var);

Modified: cfe/trunk/lib/Sema/SemaTemplateInstantiateDecl.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Sema/SemaTemplateInstantiateDecl.cpp?rev=316136&r1=316135&r2=316136&view=diff
==
--- cfe/trunk/lib/Sema/SemaTemplateInstantiateDecl.cpp (original)
+++ cfe/trunk/lib/Sema/SemaTemplateInstantiateDecl.cpp Wed Oct 18 15:45:01 2017
@@ -4359,10 +4359,12 @@ void Sema::InstantiateVariableDefinition
 return;
 
   // C++11 [temp.explicit]p10:
-  //   Except for inline functions, [...] explicit instantiation declarations
+  //   Except for inline functions, const variables of literal types, variables
+  //   of reference types, [...] explicit instantiation declarations
   //   have the effect of suppressing the implicit instantiation of the entity
   //   to which they refer.
-  if (TSK == TSK_ExplicitInstantiationDeclaration)
+  if (TSK == TSK_ExplicitInstantiationDeclaration &&
+  !Var->isUsableInConstantExpressions(getASTContext()))
 return;
 
   // Make sure to pass the instantiated variable to the consumer at the end.

Modified: cfe/trunk/test/CodeGenCXX/dllimport-members.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/CodeGenCXX/dllimport-members.cpp?rev=316136&r1=316135&r2=316136&view=diff
==
--- cfe/trunk/test/CodeGenCXX/dllimport-members.cpp (original)
+++ cfe/trunk/test/CodeGenCXX/dllimport-members.cpp Wed Oct 18 15:45:01 2017
@@ -836,7 +836,7 @@ USEMV(MemVarTmpl, ImportedStaticVar;
 USEMV(MemVarTmpl, ImportedStaticVar)
@@ -861,7 +861,7

[PATCH] D39064: implement __has_unique_object_representations

2017-10-18 Thread Erich Keane via Phabricator via cfe-commits
erichkeane updated this revision to Diff 119533.
erichkeane marked 3 inline comments as done.

https://reviews.llvm.org/D39064

Files:
  include/clang/AST/Type.h
  include/clang/Basic/TokenKinds.def
  include/clang/Basic/TypeTraits.h
  lib/AST/Type.cpp
  lib/Parse/ParseExpr.cpp
  lib/Sema/SemaExprCXX.cpp
  test/SemaCXX/type-traits.cpp

Index: lib/Parse/ParseExpr.cpp
===
--- lib/Parse/ParseExpr.cpp
+++ lib/Parse/ParseExpr.cpp
@@ -716,6 +716,7 @@
 ///   '__is_sealed'   [MS]
 ///   '__is_trivial'
 ///   '__is_union'
+///   '__has_unique_object_representations'
 ///
 /// [Clang] unary-type-trait:
 ///   '__is_aggregate'
Index: lib/AST/Type.cpp
===
--- lib/AST/Type.cpp
+++ lib/AST/Type.cpp
@@ -2166,6 +2166,89 @@
   return false;
 }
 
+bool QualType::hasUniqueObjectRepresentations(const ASTContext &Context) const {
+  // C++17 [meta.unary.prop]:
+  //   The predicate condition for a template specialization
+  //   has_unique_object_representations shall be
+  //   satisfied if and only if:
+  // (9.1) — T is trivially copyable, and
+  // (9.2) — any two objects of type T with the same value have the same
+  // object representation, where two objects
+  //   of array or non-union class type are considered to have the same value
+  //   if their respective sequences of
+  //   direct subobjects have the same values, and two objects of union type
+  //   are considered to have the same
+  //   value if they have the same active member and the corresponding members
+  //   have the same value.
+  //   The set of scalar types for which this condition holds is
+  //   implementation-defined. [ Note: If a type has padding
+  //   bits, the condition does not hold; otherwise, the condition holds true
+  //   for unsigned integral types. — end
+  //   note ]
+  if (isNull())
+return false;
+
+  // Arrays are unique only if their element type is unique.
+  if ((*this)->isArrayType())
+return Context.getBaseElementType(*this).hasUniqueObjectRepresentations(
+Context);
+
+  // (9.1) — T is trivially copyable, and
+  if (!isTriviallyCopyableType(Context))
+return false;
+
+  // Functions are not unique.
+  if ((*this)->isFunctionType())
+return false;
+
+  // All integrals and enums are unique!
+  if ((*this)->isIntegralOrEnumerationType())
+return true;
+
+  // All pointers are unique, since they're just integrals.
+  if ((*this)->isPointerType() || (*this)->isMemberPointerType())
+return true;
+
+  if ((*this)->isRecordType()) {
+const RecordDecl *Record = getTypePtr()->getAs()->getDecl();
+
+// Lambda types are not unique, so exclude them immediately.
+if (Record->isLambda())
+  return false;
+
+// Empty types are not unique.
+if (Record->field_empty())
+  return false;
+
+CharUnits RecordSize = Context.getTypeSizeInChars(*this);
+CharUnits CurOffset = Context.toCharUnitsFromBits(
+Context.getFieldOffset(*Record->field_begin()));
+for (const auto *Field : Record->fields()) {
+  if (!Field->getType().hasUniqueObjectRepresentations(Context))
+return false;
+
+  // Check for padding.
+  CharUnits FieldSize = Context.getTypeSizeInChars(Field->getType());
+  if (Record->isUnion() && FieldSize != RecordSize)
+return false;
+  else if (!Record->isUnion()) {
+CharUnits FieldOffset =
+Context.toCharUnitsFromBits(Context.getFieldOffset(Field));
+if (FieldOffset != CurOffset)
+  return false;
+CurOffset += FieldSize;
+  }
+}
+
+// struct/class with tail padding.
+if (!Record->isUnion() && CurOffset != RecordSize)
+  return false;
+
+return true;
+  }
+  return false;
+}
+
 bool QualType::isNonWeakInMRRWithObjCWeak(const ASTContext &Context) const {
   return !Context.getLangOpts().ObjCAutoRefCount &&
  Context.getLangOpts().ObjCWeak &&
Index: lib/Sema/SemaExprCXX.cpp
===
--- lib/Sema/SemaExprCXX.cpp
+++ lib/Sema/SemaExprCXX.cpp
@@ -4175,6 +4175,7 @@
   case UTT_IsDestructible:
   case UTT_IsNothrowDestructible:
   case UTT_IsTriviallyDestructible:
+  case UTT_HasUniqueObjectRepresentations:
 if (ArgTy->isIncompleteArrayType() || ArgTy->isVoidType())
   return true;
 
@@ -4614,6 +4615,8 @@
 //   Returns True if and only if T is a complete type at the point of the
 //   function call.
 return !T->isIncompleteType();
+  case UTT_HasUniqueObjectRepresentations:
+return T.hasUniqueObjectRepresentations(C);
   }
 }
 
Index: include/clang/AST/Type.h
===
--- include/clang/AST/Type.h
+++ include/clang/AST/Type.h
@@ -770,6 +770,10 @@
   /// Return true if this is a

[PATCH] D39075: Fix nodiscard for volatile references

2017-10-18 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman added inline comments.



Comment at: lib/AST/Expr.cpp:2302
+  cast(DRE->getDecl())->hasLocalStorage()) &&
+!isa(CE->getSubExpr()->IgnoreParens())) {
   return CE->getSubExpr()->isUnusedResultAWarning(WarnE, Loc,

Does this properly handle calls through function pointers (which usually have 
implicit casts)?
```
[[nodiscard]] volatile char &(*fp)();
void g() {
  (void)fp(); // No diagnostic here, either?
}
```


https://reviews.llvm.org/D39075



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


[PATCH] D39064: implement __has_unique_object_representations

2017-10-18 Thread Stephan T. Lavavej via Phabricator via cfe-commits
STL_MSFT added a comment.

Looks good to me modulo comments.




Comment at: lib/Parse/ParseExpr.cpp:719
 ///   '__is_union'
+///   '__has_unique_object_representations'   [MS]
 ///

Should this be marked as MS if it's cross-vendor?



Comment at: test/SemaCXX/type-traits.cpp:2403
+static_assert(has_unique_object_representations::value, "yes, all 
integral types");
+static_assert(has_unique_object_representations::value, "and pointer to 
members");
+static_assert(has_unique_object_representations::value, "and 
pointer to members");

char is a pointer to member! What a world. (ditto below)



Comment at: test/SemaCXX/type-traits.cpp:2420
+static_assert(!has_unique_object_representations::value, 
"or nullptr_t");
+static_assert(!has_unique_object_representations::value, "definitely 
not FP");
+static_assert(!has_unique_object_representations::value, "definitely 
not FP");

The use of "FP" to mean "floating point" is a little confusing given the FP 
typedef for Function Pointer above.


https://reviews.llvm.org/D39064



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


r316132 - Fix capitalization of parameter

2017-10-18 Thread Erich Keane via cfe-commits
Author: erichkeane
Date: Wed Oct 18 15:17:16 2017
New Revision: 316132

URL: http://llvm.org/viewvc/llvm-project?rev=316132&view=rev
Log:
Fix capitalization of parameter

The .cpp file has this properly capitalized, but 
the header does not.  Simply fixed it.

Modified:
cfe/trunk/include/clang/AST/ASTContext.h

Modified: cfe/trunk/include/clang/AST/ASTContext.h
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/AST/ASTContext.h?rev=316132&r1=316131&r2=316132&view=diff
==
--- cfe/trunk/include/clang/AST/ASTContext.h (original)
+++ cfe/trunk/include/clang/AST/ASTContext.h Wed Oct 18 15:17:16 2017
@@ -2229,7 +2229,7 @@ public:
   getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) const;
 
   /// \brief Retrieves the default calling convention for the current target.
-  CallingConv getDefaultCallingConvention(bool isVariadic,
+  CallingConv getDefaultCallingConvention(bool IsVariadic,
   bool IsCXXMethod) const;
 
   /// \brief Retrieves the "canonical" template name that refers to a


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


[PATCH] D39024: [clang-format] Sort whole block of using declarations while partially formatting

2017-10-18 Thread Krasimir Georgiev via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rL316130: [clang-format] Sort whole block of using 
declarations while partially formatting (authored by krasimir).

Repository:
  rL LLVM

https://reviews.llvm.org/D39024

Files:
  cfe/trunk/lib/Format/UsingDeclarationsSorter.cpp
  cfe/trunk/unittests/Format/UsingDeclarationsSorterTest.cpp


Index: cfe/trunk/unittests/Format/UsingDeclarationsSorterTest.cpp
===
--- cfe/trunk/unittests/Format/UsingDeclarationsSorterTest.cpp
+++ cfe/trunk/unittests/Format/UsingDeclarationsSorterTest.cpp
@@ -291,13 +291,41 @@
 }
 
 TEST_F(UsingDeclarationsSorterTest, SortsPartialRangeOfUsingDeclarations) {
-  EXPECT_EQ("using b;\n"
-"using a;\n"
+  // Sorts the whole block of using declarations surrounding the range.
+  EXPECT_EQ("using a;\n"
+"using b;\n"
 "using c;",
 sortUsingDeclarations("using b;\n"
   "using c;\n" // starts at offset 10
   "using a;",
   {tooling::Range(10, 15)}));
+  EXPECT_EQ("using a;\n"
+"using b;\n"
+"using c;\n"
+"using A = b;",
+sortUsingDeclarations("using b;\n"
+  "using c;\n" // starts at offset 10
+  "using a;\n"
+  "using A = b;",
+  {tooling::Range(10, 15)}));
+
+  EXPECT_EQ("using d;\n"
+"using c;\n"
+"\n"
+"using a;\n"
+"using b;\n"
+"\n"
+"using f;\n"
+"using e;",
+sortUsingDeclarations("using d;\n"
+  "using c;\n"
+  "\n"
+  "using b;\n" // starts at offset 19
+  "using a;\n"
+  "\n"
+  "using f;\n"
+  "using e;",
+  {tooling::Range(19, 1)}));
 }
 
 } // end namespace
Index: cfe/trunk/lib/Format/UsingDeclarationsSorter.cpp
===
--- cfe/trunk/lib/Format/UsingDeclarationsSorter.cpp
+++ cfe/trunk/lib/Format/UsingDeclarationsSorter.cpp
@@ -76,6 +76,17 @@
 void endUsingDeclarationBlock(
 SmallVectorImpl *UsingDeclarations,
 const SourceManager &SourceMgr, tooling::Replacements *Fixes) {
+  bool BlockAffected = false;
+  for (const UsingDeclaration& Declaration : *UsingDeclarations) {
+if (Declaration.Line->Affected) {
+  BlockAffected = true;
+  break;
+}
+  }
+  if (!BlockAffected) {
+UsingDeclarations->clear();
+return;
+  }
   SmallVector SortedUsingDeclarations(
   UsingDeclarations->begin(), UsingDeclarations->end());
   std::stable_sort(SortedUsingDeclarations.begin(),
@@ -122,7 +133,7 @@
   tooling::Replacements Fixes;
   SmallVector UsingDeclarations;
   for (size_t I = 0, E = AnnotatedLines.size(); I != E; ++I) {
-if (!AnnotatedLines[I]->Affected || AnnotatedLines[I]->InPPDirective ||
+if (AnnotatedLines[I]->InPPDirective ||
 !AnnotatedLines[I]->startsWith(tok::kw_using) ||
 AnnotatedLines[I]->First->Finalized) {
   endUsingDeclarationBlock(&UsingDeclarations, SourceMgr, &Fixes);


Index: cfe/trunk/unittests/Format/UsingDeclarationsSorterTest.cpp
===
--- cfe/trunk/unittests/Format/UsingDeclarationsSorterTest.cpp
+++ cfe/trunk/unittests/Format/UsingDeclarationsSorterTest.cpp
@@ -291,13 +291,41 @@
 }
 
 TEST_F(UsingDeclarationsSorterTest, SortsPartialRangeOfUsingDeclarations) {
-  EXPECT_EQ("using b;\n"
-"using a;\n"
+  // Sorts the whole block of using declarations surrounding the range.
+  EXPECT_EQ("using a;\n"
+"using b;\n"
 "using c;",
 sortUsingDeclarations("using b;\n"
   "using c;\n" // starts at offset 10
   "using a;",
   {tooling::Range(10, 15)}));
+  EXPECT_EQ("using a;\n"
+"using b;\n"
+"using c;\n"
+"using A = b;",
+sortUsingDeclarations("using b;\n"
+  "using c;\n" // starts at offset 10
+  "using a;\n"
+  "using A = b;",
+  {tooling::Range(10, 15)}));
+
+  EXPECT_EQ("using d;\n"
+"using c;\n"
+"\n"
+"using a;\n"
+"using b;\n"
+"\n"
+"using f;\n"
+"using e;",
+sortUsingDeclarations("using d;\n"
+  "using c;\n"
+ 

r316130 - [clang-format] Sort whole block of using declarations while partially formatting

2017-10-18 Thread Krasimir Georgiev via cfe-commits
Author: krasimir
Date: Wed Oct 18 15:13:25 2017
New Revision: 316130

URL: http://llvm.org/viewvc/llvm-project?rev=316130&view=rev
Log:
[clang-format] Sort whole block of using declarations while partially formatting

Summary:
This patch enables sorting the full block of using declarations when
some line is affected.

Reviewers: djasper

Reviewed By: djasper

Subscribers: cfe-commits, klimek

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

Modified:
cfe/trunk/lib/Format/UsingDeclarationsSorter.cpp
cfe/trunk/unittests/Format/UsingDeclarationsSorterTest.cpp

Modified: cfe/trunk/lib/Format/UsingDeclarationsSorter.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Format/UsingDeclarationsSorter.cpp?rev=316130&r1=316129&r2=316130&view=diff
==
--- cfe/trunk/lib/Format/UsingDeclarationsSorter.cpp (original)
+++ cfe/trunk/lib/Format/UsingDeclarationsSorter.cpp Wed Oct 18 15:13:25 2017
@@ -76,6 +76,17 @@ std::string computeUsingDeclarationLabel
 void endUsingDeclarationBlock(
 SmallVectorImpl *UsingDeclarations,
 const SourceManager &SourceMgr, tooling::Replacements *Fixes) {
+  bool BlockAffected = false;
+  for (const UsingDeclaration& Declaration : *UsingDeclarations) {
+if (Declaration.Line->Affected) {
+  BlockAffected = true;
+  break;
+}
+  }
+  if (!BlockAffected) {
+UsingDeclarations->clear();
+return;
+  }
   SmallVector SortedUsingDeclarations(
   UsingDeclarations->begin(), UsingDeclarations->end());
   std::stable_sort(SortedUsingDeclarations.begin(),
@@ -122,7 +133,7 @@ tooling::Replacements UsingDeclarationsS
   tooling::Replacements Fixes;
   SmallVector UsingDeclarations;
   for (size_t I = 0, E = AnnotatedLines.size(); I != E; ++I) {
-if (!AnnotatedLines[I]->Affected || AnnotatedLines[I]->InPPDirective ||
+if (AnnotatedLines[I]->InPPDirective ||
 !AnnotatedLines[I]->startsWith(tok::kw_using) ||
 AnnotatedLines[I]->First->Finalized) {
   endUsingDeclarationBlock(&UsingDeclarations, SourceMgr, &Fixes);

Modified: cfe/trunk/unittests/Format/UsingDeclarationsSorterTest.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/unittests/Format/UsingDeclarationsSorterTest.cpp?rev=316130&r1=316129&r2=316130&view=diff
==
--- cfe/trunk/unittests/Format/UsingDeclarationsSorterTest.cpp (original)
+++ cfe/trunk/unittests/Format/UsingDeclarationsSorterTest.cpp Wed Oct 18 
15:13:25 2017
@@ -291,13 +291,41 @@ TEST_F(UsingDeclarationsSorterTest, Supp
 }
 
 TEST_F(UsingDeclarationsSorterTest, SortsPartialRangeOfUsingDeclarations) {
-  EXPECT_EQ("using b;\n"
-"using a;\n"
+  // Sorts the whole block of using declarations surrounding the range.
+  EXPECT_EQ("using a;\n"
+"using b;\n"
 "using c;",
 sortUsingDeclarations("using b;\n"
   "using c;\n" // starts at offset 10
   "using a;",
   {tooling::Range(10, 15)}));
+  EXPECT_EQ("using a;\n"
+"using b;\n"
+"using c;\n"
+"using A = b;",
+sortUsingDeclarations("using b;\n"
+  "using c;\n" // starts at offset 10
+  "using a;\n"
+  "using A = b;",
+  {tooling::Range(10, 15)}));
+
+  EXPECT_EQ("using d;\n"
+"using c;\n"
+"\n"
+"using a;\n"
+"using b;\n"
+"\n"
+"using f;\n"
+"using e;",
+sortUsingDeclarations("using d;\n"
+  "using c;\n"
+  "\n"
+  "using b;\n" // starts at offset 19
+  "using a;\n"
+  "\n"
+  "using f;\n"
+  "using e;",
+  {tooling::Range(19, 1)}));
 }
 
 } // end namespace


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


[PATCH] D39075: Fix nodiscard for volatile references

2017-10-18 Thread Erich Keane via Phabricator via cfe-commits
erichkeane created this revision.

As reported here https://bugs.llvm.org/show_bug.cgi?id=34988
[[nodiscard]] warnings were not being suppressed for 
volatile-ref return values.


https://reviews.llvm.org/D39075

Files:
  lib/AST/Expr.cpp
  test/CXX/dcl.dcl/dcl.attr/dcl.attr.nodiscard/p2.cpp


Index: lib/AST/Expr.cpp
===
--- lib/AST/Expr.cpp
+++ lib/AST/Expr.cpp
@@ -2298,7 +2298,8 @@
 const DeclRefExpr *DRE =
 dyn_cast(CE->getSubExpr()->IgnoreParens());
 if (!(DRE && isa(DRE->getDecl()) &&
-  cast(DRE->getDecl())->hasLocalStorage())) {
+  cast(DRE->getDecl())->hasLocalStorage()) &&
+!isa(CE->getSubExpr()->IgnoreParens())) {
   return CE->getSubExpr()->isUnusedResultAWarning(WarnE, Loc,
   R1, R2, Ctx);
 }
Index: test/CXX/dcl.dcl/dcl.attr/dcl.attr.nodiscard/p2.cpp
===
--- test/CXX/dcl.dcl/dcl.attr/dcl.attr.nodiscard/p2.cpp
+++ test/CXX/dcl.dcl/dcl.attr/dcl.attr.nodiscard/p2.cpp
@@ -9,21 +9,25 @@
 E get_e();
 
 [[nodiscard]] int get_i();
+[[nodiscard]] volatile int &get_vi();
 
 void f() {
   get_s(); // expected-warning {{ignoring return value of function declared 
with 'nodiscard' attribute}}
   get_i(); // expected-warning {{ignoring return value of function declared 
with 'nodiscard' attribute}}
+  get_vi(); // expected-warning {{ignoring return value of function declared 
with 'nodiscard' attribute}}
   get_e(); // expected-warning {{ignoring return value of function declared 
with 'nodiscard' attribute}}
 
   // Okay, warnings are not encouraged
   get_s_ref();
   (void)get_s();
   (void)get_i();
+  (void)get_vi();
   (void)get_e();
 }
 
 #ifdef EXT
 // expected-warning@4 {{use of the 'nodiscard' attribute is a C++17 extension}}
 // expected-warning@8 {{use of the 'nodiscard' attribute is a C++17 extension}}
 // expected-warning@11 {{use of the 'nodiscard' attribute is a C++17 
extension}}
+// expected-warning@12 {{use of the 'nodiscard' attribute is a C++17 
extension}}
 #endif


Index: lib/AST/Expr.cpp
===
--- lib/AST/Expr.cpp
+++ lib/AST/Expr.cpp
@@ -2298,7 +2298,8 @@
 const DeclRefExpr *DRE =
 dyn_cast(CE->getSubExpr()->IgnoreParens());
 if (!(DRE && isa(DRE->getDecl()) &&
-  cast(DRE->getDecl())->hasLocalStorage())) {
+  cast(DRE->getDecl())->hasLocalStorage()) &&
+!isa(CE->getSubExpr()->IgnoreParens())) {
   return CE->getSubExpr()->isUnusedResultAWarning(WarnE, Loc,
   R1, R2, Ctx);
 }
Index: test/CXX/dcl.dcl/dcl.attr/dcl.attr.nodiscard/p2.cpp
===
--- test/CXX/dcl.dcl/dcl.attr/dcl.attr.nodiscard/p2.cpp
+++ test/CXX/dcl.dcl/dcl.attr/dcl.attr.nodiscard/p2.cpp
@@ -9,21 +9,25 @@
 E get_e();
 
 [[nodiscard]] int get_i();
+[[nodiscard]] volatile int &get_vi();
 
 void f() {
   get_s(); // expected-warning {{ignoring return value of function declared with 'nodiscard' attribute}}
   get_i(); // expected-warning {{ignoring return value of function declared with 'nodiscard' attribute}}
+  get_vi(); // expected-warning {{ignoring return value of function declared with 'nodiscard' attribute}}
   get_e(); // expected-warning {{ignoring return value of function declared with 'nodiscard' attribute}}
 
   // Okay, warnings are not encouraged
   get_s_ref();
   (void)get_s();
   (void)get_i();
+  (void)get_vi();
   (void)get_e();
 }
 
 #ifdef EXT
 // expected-warning@4 {{use of the 'nodiscard' attribute is a C++17 extension}}
 // expected-warning@8 {{use of the 'nodiscard' attribute is a C++17 extension}}
 // expected-warning@11 {{use of the 'nodiscard' attribute is a C++17 extension}}
+// expected-warning@12 {{use of the 'nodiscard' attribute is a C++17 extension}}
 #endif
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D39074: [libunwind][MIPS]: Add support for unwinding in N32 processes.

2017-10-18 Thread John Baldwin via Phabricator via cfe-commits
bsdjhb created this revision.
Herald added subscribers: JDevlieghere, arichardson, aprantl.

N32 uses the same register context as N64.  However, N32 requires one
change to properly fetch addresses from registers stored in memory.
Since N32 is an ILP32 platform, getP() only fetches the first 32-bits
of a stored register.  For a big-endian platform this fetches the
upper 32-bits which will be zero.  To fix this, add a new
getRegister() method to AddressSpace which is responsible for
extracting the address stored in a register in memory.  This matches
getP() for all current ABIs except for N32 where it reads the 64-bit
register and returns the low 32-bits as an address.  The
DwarfInstructions::getSavedRegister() method uses
AddressSpace::getRegister() instead of AddressSpace::getP().

Possibly, DwarfInstructions::getSavedRegister()'s return type should
be changed from pint_t to uint64_t.


https://reviews.llvm.org/D39074

Files:
  include/__libunwind_config.h
  src/AddressSpace.hpp
  src/DwarfInstructions.hpp
  src/UnwindRegistersRestore.S
  src/UnwindRegistersSave.S
  src/libunwind.cpp

Index: src/libunwind.cpp
===
--- src/libunwind.cpp
+++ src/libunwind.cpp
@@ -60,6 +60,8 @@
 # define REGISTER_KIND Registers_or1k
 #elif defined(__mips__) && defined(_ABIO32) && defined(__mips_soft_float)
 # define REGISTER_KIND Registers_mips_o32
+#elif defined(__mips__) && defined(_ABIN32) && defined(__mips_soft_float)
+# define REGISTER_KIND Registers_mips_n64
 #elif defined(__mips__) && defined(_ABI64) && defined(__mips_soft_float)
 # define REGISTER_KIND Registers_mips_n64
 #elif defined(__mips__)
Index: src/UnwindRegistersSave.S
===
--- src/UnwindRegistersSave.S
+++ src/UnwindRegistersSave.S
@@ -143,7 +143,7 @@
   or$2, $0, $0
   .set pop
 
-#elif defined(__mips__) && defined(_ABI64) && defined(__mips_soft_float)
+#elif defined(__mips__) && (defined(_ABI64) || defined(_ABIN32)) && defined(__mips_soft_float)
 
 #
 # extern int unw_getcontext(unw_context_t* thread_state)
Index: src/UnwindRegistersRestore.S
===
--- src/UnwindRegistersRestore.S
+++ src/UnwindRegistersRestore.S
@@ -545,7 +545,7 @@
   lw$4, (4 * 4)($4)
   .set pop
 
-#elif defined(__mips__) && defined(_ABI64) && defined(__mips_soft_float)
+#elif defined(__mips__) && (defined(_ABI64) || defined(_ABIN32)) && defined(__mips_soft_float)
 
 //
 // void libunwind::Registers_mips_n64::jumpto()
Index: src/DwarfInstructions.hpp
===
--- src/DwarfInstructions.hpp
+++ src/DwarfInstructions.hpp
@@ -82,10 +82,10 @@
 const RegisterLocation &savedReg) {
   switch (savedReg.location) {
   case CFI_Parser::kRegisterInCFA:
-return addressSpace.getP(cfa + (pint_t)savedReg.value);
+return addressSpace.getRegister(cfa + (pint_t)savedReg.value);
 
   case CFI_Parser::kRegisterAtExpression:
-return addressSpace.getP(
+return addressSpace.getRegister(
 evaluateExpression((pint_t)savedReg.value, addressSpace,
 registers, cfa));
 
Index: src/AddressSpace.hpp
===
--- src/AddressSpace.hpp
+++ src/AddressSpace.hpp
@@ -175,6 +175,7 @@
 return val;
   }
   uintptr_t   getP(pint_t addr);
+  uint64_tgetRegister(pint_t addr);
   static uint64_t getULEB128(pint_t &addr, pint_t end);
   static int64_t  getSLEB128(pint_t &addr, pint_t end);
 
@@ -196,6 +197,14 @@
 #endif
 }
 
+inline uint64_t LocalAddressSpace::getRegister(pint_t addr) {
+#if defined(__LP64__) || defined(__mips_n32)
+  return get64(addr);
+#else
+  return get32(addr);
+#endif
+}
+
 /// Read a ULEB128 into a 64-bit word.
 inline uint64_t LocalAddressSpace::getULEB128(pint_t &addr, pint_t end) {
   const uint8_t *p = (uint8_t *)addr;
@@ -511,6 +520,7 @@
   uint32_t  get32(pint_t addr);
   uint64_t  get64(pint_t addr);
   pint_tgetP(pint_t addr);
+  uint64_t  getRegister(pint_t addr);
   uint64_t  getULEB128(pint_t &addr, pint_t end);
   int64_t   getSLEB128(pint_t &addr, pint_t end);
   pint_tgetEncodedP(pint_t &addr, pint_t end, uint8_t encoding,
@@ -547,7 +557,12 @@
 }
 
 template 
-uint64_t RemoteAddressSpace::getULEB128(pint_t &addr, pint_t end) {
+typename P::uint_t OtherAddressSpace::getRegister(pint_t addr) {
+  return P::getRegister(*(uint64_t *)localCopy(addr));
+}
+
+template 
+uint64_t OtherAddressSpace::getULEB128(pint_t &addr, pint_t end) {
   uintptr_t size = (end - addr);
   LocalAddressSpace::pint_t laddr = (LocalAddressSpace::pint_t) localCopy(addr);
   LocalAddressSpace::pint_t sladdr = laddr;
Index: include/__libunwind_config.h
===
--- include/__libunwind_config.h
+++ include/__libunwind_config.h
@@ -56,6 +56,11 @@
 #  define _LIBUNWIND_CONTEXT_SIZE

r316127 - [Driver] Fix use after free in Hexagon toolchain code.

2017-10-18 Thread Benjamin Kramer via cfe-commits
Author: d0k
Date: Wed Oct 18 14:43:42 2017
New Revision: 316127

URL: http://llvm.org/viewvc/llvm-project?rev=316127&view=rev
Log:
[Driver] Fix use after free in Hexagon toolchain code.

No functionality change intended.

Modified:
cfe/trunk/lib/Driver/ToolChains/Hexagon.cpp

Modified: cfe/trunk/lib/Driver/ToolChains/Hexagon.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Driver/ToolChains/Hexagon.cpp?rev=316127&r1=316126&r2=316127&view=diff
==
--- cfe/trunk/lib/Driver/ToolChains/Hexagon.cpp (original)
+++ cfe/trunk/lib/Driver/ToolChains/Hexagon.cpp Wed Oct 18 14:43:42 2017
@@ -28,8 +28,8 @@ using namespace clang;
 using namespace llvm::opt;
 
 // Default hvx-length for various versions.
-static std::string getDefaultHvxLength(const StringRef &Cpu) {
-  return llvm::StringSwitch(Cpu)
+static StringRef getDefaultHvxLength(StringRef Cpu) {
+  return llvm::StringSwitch(Cpu)
   .Case("v60", "64b")
   .Case("v62", "64b")
   .Default("128b");
@@ -93,7 +93,7 @@ static void handleHVXTargetFeatures(cons
   }
   // Default hvx-length based on Cpu.
   else if (HasHVX)
-HVXLength = StringRef(getDefaultHvxLength(Cpu));
+HVXLength = getDefaultHvxLength(Cpu);
 
   if (!HVXLength.empty()) {
 HVXFeature =


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


[PATCH] D39071: [Hexagon] Fix the memory-leak in r316102

2017-10-18 Thread Sumanth Gundapaneni via Phabricator via cfe-commits
sgundapa created this revision.

Repository:
  rL LLVM

https://reviews.llvm.org/D39071

Files:
  lib/Driver/ToolChains/Hexagon.cpp


Index: lib/Driver/ToolChains/Hexagon.cpp
===
--- lib/Driver/ToolChains/Hexagon.cpp
+++ lib/Driver/ToolChains/Hexagon.cpp
@@ -59,7 +59,8 @@
   handleHVXWarnings(D, Args);
 
   // Add the +hvx* features based on commandline flags.
-  StringRef HVXFeature, HVXLength;
+  StringRef HVXFeature;
+  std::string HVXLength;
   StringRef Cpu(toolchains::HexagonToolChain::GetTargetCPUVersion(Args));
 
   // Handle -mhvx, -mhvx=, -mno-hvx, -mno-hvx-double.
@@ -87,17 +88,17 @@
 if (!HasHVX)
   D.Diag(diag::err_drv_invalid_hvx_length);
 else if (A->getOption().matches(options::OPT_mhexagon_hvx_length_EQ))
-  HVXLength = A->getValue();
+  HVXLength = StringRef(A->getValue()).lower();
 else if (A->getOption().matches(options::OPT_mhexagon_hvx_double))
   HVXLength = "128b";
   }
   // Default hvx-length based on Cpu.
   else if (HasHVX)
-HVXLength = StringRef(getDefaultHvxLength(Cpu));
+HVXLength = getDefaultHvxLength(Cpu);
 
   if (!HVXLength.empty()) {
 HVXFeature =
-Args.MakeArgString(llvm::Twine("+hvx-length") + HVXLength.lower());
+Args.MakeArgString(llvm::Twine("+hvx-length") + HVXLength);
 Features.push_back(HVXFeature);
   }
 }


Index: lib/Driver/ToolChains/Hexagon.cpp
===
--- lib/Driver/ToolChains/Hexagon.cpp
+++ lib/Driver/ToolChains/Hexagon.cpp
@@ -59,7 +59,8 @@
   handleHVXWarnings(D, Args);
 
   // Add the +hvx* features based on commandline flags.
-  StringRef HVXFeature, HVXLength;
+  StringRef HVXFeature;
+  std::string HVXLength;
   StringRef Cpu(toolchains::HexagonToolChain::GetTargetCPUVersion(Args));
 
   // Handle -mhvx, -mhvx=, -mno-hvx, -mno-hvx-double.
@@ -87,17 +88,17 @@
 if (!HasHVX)
   D.Diag(diag::err_drv_invalid_hvx_length);
 else if (A->getOption().matches(options::OPT_mhexagon_hvx_length_EQ))
-  HVXLength = A->getValue();
+  HVXLength = StringRef(A->getValue()).lower();
 else if (A->getOption().matches(options::OPT_mhexagon_hvx_double))
   HVXLength = "128b";
   }
   // Default hvx-length based on Cpu.
   else if (HasHVX)
-HVXLength = StringRef(getDefaultHvxLength(Cpu));
+HVXLength = getDefaultHvxLength(Cpu);
 
   if (!HVXLength.empty()) {
 HVXFeature =
-Args.MakeArgString(llvm::Twine("+hvx-length") + HVXLength.lower());
+Args.MakeArgString(llvm::Twine("+hvx-length") + HVXLength);
 Features.push_back(HVXFeature);
   }
 }
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D39024: [clang-format] Sort whole block of using declarations while partially formatting

2017-10-18 Thread Daniel Jasper via Phabricator via cfe-commits
djasper accepted this revision.
djasper added a comment.
This revision is now accepted and ready to land.

LG.


https://reviews.llvm.org/D39024



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


[PATCH] D39069: CodeGen: Fix missing debug loc due to alloca

2017-10-18 Thread Yaxun Liu via Phabricator via cfe-commits
yaxunl created this revision.

Builder save/restores insertion pointer when emitting addr space cast
for alloca, but does not save/restore debug loc, which causes verifier
failure for certain call instructions.

This patch fixes that.


https://reviews.llvm.org/D39069

Files:
  lib/CodeGen/CGExpr.cpp
  test/CodeGenOpenCL/func-call-dbg-loc.cl


Index: test/CodeGenOpenCL/func-call-dbg-loc.cl
===
--- /dev/null
+++ test/CodeGenOpenCL/func-call-dbg-loc.cl
@@ -0,0 +1,34 @@
+// RUN: %clang_cc1 -triple amdgcn---amdgizcl -debug-info-kind=limited 
-dwarf-version=2 -debugger-tuning=gdb -O0 -emit-llvm -o - %s | FileCheck %s
+// Checks the file compiles without verifier error: inlinable function call in 
a function with debug info must have a !dbg location.
+
+typedef struct
+{
+float m_max;
+} Struct;
+
+typedef struct
+{
+Struct m_volume;
+} Node;
+
+
+Struct buzz(Node node)
+{
+return node.m_volume;
+}
+
+__attribute__((always_inline))
+float bar(Struct aabb)
+{
+return 0.0f;
+}
+
+__attribute__((used))
+void foo()
+{
+Node node;
+// CHECK: store float 0.00e+00, float addrspace(5)* %f, align 4, !dbg 
!{{[0-9]+}}
+float f = bar(buzz(node));
+}
+
+
Index: lib/CodeGen/CGExpr.cpp
===
--- lib/CodeGen/CGExpr.cpp
+++ lib/CodeGen/CGExpr.cpp
@@ -75,11 +75,13 @@
   if (CastToDefaultAddrSpace && getASTAllocaAddressSpace() != LangAS::Default) 
{
 auto DestAddrSpace = getContext().getTargetAddressSpace(LangAS::Default);
 auto CurIP = Builder.saveIP();
+auto DbgLoc = Builder.getCurrentDebugLocation();
 Builder.SetInsertPoint(AllocaInsertPt);
 V = getTargetHooks().performAddrSpaceCast(
 *this, V, getASTAllocaAddressSpace(), LangAS::Default,
 Ty->getPointerTo(DestAddrSpace), /*non-null*/ true);
 Builder.restoreIP(CurIP);
+Builder.SetCurrentDebugLocation(DbgLoc);
   }
 
   return Address(V, Align);


Index: test/CodeGenOpenCL/func-call-dbg-loc.cl
===
--- /dev/null
+++ test/CodeGenOpenCL/func-call-dbg-loc.cl
@@ -0,0 +1,34 @@
+// RUN: %clang_cc1 -triple amdgcn---amdgizcl -debug-info-kind=limited -dwarf-version=2 -debugger-tuning=gdb -O0 -emit-llvm -o - %s | FileCheck %s
+// Checks the file compiles without verifier error: inlinable function call in a function with debug info must have a !dbg location.
+
+typedef struct
+{
+float m_max;
+} Struct;
+
+typedef struct
+{
+Struct m_volume;
+} Node;
+
+
+Struct buzz(Node node)
+{
+return node.m_volume;
+}
+
+__attribute__((always_inline))
+float bar(Struct aabb)
+{
+return 0.0f;
+}
+
+__attribute__((used))
+void foo()
+{
+Node node;
+// CHECK: store float 0.00e+00, float addrspace(5)* %f, align 4, !dbg !{{[0-9]+}}
+float f = bar(buzz(node));
+}
+
+
Index: lib/CodeGen/CGExpr.cpp
===
--- lib/CodeGen/CGExpr.cpp
+++ lib/CodeGen/CGExpr.cpp
@@ -75,11 +75,13 @@
   if (CastToDefaultAddrSpace && getASTAllocaAddressSpace() != LangAS::Default) {
 auto DestAddrSpace = getContext().getTargetAddressSpace(LangAS::Default);
 auto CurIP = Builder.saveIP();
+auto DbgLoc = Builder.getCurrentDebugLocation();
 Builder.SetInsertPoint(AllocaInsertPt);
 V = getTargetHooks().performAddrSpaceCast(
 *this, V, getASTAllocaAddressSpace(), LangAS::Default,
 Ty->getPointerTo(DestAddrSpace), /*non-null*/ true);
 Builder.restoreIP(CurIP);
+Builder.SetCurrentDebugLocation(DbgLoc);
   }
 
   return Address(V, Align);
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D38985: [refactor] Add support for editor commands that connect IDEs/editors to the refactoring actions

2017-10-18 Thread Sam McCall via Phabricator via cfe-commits
sammccall added a comment.

Hi Alex! I'm working on clangd, but am pretty new to the project, so forgive 
some naive questions.

I'm a bit unclear at a high level what the new abstractions in this patch add, 
in terms of wiring refactorings up to clangd and other tools.
My understanding is: we have a hierarchy of refactorings consisting of actions 
(roughly: user intent?) and rules (roughly: implementations).

Clangd needs to be able to:

- enumerate the actions and their associated rules: possible via 
`createRefactoringActions()`
- find names for these (machine readable and human readable): possible at the 
`Action` level, not `Rule` yet
- determine whether rules can be applied and what configuration is needed: 
possible via the `Rule` API
- invoke rules: possible via the `Rule` API

So AFAICT, clangd could be hooked up to the existing Refactor API, without 
`EditorCommand` or `EditorClient`. What's the gain?


Repository:
  rL LLVM

https://reviews.llvm.org/D38985



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


[libcxx] r316125 - Fix a think-o in the design of the stable_XXX sort tests; only shows up for test cases > 255 elements

2017-10-18 Thread Marshall Clow via cfe-commits
Author: marshall
Date: Wed Oct 18 13:40:57 2017
New Revision: 316125

URL: http://llvm.org/viewvc/llvm-project?rev=316125&view=rev
Log:
Fix a think-o in the design of the stable_XXX sort tests; only shows up for 
test cases > 255 elements

Modified:
libcxx/trunk/fuzzing/fuzzing.cpp

Modified: libcxx/trunk/fuzzing/fuzzing.cpp
URL: 
http://llvm.org/viewvc/llvm-project/libcxx/trunk/fuzzing/fuzzing.cpp?rev=316125&r1=316124&r2=316125&view=diff
==
--- libcxx/trunk/fuzzing/fuzzing.cpp (original)
+++ libcxx/trunk/fuzzing/fuzzing.cpp Wed Oct 18 13:40:57 2017
@@ -37,10 +37,10 @@ namespace fuzzing {
 
 struct stable_test {
uint8_t key;
-   uint8_t payload;
+   size_t payload;

stable_test(uint8_t k) : key(k), payload(0) {}
-   stable_test(uint8_t k, uint8_t p) : key(k), payload(p) {}
+   stable_test(uint8_t k, size_t p) : key(k), payload(p) {}
};
 
 void swap(stable_test &lhs, stable_test &rhs)


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


[PATCH] D34272: [Tooling] A new framework for executing clang frontend actions.

2017-10-18 Thread Alex Lorenz via Phabricator via cfe-commits
arphaman added inline comments.



Comment at: include/clang/Tooling/StandaloneExecution.h:1
+//===--- Execution.h - Standalone clang action execution. -*- C++ 
---*-===//
+//

StandaloneExecution.h?


https://reviews.llvm.org/D34272



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


[PATCH] D39024: [clang-format] Sort whole block of using declarations while partially formatting

2017-10-18 Thread Krasimir Georgiev via Phabricator via cfe-commits
krasimir updated this revision to Diff 119518.
krasimir added a comment.

- Address review comments


https://reviews.llvm.org/D39024

Files:
  lib/Format/UsingDeclarationsSorter.cpp
  unittests/Format/UsingDeclarationsSorterTest.cpp


Index: unittests/Format/UsingDeclarationsSorterTest.cpp
===
--- unittests/Format/UsingDeclarationsSorterTest.cpp
+++ unittests/Format/UsingDeclarationsSorterTest.cpp
@@ -291,13 +291,41 @@
 }
 
 TEST_F(UsingDeclarationsSorterTest, SortsPartialRangeOfUsingDeclarations) {
-  EXPECT_EQ("using b;\n"
-"using a;\n"
+  // Sorts the whole block of using declarations surrounding the range.
+  EXPECT_EQ("using a;\n"
+"using b;\n"
 "using c;",
 sortUsingDeclarations("using b;\n"
   "using c;\n" // starts at offset 10
   "using a;",
   {tooling::Range(10, 15)}));
+  EXPECT_EQ("using a;\n"
+"using b;\n"
+"using c;\n"
+"using A = b;",
+sortUsingDeclarations("using b;\n"
+  "using c;\n" // starts at offset 10
+  "using a;\n"
+  "using A = b;",
+  {tooling::Range(10, 15)}));
+
+  EXPECT_EQ("using d;\n"
+"using c;\n"
+"\n"
+"using a;\n"
+"using b;\n"
+"\n"
+"using f;\n"
+"using e;",
+sortUsingDeclarations("using d;\n"
+  "using c;\n"
+  "\n"
+  "using b;\n" // starts at offset 19
+  "using a;\n"
+  "\n"
+  "using f;\n"
+  "using e;",
+  {tooling::Range(19, 1)}));
 }
 
 } // end namespace
Index: lib/Format/UsingDeclarationsSorter.cpp
===
--- lib/Format/UsingDeclarationsSorter.cpp
+++ lib/Format/UsingDeclarationsSorter.cpp
@@ -76,6 +76,17 @@
 void endUsingDeclarationBlock(
 SmallVectorImpl *UsingDeclarations,
 const SourceManager &SourceMgr, tooling::Replacements *Fixes) {
+  bool BlockAffected = false;
+  for (const UsingDeclaration& Declaration : *UsingDeclarations) {
+if (Declaration.Line->Affected) {
+  BlockAffected = true;
+  break;
+}
+  }
+  if (!BlockAffected) {
+UsingDeclarations->clear();
+return;
+  }
   SmallVector SortedUsingDeclarations(
   UsingDeclarations->begin(), UsingDeclarations->end());
   std::stable_sort(SortedUsingDeclarations.begin(),
@@ -122,7 +133,7 @@
   tooling::Replacements Fixes;
   SmallVector UsingDeclarations;
   for (size_t I = 0, E = AnnotatedLines.size(); I != E; ++I) {
-if (!AnnotatedLines[I]->Affected || AnnotatedLines[I]->InPPDirective ||
+if (AnnotatedLines[I]->InPPDirective ||
 !AnnotatedLines[I]->startsWith(tok::kw_using) ||
 AnnotatedLines[I]->First->Finalized) {
   endUsingDeclarationBlock(&UsingDeclarations, SourceMgr, &Fixes);


Index: unittests/Format/UsingDeclarationsSorterTest.cpp
===
--- unittests/Format/UsingDeclarationsSorterTest.cpp
+++ unittests/Format/UsingDeclarationsSorterTest.cpp
@@ -291,13 +291,41 @@
 }
 
 TEST_F(UsingDeclarationsSorterTest, SortsPartialRangeOfUsingDeclarations) {
-  EXPECT_EQ("using b;\n"
-"using a;\n"
+  // Sorts the whole block of using declarations surrounding the range.
+  EXPECT_EQ("using a;\n"
+"using b;\n"
 "using c;",
 sortUsingDeclarations("using b;\n"
   "using c;\n" // starts at offset 10
   "using a;",
   {tooling::Range(10, 15)}));
+  EXPECT_EQ("using a;\n"
+"using b;\n"
+"using c;\n"
+"using A = b;",
+sortUsingDeclarations("using b;\n"
+  "using c;\n" // starts at offset 10
+  "using a;\n"
+  "using A = b;",
+  {tooling::Range(10, 15)}));
+
+  EXPECT_EQ("using d;\n"
+"using c;\n"
+"\n"
+"using a;\n"
+"using b;\n"
+"\n"
+"using f;\n"
+"using e;",
+sortUsingDeclarations("using d;\n"
+  "using c;\n"
+  "\n"
+  "using b;\n" // starts at offset 19
+  "using a;\n"
+  "\n"
+  "using f;\n"
+ 

[PATCH] D39066: [libcxx] Fix signed overflow when constructing integers from brace expressions.

2017-10-18 Thread Tim Shen via Phabricator via cfe-commits
timshen created this revision.
Herald added a subscriber: sanjoy.
Herald added a reviewer: EricWF.

This should unblock PR24411.


https://reviews.llvm.org/D39066

Files:
  libcxx/include/regex
  libcxx/test/std/re/re.grammar/excessive_brace_count.pass.cpp


Index: libcxx/test/std/re/re.grammar/excessive_brace_count.pass.cpp
===
--- /dev/null
+++ libcxx/test/std/re/re.grammar/excessive_brace_count.pass.cpp
@@ -0,0 +1,40 @@
+//===--===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is dual licensed under the MIT and the University of Illinois Open
+// Source Licenses. See LICENSE.TXT for details.
+//
+//===--===//
+
+// 
+// UNSUPPORTED: libcpp-no-exceptions
+// UNSUPPORTED: c++03
+
+// the "n" in `a{n}` should be within the numeric limits.
+
+#include 
+#include 
+
+int main() {
+  for (std::regex_constants::syntax_option_type op :
+   {std::regex::basic, std::regex::grep}) {
+try {
+  (void)std::regex("a\\{10\\}", op);
+  assert(false);
+} catch (const std::regex_error &e) {
+  assert(e.code() == std::regex_constants::error_badbrace);
+}
+  }
+  for (std::regex_constants::syntax_option_type op :
+   {std::regex::ECMAScript, std::regex::extended, std::regex::egrep,
+std::regex::awk}) {
+try {
+  (void)std::regex("a{10}", op);
+  assert(false);
+} catch (const std::regex_error &e) {
+  assert(e.code() == std::regex_constants::error_badbrace);
+}
+  }
+  return 0;
+}
Index: libcxx/include/regex
===
--- libcxx/include/regex
+++ libcxx/include/regex
@@ -4064,6 +4064,8 @@
  __first != __last && ( __val = __traits_.value(*__first, 10)) 
!= -1;
  ++__first)
 {
+if (__c >= std::numeric_limits::max() / 10)
+  __throw_regex_error();
 __c *= 10;
 __c += __val;
 }


Index: libcxx/test/std/re/re.grammar/excessive_brace_count.pass.cpp
===
--- /dev/null
+++ libcxx/test/std/re/re.grammar/excessive_brace_count.pass.cpp
@@ -0,0 +1,40 @@
+//===--===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is dual licensed under the MIT and the University of Illinois Open
+// Source Licenses. See LICENSE.TXT for details.
+//
+//===--===//
+
+// 
+// UNSUPPORTED: libcpp-no-exceptions
+// UNSUPPORTED: c++03
+
+// the "n" in `a{n}` should be within the numeric limits.
+
+#include 
+#include 
+
+int main() {
+  for (std::regex_constants::syntax_option_type op :
+   {std::regex::basic, std::regex::grep}) {
+try {
+  (void)std::regex("a\\{10\\}", op);
+  assert(false);
+} catch (const std::regex_error &e) {
+  assert(e.code() == std::regex_constants::error_badbrace);
+}
+  }
+  for (std::regex_constants::syntax_option_type op :
+   {std::regex::ECMAScript, std::regex::extended, std::regex::egrep,
+std::regex::awk}) {
+try {
+  (void)std::regex("a{10}", op);
+  assert(false);
+} catch (const std::regex_error &e) {
+  assert(e.code() == std::regex_constants::error_badbrace);
+}
+  }
+  return 0;
+}
Index: libcxx/include/regex
===
--- libcxx/include/regex
+++ libcxx/include/regex
@@ -4064,6 +4064,8 @@
  __first != __last && ( __val = __traits_.value(*__first, 10)) != -1;
  ++__first)
 {
+if (__c >= std::numeric_limits::max() / 10)
+  __throw_regex_error();
 __c *= 10;
 __c += __val;
 }
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D38549: [clang-tidy] Link targets and Asm parsers

2017-10-18 Thread Alexander Kornienko via Phabricator via cfe-commits
alexfh added a comment.

Zachary, do you plan to commit this? I'd also suggest adding a regression test.

Thanks!


https://reviews.llvm.org/D38549



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


r316105 - [refactor] Add a doc comment to the test function in the selection

2017-10-18 Thread Alex Lorenz via cfe-commits
Author: arphaman
Date: Wed Oct 18 11:51:48 2017
New Revision: 316105

URL: http://llvm.org/viewvc/llvm-project?rev=316105&view=rev
Log:
[refactor] Add a doc comment to the test function in the selection
unittest.

As suggested by Haojian Wu!

Modified:
cfe/trunk/unittests/Tooling/ASTSelectionTest.cpp

Modified: cfe/trunk/unittests/Tooling/ASTSelectionTest.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/unittests/Tooling/ASTSelectionTest.cpp?rev=316105&r1=316104&r2=316105&view=diff
==
--- cfe/trunk/unittests/Tooling/ASTSelectionTest.cpp (original)
+++ cfe/trunk/unittests/Tooling/ASTSelectionTest.cpp Wed Oct 18 11:51:48 2017
@@ -59,6 +59,11 @@ public:
   }
 };
 
+/// This is a test utility function that computes the AST selection at the
+/// given location with an optional selection range.
+///
+/// A location roughly corresponds to a cursor location in an editor, while
+/// the optional range corresponds to the selection range in an editor.
 void findSelectedASTNodesWithRange(
 StringRef Source, FileLocation Location, Optional 
SelectionRange,
 llvm::function_refhttp://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D38835: [refactor] selection: new CodeRangeASTSelection represents a set of selected consecutive statements

2017-10-18 Thread Alex Lorenz via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rL316104: [refactor] selection: new CodeRangeASTSelection 
represents a set of selected (authored by arphaman).

Changed prior to commit:
  https://reviews.llvm.org/D38835?vs=119197&id=119514#toc

Repository:
  rL LLVM

https://reviews.llvm.org/D38835

Files:
  cfe/trunk/include/clang/Tooling/Refactoring/ASTSelection.h
  cfe/trunk/lib/Tooling/Refactoring/ASTSelection.cpp
  cfe/trunk/unittests/Tooling/ASTSelectionTest.cpp

Index: cfe/trunk/lib/Tooling/Refactoring/ASTSelection.cpp
===
--- cfe/trunk/lib/Tooling/Refactoring/ASTSelection.cpp
+++ cfe/trunk/lib/Tooling/Refactoring/ASTSelection.cpp
@@ -225,3 +225,108 @@
 }
 
 void SelectedASTNode::dump(llvm::raw_ostream &OS) const { ::dump(*this, OS); }
+
+/// Returns true if the given node has any direct children with the following
+/// selection kind.
+///
+/// Note: The direct children also include children of direct children with the
+/// "None" selection kind.
+static bool hasAnyDirectChildrenWithKind(const SelectedASTNode &Node,
+ SourceSelectionKind Kind) {
+  assert(Kind != SourceSelectionKind::None && "invalid predicate!");
+  for (const auto &Child : Node.Children) {
+if (Child.SelectionKind == Kind)
+  return true;
+if (Child.SelectionKind == SourceSelectionKind::None)
+  return hasAnyDirectChildrenWithKind(Child, Kind);
+  }
+  return false;
+}
+
+namespace {
+struct SelectedNodeWithParents {
+  SelectedNodeWithParents(SelectedNodeWithParents &&) = default;
+  SelectedNodeWithParents &operator=(SelectedNodeWithParents &&) = default;
+  SelectedASTNode::ReferenceType Node;
+  llvm::SmallVector Parents;
+};
+} // end anonymous namespace
+
+/// Finds the set of bottom-most selected AST nodes that are in the selection
+/// tree with the specified selection kind.
+///
+/// For example, given the following selection tree:
+///
+/// FunctionDecl "f" contains-selection
+///   CompoundStmt contains-selection [#1]
+/// CallExpr inside
+/// ImplicitCastExpr inside
+///   DeclRefExpr inside
+/// IntegerLiteral inside
+/// IntegerLiteral inside
+/// FunctionDecl "f2" contains-selection
+///   CompoundStmt contains-selection [#2]
+/// CallExpr inside
+/// ImplicitCastExpr inside
+///   DeclRefExpr inside
+/// IntegerLiteral inside
+/// IntegerLiteral inside
+///
+/// This function will find references to nodes #1 and #2 when searching for the
+/// \c ContainsSelection kind.
+static void findDeepestWithKind(
+const SelectedASTNode &ASTSelection,
+llvm::SmallVectorImpl &MatchingNodes,
+SourceSelectionKind Kind,
+llvm::SmallVectorImpl &ParentStack) {
+  if (!hasAnyDirectChildrenWithKind(ASTSelection, Kind)) {
+// This node is the bottom-most.
+MatchingNodes.push_back(SelectedNodeWithParents{
+std::cref(ASTSelection), {ParentStack.begin(), ParentStack.end()}});
+return;
+  }
+  // Search in the children.
+  ParentStack.push_back(std::cref(ASTSelection));
+  for (const auto &Child : ASTSelection.Children)
+findDeepestWithKind(Child, MatchingNodes, Kind, ParentStack);
+  ParentStack.pop_back();
+}
+
+static void findDeepestWithKind(
+const SelectedASTNode &ASTSelection,
+llvm::SmallVectorImpl &MatchingNodes,
+SourceSelectionKind Kind) {
+  llvm::SmallVector ParentStack;
+  findDeepestWithKind(ASTSelection, MatchingNodes, Kind, ParentStack);
+}
+
+Optional
+CodeRangeASTSelection::create(SourceRange SelectionRange,
+  const SelectedASTNode &ASTSelection) {
+  // Code range is selected when the selection range is not empty.
+  if (SelectionRange.getBegin() == SelectionRange.getEnd())
+return None;
+  llvm::SmallVector ContainSelection;
+  findDeepestWithKind(ASTSelection, ContainSelection,
+  SourceSelectionKind::ContainsSelection);
+  // We are looking for a selection in one body of code, so let's focus on
+  // one matching result.
+  if (ContainSelection.size() != 1)
+return None;
+  SelectedNodeWithParents &Selected = ContainSelection[0];
+  if (!Selected.Node.get().Node.get())
+return None;
+  const Stmt *CodeRangeStmt = Selected.Node.get().Node.get();
+  if (!isa(CodeRangeStmt)) {
+// FIXME (Alex L): Canonicalize.
+return CodeRangeASTSelection(Selected.Node, Selected.Parents,
+ /*AreChildrenSelected=*/false);
+  }
+  // FIXME (Alex L): Tweak selection rules for compound statements, see:
+  // https://github.com/apple/swift-clang/blob/swift-4.1-branch/lib/Tooling/
+  // Refactor/ASTSlice.cpp#L513
+  // The user selected multiple statements in a compound statement.
+  Selected.Parents.push_back(Selected.Node);
+  return CodeRangeASTSelection(Selected.Node, Selected.Parents,
+   /*AreChildrenSelected=*/true);
+}
Index: cfe/trunk/unittests/Tooling/AS

r316104 - [refactor] selection: new CodeRangeASTSelection represents a set of selected

2017-10-18 Thread Alex Lorenz via cfe-commits
Author: arphaman
Date: Wed Oct 18 11:48:58 2017
New Revision: 316104

URL: http://llvm.org/viewvc/llvm-project?rev=316104&view=rev
Log:
[refactor] selection: new CodeRangeASTSelection represents a set of selected
consecutive statements

This commit adds a CodeRangeASTSelection value to the refactoring library. This
value represents a set of selected statements in one body of code.

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

Modified:
cfe/trunk/include/clang/Tooling/Refactoring/ASTSelection.h
cfe/trunk/lib/Tooling/Refactoring/ASTSelection.cpp
cfe/trunk/unittests/Tooling/ASTSelectionTest.cpp

Modified: cfe/trunk/include/clang/Tooling/Refactoring/ASTSelection.h
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Tooling/Refactoring/ASTSelection.h?rev=316104&r1=316103&r2=316104&view=diff
==
--- cfe/trunk/include/clang/Tooling/Refactoring/ASTSelection.h (original)
+++ cfe/trunk/include/clang/Tooling/Refactoring/ASTSelection.h Wed Oct 18 
11:48:58 2017
@@ -59,6 +59,8 @@ struct SelectedASTNode {
   SelectedASTNode &operator=(SelectedASTNode &&) = default;
 
   void dump(llvm::raw_ostream &OS = llvm::errs()) const;
+
+  using ReferenceType = std::reference_wrapper;
 };
 
 /// Traverses the given ASTContext and creates a tree of selected AST nodes.
@@ -68,6 +70,70 @@ struct SelectedASTNode {
 Optional findSelectedASTNodes(const ASTContext &Context,
SourceRange SelectionRange);
 
+/// An AST selection value that corresponds to a selection of a set of
+/// statements that belong to one body of code (like one function).
+///
+/// For example, the following selection in the source.
+///
+/// \code
+/// void function() {
+///  // selection begin:
+///  int x = 0;
+///  {
+/// // selection end
+/// x = 1;
+///  }
+///  x = 2;
+/// }
+/// \endcode
+///
+/// Would correspond to a code range selection of statements "int x = 0"
+/// and the entire compound statement that follows it.
+///
+/// A \c CodeRangeASTSelection value stores references to the full
+/// \c SelectedASTNode tree and should not outlive it.
+class CodeRangeASTSelection {
+public:
+  CodeRangeASTSelection(CodeRangeASTSelection &&) = default;
+  CodeRangeASTSelection &operator=(CodeRangeASTSelection &&) = default;
+
+  /// Returns the parent hierarchy (top to bottom) for the selected nodes.
+  ArrayRef getParents() { return Parents; }
+
+  /// Returns the number of selected statements.
+  size_t size() const {
+if (!AreChildrenSelected)
+  return 1;
+return SelectedNode.get().Children.size();
+  }
+
+  const Stmt *operator[](size_t I) const {
+if (!AreChildrenSelected) {
+  assert(I == 0 && "Invalid index");
+  return SelectedNode.get().Node.get();
+}
+return SelectedNode.get().Children[I].Node.get();
+  }
+
+  static Optional
+  create(SourceRange SelectionRange, const SelectedASTNode &ASTSelection);
+
+private:
+  CodeRangeASTSelection(SelectedASTNode::ReferenceType SelectedNode,
+ArrayRef Parents,
+bool AreChildrenSelected)
+  : SelectedNode(SelectedNode), Parents(Parents.begin(), Parents.end()),
+AreChildrenSelected(AreChildrenSelected) {}
+
+  /// The reference to the selected node (or reference to the selected
+  /// child nodes).
+  SelectedASTNode::ReferenceType SelectedNode;
+  /// The parent hierarchy (top to bottom) for the selected noe.
+  llvm::SmallVector Parents;
+  /// True only when the children of the selected node are actually selected.
+  bool AreChildrenSelected;
+};
+
 } // end namespace tooling
 } // end namespace clang
 

Modified: cfe/trunk/lib/Tooling/Refactoring/ASTSelection.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Tooling/Refactoring/ASTSelection.cpp?rev=316104&r1=316103&r2=316104&view=diff
==
--- cfe/trunk/lib/Tooling/Refactoring/ASTSelection.cpp (original)
+++ cfe/trunk/lib/Tooling/Refactoring/ASTSelection.cpp Wed Oct 18 11:48:58 2017
@@ -225,3 +225,108 @@ static void dump(const SelectedASTNode &
 }
 
 void SelectedASTNode::dump(llvm::raw_ostream &OS) const { ::dump(*this, OS); }
+
+/// Returns true if the given node has any direct children with the following
+/// selection kind.
+///
+/// Note: The direct children also include children of direct children with the
+/// "None" selection kind.
+static bool hasAnyDirectChildrenWithKind(const SelectedASTNode &Node,
+ SourceSelectionKind Kind) {
+  assert(Kind != SourceSelectionKind::None && "invalid predicate!");
+  for (const auto &Child : Node.Children) {
+if (Child.SelectionKind == Kind)
+  return true;
+if (Child.SelectionKind == SourceSelectionKind::None)
+  return hasAnyDirectChildrenWithKind(Child, Kind);
+  }
+  return false;
+}
+
+namespace {
+struct SelectedNodeWithP

r316103 - [clang-proto-fuzzer] Use ToT protobuf-mutator.

2017-10-18 Thread Matt Morehouse via cfe-commits
Author: morehouse
Date: Wed Oct 18 11:38:04 2017
New Revision: 316103

URL: http://llvm.org/viewvc/llvm-project?rev=316103&view=rev
Log:
[clang-proto-fuzzer] Use ToT protobuf-mutator.

Modified:
cfe/trunk/cmake/modules/ProtobufMutator.cmake

Modified: cfe/trunk/cmake/modules/ProtobufMutator.cmake
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/cmake/modules/ProtobufMutator.cmake?rev=316103&r1=316102&r2=316103&view=diff
==
--- cfe/trunk/cmake/modules/ProtobufMutator.cmake (original)
+++ cfe/trunk/cmake/modules/ProtobufMutator.cmake Wed Oct 18 11:38:04 2017
@@ -6,7 +6,7 @@ set(PBM_FUZZ_LIB_PATH ${PBM_PATH}/src/li
 ExternalProject_Add(${PBM_PREFIX}
   PREFIX ${PBM_PREFIX}
   GIT_REPOSITORY https://github.com/google/libprotobuf-mutator.git
-  GIT_TAG e4eae60
+  GIT_TAG master
   CONFIGURE_COMMAND ${CMAKE_COMMAND} -G${CMAKE_GENERATOR}
 -DCMAKE_C_COMPILER=${CMAKE_C_COMPILER}
 -DCMAKE_CXX_COMPILER=${CMAKE_CXX_COMPILER}


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


[PATCH] D39024: [clang-format] Sort whole block of using declarations while partially formatting

2017-10-18 Thread Daniel Jasper via Phabricator via cfe-commits
djasper added inline comments.



Comment at: lib/Format/UsingDeclarationsSorter.cpp:79
 const SourceManager &SourceMgr, tooling::Replacements *Fixes) {
-  SmallVector SortedUsingDeclarations(
-  UsingDeclarations->begin(), UsingDeclarations->end());
-  std::stable_sort(SortedUsingDeclarations.begin(),
-   SortedUsingDeclarations.end());
-  for (size_t I = 0, E = UsingDeclarations->size(); I < E; ++I) {
-if ((*UsingDeclarations)[I].Line == SortedUsingDeclarations[I].Line)
-  continue;
-auto Begin = (*UsingDeclarations)[I].Line->First->Tok.getLocation();
-auto End = (*UsingDeclarations)[I].Line->Last->Tok.getEndLoc();
-auto SortedBegin =
-SortedUsingDeclarations[I].Line->First->Tok.getLocation();
-auto SortedEnd = SortedUsingDeclarations[I].Line->Last->Tok.getEndLoc();
-StringRef Text(SourceMgr.getCharacterData(SortedBegin),
-   SourceMgr.getCharacterData(SortedEnd) -
-   SourceMgr.getCharacterData(SortedBegin));
-DEBUG({
-  StringRef OldText(SourceMgr.getCharacterData(Begin),
-SourceMgr.getCharacterData(End) -
-SourceMgr.getCharacterData(Begin));
-  llvm::dbgs() << "Replacing '" << OldText << "' with '" << Text << "'\n";
-});
-auto Range = CharSourceRange::getCharRange(Begin, End);
-auto Err = Fixes->add(tooling::Replacement(SourceMgr, Range, Text));
-if (Err) {
-  llvm::errs() << "Error while sorting using declarations: "
-   << llvm::toString(std::move(Err)) << "\n";
+  if (*BlockAffected) {
+SmallVector SortedUsingDeclarations(

I'd prefer to iterator over UsingDeclarations here and see whether any of the 
contained lines is Affected. Seems like a much more encapsulated way to do this 
and prevents you from needing the awkward in-out parameter.


https://reviews.llvm.org/D39024



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


[PATCH] D38835: [refactor] selection: new CodeRangeASTSelection represents a set of selected consecutive statements

2017-10-18 Thread Alex Lorenz via Phabricator via cfe-commits
arphaman added inline comments.



Comment at: unittests/Tooling/ASTSelectionTest.cpp:688
+  Source, {2, 2}, None,
+  [](SourceRange SelectionRange, Optional Node) {
+EXPECT_TRUE(Node);

hokein wrote:
> arphaman wrote:
> > hokein wrote:
> > > I'm a bit confused here, if the selection range is none/empty,  shouldn't 
> > > `SelectedASTNode` be empty?
> > > 
> > > If this behavior is intended, I'd suggest documenting it in 
> > > `findSelectedASTNodesWithRange`.
> > No, the AST selection will work even with a cursor location, hence it won't 
> > be empty.
> > 
> > However, the CodeRangeASTSelection requires a non-empty selection range, so 
> > it won't work with just cursors.
> I see, thanks.
> 
> > the AST selection will work even with a cursor location, hence it won't be 
> > empty.
> 
> Is this documented somewhere in the code? I couldn't find any comments in the 
> definition of `findSelectedASTNodesWithRange` or `findSelectedASTNodes` in 
> this file.  Would be nice to document it although this is a test API, so that 
> it won't confuse future code readers.
Not quite, I'll add a comment in a follow-up commit.


Repository:
  rL LLVM

https://reviews.llvm.org/D38835



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


[PATCH] D39064: implement __has_unique_object_representations

2017-10-18 Thread Erich Keane via Phabricator via cfe-commits
erichkeane created this revision.

A helper builtin to facilitate implementing the
std::has_unique_object_representations type trait.

Requested here: https://bugs.llvm.org/show_bug.cgi?id=34942
Also already exists in GCC and MSVC.


https://reviews.llvm.org/D39064

Files:
  include/clang/AST/Type.h
  include/clang/Basic/TokenKinds.def
  include/clang/Basic/TypeTraits.h
  lib/AST/Type.cpp
  lib/Parse/ParseExpr.cpp
  lib/Sema/SemaExprCXX.cpp
  test/SemaCXX/type-traits.cpp

Index: lib/Parse/ParseExpr.cpp
===
--- lib/Parse/ParseExpr.cpp
+++ lib/Parse/ParseExpr.cpp
@@ -716,6 +716,7 @@
 ///   '__is_sealed'   [MS]
 ///   '__is_trivial'
 ///   '__is_union'
+///   '__has_unique_object_representations'   [MS]
 ///
 /// [Clang] unary-type-trait:
 ///   '__is_aggregate'
Index: lib/AST/Type.cpp
===
--- lib/AST/Type.cpp
+++ lib/AST/Type.cpp
@@ -2166,6 +2166,89 @@
   return false;
 }
 
+bool QualType::hasUniqueObjectRepresentations(const ASTContext &Context) const {
+  // C++17 [meta.unary.prop]:
+  //   The predicate condition for a template specialization
+  //   has_unique_object_representations shall be
+  //   satisfied if and only if:
+  // (9.1) — T is trivially copyable, and
+  // (9.2) — any two objects of type T with the same value have the same
+  // object representation, where two objects
+  //   of array or non-union class type are considered to have the same value
+  //   if their respective sequences of
+  //   direct subobjects have the same values, and two objects of union type
+  //   are considered to have the same
+  //   value if they have the same active member and the corresponding members
+  //   have the same value.
+  //   The set of scalar types for which this condition holds is
+  //   implementation-defined. [ Note: If a type has padding
+  //   bits, the condition does not hold; otherwise, the condition holds true
+  //   for unsigned integral types. — end
+  //   note ]
+  if (isNull())
+return false;
+
+  // Arrays are unique only if their element type is unique.
+  if ((*this)->isArrayType())
+return Context.getBaseElementType(*this).hasUniqueObjectRepresentations(
+Context);
+
+  // (9.1) — T is trivially copyable, and
+  if (!isTriviallyCopyableType(Context))
+return false;
+
+  // Functions are not unique.
+  if ((*this)->isFunctionType())
+return false;
+
+  // All integrals and enums are unique!
+  if ((*this)->isIntegralOrEnumerationType())
+return true;
+
+  // All pointers are unique, since they're just integrals.
+  if ((*this)->isPointerType() || (*this)->isMemberPointerType())
+return true;
+
+  if ((*this)->isRecordType()) {
+const RecordDecl *Record = getTypePtr()->getAs()->getDecl();
+
+// Lambda types are not unique, so exclude them immediately.
+if (Record->isLambda())
+  return false;
+
+// Empty types are not unique.
+if (Record->field_empty())
+  return false;
+
+CharUnits RecordSize = Context.getTypeSizeInChars(*this);
+CharUnits CurOffset = Context.toCharUnitsFromBits(
+Context.getFieldOffset(*Record->field_begin()));
+for (const auto *Field : Record->fields()) {
+  if (!Field->getType().hasUniqueObjectRepresentations(Context))
+return false;
+
+  // Check for padding.
+  CharUnits FieldSize = Context.getTypeSizeInChars(Field->getType());
+  if (Record->isUnion() && FieldSize != RecordSize)
+return false;
+  else if (!Record->isUnion()) {
+CharUnits FieldOffset =
+Context.toCharUnitsFromBits(Context.getFieldOffset(Field));
+if (FieldOffset != CurOffset)
+  return false;
+CurOffset += FieldSize;
+  }
+}
+
+// struct/class with tail padding.
+if (!Record->isUnion() && CurOffset != RecordSize)
+  return false;
+
+return true;
+  }
+  return false;
+}
+
 bool QualType::isNonWeakInMRRWithObjCWeak(const ASTContext &Context) const {
   return !Context.getLangOpts().ObjCAutoRefCount &&
  Context.getLangOpts().ObjCWeak &&
Index: lib/Sema/SemaExprCXX.cpp
===
--- lib/Sema/SemaExprCXX.cpp
+++ lib/Sema/SemaExprCXX.cpp
@@ -4175,6 +4175,7 @@
   case UTT_IsDestructible:
   case UTT_IsNothrowDestructible:
   case UTT_IsTriviallyDestructible:
+  case UTT_HasUniqueObjectRepresentations:
 if (ArgTy->isIncompleteArrayType() || ArgTy->isVoidType())
   return true;
 
@@ -4614,6 +4615,8 @@
 //   Returns True if and only if T is a complete type at the point of the
 //   function call.
 return !T->isIncompleteType();
+  case UTT_HasUniqueObjectRepresentations:
+return T.hasUniqueObjectRepresentations(C);
   }
 }
 
Index: include/clang/AST/Type.h

Re: r315856 - Add -f[no-]double-square-bracket-attributes as new driver options to control use of [[]] attributes in all language modes. This is the initial implementation of WG14 N2165, which is a pr

2017-10-18 Thread Galina Kistanova via cfe-commits
Thank you!

On Wed, Oct 18, 2017 at 7:38 AM, Aaron Ballman 
wrote:

> Thanks for pointing the breakage out -- it should be fixed with r316075.
>
> ~Aaron
>
> On Wed, Oct 18, 2017 at 7:50 AM, Aaron Ballman 
> wrote:
> > I'll take a look, thank you for pointing it out (and sorry for the
> trouble)!
> >
> > ~Aaron
> >
> > On Tue, Oct 17, 2017 at 9:56 PM, Galina Kistanova 
> wrote:
> >> Hello Aaron,
> >>
> >> This commit broke one our builders:
> >>
> >> http://lab.llvm.org:8011/builders/ubuntu-gcc7.1-werror/builds/2272
> >>
> >> . . .
> >> FAILED: /usr/local/gcc-7.1/bin/g++-7.1   -DGTEST_HAS_RTTI=0 -D_DEBUG
> >> -D_GNU_SOURCE -D__STDC_CONSTANT_MACROS -D__STDC_FORMAT_MACROS
> >> -D__STDC_LIMIT_MACROS -Itools/clang/lib/Basic
> >> -I/home/buildslave/am1i-slv2/ubuntu-gcc7.1-werror/llvm/
> tools/clang/lib/Basic
> >> -I/home/buildslave/am1i-slv2/ubuntu-gcc7.1-werror/llvm/
> tools/clang/include
> >> -Itools/clang/include -Iinclude
> >> -I/home/buildslave/am1i-slv2/ubuntu-gcc7.1-werror/llvm/include
> >> -Wno-noexcept-type -fPIC -fvisibility-inlines-hidden -Werror
> >> -Werror=date-time -std=c++11 -Wall -W -Wno-unused-parameter
> -Wwrite-strings
> >> -Wcast-qual -Wno-missing-field-initializers -pedantic -Wno-long-long
> >> -Wno-maybe-uninitialized -Wdelete-non-virtual-dtor -Wno-comment
> >> -ffunction-sections -fdata-sections -fno-common -Woverloaded-virtual
> >> -fno-strict-aliasing -O3  -fPIC   -UNDEBUG  -fno-exceptions -fno-rtti
> -MD
> >> -MT tools/clang/lib/Basic/CMakeFiles/clangBasic.dir/Attributes.cpp.o
> -MF
> >> tools/clang/lib/Basic/CMakeFiles/clangBasic.dir/Attributes.cpp.o.d -o
> >> tools/clang/lib/Basic/CMakeFiles/clangBasic.dir/Attributes.cpp.o -c
> >> /home/buildslave/am1i-slv2/ubuntu-gcc7.1-werror/llvm/
> tools/clang/lib/Basic/Attributes.cpp
> >> In file included from
> >> /home/buildslave/am1i-slv2/ubuntu-gcc7.1-werror/llvm/
> tools/clang/lib/Basic/Attributes.cpp:15:0:
> >> tools/clang/include/clang/Basic/AttrHasAttributeImpl.inc: In function
> ‘int
> >> clang::hasAttribute(clang::AttrSyntax, const clang::IdentifierInfo*,
> const
> >> clang::IdentifierInfo*, const clang::TargetInfo&, const
> >> clang::LangOptions&)’:
> >> tools/clang/include/clang/Basic/AttrHasAttributeImpl.inc:526:8: error:
> this
> >> statement may fall through [-Werror=implicit-fallthrough=]
> >>  } else if (Scope->getName() == "gsl") {
> >> ^~
> >> tools/clang/include/clang/Basic/AttrHasAttributeImpl.inc:532:1: note:
> here
> >>  case AttrSyntax::C: {
> >>  ^~~~
> >> cc1plus: all warnings being treated as errors
> >>
> >> Please have a look?
> >>
> >> Thanks
> >>
> >> Galina
> >>
> >> On Sun, Oct 15, 2017 at 8:01 AM, Aaron Ballman via cfe-commits
> >>  wrote:
> >>>
> >>> Author: aaronballman
> >>> Date: Sun Oct 15 08:01:42 2017
> >>> New Revision: 315856
> >>>
> >>> URL: http://llvm.org/viewvc/llvm-project?rev=315856&view=rev
> >>> Log:
> >>> Add -f[no-]double-square-bracket-attributes as new driver options to
> >>> control use of [[]] attributes in all language modes. This is the
> initial
> >>> implementation of WG14 N2165, which is a proposal to add [[]]
> attributes to
> >>> C2x, but also allows you to enable these attributes in C++98, or
> disable
> >>> them in C++11 or later.
> >>>
> >>> Added:
> >>> cfe/trunk/test/Misc/ast-dump-c-attr.c
> >>> cfe/trunk/test/Parser/c2x-attributes.c
> >>> cfe/trunk/test/Parser/c2x-attributes.m
> >>> cfe/trunk/test/Sema/attr-deprecated-c2x.c
> >>> Modified:
> >>> cfe/trunk/include/clang/Basic/Attr.td
> >>> cfe/trunk/include/clang/Basic/Attributes.h
> >>> cfe/trunk/include/clang/Basic/LangOptions.def
> >>> cfe/trunk/include/clang/Driver/Options.td
> >>> cfe/trunk/include/clang/Parse/Parser.h
> >>> cfe/trunk/include/clang/Sema/AttributeList.h
> >>> cfe/trunk/lib/Frontend/CompilerInvocation.cpp
> >>> cfe/trunk/lib/Lex/Lexer.cpp
> >>> cfe/trunk/lib/Parse/ParseDecl.cpp
> >>> cfe/trunk/lib/Parse/ParseDeclCXX.cpp
> >>> cfe/trunk/lib/Sema/AttributeList.cpp
> >>> cfe/trunk/utils/TableGen/ClangAttrEmitter.cpp
> >>>
> >>> Modified: cfe/trunk/include/clang/Basic/Attr.td
> >>> URL:
> >>> http://llvm.org/viewvc/llvm-project/cfe/trunk/include/
> clang/Basic/Attr.td?rev=315856&r1=315855&r2=315856&view=diff
> >>>
> >>> 
> ==
> >>> --- cfe/trunk/include/clang/Basic/Attr.td (original)
> >>> +++ cfe/trunk/include/clang/Basic/Attr.td Sun Oct 15 08:01:42 2017
> >>> @@ -210,6 +210,10 @@ class CXX11 >>>string Namespace = namespace;
> >>>int Version = version;
> >>>  }
> >>> +class C2x : Spelling {
> >>> +  string Namespace = namespace;
> >>> +}
> >>> +
> >>>  class Keyword : Spelling;
> >>>  class Pragma : Spelling "Pragma"> {
> >>>string Namespace = namespace;
> >>> @@ -958,7 +962,7 @@ def RenderScriptKernel : Attr {
> >>>
> >>>  def Deprecated : InheritableAttr {
> >>>let Spellings = [GCC<"deprecated">, Declspec<"deprecated">,
> >>> -   C

[PATCH] D38852: [Hexagon] Handling of new HVX flags and target-features

2017-10-18 Thread Sumanth Gundapaneni via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rL316102: [Hexagon] Handling of new HVX flags and 
target-features (authored by sgundapa).

Changed prior to commit:
  https://reviews.llvm.org/D38852?vs=118802&id=119507#toc

Repository:
  rL LLVM

https://reviews.llvm.org/D38852

Files:
  cfe/trunk/include/clang/Basic/DiagnosticDriverKinds.td
  cfe/trunk/include/clang/Driver/Options.td
  cfe/trunk/lib/Basic/Targets/Hexagon.cpp
  cfe/trunk/lib/Basic/Targets/Hexagon.h
  cfe/trunk/lib/Driver/ToolChains/Clang.cpp
  cfe/trunk/lib/Driver/ToolChains/Hexagon.cpp
  cfe/trunk/lib/Driver/ToolChains/Hexagon.h
  cfe/trunk/test/CodeGen/hexagon-inline-asm.c
  cfe/trunk/test/Driver/hexagon-hvx.c
  cfe/trunk/test/Preprocessor/hexagon-predefines.c

Index: cfe/trunk/include/clang/Driver/Options.td
===
--- cfe/trunk/include/clang/Driver/Options.td
+++ cfe/trunk/include/clang/Driver/Options.td
@@ -139,6 +139,10 @@
Group, DocName<"ARM">;
 def m_hexagon_Features_Group : OptionGroup<"">,
Group, DocName<"Hexagon">;
+// The features added by this group will not be added to target features.
+// These are explicitly handled.
+def m_hexagon_Features_HVX_Group : OptionGroup<"">,
+   Group, DocName<"Hexagon">;
 def m_ppc_Features_Group : OptionGroup<"">,
Group, DocName<"PowerPC">;
 def m_wasm_Features_Group : OptionGroup<"">,
@@ -2495,14 +2499,26 @@
Alias, AliasArgs<["hexagonv60"]>;
 def mv62 : Flag<["-"], "mv62">, Group,
Alias, AliasArgs<["hexagonv62"]>;
-def mhexagon_hvx : Flag<["-"], "mhvx">, Group,
-Flags<[CC1Option]>, HelpText<"Enable Hexagon Vector eXtensions">;
-def mno_hexagon_hvx : Flag<["-"], "mno-hvx">, Group,
-Flags<[CC1Option]>, HelpText<"Disable Hexagon Vector eXtensions">;
-def mhexagon_hvx_double : Flag<["-"], "mhvx-double">, Group,
-Flags<[CC1Option]>, HelpText<"Enable Hexagon Double Vector eXtensions">;
-def mno_hexagon_hvx_double : Flag<["-"], "mno-hvx-double">, Group,
-Flags<[CC1Option]>, HelpText<"Disable Hexagon Double Vector eXtensions">;
+def mhexagon_hvx : Flag<[ "-" ], "mhvx">,
+   Group,
+   HelpText<"Enable Hexagon Vector eXtensions">;
+def mhexagon_hvx_EQ : Joined<[ "-" ], "mhvx=">,
+ Group,
+ HelpText<"Enable Hexagon Vector eXtensions">;
+def mno_hexagon_hvx : Flag<[ "-" ], "mno-hvx">,
+  Group,
+  HelpText<"Disable Hexagon Vector eXtensions">;
+def mhexagon_hvx_length_EQ : Joined<[ "-" ], "mhvx-length=">,
+Group,
+HelpText<"Set Hexagon Vector Length">, Values<"64B,128B">;
+// hvx-double deprecrated flag.
+def mhexagon_hvx_double : Flag<[ "-" ], "mhvx-double">,
+  Group,
+  HelpText<"Enable Hexagon Double Vector eXtensions">;
+def mno_hexagon_hvx_double
+: Flag<[ "-" ], "mno-hvx-double">,
+  Group,
+  HelpText<"Disable Hexagon Double Vector eXtensions">;
 
 // These are legacy user-facing driver-level option spellings. They are always
 // aliases for options that are spelled using the more common Unix / GNU flag
Index: cfe/trunk/include/clang/Basic/DiagnosticDriverKinds.td
===
--- cfe/trunk/include/clang/Basic/DiagnosticDriverKinds.td
+++ cfe/trunk/include/clang/Basic/DiagnosticDriverKinds.td
@@ -263,6 +263,9 @@
 def err_analyzer_config_multiple_values : Error<
   "analyzer-config option '%0' should contain only one '='">;
 
+def err_drv_invalid_hvx_length : Error<
+  "-mhvx-length is not supported without a -mhvx/-mhvx= flag">;
+
 def err_drv_modules_validate_once_requires_timestamp : Error<
   "option '-fmodules-validate-once-per-build-session' requires "
   "'-fbuild-session-timestamp=' or '-fbuild-session-file='">;
Index: cfe/trunk/test/Preprocessor/hexagon-predefines.c
===
--- cfe/trunk/test/Preprocessor/hexagon-predefines.c
+++ cfe/trunk/test/Preprocessor/hexagon-predefines.c
@@ -1,32 +1,43 @@
 // RUN: %clang_cc1 -E -dM -triple hexagon-unknown-elf -target-cpu hexagonv5 %s | FileCheck %s -check-prefix CHECK-V5
-
 // CHECK-V5: #define __HEXAGON_ARCH__ 5
 // CHECK-V5: #define __HEXAGON_V5__ 1
+// CHECK-V5-NOT: #define __HVX_LENGTH__
+// CHECK-V5-NOT: #define __HVX__ 1
 // CHECK-V5: #define __hexagon__ 1
 
 // RUN: %clang_cc1 -E -dM -triple hexagon-unknown-elf -target-cpu hexagonv55 %s | FileCheck %s -check-prefix CHECK-V55
-
 // CHECK-V55: #define __HEXAGON_ARCH__ 55
 // CHECK-V55: #define __HEXAGON_V55__ 1
+// CHECK-V55-NOT: #define __HVX_LENGTH__
+// CHECK-V55-NOT: #define __HVX__ 1
 // CHECK-V55: #define __hexagon__ 1
 
 // RUN: %clang_cc1 -E -dM -triple hexagon-unknown-elf -target-cpu hexagonv60 %s

r316102 - [Hexagon] Handling of new HVX flags and target-features

2017-10-18 Thread Sumanth Gundapaneni via cfe-commits
Author: sgundapa
Date: Wed Oct 18 11:10:13 2017
New Revision: 316102

URL: http://llvm.org/viewvc/llvm-project?rev=316102&view=rev
Log:
[Hexagon] Handling of new HVX flags and target-features

This patch has the following changes
A new flag "-mhvx-length={64B|128B}" is introduced to specify the length of the 
vector.
Previously we have used "-mhvx-double" for 128 Bytes. This adds the 
target-feature "+hvx-length{64|128}b"

The "-mhvx" flag must be provided on command line to enable HVX for Hexagon. If 
no -mhvx-length flag
is specified, a default length is picked from the arch mentioned in this 
priority order from either -mhvx=vxx
or -mcpu. For v60 and v62 the default length is 64 Byte. For unknown versions, 
the length is 128 Byte. The 
-mhvx flag adds the target-feature "+hvxv{hvx_version}"

The 64 Byte mode is soon going to be deprecated. A warning is emitted if 64 
Byte is enabled. A warning is
still emitted for the default 64 Byte as well. This warning can be suppressed 
with a -Wno flag.

The "-mhvx-double" and "-mno-hvx-double" flags are deprecated. A warning is 
emitted if the driver sees
them on commandline. "-mhvx-double" is an alias to "-mhvx-length=128B"

The compilation will error out if -mhvx-length is specified with out an 
-mhvx/-mhvx= flag

The macro HVX_LENGTH is defined and is set to the length of the vector. 
Eg: #define HVX_LENGTH 64

The macro HVX_ARCH is defined and is set to the version of the HVX. 
Eg: #define HVX_ARCH 62

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

Added:
cfe/trunk/test/Driver/hexagon-hvx.c
Modified:
cfe/trunk/include/clang/Basic/DiagnosticDriverKinds.td
cfe/trunk/include/clang/Driver/Options.td
cfe/trunk/lib/Basic/Targets/Hexagon.cpp
cfe/trunk/lib/Basic/Targets/Hexagon.h
cfe/trunk/lib/Driver/ToolChains/Clang.cpp
cfe/trunk/lib/Driver/ToolChains/Hexagon.cpp
cfe/trunk/lib/Driver/ToolChains/Hexagon.h
cfe/trunk/test/CodeGen/hexagon-inline-asm.c
cfe/trunk/test/Preprocessor/hexagon-predefines.c

Modified: cfe/trunk/include/clang/Basic/DiagnosticDriverKinds.td
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Basic/DiagnosticDriverKinds.td?rev=316102&r1=316101&r2=316102&view=diff
==
--- cfe/trunk/include/clang/Basic/DiagnosticDriverKinds.td (original)
+++ cfe/trunk/include/clang/Basic/DiagnosticDriverKinds.td Wed Oct 18 11:10:13 
2017
@@ -263,6 +263,9 @@ def err_analyzer_config_no_value : Error
 def err_analyzer_config_multiple_values : Error<
   "analyzer-config option '%0' should contain only one '='">;
 
+def err_drv_invalid_hvx_length : Error<
+  "-mhvx-length is not supported without a -mhvx/-mhvx= flag">;
+
 def err_drv_modules_validate_once_requires_timestamp : Error<
   "option '-fmodules-validate-once-per-build-session' requires "
   "'-fbuild-session-timestamp=' or 
'-fbuild-session-file='">;

Modified: cfe/trunk/include/clang/Driver/Options.td
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Driver/Options.td?rev=316102&r1=316101&r2=316102&view=diff
==
--- cfe/trunk/include/clang/Driver/Options.td (original)
+++ cfe/trunk/include/clang/Driver/Options.td Wed Oct 18 11:10:13 2017
@@ -139,6 +139,10 @@ def m_arm_Features_Group : OptionGroup<"
Group, DocName<"ARM">;
 def m_hexagon_Features_Group : OptionGroup<"">,
Group, DocName<"Hexagon">;
+// The features added by this group will not be added to target features.
+// These are explicitly handled.
+def m_hexagon_Features_HVX_Group : OptionGroup<"">,
+   Group, DocName<"Hexagon">;
 def m_ppc_Features_Group : OptionGroup<"">,
Group, DocName<"PowerPC">;
 def m_wasm_Features_Group : OptionGroup<"">,
@@ -2495,14 +2499,26 @@ def mv60 : Flag<["-"], "mv60">, Group, AliasArgs<["hexagonv60"]>;
 def mv62 : Flag<["-"], "mv62">, Group,
Alias, AliasArgs<["hexagonv62"]>;
-def mhexagon_hvx : Flag<["-"], "mhvx">, Group,
-Flags<[CC1Option]>, HelpText<"Enable Hexagon Vector eXtensions">;
-def mno_hexagon_hvx : Flag<["-"], "mno-hvx">, Group,
-Flags<[CC1Option]>, HelpText<"Disable Hexagon Vector eXtensions">;
-def mhexagon_hvx_double : Flag<["-"], "mhvx-double">, 
Group,
-Flags<[CC1Option]>, HelpText<"Enable Hexagon Double Vector eXtensions">;
-def mno_hexagon_hvx_double : Flag<["-"], "mno-hvx-double">, 
Group,
-Flags<[CC1Option]>, HelpText<"Disable Hexagon Double Vector eXtensions">;
+def mhexagon_hvx : Flag<[ "-" ], "mhvx">,
+   Group,
+   HelpText<"Enable Hexagon Vector eXtensions">;
+def mhexagon_hvx_EQ : Joined<[ "-" ], "mhvx=">,
+ Group,
+ HelpText<"Enable Hexagon Vector eXtensions">;
+def mno_hexagon_hvx : Flag<[ "-" ], "mno-hvx">,
+  Group,
+ 

[PATCH] D38596: Implement attribute target multiversioning

2017-10-18 Thread Erich Keane via Phabricator via cfe-commits
erichkeane added a comment.

@rsmith and @rnk just a quick bump!  I'd like to get your thoughts on the SEMA 
changes here.

Thanks!
-Erich


https://reviews.llvm.org/D38596



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


[PATCH] D39042: [Tooling] Add a factory method for CommonOptionsParser

2017-10-18 Thread Eric Liu via Phabricator via cfe-commits
ioeric updated this revision to Diff 119502.
ioeric added a comment.

- Move unique_ptr result.


https://reviews.llvm.org/D39042

Files:
  include/clang/Tooling/CommonOptionsParser.h
  lib/Tooling/CommonOptionsParser.cpp

Index: lib/Tooling/CommonOptionsParser.cpp
===
--- lib/Tooling/CommonOptionsParser.cpp
+++ lib/Tooling/CommonOptionsParser.cpp
@@ -24,9 +24,9 @@
 //
 //===--===//
 
-#include "llvm/Support/CommandLine.h"
 #include "clang/Tooling/CommonOptionsParser.h"
 #include "clang/Tooling/Tooling.h"
+#include "llvm/Support/CommandLine.h"
 
 using namespace clang::tooling;
 using namespace llvm;
@@ -81,7 +81,7 @@
   return Commands;
 }
 
-CommonOptionsParser::CommonOptionsParser(
+llvm::Error CommonOptionsParser::init(
 int &argc, const char **argv, cl::OptionCategory &Category,
 llvm::cl::NumOccurrencesFlag OccurrencesFlag, const char *Overview) {
   static cl::opt Help("h", cl::desc("Alias for -help"), cl::Hidden,
@@ -105,20 +105,30 @@
   cl::desc("Additional argument to prepend to the compiler command line"),
   cl::cat(Category), cl::sub(*cl::AllSubCommands));
 
+  cl::ResetAllOptionOccurrences();
+
   cl::HideUnrelatedOptions(Category);
 
   std::string ErrorMessage;
   Compilations =
   FixedCompilationDatabase::loadFromCommandLine(argc, argv, ErrorMessage);
-  if (!Compilations && !ErrorMessage.empty())
-llvm::errs() << ErrorMessage;
-  cl::ParseCommandLineOptions(argc, argv, Overview);
+  if (!ErrorMessage.empty())
+ErrorMessage.append("\n");
+  llvm::raw_string_ostream OS(ErrorMessage);
+  // Stop initializing if command-line option parsing failed.
+  if (!cl::ParseCommandLineOptions(argc, argv, Overview, &OS)) {
+OS.flush();
+return llvm::make_error("[CommonOptionsParser]: " +
+   ErrorMessage,
+   llvm::inconvertibleErrorCode());
+  }
+
   cl::PrintOptionValues();
 
   SourcePathList = SourcePaths;
   if ((OccurrencesFlag == cl::ZeroOrMore || OccurrencesFlag == cl::Optional) &&
   SourcePathList.empty())
-return;
+return llvm::Error::success();
   if (!Compilations) {
 if (!BuildPath.empty()) {
   Compilations =
@@ -142,4 +152,29 @@
   AdjustingCompilations->appendArgumentsAdjuster(
   getInsertArgumentAdjuster(ArgsAfter, ArgumentInsertPosition::END));
   Compilations = std::move(AdjustingCompilations);
+  return llvm::Error::success();
+}
+
+llvm::Expected>
+CommonOptionsParser::create(int &argc, const char **argv,
+llvm::cl::OptionCategory &Category,
+llvm::cl::NumOccurrencesFlag OccurrencesFlag,
+const char *Overview) {
+  std::unique_ptr Parser(new CommonOptionsParser);
+  llvm::Error Err =
+  Parser->init(argc, argv, Category, OccurrencesFlag, Overview);
+  if (Err)
+return std::move(Err);
+  return std::move(Parser);
+}
+
+CommonOptionsParser::CommonOptionsParser(
+int &argc, const char **argv, cl::OptionCategory &Category,
+llvm::cl::NumOccurrencesFlag OccurrencesFlag, const char *Overview) {
+  llvm::Error Err = init(argc, argv, Category, OccurrencesFlag, Overview);
+  if (Err) {
+llvm::report_fatal_error(
+"CommonOptionsParser: failed to parse command-line arguments. " +
+llvm::toString(std::move(Err)));
+  }
 }
Index: include/clang/Tooling/CommonOptionsParser.h
===
--- include/clang/Tooling/CommonOptionsParser.h
+++ include/clang/Tooling/CommonOptionsParser.h
@@ -30,6 +30,7 @@
 #include "clang/Tooling/ArgumentsAdjusters.h"
 #include "clang/Tooling/CompilationDatabase.h"
 #include "llvm/Support/CommandLine.h"
+#include "llvm/Support/Error.h"
 
 namespace clang {
 namespace tooling {
@@ -86,13 +87,18 @@
   /// All options not belonging to \p Category become hidden.
   ///
   /// It also allows calls to set the required number of positional parameters.
-  ///
-  /// This constructor exits program in case of error.
   CommonOptionsParser(int &argc, const char **argv,
   llvm::cl::OptionCategory &Category,
   llvm::cl::NumOccurrencesFlag OccurrencesFlag,
   const char *Overview = nullptr);
 
+  /// \brief A factory method that is similar to the above constructor, except
+  /// this returns an error instead exiting the program on error.
+  static llvm::Expected>
+  create(int &argc, const char **argv, llvm::cl::OptionCategory &Category,
+ llvm::cl::NumOccurrencesFlag OccurrencesFlag,
+ const char *Overview = nullptr);
+
   /// Returns a reference to the loaded compilations database.
   CompilationDatabase &getCompilations() {
 return *Compilations;
@@ -106,6 +112,13 @@
   static const char *const HelpMessage;
 
 private:
+  CommonOptionsParser() = d

[PATCH] D37115: [coroutines] Do not attempt to typo-correct when coroutine is looking for required members

2017-10-18 Thread Gor Nishanov via Phabricator via cfe-commits
GorNishanov added a comment.

@rsmith , here is a fix for the funny diagnostics you mentioned.


https://reviews.llvm.org/D37115



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


Re: r315984 - [CodeGen] EmitPointerWithAlignment() to generate TBAA info along with LValue base info

2017-10-18 Thread Ivan Kosarev via cfe-commits

Hello Douglas,

Sure, I'm on it. Thanks for reporting and sorry for the troubles.


On 18/10/17 20:24, Yung, Douglas wrote:

Hi Ivan,

This change caused a compiler crash in one of our tests. I have put the details 
in PR34992, can you take a look?

Douglas Yung


-Original Message-
From: cfe-commits [mailto:cfe-commits-boun...@lists.llvm.org] On Behalf Of
Ivan A. Kosarev via cfe-commits
Sent: Tuesday, October 17, 2017 2:12
To: cfe-commits@lists.llvm.org
Subject: r315984 - [CodeGen] EmitPointerWithAlignment() to generate TBAA info
along with LValue base info

Author: kosarev
Date: Tue Oct 17 02:12:13 2017
New Revision: 315984

URL: http://llvm.org/viewvc/llvm-project?rev=315984&view=rev
Log:
[CodeGen] EmitPointerWithAlignment() to generate TBAA info along with LValue
base info

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

Added:
 cfe/trunk/test/CodeGen/tbaa-cast.cpp
Modified:
 cfe/trunk/lib/CodeGen/CGExpr.cpp
 cfe/trunk/lib/CodeGen/CodeGenFunction.cpp
 cfe/trunk/lib/CodeGen/CodeGenFunction.h
 cfe/trunk/lib/CodeGen/CodeGenModule.cpp
 cfe/trunk/lib/CodeGen/CodeGenModule.h
 cfe/trunk/lib/CodeGen/CodeGenTBAA.cpp
 cfe/trunk/lib/CodeGen/CodeGenTBAA.h

Modified: cfe/trunk/lib/CodeGen/CGExpr.cpp
URL: http://llvm.org/viewvc/llvm-
project/cfe/trunk/lib/CodeGen/CGExpr.cpp?rev=315984&r1=315983&r2=315984&view=d
iff
==
--- cfe/trunk/lib/CodeGen/CGExpr.cpp (original)
+++ cfe/trunk/lib/CodeGen/CGExpr.cpp Tue Oct 17 02:12:13 2017
@@ -916,7 +916,8 @@ void CodeGenModule::EmitExplicitCastExpr
  /// EmitPointerWithAlignment - Given an expression of pointer type, try to
/// derive a more accurate bound on the alignment of the pointer.
  Address CodeGenFunction::EmitPointerWithAlignment(const Expr *E,
-  LValueBaseInfo *BaseInfo) {
+  LValueBaseInfo *BaseInfo,
+  TBAAAccessInfo
+ *TBAAInfo) {
// We allow this with ObjC object pointers because of fragile ABIs.
assert(E->getType()->isPointerType() ||
   E->getType()->isObjCObjectPointerType());
@@ -936,20 +937,30 @@ Address CodeGenFunction::EmitPointerWith
  if (PtrTy->getPointeeType()->isVoidType())
break;

-LValueBaseInfo InnerInfo;
-Address Addr = EmitPointerWithAlignment(CE->getSubExpr(),
&InnerInfo);
-if (BaseInfo) *BaseInfo = InnerInfo;
-
-// If this is an explicit bitcast, and the source l-value is
-// opaque, honor the alignment of the casted-to type.
-if (isa(CE) &&
-InnerInfo.getAlignmentSource() != AlignmentSource::Decl) {
-  LValueBaseInfo ExpInfo;
+LValueBaseInfo InnerBaseInfo;
+TBAAAccessInfo InnerTBAAInfo;
+Address Addr = EmitPointerWithAlignment(CE->getSubExpr(),
+&InnerBaseInfo,
+&InnerTBAAInfo);
+if (BaseInfo) *BaseInfo = InnerBaseInfo;
+if (TBAAInfo) *TBAAInfo = InnerTBAAInfo;
+
+if (isa(CE)) {
+  LValueBaseInfo TargetTypeBaseInfo;
+  TBAAAccessInfo TargetTypeTBAAInfo;
CharUnits Align = getNaturalPointeeTypeAlignment(E->getType(),
-   &ExpInfo);
-  if (BaseInfo)
-BaseInfo->mergeForCast(ExpInfo);
-  Addr = Address(Addr.getPointer(), Align);
+
&TargetTypeBaseInfo,
+
&TargetTypeTBAAInfo);
+  if (TBAAInfo)
+*TBAAInfo = CGM.mergeTBAAInfoForCast(*TBAAInfo,
+ TargetTypeTBAAInfo);
+  // If the source l-value is opaque, honor the alignment of the
+  // casted-to type.
+  if (InnerBaseInfo.getAlignmentSource() != AlignmentSource::Decl) {
+if (BaseInfo)
+  BaseInfo->mergeForCast(TargetTypeBaseInfo);
+Addr = Address(Addr.getPointer(), Align);
+  }
  }

  if (SanOpts.has(SanitizerKind::CFIUnrelatedCast) && @@ -969,12
+980,13 @@ Address CodeGenFunction::EmitPointerWith

  // Array-to-pointer decay.
  case CK_ArrayToPointerDecay:
-  return EmitArrayToPointerDecay(CE->getSubExpr(), BaseInfo);
+  return EmitArrayToPointerDecay(CE->getSubExpr(), BaseInfo,
+ TBAAInfo);

  // Derived-to-base conversions.
  case CK_UncheckedDerivedToBase:
  case CK_DerivedToBase: {
-  Address Addr = EmitPointerWithAlignment(CE->getSubExpr(), BaseInfo);
+  Address Addr = EmitPointerWithAlignment(CE->getSubExpr(), BaseInfo,
+  TBAAInfo);
auto Derived = CE->getSubExpr()->getType()->getPointeeCXXRecordDecl();
return GetAddressOfBaseClass(Addr, Derived,
 CE->path_begin(), CE->path_end(), @@ -
994,6 +1006,7

[PATCH] D38479: Make -mgeneral-regs-only more like GCC's

2017-10-18 Thread George Burgess IV via Phabricator via cfe-commits
george.burgess.iv updated this revision to Diff 119499.
george.burgess.iv marked 2 inline comments as done.
george.burgess.iv added a comment.

Addressed feedback. Thanks!

After looking around and internalizing a little bit of how backends in LLVM 
work, the path forward I have in mind is to basically funnel another bit to the 
backend that indicates whether the user specified `-mgeneral-regs-only`. If so, 
that flag will act like `"-crypto,-fp-armv8,-neon"` when we're setting up the 
AArch64 backend (e.g. floats/vectors will still be illegal, vector regclasses 
won't be added, ...). Importantly, this approach wouldn't actually remove the 
aforementioned feature flags, so I think it'll allow our assembler to handle 
non-general ops without any extra effort. We can also query this bit to see if 
we want to diagnose calls where the ABI mandates that vector regs are used. 
Thoughts welcome :)


https://reviews.llvm.org/D38479

Files:
  docs/UsersManual.rst
  include/clang/Basic/DiagnosticSemaKinds.td
  include/clang/Basic/LangOptions.def
  include/clang/Driver/CC1Options.td
  include/clang/Sema/Sema.h
  lib/Driver/ToolChains/Arch/AArch64.cpp
  lib/Driver/ToolChains/Clang.cpp
  lib/Frontend/CompilerInvocation.cpp
  lib/Sema/SemaDecl.cpp
  lib/Sema/SemaExprCXX.cpp
  test/CodeGen/aarch64-mgeneral_regs_only.c
  test/Driver/aarch64-mgeneral_regs_only.c
  test/Sema/aarch64-mgeneral_regs_only.c
  test/SemaCXX/aarch64-mgeneral_regs_only.cpp

Index: test/SemaCXX/aarch64-mgeneral_regs_only.cpp
===
--- /dev/null
+++ test/SemaCXX/aarch64-mgeneral_regs_only.cpp
@@ -0,0 +1,124 @@
+// RUN: %clang_cc1 -triple aarch64-linux-eabi -std=c++11 -general-regs-only %s -verify -DBANNED=float -Wno-unused-value
+// RUN: %clang_cc1 -triple aarch64-linux-eabi -std=c++11 -general-regs-only %s -verify -DBANNED=int '-DVECATTR=__attribute__((ext_vector_type(2)))' -Wno-unused-value
+// RUN: %clang_cc1 -triple aarch64-linux-eabi -std=c++11 -general-regs-only %s -verify -DBANNED=FloatTypedef -Wno-unused-value
+
+using FloatTypedef = float;
+
+#ifndef VECATTR
+#define VECATTR
+#define BannedToInt(x) (x)
+#else
+#define BannedToInt(x) ((x)[0])
+#endif
+
+typedef BANNED BannedTy VECATTR;
+
+namespace default_args {
+int foo(BannedTy = 0); // expected-error 2{{use of floating-point or vector values is disabled}}
+int bar(int = 1.0);
+
+void baz(int a = foo()); // expected-note{{from use of default argument here}}
+void bazz(int a = bar());
+
+void test() {
+  foo(); // expected-note{{from use of default argument here}}
+  bar();
+  baz(); // expected-note{{from use of default argument here}}
+  baz(4);
+  bazz();
+}
+}
+
+namespace conversions {
+struct ConvertToFloat { explicit operator BannedTy(); };
+struct ConvertToFloatImplicit { /* implicit */ operator BannedTy(); };
+struct ConvertFromFloat { ConvertFromFloat(BannedTy); };
+
+void takeFloat(BannedTy);
+void takeConvertFromFloat(ConvertFromFloat);
+void takeConvertFromFloatRef(const ConvertFromFloat &);
+
+void test() {
+  BannedTy(ConvertToFloat());
+
+  takeFloat(ConvertToFloatImplicit{}); // expected-error{{use of floating-point or vector values is disabled}}
+
+  ConvertFromFloat(0); // expected-error{{use of floating-point or vector values is disabled}}
+  ConvertFromFloat(ConvertToFloatImplicit{}); // expected-error{{use of floating-point or vector values is disabled}}
+
+  ConvertFromFloat{0}; // expected-error{{use of floating-point or vector values is disabled}}
+  ConvertFromFloat{ConvertToFloatImplicit{}}; // expected-error{{use of floating-point or vector values is disabled}}
+
+  takeConvertFromFloat(0); // expected-error{{use of floating-point or vector values is disabled}}
+  takeConvertFromFloatRef(0); // expected-error{{use of floating-point or vector values is disabled}}
+
+  takeConvertFromFloat(ConvertFromFloat(0)); // expected-error{{use of floating-point or vector values is disabled}}
+  takeConvertFromFloatRef(ConvertFromFloat(0)); // expected-error{{use of floating-point or vector values is disabled}}
+}
+
+
+void takeImplicitFloat(BannedTy = ConvertToFloatImplicit()); // expected-error{{use of floating-point or vector values is disabled}}
+void test2() {
+  takeImplicitFloat(); // expected-note{{from use of default argument here}}
+}
+}
+
+namespace refs {
+  struct BannedRef {
+const BannedTy &f;
+BannedRef(const BannedTy &f): f(f) {}
+  };
+
+  BannedTy &getBanned();
+  BannedTy getBannedVal();
+
+  void foo() {
+BannedTy &a = getBanned();
+BannedTy b = getBanned(); // expected-error{{use of floating-point or vector values is disabled}}
+const BannedTy &c = getBanned();
+const BannedTy &d = getBannedVal(); // expected-error{{use of floating-point or vector values is disabled}}
+
+const int &e = 1.0;
+const int &f = BannedToInt(getBannedVal()); // expected-error{{use of floating-point or vector values is disabled}}
+
+BannedRef{getBanned()};
+BannedRef{getBannedVa

[PATCH] D38479: Make -mgeneral-regs-only more like GCC's

2017-10-18 Thread George Burgess IV via Phabricator via cfe-commits
george.burgess.iv added a comment.

> However, the tests cover floating point, but they don't cover vector calls 
> (arm_neon.h).

`#include ` gives me ~12,000 errors, presumably because there are 
so many functions that take vectors/floats defined in it. The hope was that 
calling `bar` and `foo` in aarch64-mgeneral_regs_only.c would cover similar 
cases when the banned type was a vector. Is there another another case you had 
in mind?




Comment at: lib/Sema/SemaExprCXX.cpp:7477
+static bool typeHasFloatingOrVectorComponent(
+QualType Ty, llvm::SmallDenseMap &TypeCache) {
+  if (Ty.isNull())

rengolin wrote:
> The `TypeCache` object seems local.
> 
> It doesn't look like it needs to survive outside of this function, as per its 
> usage and the comment:
> 
> // We may see recursive types in broken code.
> 
> and it just adds another argument passing.
Good point. I just ended up making this conservative in the face of broken 
code; should work just as well, and we don't have to deal with sketchy corner 
cases. :)


https://reviews.llvm.org/D38479



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


[PATCH] D38820: [CGExprScalar] Add missing types in function GetIntrinsic

2017-10-18 Thread Nemanja Ivanovic via Phabricator via cfe-commits
nemanjai accepted this revision.
nemanjai added a comment.
This revision is now accepted and ready to land.

LGTM.


https://reviews.llvm.org/D38820



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


RE: r315984 - [CodeGen] EmitPointerWithAlignment() to generate TBAA info along with LValue base info

2017-10-18 Thread Yung, Douglas via cfe-commits
Hi Ivan,

This change caused a compiler crash in one of our tests. I have put the details 
in PR34992, can you take a look?

Douglas Yung

> -Original Message-
> From: cfe-commits [mailto:cfe-commits-boun...@lists.llvm.org] On Behalf Of
> Ivan A. Kosarev via cfe-commits
> Sent: Tuesday, October 17, 2017 2:12
> To: cfe-commits@lists.llvm.org
> Subject: r315984 - [CodeGen] EmitPointerWithAlignment() to generate TBAA info
> along with LValue base info
> 
> Author: kosarev
> Date: Tue Oct 17 02:12:13 2017
> New Revision: 315984
> 
> URL: http://llvm.org/viewvc/llvm-project?rev=315984&view=rev
> Log:
> [CodeGen] EmitPointerWithAlignment() to generate TBAA info along with LValue
> base info
> 
> Differential Revision: https://reviews.llvm.org/D38796
> 
> Added:
> cfe/trunk/test/CodeGen/tbaa-cast.cpp
> Modified:
> cfe/trunk/lib/CodeGen/CGExpr.cpp
> cfe/trunk/lib/CodeGen/CodeGenFunction.cpp
> cfe/trunk/lib/CodeGen/CodeGenFunction.h
> cfe/trunk/lib/CodeGen/CodeGenModule.cpp
> cfe/trunk/lib/CodeGen/CodeGenModule.h
> cfe/trunk/lib/CodeGen/CodeGenTBAA.cpp
> cfe/trunk/lib/CodeGen/CodeGenTBAA.h
> 
> Modified: cfe/trunk/lib/CodeGen/CGExpr.cpp
> URL: http://llvm.org/viewvc/llvm-
> project/cfe/trunk/lib/CodeGen/CGExpr.cpp?rev=315984&r1=315983&r2=315984&view=d
> iff
> ==
> --- cfe/trunk/lib/CodeGen/CGExpr.cpp (original)
> +++ cfe/trunk/lib/CodeGen/CGExpr.cpp Tue Oct 17 02:12:13 2017
> @@ -916,7 +916,8 @@ void CodeGenModule::EmitExplicitCastExpr
>  /// EmitPointerWithAlignment - Given an expression of pointer type, try to
> /// derive a more accurate bound on the alignment of the pointer.
>  Address CodeGenFunction::EmitPointerWithAlignment(const Expr *E,
> -  LValueBaseInfo *BaseInfo) {
> +  LValueBaseInfo *BaseInfo,
> +  TBAAAccessInfo
> + *TBAAInfo) {
>// We allow this with ObjC object pointers because of fragile ABIs.
>assert(E->getType()->isPointerType() ||
>   E->getType()->isObjCObjectPointerType());
> @@ -936,20 +937,30 @@ Address CodeGenFunction::EmitPointerWith
>  if (PtrTy->getPointeeType()->isVoidType())
>break;
> 
> -LValueBaseInfo InnerInfo;
> -Address Addr = EmitPointerWithAlignment(CE->getSubExpr(),
> &InnerInfo);
> -if (BaseInfo) *BaseInfo = InnerInfo;
> -
> -// If this is an explicit bitcast, and the source l-value is
> -// opaque, honor the alignment of the casted-to type.
> -if (isa(CE) &&
> -InnerInfo.getAlignmentSource() != AlignmentSource::Decl) {
> -  LValueBaseInfo ExpInfo;
> +LValueBaseInfo InnerBaseInfo;
> +TBAAAccessInfo InnerTBAAInfo;
> +Address Addr = EmitPointerWithAlignment(CE->getSubExpr(),
> +&InnerBaseInfo,
> +&InnerTBAAInfo);
> +if (BaseInfo) *BaseInfo = InnerBaseInfo;
> +if (TBAAInfo) *TBAAInfo = InnerTBAAInfo;
> +
> +if (isa(CE)) {
> +  LValueBaseInfo TargetTypeBaseInfo;
> +  TBAAAccessInfo TargetTypeTBAAInfo;
>CharUnits Align = getNaturalPointeeTypeAlignment(E->getType(),
> -   &ExpInfo);
> -  if (BaseInfo)
> -BaseInfo->mergeForCast(ExpInfo);
> -  Addr = Address(Addr.getPointer(), Align);
> +
> &TargetTypeBaseInfo,
> +
> &TargetTypeTBAAInfo);
> +  if (TBAAInfo)
> +*TBAAInfo = CGM.mergeTBAAInfoForCast(*TBAAInfo,
> + TargetTypeTBAAInfo);
> +  // If the source l-value is opaque, honor the alignment of the
> +  // casted-to type.
> +  if (InnerBaseInfo.getAlignmentSource() != AlignmentSource::Decl) {
> +if (BaseInfo)
> +  BaseInfo->mergeForCast(TargetTypeBaseInfo);
> +Addr = Address(Addr.getPointer(), Align);
> +  }
>  }
> 
>  if (SanOpts.has(SanitizerKind::CFIUnrelatedCast) && @@ -969,12
> +980,13 @@ Address CodeGenFunction::EmitPointerWith
> 
>  // Array-to-pointer decay.
>  case CK_ArrayToPointerDecay:
> -  return EmitArrayToPointerDecay(CE->getSubExpr(), BaseInfo);
> +  return EmitArrayToPointerDecay(CE->getSubExpr(), BaseInfo,
> + TBAAInfo);
> 
>  // Derived-to-base conversions.
>  case CK_UncheckedDerivedToBase:
>  case CK_DerivedToBase: {
> -  Address Addr = EmitPointerWithAlignment(CE->getSubExpr(), BaseInfo);
> +  Address Addr = EmitPointerWithAlignment(CE->getSubExpr(), BaseInfo,
> +  TBAAInfo);
>auto Derived = CE->getSubExpr()->getType()->getPointeeCXXRecordDecl();
>return GetAddressOfBaseClass(Addr, Derived,
>  

r316096 - Enable support for the [[maybe_unused]] attribute from WG14 N2053 when enabling double square bracket attributes in C code.

2017-10-18 Thread Aaron Ballman via cfe-commits
Author: aaronballman
Date: Wed Oct 18 09:59:27 2017
New Revision: 316096

URL: http://llvm.org/viewvc/llvm-project?rev=316096&view=rev
Log:
Enable support for the [[maybe_unused]] attribute from WG14 N2053 when enabling 
double square bracket attributes in C code.

Added:
cfe/trunk/test/Sema/c2x-maybe_unused-errors.c
cfe/trunk/test/Sema/c2x-maybe_unused.c
Modified:
cfe/trunk/include/clang/Basic/Attr.td
cfe/trunk/lib/Sema/SemaExpr.cpp

Modified: cfe/trunk/include/clang/Basic/Attr.td
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Basic/Attr.td?rev=316096&r1=316095&r2=316096&view=diff
==
--- cfe/trunk/include/clang/Basic/Attr.td (original)
+++ cfe/trunk/include/clang/Basic/Attr.td Wed Oct 18 09:59:27 2017
@@ -1936,7 +1936,8 @@ def ObjCRequiresPropertyDefs : Inheritab
 }
 
 def Unused : InheritableAttr {
-  let Spellings = [CXX11<"", "maybe_unused", 201603>, GCC<"unused">];
+  let Spellings = [CXX11<"", "maybe_unused", 201603>, GCC<"unused">,
+   C2x<"", "maybe_unused">];
   let Subjects = SubjectList<[Var, ObjCIvar, Type, Enum, EnumConstant, Label,
   Field, ObjCMethod, FunctionLike], WarnDiag,
  "ExpectedForMaybeUnused">;

Modified: cfe/trunk/lib/Sema/SemaExpr.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Sema/SemaExpr.cpp?rev=316096&r1=316095&r2=316096&view=diff
==
--- cfe/trunk/lib/Sema/SemaExpr.cpp (original)
+++ cfe/trunk/lib/Sema/SemaExpr.cpp Wed Oct 18 09:59:27 2017
@@ -79,7 +79,8 @@ static void DiagnoseUnusedOfDecl(Sema &S
   if (const auto *A = D->getAttr()) {
 // [[maybe_unused]] should not diagnose uses, but __attribute__((unused))
 // should diagnose them.
-if (A->getSemanticSpelling() != UnusedAttr::CXX11_maybe_unused) {
+if (A->getSemanticSpelling() != UnusedAttr::CXX11_maybe_unused &&
+A->getSemanticSpelling() != UnusedAttr::C2x_maybe_unused) {
   const Decl *DC = cast_or_null(S.getCurObjCLexicalContext());
   if (DC && !DC->hasAttr())
 S.Diag(Loc, diag::warn_used_but_marked_unused) << D->getDeclName();

Added: cfe/trunk/test/Sema/c2x-maybe_unused-errors.c
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/Sema/c2x-maybe_unused-errors.c?rev=316096&view=auto
==
--- cfe/trunk/test/Sema/c2x-maybe_unused-errors.c (added)
+++ cfe/trunk/test/Sema/c2x-maybe_unused-errors.c Wed Oct 18 09:59:27 2017
@@ -0,0 +1,12 @@
+// RUN: %clang_cc1 -fsyntax-only -Wunused -fdouble-square-bracket-attributes 
-verify %s
+
+struct [[maybe_unused]] S1 { // ok
+  int a [[maybe_unused]];
+};
+struct [[maybe_unused maybe_unused]] S2 { // expected-error {{attribute 
'maybe_unused' cannot appear multiple times in an attribute specifier}}
+  int a;
+};
+struct [[maybe_unused("Wrong")]] S3 { // expected-error {{'maybe_unused' 
cannot have an argument list}}
+  int a;
+};
+

Added: cfe/trunk/test/Sema/c2x-maybe_unused.c
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/Sema/c2x-maybe_unused.c?rev=316096&view=auto
==
--- cfe/trunk/test/Sema/c2x-maybe_unused.c (added)
+++ cfe/trunk/test/Sema/c2x-maybe_unused.c Wed Oct 18 09:59:27 2017
@@ -0,0 +1,35 @@
+// RUN: %clang_cc1 -fsyntax-only -Wunused -fdouble-square-bracket-attributes 
-verify %s
+
+struct [[maybe_unused]] S1 { // ok
+  int a [[maybe_unused]];
+};
+
+enum [[maybe_unused]] E1 {
+  EnumVal [[maybe_unused]]
+};
+
+[[maybe_unused]] void unused_func([[maybe_unused]] int parm) {
+  typedef int maybe_unused_int [[maybe_unused]];
+  [[maybe_unused]] int I;
+}
+
+void f1(void) {
+  int x; // expected-warning {{unused variable}}
+  typedef int I; // expected-warning {{unused typedef 'I'}}
+
+  // Should not warn about these due to not being used.
+  [[maybe_unused]] int y;
+  typedef int maybe_unused_int [[maybe_unused]];
+
+  // Should not warn about these uses.
+  struct S1 s;
+  maybe_unused_int test;
+  y = 12;
+}
+
+void f2(void);
+[[maybe_unused]] void f2(void);
+
+void f2(void) {
+}
+


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


[PATCH] D37955: [libcxx] Fix invert negative bracket match.

2017-10-18 Thread Marshall Clow via Phabricator via cfe-commits
mclow.lists closed this revision.
mclow.lists added a comment.

Landed as revision 316095.


https://reviews.llvm.org/D37955



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


[libcxx] r316095 - Fix regex bug with ^\W. Thanks to Tim Shen for the patch. Reviewed as https://reviews.llvm.org/D37955

2017-10-18 Thread Marshall Clow via cfe-commits
Author: marshall
Date: Wed Oct 18 09:49:22 2017
New Revision: 316095

URL: http://llvm.org/viewvc/llvm-project?rev=316095&view=rev
Log:
Fix regex bug with ^\W. Thanks to Tim Shen for the patch. Reviewed as 
https://reviews.llvm.org/D37955

Added:

libcxx/trunk/test/std/re/re.alg/re.alg.search/invert_neg_word_search.pass.cpp
Modified:
libcxx/trunk/include/regex

Modified: libcxx/trunk/include/regex
URL: 
http://llvm.org/viewvc/llvm-project/libcxx/trunk/include/regex?rev=316095&r1=316094&r2=316095&view=diff
==
--- libcxx/trunk/include/regex (original)
+++ libcxx/trunk/include/regex Wed Oct 18 09:49:22 2017
@@ -2409,17 +2409,28 @@ __bracket_expression<_CharT, _Traits>::_
 goto __exit;
 }
 }
-if (!__neg_chars_.empty())
+// set of "__found" chars =
+//   union(complement(union(__neg_chars_, __neg_mask_)),
+// other cases...)
+//
+// __neg_chars_ and __neg_mask_'d better be handled together, as there
+// are no short circuit opportunities.
+//
+// In addition, when __neg_mask_/__neg_chars_ is empty, they should be
+// treated as all ones/all chars.
 {
-for (size_t __i = 0; __i < __neg_chars_.size(); ++__i)
-{
-if (__ch == __neg_chars_[__i])
-goto __is_neg_char;
-}
+  const bool __in_neg_mask = (__neg_mask_ == 0) ||
+  __traits_.isctype(__ch, __neg_mask_);
+  const bool __in_neg_chars =
+  __neg_chars_.empty() ||
+  std::find(__neg_chars_.begin(), __neg_chars_.end(), __ch) !=
+  __neg_chars_.end();
+  if (!(__in_neg_mask || __in_neg_chars))
+  {
 __found = true;
 goto __exit;
+  }
 }
-__is_neg_char:
 if (!__ranges_.empty())
 {
 string_type __s2 = __collate_ ?
@@ -2450,11 +2461,6 @@ __is_neg_char:
 {
 __found = true;
 goto __exit;
-}
-if (__neg_mask_ && !__traits_.isctype(__ch, __neg_mask_))
-{
-__found = true;
-goto __exit;
 }
 }
 else

Added: 
libcxx/trunk/test/std/re/re.alg/re.alg.search/invert_neg_word_search.pass.cpp
URL: 
http://llvm.org/viewvc/llvm-project/libcxx/trunk/test/std/re/re.alg/re.alg.search/invert_neg_word_search.pass.cpp?rev=316095&view=auto
==
--- 
libcxx/trunk/test/std/re/re.alg/re.alg.search/invert_neg_word_search.pass.cpp 
(added)
+++ 
libcxx/trunk/test/std/re/re.alg/re.alg.search/invert_neg_word_search.pass.cpp 
Wed Oct 18 09:49:22 2017
@@ -0,0 +1,29 @@
+//===--===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is dual licensed under the MIT and the University of Illinois Open
+// Source Licenses. See LICENSE.TXT for details.
+//
+//===--===//
+
+// 
+
+// template 
+// bool
+// regex_search(BidirectionalIterator first, BidirectionalIterator last,
+//  match_results& m,
+//  const basic_regex& e,
+//  regex_constants::match_flag_type flags = 
regex_constants::match_default);
+
+#include 
+#include 
+#include "test_macros.h"
+
+// PR34310
+int main()
+{
+  assert(std::regex_search("HelloWorld", std::regex("[^\\W]")));
+  assert(std::regex_search("_", std::regex("[^\\W]")));
+  return 0;
+}


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


[clang-tools-extra] r316094 - [clang-tidy] Fix 32bit platform MSVC

2017-10-18 Thread Jonas Toth via cfe-commits
Author: jonastoth
Date: Wed Oct 18 09:40:19 2017
New Revision: 316094

URL: http://llvm.org/viewvc/llvm-project?rev=316094&view=rev
Log:
[clang-tidy] Fix 32bit platform MSVC

The previous fix only worked for 64bit MSVC, this one should fix all different
architectures.

Modified:

clang-tools-extra/trunk/test/clang-tidy/cppcoreguidelines-owning-memory-legacy-functions.cpp

Modified: 
clang-tools-extra/trunk/test/clang-tidy/cppcoreguidelines-owning-memory-legacy-functions.cpp
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/test/clang-tidy/cppcoreguidelines-owning-memory-legacy-functions.cpp?rev=316094&r1=316093&r2=316094&view=diff
==
--- 
clang-tools-extra/trunk/test/clang-tidy/cppcoreguidelines-owning-memory-legacy-functions.cpp
 (original)
+++ 
clang-tools-extra/trunk/test/clang-tidy/cppcoreguidelines-owning-memory-legacy-functions.cpp
 Wed Oct 18 09:40:19 2017
@@ -10,7 +10,7 @@ using owner = T;
 } // namespace gsl
 
 extern "C" {
-using size_t = unsigned long long;
+using size_t = decltype(sizeof(void*));
 using FILE = int;
 
 void *malloc(size_t ByteCount);


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


[clang-tools-extra] r316093 - [clang-tidy] Fix buildbot for msvc

2017-10-18 Thread Jonas Toth via cfe-commits
Author: jonastoth
Date: Wed Oct 18 09:28:06 2017
New Revision: 316093

URL: http://llvm.org/viewvc/llvm-project?rev=316093&view=rev
Log:
[clang-tidy] Fix buildbot for msvc

The testcase defined `FILE` as `unsigned long`, but MSVC expect `unsigned long 
long`.

Modified:

clang-tools-extra/trunk/test/clang-tidy/cppcoreguidelines-owning-memory-legacy-functions.cpp

Modified: 
clang-tools-extra/trunk/test/clang-tidy/cppcoreguidelines-owning-memory-legacy-functions.cpp
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/test/clang-tidy/cppcoreguidelines-owning-memory-legacy-functions.cpp?rev=316093&r1=316092&r2=316093&view=diff
==
--- 
clang-tools-extra/trunk/test/clang-tidy/cppcoreguidelines-owning-memory-legacy-functions.cpp
 (original)
+++ 
clang-tools-extra/trunk/test/clang-tidy/cppcoreguidelines-owning-memory-legacy-functions.cpp
 Wed Oct 18 09:28:06 2017
@@ -10,7 +10,7 @@ using owner = T;
 } // namespace gsl
 
 extern "C" {
-using size_t = unsigned long;
+using size_t = unsigned long long;
 using FILE = int;
 
 void *malloc(size_t ByteCount);


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


[PATCH] D38820: [CGExprScalar] Add missing types in function GetIntrinsic

2017-10-18 Thread Guozhi Wei via Phabricator via cfe-commits
Carrot added a comment.

ping


https://reviews.llvm.org/D38820



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


[clang-tools-extra] r316092 - [clang-tidy] introduce legacy resource functions to 'cppcoreguidelines-owning-memory'

2017-10-18 Thread Jonas Toth via cfe-commits
Author: jonastoth
Date: Wed Oct 18 09:14:15 2017
New Revision: 316092

URL: http://llvm.org/viewvc/llvm-project?rev=316092&view=rev
Log:
[clang-tidy] introduce legacy resource functions to 
'cppcoreguidelines-owning-memory'

Summary:
This patch introduces support for legacy C-style resource functions that must 
obey
the 'owner<>' semantics.

- added legacy creators like malloc,fopen,...
- added legacy consumers like free,fclose,...

This helps codes that mostly benefit from owner:
Legacy, C-Style code that isn't feasable to port directly to RAII but needs a 
step in between
to identify actual resource management and just using the resources.

Reviewers: aaron.ballman, alexfh, hokein

Reviewed By: aaron.ballman

Subscribers: nemanjai, JDevlieghere, xazax.hun, kbarton

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


Added:

clang-tools-extra/trunk/test/clang-tidy/cppcoreguidelines-owning-memory-containers.cpp

clang-tools-extra/trunk/test/clang-tidy/cppcoreguidelines-owning-memory-legacy-functions.cpp
Modified:
clang-tools-extra/trunk/clang-tidy/cppcoreguidelines/OwningMemoryCheck.cpp
clang-tools-extra/trunk/clang-tidy/cppcoreguidelines/OwningMemoryCheck.h

clang-tools-extra/trunk/docs/clang-tidy/checks/cppcoreguidelines-owning-memory.rst

Modified: 
clang-tools-extra/trunk/clang-tidy/cppcoreguidelines/OwningMemoryCheck.cpp
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clang-tidy/cppcoreguidelines/OwningMemoryCheck.cpp?rev=316092&r1=316091&r2=316092&view=diff
==
--- clang-tools-extra/trunk/clang-tidy/cppcoreguidelines/OwningMemoryCheck.cpp 
(original)
+++ clang-tools-extra/trunk/clang-tidy/cppcoreguidelines/OwningMemoryCheck.cpp 
Wed Oct 18 09:14:15 2017
@@ -22,6 +22,21 @@ namespace clang {
 namespace tidy {
 namespace cppcoreguidelines {
 
+// FIXME: Copied from 'NoMallocCheck.cpp'. Has to be refactored into 'util' or
+// something like that.
+namespace {
+Matcher hasAnyListedName(const std::string &FunctionNames) {
+  const std::vector NameList =
+  utils::options::parseStringList(FunctionNames);
+  return hasAnyName(std::vector(NameList.begin(), NameList.end()));
+}
+} // namespace
+
+void OwningMemoryCheck::storeOptions(ClangTidyOptions::OptionMap &Opts) {
+  Options.store(Opts, "LegacyResourceProducers", LegacyResourceProducers);
+  Options.store(Opts, "LegacyResourceConsumers", LegacyResourceConsumers);
+}
+
 /// Match common cases, where the owner semantic is relevant, like function
 /// calls, delete expressions and others.
 void OwningMemoryCheck::registerMatchers(MatchFinder *Finder) {
@@ -30,10 +45,31 @@ void OwningMemoryCheck::registerMatchers
 
   const auto OwnerDecl = typeAliasTemplateDecl(hasName("::gsl::owner"));
   const auto IsOwnerType = hasType(OwnerDecl);
+
+  const auto LegacyCreatorFunctions = 
hasAnyListedName(LegacyResourceProducers);
+  const auto LegacyConsumerFunctions =
+  hasAnyListedName(LegacyResourceConsumers);
+
+  // Legacy functions that are use for resource management but cannot be
+  // updated to use `gsl::owner<>`, like standard C memory management.
+  const auto CreatesLegacyOwner =
+  callExpr(callee(functionDecl(LegacyCreatorFunctions)));
+  // C-style functions like `::malloc()` sometimes create owners as void*
+  // which is expected to be cast to the correct type in C++. This case
+  // must be catched explicitly.
+  const auto LegacyOwnerCast =
+  castExpr(hasSourceExpression(CreatesLegacyOwner));
+  // Functions that do manual resource management but cannot be updated to use
+  // owner. Best example is `::free()`.
+  const auto LegacyOwnerConsumers = functionDecl(LegacyConsumerFunctions);
+
   const auto CreatesOwner =
-  anyOf(cxxNewExpr(), callExpr(callee(functionDecl(
-  returns(qualType(hasDeclaration(OwnerDecl)));
-  const auto ConsideredOwner = anyOf(IsOwnerType, CreatesOwner);
+  anyOf(cxxNewExpr(),
+callExpr(callee(
+functionDecl(returns(qualType(hasDeclaration(OwnerDecl)),
+CreatesLegacyOwner, LegacyOwnerCast);
+
+  const auto ConsideredOwner = eachOf(IsOwnerType, CreatesOwner);
 
   // Find delete expressions that delete non-owners.
   Finder->addMatcher(
@@ -43,6 +79,21 @@ void OwningMemoryCheck::registerMatchers
   .bind("delete_expr"),
   this);
 
+  // Ignoring the implicit casts is vital because the legacy owners do not work
+  // with the 'owner<>' annotation and therefore always implicitly cast to the
+  // legacy type (even 'void *').
+  //
+  // Furthermore, legacy owner functions are assumed to use raw pointers for
+  // resources. This check assumes that all pointer arguments of a legacy
+  // functions shall be 'gsl::owner<>'.
+  Finder->addMatcher(
+  callExpr(
+  allOf(callee(LegacyOwnerConsumers),
+hasAnyArgument(allOf(unless(ignoringImpCasts(ConsideredOwner)),
+

[clang-tools-extra] r316090 - Support Objective-C/C++ source files in check_clang_tidy.py

2017-10-18 Thread Haojian Wu via cfe-commits
Author: hokein
Date: Wed Oct 18 08:56:39 2017
New Revision: 316090

URL: http://llvm.org/viewvc/llvm-project?rev=316090&view=rev
Log:
Support Objective-C/C++ source files in check_clang_tidy.py

check_clang_tidy.py currently only handles C and C++ source files.

This extends the logic to also handle Objective-C (.m) and
Objective-C++ (.mm) files.

However, by default, clang compiles .m/.mm files using Objective-C 1.0
syntax. Objective-C 2.0 has been the default in Xcode for about 10
years, and Objective-C Automatic Reference Counting (ARC) for about 6
years, so this enables both by default.

(Clients which actually want to test clang-tidy checks for Objective-C
 1.0 or non-ARC files can pass custom flags to check_clang_tidy.py
 after --, which will disable the Objective-C 2.0 and ARC flags).

I did not add logic to handle running clang-tidy on Objective-C header
files alone; they also use the .h file extension, so we'd need to
look inside their contents.

I included a new test to confirm the new behavior.

Depends On D38963

Patch by Ben Hamilton!

Modified:
clang-tools-extra/trunk/test/clang-tidy/check_clang_tidy.py

Modified: clang-tools-extra/trunk/test/clang-tidy/check_clang_tidy.py
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/test/clang-tidy/check_clang_tidy.py?rev=316090&r1=316089&r2=316090&view=diff
==
--- clang-tools-extra/trunk/test/clang-tidy/check_clang_tidy.py (original)
+++ clang-tools-extra/trunk/test/clang-tidy/check_clang_tidy.py Wed Oct 18 
08:56:39 2017
@@ -26,6 +26,7 @@ Example:
 """
 
 import argparse
+import os
 import re
 import subprocess
 import sys
@@ -53,18 +54,19 @@ def main():
   temp_file_name = args.temp_file_name
 
   file_name_with_extension = assume_file_name or input_file_name
-
-  extension = '.cpp'
-  if (file_name_with_extension.endswith('.c')):
-extension = '.c'
-  if (file_name_with_extension.endswith('.hpp')):
-extension = '.hpp'
+  _, extension = os.path.splitext(file_name_with_extension)
+  if extension not in ['.c', '.hpp', '.m', '.mm']:
+extension = '.cpp'
   temp_file_name = temp_file_name + extension
 
   clang_tidy_extra_args = extra_args
   if len(clang_tidy_extra_args) == 0:
-clang_tidy_extra_args = ['--', '--std=c++11'] \
-if extension == '.cpp' or extension == '.hpp' else ['--']
+clang_tidy_extra_args = ['--']
+if extension in ['.cpp', '.hpp', '.mm']:
+  clang_tidy_extra_args.append('--std=c++11')
+if extension in ['.m', '.mm']:
+  clang_tidy_extra_args.extend(
+  ['-fobjc-abi-version=2', '-fobjc-arc'])
 
   # Tests should not rely on STL being available, and instead provide mock
   # implementations of relevant APIs.


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


[PATCH] D39005: [OpenMP] Clean up variable and function names for NVPTX backend

2017-10-18 Thread Justin Lebar via Phabricator via cfe-commits
jlebar added a comment.

> The first question that comes to mind is what is the link between data layout 
> and name mangling conventions?

I pulled up http://llvm.org/doxygen/classllvm_1_1DataLayout.html and searched 
for "mangling" -- presumably this is what they were referring to.  We also 
don't need to speculate, rnk still works on LLVM.  :)


Repository:
  rL LLVM

https://reviews.llvm.org/D39005



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


[PATCH] D39005: [OpenMP] Clean up variable and function names for NVPTX backend

2017-10-18 Thread Gheorghe-Teodor Bercea via Phabricator via cfe-commits
gtbercea added a comment.

In https://reviews.llvm.org/D39005#900226, @jlebar wrote:

> > I'd be interested to get the ball rolling in regard to coming up with a fix 
> > for this. I see some suggestions in past patches. Some help/clarification 
> > would be much appreciated.
>
> Happy to help, but I'm not sure what to offer beyond the link in Art's 
> previous comment.


Thanks Justin. Perhaps if we could start by clarifying this statement "One 
option is that we add a function to LLVM get an available separator character, 
which can default to '.', but we set to '$' for nvptx, and use that for 
generating new names at the IR level."  as well as this statement "This seems 
practical. Perhaps it could be part of the name mangling scheme already encoded 
in DataLayout?".

The first question that comes to mind is what is the link between data layout 
and name mangling conventions?


Repository:
  rL LLVM

https://reviews.llvm.org/D39005



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


[PATCH] D38852: [Hexagon] Handling of new HVX flags and target-features

2017-10-18 Thread Sumanth Gundapaneni via Phabricator via cfe-commits
sgundapa added a comment.

Ping


Repository:
  rL LLVM

https://reviews.llvm.org/D38852



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


[PATCH] D38985: [refactor] Add support for editor commands that connect IDEs/editors to the refactoring actions

2017-10-18 Thread Eric Liu via Phabricator via cfe-commits
ioeric added inline comments.



Comment at: include/clang/Tooling/Refactoring/RefactoringActionRule.h:58
+  /// Returns the editor command that's was bound to this rule.
+  virtual const EditorCommand *getEditorCommand() { return nullptr; }
 };

arphaman wrote:
> ioeric wrote:
> > I'm still not quite sure about the intention of `EditorCommand` (is it 
> > supposed to be used as a mapping from name to rule, or the other way 
> > around?), but I'm a bit concerned about mixing editor logic with the 
> > refactoring rules this way. Also to enable a editor command, it seems to me 
> > that we would need to touch both the registry and the rule creation code, 
> > which seems a bit cumbersome.
> > 
> > I think we should either 1) separate out the command logic cleanly without 
> > touching action/rule interfaces in the refactoring engine or 2) simply bake 
> > the logic into the refactoring engine.
> > 
> > It is unclear to me if 1) is possible, but for 2), I think we could 
> > introduce a `RefactoringEngine` class which carries all refactoring actions 
> > as well as a map to serve the purpose of `EditorCommand`. And I think by 
> > doing this, we could also make the interfaces of `RefactoringEngine` more 
> > explicit.
> (Quick comment before the devmeeting:)
> Mapping from name to rule.
> You're right though, It might be better to explore an alternative solution, 
> but I don't quite follow your proposal yet. I'll be in the tooling hacker's 
> lab at the dev meeting today if you want to discuss this in person.
Currently, we have `createRefactoringActions` as the API of the refactoring 
engine/library.  I think we could introduce a `RefactoringEngine` class that 
exposes all user-facing interfaces from the engine, including 
creating/accessing actions and providing the mapping of editor command. And the 
command registration could be handled inside the class, which I assume would be 
simpler. This would also allow us to expose more interfaces in the future via 
this class.

(Sorry, I didn't make it to the dev meeting this year... I hope I could get a 
chance to meet you in the next dev meeting or the European dev meeting early 
next year :)


Repository:
  rL LLVM

https://reviews.llvm.org/D38985



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


[PATCH] D39035: Unnamed bitfields don't block constant evaluation of constexpr constructors

2017-10-18 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.

Aside from some minor nits, LGTM!




Comment at: test/SemaCXX/constant-expression-cxx11.cpp:1924
+
+
+  struct HasUnnamedBitfield {

Can remove the spurious newline.



Comment at: test/SemaCXX/warn-global-constructors.cpp:130
+
+namespace HasUnnamedBitfield {
+  struct HasUnnamedBitfield {

Does this namespace require a name? If so, can it be named different than the 
struct declared within it?



Comment at: test/SemaCXX/warn-global-constructors.cpp:148
+}
\ No newline at end of file


Please ensure the file retains its newline.


Repository:
  rL LLVM

https://reviews.llvm.org/D39035



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


r316086 - Silencing a redefinition warning that was not germane to the test.

2017-10-18 Thread Aaron Ballman via cfe-commits
Author: aaronballman
Date: Wed Oct 18 07:48:33 2017
New Revision: 316086

URL: http://llvm.org/viewvc/llvm-project?rev=316086&view=rev
Log:
Silencing a redefinition warning that was not germane to the test.

Modified:
cfe/trunk/test/Sema/c2x-fallthrough.c

Modified: cfe/trunk/test/Sema/c2x-fallthrough.c
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/Sema/c2x-fallthrough.c?rev=316086&r1=316085&r2=316086&view=diff
==
--- cfe/trunk/test/Sema/c2x-fallthrough.c (original)
+++ cfe/trunk/test/Sema/c2x-fallthrough.c Wed Oct 18 07:48:33 2017
@@ -43,9 +43,9 @@ void f(int n) {
   }
 }
 
-[[fallthrough]] typedef int n; // expected-error {{'fallthrough' attribute 
cannot be applied to a declaration}}
-typedef int [[fallthrough]] n; // expected-error {{'fallthrough' attribute 
cannot be applied to types}}
-typedef int n [[fallthrough]]; // expected-error {{'fallthrough' attribute 
cannot be applied to a declaration}}
+[[fallthrough]] typedef int n1; // expected-error {{'fallthrough' attribute 
cannot be applied to a declaration}}
+typedef int [[fallthrough]] n2; // expected-error {{'fallthrough' attribute 
cannot be applied to types}}
+typedef int n3 [[fallthrough]]; // expected-error {{'fallthrough' attribute 
cannot be applied to a declaration}}
 
 enum [[fallthrough]] E { // expected-error {{'fallthrough' attribute cannot be 
applied to a declaration}}
   One


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


Re: r315856 - Add -f[no-]double-square-bracket-attributes as new driver options to control use of [[]] attributes in all language modes. This is the initial implementation of WG14 N2165, which is a pr

2017-10-18 Thread Aaron Ballman via cfe-commits
Thanks for pointing the breakage out -- it should be fixed with r316075.

~Aaron

On Wed, Oct 18, 2017 at 7:50 AM, Aaron Ballman  wrote:
> I'll take a look, thank you for pointing it out (and sorry for the trouble)!
>
> ~Aaron
>
> On Tue, Oct 17, 2017 at 9:56 PM, Galina Kistanova  
> wrote:
>> Hello Aaron,
>>
>> This commit broke one our builders:
>>
>> http://lab.llvm.org:8011/builders/ubuntu-gcc7.1-werror/builds/2272
>>
>> . . .
>> FAILED: /usr/local/gcc-7.1/bin/g++-7.1   -DGTEST_HAS_RTTI=0 -D_DEBUG
>> -D_GNU_SOURCE -D__STDC_CONSTANT_MACROS -D__STDC_FORMAT_MACROS
>> -D__STDC_LIMIT_MACROS -Itools/clang/lib/Basic
>> -I/home/buildslave/am1i-slv2/ubuntu-gcc7.1-werror/llvm/tools/clang/lib/Basic
>> -I/home/buildslave/am1i-slv2/ubuntu-gcc7.1-werror/llvm/tools/clang/include
>> -Itools/clang/include -Iinclude
>> -I/home/buildslave/am1i-slv2/ubuntu-gcc7.1-werror/llvm/include
>> -Wno-noexcept-type -fPIC -fvisibility-inlines-hidden -Werror
>> -Werror=date-time -std=c++11 -Wall -W -Wno-unused-parameter -Wwrite-strings
>> -Wcast-qual -Wno-missing-field-initializers -pedantic -Wno-long-long
>> -Wno-maybe-uninitialized -Wdelete-non-virtual-dtor -Wno-comment
>> -ffunction-sections -fdata-sections -fno-common -Woverloaded-virtual
>> -fno-strict-aliasing -O3  -fPIC   -UNDEBUG  -fno-exceptions -fno-rtti -MD
>> -MT tools/clang/lib/Basic/CMakeFiles/clangBasic.dir/Attributes.cpp.o -MF
>> tools/clang/lib/Basic/CMakeFiles/clangBasic.dir/Attributes.cpp.o.d -o
>> tools/clang/lib/Basic/CMakeFiles/clangBasic.dir/Attributes.cpp.o -c
>> /home/buildslave/am1i-slv2/ubuntu-gcc7.1-werror/llvm/tools/clang/lib/Basic/Attributes.cpp
>> In file included from
>> /home/buildslave/am1i-slv2/ubuntu-gcc7.1-werror/llvm/tools/clang/lib/Basic/Attributes.cpp:15:0:
>> tools/clang/include/clang/Basic/AttrHasAttributeImpl.inc: In function ‘int
>> clang::hasAttribute(clang::AttrSyntax, const clang::IdentifierInfo*, const
>> clang::IdentifierInfo*, const clang::TargetInfo&, const
>> clang::LangOptions&)’:
>> tools/clang/include/clang/Basic/AttrHasAttributeImpl.inc:526:8: error: this
>> statement may fall through [-Werror=implicit-fallthrough=]
>>  } else if (Scope->getName() == "gsl") {
>> ^~
>> tools/clang/include/clang/Basic/AttrHasAttributeImpl.inc:532:1: note: here
>>  case AttrSyntax::C: {
>>  ^~~~
>> cc1plus: all warnings being treated as errors
>>
>> Please have a look?
>>
>> Thanks
>>
>> Galina
>>
>> On Sun, Oct 15, 2017 at 8:01 AM, Aaron Ballman via cfe-commits
>>  wrote:
>>>
>>> Author: aaronballman
>>> Date: Sun Oct 15 08:01:42 2017
>>> New Revision: 315856
>>>
>>> URL: http://llvm.org/viewvc/llvm-project?rev=315856&view=rev
>>> Log:
>>> Add -f[no-]double-square-bracket-attributes as new driver options to
>>> control use of [[]] attributes in all language modes. This is the initial
>>> implementation of WG14 N2165, which is a proposal to add [[]] attributes to
>>> C2x, but also allows you to enable these attributes in C++98, or disable
>>> them in C++11 or later.
>>>
>>> Added:
>>> cfe/trunk/test/Misc/ast-dump-c-attr.c
>>> cfe/trunk/test/Parser/c2x-attributes.c
>>> cfe/trunk/test/Parser/c2x-attributes.m
>>> cfe/trunk/test/Sema/attr-deprecated-c2x.c
>>> Modified:
>>> cfe/trunk/include/clang/Basic/Attr.td
>>> cfe/trunk/include/clang/Basic/Attributes.h
>>> cfe/trunk/include/clang/Basic/LangOptions.def
>>> cfe/trunk/include/clang/Driver/Options.td
>>> cfe/trunk/include/clang/Parse/Parser.h
>>> cfe/trunk/include/clang/Sema/AttributeList.h
>>> cfe/trunk/lib/Frontend/CompilerInvocation.cpp
>>> cfe/trunk/lib/Lex/Lexer.cpp
>>> cfe/trunk/lib/Parse/ParseDecl.cpp
>>> cfe/trunk/lib/Parse/ParseDeclCXX.cpp
>>> cfe/trunk/lib/Sema/AttributeList.cpp
>>> cfe/trunk/utils/TableGen/ClangAttrEmitter.cpp
>>>
>>> Modified: cfe/trunk/include/clang/Basic/Attr.td
>>> URL:
>>> http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Basic/Attr.td?rev=315856&r1=315855&r2=315856&view=diff
>>>
>>> ==
>>> --- cfe/trunk/include/clang/Basic/Attr.td (original)
>>> +++ cfe/trunk/include/clang/Basic/Attr.td Sun Oct 15 08:01:42 2017
>>> @@ -210,6 +210,10 @@ class CXX11>>string Namespace = namespace;
>>>int Version = version;
>>>  }
>>> +class C2x : Spelling {
>>> +  string Namespace = namespace;
>>> +}
>>> +
>>>  class Keyword : Spelling;
>>>  class Pragma : Spelling {
>>>string Namespace = namespace;
>>> @@ -958,7 +962,7 @@ def RenderScriptKernel : Attr {
>>>
>>>  def Deprecated : InheritableAttr {
>>>let Spellings = [GCC<"deprecated">, Declspec<"deprecated">,
>>> -   CXX11<"","deprecated", 201309>];
>>> +   CXX11<"","deprecated", 201309>, C2x<"",
>>> "deprecated">];
>>>let Args = [StringArgument<"Message", 1>,
>>>// An optional string argument that enables us to provide a
>>>// Fix-It.
>>>
>>> Modified: cfe/trunk/include/clang/Basic/Attributes.h
>>> UR

r316083 - Enable support for the [[fallthrough]] attribute from WG14 N2052 when enabling double square bracket attributes in C code.

2017-10-18 Thread Aaron Ballman via cfe-commits
Author: aaronballman
Date: Wed Oct 18 07:33:27 2017
New Revision: 316083

URL: http://llvm.org/viewvc/llvm-project?rev=316083&view=rev
Log:
Enable support for the [[fallthrough]] attribute from WG14 N2052 when enabling 
double square bracket attributes in C code.

Added:
cfe/trunk/test/Sema/c2x-fallthrough.c
Modified:
cfe/trunk/include/clang/Basic/Attr.td
cfe/trunk/lib/Sema/AnalysisBasedWarnings.cpp

Modified: cfe/trunk/include/clang/Basic/Attr.td
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Basic/Attr.td?rev=316083&r1=316082&r2=316083&view=diff
==
--- cfe/trunk/include/clang/Basic/Attr.td (original)
+++ cfe/trunk/include/clang/Basic/Attr.td Wed Oct 18 07:33:27 2017
@@ -1009,7 +1009,7 @@ def ExtVectorType : Attr {
 }
 
 def FallThrough : StmtAttr {
-  let Spellings = [CXX11<"", "fallthrough", 201603>,
+  let Spellings = [CXX11<"", "fallthrough", 201603>, C2x<"", "fallthrough">,
CXX11<"clang", "fallthrough">];
 //  let Subjects = [NullStmt];
   let Documentation = [FallthroughDocs];

Modified: cfe/trunk/lib/Sema/AnalysisBasedWarnings.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Sema/AnalysisBasedWarnings.cpp?rev=316083&r1=316082&r2=316083&view=diff
==
--- cfe/trunk/lib/Sema/AnalysisBasedWarnings.cpp (original)
+++ cfe/trunk/lib/Sema/AnalysisBasedWarnings.cpp Wed Oct 18 07:33:27 2017
@@ -1291,16 +1291,15 @@ static StringRef getFallthroughAttrSpell
 
 static void DiagnoseSwitchLabelsFallthrough(Sema &S, AnalysisDeclContext &AC,
 bool PerFunction) {
-  // Only perform this analysis when using C++11.  There is no good workflow
-  // for this warning when not using C++11.  There is no good way to silence
-  // the warning (no attribute is available) unless we are using C++11's 
support
-  // for generalized attributes.  Once could use pragmas to silence the 
warning,
-  // but as a general solution that is gross and not in the spirit of this
-  // warning.
+  // Only perform this analysis when using [[]] attributes. There is no good
+  // workflow for this warning when not using C++11. There is no good way to
+  // silence the warning (no attribute is available) unless we are using 
+  // [[]] attributes. One could use pragmas to silence the warning, but as a
+  // general solution that is gross and not in the spirit of this warning.
   //
-  // NOTE: This an intermediate solution.  There are on-going discussions on
+  // NOTE: This an intermediate solution. There are on-going discussions on
   // how to properly support this warning outside of C++11 with an annotation.
-  if (!AC.getASTContext().getLangOpts().CPlusPlus11)
+  if (!AC.getASTContext().getLangOpts().DoubleSquareBracketAttributes)
 return;
 
   FallthroughMapper FM(S);

Added: cfe/trunk/test/Sema/c2x-fallthrough.c
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/Sema/c2x-fallthrough.c?rev=316083&view=auto
==
--- cfe/trunk/test/Sema/c2x-fallthrough.c (added)
+++ cfe/trunk/test/Sema/c2x-fallthrough.c Wed Oct 18 07:33:27 2017
@@ -0,0 +1,75 @@
+// RUN: %clang_cc1 -fsyntax-only -fdouble-square-bracket-attributes -verify %s
+
+void f(int n) {
+  switch (n) {
+  case 0:
+n += 1;
+[[fallthrough]]; // ok
+  case 1:
+if (n) {
+  [[fallthrough]]; // ok
+} else {
+  return;
+}
+  case 2:
+for (int n = 0; n != 10; ++n)
+  [[fallthrough]]; // expected-error {{does not directly precede switch 
label}}
+  case 3:
+while (1)
+  [[fallthrough]]; // expected-error {{does not directly precede switch 
label}}
+  case 4:
+while (0)
+  [[fallthrough]]; // expected-error {{does not directly precede switch 
label}}
+  case 5:
+do [[fallthrough]]; while (1); // expected-error {{does not directly 
precede switch label}}
+  case 6:
+do [[fallthrough]]; while (0); // expected-error {{does not directly 
precede switch label}}
+  case 7:
+switch (n) {
+case 0:
+  // FIXME: This should be an error, even though the next thing we do is to
+  // fall through in an outer switch statement.
+  [[fallthrough]];
+}
+  case 8:
+[[fallthrough]]; // expected-error {{does not directly precede switch 
label}}
+goto label;
+  label:
+  case 9:
+n += 1;
+  case 10: // no warning, -Wimplicit-fallthrough is not enabled in this test, 
and does not need to
+   // be enabled for these diagnostics to be produced.
+break;
+  }
+}
+
+[[fallthrough]] typedef int n; // expected-error {{'fallthrough' attribute 
cannot be applied to a declaration}}
+typedef int [[fallthrough]] n; // expected-error {{'fallthrough' attribute 
cannot be applied to types}}
+typedef int n [[fallthrough]]; // expected-error {{'fallthrough' attribute 
cannot be applied to a decla

[PATCH] D38985: [refactor] Add support for editor commands that connect IDEs/editors to the refactoring actions

2017-10-18 Thread Alex Lorenz via Phabricator via cfe-commits
arphaman added inline comments.



Comment at: include/clang/Tooling/Refactoring/RefactoringActionRule.h:58
+  /// Returns the editor command that's was bound to this rule.
+  virtual const EditorCommand *getEditorCommand() { return nullptr; }
 };

ioeric wrote:
> I'm still not quite sure about the intention of `EditorCommand` (is it 
> supposed to be used as a mapping from name to rule, or the other way 
> around?), but I'm a bit concerned about mixing editor logic with the 
> refactoring rules this way. Also to enable a editor command, it seems to me 
> that we would need to touch both the registry and the rule creation code, 
> which seems a bit cumbersome.
> 
> I think we should either 1) separate out the command logic cleanly without 
> touching action/rule interfaces in the refactoring engine or 2) simply bake 
> the logic into the refactoring engine.
> 
> It is unclear to me if 1) is possible, but for 2), I think we could introduce 
> a `RefactoringEngine` class which carries all refactoring actions as well as 
> a map to serve the purpose of `EditorCommand`. And I think by doing this, we 
> could also make the interfaces of `RefactoringEngine` more explicit.
(Quick comment before the devmeeting:)
Mapping from name to rule.
You're right though, It might be better to explore an alternative solution, but 
I don't quite follow your proposal yet. I'll be in the tooling hacker's lab at 
the dev meeting today if you want to discuss this in person.


Repository:
  rL LLVM

https://reviews.llvm.org/D38985



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


[PATCH] D39027: [docs][refactor] Add a new tutorial that talks about how one can implement refactoring actions

2017-10-18 Thread Jonas Toth via Phabricator via cfe-commits
JonasToth added inline comments.



Comment at: docs/RefactoringActionTutorial.rst:90
+Let's call it something like ``FlattenIfStatements.cpp``. Don't forget to add
+it to the ``CMakeLists.txt`` file that's located in the
+``lib/Tooling/Refactoring`` directory.

Will there be functionality like `add-new-check.py` in clang-tidy? Maybe we 
could work on this to ease getting started.


Repository:
  rL LLVM

https://reviews.llvm.org/D39027



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


[PATCH] D39057: [clangd][WIP] Integrate the refactoring actions into clangd

2017-10-18 Thread Alex Lorenz via Phabricator via cfe-commits
arphaman added a comment.

I think that the clangd editor plugin will have to be modified as well, but I 
haven't looked into that yet.


Repository:
  rL LLVM

https://reviews.llvm.org/D39057



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


[PATCH] D39057: [clangd][WIP] Integrate the refactoring actions into clangd

2017-10-18 Thread Alex Lorenz via Phabricator via cfe-commits
arphaman created this revision.
arphaman added a project: clang-tools-extra.
Herald added a subscriber: mgorny.

This WIP patch provides a sample implementation of an integration of Clang's 
refactoring actions from libToolingRefactor into clangd.

In terms of protocol support, the patch adds:

- Support for the `Command` & `CommandArgument` structures.
- Support for the `workspace/executeCommand` command.

Note that the rename is not supported as an editor command since LSP has 
another entry in the protocol for it.

The integration with the refactoring library is done through the 
`RefactoringEditorClient` class that's implemented in a parent revision. Right 
now the test checks that the initial version of the "extract function" 
refactoring can be performed.


Repository:
  rL LLVM

https://reviews.llvm.org/D39057

Files:
  clangd/CMakeLists.txt
  clangd/ClangdLSPServer.cpp
  clangd/ClangdLSPServer.h
  clangd/ClangdServer.cpp
  clangd/ClangdServer.h
  clangd/ClangdUnit.cpp
  clangd/ClangdUnit.h
  clangd/Protocol.cpp
  clangd/Protocol.h
  clangd/ProtocolHandlers.cpp
  clangd/ProtocolHandlers.h
  test/clangd/refactoring.test

Index: test/clangd/refactoring.test
===
--- /dev/null
+++ test/clangd/refactoring.test
@@ -0,0 +1,28 @@
+# RUN: clangd -run-synchronously < %s | FileCheck %s
+# It is absolutely vital that this file has CRLF line endings.
+#
+Content-Length: 125
+
+{"jsonrpc":"2.0","id":0,"method":"initialize","params":{"processId":123,"rootPath":"clangd","capabilities":{},"trace":"off"}}
+#
+Content-Length: 181
+
+{"jsonrpc":"2.0","method":"textDocument/didOpen","params":{"textDocument":{"uri":"file:///foo.c","languageId":"c","version":1,"text":"int main(int i, char **a) { if (i == 2) {}}"}}}
+#
+# CHECK: {"jsonrpc":"2.0","method":"textDocument/publishDiagnostics","params":{"uri":"file:///foo.c","diagnostics":[]}}
+#
+Content-Length: 214
+
+{"jsonrpc":"2.0","id":2,"method":"textDocument/codeAction","params":{"textDocument":{"uri":"file:///foo.c"},"range":{"start":{"line":0,"character":32},"end":{"line":0,"character":38}},"context":{"diagnostics":[]}}}
+#
+# CHECK: {"jsonrpc":"2.0","id":2,"result":[{"title":"Extract Function", "command": "clangd.refactor.ExtractFunction", "arguments": [{"doc":{"uri":"file:///foo.c"}},{"selection":{"start": {"line": 0, "character": 32}, "end": {"line": 0, "character": 38}}}, ]}]}
+#
+Content-Length: 243
+
+{"jsonrpc":"2.0","id":2,"method":"workspace/executeCommand","params":{"command":"clangd.refactor.ExtractFunction","arguments": [{"doc":{"uri":"file:///foo.c"}}, {"range":{"start":{"line":0,"character":32},"end":{"line":0,"character":38}}}]}}
+#
+# CHECK: {"jsonrpc":"2.0","id":2,"result":[{"range": {"start": {"line": 0, "character": 0}, "end": {"line": 0, "character": 0}}, "newText": "static int extracted() {\nreturn i == 2;\n}\n\n"},{"range": {"start": {"line": 0, "character": 32}, "end": {"line": 0, "character": 38}}, "newText": "extracted()"}]}
+#
+Content-Length: 44
+
+{"jsonrpc":"2.0","id":3,"method":"shutdown"}
Index: clangd/ProtocolHandlers.h
===
--- clangd/ProtocolHandlers.h
+++ clangd/ProtocolHandlers.h
@@ -51,6 +51,8 @@
   virtual void onGoToDefinition(Ctx C, TextDocumentPositionParams &Params) = 0;
   virtual void onSwitchSourceHeader(Ctx C, TextDocumentIdentifier &Params) = 0;
   virtual void onFileEvent(Ctx C, DidChangeWatchedFilesParams &Params) = 0;
+  virtual void onWorkspaceExecuteCommand(Ctx C,
+ ExecuteCommandParams &Params) = 0;
 };
 
 void registerCallbackHandlers(JSONRPCDispatcher &Dispatcher, JSONOutput &Out,
Index: clangd/ProtocolHandlers.cpp
===
--- clangd/ProtocolHandlers.cpp
+++ clangd/ProtocolHandlers.cpp
@@ -67,4 +67,6 @@
   Register("textDocument/switchSourceHeader",
&ProtocolCallbacks::onSwitchSourceHeader);
   Register("workspace/didChangeWatchedFiles", &ProtocolCallbacks::onFileEvent);
+  Register("workspace/executeCommand",
+   &ProtocolCallbacks::onWorkspaceExecuteCommand);
 }
Index: clangd/Protocol.h
===
--- clangd/Protocol.h
+++ clangd/Protocol.h
@@ -530,6 +530,72 @@
   static std::string unparse(const SignatureHelp &);
 };
 
+/// Represents an editor command argument.
+struct CommandArgument {
+  union {
+llvm::AlignedCharArrayUnion SelectionRange;
+llvm::AlignedCharArrayUnion DocumentID;
+  };
+  enum Kind { SelectionRangeKind, TextDocumentIdentifierKind };
+  Kind ArgumentKind;
+
+  CommandArgument() {}
+
+  static CommandArgument makeSelectionRange(Range R) {
+CommandArgument Result;
+*reinterpret_cast(Result.SelectionRange.buffer) = R;
+Result.ArgumentKind = SelectionRangeKind;
+return Result;
+  }
+
+  const Range &getSelectionRange() const {
+assert(ArgumentKind == SelectionRangeKind);

[PATCH] D39055: [refactor] Add an editor client that is used in clangd

2017-10-18 Thread Alex Lorenz via Phabricator via cfe-commits
arphaman created this revision.
Herald added subscribers: mgorny, klimek.

This patch adds an editor client that can do things like:

- find a list of available refactoring editor commands in a particular range.
- perform a particular refactoring editor command in a particular range.

This editor client is used in clangd's support for refactoring commands (See 
dependent revision).

(I've ran out of time to add a unit test before devmeeting, so for now this is 
tested in clangd, but I'll add a unit test when I update the patch)


Repository:
  rL LLVM

https://reviews.llvm.org/D39055

Files:
  include/clang/Tooling/Refactoring/EditorClient.h
  include/clang/Tooling/Refactoring/RefactoringActionRule.h
  include/clang/Tooling/Refactoring/RefactoringActionRules.h
  include/clang/Tooling/Refactoring/RefactoringActionRulesInternal.h
  lib/Tooling/Refactoring/CMakeLists.txt
  lib/Tooling/Refactoring/EditorClient.cpp
  lib/Tooling/Refactoring/EditorCommand.cpp

Index: lib/Tooling/Refactoring/EditorCommand.cpp
===
--- lib/Tooling/Refactoring/EditorCommand.cpp
+++ lib/Tooling/Refactoring/EditorCommand.cpp
@@ -28,8 +28,9 @@
   : Rule(std::move(Rule)), Command(Command) {}
 
   void invoke(RefactoringResultConsumer &Consumer,
-  RefactoringRuleContext &Context) override {
-Rule->invoke(Consumer, Context);
+  RefactoringRuleContext &Context,
+  RefactoringStage StopAfter) override {
+Rule->invoke(Consumer, Context, StopAfter);
   }
 
   bool hasSelectionRequirement() override {
Index: lib/Tooling/Refactoring/EditorClient.cpp
===
--- /dev/null
+++ lib/Tooling/Refactoring/EditorClient.cpp
@@ -0,0 +1,117 @@
+//===--- EditorClient.cpp - refactoring editor client -===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===--===//
+
+#include "clang/Tooling/Refactoring/EditorClient.h"
+#include "clang/AST/ASTContext.h"
+#include "clang/Tooling/Refactoring/EditorCommands.h"
+#include "clang/Tooling/Refactoring/RefactoringAction.h"
+#include "clang/Tooling/Refactoring/RefactoringActionRule.h"
+#include "llvm/ADT/STLExtras.h"
+
+namespace clang {
+namespace tooling {
+
+RefactoringEditorClient::Refactoring::~Refactoring() {}
+
+RefactoringEditorClient::RefactoringEditorClient() {
+  std::vector> Actions =
+  createRefactoringActions();
+
+  // Create subcommands and command-line options.
+  for (auto &Action : Actions) {
+RefactoringActionRules Rules = Action->createActiveActionRules();
+// Filter out refactoring rules without an source selection requirement and
+// without an editor command.
+Rules.resize(
+llvm::remove_if(Rules,
+[](const std::unique_ptr &Rule) {
+  return !Rule->hasSelectionRequirement() ||
+ !Rule->getEditorCommand();
+}) -
+Rules.begin());
+// FIXME (Alex L): Filter out rules with required options that can't be
+// fulfilled by editor clients (Also potentially simplify when selection
+// gets treated just like another option).
+if (Rules.empty())
+  continue;
+for (const auto &Rule : Rules)
+  EditorCommandsToRule.insert(
+  std::make_pair(Rule->getEditorCommand()->getName(), Rule.get()));
+RefactoringActions.push_back({std::move(Action), std::move(Rules)});
+  }
+}
+
+std::vector
+RefactoringEditorClient::getAvailableRefactorings(ASTContext &Context,
+  SourceRange SelectionRange) {
+  std::vector Commands;
+  RefactoringRuleContext RuleContext(Context.getSourceManager());
+  RuleContext.setSelectionRange(SelectionRange);
+  RuleContext.setASTContext(Context);
+
+  class ErrorChecker final : public RefactoringResultConsumer {
+  public:
+bool InitiationSucceeded = true;
+
+void handleError(llvm::Error Err) override {
+  llvm::consumeError(std::move(Err));
+  InitiationSucceeded = false;
+}
+  };
+
+  // Figure out which refactorings are available by running the initiation
+  // stage only.
+  for (const auto &Action : RefactoringActions) {
+for (const auto &Rule : Action.ActionRules) {
+  ErrorChecker Consumer;
+  Rule->invoke(Consumer, RuleContext,
+   /*StopAfter=*/RefactoringStage::Initiation);
+  if (Consumer.InitiationSucceeded)
+Commands.push_back(Rule->getEditorCommand());
+}
+  }
+  return Commands;
+}
+
+Expected RefactoringEditorClient::performRefactoring(
+ASTContext &Context, StringRef CommandName, SourceRange SelectionRange) {
+  auto It = EditorCommandsToRule.find(CommandName);
+  if (It == EditorCommandsTo

[PATCH] D39053: [Bitfield] Add more cases to making the bitfield a separate location

2017-10-18 Thread Strahinja Petrovic via Phabricator via cfe-commits
spetrovic created this revision.
Herald added subscribers: arichardson, sdardis.

This patch provides that bitfields are splitted even in case when current field 
is not legal integer type. For Example,

struct S3 {

  unsigned long a1:28;
  unsigned long a2:4;
  unsigned long a3:12;

};

struct S4 {

  unsigned long long b1:61;
  unsigned long b2:3;
  unsigned long b3:3;

};

At the moment, S3 is i48 type, and S4 is i72 type, with this change S3 is 
treated as i32 + 16, and S4 is treated as i32 + i32 + i8.
With this patch we avoid unaligned loads and stores, at least on MIPS 
architecture.


https://reviews.llvm.org/D39053

Files:
  lib/CodeGen/CGRecordLayoutBuilder.cpp
  test/CodeGenCXX/finegrain-bitfield-type.cpp


Index: test/CodeGenCXX/finegrain-bitfield-type.cpp
===
--- test/CodeGenCXX/finegrain-bitfield-type.cpp
+++ test/CodeGenCXX/finegrain-bitfield-type.cpp
@@ -0,0 +1,23 @@
+// RUN: %clang_cc1 -triple x86_64-linux-gnu -ffine-grained-bitfield-accesses \
+// RUN:   -emit-llvm -o - %s | FileCheck %s
+struct S4 {
+  unsigned long f1:28;
+  unsigned long f2:4;
+  unsigned long f3:12;
+};
+struct S4 a4;
+
+struct S5 {
+  unsigned long f1:28;
+  unsigned long f2:4;
+  unsigned long f3:28;
+  unsigned long f4:4;
+  unsigned long f5:12;
+};
+struct S5 a5;
+
+
+// CHECK: %struct.S4 = type { i32, i16 }
+// CHECK-NOT: %struct.S4 = type { i48 }
+// CHECK: %struct.S5 = type { i32, i32, i16, [6 x i8] }
+// CHECK-NOT: %struct.S5 = type { i80 }
\ No newline at end of file
Index: lib/CodeGen/CGRecordLayoutBuilder.cpp
===
--- lib/CodeGen/CGRecordLayoutBuilder.cpp
+++ lib/CodeGen/CGRecordLayoutBuilder.cpp
@@ -408,15 +408,15 @@
   // has legal integer width, and its bitfield offset is naturally aligned, it
   // is better to make the bitfield a separate storage component so as it can 
be
   // accessed directly with lower cost.
-  auto IsBetterAsSingleFieldRun = [&](RecordDecl::field_iterator Field) {
+  auto IsBetterAsSingleFieldRun = [&](uint64_t OffsetInRecord,
+  uint64_t StartBitOffset) {
 if (!Types.getCodeGenOpts().FineGrainedBitfieldAccesses)
   return false;
-unsigned Width = Field->getBitWidthValue(Context);
-if (!DataLayout.isLegalInteger(Width))
+if (!DataLayout.isLegalInteger(OffsetInRecord))
   return false;
 // Make sure Field is natually aligned if it is treated as an IType 
integer.
-if (getFieldBitOffset(*Field) %
-Context.toBits(getAlignment(getIntNType(Width))) !=
+if (StartBitOffset %
+Context.toBits(getAlignment(getIntNType(OffsetInRecord))) !=
 0)
   return false;
 return true;
@@ -435,7 +435,8 @@
 Run = Field;
 StartBitOffset = getFieldBitOffset(*Field);
 Tail = StartBitOffset + Field->getBitWidthValue(Context);
-StartFieldAsSingleRun = IsBetterAsSingleFieldRun(Run);
+StartFieldAsSingleRun = IsBetterAsSingleFieldRun(Tail - StartBitOffset,
+ StartBitOffset);
   }
   ++Field;
   continue;
@@ -449,7 +450,7 @@
 // skip the block below and go ahead to emit the storage.
 // Otherwise, try to add bitfields to the run.
 if (!StartFieldAsSingleRun && Field != FieldEnd &&
-!IsBetterAsSingleFieldRun(Field) &&
+!IsBetterAsSingleFieldRun(Tail - StartBitOffset, StartBitOffset) &&
 Field->getBitWidthValue(Context) != 0 &&
 Tail == getFieldBitOffset(*Field)) {
   Tail += Field->getBitWidthValue(Context);


Index: test/CodeGenCXX/finegrain-bitfield-type.cpp
===
--- test/CodeGenCXX/finegrain-bitfield-type.cpp
+++ test/CodeGenCXX/finegrain-bitfield-type.cpp
@@ -0,0 +1,23 @@
+// RUN: %clang_cc1 -triple x86_64-linux-gnu -ffine-grained-bitfield-accesses \
+// RUN:   -emit-llvm -o - %s | FileCheck %s
+struct S4 {
+  unsigned long f1:28;
+  unsigned long f2:4;
+  unsigned long f3:12;
+};
+struct S4 a4;
+
+struct S5 {
+  unsigned long f1:28;
+  unsigned long f2:4;
+  unsigned long f3:28;
+  unsigned long f4:4;
+  unsigned long f5:12;
+};
+struct S5 a5;
+
+
+// CHECK: %struct.S4 = type { i32, i16 }
+// CHECK-NOT: %struct.S4 = type { i48 }
+// CHECK: %struct.S5 = type { i32, i32, i16, [6 x i8] }
+// CHECK-NOT: %struct.S5 = type { i80 }
\ No newline at end of file
Index: lib/CodeGen/CGRecordLayoutBuilder.cpp
===
--- lib/CodeGen/CGRecordLayoutBuilder.cpp
+++ lib/CodeGen/CGRecordLayoutBuilder.cpp
@@ -408,15 +408,15 @@
   // has legal integer width, and its bitfield offset is naturally aligned, it
   // is better to make the bitfield a separate storage component so as it can be
   // accessed directly with lower cost.
-  auto IsBetterAsSingleFieldRun = [&](RecordDecl::field_iterator Field) {
+  auto IsBetterAsS

[PATCH] D39050: Add index-while-building support to Clang

2017-10-18 Thread Alex Lorenz via Phabricator via cfe-commits
arphaman added a comment.

I think this patch should be split into a number of smaller patches to help the 
review process.

Things like `tools/IndexStore`, `DirectoryWatcher` and other components that 
are not directly needed right now should definitely be in their own patches.
It would be nice to find some way to split the implementation into multiple 
patches as well.


https://reviews.llvm.org/D39050



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


[PATCH] D38688: [clang-tidy] Misc redundant expressions checker updated for macros

2017-10-18 Thread Barancsuk Lilla via Phabricator via cfe-commits
barancsuk added inline comments.



Comment at: clang-tidy/misc/RedundantExpressionCheck.cpp:510
+// E.g.: from (X == 5) && (X == 5) retrieves 5 and 5
+static void retrieveConstExprFromBothSides(const BinaryOperator *&BinOp,
+   BinaryOperatorKind &MainOpcode,

xazax.hun wrote:
> I would prefer to return a pair of pointer to be returned to output 
> parameters. 
I think, since 'Retrieve'  functions have multiple output parameters, they 
should remain unchanged. 

'Retrieve' methods are responsible for splitting expressions into parts (e.g.: 
into opcode and constant integer value) and storing each part into the 
corresponding output parameter. Therefore it is more reasonable to return 
whether the operation was successful than returning one of these parameters.



Comment at: test/clang-tidy/misc-redundant-expression.cpp:387
   // Should not match.
-  if (X == 10 && Y == 10) return 1;
-  if (X != 10 && X != 12) return 1;

xazax.hun wrote:
> Why did you remove these test cases?
The above test cases were not removed, just moved into the function 
`TestLogical`, as they contain only equality operators, and no relational 
operators.


https://reviews.llvm.org/D38688



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


[PATCH] D38688: [clang-tidy] Misc redundant expressions checker updated for macros

2017-10-18 Thread Barancsuk Lilla via Phabricator via cfe-commits
barancsuk updated this revision to Diff 119452.
barancsuk marked 8 inline comments as done.
barancsuk added a comment.
Herald added a subscriber: whisperity.

Address review comments.


https://reviews.llvm.org/D38688

Files:
  clang-tidy/misc/RedundantExpressionCheck.cpp
  clang-tidy/misc/RedundantExpressionCheck.h
  docs/clang-tidy/checks/misc-redundant-expression.rst
  test/clang-tidy/misc-redundant-expression.cpp

Index: test/clang-tidy/misc-redundant-expression.cpp
===
--- test/clang-tidy/misc-redundant-expression.cpp
+++ test/clang-tidy/misc-redundant-expression.cpp
@@ -15,69 +15,71 @@
 extern int bar(int x);
 extern int bat(int x, int y);
 
-int Test(int X, int Y) {
+int TestSimpleEquivalent(int X, int Y) {
   if (X - X) return 1;
-  // CHECK-MESSAGES: :[[@LINE-1]]:9: warning: both side of operator are equivalent [misc-redundant-expression]
+  // CHECK-MESSAGES: :[[@LINE-1]]:9: warning: both sides of operator are equivalent [misc-redundant-expression]
   if (X / X) return 1;
-  // CHECK-MESSAGES: :[[@LINE-1]]:9: warning: both side of operator are equivalent
+  // CHECK-MESSAGES: :[[@LINE-1]]:9: warning: both sides of operator are equivalent
   if (X % X) return 1;
-  // CHECK-MESSAGES: :[[@LINE-1]]:9: warning: both side of operator are equivalent
+  // CHECK-MESSAGES: :[[@LINE-1]]:9: warning: both sides of operator are equivalent
 
   if (X & X) return 1;
-  // CHECK-MESSAGES: :[[@LINE-1]]:9: warning: both side of operator are equivalent
+  // CHECK-MESSAGES: :[[@LINE-1]]:9: warning: both sides of operator are equivalent
   if (X | X) return 1;
-  // CHECK-MESSAGES: :[[@LINE-1]]:9: warning: both side of operator are equivalent
+  // CHECK-MESSAGES: :[[@LINE-1]]:9: warning: both sides of operator are equivalent
   if (X ^ X) return 1;
-  // CHECK-MESSAGES: :[[@LINE-1]]:9: warning: both side of operator are equivalent
+  // CHECK-MESSAGES: :[[@LINE-1]]:9: warning: both sides of operator are equivalent
 
   if (X < X) return 1;
-  // CHECK-MESSAGES: :[[@LINE-1]]:9: warning: both side of operator are equivalent
+  // CHECK-MESSAGES: :[[@LINE-1]]:9: warning: both sides of operator are equivalent
   if (X <= X) return 1;
-  // CHECK-MESSAGES: :[[@LINE-1]]:9: warning: both side of operator are equivalent
+  // CHECK-MESSAGES: :[[@LINE-1]]:9: warning: both sides of operator are equivalent
   if (X > X) return 1;
-  // CHECK-MESSAGES: :[[@LINE-1]]:9: warning: both side of operator are equivalent
+  // CHECK-MESSAGES: :[[@LINE-1]]:9: warning: both sides of operator are equivalent
   if (X >= X) return 1;
-  // CHECK-MESSAGES: :[[@LINE-1]]:9: warning: both side of operator are equivalent
+  // CHECK-MESSAGES: :[[@LINE-1]]:9: warning: both sides of operator are equivalent
 
   if (X && X) return 1;
-  // CHECK-MESSAGES: :[[@LINE-1]]:9: warning: both side of operator are equivalent
+  // CHECK-MESSAGES: :[[@LINE-1]]:9: warning: both sides of operator are equivalent
   if (X || X) return 1;
-  // CHECK-MESSAGES: :[[@LINE-1]]:9: warning: both side of operator are equivalent
+  // CHECK-MESSAGES: :[[@LINE-1]]:9: warning: both sides of operator are equivalent
 
   if (X != (((X return 1;
-  // CHECK-MESSAGES: :[[@LINE-1]]:9: warning: both side of operator are equivalent
+  // CHECK-MESSAGES: :[[@LINE-1]]:9: warning: both sides of operator are equivalent
 
   if (X + 1 == X + 1) return 1;
-  // CHECK-MESSAGES: :[[@LINE-1]]:13: warning: both side of operator are equivalent
+  // CHECK-MESSAGES: :[[@LINE-1]]:13: warning: both sides of operator are equivalent
   if (X + 1 != X + 1) return 1;
-  // CHECK-MESSAGES: :[[@LINE-1]]:13: warning: both side of operator are equivalent
+  // CHECK-MESSAGES: :[[@LINE-1]]:13: warning: both sides of operator are equivalent
   if (X + 1 <= X + 1) return 1;
-  // CHECK-MESSAGES: :[[@LINE-1]]:13: warning: both side of operator are equivalent
+  // CHECK-MESSAGES: :[[@LINE-1]]:13: warning: both sides of operator are equivalent
   if (X + 1 >= X + 1) return 1;
-  // CHECK-MESSAGES: :[[@LINE-1]]:13: warning: both side of operator are equivalent
+  // CHECK-MESSAGES: :[[@LINE-1]]:13: warning: both sides of operator are equivalent
 
   if ((X != 1 || Y != 1) && (X != 1 || Y != 1)) return 1;
-  // CHECK-MESSAGES: :[[@LINE-1]]:26: warning: both side of operator are equivalent
+  // CHECK-MESSAGES: :[[@LINE-1]]:26: warning: both sides of operator are equivalent
   if (P.a[X - P.x] != P.a[X - P.x]) return 1;
-  // CHECK-MESSAGES: :[[@LINE-1]]:20: warning: both side of operator are equivalent
+  // CHECK-MESSAGES: :[[@LINE-1]]:20: warning: both sides of operator are equivalent
 
   if ((int)X < (int)X) return 1;
-  // CHECK-MESSAGES: :[[@LINE-1]]:14: warning: both side of operator are equivalent
+  // CHECK-MESSAGES: :[[@LINE-1]]:14: warning: both sides of operator are equivalent
+  if (int(X) < int(X)) return 1;
+  // CHECK-MESSAGES: :[[@LINE-1]]:14: warning: both sides of operator are equivalent
 
   if ( + "dummy" == + "dummy"

[PATCH] D39027: [docs][refactor] Add a new tutorial that talks about how one can implement refactoring actions

2017-10-18 Thread Haojian Wu via Phabricator via cfe-commits
hokein added a comment.

Awesome, thanks for the very well-illustrated tutorial!




Comment at: docs/RefactoringActionTutorial.rst:7
+
+  This tutorial talks about a work-in-progress library in Clang.
+  Some of the described features might not be available yet in trunk, but 
should

I'm a bit concerned about this. If we check in this doc before all features are 
implemented, it probably confuses users.




Comment at: docs/RefactoringActionTutorial.rst:36
+selected ``if`` statement that's nested in another ``if`` and merge the two
+into ``if``s one just one ``if``. For example, the following code:
+

merge the two `if`s into just one `if`?



Comment at: docs/RefactoringActionTutorial.rst:96
+
+.. code-block:: c++
+

It might be more sensible to provide a repository holding  all source code of 
the sample, so that users can easily build and play around it.



Comment at: docs/RefactoringActionTutorial.rst:122
+operation. The refactoring library supports a number of different kinds of
+refactoring operations, which are describes in the
+:doc:`rule types `_ section of the

s/describes/described



Comment at: docs/RefactoringActionTutorial.rst:167
+Change.insert(Context.getSources(), ParentCond->getLocEnd(),
+  (llvm::Twine(" && ") + NestedCondStr).str());
+

An  out-of-scope comment: the new code after refactoring may not be equivalent 
to the original one because of operator precedence. 



Comment at: docs/RefactoringEngine.rst:21
 
-..  FIXME: create new refactoring action tutorial and link to the tutorial
+You can also take a look a the
+:doc:`refactoring action tutorial ` to see how

s/a/at


Repository:
  rL LLVM

https://reviews.llvm.org/D39027



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


[PATCH] D39049: [analyzer] Fix wrong calculation of offset in ArrayBoundsV2

2017-10-18 Thread Daniel Marjamäki via Phabricator via cfe-commits
danielmarjamaki created this revision.
Herald added a subscriber: szepet.

Example code:

  void test3_simplified_offset(int x, unsigned long long y) {
int buf[100];
if (x < 0)
  x = 0;
for (int i = y - x; i > 0 && i < 100; i++)
  buf[i] = 0; // no-warning
  }

Without this patch Clang will wrongly report this FP:

  File out-of-bounds.c Line 144: Out of bound memory access (accessed memory 
precedes memory block)

There is some bug in the getSimplifiedOffsets() calculations. I removed the 
wrong calculations and this does not break any existing tests so either no 
tests were written in the first place or these calculations got redundant 
sometime. If somebody wants to readd the calculations that I remove.. I am not 
against that if some tests are added and it does not break my test.


Repository:
  rL LLVM

https://reviews.llvm.org/D39049

Files:
  lib/StaticAnalyzer/Checkers/ArrayBoundCheckerV2.cpp
  test/Analysis/out-of-bounds.c


Index: test/Analysis/out-of-bounds.c
===
--- test/Analysis/out-of-bounds.c
+++ test/Analysis/out-of-bounds.c
@@ -136,6 +136,14 @@
 buf[x] = 1; // expected-warning{{Out of bound memory access}}
 }
 
+void test3_simplified_offset(int x, unsigned long long y) {
+  int buf[100];
+  if (x < 0)
+x = 0;
+  for (int i = y - x; i > 0 && i < 100; i++)
+buf[i] = 0; // no-warning
+}
+
 void test4(int x) {
   int buf[100];
   if (x > 99)
Index: lib/StaticAnalyzer/Checkers/ArrayBoundCheckerV2.cpp
===
--- lib/StaticAnalyzer/Checkers/ArrayBoundCheckerV2.cpp
+++ lib/StaticAnalyzer/Checkers/ArrayBoundCheckerV2.cpp
@@ -98,10 +98,6 @@
   nonloc::SymbolVal(SIE->getLHS()),
   svalBuilder.makeIntVal(extent.getValue() / constant),
   svalBuilder);
-  case BO_Add:
-return getSimplifiedOffsets(
-nonloc::SymbolVal(SIE->getLHS()),
-svalBuilder.makeIntVal(extent.getValue() - constant), svalBuilder);
   default:
 break;
   }


Index: test/Analysis/out-of-bounds.c
===
--- test/Analysis/out-of-bounds.c
+++ test/Analysis/out-of-bounds.c
@@ -136,6 +136,14 @@
 buf[x] = 1; // expected-warning{{Out of bound memory access}}
 }
 
+void test3_simplified_offset(int x, unsigned long long y) {
+  int buf[100];
+  if (x < 0)
+x = 0;
+  for (int i = y - x; i > 0 && i < 100; i++)
+buf[i] = 0; // no-warning
+}
+
 void test4(int x) {
   int buf[100];
   if (x > 99)
Index: lib/StaticAnalyzer/Checkers/ArrayBoundCheckerV2.cpp
===
--- lib/StaticAnalyzer/Checkers/ArrayBoundCheckerV2.cpp
+++ lib/StaticAnalyzer/Checkers/ArrayBoundCheckerV2.cpp
@@ -98,10 +98,6 @@
   nonloc::SymbolVal(SIE->getLHS()),
   svalBuilder.makeIntVal(extent.getValue() / constant),
   svalBuilder);
-  case BO_Add:
-return getSimplifiedOffsets(
-nonloc::SymbolVal(SIE->getLHS()),
-svalBuilder.makeIntVal(extent.getValue() - constant), svalBuilder);
   default:
 break;
   }
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D38982: [refactor] Initial outline of implementation of "extract function" refactoring

2017-10-18 Thread Eric Liu via Phabricator via cfe-commits
ioeric added a comment.

Code looks good in general. I see there are a bunch of major features missing; 
it might make sense to print a warning or document the major missing features 
in the high-level API.




Comment at: 
include/clang/Tooling/Refactoring/RefactoringActionRuleRequirements.h:74
+/// \see CodeRangeASTSelection
+class CodeRangeSelectionRequirement : public ASTSelectionRequirement {
+public:

Could we find a better name for this? It's not clear what the difference 
between this and `SourceRangeSelectionRequirement` is from the names.



Comment at: include/clang/Tooling/Refactoring/RefactoringRuleContext.h:84
+  // FIXME: Remove when memoized.
+  std::unique_ptr ASTSelection;
 };

Maybe `ASTNodeSelection` for clarity?



Comment at: lib/Tooling/Refactoring/ASTSelection.cpp:340
+  bool IsPrevCompound = false;
+  for (const auto &Parent : llvm::reverse(Parents)) {
+const DynTypedNode &Node = Parent.get().Node;

A short explanation of the for-loop would be appreciated :)



Comment at: lib/Tooling/Refactoring/Extract.cpp:167
+  OS << "return ";
+OS << ExtractedCodeRewriter.getRewrittenText(ExtractedRange);
+// FIXME: Compute the correct semicolon policy.

An alternative way to get the source code is:
``` 
Lexer::getSourceText(
  CharSourceRange::getTokenRange(SM.getSpellingLoc(Start), 
SM.getSpellingLoc(End)),
  SM, Result.Context->getLangOpts());
```



Comment at: tools/clang-refactor/TestSupport.cpp:106
+auto Buf = llvm::MemoryBuffer::getMemBuffer(Result->c_str());
+for (llvm::line_iterator It(*Buf, /*SkipBlanks=*/false); !It.is_at_end();
+ ++It) {

Can we filter the `CHECK`s with `sed` in the test? Similar to 
https://github.com/llvm-mirror/clang-tools-extra/blob/master/test/change-namespace/simple-move.cpp#L1


Repository:
  rL LLVM

https://reviews.llvm.org/D38982



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


[PATCH] D39048: Dump signed integers in SymIntExpr and IntSymExpr correctly

2017-10-18 Thread Gábor Horváth via Phabricator via cfe-commits
xazax.hun accepted this revision.
xazax.hun added a comment.
This revision is now accepted and ready to land.

LGTM!


https://reviews.llvm.org/D39048



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


[PATCH] D39042: [Tooling] Add a factory method for CommonOptionsParser

2017-10-18 Thread Haojian Wu via Phabricator via cfe-commits
hokein accepted this revision.
hokein added a comment.
This revision is now accepted and ready to land.

Looks good from my side. You might want @klimek to take a look before 
committing.




Comment at: include/clang/Tooling/CommonOptionsParser.h:90
-  ///
-  /// This constructor exits program in case of error.
   CommonOptionsParser(int &argc, const char **argv,

This change is unintended?



Comment at: include/clang/Tooling/CommonOptionsParser.h:118
+  llvm::Error init(int &argc, const char **argv,
+  llvm::cl::OptionCategory &Category,
+  llvm::cl::NumOccurrencesFlag OccurrencesFlag,

nit: the code indention seems wrong after updated.



Comment at: lib/Tooling/CommonOptionsParser.cpp:165
+const char *Overview) {
+  std::unique_ptr Parser(new CommonOptionsParser);
+  llvm::Error Err =

ioeric wrote:
> hokein wrote:
> > nit: using llvm::make_unique.
> `make_unique` didn't work because the constructor here is private...
Ah, I see.


https://reviews.llvm.org/D39042



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


[PATCH] D38922: [analyzer] LoopUnrolling: check the bitwidth of the used numbers (pr34943)

2017-10-18 Thread Gábor Horváth via Phabricator via cfe-commits
xazax.hun accepted this revision.
xazax.hun added a comment.
This revision is now accepted and ready to land.

LGTM!


https://reviews.llvm.org/D38922



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


[PATCH] D39048: Dump signed integers in SymIntExpr and IntSymExpr correctly

2017-10-18 Thread Balogh , Ádám via Phabricator via cfe-commits
baloghadamsoftware created this revision.

When dumping SymIntExpr or IntSymExpr signed numbers are dumped as unsigned, 
thus their two's complement is displayed. This small patch fixes this.


https://reviews.llvm.org/D39048

Files:
  lib/StaticAnalyzer/Core/SymbolManager.cpp
  test/Analysis/expr-inspection.c


Index: test/Analysis/expr-inspection.c
===
--- test/Analysis/expr-inspection.c
+++ test/Analysis/expr-inspection.c
@@ -8,6 +8,7 @@
 
 void foo(int x) {
   clang_analyzer_dump(x); // expected-warning{{reg_$0}}
+  clang_analyzer_dump(x + (-1)); // expected-warning{{(reg_$0) + -1}}
   int y = 1;
   clang_analyzer_printState();
   for (; y < 3; ++y)
Index: lib/StaticAnalyzer/Core/SymbolManager.cpp
===
--- lib/StaticAnalyzer/Core/SymbolManager.cpp
+++ lib/StaticAnalyzer/Core/SymbolManager.cpp
@@ -31,14 +31,20 @@
   os << '(';
   getLHS()->dumpToStream(os);
   os << ") "
- << BinaryOperator::getOpcodeStr(getOpcode()) << ' '
- << getRHS().getZExtValue();
+ << BinaryOperator::getOpcodeStr(getOpcode()) << ' ';
+  if (getRHS().isUnsigned())
+os << getRHS().getZExtValue();
+  else
+os << getRHS().getSExtValue();
   if (getRHS().isUnsigned())
 os << 'U';
 }
 
 void IntSymExpr::dumpToStream(raw_ostream &os) const {
-  os << getLHS().getZExtValue();
+  if (getLHS().isUnsigned())
+os << getLHS().getZExtValue();
+  else
+os << getLHS().getSExtValue();
   if (getLHS().isUnsigned())
 os << 'U';
   os << ' '


Index: test/Analysis/expr-inspection.c
===
--- test/Analysis/expr-inspection.c
+++ test/Analysis/expr-inspection.c
@@ -8,6 +8,7 @@
 
 void foo(int x) {
   clang_analyzer_dump(x); // expected-warning{{reg_$0}}
+  clang_analyzer_dump(x + (-1)); // expected-warning{{(reg_$0) + -1}}
   int y = 1;
   clang_analyzer_printState();
   for (; y < 3; ++y)
Index: lib/StaticAnalyzer/Core/SymbolManager.cpp
===
--- lib/StaticAnalyzer/Core/SymbolManager.cpp
+++ lib/StaticAnalyzer/Core/SymbolManager.cpp
@@ -31,14 +31,20 @@
   os << '(';
   getLHS()->dumpToStream(os);
   os << ") "
- << BinaryOperator::getOpcodeStr(getOpcode()) << ' '
- << getRHS().getZExtValue();
+ << BinaryOperator::getOpcodeStr(getOpcode()) << ' ';
+  if (getRHS().isUnsigned())
+os << getRHS().getZExtValue();
+  else
+os << getRHS().getSExtValue();
   if (getRHS().isUnsigned())
 os << 'U';
 }
 
 void IntSymExpr::dumpToStream(raw_ostream &os) const {
-  os << getLHS().getZExtValue();
+  if (getLHS().isUnsigned())
+os << getLHS().getZExtValue();
+  else
+os << getLHS().getSExtValue();
   if (getLHS().isUnsigned())
 os << 'U';
   os << ' '
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D39042: [Tooling] Add a factory method for CommonOptionsParser

2017-10-18 Thread Eric Liu via Phabricator via cfe-commits
ioeric updated this revision to Diff 119465.
ioeric marked 2 inline comments as done.
ioeric added a comment.

- Address review comments.


https://reviews.llvm.org/D39042

Files:
  include/clang/Tooling/CommonOptionsParser.h
  lib/Tooling/CommonOptionsParser.cpp

Index: lib/Tooling/CommonOptionsParser.cpp
===
--- lib/Tooling/CommonOptionsParser.cpp
+++ lib/Tooling/CommonOptionsParser.cpp
@@ -24,9 +24,9 @@
 //
 //===--===//
 
-#include "llvm/Support/CommandLine.h"
 #include "clang/Tooling/CommonOptionsParser.h"
 #include "clang/Tooling/Tooling.h"
+#include "llvm/Support/CommandLine.h"
 
 using namespace clang::tooling;
 using namespace llvm;
@@ -81,7 +81,7 @@
   return Commands;
 }
 
-CommonOptionsParser::CommonOptionsParser(
+llvm::Error CommonOptionsParser::init(
 int &argc, const char **argv, cl::OptionCategory &Category,
 llvm::cl::NumOccurrencesFlag OccurrencesFlag, const char *Overview) {
   static cl::opt Help("h", cl::desc("Alias for -help"), cl::Hidden,
@@ -105,20 +105,30 @@
   cl::desc("Additional argument to prepend to the compiler command line"),
   cl::cat(Category), cl::sub(*cl::AllSubCommands));
 
+  cl::ResetAllOptionOccurrences();
+
   cl::HideUnrelatedOptions(Category);
 
   std::string ErrorMessage;
   Compilations =
   FixedCompilationDatabase::loadFromCommandLine(argc, argv, ErrorMessage);
-  if (!Compilations && !ErrorMessage.empty())
-llvm::errs() << ErrorMessage;
-  cl::ParseCommandLineOptions(argc, argv, Overview);
+  if (!ErrorMessage.empty())
+ErrorMessage.append("\n");
+  llvm::raw_string_ostream OS(ErrorMessage);
+  // Stop initializing if command-line option parsing failed.
+  if (!cl::ParseCommandLineOptions(argc, argv, Overview, &OS)) {
+OS.flush();
+return llvm::make_error("[CommonOptionsParser]: " +
+   ErrorMessage,
+   llvm::inconvertibleErrorCode());
+  }
+
   cl::PrintOptionValues();
 
   SourcePathList = SourcePaths;
   if ((OccurrencesFlag == cl::ZeroOrMore || OccurrencesFlag == cl::Optional) &&
   SourcePathList.empty())
-return;
+return llvm::Error::success();
   if (!Compilations) {
 if (!BuildPath.empty()) {
   Compilations =
@@ -142,4 +152,29 @@
   AdjustingCompilations->appendArgumentsAdjuster(
   getInsertArgumentAdjuster(ArgsAfter, ArgumentInsertPosition::END));
   Compilations = std::move(AdjustingCompilations);
+  return llvm::Error::success();
+}
+
+llvm::Expected>
+CommonOptionsParser::create(int &argc, const char **argv,
+llvm::cl::OptionCategory &Category,
+llvm::cl::NumOccurrencesFlag OccurrencesFlag,
+const char *Overview) {
+  std::unique_ptr Parser(new CommonOptionsParser);
+  llvm::Error Err =
+  Parser->init(argc, argv, Category, OccurrencesFlag, Overview);
+  if (Err)
+return std::move(Err);
+  return Parser;
+}
+
+CommonOptionsParser::CommonOptionsParser(
+int &argc, const char **argv, cl::OptionCategory &Category,
+llvm::cl::NumOccurrencesFlag OccurrencesFlag, const char *Overview) {
+  llvm::Error Err = init(argc, argv, Category, OccurrencesFlag, Overview);
+  if (Err) {
+llvm::report_fatal_error(
+"CommonOptionsParser: failed to parse command-line arguments. " +
+llvm::toString(std::move(Err)));
+  }
 }
Index: include/clang/Tooling/CommonOptionsParser.h
===
--- include/clang/Tooling/CommonOptionsParser.h
+++ include/clang/Tooling/CommonOptionsParser.h
@@ -30,6 +30,7 @@
 #include "clang/Tooling/ArgumentsAdjusters.h"
 #include "clang/Tooling/CompilationDatabase.h"
 #include "llvm/Support/CommandLine.h"
+#include "llvm/Support/Error.h"
 
 namespace clang {
 namespace tooling {
@@ -86,13 +87,18 @@
   /// All options not belonging to \p Category become hidden.
   ///
   /// It also allows calls to set the required number of positional parameters.
-  ///
-  /// This constructor exits program in case of error.
   CommonOptionsParser(int &argc, const char **argv,
   llvm::cl::OptionCategory &Category,
   llvm::cl::NumOccurrencesFlag OccurrencesFlag,
   const char *Overview = nullptr);
 
+  /// \brief A factory method that is similar to the above constructor, except
+  /// this returns an error instead exiting the program on error.
+  static llvm::Expected>
+  create(int &argc, const char **argv, llvm::cl::OptionCategory &Category,
+ llvm::cl::NumOccurrencesFlag OccurrencesFlag,
+ const char *Overview = nullptr);
+
   /// Returns a reference to the loaded compilations database.
   CompilationDatabase &getCompilations() {
 return *Compilations;
@@ -106,6 +112,13 @@
   static const char *const HelpMessage;
 
 privat

[PATCH] D39042: [Tooling] Add a factory method for CommonOptionsParser

2017-10-18 Thread Eric Liu via Phabricator via cfe-commits
ioeric added inline comments.



Comment at: include/clang/Tooling/CommonOptionsParser.h:115
+
+  static llvm::Error init(int &argc, const char **argv,
+  llvm::cl::OptionCategory &Category,

hokein wrote:
> We can get rid of the `static` here by calling `parser->init(XXX)`.
Ha, right! 



Comment at: lib/Tooling/CommonOptionsParser.cpp:165
+const char *Overview) {
+  std::unique_ptr Parser(new CommonOptionsParser);
+  llvm::Error Err =

hokein wrote:
> nit: using llvm::make_unique.
`make_unique` didn't work because the constructor here is private...


https://reviews.llvm.org/D39042



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


Re: r316046 - Basic: fix __{,U}INTPTR_TYPE__ on ARM

2017-10-18 Thread Joerg Sonnenberger via cfe-commits
On Wed, Oct 18, 2017 at 12:00:51AM -, Saleem Abdulrasool via cfe-commits 
wrote:
> Author: compnerd
> Date: Tue Oct 17 17:00:50 2017
> New Revision: 316046
> 
> URL: http://llvm.org/viewvc/llvm-project?rev=316046&view=rev
> Log:
> Basic: fix __{,U}INTPTR_TYPE__ on ARM
> 
> Darwin and OpenBSD are the only platforms which use `long int` for
> `__INTPTR_TYPE__`.  The other platforms use `int` in 32-bit, and `long
> int` on 64-bit (except for VMS and Windows which are LLP64).  Adjust the
> type definitions to match the platform definitions.  We now generate the
> same definition as GCC on all the targets.

This is false as the test changes show.

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


r316075 - Silence -Wimplicit-fallthrough warnings with the generated code; NFC.

2017-10-18 Thread Aaron Ballman via cfe-commits
Author: aaronballman
Date: Wed Oct 18 05:11:58 2017
New Revision: 316075

URL: http://llvm.org/viewvc/llvm-project?rev=316075&view=rev
Log:
Silence -Wimplicit-fallthrough warnings with the generated code; NFC.

Modified:
cfe/trunk/utils/TableGen/ClangAttrEmitter.cpp

Modified: cfe/trunk/utils/TableGen/ClangAttrEmitter.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/utils/TableGen/ClangAttrEmitter.cpp?rev=316075&r1=316074&r2=316075&view=diff
==
--- cfe/trunk/utils/TableGen/ClangAttrEmitter.cpp (original)
+++ cfe/trunk/utils/TableGen/ClangAttrEmitter.cpp Wed Oct 18 05:11:58 2017
@@ -2794,7 +2794,7 @@ void EmitClangAttrHasAttrImpl(RecordKeep
   GenerateHasAttrSpellingStringSwitch(I->second, OS, Spelling, I->first);
   OS << "}";
 }
-OS << "\n}\n";
+OS << "\n} break;\n";
   };
   fn("CXX11", "CXX", CXX);
   fn("C2x", "C", C2x);


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


[PATCH] D39043: [clang-rename] Rename alias.

2017-10-18 Thread Haojian Wu via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rL316074: [clang-rename] Rename alias. (authored by hokein).

Repository:
  rL LLVM

https://reviews.llvm.org/D39043

Files:
  cfe/trunk/lib/Tooling/Refactoring/Rename/USRLocFinder.cpp
  cfe/trunk/unittests/Rename/CMakeLists.txt
  cfe/trunk/unittests/Rename/RenameAliasTest.cpp

Index: cfe/trunk/lib/Tooling/Refactoring/Rename/USRLocFinder.cpp
===
--- cfe/trunk/lib/Tooling/Refactoring/Rename/USRLocFinder.cpp
+++ cfe/trunk/lib/Tooling/Refactoring/Rename/USRLocFinder.cpp
@@ -39,6 +39,17 @@
 
 namespace {
 
+// Returns true if the given Loc is valid for edit. We don't edit the
+// SourceLocations that are valid or in temporary buffer.
+bool IsValidEditLoc(const clang::SourceManager& SM, clang::SourceLocation Loc) {
+  if (Loc.isInvalid())
+return false;
+  const clang::FullSourceLoc FullLoc(Loc, SM);
+  std::pair FileIdAndOffset =
+  FullLoc.getSpellingLoc().getDecomposedLoc();
+  return SM.getFileEntryForID(FileIdAndOffset.first) != nullptr;
+}
+
 // \brief This visitor recursively searches for all instances of a USR in a
 // translation unit and stores them for later usage.
 class USRLocFindingASTVisitor
@@ -181,13 +192,22 @@
   return true;
 
 if (isInUSRSet(Decl)) {
-  RenameInfo Info = {Decl->getLocation(),
- Decl->getLocation(),
- /*FromDecl=*/nullptr,
- /*Context=*/nullptr,
- /*Specifier=*/nullptr,
- /*IgnorePrefixQualifers=*/true};
-  RenameInfos.push_back(Info);
+  // For the case of renaming an alias template, we actually rename the
+  // underlying alias declaration of the template.
+  if (const auto* TAT = dyn_cast(Decl))
+Decl = TAT->getTemplatedDecl();
+
+  auto StartLoc = Decl->getLocation();
+  auto EndLoc = StartLoc;
+  if (IsValidEditLoc(Context.getSourceManager(), StartLoc)) {
+RenameInfo Info = {StartLoc,
+   EndLoc,
+   /*FromDecl=*/nullptr,
+   /*Context=*/nullptr,
+   /*Specifier=*/nullptr,
+   /*IgnorePrefixQualifers=*/true};
+RenameInfos.push_back(Info);
+  }
 }
 return true;
   }
@@ -200,7 +220,7 @@
   Decl = UsingShadow->getTargetDecl();
 }
 
-auto BeginLoc = Expr->getLocStart();
+auto StartLoc = Expr->getLocStart();
 auto EndLoc = Expr->getLocEnd();
 // In case of renaming an enum declaration, we have to explicitly handle
 // unscoped enum constants referenced in expressions (e.g.
@@ -233,8 +253,9 @@
   assert(EndLoc.isValid() &&
  "The enum constant should have prefix qualifers.");
 }
-if (isInUSRSet(Decl)) {
-  RenameInfo Info = {BeginLoc,
+if (isInUSRSet(Decl) &&
+IsValidEditLoc(Context.getSourceManager(), StartLoc)) {
+  RenameInfo Info = {StartLoc,
  EndLoc,
  Decl,
  getClosestAncestorDecl(*Expr),
@@ -259,8 +280,6 @@
   bool VisitNestedNameSpecifierLocations(NestedNameSpecifierLoc NestedLoc) {
 if (!NestedLoc.getNestedNameSpecifier()->getAsType())
   return true;
-if (IsTypeAliasWhichWillBeRenamedElsewhere(NestedLoc.getTypeLoc()))
-  return true;
 
 if (const auto *TargetDecl =
 getSupportedDeclFromTypeLoc(NestedLoc.getTypeLoc())) {
@@ -278,9 +297,6 @@
   }
 
   bool VisitTypeLoc(TypeLoc Loc) {
-if (IsTypeAliasWhichWillBeRenamedElsewhere(Loc))
-  return true;
-
 auto Parents = Context.getParents(Loc);
 TypeLoc ParentTypeLoc;
 if (!Parents.empty()) {
@@ -314,13 +330,18 @@
 if (!ParentTypeLoc.isNull() &&
 isInUSRSet(getSupportedDeclFromTypeLoc(ParentTypeLoc)))
   return true;
-RenameInfo Info = {StartLocationForType(Loc),
-   EndLocationForType(Loc),
-   TargetDecl,
-   getClosestAncestorDecl(Loc),
-   GetNestedNameForType(Loc),
-   /*IgnorePrefixQualifers=*/false};
-RenameInfos.push_back(Info);
+
+auto StartLoc = StartLocationForType(Loc);
+auto EndLoc = EndLocationForType(Loc);
+if (IsValidEditLoc(Context.getSourceManager(), StartLoc)) {
+  RenameInfo Info = {StartLoc,
+ EndLoc,
+ TargetDecl,
+ getClosestAncestorDecl(Loc),
+ GetNestedNameForType(Loc),
+ /*IgnorePrefixQualifers=*/false};
+  RenameInfos.push_back(Info);
+}
 return true;
   }
 }
@@ -344,15 +365,20 @@
 if (!ParentTypeLoc.isNull() &&
 llvm::isa(ParentTypeLoc.getType()))
   

r316074 - [clang-rename] Rename alias.

2017-10-18 Thread Haojian Wu via cfe-commits
Author: hokein
Date: Wed Oct 18 05:10:11 2017
New Revision: 316074

URL: http://llvm.org/viewvc/llvm-project?rev=316074&view=rev
Log:
[clang-rename] Rename alias.

Summary:
* Support rename alias.
* Add unittests for renaming alias.
* Don't generate fixes for the SourceLocations that are invalid or in temporary
  buffer, otherwise crash would be happened when generating AtomicChanges.

Reviewers: ioeric

Reviewed By: ioeric

Subscribers: klimek, mgorny, cfe-commits

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

Added:
cfe/trunk/unittests/Rename/RenameAliasTest.cpp
Modified:
cfe/trunk/lib/Tooling/Refactoring/Rename/USRLocFinder.cpp
cfe/trunk/unittests/Rename/CMakeLists.txt

Modified: cfe/trunk/lib/Tooling/Refactoring/Rename/USRLocFinder.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Tooling/Refactoring/Rename/USRLocFinder.cpp?rev=316074&r1=316073&r2=316074&view=diff
==
--- cfe/trunk/lib/Tooling/Refactoring/Rename/USRLocFinder.cpp (original)
+++ cfe/trunk/lib/Tooling/Refactoring/Rename/USRLocFinder.cpp Wed Oct 18 
05:10:11 2017
@@ -39,6 +39,17 @@ namespace tooling {
 
 namespace {
 
+// Returns true if the given Loc is valid for edit. We don't edit the
+// SourceLocations that are valid or in temporary buffer.
+bool IsValidEditLoc(const clang::SourceManager& SM, clang::SourceLocation Loc) 
{
+  if (Loc.isInvalid())
+return false;
+  const clang::FullSourceLoc FullLoc(Loc, SM);
+  std::pair FileIdAndOffset =
+  FullLoc.getSpellingLoc().getDecomposedLoc();
+  return SM.getFileEntryForID(FileIdAndOffset.first) != nullptr;
+}
+
 // \brief This visitor recursively searches for all instances of a USR in a
 // translation unit and stores them for later usage.
 class USRLocFindingASTVisitor
@@ -181,13 +192,22 @@ public:
   return true;
 
 if (isInUSRSet(Decl)) {
-  RenameInfo Info = {Decl->getLocation(),
- Decl->getLocation(),
- /*FromDecl=*/nullptr,
- /*Context=*/nullptr,
- /*Specifier=*/nullptr,
- /*IgnorePrefixQualifers=*/true};
-  RenameInfos.push_back(Info);
+  // For the case of renaming an alias template, we actually rename the
+  // underlying alias declaration of the template.
+  if (const auto* TAT = dyn_cast(Decl))
+Decl = TAT->getTemplatedDecl();
+
+  auto StartLoc = Decl->getLocation();
+  auto EndLoc = StartLoc;
+  if (IsValidEditLoc(Context.getSourceManager(), StartLoc)) {
+RenameInfo Info = {StartLoc,
+   EndLoc,
+   /*FromDecl=*/nullptr,
+   /*Context=*/nullptr,
+   /*Specifier=*/nullptr,
+   /*IgnorePrefixQualifers=*/true};
+RenameInfos.push_back(Info);
+  }
 }
 return true;
   }
@@ -200,7 +220,7 @@ public:
   Decl = UsingShadow->getTargetDecl();
 }
 
-auto BeginLoc = Expr->getLocStart();
+auto StartLoc = Expr->getLocStart();
 auto EndLoc = Expr->getLocEnd();
 // In case of renaming an enum declaration, we have to explicitly handle
 // unscoped enum constants referenced in expressions (e.g.
@@ -233,8 +253,9 @@ public:
   assert(EndLoc.isValid() &&
  "The enum constant should have prefix qualifers.");
 }
-if (isInUSRSet(Decl)) {
-  RenameInfo Info = {BeginLoc,
+if (isInUSRSet(Decl) &&
+IsValidEditLoc(Context.getSourceManager(), StartLoc)) {
+  RenameInfo Info = {StartLoc,
  EndLoc,
  Decl,
  getClosestAncestorDecl(*Expr),
@@ -259,8 +280,6 @@ public:
   bool VisitNestedNameSpecifierLocations(NestedNameSpecifierLoc NestedLoc) {
 if (!NestedLoc.getNestedNameSpecifier()->getAsType())
   return true;
-if (IsTypeAliasWhichWillBeRenamedElsewhere(NestedLoc.getTypeLoc()))
-  return true;
 
 if (const auto *TargetDecl =
 getSupportedDeclFromTypeLoc(NestedLoc.getTypeLoc())) {
@@ -278,9 +297,6 @@ public:
   }
 
   bool VisitTypeLoc(TypeLoc Loc) {
-if (IsTypeAliasWhichWillBeRenamedElsewhere(Loc))
-  return true;
-
 auto Parents = Context.getParents(Loc);
 TypeLoc ParentTypeLoc;
 if (!Parents.empty()) {
@@ -314,13 +330,18 @@ public:
 if (!ParentTypeLoc.isNull() &&
 isInUSRSet(getSupportedDeclFromTypeLoc(ParentTypeLoc)))
   return true;
-RenameInfo Info = {StartLocationForType(Loc),
-   EndLocationForType(Loc),
-   TargetDecl,
-   getClosestAncestorDecl(Loc),
-   GetNestedNameForType(Loc),
-   /*IgnorePrefixQualifers=*/false};
-RenameInfos.push_back(Info);
+
+auto StartLoc = StartLocationForType(Loc);
+auto EndLoc = En

[PATCH] D39043: [clang-rename] Rename alias.

2017-10-18 Thread Eric Liu via Phabricator via cfe-commits
ioeric accepted this revision.
ioeric added a comment.
This revision is now accepted and ready to land.

Lg


https://reviews.llvm.org/D39043



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


[PATCH] D39042: [Tooling] Add a factory method for CommonOptionsParser

2017-10-18 Thread Haojian Wu via Phabricator via cfe-commits
hokein added inline comments.



Comment at: include/clang/Tooling/CommonOptionsParser.h:95
 
+  static llvm::Expected>
+  create(int &argc, const char **argv, llvm::cl::OptionCategory &Category,

worth some documentation?



Comment at: include/clang/Tooling/CommonOptionsParser.h:115
+
+  static llvm::Error init(int &argc, const char **argv,
+  llvm::cl::OptionCategory &Category,

We can get rid of the `static` here by calling `parser->init(XXX)`.



Comment at: lib/Tooling/CommonOptionsParser.cpp:165
+const char *Overview) {
+  std::unique_ptr Parser(new CommonOptionsParser);
+  llvm::Error Err =

nit: using llvm::make_unique.


https://reviews.llvm.org/D39042



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


Re: r315856 - Add -f[no-]double-square-bracket-attributes as new driver options to control use of [[]] attributes in all language modes. This is the initial implementation of WG14 N2165, which is a pr

2017-10-18 Thread Aaron Ballman via cfe-commits
I'll take a look, thank you for pointing it out (and sorry for the trouble)!

~Aaron

On Tue, Oct 17, 2017 at 9:56 PM, Galina Kistanova  wrote:
> Hello Aaron,
>
> This commit broke one our builders:
>
> http://lab.llvm.org:8011/builders/ubuntu-gcc7.1-werror/builds/2272
>
> . . .
> FAILED: /usr/local/gcc-7.1/bin/g++-7.1   -DGTEST_HAS_RTTI=0 -D_DEBUG
> -D_GNU_SOURCE -D__STDC_CONSTANT_MACROS -D__STDC_FORMAT_MACROS
> -D__STDC_LIMIT_MACROS -Itools/clang/lib/Basic
> -I/home/buildslave/am1i-slv2/ubuntu-gcc7.1-werror/llvm/tools/clang/lib/Basic
> -I/home/buildslave/am1i-slv2/ubuntu-gcc7.1-werror/llvm/tools/clang/include
> -Itools/clang/include -Iinclude
> -I/home/buildslave/am1i-slv2/ubuntu-gcc7.1-werror/llvm/include
> -Wno-noexcept-type -fPIC -fvisibility-inlines-hidden -Werror
> -Werror=date-time -std=c++11 -Wall -W -Wno-unused-parameter -Wwrite-strings
> -Wcast-qual -Wno-missing-field-initializers -pedantic -Wno-long-long
> -Wno-maybe-uninitialized -Wdelete-non-virtual-dtor -Wno-comment
> -ffunction-sections -fdata-sections -fno-common -Woverloaded-virtual
> -fno-strict-aliasing -O3  -fPIC   -UNDEBUG  -fno-exceptions -fno-rtti -MD
> -MT tools/clang/lib/Basic/CMakeFiles/clangBasic.dir/Attributes.cpp.o -MF
> tools/clang/lib/Basic/CMakeFiles/clangBasic.dir/Attributes.cpp.o.d -o
> tools/clang/lib/Basic/CMakeFiles/clangBasic.dir/Attributes.cpp.o -c
> /home/buildslave/am1i-slv2/ubuntu-gcc7.1-werror/llvm/tools/clang/lib/Basic/Attributes.cpp
> In file included from
> /home/buildslave/am1i-slv2/ubuntu-gcc7.1-werror/llvm/tools/clang/lib/Basic/Attributes.cpp:15:0:
> tools/clang/include/clang/Basic/AttrHasAttributeImpl.inc: In function ‘int
> clang::hasAttribute(clang::AttrSyntax, const clang::IdentifierInfo*, const
> clang::IdentifierInfo*, const clang::TargetInfo&, const
> clang::LangOptions&)’:
> tools/clang/include/clang/Basic/AttrHasAttributeImpl.inc:526:8: error: this
> statement may fall through [-Werror=implicit-fallthrough=]
>  } else if (Scope->getName() == "gsl") {
> ^~
> tools/clang/include/clang/Basic/AttrHasAttributeImpl.inc:532:1: note: here
>  case AttrSyntax::C: {
>  ^~~~
> cc1plus: all warnings being treated as errors
>
> Please have a look?
>
> Thanks
>
> Galina
>
> On Sun, Oct 15, 2017 at 8:01 AM, Aaron Ballman via cfe-commits
>  wrote:
>>
>> Author: aaronballman
>> Date: Sun Oct 15 08:01:42 2017
>> New Revision: 315856
>>
>> URL: http://llvm.org/viewvc/llvm-project?rev=315856&view=rev
>> Log:
>> Add -f[no-]double-square-bracket-attributes as new driver options to
>> control use of [[]] attributes in all language modes. This is the initial
>> implementation of WG14 N2165, which is a proposal to add [[]] attributes to
>> C2x, but also allows you to enable these attributes in C++98, or disable
>> them in C++11 or later.
>>
>> Added:
>> cfe/trunk/test/Misc/ast-dump-c-attr.c
>> cfe/trunk/test/Parser/c2x-attributes.c
>> cfe/trunk/test/Parser/c2x-attributes.m
>> cfe/trunk/test/Sema/attr-deprecated-c2x.c
>> Modified:
>> cfe/trunk/include/clang/Basic/Attr.td
>> cfe/trunk/include/clang/Basic/Attributes.h
>> cfe/trunk/include/clang/Basic/LangOptions.def
>> cfe/trunk/include/clang/Driver/Options.td
>> cfe/trunk/include/clang/Parse/Parser.h
>> cfe/trunk/include/clang/Sema/AttributeList.h
>> cfe/trunk/lib/Frontend/CompilerInvocation.cpp
>> cfe/trunk/lib/Lex/Lexer.cpp
>> cfe/trunk/lib/Parse/ParseDecl.cpp
>> cfe/trunk/lib/Parse/ParseDeclCXX.cpp
>> cfe/trunk/lib/Sema/AttributeList.cpp
>> cfe/trunk/utils/TableGen/ClangAttrEmitter.cpp
>>
>> Modified: cfe/trunk/include/clang/Basic/Attr.td
>> URL:
>> http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Basic/Attr.td?rev=315856&r1=315855&r2=315856&view=diff
>>
>> ==
>> --- cfe/trunk/include/clang/Basic/Attr.td (original)
>> +++ cfe/trunk/include/clang/Basic/Attr.td Sun Oct 15 08:01:42 2017
>> @@ -210,6 +210,10 @@ class CXX11>string Namespace = namespace;
>>int Version = version;
>>  }
>> +class C2x : Spelling {
>> +  string Namespace = namespace;
>> +}
>> +
>>  class Keyword : Spelling;
>>  class Pragma : Spelling {
>>string Namespace = namespace;
>> @@ -958,7 +962,7 @@ def RenderScriptKernel : Attr {
>>
>>  def Deprecated : InheritableAttr {
>>let Spellings = [GCC<"deprecated">, Declspec<"deprecated">,
>> -   CXX11<"","deprecated", 201309>];
>> +   CXX11<"","deprecated", 201309>, C2x<"",
>> "deprecated">];
>>let Args = [StringArgument<"Message", 1>,
>>// An optional string argument that enables us to provide a
>>// Fix-It.
>>
>> Modified: cfe/trunk/include/clang/Basic/Attributes.h
>> URL:
>> http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Basic/Attributes.h?rev=315856&r1=315855&r2=315856&view=diff
>>
>> ==
>> --- cfe/trunk/include/clang/Basic/Attributes

[PATCH] D30691: [analyzer] Support for naive cross translational unit analysis

2017-10-18 Thread Gábor Horváth via Phabricator via cfe-commits
xazax.hun updated this revision to Diff 119458.
xazax.hun marked an inline comment as done.
xazax.hun added a comment.

- Update the scan-build part to work correctly with the accepted version of 
libCrossTU


https://reviews.llvm.org/D30691

Files:
  include/clang/StaticAnalyzer/Core/AnalyzerOptions.h
  include/clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h
  lib/StaticAnalyzer/Core/AnalyzerOptions.cpp
  lib/StaticAnalyzer/Core/CMakeLists.txt
  lib/StaticAnalyzer/Core/CallEvent.cpp
  lib/StaticAnalyzer/Core/ExprEngine.cpp
  lib/StaticAnalyzer/Core/PathDiagnostic.cpp
  lib/StaticAnalyzer/Frontend/AnalysisConsumer.cpp
  lib/StaticAnalyzer/Frontend/CMakeLists.txt
  test/Analysis/Inputs/ctu-chain.cpp
  test/Analysis/Inputs/ctu-other.cpp
  test/Analysis/Inputs/externalFnMap.txt
  test/Analysis/ctu-main.cpp
  tools/scan-build-py/libscanbuild/__init__.py
  tools/scan-build-py/libscanbuild/analyze.py
  tools/scan-build-py/libscanbuild/arguments.py
  tools/scan-build-py/libscanbuild/clang.py
  tools/scan-build-py/libscanbuild/report.py
  tools/scan-build-py/tests/unit/test_analyze.py
  tools/scan-build-py/tests/unit/test_clang.py

Index: tools/scan-build-py/tests/unit/test_clang.py
===
--- tools/scan-build-py/tests/unit/test_clang.py
+++ tools/scan-build-py/tests/unit/test_clang.py
@@ -92,3 +92,16 @@
 self.assertEqual('Checker One description', result.get('checker.one'))
 self.assertTrue('checker.two' in result)
 self.assertEqual('Checker Two description', result.get('checker.two'))
+
+
+class ClangIsCtuCapableTest(unittest.TestCase):
+def test_ctu_not_found(self):
+is_ctu = sut.is_ctu_capable('not-found-clang',
+'not-found-clang-func-mapping')
+self.assertFalse(is_ctu)
+
+
+class ClangGetTripleArchTest(unittest.TestCase):
+def test_arch_is_not_empty(self):
+arch = sut.get_triple_arch(['clang', '-E', '-'], '.')
+self.assertTrue(len(arch) > 0)
Index: tools/scan-build-py/tests/unit/test_analyze.py
===
--- tools/scan-build-py/tests/unit/test_analyze.py
+++ tools/scan-build-py/tests/unit/test_analyze.py
@@ -4,12 +4,12 @@
 # This file is distributed under the University of Illinois Open Source
 # License. See LICENSE.TXT for details.
 
-import libear
-import libscanbuild.analyze as sut
 import unittest
 import re
 import os
 import os.path
+import libear
+import libscanbuild.analyze as sut
 
 
 class ReportDirectoryTest(unittest.TestCase):
@@ -333,3 +333,83 @@
 
 def test_method_exception_not_caught(self):
 self.assertRaises(Exception, method_exception_from_inside, dict())
+
+
+class PrefixWithTest(unittest.TestCase):
+
+def test_gives_empty_on_empty(self):
+res = sut.prefix_with(0, [])
+self.assertFalse(res)
+
+def test_interleaves_prefix(self):
+res = sut.prefix_with(0, [1, 2, 3])
+self.assertListEqual([0, 1, 0, 2, 0, 3], res)
+
+
+class MergeCtuMapTest(unittest.TestCase):
+
+def test_no_map_gives_empty(self):
+pairs = sut.create_global_ctu_function_map([])
+self.assertFalse(pairs)
+
+def test_multiple_maps_merged(self):
+concat_map = ['c:@F@fun1#I# ast/fun1.c.ast',
+  'c:@F@fun2#I# ast/fun2.c.ast',
+  'c:@F@fun3#I# ast/fun3.c.ast']
+pairs = sut.create_global_ctu_function_map(concat_map)
+self.assertTrue(('c:@F@fun1#I#', 'ast/fun1.c.ast') in pairs)
+self.assertTrue(('c:@F@fun2#I#', 'ast/fun2.c.ast') in pairs)
+self.assertTrue(('c:@F@fun3#I#', 'ast/fun3.c.ast') in pairs)
+self.assertEqual(3, len(pairs))
+
+def test_not_unique_func_left_out(self):
+concat_map = ['c:@F@fun1#I# ast/fun1.c.ast',
+  'c:@F@fun2#I# ast/fun2.c.ast',
+  'c:@F@fun1#I# ast/fun7.c.ast']
+pairs = sut.create_global_ctu_function_map(concat_map)
+self.assertFalse(('c:@F@fun1#I#', 'ast/fun1.c.ast') in pairs)
+self.assertFalse(('c:@F@fun1#I#', 'ast/fun7.c.ast') in pairs)
+self.assertTrue(('c:@F@fun2#I#', 'ast/fun2.c.ast') in pairs)
+self.assertEqual(1, len(pairs))
+
+def test_duplicates_are_kept(self):
+concat_map = ['c:@F@fun1#I# ast/fun1.c.ast',
+  'c:@F@fun2#I# ast/fun2.c.ast',
+  'c:@F@fun1#I# ast/fun1.c.ast']
+pairs = sut.create_global_ctu_function_map(concat_map)
+self.assertTrue(('c:@F@fun1#I#', 'ast/fun1.c.ast') in pairs)
+self.assertTrue(('c:@F@fun2#I#', 'ast/fun2.c.ast') in pairs)
+self.assertEqual(2, len(pairs))
+
+def test_space_handled_in_source(self):
+concat_map = ['c:@F@fun1#I# ast/f un.c.ast']
+pairs = sut.create_global_ctu_function_map(concat_map)
+self.assertTrue(('c:@F@fun1#I#', 'ast/f un.c.ast') in pairs)
+self.assertEqual(1, len(pai

[PATCH] D39043: [clang-rename] Rename alias.

2017-10-18 Thread Haojian Wu via Phabricator via cfe-commits
hokein created this revision.
Herald added subscribers: mgorny, klimek.

- Support rename alias.
- Add unittests for renaming alias.
- Don't generate fixes for the SourceLocations that are invalid or in temporary 
buffer, otherwise crash would be happened when generating AtomicChanges.


https://reviews.llvm.org/D39043

Files:
  lib/Tooling/Refactoring/Rename/USRLocFinder.cpp
  unittests/Rename/CMakeLists.txt
  unittests/Rename/RenameAliasTest.cpp

Index: unittests/Rename/RenameAliasTest.cpp
===
--- /dev/null
+++ unittests/Rename/RenameAliasTest.cpp
@@ -0,0 +1,304 @@
+//===-- RenameAliasTest.cpp - unit tests for renaming alias ---===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===--===//
+
+#include "ClangRenameTest.h"
+
+namespace clang {
+namespace clang_rename {
+namespace test {
+namespace {
+
+class RenameAliasTest : public ClangRenameTest {
+public:
+  RenameAliasTest() {
+AppendToHeader(R"(
+#define MACRO(x) x
+namespace some_ns {
+class A {
+ public:
+  void foo() {}
+  struct Nested {
+   enum NestedEnum {
+ E1, E2,
+   };
+  };
+};
+} // namespace some_ns
+namespace a {
+typedef some_ns::A TA;
+using UA = some_ns::A;
+} // namespace a
+namespace b {
+typedef some_ns::A TA;
+using UA = some_ns::A;
+}
+template  class ptr {};
+template 
+
+using TPtr = ptr;
+)");
+  }
+};
+
+INSTANTIATE_TEST_CASE_P(
+RenameAliasTests, RenameAliasTest,
+testing::ValuesIn(std::vector({
+// basic functions
+{"void f(a::TA a1) {}", "void f(b::TB a1) {}", "a::TA", "b::TB"},
+{"void f(a::UA a1) {}", "void f(b::UB a1) {}", "a::UA", "b::UB"},
+{"void f(a::TA* a1) {}", "void f(b::TB* a1) {}", "a::TA", "b::TB"},
+{"void f(a::TA** a1) {}", "void f(b::TB** a1) {}", "a::TA", "b::TB"},
+{"a::TA f() { return a::TA(); }", "b::TB f() { return b::TB(); }",
+ "a::TA", "b::TB"},
+{"a::TA f() { return a::UA(); }", "b::TB f() { return a::UA(); }",
+ "a::TA", "b::TB"},
+{"a::TA f() { return a::UA(); }", "a::TA f() { return b::UB(); }",
+ "a::UA", "b::UB"},
+{"void f() { a::TA a; }", "void f() { b::TB a; }", "a::TA", "b::TB"},
+{"void f(const a::TA& a1) {}", "void f(const b::TB& a1) {}", "a::TA",
+ "b::TB"},
+{"void f(const a::UA& a1) {}", "void f(const b::UB& a1) {}", "a::UA",
+ "b::UB"},
+{"void f(const a::TA* a1) {}", "void f(const b::TB* a1) {}", "a::TA",
+ "b::TB"},
+{"namespace a { void f(TA a1) {} }",
+ "namespace a { void f(b::TB a1) {} }", "a::TA", "b::TB"},
+{"void f(MACRO(a::TA) a1) {}", "void f(MACRO(b::TB) a1) {}", "a::TA",
+ "b::TB"},
+{"void f(MACRO(a::TA a1)) {}", "void f(MACRO(b::TB a1)) {}", "a::TA",
+ "b::TB"},
+
+// shorten/add namespace.
+{"namespace b { void f(a::UA a1) {} }",
+ "namespace b {void f(UB a1) {} }", "a::UA", "b::UB"},
+{"namespace a { void f(UA a1) {} }",
+ "namespace a {void f(b::UB a1) {} }", "a::UA", "b::UB"},
+
+// use namespace and typedefs
+{"struct S { using T = a::TA; T a_; };",
+ "struct S { using T = b::TB; T a_; };", "a::TA", "b::TB"},
+{"using T = a::TA; T gA;", "using T = b::TB; T gA;", "a::TA", "b::TB"},
+{"using T = a::UA; T gA;", "using T = b::UB; T gA;", "a::UA", "b::UB"},
+{"typedef a::TA T; T gA;", "typedef b::TB T; T gA;", "a::TA", "b::TB"},
+{"typedef a::UA T; T gA;", "typedef b::UB T; T gA;", "a::UA", "b::UB"},
+{"typedef MACRO(a::TA) T; T gA;", "typedef MACRO(b::TB) T; T gA;",
+ "a::TA", "b::TB"},
+
+// types in using shadows.
+{"using a::TA; TA gA;", "using b::TB; b::TB gA;", "a::TA", "b::TB"},
+{"using a::UA; UA gA;", "using b::UB; b::UB gA;", "a::UA", "b::UB"},
+
+// struct members and other oddities
+{"struct S : public a::TA {};", "struct S : public b::TB {};", "a::TA",
+ "b::TB"},
+{"struct S : public a::UA {};", "struct S : public b::UB {};", "a::UA",
+ "b::UB"},
+{"struct F { void f(a::TA a1) {} };",
+ "struct F { void f(b::TB a1) {} };", "a::TA", "b::TB"},
+{"struct F { a::TA a_; };", "struct F { b::TB a_; };", "a::TA",
+ "b::TB"},
+{"struct F { ptr a_; };", "struct F { ptr a_; };",
+ "a::TA", "b::TB"},
+{"struct F { ptr a_; };", "struct F { ptr a_; };",
+ "a::UA", "b::UB"},
+
+// types in nested name specifiers
+{"void f() { a::TA::Nested ne; }", 

[PATCH] D34272: [Tooling] A new framework for executing clang frontend actions.

2017-10-18 Thread Eric Liu via Phabricator via cfe-commits
ioeric added inline comments.



Comment at: include/clang/Tooling/CommonOptionsParser.h:90
   ///
-  /// This constructor exits program in case of error.
+  /// If \p ExitOnError is set (default), This constructor exits program in 
case
+  /// of error; otherwise, this sets the error flag and stores error messages.

klimek wrote:
> hokein wrote:
> > `... is set to true` for clarify.
> If we want error handling, why not make it a static factory that returns an 
> ErrorOr instead?
Done. I pulled the changes for `CommonOptionsParser` into a separate patch 
(D39042 ). PTAL



Comment at: include/clang/Tooling/Execution.h:26-27
+//
+//  This is still experimental but expected to replace the existing `ClangTool`
+//  interface.
+//

klimek wrote:
> I'd remove this line. Those tend to only get stale without anybody changing 
> them :)
Right :)



Comment at: include/clang/Tooling/Execution.h:51-53
+  virtual std::vector> AllKVResults() = 0;
+  virtual void forEachResult(
+  llvm::function_ref Callback) = 0;

klimek wrote:
> Why do we need to get the results via the interface? For example, in a 
> map/reduce style setup getting the results is infeasible.
This would enable tools to access results regardless of the underlying 
representation of the results.

In a map/reduce style execution, we could have an implementation that deals 
with fetching and reading remote files; information about remote files can be 
fed into the implementation from the executor that performs such execution. It 
might make sense to add an interface that returns the metadata about the 
underlying data though (e.g. URI for remote files). WDYT?



Comment at: include/clang/Tooling/Execution.h:164-166
+createExecutorFromCommandLineArgs(int &argc, const char **argv,
+  llvm::cl::OptionCategory &Category,
+  const char *Overview = nullptr);

klimek wrote:
> I think for clang-refactor we'll need one level of abstraction in the middle:
> We'll need to be able to say "run on all translation units referencing symbol 
> X" - how will this fit into the design?
> Also, how will code changes generally fit with this design?
> I think for clang-refactor we'll need one level of abstraction in the middle:
> We'll need to be able to say "run on all translation units referencing symbol 
> X" - how will this fit into the design?
Yes. Firstly, I think clang-refactor is responsible for getting all TUs that 
reference a symbols and feeding the set of TUs into the tool interface. And 
then we could implements a "smart" executor that picks an appropriate execution 
(e.g. delegate to standalone executor or map/reduce style execution) according 
to the number of TUs. 

> Also, how will code changes generally fit with this design?
Code changes will be reported by tools/actions via the `ToolResults` interface 
as key-value pairs (e.g. source location + serialized `AtomicChange`). After 
the execution, callers would have access to the results in `ToolResults`, or we 
could also provide an interface that returns the information about the results 
so that they can be accessed later.


https://reviews.llvm.org/D34272



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


[PATCH] D34272: [Tooling] A new framework for executing clang frontend actions.

2017-10-18 Thread Eric Liu via Phabricator via cfe-commits
ioeric updated this revision to Diff 119449.
ioeric marked 7 inline comments as done.
ioeric added a comment.

- Address review comments.


https://reviews.llvm.org/D34272

Files:
  include/clang/Tooling/CommonOptionsParser.h
  include/clang/Tooling/Execution.h
  include/clang/Tooling/StandaloneExecution.h
  include/clang/Tooling/ToolExecutorPluginRegistry.h
  include/clang/Tooling/Tooling.h
  lib/Tooling/CMakeLists.txt
  lib/Tooling/CommonOptionsParser.cpp
  lib/Tooling/Execution.cpp
  lib/Tooling/StandaloneExecution.cpp
  lib/Tooling/Tooling.cpp
  unittests/Tooling/CMakeLists.txt
  unittests/Tooling/ExecutionTest.cpp

Index: unittests/Tooling/ExecutionTest.cpp
===
--- /dev/null
+++ unittests/Tooling/ExecutionTest.cpp
@@ -0,0 +1,248 @@
+//===- unittest/Tooling/ExecutionTest.cpp - Tool execution tests. ===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===--===//
+
+#include "clang/AST/ASTConsumer.h"
+#include "clang/AST/DeclCXX.h"
+#include "clang/AST/RecursiveASTVisitor.h"
+#include "clang/Frontend/ASTUnit.h"
+#include "clang/Frontend/FrontendAction.h"
+#include "clang/Frontend/FrontendActions.h"
+#include "clang/Tooling/CompilationDatabase.h"
+#include "clang/Tooling/Execution.h"
+#include "clang/Tooling/StandaloneExecution.h"
+#include "clang/Tooling/ToolExecutorPluginRegistry.h"
+#include "clang/Tooling/Tooling.h"
+#include "gtest/gtest.h"
+#include 
+#include 
+
+namespace clang {
+namespace tooling {
+
+namespace {
+
+// This traverses the AST and outputs function name as key and "1" as value for
+// each function declaration.
+class ASTConsumerWithResult
+: public ASTConsumer,
+  public RecursiveASTVisitor {
+public:
+  using ASTVisitor = RecursiveASTVisitor;
+
+  explicit ASTConsumerWithResult(ExecutionContext *Context) : Context(Context) {
+assert(Context != nullptr);
+  }
+
+  void HandleTranslationUnit(clang::ASTContext &Context) override {
+TraverseDecl(Context.getTranslationUnitDecl());
+  }
+
+  bool TraverseFunctionDecl(clang::FunctionDecl *Decl) {
+Context->getToolResults()->addResult(Decl->getNameAsString(), "1");
+return ASTVisitor::TraverseFunctionDecl(Decl);
+  }
+
+private:
+  ExecutionContext *const Context;
+};
+
+class ReportResultAction : public ASTFrontendAction {
+public:
+  explicit ReportResultAction(ExecutionContext *Context) : Context(Context) {
+assert(Context != nullptr);
+  }
+
+protected:
+  std::unique_ptr
+  CreateASTConsumer(clang::CompilerInstance &compiler,
+StringRef /* dummy */) override {
+std::unique_ptr ast_consumer{
+new ASTConsumerWithResult(Context)};
+return ast_consumer;
+  }
+
+private:
+  ExecutionContext *const Context;
+};
+
+class ReportResultActionFactory : public FrontendActionFactory {
+public:
+  ReportResultActionFactory(ExecutionContext *Context) : Context(Context) {}
+  FrontendAction *create() override { return new ReportResultAction(Context); }
+
+private:
+  ExecutionContext *const Context;
+};
+
+inline llvm::Error make_string_error(const llvm::Twine &Message) {
+  return llvm::make_error(Message,
+ llvm::inconvertibleErrorCode());
+}
+
+} // namespace
+
+class TestToolExecutor : public ToolExecutor {
+public:
+  static const char *ExecutorName;
+
+  TestToolExecutor(std::unique_ptr Options)
+  : OptionsParser(std::move(Options)) {}
+
+  StringRef getExecutorName() const override { return ExecutorName; }
+
+  llvm::Error execute(const ExecutionConfig &) override {
+return llvm::Error::success();
+  }
+
+  ExecutionContext *getExecutionContext() override { return nullptr; };
+
+  llvm::ArrayRef getSourcePaths() const {
+return OptionsParser->getSourcePathList();
+  }
+
+  void mapVirtualFile(StringRef FilePath, StringRef Content) override {
+VFS[FilePath] = Content;
+  }
+
+private:
+  std::unique_ptr OptionsParser;
+  std::string SourcePaths;
+  std::map VFS;
+};
+
+const char *TestToolExecutor::ExecutorName = "TestToolExecutor";
+
+class TestToolExecutorPlugin : public ToolExecutorPlugin {
+public:
+  llvm::Expected>
+  create(int &argc, const char **argv,
+ llvm::cl::OptionCategory &Category) override {
+// Depending on the test runner, test cases might run in different threads
+// in the same process, so we put test options in the stack and manually
+// remove it from the global registry later so that tests do not interfere
+// with each other.
+llvm::cl::opt TestExecutor("test_executor",
+ llvm::cl::desc("Use TestToolExecutor"));
+auto OptionsParser = CommonOptionsParser::create(
+argc, argv, Category, llvm::cl::OneOrMore, /*Overview=*/nullptr);
+TestExecutor

[PATCH] D35541: [CMake] Use #cmakedefine01 for CLANG_ENABLE_(ARCMT|OBJC_REWRITER|STATIC_ANALYZER)

2017-10-18 Thread NAKAMURA Takumi via Phabricator via cfe-commits
chapuni added a comment.

@krasimir, I concluded it is trivial and committed it with the URL to close 
this.
Feel free to revert if you had any matters.


Repository:
  rL LLVM

https://reviews.llvm.org/D35541



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


[PATCH] D34272: [Tooling] A new framework for executing clang frontend actions.

2017-10-18 Thread Eric Liu via Phabricator via cfe-commits
ioeric updated this revision to Diff 119447.
ioeric added a comment.

- Add a factory method for creating CommonOptionsParser.
- Minor cleanup in CommonOptionsParser.
- Revert CommonOptionsParser changes.
- Merge branch 'option' into arcpatch-D34272


https://reviews.llvm.org/D34272

Files:
  include/clang/Tooling/CommonOptionsParser.h
  include/clang/Tooling/Execution.h
  include/clang/Tooling/StandaloneExecution.h
  include/clang/Tooling/ToolExecutorPluginRegistry.h
  include/clang/Tooling/Tooling.h
  lib/Tooling/CMakeLists.txt
  lib/Tooling/CommonOptionsParser.cpp
  lib/Tooling/Execution.cpp
  lib/Tooling/StandaloneExecution.cpp
  lib/Tooling/Tooling.cpp
  unittests/Tooling/CMakeLists.txt
  unittests/Tooling/ExecutionTest.cpp

Index: unittests/Tooling/ExecutionTest.cpp
===
--- /dev/null
+++ unittests/Tooling/ExecutionTest.cpp
@@ -0,0 +1,248 @@
+//===- unittest/Tooling/ExecutionTest.cpp - Tool execution tests. ===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===--===//
+
+#include "clang/AST/ASTConsumer.h"
+#include "clang/AST/DeclCXX.h"
+#include "clang/AST/RecursiveASTVisitor.h"
+#include "clang/Frontend/ASTUnit.h"
+#include "clang/Frontend/FrontendAction.h"
+#include "clang/Frontend/FrontendActions.h"
+#include "clang/Tooling/CompilationDatabase.h"
+#include "clang/Tooling/Execution.h"
+#include "clang/Tooling/StandaloneExecution.h"
+#include "clang/Tooling/ToolExecutorPluginRegistry.h"
+#include "clang/Tooling/Tooling.h"
+#include "gtest/gtest.h"
+#include 
+#include 
+
+namespace clang {
+namespace tooling {
+
+namespace {
+
+// This traverses the AST and outputs function name as key and "1" as value for
+// each function declaration.
+class ASTConsumerWithResult
+: public ASTConsumer,
+  public RecursiveASTVisitor {
+public:
+  using ASTVisitor = RecursiveASTVisitor;
+
+  explicit ASTConsumerWithResult(ExecutionContext *Context) : Context(Context) {
+assert(Context != nullptr);
+  }
+
+  void HandleTranslationUnit(clang::ASTContext &Context) override {
+TraverseDecl(Context.getTranslationUnitDecl());
+  }
+
+  bool TraverseFunctionDecl(clang::FunctionDecl *Decl) {
+Context->getToolResults()->addResult(Decl->getNameAsString(), "1");
+return ASTVisitor::TraverseFunctionDecl(Decl);
+  }
+
+private:
+  ExecutionContext *const Context;
+};
+
+class ReportResultAction : public ASTFrontendAction {
+public:
+  explicit ReportResultAction(ExecutionContext *Context) : Context(Context) {
+assert(Context != nullptr);
+  }
+
+protected:
+  std::unique_ptr
+  CreateASTConsumer(clang::CompilerInstance &compiler,
+StringRef /* dummy */) override {
+std::unique_ptr ast_consumer{
+new ASTConsumerWithResult(Context)};
+return ast_consumer;
+  }
+
+private:
+  ExecutionContext *const Context;
+};
+
+class ReportResultActionFactory : public FrontendActionFactory {
+public:
+  ReportResultActionFactory(ExecutionContext *Context) : Context(Context) {}
+  FrontendAction *create() override { return new ReportResultAction(Context); }
+
+private:
+  ExecutionContext *const Context;
+};
+
+inline llvm::Error make_string_error(const llvm::Twine &Message) {
+  return llvm::make_error(Message,
+ llvm::inconvertibleErrorCode());
+}
+
+} // namespace
+
+class TestToolExecutor : public ToolExecutor {
+public:
+  static const char *ExecutorName;
+
+  TestToolExecutor(std::unique_ptr Options)
+  : OptionsParser(std::move(Options)) {}
+
+  StringRef getExecutorName() const override { return ExecutorName; }
+
+  llvm::Error execute(const ExecutionConfig &) override {
+return llvm::Error::success();
+  }
+
+  ExecutionContext *getExecutionContext() override { return nullptr; };
+
+  llvm::ArrayRef getSourcePaths() const {
+return OptionsParser->getSourcePathList();
+  }
+
+  void mapVirtualFile(StringRef FilePath, StringRef Content) override {
+VFS[FilePath] = Content;
+  }
+
+private:
+  std::unique_ptr OptionsParser;
+  std::string SourcePaths;
+  std::map VFS;
+};
+
+const char *TestToolExecutor::ExecutorName = "TestToolExecutor";
+
+class TestToolExecutorPlugin : public ToolExecutorPlugin {
+public:
+  llvm::Expected>
+  create(int &argc, const char **argv,
+ llvm::cl::OptionCategory &Category) override {
+// Depending on the test runner, test cases might run in different threads
+// in the same process, so we put test options in the stack and manually
+// remove it from the global registry later so that tests do not interfere
+// with each other.
+llvm::cl::opt TestExecutor("test_executor",
+ llvm::cl::desc("Use TestToolExecutor"));
+auto OptionsParser = CommonOpt

[PATCH] D39042: [Tooling] Add a factory method for CommonOptionsParser

2017-10-18 Thread Eric Liu via Phabricator via cfe-commits
ioeric created this revision.

This returns error instead of exiting the program in case of error.


https://reviews.llvm.org/D39042

Files:
  include/clang/Tooling/CommonOptionsParser.h
  lib/Tooling/CommonOptionsParser.cpp

Index: lib/Tooling/CommonOptionsParser.cpp
===
--- lib/Tooling/CommonOptionsParser.cpp
+++ lib/Tooling/CommonOptionsParser.cpp
@@ -24,9 +24,9 @@
 //
 //===--===//
 
-#include "llvm/Support/CommandLine.h"
 #include "clang/Tooling/CommonOptionsParser.h"
 #include "clang/Tooling/Tooling.h"
+#include "llvm/Support/CommandLine.h"
 
 using namespace clang::tooling;
 using namespace llvm;
@@ -81,9 +81,11 @@
   return Commands;
 }
 
-CommonOptionsParser::CommonOptionsParser(
-int &argc, const char **argv, cl::OptionCategory &Category,
-llvm::cl::NumOccurrencesFlag OccurrencesFlag, const char *Overview) {
+llvm::Error
+CommonOptionsParser::init(int &argc, const char **argv,
+  cl::OptionCategory &Category,
+  llvm::cl::NumOccurrencesFlag OccurrencesFlag,
+  const char *Overview, CommonOptionsParser *Parser) {
   static cl::opt Help("h", cl::desc("Alias for -help"), cl::Hidden,
 cl::sub(*cl::AllSubCommands));
 
@@ -105,41 +107,76 @@
   cl::desc("Additional argument to prepend to the compiler command line"),
   cl::cat(Category), cl::sub(*cl::AllSubCommands));
 
+  cl::ResetAllOptionOccurrences();
+
   cl::HideUnrelatedOptions(Category);
 
   std::string ErrorMessage;
-  Compilations =
+  Parser->Compilations =
   FixedCompilationDatabase::loadFromCommandLine(argc, argv, ErrorMessage);
-  if (!Compilations && !ErrorMessage.empty())
-llvm::errs() << ErrorMessage;
-  cl::ParseCommandLineOptions(argc, argv, Overview);
+  if (!ErrorMessage.empty())
+ErrorMessage.append("\n");
+  llvm::raw_string_ostream OS(ErrorMessage);
+  // Stop initializing if command-line option parsing failed.
+  if (!cl::ParseCommandLineOptions(argc, argv, Overview, &OS)) {
+OS.flush();
+return llvm::make_error("[CommonOptionsParser]: " +
+   ErrorMessage,
+   llvm::inconvertibleErrorCode());
+  }
+
   cl::PrintOptionValues();
 
-  SourcePathList = SourcePaths;
+  Parser->SourcePathList = SourcePaths;
   if ((OccurrencesFlag == cl::ZeroOrMore || OccurrencesFlag == cl::Optional) &&
-  SourcePathList.empty())
-return;
-  if (!Compilations) {
+  Parser->SourcePathList.empty())
+return llvm::Error::success();
+  if (!Parser->Compilations) {
 if (!BuildPath.empty()) {
-  Compilations =
+  Parser->Compilations =
   CompilationDatabase::autoDetectFromDirectory(BuildPath, ErrorMessage);
 } else {
-  Compilations = CompilationDatabase::autoDetectFromSource(SourcePaths[0],
-   ErrorMessage);
+  Parser->Compilations = CompilationDatabase::autoDetectFromSource(
+  SourcePaths[0], ErrorMessage);
 }
-if (!Compilations) {
+if (!Parser->Compilations) {
   llvm::errs() << "Error while trying to load a compilation database:\n"
<< ErrorMessage << "Running without flags.\n";
-  Compilations.reset(
+  Parser->Compilations.reset(
   new FixedCompilationDatabase(".", std::vector()));
 }
   }
   auto AdjustingCompilations =
   llvm::make_unique(
-  std::move(Compilations));
+  std::move(Parser->Compilations));
   AdjustingCompilations->appendArgumentsAdjuster(
   getInsertArgumentAdjuster(ArgsBefore, ArgumentInsertPosition::BEGIN));
   AdjustingCompilations->appendArgumentsAdjuster(
   getInsertArgumentAdjuster(ArgsAfter, ArgumentInsertPosition::END));
-  Compilations = std::move(AdjustingCompilations);
+  Parser->Compilations = std::move(AdjustingCompilations);
+  return llvm::Error::success();
+}
+
+llvm::Expected>
+CommonOptionsParser::create(int &argc, const char **argv,
+llvm::cl::OptionCategory &Category,
+llvm::cl::NumOccurrencesFlag OccurrencesFlag,
+const char *Overview) {
+  std::unique_ptr Parser(new CommonOptionsParser);
+  llvm::Error Err =
+  init(argc, argv, Category, OccurrencesFlag, Overview, Parser.get());
+  if (Err)
+return std::move(Err);
+  return Parser;
+}
+
+CommonOptionsParser::CommonOptionsParser(
+int &argc, const char **argv, cl::OptionCategory &Category,
+llvm::cl::NumOccurrencesFlag OccurrencesFlag, const char *Overview) {
+  llvm::Error Err = init(argc, argv, Category, OccurrencesFlag, Overview, this);
+  if (Err) {
+llvm::report_fatal_error(
+"CommonOptionsParser: failed to parse command-line arguments. " +
+llvm::toString(std::move(Err)));
+  }
 }
I

r316069 - [ASTImporter] Import SubStmt of CaseStmt

2017-10-18 Thread Gabor Horvath via cfe-commits
Author: xazax
Date: Wed Oct 18 02:25:18 2017
New Revision: 316069

URL: http://llvm.org/viewvc/llvm-project?rev=316069&view=rev
Log:
[ASTImporter] Import SubStmt of CaseStmt

Patch by: Rafael Stahl!

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

Modified:
cfe/trunk/lib/AST/ASTImporter.cpp
cfe/trunk/unittests/AST/ASTImporterTest.cpp

Modified: cfe/trunk/lib/AST/ASTImporter.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/AST/ASTImporter.cpp?rev=316069&r1=316068&r2=316069&view=diff
==
--- cfe/trunk/lib/AST/ASTImporter.cpp (original)
+++ cfe/trunk/lib/AST/ASTImporter.cpp Wed Oct 18 02:25:18 2017
@@ -3983,12 +3983,16 @@ Stmt *ASTNodeImporter::VisitCaseStmt(Cas
   Expr *ToRHS = Importer.Import(S->getRHS());
   if (!ToRHS && S->getRHS())
 return nullptr;
+  Stmt *ToSubStmt = Importer.Import(S->getSubStmt());
+  if (!ToSubStmt && S->getSubStmt())
+return nullptr;
   SourceLocation ToCaseLoc = Importer.Import(S->getCaseLoc());
   SourceLocation ToEllipsisLoc = Importer.Import(S->getEllipsisLoc());
   SourceLocation ToColonLoc = Importer.Import(S->getColonLoc());
-  return new (Importer.getToContext()) CaseStmt(ToLHS, ToRHS,
-ToCaseLoc, ToEllipsisLoc,
-ToColonLoc);
+  CaseStmt *ToStmt = new (Importer.getToContext())
+  CaseStmt(ToLHS, ToRHS, ToCaseLoc, ToEllipsisLoc, ToColonLoc);
+  ToStmt->setSubStmt(ToSubStmt);
+  return ToStmt;
 }
 
 Stmt *ASTNodeImporter::VisitDefaultStmt(DefaultStmt *S) {

Modified: cfe/trunk/unittests/AST/ASTImporterTest.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/unittests/AST/ASTImporterTest.cpp?rev=316069&r1=316068&r2=316069&view=diff
==
--- cfe/trunk/unittests/AST/ASTImporterTest.cpp (original)
+++ cfe/trunk/unittests/AST/ASTImporterTest.cpp Wed Oct 18 02:25:18 2017
@@ -97,6 +97,10 @@ testImport(const std::string &FromCode,
   llvm::raw_svector_ostream ToNothing(ImportChecker);
   ToCtx.getTranslationUnitDecl()->print(ToNothing);
 
+  // This traverses the AST to catch certain bugs like poorly or not
+  // implemented subtrees.
+  Imported->dump(ToNothing);
+
   return Verifier.match(Imported, AMatcher);
 }
 
@@ -267,6 +271,15 @@ TEST(ImportExpr, ImportParenListExpr) {
   
hasUnaryOperand(cxxThisExpr();
 }
 
+TEST(ImportExpr, ImportSwitch) {
+  MatchVerifier Verifier;
+  EXPECT_TRUE(
+  testImport("void declToImport() { int b; switch (b) { case 1: break; } 
}",
+ Lang_CXX, "", Lang_CXX, Verifier,
+ functionDecl(hasBody(compoundStmt(
+ has(switchStmt(has(compoundStmt(has(caseStmt()));
+}
+
 TEST(ImportExpr, ImportStmtExpr) {
   MatchVerifier Verifier;
   // NOTE: has() ignores implicit casts, using hasDescendant() to match it


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


[PATCH] D38943: [ASTImporter] import SubStmt of CaseStmt

2017-10-18 Thread Phabricator via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rL316069: [ASTImporter] Import SubStmt of CaseStmt (authored 
by xazax).

Changed prior to commit:
  https://reviews.llvm.org/D38943?vs=119162&id=119444#toc

Repository:
  rL LLVM

https://reviews.llvm.org/D38943

Files:
  cfe/trunk/lib/AST/ASTImporter.cpp
  cfe/trunk/unittests/AST/ASTImporterTest.cpp


Index: cfe/trunk/lib/AST/ASTImporter.cpp
===
--- cfe/trunk/lib/AST/ASTImporter.cpp
+++ cfe/trunk/lib/AST/ASTImporter.cpp
@@ -3983,12 +3983,16 @@
   Expr *ToRHS = Importer.Import(S->getRHS());
   if (!ToRHS && S->getRHS())
 return nullptr;
+  Stmt *ToSubStmt = Importer.Import(S->getSubStmt());
+  if (!ToSubStmt && S->getSubStmt())
+return nullptr;
   SourceLocation ToCaseLoc = Importer.Import(S->getCaseLoc());
   SourceLocation ToEllipsisLoc = Importer.Import(S->getEllipsisLoc());
   SourceLocation ToColonLoc = Importer.Import(S->getColonLoc());
-  return new (Importer.getToContext()) CaseStmt(ToLHS, ToRHS,
-ToCaseLoc, ToEllipsisLoc,
-ToColonLoc);
+  CaseStmt *ToStmt = new (Importer.getToContext())
+  CaseStmt(ToLHS, ToRHS, ToCaseLoc, ToEllipsisLoc, ToColonLoc);
+  ToStmt->setSubStmt(ToSubStmt);
+  return ToStmt;
 }
 
 Stmt *ASTNodeImporter::VisitDefaultStmt(DefaultStmt *S) {
Index: cfe/trunk/unittests/AST/ASTImporterTest.cpp
===
--- cfe/trunk/unittests/AST/ASTImporterTest.cpp
+++ cfe/trunk/unittests/AST/ASTImporterTest.cpp
@@ -97,6 +97,10 @@
   llvm::raw_svector_ostream ToNothing(ImportChecker);
   ToCtx.getTranslationUnitDecl()->print(ToNothing);
 
+  // This traverses the AST to catch certain bugs like poorly or not
+  // implemented subtrees.
+  Imported->dump(ToNothing);
+
   return Verifier.match(Imported, AMatcher);
 }
 
@@ -267,6 +271,15 @@
   
hasUnaryOperand(cxxThisExpr();
 }
 
+TEST(ImportExpr, ImportSwitch) {
+  MatchVerifier Verifier;
+  EXPECT_TRUE(
+  testImport("void declToImport() { int b; switch (b) { case 1: break; } 
}",
+ Lang_CXX, "", Lang_CXX, Verifier,
+ functionDecl(hasBody(compoundStmt(
+ has(switchStmt(has(compoundStmt(has(caseStmt()));
+}
+
 TEST(ImportExpr, ImportStmtExpr) {
   MatchVerifier Verifier;
   // NOTE: has() ignores implicit casts, using hasDescendant() to match it


Index: cfe/trunk/lib/AST/ASTImporter.cpp
===
--- cfe/trunk/lib/AST/ASTImporter.cpp
+++ cfe/trunk/lib/AST/ASTImporter.cpp
@@ -3983,12 +3983,16 @@
   Expr *ToRHS = Importer.Import(S->getRHS());
   if (!ToRHS && S->getRHS())
 return nullptr;
+  Stmt *ToSubStmt = Importer.Import(S->getSubStmt());
+  if (!ToSubStmt && S->getSubStmt())
+return nullptr;
   SourceLocation ToCaseLoc = Importer.Import(S->getCaseLoc());
   SourceLocation ToEllipsisLoc = Importer.Import(S->getEllipsisLoc());
   SourceLocation ToColonLoc = Importer.Import(S->getColonLoc());
-  return new (Importer.getToContext()) CaseStmt(ToLHS, ToRHS,
-ToCaseLoc, ToEllipsisLoc,
-ToColonLoc);
+  CaseStmt *ToStmt = new (Importer.getToContext())
+  CaseStmt(ToLHS, ToRHS, ToCaseLoc, ToEllipsisLoc, ToColonLoc);
+  ToStmt->setSubStmt(ToSubStmt);
+  return ToStmt;
 }
 
 Stmt *ASTNodeImporter::VisitDefaultStmt(DefaultStmt *S) {
Index: cfe/trunk/unittests/AST/ASTImporterTest.cpp
===
--- cfe/trunk/unittests/AST/ASTImporterTest.cpp
+++ cfe/trunk/unittests/AST/ASTImporterTest.cpp
@@ -97,6 +97,10 @@
   llvm::raw_svector_ostream ToNothing(ImportChecker);
   ToCtx.getTranslationUnitDecl()->print(ToNothing);
 
+  // This traverses the AST to catch certain bugs like poorly or not
+  // implemented subtrees.
+  Imported->dump(ToNothing);
+
   return Verifier.match(Imported, AMatcher);
 }
 
@@ -267,6 +271,15 @@
   hasUnaryOperand(cxxThisExpr();
 }
 
+TEST(ImportExpr, ImportSwitch) {
+  MatchVerifier Verifier;
+  EXPECT_TRUE(
+  testImport("void declToImport() { int b; switch (b) { case 1: break; } }",
+ Lang_CXX, "", Lang_CXX, Verifier,
+ functionDecl(hasBody(compoundStmt(
+ has(switchStmt(has(compoundStmt(has(caseStmt()));
+}
+
 TEST(ImportExpr, ImportStmtExpr) {
   MatchVerifier Verifier;
   // NOTE: has() ignores implicit casts, using hasDescendant() to match it
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D37808: [clang-tidy] Add new hicpp-multiway-paths-covered check for missing branches

2017-10-18 Thread Jonas Toth via Phabricator via cfe-commits
JonasToth updated this revision to Diff 119440.
JonasToth marked an inline comment as done.
JonasToth added a comment.

- address review comments


https://reviews.llvm.org/D37808

Files:
  clang-tidy/hicpp/CMakeLists.txt
  clang-tidy/hicpp/HICPPTidyModule.cpp
  clang-tidy/hicpp/MultiwayPathsCoveredCheck.cpp
  clang-tidy/hicpp/MultiwayPathsCoveredCheck.h
  docs/ReleaseNotes.rst
  docs/clang-tidy/checks/hicpp-multiway-paths-covered.rst
  docs/clang-tidy/checks/list.rst
  test/clang-tidy/hicpp-multiway-paths-covered-else.cpp
  test/clang-tidy/hicpp-multiway-paths-covered.cpp

Index: test/clang-tidy/hicpp-multiway-paths-covered.cpp
===
--- /dev/null
+++ test/clang-tidy/hicpp-multiway-paths-covered.cpp
@@ -0,0 +1,445 @@
+// RUN: %check_clang_tidy %s hicpp-multiway-paths-covered %t
+
+enum OS { Mac,
+  Windows,
+  Linux };
+
+struct Bitfields {
+  unsigned UInt : 3;
+  int SInt : 1;
+};
+
+int return_integer() { return 42; }
+
+void bad_switch(int i) {
+  switch (i) {
+// CHECK-MESSAGES: [[@LINE-1]]:3: warning: switch with only one case; use if statement
+  case 0:
+break;
+  }
+  // No default in this switch
+  switch (i) {
+  // CHECK-MESSAGES: [[@LINE-1]]:3: warning: potential uncovered codepath; add a default case
+  case 0:
+break;
+  case 1:
+break;
+  case 2:
+break;
+  }
+
+  // degenerate, maybe even warning
+  switch (i) {
+// CHECK-MESSAGES: [[@LINE-1]]:3: warning: degenerated switch without labels
+  }
+
+  switch (int j = return_integer()) {
+  // CHECK-MESSAGES: [[@LINE-1]]:3: warning: potential uncovered codepath; add a default case
+  case 0:
+  case 1:
+  case 2:
+break;
+  }
+
+  // Degenerated, only default case.
+  switch (i) {
+// CHECK-MESSAGES: [[@LINE-1]]:3: warning: degenerated switch with default label only
+  default:
+break;
+  }
+
+  // Degenerated, only one case label and default case -> Better as if-stmt.
+  switch (i) {
+// CHECK-MESSAGES: [[@LINE-1]]:3: warning: switch could be better written as if/else statement
+  case 0:
+break;
+  default:
+break;
+  }
+
+  unsigned long long BigNumber = 0;
+  switch (BigNumber) {
+  // CHECK-MESSAGES: [[@LINE-1]]:3: warning: potential uncovered codepath; add a default case
+  case 0:
+  case 1:
+break;
+  }
+
+  const int &IntRef = i;
+  switch (IntRef) {
+  // CHECK-MESSAGES: [[@LINE-1]]:3: warning: potential uncovered codepath; add a default case
+  case 0:
+  case 1:
+break;
+  }
+
+  char C = 'A';
+  switch (C) {
+  // CHECK-MESSAGES: [[@LINE-1]]:3: warning: potential uncovered codepath; add a default case
+  case 'A':
+break;
+  case 'B':
+break;
+  }
+
+  Bitfields Bf;
+  // UInt has 3 bits size.
+  switch (Bf.UInt) {
+// CHECK-MESSAGES: [[@LINE-1]]:3: warning: potential uncovered codepath; add a default case
+  case 0:
+  case 1:
+break;
+  }
+  // All paths explicitly covered.
+  switch (Bf.UInt) {
+  case 0:
+  case 1:
+  case 2:
+  case 3:
+  case 4:
+  case 5:
+  case 6:
+  case 7:
+break;
+  }
+  // SInt has 1 bit size, so this is somewhat degenerated.
+  switch (Bf.SInt) {
+// CHECK-MESSAGES: [[@LINE-1]]:3: warning: switch with only one case; use if statement
+  case 0:
+break;
+  }
+  // All paths explicitly covered.
+  switch (Bf.SInt) {
+  case 0:
+  case 1:
+break;
+  }
+}
+
+void unproblematic_switch(unsigned char c) {
+  switch (c) {
+  case 0:
+  case 1:
+  case 2:
+  case 3:
+  case 4:
+  case 5:
+  case 6:
+  case 7:
+  case 8:
+  case 9:
+  case 10:
+  case 11:
+  case 12:
+  case 13:
+  case 14:
+  case 15:
+  case 16:
+  case 17:
+  case 18:
+  case 19:
+  case 20:
+  case 21:
+  case 22:
+  case 23:
+  case 24:
+  case 25:
+  case 26:
+  case 27:
+  case 28:
+  case 29:
+  case 30:
+  case 31:
+  case 32:
+  case 33:
+  case 34:
+  case 35:
+  case 36:
+  case 37:
+  case 38:
+  case 39:
+  case 40:
+  case 41:
+  case 42:
+  case 43:
+  case 44:
+  case 45:
+  case 46:
+  case 47:
+  case 48:
+  case 49:
+  case 50:
+  case 51:
+  case 52:
+  case 53:
+  case 54:
+  case 55:
+  case 56:
+  case 57:
+  case 58:
+  case 59:
+  case 60:
+  case 61:
+  case 62:
+  case 63:
+  case 64:
+  case 65:
+  case 66:
+  case 67:
+  case 68:
+  case 69:
+  case 70:
+  case 71:
+  case 72:
+  case 73:
+  case 74:
+  case 75:
+  case 76:
+  case 77:
+  case 78:
+  case 79:
+  case 80:
+  case 81:
+  case 82:
+  case 83:
+  case 84:
+  case 85:
+  case 86:
+  case 87:
+  case 88:
+  case 89:
+  case 90:
+  case 91:
+  case 92:
+  case 93:
+  case 94:
+  case 95:
+  case 96:
+  case 97:
+  case 98:
+  case 99:
+  case 100:
+  case 101:
+  case 102:
+  case 103:
+  case 104:
+  case 105:
+  case 106:
+  case 107:
+  case 108:
+  case 109:
+  case 110:
+  case 111:
+  case 112:
+  case 113:
+  case 114:
+  case 115:
+  case 116:
+  case 117:
+  case 118:
+  case 119:
+  case 120:
+  case 121:
+  case 122:
+  case 123:
+  case 124:
+  case 125:
+  case 126:
+  case 127:

[PATCH] D37808: [clang-tidy] Add new hicpp-multiway-paths-covered check for missing branches

2017-10-18 Thread Jonas Toth via Phabricator via cfe-commits
JonasToth marked 4 inline comments as done.
JonasToth added inline comments.



Comment at: clang-tidy/hicpp/MultiwayPathsCoveredCheck.cpp:98
+  // hold.
+  const std::size_t BitCount = [&T, &Context]() {
+if (T->isIntegralType(Context))

JDevlieghere wrote:
> Unless you expect a whole bunch of logic to be added here, I'd un-const and 
> initialize BitCount to zero, then just have if-clause reassign it and get rid 
> of the lambda. This will save you a few lines of code and complexity. 
I dont know if i missed some integral types, that need special care, so this 
one was defensive.

But with the refactoring i made, I should change this, agreed.


https://reviews.llvm.org/D37808



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


[clang-tools-extra] r316066 - New -assume-filename=param to check_clang_tidy.py (like clang-format)

2017-10-18 Thread Haojian Wu via cfe-commits
Author: hokein
Date: Wed Oct 18 00:48:40 2017
New Revision: 316066

URL: http://llvm.org/viewvc/llvm-project?rev=316066&view=rev
Log:
New -assume-filename=param to check_clang_tidy.py (like clang-format)

Summary:
Currently, check_clang_tidy.py includes logic to select default
clang flags based on the extension of the source filename passed
as the first argument.

Since the source filename might be a temporary or test file with an
arbitrary extension unrelated to the file type, this adds the ability
to override the logic the same way `clang-format`'s -assume-filename=
parameter does.

I included a test with a nonstandard file extension. I confirmed
when I modified the warning message that the new test failed,
and that it passed again when I restored the warning message.

Ran tests with:

% cmake -G Ninja /path/to/llvm
% ninja check-clang-tools

Patch by Ben Hamilton!

Reviewers: hokein, alexfh

Reviewed By: hokein

Subscribers: alexfh

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

Added:
clang-tools-extra/trunk/test/clang-tidy/nonstandard-file-extension.test
Modified:
clang-tools-extra/trunk/test/clang-tidy/check_clang_tidy.py

Modified: clang-tools-extra/trunk/test/clang-tidy/check_clang_tidy.py
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/test/clang-tidy/check_clang_tidy.py?rev=316066&r1=316065&r2=316066&view=diff
==
--- clang-tools-extra/trunk/test/clang-tidy/check_clang_tidy.py (original)
+++ clang-tools-extra/trunk/test/clang-tidy/check_clang_tidy.py Wed Oct 18 
00:48:40 2017
@@ -17,6 +17,7 @@ This script runs clang-tidy in fix mode
 
 Usage:
   check_clang_tidy.py [-resource-dir ] \
+[-assume-filename ] \
\
 -- [optional clang-tidy arguments]
 
@@ -38,6 +39,7 @@ def write_file(file_name, text):
 def main():
   parser = argparse.ArgumentParser()
   parser.add_argument('-resource-dir')
+  parser.add_argument('-assume-filename')
   parser.add_argument('input_file_name')
   parser.add_argument('check_name')
   parser.add_argument('temp_file_name')
@@ -45,14 +47,17 @@ def main():
   args, extra_args = parser.parse_known_args()
 
   resource_dir = args.resource_dir
+  assume_file_name = args.assume_filename
   input_file_name = args.input_file_name
   check_name = args.check_name
   temp_file_name = args.temp_file_name
 
+  file_name_with_extension = assume_file_name or input_file_name
+
   extension = '.cpp'
-  if (input_file_name.endswith('.c')):
+  if (file_name_with_extension.endswith('.c')):
 extension = '.c'
-  if (input_file_name.endswith('.hpp')):
+  if (file_name_with_extension.endswith('.hpp')):
 extension = '.hpp'
   temp_file_name = temp_file_name + extension
 

Added: clang-tools-extra/trunk/test/clang-tidy/nonstandard-file-extension.test
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/test/clang-tidy/nonstandard-file-extension.test?rev=316066&view=auto
==
--- clang-tools-extra/trunk/test/clang-tidy/nonstandard-file-extension.test 
(added)
+++ clang-tools-extra/trunk/test/clang-tidy/nonstandard-file-extension.test Wed 
Oct 18 00:48:40 2017
@@ -0,0 +1,6 @@
+// RUN: %check_clang_tidy -assume-filename=const-cast.cpp %s 
cppcoreguidelines-pro-type-const-cast %t
+
+const int *i;
+int *j;
+void f() { j = const_cast(i); }
+// CHECK-MESSAGES: :[[@LINE-1]]:16: warning: do not use const_cast 
[cppcoreguidelines-pro-type-const-cast]


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