[PATCH] D54295: [WIP, RISCV] Add inline asm constraint A for RISC-V

2018-11-09 Thread Lewis Revill via Phabricator via cfe-commits
lewis-revill created this revision.
lewis-revill added a reviewer: asb.
Herald added subscribers: cfe-commits, jocewei, PkmX, rkruppe, the_o, 
brucehoult, MartinMosbeck, rogfer01, mgrang, edward-jones, zzheng, jrtc27, 
shiva0217, kito-cheng, niosHD, sabuasal, apazos, simoncook, johnrusso, rbar, 
eraman.

This allows the constraint A to be used in inline asm for RISC-V, which allows 
an address held in a register to be used.

This patch adds the minimal amount of code required to get operands with the 
right constraints to compile. Semantically it would be nice to be able to use 
`setAllowsRegister` rather than `setAllowsMemory` and fall through to the 
backend to verify and lower the register as a memory operand.


Repository:
  rC Clang

https://reviews.llvm.org/D54295

Files:
  lib/Basic/Targets/RISCV.cpp
  test/CodeGen/riscv-inline-asm.c


Index: test/CodeGen/riscv-inline-asm.c
===
--- test/CodeGen/riscv-inline-asm.c
+++ test/CodeGen/riscv-inline-asm.c
@@ -26,3 +26,9 @@
 // CHECK: call void asm sideeffect "", "K"(i32 0)
   asm volatile ("" :: "K"(0));
 }
+
+void test_A(int *p) {
+// CHECK-LABEL: define void @test_A(i32* %p)
+// CHECK: call void asm volatile "", "*A"(i32* %p)
+  asm volatile("" :: "A"(*p));
+}
Index: lib/Basic/Targets/RISCV.cpp
===
--- lib/Basic/Targets/RISCV.cpp
+++ lib/Basic/Targets/RISCV.cpp
@@ -57,6 +57,10 @@
 // A 5-bit unsigned immediate for CSR access instructions.
 Info.setRequiresImmediate(0, 31);
 return true;
+  case 'A':
+// An address that is held in a general-purpose register.
+Info.setAllowsMemory();
+return true;
   }
 }
 


Index: test/CodeGen/riscv-inline-asm.c
===
--- test/CodeGen/riscv-inline-asm.c
+++ test/CodeGen/riscv-inline-asm.c
@@ -26,3 +26,9 @@
 // CHECK: call void asm sideeffect "", "K"(i32 0)
   asm volatile ("" :: "K"(0));
 }
+
+void test_A(int *p) {
+// CHECK-LABEL: define void @test_A(i32* %p)
+// CHECK: call void asm volatile "", "*A"(i32* %p)
+  asm volatile("" :: "A"(*p));
+}
Index: lib/Basic/Targets/RISCV.cpp
===
--- lib/Basic/Targets/RISCV.cpp
+++ lib/Basic/Targets/RISCV.cpp
@@ -57,6 +57,10 @@
 // A 5-bit unsigned immediate for CSR access instructions.
 Info.setRequiresImmediate(0, 31);
 return true;
+  case 'A':
+// An address that is held in a general-purpose register.
+Info.setAllowsMemory();
+return true;
   }
 }
 
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D54269: Introduce shard storage to auto-index.

2018-11-09 Thread Kadir Cetinkaya via Phabricator via cfe-commits
kadircet updated this revision to Diff 173281.
kadircet marked an inline comment as done.
kadircet added a comment.

- clang-format


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D54269

Files:
  clangd/index/Background.cpp
  clangd/index/Background.h
  unittests/clangd/BackgroundIndexTests.cpp

Index: unittests/clangd/BackgroundIndexTests.cpp
===
--- unittests/clangd/BackgroundIndexTests.cpp
+++ unittests/clangd/BackgroundIndexTests.cpp
@@ -76,5 +76,79 @@
FileURI("unittest:///root/B.cc")}));
 }
 
+TEST(BackgroundIndexTest, ShardStorageTest) {
+  class MemoryShardStorage : public ShardStorage {
+mutable std::mutex StorageMu;
+llvm::StringMap &Storage;
+size_t &CacheHits;
+
+  public:
+MemoryShardStorage(llvm::StringMap &Storage, size_t &CacheHits)
+: Storage(Storage), CacheHits(CacheHits) {}
+
+bool storeShard(llvm::StringRef ShardIdentifier, IndexFileOut Shard) const {
+  std::lock_guard Lock(StorageMu);
+  std::string &str = Storage[ShardIdentifier];
+  llvm::raw_string_ostream OS(str);
+  OS << Shard;
+  OS.flush();
+  return true;
+}
+llvm::Expected retrieveShard(llvm::StringRef ShardIdentifier,
+  FileDigest Hash) const {
+  std::lock_guard Lock(StorageMu);
+  if (Storage.find(ShardIdentifier) == Storage.end())
+return llvm::make_error(
+"Shard not found.", llvm::inconvertibleErrorCode());
+  auto IndexFile = readIndexFile(Storage[ShardIdentifier]);
+  if (!IndexFile)
+return IndexFile;
+  CacheHits++;
+  return IndexFile;
+}
+bool initialize(llvm::StringRef Directory) { return true; }
+  };
+  MockFSProvider FS;
+  FS.Files[testPath("root/A.h")] = R"cpp(
+  void common();
+  void f_b();
+  class A_CC {};
+  )cpp";
+  FS.Files[testPath("root/A.cc")] =
+  "#include \"A.h\"\nvoid g() { (void)common; }";
+  llvm::StringMap Storage;
+  size_t CacheHits = 0;
+  tooling::CompileCommand Cmd;
+  Cmd.Filename = testPath("root/A.cc");
+  Cmd.Directory = testPath("root");
+  Cmd.CommandLine = {"clang++", testPath("root/A.cc")};
+  {
+BackgroundIndex Idx(
+Context::empty(), "", FS, /*URISchemes=*/{"unittest"},
+/*IndexShardStorage=*/
+llvm::make_unique(Storage, CacheHits));
+Idx.enqueue(testPath("root"), Cmd);
+Idx.blockUntilIdleForTest();
+  }
+  EXPECT_EQ(CacheHits, 0U);
+  EXPECT_EQ(Storage.size(), 2U);
+  EXPECT_NE(Storage.find(testPath("root/A.h")), Storage.end());
+  EXPECT_NE(Storage.find(testPath("root/A.cc")), Storage.end());
+
+  {
+BackgroundIndex Idx(
+Context::empty(), "", FS, /*URISchemes=*/{"unittest"},
+/*IndexShardStorage=*/
+llvm::make_unique(Storage, CacheHits));
+Idx.enqueue(testPath("root"), Cmd);
+Idx.blockUntilIdleForTest();
+  }
+  EXPECT_EQ(CacheHits, 1U);
+  EXPECT_EQ(Storage.size(), 2U);
+  EXPECT_NE(Storage.find(testPath("root/A.h")), Storage.end());
+  EXPECT_NE(Storage.find(testPath("root/A.cc")), Storage.end());
+  // B_CC is dropped as we don't collect symbols from A.h in this compilation.
+}
+
 } // namespace clangd
 } // namespace clang
Index: clangd/index/Background.h
===
--- clangd/index/Background.h
+++ clangd/index/Background.h
@@ -14,6 +14,7 @@
 #include "FSProvider.h"
 #include "index/FileIndex.h"
 #include "index/Index.h"
+#include "index/Serialization.h"
 #include "clang/Tooling/CompilationDatabase.h"
 #include "llvm/ADT/StringMap.h"
 #include "llvm/Support/SHA1.h"
