[PATCH] D44100: [ASTImporter] Reorder fields after structure import is finished

2018-03-06 Thread Gábor Horváth via Phabricator via cfe-commits
xazax.hun added a comment.

Hi Aleksei!

Just a minor high level note. If https://reviews.llvm.org/D32947 will be 
accepted once, we will need to reorder friends as well. Or alternatively, we 
have to omit the check of friends in structural equivalence in 
https://reviews.llvm.org/D32947.


Repository:
  rC Clang

https://reviews.llvm.org/D44100



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


[PATCH] D44137: [clang-tidy] Fix one corner case in make-unique check.

2018-03-06 Thread Haojian Wu via Phabricator via cfe-commits
hokein created this revision.
hokein added a reviewer: ilya-biryukov.
Herald added subscribers: xazax.hun, klimek.

Previously, we tried to cover all "std::initializer_list" implicit conversion
cases in the code, but there are some corner cases that not covered (see
newly-added test in the patch).

Sipping all implicit AST nodes is a better way to filter out all these cases.


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D44137

Files:
  clang-tidy/modernize/MakeSmartPtrCheck.cpp
  test/clang-tidy/modernize-make-unique.cpp


Index: test/clang-tidy/modernize-make-unique.cpp
===
--- test/clang-tidy/modernize-make-unique.cpp
+++ test/clang-tidy/modernize-make-unique.cpp
@@ -50,6 +50,7 @@
 
 struct H {
   H(std::vector);
+  H(std::vector &, double);
   H(MyVector, int);
 };
 
@@ -344,6 +345,13 @@
   // CHECK-MESSAGES: :[[@LINE-1]]:7: warning: use std::make_unique instead
   // CHECK-FIXES: PH2.reset(new H({1, 2, 3}, 1));
 
+  std::unique_ptr PH3 = std::unique_ptr(new H({1, 2, 3}, 1.0));
+  // CHECK-MESSAGES: :[[@LINE-1]]:28: warning: use std::make_unique instead
+  // CHECK-FIXES: std::unique_ptr PH3 = std::unique_ptr(new H({1, 2, 3}, 
1.0));
+  PH3.reset(new H({1, 2, 3}, 1.0));
+  // CHECK-MESSAGES: :[[@LINE-1]]:7: warning: use std::make_unique instead
+  // CHECK-FIXES: PH3.reset(new H({1, 2, 3}, 1.0));
+
   std::unique_ptr PI1 = std::unique_ptr(new I(G({1, 2, 3})));
   // CHECK-MESSAGES: :[[@LINE-1]]:28: warning: use std::make_unique instead
   // CHECK-FIXES: std::unique_ptr PI1 = std::make_unique(G({1, 2, 3}));
Index: clang-tidy/modernize/MakeSmartPtrCheck.cpp
===
--- clang-tidy/modernize/MakeSmartPtrCheck.cpp
+++ clang-tidy/modernize/MakeSmartPtrCheck.cpp
@@ -295,16 +295,8 @@
   }
   return false;
 };
-// Check the implicit conversion from the std::initializer_list type to
-// a class type.
-if (IsStdInitListInitConstructExpr(Arg))
+if (IsStdInitListInitConstructExpr(Arg->IgnoreImplicit()))
   return false;
-// The Arg can be a CXXBindTemporaryExpr, checking its underlying
-// construct expr.
-if (const auto * CTE = dyn_cast(Arg)) {
-  if (IsStdInitListInitConstructExpr(CTE->getSubExpr()))
-return false;
-}
   }
 }
 if (ArraySizeExpr.empty()) {


Index: test/clang-tidy/modernize-make-unique.cpp
===
--- test/clang-tidy/modernize-make-unique.cpp
+++ test/clang-tidy/modernize-make-unique.cpp
@@ -50,6 +50,7 @@
 
 struct H {
   H(std::vector);
+  H(std::vector &, double);
   H(MyVector, int);
 };
 
@@ -344,6 +345,13 @@
   // CHECK-MESSAGES: :[[@LINE-1]]:7: warning: use std::make_unique instead
   // CHECK-FIXES: PH2.reset(new H({1, 2, 3}, 1));
 
+  std::unique_ptr PH3 = std::unique_ptr(new H({1, 2, 3}, 1.0));
+  // CHECK-MESSAGES: :[[@LINE-1]]:28: warning: use std::make_unique instead
+  // CHECK-FIXES: std::unique_ptr PH3 = std::unique_ptr(new H({1, 2, 3}, 1.0));
+  PH3.reset(new H({1, 2, 3}, 1.0));
+  // CHECK-MESSAGES: :[[@LINE-1]]:7: warning: use std::make_unique instead
+  // CHECK-FIXES: PH3.reset(new H({1, 2, 3}, 1.0));
+
   std::unique_ptr PI1 = std::unique_ptr(new I(G({1, 2, 3})));
   // CHECK-MESSAGES: :[[@LINE-1]]:28: warning: use std::make_unique instead
   // CHECK-FIXES: std::unique_ptr PI1 = std::make_unique(G({1, 2, 3}));
Index: clang-tidy/modernize/MakeSmartPtrCheck.cpp
===
--- clang-tidy/modernize/MakeSmartPtrCheck.cpp
+++ clang-tidy/modernize/MakeSmartPtrCheck.cpp
@@ -295,16 +295,8 @@
   }
   return false;
 };
-// Check the implicit conversion from the std::initializer_list type to
-// a class type.
-if (IsStdInitListInitConstructExpr(Arg))
+if (IsStdInitListInitConstructExpr(Arg->IgnoreImplicit()))
   return false;
-// The Arg can be a CXXBindTemporaryExpr, checking its underlying
-// construct expr.
-if (const auto * CTE = dyn_cast(Arg)) {
-  if (IsStdInitListInitConstructExpr(CTE->getSubExpr()))
-return false;
-}
   }
 }
 if (ArraySizeExpr.empty()) {
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D44100: [ASTImporter] Reorder fields after structure import is finished

2018-03-06 Thread Aleksei Sidorin via Phabricator via cfe-commits
a.sidorin added a comment.

Hi Gabor,

> Just a minor high level note. If https://reviews.llvm.org/D32947 will be 
> accepted once, we will need to reorder friends as well. Or alternatively, we 
> have to omit the check of friends in structural equivalence in 
> https://reviews.llvm.org/D32947.

I'd prefer to land https://reviews.llvm.org/D32947 before the fix for friend 
decls reordering so we will have a subject for testing. And the fix for friend 
decls can become a separate patch. Do you already have such patch or a test for 
the issue?


Repository:
  rC Clang

https://reviews.llvm.org/D44100



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


[PATCH] D44138: [clangd] Sort includes when formatting code or inserting new includes.

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

Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D44138

Files:
  clangd/ClangdServer.cpp
  unittests/clangd/ClangdTests.cpp

Index: unittests/clangd/ClangdTests.cpp
===
--- unittests/clangd/ClangdTests.cpp
+++ unittests/clangd/ClangdTests.cpp
@@ -945,22 +945,26 @@
 
   auto FooCpp = testPath("foo.cpp");
   const auto Code = R"cpp(
+#include "z.h"
 #include "x.h"
 
 void f() {}
 )cpp";
   FS.Files[FooCpp] = Code;
   runAddDocument(Server, FooCpp, Code);
 
-  auto Inserted = [&](llvm::StringRef Original, llvm::StringRef Preferred,
-  llvm::StringRef Expected) {
+  auto ChangedCode = [&](llvm::StringRef Original, llvm::StringRef Preferred) {
 auto Replaces = Server.insertInclude(
 FooCpp, Code, Original, Preferred.empty() ? Original : Preferred);
 EXPECT_TRUE(static_cast(Replaces));
 auto Changed = tooling::applyAllReplacements(Code, *Replaces);
 EXPECT_TRUE(static_cast(Changed));
-return llvm::StringRef(*Changed).contains(
-(llvm::Twine("#include ") + Expected + "").str());
+return *Changed;
+  };
+  auto Inserted = [&](llvm::StringRef Original, llvm::StringRef Preferred,
+  llvm::StringRef Expected) {
+return llvm::StringRef(ChangedCode(Original, Preferred))
+.contains((llvm::Twine("#include ") + Expected + "").str());
   };
 
   EXPECT_TRUE(Inserted("\"y.h\"", /*Preferred=*/"","\"y.h\""));
@@ -976,6 +980,45 @@
/*Preferred=*/"", ""));
   EXPECT_TRUE(Inserted(OriginalHeader, PreferredHeader, "\"Y.h\""));
   EXPECT_TRUE(Inserted("", PreferredHeader, "\"Y.h\""));
+
+  // Check that includes are sorted.
+  const auto Expected = R"cpp(
+#include "x.h"
+#include "y.h"
+#include "z.h"
+
+void f() {}
+)cpp";
+  EXPECT_EQ(Expected, ChangedCode("\"y.h\"", /*Preferred=*/""));
+}
+
+TEST_F(ClangdVFSTest, FormatCode) {
+  MockFSProvider FS;
+  ErrorCheckingDiagConsumer DiagConsumer;
+  MockCompilationDatabase CDB;
+  ClangdServer Server(CDB, FS, DiagConsumer, ClangdServer::optsForTest());
+
+  auto Path = testPath("foo.cpp");
+  std::string Code = R"cpp(
+#include "y.h"
+#include "x.h"
+
+void f(  )  {}
+)cpp";
+  std::string Expected = R"cpp(
+#include "x.h"
+#include "y.h"
+
+void f() {}
+)cpp";
+  FS.Files[Path] = Code;
+  runAddDocument(Server, Path, Code);
+
+  auto Replaces = Server.formatFile(Code, Path);
+  EXPECT_TRUE(static_cast(Replaces));
+  auto Changed = tooling::applyAllReplacements(Code, *Replaces);
+  EXPECT_TRUE(static_cast(Changed));
+  EXPECT_EQ(Expected, *Changed);
 }
 
 } // namespace
Index: clangd/ClangdServer.cpp
===
--- clangd/ClangdServer.cpp
+++ clangd/ClangdServer.cpp
@@ -353,8 +353,11 @@
   // Replacement with offset UINT_MAX and length 0 will be treated as include
   // insertion.
   tooling::Replacement R(File, /*Offset=*/UINT_MAX, 0, "#include " + ToInclude);
-  return format::cleanupAroundReplacements(Code, tooling::Replacements(R),
-   *Style);
+  auto Replaces = format::cleanupAroundReplacements(
+  Code, tooling::Replacements(R), *Style);
+  if (!Replaces)
+return Replaces;
+  return formatReplacements(Code, *Replaces, *Style);
 }
 
 llvm::Optional ClangdServer::getDocument(PathRef File) {
@@ -465,13 +468,21 @@
  ArrayRef Ranges) {
   // Call clang-format.
   auto TaggedFS = FSProvider.getTaggedFileSystem(File);
-  auto StyleOrError =
+  auto Style =
   format::getStyle("file", File, "LLVM", Code, TaggedFS.Value.get());
-  if (!StyleOrError) {
-return StyleOrError.takeError();
-  } else {
-return format::reformat(StyleOrError.get(), Code, Ranges, File);
-  }
+  if (!Style)
+return Style.takeError();
+
+  tooling::Replacements IncludeReplaces =
+  format::sortIncludes(*Style, Code, Ranges, File);
+  auto Changed = tooling::applyAllReplacements(Code, IncludeReplaces);
+  if (!Changed)
+return Changed.takeError();
+
+  return IncludeReplaces.merge(format::reformat(
+  Style.get(), *Changed,
+  tooling::calculateRangesAfterReplacements(IncludeReplaces, Ranges),
+  File));
 }
 
 void ClangdServer::findDocumentHighlights(
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D44079: [ASTImporter] Allow testing of import sequences; fix import of typedefs for anonymous decls

2018-03-06 Thread Balogh , Ádám via Phabricator via cfe-commits
baloghadamsoftware added a comment.

Hi,

Thank you for the patch.

It seems that the new approach still does not solve a problem with anonymous 
structures in typedefs.In C++ a copy constructor is automatically generated, 
and its parameter is the anonymous structure itself. This triggers caching 
`NoLinkage` for it during the import of the constructor, but later fails with 
an assert because at the end the computed linkage is `ExternalLinkage`. It 
seems that anonymous structures are somewhat tricky in the original AST. For 
this struct:

  typedef struct {
int n;
  } T;

the original AST is:

  CXXRecordDecl 0x1abcb38  line:1:9 imported 
struct definition
  |-FieldDecl 0x1abce68  col:7 imported n 'int'
  |-CXXConstructorDecl 0x1abced0  col:9 imported implicit used  'void 
(void) throw()' inline default trivial
  | `-CompoundStmt 0x1abd2e0 
  `-CXXConstructorDecl 0x1abcfd8  col:9 imported implicit  'void (const 
T &)' inline default trivial noexcept-unevaluated 0x1abcfd8
`-ParmVarDecl 0x1abd138  col:9 imported 'const T &'
  TypedefDecl 0x1abcc78  col:3 imported 
referenced T 'struct T':'T'
  `-ElaboratedType 0x1abccd0 'struct T' sugar imported
`-RecordType 0x1abcc50 'T' imported
  `-CXXRecord 0x1abcb38 ''

But the imported one is:

  CXXRecordDecl 0x1a51400  col:9 struct definition
  |-FieldDecl 0x1a51540  col:7 n 'int'
  |-CXXConstructorDecl 0x1a515e0  col:9 implicit used  'void (void) 
throw()' inline trivial
  | `-CompoundStmt 0x1a51688 
  `-CXXConstructorDecl 0x1a51768  col:9 implicit  'void (const struct 
(anonymous at /tmp/first.cpp:1:9) &)' inline trivial noexcept-unevaluated 
0x1a51768
`-ParmVarDecl 0x1a51708  col:9 'const struct (anonymous at 
/tmp/first.cpp:1:9) &'
  TypedefDecl 0x1a518b0  col:3 T 'struct 
(anonymous struct at /tmp/first.cpp:1:9)':'struct (anonymous at 
/tmp/first.cpp:1:9)'
  `-ElaboratedType 0x1a51860 'struct (anonymous struct at /tmp/first.cpp:1:9)' 
sugar
`-RecordType 0x1a514a0 'struct (anonymous at /tmp/first.cpp:1:9)'
  `-CXXRecord 0x1a51400 ''


Repository:
  rC Clang

https://reviews.llvm.org/D44079



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


[PATCH] D43967: [ASTImporter] Add test helper Fixture

2018-03-06 Thread Gábor Horváth via Phabricator via cfe-commits
xazax.hun added a comment.

I think having both kinds of tests might make sense.
Overall, this looks good to me. Some nits inline.




Comment at: unittests/AST/ASTImporterTest.cpp:143
 
+class Fixture : public ::testing::Test {
+

I do not like the name of this class. It is like calling a variable as 
`variable`. 



Comment at: unittests/AST/ASTImporterTest.cpp:148
+
+  //Buffers for the contexts, must live in test scope
+  std::string ToCode;

Missing period on the end of the comment and missing space at the beginning.



Comment at: unittests/AST/ASTImporterTest.cpp:163
+  // We may have several From context and related translation units.
+  std::list FromTUs;
+

I think it might worth to have a note why do we use a list and not a vector.



Comment at: unittests/AST/ASTImporterTest.cpp:170
+ASTContext &ToCtx = ToAST->getASTContext();
+vfs::OverlayFileSystem *OFS = static_cast(
+
ToCtx.getSourceManager().getFileManager().getVirtualFileSystem().get());

Repeated type, use auto. Same below.
Are we sure these cast's will not fail? Shouldn't we use dynamic casts and 
asserts?



Comment at: unittests/AST/ASTImporterTest.cpp:184
+  // Must not call more than once within the same test.
+  std::tuple
+  getImportedDecl(StringRef FromSrcCode, Language FromLang,

I wonder if pair or tuple is the better choice here. I have no strong 
preference just wondering.



Comment at: unittests/AST/ASTImporterTest.cpp:187
+  StringRef ToSrcCode, Language ToLang,
+  const char *const Identifier = "declToImport") {
+ArgVector FromArgs, ToArgs;

Maybe StringRef for the Identifier? 



Comment at: unittests/AST/ASTImporterTest.cpp:190
+FromArgs = getBasicRunOptionsForLanguage(FromLang);
+ToArgs = getBasicRunOptionsForLanguage(ToLang);
+

Maybe declaring in the same line would be better.



Comment at: unittests/AST/ASTImporterTest.cpp:227
+assert(
+std::find_if(FromTUs.begin(), FromTUs.end(), [&FileName](const TU &e) {
+  return e.FileName == FileName;

I prefer to capture FileName by value. Param names should be upper case. Same 
below.



Comment at: unittests/AST/ASTImporterTest.cpp:231
+
+ArgVector Args= getBasicRunOptionsForLanguage(Lang);
+FromTUs.emplace_back(SrcCode, FileName, Args);

Formatting is off here.



Comment at: unittests/AST/ASTImporterTest.cpp:253
+auto It =
+std::find_if(FromTUs.begin(), FromTUs.end(), [&From](const TU &e) {
+  return e.TUDecl == From->getTranslationUnitDecl();

Capture From as value.



Comment at: unittests/AST/ASTImporterTest.cpp:996
+TEST_F(Fixture, TUshouldNotContainTemplatedDeclOfFunctionTemplates) {
+
+  Decl *From, *To;

Redundant new lines, same in most of the tests' beginning.



Comment at: unittests/AST/ASTImporterTest.cpp:1006
+for (auto Child : TU->decls()) {
+  if (FunctionDecl *FD = dyn_cast(Child)) {
+if (FD->getNameAsString() == "declToImport") {

Repeated type.



Comment at: unittests/AST/ASTImporterTest.cpp:1033
+for (auto Child : TU->decls()) {
+  if (CXXRecordDecl *RD = dyn_cast(Child)) {
+if (RD->getNameAsString() == "declToImport") {

Repeated type.



Comment at: unittests/AST/ASTImporterTest.cpp:1062
+for (auto Child : TU->decls()) {
+  if (TypeAliasDecl *AD = dyn_cast(Child)) {
+if (AD->getNameAsString() == "declToImport") {

Repeated type.



Comment at: unittests/AST/ASTImporterTest.cpp:1091
+
+  // Check that the ClassTemplateSpecializationDecl is NOT the child of the TU
+  auto Pattern =

Missing periods in comments.



Comment at: unittests/AST/ASTImporterTest.cpp:1156
+for (auto Child : cast(D)->decls()) {
+  if (FieldDecl *FD = dyn_cast(Child)) {
+if (FD->getNameAsString() != FieldNamesInOrder[i++]) {

Repeated type.



Comment at: unittests/AST/ASTImporterTest.cpp:1198
+for (auto Child : cast(D)->decls()) {
+  if (FieldDecl *FD = dyn_cast(Child)) {
+if (FD->getNameAsString() != FieldNamesInOrder[i++]) {

Repeated type.


Repository:
  rC Clang

https://reviews.llvm.org/D43967



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


Re: r326746 - [analyzer] AST-matching checker to detect global central dispatch performance anti-pattern

2018-03-06 Thread Alexander Kornienko via cfe-commits
On Mon, Mar 5, 2018 at 11:05 PM George Karpenkov via cfe-commits <
cfe-commits@lists.llvm.org> wrote:

> Author: george.karpenkov
> Date: Mon Mar  5 14:03:32 2018
> New Revision: 326746
>
> URL: http://llvm.org/viewvc/llvm-project?rev=326746&view=rev
> Log:
> [analyzer] AST-matching checker to detect global central dispatch
> performance anti-pattern
>
> rdar://37312818
>
> NB: The checker does not care about the ordering of callbacks, see the
> relevant FIXME in tests.
>
> Differential Revision: https://reviews.llvm.org/D44059
>
> Added:
> cfe/trunk/lib/StaticAnalyzer/Checkers/GCDAsyncSemaphoreChecker.cpp
> cfe/trunk/test/gcdasyncsemaphorechecker_test.m
>

The test doesn't belong here. The right place seems to be test/Analysis/.


> Modified:
> cfe/trunk/include/clang/StaticAnalyzer/Checkers/Checkers.td
> cfe/trunk/lib/StaticAnalyzer/Checkers/CMakeLists.txt
>
> Modified: cfe/trunk/include/clang/StaticAnalyzer/Checkers/Checkers.td
> URL:
> http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/StaticAnalyzer/Checkers/Checkers.td?rev=326746&r1=326745&r2=326746&view=diff
>
> ==
> --- cfe/trunk/include/clang/StaticAnalyzer/Checkers/Checkers.td (original)
> +++ cfe/trunk/include/clang/StaticAnalyzer/Checkers/Checkers.td Mon Mar  5
> 14:03:32 2018
> @@ -610,6 +610,13 @@ def ObjCSuperDeallocChecker : Checker<"S
>
>  } // end "osx.cocoa"
>
> +let ParentPackage = OSXAlpha in {
> +
> +def GCDAsyncSemaphoreChecker : Checker<"GCDAsyncSemaphore">,
> +  HelpText<"Checker for performance anti-pattern when using semaphors
> from async API">,
> +  DescFile<"GCDAsyncSemaphoreChecker.cpp">;
> +} // end "alpha.osx"
> +
>  let ParentPackage = CocoaAlpha in {
>
>  def InstanceVariableInvalidation :
> Checker<"InstanceVariableInvalidation">,
>
> Modified: cfe/trunk/lib/StaticAnalyzer/Checkers/CMakeLists.txt
> URL:
> http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/StaticAnalyzer/Checkers/CMakeLists.txt?rev=326746&r1=326745&r2=326746&view=diff
>
> ==
> --- cfe/trunk/lib/StaticAnalyzer/Checkers/CMakeLists.txt (original)
> +++ cfe/trunk/lib/StaticAnalyzer/Checkers/CMakeLists.txt Mon Mar  5
> 14:03:32 2018
> @@ -37,6 +37,7 @@ add_clang_library(clangStaticAnalyzerChe
>DynamicTypeChecker.cpp
>ExprInspectionChecker.cpp
>FixedAddressChecker.cpp
> +  GCDAsyncSemaphoreChecker.cpp
>GenericTaintChecker.cpp
>GTestChecker.cpp
>IdenticalExprChecker.cpp
>
> Added: cfe/trunk/lib/StaticAnalyzer/Checkers/GCDAsyncSemaphoreChecker.cpp
> URL:
> http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/StaticAnalyzer/Checkers/GCDAsyncSemaphoreChecker.cpp?rev=326746&view=auto
>
> ==
> --- cfe/trunk/lib/StaticAnalyzer/Checkers/GCDAsyncSemaphoreChecker.cpp
> (added)
> +++ cfe/trunk/lib/StaticAnalyzer/Checkers/GCDAsyncSemaphoreChecker.cpp Mon
> Mar  5 14:03:32 2018
> @@ -0,0 +1,154 @@
> +//===- GCDAsyncSemaphoreChecker.cpp -*- 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 GCDAsyncSemaphoreChecker which checks against a
> common
> +// antipattern when synchronous API is emulated from asynchronous
> callbacks
> +// using a semaphor:
> +//
> +//   dispatch_semapshore_t sema = dispatch_semaphore_create(0);
> +
> +//   AnyCFunctionCall(^{
> +// // code…
> +// dispatch_semapshore_signal(sema);
> +//   })
> +//   dispatch_semapshore_wait(sema, *)
> +//
> +// Such code is a common performance problem, due to inability of GCD to
> +// properly handle QoS when a combination of queues and semaphors is used.
> +// Good code would either use asynchronous API (when available), or
> perform
> +// the necessary action in asynchronous callback.
> +//
> +// Currently, the check is performed using a simple heuristical AST
> pattern
> +// matching.
> +//
>
> +//===--===//
> +
> +#include "ClangSACheckers.h"
> +#include "clang/ASTMatchers/ASTMatchFinder.h"
> +#include "clang/StaticAnalyzer/Core/BugReporter/BugReporter.h"
> +#include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
> +#include "clang/StaticAnalyzer/Core/Checker.h"
> +#include "clang/StaticAnalyzer/Core/PathSensitive/AnalysisManager.h"
> +#include "llvm/Support/Debug.h"
> +
> +#define DEBUG_TYPE "gcdasyncsemaphorechecker"
> +
> +using namespace clang;
> +using namespace ento;
> +using namespace ast_matchers;
> +
> +namespace {
> +
> +const char *WarningBinding = "semaphore_wait";
> +
> +class GCDAsyncSemaphoreChecker : public Checker {
> +public:
> +  void checkASTCode

[PATCH] D44093: [BUILTINS] structure pretty printer

2018-03-06 Thread Paul Semel via Phabricator via cfe-commits
paulsemel marked 4 inline comments as done.
paulsemel added inline comments.



Comment at: lib/CodeGen/CGBuiltin.cpp:1208
+
+assert(RT && "The first argument must be a record type");
+

aaron.ballman wrote:
> I don't see anything enforcing this constraint, so users are likely to hit 
> this assertion rather than a compile error.
I actually didn't manage to enforce this in the builtin declaration as we can 
only declare simple types (I am probably missing something)



Comment at: lib/CodeGen/CGBuiltin.cpp:1258
+
+  //Need to handle bitfield here
+

aaron.ballman wrote:
> Are you intending to implement this as part of this functionality?
Yes, my goal is to be able to dump the bitfields correctly, particularly if the 
structure is packed (for dumping a GDT for example).
I just didn't manage to do it properly for the moment.


Repository:
  rC Clang

https://reviews.llvm.org/D44093



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


[PATCH] D44100: [ASTImporter] Reorder fields after structure import is finished

2018-03-06 Thread Gabor Marton via Phabricator via cfe-commits
martong added a comment.

Aleksei,

We should definitely try to synchronize our work between  Samsung (?) and 
Ericsson much much more.
Unfortunately, it is often we work on the same issue and this can cause delays 
for both of us.
Actually, we solved the same issue in our branch a year ago, see
https://github.com/Ericsson/clang/blob/ctu-clang5/lib/AST/ASTImporter.cpp#L1087 
and the related test:
https://github.com/Ericsson/clang/blob/ctu-clang5/unittests/AST/ASTImporterTest.cpp#L1365

Gabor


Repository:
  rC Clang

https://reviews.llvm.org/D44100



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


[PATCH] D44138: [clangd] Sort includes when formatting code or inserting new includes.

2018-03-06 Thread Haojian Wu via Phabricator via cfe-commits
hokein accepted this revision.
hokein added a comment.
This revision is now accepted and ready to land.

LGTM.


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D44138



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


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

2018-03-06 Thread Alexey Bader via Phabricator via cfe-commits
bader accepted this revision.
bader added a comment.
This revision is now accepted and ready to land.

Hi Sam,

Sorry for the delay. LGTM, I have only minor refactoring suggestion.

Thanks,
Alexey




Comment at: lib/CodeGen/CGBlocks.cpp:1065-1067
+  llvm::Value *FuncPtr;
 
+  if (!CGM.getLangOpts().OpenCL) {

I think it would be more readable if we merge this if statement with the if 
statement at the line #1103.
It's used to initialize FuncPtr for non-OpenCL languages and the first use of 
this variable is in the else block of if statement at the line #1103.
If I didn't miss something it should reasonable to combine this if block with 
'else' block at the line #1106.


https://reviews.llvm.org/D43783



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


r326772 - Move test/gcdasyncsemaphorechecker_test.m to a subdirectory

2018-03-06 Thread Alexander Kornienko via cfe-commits
Author: alexfh
Date: Tue Mar  6 02:40:11 2018
New Revision: 326772

URL: http://llvm.org/viewvc/llvm-project?rev=326772&view=rev
Log:
Move test/gcdasyncsemaphorechecker_test.m to a subdirectory

Added:
cfe/trunk/test/Analysis/gcdasyncsemaphorechecker_test.m
  - copied, changed from r326767, 
cfe/trunk/test/gcdasyncsemaphorechecker_test.m
Removed:
cfe/trunk/test/gcdasyncsemaphorechecker_test.m

Copied: cfe/trunk/test/Analysis/gcdasyncsemaphorechecker_test.m (from r326767, 
cfe/trunk/test/gcdasyncsemaphorechecker_test.m)
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/Analysis/gcdasyncsemaphorechecker_test.m?p2=cfe/trunk/test/Analysis/gcdasyncsemaphorechecker_test.m&p1=cfe/trunk/test/gcdasyncsemaphorechecker_test.m&r1=326767&r2=326772&rev=326772&view=diff
==
(empty)

Removed: cfe/trunk/test/gcdasyncsemaphorechecker_test.m
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/gcdasyncsemaphorechecker_test.m?rev=326771&view=auto
==
--- cfe/trunk/test/gcdasyncsemaphorechecker_test.m (original)
+++ cfe/trunk/test/gcdasyncsemaphorechecker_test.m (removed)
@@ -1,203 +0,0 @@
-// RUN: %clang_analyze_cc1 -analyzer-checker=core,alpha.osx.GCDAsyncSemaphore 
%s -fblocks -verify
-typedef signed char BOOL;
-@protocol NSObject  - (BOOL)isEqual:(id)object; @end
-@interface NSObject  {}
-+(id)alloc;
--(id)init;
--(id)autorelease;
--(id)copy;
--(id)retain;
-@end
-
-typedef int dispatch_semaphore_t;
-typedef void (^block_t)();
-
-dispatch_semaphore_t dispatch_semaphore_create(int);
-void dispatch_semaphore_wait(dispatch_semaphore_t, int);
-void dispatch_semaphore_signal(dispatch_semaphore_t);
-
-void func(void (^)(void));
-void func_w_typedef(block_t);
-
-int coin();
-
-void use_semaphor_antipattern() {
-  dispatch_semaphore_t sema = dispatch_semaphore_create(0);
-
-  func(^{
-  dispatch_semaphore_signal(sema);
-  });
-  dispatch_semaphore_wait(sema, 100); // expected-warning{{Possible semaphore 
performance anti-pattern}}
-}
-
-// It's OK to use pattern in tests.
-// We simply match the containing function name against ^test.
-void test_no_warning() {
-  dispatch_semaphore_t sema = dispatch_semaphore_create(0);
-
-  func(^{
-  dispatch_semaphore_signal(sema);
-  });
-  dispatch_semaphore_wait(sema, 100);
-}
-
-void use_semaphor_antipattern_multiple_times() {
-  dispatch_semaphore_t sema1 = dispatch_semaphore_create(0);
-
-  func(^{
-  dispatch_semaphore_signal(sema1);
-  });
-  dispatch_semaphore_wait(sema1, 100); // expected-warning{{Possible semaphore 
performance anti-pattern}}
-
-  dispatch_semaphore_t sema2 = dispatch_semaphore_create(0);
-
-  func(^{
-  dispatch_semaphore_signal(sema2);
-  });
-  dispatch_semaphore_wait(sema2, 100); // expected-warning{{Possible semaphore 
performance anti-pattern}}
-}
-
-void use_semaphor_antipattern_multiple_wait() {
-  dispatch_semaphore_t sema1 = dispatch_semaphore_create(0);
-
-  func(^{
-  dispatch_semaphore_signal(sema1);
-  });
-  // FIXME: multiple waits on same semaphor should not raise a warning.
-  dispatch_semaphore_wait(sema1, 100); // expected-warning{{Possible semaphore 
performance anti-pattern}}
-  dispatch_semaphore_wait(sema1, 100); // expected-warning{{Possible semaphore 
performance anti-pattern}}
-}
-
-void warn_incorrect_order() {
-  // FIXME: ASTMatchers do not allow ordered matching, so would match even
-  // if out of order.
-  dispatch_semaphore_t sema = dispatch_semaphore_create(0);
-
-  dispatch_semaphore_wait(sema, 100); // expected-warning{{Possible semaphore 
performance anti-pattern}}
-  func(^{
-  dispatch_semaphore_signal(sema);
-  });
-}
-
-void warn_w_typedef() {
-  dispatch_semaphore_t sema = dispatch_semaphore_create(0);
-
-  func_w_typedef(^{
-  dispatch_semaphore_signal(sema);
-  });
-  dispatch_semaphore_wait(sema, 100); // expected-warning{{Possible semaphore 
performance anti-pattern}}
-}
-
-void warn_nested_ast() {
-  dispatch_semaphore_t sema = dispatch_semaphore_create(0);
-
-  if (coin()) {
-func(^{
- dispatch_semaphore_signal(sema);
- });
-  } else {
-func(^{
- dispatch_semaphore_signal(sema);
- });
-  }
-  dispatch_semaphore_wait(sema, 100); // expected-warning{{Possible semaphore 
performance anti-pattern}}
-}
-
-void use_semaphore_assignment() {
-  dispatch_semaphore_t sema;
-  sema = dispatch_semaphore_create(0);
-
-  func(^{
-  dispatch_semaphore_signal(sema);
-  });
-  dispatch_semaphore_wait(sema, 100); // expected-warning{{Possible semaphore 
performance anti-pattern}}
-}
-
-void use_semaphore_assignment_init() {
-  dispatch_semaphore_t sema = dispatch_semaphore_create(0);
-  sema = dispatch_semaphore_create(1);
-
-  func(^{
-  dispatch_semaphore_signal(sema);
-  });
-  dispatch_semaphore_wait(sema, 100); // expected-warning{{Possible semaphore 
performance anti-pattern}}
-}
-
-

[PATCH] D44093: [BUILTINS] structure pretty printer

2018-03-06 Thread Paul Semel via Phabricator via cfe-commits
paulsemel updated this revision to Diff 137141.
paulsemel added a comment.

Applied Aaron change suggestions


Repository:
  rC Clang

https://reviews.llvm.org/D44093

Files:
  include/clang/Basic/Builtins.def
  lib/CodeGen/CGBuiltin.cpp

Index: lib/CodeGen/CGBuiltin.cpp
===
--- lib/CodeGen/CGBuiltin.cpp
+++ lib/CodeGen/CGBuiltin.cpp
@@ -14,6 +14,7 @@
 #include "CGCXXABI.h"
 #include "CGObjCRuntime.h"
 #include "CGOpenCLRuntime.h"
+#include "CGRecordLayout.h"
 #include "CodeGenFunction.h"
 #include "CodeGenModule.h"
 #include "ConstantEmitter.h"
@@ -1196,6 +1197,80 @@
 return RValue::get(ComplexVal.first);
   }
 
+  case Builtin::BI__builtin_dump_struct: {
+Value *Func = EmitScalarExpr(E->getArg(1)->IgnoreImpCasts());
+CharUnits Arg0Align = EmitPointerWithAlignment(E->getArg(0)).getAlignment();
+
+const Expr *Arg0 = E->getArg(0)->IgnoreImpCasts();
+QualType Arg0Type = Arg0->getType()->getPointeeType();
+const RecordType *RT = Arg0Type->getAs();
+
+assert(RT && "The first argument must be a record type");
+
+RecordDecl *RD = RT->getDecl()->getDefinition();
+ASTContext &ASTContext = RD->getASTContext();
+const ASTRecordLayout &RL = ASTContext.getASTRecordLayout(RD);
+
+Value *GString = Builder.CreateGlobalStringPtr(Arg0Type.getAsString()
+   + " {\n");
+Value *Res = Builder.CreateCall(Func, {GString});
+
+static llvm::DenseMap Types;
+if (Types.empty()) {
+  Types[getContext().CharTy] = "%c";
+  Types[getContext().BoolTy] = "%d";
+  Types[getContext().IntTy] = "%d";
+  Types[getContext().UnsignedIntTy] = "%u";
+  Types[getContext().LongTy] = "%ld";
+  Types[getContext().UnsignedLongTy] = "%lu";
+  Types[getContext().LongLongTy] = "%lld";
+  Types[getContext().UnsignedLongLongTy] = "%llu";
+  Types[getContext().ShortTy] = "%hd";
+  Types[getContext().UnsignedShortTy] = "%hu";
+  Types[getContext().VoidPtrTy] = "%p";
+  Types[getContext().FloatTy] = "%f";
+  Types[getContext().DoubleTy] = "%f";
+  Types[getContext().LongDoubleTy] = "%Lf";
+  Types[getContext().getPointerType(getContext().CharTy)] = "%s";
+}
+
+/* field : RecordDecl::field_iterator */
+for (auto *FD : RD->fields()) {
+  uint64_t Off = RL.getFieldOffset(FD->getFieldIndex());
+  Off = ASTContext.toCharUnitsFromBits(Off).getQuantity();
+
+  Value *FieldPtr = EmitScalarExpr(E->getArg(0));
+  if (Off) {
+FieldPtr = Builder.CreatePtrToInt(FieldPtr, IntPtrTy);
+FieldPtr = Builder.CreateAdd(FieldPtr, ConstantInt::get(IntPtrTy, Off));
+FieldPtr = Builder.CreateIntToPtr(FieldPtr, VoidPtrTy);
+  }
+  std::string Format = FD->getType().getAsString() + std::string(" ") +
+FD->getNameAsString() + " : ";
+
+  Format += Types[FD->getType()];
+
+  QualType ResPtrType = getContext().getPointerType(FD->getType());
+  llvm::Type *ResType = ConvertType(ResPtrType);
+  FieldPtr = Builder.CreatePointerCast(FieldPtr, ResType);
+  Address FieldAddress = Address(FieldPtr, Arg0Align);
+  FieldPtr = Builder.CreateLoad(FieldAddress);
+
+  // Need to handle bitfield here
+
+  GString = Builder.CreateGlobalStringPtr(Format + "\n");
+  Value *TmpRes = Builder.CreateCall(Func, {GString, FieldPtr});
+  Res = Builder.CreateAdd(Res, TmpRes);
+}
+
+std::string Format = "}\n";
+GString = Builder.CreateGlobalStringPtr(Format);
+Value *TmpRes = Builder.CreateCall(Func, {GString});
+Res = Builder.CreateAdd(Res, TmpRes);
+
+return RValue::get(Res);
+  }
+
   case Builtin::BI__builtin_cimag:
   case Builtin::BI__builtin_cimagf:
   case Builtin::BI__builtin_cimagl:
Index: include/clang/Basic/Builtins.def
===
--- include/clang/Basic/Builtins.def
+++ include/clang/Basic/Builtins.def
@@ -1374,6 +1374,7 @@
 BUILTIN(__builtin_operator_new, "v*z", "c")
 BUILTIN(__builtin_operator_delete, "vv*", "n")
 BUILTIN(__builtin_char_memchr, "c*cC*iz", "n")
+BUILTIN(__builtin_dump_struct, "ivC*v*", "n")
 
 // Safestack builtins
 BUILTIN(__builtin___get_unsafe_stack_start, "v*", "Fn")
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


Re: r326746 - [analyzer] AST-matching checker to detect global central dispatch performance anti-pattern

2018-03-06 Thread Alexander Kornienko via cfe-commits
On Tue, Mar 6, 2018 at 11:03 AM Alexander Kornienko 
wrote:

> On Mon, Mar 5, 2018 at 11:05 PM George Karpenkov via cfe-commits <
> cfe-commits@lists.llvm.org> wrote:
>
>> Author: george.karpenkov
>> Date: Mon Mar  5 14:03:32 2018
>> New Revision: 326746
>>
>> cfe/trunk/test/gcdasyncsemaphorechecker_test.m
>>
>
> The test doesn't belong here. The right place seems to be test/Analysis/.
>

Moved the test in r326772.
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang-tools-extra] r326773 - [clangd] Sort includes when formatting code or inserting new includes.

2018-03-06 Thread Eric Liu via cfe-commits
Author: ioeric
Date: Tue Mar  6 02:42:50 2018
New Revision: 326773

URL: http://llvm.org/viewvc/llvm-project?rev=326773&view=rev
Log:
[clangd] Sort includes when formatting code or inserting new includes.

Reviewers: hokein, ilya-biryukov

Subscribers: klimek, jkorous-apple, cfe-commits

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

Modified:
clang-tools-extra/trunk/clangd/ClangdServer.cpp
clang-tools-extra/trunk/unittests/clangd/ClangdTests.cpp

Modified: clang-tools-extra/trunk/clangd/ClangdServer.cpp
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clangd/ClangdServer.cpp?rev=326773&r1=326772&r2=326773&view=diff
==
--- clang-tools-extra/trunk/clangd/ClangdServer.cpp (original)
+++ clang-tools-extra/trunk/clangd/ClangdServer.cpp Tue Mar  6 02:42:50 2018
@@ -353,8 +353,11 @@ ClangdServer::insertInclude(PathRef File
   // Replacement with offset UINT_MAX and length 0 will be treated as include
   // insertion.
   tooling::Replacement R(File, /*Offset=*/UINT_MAX, 0, "#include " + 
ToInclude);
-  return format::cleanupAroundReplacements(Code, tooling::Replacements(R),
-   *Style);
+  auto Replaces = format::cleanupAroundReplacements(
+  Code, tooling::Replacements(R), *Style);
+  if (!Replaces)
+return Replaces;
+  return formatReplacements(Code, *Replaces, *Style);
 }
 
 llvm::Optional ClangdServer::getDocument(PathRef File) {
@@ -465,13 +468,21 @@ ClangdServer::formatCode(llvm::StringRef
  ArrayRef Ranges) {
   // Call clang-format.
   auto TaggedFS = FSProvider.getTaggedFileSystem(File);
-  auto StyleOrError =
+  auto Style =
   format::getStyle("file", File, "LLVM", Code, TaggedFS.Value.get());
-  if (!StyleOrError) {
-return StyleOrError.takeError();
-  } else {
-return format::reformat(StyleOrError.get(), Code, Ranges, File);
-  }
+  if (!Style)
+return Style.takeError();
+
+  tooling::Replacements IncludeReplaces =
+  format::sortIncludes(*Style, Code, Ranges, File);
+  auto Changed = tooling::applyAllReplacements(Code, IncludeReplaces);
+  if (!Changed)
+return Changed.takeError();
+
+  return IncludeReplaces.merge(format::reformat(
+  Style.get(), *Changed,
+  tooling::calculateRangesAfterReplacements(IncludeReplaces, Ranges),
+  File));
 }
 
 void ClangdServer::findDocumentHighlights(

Modified: clang-tools-extra/trunk/unittests/clangd/ClangdTests.cpp
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/unittests/clangd/ClangdTests.cpp?rev=326773&r1=326772&r2=326773&view=diff
==
--- clang-tools-extra/trunk/unittests/clangd/ClangdTests.cpp (original)
+++ clang-tools-extra/trunk/unittests/clangd/ClangdTests.cpp Tue Mar  6 
02:42:50 2018
@@ -945,6 +945,7 @@ TEST_F(ClangdVFSTest, InsertIncludes) {
 
   auto FooCpp = testPath("foo.cpp");
   const auto Code = R"cpp(
+#include "z.h"
 #include "x.h"
 
 void f() {}
@@ -952,15 +953,18 @@ void f() {}
   FS.Files[FooCpp] = Code;
   runAddDocument(Server, FooCpp, Code);
 
-  auto Inserted = [&](llvm::StringRef Original, llvm::StringRef Preferred,
-  llvm::StringRef Expected) {
+  auto ChangedCode = [&](llvm::StringRef Original, llvm::StringRef Preferred) {
 auto Replaces = Server.insertInclude(
 FooCpp, Code, Original, Preferred.empty() ? Original : Preferred);
 EXPECT_TRUE(static_cast(Replaces));
 auto Changed = tooling::applyAllReplacements(Code, *Replaces);
 EXPECT_TRUE(static_cast(Changed));
-return llvm::StringRef(*Changed).contains(
-(llvm::Twine("#include ") + Expected + "").str());
+return *Changed;
+  };
+  auto Inserted = [&](llvm::StringRef Original, llvm::StringRef Preferred,
+  llvm::StringRef Expected) {
+return llvm::StringRef(ChangedCode(Original, Preferred))
+.contains((llvm::Twine("#include ") + Expected + "").str());
   };
 
   EXPECT_TRUE(Inserted("\"y.h\"", /*Preferred=*/"","\"y.h\""));
@@ -976,6 +980,45 @@ void f() {}
/*Preferred=*/"", ""));
   EXPECT_TRUE(Inserted(OriginalHeader, PreferredHeader, "\"Y.h\""));
   EXPECT_TRUE(Inserted("", PreferredHeader, "\"Y.h\""));
+
+  // Check that includes are sorted.
+  const auto Expected = R"cpp(
+#include "x.h"
+#include "y.h"
+#include "z.h"
+
+void f() {}
+)cpp";
+  EXPECT_EQ(Expected, ChangedCode("\"y.h\"", /*Preferred=*/""));
+}
+
+TEST_F(ClangdVFSTest, FormatCode) {
+  MockFSProvider FS;
+  ErrorCheckingDiagConsumer DiagConsumer;
+  MockCompilationDatabase CDB;
+  ClangdServer Server(CDB, FS, DiagConsumer, ClangdServer::optsForTest());
+
+  auto Path = testPath("foo.cpp");
+  std::string Code = R"cpp(
+#include "y.h"
+#include "x.h"
+
+void f(  )  {}
+)cpp";
+  std::string Expected = R"cpp(
+#include "x.h"
+#include "y.h"
+
+void f() {}
+)cpp";
+  FS.Files[Path] = Code;
+  run

[PATCH] D44138: [clangd] Sort includes when formatting code or inserting new includes.

2018-03-06 Thread Eric Liu via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rCTE326773: [clangd] Sort includes when formatting code or 
inserting new includes. (authored by ioeric, committed by ).

Changed prior to commit:
  https://reviews.llvm.org/D44138?vs=137137&id=137142#toc

Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D44138

Files:
  clangd/ClangdServer.cpp
  unittests/clangd/ClangdTests.cpp

Index: unittests/clangd/ClangdTests.cpp
===
--- unittests/clangd/ClangdTests.cpp
+++ unittests/clangd/ClangdTests.cpp
@@ -945,22 +945,26 @@
 
   auto FooCpp = testPath("foo.cpp");
   const auto Code = R"cpp(
+#include "z.h"
 #include "x.h"
 
 void f() {}
 )cpp";
   FS.Files[FooCpp] = Code;
   runAddDocument(Server, FooCpp, Code);
 
-  auto Inserted = [&](llvm::StringRef Original, llvm::StringRef Preferred,
-  llvm::StringRef Expected) {
+  auto ChangedCode = [&](llvm::StringRef Original, llvm::StringRef Preferred) {
 auto Replaces = Server.insertInclude(
 FooCpp, Code, Original, Preferred.empty() ? Original : Preferred);
 EXPECT_TRUE(static_cast(Replaces));
 auto Changed = tooling::applyAllReplacements(Code, *Replaces);
 EXPECT_TRUE(static_cast(Changed));
-return llvm::StringRef(*Changed).contains(
-(llvm::Twine("#include ") + Expected + "").str());
+return *Changed;
+  };
+  auto Inserted = [&](llvm::StringRef Original, llvm::StringRef Preferred,
+  llvm::StringRef Expected) {
+return llvm::StringRef(ChangedCode(Original, Preferred))
+.contains((llvm::Twine("#include ") + Expected + "").str());
   };
 
   EXPECT_TRUE(Inserted("\"y.h\"", /*Preferred=*/"","\"y.h\""));
@@ -976,6 +980,45 @@
/*Preferred=*/"", ""));
   EXPECT_TRUE(Inserted(OriginalHeader, PreferredHeader, "\"Y.h\""));
   EXPECT_TRUE(Inserted("", PreferredHeader, "\"Y.h\""));
+
+  // Check that includes are sorted.
+  const auto Expected = R"cpp(
+#include "x.h"
+#include "y.h"
+#include "z.h"
+
+void f() {}
+)cpp";
+  EXPECT_EQ(Expected, ChangedCode("\"y.h\"", /*Preferred=*/""));
+}
+
+TEST_F(ClangdVFSTest, FormatCode) {
+  MockFSProvider FS;
+  ErrorCheckingDiagConsumer DiagConsumer;
+  MockCompilationDatabase CDB;
+  ClangdServer Server(CDB, FS, DiagConsumer, ClangdServer::optsForTest());
+
+  auto Path = testPath("foo.cpp");
+  std::string Code = R"cpp(
+#include "y.h"
+#include "x.h"
+
+void f(  )  {}
+)cpp";
+  std::string Expected = R"cpp(
+#include "x.h"
+#include "y.h"
+
+void f() {}
+)cpp";
+  FS.Files[Path] = Code;
+  runAddDocument(Server, Path, Code);
+
+  auto Replaces = Server.formatFile(Code, Path);
+  EXPECT_TRUE(static_cast(Replaces));
+  auto Changed = tooling::applyAllReplacements(Code, *Replaces);
+  EXPECT_TRUE(static_cast(Changed));
+  EXPECT_EQ(Expected, *Changed);
 }
 
 } // namespace
