[PATCH] D42641: [MinGW] Emit typeinfo locally for dllimported classes without key functions

2018-02-01 Thread Martin Storsjö via Phabricator via cfe-commits
mstorsjo added a subscriber: hans.
mstorsjo added a comment.

@hans I'd like to have this in 6.0 as well, to allow building Qt for windows as 
DLLs.


Repository:
  rL LLVM

https://reviews.llvm.org/D42641



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


[PATCH] D42811: [CodeGen][va_args] Correct Vector Struct va-arg 'in_reg' code gen

2018-02-01 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.

Okay.  LGTM.


Repository:
  rC Clang

https://reviews.llvm.org/D42811



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


[PATCH] D42730: [clang-tidy]] Add check for use of types/classes/functions from header which are deprecated and removed in C++17

2018-02-01 Thread Jens Massberg via Phabricator via cfe-commits
massberg marked 5 inline comments as done.
massberg added inline comments.



Comment at: test/clang-tidy/modernize-avoid-functional.cpp:30
+
+// CHECK-MESSAGES: [[@LINE+1]]:25: warning: 'binary_function' 
is deprecated in C++11 and removed in C++17 [modernize-avoid-functional]
+class BinaryTestClass : public std::binary_function {

alexfh wrote:
> Template parameters in this message are not useful. binary_function is 
> removed in C++17 regardless of the template parameters used. I played with 
> your patch a bit and  came up with a way to remove the template parameters in 
> a not overly hacky way (and also pulled out the common part of the message to 
> avoid duplication):
> 
> ```
> void AvoidFunctionalCheck::registerMatchers(MatchFinder *Finder) {
>   Finder->addMatcher(
>   cxxRecordDecl(allOf(isDerivedFrom(classTemplateSpecializationDecl(
> hasAnyName("std::binary_function",
>"std::unary_function"))
> .bind("base")),
>   anyOf(isClass(), ast_matchers::isStruct()),
>   ast_matchers::isDefinition()))
>   .bind("un_or_binary_derived"),
>   this);
>   Finder->addMatcher(callExpr(callee(functionDecl(hasName("std::ptr_fun"
>  .bind("ptr_fun_call"),
>  this);
>   Finder->addMatcher(callExpr(callee(functionDecl(hasName("std::mem_fun"
>  .bind("mem_fun_call"),
>  this);
> }
> 
> void AvoidFunctionalCheck::check(const MatchFinder::MatchResult ) {
>   const StringRef Message = "%0 is deprecated in C++11 and removed in C++17";
>   if (const auto *const Decl =
>   Result.Nodes.getNodeAs("un_or_binary_derived")) {
> const auto *SpecDecl =
> Result.Nodes.getNodeAs("base");
> for (CXXBaseSpecifier Base : Decl->bases()) {
>   if (SpecDecl == Base.getType()->getAsCXXRecordDecl())
> diag(Base.getLocStart(), Message) << 
> SpecDecl->getSpecializedTemplate();
> }
>   } else if (const auto *const Call =
>  Result.Nodes.getNodeAs("ptr_fun_call")) {
> diag(Call->getLocStart(), Message) << "'std::ptr_fun'";
>   } else if (const auto *const Call =
>  Result.Nodes.getNodeAs("mem_fun_call")) {
> diag(Call->getLocStart(), Message) << "'std::mem_fun'";
>   }
> }
> ```
> 
> This could be done differently, of course, depending on which way this check 
> is going to evolutionize (e.g. if you're going to find usages of deprecated 
> entities on a lower level - say, TypeLocs, or if you're going to provide 
> fixits for narrower usage patterns).
Thanks for figuring this out! I updated to your suggested version.


https://reviews.llvm.org/D42730



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


[PATCH] D42730: [clang-tidy]] Add check for use of types/classes/functions from header which are deprecated and removed in C++17

2018-02-01 Thread Jens Massberg via Phabricator via cfe-commits
massberg updated this revision to Diff 132538.
massberg added a comment.

Addressed comments of reviewers.


https://reviews.llvm.org/D42730

Files:
  clang-tidy/modernize/AvoidFunctionalCheck.cpp
  clang-tidy/modernize/AvoidFunctionalCheck.h
  clang-tidy/modernize/CMakeLists.txt
  clang-tidy/modernize/ModernizeTidyModule.cpp
  docs/ReleaseNotes.rst
  docs/clang-tidy/checks/list.rst
  docs/clang-tidy/checks/modernize-avoid-functional.rst
  test/clang-tidy/modernize-avoid-functional.cpp

Index: test/clang-tidy/modernize-avoid-functional.cpp
===
--- test/clang-tidy/modernize-avoid-functional.cpp
+++ test/clang-tidy/modernize-avoid-functional.cpp
@@ -0,0 +1,63 @@
+// RUN: %check_clang_tidy %s modernize-avoid-functional %t
+
+namespace std {
+
+template 
+class binary_function {};
+
+template 
+class unary_function {};
+
+template 
+class pointer_to_unary_function
+: public std::unary_function {  // NOLINT
+};
+
+template 
+pointer_to_unary_function ptr_fun(Result (*f)(Arg)) {
+  pointer_to_unary_function Nothing;
+  return Nothing;
+}
+
+template 
+class mem_fun_t {};
+
+template 
+mem_fun_t mem_fun(Res (T::*f)()) {}
+
+}  // namespace std
+
+// CHECK-MESSAGES: [[@LINE+1]]:25: warning: 'binary_function' is deprecated in C++11 and removed in C++17 [modernize-avoid-functional]
+class BinaryTestClass : public std::binary_function {
+ public:
+  BinaryTestClass();
+};
+
+// CHECK-MESSAGES: [[@LINE+1]]:24: warning: 'unary_function' is deprecated in C++11 and removed in C++17 [modernize-avoid-functional]
+class UnaryTestClass : public std::unary_function {
+ public:
+  UnaryTestClass();
+};
+
+class TestClass {
+ public:
+  int test() { return 1; }
+};
+
+// CHECK-MESSAGES: [[@LINE+2]]:31: warning: 'unary_function' is deprecated in C++11 and removed in C++17 [modernize-avoid-functional]
+class AnotherUnaryTestClass : public TestClass,
+  public std::unary_function {
+ public:
+  AnotherUnaryTestClass();
+};
+
+
+int simpleFunc(int X) { return X + 1; };
+
+void foo(void) {
+// CHECK-MESSAGES: [[@LINE+1]]:3: warning: 'std::ptr_fun' is deprecated in C++11 and removed in C++17 [modernize-avoid-functional]
+  std::ptr_fun(simpleFunc);
+
+// CHECK-MESSAGES: [[@LINE+1]]:3: warning: 'std::mem_fun' is deprecated in C++11 and removed in C++17 [modernize-avoid-functional]
+  std::mem_fun(::test);
+}
Index: docs/clang-tidy/checks/modernize-avoid-functional.rst
===
--- docs/clang-tidy/checks/modernize-avoid-functional.rst
+++ docs/clang-tidy/checks/modernize-avoid-functional.rst
@@ -0,0 +1,14 @@
+.. title:: clang-tidy - modernize-avoid-functional
+
+modernize-avoid-functional
+==
+
+Warns if types, classes and functions from '' header which are
+  deprecated in C++11 and removed in C++17 are used.
+In particular, this check warns if one of the following deprecated objects is
+used:
+
+-  'std::unary_function'
+-  'std::binary_function'
+-  'std::ptr_fun'
+-  'std::mem_fun'
Index: docs/clang-tidy/checks/list.rst
===
--- docs/clang-tidy/checks/list.rst
+++ docs/clang-tidy/checks/list.rst
@@ -154,6 +154,7 @@
misc-unused-raii
misc-unused-using-decls
modernize-avoid-bind
+   modernize-avoid-functional
modernize-deprecated-headers
modernize-loop-convert
modernize-make-shared
Index: docs/ReleaseNotes.rst
===
--- docs/ReleaseNotes.rst
+++ docs/ReleaseNotes.rst
@@ -89,6 +89,12 @@
   using decltype specifiers and lambda with otherwise unutterable 
   return types.
 
+- New `modernize-avoid-functional
+  `_ check
+
+  Warns if types, classes and functions from '' header which are
+  deprecated in C++11 and removed in C++17 are used.
+
 - New alias `hicpp-avoid-goto
   `_ to 
   `cppcoreguidelines-avoid-goto `_
Index: clang-tidy/modernize/ModernizeTidyModule.cpp
===
--- clang-tidy/modernize/ModernizeTidyModule.cpp
+++ clang-tidy/modernize/ModernizeTidyModule.cpp
@@ -11,6 +11,7 @@
 #include "../ClangTidyModule.h"
 #include "../ClangTidyModuleRegistry.h"
 #include "AvoidBindCheck.h"
+#include "AvoidFunctionalCheck.h"
 #include "DeprecatedHeadersCheck.h"
 #include "LoopConvertCheck.h"
 #include "MakeSharedCheck.h"
