[PATCH] D59919: [Attributor] Deduce "returned" argument attribute

2019-03-28 Thread Johannes Doerfert via Phabricator via cfe-commits
jdoerfert created this revision.
jdoerfert added reviewers: homerdin, hfinkel, fedor.sergeev, sanjoy, spatel, 
nlopes, nicholas, reames.
Herald added subscribers: cfe-commits, bollu, hiraditya.
Herald added projects: clang, LLVM.

Deduce the "returned" argument attribute by collecting all potentially
returned values.

Note: Not only the unique return value, if any, can be used by
subsequent attributes but also the set of all potentially returned
values as well as the mapping from returned values to return
instructions that they originate from.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D59919

Files:
  clang/test/CodeGenOpenCL/as_type.cl
  llvm/include/llvm/Transforms/IPO/Attributor.h
  llvm/lib/Transforms/IPO/Attributor.cpp
  llvm/test/Transforms/FunctionAttrs/SCC1.ll
  llvm/test/Transforms/FunctionAttrs/arg_nocapture.ll
  llvm/test/Transforms/FunctionAttrs/arg_returned.ll

Index: llvm/test/Transforms/FunctionAttrs/arg_returned.ll
===
--- llvm/test/Transforms/FunctionAttrs/arg_returned.ll
+++ llvm/test/Transforms/FunctionAttrs/arg_returned.ll
@@ -1,4 +1,8 @@
-; RUN: opt -functionattrs -attributor -S < %s | FileCheck %s
+; RUN: opt -functionattrs -S < %s | FileCheck %s --check-prefix=FNATTR
+; RUN: opt -attributor -S < %s | FileCheck %s --check-prefix=ATTRIBUTOR
+; RUN: opt -attributor -functionattrs -S < %s | FileCheck %s --check-prefix=BOTH
+; RUN: opt -attributor -attributor-max-iterations=18 -S < %s | FileCheck %s --check-prefix=FEW_IT
+; RUN: opt -attributor -attributor-max-iterations=19 -functionattrs -S < %s | FileCheck %s --check-prefix=BOTH
 ;
 ; Test cases specifically designed for the "returned" argument attribute.
 ; We use FIXME's to indicate problems and missing attributes.
@@ -16,13 +20,20 @@
 
 ; TEST 1
 ;
-; CHECK: define dso_local i32 @sink_r0(i32 returned %r) [[NoInlineNoRecurseNoUnwindReadnoneUwtable:#[0-9]]]
+; BOTH: define dso_local i32 @sink_r0(i32 returned %r) [[NoInlineNoRecurseNoUnwindReadnoneUwtable:#[0-9]]]
+; BOTH: define dso_local i32 @scc_r1(i32 %a, i32 returned %r, i32 %b) [[NoInlineNoUnwindReadnoneUwtable:#[0-9]]]
+; BOTH: define dso_local i32 @scc_r2(i32 %a, i32 %b, i32 returned %r) [[NoInlineNoUnwindReadnoneUwtable]]
+; BOTH: define dso_local i32 @scc_rX(i32 %a, i32 %b, i32 %r) [[NoInlineNoUnwindReadnoneUwtable]]
 ;
-; FIXME: returned on %r missing:
-; CHECK: define dso_local i32 @scc_r1(i32 %a, i32 %r, i32 %b) [[NoInlineNoUnwindReadnoneUwtable:#[0-9]]]
+; FNATTR: define dso_local i32 @sink_r0(i32 returned %r) [[NoInlineNoRecurseNoUnwindReadnoneUwtable:#[0-9]]]
+; FNATTR: define dso_local i32 @scc_r1(i32 %a, i32 %r, i32 %b) [[NoInlineNoUnwindReadnoneUwtable:#[0-9]]]
+; FNATTR: define dso_local i32 @scc_r2(i32 %a, i32 %b, i32 %r) [[NoInlineNoUnwindReadnoneUwtable]]
+; FNATTR: define dso_local i32 @scc_rX(i32 %a, i32 %b, i32 %r) [[NoInlineNoUnwindReadnoneUwtable]]
 ;
-; FIXME: returned on %r missing:
-; CHECK: define dso_local i32 @scc_r2(i32 %a, i32 %b, i32 %r) [[NoInlineNoUnwindReadnoneUwtable]]
+; ATTRIBUTOR: define dso_local i32 @sink_r0(i32 returned %r) [[NoInlineNoRecurseNoUnwindReadnoneUwtable:#[0-9]]]
+; ATTRIBUTOR: define dso_local i32 @scc_r1(i32 %a, i32 returned %r, i32 %b) [[NoInlineNoUnwindReadnoneUwtable:#[0-9]]]
+; ATTRIBUTOR: define dso_local i32 @scc_r2(i32 %a, i32 %b, i32 returned %r) [[NoInlineNoUnwindReadnoneUwtable]]
+; ATTRIBUTOR: define dso_local i32 @scc_rX(i32 %a, i32 %b, i32 %r) [[NoInlineNoUnwindReadnoneUwtable]]
 ;
 ; int scc_r1(int a, int b, int r);
 ; int scc_r2(int a, int b, int r);
@@ -157,13 +168,17 @@
 
 ; TEST 2
 ;
-; CHECK: define dso_local double* @ptr_sink_r0(double* readnone returned %r) [[NoInlineNoRecurseNoUnwindReadnoneUwtable]]
+; BOTH: define dso_local double* @ptr_sink_r0(double* readnone returned %r) [[NoInlineNoRecurseNoUnwindReadnoneUwtable]]
+; BOTH: define dso_local double* @ptr_scc_r1(double* %a, double* readnone returned %r, double* nocapture readnone %b) [[NoInlineNoUnwindReadnoneUwtable]]
+; BOTH: define dso_local double* @ptr_scc_r2(double* readnone %a, double* readnone %b, double* readnone returned %r) [[NoInlineNoUnwindReadnoneUwtable]]
 ;
-; FIXME: returned on %r missing:
-; CHECK: define dso_local double* @ptr_scc_r1(double* %a, double* readnone %r, double* nocapture readnone %b) [[NoInlineNoUnwindReadnoneUwtable]]
+; FNATTR: define dso_local double* @ptr_sink_r0(double* readnone returned %r) [[NoInlineNoRecurseNoUnwindReadnoneUwtable]]
+; FNATTR: define dso_local double* @ptr_scc_r1(double* %a, double* readnone %r, double* nocapture readnone %b) [[NoInlineNoUnwindReadnoneUwtable]]
+; FNATTR: define dso_local double* @ptr_scc_r2(double* readnone %a, double* readnone %b, double* readnone %r) [[NoInlineNoUnwindReadnoneUwtable]]
 ;
-; FIXME: returned on %r missing:
-; CHECK: define dso_local double* @ptr_scc_r2(double* readnone %a, double* readnone %b, double* readnone %r) [[NoInlineNoUnwindReadnoneUwtable]]
+; ATTRIBUTOR: define dso

[PATCH] D59798: [WIP] Add analyzer option to limit the number of imported TUs

2019-03-28 Thread Endre Fülöp via Phabricator via cfe-commits
gamesh411 updated this revision to Diff 192571.
gamesh411 added a comment.

Updated option handling location to use AnalyzerOptions instead of CC1


Repository:
  rC Clang

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D59798/new/

https://reviews.llvm.org/D59798

Files:
  include/clang/CrossTU/CrossTranslationUnit.h
  include/clang/StaticAnalyzer/Core/AnalyzerOptions.def
  lib/CrossTU/CrossTranslationUnit.cpp
  lib/StaticAnalyzer/Core/CallEvent.cpp
  test/Analysis/analyzer-config.c
  test/Analysis/ctu-import-threshold.c
  unittests/CrossTU/CrossTranslationUnitTest.cpp

Index: unittests/CrossTU/CrossTranslationUnitTest.cpp
===
--- unittests/CrossTU/CrossTranslationUnitTest.cpp
+++ unittests/CrossTU/CrossTranslationUnitTest.cpp
@@ -23,8 +23,9 @@
 
 class CTUASTConsumer : public clang::ASTConsumer {
 public:
-  explicit CTUASTConsumer(clang::CompilerInstance &CI, bool *Success)
-  : CTU(CI), Success(Success) {}
+  explicit CTUASTConsumer(clang::CompilerInstance &CI, bool *Success,
+  unsigned ImportLimit)
+  : CTU(CI), Success(Success), ImportLimit(ImportLimit) {}
 
   void HandleTranslationUnit(ASTContext &Ctx) {
 const TranslationUnitDecl *TU = Ctx.getTranslationUnitDecl();
@@ -70,41 +71,54 @@
 EXPECT_TRUE(llvm::sys::fs::exists(ASTFileName));
 
 // Load the definition from the AST file.
-llvm::Expected NewFDorError =
-CTU.getCrossTUDefinition(FD, "", IndexFileName);
-EXPECT_TRUE((bool)NewFDorError);
-const FunctionDecl *NewFD = *NewFDorError;
+llvm::Expected NewFDorError = handleExpected(
+CTU.getCrossTUDefinition(FD, "", IndexFileName, false, ImportLimit),
+[]() { return nullptr; }, [](IndexError &) {});
 
-*Success = NewFD && NewFD->hasBody() && !OrigFDHasBody;
+if (NewFDorError) {
+  const FunctionDecl *NewFD = *NewFDorError;
+  *Success = NewFD && NewFD->hasBody() && !OrigFDHasBody;
+}
   }
 
 private:
   CrossTranslationUnitContext CTU;
   bool *Success;
+  unsigned ImportLimit;
 };
 
 class CTUAction : public clang::ASTFrontendAction {
 public:
-  CTUAction(bool *Success) : Success(Success) {}
+  CTUAction(bool *Success, unsigned ImportLimit)
+  : Success(Success), ImportLimit(ImportLimit) {}
 
 protected:
   std::unique_ptr
   CreateASTConsumer(clang::CompilerInstance &CI, StringRef) override {
-return llvm::make_unique(CI, Success);
+return llvm::make_unique(CI, Success, ImportLimit);
   }
 
 private:
   bool *Success;
+  unsigned ImportLimit;
 };
 
 } // end namespace
 
 TEST(CrossTranslationUnit, CanLoadFunctionDefinition) {
   bool Success = false;
-  EXPECT_TRUE(tooling::runToolOnCode(new CTUAction(&Success), "int f(int);"));
+  EXPECT_TRUE(
+  tooling::runToolOnCode(new CTUAction(&Success, 1u), "int f(int);"));
   EXPECT_TRUE(Success);
 }
 
+TEST(CrossTranslationUnit, RespectsLoadThreshold) {
+  bool Success = false;
+  EXPECT_TRUE(
+  tooling::runToolOnCode(new CTUAction(&Success, 0u), "int f(int);"));
+  EXPECT_FALSE(Success);
+}
+
 TEST(CrossTranslationUnit, IndexFormatCanBeParsed) {
   llvm::StringMap Index;
   Index["a"] = "/b/f1";
Index: test/Analysis/ctu-import-threshold.c
===
--- /dev/null
+++ test/Analysis/ctu-import-threshold.c
@@ -0,0 +1,5 @@
+// Ensure analyzer option 'ctu-import-threshold' is a recognized option.
+//
+// RUN: %clang_cc1 -analyze -analyzer-config ctu-import-threshold=30 -verify %s
+//
+// expected-no-diagnostics
Index: test/Analysis/analyzer-config.c
===
--- test/Analysis/analyzer-config.c
+++ test/Analysis/analyzer-config.c
@@ -20,6 +20,7 @@
 // CHECK-NEXT: cfg-temporary-dtors = true
 // CHECK-NEXT: crosscheck-with-z3 = false
 // CHECK-NEXT: ctu-dir = ""
+// CHECK-NEXT: ctu-import-threshold = 100
 // CHECK-NEXT: ctu-index-name = externalDefMap.txt
 // CHECK-NEXT: display-ctu-progress = false
 // CHECK-NEXT: eagerly-assume = true
@@ -52,4 +53,4 @@
 // CHECK-NEXT: unroll-loops = false
 // CHECK-NEXT: widen-loops = false
 // CHECK-NEXT: [stats]
-// CHECK-NEXT: num-entries = 49
+// CHECK-NEXT: num-entries = 50
Index: lib/StaticAnalyzer/Core/CallEvent.cpp
===
--- lib/StaticAnalyzer/Core/CallEvent.cpp
+++ lib/StaticAnalyzer/Core/CallEvent.cpp
@@ -572,7 +572,8 @@
   *Engine.getCrossTranslationUnitContext();
   llvm::Expected CTUDeclOrError =
   CTUCtx.getCrossTUDefinition(FD, Opts.CTUDir, Opts.CTUIndexName,
-  Opts.DisplayCTUProgress);
+  Opts.DisplayCTUProgress,
+  Opts.CTUImportThreshold);
 
   if (!CTUDeclOrError) {
 handleAllErrors(CTUDeclOrError.takeError(),
Index: lib/CrossTU/CrossTranslationUnit.cpp
===
--- lib/Cros

[PATCH] D59802: [clang-tidy] Add new checker: llvm-avoid-cast-in-conditional

2019-03-28 Thread Don Hinton via Phabricator via cfe-commits
hintonda added a comment.

I looked at the IR generated at `-O2`, and found that while `if (isa(y))` is 
a modest win over `if (dyn_cast(y)`,  `if (dyn_cast_or_null(y))` 
generates exactly the same IR that `if(y && isa(y))` does.  Also, if `y` is 
actually an expression that makes a function call, it's more expensive because 
it will make the call twice.

So I don't seen any reason to replace `dyn_cast_or_null<>` in conditionals.


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D59802/new/

https://reviews.llvm.org/D59802



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


r357150 - [Driver] Allow -gsplit-dwarf on ELF OSes other than Linux and Fuchsia

2019-03-28 Thread Fangrui Song via cfe-commits
Author: maskray
Date: Thu Mar 28 01:24:00 2019
New Revision: 357150

URL: http://llvm.org/viewvc/llvm-project?rev=357150&view=rev
Log:
[Driver] Allow -gsplit-dwarf on ELF OSes other than Linux and Fuchsia

In gcc, -gsplit-dwarf is handled in gcc/gcc.c as a spec
(ASM_FINAL_SPEC): objcopy --extract-dwo + objcopy --strip-dwo. In
gcc/opts.c, -gsplit_dwarf has the same semantic of a -g. Except for the
availability of the external command 'objcopy', nothing precludes the
feature working on other ELF OSes. llvm doesn't use objcopy, so it doesn't
have to exclude other OSes.

Modified:
cfe/trunk/lib/Driver/ToolChains/Clang.cpp
cfe/trunk/test/Driver/split-debug.c

Modified: cfe/trunk/lib/Driver/ToolChains/Clang.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Driver/ToolChains/Clang.cpp?rev=357150&r1=357149&r2=357150&view=diff
==
--- cfe/trunk/lib/Driver/ToolChains/Clang.cpp (original)
+++ cfe/trunk/lib/Driver/ToolChains/Clang.cpp Thu Mar 28 01:24:00 2019
@@ -3260,8 +3260,7 @@ static void RenderDebugOptions(const Too
 
   // -gsplit-dwarf should turn on -g and enable the backend dwarf
   // splitting and extraction.
-  // FIXME: Currently only works on Linux and Fuchsia.
-  if (T.isOSLinux() || T.isOSFuchsia()) {
+  if (T.isOSBinFormatELF()) {
 if (!SplitDWARFInlining)
   CmdArgs.push_back("-fno-split-dwarf-inlining");
 
@@ -4077,7 +4076,7 @@ void Clang::ConstructJob(Compilation &C,
   // Add the split debug info name to the command lines here so we
   // can propagate it to the backend.
   bool SplitDWARF = (DwarfFission != DwarfFissionKind::None) &&
-(RawTriple.isOSLinux() || RawTriple.isOSFuchsia()) &&
+TC.getTriple().isOSBinFormatELF() &&
 (isa(JA) || isa(JA) ||
  isa(JA));
   const char *SplitDWARFOut;
@@ -6134,8 +6133,8 @@ void ClangAs::ConstructJob(Compilation &
 
   const llvm::Triple &T = getToolChain().getTriple();
   Arg *A;
-  if ((getDebugFissionKind(D, Args, A) == DwarfFissionKind::Split) &&
-  (T.isOSLinux() || T.isOSFuchsia())) {
+  if (getDebugFissionKind(D, Args, A) == DwarfFissionKind::Split &&
+  T.isOSBinFormatELF()) {
 CmdArgs.push_back("-split-dwarf-file");
 CmdArgs.push_back(SplitDebugName(Args, Input, Output));
   }

Modified: cfe/trunk/test/Driver/split-debug.c
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/Driver/split-debug.c?rev=357150&r1=357149&r2=357150&view=diff
==
--- cfe/trunk/test/Driver/split-debug.c (original)
+++ cfe/trunk/test/Driver/split-debug.c Thu Mar 28 01:24:00 2019
@@ -35,6 +35,9 @@
 // RUN: %clang -target x86_64-unknown-linux-gnu -gsplit-dwarf -c -### %s 2> %t
 // RUN: FileCheck -check-prefix=CHECK-OPTION < %t %s
 //
+// RUN: %clang -target x86_64-pc-freebsd12 -gsplit-dwarf -c -### %s 2> %t
+// RUN: FileCheck -check-prefix=CHECK-OPTION < %t %s
+//
 // CHECK-OPTION: "-split-dwarf-file" "split-debug.dwo"
 
 // RUN: %clang -target x86_64-unknown-linux-gnu -gsplit-dwarf -S -### %s 2> %t


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


[PATCH] D59922: [Attributor] Deduce "no-capture" argument attribute

2019-03-28 Thread Johannes Doerfert via Phabricator via cfe-commits
jdoerfert created this revision.
jdoerfert added reviewers: homerdin, hfinkel, fedor.sergeev, sanjoy, spatel, 
nlopes, nicholas, reames.
Herald added subscribers: cfe-commits, bollu, hiraditya.
Herald added projects: clang, LLVM.

Add the no-capture argument attribute deduction to the Attributor
fixpoint framework.

The new string attributed "no-capture-maybe-returned" is introduced to
allow deduction of no-capture through functions that "capture" an
argument but only by "returning" it.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D59922

Files:
  clang/test/CodeGenObjC/os_log.m
  clang/test/CodeGenOpenCL/as_type.cl
  llvm/include/llvm/Transforms/IPO/Attributor.h
  llvm/lib/Transforms/IPO/Attributor.cpp
  llvm/test/Transforms/FunctionAttrs/2009-01-02-LocalStores.ll
  llvm/test/Transforms/FunctionAttrs/SCC1.ll
  llvm/test/Transforms/FunctionAttrs/arg_nocapture.ll
  llvm/test/Transforms/FunctionAttrs/arg_returned.ll
  llvm/test/Transforms/FunctionAttrs/incompatible_fn_attrs.ll
  llvm/test/Transforms/FunctionAttrs/nocapture.ll
  llvm/test/Transforms/FunctionAttrs/readattrs.ll

Index: llvm/test/Transforms/FunctionAttrs/readattrs.ll
===
--- llvm/test/Transforms/FunctionAttrs/readattrs.ll
+++ llvm/test/Transforms/FunctionAttrs/readattrs.ll
@@ -12,7 +12,7 @@
   ret void
 }
 
-; CHECK: define i8* @test2(i8* readnone returned %p)
+; CHECK: define i8* @test2(i8* readnone returned "no-capture-maybe-returned" %p)
 define i8* @test2(i8* %p) {
   store i32 0, i32* @x
   ret i8* %p
@@ -54,13 +54,13 @@
   ret void
 }
 
-; CHECK: define i32* @test8_1(i32* readnone returned %p)
+; CHECK: define i32* @test8_1(i32* readnone returned "no-capture-maybe-returned" %p)
 define i32* @test8_1(i32* %p) {
 entry:
   ret i32* %p
 }
 
-; CHECK: define void @test8_2(i32* %p)
+; CHECK: define void @test8_2(i32* nocapture %p)
 define void @test8_2(i32* %p) {
 entry:
   %call = call i32* @test8_1(i32* %p)
Index: llvm/test/Transforms/FunctionAttrs/nocapture.ll
===
--- llvm/test/Transforms/FunctionAttrs/nocapture.ll
+++ llvm/test/Transforms/FunctionAttrs/nocapture.ll
@@ -3,7 +3,7 @@
 
 @g = global i32* null		;  [#uses=1]
 
-; CHECK: define i32* @c1(i32* readnone returned %q)
+; CHECK: define i32* @c1(i32* readnone returned "no-capture-maybe-returned" %q)
 define i32* @c1(i32* %q) {
 	ret i32* %q
 }
@@ -134,7 +134,7 @@
 	ret void
 }
 
-; CHECK: define void @test1_1(i8* nocapture readnone %x1_1, i8* %y1_1)
+; CHECK: define void @test1_1(i8* nocapture %x1_1, i8* nocapture %y1_1)
 ; It would be acceptable to add readnone to %y1_1 and %y1_2.
 define void @test1_1(i8* %x1_1, i8* %y1_1) {
   call i8* @test1_2(i8* %x1_1, i8* %y1_1)
@@ -142,7 +142,7 @@
   ret void
 }
 
-; CHECK: define i8* @test1_2(i8* nocapture readnone %x1_2, i8* returned %y1_2)
+; CHECK: define i8* @test1_2(i8* nocapture %x1_2, i8* returned "no-capture-maybe-returned" %y1_2)
 define i8* @test1_2(i8* %x1_2, i8* %y1_2) {
   call void @test1_1(i8* %x1_2, i8* %y1_2)
   store i32* null, i32** @g
@@ -156,21 +156,21 @@
   ret void
 }
 
-; CHECK: define void @test3(i8* nocapture readnone %x3, i8* nocapture readnone %y3, i8* nocapture readnone %z3)
+; CHECK: define void @test3(i8* nocapture %x3, i8* nocapture readnone %y3, i8* nocapture %z3)
 define void @test3(i8* %x3, i8* %y3, i8* %z3) {
   call void @test3(i8* %z3, i8* %y3, i8* %x3)
   store i32* null, i32** @g
   ret void
 }
 
-; CHECK: define void @test4_1(i8* %x4_1)
+; CHECK: define void @test4_1(i8* nocapture readnone %x4_1)
 define void @test4_1(i8* %x4_1) {
   call i8* @test4_2(i8* %x4_1, i8* %x4_1, i8* %x4_1)
   store i32* null, i32** @g
   ret void
 }
 
-; CHECK: define i8* @test4_2(i8* nocapture readnone %x4_2, i8* readnone returned %y4_2, i8* nocapture readnone %z4_2)
+; CHECK: define i8* @test4_2(i8* nocapture readnone %x4_2, i8* readnone returned "no-capture-maybe-returned" %y4_2, i8* nocapture readnone %z4_2)
 define i8* @test4_2(i8* %x4_2, i8* %y4_2, i8* %z4_2) {
   call void @test4_1(i8* null)
   store i32* null, i32** @g
Index: llvm/test/Transforms/FunctionAttrs/incompatible_fn_attrs.ll
===
--- llvm/test/Transforms/FunctionAttrs/incompatible_fn_attrs.ll
+++ llvm/test/Transforms/FunctionAttrs/incompatible_fn_attrs.ll
@@ -6,21 +6,21 @@
 
 ; Function Attrs: argmemonly
 define i32* @given_argmem_infer_readnone(i32* %p) #0 {
-; CHECK: define i32* @given_argmem_infer_readnone(i32* readnone returned %p) #0 {
+; CHECK: define i32* @given_argmem_infer_readnone(i32* readnone returned "no-capture-maybe-returned" %p) #0 {
 entry:
   ret i32* %p
 }
 
 ; Function Attrs: inaccessiblememonly
 define i32* @given_inaccessible_infer_readnone(i32* %p) #1 {
-; CHECK: define i32* @given_inaccessible_infer_readnone(i32* readnone returned %p) #0 {
+; CHECK: define i32* @given_inaccessible_infer_readnone(i32* readnone returned "no-captur

[PATCH] D59802: [clang-tidy] Add new checker: llvm-avoid-cast-in-conditional

2019-03-28 Thread Don Hinton via Phabricator via cfe-commits
hintonda updated this revision to Diff 192577.
hintonda added a comment.

- Removed the dyn_cast_or_null replacements.


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D59802/new/

https://reviews.llvm.org/D59802

Files:
  clang-tools-extra/clang-tidy/llvm/AvoidCastInConditionalCheck.cpp
  clang-tools-extra/clang-tidy/llvm/AvoidCastInConditionalCheck.h
  clang-tools-extra/clang-tidy/llvm/CMakeLists.txt
  clang-tools-extra/clang-tidy/llvm/LLVMTidyModule.cpp
  clang-tools-extra/clang-tidy/utils/HeaderFileExtensionsUtils.h
  clang-tools-extra/docs/ReleaseNotes.rst
  clang-tools-extra/docs/clang-tidy/checks/list.rst
  clang-tools-extra/docs/clang-tidy/checks/llvm-avoid-cast-in-conditional.rst
  clang-tools-extra/test/clang-tidy/llvm-avoid-cast-in-conditional.cpp
  clang/include/clang/Basic/LLVM.h

Index: clang/include/clang/Basic/LLVM.h
===
--- clang/include/clang/Basic/LLVM.h
+++ clang/include/clang/Basic/LLVM.h
@@ -31,6 +31,7 @@
   template class ArrayRef;
   template class MutableArrayRef;
   template class OwningArrayRef;
+  template  class SmallSet;
   template class SmallString;
   template class SmallVector;
   template class SmallVectorImpl;
@@ -66,6 +67,7 @@
   using llvm::Optional;
   using llvm::OwningArrayRef;
   using llvm::SaveAndRestore;
+  using llvm::SmallSet;
   using llvm::SmallString;
   using llvm::SmallVector;
   using llvm::SmallVectorImpl;
Index: clang-tools-extra/test/clang-tidy/llvm-avoid-cast-in-conditional.cpp
===
--- /dev/null
+++ clang-tools-extra/test/clang-tidy/llvm-avoid-cast-in-conditional.cpp
@@ -0,0 +1,74 @@
+// RUN: %check_clang_tidy %s llvm-avoid-cast-in-conditional %t
+
+struct X;
+struct Y;
+struct Z {
+  int foo();
+};
+
+template 
+bool isa(Y *);
+template 
+X *cast(Y *);
+template 
+X *dyn_cast(Y *);
+template 
+X *dyn_cast_or_null(Y *);
+
+bool foo(Y *y) {
+  if (auto x = cast(y))
+return true;
+  // CHECK-MESSAGES: :[[@LINE-2]]:16: warning: {{cast<> in conditional .*llvm-avoid-cast-in-conditional}}
+  // CHECK-FIXES: if (auto x = dyn_cast(y))
+
+  if (cast(y))
+return true;
+  // CHECK-MESSAGES: :[[@LINE-2]]:7: warning:  {{cast<> in conditional .*llvm-avoid-cast-in-conditional}}
+  // CHECK-FIXES: if (isa(y))
+
+  if (dyn_cast(y))
+return true;
+  // CHECK-MESSAGES: :[[@LINE-2]]:7: warning:  {{.*dyn_cast<> not used .*llvm-avoid-cast-in-conditional}}
+  // CHECK-FIXES: if (isa(y))
+
+  // These don't trigger a warning.
+  if (auto x = cast(y)->foo())
+return true;
+  if (cast(y)->foo())
+return true;
+
+  while (auto x = cast(y))
+break;
+  // CHECK-MESSAGES: :[[@LINE-2]]:19: warning:  {{cast<> in conditional .*llvm-avoid-cast-in-conditional}}
+  // CHECK-FIXES: while (auto x = dyn_cast(y))
+
+  while (cast(y))
+break;
+  // CHECK-MESSAGES: :[[@LINE-2]]:10: warning:  {{cast<> in conditional .*llvm-avoid-cast-in-conditional}}
+  // CHECK-FIXES: while (isa(y))
+
+  while (dyn_cast(y))
+break;
+  // CHECK-MESSAGES: :[[@LINE-2]]:10: warning:  {{.*dyn_cast<> not used .*llvm-avoid-cast-in-conditional}}
+  // CHECK-FIXES: while (isa(y))
+
+  // These don't trigger a warning.
+  while (auto x = cast(y)->foo())
+break;
+  while (cast(y)->foo())
+break;
+
+  do {
+break;
+  } while (cast(y));
+  // CHECK-MESSAGES: :[[@LINE-1]]:12: warning:  {{cast<> in conditional .*llvm-avoid-cast-in-conditional}}
+  // CHECK-FIXES: while (isa(y));
+
+  do {
+break;
+  } while (dyn_cast(y));
+  // CHECK-MESSAGES: :[[@LINE-1]]:12: warning:  {{.*dyn_cast<> not used .*llvm-avoid-cast-in-conditional}}
+  // CHECK-FIXES: while (isa(y));
+
+  return false;
+}
Index: clang-tools-extra/docs/clang-tidy/checks/llvm-avoid-cast-in-conditional.rst
===
--- /dev/null
+++ clang-tools-extra/docs/clang-tidy/checks/llvm-avoid-cast-in-conditional.rst
@@ -0,0 +1,28 @@
+.. title:: clang-tidy - llvm-avoid-cast-in-conditional
+
+llvm-avoid-cast-in-conditional
+==
+
+  Finds uses of ``cast<>`` in conditionals of ``if``, ``while`` or
+  ``do`` statements, which will assert rather than return a null
+  pointer. It also finds uses of ``dyn_cast<>`` in conditionals where
+  the return value is not captured.
+
+.. code-block:: c++
+
+  // Finds these:
+  if (auto x = cast(y)) {}
+  // is replaced by:
+  if (auto x = dyn_cast(y)) {}
+
+  if (cast(y)) {}
+  // is replaced by:
+  if (isa(y)) {}
+
+  if (dyn_cast(y)) {}
+  // is replaced by:
+  if (isa(y)) {}
+
+  // These are ignored.
+  if (auto f = cast(y)->foo()) {}
+  if (cast(y)->foo()) {}
Index: clang-tools-extra/docs/clang-tidy/checks/list.rst
===
--- clang-tools-extra/docs/clang-tidy/checks/list.rst
+++ clang-tools-extra/docs/clang-tidy/checks/list.rst
@@ -175,6 +175,7 @@
hicpp-use-nullptr (re

r357151 - Fix tests after rC357150

2019-03-28 Thread Fangrui Song via cfe-commits
Author: maskray
Date: Thu Mar 28 01:41:17 2019
New Revision: 357151

URL: http://llvm.org/viewvc/llvm-project?rev=357151&view=rev
Log:
Fix tests after rC357150

Modified:
cfe/trunk/test/Driver/cuda-unsupported-debug-options.cu
cfe/trunk/test/Driver/openmp-unsupported-debug-options.c

Modified: cfe/trunk/test/Driver/cuda-unsupported-debug-options.cu
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/Driver/cuda-unsupported-debug-options.cu?rev=357151&r1=357150&r2=357151&view=diff
==
--- cfe/trunk/test/Driver/cuda-unsupported-debug-options.cu (original)
+++ cfe/trunk/test/Driver/cuda-unsupported-debug-options.cu Thu Mar 28 01:41:17 
2019
@@ -17,6 +17,6 @@
 // CHECK: debug information option 
'{{-gz|-fdebug-info-for-profiling|-gsplit-dwarf|-glldb|-gcodeview|-gmodules|-gembed-source|-fdebug-macro|-ggnu-pubnames|-gdwarf-aranges|-fdebug-types-section}}'
 is not supported for target 'nvptx64-nvidia-cuda' [-Wunsupported-target-opt]
 // CHECK-NOT: debug information option '{{.*}}' is not supported for target 
'x86
 // CHECK: "-triple" "nvptx64-nvidia-cuda"
-// CHECK-NOT: 
{{-compress-debug|-fdebug-info-for-profiling|split-dwarf|lldb|codeview|module-format|embed-source|debug-info-macro|gnu-pubnames|generate-arange-section|generate-type-units}}
+// CHECK-NOT: 
{{-compress-debug|-fdebug-info-for-profiling|lldb|codeview|module-format|embed-source|debug-info-macro|gnu-pubnames|generate-arange-section|generate-type-units}}
 // CHECK: "-triple" "x86_64
 // CHECK-SAME: 
{{-compress-debug|-fdebug-info-for-profiling|split-dwarf|lldb|codeview|module-format|embed-source|debug-info-macro|gnu-pubnames|generate-arange-section|generate-type-units}}

Modified: cfe/trunk/test/Driver/openmp-unsupported-debug-options.c
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/Driver/openmp-unsupported-debug-options.c?rev=357151&r1=357150&r2=357151&view=diff
==
--- cfe/trunk/test/Driver/openmp-unsupported-debug-options.c (original)
+++ cfe/trunk/test/Driver/openmp-unsupported-debug-options.c Thu Mar 28 
01:41:17 2019
@@ -17,6 +17,6 @@
 // CHECK: debug information option 
'{{-gz|-fdebug-info-for-profiling|-gsplit-dwarf|-glldb|-gcodeview|-gmodules|-gembed-source|-fdebug-macro|-ggnu-pubnames|-gdwarf-aranges|-fdebug-types-section}}'
 is not supported for target 'nvptx64-nvidia-cuda' [-Wunsupported-target-opt]
 // CHECK-NOT: debug information option '{{.*}}' is not supported for target 
'x86
 // CHECK: "-triple" "nvptx64-nvidia-cuda"
-// CHECK-NOT: 
{{-compress-debug|-fdebug-info-for-profiling|split-dwarf|lldb|codeview|module-format|embed-source|debug-info-macro|gnu-pubnames|generate-arange-section|generate-type-units}}
+// CHECK-NOT: 
{{-compress-debug|-fdebug-info-for-profiling|lldb|codeview|module-format|embed-source|debug-info-macro|gnu-pubnames|generate-arange-section|generate-type-units}}
 // CHECK: "-triple" "x86_64
 // CHECK-SAME: 
{{-compress-debug|-fdebug-info-for-profiling|split-dwarf|lldb|codeview|module-format|embed-source|debug-info-macro|gnu-pubnames|generate-arange-section|generate-type-units}}


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


[PATCH] D59870: [clang-tidy] Add MagnitudeBitsUpperLimit option to bugprone-too-small-loop-variable

2019-03-28 Thread Tamás Zolnai via Phabricator via cfe-commits
ztamas updated this revision to Diff 192582.
ztamas added a comment.

Rebased patch on https://github.com/llvm/llvm-project.git repo.
Updated the docs based on review comments.


CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D59870/new/

https://reviews.llvm.org/D59870

Files:
  clang-tools-extra/clang-tidy/bugprone/TooSmallLoopVariableCheck.cpp
  clang-tools-extra/clang-tidy/bugprone/TooSmallLoopVariableCheck.h
  clang-tools-extra/docs/ReleaseNotes.rst
  clang-tools-extra/docs/clang-tidy/checks/bugprone-too-small-loop-variable.rst
  
clang-tools-extra/test/clang-tidy/bugprone-too-small-loop-variable-magniute-bits-upper-limit.cpp

Index: clang-tools-extra/test/clang-tidy/bugprone-too-small-loop-variable-magniute-bits-upper-limit.cpp
===
--- /dev/null
+++ clang-tools-extra/test/clang-tidy/bugprone-too-small-loop-variable-magniute-bits-upper-limit.cpp
@@ -0,0 +1,31 @@
+// RUN: %check_clang_tidy %s bugprone-too-small-loop-variable %t -- \
+// RUN:   -config="{CheckOptions: \
+// RUN: [{key: bugprone-too-small-loop-variable.MagnitudeBitsUpperLimit, \
+// RUN:   value: 31}]}" \
+// RUN:   -- --target=x86_64-linux
+
+unsigned long size() { return 294967296l; }
+
+void voidFilteredOutForLoop1() {
+  for (long i = 0; i < size(); ++i) {
+// no warning
+  }
+}
+
+void voidFilteredOutForLoop2() {
+  for (unsigned i = 0; i < size(); ++i) {
+// no warning
+  }
+}
+
+void voidCaughtForLoop1() {
+  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 long' [bugprone-too-small-loop-variable]
+  }
+}
+
+void voidCaughtForLoop2() {
+  for (short i = 0; i < size(); ++i) {
+// CHECK-MESSAGES: :[[@LINE-1]]:21: warning: loop variable has narrower type 'short' than iteration's upper bound 'unsigned long' [bugprone-too-small-loop-variable]
+  }
+}
Index: clang-tools-extra/docs/clang-tidy/checks/bugprone-too-small-loop-variable.rst
===
--- clang-tools-extra/docs/clang-tidy/checks/bugprone-too-small-loop-variable.rst
+++ clang-tools-extra/docs/clang-tidy/checks/bugprone-too-small-loop-variable.rst
@@ -27,3 +27,20 @@
 
 This algorithm works for small amount of objects, but will lead to freeze for a
 a larger user input.
+
+.. option:: MagnitudeBitsUpperLimit
+
+  Upper limit for the magnitue bits of the loop variable. If it's set the check
+  filters out those catches in which the loop variable's type has more magnitude
+  bits as the specified upper limit.
+  For example, if the user sets this option to 31 (bits), then a 32-bit ``unsigend int``
+  is ignored by the check, however a 32-bit ``int`` is not (A 32-bit ``signed int``
+  has 31 magnitude bits).
+
+.. code-block:: c++
+
+  int main() {
+long size = 294967296l;
+for (unsigned i = 0; i < size; ++i) {} // no warning with MagnitudeBitsUpperLimit = 31 on a system where unsigned is 32-bit
+for (int i = 0; i < size; ++i) {} // warning with MagnitudeBitsUpperLimit = 31 on a system where int is 32-bit
+  }
Index: clang-tools-extra/docs/ReleaseNotes.rst
===
--- clang-tools-extra/docs/ReleaseNotes.rst
+++ clang-tools-extra/docs/ReleaseNotes.rst
@@ -119,6 +119,10 @@
   `CommentUserDefiniedLiterals`, `CommentStringLiterals`,
   `CommentCharacterLiterals` & `CommentNullPtrs` options.
 
+- The :doc:`bugprone-too-small-loop-variable
+  ` now supports
+  `MagnitudeBitsUpperLimit` option.
+
 - The :doc:`google-runtime-int `
   check has been disabled in Objective-C++.
 
Index: clang-tools-extra/clang-tidy/bugprone/TooSmallLoopVariableCheck.h
===
--- clang-tools-extra/clang-tidy/bugprone/TooSmallLoopVariableCheck.h
+++ clang-tools-extra/clang-tidy/bugprone/TooSmallLoopVariableCheck.h
@@ -29,10 +29,14 @@
 /// http://clang.llvm.org/extra/clang-tidy/checks/bugprone-too-small-loop-variable.html
 class TooSmallLoopVariableCheck : public ClangTidyCheck {
 public:
-  TooSmallLoopVariableCheck(StringRef Name, ClangTidyContext *Context)
-  : ClangTidyCheck(Name, Context) {}
+  TooSmallLoopVariableCheck(StringRef Name, ClangTidyContext *Context);
+
+  void storeOptions(ClangTidyOptions::OptionMap &Opts) override;
   void registerMatchers(ast_matchers::MatchFinder *Finder) override;
   void check(const ast_matchers::MatchFinder::MatchResult &Result) override;
+
+private:
+  const unsigned MagnitudeBitsUpperLimit;
 };
 
 } // namespace bugprone
Index: clang-tools-extra/clang-tidy/bugprone/TooSmallLoopVariableCheck.cpp
===
--- clang-tools-extra/clang-tidy/bugprone/TooSmallLoopVariableCheck.cpp
+++ clang-tools-extra/clang-tidy/bugprone/TooSmallLoopVariableCheck.cpp
@@ -27,6 +27,17 @@
 static constexpr llvm::StringLiteral LoopI

[PATCH] D59923: [Driver] Simplify -g level computation and its interaction with -gsplit-dwarf

2019-03-28 Thread Fangrui Song via Phabricator via cfe-commits
MaskRay created this revision.
MaskRay added reviewers: dblaikie, echristo.
Herald added subscribers: cfe-commits, jdoerfert, aprantl.
Herald added a project: clang.

Computed debug info level:

-gsplit-dwarf -gmlt => 1
-gsplit-dwarf -gmlt -fno-split-dwarf-inlining => 1
-gmlt -gsplit-dwarf => 2
-gmlt -gsplit-dwarf -fno-split-dwarf-inlining => special: 1 (before) 2 (after)

This patch simplifies the computation and drops the
-fno-split-dwarf-inlining special case to make things simpler. If the
user want to compute 1, swap -gmlt and -gsplit-dwarf.

Some context:

In gcc, -gsplit-dwarf -g0 -g1 -g2 -g3 -ggdb* -gdwarf-* ... are applied
one by one and the last one decides the debug info level (-gsplit-dwarf
has level 2). It is a bit unfortunate that -gsplit-dwarf -gdwarf-* ...
participate in the level computation but that is the status quo.


Repository:
  rC Clang

https://reviews.llvm.org/D59923

Files:
  lib/Driver/ToolChains/Clang.cpp
  test/Driver/split-debug.c


Index: test/Driver/split-debug.c
===
--- test/Driver/split-debug.c
+++ test/Driver/split-debug.c
@@ -68,7 +68,7 @@
 // RUN: FileCheck -check-prefix=CHECK-SPLIT-WITH-GMLT < %t %s
 //
 // CHECK-SPLIT-WITH-GMLT: "-enable-split-dwarf"
-// CHECK-SPLIT-WITH-GMLT: "-debug-info-kind=line-tables-only"
+// CHECK-SPLIT-WITH-GMLT: "-debug-info-kind=limited"
 // CHECK-SPLIT-WITH-GMLT: "-split-dwarf-file"
 
 // RUN: %clang -target x86_64-unknown-linux-gnu -gsplit-dwarf 
-fno-split-dwarf-inlining -S -### %s 2> %t
Index: lib/Driver/ToolChains/Clang.cpp
===
--- lib/Driver/ToolChains/Clang.cpp
+++ lib/Driver/ToolChains/Clang.cpp
@@ -3155,9 +3155,11 @@
 SplitDWARFInlining = false;
   }
 
-  if (const Arg *A = Args.getLastArg(options::OPT_g_Group)) {
+  if (const Arg *A = Args.getLastArg(options::OPT_g_Group, 
options::OPT_gsplit_dwarf)) {
+DebugInfoKind = codegenoptions::LimitedDebugInfo;
+
+// If the last option explicitly specified a debug-info level, use it.
 if (checkDebugInfoOption(A, Args, D, TC)) {
-  // If the last option explicitly specified a debug-info level, use it.
   if (A->getOption().matches(options::OPT_gN_Group)) {
 DebugInfoKind = DebugLevelToInfoKind(*A);
 // If you say "-gsplit-dwarf -gline-tables-only", -gsplit-dwarf loses.
@@ -3168,22 +3170,12 @@
 // composing split-dwarf and line-tables-only, so let those compose
 // naturally in that case. And if you just turned off debug info,
 // (-gsplit-dwarf -g0) - do that.
-if (DwarfFission != DwarfFissionKind::None) {
-  if (A->getIndex() > SplitDWARFArg->getIndex()) {
-if (DebugInfoKind == codegenoptions::NoDebugInfo ||
-DebugInfoKind == codegenoptions::DebugDirectivesOnly ||
-(DebugInfoKind == codegenoptions::DebugLineTablesOnly &&
- SplitDWARFInlining))
-  DwarfFission = DwarfFissionKind::None;
-  } else if (SplitDWARFInlining)
-DebugInfoKind = codegenoptions::NoDebugInfo;
-}
-  } else {
-// For any other 'g' option, use Limited.
-DebugInfoKind = codegenoptions::LimitedDebugInfo;
+if (DebugInfoKind == codegenoptions::NoDebugInfo ||
+DebugInfoKind == codegenoptions::DebugDirectivesOnly ||
+(DebugInfoKind == codegenoptions::DebugLineTablesOnly &&
+ SplitDWARFInlining))
+  DwarfFission = DwarfFissionKind::None;
   }
-} else {
-  DebugInfoKind = codegenoptions::LimitedDebugInfo;
 }
   }
 
@@ -3265,9 +3257,6 @@
   CmdArgs.push_back("-fno-split-dwarf-inlining");
 
 if (DwarfFission != DwarfFissionKind::None) {
-  if (DebugInfoKind == codegenoptions::NoDebugInfo)
-DebugInfoKind = codegenoptions::LimitedDebugInfo;
-
   if (DwarfFission == DwarfFissionKind::Single)
 CmdArgs.push_back("-enable-split-dwarf=single");
   else


Index: test/Driver/split-debug.c
===
--- test/Driver/split-debug.c
+++ test/Driver/split-debug.c
@@ -68,7 +68,7 @@
 // RUN: FileCheck -check-prefix=CHECK-SPLIT-WITH-GMLT < %t %s
 //
 // CHECK-SPLIT-WITH-GMLT: "-enable-split-dwarf"
-// CHECK-SPLIT-WITH-GMLT: "-debug-info-kind=line-tables-only"
+// CHECK-SPLIT-WITH-GMLT: "-debug-info-kind=limited"
 // CHECK-SPLIT-WITH-GMLT: "-split-dwarf-file"
 
 // RUN: %clang -target x86_64-unknown-linux-gnu -gsplit-dwarf -fno-split-dwarf-inlining -S -### %s 2> %t
Index: lib/Driver/ToolChains/Clang.cpp
===
--- lib/Driver/ToolChains/Clang.cpp
+++ lib/Driver/ToolChains/Clang.cpp
@@ -3155,9 +3155,11 @@
 SplitDWARFInlining = false;
   }
 
-  if (const Arg *A = Args.getLastArg(options::OPT_g_Group)) {
+  if (const Arg *A = Args.getLastArg(options::OPT_g_Group, options::OPT_gsplit_dwarf)) {
+DebugInfoKin

[PATCH] D59923: [Driver] Simplify -g level computation and its interaction with -gsplit-dwarf

2019-03-28 Thread Fangrui Song via Phabricator via cfe-commits
MaskRay updated this revision to Diff 192585.
MaskRay edited the summary of this revision.
MaskRay added a comment.

update description


Repository:
  rC Clang

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D59923/new/

https://reviews.llvm.org/D59923

Files:
  lib/Driver/ToolChains/Clang.cpp
  test/Driver/split-debug.c


Index: test/Driver/split-debug.c
===
--- test/Driver/split-debug.c
+++ test/Driver/split-debug.c
@@ -68,7 +68,7 @@
 // RUN: FileCheck -check-prefix=CHECK-SPLIT-WITH-GMLT < %t %s
 //
 // CHECK-SPLIT-WITH-GMLT: "-enable-split-dwarf"
-// CHECK-SPLIT-WITH-GMLT: "-debug-info-kind=line-tables-only"
+// CHECK-SPLIT-WITH-GMLT: "-debug-info-kind=limited"
 // CHECK-SPLIT-WITH-GMLT: "-split-dwarf-file"
 
 // RUN: %clang -target x86_64-unknown-linux-gnu -gsplit-dwarf 
-fno-split-dwarf-inlining -S -### %s 2> %t
Index: lib/Driver/ToolChains/Clang.cpp
===
--- lib/Driver/ToolChains/Clang.cpp
+++ lib/Driver/ToolChains/Clang.cpp
@@ -3155,9 +3155,11 @@
 SplitDWARFInlining = false;
   }
 
-  if (const Arg *A = Args.getLastArg(options::OPT_g_Group)) {
+  if (const Arg *A = Args.getLastArg(options::OPT_g_Group, 
options::OPT_gsplit_dwarf)) {
+DebugInfoKind = codegenoptions::LimitedDebugInfo;
+
+// If the last option explicitly specified a debug-info level, use it.
 if (checkDebugInfoOption(A, Args, D, TC)) {
-  // If the last option explicitly specified a debug-info level, use it.
   if (A->getOption().matches(options::OPT_gN_Group)) {
 DebugInfoKind = DebugLevelToInfoKind(*A);
 // If you say "-gsplit-dwarf -gline-tables-only", -gsplit-dwarf loses.
@@ -3168,22 +3170,12 @@
 // composing split-dwarf and line-tables-only, so let those compose
 // naturally in that case. And if you just turned off debug info,
 // (-gsplit-dwarf -g0) - do that.
-if (DwarfFission != DwarfFissionKind::None) {
-  if (A->getIndex() > SplitDWARFArg->getIndex()) {
-if (DebugInfoKind == codegenoptions::NoDebugInfo ||
-DebugInfoKind == codegenoptions::DebugDirectivesOnly ||
-(DebugInfoKind == codegenoptions::DebugLineTablesOnly &&
- SplitDWARFInlining))
-  DwarfFission = DwarfFissionKind::None;
-  } else if (SplitDWARFInlining)
-DebugInfoKind = codegenoptions::NoDebugInfo;
-}
-  } else {
-// For any other 'g' option, use Limited.
-DebugInfoKind = codegenoptions::LimitedDebugInfo;
+if (DebugInfoKind == codegenoptions::NoDebugInfo ||
+DebugInfoKind == codegenoptions::DebugDirectivesOnly ||
+(DebugInfoKind == codegenoptions::DebugLineTablesOnly &&
+ SplitDWARFInlining))
+  DwarfFission = DwarfFissionKind::None;
   }
-} else {
-  DebugInfoKind = codegenoptions::LimitedDebugInfo;
 }
   }
 
@@ -3265,9 +3257,6 @@
   CmdArgs.push_back("-fno-split-dwarf-inlining");
 
 if (DwarfFission != DwarfFissionKind::None) {
-  if (DebugInfoKind == codegenoptions::NoDebugInfo)
-DebugInfoKind = codegenoptions::LimitedDebugInfo;
-
   if (DwarfFission == DwarfFissionKind::Single)
 CmdArgs.push_back("-enable-split-dwarf=single");
   else


Index: test/Driver/split-debug.c
===
--- test/Driver/split-debug.c
+++ test/Driver/split-debug.c
@@ -68,7 +68,7 @@
 // RUN: FileCheck -check-prefix=CHECK-SPLIT-WITH-GMLT < %t %s
 //
 // CHECK-SPLIT-WITH-GMLT: "-enable-split-dwarf"
-// CHECK-SPLIT-WITH-GMLT: "-debug-info-kind=line-tables-only"
+// CHECK-SPLIT-WITH-GMLT: "-debug-info-kind=limited"
 // CHECK-SPLIT-WITH-GMLT: "-split-dwarf-file"
 
 // RUN: %clang -target x86_64-unknown-linux-gnu -gsplit-dwarf -fno-split-dwarf-inlining -S -### %s 2> %t
Index: lib/Driver/ToolChains/Clang.cpp
===
--- lib/Driver/ToolChains/Clang.cpp
+++ lib/Driver/ToolChains/Clang.cpp
@@ -3155,9 +3155,11 @@
 SplitDWARFInlining = false;
   }
 
-  if (const Arg *A = Args.getLastArg(options::OPT_g_Group)) {
+  if (const Arg *A = Args.getLastArg(options::OPT_g_Group, options::OPT_gsplit_dwarf)) {
+DebugInfoKind = codegenoptions::LimitedDebugInfo;
+
+// If the last option explicitly specified a debug-info level, use it.
 if (checkDebugInfoOption(A, Args, D, TC)) {
-  // If the last option explicitly specified a debug-info level, use it.
   if (A->getOption().matches(options::OPT_gN_Group)) {
 DebugInfoKind = DebugLevelToInfoKind(*A);
 // If you say "-gsplit-dwarf -gline-tables-only", -gsplit-dwarf loses.
@@ -3168,22 +3170,12 @@
 // composing split-dwarf and line-tables-only, so let those compose
 // naturally in that case. And if you just turned off debug info,
 // (-gsplit-dwarf -g0) - d

[PATCH] D59924: [PowerPC][Clang] Port MMX intrinsics and basic test cases to Power

2019-03-28 Thread Chaofan Qiu via Phabricator via cfe-commits
qiucf created this revision.
qiucf added reviewers: hfinkel, nemanjai, jsji, rsmith.
Herald added subscribers: cfe-commits, jdoerfert, kbarton, mgorny.
Herald added a project: clang.

This patch is for porting existing headers which include x86 intrinsics (MMX, 
SSE, SSE2, etc.) implementation to PowerPC platform (using Altivec).

Since x86 intrinsic headers (like mmintrin.h) are already at clang's header 
directory, I overrided PowerPC's toolchain class to insert new headers 
directory (named ppc_wrappers) into the path. This patch contains tests for 
several intrinsic functions. More complete tests will come in future patches.

To make this patch not too long, I only added mmintrin.h (MMX instruction set 
header).


Repository:
  rC Clang

https://reviews.llvm.org/D59924

Files:
  clang/lib/Driver/CMakeLists.txt
  clang/lib/Driver/Driver.cpp
  clang/lib/Driver/ToolChains/PPCLinux.cpp
  clang/lib/Driver/ToolChains/PPCLinux.h
  clang/lib/Headers/CMakeLists.txt
  clang/lib/Headers/ppc_wrappers/mmintrin.h
  clang/test/CodeGen/ppc-mmintrin.c
  clang/test/Headers/ppc-intrinsics.c

Index: clang/test/Headers/ppc-intrinsics.c
===
--- /dev/null
+++ clang/test/Headers/ppc-intrinsics.c
@@ -0,0 +1,13 @@
+// REQUIRES: powerpc-registered-target
+
+// RUN: %clang -S -emit-llvm -DNO_WARN_X86_INTRINSICS -DTEST_MACRO -target powerpc64-gnu-linux %s -Xclang -verify -o - | FileCheck %s
+// RUN: %clang -S -emit-llvm -DNO_WARN_X86_INTRINSICS -target powerpc64-gnu-linux %s -Xclang -verify -x c++ -o - | FileCheck %s
+// expected-no-diagnostics
+
+// RUN: NOT %clang -S -emit-llvm -target powerpc64-gnu-linux %s -o /dev/null 2>&1 | FileCheck %s -check-prefix=CHECK-ERROR
+
+#include 
+// CHECK-ERROR: mmintrin.h:{{[0-9]+}}:{{[0-9]+}}: error: "Please read comment above. Use -DNO_WARN_X86_INTRINSICS to disable this error."
+
+// CHECK: target triple = "powerpc64-
+// CHECK: !llvm.module.flags =
Index: clang/test/CodeGen/ppc-mmintrin.c
===
--- /dev/null
+++ clang/test/CodeGen/ppc-mmintrin.c
@@ -0,0 +1,39 @@
+// REQUIRES: powerpc-registered-target
+
+// RUN: %clang -S -emit-llvm -DNO_WARN_X86_INTRINSICS -mcpu=pwr8 -target powerpc64-gnu-linux %s \
+// RUN:-mllvm -disable-llvm-optzns -o - | llvm-cxxfilt | FileCheck %s
+// RUN: %clang -S -emit-llvm -DNO_WARN_X86_INTRINSICS -mcpu=pwr8 -target powerpc64le-gnu-linux %s \
+// RUN:-mllvm -disable-llvm-optzns -o - | llvm-cxxfilt | FileCheck %s
+
+#include 
+
+unsigned long long int ull1, ull2;
+__m64 m1, m2, res;
+
+void __attribute__((noinline))
+test_packs() {
+  res = _mm_packs_pu16((__m64)ull1, (__m64)ull2);
+  res = _mm_packs_pi16((__m64)ull1, (__m64)ull2);
+  res = _mm_packs_pi32((__m64)ull1, (__m64)ull2);
+}
+
+// CHECK-LABEL: @test_packs
+
+// CHECK: i64 @_mm_packs_pu16(i64 {{[0-9a-zA-Z_%.]+}}, i64 {{[0-9a-zA-Z_%.]+}})
+// CHECK: [[REG1:[0-9a-zA-Z_%.]+]] = call <8 x i16> @vec_cmplt
+// CHECK: store <8 x i16> [[REG1]], <8 x i16>* [[REG2:[0-9a-zA-Z_%.]+]], align 16
+// CHECK: [[REG3:[0-9a-zA-Z_%.]+]] = call <16 x i8> @vec_packs
+// CHECK: store <16 x i8> [[REG3]], <16 x i8>* [[REG4:[0-9a-zA-Z_%.]+]], align 16
+// CHECK: [[REG5:[0-9a-zA-Z_%.]+]] = load <8 x i16>, <8 x i16>* [[REG2]], align 16
+// CHECK: [[REG6:[0-9a-zA-Z_%.]+]] = load <8 x i16>, <8 x i16>* [[REG2]], align 16
+// CHECK: [[REG7:[0-9a-zA-Z_%.]+]] = call <16 x i8> @vec_pack(bool vector[8], bool vector[8])(<8 x i16> [[REG5]], <8 x i16> [[REG6]])
+// CHECK: store <16 x i8> [[REG7]], <16 x i8>* [[REG8:[0-9a-zA-Z_%.]+]], align 16
+// CHECK: [[REG9:[0-9a-zA-Z_%.]+]] = load <16 x i8>, <16 x i8>* [[REG4]], align 16
+// CHECK: [[REG10:[0-9a-zA-Z_%.]+]] = load <16 x i8>, <16 x i8>* [[REG8]], align 16
+// CHECK: call <16 x i8> @vec_sel(unsigned char vector[16], unsigned char vector[16], bool vector[16])(<16 x i8> [[REG9]], <16 x i8> zeroinitializer, <16 x i8> [[REG10]])
+
+// CHECK: i64 @_mm_packs_pi16(i64 {{[0-9a-zA-Z_%.]+}}, i64 {{[0-9a-zA-Z_%.]+}})
+// CHECK: call <16 x i8> @vec_packs(short vector[8], short vector[8])
+
+// CHECK: i64 @_mm_packs_pi32(i64 {{[0-9a-zA-Z_%.]+}}, i64 {{[0-9a-zA-Z_%.]+}})
+// CHECK: call <8 x i16> @vec_packs(int vector[4], int vector[4])
Index: clang/lib/Headers/ppc_wrappers/mmintrin.h
===
--- /dev/null
+++ clang/lib/Headers/ppc_wrappers/mmintrin.h
@@ -0,0 +1,1457 @@
+/*=== mmintrin.h - Implementation of MMX intrinsics on PowerPC -===
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ 

[PATCH] D59923: [Driver] Simplify -g level computation and its interaction with -gsplit-dwarf

2019-03-28 Thread Fangrui Song via Phabricator via cfe-commits
MaskRay updated this revision to Diff 192586.
MaskRay added a comment.

dedent


Repository:
  rC Clang

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D59923/new/

https://reviews.llvm.org/D59923

Files:
  lib/Driver/ToolChains/Clang.cpp
  test/Driver/split-debug.c


Index: test/Driver/split-debug.c
===
--- test/Driver/split-debug.c
+++ test/Driver/split-debug.c
@@ -68,7 +68,7 @@
 // RUN: FileCheck -check-prefix=CHECK-SPLIT-WITH-GMLT < %t %s
 //
 // CHECK-SPLIT-WITH-GMLT: "-enable-split-dwarf"
-// CHECK-SPLIT-WITH-GMLT: "-debug-info-kind=line-tables-only"
+// CHECK-SPLIT-WITH-GMLT: "-debug-info-kind=limited"
 // CHECK-SPLIT-WITH-GMLT: "-split-dwarf-file"
 
 // RUN: %clang -target x86_64-unknown-linux-gnu -gsplit-dwarf 
-fno-split-dwarf-inlining -S -### %s 2> %t
Index: lib/Driver/ToolChains/Clang.cpp
===
--- lib/Driver/ToolChains/Clang.cpp
+++ lib/Driver/ToolChains/Clang.cpp
@@ -3155,35 +3155,26 @@
 SplitDWARFInlining = false;
   }
 
-  if (const Arg *A = Args.getLastArg(options::OPT_g_Group)) {
-if (checkDebugInfoOption(A, Args, D, TC)) {
-  // If the last option explicitly specified a debug-info level, use it.
-  if (A->getOption().matches(options::OPT_gN_Group)) {
-DebugInfoKind = DebugLevelToInfoKind(*A);
-// If you say "-gsplit-dwarf -gline-tables-only", -gsplit-dwarf loses.
-// But -gsplit-dwarf is not a g_group option, hence we have to check 
the
-// order explicitly. If -gsplit-dwarf wins, we fix DebugInfoKind later.
-// This gets a bit more complicated if you've disabled inline info in
-// the skeleton CUs (SplitDWARFInlining) - then there's value in
-// composing split-dwarf and line-tables-only, so let those compose
-// naturally in that case. And if you just turned off debug info,
-// (-gsplit-dwarf -g0) - do that.
-if (DwarfFission != DwarfFissionKind::None) {
-  if (A->getIndex() > SplitDWARFArg->getIndex()) {
-if (DebugInfoKind == codegenoptions::NoDebugInfo ||
-DebugInfoKind == codegenoptions::DebugDirectivesOnly ||
-(DebugInfoKind == codegenoptions::DebugLineTablesOnly &&
- SplitDWARFInlining))
-  DwarfFission = DwarfFissionKind::None;
-  } else if (SplitDWARFInlining)
-DebugInfoKind = codegenoptions::NoDebugInfo;
-}
-  } else {
-// For any other 'g' option, use Limited.
-DebugInfoKind = codegenoptions::LimitedDebugInfo;
-  }
-} else {
-  DebugInfoKind = codegenoptions::LimitedDebugInfo;
+  if (const Arg *A = Args.getLastArg(options::OPT_g_Group, 
options::OPT_gsplit_dwarf)) {
+DebugInfoKind = codegenoptions::LimitedDebugInfo;
+
+// If the last option explicitly specified a debug-info level, use it.
+if (checkDebugInfoOption(A, Args, D, TC) &&
+A->getOption().matches(options::OPT_gN_Group)) {
+  DebugInfoKind = DebugLevelToInfoKind(*A);
+  // If you say "-gsplit-dwarf -gline-tables-only", -gsplit-dwarf loses.
+  // But -gsplit-dwarf is not a g_Group option, hence we have to check the
+  // order explicitly. If -gsplit-dwarf wins, we fix DebugInfoKind later.
+  // This gets a bit more complicated if you've disabled inline info in
+  // the skeleton CUs (SplitDWARFInlining) - then there's value in
+  // composing split-dwarf and line-tables-only, so let those compose
+  // naturally in that case. And if you just turned off debug info,
+  // (-gsplit-dwarf -g0) - do that.
+  if (DebugInfoKind == codegenoptions::NoDebugInfo ||
+  DebugInfoKind == codegenoptions::DebugDirectivesOnly ||
+  (DebugInfoKind == codegenoptions::DebugLineTablesOnly &&
+   SplitDWARFInlining))
+DwarfFission = DwarfFissionKind::None;
 }
   }
 
@@ -3265,9 +3256,6 @@
   CmdArgs.push_back("-fno-split-dwarf-inlining");
 
 if (DwarfFission != DwarfFissionKind::None) {
-  if (DebugInfoKind == codegenoptions::NoDebugInfo)
-DebugInfoKind = codegenoptions::LimitedDebugInfo;
-
   if (DwarfFission == DwarfFissionKind::Single)
 CmdArgs.push_back("-enable-split-dwarf=single");
   else


Index: test/Driver/split-debug.c
===
--- test/Driver/split-debug.c
+++ test/Driver/split-debug.c
@@ -68,7 +68,7 @@
 // RUN: FileCheck -check-prefix=CHECK-SPLIT-WITH-GMLT < %t %s
 //
 // CHECK-SPLIT-WITH-GMLT: "-enable-split-dwarf"
-// CHECK-SPLIT-WITH-GMLT: "-debug-info-kind=line-tables-only"
+// CHECK-SPLIT-WITH-GMLT: "-debug-info-kind=limited"
 // CHECK-SPLIT-WITH-GMLT: "-split-dwarf-file"
 
 // RUN: %clang -target x86_64-unknown-linux-gnu -gsplit-dwarf -fno-split-dwarf-inlining -S -### %s 2> %t
Index: lib/Driver/ToolChains/Clang.cpp

[PATCH] D59485: [ASTImporter] Add an ImportInternal method to allow customizing Import behavior.

2019-03-28 Thread Raphael Isemann via Phabricator via cfe-commits
teemperor updated this revision to Diff 192588.
teemperor marked an inline comment as done.
teemperor added a comment.

- Addressed (most of) Aleksei's comments.


CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D59485/new/

https://reviews.llvm.org/D59485

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

Index: clang/unittests/AST/ASTImporterTest.cpp
===
--- clang/unittests/AST/ASTImporterTest.cpp
+++ clang/unittests/AST/ASTImporterTest.cpp
@@ -304,6 +304,14 @@
   const char *const InputFileName = "input.cc";
   const char *const OutputFileName = "output.cc";
 
+public:
+  /// Allocates an ASTImporter (or one of its subclasses).
+  typedef std::function
+  ImporterConstructor;
+
+private:
   // Buffer for the To context, must live in the test scope.
   std::string ToCode;
 
@@ -316,22 +324,33 @@
 std::unique_ptr Unit;
 TranslationUnitDecl *TUDecl = nullptr;
 std::unique_ptr Importer;
-TU(StringRef Code, StringRef FileName, ArgVector Args)
+// The lambda that constructs the ASTImporter we use in this test.
+ImporterConstructor Creator;
+TU(StringRef Code, StringRef FileName, ArgVector Args,
+   ImporterConstructor C = ImporterConstructor())
 : Code(Code), FileName(FileName),
   Unit(tooling::buildASTFromCodeWithArgs(this->Code, Args,
  this->FileName)),
-  TUDecl(Unit->getASTContext().getTranslationUnitDecl()) {
+  TUDecl(Unit->getASTContext().getTranslationUnitDecl()), Creator(C) {
   Unit->enableSourceFileDiagnostics();
+
+  // If the test doesn't need a specific ASTImporter, we just create a
+  // normal ASTImporter with it.
+  if (!Creator)
+Creator = [](ASTContext &ToContext, FileManager &ToFileManager,
+ ASTContext &FromContext, FileManager &FromFileManager,
+ bool MinimalImport, ASTImporterLookupTable *LookupTable) {
+  return new ASTImporter(ToContext, ToFileManager, FromContext,
+ FromFileManager, MinimalImport, LookupTable);
+};
 }
 
 void lazyInitImporter(ASTImporterLookupTable &LookupTable, ASTUnit *ToAST) {
   assert(ToAST);
-  if (!Importer) {
-Importer.reset(
-new ASTImporter(ToAST->getASTContext(), ToAST->getFileManager(),
-Unit->getASTContext(), Unit->getFileManager(),
-false, &LookupTable));
-  }
+  if (!Importer)
+Importer.reset(Creator(ToAST->getASTContext(), ToAST->getFileManager(),
+   Unit->getASTContext(), Unit->getFileManager(),
+   false, &LookupTable));
   assert(&ToAST->getASTContext() == &Importer->getToContext());
   createVirtualFileIfNeeded(ToAST, FileName, Code);
 }
@@ -401,11 +420,12 @@
   // Must not be called more than once within the same test.
   std::tuple
   getImportedDecl(StringRef FromSrcCode, Language FromLang, StringRef ToSrcCode,
-  Language ToLang, StringRef Identifier = DeclToImportID) {
+  Language ToLang, StringRef Identifier = DeclToImportID,
+  ImporterConstructor Creator = ImporterConstructor()) {
 ArgVector FromArgs = getArgVectorForLanguage(FromLang),
   ToArgs = getArgVectorForLanguage(ToLang);
 
-FromTUs.emplace_back(FromSrcCode, InputFileName, FromArgs);
+FromTUs.emplace_back(FromSrcCode, InputFileName, FromArgs, Creator);
 TU &FromTU = FromTUs.back();
 
 assert(!ToAST);
@@ -544,6 +564,73 @@
   EXPECT_THAT(RedeclsD1, ::testing::ContainerEq(RedeclsD2));
 }
 
+struct CustomImporter : ASTImporterOptionSpecificTestBase {};
+
+namespace {
+struct RedirectingImporter : public ASTImporter {
+  using ASTImporter::ASTImporter;
+  // ImporterConstructor that constructs this class.
+  static ASTImporterOptionSpecificTestBase::ImporterConstructor Constructor;
+
+protected:
+  llvm::Expected ImportImpl(Decl *FromD) override {
+auto *ND = dyn_cast(FromD);
+if (!ND || ND->getName() != "shouldNotBeImported")
+  return ASTImporter::ImportImpl(FromD);
+for (Decl *D : getToContext().getTranslationUnitDecl()->decls()) {
+  if (auto *ND = dyn_cast(D))
+if (ND->getName() == "realDecl")
+  return ND;
+}
+return ASTImporter::ImportImpl(FromD);
+  }
+};
+
+ASTImporterOptionSpecificTestBase::ImporterConstructor
+RedirectingImporter::Constructor =
+[](ASTContext &ToContext, FileManager &ToFileManager,
+   ASTContext &FromContext, FileManager &FromFileManager,
+   bool MinimalImport, ASTImporterLookupTable *LookupTabl) {
+  return new RedirectingImporter(ToContext, ToFileManager, FromContext,
+ FromFileManager, MinimalImport,
+  

[PATCH] D59901: [analyzer] PR41239: Fix a crash on invalid source location in NoStoreFuncVisitor.

2019-03-28 Thread Kristóf Umann via Phabricator via cfe-commits
Szelethus accepted this revision.
Szelethus added a comment.

An assert would be real nice in `SourceManager`, we should definitely add that, 
since some callbacks don't even receive a `CallEvent` object. My checker runs 
on `checkPostCall`, and also checks where fields lie in a system header.


Repository:
  rC Clang

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D59901/new/

https://reviews.llvm.org/D59901



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


[PATCH] D59923: [Driver] Simplify -g level computation and its interaction with -gsplit-dwarf

2019-03-28 Thread Fangrui Song via Phabricator via cfe-commits
MaskRay updated this revision to Diff 192589.
MaskRay edited the summary of this revision.
MaskRay added a comment.

Update description


Repository:
  rC Clang

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D59923/new/

https://reviews.llvm.org/D59923

Files:
  lib/Driver/ToolChains/Clang.cpp
  test/Driver/split-debug.c


Index: test/Driver/split-debug.c
===
--- test/Driver/split-debug.c
+++ test/Driver/split-debug.c
@@ -68,7 +68,7 @@
 // RUN: FileCheck -check-prefix=CHECK-SPLIT-WITH-GMLT < %t %s
 //
 // CHECK-SPLIT-WITH-GMLT: "-enable-split-dwarf"
-// CHECK-SPLIT-WITH-GMLT: "-debug-info-kind=line-tables-only"
+// CHECK-SPLIT-WITH-GMLT: "-debug-info-kind=limited"
 // CHECK-SPLIT-WITH-GMLT: "-split-dwarf-file"
 
 // RUN: %clang -target x86_64-unknown-linux-gnu -gsplit-dwarf 
-fno-split-dwarf-inlining -S -### %s 2> %t
Index: lib/Driver/ToolChains/Clang.cpp
===
--- lib/Driver/ToolChains/Clang.cpp
+++ lib/Driver/ToolChains/Clang.cpp
@@ -3155,35 +3155,26 @@
 SplitDWARFInlining = false;
   }
 
-  if (const Arg *A = Args.getLastArg(options::OPT_g_Group)) {
-if (checkDebugInfoOption(A, Args, D, TC)) {
-  // If the last option explicitly specified a debug-info level, use it.
-  if (A->getOption().matches(options::OPT_gN_Group)) {
-DebugInfoKind = DebugLevelToInfoKind(*A);
-// If you say "-gsplit-dwarf -gline-tables-only", -gsplit-dwarf loses.
-// But -gsplit-dwarf is not a g_group option, hence we have to check 
the
-// order explicitly. If -gsplit-dwarf wins, we fix DebugInfoKind later.
-// This gets a bit more complicated if you've disabled inline info in
-// the skeleton CUs (SplitDWARFInlining) - then there's value in
-// composing split-dwarf and line-tables-only, so let those compose
-// naturally in that case. And if you just turned off debug info,
-// (-gsplit-dwarf -g0) - do that.
-if (DwarfFission != DwarfFissionKind::None) {
-  if (A->getIndex() > SplitDWARFArg->getIndex()) {
-if (DebugInfoKind == codegenoptions::NoDebugInfo ||
-DebugInfoKind == codegenoptions::DebugDirectivesOnly ||
-(DebugInfoKind == codegenoptions::DebugLineTablesOnly &&
- SplitDWARFInlining))
-  DwarfFission = DwarfFissionKind::None;
-  } else if (SplitDWARFInlining)
-DebugInfoKind = codegenoptions::NoDebugInfo;
-}
-  } else {
-// For any other 'g' option, use Limited.
-DebugInfoKind = codegenoptions::LimitedDebugInfo;
-  }
-} else {
-  DebugInfoKind = codegenoptions::LimitedDebugInfo;
+  if (const Arg *A = Args.getLastArg(options::OPT_g_Group, 
options::OPT_gsplit_dwarf)) {
+DebugInfoKind = codegenoptions::LimitedDebugInfo;
+
+// If the last option explicitly specified a debug-info level, use it.
+if (checkDebugInfoOption(A, Args, D, TC) &&
+A->getOption().matches(options::OPT_gN_Group)) {
+  DebugInfoKind = DebugLevelToInfoKind(*A);
+  // If you say "-gsplit-dwarf -gline-tables-only", -gsplit-dwarf loses.
+  // But -gsplit-dwarf is not a g_Group option, hence we have to check the
+  // order explicitly. If -gsplit-dwarf wins, we fix DebugInfoKind later.
+  // This gets a bit more complicated if you've disabled inline info in
+  // the skeleton CUs (SplitDWARFInlining) - then there's value in
+  // composing split-dwarf and line-tables-only, so let those compose
+  // naturally in that case. And if you just turned off debug info,
+  // (-gsplit-dwarf -g0) - do that.
+  if (DebugInfoKind == codegenoptions::NoDebugInfo ||
+  DebugInfoKind == codegenoptions::DebugDirectivesOnly ||
+  (DebugInfoKind == codegenoptions::DebugLineTablesOnly &&
+   SplitDWARFInlining))
+DwarfFission = DwarfFissionKind::None;
 }
   }
 
@@ -3265,9 +3256,6 @@
   CmdArgs.push_back("-fno-split-dwarf-inlining");
 
 if (DwarfFission != DwarfFissionKind::None) {
-  if (DebugInfoKind == codegenoptions::NoDebugInfo)
-DebugInfoKind = codegenoptions::LimitedDebugInfo;
-
   if (DwarfFission == DwarfFissionKind::Single)
 CmdArgs.push_back("-enable-split-dwarf=single");
   else


Index: test/Driver/split-debug.c
===
--- test/Driver/split-debug.c
+++ test/Driver/split-debug.c
@@ -68,7 +68,7 @@
 // RUN: FileCheck -check-prefix=CHECK-SPLIT-WITH-GMLT < %t %s
 //
 // CHECK-SPLIT-WITH-GMLT: "-enable-split-dwarf"
-// CHECK-SPLIT-WITH-GMLT: "-debug-info-kind=line-tables-only"
+// CHECK-SPLIT-WITH-GMLT: "-debug-info-kind=limited"
 // CHECK-SPLIT-WITH-GMLT: "-split-dwarf-file"
 
 // RUN: %clang -target x86_64-unknown-linux-gnu -gsplit-dwarf -fno-split-dwarf-inlining -S -### %s 2> %t
Index: lib/Driver/ToolChains/Clang.cpp
===

[PATCH] D59485: [ASTImporter] Add an ImportInternal method to allow customizing Import behavior.

2019-03-28 Thread Raphael Isemann via Phabricator via cfe-commits
teemperor added inline comments.



Comment at: clang/unittests/AST/ASTImporterTest.cpp:590
+  new RedirectingImporter(ToContext, ToFileManager, FromContext,
+  FromFileManager, MinimalImport, LookupTabl));
+};

a_sidorin wrote:
> LookupTable?
Not sure if I can follow?


CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D59485/new/

https://reviews.llvm.org/D59485



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


[PATCH] D59485: [ASTImporter] Add an ImportInternal method to allow customizing Import behavior.

2019-03-28 Thread Gabor Marton via Phabricator via cfe-commits
martong added inline comments.



Comment at: clang/unittests/AST/ASTImporterTest.cpp:590
+  new RedirectingImporter(ToContext, ToFileManager, FromContext,
+  FromFileManager, MinimalImport, LookupTabl));
+};

teemperor wrote:
> a_sidorin wrote:
> > LookupTable?
> Not sure if I can follow?
I think Alexey's comment relates to the parameter in 
`ASTImporterOptionSpecificTestBase::ImporterConstructor`. There is a typo in 
the name of the parameter an 'e' is missing: `ASTImporterLookupTable 
*LookupTabl`


CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D59485/new/

https://reviews.llvm.org/D59485



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


[PATCH] D53701: [Analyzer] Instead of recording comparisons in interator checkers do an eager state split

2019-03-28 Thread Balogh, Ádám via Phabricator via cfe-commits
baloghadamsoftware updated this revision to Diff 192593.
baloghadamsoftware added a comment.

Fixed double transition.


CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D53701/new/

https://reviews.llvm.org/D53701

Files:
  lib/StaticAnalyzer/Checkers/IteratorChecker.cpp

Index: lib/StaticAnalyzer/Checkers/IteratorChecker.cpp
===
--- lib/StaticAnalyzer/Checkers/IteratorChecker.cpp
+++ lib/StaticAnalyzer/Checkers/IteratorChecker.cpp
@@ -133,8 +133,6 @@
   }
 };
 
-typedef llvm::PointerUnion RegionOrSymbol;
-
 // Structure to record the symbolic begin and end position of a container
 struct ContainerData {
 private:
@@ -172,41 +170,21 @@
   }
 };
 
-// Structure fo recording iterator comparisons. We needed to retrieve the
-// original comparison expression in assumptions.
-struct IteratorComparison {
-private:
-  RegionOrSymbol Left, Right;
-  bool Equality;
-
-public:
-  IteratorComparison(RegionOrSymbol L, RegionOrSymbol R, bool Eq)
-  : Left(L), Right(R), Equality(Eq) {}
-
-  RegionOrSymbol getLeft() const { return Left; }
-  RegionOrSymbol getRight() const { return Right; }
-  bool isEquality() const { return Equality; }
-  bool operator==(const IteratorComparison &X) const {
-return Left == X.Left && Right == X.Right && Equality == X.Equality;
-  }
-  bool operator!=(const IteratorComparison &X) const {
-return Left != X.Left || Right != X.Right || Equality != X.Equality;
-  }
-  void Profile(llvm::FoldingSetNodeID &ID) const { ID.AddInteger(Equality); }
-};
-
 class IteratorChecker
 : public Checker, check::Bind,
- check::LiveSymbols, check::DeadSymbols,
- eval::Assume> {
+ check::LiveSymbols, check::DeadSymbols> {
 
   std::unique_ptr OutOfRangeBugType;
   std::unique_ptr MismatchedBugType;
   std::unique_ptr InvalidatedBugType;
 
-  void handleComparison(CheckerContext &C, const SVal &RetVal, const SVal &LVal,
-const SVal &RVal, OverloadedOperatorKind Op) const;
+  void handleComparison(CheckerContext &C, const Expr *CE, const SVal &RetVal,
+const SVal &LVal, const SVal &RVal,
+OverloadedOperatorKind Op) const;
+  void processComparison(CheckerContext &C, ProgramStateRef State,
+ SymbolRef Sym1, SymbolRef Sym2, const SVal &RetVal,
+ OverloadedOperatorKind Op) const;
   void verifyAccess(CheckerContext &C, const SVal &Val) const;
   void verifyDereference(CheckerContext &C, const SVal &Val) const;
   void handleIncrement(CheckerContext &C, const SVal &RetVal, const SVal &Iter,
@@ -281,8 +259,6 @@
  CheckerContext &C) const;
   void checkLiveSymbols(ProgramStateRef State, SymbolReaper &SR) const;
   void checkDeadSymbols(SymbolReaper &SR, CheckerContext &C) const;
-  ProgramStateRef evalAssume(ProgramStateRef State, SVal Cond,
- bool Assumption) const;
 };
 } // namespace
 
@@ -292,9 +268,6 @@
 
 REGISTER_MAP_WITH_PROGRAMSTATE(ContainerMap, const MemRegion *, ContainerData)
 
-REGISTER_MAP_WITH_PROGRAMSTATE(IteratorComparisonMap, const SymExpr *,
-   IteratorComparison)
-
 namespace {
 
 bool isIteratorType(const QualType &Type);
@@ -324,16 +297,6 @@
 bool hasSubscriptOperator(ProgramStateRef State, const MemRegion *Reg);
 bool frontModifiable(ProgramStateRef State, const MemRegion *Reg);
 bool backModifiable(ProgramStateRef State, const MemRegion *Reg);
-BinaryOperator::Opcode getOpcode(const SymExpr *SE);
-const RegionOrSymbol getRegionOrSymbol(const SVal &Val);
-const ProgramStateRef processComparison(ProgramStateRef State,
-RegionOrSymbol LVal,
-RegionOrSymbol RVal, bool Equal);
-const ProgramStateRef saveComparison(ProgramStateRef State,
- const SymExpr *Condition, const SVal &LVal,
- const SVal &RVal, bool Eq);
-const IteratorComparison *loadComparison(ProgramStateRef State,
- const SymExpr *Condition);
 SymbolRef getContainerBegin(ProgramStateRef State, const MemRegion *Cont);
 SymbolRef getContainerEnd(ProgramStateRef State, const MemRegion *Cont);
 ProgramStateRef createContainerBegin(ProgramStateRef State,
@@ -343,21 +306,11 @@
const SymbolRef Sym);
 const IteratorPosition *getIteratorPosition(ProgramStateRef State,
 const SVal &Val);
-const IteratorPosition *getIteratorPosition(ProgramStateRef State,
-RegionOrSymbol RegOrSym);
 ProgramStateRef setIteratorPosition(ProgramStateRef State, const SVal &Val,
 const IteratorPosition &Pos);
-ProgramStateRef setIteratorPosition(ProgramStateRef State,
-   

[PATCH] D59485: [ASTImporter] Add an ImportInternal method to allow customizing Import behavior.

2019-03-28 Thread Raphael Isemann via Phabricator via cfe-commits
teemperor updated this revision to Diff 192594.
teemperor added a comment.

Ah, I get it now. Fixed!


CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D59485/new/

https://reviews.llvm.org/D59485

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

Index: clang/unittests/AST/ASTImporterTest.cpp
===
--- clang/unittests/AST/ASTImporterTest.cpp
+++ clang/unittests/AST/ASTImporterTest.cpp
@@ -304,6 +304,14 @@
   const char *const InputFileName = "input.cc";
   const char *const OutputFileName = "output.cc";
 
+public:
+  /// Allocates an ASTImporter (or one of its subclasses).
+  typedef std::function
+  ImporterConstructor;
+
+private:
   // Buffer for the To context, must live in the test scope.
   std::string ToCode;
 
@@ -316,22 +324,33 @@
 std::unique_ptr Unit;
 TranslationUnitDecl *TUDecl = nullptr;
 std::unique_ptr Importer;
-TU(StringRef Code, StringRef FileName, ArgVector Args)
+// The lambda that constructs the ASTImporter we use in this test.
+ImporterConstructor Creator;
+TU(StringRef Code, StringRef FileName, ArgVector Args,
+   ImporterConstructor C = ImporterConstructor())
 : Code(Code), FileName(FileName),
   Unit(tooling::buildASTFromCodeWithArgs(this->Code, Args,
  this->FileName)),
-  TUDecl(Unit->getASTContext().getTranslationUnitDecl()) {
+  TUDecl(Unit->getASTContext().getTranslationUnitDecl()), Creator(C) {
   Unit->enableSourceFileDiagnostics();
+
+  // If the test doesn't need a specific ASTImporter, we just create a
+  // normal ASTImporter with it.
+  if (!Creator)
+Creator = [](ASTContext &ToContext, FileManager &ToFileManager,
+ ASTContext &FromContext, FileManager &FromFileManager,
+ bool MinimalImport, ASTImporterLookupTable *LookupTable) {
+  return new ASTImporter(ToContext, ToFileManager, FromContext,
+ FromFileManager, MinimalImport, LookupTable);
+};
 }
 
 void lazyInitImporter(ASTImporterLookupTable &LookupTable, ASTUnit *ToAST) {
   assert(ToAST);
-  if (!Importer) {
-Importer.reset(
-new ASTImporter(ToAST->getASTContext(), ToAST->getFileManager(),
-Unit->getASTContext(), Unit->getFileManager(),
-false, &LookupTable));
-  }
+  if (!Importer)
+Importer.reset(Creator(ToAST->getASTContext(), ToAST->getFileManager(),
+   Unit->getASTContext(), Unit->getFileManager(),
+   false, &LookupTable));
   assert(&ToAST->getASTContext() == &Importer->getToContext());
   createVirtualFileIfNeeded(ToAST, FileName, Code);
 }
@@ -401,11 +420,12 @@
   // Must not be called more than once within the same test.
   std::tuple
   getImportedDecl(StringRef FromSrcCode, Language FromLang, StringRef ToSrcCode,
-  Language ToLang, StringRef Identifier = DeclToImportID) {
+  Language ToLang, StringRef Identifier = DeclToImportID,
+  ImporterConstructor Creator = ImporterConstructor()) {
 ArgVector FromArgs = getArgVectorForLanguage(FromLang),
   ToArgs = getArgVectorForLanguage(ToLang);
 
-FromTUs.emplace_back(FromSrcCode, InputFileName, FromArgs);
+FromTUs.emplace_back(FromSrcCode, InputFileName, FromArgs, Creator);
 TU &FromTU = FromTUs.back();
 
 assert(!ToAST);
@@ -544,6 +564,73 @@
   EXPECT_THAT(RedeclsD1, ::testing::ContainerEq(RedeclsD2));
 }
 
+struct CustomImporter : ASTImporterOptionSpecificTestBase {};
+
+namespace {
+struct RedirectingImporter : public ASTImporter {
+  using ASTImporter::ASTImporter;
+  // ImporterConstructor that constructs this class.
+  static ASTImporterOptionSpecificTestBase::ImporterConstructor Constructor;
+
+protected:
+  llvm::Expected ImportImpl(Decl *FromD) override {
+auto *ND = dyn_cast(FromD);
+if (!ND || ND->getName() != "shouldNotBeImported")
+  return ASTImporter::ImportImpl(FromD);
+for (Decl *D : getToContext().getTranslationUnitDecl()->decls()) {
+  if (auto *ND = dyn_cast(D))
+if (ND->getName() == "realDecl")
+  return ND;
+}
+return ASTImporter::ImportImpl(FromD);
+  }
+};
+
+ASTImporterOptionSpecificTestBase::ImporterConstructor
+RedirectingImporter::Constructor =
+[](ASTContext &ToContext, FileManager &ToFileManager,
+   ASTContext &FromContext, FileManager &FromFileManager,
+   bool MinimalImport, ASTImporterLookupTable *LookupTable) {
+  return new RedirectingImporter(ToContext, ToFileManager, FromContext,
+ FromFileManager, MinimalImport,
+ LookupTable);
+};
+} // names

[PATCH] D59725: Additions to creduce script

2019-03-28 Thread Alexander Richardson via Phabricator via cfe-commits
arichardson added a comment.

In D59725#1443990 , @george.burgess.iv 
wrote:

> Only a few more nits on my side, and this LGTM. WDYT, arichardson?


LGTM with the minor tempfile changes.




Comment at: clang/utils/creduce-clang-crash.py:201
+# Instead of modifying the filename in the test file, just run the command
+empty_file = tempfile.NamedTemporaryFile()
+is_interesting = self.check_expected_output(filename=empty_file.name)

`with tempfile.NamedTemporaryFile() as empty_file:`? Definitely works with 
python 3 and 2.7 docs say `This file-like object can be used in a with 
statement, just like a normal file.`.



Comment at: clang/utils/creduce-clang-crash.py:210
+# use delete=False in case the tmpfile flag causes problems when copying
+tmpfile = tempfile.NamedTemporaryFile(delete=False)
+

Use a with statement?



Comment at: clang/utils/creduce-clang-crash.py:212
+
+cmd = self.get_crash_cmd() + ['-E', '-P']
+try:

Some crash messages might include the line numbers, do you think it makes sense 
to fall back to running with -E but without -P and also checking that? I do it 
in my script but I'm not sure preprocessing saves that much time since creduce 
will try to remove those statements early.


CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D59725/new/

https://reviews.llvm.org/D59725



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


[PATCH] D59811: [clangd] Add fallback mode for code completion when compile command or preamble is not ready.

2019-03-28 Thread Ilya Biryukov via Phabricator via cfe-commits
ilya-biryukov added a comment.

I think this option should be configurable (and off by default) for the 
transition period. A few reasons to do so:

- Before we have an actual implementation of fallback completions, the current 
behavior (waiting for the first preamble) actually seems like a better 
experience than returning empty results.
- Some clients do this kind of fallback on their own (e.g. VSCode), so until we 
can provide actually semantically interesting results (anything more than 
identifier-based really, e.g. keyword completions) we would be better off 
keeping it off.
- We can still test it if it's off by flipping the corresponding flag in the 
test code.
- Would make rollout easier (clients can flip the flag back and forth and make 
sure it does not break stuff for them)




Comment at: clangd/ClangdServer.cpp:197
   return CB(llvm::make_error());
+if (!IP->Preamble) {
+  vlog("File {0} is not ready for code completion. Enter fallback mode.",

This way we don't distinguish between the failure to build a preamble and the 
fallback mode.
Have you considered introducing a different callback instead to clearly 
separate two cases for the clients?
The code handling those would hardly have any similarities anyway, given that 
the nature of those two cases is so different.

Would look something like this:
```
/// When \p FallbackAction is not null, it would be called instead of \p Action 
in cases when preamble is 
/// not yet ready.
void runWithPreamble(… Callback Action, Callback 
FallbackAction);
```



Comment at: clangd/TUScheduler.cpp:186
 
   std::shared_ptr getPossiblyStalePreamble() const;
+

Could we put the preamble and compile command into a single function?
Getting them in the lock-step would mean they're always consistent, which is a 
good thing.



Comment at: clangd/TUScheduler.cpp:264
+  llvm::Optional
+  CompileCommand; /* GUARDED_BY(Mutex) */
+  /// Becomes ready when the first compile command is set.

NIT: name it `LastCompileCommand` for consistency with the name of 
`LastBuiltPreamble`.



Comment at: clangd/TUScheduler.cpp:371
+  std::lock_guard Lock(Mutex);
+  this->CompileCommand = Inputs.CompileCommand;
+}

After this point the clients might start getting a new compile command and an 
old preamble.
This seems fine (the clients should be ready for this), but let's document it 
in the methods that expose a compile command and a preamble.



Comment at: clangd/TUScheduler.cpp:918
+  // asynchronous mode, as TU update should finish before this is run.
+  if (!It->second->Worker->isFirstPreambleBuilt() && AllowFallback &&
+  PreambleTasks) {

It would be better to make a decision on whether to use a fallback mode in the 
actual function scheduled on a different thread (i.e. inside the body of 
`Task`).
Imagine the preamble is being built right now and would finish before 
scheduling this task. In that case we would have a chance to hit the "preamble" 
if we make a decision in the body of the handler, but won't have that chance in 
the current implementation.



Comment at: clangd/TUScheduler.cpp:977
+if (!Worker->isFirstCompileCommandSet()) {
+  Worker->waitForFirstCompileCommand();
+}

NIT: remove braces



Comment at: clangd/TUScheduler.h:44
+  // Can be None in fallback mode when neither Command nor Preamble is ready.
+  llvm::Optional Command;
+  // In fallback mode, this can be nullptr when preamble is not ready.

How would we expect to use the compile command when preamble is not ready?
Maybe go with passing only contents to the fallback action until we actually 
have a use for compile command?



Comment at: clangd/TUScheduler.h:156
   /// (i.e. WantDiagnostics is downgraded to Auto).
-  void update(PathRef File, ParseInputs Inputs, WantDiagnostics WD);
+  void update(PathRef File, FileUpdateInputs UpdateInputs, WantDiagnostics WD);
 

NIT: keep the parameter named `Inputs`



Comment at: unittests/clangd/ClangdTests.cpp:1099
+   clangd::CodeCompleteOptions()))
+  .Completions,
+  IsEmpty());

Could we provide a flag in the results indicating this was a fallback-mode 
completion?
This could be used here in tests and we could later use it in the clients to 
show the corresponding UI indicators for users.


Repository:
  rCTE Clang Tools Extra

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D59811/new/

https://reviews.llvm.org/D59811



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


[PATCH] D59861: [analyzer] NFC: Replace Taint API with a usual inter-checker communication API?

2019-03-28 Thread Kristóf Umann via Phabricator via cfe-commits
Szelethus accepted this revision.
Szelethus added a comment.

> "putting all such stuff into the `ProgramState` class clearly doesn't scale, 
> but we still didn't come up with anything better, so let's just put it in the 
> header and see if a better design suddenly emerges in the future after we do 
> it a few hundred times"

Now that we have a maintainer who will dedicate a lot of effort into taint 
analysis, that might just happen :) For the time being though, I agree, this is 
much cleaner.

It would be great to land this as soon as you're comfortable with it, in order 
not to block @boga95's work.


CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D59861/new/

https://reviews.llvm.org/D59861



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


r357162 - [PR41247] Fixed parsing of private keyword in C++.

2019-03-28 Thread Anastasia Stulova via cfe-commits
Author: stulova
Date: Thu Mar 28 04:47:14 2019
New Revision: 357162

URL: http://llvm.org/viewvc/llvm-project?rev=357162&view=rev
Log:
[PR41247] Fixed parsing of private keyword in C++.

Fixed bug in C++ to prevent parsing 'private' as a
valid address space qualifier.

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


Added:
cfe/trunk/test/SemaOpenCLCXX/private-access-specifier.cpp
Modified:
cfe/trunk/lib/Parse/ParseDecl.cpp
cfe/trunk/lib/Parse/ParseTentative.cpp

Modified: cfe/trunk/lib/Parse/ParseDecl.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Parse/ParseDecl.cpp?rev=357162&r1=357161&r2=357162&view=diff
==
--- cfe/trunk/lib/Parse/ParseDecl.cpp (original)
+++ cfe/trunk/lib/Parse/ParseDecl.cpp Thu Mar 28 04:47:14 2019
@@ -4791,7 +4791,6 @@ bool Parser::isTypeSpecifierQualifier()
 
   case tok::kw___kindof:
 
-  case tok::kw_private:
   case tok::kw___private:
   case tok::kw___local:
   case tok::kw___global:
@@ -4800,9 +4799,11 @@ bool Parser::isTypeSpecifierQualifier()
   case tok::kw___read_only:
   case tok::kw___read_write:
   case tok::kw___write_only:
-
 return true;
 
+  case tok::kw_private:
+return getLangOpts().OpenCL;
+
   // C11 _Atomic
   case tok::kw__Atomic:
 return true;
@@ -4982,7 +4983,6 @@ bool Parser::isDeclarationSpecifier(bool
 
   case tok::kw___kindof:
 
-  case tok::kw_private:
   case tok::kw___private:
   case tok::kw___local:
   case tok::kw___global:
@@ -4995,6 +4995,9 @@ bool Parser::isDeclarationSpecifier(bool
 #include "clang/Basic/OpenCLImageTypes.def"
 
 return true;
+
+  case tok::kw_private:
+return getLangOpts().OpenCL;
   }
 }
 
@@ -5196,6 +5199,9 @@ void Parser::ParseTypeQualifierListOpt(
 
 // OpenCL qualifiers:
 case tok::kw_private:
+  if (!getLangOpts().OpenCL)
+goto DoneWithTypeQuals;
+  LLVM_FALLTHROUGH;
 case tok::kw___private:
 case tok::kw___global:
 case tok::kw___local:

Modified: cfe/trunk/lib/Parse/ParseTentative.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Parse/ParseTentative.cpp?rev=357162&r1=357161&r2=357162&view=diff
==
--- cfe/trunk/lib/Parse/ParseTentative.cpp (original)
+++ cfe/trunk/lib/Parse/ParseTentative.cpp Thu Mar 28 04:47:14 2019
@@ -1414,8 +1414,13 @@ Parser::isCXXDeclarationSpecifier(Parser
 // cv-qualifier
   case tok::kw_const:
   case tok::kw_volatile:
+return TPResult::True;
+
 // OpenCL address space qualifiers
   case tok::kw_private:
+if (!getLangOpts().OpenCL)
+  return TPResult::False;
+LLVM_FALLTHROUGH;
   case tok::kw___private:
   case tok::kw___local:
   case tok::kw___global:

Added: cfe/trunk/test/SemaOpenCLCXX/private-access-specifier.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/SemaOpenCLCXX/private-access-specifier.cpp?rev=357162&view=auto
==
--- cfe/trunk/test/SemaOpenCLCXX/private-access-specifier.cpp (added)
+++ cfe/trunk/test/SemaOpenCLCXX/private-access-specifier.cpp Thu Mar 28 
04:47:14 2019
@@ -0,0 +1,13 @@
+// RUN: %clang_cc1 %s -pedantic -verify -fsyntax-only
+
+// Test that 'private' is not parsed as an address space qualifier
+// in regular C++ mode.
+
+struct B {
+  virtual ~B() // expected-error{{expected ';' at end of declaration list}}
+private:
+   void foo();
+   private int* i; // expected-error{{expected ':'}}
+};
+
+void bar(private int*); //expected-error{{variable has incomplete type 
'void'}} expected-error{{expected expression}}


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


[PATCH] D57835: Fix -ftime-report with -x ir

2019-03-28 Thread Fedor Sergeev via Phabricator via cfe-commits
fedor.sergeev requested changes to this revision.
fedor.sergeev added a comment.
This revision now requires changes to proceed.

just to make the comments visible :)


CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D57835/new/

https://reviews.llvm.org/D57835



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


[PATCH] D59874: [PR41247] Fixed parsing of private keyword in C++

2019-03-28 Thread Phabricator via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rL357162: [PR41247] Fixed parsing of private keyword in C++. 
(authored by stulova, committed by ).
Herald added a project: LLVM.
Herald added a subscriber: llvm-commits.

Changed prior to commit:
  https://reviews.llvm.org/D59874?vs=192485&id=192611#toc

Repository:
  rL LLVM

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D59874/new/

https://reviews.llvm.org/D59874

Files:
  cfe/trunk/lib/Parse/ParseDecl.cpp
  cfe/trunk/lib/Parse/ParseTentative.cpp
  cfe/trunk/test/SemaOpenCLCXX/private-access-specifier.cpp


Index: cfe/trunk/test/SemaOpenCLCXX/private-access-specifier.cpp
===
--- cfe/trunk/test/SemaOpenCLCXX/private-access-specifier.cpp
+++ cfe/trunk/test/SemaOpenCLCXX/private-access-specifier.cpp
@@ -0,0 +1,13 @@
+// RUN: %clang_cc1 %s -pedantic -verify -fsyntax-only
+
+// Test that 'private' is not parsed as an address space qualifier
+// in regular C++ mode.
+
+struct B {
+  virtual ~B() // expected-error{{expected ';' at end of declaration list}}
+private:
+   void foo();
+   private int* i; // expected-error{{expected ':'}}
+};
+
+void bar(private int*); //expected-error{{variable has incomplete type 
'void'}} expected-error{{expected expression}}
Index: cfe/trunk/lib/Parse/ParseDecl.cpp
===
--- cfe/trunk/lib/Parse/ParseDecl.cpp
+++ cfe/trunk/lib/Parse/ParseDecl.cpp
@@ -4791,7 +4791,6 @@
 
   case tok::kw___kindof:
 
-  case tok::kw_private:
   case tok::kw___private:
   case tok::kw___local:
   case tok::kw___global:
@@ -4800,9 +4799,11 @@
   case tok::kw___read_only:
   case tok::kw___read_write:
   case tok::kw___write_only:
-
 return true;
 
+  case tok::kw_private:
+return getLangOpts().OpenCL;
+
   // C11 _Atomic
   case tok::kw__Atomic:
 return true;
@@ -4982,7 +4983,6 @@
 
   case tok::kw___kindof:
 
-  case tok::kw_private:
   case tok::kw___private:
   case tok::kw___local:
   case tok::kw___global:
@@ -4995,6 +4995,9 @@
 #include "clang/Basic/OpenCLImageTypes.def"
 
 return true;
+
+  case tok::kw_private:
+return getLangOpts().OpenCL;
   }
 }
 
@@ -5196,6 +5199,9 @@
 
 // OpenCL qualifiers:
 case tok::kw_private:
+  if (!getLangOpts().OpenCL)
+goto DoneWithTypeQuals;
+  LLVM_FALLTHROUGH;
 case tok::kw___private:
 case tok::kw___global:
 case tok::kw___local:
Index: cfe/trunk/lib/Parse/ParseTentative.cpp
===
--- cfe/trunk/lib/Parse/ParseTentative.cpp
+++ cfe/trunk/lib/Parse/ParseTentative.cpp
@@ -1414,8 +1414,13 @@
 // cv-qualifier
   case tok::kw_const:
   case tok::kw_volatile:
+return TPResult::True;
+
 // OpenCL address space qualifiers
   case tok::kw_private:
+if (!getLangOpts().OpenCL)
+  return TPResult::False;
+LLVM_FALLTHROUGH;
   case tok::kw___private:
   case tok::kw___local:
   case tok::kw___global:


Index: cfe/trunk/test/SemaOpenCLCXX/private-access-specifier.cpp
===
--- cfe/trunk/test/SemaOpenCLCXX/private-access-specifier.cpp
+++ cfe/trunk/test/SemaOpenCLCXX/private-access-specifier.cpp
@@ -0,0 +1,13 @@
+// RUN: %clang_cc1 %s -pedantic -verify -fsyntax-only
+
+// Test that 'private' is not parsed as an address space qualifier
+// in regular C++ mode.
+
+struct B {
+  virtual ~B() // expected-error{{expected ';' at end of declaration list}}
+private:
+   void foo();
+   private int* i; // expected-error{{expected ':'}}
+};
+
+void bar(private int*); //expected-error{{variable has incomplete type 'void'}} expected-error{{expected expression}}
Index: cfe/trunk/lib/Parse/ParseDecl.cpp
===
--- cfe/trunk/lib/Parse/ParseDecl.cpp
+++ cfe/trunk/lib/Parse/ParseDecl.cpp
@@ -4791,7 +4791,6 @@
 
   case tok::kw___kindof:
 
-  case tok::kw_private:
   case tok::kw___private:
   case tok::kw___local:
   case tok::kw___global:
@@ -4800,9 +4799,11 @@
   case tok::kw___read_only:
   case tok::kw___read_write:
   case tok::kw___write_only:
-
 return true;
 
+  case tok::kw_private:
+return getLangOpts().OpenCL;
+
   // C11 _Atomic
   case tok::kw__Atomic:
 return true;
@@ -4982,7 +4983,6 @@
 
   case tok::kw___kindof:
 
-  case tok::kw_private:
   case tok::kw___private:
   case tok::kw___local:
   case tok::kw___global:
@@ -4995,6 +4995,9 @@
 #include "clang/Basic/OpenCLImageTypes.def"
 
 return true;
+
+  case tok::kw_private:
+return getLangOpts().OpenCL;
   }
 }
 
@@ -5196,6 +5199,9 @@
 
 // OpenCL qualifiers:
 case tok::kw_private:
+  if (!getLangOpts().OpenCL)
+goto DoneWithTypeQuals;
+  LLVM_FALLTHROUGH;
 case tok::kw___private:
 case tok::kw___global:
 case tok::kw___local:
Index: cfe/trunk/lib/Parse/ParseTentative.cpp
=

r357163 - Fix Wdocumentation warning. NFCI.

2019-03-28 Thread Simon Pilgrim via cfe-commits
Author: rksimon
Date: Thu Mar 28 05:03:49 2019
New Revision: 357163

URL: http://llvm.org/viewvc/llvm-project?rev=357163&view=rev
Log:
Fix Wdocumentation warning. NFCI.

Modified:
cfe/trunk/include/clang/AST/OpenMPClause.h

Modified: cfe/trunk/include/clang/AST/OpenMPClause.h
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/AST/OpenMPClause.h?rev=357163&r1=357162&r2=357163&view=diff
==
--- cfe/trunk/include/clang/AST/OpenMPClause.h (original)
+++ cfe/trunk/include/clang/AST/OpenMPClause.h Thu Mar 28 05:03:49 2019
@@ -353,7 +353,6 @@ public:
   /// \param ColonLoc Location of ':' delimiter.
   /// \param EndLoc Ending location of the clause.
   /// \param VL List of references to the variables.
-  /// \param PrivateVL List of references to private copies with initializers.
   static OMPAllocateClause *Create(const ASTContext &C, SourceLocation 
StartLoc,
SourceLocation LParenLoc, Expr *Allocator,
SourceLocation ColonLoc,


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


[PATCH] D59927: [clangd] Support UTF-32 (i.e. codepoint) offsets.

2019-03-28 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.
Herald added a project: clang.

(Changes to UTF-8/UTF-16 here are NFC, moving things around to make the
cases more symmetrical)


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D59927

Files:
  clangd/Protocol.cpp
  clangd/Protocol.h
  clangd/SourceCode.cpp
  unittests/clangd/SourceCodeTests.cpp

Index: unittests/clangd/SourceCodeTests.cpp
===
--- unittests/clangd/SourceCodeTests.cpp
+++ unittests/clangd/SourceCodeTests.cpp
@@ -58,6 +58,15 @@
   EXPECT_EQ(lspLength("¥"), 2UL);
   // astral
   EXPECT_EQ(lspLength("😂"), 4UL);
+
+  WithContextValue UTF32(kCurrentOffsetEncoding, OffsetEncoding::UTF32);
+  EXPECT_EQ(lspLength(""), 0UL);
+  EXPECT_EQ(lspLength("ascii"), 5UL);
+  // BMP
+  EXPECT_EQ(lspLength("↓"), 1UL);
+  EXPECT_EQ(lspLength("¥"), 1UL);
+  // astral
+  EXPECT_EQ(lspLength("😂"), 1UL);
 }
 
 // The = → 🡆 below are ASCII (1 byte), BMP (3 bytes), and astral (4 bytes).
@@ -131,6 +140,63 @@
   EXPECT_THAT_EXPECTED(positionToOffset(File, position(3, 0)), llvm::Failed());
   EXPECT_THAT_EXPECTED(positionToOffset(File, position(3, 1)), llvm::Failed());
 
+  // codepoints are similar, except near astral characters.
+  WithContextValue UTF32(kCurrentOffsetEncoding, OffsetEncoding::UTF32);
+  // line out of bounds
+  EXPECT_THAT_EXPECTED(positionToOffset(File, position(-1, 2)), llvm::Failed());
+  // first line
+  EXPECT_THAT_EXPECTED(positionToOffset(File, position(0, -1)),
+   llvm::Failed()); // out of range
+  EXPECT_THAT_EXPECTED(positionToOffset(File, position(0, 0)),
+   llvm::HasValue(0)); // first character
+  EXPECT_THAT_EXPECTED(positionToOffset(File, position(0, 3)),
+   llvm::HasValue(3)); // middle character
+  EXPECT_THAT_EXPECTED(positionToOffset(File, position(0, 6)),
+   llvm::HasValue(6)); // last character
+  EXPECT_THAT_EXPECTED(positionToOffset(File, position(0, 7)),
+   llvm::HasValue(7)); // the newline itself
+  EXPECT_THAT_EXPECTED(positionToOffset(File, position(0, 7), false),
+   llvm::HasValue(7));
+  EXPECT_THAT_EXPECTED(positionToOffset(File, position(0, 8)),
+   llvm::HasValue(7)); // out of range
+  EXPECT_THAT_EXPECTED(positionToOffset(File, position(0, 8), false),
+   llvm::Failed()); // out of range
+  // middle line
+  EXPECT_THAT_EXPECTED(positionToOffset(File, position(1, -1)),
+   llvm::Failed()); // out of range
+  EXPECT_THAT_EXPECTED(positionToOffset(File, position(1, 0)),
+   llvm::HasValue(8)); // first character
+  EXPECT_THAT_EXPECTED(positionToOffset(File, position(1, 3)),
+   llvm::HasValue(11)); // middle character
+  EXPECT_THAT_EXPECTED(positionToOffset(File, position(1, 3), false),
+   llvm::HasValue(11));
+  EXPECT_THAT_EXPECTED(positionToOffset(File, position(1, 6)),
+   llvm::HasValue(16)); // last character
+  EXPECT_THAT_EXPECTED(positionToOffset(File, position(1, 7)),
+   llvm::HasValue(17)); // the newline itself
+  EXPECT_THAT_EXPECTED(positionToOffset(File, position(1, 8)),
+   llvm::HasValue(17)); // out of range
+  EXPECT_THAT_EXPECTED(positionToOffset(File, position(1, 8), false),
+   llvm::Failed()); // out of range
+  // last line
+  EXPECT_THAT_EXPECTED(positionToOffset(File, position(2, -1)),
+   llvm::Failed()); // out of range
+  EXPECT_THAT_EXPECTED(positionToOffset(File, position(2, 0)),
+   llvm::HasValue(18)); // first character
+  EXPECT_THAT_EXPECTED(positionToOffset(File, position(2, 4)),
+   llvm::HasValue(22)); // Before astral character.
+  EXPECT_THAT_EXPECTED(positionToOffset(File, position(2, 5), false),
+   llvm::HasValue(26)); // after astral character
+  EXPECT_THAT_EXPECTED(positionToOffset(File, position(2, 7)),
+   llvm::HasValue(28)); // last character
+  EXPECT_THAT_EXPECTED(positionToOffset(File, position(2, 8)),
+   llvm::HasValue(29)); // EOF
+  EXPECT_THAT_EXPECTED(positionToOffset(File, position(2, 9), false),
+   llvm::Failed()); // out of range
+  // line out of bounds
+  EXPECT_THAT_EXPECTED(positionToOffset(File, position(3, 0)), llvm::Failed());
+  EXPECT_THAT_EXPECTED(positionToOffset(File, position(3, 1)), llvm::Failed());
+
   // Test UTF-8, where transformations are trivial.
   WithContextValue UTF8(kCurrentOffsetEncoding, OffsetEncoding::UTF8);
   EXPECT_THAT_EXPECTED(positionToOffset(File, position(-1, 2)), llvm::Failed());
@@ -169,6 +235,27 @@
   EXPECT_THAT(offsetToPosition(File, 29), Pos(2, 9)) << "EOF";
   E

[PATCH] D59927: [clangd] Support UTF-32 (i.e. codepoint) offsets.

2019-03-28 Thread Ilya Biryukov via Phabricator via cfe-commits
ilya-biryukov added a reviewer: gribozavr.
ilya-biryukov added a subscriber: gribozavr.
ilya-biryukov added a comment.

NIT: maybe remove parentheses from the change description, they seem to only 
add noise.
Adding @gribozavr who definitely knows more about Unicode :-)


Repository:
  rCTE Clang Tools Extra

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D59927/new/

https://reviews.llvm.org/D59927



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


[PATCH] D59927: [clangd] Support UTF-32 (i.e. codepoint) offsets.

2019-03-28 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/SourceCodeTests.cpp:164
+   llvm::Failed()); // out of range
+  // middle line
+  EXPECT_THAT_EXPECTED(positionToOffset(File, position(1, -1)),

small NIT: the `.` is missing at the end of the comment. Same for lots of 
comments in the file, I guess.


Repository:
  rCTE Clang Tools Extra

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D59927/new/

https://reviews.llvm.org/D59927



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


[PATCH] D59900: [Sema] Fix a crash when nonnull checking

2019-03-28 Thread Michael Liao via Phabricator via cfe-commits
hliao added a comment.

just explain what's the issue is and hope that help reviewers to get this fix 
quick.

- In `Sema::DiagnoseAlwaysNonNullPointer`, we issue warnings if a `nonnull` 
parameter is used in null checking. It need the function declaration to check 
parameter attributes. That usually works but fails if that function decl is not 
ready yet.
- In template instantiation, we first create the function prototype followed by 
instantiating the function body. When the function prototype is being formed, 
we may create binary or other expressions  for semantic checking. But, in that 
phase, i.e. `Sema::SubstFunctionDeclType`, we don't have the a fully 
specialized function prototype yet to check the parameter number and run into 
the assertion @ line 11596.

Hope that help to get the picture of this fix. Thanks.


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D59900/new/

https://reviews.llvm.org/D59900



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


[PATCH] D59376: [LibTooling] Add Transformer, a library for source-to-source transformations.

2019-03-28 Thread Yitzhak Mandelbaum via Phabricator via cfe-commits
ymandel updated this revision to Diff 192619.
ymandel marked 2 inline comments as done.
ymandel added a comment.

Simplified TextGenerator, changed namespace handling, collapsed verifyTarget() 
into getTarget(), and other changes in response to comments.


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D59376/new/

https://reviews.llvm.org/D59376

Files:
  clang/include/clang/Tooling/Refactoring/Transformer.h
  clang/lib/Tooling/Refactoring/CMakeLists.txt
  clang/lib/Tooling/Refactoring/Transformer.cpp
  clang/unittests/Tooling/CMakeLists.txt
  clang/unittests/Tooling/TransformerTest.cpp

Index: clang/unittests/Tooling/TransformerTest.cpp
===
--- /dev/null
+++ clang/unittests/Tooling/TransformerTest.cpp
@@ -0,0 +1,416 @@
+//===- unittest/Tooling/TransformerTest.cpp ---===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+
+#include "clang/Tooling/Refactoring/Transformer.h"
+
+#include "clang/ASTMatchers/ASTMatchers.h"
+#include "clang/Tooling/Tooling.h"
+#include "gmock/gmock.h"
+#include "gtest/gtest.h"
+
+namespace clang {
+namespace tooling {
+namespace {
+using ::clang::ast_matchers::anyOf;
+using ::clang::ast_matchers::argumentCountIs;
+using ::clang::ast_matchers::callee;
+using ::clang::ast_matchers::callExpr;
+using ::clang::ast_matchers::cxxMemberCallExpr;
+using ::clang::ast_matchers::cxxMethodDecl;
+using ::clang::ast_matchers::cxxRecordDecl;
+using ::clang::ast_matchers::declRefExpr;
+using ::clang::ast_matchers::expr;
+using ::clang::ast_matchers::functionDecl;
+using ::clang::ast_matchers::hasAnyName;
+using ::clang::ast_matchers::hasArgument;
+using ::clang::ast_matchers::hasDeclaration;
+using ::clang::ast_matchers::hasElse;
+using ::clang::ast_matchers::hasName;
+using ::clang::ast_matchers::hasType;
+using ::clang::ast_matchers::ifStmt;
+using ::clang::ast_matchers::member;
+using ::clang::ast_matchers::memberExpr;
+using ::clang::ast_matchers::namedDecl;
+using ::clang::ast_matchers::on;
+using ::clang::ast_matchers::pointsTo;
+using ::clang::ast_matchers::to;
+using ::clang::ast_matchers::unless;
+
+constexpr char KHeaderContents[] = R"cc(
+  struct string {
+string(const char*);
+char* c_str();
+int size();
+  };
+  int strlen(const char*);
+
+  namespace proto {
+  struct PCFProto {
+int foo();
+  };
+  struct ProtoCommandLineFlag : PCFProto {
+PCFProto& GetProto();
+  };
+  }  // namespace proto
+)cc";
+} // namespace
+
+static clang::ast_matchers::internal::Matcher
+isOrPointsTo(const clang::ast_matchers::DeclarationMatcher &TypeMatcher) {
+  return anyOf(hasDeclaration(TypeMatcher), pointsTo(TypeMatcher));
+}
+
+static std::string format(llvm::StringRef Code) {
+  const std::vector Ranges(1, Range(0, Code.size()));
+  auto Style = format::getLLVMStyle();
+  const auto Replacements = format::reformat(Style, Code, Ranges);
+  auto Formatted = applyAllReplacements(Code, Replacements);
+  if (!Formatted) {
+ADD_FAILURE() << "Could not format code: "
+  << llvm::toString(Formatted.takeError());
+return std::string();
+  }
+  return *Formatted;
+}
+
+void compareSnippets(llvm::StringRef Expected,
+ const llvm::Optional &MaybeActual) {
+  ASSERT_TRUE(MaybeActual) << "Rewrite failed. Expecting: " << Expected;
+  auto Actual = *MaybeActual;
+  std::string HL = "#include \"header.h\"\n";
+  auto I = Actual.find(HL);
+  if (I != std::string::npos) {
+Actual.erase(I, HL.size());
+  }
+  EXPECT_EQ(format(Expected), format(Actual));
+}
+
+// FIXME: consider separating this class into its own file(s).
+class ClangRefactoringTestBase : public testing::Test {
+protected:
+  void appendToHeader(llvm::StringRef S) { FileContents[0].second += S; }
+
+  void addFile(llvm::StringRef Filename, llvm::StringRef Content) {
+FileContents.emplace_back(Filename, Content);
+  }
+
+  llvm::Optional rewrite(llvm::StringRef Input) {
+std::string Code = ("#include \"header.h\"\n" + Input).str();
+auto Factory = newFrontendActionFactory(&MatchFinder);
+if (!runToolOnCodeWithArgs(
+Factory->create(), Code, std::vector(), "input.cc",
+"clang-tool", std::make_shared(),
+FileContents)) {
+  return None;
+}
+auto ChangedCodeOrErr =
+applyAtomicChanges("input.cc", Code, Changes, ApplyChangesSpec());
+if (auto Err = ChangedCodeOrErr.takeError()) {
+  llvm::errs() << "Change failed: " << llvm::toString(std::move(Err))
+   << "\n";
+  return None;
+}
+return *ChangedCodeOrErr;
+  }
+
+  clang::ast_matchers::MatchFinder MatchFinder;
+  AtomicChanges Changes;
+
+private:
+  Fil

[PATCH] D57497: [RISCV] Passing small data limitation value to RISCV backend

2019-03-28 Thread Shiva Chen via Phabricator via cfe-commits
shiva0217 updated this revision to Diff 192618.
shiva0217 added a comment.

Add warning message for -msmall-data-limit with -fpic or RV64 with 
-mcmodel=large


Repository:
  rC Clang

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D57497/new/

https://reviews.llvm.org/D57497

Files:
  docs/ClangCommandLineReference.rst
  include/clang/Basic/CodeGenOptions.def
  include/clang/Basic/DiagnosticDriverKinds.td
  include/clang/Driver/CC1Options.td
  include/clang/Driver/Options.td
  lib/CodeGen/CodeGenModule.cpp
  lib/CodeGen/CodeGenModule.h
  lib/Driver/ToolChains/Clang.cpp
  lib/Frontend/CompilerInvocation.cpp
  test/CodeGen/riscv-sdata-module-flag.c
  test/Driver/riscv-G-warning.c
  test/Driver/riscv-sdata-warning.c

Index: test/Driver/riscv-sdata-warning.c
===
--- /dev/null
+++ test/Driver/riscv-sdata-warning.c
@@ -0,0 +1,8 @@
+// REQUIRES: riscv-registered-target
+// RUN: %clang -S -target riscv32-unknown-elf -fpic -msmall-data-limit=8 %s 2>&1 \
+// RUN:   | FileCheck -check-prefix=CHECK-PIC-SDATA %s
+// CHECK-PIC-SDATA: warning: ignoring '-msmall-data-limit=' for -fpic or RV64 with -mcmodel=large
+
+// RUN: %clang -S -target riscv64-unknown-elf -mcmodel=large -msmall-data-limit=8 %s 2>&1 \
+// RUN:   | FileCheck -check-prefix=CHECK-RV64-LARGE-SDATA %s
+// CHECK-RV64-LARGE-SDATA: warning: ignoring '-msmall-data-limit=' for -fpic or RV64 with -mcmodel=large
Index: test/Driver/riscv-G-warning.c
===
--- /dev/null
+++ test/Driver/riscv-G-warning.c
@@ -0,0 +1,4 @@
+// REQUIRES: riscv-registered-target
+// RUN: %clang -S -target riscv32-unknown-elf -G4 -msmall-data-limit=8 %s 2>&1 \
+// RUN:   | FileCheck -check-prefix=CHECK-G %s
+// CHECK-G: warning: ignoring '-G' option as -msmall-data-limit= in the command line
Index: test/CodeGen/riscv-sdata-module-flag.c
===
--- /dev/null
+++ test/CodeGen/riscv-sdata-module-flag.c
@@ -0,0 +1,31 @@
+// RUN: %clang -target riscv32-unknown-elf %s -S -emit-llvm -o - \
+// RUN:   | FileCheck %s -check-prefix=RV32-DEFAULT
+// RUN: %clang -target riscv32-unknown-elf %s -S -emit-llvm -G4 -o - \
+// RUN:   | FileCheck %s -check-prefix=RV32-G4
+// RUN: %clang -target riscv32-unknown-elf %s -S -emit-llvm -msmall-data-limit=0 -o - \
+// RUN:   | FileCheck %s -check-prefix=RV32-S0
+// RUN: %clang -target riscv32-unknown-elf %s -S -emit-llvm -fpic -o - \
+// RUN:   | FileCheck %s -check-prefix=RV32-PIC
+
+// RUN: %clang -target riscv64-unknown-elf %s -S -emit-llvm -o - \
+// RUN:   | FileCheck %s -check-prefix=RV64-DEFAULT
+// RUN: %clang -target riscv64-unknown-elf %s -S -emit-llvm -G4 -o - \
+// RUN:   | FileCheck %s -check-prefix=RV64-G4
+// RUN: %clang -target riscv64-unknown-elf %s -S -emit-llvm -msmall-data-limit=0 -o - \
+// RUN:   | FileCheck %s -check-prefix=RV64-S0
+// RUN: %clang -target riscv64-unknown-elf %s -S -emit-llvm -fpic -o - \
+// RUN:   | FileCheck %s -check-prefix=RV64-PIC
+// RUN: %clang -target riscv64-unknown-elf %s -S -emit-llvm -mcmodel=large -o - \
+// RUN:   | FileCheck %s -check-prefix=RV64-LARGE
+
+
+// RV32-DEFAULT: !{i32 1, !"SmallDataLimit", i32 8}
+// RV32-G4:  !{i32 1, !"SmallDataLimit", i32 4}
+// RV32-S0:  !{i32 1, !"SmallDataLimit", i32 0}
+// RV32-PIC: !{i32 1, !"SmallDataLimit", i32 0}
+
+// RV64-DEFAULT: !{i32 1, !"SmallDataLimit", i32 8}
+// RV64-G4:  !{i32 1, !"SmallDataLimit", i32 4}
+// RV64-S0:  !{i32 1, !"SmallDataLimit", i32 0}
+// RV64-PIC: !{i32 1, !"SmallDataLimit", i32 0}
+// RV64-LARGE:   !{i32 1, !"SmallDataLimit", i32 0}
Index: lib/Frontend/CompilerInvocation.cpp
===
--- lib/Frontend/CompilerInvocation.cpp
+++ lib/Frontend/CompilerInvocation.cpp
@@ -849,6 +849,7 @@
 
   Opts.NoZeroInitializedInBSS = Args.hasArg(OPT_mno_zero_initialized_in_bss);
   Opts.NumRegisterParameters = getLastArgIntValue(Args, OPT_mregparm, 0, Diags);
+  Opts.SmallDataLimit = getLastArgIntValue(Args, OPT_msmall_data_limit, 0, Diags);
   Opts.NoExecStack = Args.hasArg(OPT_mno_exec_stack);
   Opts.FatalWarnings = Args.hasArg(OPT_massembler_fatal_warnings);
   Opts.EnableSegmentedStacks = Args.hasArg(OPT_split_stacks);
Index: lib/Driver/ToolChains/Clang.cpp
===
--- lib/Driver/ToolChains/Clang.cpp
+++ lib/Driver/ToolChains/Clang.cpp
@@ -1784,6 +1784,7 @@
 
 void Clang::AddRISCVTargetArgs(const ArgList &Args,
ArgStringList &CmdArgs) const {
+  const Driver &D = getToolChain().getDriver();
   // FIXME: currently defaults to the soft-float ABIs. Will need to be
   // expanded to select ilp32f, ilp32d, lp64f, lp64d when appropriate.
   const char *ABIName = nullptr;
@@ -1799,6 +1800,37 @@
 
   CmdArgs.push_back("-target-abi");
   CmdArgs.push_back(ABIName);
+
+  // Default small data limitat

r357167 - [Analyzer] Constraint Manager - Calculate Effective Range for Differences

2019-03-28 Thread Adam Balogh via cfe-commits
Author: baloghadamsoftware
Date: Thu Mar 28 06:05:59 2019
New Revision: 357167

URL: http://llvm.org/viewvc/llvm-project?rev=357167&view=rev
Log:
[Analyzer] Constraint Manager - Calculate Effective Range for Differences

Since rL335814, if the constraint manager cannot find a range set for `A - B`
(where `A` and `B` are symbols) it looks for a range for `B - A` and returns
it negated if it exists. However, if a range set for both `A - B` and `B - A`
is stored then it only returns the first one. If we both use `A - B` and
`B - A`, these expressions behave as two totally unrelated symbols. This way
we miss some useful deductions which may lead to false negatives or false
positives.

This tiny patch changes this behavior: if the symbolic expression the
constraint manager is looking for is a difference `A - B`, it tries to
retrieve the range for both `A - B` and `B - A` and if both exists it returns
the intersection of range `A - B` and the negated range of `B - A`. This way
every time a checker applies new constraints to the symbolic difference or to
its negated it always affects both the original difference and its negated.

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


Modified:

cfe/trunk/include/clang/StaticAnalyzer/Core/PathSensitive/RangedConstraintManager.h
cfe/trunk/lib/StaticAnalyzer/Core/RangeConstraintManager.cpp
cfe/trunk/test/Analysis/constraint_manager_negate_difference.c

Modified: 
cfe/trunk/include/clang/StaticAnalyzer/Core/PathSensitive/RangedConstraintManager.h
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/StaticAnalyzer/Core/PathSensitive/RangedConstraintManager.h?rev=357167&r1=357166&r2=357167&view=diff
==
--- 
cfe/trunk/include/clang/StaticAnalyzer/Core/PathSensitive/RangedConstraintManager.h
 (original)
+++ 
cfe/trunk/include/clang/StaticAnalyzer/Core/PathSensitive/RangedConstraintManager.h
 Thu Mar 28 06:05:59 2019
@@ -113,7 +113,8 @@ private:
 public:
   RangeSet Intersect(BasicValueFactory &BV, Factory &F, llvm::APSInt Lower,
  llvm::APSInt Upper) const;
-
+  RangeSet Intersect(BasicValueFactory &BV, Factory &F,
+ const RangeSet &Other) const;
   RangeSet Negate(BasicValueFactory &BV, Factory &F) const;
 
   void print(raw_ostream &os) const;

Modified: cfe/trunk/lib/StaticAnalyzer/Core/RangeConstraintManager.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/StaticAnalyzer/Core/RangeConstraintManager.cpp?rev=357167&r1=357166&r2=357167&view=diff
==
--- cfe/trunk/lib/StaticAnalyzer/Core/RangeConstraintManager.cpp (original)
+++ cfe/trunk/lib/StaticAnalyzer/Core/RangeConstraintManager.cpp Thu Mar 28 
06:05:59 2019
@@ -173,6 +173,22 @@ RangeSet RangeSet::Intersect(BasicValueF
   return newRanges;
 }
 
+// Returns a set containing the values in the receiving set, intersected with
+// the range set passed as parameter.
+RangeSet RangeSet::Intersect(BasicValueFactory &BV, Factory &F,
+ const RangeSet &Other) const {
+  PrimRangeSet newRanges = F.getEmptySet();
+
+  for (iterator i = Other.begin(), e = Other.end(); i != e; ++i) {
+RangeSet newPiece = Intersect(BV, F, i->From(), i->To());
+for (iterator j = newPiece.begin(), ee = newPiece.end(); j != ee; ++j) {
+  newRanges = F.add(newRanges, *j);
+}
+  }
+
+  return newRanges;
+}
+
 // Turn all [A, B] ranges to [-B, -A]. Ranges [MIN, B] are turned to range set
 // [MIN, MIN] U [-B, MAX], when MIN and MAX are the minimal and the maximal
 // signed values of the type.
@@ -461,14 +477,21 @@ static RangeSet applyBitwiseConstraints(
 
 RangeSet RangeConstraintManager::getRange(ProgramStateRef State,
   SymbolRef Sym) {
-  if (ConstraintRangeTy::data_type *V = State->get(Sym))
-return *V;
-
-  BasicValueFactory &BV = getBasicVals();
+  ConstraintRangeTy::data_type *V = State->get(Sym);
 
   // If Sym is a difference of symbols A - B, then maybe we have range set
   // stored for B - A.
-  if (const RangeSet *R = getRangeForMinusSymbol(State, Sym))
+  BasicValueFactory &BV = getBasicVals();
+  const RangeSet *R = getRangeForMinusSymbol(State, Sym);
+
+  // If we have range set stored for both A - B and B - A then calculate the
+  // effective range set by intersecting the range set for A - B and the
+  // negated range set of B - A.
+  if (V && R)
+return V->Intersect(BV, F, R->Negate(BV, F));
+  if (V)
+return *V;
+  if (R)
 return R->Negate(BV, F);
 
   // Lazily generate a new RangeSet representing all possible values for the

Modified: cfe/trunk/test/Analysis/constraint_manager_negate_difference.c
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/Analysis/constraint_manager_negate_difference.c?rev=357167&r1=357166&r2=357167&view=diff
==

[PATCH] D55007: [Analyzer] Constraint Manager - Calculate Effective Range for Differences

2019-03-28 Thread Balogh, Ádám via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rL357167: [Analyzer] Constraint Manager - Calculate Effective 
Range for Differences (authored by baloghadamsoftware, committed by ).
Herald added a project: LLVM.
Herald added a subscriber: llvm-commits.

Changed prior to commit:
  https://reviews.llvm.org/D55007?vs=175693&id=192621#toc

Repository:
  rL LLVM

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D55007/new/

https://reviews.llvm.org/D55007

Files:
  
cfe/trunk/include/clang/StaticAnalyzer/Core/PathSensitive/RangedConstraintManager.h
  cfe/trunk/lib/StaticAnalyzer/Core/RangeConstraintManager.cpp
  cfe/trunk/test/Analysis/constraint_manager_negate_difference.c


Index: 
cfe/trunk/include/clang/StaticAnalyzer/Core/PathSensitive/RangedConstraintManager.h
===
--- 
cfe/trunk/include/clang/StaticAnalyzer/Core/PathSensitive/RangedConstraintManager.h
+++ 
cfe/trunk/include/clang/StaticAnalyzer/Core/PathSensitive/RangedConstraintManager.h
@@ -113,7 +113,8 @@
 public:
   RangeSet Intersect(BasicValueFactory &BV, Factory &F, llvm::APSInt Lower,
  llvm::APSInt Upper) const;
-
+  RangeSet Intersect(BasicValueFactory &BV, Factory &F,
+ const RangeSet &Other) const;
   RangeSet Negate(BasicValueFactory &BV, Factory &F) const;
 
   void print(raw_ostream &os) const;
Index: cfe/trunk/test/Analysis/constraint_manager_negate_difference.c
===
--- cfe/trunk/test/Analysis/constraint_manager_negate_difference.c
+++ cfe/trunk/test/Analysis/constraint_manager_negate_difference.c
@@ -96,3 +96,17 @@
 return;
   clang_analyzer_eval(n - m <= 0); // expected-warning{{TRUE}}
 }
+
+void effective_range(int m, int n) {
+  assert(m - n >= 0);
+  assert(n - m >= 0);
+  clang_analyzer_eval(m - n == 0); // expected-warning{{TRUE}}
+  clang_analyzer_eval(n - m == 0); // expected-warning{{TRUE}}
+}
+
+void effective_range_2(int m, int n) {
+  assert(m - n <= 0);
+  assert(n - m <= 0);
+  clang_analyzer_eval(m - n == 0); // expected-warning{{TRUE}} 
expected-warning{{FALSE}}
+  clang_analyzer_eval(n - m == 0); // expected-warning{{TRUE}} 
expected-warning{{FALSE}}
+}
Index: cfe/trunk/lib/StaticAnalyzer/Core/RangeConstraintManager.cpp
===
--- cfe/trunk/lib/StaticAnalyzer/Core/RangeConstraintManager.cpp
+++ cfe/trunk/lib/StaticAnalyzer/Core/RangeConstraintManager.cpp
@@ -173,6 +173,22 @@
   return newRanges;
 }
 
+// Returns a set containing the values in the receiving set, intersected with
+// the range set passed as parameter.
+RangeSet RangeSet::Intersect(BasicValueFactory &BV, Factory &F,
+ const RangeSet &Other) const {
+  PrimRangeSet newRanges = F.getEmptySet();
+
+  for (iterator i = Other.begin(), e = Other.end(); i != e; ++i) {
+RangeSet newPiece = Intersect(BV, F, i->From(), i->To());
+for (iterator j = newPiece.begin(), ee = newPiece.end(); j != ee; ++j) {
+  newRanges = F.add(newRanges, *j);
+}
+  }
+
+  return newRanges;
+}
+
 // Turn all [A, B] ranges to [-B, -A]. Ranges [MIN, B] are turned to range set
 // [MIN, MIN] U [-B, MAX], when MIN and MAX are the minimal and the maximal
 // signed values of the type.
@@ -461,14 +477,21 @@
 
 RangeSet RangeConstraintManager::getRange(ProgramStateRef State,
   SymbolRef Sym) {
-  if (ConstraintRangeTy::data_type *V = State->get(Sym))
-return *V;
-
-  BasicValueFactory &BV = getBasicVals();
+  ConstraintRangeTy::data_type *V = State->get(Sym);
 
   // If Sym is a difference of symbols A - B, then maybe we have range set
   // stored for B - A.
-  if (const RangeSet *R = getRangeForMinusSymbol(State, Sym))
+  BasicValueFactory &BV = getBasicVals();
+  const RangeSet *R = getRangeForMinusSymbol(State, Sym);
+
+  // If we have range set stored for both A - B and B - A then calculate the
+  // effective range set by intersecting the range set for A - B and the
+  // negated range set of B - A.
+  if (V && R)
+return V->Intersect(BV, F, R->Negate(BV, F));
+  if (V)
+return *V;
+  if (R)
 return R->Negate(BV, F);
 
   // Lazily generate a new RangeSet representing all possible values for the


Index: cfe/trunk/include/clang/StaticAnalyzer/Core/PathSensitive/RangedConstraintManager.h
===
--- cfe/trunk/include/clang/StaticAnalyzer/Core/PathSensitive/RangedConstraintManager.h
+++ cfe/trunk/include/clang/StaticAnalyzer/Core/PathSensitive/RangedConstraintManager.h
@@ -113,7 +113,8 @@
 public:
   RangeSet Intersect(BasicValueFactory &BV, Factory &F, llvm::APSInt Lower,
  llvm::APSInt Upper) const;
-
+  RangeSet Intersect(BasicValueFactory &BV, Factory &F,
+ const RangeSet &Other) const;
   RangeSet Negate(BasicValueFa

[PATCH] D59376: [LibTooling] Add Transformer, a library for source-to-source transformations.

2019-03-28 Thread Yitzhak Mandelbaum via Phabricator via cfe-commits
ymandel updated this revision to Diff 192623.
ymandel marked 26 inline comments as done.
ymandel added a comment.

Adjusted test to cover case discussed in comments.


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D59376/new/

https://reviews.llvm.org/D59376

Files:
  clang/include/clang/Tooling/Refactoring/Transformer.h
  clang/lib/Tooling/Refactoring/CMakeLists.txt
  clang/lib/Tooling/Refactoring/Transformer.cpp
  clang/unittests/Tooling/CMakeLists.txt
  clang/unittests/Tooling/TransformerTest.cpp

Index: clang/unittests/Tooling/TransformerTest.cpp
===
--- /dev/null
+++ clang/unittests/Tooling/TransformerTest.cpp
@@ -0,0 +1,418 @@
+//===- unittest/Tooling/TransformerTest.cpp ---===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+
+#include "clang/Tooling/Refactoring/Transformer.h"
+
+#include "clang/ASTMatchers/ASTMatchers.h"
+#include "clang/Tooling/Tooling.h"
+#include "gmock/gmock.h"
+#include "gtest/gtest.h"
+
+namespace clang {
+namespace tooling {
+namespace {
+using ::clang::ast_matchers::anyOf;
+using ::clang::ast_matchers::argumentCountIs;
+using ::clang::ast_matchers::callee;
+using ::clang::ast_matchers::callExpr;
+using ::clang::ast_matchers::cxxMemberCallExpr;
+using ::clang::ast_matchers::cxxMethodDecl;
+using ::clang::ast_matchers::cxxRecordDecl;
+using ::clang::ast_matchers::declRefExpr;
+using ::clang::ast_matchers::expr;
+using ::clang::ast_matchers::functionDecl;
+using ::clang::ast_matchers::hasAnyName;
+using ::clang::ast_matchers::hasArgument;
+using ::clang::ast_matchers::hasDeclaration;
+using ::clang::ast_matchers::hasElse;
+using ::clang::ast_matchers::hasName;
+using ::clang::ast_matchers::hasType;
+using ::clang::ast_matchers::ifStmt;
+using ::clang::ast_matchers::member;
+using ::clang::ast_matchers::memberExpr;
+using ::clang::ast_matchers::namedDecl;
+using ::clang::ast_matchers::on;
+using ::clang::ast_matchers::pointsTo;
+using ::clang::ast_matchers::to;
+using ::clang::ast_matchers::unless;
+
+constexpr char KHeaderContents[] = R"cc(
+  struct string {
+string(const char*);
+char* c_str();
+int size();
+  };
+  int strlen(const char*);
+
+  namespace proto {
+  struct PCFProto {
+int foo();
+  };
+  struct ProtoCommandLineFlag : PCFProto {
+PCFProto& GetProto();
+  };
+  }  // namespace proto
+)cc";
+} // namespace
+
+static clang::ast_matchers::internal::Matcher
+isOrPointsTo(const clang::ast_matchers::DeclarationMatcher &TypeMatcher) {
+  return anyOf(hasDeclaration(TypeMatcher), pointsTo(TypeMatcher));
+}
+
+static std::string format(llvm::StringRef Code) {
+  const std::vector Ranges(1, Range(0, Code.size()));
+  auto Style = format::getLLVMStyle();
+  const auto Replacements = format::reformat(Style, Code, Ranges);
+  auto Formatted = applyAllReplacements(Code, Replacements);
+  if (!Formatted) {
+ADD_FAILURE() << "Could not format code: "
+  << llvm::toString(Formatted.takeError());
+return std::string();
+  }
+  return *Formatted;
+}
+
+void compareSnippets(llvm::StringRef Expected,
+ const llvm::Optional &MaybeActual) {
+  ASSERT_TRUE(MaybeActual) << "Rewrite failed. Expecting: " << Expected;
+  auto Actual = *MaybeActual;
+  std::string HL = "#include \"header.h\"\n";
+  auto I = Actual.find(HL);
+  if (I != std::string::npos) {
+Actual.erase(I, HL.size());
+  }
+  EXPECT_EQ(format(Expected), format(Actual));
+}
+
+// FIXME: consider separating this class into its own file(s).
+class ClangRefactoringTestBase : public testing::Test {
+protected:
+  void appendToHeader(llvm::StringRef S) { FileContents[0].second += S; }
+
+  void addFile(llvm::StringRef Filename, llvm::StringRef Content) {
+FileContents.emplace_back(Filename, Content);
+  }
+
+  llvm::Optional rewrite(llvm::StringRef Input) {
+std::string Code = ("#include \"header.h\"\n" + Input).str();
+auto Factory = newFrontendActionFactory(&MatchFinder);
+if (!runToolOnCodeWithArgs(
+Factory->create(), Code, std::vector(), "input.cc",
+"clang-tool", std::make_shared(),
+FileContents)) {
+  return None;
+}
+auto ChangedCodeOrErr =
+applyAtomicChanges("input.cc", Code, Changes, ApplyChangesSpec());
+if (auto Err = ChangedCodeOrErr.takeError()) {
+  llvm::errs() << "Change failed: " << llvm::toString(std::move(Err))
+   << "\n";
+  return None;
+}
+return *ChangedCodeOrErr;
+  }
+
+  clang::ast_matchers::MatchFinder MatchFinder;
+  AtomicChanges Changes;
+
+private:
+  FileContentMappings FileContents = {{"header.h", ""}};
+};
+
+class TransformerTest : public

[PATCH] D59376: [LibTooling] Add Transformer, a library for source-to-source transformations.

2019-03-28 Thread Yitzhak Mandelbaum via Phabricator via cfe-commits
ymandel added a comment.

Thanks for the detailed review and really helpful comments!




Comment at: clang/include/clang/Tooling/Refactoring/Transformer.h:38
+/// @{
+using ast_matchers::CXXCtorInitializerMatcher;
+using ast_matchers::DeclarationMatcher;

ilya-biryukov wrote:
> I'm not sure if this is in the LLVM style guide, but we might want to avoid 
> introducing these names into `clang::tooling` namespaces in the headers.
> 
> My fear is that users will rely on those using without knowing that 
> explicitly and won't add corresponding `using` directives or qualifiers to 
> their `.cpp` files, making refactoring and moving the code around harder.
> 
> Could you fully-qualify those names in the header instead? There does not 
> seem to be too many of them.
right. I'd intended to introduce these into the clang tooling namespace -- that 
is, these weren't just convenience aliases for the header file. But, I no 
longer think that's useful in any case, so dropping them is certainly best.



Comment at: clang/include/clang/Tooling/Refactoring/Transformer.h:65
+
+using TextGenerator = std::function(
+const ast_matchers::MatchFinder::MatchResult &)>;

ilya-biryukov wrote:
> Why would a `TextGenerator`  fail?
> I imagine all of the failure cases are programming errors (matchers in the 
> rewrite rule were not aligned with the corresponding text generating 
> function). For those cases, using the `assert` macro seems cleaner.
Sure.  I could go either way. I think some of these cases fall on the border 
between an invariant violation and "invalid argument" or some such.  But, let's 
keep it simpler for now.



Comment at: clang/include/clang/Tooling/Refactoring/Transformer.h:116
+  // never be the empty string.
+  std::string Target = RootId;
+  ast_type_traits::ASTNodeKind TargetKind;

ilya-biryukov wrote:
> NIT: maybe move all inits to the constructor?
> To have all initializers in one place.
nicer, thanks.



Comment at: clang/include/clang/Tooling/Refactoring/Transformer.h:170
+
+  RewriteRuleBuilder(const RewriteRuleBuilder &) = default;
+  RewriteRuleBuilder(RewriteRuleBuilder &&) = default;

ilya-biryukov wrote:
> NIT: maybe remove the `=default` copy and move ctors and assignments?
> They should be generated automatically anyway, right?
Sure. I was going based on google's style recommendations, but personally i 
prefer leaving them implicit.



Comment at: clang/lib/Tooling/Refactoring/Transformer.cpp:28
+
+namespace clang {
+namespace tooling {

ilya-biryukov wrote:
> Other files in the tooling library seem to be adding `using namespace clang` 
> instead of putting the declaration into a namespace.
> Could you please change the new code to do the same for consistency?
> 
Done.  Agreed about being consistent. FWIW, I can't say I like this style.  
Perhaps because I'm not used to it, but it feels too implicit.  It forces the 
reader to figure out where each definition is being associated. Also, I 
discovered it only works for method definitions. Free functions still need to 
be explicitly namespaced.

Any idea what the reason for this style is?



Comment at: clang/lib/Tooling/Refactoring/Transformer.cpp:30
+namespace tooling {
+namespace {
+using ::clang::ast_matchers::MatchFinder;

ilya-biryukov wrote:
> Why put using directives into an anonymous namespace?
> I have not seen this pattern before, could you point me to explanations on 
> why this is useful?
You gain an extra little bit of robustness against clashing with something 
declared in the enclosing namespace.  But, this is overkill even for me -- I 
generally only do this when I already have an anonymous namespace; there's no 
good reason to create one for this purpose.



Comment at: clang/lib/Tooling/Refactoring/Transformer.cpp:111
+// Requires verifyTarget(node, target_part) == success.
+static CharSourceRange getTarget(const DynTypedNode &Node, ASTNodeKind Kind,
+ NodePart TargetPart, ASTContext &Context) {

ilya-biryukov wrote:
> NIT: consider merging `verifyTarget` into `getTarget` and making `getTarget` 
> return `Expected`.
> Would allow avoiding to write one of the complicated switches and 
> error-checking arguably looks just as natural in the `getTarget` as it is in 
> `verifyTarget`.
> 
> Also, having the invariants closer to the code using them makes it easier to 
> certify both are correct, e.g. seeing that `NamedDecl.isIdentifier()` was 
> checked before accessing the `NamedDecl.getName()` in the same function is 
> simpler.
Yes, I like it much better this way.  The split wasn't worth it.



Comment at: clang/lib/Tooling/Refactoring/Transformer.cpp:134
+  auto R = CharSourceRange::getTokenRange(TokenLoc, TokenLoc);
+  // Verify that the range covers exa

[PATCH] D57497: [RISCV] Passing small data limitation value to RISCV backend

2019-03-28 Thread Shiva Chen via Phabricator via cfe-commits
shiva0217 marked an inline comment as done.
shiva0217 added inline comments.



Comment at: lib/Driver/ToolChains/Clang.cpp:1813
+}
+  } else if (Arg *A = Args.getLastArg(options::OPT_G)) {
+SmallDataLimit = A->getValue();

apazos wrote:
> Why do you we need to set a default? It will cause the optimization to be on 
> now, and I thought we want to first prioritize the globals we want to 
> consider for the optimization.
> I think you should check for msmall-data-limit flag occurring with G,  fpic 
> and mcmodel flags and print warning in all cases.
Hi Ana,
It seems that RISC-V GCC will set 8 as default value even with -mno-relax.
Another issue is that the sorting scope will be a compile unit. So when linker 
link the .sdata from objects, it will get globals from object A with usage 
times from high to low and then the globals from object B with usage times from 
high to low which probably not we want. The sorting might make sense when the 
LTO enabled.
I have added the warning message, thanks for the suggestion.


Repository:
  rC Clang

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D57497/new/

https://reviews.llvm.org/D57497



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


[PATCH] D59923: [Driver] Simplify -g level computation and its interaction with -gsplit-dwarf

2019-03-28 Thread Paul Robinson via Phabricator via cfe-commits
probinson added a comment.

Commentary questions.




Comment at: lib/Driver/ToolChains/Clang.cpp:3166
+  // If you say "-gsplit-dwarf -gline-tables-only", -gsplit-dwarf loses.
+  // But -gsplit-dwarf is not a g_Group option, hence we have to check the
+  // order explicitly. If -gsplit-dwarf wins, we fix DebugInfoKind later.

Regarding `But -gsplit-dwarf is not a g_Group option, hence we have to check 
the order explicitly.` It looks like when you added OPT_gsplit_dwarf to the 
if-statement above, we no longer have to check it explicitly?



Comment at: lib/Driver/ToolChains/Clang.cpp:3167
+  // But -gsplit-dwarf is not a g_Group option, hence we have to check the
+  // order explicitly. If -gsplit-dwarf wins, we fix DebugInfoKind later.
+  // This gets a bit more complicated if you've disabled inline info in

Regarding `If -gsplit-dwarf wins, we fix DebugInfoKind later.`
Is that still true?  It looks like -gsplit-dwarf is handled here now, because 
you removed the compensating code from lines 3268-3269.



Comment at: lib/Driver/ToolChains/Clang.cpp:3253
   // -gsplit-dwarf should turn on -g and enable the backend dwarf
   // splitting and extraction.
   if (T.isOSBinFormatELF()) {

This block of code no longer turns on -g?


Repository:
  rC Clang

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D59923/new/

https://reviews.llvm.org/D59923



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


[PATCH] D59932: [clang-tidy] **Prototype**: Add fix descrption to clang-tidy checks.

2019-03-28 Thread Haojian Wu via Phabricator via cfe-commits
hokein created this revision.
Herald added subscribers: cfe-commits, jdoerfert, xazax.hun.
Herald added a project: clang.

Motivation/Context: in the code review system integrating withclang-tidy,
clang-tidy doesn't provide a human-readable description of the fix. Usually
developers have to preview a code diff (before vs after apply the fix) to
understand what the fix does before applying a fix.

This patch proposes that each clang-tidy check provides a short and
actional fix description that can be shown in the UI, so that users can know
what the fix does without previewing diff.

We introduce a new interface to ClangTidyCheck, we will add implementations for
exisiting checks.


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D59932

Files:
  clang-tidy/ClangTidy.cpp
  clang-tidy/ClangTidyCheck.cpp
  clang-tidy/ClangTidyCheck.h
  clang-tidy/ClangTidyDiagnosticConsumer.cpp
  clang-tidy/ClangTidyDiagnosticConsumer.h

Index: clang-tidy/ClangTidyDiagnosticConsumer.h
===
--- clang-tidy/ClangTidyDiagnosticConsumer.h
+++ clang-tidy/ClangTidyDiagnosticConsumer.h
@@ -16,6 +16,7 @@
 #include "clang/Tooling/Core/Diagnostic.h"
 #include "clang/Tooling/Refactoring.h"
 #include "llvm/ADT/DenseMap.h"
+#include "llvm/ADT/DenseMapInfo.h"
 #include "llvm/ADT/StringMap.h"
 #include "llvm/Support/Regex.h"
 #include "llvm/Support/Timer.h"
@@ -45,6 +46,11 @@
  bool IsWarningAsError);
 
   bool IsWarningAsError;
+  // A short descrpition of the clang-tidy fix.
+  // Empty if the ClangTidyError doesn't provide any fixes.
+  //
+  // FIXME: this should move to tooling::Diagnostic.
+  std::string FixDescription;
 };
 
 /// \brief Read-only set of strings represented as a list of positive and
@@ -116,7 +122,7 @@
   /// tablegen'd diagnostic IDs.
   /// FIXME: Figure out a way to manage ID spaces.
   DiagnosticBuilder diag(StringRef CheckName, SourceLocation Loc,
- StringRef Message,
+ StringRef Message, StringRef CheckFixDescription,
  DiagnosticIDs::Level Level = DiagnosticIDs::Warning);
 
   /// \brief Sets the \c SourceManager of the used \c DiagnosticsEngine.
@@ -140,6 +146,10 @@
   /// diagnostic ID.
   std::string getCheckName(unsigned DiagnosticID) const;
 
+  /// \brief Returns the fix description of the clang-tidy check which produced
+  /// this diagnostic ID.
+  std::string getCheckFixDescription(unsigned DiagnosticID) const;
+
   /// \brief Returns \c true if the check is enabled for the \c CurrentFile.
   ///
   /// The \c CurrentFile can be changed using \c setCurrentFile.
@@ -209,7 +219,8 @@
 
   std::string CurrentBuildDirectory;
 
-  llvm::DenseMap CheckNamesByDiagnosticID;
+  llvm::DenseMap>
+  CheckNamesByDiagnosticID;
 
   bool Profile;
   std::string ProfilePrefix;
Index: clang-tidy/ClangTidyDiagnosticConsumer.cpp
===
--- clang-tidy/ClangTidyDiagnosticConsumer.cpp
+++ clang-tidy/ClangTidyDiagnosticConsumer.cpp
@@ -190,11 +190,12 @@
 
 DiagnosticBuilder ClangTidyContext::diag(
 StringRef CheckName, SourceLocation Loc, StringRef Description,
+StringRef CheckFixDescription,
 DiagnosticIDs::Level Level /* = DiagnosticIDs::Warning*/) {
   assert(Loc.isValid());
   unsigned ID = DiagEngine->getDiagnosticIDs()->getCustomDiagID(
   Level, (Description + " [" + CheckName + "]").str());
-  CheckNamesByDiagnosticID.try_emplace(ID, CheckName);
+  CheckNamesByDiagnosticID[ID] = {CheckName, CheckFixDescription};
   return DiagEngine->Report(Loc, ID);
 }
 
@@ -259,10 +260,17 @@
   DiagEngine->getDiagnosticIDs()->getWarningOptionForDiag(DiagnosticID);
   if (!ClangWarningOption.empty())
 return "clang-diagnostic-" + ClangWarningOption;
-  llvm::DenseMap::const_iterator I =
-  CheckNamesByDiagnosticID.find(DiagnosticID);
+  auto I = CheckNamesByDiagnosticID.find(DiagnosticID);
   if (I != CheckNamesByDiagnosticID.end())
-return I->second;
+return I->second.first;
+  return "";
+}
+
+std::string
+ClangTidyContext::getCheckFixDescription(unsigned DiagnosticID) const {
+  auto I = CheckNamesByDiagnosticID.find(DiagnosticID);
+  if (I != CheckNamesByDiagnosticID.end())
+return I->second.second;
   return "";
 }
 
@@ -449,6 +457,9 @@
 Loc = FullSourceLoc(Info.getLocation(), Info.getSourceManager());
   Converter.emitDiagnostic(Loc, DiagLevel, Message, Info.getRanges(),
Info.getFixItHints());
+  // Populate the fix description if the diagnostic has fixes.
+  if (!Errors.back().Fix.empty())
+Errors.back().FixDescription = Context.getCheckFixDescription(Info.getID());
 
   if (Info.hasSourceManager())
 checkFilters(Info.getLocation(), Info.getSourceManager());
Index: clang-tidy/ClangTidyCheck.h
===
--- clang-tidy/ClangTidyCheck.h
+++ clang-tidy/ClangTidyCheck.h
@@

[PATCH] D59927: [clangd] Support UTF-32 (i.e. codepoint) offsets.

2019-03-28 Thread Sam McCall via Phabricator via cfe-commits
sammccall updated this revision to Diff 192628.
sammccall added a comment.

Fix capitalization.


Repository:
  rCTE Clang Tools Extra

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D59927/new/

https://reviews.llvm.org/D59927

Files:
  clangd/Protocol.cpp
  clangd/Protocol.h
  clangd/SourceCode.cpp
  unittests/clangd/SourceCodeTests.cpp

Index: unittests/clangd/SourceCodeTests.cpp
===
--- unittests/clangd/SourceCodeTests.cpp
+++ unittests/clangd/SourceCodeTests.cpp
@@ -58,6 +58,15 @@
   EXPECT_EQ(lspLength("¥"), 2UL);
   // astral
   EXPECT_EQ(lspLength("😂"), 4UL);
+
+  WithContextValue UTF32(kCurrentOffsetEncoding, OffsetEncoding::UTF32);
+  EXPECT_EQ(lspLength(""), 0UL);
+  EXPECT_EQ(lspLength("ascii"), 5UL);
+  // BMP
+  EXPECT_EQ(lspLength("↓"), 1UL);
+  EXPECT_EQ(lspLength("¥"), 1UL);
+  // astral
+  EXPECT_EQ(lspLength("😂"), 1UL);
 }
 
 // The = → 🡆 below are ASCII (1 byte), BMP (3 bytes), and astral (4 bytes).
@@ -131,6 +140,63 @@
   EXPECT_THAT_EXPECTED(positionToOffset(File, position(3, 0)), llvm::Failed());
   EXPECT_THAT_EXPECTED(positionToOffset(File, position(3, 1)), llvm::Failed());
 
+  // Codepoints are similar, except near astral characters.
+  WithContextValue UTF32(kCurrentOffsetEncoding, OffsetEncoding::UTF32);
+  // line out of bounds
+  EXPECT_THAT_EXPECTED(positionToOffset(File, position(-1, 2)), llvm::Failed());
+  // first line
+  EXPECT_THAT_EXPECTED(positionToOffset(File, position(0, -1)),
+   llvm::Failed()); // out of range
+  EXPECT_THAT_EXPECTED(positionToOffset(File, position(0, 0)),
+   llvm::HasValue(0)); // first character
+  EXPECT_THAT_EXPECTED(positionToOffset(File, position(0, 3)),
+   llvm::HasValue(3)); // middle character
+  EXPECT_THAT_EXPECTED(positionToOffset(File, position(0, 6)),
+   llvm::HasValue(6)); // last character
+  EXPECT_THAT_EXPECTED(positionToOffset(File, position(0, 7)),
+   llvm::HasValue(7)); // the newline itself
+  EXPECT_THAT_EXPECTED(positionToOffset(File, position(0, 7), false),
+   llvm::HasValue(7));
+  EXPECT_THAT_EXPECTED(positionToOffset(File, position(0, 8)),
+   llvm::HasValue(7)); // out of range
+  EXPECT_THAT_EXPECTED(positionToOffset(File, position(0, 8), false),
+   llvm::Failed()); // out of range
+  // middle line
+  EXPECT_THAT_EXPECTED(positionToOffset(File, position(1, -1)),
+   llvm::Failed()); // out of range
+  EXPECT_THAT_EXPECTED(positionToOffset(File, position(1, 0)),
+   llvm::HasValue(8)); // first character
+  EXPECT_THAT_EXPECTED(positionToOffset(File, position(1, 3)),
+   llvm::HasValue(11)); // middle character
+  EXPECT_THAT_EXPECTED(positionToOffset(File, position(1, 3), false),
+   llvm::HasValue(11));
+  EXPECT_THAT_EXPECTED(positionToOffset(File, position(1, 6)),
+   llvm::HasValue(16)); // last character
+  EXPECT_THAT_EXPECTED(positionToOffset(File, position(1, 7)),
+   llvm::HasValue(17)); // the newline itself
+  EXPECT_THAT_EXPECTED(positionToOffset(File, position(1, 8)),
+   llvm::HasValue(17)); // out of range
+  EXPECT_THAT_EXPECTED(positionToOffset(File, position(1, 8), false),
+   llvm::Failed()); // out of range
+  // last line
+  EXPECT_THAT_EXPECTED(positionToOffset(File, position(2, -1)),
+   llvm::Failed()); // out of range
+  EXPECT_THAT_EXPECTED(positionToOffset(File, position(2, 0)),
+   llvm::HasValue(18)); // first character
+  EXPECT_THAT_EXPECTED(positionToOffset(File, position(2, 4)),
+   llvm::HasValue(22)); // Before astral character.
+  EXPECT_THAT_EXPECTED(positionToOffset(File, position(2, 5), false),
+   llvm::HasValue(26)); // after astral character
+  EXPECT_THAT_EXPECTED(positionToOffset(File, position(2, 7)),
+   llvm::HasValue(28)); // last character
+  EXPECT_THAT_EXPECTED(positionToOffset(File, position(2, 8)),
+   llvm::HasValue(29)); // EOF
+  EXPECT_THAT_EXPECTED(positionToOffset(File, position(2, 9), false),
+   llvm::Failed()); // out of range
+  // line out of bounds
+  EXPECT_THAT_EXPECTED(positionToOffset(File, position(3, 0)), llvm::Failed());
+  EXPECT_THAT_EXPECTED(positionToOffset(File, position(3, 1)), llvm::Failed());
+
   // Test UTF-8, where transformations are trivial.
   WithContextValue UTF8(kCurrentOffsetEncoding, OffsetEncoding::UTF8);
   EXPECT_THAT_EXPECTED(positionToOffset(File, position(-1, 2)), llvm::Failed());
@@ -169,6 +235,27 @@
   EXPECT_THAT(offsetToPosition(File, 29), Pos(2, 9)) << "EOF";
   EXPECT_THAT(offsetToPosition(File, 30), Pos(2, 9)) << "out of bounds";
 
+  // Codepoints are similar, except near astral charact

[PATCH] D58897: [ASTImporter] Make ODR error handling configurable

2019-03-28 Thread Endre Fülöp via Phabricator via cfe-commits
gamesh411 added a comment.

ping @a_sidorin


Repository:
  rC Clang

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D58897/new/

https://reviews.llvm.org/D58897



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


[PATCH] D59927: [clangd] Support UTF-32 (i.e. codepoint) offsets.

2019-03-28 Thread Sam McCall via Phabricator via cfe-commits
sammccall marked an inline comment as done.
sammccall added inline comments.



Comment at: unittests/clangd/SourceCodeTests.cpp:164
+   llvm::Failed()); // out of range
+  // middle line
+  EXPECT_THAT_EXPECTED(positionToOffset(File, position(1, -1)),

ilya-biryukov wrote:
> small NIT: the `.` is missing at the end of the comment. Same for lots of 
> comments in the file, I guess.
hmm, these are fragments rather than sentences (no caps, no trailing 
punctuation).
Are we not supposed to use those? There are some in the coding standards 
examples!


Repository:
  rCTE Clang Tools Extra

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D59927/new/

https://reviews.llvm.org/D59927



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


[PATCH] D59761: [ASTImporter] Convert ODR diagnostics inside ASTImporter implementation

2019-03-28 Thread Endre Fülöp via Phabricator via cfe-commits
gamesh411 added a comment.

ping @a_sidorin @shafik


Repository:
  rC Clang

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D59761/new/

https://reviews.llvm.org/D59761



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


[PATCH] D59932: [clang-tidy] **Prototype**: Add fix description to clang-tidy checks.

2019-03-28 Thread Haojian Wu via Phabricator via cfe-commits
hokein added a comment.

This is my first attempt, still missing tests, but it should be in a shape to 
get early feedbacks.


Repository:
  rCTE Clang Tools Extra

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D59932/new/

https://reviews.llvm.org/D59932



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


[clang-tools-extra] r357173 - [clangd] Support UTF-32 (i.e. codepoint) offsets.

2019-03-28 Thread Sam McCall via cfe-commits
Author: sammccall
Date: Thu Mar 28 07:37:51 2019
New Revision: 357173

URL: http://llvm.org/viewvc/llvm-project?rev=357173&view=rev
Log:
[clangd] Support UTF-32 (i.e. codepoint) offsets.

Summary:
(Changes to UTF-8/UTF-16 here are NFC, moving things around to make the
cases more symmetrical)

Reviewers: ilya-biryukov

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

Tags: #clang

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

Modified:
clang-tools-extra/trunk/clangd/Protocol.cpp
clang-tools-extra/trunk/clangd/Protocol.h
clang-tools-extra/trunk/clangd/SourceCode.cpp
clang-tools-extra/trunk/unittests/clangd/SourceCodeTests.cpp

Modified: clang-tools-extra/trunk/clangd/Protocol.cpp
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clangd/Protocol.cpp?rev=357173&r1=357172&r2=357173&view=diff
==
--- clang-tools-extra/trunk/clangd/Protocol.cpp (original)
+++ clang-tools-extra/trunk/clangd/Protocol.cpp Thu Mar 28 07:37:51 2019
@@ -938,16 +938,19 @@ bool fromJSON(const llvm::json::Value &P
   return fromJSON(Params, Base);
 }
 
-llvm::json::Value toJSON(const OffsetEncoding &OE) {
+static const char *toString(OffsetEncoding OE) {
   switch (OE) {
-case OffsetEncoding::UTF8:
-  return "utf-8";
-case OffsetEncoding::UTF16:
-  return "utf-16";
-case OffsetEncoding::UnsupportedEncoding:
-  return "unknown";
+  case OffsetEncoding::UTF8:
+return "utf-8";
+  case OffsetEncoding::UTF16:
+return "utf-16";
+  case OffsetEncoding::UTF32:
+return "utf-32";
+  case OffsetEncoding::UnsupportedEncoding:
+return "unknown";
   }
 }
+llvm::json::Value toJSON(const OffsetEncoding &OE) { return toString(OE); }
 bool fromJSON(const llvm::json::Value &V, OffsetEncoding &OE) {
   auto Str = V.getAsString();
   if (!Str)
@@ -955,9 +958,13 @@ bool fromJSON(const llvm::json::Value &V
   OE = llvm::StringSwitch(*Str)
.Case("utf-8", OffsetEncoding::UTF8)
.Case("utf-16", OffsetEncoding::UTF16)
+   .Case("utf-32", OffsetEncoding::UTF32)
.Default(OffsetEncoding::UnsupportedEncoding);
   return true;
 }
+llvm::raw_ostream &operator<<(llvm::raw_ostream &OS, OffsetEncoding Enc) {
+  return OS << toString(Enc);
+}
 
 } // namespace clangd
 } // namespace clang

Modified: clang-tools-extra/trunk/clangd/Protocol.h
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clangd/Protocol.h?rev=357173&r1=357172&r2=357173&view=diff
==
--- clang-tools-extra/trunk/clangd/Protocol.h (original)
+++ clang-tools-extra/trunk/clangd/Protocol.h Thu Mar 28 07:37:51 2019
@@ -28,6 +28,7 @@
 #include "clang/Index/IndexSymbol.h"
 #include "llvm/ADT/Optional.h"
 #include "llvm/Support/JSON.h"
+#include "llvm/Support/raw_ostream.h"
 #include 
 #include 
 #include 
@@ -346,9 +347,12 @@ enum class OffsetEncoding {
   UTF16,
   // Length counts bytes of UTF-8 encoded text. (Clangd extension).
   UTF8,
+  // Length counts codepoints in unicode text. (Clangd extension).
+  UTF32,
 };
 llvm::json::Value toJSON(const OffsetEncoding &);
 bool fromJSON(const llvm::json::Value &, OffsetEncoding &);
+llvm::raw_ostream &operator<<(llvm::raw_ostream &, OffsetEncoding OS);
 
 // This struct doesn't mirror LSP!
 // The protocol defines deeply nested structures for client capabilities.

Modified: clang-tools-extra/trunk/clangd/SourceCode.cpp
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clangd/SourceCode.cpp?rev=357173&r1=357172&r2=357173&view=diff
==
--- clang-tools-extra/trunk/clangd/SourceCode.cpp (original)
+++ clang-tools-extra/trunk/clangd/SourceCode.cpp Thu Mar 28 07:37:51 2019
@@ -17,6 +17,7 @@
 #include "llvm/ADT/StringRef.h"
 #include "llvm/Support/Errc.h"
 #include "llvm/Support/Error.h"
+#include "llvm/Support/ErrorHandling.h"
 #include "llvm/Support/Path.h"
 
 namespace clang {
@@ -30,6 +31,8 @@ namespace clangd {
 // Returns true if CB returned true, false if we hit the end of string.
 template 
 static bool iterateCodepoints(llvm::StringRef U8, const Callback &CB) {
+  // A codepoint takes two UTF-16 code unit if it's astral (outside BMP).
+  // Astral codepoints are encoded as 4 bytes in UTF-8, starting with 0xxx.
   for (size_t I = 0; I < U8.size();) {
 unsigned char C = static_cast(U8[I]);
 if (LLVM_LIKELY(!(C & 0x80))) { // ASCII character.
@@ -53,46 +56,75 @@ static bool iterateCodepoints(llvm::Stri
   return false;
 }
 
-// Returns the offset into the string that matches \p Units UTF-16 code units.
-// Conceptually, this converts to UTF-16, truncates to CodeUnits, converts back
-// to UTF-8, and returns the length in bytes.
-static size_t measureUTF16(llvm::StringRef U8, int U16Units, bool &Valid) {
+// Returns the byte offset into the string that is an o

[PATCH] D59927: [clangd] Support UTF-32 (i.e. codepoint) offsets.

2019-03-28 Thread Sam McCall via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rL357173: [clangd] Support UTF-32 (i.e. codepoint) offsets. 
(authored by sammccall, committed by ).
Herald added a project: LLVM.
Herald added a subscriber: llvm-commits.

Repository:
  rL LLVM

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D59927/new/

https://reviews.llvm.org/D59927

Files:
  clang-tools-extra/trunk/clangd/Protocol.cpp
  clang-tools-extra/trunk/clangd/Protocol.h
  clang-tools-extra/trunk/clangd/SourceCode.cpp
  clang-tools-extra/trunk/unittests/clangd/SourceCodeTests.cpp

Index: clang-tools-extra/trunk/unittests/clangd/SourceCodeTests.cpp
===
--- clang-tools-extra/trunk/unittests/clangd/SourceCodeTests.cpp
+++ clang-tools-extra/trunk/unittests/clangd/SourceCodeTests.cpp
@@ -58,6 +58,15 @@
   EXPECT_EQ(lspLength("¥"), 2UL);
   // astral
   EXPECT_EQ(lspLength("😂"), 4UL);
+
+  WithContextValue UTF32(kCurrentOffsetEncoding, OffsetEncoding::UTF32);
+  EXPECT_EQ(lspLength(""), 0UL);
+  EXPECT_EQ(lspLength("ascii"), 5UL);
+  // BMP
+  EXPECT_EQ(lspLength("↓"), 1UL);
+  EXPECT_EQ(lspLength("¥"), 1UL);
+  // astral
+  EXPECT_EQ(lspLength("😂"), 1UL);
 }
 
 // The = → 🡆 below are ASCII (1 byte), BMP (3 bytes), and astral (4 bytes).
@@ -131,6 +140,63 @@
   EXPECT_THAT_EXPECTED(positionToOffset(File, position(3, 0)), llvm::Failed());
   EXPECT_THAT_EXPECTED(positionToOffset(File, position(3, 1)), llvm::Failed());
 
+  // Codepoints are similar, except near astral characters.
+  WithContextValue UTF32(kCurrentOffsetEncoding, OffsetEncoding::UTF32);
+  // line out of bounds
+  EXPECT_THAT_EXPECTED(positionToOffset(File, position(-1, 2)), llvm::Failed());
+  // first line
+  EXPECT_THAT_EXPECTED(positionToOffset(File, position(0, -1)),
+   llvm::Failed()); // out of range
+  EXPECT_THAT_EXPECTED(positionToOffset(File, position(0, 0)),
+   llvm::HasValue(0)); // first character
+  EXPECT_THAT_EXPECTED(positionToOffset(File, position(0, 3)),
+   llvm::HasValue(3)); // middle character
+  EXPECT_THAT_EXPECTED(positionToOffset(File, position(0, 6)),
+   llvm::HasValue(6)); // last character
+  EXPECT_THAT_EXPECTED(positionToOffset(File, position(0, 7)),
+   llvm::HasValue(7)); // the newline itself
+  EXPECT_THAT_EXPECTED(positionToOffset(File, position(0, 7), false),
+   llvm::HasValue(7));
+  EXPECT_THAT_EXPECTED(positionToOffset(File, position(0, 8)),
+   llvm::HasValue(7)); // out of range
+  EXPECT_THAT_EXPECTED(positionToOffset(File, position(0, 8), false),
+   llvm::Failed()); // out of range
+  // middle line
+  EXPECT_THAT_EXPECTED(positionToOffset(File, position(1, -1)),
+   llvm::Failed()); // out of range
+  EXPECT_THAT_EXPECTED(positionToOffset(File, position(1, 0)),
+   llvm::HasValue(8)); // first character
+  EXPECT_THAT_EXPECTED(positionToOffset(File, position(1, 3)),
+   llvm::HasValue(11)); // middle character
+  EXPECT_THAT_EXPECTED(positionToOffset(File, position(1, 3), false),
+   llvm::HasValue(11));
+  EXPECT_THAT_EXPECTED(positionToOffset(File, position(1, 6)),
+   llvm::HasValue(16)); // last character
+  EXPECT_THAT_EXPECTED(positionToOffset(File, position(1, 7)),
+   llvm::HasValue(17)); // the newline itself
+  EXPECT_THAT_EXPECTED(positionToOffset(File, position(1, 8)),
+   llvm::HasValue(17)); // out of range
+  EXPECT_THAT_EXPECTED(positionToOffset(File, position(1, 8), false),
+   llvm::Failed()); // out of range
+  // last line
+  EXPECT_THAT_EXPECTED(positionToOffset(File, position(2, -1)),
+   llvm::Failed()); // out of range
+  EXPECT_THAT_EXPECTED(positionToOffset(File, position(2, 0)),
+   llvm::HasValue(18)); // first character
+  EXPECT_THAT_EXPECTED(positionToOffset(File, position(2, 4)),
+   llvm::HasValue(22)); // Before astral character.
+  EXPECT_THAT_EXPECTED(positionToOffset(File, position(2, 5), false),
+   llvm::HasValue(26)); // after astral character
+  EXPECT_THAT_EXPECTED(positionToOffset(File, position(2, 7)),
+   llvm::HasValue(28)); // last character
+  EXPECT_THAT_EXPECTED(positionToOffset(File, position(2, 8)),
+   llvm::HasValue(29)); // EOF
+  EXPECT_THAT_EXPECTED(positionToOffset(File, position(2, 9), false),
+   llvm::Failed()); // out of range
+  // line out of bounds
+  EXPECT_THAT_EXPECTED(positionToOffset(File, position(3, 0)), llvm::Failed());
+  EXPECT_THAT_EXPECTED(positionToOffset(File, position(3, 1)), llvm::Failed());
+
   // Test UTF-8, where transformations are trivial.
   WithContextValue UTF8(kCurrentOffsetEncoding, Off

[PATCH] D59934: Compare SourceLocations from different TUs by FileID

2019-03-28 Thread Endre Fülöp via Phabricator via cfe-commits
gamesh411 created this revision.
Herald added subscribers: cfe-commits, jdoerfert, Szelethus, dkrupp.
Herald added a project: clang.

The comparison of SourceLocations is extended to handle locations from different
translation units, making the comparison based on the corresponding FileID.


Repository:
  rC Clang

https://reviews.llvm.org/D59934

Files:
  lib/Basic/SourceManager.cpp


Index: lib/Basic/SourceManager.cpp
===
--- lib/Basic/SourceManager.cpp
+++ lib/Basic/SourceManager.cpp
@@ -2035,7 +2035,10 @@
   return LIsScratch;
 return LOffs.second < ROffs.second;
   }
-  llvm_unreachable("Unsortable locations found");
+
+  // If SourceLocations originate from different TUs, but cannot be handled
+  // by one of the previous cases, just compare the FileIDs directly.
+  return LOffs.first < ROffs.first;
 }
 
 std::pair SourceManager::isInTheSameTranslationUnit(


Index: lib/Basic/SourceManager.cpp
===
--- lib/Basic/SourceManager.cpp
+++ lib/Basic/SourceManager.cpp
@@ -2035,7 +2035,10 @@
   return LIsScratch;
 return LOffs.second < ROffs.second;
   }
-  llvm_unreachable("Unsortable locations found");
+
+  // If SourceLocations originate from different TUs, but cannot be handled
+  // by one of the previous cases, just compare the FileIDs directly.
+  return LOffs.first < ROffs.first;
 }
 
 std::pair SourceManager::isInTheSameTranslationUnit(
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D59935: Disable warnings when indexing as a standalone action.

2019-03-28 Thread Sam McCall via Phabricator via cfe-commits
sammccall created this revision.
sammccall added a reviewer: hokein.
Herald added subscribers: cfe-commits, kadircet, arphaman, jkorous, ioeric, 
ilya-biryukov.
Herald added a project: clang.

- we don't record the warnings at all
- even when -Werror is set, we don't want to stop indexing for a warning
- this allows some analyses to be skipped which can save some CPU

https://github.com/clangd/clangd/issues/24


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D59935

Files:
  clangd/index/IndexAction.cpp


Index: clangd/index/IndexAction.cpp
===
--- clangd/index/IndexAction.cpp
+++ clangd/index/IndexAction.cpp
@@ -135,6 +135,9 @@
   bool BeginInvocation(CompilerInstance &CI) override {
 // We want all comments, not just the doxygen ones.
 CI.getLangOpts().CommentOpts.ParseAllComments = true;
+// Index the whole file even if there are warnings and -Werror is't set.
+// Avoids some analyses too.
+CI.getDiagnosticOpts().IgnoreWarnings = true;
 return WrapperFrontendAction::BeginInvocation(CI);
   }
 


Index: clangd/index/IndexAction.cpp
===
--- clangd/index/IndexAction.cpp
+++ clangd/index/IndexAction.cpp
@@ -135,6 +135,9 @@
   bool BeginInvocation(CompilerInstance &CI) override {
 // We want all comments, not just the doxygen ones.
 CI.getLangOpts().CommentOpts.ParseAllComments = true;
+// Index the whole file even if there are warnings and -Werror is't set.
+// Avoids some analyses too.
+CI.getDiagnosticOpts().IgnoreWarnings = true;
 return WrapperFrontendAction::BeginInvocation(CI);
   }
 
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D59934: Compare SourceLocations from different TUs by FileID

2019-03-28 Thread Endre Fülöp via Phabricator via cfe-commits
gamesh411 added a comment.

Hi!

This issue came up during the generation BugReports of BugPaths containing 
macro-expansions, where the spelling location and expansion locations were in 
different files.
With this change, we make such SourceLocations comparable by their FileIDs.


Repository:
  rC Clang

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D59934/new/

https://reviews.llvm.org/D59934



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


[PATCH] D59923: [Driver] Simplify -g level computation and its interaction with -gsplit-dwarf

2019-03-28 Thread Fangrui Song via Phabricator via cfe-commits
MaskRay updated this revision to Diff 192637.
MaskRay added a comment.

Simplify comments


Repository:
  rC Clang

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D59923/new/

https://reviews.llvm.org/D59923

Files:
  lib/Driver/ToolChains/Clang.cpp
  test/Driver/split-debug.c


Index: test/Driver/split-debug.c
===
--- test/Driver/split-debug.c
+++ test/Driver/split-debug.c
@@ -68,7 +68,7 @@
 // RUN: FileCheck -check-prefix=CHECK-SPLIT-WITH-GMLT < %t %s
 //
 // CHECK-SPLIT-WITH-GMLT: "-enable-split-dwarf"
-// CHECK-SPLIT-WITH-GMLT: "-debug-info-kind=line-tables-only"
+// CHECK-SPLIT-WITH-GMLT: "-debug-info-kind=limited"
 // CHECK-SPLIT-WITH-GMLT: "-split-dwarf-file"
 
 // RUN: %clang -target x86_64-unknown-linux-gnu -gsplit-dwarf 
-fno-split-dwarf-inlining -S -### %s 2> %t
Index: lib/Driver/ToolChains/Clang.cpp
===
--- lib/Driver/ToolChains/Clang.cpp
+++ lib/Driver/ToolChains/Clang.cpp
@@ -3155,35 +3155,22 @@
 SplitDWARFInlining = false;
   }
 
-  if (const Arg *A = Args.getLastArg(options::OPT_g_Group)) {
-if (checkDebugInfoOption(A, Args, D, TC)) {
-  // If the last option explicitly specified a debug-info level, use it.
-  if (A->getOption().matches(options::OPT_gN_Group)) {
-DebugInfoKind = DebugLevelToInfoKind(*A);
-// If you say "-gsplit-dwarf -gline-tables-only", -gsplit-dwarf loses.
-// But -gsplit-dwarf is not a g_group option, hence we have to check 
the
-// order explicitly. If -gsplit-dwarf wins, we fix DebugInfoKind later.
-// This gets a bit more complicated if you've disabled inline info in
-// the skeleton CUs (SplitDWARFInlining) - then there's value in
-// composing split-dwarf and line-tables-only, so let those compose
-// naturally in that case. And if you just turned off debug info,
-// (-gsplit-dwarf -g0) - do that.
-if (DwarfFission != DwarfFissionKind::None) {
-  if (A->getIndex() > SplitDWARFArg->getIndex()) {
-if (DebugInfoKind == codegenoptions::NoDebugInfo ||
-DebugInfoKind == codegenoptions::DebugDirectivesOnly ||
-(DebugInfoKind == codegenoptions::DebugLineTablesOnly &&
- SplitDWARFInlining))
-  DwarfFission = DwarfFissionKind::None;
-  } else if (SplitDWARFInlining)
-DebugInfoKind = codegenoptions::NoDebugInfo;
-}
-  } else {
-// For any other 'g' option, use Limited.
-DebugInfoKind = codegenoptions::LimitedDebugInfo;
-  }
-} else {
-  DebugInfoKind = codegenoptions::LimitedDebugInfo;
+  if (const Arg *A = Args.getLastArg(options::OPT_g_Group, 
options::OPT_gsplit_dwarf)) {
+DebugInfoKind = codegenoptions::LimitedDebugInfo;
+
+// If the last option explicitly specified a debug-info level, use it.
+if (checkDebugInfoOption(A, Args, D, TC) &&
+A->getOption().matches(options::OPT_gN_Group)) {
+  DebugInfoKind = DebugLevelToInfoKind(*A);
+  // For -g0 or -gline-tables-only, drop -gsplit-dwarf. This gets a bit 
more
+  // complicated if you've disabled inline info in the skeleton CUs
+  // (SplitDWARFInlining) - then there's value in composing split-dwarf and
+  // line-tables-only, so let those compose naturally in that case.
+  if (DebugInfoKind == codegenoptions::NoDebugInfo ||
+  DebugInfoKind == codegenoptions::DebugDirectivesOnly ||
+  (DebugInfoKind == codegenoptions::DebugLineTablesOnly &&
+   SplitDWARFInlining))
+DwarfFission = DwarfFissionKind::None;
 }
   }
 
@@ -3258,16 +3245,12 @@
   }
 }
 
-  // -gsplit-dwarf should turn on -g and enable the backend dwarf
-  // splitting and extraction.
+  // -gsplit-dwarf enables the backend dwarf splitting and extraction.
   if (T.isOSBinFormatELF()) {
 if (!SplitDWARFInlining)
   CmdArgs.push_back("-fno-split-dwarf-inlining");
 
 if (DwarfFission != DwarfFissionKind::None) {
-  if (DebugInfoKind == codegenoptions::NoDebugInfo)
-DebugInfoKind = codegenoptions::LimitedDebugInfo;
-
   if (DwarfFission == DwarfFissionKind::Single)
 CmdArgs.push_back("-enable-split-dwarf=single");
   else


Index: test/Driver/split-debug.c
===
--- test/Driver/split-debug.c
+++ test/Driver/split-debug.c
@@ -68,7 +68,7 @@
 // RUN: FileCheck -check-prefix=CHECK-SPLIT-WITH-GMLT < %t %s
 //
 // CHECK-SPLIT-WITH-GMLT: "-enable-split-dwarf"
-// CHECK-SPLIT-WITH-GMLT: "-debug-info-kind=line-tables-only"
+// CHECK-SPLIT-WITH-GMLT: "-debug-info-kind=limited"
 // CHECK-SPLIT-WITH-GMLT: "-split-dwarf-file"
 
 // RUN: %clang -target x86_64-unknown-linux-gnu -gsplit-dwarf -fno-split-dwarf-inlining -S -### %s 2> %t
Index: lib/Driver/ToolChains/Clang.cpp
==

[PATCH] D59923: [Driver] Simplify -g level computation and its interaction with -gsplit-dwarf

2019-03-28 Thread Fangrui Song via Phabricator via cfe-commits
MaskRay marked 4 inline comments as done.
MaskRay added inline comments.



Comment at: lib/Driver/ToolChains/Clang.cpp:3167
+  // But -gsplit-dwarf is not a g_Group option, hence we have to check the
+  // order explicitly. If -gsplit-dwarf wins, we fix DebugInfoKind later.
+  // This gets a bit more complicated if you've disabled inline info in

probinson wrote:
> Regarding `If -gsplit-dwarf wins, we fix DebugInfoKind later.`
> Is that still true?  It looks like -gsplit-dwarf is handled here now, because 
> you removed the compensating code from lines 3268-3269.
Deleted.


Repository:
  rC Clang

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D59923/new/

https://reviews.llvm.org/D59923



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


[PATCH] D59934: Compare SourceLocations from different TUs by FileID

2019-03-28 Thread Roman Lebedev via Phabricator via cfe-commits
lebedev.ri added a comment.

Test?


Repository:
  rC Clang

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D59934/new/

https://reviews.llvm.org/D59934



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


[PATCH] D59935: Disable warnings when indexing as a standalone action.

2019-03-28 Thread Haojian Wu via Phabricator via cfe-commits
hokein added inline comments.



Comment at: clangd/index/IndexAction.cpp:140
+// Avoids some analyses too.
+CI.getDiagnosticOpts().IgnoreWarnings = true;
 return WrapperFrontendAction::BeginInvocation(CI);

Can we add a unittest for this?

IIRC, `IgnoreWarnings` option must be set before `CompilerInstance` is created, 
otherwise it doesn't take affect, see 
https://github.com/llvm-mirror/clang-tools-extra/blob/master/clangd/CodeComplete.cpp#L1029


Repository:
  rCTE Clang Tools Extra

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D59935/new/

https://reviews.llvm.org/D59935



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


[clang-tools-extra] r357175 - [clangd] Update error message to fix tests after r357173

2019-03-28 Thread Sam McCall via cfe-commits
Author: sammccall
Date: Thu Mar 28 08:07:15 2019
New Revision: 357175

URL: http://llvm.org/viewvc/llvm-project?rev=357175&view=rev
Log:
[clangd] Update error message to fix tests after r357173

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

Modified: clang-tools-extra/trunk/unittests/clangd/DraftStoreTests.cpp
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/unittests/clangd/DraftStoreTests.cpp?rev=357175&r1=357174&r2=357175&view=diff
==
--- clang-tools-extra/trunk/unittests/clangd/DraftStoreTests.cpp (original)
+++ clang-tools-extra/trunk/unittests/clangd/DraftStoreTests.cpp Thu Mar 28 
08:07:15 2019
@@ -240,7 +240,7 @@ TEST(DraftStoreIncrementalUpdateTest, St
 
   EXPECT_TRUE(!Result);
   EXPECT_EQ(toString(Result.takeError()),
-"UTF-16 offset 100 is invalid for line 0");
+"utf-16 offset 100 is invalid for line 0");
 }
 
 TEST(DraftStoreIncrementalUpdateTest, EndCharOutOfRange) {
@@ -261,7 +261,7 @@ TEST(DraftStoreIncrementalUpdateTest, En
 
   EXPECT_TRUE(!Result);
   EXPECT_EQ(toString(Result.takeError()),
-"UTF-16 offset 100 is invalid for line 0");
+"utf-16 offset 100 is invalid for line 0");
 }
 
 TEST(DraftStoreIncrementalUpdateTest, StartLineOutOfRange) {
@@ -335,7 +335,7 @@ TEST(DraftStoreIncrementalUpdateTest, In
 
   EXPECT_TRUE(!Result);
   EXPECT_EQ(toString(Result.takeError()),
-"UTF-16 offset 100 is invalid for line 0");
+"utf-16 offset 100 is invalid for line 0");
 
   Optional Contents = DS.getDraft(File);
   EXPECT_TRUE(Contents);


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


[PATCH] D59103: [clang-tidy] New checker bugprone-incomplete-comparison-operator

2019-03-28 Thread Kalle Huttunen via Phabricator via cfe-commits
kallehuttunen added a comment.

In D59103#1423307 , @aaron.ballman 
wrote:

> In D59103#1422775 , @kallehuttunen 
> wrote:
>
> > Another idea that came to my mind would be to enable this check only for 
> > annotated types. So warning for missing field access would be only given 
> > for types that have for example `[[clang::annotate("value type")]]` 
> > annotation. Possibly other kinds of checks could be also developed for 
> > types that have the given annotation.
>
>
> I don't think `annotate` would be a good choice because the primary purpose 
> of that one is to pass that attribute information down to the backend and 
> using it for this purpose feels a bit hackish. However, we could always add a 
> new attribute if needed, but I'm not convinced an attribute is the right 
> approach either (but then again, I'm also lacking information I'm sure).
>
> What other kinds of checks do you have in mind and what are the semantics of 
> the attribute you're thinking of?


I was thinking about something along the lines of having an attribute to mark 
types to be a "value type" as defined in Herb's metaclasses proposal (chapter 
3.5 in https://herbsutter.files.wordpress.com/2017/07/p0707r1.pdf). There could 
be then checks for having default ctor, no virtual functions etc in addition to 
this check for those types. But then again now that I think about it, a 
"string" class is an counterexample for this: it can be a value (regular) type, 
but when comparing instances you don't want to access the "capacity" member.


Repository:
  rCTE Clang Tools Extra

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D59103/new/

https://reviews.llvm.org/D59103



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


[PATCH] D59901: [analyzer] PR41239: Fix a crash on invalid source location in NoStoreFuncVisitor.

2019-03-28 Thread Alexander Kornienko via Phabricator via cfe-commits
alexfh added a comment.

I've posted another test case to https://bugs.llvm.org/show_bug.cgi?id=41239. 
It may already be covered by the fix. Could you check?


Repository:
  rC Clang

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D59901/new/

https://reviews.llvm.org/D59901



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


[PATCH] D59899: gn build: Add some build files for clangd

2019-03-28 Thread Mirko Bonadei via Phabricator via cfe-commits
mbonadei accepted this revision.
mbonadei added a comment.
This revision is now accepted and ready to land.

Sorry for the delay, LGTM % 2 small comments.




Comment at: 
llvm/utils/gn/secondary/clang-tools-extra/clang-apply-replacements/BUILD.gn:2
 static_library("clang-apply-replacements") {
+  output_name = "clangApplyReplacements"
   configs += [ "//llvm/utils/gn/build:clang_code" ]

Oh, I forgot to add this! Thanks!



Comment at: llvm/utils/gn/secondary/clang-tools-extra/clangd/BUILD.gn:32
+"//clang/lib/Serialization",
+"//clang/lib/Tooling/Core",
+"//clang/lib/Tooling/Inclusions",

Missing //clang/lib/Tooling ?



Comment at: 
llvm/utils/gn/secondary/clang-tools-extra/clangd/refactor/tweaks/BUILD.gn:7
+  configs += [ "//llvm/utils/gn/build:clang_code" ]
+  deps = [
+"//clang-tools-extra/clangd",

Missing "//llvm/lib/Support"?

Probably it is ok, since it is a `source_set`, but am I following the 1:1 
matching rule.



Comment at: llvm/utils/gn/secondary/clang-tools-extra/clangd/tool/BUILD.gn:9
+write_cmake_config("features") {
+  # FIXME: Try moving Features.inc.in to tools, seems like a better location.
+  input = "../Features.inc.in"

+1, if that is not possible this target should be in clangd/BUILD.gn (it is 
more natural).


CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D59899/new/

https://reviews.llvm.org/D59899



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


[PATCH] D59815: [Driver] Enable -fsanitize-address-globals-dead-stripping by default on PS4.

2019-03-28 Thread pierre gousseau via Phabricator via cfe-commits
pgousseau added a comment.

In D59815#1442868 , @probinson wrote:

> This is fine for PS4, I'm just curious whether anyone knows if there's a 
> predicate that means something like "target does not use GNU tools" so we 
> don't have to itemize Fuschia and PS4 this way.


It seems if there was such method it would be in Toolchain.h but I cant seem to 
find one... This is to workaround a bug though so I am not sure there are nicer 
solutions...


Repository:
  rC Clang

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D59815/new/

https://reviews.llvm.org/D59815



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


[PATCH] D59932: [clang-tidy] **Prototype**: Add fix description to clang-tidy checks.

2019-03-28 Thread Eugene Zelenko via Phabricator via cfe-commits
Eugene.Zelenko added inline comments.



Comment at: clang-tidy/ClangTidyCheck.h:109
+  /// not supported.
+  virtual llvm::StringRef fixDescription() { return ""; }
+

return {} could be used instead.



Comment at: clang-tidy/ClangTidyDiagnosticConsumer.cpp:266
+return I->second.first;
+  return "";
+}

return {} could be used instead.



Comment at: clang-tidy/ClangTidyDiagnosticConsumer.cpp:274
+return I->second.second;
   return "";
 }

return {} could be used instead.


Repository:
  rCTE Clang Tools Extra

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D59932/new/

https://reviews.llvm.org/D59932



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


[PATCH] D59935: Disable warnings when indexing as a standalone action.

2019-03-28 Thread Sam McCall via Phabricator via cfe-commits
sammccall updated this revision to Diff 192650.
sammccall added a comment.
Herald added a subscriber: jdoerfert.

Add tests, fix setting the flag too late.


Repository:
  rCTE Clang Tools Extra

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D59935/new/

https://reviews.llvm.org/D59935

Files:
  clang-tidy/tool/clang-tidy-diff.py
  clang-tidy/tool/run-clang-tidy.py
  clangd/ClangdLSPServer.cpp
  clangd/ClangdLSPServer.h
  clangd/Protocol.cpp
  clangd/Protocol.h
  clangd/SourceCode.cpp
  clangd/SourceCode.h
  clangd/index/IndexAction.cpp
  clangd/index/SymbolLocation.h
  clangd/tool/ClangdMain.cpp
  test/clang-tidy/bugprone-parent-virtual-call.cpp
  test/clang-tidy/run-clang-tidy.cpp
  test/clangd/utf8.test
  unittests/clangd/IndexActionTests.cpp
  unittests/clangd/SourceCodeTests.cpp

Index: unittests/clangd/SourceCodeTests.cpp
===
--- unittests/clangd/SourceCodeTests.cpp
+++ unittests/clangd/SourceCodeTests.cpp
@@ -6,6 +6,8 @@
 //
 //===--===//
 #include "Annotations.h"
+#include "Context.h"
+#include "Protocol.h"
 #include "SourceCode.h"
 #include "llvm/Support/Error.h"
 #include "llvm/Support/raw_os_ostream.h"
@@ -21,14 +23,9 @@
 using llvm::HasValue;
 
 MATCHER_P2(Pos, Line, Col, "") {
-  return arg.line == Line && arg.character == Col;
+  return arg.line == int(Line) && arg.character == int(Col);
 }
 
-// The = → 🡆 below are ASCII (1 byte), BMP (3 bytes), and astral (4 bytes).
-const char File[] = R"(0:0 = 0
-1:0 → 8
-2:0 🡆 18)";
-
 /// A helper to make tests easier to read.
 Position position(int line, int character) {
   Position Pos;
@@ -52,8 +49,37 @@
   EXPECT_EQ(lspLength("¥"), 1UL);
   // astral
   EXPECT_EQ(lspLength("😂"), 2UL);
+
+  WithContextValue UTF8(kCurrentOffsetEncoding, OffsetEncoding::UTF8);
+  EXPECT_EQ(lspLength(""), 0UL);
+  EXPECT_EQ(lspLength("ascii"), 5UL);
+  // BMP
+  EXPECT_EQ(lspLength("↓"), 3UL);
+  EXPECT_EQ(lspLength("¥"), 2UL);
+  // astral
+  EXPECT_EQ(lspLength("😂"), 4UL);
+
+  WithContextValue UTF32(kCurrentOffsetEncoding, OffsetEncoding::UTF32);
+  EXPECT_EQ(lspLength(""), 0UL);
+  EXPECT_EQ(lspLength("ascii"), 5UL);
+  // BMP
+  EXPECT_EQ(lspLength("↓"), 1UL);
+  EXPECT_EQ(lspLength("¥"), 1UL);
+  // astral
+  EXPECT_EQ(lspLength("😂"), 1UL);
 }
 
+// The = → 🡆 below are ASCII (1 byte), BMP (3 bytes), and astral (4 bytes).
+const char File[] = R"(0:0 = 0
+1:0 → 8
+2:0 🡆 18)";
+struct Line {
+  unsigned Number;
+  unsigned Offset;
+  unsigned Length;
+};
+Line FileLines[] = {Line{0, 0, 7}, Line{1, 8, 9}, Line{2, 18, 11}};
+
 TEST(SourceCodeTests, PositionToOffset) {
   // line out of bounds
   EXPECT_THAT_EXPECTED(positionToOffset(File, position(-1, 2)), llvm::Failed());
@@ -113,6 +139,80 @@
   // line out of bounds
   EXPECT_THAT_EXPECTED(positionToOffset(File, position(3, 0)), llvm::Failed());
   EXPECT_THAT_EXPECTED(positionToOffset(File, position(3, 1)), llvm::Failed());
+
+  // Codepoints are similar, except near astral characters.
+  WithContextValue UTF32(kCurrentOffsetEncoding, OffsetEncoding::UTF32);
+  // line out of bounds
+  EXPECT_THAT_EXPECTED(positionToOffset(File, position(-1, 2)), llvm::Failed());
+  // first line
+  EXPECT_THAT_EXPECTED(positionToOffset(File, position(0, -1)),
+   llvm::Failed()); // out of range
+  EXPECT_THAT_EXPECTED(positionToOffset(File, position(0, 0)),
+   llvm::HasValue(0)); // first character
+  EXPECT_THAT_EXPECTED(positionToOffset(File, position(0, 3)),
+   llvm::HasValue(3)); // middle character
+  EXPECT_THAT_EXPECTED(positionToOffset(File, position(0, 6)),
+   llvm::HasValue(6)); // last character
+  EXPECT_THAT_EXPECTED(positionToOffset(File, position(0, 7)),
+   llvm::HasValue(7)); // the newline itself
+  EXPECT_THAT_EXPECTED(positionToOffset(File, position(0, 7), false),
+   llvm::HasValue(7));
+  EXPECT_THAT_EXPECTED(positionToOffset(File, position(0, 8)),
+   llvm::HasValue(7)); // out of range
+  EXPECT_THAT_EXPECTED(positionToOffset(File, position(0, 8), false),
+   llvm::Failed()); // out of range
+  // middle line
+  EXPECT_THAT_EXPECTED(positionToOffset(File, position(1, -1)),
+   llvm::Failed()); // out of range
+  EXPECT_THAT_EXPECTED(positionToOffset(File, position(1, 0)),
+   llvm::HasValue(8)); // first character
+  EXPECT_THAT_EXPECTED(positionToOffset(File, position(1, 3)),
+   llvm::HasValue(11)); // middle character
+  EXPECT_THAT_EXPECTED(positionToOffset(File, position(1, 3), false),
+   llvm::HasValue(11));
+  EXPECT_THAT_EXPECTED(positionToOffset(File, position(1, 6)),
+   llvm::HasValue(16)); // last character
+  EXPECT_THAT_EXPECTED(positionToOffset(File, position(1, 7)),
+   llvm::

[PATCH] D59935: Disable warnings when indexing as a standalone action.

2019-03-28 Thread Sam McCall via Phabricator via cfe-commits
sammccall updated this revision to Diff 192651.
sammccall added a comment.

fix baseline


Repository:
  rCTE Clang Tools Extra

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D59935/new/

https://reviews.llvm.org/D59935

Files:
  clangd/index/IndexAction.cpp
  unittests/clangd/IndexActionTests.cpp


Index: unittests/clangd/IndexActionTests.cpp
===
--- unittests/clangd/IndexActionTests.cpp
+++ unittests/clangd/IndexActionTests.cpp
@@ -29,6 +29,8 @@
 
 MATCHER_P(HasDigest, Digest, "") { return arg.Digest == Digest; }
 
+MATCHER_P(HasName, Name, "") { return arg.Name == Name; }
+
 MATCHER(HasSameURI, "") {
   llvm::StringRef URI = testing::get<0>(arg);
   const std::string &Path = testing::get<1>(arg);
@@ -43,6 +45,7 @@
 
 void checkNodesAreInitialized(const IndexFileIn &IndexFile,
   const std::vector &Paths) {
+  ASSERT_TRUE(IndexFile.Sources);
   EXPECT_THAT(Paths.size(), IndexFile.Sources->size());
   for (llvm::StringRef Path : Paths) {
 auto URI = toUri(Path);
@@ -224,6 +227,27 @@
 HasDigest(digest(HeaderCode));
 }
 
+TEST_F(IndexActionTest, NoWarnings) {
+  std::string MainFilePath = testPath("main.cpp");
+  std::string MainCode = R"cpp(
+  void foo(int x) {
+if (x = 1) // -Wparentheses
+  return;
+if (x = 1) // -Wparentheses
+  return;
+  }
+  void bar() {}
+  )cpp";
+  addFile(MainFilePath, MainCode);
+  // We set -ferror-limit so the warning-promoted-to-error would be fatal.
+  // This would cause indexing to stop (if warnings weren't disabled).
+  IndexFileIn IndexFile = runIndexingAction(
+  MainFilePath, {"-ferror-limit=1", "-Wparentheses", "-Werror"});
+  ASSERT_TRUE(IndexFile.Sources);
+  ASSERT_NE(0u, IndexFile.Sources->size());
+  EXPECT_THAT(*IndexFile.Symbols, ElementsAre(HasName("foo"), HasName("bar")));
+}
+
 } // namespace
 } // namespace clangd
 } // namespace clang
Index: clangd/index/IndexAction.cpp
===
--- clangd/index/IndexAction.cpp
+++ clangd/index/IndexAction.cpp
@@ -135,6 +135,11 @@
   bool BeginInvocation(CompilerInstance &CI) override {
 // We want all comments, not just the doxygen ones.
 CI.getLangOpts().CommentOpts.ParseAllComments = true;
+// Index the whole file even if there are warnings and -Werror is't set.
+// Avoids some analyses too. Set in two places as we're late to the party.
+CI.getDiagnosticOpts().IgnoreWarnings = true;
+CI.getDiagnostics().setIgnoreAllWarnings(true);
+
 return WrapperFrontendAction::BeginInvocation(CI);
   }
 


Index: unittests/clangd/IndexActionTests.cpp
===
--- unittests/clangd/IndexActionTests.cpp
+++ unittests/clangd/IndexActionTests.cpp
@@ -29,6 +29,8 @@
 
 MATCHER_P(HasDigest, Digest, "") { return arg.Digest == Digest; }
 
+MATCHER_P(HasName, Name, "") { return arg.Name == Name; }
+
 MATCHER(HasSameURI, "") {
   llvm::StringRef URI = testing::get<0>(arg);
   const std::string &Path = testing::get<1>(arg);
@@ -43,6 +45,7 @@
 
 void checkNodesAreInitialized(const IndexFileIn &IndexFile,
   const std::vector &Paths) {
+  ASSERT_TRUE(IndexFile.Sources);
   EXPECT_THAT(Paths.size(), IndexFile.Sources->size());
   for (llvm::StringRef Path : Paths) {
 auto URI = toUri(Path);
@@ -224,6 +227,27 @@
 HasDigest(digest(HeaderCode));
 }
 
+TEST_F(IndexActionTest, NoWarnings) {
+  std::string MainFilePath = testPath("main.cpp");
+  std::string MainCode = R"cpp(
+  void foo(int x) {
+if (x = 1) // -Wparentheses
+  return;
+if (x = 1) // -Wparentheses
+  return;
+  }
+  void bar() {}
+  )cpp";
+  addFile(MainFilePath, MainCode);
+  // We set -ferror-limit so the warning-promoted-to-error would be fatal.
+  // This would cause indexing to stop (if warnings weren't disabled).
+  IndexFileIn IndexFile = runIndexingAction(
+  MainFilePath, {"-ferror-limit=1", "-Wparentheses", "-Werror"});
+  ASSERT_TRUE(IndexFile.Sources);
+  ASSERT_NE(0u, IndexFile.Sources->size());
+  EXPECT_THAT(*IndexFile.Symbols, ElementsAre(HasName("foo"), HasName("bar")));
+}
+
 } // namespace
 } // namespace clangd
 } // namespace clang
Index: clangd/index/IndexAction.cpp
===
--- clangd/index/IndexAction.cpp
+++ clangd/index/IndexAction.cpp
@@ -135,6 +135,11 @@
   bool BeginInvocation(CompilerInstance &CI) override {
 // We want all comments, not just the doxygen ones.
 CI.getLangOpts().CommentOpts.ParseAllComments = true;
+// Index the whole file even if there are warnings and -Werror is't set.
+// Avoids some analyses too. Set in two places as we're late to the party.
+CI.getDiagnosticOpts().IgnoreWarnings = true;
+CI.getDiagno

[PATCH] D59935: Disable warnings when indexing as a standalone action.

2019-03-28 Thread Sam McCall via Phabricator via cfe-commits
sammccall marked an inline comment as done.
sammccall added inline comments.



Comment at: clangd/index/IndexAction.cpp:140
+// Avoids some analyses too.
+CI.getDiagnosticOpts().IgnoreWarnings = true;
 return WrapperFrontendAction::BeginInvocation(CI);

hokein wrote:
> Can we add a unittest for this?
> 
> IIRC, `IgnoreWarnings` option must be set before `CompilerInstance` is 
> created, otherwise it doesn't take affect, see 
> https://github.com/llvm-mirror/clang-tools-extra/blob/master/clangd/CodeComplete.cpp#L1029
Added test, thanks.

You're right, the flag has already been copied to the diagnostics client. It's 
too late to set it here.

Unfortunately we don't control where the CompilerInstance is created, but this 
is semantically the right layer to make the decision to suppress warnings. So 
I've just set it on the diagnostics client too :-/


Repository:
  rCTE Clang Tools Extra

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D59935/new/

https://reviews.llvm.org/D59935



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


[PATCH] D59873: Add additional mangling for struct members of non trivial structs

2019-03-28 Thread Dan Zimmerman via Phabricator via cfe-commits
danzimm updated this revision to Diff 192652.
danzimm added a comment.

Add a third level to ensure nontrivial structs within structs within structs 
works (this suggests that N embeddings works too). Also change the invocation 
of the test


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D59873/new/

https://reviews.llvm.org/D59873

Files:
  clang/lib/CodeGen/CGNonTrivialStruct.cpp
  clang/test/CodeGenObjC/nontrivial-c-struct-within-struct-name.m
  clang/test/CodeGenObjC/strong-in-c-struct.m

Index: clang/test/CodeGenObjC/strong-in-c-struct.m
===
--- clang/test/CodeGenObjC/strong-in-c-struct.m
+++ clang/test/CodeGenObjC/strong-in-c-struct.m
@@ -89,12 +89,12 @@
 // CHECK: define void @test_constructor_destructor_StrongOuter()
 // CHECK: %[[T:.*]] = alloca %[[STRUCT_STRONGOUTER:.*]], align 8
 // CHECK: %[[V0:.*]] = bitcast %[[STRUCT_STRONGOUTER]]* %[[T]] to i8**
-// CHECK: call void @__default_constructor_8_s16_s24(i8** %[[V0]])
+// CHECK: call void @__default_constructor_8_S_s16_s24(i8** %[[V0]])
 // CHECK: %[[V1:.*]] = bitcast %[[STRUCT_STRONGOUTER]]* %[[T]] to i8**
-// CHECK: call void @__destructor_8_s16_s24(i8** %[[V1]])
+// CHECK: call void @__destructor_8_S_s16_s24(i8** %[[V1]])
 // CHECK: ret void
 
-// CHECK: define linkonce_odr hidden void @__default_constructor_8_s16_s24(i8** %[[DST:.*]])
+// CHECK: define linkonce_odr hidden void @__default_constructor_8_S_s16_s24(i8** %[[DST:.*]])
 // CHECK: %[[DST_ADDR:.*]] = alloca i8**, align 8
 // CHECK: store i8** %[[DST]], i8*** %[[DST_ADDR]], align 8
 // CHECK: %[[V0:.*]] = load i8**, i8*** %[[DST_ADDR]], align 8
@@ -117,7 +117,7 @@
 // CHECK: call void @llvm.memset.p0i8.i64(i8* align 8 %[[V4]], i8 0, i64 8, i1 false)
 // CHECK: ret void
 
-// CHECK: define linkonce_odr hidden void @__destructor_8_s16_s24(i8** %[[DST:.*]])
+// CHECK: define linkonce_odr hidden void @__destructor_8_S_s16_s24(i8** %[[DST:.*]])
 // CHECK: %[[DST_ADDR:.*]] = alloca i8**, align 8
 // CHECK: store i8** %[[DST]], i8*** %[[DST_ADDR]], align 8
 // CHECK: %[[V0:.*]] = load i8**, i8*** %[[DST_ADDR]], align 8
@@ -149,12 +149,12 @@
 // CHECK: %[[V0:.*]] = load %[[STRUCT_STRONGOUTER]]*, %[[STRUCT_STRONGOUTER]]** %[[S_ADDR]], align 8
 // CHECK: %[[V1:.*]] = bitcast %[[STRUCT_STRONGOUTER]]* %[[T]] to i8**
 // CHECK: %[[V2:.*]] = bitcast %[[STRUCT_STRONGOUTER]]* %[[V0]] to i8**
-// CHECK: call void @__copy_constructor_8_8_t0w16_s16_s24_t32w8(i8** %[[V1]], i8** %[[V2]])
+// CHECK: call void @__copy_constructor_8_8_S_t0w16_s16_s24_t32w8(i8** %[[V1]], i8** %[[V2]])
 // CHECK: %[[V3:.*]] = bitcast %[[STRUCT_STRONGOUTER]]* %[[T]] to i8**
-// CHECK: call void @__destructor_8_s16_s24(i8** %[[V3]])
+// CHECK: call void @__destructor_8_S_s16_s24(i8** %[[V3]])
 // CHECK: ret void
 
-// CHECK: define linkonce_odr hidden void @__copy_constructor_8_8_t0w16_s16_s24_t32w8(i8** %[[DST:.*]], i8** %[[SRC:.*]])
+// CHECK: define linkonce_odr hidden void @__copy_constructor_8_8_S_t0w16_s16_s24_t32w8(i8** %[[DST:.*]], i8** %[[SRC:.*]])
 // CHECK: %[[DST_ADDR:.*]] = alloca i8**, align 8
 // CHECK: %[[SRC_ADDR:.*]] = alloca i8**, align 8
 // CHECK: store i8** %[[DST]], i8*** %[[DST_ADDR]], align 8
@@ -208,7 +208,7 @@
   StrongOuter t = *s;
 }
 
-/// CHECK: define linkonce_odr hidden void @__copy_assignment_8_8_t0w16_s16_s24_t32w8(i8** %[[DST:.*]], i8** %[[SRC:.*]])
+/// CHECK: define linkonce_odr hidden void @__copy_assignment_8_8_S_t0w16_s16_s24_t32w8(i8** %[[DST:.*]], i8** %[[SRC:.*]])
 // CHECK: %[[DST_ADDR:.*]] = alloca i8**, align 8
 // CHECK: %[[SRC_ADDR:.*]] = alloca i8**, align 8
 // CHECK: store i8** %[[DST]], i8*** %[[DST_ADDR]], align 8
@@ -231,15 +231,15 @@
 // CHECK: define void @test_move_constructor_StrongOuter()
 // CHECK: %[[T1:.*]] = getelementptr inbounds %[[STRUCT_BLOCK_BYREF_T:.*]], %[[STRUCT_BLOCK_BYREF_T]]* %{{.*}}, i32 0, i32 7
 // CHECK: %[[V1:.*]] = bitcast %[[STRUCT_STRONGOUTER]]* %[[T1]] to i8**
-// CHECK: call void @__default_constructor_8_s16_s24(i8** %[[V1]])
+// CHECK: call void @__default_constructor_8_S_s16_s24(i8** %[[V1]])
 // CHECK: %[[T2:.*]] = getelementptr inbounds %[[STRUCT_BLOCK_BYREF_T]], %[[STRUCT_BLOCK_BYREF_T]]* %{{.*}}, i32 0, i32 7
 // CHECK: %[[V9:.*]] = bitcast %[[STRUCT_STRONGOUTER]]* %[[T2]] to i8**
-// CHECK: call void @__destructor_8_s16_s24(i8** %[[V9]])
+// CHECK: call void @__destructor_8_S_s16_s24(i8** %[[V9]])
 
 // CHECK: define internal void @__Block_byref_object_copy_(i8*, i8*)
-// CHECK: call void @__move_constructor_8_8_t0w16_s16_s24_t32w8(
+// CHECK: call void @__move_constructor_8_8_S_t0w16_s16_s24_t32w8(
 
-// CHECK: define linkonce_odr hidden void @__move_constructor_8_8_t0w16_s16_s24_t32w8(i8** %[[DST:.*]], i8** %[[SRC:.*]])
+// CHECK: define linkonce_odr hidden void @__move_constructor_8_8_S_t0w16_s16_s24_t32w8(i8** %[[DST:.*]], i8** %[[SRC:.*]])
 // CHECK: %[[DST_ADDR:.*]] = alloca i8**, align 8
 // CHECK: %[[SRC_ADDR:.*]] = alloca i

[PATCH] D59923: [Driver] Simplify -g level computation and its interaction with -gsplit-dwarf

2019-03-28 Thread Paul Robinson via Phabricator via cfe-commits
probinson accepted this revision.
probinson added a comment.
This revision is now accepted and ready to land.

LGTM.  I wish it had occurred to me to pass both OPT_g_Group and 
OPT_gsplit_dwarf to the same getLastArgs call in the first place.


Repository:
  rC Clang

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D59923/new/

https://reviews.llvm.org/D59923



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


[PATCH] D59873: Add additional mangling for struct members of non trivial structs

2019-03-28 Thread Dan Zimmerman via Phabricator via cfe-commits
danzimm added a comment.

@smeenai good idea on the third level!

Yep, I'll need somebody to commit this for me, thanks!


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D59873/new/

https://reviews.llvm.org/D59873



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


[PATCH] D59935: Disable warnings when indexing as a standalone action.

2019-03-28 Thread Haojian Wu via Phabricator via cfe-commits
hokein accepted this revision.
hokein added inline comments.
This revision is now accepted and ready to land.



Comment at: clangd/index/IndexAction.cpp:138
 CI.getLangOpts().CommentOpts.ParseAllComments = true;
+// Index the whole file even if there are warnings and -Werror is't set.
+// Avoids some analyses too. Set in two places as we're late to the party.

I think `-Werror is't set` should be `-Werror is set`?


Repository:
  rCTE Clang Tools Extra

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D59935/new/

https://reviews.llvm.org/D59935



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


[PATCH] D59873: Add additional mangling for struct members of non trivial structs

2019-03-28 Thread Shoaib Meenai via Phabricator via cfe-commits
smeenai added a comment.

Looks good. I'll commit this.


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D59873/new/

https://reviews.llvm.org/D59873



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


[PATCH] D59887: [Syntax] Introduce TokenBuffer, start clangToolingSyntax library

2019-03-28 Thread Ilya Biryukov via Phabricator via cfe-commits
ilya-biryukov updated this revision to Diff 192660.
ilya-biryukov marked an inline comment as done.
ilya-biryukov added a comment.

- Rename macro expansion to macro invocation everywhere
- Tweak comments


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D59887/new/

https://reviews.llvm.org/D59887

Files:
  clang/include/clang/Tooling/Syntax/TokenBuffer.h
  clang/lib/Tooling/CMakeLists.txt
  clang/lib/Tooling/Syntax/CMakeLists.txt
  clang/lib/Tooling/Syntax/TokenBuffer.cpp
  clang/unittests/Tooling/CMakeLists.txt
  clang/unittests/Tooling/Syntax/CMakeLists.txt
  clang/unittests/Tooling/Syntax/TokenBufferTest.cpp

Index: clang/unittests/Tooling/Syntax/TokenBufferTest.cpp
===
--- /dev/null
+++ clang/unittests/Tooling/Syntax/TokenBufferTest.cpp
@@ -0,0 +1,470 @@
+//===- TokenBufferTest.cpp ===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+
+#include "clang/Tooling/Syntax/TokenBuffer.h"
+#include "clang/AST/ASTConsumer.h"
+#include "clang/AST/Expr.h"
+#include "clang/Basic/Diagnostic.h"
+#include "clang/Basic/DiagnosticIDs.h"
+#include "clang/Basic/DiagnosticOptions.h"
+#include "clang/Basic/FileManager.h"
+#include "clang/Basic/FileSystemOptions.h"
+#include "clang/Basic/LLVM.h"
+#include "clang/Basic/LangOptions.h"
+#include "clang/Basic/SourceLocation.h"
+#include "clang/Basic/SourceManager.h"
+#include "clang/Basic/TokenKinds.def"
+#include "clang/Basic/TokenKinds.h"
+#include "clang/Frontend/CompilerInstance.h"
+#include "clang/Frontend/FrontendAction.h"
+#include "clang/Frontend/Utils.h"
+#include "clang/Lex/Lexer.h"
+#include "clang/Lex/PreprocessorOptions.h"
+#include "clang/Lex/Token.h"
+#include "clang/Tooling/Tooling.h"
+#include "llvm/ADT/ArrayRef.h"
+#include "llvm/ADT/IntrusiveRefCntPtr.h"
+#include "llvm/ADT/STLExtras.h"
+#include "llvm/ADT/StringRef.h"
+#include "llvm/Support/FormatVariadic.h"
+#include "llvm/Support/MemoryBuffer.h"
+#include "llvm/Support/VirtualFileSystem.h"
+#include "llvm/Support/raw_os_ostream.h"
+#include "llvm/Support/raw_ostream.h"
+#include "llvm/Testing/Support/Annotations.h"
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+
+using namespace clang;
+using namespace clang::syntax;
+
+using ::testing::AllOf;
+using ::testing::Contains;
+using ::testing::ElementsAre;
+using ::testing::IsEmpty;
+using ::testing::Matcher;
+using ::testing::Pointwise;
+
+// Debug printers.
+// FIXME: This should live somewhere else or be implemented as 'operator
+// <<(raw_ostream&, T)'.
+namespace clang {
+namespace tok {
+inline void PrintTo(TokenKind K, std::ostream *OS) {
+  *OS << tok::getTokenName(K);
+}
+} // namespace tok
+namespace syntax {
+inline void PrintTo(const syntax::Token &T, std::ostream *OS) {
+  PrintTo(T.kind(), OS);
+  OS->flush();
+}
+} // namespace syntax
+} // namespace clang
+
+namespace {
+// Matchers for clang::Token.
+MATCHER_P(Kind, K, "") { return arg.kind() == K; }
+MATCHER_P2(HasText, Text, SourceMgr, "") {
+  return arg.text(*SourceMgr) == Text;
+}
+MATCHER_P2(IsIdent, Text, SourceMgr, "") {
+  return arg.kind() == tok::identifier && arg.text(*SourceMgr) == Text;
+}
+/// Checks the start and end location of a token are equal to SourceRng.
+MATCHER_P(RangeIs, SourceRng, "") {
+  return arg.location() == SourceRng.first &&
+ arg.endLocation() == SourceRng.second;
+}
+/// Checks the passed tuple has two similar tokens, i.e. both are of the same
+/// kind and have the same text if they are identifiers.
+MATCHER_P(IsSameToken, SourceMgr, "") {
+  auto &L = std::get<0>(arg);
+  auto &R = std::get<1>(arg);
+  if (L.kind() != R.kind())
+return false;
+  return L.text(*SourceMgr) == L.text(*SourceMgr);
+}
+
+class TokenBufferTest : public ::testing::Test {
+public:
+  /// Run the clang frontend, collect the preprocessed tokens from the frontend
+  /// invocation and store them in this->Tokens.
+  /// This also clears SourceManager before running the compiler.
+  void recordTokens(llvm::StringRef Code) {
+class RecordTokens : public ASTFrontendAction {
+public:
+  explicit RecordTokens(TokenBuffer &Result) : Result(Result) {}
+
+  bool BeginSourceFileAction(CompilerInstance &CI) override {
+assert(!Collector && "expected only a single call to BeginSourceFile");
+Collector.emplace(CI.getPreprocessor());
+return true;
+  }
+  void EndSourceFileAction() override {
+assert(Collector && "BeginSourceFileAction was never called");
+Result = std::move(*Collector).consume();
+  }
+
+  std::unique_ptr
+  CreateASTConsumer(CompilerInstance &CI, StringRef InFile) override {

[PATCH] D59899: gn build: Add some build files for clangd

2019-03-28 Thread Nico Weber via Phabricator via cfe-commits
thakis marked 2 inline comments as done.
thakis added a comment.

Thanks! Landing with comments addressed.


CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D59899/new/

https://reviews.llvm.org/D59899



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


[PATCH] D59887: [Syntax] Introduce TokenBuffer, start clangToolingSyntax library

2019-03-28 Thread Ilya Biryukov via Phabricator via cfe-commits
ilya-biryukov updated this revision to Diff 192661.
ilya-biryukov added a comment.

- s/macroMacroInvocation/something else...


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D59887/new/

https://reviews.llvm.org/D59887

Files:
  clang/include/clang/Tooling/Syntax/TokenBuffer.h
  clang/lib/Tooling/CMakeLists.txt
  clang/lib/Tooling/Syntax/CMakeLists.txt
  clang/lib/Tooling/Syntax/TokenBuffer.cpp
  clang/unittests/Tooling/CMakeLists.txt
  clang/unittests/Tooling/Syntax/CMakeLists.txt
  clang/unittests/Tooling/Syntax/TokenBufferTest.cpp

Index: clang/unittests/Tooling/Syntax/TokenBufferTest.cpp
===
--- /dev/null
+++ clang/unittests/Tooling/Syntax/TokenBufferTest.cpp
@@ -0,0 +1,470 @@
+//===- TokenBufferTest.cpp ===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+
+#include "clang/Tooling/Syntax/TokenBuffer.h"
+#include "clang/AST/ASTConsumer.h"
+#include "clang/AST/Expr.h"
+#include "clang/Basic/Diagnostic.h"
+#include "clang/Basic/DiagnosticIDs.h"
+#include "clang/Basic/DiagnosticOptions.h"
+#include "clang/Basic/FileManager.h"
+#include "clang/Basic/FileSystemOptions.h"
+#include "clang/Basic/LLVM.h"
+#include "clang/Basic/LangOptions.h"
+#include "clang/Basic/SourceLocation.h"
+#include "clang/Basic/SourceManager.h"
+#include "clang/Basic/TokenKinds.def"
+#include "clang/Basic/TokenKinds.h"
+#include "clang/Frontend/CompilerInstance.h"
+#include "clang/Frontend/FrontendAction.h"
+#include "clang/Frontend/Utils.h"
+#include "clang/Lex/Lexer.h"
+#include "clang/Lex/PreprocessorOptions.h"
+#include "clang/Lex/Token.h"
+#include "clang/Tooling/Tooling.h"
+#include "llvm/ADT/ArrayRef.h"
+#include "llvm/ADT/IntrusiveRefCntPtr.h"
+#include "llvm/ADT/STLExtras.h"
+#include "llvm/ADT/StringRef.h"
+#include "llvm/Support/FormatVariadic.h"
+#include "llvm/Support/MemoryBuffer.h"
+#include "llvm/Support/VirtualFileSystem.h"
+#include "llvm/Support/raw_os_ostream.h"
+#include "llvm/Support/raw_ostream.h"
+#include "llvm/Testing/Support/Annotations.h"
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+
+using namespace clang;
+using namespace clang::syntax;
+
+using ::testing::AllOf;
+using ::testing::Contains;
+using ::testing::ElementsAre;
+using ::testing::IsEmpty;
+using ::testing::Matcher;
+using ::testing::Pointwise;
+
+// Debug printers.
+// FIXME: This should live somewhere else or be implemented as 'operator
+// <<(raw_ostream&, T)'.
+namespace clang {
+namespace tok {
+inline void PrintTo(TokenKind K, std::ostream *OS) {
+  *OS << tok::getTokenName(K);
+}
+} // namespace tok
+namespace syntax {
+inline void PrintTo(const syntax::Token &T, std::ostream *OS) {
+  PrintTo(T.kind(), OS);
+  OS->flush();
+}
+} // namespace syntax
+} // namespace clang
+
+namespace {
+// Matchers for clang::Token.
+MATCHER_P(Kind, K, "") { return arg.kind() == K; }
+MATCHER_P2(HasText, Text, SourceMgr, "") {
+  return arg.text(*SourceMgr) == Text;
+}
+MATCHER_P2(IsIdent, Text, SourceMgr, "") {
+  return arg.kind() == tok::identifier && arg.text(*SourceMgr) == Text;
+}
+/// Checks the start and end location of a token are equal to SourceRng.
+MATCHER_P(RangeIs, SourceRng, "") {
+  return arg.location() == SourceRng.first &&
+ arg.endLocation() == SourceRng.second;
+}
+/// Checks the passed tuple has two similar tokens, i.e. both are of the same
+/// kind and have the same text if they are identifiers.
+MATCHER_P(IsSameToken, SourceMgr, "") {
+  auto &L = std::get<0>(arg);
+  auto &R = std::get<1>(arg);
+  if (L.kind() != R.kind())
+return false;
+  return L.text(*SourceMgr) == L.text(*SourceMgr);
+}
+
+class TokenBufferTest : public ::testing::Test {
+public:
+  /// Run the clang frontend, collect the preprocessed tokens from the frontend
+  /// invocation and store them in this->Tokens.
+  /// This also clears SourceManager before running the compiler.
+  void recordTokens(llvm::StringRef Code) {
+class RecordTokens : public ASTFrontendAction {
+public:
+  explicit RecordTokens(TokenBuffer &Result) : Result(Result) {}
+
+  bool BeginSourceFileAction(CompilerInstance &CI) override {
+assert(!Collector && "expected only a single call to BeginSourceFile");
+Collector.emplace(CI.getPreprocessor());
+return true;
+  }
+  void EndSourceFileAction() override {
+assert(Collector && "BeginSourceFileAction was never called");
+Result = std::move(*Collector).consume();
+  }
+
+  std::unique_ptr
+  CreateASTConsumer(CompilerInstance &CI, StringRef InFile) override {
+return llvm::make_unique();
+  }
+
+private:
+  TokenBuf

[clang-tools-extra] r357182 - gn build: Add some build files for clangd

2019-03-28 Thread Nico Weber via cfe-commits
Author: nico
Date: Thu Mar 28 09:53:32 2019
New Revision: 357182

URL: http://llvm.org/viewvc/llvm-project?rev=357182&view=rev
Log:
gn build: Add some build files for clangd

Enough to build the clangd binaries, but this is still missing build
files for:
- fuzzer
- indexer
- index/dex/dexp
- benchmarks
- xpc

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

Modified:
clang-tools-extra/trunk/clangd/refactor/tweaks/CMakeLists.txt

Modified: clang-tools-extra/trunk/clangd/refactor/tweaks/CMakeLists.txt
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clangd/refactor/tweaks/CMakeLists.txt?rev=357182&r1=357181&r2=357182&view=diff
==
--- clang-tools-extra/trunk/clangd/refactor/tweaks/CMakeLists.txt (original)
+++ clang-tools-extra/trunk/clangd/refactor/tweaks/CMakeLists.txt Thu Mar 28 
09:53:32 2019
@@ -6,9 +6,9 @@ set(LLVM_LINK_COMPONENTS
 
 # A target containing all code tweaks (i.e. mini-refactorings) provided by
 # clangd.
-# Built as an object library to make sure linker does not remove global
+# Built as an object library to make sure the linker does not remove global
 # constructors that register individual tweaks in a global registry.
-# To enable these tweaks in exectubales or shared libraries, add
+# To enable these tweaks in executables or shared libraries, add
 # $ to a list of sources, see
 # clangd/tool/CMakeLists.txt for an example.
 add_clang_library(clangDaemonTweaks OBJECT


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


[PATCH] D59899: gn build: Add some build files for clangd

2019-03-28 Thread Phabricator via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rL357182: gn build: Add some build files for clangd (authored 
by nico, committed by ).

Changed prior to commit:
  https://reviews.llvm.org/D59899?vs=192509&id=192663#toc

Repository:
  rL LLVM

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D59899/new/

https://reviews.llvm.org/D59899

Files:
  clang-tools-extra/trunk/clangd/refactor/tweaks/CMakeLists.txt
  llvm/trunk/utils/gn/build/libs/atomic/BUILD.gn
  llvm/trunk/utils/gn/secondary/BUILD.gn
  
llvm/trunk/utils/gn/secondary/clang-tools-extra/clang-apply-replacements/BUILD.gn
  llvm/trunk/utils/gn/secondary/clang-tools-extra/clangd/BUILD.gn
  
llvm/trunk/utils/gn/secondary/clang-tools-extra/clangd/refactor/tweaks/BUILD.gn
  llvm/trunk/utils/gn/secondary/clang-tools-extra/clangd/tool/BUILD.gn

Index: llvm/trunk/utils/gn/secondary/clang-tools-extra/clangd/BUILD.gn
===
--- llvm/trunk/utils/gn/secondary/clang-tools-extra/clangd/BUILD.gn
+++ llvm/trunk/utils/gn/secondary/clang-tools-extra/clangd/BUILD.gn
@@ -0,0 +1,96 @@
+static_library("clangd") {
+  output_name = "clangDaemon"
+  configs += [ "//llvm/utils/gn/build:clang_code" ]
+  deps = [
+"//clang-tools-extra/clang-tidy/abseil",
+"//clang-tools-extra/clang-tidy/android",
+"//clang-tools-extra/clang-tidy/boost",
+"//clang-tools-extra/clang-tidy/bugprone",
+"//clang-tools-extra/clang-tidy/cert",
+"//clang-tools-extra/clang-tidy/cppcoreguidelines",
+"//clang-tools-extra/clang-tidy/fuchsia",
+"//clang-tools-extra/clang-tidy/google",
+"//clang-tools-extra/clang-tidy/hicpp",
+"//clang-tools-extra/clang-tidy/llvm",
+"//clang-tools-extra/clang-tidy/misc",
+"//clang-tools-extra/clang-tidy/modernize",
+"//clang-tools-extra/clang-tidy/objc",
+"//clang-tools-extra/clang-tidy/performance",
+"//clang-tools-extra/clang-tidy/portability",
+"//clang-tools-extra/clang-tidy/readability",
+"//clang-tools-extra/clang-tidy/zircon",
+"//clang/lib/AST",
+"//clang/lib/ASTMatchers",
+"//clang/lib/Basic",
+"//clang/lib/Driver",
+"//clang/lib/Format",
+"//clang/lib/Frontend",
+"//clang/lib/Index",
+"//clang/lib/Lex",
+"//clang/lib/Sema",
+"//clang/lib/Serialization",
+"//clang/lib/Tooling",
+"//clang/lib/Tooling/Core",
+"//clang/lib/Tooling/Inclusions",
+"//clang/lib/Tooling/Refactoring",
+"//llvm/lib/Support",
+"//llvm/utils/gn/build/libs/atomic",
+"//llvm/utils/gn/build/libs/pthread",
+  ]
+  include_dirs = [ "." ]
+  sources = [
+"AST.cpp",
+"Cancellation.cpp",
+"ClangdLSPServer.cpp",
+"ClangdServer.cpp",
+"ClangdUnit.cpp",
+"CodeComplete.cpp",
+"CodeCompletionStrings.cpp",
+"Compiler.cpp",
+"Context.cpp",
+"Diagnostics.cpp",
+"DraftStore.cpp",
+"ExpectedTypes.cpp",
+"FS.cpp",
+"FSProvider.cpp",
+"FileDistance.cpp",
+"FindSymbols.cpp",
+"FuzzyMatch.cpp",
+"GlobalCompilationDatabase.cpp",
+"Headers.cpp",
+"IncludeFixer.cpp",
+"JSONTransport.cpp",
+"Logger.cpp",
+"Protocol.cpp",
+"Quality.cpp",
+"RIFF.cpp",
+"Selection.cpp",
+"SourceCode.cpp",
+"TUScheduler.cpp",
+"Threading.cpp",
+"Trace.cpp",
+"URI.cpp",
+"XRefs.cpp",
+"index/Background.cpp",
+"index/BackgroundIndexStorage.cpp",
+"index/CanonicalIncludes.cpp",
+"index/FileIndex.cpp",
+"index/Index.cpp",
+"index/IndexAction.cpp",
+"index/MemIndex.cpp",
+"index/Merge.cpp",
+"index/Ref.cpp",
+"index/Serialization.cpp",
+"index/Symbol.cpp",
+"index/SymbolCollector.cpp",
+"index/SymbolID.cpp",
+"index/SymbolLocation.cpp",
+"index/SymbolOrigin.cpp",
+"index/YAMLSerialization.cpp",
+"index/dex/Dex.cpp",
+"index/dex/Iterator.cpp",
+"index/dex/PostingList.cpp",
+"index/dex/Trigram.cpp",
+"refactor/Tweak.cpp",
+  ]
+}
Index: llvm/trunk/utils/gn/secondary/clang-tools-extra/clangd/tool/BUILD.gn
===
--- llvm/trunk/utils/gn/secondary/clang-tools-extra/clangd/tool/BUILD.gn
+++ llvm/trunk/utils/gn/secondary/clang-tools-extra/clangd/tool/BUILD.gn
@@ -0,0 +1,50 @@
+import("//llvm/utils/gn/build/write_cmake_config.gni")
+
+declare_args() {
+  # Whether to build clangd's XPC components.
+  clangd_build_xpc = false
+}
+
+write_cmake_config("features") {
+  # FIXME: Try moving Features.inc.in to tools, seems like a better location.
+  input = "../Features.inc.in"
+  output = "$target_gen_dir/Features.inc"
+  values = []
+  if (clangd_build_xpc) {
+values += [ "CLANGD_BUILD_XPC=1" ]
+  } else {
+values += [ "CLANGD_BUILD_XPC=0" ]
+  }
+}
+
+executable("clangd") {
+  configs += [ "//llvm/utils/gn/build:clang_code" ]
+  deps = [
+":features",
+"//clang-tools-extra/clang-tidy",
+"//clang-tools-extra/clangd",
+"//clang

[PATCH] D59814: [Testing] Move clangd::Annotations to llvm testing support

2019-03-28 Thread Dmitri Gribenko via Phabricator via cfe-commits
gribozavr accepted this revision.
gribozavr added inline comments.
This revision is now accepted and ready to land.



Comment at: llvm/include/llvm/Testing/Support/Annotations.h:9
 //
 // Annotations lets you mark points and ranges inside source code, for tests:
 //

Move into a doc comment on the class Annonations?



Comment at: llvm/include/llvm/Testing/Support/Annotations.h:49
 public:
   // Parses the annotations from Text. Crashes if it's malformed.
   Annotations(llvm::StringRef Text);

Three slashes for doc comments.


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D59814/new/

https://reviews.llvm.org/D59814



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


[PATCH] D59725: Additions to creduce script

2019-03-28 Thread Amy Huang via Phabricator via cfe-commits
akhuang added inline comments.



Comment at: clang/utils/creduce-clang-crash.py:212
+
+cmd = self.get_crash_cmd() + ['-E', '-P']
+try:

arichardson wrote:
> Some crash messages might include the line numbers, do you think it makes 
> sense to fall back to running with -E but without -P and also checking that? 
> I do it in my script but I'm not sure preprocessing saves that much time 
> since creduce will try to remove those statements early.
Makes sense-- in my experience preprocessing is still quite a bit faster than 
letting creduce remove all the statements.


CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D59725/new/

https://reviews.llvm.org/D59725



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


r357184 - [CodeGen] Add additional mangling for struct members of non trivial structs

2019-03-28 Thread Shoaib Meenai via cfe-commits
Author: smeenai
Date: Thu Mar 28 10:01:20 2019
New Revision: 357184

URL: http://llvm.org/viewvc/llvm-project?rev=357184&view=rev
Log:
[CodeGen] Add additional mangling for struct members of non trivial structs

In https://bugs.llvm.org/show_bug.cgi?id=41206 we observe bad codegen
when embedding a non-trivial C struct within a C struct. This is due to
the fact that name mangling for non-trivial structs marks the two
structs as identical. This diff contains a fix for this issue.

Patch by Dan Zimmerman .

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

Added:
cfe/trunk/test/CodeGenObjC/nontrivial-c-struct-within-struct-name.m
Modified:
cfe/trunk/lib/CodeGen/CGNonTrivialStruct.cpp
cfe/trunk/test/CodeGenObjC/strong-in-c-struct.m

Modified: cfe/trunk/lib/CodeGen/CGNonTrivialStruct.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/CodeGen/CGNonTrivialStruct.cpp?rev=357184&r1=357183&r2=357184&view=diff
==
--- cfe/trunk/lib/CodeGen/CGNonTrivialStruct.cpp (original)
+++ cfe/trunk/lib/CodeGen/CGNonTrivialStruct.cpp Thu Mar 28 10:01:20 2019
@@ -139,8 +139,8 @@ struct CopyStructVisitor : StructVisitor
 //  ::=  ["_" ]
 //  ::= +
 //  ::=  | 
-//  ::=  |  
|
-//   
+//  ::= "_S"  |
+//| 
 //  ::= "_AB"  "s"  "n"
 //  "_AE"
 //  ::= 
@@ -175,6 +175,7 @@ template  struct GenFuncN
   void visitStruct(QualType QT, const FieldDecl *FD,
CharUnits CurStructOffset) {
 CharUnits FieldOffset = CurStructOffset + asDerived().getFieldOffset(FD);
+appendStr("_S");
 asDerived().visitStructFields(QT, FieldOffset);
   }
 

Added: cfe/trunk/test/CodeGenObjC/nontrivial-c-struct-within-struct-name.m
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/CodeGenObjC/nontrivial-c-struct-within-struct-name.m?rev=357184&view=auto
==
--- cfe/trunk/test/CodeGenObjC/nontrivial-c-struct-within-struct-name.m (added)
+++ cfe/trunk/test/CodeGenObjC/nontrivial-c-struct-within-struct-name.m Thu Mar 
28 10:01:20 2019
@@ -0,0 +1,44 @@
+// RUN: %clang_cc1 -triple arm64-apple-ios11 -fobjc-arc -emit-llvm -o - %s | 
FileCheck %s
+
+@class I;
+
+typedef struct {
+  I *name;
+} Foo;
+
+typedef struct {
+  Foo foo;
+} Bar;
+
+typedef struct {
+  Bar bar;
+} Baz;
+
+I *getI();
+
+void f() {
+  Foo foo = {getI()};
+  Bar bar = {foo};
+  Baz baz = {bar};
+}
+
+// CHECK: define linkonce_odr hidden void @__destructor_8_S_S_s0(i8** 
%[[DST:.*]])
+// CHECK: %[[DST_ADDR:.*]] = alloca i8**, align 8
+// CHECK: store i8** %[[DST]], i8*** %[[DST_ADDR]], align 8
+// CHECK: %[[V0:.*]] = load i8**, i8*** %[[DST_ADDR]], align 8
+// CHECK: call void @__destructor_8_S_s0(i8** %[[V0]])
+// CHECK: ret void
+
+// CHECK: define linkonce_odr hidden void @__destructor_8_S_s0(i8** 
%[[DST:.*]])
+// CHECK: %[[DST_ADDR:.*]] = alloca i8**, align 8
+// CHECK: store i8** %[[DST]], i8*** %[[DST_ADDR]], align 8
+// CHECK: %[[V0:.*]] = load i8**, i8*** %[[DST_ADDR]], align 8
+// CHECK: call void @__destructor_8_s0(i8** %[[V0]])
+// CHECK: ret void
+
+// CHECK: define linkonce_odr hidden void @__destructor_8_s0(i8** %dst)
+// CHECK: %[[DST_ADDR:.*]] = alloca i8**, align 8
+// CHECK: store i8** %[[DST]], i8*** %[[DST_ADDR]], align 8
+// CHECK: %[[V0:.*]] = load i8**, i8*** %[[DST_ADDR]], align 8
+// CHECK: call void @llvm.objc.storeStrong(i8** %[[V0]], i8* null)
+// CHECK: ret void

Modified: cfe/trunk/test/CodeGenObjC/strong-in-c-struct.m
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/CodeGenObjC/strong-in-c-struct.m?rev=357184&r1=357183&r2=357184&view=diff
==
--- cfe/trunk/test/CodeGenObjC/strong-in-c-struct.m (original)
+++ cfe/trunk/test/CodeGenObjC/strong-in-c-struct.m Thu Mar 28 10:01:20 2019
@@ -89,12 +89,12 @@ void func(Strong *);
 // CHECK: define void @test_constructor_destructor_StrongOuter()
 // CHECK: %[[T:.*]] = alloca %[[STRUCT_STRONGOUTER:.*]], align 8
 // CHECK: %[[V0:.*]] = bitcast %[[STRUCT_STRONGOUTER]]* %[[T]] to i8**
-// CHECK: call void @__default_constructor_8_s16_s24(i8** %[[V0]])
+// CHECK: call void @__default_constructor_8_S_s16_s24(i8** %[[V0]])
 // CHECK: %[[V1:.*]] = bitcast %[[STRUCT_STRONGOUTER]]* %[[T]] to i8**
-// CHECK: call void @__destructor_8_s16_s24(i8** %[[V1]])
+// CHECK: call void @__destructor_8_S_s16_s24(i8** %[[V1]])
 // CHECK: ret void
 
-// CHECK: define linkonce_odr hidden void 
@__default_constructor_8_s16_s24(i8** %[[DST:.*]])
+// CHECK: define linkonce_odr hidden void 
@__default_constructor_8_S_s16_s24(i8** %[[DST:.*]])
 // CHECK: %[[DST_ADDR:.*]] = alloca i8**, align 8
 // CHECK: store i8** %[[DST]], i8*** %[[DST_ADDR]], align 8
 // CHECK: %[[V0:.*]] = load i8**, i8*** %[[DST_ADDR]], align 8
@@ -117,7 +117,7 @@ void func(Strong *);
 // CHECK: call void @

[PATCH] D59725: Additions to creduce script

2019-03-28 Thread Amy Huang via Phabricator via cfe-commits
akhuang updated this revision to Diff 192669.
akhuang marked 3 inline comments as done.
akhuang added a comment.

Add preprocessing with clang -E only;
use `with` for opening files


CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D59725/new/

https://reviews.llvm.org/D59725

Files:
  clang/utils/creduce-clang-crash.py

Index: clang/utils/creduce-clang-crash.py
===
--- clang/utils/creduce-clang-crash.py
+++ clang/utils/creduce-clang-crash.py
@@ -1,8 +1,14 @@
 #!/usr/bin/env python
 """Calls C-Reduce to create a minimal reproducer for clang crashes.
+
+Output files:
+  *.reduced.sh -- crash reproducer with minimal arguments
+  *.reduced.cpp -- the reduced file
+  *.test.sh -- interestingness test for C-Reduce
 """
 
-from argparse import ArgumentParser
+from __future__ import print_function
+from argparse import ArgumentParser, RawTextHelpFormatter
 import os
 import re
 import stat
@@ -15,10 +21,14 @@
 from distutils.spawn import find_executable
 
 verbose = False
-llvm_bin = None
 creduce_cmd = None
+clang_cmd = None
 not_cmd = None
 
+def verbose_print(*args, **kwargs):
+  if verbose:
+print(*args, **kwargs)
+
 def check_file(fname):
   if not os.path.isfile(fname):
 sys.exit("ERROR: %s does not exist" % (fname))
@@ -33,166 +43,340 @@
 cmd = find_executable(cmd_path)
 if cmd:
   return cmd
-sys.exit("ERROR: executable %s not found" % (cmd_path))
+sys.exit("ERROR: executable `%s` not found" % (cmd_path))
 
   cmd = find_executable(cmd_name, path=cmd_dir)
   if cmd:
 return cmd
-  sys.exit("ERROR: %s not found in %s" % (cmd_name, cmd_dir))
 
-def quote_cmd(cmd):
-  return ' '.join(arg if arg.startswith('$') else pipes.quote(arg)
-  for arg in cmd)
-
-def get_crash_cmd(crash_script):
-  with open(crash_script) as f:
-# Assume clang call is on the last line of the script
-line = f.readlines()[-1]
-cmd = shlex.split(line)
-
-# Overwrite the script's clang with the user's clang path
-new_clang = check_cmd('clang', llvm_bin)
-cmd[0] = pipes.quote(new_clang)
-return cmd
+  if not cmd_dir:
+cmd_dir = "$PATH"
+  sys.exit("ERROR: `%s` not found in %s" % (cmd_name, cmd_dir))
 
-def has_expected_output(crash_cmd, expected_output):
-  p = subprocess.Popen(crash_cmd,
-   stdout=subprocess.PIPE,
-   stderr=subprocess.STDOUT)
-  crash_output, _ = p.communicate()
-  return all(msg in crash_output for msg in expected_output)
-
-def get_expected_output(crash_cmd):
-  p = subprocess.Popen(crash_cmd,
-   stdout=subprocess.PIPE,
-   stderr=subprocess.STDOUT)
-  crash_output, _ = p.communicate()
-
-  # If there is an assertion failure, use that;
-  # otherwise use the last five stack trace functions
-  assertion_re = r'Assertion `([^\']+)\' failed'
-  assertion_match = re.search(assertion_re, crash_output)
-  if assertion_match:
-return [assertion_match.group(1)]
-  else:
-stacktrace_re = r'#[0-9]+\s+0[xX][0-9a-fA-F]+\s*([^(]+)\('
-matches = re.findall(stacktrace_re, crash_output)
-return matches[-5:]
-
-def write_interestingness_test(testfile, crash_cmd, expected_output,
-   file_to_reduce):
-  filename = os.path.basename(file_to_reduce)
-  if filename not in crash_cmd:
-sys.exit("ERROR: expected %s to be in the crash command" % filename)
-
-  # Replace all instances of file_to_reduce with a command line variable
-  output = ['#!/bin/bash',
-'if [ -z "$1" ] ; then',
-'  f=%s' % (pipes.quote(filename)),
-'else',
-'  f="$1"',
-'fi']
-  cmd = ['$f' if s == filename else s for s in crash_cmd]
-
-  output.append('%s --crash %s >& t.log || exit 1' % (pipes.quote(not_cmd),
-  quote_cmd(cmd)))
-
-  for msg in expected_output:
-output.append('grep %s t.log || exit 1' % pipes.quote(msg))
-
-  with open(testfile, 'w') as f:
-f.write('\n'.join(output))
-  os.chmod(testfile, os.stat(testfile).st_mode | stat.S_IEXEC)
-
-def check_interestingness(testfile, file_to_reduce):
-  testfile = os.path.abspath(testfile)
-
-  # Check that the test considers the original file interesting
-  with open(os.devnull, 'w') as devnull:
-returncode = subprocess.call(testfile, stdout=devnull)
-  if returncode:
-sys.exit("The interestingness test does not pass for the original file.")
-
-  # Check that an empty file is not interesting
-  _, empty_file = tempfile.mkstemp()
-  with open(os.devnull, 'w') as devnull:
-returncode = subprocess.call([testfile, empty_file], stdout=devnull)
-  os.remove(empty_file)
-  if not returncode:
-sys.exit("The interestingness test passes for an empty file.")
-
-def clang_preprocess(file_to_reduce, crash_cmd, expected_output):
-  _, tmpfile = tempfile.mkstemp()
-  shutil.copy(file_to_reduce, tmpfile)
-
-  cmd = crash_cmd + [

[PATCH] D59873: Add additional mangling for struct members of non trivial structs

2019-03-28 Thread Shoaib Meenai via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rL357184: [CodeGen] Add additional mangling for struct members 
of non trivial structs (authored by smeenai, committed by ).
Herald added a project: LLVM.
Herald added a subscriber: llvm-commits.

Changed prior to commit:
  https://reviews.llvm.org/D59873?vs=192652&id=192671#toc

Repository:
  rL LLVM

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D59873/new/

https://reviews.llvm.org/D59873

Files:
  cfe/trunk/lib/CodeGen/CGNonTrivialStruct.cpp
  cfe/trunk/test/CodeGenObjC/nontrivial-c-struct-within-struct-name.m
  cfe/trunk/test/CodeGenObjC/strong-in-c-struct.m

Index: cfe/trunk/lib/CodeGen/CGNonTrivialStruct.cpp
===
--- cfe/trunk/lib/CodeGen/CGNonTrivialStruct.cpp
+++ cfe/trunk/lib/CodeGen/CGNonTrivialStruct.cpp
@@ -139,8 +139,8 @@
 //  ::=  ["_" ]
 //  ::= +
 //  ::=  | 
-//  ::=  |  |
-//   
+//  ::= "_S"  |
+//| 
 //  ::= "_AB"  "s"  "n"
 //  "_AE"
 //  ::= 
@@ -175,6 +175,7 @@
   void visitStruct(QualType QT, const FieldDecl *FD,
CharUnits CurStructOffset) {
 CharUnits FieldOffset = CurStructOffset + asDerived().getFieldOffset(FD);
+appendStr("_S");
 asDerived().visitStructFields(QT, FieldOffset);
   }
 
Index: cfe/trunk/test/CodeGenObjC/nontrivial-c-struct-within-struct-name.m
===
--- cfe/trunk/test/CodeGenObjC/nontrivial-c-struct-within-struct-name.m
+++ cfe/trunk/test/CodeGenObjC/nontrivial-c-struct-within-struct-name.m
@@ -0,0 +1,44 @@
+// RUN: %clang_cc1 -triple arm64-apple-ios11 -fobjc-arc -emit-llvm -o - %s | FileCheck %s
+
+@class I;
+
+typedef struct {
+  I *name;
+} Foo;
+
+typedef struct {
+  Foo foo;
+} Bar;
+
+typedef struct {
+  Bar bar;
+} Baz;
+
+I *getI();
+
+void f() {
+  Foo foo = {getI()};
+  Bar bar = {foo};
+  Baz baz = {bar};
+}
+
+// CHECK: define linkonce_odr hidden void @__destructor_8_S_S_s0(i8** %[[DST:.*]])
+// CHECK: %[[DST_ADDR:.*]] = alloca i8**, align 8
+// CHECK: store i8** %[[DST]], i8*** %[[DST_ADDR]], align 8
+// CHECK: %[[V0:.*]] = load i8**, i8*** %[[DST_ADDR]], align 8
+// CHECK: call void @__destructor_8_S_s0(i8** %[[V0]])
+// CHECK: ret void
+
+// CHECK: define linkonce_odr hidden void @__destructor_8_S_s0(i8** %[[DST:.*]])
+// CHECK: %[[DST_ADDR:.*]] = alloca i8**, align 8
+// CHECK: store i8** %[[DST]], i8*** %[[DST_ADDR]], align 8
+// CHECK: %[[V0:.*]] = load i8**, i8*** %[[DST_ADDR]], align 8
+// CHECK: call void @__destructor_8_s0(i8** %[[V0]])
+// CHECK: ret void
+
+// CHECK: define linkonce_odr hidden void @__destructor_8_s0(i8** %dst)
+// CHECK: %[[DST_ADDR:.*]] = alloca i8**, align 8
+// CHECK: store i8** %[[DST]], i8*** %[[DST_ADDR]], align 8
+// CHECK: %[[V0:.*]] = load i8**, i8*** %[[DST_ADDR]], align 8
+// CHECK: call void @llvm.objc.storeStrong(i8** %[[V0]], i8* null)
+// CHECK: ret void
Index: cfe/trunk/test/CodeGenObjC/strong-in-c-struct.m
===
--- cfe/trunk/test/CodeGenObjC/strong-in-c-struct.m
+++ cfe/trunk/test/CodeGenObjC/strong-in-c-struct.m
@@ -89,12 +89,12 @@
 // CHECK: define void @test_constructor_destructor_StrongOuter()
 // CHECK: %[[T:.*]] = alloca %[[STRUCT_STRONGOUTER:.*]], align 8
 // CHECK: %[[V0:.*]] = bitcast %[[STRUCT_STRONGOUTER]]* %[[T]] to i8**
-// CHECK: call void @__default_constructor_8_s16_s24(i8** %[[V0]])
+// CHECK: call void @__default_constructor_8_S_s16_s24(i8** %[[V0]])
 // CHECK: %[[V1:.*]] = bitcast %[[STRUCT_STRONGOUTER]]* %[[T]] to i8**
-// CHECK: call void @__destructor_8_s16_s24(i8** %[[V1]])
+// CHECK: call void @__destructor_8_S_s16_s24(i8** %[[V1]])
 // CHECK: ret void
 
-// CHECK: define linkonce_odr hidden void @__default_constructor_8_s16_s24(i8** %[[DST:.*]])
+// CHECK: define linkonce_odr hidden void @__default_constructor_8_S_s16_s24(i8** %[[DST:.*]])
 // CHECK: %[[DST_ADDR:.*]] = alloca i8**, align 8
 // CHECK: store i8** %[[DST]], i8*** %[[DST_ADDR]], align 8
 // CHECK: %[[V0:.*]] = load i8**, i8*** %[[DST_ADDR]], align 8
@@ -117,7 +117,7 @@
 // CHECK: call void @llvm.memset.p0i8.i64(i8* align 8 %[[V4]], i8 0, i64 8, i1 false)
 // CHECK: ret void
 
-// CHECK: define linkonce_odr hidden void @__destructor_8_s16_s24(i8** %[[DST:.*]])
+// CHECK: define linkonce_odr hidden void @__destructor_8_S_s16_s24(i8** %[[DST:.*]])
 // CHECK: %[[DST_ADDR:.*]] = alloca i8**, align 8
 // CHECK: store i8** %[[DST]], i8*** %[[DST_ADDR]], align 8
 // CHECK: %[[V0:.*]] = load i8**, i8*** %[[DST_ADDR]], align 8
@@ -149,12 +149,12 @@
 // CHECK: %[[V0:.*]] = load %[[STRUCT_STRONGOUTER]]*, %[[STRUCT_STRONGOUTER]]** %[[S_ADDR]], align 8
 // CHECK: %[[V1:.*]] = bitcast %[[STRUCT_STRONGOUTER]]* %[[T]] to i8**
 // CHECK: %[[V2:.*]] = bitcast %[[STRUCT_STRONGOUTER]]* %[[V0]] to i8**
-// CHECK: call void @__copy_constru

[clang-tools-extra] r357186 - Disable warnings when indexing as a standalone action.

2019-03-28 Thread Sam McCall via cfe-commits
Author: sammccall
Date: Thu Mar 28 10:07:28 2019
New Revision: 357186

URL: http://llvm.org/viewvc/llvm-project?rev=357186&view=rev
Log:
Disable warnings when indexing as a standalone action.

Summary:
- we don't record the warnings at all
- we don't want to stop indexing if we hit error-limit due to warnings
- this allows some analyses to be skipped which can save some CPU

https://github.com/clangd/clangd/issues/24

Reviewers: hokein

Subscribers: ilya-biryukov, ioeric, jkorous, arphaman, kadircet, cfe-commits

Tags: #clang

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

Modified:
clang-tools-extra/trunk/clangd/index/IndexAction.cpp
clang-tools-extra/trunk/unittests/clangd/IndexActionTests.cpp

Modified: clang-tools-extra/trunk/clangd/index/IndexAction.cpp
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clangd/index/IndexAction.cpp?rev=357186&r1=357185&r2=357186&view=diff
==
--- clang-tools-extra/trunk/clangd/index/IndexAction.cpp (original)
+++ clang-tools-extra/trunk/clangd/index/IndexAction.cpp Thu Mar 28 10:07:28 
2019
@@ -135,6 +135,11 @@ public:
   bool BeginInvocation(CompilerInstance &CI) override {
 // We want all comments, not just the doxygen ones.
 CI.getLangOpts().CommentOpts.ParseAllComments = true;
+// Index the whole file even if there are warnings and -Werror is set.
+// Avoids some analyses too. Set in two places as we're late to the party.
+CI.getDiagnosticOpts().IgnoreWarnings = true;
+CI.getDiagnostics().setIgnoreAllWarnings(true);
+
 return WrapperFrontendAction::BeginInvocation(CI);
   }
 

Modified: clang-tools-extra/trunk/unittests/clangd/IndexActionTests.cpp
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/unittests/clangd/IndexActionTests.cpp?rev=357186&r1=357185&r2=357186&view=diff
==
--- clang-tools-extra/trunk/unittests/clangd/IndexActionTests.cpp (original)
+++ clang-tools-extra/trunk/unittests/clangd/IndexActionTests.cpp Thu Mar 28 
10:07:28 2019
@@ -29,6 +29,8 @@ MATCHER(IsTU, "") { return arg.IsTU; }
 
 MATCHER_P(HasDigest, Digest, "") { return arg.Digest == Digest; }
 
+MATCHER_P(HasName, Name, "") { return arg.Name == Name; }
+
 MATCHER(HasSameURI, "") {
   llvm::StringRef URI = testing::get<0>(arg);
   const std::string &Path = testing::get<1>(arg);
@@ -43,6 +45,7 @@ IncludesAre(const std::vector &Paths) {
+  ASSERT_TRUE(IndexFile.Sources);
   EXPECT_THAT(Paths.size(), IndexFile.Sources->size());
   for (llvm::StringRef Path : Paths) {
 auto URI = toUri(Path);
@@ -224,6 +227,27 @@ TEST_F(IndexActionTest, IncludeGraphDyna
 HasDigest(digest(HeaderCode));
 }
 
+TEST_F(IndexActionTest, NoWarnings) {
+  std::string MainFilePath = testPath("main.cpp");
+  std::string MainCode = R"cpp(
+  void foo(int x) {
+if (x = 1) // -Wparentheses
+  return;
+if (x = 1) // -Wparentheses
+  return;
+  }
+  void bar() {}
+  )cpp";
+  addFile(MainFilePath, MainCode);
+  // We set -ferror-limit so the warning-promoted-to-error would be fatal.
+  // This would cause indexing to stop (if warnings weren't disabled).
+  IndexFileIn IndexFile = runIndexingAction(
+  MainFilePath, {"-ferror-limit=1", "-Wparentheses", "-Werror"});
+  ASSERT_TRUE(IndexFile.Sources);
+  ASSERT_NE(0u, IndexFile.Sources->size());
+  EXPECT_THAT(*IndexFile.Symbols, ElementsAre(HasName("foo"), HasName("bar")));
+}
+
 } // namespace
 } // namespace clangd
 } // namespace clang


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


[PATCH] D54881: [clang-format] Prevent Clang-Format from editing leading whitespace on lines outside of the format range

2019-03-28 Thread Manuel Klimek via Phabricator via cfe-commits
klimek added a comment.

I just verified why this doesn't break for our CI:
The trick is that if the indent is actually off (as opposed to being correct, 
but tab vs spaces), we do re-indent until we find an indent that's correct.
The fix that would make me happier, I think, is to do the same thing here:
Basically, when we expand the range until nothing changes, do not only check 
whether the indent is correct, but also whether we'd change the spaces in the 
indent.
WDYT?


CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D54881/new/

https://reviews.llvm.org/D54881



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


[PATCH] D59935: Disable warnings when indexing as a standalone action.

2019-03-28 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 rL357186: Disable warnings when indexing as a standalone 
action. (authored by sammccall, committed by ).
Herald added a project: LLVM.
Herald added a subscriber: llvm-commits.

Changed prior to commit:
  https://reviews.llvm.org/D59935?vs=192651&id=192672#toc

Repository:
  rL LLVM

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D59935/new/

https://reviews.llvm.org/D59935

Files:
  clang-tools-extra/trunk/clangd/index/IndexAction.cpp
  clang-tools-extra/trunk/unittests/clangd/IndexActionTests.cpp


Index: clang-tools-extra/trunk/unittests/clangd/IndexActionTests.cpp
===
--- clang-tools-extra/trunk/unittests/clangd/IndexActionTests.cpp
+++ clang-tools-extra/trunk/unittests/clangd/IndexActionTests.cpp
@@ -29,6 +29,8 @@
 
 MATCHER_P(HasDigest, Digest, "") { return arg.Digest == Digest; }
 
+MATCHER_P(HasName, Name, "") { return arg.Name == Name; }
+
 MATCHER(HasSameURI, "") {
   llvm::StringRef URI = testing::get<0>(arg);
   const std::string &Path = testing::get<1>(arg);
@@ -43,6 +45,7 @@
 
 void checkNodesAreInitialized(const IndexFileIn &IndexFile,
   const std::vector &Paths) {
+  ASSERT_TRUE(IndexFile.Sources);
   EXPECT_THAT(Paths.size(), IndexFile.Sources->size());
   for (llvm::StringRef Path : Paths) {
 auto URI = toUri(Path);
@@ -224,6 +227,27 @@
 HasDigest(digest(HeaderCode));
 }
 
+TEST_F(IndexActionTest, NoWarnings) {
+  std::string MainFilePath = testPath("main.cpp");
+  std::string MainCode = R"cpp(
+  void foo(int x) {
+if (x = 1) // -Wparentheses
+  return;
+if (x = 1) // -Wparentheses
+  return;
+  }
+  void bar() {}
+  )cpp";
+  addFile(MainFilePath, MainCode);
+  // We set -ferror-limit so the warning-promoted-to-error would be fatal.
+  // This would cause indexing to stop (if warnings weren't disabled).
+  IndexFileIn IndexFile = runIndexingAction(
+  MainFilePath, {"-ferror-limit=1", "-Wparentheses", "-Werror"});
+  ASSERT_TRUE(IndexFile.Sources);
+  ASSERT_NE(0u, IndexFile.Sources->size());
+  EXPECT_THAT(*IndexFile.Symbols, ElementsAre(HasName("foo"), HasName("bar")));
+}
+
 } // namespace
 } // namespace clangd
 } // namespace clang
Index: clang-tools-extra/trunk/clangd/index/IndexAction.cpp
===
--- clang-tools-extra/trunk/clangd/index/IndexAction.cpp
+++ clang-tools-extra/trunk/clangd/index/IndexAction.cpp
@@ -135,6 +135,11 @@
   bool BeginInvocation(CompilerInstance &CI) override {
 // We want all comments, not just the doxygen ones.
 CI.getLangOpts().CommentOpts.ParseAllComments = true;
+// Index the whole file even if there are warnings and -Werror is set.
+// Avoids some analyses too. Set in two places as we're late to the party.
+CI.getDiagnosticOpts().IgnoreWarnings = true;
+CI.getDiagnostics().setIgnoreAllWarnings(true);
+
 return WrapperFrontendAction::BeginInvocation(CI);
   }
 


Index: clang-tools-extra/trunk/unittests/clangd/IndexActionTests.cpp
===
--- clang-tools-extra/trunk/unittests/clangd/IndexActionTests.cpp
+++ clang-tools-extra/trunk/unittests/clangd/IndexActionTests.cpp
@@ -29,6 +29,8 @@
 
 MATCHER_P(HasDigest, Digest, "") { return arg.Digest == Digest; }
 
+MATCHER_P(HasName, Name, "") { return arg.Name == Name; }
+
 MATCHER(HasSameURI, "") {
   llvm::StringRef URI = testing::get<0>(arg);
   const std::string &Path = testing::get<1>(arg);
@@ -43,6 +45,7 @@
 
 void checkNodesAreInitialized(const IndexFileIn &IndexFile,
   const std::vector &Paths) {
+  ASSERT_TRUE(IndexFile.Sources);
   EXPECT_THAT(Paths.size(), IndexFile.Sources->size());
   for (llvm::StringRef Path : Paths) {
 auto URI = toUri(Path);
@@ -224,6 +227,27 @@
 HasDigest(digest(HeaderCode));
 }
 
+TEST_F(IndexActionTest, NoWarnings) {
+  std::string MainFilePath = testPath("main.cpp");
+  std::string MainCode = R"cpp(
+  void foo(int x) {
+if (x = 1) // -Wparentheses
+  return;
+if (x = 1) // -Wparentheses
+  return;
+  }
+  void bar() {}
+  )cpp";
+  addFile(MainFilePath, MainCode);
+  // We set -ferror-limit so the warning-promoted-to-error would be fatal.
+  // This would cause indexing to stop (if warnings weren't disabled).
+  IndexFileIn IndexFile = runIndexingAction(
+  MainFilePath, {"-ferror-limit=1", "-Wparentheses", "-Werror"});
+  ASSERT_TRUE(IndexFile.Sources);
+  ASSERT_NE(0u, IndexFile.Sources->size());
+  EXPECT_THAT(*IndexFile.Symbols, ElementsAre(HasName("foo"), HasName("bar")));
+}
+
 } // namespace
 } // namespace clangd
 } // namespace clang
Index: clang-tools-extra/trunk/clangd

[PATCH] D59814: [Testing] Move clangd::Annotations to llvm testing support

2019-03-28 Thread Ilya Biryukov via Phabricator via cfe-commits
ilya-biryukov updated this revision to Diff 192673.
ilya-biryukov marked 4 inline comments as done.
ilya-biryukov added a comment.

- Move Range into the body of Annotations
- Use triple-slash comments
- Added a FIXME that we might want to change the syntax
- Move the doc comment to the class


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D59814/new/

https://reviews.llvm.org/D59814

Files:
  clang-tools-extra/unittests/clangd/Annotations.cpp
  clang-tools-extra/unittests/clangd/Annotations.h
  clang/unittests/Sema/CMakeLists.txt
  clang/unittests/Sema/CodeCompleteTest.cpp
  llvm/include/llvm/Testing/Support/Annotations.h
  llvm/lib/Testing/Support/Annotations.cpp
  llvm/lib/Testing/Support/CMakeLists.txt

Index: llvm/lib/Testing/Support/CMakeLists.txt
===
--- llvm/lib/Testing/Support/CMakeLists.txt
+++ llvm/lib/Testing/Support/CMakeLists.txt
@@ -2,6 +2,7 @@
 add_definitions(-DGTEST_HAS_TR1_TUPLE=0)
 
 add_llvm_library(LLVMTestingSupport
+  Annotations.cpp
   Error.cpp
   SupportHelpers.cpp
 
Index: llvm/lib/Testing/Support/Annotations.cpp
===
--- llvm/lib/Testing/Support/Annotations.cpp
+++ llvm/lib/Testing/Support/Annotations.cpp
@@ -6,11 +6,12 @@
 //
 //===--===//
 
-#include "Annotations.h"
-#include "SourceCode.h"
+#include "llvm/Testing/Support/Annotations.h"
 
-namespace clang {
-namespace clangd {
+#include "llvm/ADT/StringExtras.h"
+#include "llvm/Support/raw_ostream.h"
+
+using namespace llvm;
 
 // Crash if the assertion fails, printing the message and testcase.
 // More elegant error handling isn't needed for unit tests.
@@ -22,30 +23,31 @@
 }
 
 Annotations::Annotations(llvm::StringRef Text) {
-  auto Here = [this] { return offsetToPosition(Code, Code.size()); };
   auto Require = [Text](bool Assertion, const char *Msg) {
 require(Assertion, Msg, Text);
   };
   llvm::Optional Name;
-  llvm::SmallVector, 8> OpenRanges;
+  llvm::SmallVector, 8> OpenRanges;
 
   Code.reserve(Text.size());
   while (!Text.empty()) {
 if (Text.consume_front("^")) {
-  Points[Name.getValueOr("")].push_back(Here());
-  Name = None;
+  Points[Name.getValueOr("")].push_back(Code.size());
+  Name = llvm::None;
   continue;
 }
 if (Text.consume_front("[[")) {
-  OpenRanges.emplace_back(Name.getValueOr(""), Here());
-  Name = None;
+  OpenRanges.emplace_back(Name.getValueOr(""), Code.size());
+  Name = llvm::None;
   continue;
 }
 Require(!Name, "$name should be followed by ^ or [[");
 if (Text.consume_front("]]")) {
   Require(!OpenRanges.empty(), "unmatched ]]");
-  Ranges[OpenRanges.back().first].push_back(
-  {OpenRanges.back().second, Here()});
+  Range R;
+  R.Begin = OpenRanges.back().second;
+  R.End = Code.size();
+  Ranges[OpenRanges.back().first].push_back(R);
   OpenRanges.pop_back();
   continue;
 }
@@ -61,26 +63,27 @@
   Require(OpenRanges.empty(), "unmatched [[");
 }
 
-Position Annotations::point(llvm::StringRef Name) const {
+size_t Annotations::point(llvm::StringRef Name) const {
   auto I = Points.find(Name);
   require(I != Points.end() && I->getValue().size() == 1,
   "expected exactly one point", Code);
   return I->getValue()[0];
 }
-std::vector Annotations::points(llvm::StringRef Name) const {
+
+std::vector Annotations::points(llvm::StringRef Name) const {
   auto P = Points.lookup(Name);
   return {P.begin(), P.end()};
 }
-Range Annotations::range(llvm::StringRef Name) const {
+
+Annotations::Range Annotations::range(llvm::StringRef Name) const {
   auto I = Ranges.find(Name);
   require(I != Ranges.end() && I->getValue().size() == 1,
   "expected exactly one range", Code);
   return I->getValue()[0];
 }
-std::vector Annotations::ranges(llvm::StringRef Name) const {
+
+std::vector
+Annotations::ranges(llvm::StringRef Name) const {
   auto R = Ranges.lookup(Name);
   return {R.begin(), R.end()};
 }
-
-} // namespace clangd
-} // namespace clang
Index: llvm/include/llvm/Testing/Support/Annotations.h
===
--- /dev/null
+++ llvm/include/llvm/Testing/Support/Annotations.h
@@ -0,0 +1,81 @@
+//===--- Annotations.h - Annotated source code for tests -*- C++-*-===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+#ifndef LLVM_TESTING_SUPPORT_ANNOTATIONS_H
+#define LLVM_TESTING_SUPPORT_ANNOTATIONS_H
+
+#include "llvm/ADT/SmallVector.h"
+#include "llvm/ADT/StringMap.h"
+#include "llvm/ADT/StringRef.h"
+#include 
+
+namespace llvm {

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

2019-03-28 Thread Manuel Klimek via Phabricator via cfe-commits
klimek added inline comments.



Comment at: lib/Format/WhitespaceManager.cpp:520
+
+  AlignMacroSequence(StartOfSequence, EndOfSequence, MinColumn, MaxColumn,
+ FoundMatchOnLine, AlignMacrosMatches, Changes);

Why are we calling AlignMacroSequence(0, 0, ...) here?



Comment at: lib/Format/WhitespaceManager.cpp:524
+  unsigned I = 0;
+  for (unsigned E = Changes.size(); I != E; ++I) {
+if (Changes[I].NewlinesBefore != 0) {

I still think the code in this loop either needs significantly more comments to 
explain what's going on, or needs to be changed to be more straight forward:
What I don't understand is why we're calling AlignMacroSequence potentially 
multiple times, and especially what things like the if in line 541 are for.


CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D28462/new/

https://reviews.llvm.org/D28462



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


[PATCH] D59814: [Testing] Move clangd::Annotations to llvm testing support

2019-03-28 Thread Ilya Biryukov via Phabricator via cfe-commits
ilya-biryukov added a comment.

I've added a FIXME to the class.
Also want to add some basic tests before landing this.




Comment at: clang-tools-extra/unittests/clangd/Annotations.h:8
 
//===--===//
-//
-// Annotations lets you mark points and ranges inside source code, for tests:
-//
-//Annotations Example(R"cpp(
-//   int complete() { x.pri^ }  // ^ indicates a point
-//   void err() { [["hello" == 42]]; }  // [[this is a range]]
-//   $definition^class Foo{};   // points can be named: 
"definition"
-//   $fail[[static_assert(false, "")]]  // ranges can be named too: "fail"
-//)cpp");
-//
-//StringRef Code = Example.code();  // annotations stripped.
-//std::vector PP = Example.points();  // all unnamed points
-//Position P = Example.point(); // there must be exactly 
one
-//Range R = Example.range("fail");  // find named ranges
-//
-// Points/ranges are coordinates into `code()` which is stripped of 
annotations.
-//
-// Ranges may be nested (and points can be inside ranges), but there's no way
-// to define general overlapping ranges.
-//
+// A clangd-specific version of llvm/Testing/Support/Annotations.h, replaces
+// offsets and offset-based ranges with types from the LSP protocol.

sammccall wrote:
> The choice to shadow the base methods is interesting. I guess we can always 
> use llvm::Annotations if we want byte offsets (I know there are some), not 
> sure if we ever want a mix.
> Anyway this is nice and clean, and minimizes the diff. We can change later if 
> we care.
Exactly my thoughts. I don't expect us to have places that need both the 
offsets and the positions.


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D59814/new/

https://reviews.llvm.org/D59814



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


r357187 - Make helper functions static. NFC.

2019-03-28 Thread Benjamin Kramer via cfe-commits
Author: d0k
Date: Thu Mar 28 10:18:42 2019
New Revision: 357187

URL: http://llvm.org/viewvc/llvm-project?rev=357187&view=rev
Log:
Make helper functions static. NFC.

Modified:
cfe/trunk/lib/CodeGen/BackendUtil.cpp
cfe/trunk/lib/Sema/SemaOpenMP.cpp
cfe/trunk/lib/StaticAnalyzer/Core/BugReporterVisitors.cpp

Modified: cfe/trunk/lib/CodeGen/BackendUtil.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/CodeGen/BackendUtil.cpp?rev=357187&r1=357186&r2=357187&view=diff
==
--- cfe/trunk/lib/CodeGen/BackendUtil.cpp (original)
+++ cfe/trunk/lib/CodeGen/BackendUtil.cpp Thu Mar 28 10:18:42 2019
@@ -914,9 +914,10 @@ static PassBuilder::OptimizationLevel ma
   }
 }
 
-void addSanitizersAtO0(ModulePassManager &MPM, const Triple &TargetTriple,
-   const LangOptions &LangOpts,
-   const CodeGenOptions &CodeGenOpts) {
+static void addSanitizersAtO0(ModulePassManager &MPM,
+  const Triple &TargetTriple,
+  const LangOptions &LangOpts,
+  const CodeGenOptions &CodeGenOpts) {
   if (LangOpts.Sanitize.has(SanitizerKind::Address)) {
 MPM.addPass(RequireAnalysisPass());
 bool Recover = CodeGenOpts.SanitizeRecover.has(SanitizerKind::Address);

Modified: cfe/trunk/lib/Sema/SemaOpenMP.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Sema/SemaOpenMP.cpp?rev=357187&r1=357186&r2=357187&view=diff
==
--- cfe/trunk/lib/Sema/SemaOpenMP.cpp (original)
+++ cfe/trunk/lib/Sema/SemaOpenMP.cpp Thu Mar 28 10:18:42 2019
@@ -13352,10 +13352,11 @@ static bool checkMapConflicts(
 
 // Look up the user-defined mapper given the mapper name and mapped type, and
 // build a reference to it.
-ExprResult buildUserDefinedMapperRef(Sema &SemaRef, Scope *S,
- CXXScopeSpec &MapperIdScopeSpec,
- const DeclarationNameInfo &MapperId,
- QualType Type, Expr *UnresolvedMapper) {
+static ExprResult buildUserDefinedMapperRef(Sema &SemaRef, Scope *S,
+CXXScopeSpec &MapperIdScopeSpec,
+const DeclarationNameInfo 
&MapperId,
+QualType Type,
+Expr *UnresolvedMapper) {
   if (MapperIdScopeSpec.isInvalid())
 return ExprError();
   // Find all user-defined mappers with the given MapperId.

Modified: cfe/trunk/lib/StaticAnalyzer/Core/BugReporterVisitors.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/StaticAnalyzer/Core/BugReporterVisitors.cpp?rev=357187&r1=357186&r2=357187&view=diff
==
--- cfe/trunk/lib/StaticAnalyzer/Core/BugReporterVisitors.cpp (original)
+++ cfe/trunk/lib/StaticAnalyzer/Core/BugReporterVisitors.cpp Thu Mar 28 
10:18:42 2019
@@ -161,8 +161,8 @@ const Expr *bugreporter::getDerefExpr(co
 /// are the immediate snapshots of the tracked region's bindings within the
 /// node's respective states but not really checking that these snapshots
 /// actually contain the same set of bindings.
-bool hasVisibleUpdate(const ExplodedNode *LeftNode, SVal LeftVal,
-  const ExplodedNode *RightNode, SVal RightVal) {
+static bool hasVisibleUpdate(const ExplodedNode *LeftNode, SVal LeftVal,
+ const ExplodedNode *RightNode, SVal RightVal) {
   if (LeftVal == RightVal)
 return true;
 


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


r357195 - [WebAssembly] Reland of rL356953 (4dcf3acce6)

2019-03-28 Thread Sam Clegg via cfe-commits
Author: sbc
Date: Thu Mar 28 10:45:18 2019
New Revision: 357195

URL: http://llvm.org/viewvc/llvm-project?rev=357195&view=rev
Log:
[WebAssembly] Reland of rL356953 (4dcf3acce6)

The previous patch was missing GetProgramPath() in the return value
of getLinkerPath().

See https://reviews.llvm.org/D59743

Modified:
cfe/trunk/lib/Driver/ToolChains/WebAssembly.cpp
cfe/trunk/lib/Driver/ToolChains/WebAssembly.h
cfe/trunk/test/Driver/wasm-toolchain.c
cfe/trunk/test/Driver/wasm-toolchain.cpp

Modified: cfe/trunk/lib/Driver/ToolChains/WebAssembly.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Driver/ToolChains/WebAssembly.cpp?rev=357195&r1=357194&r2=357195&view=diff
==
--- cfe/trunk/lib/Driver/ToolChains/WebAssembly.cpp (original)
+++ cfe/trunk/lib/Driver/ToolChains/WebAssembly.cpp Thu Mar 28 10:45:18 2019
@@ -12,6 +12,8 @@
 #include "clang/Driver/Driver.h"
 #include "clang/Driver/DriverDiagnostic.h"
 #include "clang/Driver/Options.h"
+#include "llvm/Support/FileSystem.h"
+#include "llvm/Support/Path.h"
 #include "llvm/Option/ArgList.h"
 
 using namespace clang::driver;
@@ -36,6 +38,25 @@ bool wasm::Linker::isLinkJob() const { r
 
 bool wasm::Linker::hasIntegratedCPP() const { return false; }
 
+std::string wasm::Linker::getLinkerPath(const ArgList &Args) const {
+  const ToolChain &ToolChain = getToolChain();
+  if (const Arg* A = Args.getLastArg(options::OPT_fuse_ld_EQ)) {
+StringRef UseLinker = A->getValue();
+if (!UseLinker.empty()) {
+  if (llvm::sys::path::is_absolute(UseLinker) &&
+  llvm::sys::fs::can_execute(UseLinker))
+return UseLinker;
+
+  // Accept 'lld', and 'ld' as aliases for the default linker
+  if (UseLinker != "lld" && UseLinker != "ld")
+ToolChain.getDriver().Diag(diag::err_drv_invalid_linker_name)
+<< A->getAsString(Args);
+}
+  }
+
+  return ToolChain.GetProgramPath(ToolChain.getDefaultLinker());
+}
+
 void wasm::Linker::ConstructJob(Compilation &C, const JobAction &JA,
 const InputInfo &Output,
 const InputInfoList &Inputs,
@@ -43,7 +64,7 @@ void wasm::Linker::ConstructJob(Compilat
 const char *LinkingOutput) const {
 
   const ToolChain &ToolChain = getToolChain();
-  const char *Linker = Args.MakeArgString(ToolChain.GetLinkerPath());
+  const char *Linker = Args.MakeArgString(getLinkerPath(Args));
   ArgStringList CmdArgs;
 
   if (Args.hasArg(options::OPT_s))

Modified: cfe/trunk/lib/Driver/ToolChains/WebAssembly.h
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Driver/ToolChains/WebAssembly.h?rev=357195&r1=357194&r2=357195&view=diff
==
--- cfe/trunk/lib/Driver/ToolChains/WebAssembly.h (original)
+++ cfe/trunk/lib/Driver/ToolChains/WebAssembly.h Thu Mar 28 10:45:18 2019
@@ -23,6 +23,7 @@ public:
   explicit Linker(const ToolChain &TC);
   bool isLinkJob() const override;
   bool hasIntegratedCPP() const override;
+  std::string getLinkerPath(const llvm::opt::ArgList &Args) const;
   void ConstructJob(Compilation &C, const JobAction &JA,
 const InputInfo &Output, const InputInfoList &Inputs,
 const llvm::opt::ArgList &TCArgs,

Modified: cfe/trunk/test/Driver/wasm-toolchain.c
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/Driver/wasm-toolchain.c?rev=357195&r1=357194&r2=357195&view=diff
==
--- cfe/trunk/test/Driver/wasm-toolchain.c (original)
+++ cfe/trunk/test/Driver/wasm-toolchain.c Thu Mar 28 10:45:18 2019
@@ -12,25 +12,25 @@
 
 // A basic C link command-line with unknown OS.
 
-// RUN: %clang -### -no-canonical-prefixes -target wasm32-unknown-unknown 
--sysroot=/foo -fuse-ld=wasm-ld %s 2>&1 | FileCheck -check-prefix=LINK %s
+// RUN: %clang -### -no-canonical-prefixes -target wasm32-unknown-unknown 
--sysroot=/foo %s 2>&1 | FileCheck -check-prefix=LINK %s
 // LINK: clang{{.*}}" "-cc1" {{.*}} "-o" "[[temp:[^"]*]]"
 // LINK: wasm-ld{{.*}}" "-L/foo/lib" "crt1.o" "[[temp]]" "-lc" 
"{{.*[/\\]}}libclang_rt.builtins-wasm32.a" "-o" "a.out"
 
 // A basic C link command-line with optimization with unknown OS.
 
-// RUN: %clang -### -O2 -no-canonical-prefixes -target wasm32-unknown-unknown 
--sysroot=/foo -fuse-ld=wasm-ld %s 2>&1 | FileCheck -check-prefix=LINK_OPT %s
+// RUN: %clang -### -O2 -no-canonical-prefixes -target wasm32-unknown-unknown 
--sysroot=/foo %s 2>&1 | FileCheck -check-prefix=LINK_OPT %s
 // LINK_OPT: clang{{.*}}" "-cc1" {{.*}} "-o" "[[temp:[^"]*]]"
 // LINK_OPT: wasm-ld{{.*}}" "-L/foo/lib" "crt1.o" "[[temp]]" "-lc" 
"{{.*[/\\]}}libclang_rt.builtins-wasm32.a" "-o" "a.out"
 
 // A basic C link command-line with known OS.
 
-// RUN: %clang -### -no-canonical-prefixes -target wasm32-unknown-wasi-musl 
--sysroot=/foo -fuse-

[PATCH] D59811: [clangd] Add fallback mode for code completion when compile command or preamble is not ready.

2019-03-28 Thread Eric Liu via Phabricator via cfe-commits
ioeric updated this revision to Diff 192683.
ioeric marked 9 inline comments as done.
ioeric added a comment.

- address review comments.


Repository:
  rCTE Clang Tools Extra

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D59811/new/

https://reviews.llvm.org/D59811

Files:
  clangd/ClangdServer.cpp
  clangd/CodeComplete.h
  clangd/TUScheduler.cpp
  clangd/TUScheduler.h
  clangd/Threading.h
  clangd/tool/ClangdMain.cpp
  unittests/clangd/ClangdTests.cpp
  unittests/clangd/TUSchedulerTests.cpp

Index: unittests/clangd/TUSchedulerTests.cpp
===
--- unittests/clangd/TUSchedulerTests.cpp
+++ unittests/clangd/TUSchedulerTests.cpp
@@ -15,14 +15,13 @@
 #include "gmock/gmock.h"
 #include "gtest/gtest.h"
 #include 
+#include 
 #include 
 
 namespace clang {
 namespace clangd {
 namespace {
 
-using ::testing::_;
-using ::testing::AllOf;
 using ::testing::AnyOf;
 using ::testing::Each;
 using ::testing::ElementsAre;
@@ -35,13 +34,18 @@
 
 class TUSchedulerTests : public ::testing::Test {
 protected:
-  ParseInputs getInputs(PathRef File, std::string Contents) {
+  FileUpdateInputs getInputs(PathRef File, std::string Contents) {
 ParseInputs Inputs;
-Inputs.CompileCommand = *CDB.getCompileCommand(File);
 Inputs.FS = buildTestFS(Files, Timestamps);
 Inputs.Contents = std::move(Contents);
 Inputs.Opts = ParseOptions();
-return Inputs;
+FileUpdateInputs UpdateInputs;
+UpdateInputs.InputSansCommand = std::move(Inputs);
+std::string FilePath = File;
+UpdateInputs.GetCompileCommand = [this, FilePath]() {
+  return *CDB.getCompileCommand(FilePath);
+};
+return UpdateInputs;
   }
 
   void updateWithCallback(TUScheduler &S, PathRef File,
@@ -72,7 +76,7 @@
   /// Schedule an update and call \p CB with the diagnostics it produces, if
   /// any. The TUScheduler should be created with captureDiags as a
   /// DiagsCallback for this to work.
-  void updateWithDiags(TUScheduler &S, PathRef File, ParseInputs Inputs,
+  void updateWithDiags(TUScheduler &S, PathRef File, FileUpdateInputs Inputs,
WantDiagnostics WD,
llvm::unique_function)> CB) {
 Path OrigFile = File.str();
@@ -245,7 +249,7 @@
 
 S.runWithPreamble("StaleRead", Path, TUScheduler::Stale,
   [&](Expected Pre) {
-ASSERT_TRUE(bool(Pre));
+EXPECT_TRUE((bool)Pre);
 assert(bool(Pre));
 EXPECT_THAT(includes(Pre->Preamble),
 ElementsAre(""));
@@ -397,8 +401,9 @@
 EXPECT_THAT(Context::current().get(NonceKey), Pointee(Nonce));
 
 ASSERT_TRUE((bool)AST);
-EXPECT_EQ(AST->Inputs.FS, Inputs.FS);
-EXPECT_EQ(AST->Inputs.Contents, Inputs.Contents);
+EXPECT_EQ(AST->Inputs.FS, Inputs.InputSansCommand.FS);
+EXPECT_EQ(AST->Inputs.Contents,
+  Inputs.InputSansCommand.Contents);
 
 std::lock_guard Lock(Mut);
 ++TotalASTReads;
@@ -415,7 +420,7 @@
 EXPECT_THAT(Context::current().get(NonceKey), Pointee(Nonce));
 
 ASSERT_TRUE((bool)Preamble);
-EXPECT_EQ(Preamble->Contents, Inputs.Contents);
+EXPECT_EQ(Preamble->Contents, Inputs.InputSansCommand.Contents);
 
 std::lock_guard Lock(Mut);
 ++TotalPreambleReads;
@@ -504,6 +509,7 @@
   )cpp";
   auto WithEmptyPreamble = R"cpp(int main() {})cpp";
   S.update(Foo, getInputs(Foo, WithPreamble), WantDiagnostics::Auto);
+
   S.runWithPreamble(
   "getNonEmptyPreamble", Foo, TUScheduler::Stale,
   [&](Expected Preamble) {
Index: unittests/clangd/ClangdTests.cpp
===
--- unittests/clangd/ClangdTests.cpp
+++ unittests/clangd/ClangdTests.cpp
@@ -13,8 +13,10 @@
 #include "Matchers.h"
 #include "SyncAPI.h"
 #include "TestFS.h"
+#include "Threading.h"
 #include "URI.h"
 #include "clang/Config/config.h"
+#include "clang/Sema/CodeCompleteConsumer.h"
 #include "llvm/ADT/SmallVector.h"
 #include "llvm/ADT/StringMap.h"
 #include "llvm/Support/Errc.h"
@@ -36,7 +38,6 @@
 namespace {
 
 using ::testing::ElementsAre;
-using ::testing::Eq;
 using ::testing::Field;
 using ::testing::Gt;
 using ::testing::IsEmpty;
@@ -1058,6 +1059,55 @@
   EXPECT_NE(Result, "");
 }
 
+TEST_F(ClangdVFSTest, FallbackWhenPreambleIsNotReady) {
+  MockFSProvider FS;
+  ErrorCheckingDiagConsumer DiagConsumer;
+  // Returns compile command only when notified.
+  class DelayedCompilationDatabase : public GlobalCompilationDatabase {
+  public:
+DelayedCompilationDatabase(Notification &CanReturnCommand)
+: CanReturnCommand(CanReturnCommand) {}
+
+llvm::Optional
+getCompileCommand(PathRef File, ProjectInfo * = nullptr) const override {
+  

[PATCH] D59811: [clangd] Add fallback mode for code completion when compile command or preamble is not ready.

2019-03-28 Thread Eric Liu via Phabricator via cfe-commits
ioeric added a comment.

In D59811#1445701 , @ilya-biryukov 
wrote:

> I think this option should be configurable (and off by default) for the 
> transition period. A few reasons to do so:
>
> - Before we have an actual implementation of fallback completions, the 
> current behavior (waiting for the first preamble) actually seems like a 
> better experience than returning empty results.
> - Some clients do this kind of fallback on their own (e.g. VSCode), so until 
> we can provide actually semantically interesting results (anything more than 
> identifier-based really, e.g. keyword completions) we would be better off 
> keeping it off.
> - We can still test it if it's off by flipping the corresponding flag in the 
> test code.
> - Would make rollout easier (clients can flip the flag back and forth and 
> make sure it does not break stuff for them)


All very good points. Thanks! I've added an option.




Comment at: clangd/ClangdServer.cpp:197
   return CB(llvm::make_error());
+if (!IP->Preamble) {
+  vlog("File {0} is not ready for code completion. Enter fallback mode.",

ilya-biryukov wrote:
> This way we don't distinguish between the failure to build a preamble and the 
> fallback mode.
> Have you considered introducing a different callback instead to clearly 
> separate two cases for the clients?
> The code handling those would hardly have any similarities anyway, given that 
> the nature of those two cases is so different.
> 
> Would look something like this:
> ```
> /// When \p FallbackAction is not null, it would be called instead of \p 
> Action in cases when preamble is 
> /// not yet ready.
> void runWithPreamble(… Callback Action, Callback 
> FallbackAction);
> ```
> void runWithPreamble(… Callback Action, Callback 
> FallbackAction);
This is what I started with in the first iteration. The main problem is that we 
would need to bind `CB` to both actions; however, `CB` is not 
copyable/shareable by design, I think. This seems to leave us with the only 
option to handle everything in the same action. I thought this was fine because 
an parameter `AllowFallback` seems to be clear as well. I'm open to suggestions 
;)

> This way we don't distinguish between the failure to build a preamble and the 
> fallback mode.
I am assuming that a fallback for `runWithPreamble` is either compile command 
is missing/broken or preamble fails to be built. And in both cases, fallback 
mode could be useful. Do you think we should have more distinctions made here?



Comment at: clangd/TUScheduler.cpp:186
 
   std::shared_ptr getPossiblyStalePreamble() const;
+

ilya-biryukov wrote:
> Could we put the preamble and compile command into a single function?
> Getting them in the lock-step would mean they're always consistent, which is 
> a good thing.
Could you elaborate the advantages of keeping them consistent?

They seem to be updated and used relatively independently. Grouping them into 
one function seems to add more work to the call sites.  And it seems inevitable 
that we would some inconsistency between the two.



Comment at: clangd/TUScheduler.cpp:371
+  std::lock_guard Lock(Mutex);
+  this->CompileCommand = Inputs.CompileCommand;
+}

ilya-biryukov wrote:
> After this point the clients might start getting a new compile command and an 
> old preamble.
> This seems fine (the clients should be ready for this), but let's document it 
> in the methods that expose a compile command and a preamble.
> After this point the clients might start getting a new compile command and an 
> old preamble.
Did we have guarantee about this before? It seems that we could also have the 
similar situation.

> This seems fine (the clients should be ready for this), but let's document it 
> in the methods that expose a compile command and a preamble.
I added documentation for `getCurrentPreamble`; would it be the right place? 
`getPossiblyStalePreamble` seems self-explaining enough. And since compile 
command is always fresher than preamble, I think it would be fine without 
commenting?



Comment at: clangd/TUScheduler.cpp:918
+  // asynchronous mode, as TU update should finish before this is run.
+  if (!It->second->Worker->isFirstPreambleBuilt() && AllowFallback &&
+  PreambleTasks) {

ilya-biryukov wrote:
> It would be better to make a decision on whether to use a fallback mode in 
> the actual function scheduled on a different thread (i.e. inside the body of 
> `Task`).
> Imagine the preamble is being built right now and would finish before 
> scheduling this task. In that case we would have a chance to hit the 
> "preamble" if we make a decision in the body of the handler, but won't have 
> that chance in the current implementation.
It sounds like a very small window (~ms?) that we are trying to optimize for.  
Given that users type rela

r357197 - [Driver] Default Android toolchains to noexecstack.

2019-03-28 Thread Dan Albert via cfe-commits
Author: danalbert
Date: Thu Mar 28 11:08:28 2019
New Revision: 357197

URL: http://llvm.org/viewvc/llvm-project?rev=357197&view=rev
Log:
[Driver] Default Android toolchains to noexecstack.

Android does not support executable stacks.

Reviewers: srhines, pirama

Reviewed By: pirama

Subscribers: cfe-commits

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

Modified:
cfe/trunk/include/clang/Driver/ToolChain.h
cfe/trunk/lib/Driver/ToolChain.cpp
cfe/trunk/lib/Driver/ToolChains/Clang.cpp
cfe/trunk/lib/Driver/ToolChains/Gnu.cpp
cfe/trunk/lib/Driver/ToolChains/Linux.cpp
cfe/trunk/lib/Driver/ToolChains/Linux.h
cfe/trunk/test/Driver/integrated-as.c
cfe/trunk/test/Driver/linux-as.c
cfe/trunk/test/Driver/linux-ld.c

Modified: cfe/trunk/include/clang/Driver/ToolChain.h
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Driver/ToolChain.h?rev=357197&r1=357196&r2=357197&view=diff
==
--- cfe/trunk/include/clang/Driver/ToolChain.h (original)
+++ cfe/trunk/include/clang/Driver/ToolChain.h Thu Mar 28 11:08:28 2019
@@ -412,6 +412,9 @@ public:
   /// Test whether this toolchain defaults to PIE.
   virtual bool isPIEDefault() const = 0;
 
+  /// Test whether this toolchaind defaults to non-executable stacks.
+  virtual bool isNoExecStackDefault() const;
+
   /// Tests whether this toolchain forces its default for PIC, PIE or
   /// non-PIC.  If this returns true, any PIC related flags should be ignored
   /// and instead the results of \c isPICDefault() and \c isPIEDefault() are

Modified: cfe/trunk/lib/Driver/ToolChain.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Driver/ToolChain.cpp?rev=357197&r1=357196&r2=357197&view=diff
==
--- cfe/trunk/lib/Driver/ToolChain.cpp (original)
+++ cfe/trunk/lib/Driver/ToolChain.cpp Thu Mar 28 11:08:28 2019
@@ -112,6 +112,10 @@ bool ToolChain::useRelaxRelocations() co
   return ENABLE_X86_RELAX_RELOCATIONS;
 }
 
+bool ToolChain::isNoExecStackDefault() const {
+return false;
+}
+
 const SanitizerArgs& ToolChain::getSanitizerArgs() const {
   if (!SanitizerArguments.get())
 SanitizerArguments.reset(new SanitizerArgs(*this, Args));

Modified: cfe/trunk/lib/Driver/ToolChains/Clang.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Driver/ToolChains/Clang.cpp?rev=357197&r1=357196&r2=357197&view=diff
==
--- cfe/trunk/lib/Driver/ToolChains/Clang.cpp (original)
+++ cfe/trunk/lib/Driver/ToolChains/Clang.cpp Thu Mar 28 11:08:28 2019
@@ -2053,6 +2053,7 @@ static void CollectArgsForIntegratedAsse
   bool TakeNextArg = false;
 
   bool UseRelaxRelocations = C.getDefaultToolChain().useRelaxRelocations();
+  bool UseNoExecStack = C.getDefaultToolChain().isNoExecStackDefault();
   const char *MipsTargetFeature = nullptr;
   for (const Arg *A :
Args.filtered(options::OPT_Wa_COMMA, options::OPT_Xassembler)) {
@@ -2134,7 +2135,7 @@ static void CollectArgsForIntegratedAsse
   } else if (Value == "--fatal-warnings") {
 CmdArgs.push_back("-massembler-fatal-warnings");
   } else if (Value == "--noexecstack") {
-CmdArgs.push_back("-mnoexecstack");
+UseNoExecStack = true;
   } else if (Value.startswith("-compress-debug-sections") ||
  Value.startswith("--compress-debug-sections") ||
  Value == "-nocompress-debug-sections" ||
@@ -2197,6 +2198,8 @@ static void CollectArgsForIntegratedAsse
   }
   if (UseRelaxRelocations)
 CmdArgs.push_back("--mrelax-relocations");
+  if (UseNoExecStack)
+CmdArgs.push_back("-mnoexecstack");
   if (MipsTargetFeature != nullptr) {
 CmdArgs.push_back("-target-feature");
 CmdArgs.push_back(MipsTargetFeature);

Modified: cfe/trunk/lib/Driver/ToolChains/Gnu.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Driver/ToolChains/Gnu.cpp?rev=357197&r1=357196&r2=357197&view=diff
==
--- cfe/trunk/lib/Driver/ToolChains/Gnu.cpp (original)
+++ cfe/trunk/lib/Driver/ToolChains/Gnu.cpp Thu Mar 28 11:08:28 2019
@@ -360,6 +360,11 @@ void tools::gnutools::Linker::ConstructJ
 CmdArgs.push_back("--no-dynamic-linker");
   }
 
+  if (ToolChain.isNoExecStackDefault()) {
+CmdArgs.push_back("-z");
+CmdArgs.push_back("noexecstack");
+  }
+
   if (Args.hasArg(options::OPT_rdynamic))
 CmdArgs.push_back("-export-dynamic");
 
@@ -609,6 +614,10 @@ void tools::gnutools::Assembler::Constru
 }
   }
 
+  if (getToolChain().isNoExecStackDefault()) {
+  CmdArgs.push_back("--noexecstack");
+  }
+
   switch (getToolChain().getArch()) {
   default:
 break;

Modified: cfe/trunk/lib/Driver/ToolChains/Linux.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Driver/ToolChains/Linux.cpp?rev=357197&r1=357196&r2=357

[PATCH] D59407: [clangd] Add RelationSlab

2019-03-28 Thread Sam McCall via Phabricator via cfe-commits
sammccall added a comment.

(Sorry to arrive late at this discussion, I'm just back from leave.
I have some suggestions and would appreciate your thoughts, but if simply this 
feels too much like going around in circles I'm happy to work out how we can 
address this after this patch lands instead.
Have discussed offline with @gribozavr and I think we're roughly on the same 
page. @kadircet is now out on leave)

I think the data model might be overly complicated here.
I can see how the discussion got here: it mirrors the other `*Slab` types quite 
closely. But:

- those types were designed to solve specific problems that we don't have here 
(string deduplication and symbol merging)
- I think the class-parent relation is pretty sparse (maybe 1 edge per 10 
symbols?) so lots of options will work fine
- I don't think we yet know what the more resource-critical (denser) relations 
and queries are, so it's unclear what to optimize for

I think the simplest model that can work here is something like:

- `Relation` is `struct { SymbolID Subject; SymbolRole Relation; SymbolID 
Object }`
- this is a value type, so could be passed around simply as 
`std::vector`. If `RelationSlab` is desired for symmetry, it could be 
an alias or simple wrapper around `std::vector`.

This has a few advantages:

- the `Relation` value_type is self-contained, has clearer semantics, and works 
as the result of any type of query: based on subject and/or predicate and/or 
object. (Similar to how it's convenient that Symbol contains SymbolID).
- if lookup is desired, lookup by subject, subject+predicate, or full-triple is 
possible by sorting in SPO order with binary search. Return type is simple 
`ArrayRef`. (Though fancy lookup maybe better belongs in MemIndex/Dex 
rather than in the slab). For more query types, storing a copies in OSP and/or 
POS order is pretty cheap too.
- memory efficiency: it costs `20*distinct(subject, predicate, object)` bytes, 
vs `28*distinct(subject, predicate) + 8 * distinct(subject, predicate, 
object)`. Unless the average number of objects for a `(subject, predicate)` 
pair (that has at least one object) is >2.3, the former is smaller. For the 
current use case, this average is certainly <1.1.
- simplicity: no arenas, easy mental model.

I see discussion of (something like) this option stalled around the index 
constructors, but I don't see a fundamental block there. The concept that the 
index constructor should be templated over would be `Iterable`. LMK 
if I'm missing something.


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D59407/new/

https://reviews.llvm.org/D59407



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


[PATCH] D53343: [Driver] Default Android toolchains to noexecstack.

2019-03-28 Thread Dan Albert via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rC357197: [Driver] Default Android toolchains to noexecstack. 
(authored by danalbert, committed by ).

Changed prior to commit:
  https://reviews.llvm.org/D53343?vs=169901&id=192686#toc

Repository:
  rC Clang

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D53343/new/

https://reviews.llvm.org/D53343

Files:
  include/clang/Driver/ToolChain.h
  lib/Driver/ToolChain.cpp
  lib/Driver/ToolChains/Clang.cpp
  lib/Driver/ToolChains/Gnu.cpp
  lib/Driver/ToolChains/Linux.cpp
  lib/Driver/ToolChains/Linux.h
  test/Driver/integrated-as.c
  test/Driver/linux-as.c
  test/Driver/linux-ld.c

Index: lib/Driver/ToolChains/Gnu.cpp
===
--- lib/Driver/ToolChains/Gnu.cpp
+++ lib/Driver/ToolChains/Gnu.cpp
@@ -360,6 +360,11 @@
 CmdArgs.push_back("--no-dynamic-linker");
   }
 
+  if (ToolChain.isNoExecStackDefault()) {
+CmdArgs.push_back("-z");
+CmdArgs.push_back("noexecstack");
+  }
+
   if (Args.hasArg(options::OPT_rdynamic))
 CmdArgs.push_back("-export-dynamic");
 
@@ -609,6 +614,10 @@
 }
   }
 
+  if (getToolChain().isNoExecStackDefault()) {
+  CmdArgs.push_back("--noexecstack");
+  }
+
   switch (getToolChain().getArch()) {
   default:
 break;
Index: lib/Driver/ToolChains/Clang.cpp
===
--- lib/Driver/ToolChains/Clang.cpp
+++ lib/Driver/ToolChains/Clang.cpp
@@ -2053,6 +2053,7 @@
   bool TakeNextArg = false;
 
   bool UseRelaxRelocations = C.getDefaultToolChain().useRelaxRelocations();
+  bool UseNoExecStack = C.getDefaultToolChain().isNoExecStackDefault();
   const char *MipsTargetFeature = nullptr;
   for (const Arg *A :
Args.filtered(options::OPT_Wa_COMMA, options::OPT_Xassembler)) {
@@ -2134,7 +2135,7 @@
   } else if (Value == "--fatal-warnings") {
 CmdArgs.push_back("-massembler-fatal-warnings");
   } else if (Value == "--noexecstack") {
-CmdArgs.push_back("-mnoexecstack");
+UseNoExecStack = true;
   } else if (Value.startswith("-compress-debug-sections") ||
  Value.startswith("--compress-debug-sections") ||
  Value == "-nocompress-debug-sections" ||
@@ -2197,6 +2198,8 @@
   }
   if (UseRelaxRelocations)
 CmdArgs.push_back("--mrelax-relocations");
+  if (UseNoExecStack)
+CmdArgs.push_back("-mnoexecstack");
   if (MipsTargetFeature != nullptr) {
 CmdArgs.push_back("-target-feature");
 CmdArgs.push_back(MipsTargetFeature);
Index: lib/Driver/ToolChains/Linux.h
===
--- lib/Driver/ToolChains/Linux.h
+++ lib/Driver/ToolChains/Linux.h
@@ -38,6 +38,7 @@
llvm::opt::ArgStringList &CC1Args) const override;
   CXXStdlibType GetDefaultCXXStdlibType() const override;
   bool isPIEDefault() const override;
+  bool isNoExecStackDefault() const override;
   bool IsMathErrnoDefault() const override;
   SanitizerMask getSupportedSanitizers() const override;
   void addProfileRTLibs(const llvm::opt::ArgList &Args,
Index: lib/Driver/ToolChains/Linux.cpp
===
--- lib/Driver/ToolChains/Linux.cpp
+++ lib/Driver/ToolChains/Linux.cpp
@@ -971,6 +971,10 @@
   getTriple().isMusl() || getSanitizerArgs().requiresPIE();
 }
 
+bool Linux::isNoExecStackDefault() const {
+return getTriple().isAndroid();
+}
+
 bool Linux::IsMathErrnoDefault() const {
   if (getTriple().isAndroid())
 return false;
Index: lib/Driver/ToolChain.cpp
===
--- lib/Driver/ToolChain.cpp
+++ lib/Driver/ToolChain.cpp
@@ -112,6 +112,10 @@
   return ENABLE_X86_RELAX_RELOCATIONS;
 }
 
+bool ToolChain::isNoExecStackDefault() const {
+return false;
+}
+
 const SanitizerArgs& ToolChain::getSanitizerArgs() const {
   if (!SanitizerArguments.get())
 SanitizerArguments.reset(new SanitizerArgs(*this, Args));
Index: include/clang/Driver/ToolChain.h
===
--- include/clang/Driver/ToolChain.h
+++ include/clang/Driver/ToolChain.h
@@ -412,6 +412,9 @@
   /// Test whether this toolchain defaults to PIE.
   virtual bool isPIEDefault() const = 0;
 
+  /// Test whether this toolchaind defaults to non-executable stacks.
+  virtual bool isNoExecStackDefault() const;
+
   /// Tests whether this toolchain forces its default for PIC, PIE or
   /// non-PIC.  If this returns true, any PIC related flags should be ignored
   /// and instead the results of \c isPICDefault() and \c isPIEDefault() are
Index: test/Driver/linux-as.c
===
--- test/Driver/linux-as.c
+++ test/Driver/linux-as.c
@@ -108,12 +108,12 @@
 // RUN: %clang -target arm-linux-androideabi -### \
 // RUN:   -no-integrated-as -c %s 2>&1 \
 // RUN:   

[PATCH] D59887: [Syntax] Introduce TokenBuffer, start clangToolingSyntax library

2019-03-28 Thread Dmitri Gribenko via Phabricator via cfe-commits
gribozavr added inline comments.



Comment at: clang/include/clang/Tooling/Syntax/TokenBuffer.h:69
+  /// The tokens after preprocessor replacements.
+  llvm::ArrayRef tokens(const TokenBuffer &B) const;
+  /// Tokens that appear in the text of the file, i.e. a name of an object-like

`expandedTokens`?



Comment at: clang/include/clang/Tooling/Syntax/TokenBuffer.h:72
+  /// macro or a name, arguments and parentheses of a function-like macro.
+  llvm::ArrayRef macroTokens(const TokenBuffer &B) const;
+  /// The range covering macroTokens().

`invocationTokens` or `macroInvocationTokens`



Comment at: clang/include/clang/Tooling/Syntax/TokenBuffer.h:74
+  /// The range covering macroTokens().
+  std::pair macroRange(const TokenBuffer &B,
+   const SourceManager &SM) const;

`invocationSourceRange` or `macroInvocationSourceRange` depending on what you 
choose for the function above.




Comment at: clang/include/clang/Tooling/Syntax/TokenBuffer.h:83
+  unsigned BeginMacroToken = 0;
+  unsigned EndMacroToken = 0;
+};

Please add brief doc comments to these variables. Having read the public API of 
this class, I still don't have an idea what these variables are.





Comment at: clang/include/clang/Tooling/Syntax/TokenBuffer.h:120
+  /// the original source file. The tranformation may not be possible if the
+  /// tokens cross macro invocations in the middle, e.g.
+  ///#define FOO 1*2

"The mapping fails if cross boundaries of macro expansions, that is, don't 
correspond to a complete top-level macro invocation"

Consider adding examples.

```
Given this source file:

#define FIRST f1 f2 f3
#define SECOND s1 s2 3

a FIRST b SECOND c  // expansion: a f1 f2 f3 b s1 s2 s3 c

toOffsetRange will map tokens like this:

input range => output range
a => a
s1 s2 s3 => SECOND
a f1 f2 f3 => a FIRST
a f1 => can't map
s1 s2 => s1 s2 within the macro definition
```

Could you add these to tests as well?



Comment at: clang/include/clang/Tooling/Syntax/TokenBuffer.h:153
+  /// FIXME: we do not yet store tokens of directives, like #include, #define,
+  ///#pragma, etc.
+  llvm::ArrayRef macroTokens() const { return MacroTokens; }

... For the input above, macroTokens() should return {desired output}



Comment at: clang/include/clang/Tooling/Syntax/TokenBuffer.h:191
+  /// i.e. after running Execute().
+  TokenBuffer consume() &&;
+

"Finalizes token collection"

Of course a function called "consume" consumes the result :)



Comment at: clang/include/clang/Tooling/Syntax/TokenBuffer.h:191
+  /// i.e. after running Execute().
+  TokenBuffer consume() &&;
+

gribozavr wrote:
> "Finalizes token collection"
> 
> Of course a function called "consume" consumes the result :)
LLVM_NODISCARD?



Comment at: clang/lib/Tooling/Syntax/TokenBuffer.cpp:295
+MacroExpansion::tokens(const TokenBuffer &B) const {
+  return B.tokens().slice(BeginExpansionToken,
+  EndExpansionToken - BeginExpansionToken);

"ExpansionTokenBegin"?  "ExpansionTokenStartIndex"?



Comment at: clang/lib/Tooling/Syntax/TokenBuffer.cpp:367
+  if (FirstCall != Expansions.end() &&
+  (FirstCall->BeginExpansionToken < BeginIndex ||
+   EndIndex < FirstCall->EndExpansionToken)) {

`FirstCall->BeginExpansionToken != BeginIndex` ?



Comment at: clang/lib/Tooling/Syntax/TokenBuffer.cpp:368
+  (FirstCall->BeginExpansionToken < BeginIndex ||
+   EndIndex < FirstCall->EndExpansionToken)) {
+return llvm::None;

I don't understand why `EndIndex < FirstCall->EndExpansionToken` is needed -- 
isn't it redundant with the `LastCall` checks below?



Comment at: clang/lib/Tooling/Syntax/TokenBuffer.cpp:373
+  if (LastCall != Expansions.end() &&
+  (LastCall->BeginExpansionToken < BeginIndex ||
+   EndIndex < LastCall->EndExpansionToken)) {

`LastCall->BeginExpansionToken != BeginIndex`?



Comment at: clang/lib/Tooling/Syntax/TokenBuffer.cpp:374
+  (LastCall->BeginExpansionToken < BeginIndex ||
+   EndIndex < LastCall->EndExpansionToken)) {
+return llvm::None;

Also redundant with `FirstCall` checks?



Comment at: clang/unittests/Tooling/Syntax/TokenBufferTest.cpp:355
+  checkTokens("");
+  checkMacroInvocations({{"EMPTY", "", Code.range("m")},
+   {"EMPTY_FUNC(1+2+3)", "", Code.range("f")}});

`expectTokens`, `expectMacroInvocations`?



Comment at: clang/unittests/Tooling/Syntax/TokenBufferTest.cpp:376
+  // The parser eventually breaks the first '>>' into two tokens ('>' and '>'),
+  // but 

[PATCH] D59008: [AMDGPU] Switch default dwarf version to 5

2019-03-28 Thread Scott Linder via Phabricator via cfe-commits
scott.linder updated this revision to Diff 192688.
scott.linder added a comment.

Add a test to confirm split-dwarf is supported for the amdhsa OS in the driver.


CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D59008/new/

https://reviews.llvm.org/D59008

Files:
  lib/Driver/ToolChains/AMDGPU.h
  test/Driver/amdgpu-toolchain.c
  test/Driver/split-debug.c


Index: test/Driver/split-debug.c
===
--- test/Driver/split-debug.c
+++ test/Driver/split-debug.c
@@ -38,6 +38,9 @@
 // RUN: %clang -target x86_64-pc-freebsd12 -gsplit-dwarf -c -### %s 2> %t
 // RUN: FileCheck -check-prefix=CHECK-OPTION < %t %s
 //
+// RUN: %clang -target amdgcn-amd-amdhsa -gsplit-dwarf -c -### %s 2> %t
+// RUN: FileCheck -check-prefix=CHECK-OPTION < %t %s
+//
 // CHECK-OPTION: "-split-dwarf-file" "split-debug.dwo"
 
 // RUN: %clang -target x86_64-unknown-linux-gnu -gsplit-dwarf -S -### %s 2> %t
Index: test/Driver/amdgpu-toolchain.c
===
--- test/Driver/amdgpu-toolchain.c
+++ test/Driver/amdgpu-toolchain.c
@@ -3,4 +3,4 @@
 // AS_LINK: ld.lld{{.*}} "-shared"
 
 // RUN: %clang -### -g -target amdgcn--amdhsa -mcpu=kaveri %s 2>&1 | FileCheck 
-check-prefix=DWARF_VER %s
-// DWARF_VER: "-dwarf-version=2"
+// DWARF_VER: "-dwarf-version=5"
Index: lib/Driver/ToolChains/AMDGPU.h
===
--- lib/Driver/ToolChains/AMDGPU.h
+++ lib/Driver/ToolChains/AMDGPU.h
@@ -55,7 +55,7 @@
 public:
   AMDGPUToolChain(const Driver &D, const llvm::Triple &Triple,
   const llvm::opt::ArgList &Args);
-  unsigned GetDefaultDwarfVersion() const override { return 2; }
+  unsigned GetDefaultDwarfVersion() const override { return 5; }
   bool IsIntegratedAssemblerDefault() const override { return true; }
   llvm::opt::DerivedArgList *
   TranslateArgs(const llvm::opt::DerivedArgList &Args, StringRef BoundArch,


Index: test/Driver/split-debug.c
===
--- test/Driver/split-debug.c
+++ test/Driver/split-debug.c
@@ -38,6 +38,9 @@
 // RUN: %clang -target x86_64-pc-freebsd12 -gsplit-dwarf -c -### %s 2> %t
 // RUN: FileCheck -check-prefix=CHECK-OPTION < %t %s
 //
+// RUN: %clang -target amdgcn-amd-amdhsa -gsplit-dwarf -c -### %s 2> %t
+// RUN: FileCheck -check-prefix=CHECK-OPTION < %t %s
+//
 // CHECK-OPTION: "-split-dwarf-file" "split-debug.dwo"
 
 // RUN: %clang -target x86_64-unknown-linux-gnu -gsplit-dwarf -S -### %s 2> %t
Index: test/Driver/amdgpu-toolchain.c
===
--- test/Driver/amdgpu-toolchain.c
+++ test/Driver/amdgpu-toolchain.c
@@ -3,4 +3,4 @@
 // AS_LINK: ld.lld{{.*}} "-shared"
 
 // RUN: %clang -### -g -target amdgcn--amdhsa -mcpu=kaveri %s 2>&1 | FileCheck -check-prefix=DWARF_VER %s
-// DWARF_VER: "-dwarf-version=2"
+// DWARF_VER: "-dwarf-version=5"
Index: lib/Driver/ToolChains/AMDGPU.h
===
--- lib/Driver/ToolChains/AMDGPU.h
+++ lib/Driver/ToolChains/AMDGPU.h
@@ -55,7 +55,7 @@
 public:
   AMDGPUToolChain(const Driver &D, const llvm::Triple &Triple,
   const llvm::opt::ArgList &Args);
-  unsigned GetDefaultDwarfVersion() const override { return 2; }
+  unsigned GetDefaultDwarfVersion() const override { return 5; }
   bool IsIntegratedAssemblerDefault() const override { return true; }
   llvm::opt::DerivedArgList *
   TranslateArgs(const llvm::opt::DerivedArgList &Args, StringRef BoundArch,
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D59923: [Driver] Simplify -g level computation and its interaction with -gsplit-dwarf

2019-03-28 Thread David Blaikie via Phabricator via cfe-commits
dblaikie requested changes to this revision.
dblaikie added a comment.
This revision now requires changes to proceed.

What's the general motivation for this work/changes?

> -gmlt -gsplit-dwarf -fno-split-dwarf-inlining => special: 1 (before) 2 (after)

This ^ is the only semantic change due to this refactoring?

There's a desire to be able to compose gmlt+gsplit-dwarf, /if/ 
-fno-split-dwarf-inlining is enabled. (for context, -fno-split-dwarf-inlining 
is the default in Google's optimized builds, since split-dwarf-inlining was 
never implemented in GCC & we didn't want to regress object size when switching 
from GCC to Clang (& no one had complained about that missing functionality))

So with -fno-split-dwarf-inlining, there's value in using gmlt with 
gsplit-dwarf (it reduces the size of the .dwo files - reducing the inputs/size 
of dwp, etc).

& it sounds like this change breaks that scenario?


Repository:
  rC Clang

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D59923/new/

https://reviews.llvm.org/D59923



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


[PATCH] D59932: [clang-tidy] **Prototype**: Add fix description to clang-tidy checks.

2019-03-28 Thread Eugene Zelenko via Phabricator via cfe-commits
Eugene.Zelenko added inline comments.



Comment at: clang-tidy/ClangTidyCheck.h:107
+  /// fixes for different cases.
+  ///   - clang compiler diagnostics and clang static analyzer diagnostics are
+  /// not supported.

I think Clang and Clang Static Analyzer should be capitalized.


Repository:
  rCTE Clang Tools Extra

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D59932/new/

https://reviews.llvm.org/D59932



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


[PATCH] D59932: [clang-tidy] **Prototype**: Add fix description to clang-tidy checks.

2019-03-28 Thread Jonas Toth via Phabricator via cfe-commits
JonasToth added a comment.

I think the idea is good and implementation, too. If we iterate all checks 
anyway (probably?) we could think about adding a severity to the checks, too?

I know that code-checker and code-compass have something like this to signal 
importance of problems (say bugprone and cert differ from readability for 
example).


Repository:
  rCTE Clang Tools Extra

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D59932/new/

https://reviews.llvm.org/D59932



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


[PATCH] D59870: [clang-tidy] Add MagnitudeBitsUpperLimit option to bugprone-too-small-loop-variable

2019-03-28 Thread Jonas Toth via Phabricator via cfe-commits
JonasToth added a comment.

> I think it's the easiest way to specify the bits of the ineteger type to 
> limit the catches. In real life, I met with this overflow / infinite loop 
> problem with 16-bit short type, so I think the real use cases are 8 and 16 
> bit integers. It seems intuitive to me to use the size of the loop variable's 
> type to separate those catches which can lead broken functionality in 
> practice from those use cases which are just integer incompatibilities.

Given your experience and the false positive rate in some projects, should we 
maybe default to 16 for that option?


CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D59870/new/

https://reviews.llvm.org/D59870



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


[PATCH] D59932: [clang-tidy] **Prototype**: Add fix description to clang-tidy checks.

2019-03-28 Thread Eugene Zelenko via Phabricator via cfe-commits
Eugene.Zelenko added a comment.

In D59932#1446533 , @JonasToth wrote:

> I think the idea is good and implementation, too. If we iterate all checks 
> anyway (probably?) we could think about adding a severity to the checks, too?
>
> I know that code-checker and code-compass have something like this to signal 
> importance of problems (say bugprone and cert differ from readability for 
> example).


Also Clazy  split checks by severity level.


Repository:
  rCTE Clang Tools Extra

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D59932/new/

https://reviews.llvm.org/D59932



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


[PATCH] D59953: Rename clang-tools-extra lit cfg files to lit.site.cfg.py

2019-03-28 Thread Nico Weber via Phabricator via cfe-commits
thakis created this revision.
thakis added a reviewer: zturner.
Herald added a subscriber: mgorny.
thakis added a comment.

Actually, let me rename lit.cfg to lit.cfg.py too, one sec...


Follow-up to r313892, which did this for clang and llvm.


https://reviews.llvm.org/D59953

Files:
  clang-tools-extra/test/CMakeLists.txt
  clang-tools-extra/test/Unit/lit.site.cfg.in
  clang-tools-extra/test/Unit/lit.site.cfg.py.in
  clang-tools-extra/test/lit.site.cfg.in
  clang-tools-extra/test/lit.site.cfg.py.in


Index: clang-tools-extra/test/CMakeLists.txt
===
--- clang-tools-extra/test/CMakeLists.txt
+++ clang-tools-extra/test/CMakeLists.txt
@@ -20,13 +20,13 @@
   CLANGD_BUILD_XPC_SUPPORT)
 
 configure_lit_site_cfg(
-  ${CMAKE_CURRENT_SOURCE_DIR}/lit.site.cfg.in
-  ${CMAKE_CURRENT_BINARY_DIR}/lit.site.cfg
+  ${CMAKE_CURRENT_SOURCE_DIR}/lit.site.cfg.py.in
+  ${CMAKE_CURRENT_BINARY_DIR}/lit.site.cfg.py
   )
 
 configure_lit_site_cfg(
-  ${CMAKE_CURRENT_SOURCE_DIR}/Unit/lit.site.cfg.in
-  ${CMAKE_CURRENT_BINARY_DIR}/Unit/lit.site.cfg
+  ${CMAKE_CURRENT_SOURCE_DIR}/Unit/lit.site.cfg.py.in
+  ${CMAKE_CURRENT_BINARY_DIR}/Unit/lit.site.cfg.py
   )
 
 option(CLANG_TOOLS_TEST_USE_VG "Run Clang tools' tests under Valgrind" OFF)


Index: clang-tools-extra/test/CMakeLists.txt
===
--- clang-tools-extra/test/CMakeLists.txt
+++ clang-tools-extra/test/CMakeLists.txt
@@ -20,13 +20,13 @@
   CLANGD_BUILD_XPC_SUPPORT)
 
 configure_lit_site_cfg(
-  ${CMAKE_CURRENT_SOURCE_DIR}/lit.site.cfg.in
-  ${CMAKE_CURRENT_BINARY_DIR}/lit.site.cfg
+  ${CMAKE_CURRENT_SOURCE_DIR}/lit.site.cfg.py.in
+  ${CMAKE_CURRENT_BINARY_DIR}/lit.site.cfg.py
   )
 
 configure_lit_site_cfg(
-  ${CMAKE_CURRENT_SOURCE_DIR}/Unit/lit.site.cfg.in
-  ${CMAKE_CURRENT_BINARY_DIR}/Unit/lit.site.cfg
+  ${CMAKE_CURRENT_SOURCE_DIR}/Unit/lit.site.cfg.py.in
+  ${CMAKE_CURRENT_BINARY_DIR}/Unit/lit.site.cfg.py
   )
 
 option(CLANG_TOOLS_TEST_USE_VG "Run Clang tools' tests under Valgrind" OFF)
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D59953: Rename clang-tools-extra lit cfg files to lit.site.cfg.py

2019-03-28 Thread Nico Weber via Phabricator via cfe-commits
thakis added a comment.

Actually, let me rename lit.cfg to lit.cfg.py too, one sec...


CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D59953/new/

https://reviews.llvm.org/D59953



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


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

2019-03-28 Thread Nick Renieris via Phabricator via cfe-commits
VelocityRa added inline comments.



Comment at: lib/Format/WhitespaceManager.cpp:520
+
+  AlignMacroSequence(StartOfSequence, EndOfSequence, MinColumn, MaxColumn,
+ FoundMatchOnLine, AlignMacrosMatches, Changes);

klimek wrote:
> Why are we calling AlignMacroSequence(0, 0, ...) here?
Wasn't needed apparently.



Comment at: lib/Format/WhitespaceManager.cpp:524
+  unsigned I = 0;
+  for (unsigned E = Changes.size(); I != E; ++I) {
+if (Changes[I].NewlinesBefore != 0) {

klimek wrote:
> I still think the code in this loop either needs significantly more comments 
> to explain what's going on, or needs to be changed to be more straight 
> forward:
> What I don't understand is why we're calling AlignMacroSequence potentially 
> multiple times, and especially what things like the if in line 541 are for.
That `if` and surrounding logic also exists and is copied from `AlignTokens` 
and it's not documented there.
Anyway, apparently the extra `AlignMacroSequence` in this loop could be 
removed. I tried iteratively removing/tweaking other snippets like the `if` and 
tests failed.


CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D28462/new/

https://reviews.llvm.org/D28462



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


  1   2   >