@@ -27,15 +28,27 @@
 namespace clang {
 namespace clangd {
 
+// Base class for Shard Storage operations. See DiskShardStorage for more info.
+class ShardStorage {
+public:
+  using FileDigest = decltype(llvm::SHA1::hash({}));
+  virtual bool storeShard(llvm::StringRef ShardIdentifier,
+  IndexFileOut Shard) const = 0;
+  virtual llvm::Expected
+  retrieveShard(llvm::StringRef ShardIdentifier, FileDigest Hash) const = 0;
+  virtual bool initialize(llvm::StringRef Directory) = 0;
+};
+
 // Builds an in-memory index by by running the static indexer action over
 // all commands in a compilation database. Indexing happens in the background.
 // FIXME: it should also persist its state on disk for fast start.
 // FIXME: it should watch for changes to files on disk.
 class BackgroundIndex : public SwapIndex {
 public:
   // FIXME: resource-dir injection should be hoisted somewhere common.
-  BackgroundIndex(Context BackgroundContext, StringRef ResourceDir,
+  BackgroundIndex(Context BackgroundContext, llvm::StringRef ResourceDir,
   const FileSystemProvider &, ArrayRef URISchemes,
+  std::unique_ptr IndexShardStorage = nullptr,
   size_t ThreadPoolSize = llvm::hardware_concurrency());
   ~BackgroundIndex(); // Blocks while the cu

[PATCH] D52296: [Clang] - Add -fdwarf-fission=split,single option.

2018-11-09 Thread George Rimar via Phabricator via cfe-commits
grimar added inline comments.



Comment at: lib/Driver/ToolChains/Clang.cpp:5889
   const llvm::Triple &T = getToolChain().getTriple();
-  if (Args.hasArg(options::OPT_gsplit_dwarf) &&
+  if ((getDebugFissionKind(D, Args) == DwarfFissionKind::Split) &&
   (T.isOSLinux() || T.isOSFuchsia())) {

probinson wrote:
> grimar wrote:
> > dblaikie wrote:
> > > Could having more than one call to getDebugFissionKind lead to the error 
> > > message (for -fdwarf-fission=garbage) being printed multiple times? Or is 
> > > this call on a distinct/mutually exclusive codepath to the other?
> > I think it should not be possible. Currently, there are 2 inclusions of the 
> > `getDebugFissionKind `. One is used for construction clang job,
> > and one is here, it is used to construct an assembler tool job. I do not 
> > see a way how it can be printed multiple times.
> > 
> > For example, the following invocation will print it only once:
> > 
> > ```
> > clang main.c -o out.s -S -fdwarf-fission=foo
> > clang-8: error: unsupported argument 'foo' to option 'fdwarf-fission='
> > ```
> The example you give here will not create an assembler job. Try
> `clang main.c -fdwarf-fission=foo -fno-integrated-as` which I think will 
> exercise the path David is asking about.
Oh, I did not know.

Seems the important option to test is `-save-temps`. Seems I have the same 
result with `-fno-integrated-as`/`-fintegrated-as`,
but with/without `-save-temps` I got:

```
clang main.cpp -fdwarf-fission=foo -o 1.o
clang-8: error: unsupported argument 'foo' to option 'fdwarf-fission='

clang main.cpp -fdwarf-fission=foo -o 1.o -save-temps
clang-8: error: unsupported argument 'foo' to option 'fdwarf-fission='
clang-8: error: unsupported argument 'foo' to option 'fdwarf-fission='
clang-8: error: unsupported argument 'foo' to option 'fdwarf-fission='
clang-8: error: unsupported argument 'foo' to option 'fdwarf-fission='
```

Will fix, thanks!

(The behavior seems weird to me. I would not expect tool will be creating any 
jobs should happen when the command line is invalid from the start. I am not 
very familiar with the clang code/logic though to say it wrong).


https://reviews.llvm.org/D52296



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


[PATCH] D52296: [Clang] - Add -fdwarf-fission=split,single option.

2018-11-09 Thread George Rimar via Phabricator via cfe-commits
grimar added inline comments.



Comment at: lib/Driver/ToolChains/Clang.cpp:5889
   const llvm::Triple &T = getToolChain().getTriple();
-  if (Args.hasArg(options::OPT_gsplit_dwarf) &&
+  if ((getDebugFissionKind(D, Args) == DwarfFissionKind::Split) &&
   (T.isOSLinux() || T.isOSFuchsia())) {

grimar wrote:
> probinson wrote:
> > grimar wrote:
> > > dblaikie wrote:
> > > > Could having more than one call to getDebugFissionKind lead to the 
> > > > error message (for -fdwarf-fission=garbage) being printed multiple 
> > > > times? Or is this call on a distinct/mutually exclusive codepath to the 
> > > > other?
> > > I think it should not be possible. Currently, there are 2 inclusions of 
> > > the `getDebugFissionKind `. One is used for construction clang job,
> > > and one is here, it is used to construct an assembler tool job. I do not 
> > > see a way how it can be printed multiple times.
> > > 
> > > For example, the following invocation will print it only once:
> > > 
> > > ```
> > > clang main.c -o out.s -S -fdwarf-fission=foo
> > > clang-8: error: unsupported argument 'foo' to option 'fdwarf-fission='
> > > ```
> > The example you give here will not create an assembler job. Try
> > `clang main.c -fdwarf-fission=foo -fno-integrated-as` which I think will 
> > exercise the path David is asking about.
> Oh, I did not know.
> 
> Seems the important option to test is `-save-temps`. Seems I have the same 
> result with `-fno-integrated-as`/`-fintegrated-as`,
> but with/without `-save-temps` I got:
> 
> ```
> clang main.cpp -fdwarf-fission=foo -o 1.o
> clang-8: error: unsupported argument 'foo' to option 'fdwarf-fission='
> 
> clang main.cpp -fdwarf-fission=foo -o 1.o -save-temps
> clang-8: error: unsupported argument 'foo' to option 'fdwarf-fission='
> clang-8: error: unsupported argument 'foo' to option 'fdwarf-fission='
> clang-8: error: unsupported argument 'foo' to option 'fdwarf-fission='
> clang-8: error: unsupported argument 'foo' to option 'fdwarf-fission='
> ```
> 
> Will fix, thanks!
> 
> (The behavior seems weird to me. I would not expect tool will be creating any 
> jobs should happen when the command line is invalid from the start. I am not 
> very familiar with the clang code/logic though to say it wrong).
"I would not expect tool will be creating any jobs should happen" -> "I would 
not expect tool will be creating any jobs when ..."


https://reviews.llvm.org/D52296



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


[PATCH] D54298: [clang-cl] Add warning for /Zc:dllexportInlines- when the flag is used with /fallback

2018-11-09 Thread Hans Wennborg via Phabricator via cfe-commits
hans added inline comments.



Comment at: clang/lib/Driver/ToolChains/Clang.cpp:5507
 CmdArgs.push_back("-fno-dllexport-inlines");
+if (Args.hasArg(options::OPT__SLASH_fallback)) {
+  const Arg *dllexportInlines =

I think the check should be with the code that handles /fallback, in 
visualstudio::Compiler::GetCommand, instead.


Repository:
  rL LLVM

https://reviews.llvm.org/D54298



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


[PATCH] D54300: [clangd] Respect shouldIndexFile when collecting symbols.

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

Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D54300

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

Index: unittests/clangd/SymbolCollectorTests.cpp
===
--- unittests/clangd/SymbolCollectorTests.cpp
+++ unittests/clangd/SymbolCollectorTests.cpp
@@ -523,6 +523,59 @@
AllOf(QName("Z"), RefCount(0)), QName("y")));
 }
 
+TEST_F(SymbolCollectorTest, ShouldIndexFile) {
+  const std::string IgnoredHeader = R"(
+class Foo {};
+void f();
+#define GLOBAL_Z(name) Z name;
+  )";
+
+  Annotations IndexedHeader(R"(
+class $bar[[Bar]] {};
+void $b[[b]]();
+  )");
+  Annotations Main(R"(
+#include "ignored_header.h"
+#include "indexed_header.h"
+
+void $f[[f]]() {} // only see definition
+void $b[[b]]() { $f[[f]](); }
+  )");
+  const std::string IgnoredHeaderPath = testPath("ignored_header.h");
+  const std::string IndexedHeaderPath = testPath("indexed_header.h");
+  const std::string IgnoredHeaderURI =
+  URI::createFile(IgnoredHeaderPath).toString();
+  const std::string IndexedHeaderURI =
+  URI::createFile(IndexedHeaderPath).toString();
+
+  InMemoryFileSystem->addFile(IgnoredHeaderPath, 0,
+  MemoryBuffer::getMemBuffer(IgnoredHeader));
+  InMemoryFileSystem->addFile(IndexedHeaderPath, 0,
+  MemoryBuffer::getMemBuffer(IndexedHeader.code()));
+  CollectorOpts.FileFilter = [](const SourceManager &SM, FileID FID) {
+if (const auto *F = SM.getFileEntryForID(FID))
+  return !F->getName().contains("ignored_header.h");
+return true;
+  };
+  CollectorOpts.RefFilter = RefKind::All;
+  CollectorOpts.RefsInHeaders = true;
+  runSymbolCollector("", Main.code());
+  EXPECT_THAT(Symbols,
+  UnorderedElementsAre(
+  AllOf(QName("f"), DefURI(TestFileURI), DeclURI("")),
+  AllOf(QName("Bar"), DeclRange(IndexedHeader.range("bar")),
+DeclURI(IndexedHeaderURI)),
+  AllOf(QName("b"), DeclRange(IndexedHeader.range("b")),
+DefRange(Main.range("b")), DeclURI(IndexedHeaderURI),
+DefURI(TestFileURI;
+  EXPECT_THAT(
+  Refs, UnorderedElementsAre(
+Pair(findSymbol(Symbols, "f").ID, HaveRanges(Main.ranges("f"))),
+Pair(findSymbol(Symbols, "b").ID, _),
+Pair(findSymbol(Symbols, "Bar").ID,
+ HaveRanges(IndexedHeader.ranges("bar");
+}
+
 TEST_F(SymbolCollectorTest, SymbolRelativeNoFallback) {
   runSymbolCollector("class Foo {};", /*Main=*/"");
   EXPECT_THAT(Symbols, UnorderedElementsAre(
Index: clangd/index/SymbolCollector.h
===
--- clangd/index/SymbolCollector.h
+++ clangd/index/SymbolCollector.h
@@ -111,7 +111,7 @@
 
 private:
   const Symbol *addDeclaration(const NamedDecl &, SymbolID);
-  void addDefinition(const NamedDecl &, const Symbol &DeclSymbol);
+  void addDefinition(const NamedDecl &, SymbolID, const Symbol *);
 
   // All Symbols collected from the AST.
   SymbolSlab::Builder Symbols;
Index: clangd/index/SymbolCollector.cpp
===
--- clangd/index/SymbolCollector.cpp
+++ clangd/index/SymbolCollector.cpp
@@ -257,6 +257,13 @@
   return false;
 }
 
+Symbol createBasicSymbol(SymbolID ID, const std::string &QualifiedName) {
+  Symbol S;
+  S.ID = std::move(ID);
+  std::tie(S.Scope, S.Name) = splitQualifiedName(QualifiedName);
+  return S;
+}
+
 } // namespace
 
 SymbolCollector::SymbolCollector(Options Opts) : Opts(std::move(Opts)) {}
@@ -353,9 +360,10 @@
   // D may not be an interesting symbol, but it's cheaper to check at the end.
   auto &SM = ASTCtx->getSourceManager();
   auto SpellingLoc = SM.getSpellingLoc(Loc);
+  auto FID = SM.getFileID(SpellingLoc);
   if (Opts.CountReferences &&
   (Roles & static_cast(index::SymbolRole::Reference)) &&
-  SM.getFileID(SpellingLoc) == SM.getMainFileID())
+  FID == SM.getMainFileID())
 ReferencedDecls.insert(ND);
 
   bool CollectRef = static_cast(Opts.RefFilter) & Roles;
@@ -368,8 +376,10 @@
   if (!shouldCollectSymbol(*ND, *ASTCtx, Opts))
 return true;
   if (CollectRef && !isa(ND) &&
-  (Opts.RefsInHeaders || SM.getFileID(SpellingLoc) == SM.getMainFileID()))
+  (Opts.RefsInHeaders || FID == SM.getMainFileID()) &&
+  shouldIndexFile(SM, FID, Opts, &FilesToIndexCache)) {
 DeclRefs[ND].emplace_back(SpellingLoc, Roles);
+  }
   // Don't continue indexing if this is a mere reference.
   if (IsOnlyRef)
 return true;
@@ -390,7 +400,7 @@
 BasicSymbol = addDeclaration(OriginalDecl, std::mov

[PATCH] D52296: [Clang] - Add -fdwarf-fission=split,single option.

2018-11-09 Thread George Rimar via Phabricator via cfe-commits
grimar added a comment.

Looks like this behavior is what clang already have atm. 
Messages for the options that use `D.Diag` to report invalid values can be 
printed multiple times sometimes.

The example is below:

  clang main.cpp -fdwarf-fission=foo -o 1.o -mthread-model bar 
-fcf-runtime-abi=zed
  clang-8: error: invalid thread model 'bar' in '-mthread-model bar' for this 
target
  clang-8: error: unsupported argument 'foo' to option 'fdwarf-fission='
  clang-8: error: invalid CoreFoundation Runtime ABI 'zed'; must be one of 
'objc', 'standalone', 'swift', 'swift-5.0', 'swift-4.2', 'swift-4.1'



  clang main.cpp -fdwarf-fission=foo -o 1.o -mthread-model bar 
-fcf-runtime-abi=zed -save-temps
  clang-8: error: invalid thread model 'bar' in '-mthread-model bar' for this 
target
  clang-8: error: unsupported argument 'foo' to option 'fdwarf-fission='
  clang-8: error: invalid CoreFoundation Runtime ABI 'zed'; must be one of 
'objc', 'standalone', 'swift', 'swift-5.0', 'swift-4.2', 'swift-4.1'
  clang-8: error: invalid thread model 'bar' in '-mthread-model bar' for this 
target
  clang-8: error: unsupported argument 'foo' to option 'fdwarf-fission='
  clang-8: error: invalid CoreFoundation Runtime ABI 'zed'; must be one of 
'objc', 'standalone', 'swift', 'swift-5.0', 'swift-4.2', 'swift-4.1'
  clang-8: error: invalid thread model 'bar' in '-mthread-model bar' for this 
target
  clang-8: error: unsupported argument 'foo' to option 'fdwarf-fission='
  clang-8: error: invalid CoreFoundation Runtime ABI 'zed'; must be one of 
'objc', 'standalone', 'swift', 'swift-5.0', 'swift-4.2', 'swift-4.1'
  clang-8: error: unsupported argument 'foo' to option 'fdwarf-fission='

So it seems to me this patch just follows the behavior and nothing should be 
fixed at this point right now?


https://reviews.llvm.org/D52296



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


[PATCH] D54246: [clang-tidy] Add the abseil-duration-factory-scale check

2018-11-09 Thread Haojian Wu via Phabricator via cfe-commits
hokein added inline comments.



Comment at: clang-tidy/abseil/DurationFactoryScaleCheck.cpp:36
+GetScaleForFactory(llvm::StringRef FactoryName) {
+  static const auto *ScaleMap =
+  new std::unordered_map(

aaron.ballman wrote:
> hwright wrote:
> > Eugene.Zelenko wrote:
> > > This will cause memory leaks, so may be unique_ptr should be used to hold 
> > > pointer? May be LLVM ADT has better container?
> > This is a tradeoff between leaking a small amount of known memory for the 
> > duration of the program, and constructing this map every time this function 
> > is invoked.  Since I expect the latter to occur frequently, that's a 
> > tradeoff I think is acceptable.   (Ideally, this would be a compile-time 
> > constant, but sadly we don't yet have a `constexpr` dictionary type.)
> > 
> > Of course, if there is a more typical way of doing that here, I'm happy to 
> > use it.
> Why did you not use a static value type?
I think main reason is lazy initialization.



Comment at: clang-tidy/abseil/DurationFactoryScaleCheck.cpp:22
+// Potential scales of our inputs.
+enum class DurationScale {
+  Hours,

nit: wrap it in anonymous namespace? 



Comment at: clang-tidy/abseil/DurationFactoryScaleCheck.cpp:74
+  case DurationScale::Minutes:
+if (Multiplier == 60.0)
+  return DurationScale::Hours;

we are comparing with floats, I think we should use something 
`AlmostEquals(Multiplier, 60.0)`.



Comment at: clang-tidy/abseil/DurationFactoryScaleCheck.cpp:202
+  // Don't try and replace things inside of macro definitions.
+  if (InsideMacroDefinition(Result, Call->getSourceRange()))
+return;

isn't `Call->getExprLoc().isMacroID()` enough?



Comment at: clang-tidy/abseil/DurationFactoryScaleCheck.cpp:266
+  if (DivBinOp) {
+DivBinOp->dumpColor();
+// For division, we only check the RHS.

is this for debugging?


https://reviews.llvm.org/D54246



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


r346485 - [Tooling] Avoid diagnosing missing input files in an edge-case where it's incorrect.

2018-11-09 Thread Sam McCall via cfe-commits
Author: sammccall
Date: Fri Nov  9 03:49:22 2018
New Revision: 346485

URL: http://llvm.org/viewvc/llvm-project?rev=346485&view=rev
Log:
[Tooling] Avoid diagnosing missing input files in an edge-case where it's 
incorrect.

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

Modified: cfe/trunk/lib/Tooling/Tooling.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Tooling/Tooling.cpp?rev=346485&r1=346484&r2=346485&view=diff
==
--- cfe/trunk/lib/Tooling/Tooling.cpp (original)
+++ cfe/trunk/lib/Tooling/Tooling.cpp Fri Nov  9 03:49:22 2018
@@ -303,6 +303,12 @@ bool ToolInvocation::run() {
 
   const std::unique_ptr Driver(
   newDriver(&Diagnostics, BinaryName, Files->getVirtualFileSystem()));
+  // The "input file not found" diagnostics from the driver are useful.
+  // The driver is only aware of the VFS working directory, but some clients
+  // change this at the FileManager level instead.
+  // In this case the checks have false positives, so skip them.
+  if (!Files->getFileSystemOpts().WorkingDir.empty())
+Driver->setCheckInputsExist(false);
   const std::unique_ptr Compilation(
   Driver->BuildCompilation(llvm::makeArrayRef(Argv)));
   if (!Compilation)


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


[PATCH] D54258: [Clang] Fix pretty printing of CUDA address spaces

2018-11-09 Thread Anastasia Stulova via Phabricator via cfe-commits
Anastasia added a comment.

Could this be tested using diagnostics that prints the type? Like in 
test/SemaOpenCL/address-spaces.cl.


Repository:
  rC Clang

https://reviews.llvm.org/D54258



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


[PATCH] D52296: [Clang] - Add -fdwarf-fission=split,single option.

2018-11-09 Thread George Rimar via Phabricator via cfe-commits
grimar added inline comments.



Comment at: lib/Driver/ToolChains/Clang.cpp:5889
   const llvm::Triple &T = getToolChain().getTriple();
-  if (Args.hasArg(options::OPT_gsplit_dwarf) &&
+  if ((getDebugFissionKind(D, Args) == DwarfFissionKind::Split) &&
   (T.isOSLinux() || T.isOSFuchsia())) {

grimar wrote:
> grimar wrote:
> > probinson wrote:
> > > grimar wrote:
> > > > dblaikie wrote:
> > > > > Could having more than one call to getDebugFissionKind lead to the 
> > > > > error message (for -fdwarf-fission=garbage) being printed multiple 
> > > > > times? Or is this call on a distinct/mutually exclusive codepath to 
> > > > > the other?
> > > > I think it should not be possible. Currently, there are 2 inclusions of 
> > > > the `getDebugFissionKind `. One is used for construction clang job,
> > > > and one is here, it is used to construct an assembler tool job. I do 
> > > > not see a way how it can be printed multiple times.
> > > > 
> > > > For example, the following invocation will print it only once:
> > > > 
> > > > ```
> > > > clang main.c -o out.s -S -fdwarf-fission=foo
> > > > clang-8: error: unsupported argument 'foo' to option 'fdwarf-fission='
> > > > ```
> > > The example you give here will not create an assembler job. Try
> > > `clang main.c -fdwarf-fission=foo -fno-integrated-as` which I think will 
> > > exercise the path David is asking about.
> > Oh, I did not know.
> > 
> > Seems the important option to test is `-save-temps`. Seems I have the same 
> > result with `-fno-integrated-as`/`-fintegrated-as`,
> > but with/without `-save-temps` I got:
> > 
> > ```
> > clang main.cpp -fdwarf-fission=foo -o 1.o
> > clang-8: error: unsupported argument 'foo' to option 'fdwarf-fission='
> > 
> > clang main.cpp -fdwarf-fission=foo -o 1.o -save-temps
> > clang-8: error: unsupported argument 'foo' to option 'fdwarf-fission='
> > clang-8: error: unsupported argument 'foo' to option 'fdwarf-fission='
> > clang-8: error: unsupported argument 'foo' to option 'fdwarf-fission='
> > clang-8: error: unsupported argument 'foo' to option 'fdwarf-fission='
> > ```
> > 
> > Will fix, thanks!
> > 
> > (The behavior seems weird to me. I would not expect tool will be creating 
> > any jobs should happen when the command line is invalid from the start. I 
> > am not very familiar with the clang code/logic though to say it wrong).
> "I would not expect tool will be creating any jobs should happen" -> "I would 
> not expect tool will be creating any jobs when ..."
And returning to this my example, indeed it should not have to create assembler 
job.
My mistake, sorry, just my head was overloaded with tons of new things.

The correct example should be:

```
clang library.s -fdwarf-fission=foo -o 1.o
clang-8: error: unsupported argument 'foo' to option 'fdwarf-fission='
```

So in this case clang creates the assembler job and prints the message only 
once.

If we add some *.cpp then we will see multiple messages (one for each job):

```
clang library.s main.cpp -fdwarf-fission=foo -o 1.o
clang-8: error: unsupported argument 'foo' to option 'fdwarf-fission='
clang-8: error: unsupported argument 'foo' to option 'fdwarf-fission='
```

But this is consistent with what clang already do. For example `-masm=` will 
trigger the same behavior:

```
~/LLVM/build_lldb/bin/clang library.s main.cpp -fdwarf-fission=foo -o 1.o 
-masm=foo
clang-8: error: unsupported argument 'foo' to option 'masm='
clang-8: error: unsupported argument 'foo' to option 'fdwarf-fission='
clang-8: error: unsupported argument 'foo' to option 'masm='
clang-8: error: unsupported argument 'foo' to option 'fdwarf-fission=
```

i.e. for options that are used both in main clang job and "secondary" jobs, 
like `as` that is possible already.


https://reviews.llvm.org/D52296



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


[PATCH] D54253: [OpenCL][NFC] Improve test coverage of test/Index/opencl-types.cl

2018-11-09 Thread Anastasia Stulova via Phabricator via cfe-commits
Anastasia added a comment.

Are these types represented differently wrt targets?


Repository:
  rC Clang

https://reviews.llvm.org/D54253



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


[PATCH] D54300: [clangd] Respect shouldIndexFile when collecting symbols.

2018-11-09 Thread Eric Liu via Phabricator via cfe-commits
ioeric added inline comments.



Comment at: clangd/index/SymbolCollector.cpp:555
+  auto Loc = findNameLoc(&ND);
+  if (!shouldIndexFile(SM, SM.getFileID(Loc), Opts, &FilesToIndexCache))
+return nullptr;

Should we use `getTokenLocation` like what we do below?



Comment at: clangd/index/SymbolCollector.cpp:614
 
-void SymbolCollector::addDefinition(const NamedDecl &ND,
-const Symbol &DeclSym) {
-  if (DeclSym.Definition)
+void SymbolCollector::addDefinition(const NamedDecl &ND, SymbolID ID,
+const Symbol *DeclSym) {

IIUC, if `D` is declared in d.h that is filtered out and defined in d.cc that 
is not filtered, this would only create a basic symbol with definition? 

I think what we want is a full symbol with declaration, definition, includes 
etc. This is one assumption we make in order for the merging in auto-index to 
work.


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D54300



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


[PATCH] D54298: [clang-cl] Add warning for /Zc:dllexportInlines- when the flag is used with /fallback

2018-11-09 Thread Takuto Ikuta via Phabricator via cfe-commits
takuto.ikuta updated this revision to Diff 173302.
takuto.ikuta added a comment.

warn in GetCommand


Repository:
  rL LLVM

https://reviews.llvm.org/D54298

Files:
  clang/include/clang/Basic/DiagnosticDriverKinds.td
  clang/lib/Driver/ToolChains/MSVC.cpp
  clang/test/Driver/cl-options.c


Index: clang/test/Driver/cl-options.c
===
--- clang/test/Driver/cl-options.c
+++ clang/test/Driver/cl-options.c
@@ -494,6 +494,8 @@
 // NoDllExportInlines: "-fno-dllexport-inlines"
 // RUN: %clang_cl /Zc:dllexportInlines /c -### -- %s 2>&1 | FileCheck 
-check-prefix=DllExportInlines %s
 // DllExportInlines-NOT: "-fno-dllexport-inlines"
+// RUN: %clang_cl /fallback /Zc:dllexportInlines- /c -### -- %s 2>&1 | 
FileCheck -check-prefix=DllExportInlinesFallback %s
+// DllExportInlinesFallback: warning: option '/Zc:dllexportInlines-' is 
ignored when /fallback happens [-Woption-ignored]
 
 // RUN: %clang_cl /Zi /c -### -- %s 2>&1 | FileCheck -check-prefix=Zi %s
 // Zi: "-gcodeview"
Index: clang/lib/Driver/ToolChains/MSVC.cpp
===
--- clang/lib/Driver/ToolChains/MSVC.cpp
+++ clang/lib/Driver/ToolChains/MSVC.cpp
@@ -669,6 +669,12 @@
   // them too.
   Args.AddAllArgs(CmdArgs, options::OPT_UNKNOWN);
 
+  // Warning for ignored flag.
+  if (const Arg *dllexportInlines =
+  Args.getLastArg(options::OPT__SLASH_Zc_dllexportInlines_))
+C.getDriver().Diag(clang::diag::warn_drv_non_fallback_argument_clang_cl)
+  << dllexportInlines->getAsString(Args);
+
   // Input filename.
   assert(Inputs.size() == 1);
   const InputInfo &II = Inputs[0];
Index: clang/include/clang/Basic/DiagnosticDriverKinds.td
===
--- clang/include/clang/Basic/DiagnosticDriverKinds.td
+++ clang/include/clang/Basic/DiagnosticDriverKinds.td
@@ -161,6 +161,10 @@
   "support for '/Yc' with more than one source file not implemented yet; flag 
ignored">,
   InGroup;
 
+def warn_drv_non_fallback_argument_clang_cl : Warning<
+  "option '%0' is ignored when /fallback happens">,
+  InGroup;
+
 def err_drv_invalid_value : Error<"invalid value '%1' in '%0'">;
 def err_drv_invalid_int_value : Error<"invalid integral value '%1' in '%0'">;
 def err_drv_invalid_remap_file : Error<


Index: clang/test/Driver/cl-options.c
===
--- clang/test/Driver/cl-options.c
+++ clang/test/Driver/cl-options.c
@@ -494,6 +494,8 @@
 // NoDllExportInlines: "-fno-dllexport-inlines"
 // RUN: %clang_cl /Zc:dllexportInlines /c -### -- %s 2>&1 | FileCheck -check-prefix=DllExportInlines %s
 // DllExportInlines-NOT: "-fno-dllexport-inlines"
+// RUN: %clang_cl /fallback /Zc:dllexportInlines- /c -### -- %s 2>&1 | FileCheck -check-prefix=DllExportInlinesFallback %s
+// DllExportInlinesFallback: warning: option '/Zc:dllexportInlines-' is ignored when /fallback happens [-Woption-ignored]
 
 // RUN: %clang_cl /Zi /c -### -- %s 2>&1 | FileCheck -check-prefix=Zi %s
 // Zi: "-gcodeview"
Index: clang/lib/Driver/ToolChains/MSVC.cpp
===
--- clang/lib/Driver/ToolChains/MSVC.cpp
+++ clang/lib/Driver/ToolChains/MSVC.cpp
@@ -669,6 +669,12 @@
   // them too.
   Args.AddAllArgs(CmdArgs, options::OPT_UNKNOWN);
 
+  // Warning for ignored flag.
+  if (const Arg *dllexportInlines =
+  Args.getLastArg(options::OPT__SLASH_Zc_dllexportInlines_))
+C.getDriver().Diag(clang::diag::warn_drv_non_fallback_argument_clang_cl)
+  << dllexportInlines->getAsString(Args);
+
   // Input filename.
   assert(Inputs.size() == 1);
   const InputInfo &II = Inputs[0];
Index: clang/include/clang/Basic/DiagnosticDriverKinds.td
===
--- clang/include/clang/Basic/DiagnosticDriverKinds.td
+++ clang/include/clang/Basic/DiagnosticDriverKinds.td
@@ -161,6 +161,10 @@
   "support for '/Yc' with more than one source file not implemented yet; flag ignored">,
   InGroup;
 
+def warn_drv_non_fallback_argument_clang_cl : Warning<
+  "option '%0' is ignored when /fallback happens">,
+  InGroup;
+
 def err_drv_invalid_value : Error<"invalid value '%1' in '%0'">;
 def err_drv_invalid_int_value : Error<"invalid integral value '%1' in '%0'">;
 def err_drv_invalid_remap_file : Error<
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D54298: [clang-cl] Add warning for /Zc:dllexportInlines- when the flag is used with /fallback

2018-11-09 Thread Takuto Ikuta via Phabricator via cfe-commits
takuto.ikuta marked an inline comment as done.
takuto.ikuta added a comment.

Thank you for review!


Repository:
  rL LLVM

https://reviews.llvm.org/D54298



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


[clang-tools-extra] r346488 - [clangd] Make TestTU build with preamble, and fix the fallout.

2018-11-09 Thread Sam McCall via cfe-commits
Author: sammccall
Date: Fri Nov  9 04:56:49 2018
New Revision: 346488

URL: http://llvm.org/viewvc/llvm-project?rev=346488&view=rev
Log:
[clangd] Make TestTU build with preamble, and fix the fallout.

Our testing didn't reflect reality: live clangd almost always uses a
preamble, and sometimes the preamble behaves differently.
This patch fixes a common test helper to be more realistic.

Preamble doesn't preserve information about which tokens come from the
command-line (this gets inlined into a source file). So remove logic
that attempts to treat symbols with such names differently.

A SymbolCollectorTest tries to verify that locals in headers are not
indexed, with preamble enabled this is only meaningful for locals of
auto-typed functions (otherwise the bodies aren't parsed).

Tests were relying on the fact that the findAnyDecl helper actually did expose
symbols from headers. Resolve by making all these functions consistently
able to find symbols in headers/preambles.

Modified:
clang-tools-extra/trunk/clangd/AST.cpp
clang-tools-extra/trunk/unittests/clangd/QualityTests.cpp
clang-tools-extra/trunk/unittests/clangd/SymbolCollectorTests.cpp
clang-tools-extra/trunk/unittests/clangd/TestTU.cpp
clang-tools-extra/trunk/unittests/clangd/TestTU.h

Modified: clang-tools-extra/trunk/clangd/AST.cpp
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clangd/AST.cpp?rev=346488&r1=346487&r2=346488&view=diff
==
--- clang-tools-extra/trunk/clangd/AST.cpp (original)
+++ clang-tools-extra/trunk/clangd/AST.cpp Fri Nov  9 04:56:49 2018
@@ -20,11 +20,9 @@ namespace clang {
 namespace clangd {
 
 // Returns true if the complete name of decl \p D is spelled in the source 
code.
-// This is not the case for
-//   * symbols formed via macro concatenation, the spelling location will
-// be ""
-//   * symbols controlled and defined by a compile command-line option
-// `-DName=foo`, the spelling location will be "".
+// This is not the case for symbols formed via macro concatenation.
+// (We used to attempt to treat names spelled on the command-line this way too,
+// but the preamble doesn't preserve the required information).
 bool isSpelledInSourceCode(const Decl *D) {
   const auto &SM = D->getASTContext().getSourceManager();
   auto Loc = D->getLocation();
@@ -32,8 +30,7 @@ bool isSpelledInSourceCode(const Decl *D
   // macros, we should use the location where the whole definition occurs.
   if (Loc.isMacroID()) {
 std::string PrintLoc = SM.getSpellingLoc(Loc).printToString(SM);
-if (StringRef(PrintLoc).startswith(""))
+if (StringRef(PrintLoc).startswith("http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/unittests/clangd/QualityTests.cpp?rev=346488&r1=346487&r2=346488&view=diff
==
--- clang-tools-extra/trunk/unittests/clangd/QualityTests.cpp (original)
+++ clang-tools-extra/trunk/unittests/clangd/QualityTests.cpp Fri Nov  9 
04:56:49 2018
@@ -50,10 +50,7 @@ TEST(QualityTests, SymbolQualitySignalEx
 #define DECL_NAME(x, y) x##_##y##_Decl
 #define DECL(x, y) class DECL_NAME(x, y) {};
 DECL(X, Y); // X_Y_Decl
-
-class MAC {};
   )cpp");
-  Header.ExtraArgs = {"-DMAC=mac_name"};
 
   auto Symbols = Header.headerSymbols();
   auto AST = Header.build();
@@ -69,11 +66,6 @@ TEST(QualityTests, SymbolQualitySignalEx
   Quality.merge(findSymbol(Symbols, "X_Y_Decl"));
   EXPECT_TRUE(Quality.ImplementationDetail);
 
-  Quality.ImplementationDetail = false;
-  Quality.merge(
-  CodeCompletionResult(&findDecl(AST, "mac_name"), /*Priority=*/42));
-  EXPECT_TRUE(Quality.ImplementationDetail);
-
   Symbol F = findSymbol(Symbols, "_f");
   F.References = 24; // TestTU doesn't count references, so fake it.
   Quality = {};
@@ -148,17 +140,13 @@ TEST(QualityTests, SymbolRelevanceSignal
 
   auto constructShadowDeclCompletionResult = [&](const std::string DeclName) {
 auto *Shadow =
-*dyn_cast(
- &findAnyDecl(AST,
-  [&](const NamedDecl &ND) {
-if (const UsingDecl *Using =
-dyn_cast(&ND))
-  if (Using->shadow_size() &&
-  Using->getQualifiedNameAsString() == 
DeclName)
-return true;
-return false;
-  }))
- ->shadow_begin();
+*dyn_cast(&findDecl(AST, [&](const NamedDecl &ND) {
+   if (const UsingDecl *Using = dyn_cast(&ND))
+ if (Using->shadow_size() &&
+ Using->getQualifiedNameAsString() == DeclName)
+   return true;
+   return false;
+ }))->shadow_begin();
 CodeCompletionResult Result(Shadow->getTargetDecl(), 42);
 Result.ShadowDecl = Shadow;
 return Result;
@@ -173,13 +161

[PATCH] D54298: [clang-cl] Add warning for /Zc:dllexportInlines- when the flag is used with /fallback

2018-11-09 Thread Hans Wennborg via Phabricator via cfe-commits
hans accepted this revision.
hans added a comment.
This revision is now accepted and ready to land.

lgtm


Repository:
  rL LLVM

https://reviews.llvm.org/D54298



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


[PATCH] D54303: [clangd] Don't treat top-level decls as "local" if they are from the preamble.

2018-11-09 Thread Sam McCall via Phabricator via cfe-commits
sammccall created this revision.
sammccall added a reviewer: ilya-biryukov.
Herald added subscribers: cfe-commits, kadircet, arphaman, jkorous, MaskRay, 
ioeric.

These get passed to HandleTopLevelDecl() if they happen to have been
deserialized for any reason. We don't want to treat them as part of the
main file.


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D54303

Files:
  clangd/ClangdUnit.cpp
  unittests/clangd/ClangdUnitTests.cpp


Index: unittests/clangd/ClangdUnitTests.cpp
===
--- unittests/clangd/ClangdUnitTests.cpp
+++ unittests/clangd/ClangdUnitTests.cpp
@@ -257,6 +257,20 @@
   }
 }
 
+TEST(ClangdUnitTest, TopLevelDecls) {
+  TestTU TU;
+  TU.HeaderCode = R"(
+int header1();
+int header2;
+  )";
+  TU.Code = "int main();";
+  auto AST = TU.build();
+  ASSERT_EQ(AST.getLocalTopLevelDecls().size(), 1u);
+  NamedDecl *ND = dyn_cast(AST.getLocalTopLevelDecls().front());
+  ASSERT_TRUE(ND);
+  ASSERT_EQ("main", ND->getNameAsString());
+}
+
 } // namespace
 } // namespace clangd
 } // namespace clang
Index: clangd/ClangdUnit.cpp
===
--- clangd/ClangdUnit.cpp
+++ clangd/ClangdUnit.cpp
@@ -57,6 +57,9 @@
 
   bool HandleTopLevelDecl(DeclGroupRef DG) override {
 for (Decl *D : DG) {
+  if (D->isFromASTFile())
+continue;
+
   // ObjCMethodDecl are not actually top-level decls.
   if (isa(D))
 continue;


Index: unittests/clangd/ClangdUnitTests.cpp
===
--- unittests/clangd/ClangdUnitTests.cpp
+++ unittests/clangd/ClangdUnitTests.cpp
@@ -257,6 +257,20 @@
   }
 }
 
+TEST(ClangdUnitTest, TopLevelDecls) {
+  TestTU TU;
+  TU.HeaderCode = R"(
+int header1();
+int header2;
+  )";
+  TU.Code = "int main();";
+  auto AST = TU.build();
+  ASSERT_EQ(AST.getLocalTopLevelDecls().size(), 1u);
+  NamedDecl *ND = dyn_cast(AST.getLocalTopLevelDecls().front());
+  ASSERT_TRUE(ND);
+  ASSERT_EQ("main", ND->getNameAsString());
+}
+
 } // namespace
 } // namespace clangd
 } // namespace clang
Index: clangd/ClangdUnit.cpp
===
--- clangd/ClangdUnit.cpp
+++ clangd/ClangdUnit.cpp
@@ -57,6 +57,9 @@
 
   bool HandleTopLevelDecl(DeclGroupRef DG) override {
 for (Decl *D : DG) {
+  if (D->isFromASTFile())
+continue;
+
   // ObjCMethodDecl are not actually top-level decls.
   if (isa(D))
 continue;
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


r346491 - [clang-cl] Add warning for /Zc:dllexportInlines- when the flag is used with /fallback

2018-11-09 Thread Takuto Ikuta via cfe-commits
Author: tikuta
Date: Fri Nov  9 05:25:45 2018
New Revision: 346491

URL: http://llvm.org/viewvc/llvm-project?rev=346491&view=rev
Log:
[clang-cl] Add warning for /Zc:dllexportInlines- when the flag is used with 
/fallback

Summary:
This is followup of
https://reviews.llvm.org/D51340

Reviewers: hans, thakis

Reviewed By: hans

Subscribers: cfe-commits, llvm-commits

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

Modified:
cfe/trunk/include/clang/Basic/DiagnosticDriverKinds.td
cfe/trunk/lib/Driver/ToolChains/MSVC.cpp
cfe/trunk/test/Driver/cl-options.c

Modified: cfe/trunk/include/clang/Basic/DiagnosticDriverKinds.td
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Basic/DiagnosticDriverKinds.td?rev=346491&r1=346490&r2=346491&view=diff
==
--- cfe/trunk/include/clang/Basic/DiagnosticDriverKinds.td (original)
+++ cfe/trunk/include/clang/Basic/DiagnosticDriverKinds.td Fri Nov  9 05:25:45 
2018
@@ -161,6 +161,10 @@ def warn_drv_yc_multiple_inputs_clang_cl
   "support for '/Yc' with more than one source file not implemented yet; flag 
ignored">,
   InGroup;
 
+def warn_drv_non_fallback_argument_clang_cl : Warning<
+  "option '%0' is ignored when /fallback happens">,
+  InGroup;
+
 def err_drv_invalid_value : Error<"invalid value '%1' in '%0'">;
 def err_drv_invalid_int_value : Error<"invalid integral value '%1' in '%0'">;
 def err_drv_invalid_remap_file : Error<

Modified: cfe/trunk/lib/Driver/ToolChains/MSVC.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Driver/ToolChains/MSVC.cpp?rev=346491&r1=346490&r2=346491&view=diff
==
--- cfe/trunk/lib/Driver/ToolChains/MSVC.cpp (original)
+++ cfe/trunk/lib/Driver/ToolChains/MSVC.cpp Fri Nov  9 05:25:45 2018
@@ -669,6 +669,12 @@ std::unique_ptr visualstudio::C
   // them too.
   Args.AddAllArgs(CmdArgs, options::OPT_UNKNOWN);
 
+  // Warning for ignored flag.
+  if (const Arg *dllexportInlines =
+  Args.getLastArg(options::OPT__SLASH_Zc_dllexportInlines_))
+C.getDriver().Diag(clang::diag::warn_drv_non_fallback_argument_clang_cl)
+  << dllexportInlines->getAsString(Args);
+
   // Input filename.
   assert(Inputs.size() == 1);
   const InputInfo &II = Inputs[0];

Modified: cfe/trunk/test/Driver/cl-options.c
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/Driver/cl-options.c?rev=346491&r1=346490&r2=346491&view=diff
==
--- cfe/trunk/test/Driver/cl-options.c (original)
+++ cfe/trunk/test/Driver/cl-options.c Fri Nov  9 05:25:45 2018
@@ -494,6 +494,8 @@
 // NoDllExportInlines: "-fno-dllexport-inlines"
 // RUN: %clang_cl /Zc:dllexportInlines /c -### -- %s 2>&1 | FileCheck 
-check-prefix=DllExportInlines %s
 // DllExportInlines-NOT: "-fno-dllexport-inlines"
+// RUN: %clang_cl /fallback /Zc:dllexportInlines- /c -### -- %s 2>&1 | 
FileCheck -check-prefix=DllExportInlinesFallback %s
+// DllExportInlinesFallback: warning: option '/Zc:dllexportInlines-' is 
ignored when /fallback happens [-Woption-ignored]
 
 // RUN: %clang_cl /Zi /c -### -- %s 2>&1 | FileCheck -check-prefix=Zi %s
 // Zi: "-gcodeview"


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


[PATCH] D54298: [clang-cl] Add warning for /Zc:dllexportInlines- when the flag is used with /fallback

2018-11-09 Thread Phabricator via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rC346491: [clang-cl] Add warning for /Zc:dllexportInlines- 
when the flag is used with… (authored by tikuta, committed by ).

Changed prior to commit:
  https://reviews.llvm.org/D54298?vs=173302&id=173305#toc

Repository:
  rC Clang

https://reviews.llvm.org/D54298

Files:
  include/clang/Basic/DiagnosticDriverKinds.td
  lib/Driver/ToolChains/MSVC.cpp
  test/Driver/cl-options.c


Index: test/Driver/cl-options.c
===
--- test/Driver/cl-options.c
+++ test/Driver/cl-options.c
@@ -494,6 +494,8 @@
 // NoDllExportInlines: "-fno-dllexport-inlines"
 // RUN: %clang_cl /Zc:dllexportInlines /c -### -- %s 2>&1 | FileCheck 
-check-prefix=DllExportInlines %s
 // DllExportInlines-NOT: "-fno-dllexport-inlines"
+// RUN: %clang_cl /fallback /Zc:dllexportInlines- /c -### -- %s 2>&1 | 
FileCheck -check-prefix=DllExportInlinesFallback %s
+// DllExportInlinesFallback: warning: option '/Zc:dllexportInlines-' is 
ignored when /fallback happens [-Woption-ignored]
 
 // RUN: %clang_cl /Zi /c -### -- %s 2>&1 | FileCheck -check-prefix=Zi %s
 // Zi: "-gcodeview"
Index: lib/Driver/ToolChains/MSVC.cpp
===
--- lib/Driver/ToolChains/MSVC.cpp
+++ lib/Driver/ToolChains/MSVC.cpp
@@ -669,6 +669,12 @@
   // them too.
   Args.AddAllArgs(CmdArgs, options::OPT_UNKNOWN);
 
+  // Warning for ignored flag.
+  if (const Arg *dllexportInlines =
+  Args.getLastArg(options::OPT__SLASH_Zc_dllexportInlines_))
+C.getDriver().Diag(clang::diag::warn_drv_non_fallback_argument_clang_cl)
+  << dllexportInlines->getAsString(Args);
+
   // Input filename.
   assert(Inputs.size() == 1);
   const InputInfo &II = Inputs[0];
Index: include/clang/Basic/DiagnosticDriverKinds.td
===
--- include/clang/Basic/DiagnosticDriverKinds.td
+++ include/clang/Basic/DiagnosticDriverKinds.td
@@ -161,6 +161,10 @@
   "support for '/Yc' with more than one source file not implemented yet; flag 
ignored">,
   InGroup;
 
+def warn_drv_non_fallback_argument_clang_cl : Warning<
+  "option '%0' is ignored when /fallback happens">,
+  InGroup;
+
 def err_drv_invalid_value : Error<"invalid value '%1' in '%0'">;
 def err_drv_invalid_int_value : Error<"invalid integral value '%1' in '%0'">;
 def err_drv_invalid_remap_file : Error<


Index: test/Driver/cl-options.c
===
--- test/Driver/cl-options.c
+++ test/Driver/cl-options.c
@@ -494,6 +494,8 @@
 // NoDllExportInlines: "-fno-dllexport-inlines"
 // RUN: %clang_cl /Zc:dllexportInlines /c -### -- %s 2>&1 | FileCheck -check-prefix=DllExportInlines %s
 // DllExportInlines-NOT: "-fno-dllexport-inlines"
+// RUN: %clang_cl /fallback /Zc:dllexportInlines- /c -### -- %s 2>&1 | FileCheck -check-prefix=DllExportInlinesFallback %s
+// DllExportInlinesFallback: warning: option '/Zc:dllexportInlines-' is ignored when /fallback happens [-Woption-ignored]
 
 // RUN: %clang_cl /Zi /c -### -- %s 2>&1 | FileCheck -check-prefix=Zi %s
 // Zi: "-gcodeview"
Index: lib/Driver/ToolChains/MSVC.cpp
===
--- lib/Driver/ToolChains/MSVC.cpp
+++ lib/Driver/ToolChains/MSVC.cpp
@@ -669,6 +669,12 @@
   // them too.
   Args.AddAllArgs(CmdArgs, options::OPT_UNKNOWN);
 
+  // Warning for ignored flag.
+  if (const Arg *dllexportInlines =
+  Args.getLastArg(options::OPT__SLASH_Zc_dllexportInlines_))
+C.getDriver().Diag(clang::diag::warn_drv_non_fallback_argument_clang_cl)
+  << dllexportInlines->getAsString(Args);
+
   // Input filename.
   assert(Inputs.size() == 1);
   const InputInfo &II = Inputs[0];
Index: include/clang/Basic/DiagnosticDriverKinds.td
===
--- include/clang/Basic/DiagnosticDriverKinds.td
+++ include/clang/Basic/DiagnosticDriverKinds.td
@@ -161,6 +161,10 @@
   "support for '/Yc' with more than one source file not implemented yet; flag ignored">,
   InGroup;
 
+def warn_drv_non_fallback_argument_clang_cl : Warning<
+  "option '%0' is ignored when /fallback happens">,
+  InGroup;
+
 def err_drv_invalid_value : Error<"invalid value '%1' in '%0'">;
 def err_drv_invalid_int_value : Error<"invalid integral value '%1' in '%0'">;
 def err_drv_invalid_remap_file : Error<
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D54303: [clangd] Don't treat top-level decls as "local" if they are from the preamble.

2018-11-09 Thread Ilya Biryukov via Phabricator via cfe-commits
ilya-biryukov accepted this revision.
ilya-biryukov added a comment.
This revision is now accepted and ready to land.

LGTM!




Comment at: unittests/clangd/ClangdUnitTests.cpp:268
+  auto AST = TU.build();
+  ASSERT_EQ(AST.getLocalTopLevelDecls().size(), 1u);
+  NamedDecl *ND = dyn_cast(AST.getLocalTopLevelDecls().front());

NIT: maybe use `ASSEET_THAT(AST.getLocalTopLevelDecls(), ElementsAre(...))`

Unless that's too hard for some reason.


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D54303



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


[PATCH] D54281: [clang-tidy] fix PR39583 - ignoring ParenCast for string-literals in pro-bounds-array-to-pointer-decay

2018-11-09 Thread Jonas Toth via Phabricator via cfe-commits
JonasToth updated this revision to Diff 173311.
JonasToth added a comment.

- use ignoringParens instead


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D54281

Files:
  clang-tidy/cppcoreguidelines/ProBoundsArrayToPointerDecayCheck.cpp
  test/clang-tidy/cppcoreguidelines-pro-bounds-array-to-pointer-decay.cpp


Index: test/clang-tidy/cppcoreguidelines-pro-bounds-array-to-pointer-decay.cpp
===
--- test/clang-tidy/cppcoreguidelines-pro-bounds-array-to-pointer-decay.cpp
+++ test/clang-tidy/cppcoreguidelines-pro-bounds-array-to-pointer-decay.cpp
@@ -30,6 +30,7 @@
   arrayviewfun(av); // OK
 
   int i = a[0];  // OK
+  int j = a[(1 + 2)];// OK
   pointerfun(&a[0]); // OK
 
   for (auto &e : a) // OK, iteration internally decays array to pointer
@@ -39,6 +40,9 @@
 const char *g() {
   return "clang"; // OK, decay string literal to pointer
 }
+const char *g2() {
+return ("clang"); // OK, ParenCast hides the literal-pointer decay
+}
 
 void f2(void *const *);
 void bug25362() {
Index: clang-tidy/cppcoreguidelines/ProBoundsArrayToPointerDecayCheck.cpp
===
--- clang-tidy/cppcoreguidelines/ProBoundsArrayToPointerDecayCheck.cpp
+++ clang-tidy/cppcoreguidelines/ProBoundsArrayToPointerDecayCheck.cpp
@@ -58,10 +58,11 @@
   // 2) inside a range-for over an array
   // 3) if it converts a string literal to a pointer
   Finder->addMatcher(
-  implicitCastExpr(unless(hasParent(arraySubscriptExpr())),
-   unless(hasParentIgnoringImpCasts(explicitCastExpr())),
-   unless(isInsideOfRangeBeginEndStmt()),
-   unless(hasSourceExpression(stringLiteral(
+  implicitCastExpr(
+  unless(hasParent(arraySubscriptExpr())),
+  unless(hasParentIgnoringImpCasts(explicitCastExpr())),
+  unless(isInsideOfRangeBeginEndStmt()),
+  unless(hasSourceExpression(ignoringParens(stringLiteral()
   .bind("cast"),
   this);
 }


Index: test/clang-tidy/cppcoreguidelines-pro-bounds-array-to-pointer-decay.cpp
===
--- test/clang-tidy/cppcoreguidelines-pro-bounds-array-to-pointer-decay.cpp
+++ test/clang-tidy/cppcoreguidelines-pro-bounds-array-to-pointer-decay.cpp
@@ -30,6 +30,7 @@
   arrayviewfun(av); // OK
 
   int i = a[0];  // OK
+  int j = a[(1 + 2)];// OK
   pointerfun(&a[0]); // OK
 
   for (auto &e : a) // OK, iteration internally decays array to pointer
@@ -39,6 +40,9 @@
 const char *g() {
   return "clang"; // OK, decay string literal to pointer
 }
+const char *g2() {
+return ("clang"); // OK, ParenCast hides the literal-pointer decay
+}
 
 void f2(void *const *);
 void bug25362() {
Index: clang-tidy/cppcoreguidelines/ProBoundsArrayToPointerDecayCheck.cpp
===
--- clang-tidy/cppcoreguidelines/ProBoundsArrayToPointerDecayCheck.cpp
+++ clang-tidy/cppcoreguidelines/ProBoundsArrayToPointerDecayCheck.cpp
@@ -58,10 +58,11 @@
   // 2) inside a range-for over an array
   // 3) if it converts a string literal to a pointer
   Finder->addMatcher(
-  implicitCastExpr(unless(hasParent(arraySubscriptExpr())),
-   unless(hasParentIgnoringImpCasts(explicitCastExpr())),
-   unless(isInsideOfRangeBeginEndStmt()),
-   unless(hasSourceExpression(stringLiteral(
+  implicitCastExpr(
+  unless(hasParent(arraySubscriptExpr())),
+  unless(hasParentIgnoringImpCasts(explicitCastExpr())),
+  unless(isInsideOfRangeBeginEndStmt()),
+  unless(hasSourceExpression(ignoringParens(stringLiteral()
   .bind("cast"),
   this);
 }
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D54307: [clang] overload ignoringParens for Expr

2018-11-09 Thread Jonas Toth via Phabricator via cfe-commits
JonasToth created this revision.
JonasToth added a reviewer: aaron.ballman.
Herald added a subscriber: cfe-commits.

This patch allows fixing PR39583.


Repository:
  rC Clang

https://reviews.llvm.org/D54307

Files:
  docs/LibASTMatchersReference.html
  include/clang/ASTMatchers/ASTMatchers.h
  lib/ASTMatchers/Dynamic/Registry.cpp


Index: lib/ASTMatchers/Dynamic/Registry.cpp
===
--- lib/ASTMatchers/Dynamic/Registry.cpp
+++ lib/ASTMatchers/Dynamic/Registry.cpp
@@ -106,6 +106,7 @@
   REGISTER_OVERLOADED_2(callee);
   REGISTER_OVERLOADED_2(hasPrefix);
   REGISTER_OVERLOADED_2(hasType);
+  REGISTER_OVERLOADED_2(ignoringParens);
   REGISTER_OVERLOADED_2(isDerivedFrom);
   REGISTER_OVERLOADED_2(isSameOrDerivedFrom);
   REGISTER_OVERLOADED_2(loc);
@@ -318,7 +319,6 @@
   REGISTER_MATCHER(ignoringImplicit);
   REGISTER_MATCHER(ignoringParenCasts);
   REGISTER_MATCHER(ignoringParenImpCasts);
-  REGISTER_MATCHER(ignoringParens);
   REGISTER_MATCHER(imaginaryLiteral);
   REGISTER_MATCHER(implicitCastExpr);
   REGISTER_MATCHER(implicitValueInitExpr);
Index: include/clang/ASTMatchers/ASTMatchers.h
===
--- include/clang/ASTMatchers/ASTMatchers.h
+++ include/clang/ASTMatchers/ASTMatchers.h
@@ -811,11 +811,28 @@
 ///   varDecl(hasType(pointerType(pointee(ignoringParens(functionType())
 /// \endcode
 /// would match the declaration for fp.
-AST_MATCHER_P(QualType, ignoringParens,
-  internal::Matcher, InnerMatcher) {
+AST_MATCHER_P_OVERLOAD(QualType, ignoringParens, internal::Matcher,
+   InnerMatcher, 0) {
   return InnerMatcher.matches(Node.IgnoreParens(), Finder, Builder);
 }
 
+/// Overload \c ignoringParens for \c Expr.
+///
+/// Given
+/// \code
+///   const char* str = ("my-string");
+/// \endcode
+/// The matcher
+/// \code
+///   implicitCastExpr(hasSourceExpression(ignoringParens(stringLiteral(
+/// \endcode
+/// would match the implicit cast resulting from the assignment.
+AST_MATCHER_P_OVERLOAD(Expr, ignoringParens, internal::Matcher,
+   InnerMatcher, 1) {
+  const Expr *E = Node.IgnoreParens();
+  return InnerMatcher.matches(*E, Finder, Builder);
+}
+
 /// Matches expressions that are instantiation-dependent even if it is
 /// neither type- nor value-dependent.
 ///
Index: docs/LibASTMatchersReference.html
===
--- docs/LibASTMatchersReference.html
+++ docs/LibASTMatchersReference.html
@@ -5552,6 +5552,17 @@
 
 
 
+MatcherExpr>ignoringParensMatcherExpr> 
InnerMatcher
+Overload 
ignoringParens for Expr.
+
+Given
+  const char* str = ("my-string");
+The matcher
+  implicitCastExpr(hasSourceExpression(ignoringParens(stringLiteral(
+would match the implicit cast resulting from the assignment.
+
+
+
 MatcherFieldDecl>hasInClassInitializerMatcherExpr> 
InnerMatcher
 Matches 
non-static data members that have an in-class initializer.
 


Index: lib/ASTMatchers/Dynamic/Registry.cpp
===
--- lib/ASTMatchers/Dynamic/Registry.cpp
+++ lib/ASTMatchers/Dynamic/Registry.cpp
@@ -106,6 +106,7 @@
   REGISTER_OVERLOADED_2(callee);
   REGISTER_OVERLOADED_2(hasPrefix);
   REGISTER_OVERLOADED_2(hasType);
+  REGISTER_OVERLOADED_2(ignoringParens);
   REGISTER_OVERLOADED_2(isDerivedFrom);
   REGISTER_OVERLOADED_2(isSameOrDerivedFrom);
   REGISTER_OVERLOADED_2(loc);
@@ -318,7 +319,6 @@
   REGISTER_MATCHER(ignoringImplicit);
   REGISTER_MATCHER(ignoringParenCasts);
   REGISTER_MATCHER(ignoringParenImpCasts);
-  REGISTER_MATCHER(ignoringParens);
   REGISTER_MATCHER(imaginaryLiteral);
   REGISTER_MATCHER(implicitCastExpr);
   REGISTER_MATCHER(implicitValueInitExpr);
Index: include/clang/ASTMatchers/ASTMatchers.h
===
--- include/clang/ASTMatchers/ASTMatchers.h
+++ include/clang/ASTMatchers/ASTMatchers.h
@@ -811,11 +811,28 @@
 ///   varDecl(hasType(pointerType(pointee(ignoringParens(functionType())
 /// \endcode
 /// would match the declaration for fp.
-AST_MATCHER_P(QualType, ignoringParens,
-  internal::Matcher, InnerMatcher) {
+AST_MATCHER_P_OVERLOAD(QualType, ignoringParens, internal::Matcher,
+   InnerMatcher, 0) {
   return InnerMatcher.matches(Node.IgnoreParens(), Finder, Builder);
 }
 
+/// Overload \c ignoringParens for \c Expr.
+///
+/// Given
+/// \code
+///   const char* str = ("my-string");
+/// \endcode
+/// The matcher
+/// \code
+///   implicitCastExpr(hasSourceExpression(ignoringParens(stringLiteral(
+/// \endcode
+/// would match the implicit cast resulting from the assignme

[PATCH] D54258: [Clang] Fix pretty printing of CUDA address spaces

2018-11-09 Thread Richard Membarth via Phabricator via cfe-commits
richardmembarth added a comment.

Same problem here: The CUDA memory space specifiers are represented via 
attributes, e.g. `CUDASharedAttr` and only converted in CodeGen to 
`LangAS::cuda_shared`.
We would need a different frontend that annotates `LangAS::cuda_shared`.


Repository:
  rC Clang

https://reviews.llvm.org/D54258



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


[PATCH] D54309: [AST] Allow limiting the scope of common AST traversals (getParents, RAV).

2018-11-09 Thread Sam McCall via Phabricator via cfe-commits
sammccall created this revision.
sammccall added reviewers: klimek, ioeric.
Herald added subscribers: cfe-commits, mgorny.

The goal is to allow analyses such as clang-tidy checks to run on a
subset of the AST, e.g. "only on main-file decls" for interactive tools.

Today, these become "problematically global" by running RecursiveASTVisitors
rooted at the TUDecl, or by navigating up via ASTContext::getParent().

The scope is restricted using a set of top-level-decls that RecursiveASTVisitors
should be rooted at. This also applies to the visitor that populates the
parent map, and so the top-level-decls are considered to have no parents.

This patch makes the traversal scope a mutable property of ASTContext.
The more obvious way to do this is to pass the top-level decls to
relevant functions directly, but this has some problems:

- it's error-prone: accidentally mixing restricted and unrestricted scopes is a 
performance trap. Interleaving multiple analyses is common (many clang-tidy 
checks run matchers or RAVs from matcher callbacks)
- it doesn't map well to the actual use cases, where we really do want *all* 
traversals to be restricted.
- it involves a lot of plumbing in parts of the code that don't care about 
traversals.

This approach was tried out in https://reviews.llvm.org/D54259 and 
https://reviews.llvm.org/D54261, I wanted to like it
but it feels pretty awful in practice.

Caveats: to get scope-limiting behavior of RecursiveASTVisitors, callers
have to call the new TraverseAST(Ctx) function instead of TraverseDecl(TU).
I think this is an improvement to the API regardless.


Repository:
  rC Clang

https://reviews.llvm.org/D54309

Files:
  include/clang/AST/ASTContext.h
  include/clang/AST/RecursiveASTVisitor.h
  lib/AST/ASTContext.cpp
  lib/ASTMatchers/ASTMatchFinder.cpp
  unittests/AST/ASTContextParentMapTest.cpp
  unittests/Tooling/CMakeLists.txt
  unittests/Tooling/RecursiveASTVisitorTests/TraversalScope.cpp

Index: unittests/Tooling/RecursiveASTVisitorTests/TraversalScope.cpp
===
--- /dev/null
+++ unittests/Tooling/RecursiveASTVisitorTests/TraversalScope.cpp
@@ -0,0 +1,51 @@
+//===- unittest/Tooling/RecursiveASTVisitorTests/TraversalScope.cpp ---===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===--===//
+
+#include "TestVisitor.h"
+
+using namespace clang;
+
+namespace {
+
+class Visitor : public ExpectedLocationVisitor {
+public:
+  Visitor(ASTContext *Context) { this->Context = Context; }
+
+  bool VisitNamedDecl(NamedDecl *D) {
+if (!D->isImplicit())
+  Match(D->getName(), D->getLocation());
+return true;
+  }
+};
+
+TEST(RecursiveASTVisitor, RespectsTraversalScope) {
+  auto AST = tooling::buildASTFromCode(
+  R"cpp(
+struct foo {
+  struct bar {
+struct baz {};
+  };
+};
+  )cpp",
+  "foo.cpp", std::make_shared());
+  auto &Ctx = AST->getASTContext();
+  auto &TU = *Ctx.getTranslationUnitDecl();
+  auto &Foo = *TU.lookup(&Ctx.Idents.get("foo")).front();
+  auto &Bar = *cast(Foo).lookup(&Ctx.Idents.get("bar")).front();
+
+  Ctx.setTraversalScope({&Bar});
+
+  Visitor V(&Ctx);
+  V.DisallowMatch("foo", 2, 8);
+  V.ExpectMatch("bar", 3, 10);
+  V.ExpectMatch("baz", 4, 12);
+  V.TraverseAST(Ctx);
+}
+
+} // end anonymous namespace
Index: unittests/Tooling/CMakeLists.txt
===
--- unittests/Tooling/CMakeLists.txt
+++ unittests/Tooling/CMakeLists.txt
@@ -40,6 +40,7 @@
   RecursiveASTVisitorTests/NestedNameSpecifiers.cpp
   RecursiveASTVisitorTests/ParenExpr.cpp
   RecursiveASTVisitorTests/TemplateArgumentLocTraverser.cpp
+  RecursiveASTVisitorTests/TraversalScope.cpp
   RecursiveASTVisitorTestDeclVisitor.cpp
   RecursiveASTVisitorTestPostOrderVisitor.cpp
   RecursiveASTVisitorTestTypeLocVisitor.cpp
Index: unittests/AST/ASTContextParentMapTest.cpp
===
--- unittests/AST/ASTContextParentMapTest.cpp
+++ unittests/AST/ASTContextParentMapTest.cpp
@@ -17,6 +17,9 @@
 #include "clang/ASTMatchers/ASTMatchers.h"
 #include "clang/Tooling/Tooling.h"
 #include "gtest/gtest.h"
+#include "gmock/gmock.h"
+
+using testing::ElementsAre;
 
 namespace clang {
 namespace ast_matchers {
@@ -78,5 +81,30 @@
   hasAncestor(cxxRecordDecl(unless(isTemplateInstantiation(;
 }
 
+TEST(GetParents, RespectsTraversalScope) {
+  auto AST =
+  tooling::buildASTFromCode("struct foo { int bar; };", "foo.cpp",
+std::make_shared());
+  auto &Ctx = AST->getASTContext();
+  auto &TU = *Ctx.getTranslationUnitDecl();
+  auto &Foo = *TU.lookup(&Ctx.Idents.get("foo")).front();
+  auto &Bar = *cast(Foo).lookup(&Ctx.Idents.get("bar")).front();
+
+  using ast_typ

[PATCH] D54310: Make clang-based tools find libc++ on MacOS

2018-11-09 Thread Ilya Biryukov via Phabricator via cfe-commits
ilya-biryukov created this revision.
ilya-biryukov added reviewers: sammccall, arphaman.
Herald added a reviewer: EricWF.
Herald added subscribers: kadircet, christof, ioeric.

When they read compiler args from compile_commands.json.
This change allows to run clang-based tools, like clang-tidy or clangd,
built from head using the compile_commands.json file produced for XCode
toolchains.

On MacOS clang can find the C++ standard library relative to the
compiler installation dir.

The logic to do this was based on resource dir as an approximation of
where the compiler is installed. This broke the tools that read
'compile_commands.json' and don't ship with the compiler, as they
typically change resource dir.

To workaround this, we now use compiler install dir detected by the driver
to better mimic the behavior of the original compiler when replaying the
compilations using other tools.


Repository:
  rC Clang

https://reviews.llvm.org/D54310

Files:
  include/clang/Lex/HeaderSearchOptions.h
  lib/Frontend/CompilerInvocation.cpp
  lib/Frontend/CreateInvocationFromCommandLine.cpp
  lib/Frontend/InitHeaderSearch.cpp
  lib/Tooling/Tooling.cpp
  test/Tooling/Inputs/mock-libcxx/include/c++/v1/mock_vector
  test/Tooling/clang-check-mac-libcxx.cpp

Index: test/Tooling/clang-check-mac-libcxx.cpp
===
--- /dev/null
+++ test/Tooling/clang-check-mac-libcxx.cpp
@@ -0,0 +1,16 @@
+// Clang on MacOS can find libc++ living beside the installed compiler.
+// This test makes sure our libTooling-based tools emulate this properly.
+//
+// RUN: rm -rf %t
+// RUN: mkdir %t
+//
+// Install the mock libc++ (simulates the libc++ directory structure).
+// RUN: cp -r %S/Inputs/mock-libcxx %t/
+//
+// Pretend clang is installed beside the mock library that we provided.
+// RUN: echo '[{"directory":"%t","command":"%t/mock-libcxx/bin/clang++ -stdlib=libc++ -target x86_64-apple-darwin -c test.cpp","file":"test.cpp"}]' | sed -e 's/\\/\//g' > %t/compile_commands.json
+// RUN: cp "%s" "%t/test.cpp"
+// RUN: clang-check -p "%t" "%t/test.cpp"
+
+#include 
+vector v;
Index: test/Tooling/Inputs/mock-libcxx/include/c++/v1/mock_vector
===
--- /dev/null
+++ test/Tooling/Inputs/mock-libcxx/include/c++/v1/mock_vector
@@ -0,0 +1 @@
+class vector {};
Index: lib/Tooling/Tooling.cpp
===
--- lib/Tooling/Tooling.cpp
+++ lib/Tooling/Tooling.cpp
@@ -323,6 +323,9 @@
 Invocation->getPreprocessorOpts().addRemappedFile(It.getKey(),
   Input.release());
   }
+  // Patch up the install dir, so we find the same standard library as the
+  // original compiler on MacOS.
+  Invocation->getHeaderSearchOpts().InstallDir = Driver->getInstalledDir();
   return runInvocation(BinaryName, Compilation.get(), std::move(Invocation),
std::move(PCHContainerOps));
 }
Index: lib/Frontend/InitHeaderSearch.cpp
===
--- lib/Frontend/InitHeaderSearch.cpp
+++ lib/Frontend/InitHeaderSearch.cpp
@@ -476,14 +476,9 @@
   if (triple.isOSDarwin()) {
 // On Darwin, libc++ may be installed alongside the compiler in
 // include/c++/v1.
-if (!HSOpts.ResourceDir.empty()) {
-  // Remove version from foo/lib/clang/version
-  StringRef NoVer = llvm::sys::path::parent_path(HSOpts.ResourceDir);
-  // Remove clang from foo/lib/clang
-  StringRef Lib = llvm::sys::path::parent_path(NoVer);
-  // Remove lib from foo/lib
-  SmallString<128> P = llvm::sys::path::parent_path(Lib);
-
+if (!HSOpts.InstallDir.empty()) {
+  // Get from foo/bin to foo.
+  SmallString<128> P(llvm::sys::path::parent_path(HSOpts.InstallDir));
   // Get foo/include/c++/v1
   llvm::sys::path::append(P, "include", "c++", "v1");
   AddUnmappedPath(P, CXXSystem, false);
Index: lib/Frontend/CreateInvocationFromCommandLine.cpp
===
--- lib/Frontend/CreateInvocationFromCommandLine.cpp
+++ lib/Frontend/CreateInvocationFromCommandLine.cpp
@@ -11,17 +11,18 @@
 //
 //===--===//
 
-#include "clang/Frontend/Utils.h"
 #include "clang/Basic/DiagnosticOptions.h"
+#include "clang/Driver/Action.h"
 #include "clang/Driver/Compilation.h"
 #include "clang/Driver/Driver.h"
-#include "clang/Driver/Action.h"
 #include "clang/Driver/Options.h"
 #include "clang/Driver/Tool.h"
 #include "clang/Frontend/CompilerInstance.h"
 #include "clang/Frontend/FrontendDiagnostic.h"
+#include "clang/Frontend/Utils.h"
 #include "llvm/Option/ArgList.h"
 #include "llvm/Support/Host.h"
+#include "llvm/Support/Path.h"
 using namespace clang;
 using namespace llvm::opt;
 
@@ -102,5 +103,8 @@
 

[PATCH] D54311: Add a test checking clang-tidy can find libc++ on Mac

2018-11-09 Thread Ilya Biryukov via Phabricator via cfe-commits
ilya-biryukov created this revision.
ilya-biryukov added reviewers: sammccall, arphaman.
Herald added a reviewer: EricWF.
Herald added a subscriber: christof.

Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D54311

Files:
  test/clang-tidy/Inputs/mock-libcxx/include/c++/v1/mock_vector
  test/clang-tidy/clang-tidy-mac-libcxx.cpp


Index: test/clang-tidy/clang-tidy-mac-libcxx.cpp
===
--- /dev/null
+++ test/clang-tidy/clang-tidy-mac-libcxx.cpp
@@ -0,0 +1,16 @@
+// Clang on MacOS can find libc++ living beside the installed compiler.
+// This test makes sure clang-tidy emulates this properly.
+//
+// RUN: rm -rf %t
+// RUN: mkdir %t
+//
+// Install the mock libc++ (simulates the libc++ directory structure).
+// RUN: cp -r %S/Inputs/mock-libcxx %t/
+//
+// Pretend clang is installed beside the mock library that we provided.
+// RUN: echo '[{"directory":"%t","command":"%t/mock-libcxx/bin/clang++ 
-stdlib=libc++ -target x86_64-apple-darwin -c test.cpp","file":"test.cpp"}]' | 
sed -e 's/\\/\//g' > %t/compile_commands.json
+// RUN: cp "%s" "%t/test.cpp"
+// RUN: clang-tidy "%t/test.cpp"
+
+#include 
+vector v;
Index: test/clang-tidy/Inputs/mock-libcxx/include/c++/v1/mock_vector
===
--- /dev/null
+++ test/clang-tidy/Inputs/mock-libcxx/include/c++/v1/mock_vector
@@ -0,0 +1 @@
+class vector {};


Index: test/clang-tidy/clang-tidy-mac-libcxx.cpp
===
--- /dev/null
+++ test/clang-tidy/clang-tidy-mac-libcxx.cpp
@@ -0,0 +1,16 @@
+// Clang on MacOS can find libc++ living beside the installed compiler.
+// This test makes sure clang-tidy emulates this properly.
+//
+// RUN: rm -rf %t
+// RUN: mkdir %t
+//
+// Install the mock libc++ (simulates the libc++ directory structure).
+// RUN: cp -r %S/Inputs/mock-libcxx %t/
+//
+// Pretend clang is installed beside the mock library that we provided.
+// RUN: echo '[{"directory":"%t","command":"%t/mock-libcxx/bin/clang++ -stdlib=libc++ -target x86_64-apple-darwin -c test.cpp","file":"test.cpp"}]' | sed -e 's/\\/\//g' > %t/compile_commands.json
+// RUN: cp "%s" "%t/test.cpp"
+// RUN: clang-tidy "%t/test.cpp"
+
+#include 
+vector v;
Index: test/clang-tidy/Inputs/mock-libcxx/include/c++/v1/mock_vector
===
--- /dev/null
+++ test/clang-tidy/Inputs/mock-libcxx/include/c++/v1/mock_vector
@@ -0,0 +1 @@
+class vector {};
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


Re: r345971 - Reapply Logging: make os_log buffer size an integer constant expression.

2018-11-09 Thread Sam McCall via cfe-commits
Sorry I lost track of this.
Having understood the code a bit more, the current split between the
AST/analysis/static analyzer isn't as clear as I thought.
So I'm not sure the layering is perfect here, but the fault doesn't lie
with your patch. Sorry for the noise.

On Fri, Nov 2, 2018 at 5:43 PM Tim Northover  wrote:

> On 2 Nov 2018, at 15:28, Sam McCall  wrote:
> > In that case, I don't think it makes sense to think of the format string
> parser as part of the analyzer - as the build deps suggest, it's now part
> of AST and gets reused by analyzer. (Similar to how the analyzer uses other
> bits of AST/clang). If there are parts only relevant to analyzer, it'd be
> nice to move them out of the AST library, but I don't know to what extent
> that's feasible.
>
> The Scanf one could have been left there, but that seems even worse from a
> consistency point of view.
>
> > So it does seem to me like all the uses of analyzer namespaces are
> suspect - moving code from Analyzer to AST is a semantic difference (the
> layers aren't *just* about making the linker happy, after all!)
>
> But what it’s doing is still analysis. It seems like we’d just be making
> up another term for the sake of it if we changed it.
>
> Cheers.
>
> Tim
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D54300: [clangd] Respect shouldIndexFile when collecting symbols.

2018-11-09 Thread Haojian Wu via Phabricator via cfe-commits
hokein updated this revision to Diff 173324.
hokein marked 2 inline comments as done.
hokein added a comment.

Address comments and simplify the code.


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D54300

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

Index: unittests/clangd/SymbolCollectorTests.cpp
===
--- unittests/clangd/SymbolCollectorTests.cpp
+++ unittests/clangd/SymbolCollectorTests.cpp
@@ -523,6 +523,64 @@
AllOf(QName("Z"), RefCount(0)), QName("y")));
 }
 
+TEST_F(SymbolCollectorTest, ShouldIndexFile) {
+  const std::string IgnoredHeader = R"(
+class Foo {};
+void f();
+
+void k();
+inline void k() {}
+#define GLOBAL_Z(name) Z name;
+  )";
+
+  Annotations IndexedHeader(R"(
+class $bar[[Bar]] {};
+void $b[[b]]();
+  )");
+  Annotations Main(R"(
+#include "ignored_header.h"
+#include "indexed_header.h"
+
+void $f[[f]]() {}
+void $b[[b]]() { $f[[f]](); }
+  )");
+  const std::string IgnoredHeaderPath = testPath("ignored_header.h");
+  const std::string IndexedHeaderPath = testPath("indexed_header.h");
+  const std::string IgnoredHeaderURI =
+  URI::createFile(IgnoredHeaderPath).toString();
+  const std::string IndexedHeaderURI =
+  URI::createFile(IndexedHeaderPath).toString();
+
+  InMemoryFileSystem->addFile(IgnoredHeaderPath, 0,
+  MemoryBuffer::getMemBuffer(IgnoredHeader));
+  InMemoryFileSystem->addFile(IndexedHeaderPath, 0,
+  MemoryBuffer::getMemBuffer(IndexedHeader.code()));
+  CollectorOpts.FileFilter = [](const SourceManager &SM, FileID FID) {
+if (const auto *F = SM.getFileEntryForID(FID))
+  return !F->getName().contains("ignored_header.h");
+return true;
+  };
+  CollectorOpts.RefFilter = RefKind::All;
+  CollectorOpts.RefsInHeaders = true;
+  runSymbolCollector("", Main.code());
+  EXPECT_THAT(
+  Symbols,
+  UnorderedElementsAre(
+  // We still see complete symbol f.
+  AllOf(QName("f"), DefURI(TestFileURI), DeclURI(IgnoredHeaderURI)),
+  AllOf(QName("Bar"), DeclRange(IndexedHeader.range("bar")),
+DeclURI(IndexedHeaderURI)),
+  AllOf(QName("b"), DeclRange(IndexedHeader.range("b")),
+DefRange(Main.range("b")), DeclURI(IndexedHeaderURI),
+DefURI(TestFileURI;
+  EXPECT_THAT(
+  Refs, UnorderedElementsAre(
+Pair(findSymbol(Symbols, "f").ID, HaveRanges(Main.ranges("f"))),
+Pair(findSymbol(Symbols, "b").ID, _),
+Pair(findSymbol(Symbols, "Bar").ID,
+ HaveRanges(IndexedHeader.ranges("bar");
+}
+
 TEST_F(SymbolCollectorTest, SymbolRelativeNoFallback) {
   runSymbolCollector("class Foo {};", /*Main=*/"");
   EXPECT_THAT(Symbols, UnorderedElementsAre(
Index: clangd/index/SymbolCollector.h
===
--- clangd/index/SymbolCollector.h
+++ clangd/index/SymbolCollector.h
@@ -78,6 +78,9 @@
 bool CollectMacro = false;
 /// If this is set, only collect symbols/references from a file if
 /// `FileFilter(SM, FID)` is true. If not set, all files are indexed.
+/// Note that a symbol can be redeclared in multiple files, a complete
+/// symbol will be constructed if this symbol is declared in one of indexed
+/// files.
 std::function FileFilter = nullptr;
   };
 
Index: clangd/index/SymbolCollector.cpp
===
--- clangd/index/SymbolCollector.cpp
+++ clangd/index/SymbolCollector.cpp
@@ -214,6 +214,13 @@
   return I.first->second;
 }
 
+bool shouldIndexFile(const Decl& D, const SymbolCollector::Options &Opts,
+ llvm::DenseMap *FilesToIndexCache) {
+  auto &SM = D.getASTContext().getSourceManager();
+  auto Loc = findNameLoc(&D);
+  return shouldIndexFile(SM, SM.getFileID(Loc), Opts, FilesToIndexCache);
+}
+
 // Return the symbol location of the token at \p TokLoc.
 Optional getTokenLocation(SourceLocation TokLoc,
   const SourceManager &SM,
@@ -353,9 +360,10 @@
   // D may not be an interesting symbol, but it's cheaper to check at the end.
   auto &SM = ASTCtx->getSourceManager();
   auto SpellingLoc = SM.getSpellingLoc(Loc);
+  auto FID = SM.getFileID(SpellingLoc);
   if (Opts.CountReferences &&
   (Roles & static_cast(index::SymbolRole::Reference)) &&
-  SM.getFileID(SpellingLoc) == SM.getMainFileID())
+  FID == SM.getMainFileID())
 ReferencedDecls.insert(ND);
 
   bool CollectRef = static_cast(Opts.RefFilter) & Roles;
@@ -368,8 +376,10 @@
   if (!shouldCollectSymbol(*ND, *ASTCtx, Opts))
 return true;
   if (CollectRef && !isa(ND) &&
-  (Opts.RefsInHeaders || SM.getFileID(SpellingLoc) == SM.getMainFileID()))
+  

[PATCH] D54300: [clangd] Respect shouldIndexFile when collecting symbols.

2018-11-09 Thread Haojian Wu via Phabricator via cfe-commits
hokein added inline comments.



Comment at: clangd/index/SymbolCollector.cpp:555
+  auto Loc = findNameLoc(&ND);
+  if (!shouldIndexFile(SM, SM.getFileID(Loc), Opts, &FilesToIndexCache))
+return nullptr;

ioeric wrote:
> Should we use `getTokenLocation` like what we do below?
`getTokenLocation` doesn't return a `SourceLocation`, it returns a 
`SymbolLocation`.


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D54300



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


[PATCH] D54300: [clangd] Respect shouldIndexFile when collecting symbols.

2018-11-09 Thread Haojian Wu via Phabricator via cfe-commits
hokein updated this revision to Diff 173326.
hokein added a comment.

clang-format and fix typos


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D54300

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

Index: unittests/clangd/SymbolCollectorTests.cpp
===
--- unittests/clangd/SymbolCollectorTests.cpp
+++ unittests/clangd/SymbolCollectorTests.cpp
@@ -523,6 +523,64 @@
AllOf(QName("Z"), RefCount(0)), QName("y")));
 }
 
+TEST_F(SymbolCollectorTest, ShouldIndexFile) {
+  const std::string IgnoredHeader = R"(
+class Foo {};
+void f();
+
+void k();
+inline void k() {}
+#define GLOBAL_Z(name) Z name;
+  )";
+
+  Annotations IndexedHeader(R"(
+class $bar[[Bar]] {};
+void $b[[b]]();
+  )");
+  Annotations Main(R"(
+#include "ignored_header.h"
+#include "indexed_header.h"
+
+void $f[[f]]() {}
+void $b[[b]]() { $f[[f]](); }
+  )");
+  const std::string IgnoredHeaderPath = testPath("ignored_header.h");
+  const std::string IndexedHeaderPath = testPath("indexed_header.h");
+  const std::string IgnoredHeaderURI =
+  URI::createFile(IgnoredHeaderPath).toString();
+  const std::string IndexedHeaderURI =
+  URI::createFile(IndexedHeaderPath).toString();
+
+  InMemoryFileSystem->addFile(IgnoredHeaderPath, 0,
+  MemoryBuffer::getMemBuffer(IgnoredHeader));
+  InMemoryFileSystem->addFile(IndexedHeaderPath, 0,
+  MemoryBuffer::getMemBuffer(IndexedHeader.code()));
+  CollectorOpts.FileFilter = [](const SourceManager &SM, FileID FID) {
+if (const auto *F = SM.getFileEntryForID(FID))
+  return !F->getName().contains("ignored_header.h");
+return true;
+  };
+  CollectorOpts.RefFilter = RefKind::All;
+  CollectorOpts.RefsInHeaders = true;
+  runSymbolCollector("", Main.code());
+  EXPECT_THAT(
+  Symbols,
+  UnorderedElementsAre(
+  // We still see complete symbol f.
+  AllOf(QName("f"), DefURI(TestFileURI), DeclURI(IgnoredHeaderURI)),
+  AllOf(QName("Bar"), DeclRange(IndexedHeader.range("bar")),
+DeclURI(IndexedHeaderURI)),
+  AllOf(QName("b"), DeclRange(IndexedHeader.range("b")),
+DefRange(Main.range("b")), DeclURI(IndexedHeaderURI),
+DefURI(TestFileURI;
+  EXPECT_THAT(
+  Refs, UnorderedElementsAre(
+Pair(findSymbol(Symbols, "f").ID, HaveRanges(Main.ranges("f"))),
+Pair(findSymbol(Symbols, "b").ID, _),
+Pair(findSymbol(Symbols, "Bar").ID,
+ HaveRanges(IndexedHeader.ranges("bar");
+}
+
 TEST_F(SymbolCollectorTest, SymbolRelativeNoFallback) {
   runSymbolCollector("class Foo {};", /*Main=*/"");
   EXPECT_THAT(Symbols, UnorderedElementsAre(
Index: clangd/index/SymbolCollector.h
===
--- clangd/index/SymbolCollector.h
+++ clangd/index/SymbolCollector.h
@@ -78,6 +78,9 @@
 bool CollectMacro = false;
 /// If this is set, only collect symbols/references from a file if
 /// `FileFilter(SM, FID)` is true. If not set, all files are indexed.
+/// Note that a symbol can be redeclared in multiple files, a complete
+/// symbol will be constructed if this symbol is declared in one of indexed
+/// files.
 std::function FileFilter = nullptr;
   };
 
Index: clangd/index/SymbolCollector.cpp
===
--- clangd/index/SymbolCollector.cpp
+++ clangd/index/SymbolCollector.cpp
@@ -214,6 +214,13 @@
   return I.first->second;
 }
 
+bool shouldIndexFile(const Decl &D, const SymbolCollector::Options &Opts,
+ llvm::DenseMap *FilesToIndexCache) {
+  auto &SM = D.getASTContext().getSourceManager();
+  auto Loc = findNameLoc(&D);
+  return shouldIndexFile(SM, SM.getFileID(Loc), Opts, FilesToIndexCache);
+}
+
 // Return the symbol location of the token at \p TokLoc.
 Optional getTokenLocation(SourceLocation TokLoc,
   const SourceManager &SM,
@@ -353,9 +360,10 @@
   // D may not be an interesting symbol, but it's cheaper to check at the end.
   auto &SM = ASTCtx->getSourceManager();
   auto SpellingLoc = SM.getSpellingLoc(Loc);
+  auto FID = SM.getFileID(SpellingLoc);
   if (Opts.CountReferences &&
   (Roles & static_cast(index::SymbolRole::Reference)) &&
-  SM.getFileID(SpellingLoc) == SM.getMainFileID())
+  FID == SM.getMainFileID())
 ReferencedDecls.insert(ND);
 
   bool CollectRef = static_cast(Opts.RefFilter) & Roles;
@@ -368,8 +376,10 @@
   if (!shouldCollectSymbol(*ND, *ASTCtx, Opts))
 return true;
   if (CollectRef && !isa(ND) &&
-  (Opts.RefsInHeaders || SM.getFileID(SpellingLoc) == SM.getMainFileID()))
+  (Opts.RefsInHeaders || FID == SM.getMainFileID()) 

[PATCH] D54300: [clangd] Respect shouldIndexFile when collecting symbols.

2018-11-09 Thread Eric Liu via Phabricator via cfe-commits
ioeric added inline comments.



Comment at: clangd/index/SymbolCollector.cpp:217
 
+bool shouldIndexFile(const Decl& D, const SymbolCollector::Options &Opts,
+ llvm::DenseMap *FilesToIndexCache) {

nit: this is very easily confused with the callback with the same name on the 
call sites.



Comment at: clangd/index/SymbolCollector.cpp:220
+  auto &SM = D.getASTContext().getSourceManager();
+  auto Loc = findNameLoc(&D);
+  return shouldIndexFile(SM, SM.getFileID(Loc), Opts, FilesToIndexCache);

This is following the implementation detail of how location is generated in 
`addDeclaration`/`addDefinition`. I think we could put the filtering into 
`addDeclaration`/`addDeclaration` to avoid the duplicate here (i.e. return 
nullptr if decl is filtered like what you did in the previous revision?).



Comment at: clangd/index/SymbolCollector.cpp:410
+if (!BasicSymbol)
+  BasicSymbol = addDeclaration(
+  *cast(OriginalDecl.getCanonicalDecl()), *ID);

`OriginalDecl.getCanonicalDecl()` might not be the one we prefer. I think we 
should check all `redecls` and pick the preferred one? 



Comment at: unittests/clangd/SymbolCollectorTests.cpp:526
 
+TEST_F(SymbolCollectorTest, ShouldIndexFile) {
+  const std::string IgnoredHeader = R"(

It's not trivial to tell what are the cases we are testing here. Maybe add some 
comments?

There are a few cases that are interesting. For examples:
- Symbol is declared in a filtered header and defined in a index file.
- Symbol is declared in a indexed file and defined in a filter file.
- Symbol has forward declaration and canonical declaration in filtered header 
and definition in indexed file.
- ...

It might be clearer to split them into multiple cases.


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D54300



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


[clang-tools-extra] r346503 - [clangd] Don't treat top-level decls as "local" if they are from the preamble.

2018-11-09 Thread Sam McCall via cfe-commits
Author: sammccall
Date: Fri Nov  9 07:35:00 2018
New Revision: 346503

URL: http://llvm.org/viewvc/llvm-project?rev=346503&view=rev
Log:
[clangd] Don't treat top-level decls as "local" if they are from the preamble.

Summary:
These get passed to HandleTopLevelDecl() if they happen to have been
deserialized for any reason. We don't want to treat them as part of the
main file.

Reviewers: ilya-biryukov

Subscribers: ioeric, MaskRay, jkorous, arphaman, kadircet, cfe-commits

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

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

Modified: clang-tools-extra/trunk/clangd/ClangdUnit.cpp
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clangd/ClangdUnit.cpp?rev=346503&r1=346502&r2=346503&view=diff
==
--- clang-tools-extra/trunk/clangd/ClangdUnit.cpp (original)
+++ clang-tools-extra/trunk/clangd/ClangdUnit.cpp Fri Nov  9 07:35:00 2018
@@ -57,6 +57,9 @@ public:
 
   bool HandleTopLevelDecl(DeclGroupRef DG) override {
 for (Decl *D : DG) {
+  if (D->isFromASTFile())
+continue;
+
   // ObjCMethodDecl are not actually top-level decls.
   if (isa(D))
 continue;

Modified: clang-tools-extra/trunk/unittests/clangd/ClangdUnitTests.cpp
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/unittests/clangd/ClangdUnitTests.cpp?rev=346503&r1=346502&r2=346503&view=diff
==
--- clang-tools-extra/trunk/unittests/clangd/ClangdUnitTests.cpp (original)
+++ clang-tools-extra/trunk/unittests/clangd/ClangdUnitTests.cpp Fri Nov  9 
07:35:00 2018
@@ -257,6 +257,28 @@ Bar* bar;
   }
 }
 
+MATCHER_P(DeclNamed, Name, "") {
+  if (NamedDecl *ND = dyn_cast(arg))
+if (ND->getName() == Name)
+  return true;
+  if (auto *Stream = result_listener->stream()) {
+llvm::raw_os_ostream OS(*Stream);
+arg->dump(OS);
+  }
+  return false;
+}
+
+TEST(ClangdUnitTest, TopLevelDecls) {
+  TestTU TU;
+  TU.HeaderCode = R"(
+int header1();
+int header2;
+  )";
+  TU.Code = "int main();";
+  auto AST = TU.build();
+  EXPECT_THAT(AST.getLocalTopLevelDecls(), ElementsAre(DeclNamed("main")));
+}
+
 } // namespace
 } // namespace clangd
 } // namespace clang


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


[PATCH] D54303: [clangd] Don't treat top-level decls as "local" if they are from the preamble.

2018-11-09 Thread Sam McCall via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
sammccall marked an inline comment as done.
Closed by commit rCTE346503: [clangd] Don't treat top-level decls as 
"local" if they are from the preamble. (authored by sammccall, 
committed by ).

Changed prior to commit:
  https://reviews.llvm.org/D54303?vs=173303&id=173332#toc

Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D54303

Files:
  clangd/ClangdUnit.cpp
  unittests/clangd/ClangdUnitTests.cpp


Index: clangd/ClangdUnit.cpp
===
--- clangd/ClangdUnit.cpp
+++ clangd/ClangdUnit.cpp
@@ -57,6 +57,9 @@
 
   bool HandleTopLevelDecl(DeclGroupRef DG) override {
 for (Decl *D : DG) {
+  if (D->isFromASTFile())
+continue;
+
   // ObjCMethodDecl are not actually top-level decls.
   if (isa(D))
 continue;
Index: unittests/clangd/ClangdUnitTests.cpp
===
--- unittests/clangd/ClangdUnitTests.cpp
+++ unittests/clangd/ClangdUnitTests.cpp
@@ -257,6 +257,28 @@
   }
 }
 
+MATCHER_P(DeclNamed, Name, "") {
+  if (NamedDecl *ND = dyn_cast(arg))
+if (ND->getName() == Name)
+  return true;
+  if (auto *Stream = result_listener->stream()) {
+llvm::raw_os_ostream OS(*Stream);
+arg->dump(OS);
+  }
+  return false;
+}
+
+TEST(ClangdUnitTest, TopLevelDecls) {
+  TestTU TU;
+  TU.HeaderCode = R"(
+int header1();
+int header2;
+  )";
+  TU.Code = "int main();";
+  auto AST = TU.build();
+  EXPECT_THAT(AST.getLocalTopLevelDecls(), ElementsAre(DeclNamed("main")));
+}
+
 } // namespace
 } // namespace clangd
 } // namespace clang


Index: clangd/ClangdUnit.cpp
===
--- clangd/ClangdUnit.cpp
+++ clangd/ClangdUnit.cpp
@@ -57,6 +57,9 @@
 
   bool HandleTopLevelDecl(DeclGroupRef DG) override {
 for (Decl *D : DG) {
+  if (D->isFromASTFile())
+continue;
+
   // ObjCMethodDecl are not actually top-level decls.
   if (isa(D))
 continue;
Index: unittests/clangd/ClangdUnitTests.cpp
===
--- unittests/clangd/ClangdUnitTests.cpp
+++ unittests/clangd/ClangdUnitTests.cpp
@@ -257,6 +257,28 @@
   }
 }
 
+MATCHER_P(DeclNamed, Name, "") {
+  if (NamedDecl *ND = dyn_cast(arg))
+if (ND->getName() == Name)
+  return true;
+  if (auto *Stream = result_listener->stream()) {
+llvm::raw_os_ostream OS(*Stream);
+arg->dump(OS);
+  }
+  return false;
+}
+
+TEST(ClangdUnitTest, TopLevelDecls) {
+  TestTU TU;
+  TU.HeaderCode = R"(
+int header1();
+int header2;
+  )";
+  TU.Code = "int main();";
+  auto AST = TU.build();
+  EXPECT_THAT(AST.getLocalTopLevelDecls(), ElementsAre(DeclNamed("main")));
+}
+
 } // namespace
 } // namespace clangd
 } // namespace clang
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D53764: [OpenCL] Enable address spaces for references in C++

2018-11-09 Thread Anastasia Stulova via Phabricator via cfe-commits
Anastasia updated this revision to Diff 173334.
Anastasia added a comment.

Changed the assert for address space conversion.


https://reviews.llvm.org/D53764

Files:
  include/clang/Sema/Sema.h
  lib/AST/Expr.cpp
  lib/CodeGen/CGExpr.cpp
  lib/Sema/DeclSpec.cpp
  lib/Sema/SemaDecl.cpp
  lib/Sema/SemaExprCXX.cpp
  lib/Sema/SemaInit.cpp
  lib/Sema/SemaType.cpp
  test/CodeGenOpenCLCXX/address-space-deduction.cl

Index: test/CodeGenOpenCLCXX/address-space-deduction.cl
===
--- /dev/null
+++ test/CodeGenOpenCLCXX/address-space-deduction.cl
@@ -0,0 +1,42 @@
+// RUN: %clang_cc1 %s -triple spir-unknown-unknown -cl-std=c++ -O0 -emit-llvm -o - | FileCheck %s -check-prefixes=COMMON,PTR
+// RUN: %clang_cc1 %s -triple spir-unknown-unknown -cl-std=c++ -O0 -emit-llvm -o - -DREF | FileCheck %s -check-prefixes=COMMON,REF
+
+#ifdef REF
+#define PTR &
+#define ADR(x) x
+#else
+#define PTR *
+#define ADR(x) &x
+#endif
+
+//COMMON: @glob = addrspace(1) global i32
+int glob;
+//PTR: @glob_p = addrspace(1) global i32 addrspace(4)* addrspacecast (i32 addrspace(1)* @glob to i32 addrspace(4)*)
+//REF: @glob_p = addrspace(1) global i32 addrspace(4)* null
+int PTR glob_p = ADR(glob);
+
+//COMMON: @_ZZ3fooi{{P|R}}U3AS4iE6loc_st = internal addrspace(1) global i32
+//PTR: @_ZZ3fooiPU3AS4iE8loc_st_p = internal addrspace(1) global i32 addrspace(4)* addrspacecast (i32 addrspace(1)* @_ZZ3fooiPU3AS4iE6loc_st to i32 addrspace(4)*)
+//REF: @_ZZ3fooiRU3AS4iE8loc_st_p = internal addrspace(1) global i32 addrspace(4)* null
+//COMMON: @loc_ext_p = external addrspace(1) {{global|constant}} i32 addrspace(4)*
+//COMMON: @loc_ext = external addrspace(1) global i32
+
+//REF: store i32 addrspace(4)* addrspacecast (i32 addrspace(1)* @glob to i32 addrspace(4)*), i32 addrspace(4)* addrspace(1)* @glob_p
+
+//COMMON: define spir_func i32 @_Z3fooi{{P|R}}U3AS4i(i32 %par, i32 addrspace(4)*{{.*}} %par_p)
+int foo(int par, int PTR par_p){
+//COMMON: %loc = alloca i32
+  int loc;
+//COMMON: %loc_p = alloca i32 addrspace(4)*
+//COMMON: [[GAS:%[0-9]+]] = addrspacecast i32* %loc to i32 addrspace(4)*
+//COMMON: store i32 addrspace(4)* [[GAS]], i32 addrspace(4)** %loc_p
+  int PTR loc_p = ADR(loc);
+
+// CHECK directives for the following code are located above.
+  static int loc_st;
+  static int PTR loc_st_p = ADR(loc_st);
+  extern int loc_ext;
+  extern int PTR loc_ext_p;
+  (void)loc_ext_p;
+  return loc_ext;
+}
Index: lib/Sema/SemaType.cpp
===
--- lib/Sema/SemaType.cpp
+++ lib/Sema/SemaType.cpp
@@ -7177,7 +7177,8 @@
   bool IsPointee =
   ChunkIndex > 0 &&
   (D.getTypeObject(ChunkIndex - 1).Kind == DeclaratorChunk::Pointer ||
-   D.getTypeObject(ChunkIndex - 1).Kind == DeclaratorChunk::BlockPointer);
+   D.getTypeObject(ChunkIndex - 1).Kind == DeclaratorChunk::BlockPointer ||
+   D.getTypeObject(ChunkIndex - 1).Kind == DeclaratorChunk::Reference);
   bool IsFuncReturnType =
   ChunkIndex > 0 &&
   D.getTypeObject(ChunkIndex - 1).Kind == DeclaratorChunk::Function;
Index: lib/Sema/SemaInit.cpp
===
--- lib/Sema/SemaInit.cpp
+++ lib/Sema/SemaInit.cpp
@@ -7209,12 +7209,20 @@
   return CreateMaterializeTemporaryExpr(E->getType(), E, false);
 }
 
-ExprResult
-InitializationSequence::Perform(Sema &S,
-const InitializedEntity &Entity,
-const InitializationKind &Kind,
-MultiExprArg Args,
-QualType *ResultType) {
+ExprResult Sema::PerformQualificationConversion(Expr *E, QualType Ty,
+ExprValueKind VK,
+CheckedConversionKind CCK) {
+  CastKind CK = (Ty.getAddressSpace() != E->getType().getAddressSpace())
+? CK_AddressSpaceConversion
+: CK_NoOp;
+  return ImpCastExprToType(E, Ty, CK, VK, /*BasePath=*/nullptr, CCK);
+}
+
+ExprResult InitializationSequence::Perform(Sema &S,
+   const InitializedEntity &Entity,
+   const InitializationKind &Kind,
+   MultiExprArg Args,
+   QualType *ResultType) {
   if (Failed()) {
 Diagnose(S, Entity, Kind, Args);
 return ExprError();
@@ -7603,12 +7611,11 @@
 case SK_QualificationConversionRValue: {
   // Perform a qualification conversion; these can never go wrong.
   ExprValueKind VK =
-  Step->Kind == SK_QualificationConversionLValue ?
-  VK_LValue :
-  (Step->Kind == SK_QualificationConversionXValue ?
-   VK_XValue :
-   VK_RValue);
-  CurInit = S.ImpCastExprToType(CurInit.get(), Step->Type, CK_NoOp, VK);
+  Step->

Re: r346491 - [clang-cl] Add warning for /Zc:dllexportInlines- when the flag is used with /fallback

2018-11-09 Thread Nico Weber via cfe-commits
This only prints the warning when /fallback actually happens, right? I
don't think that's good enough: If we build a few TUs with
/dllexportInlines- and don't fall back, those .obj files are not abi
compatible with the cl-built ones. (Consider all dllexport TUs of a header
being built with clang-cl but all dllimport versions of the same header
being built by cl – I think this will cause link errors). SO I think we
should error out if /dllexportIlnlines- /fallback is on the same line, even
if the fallback doesn't actually happen.

On Fri, Nov 9, 2018 at 8:28 AM Takuto Ikuta via cfe-commits <
cfe-commits@lists.llvm.org> wrote:

> Author: tikuta
> Date: Fri Nov  9 05:25:45 2018
> New Revision: 346491
>
> URL: http://llvm.org/viewvc/llvm-project?rev=346491&view=rev
> Log:
> [clang-cl] Add warning for /Zc:dllexportInlines- when the flag is used
> with /fallback
>
> Summary:
> This is followup of
> https://reviews.llvm.org/D51340
>
> Reviewers: hans, thakis
>
> Reviewed By: hans
>
> Subscribers: cfe-commits, llvm-commits
>
> Differential Revision: https://reviews.llvm.org/D54298
>
> Modified:
> cfe/trunk/include/clang/Basic/DiagnosticDriverKinds.td
> cfe/trunk/lib/Driver/ToolChains/MSVC.cpp
> cfe/trunk/test/Driver/cl-options.c
>
> Modified: cfe/trunk/include/clang/Basic/DiagnosticDriverKinds.td
> URL:
> http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Basic/DiagnosticDriverKinds.td?rev=346491&r1=346490&r2=346491&view=diff
>
> ==
> --- cfe/trunk/include/clang/Basic/DiagnosticDriverKinds.td (original)
> +++ cfe/trunk/include/clang/Basic/DiagnosticDriverKinds.td Fri Nov  9
> 05:25:45 2018
> @@ -161,6 +161,10 @@ def warn_drv_yc_multiple_inputs_clang_cl
>"support for '/Yc' with more than one source file not implemented yet;
> flag ignored">,
>InGroup;
>
> +def warn_drv_non_fallback_argument_clang_cl : Warning<
> +  "option '%0' is ignored when /fallback happens">,
> +  InGroup;
> +
>  def err_drv_invalid_value : Error<"invalid value '%1' in '%0'">;
>  def err_drv_invalid_int_value : Error<"invalid integral value '%1' in
> '%0'">;
>  def err_drv_invalid_remap_file : Error<
>
> Modified: cfe/trunk/lib/Driver/ToolChains/MSVC.cpp
> URL:
> http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Driver/ToolChains/MSVC.cpp?rev=346491&r1=346490&r2=346491&view=diff
>
> ==
> --- cfe/trunk/lib/Driver/ToolChains/MSVC.cpp (original)
> +++ cfe/trunk/lib/Driver/ToolChains/MSVC.cpp Fri Nov  9 05:25:45 2018
> @@ -669,6 +669,12 @@ std::unique_ptr visualstudio::C
>// them too.
>Args.AddAllArgs(CmdArgs, options::OPT_UNKNOWN);
>
> +  // Warning for ignored flag.
> +  if (const Arg *dllexportInlines =
> +  Args.getLastArg(options::OPT__SLASH_Zc_dllexportInlines_))
> +
> C.getDriver().Diag(clang::diag::warn_drv_non_fallback_argument_clang_cl)
> +  << dllexportInlines->getAsString(Args);
> +
>// Input filename.
>assert(Inputs.size() == 1);
>const InputInfo &II = Inputs[0];
>
> Modified: cfe/trunk/test/Driver/cl-options.c
> URL:
> http://llvm.org/viewvc/llvm-project/cfe/trunk/test/Driver/cl-options.c?rev=346491&r1=346490&r2=346491&view=diff
>
> ==
> --- cfe/trunk/test/Driver/cl-options.c (original)
> +++ cfe/trunk/test/Driver/cl-options.c Fri Nov  9 05:25:45 2018
> @@ -494,6 +494,8 @@
>  // NoDllExportInlines: "-fno-dllexport-inlines"
>  // RUN: %clang_cl /Zc:dllexportInlines /c -### -- %s 2>&1 | FileCheck
> -check-prefix=DllExportInlines %s
>  // DllExportInlines-NOT: "-fno-dllexport-inlines"
> +// RUN: %clang_cl /fallback /Zc:dllexportInlines- /c -### -- %s 2>&1 |
> FileCheck -check-prefix=DllExportInlinesFallback %s
> +// DllExportInlinesFallback: warning: option '/Zc:dllexportInlines-' is
> ignored when /fallback happens [-Woption-ignored]
>
>  // RUN: %clang_cl /Zi /c -### -- %s 2>&1 | FileCheck -check-prefix=Zi %s
>  // Zi: "-gcodeview"
>
>
> ___
> cfe-commits mailing list
> cfe-commits@lists.llvm.org
> http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
>
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D54310: Make clang-based tools find libc++ on MacOS

2018-11-09 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.

This is hacky, but solves an important problem. If you know of a good reviewer 
for this, you may want a second opinion!




Comment at: include/clang/Lex/HeaderSearchOptions.h:111
 
+  /// Compiler install dir as detected by the Driver.
+  /// Only used to add include dirs for libc++ on Darwin. Please avoid relying

Could you add "typically contains bin/clang, lib/libclang_rt, and 
include/"?



Comment at: lib/Frontend/CompilerInvocation.cpp:1776
   Opts.ResourceDir = Args.getLastArgValue(OPT_resource_dir);
+  Opts.InstallDir = Opts.ResourceDir;
 

(is this needed? I guess you fall back to this if you don't create the CI from 
the command line?)


Repository:
  rC Clang

https://reviews.llvm.org/D54310



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


[PATCH] D52273: [clangd] Initial implementation of expected types

2018-11-09 Thread Ilya Biryukov via Phabricator via cfe-commits
ilya-biryukov updated this revision to Diff 173337.
ilya-biryukov added a comment.

- Simplify the initial implementation
- Rename SType to OpaqueType


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D52273

Files:
  clangd/CMakeLists.txt
  clangd/ExpectedTypes.cpp
  clangd/ExpectedTypes.h
  unittests/clangd/CMakeLists.txt
  unittests/clangd/ExpectedTypeTest.cpp

Index: unittests/clangd/ExpectedTypeTest.cpp
===
--- /dev/null
+++ unittests/clangd/ExpectedTypeTest.cpp
@@ -0,0 +1,191 @@
+//===-- ExpectedTypeTest.cpp  ---*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===--===//
+
+#include "ClangdUnit.h"
+#include "ExpectedTypes.h"
+#include "TestTU.h"
+#include "clang/AST/ASTContext.h"
+#include "clang/AST/Decl.h"
+#include "clang/AST/Type.h"
+#include "llvm/ADT/StringRef.h"
+#include "gmock/gmock-matchers.h"
+#include "gmock/gmock.h"
+#include "gtest/gtest.h"
+
+namespace clang {
+namespace clangd {
+namespace {
+
+using ::testing::ElementsAre;
+using ::testing::Field;
+using ::testing::Matcher;
+using ::testing::UnorderedElementsAre;
+using ::testing::UnorderedElementsAreArray;
+
+class ASTTest : public ::testing::Test {
+protected:
+  void build(llvm::StringRef Code) {
+assert(!AST && "AST built twice");
+AST = TestTU::withCode(Code).build();
+  }
+
+  const ValueDecl *decl(llvm::StringRef Name) {
+return &llvm::cast(findDecl(*AST, Name));
+  }
+
+  QualType typeOf(llvm::StringRef Name) {
+return decl(Name)->getType().getCanonicalType();
+  }
+
+  ASTContext &ASTCtx() { return AST->getASTContext(); }
+
+private:
+  // Set after calling build().
+  llvm::Optional AST;
+};
+
+class ConvertibleToMatcher
+: public ::testing::MatcherInterface {
+  ASTContext &Ctx;
+  QualType To;
+  OpaqueType PreferredType;
+
+public:
+  ConvertibleToMatcher(ASTContext &Ctx, QualType To)
+  : Ctx(Ctx), To(To.getCanonicalType()),
+PreferredType(*OpaqueType::fromPreferredType(Ctx, To)) {}
+
+  void DescribeTo(std::ostream *OS) const override {
+*OS << "Is convertible to type '" << To.getAsString() << "'";
+  }
+
+  bool MatchAndExplain(const ValueDecl *V,
+   ::testing::MatchResultListener *L) const override {
+assert(V);
+assert(&V->getASTContext() == &Ctx && "different ASTs?");
+auto ConvertibleTo = OpaqueType::fromCompletionResult(
+Ctx, CodeCompletionResult(V, CCP_Declaration));
+
+bool Matched = PreferredType == ConvertibleTo;
+if (L->IsInterested())
+  *L << "Types of source and target "
+ << (Matched ? "matched" : "did not match")
+ << "\n\tTarget type: " << To.getAsString()
+ << "\n\tSource value type: " << V->getType().getAsString();
+return Matched;
+  }
+};
+
+class ExpectedTypeConversionTest : public ASTTest {
+protected:
+  Matcher isConvertibleTo(QualType To) {
+return ::testing::MakeMatcher(new ConvertibleToMatcher(ASTCtx(), To));
+  }
+};
+
+TEST_F(ExpectedTypeConversionTest, BasicTypes) {
+  build(R"cpp(
+// ints.
+bool b;
+int i;
+unsigned int ui;
+long long ll;
+
+// floats.
+float f;
+double d;
+
+// pointers
+int* iptr;
+bool* bptr;
+
+// user-defined types.
+struct X {};
+X user_type;
+  )cpp");
+
+  const ValueDecl *Ints[] = {decl("b"), decl("i"), decl("ui"), decl("ll")};
+  const ValueDecl *Floats[] = {decl("f"), decl("d")};
+  const ValueDecl *IntPtr = decl("iptr");
+  const ValueDecl *BoolPtr = decl("bptr");
+  const ValueDecl *UserType = decl("user_type");
+
+  // Split all decls into equivalence groups. Decls inside the same equivalence
+  // group contain items that are convertible between each other.
+  llvm::ArrayRef EquivGroups[] = {
+  Ints, Floats, llvm::makeArrayRef(IntPtr), llvm::makeArrayRef(BoolPtr),
+  llvm::makeArrayRef(UserType)};
+
+  // Checks decls inside the same equivalence class can convert to each other.
+  for (auto Group : EquivGroups) {
+for (auto Decl : Group) {
+  for (auto OtherDecl : Group)
+EXPECT_THAT(Decl, isConvertibleTo(OtherDecl->getType()));
+}
+  }
+
+  // Checks items from different equivalence classes are not convertible between
+  // each other.
+  for (auto Group : EquivGroups) {
+for (auto OtherGroup : EquivGroups) {
+  if (Group.data() == OtherGroup.data())
+continue;
+
+  for (auto Decl1 : Group) {
+for (auto Decl2 : OtherGroup) {
+  if (Decl1 == Decl2)
+continue;
+  EXPECT_THAT(Decl1, Not(isConvertibleTo(Decl2->getType(;
+}
+  }
+}
+  }
+}
+
+TEST_F(ExpectedTypeConversionTest, FunctionReturns) {
+  build(R"cpp(
+ int returns_int();
+ int* returns

[PATCH] D52273: [clangd] Initial implementation of expected types

2018-11-09 Thread Ilya Biryukov via Phabricator via cfe-commits
ilya-biryukov added a comment.

I've run the measurements on a highly simplified vs the original complicated 
model and got roughly the same results wrt to ranking improvements, so sending 
a new version of the patch with highly simplified mode for the type 
representation.
I believe there are still gains to be had from a more thorough treatment of C++ 
conversions, but there is definitely much to do in other areas that should 
provide better ground for seeing the actual improvements with the more 
complicated model.

In any case, starting with something simple is definitely a better ground. 
Thanks for initial review and suggestions!
And please take a look at the new version, it is significantly simpler and 
should be pretty easy to review :-)


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D52273



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


[PATCH] D54319: clang-cl: Add documentation for /Zc:dllexportInlines-

2018-11-09 Thread Hans Wennborg via Phabricator via cfe-commits
hans created this revision.
hans added reviewers: takuto.ikuta, thakis, rnk.

A great feature needs great documentation. Please take a look!


https://reviews.llvm.org/D54319

Files:
  docs/UsersManual.rst
  include/clang/Driver/CLCompatOptions.td

Index: include/clang/Driver/CLCompatOptions.td
===
--- include/clang/Driver/CLCompatOptions.td
+++ include/clang/Driver/CLCompatOptions.td
@@ -335,8 +335,10 @@
   MetaVarName<"">;
 def _SLASH_Y_ : CLFlag<"Y-">,
   HelpText<"Disable precompiled headers, overrides /Yc and /Yu">;
-def _SLASH_Zc_dllexportInlines : CLFlag<"Zc:dllexportInlines">;
-def _SLASH_Zc_dllexportInlines_ : CLFlag<"Zc:dllexportInlines-">;
+def _SLASH_Zc_dllexportInlines : CLFlag<"Zc:dllexportInlines">,
+  HelpText<"dllexport/import inline member functions of dllexport/import classes (default)">;
+def _SLASH_Zc_dllexportInlines_ : CLFlag<"Zc:dllexportInlines-">,
+  HelpText<"Don't dllexport/import inline member functions of dllexport/import classes">;
 def _SLASH_Fp : CLJoined<"Fp">,
   HelpText<"Set pch filename (with /Yc and /Yu)">, MetaVarName<"">;
 
Index: docs/UsersManual.rst
===
--- docs/UsersManual.rst
+++ docs/UsersManual.rst
@@ -2947,6 +2947,8 @@
   /Yc   Generate a pch file for all code up to and including 
   /Yu   Load a pch file and use it instead of all code up to and including 
   /Z7 Enable CodeView debug information in object files
+  /Zc:dllexportInlines-   Don't dllexport/import inline member functions of dllexport/import classes
+  /Zc:dllexportInlinesdllexport/import inline member functions of dllexport/import classes (default)
   /Zc:sizedDealloc-   Disable C++14 sized global deallocation functions
   /Zc:sizedDeallocEnable C++14 sized global deallocation functions
   /Zc:strictStrings   Treat string literals as const
@@ -3096,6 +3098,80 @@
 arguments are treated as if they were passed at the end of the clang-cl command
 line.
 
+The /Zc:dllexportInlines- Option
+
+
+This causes the class-level `dllexport` and `dllimport` attributes not to be
+applied to inline member functions, as they otherwise would. For example, in
+the code below `S::foo()` would normally be defined and exported by the DLL,
+but when using the ``/Zc:dllexportInlines-`` flag it is not:
+
+.. code-block:: c
+
+  struct __declspec(dllexport) S {
+void foo() {}
+  }
+
+This has the benefit that the compiler doesn't need to emit a definition of
+`S::foo()` in every translation unit where the declaration is included, as it
+would otherwise do to ensure there's a definition in the DLL even if it's not
+used there. If the declaration occurs in a header file that's widely used, this
+can save significant compilation time and output size. It also reduces the
+number of functions exported by the DLL similarly to what
+``-fvisibility-inlines-hidden`` does for shared objects on ELF and Mach-O.
+Since the function declaration comes with an inline definition, users of the
+library can use that definition directly instead of importing it from the DLL.
+
+Note that the Microsoft Visual C++ compiler does not support this option, and
+if code in a DLL is compiled with ``/Zc:dllexportInlines-``, the code using the
+DLL must be compiled in the same way so that it doesn't attempt to dllimport
+the inline member functions. The reverse scenario should generally work though:
+a DLL compiled without this flag (such as a system library compiled with Visual
+C++) can be referenced from code compiled using the flag, meaning that the
+referencing code will use the inline definitions instead of importing them from
+the DLL.
+
+Also note that like when using ``-fvisibility-inlines-hidden``, the address of
+`S::foo()` will be different inside and outside the DLL, breaking the C/C++
+standard requirement that functions have a unique address.
+
+The flag does not apply to explicit class template instantiation definitions or
+declarations, as those are typically used to explicitly provide a single
+definition in a DLL, (dllexported instantiation definition) or to signal that
+the definition is available elsewhere (dllimport instantiation declaration). It
+also doesn't apply to inline members with static local variables, to ensure
+that the same instance of the variable is used inside and outside the DLL.
+
+Using this flag can cause problems when inline functions that would otherwise
+be dllexported refer to internal symbols of a DLL. For example:
+
+.. code-block:: c
+
+  void internal();
+
+  struct __declspec(dllimport) S {
+void foo() { internal(); }
+  }
+
+Normally, references to `S::foo()` would use the definition in the DLL from
+which it was exported, and which presumably also has the definition of
+`internal()`. However, when using ``/Zc:dllexportInlines-``, the inline
+defini

[PATCH] D52274: [clangd] Collect and store expected types in the index

2018-11-09 Thread Ilya Biryukov via Phabricator via cfe-commits
ilya-biryukov updated this revision to Diff 173340.
ilya-biryukov added a comment.

- Rebase and update after dependent changes.


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D52274

Files:
  clangd/index/Index.cpp
  clangd/index/Index.h
  clangd/index/SymbolCollector.cpp
  clangd/index/SymbolCollector.h
  clangd/index/YAMLSerialization.cpp
  clangd/indexer/IndexerMain.cpp

Index: clangd/indexer/IndexerMain.cpp
===
--- clangd/indexer/IndexerMain.cpp
+++ clangd/indexer/IndexerMain.cpp
@@ -37,12 +37,18 @@
  "binary RIFF format")),
cl::init(IndexFileFormat::RIFF));
 
+static llvm::cl::opt
+CollectTypes("collect-types",
+ llvm::cl::desc("Collect type information during indexing"),
+ llvm::cl::init(false), llvm::cl::Hidden);
+
 class IndexActionFactory : public tooling::FrontendActionFactory {
 public:
   IndexActionFactory(IndexFileIn &Result) : Result(Result) {}
 
   clang::FrontendAction *create() override {
 SymbolCollector::Options Opts;
+Opts.CollectTypes = CollectTypes;
 return createStaticIndexingAction(
Opts,
[&](SymbolSlab S) {
Index: clangd/index/YAMLSerialization.cpp
===
--- clangd/index/YAMLSerialization.cpp
+++ clangd/index/YAMLSerialization.cpp
@@ -179,6 +179,7 @@
 IO.mapOptional("Documentation", Sym.Documentation);
 IO.mapOptional("ReturnType", Sym.ReturnType);
 IO.mapOptional("IncludeHeaders", Sym.IncludeHeaders);
+IO.mapOptional("Type", Sym.Type);
   }
 };
 
Index: clangd/index/SymbolCollector.h
===
--- clangd/index/SymbolCollector.h
+++ clangd/index/SymbolCollector.h
@@ -76,6 +76,8 @@
 /// If this is set, only collect symbols/references from a file if
 /// `FileFilter(SM, FID)` is true. If not set, all files are indexed.
 std::function FileFilter = nullptr;
+/// Collect type information. Used to improve code completion ranking.
+bool CollectTypes = true;
   };
 
   SymbolCollector(Options Opts);
Index: clangd/index/SymbolCollector.cpp
===
--- clangd/index/SymbolCollector.cpp
+++ clangd/index/SymbolCollector.cpp
@@ -596,6 +596,11 @@
   if (!Include.empty())
 S.IncludeHeaders.emplace_back(Include, 1);
 
+  llvm::Optional Type;
+  if (Opts.CollectTypes && (S.Flags & Symbol::IndexedForCodeCompletion))
+Type = OpaqueType::fromCompletionResult(*ASTCtx, SymbolCompletion);
+  S.Type = Type ? Type->rawStr() : "";
+
   S.Origin = Opts.Origin;
   if (ND.getAvailability() == AR_Deprecated)
 S.Flags |= Symbol::Deprecated;
Index: clangd/index/Index.h
===
--- clangd/index/Index.h
+++ clangd/index/Index.h
@@ -10,12 +10,14 @@
 #ifndef LLVM_CLANG_TOOLS_EXTRA_CLANGD_INDEX_INDEX_H
 #define LLVM_CLANG_TOOLS_EXTRA_CLANGD_INDEX_INDEX_H
 
+#include "ExpectedTypes.h"
 #include "clang/Index/IndexSymbol.h"
 #include "clang/Lex/Lexer.h"
 #include "llvm/ADT/DenseMap.h"
 #include "llvm/ADT/DenseSet.h"
 #include "llvm/ADT/Hashing.h"
 #include "llvm/ADT/Optional.h"
+#include "llvm/ADT/STLExtras.h"
 #include "llvm/ADT/SmallVector.h"
 #include "llvm/ADT/StringExtras.h"
 #include "llvm/ADT/StringRef.h"
@@ -270,6 +272,9 @@
 ImplementationDetail = 1 << 2,
   };
 
+  /// Type of the symbol, used for scoring purposes.
+  llvm::StringRef Type;
+
   SymbolFlag Flags = SymbolFlag::None;
   /// FIXME: also add deprecation message and fixit?
 };
@@ -285,7 +290,8 @@
 
 // Invokes Callback with each StringRef& contained in the Symbol.
 // Useful for deduplicating backing strings.
-template  void visitStrings(Symbol &S, const Callback &CB) {
+inline void visitStrings(Symbol &S,
+ llvm::function_ref CB) {
   CB(S.Name);
   CB(S.Scope);
   CB(S.CanonicalDeclaration.FileURI);
@@ -296,6 +302,7 @@
   CB(S.ReturnType);
   for (auto &Include : S.IncludeHeaders)
 CB(Include.IncludeHeader);
+  CB(S.Type);
 }
 
 // Computes query-independent quality score for a Symbol.
Index: clangd/index/Index.cpp
===
--- clangd/index/Index.cpp
+++ clangd/index/Index.cpp
@@ -114,18 +114,19 @@
 }
 
 // Copy the underlying data of the symbol into the owned arena.
-static void own(Symbol &S, UniqueStringSaver &Strings) {
+static void own(Symbol &S, UniqueStringSaver &Strings,
+BumpPtrAllocator &Arena) {
   visitStrings(S, [&](StringRef &V) { V = Strings.save(V); });
 }
 
 void SymbolSlab::Builder::insert(const Symbol &S) {
   auto R = SymbolIndex.try_emplace(S.ID, Symbols.size());
   if (R.second) {
 Symbols.push_back(S);
-own(Symbols.back(), UniqueStrings);
+own(Symbols.back(), UniqueStrings, Arena);
   } else {
 auto &Copy = Symbols[R.fir

[PATCH] D52276: [clangd] Add type boosting in code completion

2018-11-09 Thread Ilya Biryukov via Phabricator via cfe-commits
ilya-biryukov updated this revision to Diff 173341.
ilya-biryukov added a comment.

- Rebase and update wrt to dependent changes


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D52276

Files:
  clangd/CodeComplete.cpp
  clangd/Quality.cpp
  clangd/Quality.h


Index: clangd/Quality.h
===
--- clangd/Quality.h
+++ clangd/Quality.h
@@ -28,6 +28,7 @@
 #ifndef LLVM_CLANG_TOOLS_EXTRA_CLANGD_QUALITY_H
 #define LLVM_CLANG_TOOLS_EXTRA_CLANGD_QUALITY_H
 
+#include "ExpectedTypes.h"
 #include "FileDistance.h"
 #include "clang/Sema/CodeCompleteConsumer.h"
 #include "llvm/ADT/ArrayRef.h"
@@ -93,6 +94,8 @@
   /// These are used to calculate proximity between the index symbol and the
   /// query.
   llvm::StringRef SymbolURI;
+  /// Whether the item matches the type expected in the completion context.
+  bool TypeMatchesPreferred = false;
   /// FIXME: unify with index proximity score - signals should be
   /// source-independent.
   /// Proximity between best declaration and the query. [0-1], 1 is closest.
Index: clangd/Quality.cpp
===
--- clangd/Quality.cpp
+++ clangd/Quality.cpp
@@ -369,6 +369,9 @@
 }
   }
 
+  if (TypeMatchesPreferred)
+Score *= 2.0;
+
   // Penalize non-instance members when they are accessed via a class instance.
   if (!IsInstanceMember &&
   (Context == CodeCompletionContext::CCC_DotMemberAccess ||
Index: clangd/CodeComplete.cpp
===
--- clangd/CodeComplete.cpp
+++ clangd/CodeComplete.cpp
@@ -24,6 +24,7 @@
 #include "CodeCompletionStrings.h"
 #include "Compiler.h"
 #include "Diagnostics.h"
+#include "ExpectedTypes.h"
 #include "FileDistance.h"
 #include "FuzzyMatch.h"
 #include "Headers.h"
@@ -1225,6 +1226,7 @@
   std::vector QueryScopes; // Initialized once Sema runs.
   // Initialized once QueryScopes is initialized, if there are scopes.
   Optional ScopeProximity;
+  llvm::Optional PreferredType; // Initialized once Sema runs.
   // Whether to query symbols from any scope. Initialized once Sema runs.
   bool AllScopes = false;
   // Include-insertion and proximity scoring rely on the include structure.
@@ -1354,6 +1356,12 @@
 getQueryScopes(Recorder->CCContext, *Recorder->CCSema, Opts);
 if (!QueryScopes.empty())
   ScopeProximity.emplace(QueryScopes);
+PreferredType =
+OpaqueType::fromPreferredType(Recorder->CCSema->getASTContext(),
+  Recorder->CCContext.getPreferredType());
+if (PreferredType)
+  vlog("Added an expected type for {1}",
+   Recorder->CCContext.getPreferredType().getAsString());
 // Sema provides the needed context to query the index.
 // FIXME: in addition to querying for extra/overlapping symbols, we should
 //explicitly request symbols corresponding to Sema results.
@@ -1506,10 +1514,24 @@
 Relevance.merge(*Candidate.IndexResult);
 Origin |= Candidate.IndexResult->Origin;
 FromIndex = true;
+if (PreferredType &&
+PreferredType->rawStr() == Candidate.IndexResult->Type) {
+  vlog("Types matched in index for {0}", Candidate.Name);
+  Relevance.TypeMatchesPreferred = true;
+}
   }
   if (Candidate.SemaResult) {
 Quality.merge(*Candidate.SemaResult);
 Relevance.merge(*Candidate.SemaResult);
+if (PreferredType) {
+  if (auto CompletionType = OpaqueType::fromCompletionResult(
+  Recorder->CCSema->getASTContext(), *Candidate.SemaResult)) {
+if (PreferredType == CompletionType) {
+  vlog("Types matched in index for {0}", Candidate.Name);
+  Relevance.TypeMatchesPreferred = true;
+}
+  }
+}
 Origin |= SymbolOrigin::AST;
   }
 }


Index: clangd/Quality.h
===
--- clangd/Quality.h
+++ clangd/Quality.h
@@ -28,6 +28,7 @@
 #ifndef LLVM_CLANG_TOOLS_EXTRA_CLANGD_QUALITY_H
 #define LLVM_CLANG_TOOLS_EXTRA_CLANGD_QUALITY_H
 
+#include "ExpectedTypes.h"
 #include "FileDistance.h"
 #include "clang/Sema/CodeCompleteConsumer.h"
 #include "llvm/ADT/ArrayRef.h"
@@ -93,6 +94,8 @@
   /// These are used to calculate proximity between the index symbol and the
   /// query.
   llvm::StringRef SymbolURI;
+  /// Whether the item matches the type expected in the completion context.
+  bool TypeMatchesPreferred = false;
   /// FIXME: unify with index proximity score - signals should be
   /// source-independent.
   /// Proximity between best declaration and the query. [0-1], 1 is closest.
Index: clangd/Quality.cpp
===
--- clangd/Quality.cpp
+++ clangd/Quality.cpp
@@ -369,6 +369,9 @@
 }
   }
 
+  if (TypeMatchesPreferred)
+Score *= 2.0;
+
   // Penalize non-insta

r346507 - [OPENMP][NVPTX]Allow to use shared memory for the

2018-11-09 Thread Alexey Bataev via cfe-commits
Author: abataev
Date: Fri Nov  9 08:18:04 2018
New Revision: 346507

URL: http://llvm.org/viewvc/llvm-project?rev=346507&view=rev
Log:
[OPENMP][NVPTX]Allow to use shared memory for the
target|teams|distribute variables.

If the total size of the variables, declared in target|teams|distribute
regions, is less than the maximal size of shared memory available, the
buffer is allocated in the shared memory.

Modified:
cfe/trunk/lib/CodeGen/CGOpenMPRuntimeNVPTX.cpp
cfe/trunk/lib/CodeGen/CGOpenMPRuntimeNVPTX.h
cfe/trunk/test/OpenMP/nvptx_data_sharing.cpp
cfe/trunk/test/OpenMP/nvptx_distribute_parallel_generic_mode_codegen.cpp
cfe/trunk/test/OpenMP/nvptx_parallel_codegen.cpp
cfe/trunk/test/OpenMP/nvptx_parallel_for_codegen.cpp
cfe/trunk/test/OpenMP/nvptx_target_teams_distribute_parallel_for_codegen.cpp

cfe/trunk/test/OpenMP/nvptx_target_teams_distribute_parallel_for_simd_codegen.cpp
cfe/trunk/test/OpenMP/nvptx_teams_codegen.cpp

Modified: cfe/trunk/lib/CodeGen/CGOpenMPRuntimeNVPTX.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/CodeGen/CGOpenMPRuntimeNVPTX.cpp?rev=346507&r1=346506&r2=346507&view=diff
==
--- cfe/trunk/lib/CodeGen/CGOpenMPRuntimeNVPTX.cpp (original)
+++ cfe/trunk/lib/CodeGen/CGOpenMPRuntimeNVPTX.cpp Fri Nov  9 08:18:04 2018
@@ -176,6 +176,9 @@ enum MachineConfiguration : unsigned {
 
   /// Global memory alignment for performance.
   GlobalMemoryAlignment = 128,
+
+  /// Maximal size of the shared memory buffer.
+  SharedMemorySize = 128,
 };
 
 enum NamedBarrier : unsigned {
@@ -1143,13 +1146,6 @@ void CGOpenMPRuntimeNVPTX::emitNonSPMDKe
   IsInTTDRegion = true;
   // Reserve place for the globalized memory.
   GlobalizedRecords.emplace_back();
-  if (!StaticGlobalized) {
-StaticGlobalized = new llvm::GlobalVariable(
-CGM.getModule(), CGM.VoidPtrTy, /*isConstant=*/true,
-llvm::GlobalValue::WeakAnyLinkage, nullptr,
-"_openmp_static_glob_rd$ptr");
-StaticGlobalized->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
-  }
   if (!KernelStaticGlobalized) {
 KernelStaticGlobalized = new llvm::GlobalVariable(
 CGM.getModule(), CGM.VoidPtrTy, /*isConstant=*/false,
@@ -1277,13 +1273,6 @@ void CGOpenMPRuntimeNVPTX::emitSPMDKerne
   IsInTTDRegion = true;
   // Reserve place for the globalized memory.
   GlobalizedRecords.emplace_back();
-  if (!StaticGlobalized) {
-StaticGlobalized = new llvm::GlobalVariable(
-CGM.getModule(), CGM.VoidPtrTy, /*isConstant=*/true,
-llvm::GlobalValue::WeakAnyLinkage, nullptr,
-"_openmp_static_glob_rd$ptr");
-StaticGlobalized->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
-  }
   if (!KernelStaticGlobalized) {
 KernelStaticGlobalized = new llvm::GlobalVariable(
 CGM.getModule(), CGM.VoidPtrTy, /*isConstant=*/false,
@@ -2138,30 +2127,41 @@ void CGOpenMPRuntimeNVPTX::emitGenericVa
   GlobalizedRecords.back().Records.push_back(GlobalizedVarsRecord);
   ++GlobalizedRecords.back().RegionCounter;
   if (GlobalizedRecords.back().Records.size() == 1) {
-assert(StaticGlobalized &&
-   "Static pointer must be initialized already.");
-Address Buffer = CGF.EmitLoadOfPointer(
-Address(StaticGlobalized, CGM.getPointerAlign()),
-CGM.getContext()
-.getPointerType(CGM.getContext().VoidPtrTy)
-.castAs());
+assert(KernelStaticGlobalized &&
+   "Kernel static pointer must be initialized already.");
+auto *UseSharedMemory = new llvm::GlobalVariable(
+CGM.getModule(), CGM.Int16Ty, /*isConstant=*/true,
+llvm::GlobalValue::InternalLinkage, nullptr,
+"_openmp_static_kernel$is_shared");
+
UseSharedMemory->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
+QualType Int16Ty = CGM.getContext().getIntTypeForBitwidth(
+/*DestWidth=*/16, /*Signed=*/0);
+llvm::Value *IsInSharedMemory = CGF.EmitLoadOfScalar(
+Address(UseSharedMemory,
+CGM.getContext().getTypeAlignInChars(Int16Ty)),
+/*Volatile=*/false, Int16Ty, Loc);
+auto *StaticGlobalized = new llvm::GlobalVariable(
+CGM.getModule(), CGM.Int8Ty, /*isConstant=*/false,
+llvm::GlobalValue::WeakAnyLinkage, nullptr);
 auto *RecSize = new llvm::GlobalVariable(
 CGM.getModule(), CGM.SizeTy, /*isConstant=*/true,
 llvm::GlobalValue::InternalLinkage, nullptr,
 "_openmp_static_kernel$size");
 RecSize->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
 llvm::Value *Ld = CGF.EmitLoadOfScalar(
-Address(RecSize, CGM.getPointerAlign()), /*Volatile=*/false,
+Address(RecSize, CGM.getSizeAlign()), /*Volatile=*/false,
 CGM.getContext().getSizeType(), Loc);
 llvm::Value *ResAd

Re: r346491 - [clang-cl] Add warning for /Zc:dllexportInlines- when the flag is used with /fallback

2018-11-09 Thread Hans Wennborg via cfe-commits
On Fri, Nov 9, 2018 at 4:53 PM, Nico Weber  wrote:
> This only prints the warning when /fallback actually happens, right?

No, it prints it when the fallback job is created, not when (or if) it
runs. I.e. it prints if the /fallback flag is used, regardless of
whether it actually falls back or not. This is reflected by the test
which uses -###, i.e. nothing is getting run.

So I think we're good :-)

> I don't
> think that's good enough: If we build a few TUs with /dllexportInlines- and
> don't fall back, those .obj files are not abi compatible with the cl-built
> ones. (Consider all dllexport TUs of a header being built with clang-cl but
> all dllimport versions of the same header being built by cl – I think this
> will cause link errors). SO I think we should error out if
> /dllexportIlnlines- /fallback is on the same line, even if the fallback
> doesn't actually happen.
>
> On Fri, Nov 9, 2018 at 8:28 AM Takuto Ikuta via cfe-commits
>  wrote:
>>
>> Author: tikuta
>> Date: Fri Nov  9 05:25:45 2018
>> New Revision: 346491
>>
>> URL: http://llvm.org/viewvc/llvm-project?rev=346491&view=rev
>> Log:
>> [clang-cl] Add warning for /Zc:dllexportInlines- when the flag is used
>> with /fallback
>>
>> Summary:
>> This is followup of
>> https://reviews.llvm.org/D51340
>>
>> Reviewers: hans, thakis
>>
>> Reviewed By: hans
>>
>> Subscribers: cfe-commits, llvm-commits
>>
>> Differential Revision: https://reviews.llvm.org/D54298
>>
>> Modified:
>> cfe/trunk/include/clang/Basic/DiagnosticDriverKinds.td
>> cfe/trunk/lib/Driver/ToolChains/MSVC.cpp
>> cfe/trunk/test/Driver/cl-options.c
>>
>> Modified: cfe/trunk/include/clang/Basic/DiagnosticDriverKinds.td
>> URL:
>> http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Basic/DiagnosticDriverKinds.td?rev=346491&r1=346490&r2=346491&view=diff
>>
>> ==
>> --- cfe/trunk/include/clang/Basic/DiagnosticDriverKinds.td (original)
>> +++ cfe/trunk/include/clang/Basic/DiagnosticDriverKinds.td Fri Nov  9
>> 05:25:45 2018
>> @@ -161,6 +161,10 @@ def warn_drv_yc_multiple_inputs_clang_cl
>>"support for '/Yc' with more than one source file not implemented yet;
>> flag ignored">,
>>InGroup;
>>
>> +def warn_drv_non_fallback_argument_clang_cl : Warning<
>> +  "option '%0' is ignored when /fallback happens">,
>> +  InGroup;
>> +
>>  def err_drv_invalid_value : Error<"invalid value '%1' in '%0'">;
>>  def err_drv_invalid_int_value : Error<"invalid integral value '%1' in
>> '%0'">;
>>  def err_drv_invalid_remap_file : Error<
>>
>> Modified: cfe/trunk/lib/Driver/ToolChains/MSVC.cpp
>> URL:
>> http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Driver/ToolChains/MSVC.cpp?rev=346491&r1=346490&r2=346491&view=diff
>>
>> ==
>> --- cfe/trunk/lib/Driver/ToolChains/MSVC.cpp (original)
>> +++ cfe/trunk/lib/Driver/ToolChains/MSVC.cpp Fri Nov  9 05:25:45 2018
>> @@ -669,6 +669,12 @@ std::unique_ptr visualstudio::C
>>// them too.
>>Args.AddAllArgs(CmdArgs, options::OPT_UNKNOWN);
>>
>> +  // Warning for ignored flag.
>> +  if (const Arg *dllexportInlines =
>> +  Args.getLastArg(options::OPT__SLASH_Zc_dllexportInlines_))
>> +
>> C.getDriver().Diag(clang::diag::warn_drv_non_fallback_argument_clang_cl)
>> +  << dllexportInlines->getAsString(Args);
>> +
>>// Input filename.
>>assert(Inputs.size() == 1);
>>const InputInfo &II = Inputs[0];
>>
>> Modified: cfe/trunk/test/Driver/cl-options.c
>> URL:
>> http://llvm.org/viewvc/llvm-project/cfe/trunk/test/Driver/cl-options.c?rev=346491&r1=346490&r2=346491&view=diff
>>
>> ==
>> --- cfe/trunk/test/Driver/cl-options.c (original)
>> +++ cfe/trunk/test/Driver/cl-options.c Fri Nov  9 05:25:45 2018
>> @@ -494,6 +494,8 @@
>>  // NoDllExportInlines: "-fno-dllexport-inlines"
>>  // RUN: %clang_cl /Zc:dllexportInlines /c -### -- %s 2>&1 | FileCheck
>> -check-prefix=DllExportInlines %s
>>  // DllExportInlines-NOT: "-fno-dllexport-inlines"
>> +// RUN: %clang_cl /fallback /Zc:dllexportInlines- /c -### -- %s 2>&1 |
>> FileCheck -check-prefix=DllExportInlinesFallback %s
>> +// DllExportInlinesFallback: warning: option '/Zc:dllexportInlines-' is
>> ignored when /fallback happens [-Woption-ignored]
>>
>>  // RUN: %clang_cl /Zi /c -### -- %s 2>&1 | FileCheck -check-prefix=Zi %s
>>  // Zi: "-gcodeview"
>>
>>
>> ___
>> cfe-commits mailing list
>> cfe-commits@lists.llvm.org
>> http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D53488: [clang-tidy] Improving narrowing conversions

2018-11-09 Thread Guillaume Chatelet via Phabricator via cfe-commits
gchatelet updated this revision to Diff 173343.
gchatelet marked 13 inline comments as done.
gchatelet added a comment.

- Addressing comments, adding Option to disable FP to FP narrowing warnings, 
handling FP literals.


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D53488

Files:
  clang-tidy/cppcoreguidelines/NarrowingConversionsCheck.cpp
  clang-tidy/cppcoreguidelines/NarrowingConversionsCheck.h
  docs/ReleaseNotes.rst
  docs/clang-tidy/checks/cppcoreguidelines-narrowing-conversions.rst
  test/clang-tidy/cppcoreguidelines-narrowing-conversions.cpp

Index: test/clang-tidy/cppcoreguidelines-narrowing-conversions.cpp
===
--- test/clang-tidy/cppcoreguidelines-narrowing-conversions.cpp
+++ test/clang-tidy/cppcoreguidelines-narrowing-conversions.cpp
@@ -1,4 +1,4 @@
-// RUN: %check_clang_tidy %s cppcoreguidelines-narrowing-conversions %t
+// RUN: %check_clang_tidy %s cppcoreguidelines-narrowing-conversions %t -config="{CheckOptions: [{key: "cppcoreguidelines-narrowing-conversions.WarnOnFloatingPointNarrowingConversion", value: 1}]}" -- -target x86_64-unknown-linux
 
 float ceil(float);
 namespace std {
@@ -9,47 +9,287 @@
 namespace floats {
 
 struct ConvertsToFloat {
-  operator float() const { return 0.5; }
+  operator float() const { return 0.5f; }
 };
 
-float operator "" _Pa(unsigned long long);
+float operator"" _float(unsigned long long);
 
-void not_ok(double d) {
+void narrow_double_to_int_not_ok(double d) {
   int i = 0;
   i = d;
   // CHECK-MESSAGES: :[[@LINE-1]]:7: warning: narrowing conversion from 'double' to 'int' [cppcoreguidelines-narrowing-conversions]
   i = 0.5f;
-  // CHECK-MESSAGES: :[[@LINE-1]]:7: warning: narrowing conversion from 'float' to 'int' [cppcoreguidelines-narrowing-conversions]
+  // CHECK-MESSAGES: :[[@LINE-1]]:7: warning: narrowing conversion from constant 'float' to 'int' [cppcoreguidelines-narrowing-conversions]
   i = static_cast(d);
   // CHECK-MESSAGES: :[[@LINE-1]]:7: warning: narrowing conversion from 'float' to 'int' [cppcoreguidelines-narrowing-conversions]
   i = ConvertsToFloat();
   // CHECK-MESSAGES: :[[@LINE-1]]:7: warning: narrowing conversion from 'float' to 'int' [cppcoreguidelines-narrowing-conversions]
-  i = 15_Pa;
+  i = 15_float;
   // CHECK-MESSAGES: :[[@LINE-1]]:7: warning: narrowing conversion from 'float' to 'int' [cppcoreguidelines-narrowing-conversions]
 }
 
-void not_ok_binary_ops(double d) {
+void narrow_double_to_int_not_ok_binary_ops(double d) {
   int i = 0;
   i += 0.5;
-  // CHECK-MESSAGES: :[[@LINE-1]]:5: warning: narrowing conversion from 'double' to 'int' [cppcoreguidelines-narrowing-conversions]
+  // CHECK-MESSAGES: :[[@LINE-1]]:5: warning: narrowing conversion from constant 'double' to 'int' [cppcoreguidelines-narrowing-conversions]
   i += 0.5f;
-  // CHECK-MESSAGES: :[[@LINE-1]]:5: warning: narrowing conversion from 'float' to 'int' [cppcoreguidelines-narrowing-conversions]
+  // CHECK-MESSAGES: :[[@LINE-1]]:5: warning: narrowing conversion from constant 'float' to 'int' [cppcoreguidelines-narrowing-conversions]
   i += d;
   // CHECK-MESSAGES: :[[@LINE-1]]:5: warning: narrowing conversion from 'double' to 'int' [cppcoreguidelines-narrowing-conversions]
   // We warn on the following even though it's not dangerous because there is no
   // reason to use a double literal here.
-  // TODO(courbet): Provide an automatic fix.
+  // TODO: Provide an automatic fix if the number is exactly representable in the destination type.
   i += 2.0;
-  // CHECK-MESSAGES: :[[@LINE-1]]:5: warning: narrowing conversion from 'double' to 'int' [cppcoreguidelines-narrowing-conversions]
+  // CHECK-MESSAGES: :[[@LINE-1]]:5: warning: narrowing conversion from constant 'double' to 'int' [cppcoreguidelines-narrowing-conversions]
   i += 2.0f;
-  // CHECK-MESSAGES: :[[@LINE-1]]:5: warning: narrowing conversion from 'float' to 'int' [cppcoreguidelines-narrowing-conversions]
+  // CHECK-MESSAGES: :[[@LINE-1]]:5: warning: narrowing conversion from constant 'float' to 'int' [cppcoreguidelines-narrowing-conversions]
 
   i *= 0.5f;
-  // CHECK-MESSAGES: :[[@LINE-1]]:5: warning: narrowing conversion from 'float' to 'int' [cppcoreguidelines-narrowing-conversions]
+  // CHECK-MESSAGES: :[[@LINE-1]]:5: warning: narrowing conversion from constant 'float' to 'int' [cppcoreguidelines-narrowing-conversions]
   i /= 0.5f;
-  // CHECK-MESSAGES: :[[@LINE-1]]:5: warning: narrowing conversion from 'float' to 'int' [cppcoreguidelines-narrowing-conversions]
+  // CHECK-MESSAGES: :[[@LINE-1]]:5: warning: narrowing conversion from constant 'float' to 'int' [cppcoreguidelines-narrowing-conversions]
   i += (double)0.5f;
-  // CHECK-MESSAGES: :[[@LINE-1]]:5: warning: narrowing conversion from 'double' to 'int' [cppcoreguidelines-narrowing-conversions]
+  // CHECK-MESSAGES: :[[@LINE-1]]:5: warning: narrowing conversion from constant 'double' to 'int' [cppcoreguidelines-narrowing-conversions]
+}
+
+do

[PATCH] D54321: [AST] Store the expressions in ParenListExpr in a trailing array

2018-11-09 Thread Bruno Ricci via Phabricator via cfe-commits
riccibruno created this revision.
riccibruno added a reviewer: rsmith.
riccibruno added a project: clang.
Herald added a reviewer: shafik.
Herald added a subscriber: cfe-commits.

Use the newly available space in the bit-fields of `Stmt`, and store
the expressions in `ParenListExpr` in a trailing array past `ParenListExpr`.
This saves 2 pointers per `ParenListExpr`. Additionally remove the branches
in the loop used to set the bits `TypeDependent`, `ValueDependent`,
`InstantiationDependent` and `ContainsUnexpandedParameterPack`,
and just access the bit-fields once at the end instead of during each iteration.


Repository:
  rC Clang

https://reviews.llvm.org/D54321

Files:
  include/clang/AST/Expr.h
  include/clang/AST/Stmt.h
  lib/AST/ASTImporter.cpp
  lib/AST/Expr.cpp
  lib/Sema/SemaCoroutine.cpp
  lib/Sema/SemaDeclCXX.cpp
  lib/Sema/SemaExpr.cpp
  lib/Serialization/ASTReaderStmt.cpp
  lib/Serialization/ASTWriterStmt.cpp

Index: lib/Serialization/ASTWriterStmt.cpp
===
--- lib/Serialization/ASTWriterStmt.cpp
+++ lib/Serialization/ASTWriterStmt.cpp
@@ -568,11 +568,11 @@
 
 void ASTStmtWriter::VisitParenListExpr(ParenListExpr *E) {
   VisitExpr(E);
-  Record.push_back(E->NumExprs);
-  for (unsigned i=0; i != E->NumExprs; ++i)
-Record.AddStmt(E->Exprs[i]);
-  Record.AddSourceLocation(E->LParenLoc);
-  Record.AddSourceLocation(E->RParenLoc);
+  Record.push_back(E->getNumExprs());
+  for (auto *SubStmt : E->exprs())
+Record.AddStmt(SubStmt);
+  Record.AddSourceLocation(E->getLParenLoc());
+  Record.AddSourceLocation(E->getRParenLoc());
   Code = serialization::EXPR_PAREN_LIST;
 }
 
Index: lib/Serialization/ASTReaderStmt.cpp
===
--- lib/Serialization/ASTReaderStmt.cpp
+++ lib/Serialization/ASTReaderStmt.cpp
@@ -650,10 +650,9 @@
 void ASTStmtReader::VisitParenListExpr(ParenListExpr *E) {
   VisitExpr(E);
   unsigned NumExprs = Record.readInt();
-  E->Exprs = new (Record.getContext()) Stmt*[NumExprs];
-  for (unsigned i = 0; i != NumExprs; ++i)
-E->Exprs[i] = Record.readSubStmt();
-  E->NumExprs = NumExprs;
+  assert((NumExprs == E->getNumExprs()) && "Wrong NumExprs!");
+  for (unsigned I = 0; I != NumExprs; ++I)
+E->getTrailingObjects()[I] = Record.readSubStmt();
   E->LParenLoc = ReadSourceLocation();
   E->RParenLoc = ReadSourceLocation();
 }
@@ -2463,7 +2462,9 @@
   break;
 
 case EXPR_PAREN_LIST:
-  S = new (Context) ParenListExpr(Empty);
+  S = ParenListExpr::CreateEmpty(
+  Context,
+  /* NumExprs=*/Record[ASTStmtReader::NumExprFields + 0]);
   break;
 
 case EXPR_UNARY_OPERATOR:
Index: lib/Sema/SemaExpr.cpp
===
--- lib/Sema/SemaExpr.cpp
+++ lib/Sema/SemaExpr.cpp
@@ -6379,8 +6379,7 @@
 ExprResult Sema::ActOnParenListExpr(SourceLocation L,
 SourceLocation R,
 MultiExprArg Val) {
-  Expr *expr = new (Context) ParenListExpr(Context, L, Val, R);
-  return expr;
+  return ParenListExpr::Create(Context, L, Val, R);
 }
 
 /// Emit a specialized diagnostic when one expression is a null pointer
Index: lib/Sema/SemaDeclCXX.cpp
===
--- lib/Sema/SemaDeclCXX.cpp
+++ lib/Sema/SemaDeclCXX.cpp
@@ -3731,8 +3731,7 @@
   ArrayRef Args,
   SourceLocation RParenLoc,
   SourceLocation EllipsisLoc) {
-  Expr *List = new (Context) ParenListExpr(Context, LParenLoc,
-   Args, RParenLoc);
+  Expr *List = ParenListExpr::Create(Context, LParenLoc, Args, RParenLoc);
   return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
  DS, IdLoc, List, EllipsisLoc);
 }
Index: lib/Sema/SemaCoroutine.cpp
===
--- lib/Sema/SemaCoroutine.cpp
+++ lib/Sema/SemaCoroutine.cpp
@@ -565,8 +565,8 @@
 
   // Create an initialization sequence for the promise type using the
   // constructor arguments, wrapped in a parenthesized list expression.
-  Expr *PLE = new (Context) ParenListExpr(Context, FD->getLocation(),
-  CtorArgExprs, FD->getLocation());
+  Expr *PLE = ParenListExpr::Create(Context, FD->getLocation(),
+CtorArgExprs, FD->getLocation());
   InitializedEntity Entity = InitializedEntity::InitializeVariable(VD);
   InitializationKind Kind = InitializationKind::CreateForInit(
   VD->getLocation(), /*DirectInit=*/true, PLE);
Index: lib/AST/Expr.cpp
===
--- lib/AST/Expr.cpp
+++ lib/AST/Expr.cpp
@@ -3987,25 +3987,53 @@
   return getBase()->getEndLoc();
 }
 
-ParenListExpr::ParenListExpr(const ASTContext& C, SourceLoca

[PATCH] D54307: [clang] overload ignoringParens for Expr

2018-11-09 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman added inline comments.



Comment at: include/clang/ASTMatchers/ASTMatchers.h:814
 /// would match the declaration for fp.
-AST_MATCHER_P(QualType, ignoringParens,
-  internal::Matcher, InnerMatcher) {
+AST_MATCHER_P_OVERLOAD(QualType, ignoringParens, internal::Matcher,
+   InnerMatcher, 0) {

Can you do this via `AST_POLYMORPHIC_MATCHER_P` instead, given that the 
implementation is the same?


Repository:
  rC Clang

https://reviews.llvm.org/D54307



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


[PATCH] D54307: [clang] overload ignoringParens for Expr

2018-11-09 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman added a comment.

Also: the patch is missing unit tests.


Repository:
  rC Clang

https://reviews.llvm.org/D54307



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


[PATCH] D54324: [AST] Store the value of CharacterLiteral inline if possible

2018-11-09 Thread Bruno Ricci via Phabricator via cfe-commits
riccibruno created this revision.
riccibruno added a reviewer: rsmith.
riccibruno added a project: clang.
Herald added a reviewer: shafik.
Herald added a subscriber: cfe-commits.

The vast majority of `CharacterLiteral`s have a value which fits into 8 bits
(in the 2666 `CharacterLiteral`s in all of Boost, only 2 don't).
When possible, use the space in the bit-fields of `Stmt` to store the value
and otherwise store it in a trailing object.

This saves 1 pointer per `CharacterLiteral` when the value fits into 8 bits.

Note that in itself this do not save that much space, but this is part of
a larger effort to pack the statements/expressions classes.


Repository:
  rC Clang

https://reviews.llvm.org/D54324

Files:
  include/clang/AST/Expr.h
  include/clang/AST/Stmt.h
  lib/AST/ASTImporter.cpp
  lib/AST/Expr.cpp
  lib/Sema/SemaExpr.cpp
  lib/Sema/SemaTemplate.cpp
  lib/Serialization/ASTReaderStmt.cpp

Index: lib/Serialization/ASTReaderStmt.cpp
===
--- lib/Serialization/ASTReaderStmt.cpp
+++ lib/Serialization/ASTReaderStmt.cpp
@@ -636,8 +636,8 @@
 void ASTStmtReader::VisitCharacterLiteral(CharacterLiteral *E) {
   VisitExpr(E);
   E->setValue(Record.readInt());
-  E->setLocation(ReadSourceLocation());
-  E->setKind(static_cast(Record.readInt()));
+  E->CharacterLiteralBits.Loc = ReadSourceLocation();
+  E->CharacterLiteralBits.Kind = Record.readInt();
 }
 
 void ASTStmtReader::VisitParenExpr(ParenExpr *E) {
@@ -2454,7 +2454,10 @@
   break;
 
 case EXPR_CHARACTER_LITERAL:
-  S = new (Context) CharacterLiteral(Empty);
+  S = CharacterLiteral::CreateEmpty(
+  Context,
+  /* IsSmallValue=*/CharacterLiteral::isSmallValue(
+  Record[ASTStmtReader::NumExprFields + 0]));
   break;
 
 case EXPR_PAREN:
Index: lib/Sema/SemaTemplate.cpp
===
--- lib/Sema/SemaTemplate.cpp
+++ lib/Sema/SemaTemplate.cpp
@@ -6865,8 +6865,9 @@
 else
   Kind = CharacterLiteral::Ascii;
 
-E = new (Context) CharacterLiteral(Arg.getAsIntegral().getZExtValue(),
-   Kind, T, Loc);
+E = CharacterLiteral::Create(Context, Arg.getAsIntegral().getZExtValue(),
+ Kind, T, Loc);
+
   } else if (T->isBooleanType()) {
 E = new (Context) CXXBoolLiteralExpr(Arg.getAsIntegral().getBoolValue(),
  T, Loc);
Index: lib/Sema/SemaExpr.cpp
===
--- lib/Sema/SemaExpr.cpp
+++ lib/Sema/SemaExpr.cpp
@@ -3139,8 +3139,8 @@
   else if (Literal.isUTF8())
 Kind = CharacterLiteral::UTF8;
 
-  Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty,
- Tok.getLocation());
+  Expr *Lit = CharacterLiteral::Create(Context, Literal.getValue(), Kind, Ty,
+   Tok.getLocation());
 
   if (Literal.getUDSuffix().empty())
 return Lit;
Index: lib/AST/Expr.cpp
===
--- lib/AST/Expr.cpp
+++ lib/AST/Expr.cpp
@@ -815,6 +815,37 @@
   return S.str();
 }
 
+CharacterLiteral::CharacterLiteral(unsigned Value, CharacterKind Kind,
+   QualType Type, SourceLocation Loc)
+: Expr(CharacterLiteralClass, Type, VK_RValue, OK_Ordinary, false, false,
+   false, false) {
+  CharacterLiteralBits.Kind = Kind;
+  CharacterLiteralBits.Loc = Loc;
+  CharacterLiteralBits.IsSmallValue = isSmallValue(Value);
+  setValue(Value);
+}
+
+CharacterLiteral::CharacterLiteral(EmptyShell Empty, bool IsSmallValue)
+: Expr(CharacterLiteralClass, Empty) {
+  CharacterLiteralBits.IsSmallValue = IsSmallValue;
+}
+
+CharacterLiteral *CharacterLiteral::Create(const ASTContext &Ctx,
+   unsigned Value, CharacterKind Kind,
+   QualType Type, SourceLocation Loc) {
+  bool IsSmallValue = isSmallValue(Value);
+  void *Mem = Ctx.Allocate(totalSizeToAlloc(!IsSmallValue),
+   alignof(CharacterLiteral));
+  return new (Mem) CharacterLiteral(Value, Kind, Type, Loc);
+}
+
+CharacterLiteral *CharacterLiteral::CreateEmpty(const ASTContext &Ctx,
+bool IsSmallValue) {
+  void *Mem = Ctx.Allocate(totalSizeToAlloc(!IsSmallValue),
+   alignof(CharacterLiteral));
+  return new (Mem) CharacterLiteral(EmptyShell(), IsSmallValue);
+}
+
 FloatingLiteral::FloatingLiteral(const ASTContext &C, const llvm::APFloat &V,
  bool isexact, QualType Type, SourceLocation L)
   : Expr(FloatingLiteralClass, Type, VK_RValue, OK_Ordinary, false, false,
Index: lib/AST/ASTImporter.cpp
===
--- lib/AST/ASTImporter.cpp
+++ lib/AST/ASTImp

[PATCH] D54204: [clangd] Initial clang-tidy diagnostics support.

2018-11-09 Thread Sam McCall via Phabricator via cfe-commits
sammccall updated this revision to Diff 173357.
sammccall marked an inline comment as done.
sammccall added a comment.

Address comments and rebase on https://reviews.llvm.org/D54309, addressing 
performance issues.


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D54204

Files:
  clang-tidy/misc/UnusedParametersCheck.cpp
  clang-tidy/modernize/LoopConvertCheck.cpp
  clang-tidy/modernize/LoopConvertUtils.h
  clang-tidy/readability/SimplifyBooleanExprCheck.cpp
  clang-tidy/readability/SimplifyBooleanExprCheck.h
  clangd/CMakeLists.txt
  clangd/ClangdUnit.cpp
  clangd/XRefs.cpp
  unittests/clangd/ClangdUnitTests.cpp

Index: unittests/clangd/ClangdUnitTests.cpp
===
--- unittests/clangd/ClangdUnitTests.cpp
+++ unittests/clangd/ClangdUnitTests.cpp
@@ -24,6 +24,7 @@
 using testing::Field;
 using testing::IsEmpty;
 using testing::Pair;
+using testing::UnorderedElementsAre;
 
 testing::Matcher WithFix(testing::Matcher FixMatcher) {
   return Field(&Diag::Fixes, ElementsAre(FixMatcher));
@@ -128,6 +129,30 @@
   WithFix(Fix(Test.range(), "int", "change return type to 'int'");
 }
 
+TEST(DiagnosticsTest, ClangTidy) {
+  Annotations Test(R"cpp(
+#define $macrodef[[SQUARE]](X) (X)*(X)
+int main() {
+  return [[sizeof]](sizeof(int));
+  int y = 4;
+  return SQUARE($macroarg[[++]]y);
+}
+  )cpp");
+  auto TU = TestTU::withCode(Test.code());
+  EXPECT_THAT(
+  TU.build().getDiagnostics(),
+  UnorderedElementsAre(
+  Diag(Test.range(), "suspicious usage of 'sizeof(sizeof(...))' "
+ "[bugprone-sizeof-expression]"),
+  AllOf(
+  Diag(Test.range("macroarg"),
+   "side effects in the 1st macro argument 'X' are repeated in "
+   "macro expansion [bugprone-macro-repeated-side-effects]"),
+  WithNote(Diag(Test.range("macrodef"),
+"macro 'SQUARE' defined here "
+"[bugprone-macro-repeated-side-effects]");
+}
+
 TEST(DiagnosticsTest, Preprocessor) {
   // This looks like a preamble, but there's an #else in the middle!
   // Check that:
Index: clangd/XRefs.cpp
===
--- clangd/XRefs.cpp
+++ clangd/XRefs.cpp
@@ -672,8 +672,7 @@
 return {};
 
   DeducedTypeVisitor V(SourceLocationBeg);
-  for (Decl *D : AST.getLocalTopLevelDecls())
-V.TraverseDecl(D);
+  V.TraverseAST(AST.getASTContext());
   return V.getDeducedType();
 }
 
Index: clangd/ClangdUnit.cpp
===
--- clangd/ClangdUnit.cpp
+++ clangd/ClangdUnit.cpp
@@ -8,6 +8,8 @@
 //===--===//
 
 #include "ClangdUnit.h"
+#include "../clang-tidy/ClangTidyDiagnosticConsumer.h"
+#include "../clang-tidy/ClangTidyModuleRegistry.h"
 #include "Compiler.h"
 #include "Diagnostics.h"
 #include "Logger.h"
@@ -151,6 +153,38 @@
 return None;
   }
 
+  // Set up ClangTidy. Must happen after BeginSourceFile() so ASTContext exists.
+  // Clang-tidy has some limitiations to ensure reasonable performance:
+  //  - checks don't see all preprocessor events in the preamble
+  //  - matchers run only over the main-file top-level decls (and can't see
+  //ancestors outside this scope).
+  // In practice almost all checks work well without modifications.
+  std::vector> CTChecks;
+  ast_matchers::MatchFinder CTFinder;
+  llvm::Optional CTContext;
+  {
+trace::Span Tracer("ClangTidyInit");
+tidy::ClangTidyCheckFactories CTFactories;
+for (const auto &E : tidy::ClangTidyModuleRegistry::entries())
+  E.instantiate()->addCheckFactories(CTFactories);
+auto CTOpts = tidy::ClangTidyOptions::getDefaults();
+// FIXME: this needs to be configurable, and we need to support .clang-tidy
+// files and other options providers.
+// These checks exercise the matcher- and preprocessor-based hooks.
+CTOpts.Checks =
+"bugprone-sizeof-expression,bugprone-macro-repeated-side-effects";
+CTContext.emplace(llvm::make_unique(
+tidy::ClangTidyGlobalOptions(), CTOpts));
+CTContext->setDiagnosticsEngine(&Clang->getDiagnostics());
+CTContext->setASTContext(&Clang->getASTContext());
+CTContext->setCurrentFile(MainInput.getFile());
+CTFactories.createChecks(CTContext.getPointer(), CTChecks);
+for (const auto &Check : CTChecks) {
+  Check->registerPPCallbacks(*Clang);
+  Check->registerMatchers(&CTFinder);
+}
+  }
+
   // Copy over the includes from the preamble, then combine with the
   // non-preamble includes below.
   auto Includes = Preamble ? Preamble->Includes : IncludeStructure{};
@@ -160,13 +194,26 @@
   if (!Action->Execute())
 log("Execute() failed when building AST for {0}", MainInput.getFile());
 
+  std::vector ParsedDecls = Action->takeTopLevelDecls();
+  // 

[PATCH] D54281: [clang-tidy] fix PR39583 - ignoring ParenCast for string-literals in pro-bounds-array-to-pointer-decay

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

LGTM aside from a minor commenting nit.




Comment at: 
test/clang-tidy/cppcoreguidelines-pro-bounds-array-to-pointer-decay.cpp:44
+const char *g2() {
+return ("clang"); // OK, ParenCast hides the literal-pointer decay
+}

Remove "Cast" as this is not a cast. It's a ParenExpr.


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D54281



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


[PATCH] D54204: [clangd] Initial clang-tidy diagnostics support.

2018-11-09 Thread Sam McCall via Phabricator via cfe-commits
sammccall added inline comments.



Comment at: clangd/ClangdUnit.cpp:175
+CTFactories.createChecks(CTContext.getPointer(), CTChecks);
+for (const auto &Check : CTChecks) {
+  Check->registerPPCallbacks(*Clang);

hokein wrote:
> Maybe add the check names to the `Trace`?
that would be nice, but there's no API to get that info :-(



Comment at: clangd/ClangdUnit.cpp:468
+  X##ModuleAnchorSource
+LINK_TIDY_MODULE(CERT);
+LINK_TIDY_MODULE(Abseil);

hokein wrote:
> I'm curious how much does clangd binary size get increased.
It's now 21M stripped vs 18M before this patch.
The different with debug info is *much* larger for some reason... sadly this 
will hurt link times.


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D54204



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


[PATCH] D54325: [AST] Pack CXXBoolLiteralExpr, CXXNullPtrLiteralExpr and CXXThisExpr

2018-11-09 Thread Bruno Ricci via Phabricator via cfe-commits
riccibruno created this revision.
riccibruno added a reviewer: rsmith.
riccibruno added a project: clang.
Herald added a subscriber: cfe-commits.

Use the newly available space in the bit-fields of `Stmt` to
store some data from `CXXBoolLiteralExpr`, `CXXNullPtrLiteralExpr`
and `CXXThisExpr`.

This cuts the size of each of these classes by 1 pointer.


Repository:
  rC Clang

https://reviews.llvm.org/D54325

Files:
  include/clang/AST/ExprCXX.h
  include/clang/AST/Stmt.h

Index: include/clang/AST/Stmt.h
===
--- include/clang/AST/Stmt.h
+++ include/clang/AST/Stmt.h
@@ -516,18 +516,6 @@
 SourceLocation OpLoc;
   };
 
-  class ExprWithCleanupsBitfields {
-friend class ASTStmtReader; // deserialization
-friend class ExprWithCleanups;
-
-unsigned : NumExprBits;
-
-// When false, it must not have side effects.
-unsigned CleanupsHaveSideEffects : 1;
-
-unsigned NumObjects : 32 - 1 - NumExprBits;
-  };
-
   class ParenListExprBitfields {
 friend class ASTStmtReader;
 friend class ParenListExpr;
@@ -560,14 +548,6 @@
 unsigned IsUnique : 1;
   };
 
-  class ObjCIndirectCopyRestoreExprBitfields {
-friend class ObjCIndirectCopyRestoreExpr;
-
-unsigned : NumExprBits;
-
-unsigned ShouldCopy : 1;
-  };
-
   class InitListExprBitfields {
 friend class InitListExpr;
 
@@ -578,6 +558,44 @@
 unsigned HadArrayRangeDesignator : 1;
   };
 
+  //===--- C++ expression bitfields classes ---===//
+
+  class CXXBoolLiteralExprBitfields {
+friend class ASTStmtReader;
+friend class CXXBoolLiteralExpr;
+
+unsigned : NumExprBits;
+
+/// The value of the boolean literal.
+unsigned Value : 1;
+
+/// The location of the boolean literal.
+SourceLocation Loc;
+  };
+
+  class CXXNullPtrLiteralExprBitfields {
+friend class ASTStmtReader;
+friend class CXXNullPtrLiteralExpr;
+
+unsigned : NumExprBits;
+
+/// The location of the null pointer literal.
+SourceLocation Loc;
+  };
+
+  class CXXThisExprBitfields {
+friend class ASTStmtReader;
+friend class CXXThisExpr;
+
+unsigned : NumExprBits;
+
+/// Whether this is an implicit "this".
+unsigned IsImplicit : 1;
+
+/// The location of the "this".
+SourceLocation Loc;
+  };
+
   class TypeTraitExprBitfields {
 friend class ASTStmtReader;
 friend class ASTStmtWriter;
@@ -596,14 +614,38 @@
 unsigned NumArgs : 32 - 8 - 1 - NumExprBits;
   };
 
+  class ExprWithCleanupsBitfields {
+friend class ASTStmtReader;
+friend class ExprWithCleanups;
+
+unsigned : NumExprBits;
+
+/// When false, it must not have side effects.
+unsigned CleanupsHaveSideEffects : 1;
+
+unsigned NumObjects : 32 - 1 - NumExprBits;
+  };
+
+  //===--- C++ Coroutines TS expressions expression bitfields classes ---===//
+
   class CoawaitExprBitfields {
 friend class CoawaitExpr;
 
 unsigned : NumExprBits;
 
 unsigned IsImplicit : 1;
   };
 
+  //===--- Obj-C Expressions expression bitfields classes ---===//
+
+  class ObjCIndirectCopyRestoreExprBitfields {
+friend class ObjCIndirectCopyRestoreExpr;
+
+unsigned : NumExprBits;
+
+unsigned ShouldCopy : 1;
+  };
+
   union {
 // Statements
 StmtBitfields StmtBits;
@@ -636,14 +678,23 @@
 MemberExprBitfields MemberExprBits;
 CastExprBitfields CastExprBits;
 BinaryOperatorBitfields BinaryOperatorBits;
-ExprWithCleanupsBitfields ExprWithCleanupsBits;
 ParenListExprBitfields ParenListExprBits;
 PseudoObjectExprBitfields PseudoObjectExprBits;
 OpaqueValueExprBitfields OpaqueValueExprBits;
-ObjCIndirectCopyRestoreExprBitfields ObjCIndirectCopyRestoreExprBits;
 InitListExprBitfields InitListExprBits;
+
+// C++ Expressions
+CXXBoolLiteralExprBitfields CXXBoolLiteralExprBits;
+CXXNullPtrLiteralExprBitfields CXXNullPtrLiteralExprBits;
+CXXThisExprBitfields CXXThisExprBits;
 TypeTraitExprBitfields TypeTraitExprBits;
+ExprWithCleanupsBitfields ExprWithCleanupsBits;
+
+// C++ Coroutines TS expressions
 CoawaitExprBitfields CoawaitBits;
+
+// Obj-C Expressions
+ObjCIndirectCopyRestoreExprBitfields ObjCIndirectCopyRestoreExprBits;
   };
 
 public:
Index: include/clang/AST/ExprCXX.h
===
--- include/clang/AST/ExprCXX.h
+++ include/clang/AST/ExprCXX.h
@@ -548,26 +548,25 @@
 
 /// A boolean literal, per ([C++ lex.bool] Boolean literals).
 class CXXBoolLiteralExpr : public Expr {
-  bool Value;
-  SourceLocation Loc;
-
 public:
-  CXXBoolLiteralExpr(bool val, QualType Ty, SourceLocation l)
+  CXXBoolLiteralExpr(bool Val, QualType Ty, SourceLocation Loc)
   : Expr(CXXBoolLiteralExprClass, Ty, VK_RValue, OK_Ordinary, false, false,
- false, false),
-Value(val), Loc(l) {}
+ false, false) {
+CXXBoolLiteralExprBits.Value = Val;
+CXXBoolLiteralExprBits.Loc = Loc;
+  }
 
  

[PATCH] D51554: [CUDA][OPENMP][NVPTX]Improve logic of the debug info support.

2018-11-09 Thread Alexey Bataev via Phabricator via cfe-commits
ABataev added inline comments.



Comment at: lib/Driver/ToolChains/Cuda.cpp:292
+  bool IsDebugEnabled = !A || A->getOption().matches(options::OPT_O0) ||
+Args.hasFlag(options::OPT_cuda_noopt_device_debug,
+ options::OPT_no_cuda_noopt_device_debug,

echristo wrote:
> Is this an nvcc compatibility flag?
No, nvcc uses different set of flags. It uses `-g` for the debug info for the 
host code and `-G` for the device code. I'm not the original author of this 
option. clang uses it to control emission of the debug info for the device.
The bad thing about nvcc that it disables optimizations when `-G` is used. 
Using this option we can use LLVM optimizations and disable the optimizations 
only when we call `ptxas` tool.


Repository:
  rC Clang

https://reviews.llvm.org/D51554



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


[PATCH] D54326: [AST] Pack CXXThrowExpr, CXXDefaultArgExpr and CXXDefaultInitExpr

2018-11-09 Thread Bruno Ricci via Phabricator via cfe-commits
riccibruno created this revision.
riccibruno added a reviewer: rsmith.
riccibruno added a project: clang.
Herald added a subscriber: cfe-commits.
riccibruno added a dependency: D54325: [AST] Pack CXXBoolLiteralExpr, 
CXXNullPtrLiteralExpr and CXXThisExpr.

Use the newly available space in the bit-fields of `Stmt` to store
some data from `CXXThrowExpr`, `CXXDefaultArgExpr`
and `CXXDefaultInitExpr`. This saves 1 pointer for each of these classes.


Repository:
  rC Clang

https://reviews.llvm.org/D54326

Files:
  include/clang/AST/ExprCXX.h
  include/clang/AST/Stmt.h
  lib/AST/ExprCXX.cpp
  lib/Serialization/ASTReaderStmt.cpp

Index: lib/Serialization/ASTReaderStmt.cpp
===
--- lib/Serialization/ASTReaderStmt.cpp
+++ lib/Serialization/ASTReaderStmt.cpp
@@ -1480,21 +1480,21 @@
 
 void ASTStmtReader::VisitCXXThrowExpr(CXXThrowExpr *E) {
   VisitExpr(E);
-  E->ThrowLoc = ReadSourceLocation();
-  E->Op = Record.readSubExpr();
-  E->IsThrownVariableInScope = Record.readInt();
+  E->CXXThrowExprBits.ThrowLoc = ReadSourceLocation();
+  E->ThrowExpr = Record.readSubExpr();
+  E->CXXThrowExprBits.IsThrownVariableInScope = Record.readInt();
 }
 
 void ASTStmtReader::VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) {
   VisitExpr(E);
   E->Param = ReadDeclAs();
-  E->Loc = ReadSourceLocation();
+  E->CXXDefaultArgExprBits.Loc = ReadSourceLocation();
 }
 
 void ASTStmtReader::VisitCXXDefaultInitExpr(CXXDefaultInitExpr *E) {
   VisitExpr(E);
   E->Field = ReadDeclAs();
-  E->Loc = ReadSourceLocation();
+  E->CXXDefaultInitExprBits.Loc = ReadSourceLocation();
 }
 
 void ASTStmtReader::VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) {
Index: lib/AST/ExprCXX.cpp
===
--- lib/AST/ExprCXX.cpp
+++ lib/AST/ExprCXX.cpp
@@ -749,14 +749,15 @@
   return cast(getCalleeDecl())->getLiteralIdentifier();
 }
 
-CXXDefaultInitExpr::CXXDefaultInitExpr(const ASTContext &C, SourceLocation Loc,
-   FieldDecl *Field, QualType T)
-: Expr(CXXDefaultInitExprClass, T.getNonLValueExprType(C),
-   T->isLValueReferenceType() ? VK_LValue : T->isRValueReferenceType()
+CXXDefaultInitExpr::CXXDefaultInitExpr(const ASTContext &Ctx, SourceLocation Loc,
+   FieldDecl *Field, QualType Ty)
+: Expr(CXXDefaultInitExprClass, Ty.getNonLValueExprType(Ctx),
+   Ty->isLValueReferenceType() ? VK_LValue : Ty->isRValueReferenceType()
 ? VK_XValue
 : VK_RValue,
/*FIXME*/ OK_Ordinary, false, false, false, false),
-  Field(Field), Loc(Loc) {
+  Field(Field) {
+  CXXDefaultInitExprBits.Loc = Loc;
   assert(Field->hasInClassInitializer());
 }
 
Index: include/clang/AST/Stmt.h
===
--- include/clang/AST/Stmt.h
+++ include/clang/AST/Stmt.h
@@ -596,6 +596,39 @@
 SourceLocation Loc;
   };
 
+  class CXXThrowExprBitfields {
+friend class ASTStmtReader;
+friend class CXXThrowExpr;
+
+unsigned : NumExprBits;
+
+/// Whether the thrown variable (if any) is in scope.
+unsigned IsThrownVariableInScope : 1;
+
+/// The location of the "throw".
+SourceLocation ThrowLoc;
+  };
+
+  class CXXDefaultArgExprBitfields {
+friend class ASTStmtReader;
+friend class CXXDefaultArgExpr;
+
+unsigned : NumExprBits;
+
+/// The location where the default argument expression was used.
+SourceLocation Loc;
+  };
+
+  class CXXDefaultInitExprBitfields {
+friend class ASTStmtReader;
+friend class CXXDefaultInitExpr;
+
+unsigned : NumExprBits;
+
+/// The location where the default initializer expression was used.
+SourceLocation Loc;
+  };
+
   class TypeTraitExprBitfields {
 friend class ASTStmtReader;
 friend class ASTStmtWriter;
@@ -687,6 +720,9 @@
 CXXBoolLiteralExprBitfields CXXBoolLiteralExprBits;
 CXXNullPtrLiteralExprBitfields CXXNullPtrLiteralExprBits;
 CXXThisExprBitfields CXXThisExprBits;
+CXXThrowExprBitfields CXXThrowExprBits;
+CXXDefaultArgExprBitfields CXXDefaultArgExprBits;
+CXXDefaultInitExprBitfields CXXDefaultInitExprBits;
 TypeTraitExprBitfields TypeTraitExprBits;
 ExprWithCleanupsBitfields ExprWithCleanupsBits;
 
Index: include/clang/AST/ExprCXX.h
===
--- include/clang/AST/ExprCXX.h
+++ include/clang/AST/ExprCXX.h
@@ -1003,42 +1003,43 @@
 class CXXThrowExpr : public Expr {
   friend class ASTStmtReader;
 
-  Stmt *Op;
-  SourceLocation ThrowLoc;
-
-  /// Whether the thrown variable (if any) is in scope.
-  unsigned IsThrownVariableInScope : 1;
+  /// The optional expression in the throw statement.
+  Stmt *ThrowExpr;
 
 public:
   // \p Ty is the void type which is used as the result type of the
-  // expr

r346520 - Use the correct address space when emitting the ctor function list

2018-11-09 Thread Dylan McKay via cfe-commits
Author: dylanmckay
Date: Fri Nov  9 09:15:06 2018
New Revision: 346520

URL: http://llvm.org/viewvc/llvm-project?rev=346520&view=rev
Log:
Use the correct address space when emitting the ctor function list

This patch modifies clang so that, if compiling for a target that
explicitly specifies a nonzero program memory address space, the
constructor list global will have the same address space as the
functions it contains.

AVR is the only in-tree backend which has a nonzero program memory
address space.

Without this, the IR verifier would always fail if a constructor
was used on a Harvard architecture backend.

This has no functional change to any in-tree backends except AVR.

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

Modified: cfe/trunk/lib/CodeGen/CodeGenModule.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/CodeGen/CodeGenModule.cpp?rev=346520&r1=346519&r2=346520&view=diff
==
--- cfe/trunk/lib/CodeGen/CodeGenModule.cpp (original)
+++ cfe/trunk/lib/CodeGen/CodeGenModule.cpp Fri Nov  9 09:15:06 2018
@@ -1105,11 +1105,12 @@ void CodeGenModule::EmitCtorList(CtorLis
 
   // Ctor function type is void()*.
   llvm::FunctionType* CtorFTy = llvm::FunctionType::get(VoidTy, false);
-  llvm::Type *CtorPFTy = llvm::PointerType::getUnqual(CtorFTy);
+  llvm::Type *CtorPFTy = llvm::PointerType::get(CtorFTy,
+  TheModule.getDataLayout().getProgramAddressSpace());
 
   // Get the type of a ctor entry, { i32, void ()*, i8* }.
   llvm::StructType *CtorStructTy = llvm::StructType::get(
-  Int32Ty, llvm::PointerType::getUnqual(CtorFTy), VoidPtrTy);
+  Int32Ty, CtorPFTy, VoidPtrTy);
 
   // Construct the constructor and destructor arrays.
   ConstantInitBuilder builder(*this);


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


r346521 - Introduce the _Clang scoped attribute token.

2018-11-09 Thread Aaron Ballman via cfe-commits
Author: aaronballman
Date: Fri Nov  9 09:19:45 2018
New Revision: 346521

URL: http://llvm.org/viewvc/llvm-project?rev=346521&view=rev
Log:
Introduce the _Clang scoped attribute token.

Currently, we only accept clang as the scoped attribute identifier for double 
square bracket attributes provided by Clang, but this has the potential to 
conflict with user-defined macros. To help alleviate these concerns, this 
introduces the _Clang scoped attribute identifier as an alias for clang. It 
also introduces a warning with a fixit on the off chance someone attempts to 
use __clang__ as the scoped attribute (which is a predefined compiler 
identification macro).

Modified:
cfe/trunk/include/clang/Basic/DiagnosticParseKinds.td
cfe/trunk/lib/Basic/Attributes.cpp
cfe/trunk/lib/Parse/ParseDeclCXX.cpp
cfe/trunk/lib/Sema/ParsedAttr.cpp
cfe/trunk/test/FixIt/fixit-cxx11-attributes.cpp
cfe/trunk/test/Parser/cxx0x-attributes.cpp
cfe/trunk/test/Preprocessor/has_attribute.cpp
cfe/trunk/test/SemaCXX/attr-optnone.cpp

Modified: cfe/trunk/include/clang/Basic/DiagnosticParseKinds.td
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Basic/DiagnosticParseKinds.td?rev=346521&r1=346520&r2=346521&view=diff
==
--- cfe/trunk/include/clang/Basic/DiagnosticParseKinds.td (original)
+++ cfe/trunk/include/clang/Basic/DiagnosticParseKinds.td Fri Nov  9 09:19:45 
2018
@@ -575,6 +575,9 @@ def warn_cxx98_compat_noexcept_expr : Wa
 def warn_cxx98_compat_nullptr : Warning<
   "'nullptr' is incompatible with C++98">, InGroup, DefaultIgnore;
 
+def warn_wrong_clang_attr_namespace : Warning<
+  "'__clang__' is a predefined macro name, not an attribute scope specifier; "
+  "did you mean '_Clang' instead?">, InGroup;
 def ext_ns_enum_attribute : Extension<
   "attributes on %select{a namespace|an enumerator}0 declaration are "
   "a C++17 extension">, InGroup;

Modified: cfe/trunk/lib/Basic/Attributes.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Basic/Attributes.cpp?rev=346521&r1=346520&r2=346521&view=diff
==
--- cfe/trunk/lib/Basic/Attributes.cpp (original)
+++ cfe/trunk/lib/Basic/Attributes.cpp Fri Nov  9 09:19:45 2018
@@ -9,16 +9,18 @@ int clang::hasAttribute(AttrSyntax Synta
 const LangOptions &LangOpts) {
   StringRef Name = Attr->getName();
   // Normalize the attribute name, __foo__ becomes foo.
-  if (Name.size() >= 4 && Name.startswith("__") && Name.endswith("__"))
-Name = Name.substr(2, Name.size() - 4);
-
-  // Normalize the scope name, but only for gnu attributes.
-  StringRef ScopeName = Scope ? Scope->getName() : "";
-  if (ScopeName == "__gnu__")
-ScopeName = ScopeName.slice(2, ScopeName.size() - 2);
-
-#include "clang/Basic/AttrHasAttributeImpl.inc"
-
+  if (Name.size() >= 4 && Name.startswith("__") && Name.endswith("__"))
+Name = Name.substr(2, Name.size() - 4);
+
+  // Normalize the scope name, but only for gnu and clang attributes.
+  StringRef ScopeName = Scope ? Scope->getName() : "";
+  if (ScopeName == "__gnu__")
+ScopeName = "gnu";
+  else if (ScopeName == "_Clang")
+ScopeName = "clang";
+
+#include "clang/Basic/AttrHasAttributeImpl.inc"
+
   return 0;
 }
 

Modified: cfe/trunk/lib/Parse/ParseDeclCXX.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Parse/ParseDeclCXX.cpp?rev=346521&r1=346520&r2=346521&view=diff
==
--- cfe/trunk/lib/Parse/ParseDeclCXX.cpp (original)
+++ cfe/trunk/lib/Parse/ParseDeclCXX.cpp Fri Nov  9 09:19:45 2018
@@ -3790,6 +3790,28 @@ IdentifierInfo *Parser::TryParseCXX11Att
 }
 return nullptr;
 
+  case tok::numeric_constant: {
+// If we got a numeric constant, check to see if it comes from a macro that
+// corresponds to the predefined __clang__ macro. If it does, warn the user
+// and recover by pretending they said _Clang instead.
+if (Tok.getLocation().isMacroID()) {
+  SmallString<8> ExpansionBuf;
+  SourceLocation ExpansionLoc =
+  PP.getSourceManager().getExpansionLoc(Tok.getLocation());
+  StringRef Spelling = PP.getSpelling(ExpansionLoc, ExpansionBuf);
+  if (Spelling == "__clang__") {
+SourceRange TokRange(
+ExpansionLoc,
+PP.getSourceManager().getExpansionLoc(Tok.getEndLoc()));
+Diag(Tok, diag::warn_wrong_clang_attr_namespace)
+<< FixItHint::CreateReplacement(TokRange, "_Clang");
+Loc = ConsumeToken();
+return &PP.getIdentifierTable().get("_Clang");
+  }
+}
+return nullptr;
+  }
+
   case tok::ampamp:   // 'and'
   case tok::pipe: // 'bitor'
   case tok::pipepipe: // 'or'
@@ -3865,24 +3887,22 @@ bool Parser::ParseCXX11AttributeArgs(Ide
 // Eat the left paren, then skip to the ending right paren.
 ConsumePare

[PATCH] D53700: Support _Clang as a scoped attribute identifier

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

Thanks for the reviews -- I've commit in r346521.


https://reviews.llvm.org/D53700



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


[PATCH] D54310: Make clang-based tools find libc++ on MacOS

2018-11-09 Thread Ilya Biryukov via Phabricator via cfe-commits
ilya-biryukov updated this revision to Diff 173364.
ilya-biryukov marked 2 inline comments as done.
ilya-biryukov added a comment.

- Update the comment.


Repository:
  rC Clang

https://reviews.llvm.org/D54310

Files:
  include/clang/Lex/HeaderSearchOptions.h
  lib/Frontend/CreateInvocationFromCommandLine.cpp
  lib/Frontend/InitHeaderSearch.cpp
  lib/Tooling/Tooling.cpp
  test/Tooling/Inputs/mock-libcxx/include/c++/v1/mock_vector
  test/Tooling/clang-check-mac-libcxx.cpp

Index: test/Tooling/clang-check-mac-libcxx.cpp
===
--- /dev/null
+++ test/Tooling/clang-check-mac-libcxx.cpp
@@ -0,0 +1,16 @@
+// Clang on MacOS can find libc++ living beside the installed compiler.
+// This test makes sure our libTooling-based tools emulate this properly.
+//
+// RUN: rm -rf %t
+// RUN: mkdir %t
+//
+// Install the mock libc++ (simulates the libc++ directory structure).
+// RUN: cp -r %S/Inputs/mock-libcxx %t/
+//
+// Pretend clang is installed beside the mock library that we provided.
+// RUN: echo '[{"directory":"%t","command":"%t/mock-libcxx/bin/clang++ -stdlib=libc++ -target x86_64-apple-darwin -c test.cpp","file":"test.cpp"}]' | sed -e 's/\\/\//g' > %t/compile_commands.json
+// RUN: cp "%s" "%t/test.cpp"
+// RUN: clang-check -p "%t" "%t/test.cpp"
+
+#include 
+vector v;
Index: test/Tooling/Inputs/mock-libcxx/include/c++/v1/mock_vector
===
--- /dev/null
+++ test/Tooling/Inputs/mock-libcxx/include/c++/v1/mock_vector
@@ -0,0 +1 @@
+class vector {};
Index: lib/Tooling/Tooling.cpp
===
--- lib/Tooling/Tooling.cpp
+++ lib/Tooling/Tooling.cpp
@@ -323,6 +323,9 @@
 Invocation->getPreprocessorOpts().addRemappedFile(It.getKey(),
   Input.release());
   }
+  // Patch up the install dir, so we find the same standard library as the
+  // original compiler on MacOS.
+  Invocation->getHeaderSearchOpts().InstallDir = Driver->getInstalledDir();
   return runInvocation(BinaryName, Compilation.get(), std::move(Invocation),
std::move(PCHContainerOps));
 }
Index: lib/Frontend/InitHeaderSearch.cpp
===
--- lib/Frontend/InitHeaderSearch.cpp
+++ lib/Frontend/InitHeaderSearch.cpp
@@ -476,14 +476,9 @@
   if (triple.isOSDarwin()) {
 // On Darwin, libc++ may be installed alongside the compiler in
 // include/c++/v1.
-if (!HSOpts.ResourceDir.empty()) {
-  // Remove version from foo/lib/clang/version
-  StringRef NoVer = llvm::sys::path::parent_path(HSOpts.ResourceDir);
-  // Remove clang from foo/lib/clang
-  StringRef Lib = llvm::sys::path::parent_path(NoVer);
-  // Remove lib from foo/lib
-  SmallString<128> P = llvm::sys::path::parent_path(Lib);
-
+if (!HSOpts.InstallDir.empty()) {
+  // Get from foo/bin to foo.
+  SmallString<128> P(llvm::sys::path::parent_path(HSOpts.InstallDir));
   // Get foo/include/c++/v1
   llvm::sys::path::append(P, "include", "c++", "v1");
   AddUnmappedPath(P, CXXSystem, false);
Index: lib/Frontend/CreateInvocationFromCommandLine.cpp
===
--- lib/Frontend/CreateInvocationFromCommandLine.cpp
+++ lib/Frontend/CreateInvocationFromCommandLine.cpp
@@ -11,17 +11,18 @@
 //
 //===--===//
 
-#include "clang/Frontend/Utils.h"
 #include "clang/Basic/DiagnosticOptions.h"
+#include "clang/Driver/Action.h"
 #include "clang/Driver/Compilation.h"
 #include "clang/Driver/Driver.h"
-#include "clang/Driver/Action.h"
 #include "clang/Driver/Options.h"
 #include "clang/Driver/Tool.h"
 #include "clang/Frontend/CompilerInstance.h"
 #include "clang/Frontend/FrontendDiagnostic.h"
+#include "clang/Frontend/Utils.h"
 #include "llvm/Option/ArgList.h"
 #include "llvm/Support/Host.h"
+#include "llvm/Support/Path.h"
 using namespace clang;
 using namespace llvm::opt;
 
@@ -102,5 +103,8 @@
  CCArgs.size(),
  *Diags))
 return nullptr;
+  // Patch up the install dir, so we find the same standard library as the
+  // original compiler on MacOS.
+  CI->getHeaderSearchOpts().InstallDir = TheDriver.getInstalledDir();
   return CI;
 }
Index: include/clang/Lex/HeaderSearchOptions.h
===
--- include/clang/Lex/HeaderSearchOptions.h
+++ include/clang/Lex/HeaderSearchOptions.h
@@ -108,6 +108,13 @@
   /// etc.).
   std::string ResourceDir;
 
+  /// Compiler install dir as detected by the Driver.
+  /// This is typically the directory that contains the clang executable, i.e.
+  /// the 'bin/' subdir of a clang distribution.
+  /// Only used to a

[PATCH] D54310: Make clang-based tools find libc++ on MacOS

2018-11-09 Thread Ilya Biryukov via Phabricator via cfe-commits
ilya-biryukov added a comment.

In https://reviews.llvm.org/D54310#1292924, @sammccall wrote:

> If you know of a good reviewer for this, you may want a second opinion!


This would definitely be nice, but I also don't know who'd be the proper person 
to review this.
I'll take a pause until Monday, maybe @arphaman or someone else from the 
community can suggest a better way of fixing this or proper reviewers for this 
change.




Comment at: include/clang/Lex/HeaderSearchOptions.h:111
 
+  /// Compiler install dir as detected by the Driver.
+  /// Only used to add include dirs for libc++ on Darwin. Please avoid relying

sammccall wrote:
> Could you add "typically contains bin/clang, lib/libclang_rt, and 
> include/"?
This is actually the 'bin' subdirectory, I've added a comment about that but 
you see a better way to communicate this, please let me know! E.g. actually 
mentioning the parallel lib/ and include/ subdirs. 



Comment at: lib/Frontend/CompilerInvocation.cpp:1776
   Opts.ResourceDir = Args.getLastArgValue(OPT_resource_dir);
+  Opts.InstallDir = Opts.ResourceDir;
 

sammccall wrote:
> (is this needed? I guess you fall back to this if you don't create the CI 
> from the command line?)
Thanks for noticing this!
This is a leftover from a previous iteration, it's actually incorrect now since 
we rely on `InstallDir` pointing to a different place from the resource dir.
Removed it.


Repository:
  rC Clang

https://reviews.llvm.org/D54310



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


[clang-tools-extra] r346524 - [clangd] Fix clang-tidy warnings.

2018-11-09 Thread Kadir Cetinkaya via cfe-commits
Author: kadircet
Date: Fri Nov  9 09:33:48 2018
New Revision: 346524

URL: http://llvm.org/viewvc/llvm-project?rev=346524&view=rev
Log:
[clangd] Fix clang-tidy warnings.

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

Modified: clang-tools-extra/trunk/unittests/clangd/TestTU.cpp
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/unittests/clangd/TestTU.cpp?rev=346524&r1=346523&r2=346524&view=diff
==
--- clang-tools-extra/trunk/unittests/clangd/TestTU.cpp (original)
+++ clang-tools-extra/trunk/unittests/clangd/TestTU.cpp Fri Nov  9 09:33:48 2018
@@ -41,7 +41,7 @@ ParsedAST TestTU::build() const {
   auto Preamble =
   buildPreamble(FullFilename, *createInvocationFromCommandLine(Cmd),
 /*OldPreamble=*/nullptr,
-/*OldCommand=*/Inputs.CompileCommand, Inputs, PCHs,
+/*OldCompileCommand=*/Inputs.CompileCommand, Inputs, PCHs,
 /*StoreInMemory=*/true, /*PreambleCallback=*/nullptr);
   auto AST = buildAST(FullFilename, createInvocationFromCommandLine(Cmd),
   Inputs, Preamble, PCHs);
@@ -109,17 +109,17 @@ const NamedDecl &findDecl(ParsedAST &AST
 }
 
 const NamedDecl &findDecl(ParsedAST &AST,
-  std::function Callback) {
+  std::function Filter) {
   struct Visitor : RecursiveASTVisitor {
-decltype(Callback) CB;
+decltype(Filter) F;
 SmallVector Decls;
 bool VisitNamedDecl(const NamedDecl *ND) {
-  if (CB(*ND))
+  if (F(*ND))
 Decls.push_back(ND);
   return true;
 }
   } Visitor;
-  Visitor.CB = Callback;
+  Visitor.F = Filter;
   Visitor.TraverseDecl(AST.getASTContext().getTranslationUnitDecl());
   if (Visitor.Decls.size() != 1) {
 ADD_FAILURE() << Visitor.Decls.size() << " symbols matched.";


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


[PATCH] D53764: [OpenCL] Enable address spaces for references in C++

2018-11-09 Thread John McCall via Phabricator via cfe-commits
rjmccall added inline comments.



Comment at: lib/AST/Expr.cpp:1609
   case CK_AddressSpaceConversion:
-assert(getType()->isPointerType() || getType()->isBlockPointerType());
-assert(getSubExpr()->getType()->isPointerType() ||
-   getSubExpr()->getType()->isBlockPointerType());
-assert(getType()->getPointeeType().getAddressSpace() !=
-   getSubExpr()->getType()->getPointeeType().getAddressSpace());
-LLVM_FALLTHROUGH;
+assert(/*If pointer type then addr spaces for pointees must differ*/
+   (((getType()->isPointerType() &&

rjmccall wrote:
> rjmccall wrote:
> > Anastasia wrote:
> > > I don't like this assert now. Would adding extra variable be cleaner here?
> > Yeah, this assertion doesn't make any sense like this.  It should be 
> > checking whether the cast is a gl-value and, if so, requiring the 
> > subexpression to also be a gl-value and then asserting the difference 
> > between the type.  But you can certainly do an address-space conversion on 
> > l-values that just happen to be of pointer or block-pointer type.
> No, if this is a gl-value cast, the assertion must ignore whether there's a 
> pointee type, or it will be messed up on gl-values of pointer types.
> 
> That is, if I have a gl-value of type `char * __private`, I should be able to 
> do an address-space promotion to get a gl-value of type `char * __generic`.  
> It's okay that the pointers are into the same address space here — in fact, 
> it's more than okay, it's necessary.
Thanks, that's right now.  Although please assert that the base has the same 
value kind; I've seen bugs before where ICEs tried to implicitly materialize 
their arguments, and it's really frustrating to root out.



Comment at: lib/Sema/SemaExprCXX.cpp:4285
+? CK_AddressSpaceConversion
+: CK_NoOp;
+

If `ToType` is a reference type, the address space will be on its pointee type.


https://reviews.llvm.org/D53764



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


[PATCH] D54330: Driver: Make -fsanitize=shadow-call-stack compatible with -fsanitize-minimal-runtime.

2018-11-09 Thread Peter Collingbourne via Phabricator via cfe-commits
pcc created this revision.
pcc added a reviewer: eugenis.
Herald added subscribers: llvm-commits, cryptoad.

Repository:
  rL LLVM

https://reviews.llvm.org/D54330

Files:
  clang/lib/Driver/SanitizerArgs.cpp
  clang/test/Driver/fsanitize.c


Index: clang/test/Driver/fsanitize.c
===
--- clang/test/Driver/fsanitize.c
+++ clang/test/Driver/fsanitize.c
@@ -767,6 +767,10 @@
 // CHECK-CFI-NOICALL-MINIMAL: 
"-fsanitize-trap=cfi-derived-cast,cfi-mfcall,cfi-unrelated-cast,cfi-nvcall,cfi-vcall"
 // CHECK-CFI-NOICALL-MINIMAL: "-fsanitize-minimal-runtime"
 
+// RUN: %clang -target x86_64-linux-gnu -fsanitize=shadow-call-stack 
-fsanitize-minimal-runtime %s -### 2>&1 | FileCheck %s 
--check-prefix=CHECK-SCS-MINIMAL
+// CHECK-SCS-MINIMAL: "-fsanitize=shadow-call-stack"
+// CHECK-SCS-MINIMAL: "-fsanitize-minimal-runtime"
+
 // RUN: %clang -target aarch64-linux-gnu -fsanitize=scudo %s -### 2>&1 | 
FileCheck %s --check-prefix=CHECK-SCUDO
 // RUN: %clang -target arm-linux-androideabi -fsanitize=scudo %s -### 2>&1 | 
FileCheck %s --check-prefix=CHECK-SCUDO
 // RUN: %clang -target x86_64-linux-gnu -fsanitize=scudo %s -### 2>&1 | 
FileCheck %s --check-prefix=CHECK-SCUDO
Index: clang/lib/Driver/SanitizerArgs.cpp
===
--- clang/lib/Driver/SanitizerArgs.cpp
+++ clang/lib/Driver/SanitizerArgs.cpp
@@ -47,7 +47,7 @@
   TrappingDefault = CFI,
   CFIClasses =
   CFIVCall | CFINVCall | CFIMFCall | CFIDerivedCast | CFIUnrelatedCast,
-  CompatibleWithMinimalRuntime = TrappingSupported | Scudo,
+  CompatibleWithMinimalRuntime = TrappingSupported | Scudo | ShadowCallStack,
 };
 
 enum CoverageFeature {


Index: clang/test/Driver/fsanitize.c
===
--- clang/test/Driver/fsanitize.c
+++ clang/test/Driver/fsanitize.c
@@ -767,6 +767,10 @@
 // CHECK-CFI-NOICALL-MINIMAL: "-fsanitize-trap=cfi-derived-cast,cfi-mfcall,cfi-unrelated-cast,cfi-nvcall,cfi-vcall"
 // CHECK-CFI-NOICALL-MINIMAL: "-fsanitize-minimal-runtime"
 
+// RUN: %clang -target x86_64-linux-gnu -fsanitize=shadow-call-stack -fsanitize-minimal-runtime %s -### 2>&1 | FileCheck %s --check-prefix=CHECK-SCS-MINIMAL
+// CHECK-SCS-MINIMAL: "-fsanitize=shadow-call-stack"
+// CHECK-SCS-MINIMAL: "-fsanitize-minimal-runtime"
+
 // RUN: %clang -target aarch64-linux-gnu -fsanitize=scudo %s -### 2>&1 | FileCheck %s --check-prefix=CHECK-SCUDO
 // RUN: %clang -target arm-linux-androideabi -fsanitize=scudo %s -### 2>&1 | FileCheck %s --check-prefix=CHECK-SCUDO
 // RUN: %clang -target x86_64-linux-gnu -fsanitize=scudo %s -### 2>&1 | FileCheck %s --check-prefix=CHECK-SCUDO
Index: clang/lib/Driver/SanitizerArgs.cpp
===
--- clang/lib/Driver/SanitizerArgs.cpp
+++ clang/lib/Driver/SanitizerArgs.cpp
@@ -47,7 +47,7 @@
   TrappingDefault = CFI,
   CFIClasses =
   CFIVCall | CFINVCall | CFIMFCall | CFIDerivedCast | CFIUnrelatedCast,
-  CompatibleWithMinimalRuntime = TrappingSupported | Scudo,
+  CompatibleWithMinimalRuntime = TrappingSupported | Scudo | ShadowCallStack,
 };
 
 enum CoverageFeature {
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D52674: [AST] Add Obj-C discriminator to MS ABI RTTI

2018-11-09 Thread John McCall via Phabricator via cfe-commits
rjmccall added a comment.

In https://reviews.llvm.org/D52674#1291284, @smeenai wrote:

> In https://reviews.llvm.org/D52674#1281747, @rjmccall wrote:
>
> > In https://reviews.llvm.org/D52674#1271814, @smeenai wrote:
> >
> > > @rjmccall I prototyped the ForRTTI parameter approach in 
> > > https://reviews.llvm.org/D53546. It could definitely be cleaned up a bit, 
> > > but it demonstrates the problems I saw with the added parameter. Namely, 
> > > `mangleType(QualType, SourceRange, QualifierMangleMode)` has a bunch of 
> > > additional logic which is needed for correctness, so we need to thread 
> > > the parameter through the entire chain, and the only way I could think of 
> > > doing that without adding the parameter to every single `mangleType` 
> > > overload was to have an additional switch to dispatch to the overloads 
> > > with the added ForRTTI parameter, which is pretty ugly.
> > >
> > > As I see it, there are a few ways to proceed here:
> > >
> > > - The approach in https://reviews.llvm.org/D53546 (cleaned up a bit). I 
> > > think it's pretty ugly, but you may have suggestions on how to do it 
> > > better.
> > > - In the `mangleType` overload for `ObjCObjectPointerType`, skipping the 
> > > generic `mangleType` dispatch and going directly to either the 
> > > `ObjCObjectType` or `ObjCInterfaceType` overloads. That avoids the 
> > > ugliness in the generic `mangleType`, but it also requires us to 
> > > duplicate some logic from it in the `ObjCObjectPointerType` overload, 
> > > which doesn't seem great either.
> > > - Maintaining `ForRTTI` state in the mangler instead of threading a 
> > > parameter through (I'm generally not a fan of state like that, but it 
> > > might be cleaner than the threading in this case?)
> > > - Just sticking with what I'm doing in this patch.
> > >
> > >   What do you think?
> >
> >
> > Sorry for the delay.  I think duplicating the dispatch logic for 
> > `ObjCObjectPointerType` is probably the best approach; the pointee type 
> > will always an `ObjCObjectType` of some sort, and there are only two kinds 
> > of those.
>
>
> Sorry, I'm still not sure how this will work.
>
> Duplicating the dispatch logic for `ObjCObjectPointerType` ends up looking 
> like https://reviews.llvm.org/P8114, which is fine. However, when we're 
> actually mangling RTTI or RTTI names, we're still going through the main 
> `mangleType(QualType, SourceRange, QualifierMangleMode)` overload, which 
> still requires us to thread `ForRTTI` through that function, which still 
> requires us to duplicate the switch in that function (to handle the `ForRTTI` 
> case, since the other switch is generated via TypeNodes.def and not easily 
> modifiable), which is the main ugliness in my opinion. Do you also want me to 
> add special dispatching to `mangleCXXRTTI` and `mangleCXXRTTIName` to just 
> call the `ObjCObjectPointerType` function directly when they're dealing with 
> that type? That's certainly doable, but at that point just keeping some state 
> around in the demangler starts to feel cleaner, at least to me.


Well, you could check for an `ObjCObjectPointerType` in the top-level routine.

But yeah, probably the cleanest thing to do would to be push the state through 
the main dispatch.  Don't push a single `bool` through, though; make a 
`TypeManglingOptions` struct to encapsulate it, in case we have a similar 
problem elsewhere.  It should have a method for getting options that should be 
propagated down to component type manglings, and that method can drop the "for 
RTTI" bit; that's the part that `ObjCObjectPointerType` can handle differently.


Repository:
  rC Clang

https://reviews.llvm.org/D52674



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


[PATCH] D54258: [Clang] Fix pretty printing of CUDA address spaces

2018-11-09 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman added a comment.

In https://reviews.llvm.org/D54258#1292129, @richardmembarth wrote:

> I think it's not so easy to provide such tests for CUDA.
>  CUDA memory space specifiers are implemented via attributes, e.g. `#define 
> __shared__ __attribute__((shared))`.
>  As a result of this, they are pretty-printed via a different code path.
>  In my example, I call `Ctx.getAddrSpaceQualType(QT, LangAS::cuda_shared)`, 
> which is then pretty-printed via the code above.
>  Any hints how to provide tests for this one?


If there's no way to trigger a different spelling that a user would see, why is 
this change needed?


Repository:
  rC Clang

https://reviews.llvm.org/D54258



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


[PATCH] D54330: Driver: Make -fsanitize=shadow-call-stack compatible with -fsanitize-minimal-runtime.

2018-11-09 Thread Evgenii Stepanov via Phabricator via cfe-commits
eugenis accepted this revision.
eugenis added a comment.
This revision is now accepted and ready to land.

LGTM


Repository:
  rL LLVM

https://reviews.llvm.org/D54330



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


[PATCH] D54330: Driver: Make -fsanitize=shadow-call-stack compatible with -fsanitize-minimal-runtime.

2018-11-09 Thread Peter Collingbourne via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rL346526: Driver: Make -fsanitize=shadow-call-stack compatible 
with -fsanitize-minimal… (authored by pcc, committed by ).

Changed prior to commit:
  https://reviews.llvm.org/D54330?vs=173367&id=173368#toc

Repository:
  rL LLVM

https://reviews.llvm.org/D54330

Files:
  cfe/trunk/lib/Driver/SanitizerArgs.cpp
  cfe/trunk/test/Driver/fsanitize.c


Index: cfe/trunk/lib/Driver/SanitizerArgs.cpp
===
--- cfe/trunk/lib/Driver/SanitizerArgs.cpp
+++ cfe/trunk/lib/Driver/SanitizerArgs.cpp
@@ -47,7 +47,7 @@
   TrappingDefault = CFI,
   CFIClasses =
   CFIVCall | CFINVCall | CFIMFCall | CFIDerivedCast | CFIUnrelatedCast,
-  CompatibleWithMinimalRuntime = TrappingSupported | Scudo,
+  CompatibleWithMinimalRuntime = TrappingSupported | Scudo | ShadowCallStack,
 };
 
 enum CoverageFeature {
Index: cfe/trunk/test/Driver/fsanitize.c
===
--- cfe/trunk/test/Driver/fsanitize.c
+++ cfe/trunk/test/Driver/fsanitize.c
@@ -767,6 +767,10 @@
 // CHECK-CFI-NOICALL-MINIMAL: 
"-fsanitize-trap=cfi-derived-cast,cfi-mfcall,cfi-unrelated-cast,cfi-nvcall,cfi-vcall"
 // CHECK-CFI-NOICALL-MINIMAL: "-fsanitize-minimal-runtime"
 
+// RUN: %clang -target x86_64-linux-gnu -fsanitize=shadow-call-stack 
-fsanitize-minimal-runtime %s -### 2>&1 | FileCheck %s 
--check-prefix=CHECK-SCS-MINIMAL
+// CHECK-SCS-MINIMAL: "-fsanitize=shadow-call-stack"
+// CHECK-SCS-MINIMAL: "-fsanitize-minimal-runtime"
+
 // RUN: %clang -target aarch64-linux-gnu -fsanitize=scudo %s -### 2>&1 | 
FileCheck %s --check-prefix=CHECK-SCUDO
 // RUN: %clang -target arm-linux-androideabi -fsanitize=scudo %s -### 2>&1 | 
FileCheck %s --check-prefix=CHECK-SCUDO
 // RUN: %clang -target x86_64-linux-gnu -fsanitize=scudo %s -### 2>&1 | 
FileCheck %s --check-prefix=CHECK-SCUDO


Index: cfe/trunk/lib/Driver/SanitizerArgs.cpp
===
--- cfe/trunk/lib/Driver/SanitizerArgs.cpp
+++ cfe/trunk/lib/Driver/SanitizerArgs.cpp
@@ -47,7 +47,7 @@
   TrappingDefault = CFI,
   CFIClasses =
   CFIVCall | CFINVCall | CFIMFCall | CFIDerivedCast | CFIUnrelatedCast,
-  CompatibleWithMinimalRuntime = TrappingSupported | Scudo,
+  CompatibleWithMinimalRuntime = TrappingSupported | Scudo | ShadowCallStack,
 };
 
 enum CoverageFeature {
Index: cfe/trunk/test/Driver/fsanitize.c
===
--- cfe/trunk/test/Driver/fsanitize.c
+++ cfe/trunk/test/Driver/fsanitize.c
@@ -767,6 +767,10 @@
 // CHECK-CFI-NOICALL-MINIMAL: "-fsanitize-trap=cfi-derived-cast,cfi-mfcall,cfi-unrelated-cast,cfi-nvcall,cfi-vcall"
 // CHECK-CFI-NOICALL-MINIMAL: "-fsanitize-minimal-runtime"
 
+// RUN: %clang -target x86_64-linux-gnu -fsanitize=shadow-call-stack -fsanitize-minimal-runtime %s -### 2>&1 | FileCheck %s --check-prefix=CHECK-SCS-MINIMAL
+// CHECK-SCS-MINIMAL: "-fsanitize=shadow-call-stack"
+// CHECK-SCS-MINIMAL: "-fsanitize-minimal-runtime"
+
 // RUN: %clang -target aarch64-linux-gnu -fsanitize=scudo %s -### 2>&1 | FileCheck %s --check-prefix=CHECK-SCUDO
 // RUN: %clang -target arm-linux-androideabi -fsanitize=scudo %s -### 2>&1 | FileCheck %s --check-prefix=CHECK-SCUDO
 // RUN: %clang -target x86_64-linux-gnu -fsanitize=scudo %s -### 2>&1 | FileCheck %s --check-prefix=CHECK-SCUDO
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


r346526 - Driver: Make -fsanitize=shadow-call-stack compatible with -fsanitize-minimal-runtime.

2018-11-09 Thread Peter Collingbourne via cfe-commits
Author: pcc
Date: Fri Nov  9 09:54:49 2018
New Revision: 346526

URL: http://llvm.org/viewvc/llvm-project?rev=346526&view=rev
Log:
Driver: Make -fsanitize=shadow-call-stack compatible with 
-fsanitize-minimal-runtime.

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

Modified:
cfe/trunk/lib/Driver/SanitizerArgs.cpp
cfe/trunk/test/Driver/fsanitize.c

Modified: cfe/trunk/lib/Driver/SanitizerArgs.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Driver/SanitizerArgs.cpp?rev=346526&r1=346525&r2=346526&view=diff
==
--- cfe/trunk/lib/Driver/SanitizerArgs.cpp (original)
+++ cfe/trunk/lib/Driver/SanitizerArgs.cpp Fri Nov  9 09:54:49 2018
@@ -47,7 +47,7 @@ enum : SanitizerMask {
   TrappingDefault = CFI,
   CFIClasses =
   CFIVCall | CFINVCall | CFIMFCall | CFIDerivedCast | CFIUnrelatedCast,
-  CompatibleWithMinimalRuntime = TrappingSupported | Scudo,
+  CompatibleWithMinimalRuntime = TrappingSupported | Scudo | ShadowCallStack,
 };
 
 enum CoverageFeature {

Modified: cfe/trunk/test/Driver/fsanitize.c
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/Driver/fsanitize.c?rev=346526&r1=346525&r2=346526&view=diff
==
--- cfe/trunk/test/Driver/fsanitize.c (original)
+++ cfe/trunk/test/Driver/fsanitize.c Fri Nov  9 09:54:49 2018
@@ -767,6 +767,10 @@
 // CHECK-CFI-NOICALL-MINIMAL: 
"-fsanitize-trap=cfi-derived-cast,cfi-mfcall,cfi-unrelated-cast,cfi-nvcall,cfi-vcall"
 // CHECK-CFI-NOICALL-MINIMAL: "-fsanitize-minimal-runtime"
 
+// RUN: %clang -target x86_64-linux-gnu -fsanitize=shadow-call-stack 
-fsanitize-minimal-runtime %s -### 2>&1 | FileCheck %s 
--check-prefix=CHECK-SCS-MINIMAL
+// CHECK-SCS-MINIMAL: "-fsanitize=shadow-call-stack"
+// CHECK-SCS-MINIMAL: "-fsanitize-minimal-runtime"
+
 // RUN: %clang -target aarch64-linux-gnu -fsanitize=scudo %s -### 2>&1 | 
FileCheck %s --check-prefix=CHECK-SCUDO
 // RUN: %clang -target arm-linux-androideabi -fsanitize=scudo %s -### 2>&1 | 
FileCheck %s --check-prefix=CHECK-SCUDO
 // RUN: %clang -target x86_64-linux-gnu -fsanitize=scudo %s -### 2>&1 | 
FileCheck %s --check-prefix=CHECK-SCUDO


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


[PATCH] D53488: [clang-tidy] Improving narrowing conversions

2018-11-09 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman added inline comments.



Comment at: clang-tidy/cppcoreguidelines/NarrowingConversionsCheck.cpp:108-113
+  if (T.isSignedInteger())
+return {llvm::APSInt::getMinValue(Context.getTypeSize(&T), false),
+llvm::APSInt::getMaxValue(Context.getTypeSize(&T), false)};
+  assert(T.isUnsignedInteger() && "Unhandled BuiltinType");
+  return {llvm::APSInt::getMinValue(Context.getTypeSize(&T), true),
+  llvm::APSInt::getMaxValue(Context.getTypeSize(&T), true)};

This can be further simplified into:
```
  assert(T.isInteger() && "Unexpected builtin type");
  return {llvm::APSInt::getMinValue(Context.getTypeSize(&T), 
T.isUnsignedInteger()),
   llvm::APSInt::getMaxValue(Context.getTypeSize(&T), 
T.isUnsignedInteger())};
```



Comment at: clang-tidy/cppcoreguidelines/NarrowingConversionsCheck.cpp:313
+// We create variables so we make sure both sides of the
+// ConditionalOperator are evaluated, the || operator would shortciruit
+// the second call otherwise.

shortciruit -> short circuit


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D53488



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


[PATCH] D53974: [clang-tidy] new check: bugprone-too-small-loop-variable

2018-11-09 Thread Tamás Zolnai via Phabricator via cfe-commits
ztamas updated this revision to Diff 173372.
ztamas added a comment.

- Make local functions `static`


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D53974

Files:
  clang-tidy/bugprone/BugproneTidyModule.cpp
  clang-tidy/bugprone/CMakeLists.txt
  clang-tidy/bugprone/TooSmallLoopVariableCheck.cpp
  clang-tidy/bugprone/TooSmallLoopVariableCheck.h
  docs/ReleaseNotes.rst
  docs/clang-tidy/checks/bugprone-too-small-loop-variable.rst
  docs/clang-tidy/checks/list.rst
  test/clang-tidy/bugprone-too-small-loop-variable.cpp

Index: test/clang-tidy/bugprone-too-small-loop-variable.cpp
===
--- /dev/null
+++ test/clang-tidy/bugprone-too-small-loop-variable.cpp
@@ -0,0 +1,227 @@
+// RUN: %check_clang_tidy %s bugprone-too-small-loop-variable %t
+
+long size() { return 294967296l; }
+
+
+/// Test cases correctly caught by bugprone-too-small-loop-variable.
+
+void voidBadForLoop() {
+  for (int i = 0; i < size(); ++i) {
+// CHECK-MESSAGES: :[[@LINE-1]]:19: warning: loop variable has narrower type 'int' than iteration's upper bound 'long' [bugprone-too-small-loop-variable]
+  }
+}
+
+void voidBadForLoop2() {
+  for (int i = 0; i < size() + 10; ++i) {
+// CHECK-MESSAGES: :[[@LINE-1]]:19: warning: loop variable has narrower type 'int' than iteration's upper bound 'long' [bugprone-too-small-loop-variable]
+  }
+}
+
+void voidBadForLoop3() {
+  for (int i = 0; i <= size() - 1; ++i) {
+// CHECK-MESSAGES: :[[@LINE-1]]:19: warning: loop variable has narrower type 'int' than iteration's upper bound 'long' [bugprone-too-small-loop-variable]
+  }
+}
+
+void voidBadForLoop4() {
+  for (int i = 0; size() > i; ++i) {
+// CHECK-MESSAGES: :[[@LINE-1]]:28: warning: loop variable has narrower type 'int' than iteration's upper bound 'long' [bugprone-too-small-loop-variable]
+  }
+}
+
+void voidBadForLoop5() {
+  for (int i = 0; size() - 1 >= i; ++i) {
+// CHECK-MESSAGES: :[[@LINE-1]]:33: warning: loop variable has narrower type 'int' than iteration's upper bound 'long' [bugprone-too-small-loop-variable]
+  }
+}
+
+void voidBadForLoop6() {
+  int i = 0;
+  for (; i < size(); ++i) {
+// CHECK-MESSAGES: :[[@LINE-1]]:10: warning: loop variable has narrower type 'int' than iteration's upper bound 'long' [bugprone-too-small-loop-variable]
+  }
+}
+
+void voidForLoopUnsignedBound() {
+  unsigned size = 3147483647;
+  for (int i = 0; i < size; ++i) {
+// CHECK-MESSAGES: :[[@LINE-1]]:19: warning: loop variable has narrower type 'int' than iteration's upper bound 'unsigned int' [bugprone-too-small-loop-variable]
+  }
+}
+
+// The iteration's upper bound has a template dependent value.
+template 
+void doSomething() {
+  for (short i = 0; i < size; ++i) {
+// CHECK-MESSAGES: :[[@LINE-1]]:21: warning: loop variable has narrower type 'short' than iteration's upper bound 'long' [bugprone-too-small-loop-variable]
+  }
+}
+
+// The iteration's upper bound has a template dependent type.
+template 
+void doSomething() {
+  for (T i = 0; i < size(); ++i) {
+// CHECK-MESSAGES: :[[@LINE-1]]:17: warning: loop variable has narrower type 'short' than iteration's upper bound 'long' [bugprone-too-small-loop-variable]
+  }
+}
+
+void voidForLoopInstantiation() {
+  // This line does not trigger the warning.
+  doSomething();
+  // This one triggers the warning.
+  doSomething();
+}
+
+
+/// Correct loops: we should not warn here.
+
+// A simple use case when both expressions have the same type.
+void voidGoodForLoop() {
+  for (long i = 0; i < size(); ++i) { // no warning
+  }
+}
+
+// Other use case where both expressions have the same type,
+// but short expressions are converted to int by the compare operator.
+void voidGoodForLoop2() {
+  short loopCond = 10;
+  for (short i = 0; i < loopCond; ++i) { // no warning
+  }
+}
+
+// Because of the integer literal, the iteration's upper bound is int, but we suppress the warning here.
+void voidForLoopShortPlusLiteral() {
+  short size = 3;
+  for (short i = 0; i <= (size - 1); ++i) { // no warning
+  }
+}
+
+// Addition of two short variables results in an int value, but we suppress this to avoid false positives.
+void voidForLoopShortPlusShort() {
+  short size = 256;
+  short increment = 14;
+  for (short i = 0; i < size + increment; ++i) { // no warning
+  }
+}
+
+// In this test case we have different integer types, but here the loop variable has the bigger type.
+// The iteration's bound is cast implicitly, not the loop variable.
+void voidForLoopBoundImplicitCast() {
+  short start = 256;
+  short end = 14;
+  for (int i = start; i >= end; --i) { // no warning
+  }
+}
+
+// Range based loop and other iterator based loops are ignored by this check.
+void voidRangeBasedForLoop() {
+  int array[] = {1, 2, 3, 4, 5};
+  for (const int &i :

[PATCH] D53995: [analyzer] Drastically simplify the tblgen files used for checkers

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

Ping


Repository:
  rC Clang

https://reviews.llvm.org/D53995



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


[PATCH] D54307: [clang] overload ignoringParens for Expr

2018-11-09 Thread Jonas Toth via Phabricator via cfe-commits
JonasToth added inline comments.



Comment at: include/clang/ASTMatchers/ASTMatchers.h:814
 /// would match the declaration for fp.
-AST_MATCHER_P(QualType, ignoringParens,
-  internal::Matcher, InnerMatcher) {
+AST_MATCHER_P_OVERLOAD(QualType, ignoringParens, internal::Matcher,
+   InnerMatcher, 0) {

aaron.ballman wrote:
> Can you do this via `AST_POLYMORPHIC_MATCHER_P` instead, given that the 
> implementation is the same?
Do you want me to add more types? e.g. `TypeLoc` has `IgnoreParens()`, too. 


Repository:
  rC Clang

https://reviews.llvm.org/D54307



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


[PATCH] D54307: [clang] overload ignoringParens for Expr

2018-11-09 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman added inline comments.



Comment at: include/clang/ASTMatchers/ASTMatchers.h:814
 /// would match the declaration for fp.
-AST_MATCHER_P(QualType, ignoringParens,
-  internal::Matcher, InnerMatcher) {
+AST_MATCHER_P_OVERLOAD(QualType, ignoringParens, internal::Matcher,
+   InnerMatcher, 0) {

JonasToth wrote:
> aaron.ballman wrote:
> > Can you do this via `AST_POLYMORPHIC_MATCHER_P` instead, given that the 
> > implementation is the same?
> Do you want me to add more types? e.g. `TypeLoc` has `IgnoreParens()`, too. 
I'd not be opposed, given that we already expose the `typeLoc()` matcher. I'll 
leave that to your discretion.


Repository:
  rC Clang

https://reviews.llvm.org/D54307



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


[PATCH] D54246: [clang-tidy] Add the abseil-duration-factory-scale check

2018-11-09 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman added inline comments.



Comment at: clang-tidy/abseil/DurationFactoryScaleCheck.cpp:36
+GetScaleForFactory(llvm::StringRef FactoryName) {
+  static const auto *ScaleMap =
+  new std::unordered_map(

hokein wrote:
> aaron.ballman wrote:
> > hwright wrote:
> > > Eugene.Zelenko wrote:
> > > > This will cause memory leaks, so may be unique_ptr should be used to 
> > > > hold pointer? May be LLVM ADT has better container?
> > > This is a tradeoff between leaking a small amount of known memory for the 
> > > duration of the program, and constructing this map every time this 
> > > function is invoked.  Since I expect the latter to occur frequently, 
> > > that's a tradeoff I think is acceptable.   (Ideally, this would be a 
> > > compile-time constant, but sadly we don't yet have a `constexpr` 
> > > dictionary type.)
> > > 
> > > Of course, if there is a more typical way of doing that here, I'm happy 
> > > to use it.
> > Why did you not use a static value type?
> I think main reason is lazy initialization.
Static locals are lazily initialized, so I'm still not certain why this 
shouldn't use `static const std::unorderd_map 
ScaleMap{...};` instead.



Comment at: clang-tidy/abseil/DurationFactoryScaleCheck.cpp:46
+  const auto ScaleIter = ScaleMap->find(FactoryName);
+  if (ScaleIter == ScaleMap->end()) {
+return llvm::None;

Elide braces.



Comment at: clang-tidy/abseil/DurationFactoryScaleCheck.cpp:57
+   const FloatingLiteral *FloatLit) {
+  if (IntLit) {
+return IntLit->getValue().getLimitedValue();

Elide braces.



Comment at: clang-tidy/abseil/DurationFactoryScaleCheck.cpp:60
+  }
+  assert(FloatLit != nullptr);
+  return FloatLit->getValueAsApproximateDouble();

Please add a message to the assertion. e.g., `assert(foo && "bar");`



Comment at: clang-tidy/abseil/DurationFactoryScaleCheck.cpp:179-181
+  functionDecl(hasAnyName("absl::Nanoseconds", 
"absl::Microseconds",
+  "absl::Milliseconds", "absl::Seconds",
+  "absl::Minutes", "absl::Hours"))

`::absl` instead -- otherwise this can trigger in unintended places.


https://reviews.llvm.org/D54246



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


[PATCH] D53974: [clang-tidy] new check: bugprone-too-small-loop-variable

2018-11-09 Thread Jonas Toth via Phabricator via cfe-commits
JonasToth accepted this revision.
JonasToth added a comment.
This revision is now accepted and ready to land.

LGTM.
Did you run this check in its final form against a bigger project? These 
results would be interesting.
Do you have commit access?


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D53974



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


[PATCH] D54275: [HIP] Remove useless sections in linked files

2018-11-09 Thread Yaxun Liu via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rC346536: [HIP] Remove useless sections in linked files 
(authored by yaxunl, committed by ).

Repository:
  rC Clang

https://reviews.llvm.org/D54275

Files:
  lib/Driver/ToolChains/CommonArgs.cpp


Index: lib/Driver/ToolChains/CommonArgs.cpp
===
--- lib/Driver/ToolChains/CommonArgs.cpp
+++ lib/Driver/ToolChains/CommonArgs.cpp
@@ -1436,6 +1436,10 @@
   LksStream << "PROVIDE_HIDDEN(__hip_fatbin = .);\n";
   LksStream << "" << BundleFileName << "\n";
   LksStream << "  }\n";
+  LksStream << "  /DISCARD/ :\n";
+  LksStream << "  {\n";
+  LksStream << "* ( __CLANG_OFFLOAD_BUNDLE__* )\n";
+  LksStream << "  }\n";
   LksStream << "}\n";
   LksStream << "INSERT BEFORE .data\n";
   LksStream.flush();


Index: lib/Driver/ToolChains/CommonArgs.cpp
===
--- lib/Driver/ToolChains/CommonArgs.cpp
+++ lib/Driver/ToolChains/CommonArgs.cpp
@@ -1436,6 +1436,10 @@
   LksStream << "PROVIDE_HIDDEN(__hip_fatbin = .);\n";
   LksStream << "" << BundleFileName << "\n";
   LksStream << "  }\n";
+  LksStream << "  /DISCARD/ :\n";
+  LksStream << "  {\n";
+  LksStream << "* ( __CLANG_OFFLOAD_BUNDLE__* )\n";
+  LksStream << "  }\n";
   LksStream << "}\n";
   LksStream << "INSERT BEFORE .data\n";
   LksStream.flush();
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


r346536 - [HIP] Remove useless sections in linked files

2018-11-09 Thread Yaxun Liu via cfe-commits
Author: yaxunl
Date: Fri Nov  9 10:52:05 2018
New Revision: 346536

URL: http://llvm.org/viewvc/llvm-project?rev=346536&view=rev
Log:
[HIP] Remove useless sections in linked files

clang-offload-bundler creates __CLANG_OFFLOAD_BUNDLE__* sections in the bundles,
which get into the linked files. These sections are useless after linking. They 
waste disk
space and cause confusion for clang when directly linked with other object 
files, therefore
should be removed.

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

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

Modified: cfe/trunk/lib/Driver/ToolChains/CommonArgs.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Driver/ToolChains/CommonArgs.cpp?rev=346536&r1=346535&r2=346536&view=diff
==
--- cfe/trunk/lib/Driver/ToolChains/CommonArgs.cpp (original)
+++ cfe/trunk/lib/Driver/ToolChains/CommonArgs.cpp Fri Nov  9 10:52:05 2018
@@ -1436,6 +1436,10 @@ void tools::AddHIPLinkerScript(const Too
   LksStream << "PROVIDE_HIDDEN(__hip_fatbin = .);\n";
   LksStream << "" << BundleFileName << "\n";
   LksStream << "  }\n";
+  LksStream << "  /DISCARD/ :\n";
+  LksStream << "  {\n";
+  LksStream << "* ( __CLANG_OFFLOAD_BUNDLE__* )\n";
+  LksStream << "  }\n";
   LksStream << "}\n";
   LksStream << "INSERT BEFORE .data\n";
   LksStream.flush();


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


[PATCH] D54325: [AST] Pack CXXBoolLiteralExpr, CXXNullPtrLiteralExpr and CXXThisExpr

2018-11-09 Thread Bruno Ricci via Phabricator via cfe-commits
riccibruno updated this revision to Diff 173383.
riccibruno added a comment.

Fix some typos in the added comments in `Stmt.h`


Repository:
  rC Clang

https://reviews.llvm.org/D54325

Files:
  include/clang/AST/ExprCXX.h
  include/clang/AST/Stmt.h

Index: include/clang/AST/Stmt.h
===
--- include/clang/AST/Stmt.h
+++ include/clang/AST/Stmt.h
@@ -516,18 +516,6 @@
 SourceLocation OpLoc;
   };
 
-  class ExprWithCleanupsBitfields {
-friend class ASTStmtReader; // deserialization
-friend class ExprWithCleanups;
-
-unsigned : NumExprBits;
-
-// When false, it must not have side effects.
-unsigned CleanupsHaveSideEffects : 1;
-
-unsigned NumObjects : 32 - 1 - NumExprBits;
-  };
-
   class ParenListExprBitfields {
 friend class ASTStmtReader;
 friend class ParenListExpr;
@@ -560,14 +548,6 @@
 unsigned IsUnique : 1;
   };
 
-  class ObjCIndirectCopyRestoreExprBitfields {
-friend class ObjCIndirectCopyRestoreExpr;
-
-unsigned : NumExprBits;
-
-unsigned ShouldCopy : 1;
-  };
-
   class InitListExprBitfields {
 friend class InitListExpr;
 
@@ -578,6 +558,44 @@
 unsigned HadArrayRangeDesignator : 1;
   };
 
+  //===--- C++ expression bitfields classes ---===//
+
+  class CXXBoolLiteralExprBitfields {
+friend class ASTStmtReader;
+friend class CXXBoolLiteralExpr;
+
+unsigned : NumExprBits;
+
+/// The value of the boolean literal.
+unsigned Value : 1;
+
+/// The location of the boolean literal.
+SourceLocation Loc;
+  };
+
+  class CXXNullPtrLiteralExprBitfields {
+friend class ASTStmtReader;
+friend class CXXNullPtrLiteralExpr;
+
+unsigned : NumExprBits;
+
+/// The location of the null pointer literal.
+SourceLocation Loc;
+  };
+
+  class CXXThisExprBitfields {
+friend class ASTStmtReader;
+friend class CXXThisExpr;
+
+unsigned : NumExprBits;
+
+/// Whether this is an implicit "this".
+unsigned IsImplicit : 1;
+
+/// The location of the "this".
+SourceLocation Loc;
+  };
+
   class TypeTraitExprBitfields {
 friend class ASTStmtReader;
 friend class ASTStmtWriter;
@@ -596,14 +614,38 @@
 unsigned NumArgs : 32 - 8 - 1 - NumExprBits;
   };
 
+  class ExprWithCleanupsBitfields {
+friend class ASTStmtReader;
+friend class ExprWithCleanups;
+
+unsigned : NumExprBits;
+
+/// When false, it must not have side effects.
+unsigned CleanupsHaveSideEffects : 1;
+
+unsigned NumObjects : 32 - 1 - NumExprBits;
+  };
+
+  //===--- C++ Coroutines TS expression bitfields classes ---===//
+
   class CoawaitExprBitfields {
 friend class CoawaitExpr;
 
 unsigned : NumExprBits;
 
 unsigned IsImplicit : 1;
   };
 
+  //===--- Obj-C expression bitfields classes ---===//
+
+  class ObjCIndirectCopyRestoreExprBitfields {
+friend class ObjCIndirectCopyRestoreExpr;
+
+unsigned : NumExprBits;
+
+unsigned ShouldCopy : 1;
+  };
+
   union {
 // Statements
 StmtBitfields StmtBits;
@@ -636,14 +678,23 @@
 MemberExprBitfields MemberExprBits;
 CastExprBitfields CastExprBits;
 BinaryOperatorBitfields BinaryOperatorBits;
-ExprWithCleanupsBitfields ExprWithCleanupsBits;
 ParenListExprBitfields ParenListExprBits;
 PseudoObjectExprBitfields PseudoObjectExprBits;
 OpaqueValueExprBitfields OpaqueValueExprBits;
-ObjCIndirectCopyRestoreExprBitfields ObjCIndirectCopyRestoreExprBits;
 InitListExprBitfields InitListExprBits;
+
+// C++ Expressions
+CXXBoolLiteralExprBitfields CXXBoolLiteralExprBits;
+CXXNullPtrLiteralExprBitfields CXXNullPtrLiteralExprBits;
+CXXThisExprBitfields CXXThisExprBits;
 TypeTraitExprBitfields TypeTraitExprBits;
+ExprWithCleanupsBitfields ExprWithCleanupsBits;
+
+// C++ Coroutines TS expressions
 CoawaitExprBitfields CoawaitBits;
+
+// Obj-C Expressions
+ObjCIndirectCopyRestoreExprBitfields ObjCIndirectCopyRestoreExprBits;
   };
 
 public:
Index: include/clang/AST/ExprCXX.h
===
--- include/clang/AST/ExprCXX.h
+++ include/clang/AST/ExprCXX.h
@@ -548,26 +548,25 @@
 
 /// A boolean literal, per ([C++ lex.bool] Boolean literals).
 class CXXBoolLiteralExpr : public Expr {
-  bool Value;
-  SourceLocation Loc;
-
 public:
-  CXXBoolLiteralExpr(bool val, QualType Ty, SourceLocation l)
+  CXXBoolLiteralExpr(bool Val, QualType Ty, SourceLocation Loc)
   : Expr(CXXBoolLiteralExprClass, Ty, VK_RValue, OK_Ordinary, false, false,
- false, false),
-Value(val), Loc(l) {}
+ false, false) {
+CXXBoolLiteralExprBits.Value = Val;
+CXXBoolLiteralExprBits.Loc = Loc;
+  }
 
   explicit CXXBoolLiteralExpr(EmptyShell Empty)
   : Expr(CXXBoolLiteralExprClass, Empty) {}
 
-  bool getValue() const { return Value; }
-  void setValue(bool V) { Value = V; }
+  bool getValue() const { return CXXBoolLiteralExprBits.Value; }
+  

[PATCH] D54334: [AVR] Automatically link CRT and libgcc from the system avr-gcc

2018-11-09 Thread Dylan McKay via Phabricator via cfe-commits
dylanmckay created this revision.
dylanmckay added reviewers: aaron.ballman, kparzysz, asb, hfinkel.

This patch modifies the AVR toolchain so that if avr-gcc and avr-libc
are detected during compilation, the CRT, libgcc, libm, and libc anre
linked.

This matches avr-gcc's default behaviour, and the expected behaviour of
all C compilers - including the C runtime.

avr-gcc also needs a -mmcu specified in order to link runtime libraries.

The difference betwen this patch and avr-gcc is that this patch will
warn users whenever they compile without a runtime, as opposed to GCC,
which silently trims the runtime libs from the linker arguments when no
-mmcu is specified.


Repository:
  rC Clang

https://reviews.llvm.org/D54334

Files:
  include/clang/Basic/DiagnosticDriverKinds.td
  include/clang/Basic/DiagnosticGroups.td
  lib/Driver/ToolChains/AVR.cpp
  lib/Driver/ToolChains/AVR.h
  lib/Driver/ToolChains/Gnu.cpp
  test/Driver/avr-link-mcu-family-unimplemented.c
  test/Driver/avr-link-no-mcu-specified.c
  test/Driver/avr-link-nostdlib-nodefaultlibs.c

Index: test/Driver/avr-link-nostdlib-nodefaultlibs.c
===
--- /dev/null
+++ test/Driver/avr-link-nostdlib-nodefaultlibs.c
@@ -0,0 +1,8 @@
+// RUN: %clang -### -target avr -no-canonical-prefixes -save-temps -mmcu=atmega328 -nostdlib %s 2>&1 | FileCheck %s
+// RUN: %clang -### -target avr -no-canonical-prefixes -save-temps -mmcu=atmega328 -nodefaultlibs %s 2>&1 | FileCheck %s
+
+// nostdlib and nodefaultlibs programs should compile fine.
+
+// CHECK: main
+int main() { return 0; }
+
Index: test/Driver/avr-link-no-mcu-specified.c
===
--- /dev/null
+++ test/Driver/avr-link-no-mcu-specified.c
@@ -0,0 +1,10 @@
+// RUN: %clang -### -target avr -no-canonical-prefixes -save-temps %s 2>&1 | FileCheck --check-prefix=WARN %s
+// RUN: %clang -### -target avr -no-canonical-prefixes -save-temps -mmcu=atmega328 %s 2>&1 | FileCheck --check-prefix=NOWARN %s
+
+// WARN: warning: no target microcontroller specified on command line, cannot link standard libraries, please pass -mmcu=
+// WARN: warning: standard library not linked and so no interrupt vector table or compiler runtime routines will be linked
+
+// NOWARN: main
+
+int main() { return 0; }
+
Index: test/Driver/avr-link-mcu-family-unimplemented.c
===
--- /dev/null
+++ test/Driver/avr-link-mcu-family-unimplemented.c
@@ -0,0 +1,7 @@
+// RUN: %clang -### -target avr -no-canonical-prefixes -save-temps -mmcu=attiny13a %s 2>&1 | FileCheck --check-prefix=WARN %s
+
+// WARN: warning: support for linking stdlibs for microcontroller 'attiny13a' is not implemented, please file an AVR backend bug at http://bugs.llvm.org/ with your mcu name
+// WARN: warning: standard library not linked and so no interrupt vector table or compiler runtime routines will be linked
+
+int main() { return 0; }
+
Index: lib/Driver/ToolChains/Gnu.cpp
===
--- lib/Driver/ToolChains/Gnu.cpp
+++ lib/Driver/ToolChains/Gnu.cpp
@@ -1865,6 +1865,9 @@
   static const char *const ARMebHFTriples[] = {
   "armeb-linux-gnueabihf", "armebv7hl-redhat-linux-gnueabi"};
 
+  static const char *const AVRLibDirs[] = {"/lib"};
+  static const char *const AVRTriples[] = {"avr"};
+
   static const char *const X86_64LibDirs[] = {"/lib64", "/lib"};
   static const char *const X86_64Triples[] = {
   "x86_64-linux-gnu",   "x86_64-unknown-linux-gnu",
@@ -2077,6 +2080,10 @@
   TripleAliases.append(begin(ARMebTriples), end(ARMebTriples));
 }
 break;
+  case llvm::Triple::avr:
+LibDirs.append(begin(AVRLibDirs), end(AVRLibDirs));
+TripleAliases.append(begin(AVRTriples), end(AVRTriples));
+break;
   case llvm::Triple::x86_64:
 LibDirs.append(begin(X86_64LibDirs), end(X86_64LibDirs));
 TripleAliases.append(begin(X86_64Triples), end(X86_64Triples));
@@ -2205,6 +2212,8 @@
   return false;
   } else if (isRISCV(TargetArch)) {
 findRISCVMultilibs(D, TargetTriple, Path, Args, Detected);
+  } else if (TargetArch == llvm::Triple::avr) {
+// AVR has no multilibs.
   } else if (!findBiarchMultilibs(D, TargetTriple, Path, Args,
   NeedsBiarchSuffix, Detected)) {
 return false;
Index: lib/Driver/ToolChains/AVR.h
===
--- lib/Driver/ToolChains/AVR.h
+++ lib/Driver/ToolChains/AVR.h
@@ -20,26 +20,45 @@
 namespace toolchains {
 
 class LLVM_LIBRARY_VISIBILITY AVRToolChain : public Generic_ELF {
-protected:
-  Tool *buildLinker() const override;
 public:
   AVRToolChain(const Driver &D, const llvm::Triple &Triple,
const llvm::opt::ArgList &Args);
+protected:
+  Tool *buildLinker() const override;
+
+private:
+  /// Whether libgcc, libct, and friends should be linked.
+  ///
+  /// This is no

[PATCH] D54307: [clang] overload ignoringParens for Expr

2018-11-09 Thread Jonas Toth via Phabricator via cfe-commits
JonasToth added inline comments.



Comment at: include/clang/ASTMatchers/ASTMatchers.h:814
 /// would match the declaration for fp.
-AST_MATCHER_P(QualType, ignoringParens,
-  internal::Matcher, InnerMatcher) {
+AST_MATCHER_P_OVERLOAD(QualType, ignoringParens, internal::Matcher,
+   InnerMatcher, 0) {

aaron.ballman wrote:
> JonasToth wrote:
> > aaron.ballman wrote:
> > > Can you do this via `AST_POLYMORPHIC_MATCHER_P` instead, given that the 
> > > implementation is the same?
> > Do you want me to add more types? e.g. `TypeLoc` has `IgnoreParens()`, too. 
> I'd not be opposed, given that we already expose the `typeLoc()` matcher. 
> I'll leave that to your discretion.
as discussed on IRC making it an `AST_POLYMORPHIC_MATCHER_P` does not seem to 
work, as the polymorphism is only in the return type. We do need the `Node` 
itself to be polymorphic (same type as returntype). The only working version I 
got was using the overloads.


Repository:
  rC Clang

https://reviews.llvm.org/D54307



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


[PATCH] D54307: [clang] overload ignoringParens for Expr

2018-11-09 Thread Jonas Toth via Phabricator via cfe-commits
JonasToth updated this revision to Diff 173391.
JonasToth marked 3 inline comments as done.
JonasToth added a comment.

- add unit test


Repository:
  rC Clang

https://reviews.llvm.org/D54307

Files:
  docs/LibASTMatchersReference.html
  include/clang/ASTMatchers/ASTMatchers.h
  lib/ASTMatchers/Dynamic/Registry.cpp
  unittests/ASTMatchers/ASTMatchersNodeTest.cpp


Index: unittests/ASTMatchers/ASTMatchersNodeTest.cpp
===
--- unittests/ASTMatchers/ASTMatchersNodeTest.cpp
+++ unittests/ASTMatchers/ASTMatchersNodeTest.cpp
@@ -1147,6 +1147,14 @@
  parenExpr()));
 }
 
+TEST(ParenExpression, IgnoringParens) {
+  EXPECT_FALSE(matches("const char* str = (\"my-string\");",
+   
implicitCastExpr(hasSourceExpression(stringLiteral();
+  EXPECT_TRUE(matches(
+  "const char* str = (\"my-string\");",
+  implicitCastExpr(hasSourceExpression(ignoringParens(stringLiteral());
+}
+
 TEST(TypeMatching, MatchesTypes) {
   EXPECT_TRUE(matches("struct S {};", qualType().bind("loc")));
 }
Index: lib/ASTMatchers/Dynamic/Registry.cpp
===
--- lib/ASTMatchers/Dynamic/Registry.cpp
+++ lib/ASTMatchers/Dynamic/Registry.cpp
@@ -106,6 +106,7 @@
   REGISTER_OVERLOADED_2(callee);
   REGISTER_OVERLOADED_2(hasPrefix);
   REGISTER_OVERLOADED_2(hasType);
+  REGISTER_OVERLOADED_2(ignoringParens);
   REGISTER_OVERLOADED_2(isDerivedFrom);
   REGISTER_OVERLOADED_2(isSameOrDerivedFrom);
   REGISTER_OVERLOADED_2(loc);
@@ -318,7 +319,6 @@
   REGISTER_MATCHER(ignoringImplicit);
   REGISTER_MATCHER(ignoringParenCasts);
   REGISTER_MATCHER(ignoringParenImpCasts);
-  REGISTER_MATCHER(ignoringParens);
   REGISTER_MATCHER(imaginaryLiteral);
   REGISTER_MATCHER(implicitCastExpr);
   REGISTER_MATCHER(implicitValueInitExpr);
Index: include/clang/ASTMatchers/ASTMatchers.h
===
--- include/clang/ASTMatchers/ASTMatchers.h
+++ include/clang/ASTMatchers/ASTMatchers.h
@@ -811,11 +811,28 @@
 ///   varDecl(hasType(pointerType(pointee(ignoringParens(functionType())
 /// \endcode
 /// would match the declaration for fp.
-AST_MATCHER_P(QualType, ignoringParens,
-  internal::Matcher, InnerMatcher) {
+AST_MATCHER_P_OVERLOAD(QualType, ignoringParens, internal::Matcher,
+   InnerMatcher, 0) {
   return InnerMatcher.matches(Node.IgnoreParens(), Finder, Builder);
 }
 
+/// Overload \c ignoringParens for \c Expr.
+///
+/// Given
+/// \code
+///   const char* str = ("my-string");
+/// \endcode
+/// The matcher
+/// \code
+///   implicitCastExpr(hasSourceExpression(ignoringParens(stringLiteral(
+/// \endcode
+/// would match the implicit cast resulting from the assignment.
+AST_MATCHER_P_OVERLOAD(Expr, ignoringParens, internal::Matcher,
+   InnerMatcher, 1) {
+  const Expr *E = Node.IgnoreParens();
+  return InnerMatcher.matches(*E, Finder, Builder);
+}
+
 /// Matches expressions that are instantiation-dependent even if it is
 /// neither type- nor value-dependent.
 ///
Index: docs/LibASTMatchersReference.html
===
--- docs/LibASTMatchersReference.html
+++ docs/LibASTMatchersReference.html
@@ -5552,6 +5552,17 @@
 
 
 
+MatcherExpr>ignoringParensMatcherExpr> 
InnerMatcher
+Overload 
ignoringParens for Expr.
+
+Given
+  const char* str = ("my-string");
+The matcher
+  implicitCastExpr(hasSourceExpression(ignoringParens(stringLiteral(
+would match the implicit cast resulting from the assignment.
+
+
+
 MatcherFieldDecl>hasInClassInitializerMatcherExpr> 
InnerMatcher
 Matches 
non-static data members that have an in-class initializer.
 


Index: unittests/ASTMatchers/ASTMatchersNodeTest.cpp
===
--- unittests/ASTMatchers/ASTMatchersNodeTest.cpp
+++ unittests/ASTMatchers/ASTMatchersNodeTest.cpp
@@ -1147,6 +1147,14 @@
  parenExpr()));
 }
 
+TEST(ParenExpression, IgnoringParens) {
+  EXPECT_FALSE(matches("const char* str = (\"my-string\");",
+   implicitCastExpr(hasSourceExpression(stringLiteral();
+  EXPECT_TRUE(matches(
+  "const char* str = (\"my-string\");",
+  implicitCastExpr(hasSourceExpression(ignoringParens(stringLiteral());
+}
+
 TEST(TypeMatching, MatchesTypes) {
   EXPECT_TRUE(matches("struct S {};", qualType().bind("loc")));
 }
Index: lib/ASTMatchers/Dynamic/Registry.cpp
===
--- lib/ASTMatchers/Dynamic/Registry.cpp
+++ lib/ASTMatchers/Dynamic/Registry.cpp
@@ -106,6 +106,7 @@
   REGISTER_

r346542 - Fix a nondeterminism in the debug info for VLA size expressions.

2018-11-09 Thread Adrian Prantl via cfe-commits
Author: adrian
Date: Fri Nov  9 11:17:56 2018
New Revision: 346542

URL: http://llvm.org/viewvc/llvm-project?rev=346542&view=rev
Log:
Fix a nondeterminism in the debug info for VLA size expressions.

The artificial variable describing the array size is supposed to be
called "__vla_expr", but this was implemented by retrieving the name
of the associated alloca, which isn't a reliable source for the name,
since nonassert compilers may drop names from LLVM IR.

rdar://problem/45924808

Modified:
cfe/trunk/lib/CodeGen/CGDecl.cpp
cfe/trunk/lib/CodeGen/CodeGenFunction.h
cfe/trunk/test/CodeGen/debug-info-vla.c
cfe/trunk/test/CodeGenCXX/debug-info-vla.cpp

Modified: cfe/trunk/lib/CodeGen/CGDecl.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/CodeGen/CGDecl.cpp?rev=346542&r1=346541&r2=346542&view=diff
==
--- cfe/trunk/lib/CodeGen/CGDecl.cpp (original)
+++ cfe/trunk/lib/CodeGen/CGDecl.cpp Fri Nov  9 11:17:56 2018
@@ -1066,6 +1066,7 @@ void CodeGenFunction::EmitAndRegisterVar
   // For each dimension stores its QualType and corresponding
   // size-expression Value.
   SmallVector Dimensions;
+  SmallVector VLAExprNames;
 
   // Break down the array into individual dimensions.
   QualType Type1D = D.getType();
@@ -1074,8 +1075,14 @@ void CodeGenFunction::EmitAndRegisterVar
 if (auto *C = dyn_cast(VlaSize.NumElts))
   Dimensions.emplace_back(C, Type1D.getUnqualifiedType());
 else {
-  auto SizeExprAddr = CreateDefaultAlignTempAlloca(
-  VlaSize.NumElts->getType(), "__vla_expr");
+  // Generate a locally unique name for the size expression.
+  Twine Name = Twine("__vla_expr") + Twine(VLAExprCounter++);
+  SmallString<12> Buffer;
+  StringRef NameRef = Name.toStringRef(Buffer);
+  auto &Ident = getContext().Idents.getOwn(NameRef);
+  VLAExprNames.push_back(&Ident);
+  auto SizeExprAddr =
+  CreateDefaultAlignTempAlloca(VlaSize.NumElts->getType(), NameRef);
   Builder.CreateStore(VlaSize.NumElts, SizeExprAddr);
   Dimensions.emplace_back(SizeExprAddr.getPointer(),
   Type1D.getUnqualifiedType());
@@ -1089,20 +1096,20 @@ void CodeGenFunction::EmitAndRegisterVar
   // Register each dimension's size-expression with a DILocalVariable,
   // so that it can be used by CGDebugInfo when instantiating a DISubrange
   // to describe this array.
+  unsigned NameIdx = 0;
   for (auto &VlaSize : Dimensions) {
 llvm::Metadata *MD;
 if (auto *C = dyn_cast(VlaSize.NumElts))
   MD = llvm::ConstantAsMetadata::get(C);
 else {
   // Create an artificial VarDecl to generate debug info for.
-  IdentifierInfo &NameIdent = getContext().Idents.getOwn(
-  cast(VlaSize.NumElts)->getName());
+  IdentifierInfo *NameIdent = VLAExprNames[NameIdx++];
   auto VlaExprTy = VlaSize.NumElts->getType()->getPointerElementType();
   auto QT = getContext().getIntTypeForBitwidth(
   VlaExprTy->getScalarSizeInBits(), false);
   auto *ArtificialDecl = VarDecl::Create(
   getContext(), const_cast(D.getDeclContext()),
-  D.getLocation(), D.getLocation(), &NameIdent, QT,
+  D.getLocation(), D.getLocation(), NameIdent, QT,
   getContext().CreateTypeSourceInfo(QT), SC_Auto);
   ArtificialDecl->setImplicit();
 

Modified: cfe/trunk/lib/CodeGen/CodeGenFunction.h
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/CodeGen/CodeGenFunction.h?rev=346542&r1=346541&r2=346542&view=diff
==
--- cfe/trunk/lib/CodeGen/CodeGenFunction.h (original)
+++ cfe/trunk/lib/CodeGen/CodeGenFunction.h Fri Nov  9 11:17:56 2018
@@ -1197,6 +1197,8 @@ public:
 
 private:
   CGDebugInfo *DebugInfo;
+  /// Used to create unique names for artificial VLA size debug info variables.
+  unsigned VLAExprCounter = 0;
   bool DisableDebugInfo = false;
 
   /// DidCallStackSave - Whether llvm.stacksave has been called. Used to avoid

Modified: cfe/trunk/test/CodeGen/debug-info-vla.c
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/CodeGen/debug-info-vla.c?rev=346542&r1=346541&r2=346542&view=diff
==
--- cfe/trunk/test/CodeGen/debug-info-vla.c (original)
+++ cfe/trunk/test/CodeGen/debug-info-vla.c Fri Nov  9 11:17:56 2018
@@ -2,9 +2,9 @@
 
 void testVLAwithSize(int s)
 {
-// CHECK-DAG: dbg.declare({{.*}} %__vla_expr, metadata ![[VLAEXPR:[0-9]+]]
+// CHECK-DAG: dbg.declare({{.*}} %__vla_expr0, metadata ![[VLAEXPR:[0-9]+]]
 // CHECK-DAG: dbg.declare({{.*}} %vla, metadata ![[VAR:[0-9]+]]
-// CHECK-DAG: ![[VLAEXPR]] = !DILocalVariable(name: "__vla_expr", {{.*}} 
flags: DIFlagArtificial
+// CHECK-DAG: ![[VLAEXPR]] = !DILocalVariable(name: "__vla_expr0", {{.*}} 
flags: DIFlagArtificial
 // CHECK-DAG: ![[VAR]] = !DILocalVariable(name: "vla",{{.*}} line: [[@LINE+2]]
 // 

[PATCH] D52674: [AST] Add Obj-C discriminator to MS ABI RTTI

2018-11-09 Thread Shoaib Meenai via Phabricator via cfe-commits
smeenai added a comment.

In https://reviews.llvm.org/D52674#1293180, @rjmccall wrote:

> In https://reviews.llvm.org/D52674#1291284, @smeenai wrote:
>
> > In https://reviews.llvm.org/D52674#1281747, @rjmccall wrote:
> >
> > > In https://reviews.llvm.org/D52674#1271814, @smeenai wrote:
> > >
> > > > @rjmccall I prototyped the ForRTTI parameter approach in 
> > > > https://reviews.llvm.org/D53546. It could definitely be cleaned up a 
> > > > bit, but it demonstrates the problems I saw with the added parameter. 
> > > > Namely, `mangleType(QualType, SourceRange, QualifierMangleMode)` has a 
> > > > bunch of additional logic which is needed for correctness, so we need 
> > > > to thread the parameter through the entire chain, and the only way I 
> > > > could think of doing that without adding the parameter to every single 
> > > > `mangleType` overload was to have an additional switch to dispatch to 
> > > > the overloads with the added ForRTTI parameter, which is pretty ugly.
> > > >
> > > > As I see it, there are a few ways to proceed here:
> > > >
> > > > - The approach in https://reviews.llvm.org/D53546 (cleaned up a bit). I 
> > > > think it's pretty ugly, but you may have suggestions on how to do it 
> > > > better.
> > > > - In the `mangleType` overload for `ObjCObjectPointerType`, skipping 
> > > > the generic `mangleType` dispatch and going directly to either the 
> > > > `ObjCObjectType` or `ObjCInterfaceType` overloads. That avoids the 
> > > > ugliness in the generic `mangleType`, but it also requires us to 
> > > > duplicate some logic from it in the `ObjCObjectPointerType` overload, 
> > > > which doesn't seem great either.
> > > > - Maintaining `ForRTTI` state in the mangler instead of threading a 
> > > > parameter through (I'm generally not a fan of state like that, but it 
> > > > might be cleaner than the threading in this case?)
> > > > - Just sticking with what I'm doing in this patch.
> > > >
> > > >   What do you think?
> > >
> > >
> > > Sorry for the delay.  I think duplicating the dispatch logic for 
> > > `ObjCObjectPointerType` is probably the best approach; the pointee type 
> > > will always an `ObjCObjectType` of some sort, and there are only two 
> > > kinds of those.
> >
> >
> > Sorry, I'm still not sure how this will work.
> >
> > Duplicating the dispatch logic for `ObjCObjectPointerType` ends up looking 
> > like https://reviews.llvm.org/P8114, which is fine. However, when we're 
> > actually mangling RTTI or RTTI names, we're still going through the main 
> > `mangleType(QualType, SourceRange, QualifierMangleMode)` overload, which 
> > still requires us to thread `ForRTTI` through that function, which still 
> > requires us to duplicate the switch in that function (to handle the 
> > `ForRTTI` case, since the other switch is generated via TypeNodes.def and 
> > not easily modifiable), which is the main ugliness in my opinion. Do you 
> > also want me to add special dispatching to `mangleCXXRTTI` and 
> > `mangleCXXRTTIName` to just call the `ObjCObjectPointerType` function 
> > directly when they're dealing with that type? That's certainly doable, but 
> > at that point just keeping some state around in the demangler starts to 
> > feel cleaner, at least to me.
>
>
> Well, you could check for an `ObjCObjectPointerType` in the top-level routine.
>
> But yeah, probably the cleanest thing to do would to be push the state 
> through the main dispatch.  Don't push a single `bool` through, though; make 
> a `TypeManglingOptions` struct to encapsulate it, in case we have a similar 
> problem elsewhere.  It should have a method for getting options that should 
> be propagated down to component type manglings, and that method can drop the 
> "for RTTI" bit; that's the part that `ObjCObjectPointerType` can handle 
> differently.


All right, the struct is a good idea. It would require adding the 
`TypeManglingOptions` parameter to all the `mangleType` overloads (unless we 
want to stick with the second switch in the main `mangleType` dispatch 
function, but that seems super ugly, especially if we're doing a more general 
solution), so I wanted to confirm @rnk is okay with adding a parameter to all 
those overloads as well before proceeding.


Repository:
  rC Clang

https://reviews.llvm.org/D52674



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


[PATCH] D54307: [clang] overload ignoringParens for Expr

2018-11-09 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman added reviewers: sbenza, klimek.
aaron.ballman added a comment.

Adding a few other reviewers in case they have ideas on how to use the 
polymorphic matcher rather than the overload. If they don't have a better idea, 
then I think the overload approach is fine.


Repository:
  rC Clang

https://reviews.llvm.org/D54307



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


r346547 - Allow a double-underscore spelling of Clang attributes using double square bracket syntax.

2018-11-09 Thread Aaron Ballman via cfe-commits
Author: aaronballman
Date: Fri Nov  9 11:37:18 2018
New Revision: 346547

URL: http://llvm.org/viewvc/llvm-project?rev=346547&view=rev
Log:
Allow a double-underscore spelling of Clang attributes using double square 
bracket syntax.

This matches a similar behavior with GCC accepting [[gnu::__attr__]] as a alias 
for [[gnu::attr]] in that clang attributes can now be spelled with two leading 
and trailing underscores.

I had always intended for this to work, but missed the critical bit. We already 
had an existing test in test/Preprocessor/has_attribute.cpp for 
[[clang::__fallthrough__]] but using that spelling would still give an "unknown 
attribute" diagnostic.

Modified:
cfe/trunk/lib/Sema/ParsedAttr.cpp
cfe/trunk/test/SemaCXX/attr-optnone.cpp
cfe/trunk/test/SemaCXX/switch-implicit-fallthrough.cpp

Modified: cfe/trunk/lib/Sema/ParsedAttr.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Sema/ParsedAttr.cpp?rev=346547&r1=346546&r2=346547&view=diff
==
--- cfe/trunk/lib/Sema/ParsedAttr.cpp (original)
+++ cfe/trunk/lib/Sema/ParsedAttr.cpp Fri Nov  9 11:37:18 2018
@@ -122,11 +122,12 @@ static StringRef normalizeAttrName(Strin
ParsedAttr::Syntax SyntaxUsed) {
   // Normalize the attribute name, __foo__ becomes foo. This is only allowable
   // for GNU attributes, and attributes using the double square bracket syntax.
-  bool IsGNU = SyntaxUsed == ParsedAttr::AS_GNU ||
-   ((SyntaxUsed == ParsedAttr::AS_CXX11 ||
- SyntaxUsed == ParsedAttr::AS_C2x) &&
-NormalizedScopeName == "gnu");
-  if (IsGNU && AttrName.size() >= 4 && AttrName.startswith("__") &&
+  bool ShouldNormalize =
+  SyntaxUsed == ParsedAttr::AS_GNU ||
+  ((SyntaxUsed == ParsedAttr::AS_CXX11 ||
+SyntaxUsed == ParsedAttr::AS_C2x) &&
+   (NormalizedScopeName == "gnu" || NormalizedScopeName == "clang"));
+  if (ShouldNormalize && AttrName.size() >= 4 && AttrName.startswith("__") &&
   AttrName.endswith("__"))
 AttrName = AttrName.slice(2, AttrName.size() - 2);
 

Modified: cfe/trunk/test/SemaCXX/attr-optnone.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/SemaCXX/attr-optnone.cpp?rev=346547&r1=346546&r2=346547&view=diff
==
--- cfe/trunk/test/SemaCXX/attr-optnone.cpp (original)
+++ cfe/trunk/test/SemaCXX/attr-optnone.cpp Fri Nov  9 11:37:18 2018
@@ -72,8 +72,10 @@ struct B2 {
 };
 
 // Verify that we can handle the [[_Clang::optnone]] and
-// [[__clang__::optnone]] spellings.
+// [[__clang__::optnone]] spellings, as well as [[clang::__optnone__]].
 [[_Clang::optnone]] int foo3();
 [[__clang__::optnone]] int foo4(); // expected-warning {{'__clang__' is a 
predefined macro name, not an attribute scope specifier; did you mean '_Clang' 
instead?}}
+[[clang::__optnone__]] int foo5();
+[[_Clang::__optnone__]] int foo6();
 
-[[_Clang::optnone]] int foo5; // expected-warning {{'optnone' attribute only 
applies to functions}}
+[[_Clang::optnone]] int foo7; // expected-warning {{'optnone' attribute only 
applies to functions}}

Modified: cfe/trunk/test/SemaCXX/switch-implicit-fallthrough.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/SemaCXX/switch-implicit-fallthrough.cpp?rev=346547&r1=346546&r2=346547&view=diff
==
--- cfe/trunk/test/SemaCXX/switch-implicit-fallthrough.cpp (original)
+++ cfe/trunk/test/SemaCXX/switch-implicit-fallthrough.cpp Fri Nov  9 11:37:18 
2018
@@ -314,3 +314,18 @@ int fallthrough_targets(int n) {
   }
   return n;
 }
+
+int fallthrough_alt_spelling(int n) {
+  switch (n) {
+  case 0:
+n++;
+[[clang::fallthrough]];
+  case 1:
+n++;
+[[clang::__fallthrough__]];
+  case 2:
+n++;
+break;
+  }
+  return n;
+}


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


r346548 - Use the correct address space when bitcasting func pointer to int pointer

2018-11-09 Thread Dylan McKay via cfe-commits
Author: dylanmckay
Date: Fri Nov  9 11:42:05 2018
New Revision: 346548

URL: http://llvm.org/viewvc/llvm-project?rev=346548&view=rev
Log:
Use the correct address space when bitcasting func pointer to int pointer

When we cast a function pointer to an int pointer, at some pointer later
it gets bitcasted back to a function and called.

In backends that have a nonzero program memory address space specified
in the data layout, the old code would lose the address space data. When
LLVM later attempted to generate the bitcast from i8* to i8(..)*
addrspace(1), it would fail because the pointers are not in the same
address space.

With this patch, the address space of the function will carry on to the
address space of the i8* pointer. This is because all function pointers
in Harvard architectures need to be assigned to the correct address
space.

This has no effect to any in-tree backends except AVR.

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

Modified: cfe/trunk/lib/CodeGen/CGException.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/CodeGen/CGException.cpp?rev=346548&r1=346547&r2=346548&view=diff
==
--- cfe/trunk/lib/CodeGen/CGException.cpp (original)
+++ cfe/trunk/lib/CodeGen/CGException.cpp Fri Nov  9 11:42:05 2018
@@ -250,7 +250,11 @@ static llvm::Constant *getPersonalityFn(
 static llvm::Constant *getOpaquePersonalityFn(CodeGenModule &CGM,
 const EHPersonality &Personality) {
   llvm::Constant *Fn = getPersonalityFn(CGM, Personality);
-  return llvm::ConstantExpr::getBitCast(Fn, CGM.Int8PtrTy);
+  llvm::PointerType* Int8PtrTy = llvm::PointerType::get(
+  llvm::Type::getInt8Ty(CGM.getLLVMContext()),
+  CGM.getDataLayout().getProgramAddressSpace());
+
+  return llvm::ConstantExpr::getBitCast(Fn, Int8PtrTy);
 }
 
 /// Check whether a landingpad instruction only uses C++ features.


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


r346549 - Revert rL346454: Fix a use-after-free introduced by r344915.

2018-11-09 Thread Simon Pilgrim via cfe-commits
Author: rksimon
Date: Fri Nov  9 11:42:53 2018
New Revision: 346549

URL: http://llvm.org/viewvc/llvm-project?rev=346549&view=rev
Log:
Revert rL346454: Fix a use-after-free introduced by r344915.

r344915 added a call to ApplyDebugLocation to the sanitizer check
function emitter. Some of the sanitizers are emitted in the function
epilogue though and the LexicalScopeStack is emptied out before. By
detecting this situation and early-exiting from ApplyDebugLocation the
fallback location is used, which is equivalent to the return location.

rdar://problem/45859802

Causes EXPENSIVE_CHECKS build bot failures: 
http://lab.llvm.org:8011/builders/llvm-clang-x86_64-expensive-checks-win

Removed:
cfe/trunk/test/CodeGen/ubsan-debuglog-return.c
Modified:
cfe/trunk/lib/CodeGen/CGDebugInfo.cpp

Modified: cfe/trunk/lib/CodeGen/CGDebugInfo.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/CodeGen/CGDebugInfo.cpp?rev=346549&r1=346548&r2=346549&view=diff
==
--- cfe/trunk/lib/CodeGen/CGDebugInfo.cpp (original)
+++ cfe/trunk/lib/CodeGen/CGDebugInfo.cpp Fri Nov  9 11:42:53 2018
@@ -3538,7 +3538,7 @@ void CGDebugInfo::EmitLocation(CGBuilder
   // Update our current location
   setLocation(Loc);
 
-  if (CurLoc.isInvalid() || CurLoc.isMacroID() || LexicalBlockStack.empty())
+  if (CurLoc.isInvalid() || CurLoc.isMacroID())
 return;
 
   llvm::MDNode *Scope = LexicalBlockStack.back();

Removed: cfe/trunk/test/CodeGen/ubsan-debuglog-return.c
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/CodeGen/ubsan-debuglog-return.c?rev=346548&view=auto
==
--- cfe/trunk/test/CodeGen/ubsan-debuglog-return.c (original)
+++ cfe/trunk/test/CodeGen/ubsan-debuglog-return.c (removed)
@@ -1,10 +0,0 @@
-// RUN: %clang_cc1 -x c -debug-info-kind=line-tables-only -emit-llvm 
-fsanitize=returns-nonnull-attribute -o - %s | FileCheck %s
-// The UBSAN function call in the epilogue needs to have a debug location.
-
-__attribute__((returns_nonnull)) void *allocate() {}
-
-// CHECK: define nonnull i8* @allocate(){{.*}} !dbg
-// CHECK: call void @__ubsan_handle_nonnull_return_v1_abort
-// CHECK-SAME:  !dbg ![[LOC:[0-9]+]]
-// CHECK: ret i8*
-// CHECK-SAME:  !dbg ![[LOC]]


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


Re: r346548 - Use the correct address space when bitcasting func pointer to int pointer

2018-11-09 Thread Roman Lebedev via cfe-commits
The codegen change can't be tested?
On Fri, Nov 9, 2018 at 10:44 PM Dylan McKay via cfe-commits
 wrote:
>
> Author: dylanmckay
> Date: Fri Nov  9 11:42:05 2018
> New Revision: 346548
>
> URL: http://llvm.org/viewvc/llvm-project?rev=346548&view=rev
> Log:
> Use the correct address space when bitcasting func pointer to int pointer
>
> When we cast a function pointer to an int pointer, at some pointer later
> it gets bitcasted back to a function and called.
>
> In backends that have a nonzero program memory address space specified
> in the data layout, the old code would lose the address space data. When
> LLVM later attempted to generate the bitcast from i8* to i8(..)*
> addrspace(1), it would fail because the pointers are not in the same
> address space.
>
> With this patch, the address space of the function will carry on to the
> address space of the i8* pointer. This is because all function pointers
> in Harvard architectures need to be assigned to the correct address
> space.
>
> This has no effect to any in-tree backends except AVR.
>
> Modified:
> cfe/trunk/lib/CodeGen/CGException.cpp
>
> Modified: cfe/trunk/lib/CodeGen/CGException.cpp
> URL: 
> http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/CodeGen/CGException.cpp?rev=346548&r1=346547&r2=346548&view=diff
> ==
> --- cfe/trunk/lib/CodeGen/CGException.cpp (original)
> +++ cfe/trunk/lib/CodeGen/CGException.cpp Fri Nov  9 11:42:05 2018
> @@ -250,7 +250,11 @@ static llvm::Constant *getPersonalityFn(
>  static llvm::Constant *getOpaquePersonalityFn(CodeGenModule &CGM,
>  const EHPersonality &Personality) {
>llvm::Constant *Fn = getPersonalityFn(CGM, Personality);
> -  return llvm::ConstantExpr::getBitCast(Fn, CGM.Int8PtrTy);
> +  llvm::PointerType* Int8PtrTy = llvm::PointerType::get(
> +  llvm::Type::getInt8Ty(CGM.getLLVMContext()),
> +  CGM.getDataLayout().getProgramAddressSpace());
> +
> +  return llvm::ConstantExpr::getBitCast(Fn, Int8PtrTy);
>  }
>
>  /// Check whether a landingpad instruction only uses C++ features.
>
>
> ___
> cfe-commits mailing list
> cfe-commits@lists.llvm.org
> http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D54307: [clang] overload ignoringParens for Expr

2018-11-09 Thread Samuel Benzaquen via Phabricator via cfe-commits
sbenza added inline comments.



Comment at: include/clang/ASTMatchers/ASTMatchers.h:814
 /// would match the declaration for fp.
-AST_MATCHER_P(QualType, ignoringParens,
-  internal::Matcher, InnerMatcher) {
+AST_MATCHER_P_OVERLOAD(QualType, ignoringParens, internal::Matcher,
+   InnerMatcher, 0) {

JonasToth wrote:
> aaron.ballman wrote:
> > JonasToth wrote:
> > > aaron.ballman wrote:
> > > > Can you do this via `AST_POLYMORPHIC_MATCHER_P` instead, given that the 
> > > > implementation is the same?
> > > Do you want me to add more types? e.g. `TypeLoc` has `IgnoreParens()`, 
> > > too. 
> > I'd not be opposed, given that we already expose the `typeLoc()` matcher. 
> > I'll leave that to your discretion.
> as discussed on IRC making it an `AST_POLYMORPHIC_MATCHER_P` does not seem to 
> work, as the polymorphism is only in the return type. We do need the `Node` 
> itself to be polymorphic (same type as returntype). The only working version 
> I got was using the overloads.
You can't use AST_POLYMORPHIC_MATCHER_P to overload on input types.
You could try using templates, but that will make registering the matcher 
harder.
Another one that does input+output polymorphism, `id`, is simply not supported 
dynamically.


Repository:
  rC Clang

https://reviews.llvm.org/D54307



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


[PATCH] D54307: [clang] overload ignoringParens for Expr

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

LGTM!




Comment at: include/clang/ASTMatchers/ASTMatchers.h:814
 /// would match the declaration for fp.
-AST_MATCHER_P(QualType, ignoringParens,
-  internal::Matcher, InnerMatcher) {
+AST_MATCHER_P_OVERLOAD(QualType, ignoringParens, internal::Matcher,
+   InnerMatcher, 0) {

sbenza wrote:
> JonasToth wrote:
> > aaron.ballman wrote:
> > > JonasToth wrote:
> > > > aaron.ballman wrote:
> > > > > Can you do this via `AST_POLYMORPHIC_MATCHER_P` instead, given that 
> > > > > the implementation is the same?
> > > > Do you want me to add more types? e.g. `TypeLoc` has `IgnoreParens()`, 
> > > > too. 
> > > I'd not be opposed, given that we already expose the `typeLoc()` matcher. 
> > > I'll leave that to your discretion.
> > as discussed on IRC making it an `AST_POLYMORPHIC_MATCHER_P` does not seem 
> > to work, as the polymorphism is only in the return type. We do need the 
> > `Node` itself to be polymorphic (same type as returntype). The only working 
> > version I got was using the overloads.
> You can't use AST_POLYMORPHIC_MATCHER_P to overload on input types.
> You could try using templates, but that will make registering the matcher 
> harder.
> Another one that does input+output polymorphism, `id`, is simply not 
> supported dynamically.
Good to know, thank you!


Repository:
  rC Clang

https://reviews.llvm.org/D54307



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


r346551 - [OPENMP][NVPTX]Extend number of constructs executed in SPMD mode.

2018-11-09 Thread Alexey Bataev via cfe-commits
Author: abataev
Date: Fri Nov  9 12:03:19 2018
New Revision: 346551

URL: http://llvm.org/viewvc/llvm-project?rev=346551&view=rev
Log:
[OPENMP][NVPTX]Extend number of constructs executed in SPMD mode.

If the statements between target|teams|distribute directives does not
require execution in master thread, like constant expressions, null
statements, simple declarations, etc., such construct can be xecuted in
SPMD mode.

Modified:
cfe/trunk/lib/CodeGen/CGOpenMPRuntimeNVPTX.cpp
cfe/trunk/test/OpenMP/nvptx_SPMD_codegen.cpp
cfe/trunk/test/OpenMP/nvptx_target_parallel_codegen.cpp
cfe/trunk/test/OpenMP/nvptx_target_parallel_proc_bind_codegen.cpp
cfe/trunk/test/OpenMP/nvptx_target_parallel_reduction_codegen.cpp
cfe/trunk/test/OpenMP/nvptx_target_teams_codegen.cpp
cfe/trunk/test/OpenMP/nvptx_target_teams_distribute_parallel_for_codegen.cpp

cfe/trunk/test/OpenMP/nvptx_target_teams_distribute_parallel_for_simd_codegen.cpp

Modified: cfe/trunk/lib/CodeGen/CGOpenMPRuntimeNVPTX.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/CodeGen/CGOpenMPRuntimeNVPTX.cpp?rev=346551&r1=346550&r2=346551&view=diff
==
--- cfe/trunk/lib/CodeGen/CGOpenMPRuntimeNVPTX.cpp (original)
+++ cfe/trunk/lib/CodeGen/CGOpenMPRuntimeNVPTX.cpp Fri Nov  9 12:03:19 2018
@@ -698,12 +698,58 @@ getDataSharingMode(CodeGenModule &CGM) {
   : CGOpenMPRuntimeNVPTX::Generic;
 }
 
+// Checks if the expression is constant or does not have non-trivial function
+// calls.
+static bool isTrivial(ASTContext &Ctx, const Expr * E) {
+  // We can skip constant expressions.
+  // We can skip expressions with trivial calls or simple expressions.
+  return (E->isEvaluatable(Ctx, Expr::SE_AllowUndefinedBehavior) ||
+  !E->hasNonTrivialCall(Ctx)) &&
+ !E->HasSideEffects(Ctx, /*IncludePossibleEffects=*/true);
+}
+
 /// Checks if the \p Body is the \a CompoundStmt and returns its child 
statement
-/// iff there is only one.
-static const Stmt *getSingleCompoundChild(const Stmt *Body) {
-  if (const auto *C = dyn_cast(Body))
-if (C->size() == 1)
-  return C->body_front();
+/// iff there is only one that is not evaluatable at the compile time.
+static const Stmt *getSingleCompoundChild(ASTContext &Ctx, const Stmt *Body) {
+  if (const auto *C = dyn_cast(Body)) {
+const Stmt *Child = nullptr;
+for (const Stmt *S : C->body()) {
+  if (const auto *E = dyn_cast(S)) {
+if (isTrivial(Ctx, E))
+  continue;
+  }
+  // Some of the statements can be ignored.
+  if (isa(S) || isa(S) || isa(S) ||
+  isa(S) || isa(S))
+continue;
+  // Analyze declarations.
+  if (const auto *DS = dyn_cast(S)) {
+if (llvm::all_of(DS->decls(), [&Ctx](const Decl *D) {
+  if (isa(D) || isa(D) ||
+  isa(D) || isa(D) ||
+  isa(D) || isa(D) ||
+  isa(D) ||
+  isa(D) ||
+  isa(D))
+return true;
+  const auto *VD = dyn_cast(D);
+  if (!VD)
+return false;
+  return VD->isConstexpr() ||
+ ((VD->getType().isTrivialType(Ctx) ||
+   VD->getType()->isReferenceType()) &&
+  (!VD->hasInit() || isTrivial(Ctx, VD->getInit(;
+}))
+  continue;
+  }
+  // Found multiple children - cannot get the one child only.
+  if (Child)
+return Body;
+  Child = S;
+}
+if (Child)
+  return Child;
+  }
   return Body;
 }
 
@@ -732,7 +778,7 @@ static bool hasNestedSPMDDirective(ASTCo
   const auto *CS = D.getInnermostCapturedStmt();
   const auto *Body =
   CS->getCapturedStmt()->IgnoreContainers(/*IgnoreCaptured=*/true);
-  const Stmt *ChildStmt = getSingleCompoundChild(Body);
+  const Stmt *ChildStmt = getSingleCompoundChild(Ctx, Body);
 
   if (const auto *NestedDir = dyn_cast(ChildStmt)) {
 OpenMPDirectiveKind DKind = NestedDir->getDirectiveKind();
@@ -746,7 +792,7 @@ static bool hasNestedSPMDDirective(ASTCo
 /*IgnoreCaptured=*/true);
 if (!Body)
   return false;
-ChildStmt = getSingleCompoundChild(Body);
+ChildStmt = getSingleCompoundChild(Ctx, Body);
 if (const auto *NND = dyn_cast(ChildStmt)) {
   DKind = NND->getDirectiveKind();
   if (isOpenMPParallelDirective(DKind) &&
@@ -905,7 +951,7 @@ static bool hasNestedLightweightDirectiv
   const auto *CS = D.getInnermostCapturedStmt();
   const auto *Body =
   CS->getCapturedStmt()->IgnoreContainers(/*IgnoreCaptured=*/true);
-  const Stmt *ChildStmt = getSingleCompoundChild(Body);
+  const Stmt *ChildStmt = getSingleCompoundChild(Ctx, Body);
 
   if (const auto *NestedDir = dyn_cast(ChildStmt)) {
 OpenMPDirectiveKind DKind = NestedDir->getDirectiveKind();
@@ -920,7 +966,7 @@ static b

[PATCH] D54344: [Clang][CodeGen][CXX]: Workaround __attribute((no_destroy)) crash/incorrect code generation.

2018-11-09 Thread Kristina Brooks via Phabricator via cfe-commits
kristina created this revision.
kristina added reviewers: rsmith, clang, JonasToth, EricWF, aaron.ballman.
Herald added subscribers: dexonsmith, mehdi_amini.
Herald added a reviewer: jfb.

Difficult to reproduce crash, attempted it in the test, it appears to not 
trigger it. I can consistently reproduce it when building a large project with 
this attribute added and can consistently crash it without the fix in place, 
however.

This avoids the codepath that should not be executed in the first place by 
rechecking `NoDestroyAttr` and bailing out instead of emitting incorrect code 
or causing an assert in assert enabled builds. This does not appear to cause 
any regressions for x86_64 test suite and my test is useless since it does not 
offer the needed coverage.

  clang-8: /SourceCache/llvm-trunk-8.0/include/llvm/Support/Casting.h:106: 
static bool llvm::isa_impl_cl::doit(const From *) [To = clang::CXXConstructorDecl, 
From = const clang::CXXMethodDecl *]: Assertion `Val && "isa<> used on a null 
pointer"' failed.
  
  -- asserts here, rest is signal handler/stack trace --
  
  #9 0x00d5a35d toCXXCtorType 
/SourceCache/llvm-trunk-8.0/tools/clang/lib/CodeGen/CodeGenTypes.h:66:3
  #10 0x00d5a35d 
clang::CodeGen::CodeGenModule::getAddrOfCXXStructor(clang::CXXMethodDecl 
const*, clang::CodeGen::StructorType, clang::CodeGen::CGFunctionInfo const*, 
llvm::FunctionType*, bool, clang::CodeGen::ForDefinition_t) 
/SourceCache/llvm-trunk-8.0/tools/clang/lib/CodeGen/CGCXX.cpp:237:0
  #11 0x00e05c9b Address 
/SourceCache/llvm-trunk-8.0/tools/clang/lib/CodeGen/Address.h:31:5
  #12 0x00e05c9b ConstantAddress 
/SourceCache/llvm-trunk-8.0/tools/clang/lib/CodeGen/Address.h:78:0
  #13 0x00e05c9b 
clang::CodeGen::CodeGenFunction::EmitCXXGlobalVarDeclInit(clang::VarDecl 
const&, llvm::Constant*, bool) 
/SourceCache/llvm-trunk-8.0/tools/clang/lib/CodeGen/CGDeclCXX.cpp:179:0
  #14 0x00e07b7a 
clang::CodeGen::CodeGenFunction::GenerateCXXGlobalVarDeclInitFunc(llvm::Function*,
 clang::VarDecl const*, llvm::GlobalVariable*, bool) 
/SourceCache/llvm-trunk-8.0/tools/clang/lib/CodeGen/CGDeclCXX.cpp:608:3
  #15 0x00e06fc8 
clang::CodeGen::CodeGenModule::EmitCXXGlobalVarDeclInitFunc(clang::VarDecl 
const*, llvm::GlobalVariable*, bool) 
/SourceCache/llvm-trunk-8.0/tools/clang/lib/CodeGen/CGDeclCXX.cpp:441:3
  #16 0x00b6596f 
clang::CodeGen::CodeGenModule::EmitGlobalVarDefinition(clang::VarDecl const*, 
bool) 
/SourceCache/llvm-trunk-8.0/tools/clang/lib/CodeGen/CodeGenModule.cpp:3650:5
  #17 0x00b5c66b 
clang::CodeGen::CodeGenModule::EmitGlobalDefinition(clang::GlobalDecl, 
llvm::GlobalValue*) 
/SourceCache/llvm-trunk-8.0/tools/clang/lib/CodeGen/CodeGenModule.cpp:0:12
  #18 0x00b67dfb getKind 
/SourceCache/llvm-trunk-8.0/tools/clang/include/clang/AST/DeclBase.h:421:51
  #19 0x00b67dfb classof 
/SourceCache/llvm-trunk-8.0/tools/clang/include/clang/AST/DeclCXX.h:3875:0
  #20 0x00b67dfb doit 
/SourceCache/llvm-trunk-8.0/include/llvm/Support/Casting.h:59:0
  #21 0x00b67dfb doit 
/SourceCache/llvm-trunk-8.0/include/llvm/Support/Casting.h:107:0
  #22 0x00b67dfb doit 
/SourceCache/llvm-trunk-8.0/include/llvm/Support/Casting.h:133:0
  #23 0x00b67dfb doit 
/SourceCache/llvm-trunk-8.0/include/llvm/Support/Casting.h:123:0
  #24 0x00b67dfb isa 
/SourceCache/llvm-trunk-8.0/include/llvm/Support/Casting.h:143:0
  #25 0x00b67dfb dyn_cast 
/SourceCache/llvm-trunk-8.0/include/llvm/Support/Casting.h:334:0
  #26 0x00b67dfb 
clang::CodeGen::CodeGenModule::EmitTopLevelDecl(clang::Decl*) 
/SourceCache/llvm-trunk-8.0/tools/clang/lib/CodeGen/CodeGenModule.cpp:4783:0
  #27 0x00b6bf7b getPointer 
/SourceCache/llvm-trunk-8.0/include/llvm/ADT/PointerIntPair.h:56:58
  #28 0x00b6bf7b getNextDeclInContext 
/SourceCache/llvm-trunk-8.0/tools/clang/include/clang/AST/DeclBase.h:424:0
  #29 0x00b6bf7b operator++ 
/SourceCache/llvm-trunk-8.0/tools/clang/include/clang/AST/DeclBase.h:1973:0
  #30 0x00b6bf7b 
clang::CodeGen::CodeGenModule::EmitDeclContext(clang::DeclContext const*) 
/SourceCache/llvm-trunk-8.0/tools/clang/lib/CodeGen/CodeGenModule.cpp:4744:0
  #31 0x0115a470 
_ZN12_GLOBAL__N_117CodeGeneratorImpl18HandleTopLevelDeclEN5clang12DeclGroupRefE$7cf5ba2c3e38da85712ae9dd9c2a6e32
 /SourceCache/llvm-trunk-8.0/tools/clang/lib/CodeGen/ModuleBuilder.cpp:159:73
  #32 0x0115833d 
clang::BackendConsumer::HandleTopLevelDecl(clang::DeclGroupRef) 
/SourceCache/llvm-trunk-8.0/tools/clang/lib/CodeGen/CodeGenAction.cpp:171:11
  #33 0x011642f4 clang::ParseAST(clang::Sema&, bool, bool) 
/SourceCache/llvm-trunk-8.0/tools/clang/lib/Parse/ParseAST.cpp:161:11
  #34 0x010c9d83 shouldBuildGlobalModuleIndex 
/SourceCache/llvm-trunk-8.0/tools/clang/lib/Frontend/CompilerInstance.cpp:81:11
  #35 0x010c9d83 clang::FrontendAction::Execute() 
/SourceCache/llvm-trunk-8.0/tools/clang/lib/Fr

[PATCH] D33029: [clang-format] add option for dangling parenthesis

2018-11-09 Thread Adam Van Prooyen via Phabricator via cfe-commits
sciencemanx added a comment.

@djasper bump -- this feature is also really important to our team.


https://reviews.llvm.org/D33029



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


[PATCH] D54344: [Clang][CodeGen][CXX]: Workaround __attribute((no_destroy)) crash/incorrect code generation.

2018-11-09 Thread Kristina Brooks via Phabricator via cfe-commits
kristina updated this revision to Diff 173411.
kristina added a comment.

Revised (style/ordering).


https://reviews.llvm.org/D54344

Files:
  lib/CodeGen/CGDeclCXX.cpp


Index: lib/CodeGen/CGDeclCXX.cpp
===
--- lib/CodeGen/CGDeclCXX.cpp
+++ lib/CodeGen/CGDeclCXX.cpp
@@ -64,10 +64,19 @@
 /// static storage duration.
 static void EmitDeclDestroy(CodeGenFunction &CGF, const VarDecl &D,
 ConstantAddress addr) {
-  CodeGenModule &CGM = CGF.CGM;
+  // Workaround for a bug that causes a reference to a nonexistent
+  // destructor under odd circumstances, when attribute no_destroy
+  // is used. This code should not be reachable under normal 
+  // circumstances, this workaround simply checks for the attribute
+  // again and bails if it's present instead of following a path
+  // that's either going to assert or emit incorrect code if reached.
+  if (D.hasAttr())
+return;
 
   // FIXME:  __attribute__((cleanup)) ?
 
+  CodeGenModule &CGM = CGF.CGM;
+
   QualType type = D.getType();
   QualType::DestructionKind dtorKind = type.isDestructedType();
 


Index: lib/CodeGen/CGDeclCXX.cpp
===
--- lib/CodeGen/CGDeclCXX.cpp
+++ lib/CodeGen/CGDeclCXX.cpp
@@ -64,10 +64,19 @@
 /// static storage duration.
 static void EmitDeclDestroy(CodeGenFunction &CGF, const VarDecl &D,
 ConstantAddress addr) {
-  CodeGenModule &CGM = CGF.CGM;
+  // Workaround for a bug that causes a reference to a nonexistent
+  // destructor under odd circumstances, when attribute no_destroy
+  // is used. This code should not be reachable under normal 
+  // circumstances, this workaround simply checks for the attribute
+  // again and bails if it's present instead of following a path
+  // that's either going to assert or emit incorrect code if reached.
+  if (D.hasAttr())
+return;
 
   // FIXME:  __attribute__((cleanup)) ?
 
+  CodeGenModule &CGM = CGF.CGM;
+
   QualType type = D.getType();
   QualType::DestructionKind dtorKind = type.isDestructedType();
 
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D52674: [AST] Add Obj-C discriminator to MS ABI RTTI

2018-11-09 Thread Reid Kleckner via Phabricator via cfe-commits
rnk added a comment.

Threading a new options argument through mangleType that includes 
QualifierMangleMode as well as these obj-c options seems reasonable.


Repository:
  rC Clang

https://reviews.llvm.org/D52674



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


[PATCH] D54307: [clang] overload ignoringParens for Expr

2018-11-09 Thread Jonas Toth via Phabricator via cfe-commits
JonasToth added inline comments.



Comment at: include/clang/ASTMatchers/ASTMatchers.h:814
 /// would match the declaration for fp.
-AST_MATCHER_P(QualType, ignoringParens,
-  internal::Matcher, InnerMatcher) {
+AST_MATCHER_P_OVERLOAD(QualType, ignoringParens, internal::Matcher,
+   InnerMatcher, 0) {

aaron.ballman wrote:
> sbenza wrote:
> > JonasToth wrote:
> > > aaron.ballman wrote:
> > > > JonasToth wrote:
> > > > > aaron.ballman wrote:
> > > > > > Can you do this via `AST_POLYMORPHIC_MATCHER_P` instead, given that 
> > > > > > the implementation is the same?
> > > > > Do you want me to add more types? e.g. `TypeLoc` has 
> > > > > `IgnoreParens()`, too. 
> > > > I'd not be opposed, given that we already expose the `typeLoc()` 
> > > > matcher. I'll leave that to your discretion.
> > > as discussed on IRC making it an `AST_POLYMORPHIC_MATCHER_P` does not 
> > > seem to work, as the polymorphism is only in the return type. We do need 
> > > the `Node` itself to be polymorphic (same type as returntype). The only 
> > > working version I got was using the overloads.
> > You can't use AST_POLYMORPHIC_MATCHER_P to overload on input types.
> > You could try using templates, but that will make registering the matcher 
> > harder.
> > Another one that does input+output polymorphism, `id`, is simply not 
> > supported dynamically.
> Good to know, thank you!
thanks for clarifying.


Repository:
  rC Clang

https://reviews.llvm.org/D54307



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


[PATCH] D54344: [Clang][CodeGen][CXX]: Workaround __attribute((no_destroy)) crash/incorrect code generation.

2018-11-09 Thread Erik Pilkington via Phabricator via cfe-commits
erik.pilkington added a reviewer: erik.pilkington.
erik.pilkington added a comment.

Have you tried running creduce on the preprocessed source? We should really 
have a real reproducer for this, otherwise its really hard to tell what the 
underlying problem is.


https://reviews.llvm.org/D54344



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


Re: [clang-tools-extra] r346461 - Ignore implicit things like ConstantExpr.

2018-11-09 Thread Bill Wendling via cfe-commits
This fix was submitted because a test was failing without it. :-)

On Thu, Nov 8, 2018 at 10:08 PM Roman Lebedev  wrote:

> Test?
>
> On Fri, Nov 9, 2018 at 4:34 AM Bill Wendling via cfe-commits
>  wrote:
> >
> > Author: void
> > Date: Thu Nov  8 17:32:30 2018
> > New Revision: 346461
> >
> > URL: http://llvm.org/viewvc/llvm-project?rev=346461&view=rev
> > Log:
> > Ignore implicit things like ConstantExpr.
> >
> > Modified:
> >
>  
> clang-tools-extra/trunk/clang-tidy/performance/NoexceptMoveConstructorCheck.cpp
> >
> > Modified:
> clang-tools-extra/trunk/clang-tidy/performance/NoexceptMoveConstructorCheck.cpp
> > URL:
> http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clang-tidy/performance/NoexceptMoveConstructorCheck.cpp?rev=346461&r1=346460&r2=346461&view=diff
> >
> ==
> > ---
> clang-tools-extra/trunk/clang-tidy/performance/NoexceptMoveConstructorCheck.cpp
> (original)
> > +++
> clang-tools-extra/trunk/clang-tidy/performance/NoexceptMoveConstructorCheck.cpp
> Thu Nov  8 17:32:30 2018
> > @@ -58,7 +58,8 @@ void NoexceptMoveConstructorCheck::check
> >  // where expr evaluates to false.
> >  if (ProtoType->canThrow() == CT_Can) {
> >Expr *E = ProtoType->getNoexceptExpr();
> > -  if (!isa(ProtoType->getNoexceptExpr())) {
> > +  E = E->IgnoreImplicit();
> > +  if (!isa(E)) {
> >  diag(E->getExprLoc(),
> >   "noexcept specifier on the move %0 evaluates to 'false'")
> >  << MethodType;
> >
> >
> > ___
> > cfe-commits mailing list
> > cfe-commits@lists.llvm.org
> > http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
>
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


Re: r346491 - [clang-cl] Add warning for /Zc:dllexportInlines- when the flag is used with /fallback

2018-11-09 Thread Nico Weber via cfe-commits
Ah cool. But the diagnostic is "option /dllexportInlines- is ignored when
/fallback happens" – shouldn't it be ignored regardless of if fallback
happens? Does that happen and the warning text is wrong?

On Fri, Nov 9, 2018 at 11:20 AM Hans Wennborg  wrote:

> On Fri, Nov 9, 2018 at 4:53 PM, Nico Weber  wrote:
> > This only prints the warning when /fallback actually happens, right?
>
> No, it prints it when the fallback job is created, not when (or if) it
> runs. I.e. it prints if the /fallback flag is used, regardless of
> whether it actually falls back or not. This is reflected by the test
> which uses -###, i.e. nothing is getting run.
>
> So I think we're good :-)
>
> > I don't
> > think that's good enough: If we build a few TUs with /dllexportInlines-
> and
> > don't fall back, those .obj files are not abi compatible with the
> cl-built
> > ones. (Consider all dllexport TUs of a header being built with clang-cl
> but
> > all dllimport versions of the same header being built by cl – I think
> this
> > will cause link errors). SO I think we should error out if
> > /dllexportIlnlines- /fallback is on the same line, even if the fallback
> > doesn't actually happen.
> >
> > On Fri, Nov 9, 2018 at 8:28 AM Takuto Ikuta via cfe-commits
> >  wrote:
> >>
> >> Author: tikuta
> >> Date: Fri Nov  9 05:25:45 2018
> >> New Revision: 346491
> >>
> >> URL: http://llvm.org/viewvc/llvm-project?rev=346491&view=rev
> >> Log:
> >> [clang-cl] Add warning for /Zc:dllexportInlines- when the flag is used
> >> with /fallback
> >>
> >> Summary:
> >> This is followup of
> >> https://reviews.llvm.org/D51340
> >>
> >> Reviewers: hans, thakis
> >>
> >> Reviewed By: hans
> >>
> >> Subscribers: cfe-commits, llvm-commits
> >>
> >> Differential Revision: https://reviews.llvm.org/D54298
> >>
> >> Modified:
> >> cfe/trunk/include/clang/Basic/DiagnosticDriverKinds.td
> >> cfe/trunk/lib/Driver/ToolChains/MSVC.cpp
> >> cfe/trunk/test/Driver/cl-options.c
> >>
> >> Modified: cfe/trunk/include/clang/Basic/DiagnosticDriverKinds.td
> >> URL:
> >>
> http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Basic/DiagnosticDriverKinds.td?rev=346491&r1=346490&r2=346491&view=diff
> >>
> >>
> ==
> >> --- cfe/trunk/include/clang/Basic/DiagnosticDriverKinds.td (original)
> >> +++ cfe/trunk/include/clang/Basic/DiagnosticDriverKinds.td Fri Nov  9
> >> 05:25:45 2018
> >> @@ -161,6 +161,10 @@ def warn_drv_yc_multiple_inputs_clang_cl
> >>"support for '/Yc' with more than one source file not implemented
> yet;
> >> flag ignored">,
> >>InGroup;
> >>
> >> +def warn_drv_non_fallback_argument_clang_cl : Warning<
> >> +  "option '%0' is ignored when /fallback happens">,
> >> +  InGroup;
> >> +
> >>  def err_drv_invalid_value : Error<"invalid value '%1' in '%0'">;
> >>  def err_drv_invalid_int_value : Error<"invalid integral value '%1' in
> >> '%0'">;
> >>  def err_drv_invalid_remap_file : Error<
> >>
> >> Modified: cfe/trunk/lib/Driver/ToolChains/MSVC.cpp
> >> URL:
> >>
> http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Driver/ToolChains/MSVC.cpp?rev=346491&r1=346490&r2=346491&view=diff
> >>
> >>
> ==
> >> --- cfe/trunk/lib/Driver/ToolChains/MSVC.cpp (original)
> >> +++ cfe/trunk/lib/Driver/ToolChains/MSVC.cpp Fri Nov  9 05:25:45 2018
> >> @@ -669,6 +669,12 @@ std::unique_ptr visualstudio::C
> >>// them too.
> >>Args.AddAllArgs(CmdArgs, options::OPT_UNKNOWN);
> >>
> >> +  // Warning for ignored flag.
> >> +  if (const Arg *dllexportInlines =
> >> +  Args.getLastArg(options::OPT__SLASH_Zc_dllexportInlines_))
> >> +
> >> C.getDriver().Diag(clang::diag::warn_drv_non_fallback_argument_clang_cl)
> >> +  << dllexportInlines->getAsString(Args);
> >> +
> >>// Input filename.
> >>assert(Inputs.size() == 1);
> >>const InputInfo &II = Inputs[0];
> >>
> >> Modified: cfe/trunk/test/Driver/cl-options.c
> >> URL:
> >>
> http://llvm.org/viewvc/llvm-project/cfe/trunk/test/Driver/cl-options.c?rev=346491&r1=346490&r2=346491&view=diff
> >>
> >>
> ==
> >> --- cfe/trunk/test/Driver/cl-options.c (original)
> >> +++ cfe/trunk/test/Driver/cl-options.c Fri Nov  9 05:25:45 2018
> >> @@ -494,6 +494,8 @@
> >>  // NoDllExportInlines: "-fno-dllexport-inlines"
> >>  // RUN: %clang_cl /Zc:dllexportInlines /c -### -- %s 2>&1 | FileCheck
> >> -check-prefix=DllExportInlines %s
> >>  // DllExportInlines-NOT: "-fno-dllexport-inlines"
> >> +// RUN: %clang_cl /fallback /Zc:dllexportInlines- /c -### -- %s 2>&1 |
> >> FileCheck -check-prefix=DllExportInlinesFallback %s
> >> +// DllExportInlinesFallback: warning: option '/Zc:dllexportInlines-' is
> >> ignored when /fallback happens [-Woption-ignored]
> >>
> >>  // RUN: %clang_cl /Zi /c -### -- %s 2>&1 | FileCheck -check-prefix=Zi
> %s
> >>  // Zi: "-gcodeview"
> >>
> >>
> >> 

[PATCH] D54307: [ASTMatchers] overload ignoringParens for Expr

2018-11-09 Thread Jonas Toth via Phabricator via cfe-commits
JonasToth updated this revision to Diff 173422.
JonasToth added a comment.

- add unit test


Repository:
  rC Clang

https://reviews.llvm.org/D54307

Files:
  docs/LibASTMatchersReference.html
  include/clang/ASTMatchers/ASTMatchers.h
  lib/ASTMatchers/Dynamic/Registry.cpp
  unittests/ASTMatchers/ASTMatchersNodeTest.cpp


Index: unittests/ASTMatchers/ASTMatchersNodeTest.cpp
===
--- unittests/ASTMatchers/ASTMatchersNodeTest.cpp
+++ unittests/ASTMatchers/ASTMatchersNodeTest.cpp
@@ -1147,6 +1147,14 @@
  parenExpr()));
 }
 
+TEST(ParenExpression, IgnoringParens) {
+  EXPECT_FALSE(matches("const char* str = (\"my-string\");",
+   
implicitCastExpr(hasSourceExpression(stringLiteral();
+  EXPECT_TRUE(matches(
+  "const char* str = (\"my-string\");",
+  implicitCastExpr(hasSourceExpression(ignoringParens(stringLiteral());
+}
+
 TEST(TypeMatching, MatchesTypes) {
   EXPECT_TRUE(matches("struct S {};", qualType().bind("loc")));
 }
Index: lib/ASTMatchers/Dynamic/Registry.cpp
===
--- lib/ASTMatchers/Dynamic/Registry.cpp
+++ lib/ASTMatchers/Dynamic/Registry.cpp
@@ -106,6 +106,7 @@
   REGISTER_OVERLOADED_2(callee);
   REGISTER_OVERLOADED_2(hasPrefix);
   REGISTER_OVERLOADED_2(hasType);
+  REGISTER_OVERLOADED_2(ignoringParens);
   REGISTER_OVERLOADED_2(isDerivedFrom);
   REGISTER_OVERLOADED_2(isSameOrDerivedFrom);
   REGISTER_OVERLOADED_2(loc);
@@ -318,7 +319,6 @@
   REGISTER_MATCHER(ignoringImplicit);
   REGISTER_MATCHER(ignoringParenCasts);
   REGISTER_MATCHER(ignoringParenImpCasts);
-  REGISTER_MATCHER(ignoringParens);
   REGISTER_MATCHER(imaginaryLiteral);
   REGISTER_MATCHER(implicitCastExpr);
   REGISTER_MATCHER(implicitValueInitExpr);
Index: include/clang/ASTMatchers/ASTMatchers.h
===
--- include/clang/ASTMatchers/ASTMatchers.h
+++ include/clang/ASTMatchers/ASTMatchers.h
@@ -811,11 +811,28 @@
 ///   varDecl(hasType(pointerType(pointee(ignoringParens(functionType())
 /// \endcode
 /// would match the declaration for fp.
-AST_MATCHER_P(QualType, ignoringParens,
-  internal::Matcher, InnerMatcher) {
+AST_MATCHER_P_OVERLOAD(QualType, ignoringParens, internal::Matcher,
+   InnerMatcher, 0) {
   return InnerMatcher.matches(Node.IgnoreParens(), Finder, Builder);
 }
 
+/// Overload \c ignoringParens for \c Expr.
+///
+/// Given
+/// \code
+///   const char* str = ("my-string");
+/// \endcode
+/// The matcher
+/// \code
+///   implicitCastExpr(hasSourceExpression(ignoringParens(stringLiteral(
+/// \endcode
+/// would match the implicit cast resulting from the assignment.
+AST_MATCHER_P_OVERLOAD(Expr, ignoringParens, internal::Matcher,
+   InnerMatcher, 1) {
+  const Expr *E = Node.IgnoreParens();
+  return InnerMatcher.matches(*E, Finder, Builder);
+}
+
 /// Matches expressions that are instantiation-dependent even if it is
 /// neither type- nor value-dependent.
 ///
Index: docs/LibASTMatchersReference.html
===
--- docs/LibASTMatchersReference.html
+++ docs/LibASTMatchersReference.html
@@ -5552,6 +5552,17 @@
 
 
 
+MatcherExpr>ignoringParensMatcherExpr> 
InnerMatcher
+Overload 
ignoringParens for Expr.
+
+Given
+  const char* str = ("my-string");
+The matcher
+  implicitCastExpr(hasSourceExpression(ignoringParens(stringLiteral(
+would match the implicit cast resulting from the assignment.
+
+
+
 MatcherFieldDecl>hasInClassInitializerMatcherExpr> 
InnerMatcher
 Matches 
non-static data members that have an in-class initializer.
 


Index: unittests/ASTMatchers/ASTMatchersNodeTest.cpp
===
--- unittests/ASTMatchers/ASTMatchersNodeTest.cpp
+++ unittests/ASTMatchers/ASTMatchersNodeTest.cpp
@@ -1147,6 +1147,14 @@
  parenExpr()));
 }
 
+TEST(ParenExpression, IgnoringParens) {
+  EXPECT_FALSE(matches("const char* str = (\"my-string\");",
+   implicitCastExpr(hasSourceExpression(stringLiteral();
+  EXPECT_TRUE(matches(
+  "const char* str = (\"my-string\");",
+  implicitCastExpr(hasSourceExpression(ignoringParens(stringLiteral());
+}
+
 TEST(TypeMatching, MatchesTypes) {
   EXPECT_TRUE(matches("struct S {};", qualType().bind("loc")));
 }
Index: lib/ASTMatchers/Dynamic/Registry.cpp
===
--- lib/ASTMatchers/Dynamic/Registry.cpp
+++ lib/ASTMatchers/Dynamic/Registry.cpp
@@ -106,6 +106,7 @@
   REGISTER_OVERLOADED_2(callee);
   REGISTER_OVERLOADED

  1   2   >