@@ -45,6 +46,8 @@
 public:
   void addCheckFactories(ClangTidyCheckFactories ) override {
 CheckFactories.registerCheck("modernize-avoid-bind");
+CheckFactories.registerCheck(
+"modernize-avoid-functional");

[PATCH] D42641: [MinGW] Emit typeinfo locally for dllimported classes without key functions

2018-02-01 Thread Martin Storsjö via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rL324059: [MinGW] Emit typeinfo locally for dllimported 
classes without key functions (authored by mstorsjo, committed by ).
Herald added a subscriber: llvm-commits.

Changed prior to commit:
  https://reviews.llvm.org/D42641?vs=132045=132534#toc

Repository:
  rL LLVM

https://reviews.llvm.org/D42641

Files:
  cfe/trunk/lib/CodeGen/ItaniumCXXABI.cpp
  cfe/trunk/test/CodeGenCXX/dllimport-missing-key.cpp
  cfe/trunk/test/CodeGenCXX/dllimport-rtti.cpp


Index: cfe/trunk/test/CodeGenCXX/dllimport-rtti.cpp
===
--- cfe/trunk/test/CodeGenCXX/dllimport-rtti.cpp
+++ cfe/trunk/test/CodeGenCXX/dllimport-rtti.cpp
@@ -12,7 +12,7 @@
 // MSVC-DAG: @"\01??_R3S@@8" = linkonce_odr
 
 // GNU-DAG: @_ZTV1S = available_externally dllimport
-// GNU-DAG: @_ZTI1S = external dllimport
+// GNU-DAG: @_ZTI1S = linkonce_odr
 
 struct U : S {
 } u;
Index: cfe/trunk/test/CodeGenCXX/dllimport-missing-key.cpp
===
--- cfe/trunk/test/CodeGenCXX/dllimport-missing-key.cpp
+++ cfe/trunk/test/CodeGenCXX/dllimport-missing-key.cpp
@@ -0,0 +1,20 @@
+// RUN: %clang_cc1 -triple i686-windows-gnu -emit-llvm -std=c++1y -O0 -o - %s 
-w | FileCheck --check-prefix=GNU %s
+
+class __declspec(dllimport) QObjectData {
+public:
+virtual ~QObjectData() = 0;
+void *ptr;
+
+int method() const;
+};
+
+class LocalClass : public QObjectData {
+};
+
+void call() {
+(new LocalClass())->method();
+}
+
+// GNU-DAG: @_ZTV11QObjectData = available_externally dllimport
+// GNU-DAG: @_ZTS11QObjectData = linkonce_odr
+// GNU-DAG: @_ZTI11QObjectData = linkonce_odr
Index: cfe/trunk/lib/CodeGen/ItaniumCXXABI.cpp
===
--- cfe/trunk/lib/CodeGen/ItaniumCXXABI.cpp
+++ cfe/trunk/lib/CodeGen/ItaniumCXXABI.cpp
@@ -2761,6 +2761,11 @@
 // N.B. We must always emit the RTTI data ourselves if there exists a key
 // function.
 bool IsDLLImport = RD->hasAttr();
+
+// Don't import the RTTI but emit it locally.
+if (CGM.getTriple().isWindowsGNUEnvironment() && IsDLLImport)
+  return false;
+
 if (CGM.getVTables().isVTableExternal(RD))
   return IsDLLImport && !CGM.getTriple().isWindowsItaniumEnvironment()
  ? false


Index: cfe/trunk/test/CodeGenCXX/dllimport-rtti.cpp
===
--- cfe/trunk/test/CodeGenCXX/dllimport-rtti.cpp
+++ cfe/trunk/test/CodeGenCXX/dllimport-rtti.cpp
@@ -12,7 +12,7 @@
 // MSVC-DAG: @"\01??_R3S@@8" = linkonce_odr
 
 // GNU-DAG: @_ZTV1S = available_externally dllimport
-// GNU-DAG: @_ZTI1S = external dllimport
+// GNU-DAG: @_ZTI1S = linkonce_odr
 
 struct U : S {
 } u;
Index: cfe/trunk/test/CodeGenCXX/dllimport-missing-key.cpp
===
--- cfe/trunk/test/CodeGenCXX/dllimport-missing-key.cpp
+++ cfe/trunk/test/CodeGenCXX/dllimport-missing-key.cpp
@@ -0,0 +1,20 @@
+// RUN: %clang_cc1 -triple i686-windows-gnu -emit-llvm -std=c++1y -O0 -o - %s -w | FileCheck --check-prefix=GNU %s
+
+class __declspec(dllimport) QObjectData {
+public:
+virtual ~QObjectData() = 0;
+void *ptr;
+
+int method() const;
+};
+
+class LocalClass : public QObjectData {
+};
+
+void call() {
+(new LocalClass())->method();
+}
+
+// GNU-DAG: @_ZTV11QObjectData = available_externally dllimport
+// GNU-DAG: @_ZTS11QObjectData = linkonce_odr
+// GNU-DAG: @_ZTI11QObjectData = linkonce_odr
Index: cfe/trunk/lib/CodeGen/ItaniumCXXABI.cpp
===
--- cfe/trunk/lib/CodeGen/ItaniumCXXABI.cpp
+++ cfe/trunk/lib/CodeGen/ItaniumCXXABI.cpp
@@ -2761,6 +2761,11 @@
 // N.B. We must always emit the RTTI data ourselves if there exists a key
 // function.
 bool IsDLLImport = RD->hasAttr();
+
+// Don't import the RTTI but emit it locally.
+if (CGM.getTriple().isWindowsGNUEnvironment() && IsDLLImport)
+  return false;
+
 if (CGM.getVTables().isVTableExternal(RD))
   return IsDLLImport && !CGM.getTriple().isWindowsItaniumEnvironment()
  ? false
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


r324059 - [MinGW] Emit typeinfo locally for dllimported classes without key functions

2018-02-01 Thread Martin Storsjo via cfe-commits
Author: mstorsjo
Date: Thu Feb  1 22:22:35 2018
New Revision: 324059

URL: http://llvm.org/viewvc/llvm-project?rev=324059=rev
Log:
[MinGW] Emit typeinfo locally for dllimported classes without key functions

This fixes building Qt as shared libraries with clang in MinGW
mode; previously subclasses of the QObjectData class (in other
DLLs than the base DLL) failed to find the typeinfo symbols
(that neither were emitted in the base DLL nor in the DLL
containing the subclass).

If the virtual destructor in the newly added testcase wouldn't
be pure (or if there'd be another non-pure virtual method),
it'd be a key function and things would work out even before this
change. Make sure to locally emit the typeinfo for these classes
as well.

This matches what GCC does in this specific testcase.

This fixes the root issue that spawned PR35146. (The difference
to GCC that is initially described in that bug still is present
though.)

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

Added:
cfe/trunk/test/CodeGenCXX/dllimport-missing-key.cpp
Modified:
cfe/trunk/lib/CodeGen/ItaniumCXXABI.cpp
cfe/trunk/test/CodeGenCXX/dllimport-rtti.cpp

Modified: cfe/trunk/lib/CodeGen/ItaniumCXXABI.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/CodeGen/ItaniumCXXABI.cpp?rev=324059=324058=324059=diff
==
--- cfe/trunk/lib/CodeGen/ItaniumCXXABI.cpp (original)
+++ cfe/trunk/lib/CodeGen/ItaniumCXXABI.cpp Thu Feb  1 22:22:35 2018
@@ -2761,6 +2761,11 @@ static bool ShouldUseExternalRTTIDescrip
 // N.B. We must always emit the RTTI data ourselves if there exists a key
 // function.
 bool IsDLLImport = RD->hasAttr();
+
+// Don't import the RTTI but emit it locally.
+if (CGM.getTriple().isWindowsGNUEnvironment() && IsDLLImport)
+  return false;
+
 if (CGM.getVTables().isVTableExternal(RD))
   return IsDLLImport && !CGM.getTriple().isWindowsItaniumEnvironment()
  ? false

Added: cfe/trunk/test/CodeGenCXX/dllimport-missing-key.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/CodeGenCXX/dllimport-missing-key.cpp?rev=324059=auto
==
--- cfe/trunk/test/CodeGenCXX/dllimport-missing-key.cpp (added)
+++ cfe/trunk/test/CodeGenCXX/dllimport-missing-key.cpp Thu Feb  1 22:22:35 2018
@@ -0,0 +1,20 @@
+// RUN: %clang_cc1 -triple i686-windows-gnu -emit-llvm -std=c++1y -O0 -o - %s 
-w | FileCheck --check-prefix=GNU %s
+
+class __declspec(dllimport) QObjectData {
+public:
+virtual ~QObjectData() = 0;
+void *ptr;
+
+int method() const;
+};
+
+class LocalClass : public QObjectData {
+};
+
+void call() {
+(new LocalClass())->method();
+}
+
+// GNU-DAG: @_ZTV11QObjectData = available_externally dllimport
+// GNU-DAG: @_ZTS11QObjectData = linkonce_odr
+// GNU-DAG: @_ZTI11QObjectData = linkonce_odr

Modified: cfe/trunk/test/CodeGenCXX/dllimport-rtti.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/CodeGenCXX/dllimport-rtti.cpp?rev=324059=324058=324059=diff
==
--- cfe/trunk/test/CodeGenCXX/dllimport-rtti.cpp (original)
+++ cfe/trunk/test/CodeGenCXX/dllimport-rtti.cpp Thu Feb  1 22:22:35 2018
@@ -12,7 +12,7 @@ struct __declspec(dllimport) S {
 // MSVC-DAG: @"\01??_R3S@@8" = linkonce_odr
 
 // GNU-DAG: @_ZTV1S = available_externally dllimport
-// GNU-DAG: @_ZTI1S = external dllimport
+// GNU-DAG: @_ZTI1S = linkonce_odr
 
 struct U : S {
 } u;


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


[PATCH] D42672: [CFG] [analyzer] Heavier CFGConstructor elements.

2018-02-01 Thread Artem Dergachev via Phabricator via cfe-commits
NoQ updated this revision to Diff 132532.
NoQ marked an inline comment as done.
NoQ added a comment.

Cleanup construction contexts after they have been consumed. Add assertions to 
verify that our understanding of the context's lifespan is reasonable.

I will run the new mode on a large codebase before committing, to see if these 
assertions ever fail or if i'm breaking anything else.

Prettify ConstructionContext into a class with getters, write explicit 
constructors as pointed out in other patches.


https://reviews.llvm.org/D42672

Files:
  include/clang/Analysis/AnalysisDeclContext.h
  include/clang/Analysis/CFG.h
  include/clang/StaticAnalyzer/Core/AnalyzerOptions.h
  include/clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h
  lib/Analysis/AnalysisDeclContext.cpp
  lib/Analysis/CFG.cpp
  lib/Analysis/LiveVariables.cpp
  lib/StaticAnalyzer/Core/AnalysisManager.cpp
  lib/StaticAnalyzer/Core/AnalyzerOptions.cpp
  lib/StaticAnalyzer/Core/CoreEngine.cpp
  lib/StaticAnalyzer/Core/ExprEngine.cpp
  lib/StaticAnalyzer/Core/ExprEngineCXX.cpp
  lib/StaticAnalyzer/Core/PathDiagnostic.cpp
  test/Analysis/analyzer-config.c
  test/Analysis/analyzer-config.cpp
  test/Analysis/cfg-rich-constructors.cpp
  test/Analysis/cfg.cpp

Index: test/Analysis/cfg.cpp
===
--- test/Analysis/cfg.cpp
+++ test/Analysis/cfg.cpp
@@ -1,5 +1,16 @@
-// RUN: %clang_analyze_cc1 -analyzer-checker=debug.DumpCFG -triple x86_64-apple-darwin12 -analyzer-config cfg-temporary-dtors=true -std=c++11 %s > %t 2>&1
-// RUN: FileCheck --input-file=%t %s
+// RUN: %clang_analyze_cc1 -analyzer-checker=debug.DumpCFG -triple x86_64-apple-darwin12 -analyzer-config cfg-temporary-dtors=true -std=c++11 -analyzer-config cfg-rich-constructors=false %s > %t 2>&1
+// RUN: FileCheck --input-file=%t -check-prefixes=CHECK,WARNINGS %s
+// RUN: %clang_analyze_cc1 -analyzer-checker=debug.DumpCFG -triple x86_64-apple-darwin12 -analyzer-config cfg-temporary-dtors=true -std=c++11 -analyzer-config cfg-rich-constructors=true %s > %t 2>&1
+// RUN: FileCheck --input-file=%t -check-prefixes=CHECK,ANALYZER %s
+
+// This file tests how we construct two different flavors of the Clang CFG -
+// the CFG used by the Sema analysis-based warnings and the CFG used by the
+// static analyzer. The difference in the behavior is checked via FileCheck
+// prefixes (WARNINGS and ANALYZER respectively). When introducing new analyzer
+// flags, no new run lines should be added - just these flags would go to the
+// respective line depending on where is it turned on and where is it turned
+// off. Feel free to add tests that test only one of the CFG flavors if you're
+// not sure how the other flavor is supposed to work in your case.
 
 // CHECK-LABEL: void checkWrap(int i)
 // CHECK: ENTRY
@@ -116,7 +127,8 @@
 // CHECK-NEXT:   Succs (1): B1
 // CHECK: [B1]
 // CHECK-NEXT:   1:  CFGNewAllocator(A *)
-// CHECK-NEXT:   2:  (CXXConstructExpr, class A)
+// WARNINGS-NEXT:   2:  (CXXConstructExpr, class A)
+// ANALYZER-NEXT:   2:  (CXXConstructExpr, [B1.3], class A)
 // CHECK-NEXT:   3: new A([B1.2])
 // CHECK-NEXT:   4: A *a = new A();
 // CHECK-NEXT:   5: a
@@ -138,7 +150,8 @@
 // CHECK: [B1]
 // CHECK-NEXT:   1: 5
 // CHECK-NEXT:   2: CFGNewAllocator(A *)
-// CHECK-NEXT:   3:  (CXXConstructExpr, class A [5])
+// WARNINGS-NEXT:   3:  (CXXConstructExpr, class A [5])
+// ANALYZER-NEXT:   3:  (CXXConstructExpr, [B1.4], class A [5])
 // CHECK-NEXT:   4: new A {{\[\[}}B1.1]]
 // CHECK-NEXT:   5: A *a = new A [5];
 // CHECK-NEXT:   6: a
@@ -331,7 +344,8 @@
 // CHECK-NEXT:  3: [B1.2] (ImplicitCastExpr, ArrayToPointerDecay, int *)
 // CHECK-NEXT:  4: [B1.3] (ImplicitCastExpr, BitCast, void *)
 // CHECK-NEXT:  5: CFGNewAllocator(MyClass *)
-// CHECK-NEXT:  6:  (CXXConstructExpr, class MyClass)
+// WARNINGS-NEXT:  6:  (CXXConstructExpr, class MyClass)
+// ANALYZER-NEXT:  6:  (CXXConstructExpr, [B1.7], class MyClass)
 // CHECK-NEXT:  7: new ([B1.4]) MyClass([B1.6])
 // CHECK-NEXT:  8: MyClass *obj = new (buffer) MyClass();
 // CHECK-NEXT:  Preds (1): B2
@@ -363,7 +377,8 @@
 // CHECK-NEXT:  4: [B1.3] (ImplicitCastExpr, BitCast, void *)
 // CHECK-NEXT:  5: 5
 // CHECK-NEXT:  6: CFGNewAllocator(MyClass *)
-// CHECK-NEXT:  7:  (CXXConstructExpr, class MyClass [5])
+// WARNINGS-NEXT:  7:  (CXXConstructExpr, class MyClass [5])
+// ANALYZER-NEXT:  7:  (CXXConstructExpr, [B1.8], class MyClass [5])
 // CHECK-NEXT:  8: new ([B1.4]) MyClass {{\[\[}}B1.5]]
 // CHECK-NEXT:  9: MyClass *obj = new (buffer) MyClass [5];
 // CHECK-NEXT:  Preds (1): B2
Index: test/Analysis/cfg-rich-constructors.cpp
===
--- /dev/null
+++ test/Analysis/cfg-rich-constructors.cpp
@@ -0,0 +1,46 @@
+// RUN: %clang_analyze_cc1 -analyzer-checker=debug.DumpCFG -triple x86_64-apple-darwin12 -analyzer-config cfg-temporary-dtors=true -std=c++11 %s > %t 2>&1
+// RUN: FileCheck --input-file=%t %s
+
+class C {
+public:
+  C();
+  

[PATCH] D42650: [clang-format] New format param ObjCBinPackProtocolList

2018-02-01 Thread Stephane Moore via Phabricator via cfe-commits
stephanemoore added inline comments.



Comment at: lib/Format/ContinuationIndenter.cpp:1214
 // FIXME: We likely want to do this for more combinations of brackets.
 // Verify that it is wanted for ObjC, too.
 if (Current.is(tok::less) && Current.ParentBracket == tok::l_paren) {

With the new parameter does this comment still apply? Maybe we can remove it?


Repository:
  rC Clang

https://reviews.llvm.org/D42650



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


[PATCH] D42800: Let CUDA toolchain support amdgpu target

2018-02-01 Thread Greg Rodgers via Phabricator via cfe-commits
gregrodgers added a comment.

Sorry, all my great inline comments got lost somehow.  I am a newbie to 
Phabricator.  I will try to reconstruct my comments.


https://reviews.llvm.org/D42800



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


[PATCH] D42768: AST: add an extension to support SwiftCC on MS ABI

2018-02-01 Thread Saleem Abdulrasool via Phabricator via cfe-commits
compnerd added a comment.

@rnk thats not a bad idea.  However, I had implemented it slightly differently. 
 I mangled it as if it was a PMF: so you get `__Swift::__swift_cc::*` as the 
type.


Repository:
  rC Clang

https://reviews.llvm.org/D42768



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


[PATCH] D42800: Let CUDA toolchain support amdgpu target

2018-02-01 Thread Greg Rodgers via Phabricator via cfe-commits
gregrodgers requested changes to this revision.
gregrodgers added a comment.
This revision now requires changes to proceed.

Thanks to everyone for the reviews.   I hope I replied to all inline comments.  
Since I sent this to Sam to post, we discovered a major shortcoming.  As tra 
points out, there is a lot of cuda headers in the cuda sdk that are processed.  
We are able to override asm() expansions with #undef and redefine as an 
equivalent amdgpu component so the compiler never sees the asm().  I am sure we 
will need to add more redefines as we broaden our testing.  But that is not the 
big problem.  We would like to be able to run cudaclang for AMD GPUs without an 
install of cuda.   Of course you must always install cuda if any of your 
targeted GPUs are NVidia GPUs.  To run cudaclang without cuda when only 
non-NVidia gpus are specified, we need an open set of headers and we must 
replace the fatbin tools used in the toolchain.  The later can be addressed by 
using the libomptarget methods for embedding multiple target GPU objects.  The 
former is going to take a lot of work.   I am going to be sending an updated 
patch that has the stubs for the open headers noted in 
__clang_cuda_runtime_wrapper.h.   They will be included with the CC1 flag 
-D__USE_OPEN_HEADERS__.  This will be generated by the cuda driver when it 
finds no cuda installation and all target GPUs are not NVidia.


https://reviews.llvm.org/D42800



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


[PATCH] D42768: AST: add an extension to support SwiftCC on MS ABI

2018-02-01 Thread Saleem Abdulrasool via Phabricator via cfe-commits
compnerd updated this revision to Diff 132528.
compnerd added a comment.

Handle the non-top-level decl case


Repository:
  rC Clang

https://reviews.llvm.org/D42768

Files:
  lib/AST/MicrosoftMangle.cpp
  test/CodeGenCXX/msabi-swiftcall-cc.cpp

Index: test/CodeGenCXX/msabi-swiftcall-cc.cpp
===
--- /dev/null
+++ test/CodeGenCXX/msabi-swiftcall-cc.cpp
@@ -0,0 +1,32 @@
+// RUN: %clang_cc1 -triple i686-unknown-windows-msvc -fdeclspec -emit-llvm %s -o - | FileCheck %s
+
+void __attribute__((__swiftcall__)) f() {}
+// CHECK-DAG: @"\01?f@__swift_cc@__Swift@@YAXXZ"
+
+void (__attribute__((__swiftcall__)) *p)();
+// CHECK-DAG: @"\01?p@@3P8__swift_cc@__Swift@@AAXXZA"
+
+namespace {
+void __attribute__((__swiftcall__)) __attribute__((__used__)) f() { }
+// CHECK-DAG: "\01?f@?A@__swift_cc@__Swift@@YAXXZ"
+}
+
+namespace n {
+void __attribute__((__swiftcall__)) f() {}
+// CHECK-DAG: "\01?f@n@__swift_cc@__Swift@@YAXXZ"
+}
+
+namespace __Swift { namespace __swift_cc {
+void __attribute__((__swiftcall__)) f() { }
+// CHECK-DAG: "\01?f@__swift_cc@__Swift@12@YAXXZ"
+} }
+
+struct __declspec(dllexport) S {
+  S(const S &) = delete;
+  S & operator=(const S &) = delete;
+  void __attribute__((__swiftcall__)) m() { }
+  // CHECK-DAG: "\01?m@S@__swift_cc@__Swift@@QAAXXZ"
+};
+
+void f(void (__attribute__((__swiftcall__))())) {}
+// CHECK-DAG: "\01?f@@YAXP8__swift_cc@__Swift@@AAXXZ@Z"
Index: lib/AST/MicrosoftMangle.cpp
===
--- lib/AST/MicrosoftMangle.cpp
+++ lib/AST/MicrosoftMangle.cpp
@@ -953,8 +953,13 @@
 void MicrosoftCXXNameMangler::mangleNestedName(const NamedDecl *ND) {
   //  ::=  []
   //   ::=  []
-  const DeclContext *DC = getEffectiveDeclContext(ND);
 
+  const Type *Ty = nullptr;
+
+  if (const auto *FD = dyn_cast(ND))
+Ty = FD->getType()->getAs();
+
+  const DeclContext *DC = getEffectiveDeclContext(ND);
   while (!DC->isTranslationUnit()) {
 if (isa(ND) || isa(ND)) {
   unsigned Disc;
@@ -1050,6 +1055,11 @@
 }
 DC = DC->getParent();
   }
+
+  if (Ty)
+if (Ty->getAs()->getCallConv() == CC_Swift)
+  for (const char *NS : {"__swift_cc", "__Swift"})
+mangleSourceName(NS);
 }
 
 void MicrosoftCXXNameMangler::mangleCXXDtorType(CXXDtorType T) {
@@ -1702,8 +1712,16 @@
 break;
   case QMM_Mangle:
 if (const FunctionType *FT = dyn_cast(T)) {
-  Out << '6';
-  mangleFunctionType(FT);
+  if (FT->getCallConv() == CC_Swift) {
+Out << '8';
+for (const char *NS : {"__swift_cc", "__Swift"})
+  mangleSourceName(NS);
+Out << '@';
+mangleFunctionType(FT, nullptr, true);
+  } else {
+Out << '6';
+mangleFunctionType(FT);
+  }
   return;
 }
 mangleQualifiers(Quals, false);
@@ -1959,6 +1977,11 @@
 mangleQualifiers(Quals, /*IsMember=*/false);
   }
 
+  // We currently mangle the SwiftCC as `__Swift::__swift_cc` namespace on the
+  // decl in mangleNestedName.
+  if (CC == CC_Swift)
+CC = CC_C;
+
   mangleCallingConvention(CC);
 
   //  ::= 
@@ -2341,6 +2364,7 @@
 void MicrosoftCXXNameMangler::mangleType(const PointerType *T, Qualifiers Quals,
  SourceRange Range) {
   QualType PointeeType = T->getPointeeType();
+
   manglePointerCVQualifiers(Quals);
   manglePointerExtQualifiers(Quals, PointeeType);
   mangleType(PointeeType, Range);
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D42785: [Analyzer] Fix a typo in `ExprEngine::VisitMemberExpr`

2018-02-01 Thread Phabricator via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rL324053: [analyzer] Fix transitions in 
check::PreStmtMemberExpr checker callback. (authored by dergachev, 
committed by ).
Herald added a subscriber: llvm-commits.

Repository:
  rL LLVM

https://reviews.llvm.org/D42785

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


Index: cfe/trunk/lib/StaticAnalyzer/Core/ExprEngine.cpp
===
--- cfe/trunk/lib/StaticAnalyzer/Core/ExprEngine.cpp
+++ cfe/trunk/lib/StaticAnalyzer/Core/ExprEngine.cpp
@@ -2251,16 +2251,15 @@
   ExplodedNodeSet CheckedSet;
   getCheckerManager().runCheckersForPreStmt(CheckedSet, Pred, M, *this);
 
-  ExplodedNodeSet EvalSet;
-  ValueDecl *Member = M->getMemberDecl();
+  ExplodedNodeSet EvalSet;  
+  ValueDecl *Member = M->getMemberDecl();  
 
   // Handle static member variables and enum constants accessed via
   // member syntax.
-  if (isa(Member) || isa(Member)) {
-ExplodedNodeSet Dst;
+  if (isa(Member) || isa(Member)) {
 for (ExplodedNodeSet::iterator I = CheckedSet.begin(), E = 
CheckedSet.end();
  I != E; ++I) {
-  VisitCommonDeclRefExpr(M, Member, Pred, EvalSet);
+  VisitCommonDeclRefExpr(M, Member, *I, EvalSet);
 }
   } else {
 StmtNodeBuilder Bldr(CheckedSet, EvalSet, *currBldrCtx);


Index: cfe/trunk/lib/StaticAnalyzer/Core/ExprEngine.cpp
===
--- cfe/trunk/lib/StaticAnalyzer/Core/ExprEngine.cpp
+++ cfe/trunk/lib/StaticAnalyzer/Core/ExprEngine.cpp
@@ -2251,16 +2251,15 @@
   ExplodedNodeSet CheckedSet;
   getCheckerManager().runCheckersForPreStmt(CheckedSet, Pred, M, *this);
 
-  ExplodedNodeSet EvalSet;
-  ValueDecl *Member = M->getMemberDecl();
+  ExplodedNodeSet EvalSet;  
+  ValueDecl *Member = M->getMemberDecl();  
 
   // Handle static member variables and enum constants accessed via
   // member syntax.
-  if (isa(Member) || isa(Member)) {
-ExplodedNodeSet Dst;
+  if (isa(Member) || isa(Member)) {
 for (ExplodedNodeSet::iterator I = CheckedSet.begin(), E = CheckedSet.end();
  I != E; ++I) {
-  VisitCommonDeclRefExpr(M, Member, Pred, EvalSet);
+  VisitCommonDeclRefExpr(M, Member, *I, EvalSet);
 }
   } else {
 StmtNodeBuilder Bldr(CheckedSet, EvalSet, *currBldrCtx);
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


r324053 - [analyzer] Fix transitions in check::PreStmt checker callback.

2018-02-01 Thread Artem Dergachev via cfe-commits
Author: dergachev
Date: Thu Feb  1 18:23:37 2018
New Revision: 324053

URL: http://llvm.org/viewvc/llvm-project?rev=324053=rev
Log:
[analyzer] Fix transitions in check::PreStmt checker callback.

No in-tree checkers use this callback so far, hence no tests. But better fix
this now than remember to fix this when the checkers actually appear.

Patch by Henry Wong!

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

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=324053=324052=324053=diff
==
--- cfe/trunk/lib/StaticAnalyzer/Core/ExprEngine.cpp (original)
+++ cfe/trunk/lib/StaticAnalyzer/Core/ExprEngine.cpp Thu Feb  1 18:23:37 2018
@@ -2251,16 +2251,15 @@ void ExprEngine::VisitMemberExpr(const M
   ExplodedNodeSet CheckedSet;
   getCheckerManager().runCheckersForPreStmt(CheckedSet, Pred, M, *this);
 
-  ExplodedNodeSet EvalSet;
-  ValueDecl *Member = M->getMemberDecl();
+  ExplodedNodeSet EvalSet;  
+  ValueDecl *Member = M->getMemberDecl();  
 
   // Handle static member variables and enum constants accessed via
   // member syntax.
-  if (isa(Member) || isa(Member)) {
-ExplodedNodeSet Dst;
+  if (isa(Member) || isa(Member)) {
 for (ExplodedNodeSet::iterator I = CheckedSet.begin(), E = 
CheckedSet.end();
  I != E; ++I) {
-  VisitCommonDeclRefExpr(M, Member, Pred, EvalSet);
+  VisitCommonDeclRefExpr(M, Member, *I, EvalSet);
 }
   } else {
 StmtNodeBuilder Bldr(CheckedSet, EvalSet, *currBldrCtx);


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


r324052 - [analyzer] Expose return statement from CallExit program point

2018-02-01 Thread George Karpenkov via cfe-commits
Author: george.karpenkov
Date: Thu Feb  1 18:19:43 2018
New Revision: 324052

URL: http://llvm.org/viewvc/llvm-project?rev=324052=rev
Log:
[analyzer] Expose return statement from CallExit program point

If the return statement is stored, we might as well allow querying
against it.
Also fix the bug where the return statement is not stored
if there is no return value.
This change un-merges two ExplodedNodes during call exit when the state
is otherwise identical - the CallExitBegin node itself and the "Bind
Return Value"-tagged node.
And expose the return statement through
getStatement helper function.

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

Added:
cfe/trunk/test/Analysis/return-stmt-merge.cpp
Modified:
cfe/trunk/include/clang/Analysis/ProgramPoint.h
cfe/trunk/lib/StaticAnalyzer/Checkers/AnalysisOrderChecker.cpp
cfe/trunk/lib/StaticAnalyzer/Core/CoreEngine.cpp
cfe/trunk/lib/StaticAnalyzer/Core/PathDiagnostic.cpp

Modified: cfe/trunk/include/clang/Analysis/ProgramPoint.h
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Analysis/ProgramPoint.h?rev=324052=324051=324052=diff
==
--- cfe/trunk/include/clang/Analysis/ProgramPoint.h (original)
+++ cfe/trunk/include/clang/Analysis/ProgramPoint.h Thu Feb  1 18:19:43 2018
@@ -641,6 +641,10 @@ public:
   CallExitBegin(const StackFrameContext *L, const ReturnStmt *RS)
 : ProgramPoint(RS, CallExitBeginKind, L, nullptr) { }
 
+  const ReturnStmt *getReturnStmt() const {
+return static_cast(getData1());
+  }
+
 private:
   friend class ProgramPoint;
   CallExitBegin() = default;

Modified: cfe/trunk/lib/StaticAnalyzer/Checkers/AnalysisOrderChecker.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/StaticAnalyzer/Checkers/AnalysisOrderChecker.cpp?rev=324052=324051=324052=diff
==
--- cfe/trunk/lib/StaticAnalyzer/Checkers/AnalysisOrderChecker.cpp (original)
+++ cfe/trunk/lib/StaticAnalyzer/Checkers/AnalysisOrderChecker.cpp Thu Feb  1 
18:19:43 2018
@@ -37,7 +37,9 @@ class AnalysisOrderChecker
  check::PostCall,
  check::NewAllocator,
  check::Bind,
- check::RegionChanges> {
+ check::RegionChanges,
+ check::LiveSymbols> {
+
   bool isCallbackEnabled(AnalyzerOptions , StringRef CallbackName) const {
 return Opts.getBooleanOption("*", false, this) ||
 Opts.getBooleanOption(CallbackName, false, this);
@@ -118,6 +120,11 @@ public:
   llvm::errs() << "Bind\n";
   }
 
+  void checkLiveSymbols(ProgramStateRef State, SymbolReaper ) const {
+if (isCallbackEnabled(State, "LiveSymbols"))
+  llvm::errs() << "LiveSymbols\n";
+  }
+
   ProgramStateRef
   checkRegionChanges(ProgramStateRef State,
  const InvalidatedSymbols *Invalidated,

Modified: cfe/trunk/lib/StaticAnalyzer/Core/CoreEngine.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/StaticAnalyzer/Core/CoreEngine.cpp?rev=324052=324051=324052=diff
==
--- cfe/trunk/lib/StaticAnalyzer/Core/CoreEngine.cpp (original)
+++ cfe/trunk/lib/StaticAnalyzer/Core/CoreEngine.cpp Thu Feb  1 18:19:43 2018
@@ -307,10 +307,7 @@ void CoreEngine::HandleBlockEdge(const B
 const ReturnStmt *RS = nullptr;
 if (!L.getSrc()->empty()) {
   if (Optional LastStmt = L.getSrc()->back().getAs()) {
-if ((RS = dyn_cast(LastStmt->getStmt( {
-  if (!RS->getRetValue())
-RS = nullptr;
-}
+RS = dyn_cast(LastStmt->getStmt());
   }
 }
 

Modified: cfe/trunk/lib/StaticAnalyzer/Core/PathDiagnostic.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/StaticAnalyzer/Core/PathDiagnostic.cpp?rev=324052=324051=324052=diff
==
--- cfe/trunk/lib/StaticAnalyzer/Core/PathDiagnostic.cpp (original)
+++ cfe/trunk/lib/StaticAnalyzer/Core/PathDiagnostic.cpp Thu Feb  1 18:19:43 
2018
@@ -742,6 +742,8 @@ const Stmt *PathDiagnosticLocation::getS
 return CEE->getCalleeContext()->getCallSite();
   if (Optional PIPP = P.getAs())
 return PIPP->getInitializer()->getInit();
+  if (Optional CEB = P.getAs())
+return CEB->getReturnStmt();
 
   return nullptr;
 }

Added: cfe/trunk/test/Analysis/return-stmt-merge.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/Analysis/return-stmt-merge.cpp?rev=324052=auto
==
--- cfe/trunk/test/Analysis/return-stmt-merge.cpp (added)
+++ cfe/trunk/test/Analysis/return-stmt-merge.cpp Thu Feb  1 18:19:43 2018
@@ -0,0 +1,37 @@
+// RUN: %clang_analyze_cc1 
-analyzer-checker=debug.AnalysisOrder,debug.ExprInspection -analyzer-config 

r324050 - Remove the change which accidentally crept in into the cherry-pick

2018-02-01 Thread George Karpenkov via cfe-commits
Author: george.karpenkov
Date: Thu Feb  1 18:14:33 2018
New Revision: 324050

URL: http://llvm.org/viewvc/llvm-project?rev=324050=rev
Log:
Remove the change which accidentally crept in into the cherry-pick

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

Modified: cfe/trunk/lib/StaticAnalyzer/Core/AnalyzerOptions.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/StaticAnalyzer/Core/AnalyzerOptions.cpp?rev=324050=324049=324050=diff
==
--- cfe/trunk/lib/StaticAnalyzer/Core/AnalyzerOptions.cpp (original)
+++ cfe/trunk/lib/StaticAnalyzer/Core/AnalyzerOptions.cpp Thu Feb  1 18:14:33 
2018
@@ -63,7 +63,6 @@ AnalyzerOptions::getExplorationStrategy(
 ExplorationStrategy = llvm::StringSwitch(StratStr)
   .Case("dfs", ExplorationStrategyKind::DFS)
   .Case("bfs", ExplorationStrategyKind::BFS)
-  .Case("loopstack_priority", ExplorationStrategyKind::LoopstackPriority)
   .Case("bfs_block_dfs_contents", 
ExplorationStrategyKind::BFSBlockDFSContents)
   .Default(ExplorationStrategyKind::NotSet);
 assert(ExplorationStrategy != ExplorationStrategyKind::NotSet


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


[PATCH] D42785: [Analyzer] Fix a typo in `ExprEngine::VisitMemberExpr`

2018-02-01 Thread Henry Wong via Phabricator via cfe-commits
MTC added a comment.

In https://reviews.llvm.org/D42785#995211, @NoQ wrote:

> Ew. So it means that checker transitions are currently discarded. Great 
> catch. I guess we don't use this functionality yet, so we can't test it, but 
> the fix should definitely go in.


You are right, that's why I don't know how to add test for this change.

> Then, again, i'm suspecting that you may want to use `checkLocation` or 
> `checkBind` instead of `checkPreStmt` - i doubt that there's 
> anything special about member expressions that make them different from other 
> sorts of bindings. And if you're tracking how a symbol is assigned to a field 
> of the structure - well, you shouldn't, this info is already in the program 
> state and you can retrieve it any time with `getSVal(Region)`.

Thanks for your explanation, NoQ. I discovered the problem by chance, and I'll 
take your advice when it comes to dealing with //`MemberExpr`//.

And I have no commit access. If you plan to commit this change, I hope you can 
help me commit it, thank you in advance!


Repository:
  rC Clang

https://reviews.llvm.org/D42785



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


r324049 - [analyzer] Expose exploration strategy through analyzer options.

2018-02-01 Thread George Karpenkov via cfe-commits
Author: george.karpenkov
Date: Thu Feb  1 18:01:55 2018
New Revision: 324049

URL: http://llvm.org/viewvc/llvm-project?rev=324049=rev
Log:
[analyzer] Expose exploration strategy through analyzer options.

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

Modified:
cfe/trunk/include/clang/StaticAnalyzer/Core/AnalyzerOptions.h
cfe/trunk/include/clang/StaticAnalyzer/Core/PathSensitive/CoreEngine.h
cfe/trunk/include/clang/StaticAnalyzer/Core/PathSensitive/WorkList.h
cfe/trunk/lib/StaticAnalyzer/Core/AnalyzerOptions.cpp
cfe/trunk/lib/StaticAnalyzer/Core/CoreEngine.cpp
cfe/trunk/lib/StaticAnalyzer/Core/ExprEngine.cpp
cfe/trunk/test/Analysis/analyzer-config.c
cfe/trunk/test/Analysis/analyzer-config.cpp

Modified: cfe/trunk/include/clang/StaticAnalyzer/Core/AnalyzerOptions.h
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/StaticAnalyzer/Core/AnalyzerOptions.h?rev=324049=324048=324049=diff
==
--- cfe/trunk/include/clang/StaticAnalyzer/Core/AnalyzerOptions.h (original)
+++ cfe/trunk/include/clang/StaticAnalyzer/Core/AnalyzerOptions.h Thu Feb  1 
18:01:55 2018
@@ -188,7 +188,17 @@ public:
   /// \brief The mode of function selection used during inlining.
   AnalysisInliningMode InliningMode;
 
+  enum class ExplorationStrategyKind {
+DFS,
+BFS,
+BFSBlockDFSContents,
+NotSet
+  };
+
 private:
+
+  ExplorationStrategyKind ExplorationStrategy;
+
   /// \brief Describes the kinds for high-level analyzer mode.
   enum UserModeKind {
 UMK_NotSet = 0,
@@ -390,6 +400,8 @@ public:
   /// outside of AnalyzerOptions.
   UserModeKind getUserMode();
 
+  ExplorationStrategyKind getExplorationStrategy();
+
   /// \brief Returns the inter-procedural analysis mode.
   IPAKind getIPAMode();
 
@@ -611,6 +623,7 @@ public:
 // Cap the stack depth at 4 calls (5 stack frames, base + 4 calls).
 InlineMaxStackDepth(5),
 InliningMode(NoRedundancy),
+ExplorationStrategy(ExplorationStrategyKind::NotSet),
 UserMode(UMK_NotSet),
 IPAMode(IPAK_NotSet),
 CXXMemberInliningMode() {}

Modified: cfe/trunk/include/clang/StaticAnalyzer/Core/PathSensitive/CoreEngine.h
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/StaticAnalyzer/Core/PathSensitive/CoreEngine.h?rev=324049=324048=324049=diff
==
--- cfe/trunk/include/clang/StaticAnalyzer/Core/PathSensitive/CoreEngine.h 
(original)
+++ cfe/trunk/include/clang/StaticAnalyzer/Core/PathSensitive/CoreEngine.h Thu 
Feb  1 18:01:55 2018
@@ -21,6 +21,7 @@
 #include "clang/StaticAnalyzer/Core/PathSensitive/ExplodedGraph.h"
 #include "clang/StaticAnalyzer/Core/PathSensitive/FunctionSummary.h"
 #include "clang/StaticAnalyzer/Core/PathSensitive/WorkList.h"
+#include "clang/StaticAnalyzer/Core/AnalyzerOptions.h"
 #include 
 
 namespace clang {
@@ -114,9 +115,9 @@ private:
 
 public:
   /// Construct a CoreEngine object to analyze the provided CFG.
-  CoreEngine(SubEngine , FunctionSummariesTy *FS)
-  : SubEng(subengine), WList(WorkList::makeDFS()),
-BCounterFactory(G.getAllocator()), FunctionSummaries(FS) {}
+  CoreEngine(SubEngine ,
+ FunctionSummariesTy *FS,
+ AnalyzerOptions );
 
   /// getGraph - Returns the exploded graph.
   ExplodedGraph () { return G; }

Modified: cfe/trunk/include/clang/StaticAnalyzer/Core/PathSensitive/WorkList.h
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/StaticAnalyzer/Core/PathSensitive/WorkList.h?rev=324049=324048=324049=diff
==
--- cfe/trunk/include/clang/StaticAnalyzer/Core/PathSensitive/WorkList.h 
(original)
+++ cfe/trunk/include/clang/StaticAnalyzer/Core/PathSensitive/WorkList.h Thu 
Feb  1 18:01:55 2018
@@ -80,9 +80,9 @@ public:
   void setBlockCounter(BlockCounter C) { CurrentCounter = C; }
   BlockCounter getBlockCounter() const { return CurrentCounter; }
 
-  static WorkList *makeDFS();
-  static WorkList *makeBFS();
-  static WorkList *makeBFSBlockDFSContents();
+  static std::unique_ptr makeDFS();
+  static std::unique_ptr makeBFS();
+  static std::unique_ptr makeBFSBlockDFSContents();
 };
 
 } // end GR namespace

Modified: cfe/trunk/lib/StaticAnalyzer/Core/AnalyzerOptions.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/StaticAnalyzer/Core/AnalyzerOptions.cpp?rev=324049=324048=324049=diff
==
--- cfe/trunk/lib/StaticAnalyzer/Core/AnalyzerOptions.cpp (original)
+++ cfe/trunk/lib/StaticAnalyzer/Core/AnalyzerOptions.cpp Thu Feb  1 18:01:55 
2018
@@ -55,6 +55,26 @@ AnalyzerOptions::UserModeKind AnalyzerOp
   return UserMode;
 }
 
+AnalyzerOptions::ExplorationStrategyKind
+AnalyzerOptions::getExplorationStrategy() {
+  if (ExplorationStrategy == ExplorationStrategyKind::NotSet) {
+StringRef 

[PATCH] D42672: [CFG] [analyzer] Heavier CFGConstructor elements.

2018-02-01 Thread Artem Dergachev via Phabricator via cfe-commits
NoQ updated this revision to Diff 132520.
NoQ added a comment.

Add more targeted tests.


https://reviews.llvm.org/D42672

Files:
  include/clang/Analysis/AnalysisDeclContext.h
  include/clang/Analysis/CFG.h
  include/clang/StaticAnalyzer/Core/AnalyzerOptions.h
  include/clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h
  lib/Analysis/AnalysisDeclContext.cpp
  lib/Analysis/CFG.cpp
  lib/Analysis/LiveVariables.cpp
  lib/StaticAnalyzer/Core/AnalysisManager.cpp
  lib/StaticAnalyzer/Core/AnalyzerOptions.cpp
  lib/StaticAnalyzer/Core/CoreEngine.cpp
  lib/StaticAnalyzer/Core/ExprEngine.cpp
  lib/StaticAnalyzer/Core/ExprEngineCXX.cpp
  lib/StaticAnalyzer/Core/PathDiagnostic.cpp
  test/Analysis/analyzer-config.c
  test/Analysis/analyzer-config.cpp
  test/Analysis/cfg-rich-constructors.cpp
  test/Analysis/cfg.cpp

Index: test/Analysis/cfg.cpp
===
--- test/Analysis/cfg.cpp
+++ test/Analysis/cfg.cpp
@@ -1,5 +1,16 @@
-// RUN: %clang_analyze_cc1 -analyzer-checker=debug.DumpCFG -triple x86_64-apple-darwin12 -analyzer-config cfg-temporary-dtors=true -std=c++11 %s > %t 2>&1
-// RUN: FileCheck --input-file=%t %s
+// RUN: %clang_analyze_cc1 -analyzer-checker=debug.DumpCFG -triple x86_64-apple-darwin12 -analyzer-config cfg-temporary-dtors=true -std=c++11 -analyzer-config cfg-rich-constructors=false %s > %t 2>&1
+// RUN: FileCheck --input-file=%t -check-prefixes=CHECK,WARNINGS %s
+// RUN: %clang_analyze_cc1 -analyzer-checker=debug.DumpCFG -triple x86_64-apple-darwin12 -analyzer-config cfg-temporary-dtors=true -std=c++11 -analyzer-config cfg-rich-constructors=true %s > %t 2>&1
+// RUN: FileCheck --input-file=%t -check-prefixes=CHECK,ANALYZER %s
+
+// This file tests how we construct two different flavors of the Clang CFG -
+// the CFG used by the Sema analysis-based warnings and the CFG used by the
+// static analyzer. The difference in the behavior is checked via FileCheck
+// prefixes (WARNINGS and ANALYZER respectively). When introducing new analyzer
+// flags, no new run lines should be added - just these flags would go to the
+// respective line depending on where is it turned on and where is it turned
+// off. Feel free to add tests that test only one of the CFG flavors if you're
+// not sure how the other flavor is supposed to work in your case.
 
 // CHECK-LABEL: void checkWrap(int i)
 // CHECK: ENTRY
@@ -116,7 +127,8 @@
 // CHECK-NEXT:   Succs (1): B1
 // CHECK: [B1]
 // CHECK-NEXT:   1:  CFGNewAllocator(A *)
-// CHECK-NEXT:   2:  (CXXConstructExpr, class A)
+// WARNINGS-NEXT:   2:  (CXXConstructExpr, class A)
+// ANALYZER-NEXT:   2:  (CXXConstructExpr, [B1.3], class A)
 // CHECK-NEXT:   3: new A([B1.2])
 // CHECK-NEXT:   4: A *a = new A();
 // CHECK-NEXT:   5: a
@@ -138,7 +150,8 @@
 // CHECK: [B1]
 // CHECK-NEXT:   1: 5
 // CHECK-NEXT:   2: CFGNewAllocator(A *)
-// CHECK-NEXT:   3:  (CXXConstructExpr, class A [5])
+// WARNINGS-NEXT:   3:  (CXXConstructExpr, class A [5])
+// ANALYZER-NEXT:   3:  (CXXConstructExpr, [B1.4], class A [5])
 // CHECK-NEXT:   4: new A {{\[\[}}B1.1]]
 // CHECK-NEXT:   5: A *a = new A [5];
 // CHECK-NEXT:   6: a
@@ -331,7 +344,8 @@
 // CHECK-NEXT:  3: [B1.2] (ImplicitCastExpr, ArrayToPointerDecay, int *)
 // CHECK-NEXT:  4: [B1.3] (ImplicitCastExpr, BitCast, void *)
 // CHECK-NEXT:  5: CFGNewAllocator(MyClass *)
-// CHECK-NEXT:  6:  (CXXConstructExpr, class MyClass)
+// WARNINGS-NEXT:  6:  (CXXConstructExpr, class MyClass)
+// ANALYZER-NEXT:  6:  (CXXConstructExpr, [B1.7], class MyClass)
 // CHECK-NEXT:  7: new ([B1.4]) MyClass([B1.6])
 // CHECK-NEXT:  8: MyClass *obj = new (buffer) MyClass();
 // CHECK-NEXT:  Preds (1): B2
@@ -363,7 +377,8 @@
 // CHECK-NEXT:  4: [B1.3] (ImplicitCastExpr, BitCast, void *)
 // CHECK-NEXT:  5: 5
 // CHECK-NEXT:  6: CFGNewAllocator(MyClass *)
-// CHECK-NEXT:  7:  (CXXConstructExpr, class MyClass [5])
+// WARNINGS-NEXT:  7:  (CXXConstructExpr, class MyClass [5])
+// ANALYZER-NEXT:  7:  (CXXConstructExpr, [B1.8], class MyClass [5])
 // CHECK-NEXT:  8: new ([B1.4]) MyClass {{\[\[}}B1.5]]
 // CHECK-NEXT:  9: MyClass *obj = new (buffer) MyClass [5];
 // CHECK-NEXT:  Preds (1): B2
Index: test/Analysis/cfg-rich-constructors.cpp
===
--- /dev/null
+++ test/Analysis/cfg-rich-constructors.cpp
@@ -0,0 +1,46 @@
+// RUN: %clang_analyze_cc1 -analyzer-checker=debug.DumpCFG -triple x86_64-apple-darwin12 -analyzer-config cfg-temporary-dtors=true -std=c++11 %s > %t 2>&1
+// RUN: FileCheck --input-file=%t %s
+
+class C {
+public:
+  C();
+  C(C *);
+};
+
+typedef __typeof(sizeof(int)) size_t;
+void *operator new(size_t size, void *placement);
+
+namespace operator_new {
+
+// CHECK: void operatorNewWithConstructor()
+// CHECK:  1: CFGNewAllocator(C *)
+// CHECK-NEXT: 2:  (CXXConstructExpr, [B1.3], class C)
+// CHECK-NEXT: 3: new C([B1.2])
+void operatorNewWithConstructor() {
+  new C();
+}
+
+// CHECK: void 

[PATCH] D42777: [analyzer] Fix yet-another-crash in body-farming std::call_once

2018-02-01 Thread George Karpenkov via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rC324046: [analyzer] Fix yet-another-crash in body-farming 
std::call_once (authored by george.karpenkov, committed by ).
Herald added a subscriber: cfe-commits.

Repository:
  rC Clang

https://reviews.llvm.org/D42777

Files:
  lib/Analysis/BodyFarm.cpp
  test/Analysis/call_once.cpp


Index: test/Analysis/call_once.cpp
===
--- test/Analysis/call_once.cpp
+++ test/Analysis/call_once.cpp
@@ -9,9 +9,26 @@
 
 void clang_analyzer_eval(bool);
 
-// Faking std::std::call_once implementation.
+// Faking std::call_once implementation.
 namespace std {
 
+// Fake std::function implementation.
+template 
+class function;
+class function_base {
+ public:
+  long field;
+};
+template 
+class function : function_base {
+ public:
+   R operator()(P...) const {
+
+ // Read from a super-class necessary to reproduce a crash.
+ bool a = field;
+   }
+};
+
 #ifndef EMULATE_LIBSTDCPP
 typedef struct once_flag_s {
   unsigned long __state_ = 0;
@@ -360,3 +377,29 @@
   clang_analyzer_eval(x == 42); // expected-warning{{TRUE}}
 #endif
 }
+
+int param_passed(int *x) {
+  return *x; // no-warning, as std::function is not working yet.
+}
+
+void callback_taking_func_ok(std::function ) {
+  innerCallback(nullptr);
+}
+
+// The provided callback expects an std::function, but instead a pointer
+// to a C++ function is provided.
+void callback_with_implicit_cast_ok() {
+  std::once_flag flag;
+  call_once(flag, callback_taking_func_ok, _passed);
+}
+
+void callback_taking_func(std::function ) {
+  innerCallback();
+}
+
+// The provided callback expects an std::function, but instead a C function
+// name is provided, and C++ implicitly auto-constructs a pointer from it.
+void callback_with_implicit_cast() {
+  std::once_flag flag;
+  call_once(flag, callback_taking_func, callback_with_implicit_cast);
+}
Index: lib/Analysis/BodyFarm.cpp
===
--- lib/Analysis/BodyFarm.cpp
+++ lib/Analysis/BodyFarm.cpp
@@ -406,6 +406,16 @@
   // reference.
   for (unsigned int ParamIdx = 2; ParamIdx < D->getNumParams(); ParamIdx++) {
 const ParmVarDecl *PDecl = D->getParamDecl(ParamIdx);
+if (PDecl &&
+CallbackFunctionType->getParamType(ParamIdx - 2)
+.getNonReferenceType()
+.getCanonicalType() !=
+PDecl->getType().getNonReferenceType().getCanonicalType()) {
+  DEBUG(llvm::dbgs() << "Types of params of the callback do not match "
+ << "params passed to std::call_once, "
+ << "ignoring the call\n");
+  return nullptr;
+}
 Expr *ParamExpr = M.makeDeclRefExpr(PDecl);
 if (!CallbackFunctionType->getParamType(ParamIdx - 2)->isReferenceType()) {
   QualType PTy = PDecl->getType().getNonReferenceType();
@@ -816,4 +826,3 @@
 
   return Val.getValue();
 }
-


Index: test/Analysis/call_once.cpp
===
--- test/Analysis/call_once.cpp
+++ test/Analysis/call_once.cpp
@@ -9,9 +9,26 @@
 
 void clang_analyzer_eval(bool);
 
-// Faking std::std::call_once implementation.
+// Faking std::call_once implementation.
 namespace std {
 
+// Fake std::function implementation.
+template 
+class function;
+class function_base {
+ public:
+  long field;
+};
+template 
+class function : function_base {
+ public:
+   R operator()(P...) const {
+
+ // Read from a super-class necessary to reproduce a crash.
+ bool a = field;
+   }
+};
+
 #ifndef EMULATE_LIBSTDCPP
 typedef struct once_flag_s {
   unsigned long __state_ = 0;
@@ -360,3 +377,29 @@
   clang_analyzer_eval(x == 42); // expected-warning{{TRUE}}
 #endif
 }
+
+int param_passed(int *x) {
+  return *x; // no-warning, as std::function is not working yet.
+}
+
+void callback_taking_func_ok(std::function ) {
+  innerCallback(nullptr);
+}
+
+// The provided callback expects an std::function, but instead a pointer
+// to a C++ function is provided.
+void callback_with_implicit_cast_ok() {
+  std::once_flag flag;
+  call_once(flag, callback_taking_func_ok, _passed);
+}
+
+void callback_taking_func(std::function ) {
+  innerCallback();
+}
+
+// The provided callback expects an std::function, but instead a C function
+// name is provided, and C++ implicitly auto-constructs a pointer from it.
+void callback_with_implicit_cast() {
+  std::once_flag flag;
+  call_once(flag, callback_taking_func, callback_with_implicit_cast);
+}
Index: lib/Analysis/BodyFarm.cpp
===
--- lib/Analysis/BodyFarm.cpp
+++ lib/Analysis/BodyFarm.cpp
@@ -406,6 +406,16 @@
   // reference.
   for (unsigned int ParamIdx = 2; ParamIdx < D->getNumParams(); ParamIdx++) {
 const ParmVarDecl *PDecl = D->getParamDecl(ParamIdx);
+if 

r324046 - [analyzer] Fix yet-another-crash in body-farming std::call_once

2018-02-01 Thread George Karpenkov via cfe-commits
Author: george.karpenkov
Date: Thu Feb  1 17:44:07 2018
New Revision: 324046

URL: http://llvm.org/viewvc/llvm-project?rev=324046=rev
Log:
[analyzer] Fix yet-another-crash in body-farming std::call_once

Crash occurs when parameters to the callback and to std::call_once
mismatch, and C++ is supposed to auto-construct an argument.

Filed by Alexander Kornienko in
https://bugs.llvm.org/show_bug.cgi?id=36149

rdar://37034403

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

Modified:
cfe/trunk/lib/Analysis/BodyFarm.cpp
cfe/trunk/test/Analysis/call_once.cpp

Modified: cfe/trunk/lib/Analysis/BodyFarm.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Analysis/BodyFarm.cpp?rev=324046=324045=324046=diff
==
--- cfe/trunk/lib/Analysis/BodyFarm.cpp (original)
+++ cfe/trunk/lib/Analysis/BodyFarm.cpp Thu Feb  1 17:44:07 2018
@@ -406,6 +406,16 @@ static Stmt *create_call_once(ASTContext
   // reference.
   for (unsigned int ParamIdx = 2; ParamIdx < D->getNumParams(); ParamIdx++) {
 const ParmVarDecl *PDecl = D->getParamDecl(ParamIdx);
+if (PDecl &&
+CallbackFunctionType->getParamType(ParamIdx - 2)
+.getNonReferenceType()
+.getCanonicalType() !=
+PDecl->getType().getNonReferenceType().getCanonicalType()) {
+  DEBUG(llvm::dbgs() << "Types of params of the callback do not match "
+ << "params passed to std::call_once, "
+ << "ignoring the call\n");
+  return nullptr;
+}
 Expr *ParamExpr = M.makeDeclRefExpr(PDecl);
 if (!CallbackFunctionType->getParamType(ParamIdx - 2)->isReferenceType()) {
   QualType PTy = PDecl->getType().getNonReferenceType();
@@ -816,4 +826,3 @@ Stmt *BodyFarm::getBody(const ObjCMethod
 
   return Val.getValue();
 }
-

Modified: cfe/trunk/test/Analysis/call_once.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/Analysis/call_once.cpp?rev=324046=324045=324046=diff
==
--- cfe/trunk/test/Analysis/call_once.cpp (original)
+++ cfe/trunk/test/Analysis/call_once.cpp Thu Feb  1 17:44:07 2018
@@ -9,9 +9,26 @@
 
 void clang_analyzer_eval(bool);
 
-// Faking std::std::call_once implementation.
+// Faking std::call_once implementation.
 namespace std {
 
+// Fake std::function implementation.
+template 
+class function;
+class function_base {
+ public:
+  long field;
+};
+template 
+class function : function_base {
+ public:
+   R operator()(P...) const {
+
+ // Read from a super-class necessary to reproduce a crash.
+ bool a = field;
+   }
+};
+
 #ifndef EMULATE_LIBSTDCPP
 typedef struct once_flag_s {
   unsigned long __state_ = 0;
@@ -360,3 +377,29 @@ void test_implicit_funcptr() {
   clang_analyzer_eval(x == 42); // expected-warning{{TRUE}}
 #endif
 }
+
+int param_passed(int *x) {
+  return *x; // no-warning, as std::function is not working yet.
+}
+
+void callback_taking_func_ok(std::function ) {
+  innerCallback(nullptr);
+}
+
+// The provided callback expects an std::function, but instead a pointer
+// to a C++ function is provided.
+void callback_with_implicit_cast_ok() {
+  std::once_flag flag;
+  call_once(flag, callback_taking_func_ok, _passed);
+}
+
+void callback_taking_func(std::function ) {
+  innerCallback();
+}
+
+// The provided callback expects an std::function, but instead a C function
+// name is provided, and C++ implicitly auto-constructs a pointer from it.
+void callback_with_implicit_cast() {
+  std::once_flag flag;
+  call_once(flag, callback_taking_func, callback_with_implicit_cast);
+}


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


[PATCH] D42606: [Coroutines] Use allocator overload when available

2018-02-01 Thread Gor Nishanov via Phabricator via cfe-commits
GorNishanov added inline comments.



Comment at: lib/CodeGen/CGCoroutine.cpp:526
   EmitBlock(AllocBB);
-  auto *AllocateCall = EmitScalarExpr(S.getAllocate());
+  // Emit the call to the coroutine frame allocation function.
+  auto *AllocateCall = cast(EmitScalarExpr(S.getAllocate()));

GorNishanov wrote:
> First, thank you for doing this change!
> 
> Second, I am not sure that this part (CGCoroutine.cpp change) belongs in 
> clang.
> llvm CoroFrame is doing an unsafe transformation (it was safe until we got 
> the arguments to operator new :-) ). 
> 
> Moving the stores after the new that loads from those stores is an incorrect 
> transformation. I think it needs to be addressed in llvm. 
> getNotRelocatableInstructions function in CoroSplit.cpp needs to add special 
> handling for AllocaInst and freeze the stores to that Alloca in the blocks 
> preceeding the one with CoroBegin (getCoroBeginPredBlocks).
> 
> Also, for this to work for cases where parameter is used both in allocating 
> function and in the body of the coroutine we need to have a copy. Currently, 
> front-end does not create copies for scalar types (see 
> CoroutineStmtBuilder::makeParamMoves() in SemaCoroutine.cpp). I think if we 
> always create copies for all parameters, it will make this change more 
> straightforward.
> 
> Third, this code does not handle cases where scalar values passed by 
> reference to an allocation function or a struct passed by value:
> 
> Try this code on these:
> 
> void *operator new(unsigned long, promise_matching_placement_new_tag,
>int&, float, double);
> 
> or
> 
> ```
> struct Dummy { int x, y, z; ~Dummy(); };
> 
> template<>
> struct std::experimental::coroutine_traits promise_matching_placement_new_tag, Dummy&, float, double> {
>struct promise_type {
>void *operator new(unsigned long, 
> promise_matching_placement_new_tag,
>Dummy, float, double);
> ```
> 
> I think if this code is changed according to my earlier suggestion of doing 
> copies in clang and  freezing stores in the llvm, it should take care the 
> cases above.
> 
> These cases need to be added as tests to llvm\tests\Transforms\Coroutines
Alternatively, we can keep current clang behavior with respect to not doing 
copies for scalars and instead create a copy in llvm if we decided to freeze 
the store AND that alloca is used after a suspend point (CoroFrame decided that 
it needs to spill it into the coroutine frame).


Repository:
  rC Clang

https://reviews.llvm.org/D42606



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


[PATCH] D42606: [Coroutines] Use allocator overload when available

2018-02-01 Thread Gor Nishanov via Phabricator via cfe-commits
GorNishanov requested changes to this revision.
GorNishanov added inline comments.
This revision now requires changes to proceed.



Comment at: lib/CodeGen/CGCoroutine.cpp:526
   EmitBlock(AllocBB);
-  auto *AllocateCall = EmitScalarExpr(S.getAllocate());
+  // Emit the call to the coroutine frame allocation function.
+  auto *AllocateCall = cast(EmitScalarExpr(S.getAllocate()));

First, thank you for doing this change!

Second, I am not sure that this part (CGCoroutine.cpp change) belongs in clang.
llvm CoroFrame is doing an unsafe transformation (it was safe until we got the 
arguments to operator new :-) ). 

Moving the stores after the new that loads from those stores is an incorrect 
transformation. I think it needs to be addressed in llvm. 
getNotRelocatableInstructions function in CoroSplit.cpp needs to add special 
handling for AllocaInst and freeze the stores to that Alloca in the blocks 
preceeding the one with CoroBegin (getCoroBeginPredBlocks).

Also, for this to work for cases where parameter is used both in allocating 
function and in the body of the coroutine we need to have a copy. Currently, 
front-end does not create copies for scalar types (see 
CoroutineStmtBuilder::makeParamMoves() in SemaCoroutine.cpp). I think if we 
always create copies for all parameters, it will make this change more 
straightforward.

Third, this code does not handle cases where scalar values passed by reference 
to an allocation function or a struct passed by value:

Try this code on these:

void *operator new(unsigned long, promise_matching_placement_new_tag,
   int&, float, double);

or

```
struct Dummy { int x, y, z; ~Dummy(); };

template<>
struct std::experimental::coroutine_traits {
   struct promise_type {
   void *operator new(unsigned long, promise_matching_placement_new_tag,
   Dummy, float, double);
```

I think if this code is changed according to my earlier suggestion of doing 
copies in clang and  freezing stores in the llvm, it should take care the cases 
above.

These cases need to be added as tests to llvm\tests\Transforms\Coroutines


Repository:
  rC Clang

https://reviews.llvm.org/D42606



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


[PATCH] D42768: AST: add an extension to support SwiftCC on MS ABI

2018-02-01 Thread Reid Kleckner via Phabricator via cfe-commits
rnk added a comment.

In https://reviews.llvm.org/D42768#994458, @rjmccall wrote:

> No, I mean things like `void foo(__attribute__((swiftcall)) void 
> (*fnptr)());`.


Yeah, this was the example I was going to bring up. There's no function 
parameter declaration to put the NNS on.

So, here's an idea that's probably general. It's what we do for vector types 
and (I think?) Obj-C blocks. Whenever we need to mangle a FunctionType with 
swiftcc, we look at the function type and mangle it as a `struct __swiftcc` 
where T is the FunctionType without the convention.


Repository:
  rC Clang

https://reviews.llvm.org/D42768



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


[PATCH] D42829: Emit label names according to -discard-value-names.

2018-02-01 Thread Eric Fiselier via Phabricator via cfe-commits
EricWF created this revision.
EricWF added reviewers: erichkeane, aaron.ballman, majnemer.

Previously, Clang only emitted label names in assert builds.
However there is a CC1 option -discard-value-names that should have been used 
to control emission instead.

  

This patch removes the NDEBUG preprocessor block and instead allows LLVM to 
handle removing the names in accordance with the option.


https://reviews.llvm.org/D42829

Files:
  lib/CodeGen/CodeGenFunction.h
  test/CodeGenCXX/discard-name-values.cpp


Index: test/CodeGenCXX/discard-name-values.cpp
===
--- test/CodeGenCXX/discard-name-values.cpp
+++ test/CodeGenCXX/discard-name-values.cpp
@@ -1,10 +1,30 @@
-// RUN: %clang_cc1 -emit-llvm  -triple=armv7-apple-darwin -emit-llvm 
-std=c++11 %s -o - -O1 | FileCheck %s
-// RUN: %clang_cc1 -emit-llvm  -triple=armv7-apple-darwin -emit-llvm 
-std=c++11 %s -o - -O1 -discard-value-names | FileCheck %s 
--check-prefix=DISCARDVALUE
+// RUN: %clang_cc1 -emit-llvm  -triple=armv7-apple-darwin -std=c++11 %s -o - 
-O1 \
+// RUN:| FileCheck %s
+// RUN: %clang_cc1 -emit-llvm -triple=armv7-apple-darwin -std=c++11 %s -o - 
-O1 \
+// RUN:-discard-value-names | FileCheck %s --check-prefix=DISCARDVALUE
 
-int foo(int bar) {
-  return bar;
-}
 
-// CHECK: ret i32 %bar
-// DISCARDVALUE: ret i32 %0
+extern "C" void branch();
+
+bool test(bool pred) {
+// DISCARDVALUE: br i1 %0, label %2, label %3
+// CHECK: br i1 %pred, label %if.then, label %if.end
+
+  if (pred) {
+  // DISCARDVALUE: ; :2:
+  // DISCARDVALUE-NEXT: tail call void @branch()
+  // DISCARDVALUE-NEXT: br label %3
 
+  // CHECK: if.then:
+  // CHECK-NEXT: tail call void @branch()
+  // CHECK-NEXT: br label %if.end
+branch();
+  }
+
+// DISCARDVALUE: ; :3:
+// DISCARDVALUE-NEXT: ret i1 %0
+
+// CHECK: if.end:
+// CHECK-NEXT: ret i1 %pred
+  return pred;
+}
Index: lib/CodeGen/CodeGenFunction.h
===
--- lib/CodeGen/CodeGenFunction.h
+++ lib/CodeGen/CodeGenFunction.h
@@ -1849,11 +1849,7 @@
   llvm::BasicBlock *createBasicBlock(const Twine  = "",
  llvm::Function *parent = nullptr,
  llvm::BasicBlock *before = nullptr) {
-#ifdef NDEBUG
-return llvm::BasicBlock::Create(getLLVMContext(), "", parent, before);
-#else
 return llvm::BasicBlock::Create(getLLVMContext(), name, parent, before);
-#endif
   }
 
   /// getBasicBlockForLabel - Return the LLVM basicblock that the specified


Index: test/CodeGenCXX/discard-name-values.cpp
===
--- test/CodeGenCXX/discard-name-values.cpp
+++ test/CodeGenCXX/discard-name-values.cpp
@@ -1,10 +1,30 @@
-// RUN: %clang_cc1 -emit-llvm  -triple=armv7-apple-darwin -emit-llvm -std=c++11 %s -o - -O1 | FileCheck %s
-// RUN: %clang_cc1 -emit-llvm  -triple=armv7-apple-darwin -emit-llvm -std=c++11 %s -o - -O1 -discard-value-names | FileCheck %s --check-prefix=DISCARDVALUE
+// RUN: %clang_cc1 -emit-llvm  -triple=armv7-apple-darwin -std=c++11 %s -o - -O1 \
+// RUN:| FileCheck %s
+// RUN: %clang_cc1 -emit-llvm -triple=armv7-apple-darwin -std=c++11 %s -o - -O1 \
+// RUN:-discard-value-names | FileCheck %s --check-prefix=DISCARDVALUE
 
-int foo(int bar) {
-  return bar;
-}
 
-// CHECK: ret i32 %bar
-// DISCARDVALUE: ret i32 %0
+extern "C" void branch();
+
+bool test(bool pred) {
+// DISCARDVALUE: br i1 %0, label %2, label %3
+// CHECK: br i1 %pred, label %if.then, label %if.end
+
+  if (pred) {
+  // DISCARDVALUE: ; :2:
+  // DISCARDVALUE-NEXT: tail call void @branch()
+  // DISCARDVALUE-NEXT: br label %3
 
+  // CHECK: if.then:
+  // CHECK-NEXT: tail call void @branch()
+  // CHECK-NEXT: br label %if.end
+branch();
+  }
+
+// DISCARDVALUE: ; :3:
+// DISCARDVALUE-NEXT: ret i1 %0
+
+// CHECK: if.end:
+// CHECK-NEXT: ret i1 %pred
+  return pred;
+}
Index: lib/CodeGen/CodeGenFunction.h
===
--- lib/CodeGen/CodeGenFunction.h
+++ lib/CodeGen/CodeGenFunction.h
@@ -1849,11 +1849,7 @@
   llvm::BasicBlock *createBasicBlock(const Twine  = "",
  llvm::Function *parent = nullptr,
  llvm::BasicBlock *before = nullptr) {
-#ifdef NDEBUG
-return llvm::BasicBlock::Create(getLLVMContext(), "", parent, before);
-#else
 return llvm::BasicBlock::Create(getLLVMContext(), name, parent, before);
-#endif
   }
 
   /// getBasicBlockForLabel - Return the LLVM basicblock that the specified
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


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

2018-02-01 Thread Katya Romanova via Phabricator via cfe-commits
kromanova added subscribers: kromanova, alexfh.
kromanova added a comment.

We have a request for this feature in clang-format in Sony.


Repository:
  rL LLVM

https://reviews.llvm.org/D28462



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


[PATCH] D22505: clang-format Access Modifier Use Normal Indent

2018-02-01 Thread Tim Ansell via Phabricator via cfe-commits
mithro added a comment.
Herald added subscribers: hintonda, mgorny.

I was wondering what the status of this feature was? Looks like it was last 
touched back in Aug 2 2016 -- do you know if a different or replacement patch 
was landed? I have a project 
(https://github.com/verilog-to-routing/vtr-verilog-to-routing) that I'm trying 
to convince to use clang-format but they use this style of indenting after the 
accessor modifier and convincing them to change style is a *much* bigger 
challenge then getting them to adopt clang-format usage :-)


https://reviews.llvm.org/D22505



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


r324037 - [coroutines] Fix application of NRVO to Coroutine "Gro" or return object.

2018-02-01 Thread Eric Fiselier via cfe-commits
Author: ericwf
Date: Thu Feb  1 15:47:54 2018
New Revision: 324037

URL: http://llvm.org/viewvc/llvm-project?rev=324037=rev
Log:
[coroutines] Fix application of NRVO to Coroutine "Gro" or return object.

Summary:
Fix NRVO for Gro variable.

Previously, we only marked the GRO declaration as an NRVO variable
when its QualType and the function return's QualType matched exactly
(using operator==). However, this was incorrect for two reasons:

1. We were marking non-class types, such as ints, as being NRVO variables.

2. We failed to  handle cases where the canonical types were the same, but the 
actual `QualType` objects were different. For example, if  one was represented 
by a typedef. (Example: https://godbolt.org/g/3UFgsL)

This patch fixes these bugs by marking the Gro variable as supporting NRVO only
when `BuildReturnStmt` marks the Gro variable as a coroutine candidate.






Reviewers: rsmith, GorNishanov, nicholas

Reviewed By: GorNishanov

Subscribers: majnemer, cfe-commits

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

Added:
cfe/trunk/test/CodeGenCoroutines/coro-gro-nrvo.cpp
Modified:
cfe/trunk/lib/Sema/SemaCoroutine.cpp
cfe/trunk/test/CodeGenCoroutines/coro-alloc.cpp

Modified: cfe/trunk/lib/Sema/SemaCoroutine.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Sema/SemaCoroutine.cpp?rev=324037=324036=324037=diff
==
--- cfe/trunk/lib/Sema/SemaCoroutine.cpp (original)
+++ cfe/trunk/lib/Sema/SemaCoroutine.cpp Thu Feb  1 15:47:54 2018
@@ -1316,10 +1316,6 @@ bool CoroutineStmtBuilder::makeGroDeclAn
   if (Res.isInvalid())
 return false;
 
-  if (GroType == FnRetType) {
-GroDecl->setNRVOVariable(true);
-  }
-
   S.AddInitializerToDecl(GroDecl, Res.get(),
  /*DirectInit=*/false);
 
@@ -1343,6 +1339,8 @@ bool CoroutineStmtBuilder::makeGroDeclAn
 noteMemberDeclaredHere(S, ReturnValue, Fn);
 return false;
   }
+  if (cast(ReturnStmt.get())->getNRVOCandidate() == GroDecl)
+GroDecl->setNRVOVariable(true);
 
   this->ReturnStmt = ReturnStmt.get();
   return true;

Modified: cfe/trunk/test/CodeGenCoroutines/coro-alloc.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/CodeGenCoroutines/coro-alloc.cpp?rev=324037=324036=324037=diff
==
--- cfe/trunk/test/CodeGenCoroutines/coro-alloc.cpp (original)
+++ cfe/trunk/test/CodeGenCoroutines/coro-alloc.cpp Thu Feb  1 15:47:54 2018
@@ -173,6 +173,7 @@ struct std::experimental::coroutine_trai
 // CHECK-LABEL: f4(
 extern "C" int f4(promise_on_alloc_failure_tag) {
   // CHECK: %[[RetVal:.+]] = alloca i32
+  // CHECK: %[[Gro:.+]] = alloca i32
   // CHECK: %[[ID:.+]] = call token @llvm.coro.id(i32 16
   // CHECK: %[[SIZE:.+]] = call i64 @llvm.coro.size.i64()
   // CHECK: %[[MEM:.+]] = call i8* @_ZnwmRKSt9nothrow_t(i64 %[[SIZE]], 
%"struct.std::nothrow_t"* dereferenceable(1) @_ZStL7nothrow)
@@ -186,7 +187,11 @@ extern "C" int f4(promise_on_alloc_failu
 
   // CHECK: [[OKBB]]:
   // CHECK:   %[[OkRet:.+]] = call i32 
@_ZNSt12experimental16coroutine_traitsIJi28promise_on_alloc_failure_tagEE12promise_type17get_return_objectEv(
-  // CHECK:   store i32 %[[OkRet]], i32* %[[RetVal]]
+  // CHECK:   store i32 %[[OkRet]], i32* %[[Gro]]
+
+  // CHECK: %[[Tmp1:.*]] = load i32, i32* %[[Gro]]
+  // CHECK-NEXT: store i32 %[[Tmp1]], i32* %[[RetVal]]
+  // CHECK-NEXT: br label %[[RetBB]]
 
   // CHECK: [[RetBB]]:
   // CHECK:   %[[LoadRet:.+]] = load i32, i32* %[[RetVal]], align 4

Added: cfe/trunk/test/CodeGenCoroutines/coro-gro-nrvo.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/CodeGenCoroutines/coro-gro-nrvo.cpp?rev=324037=auto
==
--- cfe/trunk/test/CodeGenCoroutines/coro-gro-nrvo.cpp (added)
+++ cfe/trunk/test/CodeGenCoroutines/coro-gro-nrvo.cpp Thu Feb  1 15:47:54 2018
@@ -0,0 +1,87 @@
+// RUN: %clang_cc1 -triple x86_64-unknown-linux-gnu -fcoroutines-ts -std=c++14 
-emit-llvm %s -o - -disable-llvm-passes | FileCheck %s
+
+#include "Inputs/coroutine.h"
+
+using namespace std::experimental;
+
+namespace std {
+
+struct nothrow_t {};
+constexpr nothrow_t nothrow = {};
+
+} // end namespace std
+
+// Required when get_return_object_on_allocation_failure() is defined by
+// the promise.
+void* operator new(__SIZE_TYPE__ __sz, const std::nothrow_t&) noexcept;
+void  operator delete(void* __p, const std::nothrow_t&) noexcept;
+
+
+template 
+struct promise_type {
+RetObject get_return_object();
+suspend_always initial_suspend();
+suspend_never final_suspend();
+void return_void();
+static void unhandled_exception();
+};
+
+struct coro {
+  using promise_type = promise_type;
+  coro(coro const&);
+  struct Impl;
+  Impl *impl;
+};
+
+// Verify that the NRVO is applied to the Gro object.
+// CHECK-LABEL: define void @_Z1fi(%struct.coro* noalias sret 

[PATCH] D42343: [coroutines] Fix application of NRVO to Coroutine "Gro" or return object.

2018-02-01 Thread Eric Fiselier via Phabricator via cfe-commits
EricWF updated this revision to Diff 132495.
EricWF added a comment.

I had to revert due to failing tests when using a non-assert Clang build.

This change fixes those tests to no longer depend on label names.


https://reviews.llvm.org/D42343

Files:
  lib/Sema/SemaCoroutine.cpp
  test/CodeGenCoroutines/coro-alloc.cpp
  test/CodeGenCoroutines/coro-gro-nrvo.cpp

Index: test/CodeGenCoroutines/coro-gro-nrvo.cpp
===
--- /dev/null
+++ test/CodeGenCoroutines/coro-gro-nrvo.cpp
@@ -0,0 +1,87 @@
+// RUN: %clang_cc1 -triple x86_64-unknown-linux-gnu -fcoroutines-ts -std=c++14 -emit-llvm %s -o - -disable-llvm-passes | FileCheck %s
+
+#include "Inputs/coroutine.h"
+
+using namespace std::experimental;
+
+namespace std {
+
+struct nothrow_t {};
+constexpr nothrow_t nothrow = {};
+
+} // end namespace std
+
+// Required when get_return_object_on_allocation_failure() is defined by
+// the promise.
+void* operator new(__SIZE_TYPE__ __sz, const std::nothrow_t&) noexcept;
+void  operator delete(void* __p, const std::nothrow_t&) noexcept;
+
+
+template 
+struct promise_type {
+RetObject get_return_object();
+suspend_always initial_suspend();
+suspend_never final_suspend();
+void return_void();
+static void unhandled_exception();
+};
+
+struct coro {
+  using promise_type = promise_type;
+  coro(coro const&);
+  struct Impl;
+  Impl *impl;
+};
+
+// Verify that the NRVO is applied to the Gro object.
+// CHECK-LABEL: define void @_Z1fi(%struct.coro* noalias sret %agg.result, i32)
+coro f(int) {
+// CHECK: %call = call i8* @_Znwm(
+// CHECK-NEXT: br label %[[CoroInit:.*]]
+
+// CHECK: {{.*}}[[CoroInit]]:
+// CHECK: store i1 false, i1* %gro.active
+// CHECK-NEXT: call void @{{.*get_return_objectEv}}(%struct.coro* sret %agg.result
+// CHECK-NEXT: store i1 true, i1* %gro.active
+  co_return;
+}
+
+
+template 
+struct promise_type_with_on_alloc_failure {
+static RetObject get_return_object_on_allocation_failure();
+RetObject get_return_object();
+suspend_always initial_suspend();
+suspend_never final_suspend();
+void return_void();
+static void unhandled_exception();
+};
+
+struct coro_two {
+  using promise_type = promise_type_with_on_alloc_failure;
+  coro_two(coro_two const&);
+  struct Impl;
+  Impl *impl;
+};
+
+// Verify that the NRVO is applied to the Gro object.
+// CHECK-LABEL: define void @_Z1hi(%struct.coro_two* noalias sret %agg.result, i32)
+ coro_two h(int) {
+
+// CHECK: %call = call i8* @_ZnwmRKSt9nothrow_t
+// CHECK-NEXT: %[[CheckNull:.*]] = icmp ne i8* %call, null
+// CHECK-NEXT: br i1 %[[CheckNull]], label %[[InitOnSuccess:.*]], label %[[InitOnFailure:.*]]
+
+// CHECK: {{.*}}[[InitOnFailure]]:
+// CHECK-NEXT: call void @{{.*get_return_object_on_allocation_failureEv}}(%struct.coro_two* sret %agg.result
+// CHECK-NEXT: br label %[[RetLabel:.*]]
+
+// CHECK: {{.*}}[[InitOnSuccess]]:
+// CHECK: store i1 false, i1* %gro.active
+// CHECK-NEXT: call void @{{.*get_return_objectEv}}(%struct.coro_two* sret %agg.result
+// CHECK-NEXT: store i1 true, i1* %gro.active
+
+// CHECK: [[RetLabel]]:
+// CHECK-NEXT: ret void
+  co_return;
+}
Index: test/CodeGenCoroutines/coro-alloc.cpp
===
--- test/CodeGenCoroutines/coro-alloc.cpp
+++ test/CodeGenCoroutines/coro-alloc.cpp
@@ -173,6 +173,7 @@
 // CHECK-LABEL: f4(
 extern "C" int f4(promise_on_alloc_failure_tag) {
   // CHECK: %[[RetVal:.+]] = alloca i32
+  // CHECK: %[[Gro:.+]] = alloca i32
   // CHECK: %[[ID:.+]] = call token @llvm.coro.id(i32 16
   // CHECK: %[[SIZE:.+]] = call i64 @llvm.coro.size.i64()
   // CHECK: %[[MEM:.+]] = call i8* @_ZnwmRKSt9nothrow_t(i64 %[[SIZE]], %"struct.std::nothrow_t"* dereferenceable(1) @_ZStL7nothrow)
@@ -186,7 +187,11 @@
 
   // CHECK: [[OKBB]]:
   // CHECK:   %[[OkRet:.+]] = call i32 @_ZNSt12experimental16coroutine_traitsIJi28promise_on_alloc_failure_tagEE12promise_type17get_return_objectEv(
-  // CHECK:   store i32 %[[OkRet]], i32* %[[RetVal]]
+  // CHECK:   store i32 %[[OkRet]], i32* %[[Gro]]
+
+  // CHECK: %[[Tmp1:.*]] = load i32, i32* %[[Gro]]
+  // CHECK-NEXT: store i32 %[[Tmp1]], i32* %[[RetVal]]
+  // CHECK-NEXT: br label %[[RetBB]]
 
   // CHECK: [[RetBB]]:
   // CHECK:   %[[LoadRet:.+]] = load i32, i32* %[[RetVal]], align 4
Index: lib/Sema/SemaCoroutine.cpp
===
--- lib/Sema/SemaCoroutine.cpp
+++ lib/Sema/SemaCoroutine.cpp
@@ -1316,10 +1316,6 @@
   if (Res.isInvalid())
 return false;
 
-  if (GroType == FnRetType) {
-GroDecl->setNRVOVariable(true);
-  }
-
   S.AddInitializerToDecl(GroDecl, Res.get(),
  /*DirectInit=*/false);
 
@@ -1343,6 +1339,8 @@
 noteMemberDeclaredHere(S, ReturnValue, Fn);
 return false;
   }
+  if (cast(ReturnStmt.get())->getNRVOCandidate() == GroDecl)
+GroDecl->setNRVOVariable(true);
 
   this->ReturnStmt = ReturnStmt.get();
   return true;

[PATCH] D42351: Emit DWARF "constructor" calling convention for every supported Clang CC

2018-02-01 Thread Paul Robinson via Phabricator via cfe-commits
probinson added a comment.

+1 for testcase.


Repository:
  rC Clang

https://reviews.llvm.org/D42351



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


[libcxx] r324033 - Disable test in C++<11 mode due to use of alignas.

2018-02-01 Thread Richard Smith via cfe-commits
Author: rsmith
Date: Thu Feb  1 15:31:22 2018
New Revision: 324033

URL: http://llvm.org/viewvc/llvm-project?rev=324033=rev
Log:
Disable test in C++<11 mode due to use of alignas.

Modified:
libcxx/trunk/test/std/utilities/memory/temporary.buffer/overaligned.pass.cpp

Modified: 
libcxx/trunk/test/std/utilities/memory/temporary.buffer/overaligned.pass.cpp
URL: 
http://llvm.org/viewvc/llvm-project/libcxx/trunk/test/std/utilities/memory/temporary.buffer/overaligned.pass.cpp?rev=324033=324032=324033=diff
==
--- 
libcxx/trunk/test/std/utilities/memory/temporary.buffer/overaligned.pass.cpp 
(original)
+++ 
libcxx/trunk/test/std/utilities/memory/temporary.buffer/overaligned.pass.cpp 
Thu Feb  1 15:31:22 2018
@@ -7,6 +7,8 @@
 //
 
//===--===//
 
+// UNSUPPORTED: c++98, c++03
+
 // 
 
 // template 


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


[PATCH] D42755: [libcxx] Fix last_write_time tests for filesystems that don't support very small times.

2018-02-01 Thread Volodymyr Sapsai via Phabricator via cfe-commits
vsapsai added a comment.

In https://reviews.llvm.org/D42755#994775, @Hahnfeld wrote:

> Can you please add a summary that describes which filesystem this problem can 
> be seen with? I think outside people can't access rdar tickets, so I can only 
> guess that it's related to APFS? Further guessing the filesystem supports 
> negative timestamps in general but not `file_time_type::min()` (which 
> probably is `-2 ** 63`)?


Good suggestion for explaining the problem with `file_time_type::min()` in more 
detail. Also PR35990  has some 
details on how different filesystems handle `file_time_type::min()`. As the 
change doesn't fix the PR, I don't think it is worth mentioning it in the 
commit message but it can be still useful in code review discussion.


https://reviews.llvm.org/D42755



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


[PATCH] D39571: [clangd] DidChangeConfiguration Notification

2018-02-01 Thread Simon Marchi via Phabricator via cfe-commits
simark added inline comments.



Comment at: clangd/ClangdLSPServer.cpp:302
 
+// FIXME: This function needs to be properly tested.
+void ClangdLSPServer::onChangeConfiguration(

simark wrote:
> ilya-biryukov wrote:
> > simark wrote:
> > > simark wrote:
> > > > ilya-biryukov wrote:
> > > > > simark wrote:
> > > > > > ilya-biryukov wrote:
> > > > > > > simark wrote:
> > > > > > > > ilya-biryukov wrote:
> > > > > > > > > Are you planning to to address this FIXME before checking the 
> > > > > > > > > code in?
> > > > > > > > Following what you said here:
> > > > > > > > 
> > > > > > > > https://reviews.llvm.org/D39571?id=124024#inline-359345
> > > > > > > > 
> > > > > > > > I have not really looked into what was wrong with the test, and 
> > > > > > > > what is missing in the infrastructure to make it work.  But I 
> > > > > > > > assumed that the situation did not change since then.  Can you 
> > > > > > > > enlighten me on what the problem was, and what is missing?
> > > > > > > We usually write unittests for that kind of thing, since they 
> > > > > > > allow to plug an in-memory filesystem, but we only test 
> > > > > > > `ClangdServer` (examples are in 
> > > > > > > `unittests/clangd/ClangdTests.cpp`). `ClangdLSPServer` does not 
> > > > > > > allow to plug in a virtual filesystem (vfs). Even if we add vfs, 
> > > > > > > it's still hard to unit-test because we'll have to match the json 
> > > > > > > input/output directly.
> > > > > > > 
> > > > > > > This leaves us with an option of a lit test that runs `clangd` 
> > > > > > > directly, similar to tests in `test/clangd`.
> > > > > > > The lit test would need to create a temporary directory, create 
> > > > > > > proper `compile_commands.json` there, then send the LSP commands 
> > > > > > > with the path to the test to clangd.
> > > > > > > One major complication is that in LSP we have to specify the size 
> > > > > > > of each message, but in our case the size would change depending 
> > > > > > > on created temp path. It means we'll have to patch the test input 
> > > > > > > to setup proper paths and message sizes.
> > > > > > > If we choose to go down this path, 
> > > > > > > `clang-tools-extra/test/clang-tidy/vfsoverlay.cpp` does a similar 
> > > > > > > setup (create temp-dir, patch up some configuration files to 
> > > > > > > point into the temp directory, etc) and could be used as a 
> > > > > > > starting point.
> > > > > > > 
> > > > > > > It's not impossible to write that test, it's just a bit involved. 
> > > > > > > Having a test would be nice, though, to ensure we don't break 
> > > > > > > this method while doing other things. Especially given that this 
> > > > > > > functionality is not used anywhere in clangd.
> > > > > > > We usually write unittests for that kind of thing, since they 
> > > > > > > allow to plug an in-memory filesystem, but we only test 
> > > > > > > ClangdServer (examples are in unittests/clangd/ClangdTests.cpp). 
> > > > > > > ClangdLSPServer does not allow to plug in a virtual filesystem 
> > > > > > > (vfs). Even if we add vfs, it's still hard to unit-test because 
> > > > > > > we'll have to match the json input/output directly.
> > > > > > 
> > > > > > What do you mean by "we'll have to match the json input/output 
> > > > > > directly"?  That we'll have to match the complete JSON output 
> > > > > > textually?  Couldn't the test parse the JSON into some data 
> > > > > > structures, then we could assert specific things, like that this 
> > > > > > particular field is present and contains a certain substring, for 
> > > > > > example?
> > > > > > 
> > > > > > > This leaves us with an option of a lit test that runs clangd 
> > > > > > > directly, similar to tests in test/clangd.
> > > > > > > The lit test would need to create a temporary directory, create 
> > > > > > > proper compile_commands.json there, then send the LSP commands 
> > > > > > > with the path to the test to clangd.
> > > > > > > One major complication is that in LSP we have to specify the size 
> > > > > > > of each message, but in our case the size would change depending 
> > > > > > > on created temp path. It means we'll have to patch the test input 
> > > > > > > to setup proper paths and message sizes.
> > > > > > > If we choose to go down this path, 
> > > > > > > clang-tools-extra/test/clang-tidy/vfsoverlay.cpp does a similar 
> > > > > > > setup (create temp-dir, patch up some configuration files to 
> > > > > > > point into the temp directory, etc) and could be used as a 
> > > > > > > starting point.
> > > > > > 
> > > > > > Ok, I see the complication with the Content-Length.  I am not 
> > > > > > familiar with lit yet, so I don't know what it is capable of.  But 
> > > > > > being able to craft and send arbitrary LSP messages would certainly 
> > > > > > be helpful in the future for all kinds of black box test, so having 
> > > > > > a framework that allows to do this would be helpful, I think.  

Re: r323155 - Introduce the "retpoline" x86 mitigation technique for variant #2 of the speculative execution vulnerabilities disclosed today, specifically identified by CVE-2017-5715, "Branch Target

2018-02-01 Thread Reid Kleckner via cfe-commits
I backported these to the release_50 branch in the following revisions:

llvm r324007, r324009
cfe r324012
lld r324025, r324026

The regression test suites pass on my machine with the exception of two
pre-existing failures. I also built my small retpoline execution test that
does a variety of indirect calls and tail calls, and it executes
successfully and the only indirect jumps in it come from crt0.o. That's the
same as what we get with trunk.

We might want to do more extensive testing of the flag with the 5.0
release, but I'm not sure what's next exactly.

On Thu, Feb 1, 2018 at 11:09 AM, Chandler Carruth 
wrote:

> +Hans Wennborg  +tstel...@redhat.com
> 
>
> So the retpoline patch series we should get back ported start with this
> revision and have two follow ups:
> r323155
> r323288
> r323915
>
> +Reid Kleckner  was going to look at doing the (likely
> more involved) backport to the 5 branch
>
> On Mon, Jan 22, 2018 at 2:06 PM Chandler Carruth via cfe-commits <
> cfe-commits@lists.llvm.org> wrote:
>
>> Author: chandlerc
>> Date: Mon Jan 22 14:05:25 2018
>> New Revision: 323155
>>
>> URL: http://llvm.org/viewvc/llvm-project?rev=323155=rev
>> Log:
>> Introduce the "retpoline" x86 mitigation technique for variant #2 of the
>> speculative execution vulnerabilities disclosed today, specifically
>> identified by CVE-2017-5715, "Branch Target Injection", and is one of the
>> two halves to Spectre..
>>
>> Summary:
>> First, we need to explain the core of the vulnerability. Note that this
>> is a very incomplete description, please see the Project Zero blog post
>> for details:
>> https://googleprojectzero.blogspot.com/2018/01/reading-
>> privileged-memory-with-side.html
>>
>> The basis for branch target injection is to direct speculative execution
>> of the processor to some "gadget" of executable code by poisoning the
>> prediction of indirect branches with the address of that gadget. The
>> gadget in turn contains an operation that provides a side channel for
>> reading data. Most commonly, this will look like a load of secret data
>> followed by a branch on the loaded value and then a load of some
>> predictable cache line. The attacker then uses timing of the processors
>> cache to determine which direction the branch took *in the speculative
>> execution*, and in turn what one bit of the loaded value was. Due to the
>> nature of these timing side channels and the branch predictor on Intel
>> processors, this allows an attacker to leak data only accessible to
>> a privileged domain (like the kernel) back into an unprivileged domain.
>>
>> The goal is simple: avoid generating code which contains an indirect
>> branch that could have its prediction poisoned by an attacker. In many
>> cases, the compiler can simply use directed conditional branches and
>> a small search tree. LLVM already has support for lowering switches in
>> this way and the first step of this patch is to disable jump-table
>> lowering of switches and introduce a pass to rewrite explicit indirectbr
>> sequences into a switch over integers.
>>
>> However, there is no fully general alternative to indirect calls. We
>> introduce a new construct we call a "retpoline" to implement indirect
>> calls in a non-speculatable way. It can be thought of loosely as
>> a trampoline for indirect calls which uses the RET instruction on x86.
>> Further, we arrange for a specific call->ret sequence which ensures the
>> processor predicts the return to go to a controlled, known location. The
>> retpoline then "smashes" the return address pushed onto the stack by the
>> call with the desired target of the original indirect call. The result
>> is a predicted return to the next instruction after a call (which can be
>> used to trap speculative execution within an infinite loop) and an
>> actual indirect branch to an arbitrary address.
>>
>> On 64-bit x86 ABIs, this is especially easily done in the compiler by
>> using a guaranteed scratch register to pass the target into this device.
>> For 32-bit ABIs there isn't a guaranteed scratch register and so several
>> different retpoline variants are introduced to use a scratch register if
>> one is available in the calling convention and to otherwise use direct
>> stack push/pop sequences to pass the target address.
>>
>> This "retpoline" mitigation is fully described in the following blog
>> post: https://support.google.com/faqs/answer/7625886
>>
>> We also support a target feature that disables emission of the retpoline
>> thunk by the compiler to allow for custom thunks if users want them.
>> These are particularly useful in environments like kernels that
>> routinely do hot-patching on boot and want to hot-patch their thunk to
>> different code sequences. They can write this custom thunk and use
>> `-mretpoline-external-thunk` *in addition* to `-mretpoline`. In this
>> case, on x86-64 thu thunk names must be:
>> ```
>>   

[PATCH] D42819: [analyzer] [tests] [NFC] Remove dead code from CmpRuns

2018-02-01 Thread George Karpenkov via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rC324027: [analyzer] [tests] [NFC] Remove dead code from 
CmpRuns (authored by george.karpenkov, committed by ).
Herald added a subscriber: cfe-commits.

Repository:
  rC Clang

https://reviews.llvm.org/D42819

Files:
  utils/analyzer/CmpRuns.py


Index: utils/analyzer/CmpRuns.py
===
--- utils/analyzer/CmpRuns.py
+++ utils/analyzer/CmpRuns.py
@@ -203,10 +203,8 @@
 compareResults - Generate a relation from diagnostics in run A to
 diagnostics in run B.
 
-The result is the relation as a list of triples (a, b, confidence) where
-each element {a,b} is None or an element from the respective run, and
-confidence is a measure of the match quality (where 0 indicates equality,
-and None is used if either element is None).
+The result is the relation as a list of triples (a, b) where
+each element {a,b} is None or a matching element from the respective run
 """
 
 res = []
@@ -236,7 +234,7 @@
 path_difference_data.append(
 a.getPathLength() - b.getPathLength())
 
-res.append((a, b, 0))
+res.append((a, b))
 elif a.getIssueIdentifier() > b.getIssueIdentifier():
 eltsB.append(b)
 neqA.append(a)
@@ -253,9 +251,9 @@
 # in any way on the diagnostic format.
 
 for a in neqA:
-res.append((a, None, None))
+res.append((a, None))
 for b in neqB:
-res.append((None, b, None))
+res.append((None, b))
 
 if opts.relative_log_path_histogram or opts.relative_path_histogram or \
 opts.absolute_path_histogram:
@@ -281,9 +279,8 @@
 foundDiffs = 0
 totalAdded = 0
 totalRemoved = 0
-totalChanged = 0
 for res in diff:
-a, b, confidence = res
+a, b = res
 if a is None:
 print "ADDED: %r" % b.getReadableName()
 foundDiffs += 1
@@ -298,26 +295,14 @@
 if auxLog:
 print >>auxLog, ("('REMOVED', %r, %r)" % (a.getReadableName(),
   a.getReport()))
-elif confidence:
-print "CHANGED: %r to %r" % (a.getReadableName(),
- b.getReadableName())
-foundDiffs += 1
-totalChanged += 1
-if auxLog:
-print >>auxLog, ("('CHANGED', %r, %r, %r, %r)"
- % (a.getReadableName(),
-b.getReadableName(),
-a.getReport(),
-b.getReport()))
 else:
 pass
 
 TotalReports = len(resultsB.diagnostics)
 print "TOTAL REPORTS: %r" % TotalReports
 print "TOTAL DIFFERENCES: %r" % foundDiffs
 print "TOTAL ADDED: %r" % totalAdded
 print "TOTAL REMOVED: %r" % totalRemoved
-print "TOTAL CHANGED: %r" % totalChanged
 if auxLog:
 print >>auxLog, "('TOTAL NEW REPORTS', %r)" % TotalReports
 print >>auxLog, "('TOTAL DIFFERENCES', %r)" % foundDiffs


Index: utils/analyzer/CmpRuns.py
===
--- utils/analyzer/CmpRuns.py
+++ utils/analyzer/CmpRuns.py
@@ -203,10 +203,8 @@
 compareResults - Generate a relation from diagnostics in run A to
 diagnostics in run B.
 
-The result is the relation as a list of triples (a, b, confidence) where
-each element {a,b} is None or an element from the respective run, and
-confidence is a measure of the match quality (where 0 indicates equality,
-and None is used if either element is None).
+The result is the relation as a list of triples (a, b) where
+each element {a,b} is None or a matching element from the respective run
 """
 
 res = []
@@ -236,7 +234,7 @@
 path_difference_data.append(
 a.getPathLength() - b.getPathLength())
 
-res.append((a, b, 0))
+res.append((a, b))
 elif a.getIssueIdentifier() > b.getIssueIdentifier():
 eltsB.append(b)
 neqA.append(a)
@@ -253,9 +251,9 @@
 # in any way on the diagnostic format.
 
 for a in neqA:
-res.append((a, None, None))
+res.append((a, None))
 for b in neqB:
-res.append((None, b, None))
+res.append((None, b))
 
 if opts.relative_log_path_histogram or opts.relative_path_histogram or \
 opts.absolute_path_histogram:
@@ -281,9 +279,8 @@
 foundDiffs = 0
 totalAdded = 0
 totalRemoved = 0
-totalChanged = 0
 for res in diff:
-a, b, confidence = res
+a, b = res
 if a is None:
 print "ADDED: %r" % b.getReadableName()
 foundDiffs += 1
@@ -298,26 +295,14 @@
 if auxLog:
 print 

r324027 - [analyzer] [tests] [NFC] Remove dead code from CmpRuns

2018-02-01 Thread George Karpenkov via cfe-commits
Author: george.karpenkov
Date: Thu Feb  1 14:40:01 2018
New Revision: 324027

URL: http://llvm.org/viewvc/llvm-project?rev=324027=rev
Log:
[analyzer] [tests] [NFC] Remove dead code from CmpRuns

Indeed, "CHANGE" is not a thing yet, and we should probably not carry
around dead code which does not do anything apart from confusing the
reader.

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

Modified:
cfe/trunk/utils/analyzer/CmpRuns.py

Modified: cfe/trunk/utils/analyzer/CmpRuns.py
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/utils/analyzer/CmpRuns.py?rev=324027=324026=324027=diff
==
--- cfe/trunk/utils/analyzer/CmpRuns.py (original)
+++ cfe/trunk/utils/analyzer/CmpRuns.py Thu Feb  1 14:40:01 2018
@@ -203,10 +203,8 @@ def compareResults(A, B, opts):
 compareResults - Generate a relation from diagnostics in run A to
 diagnostics in run B.
 
-The result is the relation as a list of triples (a, b, confidence) where
-each element {a,b} is None or an element from the respective run, and
-confidence is a measure of the match quality (where 0 indicates equality,
-and None is used if either element is None).
+The result is the relation as a list of triples (a, b) where
+each element {a,b} is None or a matching element from the respective run
 """
 
 res = []
@@ -236,7 +234,7 @@ def compareResults(A, B, opts):
 path_difference_data.append(
 a.getPathLength() - b.getPathLength())
 
-res.append((a, b, 0))
+res.append((a, b))
 elif a.getIssueIdentifier() > b.getIssueIdentifier():
 eltsB.append(b)
 neqA.append(a)
@@ -253,9 +251,9 @@ def compareResults(A, B, opts):
 # in any way on the diagnostic format.
 
 for a in neqA:
-res.append((a, None, None))
+res.append((a, None))
 for b in neqB:
-res.append((None, b, None))
+res.append((None, b))
 
 if opts.relative_log_path_histogram or opts.relative_path_histogram or \
 opts.absolute_path_histogram:
@@ -281,9 +279,8 @@ def dumpScanBuildResultsDiff(dirA, dirB,
 foundDiffs = 0
 totalAdded = 0
 totalRemoved = 0
-totalChanged = 0
 for res in diff:
-a, b, confidence = res
+a, b = res
 if a is None:
 print "ADDED: %r" % b.getReadableName()
 foundDiffs += 1
@@ -298,17 +295,6 @@ def dumpScanBuildResultsDiff(dirA, dirB,
 if auxLog:
 print >>auxLog, ("('REMOVED', %r, %r)" % (a.getReadableName(),
   a.getReport()))
-elif confidence:
-print "CHANGED: %r to %r" % (a.getReadableName(),
- b.getReadableName())
-foundDiffs += 1
-totalChanged += 1
-if auxLog:
-print >>auxLog, ("('CHANGED', %r, %r, %r, %r)"
- % (a.getReadableName(),
-b.getReadableName(),
-a.getReport(),
-b.getReport()))
 else:
 pass
 
@@ -317,7 +303,6 @@ def dumpScanBuildResultsDiff(dirA, dirB,
 print "TOTAL DIFFERENCES: %r" % foundDiffs
 print "TOTAL ADDED: %r" % totalAdded
 print "TOTAL REMOVED: %r" % totalRemoved
-print "TOTAL CHANGED: %r" % totalChanged
 if auxLog:
 print >>auxLog, "('TOTAL NEW REPORTS', %r)" % TotalReports
 print >>auxLog, "('TOTAL DIFFERENCES', %r)" % foundDiffs


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


[PATCH] D42672: [CFG] [analyzer] Heavier CFGConstructor elements.

2018-02-01 Thread Artem Dergachev via Phabricator via cfe-commits
NoQ added inline comments.



Comment at: lib/Analysis/CFG.cpp:3899
+  if (auto *CE = const_cast(NE->getConstructExpr()))
+CurrentConstructionContext = {/*Constructor=*/CE, /*Trigger=*/NE};
+

dcoughlin wrote:
> Is it possible that there is already a CurrentConstructionContext? Will this 
> overwrite it?
> 
> Can you write an assertion to make sure that this doesn't happen?
> 
> Generally I would expect a context to have a well-defined start and end. I 
> think we should be explicit about where we expect it to start and end so we 
> can find violations of our expectations.
Yes, for now it'd be overwritten every time we meet a new constructor (this 
wasn't the case in the first version of this revision). However, the additional 
check (which should be eventually replaced with an assertion, but is for now 
needed) that we're picking the right context in `CXXConstructExpr` visit, 
together with only visiting every constructor once during CFG construction 
during normal visits (because weird stuff like `CXXDefaultArgExpr` isn't yet 
supported), guarantees that we're not doing anything wrong.

I should have cleaned this up, but i don't want to invest attention into that 
because subsequent patches will clearly make things way more complex than that, 
whenever we start dealing with a multitude of construction contexts or with 
partially-constructed contexts.

So for now it's a trivial kinda-safe solution.

I should document that though, for sure.



Comment at: lib/Analysis/CFG.cpp:4388
+case Stmt::WhileStmtClass: {
+  const VarDecl *var = cast(stmt)->getConditionVariable();
+  if (var)

dcoughlin wrote:
> Please, let's try to avoid changes that are unrelated to the functionality 
> being added.
I decreased indent of this whole huge for() loop, so the blame is already 
screwed (but phabricator carefully hides that), so i think this is a valid part 
of the patch.



Comment at: lib/StaticAnalyzer/Core/ExprEngine.cpp:632
+
+void ExprEngine::ProcessConstructor(const CFGConstructor C,
+ExplodedNode *Pred) {

dcoughlin wrote:
> You don't seem to be using the constructor context for anything other than 
> getting the CXXConstructExpr. Will a later patch require having a 
> CFGConstructor here?
> 
> This seems like unnecessarily duplicated code. Can we just change ProcessStmt 
> to take a `Stmt *` rather than a CFGStmt and use it for all statements 
> including constructors?
> 
Hmm, well, yeah, i guess, there isn't much value in passing the `CFGElement` 
around as long as we can find the current `CFGElement` any time we want in 
`ExprEngine->currBldrCtx`.

But if not for that, it was the whole point to have the construction context 
there. Will fix.


https://reviews.llvm.org/D42672



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


[PATCH] D42672: [CFG] [analyzer] Heavier CFGConstructor elements.

2018-02-01 Thread Artem Dergachev via Phabricator via cfe-commits
NoQ updated this revision to Diff 132476.
NoQ marked 5 inline comments as done.
NoQ added a comment.

Address comments. Most importantly, separate out sema and analyzer CFG tests.


https://reviews.llvm.org/D42672

Files:
  include/clang/Analysis/AnalysisDeclContext.h
  include/clang/Analysis/CFG.h
  include/clang/StaticAnalyzer/Core/AnalyzerOptions.h
  include/clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h
  lib/Analysis/AnalysisDeclContext.cpp
  lib/Analysis/CFG.cpp
  lib/Analysis/LiveVariables.cpp
  lib/StaticAnalyzer/Core/AnalysisManager.cpp
  lib/StaticAnalyzer/Core/AnalyzerOptions.cpp
  lib/StaticAnalyzer/Core/CoreEngine.cpp
  lib/StaticAnalyzer/Core/ExprEngine.cpp
  lib/StaticAnalyzer/Core/ExprEngineCXX.cpp
  lib/StaticAnalyzer/Core/PathDiagnostic.cpp
  test/Analysis/analyzer-config.c
  test/Analysis/analyzer-config.cpp
  test/Analysis/cfg.cpp

Index: test/Analysis/cfg.cpp
===
--- test/Analysis/cfg.cpp
+++ test/Analysis/cfg.cpp
@@ -1,5 +1,12 @@
-// RUN: %clang_analyze_cc1 -analyzer-checker=debug.DumpCFG -triple x86_64-apple-darwin12 -analyzer-config cfg-temporary-dtors=true -std=c++11 %s > %t 2>&1
-// RUN: FileCheck --input-file=%t %s
+// RUN: %clang_analyze_cc1 -analyzer-checker=debug.DumpCFG -triple x86_64-apple-darwin12 -analyzer-config cfg-temporary-dtors=true -std=c++11 -analyzer-config cfg-rich-constructors=false %s > %t 2>&1
+// RUN: FileCheck --input-file=%t -check-prefixes=CHECK,WARNINGS %s
+// RUN: %clang_analyze_cc1 -analyzer-checker=debug.DumpCFG -triple x86_64-apple-darwin12 -analyzer-config cfg-temporary-dtors=true -std=c++11 -analyzer-config cfg-rich-constructors=true %s > %t 2>&1
+// RUN: FileCheck --input-file=%t -check-prefixes=CHECK,ANALYZER %s
+
+// This file tests how we construct two different flavors of the Clang CFG -
+// the CFG used by the Sema analysis-based warnings and the CFG used by the
+// static analyzer. The difference in the behavior is checked via FileCheck
+// prefixes (WARNINGS and ANALYZER respectively).
 
 // CHECK-LABEL: void checkWrap(int i)
 // CHECK: ENTRY
@@ -116,7 +123,8 @@
 // CHECK-NEXT:   Succs (1): B1
 // CHECK: [B1]
 // CHECK-NEXT:   1:  CFGNewAllocator(A *)
-// CHECK-NEXT:   2:  (CXXConstructExpr, class A)
+// WARNINGS-NEXT:   2:  (CXXConstructExpr, class A)
+// ANALYZER-NEXT:   2:  (CXXConstructExpr, [B1.3], class A)
 // CHECK-NEXT:   3: new A([B1.2])
 // CHECK-NEXT:   4: A *a = new A();
 // CHECK-NEXT:   5: a
@@ -138,7 +146,8 @@
 // CHECK: [B1]
 // CHECK-NEXT:   1: 5
 // CHECK-NEXT:   2: CFGNewAllocator(A *)
-// CHECK-NEXT:   3:  (CXXConstructExpr, class A [5])
+// WARNINGS-NEXT:   3:  (CXXConstructExpr, class A [5])
+// ANALYZER-NEXT:   3:  (CXXConstructExpr, [B1.4], class A [5])
 // CHECK-NEXT:   4: new A {{\[\[}}B1.1]]
 // CHECK-NEXT:   5: A *a = new A [5];
 // CHECK-NEXT:   6: a
@@ -331,7 +340,8 @@
 // CHECK-NEXT:  3: [B1.2] (ImplicitCastExpr, ArrayToPointerDecay, int *)
 // CHECK-NEXT:  4: [B1.3] (ImplicitCastExpr, BitCast, void *)
 // CHECK-NEXT:  5: CFGNewAllocator(MyClass *)
-// CHECK-NEXT:  6:  (CXXConstructExpr, class MyClass)
+// WARNINGS-NEXT:  6:  (CXXConstructExpr, class MyClass)
+// ANALYZER-NEXT:  6:  (CXXConstructExpr, [B1.7], class MyClass)
 // CHECK-NEXT:  7: new ([B1.4]) MyClass([B1.6])
 // CHECK-NEXT:  8: MyClass *obj = new (buffer) MyClass();
 // CHECK-NEXT:  Preds (1): B2
@@ -363,7 +373,8 @@
 // CHECK-NEXT:  4: [B1.3] (ImplicitCastExpr, BitCast, void *)
 // CHECK-NEXT:  5: 5
 // CHECK-NEXT:  6: CFGNewAllocator(MyClass *)
-// CHECK-NEXT:  7:  (CXXConstructExpr, class MyClass [5])
+// WARNINGS-NEXT:  7:  (CXXConstructExpr, class MyClass [5])
+// ANALYZER-NEXT:  7:  (CXXConstructExpr, [B1.8], class MyClass [5])
 // CHECK-NEXT:  8: new ([B1.4]) MyClass {{\[\[}}B1.5]]
 // CHECK-NEXT:  9: MyClass *obj = new (buffer) MyClass [5];
 // CHECK-NEXT:  Preds (1): B2
Index: test/Analysis/analyzer-config.cpp
===
--- test/Analysis/analyzer-config.cpp
+++ test/Analysis/analyzer-config.cpp
@@ -26,6 +26,7 @@
 // CHECK-NEXT: cfg-implicit-dtors = true
 // CHECK-NEXT: cfg-lifetime = false
 // CHECK-NEXT: cfg-loopexit = false
+// CHECK-NEXT: cfg-rich-constructors = true
 // CHECK-NEXT: cfg-temporary-dtors = false
 // CHECK-NEXT: faux-bodies = true
 // CHECK-NEXT: graph-trim-interval = 1000
@@ -42,4 +43,4 @@
 // CHECK-NEXT: unroll-loops = false
 // CHECK-NEXT: widen-loops = false
 // CHECK-NEXT: [stats]
-// CHECK-NEXT: num-entries = 24
+// CHECK-NEXT: num-entries = 25
Index: test/Analysis/analyzer-config.c
===
--- test/Analysis/analyzer-config.c
+++ test/Analysis/analyzer-config.c
@@ -15,6 +15,7 @@
 // CHECK-NEXT: cfg-implicit-dtors = true
 // CHECK-NEXT: cfg-lifetime = false
 // CHECK-NEXT: cfg-loopexit = false
+// CHECK-NEXT: cfg-rich-constructors = true
 // CHECK-NEXT: cfg-temporary-dtors = false
 // CHECK-NEXT: faux-bodies = true
 // CHECK-NEXT: 

[PATCH] D41746: Make std::get_temporary_buffer respect overaligned types when possible

2018-02-01 Thread Richard Smith - zygoloid via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rCXX324020: Make std::get_temporary_buffer respect overaligned 
types when possible (authored by rsmith, committed by ).

Repository:
  rCXX libc++

https://reviews.llvm.org/D41746

Files:
  include/memory
  test/std/utilities/memory/temporary.buffer/overaligned.pass.cpp

Index: include/memory
===
--- include/memory
+++ include/memory
@@ -2004,7 +2004,38 @@
 __n = __m;
 while (__n > 0)
 {
+#if !defined(_LIBCPP_HAS_NO_ALIGNED_ALLOCATION)
+#if defined(__STDCPP_DEFAULT_NEW_ALIGNMENT__)
+if (std::alignment_of<_Tp>::value > __STDCPP_DEFAULT_NEW_ALIGNMENT__)
+#else
+if (std::alignment_of<_Tp>::value >
+std::alignment_of::value)
+#endif
+{
+std::align_val_t __al =
+std::align_val_t(std::alignment_of<_Tp>::value);
+__r.first = static_cast<_Tp*>(::operator new(
+__n * sizeof(_Tp), __al, nothrow));
+} else {
+__r.first = static_cast<_Tp*>(::operator new(
+__n * sizeof(_Tp), nothrow));
+}
+#else
+#if defined(__STDCPP_DEFAULT_NEW_ALIGNMENT__)
+if (std::alignment_of<_Tp>::value > __STDCPP_DEFAULT_NEW_ALIGNMENT__)
+#else
+if (std::alignment_of<_Tp>::value >
+std::alignment_of::value)
+#endif
+{
+// Since aligned operator new is unavailable, return an empty
+// buffer rather than one with invalid alignment.
+return __r;
+}
+
 __r.first = static_cast<_Tp*>(::operator new(__n * sizeof(_Tp), nothrow));
+#endif
+
 if (__r.first)
 {
 __r.second = __n;
@@ -2017,7 +2048,23 @@
 
 template 
 inline _LIBCPP_INLINE_VISIBILITY
-void return_temporary_buffer(_Tp* __p) _NOEXCEPT {::operator delete(__p);}
+void return_temporary_buffer(_Tp* __p) _NOEXCEPT
+{
+#if !defined(_LIBCPP_HAS_NO_ALIGNED_ALLOCATION)
+#if defined(__STDCPP_DEFAULT_NEW_ALIGNMENT__)
+if (std::alignment_of<_Tp>::value > __STDCPP_DEFAULT_NEW_ALIGNMENT__)
+#else
+if (std::alignment_of<_Tp>::value >
+std::alignment_of::value)
+#endif
+{
+std::align_val_t __al = std::align_val_t(std::alignment_of<_Tp>::value);
+::operator delete(__p, __al);
+return;
+}
+#endif
+::operator delete(__p);
+}
 
 #if _LIBCPP_STD_VER <= 14 || defined(_LIBCPP_ENABLE_CXX17_REMOVED_AUTO_PTR)
 template 
Index: test/std/utilities/memory/temporary.buffer/overaligned.pass.cpp
===
--- test/std/utilities/memory/temporary.buffer/overaligned.pass.cpp
+++ test/std/utilities/memory/temporary.buffer/overaligned.pass.cpp
@@ -0,0 +1,33 @@
+//===--===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is dual licensed under the MIT and the University of Illinois Open
+// Source Licenses. See LICENSE.TXT for details.
+//
+//===--===//
+
+// 
+
+// template 
+//   pair
+//   get_temporary_buffer(ptrdiff_t n);
+//
+// template 
+//   void
+//   return_temporary_buffer(T* p);
+
+#include 
+#include 
+
+struct alignas(32) A {
+int field;
+};
+
+int main()
+{
+std::pair ip = std::get_temporary_buffer(5);
+assert(!(ip.first == nullptr) ^ (ip.second == 0));
+assert(reinterpret_cast(ip.first) % alignof(A) == 0);
+std::return_temporary_buffer(ip.first);
+}
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


r324021 - [analyzer] [tests] Add an option to show the histogram of path differences between the analyzer runs

2018-02-01 Thread George Karpenkov via cfe-commits
Author: george.karpenkov
Date: Thu Feb  1 14:25:18 2018
New Revision: 324021

URL: http://llvm.org/viewvc/llvm-project?rev=324021=rev
Log:
[analyzer] [tests] Add an option to show the histogram of path differences 
between the analyzer runs

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

Modified:
cfe/trunk/utils/analyzer/CmpRuns.py

Modified: cfe/trunk/utils/analyzer/CmpRuns.py
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/utils/analyzer/CmpRuns.py?rev=324021=324020=324021=diff
==
--- cfe/trunk/utils/analyzer/CmpRuns.py (original)
+++ cfe/trunk/utils/analyzer/CmpRuns.py Thu Feb  1 14:25:18 2018
@@ -28,6 +28,7 @@ Usage:
 
 import os
 import plistlib
+from math import log
 
 
 # Information about analysis run:
@@ -47,6 +48,7 @@ class AnalysisDiagnostic:
 self._loc = self._data['location']
 self._report = report
 self._htmlReport = htmlReport
+self._reportSize = len(self._data['path'])
 
 def getFileName(self):
 root = self._report.run.root
@@ -61,6 +63,9 @@ class AnalysisDiagnostic:
 def getColumn(self):
 return self._loc['col']
 
+def getPathLength(self):
+return self._reportSize
+
 def getCategory(self):
 return self._data['category']
 
@@ -193,7 +198,7 @@ def cmpAnalysisDiagnostic(d):
 return d.getIssueIdentifier()
 
 
-def compareResults(A, B):
+def compareResults(A, B, opts):
 """
 compareResults - Generate a relation from diagnostics in run A to
 diagnostics in run B.
@@ -206,6 +211,9 @@ def compareResults(A, B):
 
 res = []
 
+# Map size_before -> size_after
+path_difference_data = []
+
 # Quickly eliminate equal elements.
 neqA = []
 neqB = []
@@ -217,6 +225,17 @@ def compareResults(A, B):
 a = eltsA.pop()
 b = eltsB.pop()
 if (a.getIssueIdentifier() == b.getIssueIdentifier()):
+if a.getPathLength() != b.getPathLength():
+if opts.relative_path_histogram:
+path_difference_data.append(
+float(a.getPathLength()) / b.getPathLength())
+elif opts.relative_log_path_histogram:
+path_difference_data.append(
+log(float(a.getPathLength()) / b.getPathLength()))
+elif opts.absolute_path_histogram:
+path_difference_data.append(
+a.getPathLength() - b.getPathLength())
+
 res.append((a, b, 0))
 elif a.getIssueIdentifier() > b.getIssueIdentifier():
 eltsB.append(b)
@@ -238,6 +257,12 @@ def compareResults(A, B):
 for b in neqB:
 res.append((None, b, None))
 
+if opts.relative_log_path_histogram or opts.relative_path_histogram or \
+opts.absolute_path_histogram:
+from matplotlib import pyplot
+pyplot.hist(path_difference_data, bins=100)
+pyplot.show()
+
 return res
 
 
@@ -252,7 +277,7 @@ def dumpScanBuildResultsDiff(dirA, dirB,
 else:
 auxLog = None
 
-diff = compareResults(resultsA, resultsB)
+diff = compareResults(resultsA, resultsB, opts)
 foundDiffs = 0
 totalAdded = 0
 totalRemoved = 0
@@ -314,6 +339,21 @@ def main():
   [default=None]",
   action="store", type=str, default=None,
   metavar="LOG")
+parser.add_option("--relative-path-differences-histogram",
+  action="store_true", dest="relative_path_histogram",
+  default=False,
+  help="Show histogram of relative paths differences. \
+  Requires matplotlib")
+parser.add_option("--relative-log-path-differences-histogram",
+  action="store_true", dest="relative_log_path_histogram",
+  default=False,
+  help="Show histogram of log relative paths differences. \
+  Requires matplotlib")
+parser.add_option("--absolute-path-differences-histogram",
+  action="store_true", dest="absolute_path_histogram",
+  default=False,
+  help="Show histogram of absolute paths differences. \
+  Requires matplotlib")
 (opts, args) = parser.parse_args()
 
 if len(args) != 2:


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


[PATCH] D42457: [analyzer] Don't communicate evaluation failures through memregion hierarchy.

2018-02-01 Thread Phabricator via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rL324018: [analyzer] Dont communicate evaluation 
failures through memregion hierarchy. (authored by dergachev, committed by ).
Herald added a subscriber: llvm-commits.

Changed prior to commit:
  https://reviews.llvm.org/D42457?vs=132450=132473#toc

Repository:
  rL LLVM

https://reviews.llvm.org/D42457

Files:
  cfe/trunk/include/clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h
  cfe/trunk/lib/StaticAnalyzer/Core/ExprEngineCXX.cpp
  cfe/trunk/lib/StaticAnalyzer/Core/ExprEngineCallAndReturn.cpp
  cfe/trunk/test/Analysis/new.cpp

Index: cfe/trunk/include/clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h
===
--- cfe/trunk/include/clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h
+++ cfe/trunk/include/clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h
@@ -567,14 +567,23 @@
   const LocationContext *LCtx,
   ProgramStateRef State);
 
+  struct EvalCallOptions {
+bool IsConstructorWithImproperlyModeledTargetRegion = false;
+bool IsArrayConstructorOrDestructor = false;
+
+EvalCallOptions() {}
+  };
+
   /// Evaluate a call, running pre- and post-call checks and allowing checkers
   /// to be responsible for handling the evaluation of the call itself.
   void evalCall(ExplodedNodeSet , ExplodedNode *Pred,
 const CallEvent );
 
   /// \brief Default implementation of call evaluation.
   void defaultEvalCall(NodeBuilder , ExplodedNode *Pred,
-   const CallEvent );
+   const CallEvent ,
+   const EvalCallOptions  = {});
+
 private:
   void evalLoadCommon(ExplodedNodeSet ,
   const Expr *NodeEx,  /* Eventually will be a CFGStmt */
@@ -598,9 +607,23 @@
   void examineStackFrames(const Decl *D, const LocationContext *LCtx,
   bool , unsigned );
 
+  enum CallInlinePolicy {
+CIP_Allowed,
+CIP_DisallowedOnce,
+CIP_DisallowedAlways
+  };
+
+  /// \brief See if a particular call should be inlined, by only looking
+  /// at the call event and the current state of analysis.
+  CallInlinePolicy mayInlineCallKind(const CallEvent ,
+ const ExplodedNode *Pred,
+ AnalyzerOptions ,
+ const EvalCallOptions );
+
   /// Checks our policies and decides weither the given call should be inlined.
   bool shouldInlineCall(const CallEvent , const Decl *D,
-const ExplodedNode *Pred);
+const ExplodedNode *Pred,
+const EvalCallOptions  = {});
 
   bool inlineCall(const CallEvent , const Decl *D, NodeBuilder ,
   ExplodedNode *Pred, ProgramStateRef State);
@@ -650,11 +673,11 @@
 
   /// For a given constructor, look forward in the current CFG block to
   /// determine the region into which an object will be constructed by \p CE.
-  /// Returns either a field or local variable region if the object will be
-  /// directly constructed in an existing region or a temporary object region
-  /// if not.
+  /// When the lookahead fails, a temporary region is returned, and the
+  /// IsConstructorWithImproperlyModeledTargetRegion flag is set in \p CallOpts.
   const MemRegion *getRegionForConstructedObject(const CXXConstructExpr *CE,
- ExplodedNode *Pred);
+ ExplodedNode *Pred,
+ EvalCallOptions );
 
   /// Store the region returned by operator new() so that the constructor
   /// that follows it knew what location to initialize. The value should be
Index: cfe/trunk/test/Analysis/new.cpp
===
--- cfe/trunk/test/Analysis/new.cpp
+++ cfe/trunk/test/Analysis/new.cpp
@@ -311,8 +311,7 @@
 void testArrayDestr() {
   NoReturnDtor *p = new NoReturnDtor[2];
   delete[] p; // Calls the base destructor which aborts, checked below
-  //TODO: clang_analyzer_eval should not be called
-  clang_analyzer_eval(true); // expected-warning{{TRUE}}
+  clang_analyzer_eval(true); // no-warning
 }
 
 // Invalidate Region even in case of default destructor
Index: cfe/trunk/lib/StaticAnalyzer/Core/ExprEngineCXX.cpp
===
--- cfe/trunk/lib/StaticAnalyzer/Core/ExprEngineCXX.cpp
+++ cfe/trunk/lib/StaticAnalyzer/Core/ExprEngineCXX.cpp
@@ -85,28 +85,32 @@
 
 
 /// Returns a region representing the first element of a (possibly
-/// multi-dimensional) array.
+/// multi-dimensional) array, for the purposes of element construction or
+/// destruction.
 ///
 /// On return, \p Ty will be set to the base type of the array.
 ///
 /// If the type is not an array type 

r324018 - [analyzer] Don't communicate evaluation failures through memregion hierarchy.

2018-02-01 Thread Artem Dergachev via cfe-commits
Author: dergachev
Date: Thu Feb  1 14:17:05 2018
New Revision: 324018

URL: http://llvm.org/viewvc/llvm-project?rev=324018=rev
Log:
[analyzer] Don't communicate evaluation failures through memregion hierarchy.

We use CXXTempObjectRegion exclusively as a bailout value for construction
targets when we are unable to find the correct construction region.
Sometimes it works correctly, but rather accidentally than intentionally.

Now that we want to increase the amount of situations where it works correctly,
the first step is to introduce a different way of communicating our failure
to find the correct construction region. EvalCallOptions are introduced
for this purpose.

For now EvalCallOptions are communicating two kinds of problems:
- We have been completely unable to find the correct construction site.
- We have found the construction site correctly, and there's more than one of
  them (i.e. array construction which we currently don't support).

Accidentally find and fix a test in which the new approach to communicating
failures produces better results.

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

Modified:
cfe/trunk/include/clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h
cfe/trunk/lib/StaticAnalyzer/Core/ExprEngineCXX.cpp
cfe/trunk/lib/StaticAnalyzer/Core/ExprEngineCallAndReturn.cpp
cfe/trunk/test/Analysis/new.cpp

Modified: cfe/trunk/include/clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h?rev=324018=324017=324018=diff
==
--- cfe/trunk/include/clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h 
(original)
+++ cfe/trunk/include/clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h Thu 
Feb  1 14:17:05 2018
@@ -567,6 +567,13 @@ public:
   const LocationContext *LCtx,
   ProgramStateRef State);
 
+  struct EvalCallOptions {
+bool IsConstructorWithImproperlyModeledTargetRegion = false;
+bool IsArrayConstructorOrDestructor = false;
+
+EvalCallOptions() {}
+  };
+
   /// Evaluate a call, running pre- and post-call checks and allowing checkers
   /// to be responsible for handling the evaluation of the call itself.
   void evalCall(ExplodedNodeSet , ExplodedNode *Pred,
@@ -574,7 +581,9 @@ public:
 
   /// \brief Default implementation of call evaluation.
   void defaultEvalCall(NodeBuilder , ExplodedNode *Pred,
-   const CallEvent );
+   const CallEvent ,
+   const EvalCallOptions  = {});
+
 private:
   void evalLoadCommon(ExplodedNodeSet ,
   const Expr *NodeEx,  /* Eventually will be a CFGStmt */
@@ -598,9 +607,23 @@ private:
   void examineStackFrames(const Decl *D, const LocationContext *LCtx,
   bool , unsigned );
 
+  enum CallInlinePolicy {
+CIP_Allowed,
+CIP_DisallowedOnce,
+CIP_DisallowedAlways
+  };
+
+  /// \brief See if a particular call should be inlined, by only looking
+  /// at the call event and the current state of analysis.
+  CallInlinePolicy mayInlineCallKind(const CallEvent ,
+ const ExplodedNode *Pred,
+ AnalyzerOptions ,
+ const EvalCallOptions );
+
   /// Checks our policies and decides weither the given call should be inlined.
   bool shouldInlineCall(const CallEvent , const Decl *D,
-const ExplodedNode *Pred);
+const ExplodedNode *Pred,
+const EvalCallOptions  = {});
 
   bool inlineCall(const CallEvent , const Decl *D, NodeBuilder ,
   ExplodedNode *Pred, ProgramStateRef State);
@@ -650,11 +673,11 @@ private:
 
   /// For a given constructor, look forward in the current CFG block to
   /// determine the region into which an object will be constructed by \p CE.
-  /// Returns either a field or local variable region if the object will be
-  /// directly constructed in an existing region or a temporary object region
-  /// if not.
+  /// When the lookahead fails, a temporary region is returned, and the
+  /// IsConstructorWithImproperlyModeledTargetRegion flag is set in \p 
CallOpts.
   const MemRegion *getRegionForConstructedObject(const CXXConstructExpr *CE,
- ExplodedNode *Pred);
+ ExplodedNode *Pred,
+ EvalCallOptions );
 
   /// Store the region returned by operator new() so that the constructor
   /// that follows it knew what location to initialize. The value should be

Modified: cfe/trunk/lib/StaticAnalyzer/Core/ExprEngineCXX.cpp
URL: 

[PATCH] D42641: [MinGW] Emit typeinfo locally for dllimported classes without key functions

2018-02-01 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.

This is actually consistent with what Microsoft does for dllimport classes. 
They don't have key functions, but they do import vftables when a class is 
dllimport and the constructor is inline. They never import RTTI and always emit 
it locally.

In any case, yes, this organization makes the most sense to me. Presumably GCC 
also exports its vtables so that we can import them and they don't need to be 
emitted locally, but we do need to emit RTTI locally.


https://reviews.llvm.org/D42641



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


Re: [PATCH] D42758: Support `#pragma comment(lib, "name")` in the frontend for ELF

2018-02-01 Thread Rui Ueyama via cfe-commits
On Wed, Jan 31, 2018 at 7:23 PM, Paul Robinson via Phabricator <
revi...@reviews.llvm.org> wrote:

> probinson added a comment.
>
> In https://reviews.llvm.org/D42758#993936, @ruiu wrote:
>
> > > I also wonder which is better `#pragma comment(lib, "m")` or `#pragma
> comment(lib, "m")`.
> >
> > Sorry, I meant `#pragma comment(lib, "m")` or `#pragma comment("lib",
> "m")`.
>
>
> I can't swear to it but I don't think Microsoft invented `#pragma
> comment`.  Various IBM compilers have it, with a syntax of `#pragma comment
> (  [ , "string" ] )`.  I'm not seeing a `lib` keyword specifically
> in the IBM docs, but being a keyword would be consistent with past practice.
>

Thank you for the info. If it's a common practice, I don't see a reason to
change that.

>
> 
> Comment at: lib/Parse/ParsePragma.cpp:299
> +  getTargetInfo().getTriple().isOSBinFormatELF()) {
>  MSCommentHandler.reset(new PragmaCommentHandler(Actions));
>  PP.AddPragmaHandler(MSCommentHandler.get());
> 
> PS4's binary format is ELF, so you should be able to remove the isPS4
> predicate.
>
>
> 
> Comment at: lib/Parse/ParsePragma.cpp:382
> +  getTargetInfo().getTriple().isOSBinFormatELF()) {
>  PP.RemovePragmaHandler(MSCommentHandler.get());
>  MSCommentHandler.reset();
> 
> Don't need isPS4, as it uses ELF.
>
>
> Repository:
>   rC Clang
>
> https://reviews.llvm.org/D42758
>
>
>
>
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D42813: [Debug] Annotate compiler generated range-for loop variables.

2018-02-01 Thread Matt Davis via Phabricator via cfe-commits
mattd updated this revision to Diff 132464.
mattd added a comment.

Updating the diff, missed a few deltas that should have been in the original 
patch.


https://reviews.llvm.org/D42813

Files:
  include/clang/Sema/Scope.h
  lib/Sema/SemaStmt.cpp
  test/CodeGenCXX/debug-for-range-scope-hints.cpp
  test/CodeGenCXX/debug-info-scope.cpp
  test/CodeGenCXX/vla.cpp

Index: test/CodeGenCXX/vla.cpp
===
--- test/CodeGenCXX/vla.cpp
+++ test/CodeGenCXX/vla.cpp
@@ -68,8 +68,8 @@
 void test2(int b) {
   // CHECK-LABEL: define void {{.*}}test2{{.*}}(i32 %b)
   int varr[b];
-  // AMD: %__end = alloca i32*, align 8, addrspace(5)
-  // AMD: [[END:%.*]] = addrspacecast i32* addrspace(5)* %__end to i32**
+  // AMD: %__end1 = alloca i32*, align 8, addrspace(5)
+  // AMD: [[END:%.*]] = addrspacecast i32* addrspace(5)* %__end1 to i32**
   // get the address of %b by checking the first store that stores it 
   //CHECK: store i32 %b, i32* [[PTR_B:%.*]]
 
@@ -86,7 +86,7 @@
   //CHECK: [[VLA_SIZEOF:%.*]] = mul nuw i64 4, [[VLA_NUM_ELEMENTS_PRE]]
   //CHECK-NEXT: [[VLA_NUM_ELEMENTS_POST:%.*]] = udiv i64 [[VLA_SIZEOF]], 4
   //CHECK-NEXT: [[VLA_END_PTR:%.*]] = getelementptr inbounds i32, i32* {{%.*}}, i64 [[VLA_NUM_ELEMENTS_POST]]
-  //X64-NEXT: store i32* [[VLA_END_PTR]], i32** %__end
+  //X64-NEXT: store i32* [[VLA_END_PTR]], i32** %__end1
   //AMD-NEXT: store i32* [[VLA_END_PTR]], i32** [[END]]
   for (int d : varr) 0;
 }
@@ -94,8 +94,8 @@
 void test3(int b, int c) {
   // CHECK-LABEL: define void {{.*}}test3{{.*}}(i32 %b, i32 %c)
   int varr[b][c];
-  // AMD: %__end = alloca i32*, align 8, addrspace(5)
-  // AMD: [[END:%.*]] = addrspacecast i32* addrspace(5)* %__end to i32**
+  // AMD: %__end1 = alloca i32*, align 8, addrspace(5)
+  // AMD: [[END:%.*]] = addrspacecast i32* addrspace(5)* %__end1 to i32**
   // get the address of %b by checking the first store that stores it 
   //CHECK: store i32 %b, i32* [[PTR_B:%.*]]
   //CHECK-NEXT: store i32 %c, i32* [[PTR_C:%.*]]
Index: test/CodeGenCXX/debug-info-scope.cpp
===
--- test/CodeGenCXX/debug-info-scope.cpp
+++ test/CodeGenCXX/debug-info-scope.cpp
@@ -58,7 +58,7 @@
   }
 
   int x[] = {1, 2};
-  // CHECK: = !DILocalVariable(name: "__range"
+  // CHECK: = !DILocalVariable(name: "__range1"
   // CHECK-SAME:   scope: [[RANGE_FOR:![0-9]*]]
   // CHECK-NOT:line:
   // CHECK-SAME:   ){{$}}
Index: test/CodeGenCXX/debug-for-range-scope-hints.cpp
===
--- test/CodeGenCXX/debug-for-range-scope-hints.cpp
+++ test/CodeGenCXX/debug-for-range-scope-hints.cpp
@@ -0,0 +1,36 @@
+// RUN: %clang_cc1 -emit-llvm -debug-info-kind=limited %s -o - | FileCheck %s
+
+struct vec {
+  using itr = int*;
+  itr begin() { return nullptr; }
+  itr end() { return nullptr; }
+};
+
+void test() {
+  vec as, bs, cs;
+
+  for (auto a : as)
+for (auto b : bs)
+  for (auto c : cs) {
+  }
+}
+
+// CHECK: define void @_Z4testv()
+// CHECK: call void @llvm.dbg.declare(metadata %struct.vec** {{.*}}, metadata ![[RANGE1:[0-9]+]]
+// CHECK: call void @llvm.dbg.declare(metadata i32** {{.*}}, metadata ![[BEGIN1:[0-9]+]]
+// CHECK: call void @llvm.dbg.declare(metadata i32** {{.*}}, metadata ![[END1:[0-9]+]]
+// CHECK: call void @llvm.dbg.declare(metadata %struct.vec** {{.*}}, metadata ![[RANGE2:[0-9]+]]
+// CHECK: call void @llvm.dbg.declare(metadata i32** {{.*}}, metadata ![[BEGIN2:[0-9]+]]
+// CHECK: call void @llvm.dbg.declare(metadata i32** {{.*}}, metadata ![[END2:[0-9]+]]
+// CHECK: call void @llvm.dbg.declare(metadata %struct.vec** {{.*}}, metadata ![[RANGE3:[0-9]+]]
+// CHECK: call void @llvm.dbg.declare(metadata i32** {{.*}}, metadata ![[BEGIN3:[0-9]+]]
+// CHECK: call void @llvm.dbg.declare(metadata i32** {{.*}}, metadata ![[END3:[0-9]+]]
+// CHECK: ![[RANGE1]] = !DILocalVariable(name: "__range1", {{.*}}, flags: DIFlagArtificial)
+// CHECK: ![[BEGIN1]] = !DILocalVariable(name: "__begin1", {{.*}}, flags: DIFlagArtificial)
+// CHECK: ![[END1]] = !DILocalVariable(name: "__end1",  {{.*}}, flags: DIFlagArtificial)
+// CHECK: ![[RANGE2]] = !DILocalVariable(name: "__range2",  {{.*}}, flags: DIFlagArtificial)
+// CHECK: ![[BEGIN2]] = !DILocalVariable(name: "__begin2", {{.*}}, flags: DIFlagArtificial)
+// CHECK: ![[END2]] = !DILocalVariable(name: "__end2",  {{.*}}, flags: DIFlagArtificial)
+// CHECK: ![[RANGE3]] = !DILocalVariable(name: "__range3",  {{.*}}, flags: DIFlagArtificial)
+// CHECK: ![[BEGIN3]] = !DILocalVariable(name: "__begin3", {{.*}}, flags: DIFlagArtificial)
+// CHECK: ![[END3]] = !DILocalVariable(name: "__end3", {{.*}}, flags: DIFlagArtificial)
Index: lib/Sema/SemaStmt.cpp
===
--- lib/Sema/SemaStmt.cpp
+++ lib/Sema/SemaStmt.cpp
@@ -2025,7 +2025,7 @@
 
 /// Build a variable declaration for a for-range statement.

[PATCH] D42813: [Debug] Annotate compiler generated range-for loop variables.

2018-02-01 Thread Matt Davis via Phabricator via cfe-commits
mattd created this revision.
mattd added a reviewer: rsmith.
mattd edited the summary of this revision.

This change aims to simplify debugging by annotating the range-for loop 
artificial variables (range, begin, end) with the scope depth.


https://reviews.llvm.org/D42813

Files:
  SemaStmt.cpp


Index: SemaStmt.cpp
===
--- SemaStmt.cpp
+++ SemaStmt.cpp
@@ -2025,7 +2025,7 @@
 
 /// Build a variable declaration for a for-range statement.
 VarDecl *BuildForRangeVarDecl(Sema , SourceLocation Loc,
-  QualType Type, const char *Name) {
+  QualType Type, StringRef Name) {
   DeclContext *DC = SemaRef.CurContext;
   IdentifierInfo *II = ().get(Name);
   TypeSourceInfo *TInfo = SemaRef.Context.getTrivialTypeSourceInfo(Type, Loc);
@@ -2093,11 +2093,13 @@
   return StmtError();
   }
 
-  // Build  auto && __range = range-init
+  // Build  auto && __range = range-init.
+  // Assume the variables are nested in the inner scope (loop body).
+  const auto DepthStr = std::to_string(S->getDepth() >> 1);
   SourceLocation RangeLoc = Range->getLocStart();
   VarDecl *RangeVar = BuildForRangeVarDecl(*this, RangeLoc,
Context.getAutoRRefDeductType(),
-   "__range");
+   std::string("__range") + DepthStr);
   if (FinishForRangeVarDecl(*this, RangeVar, Range, RangeLoc,
 diag::err_for_range_deduction_failure)) {
 LoopVar->setInvalidDecl();
@@ -2340,10 +2342,12 @@
   return StmtError();
 
 // Build auto __begin = begin-expr, __end = end-expr.
+// Assume the variables are nested in the inner scope (loop body).
+const auto DepthStr = std::to_string(S->getDepth() >> 1);
 VarDecl *BeginVar = BuildForRangeVarDecl(*this, ColonLoc, AutoType,
- "__begin");
+ std::string("__begin") + 
DepthStr);
 VarDecl *EndVar = BuildForRangeVarDecl(*this, ColonLoc, AutoType,
-   "__end");
+   std::string("__end") + DepthStr);
 
 // Build begin-expr and end-expr and attach to __begin and __end variables.
 ExprResult BeginExpr, EndExpr;


Index: SemaStmt.cpp
===
--- SemaStmt.cpp
+++ SemaStmt.cpp
@@ -2025,7 +2025,7 @@
 
 /// Build a variable declaration for a for-range statement.
 VarDecl *BuildForRangeVarDecl(Sema , SourceLocation Loc,
-  QualType Type, const char *Name) {
+  QualType Type, StringRef Name) {
   DeclContext *DC = SemaRef.CurContext;
   IdentifierInfo *II = ().get(Name);
   TypeSourceInfo *TInfo = SemaRef.Context.getTrivialTypeSourceInfo(Type, Loc);
@@ -2093,11 +2093,13 @@
   return StmtError();
   }
 
-  // Build  auto && __range = range-init
+  // Build  auto && __range = range-init.
+  // Assume the variables are nested in the inner scope (loop body).
+  const auto DepthStr = std::to_string(S->getDepth() >> 1);
   SourceLocation RangeLoc = Range->getLocStart();
   VarDecl *RangeVar = BuildForRangeVarDecl(*this, RangeLoc,
Context.getAutoRRefDeductType(),
-   "__range");
+   std::string("__range") + DepthStr);
   if (FinishForRangeVarDecl(*this, RangeVar, Range, RangeLoc,
 diag::err_for_range_deduction_failure)) {
 LoopVar->setInvalidDecl();
@@ -2340,10 +2342,12 @@
   return StmtError();
 
 // Build auto __begin = begin-expr, __end = end-expr.
+// Assume the variables are nested in the inner scope (loop body).
+const auto DepthStr = std::to_string(S->getDepth() >> 1);
 VarDecl *BeginVar = BuildForRangeVarDecl(*this, ColonLoc, AutoType,
- "__begin");
+ std::string("__begin") + DepthStr);
 VarDecl *EndVar = BuildForRangeVarDecl(*this, ColonLoc, AutoType,
-   "__end");
+   std::string("__end") + DepthStr);
 
 // Build begin-expr and end-expr and attach to __begin and __end variables.
 ExprResult BeginExpr, EndExpr;
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D42776: [Sema] Fix an assertion failure in constant expression evaluation of calls to functions with default arguments

2018-02-01 Thread Erik Pilkington via Phabricator via cfe-commits
erik.pilkington added a comment.

Hi Akira, thanks for working on this!




Comment at: lib/AST/ExprConstant.cpp:1165-1173
+  auto LB = Temporaries.lower_bound(Key);
+
+  // If an element with key Key is found, reset the value and return it. This
+  // can happen if Key is part of a default argument expression.
+  if (LB != Temporaries.end() && LB->first == Key)
+return LB->second = APValue();
+

I think that the problem is more subtle than this. This static assert errors 
(previously clang would assert) when it really it should be fine.
```
constexpr const int (const int  = 0) { return p; }
static_assert(() != ());
```
Because default arguments are allocated on the caller side, both the calls to 
`x()` call createTemporary for the same MaterializeTemporaryExpr in the same 
CallStackFrame, when really that MTE should correspond to two distinct values. 
This patch just hides that underlying problem by recycling the value created 
during the first call during the second call.

Maybe we could have a fancier key that incorporates a node on the caller side, 
such as the CXXDefaultArgExpr as well at the MTE, and store that fancy key in 
APValue::LValueBases? That would allow us generate distinct values for these 
MTEs, and also remember what expression originated it. What do you think about 
that?

There is small discussion about this problem here: 
https://bugs.llvm.org/show_bug.cgi?id=33140


https://reviews.llvm.org/D42776



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


[PATCH] D42549: [CodeGen] Use the zero initializer instead of storing an all zero representation.

2018-02-01 Thread Matt Davis via Phabricator via cfe-commits
mattd added a comment.

Ping :)


https://reviews.llvm.org/D42549



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


[PATCH] D42645: New simple Checker for mmap calls

2018-02-01 Thread David CARLIER via Phabricator via cfe-commits
devnexen updated this revision to Diff 132459.

Repository:
  rC Clang

https://reviews.llvm.org/D42645

Files:
  include/clang/StaticAnalyzer/Checkers/Checkers.td
  lib/StaticAnalyzer/Checkers/CMakeLists.txt
  lib/StaticAnalyzer/Checkers/MmapWriteExecChecker.cpp

Index: lib/StaticAnalyzer/Checkers/MmapWriteExecChecker.cpp
===
--- lib/StaticAnalyzer/Checkers/MmapWriteExecChecker.cpp
+++ lib/StaticAnalyzer/Checkers/MmapWriteExecChecker.cpp
@@ -0,0 +1,78 @@
+// MmapWriteExecChecker.cpp - Check for the prot argument -===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===--===//
+//
+// This checker tests the 3rd argument of mmap's calls to check if
+// it is writable and executable in the same time. It's somehow
+// an optional checker since for example in JIT libraries it is pretty common.
+//
+//===--===//
+
+#include "ClangSACheckers.h"
+
+#include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
+#include "clang/StaticAnalyzer/Core/Checker.h"
+#include "clang/StaticAnalyzer/Core/CheckerManager.h"
+#include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h"
+#include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
+
+using namespace clang;
+using namespace ento;
+using llvm::APSInt;
+
+namespace {
+class MmapWriteExecChecker : public Checker {
+  CallDescription MmapFn;
+  static int ProtWrite;
+  static int ProtExec;
+  mutable std::unique_ptr BT;
+public:
+  MmapWriteExecChecker() : MmapFn("mmap") {}
+  void checkPreCall(const CallEvent , CheckerContext ) const;
+};
+}
+
+int MmapWriteExecChecker::ProtWrite = 0x02;
+int MmapWriteExecChecker::ProtExec  = 0x04;
+
+void MmapWriteExecChecker::checkPreCall(const CallEvent ,
+ CheckerContext ) const {
+  if (Call.isCalled(MmapFn)) {
+if (Call.getNumArgs() < 3)
+  return;
+
+llvm::Triple Triple = C.getASTContext().getTargetInfo().getTriple();
+
+if (Triple.isOSGlibc())
+  ProtExec = 0x01;
+
+SVal ProtVal = Call.getArgSVal(2); 
+Optional ProtLoc = ProtVal.getAs();
+int64_t Prot = ProtLoc->getValue().getSExtValue();
+
+if ((Prot & (ProtWrite | ProtExec)) == (ProtWrite | ProtExec)) {
+  if (!BT)
+BT.reset(new BugType(this, "W^X check fails", "Write Exec prot flags set"));
+
+  ExplodedNode *N = C.generateNonFatalErrorNode();
+  if (!N)
+return;
+
+  auto Report = llvm::make_unique(
+  *BT, "Both PROT_WRITE and PROT_EXEC flags had been set. It can "
+   "leads to exploitable memory regions, overwritten with malicious code"
+ , N);
+  Report->addRange(Call.getArgSourceRange(2));
+  C.emitReport(std::move(Report));
+}
+  }
+}
+
+void ento::registerMmapWriteExecChecker(CheckerManager ) {
+  mgr.registerChecker();
+}
Index: lib/StaticAnalyzer/Checkers/CMakeLists.txt
===
--- lib/StaticAnalyzer/Checkers/CMakeLists.txt
+++ lib/StaticAnalyzer/Checkers/CMakeLists.txt
@@ -49,6 +49,7 @@
   MallocChecker.cpp
   MallocOverflowSecurityChecker.cpp
   MallocSizeofChecker.cpp
+  MmapWriteExecChecker.cpp
   MisusedMovedObjectChecker.cpp
   MPI-Checker/MPIBugReporter.cpp
   MPI-Checker/MPIChecker.cpp
Index: include/clang/StaticAnalyzer/Checkers/Checkers.td
===
--- include/clang/StaticAnalyzer/Checkers/Checkers.td
+++ include/clang/StaticAnalyzer/Checkers/Checkers.td
@@ -86,7 +86,7 @@
 
 // The APIModeling package is for checkers that model APIs and don't perform
 // any diagnostics. These checkers are always turned on; this package is
-// intended for API modeling that is not controlled by the target triple.
+// intended for API modeling that is not controlled by the the target triple.
 def APIModeling : Package<"apiModeling">, Hidden;
 def GoogleAPIModeling : Package<"google">, InPackage;
 
@@ -394,6 +394,10 @@
   def FloatLoopCounter : Checker<"FloatLoopCounter">,
 HelpText<"Warn on using a floating point value as a loop counter (CERT: FLP30-C, FLP30-CPP)">,
 DescFile<"CheckSecuritySyntaxOnly.cpp">;
+
+  def MmapWriteExecChecker : Checker<"MmapWriteExec">,
+HelpText<"Check if mmap() call is not both writable and executable">,
+DescFile<"MmapWriteExecChecker.cpp">;
 }
 
 let ParentPackage = SecurityAlpha in {
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D42812: [clang-tidy] ObjC ARC objects should not trigger performance-unnecessary-value-param

2018-02-01 Thread Ben Hamilton via Phabricator via cfe-commits
benhamilton created this revision.
benhamilton added reviewers: alexfh, hokein.
Herald added subscribers: cfe-commits, xazax.hun, klimek.

The following Objective-C code currently incorrectly triggers
clang-tidy's performance-unnecessary-value-param check:

  % cat /tmp/performance-unnecessary-value-param-arc.m
  void foo(id object) { }
  
  clang-tidy /tmp/performance-unnecessary-value-param-arc.m
  -checks=-\*,performance-unnecessary-value-param -- -xobjective-c
  -fobjc-abi-version=2 -fobjc-arc
  1 warning generated.
  
/src/llvm/tools/clang/tools/extra/test/clang-tidy/performance-unnecessary-value-param-arc.m:10:13:
  warning: the parameter 'object' is copied for each invocation but only
  used as a const reference; consider making it a const reference
  [performance-unnecessary-value-param]
  void foo(id object) { }
   ~~ ^
   const &

This is wrong for a few reasons:

1. Objective-C doesn't have references, so `const &` is not going to help
2. ARC heavily optimizes the "expensive" copy which triggers the warning

This fixes the issue by disabling the warning for non-C++, as well as
disabling it for objects under ARC memory management for
Objective-C++.

Test Plan: New tests added. Ran tests with `make -j12 check-clang-tools`.


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D42812

Files:
  clang-tidy/performance/UnnecessaryValueParamCheck.cpp
  clang-tidy/utils/TypeTraits.cpp
  test/clang-tidy/performance-unnecessary-value-param-arc.m
  test/clang-tidy/performance-unnecessary-value-param-arc.mm


Index: test/clang-tidy/performance-unnecessary-value-param-arc.mm
===
--- /dev/null
+++ test/clang-tidy/performance-unnecessary-value-param-arc.mm
@@ -0,0 +1,16 @@
+// RUN: clang-tidy %s -checks=-*,performance-unnecessary-value-param -- \
+// RUN:   -xobjective-c++ -fobjc-abi-version=2 -fobjc-arc | count 0
+
+#if !__has_feature(objc_arc)
+#error Objective-C ARC not enabled as expected
+#endif
+
+// Passing an Objective-C ARC-managed object to a C function should
+// not raise performance-unnecessary-value-param.
+void foo(id object) { }
+
+// Same for explcitly non-ARC-managed Objective-C objects.
+void bar(__unsafe_unretained id object) { }
+
+// Same for Objective-c classes.
+void baz(Class c) { }
Index: test/clang-tidy/performance-unnecessary-value-param-arc.m
===
--- /dev/null
+++ test/clang-tidy/performance-unnecessary-value-param-arc.m
@@ -0,0 +1,16 @@
+// RUN: clang-tidy %s -checks=-*,performance-unnecessary-value-param -- \
+// RUN:   -xobjective-c -fobjc-abi-version=2 -fobjc-arc | count 0
+
+#if !__has_feature(objc_arc)
+#error Objective-C ARC not enabled as expected
+#endif
+
+// Passing an Objective-C ARC-managed object to a C function should
+// not raise performance-unnecessary-value-param.
+void foo(id object) { }
+
+// Same for explcitly non-ARC-managed Objective-C objects.
+void bar(__unsafe_unretained id object) { }
+
+// Same for Objective-c classes.
+void baz(Class c) { }
Index: clang-tidy/utils/TypeTraits.cpp
===
--- clang-tidy/utils/TypeTraits.cpp
+++ clang-tidy/utils/TypeTraits.cpp
@@ -45,7 +45,8 @@
 return llvm::None;
   return !Type.isTriviallyCopyableType(Context) &&
  !classHasTrivialCopyAndDestroy(Type) &&
- !hasDeletedCopyConstructor(Type);
+ !hasDeletedCopyConstructor(Type) &&
+ !Type->isObjCLifetimeType();
 }
 
 bool recordIsTriviallyDefaultConstructible(const RecordDecl ,
Index: clang-tidy/performance/UnnecessaryValueParamCheck.cpp
===
--- clang-tidy/performance/UnnecessaryValueParamCheck.cpp
+++ clang-tidy/performance/UnnecessaryValueParamCheck.cpp
@@ -79,6 +79,10 @@
   Options.getLocalOrGlobal("IncludeStyle", "llvm"))) {}
 
 void UnnecessaryValueParamCheck::registerMatchers(MatchFinder *Finder) {
+  // This check is specific to C++ and doesn't apply to languages like
+  // Objective-C.
+  if (!getLangOpts().CPlusPlus)
+return;
   const auto ExpensiveValueParamDecl =
   parmVarDecl(hasType(hasCanonicalType(allOf(
   unless(referenceType()), 
matchers::isExpensiveToCopy(,


Index: test/clang-tidy/performance-unnecessary-value-param-arc.mm
===
--- /dev/null
+++ test/clang-tidy/performance-unnecessary-value-param-arc.mm
@@ -0,0 +1,16 @@
+// RUN: clang-tidy %s -checks=-*,performance-unnecessary-value-param -- \
+// RUN:   -xobjective-c++ -fobjc-abi-version=2 -fobjc-arc | count 0
+
+#if !__has_feature(objc_arc)
+#error Objective-C ARC not enabled as expected
+#endif
+
+// Passing an Objective-C ARC-managed object to a C function should
+// not raise performance-unnecessary-value-param.
+void foo(id object) { }
+
+// Same for explcitly non-ARC-managed 

[PATCH] D42811: [CodeGen][va_args] Correct Vector Struct va-arg 'in_reg' code gen

2018-02-01 Thread Erich Keane via Phabricator via cfe-commits
erichkeane created this revision.
erichkeane added reviewers: rsmith, rjmccall.

When trying to track down a different bug, we discovered
that calling `__builtin_va_arg` on a vec3f type caused
the SROA pass to issue a warning that there was an illegal
access.

Further research showed that the vec3f type is
alloca'ed as size '12', but the `_builtin_va_arg` code
on x86_64 was always loading this out of registers as 
{double, double}. Thus, the 2nd store into the vec3f
was storing in bytes 12-15!

This patch alters the original implementation which always
assumed {double, double} to use the actual coerced type 
instead, so the LLVM-IR generated is a load/GEP/store of
a <2 x float> and a float, rather than a double and a double.

Tests were added for all combinations I could think of that
would fit in 2 FP registers, and all work exactly as expected.


Repository:
  rC Clang

https://reviews.llvm.org/D42811

Files:
  lib/CodeGen/TargetInfo.cpp
  test/CodeGen/x86_64-floatvectors.c

Index: lib/CodeGen/TargetInfo.cpp
===
--- lib/CodeGen/TargetInfo.cpp
+++ lib/CodeGen/TargetInfo.cpp
@@ -3790,17 +3790,18 @@
 Address RegAddrHi =
   CGF.Builder.CreateConstInBoundsByteGEP(RegAddrLo,
  CharUnits::fromQuantity(16));
-llvm::Type *DoubleTy = CGF.DoubleTy;
-llvm::StructType *ST = llvm::StructType::get(DoubleTy, DoubleTy);
+llvm::Type *ST = AI.canHaveCoerceToType()
+ ? AI.getCoerceToType()
+ : llvm::StructType::get(CGF.DoubleTy, CGF.DoubleTy);
 llvm::Value *V;
 Address Tmp = CGF.CreateMemTemp(Ty);
 Tmp = CGF.Builder.CreateElementBitCast(Tmp, ST);
-V = CGF.Builder.CreateLoad(
-   CGF.Builder.CreateElementBitCast(RegAddrLo, DoubleTy));
+V = CGF.Builder.CreateLoad(CGF.Builder.CreateElementBitCast(
+RegAddrLo, ST->getStructElementType(0)));
 CGF.Builder.CreateStore(V,
CGF.Builder.CreateStructGEP(Tmp, 0, CharUnits::Zero()));
-V = CGF.Builder.CreateLoad(
-   CGF.Builder.CreateElementBitCast(RegAddrHi, DoubleTy));
+V = CGF.Builder.CreateLoad(CGF.Builder.CreateElementBitCast(
+RegAddrHi, ST->getStructElementType(1)));
 CGF.Builder.CreateStore(V,
   CGF.Builder.CreateStructGEP(Tmp, 1, CharUnits::fromQuantity(8)));
 
Index: test/CodeGen/x86_64-floatvectors.c
===
--- test/CodeGen/x86_64-floatvectors.c
+++ test/CodeGen/x86_64-floatvectors.c
@@ -0,0 +1,131 @@
+// RUN: %clang_cc1 -triple x86_64-unknown-unknown -emit-llvm -o - %s | \
+// RUN:   FileCheck %s
+
+// This test validates that the inreg branch generation for __builtin_va_arg 
+// does not exceed the alloca size of the type, which can cause the SROA pass to
+// eliminate the assignment.
+
+typedef struct { float x, y, z; } vec3f;
+
+double Vec3FTest(__builtin_va_list ap) {
+  vec3f vec = __builtin_va_arg(ap, vec3f);
+  return vec.x + vec.y + vec.z;
+}
+// CHECK: define double @Vec3FTest
+// CHECK: vaarg.in_reg:
+// CHECK: [[Vec3FLoad1:%.*]] = load <2 x float>, <2 x float>*
+// CHECK: [[Vec3FGEP1:%.*]] = getelementptr inbounds { <2 x float>, float }, { <2 x float>, float }* {{%.*}}, i32 0, i32 0
+// CHECK: store <2 x float> [[Vec3FLoad1]], <2 x float>* [[Vec3FGEP1]]
+// CHECK: [[Vec3FLoad2:%.*]] = load float, float*
+// CHECK: [[Vec3FGEP2:%.*]] = getelementptr inbounds { <2 x float>, float }, { <2 x float>, float }* {{%.*}}, i32 0, i32 1
+// CHECK: store float [[Vec3FLoad2]], float* [[Vec3FGEP2]]
+// CHECK: vaarg.in_mem:
+
+
+typedef struct { float x, y, z, q; } vec4f;
+
+double Vec4FTest(__builtin_va_list ap) {
+  vec4f vec = __builtin_va_arg(ap, vec4f);
+  return vec.x + vec.y + vec.z + vec.q;
+}
+// CHECK: define double @Vec4FTest
+// CHECK: vaarg.in_reg:
+// CHECK: [[Vec4FLoad1:%.*]] = load <2 x float>, <2 x float>*
+// CHECK: [[Vec4FGEP1:%.*]] = getelementptr inbounds { <2 x float>, <2 x float> }, { <2 x float>, <2 x float> }* {{%.*}}, i32 0, i32 0
+// CHECK: store <2 x float> [[Vec4FLoad1]], <2 x float>* [[Vec4FGEP1]]
+// CHECK: [[Vec4FLoad2:%.*]] = load <2 x float>, <2 x float>*
+// CHECK: [[Vec4FGEP2:%.*]] = getelementptr inbounds { <2 x float>, <2 x float> }, { <2 x float>, <2 x float> }* {{%.*}}, i32 0, i32 1
+// CHECK: store <2 x float> [[Vec4FLoad2]], <2 x float>* [[Vec4FGEP2]]
+// CHECK: vaarg.in_mem:
+
+typedef struct { double x, y; } vec2d;
+
+double Vec2DTest(__builtin_va_list ap) {
+  vec2d vec = __builtin_va_arg(ap, vec2d);
+  return vec.x + vec.y;
+}
+// CHECK: define double @Vec2DTest
+// CHECK: vaarg.in_reg:
+// CHECK: [[Vec2DLoad1:%.*]] = load double, double*
+// CHECK: [[Vec2DGEP1:%.*]] = getelementptr inbounds { double, double }, { double, double }* {{%.*}}, i32 0, i32 0
+// CHECK: store double [[Vec2DLoad1]], double* [[Vec2DGEP1]]
+// CHECK: [[Vec2DLoad2:%.*]] = load double, double*
+// CHECK: 

[PATCH] D42810: [Sema] Add implicit members even for invalid CXXRecordDecls

2018-02-01 Thread Benjamin Kramer via Phabricator via cfe-commits
bkramer accepted this revision.
bkramer added a comment.
This revision is now accepted and ready to land.

lg


Repository:
  rC Clang

https://reviews.llvm.org/D42810



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


[PATCH] D42457: [analyzer] Don't communicate evaluation failures through memregion hierarchy.

2018-02-01 Thread Artem Dergachev via Phabricator via cfe-commits
NoQ updated this revision to Diff 132450.
NoQ added a comment.

Switched to plain bools and in-class initializers.


https://reviews.llvm.org/D42457

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

Index: test/Analysis/new.cpp
===
--- test/Analysis/new.cpp
+++ test/Analysis/new.cpp
@@ -311,8 +311,7 @@
 void testArrayDestr() {
   NoReturnDtor *p = new NoReturnDtor[2];
   delete[] p; // Calls the base destructor which aborts, checked below
-  //TODO: clang_analyzer_eval should not be called
-  clang_analyzer_eval(true); // expected-warning{{TRUE}}
+  clang_analyzer_eval(true); // no-warning
 }
 
 // Invalidate Region even in case of default destructor
Index: lib/StaticAnalyzer/Core/ExprEngineCallAndReturn.cpp
===
--- lib/StaticAnalyzer/Core/ExprEngineCallAndReturn.cpp
+++ lib/StaticAnalyzer/Core/ExprEngineCallAndReturn.cpp
@@ -616,15 +616,10 @@
   Bldr.generateNode(Call.getProgramPoint(), State, Pred);
 }
 
-enum CallInlinePolicy {
-  CIP_Allowed,
-  CIP_DisallowedOnce,
-  CIP_DisallowedAlways
-};
-
-static CallInlinePolicy mayInlineCallKind(const CallEvent ,
-  const ExplodedNode *Pred,
-  AnalyzerOptions ) {
+ExprEngine::CallInlinePolicy
+ExprEngine::mayInlineCallKind(const CallEvent , const ExplodedNode *Pred,
+  AnalyzerOptions ,
+  const ExprEngine::EvalCallOptions ) {
   const LocationContext *CurLC = Pred->getLocationContext();
   const StackFrameContext *CallerSFC = CurLC->getCurrentStackFrame();
   switch (Call.getKind()) {
@@ -658,18 +653,8 @@
 // initializers for array fields in default move/copy constructors.
 // We still allow construction into ElementRegion targets when they don't
 // represent array elements.
-const MemRegion *Target = Ctor.getCXXThisVal().getAsRegion();
-if (Target && isa(Target)) {
-  if (ParentExpr)
-if (const CXXNewExpr *NewExpr = dyn_cast(ParentExpr))
-  if (NewExpr->isArray())
-return CIP_DisallowedOnce;
-
-  if (const TypedValueRegion *TR = dyn_cast(
-  cast(Target)->getSuperRegion()))
-if (TR->getValueType()->isArrayType())
-  return CIP_DisallowedOnce;
-}
+if (CallOpts.IsArrayConstructorOrDestructor)
+  return CIP_DisallowedOnce;
 
 // Inlining constructors requires including initializers in the CFG.
 const AnalysisDeclContext *ADC = CallerSFC->getAnalysisDeclContext();
@@ -688,7 +673,7 @@
 // FIXME: This is a hack. We don't handle temporary destructors
 // right now, so we shouldn't inline their constructors.
 if (CtorExpr->getConstructionKind() == CXXConstructExpr::CK_Complete)
-  if (!Target || isa(Target))
+  if (CallOpts.IsConstructorWithImproperlyModeledTargetRegion)
 return CIP_DisallowedOnce;
 
 break;
@@ -702,11 +687,8 @@
 assert(ADC->getCFGBuildOptions().AddImplicitDtors && "No CFG destructors");
 (void)ADC;
 
-const CXXDestructorCall  = cast(Call);
-
 // FIXME: We don't handle constructors or destructors for arrays properly.
-const MemRegion *Target = Dtor.getCXXThisVal().getAsRegion();
-if (Target && isa(Target))
+if (CallOpts.IsArrayConstructorOrDestructor)
   return CIP_DisallowedOnce;
 
 break;
@@ -847,7 +829,8 @@
 }
 
 bool ExprEngine::shouldInlineCall(const CallEvent , const Decl *D,
-  const ExplodedNode *Pred) {
+  const ExplodedNode *Pred,
+  const EvalCallOptions ) {
   if (!D)
 return false;
 
@@ -894,7 +877,7 @@
   // FIXME: this checks both static and dynamic properties of the call, which
   // means we're redoing a bit of work that could be cached in the function
   // summary.
-  CallInlinePolicy CIP = mayInlineCallKind(Call, Pred, Opts);
+  CallInlinePolicy CIP = mayInlineCallKind(Call, Pred, Opts, CallOpts);
   if (CIP != CIP_Allowed) {
 if (CIP == CIP_DisallowedAlways) {
   assert(!MayInline.hasValue() || MayInline.getValue());
@@ -946,7 +929,8 @@
 }
 
 void ExprEngine::defaultEvalCall(NodeBuilder , ExplodedNode *Pred,
- const CallEvent ) {
+ const CallEvent ,
+ const EvalCallOptions ) {
   // Make sure we have the most recent state attached to the call.
   ProgramStateRef State = Pred->getState();
   CallEventRef<> Call = CallTemplate.cloneWithState(State);
@@ -969,7 +953,7 @@
   } else {
 RuntimeDefinition RD = Call->getRuntimeDefinition();
 const Decl *D = RD.getDecl();
-if (shouldInlineCall(*Call, D, Pred)) {
+if (shouldInlineCall(*Call, D, Pred, 

[PATCH] D42673: [RISCV] Pick the correct RISCV linker instead of calling riscv-gcc to link

2018-02-01 Thread Mandeep Singh Grang via Phabricator via cfe-commits
mgrang abandoned this revision.
mgrang added a comment.

For now, by setting the full triple (riscv-unknown-linux-gnu) we are able to 
invoke the correct gnu linker. So will abandon this patch.


Repository:
  rC Clang

https://reviews.llvm.org/D42673



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


[PATCH] D42645: New simple Checker for mmap calls

2018-02-01 Thread Artem Dergachev via Phabricator via cfe-commits
NoQ added inline comments.



Comment at: lib/StaticAnalyzer/Checkers/MmapWriteExecChecker.cpp:62
+
+  ExplodedNode *N = C.generateErrorNode();
+  if (!N)

You should also use `generateNonFatalErrorNode()` here so that not to prevent 
the analyzer from finding other bugs on that path, because your bug doesn't 
cause abnormal program termination or otherwise leave the analyzer in an 
inconsistent state.


Repository:
  rC Clang

https://reviews.llvm.org/D42645



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


r323998 - PR36157: When injecting an implicit function declaration in C89, find the right

2018-02-01 Thread Richard Smith via cfe-commits
Author: rsmith
Date: Thu Feb  1 12:01:49 2018
New Revision: 323998

URL: http://llvm.org/viewvc/llvm-project?rev=323998=rev
Log:
PR36157: When injecting an implicit function declaration in C89, find the right
DeclContext rather than injecting it wherever we happen to be.

This avoids creating functions whose DeclContext is a struct or similar.

Added:
cfe/trunk/test/Sema/cxx-as-c.c
Modified:
cfe/trunk/lib/Sema/SemaDecl.cpp
cfe/trunk/test/Sema/bitfield.c

Modified: cfe/trunk/lib/Sema/SemaDecl.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Sema/SemaDecl.cpp?rev=323998=323997=323998=diff
==
--- cfe/trunk/lib/Sema/SemaDecl.cpp (original)
+++ cfe/trunk/lib/Sema/SemaDecl.cpp Thu Feb  1 12:01:49 2018
@@ -12910,10 +12910,20 @@ void Sema::ActOnFinishDelayedAttribute(S
 /// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
 NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
   IdentifierInfo , Scope *S) {
+  // Find the scope in which the identifier is injected and the corresponding
+  // DeclContext.
+  // FIXME: C89 does not say what happens if there is no enclosing block scope.
+  // In that case, we inject the declaration into the translation unit scope
+  // instead.
   Scope *BlockScope = S;
   while (!BlockScope->isCompoundStmtScope() && BlockScope->getParent())
 BlockScope = BlockScope->getParent();
 
+  Scope *ContextScope = BlockScope;
+  while (!ContextScope->getEntity())
+ContextScope = ContextScope->getParent();
+  ContextRAII SavedContext(*this, ContextScope->getEntity());
+
   // Before we produce a declaration for an implicitly defined
   // function, see whether there was a locally-scoped declaration of
   // this name as a function or variable. If so, use that

Modified: cfe/trunk/test/Sema/bitfield.c
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/Sema/bitfield.c?rev=323998=323997=323998=diff
==
--- cfe/trunk/test/Sema/bitfield.c (original)
+++ cfe/trunk/test/Sema/bitfield.c Thu Feb  1 12:01:49 2018
@@ -82,3 +82,7 @@ typedef __typeof__(+(t5.n--)) Unsigned;
 struct Test6 {
   : 0.0; // expected-error{{type name requires a specifier or qualifier}}
 };
+
+struct PR36157 {
+  int n : 1 ? 1 : implicitly_declare_function(); // expected-warning {{invalid 
in C99}}
+};

Added: cfe/trunk/test/Sema/cxx-as-c.c
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/Sema/cxx-as-c.c?rev=323998=auto
==
--- cfe/trunk/test/Sema/cxx-as-c.c (added)
+++ cfe/trunk/test/Sema/cxx-as-c.c Thu Feb  1 12:01:49 2018
@@ -0,0 +1,9 @@
+// RUN: %clang_cc1 %s -verify
+
+// PR36157
+struct Foo {
+  Foo(int n) : n_(n) {} // expected-error 1+{{}} expected-warning 1+{{}}
+private:
+  int n;
+};
+int main() { Foo f; } // expected-error 1+{{}}


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


[PATCH] D42810: [Sema] Add implicit members even for invalid CXXRecordDecls

2018-02-01 Thread Ilya Biryukov via Phabricator via cfe-commits
ilya-biryukov added a comment.

The following assertion from `DeclContext::removeDecl` was failing before:

  assert((D->NextInContextAndBits.getPointer() || D == LastDecl) &&
 "decl is not in decls list");


Repository:
  rC Clang

https://reviews.llvm.org/D42810



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


[PATCH] D42810: [Sema] Add implicit members even for invalid CXXRecordDecls

2018-02-01 Thread Ilya Biryukov via Phabricator via cfe-commits
ilya-biryukov created this revision.
ilya-biryukov added a reviewer: bkramer.

It should be safe, since other code paths are already generating
implicit members even in invalid CXXRecordDecls (e.g. lookup).

If we don't generate implicit members on CXXRecordDecl's completion,
they will be generated by next lookup of constructors. This causes a
crash when the following conditions are met:

- a CXXRecordDecl is invalid,
- it is provided via ExternalASTSource (e.g. from PCH),
- it has inherited constructors (they create as ShadowDecl),
- lookup of its constructors was not run before ASTWriter serialized it.

This causes the ShadowDecls created for implicit constructors to be
removed from the class, but that's no longer possible since class is
provided by ExternalASTSource.

See provided lit test for an example.


Repository:
  rC Clang

https://reviews.llvm.org/D42810

Files:
  lib/Sema/SemaDecl.cpp
  test/Index/Inputs/crash-preamble-classes.h
  test/Index/crash-preamble-classes.cpp


Index: test/Index/crash-preamble-classes.cpp
===
--- /dev/null
+++ test/Index/crash-preamble-classes.cpp
@@ -0,0 +1,8 @@
+#include "crash-preamble-classes.h"
+
+struct Z : Y {
+  Z() {}
+};
+
+// RUN: env CINDEXTEST_EDITING=1 \
+// RUN: c-index-test -test-load-source-reparse 5 local -I %S/Inputs %s
Index: test/Index/Inputs/crash-preamble-classes.h
===
--- /dev/null
+++ test/Index/Inputs/crash-preamble-classes.h
@@ -0,0 +1,9 @@
+struct Incomplete;
+
+struct X : Incomplete {
+  X();
+};
+
+struct Y : X {
+  using X::X;
+};
Index: lib/Sema/SemaDecl.cpp
===
--- lib/Sema/SemaDecl.cpp
+++ lib/Sema/SemaDecl.cpp
@@ -15430,10 +15430,10 @@
   CXXRecord->getDestructor());
 }
 
-if (!CXXRecord->isInvalidDecl()) {
-  // Add any implicitly-declared members to this class.
-  AddImplicitlyDeclaredMembersToClass(CXXRecord);
+// Add any implicitly-declared members to this class.
+AddImplicitlyDeclaredMembersToClass(CXXRecord);
 
+if (!CXXRecord->isInvalidDecl()) {
   // If we have virtual base classes, we may end up finding multiple
   // final overriders for a given virtual function. Check for this
   // problem now.


Index: test/Index/crash-preamble-classes.cpp
===
--- /dev/null
+++ test/Index/crash-preamble-classes.cpp
@@ -0,0 +1,8 @@
+#include "crash-preamble-classes.h"
+
+struct Z : Y {
+  Z() {}
+};
+
+// RUN: env CINDEXTEST_EDITING=1 \
+// RUN: c-index-test -test-load-source-reparse 5 local -I %S/Inputs %s
Index: test/Index/Inputs/crash-preamble-classes.h
===
--- /dev/null
+++ test/Index/Inputs/crash-preamble-classes.h
@@ -0,0 +1,9 @@
+struct Incomplete;
+
+struct X : Incomplete {
+  X();
+};
+
+struct Y : X {
+  using X::X;
+};
Index: lib/Sema/SemaDecl.cpp
===
--- lib/Sema/SemaDecl.cpp
+++ lib/Sema/SemaDecl.cpp
@@ -15430,10 +15430,10 @@
   CXXRecord->getDestructor());
 }
 
-if (!CXXRecord->isInvalidDecl()) {
-  // Add any implicitly-declared members to this class.
-  AddImplicitlyDeclaredMembersToClass(CXXRecord);
+// Add any implicitly-declared members to this class.
+AddImplicitlyDeclaredMembersToClass(CXXRecord);
 
+if (!CXXRecord->isInvalidDecl()) {
   // If we have virtual base classes, we may end up finding multiple
   // final overriders for a given virtual function. Check for this
   // problem now.
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D42644: [asan] Intercept std::rethrow_exception indirectly.

2018-02-01 Thread Vitaly Buka via Phabricator via cfe-commits
vitalybuka added a comment.

I would not worry about cross platform here. You can patch just Linux and 
whoever have access (and issues) on other platforms can send a patch with 
similar changes.
Mac should use libc++.
I'd put the test outside of Posix, and mark failing platforms as "// XFAIL:", 
temporarily, as we suppose to handle all of them.




Comment at: lib/asan/asan_interceptors.cc:327
+INTERCEPTOR(void, __cxa_rethrow_primary_exception, void *a) {
+  CHECK(REAL(__cxa_throw));
+  __asan_handle_no_return();

Should this be: CHECK(REAL(__cxa_rethrow_primary_exception)); ?



Repository:
  rCRT Compiler Runtime

https://reviews.llvm.org/D42644



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


[PATCH] D42530: Clang permits assignment to vector/extvector elements in a const method

2018-02-01 Thread John McCall via Phabricator via cfe-commits
rjmccall added a comment.

That's still just const-propagation.  The const qualifier on the pointee type 
of this should propagate to the l-value resulting from the member access, and 
the vector-specific projection logic should continue to propagate const to the 
type of the element l-value.


https://reviews.llvm.org/D42530



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


[PATCH] D42644: [asan] Intercept std::rethrow_exception indirectly.

2018-02-01 Thread Vitaly Buka via Phabricator via cfe-commits
vitalybuka added a comment.

Could you please reformat it?
With git I usually use: git clang-format -f --style=file HEAD^


Repository:
  rCRT Compiler Runtime

https://reviews.llvm.org/D42644



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


[PATCH] D42785: [Analyzer] Fix a typo in `ExprEngine::VisitMemberExpr`

2018-02-01 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.

Ew. So it means that checker transitions are currently discarded. Great catch. 
I guess we don't use this functionality yet, so we can't test it, but the fix 
should definitely go in.

Then, again, i'm suspecting that you may want to use `checkLocation` or 
`checkBind` instead of `checkPreStmt` - i doubt that there's 
anything special about member expressions that make them different from other 
sorts of bindings. And if you're tracking how a symbol is assigned to a field 
of the structure - well, you shouldn't, this info is already in the program 
state and you can retrieve it any time with `getSVal(Region)`.


Repository:
  rC Clang

https://reviews.llvm.org/D42785



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


[PATCH] D42803: [clangd] Log dropped diagnostics.

2018-02-01 Thread Phabricator via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rCTE323992: [clangd] Log dropped diagnostics. (authored by 
ibiryukov, committed by ).

Changed prior to commit:
  https://reviews.llvm.org/D42803?vs=132430=132432#toc

Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D42803

Files:
  clangd/ClangdUnit.cpp


Index: clangd/ClangdUnit.cpp
===
--- clangd/ClangdUnit.cpp
+++ clangd/ClangdUnit.cpp
@@ -27,6 +27,7 @@
 #include "llvm/ADT/SmallVector.h"
 #include "llvm/Support/CrashRecoveryContext.h"
 #include "llvm/Support/Format.h"
+#include "llvm/Support/raw_ostream.h"
 #include 
 #include 
 
@@ -178,15 +179,30 @@
 llvm::Optional toClangdDiag(const clang::Diagnostic ,
 DiagnosticsEngine::Level Level,
 const LangOptions ) {
+  SmallString<64> Message;
+  D.FormatDiagnostic(Message);
+
   if (!D.hasSourceManager() || !D.getLocation().isValid() ||
-  !D.getSourceManager().isInMainFile(D.getLocation()))
+  !D.getSourceManager().isInMainFile(D.getLocation())) {
+
+SmallString<64> Location;
+if (D.hasSourceManager() && D.getLocation().isValid()) {
+  auto  = D.getSourceManager();
+  auto Loc = SourceMgr.getFileLoc(D.getLocation());
+  llvm::raw_svector_ostream OS(Location);
+  Loc.print(OS, SourceMgr);
+} else {
+  Location = "";
+}
+
+log(llvm::formatv("Ignored diagnostic outside main file. {0}: {1}",
+  Location, Message));
 return llvm::None;
+  }
 
   DiagWithFixIts Result;
   Result.Diag.range = diagnosticRange(D, LangOpts);
   Result.Diag.severity = getSeverity(Level);
-  SmallString<64> Message;
-  D.FormatDiagnostic(Message);
   Result.Diag.message = Message.str();
   for (const FixItHint  : D.getFixItHints())
 Result.FixIts.push_back(toTextEdit(Fix, D.getSourceManager(), LangOpts));


Index: clangd/ClangdUnit.cpp
===
--- clangd/ClangdUnit.cpp
+++ clangd/ClangdUnit.cpp
@@ -27,6 +27,7 @@
 #include "llvm/ADT/SmallVector.h"
 #include "llvm/Support/CrashRecoveryContext.h"
 #include "llvm/Support/Format.h"
+#include "llvm/Support/raw_ostream.h"
 #include 
 #include 
 
@@ -178,15 +179,30 @@
 llvm::Optional toClangdDiag(const clang::Diagnostic ,
 DiagnosticsEngine::Level Level,
 const LangOptions ) {
+  SmallString<64> Message;
+  D.FormatDiagnostic(Message);
+
   if (!D.hasSourceManager() || !D.getLocation().isValid() ||
-  !D.getSourceManager().isInMainFile(D.getLocation()))
+  !D.getSourceManager().isInMainFile(D.getLocation())) {
+
+SmallString<64> Location;
+if (D.hasSourceManager() && D.getLocation().isValid()) {
+  auto  = D.getSourceManager();
+  auto Loc = SourceMgr.getFileLoc(D.getLocation());
+  llvm::raw_svector_ostream OS(Location);
+  Loc.print(OS, SourceMgr);
+} else {
+  Location = "";
+}
+
+log(llvm::formatv("Ignored diagnostic outside main file. {0}: {1}",
+  Location, Message));
 return llvm::None;
+  }
 
   DiagWithFixIts Result;
   Result.Diag.range = diagnosticRange(D, LangOpts);
   Result.Diag.severity = getSeverity(Level);
-  SmallString<64> Message;
-  D.FormatDiagnostic(Message);
   Result.Diag.message = Message.str();
   for (const FixItHint  : D.getFixItHints())
 Result.FixIts.push_back(toTextEdit(Fix, D.getSourceManager(), LangOpts));
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


Re: r323155 - Introduce the "retpoline" x86 mitigation technique for variant #2 of the speculative execution vulnerabilities disclosed today, specifically identified by CVE-2017-5715, "Branch Target

2018-02-01 Thread Chandler Carruth via cfe-commits
+Hans Wennborg  +tstel...@redhat.com


So the retpoline patch series we should get back ported start with this
revision and have two follow ups:
r323155
r323288
r323915

+Reid Kleckner  was going to look at doing the (likely more
involved) backport to the 5 branch

On Mon, Jan 22, 2018 at 2:06 PM Chandler Carruth via cfe-commits <
cfe-commits@lists.llvm.org> wrote:

> Author: chandlerc
> Date: Mon Jan 22 14:05:25 2018
> New Revision: 323155
>
> URL: http://llvm.org/viewvc/llvm-project?rev=323155=rev
> Log:
> Introduce the "retpoline" x86 mitigation technique for variant #2 of the
> speculative execution vulnerabilities disclosed today, specifically
> identified by CVE-2017-5715, "Branch Target Injection", and is one of the
> two halves to Spectre..
>
> Summary:
> First, we need to explain the core of the vulnerability. Note that this
> is a very incomplete description, please see the Project Zero blog post
> for details:
>
> https://googleprojectzero.blogspot.com/2018/01/reading-privileged-memory-with-side.html
>
> The basis for branch target injection is to direct speculative execution
> of the processor to some "gadget" of executable code by poisoning the
> prediction of indirect branches with the address of that gadget. The
> gadget in turn contains an operation that provides a side channel for
> reading data. Most commonly, this will look like a load of secret data
> followed by a branch on the loaded value and then a load of some
> predictable cache line. The attacker then uses timing of the processors
> cache to determine which direction the branch took *in the speculative
> execution*, and in turn what one bit of the loaded value was. Due to the
> nature of these timing side channels and the branch predictor on Intel
> processors, this allows an attacker to leak data only accessible to
> a privileged domain (like the kernel) back into an unprivileged domain.
>
> The goal is simple: avoid generating code which contains an indirect
> branch that could have its prediction poisoned by an attacker. In many
> cases, the compiler can simply use directed conditional branches and
> a small search tree. LLVM already has support for lowering switches in
> this way and the first step of this patch is to disable jump-table
> lowering of switches and introduce a pass to rewrite explicit indirectbr
> sequences into a switch over integers.
>
> However, there is no fully general alternative to indirect calls. We
> introduce a new construct we call a "retpoline" to implement indirect
> calls in a non-speculatable way. It can be thought of loosely as
> a trampoline for indirect calls which uses the RET instruction on x86.
> Further, we arrange for a specific call->ret sequence which ensures the
> processor predicts the return to go to a controlled, known location. The
> retpoline then "smashes" the return address pushed onto the stack by the
> call with the desired target of the original indirect call. The result
> is a predicted return to the next instruction after a call (which can be
> used to trap speculative execution within an infinite loop) and an
> actual indirect branch to an arbitrary address.
>
> On 64-bit x86 ABIs, this is especially easily done in the compiler by
> using a guaranteed scratch register to pass the target into this device.
> For 32-bit ABIs there isn't a guaranteed scratch register and so several
> different retpoline variants are introduced to use a scratch register if
> one is available in the calling convention and to otherwise use direct
> stack push/pop sequences to pass the target address.
>
> This "retpoline" mitigation is fully described in the following blog
> post: https://support.google.com/faqs/answer/7625886
>
> We also support a target feature that disables emission of the retpoline
> thunk by the compiler to allow for custom thunks if users want them.
> These are particularly useful in environments like kernels that
> routinely do hot-patching on boot and want to hot-patch their thunk to
> different code sequences. They can write this custom thunk and use
> `-mretpoline-external-thunk` *in addition* to `-mretpoline`. In this
> case, on x86-64 thu thunk names must be:
> ```
>   __llvm_external_retpoline_r11
> ```
> or on 32-bit:
> ```
>   __llvm_external_retpoline_eax
>   __llvm_external_retpoline_ecx
>   __llvm_external_retpoline_edx
>   __llvm_external_retpoline_push
> ```
> And the target of the retpoline is passed in the named register, or in
> the case of the `push` suffix on the top of the stack via a `pushl`
> instruction.
>
> There is one other important source of indirect branches in x86 ELF
> binaries: the PLT. These patches also include support for LLD to
> generate PLT entries that perform a retpoline-style indirection.
>
> The only other indirect branches remaining that we are aware of are from
> precompiled runtimes (such as crt0.o and similar). The ones we have
> found are not really attackable, and so 

[PATCH] D42803: [clangd] Log dropped diagnostics.

2018-02-01 Thread Phabricator via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rL323992: [clangd] Log dropped diagnostics. (authored by 
ibiryukov, committed by ).
Herald added a subscriber: llvm-commits.

Repository:
  rL LLVM

https://reviews.llvm.org/D42803

Files:
  clang-tools-extra/trunk/clangd/ClangdUnit.cpp


Index: clang-tools-extra/trunk/clangd/ClangdUnit.cpp
===
--- clang-tools-extra/trunk/clangd/ClangdUnit.cpp
+++ clang-tools-extra/trunk/clangd/ClangdUnit.cpp
@@ -27,6 +27,7 @@
 #include "llvm/ADT/SmallVector.h"
 #include "llvm/Support/CrashRecoveryContext.h"
 #include "llvm/Support/Format.h"
+#include "llvm/Support/raw_ostream.h"
 #include 
 #include 
 
@@ -178,15 +179,30 @@
 llvm::Optional toClangdDiag(const clang::Diagnostic ,
 DiagnosticsEngine::Level Level,
 const LangOptions ) {
+  SmallString<64> Message;
+  D.FormatDiagnostic(Message);
+
   if (!D.hasSourceManager() || !D.getLocation().isValid() ||
-  !D.getSourceManager().isInMainFile(D.getLocation()))
+  !D.getSourceManager().isInMainFile(D.getLocation())) {
+
+SmallString<64> Location;
+if (D.hasSourceManager() && D.getLocation().isValid()) {
+  auto  = D.getSourceManager();
+  auto Loc = SourceMgr.getFileLoc(D.getLocation());
+  llvm::raw_svector_ostream OS(Location);
+  Loc.print(OS, SourceMgr);
+} else {
+  Location = "";
+}
+
+log(llvm::formatv("Ignored diagnostic outside main file. {0}: {1}",
+  Location, Message));
 return llvm::None;
+  }
 
   DiagWithFixIts Result;
   Result.Diag.range = diagnosticRange(D, LangOpts);
   Result.Diag.severity = getSeverity(Level);
-  SmallString<64> Message;
-  D.FormatDiagnostic(Message);
   Result.Diag.message = Message.str();
   for (const FixItHint  : D.getFixItHints())
 Result.FixIts.push_back(toTextEdit(Fix, D.getSourceManager(), LangOpts));


Index: clang-tools-extra/trunk/clangd/ClangdUnit.cpp
===
--- clang-tools-extra/trunk/clangd/ClangdUnit.cpp
+++ clang-tools-extra/trunk/clangd/ClangdUnit.cpp
@@ -27,6 +27,7 @@
 #include "llvm/ADT/SmallVector.h"
 #include "llvm/Support/CrashRecoveryContext.h"
 #include "llvm/Support/Format.h"
+#include "llvm/Support/raw_ostream.h"
 #include 
 #include 
 
@@ -178,15 +179,30 @@
 llvm::Optional toClangdDiag(const clang::Diagnostic ,
 DiagnosticsEngine::Level Level,
 const LangOptions ) {
+  SmallString<64> Message;
+  D.FormatDiagnostic(Message);
+
   if (!D.hasSourceManager() || !D.getLocation().isValid() ||
-  !D.getSourceManager().isInMainFile(D.getLocation()))
+  !D.getSourceManager().isInMainFile(D.getLocation())) {
+
+SmallString<64> Location;
+if (D.hasSourceManager() && D.getLocation().isValid()) {
+  auto  = D.getSourceManager();
+  auto Loc = SourceMgr.getFileLoc(D.getLocation());
+  llvm::raw_svector_ostream OS(Location);
+  Loc.print(OS, SourceMgr);
+} else {
+  Location = "";
+}
+
+log(llvm::formatv("Ignored diagnostic outside main file. {0}: {1}",
+  Location, Message));
 return llvm::None;
+  }
 
   DiagWithFixIts Result;
   Result.Diag.range = diagnosticRange(D, LangOpts);
   Result.Diag.severity = getSeverity(Level);
-  SmallString<64> Message;
-  D.FormatDiagnostic(Message);
   Result.Diag.message = Message.str();
   for (const FixItHint  : D.getFixItHints())
 Result.FixIts.push_back(toTextEdit(Fix, D.getSourceManager(), LangOpts));
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D42803: [clangd] Log dropped diagnostics.

2018-02-01 Thread Ilya Biryukov via Phabricator via cfe-commits
ilya-biryukov added inline comments.



Comment at: clangd/ClangdUnit.cpp:182
+  SmallString<64> Message;
+  D.FormatDiagnostic(Message);
+

sammccall wrote:
> does Message include file:line? we probably want that in the log line.
No, it didn't include the line before. Now dumping the location too.



Comment at: clangd/ClangdUnit.cpp:186
+  !D.getSourceManager().isInMainFile(D.getLocation())) {
+log("Ignored diagnostic outside main file: " + Twine(Message));
 return llvm::None;

sammccall wrote:
> Agree this is useful.
> 
> Have we turned off the diagnostics limit (or will we?) a misconfig of e.g. C 
> vs C++ parsing of a header seems like it could produce 1000+ log lines from 
> preamble that we should probably avoid somehow.
> (Maybe even avoid paying to format)
I don't think we have changed default clang behavior.
This look like a good use-case for introducing log levels.
This information is definitely too verbose most of the time, but very useful 
when debugging failures


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D42803



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


[clang-tools-extra] r323992 - [clangd] Log dropped diagnostics.

2018-02-01 Thread Ilya Biryukov via cfe-commits
Author: ibiryukov
Date: Thu Feb  1 11:06:45 2018
New Revision: 323992

URL: http://llvm.org/viewvc/llvm-project?rev=323992=rev
Log:
[clangd] Log dropped diagnostics.

Summary:
clangd drops diagnostics coming outside the main file, but it is still
useful to see that something went wrong in the logs.

Reviewers: hokein, ioeric, sammccall

Reviewed By: sammccall

Subscribers: klimek, jkorous-apple, cfe-commits

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

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

Modified: clang-tools-extra/trunk/clangd/ClangdUnit.cpp
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clangd/ClangdUnit.cpp?rev=323992=323991=323992=diff
==
--- clang-tools-extra/trunk/clangd/ClangdUnit.cpp (original)
+++ clang-tools-extra/trunk/clangd/ClangdUnit.cpp Thu Feb  1 11:06:45 2018
@@ -27,6 +27,7 @@
 #include "llvm/ADT/SmallVector.h"
 #include "llvm/Support/CrashRecoveryContext.h"
 #include "llvm/Support/Format.h"
+#include "llvm/Support/raw_ostream.h"
 #include 
 #include 
 
@@ -178,15 +179,30 @@ TextEdit toTextEdit(const FixItHint 
 llvm::Optional toClangdDiag(const clang::Diagnostic ,
 DiagnosticsEngine::Level Level,
 const LangOptions ) {
+  SmallString<64> Message;
+  D.FormatDiagnostic(Message);
+
   if (!D.hasSourceManager() || !D.getLocation().isValid() ||
-  !D.getSourceManager().isInMainFile(D.getLocation()))
+  !D.getSourceManager().isInMainFile(D.getLocation())) {
+
+SmallString<64> Location;
+if (D.hasSourceManager() && D.getLocation().isValid()) {
+  auto  = D.getSourceManager();
+  auto Loc = SourceMgr.getFileLoc(D.getLocation());
+  llvm::raw_svector_ostream OS(Location);
+  Loc.print(OS, SourceMgr);
+} else {
+  Location = "";
+}
+
+log(llvm::formatv("Ignored diagnostic outside main file. {0}: {1}",
+  Location, Message));
 return llvm::None;
+  }
 
   DiagWithFixIts Result;
   Result.Diag.range = diagnosticRange(D, LangOpts);
   Result.Diag.severity = getSeverity(Level);
-  SmallString<64> Message;
-  D.FormatDiagnostic(Message);
   Result.Diag.message = Message.str();
   for (const FixItHint  : D.getFixItHints())
 Result.FixIts.push_back(toTextEdit(Fix, D.getSourceManager(), LangOpts));


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


[PATCH] D42803: [clangd] Log dropped diagnostics.

2018-02-01 Thread Ilya Biryukov via Phabricator via cfe-commits
ilya-biryukov updated this revision to Diff 132430.
ilya-biryukov added a comment.

- Show location of dropped diagnostic.


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D42803

Files:
  clangd/ClangdUnit.cpp


Index: clangd/ClangdUnit.cpp
===
--- clangd/ClangdUnit.cpp
+++ clangd/ClangdUnit.cpp
@@ -27,6 +27,7 @@
 #include "llvm/ADT/SmallVector.h"
 #include "llvm/Support/CrashRecoveryContext.h"
 #include "llvm/Support/Format.h"
+#include "llvm/Support/raw_ostream.h"
 #include 
 #include 
 
@@ -178,15 +179,30 @@
 llvm::Optional toClangdDiag(const clang::Diagnostic ,
 DiagnosticsEngine::Level Level,
 const LangOptions ) {
+  SmallString<64> Message;
+  D.FormatDiagnostic(Message);
+
   if (!D.hasSourceManager() || !D.getLocation().isValid() ||
-  !D.getSourceManager().isInMainFile(D.getLocation()))
+  !D.getSourceManager().isInMainFile(D.getLocation())) {
+
+SmallString<64> Location;
+if (D.hasSourceManager() && D.getLocation().isValid()) {
+  auto  = D.getSourceManager();
+  auto Loc = SourceMgr.getFileLoc(D.getLocation());
+  llvm::raw_svector_ostream OS(Location);
+  Loc.print(OS, SourceMgr);
+} else {
+  Location = "";
+}
+
+log(llvm::formatv("Ignored diagnostic outside main file. {0}: {1}",
+  Location, Message));
 return llvm::None;
+  }
 
   DiagWithFixIts Result;
   Result.Diag.range = diagnosticRange(D, LangOpts);
   Result.Diag.severity = getSeverity(Level);
-  SmallString<64> Message;
-  D.FormatDiagnostic(Message);
   Result.Diag.message = Message.str();
   for (const FixItHint  : D.getFixItHints())
 Result.FixIts.push_back(toTextEdit(Fix, D.getSourceManager(), LangOpts));


Index: clangd/ClangdUnit.cpp
===
--- clangd/ClangdUnit.cpp
+++ clangd/ClangdUnit.cpp
@@ -27,6 +27,7 @@
 #include "llvm/ADT/SmallVector.h"
 #include "llvm/Support/CrashRecoveryContext.h"
 #include "llvm/Support/Format.h"
+#include "llvm/Support/raw_ostream.h"
 #include 
 #include 
 
@@ -178,15 +179,30 @@
 llvm::Optional toClangdDiag(const clang::Diagnostic ,
 DiagnosticsEngine::Level Level,
 const LangOptions ) {
+  SmallString<64> Message;
+  D.FormatDiagnostic(Message);
+
   if (!D.hasSourceManager() || !D.getLocation().isValid() ||
-  !D.getSourceManager().isInMainFile(D.getLocation()))
+  !D.getSourceManager().isInMainFile(D.getLocation())) {
+
+SmallString<64> Location;
+if (D.hasSourceManager() && D.getLocation().isValid()) {
+  auto  = D.getSourceManager();
+  auto Loc = SourceMgr.getFileLoc(D.getLocation());
+  llvm::raw_svector_ostream OS(Location);
+  Loc.print(OS, SourceMgr);
+} else {
+  Location = "";
+}
+
+log(llvm::formatv("Ignored diagnostic outside main file. {0}: {1}",
+  Location, Message));
 return llvm::None;
+  }
 
   DiagWithFixIts Result;
   Result.Diag.range = diagnosticRange(D, LangOpts);
   Result.Diag.severity = getSeverity(Level);
-  SmallString<64> Message;
-  D.FormatDiagnostic(Message);
   Result.Diag.message = Message.str();
   for (const FixItHint  : D.getFixItHints())
 Result.FixIts.push_back(toTextEdit(Fix, D.getSourceManager(), LangOpts));
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[libcxx] r323989 - Put the exception classes for experimental::optional and experimental::any back in the dylib for binary compatibility

2018-02-01 Thread Marshall Clow via cfe-commits
Author: marshall
Date: Thu Feb  1 10:45:57 2018
New Revision: 323989

URL: http://llvm.org/viewvc/llvm-project?rev=323989=rev
Log:
Put the exception classes for experimental::optional and experimental::any back 
in the dylib for binary compatibility

Modified:
libcxx/trunk/src/any.cpp
libcxx/trunk/src/optional.cpp

Modified: libcxx/trunk/src/any.cpp
URL: 
http://llvm.org/viewvc/llvm-project/libcxx/trunk/src/any.cpp?rev=323989=323988=323989=diff
==
--- libcxx/trunk/src/any.cpp (original)
+++ libcxx/trunk/src/any.cpp Thu Feb  1 10:45:57 2018
@@ -14,3 +14,22 @@ const char* bad_any_cast::what() const _
 return "bad any cast";
 }
 }
+
+
+#include 
+
+//  Preserve std::experimental::any_bad_cast for ABI compatibility
+//  Even though it no longer exists in a header file
+_LIBCPP_BEGIN_NAMESPACE_LFTS
+
+class _LIBCPP_EXCEPTION_ABI _LIBCPP_AVAILABILITY_BAD_ANY_CAST bad_any_cast : 
public bad_cast
+{
+public:
+virtual const char* what() const _NOEXCEPT;
+};
+
+const char* bad_any_cast::what() const _NOEXCEPT {
+return "bad any cast";
+}
+
+_LIBCPP_END_NAMESPACE_LFTS

Modified: libcxx/trunk/src/optional.cpp
URL: 
http://llvm.org/viewvc/llvm-project/libcxx/trunk/src/optional.cpp?rev=323989=323988=323989=diff
==
--- libcxx/trunk/src/optional.cpp (original)
+++ libcxx/trunk/src/optional.cpp Thu Feb  1 10:45:57 2018
@@ -20,3 +20,23 @@ const char* bad_optional_access::what()
 
 } // std
 
+
+#include 
+
+//  Preserve std::experimental::bad_optional_access for ABI compatibility
+//  Even though it no longer exists in a header file
+_LIBCPP_BEGIN_NAMESPACE_EXPERIMENTAL
+
+class _LIBCPP_EXCEPTION_ABI _LIBCPP_AVAILABILITY_BAD_OPTIONAL_ACCESS 
bad_optional_access
+: public std::logic_error
+{
+public:
+   bad_optional_access() : std::logic_error("Bad optional Access") {}
+
+// Get the key function ~bad_optional_access() into the dylib
+virtual ~bad_optional_access() _NOEXCEPT;
+};
+
+bad_optional_access::~bad_optional_access() _NOEXCEPT = default;
+
+_LIBCPP_END_NAMESPACE_EXPERIMENTAL


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


[PATCH] D17700: [clang-format] Proposal for changes to Objective-C block formatting

2018-02-01 Thread Kent Sutherland via Phabricator via cfe-commits
ksuther added a comment.

It seems to have been. I've been using a modified version of clang-format with 
this change applied (as well as http://reviews.llvm.org/D17922) since I 
submitted this.


https://reviews.llvm.org/D17700



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


[PATCH] D42644: [asan] Intercept std::rethrow_exception indirectly.

2018-02-01 Thread Kuba (Brecka) Mracek via Phabricator via cfe-commits
kubamracek added a comment.

> This is our first patch so we're unfamiliar with the LLVM testing 
> infrastructure. Could you please tell us what kind of test you'd like? An 
> example would also be great.

Thank you for your first contribution! I'm going to comment on the testing 
infrastructure only, as I don't know the answer to the portability/mangling/ABI 
question.

Most user-visible features of ASan can usually be demonstrated in a single-file 
test that is completely standalone test program. E.g. ASan's ability to detect 
heap buffer overflows is demonstrated in `test/asan/TestCases/heap-overflow.cc` 
file. Notice that these tests don't include or reference any sanitizer internal 
functions. They are meant to be written in a way that user's code is written. 
Can you try adding such a test, which would be a standalone .cc file that would 
demonstrate the problematic scenario (C++ exception rethrow) without including 
ASan headers? The test's expectation should be that ASan doesn't report any 
issues, whereas without your patch, the test fails (or might fail). For an 
example of a negative test (that checks that ASan *doesn't* report any issues), 
see `test/asan/TestCases/Darwin/nil-return-struct.mm`.

If the test should work on all ASan supported platforms, put it directly into 
`test/asan/TestCases`. If it's POSIX-only, place it under `Posix/` subdirectory.


Repository:
  rCRT Compiler Runtime

https://reviews.llvm.org/D42644



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


[PATCH] D17700: [clang-format] Proposal for changes to Objective-C block formatting

2018-02-01 Thread Daniel Casadevall Pino via Phabricator via cfe-commits
dcasadevall added a comment.

Was this lost in the woods? I believe this is a valid change when working in 
Objective-C


https://reviews.llvm.org/D17700



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


[PATCH] D42800: Let CUDA toolchain support amdgpu target

2018-02-01 Thread Artem Belevich via Phabricator via cfe-commits
tra added a comment.

I don't have enough knowledge about compute on AMD's GPU and would appreciate 
if you could share your thoughts on how you think CUDA on AMD should work. Is 
there a good document describing how compute currently works (how do I launch a 
kernel using rough equivalent of nvidia's driver API 
 ) on AMD GPUs?

- Headers. clang pre-includes *a lot* of headers from NVidia's CUDA SDK. Some 
of them may work for AMD, but some certainly will not -- there are a lot of 
headers with nvidia-specific inline assembly or things that rely on 
nvidia-specific functionality. In the end, I think, we'll need some sort of 
CUDA SDK for AMD which would implement (possibly with asserts for unsupported 
functions) existing CUDA APIs. Or, perhaps the plan is to just use CUDA 
**syntax** only without providing complete API compatibility with nvidia.

- How will GPU-side object file be incorporated into the final executable? I 
believe OpenMP has a fairly generic way to deal with it in clang. I'm not sure 
if that would be suitable for use with AMD's runtime (whatever we need to use 
to launch the kernels).

- Launching kernels. Will it be similar to the way kernel launches are 
configured on NVidia? I.e. grid of blocks of threads with per-block shared 
memory.


https://reviews.llvm.org/D42800



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


[PATCH] D42803: [clangd] Log dropped diagnostics.

2018-02-01 Thread Sam McCall via Phabricator via cfe-commits
sammccall accepted this revision.
sammccall added inline comments.
This revision is now accepted and ready to land.



Comment at: clangd/ClangdUnit.cpp:182
+  SmallString<64> Message;
+  D.FormatDiagnostic(Message);
+

does Message include file:line? we probably want that in the log line.



Comment at: clangd/ClangdUnit.cpp:186
+  !D.getSourceManager().isInMainFile(D.getLocation())) {
+log("Ignored diagnostic outside main file: " + Twine(Message));
 return llvm::None;

Agree this is useful.

Have we turned off the diagnostics limit (or will we?) a misconfig of e.g. C vs 
C++ parsing of a header seems like it could produce 1000+ log lines from 
preamble that we should probably avoid somehow.
(Maybe even avoid paying to format)


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D42803



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


r323986 - Mark fallthrough with LLVM_FALLTHROUGH

2018-02-01 Thread Adrian Prantl via cfe-commits
Author: adrian
Date: Thu Feb  1 10:10:20 2018
New Revision: 323986

URL: http://llvm.org/viewvc/llvm-project?rev=323986=rev
Log:
Mark fallthrough with LLVM_FALLTHROUGH

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

Modified: cfe/trunk/utils/TableGen/NeonEmitter.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/utils/TableGen/NeonEmitter.cpp?rev=323986=323985=323986=diff
==
--- cfe/trunk/utils/TableGen/NeonEmitter.cpp (original)
+++ cfe/trunk/utils/TableGen/NeonEmitter.cpp Thu Feb  1 10:10:20 2018
@@ -948,7 +948,7 @@ void Type::applyModifier(char Mod) {
 break;
   case 'c':
 Constant = true;
-  // Fall through
+LLVM_FALLTHROUGH;
   case 'p':
 Pointer = true;
 Bitwidth = ElementBitwidth;


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


[PATCH] D42736: [DebugInfo] Improvements to representation of enumeration types (PR36168)

2018-02-01 Thread David Blaikie via Phabricator via cfe-commits
dblaikie added inline comments.



Comment at: test/CodeGen/debug-info-enum.cpp:2
+// RUN: %clang -target x86_64-linux -g -S -emit-llvm -o - %s | FileCheck %s
+enum class E0 : signed char {
+  A0 = -128,

Could you summarize the purpose of each of these tests (possibly in a comment 
above the enum in each case) - there look to be more test cases than I'd 
imagine being necessary, but I haven't carefully analyzed them.

For example: I wouldn't expect to test every integer type, if the code handling 
them is general enough to be demonstrated by one or two cases?



Comment at: test/CodeGen/debug-info-enum.cpp:6-10
+// CHECK: !DICompositeType(tag: DW_TAG_enumeration_type, name: "E0"
+// CHECK-SAME: flags: DIFlagFixedEnum
+// CHECK: !DIBasicType(name: "signed char", size: 8, encoding: 
DW_ATE_signed_char)
+// CHECK: !DIEnumerator(name: "A0", value: -128)
+// CHECK: !DIEnumerator(name: "B0", value: 127)

Rather than relying on specific ordering of output, generally you should test 
that the actual references across different metadata records are correct (eg: 
check that the DICompositeType's member list elements are the DIEnumerators 
(use named matches, rather than hardcoding the metadata node numbers))

Though, admittedly, this is a lot easier to read as-is. 



Comment at: test/CodeGen/debug-info-enum.cpp:66
+// CHECK-SAME: baseType: ![[INT]]
+// CHECK-NOT: flags: DIFlagFixedEnum
+// CHECK: !DIEnumerator(name: "A8", value: -128)

Probably drop the "flags: " part of this NOT check - so that if other flags are 
added, this won't be overly constrained (eg: if this type ended up with "flags: 
X | DIFlagFixedEnum" this NOT check as-is wouldn't catch the regression)


https://reviews.llvm.org/D42736



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


[PATCH] D42800: Let CUDA toolchain support amdgpu target

2018-02-01 Thread Matt Arsenault via Phabricator via cfe-commits
arsenm added inline comments.



Comment at: lib/Basic/Targets/AMDGPU.cpp:437
+  case CudaArch::UNKNOWN:
+assert(false && "No GPU arch when compiling CUDA device code.");
+return "";

llvm_unreachable



Comment at: lib/Driver/ToolChains/Cuda.cpp:359-361
+  addBCLib(C, Args, CmdArgs, LibraryPaths, "opencl.amdgcn.bc");
+  addBCLib(C, Args, CmdArgs, LibraryPaths, "ockl.amdgcn.bc");
+  addBCLib(C, Args, CmdArgs, LibraryPaths, "irif.amdgcn.bc");

Why is this done under an NVPTX:: class



Comment at: lib/Driver/ToolChains/Cuda.cpp:390
+  else {
+OptArgs.push_back(Args.MakeArgString("-O2"));
+OptArgs.push_back("-S");

Why is this hardcoded?


https://reviews.llvm.org/D42800



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


[PATCH] D42736: [DebugInfo] Improvements to representation of enumeration types (PR36168)

2018-02-01 Thread Momchil Velikov via Phabricator via cfe-commits
chill updated this revision to Diff 132414.
chill added a comment.

Minor update, the parameter to `createEnumerator` is `IsUnsigned` now (instead 
of `IsSigned`), changed caller.


https://reviews.llvm.org/D42736

Files:
  lib/CodeGen/CGDebugInfo.cpp
  test/CodeGen/debug-info-enum.cpp
  test/CodeGenCXX/debug-info-enum-class.cpp
  test/CodeGenCXX/debug-info-enum.cpp
  test/Modules/ModuleDebugInfo.cpp

Index: test/Modules/ModuleDebugInfo.cpp
===
--- test/Modules/ModuleDebugInfo.cpp
+++ test/Modules/ModuleDebugInfo.cpp
@@ -48,7 +48,7 @@
 // CHECK: !DICompositeType(tag: DW_TAG_enumeration_type,
 // CHECK-NOT:  name:
 // CHECK-SAME: )
-// CHECK: !DIEnumerator(name: "e5", value: 5)
+// CHECK: !DIEnumerator(name: "e5", value: 5, isUnsigned: true)
 
 // CHECK: !DIDerivedType(tag: DW_TAG_typedef, name: "B",
 // no mangled name here yet.
Index: test/CodeGenCXX/debug-info-enum.cpp
===
--- test/CodeGenCXX/debug-info-enum.cpp
+++ test/CodeGenCXX/debug-info-enum.cpp
@@ -11,7 +11,7 @@
 // CHECK-SAME:  identifier: "_ZTSN5test11eE"
 // CHECK: [[TEST1]] = !DINamespace(name: "test1"
 // CHECK: [[TEST1_ENUMS]] = !{[[TEST1_E:![0-9]*]]}
-// CHECK: [[TEST1_E]] = !DIEnumerator(name: "E", value: 0)
+// CHECK: [[TEST1_E]] = !DIEnumerator(name: "E", value: 0, isUnsigned: true)
 enum e { E };
 void foo() {
   int v = E;
Index: test/CodeGenCXX/debug-info-enum-class.cpp
===
--- test/CodeGenCXX/debug-info-enum-class.cpp
+++ test/CodeGenCXX/debug-info-enum-class.cpp
@@ -15,20 +15,20 @@
 // CHECK-SAME: baseType: ![[INT:[0-9]+]]
 // CHECK-SAME: size: 32
 // CHECK-NOT:  offset:
-// CHECK-NOT:  flags:
+// CHECK-SAME: flags: DIFlagFixedEnum
 // CHECK-SAME: ){{$}}
 // CHECK: ![[INT]] = !DIBasicType(name: "int"
 // CHECK: !DICompositeType(tag: DW_TAG_enumeration_type, name: "B"
 // CHECK-SAME: line: 4
 // CHECK-SAME: baseType: ![[ULONG:[0-9]+]]
 // CHECK-SAME: size: 64
 // CHECK-NOT:  offset:
-// CHECK-NOT:  flags:
+// CHECK-SAME: flags: DIFlagFixedEnum
 // CHECK-SAME: ){{$}}
 // CHECK: ![[ULONG]] = !DIBasicType(name: "long unsigned int"
 // CHECK: !DICompositeType(tag: DW_TAG_enumeration_type, name: "C"
 // CHECK-SAME: line: 5
-// CHECK-NOT:  baseType:
+// CHECK-SAME: baseType: ![[ULONG:[0-9]+]]
 // CHECK-SAME: size: 32
 // CHECK-NOT:  offset:
 // CHECK-NOT:  flags:
Index: test/CodeGen/debug-info-enum.cpp
===
--- /dev/null
+++ test/CodeGen/debug-info-enum.cpp
@@ -0,0 +1,68 @@
+// RUN: %clang -target x86_64-linux -g -S -emit-llvm -o - %s | FileCheck %s
+enum class E0 : signed char {
+  A0 = -128,
+  B0 = 127,
+} x0;
+// CHECK: !DICompositeType(tag: DW_TAG_enumeration_type, name: "E0"
+// CHECK-SAME: flags: DIFlagFixedEnum
+// CHECK: !DIBasicType(name: "signed char", size: 8, encoding: DW_ATE_signed_char)
+// CHECK: !DIEnumerator(name: "A0", value: -128)
+// CHECK: !DIEnumerator(name: "B0", value: 127)
+
+enum class E1 : unsigned char { A1 = 255 } x1;
+// CHECK: !DICompositeType(tag: DW_TAG_enumeration_type, name: "E1"
+// CHECK-SAME: flags: DIFlagFixedEnum
+// CHECK: !DIBasicType(name: "unsigned char", size: 8, encoding: DW_ATE_unsigned_char)
+// CHECK: !DIEnumerator(name: "A1", value: 255, isUnsigned: true)
+
+enum class E2 : signed short {
+  A2 = -32768,
+  B2 = 32767,
+} x2;
+// CHECK: !DICompositeType(tag: DW_TAG_enumeration_type, name: "E2"
+// CHECK-SAME: flags: DIFlagFixedEnum
+// CHECK: !DIBasicType(name: "short", size: 16, encoding: DW_ATE_signed)
+// CHECK: !DIEnumerator(name: "A2", value: -32768)
+// CHECK: !DIEnumerator(name: "B2", value: 32767)
+
+enum class E3 : unsigned short { A3 = 65535 } x3;
+// CHECK: !DICompositeType(tag: DW_TAG_enumeration_type, name: "E3"
+// CHECK-SAME: DIFlagFixedEnum
+// CHECK: !DIBasicType(name: "unsigned short", size: 16, encoding: DW_ATE_unsigned)
+// CHECK: !DIEnumerator(name: "A3", value: 65535, isUnsigned: true)
+
+enum class E4 : signed int { A4 = -2147483648, B4 = 2147483647 } x4;
+// CHECK: !DICompositeType(tag: DW_TAG_enumeration_type, name: "E4"
+// CHECK-SAME: flags: DIFlagFixedEnum
+// CHECK: ![[INT:[0-9]+]] = !DIBasicType(name: "int", size: 32, encoding: DW_ATE_signed)
+// CHECK: !DIEnumerator(name: "A4", value: -2147483648)
+// CHECK: !DIEnumerator(name: "B4", value: 2147483647)
+
+enum class E5 : unsigned int { A5 = 4294967295 } x5;
+// CHECK: !DICompositeType(tag: DW_TAG_enumeration_type, name: "E5"
+// CHECK-SAME: flags: DIFlagFixedEnum
+// CHECK: !DIBasicType(name: "unsigned int", size: 32, encoding: DW_ATE_unsigned)
+// CHECK: !DIEnumerator(name: "A5", value: 

[PATCH] D42730: [clang-tidy]] Add check for use of types/classes/functions from header which are deprecated and removed in C++17

2018-02-01 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman added inline comments.



Comment at: clang-tidy/modernize/AvoidFunctionalCheck.h:19
+
+/// Check for several deprecated types and classes from  header
+///

alexfh wrote:
> aaron.ballman wrote:
> > alexfh wrote:
> > > Quuxplusone wrote:
> > > > aaron.ballman wrote:
> > > > > alexfh wrote:
> > > > > > alexfh wrote:
> > > > > > > aaron.ballman wrote:
> > > > > > > > massberg wrote:
> > > > > > > > > massberg wrote:
> > > > > > > > > > aaron.ballman wrote:
> > > > > > > > > > > Missing full stop at the end of the sentence.
> > > > > > > > > > > 
> > > > > > > > > > > Why should this modernize check be limited to 
> > > > > > > > > > > ``? Just like we have a "deprecated headers" 
> > > > > > > > > > > check, perhaps this should be a "deprecated APIs" check?
> > > > > > > > > > Added full stop.
> > > > > > > > > > 
> > > > > > > > > > I'm not sure if this check should be limited to 
> > > > > > > > > >  or be extended to a full 'deprecated API' 
> > > > > > > > > > check.
> > > > > > > > > > This change is just a start, several more types and classes 
> > > > > > > > > > which are removed from  will follow, e.g:
> > > > > > > > > > 
> > > > > > > > > > - std::ptr_fun, std::mem_fun, std::mem_fun_ref
> > > > > > > > > > - std::bind1st, std::bind2nd
> > > > > > > > > > - std::unary_function, std::binary_function
> > > > > > > > > > - std::pointer_to_unary_function, 
> > > > > > > > > > std::pointer_to_binary_function, std::mem_fun_t, 
> > > > > > > > > > std::mem_fun1_t, std::const_mem_fun_t, 
> > > > > > > > > > - std::const_mem_fun1_t, std::mem_fun_ref_t, 
> > > > > > > > > > std::mem_fun1_ref_t, std::const_mem_fun_ref_t, 
> > > > > > > > > > std::const_mem_fun1_ref_t
> > > > > > > > > > - std::binder1st, std::binder2nd
> > > > > > > > > > 
> > > > > > > > > > As these are a bunch of functions and types, in my eyes a 
> > > > > > > > > > check just for  is fine. But I'm also fine with 
> > > > > > > > > > a general 'deprecated API' check.
> > > > > > > > > > Alex, can you comment on this?
> > > > > > > > > There are already other checks for functions which are 
> > > > > > > > > removed in C++17 like modernize-replace-random-shuffle.
> > > > > > > > > So I think having an separate check for functions and types 
> > > > > > > > > removed from  would be OK.
> > > > > > > > You've hit the nail on the head for what I'm trying to avoid -- 
> > > > > > > > we shouldn't have multiple checks unless they do drastically 
> > > > > > > > different things. Having a deprecated check like this really 
> > > > > > > > only makes sense for APIs that are deprecated but aren't 
> > > > > > > > uniformly marked as `[[deprecated]]` by the library. As such, I 
> > > > > > > > think we really only need one check for this rather than 
> > > > > > > > splitting it out over multiple checks -- the existing check 
> > > > > > > > functionality could be rolled into this one and its check 
> > > > > > > > become an alias.
> > > > > > > > I'm not sure if this check should be limited to  or 
> > > > > > > > be extended to a full 'deprecated API' check.
> > > > > > > 
> > > > > > > IIUC, it should be possible to implement fixits at least for some 
> > > > > > > use cases here. My impression was that Jens was at least 
> > > > > > > considering to work on fixits. The other check mentioned here - 
> > > > > > > `modernize-replace-random-shuffle` already implements fixits. 
> > > > > > > Fixits are specific to the API and some codebases may have better 
> > > > > > > replacement APIs than what the standard suggests, so different 
> > > > > > > users may want to apply different set of the fixes. Given all 
> > > > > > > that, I wouldn't just merge all of the checks dealing with 
> > > > > > > deprecated APIs. Splitting them at least by header seems like a 
> > > > > > > good start, maybe even finer granularity may be needed in some 
> > > > > > > cases.
> > > > > > TL;DR "they do drastically different things" is the case for this 
> > > > > > check and modernize-replace-random-shuffle.
> > > > > I disagree that they do drastically different things or that fix-its 
> > > > > are a problem. Some of these APIs have replacements, others do not. 
> > > > > At the end of the day, the basics are the same: the functionality is 
> > > > > deprecated and you should consider a replacement. Sometimes we know 
> > > > > that replacement up front, other times we don't. I don't think we 
> > > > > should make users reach for a per-header file answer to that problem 
> > > > > unless it provides them some benefit. I don't see users caring to 
> > > > > update  but not other headers.
> > > > > 
> > > > > I can see benefit to splitting the *implementations* of the checks 
> > > > > along arbitrary lines, but how we structure the implementation is 
> > > > > orthogonal to how we surface the functionality.
> > > > This sounds like clang-tidy ought to have an umbrella option here, 
> > > > analogous to how -Wformat 

[PATCH] D42530: Clang permits assignment to vector/extvector elements in a const method

2018-02-01 Thread Andrew V. Tischenko via Phabricator via cfe-commits
avt77 added a comment.

In fact we have here another problem: it is not an attempt to assign to const 
variable but it is an attempt to use the field assingment inside const  method: 
I'm working on it.


https://reviews.llvm.org/D42530



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


[PATCH] D42800: Let CUDA toolchain support amdgpu target

2018-02-01 Thread Yaxun Liu via Phabricator via cfe-commits
yaxunl added a comment.

In https://reviews.llvm.org/D42800#994955, @Hahnfeld wrote:

> Only commenting on parts that I'm a bit familiar with. In general, does it 
> make sense to split this patch, are there different "stages" of support? Like 
> 1) being able to compile an empty file, 2) generate optimized code, 3) allow 
> using math functions?


Good suggestion. Actually this patch is mainly to let the toolchain recognise 
the amdgpu implementation of CUDA and create proper stages. I can try to create 
a test for compiling an empty file.


https://reviews.llvm.org/D42800



___
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-02-01 Thread Maxim Ostapenko via Phabricator via cfe-commits
m.ostapenko updated this revision to Diff 132393.
m.ostapenko added a comment.

Fix scope ends order (as discussed above) and adjust a testcase.


Repository:
  rL LLVM

https://reviews.llvm.org/D16403

Files:
  include/clang/Analysis/AnalysisDeclContext.h
  include/clang/Analysis/CFG.h
  include/clang/StaticAnalyzer/Core/AnalyzerOptions.h
  lib/Analysis/AnalysisDeclContext.cpp
  lib/Analysis/CFG.cpp
  lib/StaticAnalyzer/Core/AnalysisManager.cpp
  lib/StaticAnalyzer/Core/AnalyzerOptions.cpp
  lib/StaticAnalyzer/Core/ExprEngine.cpp
  lib/StaticAnalyzer/Core/PathDiagnostic.cpp
  test/Analysis/analyzer-config.c
  test/Analysis/analyzer-config.cpp
  test/Analysis/scopes-cfg-output.cpp

Index: test/Analysis/scopes-cfg-output.cpp
===
--- /dev/null
+++ test/Analysis/scopes-cfg-output.cpp
@@ -0,0 +1,1168 @@
+// RUN: %clang_cc1 -fcxx-exceptions -fexceptions -analyze -analyzer-checker=debug.DumpCFG -analyzer-config cfg-scopes=true %s > %t 2>&1
+// RUN: FileCheck --input-file=%t %s
+
+class A {
+public:
+// CHECK:  [B1 (ENTRY)]
+// CHECK-NEXT:   Succs (1): B0
+// CHECK:  [B0 (EXIT)]
+// CHECK-NEXT:   Preds (1): B1
+  A() {}
+
+// CHECK:  [B1 (ENTRY)]
+// CHECK-NEXT:   Succs (1): B0
+// CHECK:  [B0 (EXIT)]
+// CHECK-NEXT:   Preds (1): B1
+  ~A() {}
+
+// CHECK:  [B2 (ENTRY)]
+// CHECK-NEXT:   Succs (1): B1
+// CHECK:  [B1]
+// CHECK-NEXT:   1: 1
+// CHECK-NEXT:   2: return [B1.1];
+// CHECK-NEXT:   Preds (1): B2
+// CHECK-NEXT:   Succs (1): B0
+// CHECK:  [B0 (EXIT)]
+// CHECK-NEXT:   Preds (1): B1
+  operator int() const { return 1; }
+};
+
+int getX();
+extern const bool UV;
+
+// CHECK:  [B2 (ENTRY)]
+// CHECK-NEXT:   Succs (1): B1
+// CHECK:  [B1]
+// CHECK-NEXT:   1: CFGScopeBegin(a)
+// CHECK-NEXT:   2:  (CXXConstructExpr, class A [2])
+// CHECK-NEXT:   3: A a[2];
+// CHECK-NEXT:   4:  (CXXConstructExpr, class A [0])
+// CHECK-NEXT:   5: A b[0];
+// CHECK-NEXT:   6: [B1.3].~A() (Implicit destructor)
+// CHECK-NEXT:   7: CFGScopeEnd(a)
+// CHECK-NEXT:   Preds (1): B2
+// CHECK-NEXT:   Succs (1): B0
+// CHECK:  [B0 (EXIT)]
+// CHECK-NEXT:   Preds (1): B1
+void test_array() {
+  A a[2];
+  A b[0];
+}
+
+// CHECK:  [B2 (ENTRY)]
+// CHECK-NEXT:   Succs (1): B1
+// CHECK:  [B1]
+// CHECK-NEXT:   1: CFGScopeBegin(a)
+// CHECK-NEXT:   2:  (CXXConstructExpr, class A)
+// CHECK-NEXT:   3: A a;
+// CHECK-NEXT:   4: CFGScopeBegin(c)
+// CHECK-NEXT:   5:  (CXXConstructExpr, class A)
+// CHECK-NEXT:   6: A c;
+// CHECK-NEXT:   7:  (CXXConstructExpr, class A)
+// CHECK-NEXT:   8: A d;
+// CHECK-NEXT:   9: [B1.8].~A() (Implicit destructor)
+// CHECK-NEXT:  10: [B1.6].~A() (Implicit destructor)
+// CHECK-NEXT:  11: CFGScopeEnd(c)
+// CHECK-NEXT:  12:  (CXXConstructExpr, class A)
+// CHECK-NEXT:  13: A b;
+// CHECK-NEXT:  14: [B1.13].~A() (Implicit destructor)
+// CHECK-NEXT:  15: [B1.3].~A() (Implicit destructor)
+// CHECK-NEXT:  16: CFGScopeEnd(a)
+// CHECK-NEXT:   Preds (1): B2
+// CHECK-NEXT:   Succs (1): B0
+// CHECK:  [B0 (EXIT)]
+// CHECK-NEXT:   Preds (1): B1
+void test_scope() {
+  A a;
+  { A c;
+A d;
+  }
+  A b;
+}
+
+// CHECK:  [B4 (ENTRY)]
+// CHECK-NEXT:   Succs (1): B3
+// CHECK:  [B1]
+// CHECK-NEXT:   1:  (CXXConstructExpr, class A)
+// CHECK-NEXT:   2: A c;
+// CHECK-NEXT:   3: [B1.2].~A() (Implicit destructor)
+// CHECK-NEXT:   4: [B3.5].~A() (Implicit destructor)
+// CHECK-NEXT:   5: [B3.3].~A() (Implicit destructor)
+// CHECK-NEXT:   6: CFGScopeEnd(a)
+// CHECK-NEXT:   Preds (1): B3
+// CHECK-NEXT:   Succs (1): B0
+// CHECK:  [B2]
+// CHECK-NEXT:   1: return;
+// CHECK-NEXT:   2: [B3.5].~A() (Implicit destructor)
+// CHECK-NEXT:   3: [B3.3].~A() (Implicit destructor)
+// CHECK-NEXT:   4: CFGScopeEnd(a)
+// CHECK-NEXT:   Preds (1): B3
+// CHECK-NEXT:   Succs (1): B0
+// CHECK:  [B3]
+// CHECK-NEXT:   1: CFGScopeBegin(a)
+// CHECK-NEXT:   2:  (CXXConstructExpr, class A)
+// CHECK-NEXT:   3: A a;
+// CHECK-NEXT:   4:  (CXXConstructExpr, class A)
+// CHECK-NEXT:   5: A b;
+// CHECK-NEXT:   6: UV
+// CHECK-NEXT:   7: [B3.6] (ImplicitCastExpr, LValueToRValue, _Bool)
+// CHECK-NEXT:   T: if [B3.7]
+// CHECK-NEXT:   Preds (1): B4
+// CHECK-NEXT:   Succs (2): B2 B1
+// CHECK:  [B0 (EXIT)]
+// CHECK-NEXT:   Preds (2): B1 B2
+void test_return() {
+  A a;
+  A b;
+  if (UV) return;
+  A c;
+}
+
+// CHECK:  [B5 (ENTRY)]
+// CHECK-NEXT:   Succs (1): B4
+// CHECK:  [B1]
+// CHECK-NEXT:   1: [B4.8].~A() (Implicit destructor)
+// CHECK-NEXT:   2: CFGScopeEnd(b)
+// CHECK-NEXT:   3: [B4.3].~A() (Implicit destructor)
+// CHECK-NEXT:   4: CFGScopeEnd(a)
+// CHECK-NEXT:   Preds (2): B2 B3
+// CHECK-NEXT:   Succs (1): B0
+// CHECK:  [B2]
+// CHECK-NEXT:   1: CFGScopeBegin(c)
+// CHECK-NEXT:   2:  (CXXConstructExpr, class A)
+// CHECK-NEXT:   3: A c;
+// CHECK-NEXT:   4: [B2.3].~A() (Implicit destructor)
+// CHECK-NEXT:   5: CFGScopeEnd(c)
+// CHECK-NEXT:   Preds (1): B4
+// 

[PATCH] D42796: [clangd] Skip inline namespace when collecting scopes for index symbols.

2018-02-01 Thread Sam McCall via Phabricator via cfe-commits
sammccall requested changes to this revision.
sammccall added a comment.
This revision now requires changes to proceed.

Doh, nevermind - SuppressUnwrittenScopes is way simpler. Thanks @hokein for 
catching!


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D42796



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


[PATCH] D42803: [clangd] Log dropped diagnostics.

2018-02-01 Thread Ilya Biryukov via Phabricator via cfe-commits
ilya-biryukov created this revision.
ilya-biryukov added reviewers: hokein, ioeric, sammccall.
Herald added subscribers: jkorous-apple, klimek.

clangd drops diagnostics coming outside the main file, but it is still
useful to see that something went wrong in the logs.


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D42803

Files:
  clangd/ClangdUnit.cpp


Index: clangd/ClangdUnit.cpp
===
--- clangd/ClangdUnit.cpp
+++ clangd/ClangdUnit.cpp
@@ -178,15 +178,18 @@
 llvm::Optional toClangdDiag(const clang::Diagnostic ,
 DiagnosticsEngine::Level Level,
 const LangOptions ) {
+  SmallString<64> Message;
+  D.FormatDiagnostic(Message);
+
   if (!D.hasSourceManager() || !D.getLocation().isValid() ||
-  !D.getSourceManager().isInMainFile(D.getLocation()))
+  !D.getSourceManager().isInMainFile(D.getLocation())) {
+log("Ignored diagnostic outside main file: " + Twine(Message));
 return llvm::None;
+  }
 
   DiagWithFixIts Result;
   Result.Diag.range = diagnosticRange(D, LangOpts);
   Result.Diag.severity = getSeverity(Level);
-  SmallString<64> Message;
-  D.FormatDiagnostic(Message);
   Result.Diag.message = Message.str();
   for (const FixItHint  : D.getFixItHints())
 Result.FixIts.push_back(toTextEdit(Fix, D.getSourceManager(), LangOpts));


Index: clangd/ClangdUnit.cpp
===
--- clangd/ClangdUnit.cpp
+++ clangd/ClangdUnit.cpp
@@ -178,15 +178,18 @@
 llvm::Optional toClangdDiag(const clang::Diagnostic ,
 DiagnosticsEngine::Level Level,
 const LangOptions ) {
+  SmallString<64> Message;
+  D.FormatDiagnostic(Message);
+
   if (!D.hasSourceManager() || !D.getLocation().isValid() ||
-  !D.getSourceManager().isInMainFile(D.getLocation()))
+  !D.getSourceManager().isInMainFile(D.getLocation())) {
+log("Ignored diagnostic outside main file: " + Twine(Message));
 return llvm::None;
+  }
 
   DiagWithFixIts Result;
   Result.Diag.range = diagnosticRange(D, LangOpts);
   Result.Diag.severity = getSeverity(Level);
-  SmallString<64> Message;
-  D.FormatDiagnostic(Message);
   Result.Diag.message = Message.str();
   for (const FixItHint  : D.getFixItHints())
 Result.FixIts.push_back(toTextEdit(Fix, D.getSourceManager(), LangOpts));
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


Re: [PATCH] D34249: [libc++] Don't use UTIME_OMIT to detect utimensat on Apple

2018-02-01 Thread Nico Weber via cfe-commits
(To be clear, the patch as-is is 100% fine with me.)

On Thu, Feb 1, 2018 at 11:44 AM, Duncan P. N. Exon Smith via cfe-commits <
cfe-commits@lists.llvm.org> wrote:

> Using runtime availability checking doesn't make sense for a system
> Libc++, as you point out.  If we add runtime checks they ought to be
> non-default, and hidden behind configuration flags.
>
> Also, do I remember correctly that __builtin_available requires linking
> against Foundation (and thus the Obj-C runtime) for NSProcessInfo, or has
> that dependency been removed/avoided?  It would be surprising for the C++
> standard library to pull in the Objective-C runtime.  A reasonable
> configuration option, but not a reasonable default behaviour IMO.
>
> > On Feb 1, 2018, at 05:52, Nico Weber via Phabricator <
> revi...@reviews.llvm.org> wrote:
> >
> > thakis added a comment.
> >
> > The powers that be updated the SDK on the chromium clang bots, so we
> need some solution for this issue soon.
> >
> > The approach in this patch should work, but it seems conservative. Now
> libc++ only uses utimesat() if it's built with a deployment target of macOS
> 10.13. But if we were to set a deployment target of 10.12 and then _run_ on
> 10.13, we could use utimesat() as well, even though this patch currently
> doesn't. (Apple bundles libc++ with the system, so it's not a meaningful
> difference for Apple-built libc++'s, but applications can build libc++
> themselves and statically link to it, and for those it would make a
> difference.)
> >
> > https://clang.llvm.org/docs/LanguageExtensions.html#
> objective-c-available has some words on it (except that `@available` is
> spelled `__builtin_available` in non-Objective-C code) -- thoughts on using
> runtime detection of utimes() instead? That's how things are supposed to
> work on the Apple platforms.
> >
> >
> > https://reviews.llvm.org/D34249
> >
> >
> >
>
> ___
> cfe-commits mailing list
> cfe-commits@lists.llvm.org
> http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
>
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D42796: [clangd] Skip inline namespace when collecting scopes for index symbols.

2018-02-01 Thread Sam McCall via Phabricator via cfe-commits
sammccall accepted this revision.
sammccall added a comment.
This revision is now accepted and ready to land.

Nice catch, and nice fix! Might be worth adding a motivating example to the 
patch description.




Comment at: clangd/index/SymbolCollector.cpp:68
+// For a symbol "a::b::c", return "a::b::". Scope is empty if there's no
+// qualifier. Inline namespaces and unscoped enums are skipped.
+llvm::Expected getScope(const NamedDecl *ND) {

I'd expand on this for inline namespaces a little, because it's non-obvious. 
e.g.

  // Inline namespaces are treated as transparent scopes.
  // This reflects the way they're most commonly used for lookup.
  // Ideally we'd include them, but at query time it's hard to find all the 
inline
  // namespaces to query: the preamble doesn't have a dedicated list.

Conversely, I don't think you need to explicitly mention unscoped enums 
anymore, because the behavior for transparent scopes is the obvious one, and we 
shouldn't need any special code handling enums (see below suggestions).



Comment at: clangd/index/SymbolCollector.cpp:71
+  llvm::SmallVector Contexts;
+  for (const auto *Context = ND->getDeclContext(); Context;
+   Context = Context->getParent()) {

if the condition is `!Context->isTranslationUnit()` you can skip the break 
inside, which I think reads more naturally. You'll never reach null - only TU 
can have a null parent I think.



Comment at: clangd/index/SymbolCollector.cpp:71
+  llvm::SmallVector Contexts;
+  for (const auto *Context = ND->getDeclContext(); Context;
+   Context = Context->getParent()) {

sammccall wrote:
> if the condition is `!Context->isTranslationUnit()` you can skip the break 
> inside, which I think reads more naturally. You'll never reach null - only TU 
> can have a null parent I think.
uber-nit: I think `DC` is pretty common in clang to refer to a DeclContext - 
once I got used to it, it seems less ambiguous than Context. Up to you though.



Comment at: clangd/index/SymbolCollector.cpp:73
+   Context = Context->getParent()) {
+if (llvm::isa(Context) ||
+llvm::isa(Context))

I'm not sure this is always correct: at least clang accepts this code:

  namespace X { extern "C++" { int y; }}

and you'll emit "y" instead of "X::y".

I think the check you want is

  if (Context->isTransparentContext() || Context->isInlineNamespace())
continue;

 isTransparentContext will handle the Namespace and Enum cases as you do below, 
including the enum/enum class distinction.

(The code you have below is otherwise correct, I think - but a reader needs to 
think about more separate cases in order to see that)



Comment at: clangd/index/SymbolCollector.cpp:76
+  break;
+
+if (const auto *NSD = dyn_cast(Context)) {

With the changes suggested above, I think we only get to this point in these 
cases:
 1. non-inline namespace
 2. decl is in some other named scope (class, scoped enum, ...)

Currently case 2 is symbols we're not indexing: shouldFilterDecl() should be 
false. So this is a programming error. So I think we just want

  Contexts.push_back(cast(Context)->getName());

which includes an assertion. Returning Expected seems weird here - we should 
never hit it unless a precondition is violated.



Comment at: clangd/index/SymbolCollector.cpp:90
+  }
+  std::string Scope = llvm::join(Contexts.rbegin(), Contexts.rend(), "::");
+  if (!Scope.empty())

(nit: might be slightly more obvious just to write the for loop and avoid the 
special case, up to you)



Comment at: clangd/index/SymbolCollector.cpp:113
   // violations.
   if (ND->isInAnonymousNamespace())
 return true;

Hmm, if this is ever hot-path, we may want to eventually combine "determine 
scope" and "shouldFilter" somewhat. shouldFilterDecl is doing much the same 
upwards-scope-traversal, and it seems pretty redundant.

Nothing to do for now though.



Comment at: clangd/index/SymbolCollector.cpp:195
 llvm::SmallString<128> USR;
+if (ND->getIdentifier() == nullptr)
+  return true;

hokein wrote:
> Consider moving to `shouldFilterDecl`? We also have a check `if 
> (ND->getDeclName().isEmpty())` there, which I assume does similar thing. 
hmm, what case is this handling? should `shouldFilterDecl` catch it?



Comment at: unittests/clangd/SymbolCollectorTests.cpp:326
 
+TEST_F(SymbolCollectorTest, Scopes) {
+  const std::string Header = R"(

you could consider modifying one of the testcases to have a weird 
linkage-spec-inside-namespace thing I mentioned :-)


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D42796



___
cfe-commits mailing list

[PATCH] D42800: Let CUDA toolchain support amdgpu target

2018-02-01 Thread Jonas Hahnfeld via Phabricator via cfe-commits
Hahnfeld added a comment.

Only commenting on parts that I'm a bit familiar with. In general, does it make 
sense to split this patch, are there different "stages" of support? Like 1) 
being able to compile an empty file, 2) generate optimized code, 3) allow using 
math functions?




Comment at: lib/Driver/ToolChains/Cuda.cpp:403-415
+  // If Verbose, save input for llc in /tmp and print all symbols
+  if (Args.hasArg(options::OPT_v)) {
+ArgStringList nmArgs;
+nmArgs.push_back(ResultingBitcodeF);
+nmArgs.push_back("-debug-syms");
+const char *nmExec = Args.MakeArgString(C.getDriver().Dir + "/llvm-nm");
+C.addCommand(llvm::make_unique(JA, *this, nmExec, nmArgs, 
Inputs));

This never gets cleaned up!



Comment at: lib/Driver/ToolChains/Cuda.cpp:531-534
+  SmallString<256> OutputFileName(Output.getFilename());
+  if (JA.isOffloading(Action::OFK_OpenMP))
+llvm::sys::path::replace_extension(OutputFileName, "cubin");
+  CmdArgs.push_back(Args.MakeArgString(OutputFileName));

That is already done in `TC.getInputFilename(Output)` (since rC318763), the 
same function call that you are removing here...



Comment at: lib/Driver/ToolChains/Cuda.cpp:639-640
+CmdArgs2.push_back(Args.MakeArgString(Output.getFilename()));
+const char *Exec2 =
+Args.MakeArgString(C.getDriver().Dir + "/clang-fixup-fatbin");
+C.addCommand(

`clang-fixup-fatbin` is not upstreamed and won't work. Sounds like a horrible 
name btw...



Comment at: lib/Driver/ToolChains/Cuda.cpp:788-793
+  // Do not add -link-cuda-bitcode or ptx42 features if gfx
+  for (Arg *A : DriverArgs)
+if (A->getOption().matches(options::OPT_cuda_gpu_arch_EQ) &&
+StringRef(A->getValue()).startswith("gfx"))
+  return;
+

You should use `GpuArch` which comes from `DriverArgs.getLastArgValue`: The 
last `-march` overrides previous arguments.


https://reviews.llvm.org/D42800



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


Re: [PATCH] D34249: [libc++] Don't use UTIME_OMIT to detect utimensat on Apple

2018-02-01 Thread Duncan P. N. Exon Smith via cfe-commits
Using runtime availability checking doesn't make sense for a system Libc++, as 
you point out.  If we add runtime checks they ought to be non-default, and 
hidden behind configuration flags.

Also, do I remember correctly that __builtin_available requires linking against 
Foundation (and thus the Obj-C runtime) for NSProcessInfo, or has that 
dependency been removed/avoided?  It would be surprising for the C++ standard 
library to pull in the Objective-C runtime.  A reasonable configuration option, 
but not a reasonable default behaviour IMO.

> On Feb 1, 2018, at 05:52, Nico Weber via Phabricator 
>  wrote:
> 
> thakis added a comment.
> 
> The powers that be updated the SDK on the chromium clang bots, so we need 
> some solution for this issue soon.
> 
> The approach in this patch should work, but it seems conservative. Now libc++ 
> only uses utimesat() if it's built with a deployment target of macOS 10.13. 
> But if we were to set a deployment target of 10.12 and then _run_ on 10.13, 
> we could use utimesat() as well, even though this patch currently doesn't. 
> (Apple bundles libc++ with the system, so it's not a meaningful difference 
> for Apple-built libc++'s, but applications can build libc++ themselves and 
> statically link to it, and for those it would make a difference.)
> 
> https://clang.llvm.org/docs/LanguageExtensions.html#objective-c-available has 
> some words on it (except that `@available` is spelled `__builtin_available` 
> in non-Objective-C code) -- thoughts on using runtime detection of utimes() 
> instead? That's how things are supposed to work on the Apple platforms.
> 
> 
> https://reviews.llvm.org/D34249
> 
> 
> 

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


[clang-tools-extra] r323980 - [clang-tidy] misc-redundant-expression: fix a crash under ubsan

2018-02-01 Thread Alexander Kornienko via cfe-commits
Author: alexfh
Date: Thu Feb  1 08:39:12 2018
New Revision: 323980

URL: http://llvm.org/viewvc/llvm-project?rev=323980=rev
Log:
[clang-tidy] misc-redundant-expression: fix a crash under ubsan

Modified:
clang-tools-extra/trunk/clang-tidy/misc/RedundantExpressionCheck.cpp
clang-tools-extra/trunk/test/clang-tidy/misc-redundant-expression.cpp

Modified: clang-tools-extra/trunk/clang-tidy/misc/RedundantExpressionCheck.cpp
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clang-tidy/misc/RedundantExpressionCheck.cpp?rev=323980=323979=323980=diff
==
--- clang-tools-extra/trunk/clang-tidy/misc/RedundantExpressionCheck.cpp 
(original)
+++ clang-tools-extra/trunk/clang-tidy/misc/RedundantExpressionCheck.cpp Thu 
Feb  1 08:39:12 2018
@@ -22,7 +22,6 @@
 #include "llvm/Support/Casting.h"
 #include 
 #include 
-#include 
 #include 
 #include 
 #include 
@@ -967,6 +966,13 @@ void RedundantExpressionCheck::checkRela
   }
 }
 
+unsigned intLog2(uint64_t X) {
+  unsigned Result = 0;
+  while (X >>= 1)
+++Result;
+  return Result;
+}
+
 void RedundantExpressionCheck::check(const MatchFinder::MatchResult ) {
   if (const auto *BinOp = Result.Nodes.getNodeAs("binary")) {
 // If the expression's constants are macros, check whether they are
@@ -1043,11 +1049,11 @@ void RedundantExpressionCheck::check(con
 // If ShiftingConst is shifted left with more bits than the position of the
 // leftmost 1 in the bit representation of AndValue, AndConstant is
 // ineffective.
-if (floor(log2(AndValue.getExtValue())) >= ShiftingValue)
+if (intLog2(AndValue.getExtValue()) >= ShiftingValue)
   return;
 
 auto Diag = diag(BinaryAndExpr->getOperatorLoc(),
- "ineffective bitwise and operation.");
+ "ineffective bitwise and operation");
   }
 
   // Check for the following bound expressions:

Modified: clang-tools-extra/trunk/test/clang-tidy/misc-redundant-expression.cpp
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/test/clang-tidy/misc-redundant-expression.cpp?rev=323980=323979=323980=diff
==
--- clang-tools-extra/trunk/test/clang-tidy/misc-redundant-expression.cpp 
(original)
+++ clang-tools-extra/trunk/test/clang-tidy/misc-redundant-expression.cpp Thu 
Feb  1 08:39:12 2018
@@ -674,7 +674,7 @@ int operatorConfusion(int X, int Y, long
 {
   // Ineffective & expressions.
   Y = (Y << 8) & 0xff;
-  // CHECK-MESSAGES: :[[@LINE-1]]:16: warning: ineffective bitwise and 
operation.
+  // CHECK-MESSAGES: :[[@LINE-1]]:16: warning: ineffective bitwise and 
operation
   Y = (Y << 12) & 0xfff;
   // CHECK-MESSAGES: :[[@LINE-1]]:17: warning: ineffective bitwise and
   Y = (Y << 12) & 0xff;
@@ -686,7 +686,7 @@ int operatorConfusion(int X, int Y, long
 
   // Tests for unmatched types
   Z = (Z << 8) & 0xff;
-  // CHECK-MESSAGES: :[[@LINE-1]]:16: warning: ineffective bitwise and 
operation.
+  // CHECK-MESSAGES: :[[@LINE-1]]:16: warning: ineffective bitwise and 
operation
   Y = (Y << 12) & 0xfffL;
   // CHECK-MESSAGES: :[[@LINE-1]]:17: warning: ineffective bitwise and
   Z = (Y << 12) & 0xffLL;
@@ -694,6 +694,11 @@ int operatorConfusion(int X, int Y, long
   Y = (Z << 8L) & 0x77L;
   // CHECK-MESSAGES: :[[@LINE-1]]:17: warning: ineffective bitwise and
 
+  Y = (Y << 8) & 0;
+  // CHECK-MESSAGES: :[[@LINE-1]]:16: warning: ineffective bitwise and
+
+  Y = (Y << 8) & -1;
+
   // Effective expressions. Do not check.
   Y = (Y << 4) & 0x15;
   Y = (Y << 3) & 0x250;


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


[PATCH] D42796: [clangd] Skip inline namespace when collecting scopes for index symbols.

2018-02-01 Thread Haojian Wu via Phabricator via cfe-commits
hokein added inline comments.



Comment at: clangd/index/SymbolCollector.cpp:69
+// qualifier. Inline namespaces and unscoped enums are skipped.
+llvm::Expected getScope(const NamedDecl *ND) {
+  llvm::SmallVector Contexts;

There is a `SuppressUnwrittenScope` option in `PrintingPolicy`,  I think we can 
probably use `printQualifiedName` with our customized policy (setting 
`SuppressUnwrittenScope` to true) here.



Comment at: clangd/index/SymbolCollector.cpp:195
 llvm::SmallString<128> USR;
+if (ND->getIdentifier() == nullptr)
+  return true;

Consider moving to `shouldFilterDecl`? We also have a check `if 
(ND->getDeclName().isEmpty())` there, which I assume does similar thing. 


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D42796



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


[PATCH] D42704: [clang-format] Do not break Objective-C string literals inside array literals

2018-02-01 Thread Ben Hamilton via Phabricator via cfe-commits
benhamilton added a comment.

Ping! Any comments?


Repository:
  rC Clang

https://reviews.llvm.org/D42704



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


[libcxx] r323979 - Remove std::experimental::sample; use std::sample instead. See https://libcxx.llvm.org/TS_deprecation.html

2018-02-01 Thread Marshall Clow via cfe-commits
Author: marshall
Date: Thu Feb  1 08:36:08 2018
New Revision: 323979

URL: http://llvm.org/viewvc/llvm-project?rev=323979=rev
Log:
Remove std::experimental::sample; use std::sample instead. See 
https://libcxx.llvm.org/TS_deprecation.html

Removed:
libcxx/trunk/test/std/experimental/algorithms/alg.random.sample/
Modified:
libcxx/trunk/include/experimental/algorithm

Modified: libcxx/trunk/include/experimental/algorithm
URL: 
http://llvm.org/viewvc/llvm-project/libcxx/trunk/include/experimental/algorithm?rev=323979=323978=323979=diff
==
--- libcxx/trunk/include/experimental/algorithm (original)
+++ libcxx/trunk/include/experimental/algorithm Thu Feb  1 08:36:08 2018
@@ -23,11 +23,8 @@ inline namespace fundamentals_v1 {
 template 
 ForwardIterator search(ForwardIterator first, ForwardIterator last,
const Searcher );
-template 
-SampleIterator sample(PopulationIterator first, PopulationIterator last,
-  SampleIterator out, Distance n,
-  UniformRandomNumberGenerator &);
+
+// sample removed because it's now part of C++17
 
 } // namespace fundamentals_v1
 } // namespace experimental
@@ -56,16 +53,6 @@ _LIBCPP_INLINE_VISIBILITY
 _ForwardIterator search(_ForwardIterator __f, _ForwardIterator __l, const 
_Searcher &__s)
 { return __s(__f, __l).first; }
 
-
-template 
-inline _LIBCPP_INLINE_VISIBILITY
-_SampleIterator sample(_PopulationIterator __first, _PopulationIterator __last,
-   _SampleIterator __output_iter, _Distance __n,
-   _UniformRandomNumberGenerator &&__g) {
-  return _VSTD::__sample(__first, __last, __output_iter, __n, __g);
-}
-
 _LIBCPP_END_NAMESPACE_LFTS
 
 _LIBCPP_POP_MACROS


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


[PATCH] D42800: Let CUDA toolchain support amdgpu target

2018-02-01 Thread Yaxun Liu via Phabricator via cfe-commits
yaxunl created this revision.
yaxunl added reviewers: gregrodgers, jlebar, b-sumner, t-tye, arsenm.
Herald added subscribers: tpr, dstuttard, nhaehnle, wdng, kzhuravl, jholewinski.

Currently CUDA toolchain only supports nvptx.

This patch will let CUDA toolchain support amdgpu target. It can also serve as 
an example for supporting CUDA on other targets.

Patch by Greg Rodgers.
Lit test added by Yaxun Liu.


https://reviews.llvm.org/D42800

Files:
  include/clang/Basic/Cuda.h
  include/clang/Driver/ToolChain.h
  lib/Basic/Cuda.cpp
  lib/Basic/Targets/AMDGPU.cpp
  lib/Basic/Targets/AMDGPU.h
  lib/Basic/Targets/NVPTX.cpp
  lib/Driver/Driver.cpp
  lib/Driver/SanitizerArgs.cpp
  lib/Driver/ToolChain.cpp
  lib/Driver/ToolChains/Clang.cpp
  lib/Driver/ToolChains/Cuda.cpp
  lib/Driver/ToolChains/Cuda.h
  test/Driver/cuda-phases.cu

Index: test/Driver/cuda-phases.cu
===
--- test/Driver/cuda-phases.cu
+++ test/Driver/cuda-phases.cu
@@ -7,22 +7,25 @@
 // REQUIRES: clang-driver
 // REQUIRES: powerpc-registered-target
 // REQUIRES: nvptx-registered-target
-
+// REQUIRES: amdgpu-registered-target
 //
 // Test single gpu architecture with complete compilation.
 //
 // RUN: %clang -target powerpc64le-ibm-linux-gnu -ccc-print-phases --cuda-gpu-arch=sm_30 %s 2>&1 \
-// RUN: | FileCheck -check-prefix=BIN %s
+// RUN: | FileCheck -check-prefixes=BIN,BIN_NV %s
+// RUN: %clang -target powerpc64le-ibm-linux-gnu -ccc-print-phases --cuda-gpu-arch=gfx803 %s 2>&1 \
+// RUN: | FileCheck -check-prefixes=BIN,BIN_AMD %s
 // BIN-DAG: [[P0:[0-9]+]]: input, "{{.*}}cuda-phases.cu", cuda, (host-cuda)
 // BIN-DAG: [[P1:[0-9]+]]: preprocessor, {[[P0]]}, cuda-cpp-output, (host-cuda)
 // BIN-DAG: [[P2:[0-9]+]]: compiler, {[[P1]]}, ir, (host-cuda)
-// BIN-DAG: [[P3:[0-9]+]]: input, "{{.*}}cuda-phases.cu", cuda, (device-cuda, sm_30)
-// BIN-DAG: [[P4:[0-9]+]]: preprocessor, {[[P3]]}, cuda-cpp-output, (device-cuda, sm_30)
-// BIN-DAG: [[P5:[0-9]+]]: compiler, {[[P4]]}, ir, (device-cuda, sm_30)
-// BIN-DAG: [[P6:[0-9]+]]: backend, {[[P5]]}, assembler, (device-cuda, sm_30)
-// BIN-DAG: [[P7:[0-9]+]]: assembler, {[[P6]]}, object, (device-cuda, sm_30)
-// BIN-DAG: [[P8:[0-9]+]]: offload, "device-cuda (nvptx64-nvidia-cuda:sm_30)" {[[P7]]}, object
-// BIN-DAG: [[P9:[0-9]+]]: offload, "device-cuda (nvptx64-nvidia-cuda:sm_30)" {[[P6]]}, assembler
+// BIN_NV-DAG: [[P3:[0-9]+]]: input, "{{.*}}cuda-phases.cu", cuda, (device-cuda, [[ARCH:sm_30]])
+// BIN_AMD-DAG: [[P3:[0-9]+]]: input, "{{.*}}cuda-phases.cu", cuda, (device-cuda, [[ARCH:gfx803]])
+// BIN-DAG: [[P4:[0-9]+]]: preprocessor, {[[P3]]}, cuda-cpp-output, (device-cuda, [[ARCH]])
+// BIN-DAG: [[P5:[0-9]+]]: compiler, {[[P4]]}, ir, (device-cuda, [[ARCH]])
+// BIN-DAG: [[P6:[0-9]+]]: backend, {[[P5]]}, assembler, (device-cuda, [[ARCH]])
+// BIN-DAG: [[P7:[0-9]+]]: assembler, {[[P6]]}, object, (device-cuda, [[ARCH]])
+// BIN-DAG: [[P8:[0-9]+]]: offload, "device-cuda (nvptx64-nvidia-cuda:[[ARCH]])" {[[P7]]}, object
+// BIN-DAG: [[P9:[0-9]+]]: offload, "device-cuda (nvptx64-nvidia-cuda:[[ARCH]])" {[[P6]]}, assembler
 // BIN-DAG: [[P10:[0-9]+]]: linker, {[[P8]], [[P9]]}, cuda-fatbin, (device-cuda)
 // BIN-DAG: [[P11:[0-9]+]]: offload, "host-cuda (powerpc64le-ibm-linux-gnu)" {[[P2]]}, "device-cuda (nvptx64-nvidia-cuda)" {[[P10]]}, ir
 // BIN-DAG: [[P12:[0-9]+]]: backend, {[[P11]]}, assembler, (host-cuda)
@@ -34,11 +37,13 @@
 //
 // RUN: %clang -target powerpc64le-ibm-linux-gnu -ccc-print-phases --cuda-gpu-arch=sm_30 %s -S 2>&1 \
 // RUN: | FileCheck -check-prefix=ASM %s
-// ASM-DAG: [[P0:[0-9]+]]: input, "{{.*}}cuda-phases.cu", cuda, (device-cuda, sm_30)
-// ASM-DAG: [[P1:[0-9]+]]: preprocessor, {[[P0]]}, cuda-cpp-output, (device-cuda, sm_30)
-// ASM-DAG: [[P2:[0-9]+]]: compiler, {[[P1]]}, ir, (device-cuda, sm_30)
-// ASM-DAG: [[P3:[0-9]+]]: backend, {[[P2]]}, assembler, (device-cuda, sm_30)
-// ASM-DAG: [[P4:[0-9]+]]: offload, "device-cuda (nvptx64-nvidia-cuda:sm_30)" {[[P3]]}, assembler
+// RUN: %clang -target powerpc64le-ibm-linux-gnu -ccc-print-phases --cuda-gpu-arch=gfx803 %s -S 2>&1 \
+// RUN: | FileCheck -check-prefix=ASM %s
+// ASM-DAG: [[P0:[0-9]+]]: input, "{{.*}}cuda-phases.cu", cuda, (device-cuda, [[ARCH:sm_30|gfx803]])
+// ASM-DAG: [[P1:[0-9]+]]: preprocessor, {[[P0]]}, cuda-cpp-output, (device-cuda, [[ARCH]])
+// ASM-DAG: [[P2:[0-9]+]]: compiler, {[[P1]]}, ir, (device-cuda, [[ARCH]])
+// ASM-DAG: [[P3:[0-9]+]]: backend, {[[P2]]}, assembler, (device-cuda, [[ARCH]])
+// ASM-DAG: [[P4:[0-9]+]]: offload, "device-cuda (nvptx64-nvidia-cuda:[[ARCH]])" {[[P3]]}, assembler
 // ASM-DAG: [[P5:[0-9]+]]: input, "{{.*}}cuda-phases.cu", cuda, (host-cuda)
 // ASM-DAG: [[P6:[0-9]+]]: preprocessor, {[[P5]]}, cuda-cpp-output, (host-cuda)
 // ASM-DAG: [[P7:[0-9]+]]: compiler, {[[P6]]}, ir, (host-cuda)
@@ -49,23 +54,25 @@
 //
 // RUN: %clang -target powerpc64le-ibm-linux-gnu -ccc-print-phases --cuda-gpu-arch=sm_30 --cuda-gpu-arch=sm_35 %s 2>&1 \
 // 

[PATCH] D42742: [clangd] Use pthread instead of thread_local to support more runtimes.

2018-02-01 Thread James Y Knight via Phabricator via cfe-commits
jyknight added a comment.

Is there some way to figure out what's going on in 
clang-x86_64-linux-selfhost-modules?

I believe there should be no linux builders which are missing this function -- 
it was added to libgcc in 4.8, and we don't support older versions, so I think 
missing this function on a linux build must be a misconfiguration of some sort.


Repository:
  rL LLVM

https://reviews.llvm.org/D42742



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


[PATCH] D42796: [clangd] Skip inline namespace when collecting scopes for index symbols.

2018-02-01 Thread Eric Liu via Phabricator via cfe-commits
ioeric created this revision.
ioeric added reviewers: sammccall, hokein.
Herald added subscribers: cfe-commits, jkorous-apple, ilya-biryukov, klimek.

Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D42796

Files:
  clangd/index/SymbolCollector.cpp
  unittests/clangd/SymbolCollectorTests.cpp

Index: unittests/clangd/SymbolCollectorTests.cpp
===
--- unittests/clangd/SymbolCollectorTests.cpp
+++ unittests/clangd/SymbolCollectorTests.cpp
@@ -201,8 +201,7 @@
   runSymbolCollector(Header, /*Main=*/"");
   EXPECT_THAT(Symbols, UnorderedElementsAre(QName("Red"), QName("Color"),
 QName("Green"), QName("Color2"),
-QName("ns"),
-QName("ns::Black")));
+QName("ns"), QName("ns::Black")));
 }
 
 TEST_F(SymbolCollectorTest, IgnoreNamelessSymbols) {
@@ -324,6 +323,41 @@
   EXPECT_THAT(Symbols, UnorderedElementsAre(QName("Foo")));
 }
 
+TEST_F(SymbolCollectorTest, Scopes) {
+  const std::string Header = R"(
+namespace na {
+class Foo {};
+namespace nb {
+class Bar {};
+}
+}
+  )";
+  runSymbolCollector(Header, /*Main=*/"");
+  EXPECT_THAT(Symbols,
+  UnorderedElementsAre(QName("na"), QName("na::nb"),
+   QName("na::Foo"), QName("na::nb::Bar")));
+}
+
+TEST_F(SymbolCollectorTest, SkipInlineNamespace) {
+  const std::string Header = R"(
+namespace na {
+inline namespace nb {
+class Foo {};
+}
+}
+namespace na {
+// This is still inlined.
+namespace nb {
+class Bar {};
+}
+}
+  )";
+  runSymbolCollector(Header, /*Main=*/"");
+  EXPECT_THAT(Symbols,
+  UnorderedElementsAre(QName("na"), QName("na::nb"),
+   QName("na::Foo"), QName("na::Bar")));
+}
+
 TEST_F(SymbolCollectorTest, SymbolWithDocumentation) {
   const std::string Header = R"(
 namespace nx {
Index: clangd/index/SymbolCollector.cpp
===
--- clangd/index/SymbolCollector.cpp
+++ clangd/index/SymbolCollector.cpp
@@ -9,6 +9,7 @@
 
 #include "SymbolCollector.h"
 #include "../CodeCompletionStrings.h"
+#include "Logger.h"
 #include "clang/AST/DeclCXX.h"
 #include "clang/ASTMatchers/ASTMatchFinder.h"
 #include "clang/Basic/SourceManager.h"
@@ -63,14 +64,33 @@
   return AbsolutePath.str();
 }
 
-// "a::b::c", return {"a::b::", "c"}. Scope is empty if there's no qualifier.
-std::pair
-splitQualifiedName(llvm::StringRef QName) {
-  assert(!QName.startswith("::") && "Qualified names should not start with ::");
-  size_t Pos = QName.rfind("::");
-  if (Pos == llvm::StringRef::npos)
-return {StringRef(), QName};
-  return {QName.substr(0, Pos + 2), QName.substr(Pos + 2)};
+// For a symbol "a::b::c", return "a::b::". Scope is empty if there's no
+// qualifier. Inline namespaces and unscoped enums are skipped.
+llvm::Expected getScope(const NamedDecl *ND) {
+  llvm::SmallVector Contexts;
+  for (const auto *Context = ND->getDeclContext(); Context;
+   Context = Context->getParent()) {
+if (llvm::isa(Context) ||
+llvm::isa(Context))
+  break;
+
+if (const auto *NSD = dyn_cast(Context)) {
+  if (!NSD->isInlineNamespace())
+Contexts.push_back(NSD->getName());
+} else if (const auto *ED = dyn_cast(Context)) {
+  if (ED->isScoped())
+Contexts.push_back(ED->getName());
+} else {
+  return llvm::make_error(
+  llvm::Twine("Unexpected context type ") + Context->getDeclKindName() +
+  " for symbol " + ND->getQualifiedNameAsString(),
+  llvm::inconvertibleErrorCode());
+}
+  }
+  std::string Scope = llvm::join(Contexts.rbegin(), Contexts.rend(), "::");
+  if (!Scope.empty())
+Scope.append("::");
+  return Scope;
 }
 
 bool shouldFilterDecl(const NamedDecl *ND, ASTContext *ASTCtx,
@@ -172,19 +192,27 @@
 if (shouldFilterDecl(ND, ASTCtx, Opts))
   return true;
 llvm::SmallString<128> USR;
+if (ND->getIdentifier() == nullptr)
+  return true;
 if (index::generateUSRForDecl(ND, USR))
   return true;
 
 auto ID = SymbolID(USR);
 if (Symbols.find(ID) != nullptr)
   return true;
 
 auto  = ND->getASTContext().getSourceManager();
-std::string QName = ND->getQualifiedNameAsString();
+auto Scope = getScope(ND);
+if (!Scope) {
+  log(llvm::toString(Scope.takeError()));
+  return true;
+}
+std::string Name = ND->getName();
 
 Symbol S;
 S.ID = std::move(ID);
-std::tie(S.Scope, S.Name) = splitQualifiedName(QName);
+S.Scope = *Scope;
+S.Name = Name;
 S.SymInfo = index::getSymbolInfo(D);
 std::string FilePath;
 S.CanonicalDeclaration = GetSymbolLocation(ND, SM, Opts.FallbackDir, 

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

2018-02-01 Thread Marshall Clow via cfe-commits
Author: marshall
Date: Thu Feb  1 07:49:27 2018
New Revision: 323975

URL: http://llvm.org/viewvc/llvm-project?rev=323975=rev
Log:
Remove ; use  instead. See 
https://libcxx.llvm.org/TS_deprecation.html

Removed:
libcxx/trunk/test/std/experimental/numeric/
Modified:
libcxx/trunk/include/experimental/numeric
libcxx/trunk/include/module.modulemap
libcxx/trunk/test/libcxx/double_include.sh.cpp
libcxx/trunk/test/libcxx/min_max_macros.sh.cpp

Modified: libcxx/trunk/include/experimental/numeric
URL: 
http://llvm.org/viewvc/llvm-project/libcxx/trunk/include/experimental/numeric?rev=323975=323974=323975=diff
==
--- libcxx/trunk/include/experimental/numeric (original)
+++ libcxx/trunk/include/experimental/numeric Thu Feb  1 07:49:27 2018
@@ -8,112 +8,4 @@
 //
 
//===--===//
 
-#ifndef _LIBCPP_EXPERIMENTAL_NUMERIC
-#define _LIBCPP_EXPERIMENTAL_NUMERIC
-/*
-experimental/numeric synopsis
-
-// C++1z
-namespace std {
-namespace experimental {
-inline namespace fundamentals_v2 {
-
-  // 13.1.2, Greatest common divisor
-  template
-  constexpr common_type_t gcd(M m, N n);
-
-  // 13.1.3, Least common multiple
-  template
-  constexpr common_type_t lcm(M m, N n);
-
-} // namespace fundamentals_v2
-} // namespace experimental
-} // namespace std
-
- */
-
-#include 
-#include 
-#include   // is_integral
-#include// numeric_limits
-
-#if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
-#pragma GCC system_header
-#endif
-
-_LIBCPP_PUSH_MACROS
-#include <__undef_macros>
-
-#if _LIBCPP_STD_VER > 11
-
-_LIBCPP_BEGIN_NAMESPACE_LFTS_V2
-
-template ::value> struct __abs;
-
-template 
-struct __abs<_Result, _Source, true> {
-_LIBCPP_CONSTEXPR _LIBCPP_INLINE_VISIBILITY
-_Result operator()(_Source __t) const noexcept
-{
-if (__t >= 0) return __t;
-if (__t == numeric_limits<_Source>::min()) return 
-static_cast<_Result>(__t);
-return -__t;
-}
-};
-
-template 
-struct __abs<_Result, _Source, false> {
-_LIBCPP_CONSTEXPR _LIBCPP_INLINE_VISIBILITY
-_Result operator()(_Source __t) const noexcept { return __t; }
-};
-
-
-template
-_LIBCPP_CONSTEXPR _LIBCPP_HIDDEN
-inline _Tp __gcd(_Tp __m, _Tp __n)
-{
-static_assert((!is_signed<_Tp>::value), "" );
-return __n == 0 ? __m : _VSTD_LFTS_V2::__gcd<_Tp>(__n, __m % __n);
-}
-
-
-template
-_LIBCPP_CONSTEXPR _LIBCPP_INLINE_VISIBILITY
-common_type_t<_Tp,_Up>
-gcd(_Tp __m, _Up __n)
-{
-static_assert((is_integral<_Tp>::value && is_integral<_Up>::value), 
"Arguments to gcd must be integer types");
-static_assert((!is_same::type, bool>::value), 
"First argument to gcd cannot be bool" );
-static_assert((!is_same::type, bool>::value), 
"Second argument to gcd cannot be bool" );
-using _Rp = common_type_t<_Tp,_Up>;
-using _Wp = make_unsigned_t<_Rp>;
-return static_cast<_Rp>(_VSTD_LFTS_V2::__gcd(
-  static_cast<_Wp>(__abs<_Rp, _Tp>()(__m)),
-  static_cast<_Wp>(__abs<_Rp, _Up>()(__n;
-}
-
-template
-_LIBCPP_CONSTEXPR _LIBCPP_INLINE_VISIBILITY
-common_type_t<_Tp,_Up>
-lcm(_Tp __m, _Up __n)
-{
-static_assert((is_integral<_Tp>::value && is_integral<_Up>::value), 
"Arguments to lcm must be integer types");
-static_assert((!is_same::type, bool>::value), 
"First argument to lcm cannot be bool" );
-static_assert((!is_same::type, bool>::value), 
"Second argument to lcm cannot be bool" );
-if (__m == 0 || __n == 0)
-return 0;
-
-using _Rp = common_type_t<_Tp,_Up>;
-_Rp __val1 = __abs<_Rp, _Tp>()(__m) / _VSTD_LFTS_V2::gcd(__m, __n);
-_Rp __val2 = __abs<_Rp, _Up>()(__n);
-_LIBCPP_ASSERT((numeric_limits<_Rp>::max() / __val1 > __val2), "Overflow 
in lcm");
-return __val1 * __val2;
-}
-
-_LIBCPP_END_NAMESPACE_LFTS_V2
-
-#endif /* _LIBCPP_STD_VER > 11 */
-
-_LIBCPP_POP_MACROS
-
-#endif /* _LIBCPP_EXPERIMENTAL_NUMERIC */
+#error " has been removed. Use  instead."

Modified: libcxx/trunk/include/module.modulemap
URL: 
http://llvm.org/viewvc/llvm-project/libcxx/trunk/include/module.modulemap?rev=323975=323974=323975=diff
==
--- libcxx/trunk/include/module.modulemap (original)
+++ libcxx/trunk/include/module.modulemap Thu Feb  1 07:49:27 2018
@@ -538,10 +538,6 @@ module std [system] {
   header "experimental/memory_resource"
   export *
 }
-module numeric {
-  header "experimental/numeric"
-  export *
-}
 module propagate_const {
   header "experimental/propagate_const"
   export *

Modified: libcxx/trunk/test/libcxx/double_include.sh.cpp
URL: 
http://llvm.org/viewvc/llvm-project/libcxx/trunk/test/libcxx/double_include.sh.cpp?rev=323975=323974=323975=diff
==
--- libcxx/trunk/test/libcxx/double_include.sh.cpp 

[PATCH] D42034: [clang-format] In tests, expected code should be format-stable

2018-02-01 Thread Mark Zeren via Phabricator via cfe-commits
mzeren-vmw updated this revision to Diff 132395.
mzeren-vmw added a comment.

- Reviewers: drop euhlmann, add djasper
- Rebase
- Ping


Repository:
  rC Clang

https://reviews.llvm.org/D42034

Files:
  unittests/Format/FormatTest.cpp


Index: unittests/Format/FormatTest.cpp
===
--- unittests/Format/FormatTest.cpp
+++ unittests/Format/FormatTest.cpp
@@ -72,6 +72,7 @@
 
   void verifyFormat(llvm::StringRef Expected, llvm::StringRef Code,
 const FormatStyle  = getLLVMStyle()) {
+EXPECT_EQ(Expected.str(), format(Expected, Style));
 EXPECT_EQ(Expected.str(), format(Code, Style));
 if (Style.Language == FormatStyle::LK_Cpp) {
   // Objective-C++ is a superset of C++, so everything checked for C++


Index: unittests/Format/FormatTest.cpp
===
--- unittests/Format/FormatTest.cpp
+++ unittests/Format/FormatTest.cpp
@@ -72,6 +72,7 @@
 
   void verifyFormat(llvm::StringRef Expected, llvm::StringRef Code,
 const FormatStyle  = getLLVMStyle()) {
+EXPECT_EQ(Expected.str(), format(Expected, Style));
 EXPECT_EQ(Expected.str(), format(Code, Style));
 if (Style.Language == FormatStyle::LK_Cpp) {
   // Objective-C++ is a superset of C++, so everything checked for C++
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


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

2018-02-01 Thread Marshall Clow via cfe-commits
Author: marshall
Date: Thu Feb  1 07:21:14 2018
New Revision: 323972

URL: http://llvm.org/viewvc/llvm-project?rev=323972=rev
Log:
Remove ; use  instead. See 
https://libcxx.llvm.org/TS_deprecation.html

Removed:
libcxx/trunk/test/libcxx/experimental/any/
libcxx/trunk/test/std/experimental/any/
Modified:
libcxx/trunk/include/experimental/any
libcxx/trunk/include/module.modulemap
libcxx/trunk/src/any.cpp
libcxx/trunk/test/libcxx/double_include.sh.cpp
libcxx/trunk/test/libcxx/min_max_macros.sh.cpp

Modified: libcxx/trunk/include/experimental/any
URL: 
http://llvm.org/viewvc/llvm-project/libcxx/trunk/include/experimental/any?rev=323972=323971=323972=diff
==
--- libcxx/trunk/include/experimental/any (original)
+++ libcxx/trunk/include/experimental/any Thu Feb  1 07:21:14 2018
@@ -8,585 +8,4 @@
 //
 
//===--===//
 
-#ifndef _LIBCPP_EXPERIMENTAL_ANY
-#define _LIBCPP_EXPERIMENTAL_ANY
-
-/*
-   experimental/any synopsis
-
-namespace std {
-namespace experimental {
-inline namespace fundamentals_v1 {
-
-  class bad_any_cast : public bad_cast
-  {
-  public:
-virtual const char* what() const noexcept;
-  };
-
-  class any
-  {
-  public:
-
-// 6.3.1 any construct/destruct
-any() noexcept;
-
-any(const any& other);
-any(any&& other) noexcept;
-
-template 
-  any(ValueType&& value);
-
-~any();
-
-// 6.3.2 any assignments
-any& operator=(const any& rhs);
-any& operator=(any&& rhs) noexcept;
-
-template 
-  any& operator=(ValueType&& rhs);
-
-// 6.3.3 any modifiers
-void clear() noexcept;
-void swap(any& rhs) noexcept;
-
-// 6.3.4 any observers
-bool empty() const noexcept;
-const type_info& type() const noexcept;
-  };
-
-   // 6.4 Non-member functions
-  void swap(any& x, any& y) noexcept;
-
-  template
-ValueType any_cast(const any& operand);
-  template
-ValueType any_cast(any& operand);
-  template
-ValueType any_cast(any&& operand);
-
-  template
-const ValueType* any_cast(const any* operand) noexcept;
-  template
-ValueType* any_cast(any* operand) noexcept;
-
-} // namespace fundamentals_v1
-} // namespace experimental
-} // namespace std
-
-*/
-
-#include 
-#include 
-#include 
-#include 
-#include 
-#include 
-
-#if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
-#pragma GCC system_header
-#endif
-
-_LIBCPP_BEGIN_NAMESPACE_LFTS
-
-class _LIBCPP_EXCEPTION_ABI _LIBCPP_AVAILABILITY_BAD_ANY_CAST bad_any_cast : 
public bad_cast
-{
-public:
-virtual const char* what() const _NOEXCEPT;
-};
-
-#if _LIBCPP_STD_VER > 11// C++ > 11
-
-_LIBCPP_NORETURN inline _LIBCPP_ALWAYS_INLINE
-_LIBCPP_AVAILABILITY_THROW_BAD_ANY_CAST
-void __throw_bad_any_cast()
-{
-#ifndef _LIBCPP_NO_EXCEPTIONS
-throw bad_any_cast();
-#else
-_VSTD::abort();
-#endif
-}
-
-// Forward declarations
-class any;
-
-template 
-typename add_pointer::type>::type
-_LIBCPP_INLINE_VISIBILITY
-any_cast(any const *) _NOEXCEPT;
-
-template 
-typename add_pointer<_ValueType>::type
-_LIBCPP_INLINE_VISIBILITY
-any_cast(any *) _NOEXCEPT;
-
-namespace __any_imp
-{
-  typedef typename aligned_storage<3*sizeof(void*), 
alignment_of::value>::type
-_Buffer;
-
-  template 
-  struct _IsSmallObject
-: public integral_constant::value
- % alignment_of<_Tp>::value == 0
-  && is_nothrow_move_constructible<_Tp>::value
->
-  {};
-
-  enum class _Action
-  {
-_Destroy,
-_Copy,
-_Move,
-_Get,
-_TypeInfo
-  };
-
-  template 
-  struct _SmallHandler;
-
-  template 
-  struct _LargeHandler;
-
-  template 
-  using _Handler = typename conditional<_IsSmallObject<_Tp>::value
-  , _SmallHandler<_Tp>
-  , _LargeHandler<_Tp>
->::type;
-  template 
-  using _EnableIfNotAny = typename
-enable_if<
-  !is_same::type, any>::value
->::type;
-
-} // namespace __any_imp
-
-class any
-{
-public:
-  // 6.3.1 any construct/destruct
-  _LIBCPP_INLINE_VISIBILITY
-  any() _NOEXCEPT : __h(nullptr) {}
-
-  _LIBCPP_INLINE_VISIBILITY
-  any(any const & __other) : __h(nullptr)
-  {
-if (__other.__h) __other.__call(_Action::_Copy, this);
-  }
-
-  _LIBCPP_INLINE_VISIBILITY
-  any(any && __other) _NOEXCEPT : __h(nullptr)
-  {
-if (__other.__h) __other.__call(_Action::_Move, this);
-  }
-
-  template <
-  class _ValueType
-, class = __any_imp::_EnableIfNotAny<_ValueType>
->
-  _LIBCPP_INLINE_VISIBILITY
-  any(_ValueType && __value);
-
-  _LIBCPP_INLINE_VISIBILITY
-  ~any()
-  {
-this->clear();
-  }
-
-  // 6.3.2 any assignments
-  _LIBCPP_INLINE_VISIBILITY
-  any & operator=(any const & __rhs)
-  {
-any(__rhs).swap(*this);
-return *this;
-  }
-
-  _LIBCPP_INLINE_VISIBILITY
-  any & 

[PATCH] D42035: [clang-format] Fixup #include guard indents after parseFile()

2018-02-01 Thread Mark Zeren via Phabricator via cfe-commits
mzeren-vmw updated this revision to Diff 132394.
mzeren-vmw added a comment.

- Add comments to IncludeGuardState.
- Fix re-initialization of IncludeGuard in UnwrappedLineParser::reset.
- Remove unnecessary block after if.
- Rebase


Repository:
  rC Clang

https://reviews.llvm.org/D42035

Files:
  lib/Format/UnwrappedLineParser.cpp
  lib/Format/UnwrappedLineParser.h
  unittests/Format/FormatTest.cpp

Index: unittests/Format/FormatTest.cpp
===
--- unittests/Format/FormatTest.cpp
+++ unittests/Format/FormatTest.cpp
@@ -2547,6 +2547,20 @@
"#elif FOO\n"
"#endif",
Style);
+  // Non-identifier #define after potential include guard.
+  verifyFormat("#ifndef FOO\n"
+   "#  define 1\n"
+   "#endif\n",
+   Style);
+  // #if closes past last non-preprocessor line.
+  verifyFormat("#ifndef FOO\n"
+   "#define FOO\n"
+   "#if 1\n"
+   "int i;\n"
+   "#  define A 0\n"
+   "#endif\n"
+   "#endif\n",
+   Style);
   // FIXME: This doesn't handle the case where there's code between the
   // #ifndef and #define but all other conditions hold. This is because when
   // the #define line is parsed, UnwrappedLineParser::Lines doesn't hold the
Index: lib/Format/UnwrappedLineParser.h
===
--- lib/Format/UnwrappedLineParser.h
+++ lib/Format/UnwrappedLineParser.h
@@ -248,10 +248,23 @@
   // sequence.
   std::stack PPChainBranchIndex;
 
-  // Contains the #ifndef condition for a potential include guard.
-  FormatToken *IfNdefCondition;
-  bool FoundIncludeGuardStart;
-  bool IncludeGuardRejected;
+  // Include guard search state. Used to fixup preprocessor indent levels
+  // so that include guards do not participate in indentation.
+  enum IncludeGuardState {
+IG_Inited,   // Search started, looking for #ifndef.
+IG_IfNdefed, // #ifndef found, IncludeGuardToken points to condition.
+IG_Defined,  // Matching #define found, checking other requirements.
+IG_Found,// All requirements met, need to fix indents.
+IG_Rejected, // Search failed or never started.
+  };
+
+  // Current state of include guard search.
+  IncludeGuardState IncludeGuard;
+
+  // Points to the #ifndef condition for a potential include guard. Null unless
+  // IncludeGuardState == IG_IfNdefed.
+  FormatToken *IncludeGuardToken;
+
   // Contains the first start column where the source begins. This is zero for
   // normal source code and may be nonzero when formatting a code fragment that
   // does not start at the beginning of the file.
Index: lib/Format/UnwrappedLineParser.cpp
===
--- lib/Format/UnwrappedLineParser.cpp
+++ lib/Format/UnwrappedLineParser.cpp
@@ -234,14 +234,17 @@
   CurrentLines(), Style(Style), Keywords(Keywords),
   CommentPragmasRegex(Style.CommentPragmas), Tokens(nullptr),
   Callback(Callback), AllTokens(Tokens), PPBranchLevel(-1),
-  IfNdefCondition(nullptr), FoundIncludeGuardStart(false),
-  IncludeGuardRejected(false), FirstStartColumn(FirstStartColumn) {}
+  IncludeGuard(Style.IndentPPDirectives == FormatStyle::PPDIS_None
+   ? IG_Rejected
+   : IG_Inited),
+  IncludeGuardToken(nullptr), FirstStartColumn(FirstStartColumn) {}
 
 void UnwrappedLineParser::reset() {
   PPBranchLevel = -1;
-  IfNdefCondition = nullptr;
-  FoundIncludeGuardStart = false;
-  IncludeGuardRejected = false;
+  IncludeGuard = Style.IndentPPDirectives == FormatStyle::PPDIS_None
+ ? IG_Rejected
+ : IG_Inited;
+  IncludeGuardToken = nullptr;
   Line.reset(new UnwrappedLine);
   CommentsBeforeNextToken.clear();
   FormatTok = nullptr;
@@ -264,6 +267,14 @@
 
 readToken();
 parseFile();
+
+// If we found an include guard then all preprocessor directives (other than
+// the guard) are over-indented by one.
+if (IncludeGuard == IG_Found)
+  for (auto  : Lines)
+if (Line.InPPDirective && Line.Level > 0)
+  --Line.Level;
+
 // Create line with eof token.
 pushToken(FormatTok);
 addUnwrappedLine();
@@ -724,26 +735,27 @@
   // If there's a #ifndef on the first line, and the only lines before it are
   // comments, it could be an include guard.
   bool MaybeIncludeGuard = IfNDef;
-  if (!IncludeGuardRejected && !FoundIncludeGuardStart && MaybeIncludeGuard) {
+  if (IncludeGuard == IG_Inited && MaybeIncludeGuard)
 for (auto  : Lines) {
   if (!Line.Tokens.front().Tok->is(tok::comment)) {
 MaybeIncludeGuard = false;
-IncludeGuardRejected = true;
+IncludeGuard = IG_Rejected;
 break;
   }
 }
-  }
   --PPBranchLevel;
   parsePPUnknown();
   ++PPBranchLevel;
-  if (!IncludeGuardRejected && 

r323956 - Reverting patch rL323952 due to build errors that I

2018-02-01 Thread Sander de Smalen via cfe-commits
Author: s.desmalen
Date: Thu Feb  1 04:27:13 2018
New Revision: 323956

URL: http://llvm.org/viewvc/llvm-project?rev=323956=rev
Log:
Reverting patch rL323952 due to build errors that I
haven't encountered in local builds.


Modified:
cfe/trunk/lib/CodeGen/CGBlocks.cpp
cfe/trunk/lib/CodeGen/CGDebugInfo.cpp
cfe/trunk/lib/CodeGen/CGDebugInfo.h
cfe/trunk/lib/CodeGen/CGDecl.cpp
cfe/trunk/lib/CodeGen/CGExpr.cpp
cfe/trunk/lib/CodeGen/CGExprScalar.cpp
cfe/trunk/lib/CodeGen/CGOpenMPRuntime.cpp
cfe/trunk/lib/CodeGen/CGOpenMPRuntimeNVPTX.cpp
cfe/trunk/lib/CodeGen/CGStmtOpenMP.cpp
cfe/trunk/lib/CodeGen/CodeGenFunction.cpp
cfe/trunk/lib/CodeGen/CodeGenFunction.h
cfe/trunk/test/CodeGen/debug-info-vla.c
cfe/trunk/test/CodeGenCXX/debug-info-vla.cpp
cfe/trunk/test/CodeGenCXX/vla-consruct.cpp
cfe/trunk/test/CodeGenObjC/arc.m
cfe/trunk/test/OpenMP/target_codegen.cpp
cfe/trunk/test/OpenMP/target_parallel_codegen.cpp
cfe/trunk/test/OpenMP/target_parallel_for_codegen.cpp
cfe/trunk/test/OpenMP/target_parallel_for_simd_codegen.cpp
cfe/trunk/test/OpenMP/target_simd_codegen.cpp
cfe/trunk/test/OpenMP/target_teams_codegen.cpp
cfe/trunk/test/OpenMP/target_teams_distribute_codegen.cpp
cfe/trunk/test/OpenMP/target_teams_distribute_simd_codegen.cpp

Modified: cfe/trunk/lib/CodeGen/CGBlocks.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/CodeGen/CGBlocks.cpp?rev=323956=323955=323956=diff
==
--- cfe/trunk/lib/CodeGen/CGBlocks.cpp (original)
+++ cfe/trunk/lib/CodeGen/CGBlocks.cpp Thu Feb  1 04:27:13 2018
@@ -1479,8 +1479,8 @@ CodeGenFunction::GenerateBlockFunction(G
 const CGBlockInfo::Capture  = blockInfo.getCapture(variable);
 if (capture.isConstant()) {
   auto addr = LocalDeclMap.find(variable)->second;
-  (void)DI->EmitDeclareOfAutoVariable(variable, addr.getPointer(),
-  Builder);
+  DI->EmitDeclareOfAutoVariable(variable, addr.getPointer(),
+Builder);
   continue;
 }
 

Modified: cfe/trunk/lib/CodeGen/CGDebugInfo.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/CodeGen/CGDebugInfo.cpp?rev=323956=323955=323956=diff
==
--- cfe/trunk/lib/CodeGen/CGDebugInfo.cpp (original)
+++ cfe/trunk/lib/CodeGen/CGDebugInfo.cpp Thu Feb  1 04:27:13 2018
@@ -2292,14 +2292,12 @@ llvm::DIType *CGDebugInfo::CreateType(co
   llvm::DIFile *Unit) {
   llvm::DIType *ElementTy = getOrCreateType(Ty->getElementType(), Unit);
   int64_t Count = Ty->getNumElements();
+  if (Count == 0)
+// If number of elements are not known then this is an unbounded array.
+// Use Count == -1 to express such arrays.
+Count = -1;
 
-  llvm::Metadata *Subscript;
-  QualType QTy(Ty, 0);
-  auto SizeExpr = SizeExprCache.find(QTy);
-  if (SizeExpr != SizeExprCache.end())
-Subscript = DBuilder.getOrCreateSubrange(0, SizeExpr->getSecond());
-  else
-Subscript = DBuilder.getOrCreateSubrange(0, Count ? Count : -1);
+  llvm::Metadata *Subscript = DBuilder.getOrCreateSubrange(0, Count);
   llvm::DINodeArray SubscriptArray = DBuilder.getOrCreateArray(Subscript);
 
   uint64_t Size = CGM.getContext().getTypeSize(Ty);
@@ -2356,12 +2354,8 @@ llvm::DIType *CGDebugInfo::CreateType(co
   }
 }
 
-auto SizeNode = SizeExprCache.find(EltTy);
-if (SizeNode != SizeExprCache.end())
-  Subscripts.push_back(
-  DBuilder.getOrCreateSubrange(0, SizeNode->getSecond()));
-else
-  Subscripts.push_back(DBuilder.getOrCreateSubrange(0, Count));
+// FIXME: Verify this is right for VLAs.
+Subscripts.push_back(DBuilder.getOrCreateSubrange(0, Count));
 EltTy = Ty->getElementType();
   }
 
@@ -3479,14 +3473,13 @@ llvm::DIType *CGDebugInfo::EmitTypeForVa
nullptr, Elements);
 }
 
-llvm::DILocalVariable *CGDebugInfo::EmitDeclare(const VarDecl *VD,
-llvm::Value *Storage,
-llvm::Optional ArgNo,
-CGBuilderTy ) {
+void CGDebugInfo::EmitDeclare(const VarDecl *VD, llvm::Value *Storage,
+  llvm::Optional ArgNo,
+  CGBuilderTy ) {
   assert(DebugKind >= codegenoptions::LimitedDebugInfo);
   assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
   if (VD->hasAttr())
-return nullptr;
+return;
 
   bool Unwritten =
   VD->isImplicit() || (isa(VD->getDeclContext()) &&
@@ -3504,7 +3497,7 @@ llvm::DILocalVariable *CGDebugInfo::Emit
   // If there is no debug info for this type then do not emit debug info
   // for this variable.
   if (!Ty)
-return nullptr;
+

  1   2   >