[PATCH] D34512: Add preliminary Cross Translation Unit support library

2017-08-29 Thread Devin Coughlin via Phabricator via cfe-commits
dcoughlin added a comment.

> The importing alters the ASTContext, so the only way to choose between the 
> definitions would be via a callback that is triggered before the import is 
> done. What do you think?

I think that could work. Another possibility would be to have a two step 
process. The first step would return a representation of possible definitions 
to import; then the client would chose which one to important and call another 
API to perform the actual import.

In either case, the important scenario I think we should support is choosing at 
a call site to a C function the most likely definition of the called function, 
based on number and type of parameters, from multiple possible definitions in 
other translation units. If the API is rich enough to support this then I think 
that is a good indication it will be useful for other scenarios as well.

> The reason we introduced the diagnostic is that we assumed that the client 
> can not recover from a configuration error and will end up reporting the 
> problem to the user.

For the static analyzer client, at least, one possible recovery is performing 
the existing invalidation that we do when calling a function defined in another 
translation unit. (I'm not really sure this a good idea; I just wanted to point 
out that the decision probably belongs with the client). I think it is 
reasonable to report an error as a diagnostic -- but I think this should be up 
to the client and I don't think it should show up in the index file itself. In 
an ideal world the user wouldn't even know that file existed. Further, for 
large projects/incremental rebuilds a text file is unlikely to be a suitable 
representation for the index. In the long term I doubt the file will be 
end-user editable/readable.


https://reviews.llvm.org/D34512



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


[PATCH] D37231: Add half load and store builtins

2017-08-29 Thread Jan Vesely via Phabricator via cfe-commits
jvesely updated this revision to Diff 113190.
jvesely added a comment.

restrict builtins to OCLC langauges


Repository:
  rL LLVM

https://reviews.llvm.org/D37231

Files:
  include/clang/Basic/Builtins.def
  include/clang/Basic/Builtins.h
  lib/Basic/Builtins.cpp
  lib/CodeGen/CGBuiltin.cpp
  test/CodeGenOpenCL/no-half.cl

Index: test/CodeGenOpenCL/no-half.cl
===
--- /dev/null
+++ test/CodeGenOpenCL/no-half.cl
@@ -0,0 +1,39 @@
+// RUN: %clang_cc1 %s -cl-std=cl2.0 -emit-llvm -o - -triple spir-unknown-unknown | FileCheck %s
+// RUN: %clang_cc1 %s -cl-std=cl1.2 -emit-llvm -o - -triple spir-unknown-unknown | FileCheck %s
+// RUN: %clang_cc1 %s -cl-std=cl1.1 -emit-llvm -o - -triple spir-unknown-unknown | FileCheck %s
+
+#pragma OPENCL EXTENSION cl_khr_fp64:enable
+
+// CHECK-LABEL: @test_store_float(float %foo, half addrspace({{.}}){{.*}} %bar)
+__kernel void test_store_float(float foo, __global half* bar)
+{
+	__builtin_store_halff(foo, bar);
+// CHECK: [[HALF_VAL:%.*]] = fptrunc float %foo to half
+// CHECK: store half [[HALF_VAL]], half addrspace({{.}})* %bar, align 2
+}
+
+// CHECK-LABEL: @test_store_double(double %foo, half addrspace({{.}}){{.*}} %bar)
+__kernel void test_store_double(double foo, __global half* bar)
+{
+	__builtin_store_half(foo, bar);
+// CHECK: [[HALF_VAL:%.*]] = fptrunc double %foo to half
+// CHECK: store half [[HALF_VAL]], half addrspace({{.}})* %bar, align 2
+}
+
+// CHECK-LABEL: @test_load_float(float addrspace({{.}}){{.*}} %foo, half addrspace({{.}}){{.*}} %bar)
+__kernel void test_load_float(__global float* foo, __global half* bar)
+{
+	foo[0] = __builtin_load_halff(bar);
+// CHECK: [[HALF_VAL:%.*]] = load
+// CHECK: [[FULL_VAL:%.*]] = fpext half [[HALF_VAL]] to float
+// CHECK: store float [[FULL_VAL]], float addrspace({{.}})* %foo
+}
+
+// CHECK-LABEL: @test_load_double(double addrspace({{.}}){{.*}} %foo, half addrspace({{.}}){{.*}} %bar)
+__kernel void test_load_double(__global double* foo, __global half* bar)
+{
+	foo[0] = __builtin_load_half(bar);
+// CHECK: [[HALF_VAL:%.*]] = load
+// CHECK: [[FULL_VAL:%.*]] = fpext half [[HALF_VAL]] to double
+// CHECK: store double [[FULL_VAL]], double addrspace({{.}})* %foo
+}
Index: lib/CodeGen/CGBuiltin.cpp
===
--- lib/CodeGen/CGBuiltin.cpp
+++ lib/CodeGen/CGBuiltin.cpp
@@ -2724,6 +2724,24 @@
 Name),
 {NDRange, Block}));
   }
+
+  case Builtin::BI__builtin_store_half:
+  case Builtin::BI__builtin_store_halff: {
+Value *Val = EmitScalarExpr(E->getArg(0));
+Address Address = EmitPointerWithAlignment(E->getArg(1));
+Value *HalfVal = Builder.CreateFPTrunc(Val, Builder.getHalfTy());
+return RValue::get(Builder.CreateStore(HalfVal, Address));
+  }
+  case Builtin::BI__builtin_load_half: {
+Address Address = EmitPointerWithAlignment(E->getArg(0));
+Value *HalfVal = Builder.CreateLoad(Address);
+return RValue::get(Builder.CreateFPExt(HalfVal, Builder.getDoubleTy()));
+  }
+  case Builtin::BI__builtin_load_halff: {
+Address Address = EmitPointerWithAlignment(E->getArg(0));
+Value *HalfVal = Builder.CreateLoad(Address);
+return RValue::get(Builder.CreateFPExt(HalfVal, Builder.getFloatTy()));
+  }
   case Builtin::BIprintf:
 if (getTarget().getTriple().isNVPTX())
   return EmitNVPTXDevicePrintfCallExpr(E, ReturnValue);
Index: lib/Basic/Builtins.cpp
===
--- lib/Basic/Builtins.cpp
+++ lib/Basic/Builtins.cpp
@@ -69,9 +69,14 @@
   bool MSModeUnsupported =
   !LangOpts.MicrosoftExt && (BuiltinInfo.Langs & MS_LANG);
   bool ObjCUnsupported = !LangOpts.ObjC1 && BuiltinInfo.Langs == OBJC_LANG;
-  bool OclCUnsupported = LangOpts.OpenCLVersion != 200 &&
- BuiltinInfo.Langs == OCLC20_LANG;
+  bool OclC1Unsupported = (LangOpts.OpenCLVersion / 100) != 1 &&
+  (BuiltinInfo.Langs & ALL_OCLC_LANGUAGES ) ==  OCLC1X_LANG;
+  bool OclC2Unsupported = LangOpts.OpenCLVersion != 200 &&
+  (BuiltinInfo.Langs & ALL_OCLC_LANGUAGES) == OCLC20_LANG;
+  bool OclCUnsupported = !LangOpts.OpenCL &&
+ (BuiltinInfo.Langs & ALL_OCLC_LANGUAGES);
   return !BuiltinsUnsupported && !MathBuiltinsUnsupported && !OclCUnsupported &&
+ !OclC1Unsupported && !OclC2Unsupported &&
  !GnuModeUnsupported && !MSModeUnsupported && !ObjCUnsupported;
 }
 
Index: include/clang/Basic/Builtins.h
===
--- include/clang/Basic/Builtins.h
+++ include/clang/Basic/Builtins.h
@@ -36,10 +36,12 @@
   CXX_LANG = 0x4, // builtin for cplusplus only.
   OBJC_LANG = 0x8,// builtin for objective-c and objective-c++
   MS_LANG = 0x10, // builtin requires MS mode.
-  OCLC20_LANG = 0x20, // builtin for OpenCL C only.
+  OCLC20_LANG = 0x20, // builtin for OpenCL C 2.0 only.
+  

[PATCH] D33852: Enable __declspec(selectany) on linux

2017-08-29 Thread Piotr Padlewski via Phabricator via cfe-commits
Prazek updated this revision to Diff 113189.
Prazek added a comment.

- Add documentation


https://reviews.llvm.org/D33852

Files:
  include/clang/Basic/Attr.td
  test/Sema/attr-selectany.c
  test/SemaCXX/attr-selectany.cpp


Index: test/SemaCXX/attr-selectany.cpp
===
--- test/SemaCXX/attr-selectany.cpp
+++ test/SemaCXX/attr-selectany.cpp
@@ -1,4 +1,7 @@
 // RUN: %clang_cc1 -triple x86_64-win32 -fms-compatibility -fms-extensions 
-fsyntax-only -verify -std=c++11 %s
+// RUN: %clang_cc1 -triple x86_64-unknown-linux -fms-compatibility 
-fms-extensions -fsyntax-only -verify -std=c++11 %s
+// RUN: %clang_cc1 -triple x86_64-win32-macho -fms-compatibility 
-fms-extensions -fsyntax-only -verify -std=c++11 %s
+
 // MSVC produces similar diagnostics.
 
 __declspec(selectany) void foo() { } // expected-error{{'selectany' can only 
be applied to data items with external linkage}}
Index: test/Sema/attr-selectany.c
===
--- test/Sema/attr-selectany.c
+++ test/Sema/attr-selectany.c
@@ -1,5 +1,7 @@
 // RUN: %clang_cc1 -triple x86_64-win32 -fdeclspec -verify %s
 // RUN: %clang_cc1 -triple x86_64-mingw32 -verify %s
+// RUN: %clang_cc1 -triple x86_64-unknown-linux -verify -fdeclspec %s
+// RUN: %clang_cc1 -triple x86_64-win32-macho -verify -fdeclspec %s
 
 extern __declspec(selectany) const int x1 = 1; // no warning, const means we 
need extern in C++
 
Index: include/clang/Basic/Attr.td
===
--- include/clang/Basic/Attr.td
+++ include/clang/Basic/Attr.td
@@ -2472,9 +2472,10 @@
   let Documentation = [DLLImportDocs];
 }
 
