[PATCH] D95877: [analyzer] Fix static_cast on pointer-to-member handling

2021-02-08 Thread Valeriy Savchenko via Phabricator via cfe-commits
vsavchenko added a comment.

In D95877#2547303 , @RedDocMD wrote:

> @vsavchenko are there some more changes you want done?

I think we had a bit of misunderstanding about the test.  It still should pass 
(we can't have broken tests, it will disrupt CI bots).  Try to put the test 
case, so it is THERE and you CHANGE the expected outcome when the analyzer 
behaves correctly.  Right now, as I see above, the test crashes.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D95877

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


[PATCH] D95369: [clang][cli] Generate and round-trip analyzer options

2021-02-08 Thread Jan Svoboda via Phabricator via cfe-commits
This revision was landed with ongoing or failed builds.
This revision was automatically updated to reflect the committed changes.
Closed by commit rG0e07383433d0: [clang][cli] Generate and round-trip analyzer 
options (authored by jansvoboda11).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D95369

Files:
  clang/include/clang/Driver/Options.td
  clang/lib/Frontend/CompilerInvocation.cpp

Index: clang/lib/Frontend/CompilerInvocation.cpp
===
--- clang/lib/Frontend/CompilerInvocation.cpp
+++ clang/lib/Frontend/CompilerInvocation.cpp
@@ -760,9 +760,121 @@
   Funcs.insert(Funcs.end(), Values.begin(), Values.end());
 }
 
-static bool ParseAnalyzerArgs(AnalyzerOptions &Opts, ArgList &Args,
-  DiagnosticsEngine &Diags) {
+static void GenerateAnalyzerArgs(AnalyzerOptions &Opts,
+ SmallVectorImpl &Args,
+ CompilerInvocation::StringAllocator SA) {
+  const AnalyzerOptions *AnalyzerOpts = &Opts;
+
+#define ANALYZER_OPTION_WITH_MARSHALLING(  \
+PREFIX_TYPE, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM,\
+HELPTEXT, METAVAR, VALUES, SPELLING, SHOULD_PARSE, ALWAYS_EMIT, KEYPATH,   \
+DEFAULT_VALUE, IMPLIED_CHECK, IMPLIED_VALUE, NORMALIZER, DENORMALIZER, \
+MERGER, EXTRACTOR, TABLE_INDEX)\
+  GENERATE_OPTION_WITH_MARSHALLING(\
+  Args, SA, KIND, FLAGS, SPELLING, ALWAYS_EMIT, KEYPATH, DEFAULT_VALUE,\
+  IMPLIED_CHECK, IMPLIED_VALUE, DENORMALIZER, EXTRACTOR, TABLE_INDEX)
+#include "clang/Driver/Options.inc"
+#undef ANALYZER_OPTION_WITH_MARSHALLING
+
+  if (Opts.AnalysisStoreOpt != RegionStoreModel) {
+switch (Opts.AnalysisStoreOpt) {
+#define ANALYSIS_STORE(NAME, CMDFLAG, DESC, CREATFN)   \
+  case NAME##Model:\
+GenerateArg(Args, OPT_analyzer_store, CMDFLAG, SA);\
+break;
+#include "clang/StaticAnalyzer/Core/Analyses.def"
+default:
+  llvm_unreachable("Tried to generate unknown analysis store.");
+}
+  }
+
+  if (Opts.AnalysisConstraintsOpt != RangeConstraintsModel) {
+switch (Opts.AnalysisConstraintsOpt) {
+#define ANALYSIS_CONSTRAINTS(NAME, CMDFLAG, DESC, CREATFN) \
+  case NAME##Model:\
+GenerateArg(Args, OPT_analyzer_constraints, CMDFLAG, SA);  \
+break;
+#include "clang/StaticAnalyzer/Core/Analyses.def"
+default:
+  llvm_unreachable("Tried to generate unknown analysis constraint.");
+}
+  }
+
+  if (Opts.AnalysisDiagOpt != PD_HTML) {
+switch (Opts.AnalysisDiagOpt) {
+#define ANALYSIS_DIAGNOSTICS(NAME, CMDFLAG, DESC, CREATFN) \
+  case PD_##NAME:  \
+GenerateArg(Args, OPT_analyzer_output, CMDFLAG, SA);   \
+break;
+#include "clang/StaticAnalyzer/Core/Analyses.def"
+default:
+  llvm_unreachable("Tried to generate unknown analysis diagnostic client.");
+}
+  }
+
+  if (Opts.AnalysisPurgeOpt != PurgeStmt) {
+switch (Opts.AnalysisPurgeOpt) {
+#define ANALYSIS_PURGE(NAME, CMDFLAG, DESC)\
+  case NAME:   \
+GenerateArg(Args, OPT_analyzer_purge, CMDFLAG, SA);\
+break;
+#include "clang/StaticAnalyzer/Core/Analyses.def"
+default:
+  llvm_unreachable("Tried to generate unknown analysis purge mode.");
+}
+  }
+
+  if (Opts.InliningMode != NoRedundancy) {
+switch (Opts.InliningMode) {
+#define ANALYSIS_INLINING_MODE(NAME, CMDFLAG, DESC)\
+  case NAME:   \
+GenerateArg(Args, OPT_analyzer_inlining_mode, CMDFLAG, SA);\
+break;
+#include "clang/StaticAnalyzer/Core/Analyses.def"
+default:
+  llvm_unreachable("Tried to generate unknown analysis inlining mode.");
+}
+  }
+
+  for (const auto &CP : Opts.CheckersAndPackages) {
+OptSpecifier Opt =
+CP.second ? OPT_analyzer_checker : OPT_analyzer_disable_checker;
+GenerateArg(Args, Opt, CP.first, SA);
+  }
+
+  AnalyzerOptions ConfigOpts;
+  parseAnalyzerConfigs(ConfigOpts, nullptr);
+
+  for (const auto &C : Opts.Config) {
+// Don't generate anything that came from parseAnalyzerConfigs. It would be
+// redundant and may not be valid on the command line.
+auto Entry = ConfigOpts.Config.find(C.getKey());
+if (Entry != ConfigOpts.Config.end() && Entry->getValue() == C.getValue())
+  continue;
+
+GenerateA

[clang] 0e07383 - [clang][cli] Generate and round-trip analyzer options

2021-02-08 Thread Jan Svoboda via cfe-commits

Author: Jan Svoboda
Date: 2021-02-08T09:26:01+01:00
New Revision: 0e07383433d0edc1f53410ce42fae437e1a8f967

URL: 
https://github.com/llvm/llvm-project/commit/0e07383433d0edc1f53410ce42fae437e1a8f967
DIFF: 
https://github.com/llvm/llvm-project/commit/0e07383433d0edc1f53410ce42fae437e1a8f967.diff

LOG: [clang][cli] Generate and round-trip analyzer options

This patch implements generation of remaining analyzer options and tests it by 
performing parse-generate-parse round trip.

Reviewed By: dexonsmith

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

Added: 


Modified: 
clang/include/clang/Driver/Options.td
clang/lib/Frontend/CompilerInvocation.cpp

Removed: 




diff  --git a/clang/include/clang/Driver/Options.td 
b/clang/include/clang/Driver/Options.td
index 7bd9a8ab40dc8..cbd501ca2a74b 100644
--- a/clang/include/clang/Driver/Options.td
+++ b/clang/include/clang/Driver/Options.td
@@ -262,7 +262,7 @@ class PreprocessorOpts
 class FileSystemOpts
   : KeyPathAndMacro<"FileSystemOpts.", base> {}
 class AnalyzerOpts
-  : KeyPathAndMacro<"AnalyzerOpts->", base> {}
+  : KeyPathAndMacro<"AnalyzerOpts->", base, "ANALYZER_"> {}
 class MigratorOpts
   : KeyPathAndMacro<"MigratorOpts.", base> {}
 

diff  --git a/clang/lib/Frontend/CompilerInvocation.cpp 
b/clang/lib/Frontend/CompilerInvocation.cpp
index 0a12705a92610..f93f10cf0988b 100644
--- a/clang/lib/Frontend/CompilerInvocation.cpp
+++ b/clang/lib/Frontend/CompilerInvocation.cpp
@@ -760,9 +760,121 @@ static void getAllNoBuiltinFuncValues(ArgList &Args,
   Funcs.insert(Funcs.end(), Values.begin(), Values.end());
 }
 
-static bool ParseAnalyzerArgs(AnalyzerOptions &Opts, ArgList &Args,
-  DiagnosticsEngine &Diags) {
+static void GenerateAnalyzerArgs(AnalyzerOptions &Opts,
+ SmallVectorImpl &Args,
+ CompilerInvocation::StringAllocator SA) {
+  const AnalyzerOptions *AnalyzerOpts = &Opts;
+
+#define ANALYZER_OPTION_WITH_MARSHALLING(  
\
+PREFIX_TYPE, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM,
\
+HELPTEXT, METAVAR, VALUES, SPELLING, SHOULD_PARSE, ALWAYS_EMIT, KEYPATH,   
\
+DEFAULT_VALUE, IMPLIED_CHECK, IMPLIED_VALUE, NORMALIZER, DENORMALIZER, 
\
+MERGER, EXTRACTOR, TABLE_INDEX)
\
+  GENERATE_OPTION_WITH_MARSHALLING(
\
+  Args, SA, KIND, FLAGS, SPELLING, ALWAYS_EMIT, KEYPATH, DEFAULT_VALUE,
\
+  IMPLIED_CHECK, IMPLIED_VALUE, DENORMALIZER, EXTRACTOR, TABLE_INDEX)
+#include "clang/Driver/Options.inc"
+#undef ANALYZER_OPTION_WITH_MARSHALLING
+
+  if (Opts.AnalysisStoreOpt != RegionStoreModel) {
+switch (Opts.AnalysisStoreOpt) {
+#define ANALYSIS_STORE(NAME, CMDFLAG, DESC, CREATFN)   
\
+  case NAME##Model:
\
+GenerateArg(Args, OPT_analyzer_store, CMDFLAG, SA);
\
+break;
+#include "clang/StaticAnalyzer/Core/Analyses.def"
+default:
+  llvm_unreachable("Tried to generate unknown analysis store.");
+}
+  }
+
+  if (Opts.AnalysisConstraintsOpt != RangeConstraintsModel) {
+switch (Opts.AnalysisConstraintsOpt) {
+#define ANALYSIS_CONSTRAINTS(NAME, CMDFLAG, DESC, CREATFN) 
\
+  case NAME##Model:
\
+GenerateArg(Args, OPT_analyzer_constraints, CMDFLAG, SA);  
\
+break;
+#include "clang/StaticAnalyzer/Core/Analyses.def"
+default:
+  llvm_unreachable("Tried to generate unknown analysis constraint.");
+}
+  }
+
+  if (Opts.AnalysisDiagOpt != PD_HTML) {
+switch (Opts.AnalysisDiagOpt) {
+#define ANALYSIS_DIAGNOSTICS(NAME, CMDFLAG, DESC, CREATFN) 
\
+  case PD_##NAME:  
\
+GenerateArg(Args, OPT_analyzer_output, CMDFLAG, SA);   
\
+break;
+#include "clang/StaticAnalyzer/Core/Analyses.def"
+default:
+  llvm_unreachable("Tried to generate unknown analysis diagnostic 
client.");
+}
+  }
+
+  if (Opts.AnalysisPurgeOpt != PurgeStmt) {
+switch (Opts.AnalysisPurgeOpt) {
+#define ANALYSIS_PURGE(NAME, CMDFLAG, DESC)
\
+  case NAME:   
\
+GenerateArg(Args, OPT_analyzer_purge, CMDFLAG, SA);
\
+break;
+#include "clang/StaticAnalyzer/Core/Analyses.def"
+default:
+  llvm_unreachable("Tried to generate unknown analysis purge mode.");
+}
+  }
+
+  if (Opts.InliningMode != NoRedundancy) {
+switch (Opts.InliningMode) {
+#define ANALYSIS_INLINING_MODE(NAME, CMDFLAG, DESC)
\
+  case NAME:

[PATCH] D96246: Make sure a module file with errors produced via '-fallow-pcm-with-compiler-errors' can be loaded when using implicit modules

2021-02-08 Thread Argyrios Kyrtzidis via Phabricator via cfe-commits
akyrtzi created this revision.
akyrtzi requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

A module with errors would be marked as out-of-date, then the `compilerModule` 
action would produce it, but due to the error it would be treated as failure 
and the resulting PCM would not get used.

rdar://74087062


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D96246

Files:
  clang/include/clang/Serialization/ASTReader.h
  clang/lib/Frontend/CompilerInstance.cpp
  clang/lib/Serialization/ASTReader.cpp
  clang/test/Modules/load-module-with-errors.m

Index: clang/test/Modules/load-module-with-errors.m
===
--- clang/test/Modules/load-module-with-errors.m
+++ clang/test/Modules/load-module-with-errors.m
@@ -1,3 +1,14 @@
+// Note: the run lines follow their respective tests, since line/column
+// matter in this test.
+
+// pcherror-error@* {{PCH file contains compiler errors}}
+@import error; // notallowerror-error {{could not build module 'error'}}
+// expected-no-diagnostics
+
+void test(Error *x) {
+  [x method];
+}
+
 // RUN: rm -rf %t
 // RUN: mkdir %t
 // RUN: mkdir %t/prebuilt
@@ -48,21 +59,27 @@
 // the verify would fail as it would be the PCH error instead)
 // RUN: %clang_cc1 -fsyntax-only -fmodules \
 // RUN:   -fmodules-cache-path=%t -fimplicit-module-maps -I %S/Inputs/error \
-// RUN:   -x objective-c -verify %s
+// RUN:   -x objective-c -verify=notallowerror %s
 
 // allow-pcm-with-compiler-errors should also allow errors in PCH
 // RUN: %clang_cc1 -fallow-pcm-with-compiler-errors -x objective-c \
 // RUN:   -o %t/check.pch -emit-pch %S/Inputs/error/error.h
 
-// pcherror-error@* {{PCH file contains compiler errors}}
-@import error; // expected-error {{could not build module 'error'}}
-
-void test(Error *x) {
-  [x method];
-}
-
 // CHECK: @interface Error
 // CHECK-NEXT: - (int)method;
 // CHECK-NEXT: - (id)method2;
 // CHECK-NEXT: @end
 // CHECK: void test(Error *x)
+
+// RUN: c-index-test -code-completion-at=%s:9:6 %s -fmodules -fmodules-cache-path=%t \
+// RUN:   -Xclang -fallow-pcm-with-compiler-errors -I %S/Inputs/error | FileCheck -check-prefix=COMPLETE %s
+// COMPLETE: ObjCInstanceMethodDecl:{ResultType int}{TypedText method}
+// COMPLETE: ObjCInstanceMethodDecl:{ResultType id}{TypedText method2}
+
+// RUN: c-index-test -test-load-source local %s -fmodules -fmodules-cache-path=%t \
+// RUN:   -Xclang -fallow-pcm-with-compiler-errors -I %S/Inputs/error | FileCheck -check-prefix=SOURCE %s
+// SOURCE: load-module-with-errors.m:8:6: FunctionDecl=test:8:6 (Definition) Extent=[8:1 - 10:2]
+// SOURCE: load-module-with-errors.m:8:18: ParmDecl=x:8:18 (Definition) Extent=[8:11 - 8:19]
+// SOURCE: load-module-with-errors.m:8:11: ObjCClassRef=Error:3:12 Extent=[8:11 - 8:16]
+// SOURCE: load-module-with-errors.m:8:21: CompoundStmt= Extent=[8:21 - 10:2]
+// SOURCE: load-module-with-errors.m:9:3: ObjCMessageExpr=method:4:8 Extent=[9:3 - 9:13]
Index: clang/lib/Serialization/ASTReader.cpp
===
--- clang/lib/Serialization/ASTReader.cpp
+++ clang/lib/Serialization/ASTReader.cpp
@@ -2751,8 +2751,9 @@
 
   bool hasErrors = Record[6];
   if (hasErrors && !DisableValidation) {
-// Always rebuild modules from the cache on an error
-if (F.Kind == MK_ImplicitModule)
+// If requested by the caller, mark modules on error as out-of-date.
+if (F.Kind == MK_ImplicitModule &&
+(ClientLoadCapabilities & ARR_TreatModuleWithErrorsAsOutOfDate))
   return OutOfDate;
 
 if (!AllowASTWithCompilerErrors) {
Index: clang/lib/Frontend/CompilerInstance.cpp
===
--- clang/lib/Frontend/CompilerInstance.cpp
+++ clang/lib/Frontend/CompilerInstance.cpp
@@ -1144,7 +1144,10 @@
   // module generation thread crashed.
   Instance.clearOutputFiles(/*EraseFiles=*/true);
 
-  return !Instance.getDiagnostics().hasErrorOccurred();
+  // If \p AllowPCMWithCompilerErrors is set return 'success' even if errors
+  // occurred.
+  return !Instance.getDiagnostics().hasErrorOccurred() ||
+ Instance.getFrontendOpts().AllowPCMWithCompilerErrors;
 }
 
 static const FileEntry *getPublicModuleMap(const FileEntry *File,
@@ -1697,10 +1700,11 @@
   // Try to load the module file. If we are not trying to load from the
   // module cache, we don't know how to rebuild modules.
   unsigned ARRFlags = Source == MS_ModuleCache
-  ? ASTReader::ARR_OutOfDate | ASTReader::ARR_Missing
-  : Source == MS_PrebuiltModulePath
-? 0
-: ASTReader::ARR_ConfigurationMismatch;
+  ? ASTReader::ARR_OutOfDate | ASTReader::ARR_Missing |
+ASTReader::ARR_TreatModuleWithErrorsAsOutOfDate
+

[clang] 0c42d87 - [clang][cli] Generate and round-trip preprocessor options

2021-02-08 Thread Jan Svoboda via cfe-commits

Author: Jan Svoboda
Date: 2021-02-08T09:34:55+01:00
New Revision: 0c42d87ea8e01f369d9cced7427a5ee0cca7574b

URL: 
https://github.com/llvm/llvm-project/commit/0c42d87ea8e01f369d9cced7427a5ee0cca7574b
DIFF: 
https://github.com/llvm/llvm-project/commit/0c42d87ea8e01f369d9cced7427a5ee0cca7574b.diff

LOG: [clang][cli] Generate and round-trip preprocessor options

This patch implements generation of remaining preprocessor options and tests it 
by performing parse-generate-parse round trip.

Reviewed By: dexonsmith

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

Added: 


Modified: 
clang/include/clang/Driver/Options.td
clang/lib/Frontend/CompilerInvocation.cpp

Removed: 




diff  --git a/clang/include/clang/Driver/Options.td 
b/clang/include/clang/Driver/Options.td
index cbd501ca2a74..49071a4c56d9 100644
--- a/clang/include/clang/Driver/Options.td
+++ b/clang/include/clang/Driver/Options.td
@@ -258,7 +258,7 @@ class CodeGenOpts
 class HeaderSearchOpts
   : KeyPathAndMacro<"HeaderSearchOpts->", base, "HEADER_SEARCH_"> {}
 class PreprocessorOpts
-  : KeyPathAndMacro<"PreprocessorOpts->", base> {}
+  : KeyPathAndMacro<"PreprocessorOpts->", base, "PREPROCESSOR_"> {}
 class FileSystemOpts
   : KeyPathAndMacro<"FileSystemOpts.", base> {}
 class AnalyzerOpts

diff  --git a/clang/lib/Frontend/CompilerInvocation.cpp 
b/clang/lib/Frontend/CompilerInvocation.cpp
index f93f10cf0988..8743da2b80ca 100644
--- a/clang/lib/Frontend/CompilerInvocation.cpp
+++ b/clang/lib/Frontend/CompilerInvocation.cpp
@@ -3122,9 +3122,96 @@ static bool 
isStrictlyPreprocessorAction(frontend::ActionKind Action) {
   llvm_unreachable("invalid frontend action");
 }
 
-static void ParsePreprocessorArgs(PreprocessorOptions &Opts, ArgList &Args,
-  DiagnosticsEngine &Diags,
-  frontend::ActionKind Action) {
+static void GeneratePreprocessorArgs(PreprocessorOptions &Opts,
+ SmallVectorImpl &Args,
+ CompilerInvocation::StringAllocator SA,
+ const LangOptions &LangOpts,
+ const FrontendOptions &FrontendOpts,
+ const CodeGenOptions &CodeGenOpts) {
+  PreprocessorOptions *PreprocessorOpts = &Opts;
+
+#define PREPROCESSOR_OPTION_WITH_MARSHALLING(  
\
+PREFIX_TYPE, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM,
\
+HELPTEXT, METAVAR, VALUES, SPELLING, SHOULD_PARSE, ALWAYS_EMIT, KEYPATH,   
\
+DEFAULT_VALUE, IMPLIED_CHECK, IMPLIED_VALUE, NORMALIZER, DENORMALIZER, 
\
+MERGER, EXTRACTOR, TABLE_INDEX)
\
+  GENERATE_OPTION_WITH_MARSHALLING(
\
+  Args, SA, KIND, FLAGS, SPELLING, ALWAYS_EMIT, KEYPATH, DEFAULT_VALUE,
\
+  IMPLIED_CHECK, IMPLIED_VALUE, DENORMALIZER, EXTRACTOR, TABLE_INDEX)
+#include "clang/Driver/Options.inc"
+#undef PREPROCESSOR_OPTION_WITH_MARSHALLING
+
+  if (Opts.PCHWithHdrStop && !Opts.PCHWithHdrStopCreate)
+GenerateArg(Args, OPT_pch_through_hdrstop_use, SA);
+
+  for (const auto &D : Opts.DeserializedPCHDeclsToErrorOn)
+GenerateArg(Args, OPT_error_on_deserialized_pch_decl, D, SA);
+
+  for (const auto &MP : Opts.MacroPrefixMap)
+GenerateArg(Args, OPT_fmacro_prefix_map_EQ, MP.first + "=" + MP.second, 
SA);
+
+  if (Opts.PrecompiledPreambleBytes != std::make_pair(0u, false))
+GenerateArg(Args, OPT_preamble_bytes_EQ,
+Twine(Opts.PrecompiledPreambleBytes.first) + "," +
+(Opts.PrecompiledPreambleBytes.second ? "1" : "0"),
+SA);
+
+  for (const auto &M : Opts.Macros) {
+// Don't generate __CET__ macro definitions. They are implied by the
+// -fcf-protection option that is generated elsewhere.
+if (M.first == "__CET__=1" && !M.second &&
+!CodeGenOpts.CFProtectionReturn && CodeGenOpts.CFProtectionBranch)
+  continue;
+if (M.first == "__CET__=2" && !M.second && CodeGenOpts.CFProtectionReturn 
&&
+!CodeGenOpts.CFProtectionBranch)
+  continue;
+if (M.first == "__CET__=3" && !M.second && CodeGenOpts.CFProtectionReturn 
&&
+CodeGenOpts.CFProtectionBranch)
+  continue;
+
+GenerateArg(Args, M.second ? OPT_U : OPT_D, M.first, SA);
+  }
+
+  for (const auto &I : Opts.Includes) {
+// Don't generate OpenCL includes. They are implied by other flags that are
+// generated elsewhere.
+if (LangOpts.OpenCL && LangOpts.IncludeDefaultHeader &&
+((LangOpts.DeclareOpenCLBuiltins && I == "opencl-c-base.h") ||
+ I == "opencl-c.h"))
+  continue;
+
+GenerateArg(Args, OPT_include, I, SA);
+  }
+
+  for (const auto &CI : Opts.ChainedIncludes)
+GenerateArg(Args, OPT_chain_include, CI, SA);
+
+  for (const 

[PATCH] D95366: [clang][cli] Generate and round-trip preprocessor options

2021-02-08 Thread Jan Svoboda via Phabricator via cfe-commits
This revision was landed with ongoing or failed builds.
This revision was automatically updated to reflect the committed changes.
Closed by commit rG0c42d87ea8e0: [clang][cli] Generate and round-trip 
preprocessor options (authored by jansvoboda11).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D95366

Files:
  clang/include/clang/Driver/Options.td
  clang/lib/Frontend/CompilerInvocation.cpp

Index: clang/lib/Frontend/CompilerInvocation.cpp
===
--- clang/lib/Frontend/CompilerInvocation.cpp
+++ clang/lib/Frontend/CompilerInvocation.cpp
@@ -3122,9 +3122,96 @@
   llvm_unreachable("invalid frontend action");
 }
 
-static void ParsePreprocessorArgs(PreprocessorOptions &Opts, ArgList &Args,
-  DiagnosticsEngine &Diags,
-  frontend::ActionKind Action) {
+static void GeneratePreprocessorArgs(PreprocessorOptions &Opts,
+ SmallVectorImpl &Args,
+ CompilerInvocation::StringAllocator SA,
+ const LangOptions &LangOpts,
+ const FrontendOptions &FrontendOpts,
+ const CodeGenOptions &CodeGenOpts) {
+  PreprocessorOptions *PreprocessorOpts = &Opts;
+
+#define PREPROCESSOR_OPTION_WITH_MARSHALLING(  \
+PREFIX_TYPE, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM,\
+HELPTEXT, METAVAR, VALUES, SPELLING, SHOULD_PARSE, ALWAYS_EMIT, KEYPATH,   \
+DEFAULT_VALUE, IMPLIED_CHECK, IMPLIED_VALUE, NORMALIZER, DENORMALIZER, \
+MERGER, EXTRACTOR, TABLE_INDEX)\
+  GENERATE_OPTION_WITH_MARSHALLING(\
+  Args, SA, KIND, FLAGS, SPELLING, ALWAYS_EMIT, KEYPATH, DEFAULT_VALUE,\
+  IMPLIED_CHECK, IMPLIED_VALUE, DENORMALIZER, EXTRACTOR, TABLE_INDEX)
+#include "clang/Driver/Options.inc"
+#undef PREPROCESSOR_OPTION_WITH_MARSHALLING
+
+  if (Opts.PCHWithHdrStop && !Opts.PCHWithHdrStopCreate)
+GenerateArg(Args, OPT_pch_through_hdrstop_use, SA);
+
+  for (const auto &D : Opts.DeserializedPCHDeclsToErrorOn)
+GenerateArg(Args, OPT_error_on_deserialized_pch_decl, D, SA);
+
+  for (const auto &MP : Opts.MacroPrefixMap)
+GenerateArg(Args, OPT_fmacro_prefix_map_EQ, MP.first + "=" + MP.second, SA);
+
+  if (Opts.PrecompiledPreambleBytes != std::make_pair(0u, false))
+GenerateArg(Args, OPT_preamble_bytes_EQ,
+Twine(Opts.PrecompiledPreambleBytes.first) + "," +
+(Opts.PrecompiledPreambleBytes.second ? "1" : "0"),
+SA);
+
+  for (const auto &M : Opts.Macros) {
+// Don't generate __CET__ macro definitions. They are implied by the
+// -fcf-protection option that is generated elsewhere.
+if (M.first == "__CET__=1" && !M.second &&
+!CodeGenOpts.CFProtectionReturn && CodeGenOpts.CFProtectionBranch)
+  continue;
+if (M.first == "__CET__=2" && !M.second && CodeGenOpts.CFProtectionReturn &&
+!CodeGenOpts.CFProtectionBranch)
+  continue;
+if (M.first == "__CET__=3" && !M.second && CodeGenOpts.CFProtectionReturn &&
+CodeGenOpts.CFProtectionBranch)
+  continue;
+
+GenerateArg(Args, M.second ? OPT_U : OPT_D, M.first, SA);
+  }
+
+  for (const auto &I : Opts.Includes) {
+// Don't generate OpenCL includes. They are implied by other flags that are
+// generated elsewhere.
+if (LangOpts.OpenCL && LangOpts.IncludeDefaultHeader &&
+((LangOpts.DeclareOpenCLBuiltins && I == "opencl-c-base.h") ||
+ I == "opencl-c.h"))
+  continue;
+
+GenerateArg(Args, OPT_include, I, SA);
+  }
+
+  for (const auto &CI : Opts.ChainedIncludes)
+GenerateArg(Args, OPT_chain_include, CI, SA);
+
+  for (const auto &RF : Opts.RemappedFiles)
+GenerateArg(Args, OPT_remap_file, RF.first + ";" + RF.second, SA);
+
+  // Don't handle LexEditorPlaceholders. It is implied by the action that is
+  // generated elsewhere.
+}
+
+static bool ParsePreprocessorArgsImpl(PreprocessorOptions &Opts, ArgList &Args,
+  DiagnosticsEngine &Diags,
+  frontend::ActionKind Action,
+  const FrontendOptions &FrontendOpts) {
+  PreprocessorOptions *PreprocessorOpts = &Opts;
+  bool Success = true;
+
+#define PREPROCESSOR_OPTION_WITH_MARSHALLING(  \
+PREFIX_TYPE, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM,\
+HELPTEXT, METAVAR, VALUES, SPELLING, SHOULD_PARSE, ALWAYS_EMIT, KEYPATH,   \
+DEFAULT_VALUE, IMPLIED_CHECK, IMPLIED_VALUE, NORMALIZER, DENORMALIZER, \
+MERGER, EXTRACTOR, TABLE_INDEX)\
+  PARSE_OP

[clang] c1b482e - [clang][index] Mark file as C++ in parse-all-comments test

2021-02-08 Thread Jan Svoboda via cfe-commits

Author: Jan Svoboda
Date: 2021-02-08T09:42:44+01:00
New Revision: c1b482e726a943862ec5277a44c1994acfb7f97f

URL: 
https://github.com/llvm/llvm-project/commit/c1b482e726a943862ec5277a44c1994acfb7f97f
DIFF: 
https://github.com/llvm/llvm-project/commit/c1b482e726a943862ec5277a44c1994acfb7f97f.diff

LOG: [clang][index] Mark file as C++ in parse-all-comments test

`CompilerInvocation::CreateFromArgs` doesn't always report command line parsing 
failures through the return value. Sometimes, errors are only reported via 
diagnostics.

Some clients like `c-index-test` only check the return value and don't check 
the state of `DiagnosticsEngine`.

If we were to start returning the correct return value from `CreateFromArgs`, 
this index test starts to fail, because it specifies `-std=c++11` for a C 
input, which is invalid.

This patch fixes that issue by adding forgotten `-x c++` argument.

Reviewed By: dexonsmith

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

Added: 


Modified: 
clang/test/Index/parse-all-comments.c

Removed: 




diff  --git a/clang/test/Index/parse-all-comments.c 
b/clang/test/Index/parse-all-comments.c
index 66981e2b421b..e199b03acd3a 100644
--- a/clang/test/Index/parse-all-comments.c
+++ b/clang/test/Index/parse-all-comments.c
@@ -75,7 +75,7 @@ int trdoxyO;
 
 // RUN: c-index-test -write-pch %t/out.pch -fparse-all-comments -x c++ 
-std=c++11 %s
 
-// RUN: c-index-test -test-load-source all 
-comments-xml-schema=%S/../../bindings/xml/comment-xml-schema.rng %s -std=c++11 
-fparse-all-comments > %t/out.c-index-direct
+// RUN: c-index-test -test-load-source all 
-comments-xml-schema=%S/../../bindings/xml/comment-xml-schema.rng -x c++ 
-std=c++11 %s -fparse-all-comments > %t/out.c-index-direct
 // RUN: c-index-test -test-load-tu %t/out.pch all > %t/out.c-index-pch
 
 // RUN: FileCheck %s -check-prefix=WRONG < %t/out.c-index-direct



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


[PATCH] D95879: [clang][index] Mark file as C++ in parse-all-comments test

2021-02-08 Thread Jan Svoboda via Phabricator via cfe-commits
This revision was landed with ongoing or failed builds.
This revision was automatically updated to reflect the committed changes.
Closed by commit rGc1b482e726a9: [clang][index] Mark file as C++ in 
parse-all-comments test (authored by jansvoboda11).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D95879

Files:
  clang/test/Index/parse-all-comments.c


Index: clang/test/Index/parse-all-comments.c
===
--- clang/test/Index/parse-all-comments.c
+++ clang/test/Index/parse-all-comments.c
@@ -75,7 +75,7 @@
 
 // RUN: c-index-test -write-pch %t/out.pch -fparse-all-comments -x c++ 
-std=c++11 %s
 
-// RUN: c-index-test -test-load-source all 
-comments-xml-schema=%S/../../bindings/xml/comment-xml-schema.rng %s -std=c++11 
-fparse-all-comments > %t/out.c-index-direct
+// RUN: c-index-test -test-load-source all 
-comments-xml-schema=%S/../../bindings/xml/comment-xml-schema.rng -x c++ 
-std=c++11 %s -fparse-all-comments > %t/out.c-index-direct
 // RUN: c-index-test -test-load-tu %t/out.pch all > %t/out.c-index-pch
 
 // RUN: FileCheck %s -check-prefix=WRONG < %t/out.c-index-direct


Index: clang/test/Index/parse-all-comments.c
===
--- clang/test/Index/parse-all-comments.c
+++ clang/test/Index/parse-all-comments.c
@@ -75,7 +75,7 @@
 
 // RUN: c-index-test -write-pch %t/out.pch -fparse-all-comments -x c++ -std=c++11 %s
 
-// RUN: c-index-test -test-load-source all -comments-xml-schema=%S/../../bindings/xml/comment-xml-schema.rng %s -std=c++11 -fparse-all-comments > %t/out.c-index-direct
+// RUN: c-index-test -test-load-source all -comments-xml-schema=%S/../../bindings/xml/comment-xml-schema.rng -x c++ -std=c++11 %s -fparse-all-comments > %t/out.c-index-direct
 // RUN: c-index-test -test-load-tu %t/out.pch all > %t/out.c-index-pch
 
 // RUN: FileCheck %s -check-prefix=WRONG < %t/out.c-index-direct
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D96247: [clangd] Fix false positive in local rename collision detetction

2021-02-08 Thread Kirill Bobyrev via Phabricator via cfe-commits
kbobyrev created this revision.
kbobyrev added a reviewer: hokein.
Herald added subscribers: usaxena95, kadircet, arphaman.
kbobyrev requested review of this revision.
Herald added subscribers: cfe-commits, MaskRay, ilya-biryukov.
Herald added a project: clang.

Fixes https://github.com/clangd/clangd/issues/685


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D96247

Files:
  clang-tools-extra/clangd/refactor/Rename.cpp
  clang-tools-extra/clangd/unittests/RenameTests.cpp


Index: clang-tools-extra/clangd/unittests/RenameTests.cpp
===
--- clang-tools-extra/clangd/unittests/RenameTests.cpp
+++ clang-tools-extra/clangd/unittests/RenameTests.cpp
@@ -1083,12 +1083,23 @@
"conflict", !HeaderFile, nullptr, "Conflict"},
 
   {R"cpp(
+void func(int Var);
+
 void func(int V^ar) {
   bool Conflict;
 }
   )cpp",
"conflict", !HeaderFile, nullptr, "Conflict"},
 
+  {R"cpp(//No conflict: only forward declaration's argument is renamed.
+void func(int [[V^ar]]);
+
+void func(int Var) {
+  bool Conflict;
+}
+  )cpp",
+   nullptr, !HeaderFile, nullptr, "Conflict"},
+
   {R"cpp(
 void func(int V^ar, int Conflict) {
 }
Index: clang-tools-extra/clangd/refactor/Rename.cpp
===
--- clang-tools-extra/clangd/refactor/Rename.cpp
+++ clang-tools-extra/clangd/refactor/Rename.cpp
@@ -421,6 +421,11 @@
 for (const auto *Parameter : EnclosingFunction->parameters())
   if (Parameter != &RenamedDecl && Parameter->getName() == NewName)
 return Parameter;
+// FIXME: We don't modify all references to function parameters when
+// renaming from forward declaration now, so using a name colliding with
+// something in the definition's body is a valid transformation.
+if (!EnclosingFunction->isThisDeclarationADefinition())
+  return nullptr;
 return CheckCompoundStmt(EnclosingFunction->getBody(), NewName);
   }
 


Index: clang-tools-extra/clangd/unittests/RenameTests.cpp
===
--- clang-tools-extra/clangd/unittests/RenameTests.cpp
+++ clang-tools-extra/clangd/unittests/RenameTests.cpp
@@ -1083,12 +1083,23 @@
"conflict", !HeaderFile, nullptr, "Conflict"},
 
   {R"cpp(
+void func(int Var);
+
 void func(int V^ar) {
   bool Conflict;
 }
   )cpp",
"conflict", !HeaderFile, nullptr, "Conflict"},
 
+  {R"cpp(//No conflict: only forward declaration's argument is renamed.
+void func(int [[V^ar]]);
+
+void func(int Var) {
+  bool Conflict;
+}
+  )cpp",
+   nullptr, !HeaderFile, nullptr, "Conflict"},
+
   {R"cpp(
 void func(int V^ar, int Conflict) {
 }
Index: clang-tools-extra/clangd/refactor/Rename.cpp
===
--- clang-tools-extra/clangd/refactor/Rename.cpp
+++ clang-tools-extra/clangd/refactor/Rename.cpp
@@ -421,6 +421,11 @@
 for (const auto *Parameter : EnclosingFunction->parameters())
   if (Parameter != &RenamedDecl && Parameter->getName() == NewName)
 return Parameter;
+// FIXME: We don't modify all references to function parameters when
+// renaming from forward declaration now, so using a name colliding with
+// something in the definition's body is a valid transformation.
+if (!EnclosingFunction->isThisDeclarationADefinition())
+  return nullptr;
 return CheckCompoundStmt(EnclosingFunction->getBody(), NewName);
   }
 
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D96247: [clangd] Fix false positive in local rename collision detetction

2021-02-08 Thread Kirill Bobyrev via Phabricator via cfe-commits
kbobyrev updated this revision to Diff 322045.
kbobyrev added a comment.

Fix comment formatting in the test.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D96247

Files:
  clang-tools-extra/clangd/refactor/Rename.cpp
  clang-tools-extra/clangd/unittests/RenameTests.cpp


Index: clang-tools-extra/clangd/unittests/RenameTests.cpp
===
--- clang-tools-extra/clangd/unittests/RenameTests.cpp
+++ clang-tools-extra/clangd/unittests/RenameTests.cpp
@@ -1083,12 +1083,23 @@
"conflict", !HeaderFile, nullptr, "Conflict"},
 
   {R"cpp(
+void func(int Var);
+
 void func(int V^ar) {
   bool Conflict;
 }
   )cpp",
"conflict", !HeaderFile, nullptr, "Conflict"},
 
+  {R"cpp(// No conflict: only forward declaration's argument is renamed.
+void func(int [[V^ar]]);
+
+void func(int Var) {
+  bool Conflict;
+}
+  )cpp",
+   nullptr, !HeaderFile, nullptr, "Conflict"},
+
   {R"cpp(
 void func(int V^ar, int Conflict) {
 }
Index: clang-tools-extra/clangd/refactor/Rename.cpp
===
--- clang-tools-extra/clangd/refactor/Rename.cpp
+++ clang-tools-extra/clangd/refactor/Rename.cpp
@@ -421,6 +421,11 @@
 for (const auto *Parameter : EnclosingFunction->parameters())
   if (Parameter != &RenamedDecl && Parameter->getName() == NewName)
 return Parameter;
+// FIXME: We don't modify all references to function parameters when
+// renaming from forward declaration now, so using a name colliding with
+// something in the definition's body is a valid transformation.
+if (!EnclosingFunction->isThisDeclarationADefinition())
+  return nullptr;
 return CheckCompoundStmt(EnclosingFunction->getBody(), NewName);
   }
 


Index: clang-tools-extra/clangd/unittests/RenameTests.cpp
===
--- clang-tools-extra/clangd/unittests/RenameTests.cpp
+++ clang-tools-extra/clangd/unittests/RenameTests.cpp
@@ -1083,12 +1083,23 @@
"conflict", !HeaderFile, nullptr, "Conflict"},
 
   {R"cpp(
+void func(int Var);
+
 void func(int V^ar) {
   bool Conflict;
 }
   )cpp",
"conflict", !HeaderFile, nullptr, "Conflict"},
 
+  {R"cpp(// No conflict: only forward declaration's argument is renamed.
+void func(int [[V^ar]]);
+
+void func(int Var) {
+  bool Conflict;
+}
+  )cpp",
+   nullptr, !HeaderFile, nullptr, "Conflict"},
+
   {R"cpp(
 void func(int V^ar, int Conflict) {
 }
Index: clang-tools-extra/clangd/refactor/Rename.cpp
===
--- clang-tools-extra/clangd/refactor/Rename.cpp
+++ clang-tools-extra/clangd/refactor/Rename.cpp
@@ -421,6 +421,11 @@
 for (const auto *Parameter : EnclosingFunction->parameters())
   if (Parameter != &RenamedDecl && Parameter->getName() == NewName)
 return Parameter;
+// FIXME: We don't modify all references to function parameters when
+// renaming from forward declaration now, so using a name colliding with
+// something in the definition's body is a valid transformation.
+if (!EnclosingFunction->isThisDeclarationADefinition())
+  return nullptr;
 return CheckCompoundStmt(EnclosingFunction->getBody(), NewName);
   }
 
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D95877: [analyzer] Fix static_cast on pointer-to-member handling

2021-02-08 Thread Deep Majumder via Phabricator via cfe-commits
RedDocMD added a comment.

In D95877#2547949 , @vsavchenko wrote:

> I think we had a bit of misunderstanding about the test.  It still should 
> pass (we can't have broken tests, it will disrupt CI bots).  Try to put the 
> test case, so it is THERE and you CHANGE the expected outcome when the 
> analyzer behaves correctly.  Right now, as I see above, the test crashes.

Actually, that is the reason why I initially had commented out the crashing 
test. Until `reinterpret_cast` is properly handled, the test will crash due to 
an assertion failure, irrespective of what is put as the expected outcome. Is 
there a way to flag that a test should crash? (I see that after the tests are 
run, there is an expectedly-failed category). The crash is caused when the 
static analyzer tries to evaluate `base.*bf`.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D95877

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


[clang] bff6d9b - [clang][cli] Report result of ParseLangArgs

2021-02-08 Thread Jan Svoboda via cfe-commits

Author: Jan Svoboda
Date: 2021-02-08T09:56:33+01:00
New Revision: bff6d9bb0f6d382d1d1826e997a6104bbe5ade73

URL: 
https://github.com/llvm/llvm-project/commit/bff6d9bb0f6d382d1d1826e997a6104bbe5ade73
DIFF: 
https://github.com/llvm/llvm-project/commit/bff6d9bb0f6d382d1d1826e997a6104bbe5ade73.diff

LOG: [clang][cli] Report result of ParseLangArgs

This patch correctly reports success/failure of `ParseLangArgs`. Besides being 
consistent with  other `Parse` functions, this is required to make 
round-tripping of `LangOptions` work.

Reviewed By: dexonsmith

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

Added: 


Modified: 
clang/include/clang/Basic/Diagnostic.h
clang/include/clang/Frontend/CompilerInvocation.h
clang/lib/Frontend/CompilerInvocation.cpp

Removed: 




diff  --git a/clang/include/clang/Basic/Diagnostic.h 
b/clang/include/clang/Basic/Diagnostic.h
index 3499c551cfdf..a3cc3af5a74a 100644
--- a/clang/include/clang/Basic/Diagnostic.h
+++ b/clang/include/clang/Basic/Diagnostic.h
@@ -806,6 +806,7 @@ class DiagnosticsEngine : public 
RefCountedBase {
 return FatalErrorOccurred || UnrecoverableErrorOccurred;
   }
 
+  unsigned getNumErrors() const { return NumErrors; }
   unsigned getNumWarnings() const { return NumWarnings; }
 
   void setNumWarnings(unsigned NumWarnings) {

diff  --git a/clang/include/clang/Frontend/CompilerInvocation.h 
b/clang/include/clang/Frontend/CompilerInvocation.h
index 233569aa727b..e880713b71aa 100644
--- a/clang/include/clang/Frontend/CompilerInvocation.h
+++ b/clang/include/clang/Frontend/CompilerInvocation.h
@@ -249,7 +249,7 @@ class CompilerInvocation : public CompilerInvocationBase {
DiagnosticsEngine &Diags);
 
   /// Parse command line options that map to LangOptions.
-  static void ParseLangArgs(LangOptions &Opts, llvm::opt::ArgList &Args,
+  static bool ParseLangArgs(LangOptions &Opts, llvm::opt::ArgList &Args,
 InputKind IK, const llvm::Triple &T,
 std::vector &Includes,
 DiagnosticsEngine &Diags);

diff  --git a/clang/lib/Frontend/CompilerInvocation.cpp 
b/clang/lib/Frontend/CompilerInvocation.cpp
index 8743da2b80ca..3f8748f83ec0 100644
--- a/clang/lib/Frontend/CompilerInvocation.cpp
+++ b/clang/lib/Frontend/CompilerInvocation.cpp
@@ -2642,10 +2642,12 @@ static void GenerateLangArgs(const LangOptions &Opts,
 GenerateArg(Args, OPT_fdeclare_opencl_builtins, SA);
 }
 
-void CompilerInvocation::ParseLangArgs(LangOptions &Opts, ArgList &Args,
+bool CompilerInvocation::ParseLangArgs(LangOptions &Opts, ArgList &Args,
InputKind IK, const llvm::Triple &T,
std::vector &Includes,
DiagnosticsEngine &Diags) {
+  unsigned NumErrorsBefore = Diags.getNumErrors();
+
   // FIXME: Cleanup per-file based stuff.
   LangStandard::Kind LangStd = LangStandard::lang_unspecified;
   if (const Arg *A = Args.getLastArg(OPT_std_EQ)) {
@@ -3076,6 +3078,8 @@ void CompilerInvocation::ParseLangArgs(LangOptions &Opts, 
ArgList &Args,
   }
 }
   }
+
+  return Success && Diags.getNumErrors() == NumErrorsBefore;
 }
 
 static bool isStrictlyPreprocessorAction(frontend::ActionKind Action) {
@@ -3416,8 +3420,8 @@ bool 
CompilerInvocation::CreateFromArgs(CompilerInvocation &Res,
   } else {
 // Other LangOpts are only initialized when the input is not AST or LLVM 
IR.
 // FIXME: Should we really be calling this for an Language::Asm input?
-ParseLangArgs(LangOpts, Args, DashX, T, Res.getPreprocessorOpts().Includes,
-  Diags);
+Success &= ParseLangArgs(LangOpts, Args, DashX, T,
+ Res.getPreprocessorOpts().Includes, Diags);
 if (Res.getFrontendOpts().ProgramAction == frontend::RewriteObjC)
   LangOpts.ObjCExceptions = 1;
 if (T.isOSDarwin() && DashX.isPreprocessed()) {



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


[PATCH] D95792: [clang][cli] Report result of ParseLangArgs

2021-02-08 Thread Jan Svoboda via Phabricator via cfe-commits
This revision was landed with ongoing or failed builds.
This revision was automatically updated to reflect the committed changes.
Closed by commit rGbff6d9bb0f6d: [clang][cli] Report result of ParseLangArgs 
(authored by jansvoboda11).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D95792

Files:
  clang/include/clang/Basic/Diagnostic.h
  clang/include/clang/Frontend/CompilerInvocation.h
  clang/lib/Frontend/CompilerInvocation.cpp


Index: clang/lib/Frontend/CompilerInvocation.cpp
===
--- clang/lib/Frontend/CompilerInvocation.cpp
+++ clang/lib/Frontend/CompilerInvocation.cpp
@@ -2642,10 +2642,12 @@
 GenerateArg(Args, OPT_fdeclare_opencl_builtins, SA);
 }
 
-void CompilerInvocation::ParseLangArgs(LangOptions &Opts, ArgList &Args,
+bool CompilerInvocation::ParseLangArgs(LangOptions &Opts, ArgList &Args,
InputKind IK, const llvm::Triple &T,
std::vector &Includes,
DiagnosticsEngine &Diags) {
+  unsigned NumErrorsBefore = Diags.getNumErrors();
+
   // FIXME: Cleanup per-file based stuff.
   LangStandard::Kind LangStd = LangStandard::lang_unspecified;
   if (const Arg *A = Args.getLastArg(OPT_std_EQ)) {
@@ -3076,6 +3078,8 @@
   }
 }
   }
+
+  return Success && Diags.getNumErrors() == NumErrorsBefore;
 }
 
 static bool isStrictlyPreprocessorAction(frontend::ActionKind Action) {
@@ -3416,8 +3420,8 @@
   } else {
 // Other LangOpts are only initialized when the input is not AST or LLVM 
IR.
 // FIXME: Should we really be calling this for an Language::Asm input?
-ParseLangArgs(LangOpts, Args, DashX, T, Res.getPreprocessorOpts().Includes,
-  Diags);
+Success &= ParseLangArgs(LangOpts, Args, DashX, T,
+ Res.getPreprocessorOpts().Includes, Diags);
 if (Res.getFrontendOpts().ProgramAction == frontend::RewriteObjC)
   LangOpts.ObjCExceptions = 1;
 if (T.isOSDarwin() && DashX.isPreprocessed()) {
Index: clang/include/clang/Frontend/CompilerInvocation.h
===
--- clang/include/clang/Frontend/CompilerInvocation.h
+++ clang/include/clang/Frontend/CompilerInvocation.h
@@ -249,7 +249,7 @@
DiagnosticsEngine &Diags);
 
   /// Parse command line options that map to LangOptions.
-  static void ParseLangArgs(LangOptions &Opts, llvm::opt::ArgList &Args,
+  static bool ParseLangArgs(LangOptions &Opts, llvm::opt::ArgList &Args,
 InputKind IK, const llvm::Triple &T,
 std::vector &Includes,
 DiagnosticsEngine &Diags);
Index: clang/include/clang/Basic/Diagnostic.h
===
--- clang/include/clang/Basic/Diagnostic.h
+++ clang/include/clang/Basic/Diagnostic.h
@@ -806,6 +806,7 @@
 return FatalErrorOccurred || UnrecoverableErrorOccurred;
   }
 
+  unsigned getNumErrors() const { return NumErrors; }
   unsigned getNumWarnings() const { return NumWarnings; }
 
   void setNumWarnings(unsigned NumWarnings) {


Index: clang/lib/Frontend/CompilerInvocation.cpp
===
--- clang/lib/Frontend/CompilerInvocation.cpp
+++ clang/lib/Frontend/CompilerInvocation.cpp
@@ -2642,10 +2642,12 @@
 GenerateArg(Args, OPT_fdeclare_opencl_builtins, SA);
 }
 
-void CompilerInvocation::ParseLangArgs(LangOptions &Opts, ArgList &Args,
+bool CompilerInvocation::ParseLangArgs(LangOptions &Opts, ArgList &Args,
InputKind IK, const llvm::Triple &T,
std::vector &Includes,
DiagnosticsEngine &Diags) {
+  unsigned NumErrorsBefore = Diags.getNumErrors();
+
   // FIXME: Cleanup per-file based stuff.
   LangStandard::Kind LangStd = LangStandard::lang_unspecified;
   if (const Arg *A = Args.getLastArg(OPT_std_EQ)) {
@@ -3076,6 +3078,8 @@
   }
 }
   }
+
+  return Success && Diags.getNumErrors() == NumErrorsBefore;
 }
 
 static bool isStrictlyPreprocessorAction(frontend::ActionKind Action) {
@@ -3416,8 +3420,8 @@
   } else {
 // Other LangOpts are only initialized when the input is not AST or LLVM IR.
 // FIXME: Should we really be calling this for an Language::Asm input?
-ParseLangArgs(LangOpts, Args, DashX, T, Res.getPreprocessorOpts().Includes,
-  Diags);
+Success &= ParseLangArgs(LangOpts, Args, DashX, T,
+ Res.getPreprocessorOpts().Includes, Diags);
 if (Res.getFrontendOpts().ProgramAction == frontend::RewriteObjC)
   LangOpts.ObjCExceptions = 1;
 if (T.isOSDarwin() && DashX.isPreprocessed()) {
Index: clang/include/clang/Frontend/CompilerInvocation

[PATCH] D95877: [analyzer] Fix static_cast on pointer-to-member handling

2021-02-08 Thread Valeriy Savchenko via Phabricator via cfe-commits
vsavchenko added a comment.

In D95877#2548021 , @RedDocMD wrote:

> In D95877#2547949 , @vsavchenko 
> wrote:
>
>> I think we had a bit of misunderstanding about the test.  It still should 
>> pass (we can't have broken tests, it will disrupt CI bots).  Try to put the 
>> test case, so it is THERE and you CHANGE the expected outcome when the 
>> analyzer behaves correctly.  Right now, as I see above, the test crashes.
>
> Actually, that is the reason why I initially had commented out the crashing 
> test. Until `reinterpret_cast` is properly handled, the test will crash due 
> to an assertion failure, irrespective of what is put as the expected outcome. 
> Is there a way to flag that a test should crash? (I see that after the tests 
> are run, there is an expectedly-failed category). The crash is caused when 
> the static analyzer tries to evaluate `base.*bf`.

Yes, it'd be better to extract this case into a separate file and mark it as 
XFAIL


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D95877

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


[PATCH] D96114: [ASTMatchers] Fix parent-child traversal between functions and parms

2021-02-08 Thread Manuel Klimek via Phabricator via cfe-commits
klimek added a comment.

Can you explain the change and the before/after a bit more? Thanks!


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D96114

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


[clang] 6362398 - [clang][cli] NFC: Mirror CreateFromArgs order in generateCC1CommandLine

2021-02-08 Thread Jan Svoboda via cfe-commits

Author: Jan Svoboda
Date: 2021-02-08T10:12:51+01:00
New Revision: 63623982e1adb4b7e85f21d00d04dd2f555b79b6

URL: 
https://github.com/llvm/llvm-project/commit/63623982e1adb4b7e85f21d00d04dd2f555b79b6
DIFF: 
https://github.com/llvm/llvm-project/commit/63623982e1adb4b7e85f21d00d04dd2f555b79b6.diff

LOG: [clang][cli] NFC: Mirror CreateFromArgs order in generateCC1CommandLine

Added: 


Modified: 
clang/lib/Frontend/CompilerInvocation.cpp

Removed: 




diff  --git a/clang/lib/Frontend/CompilerInvocation.cpp 
b/clang/lib/Frontend/CompilerInvocation.cpp
index 3f8748f83ec0..e131804b11d1 100644
--- a/clang/lib/Frontend/CompilerInvocation.cpp
+++ b/clang/lib/Frontend/CompilerInvocation.cpp
@@ -3617,11 +3617,11 @@ void CompilerInvocation::generateCC1CommandLine(
 #undef DIAG_OPTION_WITH_MARSHALLING
 #undef OPTION_WITH_MARSHALLING
 
-  GeneratePreprocessorArgs(*PreprocessorOpts, Args, SA, *LangOpts,
-   FrontendOpts, CodeGenOpts);
   GenerateAnalyzerArgs(*AnalyzerOpts, Args, SA);
   GenerateHeaderSearchArgs(*HeaderSearchOpts, Args, SA);
   GenerateLangArgs(*LangOpts, Args, SA);
+  GeneratePreprocessorArgs(*PreprocessorOpts, Args, SA, *LangOpts,
+   FrontendOpts, CodeGenOpts);
 }
 
 IntrusiveRefCntPtr



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


[PATCH] D96248: [OpenMP][AMDGPU] Add support for linking libomptarget bitcode

2021-02-08 Thread Pushpinder Singh via Phabricator via cfe-commits
pdhaliwal created this revision.
pdhaliwal added reviewers: jdoerfert, JonChesterfield, ronlieb, saiislam, 
ABataev.
Herald added subscribers: dang, kerbowa, guansong, t-tye, tpr, dstuttard, 
yaxunl, nhaehnle, jvesely, kzhuravl.
Herald added a reviewer: jansvoboda11.
pdhaliwal requested review of this revision.
Herald added subscribers: cfe-commits, sstefan1, wdng.
Herald added a project: clang.

This patch uses the existing logic of CUDA for searching libomptarget
and extracts it to a common method.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D96248

Files:
  clang/include/clang/Driver/Options.td
  clang/lib/Driver/ToolChains/AMDGPUOpenMP.cpp
  clang/lib/Driver/ToolChains/CommonArgs.cpp
  clang/lib/Driver/ToolChains/CommonArgs.h
  clang/lib/Driver/ToolChains/Cuda.cpp
  clang/test/Driver/Inputs/hip_dev_lib/libomptarget-amdgcn-gfx803.bc
  clang/test/Driver/Inputs/hip_dev_lib/libomptarget-amdgcn-gfx906.bc
  clang/test/Driver/amdgpu-openmp-toolchain.c

Index: clang/test/Driver/amdgpu-openmp-toolchain.c
===
--- clang/test/Driver/amdgpu-openmp-toolchain.c
+++ clang/test/Driver/amdgpu-openmp-toolchain.c
@@ -1,11 +1,11 @@
 // REQUIRES: amdgpu-registered-target
-// RUN:   %clang -### --target=x86_64-unknown-linux-gnu -fopenmp -fopenmp-targets=amdgcn-amd-amdhsa -Xopenmp-target=amdgcn-amd-amdhsa -march=gfx906 %s 2>&1 \
+// RUN:   env LIBRARY_PATH=%S/Inputs/hip_dev_lib %clang -### --target=x86_64-unknown-linux-gnu -fopenmp -fopenmp-targets=amdgcn-amd-amdhsa -Xopenmp-target=amdgcn-amd-amdhsa -march=gfx906 %s 2>&1 \
 // RUN:   | FileCheck %s
 
 // verify the tools invocations
 // CHECK: clang{{.*}}"-cc1" "-triple" "x86_64-unknown-linux-gnu"{{.*}}"-x" "c"{{.*}}
 // CHECK: clang{{.*}}"-cc1" "-triple" "x86_64-unknown-linux-gnu"{{.*}}"-x" "ir"{{.*}}
-// CHECK: clang{{.*}}"-cc1"{{.*}}"-triple" "amdgcn-amd-amdhsa"{{.*}}"-target-cpu" "gfx906" "-fcuda-is-device" "-emit-llvm-bc"{{.*}}
+// CHECK: clang{{.*}}"-cc1"{{.*}}"-triple" "amdgcn-amd-amdhsa"{{.*}}"-target-cpu" "gfx906" "-fcuda-is-device" "-emit-llvm-bc" "-mlink-builtin-bitcode"{{.*}}libomptarget-amdgcn-gfx906.bc"{{.*}}
 // CHECK: llvm-link{{.*}}"-o" "{{.*}}amdgpu-openmp-toolchain-{{.*}}-gfx906-linked-{{.*}}.bc"
 // CHECK: llc{{.*}}amdgpu-openmp-toolchain-{{.*}}-gfx906-linked-{{.*}}.bc" "-mtriple=amdgcn-amd-amdhsa" "-mcpu=gfx906" "-filetype=obj" "-o"{{.*}}amdgpu-openmp-toolchain-{{.*}}-gfx906-{{.*}}.o"
 // CHECK: lld{{.*}}"-flavor" "gnu" "--no-undefined" "-shared" "-o"{{.*}}amdgpu-openmp-toolchain-{{.*}}.out" "{{.*}}amdgpu-openmp-toolchain-{{.*}}-gfx906-{{.*}}.o"
@@ -34,3 +34,6 @@
 // CHECK-PHASES: 15: assembler, {14}, object, (host-openmp)
 // CHECK-PHASES: 16: linker, {4, 15}, image, (host-openmp)
 
+// handling of --libomptarget-amdgcn-bc-path
+// RUN:   %clang -### --target=x86_64-unknown-linux-gnu -fopenmp -fopenmp-targets=amdgcn-amd-amdhsa -Xopenmp-target=amdgcn-amd-amdhsa -march=gfx803 --libomptarget-amdgcn-bc-path=%S/Inputs/hip_dev_lib/libomptarget-amdgcn-gfx803.bc %s 2>&1 | FileCheck %s --check-prefix=CHECK-LIBOMPTARGET
+// CHECK-LIBOMPTARGET: clang{{.*}}"-cc1"{{.*}}"-triple" "amdgcn-amd-amdhsa"{{.*}}"-target-cpu" "gfx803" "-fcuda-is-device" "-emit-llvm-bc" "-mlink-builtin-bitcode"{{.*}}Inputs/hip_dev_lib/libomptarget-amdgcn-gfx803.bc"{{.*}}
\ No newline at end of file
Index: clang/lib/Driver/ToolChains/Cuda.cpp
===
--- clang/lib/Driver/ToolChains/Cuda.cpp
+++ clang/lib/Driver/ToolChains/Cuda.cpp
@@ -749,56 +749,8 @@
 CudaVersionToString(CudaInstallation.version(;
 
   if (DeviceOffloadingKind == Action::OFK_OpenMP) {
-SmallVector LibraryPaths;
-// Add user defined library paths from LIBRARY_PATH.
-llvm::Optional LibPath =
-llvm::sys::Process::GetEnv("LIBRARY_PATH");
-if (LibPath) {
-  SmallVector Frags;
-  const char EnvPathSeparatorStr[] = {llvm::sys::EnvPathSeparator, '\0'};
-  llvm::SplitString(*LibPath, Frags, EnvPathSeparatorStr);
-  for (StringRef Path : Frags)
-LibraryPaths.emplace_back(Path.trim());
-}
-
-// Add path to lib / lib64 folder.
-SmallString<256> DefaultLibPath =
-llvm::sys::path::parent_path(getDriver().Dir);
-llvm::sys::path::append(DefaultLibPath, Twine("lib") + CLANG_LIBDIR_SUFFIX);
-LibraryPaths.emplace_back(DefaultLibPath.c_str());
-
-// First check whether user specifies bc library
-if (const Arg *A =
-DriverArgs.getLastArg(options::OPT_libomptarget_nvptx_bc_path_EQ)) {
-  std::string LibOmpTargetName(A->getValue());
-  if (llvm::sys::fs::exists(LibOmpTargetName)) {
-CC1Args.push_back("-mlink-builtin-bitcode");
-CC1Args.push_back(DriverArgs.MakeArgString(LibOmpTargetName));
-  } else {
-getDriver().Diag(diag::err_drv_omp_offload_target_bcruntime_not_found)
-<< LibOmpTargetName;
-  }
-} else {
-  bool FoundBCLibrary = false;
-

[clang] 6039f82 - Revert "[clang][cli] Report result of ParseLangArgs"

2021-02-08 Thread Jan Svoboda via cfe-commits

Author: Jan Svoboda
Date: 2021-02-08T10:18:15+01:00
New Revision: 6039f821456fffa24fa36132f2022880fa9128df

URL: 
https://github.com/llvm/llvm-project/commit/6039f821456fffa24fa36132f2022880fa9128df
DIFF: 
https://github.com/llvm/llvm-project/commit/6039f821456fffa24fa36132f2022880fa9128df.diff

LOG: Revert "[clang][cli] Report result of ParseLangArgs"

This reverts commit bff6d9bb

The change causes failure of Clang's Index/implicit-attrs.m test.

Added: 


Modified: 
clang/include/clang/Basic/Diagnostic.h
clang/include/clang/Frontend/CompilerInvocation.h
clang/lib/Frontend/CompilerInvocation.cpp

Removed: 




diff  --git a/clang/include/clang/Basic/Diagnostic.h 
b/clang/include/clang/Basic/Diagnostic.h
index a3cc3af5a74a..3499c551cfdf 100644
--- a/clang/include/clang/Basic/Diagnostic.h
+++ b/clang/include/clang/Basic/Diagnostic.h
@@ -806,7 +806,6 @@ class DiagnosticsEngine : public 
RefCountedBase {
 return FatalErrorOccurred || UnrecoverableErrorOccurred;
   }
 
-  unsigned getNumErrors() const { return NumErrors; }
   unsigned getNumWarnings() const { return NumWarnings; }
 
   void setNumWarnings(unsigned NumWarnings) {

diff  --git a/clang/include/clang/Frontend/CompilerInvocation.h 
b/clang/include/clang/Frontend/CompilerInvocation.h
index e880713b71aa..233569aa727b 100644
--- a/clang/include/clang/Frontend/CompilerInvocation.h
+++ b/clang/include/clang/Frontend/CompilerInvocation.h
@@ -249,7 +249,7 @@ class CompilerInvocation : public CompilerInvocationBase {
DiagnosticsEngine &Diags);
 
   /// Parse command line options that map to LangOptions.
-  static bool ParseLangArgs(LangOptions &Opts, llvm::opt::ArgList &Args,
+  static void ParseLangArgs(LangOptions &Opts, llvm::opt::ArgList &Args,
 InputKind IK, const llvm::Triple &T,
 std::vector &Includes,
 DiagnosticsEngine &Diags);

diff  --git a/clang/lib/Frontend/CompilerInvocation.cpp 
b/clang/lib/Frontend/CompilerInvocation.cpp
index e131804b11d1..f4104a35c0fd 100644
--- a/clang/lib/Frontend/CompilerInvocation.cpp
+++ b/clang/lib/Frontend/CompilerInvocation.cpp
@@ -2642,12 +2642,10 @@ static void GenerateLangArgs(const LangOptions &Opts,
 GenerateArg(Args, OPT_fdeclare_opencl_builtins, SA);
 }
 
-bool CompilerInvocation::ParseLangArgs(LangOptions &Opts, ArgList &Args,
+void CompilerInvocation::ParseLangArgs(LangOptions &Opts, ArgList &Args,
InputKind IK, const llvm::Triple &T,
std::vector &Includes,
DiagnosticsEngine &Diags) {
-  unsigned NumErrorsBefore = Diags.getNumErrors();
-
   // FIXME: Cleanup per-file based stuff.
   LangStandard::Kind LangStd = LangStandard::lang_unspecified;
   if (const Arg *A = Args.getLastArg(OPT_std_EQ)) {
@@ -3078,8 +3076,6 @@ bool CompilerInvocation::ParseLangArgs(LangOptions &Opts, 
ArgList &Args,
   }
 }
   }
-
-  return Success && Diags.getNumErrors() == NumErrorsBefore;
 }
 
 static bool isStrictlyPreprocessorAction(frontend::ActionKind Action) {
@@ -3420,8 +3416,8 @@ bool 
CompilerInvocation::CreateFromArgs(CompilerInvocation &Res,
   } else {
 // Other LangOpts are only initialized when the input is not AST or LLVM 
IR.
 // FIXME: Should we really be calling this for an Language::Asm input?
-Success &= ParseLangArgs(LangOpts, Args, DashX, T,
- Res.getPreprocessorOpts().Includes, Diags);
+ParseLangArgs(LangOpts, Args, DashX, T, Res.getPreprocessorOpts().Includes,
+  Diags);
 if (Res.getFrontendOpts().ProgramAction == frontend::RewriteObjC)
   LangOpts.ObjCExceptions = 1;
 if (T.isOSDarwin() && DashX.isPreprocessed()) {



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


[PATCH] D96151: [OpenCL] Fix pipe type printing in arg info metadata

2021-02-08 Thread Marco Antognini via Phabricator via cfe-commits
mantognini accepted this revision.
mantognini added a comment.
This revision is now accepted and ready to land.

Nice refactoring & fix! LGTM. I suppose Stuart's comment about moving 
`typeNameRef` can be addressed when pushing.


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

https://reviews.llvm.org/D96151

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


[PATCH] D96248: [OpenMP][AMDGPU] Add support for linking libomptarget bitcode

2021-02-08 Thread Pushpinder Singh via Phabricator via cfe-commits
pdhaliwal updated this revision to Diff 322052.
pdhaliwal added a comment.

Accidently missed some changes,

- Fix openmp-offload.c test failure
- Fix amdgpu-openmp-toolchain.c test failure


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D96248

Files:
  clang/include/clang/Driver/Options.td
  clang/lib/Driver/ToolChains/AMDGPUOpenMP.cpp
  clang/lib/Driver/ToolChains/CommonArgs.cpp
  clang/lib/Driver/ToolChains/CommonArgs.h
  clang/lib/Driver/ToolChains/Cuda.cpp
  clang/test/Driver/Inputs/hip_dev_lib/libomptarget-amdgcn-gfx803.bc
  clang/test/Driver/Inputs/hip_dev_lib/libomptarget-amdgcn-gfx906.bc
  clang/test/Driver/amdgpu-openmp-toolchain.c

Index: clang/test/Driver/amdgpu-openmp-toolchain.c
===
--- clang/test/Driver/amdgpu-openmp-toolchain.c
+++ clang/test/Driver/amdgpu-openmp-toolchain.c
@@ -1,11 +1,11 @@
 // REQUIRES: amdgpu-registered-target
-// RUN:   %clang -### --target=x86_64-unknown-linux-gnu -fopenmp -fopenmp-targets=amdgcn-amd-amdhsa -Xopenmp-target=amdgcn-amd-amdhsa -march=gfx906 %s 2>&1 \
+// RUN:   env LIBRARY_PATH=%S/Inputs/hip_dev_lib %clang -### --target=x86_64-unknown-linux-gnu -fopenmp -fopenmp-targets=amdgcn-amd-amdhsa -Xopenmp-target=amdgcn-amd-amdhsa -march=gfx906 %s 2>&1 \
 // RUN:   | FileCheck %s
 
 // verify the tools invocations
 // CHECK: clang{{.*}}"-cc1" "-triple" "x86_64-unknown-linux-gnu"{{.*}}"-x" "c"{{.*}}
 // CHECK: clang{{.*}}"-cc1" "-triple" "x86_64-unknown-linux-gnu"{{.*}}"-x" "ir"{{.*}}
-// CHECK: clang{{.*}}"-cc1"{{.*}}"-triple" "amdgcn-amd-amdhsa"{{.*}}"-target-cpu" "gfx906" "-fcuda-is-device" "-emit-llvm-bc"{{.*}}
+// CHECK: clang{{.*}}"-cc1"{{.*}}"-triple" "amdgcn-amd-amdhsa"{{.*}}"-target-cpu" "gfx906" "-fcuda-is-device" "-emit-llvm-bc" "-mlink-builtin-bitcode"{{.*}}libomptarget-amdgcn-gfx906.bc"{{.*}}
 // CHECK: llvm-link{{.*}}"-o" "{{.*}}amdgpu-openmp-toolchain-{{.*}}-gfx906-linked-{{.*}}.bc"
 // CHECK: llc{{.*}}amdgpu-openmp-toolchain-{{.*}}-gfx906-linked-{{.*}}.bc" "-mtriple=amdgcn-amd-amdhsa" "-mcpu=gfx906" "-filetype=obj" "-o"{{.*}}amdgpu-openmp-toolchain-{{.*}}-gfx906-{{.*}}.o"
 // CHECK: lld{{.*}}"-flavor" "gnu" "--no-undefined" "-shared" "-o"{{.*}}amdgpu-openmp-toolchain-{{.*}}.out" "{{.*}}amdgpu-openmp-toolchain-{{.*}}-gfx906-{{.*}}.o"
@@ -34,3 +34,7 @@
 // CHECK-PHASES: 15: assembler, {14}, object, (host-openmp)
 // CHECK-PHASES: 16: linker, {4, 15}, image, (host-openmp)
 
+// handling of --libomptarget-device-bc-path
+// RUN:   %clang -### --target=x86_64-unknown-linux-gnu -fopenmp -fopenmp-targets=amdgcn-amd-amdhsa -Xopenmp-target=amdgcn-amd-amdhsa -march=gfx803 --libomptarget-device-bc-path=%S/Inputs/hip_dev_lib/libomptarget-amdgcn-gfx803.bc %s 2>&1 | FileCheck %s --check-prefix=CHECK-LIBOMPTARGET
+// CHECK-LIBOMPTARGET: clang{{.*}}"-cc1"{{.*}}"-triple" "amdgcn-amd-amdhsa"{{.*}}"-target-cpu" "gfx803" "-fcuda-is-device" "-emit-llvm-bc" "-mlink-builtin-bitcode"{{.*}}Inputs/hip_dev_lib/libomptarget-amdgcn-gfx803.bc"{{.*}}
+
Index: clang/lib/Driver/ToolChains/Cuda.cpp
===
--- clang/lib/Driver/ToolChains/Cuda.cpp
+++ clang/lib/Driver/ToolChains/Cuda.cpp
@@ -749,56 +749,9 @@
 CudaVersionToString(CudaInstallation.version(;
 
   if (DeviceOffloadingKind == Action::OFK_OpenMP) {
-SmallVector LibraryPaths;
-// Add user defined library paths from LIBRARY_PATH.
-llvm::Optional LibPath =
-llvm::sys::Process::GetEnv("LIBRARY_PATH");
-if (LibPath) {
-  SmallVector Frags;
-  const char EnvPathSeparatorStr[] = {llvm::sys::EnvPathSeparator, '\0'};
-  llvm::SplitString(*LibPath, Frags, EnvPathSeparatorStr);
-  for (StringRef Path : Frags)
-LibraryPaths.emplace_back(Path.trim());
-}
-
-// Add path to lib / lib64 folder.
-SmallString<256> DefaultLibPath =
-llvm::sys::path::parent_path(getDriver().Dir);
-llvm::sys::path::append(DefaultLibPath, Twine("lib") + CLANG_LIBDIR_SUFFIX);
-LibraryPaths.emplace_back(DefaultLibPath.c_str());
-
-// First check whether user specifies bc library
-if (const Arg *A =
-DriverArgs.getLastArg(options::OPT_libomptarget_nvptx_bc_path_EQ)) {
-  std::string LibOmpTargetName(A->getValue());
-  if (llvm::sys::fs::exists(LibOmpTargetName)) {
-CC1Args.push_back("-mlink-builtin-bitcode");
-CC1Args.push_back(DriverArgs.MakeArgString(LibOmpTargetName));
-  } else {
-getDriver().Diag(diag::err_drv_omp_offload_target_bcruntime_not_found)
-<< LibOmpTargetName;
-  }
-} else {
-  bool FoundBCLibrary = false;
-
-  std::string LibOmpTargetName = "libomptarget-nvptx-cuda_" +
- CudaVersionStr + "-" + GpuArch.str() +
- ".bc";
-
-  for (StringRef LibraryPath : LibraryPaths) {
-SmallString<128> LibOmp

[PATCH] D95435: [clang][aarch64][WOA64][docs] Release note for longjmp crash with /guard:cf

2021-02-08 Thread Peter Waller via Phabricator via cfe-commits
peterwaller-arm abandoned this revision.
peterwaller-arm added a comment.

Release note upstream on release/12.x branch in 
rGbc2dad1671598a87423c61c355d03db49ce76907 
.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D95435

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


[PATCH] D96245: [clangd] Propagate CodeActions in addition to Fixes for diagnostics

2021-02-08 Thread Nathan James via Phabricator via cfe-commits
njames93 added a comment.

Emitting fixes for a diagnostic in another file seems dangerous, what's the 
intended use case for this?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D96245

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


[PATCH] D96252: [RFC] Feature modularization for clangd

2021-02-08 Thread Sam McCall via Phabricator via cfe-commits
sammccall created this revision.
Herald added subscribers: usaxena95, kadircet, arphaman, mgorny.
sammccall requested review of this revision.
Herald added subscribers: cfe-commits, MaskRay, ilya-biryukov.
Herald added a project: clang.

This is related to the ideas in D96244 , but a 
bit more expansive...

Core ideas:

- the bulk of the features (though not everything) can be moved into modules, 
breaking up the Clangd[LSP]Server monoliths and allowing for out-of-tree 
features
- group together the LSP, C++ bound-to-server API, and free-function APIs for 
features. We no longer separate the first two in simple cases.
- allow modules to expose public C++ APIs, where we want to expose something 
richer than LSP

Caveats:

- this demo just pulls out formatting, which won't uncover all issues.
- Lit tests pass (so clangd works), but unit tests don't.
- Passing DraftStore into ClangdServer is a hack, need a real solution.
- I'm concerned whether richer C++ APIs will have a quite different style than 
the LSP-based ones. e.g. foo(Path, Position, Options) vs foo(FooParams).


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D96252

Files:
  clang-tools-extra/clangd/CMakeLists.txt
  clang-tools-extra/clangd/ClangdLSPServer.cpp
  clang-tools-extra/clangd/ClangdLSPServer.h
  clang-tools-extra/clangd/ClangdServer.cpp
  clang-tools-extra/clangd/ClangdServer.h
  clang-tools-extra/clangd/Format.cpp
  clang-tools-extra/clangd/Format.h
  clang-tools-extra/clangd/Module.h
  clang-tools-extra/clangd/ModuleDefaults.cpp
  clang-tools-extra/clangd/Protocol.cpp
  clang-tools-extra/clangd/Protocol.h
  clang-tools-extra/clangd/test/crash-non-added-files.test
  clang-tools-extra/clangd/tool/ClangdMain.cpp

Index: clang-tools-extra/clangd/tool/ClangdMain.cpp
===
--- clang-tools-extra/clangd/tool/ClangdMain.cpp
+++ clang-tools-extra/clangd/tool/ClangdMain.cpp
@@ -706,6 +706,8 @@
 log("{0}: {1}", FlagsEnvVar, *EnvFlags);
 
   ClangdLSPServer::Options Opts;
+  auto Modules = ModuleSet::defaults();
+  Opts.Modules = &Modules;
   Opts.UseDirBasedCDB = (CompileArgsFrom == FilesystemCompileArgs);
 
   // If --compile-commands-dir arg was invoked, check value and override default
Index: clang-tools-extra/clangd/test/crash-non-added-files.test
===
--- clang-tools-extra/clangd/test/crash-non-added-files.test
+++ clang-tools-extra/clangd/test/crash-non-added-files.test
@@ -11,21 +11,21 @@
 {"jsonrpc":"2.0","id":3,"method":"textDocument/rangeFormatting","params":{"textDocument":{"uri":"test:///foo.c"},"range":{"start":{"line":1,"character":4},"end":{"line":1,"character":12}},"options":{"tabSize":4,"insertSpaces":true}}}
 #  CHECK:  "error": {
 # CHECK-NEXT:"code": -32602
-# CHECK-NEXT:"message": "onDocumentRangeFormatting called for non-added file"
+# CHECK-NEXT:"message": "formatting non-added file"
 # CHECK-NEXT:  },
 # CHECK-NEXT:  "id": 3,
 ---
 {"jsonrpc":"2.0","id":4,"method":"textDocument/formatting","params":{"textDocument":{"uri":"test:///foo.c"},"options":{"tabSize":4,"insertSpaces":true}}}
 #  CHECK:  "error": {
 # CHECK-NEXT:"code": -32602
-# CHECK-NEXT:"message": "onDocumentFormatting called for non-added file"
+# CHECK-NEXT:"message": "formatting non-added file"
 # CHECK-NEXT:  },
 # CHECK-NEXT:  "id": 4,
 ---
 {"jsonrpc":"2.0","id":5,"method":"textDocument/onTypeFormatting","params":{"textDocument":{"uri":"test:///foo.c"},"position":{"line":3,"character":1},"ch":"}","options":{"tabSize":4,"insertSpaces":true}}}
 #  CHECK:  "error": {
 # CHECK-NEXT:"code": -32602
-# CHECK-NEXT:"message": "onDocumentOnTypeFormatting called for non-added file"
+# CHECK-NEXT:"message": "formatting non-added file"
 # CHECK-NEXT:  },
 # CHECK-NEXT:  "id": 5,
 ---
Index: clang-tools-extra/clangd/Protocol.h
===
--- clang-tools-extra/clangd/Protocol.h
+++ clang-tools-extra/clangd/Protocol.h
@@ -745,44 +745,6 @@
 bool fromJSON(const llvm::json::Value &, DidChangeConfigurationParams &,
   llvm::json::Path);
 
-// Note: we do not parse FormattingOptions for *FormattingParams.
-// In general, we use a clang-format style detected from common mechanisms
-// (.clang-format files and the -fallback-style flag).
-// It would be possible to override these with FormatOptions, but:
-//  - the protocol makes FormatOptions mandatory, so many clients set them to
-//useless values, and we can't tell when to respect them
-// - we also format in other places, where FormatOptions aren't available.
-
-struct DocumentRangeFormattingParams {
-  /// The document to format.
-  TextDocumentIdentifier textDocument;
-
-  /// The range to format
-  Range range;
-};
-bool fromJSON(const llvm::json::Value &, DocumentRangeFormattingParams &,
-  llvm::json::Path);
-
-stru

[PATCH] D96245: [clangd] Propagate CodeActions in addition to Fixes for diagnostics

2021-02-08 Thread Kadir Cetinkaya via Phabricator via cfe-commits
kadircet added a comment.

> Emitting fixes for a diagnostic in another file seems dangerous, what's the 
> intended use case for this?

one particular example is fixing layering violations in more strict build 
systems like bazel/blaze. for example if you `#include "a.h"` in a file, but 
build target of that particular file doesn't depend on a target exporting `a.h` 
clangd can generate an edit to update the relevant build target to have a 
dependency on `a.h`.




Comment at: clang-tools-extra/clangd/Diagnostics.h:113
+const ClangdDiagnosticOptions &Opts,
+llvm::function_ref,
+llvm::ArrayRef)>

we keep broadcasting fixes and actions separately to keep embedders that can't 
handle codeactions happy.

we can start emitting just codeactions here by converting fixes to codeactions 
in this layer (all we need is fileuri, and we have it). then embedders can 
still iterate over all code actions and pick only the edits for mainfile while 
ignoring the rest.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D96245

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


[PATCH] D96244: [clangd][RFC] Introudce Plugins

2021-02-08 Thread Kadir Cetinkaya via Phabricator via cfe-commits
kadircet added inline comments.



Comment at: clang-tools-extra/clangd/Plugin.h:26
+  virtual llvm::Optional
+  actOnDiagnostic(DiagnosticsEngine::Level L, const clang::Diagnostic &Diag) {
+return llvm::None;

i think it would be better to have these as separate modules. for example a
```
class DiagnosticsModule {
public:
virtual llvm::Optional
  actOnDiagnostic(DiagnosticsEngine::Level L, const clang::Diagnostic &Diag) = 
0;
};
class HoverModule {
public:
virtual llvm::Optional generateHover(ParsedAST, Selection, 
SymbolIndex) = 0;
};
class LSPModule {
public:
virtual void registerHandler(EndPoint, Functor);
virtual json::Object dispatch(EndPoint, Params, ClangdServer&); // as some of 
these might need to mutate ClangdServer or access other modules.
};
// and so on.
```
and have multiple registries for each of these modules.

Then have a `PluginManager` in `ClangdServer` that provides a unified API for 
accessing these modules. (e.g. to implement each of our features in terms of 
these modules as discussed offline).

but I am not sure if it'll be worth the complexity with only diagnostics making 
use of that mechanism in the foreseeable future. So I am leaning towards 
keeping it simple in this version, but open for suggestions.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D96244

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


[clang] a016374 - [OpenCL] Do not enforce ASTContext for OCL2Qual

2021-02-08 Thread Sven van Haastregt via cfe-commits

Author: Sven van Haastregt
Date: 2021-02-08T10:56:39Z
New Revision: a016374d079b0d8f37af052ced13f9850f1049fa

URL: 
https://github.com/llvm/llvm-project/commit/a016374d079b0d8f37af052ced13f9850f1049fa
DIFF: 
https://github.com/llvm/llvm-project/commit/a016374d079b0d8f37af052ced13f9850f1049fa.diff

LOG: [OpenCL] Do not enforce ASTContext for OCL2Qual

Do not enforce that the expression to obtain the QualType for an
OpenCL type starts with an ASTContext.  This adds the required
flexibility for handling the remaining missing argument types such as
enums.

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

Added: 


Modified: 
clang/lib/Sema/OpenCLBuiltins.td
clang/utils/TableGen/ClangOpenCLBuiltinEmitter.cpp

Removed: 




diff  --git a/clang/lib/Sema/OpenCLBuiltins.td 
b/clang/lib/Sema/OpenCLBuiltins.td
index 7c4b81967695..bd8049a04b99 100644
--- a/clang/lib/Sema/OpenCLBuiltins.td
+++ b/clang/lib/Sema/OpenCLBuiltins.td
@@ -77,10 +77,10 @@ def ArmIntegerDotProductAccumulateInt16: 
FunctionExtension<"cl_arm_integ
 def ArmIntegerDotProductAccumulateSaturateInt8 : 
FunctionExtension<"cl_arm_integer_dot_product_accumulate_saturate_int8">;
 
 // Qualified Type.  These map to ASTContext::QualType.
-class QualType {
-  // Name of the field or function in a clang::ASTContext
-  // E.g. Name="IntTy" for the int type, and "getIntPtrType()" for an intptr_t
-  string Name = _Name;
+class QualType {
+  // Expression to obtain the QualType inside OCL2Qual.
+  // E.g. TypeExpr="Context.IntTy" for the int type.
+  string TypeExpr = _TypeExpr;
   // Some QualTypes in this file represent an abstract type for which there is
   // no corresponding AST QualType, e.g. a GenType or an `image2d_t` type
   // without access qualifiers.
@@ -99,11 +99,11 @@ class IntList _List> {
 // OpenCL C basic data types (int, float, image2d_t, ...).
 // Its child classes can represent concrete types (e.g. VectorType) or
 // abstract types (e.g. GenType).
-class Type {
+class Type {
   // Name of the Type.
   string Name = _Name;
   // QualType associated with this type.
-  QualType QTName = _QTName;
+  QualType QTExpr = _QTExpr;
   // Size of the vector (if applicable).
   int VecWidth = 1;
   // Is a pointer.
@@ -119,7 +119,7 @@ class Type {
 }
 
 // OpenCL vector types (e.g. int2, int3, int16, float8, ...).
-class VectorType : Type<_Ty.Name, _Ty.QTName> {
+class VectorType : Type<_Ty.Name, _Ty.QTExpr> {
   let VecWidth = _VecWidth;
   let AccessQualifier = "";
   // Inherited fields
@@ -131,7 +131,7 @@ class VectorType : Type<_Ty.Name, 
_Ty.QTName> {
 
 // OpenCL pointer types (e.g. int*, float*, ...).
 class PointerType :
-Type<_Ty.Name, _Ty.QTName> {
+Type<_Ty.Name, _Ty.QTExpr> {
   let AddrSpace = _AS.Name;
   // Inherited fields
   let VecWidth = _Ty.VecWidth;
@@ -142,7 +142,7 @@ class PointerType :
 }
 
 // OpenCL const types (e.g. const int).
-class ConstType : Type<_Ty.Name, _Ty.QTName> {
+class ConstType : Type<_Ty.Name, _Ty.QTExpr> {
   let IsConst = 1;
   // Inherited fields
   let VecWidth = _Ty.VecWidth;
@@ -153,7 +153,7 @@ class ConstType : Type<_Ty.Name, _Ty.QTName> {
 }
 
 // OpenCL volatile types (e.g. volatile int).
-class VolatileType : Type<_Ty.Name, _Ty.QTName> {
+class VolatileType : Type<_Ty.Name, _Ty.QTExpr> {
   let IsVolatile = 1;
   // Inherited fields
   let VecWidth = _Ty.VecWidth;
@@ -165,7 +165,7 @@ class VolatileType : Type<_Ty.Name, _Ty.QTName> {
 
 // OpenCL image types (e.g. image2d).
 class ImageType :
-Type<_Ty.Name, QualType<_Ty.QTName.Name#_AccessQualifier#"Ty", 0>> {
+Type<_Ty.Name, QualType<_Ty.QTExpr.TypeExpr # _AccessQualifier # "Ty", 0>> 
{
   let VecWidth = 0;
   let AccessQualifier = _AccessQualifier;
   // Inherited fields
@@ -254,23 +254,23 @@ class Builtin _Signature, 
list _Attributes = Attr.
 
//===--===//
 
 // OpenCL v1.0/1.2/2.0 s6.1.1: Built-in Scalar Data Types.
-def Bool  : Type<"bool",  QualType<"BoolTy">>;
-def Char  : Type<"char",  QualType<"CharTy">>;
-def UChar : Type<"uchar", QualType<"UnsignedCharTy">>;
-def Short : Type<"short", QualType<"ShortTy">>;
-def UShort: Type<"ushort",QualType<"UnsignedShortTy">>;
-def Int   : Type<"int",   QualType<"IntTy">>;
-def UInt  : Type<"uint",  QualType<"UnsignedIntTy">>;
-def Long  : Type<"long",  QualType<"LongTy">>;
-def ULong : Type<"ulong", QualType<"UnsignedLongTy">>;
-def Float : Type<"float", QualType<"FloatTy">>;
-def Double: Type<"double",QualType<"DoubleTy">>;
-def Half  : Type<"half",  QualType<"HalfTy">>;
-def Size  : Type<"size_t",QualType<"getSizeType()">>;
-def PtrDiff   : Type<"ptr
diff _t", QualType<"getPointerDiffType()">>;
-def IntPtr: Type<"intptr_t",  QualType<"getIntPtrType()">>;
-def UIntPtr   : Type<"uintptr_t", QualType<"getU

[PATCH] D96050: [OpenCL] Do not enforce ASTContext for OCL2Qual

2021-02-08 Thread Sven van Haastregt via Phabricator via cfe-commits
This revision was landed with ongoing or failed builds.
This revision was automatically updated to reflect the committed changes.
Closed by commit rGa016374d079b: [OpenCL] Do not enforce ASTContext for 
OCL2Qual (authored by svenvh).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D96050

Files:
  clang/lib/Sema/OpenCLBuiltins.td
  clang/utils/TableGen/ClangOpenCLBuiltinEmitter.cpp

Index: clang/utils/TableGen/ClangOpenCLBuiltinEmitter.cpp
===
--- clang/utils/TableGen/ClangOpenCLBuiltinEmitter.cpp
+++ clang/utils/TableGen/ClangOpenCLBuiltinEmitter.cpp
@@ -691,8 +691,9 @@
 .Case("RO", "case OCLAQ_ReadOnly:\n")
 .Case("WO", "case OCLAQ_WriteOnly:\n")
 .Case("RW", "case OCLAQ_ReadWrite:\n")
- << "  QT.push_back(Context."
- << Image->getValueAsDef("QTName")->getValueAsString("Name") << ");\n"
+ << "  QT.push_back("
+ << Image->getValueAsDef("QTExpr")->getValueAsString("TypeExpr")
+ << ");\n"
  << "  break;\n";
 }
 OS << "  }\n"
@@ -713,8 +714,7 @@
  I++) {
   for (const auto *T :
GenType->getValueAsDef("TypeList")->getValueAsListOfDefs("List")) {
-OS << "Context."
-   << T->getValueAsDef("QTName")->getValueAsString("Name") << ", ";
+OS << T->getValueAsDef("QTExpr")->getValueAsString("TypeExpr") << ", ";
   }
 }
 OS << "});\n";
@@ -748,14 +748,13 @@
 TypesSeen.insert(std::make_pair(T->getValueAsString("Name"), true));
 
 // Check the Type does not have an "abstract" QualType
-auto QT = T->getValueAsDef("QTName");
+auto QT = T->getValueAsDef("QTExpr");
 if (QT->getValueAsBit("IsAbstract") == 1)
   continue;
 // Emit the cases for non generic, non image types.
-OS << "case OCLT_" << T->getValueAsString("Name") << ":\n";
-OS << "  QT.push_back(Context." << QT->getValueAsString("Name")
-   << ");\n";
-OS << "  break;\n";
+OS << "case OCLT_" << T->getValueAsString("Name") << ":\n"
+   << "  QT.push_back(" << QT->getValueAsString("TypeExpr") << ");\n"
+   << "  break;\n";
   }
 
   // End of switch statement.
Index: clang/lib/Sema/OpenCLBuiltins.td
===
--- clang/lib/Sema/OpenCLBuiltins.td
+++ clang/lib/Sema/OpenCLBuiltins.td
@@ -77,10 +77,10 @@
 def ArmIntegerDotProductAccumulateSaturateInt8 : FunctionExtension<"cl_arm_integer_dot_product_accumulate_saturate_int8">;
 
 // Qualified Type.  These map to ASTContext::QualType.
-class QualType {
-  // Name of the field or function in a clang::ASTContext
-  // E.g. Name="IntTy" for the int type, and "getIntPtrType()" for an intptr_t
-  string Name = _Name;
+class QualType {
+  // Expression to obtain the QualType inside OCL2Qual.
+  // E.g. TypeExpr="Context.IntTy" for the int type.
+  string TypeExpr = _TypeExpr;
   // Some QualTypes in this file represent an abstract type for which there is
   // no corresponding AST QualType, e.g. a GenType or an `image2d_t` type
   // without access qualifiers.
@@ -99,11 +99,11 @@
 // OpenCL C basic data types (int, float, image2d_t, ...).
 // Its child classes can represent concrete types (e.g. VectorType) or
 // abstract types (e.g. GenType).
-class Type {
+class Type {
   // Name of the Type.
   string Name = _Name;
   // QualType associated with this type.
-  QualType QTName = _QTName;
+  QualType QTExpr = _QTExpr;
   // Size of the vector (if applicable).
   int VecWidth = 1;
   // Is a pointer.
@@ -119,7 +119,7 @@
 }
 
 // OpenCL vector types (e.g. int2, int3, int16, float8, ...).
-class VectorType : Type<_Ty.Name, _Ty.QTName> {
+class VectorType : Type<_Ty.Name, _Ty.QTExpr> {
   let VecWidth = _VecWidth;
   let AccessQualifier = "";
   // Inherited fields
@@ -131,7 +131,7 @@
 
 // OpenCL pointer types (e.g. int*, float*, ...).
 class PointerType :
-Type<_Ty.Name, _Ty.QTName> {
+Type<_Ty.Name, _Ty.QTExpr> {
   let AddrSpace = _AS.Name;
   // Inherited fields
   let VecWidth = _Ty.VecWidth;
@@ -142,7 +142,7 @@
 }
 
 // OpenCL const types (e.g. const int).
-class ConstType : Type<_Ty.Name, _Ty.QTName> {
+class ConstType : Type<_Ty.Name, _Ty.QTExpr> {
   let IsConst = 1;
   // Inherited fields
   let VecWidth = _Ty.VecWidth;
@@ -153,7 +153,7 @@
 }
 
 // OpenCL volatile types (e.g. volatile int).
-class VolatileType : Type<_Ty.Name, _Ty.QTName> {
+class VolatileType : Type<_Ty.Name, _Ty.QTExpr> {
   let IsVolatile = 1;
   // Inherited fields
   let VecWidth = _Ty.VecWidth;
@@ -165,7 +165,7 @@
 
 // OpenCL image types (e.g. image2d).
 class ImageType :
-Type<_Ty.Name, QualType<_Ty.QTName.Name#_AccessQualifier#"Ty", 0>> {
+Type<_Ty.Name, QualType<_Ty.QTExpr.TypeExpr # _AccessQualifier # "Ty", 0>> {
   let VecWidth = 0;
   

[PATCH] D71714: [Sema] Fix -Warray-bounds false negative when casting an out-of-bounds array item

2021-02-08 Thread Vince Bridgers via Phabricator via cfe-commits
vabridgers added a comment.

Thanks @thakis, per @rsmith 's suggestion in the review, I'll revert this. 
Apologies for the inconvenience.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D71714

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


[PATCH] D96032: [flang][driver] Add support for -fopenmp and -fopenacc

2021-02-08 Thread Faris Rehman via Phabricator via cfe-commits
FarisRehman updated this revision to Diff 322071.
FarisRehman added a comment.

Rebase off main

Rebase off main as patch D95448 , which this 
patch depends on, has been merged into main.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D96032

Files:
  clang/include/clang/Driver/Options.td
  clang/lib/Driver/ToolChains/Flang.cpp
  flang/include/flang/Frontend/CompilerInstance.h
  flang/include/flang/Frontend/CompilerInvocation.h
  flang/include/flang/Frontend/FrontendOptions.h
  flang/lib/Frontend/CompilerInstance.cpp
  flang/lib/Frontend/CompilerInvocation.cpp
  flang/lib/Frontend/FrontendActions.cpp
  flang/test/Flang-Driver/driver-help-hidden.f90
  flang/test/Flang-Driver/driver-help.f90
  flang/test/Semantics/OpenACC/acc-atomic-validity.f90
  flang/test/Semantics/OpenACC/acc-branch.f90
  flang/test/Semantics/OpenACC/acc-cache-validity.f90
  flang/test/Semantics/OpenACC/acc-canonicalization-validity.f90
  flang/test/Semantics/OpenACC/acc-data.f90
  flang/test/Semantics/OpenACC/acc-declare-validity.f90
  flang/test/Semantics/OpenACC/acc-host-data.f90
  flang/test/Semantics/OpenACC/acc-init-validity.f90
  flang/test/Semantics/OpenACC/acc-kernels-loop.f90
  flang/test/Semantics/OpenACC/acc-kernels.f90
  flang/test/Semantics/OpenACC/acc-loop.f90
  flang/test/Semantics/OpenACC/acc-parallel-loop-validity.f90
  flang/test/Semantics/OpenACC/acc-parallel.f90
  flang/test/Semantics/OpenACC/acc-resolve01.f90
  flang/test/Semantics/OpenACC/acc-resolve02.f90
  flang/test/Semantics/OpenACC/acc-routine-validity.f90
  flang/test/Semantics/OpenACC/acc-serial-loop.f90
  flang/test/Semantics/OpenACC/acc-serial.f90
  flang/test/Semantics/OpenACC/acc-set-validity.f90
  flang/test/Semantics/OpenACC/acc-shutdown-validity.f90
  flang/test/Semantics/OpenACC/acc-update-validity.f90
  flang/test/Semantics/OpenACC/acc-wait-validity.f90
  flang/test/Semantics/omp-atomic.f90
  flang/test/Semantics/omp-combined-constructs.f90
  flang/test/Semantics/omp-copyin01.f90
  flang/test/Semantics/omp-copyin02.f90
  flang/test/Semantics/omp-copyin03.f90
  flang/test/Semantics/omp-copyin04.f90
  flang/test/Semantics/omp-copyin05.f90
  flang/test/Semantics/omp-declarative-directive.f90
  flang/test/Semantics/omp-default.f90
  flang/test/Semantics/omp-default02.f90
  flang/test/Semantics/omp-depend01.f90
  flang/test/Semantics/omp-depend02.f90
  flang/test/Semantics/omp-depend03.f90
  flang/test/Semantics/omp-device-constructs.f90
  flang/test/Semantics/omp-do-collapse-positivecases.f90
  flang/test/Semantics/omp-do-collapse.f90
  flang/test/Semantics/omp-do-cycle.f90
  flang/test/Semantics/omp-do-ordered-positivecases.f90
  flang/test/Semantics/omp-do-ordered.f90
  flang/test/Semantics/omp-do-schedule01.f90
  flang/test/Semantics/omp-do-schedule02.f90
  flang/test/Semantics/omp-do01.f90
  flang/test/Semantics/omp-do02.f90
  flang/test/Semantics/omp-do03.f90
  flang/test/Semantics/omp-do04.f90
  flang/test/Semantics/omp-do05.f90
  flang/test/Semantics/omp-do06.f90
  flang/test/Semantics/omp-do07.f90
  flang/test/Semantics/omp-do08.f90
  flang/test/Semantics/omp-do09.f90
  flang/test/Semantics/omp-do10.f90
  flang/test/Semantics/omp-flush01.f90
  flang/test/Semantics/omp-invalid-branch.f90
  flang/test/Semantics/omp-loop-association.f90
  flang/test/Semantics/omp-loop-simd01.f90
  flang/test/Semantics/omp-nested01.f90
  flang/test/Semantics/omp-no-dowhile-in-parallel.f90
  flang/test/Semantics/omp-parallel-private01.f90
  flang/test/Semantics/omp-parallel-private02.f90
  flang/test/Semantics/omp-parallel-private03.f90
  flang/test/Semantics/omp-parallel-private04.f90
  flang/test/Semantics/omp-parallel-shared01.f90
  flang/test/Semantics/omp-parallel-shared02.f90
  flang/test/Semantics/omp-parallel-shared03.f90
  flang/test/Semantics/omp-parallel-shared04.f90
  flang/test/Semantics/omp-parallel01.f90
  flang/test/Semantics/omp-parallel02.f90
  flang/test/Semantics/omp-private01.f90
  flang/test/Semantics/omp-private02.f90
  flang/test/Semantics/omp-private03.f90
  flang/test/Semantics/omp-resolve01.f90
  flang/test/Semantics/omp-resolve02.f90
  flang/test/Semantics/omp-resolve03.f90
  flang/test/Semantics/omp-resolve04.f90
  flang/test/Semantics/omp-resolve05.f90
  flang/test/Semantics/omp-sections01.f90
  flang/test/Semantics/omp-simd01.f90
  flang/test/Semantics/omp-simd02.f90
  flang/test/Semantics/omp-simd03.f90
  flang/test/Semantics/omp-single01.f90
  flang/test/Semantics/omp-single02.f90
  flang/test/Semantics/omp-task01.f90
  flang/test/Semantics/omp-taskloop-simd01.f90
  flang/test/Semantics/omp-taskloop01.f90
  flang/test/Semantics/omp-taskloop02.f90
  flang/test/Semantics/omp-taskloop03.f90
  flang/test/Semantics/omp-workshare01.f90
  flang/test/Semantics/omp-workshare02.f90
  flang/test/Semantics/omp-workshare03.f90
  flang/test/Semantics/omp-workshare04.f90
  flang/test/Semantics/omp-workshare05.f90

Index: flang/test/S

[PATCH] D91054: [Clang][OpenMP] Frontend work for sections - D89671

2021-02-08 Thread Chirag Khandelwal via Phabricator via cfe-commits
AMDChirag added a comment.

@fghanim @jdoerfert please review the code if/when possible.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D91054

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


[clang] e22677b - Reapply "[clang][cli] Report result of ParseLangArgs"

2021-02-08 Thread Jan Svoboda via cfe-commits

Author: Jan Svoboda
Date: 2021-02-08T13:14:43+01:00
New Revision: e22677bbdbdc725463feaa1aa50f179964ce442b

URL: 
https://github.com/llvm/llvm-project/commit/e22677bbdbdc725463feaa1aa50f179964ce442b
DIFF: 
https://github.com/llvm/llvm-project/commit/e22677bbdbdc725463feaa1aa50f179964ce442b.diff

LOG: Reapply "[clang][cli] Report result of ParseLangArgs"

This reverts commit 6039f821 and reapplies bff6d9bb.

Clang's Index/implicit-attrs.m test invokes c-index-test with -fobjc-arc. This 
flag is not compatible with -fobjc-runtime=gcc, which gets implied on Linux.

The original commit uncovered this by correctly reporting issues when parsing 
-cc1 command line.

This commit fixes the test to explicitly provide ObjectiveC runtime compatible 
with ARC.

Added: 


Modified: 
clang/include/clang/Basic/Diagnostic.h
clang/include/clang/Frontend/CompilerInvocation.h
clang/lib/Frontend/CompilerInvocation.cpp
clang/test/Index/implicit-attrs.m

Removed: 




diff  --git a/clang/include/clang/Basic/Diagnostic.h 
b/clang/include/clang/Basic/Diagnostic.h
index 3499c551cfdf..a3cc3af5a74a 100644
--- a/clang/include/clang/Basic/Diagnostic.h
+++ b/clang/include/clang/Basic/Diagnostic.h
@@ -806,6 +806,7 @@ class DiagnosticsEngine : public 
RefCountedBase {
 return FatalErrorOccurred || UnrecoverableErrorOccurred;
   }
 
+  unsigned getNumErrors() const { return NumErrors; }
   unsigned getNumWarnings() const { return NumWarnings; }
 
   void setNumWarnings(unsigned NumWarnings) {

diff  --git a/clang/include/clang/Frontend/CompilerInvocation.h 
b/clang/include/clang/Frontend/CompilerInvocation.h
index 233569aa727b..e880713b71aa 100644
--- a/clang/include/clang/Frontend/CompilerInvocation.h
+++ b/clang/include/clang/Frontend/CompilerInvocation.h
@@ -249,7 +249,7 @@ class CompilerInvocation : public CompilerInvocationBase {
DiagnosticsEngine &Diags);
 
   /// Parse command line options that map to LangOptions.
-  static void ParseLangArgs(LangOptions &Opts, llvm::opt::ArgList &Args,
+  static bool ParseLangArgs(LangOptions &Opts, llvm::opt::ArgList &Args,
 InputKind IK, const llvm::Triple &T,
 std::vector &Includes,
 DiagnosticsEngine &Diags);

diff  --git a/clang/lib/Frontend/CompilerInvocation.cpp 
b/clang/lib/Frontend/CompilerInvocation.cpp
index f4104a35c0fd..e131804b11d1 100644
--- a/clang/lib/Frontend/CompilerInvocation.cpp
+++ b/clang/lib/Frontend/CompilerInvocation.cpp
@@ -2642,10 +2642,12 @@ static void GenerateLangArgs(const LangOptions &Opts,
 GenerateArg(Args, OPT_fdeclare_opencl_builtins, SA);
 }
 
-void CompilerInvocation::ParseLangArgs(LangOptions &Opts, ArgList &Args,
+bool CompilerInvocation::ParseLangArgs(LangOptions &Opts, ArgList &Args,
InputKind IK, const llvm::Triple &T,
std::vector &Includes,
DiagnosticsEngine &Diags) {
+  unsigned NumErrorsBefore = Diags.getNumErrors();
+
   // FIXME: Cleanup per-file based stuff.
   LangStandard::Kind LangStd = LangStandard::lang_unspecified;
   if (const Arg *A = Args.getLastArg(OPT_std_EQ)) {
@@ -3076,6 +3078,8 @@ void CompilerInvocation::ParseLangArgs(LangOptions &Opts, 
ArgList &Args,
   }
 }
   }
+
+  return Success && Diags.getNumErrors() == NumErrorsBefore;
 }
 
 static bool isStrictlyPreprocessorAction(frontend::ActionKind Action) {
@@ -3416,8 +3420,8 @@ bool 
CompilerInvocation::CreateFromArgs(CompilerInvocation &Res,
   } else {
 // Other LangOpts are only initialized when the input is not AST or LLVM 
IR.
 // FIXME: Should we really be calling this for an Language::Asm input?
-ParseLangArgs(LangOpts, Args, DashX, T, Res.getPreprocessorOpts().Includes,
-  Diags);
+Success &= ParseLangArgs(LangOpts, Args, DashX, T,
+ Res.getPreprocessorOpts().Includes, Diags);
 if (Res.getFrontendOpts().ProgramAction == frontend::RewriteObjC)
   LangOpts.ObjCExceptions = 1;
 if (T.isOSDarwin() && DashX.isPreprocessed()) {

diff  --git a/clang/test/Index/implicit-attrs.m 
b/clang/test/Index/implicit-attrs.m
index ca651cdb791f..bd5192d150b3 100644
--- a/clang/test/Index/implicit-attrs.m
+++ b/clang/test/Index/implicit-attrs.m
@@ -2,5 +2,5 @@ @interface Foo
 -(instancetype)init;
 @end
 
-// RUN: env CINDEXTEST_VISIT_IMPLICIT_ATTRIBUTES=1 c-index-test 
-test-print-decl-attributes %s -fobjc-arc | FileCheck %s
+// RUN: env CINDEXTEST_VISIT_IMPLICIT_ATTRIBUTES=1 c-index-test 
-test-print-decl-attributes %s -fobjc-runtime=macosx-10.7 -fobjc-arc | 
FileCheck %s
 // CHECK: ObjCInstanceMethodDecl=init:2:16 attribute(ns_consumes_self)= 
attribute(ns_returns_retained)=



___
cfe-commits mailing list
cfe-commits@lists.llvm.org

[PATCH] D95935: [clang][CodeComplete] Fix crash on ParenListExprs

2021-02-08 Thread Kadir Cetinkaya via Phabricator via cfe-commits
kadircet updated this revision to Diff 322077.
kadircet marked an inline comment as done.
kadircet added a comment.

- Update comments


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D95935

Files:
  clang/lib/Sema/SemaCodeComplete.cpp
  clang/test/CodeCompletion/function-overloads.cpp
  clang/test/CodeCompletion/member-access.c
  clang/unittests/Sema/CodeCompleteTest.cpp


Index: clang/unittests/Sema/CodeCompleteTest.cpp
===
--- clang/unittests/Sema/CodeCompleteTest.cpp
+++ clang/unittests/Sema/CodeCompleteTest.cpp
@@ -488,6 +488,7 @@
 auto y = new decltype(&1)(^);
 // GNU decimal type extension is not supported in clang.
 auto z = new _Decimal128(^);
+void foo() { (void)(foo)(^); }
   )cpp";
   EXPECT_THAT(collectPreferredTypes(Code), Each("NULL TYPE"));
 }
Index: clang/test/CodeCompletion/member-access.c
===
--- clang/test/CodeCompletion/member-access.c
+++ clang/test/CodeCompletion/member-access.c
@@ -29,3 +29,10 @@
 
 // RUN: %clang_cc1 -fsyntax-only -code-completion-with-fixits 
-code-completion-at=%s:24:5 %s -o - | FileCheck -check-prefix=CHECK-CC3 %s
 // CHECK-CC3: x (requires fix-it: {24:4-24:5} to "->")
+
+void test4(struct Point *p) {
+  (int)(p)->x;
+  (int)(0,1,2,3,4,p)->x;
+}
+// RUN: %clang_cc1 -fsyntax-only -code-completion-with-fixits 
-code-completion-at=%s:34:13 %s -o - | FileCheck -check-prefix=CHECK-CC1 %s
+// RUN: %clang_cc1 -fsyntax-only -code-completion-with-fixits 
-code-completion-at=%s:35:23 %s -o - | FileCheck -check-prefix=CHECK-CC1 %s
Index: clang/test/CodeCompletion/function-overloads.cpp
===
--- clang/test/CodeCompletion/function-overloads.cpp
+++ clang/test/CodeCompletion/function-overloads.cpp
@@ -21,6 +21,8 @@
 void test_adl() {
   NS::X x;
   g(x, x);
+  (void)(f)(1, 2, 3);
+  (void)(test, test, test, f)(1, 2, 3);
 }
 
 // RUN: %clang_cc1 -fsyntax-only -code-completion-at=%s:10:9 %s -o - | 
FileCheck -check-prefix=CHECK-CC1 %s
@@ -31,6 +33,10 @@
 // RUN: %clang_cc1 -fsyntax-only -code-completion-at=%s:10:21 %s -o - | 
FileCheck -check-prefix=CHECK-CC4 %s
 // RUN: %clang_cc1 -fsyntax-only -code-completion-at=%s:23:7 %s -o - | \
 // RUN:FileCheck -check-prefix=CHECK-CC5 %s
+// RUN: %clang_cc1 -fsyntax-only -code-completion-at=%s:24:13 %s -o - | \
+// RUN:FileCheck -check-prefix=CHECK-CC1 %s
+// RUN: %clang_cc1 -fsyntax-only -code-completion-at=%s:25:31 %s -o - | \
+// RUN:FileCheck -check-prefix=CHECK-CC1 %s
 // CHECK-CC1: OVERLOAD: [#int#]f(<#float x#>, float y)
 // CHECK-CC1: OVERLOAD: [#int#]f(<#int i#>)
 // CHECK-CC1-NOT, CHECK-CC2-NOT: OVERLOAD: A(
Index: clang/lib/Sema/SemaCodeComplete.cpp
===
--- clang/lib/Sema/SemaCodeComplete.cpp
+++ clang/lib/Sema/SemaCodeComplete.cpp
@@ -5186,6 +5186,15 @@
   if (!Base || !CodeCompleter)
 return;
 
+  // Peel off the ParenListExpr by chosing the last one, as they don't have a
+  // predefined type.
+  if (auto *PLE = llvm::dyn_cast(Base))
+Base = PLE->getExpr(PLE->getNumExprs() - 1);
+  if (OtherOpBase) {
+if (auto *PLE = llvm::dyn_cast(OtherOpBase))
+  OtherOpBase = PLE->getExpr(PLE->getNumExprs() - 1);
+  }
+
   ExprResult ConvertedBase = PerformMemberExprBaseConversion(Base, IsArrow);
   if (ConvertedBase.isInvalid())
 return;
@@ -5615,12 +5624,17 @@
 QualType Sema::ProduceCallSignatureHelp(Scope *S, Expr *Fn,
 ArrayRef Args,
 SourceLocation OpenParLoc) {
-  if (!CodeCompleter)
+  if (!CodeCompleter || !Fn)
 return QualType();
 
+  // If we have a ParenListExpr for LHS, peel it off by chosing the last expr.
+  // As ParenListExprs don't have a predefined type.
+  if (auto *PLE = llvm::dyn_cast(Fn))
+Fn = PLE->getExpr(PLE->getNumExprs() - 1);
+
   // FIXME: Provide support for variadic template functions.
   // Ignore type-dependent call expressions entirely.
-  if (!Fn || Fn->isTypeDependent() || anyNullArguments(Args))
+  if (Fn->isTypeDependent() || anyNullArguments(Args))
 return QualType();
   // In presence of dependent args we surface all possible signatures using the
   // non-dependent args in the prefix. Afterwards we do a post filtering to 
make


Index: clang/unittests/Sema/CodeCompleteTest.cpp
===
--- clang/unittests/Sema/CodeCompleteTest.cpp
+++ clang/unittests/Sema/CodeCompleteTest.cpp
@@ -488,6 +488,7 @@
 auto y = new decltype(&1)(^);
 // GNU decimal type extension is not supported in clang.
 auto z = new _Decimal128(^);
+void foo() { (void)(foo)(^); }
   )cpp";
   EXPECT_THAT(collectPreferredTypes(Code), Each("NULL TYPE"));
 }
Index: clang/test/CodeCompletion/m

[clang] f743184 - [clang][CodeComplete] Fix crash on ParenListExprs

2021-02-08 Thread Kadir Cetinkaya via cfe-commits

Author: Kadir Cetinkaya
Date: 2021-02-08T13:16:49+01:00
New Revision: f74318491134356a19ba2d9673f89c8b74ff3692

URL: 
https://github.com/llvm/llvm-project/commit/f74318491134356a19ba2d9673f89c8b74ff3692
DIFF: 
https://github.com/llvm/llvm-project/commit/f74318491134356a19ba2d9673f89c8b74ff3692.diff

LOG: [clang][CodeComplete] Fix crash on ParenListExprs

Fixes https://github.com/clangd/clangd/issues/676.

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

Added: 


Modified: 
clang/lib/Sema/SemaCodeComplete.cpp
clang/test/CodeCompletion/function-overloads.cpp
clang/test/CodeCompletion/member-access.c
clang/unittests/Sema/CodeCompleteTest.cpp

Removed: 




diff  --git a/clang/lib/Sema/SemaCodeComplete.cpp 
b/clang/lib/Sema/SemaCodeComplete.cpp
index ece204c001e7..2f5a28e132b3 100644
--- a/clang/lib/Sema/SemaCodeComplete.cpp
+++ b/clang/lib/Sema/SemaCodeComplete.cpp
@@ -5186,6 +5186,15 @@ void Sema::CodeCompleteMemberReferenceExpr(Scope *S, 
Expr *Base,
   if (!Base || !CodeCompleter)
 return;
 
+  // Peel off the ParenListExpr by chosing the last one, as they don't have a
+  // predefined type.
+  if (auto *PLE = llvm::dyn_cast(Base))
+Base = PLE->getExpr(PLE->getNumExprs() - 1);
+  if (OtherOpBase) {
+if (auto *PLE = llvm::dyn_cast(OtherOpBase))
+  OtherOpBase = PLE->getExpr(PLE->getNumExprs() - 1);
+  }
+
   ExprResult ConvertedBase = PerformMemberExprBaseConversion(Base, IsArrow);
   if (ConvertedBase.isInvalid())
 return;
@@ -5615,12 +5624,17 @@ ProduceSignatureHelp(Sema &SemaRef, Scope *S,
 QualType Sema::ProduceCallSignatureHelp(Scope *S, Expr *Fn,
 ArrayRef Args,
 SourceLocation OpenParLoc) {
-  if (!CodeCompleter)
+  if (!CodeCompleter || !Fn)
 return QualType();
 
+  // If we have a ParenListExpr for LHS, peel it off by chosing the last expr.
+  // As ParenListExprs don't have a predefined type.
+  if (auto *PLE = llvm::dyn_cast(Fn))
+Fn = PLE->getExpr(PLE->getNumExprs() - 1);
+
   // FIXME: Provide support for variadic template functions.
   // Ignore type-dependent call expressions entirely.
-  if (!Fn || Fn->isTypeDependent() || anyNullArguments(Args))
+  if (Fn->isTypeDependent() || anyNullArguments(Args))
 return QualType();
   // In presence of dependent args we surface all possible signatures using the
   // non-dependent args in the prefix. Afterwards we do a post filtering to 
make

diff  --git a/clang/test/CodeCompletion/function-overloads.cpp 
b/clang/test/CodeCompletion/function-overloads.cpp
index 11c864c28107..7b8ccef1d580 100644
--- a/clang/test/CodeCompletion/function-overloads.cpp
+++ b/clang/test/CodeCompletion/function-overloads.cpp
@@ -21,6 +21,8 @@ namespace NS {
 void test_adl() {
   NS::X x;
   g(x, x);
+  (void)(f)(1, 2, 3);
+  (void)(test, test, test, f)(1, 2, 3);
 }
 
 // RUN: %clang_cc1 -fsyntax-only -code-completion-at=%s:10:9 %s -o - | 
FileCheck -check-prefix=CHECK-CC1 %s
@@ -31,6 +33,10 @@ void test_adl() {
 // RUN: %clang_cc1 -fsyntax-only -code-completion-at=%s:10:21 %s -o - | 
FileCheck -check-prefix=CHECK-CC4 %s
 // RUN: %clang_cc1 -fsyntax-only -code-completion-at=%s:23:7 %s -o - | \
 // RUN:FileCheck -check-prefix=CHECK-CC5 %s
+// RUN: %clang_cc1 -fsyntax-only -code-completion-at=%s:24:13 %s -o - | \
+// RUN:FileCheck -check-prefix=CHECK-CC1 %s
+// RUN: %clang_cc1 -fsyntax-only -code-completion-at=%s:25:31 %s -o - | \
+// RUN:FileCheck -check-prefix=CHECK-CC1 %s
 // CHECK-CC1: OVERLOAD: [#int#]f(<#float x#>, float y)
 // CHECK-CC1: OVERLOAD: [#int#]f(<#int i#>)
 // CHECK-CC1-NOT, CHECK-CC2-NOT: OVERLOAD: A(

diff  --git a/clang/test/CodeCompletion/member-access.c 
b/clang/test/CodeCompletion/member-access.c
index 72afbf2ff947..545349f71731 100644
--- a/clang/test/CodeCompletion/member-access.c
+++ b/clang/test/CodeCompletion/member-access.c
@@ -29,3 +29,10 @@ void test3(struct Point2 *p) {
 
 // RUN: %clang_cc1 -fsyntax-only -code-completion-with-fixits 
-code-completion-at=%s:24:5 %s -o - | FileCheck -check-prefix=CHECK-CC3 %s
 // CHECK-CC3: x (requires fix-it: {24:4-24:5} to "->")
+
+void test4(struct Point *p) {
+  (int)(p)->x;
+  (int)(0,1,2,3,4,p)->x;
+}
+// RUN: %clang_cc1 -fsyntax-only -code-completion-with-fixits 
-code-completion-at=%s:34:13 %s -o - | FileCheck -check-prefix=CHECK-CC1 %s
+// RUN: %clang_cc1 -fsyntax-only -code-completion-with-fixits 
-code-completion-at=%s:35:23 %s -o - | FileCheck -check-prefix=CHECK-CC1 %s

diff  --git a/clang/unittests/Sema/CodeCompleteTest.cpp 
b/clang/unittests/Sema/CodeCompleteTest.cpp
index d8b303d77bb9..dae0793658c5 100644
--- a/clang/unittests/Sema/CodeCompleteTest.cpp
+++ b/clang/unittests/Sema/CodeCompleteTest.cpp
@@ -488,6 +488,7 @@ TEST(PreferredTypeTest, NoCrashOnInvalidTypes) {
 auto y = new decltype(&1)(^);
 // GNU decimal type extension is not supported in clang.
 

[PATCH] D95935: [clang][CodeComplete] Fix crash on ParenListExprs

2021-02-08 Thread Kadir Cetinkaya via Phabricator via cfe-commits
This revision was landed with ongoing or failed builds.
This revision was automatically updated to reflect the committed changes.
Closed by commit rGf74318491134: [clang][CodeComplete] Fix crash on 
ParenListExprs (authored by kadircet).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D95935

Files:
  clang/lib/Sema/SemaCodeComplete.cpp
  clang/test/CodeCompletion/function-overloads.cpp
  clang/test/CodeCompletion/member-access.c
  clang/unittests/Sema/CodeCompleteTest.cpp


Index: clang/unittests/Sema/CodeCompleteTest.cpp
===
--- clang/unittests/Sema/CodeCompleteTest.cpp
+++ clang/unittests/Sema/CodeCompleteTest.cpp
@@ -488,6 +488,7 @@
 auto y = new decltype(&1)(^);
 // GNU decimal type extension is not supported in clang.
 auto z = new _Decimal128(^);
+void foo() { (void)(foo)(^); }
   )cpp";
   EXPECT_THAT(collectPreferredTypes(Code), Each("NULL TYPE"));
 }
Index: clang/test/CodeCompletion/member-access.c
===
--- clang/test/CodeCompletion/member-access.c
+++ clang/test/CodeCompletion/member-access.c
@@ -29,3 +29,10 @@
 
 // RUN: %clang_cc1 -fsyntax-only -code-completion-with-fixits 
-code-completion-at=%s:24:5 %s -o - | FileCheck -check-prefix=CHECK-CC3 %s
 // CHECK-CC3: x (requires fix-it: {24:4-24:5} to "->")
+
+void test4(struct Point *p) {
+  (int)(p)->x;
+  (int)(0,1,2,3,4,p)->x;
+}
+// RUN: %clang_cc1 -fsyntax-only -code-completion-with-fixits 
-code-completion-at=%s:34:13 %s -o - | FileCheck -check-prefix=CHECK-CC1 %s
+// RUN: %clang_cc1 -fsyntax-only -code-completion-with-fixits 
-code-completion-at=%s:35:23 %s -o - | FileCheck -check-prefix=CHECK-CC1 %s
Index: clang/test/CodeCompletion/function-overloads.cpp
===
--- clang/test/CodeCompletion/function-overloads.cpp
+++ clang/test/CodeCompletion/function-overloads.cpp
@@ -21,6 +21,8 @@
 void test_adl() {
   NS::X x;
   g(x, x);
+  (void)(f)(1, 2, 3);
+  (void)(test, test, test, f)(1, 2, 3);
 }
 
 // RUN: %clang_cc1 -fsyntax-only -code-completion-at=%s:10:9 %s -o - | 
FileCheck -check-prefix=CHECK-CC1 %s
@@ -31,6 +33,10 @@
 // RUN: %clang_cc1 -fsyntax-only -code-completion-at=%s:10:21 %s -o - | 
FileCheck -check-prefix=CHECK-CC4 %s
 // RUN: %clang_cc1 -fsyntax-only -code-completion-at=%s:23:7 %s -o - | \
 // RUN:FileCheck -check-prefix=CHECK-CC5 %s
+// RUN: %clang_cc1 -fsyntax-only -code-completion-at=%s:24:13 %s -o - | \
+// RUN:FileCheck -check-prefix=CHECK-CC1 %s
+// RUN: %clang_cc1 -fsyntax-only -code-completion-at=%s:25:31 %s -o - | \
+// RUN:FileCheck -check-prefix=CHECK-CC1 %s
 // CHECK-CC1: OVERLOAD: [#int#]f(<#float x#>, float y)
 // CHECK-CC1: OVERLOAD: [#int#]f(<#int i#>)
 // CHECK-CC1-NOT, CHECK-CC2-NOT: OVERLOAD: A(
Index: clang/lib/Sema/SemaCodeComplete.cpp
===
--- clang/lib/Sema/SemaCodeComplete.cpp
+++ clang/lib/Sema/SemaCodeComplete.cpp
@@ -5186,6 +5186,15 @@
   if (!Base || !CodeCompleter)
 return;
 
+  // Peel off the ParenListExpr by chosing the last one, as they don't have a
+  // predefined type.
+  if (auto *PLE = llvm::dyn_cast(Base))
+Base = PLE->getExpr(PLE->getNumExprs() - 1);
+  if (OtherOpBase) {
+if (auto *PLE = llvm::dyn_cast(OtherOpBase))
+  OtherOpBase = PLE->getExpr(PLE->getNumExprs() - 1);
+  }
+
   ExprResult ConvertedBase = PerformMemberExprBaseConversion(Base, IsArrow);
   if (ConvertedBase.isInvalid())
 return;
@@ -5615,12 +5624,17 @@
 QualType Sema::ProduceCallSignatureHelp(Scope *S, Expr *Fn,
 ArrayRef Args,
 SourceLocation OpenParLoc) {
-  if (!CodeCompleter)
+  if (!CodeCompleter || !Fn)
 return QualType();
 
+  // If we have a ParenListExpr for LHS, peel it off by chosing the last expr.
+  // As ParenListExprs don't have a predefined type.
+  if (auto *PLE = llvm::dyn_cast(Fn))
+Fn = PLE->getExpr(PLE->getNumExprs() - 1);
+
   // FIXME: Provide support for variadic template functions.
   // Ignore type-dependent call expressions entirely.
-  if (!Fn || Fn->isTypeDependent() || anyNullArguments(Args))
+  if (Fn->isTypeDependent() || anyNullArguments(Args))
 return QualType();
   // In presence of dependent args we surface all possible signatures using the
   // non-dependent args in the prefix. Afterwards we do a post filtering to 
make


Index: clang/unittests/Sema/CodeCompleteTest.cpp
===
--- clang/unittests/Sema/CodeCompleteTest.cpp
+++ clang/unittests/Sema/CodeCompleteTest.cpp
@@ -488,6 +488,7 @@
 auto y = new decltype(&1)(^);
 // GNU decimal type extension is not supported in clang.
 auto z = new _Decimal128(^);
+void foo() { (void)(foo)(^); }
   )cpp";

[PATCH] D95915: [clang][driver] Only warn once about invalid -stdlib value

2021-02-08 Thread Timm Bäder via Phabricator via cfe-commits
tbaeder updated this revision to Diff 322082.
tbaeder added a comment.

Switched to `llvm::Optional` and added some tests


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

https://reviews.llvm.org/D95915

Files:
  clang/include/clang/Driver/ToolChain.h
  clang/lib/Driver/ToolChain.cpp
  clang/test/Driver/undefined-libs.cpp

Index: clang/test/Driver/undefined-libs.cpp
===
--- /dev/null
+++ clang/test/Driver/undefined-libs.cpp
@@ -0,0 +1,15 @@
+
+// Check that all the following options print a warning when given a non-existent
+// value. But only one warning.
+
+// RUN: not %clangxx -stdlib=nostdlib %s 2>&1 | FileCheck --check-prefix=STDLIB %s
+// STDLIB: error: invalid library name in argument '-stdlib=nostdlib'
+// STDLIB-EMPTY:
+//
+// RUN: not %clangxx -rtlib=nortlib %s 2>&1 | FileCheck --check-prefix=RTLIB %s
+// RTLIB: error: invalid runtime library name in argument '-rtlib=nortlib'
+// RTLIB-EMPTY:
+//
+// RUN: not %clangxx -unwindlib=nounwindlib %s 2>&1 | FileCheck --check-prefix=UNWINDLIB %s
+// UNWINDLIB: error: invalid unwind library name in argument '-unwindlib=nounwindlib'
+// UNWINDLIB-EMPTY:
Index: clang/lib/Driver/ToolChain.cpp
===
--- clang/lib/Driver/ToolChain.cpp
+++ clang/lib/Driver/ToolChain.cpp
@@ -884,66 +884,86 @@
 
 ToolChain::RuntimeLibType ToolChain::GetRuntimeLibType(
 const ArgList &Args) const {
+  if (runtimeLibType)
+return *runtimeLibType;
+
   const Arg* A = Args.getLastArg(options::OPT_rtlib_EQ);
   StringRef LibName = A ? A->getValue() : CLANG_DEFAULT_RTLIB;
 
   // Only use "platform" in tests to override CLANG_DEFAULT_RTLIB!
   if (LibName == "compiler-rt")
-return ToolChain::RLT_CompilerRT;
+runtimeLibType = ToolChain::RLT_CompilerRT;
   else if (LibName == "libgcc")
-return ToolChain::RLT_Libgcc;
+runtimeLibType = ToolChain::RLT_Libgcc;
   else if (LibName == "platform")
-return GetDefaultRuntimeLibType();
+runtimeLibType = GetDefaultRuntimeLibType();
+  else {
+if (A)
+  getDriver().Diag(diag::err_drv_invalid_rtlib_name)
+  << A->getAsString(Args);
 
-  if (A)
-getDriver().Diag(diag::err_drv_invalid_rtlib_name) << A->getAsString(Args);
+runtimeLibType = GetDefaultRuntimeLibType();
+  }
 
-  return GetDefaultRuntimeLibType();
+  return *runtimeLibType;
 }
 
 ToolChain::UnwindLibType ToolChain::GetUnwindLibType(
 const ArgList &Args) const {
+  if (unwindLibType)
+return *unwindLibType;
+
   const Arg *A = Args.getLastArg(options::OPT_unwindlib_EQ);
   StringRef LibName = A ? A->getValue() : CLANG_DEFAULT_UNWINDLIB;
 
   if (LibName == "none")
-return ToolChain::UNW_None;
+unwindLibType = ToolChain::UNW_None;
   else if (LibName == "platform" || LibName == "") {
 ToolChain::RuntimeLibType RtLibType = GetRuntimeLibType(Args);
 if (RtLibType == ToolChain::RLT_CompilerRT)
-  return ToolChain::UNW_None;
+  unwindLibType = ToolChain::UNW_None;
 else if (RtLibType == ToolChain::RLT_Libgcc)
-  return ToolChain::UNW_Libgcc;
+  unwindLibType = ToolChain::UNW_Libgcc;
   } else if (LibName == "libunwind") {
 if (GetRuntimeLibType(Args) == RLT_Libgcc)
   getDriver().Diag(diag::err_drv_incompatible_unwindlib);
-return ToolChain::UNW_CompilerRT;
+unwindLibType = ToolChain::UNW_CompilerRT;
   } else if (LibName == "libgcc")
-return ToolChain::UNW_Libgcc;
+unwindLibType = ToolChain::UNW_Libgcc;
+  else {
+if (A)
+  getDriver().Diag(diag::err_drv_invalid_unwindlib_name)
+  << A->getAsString(Args);
 
-  if (A)
-getDriver().Diag(diag::err_drv_invalid_unwindlib_name)
-<< A->getAsString(Args);
+unwindLibType = GetDefaultUnwindLibType();
+  }
 
-  return GetDefaultUnwindLibType();
+  return *unwindLibType;
 }
 
 ToolChain::CXXStdlibType ToolChain::GetCXXStdlibType(const ArgList &Args) const{
+  if (cxxStdlibType)
+return *cxxStdlibType;
+
   const Arg *A = Args.getLastArg(options::OPT_stdlib_EQ);
   StringRef LibName = A ? A->getValue() : CLANG_DEFAULT_CXX_STDLIB;
 
   // Only use "platform" in tests to override CLANG_DEFAULT_CXX_STDLIB!
   if (LibName == "libc++")
-return ToolChain::CST_Libcxx;
+cxxStdlibType = ToolChain::CST_Libcxx;
   else if (LibName == "libstdc++")
-return ToolChain::CST_Libstdcxx;
+cxxStdlibType = ToolChain::CST_Libstdcxx;
   else if (LibName == "platform")
-return GetDefaultCXXStdlibType();
+cxxStdlibType = GetDefaultCXXStdlibType();
+  else {
+if (A)
+  getDriver().Diag(diag::err_drv_invalid_stdlib_name)
+  << A->getAsString(Args);
 
-  if (A)
-getDriver().Diag(diag::err_drv_invalid_stdlib_name) << A->getAsString(Args);
+cxxStdlibType = GetDefaultCXXStdlibType();
+  }
 
-  return GetDefaultCXXStdlibType();
+  return *cxxStdlibType;
 }
 
 /// Utility function to add a system include directory to CC1 arguments.
Index: cla

[clang] 9083d0a - Revert "[Sema] Fix -Warray-bounds false negative when casting an out-of-bounds array item"

2021-02-08 Thread via cfe-commits

Author: einvbri
Date: 2021-02-08T06:38:31-06:00
New Revision: 9083d0a40d980928f2f45236a4616528a7ab19ce

URL: 
https://github.com/llvm/llvm-project/commit/9083d0a40d980928f2f45236a4616528a7ab19ce
DIFF: 
https://github.com/llvm/llvm-project/commit/9083d0a40d980928f2f45236a4616528a7ab19ce.diff

LOG: Revert "[Sema] Fix -Warray-bounds false negative when casting an 
out-of-bounds array item"

This reverts commit e48f444751cf781c42934b242b81f549da77bad0.

thakis noticed false reports, so reverting this change for now until
those can be sorted out.

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

Added: 


Modified: 
clang/include/clang/Sema/Sema.h
clang/lib/Sema/SemaChecking.cpp
clang/test/Parser/cxx-ambig-decl-expr.cpp
clang/test/SemaCXX/array-bounds.cpp

Removed: 




diff  --git a/clang/include/clang/Sema/Sema.h b/clang/include/clang/Sema/Sema.h
index 68420fcbb85f..8b5619945865 100644
--- a/clang/include/clang/Sema/Sema.h
+++ b/clang/include/clang/Sema/Sema.h
@@ -12313,7 +12313,7 @@ class Sema final {
   void CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
 const ArraySubscriptExpr *ASE=nullptr,
 bool AllowOnePastEnd=true, bool IndexNegated=false);
-  void CheckArrayAccess(const Expr *E, int AllowOnePastEnd = 0);
+  void CheckArrayAccess(const Expr *E);
   // Used to grab the relevant information from a FormatAttr and a
   // FunctionDeclaration.
   struct FormatStringInfo {

diff  --git a/clang/lib/Sema/SemaChecking.cpp b/clang/lib/Sema/SemaChecking.cpp
index 17dd5c9e8d99..2d3d36f4adad 100644
--- a/clang/lib/Sema/SemaChecking.cpp
+++ b/clang/lib/Sema/SemaChecking.cpp
@@ -14387,63 +14387,62 @@ void Sema::CheckArrayAccess(const Expr *BaseExpr, 
const Expr *IndexExpr,
 PDiag(diag::note_array_declared_here) << ND);
 }
 
-void Sema::CheckArrayAccess(const Expr *expr, int AllowOnePastEnd) {
-  if (!expr)
-return;
-
-  expr = expr->IgnoreParenCasts();
-  switch (expr->getStmtClass()) {
-  case Stmt::ArraySubscriptExprClass: {
-const ArraySubscriptExpr *ASE = cast(expr);
-CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE, AllowOnePastEnd > 0);
-CheckArrayAccess(ASE->getBase(), AllowOnePastEnd);
-return;
-  }
-  case Stmt::MemberExprClass: {
-expr = cast(expr)->getBase();
-CheckArrayAccess(expr, /*AllowOnePastEnd=*/0);
-return;
-  }
-  case Stmt::OMPArraySectionExprClass: {
-const OMPArraySectionExpr *ASE = cast(expr);
-if (ASE->getLowerBound())
-  CheckArrayAccess(ASE->getBase(), ASE->getLowerBound(),
-   /*ASE=*/nullptr, AllowOnePastEnd > 0);
-return;
-  }
-  case Stmt::UnaryOperatorClass: {
-// Only unwrap the * and & unary operators
-const UnaryOperator *UO = cast(expr);
-expr = UO->getSubExpr();
-switch (UO->getOpcode()) {
-case UO_AddrOf:
-  AllowOnePastEnd++;
-  break;
-case UO_Deref:
-  AllowOnePastEnd--;
-  break;
-default:
-  return;
+void Sema::CheckArrayAccess(const Expr *expr) {
+  int AllowOnePastEnd = 0;
+  while (expr) {
+expr = expr->IgnoreParenImpCasts();
+switch (expr->getStmtClass()) {
+  case Stmt::ArraySubscriptExprClass: {
+const ArraySubscriptExpr *ASE = cast(expr);
+CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE,
+ AllowOnePastEnd > 0);
+expr = ASE->getBase();
+break;
+  }
+  case Stmt::MemberExprClass: {
+expr = cast(expr)->getBase();
+break;
+  }
+  case Stmt::OMPArraySectionExprClass: {
+const OMPArraySectionExpr *ASE = cast(expr);
+if (ASE->getLowerBound())
+  CheckArrayAccess(ASE->getBase(), ASE->getLowerBound(),
+   /*ASE=*/nullptr, AllowOnePastEnd > 0);
+return;
+  }
+  case Stmt::UnaryOperatorClass: {
+// Only unwrap the * and & unary operators
+const UnaryOperator *UO = cast(expr);
+expr = UO->getSubExpr();
+switch (UO->getOpcode()) {
+  case UO_AddrOf:
+AllowOnePastEnd++;
+break;
+  case UO_Deref:
+AllowOnePastEnd--;
+break;
+  default:
+return;
+}
+break;
+  }
+  case Stmt::ConditionalOperatorClass: {
+const ConditionalOperator *cond = cast(expr);
+if (const Expr *lhs = cond->getLHS())
+  CheckArrayAccess(lhs);
+if (const Expr *rhs = cond->getRHS())
+  CheckArrayAccess(rhs);
+return;
+  }
+  case Stmt::CXXOperatorCallExprClass: {
+const auto *OCE = cast(expr);
+for (const auto *Arg : OCE->arguments())
+  CheckArrayAccess(Arg);
+return;
+  }
+  default:
+return;
 }
-CheckArrayAccess(expr, AllowOnePastEnd);
-return;
-  }
-  case Stmt::ConditionalOperatorClass: {
-const C

[PATCH] D96248: [OpenMP][AMDGPU] Add support for linking libomptarget bitcode

2021-02-08 Thread Jon Chesterfield via Phabricator via cfe-commits
JonChesterfield added a comment.

I like this. Using the same logic, in the same function call, to find this 
library on either gpu is the right thing to do. Looks like a non functional 
change on nvptx, though phab doesn't make that obvious.




Comment at: clang/include/clang/Driver/Options.td:935
   HelpText<"Path to libomptarget-nvptx bitcode library">;
+def libomptarget_device_bc_path_EQ : Joined<["--"], 
"libomptarget-device-bc-path=">, Group,
+  HelpText<"Path to libomptarget bitcode library">;

I think there's an aliasing mechanism in the Options handling, where we can use 
device_bc_path as the canonical choice and nvptx_bc_path as a 
backwards-compatible argument that sets device_bc_path 



Comment at: clang/lib/Driver/ToolChains/CommonArgs.cpp:1655
+  DriverArgs.getLastArg(options::OPT_libomptarget_nvptx_bc_path_EQ,
+options::OPT_libomptarget_device_bc_path_EQ)) {
+std::string LibOmpTargetName(A->getValue());

This, I think, can be reduced to checking OPT_libomptarget_device_bc_path_EQ if 
the aliasing machinery I remember does actually exist


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D96248

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


[PATCH] D96161: [OpenCL] Fix printing of types with signed prefix in arg info metadata

2021-02-08 Thread Anastasia Stulova via Phabricator via cfe-commits
Anastasia updated this revision to Diff 322087.
Anastasia added a comment.

Use char instead of int in the test.


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

https://reviews.llvm.org/D96161

Files:
  clang/lib/CodeGen/CodeGenModule.cpp
  clang/test/CodeGenOpenCL/kernel-arg-info.cl


Index: clang/test/CodeGenOpenCL/kernel-arg-info.cl
===
--- clang/test/CodeGenOpenCL/kernel-arg-info.cl
+++ clang/test/CodeGenOpenCL/kernel-arg-info.cl
@@ -107,6 +107,16 @@
 // CHECK-NOT: !kernel_arg_name
 // ARGINFO: !kernel_arg_name ![[PIPE_ARG_NAMES:[0-9]+]]
 
+kernel void foo9(signed char si1,  global const signed char* si2) {}
+// CHECK: define{{.*}} spir_kernel void @foo9{{[^!]+}}
+// CHECK: !kernel_arg_addr_space ![[SINT_AS_QUAL:[0-9]+]]
+// CHECK: !kernel_arg_access_qual ![[MD42]]
+// CHECK: !kernel_arg_type ![[SINT_TY:[0-9]+]]
+// CHECK: !kernel_arg_base_type ![[SINT_TY]]
+// CHECK: !kernel_arg_type_qual ![[SINT_QUAL:[0-9]+]]
+// CHECK-NOT: !kernel_arg_name
+// ARGINFO: !kernel_arg_name ![[SINT_ARG_NAMES:[0-9]+]]
+
 // CHECK: ![[MD11]] = !{i32 1, i32 1, i32 1, i32 1, i32 2, i32 2, i32 1, i32 
1, i32 1, i32 1, i32 3, i32 3, i32 3, i32 3, i32 3, i32 3, i32 3, i32 3, i32 0, 
i32 0, i32 0, i32 0}
 // CHECK: ![[MD12]] = !{!"none", !"none", !"none", !"none", !"none", !"none", 
!"none", !"none", !"none", !"none", !"none", !"none", !"none", !"none", 
!"none", !"none", !"none", !"none", !"none", !"none", !"none", !"none"}
 // CHECK: ![[MD13]] = !{!"int*", !"int*", !"int*", !"int*", !"int*", !"int*", 
!"int*", !"int*", !"int*", !"int*", !"int*", !"int*", !"int*", !"int*", 
!"int*", !"int*", !"int*", !"int*", !"int", !"int", !"int", !"int"}
@@ -146,3 +156,7 @@
 // CHECK: ![[PIPE_BASE_TY]] = !{!"int", !"uchar", !"uchar 
__attribute__((ext_vector_type(2)))", !"uchar", !"uchar"}
 // CHECK: ![[PIPE_QUAL]] = !{!"pipe", !"pipe", !"pipe", !"pipe", !"pipe"}
 // ARGINFO: ![[PIPE_ARG_NAMES]] = !{!"p1", !"p2", !"p3", !"p4", !"p5"}
+// CHECK: ![[SINT_AS_QUAL]] = !{i32 0, i32 1}
+// CHECK: ![[SINT_TY]] = !{!"char", !"char*"}
+// CHECK: ![[SINT_QUAL]] = !{!"", !"const"}
+// ARGINFO: ![[SINT_ARG_NAMES]] = !{!"si1", !"si2"}
Index: clang/lib/CodeGen/CodeGenModule.cpp
===
--- clang/lib/CodeGen/CodeGenModule.cpp
+++ clang/lib/CodeGen/CodeGenModule.cpp
@@ -1501,6 +1501,8 @@
   // Turn "unsigned type" to "utype"
   if (typeNameRef.consume_front("unsigned "))
 return std::string("u") + typeNameRef.str();
+  if (typeNameRef.consume_front("signed "))
+return typeNameRef.str();
 }
 
 return typeName;


Index: clang/test/CodeGenOpenCL/kernel-arg-info.cl
===
--- clang/test/CodeGenOpenCL/kernel-arg-info.cl
+++ clang/test/CodeGenOpenCL/kernel-arg-info.cl
@@ -107,6 +107,16 @@
 // CHECK-NOT: !kernel_arg_name
 // ARGINFO: !kernel_arg_name ![[PIPE_ARG_NAMES:[0-9]+]]
 
+kernel void foo9(signed char si1,  global const signed char* si2) {}
+// CHECK: define{{.*}} spir_kernel void @foo9{{[^!]+}}
+// CHECK: !kernel_arg_addr_space ![[SINT_AS_QUAL:[0-9]+]]
+// CHECK: !kernel_arg_access_qual ![[MD42]]
+// CHECK: !kernel_arg_type ![[SINT_TY:[0-9]+]]
+// CHECK: !kernel_arg_base_type ![[SINT_TY]]
+// CHECK: !kernel_arg_type_qual ![[SINT_QUAL:[0-9]+]]
+// CHECK-NOT: !kernel_arg_name
+// ARGINFO: !kernel_arg_name ![[SINT_ARG_NAMES:[0-9]+]]
+
 // CHECK: ![[MD11]] = !{i32 1, i32 1, i32 1, i32 1, i32 2, i32 2, i32 1, i32 1, i32 1, i32 1, i32 3, i32 3, i32 3, i32 3, i32 3, i32 3, i32 3, i32 3, i32 0, i32 0, i32 0, i32 0}
 // CHECK: ![[MD12]] = !{!"none", !"none", !"none", !"none", !"none", !"none", !"none", !"none", !"none", !"none", !"none", !"none", !"none", !"none", !"none", !"none", !"none", !"none", !"none", !"none", !"none", !"none"}
 // CHECK: ![[MD13]] = !{!"int*", !"int*", !"int*", !"int*", !"int*", !"int*", !"int*", !"int*", !"int*", !"int*", !"int*", !"int*", !"int*", !"int*", !"int*", !"int*", !"int*", !"int*", !"int", !"int", !"int", !"int"}
@@ -146,3 +156,7 @@
 // CHECK: ![[PIPE_BASE_TY]] = !{!"int", !"uchar", !"uchar __attribute__((ext_vector_type(2)))", !"uchar", !"uchar"}
 // CHECK: ![[PIPE_QUAL]] = !{!"pipe", !"pipe", !"pipe", !"pipe", !"pipe"}
 // ARGINFO: ![[PIPE_ARG_NAMES]] = !{!"p1", !"p2", !"p3", !"p4", !"p5"}
+// CHECK: ![[SINT_AS_QUAL]] = !{i32 0, i32 1}
+// CHECK: ![[SINT_TY]] = !{!"char", !"char*"}
+// CHECK: ![[SINT_QUAL]] = !{!"", !"const"}
+// ARGINFO: ![[SINT_ARG_NAMES]] = !{!"si1", !"si2"}
Index: clang/lib/CodeGen/CodeGenModule.cpp
===
--- clang/lib/CodeGen/CodeGenModule.cpp
+++ clang/lib/CodeGen/CodeGenModule.cpp
@@ -1501,6 +1501,8 @@
   // Turn "unsigned type" to "utype"
   if (typeNameRef.consume_front("unsigned "))
 return std::string("u") + typeNameRef.str();
+  if (typeN

[PATCH] D96248: [OpenMP][AMDGPU] Add support for linking libomptarget bitcode

2021-02-08 Thread Pushpinder Singh via Phabricator via cfe-commits
pdhaliwal updated this revision to Diff 322090.
pdhaliwal added a comment.

Addressed review comments.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D96248

Files:
  clang/include/clang/Driver/Options.td
  clang/lib/Driver/ToolChains/AMDGPUOpenMP.cpp
  clang/lib/Driver/ToolChains/CommonArgs.cpp
  clang/lib/Driver/ToolChains/CommonArgs.h
  clang/lib/Driver/ToolChains/Cuda.cpp
  clang/test/Driver/Inputs/hip_dev_lib/libomptarget-amdgcn-gfx803.bc
  clang/test/Driver/Inputs/hip_dev_lib/libomptarget-amdgcn-gfx906.bc
  clang/test/Driver/amdgpu-openmp-toolchain.c

Index: clang/test/Driver/amdgpu-openmp-toolchain.c
===
--- clang/test/Driver/amdgpu-openmp-toolchain.c
+++ clang/test/Driver/amdgpu-openmp-toolchain.c
@@ -1,11 +1,11 @@
 // REQUIRES: amdgpu-registered-target
-// RUN:   %clang -### --target=x86_64-unknown-linux-gnu -fopenmp -fopenmp-targets=amdgcn-amd-amdhsa -Xopenmp-target=amdgcn-amd-amdhsa -march=gfx906 %s 2>&1 \
+// RUN:   env LIBRARY_PATH=%S/Inputs/hip_dev_lib %clang -### --target=x86_64-unknown-linux-gnu -fopenmp -fopenmp-targets=amdgcn-amd-amdhsa -Xopenmp-target=amdgcn-amd-amdhsa -march=gfx906 %s 2>&1 \
 // RUN:   | FileCheck %s
 
 // verify the tools invocations
 // CHECK: clang{{.*}}"-cc1" "-triple" "x86_64-unknown-linux-gnu"{{.*}}"-x" "c"{{.*}}
 // CHECK: clang{{.*}}"-cc1" "-triple" "x86_64-unknown-linux-gnu"{{.*}}"-x" "ir"{{.*}}
-// CHECK: clang{{.*}}"-cc1"{{.*}}"-triple" "amdgcn-amd-amdhsa"{{.*}}"-target-cpu" "gfx906" "-fcuda-is-device" "-emit-llvm-bc"{{.*}}
+// CHECK: clang{{.*}}"-cc1"{{.*}}"-triple" "amdgcn-amd-amdhsa"{{.*}}"-target-cpu" "gfx906" "-fcuda-is-device" "-emit-llvm-bc" "-mlink-builtin-bitcode"{{.*}}libomptarget-amdgcn-gfx906.bc"{{.*}}
 // CHECK: llvm-link{{.*}}"-o" "{{.*}}amdgpu-openmp-toolchain-{{.*}}-gfx906-linked-{{.*}}.bc"
 // CHECK: llc{{.*}}amdgpu-openmp-toolchain-{{.*}}-gfx906-linked-{{.*}}.bc" "-mtriple=amdgcn-amd-amdhsa" "-mcpu=gfx906" "-filetype=obj" "-o"{{.*}}amdgpu-openmp-toolchain-{{.*}}-gfx906-{{.*}}.o"
 // CHECK: lld{{.*}}"-flavor" "gnu" "--no-undefined" "-shared" "-o"{{.*}}amdgpu-openmp-toolchain-{{.*}}.out" "{{.*}}amdgpu-openmp-toolchain-{{.*}}-gfx906-{{.*}}.o"
@@ -34,3 +34,7 @@
 // CHECK-PHASES: 15: assembler, {14}, object, (host-openmp)
 // CHECK-PHASES: 16: linker, {4, 15}, image, (host-openmp)
 
+// handling of --libomptarget-device-bc-path
+// RUN:   %clang -### --target=x86_64-unknown-linux-gnu -fopenmp -fopenmp-targets=amdgcn-amd-amdhsa -Xopenmp-target=amdgcn-amd-amdhsa -march=gfx803 --libomptarget-device-bc-path=%S/Inputs/hip_dev_lib/libomptarget-amdgcn-gfx803.bc %s 2>&1 | FileCheck %s --check-prefix=CHECK-LIBOMPTARGET
+// CHECK-LIBOMPTARGET: clang{{.*}}"-cc1"{{.*}}"-triple" "amdgcn-amd-amdhsa"{{.*}}"-target-cpu" "gfx803" "-fcuda-is-device" "-emit-llvm-bc" "-mlink-builtin-bitcode"{{.*}}Inputs/hip_dev_lib/libomptarget-amdgcn-gfx803.bc"{{.*}}
+
Index: clang/lib/Driver/ToolChains/Cuda.cpp
===
--- clang/lib/Driver/ToolChains/Cuda.cpp
+++ clang/lib/Driver/ToolChains/Cuda.cpp
@@ -749,56 +749,9 @@
 CudaVersionToString(CudaInstallation.version(;
 
   if (DeviceOffloadingKind == Action::OFK_OpenMP) {
-SmallVector LibraryPaths;
-// Add user defined library paths from LIBRARY_PATH.
-llvm::Optional LibPath =
-llvm::sys::Process::GetEnv("LIBRARY_PATH");
-if (LibPath) {
-  SmallVector Frags;
-  const char EnvPathSeparatorStr[] = {llvm::sys::EnvPathSeparator, '\0'};
-  llvm::SplitString(*LibPath, Frags, EnvPathSeparatorStr);
-  for (StringRef Path : Frags)
-LibraryPaths.emplace_back(Path.trim());
-}
-
-// Add path to lib / lib64 folder.
-SmallString<256> DefaultLibPath =
-llvm::sys::path::parent_path(getDriver().Dir);
-llvm::sys::path::append(DefaultLibPath, Twine("lib") + CLANG_LIBDIR_SUFFIX);
-LibraryPaths.emplace_back(DefaultLibPath.c_str());
-
-// First check whether user specifies bc library
-if (const Arg *A =
-DriverArgs.getLastArg(options::OPT_libomptarget_nvptx_bc_path_EQ)) {
-  std::string LibOmpTargetName(A->getValue());
-  if (llvm::sys::fs::exists(LibOmpTargetName)) {
-CC1Args.push_back("-mlink-builtin-bitcode");
-CC1Args.push_back(DriverArgs.MakeArgString(LibOmpTargetName));
-  } else {
-getDriver().Diag(diag::err_drv_omp_offload_target_bcruntime_not_found)
-<< LibOmpTargetName;
-  }
-} else {
-  bool FoundBCLibrary = false;
-
-  std::string LibOmpTargetName = "libomptarget-nvptx-cuda_" +
- CudaVersionStr + "-" + GpuArch.str() +
- ".bc";
-
-  for (StringRef LibraryPath : LibraryPaths) {
-SmallString<128> LibOmpTargetFile(LibraryPath);
-llvm::sys::path::append(LibOmpTargetFile, LibOmpTarge

[PATCH] D95877: [analyzer] Fix static_cast on pointer-to-member handling

2021-02-08 Thread Deep Majumder via Phabricator via cfe-commits
RedDocMD updated this revision to Diff 322094.
RedDocMD added a comment.

Moved failing test of reinterpret_cast to its own file, marked to failx


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D95877

Files:
  clang/include/clang/StaticAnalyzer/Core/PathSensitive/BasicValueFactory.h
  clang/include/clang/StaticAnalyzer/Core/PathSensitive/SVals.h
  clang/lib/StaticAnalyzer/Core/BasicValueFactory.cpp
  clang/lib/StaticAnalyzer/Core/ExprEngineC.cpp
  clang/test/Analysis/pointer-to-member.cpp
  clang/test/Analysis/reinterpret-cast-pointer-to-member.cpp

Index: clang/test/Analysis/reinterpret-cast-pointer-to-member.cpp
===
--- /dev/null
+++ clang/test/Analysis/reinterpret-cast-pointer-to-member.cpp
@@ -0,0 +1,26 @@
+// RUN: %clang_analyze_cc1 -analyzer-checker=core,debug.ExprInspection -verify %s
+// XFAIL: *
+
+void clang_analyzer_eval(bool);
+
+// TODO: The following test will work properly once reinterpret_cast on pointer-to-member is handled properly
+namespace testReinterpretCasting {
+struct Base {
+  int field;
+};
+
+struct Derived : public Base {};
+
+struct DoubleDerived : public Derived {};
+
+struct Some {};
+
+void f() {
+  int DoubleDerived::*ddf = &Base::field;
+  int Base::*bf = reinterpret_cast(reinterpret_cast(reinterpret_cast(ddf)));
+  int Some::*sf = reinterpret_cast(ddf);
+  Base base;
+  base.field = 13;
+  clang_analyzer_eval(base.*bf == 13); // expected-warning{{TRUE}}
+}
+} // namespace testReinterpretCasting
Index: clang/test/Analysis/pointer-to-member.cpp
===
--- clang/test/Analysis/pointer-to-member.cpp
+++ clang/test/Analysis/pointer-to-member.cpp
@@ -287,3 +287,26 @@
   clang_analyzer_eval(a.*ep == 5); // expected-warning{{TRUE}}
 }
 } // namespace testAnonymousMember
+
+namespace testStaticCasting {
+// From bug #48739
+struct Grandfather {
+  int field;
+};
+
+struct Father : public Grandfather {};
+struct Son : public Father {};
+
+void test() {
+  int Son::*sf = &Son::field;
+  Grandfather grandpa;
+  grandpa.field = 10;
+  int Grandfather::*gpf1 = static_cast(sf);
+  int Grandfather::*gpf2 = static_cast(static_cast(sf));
+  int Grandfather::*gpf3 = static_cast(static_cast(static_cast(sf)));
+  clang_analyzer_eval(grandpa.*gpf1 == 10); // expected-warning{{TRUE}}
+  clang_analyzer_eval(grandpa.*gpf2 == 10); // expected-warning{{TRUE}}
+  clang_analyzer_eval(grandpa.*gpf3 == 10); // expected-warning{{TRUE}}
+}
+} // namespace testStaticCasting
+
Index: clang/lib/StaticAnalyzer/Core/ExprEngineC.cpp
===
--- clang/lib/StaticAnalyzer/Core/ExprEngineC.cpp
+++ clang/lib/StaticAnalyzer/Core/ExprEngineC.cpp
@@ -526,10 +526,9 @@
   case CK_ReinterpretMemberPointer: {
 SVal V = state->getSVal(Ex, LCtx);
 if (auto PTMSV = V.getAs()) {
-  SVal CastedPTMSV = svalBuilder.makePointerToMember(
-  getBasicVals().accumCXXBase(
-  llvm::make_range(
-  CastE->path_begin(), CastE->path_end()), *PTMSV));
+  SVal CastedPTMSV =
+  svalBuilder.makePointerToMember(getBasicVals().accumCXXBase(
+  CastE->path(), *PTMSV, CastE->getCastKind()));
   state = state->BindExpr(CastE, LCtx, CastedPTMSV);
   Bldr.generateNode(CastE, Pred, state);
   continue;
Index: clang/lib/StaticAnalyzer/Core/BasicValueFactory.cpp
===
--- clang/lib/StaticAnalyzer/Core/BasicValueFactory.cpp
+++ clang/lib/StaticAnalyzer/Core/BasicValueFactory.cpp
@@ -21,6 +21,7 @@
 #include "llvm/ADT/FoldingSet.h"
 #include "llvm/ADT/ImmutableList.h"
 #include "llvm/ADT/STLExtras.h"
+#include "llvm/ADT/SmallPtrSet.h"
 #include 
 #include 
 #include 
@@ -176,28 +177,73 @@
   return D;
 }
 
+LLVM_ATTRIBUTE_UNUSED bool hasNoRepeatedElements(
+llvm::ImmutableList BaseSpecList) {
+  llvm::SmallPtrSet BaseSpecSeen;
+  for (const CXXBaseSpecifier *BaseSpec : BaseSpecList) {
+QualType BaseType = BaseSpec->getType();
+// Check whether inserted
+if (!BaseSpecSeen.insert(BaseType).second)
+  return false;
+  }
+  return true;
+}
+
 const PointerToMemberData *BasicValueFactory::accumCXXBase(
 llvm::iterator_range PathRange,
-const nonloc::PointerToMember &PTM) {
+const nonloc::PointerToMember &PTM, const CastKind &kind) {
+  assert((kind == CK_DerivedToBaseMemberPointer ||
+  kind == CK_BaseToDerivedMemberPointer ||
+  kind == CK_ReinterpretMemberPointer) &&
+ "accumCXXBase called with wrong CastKind");
   nonloc::PointerToMember::PTMDataType PTMDT = PTM.getPTMData();
   const NamedDecl *ND = nullptr;
-  llvm::ImmutableList PathList;
+  llvm::ImmutableList BaseSpecList;
 
   if (PTMDT.isNull() || PTMDT.is()) {
 if (PTMDT.is())

[PATCH] D95877: [analyzer] Fix static_cast on pointer-to-member handling

2021-02-08 Thread Deep Majumder via Phabricator via cfe-commits
RedDocMD added a comment.

In D95877#2548027 , @vsavchenko wrote:

> Yes, it'd be better to extract this case into a separate file and mark it as 
> XFAIL

Done that.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D95877

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


[PATCH] D96261: [Syntax] Remove a strict valid source location assertion for TypeLoc.

2021-02-08 Thread Haojian Wu via Phabricator via cfe-commits
hokein created this revision.
hokein added a reviewer: sammccall.
hokein requested review of this revision.
Herald added a project: clang.

The EndLoc of a type loc can be invalid for broken code.

Also extend the existing test to support error code with `error-ok`
annotation.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D96261

Files:
  clang/lib/Tooling/Syntax/BuildTree.cpp
  clang/unittests/Tooling/Syntax/BuildTreeTest.cpp


Index: clang/unittests/Tooling/Syntax/BuildTreeTest.cpp
===
--- clang/unittests/Tooling/Syntax/BuildTreeTest.cpp
+++ clang/unittests/Tooling/Syntax/BuildTreeTest.cpp
@@ -23,11 +23,9 @@
 SCOPED_TRACE(llvm::join(GetParam().getCommandLineArgs(), " "));
 
 auto *Root = buildTree(Code, GetParam());
-if (Diags->getClient()->getNumErrors() != 0) {
-  return ::testing::AssertionFailure()
- << "Source file has syntax errors, they were printed to the test "
-"log";
-}
+auto ErrorOK = errorOK(Code);
+if (!ErrorOK)
+  return ErrorOK;
 auto Actual = 
StringRef(Root->dump(Arena->getSourceManager())).trim().str();
 // EXPECT_EQ shows the diff between the two strings if they are different.
 EXPECT_EQ(Tree.trim().str(), Actual);
@@ -45,11 +43,9 @@
 auto AnnotatedCode = llvm::Annotations(CodeWithAnnotations);
 auto *Root = buildTree(AnnotatedCode.code(), GetParam());
 
-if (Diags->getClient()->getNumErrors() != 0) {
-  return ::testing::AssertionFailure()
- << "Source file has syntax errors, they were printed to the test "
-"log";
-}
+auto ErrorOK = errorOK(AnnotatedCode.code());
+if (!ErrorOK)
+  return ErrorOK;
 
 auto AnnotatedRanges = AnnotatedCode.ranges();
 if (AnnotatedRanges.size() != TreeDumps.size()) {
@@ -77,6 +73,19 @@
 return Failed ? ::testing::AssertionFailure()
   : ::testing::AssertionSuccess();
   }
+
+private:
+  ::testing::AssertionResult errorOK(StringRef RawCode) {
+if (!RawCode.contains("error-ok")) {
+  if (Diags->getClient()->getNumErrors() != 0) {
+return ::testing::AssertionFailure()
+   << "Source file has syntax errors (suppress with /*error-ok*/), 
"
+  "they were printed to the "
+  "test log";
+  }
+}
+return ::testing::AssertionSuccess();
+  }
 };
 
 INSTANTIATE_TEST_CASE_P(SyntaxTreeTests, BuildSyntaxTreeTest,
@@ -4773,6 +4782,7 @@
  int func1([[int a]]);
  int func2([[int *ap]]);
  int func3([[int a, float b]]);
+ int func4([[undef a]]); // error-ok: no crash on invalid type
)cpp",
   {R"txt(
 ParameterDeclarationList Parameters
@@ -4804,6 +4814,14 @@
   `-DeclaratorList Declarators
 `-SimpleDeclarator ListElement
   `-'b'
+)txt",
+   R"txt(
+ParameterDeclarationList Parameters
+`-SimpleDeclaration ListElement
+  |-'undef'
+  `-DeclaratorList Declarators
+`-SimpleDeclarator ListElement
+  `-'a'
 )txt"}));
 }
 
Index: clang/lib/Tooling/Syntax/BuildTree.cpp
===
--- clang/lib/Tooling/Syntax/BuildTree.cpp
+++ clang/lib/Tooling/Syntax/BuildTree.cpp
@@ -294,11 +294,12 @@
   SourceRange Initializer) {
   SourceLocation Start = GetStartLoc().Visit(T);
   SourceLocation End = T.getEndLoc();
-  assert(End.isValid());
   if (Name.isValid()) {
 if (Start.isInvalid())
   Start = Name;
-if (SM.isBeforeInTranslationUnit(End, Name))
+// End of TypeLoc could be invalid if the type is invalid, fallback to the
+// NameLoc.
+if (End.isInvalid() || SM.isBeforeInTranslationUnit(End, Name))
   End = Name;
   }
   if (Initializer.isValid()) {


Index: clang/unittests/Tooling/Syntax/BuildTreeTest.cpp
===
--- clang/unittests/Tooling/Syntax/BuildTreeTest.cpp
+++ clang/unittests/Tooling/Syntax/BuildTreeTest.cpp
@@ -23,11 +23,9 @@
 SCOPED_TRACE(llvm::join(GetParam().getCommandLineArgs(), " "));
 
 auto *Root = buildTree(Code, GetParam());
-if (Diags->getClient()->getNumErrors() != 0) {
-  return ::testing::AssertionFailure()
- << "Source file has syntax errors, they were printed to the test "
-"log";
-}
+auto ErrorOK = errorOK(Code);
+if (!ErrorOK)
+  return ErrorOK;
 auto Actual = StringRef(Root->dump(Arena->getSourceManager())).trim().str();
 // EXPECT_EQ shows the diff between the two strings if they are different.
 EXPECT_EQ(Tree.trim().str(), Actual);
@@ -45,11 +43,9 @@
 auto AnnotatedCode = llvm::Annotations(CodeWithAnnotations);
 auto *Root = buildTree(AnnotatedCode.code(), GetParam());
 
-if (Diags->getClient()->getNumErrors() != 0) {
-  return ::testing::AssertionFailure()
- << "Source file has syntax errors, they were printed to the test "
-   

[PATCH] D96203: [clang][patch] Modify sanitizer options names: renaming blacklist to blocklist

2021-02-08 Thread Melanie Blower via Phabricator via cfe-commits
mibintc added a comment.

In D96203#2546856 , @aaron.ballman 
wrote:

> Thank you for working on this!
>
>> This changes the option names that include substring blacklist to blocklist.
>
> I think this change works in some places, but in other places we say things 
> like "blocklisted" which feels a bit awkward. I don't super love the name 
> `blocklist`, but I don't super hate it either. All the alternative names I 
> come up with aren't really great either, like `UnsanitiziedEntities` or 
> `IgnoredObjects`. Maybe someone will have a better idea here than me, but I 
> do think the current name is an improvement over the old name.

There is a pre-existing patch https://reviews.llvm.org/D82244 using block and 
allow, that's why I chose blocklist. Although going in cold I would prefer to 
use allow and deny, and block seems to me a little like cheating (too similar 
to black). However I can "disagree and commit" (cf. 
https://en.wikipedia.org/wiki/Disagree_and_commit) with this choice of wording. 
I can search out the awkward Blocklisted and come up with different phrasing in 
the prose, but I think names in the program should use blocklist so that they 
can be easily connected to the option name for future maintainers of llvm.  
I'll check this.

>> In options.td there is a way to officially mark an option deprecated by 
>> adding it to a specific group, I didn't do that yet. When could we actually 
>> eliminate the old spelling? How about December 2021?
>
> I think we want to leave the deprecated options in for a full release cycle, 
> so I'd say that (assuming this lands in Clang 13) we could remove support 
> once we start work on Clang 14.
>
>> I thought it would be best to start with the external clang interface, but i 
>> also want to make more patches to eliminate whitelist and blacklist in the 
>> comments and in the object names, file names etc.
>
> Fantastic, thank you!




Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D96203

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


[PATCH] D96248: [OpenMP][AMDGPU] Add support for linking libomptarget bitcode

2021-02-08 Thread Jon Chesterfield via Phabricator via cfe-commits
JonChesterfield added a comment.

LGTM. Let's wait for someone using nvptx to sanity check


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D96248

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


[PATCH] D96175: [clang] Add support for attribute 'swift_async_error'

2021-02-08 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman added inline comments.



Comment at: clang/lib/Sema/SemaDeclAttr.cpp:5867
+  << AsyncAttr << isa(D);
+  return;
+}

You can elide this `return`.



Comment at: clang/lib/Sema/SemaDeclAttr.cpp:5977
+checkSwiftAsyncErrorBlock(S, D, ErrorAttr, AsyncAttr);
+}
+

Should there be a diagnostic to combine `swift_error` and `swift_async_error` 
on the same function? Similarly, should there be a diagnostic when adding 
`swift_async_error` to a function that isn't (eventually) marked `swift_async`?


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

https://reviews.llvm.org/D96175

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


[PATCH] D96262: [clang][index] report references from unreslovedLookupExpr.

2021-02-08 Thread Haojian Wu via Phabricator via cfe-commits
hokein created this revision.
hokein added a reviewer: usaxena95.
Herald added subscribers: kadircet, arphaman.
hokein requested review of this revision.
Herald added a subscriber: ilya-biryukov.
Herald added a project: clang.

Fix https://github.com/clangd/clangd/issues/675


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D96262

Files:
  clang/lib/Index/IndexBody.cpp
  clang/test/Index/Core/index-dependent-source.cpp


Index: clang/test/Index/Core/index-dependent-source.cpp
===
--- clang/test/Index/Core/index-dependent-source.cpp
+++ clang/test/Index/Core/index-dependent-source.cpp
@@ -224,3 +224,10 @@
 // CHECK: [[@LINE+1]]:9 | struct(Gen)/C++ | UsingD | c:@ST>1#T@UsingD | 
 | Ref,RelCont | rel: 1
   using UsingD::foo;
 };
+
+template  void foo();
+// CHECK: [[@LINE-1]]:28 | function/C | foo | c:@FT@>1#Tfoo#v# |  | 
Decl | rel: 0
+template  void bar() {
+  foo();
+// CHECK: [[@LINE-1]]:3 | function/C | foo | c:@FT@>1#Tfoo#v# |  | 
Ref,Call,RelCall,RelCont | rel: 1
+}
Index: clang/lib/Index/IndexBody.cpp
===
--- clang/lib/Index/IndexBody.cpp
+++ clang/lib/Index/IndexBody.cpp
@@ -466,6 +466,15 @@
 }
 return true;
   }
+
+  bool VisitUnresolvedLookupExpr(UnresolvedLookupExpr *E) {
+SmallVector Relations;
+SymbolRoleSet Roles = getRolesForRef(E, Relations);
+for (auto *D : E->decls())
+  IndexCtx.handleReference(D, E->getNameLoc(), Parent, ParentDC, Roles,
+   Relations, E);
+return true;
+  }
 };
 
 } // anonymous namespace


Index: clang/test/Index/Core/index-dependent-source.cpp
===
--- clang/test/Index/Core/index-dependent-source.cpp
+++ clang/test/Index/Core/index-dependent-source.cpp
@@ -224,3 +224,10 @@
 // CHECK: [[@LINE+1]]:9 | struct(Gen)/C++ | UsingD | c:@ST>1#T@UsingD |  | Ref,RelCont | rel: 1
   using UsingD::foo;
 };
+
+template  void foo();
+// CHECK: [[@LINE-1]]:28 | function/C | foo | c:@FT@>1#Tfoo#v# |  | Decl | rel: 0
+template  void bar() {
+  foo();
+// CHECK: [[@LINE-1]]:3 | function/C | foo | c:@FT@>1#Tfoo#v# |  | Ref,Call,RelCall,RelCont | rel: 1
+}
Index: clang/lib/Index/IndexBody.cpp
===
--- clang/lib/Index/IndexBody.cpp
+++ clang/lib/Index/IndexBody.cpp
@@ -466,6 +466,15 @@
 }
 return true;
   }
+
+  bool VisitUnresolvedLookupExpr(UnresolvedLookupExpr *E) {
+SmallVector Relations;
+SymbolRoleSet Roles = getRolesForRef(E, Relations);
+for (auto *D : E->decls())
+  IndexCtx.handleReference(D, E->getNameLoc(), Parent, ParentDC, Roles,
+   Relations, E);
+return true;
+  }
 };
 
 } // anonymous namespace
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D92024: [clang] Implement P0692R1 from C++20 (access checking on specializations and instantiations)

2021-02-08 Thread Alex Orlov via Phabricator via cfe-commits
aorlov added a comment.

Hi, community. I kindly ask you to review this patch.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D92024

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


[PATCH] D96215: [clang-tidy] Recognize captures as a form of aliasing.

2021-02-08 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman added a comment.

Notionally, I think it makes sense to treat byref captures as a form of 
aliasing. Should structured bindings be treated similarly as well (not 
necessarily as part of this patch)?


Repository:
  rCTE Clang Tools Extra

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

https://reviews.llvm.org/D96215

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


[PATCH] D96203: [clang][patch] Modify sanitizer options names: renaming blacklist to blocklist

2021-02-08 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman added a comment.

In D96203#2548471 , @mibintc wrote:

> In D96203#2546856 , @aaron.ballman 
> wrote:
>
>> Thank you for working on this!
>>
>>> This changes the option names that include substring blacklist to blocklist.
>>
>> I think this change works in some places, but in other places we say things 
>> like "blocklisted" which feels a bit awkward. I don't super love the name 
>> `blocklist`, but I don't super hate it either. All the alternative names I 
>> come up with aren't really great either, like `UnsanitiziedEntities` or 
>> `IgnoredObjects`. Maybe someone will have a better idea here than me, but I 
>> do think the current name is an improvement over the old name.
>
> There is a pre-existing patch https://reviews.llvm.org/D82244 using block and 
> allow, that's why I chose blocklist. Although going in cold I would prefer to 
> use allow and deny, and block seems to me a little like cheating (too similar 
> to black).

That was my concern as well -- I can easily imagine someone seeing 
"blocklisted" and thinking it was a typo for "blacklisted" and undoing the 
change to comments with an NFC change.

> However I can "disagree and commit" (cf. 
> https://en.wikipedia.org/wiki/Disagree_and_commit) with this choice of 
> wording. I can search out the awkward Blocklisted and come up with different 
> phrasing in the prose, but I think names in the program should use blocklist 
> so that they can be easily connected to the option name for future 
> maintainers of llvm.  I'll check this.

I agree that the frontend option names and the internal variable names need to 
connect to one another, so if we pick a new term, it should be used 
consistently. I'd be mildly happier with a better term than blocklist, but I 
can live with that name too.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D96203

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


[PATCH] D96247: [clangd] Fix false positive in local rename collision detetction

2021-02-08 Thread Haojian Wu via Phabricator via cfe-commits
hokein accepted this revision.
hokein added a comment.
This revision is now accepted and ready to land.

Thanks for the quick fix.




Comment at: clang-tools-extra/clangd/refactor/Rename.cpp:427
+// something in the definition's body is a valid transformation.
+if (!EnclosingFunction->isThisDeclarationADefinition())
+  return nullptr;

I think using `doesThisDeclarationHaveABody` is a better fit, e.g. `Foo(Foo& a) 
= default;` is a definition, but no function body :)


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D96247

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


[PATCH] D89651: [clang-tidy] Add bugprone-suspicious-memory-comparison check

2021-02-08 Thread Balázs Benics via Phabricator via cfe-commits
steakhal added a comment.
Herald added a subscriber: nullptr.cpp.

I really love this.
I'm gonna have a look at the blocking patch.




Comment at: 
clang-tools-extra/test/clang-tidy/checkers/bugprone-suspicious-memory-comparison-32bits.cpp:2
+// RUN: %check_clang_tidy %s bugprone-suspicious-memory-comparison %t \
+// RUN: -- -- -target x86_64-unknown-unknown -m32
+

gbencze wrote:
> aaron.ballman wrote:
> > Wouldn't picking a 32-bit target suffice instead of `-m32`? e.g., `-target 
> > i386-unknown-unknown`
> To be fully honest, I have no idea, I saw some other tests using `-m32` so I 
> decided to copy that. 
Why don't we pick `i386-unknown-linux` instead?
That would limit the scope of this test to Ititanium ABI.


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

https://reviews.llvm.org/D89651

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


[PATCH] D96203: [clang][patch] Modify sanitizer options names: renaming blacklist to blocklist

2021-02-08 Thread Eric Christopher via Phabricator via cfe-commits
echristo added a reviewer: vitalybuka.
echristo added a comment.

In D96203#2548495 , @aaron.ballman 
wrote:

> In D96203#2548471 , @mibintc wrote:
>
>> In D96203#2546856 , @aaron.ballman 
>> wrote:
>>
>>> Thank you for working on this!
>>>
 This changes the option names that include substring blacklist to 
 blocklist.
>>>
>>> I think this change works in some places, but in other places we say things 
>>> like "blocklisted" which feels a bit awkward. I don't super love the name 
>>> `blocklist`, but I don't super hate it either. All the alternative names I 
>>> come up with aren't really great either, like `UnsanitiziedEntities` or 
>>> `IgnoredObjects`. Maybe someone will have a better idea here than me, but I 
>>> do think the current name is an improvement over the old name.
>>
>> There is a pre-existing patch https://reviews.llvm.org/D82244 using block 
>> and allow, that's why I chose blocklist. Although going in cold I would 
>> prefer to use allow and deny, and block seems to me a little like cheating 
>> (too similar to black).
>
> That was my concern as well -- I can easily imagine someone seeing 
> "blocklisted" and thinking it was a typo for "blacklisted" and undoing the 
> change to comments with an NFC change.
>
>> However I can "disagree and commit" (cf. 
>> https://en.wikipedia.org/wiki/Disagree_and_commit) with this choice of 
>> wording. I can search out the awkward Blocklisted and come up with different 
>> phrasing in the prose, but I think names in the program should use blocklist 
>> so that they can be easily connected to the option name for future 
>> maintainers of llvm.  I'll check this.
>
> I agree that the frontend option names and the internal variable names need 
> to connect to one another, so if we pick a new term, it should be used 
> consistently. I'd be mildly happier with a better term than blocklist, but I 
> can live with that name too.

FWIW I would prefer denylist as well. (Also uses of whitelist should be 
allowlist, but also incremental :)

-eric


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D96203

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


[PATCH] D93769: [clang] Add support for option -ffp-eval-method and extend #pragma float_control similarly

2021-02-08 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman added a reviewer: rsmith.
aaron.ballman added a comment.

One question that came up in off-line discussions with @mibintc is whether the 
evaluation method should have an impact on constant folding or not. My 
intuition is that it should impact constant folding because it would be pretty 
strange for the evaluation at runtime to produce different results, but I don't 
have anything concrete to back my intuition up with.




Comment at: clang/docs/UsersManual.rst:1464
+
+   * ``source`` The compiler uses the floating point type declared in the 
source program as the evaluation method.
+   * ``double`` The compiler uses ``double`` as the floating-point evaluation 
method for all float expressions of type that is narrower than ``double``.





Comment at: clang/include/clang/Basic/LangOptions.h:234
+FEM_Extended,
+/// Use the default float eval method specified by Target
+FEM_TargetDefault

FYI: it may be somewhat confusing that we have an enumerator with `default` in 
the name but that enumerator isn't the default.



Comment at: clang/lib/Frontend/CompilerInvocation.cpp:3080
 Opts.LexEditorPlaceholders = false;
+Opts.LexExpandSpecialBuiltins = false;
+  }

May want to update the comment above for why we're turning the option off here.



Comment at: clang/lib/Lex/PPMacroExpansion.cpp:1714
   });
-  } else if (II == Ident__has_cpp_attribute ||
- II == Ident__has_c_attribute) {
+  } else if (II == Ident__has_cpp_attribute || II == Ident__has_c_attribute) {
 bool IsCXX = II == Ident__has_cpp_attribute;

It looks like some unrelated formatting changes snuck in.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D93769

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


[PATCH] D93769: [clang] Add support for option -ffp-eval-method and extend #pragma float_control similarly

2021-02-08 Thread Melanie Blower via Phabricator via cfe-commits
mibintc added inline comments.



Comment at: clang/include/clang/Basic/LangOptions.h:234
+FEM_Extended,
+/// Use the default float eval method specified by Target
+FEM_TargetDefault

aaron.ballman wrote:
> FYI: it may be somewhat confusing that we have an enumerator with `default` 
> in the name but that enumerator isn't the default.
That's true. I had a heck of a time getting the initialization of the lang 
option setting correct: the setting should come from the TargetInfo if command 
line options don't override. That seems simple enough but there's somethng 
really odd about initialization. Adding the "default target" enumeral allowed 
me to get it initialized the way I wanted.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D93769

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


[PATCH] D96036: [clang][codegen] Remember string used to create llvm::Regex for optimization remarks

2021-02-08 Thread Jan Svoboda via Phabricator via cfe-commits
jansvoboda11 updated this revision to Diff 322103.
jansvoboda11 added a comment.

Apply suggested change


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D96036

Files:
  clang/include/clang/Basic/CodeGenOptions.h
  clang/lib/Frontend/CompilerInvocation.cpp


Index: clang/lib/Frontend/CompilerInvocation.cpp
===
--- clang/lib/Frontend/CompilerInvocation.cpp
+++ clang/lib/Frontend/CompilerInvocation.cpp
@@ -1159,8 +1159,8 @@
 }
 
 /// Create a new Regex instance out of the string value in \p RpassArg.
-/// It returns a pointer to the newly generated Regex instance.
-static std::shared_ptr
+/// It returns the string and a pointer to the newly generated Regex instance.
+static CodeGenOptions::RemarkPattern
 GenerateOptimizationRemarkRegex(DiagnosticsEngine &Diags, ArgList &Args,
 Arg *RpassArg) {
   StringRef Val = RpassArg->getValue();
@@ -1171,7 +1171,7 @@
 << RegexError << RpassArg->getAsString(Args);
 Pattern.reset();
   }
-  return Pattern;
+  return {std::string(Val), Pattern};
 }
 
 static bool parseDiagnosticLevelMask(StringRef FlagName,
Index: clang/include/clang/Basic/CodeGenOptions.h
===
--- clang/include/clang/Basic/CodeGenOptions.h
+++ clang/include/clang/Basic/CodeGenOptions.h
@@ -278,19 +278,29 @@
   /// -fsymbol-partition (see https://lld.llvm.org/Partitions.html).
   std::string SymbolPartition;
 
+  /// Regular expression and the string it was created from.
+  struct RemarkPattern {
+std::string Pattern;
+std::shared_ptr Regex;
+
+explicit operator bool() const { return Regex != nullptr; }
+
+llvm::Regex *operator->() const { return Regex.get(); }
+  };
+
   /// Regular expression to select optimizations for which we should enable
   /// optimization remarks. Transformation passes whose name matches this
   /// expression (and support this feature), will emit a diagnostic
   /// whenever they perform a transformation. This is enabled by the
   /// -Rpass=regexp flag.
-  std::shared_ptr OptimizationRemarkPattern;
+  RemarkPattern OptimizationRemarkPattern;
 
   /// Regular expression to select optimizations for which we should enable
   /// missed optimization remarks. Transformation passes whose name matches 
this
   /// expression (and support this feature), will emit a diagnostic
   /// whenever they tried but failed to perform a transformation. This is
   /// enabled by the -Rpass-missed=regexp flag.
-  std::shared_ptr OptimizationRemarkMissedPattern;
+  RemarkPattern OptimizationRemarkMissedPattern;
 
   /// Regular expression to select optimizations for which we should enable
   /// optimization analyses. Transformation passes whose name matches this
@@ -298,7 +308,7 @@
   /// whenever they want to explain why they decided to apply or not apply
   /// a given transformation. This is enabled by the -Rpass-analysis=regexp
   /// flag.
-  std::shared_ptr OptimizationRemarkAnalysisPattern;
+  RemarkPattern OptimizationRemarkAnalysisPattern;
 
   /// Set of files defining the rules for the symbol rewriting.
   std::vector RewriteMapFiles;


Index: clang/lib/Frontend/CompilerInvocation.cpp
===
--- clang/lib/Frontend/CompilerInvocation.cpp
+++ clang/lib/Frontend/CompilerInvocation.cpp
@@ -1159,8 +1159,8 @@
 }
 
 /// Create a new Regex instance out of the string value in \p RpassArg.
-/// It returns a pointer to the newly generated Regex instance.
-static std::shared_ptr
+/// It returns the string and a pointer to the newly generated Regex instance.
+static CodeGenOptions::RemarkPattern
 GenerateOptimizationRemarkRegex(DiagnosticsEngine &Diags, ArgList &Args,
 Arg *RpassArg) {
   StringRef Val = RpassArg->getValue();
@@ -1171,7 +1171,7 @@
 << RegexError << RpassArg->getAsString(Args);
 Pattern.reset();
   }
-  return Pattern;
+  return {std::string(Val), Pattern};
 }
 
 static bool parseDiagnosticLevelMask(StringRef FlagName,
Index: clang/include/clang/Basic/CodeGenOptions.h
===
--- clang/include/clang/Basic/CodeGenOptions.h
+++ clang/include/clang/Basic/CodeGenOptions.h
@@ -278,19 +278,29 @@
   /// -fsymbol-partition (see https://lld.llvm.org/Partitions.html).
   std::string SymbolPartition;
 
+  /// Regular expression and the string it was created from.
+  struct RemarkPattern {
+std::string Pattern;
+std::shared_ptr Regex;
+
+explicit operator bool() const { return Regex != nullptr; }
+
+llvm::Regex *operator->() const { return Regex.get(); }
+  };
+
   /// Regular expression to select optimizations for which we should enable
   /// optimization remarks. Transformation passes whose name matches this
   /// expression (and support this feature

[PATCH] D69560: [clang-tidy] Add 'bugprone-easily-swappable-parameters' check

2021-02-08 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman added inline comments.



Comment at: 
clang-tools-extra/clang-tidy/bugprone/EasilySwappableParametersCheck.cpp:177
+   const std::size_t StartIndex) {
+  const std::size_t NumParams = FD->getNumParams();
+  assert(StartIndex < NumParams && "out of bounds for start");

whisperity wrote:
> aaron.ballman wrote:
> > Some interesting test cases to consider: varargs functions and K&R C 
> > functions
> > K&R C functions
> 
> Call me too young, but I had to look up what a "K&R C function" is, and I am 
> absolutely baffled how this unholy construct is still supported! **But:** 
> thanks to Clang supporting it properly in the AST, the checker works out of 
> the box!
> 
> Given
> 
> ```
> int foo(a, b)
>   int a;
>   int b;
> {
>   return a + b;
> }
> ```
> 
> We get the following output:
> 
> ```
> /tmp/knr.c:2:3: warning: 2 adjacent parameters of 'foo' of similar type 
> ('int') are easily swapped by mistake [bugprone-easily-swappable-parameters]
>   int a;
>   ^
> /tmp/knr.c:2:7: note: the first parameter in the range is 'a'
>   int a;
>   ^
> /tmp/knr.c:3:7: note: the last parameter in the range is 'b'
>   int b;
>   ^
> ```
> 
> (even the locations are consistent!)
> 
> Should I add a test case for this? We could use a specifically C test case 
> either way eventually...
> 
> -
> 
> > varargs functions
> 
> This is a bit of terminology, but something tells me you meant the //variadic 
> function// here, right? As opposed to type parameter packs.
> 
> Given
> 
> ```
> int sum(int ints...) {
>   return 0;
> }
> ```
> 
> the AST looks something like this:
> 
> ```
> `-FunctionDecl 0x56372e29e258  line:1:5 sum 'int 
> (int, ...)'
>   |-ParmVarDecl 0x56372e29e188  col:13 ints 'int'
> ```
> 
> Should we diagnose this? And if so, how? The variadic part is not represented 
> (at least not at first glance?) in the AST. Understanding the insides of such 
> a function would require either overapproximatic stuff and doing a looot of 
> extra handling, or becoming flow sensitive... and we'd still need to 
> understand all the `va_` standard functions' semantics either way.
> Call me too young, but I had to look up what a "K&R C function" is, and I am 
> absolutely baffled how this unholy construct is still supported!

Ah, to be innocent again, how I miss those days. :-D

> Should I add a test case for this? We could use a specifically C test case 
> either way eventually...

I think it'd be a useful case, but the one I was specifically more concerned 
with is:
```
// N.B.: this is C-specific and does not apply to C++.
void f();

int main(void) {
  f(1, 2, 3.4, "this is why we can't have nice things");
}
```
where the function has no prototype and so is treated as a varargs call.

> This is a bit of terminology, but something tells me you meant the variadic 
> function here, right? As opposed to type parameter packs.

Yes, sorry for being unclear, I am talking about variadic functions.

> Should we diagnose this? And if so, how? The variadic part is not represented 
> (at least not at first glance?) in the AST. Understanding the insides of such 
> a function would require either overapproximatic stuff and doing a looot of 
> extra handling, or becoming flow sensitive... and we'd still need to 
> understand all the va_ standard functions' semantics either way.

Well, that's what I'm wondering, really. The arguments are certainly easy to 
swap because the type system can't help the user to identify swaps without 
further information (like format specifier strings). However, the checking code 
would be... highly unpleasant, I suspect. My intuition is to say that we don't 
support functions without prototypes at all (we just silently ignore them) and 
that we only check the typed parameters in a variadic function declaration 
(e.g., we'll diagnose `void foo(int i, int j, ...);` because of the sequential 
`int` parameters, but we won't diagnose `void foo(int i, ...);` even if call 
sites look like `foo(1, 2);`). WDYT?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D69560

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


[PATCH] D96265: [PowerPC] Change target data layout for 16-byte stack alignment

2021-02-08 Thread Ahsan Saghir via Phabricator via cfe-commits
saghir created this revision.
Herald added subscribers: shchenz, kbarton, hiraditya, nemanjai, emaste.
saghir requested review of this revision.
Herald added subscribers: llvm-commits, cfe-commits, MaskRay.
Herald added projects: clang, LLVM.

This changes the target data layout to make stack align to 16 bytes
on Power10. Before this change, stack was being aligned to 32 bytes.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D96265

Files:
  clang/lib/Basic/Targets/PPC.h
  clang/test/CodeGen/target-data.c
  lld/test/ELF/common-archive-lookup.s
  llvm/lib/Target/PowerPC/PPCTargetMachine.cpp
  llvm/test/CodeGen/PowerPC/32byte-aligned-vector-stack-alignment.ll
  llvm/test/CodeGen/PowerPC/32byte-array-stack-alignment.ll
  llvm/test/CodeGen/PowerPC/32byte-vector-stack-alignment.ll
  llvm/test/CodeGen/PowerPC/P10-stack-alignment.ll

Index: llvm/test/CodeGen/PowerPC/P10-stack-alignment.ll
===
--- /dev/null
+++ llvm/test/CodeGen/PowerPC/P10-stack-alignment.ll
@@ -0,0 +1,316 @@
+; NOTE: Assertions have been autogenerated by utils/update_llc_test_checks.py
+; RUN: llc -verify-machineinstrs -mtriple=powerpc64le-unknown-linux-gnu \
+; RUN:   -mcpu=pwr10 -ppc-asm-full-reg-names -ppc-vsr-nums-as-vr < %s | \
+; RUN:   FileCheck %s
+; RUN: llc -verify-machineinstrs -mtriple=powerpc64-unknown-linux-gnu \
+; RUN:   -mcpu=pwr10 -ppc-asm-full-reg-names -ppc-vsr-nums-as-vr < %s | \
+; RUN:   FileCheck %s --check-prefix=CHECK-BE
+
+@.str = private unnamed_addr constant [7 x i8] c"%d %d\0A\00", align 1
+
+define dso_local signext i32 @test() local_unnamed_addr nounwind {
+; CHECK-LABEL: test:
+; CHECK:   # %bb.0: # %entry
+; CHECK-NEXT:mflr r0
+; CHECK-NEXT:std r30, -16(r1)
+; CHECK-NEXT:mr r30, r1
+; CHECK-NEXT:std r0, 16(r1)
+; CHECK-NEXT:clrldi r0, r1, 59
+; CHECK-NEXT:subfic r0, r0, -448
+; CHECK-NEXT:stdux r1, r1, r0
+; CHECK-NEXT:addi r3, r1, 96
+; CHECK-NEXT:li r4, 0
+; CHECK-NEXT:li r5, 200
+; CHECK-NEXT:bl memset@notoc
+; CHECK-NEXT:plxv v2, .LCPI0_1@PCREL(0), 1
+; CHECK-NEXT:plxv v5, .LCPI0_0@PCREL(0), 1
+; CHECK-NEXT:pli r3, 1684234849
+; CHECK-NEXT:plxv v1, .LCPI0_3@PCREL(0), 1
+; CHECK-NEXT:plxv v0, .LCPI0_2@PCREL(0), 1
+; CHECK-NEXT:plxv v7, .LCPI0_5@PCREL(0), 1
+; CHECK-NEXT:plxv v6, .LCPI0_4@PCREL(0), 1
+; CHECK-NEXT:stw r3, 416(r1)
+; CHECK-NEXT:vmrghb v4, v2, v2
+; CHECK-NEXT:vmrglb v3, v2, v2
+; CHECK-NEXT:stxv v2, 320(r1)
+; CHECK-NEXT:xxspltiw v2, 524296
+; CHECK-NEXT:stxv v5, 336(r1)
+; CHECK-NEXT:stxv v0, 368(r1)
+; CHECK-NEXT:stxv v1, 352(r1)
+; CHECK-NEXT:stxv v6, 400(r1)
+; CHECK-NEXT:stxv v7, 384(r1)
+; CHECK-NEXT:vslh v4, v4, v2
+; CHECK-NEXT:vslh v3, v3, v2
+; CHECK-NEXT:vsrh v4, v4, v2
+; CHECK-NEXT:vsrh v3, v3, v2
+; CHECK-NEXT:stxv v4, 112(r1)
+; CHECK-NEXT:vmrglb v4, v5, v5
+; CHECK-NEXT:stxv v3, 96(r1)
+; CHECK-NEXT:vmrglb v3, v1, v1
+; CHECK-NEXT:li r3, 97
+; CHECK-NEXT:vmrghb v5, v5, v5
+; CHECK-NEXT:lha r5, 96(r1)
+; CHECK-NEXT:sth r3, 288(r1)
+; CHECK-NEXT:pli r3, 6488162
+; CHECK-NEXT:vslh v4, v4, v2
+; CHECK-NEXT:vslh v3, v3, v2
+; CHECK-NEXT:stw r3, 290(r1)
+; CHECK-NEXT:li r3, 100
+; CHECK-NEXT:vslh v5, v5, v2
+; CHECK-NEXT:vsrh v4, v4, v2
+; CHECK-NEXT:vsrh v3, v3, v2
+; CHECK-NEXT:sth r3, 294(r1)
+; CHECK-NEXT:lbz r3, 320(r1)
+; CHECK-NEXT:vsrh v5, v5, v2
+; CHECK-NEXT:stxv v4, 128(r1)
+; CHECK-NEXT:vmrghb v4, v1, v1
+; CHECK-NEXT:stxv v3, 160(r1)
+; CHECK-NEXT:vmrglb v3, v0, v0
+; CHECK-NEXT:stxv v5, 144(r1)
+; CHECK-NEXT:extsb r4, r3
+; CHECK-NEXT:paddi r3, 0, .L.str@PCREL, 1
+; CHECK-NEXT:vslh v4, v4, v2
+; CHECK-NEXT:vslh v3, v3, v2
+; CHECK-NEXT:vsrh v4, v4, v2
+; CHECK-NEXT:vsrh v3, v3, v2
+; CHECK-NEXT:stxv v4, 176(r1)
+; CHECK-NEXT:vmrghb v4, v0, v0
+; CHECK-NEXT:stxv v3, 192(r1)
+; CHECK-NEXT:vslh v4, v4, v2
+; CHECK-NEXT:vsrh v4, v4, v2
+; CHECK-NEXT:stxv v4, 208(r1)
+; CHECK-NEXT:vmrglb v4, v7, v7
+; CHECK-NEXT:vslh v4, v4, v2
+; CHECK-NEXT:vsrh v3, v4, v2
+; CHECK-NEXT:vmrghb v4, v7, v7
+; CHECK-NEXT:stxv v3, 224(r1)
+; CHECK-NEXT:vmrglb v3, v6, v6
+; CHECK-NEXT:vslh v4, v4, v2
+; CHECK-NEXT:vsrh v4, v4, v2
+; CHECK-NEXT:vslh v3, v3, v2
+; CHECK-NEXT:stxv v4, 240(r1)
+; CHECK-NEXT:vmrghb v4, v6, v6
+; CHECK-NEXT:vsrh v3, v3, v2
+; CHECK-NEXT:stxv v3, 256(r1)
+; CHECK-NEXT:vslh v4, v4, v2
+; CHECK-NEXT:vsrh v2, v4, v2
+; CHECK-NEXT:stxv v2, 272(r1)
+; CHECK-NEXT:bl printf@notoc
+; CHECK-NEXT:li r3, 0
+; CHECK-NEXT:mr r1, r30
+; CHECK-NEXT:ld r0, 16(r1)
+; CHECK-NEXT:ld r30, -16(r1)
+; CHECK-NEXT:mtlr r0
+; CHECK-NEXT:blr
+;
+; CHECK-BE-LABEL: test:
+; CHECK-BE:   # %bb.0: # %entry
+; CHECK-BE-NEXT:mflr r0
+; CHECK-BE-NEXT:   

[PATCH] D96036: [clang][codegen] Remember string used to create llvm::Regex for optimization remarks

2021-02-08 Thread Jan Svoboda via Phabricator via cfe-commits
jansvoboda11 added a comment.

I originally wanted to improve the API (make the null checks unnecessary), but 
keeping the API and minimizing the patch with your changes is nice too. I'm 
going with your suggestion, thanks!


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D96036

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


[PATCH] D95793: [clang][cli] Generate and round-trip language options

2021-02-08 Thread Jan Svoboda via Phabricator via cfe-commits
jansvoboda11 updated this revision to Diff 322106.
jansvoboda11 added a comment.

Add comment, remove unnecessary diff


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D95793

Files:
  clang/include/clang/Basic/Sanitizers.h
  clang/include/clang/Driver/Options.td
  clang/include/clang/Frontend/CompilerInvocation.h
  clang/lib/Basic/Sanitizers.cpp
  clang/lib/Frontend/CompilerInvocation.cpp
  clang/unittests/Basic/CMakeLists.txt
  clang/unittests/Basic/SanitizersTest.cpp

Index: clang/unittests/Basic/SanitizersTest.cpp
===
--- /dev/null
+++ clang/unittests/Basic/SanitizersTest.cpp
@@ -0,0 +1,49 @@
+//===- unittests/Basic/SanitizersTest.cpp - Test Sanitizers ---===//
+//
+// 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/Basic/Sanitizers.h"
+
+#include "gmock/gmock-matchers.h"
+#include "gtest/gtest.h"
+
+using namespace clang;
+
+using testing::Contains;
+using testing::Not;
+
+TEST(SanitizersTest, serializeSanitizers) {
+  SanitizerSet Set;
+  Set.set(parseSanitizerValue("memory", false), true);
+  Set.set(parseSanitizerValue("nullability-arg", false), true);
+
+  SmallVector Serialized;
+  serializeSanitizerSet(Set, Serialized);
+
+  ASSERT_EQ(Serialized.size(), 2u);
+  ASSERT_THAT(Serialized, Contains("memory"));
+  ASSERT_THAT(Serialized, Contains("nullability-arg"));
+}
+
+TEST(SanitizersTest, serializeSanitizersIndividual) {
+  SanitizerSet Set;
+  Set.set(parseSanitizerValue("memory", false), true);
+  Set.set(parseSanitizerValue("nullability-arg", false), true);
+  Set.set(parseSanitizerValue("nullability-assign", false), true);
+  Set.set(parseSanitizerValue("nullability-return", false), true);
+
+  SmallVector Serialized;
+  serializeSanitizerSet(Set, Serialized);
+
+  ASSERT_EQ(Serialized.size(), 4u);
+  ASSERT_THAT(Serialized, Contains("memory"));
+  ASSERT_THAT(Serialized, Contains("nullability-arg"));
+  ASSERT_THAT(Serialized, Contains("nullability-assign"));
+  ASSERT_THAT(Serialized, Contains("nullability-return"));
+  // Individual sanitizers don't get squashed into a single group.
+  ASSERT_THAT(Serialized, Not(Contains("nullability")));
+}
Index: clang/unittests/Basic/CMakeLists.txt
===
--- clang/unittests/Basic/CMakeLists.txt
+++ clang/unittests/Basic/CMakeLists.txt
@@ -8,6 +8,7 @@
   FileEntryTest.cpp
   FileManagerTest.cpp
   LineOffsetMappingTest.cpp
+  SanitizersTest.cpp
   SourceManagerTest.cpp
   )
 
Index: clang/lib/Frontend/CompilerInvocation.cpp
===
--- clang/lib/Frontend/CompilerInvocation.cpp
+++ clang/lib/Frontend/CompilerInvocation.cpp
@@ -214,6 +214,7 @@
 Args.push_back(SA(Value));
 break;
   case Option::JoinedClass:
+  case Option::CommaJoinedClass:
 Args.push_back(SA(Twine(Spelling) + Value));
 break;
   default:
@@ -1207,6 +1208,12 @@
   }
 }
 
+static SmallVector serializeSanitizerKinds(SanitizerSet S) {
+  SmallVector Values;
+  serializeSanitizerSet(S, Values);
+  return Values;
+}
+
 static void parseXRayInstrumentationBundle(StringRef FlagName, StringRef Bundle,
ArgList &Args, DiagnosticsEngine &D,
XRayInstrSet &S) {
@@ -2628,19 +2635,231 @@
   llvm_unreachable("unknown input language");
 }
 
-static void GenerateLangArgs(const LangOptions &Opts,
- SmallVectorImpl &Args,
- CompilerInvocation::StringAllocator SA) {
+void CompilerInvocation::GenerateLangArgs(const LangOptions &Opts,
+  SmallVectorImpl &Args,
+  StringAllocator SA,
+  const llvm::Triple &T) {
+  OptSpecifier StdOpt;
+  switch (Opts.LangStd) {
+  case LangStandard::lang_opencl10:
+  case LangStandard::lang_opencl11:
+  case LangStandard::lang_opencl12:
+  case LangStandard::lang_opencl20:
+  case LangStandard::lang_opencl30:
+  case LangStandard::lang_openclcpp:
+StdOpt = OPT_cl_std_EQ;
+break;
+  default:
+StdOpt = OPT_std_EQ;
+break;
+  }
+
+  auto LangStandard = LangStandard::getLangStandardForKind(Opts.LangStd);
+  GenerateArg(Args, StdOpt, LangStandard.getName(), SA);
+
   if (Opts.IncludeDefaultHeader)
 GenerateArg(Args, OPT_finclude_default_header, SA);
   if (Opts.DeclareOpenCLBuiltins)
 GenerateArg(Args, OPT_fdeclare_opencl_builtins, SA);
+
+  const LangOptions *LangOpts = &Opts;
+
+#define LANG_OPTION_WITH_MARSHALLING( 

[PATCH] D90851: [clang-tidy] Extending bugprone-signal-handler with POSIX functions.

2021-02-08 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman added inline comments.



Comment at: 
clang-tools-extra/docs/clang-tidy/checks/bugprone-signal-handler.rst:29-30
+  
`_
+  for more information). This is not an extension of the minimal set 
(``quick_exit``
+  is not included). Default is ``POSIX``.

balazske wrote:
> aaron.ballman wrote:
> > aaron.ballman wrote:
> > > Huh, that's really strange that POSIX leaves `quick_exit` off the list. 
> > > I'm going to reach out to someone from the Austin Group to see if that's 
> > > intentional or not.
> > I didn't need to reach out to them because I realized the latest POSIX spec 
> > is still based on C99 and they've not released the updated POSIX spec yet.
> > 
> > I think the POSIX functions should be a superset of the C functions.
> Do you mean that we should add `quick_exit` to the POSIX set? And have a 
> requirement that minimal set is subset of the POSIX set (if the lists are 
> modified in the future)?
> Do you mean that we should add quick_exit to the POSIX set? And have a 
> requirement that minimal set is subset of the POSIX set (if the lists are 
> modified in the future)?

Sorry for having missed your question earlier!

I think any function in the minimally safe set should also be safe within the 
POSIX set unless there's some documentation to suggest that POSIX removed an 
allowance the C standard provides for a given API (which would be pretty 
surprising). So yes, I think the minimal set should be a subset of the POSIX 
set.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D90851

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


[PATCH] D68682: format::cleanupAroundReplacements removes whole line when Removals leave previously non-blank line blank

2021-02-08 Thread Conrad Poelman via Phabricator via cfe-commits
poelmanc updated this revision to Diff 322108.
poelmanc added a comment.

Comment change, "beginning" to "start" for consistency, being sure to set 
Repository on "diff" page (not just on edit page) to see if 
https://github.com/google/llvm-premerge-checks/issues/263 was the problem.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D68682

Files:
  clang-tools-extra/clang-tidy/readability/RedundantControlFlowCheck.cpp
  clang-tools-extra/test/clang-tidy/checkers/modernize-redundant-void-arg.cpp
  
clang-tools-extra/test/clang-tidy/checkers/readability-redundant-control-flow.cpp
  
clang-tools-extra/test/clang-tidy/checkers/readability-redundant-declaration.cpp
  
clang-tools-extra/test/clang-tidy/checkers/readability-redundant-member-init.cpp
  clang-tools-extra/test/clang-tidy/checkers/readability-simplify-bool-expr.cpp
  clang-tools-extra/unittests/clang-change-namespace/ChangeNamespaceTests.cpp
  clang/include/clang/Basic/CharInfo.h
  clang/include/clang/Format/Format.h
  clang/lib/AST/CommentLexer.cpp
  clang/lib/AST/CommentParser.cpp
  clang/lib/Format/Format.cpp
  clang/unittests/Format/CMakeLists.txt
  clang/unittests/Format/CleanupTest.cpp

Index: clang/unittests/Format/CleanupTest.cpp
===
--- clang/unittests/Format/CleanupTest.cpp
+++ clang/unittests/Format/CleanupTest.cpp
@@ -12,6 +12,7 @@
 #include "clang/Tooling/Core/Replacement.h"
 
 #include "gtest/gtest.h"
+#include "llvm/Testing/Support/Annotations.h"
 
 using clang::tooling::ReplacementTest;
 using clang::tooling::toReplacements;
@@ -320,6 +321,11 @@
 return tooling::Replacement(FileName, Offset, Length, Text);
   }
 
+  tooling::Replacement createReplacement(llvm::Annotations::Range Range,
+ StringRef Text) {
+return createReplacement(Range.Begin, Range.End - Range.Begin, Text);
+  }
+
   tooling::Replacement createInsertion(StringRef IncludeDirective) {
 return createReplacement(UINT_MAX, 0, IncludeDirective);
   }
@@ -373,10 +379,12 @@
  "namespace C {\n"
  "namespace D { int i; }\n"
  "inline namespace E { namespace { int y; } }\n"
+ "\n"
  "int x= 0;"
  "}";
-  std::string Expected = "\n\nnamespace C {\n"
- "namespace D { int i; }\n\n"
+  std::string Expected = "\nnamespace C {\n"
+ "namespace D { int i; }\n"
+ "\n"
  "int x= 0;"
  "}";
   tooling::Replacements Replaces =
@@ -386,6 +394,104 @@
   EXPECT_EQ(Expected, formatAndApply(Code, Replaces));
 }
 
+TEST_F(CleanUpReplacementsTest, RemoveLineWhenAllNonWhitespaceRemoved) {
+  llvm::Annotations Code = "namespace A {$r1[[ // Useless comment]]\n"
+   "  $r2[[int]] $r3[[x]]\t $r4[[=]] $r5[[0;]]\t\n"
+   "  int y\t = 0;$r6[[\t]]\n"
+   "} // namespace A\n";
+  std::string Expected = "namespace A {\n"
+ "  int y\t = 0;\n"
+ "} // namespace A\n";
+  tooling::Replacements Replaces =
+  toReplacements({createReplacement(Code.range("r1"), ""),
+  createReplacement(Code.range("r2"), ""),
+  createReplacement(Code.range("r3"), ""),
+  createReplacement(Code.range("r4"), ""),
+  createReplacement(Code.range("r5"), ""),
+  createReplacement(Code.range("r6"), "")});
+
+  EXPECT_EQ(Expected, apply(Code.code(), Replaces));
+}
+
+TEST_F(CleanUpReplacementsTest, RemoveLinesWhenAllNonWhitespaceRemoved) {
+  llvm::Annotations Code = R"cpp(struct A {
+  A()
+  $r3[[:]] $r1[[f()]]$r2[[,]]
+$r4[[g()]]
+  {}
+  int f = 0;
+  int g = 0;
+};)cpp";
+  std::string Expected = R"cpp(struct A {
+  A()
+  {}
+  int f = 0;
+  int g = 0;
+};)cpp";
+  tooling::Replacements Replaces =
+  toReplacements({createReplacement(Code.range("r1"), ""),
+  createReplacement(Code.range("r2"), ""),
+  createReplacement(Code.range("r3"), ""),
+  createReplacement(Code.range("r4"), "")});
+
+  EXPECT_EQ(Expected, apply(Code.code(), Replaces));
+}
+
+TEST_F(CleanUpReplacementsTest, KeepLinesWithInsertsOrReplacesEvenIfBlank) {
+  // Not using raw string literals so newlines and spaces are clear and explicit
+  llvm::Annotations Code = "struct A {\n"
+ "  A() {}\n"
+ "$r3[[]]  $r1[[int]] $r2[[f;]]\n" // "  int f;\n"
+ "  \n"
+ "$r4[[  ]]\n"
+ "};";
+  std::string Expected = "struct A {\n"
+ "  A() {}\n"
+ "\n"
+ "\n"
+   

[PATCH] D96268: [-Wcompletion-handler] Support checks with builtins

2021-02-08 Thread Valeriy Savchenko via Phabricator via cfe-commits
vsavchenko created this revision.
vsavchenko added a reviewer: NoQ.
Herald added a subscriber: Charusso.
vsavchenko requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

It is very common to check callbacks and completion handlers for null.
This patch supports such checks using built-in functions:

- __builtin_expect
- __builtin_expect_with_probablity
- __builtin_unpredictable

rdar://73455388


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D96268

Files:
  clang/lib/Analysis/CalledOnceCheck.cpp
  clang/test/SemaObjC/warn-called-once.m

Index: clang/test/SemaObjC/warn-called-once.m
===
--- clang/test/SemaObjC/warn-called-once.m
+++ clang/test/SemaObjC/warn-called-once.m
@@ -4,6 +4,11 @@
 #define nil (id)0
 #define CALLED_ONCE __attribute__((called_once))
 #define NORETURN __attribute__((noreturn))
+#define LIKELY(X) __builtin_expect(!!(X), 1)
+#define UNLIKELY(X) __builtin_expect(!!(X), 0)
+#define LIKELY_WITH_PROBA(X, P) __builtin_expect_with_probability(!!(X), 1, P)
+#define UNLIKELY_WITH_PROBA(X, P) __builtin_expect_with_probability(!!(X), 0, P)
+#define UNPRED(X) __builtin_unpredictable((long)(X))
 
 @protocol NSObject
 @end
@@ -547,6 +552,70 @@
   // no-warning
 }
 
+void call_with_builtin_check_1(int (^callback)(void) CALLED_ONCE) {
+  if (LIKELY(callback))
+callback();
+  // no-warning
+}
+
+void call_with_builtin_check_2(int (^callback)(void) CALLED_ONCE) {
+  if (!UNLIKELY(callback)) {
+  } else {
+callback();
+  }
+  // no-warning
+}
+
+void call_with_builtin_check_3(int (^callback)(void) CALLED_ONCE) {
+  if (__builtin_expect((long)callback, 0L)) {
+  } else {
+callback();
+  }
+  // no-warning
+}
+
+void call_with_builtin_check_4(int (^callback)(void) CALLED_ONCE) {
+  if (__builtin_expect(0L, (long)callback)) {
+  } else {
+callback();
+  }
+  // no-warning
+}
+
+void call_with_builtin_check_5(int (^callback)(void) CALLED_ONCE) {
+  if (LIKELY_WITH_PROBA(callback, 0.9))
+callback();
+  // no-warning
+}
+
+void call_with_builtin_check_6(int (^callback)(void) CALLED_ONCE) {
+  if (!UNLIKELY_WITH_PROBA(callback, 0.9)) {
+  } else {
+callback();
+  }
+  // no-warning
+}
+
+void call_with_builtin_check_7(int (^callback)(void) CALLED_ONCE) {
+  if (UNPRED(callback)) {
+  } else {
+callback();
+  }
+  // no-warning
+}
+
+void call_with_builtin_check_8(int (^callback)(void) CALLED_ONCE) {
+  if (LIKELY(callback != nil))
+callback();
+  // no-warning
+}
+
+void call_with_builtin_check_9(int (^callback)(void) CALLED_ONCE) {
+  if (!UNLIKELY(callback == NULL))
+callback();
+  // no-warning
+}
+
 void unreachable_true_branch(void (^callback)(void) CALLED_ONCE) {
   if (0) {
 
Index: clang/lib/Analysis/CalledOnceCheck.cpp
===
--- clang/lib/Analysis/CalledOnceCheck.cpp
+++ clang/lib/Analysis/CalledOnceCheck.cpp
@@ -22,6 +22,7 @@
 #include "clang/Analysis/AnalysisDeclContext.h"
 #include "clang/Analysis/CFG.h"
 #include "clang/Analysis/FlowSensitive/DataflowWorklist.h"
+#include "clang/Basic/Builtins.h"
 #include "clang/Basic/IdentifierTable.h"
 #include "clang/Basic/LLVM.h"
 #include "llvm/ADT/BitVector.h"
@@ -330,6 +331,29 @@
 return Visit(OVE->getSourceExpr());
   }
 
+  const DeclRefExpr *VisitCallExpr(const CallExpr *CE) {
+if (!ShouldRetrieveFromComparisons)
+  return nullptr;
+
+// We want to see through some of the boolean builtin functions
+// that we are likely to see in conditions.
+switch (CE->getBuiltinCallee()) {
+case Builtin::BI__builtin_expect:
+case Builtin::BI__builtin_expect_with_probability: {
+  assert(CE->getNumArgs() >= 2);
+
+  const DeclRefExpr *Candidate = Visit(CE->getArg(0));
+  return Candidate != nullptr ? Candidate : Visit(CE->getArg(1));
+}
+
+case Builtin::BI__builtin_unpredictable:
+  return Visit(CE->getArg(0));
+
+default:
+  return nullptr;
+}
+  }
+
   const DeclRefExpr *VisitExpr(const Expr *E) {
 // It is a fallback method that gets called whenever the actual type
 // of the given expression is not covered.
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D96056: [clang][cli] Generate and round-trip CodeGen options

2021-02-08 Thread Jan Svoboda via Phabricator via cfe-commits
jansvoboda11 updated this revision to Diff 322112.
jansvoboda11 added a comment.

Document functions in XRayInstr.h


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D96056

Files:
  clang/include/clang/Basic/XRayInstr.h
  clang/include/clang/Driver/Options.td
  clang/include/clang/Frontend/CompilerInvocation.h
  clang/lib/Basic/XRayInstr.cpp
  clang/lib/Frontend/CompilerInvocation.cpp
  llvm/include/llvm/Option/OptParser.td

Index: llvm/include/llvm/Option/OptParser.td
===
--- llvm/include/llvm/Option/OptParser.td
+++ llvm/include/llvm/Option/OptParser.td
@@ -175,7 +175,7 @@
 class MarshallingInfoStringInt
   : MarshallingInfo {
   code Normalizer = "normalizeStringIntegral<"#type#">";
-  code Denormalizer = "denormalizeString";
+  code Denormalizer = "denormalizeString<"#type#">";
 }
 
 class MarshallingInfoStringVector
Index: clang/lib/Frontend/CompilerInvocation.cpp
===
--- clang/lib/Frontend/CompilerInvocation.cpp
+++ clang/lib/Frontend/CompilerInvocation.cpp
@@ -54,6 +54,7 @@
 #include "llvm/ADT/Hashing.h"
 #include "llvm/ADT/None.h"
 #include "llvm/ADT/Optional.h"
+#include "llvm/ADT/STLExtras.h"
 #include "llvm/ADT/SmallString.h"
 #include "llvm/ADT/SmallVector.h"
 #include "llvm/ADT/StringRef.h"
@@ -620,14 +621,17 @@
   // Run the first parse on the original arguments with dummy options and
   // diagnostics.
   SwapOpts(Res);
-  if (!Parse(Res, OriginalArgs, DummyDiags)) {
+  if (!Parse(Res, OriginalArgs, DummyDiags) ||
+  DummyDiags.getNumWarnings() != 0) {
 // If the first parse did not succeed, it must be user mistake (invalid
 // command line arguments). We won't be able to generate arguments that
 // would reproduce the same result. Let's fail again with the original
 // options and diagnostics, so all side-effects of parsing are visible.
+unsigned NumWarningsBefore = Diags.getNumWarnings();
 SwapOpts(Res);
-if (!Parse(Res, OriginalArgs, Diags))
-  return false;
+auto Success = Parse(Res, OriginalArgs, Diags);
+if (!Success || Diags.getNumWarnings() != NumWarningsBefore)
+  return Success;
 
 // Parse with original options and diagnostics succeeded even though it
 // shouldn't have. Something is off.
@@ -744,16 +748,11 @@
 
 static void getAllNoBuiltinFuncValues(ArgList &Args,
   std::vector &Funcs) {
-  SmallVector Values;
-  for (const auto &Arg : Args) {
-const Option &O = Arg->getOption();
-if (O.matches(options::OPT_fno_builtin_)) {
-  const char *FuncName = Arg->getValue();
-  if (Builtin::Context::isBuiltinFunc(FuncName))
-Values.push_back(FuncName);
-}
-  }
-  Funcs.insert(Funcs.end(), Values.begin(), Values.end());
+  std::vector Values = Args.getAllArgValues(OPT_fno_builtin_);
+  auto BuiltinEnd = llvm::partition(Values, [](const std::string FuncName) {
+return Builtin::Context::isBuiltinFunc(FuncName);
+  });
+  Funcs.insert(Funcs.end(), Values.begin(), BuiltinEnd);
 }
 
 static void GenerateAnalyzerArgs(AnalyzerOptions &Opts,
@@ -1233,6 +1232,15 @@
   }
 }
 
+static std::string serializeXRayInstrumentationBundle(const XRayInstrSet &S) {
+  llvm::SmallVector BundleParts;
+  serializeXRayInstrValue(S, BundleParts);
+  std::string Buffer;
+  llvm::raw_string_ostream OS(Buffer);
+  llvm::interleave(BundleParts, OS, [&OS](StringRef Part) { OS << Part; }, ",");
+  return OS.str();
+}
+
 // Set the profile kind using fprofile-instrument-use-path.
 static void setPGOUseInstrumentor(CodeGenOptions &Opts,
   const Twine &ProfileName) {
@@ -1254,12 +1262,258 @@
 Opts.setProfileUse(CodeGenOptions::ProfileClangInstr);
 }
 
-bool CompilerInvocation::ParseCodeGenArgs(CodeGenOptions &Opts, ArgList &Args,
-  InputKind IK,
-  DiagnosticsEngine &Diags,
-  const llvm::Triple &T,
-  const std::string &OutputFile,
-  const LangOptions &LangOptsRef) {
+void CompilerInvocation::GenerateCodeGenArgs(
+const CodeGenOptions &Opts, SmallVectorImpl &Args,
+StringAllocator SA, const llvm::Triple &T, const std::string &OutputFile,
+const LangOptions *LangOpts) {
+  const CodeGenOptions &CodeGenOpts = Opts;
+
+  if (Opts.OptimizationLevel == 0)
+GenerateArg(Args, OPT_O0, SA);
+  else
+GenerateArg(Args, OPT_O, Twine(Opts.OptimizationLevel), SA);
+
+#define CODEGEN_OPTION_WITH_MARSHALLING(   \
+PREFIX_TYPE, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM,\
+HELPTEXT, METAVAR, VALUES, SPELLING, SHOULD_PARSE, ALWAYS_EMIT, KEYPATH,   \
+DEFAULT_VALUE, IMPLIED_CHECK, IMPLIED_VAL

[PATCH] D89649: Fix __has_unique_object_representations with no_unique_address

2021-02-08 Thread Balázs Benics via Phabricator via cfe-commits
steakhal added a comment.

It looks great.




Comment at: clang/lib/AST/ASTContext.cpp:2582-2584
+int64_t BitfieldSize = Field->getBitWidthValue(Context);
+if (BitfieldSize > FieldSizeInBits)
+  return llvm::None;

Why do you return `None` here?



Comment at: clang/lib/AST/ASTContext.cpp:2595-2598
+template 
+static llvm::Optional structSubobjectsHaveUniqueObjectRepresentations(
+const RangeT &Subobjects, int64_t CurOffsetInBits, const ASTContext 
&Context,
+const clang::ASTRecordLayout &Layout) {

Why is this a template?
Can't you just take the `field_range`?

By the same token, `structSubobjectsHaveUniqueObjectRepresentations` returns an 
`optional int`. I'm confused.



Comment at: clang/test/SemaCXX/has_unique_object_reps_no_unique_addr.cpp:1
+// RUN: %clang_cc1 -triple x86_64-unknown-unknown -fsyntax-only -verify 
-std=c++2a %s
+//  expected-no-diagnostics

gbencze wrote:
> Just to be sure: is the specifying the triple here enough to ensure that this 
> always uses the Itanium ABI? I believe MSVC currently ignores the 
> `no_unique_address` attribute. Or do I need to add some more flags?
> Alternatively, the static_asserts could be modified to check `sizeof(T) > 
> [expected size with Itanium ABI] || __has_unique_object_representations(T)`
I think it's better to specify the triple exactly 



Comment at: clang/test/SemaCXX/has_unique_object_reps_no_unique_addr.cpp:42
+} // namespace TailPaddingReuse
+static_assert(__has_unique_object_representations(TailPaddingReuse::B));

Why is this outside of the namespace declaration?


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

https://reviews.llvm.org/D89649

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


[PATCH] D69560: [clang-tidy] Add 'bugprone-easily-swappable-parameters' check

2021-02-08 Thread Whisperity via Phabricator via cfe-commits
whisperity added inline comments.



Comment at: 
clang-tools-extra/clang-tidy/bugprone/EasilySwappableParametersCheck.cpp:177
+   const std::size_t StartIndex) {
+  const std::size_t NumParams = FD->getNumParams();
+  assert(StartIndex < NumParams && "out of bounds for start");

aaron.ballman wrote:
> whisperity wrote:
> > aaron.ballman wrote:
> > > Some interesting test cases to consider: varargs functions and K&R C 
> > > functions
> > > K&R C functions
> > 
> > Call me too young, but I had to look up what a "K&R C function" is, and I 
> > am absolutely baffled how this unholy construct is still supported! 
> > **But:** thanks to Clang supporting it properly in the AST, the checker 
> > works out of the box!
> > 
> > Given
> > 
> > ```
> > int foo(a, b)
> >   int a;
> >   int b;
> > {
> >   return a + b;
> > }
> > ```
> > 
> > We get the following output:
> > 
> > ```
> > /tmp/knr.c:2:3: warning: 2 adjacent parameters of 'foo' of similar type 
> > ('int') are easily swapped by mistake [bugprone-easily-swappable-parameters]
> >   int a;
> >   ^
> > /tmp/knr.c:2:7: note: the first parameter in the range is 'a'
> >   int a;
> >   ^
> > /tmp/knr.c:3:7: note: the last parameter in the range is 'b'
> >   int b;
> >   ^
> > ```
> > 
> > (even the locations are consistent!)
> > 
> > Should I add a test case for this? We could use a specifically C test case 
> > either way eventually...
> > 
> > -
> > 
> > > varargs functions
> > 
> > This is a bit of terminology, but something tells me you meant the 
> > //variadic function// here, right? As opposed to type parameter packs.
> > 
> > Given
> > 
> > ```
> > int sum(int ints...) {
> >   return 0;
> > }
> > ```
> > 
> > the AST looks something like this:
> > 
> > ```
> > `-FunctionDecl 0x56372e29e258  line:1:5 sum 
> > 'int (int, ...)'
> >   |-ParmVarDecl 0x56372e29e188  col:13 ints 'int'
> > ```
> > 
> > Should we diagnose this? And if so, how? The variadic part is not 
> > represented (at least not at first glance?) in the AST. Understanding the 
> > insides of such a function would require either overapproximatic stuff and 
> > doing a looot of extra handling, or becoming flow sensitive... and we'd 
> > still need to understand all the `va_` standard functions' semantics either 
> > way.
> > Call me too young, but I had to look up what a "K&R C function" is, and I 
> > am absolutely baffled how this unholy construct is still supported!
> 
> Ah, to be innocent again, how I miss those days. :-D
> 
> > Should I add a test case for this? We could use a specifically C test case 
> > either way eventually...
> 
> I think it'd be a useful case, but the one I was specifically more concerned 
> with is:
> ```
> // N.B.: this is C-specific and does not apply to C++.
> void f();
> 
> int main(void) {
>   f(1, 2, 3.4, "this is why we can't have nice things");
> }
> ```
> where the function has no prototype and so is treated as a varargs call.
> 
> > This is a bit of terminology, but something tells me you meant the variadic 
> > function here, right? As opposed to type parameter packs.
> 
> Yes, sorry for being unclear, I am talking about variadic functions.
> 
> > Should we diagnose this? And if so, how? The variadic part is not 
> > represented (at least not at first glance?) in the AST. Understanding the 
> > insides of such a function would require either overapproximatic stuff and 
> > doing a looot of extra handling, or becoming flow sensitive... and we'd 
> > still need to understand all the va_ standard functions' semantics either 
> > way.
> 
> Well, that's what I'm wondering, really. The arguments are certainly easy to 
> swap because the type system can't help the user to identify swaps without 
> further information (like format specifier strings). However, the checking 
> code would be... highly unpleasant, I suspect. My intuition is to say that we 
> don't support functions without prototypes at all (we just silently ignore 
> them) and that we only check the typed parameters in a variadic function 
> declaration (e.g., we'll diagnose `void foo(int i, int j, ...);` because of 
> the sequential `int` parameters, but we won't diagnose `void foo(int i, 
> ...);` even if call sites look like `foo(1, 2);`). WDYT?
It is definitely highly unpleasant, at one point I remember just glancing into 
the logic behind `printf()` related warnings in Sema and it was... odd, to say 
the least.

That is how the checker works right now. It will not diagnose `int f() {}` 
because from the looks of the function definition, it is a 0-parameter 
function. Same with the variadic `...`, it is a single parameter function 
(which has a rather //weird// parameter type).

But yes, I think I'll make this explicit in the documentation (and FWIW, the 
research paper, too). 

> However, the checking code would be... highly unpleasant, I suspect.

Incredibly, because this check purposefully targets the function defi

[PATCH] D96149: [clang][cli] Store InputKind in FrontendOptions

2021-02-08 Thread Jan Svoboda via Phabricator via cfe-commits
jansvoboda11 updated this revision to Diff 322113.
jansvoboda11 added a comment.

Fix typo in comment


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D96149

Files:
  clang/include/clang/Frontend/FrontendOptions.h
  clang/lib/Frontend/CompilerInvocation.cpp


Index: clang/lib/Frontend/CompilerInvocation.cpp
===
--- clang/lib/Frontend/CompilerInvocation.cpp
+++ clang/lib/Frontend/CompilerInvocation.cpp
@@ -2151,9 +2151,10 @@
   return false;
 }
 
-static InputKind ParseFrontendArgs(FrontendOptions &Opts, ArgList &Args,
-   DiagnosticsEngine &Diags,
-   bool &IsHeaderFile) {
+static bool ParseFrontendArgs(FrontendOptions &Opts, ArgList &Args,
+  DiagnosticsEngine &Diags, bool &IsHeaderFile) {
+  unsigned NumErrorsBefore = Diags.getNumErrors();
+
   Opts.ProgramAction = frontend::ParseSyntaxOnly;
   if (const Arg *A = Args.getLastArg(OPT_Action_Group)) {
 switch (A->getOption().getID()) {
@@ -2422,7 +2423,9 @@
 Opts.Inputs.emplace_back(std::move(Inputs[i]), IK, IsSystem);
   }
 
-  return DashX;
+  Opts.DashX = DashX;
+
+  return Diags.getNumErrors() == NumErrorsBefore;
 }
 
 std::string CompilerInvocation::GetResourcesPath(const char *Argv0,
@@ -3956,9 +3959,10 @@
   }
   Success &= ParseDiagnosticArgs(Res.getDiagnosticOpts(), Args, &Diags,
  /*DefaultDiagColor=*/false);
+  Success &= ParseFrontendArgs(Res.getFrontendOpts(), Args, Diags,
+   LangOpts.IsHeaderFile);
   // FIXME: We shouldn't have to pass the DashX option around here
-  InputKind DashX = ParseFrontendArgs(Res.getFrontendOpts(), Args, Diags,
-  LangOpts.IsHeaderFile);
+  InputKind DashX = Res.getFrontendOpts().DashX;
   ParseTargetArgs(Res.getTargetOpts(), Args, Diags);
   llvm::Triple T(Res.getTargetOpts().Triple);
   ParseHeaderSearchArgs(Res, Res.getHeaderSearchOpts(), Args, Diags,
Index: clang/include/clang/Frontend/FrontendOptions.h
===
--- clang/include/clang/Frontend/FrontendOptions.h
+++ clang/include/clang/Frontend/FrontendOptions.h
@@ -374,6 +374,10 @@
   std::string MTMigrateDir;
   std::string ARCMTMigrateReportOut;
 
+  /// The input kind, either specified via -x argument or deduced from the 
input
+  /// file name.
+  InputKind DashX;
+
   /// The input files and their types.
   SmallVector Inputs;
 


Index: clang/lib/Frontend/CompilerInvocation.cpp
===
--- clang/lib/Frontend/CompilerInvocation.cpp
+++ clang/lib/Frontend/CompilerInvocation.cpp
@@ -2151,9 +2151,10 @@
   return false;
 }
 
-static InputKind ParseFrontendArgs(FrontendOptions &Opts, ArgList &Args,
-   DiagnosticsEngine &Diags,
-   bool &IsHeaderFile) {
+static bool ParseFrontendArgs(FrontendOptions &Opts, ArgList &Args,
+  DiagnosticsEngine &Diags, bool &IsHeaderFile) {
+  unsigned NumErrorsBefore = Diags.getNumErrors();
+
   Opts.ProgramAction = frontend::ParseSyntaxOnly;
   if (const Arg *A = Args.getLastArg(OPT_Action_Group)) {
 switch (A->getOption().getID()) {
@@ -2422,7 +2423,9 @@
 Opts.Inputs.emplace_back(std::move(Inputs[i]), IK, IsSystem);
   }
 
-  return DashX;
+  Opts.DashX = DashX;
+
+  return Diags.getNumErrors() == NumErrorsBefore;
 }
 
 std::string CompilerInvocation::GetResourcesPath(const char *Argv0,
@@ -3956,9 +3959,10 @@
   }
   Success &= ParseDiagnosticArgs(Res.getDiagnosticOpts(), Args, &Diags,
  /*DefaultDiagColor=*/false);
+  Success &= ParseFrontendArgs(Res.getFrontendOpts(), Args, Diags,
+   LangOpts.IsHeaderFile);
   // FIXME: We shouldn't have to pass the DashX option around here
-  InputKind DashX = ParseFrontendArgs(Res.getFrontendOpts(), Args, Diags,
-  LangOpts.IsHeaderFile);
+  InputKind DashX = Res.getFrontendOpts().DashX;
   ParseTargetArgs(Res.getTargetOpts(), Args, Diags);
   llvm::Triple T(Res.getTargetOpts().Triple);
   ParseHeaderSearchArgs(Res, Res.getHeaderSearchOpts(), Args, Diags,
Index: clang/include/clang/Frontend/FrontendOptions.h
===
--- clang/include/clang/Frontend/FrontendOptions.h
+++ clang/include/clang/Frontend/FrontendOptions.h
@@ -374,6 +374,10 @@
   std::string MTMigrateDir;
   std::string ARCMTMigrateReportOut;
 
+  /// The input kind, either specified via -x argument or deduced from the input
+  /// file name.
+  InputKind DashX;
+
   /// The input files and their types.
   SmallVector Inputs;
 
___
cfe-commits mailing list
cfe-commits@lists.llvm.

[PATCH] D91054: [Clang][OpenMP] Frontend work for sections - D89671

2021-02-08 Thread Johannes Doerfert via Phabricator via cfe-commits
jdoerfert added a comment.

In D91054#2548266 , @AMDChirag wrote:

> @fghanim @jdoerfert please review the code if/when possible.

Let's resolve the issue described in the TODO before we go ahead with this. 
There is little point reviewing something that can't be tested.
That said,




Comment at: clang/lib/CodeGen/CGStmtOpenMP.cpp:3579
+SectionCBVector.push_back(SectionCB);
+  }
+} else {

Why do we unpack the children here instead of making a single call back for the 
CapturedStmt?



Comment at: clang/test/OpenMP/cancel_sections_irbuilder.cpp:14
+// which in turn causes FiniCB callback to fail in FinalizeOMPRegion()
+// as no terminator instruction (br) exists for the cancel block (.cncl)
+

I don't get it. Where is EmitOMPRegionBody called on the `.cncl` block 
such that it would remove the terminator? 

Maybe you could share the IR at the different levels if you need help resolving 
the problem.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D91054

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


[PATCH] D96151: [OpenCL] Fix pipe type printing in arg info metadata

2021-02-08 Thread Anastasia Stulova via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rGecc8ac3f081b: [OpenCL] Fix pipe type printing in arg info 
metadata (authored by Anastasia).
Herald added a project: clang.

Changed prior to commit:
  https://reviews.llvm.org/D96151?vs=321799&id=322114#toc

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D96151

Files:
  clang/lib/CodeGen/CodeGenModule.cpp
  clang/test/CodeGenOpenCL/kernel-arg-info.cl

Index: clang/test/CodeGenOpenCL/kernel-arg-info.cl
===
--- clang/test/CodeGenOpenCL/kernel-arg-info.cl
+++ clang/test/CodeGenOpenCL/kernel-arg-info.cl
@@ -85,6 +85,7 @@
 typedef read_write image1d_t RWImage;
 kernel void foo7(ROImage ro, WOImage wo, RWImage rw) {
 }
+
 // CHECK: define{{.*}} spir_kernel void @foo7{{[^!]+}}
 // CHECK: !kernel_arg_addr_space ![[MD71:[0-9]+]]
 // CHECK: !kernel_arg_access_qual ![[MD72:[0-9]+]]
@@ -94,6 +95,18 @@
 // CHECK-NOT: !kernel_arg_name
 // ARGINFO: !kernel_arg_name ![[MD76:[0-9]+]]
 
+typedef unsigned char uchar;
+typedef uchar uchar2 __attribute__((ext_vector_type(2)));
+kernel void foo8(pipe int p1, pipe uchar p2, pipe uchar2 p3, const pipe uchar p4, write_only pipe uchar p5) {}
+// CHECK: define{{.*}} spir_kernel void @foo8{{[^!]+}}
+// CHECK: !kernel_arg_addr_space ![[PIPE_AS_QUAL:[0-9]+]]
+// CHECK: !kernel_arg_access_qual ![[PIPE_ACCESS_QUAL:[0-9]+]]
+// CHECK: !kernel_arg_type ![[PIPE_TY:[0-9]+]]
+// CHECK: !kernel_arg_base_type ![[PIPE_BASE_TY:[0-9]+]]
+// CHECK: !kernel_arg_type_qual ![[PIPE_QUAL:[0-9]+]]
+// CHECK-NOT: !kernel_arg_name
+// ARGINFO: !kernel_arg_name ![[PIPE_ARG_NAMES:[0-9]+]]
+
 // CHECK: ![[MD11]] = !{i32 1, i32 1, i32 1, i32 1, i32 2, i32 2, i32 1, i32 1, i32 1, i32 1, i32 3, i32 3, i32 3, i32 3, i32 3, i32 3, i32 3, i32 3, i32 0, i32 0, i32 0, i32 0}
 // CHECK: ![[MD12]] = !{!"none", !"none", !"none", !"none", !"none", !"none", !"none", !"none", !"none", !"none", !"none", !"none", !"none", !"none", !"none", !"none", !"none", !"none", !"none", !"none", !"none", !"none"}
 // CHECK: ![[MD13]] = !{!"int*", !"int*", !"int*", !"int*", !"int*", !"int*", !"int*", !"int*", !"int*", !"int*", !"int*", !"int*", !"int*", !"int*", !"int*", !"int*", !"int*", !"int*", !"int", !"int", !"int", !"int"}
@@ -127,4 +140,9 @@
 // CHECK: ![[MD74]] = !{!"image1d_t", !"image1d_t", !"image1d_t"}
 // CHECK: ![[MD75]] = !{!"", !"", !""}
 // ARGINFO: ![[MD76]] = !{!"ro", !"wo", !"rw"}
-
+// CHECK: ![[PIPE_AS_QUAL]] = !{i32 1, i32 1, i32 1, i32 1, i32 1}
+// CHECK: ![[PIPE_ACCESS_QUAL]] = !{!"read_only", !"read_only", !"read_only", !"read_only", !"write_only"}
+// CHECK: ![[PIPE_TY]] = !{!"int", !"uchar", !"uchar2", !"uchar", !"uchar"}
+// CHECK: ![[PIPE_BASE_TY]] = !{!"int", !"uchar", !"uchar __attribute__((ext_vector_type(2)))", !"uchar", !"uchar"}
+// CHECK: ![[PIPE_QUAL]] = !{!"pipe", !"pipe", !"pipe", !"pipe", !"pipe"}
+// ARGINFO: ![[PIPE_ARG_NAMES]] = !{!"p1", !"p2", !"p3", !"p4", !"p5"}
Index: clang/lib/CodeGen/CodeGenModule.cpp
===
--- clang/lib/CodeGen/CodeGenModule.cpp
+++ clang/lib/CodeGen/CodeGenModule.cpp
@@ -1475,6 +1475,37 @@
   QualType ty = parm->getType();
   std::string typeQuals;
 
+  // Get image and pipe access qualifier:
+  if (ty->isImageType() || ty->isPipeType()) {
+const Decl *PDecl = parm;
+if (auto *TD = dyn_cast(ty))
+  PDecl = TD->getDecl();
+const OpenCLAccessAttr *A = PDecl->getAttr();
+if (A && A->isWriteOnly())
+  accessQuals.push_back(llvm::MDString::get(VMContext, "write_only"));
+else if (A && A->isReadWrite())
+  accessQuals.push_back(llvm::MDString::get(VMContext, "read_write"));
+else
+  accessQuals.push_back(llvm::MDString::get(VMContext, "read_only"));
+  } else
+accessQuals.push_back(llvm::MDString::get(VMContext, "none"));
+
+  // Get argument name.
+  argNames.push_back(llvm::MDString::get(VMContext, parm->getName()));
+
+  auto getTypeSpelling = [&](QualType Ty) {
+auto typeName = Ty.getUnqualifiedType().getAsString(Policy);
+
+if (Ty.isCanonical()) {
+  StringRef typeNameRef = typeName;
+  // Turn "unsigned type" to "utype"
+  if (typeNameRef.consume_front("unsigned "))
+return std::string("u") + typeNameRef.str();
+}
+
+return typeName;
+  };
+
   if (ty->isPointerType()) {
 QualType pointeeTy = ty->getPointeeType();
 
@@ -1484,26 +1515,10 @@
 ArgInfoAddressSpace(pointeeTy.getAddressSpace();
 
 // Get argument type name.
-std::string typeName =
-pointeeTy.getUnqualifiedType().getAsString(Policy) + "*";
-
-// Turn "unsigned type" to "utype"
-std::string::size_type pos = typeName.find("unsigned");
-if (po

[PATCH] D96269: [clang][cli] Look up program action argument in a table

2021-02-08 Thread Jan Svoboda via Phabricator via cfe-commits
jansvoboda11 created this revision.
jansvoboda11 added reviewers: Bigcheese, dexonsmith.
jansvoboda11 requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

This patch extracts the mapping between command line option and 
frontend::ActionKind into a table. The table can be reused when parsing and 
also generating command line options.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D96269

Files:
  clang/lib/Frontend/CompilerInvocation.cpp

Index: clang/lib/Frontend/CompilerInvocation.cpp
===
--- clang/lib/Frontend/CompilerInvocation.cpp
+++ clang/lib/Frontend/CompilerInvocation.cpp
@@ -2151,19 +2151,84 @@
   return false;
 }
 
+/// Return a table that associates command line option specifiers with the
+/// frontend action. Note: The pair {frontend::PluginAction, OPT_plugin} is
+/// intentionally missing, as this case is handled separately from other
+/// frontend options.
+static const auto &getFrontendActionTable() {
+  static const std::pair Table[] = {
+  {frontend::ASTDeclList, OPT_ast_list},
+
+  {frontend::ASTDump, OPT_ast_dump_all_EQ},
+  {frontend::ASTDump, OPT_ast_dump_all},
+  {frontend::ASTDump, OPT_ast_dump_EQ},
+  {frontend::ASTDump, OPT_ast_dump},
+  {frontend::ASTDump, OPT_ast_dump_lookups},
+  {frontend::ASTDump, OPT_ast_dump_decl_types},
+
+  {frontend::ASTPrint, OPT_ast_print},
+  {frontend::ASTView, OPT_ast_view},
+  {frontend::DumpCompilerOptions, OPT_compiler_options_dump},
+  {frontend::DumpRawTokens, OPT_dump_raw_tokens},
+  {frontend::DumpTokens, OPT_dump_tokens},
+  {frontend::EmitAssembly, OPT_S},
+  {frontend::EmitBC, OPT_emit_llvm_bc},
+  {frontend::EmitHTML, OPT_emit_html},
+  {frontend::EmitLLVM, OPT_emit_llvm},
+  {frontend::EmitLLVMOnly, OPT_emit_llvm_only},
+  {frontend::EmitCodeGenOnly, OPT_emit_codegen_only},
+  {frontend::EmitCodeGenOnly, OPT_emit_codegen_only},
+  {frontend::EmitObj, OPT_emit_obj},
+
+  {frontend::FixIt, OPT_fixit_EQ},
+  {frontend::FixIt, OPT_fixit},
+
+  {frontend::GenerateModule, OPT_emit_module},
+  {frontend::GenerateModuleInterface, OPT_emit_module_interface},
+  {frontend::GenerateHeaderModule, OPT_emit_header_module},
+  {frontend::GeneratePCH, OPT_emit_pch},
+  {frontend::GenerateInterfaceStubs, OPT_emit_interface_stubs},
+  {frontend::InitOnly, OPT_init_only},
+  {frontend::ParseSyntaxOnly, OPT_fsyntax_only},
+  {frontend::ModuleFileInfo, OPT_module_file_info},
+  {frontend::VerifyPCH, OPT_verify_pch},
+  {frontend::PrintPreamble, OPT_print_preamble},
+  {frontend::PrintPreprocessedInput, OPT_E},
+  {frontend::TemplightDump, OPT_templight_dump},
+  {frontend::RewriteMacros, OPT_rewrite_macros},
+  {frontend::RewriteObjC, OPT_rewrite_objc},
+  {frontend::RewriteTest, OPT_rewrite_test},
+  {frontend::RunAnalysis, OPT_analyze},
+  {frontend::MigrateSource, OPT_migrate},
+  {frontend::RunPreprocessorOnly, OPT_Eonly},
+  {frontend::PrintDependencyDirectivesSourceMinimizerOutput,
+  OPT_print_dependency_directives_minimized_source},
+  };
+
+  return Table;
+}
+
+/// Maps command line option to frontend action.
+static Optional getFrontendAction(OptSpecifier &Opt) {
+  for (const auto &ActionOpt : getFrontendActionTable())
+if (ActionOpt.second == Opt)
+  return ActionOpt.first;
+
+  return None;
+}
+
 static bool ParseFrontendArgs(FrontendOptions &Opts, ArgList &Args,
   DiagnosticsEngine &Diags, bool &IsHeaderFile) {
   unsigned NumErrorsBefore = Diags.getNumErrors();
 
   Opts.ProgramAction = frontend::ParseSyntaxOnly;
   if (const Arg *A = Args.getLastArg(OPT_Action_Group)) {
-switch (A->getOption().getID()) {
-default:
-  llvm_unreachable("Invalid option in group!");
-case OPT_ast_list:
-  Opts.ProgramAction = frontend::ASTDeclList; break;
-case OPT_ast_dump_all_EQ:
-case OPT_ast_dump_EQ: {
+OptSpecifier Opt = OptSpecifier(A->getOption().getID());
+Optional ProgramAction = getFrontendAction(Opt);
+assert(ProgramAction && "Option specifier not in Action_Group.");
+
+if (ProgramAction == frontend::ASTDump &&
+(Opt == OPT_ast_dump_all_EQ || Opt == OPT_ast_dump_EQ)) {
   unsigned Val = llvm::StringSwitch(A->getValue())
  .CaseLower("default", ADOF_Default)
  .CaseLower("json", ADOF_JSON)
@@ -2176,51 +2241,12 @@
 << A->getAsString(Args) << A->getValue();
 Opts.ASTDumpFormat = ADOF_Default;
   }
-  LLVM_FALLTHROUGH;
 }
-case OPT_ast_dump:
-case OPT_ast_dump_all:
-case OPT_ast_dump_lookups:
-case OPT_ast_dump_decl_types:
-  Opts.ProgramAction = frontend::ASTDump; break;
-case OPT_ast_print:
-  Opts.ProgramAction = frontend::ASTPrint; break;
-case OPT

[PATCH] D96161: [OpenCL] Fix printing of types with signed prefix in arg info metadata

2021-02-08 Thread Anastasia Stulova via Phabricator via cfe-commits
Anastasia marked an inline comment as done.
Anastasia added inline comments.



Comment at: clang/lib/CodeGen/CodeGenModule.cpp:1500
 StringRef typeNameRef = typeName;
 // Turn "unsigned type" to "utype"
 if (Ty.isCanonical()) {

stuart wrote:
> It'd make sense to push this comment down one line, above the 
> `consume_front("unsigned ")` call, as it doesn't apply to the 
> `consume_front("signed ")` call - or reword it so it covers both 
> substitutions.
This has been addressed in the parent review:
https://reviews.llvm.org/D96151


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

https://reviews.llvm.org/D96161

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


[PATCH] D95714: [clang-tidy] fix modernize-use-nullptr false positive with spaceship operator comparisons

2021-02-08 Thread Nathan James via Phabricator via cfe-commits
njames93 accepted this revision.
njames93 added a comment.
This revision is now accepted and ready to land.
Herald added a subscriber: nullptr.cpp.

LGTM, Same as last time for the commit?


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

https://reviews.llvm.org/D95714

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


[PATCH] D96056: [clang][cli] Generate and round-trip CodeGen options

2021-02-08 Thread Jan Svoboda via Phabricator via cfe-commits
jansvoboda11 updated this revision to Diff 322118.
jansvoboda11 added a comment.

Rebase


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D96056

Files:
  clang/include/clang/Basic/XRayInstr.h
  clang/include/clang/Driver/Options.td
  clang/include/clang/Frontend/CompilerInvocation.h
  clang/lib/Basic/XRayInstr.cpp
  clang/lib/Frontend/CompilerInvocation.cpp
  llvm/include/llvm/Option/OptParser.td

Index: llvm/include/llvm/Option/OptParser.td
===
--- llvm/include/llvm/Option/OptParser.td
+++ llvm/include/llvm/Option/OptParser.td
@@ -175,7 +175,7 @@
 class MarshallingInfoStringInt
   : MarshallingInfo {
   code Normalizer = "normalizeStringIntegral<"#type#">";
-  code Denormalizer = "denormalizeString";
+  code Denormalizer = "denormalizeString<"#type#">";
 }
 
 class MarshallingInfoStringVector
Index: clang/lib/Frontend/CompilerInvocation.cpp
===
--- clang/lib/Frontend/CompilerInvocation.cpp
+++ clang/lib/Frontend/CompilerInvocation.cpp
@@ -54,6 +54,7 @@
 #include "llvm/ADT/Hashing.h"
 #include "llvm/ADT/None.h"
 #include "llvm/ADT/Optional.h"
+#include "llvm/ADT/STLExtras.h"
 #include "llvm/ADT/SmallString.h"
 #include "llvm/ADT/SmallVector.h"
 #include "llvm/ADT/StringRef.h"
@@ -620,14 +621,17 @@
   // Run the first parse on the original arguments with dummy options and
   // diagnostics.
   SwapOpts(Res);
-  if (!Parse(Res, OriginalArgs, DummyDiags)) {
+  if (!Parse(Res, OriginalArgs, DummyDiags) ||
+  DummyDiags.getNumWarnings() != 0) {
 // If the first parse did not succeed, it must be user mistake (invalid
 // command line arguments). We won't be able to generate arguments that
 // would reproduce the same result. Let's fail again with the original
 // options and diagnostics, so all side-effects of parsing are visible.
+unsigned NumWarningsBefore = Diags.getNumWarnings();
 SwapOpts(Res);
-if (!Parse(Res, OriginalArgs, Diags))
-  return false;
+auto Success = Parse(Res, OriginalArgs, Diags);
+if (!Success || Diags.getNumWarnings() != NumWarningsBefore)
+  return Success;
 
 // Parse with original options and diagnostics succeeded even though it
 // shouldn't have. Something is off.
@@ -744,16 +748,11 @@
 
 static void getAllNoBuiltinFuncValues(ArgList &Args,
   std::vector &Funcs) {
-  SmallVector Values;
-  for (const auto &Arg : Args) {
-const Option &O = Arg->getOption();
-if (O.matches(options::OPT_fno_builtin_)) {
-  const char *FuncName = Arg->getValue();
-  if (Builtin::Context::isBuiltinFunc(FuncName))
-Values.push_back(FuncName);
-}
-  }
-  Funcs.insert(Funcs.end(), Values.begin(), Values.end());
+  std::vector Values = Args.getAllArgValues(OPT_fno_builtin_);
+  auto BuiltinEnd = llvm::partition(Values, [](const std::string FuncName) {
+return Builtin::Context::isBuiltinFunc(FuncName);
+  });
+  Funcs.insert(Funcs.end(), Values.begin(), BuiltinEnd);
 }
 
 static void GenerateAnalyzerArgs(AnalyzerOptions &Opts,
@@ -1233,6 +1232,15 @@
   }
 }
 
+static std::string serializeXRayInstrumentationBundle(const XRayInstrSet &S) {
+  llvm::SmallVector BundleParts;
+  serializeXRayInstrValue(S, BundleParts);
+  std::string Buffer;
+  llvm::raw_string_ostream OS(Buffer);
+  llvm::interleave(BundleParts, OS, [&OS](StringRef Part) { OS << Part; }, ",");
+  return OS.str();
+}
+
 // Set the profile kind using fprofile-instrument-use-path.
 static void setPGOUseInstrumentor(CodeGenOptions &Opts,
   const Twine &ProfileName) {
@@ -1254,12 +1262,258 @@
 Opts.setProfileUse(CodeGenOptions::ProfileClangInstr);
 }
 
-bool CompilerInvocation::ParseCodeGenArgs(CodeGenOptions &Opts, ArgList &Args,
-  InputKind IK,
-  DiagnosticsEngine &Diags,
-  const llvm::Triple &T,
-  const std::string &OutputFile,
-  const LangOptions &LangOptsRef) {
+void CompilerInvocation::GenerateCodeGenArgs(
+const CodeGenOptions &Opts, SmallVectorImpl &Args,
+StringAllocator SA, const llvm::Triple &T, const std::string &OutputFile,
+const LangOptions *LangOpts) {
+  const CodeGenOptions &CodeGenOpts = Opts;
+
+  if (Opts.OptimizationLevel == 0)
+GenerateArg(Args, OPT_O0, SA);
+  else
+GenerateArg(Args, OPT_O, Twine(Opts.OptimizationLevel), SA);
+
+#define CODEGEN_OPTION_WITH_MARSHALLING(   \
+PREFIX_TYPE, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM,\
+HELPTEXT, METAVAR, VALUES, SPELLING, SHOULD_PARSE, ALWAYS_EMIT, KEYPATH,   \
+DEFAULT_VALUE, IMPLIED_CHECK, IMPLIED_VALUE, NORMALIZER, DENORMALIZE

[PATCH] D95822: [FE] Manipulate the first byte of guard variable type in both load and store operation

2021-02-08 Thread Xiangling Liao via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG6b1e2fc89327: [FE] Manipulate the first byte of guard 
variable type in both load and store… (authored by Xiangling_L).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D95822

Files:
  clang/lib/CodeGen/ItaniumCXXABI.cpp
  clang/test/CodeGenCXX/aix-static-init-temp-spec-and-inline-var.cpp
  clang/test/CodeGenCXX/aix-static-init.cpp
  clang/test/CodeGenCXX/cxx11-thread-local.cpp
  clang/test/CodeGenCXX/global-init.cpp
  clang/test/CodeGenCXX/static-data-member.cpp

Index: clang/test/CodeGenCXX/static-data-member.cpp
===
--- clang/test/CodeGenCXX/static-data-member.cpp
+++ clang/test/CodeGenCXX/static-data-member.cpp
@@ -72,7 +72,7 @@
   // CHECK-NEXT: br i1 [[UNINITIALIZED]]
   // CHECK:  [[TMP:%.*]] = call i32 @_ZN5test33fooEv()
   // CHECK-NEXT: store i32 [[TMP]], i32* @_ZN5test31AIiE1xE, align 4
-  // CHECK-NEXT: store i64 1, i64* @_ZGVN5test31AIiE1xE
+  // CHECK-NEXT: store i8 1, i8* bitcast (i64* @_ZGVN5test31AIiE1xE to i8*)
   // CHECK-NEXT: br label
   // CHECK:  ret void
 }
Index: clang/test/CodeGenCXX/global-init.cpp
===
--- clang/test/CodeGenCXX/global-init.cpp
+++ clang/test/CodeGenCXX/global-init.cpp
@@ -78,10 +78,10 @@
   extern int foo();
 
   // This needs an initialization function and guard variables.
-  // CHECK: load i8, i8* bitcast (i64* @_ZGVN5test41xE
+  // CHECK: load i8, i8* bitcast (i64* @_ZGVN5test41xE to i8*)
   // CHECK: [[CALL:%.*]] = call i32 @_ZN5test43fooEv
   // CHECK-NEXT: store i32 [[CALL]], i32* @_ZN5test41xE
-  // CHECK-NEXT: store i64 1, i64* @_ZGVN5test41xE
+  // CHECK-NEXT: store i8 1, i8* bitcast (i64* @_ZGVN5test41xE to i8*)
   __attribute__((weak)) int x = foo();
 }
 
Index: clang/test/CodeGenCXX/cxx11-thread-local.cpp
===
--- clang/test/CodeGenCXX/cxx11-thread-local.cpp
+++ clang/test/CodeGenCXX/cxx11-thread-local.cpp
@@ -184,7 +184,7 @@
 // need init:
 // CHECK: call i32 @_Z1gv()
 // CHECK: store i32 %{{.*}}, i32* @_ZN1VIfE1mE, align 4
-// CHECK: store i64 1, i64* @_ZGVN1VIfE1mE
+// CHECK: store i8 1, i8* bitcast (i64* @_ZGVN1VIfE1mE to i8*)
 // CHECK: br label
 
 // LINUX: define internal void @[[XF_M_INIT]]()
@@ -197,7 +197,7 @@
 // need init:
 // LINUX: call {{.*}}__cxa_thread_atexit
 // DARWIN: call {{.*}}_tlv_atexit
-// CHECK: store i64 1, i64* @_ZGVN1XIfE1mE
+// CHECK: store i8 1, i8* bitcast (i64* @_ZGVN1XIfE1mE to i8*)
 // CHECK: br label
 
 // LINUX: declare i32 @__cxa_thread_atexit(void (i8*)*, i8*, i8*)
@@ -285,7 +285,7 @@
 // need init:
 // CHECK: call i32 @_Z1gv()
 // CHECK: store i32 %{{.*}}, i32* @_ZN1VIiE1mE, align 4
-// CHECK: store i64 1, i64* @_ZGVN1VIiE1mE
+// CHECK: store i8 1, i8* bitcast (i64* @_ZGVN1VIiE1mE to i8*)
 // CHECK: br label
 
 // LINUX: define internal void @[[X_M_INIT]]()
@@ -298,7 +298,7 @@
 // need init:
 // LINUX: call {{.*}}__cxa_thread_atexit
 // DARWIN: call {{.*}}_tlv_atexit
-// CHECK: store i64 1, i64* @_ZGVN1XIiE1mE
+// CHECK: store i8 1, i8* bitcast (i64* @_ZGVN1XIiE1mE to i8*)
 // CHECK: br label
 
 // CHECK: define {{.*}}@[[GLOBAL_INIT:.*]]()
Index: clang/test/CodeGenCXX/aix-static-init.cpp
===
--- clang/test/CodeGenCXX/aix-static-init.cpp
+++ clang/test/CodeGenCXX/aix-static-init.cpp
@@ -38,6 +38,7 @@
   }
 } // namespace test4
 
+// CHECK: @_ZGVZN5test41fEvE11staticLocal = internal global i64 0, align 8
 // CHECK: @llvm.global_ctors = appending global [1 x { i32, void ()*, i8* }] [{ i32, void ()*, i8* } { i32 65535, void ()* @_GLOBAL__sub_I__, i8* null }]
 // CHECK: @llvm.global_dtors = appending global [1 x { i32, void ()*, i8* }] [{ i32, void ()*, i8* } { i32 65535, void ()* @_GLOBAL__D_a, i8* null }]
 
@@ -135,7 +136,7 @@
 
 // CHECK: define void @_ZN5test41fEv() [[ATTR:#[0-9]+]] {
 // CHECK: entry:
-// CHECK:   %0 = load atomic i8, i8* bitcast (i64* @_ZGVZN5test41fEvE11staticLocal to i8*) acquire
+// CHECK:   %0 = load atomic i8, i8* bitcast (i64* @_ZGVZN5test41fEvE11staticLocal to i8*) acquire, align 8
 // CHECK:   %guard.uninitialized = icmp eq i8 %0, 0
 // CHECK:   br i1 %guard.uninitialized, label %init.check, label %init.end
 
Index: clang/test/CodeGenCXX/aix-static-init-temp-spec-and-inline-var.cpp
===
--- clang/test/CodeGenCXX/aix-static-init-temp-spec-and-inline-var.cpp
+++ clang/test/CodeGenCXX/aix-static-init-temp-spec-and-inline-var.cpp
@@ -44,6 +44,9 @@
 A A::instance = bar();
 } // namespace test2
 
+// CHECK: @_ZGVN5test12t2E = linkonce_odr global i64 0, align 8
+// CHECK: @_ZGVN5test21AIvE8instanceE = weak_odr global i64 0, align 8
+// CHECK: @_ZGVN5test12t1IiEE = linkonce_odr global i64 0, align 8
 /

[clang] 6b1e2fc - [FE] Manipulate the first byte of guard variable type in both load and store operation

2021-02-08 Thread Xiangling Liao via cfe-commits

Author: Xiangling Liao
Date: 2021-02-08T11:14:34-05:00
New Revision: 6b1e2fc89327a64c9300d543e00f12435c32dfcf

URL: 
https://github.com/llvm/llvm-project/commit/6b1e2fc89327a64c9300d543e00f12435c32dfcf
DIFF: 
https://github.com/llvm/llvm-project/commit/6b1e2fc89327a64c9300d543e00f12435c32dfcf.diff

LOG: [FE] Manipulate the first byte of guard variable type in both load and 
store operation

As Itanium ABI[http://itanium-cxx-abi.github.io/cxx-abi/abi.html#once-ctor]
points out:

"The size of the guard variable is 64 bits. The first byte (i.e. the byte at
the address of the full variable) shall contain the value 0 prior to
initialization of the associated variable, and 1 after initialization is 
complete."

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

Added: 


Modified: 
clang/lib/CodeGen/ItaniumCXXABI.cpp
clang/test/CodeGenCXX/aix-static-init-temp-spec-and-inline-var.cpp
clang/test/CodeGenCXX/aix-static-init.cpp
clang/test/CodeGenCXX/cxx11-thread-local.cpp
clang/test/CodeGenCXX/global-init.cpp
clang/test/CodeGenCXX/static-data-member.cpp

Removed: 




diff  --git a/clang/lib/CodeGen/ItaniumCXXABI.cpp 
b/clang/lib/CodeGen/ItaniumCXXABI.cpp
index 50fb30a95cbb..b92801a516e9 100644
--- a/clang/lib/CodeGen/ItaniumCXXABI.cpp
+++ b/clang/lib/CodeGen/ItaniumCXXABI.cpp
@@ -2472,7 +2472,10 @@ void ItaniumCXXABI::EmitGuardedInit(CodeGenFunction &CGF,
 CGF.EmitNounwindRuntimeCall(getGuardReleaseFn(CGM, guardPtrTy),
 guardAddr.getPointer());
   } else {
-Builder.CreateStore(llvm::ConstantInt::get(guardTy, 1), guardAddr);
+// Store 1 into the first byte of the guard variable after initialization 
is
+// complete.
+Builder.CreateStore(llvm::ConstantInt::get(CGM.Int8Ty, 1),
+Builder.CreateElementBitCast(guardAddr, CGM.Int8Ty));
   }
 
   CGF.EmitBlock(EndBlock);

diff  --git 
a/clang/test/CodeGenCXX/aix-static-init-temp-spec-and-inline-var.cpp 
b/clang/test/CodeGenCXX/aix-static-init-temp-spec-and-inline-var.cpp
index f7e4c0a86b46..799b158bcf60 100644
--- a/clang/test/CodeGenCXX/aix-static-init-temp-spec-and-inline-var.cpp
+++ b/clang/test/CodeGenCXX/aix-static-init-temp-spec-and-inline-var.cpp
@@ -44,6 +44,9 @@ template <>
 A A::instance = bar();
 } // namespace test2
 
+// CHECK: @_ZGVN5test12t2E = linkonce_odr global i64 0, align 8
+// CHECK: @_ZGVN5test21AIvE8instanceE = weak_odr global i64 0, align 8
+// CHECK: @_ZGVN5test12t1IiEE = linkonce_odr global i64 0, align 8
 // CHECK: @llvm.global_ctors = appending global [4 x { i32, void ()*, i8* }] 
[{ i32, void ()*, i8* } { i32 65535, void ()* @__cxx_global_var_init.1, i8* 
null }, { i32, void ()*, i8* } { i32 65535, void ()* @__cxx_global_var_init.2, 
i8* null }, { i32, void ()*, i8* } { i32 65535, void ()* 
@__cxx_global_var_init.4, i8* null }, { i32, void ()*, i8* } { i32 65535, void 
()* @_GLOBAL__sub_I__, i8* null }]
 // CHECK: @llvm.global_dtors = appending global [4 x { i32, void ()*, i8* }] 
[{ i32, void ()*, i8* } { i32 65535, void ()* @__finalize__ZN5test12t2E, i8* 
null }, { i32, void ()*, i8* } { i32 65535, void ()* 
@__finalize__ZN5test21AIvE8instanceE, i8* null }, { i32, void ()*, i8* } { i32 
65535, void ()* @__finalize__ZN5test12t1IiEE, i8* null }, { i32, void ()*, i8* 
} { i32 65535, void ()* @_GLOBAL__D_a, i8* null }]
 
@@ -77,7 +80,7 @@ A A::instance = bar();
 
 // CHECK: define internal void @__cxx_global_var_init.1() [[ATTR:#[0-9]+]] {
 // CHECK: entry:
-// CHECK:   %0 = load atomic i8, i8* bitcast (i64* @_ZGVN5test12t2E to i8*) 
acquire
+// CHECK:   %0 = load atomic i8, i8* bitcast (i64* @_ZGVN5test12t2E to i8*) 
acquire, align 8
 // CHECK:   %guard.uninitialized = icmp eq i8 %0, 0
 // CHECK:   br i1 %guard.uninitialized, label %init.check, label %init.end
 
@@ -119,14 +122,14 @@ A A::instance = bar();
 
 // CHECK: define internal void @__cxx_global_var_init.2() [[ATTR:#[0-9]+]] {
 // CHECK: entry:
-// CHECK:   %0 = load i8, i8* bitcast (i64* @_ZGVN5test21AIvE8instanceE to i8*)
+// CHECK:   %0 = load i8, i8* bitcast (i64* @_ZGVN5test21AIvE8instanceE to 
i8*), align 8
 // CHECK:   %guard.uninitialized = icmp eq i8 %0, 0
 // CHECK:   br i1 %guard.uninitialized, label %init.check, label %init.end
 
 // CHECK: init.check:
 // CHECK:   call void @_ZN5test21AIvEC1Ev(%"struct.test2::A"* {{[^,]*}} 
@_ZN5test21AIvE8instanceE)
 // CHECK:   %1 = call i32 @atexit(void ()* @__dtor__ZN5test21AIvE8instanceE)
-// CHECK:   store i64 1, i64* @_ZGVN5test21AIvE8instanceE
+// CHECK:   store i8 1, i8* bitcast (i64* @_ZGVN5test21AIvE8instanceE to i8*), 
align 8
 // CHECK:   br label %init.end
 
 // CHECK: init.end:
@@ -182,7 +185,7 @@ A A::instance = bar();
 
 // CHECK: define internal void @__cxx_global_var_init.4() [[ATTR:#[0-9]+]] {
 // CHECK: entry:
-// CHECK:   %0 = load i8, i8* bitcast (i64* @_ZGVN5test12t1IiEE to i8*)
+// CHECK:   %0 = load i8, i8* bitcast (i64* @_ZGV

[PATCH] D96155: [clang][cli] Generate and round-trip Frontend options

2021-02-08 Thread Jan Svoboda via Phabricator via cfe-commits
jansvoboda11 updated this revision to Diff 322120.
jansvoboda11 added a comment.

Document getProgramActionOpt


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D96155

Files:
  clang/include/clang/Driver/Options.td
  clang/include/clang/Frontend/CommandLineSourceLoc.h
  clang/include/clang/Serialization/ModuleFileExtension.h
  clang/lib/Frontend/CompilerInvocation.cpp
  clang/lib/Frontend/TestModuleFileExtension.cpp
  clang/lib/Frontend/TestModuleFileExtension.h

Index: clang/lib/Frontend/TestModuleFileExtension.h
===
--- clang/lib/Frontend/TestModuleFileExtension.h
+++ clang/lib/Frontend/TestModuleFileExtension.h
@@ -48,7 +48,8 @@
   unsigned MinorVersion,
   bool Hashed,
   StringRef UserInfo)
-: BlockName(BlockName),
+: ModuleFileExtension(ModuleFileExtensionKind::MFEK_Test),
+  BlockName(BlockName),
   MajorVersion(MajorVersion), MinorVersion(MinorVersion),
   Hashed(Hashed), UserInfo(UserInfo) { }
   ~TestModuleFileExtension() override;
@@ -64,6 +65,14 @@
   createExtensionReader(const ModuleFileExtensionMetadata &Metadata,
 ASTReader &Reader, serialization::ModuleFile &Mod,
 const llvm::BitstreamCursor &Stream) override;
+
+  static bool classof(const ModuleFileExtension *E) {
+return E->getKind() == MFEK_Test;
+  }
+
+  /// Serialize the extension.
+  friend llvm::raw_ostream &
+  operator<<(llvm::raw_ostream &OS, const TestModuleFileExtension &Extension);
 };
 
 } // end namespace clang
Index: clang/lib/Frontend/TestModuleFileExtension.cpp
===
--- clang/lib/Frontend/TestModuleFileExtension.cpp
+++ clang/lib/Frontend/TestModuleFileExtension.cpp
@@ -127,3 +127,10 @@
   return std::unique_ptr(
 new TestModuleFileExtension::Reader(this, Stream));
 }
+
+llvm::raw_ostream &clang::operator<<(llvm::raw_ostream &OS,
+ const TestModuleFileExtension &Extension) {
+  return OS << Extension.BlockName << ":" << Extension.MajorVersion << ":"
+<< Extension.MinorVersion << ":" << Extension.Hashed << ":"
+<< Extension.UserInfo;
+}
Index: clang/lib/Frontend/CompilerInvocation.cpp
===
--- clang/lib/Frontend/CompilerInvocation.cpp
+++ clang/lib/Frontend/CompilerInvocation.cpp
@@ -386,7 +386,7 @@
 
 template 
 static T extractMaskValue(T KeyPath) {
-  return KeyPath & Value;
+  return ((KeyPath & Value) == Value) ? Value : T();
 }
 
 #define PARSE_OPTION_WITH_MARSHALLING(ARGS, DIAGS, SUCCESS, ID, FLAGS, PARAM,  \
@@ -2217,9 +2217,188 @@
   return None;
 }
 
-static bool ParseFrontendArgs(FrontendOptions &Opts, ArgList &Args,
-  DiagnosticsEngine &Diags, bool &IsHeaderFile) {
+/// Maps frontend action to command line option.
+static Optional
+getProgramActionOpt(frontend::ActionKind ProgramAction) {
+  for (const auto &ActionOpt : getFrontendActionTable())
+if (ActionOpt.first == ProgramAction)
+  return ActionOpt.second;
+
+  return None;
+}
+
+static void GenerateFrontendArgs(const FrontendOptions &Opts,
+ SmallVectorImpl &Args,
+ CompilerInvocation::StringAllocator SA,
+ bool IsHeader) {
+  const FrontendOptions &FrontendOpts = Opts;
+#define FRONTEND_OPTION_WITH_MARSHALLING(  \
+PREFIX_TYPE, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM,\
+HELPTEXT, METAVAR, VALUES, SPELLING, SHOULD_PARSE, ALWAYS_EMIT, KEYPATH,   \
+DEFAULT_VALUE, IMPLIED_CHECK, IMPLIED_VALUE, NORMALIZER, DENORMALIZER, \
+MERGER, EXTRACTOR, TABLE_INDEX)\
+  GENERATE_OPTION_WITH_MARSHALLING(\
+  Args, SA, KIND, FLAGS, SPELLING, ALWAYS_EMIT, KEYPATH, DEFAULT_VALUE,\
+  IMPLIED_CHECK, IMPLIED_VALUE, DENORMALIZER, EXTRACTOR, TABLE_INDEX)
+#include "clang/Driver/Options.inc"
+#undef FRONTEND_OPTION_WITH_MARSHALLING
+
+  Optional ProgramActionOpt =
+  getProgramActionOpt(Opts.ProgramAction);
+
+  // Generating a simple flag covers most frontend actions.
+  std::function GenerateProgramAction = [&]() {
+GenerateArg(Args, *ProgramActionOpt, SA);
+  };
+
+  if (!ProgramActionOpt) {
+// PluginAction is the only program action handled separately.
+assert(Opts.ProgramAction == frontend::PluginAction &&
+   "Frontend action without option.");
+GenerateProgramAction = [&]() {
+  GenerateArg(Args, OPT_plugin, Opts.ActionName, SA);
+};
+  }
+
+  // FIXME: Simplify the complex 'AST dump' command line.
+  if (Opts

[PATCH] D96155: [clang][cli] Generate and round-trip Frontend options

2021-02-08 Thread Jan Svoboda via Phabricator via cfe-commits
jansvoboda11 updated this revision to Diff 322121.
jansvoboda11 added a comment.

Fix whitespace


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D96155

Files:
  clang/include/clang/Driver/Options.td
  clang/include/clang/Frontend/CommandLineSourceLoc.h
  clang/include/clang/Serialization/ModuleFileExtension.h
  clang/lib/Frontend/CompilerInvocation.cpp
  clang/lib/Frontend/TestModuleFileExtension.cpp
  clang/lib/Frontend/TestModuleFileExtension.h

Index: clang/lib/Frontend/TestModuleFileExtension.h
===
--- clang/lib/Frontend/TestModuleFileExtension.h
+++ clang/lib/Frontend/TestModuleFileExtension.h
@@ -48,7 +48,8 @@
   unsigned MinorVersion,
   bool Hashed,
   StringRef UserInfo)
-: BlockName(BlockName),
+: ModuleFileExtension(ModuleFileExtensionKind::MFEK_Test),
+  BlockName(BlockName),
   MajorVersion(MajorVersion), MinorVersion(MinorVersion),
   Hashed(Hashed), UserInfo(UserInfo) { }
   ~TestModuleFileExtension() override;
@@ -64,6 +65,14 @@
   createExtensionReader(const ModuleFileExtensionMetadata &Metadata,
 ASTReader &Reader, serialization::ModuleFile &Mod,
 const llvm::BitstreamCursor &Stream) override;
+
+  static bool classof(const ModuleFileExtension *E) {
+return E->getKind() == MFEK_Test;
+  }
+
+  /// Serialize the extension.
+  friend llvm::raw_ostream &
+  operator<<(llvm::raw_ostream &OS, const TestModuleFileExtension &Extension);
 };
 
 } // end namespace clang
Index: clang/lib/Frontend/TestModuleFileExtension.cpp
===
--- clang/lib/Frontend/TestModuleFileExtension.cpp
+++ clang/lib/Frontend/TestModuleFileExtension.cpp
@@ -127,3 +127,10 @@
   return std::unique_ptr(
 new TestModuleFileExtension::Reader(this, Stream));
 }
+
+llvm::raw_ostream &clang::operator<<(llvm::raw_ostream &OS,
+ const TestModuleFileExtension &Extension) {
+  return OS << Extension.BlockName << ":" << Extension.MajorVersion << ":"
+<< Extension.MinorVersion << ":" << Extension.Hashed << ":"
+<< Extension.UserInfo;
+}
Index: clang/lib/Frontend/CompilerInvocation.cpp
===
--- clang/lib/Frontend/CompilerInvocation.cpp
+++ clang/lib/Frontend/CompilerInvocation.cpp
@@ -386,7 +386,7 @@
 
 template 
 static T extractMaskValue(T KeyPath) {
-  return KeyPath & Value;
+  return ((KeyPath & Value) == Value) ? Value : T();
 }
 
 #define PARSE_OPTION_WITH_MARSHALLING(ARGS, DIAGS, SUCCESS, ID, FLAGS, PARAM,  \
@@ -2217,9 +2217,188 @@
   return None;
 }
 
-static bool ParseFrontendArgs(FrontendOptions &Opts, ArgList &Args,
-  DiagnosticsEngine &Diags, bool &IsHeaderFile) {
+/// Maps frontend action to command line option.
+static Optional
+getProgramActionOpt(frontend::ActionKind ProgramAction) {
+  for (const auto &ActionOpt : getFrontendActionTable())
+if (ActionOpt.first == ProgramAction)
+  return ActionOpt.second;
+
+  return None;
+}
+
+static void GenerateFrontendArgs(const FrontendOptions &Opts,
+ SmallVectorImpl &Args,
+ CompilerInvocation::StringAllocator SA,
+ bool IsHeader) {
+  const FrontendOptions &FrontendOpts = Opts;
+#define FRONTEND_OPTION_WITH_MARSHALLING(  \
+PREFIX_TYPE, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM,\
+HELPTEXT, METAVAR, VALUES, SPELLING, SHOULD_PARSE, ALWAYS_EMIT, KEYPATH,   \
+DEFAULT_VALUE, IMPLIED_CHECK, IMPLIED_VALUE, NORMALIZER, DENORMALIZER, \
+MERGER, EXTRACTOR, TABLE_INDEX)\
+  GENERATE_OPTION_WITH_MARSHALLING(\
+  Args, SA, KIND, FLAGS, SPELLING, ALWAYS_EMIT, KEYPATH, DEFAULT_VALUE,\
+  IMPLIED_CHECK, IMPLIED_VALUE, DENORMALIZER, EXTRACTOR, TABLE_INDEX)
+#include "clang/Driver/Options.inc"
+#undef FRONTEND_OPTION_WITH_MARSHALLING
+
+  Optional ProgramActionOpt =
+  getProgramActionOpt(Opts.ProgramAction);
+
+  // Generating a simple flag covers most frontend actions.
+  std::function GenerateProgramAction = [&]() {
+GenerateArg(Args, *ProgramActionOpt, SA);
+  };
+
+  if (!ProgramActionOpt) {
+// PluginAction is the only program action handled separately.
+assert(Opts.ProgramAction == frontend::PluginAction &&
+   "Frontend action without option.");
+GenerateProgramAction = [&]() {
+  GenerateArg(Args, OPT_plugin, Opts.ActionName, SA);
+};
+  }
+
+  // FIXME: Simplify the complex 'AST dump' command line.
+  if (Opts.ProgramAction

[PATCH] D96231: [X86] Always assign reassoc flag for intrinsics *reduce_add/mul_ps/pd.

2021-02-08 Thread Sanjay Patel via Phabricator via cfe-commits
spatel added inline comments.



Comment at: clang/lib/CodeGen/CGBuiltin.cpp:13829
 CGM.getIntrinsic(Intrinsic::vector_reduce_fadd, Ops[1]->getType());
+Builder.getFastMathFlags().setAllowReassoc(true);
 return Builder.CreateCall(F, {Ops[0], Ops[1]});

I haven't looked at this part of the compiler in a long time, so I was 
wondering how we handle FMF scope. It looks like there is already an FMFGuard 
object in place -- CodeGenFunction::CGFPOptionsRAII(). So setting FMF here will 
not affect anything but this CreateCall(). 

Does that match your understanding? Should we have an extra regression test to 
make sure that does not change?

I am imagining something like:

```
double test_mm512_reduce_add_pd(__m512d __W, double ExtraAddOp) {
  double S = _mm512_reduce_add_pd(__W) + ExtraAddOp;
  return S;
}

```

Then we could confirm that `reassoc` is not applied to the `fadd` that follows 
the reduction call.



Comment at: clang/lib/CodeGen/CGBuiltin.cpp:13829
 CGM.getIntrinsic(Intrinsic::vector_reduce_fadd, Ops[1]->getType());
+Builder.getFastMathFlags().setAllowReassoc(true);
 return Builder.CreateCall(F, {Ops[0], Ops[1]});

spatel wrote:
> I haven't looked at this part of the compiler in a long time, so I was 
> wondering how we handle FMF scope. It looks like there is already an FMFGuard 
> object in place -- CodeGenFunction::CGFPOptionsRAII(). So setting FMF here 
> will not affect anything but this CreateCall(). 
> 
> Does that match your understanding? Should we have an extra regression test 
> to make sure that does not change?
> 
> I am imagining something like:
> 
> ```
> double test_mm512_reduce_add_pd(__m512d __W, double ExtraAddOp) {
>   double S = _mm512_reduce_add_pd(__W) + ExtraAddOp;
>   return S;
> }
> 
> ```
> 
> Then we could confirm that `reassoc` is not applied to the `fadd` that 
> follows the reduction call.
Currently (and we could say that this is an LLVM codegen bug), we will not 
generate the optimal/expected reduction with `reassoc` alone.

I think the x86 reduction definition is implicitly assuming that -0.0 is not 
meaningful here, so we should add `nsz` too.

The backend is expecting an explicit `nsz` on this op. Ie, I see this x86 asm 
currently with only `reassoc`:

```
vextractf64x4   $1, %zmm0, %ymm1
vaddpd  %zmm1, %zmm0, %zmm0
vextractf128$1, %ymm0, %xmm1
vaddpd  %xmm1, %xmm0, %xmm0
vpermilpd   $1, %xmm0, %xmm1  
vaddsd  %xmm1, %xmm0, %xmm0 
vxorpd  %xmm1, %xmm1, %xmm1   <--- create 0.0
vaddsd  %xmm1, %xmm0, %xmm0   <--- add it to the reduction result
```

Alternatively (and I'm not sure where it is specified), we could replace the 
default 0.0 argument with -0.0?



Comment at: clang/lib/Headers/avx512fintrin.h:9300
  * outputs. This class of vector operation forms the basis of many scientific
  * computations. In vector-reduction arithmetic, the evaluation off is
  * independent of the order of the input elements of V.

This is an existing text bug, but if we are changing this text, we might as 
well fix it in this patch - I'm not sure what "off" refers to here. Should that 
be "order"?



Comment at: clang/lib/Headers/avx512fintrin.h:9303
 
+ * For floating points type, we always assume the elements are reassociable 
even
+ * if -fast-math is off.

Typo: "floating-point types"



Comment at: clang/lib/Headers/avx512fintrin.h:9304
+ * For floating points type, we always assume the elements are reassociable 
even
+ * if -fast-math is off.
+

Also mention that sign of zero is indeterminate. We might use the LangRef text 
as a model for what to say here:
https://llvm.org/docs/LangRef.html#llvm-vector-reduce-fadd-intrinsic


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D96231

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


[PATCH] D95714: [clang-tidy] fix modernize-use-nullptr false positive with spaceship operator comparisons

2021-02-08 Thread Conrad Poelman via Phabricator via cfe-commits
poelmanc added a comment.

In D95714#2548735 , @njames93 wrote:

> LGTM, Same as last time for the commit?

That would be great, thanks!


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

https://reviews.llvm.org/D95714

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


[PATCH] D96155: [clang][cli] Generate and round-trip Frontend options

2021-02-08 Thread Jan Svoboda via Phabricator via cfe-commits
jansvoboda11 added inline comments.



Comment at: clang/include/clang/Serialization/ModuleFileExtension.h:75
 
+  ModuleFileExtensionKind getKind() const { return Kind; }
+

I'm not sure what the best approach is here.

`ModuleFileExtension` is an abstract class. When parsing command line 
arguments, we may instantiate its (only) subclass `TestModuleFileExtension`.
To generate the argument, we can:
* Add a pure virtual function (e.g. `serialize`) to `ModuleFileExtension`, 
implement it in `TestModuleFileExtension` and use that in the generator. I'm 
not sure if introducing the concept of command line and serialization into 
argument makes sense. For clients subclassing `ModuleFileExtension`, 
serialization might not make sense.
* (The current approach): Add LLVM-style RTTI to the whole hierarchy, and only 
handle `TestModuleFileExtension` in the generator by invoking its (non-virtual) 
`serialize`.

WDYT would be the best approach here?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D96155

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


[PATCH] D96051: [OpenCL] Support enum and typedef args in TableGen BIFs

2021-02-08 Thread Sven van Haastregt via Phabricator via cfe-commits
svenvh updated this revision to Diff 322123.
svenvh added a comment.

Do not assume cast to Enum/TypedefDecl is always successful.


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

https://reviews.llvm.org/D96051

Files:
  clang/include/clang/Basic/DiagnosticSemaKinds.td
  clang/lib/Sema/OpenCLBuiltins.td
  clang/lib/Sema/SemaLookup.cpp
  clang/test/SemaOpenCL/fdeclare-opencl-builtins.cl
  clang/utils/TableGen/ClangOpenCLBuiltinEmitter.cpp

Index: clang/utils/TableGen/ClangOpenCLBuiltinEmitter.cpp
===
--- clang/utils/TableGen/ClangOpenCLBuiltinEmitter.cpp
+++ clang/utils/TableGen/ClangOpenCLBuiltinEmitter.cpp
@@ -48,7 +48,7 @@
 //Find out whether a string matches an existing OpenCL builtin function
 //name and return an index into BuiltinTable and the number of overloads.
 //
-//  * void OCL2Qual(ASTContext&, OpenCLTypeStruct, std::vector&)
+//  * void OCL2Qual(Sema&, OpenCLTypeStruct, std::vector&)
 //Convert an OpenCLTypeStruct type to a list of QualType instances.
 //One OpenCLTypeStruct can represent multiple types, primarily when using
 //GenTypes.
@@ -715,6 +715,9 @@
 void BuiltinNameEmitter::EmitQualTypeFinder() {
   OS << R"(
 
+static QualType getOpenCLEnumType(Sema &S, llvm::StringRef Name);
+static QualType getOpenCLTypedefType(Sema &S, llvm::StringRef Name);
+
 // Convert an OpenCLTypeStruct type to a list of QualTypes.
 // Generic types represent multiple types and vector sizes, thus a vector
 // is returned. The conversion is done in two steps:
@@ -723,8 +726,9 @@
 // or a single scalar type for non generic types.
 // Step 2: Qualifiers and other type properties such as vector size are
 // applied.
-static void OCL2Qual(ASTContext &Context, const OpenCLTypeStruct &Ty,
+static void OCL2Qual(Sema &S, const OpenCLTypeStruct &Ty,
  llvm::SmallVectorImpl &QT) {
+  ASTContext &Context = S.Context;
   // Number of scalar types in the GenType.
   unsigned GenTypeNumTypes;
   // Pointer to the list of vector sizes for the GenType.
Index: clang/test/SemaOpenCL/fdeclare-opencl-builtins.cl
===
--- clang/test/SemaOpenCL/fdeclare-opencl-builtins.cl
+++ clang/test/SemaOpenCL/fdeclare-opencl-builtins.cl
@@ -34,6 +34,9 @@
 typedef uint uint4 __attribute__((ext_vector_type(4)));
 typedef long long2 __attribute__((ext_vector_type(2)));
 
+typedef uint cl_mem_fence_flags;
+#define CLK_GLOBAL_MEM_FENCE 0x02
+
 // Enable extensions that are enabled in opencl-c-base.h.
 #if (defined(__OPENCL_CPP_VERSION__) || __OPENCL_C_VERSION__ >= 200)
 #define cl_khr_subgroup_ballot 1
@@ -52,6 +55,18 @@
   atom_cmpxchg((volatile __global unsigned int *)global_p, ui, ui);
 }
 
+// Only test enum arguments when the base header is included, because we need
+// the enum declarations.
+#if !defined(NO_HEADER) && (defined(__OPENCL_CPP_VERSION__) || __OPENCL_C_VERSION__ >= 200)
+kernel void test_enum_args(volatile global atomic_int *global_p, global int *expected) {
+  int desired;
+  atomic_compare_exchange_strong_explicit(global_p, expected, desired,
+  memory_order_acq_rel,
+  memory_order_relaxed,
+  memory_scope_work_group);
+}
+#endif
+
 kernel void basic_conversion() {
   double d;
   float f;
@@ -180,6 +195,8 @@
 kernel void basic_work_item() {
   uint ui;
 
+  barrier(CLK_GLOBAL_MEM_FENCE);
+
   get_enqueued_local_size(ui);
 #if !defined(__OPENCL_CPP_VERSION__) && __OPENCL_C_VERSION__ < CL_VERSION_2_0
 // expected-error@-2{{implicit declaration of function 'get_enqueued_local_size' is invalid in OpenCL}}
Index: clang/lib/Sema/SemaLookup.cpp
===
--- clang/lib/Sema/SemaLookup.cpp
+++ clang/lib/Sema/SemaLookup.cpp
@@ -677,9 +677,43 @@
 D->dump();
 }
 
+/// Diagnose a missing builtin type.
+static QualType diagOpenCLBuiltinTypeError(Sema &S, llvm::StringRef TypeClass,
+   llvm::StringRef Name) {
+  S.Diag(SourceLocation(), diag::err_opencl_type_not_found)
+  << TypeClass << Name;
+  return S.Context.VoidTy;
+}
+
+/// Lookup an OpenCL enum type.
+static QualType getOpenCLEnumType(Sema &S, llvm::StringRef Name) {
+  LookupResult Result(S, &S.Context.Idents.get(Name), SourceLocation(),
+  Sema::LookupTagName);
+  S.LookupName(Result, S.TUScope);
+  if (Result.empty())
+return diagOpenCLBuiltinTypeError(S, "enum", Name);
+  EnumDecl *Decl = Result.getAsSingle();
+  if (!Decl)
+return diagOpenCLBuiltinTypeError(S, "enum", Name);
+  return S.Context.getEnumType(Decl);
+}
+
+/// Lookup an OpenCL typedef type.
+static QualType getOpenCLTypedefType(Sema &S, llvm::StringRef Name) {
+  LookupResult Result(S, &S.Context.Idents.get(Name), SourceLocation(),
+  Sema::Looku

[PATCH] D96156: [clang][cli] Generate and round-trip PreprocessorOutput options

2021-02-08 Thread Jan Svoboda via Phabricator via cfe-commits
jansvoboda11 updated this revision to Diff 322124.
jansvoboda11 added a comment.

Switch from member functions to static ones


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D96156

Files:
  clang/include/clang/Driver/Options.td
  clang/lib/Frontend/CompilerInvocation.cpp

Index: clang/lib/Frontend/CompilerInvocation.cpp
===
--- clang/lib/Frontend/CompilerInvocation.cpp
+++ clang/lib/Frontend/CompilerInvocation.cpp
@@ -4095,15 +4095,76 @@
"PreprocessorOptions");
 }
 
-static void ParsePreprocessorOutputArgs(PreprocessorOutputOptions &Opts,
-ArgList &Args,
-frontend::ActionKind Action) {
-  if (isStrictlyPreprocessorAction(Action))
-Opts.ShowCPP = !Args.hasArg(OPT_dM);
-  else
-Opts.ShowCPP = 0;
+static void GeneratePreprocessorOutputArgs(
+const PreprocessorOutputOptions &Opts, SmallVectorImpl &Args,
+CompilerInvocation::StringAllocator SA, frontend::ActionKind Action) {
+  const PreprocessorOutputOptions &PreprocessorOutputOpts = Opts;
+
+#define PREPROCESSOR_OUTPUT_OPTION_WITH_MARSHALLING(   \
+PREFIX_TYPE, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM,\
+HELPTEXT, METAVAR, VALUES, SPELLING, SHOULD_PARSE, ALWAYS_EMIT, KEYPATH,   \
+DEFAULT_VALUE, IMPLIED_CHECK, IMPLIED_VALUE, NORMALIZER, DENORMALIZER, \
+MERGER, EXTRACTOR, TABLE_INDEX)\
+  GENERATE_OPTION_WITH_MARSHALLING(\
+  Args, SA, KIND, FLAGS, SPELLING, ALWAYS_EMIT, KEYPATH, DEFAULT_VALUE,\
+  IMPLIED_CHECK, IMPLIED_VALUE, DENORMALIZER, EXTRACTOR, TABLE_INDEX)
+#include "clang/Driver/Options.inc"
+#undef PREPROCESSOR_OUTPUT_OPTION_WITH_MARSHALLING
+
+  bool Generate_dM = isStrictlyPreprocessorAction(Action) && !Opts.ShowCPP;
+  if (Generate_dM)
+GenerateArg(Args, OPT_dM, SA);
+  if (!Generate_dM && Opts.ShowMacros)
+GenerateArg(Args, OPT_dD, SA);
+}
+
+static bool ParsePreprocessorOutputArgsImpl(PreprocessorOutputOptions &Opts,
+ArgList &Args,
+DiagnosticsEngine &Diags,
+frontend::ActionKind Action) {
+  PreprocessorOutputOptions &PreprocessorOutputOpts = Opts;
+  unsigned NumErrorsBefore = Diags.getNumErrors();
+  bool Success = true;
+
+#define PREPROCESSOR_OUTPUT_OPTION_WITH_MARSHALLING(   \
+PREFIX_TYPE, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM,\
+HELPTEXT, METAVAR, VALUES, SPELLING, SHOULD_PARSE, ALWAYS_EMIT, KEYPATH,   \
+DEFAULT_VALUE, IMPLIED_CHECK, IMPLIED_VALUE, NORMALIZER, DENORMALIZER, \
+MERGER, EXTRACTOR, TABLE_INDEX)\
+  PARSE_OPTION_WITH_MARSHALLING(Args, Diags, Success, ID, FLAGS, PARAM,\
+SHOULD_PARSE, KEYPATH, DEFAULT_VALUE,  \
+IMPLIED_CHECK, IMPLIED_VALUE, NORMALIZER,  \
+MERGER, TABLE_INDEX)
+#include "clang/Driver/Options.inc"
+#undef PREPROCESSOR_OUTPUT_OPTION_WITH_MARSHALLING
 
+  Opts.ShowCPP = isStrictlyPreprocessorAction(Action) && !Args.hasArg(OPT_dM);
   Opts.ShowMacros = Args.hasArg(OPT_dM) || Args.hasArg(OPT_dD);
+
+  return Success && Diags.getNumErrors() == NumErrorsBefore;
+}
+
+static bool ParsePreprocessorOutputArgs(CompilerInvocation &Res,
+PreprocessorOutputOptions &Opts,
+ArgList &Args, DiagnosticsEngine &Diags,
+frontend::ActionKind Action) {
+  PreprocessorOutputOptions DummyOpts;
+
+  return RoundTrip(
+  [Action](CompilerInvocation &Res, ArgList &Args,
+   DiagnosticsEngine &Diags) {
+return ParsePreprocessorOutputArgsImpl(Res.getPreprocessorOutputOpts(),
+   Args, Diags, Action);
+  },
+  [Action](CompilerInvocation &Res, SmallVectorImpl &Args,
+   CompilerInvocation::StringAllocator SA) {
+GeneratePreprocessorOutputArgs(Res.getPreprocessorOutputOpts(), Args,
+   SA, Action);
+  },
+  [&DummyOpts](CompilerInvocation &Res) {
+std::swap(DummyOpts, Res.getPreprocessorOutputOpts());
+  },
+  Res, Args, Diags, "PreprocessorOutputOptions");
 }
 
 static void ParseTargetArgs(TargetOptions &Opts, ArgList &Args,
@@ -4224,7 +4285,7 @@
   ParsePreprocessorArgs(Res, Res.getPreprocessorOpts(), Args, Diags,
 Res.getFrontendOpts().ProgramAction,
 Res.getFrontendOpts());
-  ParsePreprocessorOutputArgs(Res.getPreprocessorOutputOp

[PATCH] D93769: [clang] Add support for option -ffp-eval-method and extend #pragma float_control similarly

2021-02-08 Thread Melanie Blower via Phabricator via cfe-commits
mibintc added inline comments.



Comment at: clang/docs/LanguageExtensions.rst:3363
+
+When ``pragma float_control(source, off)`` or
+``pragma float_control(double, off)`` or

I'd like to add Intel ICL compatible syntax, but 'off' doesn't make too much 
sense to me. In the Intel compiler using'off' requires both 
ffp-exception-behavior to be ignore, and FENV_ACCESS to be off.  If that's true 
then setting float_control(source|double|extended, off) is allowable and the 
semantics of float evaluation method set to a 4th level "float eval fast" which 
is loosely described in the commentary as "don't care".  Ideally "float eval 
fast" would deliver the same results, in this context, as Microsoft's fp:fast 
command line option. I could make "off" an illegal setting, or warn that it's 
ignored. @andrew.w.kaylor  do you have any input here?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D93769

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


[PATCH] D96270: [release][docs] Update contributions to LLVM 12 for scalable vectors.

2021-02-08 Thread David Sherwood via Phabricator via cfe-commits
david-arm created this revision.
david-arm added reviewers: sdesmalen, willlovett, c-rhodes.
david-arm requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D96270

Files:
  clang/docs/ReleaseNotes.rst


Index: clang/docs/ReleaseNotes.rst
===
--- clang/docs/ReleaseNotes.rst
+++ clang/docs/ReleaseNotes.rst
@@ -144,6 +144,17 @@
 
 - ...
 
+Modified Pragmas in Clang
+-
+
+- The #pragma "clang loop vectorize_width" has been extended to support an
+  optional 'fixed|scalable' argument, which can be used to indicate that the
+  compiler should use fixed-width or scalable vectorization.  Fixed-width is
+  assumed by default.  Scalable vectorization is an experimental feature for
+  targets that support it, such as Arm targets that support the Scalable Vector
+  Extension (SVE) feature. For more information please refer to the
+  Clang Language Extensions documentation.
+
 Attribute Changes in Clang
 --
 


Index: clang/docs/ReleaseNotes.rst
===
--- clang/docs/ReleaseNotes.rst
+++ clang/docs/ReleaseNotes.rst
@@ -144,6 +144,17 @@
 
 - ...
 
+Modified Pragmas in Clang
+-
+
+- The #pragma "clang loop vectorize_width" has been extended to support an
+  optional 'fixed|scalable' argument, which can be used to indicate that the
+  compiler should use fixed-width or scalable vectorization.  Fixed-width is
+  assumed by default.  Scalable vectorization is an experimental feature for
+  targets that support it, such as Arm targets that support the Scalable Vector
+  Extension (SVE) feature. For more information please refer to the
+  Clang Language Extensions documentation.
+
 Attribute Changes in Clang
 --
 
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D96231: [X86] Always assign reassoc flag for intrinsics *reduce_add/mul_ps/pd.

2021-02-08 Thread Sanjay Patel via Phabricator via cfe-commits
spatel added inline comments.



Comment at: clang/lib/Headers/avx512fintrin.h:9352
 static __inline__ double __DEFAULT_FN_ATTRS512 _mm512_reduce_add_pd(__m512d 
__W) {
   return __builtin_ia32_reduce_fadd_pd512(0.0, __W);
 }

Ah - this is where the +0.0 is specified. This should be -0.0. We could still 
add 'nsz' flag to be safe.



Comment at: clang/lib/Headers/avx512fintrin.h:9362
   __W = _mm512_maskz_mov_pd(__M, __W);
   return __builtin_ia32_reduce_fadd_pd512(0.0, __W);
 }

This also should be changed to -0.0?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D96231

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


[PATCH] D96158: [clang][cli] Generate and round-trip Target options

2021-02-08 Thread Jan Svoboda via Phabricator via cfe-commits
jansvoboda11 updated this revision to Diff 322128.
jansvoboda11 added a comment.

Switch to static functions


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D96158

Files:
  clang/include/clang/Driver/Options.td
  clang/lib/Frontend/CompilerInvocation.cpp

Index: clang/lib/Frontend/CompilerInvocation.cpp
===
--- clang/lib/Frontend/CompilerInvocation.cpp
+++ clang/lib/Frontend/CompilerInvocation.cpp
@@ -4167,8 +4167,44 @@
   Res, Args, Diags, "PreprocessorOutputOptions");
 }
 
-static void ParseTargetArgs(TargetOptions &Opts, ArgList &Args,
-DiagnosticsEngine &Diags) {
+static void GenerateTargetArgs(const TargetOptions &Opts,
+   SmallVectorImpl &Args,
+   CompilerInvocation::StringAllocator SA) {
+  const TargetOptions *TargetOpts = &Opts;
+#define TARGET_OPTION_WITH_MARSHALLING(\
+PREFIX_TYPE, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM,\
+HELPTEXT, METAVAR, VALUES, SPELLING, SHOULD_PARSE, ALWAYS_EMIT, KEYPATH,   \
+DEFAULT_VALUE, IMPLIED_CHECK, IMPLIED_VALUE, NORMALIZER, DENORMALIZER, \
+MERGER, EXTRACTOR, TABLE_INDEX)\
+  GENERATE_OPTION_WITH_MARSHALLING(\
+  Args, SA, KIND, FLAGS, SPELLING, ALWAYS_EMIT, KEYPATH, DEFAULT_VALUE,\
+  IMPLIED_CHECK, IMPLIED_VALUE, DENORMALIZER, EXTRACTOR, TABLE_INDEX)
+#include "clang/Driver/Options.inc"
+#undef TARGET_OPTION_WITH_MARSHALLING
+
+  if (!Opts.SDKVersion.empty())
+GenerateArg(Args, OPT_target_sdk_version_EQ, Opts.SDKVersion.getAsString(),
+SA);
+}
+
+static bool ParseTargetArgsImpl(TargetOptions &Opts, ArgList &Args,
+DiagnosticsEngine &Diags) {
+  TargetOptions *TargetOpts = &Opts;
+  unsigned NumErrorsBefore = Diags.getNumErrors();
+  bool Success = true;
+
+#define TARGET_OPTION_WITH_MARSHALLING(\
+PREFIX_TYPE, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM,\
+HELPTEXT, METAVAR, VALUES, SPELLING, SHOULD_PARSE, ALWAYS_EMIT, KEYPATH,   \
+DEFAULT_VALUE, IMPLIED_CHECK, IMPLIED_VALUE, NORMALIZER, DENORMALIZER, \
+MERGER, EXTRACTOR, TABLE_INDEX)\
+  PARSE_OPTION_WITH_MARSHALLING(Args, Diags, Success, ID, FLAGS, PARAM,\
+SHOULD_PARSE, KEYPATH, DEFAULT_VALUE,  \
+IMPLIED_CHECK, IMPLIED_VALUE, NORMALIZER,  \
+MERGER, TABLE_INDEX)
+#include "clang/Driver/Options.inc"
+#undef TARGET_OPTION_WITH_MARSHALLING
+
   if (Arg *A = Args.getLastArg(options::OPT_target_sdk_version_EQ)) {
 llvm::VersionTuple Version;
 if (Version.tryParse(A->getValue()))
@@ -4177,6 +4213,27 @@
 else
   Opts.SDKVersion = Version;
   }
+
+  return Success && Diags.getNumErrors() == NumErrorsBefore;
+}
+
+static bool ParseTargetArgs(CompilerInvocation &Res, TargetOptions &Opts,
+ArgList &Args, DiagnosticsEngine &Diags) {
+  auto DummyOpts = std::make_shared();
+
+  return RoundTrip(
+  [](CompilerInvocation &Res, ArgList &Args,
+DiagnosticsEngine &Diags) {
+return ParseTargetArgsImpl(Res.getTargetOpts(), Args, Diags);
+  },
+  [](CompilerInvocation &Res, SmallVectorImpl &GeneratedArgs,
+ CompilerInvocation::StringAllocator SA) {
+GenerateTargetArgs(Res.getTargetOpts(), GeneratedArgs, SA);
+  },
+  [&DummyOpts](CompilerInvocation &Res) {
+Res.TargetOpts.swap(DummyOpts);
+  },
+  Res, Args, Diags, "TargetArgs");
 }
 
 bool CompilerInvocation::CreateFromArgs(CompilerInvocation &Res,
@@ -4227,7 +4284,7 @@
LangOpts.IsHeaderFile);
   // FIXME: We shouldn't have to pass the DashX option around here
   InputKind DashX = Res.getFrontendOpts().DashX;
-  ParseTargetArgs(Res.getTargetOpts(), Args, Diags);
+  ParseTargetArgs(Res, Res.getTargetOpts(), Args, Diags);
   llvm::Triple T(Res.getTargetOpts().Triple);
   ParseHeaderSearchArgs(Res, Res.getHeaderSearchOpts(), Args, Diags,
 Res.getFileSystemOpts().WorkingDir);
@@ -,6 +4501,7 @@
 
   GenerateAnalyzerArgs(*AnalyzerOpts, Args, SA);
   GenerateFrontendArgs(FrontendOpts, Args, SA, LangOpts->IsHeaderFile);
+  GenerateTargetArgs(*TargetOpts, Args, SA);
   GenerateHeaderSearchArgs(*HeaderSearchOpts, Args, SA);
   GenerateLangArgs(*LangOpts, Args, SA,  T);
   GenerateCodeGenArgs(CodeGenOpts, Args, SA, T, FrontendOpts.OutputFile,
Index: clang/include/clang/Driver/Options.td
===
--- clang/include/clang/Driver/Options.td
+++ clang/in

[PATCH] D96273: [clang][cli] Generate and round-trip DependencyOutput options

2021-02-08 Thread Jan Svoboda via Phabricator via cfe-commits
jansvoboda11 created this revision.
jansvoboda11 added reviewers: Bigcheese, dexonsmith.
Herald added a subscriber: dang.
jansvoboda11 requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

This patch implements generation of remaining dependency output options and 
tests it by performing parse-generate-parse round trip.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D96273

Files:
  clang/include/clang/Driver/Options.td
  clang/include/clang/Frontend/DependencyOutputOptions.h
  clang/lib/Frontend/CompilerInvocation.cpp
  clang/lib/Frontend/DependencyFile.cpp
  clang/lib/Frontend/HeaderIncludeGen.cpp

Index: clang/lib/Frontend/HeaderIncludeGen.cpp
===
--- clang/lib/Frontend/HeaderIncludeGen.cpp
+++ clang/lib/Frontend/HeaderIncludeGen.cpp
@@ -119,7 +119,7 @@
   // as sanitizer blacklists. It's only important for cl.exe compatibility,
   // the GNU way to generate rules is -M / -MM / -MD / -MMD.
   for (const auto &Header : DepOpts.ExtraDeps)
-PrintHeaderInfo(OutputFile, Header, ShowDepth, 2, MSStyle);
+PrintHeaderInfo(OutputFile, Header.first, ShowDepth, 2, MSStyle);
   PP.addPPCallbacks(std::make_unique(
   &PP, ShowAllHeaders, OutputFile, DepOpts, OwnsOutputFile, ShowDepth,
   MSStyle));
Index: clang/lib/Frontend/DependencyFile.cpp
===
--- clang/lib/Frontend/DependencyFile.cpp
+++ clang/lib/Frontend/DependencyFile.cpp
@@ -182,7 +182,7 @@
   IncludeModuleFiles(Opts.IncludeModuleFiles),
   OutputFormat(Opts.OutputFormat), InputFileIndex(0) {
   for (const auto &ExtraDep : Opts.ExtraDeps) {
-if (addDependency(ExtraDep))
+if (addDependency(ExtraDep.first))
   ++InputFileIndex;
   }
 }
Index: clang/lib/Frontend/CompilerInvocation.cpp
===
--- clang/lib/Frontend/CompilerInvocation.cpp
+++ clang/lib/Frontend/CompilerInvocation.cpp
@@ -1942,19 +1942,76 @@
   Res, Args, Diags, "CodeGenOptions");
 }
 
-static void ParseDependencyOutputArgs(DependencyOutputOptions &Opts,
-  ArgList &Args) {
+static void
+GenerateDependencyOutputArgs(const DependencyOutputOptions &Opts,
+ SmallVectorImpl &Args,
+ CompilerInvocation::StringAllocator SA) {
+  const DependencyOutputOptions &DependencyOutputOpts = Opts;
+#define DEPENDENCY_OUTPUT_OPTION_WITH_MARSHALLING( \
+PREFIX_TYPE, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM,\
+HELPTEXT, METAVAR, VALUES, SPELLING, SHOULD_PARSE, ALWAYS_EMIT, KEYPATH,   \
+DEFAULT_VALUE, IMPLIED_CHECK, IMPLIED_VALUE, NORMALIZER, DENORMALIZER, \
+MERGER, EXTRACTOR, TABLE_INDEX)\
+  GENERATE_OPTION_WITH_MARSHALLING(\
+  Args, SA, KIND, FLAGS, SPELLING, ALWAYS_EMIT, KEYPATH, DEFAULT_VALUE,\
+  IMPLIED_CHECK, IMPLIED_VALUE, DENORMALIZER, EXTRACTOR, TABLE_INDEX)
+#include "clang/Driver/Options.inc"
+#undef DEPENDENCY_OUTPUT_OPTION_WITH_MARSHALLING
+
+  if (Opts.ShowIncludesDest != ShowIncludesDestination::None)
+GenerateArg(Args, OPT_show_includes, SA);
+
+  for (const auto &Dep : Opts.ExtraDeps) {
+switch (Dep.second) {
+case EDK_SanitizeBlacklist:
+  // Sanitizer blacklist arguments are generated from LanguageOptions.
+  continue;
+case EDK_ModuleFile:
+  // Module file arguments are generated from FrontendOptions and
+  // HeaderSearchOptions.
+  continue;
+case EDK_ProfileList:
+  GenerateArg(Args, OPT_fprofile_list_EQ, Dep.first, SA);
+  break;
+case EDK_DepFileEntry:
+  GenerateArg(Args, OPT_fdepfile_entry, Dep.first, SA);
+  break;
+}
+  }
+}
+
+static bool ParseDependencyOutputArgsImpl(
+DependencyOutputOptions &Opts, ArgList &Args,
+DiagnosticsEngine &Diags,
+frontend::ActionKind Action, bool ShowLineMarkers) {
+  unsigned NumErrorsBefore = Diags.getNumErrors();
+  bool Success = true;
+
+  DependencyOutputOptions &DependencyOutputOpts = Opts;
+#define DEPENDENCY_OUTPUT_OPTION_WITH_MARSHALLING( \
+PREFIX_TYPE, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM,\
+HELPTEXT, METAVAR, VALUES, SPELLING, SHOULD_PARSE, ALWAYS_EMIT, KEYPATH,   \
+DEFAULT_VALUE, IMPLIED_CHECK, IMPLIED_VALUE, NORMALIZER, DENORMALIZER, \
+MERGER, EXTRACTOR, TABLE_INDEX)\
+  PARSE_OPTION_WITH_MARSHALLING(Args, Diags, Success, ID, FLAGS, PARAM,\
+SHOULD_PARSE, KEYPATH, DEFAULT_VALUE,  \
+IMPLIED_CHECK, IMPLIED_VALUE, NORMALIZER,  \
+MERGER, TABLE_INDEX)
+#include "clang/Driver/Options.in

[PATCH] D95714: [clang-tidy] fix modernize-use-nullptr false positive with spaceship operator comparisons

2021-02-08 Thread Nathan James via Phabricator via cfe-commits
njames93 added a comment.

I'm unable to cleanly apply this patch, looks like something was a bit off when 
you created the diff.

  ➜  llvm-project git:(main) ✗ arc patch D95714   
   INFO  Base commit is not in local repository; trying to fetch.
  Created and checked out branch arcpatch-D95714.
  Checking patch dev/null => 
clang-tools-extra/test/clang-tidy/checkers/modernize-use-nullptr-cxx20.cpp...
  error: dev/null: does not exist in index
  Checking patch clang-tools-extra/clang-tidy/modernize/UseNullptrCheck.cpp...
  Applied patch clang-tools-extra/clang-tidy/modernize/UseNullptrCheck.cpp 
cleanly.
  
   Patch Failed! 
  Usage Exception: Unable to apply patch!
  ➜  llvm-project git:(arcpatch-D95714) ✗ 

Can you try to reupload the diff, making sure you use full context as well.


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

https://reviews.llvm.org/D95714

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


[PATCH] D86376: [HIP] Simplify kernel launching

2021-02-08 Thread Yaxun Liu via Phabricator via cfe-commits
yaxunl added a comment.

In D86376#2239618 , @tra wrote:

> In D86376#2239391 , @yaxunl wrote:
>
>> For example, in HIP program, there is a kernel `void foo(int*)`. If a C++ 
>> program wants to launch it, the desirable way is
>>
>>   void foo(int*);
>>   hipLaunchKernel(foo, grids, blocks, args, shmem, stream);
>>
>> Due to the prefixed kernel stub name, currently the users have to use
>>
>>   void __device_stub_foo(int*);
>>   hipLaunchKernel(__device_stub_foo, grids, blocks, args, shmem, stream);
>
> Ah. That *is* painful. Perhaps we can have the cake and eat it here and do 
> something like this:
>
> Do generate a variable with the kernel name and use it for hipKernelLaunch(), 
> but also keep the stub and call it for `<<<>>>` launches, only instead of 
> using the stub itself registered as the GPU-side kernel identifier, use the 
> variable.
>
> This way, __device_stub_ will show up in the stack trace (no 
> debuggability regression), but direct calls to hipLaunchKenrel can use 
> unprefixed kernel name.
>
> WDYT?

Yes that should work. Will do.


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

https://reviews.llvm.org/D86376

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


[PATCH] D96274: [clang][cli] Generate and round-trip Diagnostic options

2021-02-08 Thread Jan Svoboda via Phabricator via cfe-commits
jansvoboda11 created this revision.
jansvoboda11 added reviewers: Bigcheese, dexonsmith.
Herald added a subscriber: dang.
jansvoboda11 requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

This patch implements generation of remaining diagnostic options and tests it 
by performing parse-generate-parse round trip.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D96274

Files:
  clang/include/clang/Basic/DiagnosticOptions.h
  clang/include/clang/Driver/Options.td
  clang/include/clang/Frontend/CompilerInvocation.h
  clang/lib/Frontend/CompilerInvocation.cpp

Index: clang/lib/Frontend/CompilerInvocation.cpp
===
--- clang/lib/Frontend/CompilerInvocation.cpp
+++ clang/lib/Frontend/CompilerInvocation.cpp
@@ -722,7 +722,10 @@
 
 static void addDiagnosticArgs(ArgList &Args, OptSpecifier Group,
   OptSpecifier GroupWithValue,
-  std::vector &Diagnostics) {
+  std::vector &Diagnostics,
+  std::vector &DiagnosticsAsWritten) {
+  ArgStringList Rendered;
+
   for (auto *A : Args.filtered(Group)) {
 if (A->getOption().getKind() == Option::FlagClass) {
   // The argument is a pure flag (such as OPT_Wall or OPT_Wdeprecated). Add
@@ -738,7 +741,13 @@
   for (const auto *Arg : A->getValues())
 Diagnostics.emplace_back(Arg);
 }
+
+A->render(Args, Rendered);
   }
+
+  DiagnosticsAsWritten.reserve(Rendered.size());
+  for (const char *Arg : Rendered)
+DiagnosticsAsWritten.emplace_back(Arg);
 }
 
 // Parse the Static Analyzer configuration. If \p Diags is set to nullptr,
@@ -2169,6 +2178,68 @@
   return Success;
 }
 
+void CompilerInvocation::GenerateDiagnosticArgs(
+const DiagnosticOptions &Opts, SmallVectorImpl &Args,
+StringAllocator SA, bool DefaultDiagColor) {
+  const DiagnosticOptions *DiagnosticOpts = &Opts;
+#define DIAG_OPTION_WITH_MARSHALLING(  \
+PREFIX_TYPE, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM,\
+HELPTEXT, METAVAR, VALUES, SPELLING, SHOULD_PARSE, ALWAYS_EMIT, KEYPATH,   \
+DEFAULT_VALUE, IMPLIED_CHECK, IMPLIED_VALUE, NORMALIZER, DENORMALIZER, \
+MERGER, EXTRACTOR, TABLE_INDEX)\
+  GENERATE_OPTION_WITH_MARSHALLING(\
+  Args, SA, KIND, FLAGS, SPELLING, ALWAYS_EMIT, KEYPATH, DEFAULT_VALUE,\
+  IMPLIED_CHECK, IMPLIED_VALUE, DENORMALIZER, EXTRACTOR, TABLE_INDEX)
+#include "clang/Driver/Options.inc"
+#undef DIAG_OPTION_WITH_MARSHALLING
+
+  if (!Opts.DiagnosticSerializationFile.empty())
+GenerateArg(Args, OPT_diagnostic_serialized_file,
+Opts.DiagnosticSerializationFile, SA);
+
+  if (Opts.ShowColors)
+GenerateArg(Args, OPT_fcolor_diagnostics, SA);
+
+  if (Opts.CLFallbackMode)
+GenerateArg(Args, OPT_fdiagnostics_format, "msvc-fallback", SA);
+
+  if (Opts.VerifyDiagnostics &&
+  llvm::is_contained(Opts.VerifyPrefixes, "expected"))
+GenerateArg(Args, OPT_verify, SA);
+
+  for (const auto &Prefix : Opts.VerifyPrefixes)
+if (Prefix != "expected")
+  GenerateArg(Args, OPT_verify_EQ, Prefix, SA);
+
+  DiagnosticLevelMask VIU = Opts.getVerifyIgnoreUnexpected();
+  if (VIU == DiagnosticLevelMask::None) {
+// This is the default, don't generate anything.
+  } else if (VIU == DiagnosticLevelMask::All) {
+GenerateArg(Args, OPT_verify_ignore_unexpected, SA);
+  } else {
+if (static_cast(VIU & DiagnosticLevelMask::Note) != 0)
+  GenerateArg(Args, OPT_verify_ignore_unexpected_EQ, "note", SA);
+if (static_cast(VIU & DiagnosticLevelMask::Remark) != 0)
+  GenerateArg(Args, OPT_verify_ignore_unexpected_EQ, "remark", SA);
+if (static_cast(VIU & DiagnosticLevelMask::Warning) != 0)
+  GenerateArg(Args, OPT_verify_ignore_unexpected_EQ, "warning", SA);
+if (static_cast(VIU & DiagnosticLevelMask::Error) != 0)
+  GenerateArg(Args, OPT_verify_ignore_unexpected_EQ, "error", SA);
+  }
+
+  for (const auto &Warning : Opts.WarningsAsWritten) {
+// This option also maps to UndefPrefixes that generates it automatically.
+if (StringRef(Warning).startswith("-Wundef-prefix="))
+  continue;
+// TODO: Consider ignoring '-Wno-rewrite-macros' that maps to
+// NoRewriteMacros.
+Args.push_back(SA(Warning));
+  }
+
+  for (const auto &Remark : Opts.RemarksAsWritten)
+Args.push_back(SA(Remark));
+}
+
 bool clang::ParseDiagnosticArgs(DiagnosticOptions &Opts, ArgList &Args,
 DiagnosticsEngine *Diags,
 bool DefaultDiagColor) {
@@ -2207,6 +2278,7 @@
 Opts.CLFallbackMode = true;
 
   Opts.VerifyDiagnostics = Args.hasArg(OPT_verify) || Args.hasArg(OPT_verify_EQ);
+  Opts.VerifyPrefixes = Args.getAllArgValues(OPT_verify_EQ);
  

[PATCH] D96270: [release][docs] Update contributions to LLVM 12 for scalable vectors.

2021-02-08 Thread Sander de Smalen via Phabricator via cfe-commits
sdesmalen added inline comments.



Comment at: clang/docs/ReleaseNotes.rst:153
+  compiler should use fixed-width or scalable vectorization.  Fixed-width is
+  assumed by default.  Scalable vectorization is an experimental feature for
+  targets that support it, such as Arm targets that support the Scalable Vector

nit: insert empty line here.



Comment at: clang/docs/ReleaseNotes.rst:153
+  compiler should use fixed-width or scalable vectorization.  Fixed-width is
+  assumed by default.  Scalable vectorization is an experimental feature for
+  targets that support it, such as Arm targets that support the Scalable Vector

sdesmalen wrote:
> nit: insert empty line here.
nit: s/Scalable/Scalable or Vector length agnostic/



Comment at: clang/docs/ReleaseNotes.rst:154-155
+  assumed by default.  Scalable vectorization is an experimental feature for
+  targets that support it, such as Arm targets that support the Scalable Vector
+  Extension (SVE) feature. For more information please refer to the
+  Clang Language Extensions documentation.

nit: s/it, [...] feature./scalable vectors./


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D96270

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


[PATCH] D96278: [clang][cli] Extract FileSystem and Migrator options parsing/generation

2021-02-08 Thread Jan Svoboda via Phabricator via cfe-commits
jansvoboda11 created this revision.
jansvoboda11 added reviewers: Bigcheese, dexonsmith.
Herald added a subscriber: dang.
jansvoboda11 requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

This patch splits out the last two option groups (`Filesystem` and `Migrator`) 
into their own `Parse`/`Generate` functions.

This effectively removes the need for `parseSimpleArgs` and marshalling block 
in `CompilerInvocation::generateCC1CommandLine`.

The two new `Parse`/`Generate` functions are not part of the round-trip, 
because they contain no custom code and the very next patch starts 
round-tripping the whole `CompilerInvocation`.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D96278

Files:
  clang/include/clang/Driver/Options.td
  clang/include/clang/Frontend/CompilerInvocation.h
  clang/lib/Frontend/CompilerInvocation.cpp

Index: clang/lib/Frontend/CompilerInvocation.cpp
===
--- clang/lib/Frontend/CompilerInvocation.cpp
+++ clang/lib/Frontend/CompilerInvocation.cpp
@@ -2159,21 +2159,70 @@
   return Success;
 }
 
-bool CompilerInvocation::parseSimpleArgs(const ArgList &Args,
- DiagnosticsEngine &Diags) {
+static void GenerateFileSystemArgs(const FileSystemOptions &FileSystemOpts,
+   SmallVectorImpl &Args,
+   CompilerInvocation::StringAllocator SA) {
+#define FILE_SYSTEM_OPTION_WITH_MARSHALLING(   \
+PREFIX_TYPE, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM,\
+HELPTEXT, METAVAR, VALUES, SPELLING, SHOULD_PARSE, ALWAYS_EMIT, KEYPATH,   \
+DEFAULT_VALUE, IMPLIED_CHECK, IMPLIED_VALUE, NORMALIZER, DENORMALIZER, \
+MERGER, EXTRACTOR, TABLE_INDEX)\
+  GENERATE_OPTION_WITH_MARSHALLING(\
+  Args, SA, KIND, FLAGS, SPELLING, ALWAYS_EMIT, KEYPATH, DEFAULT_VALUE,\
+  IMPLIED_CHECK, IMPLIED_VALUE, DENORMALIZER, EXTRACTOR, TABLE_INDEX)
+#include "clang/Driver/Options.inc"
+#undef FILE_SYSTEM_OPTION_WITH_MARSHALLING
+}
+
+static bool ParseFileSystemArgs(FileSystemOptions &FileSystemOpts,
+const ArgList &Args, DiagnosticsEngine &Diags) {
   bool Success = true;
 
-#define OPTION_WITH_MARSHALLING(   \
+#define FILE_SYSTEM_OPTION_WITH_MARSHALLING(   \
 PREFIX_TYPE, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM,\
 HELPTEXT, METAVAR, VALUES, SPELLING, SHOULD_PARSE, ALWAYS_EMIT, KEYPATH,   \
 DEFAULT_VALUE, IMPLIED_CHECK, IMPLIED_VALUE, NORMALIZER, DENORMALIZER, \
 MERGER, EXTRACTOR, TABLE_INDEX)\
   PARSE_OPTION_WITH_MARSHALLING(Args, Diags, Success, ID, FLAGS, PARAM,\
-SHOULD_PARSE, this->KEYPATH, DEFAULT_VALUE,\
+SHOULD_PARSE, KEYPATH, DEFAULT_VALUE,  \
 IMPLIED_CHECK, IMPLIED_VALUE, NORMALIZER,  \
 MERGER, TABLE_INDEX)
 #include "clang/Driver/Options.inc"
-#undef OPTION_WITH_MARSHALLING
+#undef FILE_SYSTEM_OPTION_WITH_MARSHALLING
+
+  return Success;
+}
+
+static void GenerateMigratorArgs(const MigratorOptions &MigratorOpts,
+ SmallVectorImpl &Args,
+ CompilerInvocation::StringAllocator SA) {
+#define MIGRATOR_OPTION_WITH_MARSHALLING(  \
+PREFIX_TYPE, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM,\
+HELPTEXT, METAVAR, VALUES, SPELLING, SHOULD_PARSE, ALWAYS_EMIT, KEYPATH,   \
+DEFAULT_VALUE, IMPLIED_CHECK, IMPLIED_VALUE, NORMALIZER, DENORMALIZER, \
+MERGER, EXTRACTOR, TABLE_INDEX)\
+  GENERATE_OPTION_WITH_MARSHALLING(\
+  Args, SA, KIND, FLAGS, SPELLING, ALWAYS_EMIT, KEYPATH, DEFAULT_VALUE,\
+  IMPLIED_CHECK, IMPLIED_VALUE, DENORMALIZER, EXTRACTOR, TABLE_INDEX)
+#include "clang/Driver/Options.inc"
+#undef MIGRATOR_OPTION_WITH_MARSHALLING
+}
+
+static bool ParseMigratorArgs(MigratorOptions &MigratorOpts,
+  const ArgList &Args, DiagnosticsEngine &Diags) {
+  bool Success = true;
+
+#define MIGRATOR_OPTION_WITH_MARSHALLING(  \
+PREFIX_TYPE, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM,\
+HELPTEXT, METAVAR, VALUES, SPELLING, SHOULD_PARSE, ALWAYS_EMIT, KEYPATH,   \
+DEFAULT_VALUE, IMPLIED_CHECK, IMPLIED_VALUE, NORMALIZER, DENORMALIZER, \
+MERGER, EXTRACTOR, TABLE_INDEX)\
+  PARSE_OPTION_WITH_MARSHALLING(Args, Diags, Success

[PATCH] D96279: [OpenCL] Add cl_khr_subgroup_extended_types to TableGen BIFs

2021-02-08 Thread Sven van Haastregt via Phabricator via cfe-commits
svenvh created this revision.
svenvh added a reviewer: Anastasia.
svenvh added a project: clang.
Herald added a subscriber: yaxunl.
svenvh requested review of this revision.
Herald added a subscriber: cfe-commits.

Add the builtin functions brought by the cl_khr_subgroup_extended_types 
extension to `-fdeclare-opencl-builtins`.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D96279

Files:
  clang/lib/Sema/OpenCLBuiltins.td
  clang/test/SemaOpenCL/fdeclare-opencl-builtins.cl


Index: clang/test/SemaOpenCL/fdeclare-opencl-builtins.cl
===
--- clang/test/SemaOpenCL/fdeclare-opencl-builtins.cl
+++ clang/test/SemaOpenCL/fdeclare-opencl-builtins.cl
@@ -39,6 +39,7 @@
 
 // Enable extensions that are enabled in opencl-c-base.h.
 #if (defined(__OPENCL_CPP_VERSION__) || __OPENCL_C_VERSION__ >= 200)
+#define cl_khr_subgroup_extended_types 1
 #define cl_khr_subgroup_ballot 1
 #define cl_khr_subgroup_non_uniform_arithmetic 1
 #define cl_khr_subgroup_clustered_reduce 1
@@ -157,15 +158,18 @@
 #endif
 }
 
-kernel void extended_subgroup(global uint4 *out, global int *scalar) {
+kernel void extended_subgroup(global uint4 *out, global int *scalar, global 
char2 *c2) {
   out[0] = get_sub_group_eq_mask();
   scalar[0] = sub_group_non_uniform_scan_inclusive_or(3);
   scalar[1] = sub_group_clustered_reduce_logical_xor(2, 4);
+  *c2 = sub_group_broadcast(*c2, 2);
 #if __OPENCL_C_VERSION__ < CL_VERSION_2_0 && !defined(__OPENCL_CPP_VERSION__)
-  // expected-error@-4{{implicit declaration of function 
'get_sub_group_eq_mask' is invalid in OpenCL}}
-  // expected-error@-5{{implicit conversion changes signedness}}
-  // expected-error@-5{{implicit declaration of function 
'sub_group_non_uniform_scan_inclusive_or' is invalid in OpenCL}}
-  // expected-error@-5{{implicit declaration of function 
'sub_group_clustered_reduce_logical_xor' is invalid in OpenCL}}
+  // expected-error@-5{{implicit declaration of function 
'get_sub_group_eq_mask' is invalid in OpenCL}}
+  // expected-error@-6{{implicit conversion changes signedness}}
+  // expected-error@-6{{implicit declaration of function 
'sub_group_non_uniform_scan_inclusive_or' is invalid in OpenCL}}
+  // expected-error@-6{{implicit declaration of function 
'sub_group_clustered_reduce_logical_xor' is invalid in OpenCL}}
+  // expected-error@-6{{implicit declaration of function 'sub_group_broadcast' 
is invalid in OpenCL}}
+  // expected-error@-7{{implicit conversion loses integer precision}}
 #endif
 }
 
Index: clang/lib/Sema/OpenCLBuiltins.td
===
--- clang/lib/Sema/OpenCLBuiltins.td
+++ clang/lib/Sema/OpenCLBuiltins.td
@@ -53,6 +53,7 @@
 // FunctionExtension definitions.
 def FuncExtNone  : FunctionExtension<"">;
 def FuncExtKhrSubgroups  : 
FunctionExtension<"cl_khr_subgroups">;
+def FuncExtKhrSubgroupExtendedTypes  : 
FunctionExtension<"cl_khr_subgroup_extended_types">;
 def FuncExtKhrSubgroupNonUniformVote : 
FunctionExtension<"cl_khr_subgroup_non_uniform_vote">;
 def FuncExtKhrSubgroupBallot : 
FunctionExtension<"cl_khr_subgroup_ballot">;
 def FuncExtKhrSubgroupNonUniformArithmetic: 
FunctionExtension<"cl_khr_subgroup_non_uniform_arithmetic">;
@@ -381,6 +382,9 @@
 def FGenTypeN  : GenericType<"FGenTypeN", TLFloat, VecAndScalar>;
 // (u)int, (u)long, and all floats
 def IntLongFloatGenType1   : GenericType<"IntLongFloatGenType1", 
TLIntLongFloats, Vec1>;
+// (u)char and (u)short
+def CharShortGenType1  : GenericType<"CharShortGenType1",
+ TypeList<[Char, UChar, Short, UShort]>, Vec1>;
 
 // GenType definitions for every single base type (e.g. fp32 only).
 // Names are like: GenTypeFloatVecAndScalar.
@@ -1519,7 +1523,19 @@
 // OpenCL Extension v3.0 s38 - Extended Subgroup Functions
 
 // Section 38.4.1 - cl_khr_subgroup_extended_types
-// TODO
+let Extension = FuncExtKhrSubgroupExtendedTypes in {
+  // For sub_group_broadcast, add scalar char, uchar, short, and ushort 
support,
+  def : Builtin<"sub_group_broadcast", [CharShortGenType1, CharShortGenType1, 
UInt], Attr.Convergent>;
+  // gentype may additionally be one of the supported built-in vector data 
types.
+  def : Builtin<"sub_group_broadcast", [AGenTypeNNoScalar, AGenTypeNNoScalar, 
UInt], Attr.Convergent>;
+
+  foreach name = ["sub_group_reduce_", "sub_group_scan_exclusive_",
+  "sub_group_scan_inclusive_"] in {
+foreach op = ["add", "min", "max"] in {
+  def : Builtin;
+}
+  }
+}
 
 // Section 38.5.1 - cl_khr_subgroup_non_uniform_vote
 let Extension = FuncExtKhrSubgroupNonUniformVote in {


Index: clang/test/SemaOpenCL/fdeclare-opencl-builtins.cl
===
--- clang/test/SemaOpenCL/fdeclare-opencl-builtins.cl
+++ clang/test/SemaOpenCL/fdeclare-opencl-builtins.cl
@@ -39,6 +39,7 @@
 
 // Ena

[PATCH] D96280: [WIP][clang][cli] Round-trip the whole CompilerInvocation

2021-02-08 Thread Jan Svoboda via Phabricator via cfe-commits
jansvoboda11 created this revision.
jansvoboda11 added reviewers: Bigcheese, dexonsmith.
jansvoboda11 requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

Finally, this patch moves from round-tripping one `CompilerInvocation` at a 
time to round-tripping the whole invocation.

This includes only the work to make it work. Any cleanup work will be done in a 
follow-up patch.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D96280

Files:
  clang/include/clang/Basic/DiagnosticDriverKinds.td
  clang/include/clang/Frontend/CompilerInvocation.h
  clang/lib/Frontend/CompilerInvocation.cpp

Index: clang/lib/Frontend/CompilerInvocation.cpp
===
--- clang/lib/Frontend/CompilerInvocation.cpp
+++ clang/lib/Frontend/CompilerInvocation.cpp
@@ -423,9 +423,11 @@
 
 static const StringRef GetInputKindName(InputKind IK);
 
-static void FixupInvocation(CompilerInvocation &Invocation,
-DiagnosticsEngine &Diags, const InputArgList &Args,
+static bool FixupInvocation(CompilerInvocation &Invocation,
+DiagnosticsEngine &Diags, const ArgList &Args,
 InputKind IK) {
+  unsigned NumErrorsBefore = Diags.getNumErrors();
+
   LangOptions &LangOpts = *Invocation.getLangOpts();
   CodeGenOptions &CodeGenOpts = Invocation.getCodeGenOpts();
   TargetOptions &TargetOpts = Invocation.getTargetOpts();
@@ -502,6 +504,8 @@
 Diags.Report(diag::err_drv_argument_only_allowed_with)
 << Args.getLastArg(OPT_fprofile_remapping_file_EQ)->getAsString(Args)
 << "-fno-legacy-pass-manager";
+
+  return Diags.getNumErrors() == NumErrorsBefore;
 }
 
 //===--===//
@@ -569,39 +573,39 @@
 Opt.getKind(), 0, Value);
 }
 
-// Parse subset of command line arguments into a member of CompilerInvocation.
-using ParseFn = llvm::function_ref;
+// Parse command line arguments into CompilerInvocation.
+using ParseFn =
+llvm::function_ref,
+DiagnosticsEngine &, const char *)>;
 
-// Generate part of command line arguments from a member of CompilerInvocation.
+// Generate command line arguments from CompilerInvocation.
 using GenerateFn = llvm::function_ref &,
 CompilerInvocation::StringAllocator)>;
 
-// Swap between dummy/real instance of a CompilerInvocation member.
-using SwapOptsFn = llvm::function_ref;
-
 // Performs round-trip of command line arguments if OriginalArgs contain
 // "-round-trip-args". Effectively runs the Parse function for a part of
 // CompilerInvocation on command line arguments that were already once parsed
 // and generated. This is used to check the Generate function produces arguments
 // that are semantically equivalent to those that were used to create
 // CompilerInvocation.
-static bool RoundTrip(ParseFn Parse, GenerateFn Generate, SwapOptsFn SwapOpts,
-  CompilerInvocation &Res, ArgList &OriginalArgs,
-  DiagnosticsEngine &Diags, StringRef OptsName) {
+static bool RoundTrip(ParseFn Parse, GenerateFn Generate,
+  CompilerInvocation &RealInvocation,
+  CompilerInvocation &DummyInvocation,
+  ArrayRef CommandLineArgs,
+  DiagnosticsEngine &Diags, const char *Argv0) {
   bool DoRoundTrip = false;
 #ifdef CLANG_ROUND_TRIP_CC1_ARGS
   DoRoundTrip = true;
 #endif
 
-  // If round-trip was not requested, simply run the parser with the original
-  // options and diagnostics.
+  // If round-trip was not requested, simply run the parser with the real
+  // invocation diagnostics.
   if (!DoRoundTrip)
-return Parse(Res, OriginalArgs, Diags);
+return Parse(RealInvocation, CommandLineArgs, Diags, Argv0);
 
   // Serializes quoted (and potentially escaped) arguments.
-  auto SerializeArgs = [](ArgStringList &Args) {
+  auto SerializeArgs = [](ArrayRef Args) {
 std::string Buffer;
 llvm::raw_string_ostream OS(Buffer);
 for (const char *Arg : Args) {
@@ -612,34 +616,28 @@
 return Buffer;
   };
 
-  OriginalArgs.clearQueriedOpts();
-
   // Setup a dummy DiagnosticsEngine.
   DiagnosticsEngine DummyDiags(new DiagnosticIDs(), new DiagnosticOptions());
   DummyDiags.setClient(new TextDiagnosticBuffer());
 
-  // Run the first parse on the original arguments with dummy options and
+  // Run the first parse on the original arguments with the dummy invocation and
   // diagnostics.
-  SwapOpts(Res);
-  if (!Parse(Res, OriginalArgs, DummyDiags) ||
+  if (!Parse(DummyInvocation, CommandLineArgs, DummyDiags, Argv0) ||
   DummyDiags.getNumWarnings() != 0) {
 // If the first parse did not succeed, it must be user mistake (invalid
 // command line arguments). We won't be able to generate arguments that
-// would reproduce the same result. Let's fail again wi

[PATCH] D96281: Add options to flag individual core increments and to ignore macros to cognitive complexity check.

2021-02-08 Thread Jens Massberg via Phabricator via cfe-commits
massberg created this revision.
massberg added reviewers: lebedev.ri, alexfh.
Herald added a subscriber: nullptr.cpp.
massberg requested review of this revision.
Herald added a project: clang.

Often you are only interested in the overall cognitive complexity of a
function and not every individual increment. Thus the flag
'FlagBasicIncrements' is added. If it is set to 'true', each increment
is flagged. Otherwise, only the complexity of function with complexity
of at least the threshold are flagged.

If a macro is used within the function, the code inside the macro
doesn't make the code less readable. Instead, for a reader a macro is
more like a function that is called. Thus the code inside a macro
shouldn't increase the complexity of the function in which it is called.
Thus the flag 'IgnoreMacros' is added. If set to 'true' code inside
macros isn't considered during analysis.
This isn't perfect, as now the code of a macro isn't considered at all,
even if it has a high cognitive complexity itself. It might be better if
a macro is considered in the analysis like a function and gets its own
cognitive complexity. Implementing such an analysis seems to be very
complex (if possible at all with the given AST), so we give the user the
option to either ignore macros completely or to let the expanded code
count to the calling function's complexity.

By default 'FlagBasisIncrements' is set to 'true' and 'IgnoreMacros' is
set to 'false', which is the original behavior of the check.

Added a new test for different flag combinations.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D96281

Files:
  clang-tools-extra/clang-tidy/readability/FunctionCognitiveComplexityCheck.cpp
  clang-tools-extra/clang-tidy/readability/FunctionCognitiveComplexityCheck.h
  
clang-tools-extra/docs/clang-tidy/checks/readability-function-cognitive-complexity.rst
  
clang-tools-extra/test/clang-tidy/checkers/readability-function-cognitive-complexity-flags.cpp

Index: clang-tools-extra/test/clang-tidy/checkers/readability-function-cognitive-complexity-flags.cpp
===
--- /dev/null
+++ clang-tools-extra/test/clang-tidy/checkers/readability-function-cognitive-complexity-flags.cpp
@@ -0,0 +1,64 @@
+// RUN: %check_clang_tidy %s readability-function-cognitive-complexity %t -- \
+// RUN:   -config='{CheckOptions: \
+// RUN: [{key: readability-function-cognitive-complexity.Threshold, \
+// RUN:   value: 0}, \
+// RUN:  {key: readability-function-cognitive-complexity.FlagBasicIncrements, \
+// RUN:   value: "false"} ]}'
+// RUN: %check_clang_tidy -check-suffix=THRESHOLD5 %s readability-function-cognitive-complexity %t -- \
+// RUN:   -config='{CheckOptions: \
+// RUN: [{key: readability-function-cognitive-complexity.Threshold, \
+// RUN:   value: 5}, \
+// RUN:  {key: readability-function-cognitive-complexity.FlagBasicIncrements, \
+// RUN:   value: "false"} ]}'
+// RUN: %check_clang_tidy -check-suffix=IGNORE-MACROS %s readability-function-cognitive-complexity %t -- \
+// RUN:   -config='{CheckOptions: \
+// RUN: [{key: readability-function-cognitive-complexity.Threshold, \
+// RUN:   value: 0}, \
+// RUN:  {key: readability-function-cognitive-complexity.IgnoreMacros, \
+// RUN:   value: "true"}, \
+// RUN:  {key: readability-function-cognitive-complexity.FlagBasicIncrements, \
+// RUN:   value: "false"} ]}'
+
+void func_of_complexity_4() {
+  // CHECK-NOTES: :[[@LINE-1]]:6: warning: function 'func_of_complexity_4' has cognitive complexity of 4 (threshold 0) [readability-function-cognitive-complexity]
+  // CHECK-NOTES-IGNORE-MACROS: :[[@LINE-2]]:6: warning: function 'func_of_complexity_4' has cognitive complexity of 4 (threshold 0) [readability-function-cognitive-complexity]
+  if (1) {
+if (1) {
+}
+  }
+  if (1) {
+  }
+}
+
+#define MacroOfComplexity10 \
+  if (1) {  \
+if (1) {\
+  if (1) {  \
+if (1) {\
+}   \
+  } \
+}   \
+  }
+
+void function_with_macro() {
+  // CHECK-NOTES: :[[@LINE-1]]:6: warning: function 'function_with_macro' has cognitive complexity of 11 (threshold 0) [readability-function-cognitive-complexity]
+  // CHECK-NOTES-THRESHOLD5: :[[@LINE-2]]:6: warning: function 'function_with_macro' has cognitive complexity of 11 (threshold 5) [readability-function-cognitive-complexity]
+  // CHECK-NOTES-IGNORE-MACROS: :[[@LINE-3]]:6: warning: function 'function_with_macro' has cognitive complexity of 1 (threshold 0) [readability-function-cognitive-complexity]
+
+  MacroOfComplexity10
+
+  if (1) {
+  }
+}
+
+#define uglyfunctionmacro(name) \
+  void name() { \
+if (true) { \
+  try { \

[PATCH] D96175: [clang] Add support for attribute 'swift_async_error'

2021-02-08 Thread Erik Pilkington via Phabricator via cfe-commits
erik.pilkington updated this revision to Diff 322152.
erik.pilkington marked 2 inline comments as done.
erik.pilkington added a comment.

Get rid of a useless `return`.


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

https://reviews.llvm.org/D96175

Files:
  clang/include/clang/Basic/Attr.td
  clang/include/clang/Basic/AttrDocs.td
  clang/include/clang/Basic/DiagnosticSemaKinds.td
  clang/lib/Sema/SemaDeclAttr.cpp
  clang/test/Misc/pragma-attribute-supported-attributes-list.test
  clang/test/SemaObjC/attr-swift-async-error.m

Index: clang/test/SemaObjC/attr-swift-async-error.m
===
--- /dev/null
+++ clang/test/SemaObjC/attr-swift-async-error.m
@@ -0,0 +1,90 @@
+// RUN: %clang_cc1 %s -fblocks -fsyntax-only -verify
+
+#define ASYNC(...) __attribute__((swift_async(__VA_ARGS__)))
+#define ASYNC_ERROR(...) __attribute__((swift_async_error(__VA_ARGS__)))
+
+ASYNC(swift_private, 1)
+ASYNC_ERROR(zero_argument, 1)
+void test_good(void (^handler)(int));
+
+ASYNC(swift_private, 2)
+ASYNC_ERROR(nonzero_argument, 2)
+void test_good2(double, void (^handler)(double, int, double));
+
+enum SomeEnum { SE_a, SE_b };
+
+ASYNC(swift_private, 1)
+ASYNC_ERROR(nonzero_argument, 1)
+void test_good3(void (^handler)(enum SomeEnum, double));
+
+ASYNC_ERROR(zero_argument, 1)
+ASYNC(swift_private, 1)
+void test_rev_order(void (^handler)(int));
+
+@class NSError;
+
+ASYNC(swift_private, 1)
+ASYNC_ERROR(nonnull_error)
+void test_nserror(void (^handler)(NSError *));
+
+typedef struct __attribute__((objc_bridge(NSError))) __CFError * CFErrorRef;
+
+ASYNC(swift_private, 1)
+ASYNC_ERROR(nonnull_error)
+void test_cferror(void (^handler)(CFErrorRef));
+
+ASYNC(swift_private, 1)
+ASYNC_ERROR(nonnull_error) // expected-error {{'swift_async_error' attribute with 'nonnull_error' convention can only be applied to a function with a completion handler with an error parameter}}
+void test_interror(void (^handler)(int));
+
+ASYNC(swift_private, 1)
+ASYNC_ERROR(zero_argument, 1) // expected-error {{'swift_async_error' attribute with 'zero_argument' convention must have an integral-typed parameter in completion handler at index 1, type here is 'double'}}
+void test_not_integral(void (^handler)(double));
+
+ASYNC(swift_private, 1)
+ASYNC_ERROR(none)
+void test_none(void (^)());
+
+ASYNC(none)
+ASYNC_ERROR(none)
+void test_double_none(void (^)());
+
+ASYNC(none)
+ASYNC_ERROR(none, 1) // expected-error {{'swift_async_error' attribute takes one argument}}
+void test_double_none_args();
+
+ASYNC(swift_private, 1)
+ASYNC_ERROR(nonnull_error, 1) // expected-error{{'swift_async_error' attribute takes one argument}}
+void test_args(void (^)(void));
+
+ASYNC(swift_private, 1)
+ASYNC_ERROR(zero_argument, 1, 1) // expected-error{{'swift_async_error' attribute takes no more than 2 arguments}}
+void test_args2(void (^)(int));
+
+ASYNC_ERROR(none) int x; // expected-warning{{'swift_async_error' attribute only applies to functions and Objective-C methods}}
+
+@interface ObjC
+-(void)m1:(void (^)(int))handler
+  ASYNC(swift_private, 1)
+  ASYNC_ERROR(zero_argument, 1);
+
+-(void)m2:(int)first withSecond:(void (^)(int))handler
+  ASYNC(swift_private, 2)
+  ASYNC_ERROR(nonzero_argument, 1);
+
+-(void)m3:(void (^)(void))block
+  ASYNC_ERROR(zero_argument, 1) // expected-error {{'swift_async_error' attribute parameter 2 is out of bounds}}
+  ASYNC(swift_private, 1);
+
+-(void)m4:(void (^)(double, int, float))handler
+  ASYNC(swift_private, 1)
+  ASYNC_ERROR(nonzero_argument, 1); // expected-error{{swift_async_error' attribute with 'nonzero_argument' convention must have an integral-typed parameter in completion handler at index 1, type here is 'double'}}
+
+-(void)m5:(void (^)(NSError *))handler
+  ASYNC(swift_private, 1)
+  ASYNC_ERROR(nonnull_error);
+
+-(void)m6:(void (^)(void *))handler
+  ASYNC(swift_private, 1)
+  ASYNC_ERROR(nonnull_error); // expected-error{{'swift_async_error' attribute with 'nonnull_error' convention can only be applied to a method with a completion handler with an error parameter}}
+@end
Index: clang/test/Misc/pragma-attribute-supported-attributes-list.test
===
--- clang/test/Misc/pragma-attribute-supported-attributes-list.test
+++ clang/test/Misc/pragma-attribute-supported-attributes-list.test
@@ -155,6 +155,7 @@
 // CHECK-NEXT: SetTypestate (SubjectMatchRule_function_is_member)
 // CHECK-NEXT: SpeculativeLoadHardening (SubjectMatchRule_function, SubjectMatchRule_objc_method)
 // CHECK-NEXT: SwiftAsync (SubjectMatchRule_function, SubjectMatchRule_objc_method)
+// CHECK-NEXT: SwiftAsyncError (SubjectMatchRule_function, SubjectMatchRule_objc_method)
 // CHECK-NEXT: SwiftAsyncName (SubjectMatchRule_objc_method, SubjectMatchRule_function)
 // CHECK-NEXT: SwiftBridgedTypedef (SubjectMatchRule_type_alias)
 // CHECK-NEXT: SwiftContext (SubjectMatchRule_variable_is_parameter)
Index: clang/lib/Sema/SemaDeclAtt

[PATCH] D96175: [clang] Add support for attribute 'swift_async_error'

2021-02-08 Thread Erik Pilkington via Phabricator via cfe-commits
erik.pilkington added inline comments.



Comment at: clang/lib/Sema/SemaDeclAttr.cpp:5977
+checkSwiftAsyncErrorBlock(S, D, ErrorAttr, AsyncAttr);
+}
+

aaron.ballman wrote:
> Should there be a diagnostic to combine `swift_error` and `swift_async_error` 
> on the same function? Similarly, should there be a diagnostic when adding 
> `swift_async_error` to a function that isn't (eventually) marked 
> `swift_async`?
My understanding is that `swift_error` and `swift_async_error` don't conflict 
with each other. `swift_error` describes how the non-async swift function 
handles errors, whereas `swift_async_error` describes how the swift async 
function handles errors. Since both swift functions are generated, I think it 
can make sense to have both attributes on one ObjC function. 

I think it can make sense to have `swift_async_error` without `swift_async`, 
since the swift importer infers some functions are async without the 
`swift_async` attribute using heuristics based on parameter names. I guess we 
could mimic those heuristics here to diagnose when `swift_async_error` doesn't 
make sense alone, but ISTM that it makes more sense to do that check in the 
swift importer.


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

https://reviews.llvm.org/D96175

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


[PATCH] D89649: Fix __has_unique_object_representations with no_unique_address

2021-02-08 Thread Gabor Bencze via Phabricator via cfe-commits
gbencze added inline comments.



Comment at: clang/lib/AST/ASTContext.cpp:2582-2584
+int64_t BitfieldSize = Field->getBitWidthValue(Context);
+if (BitfieldSize > FieldSizeInBits)
+  return llvm::None;

steakhal wrote:
> Why do you return `None` here?
These bits were just extracted from `structHasUniqueObjectRepresentations`, the 
underlying logic was not changed here. (originally in line 2615)
I believe this handles the case "If the width of a bit-field is larger than the 
width of the bit-field's type (or, in case of an enumeration type, of its 
underlying type), the extra bits are padding bits" from [class.bit]



Comment at: clang/lib/AST/ASTContext.cpp:2595-2598
+template 
+static llvm::Optional structSubobjectsHaveUniqueObjectRepresentations(
+const RangeT &Subobjects, int64_t CurOffsetInBits, const ASTContext 
&Context,
+const clang::ASTRecordLayout &Layout) {

steakhal wrote:
> Why is this a template?
> Can't you just take the `field_range`?
> 
> By the same token, `structSubobjectsHaveUniqueObjectRepresentations` returns 
> an `optional int`. I'm confused.
This function is also called with (non virtual) base class subobjects, not just 
fields.
A `None` return value indicates that the subobjects do not have unique object 
representations, otherwise the size of the subobjects is returned. This allows 
us to detect for example padding between a base class and the first field. 



Comment at: clang/test/SemaCXX/has_unique_object_reps_no_unique_addr.cpp:42
+} // namespace TailPaddingReuse
+static_assert(__has_unique_object_representations(TailPaddingReuse::B));

steakhal wrote:
> Why is this outside of the namespace declaration?
Tbh I'm not sure. I can move it in the namespace if you think it'd be better 
there. 


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

https://reviews.llvm.org/D89649

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


[PATCH] D96175: [clang] Add support for attribute 'swift_async_error'

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

LGTM modulo some testing requests. Thanks!




Comment at: clang/lib/Sema/SemaDeclAttr.cpp:5977
+checkSwiftAsyncErrorBlock(S, D, ErrorAttr, AsyncAttr);
+}
+

erik.pilkington wrote:
> aaron.ballman wrote:
> > Should there be a diagnostic to combine `swift_error` and 
> > `swift_async_error` on the same function? Similarly, should there be a 
> > diagnostic when adding `swift_async_error` to a function that isn't 
> > (eventually) marked `swift_async`?
> My understanding is that `swift_error` and `swift_async_error` don't conflict 
> with each other. `swift_error` describes how the non-async swift function 
> handles errors, whereas `swift_async_error` describes how the swift async 
> function handles errors. Since both swift functions are generated, I think it 
> can make sense to have both attributes on one ObjC function. 
> 
> I think it can make sense to have `swift_async_error` without `swift_async`, 
> since the swift importer infers some functions are async without the 
> `swift_async` attribute using heuristics based on parameter names. I guess we 
> could mimic those heuristics here to diagnose when `swift_async_error` 
> doesn't make sense alone, but ISTM that it makes more sense to do that check 
> in the swift importer.
Thanks for the information!

> I think it can make sense to have both attributes on one ObjC function.

Fine by me then! Can you add a test case with a comment showing that this is 
explicitly expected to be okay?

> I think it can make sense to have swift_async_error without swift_async

Also fine by me then! I don't think we need to go to great effort here to 
diagnose that (the swift importer can gain extra logic if that's useful). I 
think this is also worth a test case with a comment.

(In both cases, I'm thinking mostly about code archeology projects in the 
future to answer "did they think of" kind of questions.)


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

https://reviews.llvm.org/D96175

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


[PATCH] D96032: [flang][driver] Add support for -fopenmp and -fopenacc

2021-02-08 Thread Andrzej Warzynski via Phabricator via cfe-commits
awarzynski accepted this revision.
awarzynski added a comment.
This revision is now accepted and ready to land.

Thank you for this patch @FarisRehman , it's great to see more tests being 
ported to the new driver!

Although this patches touches many files, it mostly just generalizes the `RUN` 
lines. With this change we can easily switch between `f18` and `flang-new` 
(depending on `FLANG_BUILD_NEW_DRIVER`), which is very helpful!

LGTM (could you moving `options::OPT_fopenmp, options::OPT_fopenacc` do a 
dedicated method before merging?)




Comment at: clang/include/clang/Driver/Options.td:4219-4220
 def ffixed_line_length_VALUE : Joined<["-"], "ffixed-line-length-">, 
Group, Alias;
+def fopenacc : Flag<["-"], "fopenacc">, Group,
+  HelpText<"Parse OpenACC pragmas and generate parallel code.">;
 

Could we follow `gcc` here:
```
gcc --help=fortran | grep openacc
  -fopenacc   Enable OpenACC.
```



Comment at: clang/lib/Driver/ToolChains/Flang.cpp:25-26
   Args.AddAllArgs(CmdArgs, {options::OPT_ffixed_form, options::OPT_ffree_form,
-options::OPT_ffixed_line_length_EQ});
+options::OPT_ffixed_line_length_EQ,
++options::OPT_fopenmp, options::OPT_fopenacc});
 }

`-fopenmp` and `-fopenacc` enable extensions, so they are not dialect options.



Comment at: flang/lib/Frontend/CompilerInvocation.cpp:350
+
+  // Add predefinitions based on language features enabled
+  if (frontendOptions.features_.IsEnabled(

[nit] `language` -> `extensions`


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D96032

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


[PATCH] D96246: Make sure a module file with errors produced via '-fallow-pcm-with-compiler-errors' can be loaded when using implicit modules

2021-02-08 Thread Argyrios Kyrtzidis via Phabricator via cfe-commits
akyrtzi updated this revision to Diff 322166.
akyrtzi added a comment.

clang-format change


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D96246

Files:
  clang/include/clang/Serialization/ASTReader.h
  clang/lib/Frontend/CompilerInstance.cpp
  clang/lib/Serialization/ASTReader.cpp
  clang/test/Modules/load-module-with-errors.m

Index: clang/test/Modules/load-module-with-errors.m
===
--- clang/test/Modules/load-module-with-errors.m
+++ clang/test/Modules/load-module-with-errors.m
@@ -1,3 +1,14 @@
+// Note: the run lines follow their respective tests, since line/column
+// matter in this test.
+
+// pcherror-error@* {{PCH file contains compiler errors}}
+@import error; // notallowerror-error {{could not build module 'error'}}
+// expected-no-diagnostics
+
+void test(Error *x) {
+  [x method];
+}
+
 // RUN: rm -rf %t
 // RUN: mkdir %t
 // RUN: mkdir %t/prebuilt
@@ -48,21 +59,27 @@
 // the verify would fail as it would be the PCH error instead)
 // RUN: %clang_cc1 -fsyntax-only -fmodules \
 // RUN:   -fmodules-cache-path=%t -fimplicit-module-maps -I %S/Inputs/error \
-// RUN:   -x objective-c -verify %s
+// RUN:   -x objective-c -verify=notallowerror %s
 
 // allow-pcm-with-compiler-errors should also allow errors in PCH
 // RUN: %clang_cc1 -fallow-pcm-with-compiler-errors -x objective-c \
 // RUN:   -o %t/check.pch -emit-pch %S/Inputs/error/error.h
 
-// pcherror-error@* {{PCH file contains compiler errors}}
-@import error; // expected-error {{could not build module 'error'}}
-
-void test(Error *x) {
-  [x method];
-}
-
 // CHECK: @interface Error
 // CHECK-NEXT: - (int)method;
 // CHECK-NEXT: - (id)method2;
 // CHECK-NEXT: @end
 // CHECK: void test(Error *x)
+
+// RUN: c-index-test -code-completion-at=%s:9:6 %s -fmodules -fmodules-cache-path=%t \
+// RUN:   -Xclang -fallow-pcm-with-compiler-errors -I %S/Inputs/error | FileCheck -check-prefix=COMPLETE %s
+// COMPLETE: ObjCInstanceMethodDecl:{ResultType int}{TypedText method}
+// COMPLETE: ObjCInstanceMethodDecl:{ResultType id}{TypedText method2}
+
+// RUN: c-index-test -test-load-source local %s -fmodules -fmodules-cache-path=%t \
+// RUN:   -Xclang -fallow-pcm-with-compiler-errors -I %S/Inputs/error | FileCheck -check-prefix=SOURCE %s
+// SOURCE: load-module-with-errors.m:8:6: FunctionDecl=test:8:6 (Definition) Extent=[8:1 - 10:2]
+// SOURCE: load-module-with-errors.m:8:18: ParmDecl=x:8:18 (Definition) Extent=[8:11 - 8:19]
+// SOURCE: load-module-with-errors.m:8:11: ObjCClassRef=Error:3:12 Extent=[8:11 - 8:16]
+// SOURCE: load-module-with-errors.m:8:21: CompoundStmt= Extent=[8:21 - 10:2]
+// SOURCE: load-module-with-errors.m:9:3: ObjCMessageExpr=method:4:8 Extent=[9:3 - 9:13]
Index: clang/lib/Serialization/ASTReader.cpp
===
--- clang/lib/Serialization/ASTReader.cpp
+++ clang/lib/Serialization/ASTReader.cpp
@@ -2751,8 +2751,9 @@
 
   bool hasErrors = Record[6];
   if (hasErrors && !DisableValidation) {
-// Always rebuild modules from the cache on an error
-if (F.Kind == MK_ImplicitModule)
+// If requested by the caller, mark modules on error as out-of-date.
+if (F.Kind == MK_ImplicitModule &&
+(ClientLoadCapabilities & ARR_TreatModuleWithErrorsAsOutOfDate))
   return OutOfDate;
 
 if (!AllowASTWithCompilerErrors) {
Index: clang/lib/Frontend/CompilerInstance.cpp
===
--- clang/lib/Frontend/CompilerInstance.cpp
+++ clang/lib/Frontend/CompilerInstance.cpp
@@ -1144,7 +1144,10 @@
   // module generation thread crashed.
   Instance.clearOutputFiles(/*EraseFiles=*/true);
 
-  return !Instance.getDiagnostics().hasErrorOccurred();
+  // If \p AllowPCMWithCompilerErrors is set return 'success' even if errors
+  // occurred.
+  return !Instance.getDiagnostics().hasErrorOccurred() ||
+ Instance.getFrontendOpts().AllowPCMWithCompilerErrors;
 }
 
 static const FileEntry *getPublicModuleMap(const FileEntry *File,
@@ -1697,7 +1700,8 @@
   // Try to load the module file. If we are not trying to load from the
   // module cache, we don't know how to rebuild modules.
   unsigned ARRFlags = Source == MS_ModuleCache
-  ? ASTReader::ARR_OutOfDate | ASTReader::ARR_Missing
+  ? ASTReader::ARR_OutOfDate | ASTReader::ARR_Missing |
+ASTReader::ARR_TreatModuleWithErrorsAsOutOfDate
   : Source == MS_PrebuiltModulePath
 ? 0
 : ASTReader::ARR_ConfigurationMismatch;
Index: clang/include/clang/Serialization/ASTReader.h
===
--- clang/include/clang/Serialization/ASTReader.h
+++ clang/include/clang/Serialization/ASTRead

  1   2   >