[PATCH] D44189: [RISCV] Verify the input value of -march=

2018-03-07 Thread Kito Cheng via Phabricator via cfe-commits
kito-cheng marked 2 inline comments as done.
kito-cheng added inline comments.



Comment at: lib/Driver/ToolChains/Arch/RISCV.cpp:48
+  break;
+default:
+  // First letter should be 'i' or 'g'.

apazos wrote:
> In the switch cases move default to first position.
Done :)



Comment at: lib/Driver/ToolChains/Arch/RISCV.cpp:60
   case 'm':
 Features.push_back("+m");
 break;

apazos wrote:
> So the subsequent features can appear in any order?
Yeah, here is a canonical order specified in ISA manual, I've check the order 
now.


Repository:
  rC Clang

https://reviews.llvm.org/D44189



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


[PATCH] D44189: [RISCV] Verify the input value of -march=

2018-03-07 Thread Kito Cheng via Phabricator via cfe-commits
kito-cheng updated this revision to Diff 137547.

Repository:
  rC Clang

https://reviews.llvm.org/D44189

Files:
  lib/Driver/ToolChains/Arch/RISCV.cpp
  test/Driver/riscv-arch.c

Index: test/Driver/riscv-arch.c
===
--- /dev/null
+++ test/Driver/riscv-arch.c
@@ -0,0 +1,29 @@
+// RUN: %clang -target riscv32-unknown-elf -march=rv32 -### %s -fsyntax-only 2>&1 | FileCheck -check-prefix=RV32 %s
+// RV32: error: invalid arch name 'rv32'
+
+// RUN: %clang -target riscv32-unknown-elf -march=rv32m -### %s -fsyntax-only 2>&1 | FileCheck -check-prefix=RV32M %s
+// RV32M: error: invalid arch name 'rv32m'
+
+// RUN: %clang -target riscv32-unknown-elf -march=rv32id -### %s -fsyntax-only 2>&1 | FileCheck -check-prefix=RV32ID %s
+// RV32ID: error: invalid arch name 'rv32id'
+
+// RUN: %clang -target riscv32-unknown-elf -march=rv32l -### %s -fsyntax-only 2>&1 | FileCheck -check-prefix=RV32L %s
+// RV32L: error: invalid arch name 'rv32l'
+
+// RUN: %clang -target riscv32-unknown-elf -march=rv32imadf -### %s -fsyntax-only 2>&1 | FileCheck -check-prefix=RV32IMADF %s
+// RV32IMADF: error: invalid arch name 'rv32imadf'
+
+// RUN: %clang -target riscv64-unknown-elf -march=rv64 -### %s -fsyntax-only 2>&1 | FileCheck -check-prefix=RV64 %s
+// RV64: error: invalid arch name 'rv64'
+
+// RUN: %clang -target riscv64-unknown-elf -march=rv64m -### %s -fsyntax-only 2>&1 | FileCheck -check-prefix=RV64M %s
+// RV64M: error: invalid arch name 'rv64m'
+
+// RUN: %clang -target riscv64-unknown-elf -march=rv64id -### %s -fsyntax-only 2>&1 | FileCheck -check-prefix=RV64ID %s
+// RV64ID: error: invalid arch name 'rv64id'
+
+// RUN: %clang -target riscv64-unknown-elf -march=rv64l -### %s -fsyntax-only 2>&1 | FileCheck -check-prefix=RV64L %s
+// RV64L: error: invalid arch name 'rv64l'
+
+// RUN: %clang -target riscv64-unknown-elf -march=rv64imadf -### %s -fsyntax-only 2>&1 | FileCheck -check-prefix=RV64IMADF %s
+// RV64IMADF: error: invalid arch name 'rv64imadf'
Index: lib/Driver/ToolChains/Arch/RISCV.cpp
===
--- lib/Driver/ToolChains/Arch/RISCV.cpp
+++ lib/Driver/ToolChains/Arch/RISCV.cpp
@@ -23,33 +23,82 @@
 void riscv::getRISCVTargetFeatures(const Driver , const ArgList ,
std::vector ) {
   if (const Arg *A = Args.getLastArg(options::OPT_march_EQ)) {
-StringRef MArch = A->getValue();
-// TODO: handle rv64
-std::pair MArchSplit = StringRef(MArch).split("rv32");
-if (!MArchSplit.second.size())
+StringRef March = A->getValue();
+if (!(March.startswith("rv32") || March.startswith("rv64")) ||
+(March.size() < 5)) {
+  // ISA string must begin with rv32 or rv64.
+  D.Diag(diag::err_drv_invalid_arch_name) << March;
   return;
+}
+
+// The canonical order specified in ISA manual.
+StringRef StdExts = "mafdc";
+
+bool hasF = false, hasD = false;
+char baseline = March[4];
+
+// TODO: Handle 'e' once backend supported.
+switch (baseline) {
+default:
+  // First letter should be 'e', 'i' or 'g'.
+  D.Diag(diag::err_drv_invalid_arch_name) << March;
+  return;
+case 'i':
+  break;
+case 'g':
+  // g = imafd
+  StdExts = StdExts.drop_front(4);
+  Features.push_back("+m");
+  Features.push_back("+a");
+  Features.push_back("+f");
+  Features.push_back("+d");
+  hasF = true;
+  hasD = true;
+  break;
+}
 
-for (char c : MArchSplit.second) {
+auto StdExtsItr = StdExts.begin();
+// Skip rvxxx
+StringRef Exts = March.substr(5);
+
+for (char c : Exts) {
+  // Check march is satisfied the canonical order.
+  while (StdExtsItr != StdExts.end() && *StdExtsItr != c)
+ ++StdExtsItr;
+
+  if (StdExtsItr == StdExts.end()) {
+D.Diag(diag::err_drv_invalid_arch_name) << March;
+return;
+  }
+
+  // The order is OK, then push it into features.
   switch (c) {
-  case 'i':
-break;
+  default:
+D.Diag(diag::err_drv_invalid_arch_name) << March;
+return;
   case 'm':
 Features.push_back("+m");
 break;
   case 'a':
 Features.push_back("+a");
 break;
   case 'f':
 Features.push_back("+f");
+hasF = true;
 break;
   case 'd':
 Features.push_back("+d");
+hasD = true;
 break;
   case 'c':
 Features.push_back("+c");
 break;
   }
 }
+
+// Dependency check
+if (hasD && !hasF)
+  D.Diag(diag::err_drv_invalid_arch_name) << March;
   }
 }
 
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


r326990 - Propagate DLLAttr to friend re-declarations of member functions

2018-03-07 Thread Stephan Bergmann via cfe-commits
Author: sberg
Date: Wed Mar  7 23:34:40 2018
New Revision: 326990

URL: http://llvm.org/viewvc/llvm-project?rev=326990=rev
Log:
Propagate DLLAttr to friend re-declarations of member functions

...that have already been constructed (e.g., in inner classes) while parsing the
class definition.  They would otherwise lack any DLLAttr inherited from the
class, which are only set here (called from Sema::CheckCompletedClass) after the
class definition has been parsed completely.

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

Modified:
cfe/trunk/lib/Sema/SemaDeclCXX.cpp
cfe/trunk/test/CodeGenCXX/dllexport.cpp

Modified: cfe/trunk/lib/Sema/SemaDeclCXX.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Sema/SemaDeclCXX.cpp?rev=326990=326989=326990=diff
==
--- cfe/trunk/lib/Sema/SemaDeclCXX.cpp (original)
+++ cfe/trunk/lib/Sema/SemaDeclCXX.cpp Wed Mar  7 23:34:40 2018
@@ -5685,6 +5685,21 @@ void Sema::checkClassLevelDLLAttribute(C
   cast(ClassAttr->clone(getASTContext()));
   NewAttr->setInherited(true);
   Member->addAttr(NewAttr);
+
+  if (MD) {
+// Propagate DLLAttr to friend re-declarations of MD that have already
+// been constructed.
+for (FunctionDecl *FD = MD->getMostRecentDecl(); FD;
+ FD = FD->getPreviousDecl()) {
+  if (FD->getFriendObjectKind() == Decl::FOK_None)
+continue;
+  assert(!getDLLAttr(FD) &&
+ "friend re-decl should not already have a DLLAttr");
+  NewAttr = cast(ClassAttr->clone(getASTContext()));
+  NewAttr->setInherited(true);
+  FD->addAttr(NewAttr);
+}
+  }
 }
   }
 

Modified: cfe/trunk/test/CodeGenCXX/dllexport.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/CodeGenCXX/dllexport.cpp?rev=326990=326989=326990=diff
==
--- cfe/trunk/test/CodeGenCXX/dllexport.cpp (original)
+++ cfe/trunk/test/CodeGenCXX/dllexport.cpp Wed Mar  7 23:34:40 2018
@@ -290,6 +290,16 @@ struct FuncFriend {
 __declspec(dllexport) void friend1() {}
   void friend2() {}
 
+// MSC-DAG: define dso_local dllexport void @"\01?func@Befriended@@SAXXZ"()
+// GNU-DAG: define dso_local dllexport void @_ZN10Befriended4funcEv()
+struct __declspec(dllexport) Befriended {
+  static void func();
+  struct Befriending {
+friend void Befriended::func();
+  };
+};
+void Befriended::func() {}
+
 // Implicit declarations can be redeclared with dllexport.
 // MSC-DAG: define dso_local dllexport noalias i8* 
@"\01??2@{{YAPAXI|YAPEAX_K}}@Z"(
 // GNU-DAG: define dso_local dllexport noalias i8* @_Znw{{[yj]}}(


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


[PATCH] D16632: clang-cl: Take dllexport from original function decl into account

2018-03-07 Thread Stephan Bergmann via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rL326990: Propagate DLLAttr to friend re-declarations of 
member functions (authored by sberg, committed by ).
Herald added a subscriber: llvm-commits.

Changed prior to commit:
  https://reviews.llvm.org/D16632?vs=137374=137548#toc

Repository:
  rL LLVM

https://reviews.llvm.org/D16632

Files:
  cfe/trunk/lib/Sema/SemaDeclCXX.cpp
  cfe/trunk/test/CodeGenCXX/dllexport.cpp


Index: cfe/trunk/test/CodeGenCXX/dllexport.cpp
===
--- cfe/trunk/test/CodeGenCXX/dllexport.cpp
+++ cfe/trunk/test/CodeGenCXX/dllexport.cpp
@@ -290,6 +290,16 @@
 __declspec(dllexport) void friend1() {}
   void friend2() {}
 
+// MSC-DAG: define dso_local dllexport void @"\01?func@Befriended@@SAXXZ"()
+// GNU-DAG: define dso_local dllexport void @_ZN10Befriended4funcEv()
+struct __declspec(dllexport) Befriended {
+  static void func();
+  struct Befriending {
+friend void Befriended::func();
+  };
+};
+void Befriended::func() {}
+
 // Implicit declarations can be redeclared with dllexport.
 // MSC-DAG: define dso_local dllexport noalias i8* 
@"\01??2@{{YAPAXI|YAPEAX_K}}@Z"(
 // GNU-DAG: define dso_local dllexport noalias i8* @_Znw{{[yj]}}(
Index: cfe/trunk/lib/Sema/SemaDeclCXX.cpp
===
--- cfe/trunk/lib/Sema/SemaDeclCXX.cpp
+++ cfe/trunk/lib/Sema/SemaDeclCXX.cpp
@@ -5685,6 +5685,21 @@
   cast(ClassAttr->clone(getASTContext()));
   NewAttr->setInherited(true);
   Member->addAttr(NewAttr);
+
+  if (MD) {
+// Propagate DLLAttr to friend re-declarations of MD that have already
+// been constructed.
+for (FunctionDecl *FD = MD->getMostRecentDecl(); FD;
+ FD = FD->getPreviousDecl()) {
+  if (FD->getFriendObjectKind() == Decl::FOK_None)
+continue;
+  assert(!getDLLAttr(FD) &&
+ "friend re-decl should not already have a DLLAttr");
+  NewAttr = cast(ClassAttr->clone(getASTContext()));
+  NewAttr->setInherited(true);
+  FD->addAttr(NewAttr);
+}
+  }
 }
   }
 


Index: cfe/trunk/test/CodeGenCXX/dllexport.cpp
===
--- cfe/trunk/test/CodeGenCXX/dllexport.cpp
+++ cfe/trunk/test/CodeGenCXX/dllexport.cpp
@@ -290,6 +290,16 @@
 __declspec(dllexport) void friend1() {}
   void friend2() {}
 
+// MSC-DAG: define dso_local dllexport void @"\01?func@Befriended@@SAXXZ"()
+// GNU-DAG: define dso_local dllexport void @_ZN10Befriended4funcEv()
+struct __declspec(dllexport) Befriended {
+  static void func();
+  struct Befriending {
+friend void Befriended::func();
+  };
+};
+void Befriended::func() {}
+
 // Implicit declarations can be redeclared with dllexport.
 // MSC-DAG: define dso_local dllexport noalias i8* @"\01??2@{{YAPAXI|YAPEAX_K}}@Z"(
 // GNU-DAG: define dso_local dllexport noalias i8* @_Znw{{[yj]}}(
Index: cfe/trunk/lib/Sema/SemaDeclCXX.cpp
===
--- cfe/trunk/lib/Sema/SemaDeclCXX.cpp
+++ cfe/trunk/lib/Sema/SemaDeclCXX.cpp
@@ -5685,6 +5685,21 @@
   cast(ClassAttr->clone(getASTContext()));
   NewAttr->setInherited(true);
   Member->addAttr(NewAttr);
+
+  if (MD) {
+// Propagate DLLAttr to friend re-declarations of MD that have already
+// been constructed.
+for (FunctionDecl *FD = MD->getMostRecentDecl(); FD;
+ FD = FD->getPreviousDecl()) {
+  if (FD->getFriendObjectKind() == Decl::FOK_None)
+continue;
+  assert(!getDLLAttr(FD) &&
+ "friend re-decl should not already have a DLLAttr");
+  NewAttr = cast(ClassAttr->clone(getASTContext()));
+  NewAttr->setInherited(true);
+  FD->addAttr(NewAttr);
+}
+  }
 }
   }
 
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


r326988 - [CodeGen] Emit lifetime.ends in both EH and non-EH blocks

2018-03-07 Thread George Burgess IV via cfe-commits
Author: gbiv
Date: Wed Mar  7 21:32:30 2018
New Revision: 326988

URL: http://llvm.org/viewvc/llvm-project?rev=326988=rev
Log:
[CodeGen] Emit lifetime.ends in both EH and non-EH blocks

Before this, we'd only emit lifetime.ends for these temps in
non-exceptional paths. This potentially made our stack larger than it
needed to be for any code that follows an EH cleanup. e.g. in

```
struct Foo { char cs[32]; };

void escape(void *);

struct Bar { ~Bar() { char cs[64]; escape(cs); } };

Foo getFoo();

void baz() {
  Bar b;
  getFoo();
}
```

baz() would require 96 bytes of stack, since the temporary from getFoo()
only had a lifetime.end on the non-exceptional path.

This also makes us keep hold of the Value* returned by
EmitLifetimeStart, so we don't have to remake it later.

Added:
cfe/trunk/test/CodeGenCXX/stack-reuse-exceptions.cpp
Modified:
cfe/trunk/lib/CodeGen/CGCall.cpp

Modified: cfe/trunk/lib/CodeGen/CGCall.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/CodeGen/CGCall.cpp?rev=326988=326987=326988=diff
==
--- cfe/trunk/lib/CodeGen/CGCall.cpp (original)
+++ cfe/trunk/lib/CodeGen/CGCall.cpp Wed Mar  7 21:32:30 2018
@@ -3790,7 +3790,7 @@ RValue CodeGenFunction::EmitCall(const C
   // If the call returns a temporary with struct return, create a temporary
   // alloca to hold the result, unless one is given to us.
   Address SRetPtr = Address::invalid();
-  size_t UnusedReturnSize = 0;
+  llvm::Value *UnusedReturnSizePtr = nullptr;
   if (RetAI.isIndirect() || RetAI.isInAlloca() || RetAI.isCoerceAndExpand()) {
 if (!ReturnValue.isNull()) {
   SRetPtr = ReturnValue.getValue();
@@ -3799,8 +3799,7 @@ RValue CodeGenFunction::EmitCall(const C
   if (HaveInsertPoint() && ReturnValue.isUnused()) {
 uint64_t size =
 CGM.getDataLayout().getTypeAllocSize(ConvertTypeForMem(RetTy));
-if (EmitLifetimeStart(size, SRetPtr.getPointer()))
-  UnusedReturnSize = size;
+UnusedReturnSizePtr = EmitLifetimeStart(size, SRetPtr.getPointer());
   }
 }
 if (IRFunctionArgs.hasSRetArg()) {
@@ -4231,6 +4230,15 @@ RValue CodeGenFunction::EmitCall(const C
 CannotThrow = Attrs.hasAttribute(llvm::AttributeList::FunctionIndex,
  llvm::Attribute::NoUnwind);
   }
+
+  // If we made a temporary, be sure to clean up after ourselves. Note that we
+  // can't depend on being inside of an ExprWithCleanups, so we need to 
manually
+  // pop this cleanup later on. Being eager about this is OK, since this
+  // temporary is 'invisible' outside of the callee.
+  if (UnusedReturnSizePtr)
+pushFullExprCleanup(NormalEHLifetimeMarker, SRetPtr,
+ UnusedReturnSizePtr);
+
   llvm::BasicBlock *InvokeDest = CannotThrow ? nullptr : getInvokeDest();
 
   SmallVector BundleList =
@@ -4284,9 +4292,8 @@ RValue CodeGenFunction::EmitCall(const C
   // insertion point; this allows the rest of IRGen to discard
   // unreachable code.
   if (CS.doesNotReturn()) {
-if (UnusedReturnSize)
-  EmitLifetimeEnd(llvm::ConstantInt::get(Int64Ty, UnusedReturnSize),
-  SRetPtr.getPointer());
+if (UnusedReturnSizePtr)
+  PopCleanupBlock();
 
 // Strip away the noreturn attribute to better diagnose unreachable UB.
 if (SanOpts.has(SanitizerKind::Unreachable)) {
@@ -4355,9 +4362,8 @@ RValue CodeGenFunction::EmitCall(const C
 case ABIArgInfo::InAlloca:
 case ABIArgInfo::Indirect: {
   RValue ret = convertTempToRValue(SRetPtr, RetTy, SourceLocation());
-  if (UnusedReturnSize)
-EmitLifetimeEnd(llvm::ConstantInt::get(Int64Ty, UnusedReturnSize),
-SRetPtr.getPointer());
+  if (UnusedReturnSizePtr)
+PopCleanupBlock();
   return ret;
 }
 

Added: cfe/trunk/test/CodeGenCXX/stack-reuse-exceptions.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/CodeGenCXX/stack-reuse-exceptions.cpp?rev=326988=auto
==
--- cfe/trunk/test/CodeGenCXX/stack-reuse-exceptions.cpp (added)
+++ cfe/trunk/test/CodeGenCXX/stack-reuse-exceptions.cpp Wed Mar  7 21:32:30 
2018
@@ -0,0 +1,189 @@
+// RUN: %clang_cc1 -triple x86_64-unknown-linux-gnu %s -o - -emit-llvm -O1 \
+// RUN: -fexceptions -fcxx-exceptions | FileCheck %s
+//
+// We should emit lifetime.ends for these temporaries in both the 'exception'
+// and 'normal' paths in functions.
+//
+// -O1 is necessary to make lifetime markers appear.
+
+struct Large {
+  int cs[32];
+};
+
+Large getLarge();
+
+// Used to ensure we emit invokes.
+struct NontrivialDtor {
+  int i;
+  ~NontrivialDtor();
+};
+
+// CHECK-LABEL: define void @_Z33cleanupsAreEmittedWithoutTryCatchv
+void cleanupsAreEmittedWithoutTryCatch() {
+// CHECK: %[[CLEAN:[^ ]+]] = bitcast %struct.NontrivialDtor* %{{[^ ]+}} to i8*
+// 

[PATCH] D44095: [ObjC] Allow declaring __weak pointer fields in C structs in ObjC-ARC

2018-03-07 Thread John McCall via Phabricator via cfe-commits
rjmccall accepted this revision.
rjmccall added a comment.
This revision is now accepted and ready to land.

LGTM, thanks.




Comment at: lib/CodeGen/CGNonTrivialStruct.cpp:764
+Object = CGF->EmitObjCConsumeObject(QT, Object);
+CGF->EmitARCStoreWeak(Addrs[DstIdx], Object, true);
+  }

ahatanak wrote:
> rjmccall wrote:
> > I guess this is the most reasonable thing to do, given that we don't have 
> > an entrypoint for it.  Please ask the ObjC runtime team to consider giving 
> > us one, though.  We could pretty easily peephole assignments into `__weak` 
> > variables where the source is loaded from a `__weak` l-value / x-value, and 
> > Swift would probably be able to take advantage of it, too.
> > 
> > You might want to go ahead and add `emitARCCopyAssignWeak` / 
> > `emitARCMoveAssignWeak` methods on CGF that do these operations and which 
> > can be optimized to use those entrypoints if/when they're added.
> Do you mean we should ask for the following objc runtime functions and use 
> them in visitARCWeak?
> 
> ```
> // dst and src are either null or registered as __weak objects.
> void objc_copyAssignWeak(id *dst, id *src)
> void objc_moveAssignWeak(id *dst, id *src)
> 
I meant that we should implement `emitARCCopyAssignWeak` and 
`emitARCMoveAssignWeak` by calling those functions if they're available, yes.

(Obviously that would be a follow-up patch, even assuming the ObjC runtime 
agrees to add them.)

Those functions would be specified as leaving the source in a zeroed state, 
which is as good as uninitialized, so they could be used for true-destructive 
moves as well.


https://reviews.llvm.org/D44095



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


[PATCH] D44178: [analyzer] Correctly model iteration through "nil" objects

2018-03-07 Thread George Karpenkov via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rC326982: [analyzer] Correctly model iteration through 
nil objects (authored by george.karpenkov, committed by ).
Herald added a subscriber: cfe-commits.

Changed prior to commit:
  https://reviews.llvm.org/D44178?vs=137287=137532#toc

Repository:
  rC Clang

https://reviews.llvm.org/D44178

Files:
  lib/AST/ParentMap.cpp
  lib/StaticAnalyzer/Core/ExprEngineObjC.cpp
  test/Analysis/objc-for.m

Index: test/Analysis/objc-for.m
===
--- test/Analysis/objc-for.m
+++ test/Analysis/objc-for.m
@@ -32,6 +32,7 @@
 
 @interface NSDictionary (SomeCategory)
 - (void)categoryMethodOnNSDictionary;
+- (id) allKeys;
 @end
 
 @interface NSMutableDictionary : NSDictionary
@@ -343,3 +344,10 @@
   for (id key in array)
 clang_analyzer_warnIfReached(); // expected-warning{{REACHABLE}}
 }
+
+int not_reachable_on_iteration_through_nil() {
+  NSDictionary* d = nil;
+  for (NSString* s in [d allKeys])
+clang_analyzer_warnIfReached(); // no-warning
+  return 0;
+}
Index: lib/StaticAnalyzer/Core/ExprEngineObjC.cpp
===
--- lib/StaticAnalyzer/Core/ExprEngineObjC.cpp
+++ lib/StaticAnalyzer/Core/ExprEngineObjC.cpp
@@ -42,6 +42,47 @@
   getCheckerManager().runCheckersForPreStmt(Dst, Pred, S, *this);
 }
 
+/// Generate a node in \p Bldr for an iteration statement using ObjC
+/// for-loop iterator.
+static void populateObjCForDestinationSet(
+ExplodedNodeSet , SValBuilder ,
+const ObjCForCollectionStmt *S, const Stmt *elem, SVal elementV,
+SymbolManager , const NodeBuilderContext *currBldrCtx,
+StmtNodeBuilder , bool hasElements) {
+
+  for (ExplodedNode *Pred : dstLocation) {
+ProgramStateRef state = Pred->getState();
+const LocationContext *LCtx = Pred->getLocationContext();
+
+SVal hasElementsV = svalBuilder.makeTruthVal(hasElements);
+
+// FIXME: S is not an expression. We should not be binding values to it.
+ProgramStateRef nextState = state->BindExpr(S, LCtx, hasElementsV);
+
+if (auto MV = elementV.getAs())
+  if (const auto *R = dyn_cast(MV->getRegion())) {
+// FIXME: The proper thing to do is to really iterate over the
+//  container.  We will do this with dispatch logic to the store.
+//  For now, just 'conjure' up a symbolic value.
+QualType T = R->getValueType();
+assert(Loc::isLocType(T));
+
+SVal V;
+if (hasElements) {
+  SymbolRef Sym = SymMgr.conjureSymbol(elem, LCtx, T,
+   currBldrCtx->blockCount());
+  V = svalBuilder.makeLoc(Sym);
+} else {
+  V = svalBuilder.makeIntVal(0, T);
+}
+
+nextState = nextState->bindLoc(elementV, V, LCtx);
+  }
+
+Bldr.generateNode(S, Pred, nextState);
+  }
+}
+
 void ExprEngine::VisitObjCForCollectionStmt(const ObjCForCollectionStmt *S,
 ExplodedNode *Pred,
 ExplodedNodeSet ) {
@@ -72,60 +113,35 @@
   //result in state splitting.
 
   const Stmt *elem = S->getElement();
+  const Stmt *collection = S->getCollection();
   ProgramStateRef state = Pred->getState();
-  SVal elementV;
+  SVal collectionV = state->getSVal(collection, Pred->getLocationContext());
 
-  if (const DeclStmt *DS = dyn_cast(elem)) {
+  SVal elementV;
+  if (const auto *DS = dyn_cast(elem)) {
 const VarDecl *elemD = cast(DS->getSingleDecl());
 assert(elemD->getInit() == nullptr);
 elementV = state->getLValue(elemD, Pred->getLocationContext());
-  }
-  else {
+  } else {
 elementV = state->getSVal(elem, Pred->getLocationContext());
   }
 
+  bool isContainerNull = state->isNull(collectionV).isConstrainedTrue();
+
   ExplodedNodeSet dstLocation;
   evalLocation(dstLocation, S, elem, Pred, state, elementV, nullptr, false);
 
   ExplodedNodeSet Tmp;
   StmtNodeBuilder Bldr(Pred, Tmp, *currBldrCtx);
 
-  for (ExplodedNodeSet::iterator NI = dstLocation.begin(),
-   NE = dstLocation.end(); NI!=NE; ++NI) {
-Pred = *NI;
-ProgramStateRef state = Pred->getState();
-const LocationContext *LCtx = Pred->getLocationContext();
-
-// Handle the case where the container still has elements.
-SVal TrueV = svalBuilder.makeTruthVal(1);
-ProgramStateRef hasElems = state->BindExpr(S, LCtx, TrueV);
-
-// Handle the case where the container has no elements.
-SVal FalseV = svalBuilder.makeTruthVal(0);
-ProgramStateRef noElems = state->BindExpr(S, LCtx, FalseV);
-
-if (Optional MV = elementV.getAs())
-  if (const TypedValueRegion *R =
-  dyn_cast(MV->getRegion())) {
-// FIXME: The proper thing to do is to really iterate over the
-//  container.  We will do this with dispatch logic to the store.
-//  For now, just 'conjure' up a symbolic value.
-   

r326982 - [analyzer] Correctly model iteration through "nil" objects

2018-03-07 Thread George Karpenkov via cfe-commits
Author: george.karpenkov
Date: Wed Mar  7 18:53:39 2018
New Revision: 326982

URL: http://llvm.org/viewvc/llvm-project?rev=326982=rev
Log:
[analyzer] Correctly model iteration through "nil" objects

Previously, iteration through nil objects which resulted from
objc-messages being set to nil were modeled incorrectly.

There are a couple of notes about this patch:

In principle, ExprEngineObjC might be left untouched IFF osx.loops
checker is enabled.
I however think that we should not do something
completely incorrect depending on what checkers are left on.
We should evaluate and potentially remove altogether the isConsumedExpr
performance heuristic, as it seems very fragile.

rdar://22205149

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

Modified:
cfe/trunk/lib/AST/ParentMap.cpp
cfe/trunk/lib/StaticAnalyzer/Core/ExprEngineObjC.cpp
cfe/trunk/test/Analysis/objc-for.m

Modified: cfe/trunk/lib/AST/ParentMap.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/AST/ParentMap.cpp?rev=326982=326981=326982=diff
==
--- cfe/trunk/lib/AST/ParentMap.cpp (original)
+++ cfe/trunk/lib/AST/ParentMap.cpp Wed Mar  7 18:53:39 2018
@@ -15,6 +15,7 @@
 #include "clang/AST/Decl.h"
 #include "clang/AST/Expr.h"
 #include "clang/AST/ExprCXX.h"
+#include "clang/AST/StmtObjC.h"
 #include "llvm/ADT/DenseMap.h"
 
 using namespace clang;
@@ -193,6 +194,8 @@ bool ParentMap::isConsumedExpr(Expr* E)
   return DirectChild == cast(P)->getTarget();
 case Stmt::SwitchStmtClass:
   return DirectChild == cast(P)->getCond();
+case Stmt::ObjCForCollectionStmtClass:
+  return DirectChild == cast(P)->getCollection();
 case Stmt::ReturnStmtClass:
   return true;
   }

Modified: cfe/trunk/lib/StaticAnalyzer/Core/ExprEngineObjC.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/StaticAnalyzer/Core/ExprEngineObjC.cpp?rev=326982=326981=326982=diff
==
--- cfe/trunk/lib/StaticAnalyzer/Core/ExprEngineObjC.cpp (original)
+++ cfe/trunk/lib/StaticAnalyzer/Core/ExprEngineObjC.cpp Wed Mar  7 18:53:39 
2018
@@ -42,6 +42,47 @@ void ExprEngine::VisitObjCAtSynchronized
   getCheckerManager().runCheckersForPreStmt(Dst, Pred, S, *this);
 }
 
+/// Generate a node in \p Bldr for an iteration statement using ObjC
+/// for-loop iterator.
+static void populateObjCForDestinationSet(
+ExplodedNodeSet , SValBuilder ,
+const ObjCForCollectionStmt *S, const Stmt *elem, SVal elementV,
+SymbolManager , const NodeBuilderContext *currBldrCtx,
+StmtNodeBuilder , bool hasElements) {
+
+  for (ExplodedNode *Pred : dstLocation) {
+ProgramStateRef state = Pred->getState();
+const LocationContext *LCtx = Pred->getLocationContext();
+
+SVal hasElementsV = svalBuilder.makeTruthVal(hasElements);
+
+// FIXME: S is not an expression. We should not be binding values to it.
+ProgramStateRef nextState = state->BindExpr(S, LCtx, hasElementsV);
+
+if (auto MV = elementV.getAs())
+  if (const auto *R = dyn_cast(MV->getRegion())) {
+// FIXME: The proper thing to do is to really iterate over the
+//  container.  We will do this with dispatch logic to the store.
+//  For now, just 'conjure' up a symbolic value.
+QualType T = R->getValueType();
+assert(Loc::isLocType(T));
+
+SVal V;
+if (hasElements) {
+  SymbolRef Sym = SymMgr.conjureSymbol(elem, LCtx, T,
+   currBldrCtx->blockCount());
+  V = svalBuilder.makeLoc(Sym);
+} else {
+  V = svalBuilder.makeIntVal(0, T);
+}
+
+nextState = nextState->bindLoc(elementV, V, LCtx);
+  }
+
+Bldr.generateNode(S, Pred, nextState);
+  }
+}
+
 void ExprEngine::VisitObjCForCollectionStmt(const ObjCForCollectionStmt *S,
 ExplodedNode *Pred,
 ExplodedNodeSet ) {
@@ -72,60 +113,35 @@ void ExprEngine::VisitObjCForCollectionS
   //result in state splitting.
 
   const Stmt *elem = S->getElement();
+  const Stmt *collection = S->getCollection();
   ProgramStateRef state = Pred->getState();
-  SVal elementV;
+  SVal collectionV = state->getSVal(collection, Pred->getLocationContext());
 
-  if (const DeclStmt *DS = dyn_cast(elem)) {
+  SVal elementV;
+  if (const auto *DS = dyn_cast(elem)) {
 const VarDecl *elemD = cast(DS->getSingleDecl());
 assert(elemD->getInit() == nullptr);
 elementV = state->getLValue(elemD, Pred->getLocationContext());
-  }
-  else {
+  } else {
 elementV = state->getSVal(elem, Pred->getLocationContext());
   }
 
+  bool isContainerNull = state->isNull(collectionV).isConstrainedTrue();
+
   ExplodedNodeSet dstLocation;
   evalLocation(dstLocation, S, elem, Pred, state, elementV, nullptr, false);
 
   ExplodedNodeSet Tmp;
   

r326980 - Fix an unused variable warning; NFC

2018-03-07 Thread George Burgess IV via cfe-commits
Author: gbiv
Date: Wed Mar  7 18:15:12 2018
New Revision: 326980

URL: http://llvm.org/viewvc/llvm-project?rev=326980=rev
Log:
Fix an unused variable warning; NFC

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

Modified: cfe/trunk/lib/StaticAnalyzer/Core/ExprEngine.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/StaticAnalyzer/Core/ExprEngine.cpp?rev=326980=326979=326980=diff
==
--- cfe/trunk/lib/StaticAnalyzer/Core/ExprEngine.cpp (original)
+++ cfe/trunk/lib/StaticAnalyzer/Core/ExprEngine.cpp Wed Mar  7 18:15:12 2018
@@ -2466,7 +2466,7 @@ void ExprEngine::VisitCommonDeclRefExpr(
   ProgramPoint::PostLValueKind);
 return;
   }
-  if (const auto* BD = dyn_cast(D)) {
+  if (isa(D)) {
 // FIXME: proper support for bound declarations.
 // For now, let's just prevent crashing.
 return;


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


[PATCH] D44241: Add a check for constructing non-trivial types without assigning to a variable

2018-03-07 Thread Paul Fultz II via Phabricator via cfe-commits
pfultz2 created this revision.
pfultz2 added reviewers: clang-tools-extra, aaron.ballman.
pfultz2 added a project: clang-tools-extra.
Herald added a subscriber: mgorny.

Diagnoses when a non-trivial type is not assigned to a variable. This is useful 
to check for problems like unnamed lock guards.

For example, if you had code written like this:

  int g_i = 0;
  std::mutex g_i_mutex;  // protects g_i
   
  void safe_increment()
  {
std::lock_guard{g_i_mutex};
// The lock is locked and then unlocked before reaching here
++g_i;
  }

This will warn that a variable should be created instead:

  int g_i = 0;
  std::mutex g_i_mutex;  // protects g_i
   
  void safe_increment()
  {
std::lock_guard lock{g_i_mutex};
// The lock is locked and then will be unlocked when exiting scope
++g_i;
  }


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D44241

Files:
  clang-tidy/misc/CMakeLists.txt
  clang-tidy/misc/MiscTidyModule.cpp
  clang-tidy/misc/OwnerlessResourceCheck.cpp
  clang-tidy/misc/OwnerlessResourceCheck.h
  docs/ReleaseNotes.rst
  docs/clang-tidy/checks/list.rst
  docs/clang-tidy/checks/misc-ownerless-resource.rst
  test/clang-tidy/misc-ownerless-resource.cpp

Index: test/clang-tidy/misc-ownerless-resource.cpp
===
--- /dev/null
+++ test/clang-tidy/misc-ownerless-resource.cpp
@@ -0,0 +1,36 @@
+// RUN: %check_clang_tidy %s misc-ownerless-resource %t
+
+struct Trivial {};
+
+struct NonTrivial {
+  int *mem;
+  NonTrivial()
+  : mem(new int()) {}
+  NonTrivial(int)
+  : mem(new int()) {}
+  ~NonTrivial() {
+delete mem;
+  }
+};
+
+NonTrivial f() { return {}; }
+void g(NonTrivial) {}
+
+void fail() {
+  NonTrivial{};
+  // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: Resource has no owner; Did you mean to declare it with a variable name? [misc-ownerless-resource]
+  NonTrivial{1};
+  // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: Resource has no owner; Did you mean to declare it with a variable name? [misc-ownerless-resource]
+}
+
+void valid() {
+  NonTrivial a{};
+  auto b = NonTrivial{};
+
+  g(f());
+  f();
+
+  auto c = f();
+  Trivial{};
+  Trivial x{};
+}
Index: docs/clang-tidy/checks/misc-ownerless-resource.rst
===
--- /dev/null
+++ docs/clang-tidy/checks/misc-ownerless-resource.rst
@@ -0,0 +1,34 @@
+.. title:: clang-tidy - misc-ownerless-resource
+
+misc-ownerless-resource
+===
+
+Diagnoses when a non-trivial type is not assigned to a variable. This is useful to check for problems like unamed lock guards.
+
+For example, if you had code written like this:
+
+.. code-block:: c++
+
+  int g_i = 0;
+  std::mutex g_i_mutex;  // protects g_i
+   
+  void safe_increment()
+  {
+std::lock_guard{g_i_mutex};
+// The lock is locked and then unlocked before reaching here
+++g_i;
+  }
+
+This will warn that a variable should be created instead:
+
+.. code-block:: c++
+
+  int g_i = 0;
+  std::mutex g_i_mutex;  // protects g_i
+   
+  void safe_increment()
+  {
+std::lock_guard lock{g_i_mutex};
+// The lock is locked and then will be unlocked when exiting scope
+++g_i;
+  }
Index: docs/clang-tidy/checks/list.rst
===
--- docs/clang-tidy/checks/list.rst
+++ docs/clang-tidy/checks/list.rst
@@ -143,6 +143,7 @@
misc-misplaced-const
misc-new-delete-overloads
misc-non-copyable-objects
+   misc-ownerless-resource
misc-redundant-expression
misc-sizeof-container
misc-sizeof-expression
Index: docs/ReleaseNotes.rst
===
--- docs/ReleaseNotes.rst
+++ docs/ReleaseNotes.rst
@@ -57,6 +57,12 @@
 Improvements to clang-tidy
 --
 
+- New `misc-ownerless-resource
+  `_ check
+
+  Diagnoses when a non-trivial type is not assigned to a variable. This is
+  useful to check for problems like unamed lock guards.
+
 - New `bugprone-throw-keyword-missing
   `_ check
 
Index: clang-tidy/misc/OwnerlessResourceCheck.h
===
--- /dev/null
+++ clang-tidy/misc/OwnerlessResourceCheck.h
@@ -0,0 +1,35 @@
+//===--- OwnerlessResourceCheck.h - clang-tidy---*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===--===//
+
+#ifndef LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_MISC_OWNERLESSRESOURCECHECK_H
+#define LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_MISC_OWNERLESSRESOURCECHECK_H
+
+#include "../ClangTidy.h"
+
+namespace clang {
+namespace 

[PATCH] D16403: Add scope information to CFG

2018-03-07 Thread Artem Dergachev via Phabricator via cfe-commits
NoQ added inline comments.



Comment at: lib/Analysis/CFG.cpp:1700
 /// way return valid LocalScope object.
 LocalScope* CFGBuilder::createOrReuseLocalScope(LocalScope* Scope) {
   if (Scope)

NoQ wrote:
> It seems that something  has moved asterisks to a weird spot, might be a 
> rebase artifact or accidental tooling.
Uhm, it was always this way, just weird history when i looked at the diff 
between diffs, nvm, sorry.


Repository:
  rL LLVM

https://reviews.llvm.org/D16403



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


[PATCH] D16403: Add scope information to CFG

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

I think we should land this and celebrate.

@szepet: Ouch, i was sure i already answered this, sorry, dunno where this went.

> So, LoopExit and ScopeExit would be the same but the underlying TriggerStmt 
> would decide which marks a loop and which marks a variable?

I was thinking of a single `CFGElement` to mark both. Which would probably be 
called "`ScopeExit`", but you could use it for detecting the end of the loop 
and, if necessary, add whatever information you need into it.




Comment at: lib/Analysis/CFG.cpp:1700
 /// way return valid LocalScope object.
 LocalScope* CFGBuilder::createOrReuseLocalScope(LocalScope* Scope) {
   if (Scope)

It seems that something  has moved asterisks to a weird spot, might be a rebase 
artifact or accidental tooling.


Repository:
  rL LLVM

https://reviews.llvm.org/D16403



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


r326979 - [Documentation] Fix Release notes problems introduced in r326889. Add highlighting.

2018-03-07 Thread Eugene Zelenko via cfe-commits
Author: eugenezelenko
Date: Wed Mar  7 17:37:39 2018
New Revision: 326979

URL: http://llvm.org/viewvc/llvm-project?rev=326979=rev
Log:
[Documentation] Fix Release notes problems introduced in r326889. Add 
highlighting.

Modified:
cfe/trunk/docs/ReleaseNotes.rst

Modified: cfe/trunk/docs/ReleaseNotes.rst
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/docs/ReleaseNotes.rst?rev=326979=326978=326979=diff
==
--- cfe/trunk/docs/ReleaseNotes.rst (original)
+++ cfe/trunk/docs/ReleaseNotes.rst Wed Mar  7 17:37:39 2018
@@ -74,11 +74,12 @@ future versions of Clang.
 Modified Compiler Flags
 ---
 
-- Before Clang 7.0, we prepended the "#" character to the --autocomplete 
argument to
-enable cc1 flags. For example, when the -cc1 or -Xclang flag is in the clang 
invocation,
-the shell executed clang --autocomplete=#-. Clang 7.0 now
-requires the whole invocation including all flags to be passed to the 
--autocomplete
-like this: clang --autocomplete=-cc1,-xc++,-fsyn.
+- Before Clang 7.0, we prepended the `#` character to the `--autocomplete`
+  argument to enable cc1 flags. For example, when the `-cc1` or `-Xclang` flag
+  is in the :program:`clang` invocation, the shell executed
+  `clang --autocomplete=#-`. Clang 7.0 now requires the
+  whole invocation including all flags to be passed to the `--autocomplete` 
like
+  this: `clang --autocomplete=-cc1,-xc++,-fsyn`.
 
 New Pragmas in Clang
 ---
@@ -95,6 +96,7 @@ Attribute Changes in Clang
   sanity, however it is otherwise compatible with existing code using this
   feature for GCC. Consult the documentation for the target attribute for more
   information.
+
 - ...
 
 Windows Support


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


[PATCH] D44239: [analyzer] Re-enable constructor inlining when lifetime extension through fields occurs.

2018-03-07 Thread Artem Dergachev via Phabricator via cfe-commits
NoQ created this revision.
NoQ added reviewers: dcoughlin, xazax.hun, a.sidorin, george.karpenkov, szepet.
Herald added subscribers: cfe-commits, rnkovacs.
NoQ added a dependency: D44238: [CFG] Fix automatic destructors when a member 
is bound to a reference..

In code like

  const int  = C().x;

destructors were missing in the CFG, so it was unsafe to inline the 
constructors, so constructor inlining was disabled in 
https://reviews.llvm.org/D43689. But i think i found a way to fix the CFG in 
https://reviews.llvm.org/D44238, so it should be safe to re-enable it now.


Repository:
  rC Clang

https://reviews.llvm.org/D44239

Files:
  include/clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h
  lib/StaticAnalyzer/Core/ExprEngineCXX.cpp
  lib/StaticAnalyzer/Core/ExprEngineCallAndReturn.cpp
  test/Analysis/lifetime-extension.cpp


Index: test/Analysis/lifetime-extension.cpp
===
--- test/Analysis/lifetime-extension.cpp
+++ test/Analysis/lifetime-extension.cpp
@@ -42,10 +42,18 @@
   const int  = A().j[1]; // no-crash
   const int  = (A().j[1], A().j[0]); // no-crash
 
-  // FIXME: All of these should be TRUE, but constructors aren't inlined.
-  clang_analyzer_eval(x == 1); // expected-warning{{UNKNOWN}}
-  clang_analyzer_eval(y == 3); // expected-warning{{UNKNOWN}}
-  clang_analyzer_eval(z == 2); // expected-warning{{UNKNOWN}}
+  clang_analyzer_eval(x == 1);
+  clang_analyzer_eval(y == 3);
+  clang_analyzer_eval(z == 2);
+#ifdef TEMPORARIES
+  // expected-warning@-4{{TRUE}}
+  // expected-warning@-4{{TRUE}}
+  // expected-warning@-4{{TRUE}}
+#else
+  // expected-warning@-8{{UNKNOWN}}
+  // expected-warning@-8{{UNKNOWN}}
+  // expected-warning@-8{{UNKNOWN}}
+#endif
 }
 } // end namespace pr19539_crash_on_destroying_an_integer
 
@@ -140,8 +148,12 @@
   {
 const bool  = C(true, , ).x; // no-crash
   }
-  // FIXME: Should be TRUE. Should not warn about garbage value.
-  clang_analyzer_eval(after == before); // expected-warning{{UNKNOWN}}
+  clang_analyzer_eval(after == before);
+#ifdef TEMPORARIES
+  // expected-warning@-2{{TRUE}}
+#else
+  // expected-warning@-4{{UNKNOWN}}
+#endif
 }
 } // end namespace maintain_original_object_address_on_lifetime_extension
 
Index: lib/StaticAnalyzer/Core/ExprEngineCallAndReturn.cpp
===
--- lib/StaticAnalyzer/Core/ExprEngineCallAndReturn.cpp
+++ lib/StaticAnalyzer/Core/ExprEngineCallAndReturn.cpp
@@ -694,11 +694,6 @@
   // the fake temporary target.
   if (CallOpts.IsCtorOrDtorWithImproperlyModeledTargetRegion)
 return CIP_DisallowedOnce;
-
-  // If the temporary is lifetime-extended by binding a smaller object
-  // within it to a reference, automatic destructors don't work properly.
-  if (CallOpts.IsTemporaryLifetimeExtendedViaSubobject)
-return CIP_DisallowedOnce;
 }
 
 break;
Index: lib/StaticAnalyzer/Core/ExprEngineCXX.cpp
===
--- lib/StaticAnalyzer/Core/ExprEngineCXX.cpp
+++ lib/StaticAnalyzer/Core/ExprEngineCXX.cpp
@@ -179,18 +179,6 @@
   break;
 }
 case ConstructionContext::TemporaryObjectKind: {
-  const auto *TOCC = cast(CC);
-  // See if we're lifetime-extended via our field. If so, take a note.
-  // Because automatic destructors aren't quite working in this case.
-  if (const auto *MTE = TOCC->getMaterializedTemporaryExpr()) {
-if (const ValueDecl *VD = MTE->getExtendingDecl()) {
-  assert(VD->getType()->isReferenceType());
-  if (VD->getType()->getPointeeType().getCanonicalType() !=
-  MTE->GetTemporaryExpr()->getType().getCanonicalType()) {
-CallOpts.IsTemporaryLifetimeExtendedViaSubobject = true;
-  }
-}
-  }
   // TODO: Support temporaries lifetime-extended via static references.
   // They'd need a getCXXStaticTempObjectRegion().
   CallOpts.IsTemporaryCtorOrDtor = true;
Index: include/clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h
===
--- include/clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h
+++ include/clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h
@@ -105,11 +105,6 @@
 /// This call is a constructor or a destructor of a temporary value.
 bool IsTemporaryCtorOrDtor = false;
 
-/// This call is a constructor for a temporary that is lifetime-extended
-/// by binding a smaller object within it to a reference, for example
-/// 'const int  = C().x;'.
-bool IsTemporaryLifetimeExtendedViaSubobject = false;
-
 EvalCallOptions() {}
   };
 


Index: test/Analysis/lifetime-extension.cpp
===
--- test/Analysis/lifetime-extension.cpp
+++ test/Analysis/lifetime-extension.cpp
@@ -42,10 +42,18 @@
   const int  = A().j[1]; // no-crash
   const int  = 

[PATCH] D44238: [CFG] Fix automatic destructors when a member is bound to a reference.

2018-03-07 Thread Artem Dergachev via Phabricator via cfe-commits
NoQ created this revision.
NoQ added reviewers: rsmith, doug.gregor, dcoughlin, xazax.hun, a.sidorin, 
george.karpenkov, szepet.
Herald added subscribers: cfe-commits, rnkovacs.

In code like

  const int  = A().x;

the destructor for `A()` was not present in the CFG due to two problems in the 
pattern-matching in `getReferenceInitTemporaryType()`:

1. The no-op cast from `T` to `const T` is not necessarily performed on a 
record type. It may be performed on essentially any type. In the current 
example, it is performed on an xvalue of type `int` in order to turn it into a 
`const int`.
2. Since https://reviews.llvm.org/rC288563 member access is no longer performed 
over rvalues, but goes after the `MaterializeTemporaryExpr` instead.

**This is not an analyzer-specific change.** It may add/remove compiler 
warnings, but i don't think it makes any sense to hide this behind an 
analyzer-specific flag.


Repository:
  rC Clang

https://reviews.llvm.org/D44238

Files:
  lib/Analysis/CFG.cpp
  test/Analysis/auto-obj-dtors-cfg-output.cpp


Index: test/Analysis/auto-obj-dtors-cfg-output.cpp
===
--- test/Analysis/auto-obj-dtors-cfg-output.cpp
+++ test/Analysis/auto-obj-dtors-cfg-output.cpp
@@ -14,6 +14,8 @@
 
 class A {
 public:
+  int x;
+
 // CHECK:  [B1 (ENTRY)]
 // CHECK-NEXT:   Succs (1): B0
 // CHECK:  [B0 (EXIT)]
@@ -67,6 +69,25 @@
   const A& c = A();
 }
 
+// CHECK:  [B2 (ENTRY)]
+// CHECK-NEXT:   Succs (1): B1
+// CHECK:  [B1]
+// WARNINGS-NEXT:   1: A() (CXXConstructExpr, class A)
+// ANALYZER-NEXT:   1: A() (CXXConstructExpr, [B1.2], [B1.3], class A)
+// CHECK-NEXT:   2: [B1.1] (BindTemporary)
+// CHECK-NEXT:   3: [B1.2]
+// CHECK-NEXT:   4: [B1.3].x
+// CHECK-NEXT:   5: [B1.4] (ImplicitCastExpr, NoOp, const int)
+// CHECK-NEXT:   6: const int  = A().x;
+// CHECK-NEXT:   7: [B1.6].~A() (Implicit destructor)
+// CHECK-NEXT:   Preds (1): B2
+// CHECK-NEXT:   Succs (1): B0
+// CHECK:  [B0 (EXIT)]
+// CHECK-NEXT:   Preds (1): B1
+void test_const_ref_to_field() {
+  const int  = A().x;
+}
+
 // CHECK:  [B2 (ENTRY)]
 // CHECK-NEXT:   Succs (1): B1
 // CHECK:  [B1]
Index: lib/Analysis/CFG.cpp
===
--- lib/Analysis/CFG.cpp
+++ lib/Analysis/CFG.cpp
@@ -1458,16 +1458,15 @@
 if (const CastExpr *CE = dyn_cast(Init)) {
   if ((CE->getCastKind() == CK_DerivedToBase ||
CE->getCastKind() == CK_UncheckedDerivedToBase ||
-   CE->getCastKind() == CK_NoOp) &&
-  Init->getType()->isRecordType()) {
+   CE->getCastKind() == CK_NoOp)) {
 Init = CE->getSubExpr();
 continue;
   }
 }
 
-// Skip member accesses into rvalues.
+// Skip member accesses.
 if (const MemberExpr *ME = dyn_cast(Init)) {
-  if (!ME->isArrow() && ME->getBase()->isRValue()) {
+  if (!ME->isArrow()) {
 Init = ME->getBase();
 continue;
   }
@@ -4873,10 +4872,12 @@
 const VarDecl *VD = DE->getVarDecl();
 Helper.handleDecl(VD, OS);
 
-const Type* T = VD->getType().getTypePtr();
-if (const ReferenceType* RT = T->getAs())
-  T = RT->getPointeeType().getTypePtr();
-T = T->getBaseElementTypeUnsafe();
+ASTContext  = VD->getASTContext();
+QualType T = VD->getType();
+if (T->isReferenceType())
+  T = getReferenceInitTemporaryType(ACtx, VD->getInit(), nullptr);
+if (const ArrayType *AT = ACtx.getAsArrayType(T))
+  T = ACtx.getBaseElementType(AT);
 
 OS << ".~" << T->getAsCXXRecordDecl()->getName().str() << "()";
 OS << " (Implicit destructor)\n";


Index: test/Analysis/auto-obj-dtors-cfg-output.cpp
===
--- test/Analysis/auto-obj-dtors-cfg-output.cpp
+++ test/Analysis/auto-obj-dtors-cfg-output.cpp
@@ -14,6 +14,8 @@
 
 class A {
 public:
+  int x;
+
 // CHECK:  [B1 (ENTRY)]
 // CHECK-NEXT:   Succs (1): B0
 // CHECK:  [B0 (EXIT)]
@@ -67,6 +69,25 @@
   const A& c = A();
 }
 
+// CHECK:  [B2 (ENTRY)]
+// CHECK-NEXT:   Succs (1): B1
+// CHECK:  [B1]
+// WARNINGS-NEXT:   1: A() (CXXConstructExpr, class A)
+// ANALYZER-NEXT:   1: A() (CXXConstructExpr, [B1.2], [B1.3], class A)
+// CHECK-NEXT:   2: [B1.1] (BindTemporary)
+// CHECK-NEXT:   3: [B1.2]
+// CHECK-NEXT:   4: [B1.3].x
+// CHECK-NEXT:   5: [B1.4] (ImplicitCastExpr, NoOp, const int)
+// CHECK-NEXT:   6: const int  = A().x;
+// CHECK-NEXT:   7: [B1.6].~A() (Implicit destructor)
+// CHECK-NEXT:   Preds (1): B2
+// CHECK-NEXT:   Succs (1): B0
+// CHECK:  [B0 (EXIT)]
+// CHECK-NEXT:   Preds (1): B1
+void test_const_ref_to_field() {
+  const int  = A().x;
+}
+
 // CHECK:  [B2 (ENTRY)]
 // CHECK-NEXT:   Succs (1): B1
 // CHECK:  [B1]
Index: lib/Analysis/CFG.cpp
===
--- lib/Analysis/CFG.cpp
+++ lib/Analysis/CFG.cpp
@@ -1458,16 +1458,15 @@
 if (const 

[PATCH] D16632: clang-cl: Take dllexport from original function decl into account

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

lgtm


https://reviews.llvm.org/D16632



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


r326974 - Revert "[Sema] Make getCurFunction() return null outside function parsing"

2018-03-07 Thread Reid Kleckner via cfe-commits
Author: rnk
Date: Wed Mar  7 17:12:22 2018
New Revision: 326974

URL: http://llvm.org/viewvc/llvm-project?rev=326974=rev
Log:
Revert "[Sema] Make getCurFunction() return null outside function parsing"

This reverts r326965. It seems to have caused repeating test failures in
clang/test/Sema/diagnose_if.c on some buildbots.

I cannot reproduce the problem, and it's not immediately obvious what
the problem is, so let's revert to green.

Modified:
cfe/trunk/include/clang/Sema/Sema.h
cfe/trunk/lib/Sema/AnalysisBasedWarnings.cpp
cfe/trunk/lib/Sema/Sema.cpp
cfe/trunk/lib/Sema/SemaDecl.cpp
cfe/trunk/lib/Sema/SemaExpr.cpp
cfe/trunk/lib/Sema/SemaExprCXX.cpp
cfe/trunk/lib/Sema/SemaOpenMP.cpp
cfe/trunk/lib/Sema/SemaStmt.cpp
cfe/trunk/lib/Sema/SemaStmtAsm.cpp

Modified: cfe/trunk/include/clang/Sema/Sema.h
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Sema/Sema.h?rev=326974=326973=326974=diff
==
--- cfe/trunk/include/clang/Sema/Sema.h (original)
+++ cfe/trunk/include/clang/Sema/Sema.h Wed Mar  7 17:12:22 2018
@@ -528,10 +528,12 @@ public:
   ///  full expression.
   llvm::SmallPtrSet MaybeODRUseExprs;
 
-  std::unique_ptr PreallocatedFunctionScope;
-
   /// \brief Stack containing information about each of the nested
   /// function, block, and method scopes that are currently active.
+  ///
+  /// This array is never empty.  Clients should ignore the first
+  /// element, which is used to cache a single FunctionScopeInfo
+  /// that's used to parse every top-level function.
   SmallVector FunctionScopes;
 
   typedef LazyVectorhttp://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Sema/AnalysisBasedWarnings.cpp?rev=326974=326973=326974=diff
==
--- cfe/trunk/lib/Sema/AnalysisBasedWarnings.cpp (original)
+++ cfe/trunk/lib/Sema/AnalysisBasedWarnings.cpp Wed Mar  7 17:12:22 2018
@@ -632,19 +632,18 @@ struct CheckFallThroughDiagnostics {
 
 } // anonymous namespace
 
-/// CheckFallThroughForBody - Check that we don't fall off the end of a
+/// CheckFallThroughForFunctionDef - Check that we don't fall off the end of a
 /// function that should return a value.  Check that we don't fall off the end
 /// of a noreturn function.  We assume that functions and blocks not marked
 /// noreturn will return.
 static void CheckFallThroughForBody(Sema , const Decl *D, const Stmt *Body,
 const BlockExpr *blkExpr,
-const CheckFallThroughDiagnostics ,
-AnalysisDeclContext ,
-sema::FunctionScopeInfo *FSI) {
+const CheckFallThroughDiagnostics& CD,
+AnalysisDeclContext ) {
 
   bool ReturnsVoid = false;
   bool HasNoReturn = false;
-  bool IsCoroutine = FSI->isCoroutine();
+  bool IsCoroutine = S.getCurFunction() && S.getCurFunction()->isCoroutine();
 
   if (const auto *FD = dyn_cast(D)) {
 if (const auto *CBody = dyn_cast(Body))
@@ -676,7 +675,7 @@ static void CheckFallThroughForBody(Sema
   SourceLocation LBrace = Body->getLocStart(), RBrace = Body->getLocEnd();
   auto EmitDiag = [&](SourceLocation Loc, unsigned DiagID) {
 if (IsCoroutine)
-  S.Diag(Loc, DiagID) << FSI->CoroutinePromise->getType();
+  S.Diag(Loc, DiagID) << S.getCurFunction()->CoroutinePromise->getType();
 else
   S.Diag(Loc, DiagID);
   };
@@ -2144,7 +2143,7 @@ AnalysisBasedWarnings::IssueWarnings(sem
: (fscope->isCoroutine()
   ? CheckFallThroughDiagnostics::MakeForCoroutine(D)
   : CheckFallThroughDiagnostics::MakeForFunction(D)));
-CheckFallThroughForBody(S, D, Body, blkExpr, CD, AC, fscope);
+CheckFallThroughForBody(S, D, Body, blkExpr, CD, AC);
   }
 
   // Warning: check for unreachable code

Modified: cfe/trunk/lib/Sema/Sema.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Sema/Sema.cpp?rev=326974=326973=326974=diff
==
--- cfe/trunk/lib/Sema/Sema.cpp (original)
+++ cfe/trunk/lib/Sema/Sema.cpp Wed Mar  7 17:12:22 2018
@@ -162,7 +162,7 @@ Sema::Sema(Preprocessor , ASTContext
   ExpressionEvaluationContext::PotentiallyEvaluated, 0, CleanupInfo{},
   nullptr, false);
 
-  PreallocatedFunctionScope.reset(new FunctionScopeInfo(Diags));
+  FunctionScopes.push_back(new FunctionScopeInfo(Diags));
 
   // Initilization of data sharing attributes stack for OpenMP
   InitDataSharingAttributesStack();
@@ -332,11 +332,11 @@ void Sema::Initialize() {
 
 Sema::~Sema() {
   if (VisContext) FreeVisContext();
-
   // Kill all the active scopes.
-  for (sema::FunctionScopeInfo *FSI : FunctionScopes)
-if (FSI != PreallocatedFunctionScope.get())
-  delete FSI;
+  

r326973 - When substituting previously-checked template arguments into a template

2018-03-07 Thread Richard Smith via cfe-commits
Author: rsmith
Date: Wed Mar  7 17:07:33 2018
New Revision: 326973

URL: http://llvm.org/viewvc/llvm-project?rev=326973=rev
Log:
When substituting previously-checked template arguments into a template
template parameter that is an expanded parameter pack, only substitute into the
current slice, not the entire pack.

This reduces the checking of N template template arguments for an expanded
parameter pack containing N parameters from quadratic time to linear time in
the length of the pack. This is important because one (and possibly the only?)
general technique for splitting a template parameter pack in linear time
depends on doing this.

Added:
cfe/trunk/test/SemaTemplate/temp-param-subst-linear.cpp
Modified:
cfe/trunk/include/clang/Sema/Sema.h
cfe/trunk/lib/Sema/SemaTemplate.cpp
cfe/trunk/lib/Sema/SemaTemplateInstantiateDecl.cpp
cfe/trunk/test/CXX/drs/dr10xx.cpp

Modified: cfe/trunk/include/clang/Sema/Sema.h
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Sema/Sema.h?rev=326973=326972=326973=diff
==
--- cfe/trunk/include/clang/Sema/Sema.h (original)
+++ cfe/trunk/include/clang/Sema/Sema.h Wed Mar  7 17:07:33 2018
@@ -6362,9 +6362,8 @@ public:
QualType InstantiatedParamType, Expr *Arg,
TemplateArgument ,
CheckTemplateArgumentKind CTAK = 
CTAK_Specified);
-  bool CheckTemplateArgument(TemplateTemplateParmDecl *Param,
- TemplateArgumentLoc ,
- unsigned ArgumentPackIndex);
+  bool CheckTemplateTemplateArgument(TemplateParameterList *Params,
+ TemplateArgumentLoc );
 
   ExprResult
   BuildExpressionFromDeclTemplateArgument(const TemplateArgument ,
@@ -7700,6 +7699,10 @@ public:
   StmtResult SubstStmt(Stmt *S,
const MultiLevelTemplateArgumentList );
 
+  TemplateParameterList *
+  SubstTemplateParams(TemplateParameterList *Params, DeclContext *Owner,
+  const MultiLevelTemplateArgumentList );
+
   Decl *SubstDecl(Decl *D, DeclContext *Owner,
   const MultiLevelTemplateArgumentList );
 

Modified: cfe/trunk/lib/Sema/SemaTemplate.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Sema/SemaTemplate.cpp?rev=326973=326972=326973=diff
==
--- cfe/trunk/lib/Sema/SemaTemplate.cpp (original)
+++ cfe/trunk/lib/Sema/SemaTemplate.cpp Wed Mar  7 17:07:33 2018
@@ -4617,6 +4617,8 @@ bool Sema::CheckTemplateArgument(NamedDe
 if (NTTP->isParameterPack() && NTTP->isExpandedParameterPack())
   NTTPType = NTTP->getExpansionType(ArgumentPackIndex);
 
+// FIXME: Do we need to substitute into parameters here if they're
+// instantiation-dependent but not dependent?
 if (NTTPType->isDependentType() &&
 !isa(Template) &&
 !Template->getDeclContext()->isDependentContext()) {
@@ -4756,9 +4758,15 @@ bool Sema::CheckTemplateArgument(NamedDe
   // Check template template parameters.
   TemplateTemplateParmDecl *TempParm = cast(Param);
 
+  TemplateParameterList *Params = TempParm->getTemplateParameters();
+  if (TempParm->isExpandedParameterPack())
+Params = TempParm->getExpansionTemplateParameters(ArgumentPackIndex);
+
   // Substitute into the template parameter list of the template
   // template parameter, since previously-supplied template arguments
   // may appear within the template template parameter.
+  //
+  // FIXME: Skip this if the parameters aren't instantiation-dependent.
   {
 // Set up a template instantiation context.
 LocalInstantiationScope Scope(*this);
@@ -4769,10 +4777,9 @@ bool Sema::CheckTemplateArgument(NamedDe
   return true;
 
 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack, 
Converted);
-TempParm = cast_or_null(
-  SubstDecl(TempParm, CurContext,
-MultiLevelTemplateArgumentList(TemplateArgs)));
-if (!TempParm)
+Params = SubstTemplateParams(Params, CurContext,
+ MultiLevelTemplateArgumentList(TemplateArgs));
+if (!Params)
   return true;
   }
 
@@ -4793,7 +4800,7 @@ bool Sema::CheckTemplateArgument(NamedDe
 
   case TemplateArgument::Template:
   case TemplateArgument::TemplateExpansion:
-if (CheckTemplateArgument(TempParm, Arg, ArgumentPackIndex))
+if (CheckTemplateTemplateArgument(Params, Arg))
   return true;
 
 Converted.push_back(Arg.getArgument());
@@ -6536,9 +6543,8 @@ static void DiagnoseTemplateParameterLis
 ///
 /// This routine implements the semantics of C++ [temp.arg.template].
 /// It returns true if an error occurred, and false otherwise.
-bool Sema::CheckTemplateArgument(TemplateTemplateParmDecl *Param,
- TemplateArgumentLoc ,

r326971 - [MS] Pass CVRU qualifiers properly in Itanium mangler

2018-03-07 Thread Reid Kleckner via cfe-commits
Author: rnk
Date: Wed Mar  7 16:55:09 2018
New Revision: 326971

URL: http://llvm.org/viewvc/llvm-project?rev=326971=rev
Log:
[MS] Pass CVRU qualifiers properly in Itanium mangler

We already have a mangling for the __unaligned qualifier, we just have
to call Qualifiers::getFromCVRUMask instead of getFromCVRMask.

PR36638

Modified:
cfe/trunk/lib/AST/ItaniumMangle.cpp
cfe/trunk/test/CodeGenCXX/pr33080.cpp

Modified: cfe/trunk/lib/AST/ItaniumMangle.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/AST/ItaniumMangle.cpp?rev=326971=326970=326971=diff
==
--- cfe/trunk/lib/AST/ItaniumMangle.cpp (original)
+++ cfe/trunk/lib/AST/ItaniumMangle.cpp Wed Mar  7 16:55:09 2018
@@ -2688,7 +2688,7 @@ void CXXNameMangler::mangleType(const Fu
 
   // Mangle CV-qualifiers, if present.  These are 'this' qualifiers,
   // e.g. "const" in "int (A::*)() const".
-  mangleQualifiers(Qualifiers::fromCVRMask(T->getTypeQuals()));
+  mangleQualifiers(Qualifiers::fromCVRUMask(T->getTypeQuals()));
 
   // Mangle instantiation-dependent exception-specification, if present,
   // per cxx-abi-dev proposal on 2016-10-11.

Modified: cfe/trunk/test/CodeGenCXX/pr33080.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/CodeGenCXX/pr33080.cpp?rev=326971=326970=326971=diff
==
--- cfe/trunk/test/CodeGenCXX/pr33080.cpp (original)
+++ cfe/trunk/test/CodeGenCXX/pr33080.cpp Wed Mar  7 16:55:09 2018
@@ -21,6 +21,10 @@ void hb(__unaligned struct A *, __unalig
 void ja(__unaligned struct A *, __unaligned struct A *__unaligned *, 
__unaligned struct A *__unaligned *__unaligned *) {}
 // CHECK: define {{(dso_local )?}}void 
@_Z2jaPU11__unaligned1APU11__unalignedS1_PU11__unalignedS3_(
 
+struct A;
+void memptr(void (A::*a)(int) __unaligned) {}
+// CHECK: define {{.*}} @_Z6memptrM1AU11__unalignedFviE(
+
 void jb(__unaligned struct A *, __unaligned struct A **, __unaligned struct A 
*__unaligned *__unaligned *) {}
 // CHECK: @_Z2jbPU11__unaligned1APS1_PU11__unalignedPU11__unalignedS1_(
 


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


r326968 - Fix a doc typo; NFC

2018-03-07 Thread George Burgess IV via cfe-commits
Author: gbiv
Date: Wed Mar  7 16:22:04 2018
New Revision: 326968

URL: http://llvm.org/viewvc/llvm-project?rev=326968=rev
Log:
Fix a doc typo; NFC

Modified:
cfe/trunk/lib/CodeGen/CGExpr.cpp

Modified: cfe/trunk/lib/CodeGen/CGExpr.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/CodeGen/CGExpr.cpp?rev=326968=326967=326968=diff
==
--- cfe/trunk/lib/CodeGen/CGExpr.cpp (original)
+++ cfe/trunk/lib/CodeGen/CGExpr.cpp Wed Mar  7 16:22:04 2018
@@ -187,7 +187,7 @@ RValue CodeGenFunction::EmitAnyExpr(cons
   llvm_unreachable("bad evaluation kind");
 }
 
-/// EmitAnyExprToTemp - Similary to EmitAnyExpr(), however, the result will
+/// EmitAnyExprToTemp - Similar to EmitAnyExpr(), however, the result will
 /// always be accessible even if no aggregate location is provided.
 RValue CodeGenFunction::EmitAnyExprToTemp(const Expr *E) {
   AggValueSlot AggSlot = AggValueSlot::ignored();


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


[PATCH] D44039: [Sema] Make getCurFunction() return null outside function parsing

2018-03-07 Thread Reid Kleckner via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rL326965: [Sema] Make getCurFunction() return null outside 
function parsing (authored by rnk, committed by ).
Herald added a subscriber: llvm-commits.

Changed prior to commit:
  https://reviews.llvm.org/D44039?vs=137472=137507#toc

Repository:
  rL LLVM

https://reviews.llvm.org/D44039

Files:
  cfe/trunk/include/clang/Sema/Sema.h
  cfe/trunk/lib/Sema/AnalysisBasedWarnings.cpp
  cfe/trunk/lib/Sema/Sema.cpp
  cfe/trunk/lib/Sema/SemaDecl.cpp
  cfe/trunk/lib/Sema/SemaExpr.cpp
  cfe/trunk/lib/Sema/SemaExprCXX.cpp
  cfe/trunk/lib/Sema/SemaOpenMP.cpp
  cfe/trunk/lib/Sema/SemaStmt.cpp
  cfe/trunk/lib/Sema/SemaStmtAsm.cpp

Index: cfe/trunk/lib/Sema/Sema.cpp
===
--- cfe/trunk/lib/Sema/Sema.cpp
+++ cfe/trunk/lib/Sema/Sema.cpp
@@ -162,7 +162,7 @@
   ExpressionEvaluationContext::PotentiallyEvaluated, 0, CleanupInfo{},
   nullptr, false);
 
-  FunctionScopes.push_back(new FunctionScopeInfo(Diags));
+  PreallocatedFunctionScope.reset(new FunctionScopeInfo(Diags));
 
   // Initilization of data sharing attributes stack for OpenMP
   InitDataSharingAttributesStack();
@@ -332,11 +332,11 @@
 
 Sema::~Sema() {
   if (VisContext) FreeVisContext();
+
   // Kill all the active scopes.
-  for (unsigned I = 1, E = FunctionScopes.size(); I != E; ++I)
-delete FunctionScopes[I];
-  if (FunctionScopes.size() == 1)
-delete FunctionScopes[0];
+  for (sema::FunctionScopeInfo *FSI : FunctionScopes)
+if (FSI != PreallocatedFunctionScope.get())
+  delete FSI;
 
   // Tell the SemaConsumer to forget about us; we're going out of scope.
   if (SemaConsumer *SC = dyn_cast())
@@ -1340,17 +1340,13 @@
 
 /// \brief Enter a new function scope
 void Sema::PushFunctionScope() {
-  if (FunctionScopes.size() == 1) {
-// Use the "top" function scope rather than having to allocate
-// memory for a new scope.
-FunctionScopes.back()->Clear();
-FunctionScopes.push_back(FunctionScopes.back());
-if (LangOpts.OpenMP)
-  pushOpenMPFunctionRegion();
-return;
+  if (FunctionScopes.empty()) {
+// Use PreallocatedFunctionScope to avoid allocating memory when possible.
+PreallocatedFunctionScope->Clear();
+FunctionScopes.push_back(PreallocatedFunctionScope.get());
+  } else {
+FunctionScopes.push_back(new FunctionScopeInfo(getDiagnostics()));
   }
-
-  FunctionScopes.push_back(new FunctionScopeInfo(getDiagnostics()));
   if (LangOpts.OpenMP)
 pushOpenMPFunctionRegion();
 }
@@ -1370,15 +1366,15 @@
   if (LambdaScopeInfo *const LSI = getCurLambda()) {
 LSI->AutoTemplateParameterDepth = Depth;
 return;
-  } 
-  llvm_unreachable( 
+  }
+  llvm_unreachable(
   "Remove assertion if intentionally called in a non-lambda context.");
 }
 
 void Sema::PopFunctionScopeInfo(const AnalysisBasedWarnings::Policy *WP,
 const Decl *D, const BlockExpr *blkExpr) {
-  FunctionScopeInfo *Scope = FunctionScopes.pop_back_val();
   assert(!FunctionScopes.empty() && "mismatched push/pop!");
+  FunctionScopeInfo *Scope = FunctionScopes.pop_back_val();
 
   if (LangOpts.OpenMP)
 popOpenMPFunctionRegion(Scope);
@@ -1390,7 +1386,8 @@
 for (const auto  : Scope->PossiblyUnreachableDiags)
   Diag(PUD.Loc, PUD.PD);
 
-  if (FunctionScopes.back() != Scope)
+  // Delete the scope unless its our preallocated scope.
+  if (Scope != PreallocatedFunctionScope.get())
 delete Scope;
 }
 
@@ -1411,6 +1408,21 @@
   return getCurFunction()->ErrorTrap.hasUnrecoverableErrorOccurred();
 }
 
+void Sema::setFunctionHasBranchIntoScope() {
+  if (!FunctionScopes.empty())
+FunctionScopes.back()->setHasBranchIntoScope();
+}
+
+void Sema::setFunctionHasBranchProtectedScope() {
+  if (!FunctionScopes.empty())
+FunctionScopes.back()->setHasBranchProtectedScope();
+}
+
+void Sema::setFunctionHasIndirectGoto() {
+  if (!FunctionScopes.empty())
+FunctionScopes.back()->setHasIndirectGoto();
+}
+
 BlockScopeInfo *Sema::getCurBlock() {
   if (FunctionScopes.empty())
 return nullptr;
Index: cfe/trunk/lib/Sema/SemaExpr.cpp
===
--- cfe/trunk/lib/Sema/SemaExpr.cpp
+++ cfe/trunk/lib/Sema/SemaExpr.cpp
@@ -13126,7 +13126,7 @@
 for (const auto  : Result->getBlockDecl()->captures()) {
   const VarDecl *var = CI.getVariable();
   if (var->getType().isDestructedType() != QualType::DK_none) {
-getCurFunction()->setHasBranchProtectedScope();
+setFunctionHasBranchProtectedScope();
 break;
   }
 }
Index: cfe/trunk/lib/Sema/SemaStmtAsm.cpp
===
--- cfe/trunk/lib/Sema/SemaStmtAsm.cpp
+++ cfe/trunk/lib/Sema/SemaStmtAsm.cpp
@@ -793,7 +793,7 @@
 ArrayRef Exprs,
 SourceLocation EndLoc) {
   bool IsSimple = 

[PATCH] D44039: [Sema] Make getCurFunction() return null outside function parsing

2018-03-07 Thread Reid Kleckner via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rC326965: [Sema] Make getCurFunction() return null outside 
function parsing (authored by rnk, committed by ).

Changed prior to commit:
  https://reviews.llvm.org/D44039?vs=137472=137506#toc

Repository:
  rC Clang

https://reviews.llvm.org/D44039

Files:
  include/clang/Sema/Sema.h
  lib/Sema/AnalysisBasedWarnings.cpp
  lib/Sema/Sema.cpp
  lib/Sema/SemaDecl.cpp
  lib/Sema/SemaExpr.cpp
  lib/Sema/SemaExprCXX.cpp
  lib/Sema/SemaOpenMP.cpp
  lib/Sema/SemaStmt.cpp
  lib/Sema/SemaStmtAsm.cpp

Index: include/clang/Sema/Sema.h
===
--- include/clang/Sema/Sema.h
+++ include/clang/Sema/Sema.h
@@ -528,12 +528,10 @@
   ///  full expression.
   llvm::SmallPtrSet MaybeODRUseExprs;
 
+  std::unique_ptr PreallocatedFunctionScope;
+
   /// \brief Stack containing information about each of the nested
   /// function, block, and method scopes that are currently active.
-  ///
-  /// This array is never empty.  Clients should ignore the first
-  /// element, which is used to cache a single FunctionScopeInfo
-  /// that's used to parse every top-level function.
   SmallVector FunctionScopes;
 
   typedef LazyVector())
@@ -1340,17 +1340,13 @@
 
 /// \brief Enter a new function scope
 void Sema::PushFunctionScope() {
-  if (FunctionScopes.size() == 1) {
-// Use the "top" function scope rather than having to allocate
-// memory for a new scope.
-FunctionScopes.back()->Clear();
-FunctionScopes.push_back(FunctionScopes.back());
-if (LangOpts.OpenMP)
-  pushOpenMPFunctionRegion();
-return;
+  if (FunctionScopes.empty()) {
+// Use PreallocatedFunctionScope to avoid allocating memory when possible.
+PreallocatedFunctionScope->Clear();
+FunctionScopes.push_back(PreallocatedFunctionScope.get());
+  } else {
+FunctionScopes.push_back(new FunctionScopeInfo(getDiagnostics()));
   }
-
-  FunctionScopes.push_back(new FunctionScopeInfo(getDiagnostics()));
   if (LangOpts.OpenMP)
 pushOpenMPFunctionRegion();
 }
@@ -1370,15 +1366,15 @@
   if (LambdaScopeInfo *const LSI = getCurLambda()) {
 LSI->AutoTemplateParameterDepth = Depth;
 return;
-  } 
-  llvm_unreachable( 
+  }
+  llvm_unreachable(
   "Remove assertion if intentionally called in a non-lambda context.");
 }
 
 void Sema::PopFunctionScopeInfo(const AnalysisBasedWarnings::Policy *WP,
 const Decl *D, const BlockExpr *blkExpr) {
-  FunctionScopeInfo *Scope = FunctionScopes.pop_back_val();
   assert(!FunctionScopes.empty() && "mismatched push/pop!");
+  FunctionScopeInfo *Scope = FunctionScopes.pop_back_val();
 
   if (LangOpts.OpenMP)
 popOpenMPFunctionRegion(Scope);
@@ -1390,7 +1386,8 @@
 for (const auto  : Scope->PossiblyUnreachableDiags)
   Diag(PUD.Loc, PUD.PD);
 
-  if (FunctionScopes.back() != Scope)
+  // Delete the scope unless its our preallocated scope.
+  if (Scope != PreallocatedFunctionScope.get())
 delete Scope;
 }
 
@@ -1411,6 +1408,21 @@
   return getCurFunction()->ErrorTrap.hasUnrecoverableErrorOccurred();
 }
 
+void Sema::setFunctionHasBranchIntoScope() {
+  if (!FunctionScopes.empty())
+FunctionScopes.back()->setHasBranchIntoScope();
+}
+
+void Sema::setFunctionHasBranchProtectedScope() {
+  if (!FunctionScopes.empty())
+FunctionScopes.back()->setHasBranchProtectedScope();
+}
+
+void Sema::setFunctionHasIndirectGoto() {
+  if (!FunctionScopes.empty())
+FunctionScopes.back()->setHasIndirectGoto();
+}
+
 BlockScopeInfo *Sema::getCurBlock() {
   if (FunctionScopes.empty())
 return nullptr;
Index: lib/Sema/SemaExpr.cpp
===
--- lib/Sema/SemaExpr.cpp
+++ lib/Sema/SemaExpr.cpp
@@ -13126,7 +13126,7 @@
 for (const auto  : Result->getBlockDecl()->captures()) {
   const VarDecl *var = CI.getVariable();
   if (var->getType().isDestructedType() != QualType::DK_none) {
-getCurFunction()->setHasBranchProtectedScope();
+setFunctionHasBranchProtectedScope();
 break;
   }
 }
Index: lib/Sema/SemaStmtAsm.cpp
===
--- lib/Sema/SemaStmtAsm.cpp
+++ lib/Sema/SemaStmtAsm.cpp
@@ -793,7 +793,7 @@
 ArrayRef Exprs,
 SourceLocation EndLoc) {
   bool IsSimple = (NumOutputs != 0 || NumInputs != 0);
-  getCurFunction()->setHasBranchProtectedScope();
+  setFunctionHasBranchProtectedScope();
   MSAsmStmt *NS =
 new (Context) MSAsmStmt(Context, AsmLoc, LBraceLoc, IsSimple,
 /*IsVolatile*/ true, AsmToks, NumOutputs, NumInputs,
Index: lib/Sema/SemaStmt.cpp
===
--- lib/Sema/SemaStmt.cpp
+++ lib/Sema/SemaStmt.cpp
@@ -557,7 +557,7 @@
 return StmtError();
 
   if (IsConstexpr || 

r326965 - [Sema] Make getCurFunction() return null outside function parsing

2018-03-07 Thread Reid Kleckner via cfe-commits
Author: rnk
Date: Wed Mar  7 16:14:34 2018
New Revision: 326965

URL: http://llvm.org/viewvc/llvm-project?rev=326965=rev
Log:
[Sema] Make getCurFunction() return null outside function parsing

Summary:
Before this patch, Sema pre-allocated a FunctionScopeInfo and kept it in
the first, always present element of the FunctionScopes stack. This
meant that Sema::getCurFunction would return a pointer to this
pre-allocated object when parsing code outside a function body. This is
pretty much always a bug, so this patch moves the pre-allocated object
into a separate unique_ptr. This should make bugs like PR36536 a lot
more obvious.

As you can see from this patch, there were a number of places that
unconditionally assumed they were always called inside a function.
However, there are also many places that null checked the result of
getCurFunction(), so I think this is a reasonable direction.

Reviewers: rsmith

Subscribers: cfe-commits

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

Modified:
cfe/trunk/include/clang/Sema/Sema.h
cfe/trunk/lib/Sema/AnalysisBasedWarnings.cpp
cfe/trunk/lib/Sema/Sema.cpp
cfe/trunk/lib/Sema/SemaDecl.cpp
cfe/trunk/lib/Sema/SemaExpr.cpp
cfe/trunk/lib/Sema/SemaExprCXX.cpp
cfe/trunk/lib/Sema/SemaOpenMP.cpp
cfe/trunk/lib/Sema/SemaStmt.cpp
cfe/trunk/lib/Sema/SemaStmtAsm.cpp

Modified: cfe/trunk/include/clang/Sema/Sema.h
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Sema/Sema.h?rev=326965=326964=326965=diff
==
--- cfe/trunk/include/clang/Sema/Sema.h (original)
+++ cfe/trunk/include/clang/Sema/Sema.h Wed Mar  7 16:14:34 2018
@@ -528,12 +528,10 @@ public:
   ///  full expression.
   llvm::SmallPtrSet MaybeODRUseExprs;
 
+  std::unique_ptr PreallocatedFunctionScope;
+
   /// \brief Stack containing information about each of the nested
   /// function, block, and method scopes that are currently active.
-  ///
-  /// This array is never empty.  Clients should ignore the first
-  /// element, which is used to cache a single FunctionScopeInfo
-  /// that's used to parse every top-level function.
   SmallVector FunctionScopes;
 
   typedef LazyVectorhttp://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Sema/AnalysisBasedWarnings.cpp?rev=326965=326964=326965=diff
==
--- cfe/trunk/lib/Sema/AnalysisBasedWarnings.cpp (original)
+++ cfe/trunk/lib/Sema/AnalysisBasedWarnings.cpp Wed Mar  7 16:14:34 2018
@@ -632,18 +632,19 @@ struct CheckFallThroughDiagnostics {
 
 } // anonymous namespace
 
-/// CheckFallThroughForFunctionDef - Check that we don't fall off the end of a
+/// CheckFallThroughForBody - Check that we don't fall off the end of a
 /// function that should return a value.  Check that we don't fall off the end
 /// of a noreturn function.  We assume that functions and blocks not marked
 /// noreturn will return.
 static void CheckFallThroughForBody(Sema , const Decl *D, const Stmt *Body,
 const BlockExpr *blkExpr,
-const CheckFallThroughDiagnostics& CD,
-AnalysisDeclContext ) {
+const CheckFallThroughDiagnostics ,
+AnalysisDeclContext ,
+sema::FunctionScopeInfo *FSI) {
 
   bool ReturnsVoid = false;
   bool HasNoReturn = false;
-  bool IsCoroutine = S.getCurFunction() && S.getCurFunction()->isCoroutine();
+  bool IsCoroutine = FSI->isCoroutine();
 
   if (const auto *FD = dyn_cast(D)) {
 if (const auto *CBody = dyn_cast(Body))
@@ -675,7 +676,7 @@ static void CheckFallThroughForBody(Sema
   SourceLocation LBrace = Body->getLocStart(), RBrace = Body->getLocEnd();
   auto EmitDiag = [&](SourceLocation Loc, unsigned DiagID) {
 if (IsCoroutine)
-  S.Diag(Loc, DiagID) << S.getCurFunction()->CoroutinePromise->getType();
+  S.Diag(Loc, DiagID) << FSI->CoroutinePromise->getType();
 else
   S.Diag(Loc, DiagID);
   };
@@ -2143,7 +2144,7 @@ AnalysisBasedWarnings::IssueWarnings(sem
: (fscope->isCoroutine()
   ? CheckFallThroughDiagnostics::MakeForCoroutine(D)
   : CheckFallThroughDiagnostics::MakeForFunction(D)));
-CheckFallThroughForBody(S, D, Body, blkExpr, CD, AC);
+CheckFallThroughForBody(S, D, Body, blkExpr, CD, AC, fscope);
   }
 
   // Warning: check for unreachable code

Modified: cfe/trunk/lib/Sema/Sema.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Sema/Sema.cpp?rev=326965=326964=326965=diff
==
--- cfe/trunk/lib/Sema/Sema.cpp (original)
+++ cfe/trunk/lib/Sema/Sema.cpp Wed Mar  7 16:14:34 2018
@@ -162,7 +162,7 @@ Sema::Sema(Preprocessor , ASTContext
   

[PATCH] D44229: Don't use -pie in relocatable link.

2018-03-07 Thread Evgenii Stepanov via Phabricator via cfe-commits
eugenis added inline comments.



Comment at: clang/lib/Driver/ToolChains/Gnu.cpp:311
+  if (Args.hasArg(options::OPT_shared) || Args.hasArg(options::OPT_static) ||
+  Args.hasArg(options::OPT_r))
 return false;

mgrang wrote:
> We also need to check for -Wl,-r and -Xlinker -r options.
I don't think it is driver's job to parse -Wl or -Xlinker arguments.
There is always -no-pie.



https://reviews.llvm.org/D44229



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


[PATCH] D44233: Set dso_local on external rtti GVs

2018-03-07 Thread Rafael Avila de Espindola via Phabricator via cfe-commits
espindola created this revision.
espindola added a reviewer: rnk.

In this particular case it would be possible to just add an else with 
CGM.setDSOLocal(GV),  but it seems better to have as many callers as possible 
just call setGVProperties so that we can centralize the logic there.

This patch then makes setGVProperties able to handle null Decls.


https://reviews.llvm.org/D44233

Files:
  lib/CodeGen/CodeGenModule.cpp
  lib/CodeGen/ItaniumCXXABI.cpp
  test/CodeGenCXX/windows-itanium-exceptions.cpp


Index: test/CodeGenCXX/windows-itanium-exceptions.cpp
===
--- test/CodeGenCXX/windows-itanium-exceptions.cpp
+++ test/CodeGenCXX/windows-itanium-exceptions.cpp
@@ -10,7 +10,7 @@
   try { except(); } catch (...) { }
 }
 
-// CHECK: @_ZTIi = external constant i8*
+// CHECK: @_ZTIi = external dso_local constant i8*
 
 // CHECK: define {{.*}}void @_Z6exceptv() {{.*}} {
 // CHECK:   %exception = call {{.*}}i8* @__cxa_allocate_exception(i32 4)
Index: lib/CodeGen/ItaniumCXXABI.cpp
===
--- lib/CodeGen/ItaniumCXXABI.cpp
+++ lib/CodeGen/ItaniumCXXABI.cpp
@@ -2615,10 +2615,10 @@
   /*Constant=*/true,
   llvm::GlobalValue::ExternalLinkage, nullptr,
   Name);
-if (const RecordType *RecordTy = dyn_cast(Ty)) {
-  const CXXRecordDecl *RD = cast(RecordTy->getDecl());
-  CGM.setGVProperties(GV, RD);
-}
+const CXXRecordDecl *RD = nullptr;
+if (const auto *RecordTy = dyn_cast(Ty))
+  RD = cast(RecordTy->getDecl());
+CGM.setGVProperties(GV, RD);
   }
 
   return llvm::ConstantExpr::getBitCast(GV, CGM.Int8PtrTy);
Index: lib/CodeGen/CodeGenModule.cpp
===
--- lib/CodeGen/CodeGenModule.cpp
+++ lib/CodeGen/CodeGenModule.cpp
@@ -707,7 +707,8 @@
 GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
 return;
   }
-
+  if (!D)
+return;
   // Set visibility for definitions.
   LinkageInfo LV = D->getLinkageAndVisibility();
   if (LV.isVisibilityExplicit() || !GV->isDeclarationForLinker())
@@ -797,7 +798,7 @@
 
 void CodeGenModule::setDLLImportDLLExport(llvm::GlobalValue *GV,
   const NamedDecl *D) const {
-  if (D->isExternallyVisible()) {
+  if (D && D->isExternallyVisible()) {
 if (D->hasAttr())
   GV->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass);
 else if (D->hasAttr() && !GV->isDeclarationForLinker())


Index: test/CodeGenCXX/windows-itanium-exceptions.cpp
===
--- test/CodeGenCXX/windows-itanium-exceptions.cpp
+++ test/CodeGenCXX/windows-itanium-exceptions.cpp
@@ -10,7 +10,7 @@
   try { except(); } catch (...) { }
 }
 
-// CHECK: @_ZTIi = external constant i8*
+// CHECK: @_ZTIi = external dso_local constant i8*
 
 // CHECK: define {{.*}}void @_Z6exceptv() {{.*}} {
 // CHECK:   %exception = call {{.*}}i8* @__cxa_allocate_exception(i32 4)
Index: lib/CodeGen/ItaniumCXXABI.cpp
===
--- lib/CodeGen/ItaniumCXXABI.cpp
+++ lib/CodeGen/ItaniumCXXABI.cpp
@@ -2615,10 +2615,10 @@
   /*Constant=*/true,
   llvm::GlobalValue::ExternalLinkage, nullptr,
   Name);
-if (const RecordType *RecordTy = dyn_cast(Ty)) {
-  const CXXRecordDecl *RD = cast(RecordTy->getDecl());
-  CGM.setGVProperties(GV, RD);
-}
+const CXXRecordDecl *RD = nullptr;
+if (const auto *RecordTy = dyn_cast(Ty))
+  RD = cast(RecordTy->getDecl());
+CGM.setGVProperties(GV, RD);
   }
 
   return llvm::ConstantExpr::getBitCast(GV, CGM.Int8PtrTy);
Index: lib/CodeGen/CodeGenModule.cpp
===
--- lib/CodeGen/CodeGenModule.cpp
+++ lib/CodeGen/CodeGenModule.cpp
@@ -707,7 +707,8 @@
 GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
 return;
   }
-
+  if (!D)
+return;
   // Set visibility for definitions.
   LinkageInfo LV = D->getLinkageAndVisibility();
   if (LV.isVisibilityExplicit() || !GV->isDeclarationForLinker())
@@ -797,7 +798,7 @@
 
 void CodeGenModule::setDLLImportDLLExport(llvm::GlobalValue *GV,
   const NamedDecl *D) const {
-  if (D->isExternallyVisible()) {
+  if (D && D->isExternallyVisible()) {
 if (D->hasAttr())
   GV->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass);
 else if (D->hasAttr() && !GV->isDeclarationForLinker())
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


r326962 - [MS] Accept __unaligned as a qualifier on member function pointers

2018-03-07 Thread Reid Kleckner via cfe-commits
Author: rnk
Date: Wed Mar  7 15:26:02 2018
New Revision: 326962

URL: http://llvm.org/viewvc/llvm-project?rev=326962=rev
Log:
[MS] Accept __unaligned as a qualifier on member function pointers

We need to treat __unaligned like the other 'cvr' qualifiers when it
appears at the end of a function prototype. We weren't doing that in
some tentative parsing.

Fixes PR36638.

Modified:
cfe/trunk/lib/Parse/ParseTentative.cpp
cfe/trunk/test/Parser/MicrosoftExtensions.cpp

Modified: cfe/trunk/lib/Parse/ParseTentative.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Parse/ParseTentative.cpp?rev=326962=326961=326962=diff
==
--- cfe/trunk/lib/Parse/ParseTentative.cpp (original)
+++ cfe/trunk/lib/Parse/ParseTentative.cpp Wed Mar  7 15:26:02 2018
@@ -1894,7 +1894,8 @@ Parser::TPResult Parser::TryParseFunctio
 return TPResult::Error;
 
   // cv-qualifier-seq
-  while (Tok.isOneOf(tok::kw_const, tok::kw_volatile, tok::kw_restrict))
+  while (Tok.isOneOf(tok::kw_const, tok::kw_volatile, tok::kw___unaligned,
+ tok::kw_restrict))
 ConsumeToken();
 
   // ref-qualifier[opt]

Modified: cfe/trunk/test/Parser/MicrosoftExtensions.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/Parser/MicrosoftExtensions.cpp?rev=326962=326961=326962=diff
==
--- cfe/trunk/test/Parser/MicrosoftExtensions.cpp (original)
+++ cfe/trunk/test/Parser/MicrosoftExtensions.cpp Wed Mar  7 15:26:02 2018
@@ -424,3 +424,10 @@ struct S {
   S(T);
 } f([] {});
 }
+
+namespace pr36638 {
+// Make sure we accept __unaligned method qualifiers on member function
+// pointers.
+struct A;
+void (A::*mp1)(int) __unaligned;
+}


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


[PATCH] D44095: [ObjC] Allow declaring __weak pointer fields in C structs in ObjC-ARC

2018-03-07 Thread Akira Hatanaka via Phabricator via cfe-commits
ahatanak added inline comments.



Comment at: include/clang/AST/Decl.h:3631
+PassedIndirectly = true;
+  }
+

rjmccall wrote:
> I feel like this flag should be set by Sema for C++ types that have to be 
> passed indirectly as well; it can then become the single point of truth for 
> that information.
I moved CXXRecordDecl::CanPassInRegisters to RecordDecl along with its setter 
and getter functions.



Comment at: lib/CodeGen/CGNonTrivialStruct.cpp:764
+Object = CGF->EmitObjCConsumeObject(QT, Object);
+CGF->EmitARCStoreWeak(Addrs[DstIdx], Object, true);
+  }

rjmccall wrote:
> I guess this is the most reasonable thing to do, given that we don't have an 
> entrypoint for it.  Please ask the ObjC runtime team to consider giving us 
> one, though.  We could pretty easily peephole assignments into `__weak` 
> variables where the source is loaded from a `__weak` l-value / x-value, and 
> Swift would probably be able to take advantage of it, too.
> 
> You might want to go ahead and add `emitARCCopyAssignWeak` / 
> `emitARCMoveAssignWeak` methods on CGF that do these operations and which can 
> be optimized to use those entrypoints if/when they're added.
Do you mean we should ask for the following objc runtime functions and use them 
in visitARCWeak?

```
// dst and src are either null or registered as __weak objects.
void objc_copyAssignWeak(id *dst, id *src)
void objc_moveAssignWeak(id *dst, id *src)




Comment at: lib/CodeGen/TargetInfo.cpp:1326
+  if (RetTy.isPassedIndirectly() == QualType::APK_Struct)
+return getNaturalAlignIndirect(RetTy);
+

rjmccall wrote:
> Can we combine this into a single function that covers both the C++ case and 
> this new one?  Otherwise it seems likely that individual targets over time 
> will only add one or the other.
I added another definition of classifyReturnType and taught getRecordArgABI to 
detect non-trivial C structs. Currently, x86, arm, and arm64 are the only 
targets that use the new overload of classifyReturnType. I can modify the other 
targets to use it too if that is desirable.


https://reviews.llvm.org/D44095



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


[PATCH] D44095: [ObjC] Allow declaring __weak pointer fields in C structs in ObjC-ARC

2018-03-07 Thread Akira Hatanaka via Phabricator via cfe-commits
ahatanak updated this revision to Diff 137500.
ahatanak marked 2 inline comments as done.
ahatanak added a comment.

Address review comments.


https://reviews.llvm.org/D44095

Files:
  include/clang/AST/Decl.h
  include/clang/AST/DeclCXX.h
  include/clang/AST/Type.h
  lib/AST/ASTImporter.cpp
  lib/AST/Decl.cpp
  lib/AST/DeclCXX.cpp
  lib/AST/Type.cpp
  lib/CodeGen/CGBlocks.cpp
  lib/CodeGen/CGNonTrivialStruct.cpp
  lib/CodeGen/CGObjC.cpp
  lib/CodeGen/CodeGenFunction.h
  lib/CodeGen/TargetInfo.cpp
  lib/Sema/SemaDecl.cpp
  lib/Serialization/ASTReaderDecl.cpp
  lib/Serialization/ASTWriter.cpp
  lib/Serialization/ASTWriterDecl.cpp
  test/CodeGenObjC/nontrivial-c-struct-exception.m
  test/CodeGenObjC/weak-in-c-struct.m

Index: test/CodeGenObjC/weak-in-c-struct.m
===
--- /dev/null
+++ test/CodeGenObjC/weak-in-c-struct.m
@@ -0,0 +1,193 @@
+// RUN: %clang_cc1 -triple arm64-apple-ios11 -fobjc-arc -fblocks -fobjc-runtime=ios-11.0 -emit-llvm -o - %s | FileCheck -check-prefix=ARM64 -check-prefix=COMMON %s
+// RUN: %clang_cc1 -triple thumbv7-apple-ios10 -fobjc-arc -fblocks -fobjc-runtime=ios-10.0 -emit-llvm -o - %s | FileCheck -check-prefix=COMMON %s
+// RUN: %clang_cc1 -triple x86_64-apple-macosx10.13 -fobjc-arc -fblocks -fobjc-runtime=macosx-10.13.0 -emit-llvm -o - %s | FileCheck -check-prefix=COMMON %s
+// RUN: %clang_cc1 -triple i386-apple-macosx10.13.0 -fobjc-arc -fblocks -fobjc-runtime=macosx-fragile-10.13.0 -emit-llvm -o - %s | FileCheck -check-prefix=COMMON %s
+
+typedef void (^BlockTy)(void);
+
+// COMMON: %[[STRUCT_WEAK:.*]] = type { i32, i8* }
+
+typedef struct {
+  int f0;
+  __weak id f1;
+} Weak;
+
+Weak getWeak(void);
+void calleeWeak(Weak);
+
+// ARM64: define void @test_constructor_destructor_Weak()
+// ARM64: %[[T:.*]] = alloca %[[STRUCT_WEAK]], align 8
+// ARM64: %[[V0:.*]] = bitcast %[[STRUCT_WEAK]]* %[[T]] to i8**
+// ARM64: call void @__default_constructor_8_w8(i8** %[[V0]])
+// ARM64: %[[V1:.*]] = bitcast %[[STRUCT_WEAK]]* %[[T]] to i8**
+// ARM64: call void @__destructor_8_w8(i8** %[[V1]])
+// ARM64: ret void
+
+// ARM64: define linkonce_odr hidden void @__default_constructor_8_w8(i8** %[[DST:.*]])
+// ARM64: %[[DST_ADDR:.*]] = alloca i8**, align 8
+// ARM64: store i8** %[[DST]], i8*** %[[DST_ADDR]], align 8
+// ARM64: %[[V0:.*]] = load i8**, i8*** %[[DST_ADDR]], align 8
+// ARM64: %[[V1]] = bitcast i8** %[[V0]] to i8*
+// ARM64: %[[V2:.*]] = getelementptr inbounds i8, i8* %[[V1]], i64 8
+// ARM64: %[[V3:.*]] = bitcast i8* %[[V2]] to i8**
+// ARM64: %[[V4:.*]] = bitcast i8** %[[V3]] to i8*
+// ARM64: call void @llvm.memset.p0i8.i64(i8* align 8 %[[V4]], i8 0, i64 8, i1 false)
+
+// ARM64: define linkonce_odr hidden void @__destructor_8_w8(i8** %[[DST:.*]])
+// ARM64: %[[DST_ADDR:.*]] = alloca i8**, align 8
+// ARM64: store i8** %[[DST]], i8*** %[[DST_ADDR]], align 8
+// ARM64: %[[V0:.*]] = load i8**, i8*** %[[DST_ADDR]], align 8
+// ARM64: %[[V1:.*]] = bitcast i8** %[[V0]] to i8*
+// ARM64: %[[V2:.*]] = getelementptr inbounds i8, i8* %[[V1]], i64 8
+// ARM64: %[[V3:.*]] = bitcast i8* %[[V2]] to i8**
+// ARM64: call void @objc_destroyWeak(i8** %[[V3]])
+
+void test_constructor_destructor_Weak(void) {
+  Weak t;
+}
+
+// ARM64: define void @test_copy_constructor_Weak(%[[STRUCT_WEAK]]* %{{.*}})
+// ARM64: call void @__copy_constructor_8_8_t0w4_w8(i8** %{{.*}}, i8** %{{.*}})
+// ARM64: call void @__destructor_8_w8(i8** %{{.*}})
+
+// ARM64: define linkonce_odr hidden void @__copy_constructor_8_8_t0w4_w8(i8** %[[DST:.*]], i8** %[[SRC:.*]])
+// ARM64: %[[DST_ADDR:.*]] = alloca i8**, align 8
+// ARM64: %[[SRC_ADDR:.*]] = alloca i8**, align 8
+// ARM64: store i8** %[[DST]], i8*** %[[DST_ADDR]], align 8
+// ARM64: store i8** %[[SRC]], i8*** %[[SRC_ADDR]], align 8
+// ARM64: %[[V0:.*]] = load i8**, i8*** %[[DST_ADDR]], align 8
+// ARM64: %[[V1:.*]] = load i8**, i8*** %[[SRC_ADDR]], align 8
+// ARM64: %[[V2:.*]] = bitcast i8** %[[V0]] to i32*
+// ARM64: %[[V3:.*]] = bitcast i8** %[[V1]] to i32*
+// ARM64: %[[V4:.*]] = load i32, i32* %[[V3]], align 8
+// ARM64: store i32 %[[V4]], i32* %[[V2]], align 8
+// ARM64: %[[V5:.*]] = bitcast i8** %[[V0]] to i8*
+// ARM64: %[[V6:.*]] = getelementptr inbounds i8, i8* %[[V5]], i64 8
+// ARM64: %[[V7:.*]] = bitcast i8* %[[V6]] to i8**
+// ARM64: %[[V8:.*]] = bitcast i8** %[[V1]] to i8*
+// ARM64: %[[V9:.*]] = getelementptr inbounds i8, i8* %[[V8]], i64 8
+// ARM64: %[[V10:.*]] = bitcast i8* %[[V9]] to i8**
+// ARM64: call void @objc_copyWeak(i8** %[[V7]], i8** %[[V10]])
+
+void test_copy_constructor_Weak(Weak *s) {
+  Weak t = *s;
+}
+
+// ARM64: define void @test_copy_assignment_Weak(%[[STRUCT_WEAK]]* %{{.*}}, %[[STRUCT_WEAK]]* %{{.*}})
+// ARM64: call void @__copy_assignment_8_8_t0w4_w8(i8** %{{.*}}, i8** %{{.*}})
+
+// ARM64: define linkonce_odr hidden void @__copy_assignment_8_8_t0w4_w8(i8** %[[DST:.*]], i8** %[[SRC:.*]])
+// ARM64: %[[DST_ADDR:.*]] = alloca i8**, align 8
+// ARM64: %[[SRC_ADDR:.*]] 

[PATCH] D43990: set dso_local on tls init functions

2018-03-07 Thread Rafael Avila de Espindola via Phabricator via cfe-commits
espindola closed this revision.
espindola added a comment.

r326961


https://reviews.llvm.org/D43990



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


[PATCH] D44039: [Sema] Make getCurFunction() return null outside function parsing

2018-03-07 Thread John McCall via Phabricator via cfe-commits
rjmccall added a comment.

I agree that having those sites just no-op themselves is the cleanest approach.


https://reviews.llvm.org/D44039



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


[PATCH] D44223: [ms] Emit vtordisp initializers in a deterministic order.

2018-03-07 Thread Nico Weber via Phabricator via cfe-commits
thakis closed this revision.
thakis marked an inline comment as done.
thakis added a comment.

r326960, thanks!


https://reviews.llvm.org/D44223



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


r326961 - Set dso_local on tls init functions.

2018-03-07 Thread Rafael Espindola via cfe-commits
Author: rafael
Date: Wed Mar  7 15:18:06 2018
New Revision: 326961

URL: http://llvm.org/viewvc/llvm-project?rev=326961=rev
Log:
Set dso_local on tls init functions.

We copy the visibility, so copying the dso_local flag seems the
natural thing to do.

Modified:
cfe/trunk/lib/CodeGen/ItaniumCXXABI.cpp
cfe/trunk/test/CodeGenCXX/runtime-dllstorage.cpp

Modified: cfe/trunk/lib/CodeGen/ItaniumCXXABI.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/CodeGen/ItaniumCXXABI.cpp?rev=326961=326960=326961=diff
==
--- cfe/trunk/lib/CodeGen/ItaniumCXXABI.cpp (original)
+++ cfe/trunk/lib/CodeGen/ItaniumCXXABI.cpp Wed Mar  7 15:18:06 2018
@@ -2398,8 +2398,10 @@ void ItaniumCXXABI::EmitThreadLocalInitF
   CGM.SetLLVMFunctionAttributes(nullptr, FI, cast(Init));
 }
 
-if (Init)
+if (Init) {
   Init->setVisibility(Var->getVisibility());
+  Init->setDSOLocal(Var->isDSOLocal());
+}
 
 llvm::LLVMContext  = CGM.getModule().getContext();
 llvm::BasicBlock *Entry = llvm::BasicBlock::Create(Context, "", Wrapper);

Modified: cfe/trunk/test/CodeGenCXX/runtime-dllstorage.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/CodeGenCXX/runtime-dllstorage.cpp?rev=326961=326960=326961=diff
==
--- cfe/trunk/test/CodeGenCXX/runtime-dllstorage.cpp (original)
+++ cfe/trunk/test/CodeGenCXX/runtime-dllstorage.cpp Wed Mar  7 15:18:06 2018
@@ -114,6 +114,7 @@ void l() {
 // CHECK-MS-DAG: declare void @_Init_thread_header(i32*)
 // CHECK-MS-DAG: declare void @_Init_thread_footer(i32*)
 
+// CHECK-IA-DAG: @_ZTH1t = dso_local alias void (), void ()* @__tls_init
 // CHECK-IA-DAG: declare i32 @__gxx_personality_v0(...)
 // CHECK-IA-DAG: define linkonce_odr hidden void @__clang_call_terminate(i8*)
 


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


r326960 - [ms] Emit vtordisp initializers in a deterministic order.

2018-03-07 Thread Nico Weber via cfe-commits
Author: nico
Date: Wed Mar  7 15:15:20 2018
New Revision: 326960

URL: http://llvm.org/viewvc/llvm-project?rev=326960=rev
Log:
[ms] Emit vtordisp initializers in a deterministic order.

No effective behavior change, just for cleanliness.
Analysis and typing by me, actual patch mostly by Reid.

Fixes PR36159.
https://reviews.llvm.org/D44223

Modified:
cfe/trunk/lib/CodeGen/MicrosoftCXXABI.cpp

Modified: cfe/trunk/lib/CodeGen/MicrosoftCXXABI.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/CodeGen/MicrosoftCXXABI.cpp?rev=326960=326959=326960=diff
==
--- cfe/trunk/lib/CodeGen/MicrosoftCXXABI.cpp (original)
+++ cfe/trunk/lib/CodeGen/MicrosoftCXXABI.cpp Wed Mar  7 15:15:20 2018
@@ -1196,15 +1196,16 @@ void MicrosoftCXXABI::initializeHiddenVi
   unsigned AS = getThisAddress(CGF).getAddressSpace();
   llvm::Value *Int8This = nullptr;  // Initialize lazily.
 
-  for (VBOffsets::const_iterator I = VBaseMap.begin(), E = VBaseMap.end();
-I != E; ++I) {
+  for (const CXXBaseSpecifier  : RD->vbases()) {
+const CXXRecordDecl *VBase = S.getType()->getAsCXXRecordDecl();
+auto I = VBaseMap.find(VBase);
+assert(I != VBaseMap.end());
 if (!I->second.hasVtorDisp())
   continue;
 
 llvm::Value *VBaseOffset =
-GetVirtualBaseClassOffset(CGF, getThisAddress(CGF), RD, I->first);
-uint64_t ConstantVBaseOffset =
-Layout.getVBaseClassOffset(I->first).getQuantity();
+GetVirtualBaseClassOffset(CGF, getThisAddress(CGF), RD, VBase);
+uint64_t ConstantVBaseOffset = I->second.VBaseOffset.getQuantity();
 
 // vtorDisp_for_vbase = vbptr[vbase_idx] - offsetof(RD, vbase).
 llvm::Value *VtorDispValue = Builder.CreateSub(


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


[PATCH] D44231: Check for sizeof that call functions

2018-03-07 Thread Paul Fultz II via Phabricator via cfe-commits
pfultz2 updated this revision to Diff 137499.

https://reviews.llvm.org/D44231

Files:
  clang-tidy/misc/SizeofExpressionCheck.cpp
  clang-tidy/misc/SizeofExpressionCheck.h
  test/clang-tidy/misc-sizeof-expression.cpp

Index: test/clang-tidy/misc-sizeof-expression.cpp
===
--- test/clang-tidy/misc-sizeof-expression.cpp
+++ test/clang-tidy/misc-sizeof-expression.cpp
@@ -14,14 +14,34 @@
 #pragma pack(1)
 struct  S { char a, b, c; };
 
+enum E { E_VALUE = 0 };
+
+int AsInt() { return 0; }
+E AsEnum() { return E_VALUE; }
+S AsStruct() { return {}; }
+
+struct M {
+  int AsInt() { return 0; }
+  E AsEnum() { return E_VALUE; }
+  S AsStruct() { return {}; }
+};
+
 int Test1(const char* ptr) {
   int sum = 0;
   sum += sizeof(LEN);
   // CHECK-MESSAGES: :[[@LINE-1]]:10: warning: suspicious usage of 'sizeof(K)'
   sum += sizeof(LEN + 1);
   // CHECK-MESSAGES: :[[@LINE-1]]:10: warning: suspicious usage of 'sizeof(K)'
   sum += sizeof(sum, LEN);
   // CHECK-MESSAGES: :[[@LINE-1]]:10: warning: suspicious usage of 'sizeof(..., ...)'
+  sum += sizeof(AsInt());
+  // CHECK-MESSAGES: :[[@LINE-1]]:10: warning: suspicious usage of 'sizeof(expr)' to an integer
+  sum += sizeof(AsEnum());
+  // CHECK-MESSAGES: :[[@LINE-1]]:10: warning: suspicious usage of 'sizeof(expr)' to an integer
+  sum += sizeof(M{}.AsInt());
+  // CHECK-MESSAGES: :[[@LINE-1]]:10: warning: suspicious usage of 'sizeof(expr)' to an integer
+  sum += sizeof(M{}.AsEnum());
+  // CHECK-MESSAGES: :[[@LINE-1]]:10: warning: suspicious usage of 'sizeof(expr)' to an integer
   sum += sizeof(sizeof(X));
   // CHECK-MESSAGES: :[[@LINE-1]]:10: warning: suspicious usage of 'sizeof(sizeof(...))'
   sum += sizeof(LEN + sizeof(X));
@@ -171,6 +191,8 @@
   if (sizeof(A) < 10)
 sum += sizeof(A);
   sum += sizeof(int);
+  sum += sizeof(AsStruct());
+  sum += sizeof(M{}.AsStruct());
   sum += sizeof(A[sizeof(A) / sizeof(int)]);
   sum += sizeof([sizeof(A) / sizeof(int)]);
   sum += sizeof(sizeof(0));  // Special case: sizeof size_t.
Index: clang-tidy/misc/SizeofExpressionCheck.h
===
--- clang-tidy/misc/SizeofExpressionCheck.h
+++ clang-tidy/misc/SizeofExpressionCheck.h
@@ -29,6 +29,7 @@
 
 private:
   const bool WarnOnSizeOfConstant;
+  const bool WarnOnSizeOfCall;
   const bool WarnOnSizeOfThis;
   const bool WarnOnSizeOfCompareToConstant;
 };
Index: clang-tidy/misc/SizeofExpressionCheck.cpp
===
--- clang-tidy/misc/SizeofExpressionCheck.cpp
+++ clang-tidy/misc/SizeofExpressionCheck.cpp
@@ -62,12 +62,14 @@
  ClangTidyContext *Context)
 : ClangTidyCheck(Name, Context),
   WarnOnSizeOfConstant(Options.get("WarnOnSizeOfConstant", 1) != 0),
+  WarnOnSizeOfCall(Options.get("WarnOnSizeOfCall", 1) != 0),
   WarnOnSizeOfThis(Options.get("WarnOnSizeOfThis", 1) != 0),
   WarnOnSizeOfCompareToConstant(
   Options.get("WarnOnSizeOfCompareToConstant", 1) != 0) {}
 
 void SizeofExpressionCheck::storeOptions(ClangTidyOptions::OptionMap ) {
   Options.store(Opts, "WarnOnSizeOfConstant", WarnOnSizeOfConstant);
+  Options.store(Opts, "WarnOnSizeOfCall", WarnOnSizeOfCall);
   Options.store(Opts, "WarnOnSizeOfThis", WarnOnSizeOfThis);
   Options.store(Opts, "WarnOnSizeOfCompareToConstant",
 WarnOnSizeOfCompareToConstant);
@@ -78,6 +80,8 @@
   const auto ConstantExpr = expr(ignoringParenImpCasts(
   anyOf(integerLiteral(), unaryOperator(hasUnaryOperand(IntegerExpr)),
 binaryOperator(hasLHS(IntegerExpr), hasRHS(IntegerExpr);
+  const auto IntegerCallExpr =
+  expr(ignoringParenImpCasts(callExpr(hasType(isInteger();
   const auto SizeOfExpr =
   expr(anyOf(sizeOfExpr(has(type())), sizeOfExpr(has(expr();
   const auto SizeOfZero = expr(
@@ -94,6 +98,14 @@
 this);
   }
 
+  // Detect sizeof(f())
+  if (WarnOnSizeOfCall) {
+Finder->addMatcher(
+expr(sizeOfExpr(ignoringParenImpCasts(has(IntegerCallExpr
+.bind("sizeof-integer-call"),
+this);
+  }
+
   // Detect expression like: sizeof(this);
   if (WarnOnSizeOfThis) {
 Finder->addMatcher(
@@ -203,6 +215,9 @@
   if (const auto *E = Result.Nodes.getNodeAs("sizeof-constant")) {
 diag(E->getLocStart(),
  "suspicious usage of 'sizeof(K)'; did you mean 'K'?");
+  } else if (const auto *E =
+ Result.Nodes.getNodeAs("sizeof-integer-call")) {
+diag(E->getLocStart(), "suspicious usage of 'sizeof(expr)' to an integer");
   } else if (const auto *E = Result.Nodes.getNodeAs("sizeof-this")) {
 diag(E->getLocStart(),
  "suspicious usage of 'sizeof(this)'; did you mean 'sizeof(*this)'");
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D44231: Check for sizeof that call functions

2018-03-07 Thread Paul Fultz II via Phabricator via cfe-commits
pfultz2 updated this revision to Diff 137497.

https://reviews.llvm.org/D44231

Files:
  clang-tidy/misc/SizeofExpressionCheck.cpp
  clang-tidy/misc/SizeofExpressionCheck.h
  test/clang-tidy/misc-sizeof-expression.cpp

Index: test/clang-tidy/misc-sizeof-expression.cpp
===
--- test/clang-tidy/misc-sizeof-expression.cpp
+++ test/clang-tidy/misc-sizeof-expression.cpp
@@ -14,6 +14,18 @@
 #pragma pack(1)
 struct  S { char a, b, c; };
 
+enum E { E_VALUE = 0 };
+
+int AsInt() { return 0; }
+E AsEnum() { return E_VALUE; }
+S AsStruct() { return {}; }
+
+struct M {
+  int AsInt() { return 0; }
+  E AsEnum() { return E_VALUE; }
+  S AsStruct() { return {}; }
+};
+
 int Test1(const char* ptr) {
   int sum = 0;
   sum += sizeof(LEN);
@@ -22,6 +34,14 @@
   // CHECK-MESSAGES: :[[@LINE-1]]:10: warning: suspicious usage of 'sizeof(K)'
   sum += sizeof(sum, LEN);
   // CHECK-MESSAGES: :[[@LINE-1]]:10: warning: suspicious usage of 'sizeof(..., ...)'
+  sum += sizeof(AsInt());
+  // CHECK-MESSAGES: :[[@LINE-1]]:10: warning: suspicious usage of 'sizeof(expr)' to an integer
+  sum += sizeof(AsEnum());
+  // CHECK-MESSAGES: :[[@LINE-1]]:10: warning: suspicious usage of 'sizeof(expr)' to an integer
+  sum += sizeof(M{}.AsInt());
+  // CHECK-MESSAGES: :[[@LINE-1]]:10: warning: suspicious usage of 'sizeof(expr)' to an integer
+  sum += sizeof(M{}.AsEnum());
+  // CHECK-MESSAGES: :[[@LINE-1]]:10: warning: suspicious usage of 'sizeof(expr)' to an integer
   sum += sizeof(sizeof(X));
   // CHECK-MESSAGES: :[[@LINE-1]]:10: warning: suspicious usage of 'sizeof(sizeof(...))'
   sum += sizeof(LEN + sizeof(X));
@@ -171,6 +191,8 @@
   if (sizeof(A) < 10)
 sum += sizeof(A);
   sum += sizeof(int);
+  sum += sizeof(AsStruct());
+  sum += sizeof(M{}.AsStruct());
   sum += sizeof(A[sizeof(A) / sizeof(int)]);
   sum += sizeof([sizeof(A) / sizeof(int)]);
   sum += sizeof(sizeof(0));  // Special case: sizeof size_t.
Index: clang-tidy/misc/SizeofExpressionCheck.h
===
--- clang-tidy/misc/SizeofExpressionCheck.h
+++ clang-tidy/misc/SizeofExpressionCheck.h
@@ -29,6 +29,7 @@
 
 private:
   const bool WarnOnSizeOfConstant;
+  const bool WarnOnSizeOfCall;
   const bool WarnOnSizeOfThis;
   const bool WarnOnSizeOfCompareToConstant;
 };
Index: clang-tidy/misc/SizeofExpressionCheck.cpp
===
--- clang-tidy/misc/SizeofExpressionCheck.cpp
+++ clang-tidy/misc/SizeofExpressionCheck.cpp
@@ -62,12 +62,14 @@
  ClangTidyContext *Context)
 : ClangTidyCheck(Name, Context),
   WarnOnSizeOfConstant(Options.get("WarnOnSizeOfConstant", 1) != 0),
+  WarnOnSizeOfCall(Options.get("WarnOnSizeOfCall", 1) != 0),
   WarnOnSizeOfThis(Options.get("WarnOnSizeOfThis", 1) != 0),
   WarnOnSizeOfCompareToConstant(
   Options.get("WarnOnSizeOfCompareToConstant", 1) != 0) {}
 
 void SizeofExpressionCheck::storeOptions(ClangTidyOptions::OptionMap ) {
   Options.store(Opts, "WarnOnSizeOfConstant", WarnOnSizeOfConstant);
+  Options.store(Opts, "WarnOnSizeOfCall", WarnOnSizeOfCall);
   Options.store(Opts, "WarnOnSizeOfThis", WarnOnSizeOfThis);
   Options.store(Opts, "WarnOnSizeOfCompareToConstant",
 WarnOnSizeOfCompareToConstant);
@@ -78,6 +80,8 @@
   const auto ConstantExpr = expr(ignoringParenImpCasts(
   anyOf(integerLiteral(), unaryOperator(hasUnaryOperand(IntegerExpr)),
 binaryOperator(hasLHS(IntegerExpr), hasRHS(IntegerExpr);
+  const auto IntegerCallExpr =
+  expr(ignoringParenImpCasts(callExpr(hasType(isInteger();
   const auto SizeOfExpr =
   expr(anyOf(sizeOfExpr(has(type())), sizeOfExpr(has(expr();
   const auto SizeOfZero = expr(
@@ -94,6 +98,14 @@
 this);
   }
 
+  // Detect sizeof(f())
+  if (WarnOnSizeOfCall) {
+Finder->addMatcher(
+expr(sizeOfExpr(ignoringParenImpCasts(has(IntegerCallExpr
+.bind("sizeof-integer-call"),
+this);
+  }
+
   // Detect expression like: sizeof(this);
   if (WarnOnSizeOfThis) {
 Finder->addMatcher(
@@ -203,6 +215,9 @@
   if (const auto *E = Result.Nodes.getNodeAs("sizeof-constant")) {
 diag(E->getLocStart(),
  "suspicious usage of 'sizeof(K)'; did you mean 'K'?");
+  } else if (const auto *E =
+ Result.Nodes.getNodeAs("sizeof-integer-call")) {
+diag(E->getLocStart(), "suspicious usage of 'sizeof(expr)' to an integer");
   } else if (const auto *E = Result.Nodes.getNodeAs("sizeof-this")) {
 diag(E->getLocStart(),
  "suspicious usage of 'sizeof(this)'; did you mean 'sizeof(*this)'");
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D44231: Check for sizeof that call functions

2018-03-07 Thread Paul Fultz II via Phabricator via cfe-commits
pfultz2 updated this revision to Diff 137496.

https://reviews.llvm.org/D44231

Files:
  clangd/CodeComplete.cpp
  test/clangd/protocol.test
  unittests/clangd/CodeCompleteTests.cpp


Index: unittests/clangd/CodeCompleteTests.cpp
===
--- unittests/clangd/CodeCompleteTests.cpp
+++ unittests/clangd/CodeCompleteTests.cpp
@@ -595,6 +595,18 @@
   EXPECT_TRUE(Results.items.empty());
 }
 
+TEST(CodeCompleteTest, NoColonColonAtTheEnd) {
+  auto Results = completions(R"cpp(
+namespace clang { }
+void f() {
+  clan^
+}
+  )cpp");
+
+  EXPECT_THAT(Results.items, Contains(Labeled("clang")));
+  EXPECT_THAT(Results.items, Not(Contains(Labeled("clang::";
+}
+
 SignatureHelp signatures(StringRef Text) {
   MockFSProvider FS;
   MockCompilationDatabase CDB;
Index: test/clangd/protocol.test
===
--- test/clangd/protocol.test
+++ test/clangd/protocol.test
@@ -38,7 +38,7 @@
 # CHECK-NEXT:"insertText": "fake",
 # CHECK-NEXT:"insertTextFormat": 1,
 # CHECK-NEXT:"kind": 7,
-# CHECK-NEXT:"label": "fake::",
+# CHECK-NEXT:"label": "fake",
 # CHECK-NEXT:"sortText": "{{.*}}"
 #  CHECK:]
 # CHECK-NEXT:  }
@@ -67,7 +67,7 @@
 # CHECK-NEXT:"insertText": "fake",
 # CHECK-NEXT:"insertTextFormat": 1,
 # CHECK-NEXT:"kind": 7,
-# CHECK-NEXT:"label": "fake::",
+# CHECK-NEXT:"label": "fake",
 # CHECK-NEXT:"sortText": "{{.*}}"
 #  CHECK:]
 # CHECK-NEXT:  }
@@ -96,7 +96,7 @@
 # CHECK-NEXT:"insertText": "fake",
 # CHECK-NEXT:"insertTextFormat": 1,
 # CHECK-NEXT:"kind": 7,
-# CHECK-NEXT:"label": "fake::",
+# CHECK-NEXT:"label": "fake",
 # CHECK-NEXT:"sortText": "{{.*}}"
 #  CHECK:]
 # CHECK-NEXT:  }
Index: clangd/CodeComplete.cpp
===
--- clangd/CodeComplete.cpp
+++ clangd/CodeComplete.cpp
@@ -470,6 +470,8 @@
   // (s.^ completes ~string, but s.~st^ is an error).
   if (dyn_cast_or_null(Result.Declaration))
 continue;
+  // We choose to never append '::' to completion results in clangd.
+  Result.StartsNestedNameSpecifier = false;
   Results.push_back(Result);
 }
 ResultsCallback();


Index: unittests/clangd/CodeCompleteTests.cpp
===
--- unittests/clangd/CodeCompleteTests.cpp
+++ unittests/clangd/CodeCompleteTests.cpp
@@ -595,6 +595,18 @@
   EXPECT_TRUE(Results.items.empty());
 }
 
+TEST(CodeCompleteTest, NoColonColonAtTheEnd) {
+  auto Results = completions(R"cpp(
+namespace clang { }
+void f() {
+  clan^
+}
+  )cpp");
+
+  EXPECT_THAT(Results.items, Contains(Labeled("clang")));
+  EXPECT_THAT(Results.items, Not(Contains(Labeled("clang::";
+}
+
 SignatureHelp signatures(StringRef Text) {
   MockFSProvider FS;
   MockCompilationDatabase CDB;
Index: test/clangd/protocol.test
===
--- test/clangd/protocol.test
+++ test/clangd/protocol.test
@@ -38,7 +38,7 @@
 # CHECK-NEXT:"insertText": "fake",
 # CHECK-NEXT:"insertTextFormat": 1,
 # CHECK-NEXT:"kind": 7,
-# CHECK-NEXT:"label": "fake::",
+# CHECK-NEXT:"label": "fake",
 # CHECK-NEXT:"sortText": "{{.*}}"
 #  CHECK:]
 # CHECK-NEXT:  }
@@ -67,7 +67,7 @@
 # CHECK-NEXT:"insertText": "fake",
 # CHECK-NEXT:"insertTextFormat": 1,
 # CHECK-NEXT:"kind": 7,
-# CHECK-NEXT:"label": "fake::",
+# CHECK-NEXT:"label": "fake",
 # CHECK-NEXT:"sortText": "{{.*}}"
 #  CHECK:]
 # CHECK-NEXT:  }
@@ -96,7 +96,7 @@
 # CHECK-NEXT:"insertText": "fake",
 # CHECK-NEXT:"insertTextFormat": 1,
 # CHECK-NEXT:"kind": 7,
-# CHECK-NEXT:"label": "fake::",
+# CHECK-NEXT:"label": "fake",
 # CHECK-NEXT:"sortText": "{{.*}}"
 #  CHECK:]
 # CHECK-NEXT:  }
Index: clangd/CodeComplete.cpp
===
--- clangd/CodeComplete.cpp
+++ clangd/CodeComplete.cpp
@@ -470,6 +470,8 @@
   // (s.^ completes ~string, but s.~st^ is an error).
   if (dyn_cast_or_null(Result.Declaration))
 continue;
+  // We choose to never append '::' to completion results in clangd.
+  Result.StartsNestedNameSpecifier = false;
   Results.push_back(Result);
 }
 ResultsCallback();
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D44231: Check for sizeof that call functions

2018-03-07 Thread Paul Fultz II via Phabricator via cfe-commits
pfultz2 created this revision.
pfultz2 added reviewers: clang-tools-extra, hokein, alexfh, aaron.ballman, 
ilya-biryukov.
Herald added a subscriber: jkorous-apple.

A common mistake that I have found in our codebase is calling a function to get 
an integer or enum that represents the type such as:

  int numBytes = numElements * sizeof(x.GetType());

So this extends the `sizeof` check to check for these cases. There is also a 
`WarnOnSizeOfCall` option so it can be disabled.


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D44231

Files:
  clangd/CodeComplete.cpp
  test/clangd/protocol.test
  unittests/clangd/CodeCompleteTests.cpp


Index: unittests/clangd/CodeCompleteTests.cpp
===
--- unittests/clangd/CodeCompleteTests.cpp
+++ unittests/clangd/CodeCompleteTests.cpp
@@ -595,6 +595,18 @@
   EXPECT_TRUE(Results.items.empty());
 }
 
+TEST(CodeCompleteTest, NoColonColonAtTheEnd) {
+  auto Results = completions(R"cpp(
+namespace clang { }
+void f() {
+  clan^
+}
+  )cpp");
+
+  EXPECT_THAT(Results.items, Contains(Labeled("clang")));
+  EXPECT_THAT(Results.items, Not(Contains(Labeled("clang::";
+}
+
 SignatureHelp signatures(StringRef Text) {
   MockFSProvider FS;
   MockCompilationDatabase CDB;
Index: test/clangd/protocol.test
===
--- test/clangd/protocol.test
+++ test/clangd/protocol.test
@@ -38,7 +38,7 @@
 # CHECK-NEXT:"insertText": "fake",
 # CHECK-NEXT:"insertTextFormat": 1,
 # CHECK-NEXT:"kind": 7,
-# CHECK-NEXT:"label": "fake::",
+# CHECK-NEXT:"label": "fake",
 # CHECK-NEXT:"sortText": "{{.*}}"
 #  CHECK:]
 # CHECK-NEXT:  }
@@ -67,7 +67,7 @@
 # CHECK-NEXT:"insertText": "fake",
 # CHECK-NEXT:"insertTextFormat": 1,
 # CHECK-NEXT:"kind": 7,
-# CHECK-NEXT:"label": "fake::",
+# CHECK-NEXT:"label": "fake",
 # CHECK-NEXT:"sortText": "{{.*}}"
 #  CHECK:]
 # CHECK-NEXT:  }
@@ -96,7 +96,7 @@
 # CHECK-NEXT:"insertText": "fake",
 # CHECK-NEXT:"insertTextFormat": 1,
 # CHECK-NEXT:"kind": 7,
-# CHECK-NEXT:"label": "fake::",
+# CHECK-NEXT:"label": "fake",
 # CHECK-NEXT:"sortText": "{{.*}}"
 #  CHECK:]
 # CHECK-NEXT:  }
Index: clangd/CodeComplete.cpp
===
--- clangd/CodeComplete.cpp
+++ clangd/CodeComplete.cpp
@@ -470,6 +470,8 @@
   // (s.^ completes ~string, but s.~st^ is an error).
   if (dyn_cast_or_null(Result.Declaration))
 continue;
+  // We choose to never append '::' to completion results in clangd.
+  Result.StartsNestedNameSpecifier = false;
   Results.push_back(Result);
 }
 ResultsCallback();


Index: unittests/clangd/CodeCompleteTests.cpp
===
--- unittests/clangd/CodeCompleteTests.cpp
+++ unittests/clangd/CodeCompleteTests.cpp
@@ -595,6 +595,18 @@
   EXPECT_TRUE(Results.items.empty());
 }
 
+TEST(CodeCompleteTest, NoColonColonAtTheEnd) {
+  auto Results = completions(R"cpp(
+namespace clang { }
+void f() {
+  clan^
+}
+  )cpp");
+
+  EXPECT_THAT(Results.items, Contains(Labeled("clang")));
+  EXPECT_THAT(Results.items, Not(Contains(Labeled("clang::";
+}
+
 SignatureHelp signatures(StringRef Text) {
   MockFSProvider FS;
   MockCompilationDatabase CDB;
Index: test/clangd/protocol.test
===
--- test/clangd/protocol.test
+++ test/clangd/protocol.test
@@ -38,7 +38,7 @@
 # CHECK-NEXT:"insertText": "fake",
 # CHECK-NEXT:"insertTextFormat": 1,
 # CHECK-NEXT:"kind": 7,
-# CHECK-NEXT:"label": "fake::",
+# CHECK-NEXT:"label": "fake",
 # CHECK-NEXT:"sortText": "{{.*}}"
 #  CHECK:]
 # CHECK-NEXT:  }
@@ -67,7 +67,7 @@
 # CHECK-NEXT:"insertText": "fake",
 # CHECK-NEXT:"insertTextFormat": 1,
 # CHECK-NEXT:"kind": 7,
-# CHECK-NEXT:"label": "fake::",
+# CHECK-NEXT:"label": "fake",
 # CHECK-NEXT:"sortText": "{{.*}}"
 #  CHECK:]
 # CHECK-NEXT:  }
@@ -96,7 +96,7 @@
 # CHECK-NEXT:"insertText": "fake",
 # CHECK-NEXT:"insertTextFormat": 1,
 # CHECK-NEXT:"kind": 7,
-# CHECK-NEXT:"label": "fake::",
+# CHECK-NEXT:"label": "fake",
 # CHECK-NEXT:"sortText": "{{.*}}"
 #  CHECK:]
 # CHECK-NEXT:  }
Index: clangd/CodeComplete.cpp
===
--- clangd/CodeComplete.cpp
+++ clangd/CodeComplete.cpp
@@ -470,6 +470,8 @@
   // (s.^ completes ~string, but s.~st^ is an error).
   if (dyn_cast_or_null(Result.Declaration))
 continue;
+  // We choose to never append '::' to completion results in clangd.
+  Result.StartsNestedNameSpecifier = 

[PATCH] D44229: Don't use -pie in relocatable link.

2018-03-07 Thread Mandeep Singh Grang via Phabricator via cfe-commits
mgrang added inline comments.



Comment at: clang/lib/Driver/ToolChains/Gnu.cpp:311
+  if (Args.hasArg(options::OPT_shared) || Args.hasArg(options::OPT_static) ||
+  Args.hasArg(options::OPT_r))
 return false;

We also need to check for -Wl,-r and -Xlinker -r options.


https://reviews.llvm.org/D44229



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


[PATCH] D44229: Don't use -pie in relocatable link.

2018-03-07 Thread Stephen Hines via Phabricator via cfe-commits
srhines accepted this revision.
srhines added a comment.
This revision is now accepted and ready to land.

Thanks for fixing this quickly. :)


https://reviews.llvm.org/D44229



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


[PATCH] D44229: Don't use -pie in relocatable link.

2018-03-07 Thread Evgenii Stepanov via Phabricator via cfe-commits
eugenis created this revision.
eugenis added a reviewer: srhines.

Android, in particular, got PIE enabled by default in r316606. It resulted in
relocatable links passing both -r and -pie to the linker, which is not allowed.


https://reviews.llvm.org/D44229

Files:
  clang/lib/Driver/ToolChains/Gnu.cpp
  clang/test/Driver/android-pie.c


Index: clang/test/Driver/android-pie.c
===
--- clang/test/Driver/android-pie.c
+++ clang/test/Driver/android-pie.c
@@ -64,3 +64,20 @@
 // RUN:   | FileCheck --check-prefix=NO-PIE %s
 // RUN: %clang %s -### -o %t.o 2>&1 -pie -no-pie 
--target=arm-linux-androideabi24 \
 // RUN:   | FileCheck --check-prefix=NO-PIE %s
+
+// Static/shared/relocatable disable -pie
+
+// RUN: %clang %s -### --target=aarch64-linux-android -static 2>&1 \
+// RUN: | FileCheck %s -check-prefix=CHECK-STATIC
+// CHECK-STATIC-NOT: "-pie"
+// CHECK-STATIC: -static
+
+// RUN: %clang %s -### --target=aarch64-linux-android -shared 2>&1 \
+// RUN: | FileCheck %s -check-prefix=CHECK-SHARED
+// CHECK-SHARED-NOT: "-pie"
+// CHECK-SHARED: "-shared"
+
+// RUN: %clang %s -### --target=aarch64-linux-android -r 2>&1 \
+// RUN: | FileCheck %s -check-prefix=CHECK-RELOCATABLE
+// CHECK-RELOCATABLE-NOT: "-pie"
+// CHECK-RELOCATABLE: "-r"
Index: clang/lib/Driver/ToolChains/Gnu.cpp
===
--- clang/lib/Driver/ToolChains/Gnu.cpp
+++ clang/lib/Driver/ToolChains/Gnu.cpp
@@ -307,7 +307,8 @@
 }
 
 static bool getPIE(const ArgList , const toolchains::Linux ) {
-  if (Args.hasArg(options::OPT_shared) || Args.hasArg(options::OPT_static))
+  if (Args.hasArg(options::OPT_shared) || Args.hasArg(options::OPT_static) ||
+  Args.hasArg(options::OPT_r))
 return false;
 
   Arg *A = Args.getLastArg(options::OPT_pie, options::OPT_no_pie,


Index: clang/test/Driver/android-pie.c
===
--- clang/test/Driver/android-pie.c
+++ clang/test/Driver/android-pie.c
@@ -64,3 +64,20 @@
 // RUN:   | FileCheck --check-prefix=NO-PIE %s
 // RUN: %clang %s -### -o %t.o 2>&1 -pie -no-pie --target=arm-linux-androideabi24 \
 // RUN:   | FileCheck --check-prefix=NO-PIE %s
+
+// Static/shared/relocatable disable -pie
+
+// RUN: %clang %s -### --target=aarch64-linux-android -static 2>&1 \
+// RUN: | FileCheck %s -check-prefix=CHECK-STATIC
+// CHECK-STATIC-NOT: "-pie"
+// CHECK-STATIC: -static
+
+// RUN: %clang %s -### --target=aarch64-linux-android -shared 2>&1 \
+// RUN: | FileCheck %s -check-prefix=CHECK-SHARED
+// CHECK-SHARED-NOT: "-pie"
+// CHECK-SHARED: "-shared"
+
+// RUN: %clang %s -### --target=aarch64-linux-android -r 2>&1 \
+// RUN: | FileCheck %s -check-prefix=CHECK-RELOCATABLE
+// CHECK-RELOCATABLE-NOT: "-pie"
+// CHECK-RELOCATABLE: "-r"
Index: clang/lib/Driver/ToolChains/Gnu.cpp
===
--- clang/lib/Driver/ToolChains/Gnu.cpp
+++ clang/lib/Driver/ToolChains/Gnu.cpp
@@ -307,7 +307,8 @@
 }
 
 static bool getPIE(const ArgList , const toolchains::Linux ) {
-  if (Args.hasArg(options::OPT_shared) || Args.hasArg(options::OPT_static))
+  if (Args.hasArg(options::OPT_shared) || Args.hasArg(options::OPT_static) ||
+  Args.hasArg(options::OPT_r))
 return false;
 
   Arg *A = Args.getLastArg(options::OPT_pie, options::OPT_no_pie,
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[libcxx] r326958 - Include since we use it. Thanks to Andrey Maksimov for the catch.

2018-03-07 Thread Marshall Clow via cfe-commits
Author: marshall
Date: Wed Mar  7 14:51:16 2018
New Revision: 326958

URL: http://llvm.org/viewvc/llvm-project?rev=326958=rev
Log:
Include  since we use it. Thanks to Andrey Maksimov for the catch.


Modified:
libcxx/trunk/test/std/numerics/rand/rand.device/eval.pass.cpp

Modified: libcxx/trunk/test/std/numerics/rand/rand.device/eval.pass.cpp
URL: 
http://llvm.org/viewvc/llvm-project/libcxx/trunk/test/std/numerics/rand/rand.device/eval.pass.cpp?rev=326958=326957=326958=diff
==
--- libcxx/trunk/test/std/numerics/rand/rand.device/eval.pass.cpp (original)
+++ libcxx/trunk/test/std/numerics/rand/rand.device/eval.pass.cpp Wed Mar  7 
14:51:16 2018
@@ -23,6 +23,7 @@
 
 #include 
 #include 
+#include 
 
 #include "test_macros.h"
 


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


[PATCH] D44221: Avoid including ScopeInfo.h from Sema.h

2018-03-07 Thread Reid Kleckner via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rC326957: Avoid including ScopeInfo.h from Sema.h (authored by 
rnk, committed by ).

Changed prior to commit:
  https://reviews.llvm.org/D44221?vs=137487=137488#toc

Repository:
  rC Clang

https://reviews.llvm.org/D44221

Files:
  include/clang/Sema/ScopeInfo.h
  include/clang/Sema/Sema.h
  include/clang/Sema/SemaLambda.h
  lib/Sema/Sema.cpp
  lib/Sema/SemaCoroutine.cpp
  lib/Sema/SemaDecl.cpp
  lib/Sema/SemaDeclAttr.cpp
  lib/Sema/SemaExpr.cpp
  lib/Sema/SemaExprMember.cpp
  lib/Sema/SemaLambda.cpp
  lib/Sema/SemaPseudoObject.cpp
  lib/Sema/SemaStmt.cpp

Index: lib/Sema/SemaDecl.cpp
===
--- lib/Sema/SemaDecl.cpp
+++ lib/Sema/SemaDecl.cpp
@@ -6930,7 +6930,7 @@
 /// variable \p VD, or an invalid source location otherwise.
 static SourceLocation getCaptureLocation(const LambdaScopeInfo *LSI,
  const VarDecl *VD) {
-  for (const LambdaScopeInfo::Capture  : LSI->Captures) {
+  for (const Capture  : LSI->Captures) {
 if (Capture.isVariableCapture() && Capture.getVariable() == VD)
   return Capture.getLocation();
   }
Index: lib/Sema/SemaDeclAttr.cpp
===
--- lib/Sema/SemaDeclAttr.cpp
+++ lib/Sema/SemaDeclAttr.cpp
@@ -31,6 +31,7 @@
 #include "clang/Sema/Initialization.h"
 #include "clang/Sema/Lookup.h"
 #include "clang/Sema/Scope.h"
+#include "clang/Sema/ScopeInfo.h"
 #include "clang/Sema/SemaInternal.h"
 #include "llvm/ADT/STLExtras.h"
 #include "llvm/ADT/StringExtras.h"
Index: lib/Sema/Sema.cpp
===
--- lib/Sema/Sema.cpp
+++ lib/Sema/Sema.cpp
@@ -1426,6 +1426,18 @@
   return CurBSI;
 }
 
+FunctionScopeInfo *Sema::getEnclosingFunction() const {
+  if (FunctionScopes.empty())
+return nullptr;
+
+  for (int e = FunctionScopes.size() - 1; e >= 0; --e) {
+if (isa(FunctionScopes[e]))
+  continue;
+return FunctionScopes[e];
+  }
+  return nullptr;
+}
+
 LambdaScopeInfo *Sema::getCurLambda(bool IgnoreNonLambdaCapturingScope) {
   if (FunctionScopes.empty())
 return nullptr;
Index: lib/Sema/SemaExpr.cpp
===
--- lib/Sema/SemaExpr.cpp
+++ lib/Sema/SemaExpr.cpp
@@ -1679,9 +1679,9 @@
   MarkDeclRefReferenced(E);
 
   if (getLangOpts().ObjCWeak && isa(D) &&
-  Ty.getObjCLifetime() == Qualifiers::OCL_Weak &&
+  Ty.getObjCLifetime() == Qualifiers::OCL_Weak && !isUnevaluatedContext() &&
   !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, E->getLocStart()))
-  recordUseOfEvaluatedWeak(E);
+getCurFunction()->recordUseOfWeak(E);
 
   FieldDecl *FD = dyn_cast(D);
   if (IndirectFieldDecl *IFD = dyn_cast(D))
@@ -2431,8 +2431,9 @@
   IV->getLocation(), SelfExpr.get(), true, true);
 
   if (IV->getType().getObjCLifetime() == Qualifiers::OCL_Weak) {
-if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
-  recordUseOfEvaluatedWeak(Result);
+if (!isUnevaluatedContext() &&
+!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
+  getCurFunction()->recordUseOfWeak(Result);
   }
   if (getLangOpts().ObjCAutoRefCount) {
 if (CurContext->isClosure())
@@ -13045,7 +13046,7 @@
   // Set the captured variables on the block.
   // FIXME: Share capture structure between BlockDecl and CapturingScopeInfo!
   SmallVector Captures;
-  for (CapturingScopeInfo::Capture  : BSI->Captures) {
+  for (Capture  : BSI->Captures) {
 if (Cap.isThisCapture())
   continue;
 BlockDecl::Capture NewCap(Cap.getVariable(), Cap.isBlockCapture(),
@@ -14144,7 +14145,7 @@
 // Similarly to mutable captures in lambda, all the OpenMP captures by copy
 // are mutable in the sense that user can change their value - they are
 // private instances of the captured declarations.
-const CapturingScopeInfo::Capture  = CSI->getCapture(Var);
+const Capture  = CSI->getCapture(Var);
 if (Cap.isCopyCapture() &&
 !(isa(CSI) && cast(CSI)->Mutable) &&
 !(isa(CSI) &&
Index: lib/Sema/SemaCoroutine.cpp
===
--- lib/Sema/SemaCoroutine.cpp
+++ lib/Sema/SemaCoroutine.cpp
@@ -19,6 +19,7 @@
 #include "clang/Lex/Preprocessor.h"
 #include "clang/Sema/Initialization.h"
 #include "clang/Sema/Overload.h"
+#include "clang/Sema/ScopeInfo.h"
 #include "clang/Sema/SemaInternal.h"
 
 using namespace clang;
Index: lib/Sema/SemaExprMember.cpp
===
--- lib/Sema/SemaExprMember.cpp
+++ lib/Sema/SemaExprMember.cpp
@@ -1479,8 +1479,9 @@
 IsArrow);
 
 if (IV->getType().getObjCLifetime() == Qualifiers::OCL_Weak) {
-  if 

[PATCH] D44221: Avoid including ScopeInfo.h from Sema.h

2018-03-07 Thread Reid Kleckner via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rL326957: Avoid including ScopeInfo.h from Sema.h (authored by 
rnk, committed by ).
Herald added a subscriber: llvm-commits.

Changed prior to commit:
  https://reviews.llvm.org/D44221?vs=137487=137489#toc

Repository:
  rL LLVM

https://reviews.llvm.org/D44221

Files:
  cfe/trunk/include/clang/Sema/ScopeInfo.h
  cfe/trunk/include/clang/Sema/Sema.h
  cfe/trunk/include/clang/Sema/SemaLambda.h
  cfe/trunk/lib/Sema/Sema.cpp
  cfe/trunk/lib/Sema/SemaCoroutine.cpp
  cfe/trunk/lib/Sema/SemaDecl.cpp
  cfe/trunk/lib/Sema/SemaDeclAttr.cpp
  cfe/trunk/lib/Sema/SemaExpr.cpp
  cfe/trunk/lib/Sema/SemaExprMember.cpp
  cfe/trunk/lib/Sema/SemaLambda.cpp
  cfe/trunk/lib/Sema/SemaPseudoObject.cpp
  cfe/trunk/lib/Sema/SemaStmt.cpp

Index: cfe/trunk/include/clang/Sema/SemaLambda.h
===
--- cfe/trunk/include/clang/Sema/SemaLambda.h
+++ cfe/trunk/include/clang/Sema/SemaLambda.h
@@ -15,9 +15,13 @@
 
 #ifndef LLVM_CLANG_SEMA_SEMALAMBDA_H
 #define LLVM_CLANG_SEMA_SEMALAMBDA_H
+
 #include "clang/AST/ASTLambda.h"
-#include "clang/Sema/ScopeInfo.h"
+
 namespace clang {
+namespace sema {
+class FunctionScopeInfo;
+}
 class Sema;
 
 /// \brief Examines the FunctionScopeInfo stack to determine the nearest
Index: cfe/trunk/include/clang/Sema/Sema.h
===
--- cfe/trunk/include/clang/Sema/Sema.h
+++ cfe/trunk/include/clang/Sema/Sema.h
@@ -30,7 +30,6 @@
 #include "clang/AST/TypeLoc.h"
 #include "clang/AST/TypeOrdering.h"
 #include "clang/Basic/ExpressionTraits.h"
-#include "clang/Basic/LangOptions.h"
 #include "clang/Basic/Module.h"
 #include "clang/Basic/OpenMPKinds.h"
 #include "clang/Basic/PragmaKinds.h"
@@ -45,7 +44,6 @@
 #include "clang/Sema/ObjCMethodList.h"
 #include "clang/Sema/Ownership.h"
 #include "clang/Sema/Scope.h"
-#include "clang/Sema/ScopeInfo.h"
 #include "clang/Sema/TypoCorrection.h"
 #include "clang/Sema/Weak.h"
 #include "llvm/ADT/ArrayRef.h"
@@ -201,6 +199,7 @@
 namespace sema {
   class AccessedEntity;
   class BlockScopeInfo;
+  class Capture;
   class CapturedRegionScopeInfo;
   class CapturingScopeInfo;
   class CompoundScopeInfo;
@@ -1322,23 +1321,7 @@
 return FunctionScopes.back();
   }
 
-  sema::FunctionScopeInfo *getEnclosingFunction() const {
-if (FunctionScopes.empty())
-  return nullptr;
-
-for (int e = FunctionScopes.size()-1; e >= 0; --e) {
-  if (isa(FunctionScopes[e]))
-continue;
-  return FunctionScopes[e];
-}
-return nullptr;
-  }
-
-  template 
-  void recordUseOfEvaluatedWeak(const ExprT *E, bool IsRead=true) {
-if (!isUnevaluatedContext())
-  getCurFunction()->recordUseOfWeak(E, IsRead);
-  }
+  sema::FunctionScopeInfo *getEnclosingFunction() const;
 
   void PushCompoundScope(bool IsStmtExpr);
   void PopCompoundScope();
@@ -5553,10 +5536,10 @@
  Scope *CurScope);
 
   /// \brief Does copying/destroying the captured variable have side effects?
-  bool CaptureHasSideEffects(const sema::LambdaScopeInfo::Capture );
+  bool CaptureHasSideEffects(const sema::Capture );
 
   /// \brief Diagnose if an explicit lambda capture is unused.
-  void DiagnoseUnusedLambdaCapture(const sema::LambdaScopeInfo::Capture );
+  void DiagnoseUnusedLambdaCapture(const sema::Capture );
 
   /// \brief Complete a lambda-expression having processed and attached the
   /// lambda body.
Index: cfe/trunk/include/clang/Sema/ScopeInfo.h
===
--- cfe/trunk/include/clang/Sema/ScopeInfo.h
+++ cfe/trunk/include/clang/Sema/ScopeInfo.h
@@ -469,144 +469,144 @@
   void Clear();
 };
 
-class CapturingScopeInfo : public FunctionScopeInfo {
-protected:
-  CapturingScopeInfo(const CapturingScopeInfo&) = default;
+class Capture {
+  // There are three categories of capture: capturing 'this', capturing
+  // local variables, and C++1y initialized captures (which can have an
+  // arbitrary initializer, and don't really capture in the traditional
+  // sense at all).
+  //
+  // There are three ways to capture a local variable:
+  //  - capture by copy in the C++11 sense,
+  //  - capture by reference in the C++11 sense, and
+  //  - __block capture.
+  // Lambdas explicitly specify capture by copy or capture by reference.
+  // For blocks, __block capture applies to variables with that annotation,
+  // variables of reference type are captured by reference, and other
+  // variables are captured by copy.
+  enum CaptureKind {
+Cap_ByCopy, Cap_ByRef, Cap_Block, Cap_VLA
+  };
+  enum {
+IsNestedCapture = 0x1,
+IsThisCaptured = 0x2
+  };
+
+  /// The variable being captured (if we are not capturing 'this') and whether
+  /// this is a nested capture, and whether we are capturing 'this'
+  llvm::PointerIntPair VarAndNestedAndThis;
+
+  /// Expression to initialize a field 

r326957 - Avoid including ScopeInfo.h from Sema.h

2018-03-07 Thread Reid Kleckner via cfe-commits
Author: rnk
Date: Wed Mar  7 14:48:35 2018
New Revision: 326957

URL: http://llvm.org/viewvc/llvm-project?rev=326957=rev
Log:
Avoid including ScopeInfo.h from Sema.h

Summary:
This provides no measurable build speedup, but it reinstates an
optimization from r112038 that was lost in r179618.  It requires moving
CapturedScopeInfo::Capture out to clang::sema, which might be too
general since we have plenty of other Capture records in BlockDecl and
other AST nodes.

Reviewers: rjmccall

Subscribers: cfe-commits

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

Modified:
cfe/trunk/include/clang/Sema/ScopeInfo.h
cfe/trunk/include/clang/Sema/Sema.h
cfe/trunk/include/clang/Sema/SemaLambda.h
cfe/trunk/lib/Sema/Sema.cpp
cfe/trunk/lib/Sema/SemaCoroutine.cpp
cfe/trunk/lib/Sema/SemaDecl.cpp
cfe/trunk/lib/Sema/SemaDeclAttr.cpp
cfe/trunk/lib/Sema/SemaExpr.cpp
cfe/trunk/lib/Sema/SemaExprMember.cpp
cfe/trunk/lib/Sema/SemaLambda.cpp
cfe/trunk/lib/Sema/SemaPseudoObject.cpp
cfe/trunk/lib/Sema/SemaStmt.cpp

Modified: cfe/trunk/include/clang/Sema/ScopeInfo.h
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Sema/ScopeInfo.h?rev=326957=326956=326957=diff
==
--- cfe/trunk/include/clang/Sema/ScopeInfo.h (original)
+++ cfe/trunk/include/clang/Sema/ScopeInfo.h Wed Mar  7 14:48:35 2018
@@ -469,6 +469,132 @@ public:
   void Clear();
 };
 
+class Capture {
+  // There are three categories of capture: capturing 'this', capturing
+  // local variables, and C++1y initialized captures (which can have an
+  // arbitrary initializer, and don't really capture in the traditional
+  // sense at all).
+  //
+  // There are three ways to capture a local variable:
+  //  - capture by copy in the C++11 sense,
+  //  - capture by reference in the C++11 sense, and
+  //  - __block capture.
+  // Lambdas explicitly specify capture by copy or capture by reference.
+  // For blocks, __block capture applies to variables with that annotation,
+  // variables of reference type are captured by reference, and other
+  // variables are captured by copy.
+  enum CaptureKind {
+Cap_ByCopy, Cap_ByRef, Cap_Block, Cap_VLA
+  };
+  enum {
+IsNestedCapture = 0x1,
+IsThisCaptured = 0x2
+  };
+
+  /// The variable being captured (if we are not capturing 'this') and whether
+  /// this is a nested capture, and whether we are capturing 'this'
+  llvm::PointerIntPair VarAndNestedAndThis;
+
+  /// Expression to initialize a field of the given type, and the kind of
+  /// capture (if this is a capture and not an init-capture). The expression
+  /// is only required if we are capturing ByVal and the variable's type has
+  /// a non-trivial copy constructor.
+  llvm::PointerIntPair InitExprAndCaptureKind;
+
+  /// \brief The source location at which the first capture occurred.
+  SourceLocation Loc;
+
+  /// \brief The location of the ellipsis that expands a parameter pack.
+  SourceLocation EllipsisLoc;
+
+  /// \brief The type as it was captured, which is in effect the type of the
+  /// non-static data member that would hold the capture.
+  QualType CaptureType;
+
+  /// \brief Whether an explicit capture has been odr-used in the body of the
+  /// lambda.
+  bool ODRUsed = false;
+
+  /// \brief Whether an explicit capture has been non-odr-used in the body of
+  /// the lambda.
+  bool NonODRUsed = false;
+
+public:
+  Capture(VarDecl *Var, bool Block, bool ByRef, bool IsNested,
+  SourceLocation Loc, SourceLocation EllipsisLoc,
+  QualType CaptureType, Expr *Cpy)
+  : VarAndNestedAndThis(Var, IsNested ? IsNestedCapture : 0),
+InitExprAndCaptureKind(
+Cpy, !Var ? Cap_VLA : Block ? Cap_Block : ByRef ? Cap_ByRef
+: Cap_ByCopy),
+Loc(Loc), EllipsisLoc(EllipsisLoc), CaptureType(CaptureType) {}
+
+  enum IsThisCapture { ThisCapture };
+  Capture(IsThisCapture, bool IsNested, SourceLocation Loc,
+  QualType CaptureType, Expr *Cpy, const bool ByCopy)
+  : VarAndNestedAndThis(
+nullptr, (IsThisCaptured | (IsNested ? IsNestedCapture : 0))),
+InitExprAndCaptureKind(Cpy, ByCopy ? Cap_ByCopy : Cap_ByRef),
+Loc(Loc), CaptureType(CaptureType) {}
+
+  bool isThisCapture() const {
+return VarAndNestedAndThis.getInt() & IsThisCaptured;
+  }
+
+  bool isVariableCapture() const {
+return !isThisCapture() && !isVLATypeCapture();
+  }
+
+  bool isCopyCapture() const {
+return InitExprAndCaptureKind.getInt() == Cap_ByCopy;
+  }
+
+  bool isReferenceCapture() const {
+return InitExprAndCaptureKind.getInt() == Cap_ByRef;
+  }
+
+  bool isBlockCapture() const {
+return InitExprAndCaptureKind.getInt() == Cap_Block;
+  }
+
+  bool isVLATypeCapture() const {
+return InitExprAndCaptureKind.getInt() == Cap_VLA;
+  }
+
+  bool isNested() const {
+return 

[PATCH] D44221: Avoid including ScopeInfo.h from Sema.h

2018-03-07 Thread Reid Kleckner via Phabricator via cfe-commits
rnk updated this revision to Diff 137487.
rnk added a comment.

- remove Sema::recordEvaluatedWeakUse to fix Linux build


https://reviews.llvm.org/D44221

Files:
  clang/include/clang/Sema/ScopeInfo.h
  clang/include/clang/Sema/Sema.h
  clang/include/clang/Sema/SemaLambda.h
  clang/lib/Sema/Sema.cpp
  clang/lib/Sema/SemaCoroutine.cpp
  clang/lib/Sema/SemaDecl.cpp
  clang/lib/Sema/SemaDeclAttr.cpp
  clang/lib/Sema/SemaExpr.cpp
  clang/lib/Sema/SemaExprMember.cpp
  clang/lib/Sema/SemaLambda.cpp
  clang/lib/Sema/SemaPseudoObject.cpp
  clang/lib/Sema/SemaStmt.cpp

Index: clang/lib/Sema/SemaStmt.cpp
===
--- clang/lib/Sema/SemaStmt.cpp
+++ clang/lib/Sema/SemaStmt.cpp
@@ -4040,32 +4040,29 @@
   return RD;
 }
 
-static void buildCapturedStmtCaptureList(
-SmallVectorImpl ,
-SmallVectorImpl ,
-ArrayRef Candidates) {
-
-  typedef ArrayRef::const_iterator CaptureIter;
-  for (CaptureIter Cap = Candidates.begin(); Cap != Candidates.end(); ++Cap) {
-
-if (Cap->isThisCapture()) {
-  Captures.push_back(CapturedStmt::Capture(Cap->getLocation(),
+static void
+buildCapturedStmtCaptureList(SmallVectorImpl ,
+ SmallVectorImpl ,
+ ArrayRef Candidates) {
+  for (const sema::Capture  : Candidates) {
+if (Cap.isThisCapture()) {
+  Captures.push_back(CapturedStmt::Capture(Cap.getLocation(),
CapturedStmt::VCK_This));
-  CaptureInits.push_back(Cap->getInitExpr());
+  CaptureInits.push_back(Cap.getInitExpr());
   continue;
-} else if (Cap->isVLATypeCapture()) {
+} else if (Cap.isVLATypeCapture()) {
   Captures.push_back(
-  CapturedStmt::Capture(Cap->getLocation(), CapturedStmt::VCK_VLAType));
+  CapturedStmt::Capture(Cap.getLocation(), CapturedStmt::VCK_VLAType));
   CaptureInits.push_back(nullptr);
   continue;
 }
 
-Captures.push_back(CapturedStmt::Capture(Cap->getLocation(),
- Cap->isReferenceCapture()
+Captures.push_back(CapturedStmt::Capture(Cap.getLocation(),
+ Cap.isReferenceCapture()
  ? CapturedStmt::VCK_ByRef
  : CapturedStmt::VCK_ByCopy,
- Cap->getVariable()));
-CaptureInits.push_back(Cap->getInitExpr());
+ Cap.getVariable()));
+CaptureInits.push_back(Cap.getInitExpr());
   }
 }
 
Index: clang/lib/Sema/SemaPseudoObject.cpp
===
--- clang/lib/Sema/SemaPseudoObject.cpp
+++ clang/lib/Sema/SemaPseudoObject.cpp
@@ -965,11 +965,11 @@
 }
 
 ExprResult ObjCPropertyOpBuilder::complete(Expr *SyntacticForm) {
-  if (isWeakProperty() &&
+  if (isWeakProperty() && !S.isUnevaluatedContext() &&
   !S.Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
  SyntacticForm->getLocStart()))
-S.recordUseOfEvaluatedWeak(SyntacticRefExpr,
-   SyntacticRefExpr->isMessagingGetter());
+S.getCurFunction()->recordUseOfWeak(SyntacticRefExpr,
+SyntacticRefExpr->isMessagingGetter());
 
   return PseudoOpBuilder::complete(SyntacticForm);
 }
Index: clang/lib/Sema/SemaLambda.cpp
===
--- clang/lib/Sema/SemaLambda.cpp
+++ clang/lib/Sema/SemaLambda.cpp
@@ -1388,8 +1388,9 @@
   Class->addDecl(Conversion);
 }
 
-static ExprResult performLambdaVarCaptureInitialization(
-Sema , const LambdaScopeInfo::Capture , FieldDecl *Field) {
+static ExprResult performLambdaVarCaptureInitialization(Sema ,
+const Capture ,
+FieldDecl *Field) {
   assert(Capture.isVariableCapture() && "not a variable capture");
 
   auto *Var = Capture.getVariable();
@@ -1443,7 +1444,7 @@
   llvm_unreachable("Unknown implicit capture style");
 }
 
-bool Sema::CaptureHasSideEffects(const LambdaScopeInfo::Capture ) {
+bool Sema::CaptureHasSideEffects(const Capture ) {
   if (!From.isVLATypeCapture()) {
 Expr *Init = From.getInitExpr();
 if (Init && Init->HasSideEffects(Context))
@@ -1468,7 +1469,7 @@
   return false;
 }
 
-void Sema::DiagnoseUnusedLambdaCapture(const LambdaScopeInfo::Capture ) {
+void Sema::DiagnoseUnusedLambdaCapture(const Capture ) {
   if (CaptureHasSideEffects(From))
 return;
 
@@ -1523,7 +1524,7 @@
 // Translate captures.
 auto CurField = Class->field_begin();
 for (unsigned I = 0, N = LSI->Captures.size(); I != N; ++I, ++CurField) {
-  const LambdaScopeInfo::Capture  = LSI->Captures[I];
+  const Capture  = LSI->Captures[I];
   assert(!From.isBlockCapture() && "Cannot 

[PATCH] D44131: [analyzer] Support temporaries conjured by conservatively evaluated functions.

2018-03-07 Thread George Karpenkov via Phabricator via cfe-commits
george.karpenkov accepted this revision.
george.karpenkov added a comment.
This revision is now accepted and ready to land.

LGTM


https://reviews.llvm.org/D44131



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


[PATCH] D44226: [clangd] Add -log-lsp-to-stderr option

2018-03-07 Thread Simon Marchi via Phabricator via cfe-commits
simark added a comment.

In https://reviews.llvm.org/D44226#1030625, @ilya-biryukov wrote:

> I would vouch for adding a log level instead. It's a very well understood 
> concept that certainly covers this use-case and can be useful in other places.
>  WDYT?


I agree.  How would you prefer the flags to look like?

- --log-level {debug,info,warning,error} (warning being the default if not 
specified)
- Use -v multiple times to be more verbose: "-v" to show info, "-v -v" to show 
debug.  Without -v, we show warnings and errors.
- something else?


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D44226



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


[clang-tools-extra] r326954 - [Documentation] Fix Clang-tidy checks list broken in r326909.

2018-03-07 Thread Eugene Zelenko via cfe-commits
Author: eugenezelenko
Date: Wed Mar  7 14:30:50 2018
New Revision: 326954

URL: http://llvm.org/viewvc/llvm-project?rev=326954=rev
Log:
[Documentation] Fix Clang-tidy checks list broken in r326909.

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

Modified: clang-tools-extra/trunk/docs/clang-tidy/checks/list.rst
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/docs/clang-tidy/checks/list.rst?rev=326954=326953=326954=diff
==
--- clang-tools-extra/trunk/docs/clang-tidy/checks/list.rst (original)
+++ clang-tools-extra/trunk/docs/clang-tidy/checks/list.rst Wed Mar  7 14:30:50 
2018
@@ -197,6 +197,7 @@ Clang-Tidy Checks
performance-type-promotion-in-math-fn
performance-unnecessary-copy-initialization
performance-unnecessary-value-param
+   portability-simd-intrinsics
readability-avoid-const-params-in-decls
readability-braces-around-statements
readability-container-size-empty
@@ -218,7 +219,6 @@ Clang-Tidy Checks
readability-redundant-smartptr-get
readability-redundant-string-cstr
readability-redundant-string-init
-   readability-simd-intrinsics
readability-simplify-boolean-expr
readability-static-accessed-through-instance
readability-static-definition-in-anonymous-namespace


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


[PATCH] D43847: [clang-tidy] Add check: replace string::find(...) == 0 with absl::StartsWith

2018-03-07 Thread Niko Weh via Phabricator via cfe-commits
niko added a comment.

If this is OK as it is, can someone with commit access push this? Thanks!


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D43847



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


[PATCH] D44226: [clangd] Add -log-lsp-to-stderr option

2018-03-07 Thread Ilya Biryukov via Phabricator via cfe-commits
ilya-biryukov added a comment.

I would vouch for adding a log level instead. It's a very well understood 
concept that certainly covers this use-case and can be useful in other places.
WDYT?


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D44226



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


[PATCH] D44172: [analyzer] [PointerArithChecker] do not warn on indexes into vector types

2018-03-07 Thread George Karpenkov via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rC326952: [analyzer] [PointerArithChecker] do not warn on 
indexes into vector types (authored by george.karpenkov, committed by ).
Herald added a subscriber: cfe-commits.

Repository:
  rC Clang

https://reviews.llvm.org/D44172

Files:
  lib/StaticAnalyzer/Checkers/PointerArithChecker.cpp
  test/Analysis/ptr-arith.c


Index: lib/StaticAnalyzer/Checkers/PointerArithChecker.cpp
===
--- lib/StaticAnalyzer/Checkers/PointerArithChecker.cpp
+++ lib/StaticAnalyzer/Checkers/PointerArithChecker.cpp
@@ -308,6 +308,10 @@
   // Indexing with 0 is OK.
   if (Idx.isZeroConstant())
 return;
+
+  // Indexing vector-type expressions is also OK.
+  if (SubsExpr->getBase()->getType()->isVectorType())
+return;
   reportPointerArithMisuse(SubsExpr->getBase(), C);
 }
 
Index: test/Analysis/ptr-arith.c
===
--- test/Analysis/ptr-arith.c
+++ test/Analysis/ptr-arith.c
@@ -347,3 +347,9 @@
   a[0] = 0;
 label:;
 }
+
+typedef __attribute__((__ext_vector_type__(2))) float simd_float2;
+float test_nowarning_on_vector_deref() {
+  simd_float2 x = {0, 1};
+  return x[1]; // no-warning
+}


Index: lib/StaticAnalyzer/Checkers/PointerArithChecker.cpp
===
--- lib/StaticAnalyzer/Checkers/PointerArithChecker.cpp
+++ lib/StaticAnalyzer/Checkers/PointerArithChecker.cpp
@@ -308,6 +308,10 @@
   // Indexing with 0 is OK.
   if (Idx.isZeroConstant())
 return;
+
+  // Indexing vector-type expressions is also OK.
+  if (SubsExpr->getBase()->getType()->isVectorType())
+return;
   reportPointerArithMisuse(SubsExpr->getBase(), C);
 }
 
Index: test/Analysis/ptr-arith.c
===
--- test/Analysis/ptr-arith.c
+++ test/Analysis/ptr-arith.c
@@ -347,3 +347,9 @@
   a[0] = 0;
 label:;
 }
+
+typedef __attribute__((__ext_vector_type__(2))) float simd_float2;
+float test_nowarning_on_vector_deref() {
+  simd_float2 x = {0, 1};
+  return x[1]; // no-warning
+}
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D44183: [analyzer] Don't crash with assertion failure on structured bindings

2018-03-07 Thread George Karpenkov via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rC326951: [analyzer] Dont crash with assertion failure 
on structured bindings (authored by george.karpenkov, committed by ).
Herald added a subscriber: cfe-commits.

Changed prior to commit:
  https://reviews.llvm.org/D44183?vs=137304=137479#toc

Repository:
  rC Clang

https://reviews.llvm.org/D44183

Files:
  lib/StaticAnalyzer/Core/ExprEngine.cpp
  test/Analysis/structured_bindings.cc


Index: test/Analysis/structured_bindings.cc
===
--- test/Analysis/structured_bindings.cc
+++ test/Analysis/structured_bindings.cc
@@ -0,0 +1,10 @@
+// RUN: %clang_analyze_cc1 -std=c++17 -analyzer-checker=core -verify %s
+
+// expected-no-diagnostics
+struct s { int a; };
+int foo() {
+auto[a] = s{1}; // FIXME: proper modelling
+if (a) {
+}
+}
+
Index: lib/StaticAnalyzer/Core/ExprEngine.cpp
===
--- lib/StaticAnalyzer/Core/ExprEngine.cpp
+++ lib/StaticAnalyzer/Core/ExprEngine.cpp
@@ -2463,7 +2463,12 @@
   currBldrCtx->blockCount());
 state = state->assume(V.castAs(), true);
 Bldr.generateNode(Ex, Pred, state->BindExpr(Ex, LCtx, V), nullptr,
- ProgramPoint::PostLValueKind);
+  ProgramPoint::PostLValueKind);
+return;
+  }
+  if (const auto* BD = dyn_cast(D)) {
+// FIXME: proper support for bound declarations.
+// For now, let's just prevent crashing.
 return;
   }
 


Index: test/Analysis/structured_bindings.cc
===
--- test/Analysis/structured_bindings.cc
+++ test/Analysis/structured_bindings.cc
@@ -0,0 +1,10 @@
+// RUN: %clang_analyze_cc1 -std=c++17 -analyzer-checker=core -verify %s
+
+// expected-no-diagnostics
+struct s { int a; };
+int foo() {
+auto[a] = s{1}; // FIXME: proper modelling
+if (a) {
+}
+}
+
Index: lib/StaticAnalyzer/Core/ExprEngine.cpp
===
--- lib/StaticAnalyzer/Core/ExprEngine.cpp
+++ lib/StaticAnalyzer/Core/ExprEngine.cpp
@@ -2463,7 +2463,12 @@
   currBldrCtx->blockCount());
 state = state->assume(V.castAs(), true);
 Bldr.generateNode(Ex, Pred, state->BindExpr(Ex, LCtx, V), nullptr,
-		  ProgramPoint::PostLValueKind);
+  ProgramPoint::PostLValueKind);
+return;
+  }
+  if (const auto* BD = dyn_cast(D)) {
+// FIXME: proper support for bound declarations.
+// For now, let's just prevent crashing.
 return;
   }
 
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


r326952 - [analyzer] [PointerArithChecker] do not warn on indexes into vector types

2018-03-07 Thread George Karpenkov via cfe-commits
Author: george.karpenkov
Date: Wed Mar  7 14:20:39 2018
New Revision: 326952

URL: http://llvm.org/viewvc/llvm-project?rev=326952=rev
Log:
[analyzer] [PointerArithChecker] do not warn on indexes into vector types

rdar://35041502

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

Modified:
cfe/trunk/lib/StaticAnalyzer/Checkers/PointerArithChecker.cpp
cfe/trunk/test/Analysis/ptr-arith.c

Modified: cfe/trunk/lib/StaticAnalyzer/Checkers/PointerArithChecker.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/StaticAnalyzer/Checkers/PointerArithChecker.cpp?rev=326952=326951=326952=diff
==
--- cfe/trunk/lib/StaticAnalyzer/Checkers/PointerArithChecker.cpp (original)
+++ cfe/trunk/lib/StaticAnalyzer/Checkers/PointerArithChecker.cpp Wed Mar  7 
14:20:39 2018
@@ -308,6 +308,10 @@ void PointerArithChecker::checkPreStmt(c
   // Indexing with 0 is OK.
   if (Idx.isZeroConstant())
 return;
+
+  // Indexing vector-type expressions is also OK.
+  if (SubsExpr->getBase()->getType()->isVectorType())
+return;
   reportPointerArithMisuse(SubsExpr->getBase(), C);
 }
 

Modified: cfe/trunk/test/Analysis/ptr-arith.c
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/Analysis/ptr-arith.c?rev=326952=326951=326952=diff
==
--- cfe/trunk/test/Analysis/ptr-arith.c (original)
+++ cfe/trunk/test/Analysis/ptr-arith.c Wed Mar  7 14:20:39 2018
@@ -347,3 +347,9 @@ void test_no_crash_on_pointer_to_label()
   a[0] = 0;
 label:;
 }
+
+typedef __attribute__((__ext_vector_type__(2))) float simd_float2;
+float test_nowarning_on_vector_deref() {
+  simd_float2 x = {0, 1};
+  return x[1]; // no-warning
+}


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


r326951 - [analyzer] Don't crash with assertion failure on structured bindings

2018-03-07 Thread George Karpenkov via cfe-commits
Author: george.karpenkov
Date: Wed Mar  7 14:20:35 2018
New Revision: 326951

URL: http://llvm.org/viewvc/llvm-project?rev=326951=rev
Log:
[analyzer] Don't crash with assertion failure on structured bindings

Proper modeling still remains to be done.
Note that BindingDecl#getHoldingVar() is almost always null, and this
should probably be handled by dealing with DecompositionDecl beforehand.

rdar://36852163

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

Added:
cfe/trunk/test/Analysis/structured_bindings.cc
Modified:
cfe/trunk/lib/StaticAnalyzer/Core/ExprEngine.cpp

Modified: cfe/trunk/lib/StaticAnalyzer/Core/ExprEngine.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/StaticAnalyzer/Core/ExprEngine.cpp?rev=326951=326950=326951=diff
==
--- cfe/trunk/lib/StaticAnalyzer/Core/ExprEngine.cpp (original)
+++ cfe/trunk/lib/StaticAnalyzer/Core/ExprEngine.cpp Wed Mar  7 14:20:35 2018
@@ -2463,7 +2463,12 @@ void ExprEngine::VisitCommonDeclRefExpr(
   currBldrCtx->blockCount());
 state = state->assume(V.castAs(), true);
 Bldr.generateNode(Ex, Pred, state->BindExpr(Ex, LCtx, V), nullptr,
- ProgramPoint::PostLValueKind);
+  ProgramPoint::PostLValueKind);
+return;
+  }
+  if (const auto* BD = dyn_cast(D)) {
+// FIXME: proper support for bound declarations.
+// For now, let's just prevent crashing.
 return;
   }
 

Added: cfe/trunk/test/Analysis/structured_bindings.cc
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/Analysis/structured_bindings.cc?rev=326951=auto
==
--- cfe/trunk/test/Analysis/structured_bindings.cc (added)
+++ cfe/trunk/test/Analysis/structured_bindings.cc Wed Mar  7 14:20:35 2018
@@ -0,0 +1,10 @@
+// RUN: %clang_analyze_cc1 -std=c++17 -analyzer-checker=core -verify %s
+
+// expected-no-diagnostics
+struct s { int a; };
+int foo() {
+auto[a] = s{1}; // FIXME: proper modelling
+if (a) {
+}
+}
+


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


[PATCH] D44226: [clangd] Add -log-lsp-to-stderr option

2018-03-07 Thread Simon Marchi via Phabricator via cfe-commits
simark updated this revision to Diff 137478.
simark added a comment.

Changed -log-to-stderr to -log-lsp-to-stderr

The first version disabled a bit too much, this version removes the LSP
communication logging in a more fine grained way.


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D44226

Files:
  clangd/ClangdLSPServer.cpp
  clangd/ClangdLSPServer.h
  clangd/JSONRPCDispatcher.cpp
  clangd/JSONRPCDispatcher.h
  clangd/tool/ClangdMain.cpp

Index: clangd/tool/ClangdMain.cpp
===
--- clangd/tool/ClangdMain.cpp
+++ clangd/tool/ClangdMain.cpp
@@ -77,6 +77,11 @@
 llvm::cl::init(JSONStreamStyle::Standard));
 
 static llvm::cl::opt
+LogLspToStderr("log-lsp-to-stderr",
+   llvm::cl::desc("Output LSP communication on stderr"),
+   llvm::cl::init(false));
+
+static llvm::cl::opt
 PrettyPrint("pretty", llvm::cl::desc("Pretty-print JSON output"),
 llvm::cl::init(false));
 
@@ -190,7 +195,7 @@
 
   JSONOutput Out(llvm::outs(), llvm::errs(),
  InputMirrorStream ? InputMirrorStream.getPointer() : nullptr,
- PrettyPrint);
+ LogLspToStderr, PrettyPrint);
 
   clangd::LoggingSession LoggingSession(Out);
 
@@ -238,5 +243,7 @@
   llvm::set_thread_name("clangd.main");
   // Change stdin to binary to not lose \r\n on windows.
   llvm::sys::ChangeStdinToBinary();
-  return LSPServer.run(std::cin, InputStyle) ? 0 : NoShutdownRequestErrorCode;
+  return LSPServer.run(std::cin, InputStyle, LogLspToStderr)
+ ? 0
+ : NoShutdownRequestErrorCode;
 }
Index: clangd/JSONRPCDispatcher.h
===
--- clangd/JSONRPCDispatcher.h
+++ clangd/JSONRPCDispatcher.h
@@ -30,8 +30,10 @@
   // JSONOutput now that we pass Context everywhere.
 public:
   JSONOutput(llvm::raw_ostream , llvm::raw_ostream ,
- llvm::raw_ostream *InputMirror = nullptr, bool Pretty = false)
-  : Pretty(Pretty), Outs(Outs), Logs(Logs), InputMirror(InputMirror) {}
+ llvm::raw_ostream *InputMirror = nullptr,
+ bool LogLspToStderr = false, bool Pretty = false)
+  : LogLspToStderr(LogLspToStderr), Pretty(Pretty), Outs(Outs), Logs(Logs),
+InputMirror(InputMirror) {}
 
   /// Emit a JSONRPC message.
   void writeMessage(const json::Expr );
@@ -44,6 +46,9 @@
   /// Unlike other methods of JSONOutput, mirrorInput is not thread-safe.
   void mirrorInput(const Twine );
 
+  /// Whether to output all LSP communication to stderr.
+  const bool LogLspToStderr;
+
   // Whether output should be pretty-printed.
   const bool Pretty;
 
@@ -104,7 +109,8 @@
 /// replacements of \r\n with \n.
 void runLanguageServerLoop(std::istream , JSONOutput ,
JSONStreamStyle InputStyle,
-   JSONRPCDispatcher , bool );
+   JSONRPCDispatcher , bool LogLspToStderr,
+   bool );
 
 } // namespace clangd
 } // namespace clang
Index: clangd/JSONRPCDispatcher.cpp
===
--- clangd/JSONRPCDispatcher.cpp
+++ clangd/JSONRPCDispatcher.cpp
@@ -66,7 +66,9 @@
 Outs << "Content-Length: " << S.size() << "\r\n\r\n" << S;
 Outs.flush();
   }
-  log(llvm::Twine("--> ") + S);
+
+  if (LogLspToStderr)
+log(llvm::Twine("--> ") + S);
 }
 
 void JSONOutput::log(const Twine ) {
@@ -299,14 +301,17 @@
 void clangd::runLanguageServerLoop(std::istream , JSONOutput ,
JSONStreamStyle InputStyle,
JSONRPCDispatcher ,
-   bool ) {
+   bool LogLspToStderr, bool ) {
   auto  =
   (InputStyle == Delimited) ? readDelimitedMessage : readStandardMessage;
   while (In.good()) {
 if (auto JSON = ReadMessage(In, Out)) {
   if (auto Doc = json::parse(*JSON)) {
-// Log the formatted message.
-log(llvm::formatv(Out.Pretty ? "<-- {0:2}\n" : "<-- {0}\n", *Doc));
+if (LogLspToStderr) {
+  // Log the formatted message.
+  log(llvm::formatv(Out.Pretty ? "<-- {0:2}\n" : "<-- {0}\n", *Doc));
+}
+
 // Finally, execute the action for this JSON message.
 if (!Dispatcher.call(*Doc, Out))
   log("JSON dispatch failed!\n");
Index: clangd/ClangdLSPServer.h
===
--- clangd/ClangdLSPServer.h
+++ clangd/ClangdLSPServer.h
@@ -42,7 +42,8 @@
   ///
   /// \return Wether we received a 'shutdown' request before an 'exit' request
   bool run(std::istream ,
-   JSONStreamStyle InputStyle = JSONStreamStyle::Standard);
+   JSONStreamStyle InputStyle = JSONStreamStyle::Standard,
+   bool LogLspToStderr = false);
 
 private:
   // Implement DiagnosticsConsumer.
Index: 

[PATCH] D43625: [OpenMP] Remove implicit data sharing code gen that aims to use device shared memory

2018-03-07 Thread Phabricator via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rC326948: [OpenMP] Remove implicit data sharing code gen that 
aims to use device shared… (authored by gbercea, committed by ).

Changed prior to commit:
  https://reviews.llvm.org/D43625?vs=136570=137475#toc

Repository:
  rC Clang

https://reviews.llvm.org/D43625

Files:
  lib/CodeGen/CGOpenMPRuntimeNVPTX.cpp
  lib/CodeGen/CGOpenMPRuntimeNVPTX.h
  test/OpenMP/nvptx_data_sharing.cpp
  test/OpenMP/nvptx_parallel_codegen.cpp
  test/OpenMP/nvptx_target_teams_codegen.cpp

Index: test/OpenMP/nvptx_parallel_codegen.cpp
===
--- test/OpenMP/nvptx_parallel_codegen.cpp
+++ test/OpenMP/nvptx_parallel_codegen.cpp
@@ -78,7 +78,7 @@
   //
   // CHECK: [[AWAIT_WORK]]
   // CHECK: call void @llvm.nvvm.barrier0()
-  // CHECK: [[KPR:%.+]] = call i1 @__kmpc_kernel_parallel(i8** [[OMP_WORK_FN]],
+  // CHECK: [[KPR:%.+]] = call i1 @__kmpc_kernel_parallel(i8** [[OMP_WORK_FN]]
   // CHECK: [[KPRB:%.+]] = zext i1 [[KPR]] to i8
   // store i8 [[KPRB]], i8* [[OMP_EXEC_STATUS]], align 1
   // CHECK: [[WORK:%.+]] = load i8*, i8** [[OMP_WORK_FN]],
@@ -92,20 +92,20 @@
   //
   // CHECK: [[EXEC_PARALLEL]]
   // CHECK: [[WF1:%.+]] = load i8*, i8** [[OMP_WORK_FN]],
-  // CHECK: [[WM1:%.+]] = icmp eq i8* [[WF1]], bitcast (void (i16, i32, i8**)* [[PARALLEL_FN1:@.+]]_wrapper to i8*)
+  // CHECK: [[WM1:%.+]] = icmp eq i8* [[WF1]], bitcast (void (i32*, i32*)* [[PARALLEL_FN1:@.+]] to i8*)
   // CHECK: br i1 [[WM1]], label {{%?}}[[EXEC_PFN1:.+]], label {{%?}}[[CHECK_NEXT1:.+]]
   //
   // CHECK: [[EXEC_PFN1]]
-  // CHECK: call void [[PARALLEL_FN1]]_wrapper(
+  // CHECK: call void [[PARALLEL_FN1]](
   // CHECK: br label {{%?}}[[TERM_PARALLEL:.+]]
   //
   // CHECK: [[CHECK_NEXT1]]
   // CHECK: [[WF2:%.+]] = load i8*, i8** [[OMP_WORK_FN]],
-  // CHECK: [[WM2:%.+]] = icmp eq i8* [[WF2]], bitcast (void (i16, i32, i8**)* [[PARALLEL_FN2:@.+]]_wrapper to i8*)
+  // CHECK: [[WM2:%.+]] = icmp eq i8* [[WF2]], bitcast (void (i32*, i32*)* [[PARALLEL_FN2:@.+]] to i8*)
   // CHECK: br i1 [[WM2]], label {{%?}}[[EXEC_PFN2:.+]], label {{%?}}[[CHECK_NEXT2:.+]]
   //
   // CHECK: [[EXEC_PFN2]]
-  // CHECK: call void [[PARALLEL_FN2]]_wrapper(
+  // CHECK: call void [[PARALLEL_FN2]](
   // CHECK: br label {{%?}}[[TERM_PARALLEL:.+]]
   //
   // CHECK: [[CHECK_NEXT2]]
@@ -152,13 +152,13 @@
   // CHECK-DAG: [[MWS:%.+]] = call i32 @llvm.nvvm.read.ptx.sreg.warpsize()
   // CHECK: [[MTMP1:%.+]] = sub i32 [[MNTH]], [[MWS]]
   // CHECK: call void @__kmpc_kernel_init(i32 [[MTMP1]]
-  // CHECK: call void @__kmpc_kernel_prepare_parallel(i8* bitcast (void (i16, i32, i8**)* [[PARALLEL_FN1]]_wrapper to i8*),
+  // CHECK: call void @__kmpc_kernel_prepare_parallel(i8* bitcast (void (i32*, i32*)* [[PARALLEL_FN1]] to i8*),
   // CHECK: call void @llvm.nvvm.barrier0()
   // CHECK: call void @llvm.nvvm.barrier0()
   // CHECK: call void @__kmpc_serialized_parallel(
   // CHECK: {{call|invoke}} void [[PARALLEL_FN3:@.+]](
   // CHECK: call void @__kmpc_end_serialized_parallel(
-  // CHECK: call void @__kmpc_kernel_prepare_parallel(i8* bitcast (void (i16, i32, i8**)* [[PARALLEL_FN2]]_wrapper to i8*),
+  // CHECK: call void @__kmpc_kernel_prepare_parallel(i8* bitcast (void (i32*, i32*)* [[PARALLEL_FN2]] to i8*),
   // CHECK: call void @llvm.nvvm.barrier0()
   // CHECK: call void @llvm.nvvm.barrier0()
   // CHECK-64-DAG: load i32, i32* [[REF_A]]
@@ -203,7 +203,7 @@
   //
   // CHECK: [[AWAIT_WORK]]
   // CHECK: call void @llvm.nvvm.barrier0()
-  // CHECK: [[KPR:%.+]] = call i1 @__kmpc_kernel_parallel(i8** [[OMP_WORK_FN]],
+  // CHECK: [[KPR:%.+]] = call i1 @__kmpc_kernel_parallel(i8** [[OMP_WORK_FN]]
   // CHECK: [[KPRB:%.+]] = zext i1 [[KPR]] to i8
   // store i8 [[KPRB]], i8* [[OMP_EXEC_STATUS]], align 1
   // CHECK: [[WORK:%.+]] = load i8*, i8** [[OMP_WORK_FN]],
@@ -217,11 +217,11 @@
   //
   // CHECK: [[EXEC_PARALLEL]]
   // CHECK: [[WF:%.+]] = load i8*, i8** [[OMP_WORK_FN]],
-  // CHECK: [[WM:%.+]] = icmp eq i8* [[WF]], bitcast (void (i16, i32, i8**)* [[PARALLEL_FN4:@.+]]_wrapper to i8*)
+  // CHECK: [[WM:%.+]] = icmp eq i8* [[WF]], bitcast (void (i32*, i32*)* [[PARALLEL_FN4:@.+]] to i8*)
   // CHECK: br i1 [[WM]], label {{%?}}[[EXEC_PFN:.+]], label {{%?}}[[CHECK_NEXT:.+]]
   //
   // CHECK: [[EXEC_PFN]]
-  // CHECK: call void [[PARALLEL_FN4]]_wrapper(
+  // CHECK: call void [[PARALLEL_FN4]](
   // CHECK: br label {{%?}}[[TERM_PARALLEL:.+]]
   //
   // CHECK: [[CHECK_NEXT]]
@@ -283,7 +283,7 @@
   // CHECK: br i1 [[CMP]], label {{%?}}[[IF_THEN:.+]], label {{%?}}[[IF_ELSE:.+]]
   //
   // CHECK: [[IF_THEN]]
-  // CHECK: call void @__kmpc_kernel_prepare_parallel(i8* bitcast (void (i16, i32, i8**)* [[PARALLEL_FN4]]_wrapper to i8*),
+  // CHECK: call void @__kmpc_kernel_prepare_parallel(i8* bitcast (void (i32*, i32*)* [[PARALLEL_FN4]] to i8*),
   // CHECK: call void @llvm.nvvm.barrier0()
   // CHECK: call void @llvm.nvvm.barrier0()
   // 

[PATCH] D37994: Implement LWG2946: More ambiguity in `string` vs. `string_view`

2018-03-07 Thread Marshall Clow via Phabricator via cfe-commits
mclow.lists updated this revision to Diff 137474.
mclow.lists added a comment.

Added the proposed resolution for https://wg21.link/lwg3075 as well, and some 
deduction guide tests for `string_view`


https://reviews.llvm.org/D37994

Files:
  include/string
  test/std/strings/basic.string/string.cons/iter_alloc_deduction.pass.cpp
  test/std/strings/basic.string/string.cons/string_view.pass.cpp
  test/std/strings/basic.string/string.cons/string_view_assignment.pass.cpp
  test/std/strings/basic.string/string.cons/string_view_deduction.fail.cpp
  test/std/strings/basic.string/string.cons/string_view_deduction.pass.cpp
  
test/std/strings/basic.string/string.modifiers/string_append/string_view.pass.cpp
  
test/std/strings/basic.string/string.modifiers/string_assign/string_view.pass.cpp
  
test/std/strings/basic.string/string.modifiers/string_insert/string_view.pass.cpp
  
test/std/strings/basic.string/string.modifiers/string_op_plus_equal/string.pass.cpp
  
test/std/strings/basic.string/string.modifiers/string_replace/iter_iter_string_view.pass.cpp
  
test/std/strings/basic.string/string.modifiers/string_replace/size_size_string_view.pass.cpp
  
test/std/strings/basic.string/string.ops/string_compare/size_size_string_view.pass.cpp
  test/std/strings/basic.string/string.ops/string_compare/string_view.pass.cpp
  
test/std/strings/basic.string/string.ops/string_find.first.not.of/string_view_size.pass.cpp
  
test/std/strings/basic.string/string.ops/string_find.first.of/string_view_size.pass.cpp
  
test/std/strings/basic.string/string.ops/string_find.last.not.of/string_view_size.pass.cpp
  
test/std/strings/basic.string/string.ops/string_find.last.of/string_view_size.pass.cpp
  test/std/strings/basic.string/string.ops/string_find/string_view_size.pass.cpp
  
test/std/strings/basic.string/string.ops/string_rfind/string_view_size.pass.cpp

Index: test/std/strings/basic.string/string.ops/string_rfind/string_view_size.pass.cpp
===
--- test/std/strings/basic.string/string.ops/string_rfind/string_view_size.pass.cpp
+++ test/std/strings/basic.string/string.ops/string_rfind/string_view_size.pass.cpp
@@ -155,5 +155,10 @@
 test0();
 test1();
 }
+//	LWG 2946
+	{
+	std::string s;
+	assert(s.rfind({"abc", 1}) == std::string::npos);
+	}
 #endif
 }
Index: test/std/strings/basic.string/string.ops/string_find.last.of/string_view_size.pass.cpp
===
--- test/std/strings/basic.string/string.ops/string_find.last.of/string_view_size.pass.cpp
+++ test/std/strings/basic.string/string.ops/string_find.last.of/string_view_size.pass.cpp
@@ -155,5 +155,10 @@
 test0();
 test1();
 }
+//	LWG 2946
+	{
+	std::string s;
+	assert(s.find_last_of({"abc", 1}) == std::string::npos);
+	}
 #endif
 }
Index: test/std/strings/basic.string/string.ops/string_find.last.not.of/string_view_size.pass.cpp
===
--- test/std/strings/basic.string/string.ops/string_find.last.not.of/string_view_size.pass.cpp
+++ test/std/strings/basic.string/string.ops/string_find.last.not.of/string_view_size.pass.cpp
@@ -155,5 +155,10 @@
 // test0();
 // test1();
 }
+//	LWG 2946
+	{
+	std::string s;
+	assert(s.find_last_not_of({"abc", 1}) == std::string::npos);
+	}
 #endif
 }
Index: test/std/strings/basic.string/string.ops/string_find.first.of/string_view_size.pass.cpp
===
--- test/std/strings/basic.string/string.ops/string_find.first.of/string_view_size.pass.cpp
+++ test/std/strings/basic.string/string.ops/string_find.first.of/string_view_size.pass.cpp
@@ -155,5 +155,10 @@
 test0();
 test1();
 }
+//	LWG 2946
+	{
+	std::string s;
+	assert(s.find_first_of({"abc", 1}) == std::string::npos);
+	}
 #endif
 }
Index: test/std/strings/basic.string/string.ops/string_find.first.not.of/string_view_size.pass.cpp
===
--- test/std/strings/basic.string/string.ops/string_find.first.not.of/string_view_size.pass.cpp
+++ test/std/strings/basic.string/string.ops/string_find.first.not.of/string_view_size.pass.cpp
@@ -155,5 +155,10 @@
 test0();
 test1();
 }
+//	LWG 2946
+	{
+	std::string s;
+	assert(s.find_first_not_of({"abc", 1}) == std::string::npos);
+	}
 #endif
 }
Index: test/std/strings/basic.string/string.ops/string_find/string_view_size.pass.cpp
===
--- test/std/strings/basic.string/string.ops/string_find/string_view_size.pass.cpp
+++ test/std/strings/basic.string/string.ops/string_find/string_view_size.pass.cpp
@@ -155,5 +155,10 @@
 test0();
 test1();
 }
+//	LWG 2946
+	{
+	std::string s;
+	assert(s.find({"abc", 1}) == std::string::npos);
+	}
 #endif
 }
Index: 

r326948 - [OpenMP] Remove implicit data sharing code gen that aims to use device shared memory

2018-03-07 Thread Gheorghe-Teodor Bercea via cfe-commits
Author: gbercea
Date: Wed Mar  7 13:59:50 2018
New Revision: 326948

URL: http://llvm.org/viewvc/llvm-project?rev=326948=rev
Log:
[OpenMP] Remove implicit data sharing code gen that aims to use device shared 
memory

Summary: Remove this scheme for now since it will be covered by another more 
generic scheme using global memory. This code will be worked into an 
optimization for the generic data sharing scheme. Removing this completely and 
then adding it via future patches will make all future data sharing patches 
cleaner.

Reviewers: ABataev, carlo.bertolli, caomhin

Reviewed By: ABataev

Subscribers: jholewinski, guansong, cfe-commits

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

Removed:
cfe/trunk/test/OpenMP/nvptx_data_sharing.cpp
Modified:
cfe/trunk/lib/CodeGen/CGOpenMPRuntimeNVPTX.cpp
cfe/trunk/lib/CodeGen/CGOpenMPRuntimeNVPTX.h
cfe/trunk/test/OpenMP/nvptx_parallel_codegen.cpp
cfe/trunk/test/OpenMP/nvptx_target_teams_codegen.cpp

Modified: cfe/trunk/lib/CodeGen/CGOpenMPRuntimeNVPTX.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/CodeGen/CGOpenMPRuntimeNVPTX.cpp?rev=326948=326947=326948=diff
==
--- cfe/trunk/lib/CodeGen/CGOpenMPRuntimeNVPTX.cpp (original)
+++ cfe/trunk/lib/CodeGen/CGOpenMPRuntimeNVPTX.cpp Wed Mar  7 13:59:50 2018
@@ -33,11 +33,11 @@ enum OpenMPRTLFunctionNVPTX {
   /// \brief Call to void __kmpc_spmd_kernel_deinit();
   OMPRTL_NVPTX__kmpc_spmd_kernel_deinit,
   /// \brief Call to void __kmpc_kernel_prepare_parallel(void
-  /// *outlined_function, void ***args, kmp_int32 nArgs, int16_t
+  /// *outlined_function, int16_t
   /// IsOMPRuntimeInitialized);
   OMPRTL_NVPTX__kmpc_kernel_prepare_parallel,
-  /// \brief Call to bool __kmpc_kernel_parallel(void **outlined_function, void
-  /// ***args, int16_t IsOMPRuntimeInitialized);
+  /// \brief Call to bool __kmpc_kernel_parallel(void **outlined_function,
+  /// int16_t IsOMPRuntimeInitialized);
   OMPRTL_NVPTX__kmpc_kernel_parallel,
   /// \brief Call to void __kmpc_kernel_end_parallel();
   OMPRTL_NVPTX__kmpc_kernel_end_parallel,
@@ -288,7 +288,6 @@ void CGOpenMPRuntimeNVPTX::emitGenericKe
   EntryFunctionState EST;
   WorkerFunctionState WST(CGM, D.getLocStart());
   Work.clear();
-  WrapperFunctionsMap.clear();
 
   // Emit target region as a standalone region.
   class NVPTXPrePostActionTy : public PrePostActionTy {
@@ -508,11 +507,8 @@ void CGOpenMPRuntimeNVPTX::emitWorkerLoo
   CGF.InitTempAlloca(ExecStatus, Bld.getInt8(/*C=*/0));
   CGF.InitTempAlloca(WorkFn, llvm::Constant::getNullValue(CGF.Int8PtrTy));
 
-  // Set up shared arguments
-  Address SharedArgs =
-  CGF.CreateDefaultAlignTempAlloca(CGF.Int8PtrPtrTy, "shared_args");
   // TODO: Optimize runtime initialization and pass in correct value.
-  llvm::Value *Args[] = {WorkFn.getPointer(), SharedArgs.getPointer(),
+  llvm::Value *Args[] = {WorkFn.getPointer(),
  /*RequiresOMPRuntime=*/Bld.getInt16(1)};
   llvm::Value *Ret = CGF.EmitRuntimeCall(
   createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_kernel_parallel), Args);
@@ -532,9 +528,6 @@ void CGOpenMPRuntimeNVPTX::emitWorkerLoo
   // Signal start of parallel region.
   CGF.EmitBlock(ExecuteBB);
 
-  // Current context
-  ASTContext  = CGF.getContext();
-
   // Process work items: outlined parallel functions.
   for (auto *W : Work) {
 // Try to match this outlined function.
@@ -550,19 +543,14 @@ void CGOpenMPRuntimeNVPTX::emitWorkerLoo
 // Execute this outlined function.
 CGF.EmitBlock(ExecuteFNBB);
 
-// Insert call to work function via shared wrapper. The shared
-// wrapper takes exactly three arguments:
-//   - the parallelism level;
-//   - the master thread ID;
-//   - the list of references to shared arguments.
-//
-// TODO: Assert that the function is a wrapper function.s
-Address Capture = CGF.EmitLoadOfPointer(SharedArgs,
-   Ctx.getPointerType(
-  Ctx.getPointerType(Ctx.VoidPtrTy)).castAs());
-emitOutlinedFunctionCall(CGF, WST.Loc, W,
- {Bld.getInt16(/*ParallelLevel=*/0),
-  getMasterThreadID(CGF), Capture.getPointer()});
+// Insert call to work function.
+// FIXME: Pass arguments to outlined function from master thread.
+auto *Fn = cast(W);
+Address ZeroAddr =
+CGF.CreateDefaultAlignTempAlloca(CGF.Int32Ty, /*Name=*/".zero.addr");
+CGF.InitTempAlloca(ZeroAddr, CGF.Builder.getInt32(/*C=*/0));
+llvm::Value *FnArgs[] = {ZeroAddr.getPointer(), ZeroAddr.getPointer()};
+emitCall(CGF, WST.Loc, Fn, FnArgs);
 
 // Go to end of parallel region.
 CGF.EmitBranch(TerminateBB);
@@ -630,10 +618,8 @@ CGOpenMPRuntimeNVPTX::createNVPTXRuntime
   }
   case OMPRTL_NVPTX__kmpc_kernel_prepare_parallel: {
 /// Build void __kmpc_kernel_prepare_parallel(
-/// void *outlined_function, void ***args, kmp_int32 nArgs, int16_t
-

[PATCH] D44223: [ms] Emit vtordisp initializers in a deterministic order.

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

lgtm




Comment at: lib/CodeGen/MicrosoftCXXABI.cpp:1207
 uint64_t ConstantVBaseOffset =
-Layout.getVBaseClassOffset(I->first).getQuantity();
+Layout.getVBaseClassOffset(VBase).getQuantity();
 

The `getVBaseClassOffset` call turns around and does the same hashtable lookup 
we just did. Let's keep the iterator around and say 
`I->second.VBaseOffset.getQuantity()`.


https://reviews.llvm.org/D44223



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


[clang-tools-extra] r326928 - do not register matcher for objc-only checks when analyzing non-objc sources to save resources

2018-03-07 Thread Yan Zhang via cfe-commits
Author: wizard
Date: Wed Mar  7 10:59:25 2018
New Revision: 326928

URL: http://llvm.org/viewvc/llvm-project?rev=326928=rev
Log:
do not register matcher for objc-only checks when analyzing non-objc sources to 
save resources

Summary: I did not put lang opt check in AvoidSpinlockCheck since OSSpinLock is 
not objc specific. We won't want to skip it when analyzing some C++ target used 
by other ObjC sources.

Reviewers: hokein, benhamilton

Reviewed By: benhamilton

Subscribers: klimek, cfe-commits

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

Modified:

clang-tools-extra/trunk/clang-tidy/google/AvoidThrowingObjCExceptionCheck.cpp
clang-tools-extra/trunk/clang-tidy/objc/AvoidNSErrorInitCheck.cpp
clang-tools-extra/trunk/clang-tidy/objc/ForbiddenSubclassingCheck.cpp
clang-tools-extra/trunk/clang-tidy/objc/PropertyDeclarationCheck.cpp

Modified: 
clang-tools-extra/trunk/clang-tidy/google/AvoidThrowingObjCExceptionCheck.cpp
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clang-tidy/google/AvoidThrowingObjCExceptionCheck.cpp?rev=326928=326927=326928=diff
==
--- 
clang-tools-extra/trunk/clang-tidy/google/AvoidThrowingObjCExceptionCheck.cpp 
(original)
+++ 
clang-tools-extra/trunk/clang-tidy/google/AvoidThrowingObjCExceptionCheck.cpp 
Wed Mar  7 10:59:25 2018
@@ -19,6 +19,11 @@ namespace google {
 namespace objc {
 
 void AvoidThrowingObjCExceptionCheck::registerMatchers(MatchFinder *Finder) {
+  // this check should only be applied to ObjC sources.
+  if (!getLangOpts().ObjC1 && !getLangOpts().ObjC2) {
+return;
+  }
+
   Finder->addMatcher(objcThrowStmt().bind("throwStmt"), this);
   Finder->addMatcher(
   objcMessageExpr(anyOf(hasSelector("raise:format:"),

Modified: clang-tools-extra/trunk/clang-tidy/objc/AvoidNSErrorInitCheck.cpp
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clang-tidy/objc/AvoidNSErrorInitCheck.cpp?rev=326928=326927=326928=diff
==
--- clang-tools-extra/trunk/clang-tidy/objc/AvoidNSErrorInitCheck.cpp (original)
+++ clang-tools-extra/trunk/clang-tidy/objc/AvoidNSErrorInitCheck.cpp Wed Mar  
7 10:59:25 2018
@@ -18,6 +18,10 @@ namespace tidy {
 namespace objc {
 
 void AvoidNSErrorInitCheck::registerMatchers(MatchFinder *Finder) {
+  // this check should only be applied to ObjC sources.
+  if (!getLangOpts().ObjC1 && !getLangOpts().ObjC2) {
+return;
+  }
   Finder->addMatcher(objcMessageExpr(hasSelector("init"),
  hasReceiverType(asString("NSError *")))
  .bind("nserrorInit"),

Modified: clang-tools-extra/trunk/clang-tidy/objc/ForbiddenSubclassingCheck.cpp
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clang-tidy/objc/ForbiddenSubclassingCheck.cpp?rev=326928=326927=326928=diff
==
--- clang-tools-extra/trunk/clang-tidy/objc/ForbiddenSubclassingCheck.cpp 
(original)
+++ clang-tools-extra/trunk/clang-tidy/objc/ForbiddenSubclassingCheck.cpp Wed 
Mar  7 10:59:25 2018
@@ -77,6 +77,10 @@ ForbiddenSubclassingCheck::ForbiddenSubc
 }
 
 void ForbiddenSubclassingCheck::registerMatchers(MatchFinder *Finder) {
+  // this check should only be applied to ObjC sources.
+  if (!getLangOpts().ObjC1 && !getLangOpts().ObjC2) {
+return;
+  }
   Finder->addMatcher(
   objcInterfaceDecl(
   isSubclassOf(

Modified: clang-tools-extra/trunk/clang-tidy/objc/PropertyDeclarationCheck.cpp
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clang-tidy/objc/PropertyDeclarationCheck.cpp?rev=326928=326927=326928=diff
==
--- clang-tools-extra/trunk/clang-tidy/objc/PropertyDeclarationCheck.cpp 
(original)
+++ clang-tools-extra/trunk/clang-tidy/objc/PropertyDeclarationCheck.cpp Wed 
Mar  7 10:59:25 2018
@@ -170,6 +170,10 @@ PropertyDeclarationCheck::PropertyDeclar
   EscapedAcronyms() {}
 
 void PropertyDeclarationCheck::registerMatchers(MatchFinder *Finder) {
+  // this check should only be applied to ObjC sources.
+  if (!getLangOpts().ObjC1 && !getLangOpts().ObjC2) {
+return;
+  }
   if (IncludeDefaultAcronyms) {
 EscapedAcronyms.reserve(llvm::array_lengthof(DefaultSpecialAcronyms) +
 SpecialAcronyms.size());


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


[PATCH] D44226: [clangd] Add -log-to-stderr option

2018-03-07 Thread Simon Marchi via Phabricator via cfe-commits
simark created this revision.
Herald added subscribers: cfe-commits, ioeric, JDevlieghere, jkorous-apple, 
ilya-biryukov, klimek.

Currently, clangd prints all the LSP communication on stderr.  While
this is good for developping, I don't think it's good as a general
default.  For example, we are integrating clangd (and other language
servers) in an IDE, and we print everything the language servers send on
their stderr on our own stderr.  Printing the whole LSP communication
adds a lot of noise.  If there are actual error messages to be printed,
then it makes sense to output them on stderr.

Also, an IDE or tool that integrates many language servers will likely
have its own way of logging LSP communication in a consistent way, so
it's better to leave it to that tool to log the LSP communication if it
wants to.

An alternative would be to introduce log levels (debug, info, warning,
error), and output LSP communications only at the debug log level.

Signed-off-by: Simon Marchi 


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D44226

Files:
  clangd/JSONRPCDispatcher.cpp
  clangd/JSONRPCDispatcher.h
  clangd/tool/ClangdMain.cpp
  test/clangd/protocol.test
  test/clangd/too_large.test

Index: test/clangd/too_large.test
===
--- test/clangd/too_large.test
+++ test/clangd/too_large.test
@@ -1,4 +1,4 @@
-# RUN: not clangd -run-synchronously < %s 2>&1 | FileCheck -check-prefix=STDERR %s
+# RUN: not clangd -run-synchronously -log-to-stderr < %s 2>&1 | FileCheck -check-prefix=STDERR %s
 # vim: fileformat=dos
 # It is absolutely vital that this file has CRLF line endings.
 #
Index: test/clangd/protocol.test
===
--- test/clangd/protocol.test
+++ test/clangd/protocol.test
@@ -1,5 +1,5 @@
-# RUN: not clangd -pretty -run-synchronously < %s | FileCheck -strict-whitespace %s
-# RUN: not clangd -pretty -run-synchronously < %s 2>&1 | FileCheck -check-prefix=STDERR %s
+# RUN: not clangd -pretty -log-to-stderr -run-synchronously < %s | FileCheck -strict-whitespace %s
+# RUN: not clangd -pretty -log-to-stderr -run-synchronously < %s 2>&1 | FileCheck -check-prefix=STDERR %s
 # vim: fileformat=dos
 # It is absolutely vital that this file has CRLF line endings.
 #
Index: clangd/tool/ClangdMain.cpp
===
--- clangd/tool/ClangdMain.cpp
+++ clangd/tool/ClangdMain.cpp
@@ -77,15 +77,20 @@
 llvm::cl::init(JSONStreamStyle::Standard));
 
 static llvm::cl::opt
+LogToStderr("log-to-stderr",
+llvm::cl::desc("Output LSP communication on stderr"),
+llvm::cl::init(false));
+
+static llvm::cl::opt
 PrettyPrint("pretty", llvm::cl::desc("Pretty-print JSON output"),
 llvm::cl::init(false));
 
-static llvm::cl::opt Test(
-"lit-test",
-llvm::cl::desc(
-"Abbreviation for -input-style=delimited -pretty -run-synchronously. "
-"Intended to simplify lit tests."),
-llvm::cl::init(false), llvm::cl::Hidden);
+static llvm::cl::opt
+Test("lit-test",
+ llvm::cl::desc(
+ "Abbreviation for -input-style=delimited -pretty -log-to-stderr "
+ "-run-synchronously. Intended to simplify lit tests."),
+ llvm::cl::init(false), llvm::cl::Hidden);
 
 static llvm::cl::opt PCHStorage(
 "pch-storage",
@@ -140,6 +145,7 @@
   if (Test) {
 RunSynchronously = true;
 InputStyle = JSONStreamStyle::Delimited;
+LogToStderr = true;
 PrettyPrint = true;
   }
 
@@ -190,7 +196,7 @@
 
   JSONOutput Out(llvm::outs(), llvm::errs(),
  InputMirrorStream ? InputMirrorStream.getPointer() : nullptr,
- PrettyPrint);
+ LogToStderr, PrettyPrint);
 
   clangd::LoggingSession LoggingSession(Out);
 
Index: clangd/JSONRPCDispatcher.h
===
--- clangd/JSONRPCDispatcher.h
+++ clangd/JSONRPCDispatcher.h
@@ -30,8 +30,10 @@
   // JSONOutput now that we pass Context everywhere.
 public:
   JSONOutput(llvm::raw_ostream , llvm::raw_ostream ,
- llvm::raw_ostream *InputMirror = nullptr, bool Pretty = false)
-  : Pretty(Pretty), Outs(Outs), Logs(Logs), InputMirror(InputMirror) {}
+ llvm::raw_ostream *InputMirror = nullptr, bool LogToStderr = false,
+ bool Pretty = false)
+  : LogToStderr(LogToStderr), Pretty(Pretty), Outs(Outs), Logs(Logs),
+InputMirror(InputMirror) {}
 
   /// Emit a JSONRPC message.
   void writeMessage(const json::Expr );
@@ -44,6 +46,9 @@
   /// Unlike other methods of JSONOutput, mirrorInput is not thread-safe.
   void mirrorInput(const Twine );
 
+  // Whether to output all LSP communication to stderr.
+  const bool LogToStderr;
+
   // Whether output should be pretty-printed.
   const bool Pretty;
 
Index: clangd/JSONRPCDispatcher.cpp

[PATCH] D44223: [ms] Emit vtordisp initializers in a deterministic order.

2018-03-07 Thread Nico Weber via Phabricator via cfe-commits
thakis marked an inline comment as done.
thakis added inline comments.



Comment at: lib/CodeGen/MicrosoftCXXABI.cpp:1206
+
+  for (const VBase  : VBases) {
+if (!V.second.hasVtorDisp())

rnk wrote:
> I think we can avoid the sort altogether if we iterate `RD->vbases()`, which 
> should already be in layout order, and then do lookup into `VBaseMap`.
That's way nicer, thanks. Done.


https://reviews.llvm.org/D44223



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


[PATCH] D44223: [ms] Emit vtordisp initializers in a deterministic order.

2018-03-07 Thread Nico Weber via Phabricator via cfe-commits
thakis updated this revision to Diff 137470.
thakis added a comment.

rnk comment


https://reviews.llvm.org/D44223

Files:
  lib/CodeGen/MicrosoftCXXABI.cpp


Index: lib/CodeGen/MicrosoftCXXABI.cpp
===
--- lib/CodeGen/MicrosoftCXXABI.cpp
+++ lib/CodeGen/MicrosoftCXXABI.cpp
@@ -1196,15 +1196,15 @@
   unsigned AS = getThisAddress(CGF).getAddressSpace();
   llvm::Value *Int8This = nullptr;  // Initialize lazily.
 
-  for (VBOffsets::const_iterator I = VBaseMap.begin(), E = VBaseMap.end();
-I != E; ++I) {
-if (!I->second.hasVtorDisp())
+  for (const CXXBaseSpecifier  : RD->vbases()) {
+const CXXRecordDecl *VBase = S.getType()->getAsCXXRecordDecl();
+if (!VBaseMap.find(VBase)->second.hasVtorDisp())
   continue;
 
 llvm::Value *VBaseOffset =
-GetVirtualBaseClassOffset(CGF, getThisAddress(CGF), RD, I->first);
+GetVirtualBaseClassOffset(CGF, getThisAddress(CGF), RD, VBase);
 uint64_t ConstantVBaseOffset =
-Layout.getVBaseClassOffset(I->first).getQuantity();
+Layout.getVBaseClassOffset(VBase).getQuantity();
 
 // vtorDisp_for_vbase = vbptr[vbase_idx] - offsetof(RD, vbase).
 llvm::Value *VtorDispValue = Builder.CreateSub(


Index: lib/CodeGen/MicrosoftCXXABI.cpp
===
--- lib/CodeGen/MicrosoftCXXABI.cpp
+++ lib/CodeGen/MicrosoftCXXABI.cpp
@@ -1196,15 +1196,15 @@
   unsigned AS = getThisAddress(CGF).getAddressSpace();
   llvm::Value *Int8This = nullptr;  // Initialize lazily.
 
-  for (VBOffsets::const_iterator I = VBaseMap.begin(), E = VBaseMap.end();
-I != E; ++I) {
-if (!I->second.hasVtorDisp())
+  for (const CXXBaseSpecifier  : RD->vbases()) {
+const CXXRecordDecl *VBase = S.getType()->getAsCXXRecordDecl();
+if (!VBaseMap.find(VBase)->second.hasVtorDisp())
   continue;
 
 llvm::Value *VBaseOffset =
-GetVirtualBaseClassOffset(CGF, getThisAddress(CGF), RD, I->first);
+GetVirtualBaseClassOffset(CGF, getThisAddress(CGF), RD, VBase);
 uint64_t ConstantVBaseOffset =
-Layout.getVBaseClassOffset(I->first).getQuantity();
+Layout.getVBaseClassOffset(VBase).getQuantity();
 
 // vtorDisp_for_vbase = vbptr[vbase_idx] - offsetof(RD, vbase).
 llvm::Value *VtorDispValue = Builder.CreateSub(
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D44039: [Sema] Make getCurFunction() return null outside function parsing

2018-03-07 Thread Reid Kleckner via Phabricator via cfe-commits
rnk updated this revision to Diff 137472.
rnk added a comment.

Bring back Sema::setFunctionHas* methods which internally do nothing when
called outside function scope. This appears to happen in practice when parsing
invalid code involving things like statement expressions, VLAs at global scope,
etc.


https://reviews.llvm.org/D44039

Files:
  clang/include/clang/Sema/Sema.h
  clang/lib/Sema/AnalysisBasedWarnings.cpp
  clang/lib/Sema/Sema.cpp
  clang/lib/Sema/SemaDecl.cpp
  clang/lib/Sema/SemaExpr.cpp
  clang/lib/Sema/SemaExprCXX.cpp
  clang/lib/Sema/SemaOpenMP.cpp
  clang/lib/Sema/SemaStmt.cpp
  clang/lib/Sema/SemaStmtAsm.cpp

Index: clang/lib/Sema/SemaStmtAsm.cpp
===
--- clang/lib/Sema/SemaStmtAsm.cpp
+++ clang/lib/Sema/SemaStmtAsm.cpp
@@ -793,7 +793,7 @@
 ArrayRef Exprs,
 SourceLocation EndLoc) {
   bool IsSimple = (NumOutputs != 0 || NumInputs != 0);
-  getCurFunction()->setHasBranchProtectedScope();
+  setFunctionHasBranchProtectedScope();
   MSAsmStmt *NS =
 new (Context) MSAsmStmt(Context, AsmLoc, LBraceLoc, IsSimple,
 /*IsVolatile*/ true, AsmToks, NumOutputs, NumInputs,
Index: clang/lib/Sema/SemaStmt.cpp
===
--- clang/lib/Sema/SemaStmt.cpp
+++ clang/lib/Sema/SemaStmt.cpp
@@ -557,7 +557,7 @@
 return StmtError();
 
   if (IsConstexpr || isa(Cond.get().second))
-getCurFunction()->setHasBranchProtectedScope();
+setFunctionHasBranchProtectedScope();
 
   DiagnoseUnusedExprResult(thenStmt);
   DiagnoseUnusedExprResult(elseStmt);
@@ -688,7 +688,7 @@
   if (Cond.isInvalid())
 return StmtError();
 
-  getCurFunction()->setHasBranchIntoScope();
+  setFunctionHasBranchIntoScope();
 
   SwitchStmt *SS = new (Context)
   SwitchStmt(Context, InitStmt, Cond.get().first, Cond.get().second);
@@ -1873,7 +1873,7 @@
 Sema::ActOnObjCForCollectionStmt(SourceLocation ForLoc,
  Stmt *First, Expr *collection,
  SourceLocation RParenLoc) {
-  getCurFunction()->setHasBranchProtectedScope();
+  setFunctionHasBranchProtectedScope();
 
   ExprResult CollectionExprResult =
 CheckObjCForCollectionOperand(ForLoc, collection);
@@ -2784,7 +2784,7 @@
 StmtResult Sema::ActOnGotoStmt(SourceLocation GotoLoc,
SourceLocation LabelLoc,
LabelDecl *TheDecl) {
-  getCurFunction()->setHasBranchIntoScope();
+  setFunctionHasBranchIntoScope();
   TheDecl->markUsed(Context);
   return new (Context) GotoStmt(TheDecl, GotoLoc, LabelLoc);
 }
@@ -2811,7 +2811,7 @@
 return StmtError();
   E = ExprRes.get();
 
-  getCurFunction()->setHasIndirectGoto();
+  setFunctionHasIndirectGoto();
 
   return new (Context) IndirectGotoStmt(GotoLoc, StarLoc, E);
 }
@@ -3607,7 +3607,7 @@
   if (!getLangOpts().ObjCExceptions)
 Diag(AtLoc, diag::err_objc_exceptions_disabled) << "@try";
 
-  getCurFunction()->setHasBranchProtectedScope();
+  setFunctionHasBranchProtectedScope();
   unsigned NumCatchStmts = CatchStmts.size();
   return ObjCAtTryStmt::Create(Context, AtLoc, Try, CatchStmts.data(),
NumCatchStmts, Finally);
@@ -3698,7 +3698,7 @@
 Sema::ActOnObjCAtSynchronizedStmt(SourceLocation AtLoc, Expr *SyncExpr,
   Stmt *SyncBody) {
   // We can't jump into or indirect-jump out of a @synchronized block.
-  getCurFunction()->setHasBranchProtectedScope();
+  setFunctionHasBranchProtectedScope();
   return new (Context) ObjCAtSynchronizedStmt(AtLoc, SyncExpr, SyncBody);
 }
 
@@ -3714,7 +3714,7 @@
 
 StmtResult
 Sema::ActOnObjCAutoreleasePoolStmt(SourceLocation AtLoc, Stmt *Body) {
-  getCurFunction()->setHasBranchProtectedScope();
+  setFunctionHasBranchProtectedScope();
   return new (Context) ObjCAutoreleasePoolStmt(AtLoc, Body);
 }
 
Index: clang/lib/Sema/SemaOpenMP.cpp
===
--- clang/lib/Sema/SemaOpenMP.cpp
+++ clang/lib/Sema/SemaOpenMP.cpp
@@ -3572,7 +3572,7 @@
   // longjmp() and throw() must not violate the entry/exit criteria.
   CS->getCapturedDecl()->setNothrow();
 
-  getCurFunction()->setHasBranchProtectedScope();
+  setFunctionHasBranchProtectedScope();
 
   return OMPParallelDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
   DSAStack->isCancelRegion());
@@ -5281,7 +5281,7 @@
   if (checkSimdlenSafelenSpecified(*this, Clauses))
 return StmtError();
 
-  getCurFunction()->setHasBranchProtectedScope();
+  setFunctionHasBranchProtectedScope();
   return OMPSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
   Clauses, AStmt, B);
 }
@@ -5317,7 +5317,7 @@
 }
   }
 
-  getCurFunction()->setHasBranchProtectedScope();
+  

Re: r326602 - [Attr] Fix parameter indexing for several attributes

2018-03-07 Thread Aaron Ballman via cfe-commits
Joel, can you investigate the issue?

~Aaron

On Wed, Mar 7, 2018 at 4:32 PM, Nico Weber via cfe-commits
 wrote:
> (I had to revert this since it caused
> https://bugs.llvm.org/show_bug.cgi?id=36620)
>
> On Fri, Mar 2, 2018 at 2:03 PM, Joel E. Denny via cfe-commits
>  wrote:
>>
>> Author: jdenny
>> Date: Fri Mar  2 11:03:22 2018
>> New Revision: 326602
>>
>> URL: http://llvm.org/viewvc/llvm-project?rev=326602=rev
>> Log:
>> [Attr] Fix parameter indexing for several attributes
>>
>> The patch fixes a number of bugs related to parameter indexing in
>> attributes:
>>
>> * Parameter indices in some attributes (argument_with_type_tag,
>>   pointer_with_type_tag, nonnull, ownership_takes, ownership_holds,
>>   and ownership_returns) are specified in source as one-origin
>>   including any C++ implicit this parameter, were stored as
>>   zero-origin excluding any this parameter, and were erroneously
>>   printing (-ast-print) and confusingly dumping (-ast-dump) as the
>>   stored values.
>>
>> * For alloc_size, the C++ implicit this parameter was not subtracted
>>   correctly in Sema, leading to assert failures or to silent failures
>>   of __builtin_object_size to compute a value.
>>
>> * For argument_with_type_tag, pointer_with_type_tag, and
>>   ownership_returns, the C++ implicit this parameter was not added
>>   back to parameter indices in some diagnostics.
>>
>> This patch fixes the above bugs and aims to prevent similar bugs in
>> the future by introducing careful mechanisms for handling parameter
>> indices in attributes.  ParamIdx stores a parameter index and is
>> designed to hide the stored encoding while providing accessors that
>> require each use (such as printing) to make explicit the encoding that
>> is needed.  Attribute declarations declare parameter index arguments
>> as [Variadic]ParamIdxArgument, which are exposed as ParamIdx[*].  This
>> patch rewrites all attribute arguments that are processed by
>> checkFunctionOrMethodParameterIndex in SemaDeclAttr.cpp to be declared
>> as [Variadic]ParamIdxArgument.  The only exception is xray_log_args's
>> argument, which is encoded as a count not an index.
>>
>> Differential Revision: https://reviews.llvm.org/D43248
>>
>> Added:
>> cfe/trunk/test/Sema/attr-ownership.cpp
>> Modified:
>> cfe/trunk/include/clang/AST/Attr.h
>> cfe/trunk/include/clang/Basic/Attr.td
>> cfe/trunk/lib/AST/ExprConstant.cpp
>> cfe/trunk/lib/CodeGen/CGCall.cpp
>> cfe/trunk/lib/Sema/SemaChecking.cpp
>> cfe/trunk/lib/Sema/SemaDecl.cpp
>> cfe/trunk/lib/Sema/SemaDeclAttr.cpp
>> cfe/trunk/lib/Sema/SemaTemplateInstantiateDecl.cpp
>> cfe/trunk/lib/StaticAnalyzer/Checkers/MallocChecker.cpp
>> cfe/trunk/lib/StaticAnalyzer/Checkers/NonNullParamChecker.cpp
>> cfe/trunk/test/CodeGenCXX/alloc-size.cpp
>> cfe/trunk/test/Misc/ast-dump-attr.cpp
>> cfe/trunk/test/Sema/attr-print.cpp
>> cfe/trunk/test/Sema/error-type-safety.cpp
>> cfe/trunk/utils/TableGen/ClangAttrEmitter.cpp
>>
>> Modified: cfe/trunk/include/clang/AST/Attr.h
>> URL:
>> http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/AST/Attr.h?rev=326602=326601=326602=diff
>>
>> ==
>> --- cfe/trunk/include/clang/AST/Attr.h (original)
>> +++ cfe/trunk/include/clang/AST/Attr.h Fri Mar  2 11:03:22 2018
>> @@ -195,6 +195,120 @@ public:
>> }
>>  };
>>
>> +/// A single parameter index whose accessors require each use to make
>> explicit
>> +/// the parameter index encoding needed.
>> +class ParamIdx {
>> +  // Idx is exposed only via accessors that specify specific encodings.
>> +  unsigned Idx : 30;
>> +  unsigned HasThis : 1;
>> +  unsigned IsValid : 1;
>> +
>> +  void assertComparable(const ParamIdx ) const {
>> +assert(isValid() && I.isValid() &&
>> +   "ParamIdx must be valid to be compared");
>> +// It's possible to compare indices from separate functions, but so
>> far
>> +// it's not proven useful.  Moreover, it might be confusing because a
>> +// comparison on the results of getASTIndex might be inconsistent
>> with a
>> +// comparison on the ParamIdx objects themselves.
>> +assert(HasThis == I.HasThis &&
>> +   "ParamIdx must be for the same function to be compared");
>> +  }
>> +
>> +public:
>> +  /// Construct an invalid parameter index (\c isValid returns false and
>> +  /// accessors fail an assert).
>> +  ParamIdx() : Idx(0), HasThis(false), IsValid(false) {}
>> +
>> +  /// \param Idx is the parameter index as it is normally specified in
>> +  /// attributes in the source: one-origin including any C++ implicit
>> this
>> +  /// parameter.
>> +  ///
>> +  /// \param D is the declaration containing the parameters.  It is used
>> to
>> +  /// determine if there is a C++ implicit this parameter.
>> +  ParamIdx(unsigned Idx, const Decl *D)
>> +  : Idx(Idx), HasThis(false), IsValid(true) {

[PATCH] D44213: [clangd] Remove unused field in HandlerRegisterer

2018-03-07 Thread Simon Marchi via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rCTE326947: [clangd] Remove unused field in HandlerRegisterer 
(authored by simark, committed by ).

Changed prior to commit:
  https://reviews.llvm.org/D44213?vs=137410=137471#toc

Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D44213

Files:
  clangd/ClangdLSPServer.cpp
  clangd/ProtocolHandlers.cpp
  clangd/ProtocolHandlers.h


Index: clangd/ProtocolHandlers.cpp
===
--- clangd/ProtocolHandlers.cpp
+++ clangd/ProtocolHandlers.cpp
@@ -38,16 +38,14 @@
   }
 
   JSONRPCDispatcher 
-  JSONOutput *Out;
   ProtocolCallbacks *Callbacks;
 };
 
 } // namespace
 
 void clangd::registerCallbackHandlers(JSONRPCDispatcher ,
-  JSONOutput ,
   ProtocolCallbacks ) {
-  HandlerRegisterer Register{Dispatcher, , };
+  HandlerRegisterer Register{Dispatcher, };
 
   Register("initialize", ::onInitialize);
   Register("shutdown", ::onShutdown);
Index: clangd/ProtocolHandlers.h
===
--- clangd/ProtocolHandlers.h
+++ clangd/ProtocolHandlers.h
@@ -55,7 +55,7 @@
   virtual void onChangeConfiguration(DidChangeConfigurationParams ) = 0;
 };
 
-void registerCallbackHandlers(JSONRPCDispatcher , JSONOutput ,
+void registerCallbackHandlers(JSONRPCDispatcher ,
   ProtocolCallbacks );
 
 } // namespace clangd
Index: clangd/ClangdLSPServer.cpp
===
--- clangd/ClangdLSPServer.cpp
+++ clangd/ClangdLSPServer.cpp
@@ -409,7 +409,7 @@
   JSONRPCDispatcher Dispatcher([](const json::Expr ) {
 replyError(ErrorCode::MethodNotFound, "method not found");
   });
-  registerCallbackHandlers(Dispatcher, Out, /*Callbacks=*/*this);
+  registerCallbackHandlers(Dispatcher, /*Callbacks=*/*this);
 
   // Run the Language Server loop.
   runLanguageServerLoop(In, Out, InputStyle, Dispatcher, IsDone);


Index: clangd/ProtocolHandlers.cpp
===
--- clangd/ProtocolHandlers.cpp
+++ clangd/ProtocolHandlers.cpp
@@ -38,16 +38,14 @@
   }
 
   JSONRPCDispatcher 
-  JSONOutput *Out;
   ProtocolCallbacks *Callbacks;
 };
 
 } // namespace
 
 void clangd::registerCallbackHandlers(JSONRPCDispatcher ,
-  JSONOutput ,
   ProtocolCallbacks ) {
-  HandlerRegisterer Register{Dispatcher, , };
+  HandlerRegisterer Register{Dispatcher, };
 
   Register("initialize", ::onInitialize);
   Register("shutdown", ::onShutdown);
Index: clangd/ProtocolHandlers.h
===
--- clangd/ProtocolHandlers.h
+++ clangd/ProtocolHandlers.h
@@ -55,7 +55,7 @@
   virtual void onChangeConfiguration(DidChangeConfigurationParams ) = 0;
 };
 
-void registerCallbackHandlers(JSONRPCDispatcher , JSONOutput ,
+void registerCallbackHandlers(JSONRPCDispatcher ,
   ProtocolCallbacks );
 
 } // namespace clangd
Index: clangd/ClangdLSPServer.cpp
===
--- clangd/ClangdLSPServer.cpp
+++ clangd/ClangdLSPServer.cpp
@@ -409,7 +409,7 @@
   JSONRPCDispatcher Dispatcher([](const json::Expr ) {
 replyError(ErrorCode::MethodNotFound, "method not found");
   });
-  registerCallbackHandlers(Dispatcher, Out, /*Callbacks=*/*this);
+  registerCallbackHandlers(Dispatcher, /*Callbacks=*/*this);
 
   // Run the Language Server loop.
   runLanguageServerLoop(In, Out, InputStyle, Dispatcher, IsDone);
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D34367: CodeGen: Fix address space of indirect function argument

2018-03-07 Thread Yaxun Liu via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rL326946: CodeGen: Fix address space of indirect function 
argument (authored by yaxunl, committed by ).
Herald added a subscriber: llvm-commits.

Changed prior to commit:
  https://reviews.llvm.org/D34367?vs=137460=137469#toc

Repository:
  rL LLVM

https://reviews.llvm.org/D34367

Files:
  cfe/trunk/lib/CodeGen/CGAtomic.cpp
  cfe/trunk/lib/CodeGen/CGCall.cpp
  cfe/trunk/lib/CodeGen/CGCall.h
  cfe/trunk/lib/CodeGen/CGClass.cpp
  cfe/trunk/lib/CodeGen/CGDecl.cpp
  cfe/trunk/lib/CodeGen/CGExprCXX.cpp
  cfe/trunk/lib/CodeGen/CGGPUBuiltin.cpp
  cfe/trunk/lib/CodeGen/CGObjCGNU.cpp
  cfe/trunk/lib/CodeGen/CGObjCMac.cpp
  cfe/trunk/lib/CodeGen/CodeGenFunction.h
  cfe/trunk/lib/CodeGen/ItaniumCXXABI.cpp
  cfe/trunk/lib/CodeGen/MicrosoftCXXABI.cpp
  cfe/trunk/test/CodeGenCXX/amdgcn-func-arg.cpp
  cfe/trunk/test/CodeGenOpenCL/addr-space-struct-arg.cl
  cfe/trunk/test/CodeGenOpenCL/byval.cl

Index: cfe/trunk/test/CodeGenCXX/amdgcn-func-arg.cpp
===
--- cfe/trunk/test/CodeGenCXX/amdgcn-func-arg.cpp
+++ cfe/trunk/test/CodeGenCXX/amdgcn-func-arg.cpp
@@ -0,0 +1,94 @@
+// RUN: %clang_cc1 -O0 -triple amdgcn -emit-llvm %s -o - | FileCheck %s
+
+class A {
+public:
+  int x;
+  A():x(0) {}
+  ~A() {}
+};
+
+class B {
+int x[100];
+};
+
+A g_a;
+B g_b;
+
+void func_with_ref_arg(A );
+void func_with_ref_arg(B );
+
+// CHECK-LABEL: define void @_Z22func_with_indirect_arg1A(%class.A addrspace(5)* %a)
+// CHECK:  %p = alloca %class.A*, align 8, addrspace(5)
+// CHECK:  %[[r1:.+]] = addrspacecast %class.A* addrspace(5)* %p to %class.A**
+// CHECK:  %[[r0:.+]] = addrspacecast %class.A addrspace(5)* %a to %class.A*
+// CHECK:  store %class.A* %[[r0]], %class.A** %[[r1]], align 8
+void func_with_indirect_arg(A a) {
+  A *p = 
+}
+
+// CHECK-LABEL: define void @_Z22test_indirect_arg_autov()
+// CHECK:  %a = alloca %class.A, align 4, addrspace(5)
+// CHECK:  %[[r0:.+]] = addrspacecast %class.A addrspace(5)* %a to %class.A*
+// CHECK:  %agg.tmp = alloca %class.A, align 4, addrspace(5)
+// CHECK:  %[[r1:.+]] = addrspacecast %class.A addrspace(5)* %agg.tmp to %class.A*
+// CHECK:  call void @_ZN1AC1Ev(%class.A* %[[r0]])
+// CHECK:  call void @llvm.memcpy.p0i8.p0i8.i64
+// CHECK:  %[[r4:.+]] = addrspacecast %class.A* %[[r1]] to %class.A addrspace(5)*
+// CHECK:  call void @_Z22func_with_indirect_arg1A(%class.A addrspace(5)* %[[r4]])
+// CHECK:  call void @_ZN1AD1Ev(%class.A* %[[r1]])
+// CHECK:  call void @_Z17func_with_ref_argR1A(%class.A* dereferenceable(4) %[[r0]])
+// CHECK:  call void @_ZN1AD1Ev(%class.A* %[[r0]])
+void test_indirect_arg_auto() {
+  A a;
+  func_with_indirect_arg(a);
+  func_with_ref_arg(a);
+}
+
+// CHECK: define void @_Z24test_indirect_arg_globalv()
+// CHECK:  %agg.tmp = alloca %class.A, align 4, addrspace(5)
+// CHECK:  %[[r0:.+]] = addrspacecast %class.A addrspace(5)* %agg.tmp to %class.A*
+// CHECK:  call void @llvm.memcpy.p0i8.p0i8.i64
+// CHECK:  %[[r2:.+]] = addrspacecast %class.A* %[[r0]] to %class.A addrspace(5)*
+// CHECK:  call void @_Z22func_with_indirect_arg1A(%class.A addrspace(5)* %[[r2]])
+// CHECK:  call void @_ZN1AD1Ev(%class.A* %[[r0]])
+// CHECK:  call void @_Z17func_with_ref_argR1A(%class.A* dereferenceable(4) addrspacecast (%class.A addrspace(1)* @g_a to %class.A*))
+void test_indirect_arg_global() {
+  func_with_indirect_arg(g_a);
+  func_with_ref_arg(g_a);
+}
+
+// CHECK-LABEL: define void @_Z19func_with_byval_arg1B(%class.B addrspace(5)* byval align 4 %b)
+// CHECK:  %p = alloca %class.B*, align 8, addrspace(5)
+// CHECK:  %[[r1:.+]] = addrspacecast %class.B* addrspace(5)* %p to %class.B**
+// CHECK:  %[[r0:.+]] = addrspacecast %class.B addrspace(5)* %b to %class.B*
+// CHECK:  store %class.B* %[[r0]], %class.B** %[[r1]], align 8
+void func_with_byval_arg(B b) {
+  B *p = 
+}
+
+// CHECK-LABEL: define void @_Z19test_byval_arg_autov()
+// CHECK:  %b = alloca %class.B, align 4, addrspace(5)
+// CHECK:  %[[r0:.+]] = addrspacecast %class.B addrspace(5)* %b to %class.B*
+// CHECK:  %agg.tmp = alloca %class.B, align 4, addrspace(5)
+// CHECK:  %[[r1:.+]] = addrspacecast %class.B addrspace(5)* %agg.tmp to %class.B*
+// CHECK:  call void @llvm.memcpy.p0i8.p0i8.i64
+// CHECK:  %[[r4:.+]] = addrspacecast %class.B* %[[r1]] to %class.B addrspace(5)*
+// CHECK:  call void @_Z19func_with_byval_arg1B(%class.B addrspace(5)* byval align 4 %[[r4]])
+// CHECK:  call void @_Z17func_with_ref_argR1B(%class.B* dereferenceable(400) %[[r0]])
+void test_byval_arg_auto() {
+  B b;
+  func_with_byval_arg(b);
+  func_with_ref_arg(b);
+}
+
+// CHECK-LABEL: define void @_Z21test_byval_arg_globalv()
+// CHECK:  %agg.tmp = alloca %class.B, align 4, addrspace(5)
+// CHECK:  %[[r0:.+]] = addrspacecast %class.B addrspace(5)* %agg.tmp to %class.B*
+// CHECK:  call void @llvm.memcpy.p0i8.p0i8.i64
+// CHECK:  %[[r2:.+]] = addrspacecast %class.B* %[[r0]] to %class.B 

r326946 - CodeGen: Fix address space of indirect function argument

2018-03-07 Thread Yaxun Liu via cfe-commits
Author: yaxunl
Date: Wed Mar  7 13:45:40 2018
New Revision: 326946

URL: http://llvm.org/viewvc/llvm-project?rev=326946=rev
Log:
CodeGen: Fix address space of indirect function argument

The indirect function argument is in alloca address space in LLVM IR. However,
during Clang codegen for C++, the address space of indirect function argument
should match its address space in the source code, i.e., default addr space, 
even
for indirect argument. This is because destructor of the indirect argument may
be called in the caller function, and address of the indirect argument may be
taken, in either case the indirect function argument is expected to be in 
default
addr space, not the alloca address space.

Therefore, the indirect function argument should be mapped to the temp var
casted to default address space. The caller will cast it to alloca addr space
when passing it to the callee. In the callee, the argument is also casted to the
default address space and used.

CallArg is refactored to facilitate this fix.

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

Added:
cfe/trunk/test/CodeGenCXX/amdgcn-func-arg.cpp
Modified:
cfe/trunk/lib/CodeGen/CGAtomic.cpp
cfe/trunk/lib/CodeGen/CGCall.cpp
cfe/trunk/lib/CodeGen/CGCall.h
cfe/trunk/lib/CodeGen/CGClass.cpp
cfe/trunk/lib/CodeGen/CGDecl.cpp
cfe/trunk/lib/CodeGen/CGExprCXX.cpp
cfe/trunk/lib/CodeGen/CGGPUBuiltin.cpp
cfe/trunk/lib/CodeGen/CGObjCGNU.cpp
cfe/trunk/lib/CodeGen/CGObjCMac.cpp
cfe/trunk/lib/CodeGen/CodeGenFunction.h
cfe/trunk/lib/CodeGen/ItaniumCXXABI.cpp
cfe/trunk/lib/CodeGen/MicrosoftCXXABI.cpp
cfe/trunk/test/CodeGenOpenCL/addr-space-struct-arg.cl
cfe/trunk/test/CodeGenOpenCL/byval.cl

Modified: cfe/trunk/lib/CodeGen/CGAtomic.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/CodeGen/CGAtomic.cpp?rev=326946=326945=326946=diff
==
--- cfe/trunk/lib/CodeGen/CGAtomic.cpp (original)
+++ cfe/trunk/lib/CodeGen/CGAtomic.cpp Wed Mar  7 13:45:40 2018
@@ -1160,7 +1160,7 @@ RValue CodeGenFunction::EmitAtomicExpr(A
 if (UseOptimizedLibcall && Res.getScalarVal()) {
   llvm::Value *ResVal = Res.getScalarVal();
   if (PostOp) {
-llvm::Value *LoadVal1 = Args[1].RV.getScalarVal();
+llvm::Value *LoadVal1 = Args[1].getRValue(*this).getScalarVal();
 ResVal = Builder.CreateBinOp(PostOp, ResVal, LoadVal1);
   }
   if (E->getOp() == AtomicExpr::AO__atomic_nand_fetch)

Modified: cfe/trunk/lib/CodeGen/CGCall.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/CodeGen/CGCall.cpp?rev=326946=326945=326946=diff
==
--- cfe/trunk/lib/CodeGen/CGCall.cpp (original)
+++ cfe/trunk/lib/CodeGen/CGCall.cpp Wed Mar  7 13:45:40 2018
@@ -1040,42 +1040,49 @@ void CodeGenFunction::ExpandTypeFromArgs
 }
 
 void CodeGenFunction::ExpandTypeToArgs(
-QualType Ty, RValue RV, llvm::FunctionType *IRFuncTy,
+QualType Ty, CallArg Arg, llvm::FunctionType *IRFuncTy,
 SmallVectorImpl , unsigned ) {
   auto Exp = getTypeExpansion(Ty, getContext());
   if (auto CAExp = dyn_cast(Exp.get())) {
-forConstantArrayExpansion(*this, CAExp, RV.getAggregateAddress(),
-  [&](Address EltAddr) {
-  RValue EltRV =
-  convertTempToRValue(EltAddr, CAExp->EltTy, SourceLocation());
-  ExpandTypeToArgs(CAExp->EltTy, EltRV, IRFuncTy, IRCallArgs, 
IRCallArgPos);
-});
+Address Addr = Arg.hasLValue() ? Arg.getKnownLValue().getAddress()
+   : 
Arg.getKnownRValue().getAggregateAddress();
+forConstantArrayExpansion(
+*this, CAExp, Addr, [&](Address EltAddr) {
+  CallArg EltArg = CallArg(
+  convertTempToRValue(EltAddr, CAExp->EltTy, SourceLocation()),
+  CAExp->EltTy);
+  ExpandTypeToArgs(CAExp->EltTy, EltArg, IRFuncTy, IRCallArgs,
+   IRCallArgPos);
+});
   } else if (auto RExp = dyn_cast(Exp.get())) {
-Address This = RV.getAggregateAddress();
+Address This = Arg.hasLValue() ? Arg.getKnownLValue().getAddress()
+   : 
Arg.getKnownRValue().getAggregateAddress();
 for (const CXXBaseSpecifier *BS : RExp->Bases) {
   // Perform a single step derived-to-base conversion.
   Address Base =
   GetAddressOfBaseClass(This, Ty->getAsCXXRecordDecl(), ,  + 1,
 /*NullCheckValue=*/false, SourceLocation());
-  RValue BaseRV = RValue::getAggregate(Base);
+  CallArg BaseArg = CallArg(RValue::getAggregate(Base), BS->getType());
 
   // Recurse onto bases.
-  ExpandTypeToArgs(BS->getType(), BaseRV, IRFuncTy, IRCallArgs,
+  ExpandTypeToArgs(BS->getType(), BaseArg, IRFuncTy, IRCallArgs,
IRCallArgPos);
 }
 
 LValue LV = MakeAddrLValue(This, Ty);
 for (auto FD : 

[PATCH] D44213: [clangd] Remove unused field in HandlerRegisterer

2018-03-07 Thread Marc-Andre Laperle via Phabricator via cfe-commits
malaperle accepted this revision.
malaperle added a comment.
This revision is now accepted and ready to land.

LGTM


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D44213



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


[PATCH] D44189: [RISCV] Verify the input value of -march=

2018-03-07 Thread Ana Pazos via Phabricator via cfe-commits
apazos added inline comments.



Comment at: lib/Driver/ToolChains/Arch/RISCV.cpp:48
+  break;
+default:
+  // First letter should be 'i' or 'g'.

In the switch cases move default to first position.



Comment at: lib/Driver/ToolChains/Arch/RISCV.cpp:60
   case 'm':
 Features.push_back("+m");
 break;

So the subsequent features can appear in any order?


Repository:
  rC Clang

https://reviews.llvm.org/D44189



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


[PATCH] D41102: Setup clang-doc frontend framework

2018-03-07 Thread Roman Lebedev via Phabricator via cfe-commits
lebedev.ri added a comment.

Hmm, i'm missing something about the way store sha1...




Comment at: clang-doc/BitcodeWriter.cpp:53
+{// 0. Fixed-size integer (length of the sha1'd USR)
+ llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::VBR,
+   BitCodeConstants::USRLengthSize),

This is VBR because USRLengthSize is of such strange size, to conserve the bits?



Comment at: clang-doc/BitcodeWriter.cpp:57
+ llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::Array),
+ llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::Char6)});
+}

Looking at the `NumWords` changes (decrease!) in the tests, and this is bugging 
me.
And now that i have realized what we do with USR:
* we first compute SHA1, and get 20x uint8_t
* store/use it internally
* then hex-ify it, getting 40x char (assuming 8-bit char)
* then convert to char6, winning back two bits. but we still loose 2 bits.

Question: *why* do we store sha1 of USR as a string? 
Why can't we just store that USRString (aka USRSha1 binary) directly?
That would be just 20 bytes, you just couldn't go any lower than that.



Comment at: clang-doc/Representation.h:29
+
+using USRString = std::array;
+

Right, of course, internally this is kept in the binary format, which is just 
20 chars.
This is not the string (the hex-ified version of sha1), but the raw sha1, the 
binary.
This should somehow convey that. This should be something closer to `USRSha1`.


https://reviews.llvm.org/D41102



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


[PATCH] D44204: [clang-format] Break consecutive string literals in text protos

2018-03-07 Thread Krasimir Georgiev via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rL326945: [clang-format] Break consecutive string literals in 
text protos (authored by krasimir, committed by ).
Herald added a subscriber: llvm-commits.

Repository:
  rL LLVM

https://reviews.llvm.org/D44204

Files:
  cfe/trunk/lib/Format/TokenAnnotator.cpp
  cfe/trunk/unittests/Format/FormatTestTextProto.cpp


Index: cfe/trunk/lib/Format/TokenAnnotator.cpp
===
--- cfe/trunk/lib/Format/TokenAnnotator.cpp
+++ cfe/trunk/lib/Format/TokenAnnotator.cpp
@@ -2717,7 +2717,8 @@
   return true;
   } else if (Style.Language == FormatStyle::LK_Cpp ||
  Style.Language == FormatStyle::LK_ObjC ||
- Style.Language == FormatStyle::LK_Proto) {
+ Style.Language == FormatStyle::LK_Proto ||
+ Style.Language == FormatStyle::LK_TextProto) {
 if (Left.isStringLiteral() && Right.isStringLiteral())
   return true;
   }
Index: cfe/trunk/unittests/Format/FormatTestTextProto.cpp
===
--- cfe/trunk/unittests/Format/FormatTestTextProto.cpp
+++ cfe/trunk/unittests/Format/FormatTestTextProto.cpp
@@ -452,5 +452,11 @@
"  >\n"
">");
 }
+
+TEST_F(FormatTestTextProto, BreaksConsecutiveStringLiterals) {
+  verifyFormat("ala: \"str1\"\n"
+   " \"str2\"\n");
+}
+
 } // end namespace tooling
 } // end namespace clang


Index: cfe/trunk/lib/Format/TokenAnnotator.cpp
===
--- cfe/trunk/lib/Format/TokenAnnotator.cpp
+++ cfe/trunk/lib/Format/TokenAnnotator.cpp
@@ -2717,7 +2717,8 @@
   return true;
   } else if (Style.Language == FormatStyle::LK_Cpp ||
  Style.Language == FormatStyle::LK_ObjC ||
- Style.Language == FormatStyle::LK_Proto) {
+ Style.Language == FormatStyle::LK_Proto ||
+ Style.Language == FormatStyle::LK_TextProto) {
 if (Left.isStringLiteral() && Right.isStringLiteral())
   return true;
   }
Index: cfe/trunk/unittests/Format/FormatTestTextProto.cpp
===
--- cfe/trunk/unittests/Format/FormatTestTextProto.cpp
+++ cfe/trunk/unittests/Format/FormatTestTextProto.cpp
@@ -452,5 +452,11 @@
"  >\n"
">");
 }
+
+TEST_F(FormatTestTextProto, BreaksConsecutiveStringLiterals) {
+  verifyFormat("ala: \"str1\"\n"
+   " \"str2\"\n");
+}
+
 } // end namespace tooling
 } // end namespace clang
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


r326945 - [clang-format] Break consecutive string literals in text protos

2018-03-07 Thread Krasimir Georgiev via cfe-commits
Author: krasimir
Date: Wed Mar  7 13:30:38 2018
New Revision: 326945

URL: http://llvm.org/viewvc/llvm-project?rev=326945=rev
Log:
[clang-format] Break consecutive string literals in text protos

Summary:
This patch fixes a bug where consecutive string literals in text protos were
put on the same line.

Reviewers: alexfh

Reviewed By: alexfh

Subscribers: klimek, cfe-commits

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

Modified:
cfe/trunk/lib/Format/TokenAnnotator.cpp
cfe/trunk/unittests/Format/FormatTestTextProto.cpp

Modified: cfe/trunk/lib/Format/TokenAnnotator.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Format/TokenAnnotator.cpp?rev=326945=326944=326945=diff
==
--- cfe/trunk/lib/Format/TokenAnnotator.cpp (original)
+++ cfe/trunk/lib/Format/TokenAnnotator.cpp Wed Mar  7 13:30:38 2018
@@ -2717,7 +2717,8 @@ bool TokenAnnotator::mustBreakBefore(con
   return true;
   } else if (Style.Language == FormatStyle::LK_Cpp ||
  Style.Language == FormatStyle::LK_ObjC ||
- Style.Language == FormatStyle::LK_Proto) {
+ Style.Language == FormatStyle::LK_Proto ||
+ Style.Language == FormatStyle::LK_TextProto) {
 if (Left.isStringLiteral() && Right.isStringLiteral())
   return true;
   }

Modified: cfe/trunk/unittests/Format/FormatTestTextProto.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/unittests/Format/FormatTestTextProto.cpp?rev=326945=326944=326945=diff
==
--- cfe/trunk/unittests/Format/FormatTestTextProto.cpp (original)
+++ cfe/trunk/unittests/Format/FormatTestTextProto.cpp Wed Mar  7 13:30:38 2018
@@ -452,5 +452,11 @@ TEST_F(FormatTestTextProto, AcceptsOpera
"  >\n"
">");
 }
+
+TEST_F(FormatTestTextProto, BreaksConsecutiveStringLiterals) {
+  verifyFormat("ala: \"str1\"\n"
+   " \"str2\"\n");
+}
+
 } // end namespace tooling
 } // end namespace clang


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


Re: r326602 - [Attr] Fix parameter indexing for several attributes

2018-03-07 Thread Nico Weber via cfe-commits
(I had to revert this since it caused
https://bugs.llvm.org/show_bug.cgi?id=36620)

On Fri, Mar 2, 2018 at 2:03 PM, Joel E. Denny via cfe-commits <
cfe-commits@lists.llvm.org> wrote:

> Author: jdenny
> Date: Fri Mar  2 11:03:22 2018
> New Revision: 326602
>
> URL: http://llvm.org/viewvc/llvm-project?rev=326602=rev
> Log:
> [Attr] Fix parameter indexing for several attributes
>
> The patch fixes a number of bugs related to parameter indexing in
> attributes:
>
> * Parameter indices in some attributes (argument_with_type_tag,
>   pointer_with_type_tag, nonnull, ownership_takes, ownership_holds,
>   and ownership_returns) are specified in source as one-origin
>   including any C++ implicit this parameter, were stored as
>   zero-origin excluding any this parameter, and were erroneously
>   printing (-ast-print) and confusingly dumping (-ast-dump) as the
>   stored values.
>
> * For alloc_size, the C++ implicit this parameter was not subtracted
>   correctly in Sema, leading to assert failures or to silent failures
>   of __builtin_object_size to compute a value.
>
> * For argument_with_type_tag, pointer_with_type_tag, and
>   ownership_returns, the C++ implicit this parameter was not added
>   back to parameter indices in some diagnostics.
>
> This patch fixes the above bugs and aims to prevent similar bugs in
> the future by introducing careful mechanisms for handling parameter
> indices in attributes.  ParamIdx stores a parameter index and is
> designed to hide the stored encoding while providing accessors that
> require each use (such as printing) to make explicit the encoding that
> is needed.  Attribute declarations declare parameter index arguments
> as [Variadic]ParamIdxArgument, which are exposed as ParamIdx[*].  This
> patch rewrites all attribute arguments that are processed by
> checkFunctionOrMethodParameterIndex in SemaDeclAttr.cpp to be declared
> as [Variadic]ParamIdxArgument.  The only exception is xray_log_args's
> argument, which is encoded as a count not an index.
>
> Differential Revision: https://reviews.llvm.org/D43248
>
> Added:
> cfe/trunk/test/Sema/attr-ownership.cpp
> Modified:
> cfe/trunk/include/clang/AST/Attr.h
> cfe/trunk/include/clang/Basic/Attr.td
> cfe/trunk/lib/AST/ExprConstant.cpp
> cfe/trunk/lib/CodeGen/CGCall.cpp
> cfe/trunk/lib/Sema/SemaChecking.cpp
> cfe/trunk/lib/Sema/SemaDecl.cpp
> cfe/trunk/lib/Sema/SemaDeclAttr.cpp
> cfe/trunk/lib/Sema/SemaTemplateInstantiateDecl.cpp
> cfe/trunk/lib/StaticAnalyzer/Checkers/MallocChecker.cpp
> cfe/trunk/lib/StaticAnalyzer/Checkers/NonNullParamChecker.cpp
> cfe/trunk/test/CodeGenCXX/alloc-size.cpp
> cfe/trunk/test/Misc/ast-dump-attr.cpp
> cfe/trunk/test/Sema/attr-print.cpp
> cfe/trunk/test/Sema/error-type-safety.cpp
> cfe/trunk/utils/TableGen/ClangAttrEmitter.cpp
>
> Modified: cfe/trunk/include/clang/AST/Attr.h
> URL: http://llvm.org/viewvc/llvm-project/cfe/trunk/include/
> clang/AST/Attr.h?rev=326602=326601=326602=diff
> 
> ==
> --- cfe/trunk/include/clang/AST/Attr.h (original)
> +++ cfe/trunk/include/clang/AST/Attr.h Fri Mar  2 11:03:22 2018
> @@ -195,6 +195,120 @@ public:
> }
>  };
>
> +/// A single parameter index whose accessors require each use to make
> explicit
> +/// the parameter index encoding needed.
> +class ParamIdx {
> +  // Idx is exposed only via accessors that specify specific encodings.
> +  unsigned Idx : 30;
> +  unsigned HasThis : 1;
> +  unsigned IsValid : 1;
> +
> +  void assertComparable(const ParamIdx ) const {
> +assert(isValid() && I.isValid() &&
> +   "ParamIdx must be valid to be compared");
> +// It's possible to compare indices from separate functions, but so
> far
> +// it's not proven useful.  Moreover, it might be confusing because a
> +// comparison on the results of getASTIndex might be inconsistent
> with a
> +// comparison on the ParamIdx objects themselves.
> +assert(HasThis == I.HasThis &&
> +   "ParamIdx must be for the same function to be compared");
> +  }
> +
> +public:
> +  /// Construct an invalid parameter index (\c isValid returns false and
> +  /// accessors fail an assert).
> +  ParamIdx() : Idx(0), HasThis(false), IsValid(false) {}
> +
> +  /// \param Idx is the parameter index as it is normally specified in
> +  /// attributes in the source: one-origin including any C++ implicit this
> +  /// parameter.
> +  ///
> +  /// \param D is the declaration containing the parameters.  It is used
> to
> +  /// determine if there is a C++ implicit this parameter.
> +  ParamIdx(unsigned Idx, const Decl *D)
> +  : Idx(Idx), HasThis(false), IsValid(true) {
> +if (const auto *FD = dyn_cast(D))
> +  HasThis = FD->isCXXInstanceMember();
> +  }
> +
> +  /// \param Idx is the parameter index as it is normally specified in
> +  /// attributes in the source: one-origin including any C++ implicit this
> +  /// 

[PATCH] D44223: [ms] Emit vtordisp initializers in a deterministic order.

2018-03-07 Thread Reid Kleckner via Phabricator via cfe-commits
rnk added a comment.

Thanks for investigating!




Comment at: lib/CodeGen/MicrosoftCXXABI.cpp:1206
+
+  for (const VBase  : VBases) {
+if (!V.second.hasVtorDisp())

I think we can avoid the sort altogether if we iterate `RD->vbases()`, which 
should already be in layout order, and then do lookup into `VBaseMap`.


https://reviews.llvm.org/D44223



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


[PATCH] D44223: [ms] Emit vtordisp initializers in a deterministic order.

2018-03-07 Thread Nico Weber via Phabricator via cfe-commits
thakis updated this revision to Diff 137463.
thakis added a comment.
Herald added a subscriber: mgrang.

sort unstably


https://reviews.llvm.org/D44223

Files:
  lib/CodeGen/MicrosoftCXXABI.cpp


Index: lib/CodeGen/MicrosoftCXXABI.cpp
===
--- lib/CodeGen/MicrosoftCXXABI.cpp
+++ lib/CodeGen/MicrosoftCXXABI.cpp
@@ -1196,15 +1196,21 @@
   unsigned AS = getThisAddress(CGF).getAddressSpace();
   llvm::Value *Int8This = nullptr;  // Initialize lazily.
 
-  for (VBOffsets::const_iterator I = VBaseMap.begin(), E = VBaseMap.end();
-I != E; ++I) {
-if (!I->second.hasVtorDisp())
+  // Emit vtordisps in vbase offset order, to have deterministic output.
+  typedef VBOffsets::value_type VBase;
+  SmallVector VBases(VBaseMap.begin(), VBaseMap.end());
+  std::sort(VBases.begin(), VBases.end(), [](const VBase , const VBase ) {
+return a.second.VBaseOffset < b.second.VBaseOffset;
+  });
+
+  for (const VBase  : VBases) {
+if (!V.second.hasVtorDisp())
   continue;
 
 llvm::Value *VBaseOffset =
-GetVirtualBaseClassOffset(CGF, getThisAddress(CGF), RD, I->first);
+GetVirtualBaseClassOffset(CGF, getThisAddress(CGF), RD, V.first);
 uint64_t ConstantVBaseOffset =
-Layout.getVBaseClassOffset(I->first).getQuantity();
+Layout.getVBaseClassOffset(V.first).getQuantity();
 
 // vtorDisp_for_vbase = vbptr[vbase_idx] - offsetof(RD, vbase).
 llvm::Value *VtorDispValue = Builder.CreateSub(


Index: lib/CodeGen/MicrosoftCXXABI.cpp
===
--- lib/CodeGen/MicrosoftCXXABI.cpp
+++ lib/CodeGen/MicrosoftCXXABI.cpp
@@ -1196,15 +1196,21 @@
   unsigned AS = getThisAddress(CGF).getAddressSpace();
   llvm::Value *Int8This = nullptr;  // Initialize lazily.
 
-  for (VBOffsets::const_iterator I = VBaseMap.begin(), E = VBaseMap.end();
-I != E; ++I) {
-if (!I->second.hasVtorDisp())
+  // Emit vtordisps in vbase offset order, to have deterministic output.
+  typedef VBOffsets::value_type VBase;
+  SmallVector VBases(VBaseMap.begin(), VBaseMap.end());
+  std::sort(VBases.begin(), VBases.end(), [](const VBase , const VBase ) {
+return a.second.VBaseOffset < b.second.VBaseOffset;
+  });
+
+  for (const VBase  : VBases) {
+if (!V.second.hasVtorDisp())
   continue;
 
 llvm::Value *VBaseOffset =
-GetVirtualBaseClassOffset(CGF, getThisAddress(CGF), RD, I->first);
+GetVirtualBaseClassOffset(CGF, getThisAddress(CGF), RD, V.first);
 uint64_t ConstantVBaseOffset =
-Layout.getVBaseClassOffset(I->first).getQuantity();
+Layout.getVBaseClassOffset(V.first).getQuantity();
 
 // vtorDisp_for_vbase = vbptr[vbase_idx] - offsetof(RD, vbase).
 llvm::Value *VtorDispValue = Builder.CreateSub(
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D44222: [AArch64] Add vmulxh_lane FP16 intrinsics

2018-03-07 Thread Evandro Menezes via Phabricator via cfe-commits
evandro accepted this revision.
evandro added a comment.
This revision is now accepted and ready to land.

Looks pretty straightforward to me.


https://reviews.llvm.org/D44222



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


[PATCH] D34367: CodeGen: Fix address space of indirect function argument

2018-03-07 Thread John McCall via Phabricator via cfe-commits
rjmccall accepted this revision.
rjmccall added a comment.
This revision is now accepted and ready to land.

Thanks.  LGTM!


https://reviews.llvm.org/D34367



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


[PATCH] D34367: CodeGen: Fix address space of indirect function argument

2018-03-07 Thread Yaxun Liu via Phabricator via cfe-commits
yaxunl updated this revision to Diff 137460.
yaxunl marked an inline comment as done.
yaxunl edited the summary of this revision.
yaxunl added a comment.

Added comment about emit non-null argument check.


https://reviews.llvm.org/D34367

Files:
  lib/CodeGen/CGAtomic.cpp
  lib/CodeGen/CGCall.cpp
  lib/CodeGen/CGCall.h
  lib/CodeGen/CGClass.cpp
  lib/CodeGen/CGDecl.cpp
  lib/CodeGen/CGExprCXX.cpp
  lib/CodeGen/CGGPUBuiltin.cpp
  lib/CodeGen/CGObjCGNU.cpp
  lib/CodeGen/CGObjCMac.cpp
  lib/CodeGen/CodeGenFunction.h
  lib/CodeGen/ItaniumCXXABI.cpp
  lib/CodeGen/MicrosoftCXXABI.cpp
  test/CodeGenCXX/amdgcn-func-arg.cpp
  test/CodeGenOpenCL/addr-space-struct-arg.cl
  test/CodeGenOpenCL/byval.cl

Index: test/CodeGenOpenCL/byval.cl
===
--- test/CodeGenOpenCL/byval.cl
+++ test/CodeGenOpenCL/byval.cl
@@ -1,5 +1,4 @@
 // RUN: %clang_cc1 -emit-llvm -o - -triple amdgcn %s | FileCheck %s
-// RUN: %clang_cc1 -emit-llvm -o - -triple amdgcn---opencl %s | FileCheck %s
 
 struct A {
   int x[100];
Index: test/CodeGenOpenCL/addr-space-struct-arg.cl
===
--- test/CodeGenOpenCL/addr-space-struct-arg.cl
+++ test/CodeGenOpenCL/addr-space-struct-arg.cl
@@ -1,5 +1,6 @@
 // RUN: %clang_cc1 %s -emit-llvm -o - -O0 -finclude-default-header -ffake-address-space-map -triple i686-pc-darwin | FileCheck -enable-var-scope -check-prefixes=COM,X86 %s
-// RUN: %clang_cc1 %s -emit-llvm -o - -O0 -finclude-default-header -triple amdgcn-amdhsa-amd | FileCheck -enable-var-scope -check-prefixes=COM,AMDGCN %s
+// RUN: %clang_cc1 %s -emit-llvm -o - -O0 -finclude-default-header -triple amdgcn | FileCheck -enable-var-scope -check-prefixes=COM,AMDGCN %s
+// RUN: %clang_cc1 %s -emit-llvm -o - -cl-std=CL2.0 -O0 -finclude-default-header -triple amdgcn | FileCheck -enable-var-scope -check-prefixes=COM,AMDGCN,AMDGCN20 %s
 
 typedef struct {
   int cells[9];
@@ -35,6 +36,9 @@
   int2 y[20];
 };
 
+#if __OPENCL_C_VERSION__ >= 200
+struct LargeStructOneMember g_s;
+#endif
 
 // X86-LABEL: define void @foo(%struct.Mat4X4* noalias sret %agg.result, %struct.Mat3X3* byval align 4 %in)
 // AMDGCN-LABEL: define %struct.Mat4X4 @foo([9 x i32] %in.coerce)
@@ -80,10 +84,42 @@
 }
 
 // AMDGCN-LABEL: define void @FuncOneLargeMember(%struct.LargeStructOneMember addrspace(5)* byval align 8 %u)
+// AMDGCN-NOT: addrspacecast
+// AMDGCN:   store <2 x i32> %{{.*}}, <2 x i32> addrspace(5)*
 void FuncOneLargeMember(struct LargeStructOneMember u) {
   u.x[0] = (int2)(0, 0);
 }
 
+// AMDGCN20-LABEL: define void @test_indirect_arg_globl()
+// AMDGCN20:  %[[byval_temp:.*]] = alloca %struct.LargeStructOneMember, align 8, addrspace(5)
+// AMDGCN20:  %[[r0:.*]] = bitcast %struct.LargeStructOneMember addrspace(5)* %[[byval_temp]] to i8 addrspace(5)*
+// AMDGCN20:  call void @llvm.memcpy.p5i8.p1i8.i64(i8 addrspace(5)* align 8 %[[r0]], i8 addrspace(1)* align 8 bitcast (%struct.LargeStructOneMember addrspace(1)* @g_s to i8 addrspace(1)*), i64 800, i1 false)
+// AMDGCN20:  call void @FuncOneLargeMember(%struct.LargeStructOneMember addrspace(5)* byval align 8 %[[byval_temp]])
+#if __OPENCL_C_VERSION__ >= 200
+void test_indirect_arg_globl(void) {
+  FuncOneLargeMember(g_s);
+}
+#endif
+
+// AMDGCN-LABEL: define amdgpu_kernel void @test_indirect_arg_local()
+// AMDGCN: %[[byval_temp:.*]] = alloca %struct.LargeStructOneMember, align 8, addrspace(5)
+// AMDGCN: %[[r0:.*]] = bitcast %struct.LargeStructOneMember addrspace(5)* %[[byval_temp]] to i8 addrspace(5)*
+// AMDGCN: call void @llvm.memcpy.p5i8.p3i8.i64(i8 addrspace(5)* align 8 %[[r0]], i8 addrspace(3)* align 8 bitcast (%struct.LargeStructOneMember addrspace(3)* @test_indirect_arg_local.l_s to i8 addrspace(3)*), i64 800, i1 false)
+// AMDGCN: call void @FuncOneLargeMember(%struct.LargeStructOneMember addrspace(5)* byval align 8 %[[byval_temp]])
+kernel void test_indirect_arg_local(void) {
+  local struct LargeStructOneMember l_s;
+  FuncOneLargeMember(l_s);
+}
+
+// AMDGCN-LABEL: define void @test_indirect_arg_private()
+// AMDGCN: %[[p_s:.*]] = alloca %struct.LargeStructOneMember, align 8, addrspace(5)
+// AMDGCN-NOT: @llvm.memcpy
+// AMDGCN-NEXT: call void @FuncOneLargeMember(%struct.LargeStructOneMember addrspace(5)* byval align 8 %[[p_s]])
+void test_indirect_arg_private(void) {
+  struct LargeStructOneMember p_s;
+  FuncOneLargeMember(p_s);
+}
+
 // AMDGCN-LABEL: define amdgpu_kernel void @KernelOneMember
 // AMDGCN-SAME:  (<2 x i32> %[[u_coerce:.*]])
 // AMDGCN:  %[[u:.*]] = alloca %struct.StructOneMember, align 8, addrspace(5)
@@ -112,7 +148,6 @@
   u.y[0] = (int2)(0, 0);
 }
 
-
 // AMDGCN-LABEL: define amdgpu_kernel void @KernelTwoMember
 // AMDGCN-SAME:  (%struct.StructTwoMember %[[u_coerce:.*]])
 // AMDGCN:  %[[u:.*]] = alloca %struct.StructTwoMember, align 8, addrspace(5)
Index: test/CodeGenCXX/amdgcn-func-arg.cpp
===
--- /dev/null
+++ 

r326942 - Correct the alignment for the PS4 target

2018-03-07 Thread Matthew Voss via cfe-commits
Author: ormris
Date: Wed Mar  7 12:48:16 2018
New Revision: 326942

URL: http://llvm.org/viewvc/llvm-project?rev=326942=rev
Log:
Correct the alignment for the PS4 target

https://reviews.llvm.org/D44218

Modified:
cfe/trunk/lib/Basic/Targets/OSTargets.h
cfe/trunk/test/Preprocessor/init.c

Modified: cfe/trunk/lib/Basic/Targets/OSTargets.h
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Basic/Targets/OSTargets.h?rev=326942=326941=326942=diff
==
--- cfe/trunk/lib/Basic/Targets/OSTargets.h (original)
+++ cfe/trunk/lib/Basic/Targets/OSTargets.h Wed Mar  7 12:48:16 2018
@@ -485,6 +485,7 @@ public:
 default:
 case llvm::Triple::x86_64:
   this->MCountName = ".mcount";
+  this->NewAlign = 256;
   break;
 }
   }

Modified: cfe/trunk/test/Preprocessor/init.c
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/Preprocessor/init.c?rev=326942=326941=326942=diff
==
--- cfe/trunk/test/Preprocessor/init.c (original)
+++ cfe/trunk/test/Preprocessor/init.c Wed Mar  7 12:48:16 2018
@@ -8965,6 +8965,9 @@
 // PS4:#define __x86_64__ 1
 // PS4:#define unix 1
 //
+// RUN: %clang_cc1 -x c++ -E -dM -ffreestanding -triple=x86_64-scei-ps4 < 
/dev/null | FileCheck -match-full-lines -check-prefix PS4-CXX %s
+// PS4-CXX:#define __STDCPP_DEFAULT_NEW_ALIGNMENT__ 32UL
+//
 // RUN: %clang_cc1 -E -dM -triple=x86_64-pc-mingw32 < /dev/null | FileCheck 
-match-full-lines -check-prefix X86-64-DECLSPEC %s
 // RUN: %clang_cc1 -E -dM -fms-extensions -triple=x86_64-unknown-mingw32 < 
/dev/null | FileCheck -match-full-lines -check-prefix X86-64-DECLSPEC %s
 // X86-64-DECLSPEC: #define __declspec{{.*}}


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


[PATCH] D43322: Diagnose cases of "return x" that should be "return std::move(x)" for efficiency

2018-03-07 Thread Arthur O'Dwyer via Phabricator via cfe-commits
Quuxplusone added a comment.

Btw, I'm going to be talking about this patch tonight at 7 in Palo Alto. :)
https://www.meetup.com/ACCU-Bay-Area/events/248040207/
https://docs.google.com/presentation/d/18ZRnedocXSQKn9Eh67gGv-ignReHfRD7vj_dxrra1kc/


Repository:
  rC Clang

https://reviews.llvm.org/D43322



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


RE: [PATCH] D44218: Correct the alignment for the PS4 target

2018-03-07 Thread via cfe-commits
Thanks! I’ll commit this.

From: Eric Christopher [mailto:echri...@gmail.com]
Sent: Wednesday, March 7, 2018 12:33 PM
To: reviews+d44218+public+fd8ca19cc9985...@reviews.llvm.org
Cc: cfe-commits@lists.llvm.org; craig.top...@gmail.com; erich.ke...@intel.com; 
filcab+llvm.phabrica...@gmail.com; Voss, Matthew; rich...@metafoo.co.uk
Subject: Re: [PATCH] D44218: Correct the alignment for the PS4 target

LGTM.
On Wed, Mar 7, 2018, 11:02 AM Matthew Voss via Phabricator 
> wrote:
ormris created this revision.
ormris added reviewers: rsmith, craig.topper, echristo, erichkeane.

See above.


Repository:
  rC Clang

https://reviews.llvm.org/D44218

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


Index: test/Preprocessor/init.c
===
--- test/Preprocessor/init.c
+++ test/Preprocessor/init.c
@@ -8965,6 +8965,9 @@
 // PS4:#define __x86_64__ 1
 // PS4:#define unix 1
 //
+// RUN: %clang_cc1 -x c++ -E -dM -ffreestanding -triple=x86_64-scei-ps4 < 
/dev/null | FileCheck -match-full-lines -check-prefix PS4-CXX %s
+// PS4-CXX:#define __STDCPP_DEFAULT_NEW_ALIGNMENT__ 32UL
+//
 // RUN: %clang_cc1 -E -dM -triple=x86_64-pc-mingw32 < /dev/null | FileCheck 
-match-full-lines -check-prefix X86-64-DECLSPEC %s
 // RUN: %clang_cc1 -E -dM -fms-extensions -triple=x86_64-unknown-mingw32 < 
/dev/null | FileCheck -match-full-lines -check-prefix X86-64-DECLSPEC %s
 // X86-64-DECLSPEC: #define __declspec{{.*}}
Index: lib/Basic/Targets/OSTargets.h
===
--- lib/Basic/Targets/OSTargets.h
+++ lib/Basic/Targets/OSTargets.h
@@ -485,6 +485,7 @@
 default:
 case llvm::Triple::x86_64:
   this->MCountName = ".mcount";
+  this->NewAlign = 256;
   break;
 }
   }

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


[PATCH] D41102: Setup clang-doc frontend framework

2018-03-07 Thread Julie Hockett via Phabricator via cfe-commits
juliehockett updated this revision to Diff 137457.
juliehockett marked 13 inline comments as done.
juliehockett added a comment.

Updating bitcode writer for hashed USRs, and re-running clang-format. Also 
cleaning up a couple of unused fields.


https://reviews.llvm.org/D41102

Files:
  CMakeLists.txt
  clang-doc/BitcodeWriter.cpp
  clang-doc/BitcodeWriter.h
  clang-doc/CMakeLists.txt
  clang-doc/ClangDoc.h
  clang-doc/Mapper.cpp
  clang-doc/Mapper.h
  clang-doc/Representation.h
  clang-doc/Serialize.cpp
  clang-doc/Serialize.h
  clang-doc/tool/CMakeLists.txt
  clang-doc/tool/ClangDocMain.cpp
  docs/clang-doc.rst
  test/CMakeLists.txt
  test/clang-doc/mapper-class-in-class.cpp
  test/clang-doc/mapper-class-in-function.cpp
  test/clang-doc/mapper-class.cpp
  test/clang-doc/mapper-comments.cpp
  test/clang-doc/mapper-enum.cpp
  test/clang-doc/mapper-function.cpp
  test/clang-doc/mapper-method.cpp
  test/clang-doc/mapper-namespace.cpp
  test/clang-doc/mapper-struct.cpp
  test/clang-doc/mapper-union.cpp

Index: test/clang-doc/mapper-union.cpp
===
--- /dev/null
+++ test/clang-doc/mapper-union.cpp
@@ -0,0 +1,28 @@
+// RUN: rm -rf %t
+// RUN: mkdir %t
+// RUN: echo "" > %t/compile_flags.txt
+// RUN: cp "%s" "%t/test.cpp"
+// RUN: clang-doc --dump-mapper --omit-filenames -doxygen -p %t %t/test.cpp -output=%t/docs
+// RUN: llvm-bcanalyzer %t/docs/bc/0B8A6B938B939B77C63258AA3E938BF9E2E8.bc --dump | FileCheck %s
+
+union D { int X; int Y; };
+
+// CHECK: 
+// CHECK-NEXT: 
+  // CHECK-NEXT: 
+// CHECK-NEXT: 
+// CHECK-NEXT: 
+  // CHECK-NEXT:  record string = '0B8A6B938B939B77C63258AA3E938BF9E2E8'
+  // CHECK-NEXT:  blob data = 'D'
+  // CHECK-NEXT: 
+  // CHECK-NEXT: 
+// CHECK-NEXT:  blob data = 'int'
+// CHECK-NEXT:  blob data = 'D::X'
+// CHECK-NEXT: 
+  // CHECK-NEXT: 
+  // CHECK-NEXT: 
+// CHECK-NEXT:  blob data = 'int'
+// CHECK-NEXT:  blob data = 'D::Y'
+// CHECK-NEXT: 
+  // CHECK-NEXT: 
+// CHECK-NEXT: 
Index: test/clang-doc/mapper-struct.cpp
===
--- /dev/null
+++ test/clang-doc/mapper-struct.cpp
@@ -0,0 +1,22 @@
+// RUN: rm -rf %t
+// RUN: mkdir %t
+// RUN: echo "" > %t/compile_flags.txt
+// RUN: cp "%s" "%t/test.cpp"
+// RUN: clang-doc --dump-mapper --omit-filenames -doxygen -p %t %t/test.cpp -output=%t/docs
+// RUN: llvm-bcanalyzer %t/docs/bc/06B5F6A19BA9F6A832E127C9968282B94619B210.bc --dump | FileCheck %s
+
+struct C { int i; };
+
+// CHECK: 
+// CHECK-NEXT: 
+  // CHECK-NEXT: 
+// CHECK-NEXT: 
+// CHECK-NEXT: 
+  // CHECK-NEXT:  record string = '06B5F6A19BA9F6A832E127C9968282B94619B210'
+  // CHECK-NEXT:  blob data = 'C'
+  // CHECK-NEXT: 
+// CHECK-NEXT:  blob data = 'int'
+// CHECK-NEXT:  blob data = 'C::i'
+// CHECK-NEXT: 
+  // CHECK-NEXT: 
+// CHECK-NEXT: 
Index: test/clang-doc/mapper-namespace.cpp
===
--- /dev/null
+++ test/clang-doc/mapper-namespace.cpp
@@ -0,0 +1,17 @@
+// RUN: rm -rf %t
+// RUN: mkdir %t
+// RUN: echo "" > %t/compile_flags.txt
+// RUN: cp "%s" "%t/test.cpp"
+// RUN: clang-doc --dump-mapper --omit-filenames -doxygen -p %t %t/test.cpp -output=%t/docs
+// RUN: llvm-bcanalyzer %t/docs/bc/8D042EFFC98B373450BC6B5B90A330C25A150E9C.bc --dump | FileCheck %s
+
+namespace A {}
+
+// CHECK: 
+// CHECK-NEXT: 
+  // CHECK-NEXT: 
+// CHECK-NEXT: 
+// CHECK-NEXT: 
+  // CHECK-NEXT:  record string = '8D042EFFC98B373450BC6B5B90A330C25A150E9C'
+  // CHECK-NEXT:  blob data = 'A'
+// CHECK-NEXT: 
Index: test/clang-doc/mapper-method.cpp
===
--- /dev/null
+++ test/clang-doc/mapper-method.cpp
@@ -0,0 +1,41 @@
+// RUN: rm -rf %t
+// RUN: mkdir %t
+// RUN: echo "" > %t/compile_flags.txt
+// RUN: cp "%s" "%t/test.cpp"
+// RUN: clang-doc --dump-mapper --omit-filenames -doxygen -p %t %t/test.cpp -output=%t/docs
+// RUN: llvm-bcanalyzer %t/docs/bc/F0F9FC65FC90F54F690144A7AFB15DFC3D69B6E6.bc --dump | FileCheck %s --check-prefix CHECK-G-F
+// RUN: llvm-bcanalyzer %t/docs/bc/4202E8BF0ECB12AE354C8499C52725B0EE30AED5.bc --dump | FileCheck %s --check-prefix CHECK-G
+
+class G {
+public: 
+	int Method(int param) { return param; }
+};
+
+// CHECK-G: 
+// CHECK-G-NEXT: 
+  // CHECK-G-NEXT: 
+// CHECK-G-NEXT: 
+// CHECK-G-NEXT: 
+  // CHECK-G-NEXT:  record string = '4202E8BF0ECB12AE354C8499C52725B0EE30AED5'
+  // CHECK-G-NEXT:  blob data = 'G'
+  // CHECK-G-NEXT: 
+// CHECK-G-NEXT: 
+
+// CHECK-G-F: 
+// CHECK-G-F-NEXT: 
+  // CHECK-G-F-NEXT: 
+// CHECK-G-F-NEXT: 
+// CHECK-G-F-NEXT: 
+  // CHECK-G-F-NEXT:  record string = 'F0F9FC65FC90F54F690144A7AFB15DFC3D69B6E6'
+  // CHECK-G-F-NEXT:  blob data = 'Method'
+  // CHECK-G-F-NEXT:  blob data = '4202E8BF0ECB12AE354C8499C52725B0EE30AED5'
+  // CHECK-G-F-NEXT: 
+  // CHECK-G-F-NEXT:  blob data = '4202E8BF0ECB12AE354C8499C52725B0EE30AED5'
+  // CHECK-G-F-NEXT: 
+// 

[PATCH] D44223: [ms] Emit vtordisp initializers in a deterministic order.

2018-03-07 Thread Eli Friedman via Phabricator via cfe-commits
efriedma added inline comments.



Comment at: lib/CodeGen/MicrosoftCXXABI.cpp:1202
+  SmallVector VBases(VBaseMap.begin(), VBaseMap.end());
+  std::stable_sort(VBases.begin(), VBases.end(),
+   [](const VBaseEntry , const VBaseEntry ) {

Using stable_sort() here, as opposed to sort(), doesn't do anything useful 
here; VBaseMap is a DenseMap with a pointer key, so the input is in random 
order anyway.


https://reviews.llvm.org/D44223



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


Re: [PATCH] D44218: Correct the alignment for the PS4 target

2018-03-07 Thread Eric Christopher via cfe-commits
LGTM.

On Wed, Mar 7, 2018, 11:02 AM Matthew Voss via Phabricator <
revi...@reviews.llvm.org> wrote:

> ormris created this revision.
> ormris added reviewers: rsmith, craig.topper, echristo, erichkeane.
>
> See above.
>
>
> Repository:
>   rC Clang
>
> https://reviews.llvm.org/D44218
>
> Files:
>   lib/Basic/Targets/OSTargets.h
>   test/Preprocessor/init.c
>
>
> Index: test/Preprocessor/init.c
> ===
> --- test/Preprocessor/init.c
> +++ test/Preprocessor/init.c
> @@ -8965,6 +8965,9 @@
>  // PS4:#define __x86_64__ 1
>  // PS4:#define unix 1
>  //
> +// RUN: %clang_cc1 -x c++ -E -dM -ffreestanding -triple=x86_64-scei-ps4 <
> /dev/null | FileCheck -match-full-lines -check-prefix PS4-CXX %s
> +// PS4-CXX:#define __STDCPP_DEFAULT_NEW_ALIGNMENT__ 32UL
> +//
>  // RUN: %clang_cc1 -E -dM -triple=x86_64-pc-mingw32 < /dev/null |
> FileCheck -match-full-lines -check-prefix X86-64-DECLSPEC %s
>  // RUN: %clang_cc1 -E -dM -fms-extensions -triple=x86_64-unknown-mingw32
> < /dev/null | FileCheck -match-full-lines -check-prefix X86-64-DECLSPEC %s
>  // X86-64-DECLSPEC: #define __declspec{{.*}}
> Index: lib/Basic/Targets/OSTargets.h
> ===
> --- lib/Basic/Targets/OSTargets.h
> +++ lib/Basic/Targets/OSTargets.h
> @@ -485,6 +485,7 @@
>  default:
>  case llvm::Triple::x86_64:
>this->MCountName = ".mcount";
> +  this->NewAlign = 256;
>break;
>  }
>}
>
>
>
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D44223: [ms] Emit vtordisp initializers in a deterministic order.

2018-03-07 Thread Nico Weber via Phabricator via cfe-commits
thakis added inline comments.



Comment at: lib/CodeGen/MicrosoftCXXABI.cpp:1207
+
+  for (const VBaseEntry E : VBases) {
+if (!E.second.hasVtorDisp())

(I added the missing `&` here locally.)


https://reviews.llvm.org/D44223



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


[PATCH] D44223: [ms] Emit vtordisp initializers in a deterministic order.

2018-03-07 Thread Nico Weber via Phabricator via cfe-commits
thakis created this revision.
thakis added a reviewer: rnk.

No effective behavior change, just for cleanliness.

Fixes PR36159.


https://reviews.llvm.org/D44223

Files:
  lib/CodeGen/MicrosoftCXXABI.cpp


Index: lib/CodeGen/MicrosoftCXXABI.cpp
===
--- lib/CodeGen/MicrosoftCXXABI.cpp
+++ lib/CodeGen/MicrosoftCXXABI.cpp
@@ -1196,15 +1196,22 @@
   unsigned AS = getThisAddress(CGF).getAddressSpace();
   llvm::Value *Int8This = nullptr;  // Initialize lazily.
 
-  for (VBOffsets::const_iterator I = VBaseMap.begin(), E = VBaseMap.end();
-I != E; ++I) {
-if (!I->second.hasVtorDisp())
+  // Emit vtordisps in vbase offset order, to have deterministic output.
+  typedef VBOffsets::value_type VBaseEntry;
+  SmallVector VBases(VBaseMap.begin(), VBaseMap.end());
+  std::stable_sort(VBases.begin(), VBases.end(),
+   [](const VBaseEntry , const VBaseEntry ) {
+ return a.second.VBaseOffset < b.second.VBaseOffset;
+   });
+
+  for (const VBaseEntry E : VBases) {
+if (!E.second.hasVtorDisp())
   continue;
 
 llvm::Value *VBaseOffset =
-GetVirtualBaseClassOffset(CGF, getThisAddress(CGF), RD, I->first);
+GetVirtualBaseClassOffset(CGF, getThisAddress(CGF), RD, E.first);
 uint64_t ConstantVBaseOffset =
-Layout.getVBaseClassOffset(I->first).getQuantity();
+Layout.getVBaseClassOffset(E.first).getQuantity();
 
 // vtorDisp_for_vbase = vbptr[vbase_idx] - offsetof(RD, vbase).
 llvm::Value *VtorDispValue = Builder.CreateSub(


Index: lib/CodeGen/MicrosoftCXXABI.cpp
===
--- lib/CodeGen/MicrosoftCXXABI.cpp
+++ lib/CodeGen/MicrosoftCXXABI.cpp
@@ -1196,15 +1196,22 @@
   unsigned AS = getThisAddress(CGF).getAddressSpace();
   llvm::Value *Int8This = nullptr;  // Initialize lazily.
 
-  for (VBOffsets::const_iterator I = VBaseMap.begin(), E = VBaseMap.end();
-I != E; ++I) {
-if (!I->second.hasVtorDisp())
+  // Emit vtordisps in vbase offset order, to have deterministic output.
+  typedef VBOffsets::value_type VBaseEntry;
+  SmallVector VBases(VBaseMap.begin(), VBaseMap.end());
+  std::stable_sort(VBases.begin(), VBases.end(),
+   [](const VBaseEntry , const VBaseEntry ) {
+ return a.second.VBaseOffset < b.second.VBaseOffset;
+   });
+
+  for (const VBaseEntry E : VBases) {
+if (!E.second.hasVtorDisp())
   continue;
 
 llvm::Value *VBaseOffset =
-GetVirtualBaseClassOffset(CGF, getThisAddress(CGF), RD, I->first);
+GetVirtualBaseClassOffset(CGF, getThisAddress(CGF), RD, E.first);
 uint64_t ConstantVBaseOffset =
-Layout.getVBaseClassOffset(I->first).getQuantity();
+Layout.getVBaseClassOffset(E.first).getQuantity();
 
 // vtorDisp_for_vbase = vbptr[vbase_idx] - offsetof(RD, vbase).
 llvm::Value *VtorDispValue = Builder.CreateSub(
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D34367: CodeGen: Fix address space of indirect function argument

2018-03-07 Thread John McCall via Phabricator via cfe-commits
rjmccall added inline comments.



Comment at: lib/CodeGen/CGCall.cpp:3427
 (void)InitialArgSize;
-RValue RVArg = Args.back().RV;
-EmitNonNullArgCheck(RVArg, ArgTypes[Idx], (*Arg)->getExprLoc(), AC,
-ParamsToSkip + Idx);
-// @llvm.objectsize should never have side-effects and shouldn't need
-// destruction/cleanups, so we can safely "emit" it after its arg,
-// regardless of right-to-leftness
-MaybeEmitImplicitObjectSize(Idx, *Arg, RVArg);
+if (!Args.back().hasLValue()) {
+  RValue RVArg = Args.back().getKnownRValue();

I think it's okay to do this because of a reasonable assumption that pointer 
arguments are never emitted as LValues, but you should leave that as a comment.


https://reviews.llvm.org/D34367



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


[PATCH] D44222: [AArch64] Add vmulxh_lane FP16 intrinsics

2018-03-07 Thread Sjoerd Meijer via Phabricator via cfe-commits
SjoerdMeijer created this revision.
SjoerdMeijer added reviewers: az, evandro, olista01.
Herald added subscribers: kristof.beyls, javed.absar, rengolin.

Add 2 vmulxh_lane vector intrinsics that were commented out.


https://reviews.llvm.org/D44222

Files:
  include/clang/Basic/arm_neon.td
  test/CodeGen/aarch64-v8.2a-neon-intrinsics.c


Index: test/CodeGen/aarch64-v8.2a-neon-intrinsics.c
===
--- test/CodeGen/aarch64-v8.2a-neon-intrinsics.c
+++ test/CodeGen/aarch64-v8.2a-neon-intrinsics.c
@@ -1223,27 +1223,25 @@
   return vmulxq_n_f16(a, b);
 }
 
-/* TODO: Not implemented yet (needs scalar intrinsic from arm_fp16.h)
-// CCHECK-LABEL: test_vmulxh_lane_f16
-// CCHECK: [[CONV0:%.*]] = fpext half %a to float
-// CCHECK: [[CONV1:%.*]] = fpext half %{{.*}} to float
-// CCHECK: [[MUL:%.*]]   = fmul float [[CONV0:%.*]], [[CONV0:%.*]]
-// CCHECK: [[CONV3:%.*]] = fptrunc float %mul to half
-// CCHECK: ret half [[CONV3:%.*]]
+// CHECK-LABEL: test_vmulxh_lane_f16
+// CHECK: [[CONV0:%.*]] = fpext half %a to float
+// CHECK: [[CONV1:%.*]] = fpext half %{{.*}} to float
+// CHECK: [[MUL:%.*]]   = fmul float [[CONV0:%.*]], [[CONV0:%.*]]
+// CHECK: [[CONV3:%.*]] = fptrunc float %mul to half
+// CHECK: ret half [[CONV3:%.*]]
 float16_t test_vmulxh_lane_f16(float16_t a, float16x4_t b) {
   return vmulxh_lane_f16(a, b, 3);
 }
 
-// CCHECK-LABEL: test_vmulxh_laneq_f16
-// CCHECK: [[CONV0:%.*]] = fpext half %a to float
-// CCHECK: [[CONV1:%.*]] = fpext half %{{.*}} to float
-// CCHECK: [[MUL:%.*]]   = fmul float [[CONV0:%.*]], [[CONV0:%.*]]
-// CCHECK: [[CONV3:%.*]] = fptrunc float %mul to half
-// CCHECK: ret half [[CONV3:%.*]]
+// CHECK-LABEL: test_vmulxh_laneq_f16
+// CHECK: [[CONV0:%.*]] = fpext half %a to float
+// CHECK: [[CONV1:%.*]] = fpext half %{{.*}} to float
+// CHECK: [[MUL:%.*]]   = fmul float [[CONV0:%.*]], [[CONV0:%.*]]
+// CHECK: [[CONV3:%.*]] = fptrunc float %mul to half
+// CHECK: ret half [[CONV3:%.*]]
 float16_t test_vmulxh_laneq_f16(float16_t a, float16x8_t b) {
   return vmulxh_laneq_f16(a, b, 7);
 }
-*/
 
 // CHECK-LABEL: test_vmaxv_f16
 // CHECK: [[TMP0:%.*]] = bitcast <4 x half> %a to <8 x i8>
Index: include/clang/Basic/arm_neon.td
===
--- include/clang/Basic/arm_neon.td
+++ include/clang/Basic/arm_neon.td
@@ -1499,11 +1499,10 @@
   def VMULX_LANEH   : IOpInst<"vmulx_lane", "ddgi", "hQh", OP_MULX_LN>;
   def VMULX_LANEQH  : IOpInst<"vmulx_laneq", "ddji", "hQh", OP_MULX_LN>;
   def VMULX_NH  : IOpInst<"vmulx_n", "dds", "hQh", OP_MULX_N>;
-  // TODO: Scalar floating point multiply extended (scalar, by element)
-  // Below ones are commented out because they need vmulx_f16(float16_t, 
float16_t)
-  // which will be implemented later with fp16 scalar intrinsic (arm_fp16.h)
-  //def SCALAR_FMULX_LANEH : IOpInst<"vmulx_lane", "ssdi", "Sh", 
OP_SCALAR_MUL_LN>;
-  //def SCALAR_FMULX_LANEQH : IOpInst<"vmulx_laneq", "ssji", "Sh", 
OP_SCALAR_MUL_LN>;
+
+  // Scalar floating point multiply extended (scalar, by element)
+  def SCALAR_FMULX_LANEH : IOpInst<"vmulx_lane", "ssdi", "Sh", 
OP_SCALAR_MUL_LN>;
+  def SCALAR_FMULX_LANEQH : IOpInst<"vmulx_laneq", "ssji", "Sh", 
OP_SCALAR_MUL_LN>;
 
   // ARMv8.2-A FP16 reduction vector intrinsics.
   def VMAXVH   : SInst<"vmaxv", "sd", "hQh">;


Index: test/CodeGen/aarch64-v8.2a-neon-intrinsics.c
===
--- test/CodeGen/aarch64-v8.2a-neon-intrinsics.c
+++ test/CodeGen/aarch64-v8.2a-neon-intrinsics.c
@@ -1223,27 +1223,25 @@
   return vmulxq_n_f16(a, b);
 }
 
-/* TODO: Not implemented yet (needs scalar intrinsic from arm_fp16.h)
-// CCHECK-LABEL: test_vmulxh_lane_f16
-// CCHECK: [[CONV0:%.*]] = fpext half %a to float
-// CCHECK: [[CONV1:%.*]] = fpext half %{{.*}} to float
-// CCHECK: [[MUL:%.*]]   = fmul float [[CONV0:%.*]], [[CONV0:%.*]]
-// CCHECK: [[CONV3:%.*]] = fptrunc float %mul to half
-// CCHECK: ret half [[CONV3:%.*]]
+// CHECK-LABEL: test_vmulxh_lane_f16
+// CHECK: [[CONV0:%.*]] = fpext half %a to float
+// CHECK: [[CONV1:%.*]] = fpext half %{{.*}} to float
+// CHECK: [[MUL:%.*]]   = fmul float [[CONV0:%.*]], [[CONV0:%.*]]
+// CHECK: [[CONV3:%.*]] = fptrunc float %mul to half
+// CHECK: ret half [[CONV3:%.*]]
 float16_t test_vmulxh_lane_f16(float16_t a, float16x4_t b) {
   return vmulxh_lane_f16(a, b, 3);
 }
 
-// CCHECK-LABEL: test_vmulxh_laneq_f16
-// CCHECK: [[CONV0:%.*]] = fpext half %a to float
-// CCHECK: [[CONV1:%.*]] = fpext half %{{.*}} to float
-// CCHECK: [[MUL:%.*]]   = fmul float [[CONV0:%.*]], [[CONV0:%.*]]
-// CCHECK: [[CONV3:%.*]] = fptrunc float %mul to half
-// CCHECK: ret half [[CONV3:%.*]]
+// CHECK-LABEL: test_vmulxh_laneq_f16
+// CHECK: [[CONV0:%.*]] = fpext half %a to float
+// CHECK: [[CONV1:%.*]] = fpext half %{{.*}} to float
+// CHECK: [[MUL:%.*]]   = fmul float [[CONV0:%.*]], [[CONV0:%.*]]
+// CHECK: [[CONV3:%.*]] = fptrunc float %mul to half
+// 

[PATCH] D44221: Avoid including ScopeInfo.h from Sema.h

2018-03-07 Thread John McCall via Phabricator via cfe-commits
rjmccall accepted this revision.
rjmccall added a comment.
This revision is now accepted and ready to land.

LGTM.


https://reviews.llvm.org/D44221



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


[PATCH] D41102: Setup clang-doc frontend framework

2018-03-07 Thread Roman Lebedev via Phabricator via cfe-commits
lebedev.ri added a comment.

In https://reviews.llvm.org/D41102#1028995, @lebedev.ri wrote:

> Some further notes based on the SHA1 nature.


I'm sorry, brainfreeze, i meant `40` chars, not `20`.
Updated comments...




Comment at: clang-doc/BitcodeWriter.cpp:309
+  assert(Ref.USR.size() < (1U << BitCodeConstants::USRLengthSize));
+  Record.push_back(Ref.USR.size());
+  Stream.EmitRecordWithBlob(Abbrevs.get(ID), Record, Ref.USR);

lebedev.ri wrote:
> Now it would make sense to also assert that this sha1(usr).strlen() == 20
40 that is



Comment at: clang-doc/BitcodeWriter.h:46
+  static constexpr unsigned ReferenceTypeSize = 8U;
+  static constexpr unsigned USRLengthSize = 16U;
+};

lebedev.ri wrote:
> Can definitively lower this to `5U` (2^6 == 32, which is more than the 20 
> 8-bit chars of sha1)
Edit: to 6U (2^6 == 64, which is more than the 40 8-bit chars of sha1)



Comment at: clang-doc/Representation.h:59
+
+  SmallString<16> USR;
+  InfoType RefType = InfoType::IT_default;

lebedev.ri wrote:
> Now that USR is sha1'd, this is **always** 20 8-bit characters long.
40 that is



Comment at: clang-doc/Representation.h:107
+
+  SmallString<16> USR;
+  SmallString<16> Name;

lebedev.ri wrote:
> `20`
> Maybe place `using USRString = SmallString<20>; // SHA1 of USR` somewhere and 
> use it everywhere?
40


https://reviews.llvm.org/D41102



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


[PATCH] D44221: Avoid including ScopeInfo.h from Sema.h

2018-03-07 Thread Reid Kleckner via Phabricator via cfe-commits
rnk created this revision.
rnk added a reviewer: rjmccall.

This provides no measurable build speedup, but it reinstates an
optimization from r112038 that was lost in r179618.  It requires moving
CapturedScopeInfo::Capture out to clang::sema, which might be too
general since we have plenty of other Capture records in BlockDecl and
other AST nodes.


https://reviews.llvm.org/D44221

Files:
  clang/include/clang/Sema/ScopeInfo.h
  clang/include/clang/Sema/Sema.h
  clang/include/clang/Sema/SemaLambda.h
  clang/lib/Sema/Sema.cpp
  clang/lib/Sema/SemaCoroutine.cpp
  clang/lib/Sema/SemaDecl.cpp
  clang/lib/Sema/SemaDeclAttr.cpp
  clang/lib/Sema/SemaExpr.cpp
  clang/lib/Sema/SemaLambda.cpp
  clang/lib/Sema/SemaStmt.cpp

Index: clang/lib/Sema/SemaStmt.cpp
===
--- clang/lib/Sema/SemaStmt.cpp
+++ clang/lib/Sema/SemaStmt.cpp
@@ -4040,32 +4040,29 @@
   return RD;
 }
 
-static void buildCapturedStmtCaptureList(
-SmallVectorImpl ,
-SmallVectorImpl ,
-ArrayRef Candidates) {
-
-  typedef ArrayRef::const_iterator CaptureIter;
-  for (CaptureIter Cap = Candidates.begin(); Cap != Candidates.end(); ++Cap) {
-
-if (Cap->isThisCapture()) {
-  Captures.push_back(CapturedStmt::Capture(Cap->getLocation(),
+static void
+buildCapturedStmtCaptureList(SmallVectorImpl ,
+ SmallVectorImpl ,
+ ArrayRef Candidates) {
+  for (const sema::Capture  : Candidates) {
+if (Cap.isThisCapture()) {
+  Captures.push_back(CapturedStmt::Capture(Cap.getLocation(),
CapturedStmt::VCK_This));
-  CaptureInits.push_back(Cap->getInitExpr());
+  CaptureInits.push_back(Cap.getInitExpr());
   continue;
-} else if (Cap->isVLATypeCapture()) {
+} else if (Cap.isVLATypeCapture()) {
   Captures.push_back(
-  CapturedStmt::Capture(Cap->getLocation(), CapturedStmt::VCK_VLAType));
+  CapturedStmt::Capture(Cap.getLocation(), CapturedStmt::VCK_VLAType));
   CaptureInits.push_back(nullptr);
   continue;
 }
 
-Captures.push_back(CapturedStmt::Capture(Cap->getLocation(),
- Cap->isReferenceCapture()
+Captures.push_back(CapturedStmt::Capture(Cap.getLocation(),
+ Cap.isReferenceCapture()
  ? CapturedStmt::VCK_ByRef
  : CapturedStmt::VCK_ByCopy,
- Cap->getVariable()));
-CaptureInits.push_back(Cap->getInitExpr());
+ Cap.getVariable()));
+CaptureInits.push_back(Cap.getInitExpr());
   }
 }
 
Index: clang/lib/Sema/SemaLambda.cpp
===
--- clang/lib/Sema/SemaLambda.cpp
+++ clang/lib/Sema/SemaLambda.cpp
@@ -1388,8 +1388,9 @@
   Class->addDecl(Conversion);
 }
 
-static ExprResult performLambdaVarCaptureInitialization(
-Sema , const LambdaScopeInfo::Capture , FieldDecl *Field) {
+static ExprResult performLambdaVarCaptureInitialization(Sema ,
+const Capture ,
+FieldDecl *Field) {
   assert(Capture.isVariableCapture() && "not a variable capture");
 
   auto *Var = Capture.getVariable();
@@ -1443,7 +1444,7 @@
   llvm_unreachable("Unknown implicit capture style");
 }
 
-bool Sema::CaptureHasSideEffects(const LambdaScopeInfo::Capture ) {
+bool Sema::CaptureHasSideEffects(const Capture ) {
   if (!From.isVLATypeCapture()) {
 Expr *Init = From.getInitExpr();
 if (Init && Init->HasSideEffects(Context))
@@ -1468,7 +1469,7 @@
   return false;
 }
 
-void Sema::DiagnoseUnusedLambdaCapture(const LambdaScopeInfo::Capture ) {
+void Sema::DiagnoseUnusedLambdaCapture(const Capture ) {
   if (CaptureHasSideEffects(From))
 return;
 
@@ -1523,7 +1524,7 @@
 // Translate captures.
 auto CurField = Class->field_begin();
 for (unsigned I = 0, N = LSI->Captures.size(); I != N; ++I, ++CurField) {
-  const LambdaScopeInfo::Capture  = LSI->Captures[I];
+  const Capture  = LSI->Captures[I];
   assert(!From.isBlockCapture() && "Cannot capture __block variables");
   bool IsImplicit = I >= LSI->NumExplicitCaptures;
 
Index: clang/lib/Sema/SemaExpr.cpp
===
--- clang/lib/Sema/SemaExpr.cpp
+++ clang/lib/Sema/SemaExpr.cpp
@@ -13045,7 +13045,7 @@
   // Set the captured variables on the block.
   // FIXME: Share capture structure between BlockDecl and CapturingScopeInfo!
   SmallVector Captures;
-  for (CapturingScopeInfo::Capture  : BSI->Captures) {
+  for (Capture  : BSI->Captures) {
 if (Cap.isThisCapture())
   continue;
 BlockDecl::Capture NewCap(Cap.getVariable(), 

[PATCH] D44069: Test Driver sanitise, unsupported on OpenBSD

2018-03-07 Thread David CARLIER via Phabricator via cfe-commits
devnexen updated this revision to Diff 137448.

https://reviews.llvm.org/D44069

Files:
  test/Driver/fsanitize.c


Index: test/Driver/fsanitize.c
===
--- test/Driver/fsanitize.c
+++ test/Driver/fsanitize.c
@@ -388,6 +388,25 @@
 // RUN: %clang -target armv7-apple-ios7 -miphoneos-version-min=7.0 
-fsanitize=address %s -### 2>&1 | FileCheck %s --check-prefix=CHECK-ASAN-IOS
 // CHECK-ASAN-IOS: -fsanitize=address
 
+// RUN %clang -target i386-pc-openbsd -fsanitize=undefined %s -### 2>&1 | 
FileCheck --check-prefix=CHECK-UBSAN-OPENBSD
+// CHECK-UBSAN-OPENBSD: -fsanitize=undefined
+
+// RUN: %clang -target i386-pc-openbsd -fsanitize=address %s -### 2>&1 | 
FileCheck %s --check-prefix=CHECK-ASAN-OPENBSD
+// CHECK-ASAN-OPENBSD: unsupported option '-fsanitize=address' for target 
'i386-pc-openbsd'
+
+// RUN: %clang -target i386-pc-openbsd -fsanitize=leak %s -### 2>&1 | 
FileCheck %s --check-prefix=CHECK-LSAN-OPENBSD
+// CHECK-LSAN-OPENBSD: unsupported option '-fsanitize=leak' for target 
'i386-pc-openbsd'
+
+// RUN: %clang -target i386-pc-openbsd -fsanitize=thread %s -### 2>&1 | 
FileCheck %s --check-prefix=CHECK-TSAN-OPENBSD
+// CHECK-TSAN-OPENBSD: unsupported option '-fsanitize=thread' for target 
'i386-pc-openbsd'
+
+// RUN: %clang -target i386-pc-openbsd -fsanitize=memory %s -### 2>&1 | 
FileCheck %s --check-prefix=CHECK-MSAN-OPENBSD
+// CHECK-MSAN-OPENBSD: unsupported option '-fsanitize=memory' for target 
'i386-pc-openbsd'
+
+// RUN: %clang -target i386-pc-openbsd -fsanitize=efficiency-cache-frag %s 
-### 2>&1 | FileCheck %s --check-prefix=CHECK-ESAN-OPENBSD
+// RUN: %clang -target i386-pc-openbsd -fsanitize=efficiency-working-set %s 
-### 2>&1 | FileCheck %s --check-prefix=CHECK-ESAN-OPENBSD
+// CHECK-ESAN-OPENBSD: error: unsupported option 
'-fsanitize=efficiency-{{.*}}' for target 'i386-pc-openbsd'
+
 // RUN: %clang -target x86_64-apple-darwin -fsanitize=leak %s -### 2>&1 | 
FileCheck %s --check-prefix=CHECK-LSAN-X86-64-DARWIN
 // CHECK-LSAN-X86-64-DARWIN-NOT: unsupported option
 


Index: test/Driver/fsanitize.c
===
--- test/Driver/fsanitize.c
+++ test/Driver/fsanitize.c
@@ -388,6 +388,25 @@
 // RUN: %clang -target armv7-apple-ios7 -miphoneos-version-min=7.0 -fsanitize=address %s -### 2>&1 | FileCheck %s --check-prefix=CHECK-ASAN-IOS
 // CHECK-ASAN-IOS: -fsanitize=address
 
+// RUN %clang -target i386-pc-openbsd -fsanitize=undefined %s -### 2>&1 | FileCheck --check-prefix=CHECK-UBSAN-OPENBSD
+// CHECK-UBSAN-OPENBSD: -fsanitize=undefined
+
+// RUN: %clang -target i386-pc-openbsd -fsanitize=address %s -### 2>&1 | FileCheck %s --check-prefix=CHECK-ASAN-OPENBSD
+// CHECK-ASAN-OPENBSD: unsupported option '-fsanitize=address' for target 'i386-pc-openbsd'
+
+// RUN: %clang -target i386-pc-openbsd -fsanitize=leak %s -### 2>&1 | FileCheck %s --check-prefix=CHECK-LSAN-OPENBSD
+// CHECK-LSAN-OPENBSD: unsupported option '-fsanitize=leak' for target 'i386-pc-openbsd'
+
+// RUN: %clang -target i386-pc-openbsd -fsanitize=thread %s -### 2>&1 | FileCheck %s --check-prefix=CHECK-TSAN-OPENBSD
+// CHECK-TSAN-OPENBSD: unsupported option '-fsanitize=thread' for target 'i386-pc-openbsd'
+
+// RUN: %clang -target i386-pc-openbsd -fsanitize=memory %s -### 2>&1 | FileCheck %s --check-prefix=CHECK-MSAN-OPENBSD
+// CHECK-MSAN-OPENBSD: unsupported option '-fsanitize=memory' for target 'i386-pc-openbsd'
+
+// RUN: %clang -target i386-pc-openbsd -fsanitize=efficiency-cache-frag %s -### 2>&1 | FileCheck %s --check-prefix=CHECK-ESAN-OPENBSD
+// RUN: %clang -target i386-pc-openbsd -fsanitize=efficiency-working-set %s -### 2>&1 | FileCheck %s --check-prefix=CHECK-ESAN-OPENBSD
+// CHECK-ESAN-OPENBSD: error: unsupported option '-fsanitize=efficiency-{{.*}}' for target 'i386-pc-openbsd'
+
 // RUN: %clang -target x86_64-apple-darwin -fsanitize=leak %s -### 2>&1 | FileCheck %s --check-prefix=CHECK-LSAN-X86-64-DARWIN
 // CHECK-LSAN-X86-64-DARWIN-NOT: unsupported option
 
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D43980: Push a function scope when parsing function bodies without a declaration

2018-03-07 Thread Reid Kleckner via Phabricator via cfe-commits
rnk added a comment.

Thanks!

John touched this code last in https://reviews.llvm.org/rL112038 in 2010, so 
maybe he has some thoughts on how to clean this and the follow-up. I think I'll 
land this as is since it fixes the crash and we can discuss more improvements 
in https://reviews.llvm.org/D44039.




Comment at: clang/lib/Sema/SemaDecl.cpp:12412
+// anyway so we can try to parse the function body.
+PushFunctionScope();
 return D;

thakis wrote:
> Feels a bit long-term risky since ActOnStartOfFunctionDef() and 
> ActOnFinishFunctionBody() both need to know about this special-case 
> invariant. Maybe it's worth to add a FakeFunctionScopeCount member to sema in 
> +assert builds, and to increment that here, assert it's > 0 in the other 
> place and decrement it there, and then assert it's 0 at end of TU?
Well, it's more like these early returns break the invariant that 
`ActOnStartOfFunctionDef` pushes a function scope. We could try to clean it up 
with an RAII helper or an layer of function call that ensures that we always 
push and pop on start and finish, but I'll leave that for the follow-up.



Comment at: clang/test/SemaCXX/pr36536.cpp:19
+  // this when they forget to close a namespace, and we'd generate far fewer
+  // errors if names in Foo were in scope.
+  // expected-error@+1 {{unknown type name 'NameInClass'}}

thakis wrote:
> Not 100% clear to me what the FIXME is here. Maybe "FIXME: We should improve 
> our recovery to redeclare" if that's what's meant.
I rewrote this to clarify things.


Repository:
  rC Clang

https://reviews.llvm.org/D43980



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


[PATCH] D44069: Test Driver sanitise, unsupported on OpenBSD

2018-03-07 Thread David CARLIER via Phabricator via cfe-commits
devnexen updated this revision to Diff 137447.

https://reviews.llvm.org/D44069

Files:
  test/Driver/fsanitize.c


Index: test/Driver/fsanitize.c
===
--- test/Driver/fsanitize.c
+++ test/Driver/fsanitize.c
@@ -388,6 +388,21 @@
 // RUN: %clang -target armv7-apple-ios7 -miphoneos-version-min=7.0 
-fsanitize=address %s -### 2>&1 | FileCheck %s --check-prefix=CHECK-ASAN-IOS
 // CHECK-ASAN-IOS: -fsanitize=address
 
+// RUN %clang -target i386-pc-openbsd -fsanitize=undefined %s -### 2>&1 | 
FileCheck --check-prefix=CHECK-UBSAN-OPENBSD
+// CHECK-UBSAN-OPENBSD: -fsanitize=undefined
+
+// RUN: %clang -target i386-pc-openbsd -fsanitize=address %s -### 2>&1 | 
FileCheck %s --check-prefix=CHECK-ASAN-OPENBSD
+// CHECK-ASAN-OPENBSD: unsupported option '-fsanitize=address' for target 
'i386-pc-openbsd'
+
+// RUN: %clang -target i386-pc-openbsd -fsanitize=leak %s -### 2>&1 | 
FileCheck %s --check-prefix=CHECK-LSAN-OPENBSD
+// CHECK-LSAN-OPENBSD: unsupported option '-fsanitize=leak' for target 
'i386-pc-openbsd'
+
+// RUN: %clang -target i386-pc-openbsd -fsanitize=thread %s -### 2>&1 | 
FileCheck %s --check-prefix=CHECK-TSAN-OPENBSD
+// CHECK-TSAN-OPENBSD: unsupported option '-fsanitize=thread' for target 
'i386-pc-openbsd'
+
+// RUN: %clang -target i386-pc-openbsd -fsanitize=memory %s -### 2>&1 | 
FileCheck %s --check-prefix=CHECK-MSAN-OPENBSD
+// CHECK-MSAN-OPENBSD: unsupported option '-fsanitize=memory' for target 
'i386-pc-openbsd'
+
 // RUN: %clang -target x86_64-apple-darwin -fsanitize=leak %s -### 2>&1 | 
FileCheck %s --check-prefix=CHECK-LSAN-X86-64-DARWIN
 // CHECK-LSAN-X86-64-DARWIN-NOT: unsupported option
 


Index: test/Driver/fsanitize.c
===
--- test/Driver/fsanitize.c
+++ test/Driver/fsanitize.c
@@ -388,6 +388,21 @@
 // RUN: %clang -target armv7-apple-ios7 -miphoneos-version-min=7.0 -fsanitize=address %s -### 2>&1 | FileCheck %s --check-prefix=CHECK-ASAN-IOS
 // CHECK-ASAN-IOS: -fsanitize=address
 
+// RUN %clang -target i386-pc-openbsd -fsanitize=undefined %s -### 2>&1 | FileCheck --check-prefix=CHECK-UBSAN-OPENBSD
+// CHECK-UBSAN-OPENBSD: -fsanitize=undefined
+
+// RUN: %clang -target i386-pc-openbsd -fsanitize=address %s -### 2>&1 | FileCheck %s --check-prefix=CHECK-ASAN-OPENBSD
+// CHECK-ASAN-OPENBSD: unsupported option '-fsanitize=address' for target 'i386-pc-openbsd'
+
+// RUN: %clang -target i386-pc-openbsd -fsanitize=leak %s -### 2>&1 | FileCheck %s --check-prefix=CHECK-LSAN-OPENBSD
+// CHECK-LSAN-OPENBSD: unsupported option '-fsanitize=leak' for target 'i386-pc-openbsd'
+
+// RUN: %clang -target i386-pc-openbsd -fsanitize=thread %s -### 2>&1 | FileCheck %s --check-prefix=CHECK-TSAN-OPENBSD
+// CHECK-TSAN-OPENBSD: unsupported option '-fsanitize=thread' for target 'i386-pc-openbsd'
+
+// RUN: %clang -target i386-pc-openbsd -fsanitize=memory %s -### 2>&1 | FileCheck %s --check-prefix=CHECK-MSAN-OPENBSD
+// CHECK-MSAN-OPENBSD: unsupported option '-fsanitize=memory' for target 'i386-pc-openbsd'
+
 // RUN: %clang -target x86_64-apple-darwin -fsanitize=leak %s -### 2>&1 | FileCheck %s --check-prefix=CHECK-LSAN-X86-64-DARWIN
 // CHECK-LSAN-X86-64-DARWIN-NOT: unsupported option
 
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D43783: [OpenCL] Remove block invoke function from emitted block literal struct

2018-03-07 Thread Yaxun Liu via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rC326937: [OpenCL] Remove block invoke function from emitted 
block literal struct (authored by yaxunl, committed by ).

Repository:
  rC Clang

https://reviews.llvm.org/D43783

Files:
  lib/CodeGen/CGBlocks.cpp
  lib/CodeGen/CGOpenCLRuntime.cpp
  lib/CodeGen/CGOpenCLRuntime.h
  test/CodeGenOpenCL/amdgpu-enqueue-kernel.cl
  test/CodeGenOpenCL/blocks.cl
  test/CodeGenOpenCL/cl20-device-side-enqueue.cl

Index: test/CodeGenOpenCL/blocks.cl
===
--- test/CodeGenOpenCL/blocks.cl
+++ test/CodeGenOpenCL/blocks.cl
@@ -1,10 +1,7 @@
 // RUN: %clang_cc1 %s -cl-std=CL2.0 -emit-llvm -o - -O0 -triple spir-unknown-unknown | FileCheck -check-prefixes=COMMON,SPIR %s
 // RUN: %clang_cc1 %s -cl-std=CL2.0 -emit-llvm -o - -O0 -triple amdgcn-amd-amdhsa | FileCheck -check-prefixes=COMMON,AMDGCN %s
 
-// SPIR: %struct.__opencl_block_literal_generic = type { i32, i32, i8 addrspace(4)* }
-// AMDGCN: %struct.__opencl_block_literal_generic = type { i32, i32, i8* }
-// SPIR: @__block_literal_global = internal addrspace(1) constant { i32, i32, i8 addrspace(4)* } { i32 12, i32 4, i8 addrspace(4)* addrspacecast (i8* bitcast (void (i8 addrspace(4)*, i8 addrspace(3)*)* @block_A_block_invoke to i8*) to i8 addrspace(4)*) }
-// AMDGCN: @__block_literal_global = internal addrspace(1) constant { i32, i32, i8* } { i32 16, i32 8, i8* bitcast (void (i8*, i8 addrspace(3)*)* @block_A_block_invoke to i8*) }
+// COMMON: @__block_literal_global = internal addrspace(1) constant { i32, i32 } { i32 8, i32 4 }
 // COMMON-NOT: .str
 
 // SPIR-LABEL: define internal {{.*}}void @block_A_block_invoke(i8 addrspace(4)* %.block_descriptor, i8 addrspace(3)* %a)
@@ -20,58 +17,46 @@
   // COMMON-NOT: %block.flags
   // COMMON-NOT: %block.reserved
   // COMMON-NOT: %block.descriptor
-  // SPIR: %[[block_size:.*]] = getelementptr inbounds <{ i32, i32, i8 addrspace(4)*, i32 }>, <{ i32, i32, i8 addrspace(4)*, i32 }>* %block, i32 0, i32 0
-  // AMDGCN: %[[block_size:.*]] = getelementptr inbounds <{ i32, i32, i8*, i32 }>, <{ i32, i32, i8*, i32 }> addrspace(5)* %block, i32 0, i32 0
-  // SPIR: store i32 16, i32* %[[block_size]]
-  // AMDGCN: store i32 20, i32 addrspace(5)* %[[block_size]]
-  // SPIR: %[[block_align:.*]] = getelementptr inbounds <{ i32, i32, i8 addrspace(4)*, i32 }>, <{ i32, i32, i8 addrspace(4)*, i32 }>* %block, i32 0, i32 1
-  // AMDGCN: %[[block_align:.*]] = getelementptr inbounds <{ i32, i32, i8*, i32 }>, <{ i32, i32, i8*, i32 }> addrspace(5)* %block, i32 0, i32 1
+  // SPIR: %[[block_size:.*]] = getelementptr inbounds <{ i32, i32, i32 }>, <{ i32, i32, i32 }>* %[[block:.*]], i32 0, i32 0
+  // AMDGCN: %[[block_size:.*]] = getelementptr inbounds <{ i32, i32, i32 }>, <{ i32, i32, i32 }> addrspace(5)* %[[block:.*]], i32 0, i32 0
+  // SPIR: store i32 12, i32* %[[block_size]]
+  // AMDGCN: store i32 12, i32 addrspace(5)* %[[block_size]]
+  // SPIR: %[[block_align:.*]] = getelementptr inbounds <{ i32, i32, i32 }>, <{ i32, i32, i32 }>* %[[block]], i32 0, i32 1
+  // AMDGCN: %[[block_align:.*]] = getelementptr inbounds <{ i32, i32, i32 }>, <{ i32, i32, i32 }> addrspace(5)* %[[block]], i32 0, i32 1
   // SPIR: store i32 4, i32* %[[block_align]]
-  // AMDGCN: store i32 8, i32 addrspace(5)* %[[block_align]]
-  // SPIR: %[[block_invoke:.*]] = getelementptr inbounds <{ i32, i32, i8 addrspace(4)*, i32 }>, <{ i32, i32, i8 addrspace(4)*, i32 }>* %[[block:.*]], i32 0, i32 2
-  // SPIR: store i8 addrspace(4)* addrspacecast (i8* bitcast (i32 (i8 addrspace(4)*)* @__foo_block_invoke to i8*) to i8 addrspace(4)*), i8 addrspace(4)** %[[block_invoke]]
-  // SPIR: %[[block_captured:.*]] = getelementptr inbounds <{ i32, i32, i8 addrspace(4)*, i32 }>, <{ i32, i32, i8 addrspace(4)*, i32 }>* %[[block]], i32 0, i32 3
+  // AMDGCN: store i32 4, i32 addrspace(5)* %[[block_align]]
+  // SPIR: %[[block_captured:.*]] = getelementptr inbounds <{ i32, i32, i32 }>, <{ i32, i32, i32 }>* %[[block]], i32 0, i32 2
   // SPIR: %[[i_value:.*]] = load i32, i32* %i
   // SPIR: store i32 %[[i_value]], i32* %[[block_captured]],
-  // SPIR: %[[blk_ptr:.*]] = bitcast <{ i32, i32, i8 addrspace(4)*, i32 }>* %[[block]] to i32 ()*
+  // SPIR: %[[blk_ptr:.*]] = bitcast <{ i32, i32, i32 }>* %[[block]] to i32 ()*
   // SPIR: %[[blk_gen_ptr:.*]] = addrspacecast i32 ()* %[[blk_ptr]] to i32 () addrspace(4)*
   // SPIR: store i32 () addrspace(4)* %[[blk_gen_ptr]], i32 () addrspace(4)** %[[block_B:.*]],
-  // SPIR: %[[blk_gen_ptr:.*]] = load i32 () addrspace(4)*, i32 () addrspace(4)** %[[block_B]]
-  // SPIR: %[[block_literal:.*]] = bitcast i32 () addrspace(4)* %[[blk_gen_ptr]] to %struct.__opencl_block_literal_generic addrspace(4)*
-  // SPIR: %[[invoke_addr:.*]] = getelementptr inbounds %struct.__opencl_block_literal_generic, %struct.__opencl_block_literal_generic addrspace(4)* %[[block_literal]], i32 0, i32 2
-  // SPIR: %[[blk_gen_ptr:.*]] = bitcast 

r326937 - [OpenCL] Remove block invoke function from emitted block literal struct

2018-03-07 Thread Yaxun Liu via cfe-commits
Author: yaxunl
Date: Wed Mar  7 11:32:58 2018
New Revision: 326937

URL: http://llvm.org/viewvc/llvm-project?rev=326937=rev
Log:
[OpenCL] Remove block invoke function from emitted block literal struct

OpenCL runtime tracks the invoke function emitted for
any block expression. Due to restrictions on blocks in
OpenCL (v2.0 s6.12.5), it is always possible to know the
block invoke function when emitting call of block expression
or __enqueue_kernel builtin functions. Since __enqueu_kernel
already has an argument for the invoke function, it is redundant
to have invoke function member in the llvm block literal structure.

This patch removes invoke function from the llvm block literal
structure. It also removes the bitcast of block invoke function
to the generic block literal type which is useless for OpenCL.

This will save some space for the kernel argument, and also
eliminate some store instructions.

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

Modified:
cfe/trunk/lib/CodeGen/CGBlocks.cpp
cfe/trunk/lib/CodeGen/CGOpenCLRuntime.cpp
cfe/trunk/lib/CodeGen/CGOpenCLRuntime.h
cfe/trunk/test/CodeGenOpenCL/amdgpu-enqueue-kernel.cl
cfe/trunk/test/CodeGenOpenCL/blocks.cl
cfe/trunk/test/CodeGenOpenCL/cl20-device-side-enqueue.cl

Modified: cfe/trunk/lib/CodeGen/CGBlocks.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/CodeGen/CGBlocks.cpp?rev=326937=326936=326937=diff
==
--- cfe/trunk/lib/CodeGen/CGBlocks.cpp (original)
+++ cfe/trunk/lib/CodeGen/CGBlocks.cpp Wed Mar  7 11:32:58 2018
@@ -307,25 +307,12 @@ static void initializeForBlockHeader(Cod
 
   assert(elementTypes.empty());
   if (CGM.getLangOpts().OpenCL) {
-// The header is basically 'struct { int; int; generic void *;
+// The header is basically 'struct { int; int;
 // custom_fields; }'. Assert that struct is packed.
-auto GenericAS =
-CGM.getContext().getTargetAddressSpace(LangAS::opencl_generic);
-auto GenPtrAlign =
-CharUnits::fromQuantity(CGM.getTarget().getPointerAlign(GenericAS) / 
8);
-auto GenPtrSize =
-CharUnits::fromQuantity(CGM.getTarget().getPointerWidth(GenericAS) / 
8);
-assert(CGM.getIntSize() <= GenPtrSize);
-assert(CGM.getIntAlign() <= GenPtrAlign);
-assert((2 * CGM.getIntSize()).isMultipleOf(GenPtrAlign));
 elementTypes.push_back(CGM.IntTy); /* total size */
 elementTypes.push_back(CGM.IntTy); /* align */
-elementTypes.push_back(
-CGM.getOpenCLRuntime()
-.getGenericVoidPointerType()); /* invoke function */
-unsigned Offset =
-2 * CGM.getIntSize().getQuantity() + GenPtrSize.getQuantity();
-unsigned BlockAlign = GenPtrAlign.getQuantity();
+unsigned Offset = 2 * CGM.getIntSize().getQuantity();
+unsigned BlockAlign = CGM.getIntAlign().getQuantity();
 if (auto *Helper =
 CGM.getTargetCodeGenInfo().getTargetOpenCLBlockHelper()) {
   for (auto I : Helper->getCustomFieldTypes()) /* custom fields */ {
@@ -771,20 +758,12 @@ llvm::Value *CodeGenFunction::EmitBlockL
 
 llvm::Value *CodeGenFunction::EmitBlockLiteral(const CGBlockInfo ) {
   bool IsOpenCL = CGM.getContext().getLangOpts().OpenCL;
-  auto GenVoidPtrTy =
-  IsOpenCL ? CGM.getOpenCLRuntime().getGenericVoidPointerType() : 
VoidPtrTy;
-  LangAS GenVoidPtrAddr = IsOpenCL ? LangAS::opencl_generic : LangAS::Default;
-  auto GenVoidPtrSize = CharUnits::fromQuantity(
-  CGM.getTarget().getPointerWidth(
-  CGM.getContext().getTargetAddressSpace(GenVoidPtrAddr)) /
-  8);
   // Using the computed layout, generate the actual block function.
   bool isLambdaConv = blockInfo.getBlockDecl()->isConversionFromLambda();
   CodeGenFunction BlockCGF{CGM, true};
   BlockCGF.SanOpts = SanOpts;
   auto *InvokeFn = BlockCGF.GenerateBlockFunction(
   CurGD, blockInfo, LocalDeclMap, isLambdaConv, blockInfo.CanBeGlobal);
-  auto *blockFn = llvm::ConstantExpr::getPointerCast(InvokeFn, GenVoidPtrTy);
 
   // If there is nothing to capture, we can emit this as a global block.
   if (blockInfo.CanBeGlobal)
@@ -853,11 +832,12 @@ llvm::Value *CodeGenFunction::EmitBlockL
   llvm::ConstantInt::get(IntTy, blockInfo.BlockAlign.getQuantity()),
   getIntSize(), "block.align");
 }
-addHeaderField(blockFn, GenVoidPtrSize, "block.invoke");
-if (!IsOpenCL)
+if (!IsOpenCL) {
+  addHeaderField(llvm::ConstantExpr::getBitCast(InvokeFn, VoidPtrTy),
+ getPointerSize(), "block.invoke");
   addHeaderField(descriptor, getPointerSize(), "block.descriptor");
-else if (auto *Helper =
- CGM.getTargetCodeGenInfo().getTargetOpenCLBlockHelper()) {
+} else if (auto *Helper =
+   CGM.getTargetCodeGenInfo().getTargetOpenCLBlockHelper()) {
   for (auto I : Helper->getCustomFieldValues(*this, blockInfo)) {
 addHeaderField(
 I.first,
@@ -1060,38 +1040,23 @@ 

[PATCH] D43917: [analyzer] [NFC] Minor refactoring of NonNullParamChecker

2018-03-07 Thread George Karpenkov via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rC326935: [analyzer] [NFC] Minor refactoring of 
NonNullParamChecker (authored by george.karpenkov, committed by ).
Herald added a subscriber: cfe-commits.

Repository:
  rC Clang

https://reviews.llvm.org/D43917

Files:
  lib/StaticAnalyzer/Checkers/NonNullParamChecker.cpp

Index: lib/StaticAnalyzer/Checkers/NonNullParamChecker.cpp
===
--- lib/StaticAnalyzer/Checkers/NonNullParamChecker.cpp
+++ lib/StaticAnalyzer/Checkers/NonNullParamChecker.cpp
@@ -44,13 +44,9 @@
 };
 } // end anonymous namespace
 
-void NonNullParamChecker::checkPreCall(const CallEvent ,
-   CheckerContext ) const {
+/// \return Bitvector marking non-null attributes.
+static llvm::SmallBitVector getNonNullAttrs(const CallEvent ) {
   const Decl *FD = Call.getDecl();
-  if (!FD)
-return;
-
-  // Merge all non-null attributes
   unsigned NumArgs = Call.getNumArgs();
   llvm::SmallBitVector AttrNonNull(NumArgs);
   for (const auto *NonNull : FD->specific_attrs()) {
@@ -64,43 +60,47 @@
   AttrNonNull.set(Val);
 }
   }
+  return AttrNonNull;
+}
 
-  ProgramStateRef state = C.getState();
+void NonNullParamChecker::checkPreCall(const CallEvent ,
+   CheckerContext ) const {
+  if (!Call.getDecl())
+return;
 
-  CallEvent::param_type_iterator TyI = Call.param_type_begin(),
- TyE = Call.param_type_end();
+  llvm::SmallBitVector AttrNonNull = getNonNullAttrs(Call);
+  unsigned NumArgs = Call.getNumArgs();
+
+  ProgramStateRef state = C.getState();
+  ArrayRef parms = Call.parameters();
 
   for (unsigned idx = 0; idx < NumArgs; ++idx) {
+// For vararg functions, a corresponding parameter decl may not exist.
+bool HasParam = idx < parms.size();
 
 // Check if the parameter is a reference. We want to report when reference
 // to a null pointer is passed as a parameter.
-bool haveRefTypeParam = false;
-if (TyI != TyE) {
-  haveRefTypeParam = (*TyI)->isReferenceType();
-  TyI++;
-}
-
+bool haveRefTypeParam =
+HasParam ? parms[idx]->getType()->isReferenceType() : false;
 bool haveAttrNonNull = AttrNonNull[idx];
-if (!haveAttrNonNull) {
-  // Check if the parameter is also marked 'nonnull'.
-  ArrayRef parms = Call.parameters();
-  if (idx < parms.size())
-haveAttrNonNull = parms[idx]->hasAttr();
-}
 
-if (!haveRefTypeParam && !haveAttrNonNull)
+// Check if the parameter is also marked 'nonnull'.
+if (!haveAttrNonNull && HasParam)
+  haveAttrNonNull = parms[idx]->hasAttr();
+
+if (!haveAttrNonNull && !haveRefTypeParam)
   continue;
 
 // If the value is unknown or undefined, we can't perform this check.
 const Expr *ArgE = Call.getArgExpr(idx);
 SVal V = Call.getArgSVal(idx);
-Optional DV = V.getAs();
+auto DV = V.getAs();
 if (!DV)
   continue;
 
-// Process the case when the argument is not a location.
 assert(!haveRefTypeParam || DV->getAs());
 
+// Process the case when the argument is not a location.
 if (haveAttrNonNull && !DV->getAs()) {
   // If the argument is a union type, we want to handle a potential
   // transparent_union GCC extension.
@@ -112,66 +112,63 @@
   if (!UT || !UT->getDecl()->hasAttr())
 continue;
 
-  if (Optional CSV =
-  DV->getAs()) {
-nonloc::CompoundVal::iterator CSV_I = CSV->begin();
-assert(CSV_I != CSV->end());
-V = *CSV_I;
-DV = V.getAs();
-assert(++CSV_I == CSV->end());
-// FIXME: Handle (some_union){ some_other_union_val }, which turns into
-// a LazyCompoundVal inside a CompoundVal.
-if (!V.getAs())
-  continue;
-// Retrieve the corresponding expression.
-if (const CompoundLiteralExpr *CE = dyn_cast(ArgE))
-  if (const InitListExpr *IE =
-dyn_cast(CE->getInitializer()))
- ArgE = dyn_cast(*(IE->begin()));
+  auto CSV = DV->getAs();
 
-  } else {
-// FIXME: Handle LazyCompoundVals?
+  // FIXME: Handle LazyCompoundVals?
+  if (!CSV)
 continue;
-  }
+
+  V = *(CSV->begin());
+  DV = V.getAs();
+  assert(++CSV->begin() == CSV->end());
+  // FIXME: Handle (some_union){ some_other_union_val }, which turns into
+  // a LazyCompoundVal inside a CompoundVal.
+  if (!V.getAs())
+continue;
+
+  // Retrieve the corresponding expression.
+  if (const auto *CE = dyn_cast(ArgE))
+if (const auto *IE = dyn_cast(CE->getInitializer()))
+  ArgE = dyn_cast(*(IE->begin()));
 }
 
 ConstraintManager  = C.getConstraintManager();
 ProgramStateRef stateNotNull, stateNull;
 std::tie(stateNotNull, stateNull) = CM.assumeDual(state, *DV);
 

r326935 - [analyzer] [NFC] Minor refactoring of NonNullParamChecker

2018-03-07 Thread George Karpenkov via cfe-commits
Author: george.karpenkov
Date: Wed Mar  7 11:27:32 2018
New Revision: 326935

URL: http://llvm.org/viewvc/llvm-project?rev=326935=rev
Log:
[analyzer] [NFC] Minor refactoring of NonNullParamChecker

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

Modified:
cfe/trunk/lib/StaticAnalyzer/Checkers/NonNullParamChecker.cpp

Modified: cfe/trunk/lib/StaticAnalyzer/Checkers/NonNullParamChecker.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/StaticAnalyzer/Checkers/NonNullParamChecker.cpp?rev=326935=326934=326935=diff
==
--- cfe/trunk/lib/StaticAnalyzer/Checkers/NonNullParamChecker.cpp (original)
+++ cfe/trunk/lib/StaticAnalyzer/Checkers/NonNullParamChecker.cpp Wed Mar  7 
11:27:32 2018
@@ -44,13 +44,9 @@ public:
 };
 } // end anonymous namespace
 
-void NonNullParamChecker::checkPreCall(const CallEvent ,
-   CheckerContext ) const {
+/// \return Bitvector marking non-null attributes.
+static llvm::SmallBitVector getNonNullAttrs(const CallEvent ) {
   const Decl *FD = Call.getDecl();
-  if (!FD)
-return;
-
-  // Merge all non-null attributes
   unsigned NumArgs = Call.getNumArgs();
   llvm::SmallBitVector AttrNonNull(NumArgs);
   for (const auto *NonNull : FD->specific_attrs()) {
@@ -64,43 +60,47 @@ void NonNullParamChecker::checkPreCall(c
   AttrNonNull.set(Val);
 }
   }
+  return AttrNonNull;
+}
 
-  ProgramStateRef state = C.getState();
+void NonNullParamChecker::checkPreCall(const CallEvent ,
+   CheckerContext ) const {
+  if (!Call.getDecl())
+return;
+
+  llvm::SmallBitVector AttrNonNull = getNonNullAttrs(Call);
+  unsigned NumArgs = Call.getNumArgs();
 
-  CallEvent::param_type_iterator TyI = Call.param_type_begin(),
- TyE = Call.param_type_end();
+  ProgramStateRef state = C.getState();
+  ArrayRef parms = Call.parameters();
 
   for (unsigned idx = 0; idx < NumArgs; ++idx) {
+// For vararg functions, a corresponding parameter decl may not exist.
+bool HasParam = idx < parms.size();
 
 // Check if the parameter is a reference. We want to report when reference
 // to a null pointer is passed as a parameter.
-bool haveRefTypeParam = false;
-if (TyI != TyE) {
-  haveRefTypeParam = (*TyI)->isReferenceType();
-  TyI++;
-}
-
+bool haveRefTypeParam =
+HasParam ? parms[idx]->getType()->isReferenceType() : false;
 bool haveAttrNonNull = AttrNonNull[idx];
-if (!haveAttrNonNull) {
-  // Check if the parameter is also marked 'nonnull'.
-  ArrayRef parms = Call.parameters();
-  if (idx < parms.size())
-haveAttrNonNull = parms[idx]->hasAttr();
-}
 
-if (!haveRefTypeParam && !haveAttrNonNull)
+// Check if the parameter is also marked 'nonnull'.
+if (!haveAttrNonNull && HasParam)
+  haveAttrNonNull = parms[idx]->hasAttr();
+
+if (!haveAttrNonNull && !haveRefTypeParam)
   continue;
 
 // If the value is unknown or undefined, we can't perform this check.
 const Expr *ArgE = Call.getArgExpr(idx);
 SVal V = Call.getArgSVal(idx);
-Optional DV = V.getAs();
+auto DV = V.getAs();
 if (!DV)
   continue;
 
-// Process the case when the argument is not a location.
 assert(!haveRefTypeParam || DV->getAs());
 
+// Process the case when the argument is not a location.
 if (haveAttrNonNull && !DV->getAs()) {
   // If the argument is a union type, we want to handle a potential
   // transparent_union GCC extension.
@@ -112,66 +112,63 @@ void NonNullParamChecker::checkPreCall(c
   if (!UT || !UT->getDecl()->hasAttr())
 continue;
 
-  if (Optional CSV =
-  DV->getAs()) {
-nonloc::CompoundVal::iterator CSV_I = CSV->begin();
-assert(CSV_I != CSV->end());
-V = *CSV_I;
-DV = V.getAs();
-assert(++CSV_I == CSV->end());
-// FIXME: Handle (some_union){ some_other_union_val }, which turns into
-// a LazyCompoundVal inside a CompoundVal.
-if (!V.getAs())
-  continue;
-// Retrieve the corresponding expression.
-if (const CompoundLiteralExpr *CE = 
dyn_cast(ArgE))
-  if (const InitListExpr *IE =
-dyn_cast(CE->getInitializer()))
- ArgE = dyn_cast(*(IE->begin()));
+  auto CSV = DV->getAs();
 
-  } else {
-// FIXME: Handle LazyCompoundVals?
+  // FIXME: Handle LazyCompoundVals?
+  if (!CSV)
 continue;
-  }
+
+  V = *(CSV->begin());
+  DV = V.getAs();
+  assert(++CSV->begin() == CSV->end());
+  // FIXME: Handle (some_union){ some_other_union_val }, which turns into
+  // a LazyCompoundVal inside a CompoundVal.
+  if (!V.getAs())
+continue;
+
+  // Retrieve the corresponding expression.
+  if (const auto *CE = dyn_cast(ArgE))
+if 

Re: [libcxx] r323971 - Remove ; use instead. See https://libcxx.llvm.org/TS_deprecation.html

2018-03-07 Thread Nico Weber via cfe-commits
On Sat, Feb 24, 2018 at 7:17 PM, Marshall Clow 
wrote:

> On Thu, Feb 22, 2018 at 7:58 AM, Nico Weber  wrote:
>
>> I have a small personal project where I used to use this. I tried
>> switching to  instead, but that apparently requires -std=c++17.
>> With that, things build fine with my locally-built clang, but latest Xcode
>> clang doesn't accept that flag yet. So I tried -std=c++1z, but latest Xcode
>> (9.2) doesn't even include the  header yet. So now I have no way
>> of being able to build my project with both trunk clang and Xcode clang.
>> Maybe a one-year deprecation period is too short?
>>
>
> Nico --
>
> I'm sorry you were caught out by this.
>
> (It's not a huge deal, I have a optional<> implementation in my project
>> for platforms that don't ship it yet, but things used to be fine on mac
>> until this change at least. It's also not an important project, I just
>> thought I'd point out that this makes life more complicated than it would
>> be if the deletion period was longer.)
>>
>
> Yes, but it also makes life less complicated also.
>
> In fact, optional was the poster child for removing stuff from
> experimental.
> experimental::optional and std::optional have diverged, and are
> significantly different today (and only going to get more different in the
> future)
>
> The cost for someone to move to std::optional will never be lower than it
> is now. (they're only going to become more different).
>
> I really didn't (and don't) want to maintain two closely related (but
> different, and slowly diverging) code bases - and (repeatedly) explain to
> people the difference between them.
>
> As for Apple not shipping std::optional, I too am dismayed by that, but I
> have no control over that. :-(  I don't know when Apple will ship
> std::optional (they don't share their product plans with me), but it
> requires an update to libc++.dylib
>

Does this mean that if I build a mac program with trunk clang and trunk
libc++ using std::optional and -mmacosx-version-min=10.11 (or any other
version), my program will build without problems but then fail to start at
runtime because system libc++.dylib is missing the required optional code?


> , and in the past they have gone *years* without updating the dylib.
>  Hopefully they will update before LLVM 7 ships in August.
>
> -- Marshall
>
>
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


  1   2   >