-def SelectAny : InheritableAttr, TargetSpecificAttr {
+def SelectAny : InheritableAttr {
   let Spellings = [Declspec<"selectany">, GCC<"selectany">];
-  let Documentation = [Undocumented];
+  let Documentation = ["This makes global symbol have a weak definition,
+meaning that the linker can select any definition."];
 }
 
 def Thread : Attr {


Index: test/SemaCXX/attr-selectany.cpp
===
--- test/SemaCXX/attr-selectany.cpp
+++ test/SemaCXX/attr-selectany.cpp
@@ -1,4 +1,7 @@
 // RUN: %clang_cc1 -triple x86_64-win32 -fms-compatibility -fms-extensions -fsyntax-only -verify -std=c++11 %s
+// RUN: %clang_cc1 -triple x86_64-unknown-linux -fms-compatibility -fms-extensions -fsyntax-only -verify -std=c++11 %s
+// RUN: %clang_cc1 -triple x86_64-win32-macho -fms-compatibility -fms-extensions -fsyntax-only -verify -std=c++11 %s
+
 // MSVC produces similar diagnostics.
 
 __declspec(selectany) void foo() { } // expected-error{{'selectany' can only be applied to data items with external linkage}}
Index: test/Sema/attr-selectany.c
===
--- test/Sema/attr-selectany.c
+++ test/Sema/attr-selectany.c
@@ -1,5 +1,7 @@
 // RUN: %clang_cc1 -triple x86_64-win32 -fdeclspec -verify %s
 // RUN: %clang_cc1 -triple x86_64-mingw32 -verify %s
+// RUN: %clang_cc1 -triple x86_64-unknown-linux -verify -fdeclspec %s
+// RUN: %clang_cc1 -triple x86_64-win32-macho -verify -fdeclspec %s
 
 extern __declspec(selectany) const int x1 = 1; // no warning, const means we need extern in C++
 
Index: include/clang/Basic/Attr.td
===
--- include/clang/Basic/Attr.td
+++ include/clang/Basic/Attr.td
@@ -2472,9 +2472,10 @@
   let Documentation = [DLLImportDocs];
 }
 
-def SelectAny : InheritableAttr, TargetSpecificAttr {
+def SelectAny : InheritableAttr {
   let Spellings = [Declspec<"selectany">, GCC<"selectany">];
-  let Documentation = [Undocumented];
+  let Documentation = ["This makes global symbol have a weak definition,
+meaning that the linker can select any definition."];
 }
 
 def Thread : Attr {
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D33852: Enable __declspec(selectany) on linux

2017-08-29 Thread Piotr Padlewski via Phabricator via cfe-commits
Prazek added a comment.

In https://reviews.llvm.org/D33852#854213, @aaron.ballman wrote:

> In https://reviews.llvm.org/D33852#854176, @Prazek wrote:
>
> > In https://reviews.llvm.org/D33852#853982, @aaron.ballman wrote:
> >
> > > In https://reviews.llvm.org/D33852#853410, @Prazek wrote:
> > >
> > > > Sorry for so late fixes, but it would be good to put it in 5.0
> > >
> > >
> > > I do not think this should be in 5.0, as I believe we're only accepting 
> > > regression fixes at this point.
> >
> >
> > This is a regression. __declspec(selectany) works completely fine on linux 
> > with 4.0. Without it clang-5.0 will be useless for any major windows 
> > project compiled on linux.
> >
> > edit:
> >  here is a regression: https://reviews.llvm.org/D32083
>
>
> This is also adding new functionality that has had zero testing because it 
> removes *all* target-specific checking for the attribute. Under the previous 
> functionality (changed in https://reviews.llvm.org/D32083), this still 
> required some mention of microsoft something (it went from requiring 
> microsoft extensions to be enabled to instead require a Windows target) -- 
> that's been entirely removed from this patch so now you can use this 
> attribute for all target architectures, so it's not purely fixing a 
> regression. Given how late we are in the release cycle, I am uncomfortable 
> with this going in to 5.0, but I'd have no problems letting it bake for a bit 
> and putting it into 5.1 (or 5.0.1, however we're naming bug releases these 
> days).


I don't think this is the case - @rnk said that

> I guess so. I think __declspec spellings are controlled by 
> -fdeclspec-extensions, which is off by default except on Windows & PS4. If we 
> remove this constraint, __attribute__((selectany)) will become available 
> everywhere. I guess that's OK.

So we went from requiring ms extension to not requiring ms extension but only 
working on windows and now 
we require -fdeclspec-extensions or -fms-extensions on every platform other 
than windows and ps4.


https://reviews.llvm.org/D33852



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


[PATCH] D33719: Add _Float16 as a C/C++ source language type

2017-08-29 Thread Richard Smith - zygoloid via Phabricator via cfe-commits
rsmith added inline comments.



Comment at: lib/Sema/SemaExpr.cpp:727-728
+  // promote to double.
+  // Note that there is default argument promotion for '_Float16'; this
+  // applies to the standard floating types only.
   const BuiltinType *BTy = Ty->getAs();

Do you mean "there is no default argument promotion for '_Float16'"? I think 
you could be even more specific: default argument promotion applies only to 
`float`. (And apparently to `__half` / `__fp16`.)



Comment at: test/Frontend/float16.cpp:1-2
+// RUN: %clang_cc1 -std=c++11 -ast-dump %s | FileCheck %s
+// RUN: %clang_cc1 -std=c++11 -ast-dump -fnative-half-type %s | FileCheck %s 
--check-prefix=CHECK-NATIVE
+

If you're going to check the tree structure from an AST dump, you should turn 
on --strict-whitespace in FileCheck.


https://reviews.llvm.org/D33719



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


[PATCH] D37023: [analyzer] Fix bugreporter::getDerefExpr() again.

2017-08-29 Thread Devin Coughlin via Phabricator via cfe-commits
dcoughlin added a comment.

This seems like it is on the right track, but I think the emphasis here on 
lvalue-to-rvalue casts is a bit misplaced. The logic for "what is the pointer 
being dereferenced" and "what is the lvalue that holds the pointer being 
dereferenced" is mixed together in a way that I find confusing.

I think an easier to understand approach is to first find the rvalue of the 
pointer being dereferenced. Then, second, pattern match on that to find the 
underlying lvalue the pointer was loaded from (when possible).

But first a couple of points just to make sure we're on the same page (with 
apologies for the wall of text!). Suppose we have:

  struct Y {
 ...
 int z;
  };
  
  struct X {
...
Y y;
  };

and a local 'x' of type `X *`.

For an access of the form `int l = x->y.z` the pointer being dereferenced is 
the rvalue `x`. The dereference ultimately results in a load from memory, but 
the address loaded from may be different from the the pointer being 
dereferenced. Here, for example, the address loaded from is (the rvalue of) `x` 
+ "offset of field y into X" + "offset of field z into Y".

Fundamentally, given an expression representing the lvalue that will be loaded 
from, the way to find the rvalue of the pointer being dereferenced is to strip 
off the parts of the expression representing addition of offsets and any 
identity-preserving casts until you get to the expression that represents the 
rvalue of the base address. (This is why stripping off unary `*` makes sense -- 
in an lvalue context it represents adding an offset of 0. This is also why 
stripping off lvalue-to-rvalue casts doesn't make sense -- they do not preserve 
identity nor add an offset)

For `int l = x->y.z,` the expression for the pointer being dereferenced is the 
lvalue-to-rvalue cast that loads the value stored in local variable `x` from 
the lvalue that represents the address of the local variable `x`. But note that 
the pointer being dereferenced won't always be an lvalue-to-rvalue cast. For 
example in `int l = returnsPointerToAnX()->y.z` the expression for the pointer 
being dereferenced is the call expression `returnsPointerToAnX()`. There is no 
lvalue in sight.

Now, the existing behavior of `getDerefExpr()` requires that it return the 
lvalue representing the location containing the dereferenced pointer when 
possible. This is required by `trackNullOrUndefValue()` (sigh). So I suggest, 
for now, first finding the rvalue for the dereferenced value and then adding a 
fixup at the end of `getDerefExpr()` that looks to see whether the rvalue for 
the dereferenced pointer is an lvalue-to-rvalue cast. If so, the fixup will 
return the sub expression representing the lvalue.




Comment at: lib/StaticAnalyzer/Core/BugReporterVisitors.cpp:46
+/// Given that expression S represents a pointer that would be dereferenced,
+/// try to find the immediate sub-expression that represents the pointer
+/// which is being dereferenced.

An interesting aspect of this function is that sometimes it returns a 
sub-expression that represents the pointer rvalue and sometimes it returns a 
sub-expression that represents the lvalue whose location contains the pointer 
which is being dereferenced.

I believe the reason we need the lvalue is that trackNullOrUndef() tracks 
lvalues better than rvalues. (That function loads from the lvalue to get the 
symbol representing the dereferenced pointer value.)

This behavior is pretty confusing, so we should document it in the comment.



Comment at: lib/StaticAnalyzer/Core/BugReporterVisitors.cpp:48
+/// which is being dereferenced.
+/// For example, for 'x->y.z = 2' the answer would be 'x->y' (without the
+/// implicit lvalue-to-rvalue cast surrounding it); then, for 'x->y' (again,

This comment is not right. For `x->y.z = 2` the answer should be `x` and not 
`x->y`.


https://reviews.llvm.org/D37023



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


r312085 - Give a better error if auto deduction fails due to inconsistent element types in a braced initializer list.

2017-08-29 Thread Richard Smith via cfe-commits
Author: rsmith
Date: Tue Aug 29 17:44:08 2017
New Revision: 312085

URL: http://llvm.org/viewvc/llvm-project?rev=312085=rev
Log:
Give a better error if auto deduction fails due to inconsistent element types 
in a braced initializer list.

Modified:
cfe/trunk/include/clang/Basic/DiagnosticSemaKinds.td
cfe/trunk/lib/Sema/SemaTemplateDeduction.cpp
cfe/trunk/test/SemaCXX/cxx0x-initializer-stdinitializerlist.cpp

Modified: cfe/trunk/include/clang/Basic/DiagnosticSemaKinds.td
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Basic/DiagnosticSemaKinds.td?rev=312085=312084=312085=diff
==
--- cfe/trunk/include/clang/Basic/DiagnosticSemaKinds.td (original)
+++ cfe/trunk/include/clang/Basic/DiagnosticSemaKinds.td Tue Aug 29 17:44:08 
2017
@@ -1984,6 +1984,9 @@ def err_auto_var_deduction_failure_from_
   "cannot deduce actual type for variable %0 with type %1 from initializer 
list">;
 def err_auto_new_deduction_failure : Error<
   "new expression for type %0 has incompatible constructor argument of type 
%1">;
+def err_auto_inconsistent_deduction : Error<
+  "deduced conflicting types %diff{($ vs $) |}0,1"
+  "for initializer list element type">;
 def err_auto_different_deductions : Error<
   "%select{'auto'|'decltype(auto)'|'__auto_type'|template arguments}0 "
   "deduced as %1 in declaration of %2 and "

Modified: cfe/trunk/lib/Sema/SemaTemplateDeduction.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Sema/SemaTemplateDeduction.cpp?rev=312085=312084=312085=diff
==
--- cfe/trunk/lib/Sema/SemaTemplateDeduction.cpp (original)
+++ cfe/trunk/lib/Sema/SemaTemplateDeduction.cpp Tue Aug 29 17:44:08 2017
@@ -2907,17 +2907,26 @@ Sema::SubstituteExplicitTemplateArgument
 
 /// \brief Check whether the deduced argument type for a call to a function
 /// template matches the actual argument type per C++ [temp.deduct.call]p4.
-static bool
-CheckOriginalCallArgDeduction(Sema , Sema::OriginalCallArg OriginalArg,
+static Sema::TemplateDeductionResult
+CheckOriginalCallArgDeduction(Sema , TemplateDeductionInfo ,
+  Sema::OriginalCallArg OriginalArg,
   QualType DeducedA) {
   ASTContext  = S.Context;
 
+  auto Failed = [&]() -> Sema::TemplateDeductionResult {
+Info.FirstArg = TemplateArgument(DeducedA);
+Info.SecondArg = TemplateArgument(OriginalArg.OriginalArgType);
+Info.CallArgIndex = OriginalArg.ArgIdx;
+return OriginalArg.DecomposedParam ? Sema::TDK_DeducedMismatchNested
+   : Sema::TDK_DeducedMismatch;
+  };
+
   QualType A = OriginalArg.OriginalArgType;
   QualType OriginalParamType = OriginalArg.OriginalParamType;
 
   // Check for type equality (top-level cv-qualifiers are ignored).
   if (Context.hasSameUnqualifiedType(A, DeducedA))
-return false;
+return Sema::TDK_Success;
 
   // Strip off references on the argument types; they aren't needed for
   // the following checks.
@@ -2941,7 +2950,7 @@ CheckOriginalCallArgDeduction(Sema , S
 // the deduced A can be F.
 QualType Tmp;
 if (A->isFunctionType() && S.IsFunctionConversion(A, DeducedA, Tmp))
-  return false;
+  return Sema::TDK_Success;
 
 Qualifiers AQuals = A.getQualifiers();
 Qualifiers DeducedAQuals = DeducedA.getQualifiers();
@@ -2961,7 +2970,7 @@ CheckOriginalCallArgDeduction(Sema , S
 if (AQuals == DeducedAQuals) {
   // Qualifiers match; there's nothing to do.
 } else if (!DeducedAQuals.compatiblyIncludes(AQuals)) {
-  return true;
+  return Failed();
 } else {
   // Qualifiers are compatible, so have the argument type adopt the
   // deduced argument type's qualifiers as if we had performed the
@@ -2982,7 +2991,7 @@ CheckOriginalCallArgDeduction(Sema , S
   (S.IsQualificationConversion(A, DeducedA, false,
ObjCLifetimeConversion) ||
S.IsFunctionConversion(A, DeducedA, ResultTy)))
-return false;
+return Sema::TDK_Success;
 
   //- If P is a class and P has the form simple-template-id, then the
   //  transformed A can be a derived class of the deduced A. [...]
@@ -3003,13 +3012,13 @@ CheckOriginalCallArgDeduction(Sema , S
   }
 
   if (Context.hasSameUnqualifiedType(A, DeducedA))
-return false;
+return Sema::TDK_Success;
 
   if (A->isRecordType() && isSimpleTemplateIdType(OriginalParamType) &&
   S.IsDerivedFrom(SourceLocation(), A, DeducedA))
-return false;
+return Sema::TDK_Success;
 
-  return true;
+  return Failed();
 }
 
 /// Find the pack index for a particular parameter index in an instantiation of
@@ -3165,13 +3174,9 @@ Sema::TemplateDeductionResult Sema::Fini
 DeducedA = CacheEntry;
   }
 
-  if (CheckOriginalCallArgDeduction(*this, OriginalArg, DeducedA)) {
-Info.FirstArg = 

[PATCH] D37038: Replace temp MD nodes with unique/distinct before cloning

2017-08-29 Thread Paul Robinson via Phabricator via cfe-commits
probinson added a comment.

In https://reviews.llvm.org/D37038#89, @aprantl wrote:

> This may have gotten lost earlier:  Would it be possible to instruct 
> CloneFunction to not clone any temporary MDNodes via one of the flags that 
> are passed to the ValueMapper?


I tried that.  Basically, the new flag just disabled all the `isUniqued` 
assertions.  What I found for test case 1 is that the DIE for CharlieImpl was 
duplicated, but there was only one copy of Charlie.  This is, hmmm, less bad (I 
hesitate to say "better") than the original patch, which duplicated both 
CharlieImpl and Charlie.  Obviously we'd rather not duplicate anything.


https://reviews.llvm.org/D37038



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


[PATCH] D37042: Teach clang to tolerate the 'p = nullptr + n' idiom used by glibc

2017-08-29 Thread Eli Friedman via Phabricator via cfe-commits
efriedma added inline comments.



Comment at: lib/Sema/SemaExpr.cpp:8808
+Context.getTypeSize(pointerType) == 
+Context.getTypeSize(IExp->getType()))
+  IsGNUIdiom = true;

andrew.w.kaylor wrote:
> efriedma wrote:
> > rsmith wrote:
> > > andrew.w.kaylor wrote:
> > > > efriedma wrote:
> > > > > Please make sure you use exactly the same check in Sema and CodeGen 
> > > > > (probably easiest to stick a helper into lib/AST/).
> > > > That's a good idea, but I'm not really familiar enough with the 
> > > > structure of clang to be sure I'm not doing it in a ham-fisted way.  
> > > > Can you clarify?  Are you suggesting adding something like 
> > > > ASTContext::isPointeeTypeCharSize() and 
> > > > ASTContext::isIntegerTypePointerSize()?  Or maybe a single specialized 
> > > > function somewhere that does both checks like 
> > > > ASTContext::areOperandNullPointerArithmeticCompatible()?
> > > I would suggest something even more specific, such as 
> > > `isNullPointerPlusIntegerExtension`
> > I'm most concerned about the difference between 
> > "isa(pointer)" and 
> > "PExp->IgnoreParenCasts()->isNullPointerConstant()"... they're different in 
> > important ways.
> > 
> > I was thinking something like 
> > "BinaryOperator::isNullPointerArithmeticExtension()"
> At this point in Sema the BinaryOperator for the addition hasn't been created 
> yet, right?  So a static function that takes the opcode and operands?
I wasn't really thinking about that... but yes, something like that.


https://reviews.llvm.org/D37042



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


[PATCH] D35216: [analyzer] Escape symbols when creating std::initializer_list.

2017-08-29 Thread Richard Smith - zygoloid via Phabricator via cfe-commits
rsmith added a comment.

The `CXXStdInitializerListExpr` node has pretty simple evaluation semantics: it 
takes a glvalue array expression, and constructs a `std::initializer_list` 
from it as if by filling in the two members with a pointer to the array and 
either the size of the array or a pointer to its end. Can we not model those 
semantics directly here?


https://reviews.llvm.org/D35216



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


[PATCH] D37156: [SanitizeCoverage] Enable stack-depth coverage for -fsanitize=fuzzer

2017-08-29 Thread Matt Morehouse via Phabricator via cfe-commits
morehouse updated this revision to Diff 113177.
morehouse added a comment.

- Only enable stack depth tracking on Linux.
- Ignore __sancov_lowest_stack in interface symbols tests.


https://reviews.llvm.org/D37156

Files:
  clang/lib/Driver/SanitizerArgs.cpp
  compiler-rt/lib/sanitizer_common/sanitizer_coverage_libcdep_new.cc
  compiler-rt/lib/sanitizer_common/sanitizer_internal_defs.h
  compiler-rt/test/asan/TestCases/Darwin/interface_symbols_darwin.c
  compiler-rt/test/asan/TestCases/Linux/interface_symbols_linux.c
  compiler-rt/test/asan/TestCases/Windows/interface_symbols_windows.c
  compiler-rt/test/fuzzer/deep-recursion.test
  llvm/lib/Transforms/Instrumentation/SanitizerCoverage.cpp
  llvm/test/Instrumentation/SanitizerCoverage/stack-depth.ll

Index: llvm/test/Instrumentation/SanitizerCoverage/stack-depth.ll
===
--- llvm/test/Instrumentation/SanitizerCoverage/stack-depth.ll
+++ llvm/test/Instrumentation/SanitizerCoverage/stack-depth.ll
@@ -1,9 +1,9 @@
 ; This check verifies that stack depth instrumentation works correctly.
 ; RUN: opt < %s -sancov -sanitizer-coverage-level=1 \
-; RUN: -sanitizer-coverage-stack-depth -S | FileCheck %s --enable-var-scope
+; RUN: -sanitizer-coverage-stack-depth -S | FileCheck %s
 ; RUN: opt < %s -sancov -sanitizer-coverage-level=3 \
 ; RUN: -sanitizer-coverage-stack-depth -sanitizer-coverage-trace-pc-guard \
-; RUN: -S | FileCheck %s --enable-var-scope
+; RUN: -S | FileCheck %s
 
 target datalayout = "e-m:e-i64:64-f80:128-n8:16:32:64-S128"
 target triple = "x86_64-unknown-linux-gnu"
@@ -14,13 +14,8 @@
 define i32 @foo() {
 entry:
 ; CHECK-LABEL: define i32 @foo
-; CHECK: [[framePtr:%[^ \t]+]] = call i8* @llvm.frameaddress(i32 0)
-; CHECK: [[frameInt:%[^ \t]+]] = ptrtoint i8* [[framePtr]] to [[$intType:i[0-9]+]]
-; CHECK: [[lowest:%[^ \t]+]] = load [[$intType]], [[$intType]]* @__sancov_lowest_stack
-; CHECK: [[cmp:%[^ \t]+]] = icmp ult [[$intType]] [[frameInt]], [[lowest]]
-; CHECK: br i1 [[cmp]], label %[[ifLabel:[^ \t]+]], label
-; CHECK: :[[ifLabel]]:
-; CHECK: store [[$intType]] [[frameInt]], [[$intType]]* @__sancov_lowest_stack
+; CHECK-NOT: call i8* @llvm.frameaddress(i32 0)
+; CHECK-NOT: @__sancov_lowest_stack
 ; CHECK: ret i32 7
 
   ret i32 7
@@ -30,12 +25,12 @@
 entry:
 ; CHECK-LABEL: define i32 @bar
 ; CHECK: [[framePtr:%[^ \t]+]] = call i8* @llvm.frameaddress(i32 0)
-; CHECK: [[frameInt:%[^ \t]+]] = ptrtoint i8* [[framePtr]] to [[$intType]]
-; CHECK: [[lowest:%[^ \t]+]] = load [[$intType]], [[$intType]]* @__sancov_lowest_stack
-; CHECK: [[cmp:%[^ \t]+]] = icmp ult [[$intType]] [[frameInt]], [[lowest]]
+; CHECK: [[frameInt:%[^ \t]+]] = ptrtoint i8* [[framePtr]] to [[intType:i[0-9]+]]
+; CHECK: [[lowest:%[^ \t]+]] = load [[intType]], [[intType]]* @__sancov_lowest_stack
+; CHECK: [[cmp:%[^ \t]+]] = icmp ult [[intType]] [[frameInt]], [[lowest]]
 ; CHECK: br i1 [[cmp]], label %[[ifLabel:[^ \t]+]], label
 ; CHECK: :[[ifLabel]]:
-; CHECK: store [[$intType]] [[frameInt]], [[$intType]]* @__sancov_lowest_stack
+; CHECK: store [[intType]] [[frameInt]], [[intType]]* @__sancov_lowest_stack
 ; CHECK: %call = call i32 @foo()
 ; CHECK: ret i32 %call
 
Index: llvm/lib/Transforms/Instrumentation/SanitizerCoverage.cpp
===
--- llvm/lib/Transforms/Instrumentation/SanitizerCoverage.cpp
+++ llvm/lib/Transforms/Instrumentation/SanitizerCoverage.cpp
@@ -25,6 +25,7 @@
 #include "llvm/IR/GlobalVariable.h"
 #include "llvm/IR/IRBuilder.h"
 #include "llvm/IR/InlineAsm.h"
+#include "llvm/IR/IntrinsicInst.h"
 #include "llvm/IR/Intrinsics.h"
 #include "llvm/IR/LLVMContext.h"
 #include "llvm/IR/MDBuilder.h"
@@ -200,13 +201,15 @@
  ArrayRef GepTraceTargets);
   void InjectTraceForSwitch(Function ,
 ArrayRef SwitchTraceTargets);
-  bool InjectCoverage(Function , ArrayRef AllBlocks);
+  bool InjectCoverage(Function , ArrayRef AllBlocks,
+  bool IsLeafFunc = true);
   GlobalVariable *CreateFunctionLocalArrayInSection(size_t NumElements,
 Function , Type *Ty,
 const char *Section);
   GlobalVariable *CreatePCArray(Function , ArrayRef AllBlocks);
   void CreateFunctionLocalArrays(Function , ArrayRef AllBlocks);
-  void InjectCoverageAtBlock(Function , BasicBlock , size_t Idx);
+  void InjectCoverageAtBlock(Function , BasicBlock , size_t Idx,
+ bool IsLeafFunc = true);
   Function *CreateInitCallsForSections(Module , const char *InitFunctionName,
Type *Ty, const char *Section);
   std::pair
@@ -491,6 +494,7 @@
   (F).getDomTree();
   const PostDominatorTree *PDT =
   (F).getPostDomTree();
+  bool IsLeafFunc = true;
 
   for (auto  : F) {
 if (shouldInstrumentBlock(F, , DT, PDT, Options))
@@ -515,10 

[PATCH] D37042: Teach clang to tolerate the 'p = nullptr + n' idiom used by glibc

2017-08-29 Thread Andy Kaylor via Phabricator via cfe-commits
andrew.w.kaylor added inline comments.



Comment at: lib/Sema/SemaExpr.cpp:8808
+Context.getTypeSize(pointerType) == 
+Context.getTypeSize(IExp->getType()))
+  IsGNUIdiom = true;

efriedma wrote:
> rsmith wrote:
> > andrew.w.kaylor wrote:
> > > efriedma wrote:
> > > > Please make sure you use exactly the same check in Sema and CodeGen 
> > > > (probably easiest to stick a helper into lib/AST/).
> > > That's a good idea, but I'm not really familiar enough with the structure 
> > > of clang to be sure I'm not doing it in a ham-fisted way.  Can you 
> > > clarify?  Are you suggesting adding something like 
> > > ASTContext::isPointeeTypeCharSize() and 
> > > ASTContext::isIntegerTypePointerSize()?  Or maybe a single specialized 
> > > function somewhere that does both checks like 
> > > ASTContext::areOperandNullPointerArithmeticCompatible()?
> > I would suggest something even more specific, such as 
> > `isNullPointerPlusIntegerExtension`
> I'm most concerned about the difference between 
> "isa(pointer)" and 
> "PExp->IgnoreParenCasts()->isNullPointerConstant()"... they're different in 
> important ways.
> 
> I was thinking something like 
> "BinaryOperator::isNullPointerArithmeticExtension()"
At this point in Sema the BinaryOperator for the addition hasn't been created 
yet, right?  So a static function that takes the opcode and operands?


https://reviews.llvm.org/D37042



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


[PATCH] D37042: Teach clang to tolerate the 'p = nullptr + n' idiom used by glibc

2017-08-29 Thread Eli Friedman via Phabricator via cfe-commits
efriedma added inline comments.



Comment at: lib/Sema/SemaExpr.cpp:8808
+Context.getTypeSize(pointerType) == 
+Context.getTypeSize(IExp->getType()))
+  IsGNUIdiom = true;

rsmith wrote:
> andrew.w.kaylor wrote:
> > efriedma wrote:
> > > Please make sure you use exactly the same check in Sema and CodeGen 
> > > (probably easiest to stick a helper into lib/AST/).
> > That's a good idea, but I'm not really familiar enough with the structure 
> > of clang to be sure I'm not doing it in a ham-fisted way.  Can you clarify? 
> >  Are you suggesting adding something like 
> > ASTContext::isPointeeTypeCharSize() and 
> > ASTContext::isIntegerTypePointerSize()?  Or maybe a single specialized 
> > function somewhere that does both checks like 
> > ASTContext::areOperandNullPointerArithmeticCompatible()?
> I would suggest something even more specific, such as 
> `isNullPointerPlusIntegerExtension`
I'm most concerned about the difference between 
"isa(pointer)" and 
"PExp->IgnoreParenCasts()->isNullPointerConstant()"... they're different in 
important ways.

I was thinking something like 
"BinaryOperator::isNullPointerArithmeticExtension()"


https://reviews.llvm.org/D37042



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


r312084 - Driver: refactor SSP argument handling (NFC)

2017-08-29 Thread Saleem Abdulrasool via cfe-commits
Author: compnerd
Date: Tue Aug 29 16:59:08 2017
New Revision: 312084

URL: http://llvm.org/viewvc/llvm-project?rev=312084=rev
Log:
Driver: refactor SSP argument handling (NFC)

Out-of-line the SSP argument handling for the sake of readability.  Pass
along some state information to avoid re-computing the command line
flags.

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

Modified: cfe/trunk/lib/Driver/ToolChains/Clang.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Driver/ToolChains/Clang.cpp?rev=312084=312083=312084=diff
==
--- cfe/trunk/lib/Driver/ToolChains/Clang.cpp (original)
+++ cfe/trunk/lib/Driver/ToolChains/Clang.cpp Tue Aug 29 16:59:08 2017
@@ -1968,6 +1968,60 @@ static void CollectArgsForIntegratedAsse
   }
 }
 
+static void RenderSSPOptions(const ToolChain , const ArgList ,
+ ArgStringList , bool KernelOrKext,
+ bool IsHosted) {
+  const llvm::Triple  = TC.getEffectiveTriple();
+
+  // NVPTX doesn't support stack protectors; from the compiler's perspective, 
it
+  // doesn't even have a stack!
+  if (EffectiveTriple.isNVPTX())
+return;
+
+  // -stack-protector=0 is default.
+  unsigned StackProtectorLevel = 0;
+  unsigned DefaultStackProtectorLevel =
+  TC.GetDefaultStackProtectorLevel(KernelOrKext);
+
+  if (Arg *A = Args.getLastArg(options::OPT_fno_stack_protector,
+   options::OPT_fstack_protector_all,
+   options::OPT_fstack_protector_strong,
+   options::OPT_fstack_protector)) {
+if (A->getOption().matches(options::OPT_fstack_protector))
+  StackProtectorLevel =
+  std::max(LangOptions::SSPOn, DefaultStackProtectorLevel);
+else if (A->getOption().matches(options::OPT_fstack_protector_strong))
+  StackProtectorLevel = LangOptions::SSPStrong;
+else if (A->getOption().matches(options::OPT_fstack_protector_all))
+  StackProtectorLevel = LangOptions::SSPReq;
+  } else {
+// Only use a default stack protector on Darwin in case -ffreestanding is
+// not specified.
+if (EffectiveTriple.isOSDarwin() && !IsHosted)
+  StackProtectorLevel = 0;
+else
+  StackProtectorLevel = DefaultStackProtectorLevel;
+  }
+
+  if (StackProtectorLevel) {
+CmdArgs.push_back("-stack-protector");
+CmdArgs.push_back(Args.MakeArgString(Twine(StackProtectorLevel)));
+  }
+
+  // --param ssp-buffer-size=
+  for (const Arg *A : Args.filtered(options::OPT__param)) {
+StringRef Str(A->getValue());
+if (Str.startswith("ssp-buffer-size=")) {
+  if (StackProtectorLevel) {
+CmdArgs.push_back("-stack-protector-buffer-size");
+// FIXME: Verify the argument is a valid integer.
+CmdArgs.push_back(Args.MakeArgString(Str.drop_front(16)));
+  }
+  A->claim();
+}
+  }
+}
+
 static void RenderOpenCLOptions(const ArgList , ArgStringList ) {
   const unsigned ForwardedArguments[] = {
   options::OPT_cl_opt_disable,
@@ -3294,12 +3348,11 @@ void Clang::ConstructJob(Compilation ,
   Args.AddLastArg(CmdArgs, options::OPT_ftlsmodel_EQ);
 
   // -fhosted is default.
-  bool IsHosted = true;
-  if (Args.hasFlag(options::OPT_ffreestanding, options::OPT_fhosted, false) ||
-  KernelOrKext) {
+  bool IsHosted =
+  !Args.hasFlag(options::OPT_ffreestanding, options::OPT_fhosted, false) &&
+  !KernelOrKext;
+  if (!IsHosted)
 CmdArgs.push_back("-ffreestanding");
-IsHosted = false;
-  }
 
   // Forward -f (flag) options which we can pass directly.
   Args.AddLastArg(CmdArgs, options::OPT_femit_all_decls);
@@ -3406,49 +3459,7 @@ void Clang::ConstructJob(Compilation ,
 
   Args.AddLastArg(CmdArgs, options::OPT_pthread);
 
-  // -stack-protector=0 is default.
-  unsigned StackProtectorLevel = 0;
-  // NVPTX doesn't support stack protectors; from the compiler's perspective, 
it
-  // doesn't even have a stack!
-  if (!Triple.isNVPTX()) {
-if (Arg *A = Args.getLastArg(options::OPT_fno_stack_protector,
- options::OPT_fstack_protector_all,
- options::OPT_fstack_protector_strong,
- options::OPT_fstack_protector)) {
-  if (A->getOption().matches(options::OPT_fstack_protector)) {
-StackProtectorLevel = std::max(
-LangOptions::SSPOn,
-getToolChain().GetDefaultStackProtectorLevel(KernelOrKext));
-  } else if (A->getOption().matches(options::OPT_fstack_protector_strong))
-StackProtectorLevel = LangOptions::SSPStrong;
-  else if (A->getOption().matches(options::OPT_fstack_protector_all))
-StackProtectorLevel = LangOptions::SSPReq;
-} else {
-  StackProtectorLevel =
-  getToolChain().GetDefaultStackProtectorLevel(KernelOrKext);
-  // Only use a default stack protector on Darwin in case -ffreestanding
-  // is not 

r312083 - Driver: refactor OpenCL argument forwarding

2017-08-29 Thread Saleem Abdulrasool via cfe-commits
Author: compnerd
Date: Tue Aug 29 16:59:07 2017
New Revision: 312083

URL: http://llvm.org/viewvc/llvm-project?rev=312083=rev
Log:
Driver: refactor OpenCL argument forwarding

Extract the argument forwarding for OpenCL arguments.  Make this more
data driven as we are just repeating the argument name and spelling.
This costs a slight bit more memory due to the string duplication, but
makes it easier to follow.  It should be possible to forward the
internal string representation from the TableGen data to avoid this.
But, this makes the code simpler to follow for now.

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

Modified: cfe/trunk/lib/Driver/ToolChains/Clang.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Driver/ToolChains/Clang.cpp?rev=312083=312082=312083=diff
==
--- cfe/trunk/lib/Driver/ToolChains/Clang.cpp (original)
+++ cfe/trunk/lib/Driver/ToolChains/Clang.cpp Tue Aug 29 16:59:07 2017
@@ -1968,6 +1968,31 @@ static void CollectArgsForIntegratedAsse
   }
 }
 
+static void RenderOpenCLOptions(const ArgList , ArgStringList ) {
+  const unsigned ForwardedArguments[] = {
+  options::OPT_cl_opt_disable,
+  options::OPT_cl_strict_aliasing,
+  options::OPT_cl_single_precision_constant,
+  options::OPT_cl_finite_math_only,
+  options::OPT_cl_kernel_arg_info,
+  options::OPT_cl_unsafe_math_optimizations,
+  options::OPT_cl_fast_relaxed_math,
+  options::OPT_cl_mad_enable,
+  options::OPT_cl_no_signed_zeros,
+  options::OPT_cl_denorms_are_zero,
+  options::OPT_cl_fp32_correctly_rounded_divide_sqrt,
+  };
+
+  if (Arg *A = Args.getLastArg(options::OPT_cl_std_EQ)) {
+std::string CLStdStr = std::string("-cl-std=") + A->getValue();
+CmdArgs.push_back(Args.MakeArgString(CLStdStr));
+  }
+
+  for (const auto  : ForwardedArguments)
+if (const auto *A = Args.getLastArg(Arg))
+  CmdArgs.push_back(Args.MakeArgString(A->getOption().getPrefixedName()));
+}
+
 void Clang::ConstructJob(Compilation , const JobAction ,
  const InputInfo , const InputInfoList ,
  const ArgList , const char *LinkingOutput) const 
{
@@ -3476,44 +3501,7 @@ void Clang::ConstructJob(Compilation ,
   }
 
   // Forward -cl options to -cc1
-  if (Args.getLastArg(options::OPT_cl_opt_disable)) {
-CmdArgs.push_back("-cl-opt-disable");
-  }
-  if (Args.getLastArg(options::OPT_cl_strict_aliasing)) {
-CmdArgs.push_back("-cl-strict-aliasing");
-  }
-  if (Args.getLastArg(options::OPT_cl_single_precision_constant)) {
-CmdArgs.push_back("-cl-single-precision-constant");
-  }
-  if (Args.getLastArg(options::OPT_cl_finite_math_only)) {
-CmdArgs.push_back("-cl-finite-math-only");
-  }
-  if (Args.getLastArg(options::OPT_cl_kernel_arg_info)) {
-CmdArgs.push_back("-cl-kernel-arg-info");
-  }
-  if (Args.getLastArg(options::OPT_cl_unsafe_math_optimizations)) {
-CmdArgs.push_back("-cl-unsafe-math-optimizations");
-  }
-  if (Args.getLastArg(options::OPT_cl_fast_relaxed_math)) {
-CmdArgs.push_back("-cl-fast-relaxed-math");
-  }
-  if (Args.getLastArg(options::OPT_cl_mad_enable)) {
-CmdArgs.push_back("-cl-mad-enable");
-  }
-  if (Args.getLastArg(options::OPT_cl_no_signed_zeros)) {
-CmdArgs.push_back("-cl-no-signed-zeros");
-  }
-  if (Arg *A = Args.getLastArg(options::OPT_cl_std_EQ)) {
-std::string CLStdStr = "-cl-std=";
-CLStdStr += A->getValue();
-CmdArgs.push_back(Args.MakeArgString(CLStdStr));
-  }
-  if (Args.getLastArg(options::OPT_cl_denorms_are_zero)) {
-CmdArgs.push_back("-cl-denorms-are-zero");
-  }
-  if (Args.getLastArg(options::OPT_cl_fp32_correctly_rounded_divide_sqrt)) {
-CmdArgs.push_back("-cl-fp32-correctly-rounded-divide-sqrt");
-  }
+  RenderOpenCLOptions(Args, CmdArgs);
 
   // Forward -f options with positive and negative forms; we translate
   // these by hand.


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


r312082 - Driver: reuse existing `D` variable (NFC)

2017-08-29 Thread Saleem Abdulrasool via cfe-commits
Author: compnerd
Date: Tue Aug 29 16:59:06 2017
New Revision: 312082

URL: http://llvm.org/viewvc/llvm-project?rev=312082=rev
Log:
Driver: reuse existing `D` variable (NFC)

Change the rest of the function to use the `D` variable for the driver
instance.  NFC.

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

Modified: cfe/trunk/lib/Driver/ToolChains/Clang.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Driver/ToolChains/Clang.cpp?rev=312082=312081=312082=diff
==
--- cfe/trunk/lib/Driver/ToolChains/Clang.cpp (original)
+++ cfe/trunk/lib/Driver/ToolChains/Clang.cpp Tue Aug 29 16:59:06 2017
@@ -2381,7 +2381,7 @@ void Clang::ConstructJob(Compilation ,
   OFastEnabled ? options::OPT_Ofast : options::OPT_fstrict_aliasing;
   // We turn strict aliasing off by default if we're in CL mode, since MSVC
   // doesn't do any TBAA.
-  bool TBAAOnByDefault = !getToolChain().getDriver().IsCLMode();
+  bool TBAAOnByDefault = !D.IsCLMode();
   if (!Args.hasFlag(options::OPT_fstrict_aliasing, StrictAliasingAliasOption,
 options::OPT_fno_strict_aliasing, TBAAOnByDefault))
 CmdArgs.push_back("-relaxed-aliasing");
@@ -2551,7 +2551,7 @@ void Clang::ConstructJob(Compilation ,
   if (!FpContract.empty())
 CmdArgs.push_back(Args.MakeArgString("-ffp-contract="+FpContract));
 
-  ParseMRecip(getToolChain().getDriver(), Args, CmdArgs);
+  ParseMRecip(D, Args, CmdArgs);
 
   // -ffast-math enables the __FAST_MATH__ preprocessor macro, but check for 
the
   // individual features enabled by -ffast-math instead of the option itself as
@@ -2729,7 +2729,7 @@ void Clang::ConstructJob(Compilation ,
 
   // Add clang-cl arguments.
   types::ID InputType = Input.getType();
-  if (getToolChain().getDriver().IsCLMode())
+  if (D.IsCLMode())
 AddClangCLArgs(Args, InputType, CmdArgs, , );
 
   // Pass the linker version in use.
@@ -3300,7 +3300,7 @@ void Clang::ConstructJob(Compilation ,
options::OPT_fno_openmp, false) &&
   (JA.isDeviceOffloading(Action::OFK_None) ||
JA.isDeviceOffloading(Action::OFK_OpenMP))) {
-switch (getToolChain().getDriver().getOpenMPRuntime(Args)) {
+switch (D.getOpenMPRuntime(Args)) {
 case Driver::OMPRT_OMP:
 case Driver::OMPRT_IOMP5:
   // Clang can generate useful OpenMP code for these two runtime libraries.
@@ -3666,7 +3666,7 @@ void Clang::ConstructJob(Compilation ,
   // -fbuiltin-module-map can be used to load the clang
   // builtin headers modulemap file.
   if (Args.hasArg(options::OPT_fbuiltin_module_map)) {
-SmallString<128> BuiltinModuleMap(getToolChain().getDriver().ResourceDir);
+SmallString<128> BuiltinModuleMap(D.ResourceDir);
 llvm::sys::path::append(BuiltinModuleMap, "include");
 llvm::sys::path::append(BuiltinModuleMap, "module.modulemap");
 if (llvm::sys::fs::exists(BuiltinModuleMap)) {
@@ -3795,8 +3795,7 @@ void Clang::ConstructJob(Compilation ,
  options::OPT_fno_ms_extensions, true
 CmdArgs.push_back("-fms-compatibility");
 
-  VersionTuple MSVT =
-  getToolChain().computeMSVCVersion(().getDriver(), Args);
+  VersionTuple MSVT = getToolChain().computeMSVCVersion(, Args);
   if (!MSVT.empty())
 CmdArgs.push_back(
 Args.MakeArgString("-fms-compatibility-version=" + 
MSVT.getAsString()));
@@ -4166,8 +4165,8 @@ void Clang::ConstructJob(Compilation ,
 if (O.matches(options::OPT_fdiagnostics_color_EQ)) {
   StringRef Value(A->getValue());
   if (Value != "always" && Value != "never" && Value != "auto")
-getToolChain().getDriver().Diag(diag::err_drv_clang_unsupported)
-  << ("-fdiagnostics-color=" + Value).str();
+D.Diag(diag::err_drv_clang_unsupported)
+<< ("-fdiagnostics-color=" + Value).str();
 }
 A->claim();
   }
@@ -4440,7 +4439,7 @@ void Clang::ConstructJob(Compilation ,
 
   Args.AddAllArgs(CmdArgs, options::OPT_undef);
 
-  const char *Exec = getToolChain().getDriver().getClangProgramPath();
+  const char *Exec = D.getClangProgramPath();
 
   // Optionally embed the -cc1 level arguments into the debug info, for build
   // analysis.


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


r312081 - Driver: hoist a local variable (NFC)

2017-08-29 Thread Saleem Abdulrasool via cfe-commits
Author: compnerd
Date: Tue Aug 29 16:59:05 2017
New Revision: 312081

URL: http://llvm.org/viewvc/llvm-project?rev=312081=rev
Log:
Driver: hoist a local variable (NFC)

Hoist the `getToolChain().getTriple()` to a variable rather than
re-fetching it every time.  NFC.

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

Modified: cfe/trunk/lib/Driver/ToolChains/Clang.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Driver/ToolChains/Clang.cpp?rev=312081=312080=312081=diff
==
--- cfe/trunk/lib/Driver/ToolChains/Clang.cpp (original)
+++ cfe/trunk/lib/Driver/ToolChains/Clang.cpp Tue Aug 29 16:59:05 2017
@@ -1971,6 +1971,7 @@ static void CollectArgsForIntegratedAsse
 void Clang::ConstructJob(Compilation , const JobAction ,
  const InputInfo , const InputInfoList ,
  const ArgList , const char *LinkingOutput) const 
{
+  const llvm::Triple  = getToolChain().getTriple();
   const llvm::Triple  = getToolChain().getEffectiveTriple();
   const std::string  = Triple.getTriple();
 
@@ -1992,12 +1993,11 @@ void Clang::ConstructJob(Compilation ,
   Inputs.size() == 1) &&
  "Unable to handle multiple inputs.");
 
-  bool IsWindowsGNU = getToolChain().getTriple().isWindowsGNUEnvironment();
-  bool IsWindowsCygnus =
-  getToolChain().getTriple().isWindowsCygwinEnvironment();
-  bool IsWindowsMSVC = getToolChain().getTriple().isWindowsMSVCEnvironment();
-  bool IsPS4CPU = getToolChain().getTriple().isPS4CPU();
-  bool IsIAMCU = getToolChain().getTriple().isOSIAMCU();
+  bool IsWindowsGNU = RawTriple.isWindowsGNUEnvironment();
+  bool IsWindowsCygnus = RawTriple.isWindowsCygwinEnvironment();
+  bool IsWindowsMSVC = RawTriple.isWindowsMSVCEnvironment();
+  bool IsPS4CPU = RawTriple.isPS4CPU();
+  bool IsIAMCU = RawTriple.isOSIAMCU();
 
   // Adjust IsWindowsXYZ for CUDA compilations.  Even when compiling in device
   // mode (i.e., getToolchain().getTriple() is NVPTX, not Windows), we need to
@@ -2147,8 +2147,7 @@ void Clang::ConstructJob(Compilation ,
   // The Darwin and PS4 linkers currently use the legacy LTO API, which
   // does not support LTO unit features (CFI, whole program vtable opt)
   // under ThinLTO.
-  if (!(getToolChain().getTriple().isOSDarwin() ||
-getToolChain().getTriple().isPS4()) ||
+  if (!(RawTriple.isOSDarwin() || RawTriple.isPS4()) ||
   D.getLTOMode() == LTOK_Full)
 CmdArgs.push_back("-flto-unit");
 }
@@ -2227,7 +2226,7 @@ void Clang::ConstructJob(Compilation ,
 CmdArgs.push_back("-analyzer-disable-checker=unix.Vfork");
   }
 
-  if (getToolChain().getTriple().getVendor() == llvm::Triple::Apple)
+  if (RawTriple.getVendor() == llvm::Triple::Apple)
 CmdArgs.push_back("-analyzer-checker=osx");
 
   CmdArgs.push_back("-analyzer-checker=deadcode");
@@ -2357,7 +2356,7 @@ void Clang::ConstructJob(Compilation ,
options::OPT_freg_struct_return)) {
 if (getToolChain().getArch() != llvm::Triple::x86) {
   D.Diag(diag::err_drv_unsupported_opt_for_target)
-  << A->getSpelling() << getToolChain().getTriple().str();
+  << A->getSpelling() << RawTriple.str();
 } else if (A->getOption().matches(options::OPT_fpcc_struct_return)) {
   CmdArgs.push_back("-fpcc-struct-return");
 } else {
@@ -2369,7 +2368,7 @@ void Clang::ConstructJob(Compilation ,
   if (Args.hasFlag(options::OPT_mrtd, options::OPT_mno_rtd, false))
 CmdArgs.push_back("-fdefault-calling-conv=stdcall");
 
-  if (shouldUseFramePointer(Args, getToolChain().getTriple()))
+  if (shouldUseFramePointer(Args, RawTriple))
 CmdArgs.push_back("-mdisable-fp-elim");
   if (!Args.hasFlag(options::OPT_fzero_initialized_in_bss,
 options::OPT_fno_zero_initialized_in_bss))
@@ -2590,13 +2589,12 @@ void Clang::ConstructJob(Compilation ,
   // Enable -mconstructor-aliases except on darwin, where we have to work 
around
   // a linker bug (see ), and CUDA device code, where
   // aliases aren't supported.
-  if (!getToolChain().getTriple().isOSDarwin() &&
-  !getToolChain().getTriple().isNVPTX())
+  if (!RawTriple.isOSDarwin() && !RawTriple.isNVPTX())
 CmdArgs.push_back("-mconstructor-aliases");
 
   // Darwin's kernel doesn't support guard variables; just die if we
   // try to use them.
-  if (KernelOrKext && getToolChain().getTriple().isOSDarwin())
+  if (KernelOrKext && RawTriple.isOSDarwin())
 CmdArgs.push_back("-fforbid-guard-variables");
 
   if (Args.hasFlag(options::OPT_mms_bitfields, options::OPT_mno_ms_bitfields,
@@ -2740,14 +2738,14 @@ void Clang::ConstructJob(Compilation ,
 CmdArgs.push_back(A->getValue());
   }
 
-  if (!shouldUseLeafFramePointer(Args, getToolChain().getTriple()))
+  if (!shouldUseLeafFramePointer(Args, RawTriple))
 CmdArgs.push_back("-momit-leaf-frame-pointer");
 
   // Explicitly error 

[PATCH] D37042: Teach clang to tolerate the 'p = nullptr + n' idiom used by glibc

2017-08-29 Thread Richard Smith - zygoloid via Phabricator via cfe-commits
rsmith added inline comments.



Comment at: lib/Sema/SemaExpr.cpp:8808
+Context.getTypeSize(pointerType) == 
+Context.getTypeSize(IExp->getType()))
+  IsGNUIdiom = true;

andrew.w.kaylor wrote:
> efriedma wrote:
> > Please make sure you use exactly the same check in Sema and CodeGen 
> > (probably easiest to stick a helper into lib/AST/).
> That's a good idea, but I'm not really familiar enough with the structure of 
> clang to be sure I'm not doing it in a ham-fisted way.  Can you clarify?  Are 
> you suggesting adding something like ASTContext::isPointeeTypeCharSize() and 
> ASTContext::isIntegerTypePointerSize()?  Or maybe a single specialized 
> function somewhere that does both checks like 
> ASTContext::areOperandNullPointerArithmeticCompatible()?
I would suggest something even more specific, such as 
`isNullPointerPlusIntegerExtension`


https://reviews.llvm.org/D37042



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


[libunwind] r312080 - Creating release candidate rc4 from release_500 branch

2017-08-29 Thread Hans Wennborg via cfe-commits
Author: hans
Date: Tue Aug 29 16:49:14 2017
New Revision: 312080

URL: http://llvm.org/viewvc/llvm-project?rev=312080=rev
Log:
Creating release candidate rc4 from release_500 branch

Added:
libunwind/tags/RELEASE_500/rc4/   (props changed)
  - copied from r312079, libunwind/branches/release_50/

Propchange: libunwind/tags/RELEASE_500/rc4/
--
svn:mergeinfo = /libunwind/trunk:308871,309147


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


[libcxx] r312073 - Creating release candidate rc4 from release_500 branch

2017-08-29 Thread Hans Wennborg via cfe-commits
Author: hans
Date: Tue Aug 29 16:49:07 2017
New Revision: 312073

URL: http://llvm.org/viewvc/llvm-project?rev=312073=rev
Log:
Creating release candidate rc4 from release_500 branch

Added:
libcxx/tags/RELEASE_500/rc4/   (props changed)
  - copied from r312072, libcxx/branches/release_50/

Propchange: libcxx/tags/RELEASE_500/rc4/
--
--- svn:mergeinfo (added)
+++ svn:mergeinfo Tue Aug 29 16:49:07 2017
@@ -0,0 +1,2 @@
+/libcxx/branches/apple:136569-137939
+/libcxx/trunk:309296,309307,309474,309838,309851,309917,309920


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


[libcxxabi] r312074 - Creating release candidate rc4 from release_500 branch

2017-08-29 Thread Hans Wennborg via cfe-commits
Author: hans
Date: Tue Aug 29 16:49:07 2017
New Revision: 312074

URL: http://llvm.org/viewvc/llvm-project?rev=312074=rev
Log:
Creating release candidate rc4 from release_500 branch

Added:
libcxxabi/tags/RELEASE_500/rc4/
  - copied from r312073, libcxxabi/branches/release_50/

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


[PATCH] D37042: Teach clang to tolerate the 'p = nullptr + n' idiom used by glibc

2017-08-29 Thread Andy Kaylor via Phabricator via cfe-commits
andrew.w.kaylor added inline comments.



Comment at: lib/Sema/SemaExpr.cpp:8808
+Context.getTypeSize(pointerType) == 
+Context.getTypeSize(IExp->getType()))
+  IsGNUIdiom = true;

efriedma wrote:
> Please make sure you use exactly the same check in Sema and CodeGen (probably 
> easiest to stick a helper into lib/AST/).
That's a good idea, but I'm not really familiar enough with the structure of 
clang to be sure I'm not doing it in a ham-fisted way.  Can you clarify?  Are 
you suggesting adding something like ASTContext::isPointeeTypeCharSize() and 
ASTContext::isIntegerTypePointerSize()?  Or maybe a single specialized function 
somewhere that does both checks like 
ASTContext::areOperandNullPointerArithmeticCompatible()?


https://reviews.llvm.org/D37042



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


[PATCH] D36806: Switch to cantFail(), since it does the same assertion.

2017-08-29 Thread Lang Hames via Phabricator via cfe-commits
lhames added a comment.

I've added an optional ErrMsg argument to cantFail in r312066 - you can now use 
this to preserve your explanatory text.


https://reviews.llvm.org/D36806



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


[PATCH] D36272: [CodeGen][x86_64] Enable 'force_align_arg_pointer' attribute at x86_64

2017-08-29 Thread Anatol Pomozov via Phabricator via cfe-commits
anatol.pomozov added a comment.

Hi Eric, thank you for your reply. Both these triples are currently broken, 
with my change and without.

The attribute functionality in WinX86_64TargetCodeGenInfo mirrors one in 
X86_64TargetCodeGenInfo and it should work the same way. It is done 
intentionally as both these systems have the stack alignment restrictions.

In addition to option you proposed there are other ways to make forward 
progress:

- fix function-attributes.c for win32 systems (both 32 and 64bit). Having 
working tests in important not only for force_align_arg_pointer functionality 
but for any other win32 change. It needs attention from Clang developers who is 
familiar with this area.
- bypass the broken win32 test as it is done up until now.


https://reviews.llvm.org/D36272



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


[PATCH] D37042: Teach clang to tolerate the 'p = nullptr + n' idiom used by glibc

2017-08-29 Thread Andy Kaylor via Phabricator via cfe-commits
andrew.w.kaylor added inline comments.



Comment at: include/clang/Basic/DiagnosticSemaKinds.td:6032
+def ext_gnu_null_ptr_arith : Extension<
+  "inttoptr casting using arithmetic on a null pointer is a GNU extension">,
+  InGroup;

rsmith wrote:
> efriedma wrote:
> > The keyword "inttoptr" is part of LLVM, not something we expect users to 
> > understand.
> How about something like "arithmetic on null pointer treated as cast from 
> integer to pointer as a GNU extension"?
I like that.  Thanks for the suggestion.



Comment at: lib/Sema/SemaExpr.cpp:8805
+const PointerType *pointerType = PExp->getType()->getAs();
+if (!IExp->isIntegerConstantExpr(Context) &&
+pointerType->getPointeeType()->isCharType() &&

rsmith wrote:
> It seems strange to me to disable this when the RHS is an ICE. If we're going 
> to support this as an extension, we should make the rules for it as simple as 
> we reasonably can; this ICE check seems like an unnecessary complication.
You're probably right.  My thinking was that I wanted to keep the extension 
idiom as narrow as was reasonable, so these were cases that I felt like I could 
rule out, but the argument for simplicity is compelling since the alternative 
isn't doing anything particularly desirable in most cases.


https://reviews.llvm.org/D37042



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


[PATCH] D26764: [compiler-rt] [cmake] Remove i686 target that is duplicate to i386

2017-08-29 Thread Reid Kleckner via Phabricator via cfe-commits
rnk added a comment.

In https://reviews.llvm.org/D26764#855791, @eugenis wrote:

> IMHO it was a very bad idea to include the "architecture name" (not even a 
> target triple!) in the library path in the first place. No one else does 
> that. GCC made the right choice and called theirs "libasan.so".


+1, one day we should untangle the compiler-rt library names.

> My plan is to tweak the code that sets the library name to use i686 when the 
> target is i386 and the os is android, both in compiler-rt and in clang. There 
> will be no duplicate targets.




Repository:
  rL LLVM

https://reviews.llvm.org/D26764



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


[PATCH] D36272: [CodeGen][x86_64] Enable 'force_align_arg_pointer' attribute at x86_64

2017-08-29 Thread Erich Keane via Phabricator via cfe-commits
erichkeane added a comment.

In https://reviews.llvm.org/D36272#855957, @anatol.pomozov wrote:

> The function-attributes.c test  does not pass at Windows 
>  even without my patch. Unfortunately 
> I am not familiar with clang enough to debug this issue.


Yes, but the point of your patch seems to be to ADD this functionality to x64 
Linux AND windows.
My question is what happens with:
-triple i386-pc-win32?

This needs to match the behavior of 
-triple x86_64-pc-win32


https://reviews.llvm.org/D36272



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


r312049 - PR10147: When substituting a template template argument, substitute in the most

2017-08-29 Thread Richard Smith via cfe-commits
Author: rsmith
Date: Tue Aug 29 15:14:43 2017
New Revision: 312049

URL: http://llvm.org/viewvc/llvm-project?rev=312049=rev
Log:
PR10147: When substituting a template template argument, substitute in the most
recent (non-friend) declaration to pick up the right set of default template
arguments.

Modified:
cfe/trunk/include/clang/AST/TemplateName.h
cfe/trunk/lib/AST/TemplateName.cpp
cfe/trunk/lib/Sema/SemaTemplateInstantiate.cpp
cfe/trunk/test/SemaTemplate/temp_arg_template.cpp

Modified: cfe/trunk/include/clang/AST/TemplateName.h
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/AST/TemplateName.h?rev=312049=312048=312049=diff
==
--- cfe/trunk/include/clang/AST/TemplateName.h (original)
+++ cfe/trunk/include/clang/AST/TemplateName.h Tue Aug 29 15:14:43 2017
@@ -262,6 +262,11 @@ public:
 
   TemplateName getUnderlying() const;
 
+  /// Get the template name to substitute when this template name is used as a
+  /// template template argument. This refers to the most recent declaration of
+  /// the template, including any default template arguments.
+  TemplateName getNameToSubstitute() const;
+
   /// \brief Determines whether this is a dependent template name.
   bool isDependent() const;
 

Modified: cfe/trunk/lib/AST/TemplateName.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/AST/TemplateName.cpp?rev=312049=312048=312049=diff
==
--- cfe/trunk/lib/AST/TemplateName.cpp (original)
+++ cfe/trunk/lib/AST/TemplateName.cpp Tue Aug 29 15:14:43 2017
@@ -131,6 +131,23 @@ DependentTemplateName *TemplateName::get
   return Storage.dyn_cast();
 }
 
+TemplateName TemplateName::getNameToSubstitute() const {
+  TemplateDecl *Decl = getAsTemplateDecl();
+
+  // Substituting a dependent template name: preserve it as written.
+  if (!Decl)
+return *this;
+
+  // If we have a template declaration, use the most recent non-friend
+  // declaration of that template.
+  Decl = cast(Decl->getMostRecentDecl());
+  while (Decl->getFriendObjectKind()) {
+Decl = cast(Decl->getPreviousDecl());
+assert(Decl && "all declarations of template are friends");
+  }
+  return TemplateName(Decl);
+}
+
 bool TemplateName::isDependent() const {
   if (TemplateDecl *Template = getAsTemplateDecl()) {
 if (isa(Template))

Modified: cfe/trunk/lib/Sema/SemaTemplateInstantiate.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Sema/SemaTemplateInstantiate.cpp?rev=312049=312048=312049=diff
==
--- cfe/trunk/lib/Sema/SemaTemplateInstantiate.cpp (original)
+++ cfe/trunk/lib/Sema/SemaTemplateInstantiate.cpp Tue Aug 29 15:14:43 2017
@@ -975,7 +975,7 @@ Decl *TemplateInstantiator::TransformDec
 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
   }
 
-  TemplateName Template = Arg.getAsTemplate();
+  TemplateName Template = Arg.getAsTemplate().getNameToSubstitute();
   assert(!Template.isNull() && Template.getAsTemplateDecl() &&
  "Wrong kind of template template argument");
   return Template.getAsTemplateDecl();
@@ -1122,14 +1122,10 @@ TemplateName TemplateInstantiator::Trans
 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
   }
   
-  TemplateName Template = Arg.getAsTemplate();
+  TemplateName Template = Arg.getAsTemplate().getNameToSubstitute();
   assert(!Template.isNull() && "Null template template argument");
-
-  // We don't ever want to substitute for a qualified template name, since
-  // the qualifier is handled separately. So, look through the qualified
-  // template name to its underlying declaration.
-  if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
-Template = TemplateName(QTN->getTemplateDecl());
+  assert(!Template.getAsQualifiedTemplateName() &&
+ "template decl to substitute is qualified?");
 
   Template = getSema().Context.getSubstTemplateTemplateParm(TTP, Template);
   return Template;
@@ -1143,7 +1139,7 @@ TemplateName TemplateInstantiator::Trans
 
 TemplateArgument Arg = SubstPack->getArgumentPack();
 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
-return Arg.getAsTemplate();
+return Arg.getAsTemplate().getNameToSubstitute();
   }
 
   return inherited::TransformTemplateName(SS, Name, NameLoc, ObjectType,

Modified: cfe/trunk/test/SemaTemplate/temp_arg_template.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/SemaTemplate/temp_arg_template.cpp?rev=312049=312048=312049=diff
==
--- cfe/trunk/test/SemaTemplate/temp_arg_template.cpp (original)
+++ cfe/trunk/test/SemaTemplate/temp_arg_template.cpp Tue Aug 29 15:14:43 2017
@@ -141,3 +141,10 @@ namespace PR32185 {
   

[PATCH] D26764: [compiler-rt] [cmake] Remove i686 target that is duplicate to i386

2017-08-29 Thread Evgenii Stepanov via Phabricator via cfe-commits
eugenis added a comment.

I've landed the android special case in r312048


Repository:
  rL LLVM

https://reviews.llvm.org/D26764



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


[PATCH] D37278: Restore clang_rt library name on i686-android.

2017-08-29 Thread Evgenii Stepanov via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rL312048: Restore clang_rt library name on i686-android. 
(authored by eugenis).

Changed prior to commit:
  https://reviews.llvm.org/D37278?vs=113167=113170#toc

Repository:
  rL LLVM

https://reviews.llvm.org/D37278

Files:
  cfe/trunk/lib/Driver/ToolChain.cpp
  cfe/trunk/test/Driver/sanitizer-ld.c
  compiler-rt/trunk/cmake/Modules/AddCompilerRT.cmake


Index: compiler-rt/trunk/cmake/Modules/AddCompilerRT.cmake
===
--- compiler-rt/trunk/cmake/Modules/AddCompilerRT.cmake
+++ compiler-rt/trunk/cmake/Modules/AddCompilerRT.cmake
@@ -86,6 +86,14 @@
   add_dependencies(compiler-rt ${name})
 endfunction()
 
+macro(set_output_name output name arch)
+  if(ANDROID AND ${arch} STREQUAL "i386")
+set(${output} "${name}-i686${COMPILER_RT_OS_SUFFIX}")
+  else()
+set(${output} "${name}-${arch}${COMPILER_RT_OS_SUFFIX}")
+  endif()
+endmacro()
+
 # Adds static or shared runtime for a list of architectures and operating
 # systems and puts it in the proper directory in the build and install trees.
 # add_compiler_rt_runtime(
@@ -142,15 +150,15 @@
   endif()
   if(type STREQUAL "STATIC")
 set(libname "${name}-${arch}")
-set(output_name_${libname} ${libname}${COMPILER_RT_OS_SUFFIX})
+set_output_name(output_name_${libname} ${name} ${arch})
   else()
 set(libname "${name}-dynamic-${arch}")
 set(extra_cflags_${libname} ${TARGET_${arch}_CFLAGS} ${LIB_CFLAGS})
 set(extra_link_flags_${libname} ${TARGET_${arch}_LINK_FLAGS} 
${LIB_LINK_FLAGS})
 if(WIN32)
-  set(output_name_${libname} 
${name}_dynamic-${arch}${COMPILER_RT_OS_SUFFIX})
+  set_output_name(output_name_${libname} ${name}_dynamic ${arch})
 else()
-  set(output_name_${libname} ${name}-${arch}${COMPILER_RT_OS_SUFFIX})
+  set_output_name(output_name_${libname} ${name} ${arch})
 endif()
   endif()
   set(sources_${libname} ${LIB_SOURCES})
Index: cfe/trunk/test/Driver/sanitizer-ld.c
===
--- cfe/trunk/test/Driver/sanitizer-ld.c
+++ cfe/trunk/test/Driver/sanitizer-ld.c
@@ -133,6 +133,18 @@
 // CHECK-ASAN-ANDROID-NOT: "-lpthread"
 //
 // RUN: %clang -no-canonical-prefixes %s -### -o %t.o 2>&1 \
+// RUN: -target i686-linux-android -fuse-ld=ld -fsanitize=address \
+// RUN: --sysroot=%S/Inputs/basic_android_tree/sysroot \
+// RUN:   | FileCheck --check-prefix=CHECK-ASAN-ANDROID-X86 %s
+//
+// CHECK-ASAN-ANDROID-X86: "{{(.*[^.0-9A-Z_a-z])?}}ld{{(.exe)?}}"
+// CHECK-ASAN-ANDROID-X86-NOT: "-lc"
+// CHECK-ASAN-ANDROID-X86: "-pie"
+// CHECK-ASAN-ANDROID-X86-NOT: "-lpthread"
+// CHECK-ASAN-ANDROID-X86: libclang_rt.asan-i686-android.so"
+// CHECK-ASAN-ANDROID-X86-NOT: "-lpthread"
+//
+// RUN: %clang -no-canonical-prefixes %s -### -o %t.o 2>&1 \
 // RUN: -target arm-linux-androideabi -fsanitize=address \
 // RUN: --sysroot=%S/Inputs/basic_android_tree/sysroot \
 // RUN: -shared-libasan \
Index: cfe/trunk/lib/Driver/ToolChain.cpp
===
--- cfe/trunk/lib/Driver/ToolChain.cpp
+++ cfe/trunk/lib/Driver/ToolChain.cpp
@@ -305,6 +305,10 @@
? "armhf"
: "arm";
 
+  // For historic reasons, Android library is using i686 instead of i386.
+  if (TC.getArch() == llvm::Triple::x86 && Triple.isAndroid())
+return "i686";
+
   return llvm::Triple::getArchTypeName(TC.getArch());
 }
 


Index: compiler-rt/trunk/cmake/Modules/AddCompilerRT.cmake
===
--- compiler-rt/trunk/cmake/Modules/AddCompilerRT.cmake
+++ compiler-rt/trunk/cmake/Modules/AddCompilerRT.cmake
@@ -86,6 +86,14 @@
   add_dependencies(compiler-rt ${name})
 endfunction()
 
+macro(set_output_name output name arch)
+  if(ANDROID AND ${arch} STREQUAL "i386")
+set(${output} "${name}-i686${COMPILER_RT_OS_SUFFIX}")
+  else()
+set(${output} "${name}-${arch}${COMPILER_RT_OS_SUFFIX}")
+  endif()
+endmacro()
+
 # Adds static or shared runtime for a list of architectures and operating
 # systems and puts it in the proper directory in the build and install trees.
 # add_compiler_rt_runtime(
@@ -142,15 +150,15 @@
   endif()
   if(type STREQUAL "STATIC")
 set(libname "${name}-${arch}")
-set(output_name_${libname} ${libname}${COMPILER_RT_OS_SUFFIX})
+set_output_name(output_name_${libname} ${name} ${arch})
   else()
 set(libname "${name}-dynamic-${arch}")
 set(extra_cflags_${libname} ${TARGET_${arch}_CFLAGS} ${LIB_CFLAGS})
 set(extra_link_flags_${libname} ${TARGET_${arch}_LINK_FLAGS} ${LIB_LINK_FLAGS})
 if(WIN32)
-  set(output_name_${libname} ${name}_dynamic-${arch}${COMPILER_RT_OS_SUFFIX})
+  set_output_name(output_name_${libname} ${name}_dynamic 

r312048 - Restore clang_rt library name on i686-android.

2017-08-29 Thread Evgeniy Stepanov via cfe-commits
Author: eugenis
Date: Tue Aug 29 15:12:31 2017
New Revision: 312048

URL: http://llvm.org/viewvc/llvm-project?rev=312048=rev
Log:
Restore clang_rt library name on i686-android.

Summary:
Recent changes canonicalized clang_rt library names to refer to
"i386" on all x86 targets. Android historically uses i686.

This change adds a special case to keep i686 in all clang_rt
libraries when targeting Android.

Reviewers: hans, mgorny, beanz

Subscribers: srhines, cfe-commits, llvm-commits

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

Modified:
cfe/trunk/lib/Driver/ToolChain.cpp
cfe/trunk/test/Driver/sanitizer-ld.c

Modified: cfe/trunk/lib/Driver/ToolChain.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Driver/ToolChain.cpp?rev=312048=312047=312048=diff
==
--- cfe/trunk/lib/Driver/ToolChain.cpp (original)
+++ cfe/trunk/lib/Driver/ToolChain.cpp Tue Aug 29 15:12:31 2017
@@ -305,6 +305,10 @@ static StringRef getArchNameForCompilerR
? "armhf"
: "arm";
 
+  // For historic reasons, Android library is using i686 instead of i386.
+  if (TC.getArch() == llvm::Triple::x86 && Triple.isAndroid())
+return "i686";
+
   return llvm::Triple::getArchTypeName(TC.getArch());
 }
 

Modified: cfe/trunk/test/Driver/sanitizer-ld.c
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/Driver/sanitizer-ld.c?rev=312048=312047=312048=diff
==
--- cfe/trunk/test/Driver/sanitizer-ld.c (original)
+++ cfe/trunk/test/Driver/sanitizer-ld.c Tue Aug 29 15:12:31 2017
@@ -133,6 +133,18 @@
 // CHECK-ASAN-ANDROID-NOT: "-lpthread"
 //
 // RUN: %clang -no-canonical-prefixes %s -### -o %t.o 2>&1 \
+// RUN: -target i686-linux-android -fuse-ld=ld -fsanitize=address \
+// RUN: --sysroot=%S/Inputs/basic_android_tree/sysroot \
+// RUN:   | FileCheck --check-prefix=CHECK-ASAN-ANDROID-X86 %s
+//
+// CHECK-ASAN-ANDROID-X86: "{{(.*[^.0-9A-Z_a-z])?}}ld{{(.exe)?}}"
+// CHECK-ASAN-ANDROID-X86-NOT: "-lc"
+// CHECK-ASAN-ANDROID-X86: "-pie"
+// CHECK-ASAN-ANDROID-X86-NOT: "-lpthread"
+// CHECK-ASAN-ANDROID-X86: libclang_rt.asan-i686-android.so"
+// CHECK-ASAN-ANDROID-X86-NOT: "-lpthread"
+//
+// RUN: %clang -no-canonical-prefixes %s -### -o %t.o 2>&1 \
 // RUN: -target arm-linux-androideabi -fsanitize=address \
 // RUN: --sysroot=%S/Inputs/basic_android_tree/sysroot \
 // RUN: -shared-libasan \


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


[PATCH] D36272: [CodeGen][x86_64] Enable 'force_align_arg_pointer' attribute at x86_64

2017-08-29 Thread Anatol Pomozov via Phabricator via cfe-commits
anatol.pomozov added a comment.

The function-attributes.c test  does not pass at Windows 
 even without my patch. Unfortunately I 
am not familiar with clang enough to debug this issue.


https://reviews.llvm.org/D36272



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


[PATCH] D37278: Restore clang_rt library name on i686-android.

2017-08-29 Thread Evgenii Stepanov via Phabricator via cfe-commits
eugenis updated this revision to Diff 113167.
eugenis added a comment.

+comment


https://reviews.llvm.org/D37278

Files:
  clang/lib/Driver/ToolChain.cpp
  clang/test/Driver/sanitizer-ld.c
  compiler-rt/cmake/Modules/AddCompilerRT.cmake


Index: compiler-rt/cmake/Modules/AddCompilerRT.cmake
===
--- compiler-rt/cmake/Modules/AddCompilerRT.cmake
+++ compiler-rt/cmake/Modules/AddCompilerRT.cmake
@@ -86,6 +86,14 @@
   add_dependencies(compiler-rt ${name})
 endfunction()
 
+macro(set_output_name output name arch)
+  if(ANDROID AND ${arch} STREQUAL "i386")
+set(${output} "${name}-i686${COMPILER_RT_OS_SUFFIX}")
+  else()
+set(${output} "${name}-${arch}${COMPILER_RT_OS_SUFFIX}")
+  endif()
+endmacro()
+
 # Adds static or shared runtime for a list of architectures and operating
 # systems and puts it in the proper directory in the build and install trees.
 # add_compiler_rt_runtime(
@@ -142,15 +150,15 @@
   endif()
   if(type STREQUAL "STATIC")
 set(libname "${name}-${arch}")
-set(output_name_${libname} ${libname}${COMPILER_RT_OS_SUFFIX})
+set_output_name(output_name_${libname} ${name} ${arch})
   else()
 set(libname "${name}-dynamic-${arch}")
 set(extra_cflags_${libname} ${TARGET_${arch}_CFLAGS} ${LIB_CFLAGS})
 set(extra_link_flags_${libname} ${TARGET_${arch}_LINK_FLAGS} 
${LIB_LINK_FLAGS})
 if(WIN32)
-  set(output_name_${libname} 
${name}_dynamic-${arch}${COMPILER_RT_OS_SUFFIX})
+  set_output_name(output_name_${libname} ${name}_dynamic ${arch})
 else()
-  set(output_name_${libname} ${name}-${arch}${COMPILER_RT_OS_SUFFIX})
+  set_output_name(output_name_${libname} ${name} ${arch})
 endif()
   endif()
   set(sources_${libname} ${LIB_SOURCES})
Index: clang/test/Driver/sanitizer-ld.c
===
--- clang/test/Driver/sanitizer-ld.c
+++ clang/test/Driver/sanitizer-ld.c
@@ -133,6 +133,18 @@
 // CHECK-ASAN-ANDROID-NOT: "-lpthread"
 //
 // RUN: %clang -no-canonical-prefixes %s -### -o %t.o 2>&1 \
+// RUN: -target i686-linux-android -fuse-ld=ld -fsanitize=address \
+// RUN: --sysroot=%S/Inputs/basic_android_tree/sysroot \
+// RUN:   | FileCheck --check-prefix=CHECK-ASAN-ANDROID-X86 %s
+//
+// CHECK-ASAN-ANDROID-X86: "{{(.*[^.0-9A-Z_a-z])?}}ld{{(.exe)?}}"
+// CHECK-ASAN-ANDROID-X86-NOT: "-lc"
+// CHECK-ASAN-ANDROID-X86: "-pie"
+// CHECK-ASAN-ANDROID-X86-NOT: "-lpthread"
+// CHECK-ASAN-ANDROID-X86: libclang_rt.asan-i686-android.so"
+// CHECK-ASAN-ANDROID-X86-NOT: "-lpthread"
+//
+// RUN: %clang -no-canonical-prefixes %s -### -o %t.o 2>&1 \
 // RUN: -target arm-linux-androideabi -fsanitize=address \
 // RUN: --sysroot=%S/Inputs/basic_android_tree/sysroot \
 // RUN: -shared-libasan \
Index: clang/lib/Driver/ToolChain.cpp
===
--- clang/lib/Driver/ToolChain.cpp
+++ clang/lib/Driver/ToolChain.cpp
@@ -305,6 +305,10 @@
? "armhf"
: "arm";
 
+  // For historic reasons, Android library is using i686 instead of i386.
+  if (TC.getArch() == llvm::Triple::x86 && Triple.isAndroid())
+return "i686";
+
   return llvm::Triple::getArchTypeName(TC.getArch());
 }
 


Index: compiler-rt/cmake/Modules/AddCompilerRT.cmake
===
--- compiler-rt/cmake/Modules/AddCompilerRT.cmake
+++ compiler-rt/cmake/Modules/AddCompilerRT.cmake
@@ -86,6 +86,14 @@
   add_dependencies(compiler-rt ${name})
 endfunction()
 
+macro(set_output_name output name arch)
+  if(ANDROID AND ${arch} STREQUAL "i386")
+set(${output} "${name}-i686${COMPILER_RT_OS_SUFFIX}")
+  else()
+set(${output} "${name}-${arch}${COMPILER_RT_OS_SUFFIX}")
+  endif()
+endmacro()
+
 # Adds static or shared runtime for a list of architectures and operating
 # systems and puts it in the proper directory in the build and install trees.
 # add_compiler_rt_runtime(
@@ -142,15 +150,15 @@
   endif()
   if(type STREQUAL "STATIC")
 set(libname "${name}-${arch}")
-set(output_name_${libname} ${libname}${COMPILER_RT_OS_SUFFIX})
+set_output_name(output_name_${libname} ${name} ${arch})
   else()
 set(libname "${name}-dynamic-${arch}")
 set(extra_cflags_${libname} ${TARGET_${arch}_CFLAGS} ${LIB_CFLAGS})
 set(extra_link_flags_${libname} ${TARGET_${arch}_LINK_FLAGS} ${LIB_LINK_FLAGS})
 if(WIN32)
-  set(output_name_${libname} ${name}_dynamic-${arch}${COMPILER_RT_OS_SUFFIX})
+  set_output_name(output_name_${libname} ${name}_dynamic ${arch})
 else()
-  set(output_name_${libname} ${name}-${arch}${COMPILER_RT_OS_SUFFIX})
+  set_output_name(output_name_${libname} ${name} ${arch})
 endif()
   endif()
   set(sources_${libname} ${LIB_SOURCES})
Index: 

[PATCH] D36272: [CodeGen][x86_64] Enable 'force_align_arg_pointer' attribute at x86_64

2017-08-29 Thread Erich Keane via Phabricator via cfe-commits
erichkeane added a comment.

Did you figure out why this doesn't work on windows?  Not having the 
windows-specific x64 test seems like a mistake, unless we're going to make this 
a linux-only attribute.  In which case, you'll have to remove this attribute in 
the 32-bit windows case.


https://reviews.llvm.org/D36272



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


r312047 - Revert "[SanitizeCoverage] Enable stack-depth coverage for -fsanitize=fuzzer"

2017-08-29 Thread Matt Morehouse via cfe-commits
Author: morehouse
Date: Tue Aug 29 14:56:56 2017
New Revision: 312047

URL: http://llvm.org/viewvc/llvm-project?rev=312047=rev
Log:
Revert "[SanitizeCoverage] Enable stack-depth coverage for -fsanitize=fuzzer"

This reverts r312026 due to bot breakage.

Modified:
cfe/trunk/lib/Driver/SanitizerArgs.cpp

Modified: cfe/trunk/lib/Driver/SanitizerArgs.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Driver/SanitizerArgs.cpp?rev=312047=312046=312047=diff
==
--- cfe/trunk/lib/Driver/SanitizerArgs.cpp (original)
+++ cfe/trunk/lib/Driver/SanitizerArgs.cpp Tue Aug 29 14:56:56 2017
@@ -312,13 +312,9 @@ SanitizerArgs::SanitizerArgs(const ToolC
 Add |= FuzzerNoLink;
 
   // Enable coverage if the fuzzing flag is set.
-  if (Add & FuzzerNoLink) {
+  if (Add & FuzzerNoLink)
 CoverageFeatures |= CoverageTracePCGuard | CoverageIndirCall |
 CoverageTraceCmp | CoveragePCTable;
-// Due to TLS differences, stack depth tracking is disabled on Mac.
-if (!TC.getTriple().isOSDarwin())
-  CoverageFeatures |= CoverageStackDepth;
-  }
 
   Kinds |= Add;
 } else if (Arg->getOption().matches(options::OPT_fno_sanitize_EQ)) {


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


[PATCH] D36272: [CodeGen][x86_64] Enable 'force_align_arg_pointer' attribute at x86_64

2017-08-29 Thread Anatol Pomozov via Phabricator via cfe-commits
anatol.pomozov updated this revision to Diff 113166.
anatol.pomozov edited the summary of this revision.

https://reviews.llvm.org/D36272

Files:
  include/clang/Basic/Attr.td
  lib/CodeGen/TargetInfo.cpp
  test/CodeGen/function-attributes.c


Index: test/CodeGen/function-attributes.c
===
--- test/CodeGen/function-attributes.c
+++ test/CodeGen/function-attributes.c
@@ -1,5 +1,6 @@
 // RUN: %clang_cc1 -triple i386-unknown-unknown -emit-llvm 
-disable-llvm-passes -Os -o - %s | FileCheck %s
 // RUN: %clang_cc1 -triple i386-unknown-unknown -emit-llvm 
-disable-llvm-passes -Os -std=c99 -o - %s | FileCheck %s
+// RUN: %clang_cc1 -triple x86_64-unknown-unknown -emit-llvm 
-disable-llvm-passes -Os -std=c99 -o - %s | FileCheck %s
 // CHECK: define signext i8 @f0(i32 %x) [[NUW:#[0-9]+]]
 // CHECK: define zeroext i8 @f1(i32 %x) [[NUW]]
 // CHECK: define void @f2(i8 signext %x) [[NUW]]
Index: lib/CodeGen/TargetInfo.cpp
===
--- lib/CodeGen/TargetInfo.cpp
+++ lib/CodeGen/TargetInfo.cpp
@@ -2297,6 +2297,15 @@
 if (!IsForDefinition)
   return;
 if (const FunctionDecl *FD = dyn_cast_or_null(D)) {
+  if (FD->hasAttr()) {
+// Get the LLVM function.
+auto *Fn = cast(GV);
+
+// Now add the 'alignstack' attribute with a value of 16.
+llvm::AttrBuilder B;
+B.addStackAlignmentAttr(16);
+Fn->addAttributes(llvm::AttributeList::FunctionIndex, B);
+  }
   if (FD->hasAttr()) {
 llvm::Function *Fn = cast(GV);
 Fn->setCallingConv(llvm::CallingConv::X86_INTR);
@@ -2425,6 +2434,15 @@
   if (!IsForDefinition)
 return;
   if (const FunctionDecl *FD = dyn_cast_or_null(D)) {
+if (FD->hasAttr()) {
+  // Get the LLVM function.
+  auto *Fn = cast(GV);
+
+  // Now add the 'alignstack' attribute with a value of 16.
+  llvm::AttrBuilder B;
+  B.addStackAlignmentAttr(16);
+  Fn->addAttributes(llvm::AttributeList::FunctionIndex, B);
+}
 if (FD->hasAttr()) {
   llvm::Function *Fn = cast(GV);
   Fn->setCallingConv(llvm::CallingConv::X86_INTR);
Index: include/clang/Basic/Attr.td
===
--- include/clang/Basic/Attr.td
+++ include/clang/Basic/Attr.td
@@ -2042,7 +2042,7 @@
   let Documentation = [AnyX86NoCallerSavedRegistersDocs];
 }
 
-def X86ForceAlignArgPointer : InheritableAttr, TargetSpecificAttr {
+def X86ForceAlignArgPointer : InheritableAttr, 
TargetSpecificAttr {
   let Spellings = [GNU<"force_align_arg_pointer">];
   // Technically, this appertains to a FunctionDecl, but the target-specific
   // code silently allows anything function-like (such as typedefs or function


Index: test/CodeGen/function-attributes.c
===
--- test/CodeGen/function-attributes.c
+++ test/CodeGen/function-attributes.c
@@ -1,5 +1,6 @@
 // RUN: %clang_cc1 -triple i386-unknown-unknown -emit-llvm -disable-llvm-passes -Os -o - %s | FileCheck %s
 // RUN: %clang_cc1 -triple i386-unknown-unknown -emit-llvm -disable-llvm-passes -Os -std=c99 -o - %s | FileCheck %s
+// RUN: %clang_cc1 -triple x86_64-unknown-unknown -emit-llvm -disable-llvm-passes -Os -std=c99 -o - %s | FileCheck %s
 // CHECK: define signext i8 @f0(i32 %x) [[NUW:#[0-9]+]]
 // CHECK: define zeroext i8 @f1(i32 %x) [[NUW]]
 // CHECK: define void @f2(i8 signext %x) [[NUW]]
Index: lib/CodeGen/TargetInfo.cpp
===
--- lib/CodeGen/TargetInfo.cpp
+++ lib/CodeGen/TargetInfo.cpp
@@ -2297,6 +2297,15 @@
 if (!IsForDefinition)
   return;
 if (const FunctionDecl *FD = dyn_cast_or_null(D)) {
+  if (FD->hasAttr()) {
+// Get the LLVM function.
+auto *Fn = cast(GV);
+
+// Now add the 'alignstack' attribute with a value of 16.
+llvm::AttrBuilder B;
+B.addStackAlignmentAttr(16);
+Fn->addAttributes(llvm::AttributeList::FunctionIndex, B);
+  }
   if (FD->hasAttr()) {
 llvm::Function *Fn = cast(GV);
 Fn->setCallingConv(llvm::CallingConv::X86_INTR);
@@ -2425,6 +2434,15 @@
   if (!IsForDefinition)
 return;
   if (const FunctionDecl *FD = dyn_cast_or_null(D)) {
+if (FD->hasAttr()) {
+  // Get the LLVM function.
+  auto *Fn = cast(GV);
+
+  // Now add the 'alignstack' attribute with a value of 16.
+  llvm::AttrBuilder B;
+  B.addStackAlignmentAttr(16);
+  Fn->addAttributes(llvm::AttributeList::FunctionIndex, B);
+}
 if (FD->hasAttr()) {
   llvm::Function *Fn = cast(GV);
   Fn->setCallingConv(llvm::CallingConv::X86_INTR);
Index: include/clang/Basic/Attr.td
===
--- include/clang/Basic/Attr.td
+++ include/clang/Basic/Attr.td
@@ -2042,7 +2042,7 @@
   let Documentation = [AnyX86NoCallerSavedRegistersDocs];
 }

[PATCH] D37278: Restore clang_rt library name on i686-android.

2017-08-29 Thread Hans Wennborg via Phabricator via cfe-commits
hans accepted this revision.
hans added a comment.
This revision is now accepted and ready to land.

Thanks! Looks good to me.




Comment at: clang/lib/Driver/ToolChain.cpp:308
 
+  if (TC.getArch() == llvm::Triple::x86 && Triple.isAndroid())
+return "i686";

Maybe add a comment here explaining that this is for historical reasons. Or in 
the cmake file below (or both).


https://reviews.llvm.org/D37278



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


[PATCH] D37278: Restore clang_rt library name on i686-android.

2017-08-29 Thread Evgenii Stepanov via Phabricator via cfe-commits
eugenis created this revision.
Herald added a subscriber: srhines.

Recent changes canonicalized clang_rt library names to refer to
"i386" on all x86 targets. Android historically uses i686.

This change adds a special case to keep i686 in all clang_rt
libraries when targeting Android.


https://reviews.llvm.org/D37278

Files:
  clang/lib/Driver/ToolChain.cpp
  clang/test/Driver/sanitizer-ld.c
  compiler-rt/cmake/Modules/AddCompilerRT.cmake


Index: compiler-rt/cmake/Modules/AddCompilerRT.cmake
===
--- compiler-rt/cmake/Modules/AddCompilerRT.cmake
+++ compiler-rt/cmake/Modules/AddCompilerRT.cmake
@@ -86,6 +86,14 @@
   add_dependencies(compiler-rt ${name})
 endfunction()
 
+macro(set_output_name output name arch)
+  if(ANDROID AND ${arch} STREQUAL "i386")
+set(${output} "${name}-i686${COMPILER_RT_OS_SUFFIX}")
+  else()
+set(${output} "${name}-${arch}${COMPILER_RT_OS_SUFFIX}")
+  endif()
+endmacro()
+
 # Adds static or shared runtime for a list of architectures and operating
 # systems and puts it in the proper directory in the build and install trees.
 # add_compiler_rt_runtime(
@@ -142,15 +150,15 @@
   endif()
   if(type STREQUAL "STATIC")
 set(libname "${name}-${arch}")
-set(output_name_${libname} ${libname}${COMPILER_RT_OS_SUFFIX})
+set_output_name(output_name_${libname} ${name} ${arch})
   else()
 set(libname "${name}-dynamic-${arch}")
 set(extra_cflags_${libname} ${TARGET_${arch}_CFLAGS} ${LIB_CFLAGS})
 set(extra_link_flags_${libname} ${TARGET_${arch}_LINK_FLAGS} 
${LIB_LINK_FLAGS})
 if(WIN32)
-  set(output_name_${libname} 
${name}_dynamic-${arch}${COMPILER_RT_OS_SUFFIX})
+  set_output_name(output_name_${libname} ${name}_dynamic ${arch})
 else()
-  set(output_name_${libname} ${name}-${arch}${COMPILER_RT_OS_SUFFIX})
+  set_output_name(output_name_${libname} ${name} ${arch})
 endif()
   endif()
   set(sources_${libname} ${LIB_SOURCES})
Index: clang/test/Driver/sanitizer-ld.c
===
--- clang/test/Driver/sanitizer-ld.c
+++ clang/test/Driver/sanitizer-ld.c
@@ -133,6 +133,18 @@
 // CHECK-ASAN-ANDROID-NOT: "-lpthread"
 //
 // RUN: %clang -no-canonical-prefixes %s -### -o %t.o 2>&1 \
+// RUN: -target i686-linux-android -fuse-ld=ld -fsanitize=address \
+// RUN: --sysroot=%S/Inputs/basic_android_tree/sysroot \
+// RUN:   | FileCheck --check-prefix=CHECK-ASAN-ANDROID-X86 %s
+//
+// CHECK-ASAN-ANDROID-X86: "{{(.*[^.0-9A-Z_a-z])?}}ld{{(.exe)?}}"
+// CHECK-ASAN-ANDROID-X86-NOT: "-lc"
+// CHECK-ASAN-ANDROID-X86: "-pie"
+// CHECK-ASAN-ANDROID-X86-NOT: "-lpthread"
+// CHECK-ASAN-ANDROID-X86: libclang_rt.asan-i686-android.so"
+// CHECK-ASAN-ANDROID-X86-NOT: "-lpthread"
+//
+// RUN: %clang -no-canonical-prefixes %s -### -o %t.o 2>&1 \
 // RUN: -target arm-linux-androideabi -fsanitize=address \
 // RUN: --sysroot=%S/Inputs/basic_android_tree/sysroot \
 // RUN: -shared-libasan \
Index: clang/lib/Driver/ToolChain.cpp
===
--- clang/lib/Driver/ToolChain.cpp
+++ clang/lib/Driver/ToolChain.cpp
@@ -305,6 +305,9 @@
? "armhf"
: "arm";
 
+  if (TC.getArch() == llvm::Triple::x86 && Triple.isAndroid())
+return "i686";
+
   return llvm::Triple::getArchTypeName(TC.getArch());
 }
 


Index: compiler-rt/cmake/Modules/AddCompilerRT.cmake
===
--- compiler-rt/cmake/Modules/AddCompilerRT.cmake
+++ compiler-rt/cmake/Modules/AddCompilerRT.cmake
@@ -86,6 +86,14 @@
   add_dependencies(compiler-rt ${name})
 endfunction()
 
+macro(set_output_name output name arch)
+  if(ANDROID AND ${arch} STREQUAL "i386")
+set(${output} "${name}-i686${COMPILER_RT_OS_SUFFIX}")
+  else()
+set(${output} "${name}-${arch}${COMPILER_RT_OS_SUFFIX}")
+  endif()
+endmacro()
+
 # Adds static or shared runtime for a list of architectures and operating
 # systems and puts it in the proper directory in the build and install trees.
 # add_compiler_rt_runtime(
@@ -142,15 +150,15 @@
   endif()
   if(type STREQUAL "STATIC")
 set(libname "${name}-${arch}")
-set(output_name_${libname} ${libname}${COMPILER_RT_OS_SUFFIX})
+set_output_name(output_name_${libname} ${name} ${arch})
   else()
 set(libname "${name}-dynamic-${arch}")
 set(extra_cflags_${libname} ${TARGET_${arch}_CFLAGS} ${LIB_CFLAGS})
 set(extra_link_flags_${libname} ${TARGET_${arch}_LINK_FLAGS} ${LIB_LINK_FLAGS})
 if(WIN32)
-  set(output_name_${libname} ${name}_dynamic-${arch}${COMPILER_RT_OS_SUFFIX})
+  set_output_name(output_name_${libname} ${name}_dynamic ${arch})
 else()
-  set(output_name_${libname} ${name}-${arch}${COMPILER_RT_OS_SUFFIX})
+  

r312037 - Re-enable stack depth instrumentation on Windows.

2017-08-29 Thread Matt Morehouse via cfe-commits
Author: morehouse
Date: Tue Aug 29 14:15:33 2017
New Revision: 312037

URL: http://llvm.org/viewvc/llvm-project?rev=312037=rev
Log:
Re-enable stack depth instrumentation on Windows.

Specified tls_model attribute properly. Should compile on Windows
now.

Modified:
cfe/trunk/lib/Driver/SanitizerArgs.cpp

Modified: cfe/trunk/lib/Driver/SanitizerArgs.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Driver/SanitizerArgs.cpp?rev=312037=312036=312037=diff
==
--- cfe/trunk/lib/Driver/SanitizerArgs.cpp (original)
+++ cfe/trunk/lib/Driver/SanitizerArgs.cpp Tue Aug 29 14:15:33 2017
@@ -315,8 +315,8 @@ SanitizerArgs::SanitizerArgs(const ToolC
   if (Add & FuzzerNoLink) {
 CoverageFeatures |= CoverageTracePCGuard | CoverageIndirCall |
 CoverageTraceCmp | CoveragePCTable;
-// Due to TLS differences, stack depth tracking is disabled on Mac/Win.
-if (!TC.getTriple().isOSDarwin() && !TC.getTriple().isOSWindows())
+// Due to TLS differences, stack depth tracking is disabled on Mac.
+if (!TC.getTriple().isOSDarwin())
   CoverageFeatures |= CoverageStackDepth;
   }
 


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


[PATCH] D26764: [compiler-rt] [cmake] Remove i686 target that is duplicate to i386

2017-08-29 Thread Hans Wennborg via Phabricator via cfe-commits
hans added a comment.

In https://reviews.llvm.org/D26764#855791, @eugenis wrote:

> IMHO it was a very bad idea to include the "architecture name" (not even a 
> target triple!) in the library path in the first place. No one else does 
> that. GCC made the right choice and called theirs "libasan.so".
>
> My plan is to tweak the code that sets the library name to use i686 when the 
> target is i386 and the os is android, both in compiler-rt and in clang. There 
> will be no duplicate targets.


Sounds good to me. Let me know if you think this will take a while and we 
should revert to green in the meantime.


Repository:
  rL LLVM

https://reviews.llvm.org/D26764



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


[PATCH] D37042: Teach clang to tolerate the 'p = nullptr + n' idiom used by glibc

2017-08-29 Thread Richard Smith - zygoloid via Phabricator via cfe-commits
rsmith added a comment.

In https://reviews.llvm.org/D37042#855713, @efriedma wrote:

> I didn't think of this earlier, but strictly speaking, I think 
> "(char*)nullptr+0" isn't undefined in C++?


Yes, that's correct. (C++'s model is basically equivalent to having an object 
of size zero at the null address, so things like `(char*)nullptr - 
(char*)nullptr` and `(char*)nullptr + 0` are valid.)

> But probably worth emitting the warning anyway; anyone writing out arithmetic 
> on null is probably doing something suspicious, even if it isn't technically 
> undefined.

I agree. We should probably suppress the warning if the non-pointer operand is 
known to be zero in C++, and weaken the wording slightly "[..] has undefined 
behavior if offset is nonzero" otherwise, though.




Comment at: include/clang/Basic/DiagnosticSemaKinds.td:6032
+def ext_gnu_null_ptr_arith : Extension<
+  "inttoptr casting using arithmetic on a null pointer is a GNU extension">,
+  InGroup;

efriedma wrote:
> The keyword "inttoptr" is part of LLVM, not something we expect users to 
> understand.
How about something like "arithmetic on null pointer treated as cast from 
integer to pointer as a GNU extension"?



Comment at: lib/Sema/SemaExpr.cpp:8799
 
+  // Adding to a null pointer is never an error, but should warn.
+  if (PExp->IgnoreParenCasts()->isNullPointerConstant(Context, 

Maybe `// Adding to a null pointer results in undefined behavior.` to explain 
why we warn (a reader of the code can already see that we do warn in this case).



Comment at: lib/Sema/SemaExpr.cpp:8805
+const PointerType *pointerType = PExp->getType()->getAs();
+if (!IExp->isIntegerConstantExpr(Context) &&
+pointerType->getPointeeType()->isCharType() &&

It seems strange to me to disable this when the RHS is an ICE. If we're going 
to support this as an extension, we should make the rules for it as simple as 
we reasonably can; this ICE check seems like an unnecessary complication.


https://reviews.llvm.org/D37042



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


r312032 - Disable stack depth tracking on Windows.

2017-08-29 Thread Matt Morehouse via cfe-commits
Author: morehouse
Date: Tue Aug 29 13:44:41 2017
New Revision: 312032

URL: http://llvm.org/viewvc/llvm-project?rev=312032=rev
Log:
Disable stack depth tracking on Windows.

Windows doesn't support the tls_model attribute.

Modified:
cfe/trunk/lib/Driver/SanitizerArgs.cpp

Modified: cfe/trunk/lib/Driver/SanitizerArgs.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Driver/SanitizerArgs.cpp?rev=312032=312031=312032=diff
==
--- cfe/trunk/lib/Driver/SanitizerArgs.cpp (original)
+++ cfe/trunk/lib/Driver/SanitizerArgs.cpp Tue Aug 29 13:44:41 2017
@@ -315,8 +315,8 @@ SanitizerArgs::SanitizerArgs(const ToolC
   if (Add & FuzzerNoLink) {
 CoverageFeatures |= CoverageTracePCGuard | CoverageIndirCall |
 CoverageTraceCmp | CoveragePCTable;
-// Due to TLS differences, stack depth tracking is disabled on Mac.
-if (!TC.getTriple().isOSDarwin())
+// Due to TLS differences, stack depth tracking is disabled on Mac/Win.
+if (!TC.getTriple().isOSDarwin() && !TC.getTriple().isOSWindows())
   CoverageFeatures |= CoverageStackDepth;
   }
 


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


[PATCH] D26764: [compiler-rt] [cmake] Remove i686 target that is duplicate to i386

2017-08-29 Thread Evgenii Stepanov via Phabricator via cfe-commits
eugenis added a comment.

IMHO it was a very bad idea to include the "architecture name" (not even a 
target triple!) in the library path in the first place. No one else does that. 
GCC made the right choice and called theirs "libasan.so".

My plan is to tweak the code that sets the library name to use i686 when the 
target is i386 and the os is android, both in compiler-rt and in clang. There 
will be no duplicate targets.


Repository:
  rL LLVM

https://reviews.llvm.org/D26764



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


r312029 - Minimal runtime for UBSan.

2017-08-29 Thread Evgeniy Stepanov via cfe-commits
Author: eugenis
Date: Tue Aug 29 13:03:51 2017
New Revision: 312029

URL: http://llvm.org/viewvc/llvm-project?rev=312029=rev
Log:
Minimal runtime for UBSan.

Summary:
An implementation of ubsan runtime library suitable for use in production.

Minimal attack surface.
* No stack traces.
* Definitely no C++ demangling.
* No UBSAN_OPTIONS=log_file=/path (very suid-unfriendly). And no UBSAN_OPTIONS 
in general.
* as simple as possible

Minimal CPU and RAM overhead.
* Source locations unnecessary in the presence of (split) debug info.
* Values and types (as in A+B overflows T) can be reconstructed from 
register/stack dumps, once you know what type of error you are looking at.
* above two items save 3% binary size.

When UBSan is used with -ftrap-function=abort, sometimes it is hard to reason 
about failures. This library replaces abort with a slightly more informative 
message without much extra overhead. Since ubsan interface in not stable, this 
code must reside in compiler-rt.

Reviewers: pcc, kcc

Subscribers: srhines, mgorny, aprantl, krytarowski, llvm-commits

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

Added:
cfe/trunk/test/CodeGen/unsigned-overflow-minimal.c
Modified:
cfe/trunk/include/clang/Driver/Options.td
cfe/trunk/include/clang/Driver/SanitizerArgs.h
cfe/trunk/include/clang/Frontend/CodeGenOptions.def
cfe/trunk/lib/CodeGen/CGExpr.cpp
cfe/trunk/lib/Driver/SanitizerArgs.cpp
cfe/trunk/lib/Driver/ToolChains/CommonArgs.cpp
cfe/trunk/lib/Frontend/CompilerInvocation.cpp
cfe/trunk/test/Driver/fsanitize.c
cfe/trunk/test/Driver/sanitizer-ld.c

Modified: cfe/trunk/include/clang/Driver/Options.td
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Driver/Options.td?rev=312029=312028=312029=diff
==
--- cfe/trunk/include/clang/Driver/Options.td (original)
+++ cfe/trunk/include/clang/Driver/Options.td Tue Aug 29 13:03:51 2017
@@ -885,6 +885,10 @@ def fsanitize_undefined_trap_on_error :
 Group;
 def fno_sanitize_undefined_trap_on_error : Flag<["-"], 
"fno-sanitize-undefined-trap-on-error">,
Group;
+def fsanitize_minimal_runtime : Flag<["-"], "fsanitize-minimal-runtime">,
+Group;
+def fno_sanitize_minimal_runtime : Flag<["-"], "fno-sanitize-minimal-runtime">,
+Group;
 def fsanitize_link_cxx_runtime : Flag<["-"], "fsanitize-link-c++-runtime">,
  Group;
 def fsanitize_cfi_cross_dso : Flag<["-"], "fsanitize-cfi-cross-dso">,

Modified: cfe/trunk/include/clang/Driver/SanitizerArgs.h
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Driver/SanitizerArgs.h?rev=312029=312028=312029=diff
==
--- cfe/trunk/include/clang/Driver/SanitizerArgs.h (original)
+++ cfe/trunk/include/clang/Driver/SanitizerArgs.h Tue Aug 29 13:03:51 2017
@@ -43,6 +43,7 @@ class SanitizerArgs {
   bool TsanMemoryAccess = true;
   bool TsanFuncEntryExit = true;
   bool TsanAtomics = true;
+  bool MinimalRuntime = false;
 
  public:
   /// Parses the sanitizer arguments from an argument list.
@@ -58,6 +59,7 @@ class SanitizerArgs {
!Sanitizers.has(SanitizerKind::Address);
   }
   bool needsUbsanRt() const;
+  bool requiresMinimalRuntime() const { return MinimalRuntime; }
   bool needsDfsanRt() const { return Sanitizers.has(SanitizerKind::DataFlow); }
   bool needsSafeStackRt() const { return SafeStackRuntime; }
   bool needsCfiRt() const;

Modified: cfe/trunk/include/clang/Frontend/CodeGenOptions.def
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Frontend/CodeGenOptions.def?rev=312029=312028=312029=diff
==
--- cfe/trunk/include/clang/Frontend/CodeGenOptions.def (original)
+++ cfe/trunk/include/clang/Frontend/CodeGenOptions.def Tue Aug 29 13:03:51 2017
@@ -152,6 +152,8 @@ CODEGENOPT(SanitizeMemoryTrackOrigins, 2
 CODEGENOPT(SanitizeMemoryUseAfterDtor, 1, 0) ///< Enable use-after-delete 
detection
  ///< in MemorySanitizer
 CODEGENOPT(SanitizeCfiCrossDso, 1, 0) ///< Enable cross-dso support in CFI.
+CODEGENOPT(SanitizeMinimalRuntime, 1, 0) ///< Use "_minimal" sanitizer runtime 
for
+ ///< diagnostics.
 CODEGENOPT(SanitizeCoverageType, 2, 0) ///< Type of sanitizer coverage
///< instrumentation.
 CODEGENOPT(SanitizeCoverageIndirectCalls, 1, 0) ///< Enable sanitizer coverage

Modified: cfe/trunk/lib/CodeGen/CGExpr.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/CodeGen/CGExpr.cpp?rev=312029=312028=312029=diff
==
--- 

[PATCH] D37156: [SanitizeCoverage] Enable stack-depth coverage for -fsanitize=fuzzer

2017-08-29 Thread Matt Morehouse via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rL312026: [SanitizeCoverage] Enable stack-depth coverage for 
-fsanitize=fuzzer (authored by morehouse).

Changed prior to commit:
  https://reviews.llvm.org/D37156?vs=113133=113136#toc

Repository:
  rL LLVM

https://reviews.llvm.org/D37156

Files:
  cfe/trunk/lib/Driver/SanitizerArgs.cpp
  compiler-rt/trunk/lib/sanitizer_common/sanitizer_coverage_libcdep_new.cc
  compiler-rt/trunk/lib/sanitizer_common/sanitizer_internal_defs.h
  compiler-rt/trunk/test/fuzzer/deep-recursion.test
  llvm/trunk/lib/Transforms/Instrumentation/SanitizerCoverage.cpp
  llvm/trunk/test/Instrumentation/SanitizerCoverage/stack-depth.ll

Index: llvm/trunk/test/Instrumentation/SanitizerCoverage/stack-depth.ll
===
--- llvm/trunk/test/Instrumentation/SanitizerCoverage/stack-depth.ll
+++ llvm/trunk/test/Instrumentation/SanitizerCoverage/stack-depth.ll
@@ -1,9 +1,9 @@
 ; This check verifies that stack depth instrumentation works correctly.
 ; RUN: opt < %s -sancov -sanitizer-coverage-level=1 \
-; RUN: -sanitizer-coverage-stack-depth -S | FileCheck %s --enable-var-scope
+; RUN: -sanitizer-coverage-stack-depth -S | FileCheck %s
 ; RUN: opt < %s -sancov -sanitizer-coverage-level=3 \
 ; RUN: -sanitizer-coverage-stack-depth -sanitizer-coverage-trace-pc-guard \
-; RUN: -S | FileCheck %s --enable-var-scope
+; RUN: -S | FileCheck %s
 
 target datalayout = "e-m:e-i64:64-f80:128-n8:16:32:64-S128"
 target triple = "x86_64-unknown-linux-gnu"
@@ -14,13 +14,8 @@
 define i32 @foo() {
 entry:
 ; CHECK-LABEL: define i32 @foo
-; CHECK: [[framePtr:%[^ \t]+]] = call i8* @llvm.frameaddress(i32 0)
-; CHECK: [[frameInt:%[^ \t]+]] = ptrtoint i8* [[framePtr]] to [[$intType:i[0-9]+]]
-; CHECK: [[lowest:%[^ \t]+]] = load [[$intType]], [[$intType]]* @__sancov_lowest_stack
-; CHECK: [[cmp:%[^ \t]+]] = icmp ult [[$intType]] [[frameInt]], [[lowest]]
-; CHECK: br i1 [[cmp]], label %[[ifLabel:[^ \t]+]], label
-; CHECK: :[[ifLabel]]:
-; CHECK: store [[$intType]] [[frameInt]], [[$intType]]* @__sancov_lowest_stack
+; CHECK-NOT: call i8* @llvm.frameaddress(i32 0)
+; CHECK-NOT: @__sancov_lowest_stack
 ; CHECK: ret i32 7
 
   ret i32 7
@@ -30,12 +25,12 @@
 entry:
 ; CHECK-LABEL: define i32 @bar
 ; CHECK: [[framePtr:%[^ \t]+]] = call i8* @llvm.frameaddress(i32 0)
-; CHECK: [[frameInt:%[^ \t]+]] = ptrtoint i8* [[framePtr]] to [[$intType]]
-; CHECK: [[lowest:%[^ \t]+]] = load [[$intType]], [[$intType]]* @__sancov_lowest_stack
-; CHECK: [[cmp:%[^ \t]+]] = icmp ult [[$intType]] [[frameInt]], [[lowest]]
+; CHECK: [[frameInt:%[^ \t]+]] = ptrtoint i8* [[framePtr]] to [[intType:i[0-9]+]]
+; CHECK: [[lowest:%[^ \t]+]] = load [[intType]], [[intType]]* @__sancov_lowest_stack
+; CHECK: [[cmp:%[^ \t]+]] = icmp ult [[intType]] [[frameInt]], [[lowest]]
 ; CHECK: br i1 [[cmp]], label %[[ifLabel:[^ \t]+]], label
 ; CHECK: :[[ifLabel]]:
-; CHECK: store [[$intType]] [[frameInt]], [[$intType]]* @__sancov_lowest_stack
+; CHECK: store [[intType]] [[frameInt]], [[intType]]* @__sancov_lowest_stack
 ; CHECK: %call = call i32 @foo()
 ; CHECK: ret i32 %call
 
Index: llvm/trunk/lib/Transforms/Instrumentation/SanitizerCoverage.cpp
===
--- llvm/trunk/lib/Transforms/Instrumentation/SanitizerCoverage.cpp
+++ llvm/trunk/lib/Transforms/Instrumentation/SanitizerCoverage.cpp
@@ -25,6 +25,7 @@
 #include "llvm/IR/GlobalVariable.h"
 #include "llvm/IR/IRBuilder.h"
 #include "llvm/IR/InlineAsm.h"
+#include "llvm/IR/IntrinsicInst.h"
 #include "llvm/IR/Intrinsics.h"
 #include "llvm/IR/LLVMContext.h"
 #include "llvm/IR/MDBuilder.h"
@@ -200,13 +201,15 @@
  ArrayRef GepTraceTargets);
   void InjectTraceForSwitch(Function ,
 ArrayRef SwitchTraceTargets);
-  bool InjectCoverage(Function , ArrayRef AllBlocks);
+  bool InjectCoverage(Function , ArrayRef AllBlocks,
+  bool IsLeafFunc = true);
   GlobalVariable *CreateFunctionLocalArrayInSection(size_t NumElements,
 Function , Type *Ty,
 const char *Section);
   GlobalVariable *CreatePCArray(Function , ArrayRef AllBlocks);
   void CreateFunctionLocalArrays(Function , ArrayRef AllBlocks);
-  void InjectCoverageAtBlock(Function , BasicBlock , size_t Idx);
+  void InjectCoverageAtBlock(Function , BasicBlock , size_t Idx,
+ bool IsLeafFunc = true);
   Function *CreateInitCallsForSections(Module , const char *InitFunctionName,
Type *Ty, const char *Section);
   std::pair
@@ -491,6 +494,7 @@
   (F).getDomTree();
   const PostDominatorTree *PDT =
   (F).getPostDomTree();
+  bool IsLeafFunc = true;
 
   for (auto  : F) {
 if (shouldInstrumentBlock(F, , DT, PDT, Options))
@@ -515,10 +519,14 @@
   

r312026 - [SanitizeCoverage] Enable stack-depth coverage for -fsanitize=fuzzer

2017-08-29 Thread Matt Morehouse via cfe-commits
Author: morehouse
Date: Tue Aug 29 12:48:12 2017
New Revision: 312026

URL: http://llvm.org/viewvc/llvm-project?rev=312026=rev
Log:
[SanitizeCoverage] Enable stack-depth coverage for -fsanitize=fuzzer

Summary:
- Don't sanitize __sancov_lowest_stack.
- Don't instrument leaf functions.
- Add CoverageStackDepth to Fuzzer and FuzzerNoLink.
- Disable stack depth tracking on Mac.

Reviewers: vitalybuka, kcc, george.karpenkov

Reviewed By: kcc

Subscribers: kubamracek, cfe-commits, llvm-commits, hiraditya

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

Modified:
cfe/trunk/lib/Driver/SanitizerArgs.cpp

Modified: cfe/trunk/lib/Driver/SanitizerArgs.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Driver/SanitizerArgs.cpp?rev=312026=312025=312026=diff
==
--- cfe/trunk/lib/Driver/SanitizerArgs.cpp (original)
+++ cfe/trunk/lib/Driver/SanitizerArgs.cpp Tue Aug 29 12:48:12 2017
@@ -291,9 +291,13 @@ SanitizerArgs::SanitizerArgs(const ToolC
 Add |= FuzzerNoLink;
 
   // Enable coverage if the fuzzing flag is set.
-  if (Add & FuzzerNoLink)
+  if (Add & FuzzerNoLink) {
 CoverageFeatures |= CoverageTracePCGuard | CoverageIndirCall |
 CoverageTraceCmp | CoveragePCTable;
+// Due to TLS differences, stack depth tracking is disabled on Mac.
+if (!TC.getTriple().isOSDarwin())
+  CoverageFeatures |= CoverageStackDepth;
+  }
 
   Kinds |= Add;
 } else if (Arg->getOption().matches(options::OPT_fno_sanitize_EQ)) {


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


[PATCH] D37156: [SanitizeCoverage] Enable stack-depth coverage for -fsanitize=fuzzer

2017-08-29 Thread Kostya Serebryany via Phabricator via cfe-commits
kcc accepted this revision.
kcc added a comment.

LGTM


https://reviews.llvm.org/D37156



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


r312024 - [OPENMP] Capture global variables in all target executable regions.

2017-08-29 Thread Alexey Bataev via cfe-commits
Author: abataev
Date: Tue Aug 29 12:30:57 2017
New Revision: 312024

URL: http://llvm.org/viewvc/llvm-project?rev=312024=rev
Log:
[OPENMP] Capture global variables in all target executable regions.

Capturing of the global variables occurs only in target regions. Patch
fixes it and allows capturing of globals in all target executable
directives.

Modified:
cfe/trunk/lib/Sema/SemaOpenMP.cpp
cfe/trunk/test/OpenMP/target_teams_codegen.cpp

Modified: cfe/trunk/lib/Sema/SemaOpenMP.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Sema/SemaOpenMP.cpp?rev=312024=312023=312024=diff
==
--- cfe/trunk/lib/Sema/SemaOpenMP.cpp (original)
+++ cfe/trunk/lib/Sema/SemaOpenMP.cpp Tue Aug 29 12:30:57 2017
@@ -1278,7 +1278,7 @@ VarDecl *Sema::IsOpenMPCapturedDecl(Valu
   //
   auto *VD = dyn_cast(D);
   if (VD && !VD->hasLocalStorage()) {
-if (DSAStack->getCurrentDirective() == OMPD_target &&
+if (isOpenMPTargetExecutionDirective(DSAStack->getCurrentDirective()) &&
 !DSAStack->isClauseParsingMode())
   return VD;
 if (DSAStack->hasDirective(

Modified: cfe/trunk/test/OpenMP/target_teams_codegen.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/OpenMP/target_teams_codegen.cpp?rev=312024=312023=312024=diff
==
--- cfe/trunk/test/OpenMP/target_teams_codegen.cpp (original)
+++ cfe/trunk/test/OpenMP/target_teams_codegen.cpp Tue Aug 29 12:30:57 2017
@@ -83,6 +83,8 @@ struct TT{
   ty Y;
 };
 
+int global;
+
 // CHECK: define {{.*}}[[FOO:@.+]](
 int foo(int n) {
   int a = 0;
@@ -178,6 +180,7 @@ int foo(int n) {
   {
 a += 1;
 aa += 1;
+global += 1;
   }
 
   // We capture 3 VLA sizes in this target region
@@ -372,6 +375,7 @@ int foo(int n) {
 // CHECK:   [[AA_ADDR:%.+]] = alloca i[[SZ]], align
 // CHECK:   [[A_CASTED:%.+]] = alloca i[[SZ]], align
 // CHECK:   [[AA_CASTED:%.+]] = alloca i[[SZ]], align
+// CHECK:   [[GLOBAL_CASTED:%.+]] = alloca i[[SZ]], align
 // CHECK-DAG:   store i[[SZ]] %{{.+}}, i[[SZ]]* [[A_ADDR]], align
 // CHECK-DAG:   store i[[SZ]] %{{.+}}, i[[SZ]]* [[AA_ADDR]], align
 // CHECK-64-DAG:[[A_CADDR:%.+]] = bitcast i[[SZ]]* [[A_ADDR]] to i32*
@@ -384,18 +388,28 @@ int foo(int n) {
 // CHECK-DAG:   [[AA:%.+]] = load i16, i16* [[AA_CADDR]], align
 // CHECK-DAG:   [[AA_C:%.+]] = bitcast i[[SZ]]* [[AA_CASTED]] to i16*
 // CHECK-DAG:   store i16 [[AA]], i16* [[AA_C]], align
+// CHECK-DAG:   [[GLOBAL:%.+]] = load i32, i32* @global, align
+// CHECK-64-DAG:[[GLOBAL_C:%.+]] = bitcast i[[SZ]]* [[GLOBAL_CASTED]] to i32*
+// CHECK-64-DAG:store i32 [[GLOBAL]], i32* [[GLOBAL_C]], align
+// CHECK-32-DAG:store i32 [[GLOBAL]], i32* [[GLOBAL_CASTED]], align
 // CHECK-DAG:   [[PARAM1:%.+]] = load i[[SZ]], i[[SZ]]* [[A_CASTED]], align
 // CHECK-DAG:   [[PARAM2:%.+]] = load i[[SZ]], i[[SZ]]* [[AA_CASTED]], align
-// CHECK-DAG:   call {{.*}}void (%ident_t*, i32, void (i32*, i32*, ...)*, ...) 
@__kmpc_fork_teams(%ident_t* [[DEF_LOC]], i32 2, void (i32*, i32*, ...)* 
bitcast (void (i32*, i32*, i[[SZ]], i[[SZ]])* [[OMP_OUTLINED3:@.+]] to void 
(i32*, i32*, ...)*), i[[SZ]] [[PARAM1]], i[[SZ]] [[PARAM2]])
+// CHECK-DAG:   [[PARAM3:%.+]] = load i[[SZ]], i[[SZ]]* [[GLOBAL_CASTED]], 
align
+// CHECK-DAG:   call {{.*}}void (%ident_t*, i32, void (i32*, i32*, ...)*, ...) 
@__kmpc_fork_teams(%ident_t* [[DEF_LOC]], i32 3, void (i32*, i32*, ...)* 
bitcast (void (i32*, i32*, i[[SZ]], i[[SZ]], i[[SZ]])* [[OMP_OUTLINED3:@.+]] to 
void (i32*, i32*, ...)*), i[[SZ]] [[PARAM1]], i[[SZ]] [[PARAM2]], i[[SZ]] 
[[PARAM3]])
 //
 //
-// CHECK:   define internal {{.*}}void [[OMP_OUTLINED3]](i32* noalias 
%.global_tid., i32* noalias %.bound_tid., i[[SZ]] %{{.+}}, i[[SZ]] %{{.+}})
+// CHECK:   define internal {{.*}}void [[OMP_OUTLINED3]](i32* noalias 
%.global_tid., i32* noalias %.bound_tid., i[[SZ]] %{{.+}}, i[[SZ]] %{{.+}}, 
i[[SZ]] %{{.+}})
 // CHECK:   [[A_ADDR:%.+]] = alloca i[[SZ]], align
 // CHECK:   [[AA_ADDR:%.+]] = alloca i[[SZ]], align
+// CHECK:   [[GLOBAL_ADDR:%.+]] = alloca i[[SZ]], align
 // CHECK-DAG:   store i[[SZ]] %{{.+}}, i[[SZ]]* [[A_ADDR]], align
 // CHECK-DAG:   store i[[SZ]] %{{.+}}, i[[SZ]]* [[AA_ADDR]], align
+// CHECK-DAG:   store i[[SZ]] %{{.+}}, i[[SZ]]* [[GLOBAL_ADDR]], align
 // CHECK-64-DAG:[[A_CADDR:%.+]] = bitcast i[[SZ]]* [[A_ADDR]] to i32*
 // CHECK-DAG:   [[AA_CADDR:%.+]] = bitcast i[[SZ]]* [[AA_ADDR]] to i16*
+// CHECK-64-DAG:[[GLOBAL_CADDR:%.+]] = bitcast i[[SZ]]* [[GLOBAL_ADDR]] to i32*
+// CHECK-64:store i32 {{.+}}, i32* [[GLOBAL_CADDR]],
+// CHECK-32:store i32 {{.+}}, i32* [[GLOBAL_ADDR]],
 // CHECK:   ret void
 // CHECK-NEXT:  }
 


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


[PATCH] D37042: Teach clang to tolerate the 'p = nullptr + n' idiom used by glibc

2017-08-29 Thread Eli Friedman via Phabricator via cfe-commits
efriedma added a reviewer: rsmith.
efriedma added a comment.

I didn't think of this earlier, but strictly speaking, I think 
"(char*)nullptr+0" isn't undefined in C++?  But probably worth emitting the 
warning anyway; anyone writing out arithmetic on null is probably doing 
something suspicious, even if it isn't technically undefined.




Comment at: include/clang/Basic/DiagnosticSemaKinds.td:6032
+def ext_gnu_null_ptr_arith : Extension<
+  "inttoptr casting using arithmetic on a null pointer is a GNU extension">,
+  InGroup;

The keyword "inttoptr" is part of LLVM, not something we expect users to 
understand.



Comment at: lib/Sema/SemaExpr.cpp:8808
+Context.getTypeSize(pointerType) == 
+Context.getTypeSize(IExp->getType()))
+  IsGNUIdiom = true;

Please make sure you use exactly the same check in Sema and CodeGen (probably 
easiest to stick a helper into lib/AST/).


https://reviews.llvm.org/D37042



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


[PATCH] D37042: Teach clang to tolerate the 'p = nullptr + n' idiom used by glibc

2017-08-29 Thread Andy Kaylor via Phabricator via cfe-commits
andrew.w.kaylor updated this revision to Diff 113134.
andrew.w.kaylor added a comment.

Added warnings for null pointer arithmetic.


https://reviews.llvm.org/D37042

Files:
  include/clang/Basic/DiagnosticGroups.td
  include/clang/Basic/DiagnosticSemaKinds.td
  lib/CodeGen/CGExprScalar.cpp
  lib/Sema/SemaExpr.cpp
  test/CodeGen/nullptr-arithmetic.c
  test/Sema/pointer-addition.c

Index: lib/CodeGen/CGExprScalar.cpp
===
--- lib/CodeGen/CGExprScalar.cpp
+++ lib/CodeGen/CGExprScalar.cpp
@@ -2671,6 +2671,37 @@
   unsigned width = cast(index->getType())->getBitWidth();
   auto  = CGF.CGM.getDataLayout();
   auto PtrTy = cast(pointer->getType());
+
+  // Some versions of glibc and gcc use idioms (particularly in their malloc
+  // routines) that add a pointer-sized integer (known to be a pointer value)
+  // to a null pointer in order to cast the value back to an integer or as
+  // part of a pointer alignment algorithm.  This is undefined behavior, but
+  // we'd like to be able to compile programs that use it.
+  //
+  // Normally, we'd generate a GEP with a null-pointer base here in response
+  // to that code, but it's also UB to dereference a pointer created that
+  // way.  Instead (as an acknowledged hack to tolerate the idiom) we will
+  // generate a direct cast of the integer value to a pointer.
+  //
+  // The idiom (p = nullptr + N) is not met if any of the following are true:
+  //
+  //   The operation is subtraction.
+  //   The index is not pointer-sized.
+  //   The pointer type is not byte-sized.
+  //   The index operand is a constant.
+  //
+  if (isa(pointer) && !isSubtraction && 
+  (width == DL.getTypeSizeInBits(PtrTy)) && 
+  !isa(index)) {
+// The pointer type might come back as null, so it's deferred until here.
+const PointerType *pointerType 
+  = pointerOperand->getType()->getAs();
+if (pointerType && pointerType->getPointeeType()->isCharType()) { 
+  // (nullptr + N) -> inttoptr N to 
+  return CGF.Builder.CreateIntToPtr(index, pointer->getType());
+}
+  }
+
   if (width != DL.getTypeSizeInBits(PtrTy)) {
 // Zero-extend or sign-extend the pointer value according to
 // whether the index is signed or not.
Index: lib/Sema/SemaExpr.cpp
===
--- lib/Sema/SemaExpr.cpp
+++ lib/Sema/SemaExpr.cpp
@@ -8490,6 +8490,18 @@
 << 0 /* one pointer */ << Pointer->getSourceRange();
 }
 
+/// \brief Diagnose invalid arithmetic on a null pointer.
+///
+/// If \p IsGNUIdiom is true, the operation is using the 'p = (i8*)nullptr + n'
+/// idiom, which we recognize as a GNU extension.
+///
+static void diagnoseArithmeticOnNullPointer(Sema , SourceLocation Loc,
+Expr *Pointer, bool IsGNUIdiom) {
+  S.Diag(Loc, IsGNUIdiom ? diag::ext_gnu_null_ptr_arith
+ : diag::warn_pointer_arith_null_ptr)
+<< Pointer->getSourceRange();
+}
+
 /// \brief Diagnose invalid arithmetic on two function pointers.
 static void diagnoseArithmeticOnTwoFunctionPointers(Sema , SourceLocation Loc,
 Expr *LHS, Expr *RHS) {
@@ -8784,6 +8796,21 @@
   if (!IExp->getType()->isIntegerType())
 return InvalidOperands(Loc, LHS, RHS);
 
+  // Adding to a null pointer is never an error, but should warn.
+  if (PExp->IgnoreParenCasts()->isNullPointerConstant(Context, 
+ Expr::NPC_ValueDependentIsNull)) {
+// Check the conditions to see if this is the 'p = (i8*)nullptr + n' idiom.
+bool IsGNUIdiom = false;
+const PointerType *pointerType = PExp->getType()->getAs();
+if (!IExp->isIntegerConstantExpr(Context) &&
+pointerType->getPointeeType()->isCharType() &&
+Context.getTypeSize(pointerType) == 
+Context.getTypeSize(IExp->getType()))
+  IsGNUIdiom = true;
+
+diagnoseArithmeticOnNullPointer(*this, Loc, PExp, IsGNUIdiom);
+  }
+
   if (!checkArithmeticOpPointerOperand(*this, Loc, PExp))
 return QualType();
 
@@ -8845,6 +8872,13 @@
 
 // The result type of a pointer-int computation is the pointer type.
 if (RHS.get()->getType()->isIntegerType()) {
+  // Subtracting from a null pointer should produce a warning.
+  // The last argument to the diagnose call says this doesn't match the
+  // GNU int-to-pointer idiom.
+  if (LHS.get()->IgnoreParenCasts()->isNullPointerConstant(Context,
+   Expr::NPC_ValueDependentIsNull))
+diagnoseArithmeticOnNullPointer(*this, Loc, LHS.get(), false);
+
   if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get()))
 return QualType();
 
Index: include/clang/Basic/DiagnosticSemaKinds.td
===
--- include/clang/Basic/DiagnosticSemaKinds.td
+++ include/clang/Basic/DiagnosticSemaKinds.td

[PATCH] D37156: [SanitizeCoverage] Enable stack-depth coverage for -fsanitize=fuzzer

2017-08-29 Thread Matt Morehouse via Phabricator via cfe-commits
morehouse updated this revision to Diff 113133.
morehouse added a comment.

- Eliminate "#if".
- Replace uintptr_t with uptr.


https://reviews.llvm.org/D37156

Files:
  clang/lib/Driver/SanitizerArgs.cpp
  compiler-rt/lib/sanitizer_common/sanitizer_coverage_libcdep_new.cc
  compiler-rt/lib/sanitizer_common/sanitizer_internal_defs.h
  compiler-rt/test/fuzzer/deep-recursion.test
  llvm/lib/Transforms/Instrumentation/SanitizerCoverage.cpp
  llvm/test/Instrumentation/SanitizerCoverage/stack-depth.ll

Index: llvm/test/Instrumentation/SanitizerCoverage/stack-depth.ll
===
--- llvm/test/Instrumentation/SanitizerCoverage/stack-depth.ll
+++ llvm/test/Instrumentation/SanitizerCoverage/stack-depth.ll
@@ -1,9 +1,9 @@
 ; This check verifies that stack depth instrumentation works correctly.
 ; RUN: opt < %s -sancov -sanitizer-coverage-level=1 \
-; RUN: -sanitizer-coverage-stack-depth -S | FileCheck %s --enable-var-scope
+; RUN: -sanitizer-coverage-stack-depth -S | FileCheck %s
 ; RUN: opt < %s -sancov -sanitizer-coverage-level=3 \
 ; RUN: -sanitizer-coverage-stack-depth -sanitizer-coverage-trace-pc-guard \
-; RUN: -S | FileCheck %s --enable-var-scope
+; RUN: -S | FileCheck %s
 
 target datalayout = "e-m:e-i64:64-f80:128-n8:16:32:64-S128"
 target triple = "x86_64-unknown-linux-gnu"
@@ -14,13 +14,8 @@
 define i32 @foo() {
 entry:
 ; CHECK-LABEL: define i32 @foo
-; CHECK: [[framePtr:%[^ \t]+]] = call i8* @llvm.frameaddress(i32 0)
-; CHECK: [[frameInt:%[^ \t]+]] = ptrtoint i8* [[framePtr]] to [[$intType:i[0-9]+]]
-; CHECK: [[lowest:%[^ \t]+]] = load [[$intType]], [[$intType]]* @__sancov_lowest_stack
-; CHECK: [[cmp:%[^ \t]+]] = icmp ult [[$intType]] [[frameInt]], [[lowest]]
-; CHECK: br i1 [[cmp]], label %[[ifLabel:[^ \t]+]], label
-; CHECK: :[[ifLabel]]:
-; CHECK: store [[$intType]] [[frameInt]], [[$intType]]* @__sancov_lowest_stack
+; CHECK-NOT: call i8* @llvm.frameaddress(i32 0)
+; CHECK-NOT: @__sancov_lowest_stack
 ; CHECK: ret i32 7
 
   ret i32 7
@@ -30,12 +25,12 @@
 entry:
 ; CHECK-LABEL: define i32 @bar
 ; CHECK: [[framePtr:%[^ \t]+]] = call i8* @llvm.frameaddress(i32 0)
-; CHECK: [[frameInt:%[^ \t]+]] = ptrtoint i8* [[framePtr]] to [[$intType]]
-; CHECK: [[lowest:%[^ \t]+]] = load [[$intType]], [[$intType]]* @__sancov_lowest_stack
-; CHECK: [[cmp:%[^ \t]+]] = icmp ult [[$intType]] [[frameInt]], [[lowest]]
+; CHECK: [[frameInt:%[^ \t]+]] = ptrtoint i8* [[framePtr]] to [[intType:i[0-9]+]]
+; CHECK: [[lowest:%[^ \t]+]] = load [[intType]], [[intType]]* @__sancov_lowest_stack
+; CHECK: [[cmp:%[^ \t]+]] = icmp ult [[intType]] [[frameInt]], [[lowest]]
 ; CHECK: br i1 [[cmp]], label %[[ifLabel:[^ \t]+]], label
 ; CHECK: :[[ifLabel]]:
-; CHECK: store [[$intType]] [[frameInt]], [[$intType]]* @__sancov_lowest_stack
+; CHECK: store [[intType]] [[frameInt]], [[intType]]* @__sancov_lowest_stack
 ; CHECK: %call = call i32 @foo()
 ; CHECK: ret i32 %call
 
Index: llvm/lib/Transforms/Instrumentation/SanitizerCoverage.cpp
===
--- llvm/lib/Transforms/Instrumentation/SanitizerCoverage.cpp
+++ llvm/lib/Transforms/Instrumentation/SanitizerCoverage.cpp
@@ -25,6 +25,7 @@
 #include "llvm/IR/GlobalVariable.h"
 #include "llvm/IR/IRBuilder.h"
 #include "llvm/IR/InlineAsm.h"
+#include "llvm/IR/IntrinsicInst.h"
 #include "llvm/IR/Intrinsics.h"
 #include "llvm/IR/LLVMContext.h"
 #include "llvm/IR/MDBuilder.h"
@@ -200,13 +201,15 @@
  ArrayRef GepTraceTargets);
   void InjectTraceForSwitch(Function ,
 ArrayRef SwitchTraceTargets);
-  bool InjectCoverage(Function , ArrayRef AllBlocks);
+  bool InjectCoverage(Function , ArrayRef AllBlocks,
+  bool IsLeafFunc = true);
   GlobalVariable *CreateFunctionLocalArrayInSection(size_t NumElements,
 Function , Type *Ty,
 const char *Section);
   GlobalVariable *CreatePCArray(Function , ArrayRef AllBlocks);
   void CreateFunctionLocalArrays(Function , ArrayRef AllBlocks);
-  void InjectCoverageAtBlock(Function , BasicBlock , size_t Idx);
+  void InjectCoverageAtBlock(Function , BasicBlock , size_t Idx,
+ bool IsLeafFunc = true);
   Function *CreateInitCallsForSections(Module , const char *InitFunctionName,
Type *Ty, const char *Section);
   std::pair
@@ -491,6 +494,7 @@
   (F).getDomTree();
   const PostDominatorTree *PDT =
   (F).getPostDomTree();
+  bool IsLeafFunc = true;
 
   for (auto  : F) {
 if (shouldInstrumentBlock(F, , DT, PDT, Options))
@@ -515,10 +519,14 @@
   if (Options.TraceGep)
 if (GetElementPtrInst *GEP = dyn_cast())
   GepTraceTargets.push_back(GEP);
-   }
+  if (Options.StackDepth)
+if (isa(Inst) ||
+(isa(Inst) && !isa(Inst)))
+  IsLeafFunc = 

[PATCH] D36272: [CodeGen][x86_64] Enable 'force_align_arg_pointer' attribute at x86_64

2017-08-29 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman added a comment.

In https://reviews.llvm.org/D36272#851709, @erichkeane wrote:

> Aaron would likely know better than me... but could it be the spelling type 
> should be GCC instead of GNU?


Yes, this should be spelled with `GCC` rather than `GNU`, as it's a documented 
GCC attribute and needs the C++11 spelling you get from that switch. That 
doesn't have to be a part of this patch, however, when it gets done, we should 
also add documentation to AttrDocs.td for the attribute.




Comment at: lib/CodeGen/TargetInfo.cpp:2293
+// Get the LLVM function.
+llvm::Function *Fn = cast(GV);
+

You can use `auto *` here instead of spelling out the type twice.



Comment at: lib/CodeGen/TargetInfo.cpp:2430
+  // Get the LLVM function.
+  llvm::Function *Fn = cast(GV);
+

You can use `auto *` here as well.


https://reviews.llvm.org/D36272



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


[PATCH] D26764: [compiler-rt] [cmake] Remove i686 target that is duplicate to i386

2017-08-29 Thread Michał Górny via Phabricator via cfe-commits
mgorny added a comment.

I'm happy to help with whatever needs to be done to keep breakage to the 
minimum, provided that we determine some clear path forward that doesn't 
involve regressing to the half-broken state for non-Android Linux systems and 
it's doable in the free time I can spare. However, I should point out that it 
was a very bad idea to hardcode paths all over the projects in the first place.


Repository:
  rL LLVM

https://reviews.llvm.org/D26764



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


[PATCH] D26764: [compiler-rt] [cmake] Remove i686 target that is duplicate to i386

2017-08-29 Thread Evgenii Stepanov via Phabricator via cfe-commits
eugenis added a comment.

I may have underestimated the number of places that will need to be patched 
because of this change. Perhaps we should restore the special case in the 
android library name?


Repository:
  rL LLVM

https://reviews.llvm.org/D26764



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


[PATCH] D37156: [SanitizeCoverage] Enable stack-depth coverage for -fsanitize=fuzzer

2017-08-29 Thread Kostya Serebryany via Phabricator via cfe-commits
kcc added inline comments.



Comment at: clang/lib/Driver/SanitizerArgs.cpp:297
 CoverageTraceCmp | CoveragePCTable;
+#if !defined(__APPLE__)
+// Due to TLS differences, stack depth tracking is disabled on Mac.

please use if(SomeCondition) instead of #if

In general: 99% of cases where you may want to use #if -- you shouldn't



Comment at: 
compiler-rt/lib/sanitizer_common/sanitizer_coverage_libcdep_new.cc:20
 #include "sanitizer_symbolizer.h"
+#include 
 

no standard hearder in this files. Just use the 'uptr' type. 


https://reviews.llvm.org/D37156



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


[PATCH] D36272: [CodeGen][x86_64] Enable 'force_align_arg_pointer' attribute at x86_64

2017-08-29 Thread Anatol Pomozov via Phabricator via cfe-commits
anatol.pomozov added a comment.

Another fact: gcc 7.2.0 supports this attribute at x86_64. It would be great if 
two major compilers were feature compatible and worked in a similar way.


https://reviews.llvm.org/D36272



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


[PATCH] D37156: [SanitizeCoverage] Enable stack-depth coverage for -fsanitize=fuzzer

2017-08-29 Thread Matt Morehouse via Phabricator via cfe-commits
morehouse updated this revision to Diff 113129.
morehouse added a comment.

- Disable stack depth tracking on Mac.


https://reviews.llvm.org/D37156

Files:
  clang/lib/Driver/SanitizerArgs.cpp
  compiler-rt/lib/sanitizer_common/sanitizer_coverage_libcdep_new.cc
  compiler-rt/lib/sanitizer_common/sanitizer_internal_defs.h
  compiler-rt/test/fuzzer/deep-recursion.test
  llvm/lib/Transforms/Instrumentation/SanitizerCoverage.cpp
  llvm/test/Instrumentation/SanitizerCoverage/stack-depth.ll

Index: llvm/test/Instrumentation/SanitizerCoverage/stack-depth.ll
===
--- llvm/test/Instrumentation/SanitizerCoverage/stack-depth.ll
+++ llvm/test/Instrumentation/SanitizerCoverage/stack-depth.ll
@@ -1,9 +1,9 @@
 ; This check verifies that stack depth instrumentation works correctly.
 ; RUN: opt < %s -sancov -sanitizer-coverage-level=1 \
-; RUN: -sanitizer-coverage-stack-depth -S | FileCheck %s --enable-var-scope
+; RUN: -sanitizer-coverage-stack-depth -S | FileCheck %s
 ; RUN: opt < %s -sancov -sanitizer-coverage-level=3 \
 ; RUN: -sanitizer-coverage-stack-depth -sanitizer-coverage-trace-pc-guard \
-; RUN: -S | FileCheck %s --enable-var-scope
+; RUN: -S | FileCheck %s
 
 target datalayout = "e-m:e-i64:64-f80:128-n8:16:32:64-S128"
 target triple = "x86_64-unknown-linux-gnu"
@@ -14,13 +14,8 @@
 define i32 @foo() {
 entry:
 ; CHECK-LABEL: define i32 @foo
-; CHECK: [[framePtr:%[^ \t]+]] = call i8* @llvm.frameaddress(i32 0)
-; CHECK: [[frameInt:%[^ \t]+]] = ptrtoint i8* [[framePtr]] to [[$intType:i[0-9]+]]
-; CHECK: [[lowest:%[^ \t]+]] = load [[$intType]], [[$intType]]* @__sancov_lowest_stack
-; CHECK: [[cmp:%[^ \t]+]] = icmp ult [[$intType]] [[frameInt]], [[lowest]]
-; CHECK: br i1 [[cmp]], label %[[ifLabel:[^ \t]+]], label
-; CHECK: :[[ifLabel]]:
-; CHECK: store [[$intType]] [[frameInt]], [[$intType]]* @__sancov_lowest_stack
+; CHECK-NOT: call i8* @llvm.frameaddress(i32 0)
+; CHECK-NOT: @__sancov_lowest_stack
 ; CHECK: ret i32 7
 
   ret i32 7
@@ -30,12 +25,12 @@
 entry:
 ; CHECK-LABEL: define i32 @bar
 ; CHECK: [[framePtr:%[^ \t]+]] = call i8* @llvm.frameaddress(i32 0)
-; CHECK: [[frameInt:%[^ \t]+]] = ptrtoint i8* [[framePtr]] to [[$intType]]
-; CHECK: [[lowest:%[^ \t]+]] = load [[$intType]], [[$intType]]* @__sancov_lowest_stack
-; CHECK: [[cmp:%[^ \t]+]] = icmp ult [[$intType]] [[frameInt]], [[lowest]]
+; CHECK: [[frameInt:%[^ \t]+]] = ptrtoint i8* [[framePtr]] to [[intType:i[0-9]+]]
+; CHECK: [[lowest:%[^ \t]+]] = load [[intType]], [[intType]]* @__sancov_lowest_stack
+; CHECK: [[cmp:%[^ \t]+]] = icmp ult [[intType]] [[frameInt]], [[lowest]]
 ; CHECK: br i1 [[cmp]], label %[[ifLabel:[^ \t]+]], label
 ; CHECK: :[[ifLabel]]:
-; CHECK: store [[$intType]] [[frameInt]], [[$intType]]* @__sancov_lowest_stack
+; CHECK: store [[intType]] [[frameInt]], [[intType]]* @__sancov_lowest_stack
 ; CHECK: %call = call i32 @foo()
 ; CHECK: ret i32 %call
 
Index: llvm/lib/Transforms/Instrumentation/SanitizerCoverage.cpp
===
--- llvm/lib/Transforms/Instrumentation/SanitizerCoverage.cpp
+++ llvm/lib/Transforms/Instrumentation/SanitizerCoverage.cpp
@@ -25,6 +25,7 @@
 #include "llvm/IR/GlobalVariable.h"
 #include "llvm/IR/IRBuilder.h"
 #include "llvm/IR/InlineAsm.h"
+#include "llvm/IR/IntrinsicInst.h"
 #include "llvm/IR/Intrinsics.h"
 #include "llvm/IR/LLVMContext.h"
 #include "llvm/IR/MDBuilder.h"
@@ -200,13 +201,15 @@
  ArrayRef GepTraceTargets);
   void InjectTraceForSwitch(Function ,
 ArrayRef SwitchTraceTargets);
-  bool InjectCoverage(Function , ArrayRef AllBlocks);
+  bool InjectCoverage(Function , ArrayRef AllBlocks,
+  bool IsLeafFunc = true);
   GlobalVariable *CreateFunctionLocalArrayInSection(size_t NumElements,
 Function , Type *Ty,
 const char *Section);
   GlobalVariable *CreatePCArray(Function , ArrayRef AllBlocks);
   void CreateFunctionLocalArrays(Function , ArrayRef AllBlocks);
-  void InjectCoverageAtBlock(Function , BasicBlock , size_t Idx);
+  void InjectCoverageAtBlock(Function , BasicBlock , size_t Idx,
+ bool IsLeafFunc = true);
   Function *CreateInitCallsForSections(Module , const char *InitFunctionName,
Type *Ty, const char *Section);
   std::pair
@@ -491,6 +494,7 @@
   (F).getDomTree();
   const PostDominatorTree *PDT =
   (F).getPostDomTree();
+  bool IsLeafFunc = true;
 
   for (auto  : F) {
 if (shouldInstrumentBlock(F, , DT, PDT, Options))
@@ -515,10 +519,14 @@
   if (Options.TraceGep)
 if (GetElementPtrInst *GEP = dyn_cast())
   GepTraceTargets.push_back(GEP);
-   }
+  if (Options.StackDepth)
+if (isa(Inst) ||
+(isa(Inst) && !isa(Inst)))
+  IsLeafFunc = false;
+

[PATCH] D26764: [compiler-rt] [cmake] Remove i686 target that is duplicate to i386

2017-08-29 Thread Hans Wennborg via Phabricator via cfe-commits
hans added inline comments.



Comment at: compiler-rt/trunk/lib/asan/scripts/asan_device_setup:98
 if [[ $_ABI == x86* ]]; then
-_ARCH=i686
+_ARCH=i386
 elif [[ $_ABI == armeabi* ]]; then

There are lots of copies of this script in various project that now all need to 
be updated (searching the web for asan_device_setup shows some).

For me personally, this means updating Chromium (also the build system needs an 
update) to handle different names before and after this revision.

Do you have any suggestions for how we should handle this rename? Is there some 
backwards-compatibility fix we could do?

As you noticed this broke some LLVM buildbots. It also broke Chromium 
buildbots, and I suppose other projects which use asan. I'm wondering if the 
fallout is worth the benefits here.


Repository:
  rL LLVM

https://reviews.llvm.org/D26764



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


[PATCH] D37038: Replace temp MD nodes with unique/distinct before cloning

2017-08-29 Thread Paul Robinson via Phabricator via cfe-commits
probinson added a comment.

In https://reviews.llvm.org/D37038#89, @aprantl wrote:

> This may have gotten lost earlier:  Would it be possible to instruct 
> CloneFunction to not clone any temporary MDNodes via one of the flags that 
> are passed to the ValueMapper?


I did look at that, sorry for not reporting back.  ValueMapper seems to be 
quite adamant about having non-temporary nodes.  I can try pursuing that 
further but it would be quite the "learning experience" I think.
Alternatively we could try deferring the thunk cloning until after all other 
codegen, but that also seems like a pretty hacky approach.


https://reviews.llvm.org/D37038



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


[PATCH] D37249: [Bash-autocomplete] Refactor autocomplete code into own function

2017-08-29 Thread Yuka Takahashi via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rL312018: [Bash-autocomplete] Refactor autocomplete code into 
own function (authored by yamaguchi).

Changed prior to commit:
  https://reviews.llvm.org/D37249?vs=113027=113118#toc

Repository:
  rL LLVM

https://reviews.llvm.org/D37249

Files:
  cfe/trunk/include/clang/Driver/Driver.h
  cfe/trunk/lib/Driver/Driver.cpp

Index: cfe/trunk/lib/Driver/Driver.cpp
===
--- cfe/trunk/lib/Driver/Driver.cpp
+++ cfe/trunk/lib/Driver/Driver.cpp
@@ -1156,6 +1156,56 @@
 OS << i << ',' << DiagnosticIDs::getCategoryNameFromID(i) << '\n';
 }
 
+void Driver::handleAutocompletions(StringRef PassedFlags) const {
+  // Print out all options that start with a given argument. This is used for
+  // shell autocompletion.
+  std::vector SuggestedCompletions;
+
+  unsigned short DisableFlags =
+  options::NoDriverOption | options::Unsupported | options::Ignored;
+  // We want to show cc1-only options only when clang is invoked as "clang
+  // -cc1".
+  // When clang is invoked as "clang -cc1", we add "#" to the beginning of an
+  // --autocomplete
+  // option so that the clang driver can distinguish whether it is requested to
+  // show cc1-only options or not.
+  if (PassedFlags[0] == '#') {
+DisableFlags &= ~options::NoDriverOption;
+PassedFlags = PassedFlags.substr(1);
+  }
+
+  if (PassedFlags.find(',') == StringRef::npos) {
+// If the flag is in the form of "--autocomplete=-foo",
+// we were requested to print out all option names that start with "-foo".
+// For example, "--autocomplete=-fsyn" is expanded to "-fsyntax-only".
+SuggestedCompletions = Opts->findByPrefix(PassedFlags, DisableFlags);
+
+// We have to query the -W flags manually as they're not in the OptTable.
+// TODO: Find a good way to add them to OptTable instead and them remove
+// this code.
+for (StringRef S : DiagnosticIDs::getDiagnosticFlags())
+  if (S.startswith(PassedFlags))
+SuggestedCompletions.push_back(S);
+  } else {
+// If the flag is in the form of "--autocomplete=foo,bar", we were
+// requested to print out all option values for "-foo" that start with
+// "bar". For example,
+// "--autocomplete=-stdlib=,l" is expanded to "libc++" and "libstdc++".
+StringRef Option, Arg;
+std::tie(Option, Arg) = PassedFlags.split(',');
+SuggestedCompletions = Opts->suggestValueCompletions(Option, Arg);
+  }
+
+  // Sort the autocomplete candidates so that shells print them out in a
+  // deterministic order. We could sort in any way, but we chose
+  // case-insensitive sorting for consistency with the -help option
+  // which prints out options in the case-insensitive alphabetical order.
+  std::sort(SuggestedCompletions.begin(), SuggestedCompletions.end(),
+[](StringRef A, StringRef B) { return A.compare_lower(B) < 0; });
+
+  llvm::outs() << llvm::join(SuggestedCompletions, "\n") << '\n';
+}
+
 bool Driver::HandleImmediateArgs(const Compilation ) {
   // The order these options are handled in gcc is all over the place, but we
   // don't expect inconsistencies w.r.t. that to matter in practice.
@@ -1249,50 +1299,8 @@
   }
 
   if (Arg *A = C.getArgs().getLastArg(options::OPT_autocomplete)) {
-// Print out all options that start with a given argument. This is used for
-// shell autocompletion.
 StringRef PassedFlags = A->getValue();
-std::vector SuggestedCompletions;
-
-unsigned short DisableFlags = options::NoDriverOption | options::Unsupported | options::Ignored;
-// We want to show cc1-only options only when clang is invoked as "clang -cc1".
-// When clang is invoked as "clang -cc1", we add "#" to the beginning of an --autocomplete
-// option so that the clang driver can distinguish whether it is requested to show cc1-only options or not.
-if (PassedFlags[0] == '#') {
-  DisableFlags &= ~options::NoDriverOption;
-  PassedFlags = PassedFlags.substr(1);
-}
-
-if (PassedFlags.find(',') == StringRef::npos) {
-  // If the flag is in the form of "--autocomplete=-foo",
-  // we were requested to print out all option names that start with "-foo".
-  // For example, "--autocomplete=-fsyn" is expanded to "-fsyntax-only".
-  SuggestedCompletions = Opts->findByPrefix(PassedFlags, DisableFlags);
-
-  // We have to query the -W flags manually as they're not in the OptTable.
-  // TODO: Find a good way to add them to OptTable instead and them remove
-  // this code.
-  for (StringRef S : DiagnosticIDs::getDiagnosticFlags())
-if (S.startswith(PassedFlags))
-  SuggestedCompletions.push_back(S);
-} else {
-  // If the flag is in the form of "--autocomplete=foo,bar", we were
-  // requested to print out all option values for "-foo" that start with
-  // "bar". For example,
-  // "--autocomplete=-stdlib=,l" is 

r312018 - [Bash-autocomplete] Refactor autocomplete code into own function

2017-08-29 Thread Yuka Takahashi via cfe-commits
Author: yamaguchi
Date: Tue Aug 29 10:46:46 2017
New Revision: 312018

URL: http://llvm.org/viewvc/llvm-project?rev=312018=rev
Log:
[Bash-autocomplete] Refactor autocomplete code into own function

Summary:
We wrote many codes in HandleImediateArgs, so I've refactored it into
handleAutocompletions.

Reviewers: v.g.vassilev, teemperor

Subscribers: cfe-commits

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

Modified:
cfe/trunk/include/clang/Driver/Driver.h
cfe/trunk/lib/Driver/Driver.cpp

Modified: cfe/trunk/include/clang/Driver/Driver.h
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Driver/Driver.h?rev=312018=312017=312018=diff
==
--- cfe/trunk/include/clang/Driver/Driver.h (original)
+++ cfe/trunk/include/clang/Driver/Driver.h Tue Aug 29 10:46:46 2017
@@ -425,6 +425,10 @@ public:
   // FIXME: This should be in CompilationInfo.
   std::string GetProgramPath(StringRef Name, const ToolChain ) const;
 
+  /// handleAutocompletions - Handle --autocomplete by searching and printing
+  /// possible flags, descriptions, and its arguments.
+  void handleAutocompletions(StringRef PassedFlags) const;
+
   /// HandleImmediateArgs - Handle any arguments which should be
   /// treated before building actions or binding tools.
   ///

Modified: cfe/trunk/lib/Driver/Driver.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Driver/Driver.cpp?rev=312018=312017=312018=diff
==
--- cfe/trunk/lib/Driver/Driver.cpp (original)
+++ cfe/trunk/lib/Driver/Driver.cpp Tue Aug 29 10:46:46 2017
@@ -1156,6 +1156,56 @@ static void PrintDiagnosticCategories(ra
 OS << i << ',' << DiagnosticIDs::getCategoryNameFromID(i) << '\n';
 }
 
+void Driver::handleAutocompletions(StringRef PassedFlags) const {
+  // Print out all options that start with a given argument. This is used for
+  // shell autocompletion.
+  std::vector SuggestedCompletions;
+
+  unsigned short DisableFlags =
+  options::NoDriverOption | options::Unsupported | options::Ignored;
+  // We want to show cc1-only options only when clang is invoked as "clang
+  // -cc1".
+  // When clang is invoked as "clang -cc1", we add "#" to the beginning of an
+  // --autocomplete
+  // option so that the clang driver can distinguish whether it is requested to
+  // show cc1-only options or not.
+  if (PassedFlags[0] == '#') {
+DisableFlags &= ~options::NoDriverOption;
+PassedFlags = PassedFlags.substr(1);
+  }
+
+  if (PassedFlags.find(',') == StringRef::npos) {
+// If the flag is in the form of "--autocomplete=-foo",
+// we were requested to print out all option names that start with "-foo".
+// For example, "--autocomplete=-fsyn" is expanded to "-fsyntax-only".
+SuggestedCompletions = Opts->findByPrefix(PassedFlags, DisableFlags);
+
+// We have to query the -W flags manually as they're not in the OptTable.
+// TODO: Find a good way to add them to OptTable instead and them remove
+// this code.
+for (StringRef S : DiagnosticIDs::getDiagnosticFlags())
+  if (S.startswith(PassedFlags))
+SuggestedCompletions.push_back(S);
+  } else {
+// If the flag is in the form of "--autocomplete=foo,bar", we were
+// requested to print out all option values for "-foo" that start with
+// "bar". For example,
+// "--autocomplete=-stdlib=,l" is expanded to "libc++" and "libstdc++".
+StringRef Option, Arg;
+std::tie(Option, Arg) = PassedFlags.split(',');
+SuggestedCompletions = Opts->suggestValueCompletions(Option, Arg);
+  }
+
+  // Sort the autocomplete candidates so that shells print them out in a
+  // deterministic order. We could sort in any way, but we chose
+  // case-insensitive sorting for consistency with the -help option
+  // which prints out options in the case-insensitive alphabetical order.
+  std::sort(SuggestedCompletions.begin(), SuggestedCompletions.end(),
+[](StringRef A, StringRef B) { return A.compare_lower(B) < 0; });
+
+  llvm::outs() << llvm::join(SuggestedCompletions, "\n") << '\n';
+}
+
 bool Driver::HandleImmediateArgs(const Compilation ) {
   // The order these options are handled in gcc is all over the place, but we
   // don't expect inconsistencies w.r.t. that to matter in practice.
@@ -1249,50 +1299,8 @@ bool Driver::HandleImmediateArgs(const C
   }
 
   if (Arg *A = C.getArgs().getLastArg(options::OPT_autocomplete)) {
-// Print out all options that start with a given argument. This is used for
-// shell autocompletion.
 StringRef PassedFlags = A->getValue();
-std::vector SuggestedCompletions;
-
-unsigned short DisableFlags = options::NoDriverOption | 
options::Unsupported | options::Ignored;
-// We want to show cc1-only options only when clang is invoked as "clang 
-cc1".
-// When clang is invoked as "clang -cc1", we add "#" to the beginning of 
an 

r312017 - [ms] Fix vbtable index for covariant overrides of vbase methods

2017-08-29 Thread Reid Kleckner via cfe-commits
Author: rnk
Date: Tue Aug 29 10:40:04 2017
New Revision: 312017

URL: http://llvm.org/viewvc/llvm-project?rev=312017=rev
Log:
[ms] Fix vbtable index for covariant overrides of vbase methods

Overriding a method from a virtual base with a covariant return type
consumes a slot from the vftable in the virtual base. This can make it
impossible to implement certain diamond inheritance hierarchies, but we
have to follow along for compatibility in the simple cases.

This patch only affects our vtable dumper and member pointer function
mangling, since all other callers of getMethodVFTableLocation seem to
recompute VBTableIndex instead of using the one in the method location.

Patch by David Majnemer

Modified:
cfe/trunk/lib/AST/VTableBuilder.cpp
cfe/trunk/test/CodeGenCXX/microsoft-abi-vtables-return-thunks.cpp

Modified: cfe/trunk/lib/AST/VTableBuilder.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/AST/VTableBuilder.cpp?rev=312017=312016=312017=diff
==
--- cfe/trunk/lib/AST/VTableBuilder.cpp (original)
+++ cfe/trunk/lib/AST/VTableBuilder.cpp Tue Aug 29 10:40:04 2017
@@ -2963,6 +2963,9 @@ void VFTableBuilder::AddMethods(BaseSubo
   CalculateVtordispAdjustment(FinalOverrider, ThisOffset,
   ThisAdjustmentOffset);
 
+unsigned VBIndex =
+LastVBase ? VTables.getVBTableIndex(MostDerivedClass, LastVBase) : 0;
+
 if (OverriddenMD) {
   // If MD overrides anything in this vftable, we need to update the
   // entries.
@@ -2975,6 +2978,8 @@ void VFTableBuilder::AddMethods(BaseSubo
 
   MethodInfo  = OverriddenMDIterator->second;
 
+  VBIndex = OverriddenMethodInfo.VBTableIndex;
+
   // Let's check if the overrider requires any return adjustments.
   // We must create a new slot if the MD's return type is not trivially
   // convertible to the OverriddenMD's one.
@@ -2987,8 +2992,7 @@ void VFTableBuilder::AddMethods(BaseSubo
   if (!ReturnAdjustingThunk) {
 // No return adjustment needed - just replace the overridden method 
info
 // with the current info.
-MethodInfo MI(OverriddenMethodInfo.VBTableIndex,
-  OverriddenMethodInfo.VFTableIndex);
+MethodInfo MI(VBIndex, OverriddenMethodInfo.VFTableIndex);
 MethodInfoMap.erase(OverriddenMDIterator);
 
 assert(!MethodInfoMap.count(MD) &&
@@ -3015,8 +3019,6 @@ void VFTableBuilder::AddMethods(BaseSubo
 
 // If we got here, MD is a method not seen in any of the sub-bases or
 // it requires return adjustment. Insert the method info for this method.
-unsigned VBIndex =
-LastVBase ? VTables.getVBTableIndex(MostDerivedClass, LastVBase) : 0;
 MethodInfo MI(VBIndex,
   HasRTTIComponent ? Components.size() - 1 : Components.size(),
   ReturnAdjustingThunk);

Modified: cfe/trunk/test/CodeGenCXX/microsoft-abi-vtables-return-thunks.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/CodeGenCXX/microsoft-abi-vtables-return-thunks.cpp?rev=312017=312016=312017=diff
==
--- cfe/trunk/test/CodeGenCXX/microsoft-abi-vtables-return-thunks.cpp (original)
+++ cfe/trunk/test/CodeGenCXX/microsoft-abi-vtables-return-thunks.cpp Tue Aug 
29 10:40:04 2017
@@ -201,3 +201,18 @@ D::D() {}
 // GLOBALS: @"\01?fn@D@test3@@$4PPPM@A@AEPAUB@2@XZ"
 // GLOBALS: @"\01?fn@D@test3@@$4PPPM@A@AEPAU12@XZ"
 }
+
+namespace pr34302 {
+// C::f is lives in the vftable inside its virtual B subobject. In the MS ABI,
+// covariant return type virtual methods extend vftables from virtual bases,
+// even though that can make it impossible to implement certain diamond
+// hierarchies correctly.
+struct A { virtual ~A(); };
+struct B : A { virtual B *f(); };
+struct C : virtual B { C *f(); };
+C c;
+// VFTABLES-LABEL: VFTable indices for 'pr34302::C' (2 entries).
+// VFTABLES-NEXT:  -- accessible via vbtable index 1, vfptr at offset 0 --
+// VFTABLES-NEXT:0 | pr34302::C::~C() [scalar deleting]
+// VFTABLES-NEXT:2 | pr34302::C *pr34302::C::f()
+}


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


Re: r311823 - Add flag to request Clang is ABI-compatible with older versions of itself

2017-08-29 Thread Hans Wennborg via cfe-commits
Merged in r312013.

On Fri, Aug 25, 2017 at 6:06 PM, Richard Smith  wrote:
> Hi Hans,
>
> We should get this into Clang 5 so that people can opt out of the ABI bugfix
> for passing C++ class types by value.
>
> On 25 August 2017 at 18:04, Richard Smith via cfe-commits
>  wrote:
>>
>> Author: rsmith
>> Date: Fri Aug 25 18:04:35 2017
>> New Revision: 311823
>>
>> URL: http://llvm.org/viewvc/llvm-project?rev=311823=rev
>> Log:
>> Add flag to request Clang is ABI-compatible with older versions of itself
>>
>> This patch adds a flag -fclang-abi-compat that can be used to request that
>> Clang attempts to be ABI-compatible with some older version of itself.
>>
>> This is provided on a best-effort basis; right now, this can be used to
>> undo
>> the ABI change in r310401, reverting Clang to its prior C++ ABI for
>> pass/return
>> by value of class types affected by that change, and to undo the ABI
>> change in
>> r262688, reverting Clang to using integer registers rather than SSE
>> registers
>> for passing <1 x long long> vectors. The intent is that we will maintain
>> this
>> backwards compatibility path as we make ABI-breaking fixes in future.
>>
>> The reversion to the old behavior for r310401 is also applied to the PS4
>> target
>> since that change is not part of its platform ABI (which is essentially to
>> do
>> whatever Clang 3.2 did).
>>
>> Added:
>> cfe/trunk/test/CodeGenCXX/clang-abi-compat.cpp
>> cfe/trunk/test/Frontend/clang-abi-compat.cpp
>> Modified:
>> cfe/trunk/include/clang/Driver/Options.td
>> cfe/trunk/include/clang/Frontend/CodeGenOptions.def
>> cfe/trunk/include/clang/Frontend/CodeGenOptions.h
>> cfe/trunk/lib/CodeGen/ABIInfo.h
>> cfe/trunk/lib/CodeGen/CodeGenTypes.cpp
>> cfe/trunk/lib/CodeGen/CodeGenTypes.h
>> cfe/trunk/lib/CodeGen/ItaniumCXXABI.cpp
>> cfe/trunk/lib/CodeGen/TargetInfo.cpp
>> cfe/trunk/lib/Driver/ToolChains/Clang.cpp
>> cfe/trunk/lib/Frontend/CompilerInvocation.cpp
>> cfe/trunk/test/CodeGenCXX/uncopyable-args.cpp
>> cfe/trunk/test/Driver/flags.c
>>
>> Modified: cfe/trunk/include/clang/Driver/Options.td
>> URL:
>> http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Driver/Options.td?rev=311823=311822=311823=diff
>>
>> ==
>> --- cfe/trunk/include/clang/Driver/Options.td (original)
>> +++ cfe/trunk/include/clang/Driver/Options.td Fri Aug 25 18:04:35 2017
>> @@ -711,6 +711,9 @@ def fbuiltin : Flag<["-"], "fbuiltin">,
>>  def fbuiltin_module_map : Flag <["-"], "fbuiltin-module-map">,
>> Group,
>>Flags<[DriverOption]>, HelpText<"Load the clang builtins module map
>> file.">;
>>  def fcaret_diagnostics : Flag<["-"], "fcaret-diagnostics">,
>> Group;
>> +def fclang_abi_compat_EQ : Joined<["-"], "fclang-abi-compat=">,
>> Group,
>> +  Flags<[CC1Option]>, MetaVarName<"">,
>> Values<".,latest">,
>> +  HelpText<"Attempt to match the ABI of Clang ">;
>>  def fclasspath_EQ : Joined<["-"], "fclasspath=">, Group;
>>  def fcolor_diagnostics : Flag<["-"], "fcolor-diagnostics">,
>> Group,
>>Flags<[CoreOption, CC1Option]>, HelpText<"Use colors in diagnostics">;
>>
>> Modified: cfe/trunk/include/clang/Frontend/CodeGenOptions.def
>> URL:
>> http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Frontend/CodeGenOptions.def?rev=311823=311822=311823=diff
>>
>> ==
>> --- cfe/trunk/include/clang/Frontend/CodeGenOptions.def (original)
>> +++ cfe/trunk/include/clang/Frontend/CodeGenOptions.def Fri Aug 25
>> 18:04:35 2017
>> @@ -120,6 +120,10 @@ CODEGENOPT(NoZeroInitializedInBSS , 1, 0
>>  ENUM_CODEGENOPT(ObjCDispatchMethod, ObjCDispatchMethodKind, 2, Legacy)
>>  CODEGENOPT(OmitLeafFramePointer , 1, 0) ///< Set when
>> -momit-leaf-frame-pointer is
>>  ///< enabled.
>> +
>> +/// A version of Clang that we should attempt to be ABI-compatible with.
>> +ENUM_CODEGENOPT(ClangABICompat, ClangABI, 4, ClangABI::Latest)
>> +
>>  VALUE_CODEGENOPT(OptimizationLevel, 2, 0) ///< The -O[0-3] option
>> specified.
>>  VALUE_CODEGENOPT(OptimizeSize, 2, 0) ///< If -Os (==1) or -Oz (==2) is
>> specified.
>>
>>
>> Modified: cfe/trunk/include/clang/Frontend/CodeGenOptions.h
>> URL:
>> http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Frontend/CodeGenOptions.h?rev=311823=311822=311823=diff
>>
>> ==
>> --- cfe/trunk/include/clang/Frontend/CodeGenOptions.h (original)
>> +++ cfe/trunk/include/clang/Frontend/CodeGenOptions.h Fri Aug 25 18:04:35
>> 2017
>> @@ -69,6 +69,23 @@ public:
>>  LocalExecTLSModel
>>};
>>
>> +  /// Clang versions with different platform ABI conformance.
>> +  enum class ClangABI {
>> +/// Attempt to be ABI-compatible with code generated by Clang 3.8.x
>> +/// (SVN r257626). This causes <1 x 

[PATCH] D37038: Replace temp MD nodes with unique/distinct before cloning

2017-08-29 Thread Adrian Prantl via Phabricator via cfe-commits
aprantl added a comment.

This may have gotten lost earlier:  Would it be possible to instruct 
CloneFunction to not clone any temporary MDNodes via one of the flags that are 
passed to the ValueMapper?


https://reviews.llvm.org/D37038



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


[PATCH] D36750: [analyzer] RetainCount: When diagnosing overrelease, mention if it's coming from a nested block.

2017-08-29 Thread Artem Dergachev via Phabricator via cfe-commits
NoQ updated this revision to Diff 113102.
NoQ marked an inline comment as done.
NoQ added a comment.

Avoid creating a new `RefVal` kind.

In https://reviews.llvm.org/D36750#843427, @dcoughlin wrote:

> > By the way, plist-based tests in retain-release.m are disabled since 
> > r163536 (~2012), and need to be updated. It's trivial to re-enable them but 
> > annoying to maintain - would we prefer to re-enable or delete them or 
> > replace with -analyzer-output=text tests?
>
> My preference would be to factor out/re-target some specific tests into their 
> own file and check that with -verify + -analyzer-output=text and with plist 
> comparisons


Hmm, which specific tests do you have in mind? And is it worth it to try to 
recover the intended arrows in plists from the old plist tests?


https://reviews.llvm.org/D36750

Files:
  lib/StaticAnalyzer/Checkers/RetainCountChecker.cpp
  test/Analysis/retain-release.m


Index: test/Analysis/retain-release.m
===
--- test/Analysis/retain-release.m
+++ test/Analysis/retain-release.m
@@ -2300,6 +2300,23 @@
   CFRelease(obj);
 }
 
+//===--===//
+// When warning within blocks make it obvious that warnings refer to blocks.
+//===--===//
+
+int useBlock(int (^block)());
+void rdar31699502_hardToNoticeBlocks() {
+  if (useBlock(^{
+NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
+NSArray *array = [NSArray array];
+[array release]; // expected-warning{{Incorrect decrement of the reference 
count of an object that is not owned at this point by the current block}}
+[pool drain];
+return 0;
+  })) {
+return;
+  }
+}
+
 // CHECK:  diagnostics
 // CHECK-NEXT:  
 // CHECK-NEXT:   
Index: lib/StaticAnalyzer/Checkers/RetainCountChecker.cpp
===
--- lib/StaticAnalyzer/Checkers/RetainCountChecker.cpp
+++ lib/StaticAnalyzer/Checkers/RetainCountChecker.cpp
@@ -1722,6 +1722,17 @@
 }
   };
 
+  class BadReleaseByBlock : public CFRefBug {
+  public:
+BadReleaseByBlock(const CheckerBase *checker)
+: CFRefBug(checker, "Bad release") {}
+
+const char *getDescription() const override {
+  return "Incorrect decrement of the reference count of an object that is "
+ "not owned at this point by the current block";
+}
+  };
+
   class DeallocGC : public CFRefBug {
   public:
 DeallocGC(const CheckerBase *checker)
@@ -2560,7 +2571,8 @@
 check::RegionChanges,
 eval::Assume,
 eval::Call > {
-  mutable std::unique_ptr useAfterRelease, releaseNotOwned;
+  mutable std::unique_ptr useAfterRelease;
+  mutable std::unique_ptr releaseNotOwned, releaseNotOwnedByBlock;
   mutable std::unique_ptr deallocGC, deallocNotOwned;
   mutable std::unique_ptr overAutorelease, returnNotOwnedForOwned;
   mutable std::unique_ptr leakWithinFunction, leakAtReturn;
@@ -3396,9 +3408,15 @@
   BT = useAfterRelease.get();
   break;
 case RefVal::ErrorReleaseNotOwned:
-  if (!releaseNotOwned)
-releaseNotOwned.reset(new BadRelease(this));
-  BT = releaseNotOwned.get();
+  if (isa(C.getLocationContext()->getDecl())) {
+if (!releaseNotOwnedByBlock)
+  releaseNotOwnedByBlock.reset(new BadReleaseByBlock(this));
+BT = releaseNotOwnedByBlock.get();
+  } else {
+if (!releaseNotOwned)
+  releaseNotOwned.reset(new BadRelease(this));
+BT = releaseNotOwned.get();
+  }
   break;
 case RefVal::ErrorDeallocGC:
   if (!deallocGC)


Index: test/Analysis/retain-release.m
===
--- test/Analysis/retain-release.m
+++ test/Analysis/retain-release.m
@@ -2300,6 +2300,23 @@
   CFRelease(obj);
 }
 
+//===--===//
+// When warning within blocks make it obvious that warnings refer to blocks.
+//===--===//
+
+int useBlock(int (^block)());
+void rdar31699502_hardToNoticeBlocks() {
+  if (useBlock(^{
+NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
+NSArray *array = [NSArray array];
+[array release]; // expected-warning{{Incorrect decrement of the reference count of an object that is not owned at this point by the current block}}
+[pool drain];
+return 0;
+  })) {
+return;
+  }
+}
+
 // CHECK:  diagnostics
 // CHECK-NEXT:  
 // CHECK-NEXT:   
Index: lib/StaticAnalyzer/Checkers/RetainCountChecker.cpp
===
--- lib/StaticAnalyzer/Checkers/RetainCountChecker.cpp
+++ lib/StaticAnalyzer/Checkers/RetainCountChecker.cpp
@@ -1722,6 +1722,17 @@
 }
   };
 
+  class 

[PATCH] D33719: Add _Float16 as a C/C++ source language type

2017-08-29 Thread Roger Ferrer Ibanez via Phabricator via cfe-commits
rogfer01 accepted this revision.
rogfer01 added a comment.
This revision is now accepted and ready to land.

Thanks @SjoerdMeijer

This LGTM now. Wait a couple of days in case @rsmith has more comments.


https://reviews.llvm.org/D33719



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


[PATCH] D37001: [clang-diff] Use data collectors for node comparison

2017-08-29 Thread Alex Lorenz via Phabricator via cfe-commits
arphaman added inline comments.



Comment at: lib/Tooling/ASTDiff/ASTDiff.cpp:537
+
+#include "../../AST/DeclDataCollectors.inc"
+

I didn't realize that you're including files from within `lib`. That's not 
ideal. You should add a pre-commit that moves the *.inc files over to 
include/AST (and marks them as textual in Clang's `module.modulemap`). Then you 
should include them using the clang/AST path.


https://reviews.llvm.org/D37001



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


[PATCH] D33719: Add _Float16 as a C/C++ source language type

2017-08-29 Thread Sjoerd Meijer via Phabricator via cfe-commits
SjoerdMeijer updated this revision to Diff 113100.
SjoerdMeijer added a comment.

No changes were needed to make the conversions work, the existing logic is 
taking care of that, but I agree it doesn't hurt to add a few test cases. So 
I've added tests to both files, and cleaned up that comment.


https://reviews.llvm.org/D33719

Files:
  include/clang-c/Index.h
  include/clang/AST/ASTContext.h
  include/clang/AST/BuiltinTypes.def
  include/clang/Basic/Specifiers.h
  include/clang/Basic/TokenKinds.def
  include/clang/Lex/LiteralSupport.h
  include/clang/Sema/DeclSpec.h
  include/clang/Serialization/ASTBitCodes.h
  lib/AST/ASTContext.cpp
  lib/AST/ItaniumMangle.cpp
  lib/AST/MicrosoftMangle.cpp
  lib/AST/NSAPI.cpp
  lib/AST/StmtPrinter.cpp
  lib/AST/Type.cpp
  lib/AST/TypeLoc.cpp
  lib/Analysis/PrintfFormatString.cpp
  lib/CodeGen/CGDebugInfo.cpp
  lib/CodeGen/CGExprScalar.cpp
  lib/CodeGen/CodeGenTypes.cpp
  lib/CodeGen/ItaniumCXXABI.cpp
  lib/Format/FormatToken.cpp
  lib/Index/USRGeneration.cpp
  lib/Lex/LiteralSupport.cpp
  lib/Parse/ParseDecl.cpp
  lib/Parse/ParseExpr.cpp
  lib/Parse/ParseExprCXX.cpp
  lib/Parse/ParseTentative.cpp
  lib/Sema/DeclSpec.cpp
  lib/Sema/SemaDecl.cpp
  lib/Sema/SemaExpr.cpp
  lib/Sema/SemaTemplateVariadic.cpp
  lib/Sema/SemaType.cpp
  lib/Serialization/ASTCommon.cpp
  lib/Serialization/ASTReader.cpp
  test/CodeGenCXX/float16-declarations.cpp
  test/Frontend/float16.cpp
  test/Lexer/half-literal.cpp
  tools/libclang/CXType.cpp

Index: tools/libclang/CXType.cpp
===
--- tools/libclang/CXType.cpp
+++ tools/libclang/CXType.cpp
@@ -53,6 +53,7 @@
 BTCASE(Float);
 BTCASE(Double);
 BTCASE(LongDouble);
+BTCASE(Float16);
 BTCASE(Float128);
 BTCASE(NullPtr);
 BTCASE(Overload);
@@ -520,7 +521,7 @@
 TKIND(Char_U);
 TKIND(UChar);
 TKIND(Char16);
-TKIND(Char32);  
+TKIND(Char32);
 TKIND(UShort);
 TKIND(UInt);
 TKIND(ULong);
@@ -538,6 +539,7 @@
 TKIND(Float);
 TKIND(Double);
 TKIND(LongDouble);
+TKIND(Float16);
 TKIND(Float128);
 TKIND(NullPtr);
 TKIND(Overload);
Index: test/Lexer/half-literal.cpp
===
--- test/Lexer/half-literal.cpp
+++ test/Lexer/half-literal.cpp
@@ -1,3 +1,6 @@
 // RUN: %clang_cc1 -fsyntax-only -verify -pedantic %s
 float a = 1.0h; // expected-error{{invalid suffix 'h' on floating constant}}
 float b = 1.0H; // expected-error{{invalid suffix 'H' on floating constant}}
+
+_Float16 c = 1.f166; // expected-error{{invalid suffix 'f166' on floating constant}}
+_Float16 d = 1.f1;   // expected-error{{invalid suffix 'f1' on floating constant}}
Index: test/Frontend/float16.cpp
===
--- /dev/null
+++ test/Frontend/float16.cpp
@@ -0,0 +1,326 @@
+// RUN: %clang_cc1 -std=c++11 -ast-dump %s | FileCheck %s
+// RUN: %clang_cc1 -std=c++11 -ast-dump -fnative-half-type %s | FileCheck %s --check-prefix=CHECK-NATIVE
+
+/*  Various contexts where type _Float16 can appear. */
+
+/*  Namespace */
+namespace {
+  _Float16 f1n;
+  _Float16 f2n = 33.f16;
+  _Float16 arr1n[10];
+  _Float16 arr2n[] = { 1.2, 3.0, 3.e4 };
+  const volatile _Float16 func1n(const _Float16 ) {
+return arg + f2n + arr1n[4] - arr2n[1];
+  }
+}
+
+//CHECK: |-NamespaceDecl
+//CHECK: | |-VarDecl {{.*}} f1n '_Float16'
+//CHECK: | |-VarDecl {{.*}} f2n '_Float16' cinit
+//CHECK: | | `-FloatingLiteral {{.*}} '_Float16' 3.30e+01
+//CHECK: | |-VarDecl {{.*}} arr1n '_Float16 [10]'
+//CHECK: | |-VarDecl {{.*}} arr2n '_Float16 [3]' cinit
+//CHECK: | | `-InitListExpr {{.*}} '_Float16 [3]'
+//CHECK: | |   |-ImplicitCastExpr {{.*}} '_Float16' 
+//CHECK: | |   | `-FloatingLiteral {{.*}} 'double' 1.20e+00
+//CHECK: | |   |-ImplicitCastExpr {{.*}} '_Float16' 
+//CHECK: | |   | `-FloatingLiteral {{.*}} 'double' 3.00e+00
+//CHECK: | |   `-ImplicitCastExpr {{.*}} '_Float16' 
+//CHECK: | | `-FloatingLiteral {{.*}} 'double' 3.00e+04
+//CHECK: | `-FunctionDecl {{.*}} func1n 'const volatile _Float16 (const _Float16 &)'
+
+/* File */
+_Float16 f1f;
+_Float16 f2f = 32.4;
+_Float16 arr1f[10];
+_Float16 arr2f[] = { -1.2, -3.0, -3.e4 };
+_Float16 func1f(_Float16 arg);
+
+//CHECK: |-VarDecl {{.*}} f1f '_Float16'
+//CHECK: |-VarDecl {{.*}} f2f '_Float16' cinit
+//CHECK: | `-ImplicitCastExpr {{.*}} '_Float16' 
+//CHECK: |   `-FloatingLiteral {{.*}} 'double' 3.24e+01
+//CHECK: |-VarDecl {{.*}} arr1f '_Float16 [10]'
+//CHECK: |-VarDecl {{.*}} arr2f '_Float16 [3]' cinit
+//CHECK: | `-InitListExpr {{.*}} '_Float16 [3]'
+//CHECK: |   |-ImplicitCastExpr {{.*}} '_Float16' 
+//CHECK: |   | `-UnaryOperator {{.*}} 'double' prefix '-'
+//CHECK: |   |   `-FloatingLiteral {{.*}} 'double' 1.20e+00
+//CHECK: |   |-ImplicitCastExpr {{.*}} '_Float16' 
+//CHECK: |   | `-UnaryOperator {{.*}} 'double' prefix '-'
+//CHECK: |   |   `-FloatingLiteral {{.*}} 'double' 

[PATCH] D35216: [analyzer] Escape symbols when creating std::initializer_list.

2017-08-29 Thread Artem Dergachev via Phabricator via cfe-commits
NoQ updated this revision to Diff 113101.
NoQ added a comment.

Fix a bit of ObjCBoxedExpr behavior.


https://reviews.llvm.org/D35216

Files:
  lib/StaticAnalyzer/Core/ExprEngine.cpp
  test/Analysis/initializer.cpp
  test/Analysis/objc-boxing.m

Index: test/Analysis/objc-boxing.m
===
--- test/Analysis/objc-boxing.m
+++ test/Analysis/objc-boxing.m
@@ -5,6 +5,16 @@
 typedef signed char BOOL;
 typedef long NSInteger;
 typedef unsigned long NSUInteger;
+
+@protocol NSObject
+@end
+@interface NSObject  {}
+@end
+@protocol NSCopying
+@end
+@protocol NSCoding
+@end
+
 @interface NSString @end
 @interface NSString (NSStringExtensionMethods)
 + (id)stringWithUTF8String:(const char *)nullTerminatedCString;
@@ -28,7 +38,15 @@
 + (NSNumber *)numberWithUnsignedInteger:(NSUInteger)value ;
 @end
 
+@interface NSValue : NSObject 
+- (void)getValue:(void *)value;
++ (NSValue *)valueWithBytes:(const void *)value
+   objCType:(const char *)type;
+@end
 
+typedef typeof(sizeof(int)) size_t;
+extern void *malloc(size_t);
+extern void free(void *);
 extern char *strdup(const char *str);
 
 id constant_string() {
@@ -39,6 +57,23 @@
 return @(strdup("boxed dynamic string")); // expected-warning{{Potential memory leak}}
 }
 
+typedef struct __attribute__((objc_boxable)) {
+  const char *str;
+} BoxableStruct;
+
+id leak_within_boxed_struct() {
+  BoxableStruct bs;
+  bs.str = strdup("dynamic string"); // The duped string is now owned by val.
+  NSValue *val = @(bs); // no-warning
+  return val;
+}
+
+id leak_of_boxed_struct() {
+  BoxableStruct *bs = malloc(sizeof(BoxableStruct)); // This pointer isn't owned by val.
+  NSValue *val = @(*bs); // expected-warning{{Potential leak of memory pointed to by 'bs'}}
+  return val;
+}
+
 id const_char_pointer(int *x) {
   if (x)
 return @(3);
Index: test/Analysis/initializer.cpp
===
--- test/Analysis/initializer.cpp
+++ test/Analysis/initializer.cpp
@@ -1,7 +1,9 @@
-// RUN: %clang_analyze_cc1 -analyzer-checker=core,unix.Malloc,debug.ExprInspection -analyzer-config c++-inlining=constructors -std=c++11 -verify %s
+// RUN: %clang_analyze_cc1 -analyzer-checker=core,unix.Malloc,cplusplus.NewDeleteLeaks,debug.ExprInspection -analyzer-config c++-inlining=constructors -std=c++11 -verify %s
 
 void clang_analyzer_eval(bool);
 
+#include "Inputs/system-header-simulator-cxx.h"
+
 class A {
   int x;
 public:
@@ -204,3 +206,13 @@
const char()[2];
 };
 }
+
+namespace CXX_initializer_lists {
+struct C {
+  C(std::initializer_list list);
+};
+void foo() {
+  int *x = new int;
+  C c{x}; // no-warning
+}
+}
Index: lib/StaticAnalyzer/Core/ExprEngine.cpp
===
--- lib/StaticAnalyzer/Core/ExprEngine.cpp
+++ lib/StaticAnalyzer/Core/ExprEngine.cpp
@@ -827,6 +827,21 @@
   }
 }
 
+namespace {
+class CollectReachableSymbolsCallback final : public SymbolVisitor {
+  InvalidatedSymbols Symbols;
+
+public:
+  explicit CollectReachableSymbolsCallback(ProgramStateRef State) {}
+  const InvalidatedSymbols () const { return Symbols; }
+
+  bool VisitSymbol(SymbolRef Sym) override {
+Symbols.insert(Sym);
+return true;
+  }
+};
+} // end anonymous namespace
+
 void ExprEngine::Visit(const Stmt *S, ExplodedNode *Pred,
ExplodedNodeSet ) {
   PrettyStackTraceLoc CrashInfo(getContext().getSourceManager(),
@@ -1103,8 +1118,33 @@
 SVal result = svalBuilder.conjureSymbolVal(nullptr, Ex, LCtx,
resultType,
currBldrCtx->blockCount());
-ProgramStateRef state = N->getState()->BindExpr(Ex, LCtx, result);
-Bldr2.generateNode(S, N, state);
+ProgramStateRef State = N->getState()->BindExpr(Ex, LCtx, result);
+
+// Escape pointers passed into the list.
+// TODO: Ideally we also need to escape the elements of
+// ObjCArrayLiterals and ObjCDictionaryLiterals, however these
+// only consist of ObjC objects, and escapes of ObjC objects
+// aren't so important (eg., retain count checker ignores them).
+if (isa(Ex) ||
+(isa(Ex) &&
+ cast(Ex)->getSubExpr()->getType()->isRecordType()))
+  for (auto Child : Ex->children()) {
+if (!Child)
+  continue;
+
+SVal Val = State->getSVal(Child, LCtx);
+
+CollectReachableSymbolsCallback Scanner =
+State->scanReachableSymbols(
+Val);
+const InvalidatedSymbols  = Scanner.getSymbols();
+
+State = getCheckerManager().runCheckersForPointerEscape(
+State, EscapedSymbols,
+/*CallEvent*/ nullptr, PSK_EscapeOther, nullptr);
+  }
+
+Bldr2.generateNode(S, N, State);
   }
 
   

[PATCH] D35216: [analyzer] Escape symbols when creating std::initializer_list.

2017-08-29 Thread Artem Dergachev via Phabricator via cfe-commits
NoQ added inline comments.



Comment at: lib/StaticAnalyzer/Core/ExprEngine.cpp:1104
+// expression classes separately.
+if (!isa(Ex))
+  for (auto Child : Ex->children()) {

dcoughlin wrote:
> What is special about ObjCBoxedExpr here? Naively I would have expected that 
> we'd want to keep the old behavior for ObjCArrayLiteral and ObjCDictionary as 
> well.
Yeah, i got it all wrong initially.

If a `char *` is boxed into `NSString`, it doesn't escape, even though `Val` 
would be the string pointer - which is what i wanted to express here; we 
already had a test for that.

Similarly, if, say, a C struct is boxed, the pointer to the struct doesn't 
escape. However, contents of the struct do escape! Conveniently, `Val` here 
would be the (lazy) compound value, similarly to `std::initializer_list`, so we 
don't need to explicitly avoid escaping the struct pointer itself.

If a C integer is boxed, nothing escapes, of course, until we implement the 
mythical non-pointer escape (eg. file descriptor integers in stream checker 
should escape when they get boxed).

For `ObjC{Array,Dictionary}Expr`essions, contents of the array/dictionary do 
actually escape. However, because only `NSObject`s can be within such boxed 
literals, and `RetainCountChecker` ignores escapes, it is largely irrelevant 
how we behave in this case - i've even no idea how to test that, so i guess it 
could be fixed later.

Reference: https://clang.llvm.org/docs/ObjectiveCLiterals.html


https://reviews.llvm.org/D35216



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


r312007 - [modules-ts] Omit submodule semantics for TS modules

2017-08-29 Thread Boris Kolpackov via cfe-commits
Author: borisk
Date: Tue Aug 29 08:30:18 2017
New Revision: 312007

URL: http://llvm.org/viewvc/llvm-project?rev=312007=rev
Log:
[modules-ts] Omit submodule semantics for TS modules

If a TS module name has more than one component (e.g., foo.bar) then we
erroneously activated the submodule semantics when encountering a module
declaration in the module implementation unit (e.g., 'module foo.bar;').

Reviewed By: rsmith

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


Modified:
cfe/trunk/lib/Frontend/CompilerInstance.cpp
cfe/trunk/test/CXX/modules-ts/dcl.dcl/dcl.module/dcl.module.import/p1.cpp

Modified: cfe/trunk/lib/Frontend/CompilerInstance.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Frontend/CompilerInstance.cpp?rev=312007=312006=312007=diff
==
--- cfe/trunk/lib/Frontend/CompilerInstance.cpp (original)
+++ cfe/trunk/lib/Frontend/CompilerInstance.cpp Tue Aug 29 08:30:18 2017
@@ -1601,7 +1601,22 @@ CompilerInstance::loadModule(SourceLocat
  Module::NameVisibilityKind Visibility,
  bool IsInclusionDirective) {
   // Determine what file we're searching from.
-  StringRef ModuleName = Path[0].first->getName();
+  // FIXME: Should we be deciding whether this is a submodule (here and
+  // below) based on -fmodules-ts or should we pass a flag and make the
+  // caller decide?
+  std::string ModuleName;
+  if (getLangOpts().ModulesTS) {
+// FIXME: Same code as Sema::ActOnModuleDecl() so there is probably a
+// better place/way to do this.
+for (auto  : Path) {
+  if (!ModuleName.empty())
+ModuleName += ".";
+  ModuleName += Piece.first->getName();
+}
+  }
+  else
+ModuleName = Path[0].first->getName();
+
   SourceLocation ModuleNameLoc = Path[0].second;
 
   // If we've already handled this import, just return the cached result.
@@ -1816,7 +1831,7 @@ CompilerInstance::loadModule(SourceLocat
 
   // Verify that the rest of the module path actually corresponds to
   // a submodule.
-  if (Path.size() > 1) {
+  if (!getLangOpts().ModulesTS && Path.size() > 1) {
 for (unsigned I = 1, N = Path.size(); I != N; ++I) {
   StringRef Name = Path[I].first->getName();
   clang::Module *Sub = Module->findSubmodule(Name);

Modified: 
cfe/trunk/test/CXX/modules-ts/dcl.dcl/dcl.module/dcl.module.import/p1.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/CXX/modules-ts/dcl.dcl/dcl.module/dcl.module.import/p1.cpp?rev=312007=312006=312007=diff
==
--- cfe/trunk/test/CXX/modules-ts/dcl.dcl/dcl.module/dcl.module.import/p1.cpp 
(original)
+++ cfe/trunk/test/CXX/modules-ts/dcl.dcl/dcl.module/dcl.module.import/p1.cpp 
Tue Aug 29 08:30:18 2017
@@ -2,13 +2,17 @@
 // RUN: mkdir -p %t
 // RUN: echo 'export module x; export int a, b;' > %t/x.cppm
 // RUN: echo 'export module x.y; export int c;' > %t/x.y.cppm
+// RUN: echo 'export module a.b; export int d;' > %t/a.b.cppm
 //
 // RUN: %clang_cc1 -std=c++1z -fmodules-ts -emit-module-interface %t/x.cppm -o 
%t/x.pcm
 // RUN: %clang_cc1 -std=c++1z -fmodules-ts -emit-module-interface 
-fmodule-file=%t/x.pcm %t/x.y.cppm -o %t/x.y.pcm
+// RUN: %clang_cc1 -std=c++1z -fmodules-ts -emit-module-interface %t/a.b.cppm 
-o %t/a.b.pcm
 //
-// RUN: %clang_cc1 -std=c++1z -fmodules-ts -I%t -fmodule-file=%t/x.y.pcm 
-verify %s \
+// RUN: %clang_cc1 -std=c++1z -fmodules-ts -I%t -fmodule-file=%t/x.y.pcm 
-fmodule-file=%t/a.b.pcm -verify %s \
 // RUN:-DMODULE_NAME=z
-// RUN: %clang_cc1 -std=c++1z -fmodules-ts -I%t -fmodule-file=%t/x.y.pcm 
-verify %s \
+// RUN: %clang_cc1 -std=c++1z -fmodules-ts -I%t -fmodule-file=%t/x.y.pcm 
-fmodule-file=%t/a.b.pcm -verify %s \
+// RUN:-DMODULE_NAME=a.b
+// RUN: %clang_cc1 -std=c++1z -fmodules-ts -I%t -fmodule-file=%t/x.y.pcm 
-fmodule-file=%t/a.b.pcm -verify %s \
 // RUN:-DMODULE_X -DMODULE_NAME=x
 
 module MODULE_NAME;
@@ -33,6 +37,7 @@ import x [[noreturn]]; // expected-error
 import x [[blarg::noreturn]]; // expected-warning {{unknown attribute 
'noreturn' ignored}}
 
 import x.y;
+import a.b; // Does not imply existence of module a.
 import x.; // expected-error {{expected a module name after 'import'}}
 import .x; // expected-error {{expected a module name after 'import'}}
 


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


[PATCH] D35678: Omit sumbodule semantics for TS modules

2017-08-29 Thread Phabricator via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rL312007: [modules-ts] Omit submodule semantics for TS modules 
(authored by borisk).

Changed prior to commit:
  https://reviews.llvm.org/D35678?vs=110875=113098#toc

Repository:
  rL LLVM

https://reviews.llvm.org/D35678

Files:
  cfe/trunk/lib/Frontend/CompilerInstance.cpp
  cfe/trunk/test/CXX/modules-ts/dcl.dcl/dcl.module/dcl.module.import/p1.cpp


Index: cfe/trunk/test/CXX/modules-ts/dcl.dcl/dcl.module/dcl.module.import/p1.cpp
===
--- cfe/trunk/test/CXX/modules-ts/dcl.dcl/dcl.module/dcl.module.import/p1.cpp
+++ cfe/trunk/test/CXX/modules-ts/dcl.dcl/dcl.module/dcl.module.import/p1.cpp
@@ -2,13 +2,17 @@
 // RUN: mkdir -p %t
 // RUN: echo 'export module x; export int a, b;' > %t/x.cppm
 // RUN: echo 'export module x.y; export int c;' > %t/x.y.cppm
+// RUN: echo 'export module a.b; export int d;' > %t/a.b.cppm
 //
 // RUN: %clang_cc1 -std=c++1z -fmodules-ts -emit-module-interface %t/x.cppm -o 
%t/x.pcm
 // RUN: %clang_cc1 -std=c++1z -fmodules-ts -emit-module-interface 
-fmodule-file=%t/x.pcm %t/x.y.cppm -o %t/x.y.pcm
+// RUN: %clang_cc1 -std=c++1z -fmodules-ts -emit-module-interface %t/a.b.cppm 
-o %t/a.b.pcm
 //
-// RUN: %clang_cc1 -std=c++1z -fmodules-ts -I%t -fmodule-file=%t/x.y.pcm 
-verify %s \
+// RUN: %clang_cc1 -std=c++1z -fmodules-ts -I%t -fmodule-file=%t/x.y.pcm 
-fmodule-file=%t/a.b.pcm -verify %s \
 // RUN:-DMODULE_NAME=z
-// RUN: %clang_cc1 -std=c++1z -fmodules-ts -I%t -fmodule-file=%t/x.y.pcm 
-verify %s \
+// RUN: %clang_cc1 -std=c++1z -fmodules-ts -I%t -fmodule-file=%t/x.y.pcm 
-fmodule-file=%t/a.b.pcm -verify %s \
+// RUN:-DMODULE_NAME=a.b
+// RUN: %clang_cc1 -std=c++1z -fmodules-ts -I%t -fmodule-file=%t/x.y.pcm 
-fmodule-file=%t/a.b.pcm -verify %s \
 // RUN:-DMODULE_X -DMODULE_NAME=x
 
 module MODULE_NAME;
@@ -33,6 +37,7 @@
 import x [[blarg::noreturn]]; // expected-warning {{unknown attribute 
'noreturn' ignored}}
 
 import x.y;
+import a.b; // Does not imply existence of module a.
 import x.; // expected-error {{expected a module name after 'import'}}
 import .x; // expected-error {{expected a module name after 'import'}}
 
Index: cfe/trunk/lib/Frontend/CompilerInstance.cpp
===
--- cfe/trunk/lib/Frontend/CompilerInstance.cpp
+++ cfe/trunk/lib/Frontend/CompilerInstance.cpp
@@ -1601,7 +1601,22 @@
  Module::NameVisibilityKind Visibility,
  bool IsInclusionDirective) {
   // Determine what file we're searching from.
-  StringRef ModuleName = Path[0].first->getName();
+  // FIXME: Should we be deciding whether this is a submodule (here and
+  // below) based on -fmodules-ts or should we pass a flag and make the
+  // caller decide?
+  std::string ModuleName;
+  if (getLangOpts().ModulesTS) {
+// FIXME: Same code as Sema::ActOnModuleDecl() so there is probably a
+// better place/way to do this.
+for (auto  : Path) {
+  if (!ModuleName.empty())
+ModuleName += ".";
+  ModuleName += Piece.first->getName();
+}
+  }
+  else
+ModuleName = Path[0].first->getName();
+
   SourceLocation ModuleNameLoc = Path[0].second;
 
   // If we've already handled this import, just return the cached result.
@@ -1816,7 +1831,7 @@
 
   // Verify that the rest of the module path actually corresponds to
   // a submodule.
-  if (Path.size() > 1) {
+  if (!getLangOpts().ModulesTS && Path.size() > 1) {
 for (unsigned I = 1, N = Path.size(); I != N; ++I) {
   StringRef Name = Path[I].first->getName();
   clang::Module *Sub = Module->findSubmodule(Name);


Index: cfe/trunk/test/CXX/modules-ts/dcl.dcl/dcl.module/dcl.module.import/p1.cpp
===
--- cfe/trunk/test/CXX/modules-ts/dcl.dcl/dcl.module/dcl.module.import/p1.cpp
+++ cfe/trunk/test/CXX/modules-ts/dcl.dcl/dcl.module/dcl.module.import/p1.cpp
@@ -2,13 +2,17 @@
 // RUN: mkdir -p %t
 // RUN: echo 'export module x; export int a, b;' > %t/x.cppm
 // RUN: echo 'export module x.y; export int c;' > %t/x.y.cppm
+// RUN: echo 'export module a.b; export int d;' > %t/a.b.cppm
 //
 // RUN: %clang_cc1 -std=c++1z -fmodules-ts -emit-module-interface %t/x.cppm -o %t/x.pcm
 // RUN: %clang_cc1 -std=c++1z -fmodules-ts -emit-module-interface -fmodule-file=%t/x.pcm %t/x.y.cppm -o %t/x.y.pcm
+// RUN: %clang_cc1 -std=c++1z -fmodules-ts -emit-module-interface %t/a.b.cppm -o %t/a.b.pcm
 //
-// RUN: %clang_cc1 -std=c++1z -fmodules-ts -I%t -fmodule-file=%t/x.y.pcm -verify %s \
+// RUN: %clang_cc1 -std=c++1z -fmodules-ts -I%t -fmodule-file=%t/x.y.pcm -fmodule-file=%t/a.b.pcm -verify %s \
 // RUN:-DMODULE_NAME=z
-// RUN: %clang_cc1 -std=c++1z -fmodules-ts -I%t -fmodule-file=%t/x.y.pcm -verify %s \
+// RUN: %clang_cc1 -std=c++1z -fmodules-ts -I%t -fmodule-file=%t/x.y.pcm 

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

2017-08-29 Thread Daniel Kolozsvari via Phabricator via cfe-commits
koldaniel updated this revision to Diff 113094.
koldaniel added a comment.

Renaming the unsafe checker, updating tests.


https://reviews.llvm.org/D35068

Files:
  include/clang/StaticAnalyzer/Checkers/Checkers.td
  lib/Driver/Tools.cpp
  lib/StaticAnalyzer/Checkers/CheckSecuritySyntaxOnly.cpp
  test/Analysis/security-syntax-checks.m

Index: test/Analysis/security-syntax-checks.m
===
--- test/Analysis/security-syntax-checks.m
+++ test/Analysis/security-syntax-checks.m
@@ -13,6 +13,9 @@
 # define BUILTIN(f) f
 #endif /* USE_BUILTINS */
 
+#include "Inputs/system-header-simulator-for-valist.h"
+#include "Inputs/system-header-simulator-for-simple-stream.h"
+
 typedef typeof(sizeof(int)) size_t;
 
 
@@ -202,3 +205,83 @@
   mkdtemp("XX");
 }
 
+
+//===--===
+// deprecated or unsafe buffer handling
+//===--===
+typedef int wchar_t;
+
+int sprintf(char *str, const char *format, ...);
+//int vsprintf (char *s, const char *format, va_list arg);
+int scanf(const char *format, ...);
+int wscanf(const wchar_t *format, ...);
+int fscanf(FILE *stream, const char *format, ...);
+int fwscanf(FILE *stream, const wchar_t *format, ...);
+int vscanf(const char *format, va_list arg);
+int vwscanf(const wchar_t *format, va_list arg);
+int vfscanf(FILE *stream, const char *format, va_list arg);
+int vfwscanf(FILE *stream, const wchar_t *format, va_list arg);
+int sscanf(const char *s, const char *format, ...);
+int swscanf(const wchar_t *ws, const wchar_t *format, ...);
+int vsscanf(const char *s, const char *format, va_list arg);
+int vswscanf(const wchar_t *ws, const wchar_t *format, va_list arg);
+int swprintf(wchar_t *ws, size_t len, const wchar_t *format, ...);
+int snprintf(char *s, size_t n, const char *format, ...);
+int vswprintf(wchar_t *ws, size_t len, const wchar_t *format, va_list arg);
+int vsnprintf(char *s, size_t n, const char *format, va_list arg);
+void *memcpy(void *destination, const void *source, size_t num);
+void *memmove(void *destination, const void *source, size_t num);
+char *strncpy(char *destination, const char *source, size_t num);
+char *strncat(char *destination, const char *source, size_t num);
+void *memset(void *ptr, int value, size_t num);
+
+void test_deprecated_or_unsafe_buffer_handling_1() {
+  char buf [5];
+  wchar_t wbuf [5];
+  int a;
+  FILE *file;
+  sprintf(buf, "a"); // expected-warning{{Using 'sprintf' is deprecated as it does not provide bounding of the memory buffer or security checks introduced in the C11 standard. Replace with analogous functions introduced in C11 standard that supports length arguments or provides boundary checks such as 'sprintf_s'}}
+  scanf("%d", ); // expected-warning{{Using 'scanf' is deprecated as it does not provide bounding of the memory buffer or security checks introduced in the C11 standard. Replace with analogous functions introduced in C11 standard that supports length arguments or provides boundary checks such as 'scanf_s'}}
+  scanf("%s", buf); // expected-warning{{Call to function 'scanf' is insecure as it does not provide bounding of the memory buffer. Replace with analogous functions that support length arguments or provides boundary checks such as 'scanf_s' in case of C11}} expected-warning{{Using 'scanf' is deprecated as it does not provide bounding of the memory buffer or security checks introduced in the C11 standard. Replace with analogous functions introduced in C11 standard that supports length arguments or provides boundary checks such as 'scanf_s'}}
+  scanf("%4s", buf); // expected-warning{{Using 'scanf' is deprecated as it does not provide bounding of the memory buffer or security checks introduced in the C11 standard. Replace with analogous functions introduced in C11 standard that supports length arguments or provides boundary checks such as 'scanf_s'}}
+  wscanf((const wchar_t*) L"%s", buf); // expected-warning{{Call to function 'wscanf' is insecure as it does not provide bounding of the memory buffer. Replace with analogous functions that support length arguments or provides boundary checks such as 'wscanf_s' in case of C11}} expected-warning{{Using 'wscanf' is deprecated as it does not provide bounding of the memory buffer or security checks introduced in the C11 standard. Replace with analogous functions introduced in C11 standard that supports length arguments or provides boundary checks such as 'wscanf_s'}}
+  fscanf(file, "%d", ); // expected-warning{{Using 'fscanf' is deprecated as it does not provide bounding of the memory buffer or security checks introduced in the C11 standard. Replace with analogous functions introduced in C11 standard that supports length arguments or provides boundary checks such as 'fscanf_s'}}
+  fscanf(file, "%s", buf); // expected-warning{{Call to function 'fscanf' is insecure as it does not 

[PATCH] D37263: [clang-format] Ignore case when sorting using-declarations

2017-08-29 Thread Krasimir Georgiev via Phabricator via cfe-commits
krasimir updated this revision to Diff 113092.
krasimir added a comment.

- Actually add a test


https://reviews.llvm.org/D37263

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


Index: unittests/Format/UsingDeclarationsSorterTest.cpp
===
--- unittests/Format/UsingDeclarationsSorterTest.cpp
+++ unittests/Format/UsingDeclarationsSorterTest.cpp
@@ -86,6 +86,40 @@
   "using a, b;"));
 }
 
+TEST_F(UsingDeclarationsSorterTest, SortsCaseInsensitively) {
+  EXPECT_EQ("using A;\n"
+"using a;",
+sortUsingDeclarations("using A;\n"
+  "using a;"));
+  EXPECT_EQ("using a;\n"
+"using A;",
+sortUsingDeclarations("using a;\n"
+  "using A;"));
+  EXPECT_EQ("using a;\n"
+"using B;",
+sortUsingDeclarations("using B;\n"
+  "using a;"));
+  EXPECT_EQ("using _;\n"
+"using a;",
+sortUsingDeclarations("using a;\n"
+  "using _;"));
+  EXPECT_EQ("using a::_;\n"
+"using a::a;",
+sortUsingDeclarations("using a::a;\n"
+  "using a::_;"));
+
+  EXPECT_EQ("using ::testing::_;\n"
+"using ::testing::Aardvark;\n"
+"using ::testing::apple::Honeycrisp;\n"
+"using ::testing::Xylophone;\n"
+"using ::testing::zebra::Stripes;",
+sortUsingDeclarations("using ::testing::Aardvark;\n"
+  "using ::testing::Xylophone;\n"
+  "using ::testing::_;\n"
+  "using ::testing::apple::Honeycrisp;\n"
+  "using ::testing::zebra::Stripes;"));
+}
+
 TEST_F(UsingDeclarationsSorterTest, SortsMultipleTopLevelDeclarations) {
   EXPECT_EQ("using a;\n"
 "using b;\n"
Index: lib/Format/UsingDeclarationsSorter.cpp
===
--- lib/Format/UsingDeclarationsSorter.cpp
+++ lib/Format/UsingDeclarationsSorter.cpp
@@ -34,7 +34,7 @@
   : Line(Line), Label(Label) {}
 
   bool operator<(const UsingDeclaration ) const {
-return Label < Other.Label;
+return StringRef(Label).compare_lower(Other.Label) < 0;
   }
 };
 


Index: unittests/Format/UsingDeclarationsSorterTest.cpp
===
--- unittests/Format/UsingDeclarationsSorterTest.cpp
+++ unittests/Format/UsingDeclarationsSorterTest.cpp
@@ -86,6 +86,40 @@
   "using a, b;"));
 }
 
+TEST_F(UsingDeclarationsSorterTest, SortsCaseInsensitively) {
+  EXPECT_EQ("using A;\n"
+"using a;",
+sortUsingDeclarations("using A;\n"
+  "using a;"));
+  EXPECT_EQ("using a;\n"
+"using A;",
+sortUsingDeclarations("using a;\n"
+  "using A;"));
+  EXPECT_EQ("using a;\n"
+"using B;",
+sortUsingDeclarations("using B;\n"
+  "using a;"));
+  EXPECT_EQ("using _;\n"
+"using a;",
+sortUsingDeclarations("using a;\n"
+  "using _;"));
+  EXPECT_EQ("using a::_;\n"
+"using a::a;",
+sortUsingDeclarations("using a::a;\n"
+  "using a::_;"));
+
+  EXPECT_EQ("using ::testing::_;\n"
+"using ::testing::Aardvark;\n"
+"using ::testing::apple::Honeycrisp;\n"
+"using ::testing::Xylophone;\n"
+"using ::testing::zebra::Stripes;",
+sortUsingDeclarations("using ::testing::Aardvark;\n"
+  "using ::testing::Xylophone;\n"
+  "using ::testing::_;\n"
+  "using ::testing::apple::Honeycrisp;\n"
+  "using ::testing::zebra::Stripes;"));
+}
+
 TEST_F(UsingDeclarationsSorterTest, SortsMultipleTopLevelDeclarations) {
   EXPECT_EQ("using a;\n"
 "using b;\n"
Index: lib/Format/UsingDeclarationsSorter.cpp
===
--- lib/Format/UsingDeclarationsSorter.cpp
+++ lib/Format/UsingDeclarationsSorter.cpp
@@ -34,7 +34,7 @@
   : Line(Line), Label(Label) {}
 
   bool operator<(const UsingDeclaration ) const {
-return Label < Other.Label;
+return StringRef(Label).compare_lower(Other.Label) < 0;
   }
 };
 
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D33719: Add _Float16 as a C/C++ source language type

2017-08-29 Thread Roger Ferrer Ibanez via Phabricator via cfe-commits
rogfer01 added a comment.

There are a few tests checking the precise interaction between `__fp16` and 
`_Float16` values but I don't see tests interacting `_Float16` and the other 
standard floating types `float`, `double` and `long double`.

Do you reckon it is worth adding them as well?




Comment at: test/Frontend/float16.cpp:82
+
+// When do have native half types, we expect to see promotions X:
+

Is this X some form of TODO?


https://reviews.llvm.org/D33719



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


[PATCH] D37263: [clang-format] Ignore case when sorting using-declarations

2017-08-29 Thread Krasimir Georgiev via Phabricator via cfe-commits
krasimir created this revision.

This ignores case while sorting using-declarations, fixing the wierd case in the
last test case added.


https://reviews.llvm.org/D37263

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


Index: unittests/Format/UsingDeclarationsSorterTest.cpp
===
--- unittests/Format/UsingDeclarationsSorterTest.cpp
+++ unittests/Format/UsingDeclarationsSorterTest.cpp
@@ -86,6 +86,40 @@
   "using a, b;"));
 }
 
+TEST_F(UsingDeclarationsSorterTest, SortsCaseInsensitively) {
+  EXPECT_EQ("using A;\n"
+"using a;",
+sortUsingDeclarations("using A;\n"
+  "using a;"));
+  EXPECT_EQ("using a;\n"
+"using B;",
+sortUsingDeclarations("using B;\n"
+  "using a;"));
+  EXPECT_EQ("using _;\n"
+"using a;",
+sortUsingDeclarations("using a;\n"
+  "using _;"));
+  EXPECT_EQ("using _;\n"
+"using a;",
+sortUsingDeclarations("using a;\n"
+  "using _;"));
+  EXPECT_EQ("using a::_;\n"
+"using a::a;",
+sortUsingDeclarations("using a::a;\n"
+  "using a::_;"));
+
+  EXPECT_EQ("using ::testing::_;\n"
+"using ::testing::Aardvark;\n"
+"using ::testing::apple::Honeycrisp;\n"
+"using ::testing::Xylophone;\n"
+"using ::testing::zebra::Stripes;",
+sortUsingDeclarations("using ::testing::Aardvark;\n"
+  "using ::testing::Xylophone;\n"
+  "using ::testing::_;\n"
+  "using ::testing::apple::Honeycrisp;\n"
+  "using ::testing::zebra::Stripes;"));
+}
+
 TEST_F(UsingDeclarationsSorterTest, SortsMultipleTopLevelDeclarations) {
   EXPECT_EQ("using a;\n"
 "using b;\n"
Index: lib/Format/UsingDeclarationsSorter.cpp
===
--- lib/Format/UsingDeclarationsSorter.cpp
+++ lib/Format/UsingDeclarationsSorter.cpp
@@ -34,7 +34,7 @@
   : Line(Line), Label(Label) {}
 
   bool operator<(const UsingDeclaration ) const {
-return Label < Other.Label;
+return StringRef(Label).compare_lower(Other.Label) < 0;
   }
 };
 


Index: unittests/Format/UsingDeclarationsSorterTest.cpp
===
--- unittests/Format/UsingDeclarationsSorterTest.cpp
+++ unittests/Format/UsingDeclarationsSorterTest.cpp
@@ -86,6 +86,40 @@
   "using a, b;"));
 }
 
+TEST_F(UsingDeclarationsSorterTest, SortsCaseInsensitively) {
+  EXPECT_EQ("using A;\n"
+"using a;",
+sortUsingDeclarations("using A;\n"
+  "using a;"));
+  EXPECT_EQ("using a;\n"
+"using B;",
+sortUsingDeclarations("using B;\n"
+  "using a;"));
+  EXPECT_EQ("using _;\n"
+"using a;",
+sortUsingDeclarations("using a;\n"
+  "using _;"));
+  EXPECT_EQ("using _;\n"
+"using a;",
+sortUsingDeclarations("using a;\n"
+  "using _;"));
+  EXPECT_EQ("using a::_;\n"
+"using a::a;",
+sortUsingDeclarations("using a::a;\n"
+  "using a::_;"));
+
+  EXPECT_EQ("using ::testing::_;\n"
+"using ::testing::Aardvark;\n"
+"using ::testing::apple::Honeycrisp;\n"
+"using ::testing::Xylophone;\n"
+"using ::testing::zebra::Stripes;",
+sortUsingDeclarations("using ::testing::Aardvark;\n"
+  "using ::testing::Xylophone;\n"
+  "using ::testing::_;\n"
+  "using ::testing::apple::Honeycrisp;\n"
+  "using ::testing::zebra::Stripes;"));
+}
+
 TEST_F(UsingDeclarationsSorterTest, SortsMultipleTopLevelDeclarations) {
   EXPECT_EQ("using a;\n"
 "using b;\n"
Index: lib/Format/UsingDeclarationsSorter.cpp
===
--- lib/Format/UsingDeclarationsSorter.cpp
+++ lib/Format/UsingDeclarationsSorter.cpp
@@ -34,7 +34,7 @@
   : Line(Line), Label(Label) {}
 
   bool operator<(const UsingDeclaration ) const {
-return Label < Other.Label;
+return StringRef(Label).compare_lower(Other.Label) < 0;
   }
 };
 
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D37249: [Bash-autocomplete] Refactor autocomplete code into own function

2017-08-29 Thread Raphael Isemann via Phabricator via cfe-commits
teemperor accepted this revision.
teemperor added a comment.
This revision is now accepted and ready to land.

LGTM!


https://reviews.llvm.org/D37249



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


[PATCH] D34512: Add preliminary Cross Translation Unit support library

2017-08-29 Thread Gábor Horváth via Phabricator via cfe-commits
xazax.hun updated this revision to Diff 113088.
xazax.hun marked 2 inline comments as done.
xazax.hun added a comment.

- Updates according to review comments.


https://reviews.llvm.org/D34512

Files:
  include/clang/Basic/AllDiagnostics.h
  include/clang/Basic/CMakeLists.txt
  include/clang/Basic/Diagnostic.td
  include/clang/Basic/DiagnosticCrossTUKinds.td
  include/clang/Basic/DiagnosticIDs.h
  include/clang/CrossTU/CrossTUDiagnostic.h
  include/clang/CrossTU/CrossTranslationUnit.h
  lib/AST/ASTImporter.cpp
  lib/Basic/DiagnosticIDs.cpp
  lib/CMakeLists.txt
  lib/CrossTU/CMakeLists.txt
  lib/CrossTU/CrossTranslationUnit.cpp
  test/Analysis/func-mapping-test.cpp
  test/CMakeLists.txt
  test/lit.cfg
  tools/CMakeLists.txt
  tools/clang-func-mapping/CMakeLists.txt
  tools/clang-func-mapping/ClangFnMapGen.cpp
  tools/diagtool/DiagnosticNames.cpp
  unittests/CMakeLists.txt
  unittests/CrossTU/CMakeLists.txt
  unittests/CrossTU/CrossTranslationUnitTest.cpp

Index: unittests/CrossTU/CrossTranslationUnitTest.cpp
===
--- /dev/null
+++ unittests/CrossTU/CrossTranslationUnitTest.cpp
@@ -0,0 +1,98 @@
+//===- unittest/Tooling/CrossTranslationUnitTest.cpp - Tooling unit tests -===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===--===//
+
+#include "clang/AST/ASTConsumer.h"
+#include "clang/CrossTU/CrossTranslationUnit.h"
+#include "clang/Frontend/FrontendAction.h"
+#include "clang/Tooling/Tooling.h"
+#include "llvm/Config/llvm-config.h"
+#include "llvm/Support/Path.h"
+#include "gtest/gtest.h"
+#include 
+
+namespace clang {
+namespace cross_tu {
+
+namespace {
+StringRef IndexFileName = "index.txt";
+StringRef ASTFileName = "f.ast";
+StringRef DefinitionFileName = "input.cc";
+
+class CTUASTConsumer : public clang::ASTConsumer {
+public:
+  explicit CTUASTConsumer(clang::CompilerInstance , bool *Success)
+  : CTU(CI), Success(Success) {}
+
+  void HandleTranslationUnit(ASTContext ) {
+const TranslationUnitDecl *TU = Ctx.getTranslationUnitDecl();
+const FunctionDecl *FD = nullptr;
+for (const Decl *D : TU->decls()) {
+  FD = dyn_cast(D);
+  if (FD && FD->getName() == "f")
+break;
+}
+assert(FD);
+bool OrigFDHasBody = FD->hasBody();
+
+// Prepare the index file and the AST file.
+std::error_code EC;
+llvm::raw_fd_ostream OS(IndexFileName, EC, llvm::sys::fs::F_Text);
+OS << "c:@F@f#I# " << ASTFileName << "\n";
+OS.flush();
+StringRef SourceText = "int f(int) { return 0; }\n";
+// This file must exist since the saved ASTFile will reference it.
+llvm::raw_fd_ostream OS2(DefinitionFileName, EC, llvm::sys::fs::F_Text);
+OS2 << SourceText;
+OS2.flush();
+std::unique_ptr ASTWithDefinition =
+tooling::buildASTFromCode(SourceText);
+ASTWithDefinition->Save(ASTFileName);
+
+// Load the definition from the AST file.
+const FunctionDecl *NewFD =
+CTU.getCrossTUDefinition(FD, ".", IndexFileName);
+
+*Success = NewFD && NewFD->hasBody() && !OrigFDHasBody;
+  }
+
+private:
+  CrossTranslationUnitContext CTU;
+  bool *Success;
+};
+
+class CTUAction : public clang::ASTFrontendAction {
+public:
+  CTUAction(bool *Success) : Success(Success) {}
+
+protected:
+  std::unique_ptr
+  CreateASTConsumer(clang::CompilerInstance , StringRef) override {
+return llvm::make_unique(CI, Success);
+  }
+
+private:
+  bool *Success;
+};
+
+} // end namespace
+
+TEST(CrossTranslationUnit, CanLoadFunctionDefinition) {
+  bool Success = false;
+  EXPECT_TRUE(tooling::runToolOnCode(new CTUAction(), "int f(int);"));
+  EXPECT_TRUE(Success);
+  EXPECT_TRUE(llvm::sys::fs::exists(IndexFileName));
+  EXPECT_FALSE((bool)llvm::sys::fs::remove(IndexFileName));
+  EXPECT_TRUE(llvm::sys::fs::exists(ASTFileName));
+  EXPECT_FALSE((bool)llvm::sys::fs::remove(ASTFileName));
+  EXPECT_TRUE(llvm::sys::fs::exists(DefinitionFileName));
+  EXPECT_FALSE((bool)llvm::sys::fs::remove(DefinitionFileName));
+}
+
+} // end namespace cross_tu
+} // end namespace clang
Index: unittests/CrossTU/CMakeLists.txt
===
--- /dev/null
+++ unittests/CrossTU/CMakeLists.txt
@@ -0,0 +1,16 @@
+set(LLVM_LINK_COMPONENTS
+  ${LLVM_TARGETS_TO_BUILD}
+  Support
+  )
+
+add_clang_unittest(CrossTUTests
+  CrossTranslationUnitTest.cpp
+  )
+
+target_link_libraries(CrossTUTests
+  clangAST
+  clangBasic
+  clangCrossTU
+  clangFrontend
+  clangTooling
+  )
Index: unittests/CMakeLists.txt
===
--- unittests/CMakeLists.txt
+++ unittests/CMakeLists.txt
@@ -19,6 +19,7 @@
 endif()
 add_subdirectory(ASTMatchers)
 add_subdirectory(AST)
+add_subdirectory(CrossTU)
 add_subdirectory(Tooling)
 

r312000 - [clang-format] Refactor likely xml a bit, NFC

2017-08-29 Thread Krasimir Georgiev via cfe-commits
Author: krasimir
Date: Tue Aug 29 06:57:31 2017
New Revision: 312000

URL: http://llvm.org/viewvc/llvm-project?rev=312000=rev
Log:
[clang-format] Refactor likely xml a bit, NFC

Modified:
cfe/trunk/lib/Format/Format.cpp

Modified: cfe/trunk/lib/Format/Format.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Format/Format.cpp?rev=312000=311999=312000=diff
==
--- cfe/trunk/lib/Format/Format.cpp (original)
+++ cfe/trunk/lib/Format/Format.cpp Tue Aug 29 06:57:31 2017
@@ -1539,7 +1539,7 @@ bool isMpegTS(StringRef Code) {
   return Code.size() > 188 && Code[0] == 0x47 && Code[188] == 0x47;
 }
 
-bool likelyXml(StringRef Code) {
+bool isLikelyXml(StringRef Code) {
   return Code.ltrim().startswith("<");
 }
 
@@ -1549,9 +1549,10 @@ tooling::Replacements sortIncludes(const
   tooling::Replacements Replaces;
   if (!Style.SortIncludes)
 return Replaces;
-  if (likelyXml(Code) ||
-  (Style.Language == FormatStyle::LanguageKind::LK_JavaScript &&
-   isMpegTS(Code)))
+  if (isLikelyXml(Code))
+return Replaces;
+  if (Style.Language == FormatStyle::LanguageKind::LK_JavaScript &&
+  isMpegTS(Code))
 return Replaces;
   if (Style.Language == FormatStyle::LanguageKind::LK_JavaScript)
 return sortJavaScriptImports(Style, Code, Ranges, FileName);
@@ -1899,8 +1900,9 @@ tooling::Replacements reformat(const For
   FormatStyle Expanded = expandPresets(Style);
   if (Expanded.DisableFormat)
 return tooling::Replacements();
-  if (likelyXml(Code) ||
-  (Expanded.Language == FormatStyle::LK_JavaScript && isMpegTS(Code)))
+  if (isLikelyXml(Code))
+return tooling::Replacements();
+  if (Expanded.Language == FormatStyle::LK_JavaScript && isMpegTS(Code))
 return tooling::Replacements();
 
   typedef std::function


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


[PATCH] D37136: [clang-format] Do not format likely xml

2017-08-29 Thread Krasimir Georgiev via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rL311999: [clang-format] Do not format likely xml (authored by 
krasimir).

Changed prior to commit:
  https://reviews.llvm.org/D37136?vs=113085=113087#toc

Repository:
  rL LLVM

https://reviews.llvm.org/D37136

Files:
  cfe/trunk/lib/Format/Format.cpp
  cfe/trunk/unittests/Format/FormatTest.cpp
  cfe/trunk/unittests/Format/SortIncludesTest.cpp


Index: cfe/trunk/lib/Format/Format.cpp
===
--- cfe/trunk/lib/Format/Format.cpp
+++ cfe/trunk/lib/Format/Format.cpp
@@ -1539,14 +1539,19 @@
   return Code.size() > 188 && Code[0] == 0x47 && Code[188] == 0x47;
 }
 
+bool likelyXml(StringRef Code) {
+  return Code.ltrim().startswith("<");
+}
+
 tooling::Replacements sortIncludes(const FormatStyle , StringRef Code,
ArrayRef Ranges,
StringRef FileName, unsigned *Cursor) {
   tooling::Replacements Replaces;
   if (!Style.SortIncludes)
 return Replaces;
-  if (Style.Language == FormatStyle::LanguageKind::LK_JavaScript &&
-  isMpegTS(Code))
+  if (likelyXml(Code) ||
+  (Style.Language == FormatStyle::LanguageKind::LK_JavaScript &&
+   isMpegTS(Code)))
 return Replaces;
   if (Style.Language == FormatStyle::LanguageKind::LK_JavaScript)
 return sortJavaScriptImports(Style, Code, Ranges, FileName);
@@ -1894,7 +1899,8 @@
   FormatStyle Expanded = expandPresets(Style);
   if (Expanded.DisableFormat)
 return tooling::Replacements();
-  if (Expanded.Language == FormatStyle::LK_JavaScript && isMpegTS(Code))
+  if (likelyXml(Code) ||
+  (Expanded.Language == FormatStyle::LK_JavaScript && isMpegTS(Code)))
 return tooling::Replacements();
 
   typedef std::function
Index: cfe/trunk/unittests/Format/FormatTest.cpp
===
--- cfe/trunk/unittests/Format/FormatTest.cpp
+++ cfe/trunk/unittests/Format/FormatTest.cpp
@@ -11253,6 +11253,13 @@
   EXPECT_EQ("auto c = u8'a';", format("auto c = u8'a';"));
 }
 
+TEST_F(FormatTest, DoNotFormatLikelyXml) {
+  EXPECT_EQ("",
+format("", getGoogleStyle()));
+  EXPECT_EQ(" ",
+format(" ", getGoogleStyle()));
+}
+
 } // end namespace
 } // end namespace format
 } // end namespace clang
Index: cfe/trunk/unittests/Format/SortIncludesTest.cpp
===
--- cfe/trunk/unittests/Format/SortIncludesTest.cpp
+++ cfe/trunk/unittests/Format/SortIncludesTest.cpp
@@ -398,6 +398,17 @@
   EXPECT_EQ(26u, Ranges[0].getLength());
 }
 
+TEST_F(SortIncludesTest, DoNotSortLikelyXml) {
+  EXPECT_EQ("",
+sort(""));
+}
+
 } // end namespace
 } // end namespace format
 } // end namespace clang


Index: cfe/trunk/lib/Format/Format.cpp
===
--- cfe/trunk/lib/Format/Format.cpp
+++ cfe/trunk/lib/Format/Format.cpp
@@ -1539,14 +1539,19 @@
   return Code.size() > 188 && Code[0] == 0x47 && Code[188] == 0x47;
 }
 
+bool likelyXml(StringRef Code) {
+  return Code.ltrim().startswith("<");
+}
+
 tooling::Replacements sortIncludes(const FormatStyle , StringRef Code,
ArrayRef Ranges,
StringRef FileName, unsigned *Cursor) {
   tooling::Replacements Replaces;
   if (!Style.SortIncludes)
 return Replaces;
-  if (Style.Language == FormatStyle::LanguageKind::LK_JavaScript &&
-  isMpegTS(Code))
+  if (likelyXml(Code) ||
+  (Style.Language == FormatStyle::LanguageKind::LK_JavaScript &&
+   isMpegTS(Code)))
 return Replaces;
   if (Style.Language == FormatStyle::LanguageKind::LK_JavaScript)
 return sortJavaScriptImports(Style, Code, Ranges, FileName);
@@ -1894,7 +1899,8 @@
   FormatStyle Expanded = expandPresets(Style);
   if (Expanded.DisableFormat)
 return tooling::Replacements();
-  if (Expanded.Language == FormatStyle::LK_JavaScript && isMpegTS(Code))
+  if (likelyXml(Code) ||
+  (Expanded.Language == FormatStyle::LK_JavaScript && isMpegTS(Code)))
 return tooling::Replacements();
 
   typedef std::function
Index: cfe/trunk/unittests/Format/FormatTest.cpp
===
--- cfe/trunk/unittests/Format/FormatTest.cpp
+++ cfe/trunk/unittests/Format/FormatTest.cpp
@@ -11253,6 +11253,13 @@
   EXPECT_EQ("auto c = u8'a';", format("auto c = u8'a';"));
 }
 
+TEST_F(FormatTest, DoNotFormatLikelyXml) {
+  EXPECT_EQ("",
+format("", getGoogleStyle()));
+  EXPECT_EQ(" ",
+format(" ", getGoogleStyle()));
+}
+
 } // end namespace
 } // end namespace format
 } // end namespace clang
Index: cfe/trunk/unittests/Format/SortIncludesTest.cpp
===
--- 

[PATCH] D37136: [clang-format] Do not format likely xml

2017-08-29 Thread Krasimir Georgiev via Phabricator via cfe-commits
krasimir updated this revision to Diff 113085.
krasimir marked 3 inline comments as done.
krasimir added a comment.

- Address review comments


https://reviews.llvm.org/D37136

Files:
  lib/Format/Format.cpp
  unittests/Format/FormatTest.cpp
  unittests/Format/SortIncludesTest.cpp


Index: unittests/Format/SortIncludesTest.cpp
===
--- unittests/Format/SortIncludesTest.cpp
+++ unittests/Format/SortIncludesTest.cpp
@@ -398,6 +398,17 @@
   EXPECT_EQ(26u, Ranges[0].getLength());
 }
 
+TEST_F(SortIncludesTest, DoNotSortLikelyXml) {
+  EXPECT_EQ("",
+sort(""));
+}
+
 } // end namespace
 } // end namespace format
 } // end namespace clang
Index: unittests/Format/FormatTest.cpp
===
--- unittests/Format/FormatTest.cpp
+++ unittests/Format/FormatTest.cpp
@@ -11253,6 +11253,13 @@
   EXPECT_EQ("auto c = u8'a';", format("auto c = u8'a';"));
 }
 
+TEST_F(FormatTest, DoNotFormatLikelyXml) {
+  EXPECT_EQ("",
+format("", getGoogleStyle()));
+  EXPECT_EQ(" ",
+format(" ", getGoogleStyle()));
+}
+
 } // end namespace
 } // end namespace format
 } // end namespace clang
Index: lib/Format/Format.cpp
===
--- lib/Format/Format.cpp
+++ lib/Format/Format.cpp
@@ -1539,12 +1539,18 @@
   return Code.size() > 188 && Code[0] == 0x47 && Code[188] == 0x47;
 }
 
+bool isLikelyXml(StringRef Code) {
+  return Code.ltrim().startswith("<");
+}
+
 tooling::Replacements sortIncludes(const FormatStyle , StringRef Code,
ArrayRef Ranges,
StringRef FileName, unsigned *Cursor) {
   tooling::Replacements Replaces;
   if (!Style.SortIncludes)
 return Replaces;
+  if (isLikelyXml(Code))
+return Replaces;
   if (Style.Language == FormatStyle::LanguageKind::LK_JavaScript &&
   isMpegTS(Code))
 return Replaces;
@@ -1894,6 +1900,8 @@
   FormatStyle Expanded = expandPresets(Style);
   if (Expanded.DisableFormat)
 return tooling::Replacements();
+  if (isLikelyXml(Code))
+return tooling::Replacements();
   if (Expanded.Language == FormatStyle::LK_JavaScript && isMpegTS(Code))
 return tooling::Replacements();
 


Index: unittests/Format/SortIncludesTest.cpp
===
--- unittests/Format/SortIncludesTest.cpp
+++ unittests/Format/SortIncludesTest.cpp
@@ -398,6 +398,17 @@
   EXPECT_EQ(26u, Ranges[0].getLength());
 }
 
+TEST_F(SortIncludesTest, DoNotSortLikelyXml) {
+  EXPECT_EQ("",
+sort(""));
+}
+
 } // end namespace
 } // end namespace format
 } // end namespace clang
Index: unittests/Format/FormatTest.cpp
===
--- unittests/Format/FormatTest.cpp
+++ unittests/Format/FormatTest.cpp
@@ -11253,6 +11253,13 @@
   EXPECT_EQ("auto c = u8'a';", format("auto c = u8'a';"));
 }
 
+TEST_F(FormatTest, DoNotFormatLikelyXml) {
+  EXPECT_EQ("",
+format("", getGoogleStyle()));
+  EXPECT_EQ(" ",
+format(" ", getGoogleStyle()));
+}
+
 } // end namespace
 } // end namespace format
 } // end namespace clang
Index: lib/Format/Format.cpp
===
--- lib/Format/Format.cpp
+++ lib/Format/Format.cpp
@@ -1539,12 +1539,18 @@
   return Code.size() > 188 && Code[0] == 0x47 && Code[188] == 0x47;
 }
 
+bool isLikelyXml(StringRef Code) {
+  return Code.ltrim().startswith("<");
+}
+
 tooling::Replacements sortIncludes(const FormatStyle , StringRef Code,
ArrayRef Ranges,
StringRef FileName, unsigned *Cursor) {
   tooling::Replacements Replaces;
   if (!Style.SortIncludes)
 return Replaces;
+  if (isLikelyXml(Code))
+return Replaces;
   if (Style.Language == FormatStyle::LanguageKind::LK_JavaScript &&
   isMpegTS(Code))
 return Replaces;
@@ -1894,6 +1900,8 @@
   FormatStyle Expanded = expandPresets(Style);
   if (Expanded.DisableFormat)
 return tooling::Replacements();
+  if (isLikelyXml(Code))
+return tooling::Replacements();
   if (Expanded.Language == FormatStyle::LK_JavaScript && isMpegTS(Code))
 return tooling::Replacements();
 
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D37132: [clang-format] Add support for C++17 structured bindings.

2017-08-29 Thread Marek Kurdej via Phabricator via cfe-commits
curdeius updated this revision to Diff 113084.
curdeius added a comment.

Fix: use do-while loop.


https://reviews.llvm.org/D37132

Files:
  lib/Format/FormatToken.h
  lib/Format/TokenAnnotator.cpp
  unittests/Format/FormatTest.cpp

Index: unittests/Format/FormatTest.cpp
===
--- unittests/Format/FormatTest.cpp
+++ unittests/Format/FormatTest.cpp
@@ -11217,6 +11217,31 @@
   EXPECT_EQ("auto c = u8'a';", format("auto c = u8'a';"));
 }
 
+TEST_F(FormatTest, StructuredBindings) {
+  // Structured bindings is a C++17 feature.
+  // all modes, including C++11, C++14 and C++17
+  verifyFormat("auto [a, b] = f();");
+  EXPECT_EQ("auto [a, b] = f();", format("auto[a, b] = f();"));
+  EXPECT_EQ("const auto [a, b] = f();", format("const   auto[a, b] = f();"));
+  EXPECT_EQ("auto const [a, b] = f();", format("auto  const[a, b] = f();"));
+  EXPECT_EQ("auto const volatile [a, b] = f();",
+format("auto  const   volatile[a, b] = f();"));
+  EXPECT_EQ("auto [a, b, c] = f();", format("auto   [  a  ,  b,c   ] = f();"));
+  EXPECT_EQ("auto & [a, b, c] = f();",
+format("auto   &[  a  ,  b,c   ] = f();"));
+  EXPECT_EQ("auto && [a, b, c] = f();",
+format("auto   &&[  a  ,  b,c   ] = f();"));
+  EXPECT_EQ("auto const & [a, b] = f();", format("auto  const&[a, b] = f();"));
+  EXPECT_EQ("auto const volatile && [a, b] = f();",
+format("auto  const  volatile  &&[a, b] = f();"));
+  EXPECT_EQ("auto && [a, b] = f();", format("auto  &&[a, b] = f();"));
+
+  format::FormatStyle Spaces = format::getLLVMStyle();
+  Spaces.SpacesInSquareBrackets = true;
+  verifyFormat("auto [ a, b ] = f();", Spaces);
+  verifyFormat("auto && [ a, b ] = f();", Spaces);
+}
+
 } // end namespace
 } // end namespace format
 } // end namespace clang
Index: lib/Format/TokenAnnotator.cpp
===
--- lib/Format/TokenAnnotator.cpp
+++ lib/Format/TokenAnnotator.cpp
@@ -310,6 +310,16 @@
 return false;
   }
 
+  bool isCppStructuredBinding(const FormatToken *Tok) {
+if (!Style.isCpp() || !Tok->is(tok::l_square))
+  return false;
+do {
+  Tok = Tok->getPreviousNonComment();
+} while (Tok && Tok->isOneOf(tok::kw_const, tok::kw_volatile, tok::amp,
+ tok::ampamp));
+return Tok && Tok->is(tok::kw_auto);
+  }
+
   bool parseSquare() {
 if (!CurrentToken)
   return false;
@@ -344,7 +354,9 @@
 
 unsigned BindingIncrease = 1;
 if (Left->is(TT_Unknown)) {
-  if (StartsObjCMethodExpr) {
+  if (isCppStructuredBinding(Left)) {
+Left->Type = TT_StructuredBindingLSquare;
+  } else if (StartsObjCMethodExpr) {
 Left->Type = TT_ObjCMethodExpr;
   } else if (Style.Language == FormatStyle::LK_JavaScript && Parent &&
  Contexts.back().ContextKind == tok::l_brace &&
@@ -2256,17 +2268,20 @@
   if (Left.is(tok::l_square))
 return (Left.is(TT_ArrayInitializerLSquare) &&
 Style.SpacesInContainerLiterals && Right.isNot(tok::r_square)) ||
-   (Left.is(TT_ArraySubscriptLSquare) && Style.SpacesInSquareBrackets &&
-Right.isNot(tok::r_square));
+   (Left.isOneOf(TT_ArraySubscriptLSquare,
+ TT_StructuredBindingLSquare) &&
+Style.SpacesInSquareBrackets && Right.isNot(tok::r_square));
   if (Right.is(tok::r_square))
 return Right.MatchingParen &&
((Style.SpacesInContainerLiterals &&
  Right.MatchingParen->is(TT_ArrayInitializerLSquare)) ||
 (Style.SpacesInSquareBrackets &&
- Right.MatchingParen->is(TT_ArraySubscriptLSquare)));
+ Right.MatchingParen->isOneOf(TT_ArraySubscriptLSquare,
+  TT_StructuredBindingLSquare)));
   if (Right.is(tok::l_square) &&
   !Right.isOneOf(TT_ObjCMethodExpr, TT_LambdaLSquare,
- TT_DesignatedInitializerLSquare) &&
+ TT_DesignatedInitializerLSquare,
+ TT_StructuredBindingLSquare) &&
   !Left.isOneOf(tok::numeric_constant, TT_DictLiteral))
 return false;
   if (Left.is(tok::l_brace) && Right.is(tok::r_brace))
Index: lib/Format/FormatToken.h
===
--- lib/Format/FormatToken.h
+++ lib/Format/FormatToken.h
@@ -84,6 +84,7 @@
   TYPE(RegexLiteral) \
   TYPE(SelectorName) \
   TYPE(StartOfName) \
+  TYPE(StructuredBindingLSquare) \
   TYPE(TemplateCloser) \
   TYPE(TemplateOpener) \
   TYPE(TemplateString) \
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D37143: [clang-format] Fixed typedef enum brace wrapping

2017-08-29 Thread Pawel Maciocha via Phabricator via cfe-commits
PriMee added a comment.

Could you change the "Contributed by" section? Wrong account is assigned. Full 
name would be more satisfying. Thank You in advance :)


Repository:
  rL LLVM

https://reviews.llvm.org/D37143



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


[PATCH] D37143: [clang-format] Fixed typedef enum brace wrapping

2017-08-29 Thread Krasimir Georgiev via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rL311998: [clang-format] Fixed typedef enum brace wrapping 
(authored by krasimir).

Changed prior to commit:
  https://reviews.llvm.org/D37143?vs=113062=113081#toc

Repository:
  rL LLVM

https://reviews.llvm.org/D37143

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


Index: cfe/trunk/lib/Format/TokenAnnotator.cpp
===
--- cfe/trunk/lib/Format/TokenAnnotator.cpp
+++ cfe/trunk/lib/Format/TokenAnnotator.cpp
@@ -2647,6 +2647,7 @@
 return Right.HasUnescapedNewline;
   if (isAllmanBrace(Left) || isAllmanBrace(Right))
 return (Line.startsWith(tok::kw_enum) && Style.BraceWrapping.AfterEnum) ||
+   (Line.startsWith(tok::kw_typedef, tok::kw_enum) && 
Style.BraceWrapping.AfterEnum) ||
(Line.startsWith(tok::kw_class) && Style.BraceWrapping.AfterClass) 
||
(Line.startsWith(tok::kw_struct) && 
Style.BraceWrapping.AfterStruct);
   if (Left.is(TT_ObjCBlockLBrace) && !Style.AllowShortBlocksOnASingleLine)
Index: cfe/trunk/unittests/Format/FormatTest.cpp
===
--- cfe/trunk/unittests/Format/FormatTest.cpp
+++ cfe/trunk/unittests/Format/FormatTest.cpp
@@ -1324,6 +1324,32 @@
   verifyFormat("enum X : std::uint32_t { A, B };");
 }
 
+TEST_F(FormatTest, FormatsTypedefEnum) {
+  FormatStyle Style = getLLVMStyle();
+  Style.ColumnLimit = 40;
+  verifyFormat("typedef enum {} EmptyEnum;");
+  verifyFormat("typedef enum { A, B, C } ShortEnum;");
+  verifyFormat("typedef enum {\n"
+   "  ZERO = 0,\n" 
+   "  ONE = 1,\n"
+   "  TWO = 2,\n"
+   "  THREE = 3\n"
+   "} LongEnum;",
+   Style);
+  Style.BreakBeforeBraces = FormatStyle::BS_Custom;
+  Style.BraceWrapping.AfterEnum = true;
+  verifyFormat("typedef enum {} EmptyEnum;");
+  verifyFormat("typedef enum { A, B, C } ShortEnum;");
+  verifyFormat("typedef enum\n"
+   "{\n"
+   "  ZERO = 0,\n" 
+   "  ONE = 1,\n"
+   "  TWO = 2,\n"
+   "  THREE = 3\n"
+   "} LongEnum;",
+   Style);
+}
+
 TEST_F(FormatTest, FormatsNSEnums) {
   verifyGoogleFormat("typedef NS_ENUM(NSInteger, SomeName) { AAA, BBB }");
   verifyGoogleFormat("typedef NS_ENUM(NSInteger, MyType) {\n"


Index: cfe/trunk/lib/Format/TokenAnnotator.cpp
===
--- cfe/trunk/lib/Format/TokenAnnotator.cpp
+++ cfe/trunk/lib/Format/TokenAnnotator.cpp
@@ -2647,6 +2647,7 @@
 return Right.HasUnescapedNewline;
   if (isAllmanBrace(Left) || isAllmanBrace(Right))
 return (Line.startsWith(tok::kw_enum) && Style.BraceWrapping.AfterEnum) ||
+   (Line.startsWith(tok::kw_typedef, tok::kw_enum) && Style.BraceWrapping.AfterEnum) ||
(Line.startsWith(tok::kw_class) && Style.BraceWrapping.AfterClass) ||
(Line.startsWith(tok::kw_struct) && Style.BraceWrapping.AfterStruct);
   if (Left.is(TT_ObjCBlockLBrace) && !Style.AllowShortBlocksOnASingleLine)
Index: cfe/trunk/unittests/Format/FormatTest.cpp
===
--- cfe/trunk/unittests/Format/FormatTest.cpp
+++ cfe/trunk/unittests/Format/FormatTest.cpp
@@ -1324,6 +1324,32 @@
   verifyFormat("enum X : std::uint32_t { A, B };");
 }
 
+TEST_F(FormatTest, FormatsTypedefEnum) {
+  FormatStyle Style = getLLVMStyle();
+  Style.ColumnLimit = 40;
+  verifyFormat("typedef enum {} EmptyEnum;");
+  verifyFormat("typedef enum { A, B, C } ShortEnum;");
+  verifyFormat("typedef enum {\n"
+   "  ZERO = 0,\n" 
+   "  ONE = 1,\n"
+   "  TWO = 2,\n"
+   "  THREE = 3\n"
+   "} LongEnum;",
+   Style);
+  Style.BreakBeforeBraces = FormatStyle::BS_Custom;
+  Style.BraceWrapping.AfterEnum = true;
+  verifyFormat("typedef enum {} EmptyEnum;");
+  verifyFormat("typedef enum { A, B, C } ShortEnum;");
+  verifyFormat("typedef enum\n"
+   "{\n"
+   "  ZERO = 0,\n" 
+   "  ONE = 1,\n"
+   "  TWO = 2,\n"
+   "  THREE = 3\n"
+   "} LongEnum;",
+   Style);
+}
+
 TEST_F(FormatTest, FormatsNSEnums) {
   verifyGoogleFormat("typedef NS_ENUM(NSInteger, SomeName) { AAA, BBB }");
   verifyGoogleFormat("typedef NS_ENUM(NSInteger, MyType) {\n"
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


r311998 - [clang-format] Fixed typedef enum brace wrapping

2017-08-29 Thread Krasimir Georgiev via cfe-commits
Author: krasimir
Date: Tue Aug 29 06:32:30 2017
New Revision: 311998

URL: http://llvm.org/viewvc/llvm-project?rev=311998=rev
Log:
[clang-format] Fixed typedef enum brace wrapping

Summary:
Bug: https://bugs.llvm.org/show_bug.cgi?id=34016 - **Typedef enum part**

**Problem:**

Clang format does not allow the flag **BraceWrapping.AfterEnum** control the 
case when our **enum** is preceded by **typedef** keyword (what is common in C 
language).

**Patch description:**

Added case to the **"AfterEnum"** flag when our enum does not start a line - is 
preceded by **typedef** keyword.

**After fix:**

**CONFIG:**
```
BreakBeforeBraces: Custom
BraceWrapping: {
AfterClass: true, AfterControlStatement: true, AfterEnum: true, AfterFunction: 
true, AfterNamespace: false, AfterStruct: true, AfterUnion: true, BeforeCatch: 
true, BeforeElse: true
}
```

**BEFORE:**
```
typedef enum
{
a,
b,
c
} SomeEnum;
```

**AFTER:**

```
typedef enum
{
a,
b,
c
} SomeEnum;
```

Contributed by @PriMee!

Reviewers: krasimir, djasper

Reviewed By: djasper

Subscribers: cfe-commits, klimek

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

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

Modified: cfe/trunk/lib/Format/TokenAnnotator.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Format/TokenAnnotator.cpp?rev=311998=311997=311998=diff
==
--- cfe/trunk/lib/Format/TokenAnnotator.cpp (original)
+++ cfe/trunk/lib/Format/TokenAnnotator.cpp Tue Aug 29 06:32:30 2017
@@ -2647,6 +2647,7 @@ bool TokenAnnotator::mustBreakBefore(con
 return Right.HasUnescapedNewline;
   if (isAllmanBrace(Left) || isAllmanBrace(Right))
 return (Line.startsWith(tok::kw_enum) && Style.BraceWrapping.AfterEnum) ||
+   (Line.startsWith(tok::kw_typedef, tok::kw_enum) && 
Style.BraceWrapping.AfterEnum) ||
(Line.startsWith(tok::kw_class) && Style.BraceWrapping.AfterClass) 
||
(Line.startsWith(tok::kw_struct) && 
Style.BraceWrapping.AfterStruct);
   if (Left.is(TT_ObjCBlockLBrace) && !Style.AllowShortBlocksOnASingleLine)

Modified: cfe/trunk/unittests/Format/FormatTest.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/unittests/Format/FormatTest.cpp?rev=311998=311997=311998=diff
==
--- cfe/trunk/unittests/Format/FormatTest.cpp (original)
+++ cfe/trunk/unittests/Format/FormatTest.cpp Tue Aug 29 06:32:30 2017
@@ -1324,6 +1324,32 @@ TEST_F(FormatTest, FormatsEnumTypes) {
   verifyFormat("enum X : std::uint32_t { A, B };");
 }
 
+TEST_F(FormatTest, FormatsTypedefEnum) {
+  FormatStyle Style = getLLVMStyle();
+  Style.ColumnLimit = 40;
+  verifyFormat("typedef enum {} EmptyEnum;");
+  verifyFormat("typedef enum { A, B, C } ShortEnum;");
+  verifyFormat("typedef enum {\n"
+   "  ZERO = 0,\n" 
+   "  ONE = 1,\n"
+   "  TWO = 2,\n"
+   "  THREE = 3\n"
+   "} LongEnum;",
+   Style);
+  Style.BreakBeforeBraces = FormatStyle::BS_Custom;
+  Style.BraceWrapping.AfterEnum = true;
+  verifyFormat("typedef enum {} EmptyEnum;");
+  verifyFormat("typedef enum { A, B, C } ShortEnum;");
+  verifyFormat("typedef enum\n"
+   "{\n"
+   "  ZERO = 0,\n" 
+   "  ONE = 1,\n"
+   "  TWO = 2,\n"
+   "  THREE = 3\n"
+   "} LongEnum;",
+   Style);
+}
+
 TEST_F(FormatTest, FormatsNSEnums) {
   verifyGoogleFormat("typedef NS_ENUM(NSInteger, SomeName) { AAA, BBB }");
   verifyGoogleFormat("typedef NS_ENUM(NSInteger, MyType) {\n"


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


[PATCH] D37132: [clang-format] Add support for C++17 structured bindings.

2017-08-29 Thread Marek Kurdej via Phabricator via cfe-commits
curdeius updated this revision to Diff 113079.
curdeius added a comment.

Extract method.


https://reviews.llvm.org/D37132

Files:
  lib/Format/FormatToken.h
  lib/Format/TokenAnnotator.cpp
  unittests/Format/FormatTest.cpp

Index: unittests/Format/FormatTest.cpp
===
--- unittests/Format/FormatTest.cpp
+++ unittests/Format/FormatTest.cpp
@@ -11217,6 +11217,31 @@
   EXPECT_EQ("auto c = u8'a';", format("auto c = u8'a';"));
 }
 
+TEST_F(FormatTest, StructuredBindings) {
+  // Structured bindings is a C++17 feature.
+  // all modes, including C++11, C++14 and C++17
+  verifyFormat("auto [a, b] = f();");
+  EXPECT_EQ("auto [a, b] = f();", format("auto[a, b] = f();"));
+  EXPECT_EQ("const auto [a, b] = f();", format("const   auto[a, b] = f();"));
+  EXPECT_EQ("auto const [a, b] = f();", format("auto  const[a, b] = f();"));
+  EXPECT_EQ("auto const volatile [a, b] = f();",
+format("auto  const   volatile[a, b] = f();"));
+  EXPECT_EQ("auto [a, b, c] = f();", format("auto   [  a  ,  b,c   ] = f();"));
+  EXPECT_EQ("auto & [a, b, c] = f();",
+format("auto   &[  a  ,  b,c   ] = f();"));
+  EXPECT_EQ("auto && [a, b, c] = f();",
+format("auto   &&[  a  ,  b,c   ] = f();"));
+  EXPECT_EQ("auto const & [a, b] = f();", format("auto  const&[a, b] = f();"));
+  EXPECT_EQ("auto const volatile && [a, b] = f();",
+format("auto  const  volatile  &&[a, b] = f();"));
+  EXPECT_EQ("auto && [a, b] = f();", format("auto  &&[a, b] = f();"));
+
+  format::FormatStyle Spaces = format::getLLVMStyle();
+  Spaces.SpacesInSquareBrackets = true;
+  verifyFormat("auto [ a, b ] = f();", Spaces);
+  verifyFormat("auto && [ a, b ] = f();", Spaces);
+}
+
 } // end namespace
 } // end namespace format
 } // end namespace clang
Index: lib/Format/TokenAnnotator.cpp
===
--- lib/Format/TokenAnnotator.cpp
+++ lib/Format/TokenAnnotator.cpp
@@ -310,6 +310,16 @@
 return false;
   }
 
+  bool isCppStructuredBinding(const FormatToken *Tok) {
+if (!Style.isCpp() || !Tok->is(tok::l_square))
+  return false;
+while (Tok && Tok->isOneOf(tok::kw_const, tok::kw_volatile, tok::amp,
+   tok::ampamp)) {
+  Tok = Tok->getPreviousNonComment();
+}
+return Tok && Tok->is(tok::kw_auto);
+  }
+
   bool parseSquare() {
 if (!CurrentToken)
   return false;
@@ -344,7 +354,9 @@
 
 unsigned BindingIncrease = 1;
 if (Left->is(TT_Unknown)) {
-  if (StartsObjCMethodExpr) {
+  if (isCppStructuredBinding(Left)) {
+Left->Type = TT_StructuredBindingLSquare;
+  } else if (StartsObjCMethodExpr) {
 Left->Type = TT_ObjCMethodExpr;
   } else if (Style.Language == FormatStyle::LK_JavaScript && Parent &&
  Contexts.back().ContextKind == tok::l_brace &&
@@ -2256,17 +2268,20 @@
   if (Left.is(tok::l_square))
 return (Left.is(TT_ArrayInitializerLSquare) &&
 Style.SpacesInContainerLiterals && Right.isNot(tok::r_square)) ||
-   (Left.is(TT_ArraySubscriptLSquare) && Style.SpacesInSquareBrackets &&
-Right.isNot(tok::r_square));
+   (Left.isOneOf(TT_ArraySubscriptLSquare,
+ TT_StructuredBindingLSquare) &&
+Style.SpacesInSquareBrackets && Right.isNot(tok::r_square));
   if (Right.is(tok::r_square))
 return Right.MatchingParen &&
((Style.SpacesInContainerLiterals &&
  Right.MatchingParen->is(TT_ArrayInitializerLSquare)) ||
 (Style.SpacesInSquareBrackets &&
- Right.MatchingParen->is(TT_ArraySubscriptLSquare)));
+ Right.MatchingParen->isOneOf(TT_ArraySubscriptLSquare,
+  TT_StructuredBindingLSquare)));
   if (Right.is(tok::l_square) &&
   !Right.isOneOf(TT_ObjCMethodExpr, TT_LambdaLSquare,
- TT_DesignatedInitializerLSquare) &&
+ TT_DesignatedInitializerLSquare,
+ TT_StructuredBindingLSquare) &&
   !Left.isOneOf(tok::numeric_constant, TT_DictLiteral))
 return false;
   if (Left.is(tok::l_brace) && Right.is(tok::r_brace))
Index: lib/Format/FormatToken.h
===
--- lib/Format/FormatToken.h
+++ lib/Format/FormatToken.h
@@ -84,6 +84,7 @@
   TYPE(RegexLiteral) \
   TYPE(SelectorName) \
   TYPE(StartOfName) \
+  TYPE(StructuredBindingLSquare) \
   TYPE(TemplateCloser) \
   TYPE(TemplateOpener) \
   TYPE(TemplateString) \
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D37005: [clang-diff] Initial implementation of patching

2017-08-29 Thread Johannes Altmanninger via Phabricator via cfe-commits
johannes added inline comments.



Comment at: include/clang/Tooling/ASTDiff/ASTDiff.h:73
 public:
+  /// Empty (invalid) SyntaxTree.
+  SyntaxTree();

arphaman wrote:
> Why do you need to create an empty tree? What about using llvm::Optional 
> instead?
ok, i use optional now instead in the unittest


https://reviews.llvm.org/D37005



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


[PATCH] D37005: [clang-diff] Initial implementation of patching

2017-08-29 Thread Johannes Altmanninger via Phabricator via cfe-commits
johannes updated this revision to Diff 113078.
johannes added a comment.

fixes


https://reviews.llvm.org/D37005

Files:
  include/clang/Tooling/ASTDiff/ASTDiff.h
  include/clang/Tooling/ASTDiff/ASTPatch.h
  lib/Tooling/ASTDiff/ASTDiff.cpp
  lib/Tooling/ASTDiff/ASTPatch.cpp
  lib/Tooling/ASTDiff/CMakeLists.txt
  test/Tooling/clang-diff-patch.test
  tools/clang-diff/CMakeLists.txt
  tools/clang-diff/ClangDiff.cpp
  unittests/Tooling/ASTDiffTest.cpp
  unittests/Tooling/CMakeLists.txt

Index: unittests/Tooling/CMakeLists.txt
===
--- unittests/Tooling/CMakeLists.txt
+++ unittests/Tooling/CMakeLists.txt
@@ -11,6 +11,7 @@
 endif()
 
 add_clang_unittest(ToolingTests
+  ASTDiffTest.cpp
   ASTSelectionTest.cpp
   CastExprTest.cpp
   CommentHandlerTest.cpp
@@ -43,4 +44,5 @@
   clangTooling
   clangToolingCore
   clangToolingRefactor
+  clangToolingASTDiff
   )
Index: unittests/Tooling/ASTDiffTest.cpp
===
--- /dev/null
+++ unittests/Tooling/ASTDiffTest.cpp
@@ -0,0 +1,85 @@
+//===- unittest/Tooling/ASTDiffTest.cpp ---===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===--===//
+
+#include "clang/Tooling/ASTDiff/ASTDiff.h"
+#include "clang/Tooling/ASTDiff/ASTPatch.h"
+#include "clang/Tooling/Tooling.h"
+#include "gtest/gtest.h"
+
+using namespace clang;
+using namespace tooling;
+
+static std::string patchResult(std::array Codes) {
+  llvm::Optional Trees[3];
+  std::unique_ptr ASTs[3];
+  for (int I = 0; I < 3; I++) {
+ASTs[I] = buildASTFromCode(Codes[I]);
+if (!ASTs[I]) {
+  llvm::errs() << "Failed to build AST from code:\n" << Codes[I] << "\n";
+  return "";
+}
+Trees[I].emplace(*ASTs[I]);
+  }
+
+  diff::ComparisonOptions Options;
+  std::string TargetDstCode;
+  llvm::raw_string_ostream OS(TargetDstCode);
+  if (!diff::patch(/*ModelSrc=*/*Trees[0], /*ModelDst=*/*Trees[1],
+   /*TargetSrc=*/*Trees[2], Options, OS))
+return "";
+  return OS.str();
+}
+
+// abstract the EXPECT_EQ call so that the code snippets align properly
+// use macros for this to make test failures have proper line numbers
+#define PATCH(Preamble, ModelSrc, ModelDst, Target, Expected)  \
+  EXPECT_EQ(patchResult({{std::string(Preamble) + ModelSrc,\
+  std::string(Preamble) + ModelDst,\
+  std::string(Preamble) + Target}}),   \
+std::string(Preamble) + Expected)
+
+TEST(ASTDiff, TestDeleteArguments) {
+  PATCH(R"(void printf(const char *, ...);)",
+R"(void foo(int x) { printf("%d", x, x); })",
+R"(void foo(int x) { printf("%d", x); })",
+R"(void foo(int x) { printf("different string %d", x, x); })",
+R"(void foo(int x) { printf("different string %d", x); })");
+
+  PATCH(R"(void foo(...);)",
+R"(void test1() { foo ( 1 + 1); })",
+R"(void test1() { foo ( ); })",
+R"(void test2() { foo ( 1 + 1 ); })",
+R"(void test2() { foo (  ); })");
+
+  PATCH(R"(void foo(...);)",
+R"(void test1() { foo (1, 2 + 2); })",
+R"(void test1() { foo (2 + 2); })",
+R"(void test2() { foo (/*L*/ 0 /*R*/ , 2 + 2); })",
+R"(void test2() { foo (/*L*/  2 + 2); })");
+
+  PATCH(R"(void foo(...);)",
+R"(void test1() { foo (1, 2); })",
+R"(void test1() { foo (1); })",
+R"(void test2() { foo (0, /*L*/ 0 /*R*/); })",
+R"(void test2() { foo (0 /*R*/); })");
+}
+
+TEST(ASTDiff, TestDeleteDecls) {
+  PATCH(R"()",
+R"()",
+R"()",
+R"()",
+R"()");
+
+  PATCH(R"()",
+R"(void foo(){})",
+R"()",
+R"(int x; void foo() {;;} int y;)",
+R"(int x;  int y;)");
+}
Index: tools/clang-diff/ClangDiff.cpp
===
--- tools/clang-diff/ClangDiff.cpp
+++ tools/clang-diff/ClangDiff.cpp
@@ -13,6 +13,7 @@
 //===--===//
 
 #include "clang/Tooling/ASTDiff/ASTDiff.h"
+#include "clang/Tooling/ASTDiff/ASTPatch.h"
 #include "clang/Tooling/CommonOptionsParser.h"
 #include "clang/Tooling/Tooling.h"
 #include "llvm/Support/CommandLine.h"
@@ -42,6 +43,12 @@
   cl::desc("Output a side-by-side diff in HTML."),
   cl::init(false), cl::cat(ClangDiffCategory));
 
+static cl::opt
+Patch("patch",
+  cl::desc("Try to apply the edit actions between the two input "
+   "files to the specified target."),
+  cl::desc(""), cl::cat(ClangDiffCategory));
+
 static cl::opt 

[PATCH] D37132: [clang-format] Add support for C++17 structured bindings.

2017-08-29 Thread Marek Kurdej via Phabricator via cfe-commits
curdeius updated this revision to Diff 113077.
curdeius added a comment.

Fix line endings again.


https://reviews.llvm.org/D37132

Files:
  lib/Format/FormatToken.h
  lib/Format/TokenAnnotator.cpp
  unittests/Format/FormatTest.cpp

Index: unittests/Format/FormatTest.cpp
===
--- unittests/Format/FormatTest.cpp
+++ unittests/Format/FormatTest.cpp
@@ -11217,6 +11217,31 @@
   EXPECT_EQ("auto c = u8'a';", format("auto c = u8'a';"));
 }
 
+TEST_F(FormatTest, StructuredBindings) {
+  // Structured bindings is a C++17 feature.
+  // all modes, including C++11, C++14 and C++17
+  verifyFormat("auto [a, b] = f();");
+  EXPECT_EQ("auto [a, b] = f();", format("auto[a, b] = f();"));
+  EXPECT_EQ("const auto [a, b] = f();", format("const   auto[a, b] = f();"));
+  EXPECT_EQ("auto const [a, b] = f();", format("auto  const[a, b] = f();"));
+  EXPECT_EQ("auto const volatile [a, b] = f();",
+format("auto  const   volatile[a, b] = f();"));
+  EXPECT_EQ("auto [a, b, c] = f();", format("auto   [  a  ,  b,c   ] = f();"));
+  EXPECT_EQ("auto & [a, b, c] = f();",
+format("auto   &[  a  ,  b,c   ] = f();"));
+  EXPECT_EQ("auto && [a, b, c] = f();",
+format("auto   &&[  a  ,  b,c   ] = f();"));
+  EXPECT_EQ("auto const & [a, b] = f();", format("auto  const&[a, b] = f();"));
+  EXPECT_EQ("auto const volatile && [a, b] = f();",
+format("auto  const  volatile  &&[a, b] = f();"));
+  EXPECT_EQ("auto && [a, b] = f();", format("auto  &&[a, b] = f();"));
+
+  format::FormatStyle Spaces = format::getLLVMStyle();
+  Spaces.SpacesInSquareBrackets = true;
+  verifyFormat("auto [ a, b ] = f();", Spaces);
+  verifyFormat("auto && [ a, b ] = f();", Spaces);
+}
+
 } // end namespace
 } // end namespace format
 } // end namespace clang
Index: lib/Format/TokenAnnotator.cpp
===
--- lib/Format/TokenAnnotator.cpp
+++ lib/Format/TokenAnnotator.cpp
@@ -47,7 +47,7 @@
 if (NonTemplateLess.count(CurrentToken->Previous))
   return false;
 
-const FormatToken& Previous = *CurrentToken->Previous;
+const FormatToken  = *CurrentToken->Previous;
 if (Previous.Previous) {
   if (Previous.Previous->Tok.isLiteral())
 return false;
@@ -152,11 +152,11 @@
   // export type X = (...);
   Contexts.back().IsExpression = false;
 } else if (Left->Previous &&
-(Left->Previous->isOneOf(tok::kw_static_assert, tok::kw_decltype,
- tok::kw_if, tok::kw_while, tok::l_paren,
- tok::comma) ||
- Left->Previous->endsSequence(tok::kw_constexpr, tok::kw_if) ||
- Left->Previous->is(TT_BinaryOperator))) {
+   (Left->Previous->isOneOf(tok::kw_static_assert, tok::kw_decltype,
+tok::kw_if, tok::kw_while, tok::l_paren,
+tok::comma) ||
+Left->Previous->endsSequence(tok::kw_constexpr, tok::kw_if) ||
+Left->Previous->is(TT_BinaryOperator))) {
   // static_assert, if and while usually contain expressions.
   Contexts.back().IsExpression = true;
 } else if (Style.Language == FormatStyle::LK_JavaScript && Left->Previous &&
@@ -325,8 +325,7 @@
 // In C++, this can happen either in array of templates (foo[10])
 // or when array is a nested template type (unique_ptr).
 bool CppArrayTemplates =
-Style.isCpp() && Parent &&
-Parent->is(TT_TemplateCloser) &&
+Style.isCpp() && Parent && Parent->is(TT_TemplateCloser) &&
 (Contexts.back().CanBeExpression || Contexts.back().IsExpression ||
  Contexts.back().InTemplateArgument);
 
@@ -342,9 +341,22 @@
  getBinOpPrecedence(Parent->Tok.getKind(), true, true) > prec::Unknown);
 bool ColonFound = false;
 
+FormatToken *PreviousNoneOfConstVolatileReference = Parent;
+while (PreviousNoneOfConstVolatileReference &&
+   PreviousNoneOfConstVolatileReference->isOneOf(
+   tok::kw_const, tok::kw_volatile, tok::amp, tok::ampamp))
+  PreviousNoneOfConstVolatileReference =
+  PreviousNoneOfConstVolatileReference->getPreviousNonComment();
+
+bool CppStructuredBindings =
+Style.isCpp() && PreviousNoneOfConstVolatileReference &&
+PreviousNoneOfConstVolatileReference->is(tok::kw_auto);
+
 unsigned BindingIncrease = 1;
 if (Left->is(TT_Unknown)) {
-  if (StartsObjCMethodExpr) {
+  if (CppStructuredBindings) {
+Left->Type = TT_StructuredBindingLSquare;
+  } else if (StartsObjCMethodExpr) {
 Left->Type = TT_ObjCMethodExpr;
   } else if (Style.Language == FormatStyle::LK_JavaScript && Parent &&
  Contexts.back().ContextKind == tok::l_brace &&
@@ -605,7 +617,8 @@
   break;
 case tok::kw_if:
 case tok::kw_while:
-  if (Tok->is(tok::kw_if) && 

[PATCH] D37231: Add half load and store builtins

2017-08-29 Thread Jan Vesely via Phabricator via cfe-commits
jvesely added inline comments.



Comment at: include/clang/Basic/Builtins.def:1427
+// OpenCL half load/store builtin
+BUILTIN(__builtin_store_half, "vdh*", "n")
+BUILTIN(__builtin_store_halff, "vfh*", "n")

Anastasia wrote:
> I think this should be a language builtin (see above) but perhaps we might 
> need to extend the language version here. Because I believe we only have 
> OpenCL v2.0 currently.
> 
> Also this should only be available if `cl_khr_fp16` is supported and enabled? 
> I think we are doing similar with some subgroups functions (e.g. 
> `get_kernel_sub_group_count_for_ndrange`) that are only supported by 
> `cl_khr_subgroup` but those have custom diagnostic though. May be we could 
> leave this check out since `half` is not available if `cl_khr_fp16` is not 
> enabled anyways.
This is specifically meant to be used when `cl_khr_fp16` is **not** available.
CLC allows using half as storage format and  half pointers without the 
extension,
vstore_half/vload_half are used to load/store half values. (CL1.2 CH 6.1.1.1)

These builtins are not necessary if `cl_khr_fp16` is available (we can use 
regular loads/stores).

I'll take stab at making these CLC only, but similarly to device specific 
builtins it looked useful beyond that, since these builtins provide access to 
half type storage.


Repository:
  rL LLVM

https://reviews.llvm.org/D37231



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


[PATCH] D37140: [clang-format] Fixed one-line if statement

2017-08-29 Thread Pawel Maciocha via Phabricator via cfe-commits
PriMee updated this revision to Diff 113074.
PriMee added a comment.

Unit tests added.


https://reviews.llvm.org/D37140

Files:
  lib/Format/UnwrappedLineFormatter.cpp
  unittests/Format/FormatTest.cpp

Index: unittests/Format/FormatTest.cpp
===
--- unittests/Format/FormatTest.cpp
+++ unittests/Format/FormatTest.cpp
@@ -486,9 +486,9 @@
"  f();\n"
"}",
AllowSimpleBracedStatements);
-  verifyFormat("if (true) {\n"
+  verifyFormat("if (true) {\n" 
"  f();\n"
-   "} else {\n"
+   "} else {\n" 
"  f();\n"
"}",
AllowSimpleBracedStatements);
@@ -498,7 +498,67 @@
"  f();\n"
"}",
AllowSimpleBracedStatements);
-  verifyFormat("for (;;) {\n"
+  verifyFormat("for (;;) {\n" 
+   "  f();\n"
+   "}",
+   AllowSimpleBracedStatements);
+
+  AllowSimpleBracedStatements.AllowShortIfStatementsOnASingleLine = true;
+  AllowSimpleBracedStatements.AllowShortLoopsOnASingleLine = true;
+  AllowSimpleBracedStatements.BreakBeforeBraces = FormatStyle::BS_Custom;
+  AllowSimpleBracedStatements.BraceWrapping.AfterControlStatement = true;
+
+  verifyFormat("if (true) {}", AllowSimpleBracedStatements);
+  verifyFormat("if constexpr (true) {}", AllowSimpleBracedStatements);
+  verifyFormat("while (true) {}", AllowSimpleBracedStatements);
+  verifyFormat("for (;;) {}", AllowSimpleBracedStatements);
+  verifyFormat("if (true) { f(); }", AllowSimpleBracedStatements);
+  verifyFormat("if constexpr (true) { f(); }", AllowSimpleBracedStatements);
+  verifyFormat("while (true) { f(); }", AllowSimpleBracedStatements);
+  verifyFormat("for (;;) { f(); }", AllowSimpleBracedStatements);
+  verifyFormat("if (true)\n" 
+   "{ //\n"
+   "  f();\n"
+   "}",
+   AllowSimpleBracedStatements);
+  verifyFormat("if (true)\n" 
+   "{\n"
+   "  f();\n"
+   "  f();\n"
+   "}",
+   AllowSimpleBracedStatements);
+  verifyFormat("if (true)\n"
+   "{\n"
+   "  f();\n"
+   "} else\n" 
+   "{\n"
+   "  f();\n"
+   "}",
+   AllowSimpleBracedStatements);
+
+  AllowSimpleBracedStatements.AllowShortIfStatementsOnASingleLine = false;
+  verifyFormat("if (true)\n"
+   "{\n"
+   "  f();\n"
+   "}",
+   AllowSimpleBracedStatements);
+  verifyFormat("if (true)\n" 
+   "{\n"
+   "  f();\n"
+   "} else\n" 
+   "{\n"
+   "  f();\n"
+   "}",
+   AllowSimpleBracedStatements);
+
+  AllowSimpleBracedStatements.AllowShortLoopsOnASingleLine = false;
+  verifyFormat("while (true)\n"
+   "{\n"
+   "  f();\n"
+   "}",
+   AllowSimpleBracedStatements);
+  verifyFormat("for (;;)\n" 
+   "{\n"
"  f();\n"
"}",
AllowSimpleBracedStatements);
Index: lib/Format/UnwrappedLineFormatter.cpp
===
--- lib/Format/UnwrappedLineFormatter.cpp
+++ lib/Format/UnwrappedLineFormatter.cpp
@@ -283,13 +283,28 @@
 TheLine->First != TheLine->Last) {
   return MergeShortFunctions ? tryMergeSimpleBlock(I, E, Limit) : 0;
 }
+if (TheLine->Last->is(tok::l_brace) &&
+TheLine->First != TheLine->Last &&
+TheLine->First->isOneOf(tok::kw_if, tok::kw_while, tok::kw_for)) { 
+  return Style.AllowShortBlocksOnASingleLine ? tryMergeSimpleBlock(I, E, Limit) : 0;
+}
+if (I[1]->First->is(tok::l_brace) && 
+TheLine->First->isOneOf(tok::kw_if, tok::kw_while, tok::kw_for)) { 
+  return Style.BraceWrapping.AfterControlStatement ? tryMergeSimpleBlock(I, E, Limit) : 0;
+}
+if (TheLine->First->is(tok::l_brace) &&
+   (TheLine->First == TheLine->Last) &&
+   (I != AnnotatedLines.begin()) &&
+   (I[-1]->First->isOneOf(tok::kw_if, tok::kw_while, tok::kw_for))) { 
+  return Style.AllowShortBlocksOnASingleLine ? tryMergeSimpleBlock(I-1, E, Limit) : 0;
+}
 if (TheLine->Last->is(tok::l_brace)) {
   return !Style.BraceWrapping.AfterFunction
  ? tryMergeSimpleBlock(I, E, Limit)
  : 0;
 }
 if (I[1]->First->is(TT_FunctionLBrace) &&
-Style.BraceWrapping.AfterFunction) {
+Style.BraceWrapping.AfterFunction) { 
   if (I[1]->Last->is(TT_LineComment))
 return 0;
 
@@ -426,7 +441,7 @@
   SmallVectorImpl::const_iterator E,
   unsigned Limit) {
 AnnotatedLine  = **I;
-
+
 // Don't merge ObjC @ keywords and methods.
 // FIXME: If an option to allow short exception handling 

[PATCH] D36998: [AST] Traverse templates in LexicallyOrderedRecursiveASTVisitor

2017-08-29 Thread Johannes Altmanninger via Phabricator via cfe-commits
johannes added a comment.

This is currently broken, if a user provides a TraverseClassTemplateDecl, then 
the same method in this class will not be called, I think I will add a flag 
(probably not user visible) in RecursiveASTVisitor.h to switch the order for 
templates


https://reviews.llvm.org/D36998



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


[PATCH] D37132: [clang-format] Add support for C++17 structured bindings.

2017-08-29 Thread Marek Kurdej via Phabricator via cfe-commits
curdeius updated this revision to Diff 113073.
curdeius added a comment.

Fix line endings.


https://reviews.llvm.org/D37132

Files:
  lib/Format/FormatToken.h
  lib/Format/TokenAnnotator.cpp
  unittests/Format/FormatTest.cpp

Index: unittests/Format/FormatTest.cpp
===
--- unittests/Format/FormatTest.cpp
+++ unittests/Format/FormatTest.cpp
@@ -30,11 +30,7 @@
 
 class FormatTest : public ::testing::Test {
 protected:
-  enum StatusCheck {
-SC_ExpectComplete,
-SC_ExpectIncomplete,
-SC_DoNotCheck
-  };
+  enum StatusCheck { SC_ExpectComplete, SC_ExpectIncomplete, SC_DoNotCheck };
 
   std::string format(llvm::StringRef Code,
  const FormatStyle  = getLLVMStyle(),
@@ -280,7 +276,8 @@
 format("namespace {\n"
"int i;\n"
"\n"
-   "}", LLVMWithNoNamespaceFix));
+   "}",
+   LLVMWithNoNamespaceFix));
   EXPECT_EQ("namespace {\n"
 "int i;\n"
 "}",
@@ -961,20 +958,26 @@
"#endif\n"
"}",
Style));
-  EXPECT_EQ("switch (a) {\n" "case 0:\n"
-"  return; // long long long long long long long long long long long long comment\n"
-"  // line\n" "}",
+  EXPECT_EQ("switch (a) {\n"
+"case 0:\n"
+"  return; // long long long long long long long long long long "
+"long long comment\n"
+"  // line\n"
+"}",
 format("switch (a) {\n"
-   "case 0: return; // long long long long long long long long long long long long comment line\n"
+   "case 0: return; // long long long long long long long long "
+   "long long long long comment line\n"
"}",
Style));
   EXPECT_EQ("switch (a) {\n"
 "case 0:\n"
-"  return; /* long long long long long long long long long long long long comment\n"
+"  return; /* long long long long long long long long long long "
+"long long comment\n"
 " line */\n"
 "}",
 format("switch (a) {\n"
-   "case 0: return; /* long long long long long long long long long long long long comment line */\n"
+   "case 0: return; /* long long long long long long long long "
+   "long long long long comment line */\n"
"}",
Style));
   verifyFormat("switch (a) {\n"
@@ -1395,8 +1398,7 @@
   // This code is more common than we thought; if we
   // layout this correctly the semicolon will go into
   // its own line, which is undesirable.
-  verifyFormat("namespace {};",
-   LLVMWithNoNamespaceFix);
+  verifyFormat("namespace {};", LLVMWithNoNamespaceFix);
   verifyFormat("namespace {\n"
"class A {};\n"
"};",
@@ -1465,8 +1467,8 @@
   Style.CompactNamespaces = true;
 
   verifyFormat("namespace A { namespace B {\n"
-			   "}} // namespace A::B",
-			   Style);
+   "}} // namespace A::B",
+   Style);
 
   EXPECT_EQ("namespace out { namespace in {\n"
 "}} // namespace out::in",
@@ -2332,7 +2334,8 @@
"\\\n"
"  public: \\\n"
"void baz(); \\\n"
-   "  };", DontAlign));
+   "  };",
+   DontAlign));
 }
 
 TEST_F(FormatTest, CalculateSpaceOnConsecutiveLinesInMacro) {
@@ -2614,16 +2617,19 @@
   Style.MacroBlockEnd = "^[A-Z_]+_END$";
   verifyFormat("FOO_BEGIN\n"
"  FOO_ENTRY\n"
-   "FOO_END", Style);
+   "FOO_END",
+   Style);
   verifyFormat("FOO_BEGIN\n"
"  NESTED_FOO_BEGIN\n"
"NESTED_FOO_ENTRY\n"
"  NESTED_FOO_END\n"
-   "FOO_END", Style);
+   "FOO_END",
+   Style);
   verifyFormat("FOO_BEGIN(Foo, Bar)\n"
"  int x;\n"
"  x = 1;\n"
-   "FOO_END(Baz)", Style);
+   "FOO_END(Baz)",
+   Style);
 }
 
 //===--===//
@@ -3101,22 +3107,22 @@
   verifyFormat(
   "SomeClass::Constructor() :\n"
   "a(aa), aaa() {}",
-	  Style);
+  Style);
 
   verifyFormat(
   "SomeClass::Constructor() :\n"
   "a(aa), a(aa),\n"
   "a(aa) {}",
-	  Style);
+  Style);
   verifyFormat(
   "SomeClass::Constructor() :\n"
   "aa(aa),\n"
   "aaa() {}",
-	  Style);
+  Style);
   verifyFormat("Constructor(aa 

[PATCH] D37143: [clang-format] Fixed typedef enum brace wrapping

2017-08-29 Thread Pawel Maciocha via Phabricator via cfe-commits
PriMee added a comment.

I am glad to hear that. Would be great if someone could commit it. Thank You :)


https://reviews.llvm.org/D37143



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


[PATCH] D36410: [OpenCL] Handle taking address of block captures

2017-08-29 Thread Alexey Bader via Phabricator via cfe-commits
bader added a comment.

In https://reviews.llvm.org/D36410#855282, @Anastasia wrote:

> Ok, I will update it to be implicitly generic then. Just to be sure, @bader 
> do you agree on this too?




> An alternative approached could be (in case we want to allow this code) to 
> **assume captures are located in the generic AS implicitly**. However, in 
> this case programmers should be advised that erroneous AS casts can occur 
> further that can't be diagnosed by the frontend (i.e. if capture address is 
> used further in the operations of a different address space to where the 
> captures physical location is).

I don't have a strong opinion on this topic, but I'm worried about relying on 
implicit assumptions, which might make code less portable.

How the alternative approach is this suppose to work for enqueue_kernel? Do we 
assume that the captured variables passed by generic pointer and compiler will 
assign the correct address space based on the explicit casts in the block?
There are some restrictions on kernel parameters: 6.9.a. Arguments to kernel 
functions declared in a program that are pointers must be declared with the 
global, constant or local qualifier.

> I feel forbidding user taking address of captured variable is too restrictive 
> and make blocks less useful.

I have no information how widely blocks are used by the OpenCL community and 
how important this feature is.


https://reviews.llvm.org/D36410



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


[PATCH] D37005: [clang-diff] Initial implementation of patching

2017-08-29 Thread Alex Lorenz via Phabricator via cfe-commits
arphaman added inline comments.



Comment at: include/clang/Tooling/ASTDiff/ASTDiff.h:73
 public:
+  /// Empty (invalid) SyntaxTree.
+  SyntaxTree();

Why do you need to create an empty tree? What about using llvm::Optional 
instead?



Comment at: include/clang/Tooling/ASTDiff/ASTDiff.h:82
+  SyntaxTree(SyntaxTree &);
+  SyntaxTree =(SyntaxTree &);
+  explicit SyntaxTree(const SyntaxTree );

It's fine to have = default in the header


https://reviews.llvm.org/D37005



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


[PATCH] D37005: [clang-diff] Initial implementation of patching

2017-08-29 Thread Alex Lorenz via Phabricator via cfe-commits
arphaman added inline comments.



Comment at: include/clang/Tooling/ASTDiff/ASTPatch.h:1
+//===- ASTDiff.h - Structural patching based on ASTDiff ---*- C++ -*- 
-===//
+//

Please update the file name in the comment



Comment at: lib/Tooling/ASTDiff/ASTDiff.cpp:656
+  if (N.ASTNode.get())
+Range = TemplateArgumentLocations.at( - [0]);
+  else {

You might as well return early here and avoid else entirely 


https://reviews.llvm.org/D37005



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


[PATCH] D37200: [AST] Traverse CXXOperatorCallExpr in LexicallyOrderedRecursiveASTVisitor

2017-08-29 Thread Alex Lorenz via Phabricator via cfe-commits
arphaman accepted this revision.
arphaman added a comment.
This revision is now accepted and ready to land.

Lgtm with two requests below




Comment at: include/clang/AST/RecursiveASTVisitor.h:354
+protected:
+  bool TraverseStmtBase(Stmt *S, DataRecursionQueue *Queue) {
+return TRAVERSE_STMT_BASE(Stmt, Stmt, S, Queue);

I don't think you need this function now 



Comment at: include/clang/AST/RecursiveASTVisitor.h:2089
   }
-
 DEF_TRAVERSE_STMT(GCCAsmStmt, {

Please avoid deleting this line


https://reviews.llvm.org/D37200



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


[PATCH] D37136: [clang-format] Do not format likely xml

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

Just a few minor comments, otherwise looks good.




Comment at: lib/Format/Format.cpp:1542
 
+bool likelyXml(StringRef Code) {
+  return Code.ltrim().startswith("<");

Rename to isLikelyXml.



Comment at: lib/Format/Format.cpp:1552
 return Replaces;
-  if (Style.Language == FormatStyle::LanguageKind::LK_JavaScript &&
-  isMpegTS(Code))
+  if (likelyXml(Code) ||
+  (Style.Language == FormatStyle::LanguageKind::LK_JavaScript &&

Just add a separate if statement. Or merge with previous one, but I think three 
separate if statements is actually easiest to read.



Comment at: lib/Format/Format.cpp:1902
 return tooling::Replacements();
-  if (Expanded.Language == FormatStyle::LK_JavaScript && isMpegTS(Code))
+  if (likelyXml(Code) ||
+  (Expanded.Language == FormatStyle::LK_JavaScript && isMpegTS(Code)))

Same here.


https://reviews.llvm.org/D37136



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


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

2017-08-29 Thread Daniel Kolozsvari via Phabricator via cfe-commits
koldaniel updated this revision to Diff 113065.
koldaniel added a comment.

Updated checker name, minor modifications


https://reviews.llvm.org/D35068

Files:
  lib/StaticAnalyzer/Checkers/CheckSecuritySyntaxOnly.cpp


Index: lib/StaticAnalyzer/Checkers/CheckSecuritySyntaxOnly.cpp
===
--- lib/StaticAnalyzer/Checkers/CheckSecuritySyntaxOnly.cpp
+++ lib/StaticAnalyzer/Checkers/CheckSecuritySyntaxOnly.cpp
@@ -100,7 +100,7 @@
   void checkCall_mkstemp(const CallExpr *CE, const FunctionDecl *FD);
   void checkCall_strcpy(const CallExpr *CE, const FunctionDecl *FD);
   void checkCall_strcat(const CallExpr *CE, const FunctionDecl *FD);
-  void checkUnsafeBufferHandling(const CallExpr *CE, const FunctionDecl *FD);
+  void checkDeprecatedOrUnsafeBufferHandling(const CallExpr *CE, const 
FunctionDecl *FD);
   void checkDeprecatedBufferHandling(const CallExpr *CE, const FunctionDecl 
*FD);
   void checkCall_rand(const CallExpr *CE, const FunctionDecl *FD);
   void checkCall_random(const CallExpr *CE, const FunctionDecl *FD);
@@ -144,20 +144,20 @@
 .Case("mkstemps", ::checkCall_mkstemp)
 .Cases("strcpy", "__strcpy_chk", ::checkCall_strcpy)
 .Cases("strcat", "__strcat_chk", ::checkCall_strcat)
-.Case("sprintf", ::checkUnsafeBufferHandling)
-.Case("vsprintf", ::checkUnsafeBufferHandling)
-.Case("scanf", ::checkUnsafeBufferHandling)
-.Case("wscanf", ::checkUnsafeBufferHandling)
-.Case("fscanf", ::checkUnsafeBufferHandling)
-.Case("fwscanf", ::checkUnsafeBufferHandling)
-.Case("vscanf", ::checkUnsafeBufferHandling)
-.Case("vwscanf", ::checkUnsafeBufferHandling)
-.Case("vfscanf", ::checkUnsafeBufferHandling)
-.Case("vfwscanf", ::checkUnsafeBufferHandling)
-.Case("sscanf", ::checkUnsafeBufferHandling)
-.Case("swscanf", ::checkUnsafeBufferHandling)
-.Case("vsscanf", ::checkUnsafeBufferHandling)
-.Case("vswscanf", ::checkUnsafeBufferHandling)
+.Case("sprintf", ::checkDeprecatedOrUnsafeBufferHandling)
+.Case("vsprintf", ::checkDeprecatedOrUnsafeBufferHandling)
+.Case("scanf", ::checkDeprecatedOrUnsafeBufferHandling)
+.Case("wscanf", ::checkDeprecatedOrUnsafeBufferHandling)
+.Case("fscanf", ::checkDeprecatedOrUnsafeBufferHandling)
+.Case("fwscanf", ::checkDeprecatedOrUnsafeBufferHandling)
+.Case("vscanf", ::checkDeprecatedOrUnsafeBufferHandling)
+.Case("vwscanf", ::checkDeprecatedOrUnsafeBufferHandling)
+.Case("vfscanf", ::checkDeprecatedOrUnsafeBufferHandling)
+.Case("vfwscanf", ::checkDeprecatedOrUnsafeBufferHandling)
+.Case("sscanf", ::checkDeprecatedOrUnsafeBufferHandling)
+.Case("swscanf", ::checkDeprecatedOrUnsafeBufferHandling)
+.Case("vsscanf", ::checkDeprecatedOrUnsafeBufferHandling)
+.Case("vswscanf", ::checkDeprecatedOrUnsafeBufferHandling)
 .Case("swprintf", ::checkDeprecatedBufferHandling)
 .Case("snprintf", ::checkDeprecatedBufferHandling)
 .Case("vswprintf", ::checkDeprecatedBufferHandling)
@@ -604,7 +604,7 @@
   llvm::raw_svector_ostream out2(buf2);
   out1 << "Potential insecure memory buffer bounds restriction in call '"
<< Name << "'";
-  out2 << "Using '" << Name << "' is depracated as it does not "
+  out2 << "Using '" << Name << "' is deprecated as it does not "
  "provide bounding of the memory buffer or security "
  "checks introduced in the C11 standard. Replace "
  "with analogous functions introduced in C11 standard that 
"
@@ -619,6 +619,7 @@
  out2.str(),
  CELoc, CE->getCallee()->getSourceRange());
 }
+
 
//===--===//
 // Check: Use of 'sprintf', 'vsprintf', 'scanf', 'wscanf', 'fscanf',
 //'fwscanf', 'vscanf', 'vwscanf', 'vfscanf', 'vfwscanf', 'sscanf',
@@ -628,8 +629,7 @@
 // CWE-119: Improper Restriction of Operations within
 // the Bounds of a Memory Buffer
 
//===--===//
-
-void WalkAST::checkUnsafeBufferHandling(const CallExpr *CE, const FunctionDecl 
*FD) { //TODO:TESTS
+void WalkAST::checkDeprecatedOrUnsafeBufferHandling(const CallExpr *CE, const 
FunctionDecl *FD) {
   if (!filter.check_UnsafeBufferHandling)
 return;
   checkDeprecatedBufferHandling(CE, FD);


Index: lib/StaticAnalyzer/Checkers/CheckSecuritySyntaxOnly.cpp
===
--- lib/StaticAnalyzer/Checkers/CheckSecuritySyntaxOnly.cpp
+++ lib/StaticAnalyzer/Checkers/CheckSecuritySyntaxOnly.cpp
@@ -100,7 +100,7 @@
   void checkCall_mkstemp(const CallExpr *CE, const FunctionDecl *FD);
   void checkCall_strcpy(const CallExpr *CE, const FunctionDecl *FD);
   void checkCall_strcat(const CallExpr *CE, const FunctionDecl *FD);
-  void checkUnsafeBufferHandling(const CallExpr *CE, const FunctionDecl *FD);
+  void 

  1   2   >