[PATCH] D53738: [Fixed Point Arithmetic] Fixed Point Addition

2018-10-29 Thread Bevin Hansson via Phabricator via cfe-commits
ebevhan added a comment.

In https://reviews.llvm.org/D53738#1278078, @rjmccall wrote:

> I don't think we should add *types* just for this, but if you need to make a 
> different kind of `BinaryOperator` that represents that the semantics aren't 
> quite the same (the same way that the compound assignments have their own 
> subclass), that seems natural to me.


I don't know if adding a new operator kind was what I had in mind. The operator 
hasn't changed, it's still a normal binary operator. Compound assignments are 
their own operator with its own syntax; it doesn't really strike me as the same 
thing.

The important difference would be that we separate the semantics of performing 
the conversion and the operation. I understand that adding a new type could be 
a bit more involved than baking the conversion into the operator, but I really 
do not enjoy seeing so much implicit, implementation-specific logic 
encapsulated in the same AST element. Anyone who wants to look at 
BinaryOperators with fixed-point types will need to know all of the details of 
how the finding the common type and conversion is done, rather than simply "it 
does an addition".


Repository:
  rC Clang

https://reviews.llvm.org/D53738



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


[PATCH] D33672: [analyzer] INT50-CPP. Do not cast to an out-of-range enumeration checker

2018-10-29 Thread Umann Kristóf via Phabricator via cfe-commits
Szelethus added a comment.

I think is good to go! Please wait on @xazax.hun or @NoQ to have the final say 
(it's been a while since this revision was accepted by them), but for a 
work-in-progress alpha checker, I like what I'm seeing.




Comment at: lib/StaticAnalyzer/Checkers/EnumCastOutOfRangeChecker.cpp:19
+//   of casting an integer value that is out of range
+//===--===//
+

ZaMaZaN4iK wrote:
> aaron.ballman wrote:
> > If this check is intended to conform to CERT's INT50-CPP rule, you should 
> > put a link to the wiki entry for it here as well.
> Which wiki entry do you mean?
Maybe this one? 
https://wiki.sei.cmu.edu/confluence/display/cplusplus/INT50-CPP.+Do+not+cast+to+an+out-of-range+enumeration+value



Comment at: lib/StaticAnalyzer/Checkers/EnumCastOutOfRangeChecker.cpp:36
+  const ProgramStateRef PS;
+  SValBuilder &SVB;
+

You can acquire `SValBuilder` from `ProgramState`:
`PS->getStateManager()->getSvalBuilder()`



Comment at: lib/StaticAnalyzer/Checkers/EnumCastOutOfRangeChecker.cpp:66
+
+typedef typename llvm::SmallVector EnumValueVector;
+

Prefer `using`.



https://reviews.llvm.org/D33672



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


[PATCH] D53704: [ASTImporter] Import overrides before importing the rest of the chain

2018-10-29 Thread Gabor Marton via Phabricator via cfe-commits
martong added a comment.

Hi Aleksei,

Thanks for the review. Yes, we encountered the issue during the analysis of 
Xerces.


Repository:
  rC Clang

https://reviews.llvm.org/D53704



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


[PATCH] D53654: [clang] Improve ctor initializer completions.

2018-10-29 Thread Ilya Biryukov via Phabricator via cfe-commits
ilya-biryukov added inline comments.



Comment at: include/clang/Sema/CodeCompleteConsumer.h:767
+  /// When Kind == RK_Declaration and a FieldDecl has been passed as
+  /// Declaration, this will hold the identifiers name. To be used later on 
when
+  /// generating constructors for the variable.

NIT: does "identifiers name" refer to a field name? Maybe use "field name" 
directly to avoid possibly confusion.



Comment at: lib/Sema/SemaCodeComplete.cpp:3027
Ctx, Policy);
-AddTypedNameChunk(Ctx, Policy, ND, Result);
+AddTypedNameChunk(Ctx, Policy, ND, Result, PreferredTypedName);
 Result.AddChunk(CodeCompletionString::CK_LeftParen);

Maybe directly set the name here whenever PreferredTypedName is set and avoid 
changing the AddTypedNameChunk function?
This would keep the `AddTypedNameChunk` simpler and `PreferredTypedName` would 
simply become an overriden name that the code completion string should use 
instead of the declaration name. 
I.e.
```
if (PreferredTypedName)
  
Result.AddTypedTextChunk(Result.getAllocator().CopyString(PreferredTypedName));
else
  AddTypedNameChunk(Ctx, Policy, ...);
```
 



Comment at: lib/Sema/SemaCodeComplete.cpp:5192
+const CXXRecordDecl *RD = Field->getType()->getAsCXXRecordDecl();
+if (!RD) {
+  Builder.AddTypedTextChunk(Builder.getAllocator().CopyString(FieldName));

Should we also have fallbacks for bases in addition to fields? They may also 
have non-class types.
Could we also add a test? 
Should pop up in completions of dependent bases, e.g.
```
template 
struct Y : T {};

template 
struct X : std::vector {}; // referring to an explicit template, however 
still dependent.
```




Comment at: lib/Sema/SemaCodeComplete.cpp:5193
+if (!RD) {
+  Builder.AddTypedTextChunk(Builder.getAllocator().CopyString(FieldName));
+  Builder.AddChunk(CodeCompletionString::CK_LeftParen);

Maybe add a comment that this is a fallback?



Comment at: test/CodeCompletion/ordinary-name-cxx11.cpp:65
   // CHECK-CC1: COMPLETION: X : X
+  // CHECK-CC1-NEXT: COMPLETION: Pattern : X(<#X#>)
   // CHECK-CC1-NEXT: COMPLETION: y : [#int#]y

This completion is outside constructor initializers.
Why behavior change for these completions too?


Repository:
  rC Clang

https://reviews.llvm.org/D53654



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


[PATCH] D51340: Add /Zc:DllexportInlines option to clang-cl

2018-10-29 Thread Takuto Ikuta via Phabricator via cfe-commits
takuto.ikuta added inline comments.



Comment at: clang/lib/AST/ASTContext.cpp:9552
+// overwrite linkage of explicit template instantiation
+// definition/declaration.
+return GVA_DiscardableODR;

hans wrote:
> Can you give an example for why this is needed?
Sorry, this change does not need. Removed.



Comment at: clang/lib/Sema/SemaDeclCXX.cpp:5719
+  TSK != TSK_ExplicitInstantiationDeclaration &&
+  TSK != TSK_ExplicitInstantiationDefinition) {
+if (ClassExported) {

takuto.ikuta wrote:
> takuto.ikuta wrote:
> > hans wrote:
> > > takuto.ikuta wrote:
> > > > hans wrote:
> > > > > I still don't understand why we need these checks for template 
> > > > > instantiations. Why does it matter whether the functions get inlined 
> > > > > or not?
> > > > When function of dllimported class is not inlined, such funtion needs 
> > > > to be dllexported from implementation library.
> > > > 
> > > > c.h
> > > > ```
> > > > template
> > > > class EXPORT C {
> > > >  public:
> > > >   void f() {}
> > > > };
> > > > ```
> > > > 
> > > > cuser.cc
> > > > ```
> > > > #include "c.h"
> > > > 
> > > > void cuser() {
> > > >   C c;
> > > >   c.f();  // This function may not be inlined when EXPORT is 
> > > > __declspec(dllimport), so link may fail.
> > > > }
> > > > ```
> > > > 
> > > > When cuser.cc and c.h are built to different library, cuser.cc needs to 
> > > > be able to see dllexported C::f() when C::f() is not inlined.
> > > > This is my understanding.
> > > Your example doesn't use explicit instantiation definition or 
> > > declaration, so doesn't apply here I think.
> > > 
> > > As long as the dllexport and dllimport attributes matches it's fine. It 
> > > doesn't matter whether the function gets inlined or not, the only thing 
> > > that matters is that if it's marked dllimport on the "consumer side", it 
> > > must be dllexport when building the dll.
> > Hmm, I changed the linkage for functions having DLLExport/ImportStaticLocal 
> > Attr.
> > 
> I changed linkage in ASTContext so that inline function is emitted when it is 
> necessary when we use fno-dllexport-inlines.
I revived explicit template instantiation check. 
Found that this is necessary.

For explicit template instantiation, inheriting dll attribute from function for 
local static var is run before inheriting dll attribute from class for member 
functions. So I cannot detect local static var of inline function after class 
level dll attribute processing for explicit template instantiation.



https://reviews.llvm.org/D51340



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


[PATCH] D51340: Add /Zc:DllexportInlines option to clang-cl

2018-10-29 Thread Takuto Ikuta via Phabricator via cfe-commits
takuto.ikuta updated this revision to Diff 171466.
takuto.ikuta marked an inline comment as done.
takuto.ikuta added a comment.

Added explanation comment for added attributes and rebased


https://reviews.llvm.org/D51340

Files:
  clang/include/clang/Basic/Attr.td
  clang/include/clang/Basic/LangOptions.h
  clang/include/clang/Driver/CC1Options.td
  clang/include/clang/Driver/CLCompatOptions.td
  clang/lib/Driver/ToolChains/Clang.cpp
  clang/lib/Frontend/CompilerInvocation.cpp
  clang/lib/Sema/SemaDecl.cpp
  clang/lib/Sema/SemaDeclCXX.cpp
  clang/test/CodeGenCXX/dllexport-no-dllexport-inlines.cpp

Index: clang/test/CodeGenCXX/dllexport-no-dllexport-inlines.cpp
===
--- /dev/null
+++ clang/test/CodeGenCXX/dllexport-no-dllexport-inlines.cpp
@@ -0,0 +1,181 @@
+// RUN: %clang_cc1 %s -fms-extensions -triple x86_64-windows-msvc   \
+// RUN: -fno-dllexport-inlines -emit-llvm -O0 -o - |\
+// RUN: FileCheck --check-prefix=DEFAULT --check-prefix=NOINLINE %s
+
+// RUN: %clang_cc1 %s -fms-extensions -triple x86_64-windows-msvc   \
+// RUN: -emit-llvm -O0 -o - |   \
+// RUN: FileCheck --check-prefix=DEFAULT --check-prefix=INLINE %s
+
+// Function
+
+// DEFAULT-DAG: define dso_local dllexport void @"?NormalFunction@@YAXXZ"()
+void __declspec(dllexport) NormalFunction() {}
+
+
+// DEFAULT-DAG: define weak_odr dso_local dllexport void @"?AlwaysInlineFunction@@YAXXZ"
+__forceinline void __declspec(dllexport) AlwaysInlineFunction() {}
+
+// DEFAULT-DAG: @"?static_variable@?1??AlwaysInlineWithStaticVariableExported@@YAHXZ@4HA" = weak_odr dso_local dllexport global i32 0, comdat, align 4
+__forceinline int __declspec(dllexport) AlwaysInlineWithStaticVariableExported() {
+  static int static_variable = 0;
+  ++static_variable;
+  return static_variable;
+}
+
+// DEFAULT-DAG: @"?static_variable@?1??AlwaysInlineWithStaticVariableImported@@YAHXZ@4HA" = available_externally dllimport global i32 0, align 4
+__forceinline int __declspec(dllimport) AlwaysInlineWithStaticVariableImported() {
+  static int static_variable = 0;
+  ++static_variable;
+  return static_variable;
+}
+
+int ImportedFunctionUser() {
+  return AlwaysInlineWithStaticVariableImported();
+}
+
+// Class member function
+
+// check for local static variables
+// NOINLINE-DAG: @"?static_variable@?1??InclassDefFuncWithStaticVariable@NoTemplateExportedClass@@QEAAHXZ@4HA" = weak_odr dso_local dllexport global i32 0, comdat, align 4
+
+// INLINE-DAG: @"?static_variable@?1??InclassDefFuncWithStaticVariable@NoTemplateExportedClass@@QEAAHXZ@4HA" = weak_odr dso_local dllexport global i32 0, comdat, align 4
+
+// NOINLINE-DAG: @"?static_variable@?1??InClassDefFuncWithStaticVariable@ImportedClass@@QEAAHXZ@4HA" = available_externally dllimport global i32 0, align 4
+
+class __declspec(dllexport) NoTemplateExportedClass {
+ public:
+  // DEFAULT-NOT: NoTemplateExportedClass@NoTemplateExportedClass@@
+  NoTemplateExportedClass() = default;
+
+  // NOINLINE-NOT: InclassDefFunc@NoTemplateExportedClass
+  // INLINE-DAG: define weak_odr dso_local dllexport void @"?InclassDefFunc@NoTemplateExportedClass@@
+  void InclassDefFunc() {}
+
+  int f();
+
+  // DEFAULT-DAG: define weak_odr dso_local dllexport i32 @"?InclassDefFuncWithStaticVariable@NoTemplateExportedClass@@QEAAHXZ"
+  int InclassDefFuncWithStaticVariable() {
+static int static_variable = 0;
+++static_variable;
+return static_variable;
+  }
+
+  // DEFAULT-DAG: define weak_odr dso_local dllexport i32 @"?InclassDefFunctWithLambdaStaticVariable@NoTemplateExportedClass@@QEAAHXZ"
+  int InclassDefFunctWithLambdaStaticVariable() {
+return ([]() { static int static_x; return ++static_x; })();
+  }
+
+  // DEFAULT-NOT: InlineOutclassDefFuncWihtoutDefinition
+  __forceinline void InlineOutclassDefFuncWihtoutDefinition();
+
+  // DEFAULT-NOT: InlineOutclassDefFunc@NoTemplateExportedClass@@
+  __forceinline void InlineOutclassDefFunc();
+
+  // DEFAULT-NOT: InlineOutclassDefFuncWithStaticVariable@NoTemplateExportedClass@@
+  __forceinline int InlineOutclassDefFuncWithStaticVariable();
+
+  // DEFAULT-DAG: define dso_local dllexport void @"?OutclassDefFunc@NoTemplateExportedClass@@QEAAXXZ"
+  void OutclassDefFunc();
+};
+
+void NoTemplateExportedClass::OutclassDefFunc() {}
+
+__forceinline void NoTemplateExportedClass::InlineOutclassDefFunc() {}
+
+__forceinline int NoTemplateExportedClass::InlineOutclassDefFuncWithStaticVariable() {
+  static int static_variable = 0;
+  return ++static_variable;
+}
+
+void __declspec(dllexport) NoTemplateExportedClassUser() {
+  NoTemplateExportedClass a;
+  a.InlineOutclassDefFunc();
+}
+
+template
+class __declspec(dllexport) TemplateExportedClass {
+  void InclassDefFunc() {}
+  void OutclassDefFunc();
+
+  T templateValue;
+};
+
+// DEFAULT-NOT: define dso_local dllexport void @"?OutclassDefFunc@NoTemplateExportedClass@@
+template void Template

[PATCH] D53433: [clangd] auto-index stores symbols per-file instead of per-TU.

2018-10-29 Thread Eric Liu via Phabricator via cfe-commits
ioeric updated this revision to Diff 171467.
ioeric added a comment.

- minor cleanup and a friendly ping.


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D53433

Files:
  clangd/index/Background.cpp
  clangd/index/Background.h
  clangd/index/FileIndex.cpp
  clangd/index/FileIndex.h
  clangd/index/SymbolCollector.cpp
  clangd/index/SymbolCollector.h
  unittests/clangd/BackgroundIndexTests.cpp
  unittests/clangd/FileIndexTests.cpp
  unittests/clangd/SyncAPI.cpp
  unittests/clangd/SyncAPI.h

Index: unittests/clangd/SyncAPI.h
===
--- unittests/clangd/SyncAPI.h
+++ unittests/clangd/SyncAPI.h
@@ -52,6 +52,7 @@
 
 SymbolSlab runFuzzyFind(const SymbolIndex &Index, StringRef Query);
 SymbolSlab runFuzzyFind(const SymbolIndex &Index, const FuzzyFindRequest &Req);
+RefSlab getRefs(const SymbolIndex &Index, SymbolID ID);
 
 } // namespace clangd
 } // namespace clang
Index: unittests/clangd/SyncAPI.cpp
===
--- unittests/clangd/SyncAPI.cpp
+++ unittests/clangd/SyncAPI.cpp
@@ -8,6 +8,7 @@
 //===--===//
 
 #include "SyncAPI.h"
+#include "index/Index.h"
 
 using namespace llvm;
 namespace clang {
@@ -138,5 +139,14 @@
   return std::move(Builder).build();
 }
 
+RefSlab getRefs(const SymbolIndex &Index, SymbolID ID) {
+  RefsRequest Req;
+  Req.IDs = {ID};
+  RefSlab::Builder Slab;
+  Index.refs(Req, [&](const Ref &S) { Slab.insert(ID, S); });
+  return std::move(Slab).build();
+}
+
+
 } // namespace clangd
 } // namespace clang
Index: unittests/clangd/FileIndexTests.cpp
===
--- unittests/clangd/FileIndexTests.cpp
+++ unittests/clangd/FileIndexTests.cpp
@@ -14,6 +14,7 @@
 #include "TestFS.h"
 #include "TestTU.h"
 #include "index/FileIndex.h"
+#include "index/Index.h"
 #include "clang/Frontend/CompilerInvocation.h"
 #include "clang/Frontend/PCHContainerOperations.h"
 #include "clang/Frontend/Utils.h"
@@ -39,6 +40,7 @@
 }
 MATCHER_P(FileURI, F, "") { return arg.Location.FileURI == F; }
 MATCHER_P(DeclURI, U, "") { return arg.CanonicalDeclaration.FileURI == U; }
+MATCHER_P(DefURI, U, "") { return arg.Definition.FileURI == U; }
 MATCHER_P(QName, N, "") { return (arg.Scope + arg.Name).str() == N; }
 
 using namespace llvm;
@@ -73,14 +75,6 @@
   return llvm::make_unique(std::move(Slab).build());
 }
 
-RefSlab getRefs(const SymbolIndex &I, SymbolID ID) {
-  RefsRequest Req;
-  Req.IDs = {ID};
-  RefSlab::Builder Slab;
-  I.refs(Req, [&](const Ref &S) { Slab.insert(ID, S); });
-  return std::move(Slab).build();
-}
-
 TEST(FileSymbolsTest, UpdateAndGet) {
   FileSymbols FS;
   EXPECT_THAT(runFuzzyFind(*FS.buildIndex(IndexType::Light), ""), IsEmpty());
@@ -102,6 +96,27 @@
  QName("4"), QName("5")));
 }
 
+TEST(FileSymbolsTest, MergeOverlap) {
+  FileSymbols FS;
+  auto OneSymboSlab = [](Symbol Sym) {
+SymbolSlab::Builder S;
+S.insert(Sym);
+return make_unique(std::move(S).build());
+  };
+  auto X1 = symbol("x");
+  X1.CanonicalDeclaration.FileURI = "file:///x1";
+  auto X2 = symbol("x");
+  X2.Definition.FileURI = "file:///x2";
+
+  FS.update("f1", OneSymboSlab(X1), nullptr);
+  FS.update("f2", OneSymboSlab(X2), nullptr);
+  for (auto Type : {IndexType::Light, IndexType::Heavy})
+EXPECT_THAT(
+runFuzzyFind(*FS.buildIndex(Type, DuplicateHandling::Merge), "x"),
+UnorderedElementsAre(
+AllOf(QName("x"), DeclURI("file:///x1"), DefURI("file:///x2";
+}
+
 TEST(FileSymbolsTest, SnapshotAliveAfterRemove) {
   FileSymbols FS;
 
Index: unittests/clangd/BackgroundIndexTests.cpp
===
--- unittests/clangd/BackgroundIndexTests.cpp
+++ unittests/clangd/BackgroundIndexTests.cpp
@@ -4,33 +4,72 @@
 #include "gmock/gmock.h"
 #include "gtest/gtest.h"
 
+using testing::_;
+using testing::AllOf;
+using testing::Not;
 using testing::UnorderedElementsAre;
 
 namespace clang {
 namespace clangd {
 
 MATCHER_P(Named, N, "") { return arg.Name == N; }
+MATCHER(Declared, "") { return !arg.CanonicalDeclaration.FileURI.empty(); }
+MATCHER(Defined, "") { return !arg.Definition.FileURI.empty(); }
+
+MATCHER_P(FileURI, F, "") { return arg.Location.FileURI == F; }
+testing::Matcher
+RefsAre(std::vector> Matchers) {
+  return ElementsAre(testing::Pair(_, UnorderedElementsAreArray(Matchers)));
+}
 
 TEST(BackgroundIndexTest, IndexTwoFiles) {
   MockFSProvider FS;
   // a.h yields different symbols when included by A.cc vs B.cc.
   // Currently we store symbols for each TU, so we get both.
-  FS.Files[testPath("root/A.h")] = "void a_h(); void NAME(){}";
-  FS.Files[testPath("root/A.cc")] = "#include \"A.h\"";
-  FS.Files[testPath("root/B.cc")] = "#define NAME bar\n#include \"A.h\"";
-  BackgroundIndex Idx(Context::empty(), "", FS);
+  FS.Files[testPath(

[PATCH] D53771: [clang-tidy] Avoid C arrays check

2018-10-29 Thread Jonas Toth via Phabricator via cfe-commits
JonasToth added inline comments.



Comment at: clang-tidy/cppcoreguidelines/CppCoreGuidelinesTidyModule.cpp:84
 "cppcoreguidelines-c-copy-assignment-signature");
+CheckFactories.registerCheck(
+"cppcoreguidelines-avoid-c-arrays");

please conserve the alphabetical order here



Comment at: clang-tidy/hicpp/HICPPTidyModule.cpp:54
 "hicpp-avoid-goto");
+CheckFactories.registerCheck(
+"hicpp-avoid-c-arrays");

i would this one should be before `avoid-goto`.



Comment at: clang-tidy/modernize/AvoidCArraysCheck.cpp:44
+  unless(anyOf(hasParent(varDecl(isExternC())),
+   hasAncestor(functionDecl(isExternC())
+  .bind("typeloc"),

What about struct-decls that are externC?



Comment at: docs/clang-tidy/checks/modernize-avoid-c-arrays.rst:15
+observe *all* the uses of said declaration in order to decide whether it is
+safe to transform or not, and that is impossible in case of headers.
+

Not sure if we want the rational of not providing fixits here in this detail. 
Maybe it's better to formulate it as `fix-it are potentially dangerous in 
header files and are therefor not emitted right now`? Some places would be save 
to transform and we might want to provide these in the future.



Comment at: test/clang-tidy/modernize-avoid-c-arrays.cpp:48
+// Some header
+extern "C" {
+

Please add a test for extern c structs, maybe even in the form `extern "C" 
struct Foo { ... };`.

Additionally to that, maybe the opposite case should be tested too: `extern 
"C++"` in C-Code.


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D53771



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


[PATCH] D53457: clang-cl: Add "/clang:" pass-through arg support.

2018-10-29 Thread Hans Wennborg via Phabricator via cfe-commits
hans added a comment.

In https://reviews.llvm.org/D53457#1277950, @neerajksingh wrote:

> In https://reviews.llvm.org/D53457#1277315, @hans wrote:
>
> >   One note about flag ordering: the /clang: flags are concatenated to the 
> > end of
> >   the argument list, so in cases where the last flag wins, the /clang: flags
> >   will be chosen regardless of their order relative to other flags on the 
> > driver
> >   command line.
> >
> >
> > This seems a little unfortunate. I wonder if it would be possible to not 
> > have this restriction, i.e. to process these in-line with the rest of the 
> > flags?
> >
> > One way to achieve this would be to change Driver::ParseArgStrings() to 
> > handle the "/clang:" arguments. After doing the regular option parsing, it 
> > would look for "/clang:" options and substitute them for the underlying 
> > option. This has the downside of adding some option-specific logic to 
> > ParseArgStrings, but on the other hand it's less intrusive than passing 
> > around the IsCLMode bool. Do you think something like this could work?
>
>
> One difficulty occurs with options that have separated values, like the 
> `/clang:-MF /clang:` case.  In this case, we need to take two 
> /clang: arguments and process them next to each other in order to form a 
> single coherent argument/value pair. Another option is to allow the user to 
> specify the option like `/clang:"-MF "` and then require that the 
> user specify any flags that need a value in a single /clang: argument.  This 
> would require some code to split the value string on spaces before passing it 
> on to clang argument parsing.
>
> Do you have any preference or better suggestion for the option-with-value 
> case?


The `-Xclang` option has the same issue, and I think `/clang:` should work 
similarly, i.e. `/clang:-MF /clang:`. It's not pretty, but at least 
it's consistent. Yes, that means processing consecutive `/Xclang:` options 
together, but hopefully that's doable.


https://reviews.llvm.org/D53457



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


[PATCH] D53807: Create a diagnostic group for warn_call_to_pure_virtual_member_function_from_ctor_dtor, so it can be turned into an error using Werror

2018-10-29 Thread Arnaud Bienner via Phabricator via cfe-commits
ArnaudBienner created this revision.
Herald added a subscriber: cfe-commits.

Repository:
  rC Clang

https://reviews.llvm.org/D53807

Files:
  include/clang/Basic/DiagnosticGroups.td
  include/clang/Basic/DiagnosticSemaKinds.td


Index: include/clang/Basic/DiagnosticSemaKinds.td
===
--- include/clang/Basic/DiagnosticSemaKinds.td
+++ include/clang/Basic/DiagnosticSemaKinds.td
@@ -1656,7 +1656,7 @@
 def warn_call_to_pure_virtual_member_function_from_ctor_dtor : Warning<
   "call to pure virtual member function %0 has undefined behavior; "
   "overrides of %0 in subclasses are not available in the "
-  "%select{constructor|destructor}1 of %2">;
+  "%select{constructor|destructor}1 of %2">, 
InGroup;
 
 def select_special_member_kind : TextSubstitution<
   "%select{default constructor|copy constructor|move constructor|"
Index: include/clang/Basic/DiagnosticGroups.td
===
--- include/clang/Basic/DiagnosticGroups.td
+++ include/clang/Basic/DiagnosticGroups.td
@@ -285,6 +285,7 @@
 def FlagEnum : DiagGroup<"flag-enum">;
 def IncrementBool : DiagGroup<"increment-bool", [DeprecatedIncrementBool]>;
 def InfiniteRecursion : DiagGroup<"infinite-recursion">;
+def PureVirtualCallFromCtorDtor: 
DiagGroup<"call-to-pure-virtual-from-ctor-dtor">;
 def GNUImaginaryConstant : DiagGroup<"gnu-imaginary-constant">;
 def IgnoredQualifiers : DiagGroup<"ignored-qualifiers">;
 def : DiagGroup<"import">;


Index: include/clang/Basic/DiagnosticSemaKinds.td
===
--- include/clang/Basic/DiagnosticSemaKinds.td
+++ include/clang/Basic/DiagnosticSemaKinds.td
@@ -1656,7 +1656,7 @@
 def warn_call_to_pure_virtual_member_function_from_ctor_dtor : Warning<
   "call to pure virtual member function %0 has undefined behavior; "
   "overrides of %0 in subclasses are not available in the "
-  "%select{constructor|destructor}1 of %2">;
+  "%select{constructor|destructor}1 of %2">, InGroup;
 
 def select_special_member_kind : TextSubstitution<
   "%select{default constructor|copy constructor|move constructor|"
Index: include/clang/Basic/DiagnosticGroups.td
===
--- include/clang/Basic/DiagnosticGroups.td
+++ include/clang/Basic/DiagnosticGroups.td
@@ -285,6 +285,7 @@
 def FlagEnum : DiagGroup<"flag-enum">;
 def IncrementBool : DiagGroup<"increment-bool", [DeprecatedIncrementBool]>;
 def InfiniteRecursion : DiagGroup<"infinite-recursion">;
+def PureVirtualCallFromCtorDtor: DiagGroup<"call-to-pure-virtual-from-ctor-dtor">;
 def GNUImaginaryConstant : DiagGroup<"gnu-imaginary-constant">;
 def IgnoredQualifiers : DiagGroup<"ignored-qualifiers">;
 def : DiagGroup<"import">;
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D53807: Create a diagnostic group for warn_call_to_pure_virtual_member_function_from_ctor_dtor, so it can be turned into an error using Werror

2018-10-29 Thread Sylvestre Ledru via Phabricator via cfe-commits
sylvestre.ledru added a comment.

Please add some tests


Repository:
  rC Clang

https://reviews.llvm.org/D53807



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


r345496 - [ASTImporter] Import overrides before importing the rest of the chain

2018-10-29 Thread Gabor Marton via cfe-commits
Author: martong
Date: Mon Oct 29 03:18:28 2018
New Revision: 345496

URL: http://llvm.org/viewvc/llvm-project?rev=345496&view=rev
Log:
[ASTImporter] Import overrides before importing the rest of the chain

Summary:
During method import we check for structural eq of two methods.
In the structural eq check we check for their isVirtual() flag. That
flag, however, may depend on the number of overrides. Before this
change we imported the overrides *after* we had imported the rest of the
redecl chain.  So, during the import of another decl from the chain
IsVirtual() gave false result.

Writing tests for this is not really possible, because there is no way
to remove an overridden method via the AST API.
(We should access the private ASTContext::OverriddenMethods container.)
Also, we should do the remove in the middle of the import process.

Reviewers: a_sidorin, a.sidorin

Subscribers: rnkovacs, dkrupp, Szelethus, cfe-commits

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

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

Modified: cfe/trunk/lib/AST/ASTImporter.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/AST/ASTImporter.cpp?rev=345496&r1=345495&r2=345496&view=diff
==
--- cfe/trunk/lib/AST/ASTImporter.cpp (original)
+++ cfe/trunk/lib/AST/ASTImporter.cpp Mon Oct 29 03:18:28 2018
@@ -3258,6 +3258,9 @@ ExpectedDecl ASTNodeImporter::VisitFunct
 DC->makeDeclVisibleInContext(ToFunction);
   }
 
+  if (auto *FromCXXMethod = dyn_cast(D))
+ImportOverrides(cast(ToFunction), FromCXXMethod);
+
   // Import the rest of the chain. I.e. import all subsequent declarations.
   for (++RedeclIt; RedeclIt != Redecls.end(); ++RedeclIt) {
 ExpectedDecl ToRedeclOrErr = import(*RedeclIt);
@@ -3265,9 +3268,6 @@ ExpectedDecl ASTNodeImporter::VisitFunct
   return ToRedeclOrErr.takeError();
   }
 
-  if (auto *FromCXXMethod = dyn_cast(D))
-ImportOverrides(cast(ToFunction), FromCXXMethod);
-
   return ToFunction;
 }
 


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


[PATCH] D53704: [ASTImporter] Import overrides before importing the rest of the chain

2018-10-29 Thread Gabor Marton via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rC345496: [ASTImporter] Import overrides before importing the 
rest of the chain (authored by martong, committed by ).

Changed prior to commit:
  https://reviews.llvm.org/D53704?vs=171097&id=171471#toc

Repository:
  rC Clang

https://reviews.llvm.org/D53704

Files:
  lib/AST/ASTImporter.cpp


Index: lib/AST/ASTImporter.cpp
===
--- lib/AST/ASTImporter.cpp
+++ lib/AST/ASTImporter.cpp
@@ -3258,16 +3258,16 @@
 DC->makeDeclVisibleInContext(ToFunction);
   }
 
+  if (auto *FromCXXMethod = dyn_cast(D))
+ImportOverrides(cast(ToFunction), FromCXXMethod);
+
   // Import the rest of the chain. I.e. import all subsequent declarations.
   for (++RedeclIt; RedeclIt != Redecls.end(); ++RedeclIt) {
 ExpectedDecl ToRedeclOrErr = import(*RedeclIt);
 if (!ToRedeclOrErr)
   return ToRedeclOrErr.takeError();
   }
 
-  if (auto *FromCXXMethod = dyn_cast(D))
-ImportOverrides(cast(ToFunction), FromCXXMethod);
-
   return ToFunction;
 }
 


Index: lib/AST/ASTImporter.cpp
===
--- lib/AST/ASTImporter.cpp
+++ lib/AST/ASTImporter.cpp
@@ -3258,16 +3258,16 @@
 DC->makeDeclVisibleInContext(ToFunction);
   }
 
+  if (auto *FromCXXMethod = dyn_cast(D))
+ImportOverrides(cast(ToFunction), FromCXXMethod);
+
   // Import the rest of the chain. I.e. import all subsequent declarations.
   for (++RedeclIt; RedeclIt != Redecls.end(); ++RedeclIt) {
 ExpectedDecl ToRedeclOrErr = import(*RedeclIt);
 if (!ToRedeclOrErr)
   return ToRedeclOrErr.takeError();
   }
 
-  if (auto *FromCXXMethod = dyn_cast(D))
-ImportOverrides(cast(ToFunction), FromCXXMethod);
-
   return ToFunction;
 }
 
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D33672: [analyzer] INT50-CPP. Do not cast to an out-of-range enumeration checker

2018-10-29 Thread Alexander Zaitsev via Phabricator via cfe-commits
ZaMaZaN4iK updated this revision to Diff 171472.
ZaMaZaN4iK added a comment.

Add the reference to CERT page


https://reviews.llvm.org/D33672

Files:
  include/clang/StaticAnalyzer/Checkers/Checkers.td
  lib/StaticAnalyzer/Checkers/CMakeLists.txt
  lib/StaticAnalyzer/Checkers/EnumCastOutOfRangeChecker.cpp
  test/Analysis/enum-cast-out-of-range.cpp
  www/analyzer/alpha_checks.html

Index: www/analyzer/alpha_checks.html
===
--- www/analyzer/alpha_checks.html
+++ www/analyzer/alpha_checks.html
@@ -348,6 +348,24 @@
 }
 
 
+
+alpha.cplusplus.EnumCastOutOfRange
+(C++)
+  Check for integer to enumeration casts that could result in undefined values.
+
+  
+
+enum TestEnum {
+  A = 0
+};
+
+void foo() {
+  TestEnum t = static_cast(-1);
+  // warn: the value provided to the cast expression is not in
+   the valid range of values for the enum
+}
+
+
 
 
 alpha.cplusplus.InvalidatedIterator
Index: test/Analysis/enum-cast-out-of-range.cpp
===
--- /dev/null
+++ test/Analysis/enum-cast-out-of-range.cpp
@@ -0,0 +1,182 @@
+// RUN: %clang_analyze_cc1 \
+// RUN:   -analyzer-checker=core,alpha.cplusplus.EnumCastOutOfRange \
+// RUN:   -std=c++11 -verify %s
+
+enum unscoped_unspecified_t {
+  unscoped_unspecified_0 = -4,
+  unscoped_unspecified_1,
+  unscoped_unspecified_2 = 1,
+  unscoped_unspecified_3,
+  unscoped_unspecified_4 = 4
+};
+
+enum unscoped_specified_t : int {
+  unscoped_specified_0 = -4,
+  unscoped_specified_1,
+  unscoped_specified_2 = 1,
+  unscoped_specified_3,
+  unscoped_specified_4 = 4
+};
+
+enum class scoped_unspecified_t {
+  scoped_unspecified_0 = -4,
+  scoped_unspecified_1,
+  scoped_unspecified_2 = 1,
+  scoped_unspecified_3,
+  scoped_unspecified_4 = 4
+};
+
+enum class scoped_specified_t : int {
+  scoped_specified_0 = -4,
+  scoped_specified_1,
+  scoped_specified_2 = 1,
+  scoped_specified_3,
+  scoped_specified_4 = 4
+};
+
+void unscopedUnspecified() {
+  unscoped_unspecified_t InvalidBeforeRangeBegin = static_cast(-5); // expected-warning {{the value provided to the cast expression is not in the valid range of values for the enum}}
+  unscoped_unspecified_t ValidNegativeValue1 = static_cast(-4); // OK.
+  unscoped_unspecified_t ValidNegativeValue2 = static_cast(-3); // OK.
+  unscoped_unspecified_t InvalidInsideRange1 = static_cast(-2); // expected-warning {{the value provided to the cast expression is not in the valid range of values for the enum}}
+  unscoped_unspecified_t InvalidInsideRange2 = static_cast(-1); // expected-warning {{the value provided to the cast expression is not in the valid range of values for the enum}}
+  unscoped_unspecified_t InvalidInsideRange3 = static_cast(0); // expected-warning {{the value provided to the cast expression is not in the valid range of values for the enum}}
+  unscoped_unspecified_t ValidPositiveValue1 = static_cast(1); // OK.
+  unscoped_unspecified_t ValidPositiveValue2 = static_cast(2); // OK.
+  unscoped_unspecified_t InvalidInsideRange4 = static_cast(3); // expected-warning {{the value provided to the cast expression is not in the valid range of values for the enum}}
+  unscoped_unspecified_t ValidPositiveValue3 = static_cast(4); // OK.
+  unscoped_unspecified_t InvalidAfterRangeEnd = static_cast(5); // expected-warning {{the value provided to the cast expression is not in the valid range of values for the enum}}
+}
+
+void unscopedSpecified() {
+  unscoped_specified_t InvalidBeforeRangeBegin = static_cast(-5); // expected-warning {{the value provided to the cast expression is not in the valid range of values for the enum}}
+  unscoped_specified_t ValidNegativeValue1 = static_cast(-4); // OK.
+  unscoped_specified_t ValidNegativeValue2 = static_cast(-3); // OK.
+  unscoped_specified_t InvalidInsideRange1 = static_cast(-2); // expected-warning {{the value provided to the cast expression is not in the valid range of values for the enum}}
+  unscoped_specified_t InvalidInsideRange2 = static_cast(-1); // expected-warning {{the value provided to the cast expression is not in the valid range of values for the enum}}
+  unscoped_specified_t InvalidInsideRange3 = static_cast(0); // expected-warning {{the value provided to the cast expression is not in the valid range of values for the enum}}
+  unscoped_specified_t ValidPositiveValue1 = static_cast(1); // OK.
+  unscoped_specified_t ValidPositiveValue2 = static_cast(2); // OK.
+  unscoped_specified_t InvalidInsideRange4 = static_cast(3); // expected-warning {{the value provided to the cast expression is not in the valid range of values for the enum}}
+  unscoped_specified_t ValidPositiveValue3 = static_cast(4); // OK.
+  unscoped_specified_t InvalidAfterRangeEnd = static_cast(5); // expected-warning {{the value provided to the cast expression is not in the valid range of values for the enum}}
+}
+
+void scopedUnspecified() {
+  scoped_unspecified_t Inval

[PATCH] D33672: [analyzer] INT50-CPP. Do not cast to an out-of-range enumeration checker

2018-10-29 Thread Alexander Zaitsev via Phabricator via cfe-commits
ZaMaZaN4iK marked 3 inline comments as done.
ZaMaZaN4iK added inline comments.



Comment at: lib/StaticAnalyzer/Checkers/EnumCastOutOfRangeChecker.cpp:19
+//   of casting an integer value that is out of range
+//===--===//
+

Szelethus wrote:
> ZaMaZaN4iK wrote:
> > aaron.ballman wrote:
> > > If this check is intended to conform to CERT's INT50-CPP rule, you should 
> > > put a link to the wiki entry for it here as well.
> > Which wiki entry do you mean?
> Maybe this one? 
> https://wiki.sei.cmu.edu/confluence/display/cplusplus/INT50-CPP.+Do+not+cast+to+an+out-of-range+enumeration+value
Added a note about CERT's coding standard recommendaation. Didn't add the 
reference to web page because web pages can become broken. I think standard and 
check names are quite good explanation for here


https://reviews.llvm.org/D33672



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


[PATCH] D53808: [clangd] Don't collect refs from non-canonical headers.

2018-10-29 Thread Haojian Wu via Phabricator via cfe-commits
hokein created this revision.
hokein added a reviewer: sammccall.
Herald added subscribers: kadircet, arphaman, jkorous, MaskRay, ioeric, 
ilya-biryukov.

With this patch, we only collect refs for canonical headers (headers
with header guards). As non-canonical headers are usually generated, and
not interesting to users.

For LLVM, we have ~2.8 million refs (out of 6 million) for generated inc
headers.

|   | Before | After |
| file size | 78 MB  | 55MB  |
| memory| 330MB  | 260MB |


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D53808

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


Index: unittests/clangd/SymbolCollectorTests.cpp
===
--- unittests/clangd/SymbolCollectorTests.cpp
+++ unittests/clangd/SymbolCollectorTests.cpp
@@ -486,13 +486,29 @@
   CollectorOpts.RefFilter = RefKind::All;
   CollectorOpts.RefsInHeaders = true;
   Annotations Header(R"(
+  #ifndef HEAD_H_
+  #define HEAD_H_
   class [[Foo]] {};
+  #endif
   )");
   runSymbolCollector(Header.code(), "");
   EXPECT_THAT(Refs, Contains(Pair(findSymbol(Symbols, "Foo").ID,
   HaveRanges(Header.ranges();
 }
 
+TEST_F(SymbolCollectorTest, NoRefsInNonCanonicalHeaders) {
+  CollectorOpts.RefFilter = RefKind::All;
+  CollectorOpts.RefsInHeaders = true;
+  Annotations Header(R"(
+  class [[Foo]] {};
+  inline void f() {
+[[Foo]] foo;
+  }
+  )");
+  runSymbolCollector(Header.code(), "");
+  EXPECT_THAT(Refs, Not(Contains(Pair(findSymbol(Symbols, "Foo").ID, _;
+}
+
 TEST_F(SymbolCollectorTest, References) {
   const std::string Header = R"(
 class W;
Index: clangd/index/SymbolCollector.cpp
===
--- clangd/index/SymbolCollector.cpp
+++ clangd/index/SymbolCollector.cpp
@@ -475,8 +475,15 @@
   IncRef(*ID);
 }
   }
-
   const auto &SM = ASTCtx->getSourceManager();
+  llvm::DenseSet CanonicalHeaders;
+  for (auto &IT : PP->macros()) {
+auto MI = PP->getMacroInfo(IT.first);
+if (MI && MI->isUsedForHeaderGuard()) {
+  auto FID = SM.getFileID(MI->getDefinitionLoc());
+  CanonicalHeaders.insert(FID);
+}
+  }
   DenseMap URICache;
   auto GetURI = [&](FileID FID) -> Optional {
 auto Found = URICache.find(FID);
@@ -503,6 +510,9 @@
   if (auto ID = getSymbolID(It.first)) {
 for (const auto &LocAndRole : It.second) {
   auto FileID = SM.getFileID(LocAndRole.first);
+  // Only collect refs from the main file and canonical headers.
+  if (FileID != SM.getMainFileID() && !CanonicalHeaders.count(FileID))
+continue;
   if (auto FileURI = GetURI(FileID)) {
 auto Range =
 getTokenRange(LocAndRole.first, SM, ASTCtx->getLangOpts());


Index: unittests/clangd/SymbolCollectorTests.cpp
===
--- unittests/clangd/SymbolCollectorTests.cpp
+++ unittests/clangd/SymbolCollectorTests.cpp
@@ -486,13 +486,29 @@
   CollectorOpts.RefFilter = RefKind::All;
   CollectorOpts.RefsInHeaders = true;
   Annotations Header(R"(
+  #ifndef HEAD_H_
+  #define HEAD_H_
   class [[Foo]] {};
+  #endif
   )");
   runSymbolCollector(Header.code(), "");
   EXPECT_THAT(Refs, Contains(Pair(findSymbol(Symbols, "Foo").ID,
   HaveRanges(Header.ranges();
 }
 
+TEST_F(SymbolCollectorTest, NoRefsInNonCanonicalHeaders) {
+  CollectorOpts.RefFilter = RefKind::All;
+  CollectorOpts.RefsInHeaders = true;
+  Annotations Header(R"(
+  class [[Foo]] {};
+  inline void f() {
+[[Foo]] foo;
+  }
+  )");
+  runSymbolCollector(Header.code(), "");
+  EXPECT_THAT(Refs, Not(Contains(Pair(findSymbol(Symbols, "Foo").ID, _;
+}
+
 TEST_F(SymbolCollectorTest, References) {
   const std::string Header = R"(
 class W;
Index: clangd/index/SymbolCollector.cpp
===
--- clangd/index/SymbolCollector.cpp
+++ clangd/index/SymbolCollector.cpp
@@ -475,8 +475,15 @@
   IncRef(*ID);
 }
   }
-
   const auto &SM = ASTCtx->getSourceManager();
+  llvm::DenseSet CanonicalHeaders;
+  for (auto &IT : PP->macros()) {
+auto MI = PP->getMacroInfo(IT.first);
+if (MI && MI->isUsedForHeaderGuard()) {
+  auto FID = SM.getFileID(MI->getDefinitionLoc());
+  CanonicalHeaders.insert(FID);
+}
+  }
   DenseMap URICache;
   auto GetURI = [&](FileID FID) -> Optional {
 auto Found = URICache.find(FID);
@@ -503,6 +510,9 @@
   if (auto ID = getSymbolID(It.first)) {
 for (const auto &LocAndRole : It.second) {
   auto FileID = SM.getFileID(LocAndRole.first);
+  // Only collect refs from the main file and canonical headers.
+  if (FileID != SM.getMainFileID() && !CanonicalHeaders.count(FileID))
+continue;
   if (auto FileURI = GetURI(FileID)) {
 

[PATCH] D53809: Fix invalid address space generation for clk_event_t

2018-10-29 Thread Viktoria Maximova via Phabricator via cfe-commits
vmaksimo created this revision.
vmaksimo added reviewers: Anastasia, yaxunl, AlexeySotkin.
Herald added a subscriber: cfe-commits.

Addrspace(32) was generated when putting 0 in clk_event_t * event_ret parameter 
for enqueue_kernel function.


Repository:
  rC Clang

https://reviews.llvm.org/D53809

Files:
  lib/CodeGen/CGBuiltin.cpp
  test/CodeGenOpenCL/cl20-device-side-enqueue.cl


Index: test/CodeGenOpenCL/cl20-device-side-enqueue.cl
===
--- test/CodeGenOpenCL/cl20-device-side-enqueue.cl
+++ test/CodeGenOpenCL/cl20-device-side-enqueue.cl
@@ -106,6 +106,13 @@
a[i] = b[i];
  });
 
+  // COMMON-LABEL: call i32 @__enqueue_kernel_basic_events
+  // COMMON-SAME: (%opencl.queue_t{{.*}}* {{%[0-9]+}}, i32 {{%[0-9]+}}, 
%struct.ndrange_t* {{.*}}, i32 1, %opencl.clk_event_t{{.*}}* addrspace(4)* 
{{%[0-9]+}}, %opencl.clk_event_t{{.*}}* addrspace(4)* null,
+  enqueue_kernel(default_queue, flags, ndrange, 1, &event_wait_list, 0,
+ ^(void) {
+   return;
+ });
+
   // Emits global block literal [[BLG1]] and block kernel [[INVGK1]].
   // COMMON: [[DEF_Q:%[0-9]+]] = load %opencl.queue_t{{.*}}*, 
%opencl.queue_t{{.*}}** %default_queue
   // COMMON: [[FLAGS:%[0-9]+]] = load i32, i32* %flags
@@ -390,7 +397,7 @@
 // COMMON: define internal spir_kernel void [[INVGK5]](i8 addrspace(4)*{{.*}}, 
i8 addrspace(3)*{{.*}})
 // COMMON: define internal spir_kernel void [[INVGK6]](i8 addrspace(4)*, i8 
addrspace(3)*, i8 addrspace(3)*, i8 addrspace(3)*) #{{[0-9]+}} {
 // COMMON: entry:
-// COMMON:  call void @__device_side_enqueue_block_invoke_8(i8 addrspace(4)* 
%0, i8 addrspace(3)* %1, i8 addrspace(3)* %2, i8 addrspace(3)* %3)
+// COMMON:  call void @__device_side_enqueue_block_invoke_9(i8 addrspace(4)* 
%0, i8 addrspace(3)* %1, i8 addrspace(3)* %2, i8 addrspace(3)* %3)
 // COMMON:  ret void
 // COMMON: }
 // COMMON: define internal spir_kernel void [[INVGK7]](i8 addrspace(4)*{{.*}}, 
i8 addrspace(3)*{{.*}})
Index: lib/CodeGen/CGBuiltin.cpp
===
--- lib/CodeGen/CGBuiltin.cpp
+++ lib/CodeGen/CGBuiltin.cpp
@@ -3460,7 +3460,9 @@
   llvm::Value *ClkEvent = EmitScalarExpr(E->getArg(5));
   // Convert to generic address space.
   EventList = Builder.CreatePointerCast(EventList, EventPtrTy);
-  ClkEvent = Builder.CreatePointerCast(ClkEvent, EventPtrTy);
+  ClkEvent = ClkEvent->getType()->isIntegerTy()
+   ? Builder.CreateBitOrPointerCast(ClkEvent, EventPtrTy)
+   : Builder.CreatePointerCast(ClkEvent, EventPtrTy);
   auto Info =
   CGM.getOpenCLRuntime().emitOpenCLEnqueuedBlock(*this, E->getArg(6));
   llvm::Value *Kernel =


Index: test/CodeGenOpenCL/cl20-device-side-enqueue.cl
===
--- test/CodeGenOpenCL/cl20-device-side-enqueue.cl
+++ test/CodeGenOpenCL/cl20-device-side-enqueue.cl
@@ -106,6 +106,13 @@
a[i] = b[i];
  });
 
+  // COMMON-LABEL: call i32 @__enqueue_kernel_basic_events
+  // COMMON-SAME: (%opencl.queue_t{{.*}}* {{%[0-9]+}}, i32 {{%[0-9]+}}, %struct.ndrange_t* {{.*}}, i32 1, %opencl.clk_event_t{{.*}}* addrspace(4)* {{%[0-9]+}}, %opencl.clk_event_t{{.*}}* addrspace(4)* null,
+  enqueue_kernel(default_queue, flags, ndrange, 1, &event_wait_list, 0,
+ ^(void) {
+   return;
+ });
+
   // Emits global block literal [[BLG1]] and block kernel [[INVGK1]].
   // COMMON: [[DEF_Q:%[0-9]+]] = load %opencl.queue_t{{.*}}*, %opencl.queue_t{{.*}}** %default_queue
   // COMMON: [[FLAGS:%[0-9]+]] = load i32, i32* %flags
@@ -390,7 +397,7 @@
 // COMMON: define internal spir_kernel void [[INVGK5]](i8 addrspace(4)*{{.*}}, i8 addrspace(3)*{{.*}})
 // COMMON: define internal spir_kernel void [[INVGK6]](i8 addrspace(4)*, i8 addrspace(3)*, i8 addrspace(3)*, i8 addrspace(3)*) #{{[0-9]+}} {
 // COMMON: entry:
-// COMMON:  call void @__device_side_enqueue_block_invoke_8(i8 addrspace(4)* %0, i8 addrspace(3)* %1, i8 addrspace(3)* %2, i8 addrspace(3)* %3)
+// COMMON:  call void @__device_side_enqueue_block_invoke_9(i8 addrspace(4)* %0, i8 addrspace(3)* %1, i8 addrspace(3)* %2, i8 addrspace(3)* %3)
 // COMMON:  ret void
 // COMMON: }
 // COMMON: define internal spir_kernel void [[INVGK7]](i8 addrspace(4)*{{.*}}, i8 addrspace(3)*{{.*}})
Index: lib/CodeGen/CGBuiltin.cpp
===
--- lib/CodeGen/CGBuiltin.cpp
+++ lib/CodeGen/CGBuiltin.cpp
@@ -3460,7 +3460,9 @@
   llvm::Value *ClkEvent = EmitScalarExpr(E->getArg(5));
   // Convert to generic address space.
   EventList = Builder.CreatePointerCast(EventList, EventPtrTy);
-  ClkEvent = Builder.CreatePointerCast(ClkEvent, EventPtrTy);
+  ClkEvent = ClkEvent->getType()->isIntegerTy()
+   ? Builder.CreateBitO

[PATCH] D53808: [clangd] Don't collect refs from non-canonical headers.

2018-10-29 Thread Roman Lebedev via Phabricator via cfe-commits
lebedev.ri added a comment.

Please add a test with `#pragma once`, which should still be counted as a 
header guard.


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D53808



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


[PATCH] D53693: [ASTImporter] Typedef import brings in the complete type

2018-10-29 Thread Gabor Marton via Phabricator via cfe-commits
martong updated this revision to Diff 171478.
martong marked 2 inline comments as done.
martong added a comment.

- Move FromUT upper, add break


Repository:
  rC Clang

https://reviews.llvm.org/D53693

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


Index: unittests/AST/ASTImporterTest.cpp
===
--- unittests/AST/ASTImporterTest.cpp
+++ unittests/AST/ASTImporterTest.cpp
@@ -3726,6 +3726,38 @@
   EXPECT_EQ(To1->getPreviousDecl(), To0);
 }
 
+TEST_P(ASTImporterTestBase, ImportingTypedefShouldImportTheCompleteType) {
+  // We already have an incomplete underlying type in the "To" context.
+  auto Code =
+  R"(
+  template 
+  struct S {
+void foo();
+  };
+  using U = S;
+  )";
+  Decl *ToTU = getToTuDecl(Code, Lang_CXX11);
+  auto *ToD = FirstDeclMatcher().match(ToTU,
+  typedefNameDecl(hasName("U")));
+  ASSERT_TRUE(ToD->getUnderlyingType()->isIncompleteType());
+
+  // The "From" context has the same typedef, but the underlying type is
+  // complete this time.
+  Decl *FromTU = getTuDecl(std::string(Code) +
+  R"(
+  void foo(U* u) {
+u->foo();
+  }
+  )", Lang_CXX11);
+  auto *FromD = FirstDeclMatcher().match(FromTU,
+  typedefNameDecl(hasName("U")));
+  ASSERT_FALSE(FromD->getUnderlyingType()->isIncompleteType());
+
+  // The imported type should be complete.
+  auto *ImportedD = cast(Import(FromD, Lang_CXX11));
+  EXPECT_FALSE(ImportedD->getUnderlyingType()->isIncompleteType());
+}
+
 INSTANTIATE_TEST_CASE_P(ParameterizedTests, DeclContextTest,
 ::testing::Values(ArgVector()), );
 
Index: lib/AST/ASTImporter.cpp
===
--- lib/AST/ASTImporter.cpp
+++ lib/AST/ASTImporter.cpp
@@ -2305,9 +2305,16 @@
   if (!FoundDecl->isInIdentifierNamespace(IDNS))
 continue;
   if (auto *FoundTypedef = dyn_cast(FoundDecl)) {
-if (Importer.IsStructurallyEquivalent(
-D->getUnderlyingType(), FoundTypedef->getUnderlyingType()))
+QualType FromUT = D->getUnderlyingType();
+QualType FoundUT = FoundTypedef->getUnderlyingType();
+if (Importer.IsStructurallyEquivalent(FromUT, FoundUT)) {
+  // If the "From" context has a complete underlying type but we
+  // already have a complete underlying type then return with that.
+  if (!FromUT->isIncompleteType() && !FoundUT->isIncompleteType())
 return Importer.MapImported(D, FoundTypedef);
+}
+// FIXME Handle redecl chain.
+break;
   }
 
   ConflictingDecls.push_back(FoundDecl);


Index: unittests/AST/ASTImporterTest.cpp
===
--- unittests/AST/ASTImporterTest.cpp
+++ unittests/AST/ASTImporterTest.cpp
@@ -3726,6 +3726,38 @@
   EXPECT_EQ(To1->getPreviousDecl(), To0);
 }
 
+TEST_P(ASTImporterTestBase, ImportingTypedefShouldImportTheCompleteType) {
+  // We already have an incomplete underlying type in the "To" context.
+  auto Code =
+  R"(
+  template 
+  struct S {
+void foo();
+  };
+  using U = S;
+  )";
+  Decl *ToTU = getToTuDecl(Code, Lang_CXX11);
+  auto *ToD = FirstDeclMatcher().match(ToTU,
+  typedefNameDecl(hasName("U")));
+  ASSERT_TRUE(ToD->getUnderlyingType()->isIncompleteType());
+
+  // The "From" context has the same typedef, but the underlying type is
+  // complete this time.
+  Decl *FromTU = getTuDecl(std::string(Code) +
+  R"(
+  void foo(U* u) {
+u->foo();
+  }
+  )", Lang_CXX11);
+  auto *FromD = FirstDeclMatcher().match(FromTU,
+  typedefNameDecl(hasName("U")));
+  ASSERT_FALSE(FromD->getUnderlyingType()->isIncompleteType());
+
+  // The imported type should be complete.
+  auto *ImportedD = cast(Import(FromD, Lang_CXX11));
+  EXPECT_FALSE(ImportedD->getUnderlyingType()->isIncompleteType());
+}
+
 INSTANTIATE_TEST_CASE_P(ParameterizedTests, DeclContextTest,
 ::testing::Values(ArgVector()), );
 
Index: lib/AST/ASTImporter.cpp
===
--- lib/AST/ASTImporter.cpp
+++ lib/AST/ASTImporter.cpp
@@ -2305,9 +2305,16 @@
   if (!FoundDecl->isInIdentifierNamespace(IDNS))
 continue;
   if (auto *FoundTypedef = dyn_cast(FoundDecl)) {
-if (Importer.IsStructurallyEquivalent(
-D->getUnderlyingType(), FoundTypedef->getUnderlyingType()))
+QualType FromUT = D->getUnderlyingType();
+QualType FoundUT = FoundTypedef->getUnderlyingType();
+if (Importer.IsStructurallyEquivalent(FromUT, FoundUT)) {
+  // If the "From" context has a complete underlying type but we
+  // already have a complete underlying type then return with that.
+  if (!FromUT->isIncompleteType() && !FoundUT->isIncompleteType())
 return Importer.MapImported

[PATCH] D52296: [Clang] - Add -gsingle-file-split-dwarf option.

2018-10-29 Thread George Rimar via Phabricator via cfe-commits
grimar updated this revision to Diff 171480.
grimar added a comment.

Ping.

- Rebased.


https://reviews.llvm.org/D52296

Files:
  include/clang/Driver/CC1Options.td
  include/clang/Driver/Options.td
  include/clang/Frontend/CodeGenOptions.h
  lib/CodeGen/BackendUtil.cpp
  lib/Driver/ToolChains/Clang.cpp
  lib/Driver/ToolChains/CommonArgs.cpp
  lib/Driver/ToolChains/CommonArgs.h
  lib/Driver/ToolChains/Gnu.cpp
  lib/Driver/ToolChains/MinGW.cpp
  lib/Frontend/CompilerInvocation.cpp
  test/CodeGen/split-debug-single-file.c
  test/Driver/split-debug.c
  test/Driver/split-debug.s

Index: test/Driver/split-debug.s
===
--- test/Driver/split-debug.s
+++ test/Driver/split-debug.s
@@ -5,6 +5,9 @@
 //
 // CHECK-ACTIONS: "-split-dwarf-file" "split-debug.dwo"
 
+// Check we do not pass any -split-dwarf commands to `as` if -gsingle-file-split-dwarf is specified.
+// RUN: %clang -target x86_64-unknown-linux-gnu -gsplit-dwarf -gsingle-file-split-dwarf -c -### %s 2> %t
+// RUN: FileCheck -check-prefix=CHECK-NO-ACTIONS < %t %s
 
 // RUN: %clang -target x86_64-macosx -gsplit-dwarf -c -### %s 2> %t
 // RUN: FileCheck -check-prefix=CHECK-NO-ACTIONS < %t %s
Index: test/Driver/split-debug.c
===
--- test/Driver/split-debug.c
+++ test/Driver/split-debug.c
@@ -5,6 +5,16 @@
 //
 // CHECK-ACTIONS: "-split-dwarf-file" "split-debug.dwo"
 
+// RUN: %clang -target x86_64-unknown-linux-gnu -gsplit-dwarf -gsingle-file-split-dwarf -c -### %s 2> %t
+// RUN: FileCheck -check-prefix=CHECK-ACTIONS-SINGLE-SPLIT < %t %s
+//
+// CHECK-ACTIONS-SINGLE-SPLIT: "-single-file-split-dwarf"
+// CHECK-ACTIONS-SINGLE-SPLIT: "-split-dwarf-file" "split-debug.o"
+
+// RUN: %clang -target x86_64-unknown-linux-gnu -gsplit-dwarf -gsingle-file-split-dwarf -c -### -o %tfoo.o %s 2> %t
+// RUN: FileCheck -check-prefix=CHECK-SINGLE-SPLIT-FILENAME < %t %s
+//
+// CHECK-SINGLE-SPLIT-FILENAME: "-split-dwarf-file" "{{.*}}foo.o"
 
 // RUN: %clang -target x86_64-macosx -gsplit-dwarf -c -### %s 2> %t
 // RUN: FileCheck -check-prefix=CHECK-NO-ACTIONS < %t %s
Index: test/CodeGen/split-debug-single-file.c
===
--- test/CodeGen/split-debug-single-file.c
+++ test/CodeGen/split-debug-single-file.c
@@ -0,0 +1,16 @@
+// REQUIRES: x86-registered-target
+
+// Testing to ensure -single-file-split-dwarf allows to place .dwo sections into regular output object.
+//  RUN: %clang_cc1 -debug-info-kind=limited -triple x86_64-unknown-linux \
+//  RUN:   -enable-split-dwarf -split-dwarf-file %t.o -emit-obj -single-file-split-dwarf -o %t.o %s
+//  RUN: llvm-objdump -section-headers %t.o | FileCheck --check-prefix=SINGLE-FILE-SPLIT %s
+//  SINGLE-FILE-SPLIT: .dwo
+
+// Testing to ensure that the dwo name gets output into the compile unit.
+//  RUN: %clang_cc1 -debug-info-kind=limited -split-dwarf-file foo.o -single-file-split-dwarf \
+//  RUN:   -S -emit-llvm -o - %s | FileCheck %s --check-prefix=DWONAME
+//  DWONAME: !DICompileUnit({{.*}}, splitDebugFilename: "foo.o"
+
+int main (void) {
+  return 0;
+}
Index: lib/Frontend/CompilerInvocation.cpp
===
--- lib/Frontend/CompilerInvocation.cpp
+++ lib/Frontend/CompilerInvocation.cpp
@@ -598,6 +598,8 @@
   Opts.EnableSplitDwarf = Args.hasArg(OPT_enable_split_dwarf);
   Opts.SplitDwarfFile = Args.getLastArgValue(OPT_split_dwarf_file);
   Opts.SplitDwarfInlining = !Args.hasArg(OPT_fno_split_dwarf_inlining);
+  Opts.SingleFileSplitDwarf = Args.hasArg(OPT_single_file_split_dwarf);
+
   Opts.DebugTypeExtRefs = Args.hasArg(OPT_dwarf_ext_refs);
   Opts.DebugExplicitImport = Args.hasArg(OPT_dwarf_explicit_import);
   Opts.DebugFwdTemplateParams = Args.hasArg(OPT_debug_forward_template_params);
Index: lib/Driver/ToolChains/MinGW.cpp
===
--- lib/Driver/ToolChains/MinGW.cpp
+++ lib/Driver/ToolChains/MinGW.cpp
@@ -54,7 +54,7 @@
 
   if (Args.hasArg(options::OPT_gsplit_dwarf))
 SplitDebugInfo(getToolChain(), C, *this, JA, Args, Output,
-   SplitDebugName(Args, Inputs[0]));
+   SplitDebugName(Args, Inputs[0], Output));
 }
 
 void tools::MinGW::Linker::AddLibGCC(const ArgList &Args,
Index: lib/Driver/ToolChains/Gnu.cpp
===
--- lib/Driver/ToolChains/Gnu.cpp
+++ lib/Driver/ToolChains/Gnu.cpp
@@ -817,7 +817,7 @@
   if (Args.hasArg(options::OPT_gsplit_dwarf) &&
   getToolChain().getTriple().isOSLinux())
 SplitDebugInfo(getToolChain(), C, *this, JA, Args, Output,
-   SplitDebugName(Args, Inputs[0]));
+   SplitDebugName(Args, Inputs[0], Output));
 }
 
 namespace {
Index: lib/Driver/ToolChains/CommonArgs.h
===
--- lib/Driver/ToolChains/CommonArgs.h
+++ lib/

[PATCH] D53810: [analyzer][NFC] Refactor PlistDiagnostics to use a class instead of passing 9 parameters around

2018-10-29 Thread Umann Kristóf via Phabricator via cfe-commits
Szelethus created this revision.
Szelethus added reviewers: xazax.hun, rnkovacs, george.karpenkov, NoQ.
Herald added subscribers: cfe-commits, dkrupp, donat.nagy, mikhail.ramalho, 
a.sidorin, szepet, whisperity.

This has been a long time coming. Note the usage of `AnalyzerOptions`: I'll 
need it for https://reviews.llvm.org/D52742, and added it in 
https://reviews.llvm.org/rC343620.


Repository:
  rC Clang

https://reviews.llvm.org/D53810

Files:
  lib/StaticAnalyzer/Core/PlistDiagnostics.cpp

Index: lib/StaticAnalyzer/Core/PlistDiagnostics.cpp
===
--- lib/StaticAnalyzer/Core/PlistDiagnostics.cpp
+++ lib/StaticAnalyzer/Core/PlistDiagnostics.cpp
@@ -24,10 +24,16 @@
 #include "llvm/ADT/Statistic.h"
 #include "llvm/ADT/SmallVector.h"
 #include "llvm/Support/Casting.h"
+
 using namespace clang;
 using namespace ento;
 using namespace markup;
 
+//===--===//
+// Declarations of helper classes and functions for emitting bug reports in
+// plist format.
+//===--===//
+
 namespace {
   class PlistDiagnostics : public PathDiagnosticConsumer {
 const std::string OutputFile;
@@ -59,34 +65,86 @@
   };
 } // end anonymous namespace
 
-PlistDiagnostics::PlistDiagnostics(AnalyzerOptions &AnalyzerOpts,
-   const std::string& output,
-   const Preprocessor &PP,
-   bool supportsMultipleFiles)
-  : OutputFile(output), PP(PP), AnOpts(AnalyzerOpts),
-SupportsCrossFileDiagnostics(supportsMultipleFiles) {}
+namespace {
 
-void ento::createPlistDiagnosticConsumer(AnalyzerOptions &AnalyzerOpts,
- PathDiagnosticConsumers &C,
- const std::string& s,
- const Preprocessor &PP) {
-  C.push_back(new PlistDiagnostics(AnalyzerOpts, s, PP,
-   /*supportsMultipleFiles*/ false));
-}
+/// A helper class for emitting a single report.
+class PlistPrinter {
+  const FIDMap& FM;
+  AnalyzerOptions &AnOpts;
+  const Preprocessor &PP;
 
-void ento::createPlistMultiFileDiagnosticConsumer(AnalyzerOptions &AnalyzerOpts,
-  PathDiagnosticConsumers &C,
-  const std::string &s,
-  const Preprocessor &PP) {
-  C.push_back(new PlistDiagnostics(AnalyzerOpts, s, PP,
-   /*supportsMultipleFiles*/ true));
-}
+public:
+  PlistPrinter(const FIDMap& FM, AnalyzerOptions &AnOpts,
+   const Preprocessor &PP)
+: FM(FM), AnOpts(AnOpts), PP(PP) {
+  }
+
+  void ReportDiag(raw_ostream &o, const PathDiagnosticPiece& P) {
+ReportPiece(o, P, /*indent*/ 4, /*depth*/ 0, /*includeControlFlow*/ true);
+
+// Don't emit a warning about an unused private field.
+(void)AnOpts;
+  }
+
+private:
+  void ReportPiece(raw_ostream &o, const PathDiagnosticPiece &P,
+   unsigned indent, unsigned depth, bool includeControlFlow,
+   bool isKeyEvent = false) {
+switch (P.getKind()) {
+  case PathDiagnosticPiece::ControlFlow:
+if (includeControlFlow)
+  ReportControlFlow(o, cast(P), indent);
+break;
+  case PathDiagnosticPiece::Call:
+ReportCall(o, cast(P), indent,
+   depth);
+break;
+  case PathDiagnosticPiece::Event:
+ReportEvent(o, cast(P), indent, depth,
+isKeyEvent);
+break;
+  case PathDiagnosticPiece::Macro:
+ReportMacro(o, cast(P), indent, depth);
+break;
+  case PathDiagnosticPiece::Note:
+ReportNote(o, cast(P), indent);
+break;
+}
+  }
 
-static void EmitRanges(raw_ostream &o,
-   const ArrayRef Ranges,
-   const FIDMap& FM,
-   const Preprocessor &PP,
-   unsigned indent) {
+  void EmitRanges(raw_ostream &o, const ArrayRef Ranges,
+  unsigned indent);
+  void EmitMessage(raw_ostream &o, StringRef Message, unsigned indent);
+
+  void ReportControlFlow(raw_ostream &o,
+ const PathDiagnosticControlFlowPiece& P,
+ unsigned indent);
+  void ReportEvent(raw_ostream &o, const PathDiagnosticEventPiece& P,
+   unsigned indent, unsigned depth, bool isKeyEvent = false);
+  void ReportCall(raw_ostream &o, const PathDiagnosticCallPiece &P,
+  unsigned indent, unsigned depth);
+  void ReportMacro(raw_ostream &o, const PathDiagnosticMacroPiece& P,
+   unsigned indent, unsigned depth);
+  void ReportNote(raw_ostream &o, const PathDiagnosticNotePiece& P,
+  unsig

r345497 - [OpenCL] Fix serialization of OpenCLExtensionDecls

2018-10-29 Thread Andrew Savonichev via cfe-commits
Author: asavonic
Date: Mon Oct 29 04:14:01 2018
New Revision: 345497

URL: http://llvm.org/viewvc/llvm-project?rev=345497&view=rev
Log:
[OpenCL] Fix serialization of OpenCLExtensionDecls

Summary:
I recently discovered that adding the following code into `opencl-c.h` causes
failure of `test/Headers/opencl-c-header.cl`:
```
#pragma OPENCL EXTENSION cl_my_ext : begin
void cl_my_ext_foobarbaz();
#pragma OPENCL EXTENSIOn cl_my_ext : end
```

Clang crashes at the assertion is `ASTReader::getGlobalSubmoduleID()`:
```
assert(I != M.SubmoduleRemap.end() && "Invalid index into submodule index 
remap");
```

The root cause of the problem that to deserialize `OPENCL_EXTENSION_DECLS`
section `ASTReader` needs to deserialize a Decl contained in it. In turn,
deserializing a Decl requires information about whether this declaration is
part of a (sub)module, but this information is not read yet because it is
located further in a module file.

Reviewers: Anastasia, yaxunl, JDevlieghere

Reviewed By: Anastasia

Subscribers: sidorovd, cfe-commits, asavonic

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

Added:
cfe/trunk/test/SemaOpenCL/extension-begin.h
Modified:
cfe/trunk/lib/Serialization/ASTWriter.cpp
cfe/trunk/test/SemaOpenCL/extension-begin.cl

Modified: cfe/trunk/lib/Serialization/ASTWriter.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Serialization/ASTWriter.cpp?rev=345497&r1=345496&r2=345497&view=diff
==
--- cfe/trunk/lib/Serialization/ASTWriter.cpp (original)
+++ cfe/trunk/lib/Serialization/ASTWriter.cpp Mon Oct 29 04:14:01 2018
@@ -5014,13 +5014,16 @@ ASTFileSignature ASTWriter::WriteASTCore
   WriteFPPragmaOptions(SemaRef.getFPOptions());
   WriteOpenCLExtensions(SemaRef);
   WriteOpenCLExtensionTypes(SemaRef);
-  WriteOpenCLExtensionDecls(SemaRef);
   WriteCUDAPragmas(SemaRef);
 
   // If we're emitting a module, write out the submodule information.
   if (WritingModule)
 WriteSubmodules(WritingModule);
 
+  // We need to have information about submodules to correctly deserialize
+  // decls from OpenCLExtensionDecls block
+  WriteOpenCLExtensionDecls(SemaRef);
+
   Stream.EmitRecord(SPECIAL_TYPES, SpecialTypes);
 
   // Write the record containing external, unnamed definitions.

Modified: cfe/trunk/test/SemaOpenCL/extension-begin.cl
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/SemaOpenCL/extension-begin.cl?rev=345497&r1=345496&r2=345497&view=diff
==
--- cfe/trunk/test/SemaOpenCL/extension-begin.cl (original)
+++ cfe/trunk/test/SemaOpenCL/extension-begin.cl Mon Oct 29 04:14:01 2018
@@ -1,37 +1,29 @@
 // Test this without pch.
-// RUN: %clang_cc1 %s -DHEADER -DHEADER_USER -triple spir-unknown-unknown 
-verify -pedantic -fsyntax-only
+// RUN: %clang_cc1 %s -triple spir-unknown-unknown -verify -pedantic 
-fsyntax-only
 
 // Test with pch.
-// RUN: %clang_cc1 %s -DHEADER -triple spir-unknown-unknown -emit-pch -o %t 
-verify -pedantic
-// RUN: %clang_cc1 %s -DHEADER_USER -triple spir-unknown-unknown -include-pch 
%t -fsyntax-only -verify -pedantic
+// RUN: %clang_cc1 -x cl %S/extension-begin.h -triple spir-unknown-unknown 
-emit-pch -o %t.pch -pedantic
+// RUN: %clang_cc1 %s -triple spir-unknown-unknown -include-pch %t.pch 
-DIMPLICIT_INCLUDE -DUSE_PCH -fsyntax-only -verify -pedantic
 
-#if defined(HEADER) && !defined(INCLUDED)
-#define INCLUDED 
-
-#pragma OPENCL EXTENSION all : begin // expected-warning {{expected 'disable' 
- ignoring}}
-#pragma OPENCL EXTENSION all : end // expected-warning {{expected 'disable' - 
ignoring}}
-
-#pragma OPENCL EXTENSION my_ext : begin 
-
-struct A {
-  int a;
-};
-
-typedef struct A TypedefOfA;
-typedef const TypedefOfA* PointerOfA;
-
-void f(void);
-
-__attribute__((overloadable)) void g(long x);
-
-#pragma OPENCL EXTENSION my_ext : end
-#pragma OPENCL EXTENSION my_ext : end // expected-warning {{OpenCL extension 
end directive mismatches begin directive - ignoring}}
-
-__attribute__((overloadable)) void g(void);
-
-#endif // defined(HEADER) && !defined(INCLUDED)
-
-#ifdef HEADER_USER
+// Test with modules
+// RUN: rm -rf %t.modules
+// RUN: mkdir -p %t.modules
+//
+// RUN: %clang_cc1 -cl-std=CL1.2 -DIMPLICIT_INCLUDE -include 
%S/extension-begin.h -triple spir-unknown-unknown -O0 -emit-llvm -o - -fmodules 
-fimplicit-module-maps -fmodules-cache-path=%t.modules %s -verify -pedantic
+//
+// RUN: rm -rf %t.modules
+// RUN: mkdir -p %t.modules
+//
+// RUN: %clang_cc1 -cl-std=CL2.0 -DIMPLICIT_INCLUDE -include 
%S/extension-begin.h -triple spir-unknown-unknown -O0 -emit-llvm -o - -fmodules 
-fimplicit-module-maps -fmodules-cache-path=%t.modules %s -verify -pedantic
+
+#ifndef IMPLICIT_INCLUDE
+#include "extension-begin.h"
+#endif // IMPLICIT_INCLUDE
+#ifndef USE_PCH
+// expected-warning@extension-begin.h:4 {{expected 'disable' - ignoring}}
+// expected-warning@extension-begin.h:5 {{expect

[PATCH] D53200: [OpenCL] Fix serialization of OpenCLExtensionDecls

2018-10-29 Thread Andrew Savonichev via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rC345497: [OpenCL] Fix serialization of OpenCLExtensionDecls 
(authored by asavonic, committed by ).

Repository:
  rC Clang

https://reviews.llvm.org/D53200

Files:
  lib/Serialization/ASTWriter.cpp
  test/SemaOpenCL/extension-begin.cl
  test/SemaOpenCL/extension-begin.h

Index: test/SemaOpenCL/extension-begin.h
===
--- test/SemaOpenCL/extension-begin.h
+++ test/SemaOpenCL/extension-begin.h
@@ -0,0 +1,26 @@
+#ifndef INCLUDED
+#define INCLUDED
+
+#pragma OPENCL EXTENSION all : begin
+#pragma OPENCL EXTENSION all : end
+
+#pragma OPENCL EXTENSION my_ext : begin
+
+struct A {
+  int a;
+};
+
+typedef struct A TypedefOfA;
+typedef const __private TypedefOfA* PointerOfA;
+
+void f(void);
+
+__attribute__((overloadable)) void g(long x);
+
+#pragma OPENCL EXTENSION my_ext : end
+#pragma OPENCL EXTENSION my_ext : end
+
+__attribute__((overloadable)) void g(void);
+
+#endif // INCLUDED
+
Index: test/SemaOpenCL/extension-begin.cl
===
--- test/SemaOpenCL/extension-begin.cl
+++ test/SemaOpenCL/extension-begin.cl
@@ -1,37 +1,29 @@
 // Test this without pch.
-// RUN: %clang_cc1 %s -DHEADER -DHEADER_USER -triple spir-unknown-unknown -verify -pedantic -fsyntax-only
+// RUN: %clang_cc1 %s -triple spir-unknown-unknown -verify -pedantic -fsyntax-only
 
 // Test with pch.
-// RUN: %clang_cc1 %s -DHEADER -triple spir-unknown-unknown -emit-pch -o %t -verify -pedantic
-// RUN: %clang_cc1 %s -DHEADER_USER -triple spir-unknown-unknown -include-pch %t -fsyntax-only -verify -pedantic
+// RUN: %clang_cc1 -x cl %S/extension-begin.h -triple spir-unknown-unknown -emit-pch -o %t.pch -pedantic
+// RUN: %clang_cc1 %s -triple spir-unknown-unknown -include-pch %t.pch -DIMPLICIT_INCLUDE -DUSE_PCH -fsyntax-only -verify -pedantic
 
-#if defined(HEADER) && !defined(INCLUDED)
-#define INCLUDED 
-
-#pragma OPENCL EXTENSION all : begin // expected-warning {{expected 'disable' - ignoring}}
-#pragma OPENCL EXTENSION all : end // expected-warning {{expected 'disable' - ignoring}}
-
-#pragma OPENCL EXTENSION my_ext : begin 
-
-struct A {
-  int a;
-};
-
-typedef struct A TypedefOfA;
-typedef const TypedefOfA* PointerOfA;
-
-void f(void);
-
-__attribute__((overloadable)) void g(long x);
-
-#pragma OPENCL EXTENSION my_ext : end
-#pragma OPENCL EXTENSION my_ext : end // expected-warning {{OpenCL extension end directive mismatches begin directive - ignoring}}
-
-__attribute__((overloadable)) void g(void);
-
-#endif // defined(HEADER) && !defined(INCLUDED)
-
-#ifdef HEADER_USER
+// Test with modules
+// RUN: rm -rf %t.modules
+// RUN: mkdir -p %t.modules
+//
+// RUN: %clang_cc1 -cl-std=CL1.2 -DIMPLICIT_INCLUDE -include %S/extension-begin.h -triple spir-unknown-unknown -O0 -emit-llvm -o - -fmodules -fimplicit-module-maps -fmodules-cache-path=%t.modules %s -verify -pedantic
+//
+// RUN: rm -rf %t.modules
+// RUN: mkdir -p %t.modules
+//
+// RUN: %clang_cc1 -cl-std=CL2.0 -DIMPLICIT_INCLUDE -include %S/extension-begin.h -triple spir-unknown-unknown -O0 -emit-llvm -o - -fmodules -fimplicit-module-maps -fmodules-cache-path=%t.modules %s -verify -pedantic
+
+#ifndef IMPLICIT_INCLUDE
+#include "extension-begin.h"
+#endif // IMPLICIT_INCLUDE
+#ifndef USE_PCH
+// expected-warning@extension-begin.h:4 {{expected 'disable' - ignoring}}
+// expected-warning@extension-begin.h:5 {{expected 'disable' - ignoring}}
+// expected-warning@extension-begin.h:21 {{OpenCL extension end directive mismatches begin directive - ignoring}}
+#endif // USE_PCH
 
 #pragma OPENCL EXTENSION my_ext : enable
 void test_f1(void) {
@@ -48,9 +40,7 @@
   PointerOfA test_A_pointer; // expected-error {{use of type 'PointerOfA' (aka 'const struct A *') requires my_ext extension to be enabled}}
   f(); // expected-error {{use of declaration 'f' requires my_ext extension to be enabled}}
   g(0); // expected-error {{no matching function for call to 'g'}}
-// expected-note@-26 {{candidate unavailable as it requires OpenCL extension 'my_ext' to be disabled}}
-// expected-note@-22 {{candidate function not viable: requires 0 arguments, but 1 was provided}}
+// expected-note@extension-begin.h:18 {{candidate unavailable as it requires OpenCL extension 'my_ext' to be disabled}}
+// expected-note@extension-begin.h:23 {{candidate function not viable: requires 0 arguments, but 1 was provided}}
 }
 
-#endif // HEADER_USER
-
Index: lib/Serialization/ASTWriter.cpp
===
--- lib/Serialization/ASTWriter.cpp
+++ lib/Serialization/ASTWriter.cpp
@@ -5014,13 +5014,16 @@
   WriteFPPragmaOptions(SemaRef.getFPOptions());
   WriteOpenCLExtensions(SemaRef);
   WriteOpenCLExtensionTypes(SemaRef);
-  WriteOpenCLExtensionDecls(SemaRef);
   WriteCUDAPragmas(SemaRef);
 
   // If we're emitting a module, write out the submodu

[PATCH] D53701: [Analyzer] Record and process comparison of symbols instead of iterator positions in interator checkers

2018-10-29 Thread Umann Kristóf via Phabricator via cfe-commits
Szelethus added a comment.

Makes sense!




Comment at: lib/StaticAnalyzer/Checkers/IteratorChecker.cpp:39
 //currently treated as an lvalue.
 // * type-IIc, type-IIIc: compound values of iterator-typed objects, when the
 //iterator object is treated as an rvalue taken of a

Did you mean lazy compound values?



Comment at: lib/StaticAnalyzer/Checkers/IteratorChecker.cpp:174
 
-// Structure fo recording iterator comparisons. We needed to retrieve the
-// original comparison expression in assumptions.
-struct IteratorComparison {
+// Structure fo recording symbol comparisons. We need to retrieve the original
+// comparison expression in assumptions.

typo: for



Comment at: lib/StaticAnalyzer/Checkers/IteratorChecker.cpp:332-333
 BinaryOperator::Opcode getOpcode(const SymExpr *SE);
-const RegionOrSymbol getRegionOrSymbol(const SVal &Val);
-const ProgramStateRef processComparison(ProgramStateRef State,
-RegionOrSymbol LVal,
-RegionOrSymbol RVal, bool Equal);
-const ProgramStateRef saveComparison(ProgramStateRef State,
- const SymExpr *Condition, const SVal 
&LVal,
- const SVal &RVal, bool Eq);
-const IteratorComparison *loadComparison(ProgramStateRef State,
- const SymExpr *Condition);
+const ProgramStateRef saveComparison(ProgramStateRef State, SymbolRef 
Condition,
+ SymbolRef LSym, SymbolRef RSym, bool Eq);
+const SymbolComparison *loadComparison(ProgramStateRef State,

I think this name would be better if you added the new state to 
`CheckerContext` within this function (and making it `void`), or rename it to 
`getEvaluatedComparisonState`.



Comment at: lib/StaticAnalyzer/Checkers/IteratorChecker.cpp:373
 SymbolRef NewSym, SymbolRef CondSym, BinaryOperator::Opcode Opc);
+ProgramStateRef relateSymbols(ProgramStateRef State, SymbolRef Sym1,
+  SymbolRef Sym2, bool Equal);

I think `evaluateComparison` would be a more fitting name.



Comment at: lib/StaticAnalyzer/Checkers/IteratorChecker.cpp:1197-1199
   while (const auto *CBOR = Cont->getAs()) {
 Cont = CBOR->getSuperRegion();
   }

You will have to excuse me for commenting on something totally unrelated, but 
I'm afraid this may cause a crash, if the region returned by `getSuperRegion` 
is symbolic. I encountered this error when doing the exact same thing in my 
checker: D50892. Can something like this occur with this checker?



Comment at: lib/StaticAnalyzer/Checkers/IteratorChecker.cpp:2057-2058
   auto NewState = State->assume(comparison.castAs(), Equal);
+  if (!NewState)
+return nullptr;
+

It isn't obvious to me (at first) what happens here -- maybe document when this 
function will return with `nullptr`? When `relateSymbol` is called and checked 
whether the returned value is null or not, one could think that this symbolizes 
some sort of failure.


Repository:
  rC Clang

https://reviews.llvm.org/D53701



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


[PATCH] D33672: [analyzer] INT50-CPP. Do not cast to an out-of-range enumeration checker

2018-10-29 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman added inline comments.



Comment at: lib/StaticAnalyzer/Checkers/EnumCastOutOfRangeChecker.cpp:19
+//   of casting an integer value that is out of range
+//===--===//
+

ZaMaZaN4iK wrote:
> Szelethus wrote:
> > ZaMaZaN4iK wrote:
> > > aaron.ballman wrote:
> > > > If this check is intended to conform to CERT's INT50-CPP rule, you 
> > > > should put a link to the wiki entry for it here as well.
> > > Which wiki entry do you mean?
> > Maybe this one? 
> > https://wiki.sei.cmu.edu/confluence/display/cplusplus/INT50-CPP.+Do+not+cast+to+an+out-of-range+enumeration+value
> Added a note about CERT's coding standard recommendaation. Didn't add the 
> reference to web page because web pages can become broken. I think standard 
> and check names are quite good explanation for here
That was the wiki entry I was talking about, but we do typically add links 
directly to coding guidelines that we implement checks for (at least, we do in 
clang-tidy, perhaps the static analyzer has a different policy) -- it makes it 
easier for folks reading the code to reference the rationale behind why the 
check behaves the way it does. However, what you have is also fine -- it's 
searchable.



Comment at: test/Analysis/enum-cast-out-of-range.cpp:1
+// RUN: %clang_analyze_cc1 \
+// RUN:   -analyzer-checker=core,alpha.cplusplus.EnumCastOutOfRange \

Can you add a test for bit-field assignment. e.g.,
```
struct S {
  some_enum E : 4;
};

int main(void) {
  struct S s;
  s.E = 9;
}
```


https://reviews.llvm.org/D33672



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


[PATCH] D53812: [Analyzer] Iterator Checker - Forbid increments past the begin() and decrements past the end() of containers

2018-10-29 Thread Balogh , Ádám via Phabricator via cfe-commits
baloghadamsoftware created this revision.
baloghadamsoftware added a reviewer: NoQ.
baloghadamsoftware added a project: clang.
Herald added subscribers: donat.nagy, Szelethus, mikhail.ramalho, a.sidorin, 
rnkovacs, szepet, whisperity.
Herald added a reviewer: george.karpenkov.

Previously, the iterator range checker only warned upon dereference of 
iterators outside their valid range as well as increments and decrements of 
out-of range iterators where the result remains out-of range. However, the 
`C++` standard is more strict than this: decrementing `begin()` or inrementing 
`end()` results in undefined behavior even if the iterator is not dereferenced 
afterward. Coming back to the range once out-of-range is also undefined.

This patch corrects the behavior of the iterator range checker: warnings are 
given for any operation whose result is ahead of `begin()` or past the `end()` 
(which is the past-end iterator itself, thus now we are speaking of past 
past-end).


Repository:
  rC Clang

https://reviews.llvm.org/D53812

Files:
  lib/StaticAnalyzer/Checkers/IteratorChecker.cpp
  test/Analysis/iterator-range.cpp

Index: test/Analysis/iterator-range.cpp
===
--- test/Analysis/iterator-range.cpp
+++ test/Analysis/iterator-range.cpp
@@ -26,27 +26,6 @@
   *i; // expected-warning{{Iterator accessed outside of its range}}
 }
 
-void simple_good_begin(const std::vector &v) {
-  auto i = v.begin();
-  if (i != v.begin()) {
-clang_analyzer_warnIfReached();
-*--i; // no-warning
-  }
-}
-
-void simple_good_begin_negated(const std::vector &v) {
-  auto i = v.begin();
-  if (!(i == v.begin())) {
-clang_analyzer_warnIfReached();
-*--i; // no-warning
-  }
-}
-
-void simple_bad_begin(const std::vector &v) {
-  auto i = v.begin();
-  *--i; // expected-warning{{Iterator accessed outside of its range}}
-}
-
 void copy(const std::vector &v) {
   auto i1 = v.end();
   auto i2 = i1;
@@ -172,7 +151,7 @@
   auto i0 = L.cbegin();
   L.push_front(n);
   --i0;
-  *--i0; // expected-warning{{Iterator accessed outside of its range}}
+  --i0; // expected-warning{{Iterator accessed outside of its range}}
 }
 
 void good_pop_front(std::list &L, int n) {
@@ -184,7 +163,7 @@
 void bad_pop_front(std::list &L, int n) {
   auto i0 = ++L.cbegin();
   L.pop_front();
-  *--i0; // expected-warning{{Iterator accessed outside of its range}}
+  --i0; // expected-warning{{Iterator accessed outside of its range}}
 }
 
 void bad_move(std::list &L1, std::list &L2) {
@@ -200,3 +179,23 @@
   ++i0;
   *++i0; // expected-warning{{Iterator accessed outside of its range}}
 }
+
+void good_incr_begin(const std::list &L) {
+  auto i0 = L.begin();
+  ++i0; // no-warning
+}
+
+void bad_decr_begin(const std::list &L) {
+  auto i0 = L.begin();
+  --i0;  // expected-warning{{Iterator accessed outside of its range}}
+}
+
+void good_decr_end(const std::list &L) {
+  auto i0 = L.end();
+  --i0; // no-warning
+}
+
+void bad_incr_end(const std::list &L) {
+  auto i0 = L.end();
+  ++i0;  // expected-warning{{Iterator accessed outside of its range}}
+}
Index: lib/StaticAnalyzer/Checkers/IteratorChecker.cpp
===
--- lib/StaticAnalyzer/Checkers/IteratorChecker.cpp
+++ lib/StaticAnalyzer/Checkers/IteratorChecker.cpp
@@ -238,14 +238,17 @@
   void handleEraseAfter(CheckerContext &C, const SVal &Iter) const;
   void handleEraseAfter(CheckerContext &C, const SVal &Iter1,
 const SVal &Iter2) const;
+  void verifyIncrement(CheckerContext &C, const SVal &Iter) const;
+  void verifyDecrement(CheckerContext &C, const SVal &Iter) const;
   void verifyRandomIncrOrDecr(CheckerContext &C, OverloadedOperatorKind Op,
-  const SVal &RetVal, const SVal &LHS,
-  const SVal &RHS) const;
+  const SVal &LHS, const SVal &RHS) const;
   void verifyMatch(CheckerContext &C, const SVal &Iter,
const MemRegion *Cont) const;
   void verifyMatch(CheckerContext &C, const SVal &Iter1,
const SVal &Iter2) const;
-
+  IteratorPosition shiftPosition(CheckerContext &C, OverloadedOperatorKind Op,
+ const IteratorPosition &Pos,
+ const SVal &Distance) const;
   void reportOutOfRangeBug(const StringRef &Message, const SVal &Val,
CheckerContext &C, ExplodedNode *ErrNode) const;
   void reportMismatchedBug(const StringRef &Message, const SVal &Val1,
@@ -388,7 +391,8 @@
 bool hasLiveIterators(ProgramStateRef State, const MemRegion *Cont);
 bool isBoundThroughLazyCompoundVal(const Environment &Env,
const MemRegion *Reg);
-bool isOutOfRange(ProgramStateRef State, const IteratorPosition &Pos);
+bool isOutOfRange(ProgramStateRef State, const IteratorPosition &Pos,
+  bool IncludeEnd = false);
 b

[PATCH] D52857: [clang-query] Add non-exclusive output API

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

LGTM with some minor fixes.

At some point (not necessarily as part of this patch), you should also update 
`docs\ReleaseNotes.rst` to broadly list the new features you've been adding to 
clang-query.




Comment at: clang-query/QueryParser.cpp:285
+if (VarStr.empty())
+  return new InvalidQuery("expected variable name");
+if (Var == PQV_Invalid)

This seems incorrect to me; we expect the command identifier `output` here, 
don't we?



Comment at: clang-query/QueryParser.cpp:291-297
+if (QKind == PQK_Enable) {
+  Q = parseSetOutputKind();
+} else if (QKind == PQK_Disable) {
+  Q = parseSetOutputKind();
+} else {
+  llvm_unreachable("Invalid query kind");
+}

Elide braces here.


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D52857



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


[PATCH] D53514: os_log: make buffer size an integer constant expression.

2018-10-29 Thread Tim Northover via Phabricator via cfe-commits
t.p.northover added a comment.

Ping.


Repository:
  rC Clang

https://reviews.llvm.org/D53514



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


[PATCH] D41648: [clang-tidy] implement cppcoreguidelines macro rules

2018-10-29 Thread Roman Lebedev via Phabricator via cfe-commits
lebedev.ri added inline comments.



Comment at: clang-tidy/cppcoreguidelines/MacroUsageCheck.cpp:67
+
+  diag(MD->getLocation(), DiagnosticMessage);
+}

And once again, i'm going to bitch about useless diagnostic messages:
```
[1/357] Building CXX object 
src/CMakeFiles/rawspeed.dir/librawspeed/metadata/CameraMetaData.cpp.o
FAILED: src/CMakeFiles/rawspeed.dir/librawspeed/metadata/CameraMetaData.cpp.o 
/usr/bin/cmake -E __run_co_compile --tidy=/usr/local/bin/clang-tidy 
--source=../src/librawspeed/metadata/CameraMetaData.cpp -- 
/usr/local/bin/clang++  -DDEBUG -D_GLIBCXX_SANITIZE_VECTOR -Isrc 
-I../src/librawspeed -isystem ../src/external -std=c++14 -Wall -Wextra 
-Weverything -Wno-c++98-compat -Wno-c++98-compat-pedantic -Wno-conversion 
-Wno-covered-switch-default -Wno-deprecated -Wno-double-promotion 
-Wno-exit-time-destructors -Wno-global-constructors 
-Wno-gnu-zero-variadic-macro-arguments -Wno-old-style-cast -Wno-padded 
-Wno-switch-enum -Wno-unused-macros -Wno-unused-parameter -Wno-weak-vtables 
-Wno-zero-as-null-pointer-constant -Wextra-semi -O3 -fno-optimize-sibling-calls 
-fsanitize=address -fno-omit-frame-pointer -fno-common -U_FORTIFY_SOURCE 
-fsanitize-address-use-after-scope -fsanitize=undefined 
-fno-sanitize-recover=undefined -fsanitize=integer 
-fno-sanitize-recover=integer -fPIC   -march=native -g3 -ggdb3 -Werror -pthread 
-fopenmp=libomp -std=c++14 -MD -MT 
src/CMakeFiles/rawspeed.dir/librawspeed/metadata/CameraMetaData.cpp.o -MF 
src/CMakeFiles/rawspeed.dir/librawspeed/metadata/CameraMetaData.cpp.o.d -o 
src/CMakeFiles/rawspeed.dir/librawspeed/metadata/CameraMetaData.cpp.o -c 
../src/librawspeed/metadata/CameraMetaData.cpp
error: macro used to declare a constant; consider using a 'constexpr' constant 
[cppcoreguidelines-macro-usage,-warnings-as-errors]
error: macro used to declare a constant; consider using a 'constexpr' constant 
[cppcoreguidelines-macro-usage,-warnings-as-errors]
9174 warnings generated.
Suppressed 9172 warnings (9172 in non-user code).
Use -header-filter=.* to display errors from all non-system headers. Use 
-system-headers to display errors from system headers as well.
2 warnings treated as errors
ninja: build stopped: subcommand failed.
```
1. It complains about something that has to location (so it was declared in 
command line?)
2. I have absolutely no clue whatsoever on what macro it complains.
   And i don't really see a way to find it out, without modifying clang-tidy :/


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D41648



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


[PATCH] D52610: [Esan] Port cache frag to FreeBSD

2018-10-29 Thread David CARLIER via Phabricator via cfe-commits
devnexen added a comment.

ping working-set on FreeBSD does not seem doable.


Repository:
  rC Clang

https://reviews.llvm.org/D52610



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


[PATCH] D53814: Allow the analyzer to output to a SARIF file

2018-10-29 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman created this revision.
aaron.ballman added reviewers: dcoughlin, zaks.anna.
Herald added subscribers: dkrupp, donat.nagy, Szelethus, a.sidorin, mgorny.
Herald added a reviewer: george.karpenkov.

SARIF (https://github.com/oasis-tcs/sarif-spec) is a new draft standard 
interchange format for static analysis results that allows result viewers to be 
decoupled from the tool producing the analysis results. This patch allows users 
to specify SARIF as the output from the clang static analyzer so that the 
results can be read in by other tools. There are several such tools for 
consuming SARIF, such as extensions to Visual Studio and VSCode, as well as 
static analyzers like CodeSonar.

SARIF is JSON-based and the latest provisional specification can be found at: 
https://github.com/oasis-tcs/sarif-spec/blob/master/Documents/ProvisionalDrafts/sarif-v2.0-csd02-provisional.docx.
 GrammaTech sponsored the work to produce this patch and we will make any 
necessary changes if the draft standard changes before publication.


https://reviews.llvm.org/D53814

Files:
  Analysis/diagnostics/sarif-check.py
  Analysis/diagnostics/sarif-diagnostics-taint-test.c
  StaticAnalyzer/Core/CMakeLists.txt
  StaticAnalyzer/Core/SarifDiagnostics.cpp
  clang/StaticAnalyzer/Core/Analyses.def
  clang/StaticAnalyzer/Core/BugReporter/PathDiagnostic.h

Index: Analysis/diagnostics/sarif-diagnostics-taint-test.c
===
--- /dev/null
+++ Analysis/diagnostics/sarif-diagnostics-taint-test.c
@@ -0,0 +1,32 @@
+// RUN: %clang_analyze_cc1 -analyzer-checker=alpha.security.taint,debug.TaintTest %s -verify -analyzer-output=sarif -o %t.sarif | %python %S/sarif-check.py %s %t.sarif
+#include "../Inputs/system-header-simulator.h"
+
+int atoi(const char *nptr);
+
+void f(void) {
+  char s[80];
+  scanf("%s", s);
+  int d = atoi(s); // expected-warning {{tainted}}
+}
+
+int main(void) {
+  f();
+  return 0;
+}
+
+// Test the basics for sanity.
+// CHECK: sarifLog['version'].startswith("2.0.0")
+// CHECK: sarifLog['runs'][0]['tool']['fullName'] == "clang static analyzer"
+// CHECK: sarifLog['runs'][0]['tool']['name'] == "clang"
+// CHECK: sarifLog['runs'][0]['tool']['language'] == "en-US"
+
+// Test the specifics of this taint test.
+// CHECK: len(result(0)['codeFlows'][0]['threadFlows'][0]['locations']) == 2
+// CHECK: flow(0)['locations'][0]['step'] == 1
+// CHECK: flow(0)['locations'][0]['importance'] == "essential"
+// CHECK: flow(0)['locations'][0]['location']['message']['text'] == "Calling 'f'"
+// CHECK: flow(0)['locations'][0]['location']['physicalLocation']['region']['startLine'] == 13
+// CHECK: flow(0)['locations'][1]['step'] == 2
+// CHECK: flow(0)['locations'][1]['importance'] == "essential"
+// CHECK: flow(0)['locations'][1]['location']['message']['text'] == "tainted"
+// CHECK: flow(0)['locations'][1]['location']['physicalLocation']['region']['startLine'] == 9
Index: Analysis/diagnostics/sarif-check.py
===
--- /dev/null
+++ Analysis/diagnostics/sarif-check.py
@@ -0,0 +1,61 @@
+#!/usr/bin/env python
+
+import sys
+import subprocess
+import traceback
+import json
+
+testfile = sys.argv[1]
+with open(sys.argv[2]) as datafh:
+data = json.load(datafh)
+
+prefix = "CHECK: "
+
+def sarifLogFirstResult(idx):
+return data['runs'][0]['results'][idx]
+
+def threadFlow(idx):
+return data['runs'][0]['results'][0]['codeFlows'][0]['threadFlows'][idx]
+
+fails = 0
+passes = 0
+with open(testfile) as testfh:
+lineno = 0
+for line in iter(testfh.readline, ""):
+lineno += 1
+line = line.rstrip("\r\n")
+try:
+prefix_pos = line.index(prefix)
+except ValueError:
+continue
+check_expr = line[prefix_pos + len(prefix):]
+
+try:
+exception = None
+result = eval(check_expr, {"sarifLog":data,
+   "result":sarifLogFirstResult,
+   "flow":threadFlow})
+except Exception:
+result = False
+exception = traceback.format_exc().splitlines()[-1]
+
+if exception is not None:
+sys.stderr.write(
+"{file}:{line:d}: check threw exception: {expr}\n"
+"{file}:{line:d}: exception was: {exception}\n".format(
+file=testfile, line=lineno,
+expr=check_expr, exception=exception))
+fails += 1
+elif not result:
+sys.stderr.write(
+"{file}:{line:d}: check returned False: {expr}\n".format(
+file=testfile, line=lineno, expr=check_expr))
+fails += 1
+else:
+passes += 1
+
+if fails != 0:
+sys.exit("{} checks failed".format(fails))
+else:
+sys.stdout.write("{} checks passed\n".format(passes))
+
Index: StaticAnalyzer/Core/SarifDiagnostics.cpp
===

[PATCH] D53651: [clangd] Use thread pool for background indexing.

2018-10-29 Thread Ilya Biryukov via Phabricator via cfe-commits
ilya-biryukov added a comment.

Update from the offline meeting: decided to start with `llvm::ThreadPool` for 
background tasks and lower thread priorities for background tasks.




Comment at: clangd/index/Background.cpp:89
   }
-  QueueCV.notify_all();
+  QueueCV.notify_one();
 }

kadircet wrote:
> sammccall wrote:
> > I always forget the details of how these work :-\
> > Is it possible for the "one" notification to be consumed by a waiter on 
> > blockUntilIdleForTest?
> > 
> > In general I'm not sure whether the `notify_one` optimization is worth the 
> > correctness risk as the code evolves.
> Ah, you are right, a thread waiting for done might catch that one as well, 
> but I think it only applies to that one. Is there a possibility of 
> `blockUntilIdleForTest` and `enqueue` being called from different threads?
> 
> There is still the argument of code evolution, but I don't think we should 
> ever end up in a state in which an enqueue and a wait that will not consume 
> that enqueue should occur concurrently.
> but I don't think we should ever end up in a state in which an enqueue and a 
> wait that will not consume that enqueue should occur concurrently.

We definitely will, +1 to Sam's comment, please call `notify_all` here. It's 
too easy to deadlock with `notify_one`.
E.g. just from the top of my mind, we can easily start adding tasks from a 
different thread if we start watching for changes (to compile commands, to 
header dependencies, etc.)



Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D53651



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


[PATCH] D53781: [ASTMatchers] add a matcher for static locals

2018-10-29 Thread Joe Ranieri via Phabricator via cfe-commits
jranieri-grammatech added a comment.

I do.


Repository:
  rC Clang

https://reviews.llvm.org/D53781



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


r345502 - Add the isStaticLocal() AST matcher for matching on local static variables.

2018-10-29 Thread Aaron Ballman via cfe-commits
Author: aaronballman
Date: Mon Oct 29 06:47:56 2018
New Revision: 345502

URL: http://llvm.org/viewvc/llvm-project?rev=345502&view=rev
Log:
Add the isStaticLocal() AST matcher for matching on local static variables.

Patch by Joe Ranieri.

Modified:
cfe/trunk/docs/LibASTMatchersReference.html
cfe/trunk/include/clang/ASTMatchers/ASTMatchers.h
cfe/trunk/lib/ASTMatchers/Dynamic/Registry.cpp
cfe/trunk/unittests/ASTMatchers/ASTMatchersNarrowingTest.cpp

Modified: cfe/trunk/docs/LibASTMatchersReference.html
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/docs/LibASTMatchersReference.html?rev=345502&r1=345501&r2=345502&view=diff
==
--- cfe/trunk/docs/LibASTMatchersReference.html (original)
+++ cfe/trunk/docs/LibASTMatchersReference.html Mon Oct 29 06:47:56 2018
@@ -4123,6 +4123,18 @@ varDecl(isExternC())
 
 
 
+MatcherVarDecl>isStaticLocal
+Matches a static 
variable with local scope.
+
+Example matches y (matcher = varDecl(isStaticLocal()))
+void f() {
+  int x;
+  static int y;
+}
+static int z;
+
+
+
 MatcherVarDecl>isStaticStorageClass
 Matches 
variablefunction declarations that have "static" storage
 class specifier ("static" keyword) written in the source.

Modified: cfe/trunk/include/clang/ASTMatchers/ASTMatchers.h
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/ASTMatchers/ASTMatchers.h?rev=345502&r1=345501&r2=345502&view=diff
==
--- cfe/trunk/include/clang/ASTMatchers/ASTMatchers.h (original)
+++ cfe/trunk/include/clang/ASTMatchers/ASTMatchers.h Mon Oct 29 06:47:56 2018
@@ -3300,6 +3300,20 @@ AST_MATCHER_P(
   InnerMatcher.matches(*Initializer, Finder, Builder));
 }
 
+/// \brief Matches a static variable with local scope.
+///
+/// Example matches y (matcher = varDecl(isStaticLocal()))
+/// \code
+/// void f() {
+///   int x;
+///   static int y;
+/// }
+/// static int z;
+/// \endcode
+AST_MATCHER(VarDecl, isStaticLocal) {
+  return Node.isStaticLocal();
+}
+
 /// Matches a variable declaration that has function scope and is a
 /// non-static local variable.
 ///

Modified: cfe/trunk/lib/ASTMatchers/Dynamic/Registry.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/ASTMatchers/Dynamic/Registry.cpp?rev=345502&r1=345501&r2=345502&view=diff
==
--- cfe/trunk/lib/ASTMatchers/Dynamic/Registry.cpp (original)
+++ cfe/trunk/lib/ASTMatchers/Dynamic/Registry.cpp Mon Oct 29 06:47:56 2018
@@ -378,6 +378,7 @@ RegistryMaps::RegistryMaps() {
   REGISTER_MATCHER(isPure);
   REGISTER_MATCHER(isScoped);
   REGISTER_MATCHER(isSignedInteger);
+  REGISTER_MATCHER(isStaticLocal);
   REGISTER_MATCHER(isStaticStorageClass);
   REGISTER_MATCHER(isStruct);
   REGISTER_MATCHER(isTemplateInstantiation);

Modified: cfe/trunk/unittests/ASTMatchers/ASTMatchersNarrowingTest.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/unittests/ASTMatchers/ASTMatchersNarrowingTest.cpp?rev=345502&r1=345501&r2=345502&view=diff
==
--- cfe/trunk/unittests/ASTMatchers/ASTMatchersNarrowingTest.cpp (original)
+++ cfe/trunk/unittests/ASTMatchers/ASTMatchersNarrowingTest.cpp Mon Oct 29 
06:47:56 2018
@@ -667,6 +667,14 @@ TEST(Matcher, VarDecl_Storage) {
   EXPECT_TRUE(matches("void f() { static int X; }", M));
 }
 
+TEST(Matcher, VarDecl_IsStaticLocal) {
+  auto M = varDecl(isStaticLocal());
+  EXPECT_TRUE(matches("void f() { static int X; }", M));
+  EXPECT_TRUE(notMatches("static int X;", M));
+  EXPECT_TRUE(notMatches("void f() { int X; }", M));
+  EXPECT_TRUE(notMatches("int X;", M));
+}
+
 TEST(Matcher, VarDecl_StorageDuration) {
   std::string T =
 "void f() { int x; static int y; } int a;static int b;extern int c;";


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


[PATCH] D53781: [ASTMatchers] add a matcher for static locals

2018-10-29 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman closed this revision.
aaron.ballman added a comment.

Committed in r345502, thank you for the patch!


Repository:
  rC Clang

https://reviews.llvm.org/D53781



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


[PATCH] D51340: Add /Zc:DllexportInlines option to clang-cl

2018-10-29 Thread Hans Wennborg via Phabricator via cfe-commits
hans added a comment.

I've been thinking more about your example with static locals in lambda and how 
this works with regular dllexport.

It got me thinking more about the problem of exposing inline functions from a 
library. For example:

`lib.h`:

  #ifndef LIB_H
  #define LIB_H
  
  int foo();
  
  struct __declspec(dllimport) S {
int bar() { return foo(); }
  };
  
  #endif

`lib.cc`:

  #include "lib.h"
  
  int foo() { return 123; }

`main.cc`:

  #include "lib.h"
  
  int main() {
S s;
return s.bar();
  }

Here, Clang will not emit the body of `S::bar()`, because it references the 
non-dllimport function `foo()`, and trying to referencing `foo()` outside the 
library would result in a link error. This is what the 
`DLLImportFunctionVisitor` is used for. For the same reason, MSVC will also not 
inline dllimport functions.

Now, with `/Zc:dllexportInlines-`, we no longer mark `S::bar()` dllimport, and 
so we do emit it, causing that link error. The same problem happens with 
`-fvisibility-inlines-hidden`: substitute the `declspec` above for 
`__attribute__((visibility("default")))` above and try it:

  $ g++ -fvisibility=hidden -fvisibility-inlines-hidden -fpic -shared -o lib.so 
lib.cc
  $ g++ main.cc lib.so
  /tmp/cc557J3i.o: In function `S::bar()':
  main.cc:(.text._ZN1S3barEv[_ZN1S3barEv]+0xd): undefined reference to `foo()'

So this is a known issue with `-fvisibility-inlines-hidden`. This doesn't come 
up often in practice, but when it does the developer needs to deal with it.

However, the static local problem is much scarier, because that leads to 
run-time bugs:

`lib.h`:

  #ifndef LIB_H
  #define LIB_H
  
  inline int foo() { static int x = 0; return x++; }
  
  struct __attribute__((visibility("default"))) S {
int bar() { return foo(); }
int baz();
  };
  
  #endif

`lib.cc`:

  #include "lib.h"
  
  int S::baz() { return foo(); }

`main.cc`:

  #include 
  #include "lib.h"
  
  int main() {
S s;
printf("s.bar(): %d\n", s.bar());
printf("s.baz(): %d\n", s.baz());
return 0;
  }

If we build the program normally, we get the expected output:

  $ g++ lib.cc main.cc && ./a.out
  s.bar(): 0
  s.baz(): 1

but building as a shared library shows the problem:

  $ g++ -fvisibility=hidden -fvisibility-inlines-hidden -fpic -shared -o lib.so 
lib.cc
  $ g++ main.cc lib.so
  $ LD_LIBRARY_PATH=$PWD:$LD_LIBRARY_PATH ./a.out
  s.bar(): 0
  s.baz(): 0

Oops.

This does show that it's a pre-existing problem with the model of not exporting 
inline functions though. I don't think we need to solve this specifically for 
Windows, I think we should match what `-fvisibility-inlines-hidden` is doing.

And what about the lambdas?

`lib.h`:

  #ifndef LIB_H
  #define LIB_H
  
  struct __attribute__((visibility("default"))) S {
int bar() { return ([]() { static int x; return x++; })(); }
int baz();
  };
  
  #endif

`lib.cc`:

  #include "lib.h"
  
  int S::baz() { return bar(); }

  $ g++ -fvisibility=hidden -fvisibility-inlines-hidden -fpic -shared -o lib.so 
lib.cc && g++ main.cc lib.so && LD_LIBRARY_PATH=$PWD:$LD_LIBRARY_PATH ./a.out
  s.bar(): 0
  s.baz(): 1

Interesting, the lambda function and its static local are not hidden.

Either that's because they're applying the "static locals of hidden functions 
in visible decl contexts are visible" thing. Or alternatively, they never 
applied the hidden visibility to the lambda in the first place.

I'm not entirely sure what this means for the dllexport case though. Maybe the 
loop in the current patch is fine.


https://reviews.llvm.org/D51340



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


[PATCH] D53817: [clang-tidy] cppcoreguidelines-macro-usage: print macro names

2018-10-29 Thread Roman Lebedev via Phabricator via cfe-commits
lebedev.ri created this revision.
lebedev.ri added reviewers: JonasToth, aaron.ballman, hokein, xazax.hun, alexfh.
lebedev.ri added a project: clang-tools-extra.
Herald added subscribers: rnkovacs, kbarton, nemanjai.

The macro may not have location (or more generally, the location may not exist),
e.g. if it originates from compiler's command-line.

The check complains on all the macros, even those without the location info.
Which means, it only says it does not like it. What is 'it'? I have no idea.
If we don't print the name, then there is no way to deal with that situation.

And in general, not printing name here forces the user to try to understand,
given, the macro definition location, what is the macro name?
This isn't fun.

I suspect some more issues may crop up later.


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D53817

Files:
  clang-tidy/cppcoreguidelines/MacroUsageCheck.cpp
  clang-tidy/cppcoreguidelines/MacroUsageCheck.h
  test/clang-tidy/cppcoreguidelines-macro-usage-caps-only.cpp
  test/clang-tidy/cppcoreguidelines-macro-usage-custom.cpp
  test/clang-tidy/cppcoreguidelines-macro-usage.cpp

Index: test/clang-tidy/cppcoreguidelines-macro-usage.cpp
===
--- test/clang-tidy/cppcoreguidelines-macro-usage.cpp
+++ test/clang-tidy/cppcoreguidelines-macro-usage.cpp
@@ -4,15 +4,15 @@
 #define INCLUDE_GUARD
 
 #define PROBLEMATIC_CONSTANT 0
-// CHECK-MESSAGES: [[@LINE-1]]:9: warning: macro used to declare a constant; consider using a 'constexpr' constant
+// CHECK-MESSAGES: [[@LINE-1]]:9: warning: macro 'PROBLEMATIC_CONSTANT' used to declare a constant; consider using a 'constexpr' constant
 
 #define PROBLEMATIC_FUNCTION(x, y) ((a) > (b) ? (a) : (b))
-// CHECK-MESSAGES: [[@LINE-1]]:9: warning: function-like macro used; consider a 'constexpr' template function
+// CHECK-MESSAGES: [[@LINE-1]]:9: warning: function-like macro 'PROBLEMATIC_FUNCTION' used; consider a 'constexpr' template function
 
 #define PROBLEMATIC_VARIADIC(...) (__VA_ARGS__)
-// CHECK-MESSAGES: [[@LINE-1]]:9: warning: variadic macro used; consider using a 'constexpr' variadic template function
+// CHECK-MESSAGES: [[@LINE-1]]:9: warning: variadic macro 'PROBLEMATIC_VARIADIC' used; consider using a 'constexpr' variadic template function
 
 #define PROBLEMATIC_VARIADIC2(x, ...) (__VA_ARGS__)
-// CHECK-MESSAGES: [[@LINE-1]]:9: warning: variadic macro used; consider using a 'constexpr' variadic template function
+// CHECK-MESSAGES: [[@LINE-1]]:9: warning: variadic macro 'PROBLEMATIC_VARIADIC2' used; consider using a 'constexpr' variadic template function
 
 #endif
Index: test/clang-tidy/cppcoreguidelines-macro-usage-custom.cpp
===
--- test/clang-tidy/cppcoreguidelines-macro-usage-custom.cpp
+++ test/clang-tidy/cppcoreguidelines-macro-usage-custom.cpp
@@ -6,16 +6,16 @@
 #define INCLUDE_GUARD
 
 #define PROBLEMATIC_CONSTANT 0
-// CHECK-MESSAGES: [[@LINE-1]]:9: warning: macro used to declare a constant; consider using a 'constexpr' constant
+// CHECK-MESSAGES: [[@LINE-1]]:9: warning: macro 'PROBLEMATIC_CONSTANT' used to declare a constant; consider using a 'constexpr' constant
 
 #define PROBLEMATIC_FUNCTION(x, y) ((a) > (b) ? (a) : (b))
-// CHECK-MESSAGES: [[@LINE-1]]:9: warning: function-like macro used; consider a 'constexpr' template function
+// CHECK-MESSAGES: [[@LINE-1]]:9: warning: function-like macro 'PROBLEMATIC_FUNCTION' used; consider a 'constexpr' template function
 
 #define PROBLEMATIC_VARIADIC(...) (__VA_ARGS__)
-// CHECK-MESSAGES: [[@LINE-1]]:9: warning: variadic macro used; consider using a 'constexpr' variadic template function
+// CHECK-MESSAGES: [[@LINE-1]]:9: warning: variadic macro 'PROBLEMATIC_VARIADIC' used; consider using a 'constexpr' variadic template function
 
 #define PROBLEMATIC_VARIADIC2(x, ...) (__VA_ARGS__)
-// CHECK-MESSAGES: [[@LINE-1]]:9: warning: variadic macro used; consider using a 'constexpr' variadic template function
+// CHECK-MESSAGES: [[@LINE-1]]:9: warning: variadic macro 'PROBLEMATIC_VARIADIC2' used; consider using a 'constexpr' variadic template function
 
 #define DEBUG_CONSTANT 0
 #define DEBUG_FUNCTION(x, y) ((a) > (b) ? (a) : (b))
Index: test/clang-tidy/cppcoreguidelines-macro-usage-caps-only.cpp
===
--- test/clang-tidy/cppcoreguidelines-macro-usage-caps-only.cpp
+++ test/clang-tidy/cppcoreguidelines-macro-usage-caps-only.cpp
@@ -6,16 +6,16 @@
 #define INCLUDE_GUARD
 
 #define problematic_constant 0
-// CHECK-MESSAGES: [[@LINE-1]]:9: warning: macro definition does not define the macro name using all uppercase characters
+// CHECK-MESSAGES: [[@LINE-1]]:9: warning: macro definition does not define the macro name 'problematic_constant' using all uppercase characters
 
 #define problematic_function(x, y) ((a) > (b) ? (a) : (b))
-// CHECK-MESSAGES: [[@LINE-1]]:9: warning: macro definition d

[PATCH] D53770: Support g++ headers in include/g++

2018-10-29 Thread David Greene via Phabricator via cfe-commits
greened added inline comments.



Comment at: lib/Driver/ToolChains/Linux.cpp:927-928
   LibDir.str() + "/../include/c++",
+  // Some gcc installations put headers under "g++" without a
+  // version suffix.
+  LibDir.str() + "/../include/g++",

rsmith wrote:
> It'd be useful to say who this "some" is, so we can check whether this is 
> still a valid concern in the future.
I will try to find out where we got the package from.


Repository:
  rC Clang

https://reviews.llvm.org/D53770



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


[PATCH] D51340: Add /Zc:DllexportInlines option to clang-cl

2018-10-29 Thread Hans Wennborg via Phabricator via cfe-commits
hans added inline comments.



Comment at: clang/lib/Sema/SemaDeclCXX.cpp:5719
+  TSK != TSK_ExplicitInstantiationDeclaration &&
+  TSK != TSK_ExplicitInstantiationDefinition) {
+if (ClassExported) {

takuto.ikuta wrote:
> takuto.ikuta wrote:
> > takuto.ikuta wrote:
> > > hans wrote:
> > > > takuto.ikuta wrote:
> > > > > hans wrote:
> > > > > > I still don't understand why we need these checks for template 
> > > > > > instantiations. Why does it matter whether the functions get 
> > > > > > inlined or not?
> > > > > When function of dllimported class is not inlined, such funtion needs 
> > > > > to be dllexported from implementation library.
> > > > > 
> > > > > c.h
> > > > > ```
> > > > > template
> > > > > class EXPORT C {
> > > > >  public:
> > > > >   void f() {}
> > > > > };
> > > > > ```
> > > > > 
> > > > > cuser.cc
> > > > > ```
> > > > > #include "c.h"
> > > > > 
> > > > > void cuser() {
> > > > >   C c;
> > > > >   c.f();  // This function may not be inlined when EXPORT is 
> > > > > __declspec(dllimport), so link may fail.
> > > > > }
> > > > > ```
> > > > > 
> > > > > When cuser.cc and c.h are built to different library, cuser.cc needs 
> > > > > to be able to see dllexported C::f() when C::f() is not inlined.
> > > > > This is my understanding.
> > > > Your example doesn't use explicit instantiation definition or 
> > > > declaration, so doesn't apply here I think.
> > > > 
> > > > As long as the dllexport and dllimport attributes matches it's fine. It 
> > > > doesn't matter whether the function gets inlined or not, the only thing 
> > > > that matters is that if it's marked dllimport on the "consumer side", 
> > > > it must be dllexport when building the dll.
> > > Hmm, I changed the linkage for functions having 
> > > DLLExport/ImportStaticLocal Attr.
> > > 
> > I changed linkage in ASTContext so that inline function is emitted when it 
> > is necessary when we use fno-dllexport-inlines.
> I revived explicit template instantiation check. 
> Found that this is necessary.
> 
> For explicit template instantiation, inheriting dll attribute from function 
> for local static var is run before inheriting dll attribute from class for 
> member functions. So I cannot detect local static var of inline function 
> after class level dll attribute processing for explicit template 
> instantiation.
> 
Oh I see, it's a static local problem..
Can you provide a concrete example that does not work without your check?
Maybe this is the right thing to do, but I would like to understand exactly 
what the problem is.


https://reviews.llvm.org/D51340



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


[PATCH] D53448: [OpenMP][NVPTX] Use single loops when generating code for distribute parallel for

2018-10-29 Thread Gheorghe-Teodor Bercea via Phabricator via cfe-commits
gtbercea updated this revision to Diff 171499.
gtbercea added a comment.

Fix comment.


Repository:
  rC Clang

https://reviews.llvm.org/D53448

Files:
  include/clang/AST/StmtOpenMP.h
  lib/AST/StmtOpenMP.cpp
  lib/CodeGen/CGOpenMPRuntime.cpp
  lib/CodeGen/CGOpenMPRuntime.h
  lib/CodeGen/CGOpenMPRuntimeNVPTX.cpp
  lib/CodeGen/CGOpenMPRuntimeNVPTX.h
  lib/CodeGen/CGStmtOpenMP.cpp
  lib/Sema/SemaOpenMP.cpp
  lib/Serialization/ASTReaderStmt.cpp
  lib/Serialization/ASTWriterStmt.cpp
  test/OpenMP/distribute_parallel_for_codegen.cpp
  test/OpenMP/distribute_parallel_for_simd_codegen.cpp
  test/OpenMP/nvptx_target_teams_distribute_parallel_for_codegen.cpp

Index: test/OpenMP/nvptx_target_teams_distribute_parallel_for_codegen.cpp
===
--- test/OpenMP/nvptx_target_teams_distribute_parallel_for_codegen.cpp
+++ test/OpenMP/nvptx_target_teams_distribute_parallel_for_codegen.cpp
@@ -112,13 +112,89 @@
 // CHECK: call void @__kmpc_for_static_fini(
 // CHECK: ret void
 
+// Distribute with collapse(2)
 // CHECK: define {{.*}}void {{@__omp_offloading_.+}}({{.+}}, i{{32|64}} [[F_IN:%.+]])
+// CHECK: alloca
+// CHECK: alloca
+// CHECK: alloca
+// CHECK: alloca
+// CHECK: [[OMP_IV:%.+]] = alloca
+// CHECK: alloca
+// CHECK: alloca
+// CHECK: [[OMP_LB:%.+]] = alloca
+// CHECK: [[OMP_UB:%.+]] = alloca
+// CHECK: [[OMP_ST:%.+]] = alloca
 // CHECK: store {{.+}} [[F_IN]], {{.+}}* {{.+}},
 // CHECK-DAG: [[THREAD_LIMIT:%.+]] = call i32 @llvm.nvvm.read.ptx.sreg.ntid.x()
 // CHECK: call void @__kmpc_spmd_kernel_init(i32 [[THREAD_LIMIT]], i16 0, i16 0)
 // CHECK: store {{.+}} 99, {{.+}}* [[COMB_UB:%.+]], align
 // CHECK: call void @__kmpc_for_static_init_4({{.+}}, {{.+}}, {{.+}} 91, {{.+}}, {{.+}}, {{.+}}* [[COMB_UB]],
-// CHECK: {{call|invoke}} void [[OUTL4:@.+]](
+
+// check EUB for distribute
+// CHECK-DAG: [[OMP_UB_VAL_1:%.+]] = load{{.+}} [[OMP_UB]],
+// CHECK-DAG: [[CMP_UB_NUM_IT:%.+]] = icmp sgt {{.+}}  [[OMP_UB_VAL_1]], 99
+// CHECK: br {{.+}} [[CMP_UB_NUM_IT]], label %[[EUB_TRUE:.+]], label %[[EUB_FALSE:.+]]
+// CHECK-DAG: [[EUB_TRUE]]:
+// CHECK: br label %[[EUB_END:.+]]
+// CHECK-DAG: [[EUB_FALSE]]:
+// CHECK: [[OMP_UB_VAL2:%.+]] = load{{.+}} [[OMP_UB]],
+// CHECK: br label %[[EUB_END]]
+// CHECK-DAG: [[EUB_END]]:
+// CHECK-DAG: [[EUB_RES:%.+]] = phi{{.+}} [ 99, %[[EUB_TRUE]] ], [ [[OMP_UB_VAL2]], %[[EUB_FALSE]] ]
+// CHECK: store{{.+}} [[EUB_RES]], {{.+}}* [[OMP_UB]],
+
+// initialize omp.iv
+// CHECK: [[OMP_LB_VAL_1:%.+]] = load{{.+}}, {{.+}}* [[OMP_LB]],
+// CHECK: store {{.+}} [[OMP_LB_VAL_1]], {{.+}}* [[OMP_IV]],
+
+// check exit condition
+// CHECK-DAG: [[OMP_IV_VAL_1:%.+]] = load {{.+}} [[OMP_IV]],
+// CHECK: [[CMP_IV_UB:%.+]] = icmp sle {{.+}} [[OMP_IV_VAL_1]], 100
+// CHECK: br {{.+}} [[CMP_IV_UB]], label %[[DIST_INNER_LOOP_BODY:.+]], label %[[DIST_INNER_LOOP_END:.+]]
+
+// check that PrevLB and PrevUB are passed to the 'for'
+// CHECK: [[DIST_INNER_LOOP_BODY]]:
+// CHECK-DAG: [[OMP_PREV_LB:%.+]] = load {{.+}}, {{.+}} [[OMP_LB]],
+// CHECK-64-DAG: [[OMP_PREV_LB_EXT:%.+]] = zext {{.+}} [[OMP_PREV_LB]] to {{.+}}
+// CHECK-DAG: [[OMP_PREV_UB:%.+]] = load {{.+}}, {{.+}} [[OMP_UB]],
+// CHECK-64-DAG: [[OMP_PREV_UB_EXT:%.+]] = zext {{.+}} [[OMP_PREV_UB]] to {{.+}}
+
+// check that distlb and distub are properly passed to the outlined function
+// CHECK-32: {{call|invoke}} void [[OUTL4:@.+]]({{.*}} i32 [[OMP_PREV_LB]], i32 [[OMP_PREV_UB]]
+// CHECK-64: {{call|invoke}} void [[OUTL4:@.+]]({{.*}} i64 [[OMP_PREV_LB_EXT]], i64 [[OMP_PREV_UB_EXT]]
+
+// check DistInc
+// CHECK-DAG: [[OMP_IV_VAL_3:%.+]] = load {{.+}}, {{.+}}* [[OMP_IV]],
+// CHECK-DAG: [[OMP_ST_VAL_1:%.+]] = load {{.+}}, {{.+}}* [[OMP_ST]],
+// CHECK: [[OMP_IV_INC:%.+]] = add{{.+}} [[OMP_IV_VAL_3]], [[OMP_ST_VAL_1]]
+// CHECK: store{{.+}} [[OMP_IV_INC]], {{.+}}* [[OMP_IV]],
+// CHECK-DAG: [[OMP_LB_VAL_2:%.+]] = load{{.+}}, {{.+}} [[OMP_LB]],
+// CHECK-DAG: [[OMP_ST_VAL_2:%.+]] = load{{.+}}, {{.+}} [[OMP_ST]],
+// CHECK-DAG: [[OMP_LB_NEXT:%.+]] = add{{.+}} [[OMP_LB_VAL_2]], [[OMP_ST_VAL_2]]
+// CHECK: store{{.+}} [[OMP_LB_NEXT]], {{.+}}* [[OMP_LB]],
+// CHECK-DAG: [[OMP_UB_VAL_5:%.+]] = load{{.+}}, {{.+}} [[OMP_UB]],
+// CHECK-DAG: [[OMP_ST_VAL_3:%.+]] = load{{.+}}, {{.+}} [[OMP_ST]],
+// CHECK-DAG: [[OMP_UB_NEXT:%.+]] = add{{.+}} [[OMP_UB_VAL_5]], [[OMP_ST_VAL_3]]
+// CHECK: store{{.+}} [[OMP_UB_NEXT]], {{.+}}* [[OMP_UB]],
+
+// Update UB
+// CHECK-DAG: [[OMP_UB_VAL_6:%.+]] = load{{.+}}, {{.+}} [[OMP_UB]],
+// CHECK-DAG: [[CMP_UB_NUM_IT_1:%.+]] = icmp sgt {{.+}}[[OMP_UB_VAL_6]], 99
+// CHECK: br {{.+}} [[CMP_UB_NUM_IT_1]], label %[[EUB_TRUE_1:.+]], label %[[EUB_FALSE_1:.+]]
+// CHECK-DAG: [[EUB_TRUE_1]]:
+// CHECK: br label %[[EUB_END_1:.+]]
+// CHECK-DAG: [[EUB_FALSE_1]]:
+// CHECK: [[OMP_UB_VAL3:%.+]] = load{{.+}} [[OMP_UB]],
+// CHECK: br label %[[EUB_END_1]]
+// CHECK-DAG: [[EUB_END_1]]:
+// CHECK-DAG: [[EUB_RES_1:%.+]] = phi{{.+}} [ 99, %[[EUB_TRUE_1]] ], [ [[OMP_UB_VAL3]], %[[EUB_FALSE_1]] ]

[PATCH] D53443: [OpenMP][NVPTX] Enable default scheduling for parallel for in non-SPMD cases.

2018-10-29 Thread Gheorghe-Teodor Bercea via Phabricator via cfe-commits
gtbercea added a comment.

ping


Repository:
  rC Clang

https://reviews.llvm.org/D53443



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


[PATCH] D53443: [OpenMP][NVPTX] Enable default scheduling for parallel for in non-SPMD cases.

2018-10-29 Thread Alexey Bataev via Phabricator via cfe-commits
ABataev accepted this revision.
ABataev added a comment.
This revision is now accepted and ready to land.

LG


Repository:
  rC Clang

https://reviews.llvm.org/D53443



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


r345505 - [OPENMP] Do not capture private loop counters.

2018-10-29 Thread Alexey Bataev via cfe-commits
Author: abataev
Date: Mon Oct 29 08:01:58 2018
New Revision: 345505

URL: http://llvm.org/viewvc/llvm-project?rev=345505&view=rev
Log:
[OPENMP] Do not capture private loop counters.

If the loop counter is not declared in the context of the loop and it is
private, such loop counters should not be captured in the outlined
regions.

Modified:
cfe/trunk/include/clang/Parse/Parser.h
cfe/trunk/include/clang/Sema/Sema.h
cfe/trunk/lib/CodeGen/CGStmtOpenMP.cpp
cfe/trunk/lib/Sema/SemaOpenMP.cpp
cfe/trunk/test/OpenMP/debug-info-openmp-array.cpp
cfe/trunk/test/OpenMP/parallel_for_codegen.cpp
cfe/trunk/test/OpenMP/taskloop_codegen.cpp
cfe/trunk/test/OpenMP/taskloop_firstprivate_messages.cpp
cfe/trunk/test/OpenMP/taskloop_reduction_codegen.cpp
cfe/trunk/test/OpenMP/taskloop_simd_firstprivate_messages.cpp

Modified: cfe/trunk/include/clang/Parse/Parser.h
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Parse/Parser.h?rev=345505&r1=345504&r2=345505&view=diff
==
--- cfe/trunk/include/clang/Parse/Parser.h (original)
+++ cfe/trunk/include/clang/Parse/Parser.h Mon Oct 29 08:01:58 2018
@@ -2144,6 +2144,8 @@ private:
   // 'for-init-statement' part of a 'for' statement.
   /// Returns true for declaration, false for expression.
   bool isForInitDeclaration() {
+if (getLangOpts().OpenMP)
+  Actions.startOpenMPLoop();
 if (getLangOpts().CPlusPlus)
   return isCXXSimpleDeclaration(/*AllowForRangeDecl=*/true);
 return isDeclarationSpecifier(true);

Modified: cfe/trunk/include/clang/Sema/Sema.h
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Sema/Sema.h?rev=345505&r1=345504&r2=345505&view=diff
==
--- cfe/trunk/include/clang/Sema/Sema.h (original)
+++ cfe/trunk/include/clang/Sema/Sema.h Mon Oct 29 08:01:58 2018
@@ -8686,6 +8686,10 @@ public:
   ExprResult getOpenMPCapturedExpr(VarDecl *Capture, ExprValueKind VK,
ExprObjectKind OK, SourceLocation Loc);
 
+  /// If the current region is a loop-based region, mark the start of the loop
+  /// construct.
+  void startOpenMPLoop();
+
   /// Check if the specified variable is used in 'private' clause.
   /// \param Level Relative level of nested OpenMP construct for that the check
   /// is performed.

Modified: cfe/trunk/lib/CodeGen/CGStmtOpenMP.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/CodeGen/CGStmtOpenMP.cpp?rev=345505&r1=345504&r2=345505&view=diff
==
--- cfe/trunk/lib/CodeGen/CGStmtOpenMP.cpp (original)
+++ cfe/trunk/lib/CodeGen/CGStmtOpenMP.cpp Mon Oct 29 08:01:58 2018
@@ -4949,10 +4949,16 @@ void CodeGenFunction::EmitSimpleOMPExecu
 if (isOpenMPSimdDirective(D.getDirectiveKind())) {
   emitOMPSimdRegion(CGF, cast(D), Action);
 } else {
+  OMPPrivateScope LoopGlobals(CGF);
   if (const auto *LD = dyn_cast(&D)) {
 for (const Expr *E : LD->counters()) {
-  if (const auto *VD = dyn_cast(
-  cast(E)->getDecl())) {
+  const auto *VD = dyn_cast(cast(E)->getDecl());
+  if (!VD->hasLocalStorage() && !CGF.LocalDeclMap.count(VD)) {
+LValue GlobLVal = CGF.EmitLValue(E);
+LoopGlobals.addPrivate(
+VD, [&GlobLVal]() { return GlobLVal.getAddress(); });
+  }
+  if (const auto *CED = dyn_cast(VD)) {
 // Emit only those that were not explicitly referenced in clauses.
 if (!CGF.LocalDeclMap.count(VD))
   CGF.EmitVarDecl(*VD);
@@ -4973,6 +4979,7 @@ void CodeGenFunction::EmitSimpleOMPExecu
   }
 }
   }
+  LoopGlobals.Privatize();
   CGF.EmitStmt(D.getInnermostCapturedStmt()->getCapturedStmt());
 }
   };

Modified: cfe/trunk/lib/Sema/SemaOpenMP.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Sema/SemaOpenMP.cpp?rev=345505&r1=345504&r2=345505&view=diff
==
--- cfe/trunk/lib/Sema/SemaOpenMP.cpp (original)
+++ cfe/trunk/lib/Sema/SemaOpenMP.cpp Mon Oct 29 08:01:58 2018
@@ -138,9 +138,11 @@ private:
 /// 'ordered' clause, the second one is true if the regions has 'ordered'
 /// clause, false otherwise.
 llvm::Optional> OrderedRegion;
+unsigned AssociatedLoops = 1;
+const Decl *PossiblyLoopCounter = nullptr;
 bool NowaitRegion = false;
 bool CancelRegion = false;
-unsigned AssociatedLoops = 1;
+bool LoopStart = false;
 SourceLocation InnerTeamsRegionLoc;
 /// Reference to the taskgroup task_reduction reference expression.
 Expr *TaskgroupReductionRef = nullptr;
@@ -208,6 +210,33 @@ public:
 Stack.back().first.pop_back();
   }
 
+  /// Marks that we're started loop parsing.
+  void loopInit() {
+assert(isOpenMPLoo

[PATCH] D53807: Create a diagnostic group for warn_call_to_pure_virtual_member_function_from_ctor_dtor, so it can be turned into an error using Werror

2018-10-29 Thread Arnaud Bienner via Phabricator via cfe-commits
ArnaudBienner updated this revision to Diff 171502.
ArnaudBienner added a comment.

Update tests


Repository:
  rC Clang

https://reviews.llvm.org/D53807

Files:
  include/clang/Basic/DiagnosticGroups.td
  include/clang/Basic/DiagnosticSemaKinds.td
  test/Misc/warning-flags.c
  test/SemaCXX/warn-pure-virtual-call-from-ctor-dtor.cpp


Index: test/SemaCXX/warn-pure-virtual-call-from-ctor-dtor.cpp
===
--- test/SemaCXX/warn-pure-virtual-call-from-ctor-dtor.cpp
+++ test/SemaCXX/warn-pure-virtual-call-from-ctor-dtor.cpp
@@ -1,4 +1,4 @@
-// RUN: %clang_cc1 %s -fsyntax-only -verify
+// RUN: %clang_cc1 %s -fsyntax-only -verify 
-Wcall-to-pure-virtual-from-ctor-dtor
 struct A {
   A() { f(); } // expected-warning {{call to pure virtual member function 'f' 
has undefined behavior; overrides of 'f' in subclasses are not available in the 
constructor of 'A'}}
   ~A() { f(); } // expected-warning {{call to pure virtual member function 'f' 
has undefined behavior; overrides of 'f' in subclasses are not available in the 
destructor of 'A'}}
Index: test/Misc/warning-flags.c
===
--- test/Misc/warning-flags.c
+++ test/Misc/warning-flags.c
@@ -18,7 +18,7 @@
 
 The list of warnings below should NEVER grow.  It should gradually shrink to 0.
 
-CHECK: Warnings without flags (76):
+CHECK: Warnings without flags (75):
 CHECK-NEXT:   ext_excess_initializers
 CHECK-NEXT:   ext_excess_initializers_in_char_array_initializer
 CHECK-NEXT:   ext_expected_semi_decl_list
@@ -40,7 +40,6 @@
 CHECK-NEXT:   warn_arcmt_nsalloc_realloc
 CHECK-NEXT:   warn_asm_label_on_auto_decl
 CHECK-NEXT:   warn_c_kext
-CHECK-NEXT:   warn_call_to_pure_virtual_member_function_from_ctor_dtor
 CHECK-NEXT:   warn_call_wrong_number_of_arguments
 CHECK-NEXT:   warn_case_empty_range
 CHECK-NEXT:   warn_char_constant_too_large
Index: include/clang/Basic/DiagnosticSemaKinds.td
===
--- include/clang/Basic/DiagnosticSemaKinds.td
+++ include/clang/Basic/DiagnosticSemaKinds.td
@@ -1656,7 +1656,7 @@
 def warn_call_to_pure_virtual_member_function_from_ctor_dtor : Warning<
   "call to pure virtual member function %0 has undefined behavior; "
   "overrides of %0 in subclasses are not available in the "
-  "%select{constructor|destructor}1 of %2">;
+  "%select{constructor|destructor}1 of %2">, 
InGroup;
 
 def select_special_member_kind : TextSubstitution<
   "%select{default constructor|copy constructor|move constructor|"
Index: include/clang/Basic/DiagnosticGroups.td
===
--- include/clang/Basic/DiagnosticGroups.td
+++ include/clang/Basic/DiagnosticGroups.td
@@ -285,6 +285,7 @@
 def FlagEnum : DiagGroup<"flag-enum">;
 def IncrementBool : DiagGroup<"increment-bool", [DeprecatedIncrementBool]>;
 def InfiniteRecursion : DiagGroup<"infinite-recursion">;
+def PureVirtualCallFromCtorDtor: 
DiagGroup<"call-to-pure-virtual-from-ctor-dtor">;
 def GNUImaginaryConstant : DiagGroup<"gnu-imaginary-constant">;
 def IgnoredQualifiers : DiagGroup<"ignored-qualifiers">;
 def : DiagGroup<"import">;


Index: test/SemaCXX/warn-pure-virtual-call-from-ctor-dtor.cpp
===
--- test/SemaCXX/warn-pure-virtual-call-from-ctor-dtor.cpp
+++ test/SemaCXX/warn-pure-virtual-call-from-ctor-dtor.cpp
@@ -1,4 +1,4 @@
-// RUN: %clang_cc1 %s -fsyntax-only -verify
+// RUN: %clang_cc1 %s -fsyntax-only -verify -Wcall-to-pure-virtual-from-ctor-dtor
 struct A {
   A() { f(); } // expected-warning {{call to pure virtual member function 'f' has undefined behavior; overrides of 'f' in subclasses are not available in the constructor of 'A'}}
   ~A() { f(); } // expected-warning {{call to pure virtual member function 'f' has undefined behavior; overrides of 'f' in subclasses are not available in the destructor of 'A'}}
Index: test/Misc/warning-flags.c
===
--- test/Misc/warning-flags.c
+++ test/Misc/warning-flags.c
@@ -18,7 +18,7 @@
 
 The list of warnings below should NEVER grow.  It should gradually shrink to 0.
 
-CHECK: Warnings without flags (76):
+CHECK: Warnings without flags (75):
 CHECK-NEXT:   ext_excess_initializers
 CHECK-NEXT:   ext_excess_initializers_in_char_array_initializer
 CHECK-NEXT:   ext_expected_semi_decl_list
@@ -40,7 +40,6 @@
 CHECK-NEXT:   warn_arcmt_nsalloc_realloc
 CHECK-NEXT:   warn_asm_label_on_auto_decl
 CHECK-NEXT:   warn_c_kext
-CHECK-NEXT:   warn_call_to_pure_virtual_member_function_from_ctor_dtor
 CHECK-NEXT:   warn_call_wrong_number_of_arguments
 CHECK-NEXT:   warn_case_empty_range
 CHECK-NEXT:   warn_char_constant_too_large
Index: include/clang/Basic/DiagnosticSemaKinds.td
===
--- include/clang/Basic/DiagnosticSemaKinds.td
+++ include/clang/Basic/Diag

[PATCH] D33672: [analyzer] INT50-CPP. Do not cast to an out-of-range enumeration checker

2018-10-29 Thread Alexander Zaitsev via Phabricator via cfe-commits
ZaMaZaN4iK updated this revision to Diff 171503.
ZaMaZaN4iK added a comment.

Add new test for enum bit field


https://reviews.llvm.org/D33672

Files:
  include/clang/StaticAnalyzer/Checkers/Checkers.td
  lib/StaticAnalyzer/Checkers/CMakeLists.txt
  lib/StaticAnalyzer/Checkers/EnumCastOutOfRangeChecker.cpp
  test/Analysis/enum-cast-out-of-range.cpp
  www/analyzer/alpha_checks.html

Index: www/analyzer/alpha_checks.html
===
--- www/analyzer/alpha_checks.html
+++ www/analyzer/alpha_checks.html
@@ -348,6 +348,24 @@
 }
 
 
+
+alpha.cplusplus.EnumCastOutOfRange
+(C++)
+  Check for integer to enumeration casts that could result in undefined values.
+
+  
+
+enum TestEnum {
+  A = 0
+};
+
+void foo() {
+  TestEnum t = static_cast(-1);
+  // warn: the value provided to the cast expression is not in
+   the valid range of values for the enum
+}
+
+
 
 
 alpha.cplusplus.InvalidatedIterator
Index: test/Analysis/enum-cast-out-of-range.cpp
===
--- /dev/null
+++ test/Analysis/enum-cast-out-of-range.cpp
@@ -0,0 +1,192 @@
+// RUN: %clang_analyze_cc1 \
+// RUN:   -analyzer-checker=core,alpha.cplusplus.EnumCastOutOfRange \
+// RUN:   -std=c++11 -verify %s
+
+enum unscoped_unspecified_t {
+  unscoped_unspecified_0 = -4,
+  unscoped_unspecified_1,
+  unscoped_unspecified_2 = 1,
+  unscoped_unspecified_3,
+  unscoped_unspecified_4 = 4
+};
+
+enum unscoped_specified_t : int {
+  unscoped_specified_0 = -4,
+  unscoped_specified_1,
+  unscoped_specified_2 = 1,
+  unscoped_specified_3,
+  unscoped_specified_4 = 4
+};
+
+enum class scoped_unspecified_t {
+  scoped_unspecified_0 = -4,
+  scoped_unspecified_1,
+  scoped_unspecified_2 = 1,
+  scoped_unspecified_3,
+  scoped_unspecified_4 = 4
+};
+
+enum class scoped_specified_t : int {
+  scoped_specified_0 = -4,
+  scoped_specified_1,
+  scoped_specified_2 = 1,
+  scoped_specified_3,
+  scoped_specified_4 = 4
+};
+
+struct S {
+unscoped_unspecified_t E : 5;
+};
+
+void unscopedUnspecified() {
+  unscoped_unspecified_t InvalidBeforeRangeBegin = static_cast(-5); // expected-warning {{the value provided to the cast expression is not in the valid range of values for the enum}}
+  unscoped_unspecified_t ValidNegativeValue1 = static_cast(-4); // OK.
+  unscoped_unspecified_t ValidNegativeValue2 = static_cast(-3); // OK.
+  unscoped_unspecified_t InvalidInsideRange1 = static_cast(-2); // expected-warning {{the value provided to the cast expression is not in the valid range of values for the enum}}
+  unscoped_unspecified_t InvalidInsideRange2 = static_cast(-1); // expected-warning {{the value provided to the cast expression is not in the valid range of values for the enum}}
+  unscoped_unspecified_t InvalidInsideRange3 = static_cast(0); // expected-warning {{the value provided to the cast expression is not in the valid range of values for the enum}}
+  unscoped_unspecified_t ValidPositiveValue1 = static_cast(1); // OK.
+  unscoped_unspecified_t ValidPositiveValue2 = static_cast(2); // OK.
+  unscoped_unspecified_t InvalidInsideRange4 = static_cast(3); // expected-warning {{the value provided to the cast expression is not in the valid range of values for the enum}}
+  unscoped_unspecified_t ValidPositiveValue3 = static_cast(4); // OK.
+  unscoped_unspecified_t InvalidAfterRangeEnd = static_cast(5); // expected-warning {{the value provided to the cast expression is not in the valid range of values for the enum}}
+}
+
+void unscopedSpecified() {
+  unscoped_specified_t InvalidBeforeRangeBegin = static_cast(-5); // expected-warning {{the value provided to the cast expression is not in the valid range of values for the enum}}
+  unscoped_specified_t ValidNegativeValue1 = static_cast(-4); // OK.
+  unscoped_specified_t ValidNegativeValue2 = static_cast(-3); // OK.
+  unscoped_specified_t InvalidInsideRange1 = static_cast(-2); // expected-warning {{the value provided to the cast expression is not in the valid range of values for the enum}}
+  unscoped_specified_t InvalidInsideRange2 = static_cast(-1); // expected-warning {{the value provided to the cast expression is not in the valid range of values for the enum}}
+  unscoped_specified_t InvalidInsideRange3 = static_cast(0); // expected-warning {{the value provided to the cast expression is not in the valid range of values for the enum}}
+  unscoped_specified_t ValidPositiveValue1 = static_cast(1); // OK.
+  unscoped_specified_t ValidPositiveValue2 = static_cast(2); // OK.
+  unscoped_specified_t InvalidInsideRange4 = static_cast(3); // expected-warning {{the value provided to the cast expression is not in the valid range of values for the enum}}
+  unscoped_specified_t ValidPositiveValue3 = static_cast(4); // OK.
+  unscoped_specified_t InvalidAfterRangeEnd = static_cast(5); // expected-warning {{the value provided to the cast expression is not in the valid range of values for the enum}}
+}
+
+vo

r345506 - [AST] Check that GNU range case statements are correctly imported.

2018-10-29 Thread Bruno Ricci via cfe-commits
Author: brunoricci
Date: Mon Oct 29 08:04:19 2018
New Revision: 345506

URL: http://llvm.org/viewvc/llvm-project?rev=345506&view=rev
Log:
[AST] Check that GNU range case statements are correctly imported.

The test for case statements did not cover GNU range case statements.

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

Reviewed By: rjmccall


Modified:
cfe/trunk/test/Import/switch-stmt/Inputs/F.cpp
cfe/trunk/test/Import/switch-stmt/test.cpp

Modified: cfe/trunk/test/Import/switch-stmt/Inputs/F.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/Import/switch-stmt/Inputs/F.cpp?rev=345506&r1=345505&r2=345506&view=diff
==
--- cfe/trunk/test/Import/switch-stmt/Inputs/F.cpp (original)
+++ cfe/trunk/test/Import/switch-stmt/Inputs/F.cpp Mon Oct 29 08:04:19 2018
@@ -3,12 +3,17 @@ void f() {
   case 1:
   case 2:
 break;
+  case 3 ... 4:
+  case 5 ... 5:
+break;
   }
   switch (int varname; 1) {
   case 1:
 break;
   case 2:
 break;
+  case 3 ... 5:
+break;
   }
   switch (1)
   default:

Modified: cfe/trunk/test/Import/switch-stmt/test.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/Import/switch-stmt/test.cpp?rev=345506&r1=345505&r2=345506&view=diff
==
--- cfe/trunk/test/Import/switch-stmt/test.cpp (original)
+++ cfe/trunk/test/Import/switch-stmt/test.cpp Mon Oct 29 08:04:19 2018
@@ -10,6 +10,13 @@
 // CHECK-NEXT: CaseStmt
 // CHECK-NEXT: IntegerLiteral
 // CHECK-NEXT: BreakStmt
+// CHECK-NEXT: CaseStmt
+// CHECK-NEXT: IntegerLiteral
+// CHECK-NEXT: IntegerLiteral
+// CHECK-NEXT: CaseStmt
+// CHECK-NEXT: IntegerLiteral
+// CHECK-NEXT: IntegerLiteral
+// CHECK-NEXT: BreakStmt
 
 // CHECK: SwitchStmt
 // CHECK-NEXT: DeclStmt
@@ -24,6 +31,10 @@
 // CHECK-NEXT: CaseStmt
 // CHECK-NEXT: IntegerLiteral
 // CHECK-NEXT: BreakStmt
+// CHECK-NEXT: CaseStmt
+// CHECK-NEXT: IntegerLiteral
+// CHECK-NEXT: IntegerLiteral
+// CHECK-NEXT: BreakStmt
 
 // CHECK: SwitchStmt
 // CHECK-NEXT: <>


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


[PATCH] D53610: [AST] Check that GNU range case statements are correctly imported.

2018-10-29 Thread Phabricator via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rC345506: [AST] Check that GNU range case statements are 
correctly imported. (authored by brunoricci, committed by ).

Repository:
  rC Clang

https://reviews.llvm.org/D53610

Files:
  test/Import/switch-stmt/Inputs/F.cpp
  test/Import/switch-stmt/test.cpp


Index: test/Import/switch-stmt/Inputs/F.cpp
===
--- test/Import/switch-stmt/Inputs/F.cpp
+++ test/Import/switch-stmt/Inputs/F.cpp
@@ -3,12 +3,17 @@
   case 1:
   case 2:
 break;
+  case 3 ... 4:
+  case 5 ... 5:
+break;
   }
   switch (int varname; 1) {
   case 1:
 break;
   case 2:
 break;
+  case 3 ... 5:
+break;
   }
   switch (1)
   default:
Index: test/Import/switch-stmt/test.cpp
===
--- test/Import/switch-stmt/test.cpp
+++ test/Import/switch-stmt/test.cpp
@@ -10,6 +10,13 @@
 // CHECK-NEXT: CaseStmt
 // CHECK-NEXT: IntegerLiteral
 // CHECK-NEXT: BreakStmt
+// CHECK-NEXT: CaseStmt
+// CHECK-NEXT: IntegerLiteral
+// CHECK-NEXT: IntegerLiteral
+// CHECK-NEXT: CaseStmt
+// CHECK-NEXT: IntegerLiteral
+// CHECK-NEXT: IntegerLiteral
+// CHECK-NEXT: BreakStmt
 
 // CHECK: SwitchStmt
 // CHECK-NEXT: DeclStmt
@@ -24,6 +31,10 @@
 // CHECK-NEXT: CaseStmt
 // CHECK-NEXT: IntegerLiteral
 // CHECK-NEXT: BreakStmt
+// CHECK-NEXT: CaseStmt
+// CHECK-NEXT: IntegerLiteral
+// CHECK-NEXT: IntegerLiteral
+// CHECK-NEXT: BreakStmt
 
 // CHECK: SwitchStmt
 // CHECK-NEXT: <>


Index: test/Import/switch-stmt/Inputs/F.cpp
===
--- test/Import/switch-stmt/Inputs/F.cpp
+++ test/Import/switch-stmt/Inputs/F.cpp
@@ -3,12 +3,17 @@
   case 1:
   case 2:
 break;
+  case 3 ... 4:
+  case 5 ... 5:
+break;
   }
   switch (int varname; 1) {
   case 1:
 break;
   case 2:
 break;
+  case 3 ... 5:
+break;
   }
   switch (1)
   default:
Index: test/Import/switch-stmt/test.cpp
===
--- test/Import/switch-stmt/test.cpp
+++ test/Import/switch-stmt/test.cpp
@@ -10,6 +10,13 @@
 // CHECK-NEXT: CaseStmt
 // CHECK-NEXT: IntegerLiteral
 // CHECK-NEXT: BreakStmt
+// CHECK-NEXT: CaseStmt
+// CHECK-NEXT: IntegerLiteral
+// CHECK-NEXT: IntegerLiteral
+// CHECK-NEXT: CaseStmt
+// CHECK-NEXT: IntegerLiteral
+// CHECK-NEXT: IntegerLiteral
+// CHECK-NEXT: BreakStmt
 
 // CHECK: SwitchStmt
 // CHECK-NEXT: DeclStmt
@@ -24,6 +31,10 @@
 // CHECK-NEXT: CaseStmt
 // CHECK-NEXT: IntegerLiteral
 // CHECK-NEXT: BreakStmt
+// CHECK-NEXT: CaseStmt
+// CHECK-NEXT: IntegerLiteral
+// CHECK-NEXT: IntegerLiteral
+// CHECK-NEXT: BreakStmt
 
 // CHECK: SwitchStmt
 // CHECK-NEXT: <>
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D53810: [analyzer][NFC] Refactor PlistDiagnostics to use a class instead of passing 9 parameters around

2018-10-29 Thread Umann Kristóf via Phabricator via cfe-commits
Szelethus updated this revision to Diff 171505.

https://reviews.llvm.org/D53810

Files:
  lib/StaticAnalyzer/Core/PlistDiagnostics.cpp

Index: lib/StaticAnalyzer/Core/PlistDiagnostics.cpp
===
--- lib/StaticAnalyzer/Core/PlistDiagnostics.cpp
+++ lib/StaticAnalyzer/Core/PlistDiagnostics.cpp
@@ -24,10 +24,16 @@
 #include "llvm/ADT/Statistic.h"
 #include "llvm/ADT/SmallVector.h"
 #include "llvm/Support/Casting.h"
+
 using namespace clang;
 using namespace ento;
 using namespace markup;
 
+//===--===//
+// Declarations of helper classes and functions for emitting bug reports in
+// plist format.
+//===--===//
+
 namespace {
   class PlistDiagnostics : public PathDiagnosticConsumer {
 const std::string OutputFile;
@@ -59,34 +65,91 @@
   };
 } // end anonymous namespace
 
-PlistDiagnostics::PlistDiagnostics(AnalyzerOptions &AnalyzerOpts,
-   const std::string& output,
-   const Preprocessor &PP,
-   bool supportsMultipleFiles)
-  : OutputFile(output), PP(PP), AnOpts(AnalyzerOpts),
-SupportsCrossFileDiagnostics(supportsMultipleFiles) {}
+namespace {
 
-void ento::createPlistDiagnosticConsumer(AnalyzerOptions &AnalyzerOpts,
- PathDiagnosticConsumers &C,
- const std::string& s,
- const Preprocessor &PP) {
-  C.push_back(new PlistDiagnostics(AnalyzerOpts, s, PP,
-   /*supportsMultipleFiles*/ false));
-}
+/// A helper class for emitting a single report.
+class PlistPrinter {
+  const FIDMap& FM;
+  AnalyzerOptions &AnOpts;
+  const Preprocessor &PP;
 
-void ento::createPlistMultiFileDiagnosticConsumer(AnalyzerOptions &AnalyzerOpts,
-  PathDiagnosticConsumers &C,
-  const std::string &s,
-  const Preprocessor &PP) {
-  C.push_back(new PlistDiagnostics(AnalyzerOpts, s, PP,
-   /*supportsMultipleFiles*/ true));
-}
+public:
+  PlistPrinter(const FIDMap& FM, AnalyzerOptions &AnOpts,
+   const Preprocessor &PP)
+: FM(FM), AnOpts(AnOpts), PP(PP) {
+  }
 
-static void EmitRanges(raw_ostream &o,
-   const ArrayRef Ranges,
-   const FIDMap& FM,
-   const Preprocessor &PP,
-   unsigned indent) {
+  void ReportDiag(raw_ostream &o, const PathDiagnosticPiece& P) {
+ReportPiece(o, P, /*indent*/ 4, /*depth*/ 0, /*includeControlFlow*/ true);
+
+// Don't emit a warning about an unused private field.
+(void)AnOpts;
+  }
+
+private:
+  void ReportPiece(raw_ostream &o, const PathDiagnosticPiece &P,
+   unsigned indent, unsigned depth, bool includeControlFlow,
+   bool isKeyEvent = false) {
+switch (P.getKind()) {
+  case PathDiagnosticPiece::ControlFlow:
+if (includeControlFlow)
+  ReportControlFlow(o, cast(P), indent);
+break;
+  case PathDiagnosticPiece::Call:
+ReportCall(o, cast(P), indent,
+   depth);
+break;
+  case PathDiagnosticPiece::Event:
+ReportEvent(o, cast(P), indent, depth,
+isKeyEvent);
+break;
+  case PathDiagnosticPiece::Macro:
+ReportMacro(o, cast(P), indent, depth);
+break;
+  case PathDiagnosticPiece::Note:
+ReportNote(o, cast(P), indent);
+break;
+}
+  }
+
+  void EmitRanges(raw_ostream &o, const ArrayRef Ranges,
+  unsigned indent);
+  void EmitMessage(raw_ostream &o, StringRef Message, unsigned indent);
+
+  void ReportControlFlow(raw_ostream &o,
+ const PathDiagnosticControlFlowPiece& P,
+ unsigned indent);
+  void ReportEvent(raw_ostream &o, const PathDiagnosticEventPiece& P,
+   unsigned indent, unsigned depth, bool isKeyEvent = false);
+  void ReportCall(raw_ostream &o, const PathDiagnosticCallPiece &P,
+  unsigned indent, unsigned depth);
+  void ReportMacro(raw_ostream &o, const PathDiagnosticMacroPiece& P,
+   unsigned indent, unsigned depth);
+  void ReportNote(raw_ostream &o, const PathDiagnosticNotePiece& P,
+  unsigned indent);
+};
+
+} // end of anonymous namespace
+
+static void printBugPath(llvm::raw_ostream &o, const FIDMap& FM,
+ AnalyzerOptions &AnOpts,
+ const Preprocessor &PP,
+ const PathPieces &Path);
+
+/// Print coverage information to output stream {@code o}.
+/// May modify the used list 

[PATCH] D53807: Create a diagnostic group for warn_call_to_pure_virtual_member_function_from_ctor_dtor, so it can be turned into an error using Werror

2018-10-29 Thread Arnaud Bienner via Phabricator via cfe-commits
ArnaudBienner added a reviewer: davide.
ArnaudBienner added a comment.

Hi Davide,

I see you the last person who updated the test file related to this feature.
Would you feel comfortable reviewing my patch?

This is my first clang patch, so I apologize in advance if I missed obvious 
things :)


Repository:
  rC Clang

https://reviews.llvm.org/D53807



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


[PATCH] D53807: Create a diagnostic group for warn_call_to_pure_virtual_member_function_from_ctor_dtor, so it can be turned into an error using Werror

2018-10-29 Thread Davide Italiano via Phabricator via cfe-commits
davide added a comment.

While it's true that I implemented this warning, I don't feel qualified enough 
to approve the introduction of a new flag to clang. Probably @rsmith should 
sign this off.


Repository:
  rC Clang

https://reviews.llvm.org/D53807



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


[PATCH] D33672: [analyzer] INT50-CPP. Do not cast to an out-of-range enumeration checker

2018-10-29 Thread Alexander Zaitsev via Phabricator via cfe-commits
ZaMaZaN4iK updated this revision to Diff 171506.
ZaMaZaN4iK marked 2 inline comments as done.
ZaMaZaN4iK added a comment.

Fix typedef -> using


https://reviews.llvm.org/D33672

Files:
  include/clang/StaticAnalyzer/Checkers/Checkers.td
  lib/StaticAnalyzer/Checkers/CMakeLists.txt
  lib/StaticAnalyzer/Checkers/EnumCastOutOfRangeChecker.cpp
  test/Analysis/enum-cast-out-of-range.cpp
  www/analyzer/alpha_checks.html

Index: www/analyzer/alpha_checks.html
===
--- www/analyzer/alpha_checks.html
+++ www/analyzer/alpha_checks.html
@@ -348,6 +348,24 @@
 }
 
 
+
+alpha.cplusplus.EnumCastOutOfRange
+(C++)
+  Check for integer to enumeration casts that could result in undefined values.
+
+  
+
+enum TestEnum {
+  A = 0
+};
+
+void foo() {
+  TestEnum t = static_cast(-1);
+  // warn: the value provided to the cast expression is not in
+   the valid range of values for the enum
+}
+
+
 
 
 alpha.cplusplus.InvalidatedIterator
Index: test/Analysis/enum-cast-out-of-range.cpp
===
--- /dev/null
+++ test/Analysis/enum-cast-out-of-range.cpp
@@ -0,0 +1,192 @@
+// RUN: %clang_analyze_cc1 \
+// RUN:   -analyzer-checker=core,alpha.cplusplus.EnumCastOutOfRange \
+// RUN:   -std=c++11 -verify %s
+
+enum unscoped_unspecified_t {
+  unscoped_unspecified_0 = -4,
+  unscoped_unspecified_1,
+  unscoped_unspecified_2 = 1,
+  unscoped_unspecified_3,
+  unscoped_unspecified_4 = 4
+};
+
+enum unscoped_specified_t : int {
+  unscoped_specified_0 = -4,
+  unscoped_specified_1,
+  unscoped_specified_2 = 1,
+  unscoped_specified_3,
+  unscoped_specified_4 = 4
+};
+
+enum class scoped_unspecified_t {
+  scoped_unspecified_0 = -4,
+  scoped_unspecified_1,
+  scoped_unspecified_2 = 1,
+  scoped_unspecified_3,
+  scoped_unspecified_4 = 4
+};
+
+enum class scoped_specified_t : int {
+  scoped_specified_0 = -4,
+  scoped_specified_1,
+  scoped_specified_2 = 1,
+  scoped_specified_3,
+  scoped_specified_4 = 4
+};
+
+struct S {
+unscoped_unspecified_t E : 5;
+};
+
+void unscopedUnspecified() {
+  unscoped_unspecified_t InvalidBeforeRangeBegin = static_cast(-5); // expected-warning {{the value provided to the cast expression is not in the valid range of values for the enum}}
+  unscoped_unspecified_t ValidNegativeValue1 = static_cast(-4); // OK.
+  unscoped_unspecified_t ValidNegativeValue2 = static_cast(-3); // OK.
+  unscoped_unspecified_t InvalidInsideRange1 = static_cast(-2); // expected-warning {{the value provided to the cast expression is not in the valid range of values for the enum}}
+  unscoped_unspecified_t InvalidInsideRange2 = static_cast(-1); // expected-warning {{the value provided to the cast expression is not in the valid range of values for the enum}}
+  unscoped_unspecified_t InvalidInsideRange3 = static_cast(0); // expected-warning {{the value provided to the cast expression is not in the valid range of values for the enum}}
+  unscoped_unspecified_t ValidPositiveValue1 = static_cast(1); // OK.
+  unscoped_unspecified_t ValidPositiveValue2 = static_cast(2); // OK.
+  unscoped_unspecified_t InvalidInsideRange4 = static_cast(3); // expected-warning {{the value provided to the cast expression is not in the valid range of values for the enum}}
+  unscoped_unspecified_t ValidPositiveValue3 = static_cast(4); // OK.
+  unscoped_unspecified_t InvalidAfterRangeEnd = static_cast(5); // expected-warning {{the value provided to the cast expression is not in the valid range of values for the enum}}
+}
+
+void unscopedSpecified() {
+  unscoped_specified_t InvalidBeforeRangeBegin = static_cast(-5); // expected-warning {{the value provided to the cast expression is not in the valid range of values for the enum}}
+  unscoped_specified_t ValidNegativeValue1 = static_cast(-4); // OK.
+  unscoped_specified_t ValidNegativeValue2 = static_cast(-3); // OK.
+  unscoped_specified_t InvalidInsideRange1 = static_cast(-2); // expected-warning {{the value provided to the cast expression is not in the valid range of values for the enum}}
+  unscoped_specified_t InvalidInsideRange2 = static_cast(-1); // expected-warning {{the value provided to the cast expression is not in the valid range of values for the enum}}
+  unscoped_specified_t InvalidInsideRange3 = static_cast(0); // expected-warning {{the value provided to the cast expression is not in the valid range of values for the enum}}
+  unscoped_specified_t ValidPositiveValue1 = static_cast(1); // OK.
+  unscoped_specified_t ValidPositiveValue2 = static_cast(2); // OK.
+  unscoped_specified_t InvalidInsideRange4 = static_cast(3); // expected-warning {{the value provided to the cast expression is not in the valid range of values for the enum}}
+  unscoped_specified_t ValidPositiveValue3 = static_cast(4); // OK.
+  unscoped_specified_t InvalidAfterRangeEnd = static_cast(5); // expected-warning {{the value provided to the cast expression is not in the valid range

[PATCH] D33672: [analyzer] INT50-CPP. Do not cast to an out-of-range enumeration checker

2018-10-29 Thread Alexander Zaitsev via Phabricator via cfe-commits
ZaMaZaN4iK added inline comments.



Comment at: lib/StaticAnalyzer/Checkers/EnumCastOutOfRangeChecker.cpp:36
+  const ProgramStateRef PS;
+  SValBuilder &SVB;
+

Szelethus wrote:
> You can acquire `SValBuilder` from `ProgramState`:
> `PS->getStateManager()->getSvalBuilder()`
Is there any difference? Is it critical to get `SValBuilder` from 
`CheckerContext' ?


https://reviews.llvm.org/D33672



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


[PATCH] D53810: [analyzer][NFC] Refactor PlistDiagnostics to use a class instead of passing 9 parameters around

2018-10-29 Thread Gábor Horváth via Phabricator via cfe-commits
xazax.hun added inline comments.



Comment at: lib/StaticAnalyzer/Core/PlistDiagnostics.cpp:82
 
-static void EmitRanges(raw_ostream &o,
-   const ArrayRef Ranges,
-   const FIDMap& FM,
-   const Preprocessor &PP,
-   unsigned indent) {
+  void ReportDiag(raw_ostream &o, const PathDiagnosticPiece& P) {
+ReportPiece(o, P, /*indent*/ 4, /*depth*/ 0, /*includeControlFlow*/ true);

The `raw_ostream` seems to be a common argument. MAybe it would be worth to 
make that a member too?


https://reviews.llvm.org/D53810



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


r345507 - [OpenMP][NVPTX] Enable default scheduling for parallel for in non-SPMD cases.

2018-10-29 Thread Gheorghe-Teodor Bercea via cfe-commits
Author: gbercea
Date: Mon Oct 29 08:23:23 2018
New Revision: 345507

URL: http://llvm.org/viewvc/llvm-project?rev=345507&view=rev
Log:
[OpenMP][NVPTX] Enable default scheduling for parallel for in non-SPMD cases.

Summary: This patch enables the choosing of the default schedule for parallel 
for loops even in non-SPMD cases.

Reviewers: ABataev, caomhin

Reviewed By: ABataev

Subscribers: jholewinski, guansong, cfe-commits

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

Modified:
cfe/trunk/lib/CodeGen/CGOpenMPRuntimeNVPTX.cpp
cfe/trunk/test/OpenMP/nvptx_parallel_for_codegen.cpp

Modified: cfe/trunk/lib/CodeGen/CGOpenMPRuntimeNVPTX.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/CodeGen/CGOpenMPRuntimeNVPTX.cpp?rev=345507&r1=345506&r2=345507&view=diff
==
--- cfe/trunk/lib/CodeGen/CGOpenMPRuntimeNVPTX.cpp (original)
+++ cfe/trunk/lib/CodeGen/CGOpenMPRuntimeNVPTX.cpp Mon Oct 29 08:23:23 2018
@@ -4238,16 +4238,17 @@ void CGOpenMPRuntimeNVPTX::getDefaultDis
 Chunk = CGF.EmitScalarConversion(getNVPTXNumThreads(CGF),
 CGF.getContext().getIntTypeForBitwidth(32, /*Signed=*/0),
 S.getIterationVariable()->getType(), S.getBeginLoc());
+return;
   }
+  CGOpenMPRuntime::getDefaultDistScheduleAndChunk(
+  CGF, S, ScheduleKind, Chunk);
 }
 
 void CGOpenMPRuntimeNVPTX::getDefaultScheduleAndChunk(
 CodeGenFunction &CGF, const OMPLoopDirective &S,
 OpenMPScheduleClauseKind &ScheduleKind,
 llvm::Value *&Chunk) const {
-  if (getExecutionMode() == CGOpenMPRuntimeNVPTX::EM_SPMD) {
-ScheduleKind = OMPC_SCHEDULE_static;
-Chunk = CGF.Builder.getIntN(CGF.getContext().getTypeSize(
-S.getIterationVariable()->getType()), 1);
-  }
+  ScheduleKind = OMPC_SCHEDULE_static;
+  Chunk = CGF.Builder.getIntN(CGF.getContext().getTypeSize(
+  S.getIterationVariable()->getType()), 1);
 }

Modified: cfe/trunk/test/OpenMP/nvptx_parallel_for_codegen.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/OpenMP/nvptx_parallel_for_codegen.cpp?rev=345507&r1=345506&r2=345507&view=diff
==
--- cfe/trunk/test/OpenMP/nvptx_parallel_for_codegen.cpp (original)
+++ cfe/trunk/test/OpenMP/nvptx_parallel_for_codegen.cpp Mon Oct 29 08:23:23 
2018
@@ -57,7 +57,10 @@ int bar(int n){
 // CHECK: store i32 0, {{.*}} [[OMP_LB:%.+]],
 // CHECK: store i32 9, {{.*}} [[OMP_UB:%.+]],
 // CHECK: store i32 1, {{.*}} [[OMP_ST:%.+]],
-// CHECK: call void @__kmpc_for_static_init_4({{.*}} i32 34, {{.*}} 
[[OMP_LB]], {{.*}} [[OMP_UB]], {{.*}} [[OMP_ST]], i32 1, i32 1)
+// CHECK: call void @__kmpc_for_static_init_4({{.*}} i32 33, {{.*}} 
[[OMP_LB]], {{.*}} [[OMP_UB]], {{.*}} [[OMP_ST]], i32 1, i32 1)
+// CHECK: br label %[[OMP_DISPATCH_COND:.+]]
+
+// CHECK: [[OMP_DISPATCH_COND]]
 // CHECK: [[OMP_UB_1:%.+]] = load {{.*}} [[OMP_UB]]
 // CHECK: [[COMP_1:%.+]] = icmp sgt {{.*}} [[OMP_UB_1]]
 // CHECK: br i1 [[COMP_1]], label %[[COND_TRUE:.+]], label %[[COND_FALSE:.+]]
@@ -74,6 +77,12 @@ int bar(int n){
 // CHECK: store i32 [[COND_RES]], i32* [[OMP_UB]]
 // CHECK: [[OMP_LB_1:%.+]] = load i32, i32* [[OMP_LB]]
 // CHECK: store i32 [[OMP_LB_1]], i32* [[OMP_IV]]
+// CHECK: [[OMP_IV_1:%.+]] = load i32, i32* [[OMP_IV]]
+// CHECK: [[OMP_UB_3:%.+]] = load i32, i32* [[OMP_UB]]
+// CHECK: [[COMP_2:%.+]] = icmp sle i32 [[OMP_IV_1]], [[OMP_UB_3]]
+// CHECK: br i1 [[COMP_2]], label %[[DISPATCH_BODY:.+]], label 
%[[DISPATCH_END:.+]]
+
+// CHECK: [[DISPATCH_BODY]]
 // CHECK: br label %[[OMP_INNER_FOR_COND:.+]]
 
 // CHECK: [[OMP_INNER_FOR_COND]]
@@ -94,7 +103,20 @@ int bar(int n){
 // CHECK: store i32 [[ADD_1]], i32* [[OMP_IV]]
 // CHECK: br label %[[OMP_INNER_FOR_COND]]
 
-// CHECK: [[OMP_INNER_FOR_END]]
+// CHECK: [[OMP_INNER_FOR_COND]]
+// CHECK: br label %[[OMP_DISPATCH_INC:.+]]
+
+// CHECK: [[OMP_DISPATCH_INC]]
+// CHECK: [[OMP_LB_2:%.+]] = load i32, i32* [[OMP_LB]]
+// CHECK: [[OMP_ST_1:%.+]] = load i32, i32* [[OMP_ST]]
+// CHECK: [[ADD_2:%.+]] = add nsw i32 [[OMP_LB_2]], [[OMP_ST_1]]
+// CHECK: store i32 [[ADD_2]], i32* [[OMP_LB]]
+// CHECK: [[OMP_UB_5:%.+]] = load i32, i32* [[OMP_UB]]
+// CHECK: [[OMP_ST_2:%.+]] = load i32, i32* [[OMP_ST]]
+// CHECK: [[ADD_3:%.+]] = add nsw i32 [[OMP_UB_5]], [[OMP_ST_2]]
+// CHECK: store i32 [[ADD_3]], i32* [[OMP_UB]]
+
+// CHECK: [[DISPATCH_END]]
 // CHECK: call void @__kmpc_for_static_fini(
 // CHECK: ret void
 


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


[PATCH] D53443: [OpenMP][NVPTX] Enable default scheduling for parallel for in non-SPMD cases.

2018-10-29 Thread Phabricator via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rL345507: [OpenMP][NVPTX] Enable default scheduling for 
parallel for in non-SPMD cases. (authored by gbercea, committed by ).
Herald added a subscriber: llvm-commits.

Repository:
  rL LLVM

https://reviews.llvm.org/D53443

Files:
  cfe/trunk/lib/CodeGen/CGOpenMPRuntimeNVPTX.cpp
  cfe/trunk/test/OpenMP/nvptx_parallel_for_codegen.cpp


Index: cfe/trunk/lib/CodeGen/CGOpenMPRuntimeNVPTX.cpp
===
--- cfe/trunk/lib/CodeGen/CGOpenMPRuntimeNVPTX.cpp
+++ cfe/trunk/lib/CodeGen/CGOpenMPRuntimeNVPTX.cpp
@@ -4238,16 +4238,17 @@
 Chunk = CGF.EmitScalarConversion(getNVPTXNumThreads(CGF),
 CGF.getContext().getIntTypeForBitwidth(32, /*Signed=*/0),
 S.getIterationVariable()->getType(), S.getBeginLoc());
+return;
   }
+  CGOpenMPRuntime::getDefaultDistScheduleAndChunk(
+  CGF, S, ScheduleKind, Chunk);
 }
 
 void CGOpenMPRuntimeNVPTX::getDefaultScheduleAndChunk(
 CodeGenFunction &CGF, const OMPLoopDirective &S,
 OpenMPScheduleClauseKind &ScheduleKind,
 llvm::Value *&Chunk) const {
-  if (getExecutionMode() == CGOpenMPRuntimeNVPTX::EM_SPMD) {
-ScheduleKind = OMPC_SCHEDULE_static;
-Chunk = CGF.Builder.getIntN(CGF.getContext().getTypeSize(
-S.getIterationVariable()->getType()), 1);
-  }
+  ScheduleKind = OMPC_SCHEDULE_static;
+  Chunk = CGF.Builder.getIntN(CGF.getContext().getTypeSize(
+  S.getIterationVariable()->getType()), 1);
 }
Index: cfe/trunk/test/OpenMP/nvptx_parallel_for_codegen.cpp
===
--- cfe/trunk/test/OpenMP/nvptx_parallel_for_codegen.cpp
+++ cfe/trunk/test/OpenMP/nvptx_parallel_for_codegen.cpp
@@ -57,7 +57,10 @@
 // CHECK: store i32 0, {{.*}} [[OMP_LB:%.+]],
 // CHECK: store i32 9, {{.*}} [[OMP_UB:%.+]],
 // CHECK: store i32 1, {{.*}} [[OMP_ST:%.+]],
-// CHECK: call void @__kmpc_for_static_init_4({{.*}} i32 34, {{.*}} 
[[OMP_LB]], {{.*}} [[OMP_UB]], {{.*}} [[OMP_ST]], i32 1, i32 1)
+// CHECK: call void @__kmpc_for_static_init_4({{.*}} i32 33, {{.*}} 
[[OMP_LB]], {{.*}} [[OMP_UB]], {{.*}} [[OMP_ST]], i32 1, i32 1)
+// CHECK: br label %[[OMP_DISPATCH_COND:.+]]
+
+// CHECK: [[OMP_DISPATCH_COND]]
 // CHECK: [[OMP_UB_1:%.+]] = load {{.*}} [[OMP_UB]]
 // CHECK: [[COMP_1:%.+]] = icmp sgt {{.*}} [[OMP_UB_1]]
 // CHECK: br i1 [[COMP_1]], label %[[COND_TRUE:.+]], label %[[COND_FALSE:.+]]
@@ -74,6 +77,12 @@
 // CHECK: store i32 [[COND_RES]], i32* [[OMP_UB]]
 // CHECK: [[OMP_LB_1:%.+]] = load i32, i32* [[OMP_LB]]
 // CHECK: store i32 [[OMP_LB_1]], i32* [[OMP_IV]]
+// CHECK: [[OMP_IV_1:%.+]] = load i32, i32* [[OMP_IV]]
+// CHECK: [[OMP_UB_3:%.+]] = load i32, i32* [[OMP_UB]]
+// CHECK: [[COMP_2:%.+]] = icmp sle i32 [[OMP_IV_1]], [[OMP_UB_3]]
+// CHECK: br i1 [[COMP_2]], label %[[DISPATCH_BODY:.+]], label 
%[[DISPATCH_END:.+]]
+
+// CHECK: [[DISPATCH_BODY]]
 // CHECK: br label %[[OMP_INNER_FOR_COND:.+]]
 
 // CHECK: [[OMP_INNER_FOR_COND]]
@@ -94,7 +103,20 @@
 // CHECK: store i32 [[ADD_1]], i32* [[OMP_IV]]
 // CHECK: br label %[[OMP_INNER_FOR_COND]]
 
-// CHECK: [[OMP_INNER_FOR_END]]
+// CHECK: [[OMP_INNER_FOR_COND]]
+// CHECK: br label %[[OMP_DISPATCH_INC:.+]]
+
+// CHECK: [[OMP_DISPATCH_INC]]
+// CHECK: [[OMP_LB_2:%.+]] = load i32, i32* [[OMP_LB]]
+// CHECK: [[OMP_ST_1:%.+]] = load i32, i32* [[OMP_ST]]
+// CHECK: [[ADD_2:%.+]] = add nsw i32 [[OMP_LB_2]], [[OMP_ST_1]]
+// CHECK: store i32 [[ADD_2]], i32* [[OMP_LB]]
+// CHECK: [[OMP_UB_5:%.+]] = load i32, i32* [[OMP_UB]]
+// CHECK: [[OMP_ST_2:%.+]] = load i32, i32* [[OMP_ST]]
+// CHECK: [[ADD_3:%.+]] = add nsw i32 [[OMP_UB_5]], [[OMP_ST_2]]
+// CHECK: store i32 [[ADD_3]], i32* [[OMP_UB]]
+
+// CHECK: [[DISPATCH_END]]
 // CHECK: call void @__kmpc_for_static_fini(
 // CHECK: ret void
 


Index: cfe/trunk/lib/CodeGen/CGOpenMPRuntimeNVPTX.cpp
===
--- cfe/trunk/lib/CodeGen/CGOpenMPRuntimeNVPTX.cpp
+++ cfe/trunk/lib/CodeGen/CGOpenMPRuntimeNVPTX.cpp
@@ -4238,16 +4238,17 @@
 Chunk = CGF.EmitScalarConversion(getNVPTXNumThreads(CGF),
 CGF.getContext().getIntTypeForBitwidth(32, /*Signed=*/0),
 S.getIterationVariable()->getType(), S.getBeginLoc());
+return;
   }
+  CGOpenMPRuntime::getDefaultDistScheduleAndChunk(
+  CGF, S, ScheduleKind, Chunk);
 }
 
 void CGOpenMPRuntimeNVPTX::getDefaultScheduleAndChunk(
 CodeGenFunction &CGF, const OMPLoopDirective &S,
 OpenMPScheduleClauseKind &ScheduleKind,
 llvm::Value *&Chunk) const {
-  if (getExecutionMode() == CGOpenMPRuntimeNVPTX::EM_SPMD) {
-ScheduleKind = OMPC_SCHEDULE_static;
-Chunk = CGF.Builder.getIntN(CGF.getContext().getTypeSize(
-S.getIterationVariable()->getType()), 1);
-  }
+  ScheduleKind = OMPC_SCHEDULE_static;
+  Chunk = CGF.Builder.getIntN(CGF.getContext().getTypeSize(
+  S.getIterationVariable()->getType()), 1);
 }
Index: cfe/trunk/test/O

[PATCH] D53818: [ASTImporter] Changed use of Import to Import_New in ASTImporter.

2018-10-29 Thread Balázs Kéri via Phabricator via cfe-commits
balazske created this revision.
Herald added subscribers: cfe-commits, Szelethus, martong, dkrupp.
Herald added a reviewer: a.sidorin.

Repository:
  rC Clang

https://reviews.llvm.org/D53818

Files:
  include/clang/AST/ASTImporter.h
  lib/AST/ASTImporter.cpp

Index: lib/AST/ASTImporter.cpp
===
--- lib/AST/ASTImporter.cpp
+++ lib/AST/ASTImporter.cpp
@@ -154,25 +154,6 @@
 return None;
   }
 
-  // FIXME: Temporary until every import returns Expected.
-  template <>
-  LLVM_NODISCARD Error
-  ASTImporter::importInto(SourceLocation &To, const SourceLocation &From) {
-To = Import(From);
-if (From.isValid() && To.isInvalid())
-return llvm::make_error();
-return Error::success();
-  }
-  // FIXME: Temporary until every import returns Expected.
-  template <>
-  LLVM_NODISCARD Error
-  ASTImporter::importInto(QualType &To, const QualType &From) {
-To = Import(From);
-if (!From.isNull() && To.isNull())
-return llvm::make_error();
-return Error::success();
-  }
-
   class ASTNodeImporter : public TypeVisitor,
   public DeclVisitor,
   public StmtVisitor {
@@ -7657,14 +7638,8 @@
 ASTImporter::~ASTImporter() = default;
 
 Expected ASTImporter::Import_New(QualType FromT) {
-  QualType ToT = Import(FromT);
-  if (ToT.isNull() && !FromT.isNull())
-return make_error();
-  return ToT;
-}
-QualType ASTImporter::Import(QualType FromT) {
   if (FromT.isNull())
-return {};
+return QualType{};
 
   const Type *FromTy = FromT.getTypePtr();
 
@@ -7677,46 +7652,65 @@
   // Import the type
   ASTNodeImporter Importer(*this);
   ExpectedType ToTOrErr = Importer.Visit(FromTy);
-  if (!ToTOrErr) {
-llvm::consumeError(ToTOrErr.takeError());
-return {};
-  }
+  if (!ToTOrErr)
+return ToTOrErr.takeError();
 
   // Record the imported type.
   ImportedTypes[FromTy] = (*ToTOrErr).getTypePtr();
 
   return ToContext.getQualifiedType(*ToTOrErr, FromT.getLocalQualifiers());
 }
+QualType ASTImporter::Import(QualType From) {
+  llvm::Expected To = Import_New(From);
+  if (To)
+return *To;
+  else
+llvm::consumeError(To.takeError());
+  return {};
+}
 
 Expected ASTImporter::Import_New(TypeSourceInfo *FromTSI) {
-  TypeSourceInfo *ToTSI = Import(FromTSI);
-  if (!ToTSI && FromTSI)
-return llvm::make_error();
-  return ToTSI;
-}
-TypeSourceInfo *ASTImporter::Import(TypeSourceInfo *FromTSI) {
   if (!FromTSI)
 return FromTSI;
 
   // FIXME: For now we just create a "trivial" type source info based
   // on the type and a single location. Implement a real version of this.
-  QualType T = Import(FromTSI->getType());
-  if (T.isNull())
-return nullptr;
+  ExpectedType TOrErr = Import_New(FromTSI->getType());
+  if (!TOrErr)
+return TOrErr.takeError();
+  ExpectedSLoc BeginLocOrErr = Import_New(FromTSI->getTypeLoc().getBeginLoc());
+  if (!BeginLocOrErr)
+return BeginLocOrErr.takeError();
 
-  return ToContext.getTrivialTypeSourceInfo(
-  T, Import(FromTSI->getTypeLoc().getBeginLoc()));
+  return ToContext.getTrivialTypeSourceInfo(*TOrErr, *BeginLocOrErr);
+}
+TypeSourceInfo *ASTImporter::Import(TypeSourceInfo *From) {
+  llvm::Expected To = Import_New(From);
+  if (To)
+return *To;
+  else
+llvm::consumeError(To.takeError());
+  return nullptr;
 }
 
 Expected ASTImporter::Import_New(const Attr *FromAttr) {
-  return Import(FromAttr);
-}
-Attr *ASTImporter::Import(const Attr *FromAttr) {
   Attr *ToAttr = FromAttr->clone(ToContext);
-  // NOTE: Import of SourceRange may fail.
-  ToAttr->setRange(Import(FromAttr->getRange()));
+  if (auto ToRangeOrErr = Import_New(FromAttr->getRange()))
+ToAttr->setRange(*ToRangeOrErr);
+  else
+return ToRangeOrErr.takeError();
+
   return ToAttr;
 }
+Attr *ASTImporter::Import(const Attr *From) {
+  llvm::Expected To = Import_New(From);
+  if (To)
+return *To;
+  else
+llvm::consumeError(To.takeError());
+  return nullptr;
+}
+
 
 Decl *ASTImporter::GetAlreadyImportedOrNull(Decl *FromD) {
   llvm::DenseMap::iterator Pos = ImportedDecls.find(FromD);
@@ -7732,12 +7726,6 @@
 }
 
 Expected ASTImporter::Import_New(Decl *FromD) {
-  Decl *ToD = Import(FromD);
-  if (!ToD && FromD)
-return llvm::make_error();
-  return ToD;
-}
-Decl *ASTImporter::Import(Decl *FromD) {
   if (!FromD)
 return nullptr;
 
@@ -7751,19 +7739,25 @@
 return ToD;
   }
 
-  // Import the type.
+  // Import the declaration.
   ExpectedDecl ToDOrErr = Importer.Visit(FromD);
-  if (!ToDOrErr) {
-llvm::consumeError(ToDOrErr.takeError());
-return nullptr;
-  }
+  if (!ToDOrErr)
+return ToDOrErr;
   ToD = *ToDOrErr;
 
   // Notify subclasses.
   Imported(FromD, ToD);
 
   updateFlags(FromD, ToD);
-  return ToD;
+  return ToDOrErr;
+}
+Decl *ASTImporter::Import(Decl *From) {
+  llvm::Expected To = Import_New(From);
+  if (To)
+return *To;
+  else
+llvm::consumeError(To.takeError());
+  return nu

[PATCH] D53810: [analyzer][NFC] Refactor PlistDiagnostics to use a class instead of passing 9 parameters around

2018-10-29 Thread Umann Kristóf via Phabricator via cfe-commits
Szelethus added inline comments.



Comment at: lib/StaticAnalyzer/Core/PlistDiagnostics.cpp:82
 
-static void EmitRanges(raw_ostream &o,
-   const ArrayRef Ranges,
-   const FIDMap& FM,
-   const Preprocessor &PP,
-   unsigned indent) {
+  void ReportDiag(raw_ostream &o, const PathDiagnosticPiece& P) {
+ReportPiece(o, P, /*indent*/ 4, /*depth*/ 0, /*includeControlFlow*/ true);

xazax.hun wrote:
> The `raw_ostream` seems to be a common argument. MAybe it would be worth to 
> make that a member too?
I did that, and then later changed it back for debugging purposes, if anyone 
needs to print note pieces to errs or something.


https://reviews.llvm.org/D53810



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


r345509 - [OpenMP][NVPTX] Use single loops when generating code for distribute parallel for

2018-10-29 Thread Gheorghe-Teodor Bercea via cfe-commits
Author: gbercea
Date: Mon Oct 29 08:45:47 2018
New Revision: 345509

URL: http://llvm.org/viewvc/llvm-project?rev=345509&view=rev
Log:
[OpenMP][NVPTX] Use single loops when generating code for distribute parallel 
for

Summary: This patch adds a new code generation path for bound sharing 
directives containing distribute parallel for. The new code generation scheme 
applies to chunked schedules on distribute and parallel for directives. The 
scheme simplifies the code that is being generated by eliminating the need for 
an outer for loop over chunks for both distribute and parallel for directives. 
In the case of distribute it applies to any sized chunk while in the parallel 
for case it only applies when chunk size is 1.

Reviewers: ABataev, caomhin

Reviewed By: ABataev

Subscribers: jholewinski, guansong, cfe-commits

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

Modified:
cfe/trunk/include/clang/AST/StmtOpenMP.h
cfe/trunk/lib/AST/StmtOpenMP.cpp
cfe/trunk/lib/CodeGen/CGOpenMPRuntime.cpp
cfe/trunk/lib/CodeGen/CGOpenMPRuntime.h
cfe/trunk/lib/CodeGen/CGOpenMPRuntimeNVPTX.cpp
cfe/trunk/lib/CodeGen/CGOpenMPRuntimeNVPTX.h
cfe/trunk/lib/CodeGen/CGStmtOpenMP.cpp
cfe/trunk/lib/Sema/SemaOpenMP.cpp
cfe/trunk/lib/Serialization/ASTReaderStmt.cpp
cfe/trunk/lib/Serialization/ASTWriterStmt.cpp
cfe/trunk/test/OpenMP/distribute_parallel_for_codegen.cpp
cfe/trunk/test/OpenMP/distribute_parallel_for_simd_codegen.cpp
cfe/trunk/test/OpenMP/nvptx_target_teams_distribute_parallel_for_codegen.cpp

Modified: cfe/trunk/include/clang/AST/StmtOpenMP.h
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/AST/StmtOpenMP.h?rev=345509&r1=345508&r2=345509&view=diff
==
--- cfe/trunk/include/clang/AST/StmtOpenMP.h (original)
+++ cfe/trunk/include/clang/AST/StmtOpenMP.h Mon Oct 29 08:45:47 2018
@@ -392,9 +392,11 @@ class OMPLoopDirective : public OMPExecu
 CombinedConditionOffset = 25,
 CombinedNextLowerBoundOffset = 26,
 CombinedNextUpperBoundOffset = 27,
+CombinedDistConditionOffset = 28,
+CombinedParForInDistConditionOffset = 29,
 // Offset to the end (and start of the following counters/updates/finals
 // arrays) for combined distribute loop directives.
-CombinedDistributeEnd = 28,
+CombinedDistributeEnd = 30,
   };
 
   /// Get the counters storage.
@@ -605,6 +607,17 @@ protected:
"expected loop bound sharing directive");
 *std::next(child_begin(), CombinedNextUpperBoundOffset) = CombNUB;
   }
+  void setCombinedDistCond(Expr *CombDistCond) {
+assert(isOpenMPLoopBoundSharingDirective(getDirectiveKind()) &&
+   "expected loop bound distribute sharing directive");
+*std::next(child_begin(), CombinedDistConditionOffset) = CombDistCond;
+  }
+  void setCombinedParForInDistCond(Expr *CombParForInDistCond) {
+assert(isOpenMPLoopBoundSharingDirective(getDirectiveKind()) &&
+   "expected loop bound distribute sharing directive");
+*std::next(child_begin(),
+   CombinedParForInDistConditionOffset) = CombParForInDistCond;
+  }
   void setCounters(ArrayRef A);
   void setPrivateCounters(ArrayRef A);
   void setInits(ArrayRef A);
@@ -637,6 +650,13 @@ public:
 /// Update of UpperBound for statically scheduled omp loops for
 /// outer loop in combined constructs (e.g. 'distribute parallel for')
 Expr *NUB;
+/// Distribute Loop condition used when composing 'omp distribute'
+///  with 'omp for' in a same construct when schedule is chunked.
+Expr *DistCond;
+/// 'omp parallel for' loop condition used when composed with
+/// 'omp distribute' in the same construct and when schedule is
+/// chunked and the chunk size is 1.
+Expr *ParForInDistCond;
   };
 
   /// The expressions built for the OpenMP loop CodeGen for the
@@ -754,6 +774,8 @@ public:
   DistCombinedFields.Cond = nullptr;
   DistCombinedFields.NLB = nullptr;
   DistCombinedFields.NUB = nullptr;
+  DistCombinedFields.DistCond = nullptr;
+  DistCombinedFields.ParForInDistCond = nullptr;
 }
   };
 
@@ -922,6 +944,18 @@ public:
 return const_cast(reinterpret_cast(
 *std::next(child_begin(), CombinedNextUpperBoundOffset)));
   }
+  Expr *getCombinedDistCond() const {
+assert(isOpenMPLoopBoundSharingDirective(getDirectiveKind()) &&
+   "expected loop bound distribute sharing directive");
+return const_cast(reinterpret_cast(
+*std::next(child_begin(), CombinedDistConditionOffset)));
+  }
+  Expr *getCombinedParForInDistCond() const {
+assert(isOpenMPLoopBoundSharingDirective(getDirectiveKind()) &&
+   "expected loop bound distribute sharing directive");
+return const_cast(reinterpret_cast(
+*std::next(child_begin(), CombinedParForInDistConditionOffset)));
+  }
   const Stmt *getBody() const {
 // This relies on the loop form is al

[PATCH] D53448: [OpenMP][NVPTX] Use single loops when generating code for distribute parallel for

2018-10-29 Thread Phabricator via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rL345509: [OpenMP][NVPTX] Use single loops when generating 
code for distribute parallel… (authored by gbercea, committed by ).
Herald added a subscriber: llvm-commits.

Changed prior to commit:
  https://reviews.llvm.org/D53448?vs=171499&id=171512#toc

Repository:
  rL LLVM

https://reviews.llvm.org/D53448

Files:
  cfe/trunk/include/clang/AST/StmtOpenMP.h
  cfe/trunk/lib/AST/StmtOpenMP.cpp
  cfe/trunk/lib/CodeGen/CGOpenMPRuntime.cpp
  cfe/trunk/lib/CodeGen/CGOpenMPRuntime.h
  cfe/trunk/lib/CodeGen/CGOpenMPRuntimeNVPTX.cpp
  cfe/trunk/lib/CodeGen/CGOpenMPRuntimeNVPTX.h
  cfe/trunk/lib/CodeGen/CGStmtOpenMP.cpp
  cfe/trunk/lib/Sema/SemaOpenMP.cpp
  cfe/trunk/lib/Serialization/ASTReaderStmt.cpp
  cfe/trunk/lib/Serialization/ASTWriterStmt.cpp
  cfe/trunk/test/OpenMP/distribute_parallel_for_codegen.cpp
  cfe/trunk/test/OpenMP/distribute_parallel_for_simd_codegen.cpp
  cfe/trunk/test/OpenMP/nvptx_target_teams_distribute_parallel_for_codegen.cpp

Index: cfe/trunk/lib/CodeGen/CGOpenMPRuntimeNVPTX.h
===
--- cfe/trunk/lib/CodeGen/CGOpenMPRuntimeNVPTX.h
+++ cfe/trunk/lib/CodeGen/CGOpenMPRuntimeNVPTX.h
@@ -348,7 +348,7 @@
   /// Choose a default value for the schedule clause.
   void getDefaultScheduleAndChunk(CodeGenFunction &CGF,
   const OMPLoopDirective &S, OpenMPScheduleClauseKind &ScheduleKind,
-  llvm::Value *&Chunk) const override;
+  const Expr *&ChunkExpr) const override;
 
 private:
   /// Track the execution mode when codegening directives within a target
Index: cfe/trunk/lib/CodeGen/CGOpenMPRuntime.h
===
--- cfe/trunk/lib/CodeGen/CGOpenMPRuntime.h
+++ cfe/trunk/lib/CodeGen/CGOpenMPRuntime.h
@@ -890,6 +890,20 @@
   virtual bool isStaticNonchunked(OpenMPDistScheduleClauseKind ScheduleKind,
   bool Chunked) const;
 
+  /// Check if the specified \a ScheduleKind is static chunked.
+  /// \param ScheduleKind Schedule kind specified in the 'schedule' clause.
+  /// \param Chunked True if chunk is specified in the clause.
+  ///
+  virtual bool isStaticChunked(OpenMPScheduleClauseKind ScheduleKind,
+   bool Chunked) const;
+
+  /// Check if the specified \a ScheduleKind is static non-chunked.
+  /// \param ScheduleKind Schedule kind specified in the 'dist_schedule' clause.
+  /// \param Chunked True if chunk is specified in the clause.
+  ///
+  virtual bool isStaticChunked(OpenMPDistScheduleClauseKind ScheduleKind,
+   bool Chunked) const;
+
   /// Check if the specified \a ScheduleKind is dynamic.
   /// This kind of worksharing directive is emitted without outer loop.
   /// \param ScheduleKind Schedule Kind specified in the 'schedule' clause.
@@ -1506,7 +1520,7 @@
   /// schedule clause.
   virtual void getDefaultScheduleAndChunk(CodeGenFunction &CGF,
   const OMPLoopDirective &S, OpenMPScheduleClauseKind &ScheduleKind,
-  llvm::Value *&Chunk) const {}
+  const Expr *&ChunkExpr) const {}
 
   /// Emits call of the outlined function with the provided arguments,
   /// translating these arguments to correct target-specific arguments.
Index: cfe/trunk/lib/CodeGen/CGStmtOpenMP.cpp
===
--- cfe/trunk/lib/CodeGen/CGStmtOpenMP.cpp
+++ cfe/trunk/lib/CodeGen/CGStmtOpenMP.cpp
@@ -2006,7 +2006,7 @@
   RT.emitDistributeStaticInit(*this, S.getBeginLoc(), ScheduleKind, StaticInit);
 
   // for combined 'distribute' and 'for' the increment expression of distribute
-  // is store in DistInc. For 'distribute' alone, it is in Inc.
+  // is stored in DistInc. For 'distribute' alone, it is in Inc.
   Expr *IncExpr;
   if (isOpenMPLoopBoundSharingDirective(S.getDirectiveKind()))
 IncExpr = S.getDistInc();
@@ -2298,31 +2298,41 @@
   (void)LoopScope.Privatize();
 
   // Detect the loop schedule kind and chunk.
-  llvm::Value *Chunk = nullptr;
+  const Expr *ChunkExpr = nullptr;
   OpenMPScheduleTy ScheduleKind;
   if (const auto *C = S.getSingleClause()) {
 ScheduleKind.Schedule = C->getScheduleKind();
 ScheduleKind.M1 = C->getFirstScheduleModifier();
 ScheduleKind.M2 = C->getSecondScheduleModifier();
-if (const Expr *Ch = C->getChunkSize()) {
-  Chunk = EmitScalarExpr(Ch);
-  Chunk = EmitScalarConversion(Chunk, Ch->getType(),
-   S.getIterationVariable()->getType(),
-   S.getBeginLoc());
-}
+ChunkExpr = C->getChunkSize();
   } else {
 // Default behaviour for schedule clause.
 CGM.getOpenMPRuntime().getDefaultScheduleAndChunk(
-*this, S, ScheduleKind.Schedule, Chunk);
+*this, S, ScheduleKind.Schedule, ChunkExpr);
+  }
+  bool HasC

[PATCH] D53817: [clang-tidy] cppcoreguidelines-macro-usage: print macro names

2018-10-29 Thread Jonas Toth via Phabricator via cfe-commits
JonasToth added a comment.

How does this patch change the behaviour for macros without location? They will 
be diagnosed at the beginning of the TU?

It is probably better to ignore these kind of macros, as there is no way around 
them (compile time configuration can only be done with macros?!) and therefore 
warnings for theses macros are false positives. Using `constexpr` constructs 
does not help either.


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D53817



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


[PATCH] D53654: [clang] Improve ctor initializer completions.

2018-10-29 Thread Kadir Cetinkaya via Phabricator via cfe-commits
kadircet updated this revision to Diff 171516.
kadircet marked 5 inline comments as done.
kadircet added a comment.

- Address comments & offline discussions.


Repository:
  rC Clang

https://reviews.llvm.org/D53654

Files:
  lib/Sema/SemaCodeComplete.cpp
  test/CodeCompletion/ctor-initializer.cpp
  test/Index/complete-ctor-inits.cpp
  test/Index/complete-cxx-inline-methods.cpp

Index: test/Index/complete-cxx-inline-methods.cpp
===
--- test/Index/complete-cxx-inline-methods.cpp
+++ test/Index/complete-cxx-inline-methods.cpp
@@ -21,6 +21,13 @@
   int value;
   MyCls *object;
 };
+
+template 
+class X {};
+
+class Y : public X {
+  Y() : X() {}
+};
 }
 
 // RUN: c-index-test -code-completion-at=%s:4:9 -std=c++98 %s | FileCheck %s
@@ -35,10 +42,12 @@
 // CHECK-NEXT: Container Kind: StructDecl
 
 // RUN: c-index-test -code-completion-at=%s:18:41 %s | FileCheck -check-prefix=CHECK-CTOR-INIT %s
-// CHECK-CTOR-INIT: NotImplemented:{TypedText MyCls}{LeftParen (}{Placeholder args}{RightParen )} (7)
-// CHECK-CTOR-INIT: MemberRef:{TypedText object}{LeftParen (}{Placeholder args}{RightParen )} (35)
-// CHECK-CTOR-INIT: MemberRef:{TypedText value}{LeftParen (}{Placeholder args}{RightParen )} (35)
+// CHECK-CTOR-INIT: ClassDecl:{TypedText MyCls}{LeftParen (}{Placeholder MyCls}{RightParen )} (7)
+// CHECK-CTOR-INIT: FieldDecl:{TypedText object}{LeftParen (}{Placeholder MyCls *}{RightParen )} (35)
+// CHECK-CTOR-INIT: FieldDecl:{TypedText value}{LeftParen (}{Placeholder int}{RightParen )} (35)
 // RUN: c-index-test -code-completion-at=%s:18:55 %s | FileCheck -check-prefix=CHECK-CTOR-INIT-2 %s
-// CHECK-CTOR-INIT-2-NOT: NotImplemented:{TypedText MyCls}{LeftParen (}{Placeholder args}{RightParen )}
-// CHECK-CTOR-INIT-2: MemberRef:{TypedText object}{LeftParen (}{Placeholder args}{RightParen )} (35)
-// CHECK-CTOR-INIT-2: MemberRef:{TypedText value}{LeftParen (}{Placeholder args}{RightParen )} (7)
+// CHECK-CTOR-INIT-2-NOT: ClassDecl:{TypedText MyCls}{LeftParen (}{Placeholder MyCls}{RightParen )} (7)
+// CHECK-CTOR-INIT-2: FieldDecl:{TypedText object}{LeftParen (}{Placeholder MyCls *}{RightParen )} (35)
+// CHECK-CTOR-INIT-2: FieldDecl:{TypedText value}{LeftParen (}{Placeholder int}{RightParen )} (7)
+// RUN: c-index-test -code-completion-at=%s:29:9 %s | FileCheck -check-prefix=CHECK-CTOR-INIT-3 %s
+// CHECK-CTOR-INIT-3: ClassDecl:{TypedText X}{LeftParen (}{Placeholder X}{RightParen )} (7)
Index: test/Index/complete-ctor-inits.cpp
===
--- test/Index/complete-ctor-inits.cpp
+++ test/Index/complete-ctor-inits.cpp
@@ -30,27 +30,33 @@
 };
 
 // RUN: c-index-test -code-completion-at=%s:18:10 %s | FileCheck -check-prefix=CHECK-CC1 %s
-// CHECK-CC1: MemberRef:{TypedText a}{LeftParen (}{Placeholder args}{RightParen )} (35)
-// CHECK-CC1: MemberRef:{TypedText b}{LeftParen (}{Placeholder args}{RightParen )} (35)
-// CHECK-CC1: MemberRef:{TypedText c}{LeftParen (}{Placeholder args}{RightParen )} (35)
-// CHECK-CC1: NotImplemented:{TypedText Virt}{LeftParen (}{Placeholder args}{RightParen )} (35)
-// CHECK-CC1: NotImplemented:{TypedText X}{LeftParen (}{Placeholder args}{RightParen )} (7)
-// CHECK-CC1: NotImplemented:{TypedText Y}{LeftParen (}{Placeholder args}{RightParen )} (35)
+// CHECK-CC1: FieldDecl:{TypedText a}{LeftParen (}{Placeholder int}{RightParen )} (35)
+// CHECK-CC1: FieldDecl:{TypedText b}{LeftParen (}{Placeholder int}{RightParen )} (35)
+// CHECK-CC1: FieldDecl:{TypedText c}{LeftParen (}{Placeholder int}{RightParen )} (35)
+// CHECK-CC1: CXXConstructor:{TypedText Virt}{LeftParen (}{Placeholder const Virt &}{RightParen )} (35)
+// CHECK-CC1: CXXConstructor:{TypedText Virt}{LeftParen (}{Placeholder Virt &&}{RightParen )} (35)
+// CHECK-CC1: CXXConstructor:{TypedText X}{LeftParen (}{Placeholder int}{RightParen )} (7)
+// CHECK-CC1: CXXConstructor:{TypedText Y}{LeftParen (}{Placeholder const Y &}{RightParen )} (35)
+// CHECK-CC1: CXXConstructor:{TypedText Y}{LeftParen (}{Placeholder Y &&}{RightParen )} (35)
 
 // RUN: c-index-test -code-completion-at=%s:18:23 %s | FileCheck -check-prefix=CHECK-CC2 %s
-// CHECK-CC2: MemberRef:{TypedText a}{LeftParen (}{Placeholder args}{RightParen )} (35)
-// CHECK-CC2: MemberRef:{TypedText b}{LeftParen (}{Placeholder args}{RightParen )} (35)
-// CHECK-CC2: MemberRef:{TypedText c}{LeftParen (}{Placeholder args}{RightParen )} (35)
-// CHECK-CC2: NotImplemented:{TypedText Virt}{LeftParen (}{Placeholder args}{RightParen )} (35)
-// CHECK-CC2: NotImplemented:{TypedText Y}{LeftParen (}{Placeholder args}{RightParen )} (7)
+// CHECK-CC2: FieldDecl:{TypedText a}{LeftParen (}{Placeholder int}{RightParen )} (35)
+// CHECK-CC2: FieldDecl:{TypedText b}{LeftParen (}{Placeholder int}{RightParen )} (35)
+// CHECK-CC2: FieldDecl:{TypedText c}{LeftParen (}{Placeholder int}{RightParen )} (35)
+// CHECK-CC2: CXXConstructor:{TypedText Virt}{LeftParen (}{Placeholder const Virt &}{RightP

[PATCH] D53818: [ASTImporter] Changed use of Import to Import_New in ASTImporter.

2018-10-29 Thread Balázs Kéri via Phabricator via cfe-commits
balazske added a comment.

The Import functions are replaced by Import_New and error handling is added. 
This is done in the implementation of the Import_New functions itself, and in 
importInto. (Code of old Import functions is moved to the Import_New and 
updated to use Import_New.) Some other functions in ASTImporter are still using 
the Import, these are to be changed later.


Repository:
  rC Clang

https://reviews.llvm.org/D53818



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


[PATCH] D53814: Allow the analyzer to output to a SARIF file

2018-10-29 Thread Alexander Zaitsev via Phabricator via cfe-commits
ZaMaZaN4iK added inline comments.



Comment at: StaticAnalyzer/Core/CMakeLists.txt:43
   PlistDiagnostics.cpp
+  SarifDiagnostics.cpp
   ProgramState.cpp

Sort alphabetically



Comment at: StaticAnalyzer/Core/SarifDiagnostics.cpp:88
+  // URI encode the part.
+  for (char C : Component) {
+// RFC 3986 claims alpha, numeric, and this handful of

I don't know about const corectness policy in LLVM. But I prefer here const 
char C .



Comment at: StaticAnalyzer/Core/SarifDiagnostics.cpp:94
+// reserved character.
+if (llvm::isAlnum(C) ||
+StringRef::npos !=

Probably this piece of code will be better to write separately as function


https://reviews.llvm.org/D53814



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


r345510 - [AST] Only store the needed data in SwitchStmt

2018-10-29 Thread Bruno Ricci via cfe-commits
Author: brunoricci
Date: Mon Oct 29 09:12:37 2018
New Revision: 345510

URL: http://llvm.org/viewvc/llvm-project?rev=345510&view=rev
Log:
[AST] Only store the needed data in SwitchStmt

Don't store the data for the init statement and condition variable
if not needed. This cuts the size of SwitchStmt by up to 2 pointers.
The order of the children is intentionally kept the same.

Also use the newly available space in the bit-fields of Stmt
to store the bit representing whether all enums have been covered
instead of using a PointerIntPair.

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

Reviewed By: rjmccall


Modified:
cfe/trunk/include/clang/AST/Stmt.h
cfe/trunk/lib/AST/ASTDumper.cpp
cfe/trunk/lib/AST/ASTImporter.cpp
cfe/trunk/lib/AST/Stmt.cpp
cfe/trunk/lib/Sema/SemaStmt.cpp
cfe/trunk/lib/Serialization/ASTReaderStmt.cpp
cfe/trunk/lib/Serialization/ASTWriterStmt.cpp
cfe/trunk/test/Import/switch-stmt/test.cpp
cfe/trunk/test/Misc/ast-dump-color.cpp

Modified: cfe/trunk/include/clang/AST/Stmt.h
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/AST/Stmt.h?rev=345510&r1=345509&r2=345510&view=diff
==
--- cfe/trunk/include/clang/AST/Stmt.h (original)
+++ cfe/trunk/include/clang/AST/Stmt.h Mon Oct 29 09:12:37 2018
@@ -177,6 +177,17 @@ protected:
 
 unsigned : NumStmtBits;
 
+/// True if the SwitchStmt has storage for an init statement.
+unsigned HasInit : 1;
+
+/// True if the SwitchStmt has storage for a condition variable.
+unsigned HasVar : 1;
+
+/// If the SwitchStmt is a switch on an enum value, records whether all
+/// the enum values were covered by CaseStmts.  The coverage information
+/// value is meant to be a hint for possible clients.
+unsigned AllEnumCasesCovered : 1;
+
 /// The location of the "switch".
 SourceLocation SwitchLoc;
   };
@@ -1427,21 +1438,102 @@ public:
 };
 
 /// SwitchStmt - This represents a 'switch' stmt.
-class SwitchStmt : public Stmt {
-  enum { INIT, VAR, COND, BODY, END_EXPR };
-  Stmt* SubExprs[END_EXPR];
-
-  // This points to a linked list of case and default statements and, if the
-  // SwitchStmt is a switch on an enum value, records whether all the enum
-  // values were covered by CaseStmts.  The coverage information value is meant
-  // to be a hint for possible clients.
-  llvm::PointerIntPair FirstCase;
+class SwitchStmt final : public Stmt,
+ private llvm::TrailingObjects {
+  friend TrailingObjects;
 
-public:
-  SwitchStmt(const ASTContext &C, Stmt *Init, VarDecl *Var, Expr *cond);
+  /// Points to a linked list of case and default statements.
+  SwitchCase *FirstCase;
+
+  // SwitchStmt is followed by several trailing objects,
+  // some of which optional. Note that it would be more convenient to
+  // put the optional trailing objects at the end but this would change
+  // the order in children().
+  // The trailing objects are in order:
+  //
+  // * A "Stmt *" for the init statement.
+  //Present if and only if hasInitStorage().
+  //
+  // * A "Stmt *" for the condition variable.
+  //Present if and only if hasVarStorage(). This is in fact a "DeclStmt *".
+  //
+  // * A "Stmt *" for the condition.
+  //Always present. This is in fact an "Expr *".
+  //
+  // * A "Stmt *" for the body.
+  //Always present.
+  enum { InitOffset = 0, BodyOffsetFromCond = 1 };
+  enum { NumMandatoryStmtPtr = 2 };
+
+  unsigned numTrailingObjects(OverloadToken) const {
+return NumMandatoryStmtPtr + hasInitStorage() + hasVarStorage();
+  }
+
+  unsigned initOffset() const { return InitOffset; }
+  unsigned varOffset() const { return InitOffset + hasInitStorage(); }
+  unsigned condOffset() const {
+return InitOffset + hasInitStorage() + hasVarStorage();
+  }
+  unsigned bodyOffset() const { return condOffset() + BodyOffsetFromCond; }
+
+  /// Build a switch statement.
+  SwitchStmt(const ASTContext &Ctx, Stmt *Init, VarDecl *Var, Expr *Cond);
 
   /// Build a empty switch statement.
-  explicit SwitchStmt(EmptyShell Empty) : Stmt(SwitchStmtClass, Empty) {}
+  explicit SwitchStmt(EmptyShell Empty, bool HasInit, bool HasVar);
+
+public:
+  /// Create a switch statement.
+  static SwitchStmt *Create(const ASTContext &Ctx, Stmt *Init, VarDecl *Var,
+Expr *Cond);
+
+  /// Create an empty switch statement optionally with storage for
+  /// an init expression and a condition variable.
+  static SwitchStmt *CreateEmpty(const ASTContext &Ctx, bool HasInit,
+ bool HasVar);
+
+  /// True if this SwitchStmt has storage for an init statement.
+  bool hasInitStorage() const { return SwitchStmtBits.HasInit; }
+
+  /// True if this SwitchStmt has storage for a condition variable.
+  bool hasVarStorage() const { return SwitchStmtBits.HasVar; }
+
+  Expr *getCond() {
+return reinterpret_cast(getTrailingObjects()[

[PATCH] D53714: [AST] Only store the needed data in SwitchStmt.

2018-10-29 Thread Phabricator via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rL345510: [AST] Only store the needed data in SwitchStmt 
(authored by brunoricci, committed by ).
Herald added a subscriber: llvm-commits.

Changed prior to commit:
  https://reviews.llvm.org/D53714?vs=171337&id=171518#toc

Repository:
  rL LLVM

https://reviews.llvm.org/D53714

Files:
  cfe/trunk/include/clang/AST/Stmt.h
  cfe/trunk/lib/AST/ASTDumper.cpp
  cfe/trunk/lib/AST/ASTImporter.cpp
  cfe/trunk/lib/AST/Stmt.cpp
  cfe/trunk/lib/Sema/SemaStmt.cpp
  cfe/trunk/lib/Serialization/ASTReaderStmt.cpp
  cfe/trunk/lib/Serialization/ASTWriterStmt.cpp
  cfe/trunk/test/Import/switch-stmt/test.cpp
  cfe/trunk/test/Misc/ast-dump-color.cpp

Index: cfe/trunk/include/clang/AST/Stmt.h
===
--- cfe/trunk/include/clang/AST/Stmt.h
+++ cfe/trunk/include/clang/AST/Stmt.h
@@ -177,6 +177,17 @@
 
 unsigned : NumStmtBits;
 
+/// True if the SwitchStmt has storage for an init statement.
+unsigned HasInit : 1;
+
+/// True if the SwitchStmt has storage for a condition variable.
+unsigned HasVar : 1;
+
+/// If the SwitchStmt is a switch on an enum value, records whether all
+/// the enum values were covered by CaseStmts.  The coverage information
+/// value is meant to be a hint for possible clients.
+unsigned AllEnumCasesCovered : 1;
+
 /// The location of the "switch".
 SourceLocation SwitchLoc;
   };
@@ -1427,21 +1438,102 @@
 };
 
 /// SwitchStmt - This represents a 'switch' stmt.
-class SwitchStmt : public Stmt {
-  enum { INIT, VAR, COND, BODY, END_EXPR };
-  Stmt* SubExprs[END_EXPR];
+class SwitchStmt final : public Stmt,
+ private llvm::TrailingObjects {
+  friend TrailingObjects;
 
-  // This points to a linked list of case and default statements and, if the
-  // SwitchStmt is a switch on an enum value, records whether all the enum
-  // values were covered by CaseStmts.  The coverage information value is meant
-  // to be a hint for possible clients.
-  llvm::PointerIntPair FirstCase;
+  /// Points to a linked list of case and default statements.
+  SwitchCase *FirstCase;
 
-public:
-  SwitchStmt(const ASTContext &C, Stmt *Init, VarDecl *Var, Expr *cond);
+  // SwitchStmt is followed by several trailing objects,
+  // some of which optional. Note that it would be more convenient to
+  // put the optional trailing objects at the end but this would change
+  // the order in children().
+  // The trailing objects are in order:
+  //
+  // * A "Stmt *" for the init statement.
+  //Present if and only if hasInitStorage().
+  //
+  // * A "Stmt *" for the condition variable.
+  //Present if and only if hasVarStorage(). This is in fact a "DeclStmt *".
+  //
+  // * A "Stmt *" for the condition.
+  //Always present. This is in fact an "Expr *".
+  //
+  // * A "Stmt *" for the body.
+  //Always present.
+  enum { InitOffset = 0, BodyOffsetFromCond = 1 };
+  enum { NumMandatoryStmtPtr = 2 };
+
+  unsigned numTrailingObjects(OverloadToken) const {
+return NumMandatoryStmtPtr + hasInitStorage() + hasVarStorage();
+  }
+
+  unsigned initOffset() const { return InitOffset; }
+  unsigned varOffset() const { return InitOffset + hasInitStorage(); }
+  unsigned condOffset() const {
+return InitOffset + hasInitStorage() + hasVarStorage();
+  }
+  unsigned bodyOffset() const { return condOffset() + BodyOffsetFromCond; }
+
+  /// Build a switch statement.
+  SwitchStmt(const ASTContext &Ctx, Stmt *Init, VarDecl *Var, Expr *Cond);
 
   /// Build a empty switch statement.
-  explicit SwitchStmt(EmptyShell Empty) : Stmt(SwitchStmtClass, Empty) {}
+  explicit SwitchStmt(EmptyShell Empty, bool HasInit, bool HasVar);
+
+public:
+  /// Create a switch statement.
+  static SwitchStmt *Create(const ASTContext &Ctx, Stmt *Init, VarDecl *Var,
+Expr *Cond);
+
+  /// Create an empty switch statement optionally with storage for
+  /// an init expression and a condition variable.
+  static SwitchStmt *CreateEmpty(const ASTContext &Ctx, bool HasInit,
+ bool HasVar);
+
+  /// True if this SwitchStmt has storage for an init statement.
+  bool hasInitStorage() const { return SwitchStmtBits.HasInit; }
+
+  /// True if this SwitchStmt has storage for a condition variable.
+  bool hasVarStorage() const { return SwitchStmtBits.HasVar; }
+
+  Expr *getCond() {
+return reinterpret_cast(getTrailingObjects()[condOffset()]);
+  }
+
+  const Expr *getCond() const {
+return reinterpret_cast(getTrailingObjects()[condOffset()]);
+  }
+
+  void setCond(Expr *Cond) {
+getTrailingObjects()[condOffset()] = reinterpret_cast(Cond);
+  }
+
+  Stmt *getBody() { return getTrailingObjects()[bodyOffset()]; }
+  const Stmt *getBody() const {
+return getTrailingObjects()[bodyOffset()];
+  }
+
+  void setBody(Stmt *Body) {
+getTrailingObjects()[bodyOffset()] = Body

[PATCH] D53817: [clang-tidy] cppcoreguidelines-macro-usage: print macro names

2018-10-29 Thread Roman Lebedev via Phabricator via cfe-commits
lebedev.ri added a comment.

In https://reviews.llvm.org/D53817#1278916, @JonasToth wrote:

> How does this patch change the behaviour for macros without location?


It doesn't.

> They will be diagnosed at the beginning of the TU?



> It is probably better to ignore these kind of macros, as there is no way 
> around them (compile time configuration can only be done with macros?!) and 
> therefore warnings for theses macros are false positives. Using `constexpr` 
> constructs does not help either.

I agree that it might be good idea to add an *option* to not diagnose such 
macros.
But i think it is not the spirit of the check/rule to ignore them completely 
[by default],
because those macros are still horrible, and can affect all kinds of things,
just like the 'normal' macros.


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D53817



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


[PATCH] D53814: Allow the analyzer to output to a SARIF file

2018-10-29 Thread George Karpenkov via Phabricator via cfe-commits
george.karpenkov added a comment.

Patch context is missing.




Comment at: Analysis/diagnostics/sarif-check.py:22
+passes = 0
+with open(testfile) as testfh:
+lineno = 0

Wow, this is super neat!
Since you are quite active in LLVM community, would you think it's better to 
have this tool in `llvm/utils` next to FileCheck? The concept is very general, 
and I think a lot of people really feel FileCheck limitations.



Comment at: Analysis/diagnostics/sarif-diagnostics-taint-test.c:18
+// Test the basics for sanity.
+// CHECK: sarifLog['version'].startswith("2.0.0")
+// CHECK: sarifLog['runs'][0]['tool']['fullName'] == "clang static analyzer"

Would it make more sense to just use `diff` + json pretty-formatter to write a 
test?
With this test I can't even quite figure out how the output should look like.



Comment at: StaticAnalyzer/Core/SarifDiagnostics.cpp:74
+  // Add the rest of the path components, encoding any reserved characters.
+  std::for_each(std::next(sys::path::begin(Filename)), 
sys::path::end(Filename),
+[&Ret](StringRef Component) {

Nitpicking style, but I don't see why for-each loop, preferably with a range 
wrapping the iterators would not be more readable.



Comment at: StaticAnalyzer/Core/SarifDiagnostics.cpp:182
+  case PathDiagnosticPiece::Kind::Note:
+// FIXME: What should be reported here?
+break;

"Note" are notes which do not have to be attached to a particular path element.



Comment at: StaticAnalyzer/Core/SarifDiagnostics.cpp:243
+
+  llvm::for_each(Diags, [&](const PathDiagnostic *D) {
+Results.push_back(createResult(*D, Files));

I like closures, but what's wrong with just using a `for` loop here?



Comment at: StaticAnalyzer/Core/SarifDiagnostics.cpp:254
+std::vector &Diags, FilesMade *) {
+  // FIXME: if the file already exists, do we overwrite it with a single run,
+  // or do we append a run into the file if it's a valid SARIF log?

Usually we overwrite the file and note that on stderr in such cases.


https://reviews.llvm.org/D53814



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


[PATCH] D53814: Allow the analyzer to output to a SARIF file

2018-10-29 Thread George Karpenkov via Phabricator via cfe-commits
george.karpenkov requested changes to this revision.
george.karpenkov added a comment.
This revision now requires changes to proceed.

Minor style notes + context missing.

I think using `diff` would be better than a custom python tool.


https://reviews.llvm.org/D53814



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


[PATCH] D53818: [ASTImporter] Changed use of Import to Import_New in ASTImporter.

2018-10-29 Thread Balázs Kéri via Phabricator via cfe-commits
balazske updated this revision to Diff 171519.
balazske added a comment.

Reformatted code.


Repository:
  rC Clang

https://reviews.llvm.org/D53818

Files:
  include/clang/AST/ASTImporter.h
  lib/AST/ASTImporter.cpp

Index: lib/AST/ASTImporter.cpp
===
--- lib/AST/ASTImporter.cpp
+++ lib/AST/ASTImporter.cpp
@@ -154,25 +154,6 @@
 return None;
   }
 
-  // FIXME: Temporary until every import returns Expected.
-  template <>
-  LLVM_NODISCARD Error
-  ASTImporter::importInto(SourceLocation &To, const SourceLocation &From) {
-To = Import(From);
-if (From.isValid() && To.isInvalid())
-return llvm::make_error();
-return Error::success();
-  }
-  // FIXME: Temporary until every import returns Expected.
-  template <>
-  LLVM_NODISCARD Error
-  ASTImporter::importInto(QualType &To, const QualType &From) {
-To = Import(From);
-if (!From.isNull() && To.isNull())
-return llvm::make_error();
-return Error::success();
-  }
-
   class ASTNodeImporter : public TypeVisitor,
   public DeclVisitor,
   public StmtVisitor {
@@ -7656,9 +7637,9 @@
 
 ASTImporter::~ASTImporter() = default;
 
-QualType ASTImporter::Import(QualType FromT) {
+Expected ASTImporter::Import_New(QualType FromT) {
   if (FromT.isNull())
-return {};
+return QualType{};
 
   const Type *FromTy = FromT.getTypePtr();
 
@@ -7671,36 +7652,64 @@
   // Import the type
   ASTNodeImporter Importer(*this);
   ExpectedType ToTOrErr = Importer.Visit(FromTy);
-  if (!ToTOrErr) {
-llvm::consumeError(ToTOrErr.takeError());
-return {};
-  }
+  if (!ToTOrErr)
+return ToTOrErr.takeError();
 
   // Record the imported type.
   ImportedTypes[FromTy] = (*ToTOrErr).getTypePtr();
 
   return ToContext.getQualifiedType(*ToTOrErr, FromT.getLocalQualifiers());
 }
+QualType ASTImporter::Import(QualType From) {
+  llvm::Expected To = Import_New(From);
+  if (To)
+return *To;
+  else
+llvm::consumeError(To.takeError());
+  return {};
+}
 
-TypeSourceInfo *ASTImporter::Import(TypeSourceInfo *FromTSI) {
+Expected ASTImporter::Import_New(TypeSourceInfo *FromTSI) {
   if (!FromTSI)
 return FromTSI;
 
   // FIXME: For now we just create a "trivial" type source info based
   // on the type and a single location. Implement a real version of this.
-  QualType T = Import(FromTSI->getType());
-  if (T.isNull())
-return nullptr;
+  ExpectedType TOrErr = Import_New(FromTSI->getType());
+  if (!TOrErr)
+return TOrErr.takeError();
+  ExpectedSLoc BeginLocOrErr = Import_New(FromTSI->getTypeLoc().getBeginLoc());
+  if (!BeginLocOrErr)
+return BeginLocOrErr.takeError();
 
-  return ToContext.getTrivialTypeSourceInfo(
-  T, Import(FromTSI->getTypeLoc().getBeginLoc()));
+  return ToContext.getTrivialTypeSourceInfo(*TOrErr, *BeginLocOrErr);
+}
+TypeSourceInfo *ASTImporter::Import(TypeSourceInfo *From) {
+  llvm::Expected To = Import_New(From);
+  if (To)
+return *To;
+  else
+llvm::consumeError(To.takeError());
+  return nullptr;
 }
 
-Attr *ASTImporter::Import(const Attr *FromAttr) {
+Expected ASTImporter::Import_New(const Attr *FromAttr) {
   Attr *ToAttr = FromAttr->clone(ToContext);
-  ToAttr->setRange(Import(FromAttr->getRange()));
+  if (auto ToRangeOrErr = Import_New(FromAttr->getRange()))
+ToAttr->setRange(*ToRangeOrErr);
+  else
+return ToRangeOrErr.takeError();
+
   return ToAttr;
 }
+Attr *ASTImporter::Import(const Attr *From) {
+  llvm::Expected To = Import_New(From);
+  if (To)
+return *To;
+  else
+llvm::consumeError(To.takeError());
+  return nullptr;
+}
 
 Decl *ASTImporter::GetAlreadyImportedOrNull(Decl *FromD) {
   llvm::DenseMap::iterator Pos = ImportedDecls.find(FromD);
@@ -7715,7 +7724,7 @@
   }
 }
 
-Decl *ASTImporter::Import(Decl *FromD) {
+Expected ASTImporter::Import_New(Decl *FromD) {
   if (!FromD)
 return nullptr;
 
@@ -7729,19 +7738,25 @@
 return ToD;
   }
 
-  // Import the type.
+  // Import the declaration.
   ExpectedDecl ToDOrErr = Importer.Visit(FromD);
-  if (!ToDOrErr) {
-llvm::consumeError(ToDOrErr.takeError());
-return nullptr;
-  }
+  if (!ToDOrErr)
+return ToDOrErr;
   ToD = *ToDOrErr;
 
   // Notify subclasses.
   Imported(FromD, ToD);
 
   updateFlags(FromD, ToD);
-  return ToD;
+  return ToDOrErr;
+}
+Decl *ASTImporter::Import(Decl *From) {
+  llvm::Expected To = Import_New(From);
+  if (To)
+return *To;
+  else
+llvm::consumeError(To.takeError());
+  return nullptr;
 }
 
 Expected ASTImporter::ImportContext(DeclContext *FromDC) {
@@ -7803,29 +7818,35 @@
   return ToDC;
 }
 
-Expr *ASTImporter::Import(Expr *FromE) {
-  if (!FromE)
-return nullptr;
-
-  return cast_or_null(Import(cast(FromE)));
+Expected ASTImporter::Import_New(Expr *FromE) {
+  if (ExpectedStmt ToSOrErr = Import_New(cast_or_null(FromE)))
+return cast_or_null(*ToSOrErr);
+  else
+return ToSOrErr.takeError();
+}
+Expr *ASTImporter

[PATCH] D53817: [clang-tidy] cppcoreguidelines-macro-usage: print macro names

2018-10-29 Thread Jonas Toth via Phabricator via cfe-commits
JonasToth added a comment.

>> They will be diagnosed at the beginning of the TU?
>>  It is probably better to ignore these kind of macros, as there is no way 
>> around them (compile time configuration can only be done with macros?!) and 
>> therefore warnings for theses macros are false positives. Using `constexpr` 
>> constructs does not help either.
> 
> I agree that it might be good idea to add an *option* to not diagnose such 
> macros.
>  But i think it is not the spirit of the check/rule to ignore them completely 
> [by default],
>  because those macros are still horrible, and can affect all kinds of things,
>  just like the 'normal' macros.

Yes and no, the CPPCG do acknowledge the fact, that macros are (still)
necessary for some jobs, like compile-time configurations of values and
require that the macros should at least be super visible in the code
(enforceable with the regex option in this check).

Turning off assertions for release builds would be a good example of
necessary macros. I would say this check must take this into account.

As for printing the name in the diagnostic: Not sure if this really adds
value. The location the diagnostic is pointing to is the name of macro
itself. The unclear diag comes from the fact that the macro is not
defined in code, so i think we should find a position on that issue first.

My opinion is, that macros without location (however compiler defined
macros) should not be diagnosed. It is unlikely that complicated
functions or the like a defined via compiler flags. These tend to be
used for integral constants to turn things on/off.


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D53817



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


[PATCH] D53817: [clang-tidy] cppcoreguidelines-macro-usage: print macro names

2018-10-29 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman added a comment.

In https://reviews.llvm.org/D53817#1278933, @lebedev.ri wrote:

> In https://reviews.llvm.org/D53817#1278916, @JonasToth wrote:
>
> > How does this patch change the behaviour for macros without location?
>
>
> It doesn't.
>
> > They will be diagnosed at the beginning of the TU?
>
>
>
> > It is probably better to ignore these kind of macros, as there is no way 
> > around them (compile time configuration can only be done with macros?!) and 
> > therefore warnings for theses macros are false positives. Using `constexpr` 
> > constructs does not help either.
>
> I agree that it might be good idea to add an *option* to not diagnose such 
> macros.
>  But i think it is not the spirit of the check/rule to ignore them completely 
> [by default],
>  because those macros are still horrible, and can affect all kinds of things,
>  just like the 'normal' macros.


I'm not certain an option makes sense in practice. Predefined macros and macros 
that come from the command line are a different beast from macros defined by 
the developer -- I don't think we should be diagnosing those cases as they're 
generally outside of programmer control. Predefined macros are entirely outside 
of the user's control. Macros from the command line are most often going to be 
controlling build toggles, but there is no reason to assume the user can 
control those (like 3rd party packages) or that they can be replaced with an 
alternative like `constexpr`.


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D53817



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


[PATCH] D53654: [clang] Improve ctor initializer completions.

2018-10-29 Thread Alexander Zaitsev via Phabricator via cfe-commits
ZaMaZaN4iK added inline comments.



Comment at: lib/Sema/SemaCodeComplete.cpp:5135
+  };
+  auto AddDefaultCtorInit = [&](const char *TypedName,
+const char *TypeName,

Is it good idea to capture ALL by reference? Probably will be better to capture 
only required things by reference


Repository:
  rC Clang

https://reviews.llvm.org/D53654



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


[PATCH] D53651: [clangd] Use thread pool for background indexing.

2018-10-29 Thread Kadir Cetinkaya via Phabricator via cfe-commits
kadircet updated this revision to Diff 171527.
kadircet added a comment.

- Use notify_all.
- Use priorities.


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D53651

Files:
  clangd/Threading.cpp
  clangd/Threading.h
  clangd/index/Background.cpp
  clangd/index/Background.h

Index: clangd/index/Background.h
===
--- clangd/index/Background.h
+++ clangd/index/Background.h
@@ -16,6 +16,7 @@
 #include "index/Index.h"
 #include "clang/Tooling/CompilationDatabase.h"
 #include "llvm/Support/SHA1.h"
+#include "TUScheduler.h"
 #include 
 #include 
 #include 
@@ -34,7 +35,8 @@
   // FIXME: resource-dir injection should be hoisted somewhere common.
   BackgroundIndex(Context BackgroundContext, StringRef ResourceDir,
   const FileSystemProvider &,
-  ArrayRef URISchemes = {});
+  ArrayRef URISchemes = {},
+  size_t ThreadPoolSize = getDefaultAsyncThreadsCount());
   ~BackgroundIndex(); // Blocks while the current task finishes.
 
   // Enqueue a translation unit for indexing.
@@ -74,7 +76,8 @@
   std::condition_variable QueueCV;
   bool ShouldStop = false;
   std::deque Queue;
-  std::thread Thread; // Must be last, spawned thread reads instance vars.
+  // Must be last, spawned thread reads instance vars.
+  llvm::SmallVector ThreadPool;
 };
 
 } // namespace clangd
Index: clangd/index/Background.cpp
===
--- clangd/index/Background.cpp
+++ clangd/index/Background.cpp
@@ -11,6 +11,7 @@
 #include "ClangdUnit.h"
 #include "Compiler.h"
 #include "Logger.h"
+#include "Threading.h"
 #include "Trace.h"
 #include "index/IndexAction.h"
 #include "index/MemIndex.h"
@@ -25,14 +26,22 @@
 BackgroundIndex::BackgroundIndex(Context BackgroundContext,
  StringRef ResourceDir,
  const FileSystemProvider &FSProvider,
- ArrayRef URISchemes)
+ ArrayRef URISchemes,
+ size_t ThreadPoolSize)
 : SwapIndex(make_unique()), ResourceDir(ResourceDir),
   FSProvider(FSProvider), BackgroundContext(std::move(BackgroundContext)),
-  URISchemes(URISchemes), Thread([this] { run(); }) {}
+  URISchemes(URISchemes) {
+  assert(ThreadPoolSize > 0 && "Thread pool size can't be zero.");
+  while(ThreadPoolSize--) {
+ThreadPool.emplace_back([this] { run(); });
+setThreadPriority(ThreadPool.back(), ThreadPriority::LOW);
+  }
+}
 
 BackgroundIndex::~BackgroundIndex() {
   stop();
-  Thread.join();
+  for (auto& Thread : ThreadPool)
+Thread.join();
 }
 
 void BackgroundIndex::stop() {
@@ -44,7 +53,7 @@
 }
 
 void BackgroundIndex::run() {
-  WithContext Background(std::move(BackgroundContext));
+  WithContext Background(BackgroundContext.clone());
   while (true) {
 Optional Task;
 {
Index: clangd/Threading.h
===
--- clangd/Threading.h
+++ clangd/Threading.h
@@ -17,6 +17,7 @@
 #include 
 #include 
 #include 
+#include 
 #include 
 
 namespace clang {
@@ -115,6 +116,13 @@
   mutable std::condition_variable TasksReachedZero;
   std::size_t InFlightTasks = 0;
 };
+
+enum ThreadPriority {
+  LOW = 0,
+  NORMAL = 1,
+};
+void setThreadPriority(std::thread &T, ThreadPriority Priority);
+
 } // namespace clangd
 } // namespace clang
 #endif
Index: clangd/Threading.cpp
===
--- clangd/Threading.cpp
+++ clangd/Threading.cpp
@@ -1,6 +1,7 @@
 #include "Threading.h"
 #include "Trace.h"
 #include "llvm/ADT/ScopeExit.h"
+#include "llvm/Config/config.h"
 #include "llvm/Support/FormatVariadic.h"
 #include "llvm/Support/Threading.h"
 #include 
@@ -97,5 +98,14 @@
   CV.wait_until(Lock, D.time());
 }
 
+void setThreadPriority(std::thread &T, ThreadPriority Priority) {
+#ifdef HAVE_PTHREAD_H
+  sched_param priority;
+  priority.sched_priority = 0;
+  pthread_setschedparam(T.native_handle(),
+Priority == LOW ? SCHED_IDLE : SCHED_OTHER, &priority);
+#endif
+}
+
 } // namespace clangd
 } // namespace clang
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D53814: Allow the analyzer to output to a SARIF file

2018-10-29 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman added inline comments.



Comment at: Analysis/diagnostics/sarif-check.py:22
+passes = 0
+with open(testfile) as testfh:
+lineno = 0

george.karpenkov wrote:
> Wow, this is super neat!
> Since you are quite active in LLVM community, would you think it's better to 
> have this tool in `llvm/utils` next to FileCheck? The concept is very 
> general, and I think a lot of people really feel FileCheck limitations.
The concept was pulled from test\TableGen\JSON-check.py, so it likely could be 
generalized. However, I suspect that each JSON test may want to expose 
different helper capabilities, so perhaps it won't be super general? I don't 
know enough about good Python design to know.



Comment at: Analysis/diagnostics/sarif-diagnostics-taint-test.c:18
+// Test the basics for sanity.
+// CHECK: sarifLog['version'].startswith("2.0.0")
+// CHECK: sarifLog['runs'][0]['tool']['fullName'] == "clang static analyzer"

george.karpenkov wrote:
> Would it make more sense to just use `diff` + json pretty-formatter to write 
> a test?
> With this test I can't even quite figure out how the output should look like.
I'm not super comfortable with that approach, but perhaps I'm thinking of 
something different than what you're proposing. The reason I went with this 
approach is because diff would be fragile (depends heavily on field ordering, 
which the JSON support library doesn't give control over) and the physical 
layout of the file isn't what needs to be tested anyway. SARIF has a fair 
amount of optional data that can be provided as well, so using a purely textual 
diff worried me that exporting additional optional data in the future would 
require extensive unrelated changes to all SARIF diffs in the test directory.

The goal for this test was to demonstrate that we can validate that the 
interesting bits of information are present in the output without worrying 
about the details.

Also, the python approach allows us to express relationships between data items 
more easily than a textual diff tool would. I've not used that here, but I 
could imagine a test where we want to check that each code location has a 
corresponding file entry in another list.



Comment at: StaticAnalyzer/Core/SarifDiagnostics.cpp:74
+  // Add the rest of the path components, encoding any reserved characters.
+  std::for_each(std::next(sys::path::begin(Filename)), 
sys::path::end(Filename),
+[&Ret](StringRef Component) {

george.karpenkov wrote:
> Nitpicking style, but I don't see why for-each loop, preferably with a range 
> wrapping the iterators would not be more readable.
I tend to prefer using algorithms when the logic is simple -- it makes it more 
clear that the loop is an unimportant detail. I don't have strong opinions on 
this particular loop, however.



Comment at: StaticAnalyzer/Core/SarifDiagnostics.cpp:88
+  // URI encode the part.
+  for (char C : Component) {
+// RFC 3986 claims alpha, numeric, and this handful of

ZaMaZaN4iK wrote:
> I don't know about const corectness policy in LLVM. But I prefer here const 
> char C .
We typically do not put top-level `const` on locals, so I'd prefer to leave it 
off here rather than be inconsistent.



Comment at: StaticAnalyzer/Core/SarifDiagnostics.cpp:182
+  case PathDiagnosticPiece::Kind::Note:
+// FIXME: What should be reported here?
+break;

george.karpenkov wrote:
> "Note" are notes which do not have to be attached to a particular path 
> element.
Good to know!



Comment at: StaticAnalyzer/Core/SarifDiagnostics.cpp:243
+
+  llvm::for_each(Diags, [&](const PathDiagnostic *D) {
+Results.push_back(createResult(*D, Files));

george.karpenkov wrote:
> I like closures, but what's wrong with just using a `for` loop here?
Same as above: clarity of exposition. This one I'd feel pretty strongly about 
keeping as an algorithm given how trivial the loop body is.



Comment at: StaticAnalyzer/Core/SarifDiagnostics.cpp:254
+std::vector &Diags, FilesMade *) {
+  // FIXME: if the file already exists, do we overwrite it with a single run,
+  // or do we append a run into the file if it's a valid SARIF log?

george.karpenkov wrote:
> Usually we overwrite the file and note that on stderr in such cases.
We took the decision internally to overwrite as well, but the SARIF format 
allows for multiple runs within the same output file (so you can compare 
analysis results for the same project over time). I think this will eventually 
have to be user-controlled because I can see some users wanting to append to 
the run and others wanting to overwrite. However, these log files can become 
quite large in practice (GBs of data), so "read in the JSON and add to it" may 
be implausible, hence 

[PATCH] D52742: [analyzer][PlistMacroExpansion] Part 1.: New expand-macros flag

2018-10-29 Thread Umann Kristóf via Phabricator via cfe-commits
Szelethus updated this revision to Diff 171532.
Szelethus added a comment.
This revision is now accepted and ready to land.

Changes according to my last comment.


https://reviews.llvm.org/D52742

Files:
  include/clang/StaticAnalyzer/Core/AnalyzerOptions.h
  lib/StaticAnalyzer/Core/AnalyzerOptions.cpp
  lib/StaticAnalyzer/Core/BugReporter.cpp
  lib/StaticAnalyzer/Core/PlistDiagnostics.cpp
  test/Analysis/Inputs/expected-plists/plist-macros-with-expansion.cpp.plist
  test/Analysis/plist-macros-with-expansion.cpp

Index: test/Analysis/plist-macros-with-expansion.cpp
===
--- /dev/null
+++ test/Analysis/plist-macros-with-expansion.cpp
@@ -0,0 +1,44 @@
+// RUN: %clang_analyze_cc1 -analyzer-checker=core -verify %s
+//
+// RUN: %clang_analyze_cc1 -analyzer-checker=core %s  \
+// RUN:   -analyzer-output=plist -o %t.plist \
+// RUN:   -analyzer-config expand-macros=true
+//
+// Check the actual plist output.
+//   RUN: cat %t.plist | %diff_plist \
+//   RUN:   %S/Inputs/expected-plists/plist-macros-with-expansion.cpp.plist
+//
+// Check the macro expansions from the plist output here, to make the test more
+// understandable.
+//   RUN: FileCheck --input-file=%t.plist %s
+
+void print(const void*);
+
+//===--===//
+// Tests for non-function-like macro expansions.
+//===--===//
+
+#define SET_PTR_VAR_TO_NULL \
+  ptr = 0
+
+void nonFunctionLikeMacroTest() {
+  int *ptr;
+  SET_PTR_VAR_TO_NULL;
+  *ptr = 5; // expected-warning{{Dereference of null pointer}}
+}
+
+// CHECK: name
+// CHECK-NEXT: expansion
+
+#define NULL 0
+#define SET_PTR_VAR_TO_NULL_WITH_NESTED_MACRO \
+  ptr = NULL
+
+void nonFunctionLikeNestedMacroTest() {
+  int *ptr;
+  SET_PTR_VAR_TO_NULL_WITH_NESTED_MACRO;
+  *ptr = 5; // expected-warning{{Dereference of null pointer}}
+}
+
+// CHECK: name
+// CHECK-NEXT: expansion
Index: test/Analysis/Inputs/expected-plists/plist-macros-with-expansion.cpp.plist
===
--- /dev/null
+++ test/Analysis/Inputs/expected-plists/plist-macros-with-expansion.cpp.plist
@@ -0,0 +1,353 @@
+
+http://www.apple.com/DTDs/PropertyList-1.0.dtd";>
+
+
+ clang_version
+clang version 8.0.0 (http://mainstream.inf.elte.hu/Szelethus/clang e0f3a71311657c25ac9844d8124f1564353487ca) (https://github.com/llvm-mirror/llvm 5973d705524e5432b05634a9aab38ecd2360ff13)
+ diagnostics
+ 
+  
+   path
+   
+
+ kindcontrol
+ edges
+  
+   
+start
+ 
+  
+   line25
+   col3
+   file0
+  
+  
+   line25
+   col5
+   file0
+  
+ 
+end
+ 
+  
+   line26
+   col3
+   file0
+  
+  
+   line26
+   col21
+   file0
+  
+ 
+   
+  
+
+
+ kindevent
+ location
+ 
+  line26
+  col3
+  file0
+ 
+ ranges
+ 
+   
+
+ line26
+ col3
+ file0
+
+
+ line26
+ col21
+ file0
+
+   
+ 
+ depth0
+ extended_message
+ Null pointer value stored to 'ptr'
+ message
+ Null pointer value stored to 'ptr'
+
+
+ kindcontrol
+ edges
+  
+   
+start
+ 
+  
+   line27
+   col3
+   file0
+  
+  
+   line27
+   col3
+   file0
+  
+ 
+end
+ 
+  
+   line27
+   col8
+   file0
+  
+  
+   line27
+   col8
+   file0
+  
+ 
+   
+  
+
+
+ kindevent
+ location
+ 
+  line27
+  col8
+  file0
+ 
+ ranges
+ 
+   
+
+ line27
+ col4
+ file0
+
+
+ line27
+ col6
+ file0
+
+   
+ 
+ depth0
+ extended_message
+ Dereference of null pointer (loaded from variable 'ptr')
+ message
+ Dereference of null pointer (loaded from variable 'ptr')
+
+   
+   macro_expansions
+   
+
+ location
+ 
+  line26
+  col3
+  file0
+ 
+ name
+ expansion
+
+   
+   descriptionDereference of null pointer (loaded from variable 'ptr')
+   categoryLogic error
+   typeDereference of null pointer
+   check_namecore.NullDereference
+   
+   issue_hash_content_of_line_in_contextf8fbc46cc5afbb056d92bd3d3d702781
+  issue_context_kindfunction
+  issue_contextnonFunctionLikeMacroTest
+  issue_hash_function_offset3
+  location
+  
+   line27
+   col8
+   file0
+  
+  ExecutedLines
+  
+   0
+   
+24
+25
+26
+27
+   
+  
+  
+  
+   path
+   
+
+

[PATCH] D52742: [analyzer][PlistMacroExpansion] Part 1.: New expand-macros flag

2018-10-29 Thread Umann Kristóf via Phabricator via cfe-commits
Szelethus updated this revision to Diff 171533.

https://reviews.llvm.org/D52742

Files:
  include/clang/StaticAnalyzer/Core/AnalyzerOptions.h
  lib/StaticAnalyzer/Core/AnalyzerOptions.cpp
  lib/StaticAnalyzer/Core/BugReporter.cpp
  lib/StaticAnalyzer/Core/PlistDiagnostics.cpp
  test/Analysis/Inputs/expected-plists/plist-macros-with-expansion.cpp.plist
  test/Analysis/plist-macros-with-expansion.cpp

Index: test/Analysis/plist-macros-with-expansion.cpp
===
--- /dev/null
+++ test/Analysis/plist-macros-with-expansion.cpp
@@ -0,0 +1,44 @@
+// RUN: %clang_analyze_cc1 -analyzer-checker=core -verify %s
+//
+// RUN: %clang_analyze_cc1 -analyzer-checker=core %s  \
+// RUN:   -analyzer-output=plist -o %t.plist \
+// RUN:   -analyzer-config expand-macros=true
+//
+// Check the actual plist output.
+//   RUN: cat %t.plist | %diff_plist \
+//   RUN:   %S/Inputs/expected-plists/plist-macros-with-expansion.cpp.plist
+//
+// Check the macro expansions from the plist output here, to make the test more
+// understandable.
+//   RUN: FileCheck --input-file=%t.plist %s
+
+void print(const void*);
+
+//===--===//
+// Tests for non-function-like macro expansions.
+//===--===//
+
+#define SET_PTR_VAR_TO_NULL \
+  ptr = 0
+
+void nonFunctionLikeMacroTest() {
+  int *ptr;
+  SET_PTR_VAR_TO_NULL;
+  *ptr = 5; // expected-warning{{Dereference of null pointer}}
+}
+
+// CHECK: name
+// CHECK-NEXT: expansion
+
+#define NULL 0
+#define SET_PTR_VAR_TO_NULL_WITH_NESTED_MACRO \
+  ptr = NULL
+
+void nonFunctionLikeNestedMacroTest() {
+  int *ptr;
+  SET_PTR_VAR_TO_NULL_WITH_NESTED_MACRO;
+  *ptr = 5; // expected-warning{{Dereference of null pointer}}
+}
+
+// CHECK: name
+// CHECK-NEXT: expansion
Index: test/Analysis/Inputs/expected-plists/plist-macros-with-expansion.cpp.plist
===
--- /dev/null
+++ test/Analysis/Inputs/expected-plists/plist-macros-with-expansion.cpp.plist
@@ -0,0 +1,351 @@
+
+http://www.apple.com/DTDs/PropertyList-1.0.dtd";>
+
+
+ diagnostics
+ 
+  
+   path
+   
+
+ kindcontrol
+ edges
+  
+   
+start
+ 
+  
+   line25
+   col3
+   file0
+  
+  
+   line25
+   col5
+   file0
+  
+ 
+end
+ 
+  
+   line26
+   col3
+   file0
+  
+  
+   line26
+   col21
+   file0
+  
+ 
+   
+  
+
+
+ kindevent
+ location
+ 
+  line26
+  col3
+  file0
+ 
+ ranges
+ 
+   
+
+ line26
+ col3
+ file0
+
+
+ line26
+ col21
+ file0
+
+   
+ 
+ depth0
+ extended_message
+ Null pointer value stored to 'ptr'
+ message
+ Null pointer value stored to 'ptr'
+
+
+ kindcontrol
+ edges
+  
+   
+start
+ 
+  
+   line27
+   col3
+   file0
+  
+  
+   line27
+   col3
+   file0
+  
+ 
+end
+ 
+  
+   line27
+   col8
+   file0
+  
+  
+   line27
+   col8
+   file0
+  
+ 
+   
+  
+
+
+ kindevent
+ location
+ 
+  line27
+  col8
+  file0
+ 
+ ranges
+ 
+   
+
+ line27
+ col4
+ file0
+
+
+ line27
+ col6
+ file0
+
+   
+ 
+ depth0
+ extended_message
+ Dereference of null pointer (loaded from variable 'ptr')
+ message
+ Dereference of null pointer (loaded from variable 'ptr')
+
+   
+   macro_expansions
+   
+
+ location
+ 
+  line26
+  col3
+  file0
+ 
+ name
+ expansion
+
+   
+   descriptionDereference of null pointer (loaded from variable 'ptr')
+   categoryLogic error
+   typeDereference of null pointer
+   check_namecore.NullDereference
+   
+   issue_hash_content_of_line_in_contextf8fbc46cc5afbb056d92bd3d3d702781
+  issue_context_kindfunction
+  issue_contextnonFunctionLikeMacroTest
+  issue_hash_function_offset3
+  location
+  
+   line27
+   col8
+   file0
+  
+  ExecutedLines
+  
+   0
+   
+24
+25
+26
+27
+   
+  
+  
+  
+   path
+   
+
+ kindcontrol
+ edges
+  
+   
+start
+ 
+  
+   line38
+   col3
+   file0
+  
+  
+   line38
+   col5
+   file0
+  
+ 
+end
+ 
+  
+   line39
+   col3
+   fi

[PATCH] D53817: [clang-tidy] cppcoreguidelines-macro-usage: print macro names

2018-10-29 Thread Roman Lebedev via Phabricator via cfe-commits
lebedev.ri added a comment.

In https://reviews.llvm.org/D53817#1278970, @aaron.ballman wrote:

> In https://reviews.llvm.org/D53817#1278933, @lebedev.ri wrote:
>
> > In https://reviews.llvm.org/D53817#1278916, @JonasToth wrote:
> >
> > > How does this patch change the behaviour for macros without location?
> >
> >
> > It doesn't.
> >
> > > They will be diagnosed at the beginning of the TU?
> >
> >
> >
> > > It is probably better to ignore these kind of macros, as there is no way 
> > > around them (compile time configuration can only be done with macros?!) 
> > > and therefore warnings for theses macros are false positives. Using 
> > > `constexpr` constructs does not help either.
> >
> > I agree that it might be good idea to add an *option* to not diagnose such 
> > macros.
> >  But i think it is not the spirit of the check/rule to ignore them 
> > completely [by default],
> >  because those macros are still horrible, and can affect all kinds of 
> > things,
> >  just like the 'normal' macros.
>
>
> I'm not certain an option makes sense in practice. Predefined macros and 
> macros that come from the command line are a different beast from macros 
> defined by the developer -- I don't think we should be diagnosing those cases 
> as they're generally outside of programmer control. Predefined macros are 
> entirely outside of the user's control. Macros from the command line are most 
> often going to be controlling build toggles, but there is no reason to assume 
> the user can control those (like 3rd party packages) or that they can be 
> replaced with an alternative like `constexpr`.


I personally haven't yet seen this check firing on *predefined* macros.
The only problem i have are these command-line-based macros.
They *may* be outside of programmer's control, but if one has access to the 
buildsystem
(as in, not *just* to the source code to be compiled, but to the build system 
definitions
that say *how* to build it), then one can easily add such command-line-based 
macros.


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D53817



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


[PATCH] D50147: clang-format: support external styles

2018-10-29 Thread Francois Ferrand via Phabricator via cfe-commits
Typz added a comment.

In https://reviews.llvm.org/D50147#1272742, @sammccall wrote:

> The idea here does seem to be a natural extension of -style, at least for the 
> case when the arg is a filename directly. I'm not opposed, happy to review 
> this.
>
> I do want to probe the use case a bit though: we have found that configuring 
> via -style= doesn't scale that well to lots of codebases and tools. e.g. if 
> someone's running clang-tidy or clangd via some driver, are they going to 
> have a way to plumb through the right -style=?
>
> Being able to discover the right style from the filesystem is powerful, and 
> if I was going to use this flag, I'd consider symlinking the style-file to 
> `subproject/.clang_format` instead. That way the setting is persistent and 
> available to all tools, rather than us needing to get it right on each 
> invocation.


I totally agree: using '-style' does not scale well. However this patch works 
also when the style is used in the 'basedOn' tag. This is actually the way we 
expect to use this: store a small .clang_format file in each repo, which simply 
references a clang-format file which must be installed (manually, for now) on 
each user's computer.


Repository:
  rC Clang

https://reviews.llvm.org/D50147



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


[PATCH] D53817: [clang-tidy] cppcoreguidelines-macro-usage: print macro names

2018-10-29 Thread Jonas Toth via Phabricator via cfe-commits
JonasToth added a comment.

> I personally haven't yet seen this check firing on *predefined* macros.

I did specifically check the compiler defined macros I could see in the AST and 
they were not diagnosed from the beginning.
I would guess, only the compiler-flag macros are passed in the PPCallbacks, 
which would explain the current behaviour.

> The only problem i have are these command-line-based macros.
>  They *may* be outside of programmer's control, but if one has access to the 
> buildsystem
>  (as in, not *just* to the source code to be compiled, but to the build 
> system definitions
>  that say *how* to build it), then one can easily add such command-line-based 
> macros.

It is a burden with little to gain as they the toggle-stuff use-case is not 
replaceable with other constructs.
Having it as opt-in might be ok, but by default the check should not diagnose 
them.


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D53817



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


[PATCH] D50147: clang-format: support external styles

2018-10-29 Thread Sam McCall via Phabricator via cfe-commits
sammccall added a comment.

In https://reviews.llvm.org/D50147#1279056, @Typz wrote:

> In https://reviews.llvm.org/D50147#1272742, @sammccall wrote:
>
> > The idea here does seem to be a natural extension of -style, at least for 
> > the case when the arg is a filename directly. I'm not opposed, happy to 
> > review this.
> >
> > I do want to probe the use case a bit though: we have found that 
> > configuring via -style= doesn't scale that well to lots of codebases and 
> > tools. e.g. if someone's running clang-tidy or clangd via some driver, are 
> > they going to have a way to plumb through the right -style=?
> >
> > Being able to discover the right style from the filesystem is powerful, and 
> > if I was going to use this flag, I'd consider symlinking the style-file to 
> > `subproject/.clang_format` instead. That way the setting is persistent and 
> > available to all tools, rather than us needing to get it right on each 
> > invocation.
>
>
> I totally agree: using '-style' does not scale well. However this patch works 
> also when the style is used in the 'basedOn' tag. This is actually the way we 
> expect to use this: store a small .clang_format file in each repo, which 
> simply references a clang-format file which must be installed (manually, for 
> now) on each user's computer.


`BasedOn: "/path/to/some/file"` would certainly work; but why not just use a 
symlink?


Repository:
  rC Clang

https://reviews.llvm.org/D50147



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


[PATCH] D53817: [clang-tidy] cppcoreguidelines-macro-usage: print macro names

2018-10-29 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman added a comment.

In https://reviews.llvm.org/D53817#1279053, @JonasToth wrote:

> > I personally haven't yet seen this check firing on *predefined* macros.
>
> I did specifically check the compiler defined macros I could see in the AST 
> and they were not diagnosed from the beginning.
>  I would guess, only the compiler-flag macros are passed in the PPCallbacks, 
> which would explain the current behaviour.


Thanks for checking; I hadn't had the chance to try it out yet and was making a 
guess.

>> The only problem i have are these command-line-based macros.
>>  They *may* be outside of programmer's control, but if one has access to the 
>> buildsystem
>>  (as in, not *just* to the source code to be compiled, but to the build 
>> system definitions
>>  that say *how* to build it), then one can easily add such 
>> command-line-based macros.
> 
> It is a burden with little to gain as they the toggle-stuff use-case is not 
> replaceable with other constructs.
>  Having it as opt-in might be ok, but by default the check should not 
> diagnose them.

+1; I'd be fine with an opt-in option for the behavior.


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D53817



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


r345517 - Revert "Revert "Support for groups of attributes in #pragma clang attribute""

2018-10-29 Thread Erik Pilkington via cfe-commits
Author: epilk
Date: Mon Oct 29 10:38:42 2018
New Revision: 345517

URL: http://llvm.org/viewvc/llvm-project?rev=345517&view=rev
Log:
Revert "Revert "Support for groups of attributes in #pragma clang attribute""

This reverts commit r345487, which reverted r345486. I think the crashes were
caused by an OOM on the builder, trying again to confirm...

Modified:
cfe/trunk/docs/LanguageExtensions.rst
cfe/trunk/docs/ReleaseNotes.rst
cfe/trunk/include/clang/Basic/DiagnosticParseKinds.td
cfe/trunk/include/clang/Basic/DiagnosticSemaKinds.td
cfe/trunk/include/clang/Sema/Sema.h
cfe/trunk/lib/Parse/ParsePragma.cpp
cfe/trunk/lib/Sema/SemaAttr.cpp
cfe/trunk/test/Parser/pragma-attribute.cpp
cfe/trunk/test/Sema/pragma-attribute.c

Modified: cfe/trunk/docs/LanguageExtensions.rst
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/docs/LanguageExtensions.rst?rev=345517&r1=345516&r2=345517&view=diff
==
--- cfe/trunk/docs/LanguageExtensions.rst (original)
+++ cfe/trunk/docs/LanguageExtensions.rst Mon Oct 29 10:38:42 2018
@@ -2651,17 +2651,19 @@ Specifying an attribute for multiple dec
 
 The ``#pragma clang attribute`` directive can be used to apply an attribute to
 multiple declarations. The ``#pragma clang attribute push`` variation of the
-directive pushes a new attribute to the attribute stack. The declarations that
-follow the pragma receive the attributes that are on the attribute stack, until
-the stack is cleared using a ``#pragma clang attribute pop`` directive. 
Multiple
-push directives can be nested inside each other.
+directive pushes a new "scope" of ``#pragma clang attribute`` that attributes
+can be added to. The ``#pragma clang attribute (...)`` variation adds an
+attribute to that scope, and the ``#pragma clang attribute pop`` variation pops
+the scope. You can also use ``#pragma clang attribute push (...)``, which is a
+shorthand for when you want to add one attribute to a new scope. Multiple push
+directives can be nested inside each other.
 
 The attributes that are used in the ``#pragma clang attribute`` directives
 can be written using the GNU-style syntax:
 
 .. code-block:: c++
 
-  #pragma clang attribute push(__attribute__((annotate("custom"))), apply_to = 
function)
+  #pragma clang attribute push (__attribute__((annotate("custom"))), apply_to 
= function)
 
   void function(); // The function now has the annotate("custom") attribute
 
@@ -2671,7 +2673,7 @@ The attributes can also be written using
 
 .. code-block:: c++
 
-  #pragma clang attribute push([[noreturn]], apply_to = function)
+  #pragma clang attribute push ([[noreturn]], apply_to = function)
 
   void function(); // The function now has the [[noreturn]] attribute
 
@@ -2681,7 +2683,7 @@ The ``__declspec`` style syntax is also
 
 .. code-block:: c++
 
-  #pragma clang attribute push(__declspec(dllexport), apply_to = function)
+  #pragma clang attribute push (__declspec(dllexport), apply_to = function)
 
   void function(); // The function now has the __declspec(dllexport) attribute
 

Modified: cfe/trunk/docs/ReleaseNotes.rst
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/docs/ReleaseNotes.rst?rev=345517&r1=345516&r2=345517&view=diff
==
--- cfe/trunk/docs/ReleaseNotes.rst (original)
+++ cfe/trunk/docs/ReleaseNotes.rst Mon Oct 29 10:38:42 2018
@@ -86,8 +86,8 @@ Modified Compiler Flags
 New Pragmas in Clang
 
 
-Clang now supports the ...
-
+- Clang now supports adding multiple `#pragma clang attribute` attributes into
+  a scope of pushed attributes.
 
 Attribute Changes in Clang
 --

Modified: cfe/trunk/include/clang/Basic/DiagnosticParseKinds.td
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Basic/DiagnosticParseKinds.td?rev=345517&r1=345516&r2=345517&view=diff
==
--- cfe/trunk/include/clang/Basic/DiagnosticParseKinds.td (original)
+++ cfe/trunk/include/clang/Basic/DiagnosticParseKinds.td Mon Oct 29 10:38:42 
2018
@@ -1032,8 +1032,8 @@ def err_pragma_optimize_invalid_argument
 def err_pragma_optimize_extra_argument : Error<
   "unexpected extra argument '%0' to '#pragma clang optimize'">;
 // - #pragma clang attribute
-def err_pragma_attribute_expected_push_pop : Error<
-  "expected 'push' or 'pop' after '#pragma clang attribute'">;
+def err_pragma_attribute_expected_push_pop_paren : Error<
+  "expected 'push', 'pop', or '(' after '#pragma clang attribute'">;
 def err_pragma_attribute_invalid_argument : Error<
   "unexpected argument '%0' to '#pragma clang attribute'; "
   "expected 'push' or 'pop'">;

Modified: cfe/trunk/include/clang/Basic/DiagnosticSemaKinds.td
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Basic/DiagnosticSemaKinds.td?rev=345517&r1=345516&r2=345517&view=diff

[PATCH] D50147: clang-format: support external styles

2018-10-29 Thread Francois Ferrand via Phabricator via cfe-commits
Typz added a comment.

In https://reviews.llvm.org/D50147#1272742, @sammccall wrote:

> Being able to discover the right style from the filesystem is powerful, and 
> if I was going to use this flag, I'd consider symlinking the style-file to 
> `subproject/.clang_format` instead. That way the setting is persistent and 
> available to all tools, rather than us needing to get it right on each 
> invocation.


I did not think of this solution. However:

- I am not sure how it works when the .clang-format link is stored in SCM: not 
sure git will allow storing a link which points outside of the repo... But it 
may be worth trying, it could be an alternative
- Making a symlink will hardcode the full path of the style, which may not suit 
different users: maybe in some cases the styles could be installed per-user (as 
users do not have root permissions), which they would be installed system-wide 
(in containers used for CI builds, where we may not know which user will 
actually run the build)
- Making a symlink will definitely not be portable to different OS : esp. on 
Windows, the path would probably not be the same
- I am not sure a symlink can point to a "~"-relative path, and automatically 
perform the user HOME path resolution




Comment at: lib/Format/Format.cpp:938
+  const llvm::SmallVector paths = {
+{"/usr/local/share/clang-format/", Name},
+{"~/.local/share/clang-format/", Name},

sammccall wrote:
> I'm not sure these prefixes are a good idea - can you explain what the 
> purpose is, and why the simpler model of just using the path doesn't work?
> 
> Certainly this needs some more thought about how it would work on windows 
> etc. I'd suggest limiting this patch to filenames.
the goal is actually to store these "base" styles in some global folder, so 
that multiple projects can reference it (through their own .clang-format file), 
without having to make any copy.

The idea is that the project is under SCM, and simply includes a reference to 
the style: in its own .clang-format, which would ideally only contain a single 
//basedOn// tag. The styles are defined globally, then each project only 
indicates which styles in uses.

But indeed, the 'HOME' folder on windows is probably not this one...


Repository:
  rC Clang

https://reviews.llvm.org/D50147



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


[PATCH] D53705: [OpenCL] Postpone PSV address space diagnostic

2018-10-29 Thread Sven van Haastregt via Phabricator via cfe-commits
svenvh added a comment.

Unlikely, since address spaces are provided in a different way in OpenCL C++ vs 
OpenCL C.

OpenCL C provides qualifiers such as `global` as part of the language.  OpenCL 
C++ provides template classes such as `cl::global` through a header file.


Repository:
  rC Clang

https://reviews.llvm.org/D53705



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


[PATCH] D53738: [Fixed Point Arithmetic] Fixed Point Addition

2018-10-29 Thread John McCall via Phabricator via cfe-commits
rjmccall added a comment.

In https://reviews.llvm.org/D53738#1278528, @ebevhan wrote:

> In https://reviews.llvm.org/D53738#1278078, @rjmccall wrote:
>
> > I don't think we should add *types* just for this, but if you need to make 
> > a different kind of `BinaryOperator` that represents that the semantics 
> > aren't quite the same (the same way that the compound assignments have 
> > their own subclass), that seems natural to me.
>
>
> I don't know if adding a new operator kind was what I had in mind. The 
> operator hasn't changed, it's still a normal binary operator. Compound 
> assignments are their own operator with its own syntax; it doesn't really 
> strike me as the same thing.


Sorry for being unclear.  I wasn't suggesting adding a new 
`BinaryOperatorKind`, I was suggesting making a subclass of `BinaryOperator` 
that stored the extra information you'd like to store.

> The important difference would be that we separate the semantics of 
> performing the conversion and the operation. I understand that adding a new 
> type could be a bit more involved than baking the conversion into the 
> operator, but I really do not enjoy seeing so much implicit, 
> implementation-specific logic encapsulated in the same AST element. Anyone 
> who wants to look at BinaryOperators with fixed-point types will need to know 
> all of the details of how the finding the common type and conversion is done, 
> rather than simply "it does an addition".

It's not just that adding a new type is "involved", it's that it's a bad 
solution.  Those types can't actually be expressed in the language, and 
changing the type system to be able to express them is going to lead to a lot 
of pain elsewhere.


Repository:
  rC Clang

https://reviews.llvm.org/D53738



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


[PATCH] D53705: [OpenCL] Postpone PSV address space diagnostic

2018-10-29 Thread John McCall via Phabricator via cfe-commits
rjmccall added a comment.

In https://reviews.llvm.org/D53705#1279068, @svenvh wrote:

> Unlikely, since address spaces are provided in a different way in OpenCL C++ 
> vs OpenCL C.
>
> OpenCL C provides qualifiers such as `global` as part of the language.  
> OpenCL C++ provides template classes such as `cl::global` through a header 
> file.


So OpenCL C code has to be completely rewritten if it needs to be used as part 
of an OpenCL C++ program?  And it doesn't really compose like a type if it's 
supposed to change how a variable is stored.  What a terrible little mess 
they've made for themselves.

I think a better solution might be to hack the parser to recognize cases like 
this.  It's more annoying work, but it'll lead to much better results.


Repository:
  rC Clang

https://reviews.llvm.org/D53705



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


[PATCH] D51949: [clang-tidy] new check 'readability-isolate-declaration'

2018-10-29 Thread Jonas Toth via Phabricator via cfe-commits
JonasToth updated this revision to Diff 171538.
JonasToth added a comment.

- Merge branch 'master' into experiment_isolate_decl
- adjust doc slighty to comment


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D51949

Files:
  clang-tidy/readability/CMakeLists.txt
  clang-tidy/readability/IsolateDeclarationCheck.cpp
  clang-tidy/readability/IsolateDeclarationCheck.h
  clang-tidy/readability/ReadabilityTidyModule.cpp
  clang-tidy/utils/LexerUtils.cpp
  clang-tidy/utils/LexerUtils.h
  docs/ReleaseNotes.rst
  docs/clang-tidy/checks/list.rst
  docs/clang-tidy/checks/readability-isolate-declaration.rst
  test/clang-tidy/readability-isolate-declaration-cxx17.cpp
  test/clang-tidy/readability-isolate-declaration-fixing.cpp
  test/clang-tidy/readability-isolate-declaration.c
  test/clang-tidy/readability-isolate-declaration.cpp

Index: test/clang-tidy/readability-isolate-declaration.cpp
===
--- /dev/null
+++ test/clang-tidy/readability-isolate-declaration.cpp
@@ -0,0 +1,412 @@
+// RUN: %check_clang_tidy %s readability-isolate-declaration %t
+
+void f() {
+  int i;
+}
+
+void f2() {
+  int i, j, *k, lala = 42;
+  // CHECK-MESSAGES: [[@LINE-1]]:3: warning: multiple declarations in a single statement reduces readability
+  // CHECK-FIXES: int i;
+  // CHECK-FIXES: {{^  }}int j;
+  // CHECK-FIXES: {{^  }}int *k;
+  // CHECK-FIXES: {{^  }}int lala = 42;
+
+  int normal, weird = /* comment */ 42;
+  // CHECK-MESSAGES: [[@LINE-1]]:3: warning: multiple declarations in a single statement reduces readability
+  // CHECK-FIXES: int normal;
+  // CHECK-FIXES: {{^  }}int weird = /* comment */ 42;
+
+  int /* here is a comment */ v1,
+  // another comment
+  v2 = 42 // Ok, more comments
+  ;
+  // CHECK-MESSAGES: [[@LINE-4]]:3: warning: multiple declarations in a single statement reduces readability
+  // CHECK-FIXES: int /* here is a comment */ v1;
+  // CHECK-FIXES: {{^  }}int /* here is a comment */ // another comment
+  // CHECK-FIXES: {{^  }}v2 = 42 // Ok, more comments
+  // CHECK-FIXES: {{^  }};
+
+  auto int1 = 42, int2 = 0, int3 = 43;
+  // CHECK-MESSAGES: [[@LINE-1]]:3: warning: multiple declarations in a single statement reduces readability
+  // CHECK-FIXES: auto int1 = 42;
+  // CHECK-FIXES: {{^  }}auto int2 = 0;
+  // CHECK-FIXES: {{^  }}auto int3 = 43;
+
+  decltype(auto) ptr1 = &int1, ptr2 = &int1;
+  // CHECK-MESSAGES: [[@LINE-1]]:3: warning: multiple declarations in a single statement reduces readability
+  // CHECK-FIXES: decltype(auto) ptr1 = &int1;
+  // CHECK-FIXES: {{^  }}decltype(auto) ptr2 = &int1;
+
+  decltype(k) ptr3 = &int1, ptr4 = &int1;
+  // CHECK-MESSAGES: [[@LINE-1]]:3: warning: multiple declarations in a single statement reduces readability
+  // CHECK-FIXES: decltype(k) ptr3 = &int1;
+  // CHECK-FIXES: {{^  }}decltype(k) ptr4 = &int1;
+}
+
+void f3() {
+  int i, *pointer1;
+  // CHECK-MESSAGES: [[@LINE-1]]:3: warning: multiple declarations in a single statement reduces readability
+  // CHECK-FIXES: int i;
+  // CHECK-FIXES: {{^  }}int *pointer1;
+  //
+  int *pointer2 = nullptr, *pointer3 = &i;
+  // CHECK-MESSAGES: [[@LINE-1]]:3: warning: multiple declarations in a single statement reduces readability
+  // CHECK-FIXES: int *pointer2 = nullptr;
+  // CHECK-FIXES: {{^  }}int *pointer3 = &i;
+
+  int *(i_ptr) = nullptr, *((i_ptr2));
+  // CHECK-MESSAGES: [[@LINE-1]]:3: warning: multiple declarations in a single statement reduces readability
+  // CHECK-FIXES: int *(i_ptr) = nullptr;
+  // CHECK-FIXES: {{^  }}int *((i_ptr2));
+
+  float(*f_ptr)[42], (((f_value))) = 42;
+  // CHECK-MESSAGES: [[@LINE-1]]:3: warning: multiple declarations in a single statement reduces readability
+  // CHECK-FIXES: float (*f_ptr)[42];
+  // CHECK-FIXES: {{^  }}float (((f_value))) = 42;
+
+  float(((*f_ptr2)))[42], ((*f_ptr3)), f_value2 = 42.f;
+  // CHECK-MESSAGES: [[@LINE-1]]:3: warning: multiple declarations in a single statement reduces readability
+  // CHECK-FIXES: float (((*f_ptr2)))[42];
+  // CHECK-FIXES: {{^  }}float ((*f_ptr3));
+  // CHECK-FIXES: {{^  }}float f_value2 = 42.f;
+
+  float(((*f_ptr4)))[42], *f_ptr5, ((f_value3));
+  // CHECK-MESSAGES: [[@LINE-1]]:3: warning: multiple declarations in a single statement reduces readability
+  // CHECK-FIXES: float (((*f_ptr4)))[42];
+  // CHECK-FIXES: {{^  }}float *f_ptr5;
+  // CHECK-FIXES: {{^  }}float ((f_value3));
+
+  void(((*f2))(int)), (*g2)(int, float);
+  // CHECK-MESSAGES: [[@LINE-1]]:3: warning: multiple declarations in a single statement reduces readability
+  // CHECK-FIXES: void (((*f2))(int));
+  // CHECK-FIXES: {{^  }}void (*g2)(int, float);
+
+  float(*(*(*f_ptr6)))[42], (*f_ptr7);
+  // CHECK-MESSAGES: [[@LINE-1]]:3: warning: multiple declarations in a single statement reduces readability
+  // CHECK-FIXES: float (*(*(*f_ptr6)))[42];
+  // CHECK-FIXES: {{^  }}float (*f_ptr7);
+}
+
+void f4() {
+  double d = 42. /* foo */, z = 43., /* hi */ y

[PATCH] D53066: [Driver] Use forward slashes in most linker arguments

2018-10-29 Thread Jordan Rupprecht via Phabricator via cfe-commits
rupprecht resigned from this revision.
rupprecht added a comment.

I'm not familiar with this code or anything windows related, and it looks like 
@rnk is, so I'll remove myself and let him approve


Repository:
  rL LLVM

https://reviews.llvm.org/D53066



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


[PATCH] D53276: [analyzer][NFC] Fix some incorrect uses of -analyzer-config options

2018-10-29 Thread Umann Kristóf via Phabricator via cfe-commits
Szelethus added a comment.

@NoQ did you have time to ping Devin about this? (Sorry for the early ping, but 
this patch is blocking a lot of my other patches.)


https://reviews.llvm.org/D53276



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


[PATCH] D38061: Set AnonymousTagLocations false for ASTContext if column info is expected not to be used

2018-10-29 Thread Taewook Oh via Phabricator via cfe-commits
twoh added a comment.

@rsmith @dblaikie Thank you for the comments! It seems that this is not the 
appropriate way to handle the issue. I'll find different way to resolve the 
problem.


Repository:
  rC Clang

https://reviews.llvm.org/D38061



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


[PATCH] D52794: [analyzer][PlistMacroExpansion] Part 2.: Retrieving the macro name and primitive expansion

2018-10-29 Thread Umann Kristóf via Phabricator via cfe-commits
Szelethus added inline comments.



Comment at: lib/StaticAnalyzer/Core/PlistDiagnostics.cpp:787-791
+  // Acquire the macro's name.
+  Token TheTok;
+  RawLexer.LexFromRawLexer(TheTok);
+
+  std::string MacroName = PP.getSpelling(TheTok);

NoQ wrote:
> Not sure, random thought: Could this work in fact be done with the //static// 
> `Lexer::getImmediateMacroName()` helper?
I need to create a lexer to lex the arguments of function-like macros (which is 
in part 3), so I can't get away with it I'm afraid :/


https://reviews.llvm.org/D52794



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


Re: r344957 - Give Multiversion-inline functions linkonce linkage

2018-10-29 Thread David Blaikie via cfe-commits
Does this match GCC's approach here?

(I ask this sort of as throwaway/conversation starter - because the
linkage/behavior around multiversion functions and their inlining is full
of sharp corners/risks of code moving out of the areas appropriately
restricted based on the cpu features)

On Mon, Oct 22, 2018 at 2:22 PM Erich Keane via cfe-commits <
cfe-commits@lists.llvm.org> wrote:

> Author: erichkeane
> Date: Mon Oct 22 14:20:45 2018
> New Revision: 344957
>
> URL: http://llvm.org/viewvc/llvm-project?rev=344957&view=rev
> Log:
> Give Multiversion-inline functions linkonce linkage
>
> Since multiversion variant functions can be inline, in C they become
> available-externally linkage.  This ends up causing the variants to not
> be emitted, and not available to the linker.
>
> The solution is to make sure that multiversion functions are always
> emitted by marking them linkonce.
>
> Change-Id: I897aa37c7cbba0c1eb2c57ee881d5000a2113b75
>
> Modified:
> cfe/trunk/lib/CodeGen/CodeGenModule.cpp
> cfe/trunk/test/CodeGen/attr-target-mv.c
>
> Modified: cfe/trunk/lib/CodeGen/CodeGenModule.cpp
> URL:
> http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/CodeGen/CodeGenModule.cpp?rev=344957&r1=344956&r2=344957&view=diff
>
> ==
> --- cfe/trunk/lib/CodeGen/CodeGenModule.cpp (original)
> +++ cfe/trunk/lib/CodeGen/CodeGenModule.cpp Mon Oct 22 14:20:45 2018
> @@ -3669,6 +3669,10 @@ llvm::GlobalValue::LinkageTypes CodeGenM
>return llvm::GlobalVariable::WeakAnyLinkage;
>}
>
> +  if (const auto *FD = D->getAsFunction())
> +if (FD->isMultiVersion() && Linkage == GVA_AvailableExternally)
> +  return llvm::GlobalVariable::LinkOnceAnyLinkage;
> +
>// We are guaranteed to have a strong definition somewhere else,
>// so we can use available_externally linkage.
>if (Linkage == GVA_AvailableExternally)
>
> Modified: cfe/trunk/test/CodeGen/attr-target-mv.c
> URL:
> http://llvm.org/viewvc/llvm-project/cfe/trunk/test/CodeGen/attr-target-mv.c?rev=344957&r1=344956&r2=344957&view=diff
>
> ==
> --- cfe/trunk/test/CodeGen/attr-target-mv.c (original)
> +++ cfe/trunk/test/CodeGen/attr-target-mv.c Mon Oct 22 14:20:45 2018
> @@ -88,19 +88,19 @@ void bar4() {
>
>  // CHECK: declare i32 @foo.arch_sandybridge()
>
> -// CHECK: define available_externally i32 @foo_inline.sse4.2()
> +// CHECK: define linkonce i32 @foo_inline.sse4.2()
>  // CHECK: ret i32 0
>
>  // CHECK: declare i32 @foo_inline.arch_sandybridge()
>  //
> -// CHECK: define available_externally i32 @foo_inline.arch_ivybridge()
> +// CHECK: define linkonce i32 @foo_inline.arch_ivybridge()
>  // CHECK: ret i32 1
> -// CHECK: define available_externally i32 @foo_inline()
> +// CHECK: define linkonce i32 @foo_inline()
>  // CHECK: ret i32 2
>
> -// CHECK: define available_externally void @foo_decls()
> -// CHECK: define available_externally void @foo_decls.sse4.2()
> +// CHECK: define linkonce void @foo_decls()
> +// CHECK: define linkonce void @foo_decls.sse4.2()
>
> -// CHECK: define available_externally void @foo_multi.avx_sse4.2()
> -// CHECK: define available_externally void @foo_multi.fma4_sse4.2()
> -// CHECK: define available_externally void
> @foo_multi.arch_ivybridge_fma4_sse4.2()
> +// CHECK: define linkonce void @foo_multi.avx_sse4.2()
> +// CHECK: define linkonce void @foo_multi.fma4_sse4.2()
> +// CHECK: define linkonce void @foo_multi.arch_ivybridge_fma4_sse4.2()
>
>
> ___
> cfe-commits mailing list
> cfe-commits@lists.llvm.org
> http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
>
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


Re: r345109 - Debug Info (-gmodules): emit full types for non-anchored template specializations

2018-10-29 Thread David Blaikie via cfe-commits
Is this a workaround for now with the intent to fix this to allow such
implicit specializations to have their debug info modularized? I believe
this does work correctly in modular debug info with expliict modules, would
probably be sort of nice to have these things be consistent/similar?

On Tue, Oct 23, 2018 at 5:08 PM Adrian Prantl via cfe-commits <
cfe-commits@lists.llvm.org> wrote:

> Author: adrian
> Date: Tue Oct 23 17:06:02 2018
> New Revision: 345109
>
> URL: http://llvm.org/viewvc/llvm-project?rev=345109&view=rev
> Log:
> Debug Info (-gmodules): emit full types for non-anchored template
> specializations
>
> Before this patch, clang would emit a (module-)forward declaration for
> template instantiations that are not anchored by an explicit template
> instantiation, but still are guaranteed to be available in an imported
> module. Unfortunately detecting the owning module doesn't reliably
> work when local submodule visibility is enabled and the template is
> inside a cross-module namespace.
>
> This make clang debuggable again with -gmodules and LSV enabled.
>
> rdar://problem/41552377
>
> Added:
> cfe/trunk/test/Modules/Inputs/lsv-debuginfo/
> cfe/trunk/test/Modules/Inputs/lsv-debuginfo/A/
> cfe/trunk/test/Modules/Inputs/lsv-debuginfo/A/ADT.h
> cfe/trunk/test/Modules/Inputs/lsv-debuginfo/B/
> cfe/trunk/test/Modules/Inputs/lsv-debuginfo/B/B.h
> cfe/trunk/test/Modules/Inputs/lsv-debuginfo/C/
> cfe/trunk/test/Modules/Inputs/lsv-debuginfo/C/C.h
> cfe/trunk/test/Modules/Inputs/lsv-debuginfo/module.modulemap
> cfe/trunk/test/Modules/lsv-debuginfo.cpp   (with props)
> Modified:
> cfe/trunk/lib/CodeGen/CGDebugInfo.cpp
> cfe/trunk/test/Modules/ExtDebugInfo.cpp
>
> Modified: cfe/trunk/lib/CodeGen/CGDebugInfo.cpp
> URL:
> http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/CodeGen/CGDebugInfo.cpp?rev=345109&r1=345108&r2=345109&view=diff
>
> ==
> --- cfe/trunk/lib/CodeGen/CGDebugInfo.cpp (original)
> +++ cfe/trunk/lib/CodeGen/CGDebugInfo.cpp Tue Oct 23 17:06:02 2018
> @@ -1955,8 +1955,17 @@ static bool isDefinedInClangModule(const
>if (auto *CXXDecl = dyn_cast(RD)) {
>  if (!CXXDecl->isCompleteDefinition())
>return false;
> +// Check wether RD is a template.
>  auto TemplateKind = CXXDecl->getTemplateSpecializationKind();
>  if (TemplateKind != TSK_Undeclared) {
> +  // Unfortunately getOwningModule() isn't accurate enough to find the
> +  // owning module of a ClassTemplateSpecializationDecl that is
> inside a
> +  // namespace spanning multiple modules.
> +  bool Explicit = false;
> +  if (auto *TD = dyn_cast(CXXDecl))
> +Explicit = TD->isExplicitInstantiationOrSpecialization();
> +  if (!Explicit && CXXDecl->getEnclosingNamespaceContext())
> +return false;
>// This is a template, check the origin of the first member.
>if (CXXDecl->field_begin() == CXXDecl->field_end())
>  return TemplateKind == TSK_ExplicitInstantiationDeclaration;
>
> Modified: cfe/trunk/test/Modules/ExtDebugInfo.cpp
> URL:
> http://llvm.org/viewvc/llvm-project/cfe/trunk/test/Modules/ExtDebugInfo.cpp?rev=345109&r1=345108&r2=345109&view=diff
>
> ==
> --- cfe/trunk/test/Modules/ExtDebugInfo.cpp (original)
> +++ cfe/trunk/test/Modules/ExtDebugInfo.cpp Tue Oct 23 17:06:02 2018
> @@ -83,11 +83,11 @@ void foo() {
>  // CHECK: ![[NS]] = !DINamespace(name: "DebugCXX", scope: ![[MOD:[0-9]+]])
>  // CHECK: ![[MOD]] = !DIModule(scope: null, name: {{.*}}DebugCXX
>
> -// This type is anchored in the module by an explicit template
> instantiation.
> +// This type is not anchored in the module by an explicit template
> instantiation.
>  // CHECK: !DICompositeType(tag: DW_TAG_class_type,
>  // CHECK-SAME: name: "Template
> >",
>  // CHECK-SAME: scope: ![[NS]],
> -// CHECK-SAME: flags: DIFlagFwdDecl,
> +// CHECK-SAME: elements:
>  // CHECK-SAME: identifier:
> "_ZTSN8DebugCXX8TemplateIlNS_6traitsIl")
>
>  // This type is anchored in the module by an explicit template
> instantiation.
>
> Added: cfe/trunk/test/Modules/Inputs/lsv-debuginfo/A/ADT.h
> URL:
> http://llvm.org/viewvc/llvm-project/cfe/trunk/test/Modules/Inputs/lsv-debuginfo/A/ADT.h?rev=345109&view=auto
>
> ==
> --- cfe/trunk/test/Modules/Inputs/lsv-debuginfo/A/ADT.h (added)
> +++ cfe/trunk/test/Modules/Inputs/lsv-debuginfo/A/ADT.h Tue Oct 23
> 17:06:02 2018
> @@ -0,0 +1,45 @@
> +#ifndef ADT
> +#define ADT
> +
> +#ifdef WITH_NAMESPACE
> +namespace llvm {
> +#endif
> +template 
> +struct AlignedCharArray {
> +  alignas(Alignment) char buffer[Size];
> +};
> +
> +template 
> +class AlignerImpl {
> +  T1 t1;
> +};
> +
> +template 
> +union SizerImpl {
> +  char arr1[sizeof(T1)];
> +}

RE: r344957 - Give Multiversion-inline functions linkonce linkage

2018-10-29 Thread Keane, Erich via cfe-commits
GCC actually doesn’t support function multiversioning in C mode, so this fix is 
part of our extension to support C with multiversioning.  I perhaps wonder if 
this is part of the reason GCC only supports it in C++ mode...

From: David Blaikie [mailto:dblai...@gmail.com]
Sent: Monday, October 29, 2018 11:25 AM
To: Keane, Erich ; Eric Christopher 
Cc: cfe-commits@lists.llvm.org
Subject: Re: r344957 - Give Multiversion-inline functions linkonce linkage

Does this match GCC's approach here?

(I ask this sort of as throwaway/conversation starter - because the 
linkage/behavior around multiversion functions and their inlining is full of 
sharp corners/risks of code moving out of the areas appropriately restricted 
based on the cpu features)
On Mon, Oct 22, 2018 at 2:22 PM Erich Keane via cfe-commits 
mailto:cfe-commits@lists.llvm.org>> wrote:
Author: erichkeane
Date: Mon Oct 22 14:20:45 2018
New Revision: 344957

URL: http://llvm.org/viewvc/llvm-project?rev=344957&view=rev
Log:
Give Multiversion-inline functions linkonce linkage

Since multiversion variant functions can be inline, in C they become
available-externally linkage.  This ends up causing the variants to not
be emitted, and not available to the linker.

The solution is to make sure that multiversion functions are always
emitted by marking them linkonce.

Change-Id: I897aa37c7cbba0c1eb2c57ee881d5000a2113b75

Modified:
cfe/trunk/lib/CodeGen/CodeGenModule.cpp
cfe/trunk/test/CodeGen/attr-target-mv.c

Modified: cfe/trunk/lib/CodeGen/CodeGenModule.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/CodeGen/CodeGenModule.cpp?rev=344957&r1=344956&r2=344957&view=diff
==
--- cfe/trunk/lib/CodeGen/CodeGenModule.cpp (original)
+++ cfe/trunk/lib/CodeGen/CodeGenModule.cpp Mon Oct 22 14:20:45 2018
@@ -3669,6 +3669,10 @@ llvm::GlobalValue::LinkageTypes CodeGenM
   return llvm::GlobalVariable::WeakAnyLinkage;
   }

+  if (const auto *FD = D->getAsFunction())
+if (FD->isMultiVersion() && Linkage == GVA_AvailableExternally)
+  return llvm::GlobalVariable::LinkOnceAnyLinkage;
+
   // We are guaranteed to have a strong definition somewhere else,
   // so we can use available_externally linkage.
   if (Linkage == GVA_AvailableExternally)

Modified: cfe/trunk/test/CodeGen/attr-target-mv.c
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/CodeGen/attr-target-mv.c?rev=344957&r1=344956&r2=344957&view=diff
==
--- cfe/trunk/test/CodeGen/attr-target-mv.c (original)
+++ cfe/trunk/test/CodeGen/attr-target-mv.c Mon Oct 22 14:20:45 2018
@@ -88,19 +88,19 @@ void bar4() {

 // CHECK: declare i32 @foo.arch_sandybridge()

-// CHECK: define available_externally i32 @foo_inline.sse4.2()
+// CHECK: define linkonce i32 @foo_inline.sse4.2()
 // CHECK: ret i32 0

 // CHECK: declare i32 @foo_inline.arch_sandybridge()
 //
-// CHECK: define available_externally i32 @foo_inline.arch_ivybridge()
+// CHECK: define linkonce i32 @foo_inline.arch_ivybridge()
 // CHECK: ret i32 1
-// CHECK: define available_externally i32 @foo_inline()
+// CHECK: define linkonce i32 @foo_inline()
 // CHECK: ret i32 2

-// CHECK: define available_externally void @foo_decls()
-// CHECK: define available_externally void @foo_decls.sse4.2()
+// CHECK: define linkonce void @foo_decls()
+// CHECK: define linkonce void @foo_decls.sse4.2()

-// CHECK: define available_externally void @foo_multi.avx_sse4.2()
-// CHECK: define available_externally void @foo_multi.fma4_sse4.2()
-// CHECK: define available_externally void 
@foo_multi.arch_ivybridge_fma4_sse4.2()
+// CHECK: define linkonce void @foo_multi.avx_sse4.2()
+// CHECK: define linkonce void @foo_multi.fma4_sse4.2()
+// CHECK: define linkonce void @foo_multi.arch_ivybridge_fma4_sse4.2()


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


[PATCH] D53814: Allow the analyzer to output to a SARIF file

2018-10-29 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman updated this revision to Diff 171545.
aaron.ballman marked 3 inline comments as done.
aaron.ballman added a comment.

Updated based on initial review feedback, and added more context to the patch.


https://reviews.llvm.org/D53814

Files:
  Analysis/diagnostics/sarif-check.py
  Analysis/diagnostics/sarif-diagnostics-taint-test.c
  StaticAnalyzer/Core/CMakeLists.txt
  StaticAnalyzer/Core/SarifDiagnostics.cpp
  clang/StaticAnalyzer/Core/Analyses.def
  clang/StaticAnalyzer/Core/BugReporter/PathDiagnostic.h

Index: Analysis/diagnostics/sarif-diagnostics-taint-test.c
===
--- /dev/null
+++ Analysis/diagnostics/sarif-diagnostics-taint-test.c
@@ -0,0 +1,32 @@
+// RUN: %clang_analyze_cc1 -analyzer-checker=alpha.security.taint,debug.TaintTest %s -verify -analyzer-output=sarif -o %t.sarif | %python %S/sarif-check.py %s %t.sarif
+#include "../Inputs/system-header-simulator.h"
+
+int atoi(const char *nptr);
+
+void f(void) {
+  char s[80];
+  scanf("%s", s);
+  int d = atoi(s); // expected-warning {{tainted}}
+}
+
+int main(void) {
+  f();
+  return 0;
+}
+
+// Test the basics for sanity.
+// CHECK: sarifLog['version'].startswith("2.0.0")
+// CHECK: sarifLog['runs'][0]['tool']['fullName'] == "clang static analyzer"
+// CHECK: sarifLog['runs'][0]['tool']['name'] == "clang"
+// CHECK: sarifLog['runs'][0]['tool']['language'] == "en-US"
+
+// Test the specifics of this taint test.
+// CHECK: len(result(0)['codeFlows'][0]['threadFlows'][0]['locations']) == 2
+// CHECK: flow(0)['locations'][0]['step'] == 1
+// CHECK: flow(0)['locations'][0]['importance'] == "essential"
+// CHECK: flow(0)['locations'][0]['location']['message']['text'] == "Calling 'f'"
+// CHECK: flow(0)['locations'][0]['location']['physicalLocation']['region']['startLine'] == 13
+// CHECK: flow(0)['locations'][1]['step'] == 2
+// CHECK: flow(0)['locations'][1]['importance'] == "essential"
+// CHECK: flow(0)['locations'][1]['location']['message']['text'] == "tainted"
+// CHECK: flow(0)['locations'][1]['location']['physicalLocation']['region']['startLine'] == 9
Index: Analysis/diagnostics/sarif-check.py
===
--- /dev/null
+++ Analysis/diagnostics/sarif-check.py
@@ -0,0 +1,61 @@
+#!/usr/bin/env python
+
+import sys
+import subprocess
+import traceback
+import json
+
+testfile = sys.argv[1]
+with open(sys.argv[2]) as datafh:
+data = json.load(datafh)
+
+prefix = "CHECK: "
+
+def sarifLogFirstResult(idx):
+return data['runs'][0]['results'][idx]
+
+def threadFlow(idx):
+return data['runs'][0]['results'][0]['codeFlows'][0]['threadFlows'][idx]
+
+fails = 0
+passes = 0
+with open(testfile) as testfh:
+lineno = 0
+for line in iter(testfh.readline, ""):
+lineno += 1
+line = line.rstrip("\r\n")
+try:
+prefix_pos = line.index(prefix)
+except ValueError:
+continue
+check_expr = line[prefix_pos + len(prefix):]
+
+try:
+exception = None
+result = eval(check_expr, {"sarifLog":data,
+   "result":sarifLogFirstResult,
+   "flow":threadFlow})
+except Exception:
+result = False
+exception = traceback.format_exc().splitlines()[-1]
+
+if exception is not None:
+sys.stderr.write(
+"{file}:{line:d}: check threw exception: {expr}\n"
+"{file}:{line:d}: exception was: {exception}\n".format(
+file=testfile, line=lineno,
+expr=check_expr, exception=exception))
+fails += 1
+elif not result:
+sys.stderr.write(
+"{file}:{line:d}: check returned False: {expr}\n".format(
+file=testfile, line=lineno, expr=check_expr))
+fails += 1
+else:
+passes += 1
+
+if fails != 0:
+sys.exit("{} checks failed".format(fails))
+else:
+sys.stdout.write("{} checks passed\n".format(passes))
+
Index: StaticAnalyzer/Core/SarifDiagnostics.cpp
===
--- /dev/null
+++ StaticAnalyzer/Core/SarifDiagnostics.cpp
@@ -0,0 +1,267 @@
+//===--- SarifDiagnostics.cpp - Sarif Diagnostics for Paths -*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===--===//
+//
+//  This file defines the SarifDiagnostics object.
+//
+//===--===//
+
+#include "clang/Basic/Version.h"
+#include "clang/Lex/Preprocessor.h"
+#include "clang/StaticAnalyzer/Core/AnalyzerOptions.h"
+#include "clang/StaticAnalyzer/Core/BugReporter/PathDiagnostic.h"
+#include

Re: r344957 - Give Multiversion-inline functions linkonce linkage

2018-10-29 Thread David Blaikie via cfe-commits
On Mon, Oct 29, 2018 at 11:30 AM Keane, Erich  wrote:

> GCC actually doesn’t support function multiversioning in C mode, so this
> fix is part of our extension to support C with multiversioning.
>

Ah, what's the motivation for that?


>   I perhaps wonder if this is part of the reason GCC only supports it in
> C++ mode...
>

Yeah... could be.

I mean I suppose using linkonce isn't making multiversioning any worse in C
than it already is in C++ inline functions (which is where it's pretty easy
to misuse, as I understand it - two files, one compiled with a CPU feature,
one without, linkonce functions get linked together & the linker picks one
- then code built without the feature calls code that uses the feature -
but, I mean, that can happen even witohut multiversioning, if you compile
some source files with a feature and some without) - I guess the main risk
would be if it confuses users by making multiversioned C inline functions
end up behaving too differently from non-multiversioned ones...

- Dave


>
>
> *From:* David Blaikie [mailto:dblai...@gmail.com]
> *Sent:* Monday, October 29, 2018 11:25 AM
> *To:* Keane, Erich ; Eric Christopher <
> echri...@gmail.com>
> *Cc:* cfe-commits@lists.llvm.org
> *Subject:* Re: r344957 - Give Multiversion-inline functions linkonce
> linkage
>
>
>
> Does this match GCC's approach here?
>
> (I ask this sort of as throwaway/conversation starter - because the
> linkage/behavior around multiversion functions and their inlining is full
> of sharp corners/risks of code moving out of the areas appropriately
> restricted based on the cpu features)
>
> On Mon, Oct 22, 2018 at 2:22 PM Erich Keane via cfe-commits <
> cfe-commits@lists.llvm.org> wrote:
>
> Author: erichkeane
> Date: Mon Oct 22 14:20:45 2018
> New Revision: 344957
>
> URL: http://llvm.org/viewvc/llvm-project?rev=344957&view=rev
> Log:
> Give Multiversion-inline functions linkonce linkage
>
> Since multiversion variant functions can be inline, in C they become
> available-externally linkage.  This ends up causing the variants to not
> be emitted, and not available to the linker.
>
> The solution is to make sure that multiversion functions are always
> emitted by marking them linkonce.
>
> Change-Id: I897aa37c7cbba0c1eb2c57ee881d5000a2113b75
>
> Modified:
> cfe/trunk/lib/CodeGen/CodeGenModule.cpp
> cfe/trunk/test/CodeGen/attr-target-mv.c
>
> Modified: cfe/trunk/lib/CodeGen/CodeGenModule.cpp
> URL:
> http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/CodeGen/CodeGenModule.cpp?rev=344957&r1=344956&r2=344957&view=diff
>
> ==
> --- cfe/trunk/lib/CodeGen/CodeGenModule.cpp (original)
> +++ cfe/trunk/lib/CodeGen/CodeGenModule.cpp Mon Oct 22 14:20:45 2018
> @@ -3669,6 +3669,10 @@ llvm::GlobalValue::LinkageTypes CodeGenM
>return llvm::GlobalVariable::WeakAnyLinkage;
>}
>
> +  if (const auto *FD = D->getAsFunction())
> +if (FD->isMultiVersion() && Linkage == GVA_AvailableExternally)
> +  return llvm::GlobalVariable::LinkOnceAnyLinkage;
> +
>// We are guaranteed to have a strong definition somewhere else,
>// so we can use available_externally linkage.
>if (Linkage == GVA_AvailableExternally)
>
> Modified: cfe/trunk/test/CodeGen/attr-target-mv.c
> URL:
> http://llvm.org/viewvc/llvm-project/cfe/trunk/test/CodeGen/attr-target-mv.c?rev=344957&r1=344956&r2=344957&view=diff
>
> ==
> --- cfe/trunk/test/CodeGen/attr-target-mv.c (original)
> +++ cfe/trunk/test/CodeGen/attr-target-mv.c Mon Oct 22 14:20:45 2018
> @@ -88,19 +88,19 @@ void bar4() {
>
>  // CHECK: declare i32 @foo.arch_sandybridge()
>
> -// CHECK: define available_externally i32 @foo_inline.sse4.2()
> +// CHECK: define linkonce i32 @foo_inline.sse4.2()
>  // CHECK: ret i32 0
>
>  // CHECK: declare i32 @foo_inline.arch_sandybridge()
>  //
> -// CHECK: define available_externally i32 @foo_inline.arch_ivybridge()
> +// CHECK: define linkonce i32 @foo_inline.arch_ivybridge()
>  // CHECK: ret i32 1
> -// CHECK: define available_externally i32 @foo_inline()
> +// CHECK: define linkonce i32 @foo_inline()
>  // CHECK: ret i32 2
>
> -// CHECK: define available_externally void @foo_decls()
> -// CHECK: define available_externally void @foo_decls.sse4.2()
> +// CHECK: define linkonce void @foo_decls()
> +// CHECK: define linkonce void @foo_decls.sse4.2()
>
> -// CHECK: define available_externally void @foo_multi.avx_sse4.2()
> -// CHECK: define available_externally void @foo_multi.fma4_sse4.2()
> -// CHECK: define available_externally void
> @foo_multi.arch_ivybridge_fma4_sse4.2()
> +// CHECK: define linkonce void @foo_multi.avx_sse4.2()
> +// CHECK: define linkonce void @foo_multi.fma4_sse4.2()
> +// CHECK: define linkonce void @foo_multi.arch_ivybridge_fma4_sse4.2()
>
>
> ___
> cfe-commits mailing list
> cfe-commits@lists.llvm.org
> http://lists.llvm.

RE: r344957 - Give Multiversion-inline functions linkonce linkage

2018-10-29 Thread Keane, Erich via cfe-commits

From: David Blaikie [mailto:dblai...@gmail.com]
Sent: Monday, October 29, 2018 11:41 AM
To: Keane, Erich 
Cc: Eric Christopher ; cfe-commits@lists.llvm.org
Subject: Re: r344957 - Give Multiversion-inline functions linkonce linkage


On Mon, Oct 29, 2018 at 11:30 AM Keane, Erich 
mailto:erich.ke...@intel.com>> wrote:
GCC actually doesn’t support function multiversioning in C mode, so this fix is 
part of our extension to support C with multiversioning.

Ah, what's the motivation for that?
[Keane, Erich] Basically, I identified no good reason to not support it.  GCC’s 
motivation is lost to time as far as I can tell.  This multiversioning is super 
useful in my employer’s math/intrinsic libraries (MKL uses this feature 
extensively), so enabling it in C seemed like a positive improvement.  We’ve 
made some other behavioral changes to make ‘target’ work more sanely to 
suppress some of the worst bugs (becoming MV after usage) as well as make it 
work better with Clang’s emit-functionality.


  I perhaps wonder if this is part of the reason GCC only supports it in C++ 
mode...

Yeah... could be.

I mean I suppose using linkonce isn't making multiversioning any worse in C 
than it already is in C++ inline functions (which is where it's pretty easy to 
misuse, as I understand it - two files, one compiled with a CPU feature, one 
without, linkonce functions get linked together & the linker picks one - then 
code built without the feature calls code that uses the feature - but, I mean, 
that can happen even witohut multiversioning, if you compile some source files 
with a feature and some without) - I guess the main risk would be if it 
confuses users by making multiversioned C inline functions end up behaving too 
differently from non-multiversioned ones...
[Keane, Erich] I suspect that multiversioning is such a sharp edged feature, 
that a change like this makes it a touch more sane.  Since the individual 
versions are independently mangled, you don’t have to worry about merging 
different versions.  The only real issue comes from merging the resolver 
functions if the visible list of declarations is different, but we treat that 
as an ODR violation.


- Dave


From: David Blaikie [mailto:dblai...@gmail.com]
Sent: Monday, October 29, 2018 11:25 AM
To: Keane, Erich mailto:erich.ke...@intel.com>>; Eric 
Christopher mailto:echri...@gmail.com>>
Cc: cfe-commits@lists.llvm.org
Subject: Re: r344957 - Give Multiversion-inline functions linkonce linkage

Does this match GCC's approach here?

(I ask this sort of as throwaway/conversation starter - because the 
linkage/behavior around multiversion functions and their inlining is full of 
sharp corners/risks of code moving out of the areas appropriately restricted 
based on the cpu features)
On Mon, Oct 22, 2018 at 2:22 PM Erich Keane via cfe-commits 
mailto:cfe-commits@lists.llvm.org>> wrote:
Author: erichkeane
Date: Mon Oct 22 14:20:45 2018
New Revision: 344957

URL: http://llvm.org/viewvc/llvm-project?rev=344957&view=rev
Log:
Give Multiversion-inline functions linkonce linkage

Since multiversion variant functions can be inline, in C they become
available-externally linkage.  This ends up causing the variants to not
be emitted, and not available to the linker.

The solution is to make sure that multiversion functions are always
emitted by marking them linkonce.

Change-Id: I897aa37c7cbba0c1eb2c57ee881d5000a2113b75

Modified:
cfe/trunk/lib/CodeGen/CodeGenModule.cpp
cfe/trunk/test/CodeGen/attr-target-mv.c

Modified: cfe/trunk/lib/CodeGen/CodeGenModule.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/CodeGen/CodeGenModule.cpp?rev=344957&r1=344956&r2=344957&view=diff
==
--- cfe/trunk/lib/CodeGen/CodeGenModule.cpp (original)
+++ cfe/trunk/lib/CodeGen/CodeGenModule.cpp Mon Oct 22 14:20:45 2018
@@ -3669,6 +3669,10 @@ llvm::GlobalValue::LinkageTypes CodeGenM
   return llvm::GlobalVariable::WeakAnyLinkage;
   }

+  if (const auto *FD = D->getAsFunction())
+if (FD->isMultiVersion() && Linkage == GVA_AvailableExternally)
+  return llvm::GlobalVariable::LinkOnceAnyLinkage;
+
   // We are guaranteed to have a strong definition somewhere else,
   // so we can use available_externally linkage.
   if (Linkage == GVA_AvailableExternally)

Modified: cfe/trunk/test/CodeGen/attr-target-mv.c
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/CodeGen/attr-target-mv.c?rev=344957&r1=344956&r2=344957&view=diff
==
--- cfe/trunk/test/CodeGen/attr-target-mv.c (original)
+++ cfe/trunk/test/CodeGen/attr-target-mv.c Mon Oct 22 14:20:45 2018
@@ -88,19 +88,19 @@ void bar4() {

 // CHECK: declare i32 @foo.arch_sandybridge()

-// CHECK: define available_externally i32 @foo_inline.sse4.2()
+// CHECK: define linkonce i32 @foo_inline.sse4.2()
 // CHECK: ret i3

Re: r344957 - Give Multiversion-inline functions linkonce linkage

2018-10-29 Thread David Blaikie via cfe-commits
On Mon, Oct 29, 2018 at 11:46 AM Keane, Erich  wrote:

>
>
>
>
> *From:* David Blaikie [mailto:dblai...@gmail.com]
> *Sent:* Monday, October 29, 2018 11:41 AM
> *To:* Keane, Erich 
> *Cc:* Eric Christopher ; cfe-commits@lists.llvm.org
>
>
> *Subject:* Re: r344957 - Give Multiversion-inline functions linkonce
> linkage
>
>
>
>
>
> On Mon, Oct 29, 2018 at 11:30 AM Keane, Erich 
> wrote:
>
> GCC actually doesn’t support function multiversioning in C mode, so this
> fix is part of our extension to support C with multiversioning.
>
>
> Ah, what's the motivation for that?
>
> *[Keane, Erich] Basically, I identified no good reason to not support it.
> GCC’s motivation is lost to time as far as I can tell.  This
> multiversioning is super useful in my employer’s math/intrinsic libraries
> (MKL uses this feature extensively), so enabling it in C seemed like a
> positive improvement.  We’ve made some other behavioral changes to make
> ‘target’ work more sanely to suppress some of the worst bugs (becoming MV
> after usage) as well as make it work better with Clang’s
> emit-functionality.*
>
>
>
>
>   I perhaps wonder if this is part of the reason GCC only supports it in
> C++ mode...
>
>
> Yeah... could be.
>
> I mean I suppose using linkonce isn't making multiversioning any worse in
> C than it already is in C++ inline functions (which is where it's pretty
> easy to misuse, as I understand it - two files, one compiled with a CPU
> feature, one without, linkonce functions get linked together & the linker
> picks one - then code built without the feature calls code that uses the
> feature - but, I mean, that can happen even witohut multiversioning, if you
> compile some source files with a feature and some without) - I guess the
> main risk would be if it confuses users by making multiversioned C inline
> functions end up behaving too differently from non-multiversioned ones...
>
> *[Keane, Erich] I suspect that multiversioning is such a sharp edged
> feature, that a change like this makes it a touch more sane.  Since the
> individual versions are independently mangled, you don’t have to worry
> about merging different versions.  The only real issue comes from merging
> the resolver functions if the visible list of declarations is different,
> but we treat that as an ODR violation.*
>
>
>
Rightio - thanks for all the context (:


>
> - Dave
>
>
>
>
> *From:* David Blaikie [mailto:dblai...@gmail.com]
> *Sent:* Monday, October 29, 2018 11:25 AM
> *To:* Keane, Erich ; Eric Christopher <
> echri...@gmail.com>
> *Cc:* cfe-commits@lists.llvm.org
> *Subject:* Re: r344957 - Give Multiversion-inline functions linkonce
> linkage
>
>
>
> Does this match GCC's approach here?
>
> (I ask this sort of as throwaway/conversation starter - because the
> linkage/behavior around multiversion functions and their inlining is full
> of sharp corners/risks of code moving out of the areas appropriately
> restricted based on the cpu features)
>
> On Mon, Oct 22, 2018 at 2:22 PM Erich Keane via cfe-commits <
> cfe-commits@lists.llvm.org> wrote:
>
> Author: erichkeane
> Date: Mon Oct 22 14:20:45 2018
> New Revision: 344957
>
> URL: http://llvm.org/viewvc/llvm-project?rev=344957&view=rev
> Log:
> Give Multiversion-inline functions linkonce linkage
>
> Since multiversion variant functions can be inline, in C they become
> available-externally linkage.  This ends up causing the variants to not
> be emitted, and not available to the linker.
>
> The solution is to make sure that multiversion functions are always
> emitted by marking them linkonce.
>
> Change-Id: I897aa37c7cbba0c1eb2c57ee881d5000a2113b75
>
> Modified:
> cfe/trunk/lib/CodeGen/CodeGenModule.cpp
> cfe/trunk/test/CodeGen/attr-target-mv.c
>
> Modified: cfe/trunk/lib/CodeGen/CodeGenModule.cpp
> URL:
> http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/CodeGen/CodeGenModule.cpp?rev=344957&r1=344956&r2=344957&view=diff
>
> ==
> --- cfe/trunk/lib/CodeGen/CodeGenModule.cpp (original)
> +++ cfe/trunk/lib/CodeGen/CodeGenModule.cpp Mon Oct 22 14:20:45 2018
> @@ -3669,6 +3669,10 @@ llvm::GlobalValue::LinkageTypes CodeGenM
>return llvm::GlobalVariable::WeakAnyLinkage;
>}
>
> +  if (const auto *FD = D->getAsFunction())
> +if (FD->isMultiVersion() && Linkage == GVA_AvailableExternally)
> +  return llvm::GlobalVariable::LinkOnceAnyLinkage;
> +
>// We are guaranteed to have a strong definition somewhere else,
>// so we can use available_externally linkage.
>if (Linkage == GVA_AvailableExternally)
>
> Modified: cfe/trunk/test/CodeGen/attr-target-mv.c
> URL:
> http://llvm.org/viewvc/llvm-project/cfe/trunk/test/CodeGen/attr-target-mv.c?rev=344957&r1=344956&r2=344957&view=diff
>
> ==
> --- cfe/trunk/test/CodeGen/attr-target-mv.c (original)
> +++ cfe/trunk/test/CodeGen/attr-target-mv.c Mon Oct 22 14:20:45 2018
> @@ -88,1

[clang-tools-extra] r345522 - [clang-query] Add non-exclusive output API

2018-10-29 Thread Stephen Kelly via cfe-commits
Author: steveire
Date: Mon Oct 29 11:59:56 2018
New Revision: 345522

URL: http://llvm.org/viewvc/llvm-project?rev=345522&view=rev
Log:
[clang-query] Add non-exclusive output API

Summary:
Add granular options for AST dumping, text printing and diagnostics.

This makes it possible to

* Have both diag and dump active at once
* Extend the output with other queryable content in the future.

Reviewers: aaron.ballman, pcc, ioeric, ilya-biryukov, klimek, sammccall

Reviewed By: aaron.ballman

Subscribers: cfe-commits

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

Modified:
clang-tools-extra/trunk/clang-query/Query.cpp
clang-tools-extra/trunk/clang-query/Query.h
clang-tools-extra/trunk/clang-query/QueryParser.cpp
clang-tools-extra/trunk/clang-query/QueryParser.h
clang-tools-extra/trunk/unittests/clang-query/QueryEngineTest.cpp
clang-tools-extra/trunk/unittests/clang-query/QueryParserTest.cpp

Modified: clang-tools-extra/trunk/clang-query/Query.cpp
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clang-query/Query.cpp?rev=345522&r1=345521&r2=345522&view=diff
==
--- clang-tools-extra/trunk/clang-query/Query.cpp (original)
+++ clang-tools-extra/trunk/clang-query/Query.cpp Mon Oct 29 11:59:56 2018
@@ -45,6 +45,10 @@ bool HelpQuery::run(llvm::raw_ostream &O
 "Set whether to print the current matcher,\n"
 "  set output   "
 "Set whether to output only  content.\n"
+"  enable output"
+"Enable  content non-exclusively.\n"
+"  disable output   "
+"Disable  content non-exclusively.\n"
 "  quit, q   "
 "Terminates the query session.\n\n"
 "Several commands accept a  parameter. The available features 
"

Modified: clang-tools-extra/trunk/clang-query/Query.h
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clang-query/Query.h?rev=345522&r1=345521&r2=345522&view=diff
==
--- clang-tools-extra/trunk/clang-query/Query.h (original)
+++ clang-tools-extra/trunk/clang-query/Query.h Mon Oct 29 11:59:56 2018
@@ -29,6 +29,8 @@ enum QueryKind {
   QK_Match,
   QK_SetBool,
   QK_SetOutputKind,
+  QK_EnableOutputKind,
+  QK_DisableOutputKind,
   QK_Quit
 };
 
@@ -151,6 +153,36 @@ struct SetExclusiveOutputQuery : Query {
   bool QuerySession::*Var;
 };
 
+// Implements the non-exclusive 'set output dump|diag|print' options.
+struct SetNonExclusiveOutputQuery : Query {
+  SetNonExclusiveOutputQuery(QueryKind Kind, bool QuerySession::*Var,
+ bool Value)
+  : Query(Kind), Var(Var), Value(Value) {}
+  bool run(llvm::raw_ostream &OS, QuerySession &QS) const override {
+QS.*Var = Value;
+return true;
+  }
+
+  bool QuerySession::*Var;
+  bool Value;
+};
+
+struct EnableOutputQuery : SetNonExclusiveOutputQuery {
+  EnableOutputQuery(bool QuerySession::*Var)
+  : SetNonExclusiveOutputQuery(QK_EnableOutputKind, Var, true) {}
+
+  static bool classof(const Query *Q) { return Q->Kind == QK_EnableOutputKind; 
}
+};
+
+struct DisableOutputQuery : SetNonExclusiveOutputQuery {
+  DisableOutputQuery(bool QuerySession::*Var)
+  : SetNonExclusiveOutputQuery(QK_DisableOutputKind, Var, false) {}
+
+  static bool classof(const Query *Q) {
+return Q->Kind == QK_DisableOutputKind;
+  }
+};
+
 } // namespace query
 } // namespace clang
 

Modified: clang-tools-extra/trunk/clang-query/QueryParser.cpp
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clang-query/QueryParser.cpp?rev=345522&r1=345521&r2=345522&view=diff
==
--- clang-tools-extra/trunk/clang-query/QueryParser.cpp (original)
+++ clang-tools-extra/trunk/clang-query/QueryParser.cpp Mon Oct 29 11:59:56 2018
@@ -106,7 +106,7 @@ QueryRef QueryParser::parseSetBool(bool
   return new SetQuery(Var, Value);
 }
 
-QueryRef QueryParser::parseSetOutputKind() {
+template  QueryRef QueryParser::parseSetOutputKind() {
   StringRef ValStr;
   unsigned OutKind = LexOrCompleteWord(this, ValStr)
  .Case("diag", OK_Diag)
@@ -122,11 +122,11 @@ QueryRef QueryParser::parseSetOutputKind
 
   switch (OutKind) {
   case OK_DetailedAST:
-return new SetExclusiveOutputQuery(&QuerySession::DetailedASTOutput);
+return new QueryType(&QuerySession::DetailedASTOutput);
   case OK_Diag:
-return new SetExclusiveOutputQuery(&QuerySession::DiagOutput);
+return new QueryType(&QuerySession::DiagOutput);
   case OK_Print:
-return new SetExclusiveOutputQuery(&QuerySession::PrintOutput);
+return new QueryType(&QuerySession::PrintOutput);
   }
 
   llvm_unreachable("Invalid output kind");
@@ -151,7 +151,9 @@ enum ParsedQueryKind {
   PQK_Match,
   PQK_Set,
   PQK_Unlet,
-  PQK_Quit
+  PQK_Quit,
+  PQK_Enable,

[PATCH] D52857: [clang-query] Add non-exclusive output API

2018-10-29 Thread Stephen Kelly via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rL345522: [clang-query] Add non-exclusive output API (authored 
by steveire, committed by ).
Herald added a subscriber: llvm-commits.

Changed prior to commit:
  https://reviews.llvm.org/D52857?vs=171046&id=171549#toc

Repository:
  rL LLVM

https://reviews.llvm.org/D52857

Files:
  clang-tools-extra/trunk/clang-query/Query.cpp
  clang-tools-extra/trunk/clang-query/Query.h
  clang-tools-extra/trunk/clang-query/QueryParser.cpp
  clang-tools-extra/trunk/clang-query/QueryParser.h
  clang-tools-extra/trunk/unittests/clang-query/QueryEngineTest.cpp
  clang-tools-extra/trunk/unittests/clang-query/QueryParserTest.cpp

Index: clang-tools-extra/trunk/clang-query/Query.h
===
--- clang-tools-extra/trunk/clang-query/Query.h
+++ clang-tools-extra/trunk/clang-query/Query.h
@@ -29,6 +29,8 @@
   QK_Match,
   QK_SetBool,
   QK_SetOutputKind,
+  QK_EnableOutputKind,
+  QK_DisableOutputKind,
   QK_Quit
 };
 
@@ -151,6 +153,36 @@
   bool QuerySession::*Var;
 };
 
+// Implements the non-exclusive 'set output dump|diag|print' options.
+struct SetNonExclusiveOutputQuery : Query {
+  SetNonExclusiveOutputQuery(QueryKind Kind, bool QuerySession::*Var,
+ bool Value)
+  : Query(Kind), Var(Var), Value(Value) {}
+  bool run(llvm::raw_ostream &OS, QuerySession &QS) const override {
+QS.*Var = Value;
+return true;
+  }
+
+  bool QuerySession::*Var;
+  bool Value;
+};
+
+struct EnableOutputQuery : SetNonExclusiveOutputQuery {
+  EnableOutputQuery(bool QuerySession::*Var)
+  : SetNonExclusiveOutputQuery(QK_EnableOutputKind, Var, true) {}
+
+  static bool classof(const Query *Q) { return Q->Kind == QK_EnableOutputKind; }
+};
+
+struct DisableOutputQuery : SetNonExclusiveOutputQuery {
+  DisableOutputQuery(bool QuerySession::*Var)
+  : SetNonExclusiveOutputQuery(QK_DisableOutputKind, Var, false) {}
+
+  static bool classof(const Query *Q) {
+return Q->Kind == QK_DisableOutputKind;
+  }
+};
+
 } // namespace query
 } // namespace clang
 
Index: clang-tools-extra/trunk/clang-query/QueryParser.h
===
--- clang-tools-extra/trunk/clang-query/QueryParser.h
+++ clang-tools-extra/trunk/clang-query/QueryParser.h
@@ -44,7 +44,7 @@
   template  struct LexOrCompleteWord;
 
   QueryRef parseSetBool(bool QuerySession::*Var);
-  QueryRef parseSetOutputKind();
+  template  QueryRef parseSetOutputKind();
   QueryRef completeMatcherExpression();
 
   QueryRef endQuery(QueryRef Q);
Index: clang-tools-extra/trunk/clang-query/Query.cpp
===
--- clang-tools-extra/trunk/clang-query/Query.cpp
+++ clang-tools-extra/trunk/clang-query/Query.cpp
@@ -45,6 +45,10 @@
 "Set whether to print the current matcher,\n"
 "  set output   "
 "Set whether to output only  content.\n"
+"  enable output"
+"Enable  content non-exclusively.\n"
+"  disable output   "
+"Disable  content non-exclusively.\n"
 "  quit, q   "
 "Terminates the query session.\n\n"
 "Several commands accept a  parameter. The available features "
Index: clang-tools-extra/trunk/clang-query/QueryParser.cpp
===
--- clang-tools-extra/trunk/clang-query/QueryParser.cpp
+++ clang-tools-extra/trunk/clang-query/QueryParser.cpp
@@ -106,7 +106,7 @@
   return new SetQuery(Var, Value);
 }
 
-QueryRef QueryParser::parseSetOutputKind() {
+template  QueryRef QueryParser::parseSetOutputKind() {
   StringRef ValStr;
   unsigned OutKind = LexOrCompleteWord(this, ValStr)
  .Case("diag", OK_Diag)
@@ -122,11 +122,11 @@
 
   switch (OutKind) {
   case OK_DetailedAST:
-return new SetExclusiveOutputQuery(&QuerySession::DetailedASTOutput);
+return new QueryType(&QuerySession::DetailedASTOutput);
   case OK_Diag:
-return new SetExclusiveOutputQuery(&QuerySession::DiagOutput);
+return new QueryType(&QuerySession::DiagOutput);
   case OK_Print:
-return new SetExclusiveOutputQuery(&QuerySession::PrintOutput);
+return new QueryType(&QuerySession::PrintOutput);
   }
 
   llvm_unreachable("Invalid output kind");
@@ -151,7 +151,9 @@
   PQK_Match,
   PQK_Set,
   PQK_Unlet,
-  PQK_Quit
+  PQK_Quit,
+  PQK_Enable,
+  PQK_Disable
 };
 
 enum ParsedQueryVariable {
@@ -193,6 +195,8 @@
   .Case("q", PQK_Quit,  /*IsCompletion=*/false)
   .Case("quit", PQK_Quit)
   .Case("set", PQK_Set)
+  .Case("enable", PQK_Enable)
+  .Case("disable", PQK_Disable)
   .Case("unlet", PQK_Unlet)
   .Default(PQ

  1   2   >