Index: clangd/ClangdServer.cpp
===
--- clangd/ClangdServer.cpp
+++ clangd/ClangdServer.cpp
@@ -353,8 +353,11 @@
   // Replacement with offset UINT_MAX and length 0 will be treated as include
   // insertion.
   tooling::Replacement R(File, /*Offset=*/UINT_MAX, 0, "#include " + ToInclude);
-  return format::cleanupAroundReplacements(Code, tooling::Replacements(R),
-   *Style);
+  auto Replaces = format::cleanupAroundReplacements(
+  Code, tooling::Replacements(R), *Style);
+  if (!Replaces)
+return Replaces;
+  return formatReplacements(Code, *Replaces, *Style);
 }
 
 llvm::Optional ClangdServer::getDocument(PathRef File) {
@@ -465,13 +468,21 @@
  ArrayRef Ranges) {
   // Call clang-format.
   auto TaggedFS = FSProvider.getTaggedFileSystem(File);
-  auto StyleOrError =
+  auto Style =
   format::getStyle("file", File, "LLVM", Code, TaggedFS.Value.get());
-  if (!StyleOrError) {
-return StyleOrError.takeError();
-  } else {
-return format::reformat(StyleOrError.get(), Code, Ranges, File);
-  }
+  if (!Style)
+return Style.takeError();
+
+  tooling::Replacements IncludeReplaces =
+  format::sortIncludes(*Style, Code, Ranges, File);
+  auto Changed = tooling::applyAllReplacements(Code, IncludeReplaces);
+  if (!Changed)
+return Changed.takeError();
+
+  return IncludeReplaces.merge(format::reformat(
+  Style.get(), *Changed,
+  tooling::calculateRangesAfterReplacements(IncludeReplaces, Ranges),
+  File));
 }
 
 void ClangdServer::findDocumentHighlights(
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D41102: Setup clang-doc frontend framework

2018-03-06 Thread Athos via Phabricator via cfe-commits
Athosvk added a comment.

My apologies for getting back on this so late!

In https://reviews.llvm.org/D41102#1017683, @juliehockett wrote:

> So, as an idea (as this diff implements), I updated the string references to 
> be a struct, which holds the USR of the referenced type (for serialization, 
> both here in the mapper and for the dump option in the reducer, as well as a 
> pointer to an `Info` struct. This pointer is not used at this point, but 
> would be populated by the reducer. Thoughts?


This seems like quite a decent approach! That being said, I don't see the 
pointer yet? I assume you mean that you will be adding this? Additionally, a 
slight disadvantage of doing this generic approach is that you need to do 
bookkeeping on what it is referencing, but I guess there's no helping that due 
to the architecture which makes you rely upon the USR? Personally I'd prefer 
having the explicit types if and where possible. So for now a RecordInfo has a 
vecotr of Reference's to its parents, but we know the parents can only be of 
certain kinds (more than just a RecordType, but you get the point); it won't be 
an enum, namespace or function.

As I mentioned, we did this the other way around, which also has the slight 
advantage that I only had to create and save the USR once per info instance (as 
in, 10 references to a class only add the overhead of 10 pointers, rather than 
each having the USR as well), but our disadvantage was of course that we had 
delayed serialization (although we could arguably do both simultaneously). It 
seems each method has its merits :).


https://reviews.llvm.org/D41102



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


[PATCH] D42983: [clang-tidy] Add readability-simd-intrinsics check.

2018-03-06 Thread Alexander Kornienko via Phabricator via cfe-commits
alexfh added a comment.

In https://reviews.llvm.org/D42983#1028093, @MaskRay wrote:

> In https://reviews.llvm.org/D42983#1025179, @alexfh wrote:
>
> > A late comment here: should this check start a new "portability" module? 
> > This seems to be the main focus of the check rather than making code more 
> > readable.
>
>
> SG. Should I rename it?


If nobody objects, yes, please. You'll need create the module manually and then 
use the rename_check.py script for the actual renaming.


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D42983



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


[PATCH] D42624: [clang-tidy] Add a utility Matcher to match the next statement within a statement sequence

2018-03-06 Thread Alexander Kornienko via Phabricator via cfe-commits
alexfh added a comment.

In https://reviews.llvm.org/D42624#1027506, @tbourvon wrote:

> @alexfh What is your opinion regarding adding this dependency?


I'm fine with the dependency, and I'd probably make the matcher local to the 
check until there is at least one more use case for it in the codebase.


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D42624



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


[PATCH] D44141: [clang-format] Use NestedBlockIndent as a 0 column in formatted raw strings

2018-03-06 Thread Krasimir Georgiev via Phabricator via cfe-commits
krasimir created this revision.
krasimir added reviewers: djasper, sammccall.
Herald added subscribers: cfe-commits, klimek.

This makes the formatter of raw string literals use NestedBlockIndent for
determining the 0 column of the content inside. This makes the formatting use
less horizonal space and fixes a case where two newlines before and after the
raw string prefix were selected instead of a single newline after it:

Before:

   = (
  R"pb(
key: value)pb");

After:

   = (R"pb(
  key: value)pb");


Repository:
  rC Clang

https://reviews.llvm.org/D44141

Files:
  lib/Format/ContinuationIndenter.cpp
  unittests/Format/FormatTestRawStrings.cpp


Index: unittests/Format/FormatTestRawStrings.cpp
===
--- unittests/Format/FormatTestRawStrings.cpp
+++ unittests/Format/FormatTestRawStrings.cpp
@@ -681,15 +681,14 @@
 })test",
getRawStringPbStyleWithColumns(20)));
 
-  // Align the suffix with the surrounding FirstIndent if the prefix is not on
+  // Align the suffix with the surrounding indent if the prefix is not on
   // a line of its own.
   expect_eq(R"test(
 int s() {
-  auto S = PTP(
-  R"pb(
-item_1: 1,
-item_2: 2
-  )pb");
+  auto S = PTP(R"pb(
+item_1: 1,
+item_2: 2
+  )pb");
 })test",
 format(R"test(
 int s() {
Index: lib/Format/ContinuationIndenter.cpp
===
--- lib/Format/ContinuationIndenter.cpp
+++ lib/Format/ContinuationIndenter.cpp
@@ -1385,9 +1385,10 @@
   // violate the rectangle rule and visually flows within the surrounding
   // source.
   bool ContentStartsOnNewline = Current.TokenText[OldPrefixSize] == '\n';
-  unsigned NextStartColumn = ContentStartsOnNewline
- ? State.Stack.back().Indent + 
Style.IndentWidth
- : FirstStartColumn;
+  unsigned NextStartColumn =
+  ContentStartsOnNewline
+  ? State.Stack.back().NestedBlockIndent + Style.IndentWidth
+  : FirstStartColumn;
 
   // The last start column is the column the raw string suffix starts if it is
   // put on a newline.
@@ -1399,7 +1400,7 @@
   // indent.
   unsigned LastStartColumn = Current.NewlinesBefore
  ? FirstStartColumn - NewPrefixSize
- : State.Stack.back().Indent;
+ : State.Stack.back().NestedBlockIndent;
 
   std::pair Fixes = internal::reformat(
   RawStringStyle, RawText, {tooling::Range(0, RawText.size())},


Index: unittests/Format/FormatTestRawStrings.cpp
===
--- unittests/Format/FormatTestRawStrings.cpp
+++ unittests/Format/FormatTestRawStrings.cpp
@@ -681,15 +681,14 @@
 })test",
getRawStringPbStyleWithColumns(20)));
 
-  // Align the suffix with the surrounding FirstIndent if the prefix is not on
+  // Align the suffix with the surrounding indent if the prefix is not on
   // a line of its own.
   expect_eq(R"test(
 int s() {
-  auto S = PTP(
-  R"pb(
-item_1: 1,
-item_2: 2
-  )pb");
+  auto S = PTP(R"pb(
+item_1: 1,
+item_2: 2
+  )pb");
 })test",
 format(R"test(
 int s() {
Index: lib/Format/ContinuationIndenter.cpp
===
--- lib/Format/ContinuationIndenter.cpp
+++ lib/Format/ContinuationIndenter.cpp
@@ -1385,9 +1385,10 @@
   // violate the rectangle rule and visually flows within the surrounding
   // source.
   bool ContentStartsOnNewline = Current.TokenText[OldPrefixSize] == '\n';
-  unsigned NextStartColumn = ContentStartsOnNewline
- ? State.Stack.back().Indent + Style.IndentWidth
- : FirstStartColumn;
+  unsigned NextStartColumn =
+  ContentStartsOnNewline
+  ? State.Stack.back().NestedBlockIndent + Style.IndentWidth
+  : FirstStartColumn;
 
   // The last start column is the column the raw string suffix starts if it is
   // put on a newline.
@@ -1399,7 +1400,7 @@
   // indent.
   unsigned LastStartColumn = Current.NewlinesBefore
  ? FirstStartColumn - NewPrefixSize
- : State.Stack.back().Indent;
+ : State.Stack.back().NestedBlockIndent;
 
   std::pair Fixes = internal::reformat(
   RawStringStyle, RawText, {tooling::Range(0, RawText.size())},
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D44142: [clangd] Revamp handling of diagnostics.

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

The new implementation attaches notes to diagnostic message and shows
the original diagnostics in the message of the note.


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D44142

Files:
  clangd/CMakeLists.txt
  clangd/ClangdLSPServer.cpp
  clangd/ClangdLSPServer.h
  clangd/ClangdServer.cpp
  clangd/ClangdServer.h
  clangd/ClangdUnit.cpp
  clangd/ClangdUnit.h
  clangd/Diagnostics.cpp
  clangd/Diagnostics.h
  clangd/SourceCode.cpp
  clangd/SourceCode.h
  clangd/TUScheduler.cpp
  clangd/TUScheduler.h
  test/clangd/diagnostics.test
  test/clangd/execute-command.test
  test/clangd/extra-flags.test
  test/clangd/fixits.test
  unittests/clangd/ClangdTests.cpp
  unittests/clangd/ClangdUnitTests.cpp
  unittests/clangd/CodeCompleteTests.cpp
  unittests/clangd/TUSchedulerTests.cpp
  unittests/clangd/XRefsTests.cpp

Index: unittests/clangd/XRefsTests.cpp
===
--- unittests/clangd/XRefsTests.cpp
+++ unittests/clangd/XRefsTests.cpp
@@ -41,8 +41,8 @@
 using testing::UnorderedElementsAreArray;
 
 class IgnoreDiagnostics : public DiagnosticsConsumer {
-  void onDiagnosticsReady(
-  PathRef File, Tagged> Diagnostics) override {}
+  void onDiagnosticsReady(PathRef File, Tagged Diagnostics) override {
+  }
 };
 
 // FIXME: this is duplicated with FileIndexTests. Share it.
Index: unittests/clangd/TUSchedulerTests.cpp
===
--- unittests/clangd/TUSchedulerTests.cpp
+++ unittests/clangd/TUSchedulerTests.cpp
@@ -21,7 +21,7 @@
 using ::testing::Pair;
 using ::testing::Pointee;
 
-void ignoreUpdate(llvm::Optional>) {}
+void ignoreUpdate(llvm::Optional) {}
 void ignoreError(llvm::Error Err) {
   handleAllErrors(std::move(Err), [](const llvm::ErrorInfoBase &) {});
 }
@@ -102,20 +102,20 @@
 /*UpdateDebounce=*/std::chrono::steady_clock::duration::zero());
 auto Path = testPath("foo.cpp");
 S.update(Path, getInputs(Path, ""), WantDiagnostics::Yes,
- [&](std::vector) { Ready.wait(); });
+ [&](DiagList) { Ready.wait(); });
 
 S.update(Path, getInputs(Path, "request diags"), WantDiagnostics::Yes,
- [&](std::vector Diags) { ++CallbackCount; });
+ [&](DiagList Diags) { ++CallbackCount; });
 S.update(Path, getInputs(Path, "auto (clobbered)"), WantDiagnostics::Auto,
- [&](std::vector Diags) {
+ [&](DiagList Diags) {
ADD_FAILURE() << "auto should have been cancelled by auto";
  });
 S.update(Path, getInputs(Path, "request no diags"), WantDiagnostics::No,
- [&](std::vector Diags) {
+ [&](DiagList Diags) {
ADD_FAILURE() << "no diags should not be called back";
  });
 S.update(Path, getInputs(Path, "auto (produces)"), WantDiagnostics::Auto,
- [&](std::vector Diags) { ++CallbackCount; });
+ [&](DiagList Diags) { ++CallbackCount; });
 Ready.notify();
   }
   EXPECT_EQ(2, CallbackCount);
@@ -131,15 +131,15 @@
 // FIXME: we could probably use timeouts lower than 1 second here.
 auto Path = testPath("foo.cpp");
 S.update(Path, getInputs(Path, "auto (debounced)"), WantDiagnostics::Auto,
- [&](std::vector Diags) {
+ [&](DiagList Diags) {
ADD_FAILURE() << "auto should have been debounced and canceled";
  });
 std::this_thread::sleep_for(std::chrono::milliseconds(200));
 S.update(Path, getInputs(Path, "auto (timed out)"), WantDiagnostics::Auto,
- [&](std::vector Diags) { ++CallbackCount; });
+ [&](DiagList Diags) { ++CallbackCount; });
 std::this_thread::sleep_for(std::chrono::seconds(2));
 S.update(Path, getInputs(Path, "auto (shut down)"), WantDiagnostics::Auto,
- [&](std::vector Diags) { ++CallbackCount; });
+ [&](DiagList Diags) { ++CallbackCount; });
   }
   EXPECT_EQ(2, CallbackCount);
 }
@@ -189,15 +189,14 @@
 
 {
   WithContextValue WithNonce(NonceKey, ++Nonce);
-  S.update(File, Inputs, WantDiagnostics::Auto,
-   [Nonce, &Mut, &TotalUpdates](
-   llvm::Optional> Diags) {
- EXPECT_THAT(Context::current().get(NonceKey),
- Pointee(Nonce));
-
- std::lock_guard Lock(Mut);
- ++TotalUpdates;
-   });
+  S.update(
+  File, Inputs, WantDiagnostics::Auto,
+  [Nonce, &Mut, &TotalUpdates](llvm::Optional Diags) {
+EXPECT_THAT(Context::current().get(NonceKey), Pointee(Nonce));
+
+std::lock_guard Lock(Mut);
+++TotalUpdates;
+  });
 }
 
 {
Index: unittests/clangd/Co

[PATCH] D44142: [clangd] Revamp handling of diagnostics.

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

This revision is still missing tests, but I wanted to get feedback for the 
overall design and the new diagnostic messages. So sending out for review now.


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D44142



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


[PATCH] D44143: Create properly seeded random generator check

2018-03-06 Thread Borsik Gábor via Phabricator via cfe-commits
boga95 created this revision.
boga95 added a reviewer: clang-tools-extra.
boga95 added a project: clang-tools-extra.
Herald added subscribers: cfe-commits, mgorny.

This check flags all pseudo-random number engines and engine adaptors 
instantiations when it initialized or seeded with default argument or a 
constant expression. Pseudo-random number engines seeded with a predictable 
value may cause vulnerabilities e.g. in security protocols.
This is a CERT security rule, see MSC51-CPP 
.

Example:

  void foo() {
  std::mt19937 engine1; // Bad, always generate the same sequence
  std::mt19937 engine2(1); // Bad
  engine1.seed(); // Bad
  engine2.seed(1); // Bad
  
  std::time_t t;
  engine1.seed(std::time(&t)); // Bad, system time might be controlled by 
user
  
  std::random_device dev;
  std::mt19937 engine3(dev()); // Good
  }


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D44143

Files:
  clang-tidy/cert/CERTTidyModule.cpp
  clang-tidy/cert/CMakeLists.txt
  clang-tidy/cert/ProperlySeededRandomGeneratorCheck.cpp
  clang-tidy/cert/ProperlySeededRandomGeneratorCheck.h
  docs/ReleaseNotes.rst
  docs/clang-tidy/checks/cert-properly-seeded-random-generator.rst
  test/clang-tidy/cert-properly-seeded-random-generator.cpp

Index: test/clang-tidy/cert-properly-seeded-random-generator.cpp
===
--- /dev/null
+++ test/clang-tidy/cert-properly-seeded-random-generator.cpp
@@ -0,0 +1,172 @@
+// RUN: %check_clang_tidy %s cert-properly-seeded-random-generator %t -- -- -std=c++11
+
+namespace std {
+
+template 
+struct linear_congruential_engine {
+  linear_congruential_engine(int _ = 0);
+  void seed(int _ = 0);
+};
+using default_random_engine = linear_congruential_engine;
+
+using size_t = int;
+template 
+struct mersenne_twister_engine {
+  mersenne_twister_engine(int _ = 0);
+  void seed(int _ = 0);
+};
+using mt19937 = mersenne_twister_engine;
+
+template 
+struct subtract_with_carry_engine {
+  subtract_with_carry_engine(int _ = 0);
+  void seed(int _ = 0);
+};
+using ranlux24_base = subtract_with_carry_engine;
+
+template 
+struct discard_block_engine {
+  discard_block_engine();
+  discard_block_engine(int _);
+  void seed();
+  void seed(int _);
+};
+using ranlux24 = discard_block_engine;
+
+template 
+struct independent_bits_engine {
+  independent_bits_engine();
+  independent_bits_engine(int _);
+  void seed();
+  void seed(int _);
+};
+using independent_bits = independent_bits_engine;
+
+template 
+struct shuffle_order_engine {
+  shuffle_order_engine();
+  shuffle_order_engine(int _);
+  void seed();
+  void seed(int _);
+};
+using shuffle_order = shuffle_order_engine;
+
+struct random_device {
+  random_device();
+  int operator()();
+};
+} // namespace std
+
+void f() {
+  const int seed = 2;
+  // One instantiation for every engine
+  std::default_random_engine engine1;
+  // CHECK-MESSAGES: :[[@LINE-1]]:30: warning: random number generator must be seeded with a random_device instead of default argument
+  std::default_random_engine engine2(1);
+  // CHECK-MESSAGES: :[[@LINE-1]]:30: warning: random number generator must be seeded with a random_device instead of a constant [cert-properly-seeded-random-generator]
+  std::default_random_engine engine3(seed);
+  // CHECK-MESSAGES: :[[@LINE-1]]:30: warning: random number generator must be seeded with a random_device instead of a constant [cert-properly-seeded-random-generator]
+  engine1.seed();
+  // CHECK-MESSAGES: :[[@LINE-1]]:11: warning: random number generator must be seeded with a random_device instead of default argument [cert-properly-seeded-random-generator]
+  engine1.seed(1);
+  // CHECK-MESSAGES: :[[@LINE-1]]:11: warning: random number generator must be seeded with a random_device instead of a constant [cert-properly-seeded-random-generator]
+  engine1.seed(seed);
+  // CHECK-MESSAGES: :[[@LINE-1]]:11: warning: random number generator must be seeded with a random_device instead of a constant [cert-properly-seeded-random-generator]
+
+  std::mt19937 engine4;
+  // CHECK-MESSAGES: :[[@LINE-1]]:16: warning: random number generator must be seeded with a random_device instead of default argument
+  std::mt19937 engine5(1);
+  // CHECK-MESSAGES: :[[@LINE-1]]:16: warning: random number generator must be seeded with a random_device instead of a constant [cert-properly-seeded-random-generator]
+  std::mt19937 engine6(seed);
+  // CHECK-MESSAGES: :[[@LINE-1]]:16: warning: random number generator must be seeded with a random_device instead of a constant [cert-properly-seeded-random-generator]
+  engine4.seed();
+  // CHECK-MESSAGES: :[[@LINE-1]]:11: warning: random number generator must be seeded with a random_device instead of default argument [cert-properly-seeded-random-generator]
+  engine4.seed(1);
+  // CHECK-MESSAGE

[PATCH] D16403: Add scope information to CFG

2018-03-06 Thread Maxim Ostapenko via Phabricator via cfe-commits
m.ostapenko updated this revision to Diff 137150.
m.ostapenko added a comment.

Rebased and updated. Fix the issue with ordering between ScopeEnds and implicit 
destructors.


Repository:
  rL LLVM

https://reviews.llvm.org/D16403

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

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

[PATCH] D16403: Add scope information to CFG

2018-03-06 Thread Maxim Ostapenko via Phabricator via cfe-commits
m.ostapenko added a comment.

Now, the cfg for this example:

  void test_for_implicit_scope() {
for (A a; A b = a;)
  A c;
  }

looks like this:
F5874197: CFG-implicit-for.dot 


Repository:
  rL LLVM

https://reviews.llvm.org/D16403



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


[PATCH] D43741: [Analyzer] More accurate modeling about the increment operator of the operand with type bool.

2018-03-06 Thread Henry Wong via Phabricator via cfe-commits
MTC updated this revision to Diff 137154.
MTC added a comment.

Remove the default configuration `-analyzer-store=region` in the test file.


Repository:
  rC Clang

https://reviews.llvm.org/D43741

Files:
  include/clang/StaticAnalyzer/Core/PathSensitive/BasicValueFactory.h
  lib/StaticAnalyzer/Core/ExprEngineC.cpp
  test/Analysis/_Bool-increment-decrement.c
  test/Analysis/bool-increment.cpp

Index: test/Analysis/bool-increment.cpp
===
--- /dev/null
+++ test/Analysis/bool-increment.cpp
@@ -0,0 +1,84 @@
+// RUN: %clang_analyze_cc1 -analyzer-checker=debug.ExprInspection -verify -std=c++98 -Wno-deprecated %s
+// RUN: %clang_analyze_cc1 -analyzer-checker=debug.ExprInspection -verify -std=c++11 -Wno-deprecated %s
+// RUN: %clang_analyze_cc1 -analyzer-checker=debug.ExprInspection -verify -std=c++14 -Wno-deprecated %s
+
+extern void clang_analyzer_eval(bool);
+
+void test_bool_value() {
+  {
+bool b = true;
+clang_analyzer_eval(b == 1); // expected-warning{{TRUE}}
+  }
+
+  {
+bool b = false;
+clang_analyzer_eval(b == 0); // expected-warning{{TRUE}}
+  }
+
+  {
+bool b = -10;
+clang_analyzer_eval(b == 1); // expected-warning{{TRUE}}
+  }
+
+  {
+bool b = 10;
+clang_analyzer_eval(b == 1); // expected-warning{{TRUE}}
+  }
+
+  {
+bool b = 10;
+b++;
+clang_analyzer_eval(b == 1); // expected-warning{{TRUE}}
+  }
+
+  {
+bool b = 0;
+b++;
+clang_analyzer_eval(b == 1); // expected-warning{{TRUE}}
+  }
+}
+
+void test_bool_increment() {
+  {
+bool b = true;
+b++;
+clang_analyzer_eval(b); // expected-warning{{TRUE}}
+  }
+
+  {
+bool b = false;
+b++;
+clang_analyzer_eval(b); // expected-warning{{TRUE}}
+  }
+
+  {
+bool b = true;
+++b;
+clang_analyzer_eval(b); // expected-warning{{TRUE}}
+  }
+
+  {
+bool b = false;
+++b;
+clang_analyzer_eval(b); // expected-warning{{TRUE}}
+  }
+
+  {
+bool b = 0;
+++b;
+clang_analyzer_eval(b); // expected-warning{{TRUE}}
+  }
+
+  {
+bool b = 10;
+++b;
+++b;
+clang_analyzer_eval(b); // expected-warning{{TRUE}}
+  }
+
+  {
+bool b = -10;
+++b;
+clang_analyzer_eval(b); // expected-warning{{TRUE}}
+  }
+}
Index: test/Analysis/_Bool-increment-decrement.c
===
--- /dev/null
+++ test/Analysis/_Bool-increment-decrement.c
@@ -0,0 +1,140 @@
+// RUN: %clang_analyze_cc1 -analyzer-checker=debug.ExprInspection -verify -std=c99 -Dbool=_Bool -Dtrue=1 -Dfalse=0 %s
+// RUN: %clang_analyze_cc1 -analyzer-checker=debug.ExprInspection -verify -std=c11 -Dbool=_Bool -Dtrue=1 -Dfalse=0 %s
+extern void clang_analyzer_eval(bool);
+
+void test__Bool_value() {
+  {
+bool b = true;
+clang_analyzer_eval(b == 1); // expected-warning{{TRUE}}
+  }
+
+  {
+bool b = false;
+clang_analyzer_eval(b == 0); // expected-warning{{TRUE}}
+  }
+
+  {
+bool b = -10;
+clang_analyzer_eval(b == 1); // expected-warning{{TRUE}}
+  }
+
+  {
+bool b = 10;
+clang_analyzer_eval(b == 1); // expected-warning{{TRUE}}
+  }
+
+  {
+bool b = 10;
+b++;
+clang_analyzer_eval(b == 1); // expected-warning{{TRUE}}
+  }
+
+  {
+bool b = 0;
+b++;
+clang_analyzer_eval(b == 1); // expected-warning{{TRUE}}
+  }
+}
+
+void test__Bool_increment() {
+  {
+bool b = true;
+b++;
+clang_analyzer_eval(b == 1); // expected-warning{{TRUE}}
+  }
+
+  {
+bool b = false;
+b++;
+clang_analyzer_eval(b == 1); // expected-warning{{TRUE}}
+  }
+
+  {
+bool b = true;
+++b;
+clang_analyzer_eval(b == 1); // expected-warning{{TRUE}}
+  }
+
+  {
+bool b = false;
+++b;
+clang_analyzer_eval(b == 1); // expected-warning{{TRUE}}
+  }
+
+  {
+bool b = 0;
+++b;
+clang_analyzer_eval(b == 1); // expected-warning{{TRUE}}
+  }
+
+  {
+bool b = 10;
+++b;
+++b;
+clang_analyzer_eval(b == 1); // expected-warning{{TRUE}}
+  }
+
+  {
+bool b = -10;
+++b;
+clang_analyzer_eval(b == 1); // expected-warning{{TRUE}}
+  }
+
+  {
+bool b = -1;
+++b;
+clang_analyzer_eval(b == 1); // expected-warning{{TRUE}}
+  }
+}
+
+void test__Bool_decrement() {
+  {
+bool b = true;
+b--;
+clang_analyzer_eval(b == 0); // expected-warning{{TRUE}}
+  }
+
+  {
+bool b = false;
+b--;
+clang_analyzer_eval(b == 1); // expected-warning{{TRUE}}
+  }
+
+  {
+bool b = true;
+--b;
+clang_analyzer_eval(b == 0); // expected-warning{{TRUE}}
+  }
+
+  {
+bool b = false;
+--b;
+clang_analyzer_eval(b == 1); // expected-warning{{TRUE}}
+  }
+
+  {
+bool b = 0;
+--b;
+clang_analyzer_eval(b == 1); // expected-warning{{TRUE}}
+  }
+
+  {
+bool b = 10;
+--b;
+clang_analyzer_eval(b == 0); // expected-warning{{TRUE}}
+--b;
+clang_analyzer_eval(b == 1); // expected-warning{{TRUE}}
+  }
+
+  {
+bool b = -10;
+--b;
+clang_analyzer_

r326776 - [Analyzer] More accurate modeling about the increment operator of the operand with type bool.

2018-03-06 Thread Henry Wong via cfe-commits
Author: henrywong
Date: Tue Mar  6 04:29:09 2018
New Revision: 326776

URL: http://llvm.org/viewvc/llvm-project?rev=326776&view=rev
Log:
[Analyzer] More accurate modeling about the increment operator of the operand 
with type bool.

Summary:
There is a problem with analyzer that a wrong value is given when modeling the 
increment operator of the operand with type bool. After `rL307604` is applied, 
a unsigned overflow may occur.

Example:
```
void func() {
  bool b = true;
  // unsigned overflow occur, 2 -> 0 U1b
  b++;
}
``` 

The use of an operand of type bool with the ++ operators is deprecated but 
valid untill C++17. And if the operand of the increment operator is of type 
bool, it is set to true.

This patch includes two parts:

  - If the operand of the increment operator is of type bool or type _Bool, set 
to true.
  - Modify `BasicValueFactory::getTruthValue()`, use `getIntWidth()` instead 
`getTypeSize()` and use `unsigned` instead `signed`.

Reviewers: alexshap, NoQ, dcoughlin, george.karpenkov

Reviewed By: NoQ

Subscribers: xazax.hun, szepet, a.sidorin, cfe-commits, MTC

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

Added:
cfe/trunk/test/Analysis/_Bool-increment-decrement.c
cfe/trunk/test/Analysis/bool-increment.cpp
Modified:

cfe/trunk/include/clang/StaticAnalyzer/Core/PathSensitive/BasicValueFactory.h
cfe/trunk/lib/StaticAnalyzer/Core/ExprEngineC.cpp

Modified: 
cfe/trunk/include/clang/StaticAnalyzer/Core/PathSensitive/BasicValueFactory.h
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/StaticAnalyzer/Core/PathSensitive/BasicValueFactory.h?rev=326776&r1=326775&r2=326776&view=diff
==
--- 
cfe/trunk/include/clang/StaticAnalyzer/Core/PathSensitive/BasicValueFactory.h 
(original)
+++ 
cfe/trunk/include/clang/StaticAnalyzer/Core/PathSensitive/BasicValueFactory.h 
Tue Mar  6 04:29:09 2018
@@ -211,7 +211,7 @@ public:
   }
 
   const llvm::APSInt &getTruthValue(bool b, QualType T) {
-return getValue(b ? 1 : 0, Ctx.getTypeSize(T), false);
+return getValue(b ? 1 : 0, Ctx.getIntWidth(T), true);
   }
 
   const llvm::APSInt &getTruthValue(bool b) {

Modified: cfe/trunk/lib/StaticAnalyzer/Core/ExprEngineC.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/StaticAnalyzer/Core/ExprEngineC.cpp?rev=326776&r1=326775&r2=326776&view=diff
==
--- cfe/trunk/lib/StaticAnalyzer/Core/ExprEngineC.cpp (original)
+++ cfe/trunk/lib/StaticAnalyzer/Core/ExprEngineC.cpp Tue Mar  6 04:29:09 2018
@@ -1066,6 +1066,7 @@ void ExprEngine::VisitIncrementDecrement
 // constant value. If the UnaryOperator has location type, create the
 // constant with int type and pointer width.
 SVal RHS;
+SVal Result;
 
 if (U->getType()->isAnyPointerType())
   RHS = svalBuilder.makeArrayIndex(1);
@@ -1074,7 +1075,14 @@ void ExprEngine::VisitIncrementDecrement
 else
   RHS = UnknownVal();
 
-SVal Result = evalBinOp(state, Op, V2, RHS, U->getType());
+// The use of an operand of type bool with the ++ operators is deprecated
+// but valid until C++17. And if the operand of the ++ operator is of type
+// bool, it is set to true until C++17. Note that for '_Bool', it is also
+// set to true when it encounters ++ operator.
+if (U->getType()->isBooleanType() && U->isIncrementOp())
+  Result = svalBuilder.makeTruthVal(true, U->getType());
+else
+  Result = evalBinOp(state, Op, V2, RHS, U->getType());
 
 // Conjure a new symbol if necessary to recover precision.
 if (Result.isUnknown()){
@@ -1096,7 +1104,6 @@ void ExprEngine::VisitIncrementDecrement
   Constraint = svalBuilder.evalEQ(state, SymVal,
svalBuilder.makeZeroVal(U->getType()));
 
-
   state = state->assume(Constraint, false);
   assert(state);
 }

Added: cfe/trunk/test/Analysis/_Bool-increment-decrement.c
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/Analysis/_Bool-increment-decrement.c?rev=326776&view=auto
==
--- cfe/trunk/test/Analysis/_Bool-increment-decrement.c (added)
+++ cfe/trunk/test/Analysis/_Bool-increment-decrement.c Tue Mar  6 04:29:09 2018
@@ -0,0 +1,140 @@
+// RUN: %clang_analyze_cc1 -analyzer-checker=debug.ExprInspection -verify 
-std=c99 -Dbool=_Bool -Dtrue=1 -Dfalse=0 %s
+// RUN: %clang_analyze_cc1 -analyzer-checker=debug.ExprInspection -verify 
-std=c11 -Dbool=_Bool -Dtrue=1 -Dfalse=0 %s
+extern void clang_analyzer_eval(bool);
+
+void test__Bool_value() {
+  {
+bool b = true;
+clang_analyzer_eval(b == 1); // expected-warning{{TRUE}}
+  }
+
+  {
+bool b = false;
+clang_analyzer_eval(b == 0); // expected-warning{{TRUE}}
+  }
+
+  {
+bool b = -10;
+clang_analyzer_eval(b == 1); // expected-warning{{TRUE}}
+  }
+
+  {
+

[PATCH] D43741: [Analyzer] More accurate modeling about the increment operator of the operand with type bool.

2018-03-06 Thread Phabricator via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rL326776: [Analyzer] More accurate modeling about the 
increment operator of the operand… (authored by henrywong, committed by ).
Herald added a subscriber: llvm-commits.

Changed prior to commit:
  https://reviews.llvm.org/D43741?vs=137154&id=137158#toc

Repository:
  rL LLVM

https://reviews.llvm.org/D43741

Files:
  cfe/trunk/include/clang/StaticAnalyzer/Core/PathSensitive/BasicValueFactory.h
  cfe/trunk/lib/StaticAnalyzer/Core/ExprEngineC.cpp
  cfe/trunk/test/Analysis/_Bool-increment-decrement.c
  cfe/trunk/test/Analysis/bool-increment.cpp

Index: cfe/trunk/include/clang/StaticAnalyzer/Core/PathSensitive/BasicValueFactory.h
===
--- cfe/trunk/include/clang/StaticAnalyzer/Core/PathSensitive/BasicValueFactory.h
+++ cfe/trunk/include/clang/StaticAnalyzer/Core/PathSensitive/BasicValueFactory.h
@@ -211,7 +211,7 @@
   }
 
   const llvm::APSInt &getTruthValue(bool b, QualType T) {
-return getValue(b ? 1 : 0, Ctx.getTypeSize(T), false);
+return getValue(b ? 1 : 0, Ctx.getIntWidth(T), true);
   }
 
   const llvm::APSInt &getTruthValue(bool b) {
Index: cfe/trunk/test/Analysis/bool-increment.cpp
===
--- cfe/trunk/test/Analysis/bool-increment.cpp
+++ cfe/trunk/test/Analysis/bool-increment.cpp
@@ -0,0 +1,84 @@
+// RUN: %clang_analyze_cc1 -analyzer-checker=debug.ExprInspection -verify -std=c++98 -Wno-deprecated %s
+// RUN: %clang_analyze_cc1 -analyzer-checker=debug.ExprInspection -verify -std=c++11 -Wno-deprecated %s
+// RUN: %clang_analyze_cc1 -analyzer-checker=debug.ExprInspection -verify -std=c++14 -Wno-deprecated %s
+
+extern void clang_analyzer_eval(bool);
+
+void test_bool_value() {
+  {
+bool b = true;
+clang_analyzer_eval(b == 1); // expected-warning{{TRUE}}
+  }
+
+  {
+bool b = false;
+clang_analyzer_eval(b == 0); // expected-warning{{TRUE}}
+  }
+
+  {
+bool b = -10;
+clang_analyzer_eval(b == 1); // expected-warning{{TRUE}}
+  }
+
+  {
+bool b = 10;
+clang_analyzer_eval(b == 1); // expected-warning{{TRUE}}
+  }
+
+  {
+bool b = 10;
+b++;
+clang_analyzer_eval(b == 1); // expected-warning{{TRUE}}
+  }
+
+  {
+bool b = 0;
+b++;
+clang_analyzer_eval(b == 1); // expected-warning{{TRUE}}
+  }
+}
+
+void test_bool_increment() {
+  {
+bool b = true;
+b++;
+clang_analyzer_eval(b); // expected-warning{{TRUE}}
+  }
+
+  {
+bool b = false;
+b++;
+clang_analyzer_eval(b); // expected-warning{{TRUE}}
+  }
+
+  {
+bool b = true;
+++b;
+clang_analyzer_eval(b); // expected-warning{{TRUE}}
+  }
+
+  {
+bool b = false;
+++b;
+clang_analyzer_eval(b); // expected-warning{{TRUE}}
+  }
+
+  {
+bool b = 0;
+++b;
+clang_analyzer_eval(b); // expected-warning{{TRUE}}
+  }
+
+  {
+bool b = 10;
+++b;
+++b;
+clang_analyzer_eval(b); // expected-warning{{TRUE}}
+  }
+
+  {
+bool b = -10;
+++b;
+clang_analyzer_eval(b); // expected-warning{{TRUE}}
+  }
+}
Index: cfe/trunk/test/Analysis/_Bool-increment-decrement.c
===
--- cfe/trunk/test/Analysis/_Bool-increment-decrement.c
+++ cfe/trunk/test/Analysis/_Bool-increment-decrement.c
@@ -0,0 +1,140 @@
+// RUN: %clang_analyze_cc1 -analyzer-checker=debug.ExprInspection -verify -std=c99 -Dbool=_Bool -Dtrue=1 -Dfalse=0 %s
+// RUN: %clang_analyze_cc1 -analyzer-checker=debug.ExprInspection -verify -std=c11 -Dbool=_Bool -Dtrue=1 -Dfalse=0 %s
+extern void clang_analyzer_eval(bool);
+
+void test__Bool_value() {
+  {
+bool b = true;
+clang_analyzer_eval(b == 1); // expected-warning{{TRUE}}
+  }
+
+  {
+bool b = false;
+clang_analyzer_eval(b == 0); // expected-warning{{TRUE}}
+  }
+
+  {
+bool b = -10;
+clang_analyzer_eval(b == 1); // expected-warning{{TRUE}}
+  }
+
+  {
+bool b = 10;
+clang_analyzer_eval(b == 1); // expected-warning{{TRUE}}
+  }
+
+  {
+bool b = 10;
+b++;
+clang_analyzer_eval(b == 1); // expected-warning{{TRUE}}
+  }
+
+  {
+bool b = 0;
+b++;
+clang_analyzer_eval(b == 1); // expected-warning{{TRUE}}
+  }
+}
+
+void test__Bool_increment() {
+  {
+bool b = true;
+b++;
+clang_analyzer_eval(b == 1); // expected-warning{{TRUE}}
+  }
+
+  {
+bool b = false;
+b++;
+clang_analyzer_eval(b == 1); // expected-warning{{TRUE}}
+  }
+
+  {
+bool b = true;
+++b;
+clang_analyzer_eval(b == 1); // expected-warning{{TRUE}}
+  }
+
+  {
+bool b = false;
+++b;
+clang_analyzer_eval(b == 1); // expected-warning{{TRUE}}
+  }
+
+  {
+bool b = 0;
+++b;
+clang_analyzer_eval(b == 1); // expected-warning{{TRUE}}
+  }
+
+  {
+bool b = 10;
+++b;
+++b;
+clang_analyzer_eval(b == 1); // expected-warning{{TRUE}}
+  }
+
+  {
+bool b = -10;
+++b;
+clang_analyz

[PATCH] D43741: [Analyzer] More accurate modeling about the increment operator of the operand with type bool.

2018-03-06 Thread Phabricator via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rC326776: [Analyzer] More accurate modeling about the 
increment operator of the operand… (authored by henrywong, committed by ).

Repository:
  rC Clang

https://reviews.llvm.org/D43741

Files:
  include/clang/StaticAnalyzer/Core/PathSensitive/BasicValueFactory.h
  lib/StaticAnalyzer/Core/ExprEngineC.cpp
  test/Analysis/_Bool-increment-decrement.c
  test/Analysis/bool-increment.cpp

Index: include/clang/StaticAnalyzer/Core/PathSensitive/BasicValueFactory.h
===
--- include/clang/StaticAnalyzer/Core/PathSensitive/BasicValueFactory.h
+++ include/clang/StaticAnalyzer/Core/PathSensitive/BasicValueFactory.h
@@ -211,7 +211,7 @@
   }
 
   const llvm::APSInt &getTruthValue(bool b, QualType T) {
-return getValue(b ? 1 : 0, Ctx.getTypeSize(T), false);
+return getValue(b ? 1 : 0, Ctx.getIntWidth(T), true);
   }
 
   const llvm::APSInt &getTruthValue(bool b) {
Index: test/Analysis/bool-increment.cpp
===
--- test/Analysis/bool-increment.cpp
+++ test/Analysis/bool-increment.cpp
@@ -0,0 +1,84 @@
+// RUN: %clang_analyze_cc1 -analyzer-checker=debug.ExprInspection -verify -std=c++98 -Wno-deprecated %s
+// RUN: %clang_analyze_cc1 -analyzer-checker=debug.ExprInspection -verify -std=c++11 -Wno-deprecated %s
+// RUN: %clang_analyze_cc1 -analyzer-checker=debug.ExprInspection -verify -std=c++14 -Wno-deprecated %s
+
+extern void clang_analyzer_eval(bool);
+
+void test_bool_value() {
+  {
+bool b = true;
+clang_analyzer_eval(b == 1); // expected-warning{{TRUE}}
+  }
+
+  {
+bool b = false;
+clang_analyzer_eval(b == 0); // expected-warning{{TRUE}}
+  }
+
+  {
+bool b = -10;
+clang_analyzer_eval(b == 1); // expected-warning{{TRUE}}
+  }
+
+  {
+bool b = 10;
+clang_analyzer_eval(b == 1); // expected-warning{{TRUE}}
+  }
+
+  {
+bool b = 10;
+b++;
+clang_analyzer_eval(b == 1); // expected-warning{{TRUE}}
+  }
+
+  {
+bool b = 0;
+b++;
+clang_analyzer_eval(b == 1); // expected-warning{{TRUE}}
+  }
+}
+
+void test_bool_increment() {
+  {
+bool b = true;
+b++;
+clang_analyzer_eval(b); // expected-warning{{TRUE}}
+  }
+
+  {
+bool b = false;
+b++;
+clang_analyzer_eval(b); // expected-warning{{TRUE}}
+  }
+
+  {
+bool b = true;
+++b;
+clang_analyzer_eval(b); // expected-warning{{TRUE}}
+  }
+
+  {
+bool b = false;
+++b;
+clang_analyzer_eval(b); // expected-warning{{TRUE}}
+  }
+
+  {
+bool b = 0;
+++b;
+clang_analyzer_eval(b); // expected-warning{{TRUE}}
+  }
+
+  {
+bool b = 10;
+++b;
+++b;
+clang_analyzer_eval(b); // expected-warning{{TRUE}}
+  }
+
+  {
+bool b = -10;
+++b;
+clang_analyzer_eval(b); // expected-warning{{TRUE}}
+  }
+}
Index: test/Analysis/_Bool-increment-decrement.c
===
--- test/Analysis/_Bool-increment-decrement.c
+++ test/Analysis/_Bool-increment-decrement.c
@@ -0,0 +1,140 @@
+// RUN: %clang_analyze_cc1 -analyzer-checker=debug.ExprInspection -verify -std=c99 -Dbool=_Bool -Dtrue=1 -Dfalse=0 %s
+// RUN: %clang_analyze_cc1 -analyzer-checker=debug.ExprInspection -verify -std=c11 -Dbool=_Bool -Dtrue=1 -Dfalse=0 %s
+extern void clang_analyzer_eval(bool);
+
+void test__Bool_value() {
+  {
+bool b = true;
+clang_analyzer_eval(b == 1); // expected-warning{{TRUE}}
+  }
+
+  {
+bool b = false;
+clang_analyzer_eval(b == 0); // expected-warning{{TRUE}}
+  }
+
+  {
+bool b = -10;
+clang_analyzer_eval(b == 1); // expected-warning{{TRUE}}
+  }
+
+  {
+bool b = 10;
+clang_analyzer_eval(b == 1); // expected-warning{{TRUE}}
+  }
+
+  {
+bool b = 10;
+b++;
+clang_analyzer_eval(b == 1); // expected-warning{{TRUE}}
+  }
+
+  {
+bool b = 0;
+b++;
+clang_analyzer_eval(b == 1); // expected-warning{{TRUE}}
+  }
+}
+
+void test__Bool_increment() {
+  {
+bool b = true;
+b++;
+clang_analyzer_eval(b == 1); // expected-warning{{TRUE}}
+  }
+
+  {
+bool b = false;
+b++;
+clang_analyzer_eval(b == 1); // expected-warning{{TRUE}}
+  }
+
+  {
+bool b = true;
+++b;
+clang_analyzer_eval(b == 1); // expected-warning{{TRUE}}
+  }
+
+  {
+bool b = false;
+++b;
+clang_analyzer_eval(b == 1); // expected-warning{{TRUE}}
+  }
+
+  {
+bool b = 0;
+++b;
+clang_analyzer_eval(b == 1); // expected-warning{{TRUE}}
+  }
+
+  {
+bool b = 10;
+++b;
+++b;
+clang_analyzer_eval(b == 1); // expected-warning{{TRUE}}
+  }
+
+  {
+bool b = -10;
+++b;
+clang_analyzer_eval(b == 1); // expected-warning{{TRUE}}
+  }
+
+  {
+bool b = -1;
+++b;
+clang_analyzer_eval(b == 1); // expected-warning{{TRUE}}
+  }
+}
+
+void test__Bool_decrement() {
+  {
+bool b = true;
+b--;
+clang_analyzer_eval(b == 0

[clang-tools-extra] r326778 - [clangd] Fix -Wpedantic warning, NFC.

2018-03-06 Thread Haojian Wu via cfe-commits
Author: hokein
Date: Tue Mar  6 04:56:18 2018
New Revision: 326778

URL: http://llvm.org/viewvc/llvm-project?rev=326778&view=rev
Log:
[clangd] Fix -Wpedantic warning, NFC.

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

Modified: clang-tools-extra/trunk/clangd/ClangdServer.cpp
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clangd/ClangdServer.cpp?rev=326778&r1=326777&r2=326778&view=diff
==
--- clang-tools-extra/trunk/clangd/ClangdServer.cpp (original)
+++ clang-tools-extra/trunk/clangd/ClangdServer.cpp Tue Mar  6 04:56:18 2018
@@ -320,7 +320,7 @@ static llvm::Expected toHead
   if (!Resolved)
 return Resolved.takeError();
   return HeaderFile{std::move(*Resolved), /*Verbatim=*/false};
-};
+}
 
 Expected
 ClangdServer::insertInclude(PathRef File, StringRef Code,


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


[PATCH] D44137: [clang-tidy] Fix one corner case in make-unique check.

2018-03-06 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman accepted this revision.
aaron.ballman added a comment.

LGTM!


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D44137



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


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

2018-03-06 Thread Daniel Kolozsvari via Phabricator via cfe-commits
koldaniel updated this revision to Diff 137162.

https://reviews.llvm.org/D35068

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

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

[PATCH] D43906: [clang-format] Improve detection of Objective-C block types

2018-03-06 Thread Krasimir Georgiev via Phabricator via cfe-commits
krasimir added inline comments.



Comment at: unittests/Format/FormatTest.cpp:7698
 
+TEST_F(FormatTest, ObjCBlockTypesAndVariables) {
+  verifyFormat("void DoStuffWithBlockType(int (^)(char));");

This should be in `FormatTestObjC.cpp`.


Repository:
  rC Clang

https://reviews.llvm.org/D43906



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


[PATCH] D44093: [BUILTINS] structure pretty printer

2018-03-06 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman added inline comments.



Comment at: lib/CodeGen/CGBuiltin.cpp:1208
+
+assert(RT && "The first argument must be a record type");
+

paulsemel wrote:
> aaron.ballman wrote:
> > I don't see anything enforcing this constraint, so users are likely to hit 
> > this assertion rather than a compile error.
> I actually didn't manage to enforce this in the builtin declaration as we can 
> only declare simple types (I am probably missing something)
I think this builtin will require custom type checking (so its signature needs 
a `t`), and then you can add your code to `Sema::CheckBuiltinFunctionCall()` to 
do the actual semantic checking.



Comment at: lib/CodeGen/CGBuiltin.cpp:1258
+
+  //Need to handle bitfield here
+

paulsemel wrote:
> aaron.ballman wrote:
> > Are you intending to implement this as part of this functionality?
> Yes, my goal is to be able to dump the bitfields correctly, particularly if 
> the structure is packed (for dumping a GDT for example).
> I just didn't manage to do it properly for the moment.
Okay, this should probably be a FIXME comment if you don't intend to handle it 
in the initial patch. It should also have a test case with some comments about 
the test behavior.



Comment at: lib/CodeGen/CGBuiltin.cpp:1206
+QualType Arg0Type = Arg0->getType()->getPointeeType();
+const RecordType *RT = Arg0Type->getAs();
+

You can use `const auto *` here because the type is spelled out in the 
initializer.



Comment at: lib/CodeGen/CGBuiltin.cpp:1211
+RecordDecl *RD = RT->getDecl()->getDefinition();
+ASTContext &ASTContext = RD->getASTContext();
+const ASTRecordLayout &RL = ASTContext.getASTRecordLayout(RD);

Please don't name the variable the same name as a type.



Comment at: lib/CodeGen/CGBuiltin.cpp:1231
+  Types[getContext().VoidPtrTy] = "%p";
+  Types[getContext().FloatTy] = "%f";
+  Types[getContext().DoubleTy] = "%f";

It's unfortunate that you cannot distinguish between `float` and `double`. Do 
you need to use the format specifiers exactly?

What about other type information, like qualifiers or array extents? How should 
this handle types that do not exist in this mapping, like structure or enum 
types?



Comment at: lib/CodeGen/CGBuiltin.cpp:1238
+/* field : RecordDecl::field_iterator */
+for (auto *FD : RD->fields()) {
+  uint64_t Off = RL.getFieldOffset(FD->getFieldIndex());

`const auto *`


Repository:
  rC Clang

https://reviews.llvm.org/D44093



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


[PATCH] D43904: [clang-format] Improve detection of ObjC for-in statements

2018-03-06 Thread Krasimir Georgiev via Phabricator via cfe-commits
krasimir added inline comments.



Comment at: unittests/Format/FormatTest.cpp:778
 
+TEST_F(FormatTest, ObjCForInLoop) {
+  verifyFormat("for (Foo *x = 0; x != in; x++) {\n}");

Please move the ObjC-specific instances to `FormatTestObjC.cpp`.


Repository:
  rC Clang

https://reviews.llvm.org/D43904



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


[PATCH] D43731: [clang-format] Fix documentation for SpaceAfterCStyleCast option

2018-03-06 Thread Krasimir Georgiev via Phabricator via cfe-commits
krasimir added a comment.

I'll commit this for you.


https://reviews.llvm.org/D43731



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


r326781 - [clang-format] Fix documentation for SpaceAfterCStyleCast option

2018-03-06 Thread Krasimir Georgiev via cfe-commits
Author: krasimir
Date: Tue Mar  6 05:24:01 2018
New Revision: 326781

URL: http://llvm.org/viewvc/llvm-project?rev=326781&view=rev
Log:
[clang-format] Fix documentation for SpaceAfterCStyleCast option

Patch contributed by @EricMarti!

Summary: I noticed that the example for SpaceAfterCStyleCast does not match its 
description. I fixed the example after testing it out.

Reviewers: rsmith, krasimir

Reviewed By: krasimir

Subscribers: klimek, cfe-commits

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

Modified:
cfe/trunk/docs/ClangFormatStyleOptions.rst
cfe/trunk/include/clang/Format/Format.h

Modified: cfe/trunk/docs/ClangFormatStyleOptions.rst
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/docs/ClangFormatStyleOptions.rst?rev=326781&r1=326780&r2=326781&view=diff
==
--- cfe/trunk/docs/ClangFormatStyleOptions.rst (original)
+++ cfe/trunk/docs/ClangFormatStyleOptions.rst Tue Mar  6 05:24:01 2018
@@ -629,7 +629,9 @@ the configuration (without a prefix: ``A
   int bar();
   }
 
-  * ``bool AfterObjCDeclaration`` Wrap ObjC definitions (``@autoreleasepool``, 
interfaces, ..).
+  * ``bool AfterObjCDeclaration`` Wrap ObjC definitions (interfaces, 
implementations...).
+@autoreleasepool and @synchronized blocks are wrapped
+according to `AfterControlStatement` flag.
 
   * ``bool AfterStruct`` Wrap struct definitions.
 
@@ -1508,6 +1510,52 @@ the configuration (without a prefix: ``A
 
 
 
+**ObjCBinPackProtocolList** (``BinPackStyle``)
+  Controls bin-packing Objective-C protocol conformance list
+  items into as few lines as possible when they go over ``ColumnLimit``.
+
+  If ``Auto`` (the default), delegates to the value in
+  ``BinPackParameters``. If that is ``true``, bin-packs Objective-C
+  protocol conformance list items into as few lines as possible
+  whenever they go over ``ColumnLimit``.
+
+  If ``Always``, always bin-packs Objective-C protocol conformance
+  list items into as few lines as possible whenever they go over
+  ``ColumnLimit``.
+
+  If ``Never``, lays out Objective-C protocol conformance list items
+  onto individual lines whenever they go over ``ColumnLimit``.
+
+
+  .. code-block:: c++
+
+ Always (or Auto, if BinPackParameters=true):
+ @interface c () <
+ c, c,
+ c, c> {
+ }
+
+ Never (or Auto, if BinPackParameters=false):
+ @interface d () <
+ d,
+ d,
+ d,
+ d> {
+ }
+
+  Possible values:
+
+  * ``BPS_Auto`` (in configuration: ``Auto``)
+Automatically determine parameter bin-packing behavior.
+
+  * ``BPS_Always`` (in configuration: ``Always``)
+Always bin-pack parameters.
+
+  * ``BPS_Never`` (in configuration: ``Never``)
+Never bin-pack parameters.
+
+
+
 **ObjCBlockIndentWidth** (``unsigned``)
   The number of characters to use for indentation of ObjC blocks.
 
@@ -1662,7 +1710,7 @@ the configuration (without a prefix: ``A
   .. code-block:: c++
 
  true:  false:
- (int)i;vs. (int) i;
+ (int) i;   vs. (int)i;
 
 **SpaceAfterTemplateKeyword** (``bool``)
   If ``true``, a space will be inserted after the 'template' keyword.

Modified: cfe/trunk/include/clang/Format/Format.h
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Format/Format.h?rev=326781&r1=326780&r2=326781&view=diff
==
--- cfe/trunk/include/clang/Format/Format.h (original)
+++ cfe/trunk/include/clang/Format/Format.h Tue Mar  6 05:24:01 2018
@@ -1506,7 +1506,7 @@ struct FormatStyle {
   /// \brief If ``true``, a space is inserted after C style casts.
   /// \code
   ///true:  false:
-  ///(int)i;vs. (int) i;
+  ///(int) i;   vs. (int)i;
   /// \endcode
   bool SpaceAfterCStyleCast;
 


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


[PATCH] D43731: [clang-format] Fix documentation for SpaceAfterCStyleCast option

2018-03-06 Thread Krasimir Georgiev via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rL326781: [clang-format] Fix documentation for 
SpaceAfterCStyleCast option (authored by krasimir, committed by ).
Herald added a subscriber: llvm-commits.

Changed prior to commit:
  https://reviews.llvm.org/D43731?vs=136645&id=137166#toc

Repository:
  rL LLVM

https://reviews.llvm.org/D43731

Files:
  cfe/trunk/docs/ClangFormatStyleOptions.rst
  cfe/trunk/include/clang/Format/Format.h


Index: cfe/trunk/docs/ClangFormatStyleOptions.rst
===
--- cfe/trunk/docs/ClangFormatStyleOptions.rst
+++ cfe/trunk/docs/ClangFormatStyleOptions.rst
@@ -629,7 +629,9 @@
   int bar();
   }
 
-  * ``bool AfterObjCDeclaration`` Wrap ObjC definitions (``@autoreleasepool``, 
interfaces, ..).
+  * ``bool AfterObjCDeclaration`` Wrap ObjC definitions (interfaces, 
implementations...).
+@autoreleasepool and @synchronized blocks are wrapped
+according to `AfterControlStatement` flag.
 
   * ``bool AfterStruct`` Wrap struct definitions.
 
@@ -1508,6 +1510,52 @@
 
 
 
+**ObjCBinPackProtocolList** (``BinPackStyle``)
+  Controls bin-packing Objective-C protocol conformance list
+  items into as few lines as possible when they go over ``ColumnLimit``.
+
+  If ``Auto`` (the default), delegates to the value in
+  ``BinPackParameters``. If that is ``true``, bin-packs Objective-C
+  protocol conformance list items into as few lines as possible
+  whenever they go over ``ColumnLimit``.
+
+  If ``Always``, always bin-packs Objective-C protocol conformance
+  list items into as few lines as possible whenever they go over
+  ``ColumnLimit``.
+
+  If ``Never``, lays out Objective-C protocol conformance list items
+  onto individual lines whenever they go over ``ColumnLimit``.
+
+
+  .. code-block:: c++
+
+ Always (or Auto, if BinPackParameters=true):
+ @interface c () <
+ c, c,
+ c, c> {
+ }
+
+ Never (or Auto, if BinPackParameters=false):
+ @interface d () <
+ d,
+ d,
+ d,
+ d> {
+ }
+
+  Possible values:
+
+  * ``BPS_Auto`` (in configuration: ``Auto``)
+Automatically determine parameter bin-packing behavior.
+
+  * ``BPS_Always`` (in configuration: ``Always``)
+Always bin-pack parameters.
+
+  * ``BPS_Never`` (in configuration: ``Never``)
+Never bin-pack parameters.
+
+
+
 **ObjCBlockIndentWidth** (``unsigned``)
   The number of characters to use for indentation of ObjC blocks.
 
@@ -1662,7 +1710,7 @@
   .. code-block:: c++
 
  true:  false:
- (int)i;vs. (int) i;
+ (int) i;   vs. (int)i;
 
 **SpaceAfterTemplateKeyword** (``bool``)
   If ``true``, a space will be inserted after the 'template' keyword.
Index: cfe/trunk/include/clang/Format/Format.h
===
--- cfe/trunk/include/clang/Format/Format.h
+++ cfe/trunk/include/clang/Format/Format.h
@@ -1506,7 +1506,7 @@
   /// \brief If ``true``, a space is inserted after C style casts.
   /// \code
   ///true:  false:
-  ///(int)i;vs. (int) i;
+  ///(int) i;   vs. (int)i;
   /// \endcode
   bool SpaceAfterCStyleCast;
 


Index: cfe/trunk/docs/ClangFormatStyleOptions.rst
===
--- cfe/trunk/docs/ClangFormatStyleOptions.rst
+++ cfe/trunk/docs/ClangFormatStyleOptions.rst
@@ -629,7 +629,9 @@
   int bar();
   }
 
-  * ``bool AfterObjCDeclaration`` Wrap ObjC definitions (``@autoreleasepool``, interfaces, ..).
+  * ``bool AfterObjCDeclaration`` Wrap ObjC definitions (interfaces, implementations...).
+@autoreleasepool and @synchronized blocks are wrapped
+according to `AfterControlStatement` flag.
 
   * ``bool AfterStruct`` Wrap struct definitions.
 
@@ -1508,6 +1510,52 @@
 
 
 
+**ObjCBinPackProtocolList** (``BinPackStyle``)
+  Controls bin-packing Objective-C protocol conformance list
+  items into as few lines as possible when they go over ``ColumnLimit``.
+
+  If ``Auto`` (the default), delegates to the value in
+  ``BinPackParameters``. If that is ``true``, bin-packs Objective-C
+  protocol conformance list items into as few lines as possible
+  whenever they go over ``ColumnLimit``.
+
+  If ``Always``, always bin-packs Objective-C protocol conformance
+  list items into as few lines as possible whenever they go over
+  ``ColumnLimit``.
+
+  If ``Never``, lays out Objective-C protocol conformance list items
+  onto individual lines whenever they go over ``ColumnLimit``.
+
+
+  .. code-block:: c++
+
+ Always (or Auto, if BinPackParameters=true):
+ @interface c () <
+ c, cc

[PATCH] D43906: [clang-format] Improve detection of Objective-C block types

2018-03-06 Thread Daniel Jasper via Phabricator via cfe-commits
djasper added inline comments.



Comment at: lib/Format/TokenAnnotator.cpp:155
+   Next->startsSequence(tok::identifier, tok::l_square,
+tok::numeric_constant, tok::r_square,
+tok::r_paren, tok::l_paren))) {

benhamilton wrote:
> djasper wrote:
> > This seems suspect. Does it have to be a numeric_constant?
> Probably not, any constexpr would do, I suspect. What's the best way to parse 
> that?
I think this is the same answer for both of your questions. If what you are 
trying to prevent "FOO(^)" to be parsed as a block, wouldn't it be enough to 
look for whether there is a "(" after the ")" or even only after "(^)", 
everything else is already correct IIUC? That would get you out of need to 
parse the specifics here, which will be hard.

Or thinking about it another way. Previously, every "(^" would be parsed as an 
ObjC block. There seems to be only a really rare corner case in which it isn't 
(macros). Thus, I'd just try to detect that corner case. Instead you are 
completely inverting the defaults (defaulting to "^" is not a block) and then 
try to exactly parse ObjC where there might be many cases and edge cases that 
you won't even think of now.


Repository:
  rC Clang

https://reviews.llvm.org/D43906



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


r326782 - [analyzer] CStringChecker.cpp: Remove the duplicated check about null dereference on dest-buffer or src-buffer.

2018-03-06 Thread Henry Wong via cfe-commits
Author: henrywong
Date: Tue Mar  6 05:38:42 2018
New Revision: 326782

URL: http://llvm.org/viewvc/llvm-project?rev=326782&view=rev
Log:
[analyzer] CStringChecker.cpp: Remove the duplicated check about null 
dereference on dest-buffer or src-buffer.

Summary: `CheckBufferAccess()` calls `CheckNonNull()`, so there are some calls 
to `CheckNonNull()` that are useless.

Reviewers: dcoughlin, NoQ, xazax.hun, cfe-commits, george.karpenkov

Reviewed By: NoQ

Subscribers: szepet, rnkovacs, MTC, a.sidorin

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

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

Modified: cfe/trunk/lib/StaticAnalyzer/Checkers/CStringChecker.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/StaticAnalyzer/Checkers/CStringChecker.cpp?rev=326782&r1=326781&r2=326782&view=diff
==
--- cfe/trunk/lib/StaticAnalyzer/Checkers/CStringChecker.cpp (original)
+++ cfe/trunk/lib/StaticAnalyzer/Checkers/CStringChecker.cpp Tue Mar  6 
05:38:42 2018
@@ -1033,21 +1033,6 @@ void CStringChecker::evalCopyCommon(Chec
   if (stateNonZeroSize) {
 state = stateNonZeroSize;
 
-// Ensure the destination is not null. If it is NULL there will be a
-// NULL pointer dereference.
-state = checkNonNull(C, state, Dest, destVal);
-if (!state)
-  return;
-
-// Get the value of the Src.
-SVal srcVal = state->getSVal(Source, LCtx);
-
-// Ensure the source is not null. If it is NULL there will be a
-// NULL pointer dereference.
-state = checkNonNull(C, state, Source, srcVal);
-if (!state)
-  return;
-
 // Ensure the accesses are valid and that the buffers do not overlap.
 const char * const writeWarning =
   "Memory copy function overflows destination buffer";
@@ -2033,12 +2018,6 @@ void CStringChecker::evalMemset(CheckerC
 return;
   }
 
-  // Ensure the memory area is not null.
-  // If it is NULL there will be a NULL pointer dereference.
-  State = checkNonNull(C, StateNonZeroSize, Mem, MemVal);
-  if (!State)
-return;
-
   State = CheckBufferAccess(C, State, Size, Mem);
   if (!State)
 return;


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


[PATCH] D44075: [analyzer] CStringChecker.cpp: Remove the duplicated check about null dereference on dest-buffer or src-buffer.

2018-03-06 Thread Phabricator via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rC326782: [analyzer] CStringChecker.cpp: Remove the duplicated 
check about null… (authored by henrywong, committed by ).

Changed prior to commit:
  https://reviews.llvm.org/D44075?vs=136936&id=137167#toc

Repository:
  rC Clang

https://reviews.llvm.org/D44075

Files:
  lib/StaticAnalyzer/Checkers/CStringChecker.cpp


Index: lib/StaticAnalyzer/Checkers/CStringChecker.cpp
===
--- lib/StaticAnalyzer/Checkers/CStringChecker.cpp
+++ lib/StaticAnalyzer/Checkers/CStringChecker.cpp
@@ -1033,21 +1033,6 @@
   if (stateNonZeroSize) {
 state = stateNonZeroSize;
 
-// Ensure the destination is not null. If it is NULL there will be a
-// NULL pointer dereference.
-state = checkNonNull(C, state, Dest, destVal);
-if (!state)
-  return;
-
-// Get the value of the Src.
-SVal srcVal = state->getSVal(Source, LCtx);
-
-// Ensure the source is not null. If it is NULL there will be a
-// NULL pointer dereference.
-state = checkNonNull(C, state, Source, srcVal);
-if (!state)
-  return;
-
 // Ensure the accesses are valid and that the buffers do not overlap.
 const char * const writeWarning =
   "Memory copy function overflows destination buffer";
@@ -2033,12 +2018,6 @@
 return;
   }
 
-  // Ensure the memory area is not null.
-  // If it is NULL there will be a NULL pointer dereference.
-  State = checkNonNull(C, StateNonZeroSize, Mem, MemVal);
-  if (!State)
-return;
-
   State = CheckBufferAccess(C, State, Size, Mem);
   if (!State)
 return;


Index: lib/StaticAnalyzer/Checkers/CStringChecker.cpp
===
--- lib/StaticAnalyzer/Checkers/CStringChecker.cpp
+++ lib/StaticAnalyzer/Checkers/CStringChecker.cpp
@@ -1033,21 +1033,6 @@
   if (stateNonZeroSize) {
 state = stateNonZeroSize;
 
-// Ensure the destination is not null. If it is NULL there will be a
-// NULL pointer dereference.
-state = checkNonNull(C, state, Dest, destVal);
-if (!state)
-  return;
-
-// Get the value of the Src.
-SVal srcVal = state->getSVal(Source, LCtx);
-
-// Ensure the source is not null. If it is NULL there will be a
-// NULL pointer dereference.
-state = checkNonNull(C, state, Source, srcVal);
-if (!state)
-  return;
-
 // Ensure the accesses are valid and that the buffers do not overlap.
 const char * const writeWarning =
   "Memory copy function overflows destination buffer";
@@ -2033,12 +2018,6 @@
 return;
   }
 
-  // Ensure the memory area is not null.
-  // If it is NULL there will be a NULL pointer dereference.
-  State = checkNonNull(C, StateNonZeroSize, Mem, MemVal);
-  if (!State)
-return;
-
   State = CheckBufferAccess(C, State, Size, Mem);
   if (!State)
 return;
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D44143: Create properly seeded random generator check

2018-03-06 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman added a comment.

Thank you for working on this check!

Do you think it might be possible to also add a check for `cert-msc32-c` that 
handles the C side of things, and use a common check to implement both? C won't 
ever have the C++'isms, but C++ can certainly abuse `std::srand()` so it seems 
like there's at least some overlap.




Comment at: clang-tidy/cert/CERTTidyModule.cpp:43
+CheckFactories.registerCheck(
+"cert-properly-seeded-random-generator");
 CheckFactories.registerCheck("cert-dcl50-cpp");

The name should be `cert-msc51-cpp` (and categorized with the other msc checks).



Comment at: clang-tidy/cert/ProperlySeededRandomGeneratorCheck.cpp:22-24
+  hasAnyName("linear_congruential_engine", "mersenne_twister_engine",
+ "subtract_with_carry_engine", "discard_block_engine",
+ "independent_bits_engine", "shuffle_order_engine"));

These should be using fully-qualified names, like 
`::std::mersenne_twister_engine`. Also, I think this list should be 
configurable so that users can add their own engines if needed.



Comment at: clang-tidy/cert/ProperlySeededRandomGeneratorCheck.cpp:66
+
+  template
+void ProperlySeededRandomGeneratorCheck::checkSeed(

Formatting looks off here.



Comment at: clang-tidy/cert/ProperlySeededRandomGeneratorCheck.cpp:71
+diag(Func->getExprLoc(), "random number generator must be seeded with "
+ "a random_device instead of default argument");
+return;

The diagnostics here aren't quite correct -- a `random_device` isn't 
*required*. For instance, it's also fine to open up /dev/random and read a 
seed's worth of bytes. I think a better phrasing might be: `random number 
generator seeded with a default argument will generate a predictable sequence 
of values`.



Comment at: clang-tidy/cert/ProperlySeededRandomGeneratorCheck.cpp:77-78
+  if (Func->getArg(0)->EvaluateAsInt(Value, *Result.Context)) {
+diag(Func->getExprLoc(), "random number generator must be seeded with "
+ "a random_device instead of a constant");
+return;

I'd probably use similar wording here: `random number generator seeded with a 
constant value will generate a predictable sequence of values`.

You can combine these diagnostics and use %select{}0 to choose between the 
variants.



Comment at: clang-tidy/cert/ProperlySeededRandomGeneratorCheck.h:33-34
+  template
+  void checkSeed(const ast_matchers::MatchFinder::MatchResult &Result,
+ const T *Func);
+};

It seems like this should be a private function rather than public.



Comment at: docs/clang-tidy/checks/cert-properly-seeded-random-generator.rst:3
+
+cert-properly-seeded-random-generator
+=

When renaming the check, be sure to update titles, file names, etc.



Comment at: docs/clang-tidy/checks/cert-properly-seeded-random-generator.rst:7
+This check flags all pseudo-random number engines and engine adaptors
+instantiations when it initialized or seeded with default argument or constant
+expression. Pseudo-random number engines seeded with a predictable value may

Remove "it".



Comment at: 
docs/clang-tidy/checks/cert-properly-seeded-random-generator.rst:22-23
+
+std::time_t t;
+engine1.seed(std::time(&t)); // Bad, system time might be controlled by 
user
+

There's no test case for this test, and I don't think this code would generate 
a diagnostic in the current check form. This might require a 
(user-configurable) list of disallowed sources of seed values. For instance, it 
should diagnose when called with a `time_t` value or a direct call to a time 
function, but it need not diagnose if the value is somehow obscured. e.g.,
```
unsigned get_seed() { std::time_t t; return std::time(&t); }
engine1.seed(get_seed()); // No diagnostic required
```


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D44143



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


r326792 - [clang-format] fix handling of consecutive unary operators

2018-03-06 Thread Krasimir Georgiev via cfe-commits
Author: krasimir
Date: Tue Mar  6 05:56:28 2018
New Revision: 326792

URL: http://llvm.org/viewvc/llvm-project?rev=326792&view=rev
Log:
[clang-format] fix handling of consecutive unary operators

Summary:
Code that used to be formatted as `if (! + object) {` is now formatted as `if 
(!+object) {`
(we have a particular object in our codebase where unary `operator+` is 
overloaded to return the underlying value, which in this case is a `bool`)

We still preserve the TypeScript behavior where `!` is a trailing non-null 
operator. (This is already tested by an existing unit test in 
`FormatTestJS.cpp`)

It doesn't appear like handling of consecutive unary operators are tested in 
general, so I added another test for completeness

Patch contributed by @kevinl!

Reviewers: krasimir

Reviewed By: krasimir

Subscribers: klimek, cfe-commits

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

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

Modified: cfe/trunk/lib/Format/TokenAnnotator.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Format/TokenAnnotator.cpp?rev=326792&r1=326791&r2=326792&view=diff
==
--- cfe/trunk/lib/Format/TokenAnnotator.cpp (original)
+++ cfe/trunk/lib/Format/TokenAnnotator.cpp Tue Mar  6 05:56:28 2018
@@ -1531,10 +1531,8 @@ private:
 if (!PrevToken)
   return TT_UnaryOperator;
 
-if (PrevToken->isOneOf(TT_CastRParen, TT_UnaryOperator) &&
-!PrevToken->is(tok::exclaim))
-  // There aren't any trailing unary operators except for TypeScript's
-  // non-null operator (!). Thus, this must be squence of leading 
operators.
+if (PrevToken->isOneOf(TT_CastRParen, TT_UnaryOperator))
+  // This must be a sequence of leading unary operators.
   return TT_UnaryOperator;
 
 // Use heuristics to recognize unary operators.

Modified: cfe/trunk/unittests/Format/FormatTest.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/unittests/Format/FormatTest.cpp?rev=326792&r1=326791&r2=326792&view=diff
==
--- cfe/trunk/unittests/Format/FormatTest.cpp (original)
+++ cfe/trunk/unittests/Format/FormatTest.cpp Tue Mar  6 05:56:28 2018
@@ -5655,6 +5655,8 @@ TEST_F(FormatTest, UnderstandsUnaryOpera
   verifyFormat("(a->f())++;");
   verifyFormat("a[42]++;");
   verifyFormat("if (!(a->f())) {\n}");
+  verifyFormat("if (!+i) {\n}");
+  verifyFormat("~&a;");
 
   verifyFormat("a-- > b;");
   verifyFormat("b ? -a : c;");

Modified: cfe/trunk/unittests/Format/FormatTestJS.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/unittests/Format/FormatTestJS.cpp?rev=326792&r1=326791&r2=326792&view=diff
==
--- cfe/trunk/unittests/Format/FormatTestJS.cpp (original)
+++ cfe/trunk/unittests/Format/FormatTestJS.cpp Tue Mar  6 05:56:28 2018
@@ -2133,6 +2133,7 @@ TEST_F(FormatTestJS, NonNullAssertionOpe
   verifyFormat("let x = foo!.bar();\n");
   verifyFormat("let x = foo ? bar! : baz;\n");
   verifyFormat("let x = !foo;\n");
+  verifyFormat("if (!+a) {\n}");
   verifyFormat("let x = foo[0]!;\n");
   verifyFormat("let x = (foo)!;\n");
   verifyFormat("let x = x(foo!);\n");


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


[PATCH] D43312: [clang-format] fix handling of consecutive unary operators

2018-03-06 Thread Krasimir Georgiev via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rL326792: [clang-format] fix handling of consecutive unary 
operators (authored by krasimir, committed by ).
Herald added a subscriber: llvm-commits.

Changed prior to commit:
  https://reviews.llvm.org/D43312?vs=134511&id=137179#toc

Repository:
  rL LLVM

https://reviews.llvm.org/D43312

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


Index: cfe/trunk/lib/Format/TokenAnnotator.cpp
===
--- cfe/trunk/lib/Format/TokenAnnotator.cpp
+++ cfe/trunk/lib/Format/TokenAnnotator.cpp
@@ -1531,10 +1531,8 @@
 if (!PrevToken)
   return TT_UnaryOperator;
 
-if (PrevToken->isOneOf(TT_CastRParen, TT_UnaryOperator) &&
-!PrevToken->is(tok::exclaim))
-  // There aren't any trailing unary operators except for TypeScript's
-  // non-null operator (!). Thus, this must be squence of leading 
operators.
+if (PrevToken->isOneOf(TT_CastRParen, TT_UnaryOperator))
+  // This must be a sequence of leading unary operators.
   return TT_UnaryOperator;
 
 // Use heuristics to recognize unary operators.
Index: cfe/trunk/unittests/Format/FormatTest.cpp
===
--- cfe/trunk/unittests/Format/FormatTest.cpp
+++ cfe/trunk/unittests/Format/FormatTest.cpp
@@ -5655,6 +5655,8 @@
   verifyFormat("(a->f())++;");
   verifyFormat("a[42]++;");
   verifyFormat("if (!(a->f())) {\n}");
+  verifyFormat("if (!+i) {\n}");
+  verifyFormat("~&a;");
 
   verifyFormat("a-- > b;");
   verifyFormat("b ? -a : c;");
Index: cfe/trunk/unittests/Format/FormatTestJS.cpp
===
--- cfe/trunk/unittests/Format/FormatTestJS.cpp
+++ cfe/trunk/unittests/Format/FormatTestJS.cpp
@@ -2133,6 +2133,7 @@
   verifyFormat("let x = foo!.bar();\n");
   verifyFormat("let x = foo ? bar! : baz;\n");
   verifyFormat("let x = !foo;\n");
+  verifyFormat("if (!+a) {\n}");
   verifyFormat("let x = foo[0]!;\n");
   verifyFormat("let x = (foo)!;\n");
   verifyFormat("let x = x(foo!);\n");


Index: cfe/trunk/lib/Format/TokenAnnotator.cpp
===
--- cfe/trunk/lib/Format/TokenAnnotator.cpp
+++ cfe/trunk/lib/Format/TokenAnnotator.cpp
@@ -1531,10 +1531,8 @@
 if (!PrevToken)
   return TT_UnaryOperator;
 
-if (PrevToken->isOneOf(TT_CastRParen, TT_UnaryOperator) &&
-!PrevToken->is(tok::exclaim))
-  // There aren't any trailing unary operators except for TypeScript's
-  // non-null operator (!). Thus, this must be squence of leading operators.
+if (PrevToken->isOneOf(TT_CastRParen, TT_UnaryOperator))
+  // This must be a sequence of leading unary operators.
   return TT_UnaryOperator;
 
 // Use heuristics to recognize unary operators.
Index: cfe/trunk/unittests/Format/FormatTest.cpp
===
--- cfe/trunk/unittests/Format/FormatTest.cpp
+++ cfe/trunk/unittests/Format/FormatTest.cpp
@@ -5655,6 +5655,8 @@
   verifyFormat("(a->f())++;");
   verifyFormat("a[42]++;");
   verifyFormat("if (!(a->f())) {\n}");
+  verifyFormat("if (!+i) {\n}");
+  verifyFormat("~&a;");
 
   verifyFormat("a-- > b;");
   verifyFormat("b ? -a : c;");
Index: cfe/trunk/unittests/Format/FormatTestJS.cpp
===
--- cfe/trunk/unittests/Format/FormatTestJS.cpp
+++ cfe/trunk/unittests/Format/FormatTestJS.cpp
@@ -2133,6 +2133,7 @@
   verifyFormat("let x = foo!.bar();\n");
   verifyFormat("let x = foo ? bar! : baz;\n");
   verifyFormat("let x = !foo;\n");
+  verifyFormat("if (!+a) {\n}");
   verifyFormat("let x = foo[0]!;\n");
   verifyFormat("let x = (foo)!;\n");
   verifyFormat("let x = x(foo!);\n");
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[libcxxabi] r326796 - [demangler] Modernize parse_unresolved_name.

2018-03-06 Thread Erik Pilkington via cfe-commits
Author: epilk
Date: Tue Mar  6 06:21:08 2018
New Revision: 326796

URL: http://llvm.org/viewvc/llvm-project?rev=326796&view=rev
Log:
[demangler] Modernize parse_unresolved_name.

Modified:
libcxxabi/trunk/src/cxa_demangle.cpp

Modified: libcxxabi/trunk/src/cxa_demangle.cpp
URL: 
http://llvm.org/viewvc/llvm-project/libcxxabi/trunk/src/cxa_demangle.cpp?rev=326796&r1=326795&r2=326796&view=diff
==
--- libcxxabi/trunk/src/cxa_demangle.cpp (original)
+++ libcxxabi/trunk/src/cxa_demangle.cpp Tue Mar  6 06:21:08 2018
@@ -2102,6 +2102,13 @@ struct Db {
 
   Node *parseAbiTags(Node *N);
 
+  /// Parse the  production.
+  Node *parseUnresolvedName();
+  Node *parseSimpleId();
+  Node *parseBaseUnresolvedName();
+  Node *parseUnresolvedType();
+  Node *parseDestructorName();
+
   // FIXME: remove this when all the parse_* functions have been rewritten.
   template 
   Node *legacyParse() {
@@ -2147,46 +2154,6 @@ const char *parse_type(const char *first
   return db.First;
 }
 
-const char *parse_decltype(const char *first, const char *last, Db &db) {
-  db.First = first;
-  db.Last = last;
-  Node *R = db.parseDecltype();
-  if (R == nullptr)
-return first;
-  db.Names.push_back(R);
-  return db.First;
-}
-
-const char *parse_source_name(const char *first, const char *last, Db &db) {
-  db.First = first;
-  db.Last = last;
-  Node *R = db.parseSourceName(/*NameState=*/nullptr);
-  if (R == nullptr)
-return first;
-  db.Names.push_back(R);
-  return db.First;
-}
-
-const char *parse_operator_name(const char *first, const char *last, Db &db) {
-  db.First = first;
-  db.Last = last;
-  Node *R = db.parseOperatorName(/*NameState=*/nullptr);
-  if (R == nullptr)
-return first;
-  db.Names.push_back(R);
-  return db.First;
-}
-
-const char *parse_unqualified_name(const char *first, const char *last, Db 
&db) {
-  db.First = first;
-  db.Last = last;
-  Node *R = db.parseUnqualifiedName(/*NameState=*/nullptr);
-  if (R == nullptr)
-return first;
-  db.Names.push_back(R);
-  return db.First;
-}
-
 const char *parse_encoding(const char *first, const char *last, Db &db) {
   db.First = first;
   db.Last = last;
@@ -2200,7 +2167,6 @@ const char *parse_encoding(const char *f
 const char* parse_discriminator(const char* first, const char* last);
 const char *parse_template_args(const char *first, const char *last, Db &db);
 const char *parse_template_param(const char *, const char *, Db &);
-const char *parse_unresolved_name(const char *, const char *, Db &);
 const char *parse_substitution(const char *, const char *, Db &);
 
 
@@ -2797,6 +2763,172 @@ Node *Db::parseNestedName(NameState *Sta
   return SoFar;
 }
 
+//  ::=  [  ]
+Node *Db::parseSimpleId() {
+  Node *SN = parseSourceName(/*NameState=*/nullptr);
+  if (SN == nullptr)
+return nullptr;
+  if (look() == 'I') {
+Node *TA = legacyParse();
+if (TA == nullptr)
+  return nullptr;
+return make(SN, TA);
+  }
+  return SN;
+}
+
+//  ::=   # e.g., ~T or ~decltype(f())
+//   ::= # e.g., ~A<2*N>
+Node *Db::parseDestructorName() {
+  Node *Result;
+  if (std::isdigit(look()))
+Result = parseSimpleId();
+  else
+Result = parseUnresolvedType();
+  if (Result == nullptr)
+return nullptr;
+  return make(Result);
+}
+
+//  ::= 
+//   ::= 
+//   ::= 
+Node *Db::parseUnresolvedType() {
+  if (look() == 'T') {
+Node *TP = legacyParse();
+if (TP == nullptr)
+  return nullptr;
+Subs.push_back(TP);
+return TP;
+  }
+  if (look() == 'D') {
+Node *DT = parseDecltype();
+if (DT == nullptr)
+  return nullptr;
+Subs.push_back(DT);
+return DT;
+  }
+  return legacyParse();
+}
+
+//  ::= # 
unresolved name
+//  extension ::= # 
unresolved operator-function-id
+//  extension ::=  # 
unresolved operator template-id
+//::= on  # 
unresolved operator-function-id
+//::= on   # 
unresolved operator template-id
+//::= dn# 
destructor or pseudo-destructor;
+// # 
e.g. ~X or ~X
+Node *Db::parseBaseUnresolvedName() {
+  if (std::isdigit(look()))
+return parseSimpleId();
+
+  if (consumeIf("dn"))
+return parseDestructorName();
+
+  consumeIf("on");
+
+  Node *Oper = parseOperatorName(/*NameState=*/nullptr);
+  if (Oper == nullptr)
+return nullptr;
+  if (look() == 'I') {
+Node *TA = legacyParse();
+if (TA == nullptr)
+  return nullptr;
+return make(Oper, TA);
+  }
+  return Oper;
+}
+
+// 
+//  extension::= srN  [] 
* E 
+//   ::= [gs]  # x 
or (with "gs") ::x
+//   ::= [gs] sr + E 
  
+//   

[libcxxabi] r326797 - [demangler] Modernize the rest of the demangler.

2018-03-06 Thread Erik Pilkington via cfe-commits
Author: epilk
Date: Tue Mar  6 06:21:10 2018
New Revision: 326797

URL: http://llvm.org/viewvc/llvm-project?rev=326797&view=rev
Log:
[demangler] Modernize the rest of the demangler.

Modified:
libcxxabi/trunk/src/cxa_demangle.cpp
libcxxabi/trunk/test/test_demangle.pass.cpp

Modified: libcxxabi/trunk/src/cxa_demangle.cpp
URL: 
http://llvm.org/viewvc/llvm-project/libcxxabi/trunk/src/cxa_demangle.cpp?rev=326797&r1=326796&r2=326797&view=diff
==
--- libcxxabi/trunk/src/cxa_demangle.cpp (original)
+++ libcxxabi/trunk/src/cxa_demangle.cpp Tue Mar  6 06:21:10 2018
@@ -2002,6 +2002,8 @@ struct Db {
 
   BumpPointerAllocator ASTAllocator;
 
+  Db(const char *First_, const char *Last_) : First(First_), Last(Last_) {}
+
   template  T *make(Args &&... args) {
 return new (ASTAllocator.allocate(sizeof(T)))
 T(std::forward(args)...);
@@ -2054,6 +2056,12 @@ struct Db {
   bool parsePositiveInteger(size_t *Out);
   StringView parseBareSourceName();
 
+  bool parseSeqId(size_t *Out);
+  Node *parseSubstitution();
+  Node *parseTemplateParam();
+  Node *parseTemplateArgs();
+  Node *parseTemplateArg();
+
   /// Parse the  production.
   Node *parseExpr();
   Node *parsePrefixExpr(StringView Kind);
@@ -2109,66 +2117,11 @@ struct Db {
   Node *parseUnresolvedType();
   Node *parseDestructorName();
 
-  // FIXME: remove this when all the parse_* functions have been rewritten.
-  template 
-  Node *legacyParse() {
-size_t BeforeType = Names.size();
-const char *OrigFirst = First;
-const char *T = parse_fn(First, Last, *this);
-if (T == OrigFirst || BeforeType + 1 != Names.size())
-  return nullptr;
-First = T;
-Node *R = Names.back();
-Names.pop_back();
-return R;
-  }
+  /// Top-level entry point into the parser.
+  Node *parse();
 };
 
-const char *parse_expression(const char *first, const char *last, Db &db) {
-  db.First = first;
-  db.Last = last;
-  Node *R = db.parseExpr();
-  if (R == nullptr)
-return first;
-  db.Names.push_back(R);
-  return db.First;
-}
-
-const char *parse_expr_primary(const char *first, const char *last, Db &db) {
-  db.First = first;
-  db.Last = last;
-  Node *R = db.parseExprPrimary();
-  if (R == nullptr)
-return first;
-  db.Names.push_back(R);
-  return db.First;
-}
-
-const char *parse_type(const char *first, const char *last, Db &db) {
-  db.First = first;
-  db.Last = last;
-  Node *R = db.parseType();
-  if (R == nullptr)
-return first;
-  db.Names.push_back(R);
-  return db.First;
-}
-
-const char *parse_encoding(const char *first, const char *last, Db &db) {
-  db.First = first;
-  db.Last = last;
-  Node *R = db.parseEncoding();
-  if (R == nullptr)
-return first;
-  db.Names.push_back(R);
-  return db.First;
-}
-
 const char* parse_discriminator(const char* first, const char* last);
-const char *parse_template_args(const char *first, const char *last, Db &db);
-const char *parse_template_param(const char *, const char *, Db &);
-const char *parse_substitution(const char *, const char *, Db &);
-
 
 //  ::=  // N
 //::=  # See Scope Encoding below  // Z
@@ -2187,10 +2140,12 @@ Node *Db::parseName(NameState *State) {
 
   //::=  
   if (look() == 'S' && look(1) != 't') {
-Node *S = legacyParse();
+Node *S = parseSubstitution();
+if (S == nullptr)
+  return nullptr;
 if (look() != 'I')
   return nullptr;
-Node *TA = legacyParse();
+Node *TA = parseTemplateArgs();
 if (TA == nullptr)
   return nullptr;
 if (State) State->EndsWithTemplateArgs = true;
@@ -2203,7 +2158,7 @@ Node *Db::parseName(NameState *State) {
   //::=  
   if (look() == 'I') {
 Subs.push_back(N);
-Node *TA = legacyParse();
+Node *TA = parseTemplateArgs();
 if (TA == nullptr)
   return nullptr;
 if (State) State->EndsWithTemplateArgs = true;
@@ -2693,7 +2648,7 @@ Node *Db::parseNestedName(NameState *Sta
 
 //  ::= 
 if (look() == 'T') {
-  Node *TP = legacyParse();
+  Node *TP = parseTemplateParam();
   if (TP == nullptr)
 return nullptr;
   PushComponent(TP);
@@ -2703,7 +2658,7 @@ Node *Db::parseNestedName(NameState *Sta
 
 //  ::=  
 if (look() == 'I') {
-  Node *TA = legacyParse();
+  Node *TA = parseTemplateArgs();
   if (TA == nullptr || SoFar == nullptr)
 return nullptr;
   SoFar = make(SoFar, TA);
@@ -2724,7 +2679,7 @@ Node *Db::parseNestedName(NameState *Sta
 
 //  ::= 
 if (look() == 'S' && look(1) != 't') {
-  Node *S = legacyParse();
+  Node *S = parseSubstitution();
   if (S == nullptr)
 return nullptr;
   PushComponent(S);
@@ -2769,7 +2724,7 @@ Node *Db::parseSimpleId() {
   if (SN == nullptr)
 return nullptr;
   if (look() == 'I') {
-Node *TA = legacyParse();
+Node *TA = parseTemplateArgs();
 if (TA == nullptr)
   return nullptr;
 

[PATCH] D44141: [clang-format] Use NestedBlockIndent as a 0 column in formatted raw strings

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

LGTM, probably want to wait for djasper's opinion.


Repository:
  rC Clang

https://reviews.llvm.org/D44141



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


[clang-tools-extra] r326798 - [clangd] Address missed comments from D44003

2018-03-06 Thread Sam McCall via cfe-commits
Author: sammccall
Date: Tue Mar  6 06:30:07 2018
New Revision: 326798

URL: http://llvm.org/viewvc/llvm-project?rev=326798&view=rev
Log:
[clangd] Address missed comments from D44003

Modified:
clang-tools-extra/trunk/unittests/clangd/FuzzyMatchTests.cpp

Modified: clang-tools-extra/trunk/unittests/clangd/FuzzyMatchTests.cpp
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/unittests/clangd/FuzzyMatchTests.cpp?rev=326798&r1=326797&r2=326798&view=diff
==
--- clang-tools-extra/trunk/unittests/clangd/FuzzyMatchTests.cpp (original)
+++ clang-tools-extra/trunk/unittests/clangd/FuzzyMatchTests.cpp Tue Mar  6 
06:30:07 2018
@@ -30,14 +30,16 @@ struct ExpectedMatch {
   bool accepts(StringRef ActualAnnotated) const {
 return !Annotated || ActualAnnotated == *Annotated;
   }
-  std::string Word;
 
   friend raw_ostream &operator<<(raw_ostream &OS, const ExpectedMatch &M) {
-return OS << "'" << M.Word;
+OS << "'" << M.Word;
 if (M.Annotated)
   OS << "' as " << *M.Annotated;
+return OS;
   }
 
+  std::string Word;
+
 private:
   Optional Annotated;
 };


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


[PATCH] D43197: [OpenMP] Add flag for linking runtime bitcode library

2018-03-06 Thread Alexey Bataev via Phabricator via cfe-commits
ABataev added inline comments.



Comment at: lib/Driver/ToolChains/Cuda.cpp:535
+SmallVector LibraryPaths;
+if (char *env = ::getenv("LIBRARY_PATH")) {
+  StringRef CompilerPath = env;

1. `char *`->`const char *`
2. `::getenv`->`llvm::Process::GetEnv`



Comment at: lib/Driver/ToolChains/Cuda.cpp:539
+std::pair Split =
+CompilerPath.split(llvm::sys::EnvPathSeparator);
+LibraryPaths.push_back(Split.first);

Use `llvm::SplitString` instead



Comment at: lib/Driver/ToolChains/Cuda.cpp:548
+bool FoundBCLibrary = false;
+for (std::string LibraryPath : LibraryPaths) {
+  SmallString<128> LibOmpTargetFile(LibraryPath);

`const std::string &`


Repository:
  rC Clang

https://reviews.llvm.org/D43197



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


[clang-tools-extra] r326799 - [clang-tidy] Fix one corner case in make-unique check.

2018-03-06 Thread Haojian Wu via cfe-commits
Author: hokein
Date: Tue Mar  6 06:34:35 2018
New Revision: 326799

URL: http://llvm.org/viewvc/llvm-project?rev=326799&view=rev
Log:
[clang-tidy] Fix one corner case in make-unique check.

Summary:
Previously, we tried to cover all "std::initializer_list" implicit conversion
cases in the code, but there are some corner cases that not covered (see
newly-added test in the patch).

Sipping all implicit AST nodes is a better way to filter out all these cases.

Reviewers: ilya-biryukov

Subscribers: klimek, xazax.hun, cfe-commits

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

Modified:
clang-tools-extra/trunk/clang-tidy/modernize/MakeSmartPtrCheck.cpp
clang-tools-extra/trunk/test/clang-tidy/modernize-make-unique.cpp

Modified: clang-tools-extra/trunk/clang-tidy/modernize/MakeSmartPtrCheck.cpp
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clang-tidy/modernize/MakeSmartPtrCheck.cpp?rev=326799&r1=326798&r2=326799&view=diff
==
--- clang-tools-extra/trunk/clang-tidy/modernize/MakeSmartPtrCheck.cpp 
(original)
+++ clang-tools-extra/trunk/clang-tidy/modernize/MakeSmartPtrCheck.cpp Tue Mar  
6 06:34:35 2018
@@ -295,16 +295,8 @@ bool MakeSmartPtrCheck::replaceNew(Diagn
   }
   return false;
 };
-// Check the implicit conversion from the std::initializer_list type to
-// a class type.
-if (IsStdInitListInitConstructExpr(Arg))
+if (IsStdInitListInitConstructExpr(Arg->IgnoreImplicit()))
   return false;
-// The Arg can be a CXXBindTemporaryExpr, checking its underlying
-// construct expr.
-if (const auto * CTE = dyn_cast(Arg)) {
-  if (IsStdInitListInitConstructExpr(CTE->getSubExpr()))
-return false;
-}
   }
 }
 if (ArraySizeExpr.empty()) {

Modified: clang-tools-extra/trunk/test/clang-tidy/modernize-make-unique.cpp
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/test/clang-tidy/modernize-make-unique.cpp?rev=326799&r1=326798&r2=326799&view=diff
==
--- clang-tools-extra/trunk/test/clang-tidy/modernize-make-unique.cpp (original)
+++ clang-tools-extra/trunk/test/clang-tidy/modernize-make-unique.cpp Tue Mar  
6 06:34:35 2018
@@ -50,6 +50,7 @@ struct G {
 
 struct H {
   H(std::vector);
+  H(std::vector &, double);
   H(MyVector, int);
 };
 
@@ -344,6 +345,13 @@ void initialization(int T, Base b) {
   // CHECK-MESSAGES: :[[@LINE-1]]:7: warning: use std::make_unique instead
   // CHECK-FIXES: PH2.reset(new H({1, 2, 3}, 1));
 
+  std::unique_ptr PH3 = std::unique_ptr(new H({1, 2, 3}, 1.0));
+  // CHECK-MESSAGES: :[[@LINE-1]]:28: warning: use std::make_unique instead
+  // CHECK-FIXES: std::unique_ptr PH3 = std::unique_ptr(new H({1, 2, 3}, 
1.0));
+  PH3.reset(new H({1, 2, 3}, 1.0));
+  // CHECK-MESSAGES: :[[@LINE-1]]:7: warning: use std::make_unique instead
+  // CHECK-FIXES: PH3.reset(new H({1, 2, 3}, 1.0));
+
   std::unique_ptr PI1 = std::unique_ptr(new I(G({1, 2, 3})));
   // CHECK-MESSAGES: :[[@LINE-1]]:28: warning: use std::make_unique instead
   // CHECK-FIXES: std::unique_ptr PI1 = std::make_unique(G({1, 2, 3}));


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


[PATCH] D44137: [clang-tidy] Fix one corner case in make-unique check.

2018-03-06 Thread Haojian Wu via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rCTE326799: [clang-tidy] Fix one corner case in make-unique 
check. (authored by hokein, committed by ).

Changed prior to commit:
  https://reviews.llvm.org/D44137?vs=137136&id=137188#toc

Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D44137

Files:
  clang-tidy/modernize/MakeSmartPtrCheck.cpp
  test/clang-tidy/modernize-make-unique.cpp


Index: clang-tidy/modernize/MakeSmartPtrCheck.cpp
===
--- clang-tidy/modernize/MakeSmartPtrCheck.cpp
+++ clang-tidy/modernize/MakeSmartPtrCheck.cpp
@@ -295,16 +295,8 @@
   }
   return false;
 };
-// Check the implicit conversion from the std::initializer_list type to
-// a class type.
-if (IsStdInitListInitConstructExpr(Arg))
+if (IsStdInitListInitConstructExpr(Arg->IgnoreImplicit()))
   return false;
-// The Arg can be a CXXBindTemporaryExpr, checking its underlying
-// construct expr.
-if (const auto * CTE = dyn_cast(Arg)) {
-  if (IsStdInitListInitConstructExpr(CTE->getSubExpr()))
-return false;
-}
   }
 }
 if (ArraySizeExpr.empty()) {
Index: test/clang-tidy/modernize-make-unique.cpp
===
--- test/clang-tidy/modernize-make-unique.cpp
+++ test/clang-tidy/modernize-make-unique.cpp
@@ -50,6 +50,7 @@
 
 struct H {
   H(std::vector);
+  H(std::vector &, double);
   H(MyVector, int);
 };
 
@@ -344,6 +345,13 @@
   // CHECK-MESSAGES: :[[@LINE-1]]:7: warning: use std::make_unique instead
   // CHECK-FIXES: PH2.reset(new H({1, 2, 3}, 1));
 
+  std::unique_ptr PH3 = std::unique_ptr(new H({1, 2, 3}, 1.0));
+  // CHECK-MESSAGES: :[[@LINE-1]]:28: warning: use std::make_unique instead
+  // CHECK-FIXES: std::unique_ptr PH3 = std::unique_ptr(new H({1, 2, 3}, 
1.0));
+  PH3.reset(new H({1, 2, 3}, 1.0));
+  // CHECK-MESSAGES: :[[@LINE-1]]:7: warning: use std::make_unique instead
+  // CHECK-FIXES: PH3.reset(new H({1, 2, 3}, 1.0));
+
   std::unique_ptr PI1 = std::unique_ptr(new I(G({1, 2, 3})));
   // CHECK-MESSAGES: :[[@LINE-1]]:28: warning: use std::make_unique instead
   // CHECK-FIXES: std::unique_ptr PI1 = std::make_unique(G({1, 2, 3}));


Index: clang-tidy/modernize/MakeSmartPtrCheck.cpp
===
--- clang-tidy/modernize/MakeSmartPtrCheck.cpp
+++ clang-tidy/modernize/MakeSmartPtrCheck.cpp
@@ -295,16 +295,8 @@
   }
   return false;
 };
-// Check the implicit conversion from the std::initializer_list type to
-// a class type.
-if (IsStdInitListInitConstructExpr(Arg))
+if (IsStdInitListInitConstructExpr(Arg->IgnoreImplicit()))
   return false;
-// The Arg can be a CXXBindTemporaryExpr, checking its underlying
-// construct expr.
-if (const auto * CTE = dyn_cast(Arg)) {
-  if (IsStdInitListInitConstructExpr(CTE->getSubExpr()))
-return false;
-}
   }
 }
 if (ArraySizeExpr.empty()) {
Index: test/clang-tidy/modernize-make-unique.cpp
===
--- test/clang-tidy/modernize-make-unique.cpp
+++ test/clang-tidy/modernize-make-unique.cpp
@@ -50,6 +50,7 @@
 
 struct H {
   H(std::vector);
+  H(std::vector &, double);
   H(MyVector, int);
 };
 
@@ -344,6 +345,13 @@
   // CHECK-MESSAGES: :[[@LINE-1]]:7: warning: use std::make_unique instead
   // CHECK-FIXES: PH2.reset(new H({1, 2, 3}, 1));
 
+  std::unique_ptr PH3 = std::unique_ptr(new H({1, 2, 3}, 1.0));
+  // CHECK-MESSAGES: :[[@LINE-1]]:28: warning: use std::make_unique instead
+  // CHECK-FIXES: std::unique_ptr PH3 = std::unique_ptr(new H({1, 2, 3}, 1.0));
+  PH3.reset(new H({1, 2, 3}, 1.0));
+  // CHECK-MESSAGES: :[[@LINE-1]]:7: warning: use std::make_unique instead
+  // CHECK-FIXES: PH3.reset(new H({1, 2, 3}, 1.0));
+
   std::unique_ptr PI1 = std::unique_ptr(new I(G({1, 2, 3})));
   // CHECK-MESSAGES: :[[@LINE-1]]:28: warning: use std::make_unique instead
   // CHECK-FIXES: std::unique_ptr PI1 = std::make_unique(G({1, 2, 3}));
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D44142: [clangd] Revamp handling of diagnostics.

2018-03-06 Thread Ilya Biryukov via Phabricator via cfe-commits
ilya-biryukov added inline comments.



Comment at: clangd/Diagnostics.h:28
+/// DiagList.
+struct PersistentDiag {
+  llvm::StringRef Message;

This could probably use a better name


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D44142



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


[PATCH] D43650: [ARM] Add ARMv8.2-A FP16 vector intrinsics

2018-03-06 Thread Sjoerd Meijer via Phabricator via cfe-commits
SjoerdMeijer accepted this revision.
SjoerdMeijer added a comment.
This revision is now accepted and ready to land.

Look like sensible cleanups/fixes/additions to me.

We were struggling whether to pass an i16 or f16 type, which can both be 
illegal types.
Therefore, it perhaps doesn't really matter much which one we use. At the time 
we
were having these problems, the ARM backend wasn't ready for f16s, but a lot 
has changed
since then. So I think we can get this in, review where we are, and iterate on 
this
if necessary.


https://reviews.llvm.org/D43650



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


[PATCH] D43821: [SemaCXX] _Pragma("clang optimize off") not affecting lambda.

2018-03-06 Thread Carlos Alberto Enciso via Phabricator via cfe-commits
CarlosAlbertoEnciso added a comment.

Ping.

Thanks


Repository:
  rC Clang

https://reviews.llvm.org/D43821



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


[PATCH] D43821: [SemaCXX] _Pragma("clang optimize off") not affecting lambda.

2018-03-06 Thread Erich Keane via Phabricator via cfe-commits
erichkeane added inline comments.



Comment at: lib/Sema/SemaDecl.cpp:12598
+// have to apply optnone due to a pragma.
+AddRangeBasedOptnone(FD);
+

Should thi sonly happen if this is a definition?  Additionally, does this 
negate the need for the other call to this in ActOnFunctionDeclarator?


Repository:
  rC Clang

https://reviews.llvm.org/D43821



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


[libcxx] r326801 - Implement P0767R1 - Deprecate POD

2018-03-06 Thread Marshall Clow via cfe-commits
Author: marshall
Date: Tue Mar  6 07:01:19 2018
New Revision: 326801

URL: http://llvm.org/viewvc/llvm-project?rev=326801&view=rev
Log:
Implement P0767R1 - Deprecate POD

Modified:
libcxx/trunk/test/std/language.support/support.types/byte.pass.cpp
libcxx/trunk/test/std/language.support/support.types/max_align_t.pass.cpp

libcxx/trunk/test/std/utilities/meta/meta.trans/meta.trans.other/aligned_storage.pass.cpp
libcxx/trunk/www/cxx2a_status.html

Modified: libcxx/trunk/test/std/language.support/support.types/byte.pass.cpp
URL: 
http://llvm.org/viewvc/llvm-project/libcxx/trunk/test/std/language.support/support.types/byte.pass.cpp?rev=326801&r1=326800&r2=326801&view=diff
==
--- libcxx/trunk/test/std/language.support/support.types/byte.pass.cpp 
(original)
+++ libcxx/trunk/test/std/language.support/support.types/byte.pass.cpp Tue Mar  
6 07:01:19 2018
@@ -9,14 +9,18 @@
 
 #include 
 #include 
-#include 
+#include "test_macros.h"
 
 // XFAIL: c++98, c++03, c++11, c++14
 
 // std::byte is not an integer type, nor a character type.
 // It is a distinct type for accessing the bits that ultimately make up object 
storage.
 
+#if TEST_STD_VER > 17
+static_assert( std::is_trivial::value, "" );   // P0767
+#else
 static_assert( std::is_pod::value, "" );
+#endif
 static_assert(!std::is_arithmetic::value, "" );
 static_assert(!std::is_integral::value, "" );
 

Modified: 
libcxx/trunk/test/std/language.support/support.types/max_align_t.pass.cpp
URL: 
http://llvm.org/viewvc/llvm-project/libcxx/trunk/test/std/language.support/support.types/max_align_t.pass.cpp?rev=326801&r1=326800&r2=326801&view=diff
==
--- libcxx/trunk/test/std/language.support/support.types/max_align_t.pass.cpp 
(original)
+++ libcxx/trunk/test/std/language.support/support.types/max_align_t.pass.cpp 
Tue Mar  6 07:01:19 2018
@@ -14,11 +14,18 @@
 //   great as that of every scalar type
 
 #include 
+#include "test_macros.h"
 
 int main()
 {
+#if TEST_STD_VER > 17
+//  P0767
+static_assert(std::is_trivial::value,
+  "std::is_trivial::value");
+#else
 static_assert(std::is_pod::value,
   "std::is_pod::value");
+#endif
 static_assert((std::alignment_of::value >=
   std::alignment_of::value),
   "std::alignment_of::value >= "

Modified: 
libcxx/trunk/test/std/utilities/meta/meta.trans/meta.trans.other/aligned_storage.pass.cpp
URL: 
http://llvm.org/viewvc/llvm-project/libcxx/trunk/test/std/utilities/meta/meta.trans/meta.trans.other/aligned_storage.pass.cpp?rev=326801&r1=326800&r2=326801&view=diff
==
--- 
libcxx/trunk/test/std/utilities/meta/meta.trans/meta.trans.other/aligned_storage.pass.cpp
 (original)
+++ 
libcxx/trunk/test/std/utilities/meta/meta.trans/meta.trans.other/aligned_storage.pass.cpp
 Tue Mar  6 07:01:19 2018
@@ -22,6 +22,12 @@ int main()
 #if TEST_STD_VER > 11
 static_assert(std::is_same, T1>::value, "" );
 #endif
+#if TEST_STD_VER > 17
+//  P0767
+static_assert(std::is_trivial::value, "" );
+#else
+static_assert(std::is_pod::value, "" );
+#endif
 static_assert(std::alignment_of::value == 1, "");
 static_assert(sizeof(T1) == 10, "");
 }
@@ -30,6 +36,12 @@ int main()
 #if TEST_STD_VER > 11
 static_assert(std::is_same, T1>::value, "" );
 #endif
+#if TEST_STD_VER > 17
+//  P0767
+static_assert(std::is_trivial::value, "" );
+#else
+static_assert(std::is_pod::value, "" );
+#endif
 static_assert(std::alignment_of::value == 2, "");
 static_assert(sizeof(T1) == 10, "");
 }
@@ -38,6 +50,12 @@ int main()
 #if TEST_STD_VER > 11
 static_assert(std::is_same, T1>::value, "" );
 #endif
+#if TEST_STD_VER > 17
+//  P0767
+static_assert(std::is_trivial::value, "" );
+#else
+static_assert(std::is_pod::value, "" );
+#endif
 static_assert(std::alignment_of::value == 4, "");
 static_assert(sizeof(T1) == 12, "");
 }
@@ -46,6 +64,12 @@ int main()
 #if TEST_STD_VER > 11
 static_assert(std::is_same, T1>::value, "" );
 #endif
+#if TEST_STD_VER > 17
+//  P0767
+static_assert(std::is_trivial::value, "" );
+#else
+static_assert(std::is_pod::value, "" );
+#endif
 static_assert(std::alignment_of::value == 8, "");
 static_assert(sizeof(T1) == 16, "");
 }
@@ -54,6 +78,12 @@ int main()
 #if TEST_STD_VER > 11
 static_assert(std::is_same, T1>::value, "" 
);
 #endif
+#if TEST_STD_VER > 17
+//  P0767
+static_assert(std::is_trivial::value, "" );
+#else
+static_assert(std::is_pod::value, "" );
+#endif
 static_assert(std::alignment_of::value == 16, "");
 static_assert(sizeof(T1) == 16, "");
 }
@@ -62,6 +92,12 @@ int main()
 #if TEST_STD_VER > 11
 static_assert(std::is_same, T1>::value, "" 
);
 #endif
+#if TEST_STD_VER > 17
+//  P0767
+static_assert

[libcxx] r326802 - One more test for P0767:

2018-03-06 Thread Marshall Clow via cfe-commits
Author: marshall
Date: Tue Mar  6 07:01:55 2018
New Revision: 326802

URL: http://llvm.org/viewvc/llvm-project?rev=326802&view=rev
Log:
One more test for P0767:

Modified:
libcxx/trunk/test/std/depr/depr.c.headers/stddef_h.pass.cpp

Modified: libcxx/trunk/test/std/depr/depr.c.headers/stddef_h.pass.cpp
URL: 
http://llvm.org/viewvc/llvm-project/libcxx/trunk/test/std/depr/depr.c.headers/stddef_h.pass.cpp?rev=326802&r1=326801&r2=326802&view=diff
==
--- libcxx/trunk/test/std/depr/depr.c.headers/stddef_h.pass.cpp (original)
+++ libcxx/trunk/test/std/depr/depr.c.headers/stddef_h.pass.cpp Tue Mar  6 
07:01:55 2018
@@ -13,6 +13,8 @@
 #include 
 #include 
 
+#include "test_macros.h"
+
 #ifndef NULL
 #error NULL not defined
 #endif
@@ -42,8 +44,14 @@ int main()
   "decltype(nullptr) == nullptr_t");
 static_assert(sizeof(nullptr_t) == sizeof(void*),
   "sizeof(nullptr_t) == sizeof(void*)");
+#if TEST_STD_VER > 17
+//   P0767
+static_assert(std::is_trivial::value,
+  "std::is_trivial::value");
+#else
 static_assert(std::is_pod::value,
   "std::is_pod::value");
+#endif
 static_assert((std::alignment_of::value >=
   std::alignment_of::value),
   "std::alignment_of::value >= "


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


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

2018-03-06 Thread Haojian Wu via Phabricator via cfe-commits
hokein accepted this revision.
hokein added a comment.
This revision is now accepted and ready to land.

Looks good with a few nits.




Comment at: clang-tidy/abseil/AbseilTidyModule.cpp:15
+
+#include 
+

What is this header used for?



Comment at: clang-tidy/abseil/StringFindStartswithCheck.cpp:94
+
+  if (ComparisonExpr->getLocStart().isMacroID())
+return;

nit: we can put it at the beginning of this method to make it early return if 
it is in macro. I think it is fine to ignore macro cases.



Comment at: docs/clang-tidy/checks/abseil-string-find-startswith.rst:30
+   Semicolon-separated list of names of string-like classes. By default only
+   ``std::basic_string`` is considered. The list of methods to consired is
+   fixed.

s/consired/considered



Comment at: test/clang-tidy/abseil-string-find-startswith.cpp:2
+// RUN: %check_clang_tidy %s abseil-string-find-startswith %t
+// -std=c++11
+

nit: -std=c++11 is not needed, it is on by default.


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D43847



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


[PATCH] D43341: [clang-doc] Implement reducer portion of the frontend framework

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

Thank you for working on this!

Finally trying to review this...
I must say i'm **really** not fond of the test 'changes'.

But some initial comments added:




Comment at: clang-doc/BitcodeReader.cpp:19
+
+void ClangDocBitcodeReader::storeData(llvm::SmallString<4> &Field,
+  llvm::StringRef Blob) {

I think all these `SmallString` can be one `llvm::SmallVectorImpl`?



Comment at: clang-doc/BitcodeReader.cpp:454
+for (const auto &N : (*BlockInfo).getBlockInfo(I)->RecordNames)
+  RecordNames[N.first] = N.second;
+  }

`RecordNames` is basically not kept between the reuses of 
`ClangDocBitcodeReader`, but is also not actually properly gc'd.
Also, this uses `BI_FIRST` / `BI_LAST`, which means the versioning is actually 
absolutely required...
Also, `RecordNames` isn't actually used anywhere later in this code.

So, Is that needed for the next patches? Or why read this at all?





Comment at: clang-doc/BitcodeReader.h:36
+
+  bool readBitstream(llvm::SmallString<2048> Bits,
+ std::unique_ptr &IS);

`Bits` is not an output parameter, but just a const input parameter?
I think it would be cleaner to use `StringRef`, to avoid depending on the 
actual size of the small-size.



Comment at: clang-doc/BitcodeReader.h:46
+  bool readBlockInfoBlock(llvm::BitstreamCursor &Stream);
+  template 
+  bool readBlockToInfo(llvm::BitstreamCursor &Stream, unsigned ID,

Please separate those tree functions and this template function with one 
newline.



Comment at: clang-doc/BitcodeReader.h:48
+  bool readBlockToInfo(llvm::BitstreamCursor &Stream, unsigned ID,
+   std::unique_ptr &IS, T &&I);
+

 `T &&I` looks super vague.
`T` is `{something}Info`, which is inherited from `Info` base-class.
Maybe something like `InfoT &&I` ?



Comment at: clang-doc/Reducer.cpp:19
+  std::unique_ptr UniqueInfos = llvm::make_unique();
+  doc::ClangDocBitcodeReader Reader;
+  bool Err = false;

As far as i can tell, `Reader` isn't required to be kept out here.
It seems it's not used to retain any internal state.
The only obvious reason to keep it, is to avoid de-allocating and then 
re-allocating the memory each time.

I'm wondering if it would be better to move it into the lambda.
Also, why is it prefixed with the `doc::`? We are in that namespace already.

Then, you will also be able to get rid of `llvm::BitstreamCursor &Stream` 
params in the `ClangDocBitcodeReader` member functions, like with 
`ClangDocBitcodeWriter`.



Comment at: clang-doc/Representation.h:193
+ private:
+  void resolveReferences(llvm::SmallVector &References,
+ Reference &Caller);

Similarly, i think those should be `SmallVectorImpl` (i assume those are output 
params, too?)



Comment at: test/clang-doc/mapper-class-in-class.cpp:1
-// RUN: rm -rf %t
-// RUN: mkdir %t

What's up with all tests being deleted? That is rather disturbing.
I would expect the merge phase to be disable-able, if only just for the testing 
purposes.


https://reviews.llvm.org/D43341



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


[PATCH] D44154: [checker] PoC : Unsequenced Modification Checker

2018-03-06 Thread Paul Semel via Phabricator via cfe-commits
paulsemel created this revision.
Herald added subscribers: cfe-commits, mgorny.

\!/ This is only a proof of concept !

The purpose of this checker is to improve the detection of unsequenced 
modifications. Indeed, there is a warning the tries to detect those, but this 
is not efficient at all.
The goal of this checker is to detect more complicated UM.


Repository:
  rC Clang

https://reviews.llvm.org/D44154

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

Index: lib/StaticAnalyzer/Checkers/UnsequencedModificationChecker.cpp
===
--- lib/StaticAnalyzer/Checkers/UnsequencedModificationChecker.cpp
+++ lib/StaticAnalyzer/Checkers/UnsequencedModificationChecker.cpp
@@ -0,0 +1,450 @@
+//=== UnsequencedModificationChecker.cpp ---*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===--===//
+//
+// This defines UnsequencedModificationChecker, a builtin check in ExprEngine
+// that performs checks for unsequenced modifications.
+//
+//===--===//
+
+#include "ClangSACheckers.h"
+#include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
+#include "clang/StaticAnalyzer/Core/Checker.h"
+#include "clang/StaticAnalyzer/Core/CheckerManager.h"
+#include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
+#include "clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h"
+#include "llvm/ADT/SmallString.h"
+#include "llvm/Support/raw_ostream.h"
+#include 
+#include 
+#include 
+#include 
+#include 
+
+using namespace clang;
+using namespace ento;
+
+namespace {
+
+  enum UBType
+  {
+UB_VAR,
+UB_ARRAY,
+UB_POINTER,
+UB_POINTERINDEX
+  };
+
+  class UBDecl
+  {
+public:
+  UBDecl(const VarDecl *vd)
+  {
+this->idx = SVal();
+this->type = UB_VAR;
+this->vd = vd;
+  };
+  UBDecl(const VarDecl *vd, enum UBType t)
+: vd(vd), type(t)
+  {
+this->idx = SVal();
+  }
+  UBDecl(const VarDecl *vd, SVal index)
+  {
+this->type = UB_ARRAY;
+this->vd = vd;
+this->idx = index;
+  };
+  void changeType(enum UBType t)
+  {
+this->type = t;
+  };
+  bool operator==(const UBDecl& ub)
+  {
+if (this->type != ub.type)
+  return false;
+switch(this->type)
+{
+  case UB_VAR:
+  case UB_POINTER:
+return this->vd == ub.vd;
+  case UB_ARRAY:
+  case UB_POINTERINDEX:
+return this->vd == ub.vd && this->idx == ub.idx;
+};
+return false;
+  };
+  const VarDecl *vd;
+  SVal idx;
+  enum UBType type;
+private:
+  };
+
+  enum UBAction
+  {
+UBUSED = 1,
+UBMODIFIED = 2,
+UBMULTIPLE = 4,
+  };
+
+  class UBListElement
+  {
+public:
+  UBListElement(std::shared_ptr& ub, enum UBAction action)
+:ub(ub), action(action)
+  { };
+  UBListElement(std::shared_ptr& ub, uint32_t action)
+:ub(ub), action(action)
+  { };
+  bool operator==(const UBDecl& elt)
+  {
+return *ub == elt;
+  };
+  std::shared_ptr ub;
+  uint32_t action;
+  };
+
+  class UBList
+  {
+public:
+  UBList() = default;
+  void push(std::shared_ptr ub, enum UBAction action)
+  {
+auto it = std::find(list.begin(), list.end(), *ub);
+if (it != list.end())
+{
+  if (it->action == action && action == UBMODIFIED)
+it->action = UBMULTIPLE;
+  else
+it->action |= action;
+}
+else
+  list.push_back(UBListElement(ub, action));
+  };
+  void pushCallExpr(std::shared_ptr ub, uint32_t action)
+  {
+auto it = std::find(list.begin(), list.end(), *ub);
+if (it != list.end())
+{
+  if (action != it->action)
+it->action = UBMODIFIED;
+}
+else
+  list.push_back(UBListElement(ub, action));
+  }
+  void push(std::shared_ptr ub, uint32_t action)
+  {
+auto it = std::find(list.begin(), list.end(), *ub);
+if (it != list.end())
+{
+  if (it->action == action && action == UBMODIFIED)
+it->action = UBMULTIPLE;
+  else
+it->action |= action;
+}
+else
+  list.push_back(UBListElement(ub, action));
+  };
+  size_t size()
+  {
+return list.size();
+  };
+  std::shared_ptr find_UB()
+  {
+for (auto &elt : list)
+{
+  if (elt.action == UBMULTIPLE || elt.action == (UBMO

[PATCH] D43906: [clang-format] Improve detection of Objective-C block types

2018-03-06 Thread Ben Hamilton via Phabricator via cfe-commits
benhamilton added inline comments.



Comment at: lib/Format/TokenAnnotator.cpp:155
+   Next->startsSequence(tok::identifier, tok::l_square,
+tok::numeric_constant, tok::r_square,
+tok::r_paren, tok::l_paren))) {

djasper wrote:
> benhamilton wrote:
> > djasper wrote:
> > > This seems suspect. Does it have to be a numeric_constant?
> > Probably not, any constexpr would do, I suspect. What's the best way to 
> > parse that?
> I think this is the same answer for both of your questions. If what you are 
> trying to prevent "FOO(^)" to be parsed as a block, wouldn't it be enough to 
> look for whether there is a "(" after the ")" or even only after "(^)", 
> everything else is already correct IIUC? That would get you out of need to 
> parse the specifics here, which will be hard.
> 
> Or thinking about it another way. Previously, every "(^" would be parsed as 
> an ObjC block. There seems to be only a really rare corner case in which it 
> isn't (macros). Thus, I'd just try to detect that corner case. Instead you 
> are completely inverting the defaults (defaulting to "^" is not a block) and 
> then try to exactly parse ObjC where there might be many cases and edge cases 
> that you won't even think of now.
Hmm. Well, it's not just `FOO(^);` that isn't a block:

```
#define FOO(X) operator X

SomeType FOO(^)(int x, const SomeType& y) { ... }
```

Obviously we can't get this perfect without a pre-processor, but it seems like 
our best bet is to only assign mark `TT_ObjCBlockLParen` when we are sure the 
syntax is a valid block type or block variable.


Repository:
  rC Clang

https://reviews.llvm.org/D43906



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


r326807 - [X86] Fix typo in cpuid.h, bit_AVX51SER->bit_AVX512ER.

2018-03-06 Thread Craig Topper via cfe-commits
Author: ctopper
Date: Tue Mar  6 08:06:44 2018
New Revision: 326807

URL: http://llvm.org/viewvc/llvm-project?rev=326807&view=rev
Log:
[X86] Fix typo in cpuid.h, bit_AVX51SER->bit_AVX512ER.

Modified:
cfe/trunk/lib/Headers/cpuid.h

Modified: cfe/trunk/lib/Headers/cpuid.h
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Headers/cpuid.h?rev=326807&r1=326806&r2=326807&view=diff
==
--- cfe/trunk/lib/Headers/cpuid.h (original)
+++ cfe/trunk/lib/Headers/cpuid.h Tue Mar  6 08:06:44 2018
@@ -166,7 +166,7 @@
 #define bit_CLFLUSHOPT  0x0080
 #define bit_CLWB0x0100
 #define bit_AVX512PF0x0400
-#define bit_AVX51SER0x0800
+#define bit_AVX512ER0x0800
 #define bit_AVX512CD0x1000
 #define bit_SHA 0x2000
 #define bit_AVX512BW0x4000


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


[PATCH] D43904: [clang-format] Improve detection of ObjC for-in statements

2018-03-06 Thread Ben Hamilton via Phabricator via cfe-commits
benhamilton updated this revision to Diff 137199.
benhamilton marked an inline comment as done.
benhamilton added a comment.

- Move ObjC-specific tests to `FormatTestObjC.cpp`.


Repository:
  rC Clang

https://reviews.llvm.org/D43904

Files:
  lib/Format/TokenAnnotator.cpp
  unittests/Format/FormatTest.cpp
  unittests/Format/FormatTestObjC.cpp


Index: unittests/Format/FormatTestObjC.cpp
===
--- unittests/Format/FormatTestObjC.cpp
+++ unittests/Format/FormatTestObjC.cpp
@@ -893,6 +893,13 @@
"foo(n);\n"
"  }\n"
"}");
+  verifyFormat("for (Foo *x in bar) {\n}");
+  verifyFormat("for (Foo *x in [bar baz]) {\n}");
+  verifyFormat("for (Foo *x in [bar baz:blech]) {\n}");
+  verifyFormat("for (Foo *x in [bar baz:blech, 1, 2, 3, 0]) {\n}");
+  verifyFormat("for (Foo *x in [bar baz:^{\n"
+   "   [uh oh];\n"
+   " }]) {\n}");
 }
 
 TEST_F(FormatTestObjC, ObjCLiterals) {
Index: unittests/Format/FormatTest.cpp
===
--- unittests/Format/FormatTest.cpp
+++ unittests/Format/FormatTest.cpp
@@ -742,6 +742,12 @@
" aaa != bbb;\n"
" ++aaa) {");
 
+  // These should not be formatted as Objective-C for-in loops.
+  verifyFormat("for (Foo *x = 0; x != in; x++) {\n}");
+  verifyFormat("Foo *x;\nfor (x = 0; x != in; x++) {\n}");
+  verifyFormat("Foo *x;\nfor (x in y) {\n}");
+  verifyFormat("for (const Foo &baz = in.value(); !baz.at_end(); ++baz) 
{\n}");
+
   FormatStyle NoBinPacking = getLLVMStyle();
   NoBinPacking.BinPackParameters = false;
   verifyFormat("for (int aaa = 1;\n"
@@ -12120,6 +12126,31 @@
   EXPECT_EQ(FormatStyle::LK_Cpp, guessLanguage("foo.h", "[[foo::bar, ...]]"));
 }
 
+TEST_F(FormatTest, GuessLanguageWithForIn) {
+  EXPECT_EQ(FormatStyle::LK_Cpp,
+guessLanguage("foo.h", "for (Foo *x = 0; x != in; x++) {}"));
+  EXPECT_EQ(FormatStyle::LK_ObjC,
+guessLanguage("foo.h", "for (Foo *x in bar) {}"));
+  EXPECT_EQ(FormatStyle::LK_ObjC,
+guessLanguage("foo.h", "for (Foo *x in [bar baz]) {}"));
+  EXPECT_EQ(FormatStyle::LK_ObjC,
+guessLanguage("foo.h", "for (Foo *x in [bar baz:blech]) {}"));
+  EXPECT_EQ(
+  FormatStyle::LK_ObjC,
+  guessLanguage("foo.h", "for (Foo *x in [bar baz:blech, 1, 2, 3, 0]) 
{}"));
+  EXPECT_EQ(FormatStyle::LK_ObjC,
+guessLanguage("foo.h", "for (Foo *x in [bar baz:^{[uh oh];}]) 
{}"));
+  EXPECT_EQ(FormatStyle::LK_Cpp,
+guessLanguage("foo.h", "Foo *x; for (x = 0; x != in; x++) {}"));
+  EXPECT_EQ(FormatStyle::LK_ObjC,
+guessLanguage("foo.h", "Foo *x; for (x in y) {}"));
+  EXPECT_EQ(
+  FormatStyle::LK_Cpp,
+  guessLanguage(
+  "foo.h",
+  "for (const Foo& baz = in.value(); !baz.at_end(); ++baz) {}"));
+}
+
 } // end namespace
 } // end namespace format
 } // end namespace clang
Index: lib/Format/TokenAnnotator.cpp
===
--- lib/Format/TokenAnnotator.cpp
+++ lib/Format/TokenAnnotator.cpp
@@ -216,6 +216,7 @@
 bool HasMultipleParametersOnALine = false;
 bool MightBeObjCForRangeLoop =
 Left->Previous && Left->Previous->is(tok::kw_for);
+FormatToken *PossibleObjCForInToken = nullptr;
 while (CurrentToken) {
   // LookForDecls is set when "if (" has been seen. Check for
   // 'identifier' '*' 'identifier' followed by not '=' -- this
@@ -301,10 +302,17 @@
CurrentToken->Previous->isSimpleTypeSpecifier()) &&
   !CurrentToken->is(tok::l_brace))
 Contexts.back().IsExpression = false;
-  if (CurrentToken->isOneOf(tok::semi, tok::colon))
+  if (CurrentToken->isOneOf(tok::semi, tok::colon)) {
 MightBeObjCForRangeLoop = false;
-  if (MightBeObjCForRangeLoop && CurrentToken->is(Keywords.kw_in))
-CurrentToken->Type = TT_ObjCForIn;
+if (PossibleObjCForInToken) {
+  PossibleObjCForInToken->Type = TT_Unknown;
+  PossibleObjCForInToken = nullptr;
+}
+  }
+  if (MightBeObjCForRangeLoop && CurrentToken->is(Keywords.kw_in)) {
+PossibleObjCForInToken = CurrentToken;
+PossibleObjCForInToken->Type = TT_ObjCForIn;
+  }
   // When we discover a 'new', we set CanBeExpression to 'false' in order 
to
   // parse the type correctly. Reset that after a comma.
   if (CurrentToken->is(tok::comma))


Index: unittests/Format/FormatTestObjC.cpp
===
--- unittests/Format/FormatTestObjC.cpp
+++ unittests/Format/FormatTestObjC.cpp
@@ -893,6 +893,13 @@
"foo(n);\n"
"  }\n"
"}");
+  verifyFormat("for (Foo *x in bar) {\n}");
+  verifyFormat("for (Foo *x in [bar baz]) {\

[PATCH] D43904: [clang-format] Improve detection of ObjC for-in statements

2018-03-06 Thread Ben Hamilton via Phabricator via cfe-commits
benhamilton added inline comments.



Comment at: unittests/Format/FormatTest.cpp:778
 
+TEST_F(FormatTest, ObjCForInLoop) {
+  verifyFormat("for (Foo *x = 0; x != in; x++) {\n}");

krasimir wrote:
> Please move the ObjC-specific instances to `FormatTestObjC.cpp`.
Done.


Repository:
  rC Clang

https://reviews.llvm.org/D43904



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


[PATCH] D41958: Create a deduction guide for basic_string

2018-03-06 Thread Marshall Clow via Phabricator via cfe-commits
mclow.lists closed this revision.
mclow.lists added a comment.

This was landed as r324619


https://reviews.llvm.org/D41958



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


[PATCH] D44154: [checker] PoC : Unsequenced Modification Checker

2018-03-06 Thread Aleksei Sidorin via Phabricator via cfe-commits
a.sidorin added a comment.

Hi Paul,

You didn't add any reviewer. Do you need a review for this checker? Are you 
going to contribute this code to the upstream?


Repository:
  rC Clang

https://reviews.llvm.org/D44154



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


[PATCH] D43906: [clang-format] Improve detection of Objective-C block types

2018-03-06 Thread Ben Hamilton via Phabricator via cfe-commits
benhamilton added inline comments.



Comment at: lib/Format/TokenAnnotator.cpp:155
+   Next->startsSequence(tok::identifier, tok::l_square,
+tok::numeric_constant, tok::r_square,
+tok::r_paren, tok::l_paren))) {

benhamilton wrote:
> djasper wrote:
> > benhamilton wrote:
> > > djasper wrote:
> > > > This seems suspect. Does it have to be a numeric_constant?
> > > Probably not, any constexpr would do, I suspect. What's the best way to 
> > > parse that?
> > I think this is the same answer for both of your questions. If what you are 
> > trying to prevent "FOO(^)" to be parsed as a block, wouldn't it be enough 
> > to look for whether there is a "(" after the ")" or even only after "(^)", 
> > everything else is already correct IIUC? That would get you out of need to 
> > parse the specifics here, which will be hard.
> > 
> > Or thinking about it another way. Previously, every "(^" would be parsed as 
> > an ObjC block. There seems to be only a really rare corner case in which it 
> > isn't (macros). Thus, I'd just try to detect that corner case. Instead you 
> > are completely inverting the defaults (defaulting to "^" is not a block) 
> > and then try to exactly parse ObjC where there might be many cases and edge 
> > cases that you won't even think of now.
> Hmm. Well, it's not just `FOO(^);` that isn't a block:
> 
> ```
> #define FOO(X) operator X
> 
> SomeType FOO(^)(int x, const SomeType& y) { ... }
> ```
> 
> Obviously we can't get this perfect without a pre-processor, but it seems 
> like our best bet is to only assign mark `TT_ObjCBlockLParen` when we are 
> sure the syntax is a valid block type or block variable.
I tried the suggestion to only treat `(^)(` as a block type, but it appears 
this is the primary place where we set `TT_ObjCBlockLParen`, so I think we 
really do need to handle the other cases here.


Repository:
  rC Clang

https://reviews.llvm.org/D43906



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


[PATCH] D43197: [OpenMP] Add flag for linking runtime bitcode library

2018-03-06 Thread Gheorghe-Teodor Bercea via Phabricator via cfe-commits
gtbercea updated this revision to Diff 137203.
gtbercea added a comment.

Address comments.


Repository:
  rC Clang

https://reviews.llvm.org/D43197

Files:
  include/clang/Basic/DiagnosticDriverKinds.td
  lib/Driver/ToolChains/Cuda.cpp
  test/Driver/openmp-offload-gpu.c


Index: test/Driver/openmp-offload-gpu.c
===
--- test/Driver/openmp-offload-gpu.c
+++ test/Driver/openmp-offload-gpu.c
@@ -142,3 +142,25 @@
 // RUN:   | FileCheck -check-prefix=CHK-NOLIBDEVICE %s
 
 // CHK-NOLIBDEVICE-NOT: error:{{.*}}sm_60
+
+/// ###
+
+/// Check that the runtime bitcode library is part of the compile line. Create 
a bogus
+/// bitcode library and add it to the LIBRARY_PATH.
+// RUN:   touch %T/libomptarget-nvptx-sm_60.bc
+// RUN:   env LIBRARY_PATH=%T %clang -### -fopenmp=libomp 
-fopenmp-targets=nvptx64-nvidia-cuda \
+// RUN:   -Xopenmp-target -march=sm_60 -fopenmp-relocatable-target -save-temps 
\
+// RUN:   -no-canonical-prefixes %s 2>&1 | FileCheck -check-prefix=CHK-BCLIB %s
+// RUN:   rm %T/libomptarget-nvptx-sm_60.bc
+
+// CHK-BCLIB: 
clang{{.*}}-triple{{.*}}nvptx64-nvidia-cuda{{.*}}-mlink-cuda-bitcode{{.*}}libomptarget-nvptx-sm_60.bc
+
+/// ###
+
+/// Check that the warning is thrown when the libomptarget bitcode library is 
not found.
+/// Libomptarget requires sm_35 or newer so an sm_20 bitcode library should 
never exist.
+// RUN:   %clang -### -fopenmp=libomp -fopenmp-targets=nvptx64-nvidia-cuda \
+// RUN:   -Xopenmp-target -march=sm_20 -fopenmp-relocatable-target -save-temps 
\
+// RUN:   -no-canonical-prefixes %s 2>&1 | FileCheck 
-check-prefix=CHK-BCLIB-WARN %s
+
+// CHK-BCLIB-WARN: Expect degraded performance on the target device due to 
missing 'libomptarget-nvptx-sm_20.bc' in LIBRARY_PATH.
Index: lib/Driver/ToolChains/Cuda.cpp
===
--- lib/Driver/ToolChains/Cuda.cpp
+++ lib/Driver/ToolChains/Cuda.cpp
@@ -21,6 +21,7 @@
 #include "llvm/Option/ArgList.h"
 #include "llvm/Support/FileSystem.h"
 #include "llvm/Support/Path.h"
+#include "llvm/Support/Process.h"
 #include "llvm/Support/Program.h"
 #include 
 
@@ -580,6 +581,42 @@
 CC1Args.push_back("-target-feature");
 CC1Args.push_back("+ptx42");
   }
+
+  if (DeviceOffloadingKind == Action::OFK_OpenMP) {
+SmallVector LibraryPaths;
+// Add path to lib and/or lib64 folders.
+SmallString<256> DefaultLibPath =
+  llvm::sys::path::parent_path(getDriver().Dir);
+llvm::sys::path::append(DefaultLibPath, "lib" CLANG_LIBDIR_SUFFIX);
+LibraryPaths.emplace_back(DriverArgs.MakeArgString(DefaultLibPath));
+
+// Add user defined library paths from LIBRARY_PATH.
+if (llvm::Optional LibPath =
+  llvm::sys::Process::GetEnv("LIBRARY_PATH")) {
+  SmallVector Frags;
+  llvm::SplitString(*LibPath, Frags,
+  StringRef(&(llvm::sys::EnvPathSeparator)));
+  for (auto Path : Frags)
+LibraryPaths.emplace_back(Path.trim());
+}
+
+std::string LibOmpTargetName =
+  "libomptarget-nvptx-" + GpuArch.str() + ".bc";
+bool FoundBCLibrary = false;
+for (const std::string &LibraryPath : LibraryPaths) {
+  SmallString<128> LibOmpTargetFile(LibraryPath);
+  llvm::sys::path::append(LibOmpTargetFile, LibOmpTargetName);
+  if (llvm::sys::fs::exists(LibOmpTargetFile)) {
+CC1Args.push_back("-mlink-cuda-bitcode");
+CC1Args.push_back(DriverArgs.MakeArgString(LibOmpTargetFile));
+FoundBCLibrary = true;
+break;
+  }
+}
+if (!FoundBCLibrary)
+  getDriver().Diag(diag::remark_drv_omp_offload_target_missingbcruntime)
+  << LibOmpTargetName;
+  }
 }
 
 void CudaToolChain::AddCudaIncludeArgs(const ArgList &DriverArgs,
Index: include/clang/Basic/DiagnosticDriverKinds.td
===
--- include/clang/Basic/DiagnosticDriverKinds.td
+++ include/clang/Basic/DiagnosticDriverKinds.td
@@ -203,6 +203,9 @@
 def warn_drv_omp_offload_target_duplicate : Warning<
   "The OpenMP offloading target '%0' is similar to target '%1' already 
specified - will be ignored.">, 
   InGroup;
+def remark_drv_omp_offload_target_missingbcruntime : Warning<
+  "Expect degraded performance on the target device due to missing '%0' in 
LIBRARY_PATH.">,
+  InGroup;
 def err_drv_bitcode_unsupported_on_toolchain : Error<
   "-fembed-bitcode is not supported on versions of iOS prior to 6.0">;
 


Index: test/Driver/openmp-offload-gpu.c
===
--- test/Driver/openmp-offload-gpu.c
+++ test/Driver/openmp-offload-gpu.c
@@ -142,3 +142,25 @@
 // RUN:   | FileCheck -check-prefix=CHK-NOLIBDEVICE %s
 
 // CHK-NOLIBDEVICE-NOT: error:{{.*}}sm_60
+
+/// 

[PATCH] D44154: [checker] PoC : Unsequenced Modification Checker

2018-03-06 Thread Paul Semel via Phabricator via cfe-commits
paulsemel added a comment.

Hi Aleksei,

In https://reviews.llvm.org/D44154#1028612, @a.sidorin wrote:

> Hi Paul,
>
> You didn't add any reviewer. Do you need a review for this checker? Are you 
> going to contribute this code to the upstream?


I was actually uploading this because Artem Dergachev told me that he was 
curious about this checker, but I'm pretty sure that this implementation is not 
good enough to be upstreamed !


Repository:
  rC Clang

https://reviews.llvm.org/D44154



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


[PATCH] D43660: [OpenMP] Add OpenMP data sharing infrastructure using global memory

2018-03-06 Thread Gheorghe-Teodor Bercea via Phabricator via cfe-commits
gtbercea updated this revision to Diff 137210.
gtbercea added a comment.

Add init stack function.


Repository:
  rC Clang

https://reviews.llvm.org/D43660

Files:
  lib/CodeGen/CGDecl.cpp
  lib/CodeGen/CGOpenMPRuntime.cpp
  lib/CodeGen/CGOpenMPRuntime.h
  lib/CodeGen/CGOpenMPRuntimeNVPTX.cpp
  lib/CodeGen/CGOpenMPRuntimeNVPTX.h
  lib/CodeGen/CGStmtOpenMP.cpp
  lib/CodeGen/CodeGenFunction.cpp
  test/OpenMP/nvptx_data_sharing.cpp
  test/OpenMP/nvptx_parallel_codegen.cpp

Index: test/OpenMP/nvptx_parallel_codegen.cpp
===
--- test/OpenMP/nvptx_parallel_codegen.cpp
+++ test/OpenMP/nvptx_parallel_codegen.cpp
@@ -64,254 +64,243 @@
 
   // CHECK-NOT: define {{.*}}void {{@__omp_offloading_.+template.+l17}}_worker()
 
+// CHECK-LABEL: define {{.*}}void {{@__omp_offloading_.+template.+l26}}_worker()
+// CHECK-DAG: [[OMP_EXEC_STATUS:%.+]] = alloca i8,
+// CHECK-DAG: [[OMP_WORK_FN:%.+]] = alloca i8*,
+// CHECK: store i8* null, i8** [[OMP_WORK_FN]],
+// CHECK: store i8 0, i8* [[OMP_EXEC_STATUS]],
+// CHECK: br label {{%?}}[[AWAIT_WORK:.+]]
+//
+// CHECK: [[AWAIT_WORK]]
+// CHECK: call void @llvm.nvvm.barrier0()
+// CHECK: [[KPR:%.+]] = call i1 @__kmpc_kernel_parallel(i8** [[OMP_WORK_FN]]
+// CHECK: [[KPRB:%.+]] = zext i1 [[KPR]] to i8
+// store i8 [[KPRB]], i8* [[OMP_EXEC_STATUS]], align 1
+// CHECK: [[WORK:%.+]] = load i8*, i8** [[OMP_WORK_FN]],
+// CHECK: [[SHOULD_EXIT:%.+]] = icmp eq i8* [[WORK]], null
+// CHECK: br i1 [[SHOULD_EXIT]], label {{%?}}[[EXIT:.+]], label {{%?}}[[SEL_WORKERS:.+]]
+//
+// CHECK: [[SEL_WORKERS]]
+// CHECK: [[ST:%.+]] = load i8, i8* [[OMP_EXEC_STATUS]]
+// CHECK: [[IS_ACTIVE:%.+]] = icmp ne i8 [[ST]], 0
+// CHECK: br i1 [[IS_ACTIVE]], label {{%?}}[[EXEC_PARALLEL:.+]], label {{%?}}[[BAR_PARALLEL:.+]]
+//
+// CHECK: [[EXEC_PARALLEL]]
+// CHECK: [[WF1:%.+]] = load i8*, i8** [[OMP_WORK_FN]],
+// CHECK: [[WM1:%.+]] = icmp eq i8* [[WF1]], bitcast (void (i16, i32)* [[PARALLEL_FN1:@.+]]_wrapper to i8*)
+// CHECK: br i1 [[WM1]], label {{%?}}[[EXEC_PFN1:.+]], label {{%?}}[[CHECK_NEXT1:.+]]
+//
+// CHECK: [[EXEC_PFN1]]
+// CHECK: call void [[PARALLEL_FN1]]_wrapper(
+// CHECK: br label {{%?}}[[TERM_PARALLEL:.+]]
+//
+// CHECK: [[CHECK_NEXT1]]
+// CHECK: [[WF2:%.+]] = load i8*, i8** [[OMP_WORK_FN]],
+// CHECK: [[WM2:%.+]] = icmp eq i8* [[WF2]], bitcast (void (i16, i32)* [[PARALLEL_FN2:@.+]]_wrapper to i8*)
+// CHECK: br i1 [[WM2]], label {{%?}}[[EXEC_PFN2:.+]], label {{%?}}[[CHECK_NEXT2:.+]]
+//
+// CHECK: [[EXEC_PFN2]]
+// CHECK: call void [[PARALLEL_FN2]]_wrapper(
+// CHECK: br label {{%?}}[[TERM_PARALLEL:.+]]
+//
+// CHECK: [[CHECK_NEXT2]]
+// CHECK: br label {{%?}}[[TERM_PARALLEL:.+]]
+//
+// CHECK: [[TERM_PARALLEL]]
+// CHECK: call void @__kmpc_kernel_end_parallel()
+// CHECK: br label {{%?}}[[BAR_PARALLEL]]
+//
+// CHECK: [[BAR_PARALLEL]]
+// CHECK: call void @llvm.nvvm.barrier0()
+// CHECK: br label {{%?}}[[AWAIT_WORK]]
+//
+// CHECK: [[EXIT]]
+// CHECK: ret void
 
+// CHECK: define {{.*}}void [[T6:@__omp_offloading_.+template.+l26]](i[[SZ:32|64]]
+// Create local storage for each capture.
+// CHECK:  [[LOCAL_A:%.+]] = alloca i[[SZ]],
+// CHECK-DAG:  store i[[SZ]] [[ARG_A:%.+]], i[[SZ]]* [[LOCAL_A]]
+// Store captures in the context.
+// CHECK-64-DAG:[[REF_A:%.+]] = bitcast i[[SZ]]* [[LOCAL_A]] to i32*
+//
+// CHECK-DAG: [[TID:%.+]] = call i32 @llvm.nvvm.read.ptx.sreg.tid.x()
+// CHECK-DAG: [[NTH:%.+]] = call i32 @llvm.nvvm.read.ptx.sreg.ntid.x()
+// CHECK-DAG: [[WS:%.+]] = call i32 @llvm.nvvm.read.ptx.sreg.warpsize()
+// CHECK-DAG: [[TH_LIMIT:%.+]] = sub i32 [[NTH]], [[WS]]
+// CHECK: [[IS_WORKER:%.+]] = icmp ult i32 [[TID]], [[TH_LIMIT]]
+// CHECK: br i1 [[IS_WORKER]], label {{%?}}[[WORKER:.+]], label {{%?}}[[CHECK_MASTER:.+]]
+//
+// CHECK: [[WORKER]]
+// CHECK: {{call|invoke}} void [[T6]]_worker()
+// CHECK: br label {{%?}}[[EXIT:.+]]
+//
+// CHECK: [[CHECK_MASTER]]
+// CHECK-DAG: [[CMTID:%.+]] = call i32 @llvm.nvvm.read.ptx.sreg.tid.x()
+// CHECK-DAG: [[CMNTH:%.+]] = call i32 @llvm.nvvm.read.ptx.sreg.ntid.x()
+// CHECK-DAG: [[CMWS:%.+]] = call i32 @llvm.nvvm.read.ptx.sreg.warpsize()
+// CHECK: [[IS_MASTER:%.+]] = icmp eq i32 [[CMTID]],
+// CHECK: br i1 [[IS_MASTER]], label {{%?}}[[MASTER:.+]], label {{%?}}[[EXIT]]
+//
+// CHECK: [[MASTER]]
+// CHECK-DAG: [[MNTH:%.+]] = call i32 @llvm.nvvm.read.ptx.sreg.ntid.x()
+// CHECK-DAG: [[MWS:%.+]] = call i32 @llvm.nvvm.read.ptx.sreg.warpsize()
+// CHECK: [[MTMP1:%.+]] = sub i32 [[MNTH]], [[MWS]]
+// CHECK: call void @__kmpc_kernel_init(i32 [[MTMP1]]
+// CHECK: call void @__kmpc_kernel_prepare_parallel(i8* bitcast (void (i16, i32)* [[PARALLEL_FN1]]_wrapper to i8*),
+// CHECK: call void @llvm.nvvm.barrier0()
+// CHECK: call void @llvm.nvvm.barrier0()
+// CHECK: call void @__kmpc_serialized_parallel(
+// CHECK: {{call|invoke}} void [[PARALLEL_FN3:@.+]](
+// CHECK: call void @__kmpc_end_serialized_parallel(
+// CHECK: call void @__kmpc_kernel_prepare_parallel(i8* bitcast (void (i16, i32)* [[P

[PATCH] D44158: [clangd:vscode] Resolve symlinks for file paths from clangd.

2018-03-06 Thread Eric Liu via Phabricator via cfe-commits
ioeric created this revision.
ioeric added a reviewer: sammccall.
Herald added subscribers: cfe-commits, jkorous-apple, ilya-biryukov, klimek.

For features like go-to-definition, clangd can point clients to symlink paths
(e.g. in bazel execroot) which might not be desired if the symlink points to a
file in the workspace. Clangd might not be able to build the file, and users
might prefer to edit the file on the real path.

This change converts file paths from clangd to real path (e.g. resolving 
symlinks).
Long term, we might want to the symlink handling logic to clangd where clangd
can better decide whether symlinks should be resolved according to e.g. compile
commands.


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D44158

Files:
  clangd/clients/clangd-vscode/src/extension.ts


Index: clangd/clients/clangd-vscode/src/extension.ts
===
--- clangd/clients/clangd-vscode/src/extension.ts
+++ clangd/clients/clangd-vscode/src/extension.ts
@@ -1,12 +1,13 @@
 import * as vscode from 'vscode';
 import * as vscodelc from 'vscode-languageclient';
+import { realpathSync } from 'fs';
 
 /**
  * Method to get workspace configuration option
  * @param option name of the option (e.g. for clangd.path should be path)
  * @param defaultValue default value to return if option is not set
  */
-function getConfig(option: string, defaultValue?: any) : T {
+function getConfig(option: string, defaultValue?: any): T {
 const config = vscode.workspace.getConfiguration('clangd');
 return config.get(option, defaultValue);
 }
@@ -24,18 +25,25 @@
 };
 const traceFile = getConfig('trace');
 if (!!traceFile) {
-  const trace = {CLANGD_TRACE : traceFile};
-  clangd.options = {env : {...process.env, ...trace}};
+const trace = { CLANGD_TRACE: traceFile };
+clangd.options = { env: { ...process.env, ...trace } };
 }
 const serverOptions: vscodelc.ServerOptions = clangd;
 
 const filePattern: string = '**/*.{' +
-  ['cpp', 'c', 'cc', 'cxx', 'c++', 'm', 'mm', 'h', 'hh', 'hpp', 'hxx', 
'inc'].join() + '}';
+['cpp', 'c', 'cc', 'cxx', 'c++', 'm', 'mm', 'h', 'hh', 'hpp', 'hxx', 
'inc'].join() + '}';
 const clientOptions: vscodelc.LanguageClientOptions = {
 // Register the server for C/C++ files
-documentSelector: [{scheme: 'file', pattern: filePattern}],
+documentSelector: [{ scheme: 'file', pattern: filePattern }],
 synchronize: !syncFileEvents ? undefined : {
 fileEvents: vscode.workspace.createFileSystemWatcher(filePattern)
+},
+// Resolve symlinks for all files provided by clangd.
+// FIXME: it might make more sense to rely on clangd to handle 
symlinks.
+uriConverters: {
+code2Protocol: (value: vscode.Uri) => value.toString(),
+protocol2Code: (value: string) =>
+vscode.Uri.file(realpathSync(vscode.Uri.parse(value).fsPath))
 }
 };
 


Index: clangd/clients/clangd-vscode/src/extension.ts
===
--- clangd/clients/clangd-vscode/src/extension.ts
+++ clangd/clients/clangd-vscode/src/extension.ts
@@ -1,12 +1,13 @@
 import * as vscode from 'vscode';
 import * as vscodelc from 'vscode-languageclient';
+import { realpathSync } from 'fs';
 
 /**
  * Method to get workspace configuration option
  * @param option name of the option (e.g. for clangd.path should be path)
  * @param defaultValue default value to return if option is not set
  */
-function getConfig(option: string, defaultValue?: any) : T {
+function getConfig(option: string, defaultValue?: any): T {
 const config = vscode.workspace.getConfiguration('clangd');
 return config.get(option, defaultValue);
 }
@@ -24,18 +25,25 @@
 };
 const traceFile = getConfig('trace');
 if (!!traceFile) {
-  const trace = {CLANGD_TRACE : traceFile};
-  clangd.options = {env : {...process.env, ...trace}};
+const trace = { CLANGD_TRACE: traceFile };
+clangd.options = { env: { ...process.env, ...trace } };
 }
 const serverOptions: vscodelc.ServerOptions = clangd;
 
 const filePattern: string = '**/*.{' +
-  ['cpp', 'c', 'cc', 'cxx', 'c++', 'm', 'mm', 'h', 'hh', 'hpp', 'hxx', 'inc'].join() + '}';
+['cpp', 'c', 'cc', 'cxx', 'c++', 'm', 'mm', 'h', 'hh', 'hpp', 'hxx', 'inc'].join() + '}';
 const clientOptions: vscodelc.LanguageClientOptions = {
 // Register the server for C/C++ files
-documentSelector: [{scheme: 'file', pattern: filePattern}],
+documentSelector: [{ scheme: 'file', pattern: filePattern }],
 synchronize: !syncFileEvents ? undefined : {
 fileEvents: vscode.workspace.createFileSystemWatcher(filePattern)
+},
+// Resolve symlinks for all files provided by clangd.
+// FIXME: it might make more sense to rely on clangd to handle symlinks

[clang-tools-extra] r326809 - [clangd] Don't end completion item labels with '::'

2018-03-06 Thread Ilya Biryukov via cfe-commits
Author: ibiryukov
Date: Tue Mar  6 08:45:21 2018
New Revision: 326809

URL: http://llvm.org/viewvc/llvm-project?rev=326809&view=rev
Log:
[clangd] Don't end completion item labels with '::'

Modified:
clang-tools-extra/trunk/clangd/CodeComplete.cpp
clang-tools-extra/trunk/test/clangd/protocol.test
clang-tools-extra/trunk/unittests/clangd/CodeCompleteTests.cpp

Modified: clang-tools-extra/trunk/clangd/CodeComplete.cpp
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clangd/CodeComplete.cpp?rev=326809&r1=326808&r2=326809&view=diff
==
--- clang-tools-extra/trunk/clangd/CodeComplete.cpp (original)
+++ clang-tools-extra/trunk/clangd/CodeComplete.cpp Tue Mar  6 08:45:21 2018
@@ -470,6 +470,8 @@ struct CompletionRecorder : public CodeC
   // (s.^ completes ~string, but s.~st^ is an error).
   if (dyn_cast_or_null(Result.Declaration))
 continue;
+  // We choose to never append '::' to completion results in clangd.
+  Result.StartsNestedNameSpecifier = false;
   Results.push_back(Result);
 }
 ResultsCallback();

Modified: clang-tools-extra/trunk/test/clangd/protocol.test
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/test/clangd/protocol.test?rev=326809&r1=326808&r2=326809&view=diff
==
--- clang-tools-extra/trunk/test/clangd/protocol.test (original)
+++ clang-tools-extra/trunk/test/clangd/protocol.test Tue Mar  6 08:45:21 2018
@@ -38,7 +38,7 @@ Content-Length: 146
 # CHECK-NEXT:"insertText": "fake",
 # CHECK-NEXT:"insertTextFormat": 1,
 # CHECK-NEXT:"kind": 7,
-# CHECK-NEXT:"label": "fake::",
+# CHECK-NEXT:"label": "fake",
 # CHECK-NEXT:"sortText": "{{.*}}"
 #  CHECK:]
 # CHECK-NEXT:  }
@@ -67,7 +67,7 @@ Content-Length: 146
 # CHECK-NEXT:"insertText": "fake",
 # CHECK-NEXT:"insertTextFormat": 1,
 # CHECK-NEXT:"kind": 7,
-# CHECK-NEXT:"label": "fake::",
+# CHECK-NEXT:"label": "fake",
 # CHECK-NEXT:"sortText": "{{.*}}"
 #  CHECK:]
 # CHECK-NEXT:  }
@@ -96,7 +96,7 @@ Content-Length: 146
 # CHECK-NEXT:"insertText": "fake",
 # CHECK-NEXT:"insertTextFormat": 1,
 # CHECK-NEXT:"kind": 7,
-# CHECK-NEXT:"label": "fake::",
+# CHECK-NEXT:"label": "fake",
 # CHECK-NEXT:"sortText": "{{.*}}"
 #  CHECK:]
 # CHECK-NEXT:  }

Modified: clang-tools-extra/trunk/unittests/clangd/CodeCompleteTests.cpp
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/unittests/clangd/CodeCompleteTests.cpp?rev=326809&r1=326808&r2=326809&view=diff
==
--- clang-tools-extra/trunk/unittests/clangd/CodeCompleteTests.cpp (original)
+++ clang-tools-extra/trunk/unittests/clangd/CodeCompleteTests.cpp Tue Mar  6 
08:45:21 2018
@@ -595,6 +595,18 @@ TEST(CodeCompleteTest, DisableTypoCorrec
   EXPECT_TRUE(Results.items.empty());
 }
 
+TEST(CodeCompleteTest, NoColonColonAtTheEnd) {
+  auto Results = completions(R"cpp(
+namespace clang { }
+void f() {
+  clan^
+}
+  )cpp");
+
+  EXPECT_THAT(Results.items, Contains(Labeled("clang")));
+  EXPECT_THAT(Results.items, Not(Contains(Labeled("clang::";
+}
+
 SignatureHelp signatures(StringRef Text) {
   MockFSProvider FS;
   MockCompilationDatabase CDB;


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


[PATCH] D43197: [OpenMP] Add flag for linking runtime bitcode library

2018-03-06 Thread Alexey Bataev via Phabricator via cfe-commits
ABataev added inline comments.



Comment at: lib/Driver/ToolChains/Cuda.cpp:591
+llvm::sys::path::append(DefaultLibPath, "lib" CLANG_LIBDIR_SUFFIX);
+LibraryPaths.emplace_back(DriverArgs.MakeArgString(DefaultLibPath));
+

Maybe just `LibraryPaths.emplace_back(DefaultLibPath);`?



Comment at: lib/Driver/ToolChains/Cuda.cpp:598
+  llvm::SplitString(*LibPath, Frags,
+  StringRef(&(llvm::sys::EnvPathSeparator)));
+  for (auto Path : Frags)

Wow, never do such things! This is a pointer to non-null terminated string.
Instead 
```
const char EnvPathSeparatorStr[] = {EnvPathSeparator, '\0'};
```
And use this array as a separator.


Repository:
  rC Clang

https://reviews.llvm.org/D43197



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


Re: r326746 - [analyzer] AST-matching checker to detect global central dispatch performance anti-pattern

2018-03-06 Thread George Karpenkov via cfe-commits
Yep, sorry, bad typing skills.

> On Mar 6, 2018, at 2:44 AM, Alexander Kornienko  wrote:
> 
> On Tue, Mar 6, 2018 at 11:03 AM Alexander Kornienko  > wrote:
> On Mon, Mar 5, 2018 at 11:05 PM George Karpenkov via cfe-commits 
> mailto:cfe-commits@lists.llvm.org>> wrote:
> Author: george.karpenkov
> Date: Mon Mar  5 14:03:32 2018
> New Revision: 326746
> 
> cfe/trunk/test/gcdasyncsemaphorechecker_test.m
> 
> The test doesn't belong here. The right place seems to be test/Analysis/.
> 
> Moved the test in r326772. 

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


r326815 - [clang-format] Improve detection of ObjC for-in statements

2018-03-06 Thread Ben Hamilton via cfe-commits
Author: benhamilton
Date: Tue Mar  6 09:21:42 2018
New Revision: 326815

URL: http://llvm.org/viewvc/llvm-project?rev=326815&view=rev
Log:
[clang-format] Improve detection of ObjC for-in statements

Summary:
Previously, clang-format would detect the following as an
Objective-C for-in statement:

  for (int x = in.value(); ...) {}

because the logic only decided a for-loop was definitely *not*
an Objective-C for-in loop after it saw a semicolon or a colon.

To fix this, I delayed the decision of whether this was a for-in
statement until after we found the matching right-paren, at which
point we know if we've seen a semicolon or not.

Test Plan: New tests added. Ran tests with:
  make -j12 FormatTests && ./tools/clang/unittests/Format/FormatTests

Reviewers: krasimir, jolesiak

Reviewed By: jolesiak

Subscribers: djasper, cfe-commits, klimek

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

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

Modified: cfe/trunk/lib/Format/TokenAnnotator.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Format/TokenAnnotator.cpp?rev=326815&r1=326814&r2=326815&view=diff
==
--- cfe/trunk/lib/Format/TokenAnnotator.cpp (original)
+++ cfe/trunk/lib/Format/TokenAnnotator.cpp Tue Mar  6 09:21:42 2018
@@ -216,6 +216,7 @@ private:
 bool HasMultipleParametersOnALine = false;
 bool MightBeObjCForRangeLoop =
 Left->Previous && Left->Previous->is(tok::kw_for);
+FormatToken *PossibleObjCForInToken = nullptr;
 while (CurrentToken) {
   // LookForDecls is set when "if (" has been seen. Check for
   // 'identifier' '*' 'identifier' followed by not '=' -- this
@@ -301,10 +302,17 @@ private:
CurrentToken->Previous->isSimpleTypeSpecifier()) &&
   !CurrentToken->is(tok::l_brace))
 Contexts.back().IsExpression = false;
-  if (CurrentToken->isOneOf(tok::semi, tok::colon))
+  if (CurrentToken->isOneOf(tok::semi, tok::colon)) {
 MightBeObjCForRangeLoop = false;
-  if (MightBeObjCForRangeLoop && CurrentToken->is(Keywords.kw_in))
-CurrentToken->Type = TT_ObjCForIn;
+if (PossibleObjCForInToken) {
+  PossibleObjCForInToken->Type = TT_Unknown;
+  PossibleObjCForInToken = nullptr;
+}
+  }
+  if (MightBeObjCForRangeLoop && CurrentToken->is(Keywords.kw_in)) {
+PossibleObjCForInToken = CurrentToken;
+PossibleObjCForInToken->Type = TT_ObjCForIn;
+  }
   // When we discover a 'new', we set CanBeExpression to 'false' in order 
to
   // parse the type correctly. Reset that after a comma.
   if (CurrentToken->is(tok::comma))

Modified: cfe/trunk/unittests/Format/FormatTest.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/unittests/Format/FormatTest.cpp?rev=326815&r1=326814&r2=326815&view=diff
==
--- cfe/trunk/unittests/Format/FormatTest.cpp (original)
+++ cfe/trunk/unittests/Format/FormatTest.cpp Tue Mar  6 09:21:42 2018
@@ -742,6 +742,12 @@ TEST_F(FormatTest, FormatsForLoop) {
" aaa != bbb;\n"
" ++aaa) {");
 
+  // These should not be formatted as Objective-C for-in loops.
+  verifyFormat("for (Foo *x = 0; x != in; x++) {\n}");
+  verifyFormat("Foo *x;\nfor (x = 0; x != in; x++) {\n}");
+  verifyFormat("Foo *x;\nfor (x in y) {\n}");
+  verifyFormat("for (const Foo &baz = in.value(); !baz.at_end(); ++baz) 
{\n}");
+
   FormatStyle NoBinPacking = getLLVMStyle();
   NoBinPacking.BinPackParameters = false;
   verifyFormat("for (int aaa = 1;\n"
@@ -12082,6 +12088,31 @@ TEST_F(FormatTest, FileAndCode) {
   EXPECT_EQ(FormatStyle::LK_ObjC, guessLanguage("foo", "@interface 
Foo\n@end\n"));
 }
 
+TEST_F(FormatTest, GuessLanguageWithForIn) {
+  EXPECT_EQ(FormatStyle::LK_Cpp,
+guessLanguage("foo.h", "for (Foo *x = 0; x != in; x++) {}"));
+  EXPECT_EQ(FormatStyle::LK_ObjC,
+guessLanguage("foo.h", "for (Foo *x in bar) {}"));
+  EXPECT_EQ(FormatStyle::LK_ObjC,
+guessLanguage("foo.h", "for (Foo *x in [bar baz]) {}"));
+  EXPECT_EQ(FormatStyle::LK_ObjC,
+guessLanguage("foo.h", "for (Foo *x in [bar baz:blech]) {}"));
+  EXPECT_EQ(
+  FormatStyle::LK_ObjC,
+  guessLanguage("foo.h", "for (Foo *x in [bar baz:blech, 1, 2, 3, 0]) 
{}"));
+  EXPECT_EQ(FormatStyle::LK_ObjC,
+guessLanguage("foo.h", "for (Foo *x in [bar baz:^{[uh oh];}]) 
{}"));
+  EXPECT_EQ(FormatStyle::LK_Cpp,
+guessLanguage("foo.h", "Foo *x; for (x = 0; x != in; x++) {}"));
+  EXPECT_EQ(FormatStyle::LK_ObjC,
+guessLanguage("foo.h", "Foo *x; for (x in y) {}"));
+  EXPECT_EQ(
+  FormatStyle::LK_Cpp,
+  guessLanguage(
+  "foo.

[PATCH] D43904: [clang-format] Improve detection of ObjC for-in statements

2018-03-06 Thread Ben Hamilton via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rL326815: [clang-format] Improve detection of ObjC for-in 
statements (authored by benhamilton, committed by ).
Herald added a subscriber: llvm-commits.

Changed prior to commit:
  https://reviews.llvm.org/D43904?vs=137199&id=137218#toc

Repository:
  rL LLVM

https://reviews.llvm.org/D43904

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


Index: cfe/trunk/lib/Format/TokenAnnotator.cpp
===
--- cfe/trunk/lib/Format/TokenAnnotator.cpp
+++ cfe/trunk/lib/Format/TokenAnnotator.cpp
@@ -216,6 +216,7 @@
 bool HasMultipleParametersOnALine = false;
 bool MightBeObjCForRangeLoop =
 Left->Previous && Left->Previous->is(tok::kw_for);
+FormatToken *PossibleObjCForInToken = nullptr;
 while (CurrentToken) {
   // LookForDecls is set when "if (" has been seen. Check for
   // 'identifier' '*' 'identifier' followed by not '=' -- this
@@ -301,10 +302,17 @@
CurrentToken->Previous->isSimpleTypeSpecifier()) &&
   !CurrentToken->is(tok::l_brace))
 Contexts.back().IsExpression = false;
-  if (CurrentToken->isOneOf(tok::semi, tok::colon))
+  if (CurrentToken->isOneOf(tok::semi, tok::colon)) {
 MightBeObjCForRangeLoop = false;
-  if (MightBeObjCForRangeLoop && CurrentToken->is(Keywords.kw_in))
-CurrentToken->Type = TT_ObjCForIn;
+if (PossibleObjCForInToken) {
+  PossibleObjCForInToken->Type = TT_Unknown;
+  PossibleObjCForInToken = nullptr;
+}
+  }
+  if (MightBeObjCForRangeLoop && CurrentToken->is(Keywords.kw_in)) {
+PossibleObjCForInToken = CurrentToken;
+PossibleObjCForInToken->Type = TT_ObjCForIn;
+  }
   // When we discover a 'new', we set CanBeExpression to 'false' in order 
to
   // parse the type correctly. Reset that after a comma.
   if (CurrentToken->is(tok::comma))
Index: cfe/trunk/unittests/Format/FormatTest.cpp
===
--- cfe/trunk/unittests/Format/FormatTest.cpp
+++ cfe/trunk/unittests/Format/FormatTest.cpp
@@ -742,6 +742,12 @@
" aaa != bbb;\n"
" ++aaa) {");
 
+  // These should not be formatted as Objective-C for-in loops.
+  verifyFormat("for (Foo *x = 0; x != in; x++) {\n}");
+  verifyFormat("Foo *x;\nfor (x = 0; x != in; x++) {\n}");
+  verifyFormat("Foo *x;\nfor (x in y) {\n}");
+  verifyFormat("for (const Foo &baz = in.value(); !baz.at_end(); ++baz) 
{\n}");
+
   FormatStyle NoBinPacking = getLLVMStyle();
   NoBinPacking.BinPackParameters = false;
   verifyFormat("for (int aaa = 1;\n"
@@ -12082,6 +12088,31 @@
   EXPECT_EQ(FormatStyle::LK_ObjC, guessLanguage("foo", "@interface 
Foo\n@end\n"));
 }
 
+TEST_F(FormatTest, GuessLanguageWithForIn) {
+  EXPECT_EQ(FormatStyle::LK_Cpp,
+guessLanguage("foo.h", "for (Foo *x = 0; x != in; x++) {}"));
+  EXPECT_EQ(FormatStyle::LK_ObjC,
+guessLanguage("foo.h", "for (Foo *x in bar) {}"));
+  EXPECT_EQ(FormatStyle::LK_ObjC,
+guessLanguage("foo.h", "for (Foo *x in [bar baz]) {}"));
+  EXPECT_EQ(FormatStyle::LK_ObjC,
+guessLanguage("foo.h", "for (Foo *x in [bar baz:blech]) {}"));
+  EXPECT_EQ(
+  FormatStyle::LK_ObjC,
+  guessLanguage("foo.h", "for (Foo *x in [bar baz:blech, 1, 2, 3, 0]) 
{}"));
+  EXPECT_EQ(FormatStyle::LK_ObjC,
+guessLanguage("foo.h", "for (Foo *x in [bar baz:^{[uh oh];}]) 
{}"));
+  EXPECT_EQ(FormatStyle::LK_Cpp,
+guessLanguage("foo.h", "Foo *x; for (x = 0; x != in; x++) {}"));
+  EXPECT_EQ(FormatStyle::LK_ObjC,
+guessLanguage("foo.h", "Foo *x; for (x in y) {}"));
+  EXPECT_EQ(
+  FormatStyle::LK_Cpp,
+  guessLanguage(
+  "foo.h",
+  "for (const Foo& baz = in.value(); !baz.at_end(); ++baz) {}"));
+}
+
 } // end namespace
 } // end namespace format
 } // end namespace clang
Index: cfe/trunk/unittests/Format/FormatTestObjC.cpp
===
--- cfe/trunk/unittests/Format/FormatTestObjC.cpp
+++ cfe/trunk/unittests/Format/FormatTestObjC.cpp
@@ -893,6 +893,13 @@
"foo(n);\n"
"  }\n"
"}");
+  verifyFormat("for (Foo *x in bar) {\n}");
+  verifyFormat("for (Foo *x in [bar baz]) {\n}");
+  verifyFormat("for (Foo *x in [bar baz:blech]) {\n}");
+  verifyFormat("for (Foo *x in [bar baz:blech, 1, 2, 3, 0]) {\n}");
+  verifyFormat("for (Foo *x in [bar baz:^{\n"
+   "   [uh oh];\n"
+   " }]) {\n}");
 }
 
 TEST_F(FormatTestObjC, ObjCLiterals) {


Index: cfe/trunk/lib/Format/TokenAnnotator.cpp

[PATCH] D43197: [OpenMP] Add flag for linking runtime bitcode library

2018-03-06 Thread Gheorghe-Teodor Bercea via Phabricator via cfe-commits
gtbercea updated this revision to Diff 137219.
gtbercea added a comment.

Address comments.


Repository:
  rC Clang

https://reviews.llvm.org/D43197

Files:
  include/clang/Basic/DiagnosticDriverKinds.td
  lib/Driver/ToolChains/Cuda.cpp
  test/Driver/openmp-offload-gpu.c


Index: test/Driver/openmp-offload-gpu.c
===
--- test/Driver/openmp-offload-gpu.c
+++ test/Driver/openmp-offload-gpu.c
@@ -142,3 +142,25 @@
 // RUN:   | FileCheck -check-prefix=CHK-NOLIBDEVICE %s
 
 // CHK-NOLIBDEVICE-NOT: error:{{.*}}sm_60
+
+/// ###
+
+/// Check that the runtime bitcode library is part of the compile line. Create 
a bogus
+/// bitcode library and add it to the LIBRARY_PATH.
+// RUN:   touch %T/libomptarget-nvptx-sm_60.bc
+// RUN:   env LIBRARY_PATH=%T %clang -### -fopenmp=libomp 
-fopenmp-targets=nvptx64-nvidia-cuda \
+// RUN:   -Xopenmp-target -march=sm_60 -fopenmp-relocatable-target -save-temps 
\
+// RUN:   -no-canonical-prefixes %s 2>&1 | FileCheck -check-prefix=CHK-BCLIB %s
+// RUN:   rm %T/libomptarget-nvptx-sm_60.bc
+
+// CHK-BCLIB: 
clang{{.*}}-triple{{.*}}nvptx64-nvidia-cuda{{.*}}-mlink-cuda-bitcode{{.*}}libomptarget-nvptx-sm_60.bc
+
+/// ###
+
+/// Check that the warning is thrown when the libomptarget bitcode library is 
not found.
+/// Libomptarget requires sm_35 or newer so an sm_20 bitcode library should 
never exist.
+// RUN:   %clang -### -fopenmp=libomp -fopenmp-targets=nvptx64-nvidia-cuda \
+// RUN:   -Xopenmp-target -march=sm_20 -fopenmp-relocatable-target -save-temps 
\
+// RUN:   -no-canonical-prefixes %s 2>&1 | FileCheck 
-check-prefix=CHK-BCLIB-WARN %s
+
+// CHK-BCLIB-WARN: Expect degraded performance on the target device due to 
missing 'libomptarget-nvptx-sm_20.bc' in LIBRARY_PATH.
Index: lib/Driver/ToolChains/Cuda.cpp
===
--- lib/Driver/ToolChains/Cuda.cpp
+++ lib/Driver/ToolChains/Cuda.cpp
@@ -21,6 +21,7 @@
 #include "llvm/Option/ArgList.h"
 #include "llvm/Support/FileSystem.h"
 #include "llvm/Support/Path.h"
+#include "llvm/Support/Process.h"
 #include "llvm/Support/Program.h"
 #include 
 
@@ -580,6 +581,43 @@
 CC1Args.push_back("-target-feature");
 CC1Args.push_back("+ptx42");
   }
+
+  if (DeviceOffloadingKind == Action::OFK_OpenMP) {
+SmallVector LibraryPaths;
+// Add path to lib and/or lib64 folders.
+SmallString<256> DefaultLibPath =
+  llvm::sys::path::parent_path(getDriver().Dir);
+llvm::sys::path::append(DefaultLibPath,
+Twine("lib") + CLANG_LIBDIR_SUFFIX);
+LibraryPaths.emplace_back(DefaultLibPath.c_str());
+
+// Add user defined library paths from LIBRARY_PATH.
+if (llvm::Optional LibPath =
+  llvm::sys::Process::GetEnv("LIBRARY_PATH")) {
+  SmallVector Frags;
+  const char EnvPathSeparatorStr[] = {llvm::sys::EnvPathSeparator, '\0'};
+  llvm::SplitString(*LibPath, Frags, EnvPathSeparatorStr);
+  for (auto Path : Frags)
+LibraryPaths.emplace_back(Path.trim());
+}
+
+std::string LibOmpTargetName =
+  "libomptarget-nvptx-" + GpuArch.str() + ".bc";
+bool FoundBCLibrary = false;
+for (const std::string &LibraryPath : LibraryPaths) {
+  SmallString<128> LibOmpTargetFile(LibraryPath);
+  llvm::sys::path::append(LibOmpTargetFile, LibOmpTargetName);
+  if (llvm::sys::fs::exists(LibOmpTargetFile)) {
+CC1Args.push_back("-mlink-cuda-bitcode");
+CC1Args.push_back(DriverArgs.MakeArgString(LibOmpTargetFile));
+FoundBCLibrary = true;
+break;
+  }
+}
+if (!FoundBCLibrary)
+  getDriver().Diag(diag::remark_drv_omp_offload_target_missingbcruntime)
+  << LibOmpTargetName;
+  }
 }
 
 void CudaToolChain::AddCudaIncludeArgs(const ArgList &DriverArgs,
Index: include/clang/Basic/DiagnosticDriverKinds.td
===
--- include/clang/Basic/DiagnosticDriverKinds.td
+++ include/clang/Basic/DiagnosticDriverKinds.td
@@ -203,6 +203,9 @@
 def warn_drv_omp_offload_target_duplicate : Warning<
   "The OpenMP offloading target '%0' is similar to target '%1' already 
specified - will be ignored.">, 
   InGroup;
+def remark_drv_omp_offload_target_missingbcruntime : Warning<
+  "Expect degraded performance on the target device due to missing '%0' in 
LIBRARY_PATH.">,
+  InGroup;
 def err_drv_bitcode_unsupported_on_toolchain : Error<
   "-fembed-bitcode is not supported on versions of iOS prior to 6.0">;
 


Index: test/Driver/openmp-offload-gpu.c
===
--- test/Driver/openmp-offload-gpu.c
+++ test/Driver/openmp-offload-gpu.c
@@ -142,3 +142,25 @@
 // RUN:   | FileCheck -check-prefix=CHK-NOLIBDEVICE %s
 
 // CHK-NOLIBDEVICE-NOT: error:{{.*}}sm_60
+
+/// ##

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

2018-03-06 Thread Yaxun Liu via Phabricator via cfe-commits
yaxunl added inline comments.



Comment at: lib/CodeGen/CGBlocks.cpp:1065-1067
+  llvm::Value *FuncPtr;
 
+  if (!CGM.getLangOpts().OpenCL) {

bader wrote:
> I think it would be more readable if we merge this if statement with the if 
> statement at the line #1103.
> It's used to initialize FuncPtr for non-OpenCL languages and the first use of 
> this variable is in the else block of if statement at the line #1103.
> If I didn't miss something it should reasonable to combine this if block with 
> 'else' block at the line #1106.
BlockPtr is used on line 1093, so it cannot be moved to line 1106.


https://reviews.llvm.org/D43783



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


[PATCH] D43197: [OpenMP] Add flag for linking runtime bitcode library

2018-03-06 Thread Alexey Bataev via Phabricator via cfe-commits
ABataev added inline comments.



Comment at: include/clang/Basic/DiagnosticDriverKinds.td:207-208
+def remark_drv_omp_offload_target_missingbcruntime : Warning<
+  "Expect degraded performance on the target device due to missing '%0' in 
LIBRARY_PATH.">,
+  InGroup;
 def err_drv_bitcode_unsupported_on_toolchain : Error<

Fix the message in the warning, it does not follow the logic of the patch



Comment at: lib/Driver/ToolChains/Cuda.cpp:586
+  if (DeviceOffloadingKind == Action::OFK_OpenMP) {
+SmallVector LibraryPaths;
+// Add path to lib and/or lib64 folders.

Do you really need `std::string` here? Or StringRef is enough?


Repository:
  rC Clang

https://reviews.llvm.org/D43197



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


[libclc] r326816 - Move cl_khr_fp64 exntension enablement to gentype include lists

2018-03-06 Thread Jan Vesely via cfe-commits
Author: jvesely
Date: Tue Mar  6 09:48:35 2018
New Revision: 326816

URL: http://llvm.org/viewvc/llvm-project?rev=326816&view=rev
Log:
Move cl_khr_fp64 exntension enablement to gentype include lists

This will make adding cl_khr_fp16 support easier

Reviewed-by: Aaron Watry 
Signed-off-by: Jan Vesely 

Modified:
libclc/trunk/generic/include/clc/async/gentype.inc
libclc/trunk/generic/include/clc/geometric/floatn.inc
libclc/trunk/generic/include/clc/math/binary_intrin.inc
libclc/trunk/generic/include/clc/math/ternary_intrin.inc
libclc/trunk/generic/include/clc/math/unary_intrin.inc
libclc/trunk/generic/lib/async/async_work_group_copy.cl
libclc/trunk/generic/lib/async/async_work_group_strided_copy.cl
libclc/trunk/generic/lib/async/prefetch.cl
libclc/trunk/generic/lib/common/mix.cl
libclc/trunk/generic/lib/geometric/distance.cl
libclc/trunk/generic/lib/math/acos.cl
libclc/trunk/generic/lib/math/asin.cl
libclc/trunk/generic/lib/math/clc_sqrt.cl
libclc/trunk/generic/lib/math/exp10.cl
libclc/trunk/generic/lib/math/fdim.cl
libclc/trunk/generic/lib/math/fract.cl
libclc/trunk/generic/lib/math/frexp.cl
libclc/trunk/generic/lib/math/hypot.cl
libclc/trunk/generic/lib/math/lgamma_r.cl
libclc/trunk/generic/lib/math/log10.cl
libclc/trunk/generic/lib/math/mad.cl
libclc/trunk/generic/lib/math/modf.cl
libclc/trunk/generic/lib/math/sincos.cl
libclc/trunk/generic/lib/shared/clamp.cl
libclc/trunk/generic/lib/shared/max.cl
libclc/trunk/generic/lib/shared/min.cl

Modified: libclc/trunk/generic/include/clc/async/gentype.inc
URL: 
http://llvm.org/viewvc/llvm-project/libclc/trunk/generic/include/clc/async/gentype.inc?rev=326816&r1=326815&r2=326816&view=diff
==
--- libclc/trunk/generic/include/clc/async/gentype.inc (original)
+++ libclc/trunk/generic/include/clc/async/gentype.inc Tue Mar  6 09:48:35 2018
@@ -180,6 +180,7 @@
 #undef __CLC_GENTYPE
 
 #ifdef cl_khr_fp64
+#pragma OPENCL EXTENSION cl_khr_fp64 : enable
 
 #define __CLC_GENTYPE double
 #include __CLC_BODY
@@ -202,3 +203,5 @@
 #undef __CLC_GENTYPE
 
 #endif
+
+#undef __CLC_BODY

Modified: libclc/trunk/generic/include/clc/geometric/floatn.inc
URL: 
http://llvm.org/viewvc/llvm-project/libclc/trunk/generic/include/clc/geometric/floatn.inc?rev=326816&r1=326815&r2=326816&view=diff
==
--- libclc/trunk/generic/include/clc/geometric/floatn.inc (original)
+++ libclc/trunk/generic/include/clc/geometric/floatn.inc Tue Mar  6 09:48:35 
2018
@@ -24,6 +24,7 @@
 
 #ifndef __FLOAT_ONLY
 #ifdef cl_khr_fp64
+#pragma OPENCL EXTENSION cl_khr_fp64 : enable
 
 #define __CLC_FLOAT double
 #define __CLC_FPSIZE 64

Modified: libclc/trunk/generic/include/clc/math/binary_intrin.inc
URL: 
http://llvm.org/viewvc/llvm-project/libclc/trunk/generic/include/clc/math/binary_intrin.inc?rev=326816&r1=326815&r2=326816&view=diff
==
--- libclc/trunk/generic/include/clc/math/binary_intrin.inc (original)
+++ libclc/trunk/generic/include/clc/math/binary_intrin.inc Tue Mar  6 09:48:35 
2018
@@ -6,6 +6,7 @@ _CLC_OVERLOAD float8 __CLC_FUNCTION(floa
 _CLC_OVERLOAD float16 __CLC_FUNCTION(float16, float16) __asm(__CLC_INTRINSIC 
".v16f32");
 
 #ifdef cl_khr_fp64
+#pragma OPENCL EXTENSION cl_khr_fp64 : enable
 _CLC_OVERLOAD double __CLC_FUNCTION(double, double) __asm(__CLC_INTRINSIC 
".f64");
 _CLC_OVERLOAD double2 __CLC_FUNCTION(double2, double2) __asm(__CLC_INTRINSIC 
".v2f64");
 _CLC_OVERLOAD double3 __CLC_FUNCTION(double3, double3) __asm(__CLC_INTRINSIC 
".v3f64");

Modified: libclc/trunk/generic/include/clc/math/ternary_intrin.inc
URL: 
http://llvm.org/viewvc/llvm-project/libclc/trunk/generic/include/clc/math/ternary_intrin.inc?rev=326816&r1=326815&r2=326816&view=diff
==
--- libclc/trunk/generic/include/clc/math/ternary_intrin.inc (original)
+++ libclc/trunk/generic/include/clc/math/ternary_intrin.inc Tue Mar  6 
09:48:35 2018
@@ -6,6 +6,7 @@ _CLC_OVERLOAD float8 __CLC_FUNCTION(floa
 _CLC_OVERLOAD float16 __CLC_FUNCTION(float16, float16, float16) 
__asm(__CLC_INTRINSIC ".v16f32");
 
 #ifdef cl_khr_fp64
+#pragma OPENCL EXTENSION cl_khr_fp64 : enable
 _CLC_OVERLOAD double __CLC_FUNCTION(double, double, double) 
__asm(__CLC_INTRINSIC ".f64");
 _CLC_OVERLOAD double2 __CLC_FUNCTION(double2, double2, double2) 
__asm(__CLC_INTRINSIC ".v2f64");
 _CLC_OVERLOAD double3 __CLC_FUNCTION(double3, double3, double3) 
__asm(__CLC_INTRINSIC ".v3f64");

Modified: libclc/trunk/generic/include/clc/math/unary_intrin.inc
URL: 
http://llvm.org/viewvc/llvm-project/libclc/trunk/generic/include/clc/math/unary_intrin.inc?rev=326816&r1=326815&r2=326816&view=diff
==
--- li

[libclc] r326817 - maxmag: Condition variable needs to be the same bitwidth as operands

2018-03-06 Thread Jan Vesely via cfe-commits
Author: jvesely
Date: Tue Mar  6 09:48:38 2018
New Revision: 326817

URL: http://llvm.org/viewvc/llvm-project?rev=326817&view=rev
Log:
maxmag: Condition variable needs to be the same bitwidth as operands

No changes wrt CTS

Reviewed-by: Aaron Watry 
Signed-off-by: Jan Vesely 

Modified:
libclc/trunk/generic/lib/math/maxmag.cl
libclc/trunk/generic/lib/math/maxmag.inc

Modified: libclc/trunk/generic/lib/math/maxmag.cl
URL: 
http://llvm.org/viewvc/llvm-project/libclc/trunk/generic/lib/math/maxmag.cl?rev=326817&r1=326816&r2=326817&view=diff
==
--- libclc/trunk/generic/lib/math/maxmag.cl (original)
+++ libclc/trunk/generic/lib/math/maxmag.cl Tue Mar  6 09:48:38 2018
@@ -1,4 +1,5 @@
 #include 
+#include 
 
 #define __CLC_BODY 
 #include 

Modified: libclc/trunk/generic/lib/math/maxmag.inc
URL: 
http://llvm.org/viewvc/llvm-project/libclc/trunk/generic/lib/math/maxmag.inc?rev=326817&r1=326816&r2=326817&view=diff
==
--- libclc/trunk/generic/lib/math/maxmag.inc (original)
+++ libclc/trunk/generic/lib/math/maxmag.inc Tue Mar  6 09:48:38 2018
@@ -1,4 +1,22 @@
+#ifdef __CLC_SCALAR
+#define __CLC_VECSIZE
+#endif
+
+#if __CLC_FPSIZE == 64
+#define __CLC_CONVERT_NATN __CLC_XCONCAT(convert_long, __CLC_VECSIZE)
+#elif __CLC_FPSIZE == 32
+#define __CLC_CONVERT_NATN __CLC_XCONCAT(convert_int, __CLC_VECSIZE)
+#elif __CLC_FPSIZE == 16
+#define __CLC_CONVERT_NATN __CLC_XCONCAT(convert_short, __CLC_VECSIZE)
+#endif
+
 _CLC_OVERLOAD _CLC_DEF __CLC_GENTYPE maxmag(__CLC_GENTYPE x, __CLC_GENTYPE y) {
-  const __CLC_GENTYPE res = select(y, x, isgreater(fabs(x), fabs(y)));
-  return select(res, fmax(x, y), isnan(x) | isnan(y) | isequal(fabs(x), 
fabs(y)));
+  const __CLC_GENTYPE res = select(y, x, __CLC_CONVERT_NATN(isgreater(fabs(x), 
fabs(y;
+  return select(res, fmax(x, y), __CLC_CONVERT_NATN(isnan(x) | isnan(y) | 
isequal(fabs(x), fabs(y;
 }
+
+#undef __CLC_CONVERT_NATN
+
+#ifdef __CLC_SCALAR
+#undef __CLC_VECSIZE
+#endif


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


[libclc] r326818 - minmag: Condition variable needs to be the same bitwidth as operands

2018-03-06 Thread Jan Vesely via cfe-commits
Author: jvesely
Date: Tue Mar  6 09:48:40 2018
New Revision: 326818

URL: http://llvm.org/viewvc/llvm-project?rev=326818&view=rev
Log:
minmag: Condition variable needs to be the same bitwidth as operands

No changes wrt CTS

Reviewed-by: Aaron Watry 
Signed-off-by: Jan Vesely 

Modified:
libclc/trunk/generic/lib/math/minmag.cl
libclc/trunk/generic/lib/math/minmag.inc

Modified: libclc/trunk/generic/lib/math/minmag.cl
URL: 
http://llvm.org/viewvc/llvm-project/libclc/trunk/generic/lib/math/minmag.cl?rev=326818&r1=326817&r2=326818&view=diff
==
--- libclc/trunk/generic/lib/math/minmag.cl (original)
+++ libclc/trunk/generic/lib/math/minmag.cl Tue Mar  6 09:48:40 2018
@@ -1,4 +1,5 @@
 #include 
+#include 
 
 #define __CLC_BODY 
 #include 

Modified: libclc/trunk/generic/lib/math/minmag.inc
URL: 
http://llvm.org/viewvc/llvm-project/libclc/trunk/generic/lib/math/minmag.inc?rev=326818&r1=326817&r2=326818&view=diff
==
--- libclc/trunk/generic/lib/math/minmag.inc (original)
+++ libclc/trunk/generic/lib/math/minmag.inc Tue Mar  6 09:48:40 2018
@@ -1,4 +1,22 @@
+#ifdef __CLC_SCALAR
+#define __CLC_VECSIZE
+#endif
+
+#if __CLC_FPSIZE == 64
+#define __CLC_CONVERT_NATN __CLC_XCONCAT(convert_long, __CLC_VECSIZE)
+#elif __CLC_FPSIZE == 32
+#define __CLC_CONVERT_NATN __CLC_XCONCAT(convert_int, __CLC_VECSIZE)
+#elif __CLC_FPSIZE == 16
+#define __CLC_CONVERT_NATN __CLC_XCONCAT(convert_short, __CLC_VECSIZE)
+#endif
+
 _CLC_OVERLOAD _CLC_DEF __CLC_GENTYPE minmag(__CLC_GENTYPE x, __CLC_GENTYPE y) {
-  const __CLC_GENTYPE res = select(y, x, isless(fabs(x), fabs(y)));
-  return select(res, fmin(x, y), isnan(x) | isnan(y) | isequal(fabs(x), 
fabs(y)));
+  const __CLC_GENTYPE res = select(y, x, __CLC_CONVERT_NATN(isless(fabs(x), 
fabs(y;
+  return select(res, fmin(x, y), __CLC_CONVERT_NATN(isnan(x) | isnan(y) | 
isequal(fabs(x), fabs(y;
 }
+
+#undef __CLC_CONVERT_NATN
+
+#ifdef __CLC_SCALAR
+#undef __CLC_VECSIZE
+#endif


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


[libclc] r326819 - select: Add vector implementation

2018-03-06 Thread Jan Vesely via cfe-commits
Author: jvesely
Date: Tue Mar  6 09:48:43 2018
New Revision: 326819

URL: http://llvm.org/viewvc/llvm-project?rev=326819&view=rev
Log:
select: Add vector implementation

Passes CTS on Carrizo

Reviewed-by: Aaron Watry 
Signed-off-by: Jan Vesely 

Added:
libclc/trunk/generic/include/clc/relational/select.inc
libclc/trunk/generic/lib/relational/select.cl
libclc/trunk/generic/lib/relational/select.inc
Modified:
libclc/trunk/generic/include/clc/relational/select.h
libclc/trunk/generic/lib/SOURCES

Modified: libclc/trunk/generic/include/clc/relational/select.h
URL: 
http://llvm.org/viewvc/llvm-project/libclc/trunk/generic/include/clc/relational/select.h?rev=326819&r1=326818&r2=326819&view=diff
==
--- libclc/trunk/generic/include/clc/relational/select.h (original)
+++ libclc/trunk/generic/include/clc/relational/select.h Tue Mar  6 09:48:43 
2018
@@ -1 +1,11 @@
-#define select(a, b, c) ((c) ? (b) : (a))
+/* Duplciate these so we don't have to distribute utils.h */
+#define __CLC_CONCAT(x, y) x ## y
+#define __CLC_XCONCAT(x, y) __CLC_CONCAT(x, y)
+
+#define __CLC_BODY 
+#include 
+#define __CLC_BODY 
+#include 
+
+#undef __CLC_CONCAT
+#undef __CLC_XCONCAT

Added: libclc/trunk/generic/include/clc/relational/select.inc
URL: 
http://llvm.org/viewvc/llvm-project/libclc/trunk/generic/include/clc/relational/select.inc?rev=326819&view=auto
==
--- libclc/trunk/generic/include/clc/relational/select.inc (added)
+++ libclc/trunk/generic/include/clc/relational/select.inc Tue Mar  6 09:48:43 
2018
@@ -0,0 +1,25 @@
+#ifdef __CLC_SCALAR
+#define __CLC_VECSIZE
+#endif
+
+#if __CLC_FPSIZE == 64
+#define __CLC_S_GENTYPE __CLC_XCONCAT(long, __CLC_VECSIZE)
+#define __CLC_U_GENTYPE __CLC_XCONCAT(ulong, __CLC_VECSIZE)
+#elif __CLC_FPSIZE == 32
+#define __CLC_S_GENTYPE __CLC_XCONCAT(int, __CLC_VECSIZE)
+#define __CLC_U_GENTYPE __CLC_XCONCAT(uint, __CLC_VECSIZE)
+#elif __CLC_FPSIZE == 16
+#define __CLC_S_GENTYPE __CLC_XCONCAT(char, __CLC_VECSIZE)
+#define __CLC_U_GENTYPE __CLC_XCONCAT(uchar, __CLC_VECSIZE)
+#endif
+
+_CLC_OVERLOAD _CLC_DECL __CLC_GENTYPE select(__CLC_GENTYPE x, __CLC_GENTYPE y, 
__CLC_S_GENTYPE z);
+_CLC_OVERLOAD _CLC_DECL __CLC_GENTYPE select(__CLC_GENTYPE x, __CLC_GENTYPE y, 
__CLC_U_GENTYPE z);
+
+#ifdef __CLC_FPSIZE
+#undef __CLC_S_GENTYPE
+#undef __CLC_U_GENTYPE
+#endif
+#ifdef __CLC_SCALAR
+#undef __CLC_VECSIZE
+#endif

Modified: libclc/trunk/generic/lib/SOURCES
URL: 
http://llvm.org/viewvc/llvm-project/libclc/trunk/generic/lib/SOURCES?rev=326819&r1=326818&r2=326819&view=diff
==
--- libclc/trunk/generic/lib/SOURCES (original)
+++ libclc/trunk/generic/lib/SOURCES Tue Mar  6 09:48:43 2018
@@ -189,6 +189,7 @@ relational/isnormal.cl
 relational/isnotequal.cl
 relational/isordered.cl
 relational/isunordered.cl
+relational/select.cl
 relational/signbit.cl
 shared/clamp.cl
 shared/max.cl

Added: libclc/trunk/generic/lib/relational/select.cl
URL: 
http://llvm.org/viewvc/llvm-project/libclc/trunk/generic/lib/relational/select.cl?rev=326819&view=auto
==
--- libclc/trunk/generic/lib/relational/select.cl (added)
+++ libclc/trunk/generic/lib/relational/select.cl Tue Mar  6 09:48:43 2018
@@ -0,0 +1,7 @@
+#include 
+#include 
+
+#define __CLC_BODY 
+#include 
+#define __CLC_BODY 
+#include 

Added: libclc/trunk/generic/lib/relational/select.inc
URL: 
http://llvm.org/viewvc/llvm-project/libclc/trunk/generic/lib/relational/select.inc?rev=326819&view=auto
==
--- libclc/trunk/generic/lib/relational/select.inc (added)
+++ libclc/trunk/generic/lib/relational/select.inc Tue Mar  6 09:48:43 2018
@@ -0,0 +1,47 @@
+#ifdef __CLC_SCALAR
+#define __CLC_VECSIZE
+#endif
+
+#if __CLC_FPSIZE == 64
+#define __CLC_S_GENTYPE __CLC_XCONCAT(long, __CLC_VECSIZE)
+#define __CLC_U_GENTYPE __CLC_XCONCAT(ulong, __CLC_VECSIZE)
+#elif __CLC_FPSIZE == 32
+#define __CLC_S_GENTYPE __CLC_XCONCAT(int, __CLC_VECSIZE)
+#define __CLC_U_GENTYPE __CLC_XCONCAT(uint, __CLC_VECSIZE)
+#elif __CLC_FPSIZE == 16
+#define __CLC_S_GENTYPE __CLC_XCONCAT(char, __CLC_VECSIZE)
+#define __CLC_U_GENTYPE __CLC_XCONCAT(uchar, __CLC_VECSIZE)
+#endif
+#ifdef __CLC_FPSIZE
+#define __CLC_GENSIZE   __CLC_FPSIZE
+#endif
+
+#define __CLC_AS_S_GENTYPE __CLC_XCONCAT(as_, __CLC_S_GENTYPE)
+#define __CLC_AS_GENTYPE __CLC_XCONCAT(as_, __CLC_GENTYPE)
+
+_CLC_OVERLOAD _CLC_DEF __CLC_GENTYPE select(__CLC_GENTYPE x, __CLC_GENTYPE y, 
__CLC_S_GENTYPE z)
+{
+#ifdef __CLC_SCALAR
+   return z ? y : x;
+#else
+   __CLC_S_GENTYPE bitmask = z >> (__CLC_GENSIZE - 1);
+   return __CLC_AS_GENTYPE(bitselect(__CLC_AS_S_GENTYPE(x), 
__CLC_AS_S_GENTYPE(y), bitmask));
+#endif
+}
+
+_CLC_OVERLOAD _CLC_DEF __CLC_

[libclc] r326820 - frexp: Reuse types provided by gentype.inc

2018-03-06 Thread Jan Vesely via cfe-commits
Author: jvesely
Date: Tue Mar  6 09:48:45 2018
New Revision: 326820

URL: http://llvm.org/viewvc/llvm-project?rev=326820&view=rev
Log:
frexp: Reuse types provided by gentype.inc

v2: Use select instead of bitselect to consolidate scalar and vector
versions

Passes CTS on Carrizo

Reviewed-by: Aaron Watry 
Signed-off-by: Jan Vesely 

Modified:
libclc/trunk/generic/lib/math/frexp.cl
libclc/trunk/generic/lib/math/frexp.inc

Modified: libclc/trunk/generic/lib/math/frexp.cl
URL: 
http://llvm.org/viewvc/llvm-project/libclc/trunk/generic/lib/math/frexp.cl?rev=326820&r1=326819&r2=326820&view=diff
==
--- libclc/trunk/generic/lib/math/frexp.cl (original)
+++ libclc/trunk/generic/lib/math/frexp.cl Tue Mar  6 09:48:45 2018
@@ -1,6 +1,17 @@
 #include 
+#include 
 
-#include "math.h"
+#define __CLC_BODY 
+#define __CLC_ADDRESS_SPACE private
+#include 
+#undef __CLC_ADDRESS_SPACE
+
+#define __CLC_BODY 
+#define __CLC_ADDRESS_SPACE global
+#include 
+#undef __CLC_ADDRESS_SPACE
 
 #define __CLC_BODY 
+#define __CLC_ADDRESS_SPACE local
 #include 
+#undef __CLC_ADDRESS_SPACE

Modified: libclc/trunk/generic/lib/math/frexp.inc
URL: 
http://llvm.org/viewvc/llvm-project/libclc/trunk/generic/lib/math/frexp.inc?rev=326820&r1=326819&r2=326820&view=diff
==
--- libclc/trunk/generic/lib/math/frexp.inc (original)
+++ libclc/trunk/generic/lib/math/frexp.inc Tue Mar  6 09:48:45 2018
@@ -20,91 +20,55 @@
  * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  * THE SOFTWARE.
  */
+
+#define __CLC_AS_GENTYPE __CLC_XCONCAT(as_, __CLC_GENTYPE)
+#define __CLC_AS_INTN __CLC_XCONCAT(as_, __CLC_INTN)
+
 #if __CLC_FPSIZE == 32
-#ifdef __CLC_SCALAR
-_CLC_OVERLOAD _CLC_DEF __CLC_GENTYPE frexp(float x, private int *ep) {
-int i = as_int(x);
-int ai = i & 0x7fff;
-int d = ai > 0 & ai < 0x0080;
-// scale subnormal by 2^26 without multiplying
-float s = as_float(ai | 0x0d80) - 0x1.0p-100F;
-ai = d ? as_int(s) : ai;
-int e = (ai >> 23) - 126 - (d ? 26 : 0);
-int t = ai == 0 | e == 129;
-i = (i & 0x8000) | 0x3f00 | (ai & 0x007f);
-*ep = t ? 0 : e;
-return t ? x : as_float(i);
+_CLC_OVERLOAD _CLC_DEF __CLC_GENTYPE frexp(__CLC_GENTYPE x, 
__CLC_ADDRESS_SPACE __CLC_INTN *ep) {
+__CLC_INTN i = __CLC_AS_INTN(x);
+__CLC_INTN ai = i & 0x7fff;
+__CLC_INTN d = ai > 0 & ai < 0x0080;
+/* scale subnormal by 2^26 without multiplying */
+__CLC_GENTYPE s = __CLC_AS_GENTYPE(ai | 0x0d80) - 0x1.0p-100f;
+ai = select(ai, __CLC_AS_INTN(s), d);
+__CLC_INTN e = (ai >> 23) - 126 - select((__CLC_INTN)0, (__CLC_INTN)26, d);
+__CLC_INTN t = ai == (__CLC_INTN)0 | e == (__CLC_INTN)129;
+i = (i & (__CLC_INTN)0x8000) | (__CLC_INTN)0x3f00 | (ai & 
0x007f);
+*ep = select(e, (__CLC_INTN)0, t);
+return select(__CLC_AS_GENTYPE(i), x, t);
 }
-#define __CLC_FREXP_VEC(width) \
-_CLC_OVERLOAD _CLC_DEF float##width frexp(float##width x, private int##width 
*ep) { \
-int##width i = as_int##width(x); \
-int##width ai = i & 0x7fff; \
-int##width d = ai > 0 & ai < 0x0080; \
-/* scale subnormal by 2^26 without multiplying */ \
-float##width s = as_float##width(ai | 0x0d80) - 0x1.0p-100F; \
-ai = bitselect(ai, as_int##width(s), d); \
-int##width e = (ai >> 23) - 126 - bitselect((int##width)0, (int##width)26, 
d); \
-int##width t = ai == (int##width)0 | e == (int##width)129; \
-i = (i & (int##width)0x8000) | (int##width)0x3f00 | (ai & 
0x007f); \
-*ep = bitselect(e, (int##width)0, t); \
-return bitselect(as_float##width(i), x, as_float##width(t)); \
-}
-__CLC_FREXP_VEC(2)
-__CLC_FREXP_VEC(3)
-__CLC_FREXP_VEC(4)
-__CLC_FREXP_VEC(8)
-__CLC_FREXP_VEC(16)
-#undef __CLC_FREXP_VEC
-#endif
 #endif
 
 #if __CLC_FPSIZE == 64
 #ifdef __CLC_SCALAR
-_CLC_OVERLOAD _CLC_DEF __CLC_GENTYPE frexp(__CLC_GENTYPE x, private __CLC_INTN 
*ep) {
-long i = as_long(x);
-long ai = i & 0x7fffL;
-int d = ai > 0 & ai < 0x0010L;
-// scale subnormal by 2^54 without multiplying
-double s = as_double(ai | 0x0370L) - 0x1.0p-968;
-ai = d ? as_long(s) : ai;
-int e = (int)(ai >> 52) - 1022 - (d ? 54 : 0);
-int t = ai == 0 | e == 1025;
-i = (i & 0x8000L) | 0x3fe0L | (ai & 
0x000fL);
-*ep = t ? 0 : e;
-return t ? x : as_double(i);
-}
-#define __CLC_FREXP_VEC(width) \
-_CLC_OVERLOAD _CLC_DEF double##width frexp(double##width x, private int##width 
*ep) { \
-long##width i = as_long##width(x); \
-long##width ai = i & 0x7fffL; \
-long##width d = ai > 0 & ai < 0x0010L; \
-/* scale subnormal by 2^54 without multiplying */ \
-double##width s = as_double##width(ai | 0x0370L) - 0x1.0p-968; 
\
-a

[libclc] r326821 - lgamma_r: Move code from .inc to .cl file

2018-03-06 Thread Jan Vesely via cfe-commits
Author: jvesely
Date: Tue Mar  6 09:48:47 2018
New Revision: 326821

URL: http://llvm.org/viewvc/llvm-project?rev=326821&view=rev
Log:
lgamma_r: Move code from .inc to .cl file

Reviewed-by: Aaron Watry 
Signed-off-by: Jan Vesely 

Modified:
libclc/trunk/generic/lib/math/lgamma_r.cl
libclc/trunk/generic/lib/math/lgamma_r.inc

Modified: libclc/trunk/generic/lib/math/lgamma_r.cl
URL: 
http://llvm.org/viewvc/llvm-project/libclc/trunk/generic/lib/math/lgamma_r.cl?rev=326821&r1=326820&r2=326821&view=diff
==
--- libclc/trunk/generic/lib/math/lgamma_r.cl (original)
+++ libclc/trunk/generic/lib/math/lgamma_r.cl Tue Mar  6 09:48:47 2018
@@ -1,7 +1,498 @@
+/*
+ * Copyright (c) 2014 Advanced Micro Devices, Inc.
+ * Copyright (c) 2016 Aaron Watry 
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to 
deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING 
FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ * THE SOFTWARE.
+ */
+
 #include 
 
 #include "../clcmacro.h"
 #include "math.h"
 
+/*
+ * 
+ * Copyright (C) 1993 by Sun Microsystems, Inc. All rights reserved.
+ *
+ * Developed at SunPro, a Sun Microsystems, Inc. business.
+ * Permission to use, copy, modify, and distribute this
+ * software is freely granted, provided that this notice
+ * is preserved.
+ * 
+ */
+
+#define pi_f   3.1415927410e+00f/* 0x40490fdb */
+
+#define a0_f   7.7215664089e-02f/* 0x3d9e233f */
+#define a1_f   3.2246702909e-01f/* 0x3ea51a66 */
+#define a2_f   6.7352302372e-02f/* 0x3d89f001 */
+#define a3_f   2.0580807701e-02f/* 0x3ca89915 */
+#define a4_f   7.3855509982e-03f/* 0x3bf2027e */
+#define a5_f   2.8905137442e-03f/* 0x3b3d6ec6 */
+#define a6_f   1.1927076848e-03f/* 0x3a9c54a1 */
+#define a7_f   5.1006977446e-04f/* 0x3a05b634 */
+#define a8_f   2.2086278477e-04f/* 0x39679767 */
+#define a9_f   1.0801156895e-04f/* 0x38e28445 */
+#define a10_f  2.5214456400e-05f/* 0x37d383a2 */
+#define a11_f  4.4864096708e-05f/* 0x383c2c75 */
+
+#define tc_f   1.4616321325e+00f/* 0x3fbb16c3 */
+
+#define tf_f  -1.2148628384e-01f/* 0xbdf8cdcd */
+/* tt -(tail of tf) */
+#define tt_f   6.6971006518e-09f/* 0x31e61c52 */
+
+#define t0_f   4.8383611441e-01f/* 0x3ef7b95e */
+#define t1_f  -1.4758771658e-01f/* 0xbe17213c */
+#define t2_f   6.4624942839e-02f/* 0x3d845a15 */
+#define t3_f  -3.2788541168e-02f/* 0xbd064d47 */
+#define t4_f   1.7970675603e-02f/* 0x3c93373d */
+#define t5_f  -1.0314224288e-02f/* 0xbc28fcfe */
+#define t6_f   6.1005386524e-03f/* 0x3bc7e707 */
+#define t7_f  -3.6845202558e-03f/* 0xbb7177fe */
+#define t8_f   2.2596477065e-03f/* 0x3b141699 */
+#define t9_f  -1.4034647029e-03f/* 0xbab7f476 */
+#define t10_f  8.8108185446e-04f/* 0x3a66f867 */
+#define t11_f -5.3859531181e-04f/* 0xba0d3085 */
+#define t12_f  3.1563205994e-04f/* 0x39a57b6b */
+#define t13_f -3.1275415677e-04f/* 0xb9a3f927 */
+#define t14_f  3.3552918467e-04f/* 0x39afe9f7 */
+
+#define u0_f  -7.7215664089e-02f/* 0xbd9e233f */
+#define u1_f   6.3282704353e-01f/* 0x3f2200f4 */
+#define u2_f   1.4549225569e+00f/* 0x3fba3ae7 */
+#define u3_f   9.7771751881e-01f/* 0x3f7a4bb2 */
+#define u4_f   2.2896373272e-01f/* 0x3e6a7578 */
+#define u5_f   1.3381091878e-02f/* 0x3c5b3c5e */
+
+#define v1_f   2.4559779167e+00f/* 0x401d2ebe */
+#define v2_f   2.1284897327e+00f/* 0x4008392d */
+#define v3_f   7.6928514242e-01f/* 0x3f44efdf */
+#define v4_f   1.0422264785e-01f/* 0x3dd572af */
+#define v5_f   3.2170924824e-03f/* 0x3b52d5db */
+
+#define s0_f  -7.7215664089e-02f/* 0xbd9e233f */
+#define s1_f   2.1498242021e-01f/* 0x3e5c245a */
+#define s2_f   3.2577878

[PATCH] D41102: Setup clang-doc frontend framework

2018-03-06 Thread Julie Hockett via Phabricator via cfe-commits
juliehockett added a comment.

In https://reviews.llvm.org/D41102#1028228, @Athosvk wrote:

> This seems like quite a decent approach! That being said, I don't see the 
> pointer yet? I assume you mean that you will be adding this? Additionally, a 
> slight disadvantage of doing this generic approach is that you need to do 
> bookkeeping on what it is referencing, but I guess there's no helping that 
> due to the architecture which makes you rely upon the USR? Personally I'd 
> prefer having the explicit types if and where possible. So for now a 
> RecordInfo has a vecotr of Reference's to its parents, but we know the 
> parents can only be of certain kinds (more than just a RecordType, but you 
> get the point); it won't be an enum, namespace or function.


If you take a look at the follow-on patch to this (D43341 
), you'll see that that is where the pointer 
is added in (since it is irrelevant to the mapper portion, as it cannot be 
filled out until the information has been reduced). The back references to 
children and whatnot are also added there.

> As I mentioned, we did this the other way around, which also has the slight 
> advantage that I only had to create and save the USR once per info instance 
> (as in, 10 references to a class only add the overhead of 10 pointers, rather 
> than each having the USR as well), but our disadvantage was of course that we 
> had delayed serialization (although we could arguably do both 
> simultaneously). It seems each method has its merits :).

The USRs are kept for serialization purposes -- given the modular nature of the 
design, the goal is to be able to write out the bitstream and have it be 
consumable with all necessary information. Since we can't write out pointers 
(and it would be useless if we did, since they would change as soon as the file 
was read in), we maintain the USRs to have a means of re-finding the referenced 
declaration.

That said, I was looking at the Clangd symbol indexing code yesterday, and 
noticed that they're hashing the USRs (since they get a little lengthy, 
particularly when you have nested and/or overloaded functions). I'm going to 
take a look at that today to try to make the USRs more space-efficient here.


https://reviews.llvm.org/D41102



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


[PATCH] D34365: [FrontEnd] Allow overriding the default C/C++ -std via CMake vars

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

Let's do this. I thought we'd already have a higher C++ standard version by 
now, but apparently not.


https://reviews.llvm.org/D34365



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


[PATCH] D43197: [OpenMP] Add flag for linking runtime bitcode library

2018-03-06 Thread Gheorghe-Teodor Bercea via Phabricator via cfe-commits
gtbercea updated this revision to Diff 137226.
gtbercea added a comment.

Address comments.


Repository:
  rC Clang

https://reviews.llvm.org/D43197

Files:
  include/clang/Basic/DiagnosticDriverKinds.td
  lib/Driver/ToolChains/Cuda.cpp
  test/Driver/openmp-offload-gpu.c


Index: test/Driver/openmp-offload-gpu.c
===
--- test/Driver/openmp-offload-gpu.c
+++ test/Driver/openmp-offload-gpu.c
@@ -142,3 +142,25 @@
 // RUN:   | FileCheck -check-prefix=CHK-NOLIBDEVICE %s
 
 // CHK-NOLIBDEVICE-NOT: error:{{.*}}sm_60
+
+/// ###
+
+/// Check that the runtime bitcode library is part of the compile line. Create 
a bogus
+/// bitcode library and add it to the LIBRARY_PATH.
+// RUN:   touch %T/libomptarget-nvptx-sm_60.bc
+// RUN:   env LIBRARY_PATH=%T %clang -### -fopenmp=libomp 
-fopenmp-targets=nvptx64-nvidia-cuda \
+// RUN:   -Xopenmp-target -march=sm_60 -fopenmp-relocatable-target -save-temps 
\
+// RUN:   -no-canonical-prefixes %s 2>&1 | FileCheck -check-prefix=CHK-BCLIB %s
+// RUN:   rm %T/libomptarget-nvptx-sm_60.bc
+
+// CHK-BCLIB: 
clang{{.*}}-triple{{.*}}nvptx64-nvidia-cuda{{.*}}-mlink-cuda-bitcode{{.*}}libomptarget-nvptx-sm_60.bc
+
+/// ###
+
+/// Check that the warning is thrown when the libomptarget bitcode library is 
not found.
+/// Libomptarget requires sm_35 or newer so an sm_20 bitcode library should 
never exist.
+// RUN:   %clang -### -fopenmp=libomp -fopenmp-targets=nvptx64-nvidia-cuda \
+// RUN:   -Xopenmp-target -march=sm_20 -fopenmp-relocatable-target -save-temps 
\
+// RUN:   -no-canonical-prefixes %s 2>&1 | FileCheck 
-check-prefix=CHK-BCLIB-WARN %s
+
+// CHK-BCLIB-WARN: Expect degraded performance on the target device due to 
missing 'libomptarget-nvptx-sm_20.bc' in LIBRARY_PATH.
Index: lib/Driver/ToolChains/Cuda.cpp
===
--- lib/Driver/ToolChains/Cuda.cpp
+++ lib/Driver/ToolChains/Cuda.cpp
@@ -21,6 +21,7 @@
 #include "llvm/Option/ArgList.h"
 #include "llvm/Support/FileSystem.h"
 #include "llvm/Support/Path.h"
+#include "llvm/Support/Process.h"
 #include "llvm/Support/Program.h"
 #include 
 
@@ -580,6 +581,43 @@
 CC1Args.push_back("-target-feature");
 CC1Args.push_back("+ptx42");
   }
+
+  if (DeviceOffloadingKind == Action::OFK_OpenMP) {
+SmallVector LibraryPaths;
+// Add path to lib and/or lib64 folders.
+SmallString<256> DefaultLibPath =
+  llvm::sys::path::parent_path(getDriver().Dir);
+llvm::sys::path::append(DefaultLibPath,
+Twine("lib") + CLANG_LIBDIR_SUFFIX);
+LibraryPaths.emplace_back(DefaultLibPath.c_str());
+
+// Add user defined library paths from LIBRARY_PATH.
+if (llvm::Optional LibPath =
+  llvm::sys::Process::GetEnv("LIBRARY_PATH")) {
+  SmallVector Frags;
+  const char EnvPathSeparatorStr[] = {llvm::sys::EnvPathSeparator, '\0'};
+  llvm::SplitString(*LibPath, Frags, EnvPathSeparatorStr);
+  for (auto Path : Frags)
+LibraryPaths.emplace_back(Path.trim());
+}
+
+std::string LibOmpTargetName =
+  "libomptarget-nvptx-" + GpuArch.str() + ".bc";
+bool FoundBCLibrary = false;
+for (const std::string &LibraryPath : LibraryPaths) {
+  SmallString<128> LibOmpTargetFile(LibraryPath);
+  llvm::sys::path::append(LibOmpTargetFile, LibOmpTargetName);
+  if (llvm::sys::fs::exists(LibOmpTargetFile)) {
+CC1Args.push_back("-mlink-cuda-bitcode");
+CC1Args.push_back(DriverArgs.MakeArgString(LibOmpTargetFile));
+FoundBCLibrary = true;
+break;
+  }
+}
+if (!FoundBCLibrary)
+  getDriver().Diag(diag::remark_drv_omp_offload_target_missingbcruntime)
+  << LibOmpTargetName;
+  }
 }
 
 void CudaToolChain::AddCudaIncludeArgs(const ArgList &DriverArgs,
Index: include/clang/Basic/DiagnosticDriverKinds.td
===
--- include/clang/Basic/DiagnosticDriverKinds.td
+++ include/clang/Basic/DiagnosticDriverKinds.td
@@ -203,6 +203,9 @@
 def warn_drv_omp_offload_target_duplicate : Warning<
   "The OpenMP offloading target '%0' is similar to target '%1' already 
specified - will be ignored.">, 
   InGroup;
+def remark_drv_omp_offload_target_missingbcruntime : Warning<
+  "No .bc library found in the default clang lib directory or in LIBRARY_PATH. 
Expect degraded performance due to no inlining of runtime functions on target 
devices.">,
+  InGroup;
 def err_drv_bitcode_unsupported_on_toolchain : Error<
   "-fembed-bitcode is not supported on versions of iOS prior to 6.0">;
 


Index: test/Driver/openmp-offload-gpu.c
===
--- test/Driver/openmp-offload-gpu.c
+++ test/Driver/openmp-offload-gpu.c
@@ -142,3 +142,25 @@
 // RUN:   | FileCheck -check-prefix=CHK-NOLIBDEVICE

[PATCH] D44142: [clangd] Revamp handling of diagnostics.

2018-03-06 Thread Sam McCall via Phabricator via cfe-commits
sammccall added a comment.

Behavior looks good. I think we can do a bit better with (most) fixits - your 
call on whether it makes sense to do here.

As discussed i'd simplify the diagnostic containers until we know there's a 
strong need.




Comment at: clangd/ClangdLSPServer.cpp:329
+  {"title",
+   llvm::formatv("Apply FixIt {0}", GetFixitMessage(D.message))},
   {"command", ExecuteCommandParams::CLANGD_APPLY_FIX_COMMAND},

nit: while here, can we add a colon after FixIt (or if appropriate in practice, 
just drop the prefix altogether?). My recollection is this is a bit hard to 
parse.



Comment at: clangd/Diagnostics.cpp:85
+
+bool isInsdieMainFile(const clang::Diagnostic &D) {
+  if (!D.hasSourceManager())

inside



Comment at: clangd/Diagnostics.cpp:125
+
+void printDiag(llvm::raw_string_ostream &OS, const PersistentDiag &D) {
+  if (D.InsideMainFile) {

mind pasting a small example as a function comment?
Logic looks good, but I had to reconstruct the message in my head.



Comment at: clangd/Diagnostics.cpp:147
+
+std::string presentMainMessage(const DiagWithNotes &D) {
+  std::string Result;

or just mainMessage (this is another verbs-for-pure-functions case where the 
style recommendation seems to hurt readability to me, but up to you)



Comment at: clangd/Diagnostics.cpp:192
+llvm::function_ref OutFn) {
+  auto PreBuild = [](const PersistentDiag &D) {
+DiagWithFixIts Res;

PreBuild could be FillBasicFields or something? found this name confusing.



Comment at: clangd/Diagnostics.cpp:200
+
+  DiagWithFixIts Main = PreBuild(D.main());
+  Main.Diag.message = presentMainMessage(D);

(nit: if the goal with the callback function is to avoid allocations, shouldn't 
we reuse the DiagWithFixIts?)



Comment at: clangd/Diagnostics.cpp:322
+  addToOutput(D);
+  }
+  LastDiagAndNotes.clear();

do you need else log here? (and just log the main diag)



Comment at: clangd/Diagnostics.h:28
+/// DiagList.
+struct PersistentDiag {
+  llvm::StringRef Message;

ilya-biryukov wrote:
> This could probably use a better name
I found it a bit confusing that this represents both "top-level" diagnostics 
and notes. It obscures the nature of the hierarchy a bit: there *are* a fixed 
number of levels with different "kinds", but the kinds are similar enough to 
share a type.

I'd actually consider using inheritance here to model the relationships more 
clearly. (Yes, gross, I know)
Like:

  struct DiagBase { Message, File, Range, InMainFile }
  struct Diag : DiagBase { FixIts, Notes, Severity }
  struct Note : DiagBase {} // or leave this one out until needed

(I think we came to the conclusion that different severity of notes isn't 
interesting and potentially just confusing)



Comment at: clangd/Diagnostics.h:35
+  DiagnosticsEngine::Level Severity;
+  llvm::SmallVector FixIts;
+  // Since File is only descriptive, we store a separate flag to distinguish

As discussed offline - I think fixits should probably be a different struct 
hanging off the main diagnostic, with a name. Following clang's example 
seems... less than clear here.

They could also be modeled as notes with an optional TextEdit - this seems 
sligthly less clear but more faithful to clang internals*.
Either way, it should be clear that they're only allowed in *one* of these 
locations - having notes and main diags be distinct types would help.

I think this probably affects how we should expose them through LSP - they 
should be named code actions attached to the original diagnostic.
Maybe they should also be separate diagnostics, but only if they contribute a 
unique opportunity to the user e.g. they have a non-empty range that isn't 
contained within the diagnostic's range.
This patch seems like a reasonable place to do that, but also OK if you want to 
defer.



Comment at: clangd/Diagnostics.h:35
+  DiagnosticsEngine::Level Severity;
+  llvm::SmallVector FixIts;
+  // Since File is only descriptive, we store a separate flag to distinguish

sammccall wrote:
> As discussed offline - I think fixits should probably be a different struct 
> hanging off the main diagnostic, with a name. Following clang's example 
> seems... less than clear here.
> 
> They could also be modeled as notes with an optional TextEdit - this seems 
> sligthly less clear but more faithful to clang internals*.
> Either way, it should be clear that they're only allowed in *one* of these 
> locations - having notes and main diags be distinct types would help.
> 
> I think this probably affects how we should expose them through LSP - they 
> should be named code actions attached to the original diagnostic.
> Maybe they 

[PATCH] D34365: [FrontEnd] Allow overriding the default C/C++ -std via CMake vars

2018-03-06 Thread Michał Górny via Phabricator via cfe-commits
mgorny updated this revision to Diff 137227.
mgorny added a comment.

@rnk, could you confirm the rebased patch? I'm not sure if I should override 
`InputKind::RenderScript` as well.


https://reviews.llvm.org/D34365

Files:
  CMakeLists.txt
  include/clang/Config/config.h.cmake
  lib/Frontend/CompilerInvocation.cpp


Index: lib/Frontend/CompilerInvocation.cpp
===
--- lib/Frontend/CompilerInvocation.cpp
+++ lib/Frontend/CompilerInvocation.cpp
@@ -1809,18 +1809,30 @@
   break;
 case InputKind::Asm:
 case InputKind::C:
+#if defined(CLANG_DEFAULT_STD_C)
+  LangStd = CLANG_DEFAULT_STD_C;
+#else
   // The PS4 uses C99 as the default C standard.
   if (T.isPS4())
 LangStd = LangStandard::lang_gnu99;
   else
 LangStd = LangStandard::lang_gnu11;
+#endif
   break;
 case InputKind::ObjC:
+#if defined(CLANG_DEFAULT_STD_C)
+  LangStd = CLANG_DEFAULT_STD_C;
+#else
   LangStd = LangStandard::lang_gnu11;
+#endif
   break;
 case InputKind::CXX:
 case InputKind::ObjCXX:
+#if defined(CLANG_DEFAULT_STD_CXX)
+  LangStd = CLANG_DEFAULT_STD_CXX;
+#else
   LangStd = LangStandard::lang_gnucxx14;
+#endif
   break;
 case InputKind::RenderScript:
   LangStd = LangStandard::lang_c99;
Index: include/clang/Config/config.h.cmake
===
--- include/clang/Config/config.h.cmake
+++ include/clang/Config/config.h.cmake
@@ -11,6 +11,12 @@
 /* Default linker to use. */
 #define CLANG_DEFAULT_LINKER "${CLANG_DEFAULT_LINKER}"
 
+/* Default C/ObjC standard to use. */
+#cmakedefine CLANG_DEFAULT_STD_C LangStandard::lang_${CLANG_DEFAULT_STD_C}
+
+/* Default C++/ObjC++ standard to use. */
+#cmakedefine CLANG_DEFAULT_STD_CXX LangStandard::lang_${CLANG_DEFAULT_STD_CXX}
+
 /* Default C++ stdlib to use. */
 #define CLANG_DEFAULT_CXX_STDLIB "${CLANG_DEFAULT_CXX_STDLIB}"
 
Index: CMakeLists.txt
===
--- CMakeLists.txt
+++ CMakeLists.txt
@@ -212,6 +212,12 @@
 set(ENABLE_X86_RELAX_RELOCATIONS OFF CACHE BOOL
 "enable x86 relax relocations by default")
 
+# TODO: verify the values against LangStandards.def?
+set(CLANG_DEFAULT_STD_C "" CACHE STRING
+  "Default standard to use for C/ObjC code (IDENT from LangStandards.def, 
empty for platform default)")
+set(CLANG_DEFAULT_STD_CXX "" CACHE STRING
+  "Default standard to use for C++/ObjC++ code (IDENT from LangStandards.def, 
empty for platform default)")
+
 set(CLANG_DEFAULT_LINKER "" CACHE STRING
   "Default linker to use (linker name or absolute path, empty for platform 
default)")
 


Index: lib/Frontend/CompilerInvocation.cpp
===
--- lib/Frontend/CompilerInvocation.cpp
+++ lib/Frontend/CompilerInvocation.cpp
@@ -1809,18 +1809,30 @@
   break;
 case InputKind::Asm:
 case InputKind::C:
+#if defined(CLANG_DEFAULT_STD_C)
+  LangStd = CLANG_DEFAULT_STD_C;
+#else
   // The PS4 uses C99 as the default C standard.
   if (T.isPS4())
 LangStd = LangStandard::lang_gnu99;
   else
 LangStd = LangStandard::lang_gnu11;
+#endif
   break;
 case InputKind::ObjC:
+#if defined(CLANG_DEFAULT_STD_C)
+  LangStd = CLANG_DEFAULT_STD_C;
+#else
   LangStd = LangStandard::lang_gnu11;
+#endif
   break;
 case InputKind::CXX:
 case InputKind::ObjCXX:
+#if defined(CLANG_DEFAULT_STD_CXX)
+  LangStd = CLANG_DEFAULT_STD_CXX;
+#else
   LangStd = LangStandard::lang_gnucxx14;
+#endif
   break;
 case InputKind::RenderScript:
   LangStd = LangStandard::lang_c99;
Index: include/clang/Config/config.h.cmake
===
--- include/clang/Config/config.h.cmake
+++ include/clang/Config/config.h.cmake
@@ -11,6 +11,12 @@
 /* Default linker to use. */
 #define CLANG_DEFAULT_LINKER "${CLANG_DEFAULT_LINKER}"
 
+/* Default C/ObjC standard to use. */
+#cmakedefine CLANG_DEFAULT_STD_C LangStandard::lang_${CLANG_DEFAULT_STD_C}
+
+/* Default C++/ObjC++ standard to use. */
+#cmakedefine CLANG_DEFAULT_STD_CXX LangStandard::lang_${CLANG_DEFAULT_STD_CXX}
+
 /* Default C++ stdlib to use. */
 #define CLANG_DEFAULT_CXX_STDLIB "${CLANG_DEFAULT_CXX_STDLIB}"
 
Index: CMakeLists.txt
===
--- CMakeLists.txt
+++ CMakeLists.txt
@@ -212,6 +212,12 @@
 set(ENABLE_X86_RELAX_RELOCATIONS OFF CACHE BOOL
 "enable x86 relax relocations by default")
 
+# TODO: verify the values against LangStandards.def?
+set(CLANG_DEFAULT_STD_C "" CACHE STRING
+  "Default standard to use for C/ObjC code (IDENT from LangStandards.def, empty for platform default)")
+set(CLANG_DEFAULT_STD_CXX "" CACHE STRING
+  "Default standard to use for C++/ObjC++ code (IDENT from LangStandards.def, empty for platform default)")
+
 set(CLANG_DEFAULT_LINKER "" CACHE ST

[PATCH] D43197: [OpenMP] Add flag for linking runtime bitcode library

2018-03-06 Thread Gheorghe-Teodor Bercea via Phabricator via cfe-commits
gtbercea updated this revision to Diff 137230.
gtbercea added a comment.

Fix test.


Repository:
  rC Clang

https://reviews.llvm.org/D43197

Files:
  include/clang/Basic/DiagnosticDriverKinds.td
  lib/Driver/ToolChains/Cuda.cpp
  test/Driver/openmp-offload-gpu.c


Index: test/Driver/openmp-offload-gpu.c
===
--- test/Driver/openmp-offload-gpu.c
+++ test/Driver/openmp-offload-gpu.c
@@ -142,3 +142,25 @@
 // RUN:   | FileCheck -check-prefix=CHK-NOLIBDEVICE %s
 
 // CHK-NOLIBDEVICE-NOT: error:{{.*}}sm_60
+
+/// ###
+
+/// Check that the runtime bitcode library is part of the compile line. Create 
a bogus
+/// bitcode library and add it to the LIBRARY_PATH.
+// RUN:   touch %T/libomptarget-nvptx-sm_60.bc
+// RUN:   env LIBRARY_PATH=%T %clang -### -fopenmp=libomp 
-fopenmp-targets=nvptx64-nvidia-cuda \
+// RUN:   -Xopenmp-target -march=sm_60 -fopenmp-relocatable-target -save-temps 
\
+// RUN:   -no-canonical-prefixes %s 2>&1 | FileCheck -check-prefix=CHK-BCLIB %s
+// RUN:   rm %T/libomptarget-nvptx-sm_60.bc
+
+// CHK-BCLIB: 
clang{{.*}}-triple{{.*}}nvptx64-nvidia-cuda{{.*}}-mlink-cuda-bitcode{{.*}}libomptarget-nvptx-sm_60.bc
+
+/// ###
+
+/// Check that the warning is thrown when the libomptarget bitcode library is 
not found.
+/// Libomptarget requires sm_35 or newer so an sm_20 bitcode library should 
never exist.
+// RUN:   %clang -### -fopenmp=libomp -fopenmp-targets=nvptx64-nvidia-cuda \
+// RUN:   -Xopenmp-target -march=sm_20 -fopenmp-relocatable-target -save-temps 
\
+// RUN:   -no-canonical-prefixes %s 2>&1 | FileCheck 
-check-prefix=CHK-BCLIB-WARN %s
+
+// CHK-BCLIB-WARN: No .bc library 'libomptarget-nvptx-sm_20.bc' found in the 
default clang lib directory or in LIBRARY_PATH. Expect degraded performance due 
to no inlining of runtime functions on target devices.
Index: lib/Driver/ToolChains/Cuda.cpp
===
--- lib/Driver/ToolChains/Cuda.cpp
+++ lib/Driver/ToolChains/Cuda.cpp
@@ -21,6 +21,7 @@
 #include "llvm/Option/ArgList.h"
 #include "llvm/Support/FileSystem.h"
 #include "llvm/Support/Path.h"
+#include "llvm/Support/Process.h"
 #include "llvm/Support/Program.h"
 #include 
 
@@ -580,6 +581,43 @@
 CC1Args.push_back("-target-feature");
 CC1Args.push_back("+ptx42");
   }
+
+  if (DeviceOffloadingKind == Action::OFK_OpenMP) {
+SmallVector LibraryPaths;
+// Add path to lib and/or lib64 folders.
+SmallString<256> DefaultLibPath =
+  llvm::sys::path::parent_path(getDriver().Dir);
+llvm::sys::path::append(DefaultLibPath,
+Twine("lib") + CLANG_LIBDIR_SUFFIX);
+LibraryPaths.emplace_back(DefaultLibPath.c_str());
+
+// Add user defined library paths from LIBRARY_PATH.
+if (llvm::Optional LibPath =
+  llvm::sys::Process::GetEnv("LIBRARY_PATH")) {
+  SmallVector Frags;
+  const char EnvPathSeparatorStr[] = {llvm::sys::EnvPathSeparator, '\0'};
+  llvm::SplitString(*LibPath, Frags, EnvPathSeparatorStr);
+  for (auto Path : Frags)
+LibraryPaths.emplace_back(Path.trim());
+}
+
+std::string LibOmpTargetName =
+  "libomptarget-nvptx-" + GpuArch.str() + ".bc";
+bool FoundBCLibrary = false;
+for (const std::string &LibraryPath : LibraryPaths) {
+  SmallString<128> LibOmpTargetFile(LibraryPath);
+  llvm::sys::path::append(LibOmpTargetFile, LibOmpTargetName);
+  if (llvm::sys::fs::exists(LibOmpTargetFile)) {
+CC1Args.push_back("-mlink-cuda-bitcode");
+CC1Args.push_back(DriverArgs.MakeArgString(LibOmpTargetFile));
+FoundBCLibrary = true;
+break;
+  }
+}
+if (!FoundBCLibrary)
+  getDriver().Diag(diag::remark_drv_omp_offload_target_missingbcruntime)
+  << LibOmpTargetName;
+  }
 }
 
 void CudaToolChain::AddCudaIncludeArgs(const ArgList &DriverArgs,
Index: include/clang/Basic/DiagnosticDriverKinds.td
===
--- include/clang/Basic/DiagnosticDriverKinds.td
+++ include/clang/Basic/DiagnosticDriverKinds.td
@@ -203,6 +203,9 @@
 def warn_drv_omp_offload_target_duplicate : Warning<
   "The OpenMP offloading target '%0' is similar to target '%1' already 
specified - will be ignored.">, 
   InGroup;
+def remark_drv_omp_offload_target_missingbcruntime : Warning<
+  "No .bc library '%0' found in the default clang lib directory or in 
LIBRARY_PATH. Expect degraded performance due to no inlining of runtime 
functions on target devices.">,
+  InGroup;
 def err_drv_bitcode_unsupported_on_toolchain : Error<
   "-fembed-bitcode is not supported on versions of iOS prior to 6.0">;
 


Index: test/Driver/openmp-offload-gpu.c
===
--- test/Driver/openmp-offload-gpu.c
+++ test/Driver/openmp-offload

r326822 - TableGen: Give up on exact fixits for diagnostic groups

2018-03-06 Thread Nicolai Haehnle via cfe-commits
Author: nha
Date: Tue Mar  6 09:55:00 2018
New Revision: 326822

URL: http://llvm.org/viewvc/llvm-project?rev=326822&view=rev
Log:
TableGen: Give up on exact fixits for diagnostic groups

With recent changes in the TableGen frontend, we no longer have usable
location information for anonymous defs.

Fixes test breakage caused by r326788.

The normal, non-error TableGen output is not affected by this change.

Modified:
cfe/trunk/test/TableGen/anonymous-groups.td
cfe/trunk/test/TableGen/tg-fixits.td
cfe/trunk/utils/TableGen/ClangDiagnosticsEmitter.cpp

Modified: cfe/trunk/test/TableGen/anonymous-groups.td
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/TableGen/anonymous-groups.td?rev=326822&r1=326821&r2=326822&view=diff
==
--- cfe/trunk/test/TableGen/anonymous-groups.td (original)
+++ cfe/trunk/test/TableGen/anonymous-groups.td Tue Mar  6 09:55:00 2018
@@ -7,21 +7,17 @@ def NamedGroup : DiagGroup<"name">;
 
 
 def InNamedGroup : Warning<"">, InGroup>;
-//  CHECK: anonymous-groups.td:[[@LINE-1]]:41: error: group 'name' is 
referred to anonymously
+//  CHECK: anonymous-groups.td:[[@LINE-1]]:1: error: group 'name' is 
referred to anonymously
 // CHECK-NEXT: {{^def InNamedGroup : Warning<"">, InGroup>;}}
-// CHECK-NEXT: {{^\^~}}
-// CHECK-NEXT: {{^InGroup}}
-// CHECK-NEXT: anonymous-groups.td:6:1: note: group defined here
+//  CHECK: anonymous-groups.td:6:1: note: group defined here
 // CHECK-NEXT: def NamedGroup : DiagGroup<"name">;
 // CHECK-NEXT: ^
 
 
 def AlsoInNamedGroup : Warning<"">, InGroup  < DiagGroup<"name"> >;
-//  CHECK: anonymous-groups.td:[[@LINE-1]]:48: error: group 'name' is 
referred to anonymously
+//  CHECK: anonymous-groups.td:[[@LINE-1]]:1: error: group 'name' is 
referred to anonymously
 // CHECK-NEXT: {{^def AlsoInNamedGroup : Warning<"">, InGroup  < 
DiagGroup<"name"> >;}}
-// CHECK-NEXT: {{^
~~~\^~~}}
-// CHECK-NEXT: {{^InGroup}}
-// CHECK-NEXT: anonymous-groups.td:6:1: note: group defined here
+//  CHECK: anonymous-groups.td:6:1: note: group defined here
 // CHECK-NEXT: def NamedGroup : DiagGroup<"name">;
 // CHECK-NEXT: ^
 
@@ -31,12 +27,8 @@ def AlsoAnonymousGroup : Warning<"">, In
 def AnonymousGroupAgain : Warning<"">,
   InGroup>;
 
-//  CHECK: anonymous-groups.td:[[@LINE-5]]:43: error: group 'anonymous' is 
referred to anonymously
+//  CHECK: anonymous-groups.td:[[@LINE-5]]:1: error: group 'anonymous' is 
referred to anonymously
 // CHECK-NEXT: {{^def AnonymousGroup : Warning<"">, 
InGroup>;}}
-// CHECK-NEXT: {{^  
\^~~}}
-// CHECK-NEXT: anonymous-groups.td:[[@LINE-7]]:47: note: also referenced here
+//  CHECK: anonymous-groups.td:[[@LINE-6]]:1: note: also referenced here
 // CHECK-NEXT: {{^def AlsoAnonymousGroup : Warning<"">, 
InGroup>;}}
-// CHECK-NEXT: {{^  
\^~~}}
-// CHECK-NEXT: anonymous-groups.td:[[@LINE-8]]:11: note: also referenced here
-// CHECK-NEXT: {{^  InGroup>;}}
-// CHECK-NEXT: {{^  \^~~}}
+//  CHECK: anonymous-groups.td:[[@LINE-7]]:1: note: also referenced here

Modified: cfe/trunk/test/TableGen/tg-fixits.td
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/TableGen/tg-fixits.td?rev=326822&r1=326821&r2=326822&view=diff
==
--- cfe/trunk/test/TableGen/tg-fixits.td (original)
+++ cfe/trunk/test/TableGen/tg-fixits.td Tue Mar  6 09:55:00 2018
@@ -4,38 +4,22 @@ include "DiagnosticBase.inc"
 def NamedGroup : DiagGroup<"name">;
 
 def InNamedGroup : Warning<"">, InGroup>;
-//  CHECK: tg-fixits.td:[[@LINE-1]]:41: error: group 'name' is referred to 
anonymously
+//  CHECK: tg-fixits.td:[[@LINE-1]]:1: error: group 'name' is referred to 
anonymously
 // CHECK-NEXT: {{^def InNamedGroup : Warning<"">, InGroup>;}}
-// CHECK-NEXT: {{^\^~}}
-// CHECK-NEXT: {{^InGroup}}
 
 def Wrapped : Warning<"">, InGroup>;
-//  CHECK: tg-fixits.td:[[@LINE-2]]:36: error: group 'name' is referred to 
anonymously
+//  CHECK: tg-fixits.td:[[@LINE-2]]:1: error: group 'name' is referred to 
anonymously
 // CHECK-NEXT: {{^def Wrapped : Warning<"">, InGroup}}
 
 def AlsoWrapped : Warning<"">, InGroup<
   DiagGroup<"name">>;
-//  CHECK: tg-fixits.td:[[@LINE-1]]:3: error: group 'name' is referred to 
anonymously
-// CHECK-NEXT: {{^  DiagGroup<"name">>;}}
-// CHECK-NEXT: {{^~~\^~}}
-// CHECK-NEXT: {{^InGroup}}
-
-// The following lines contain hard tabs (\t); do not change this!
-def HardTabs : Warning<"">,
-   InGroup

[PATCH] D43197: [OpenMP] Add flag for linking runtime bitcode library

2018-03-06 Thread Gheorghe-Teodor Bercea via Phabricator via cfe-commits
gtbercea updated this revision to Diff 137233.
gtbercea added a comment.

- Fix message and test.


Repository:
  rC Clang

https://reviews.llvm.org/D43197

Files:
  include/clang/Basic/DiagnosticDriverKinds.td
  lib/Driver/ToolChains/Cuda.cpp
  test/Driver/openmp-offload-gpu.c


Index: test/Driver/openmp-offload-gpu.c
===
--- test/Driver/openmp-offload-gpu.c
+++ test/Driver/openmp-offload-gpu.c
@@ -142,3 +142,25 @@
 // RUN:   | FileCheck -check-prefix=CHK-NOLIBDEVICE %s
 
 // CHK-NOLIBDEVICE-NOT: error:{{.*}}sm_60
+
+/// ###
+
+/// Check that the runtime bitcode library is part of the compile line. Create 
a bogus
+/// bitcode library and add it to the LIBRARY_PATH.
+// RUN:   touch %T/libomptarget-nvptx-sm_60.bc
+// RUN:   env LIBRARY_PATH=%T %clang -### -fopenmp=libomp 
-fopenmp-targets=nvptx64-nvidia-cuda \
+// RUN:   -Xopenmp-target -march=sm_60 -fopenmp-relocatable-target -save-temps 
\
+// RUN:   -no-canonical-prefixes %s 2>&1 | FileCheck -check-prefix=CHK-BCLIB %s
+// RUN:   rm %T/libomptarget-nvptx-sm_60.bc
+
+// CHK-BCLIB: 
clang{{.*}}-triple{{.*}}nvptx64-nvidia-cuda{{.*}}-mlink-cuda-bitcode{{.*}}libomptarget-nvptx-sm_60.bc
+
+/// ###
+
+/// Check that the warning is thrown when the libomptarget bitcode library is 
not found.
+/// Libomptarget requires sm_35 or newer so an sm_20 bitcode library should 
never exist.
+// RUN:   %clang -### -fopenmp=libomp -fopenmp-targets=nvptx64-nvidia-cuda \
+// RUN:   -Xopenmp-target -march=sm_20 -fopenmp-relocatable-target -save-temps 
\
+// RUN:   -no-canonical-prefixes %s 2>&1 | FileCheck 
-check-prefix=CHK-BCLIB-WARN %s
+
+// CHK-BCLIB-WARN: No library 'libomptarget-nvptx-sm_20.bc' found in the 
default clang lib directory or in LIBRARY_PATH. Expect degraded performance due 
to no inlining of runtime functions on target devices.
Index: lib/Driver/ToolChains/Cuda.cpp
===
--- lib/Driver/ToolChains/Cuda.cpp
+++ lib/Driver/ToolChains/Cuda.cpp
@@ -21,6 +21,7 @@
 #include "llvm/Option/ArgList.h"
 #include "llvm/Support/FileSystem.h"
 #include "llvm/Support/Path.h"
+#include "llvm/Support/Process.h"
 #include "llvm/Support/Program.h"
 #include 
 
@@ -580,6 +581,43 @@
 CC1Args.push_back("-target-feature");
 CC1Args.push_back("+ptx42");
   }
+
+  if (DeviceOffloadingKind == Action::OFK_OpenMP) {
+SmallVector LibraryPaths;
+// Add path to lib and/or lib64 folders.
+SmallString<256> DefaultLibPath =
+  llvm::sys::path::parent_path(getDriver().Dir);
+llvm::sys::path::append(DefaultLibPath,
+Twine("lib") + CLANG_LIBDIR_SUFFIX);
+LibraryPaths.emplace_back(DefaultLibPath.c_str());
+
+// Add user defined library paths from LIBRARY_PATH.
+if (llvm::Optional LibPath =
+  llvm::sys::Process::GetEnv("LIBRARY_PATH")) {
+  SmallVector Frags;
+  const char EnvPathSeparatorStr[] = {llvm::sys::EnvPathSeparator, '\0'};
+  llvm::SplitString(*LibPath, Frags, EnvPathSeparatorStr);
+  for (auto Path : Frags)
+LibraryPaths.emplace_back(Path.trim());
+}
+
+std::string LibOmpTargetName =
+  "libomptarget-nvptx-" + GpuArch.str() + ".bc";
+bool FoundBCLibrary = false;
+for (const std::string &LibraryPath : LibraryPaths) {
+  SmallString<128> LibOmpTargetFile(LibraryPath);
+  llvm::sys::path::append(LibOmpTargetFile, LibOmpTargetName);
+  if (llvm::sys::fs::exists(LibOmpTargetFile)) {
+CC1Args.push_back("-mlink-cuda-bitcode");
+CC1Args.push_back(DriverArgs.MakeArgString(LibOmpTargetFile));
+FoundBCLibrary = true;
+break;
+  }
+}
+if (!FoundBCLibrary)
+  getDriver().Diag(diag::warn_drv_omp_offload_target_missingbcruntime)
+  << LibOmpTargetName;
+  }
 }
 
 void CudaToolChain::AddCudaIncludeArgs(const ArgList &DriverArgs,
Index: include/clang/Basic/DiagnosticDriverKinds.td
===
--- include/clang/Basic/DiagnosticDriverKinds.td
+++ include/clang/Basic/DiagnosticDriverKinds.td
@@ -203,6 +203,9 @@
 def warn_drv_omp_offload_target_duplicate : Warning<
   "The OpenMP offloading target '%0' is similar to target '%1' already 
specified - will be ignored.">, 
   InGroup;
+def warn_drv_omp_offload_target_missingbcruntime : Warning<
+  "No library '%0' found in the default clang lib directory or in 
LIBRARY_PATH. Expect degraded performance due to no inlining of runtime 
functions on target devices.">,
+  InGroup;
 def err_drv_bitcode_unsupported_on_toolchain : Error<
   "-fembed-bitcode is not supported on versions of iOS prior to 6.0">;
 


Index: test/Driver/openmp-offload-gpu.c
===
--- test/Driver/openmp-offload-gpu.c
+++ test/Driver/openmp-offlo

r326827 - [OPENMP] Fix generation of the unique names for task reduction

2018-03-06 Thread Alexey Bataev via cfe-commits
Author: abataev
Date: Tue Mar  6 10:59:43 2018
New Revision: 326827

URL: http://llvm.org/viewvc/llvm-project?rev=326827&view=rev
Log:
[OPENMP] Fix generation of the unique names for task reduction
variables.

If the task has reduction construct and this construct for some variable
requires unique threadprivate storage, we may generate different names
for variables used in taskgroup task_reduction clause and in task
  in_reduction clause. Patch fixes this problem.

Modified:
cfe/trunk/lib/CodeGen/CGOpenMPRuntime.cpp
cfe/trunk/lib/CodeGen/CGOpenMPRuntime.h
cfe/trunk/test/OpenMP/taskgroup_task_reduction_codegen.cpp

Modified: cfe/trunk/lib/CodeGen/CGOpenMPRuntime.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/CodeGen/CGOpenMPRuntime.cpp?rev=326827&r1=326826&r2=326827&view=diff
==
--- cfe/trunk/lib/CodeGen/CGOpenMPRuntime.cpp (original)
+++ cfe/trunk/lib/CodeGen/CGOpenMPRuntime.cpp Tue Mar  6 10:59:43 2018
@@ -1101,11 +1101,9 @@ static Address castToBase(CodeGenFunctio
   return Address(Addr, BaseLVAlignment);
 }
 
-Address ReductionCodeGen::adjustPrivateAddress(CodeGenFunction &CGF, unsigned 
N,
-   Address PrivateAddr) {
-  const DeclRefExpr *DE;
+static const VarDecl *getBaseDecl(const Expr *Ref, const DeclRefExpr *&DE) {
   const VarDecl *OrigVD = nullptr;
-  if (auto *OASE = dyn_cast(ClausesData[N].Ref)) {
+  if (auto *OASE = dyn_cast(Ref)) {
 auto *Base = OASE->getBase()->IgnoreParenImpCasts();
 while (auto *TempOASE = dyn_cast(Base))
   Base = TempOASE->getBase()->IgnoreParenImpCasts();
@@ -1113,14 +,20 @@ Address ReductionCodeGen::adjustPrivateA
   Base = TempASE->getBase()->IgnoreParenImpCasts();
 DE = cast(Base);
 OrigVD = cast(DE->getDecl());
-  } else if (auto *ASE = dyn_cast(ClausesData[N].Ref)) {
+  } else if (auto *ASE = dyn_cast(Ref)) {
 auto *Base = ASE->getBase()->IgnoreParenImpCasts();
 while (auto *TempASE = dyn_cast(Base))
   Base = TempASE->getBase()->IgnoreParenImpCasts();
 DE = cast(Base);
 OrigVD = cast(DE->getDecl());
   }
-  if (OrigVD) {
+  return OrigVD;
+}
+
+Address ReductionCodeGen::adjustPrivateAddress(CodeGenFunction &CGF, unsigned 
N,
+   Address PrivateAddr) {
+  const DeclRefExpr *DE;
+  if (const VarDecl *OrigVD = ::getBaseDecl(ClausesData[N].Ref, DE)) {
 BaseDecls.emplace_back(OrigVD);
 auto OriginalBaseLValue = CGF.EmitLValue(DE);
 LValue BaseLValue =
@@ -5355,12 +5359,19 @@ void CGOpenMPRuntime::emitReduction(Code
 }
 
 /// Generates unique name for artificial threadprivate variables.
-/// Format is:  "."  "_" 
-static std::string generateUniqueName(StringRef Prefix, SourceLocation Loc,
-  unsigned N) {
+/// Format is:  "."  "_" ""
+static std::string generateUniqueName(CodeGenModule &CGM, StringRef Prefix,
+  const Expr *Ref) {
   SmallString<256> Buffer;
   llvm::raw_svector_ostream Out(Buffer);
-  Out << Prefix << "." << Loc.getRawEncoding() << "_" << N;
+  const clang::DeclRefExpr *DE;
+  const VarDecl *D = ::getBaseDecl(Ref, DE);
+  if (!D)
+D = cast(cast(Ref)->getDecl());
+  D = D->getCanonicalDecl();
+  Out << Prefix << "."
+  << (D->isLocalVarDeclOrParm() ? D->getName() : CGM.getMangledName(D))
+  << "_" << D->getCanonicalDecl()->getLocStart().getRawEncoding();
   return Out.str();
 }
 
@@ -5397,7 +5408,7 @@ static llvm::Value *emitReduceInitFuncti
   if (RCG.getSizes(N).second) {
 Address SizeAddr = CGM.getOpenMPRuntime().getAddrOfArtificialThreadPrivate(
 CGF, CGM.getContext().getSizeType(),
-generateUniqueName("reduction_size", Loc, N));
+generateUniqueName(CGM, "reduction_size", RCG.getRefExpr(N)));
 Size = CGF.EmitLoadOfScalar(SizeAddr, /*Volatile=*/false,
 CGM.getContext().getSizeType(), Loc);
   }
@@ -5410,7 +5421,7 @@ static llvm::Value *emitReduceInitFuncti
 Address SharedAddr =
 CGM.getOpenMPRuntime().getAddrOfArtificialThreadPrivate(
 CGF, CGM.getContext().VoidPtrTy,
-generateUniqueName("reduction", Loc, N));
+generateUniqueName(CGM, "reduction", RCG.getRefExpr(N)));
 SharedLVal = CGF.MakeAddrLValue(SharedAddr, CGM.getContext().VoidPtrTy);
   } else {
 SharedLVal = CGF.MakeNaturalAlignAddrLValue(
@@ -5466,7 +5477,7 @@ static llvm::Value *emitReduceCombFuncti
   if (RCG.getSizes(N).second) {
 Address SizeAddr = CGM.getOpenMPRuntime().getAddrOfArtificialThreadPrivate(
 CGF, CGM.getContext().getSizeType(),
-generateUniqueName("reduction_size", Loc, N));
+generateUniqueName(CGM, "reduction_size", RCG.getRefExpr(N)));
 Size = CGF.EmitLoadOfScalar(SizeAddr, /*Volatile=*/false,
 CGM.getContext().getSizeType(), Loc);
   }
@@ -5537,7 +5548,7 @@ static 

[PATCH] D44143: Create properly seeded random generator check

2018-03-06 Thread Arthur O'Dwyer via Phabricator via cfe-commits
Quuxplusone added inline comments.



Comment at: docs/clang-tidy/checks/cert-properly-seeded-random-generator.rst:26
+std::random_device dev;
+std::mt19937 engine3(dev()); // Good
+  }

Seeding MT19937 with a single 32-bit integer is //not// "Good". It makes the 
seed super easy to brute-force; and for example, `engine3` will never produce 7 
or 13 as its first output.
http://www.pcg-random.org/posts/cpp-seeding-surprises.html

This doesn't affect the implementation or usefulness of this clang-tidy check, 
which is pretty nifty. I merely object to marking this sample code with the 
comment "Good" in official documentation. It should be marked "Will not warn" 
at best. Or replace it with something slightly more realistic, e.g.

int x = atoi(argv[1]);
std::mt19937 engine3(x);  // Will not warn

As Aaron said above, seeding with the current time is approximately as good an 
idea, and "will not warn" with the current diagnostic either.

The correct way to seed a PRNG is to initialize the //entire state// with 
random bits, not just 32 bits of the state. This can be done, but not yet in 
standard C++: 
http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2016/p0205r0.html



Comment at: test/clang-tidy/cert-properly-seeded-random-generator.cpp:76
+  // CHECK-MESSAGES: :[[@LINE-1]]:11: warning: random number generator must be 
seeded with a random_device instead of a constant 
[cert-properly-seeded-random-generator]
+  engine1.seed(seed);
+  // CHECK-MESSAGES: :[[@LINE-1]]:11: warning: random number generator must be 
seeded with a random_device instead of a constant 
[cert-properly-seeded-random-generator]

Is the diagnostic suppressed if `seed` is a template parameter? (Not that I'd 
do this. It's just a corner case I thought of.)


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D44143



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


[PATCH] D43906: [clang-format] Improve detection of Objective-C block types

2018-03-06 Thread Daniel Jasper via Phabricator via cfe-commits
djasper added inline comments.



Comment at: lib/Format/TokenAnnotator.cpp:155
+   Next->startsSequence(tok::identifier, tok::l_square,
+tok::numeric_constant, tok::r_square,
+tok::r_paren, tok::l_paren))) {

benhamilton wrote:
> benhamilton wrote:
> > djasper wrote:
> > > benhamilton wrote:
> > > > djasper wrote:
> > > > > This seems suspect. Does it have to be a numeric_constant?
> > > > Probably not, any constexpr would do, I suspect. What's the best way to 
> > > > parse that?
> > > I think this is the same answer for both of your questions. If what you 
> > > are trying to prevent "FOO(^)" to be parsed as a block, wouldn't it be 
> > > enough to look for whether there is a "(" after the ")" or even only 
> > > after "(^)", everything else is already correct IIUC? That would get you 
> > > out of need to parse the specifics here, which will be hard.
> > > 
> > > Or thinking about it another way. Previously, every "(^" would be parsed 
> > > as an ObjC block. There seems to be only a really rare corner case in 
> > > which it isn't (macros). Thus, I'd just try to detect that corner case. 
> > > Instead you are completely inverting the defaults (defaulting to "^" is 
> > > not a block) and then try to exactly parse ObjC where there might be many 
> > > cases and edge cases that you won't even think of now.
> > Hmm. Well, it's not just `FOO(^);` that isn't a block:
> > 
> > ```
> > #define FOO(X) operator X
> > 
> > SomeType FOO(^)(int x, const SomeType& y) { ... }
> > ```
> > 
> > Obviously we can't get this perfect without a pre-processor, but it seems 
> > like our best bet is to only assign mark `TT_ObjCBlockLParen` when we are 
> > sure the syntax is a valid block type or block variable.
> I tried the suggestion to only treat `(^)(` as a block type, but it appears 
> this is the primary place where we set `TT_ObjCBlockLParen`, so I think we 
> really do need to handle the other cases here.
I don't follow your logic. I'd like you to slowly change this as opposed to 
completely going the opposite way.

So currently, the only know real-live problem is "FOO(^);". So address this 
somehow, but still default/error to recognizing too much stuff as a block.

Have you actually seen

  SomeType FOO(^)(int x, const SomeType& y) { ... }

in real code?


Repository:
  rC Clang

https://reviews.llvm.org/D43906



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


[PATCH] D34365: [FrontEnd] Allow overriding the default C/C++ -std via CMake vars

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

Yep, looks good. I'd leave renderscript alone. I think it's deprecated.


https://reviews.llvm.org/D34365



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


[PATCH] D43494: [Modules] Fix creating fake definition data for lambdas.

2018-03-06 Thread Volodymyr Sapsai via Phabricator via cfe-commits
vsapsai added a comment.

Ping.


https://reviews.llvm.org/D43494



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


[PATCH] D43494: [Modules] Fix creating fake definition data for lambdas.

2018-03-06 Thread Richard Smith - zygoloid via Phabricator via cfe-commits
rsmith accepted this revision.
rsmith added inline comments.
This revision is now accepted and ready to land.



Comment at: clang/lib/Serialization/ASTReaderDecl.cpp:1795
   CXXRecordDecl *Canon = D->getCanonicalDecl();
-  if (Canon->DefinitionData) {
+  if (Canon->DefinitionData && Canon->DefinitionData != DD) {
 MergeDefinitionData(Canon, std::move(*DD));

It's a little odd that we'll temporarily have two different declarations that 
think they're the definition in this case, but I don't actually know of 
anything that'll go wrong as a result.

(This seems easy to avoid, though, by checking whether there already is a 
definition earlier.)


https://reviews.llvm.org/D43494



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


[PATCH] D43906: [clang-format] Improve detection of Objective-C block types

2018-03-06 Thread Ben Hamilton via Phabricator via cfe-commits
benhamilton added inline comments.



Comment at: lib/Format/TokenAnnotator.cpp:155
+   Next->startsSequence(tok::identifier, tok::l_square,
+tok::numeric_constant, tok::r_square,
+tok::r_paren, tok::l_paren))) {

djasper wrote:
> benhamilton wrote:
> > benhamilton wrote:
> > > djasper wrote:
> > > > benhamilton wrote:
> > > > > djasper wrote:
> > > > > > This seems suspect. Does it have to be a numeric_constant?
> > > > > Probably not, any constexpr would do, I suspect. What's the best way 
> > > > > to parse that?
> > > > I think this is the same answer for both of your questions. If what you 
> > > > are trying to prevent "FOO(^)" to be parsed as a block, wouldn't it be 
> > > > enough to look for whether there is a "(" after the ")" or even only 
> > > > after "(^)", everything else is already correct IIUC? That would get 
> > > > you out of need to parse the specifics here, which will be hard.
> > > > 
> > > > Or thinking about it another way. Previously, every "(^" would be 
> > > > parsed as an ObjC block. There seems to be only a really rare corner 
> > > > case in which it isn't (macros). Thus, I'd just try to detect that 
> > > > corner case. Instead you are completely inverting the defaults 
> > > > (defaulting to "^" is not a block) and then try to exactly parse ObjC 
> > > > where there might be many cases and edge cases that you won't even 
> > > > think of now.
> > > Hmm. Well, it's not just `FOO(^);` that isn't a block:
> > > 
> > > ```
> > > #define FOO(X) operator X
> > > 
> > > SomeType FOO(^)(int x, const SomeType& y) { ... }
> > > ```
> > > 
> > > Obviously we can't get this perfect without a pre-processor, but it seems 
> > > like our best bet is to only assign mark `TT_ObjCBlockLParen` when we are 
> > > sure the syntax is a valid block type or block variable.
> > I tried the suggestion to only treat `(^)(` as a block type, but it appears 
> > this is the primary place where we set `TT_ObjCBlockLParen`, so I think we 
> > really do need to handle the other cases here.
> I don't follow your logic. I'd like you to slowly change this as opposed to 
> completely going the opposite way.
> 
> So currently, the only know real-live problem is "FOO(^);". So address this 
> somehow, but still default/error to recognizing too much stuff as a block.
> 
> Have you actually seen
> 
>   SomeType FOO(^)(int x, const SomeType& y) { ... }
> 
> in real code?
I haven't seen that example, but I have seen `FOO(^, OtherParam);`.

I'm trying to change the parser to handle this now without explicitly parsing 
all block types, but it's tricky. The following should be ObjC block types:

```
(^)(int, char);
(^foo)(int, char);
(^foo[10])(int, char);
(^foo[kNum])(int, char);
(^foo[(kNum + kOtherNum)])(int, char);
```

but the following should not:

```
FOO(^);
FOO(^, int, char);
```

I'll make it work, it's just easy to make a mistake.


Repository:
  rC Clang

https://reviews.llvm.org/D43906



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


  1   2   >