[PATCH] D85474: Add -fbinutils-version= to gate ELF features on the specified binutils version

2021-01-22 Thread Fangrui Song via Phabricator via cfe-commits
MaskRay added a comment.
Herald added a reviewer: jansvoboda11.

Ping:)


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D85474

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


[PATCH] D95206: [clangd][SwapIndex] ensure that the old index is alive while we are using it via the function returned by `SwapIndex::indexedFiles()` call

2021-01-22 Thread Aleksandr Platonov via Phabricator via cfe-commits
ArcsinX updated this revision to Diff 318442.
ArcsinX added a comment.

Fix format


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D95206

Files:
  clang-tools-extra/clangd/index/Index.cpp
  clang-tools-extra/clangd/index/Merge.cpp


Index: clang-tools-extra/clangd/index/Merge.cpp
===
--- clang-tools-extra/clangd/index/Merge.cpp
+++ clang-tools-extra/clangd/index/Merge.cpp
@@ -44,21 +44,23 @@
   SymbolSlab Dyn = std::move(DynB).build();
 
   llvm::DenseSet SeenDynamicSymbols;
-  auto DynamicContainsFile = Dynamic->indexedFiles();
-  More |= Static->fuzzyFind(Req, [&](const Symbol &S) {
-// We expect the definition to see the canonical declaration, so it seems
-// to be enough to check only the definition if it exists.
-if (DynamicContainsFile(S.Definition ? S.Definition.FileURI
- : S.CanonicalDeclaration.FileURI))
-  return;
-auto DynS = Dyn.find(S.ID);
-++StaticCount;
-if (DynS == Dyn.end())
-  return Callback(S);
-++MergedCount;
-SeenDynamicSymbols.insert(S.ID);
-Callback(mergeSymbol(*DynS, S));
-  });
+  {
+auto DynamicContainsFile = Dynamic->indexedFiles();
+More |= Static->fuzzyFind(Req, [&](const Symbol &S) {
+  // We expect the definition to see the canonical declaration, so it seems
+  // to be enough to check only the definition if it exists.
+  if (DynamicContainsFile(S.Definition ? S.Definition.FileURI
+   : S.CanonicalDeclaration.FileURI))
+return;
+  auto DynS = Dyn.find(S.ID);
+  ++StaticCount;
+  if (DynS == Dyn.end())
+return Callback(S);
+  ++MergedCount;
+  SeenDynamicSymbols.insert(S.ID);
+  Callback(mergeSymbol(*DynS, S));
+});
+  }
   SPAN_ATTACH(Tracer, "dynamic", DynamicCount);
   SPAN_ATTACH(Tracer, "static", StaticCount);
   SPAN_ATTACH(Tracer, "merged", MergedCount);
@@ -77,20 +79,22 @@
   Dynamic->lookup(Req, [&](const Symbol &S) { B.insert(S); });
 
   auto RemainingIDs = Req.IDs;
-  auto DynamicContainsFile = Dynamic->indexedFiles();
-  Static->lookup(Req, [&](const Symbol &S) {
-// We expect the definition to see the canonical declaration, so it seems
-// to be enough to check only the definition if it exists.
-if (DynamicContainsFile(S.Definition ? S.Definition.FileURI
- : S.CanonicalDeclaration.FileURI))
-  return;
-const Symbol *Sym = B.find(S.ID);
-RemainingIDs.erase(S.ID);
-if (!Sym)
-  Callback(S);
-else
-  Callback(mergeSymbol(*Sym, S));
-  });
+  {
+auto DynamicContainsFile = Dynamic->indexedFiles();
+Static->lookup(Req, [&](const Symbol &S) {
+  // We expect the definition to see the canonical declaration, so it seems
+  // to be enough to check only the definition if it exists.
+  if (DynamicContainsFile(S.Definition ? S.Definition.FileURI
+   : S.CanonicalDeclaration.FileURI))
+return;
+  const Symbol *Sym = B.find(S.ID);
+  RemainingIDs.erase(S.ID);
+  if (!Sym)
+Callback(S);
+  else
+Callback(mergeSymbol(*Sym, S));
+});
+  }
   for (const auto &ID : RemainingIDs)
 if (const Symbol *Sym = B.find(ID))
   Callback(*Sym);
Index: clang-tools-extra/clangd/index/Index.cpp
===
--- clang-tools-extra/clangd/index/Index.cpp
+++ clang-tools-extra/clangd/index/Index.cpp
@@ -78,7 +78,8 @@
 
 llvm::unique_function
 SwapIndex::indexedFiles() const {
-  return snapshot()->indexedFiles();
+  return [KeepAlive = snapshot(), IndexedFiles = snapshot()->indexedFiles()](
+ llvm::StringRef File) { return IndexedFiles(File); };
 }
 
 size_t SwapIndex::estimateMemoryUsage() const {


Index: clang-tools-extra/clangd/index/Merge.cpp
===
--- clang-tools-extra/clangd/index/Merge.cpp
+++ clang-tools-extra/clangd/index/Merge.cpp
@@ -44,21 +44,23 @@
   SymbolSlab Dyn = std::move(DynB).build();
 
   llvm::DenseSet SeenDynamicSymbols;
-  auto DynamicContainsFile = Dynamic->indexedFiles();
-  More |= Static->fuzzyFind(Req, [&](const Symbol &S) {
-// We expect the definition to see the canonical declaration, so it seems
-// to be enough to check only the definition if it exists.
-if (DynamicContainsFile(S.Definition ? S.Definition.FileURI
- : S.CanonicalDeclaration.FileURI))
-  return;
-auto DynS = Dyn.find(S.ID);
-++StaticCount;
-if (DynS == Dyn.end())
-  return Callback(S);
-++MergedCount;
-SeenDynamicSymbols.insert(S.ID);
-Callback(mergeSymbol(*DynS, S));
-  });
+  {
+auto DynamicContainsFile = Dynamic->indexedFiles();
+More |= Static->fuzzyFind(Req, [

[clang] ff5f42e - [clang][cli] Port visibility LangOptions to marshalling system

2021-01-22 Thread Jan Svoboda via cfe-commits

Author: Jan Svoboda
Date: 2021-01-22T09:32:01+01:00
New Revision: ff5f42e413386b1b3730879abf7b35756891e1c3

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

LOG: [clang][cli] Port visibility LangOptions to marshalling system

This patch introduces Clang-specific MarshallingInfoVisibility TableGen class.

Reviewed By: dexonsmith

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

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 a2800381be0e..3bb545f84132 100644
--- a/clang/include/clang/Driver/Options.td
+++ b/clang/include/clang/Driver/Options.td
@@ -510,6 +510,14 @@ multiclass BoolGOption;
 }
 
+// FIXME: Diagnose if target does not support protected visibility.
+class MarshallingInfoVisibility
+  : MarshallingInfoString,
+Values<"default,hidden,internal,protected">,
+NormalizedValues<["DefaultVisibility", "HiddenVisibility",
+  "HiddenVisibility", "ProtectedVisibility"]>,
+AutoNormalizeEnum {}
+
 // Key paths that are constant during parsing of options with the same key 
path prefix.
 defvar open_cl = LangOpts<"OpenCL">;
 
@@ -2482,15 +2490,26 @@ def fno_var_tracking : Flag<["-"], "fno-var-tracking">, 
Group, Group,
   HelpText<"Generate verbose assembly output">;
 def dA : Flag<["-"], "dA">, Alias;
-defm visibility_from_dllstorageclass : 
OptInFFlag<"visibility-from-dllstorageclass", "Set the visiblity of symbols in 
the generated code from their DLL storage class">;
+defm visibility_from_dllstorageclass : 
BoolFOption<"visibility-from-dllstorageclass",
+  LangOpts<"VisibilityFromDLLStorageClass">, DefaultsToFalse,
+  ChangedBy,
+  ResetBy>;
 def fvisibility_dllexport_EQ : Joined<["-"], "fvisibility-dllexport=">, 
Group, Flags<[CC1Option]>,
-  HelpText<"The visibility for dllexport defintions 
[-fvisibility-from-dllstorageclass]">, Values<"hidden,protected,default">;
+  HelpText<"The visibility for dllexport defintions 
[-fvisibility-from-dllstorageclass]">,
+  MarshallingInfoVisibility, 
"DefaultVisibility">,
+  ShouldParseIf;
 def fvisibility_nodllstorageclass_EQ : Joined<["-"], 
"fvisibility-nodllstorageclass=">, Group, Flags<[CC1Option]>,
-  HelpText<"The visibility for defintiions without an explicit DLL export 
class [-fvisibility-from-dllstorageclass]">, Values<"hidden,protected,default">;
+  HelpText<"The visibility for defintiions without an explicit DLL export 
class [-fvisibility-from-dllstorageclass]">,
+  MarshallingInfoVisibility, 
"HiddenVisibility">,
+  ShouldParseIf;
 def fvisibility_externs_dllimport_EQ : Joined<["-"], 
"fvisibility-externs-dllimport=">, Group, Flags<[CC1Option]>,
-  HelpText<"The visibility for dllimport external declarations 
[-fvisibility-from-dllstorageclass]">, Values<"hidden,protected,default">;
+  HelpText<"The visibility for dllimport external declarations 
[-fvisibility-from-dllstorageclass]">,
+  MarshallingInfoVisibility, 
"DefaultVisibility">,
+  ShouldParseIf;
 def fvisibility_externs_nodllstorageclass_EQ : Joined<["-"], 
"fvisibility-externs-nodllstorageclass=">, Group, Flags<[CC1Option]>,
-  HelpText<"The visibility for external declarations without an explicit DLL 
dllstorageclass [-fvisibility-from-dllstorageclass]">, 
Values<"hidden,protected,default">;
+  HelpText<"The visibility for external declarations without an explicit DLL 
dllstorageclass [-fvisibility-from-dllstorageclass]">,
+  MarshallingInfoVisibility, 
"HiddenVisibility">,
+  ShouldParseIf;
 def fvisibility_EQ : Joined<["-"], "fvisibility=">, Group,
   HelpText<"Set the default symbol visibility for all global declarations">, 
Values<"hidden,default">;
 def fvisibility_inlines_hidden : Flag<["-"], "fvisibility-inlines-hidden">, 
Group,
@@ -5148,14 +5167,12 @@ def stack_protector : Separate<["-"], 
"stack-protector">,
 def stack_protector_buffer_size : Separate<["-"], 
"stack-protector-buffer-size">,
   HelpText<"Lower bound for a buffer to be considered for stack protection">,
   MarshallingInfoStringInt, "8">;
-// FIXME: diagnose if target does not support protected visibility
-// Good place for this is CompilerInvocation::fixupInvocation. Do the same for 
parseVisibility.
 def fvisibility : Separate<["-"], "fvisibility">,
-  HelpText<"Default type and symbol visibility">, 
Values<"default,hidden,internal,protected">,
-  NormalizedValues<["DefaultVisibility", "HiddenVisibility", 
"HiddenVisibility", "ProtectedVisibility"]>,
-  MarshallingInfoString, "DefaultVisibility">, 
AutoNormalizeEnum;
+  HelpText<"Default type and symbol visibility">,
+  MarshallingInfoVisibility, 
"DefaultVisibility">;
 def ftype_visibility : Separate<["-"], "ftype-visibility">,
-  

[PATCH] D95147: [clang][cli] Port visibility LangOptions to marshalling system

2021-01-22 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 rGff5f42e41338: [clang][cli] Port visibility LangOptions to 
marshalling system (authored by jansvoboda11).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D95147

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
@@ -2061,24 +2061,6 @@
   Opts.DoubleSquareBracketAttributes = Opts.CPlusPlus11 || Opts.C2x;
 }
 
-/// Attempt to parse a visibility value out of the given argument.
-static Visibility parseVisibility(Arg *arg, ArgList &args,
-  DiagnosticsEngine &diags) {
-  StringRef value = arg->getValue();
-  if (value == "default") {
-return DefaultVisibility;
-  } else if (value == "hidden" || value == "internal") {
-return HiddenVisibility;
-  } else if (value == "protected") {
-// FIXME: diagnose if target does not support protected visibility
-return ProtectedVisibility;
-  }
-
-  diags.Report(diag::err_drv_invalid_value)
-<< arg->getAsString(args) << value;
-  return DefaultVisibility;
-}
-
 /// Check if input file kind and language standard are compatible.
 static bool IsInputCompatibleWithStandard(InputKind IK,
   const LangStandard &S) {
@@ -2366,45 +2348,6 @@
   Opts.GNUInline = 1;
   }
 
-  // The type-visibility mode defaults to the value-visibility mode.
-  if (Arg *typeVisOpt = Args.getLastArg(OPT_ftype_visibility)) {
-Opts.setTypeVisibilityMode(parseVisibility(typeVisOpt, Args, Diags));
-  } else {
-Opts.setTypeVisibilityMode(Opts.getValueVisibilityMode());
-  }
-
-  if (Args.hasArg(OPT_fvisibility_from_dllstorageclass)) {
-Opts.VisibilityFromDLLStorageClass = 1;
-
-// Translate dllexport defintions to default visibility, by default.
-if (Arg *O = Args.getLastArg(OPT_fvisibility_dllexport_EQ))
-  Opts.setDLLExportVisibility(parseVisibility(O, Args, Diags));
-else
-  Opts.setDLLExportVisibility(DefaultVisibility);
-
-// Translate defintions without an explict DLL storage class to hidden
-// visibility, by default.
-if (Arg *O = Args.getLastArg(OPT_fvisibility_nodllstorageclass_EQ))
-  Opts.setNoDLLStorageClassVisibility(parseVisibility(O, Args, Diags));
-else
-  Opts.setNoDLLStorageClassVisibility(HiddenVisibility);
-
-// Translate dllimport external declarations to default visibility, by
-// default.
-if (Arg *O = Args.getLastArg(OPT_fvisibility_externs_dllimport_EQ))
-  Opts.setExternDeclDLLImportVisibility(parseVisibility(O, Args, Diags));
-else
-  Opts.setExternDeclDLLImportVisibility(DefaultVisibility);
-
-// Translate external declarations without an explicit DLL storage class
-// to hidden visibility, by default.
-if (Arg *O = Args.getLastArg(OPT_fvisibility_externs_nodllstorageclass_EQ))
-  Opts.setExternDeclNoDLLStorageClassVisibility(
-  parseVisibility(O, Args, Diags));
-else
-  Opts.setExternDeclNoDLLStorageClassVisibility(HiddenVisibility);
-  }
-
   if (Args.hasArg(OPT_ftrapv)) {
 Opts.setSignedOverflowBehavior(LangOptions::SOB_Trapping);
 // Set the handler, if one is specified.
Index: clang/include/clang/Driver/Options.td
===
--- clang/include/clang/Driver/Options.td
+++ clang/include/clang/Driver/Options.td
@@ -510,6 +510,14 @@
   Group;
 }
 
+// FIXME: Diagnose if target does not support protected visibility.
+class MarshallingInfoVisibility
+  : MarshallingInfoString,
+Values<"default,hidden,internal,protected">,
+NormalizedValues<["DefaultVisibility", "HiddenVisibility",
+  "HiddenVisibility", "ProtectedVisibility"]>,
+AutoNormalizeEnum {}
+
 // Key paths that are constant during parsing of options with the same key path prefix.
 defvar open_cl = LangOpts<"OpenCL">;
 
@@ -2482,15 +2490,26 @@
 def fverbose_asm : Flag<["-"], "fverbose-asm">, Group,
   HelpText<"Generate verbose assembly output">;
 def dA : Flag<["-"], "dA">, Alias;
-defm visibility_from_dllstorageclass : OptInFFlag<"visibility-from-dllstorageclass", "Set the visiblity of symbols in the generated code from their DLL storage class">;
+defm visibility_from_dllstorageclass : BoolFOption<"visibility-from-dllstorageclass",
+  LangOpts<"VisibilityFromDLLStorageClass">, DefaultsToFalse,
+  ChangedBy,
+  ResetBy>;
 def fvisibility_dllexport_EQ : Joined<["-"], "fvisibility-dllexport=">, Group, Flags<[CC1Option]>,
-  HelpText<"The visibility for dllexport defintions [-fvisibility-from-dllstorageclass]">, Values<"hidden,protected,def

[PATCH] D94472: [WIP][clang][cli] Command line round-trip for HeaderSearch options

2021-01-22 Thread Jan Svoboda via Phabricator via cfe-commits
jansvoboda11 updated this revision to Diff 318452.
jansvoboda11 added a comment.

Create function for argument generation


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D94472

Files:
  clang/include/clang/Frontend/CompilerInvocation.h
  clang/lib/Frontend/CompilerInvocation.cpp
  llvm/include/llvm/Option/ArgList.h
  llvm/lib/Option/ArgList.cpp

Index: llvm/lib/Option/ArgList.cpp
===
--- llvm/lib/Option/ArgList.cpp
+++ llvm/lib/Option/ArgList.cpp
@@ -90,11 +90,22 @@
 }
 
 std::vector ArgList::getAllArgValues(OptSpecifier Id) const {
+  recordQueriedOpts(Id);
   SmallVector Values;
   AddAllArgValues(Values, Id);
   return std::vector(Values.begin(), Values.end());
 }
 
+void ArgList::AddAllArgsExcept(ArgStringList &Output,
+   const DenseSet &ExcludeIds) const {
+  for (const Arg *Arg : *this) {
+if (!ExcludeIds.contains(Arg->getOption().getID())) {
+  Arg->claim();
+  Arg->render(*this, Output);
+}
+  }
+}
+
 void ArgList::AddAllArgsExcept(ArgStringList &Output,
ArrayRef Ids,
ArrayRef ExcludeIds) const {
Index: llvm/include/llvm/Option/ArgList.h
===
--- llvm/include/llvm/Option/ArgList.h
+++ llvm/include/llvm/Option/ArgList.h
@@ -137,6 +137,16 @@
   /// The first and last index of each different OptSpecifier ID.
   DenseMap OptRanges;
 
+  /// The OptSpecifiers that were queried from this argument list.
+  mutable DenseSet QueriedOpts;
+
+  /// Record the queried OptSpecifiers.
+  template 
+  void recordQueriedOpts(OptSpecifiers... Ids) const {
+SmallVector OptsSpecifiers({toOptSpecifier(Ids).getID()...});
+QueriedOpts.insert(OptsSpecifiers.begin(), OptsSpecifiers.end());
+  }
+
   /// Get the range of indexes in which options with the specified IDs might
   /// reside, or (0, 0) if there are no such options.
   OptRange getRange(std::initializer_list Ids) const;
@@ -203,6 +213,7 @@
   template
   iterator_range>
   filtered(OptSpecifiers ...Ids) const {
+recordQueriedOpts(Ids...);
 OptRange Range = getRange({toOptSpecifier(Ids)...});
 auto B = Args.begin() + Range.first;
 auto E = Args.begin() + Range.second;
@@ -214,6 +225,7 @@
   template
   iterator_range>
   filtered_reverse(OptSpecifiers ...Ids) const {
+recordQueriedOpts(Ids...);
 OptRange Range = getRange({toOptSpecifier(Ids)...});
 auto B = Args.rend() - Range.second;
 auto E = Args.rend() - Range.first;
@@ -308,6 +320,10 @@
   A->render(*this, Output);
   }
 
+  /// AddAllArgsExcept - Render all arguments not matching any of the excluded
+  /// ids.
+  void AddAllArgsExcept(ArgStringList &Output,
+const DenseSet &ExcludeIds) const;
   /// AddAllArgsExcept - Render all arguments matching any of the given ids
   /// and not matching any of the excluded ids.
   void AddAllArgsExcept(ArgStringList &Output, ArrayRef Ids,
@@ -342,6 +358,9 @@
   ///
   void ClaimAllArgs() const;
 
+  /// Return the OptSpecifiers queried from this argument list.
+  const DenseSet &getQueriedOpts() const { return QueriedOpts; }
+
   /// @}
   /// @name Arg Synthesis
   /// @{
Index: clang/lib/Frontend/CompilerInvocation.cpp
===
--- clang/lib/Frontend/CompilerInvocation.cpp
+++ clang/lib/Frontend/CompilerInvocation.cpp
@@ -48,10 +48,12 @@
 #include "llvm/ADT/APInt.h"
 #include "llvm/ADT/ArrayRef.h"
 #include "llvm/ADT/CachedHashString.h"
+#include "llvm/ADT/DenseSet.h"
 #include "llvm/ADT/FloatingPointMode.h"
 #include "llvm/ADT/Hashing.h"
 #include "llvm/ADT/None.h"
 #include "llvm/ADT/Optional.h"
+#include "llvm/ADT/SetOperations.h"
 #include "llvm/ADT/SmallString.h"
 #include "llvm/ADT/SmallVector.h"
 #include "llvm/ADT/StringRef.h"
@@ -151,10 +153,10 @@
 /// unnecessary template instantiations and just ignore it with a variadic
 /// argument.
 static void denormalizeSimpleFlag(SmallVectorImpl &Args,
-  const char *Spelling,
-  CompilerInvocation::StringAllocator,
+  Twine Spelling,
+  CompilerInvocation::StringAllocator SA,
   Option::OptionClass, unsigned, /*T*/...) {
-  Args.push_back(Spelling);
+  Args.push_back(SA(Spelling));
 }
 
 template  static constexpr bool is_uint64_t_convertible() {
@@ -201,18 +203,18 @@
 }
 
 static void denormalizeStringImpl(SmallVectorImpl &Args,
-  const char *Spelling,
+  Twine Spelling,
   CompilerInvocation::StringAllocator SA,
   Option::OptionClass OptClass, unsigned,
   

[PATCH] D95206: [clangd][SwapIndex] ensure that the old index is alive while we are using it via the function returned by `SwapIndex::indexedFiles()` call

2021-01-22 Thread Sam McCall via Phabricator via cfe-commits
sammccall accepted this revision.
sammccall added a comment.
This revision is now accepted and ready to land.

Thanks, I'd seen these crashes but not manage to track down yet!

LG with one fix




Comment at: clang-tools-extra/clangd/index/Index.cpp:81
 SwapIndex::indexedFiles() const {
-  return snapshot()->indexedFiles();
+  return [KeepAlive = snapshot(), IndexedFiles = snapshot()->indexedFiles()](
+ llvm::StringRef File) { return IndexedFiles(File); };

Calling snapshot() twice introduces a race - we may keep the wrong one alive.

Evaluate snapshot first into a variable, then call indexedFiles, then move both 
into the lambda?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D95206

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


[PATCH] D93986: [clang-format] Add the possibility to align assignments spanning empty lines or comments

2021-01-22 Thread Marek Kurdej via Phabricator via cfe-commits
curdeius added inline comments.



Comment at: clang/docs/tools/dump_format_style.py:194
+# is used.
+pass
 elif state == State.InEnumMemberComment:

Just a nit, maybe we should have a warning at least?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D93986

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


[PATCH] D94472: [WIP][clang][cli] Command line round-trip for HeaderSearch options

2021-01-22 Thread Jan Svoboda via Phabricator via cfe-commits
jansvoboda11 updated this revision to Diff 318457.
jansvoboda11 added a comment.

Move boilerplate from CreateFromArgs to separate function


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D94472

Files:
  clang/include/clang/Frontend/CompilerInvocation.h
  clang/lib/Frontend/CompilerInvocation.cpp
  llvm/include/llvm/Option/ArgList.h
  llvm/lib/Option/ArgList.cpp

Index: llvm/lib/Option/ArgList.cpp
===
--- llvm/lib/Option/ArgList.cpp
+++ llvm/lib/Option/ArgList.cpp
@@ -90,11 +90,22 @@
 }
 
 std::vector ArgList::getAllArgValues(OptSpecifier Id) const {
+  recordQueriedOpts(Id);
   SmallVector Values;
   AddAllArgValues(Values, Id);
   return std::vector(Values.begin(), Values.end());
 }
 
+void ArgList::AddAllArgsExcept(ArgStringList &Output,
+   const DenseSet &ExcludeIds) const {
+  for (const Arg *Arg : *this) {
+if (!ExcludeIds.contains(Arg->getOption().getID())) {
+  Arg->claim();
+  Arg->render(*this, Output);
+}
+  }
+}
+
 void ArgList::AddAllArgsExcept(ArgStringList &Output,
ArrayRef Ids,
ArrayRef ExcludeIds) const {
Index: llvm/include/llvm/Option/ArgList.h
===
--- llvm/include/llvm/Option/ArgList.h
+++ llvm/include/llvm/Option/ArgList.h
@@ -137,6 +137,16 @@
   /// The first and last index of each different OptSpecifier ID.
   DenseMap OptRanges;
 
+  /// The OptSpecifiers that were queried from this argument list.
+  mutable DenseSet QueriedOpts;
+
+  /// Record the queried OptSpecifiers.
+  template 
+  void recordQueriedOpts(OptSpecifiers... Ids) const {
+SmallVector OptsSpecifiers({toOptSpecifier(Ids).getID()...});
+QueriedOpts.insert(OptsSpecifiers.begin(), OptsSpecifiers.end());
+  }
+
   /// Get the range of indexes in which options with the specified IDs might
   /// reside, or (0, 0) if there are no such options.
   OptRange getRange(std::initializer_list Ids) const;
@@ -203,6 +213,7 @@
   template
   iterator_range>
   filtered(OptSpecifiers ...Ids) const {
+recordQueriedOpts(Ids...);
 OptRange Range = getRange({toOptSpecifier(Ids)...});
 auto B = Args.begin() + Range.first;
 auto E = Args.begin() + Range.second;
@@ -214,6 +225,7 @@
   template
   iterator_range>
   filtered_reverse(OptSpecifiers ...Ids) const {
+recordQueriedOpts(Ids...);
 OptRange Range = getRange({toOptSpecifier(Ids)...});
 auto B = Args.rend() - Range.second;
 auto E = Args.rend() - Range.first;
@@ -308,6 +320,10 @@
   A->render(*this, Output);
   }
 
+  /// AddAllArgsExcept - Render all arguments not matching any of the excluded
+  /// ids.
+  void AddAllArgsExcept(ArgStringList &Output,
+const DenseSet &ExcludeIds) const;
   /// AddAllArgsExcept - Render all arguments matching any of the given ids
   /// and not matching any of the excluded ids.
   void AddAllArgsExcept(ArgStringList &Output, ArrayRef Ids,
@@ -342,6 +358,9 @@
   ///
   void ClaimAllArgs() const;
 
+  /// Return the OptSpecifiers queried from this argument list.
+  const DenseSet &getQueriedOpts() const { return QueriedOpts; }
+
   /// @}
   /// @name Arg Synthesis
   /// @{
Index: clang/lib/Frontend/CompilerInvocation.cpp
===
--- clang/lib/Frontend/CompilerInvocation.cpp
+++ clang/lib/Frontend/CompilerInvocation.cpp
@@ -48,10 +48,12 @@
 #include "llvm/ADT/APInt.h"
 #include "llvm/ADT/ArrayRef.h"
 #include "llvm/ADT/CachedHashString.h"
+#include "llvm/ADT/DenseSet.h"
 #include "llvm/ADT/FloatingPointMode.h"
 #include "llvm/ADT/Hashing.h"
 #include "llvm/ADT/None.h"
 #include "llvm/ADT/Optional.h"
+#include "llvm/ADT/SetOperations.h"
 #include "llvm/ADT/SmallString.h"
 #include "llvm/ADT/SmallVector.h"
 #include "llvm/ADT/StringRef.h"
@@ -151,10 +153,10 @@
 /// unnecessary template instantiations and just ignore it with a variadic
 /// argument.
 static void denormalizeSimpleFlag(SmallVectorImpl &Args,
-  const char *Spelling,
-  CompilerInvocation::StringAllocator,
+  Twine Spelling,
+  CompilerInvocation::StringAllocator SA,
   Option::OptionClass, unsigned, /*T*/...) {
-  Args.push_back(Spelling);
+  Args.push_back(SA(Spelling));
 }
 
 template  static constexpr bool is_uint64_t_convertible() {
@@ -201,18 +203,18 @@
 }
 
 static void denormalizeStringImpl(SmallVectorImpl &Args,
-  const char *Spelling,
+  Twine Spelling,
   CompilerInvocation::StringAllocator SA,
   Option::OptionClass OptClass, unsigned,
 

[PATCH] D92277: [OpenCL] Refactor of targets OpenCL option settings

2021-01-22 Thread Anton Zabaznov via Phabricator via cfe-commits
azabaznov updated this revision to Diff 318458.
azabaznov added a comment.
Herald added a project: clang.

Removed getCoreFeatures() as it's not used in this change.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D92277

Files:
  clang/include/clang/Basic/OpenCLExtensions.def
  clang/include/clang/Basic/OpenCLOptions.h
  clang/include/clang/Basic/TargetInfo.h
  clang/include/clang/Basic/TargetOptions.h
  clang/lib/Basic/CMakeLists.txt
  clang/lib/Basic/OpenCLOptions.cpp
  clang/lib/Basic/Targets.cpp
  clang/lib/Basic/Targets/AMDGPU.h
  clang/lib/Basic/Targets/NVPTX.h
  clang/lib/Basic/Targets/SPIR.h
  clang/lib/Basic/Targets/X86.h
  clang/lib/Frontend/InitPreprocessor.cpp
  clang/lib/Parse/ParsePragma.cpp
  clang/lib/Sema/Sema.cpp
  clang/lib/Serialization/ASTReader.cpp
  clang/lib/Serialization/ASTWriter.cpp
  clang/test/Misc/nvptx.languageOptsOpenCL.cl
  clang/test/Misc/r600.languageOptsOpenCL.cl

Index: clang/test/Misc/r600.languageOptsOpenCL.cl
===
--- clang/test/Misc/r600.languageOptsOpenCL.cl
+++ clang/test/Misc/r600.languageOptsOpenCL.cl
@@ -2,27 +2,21 @@
 // RUN: %clang_cc1 -x cl -cl-std=CL %s -verify -triple r600-unknown-unknown -target-cpu cayman
 // RUN: %clang_cc1 -x cl -cl-std=CL1.1 %s -verify -triple r600-unknown-unknown -target-cpu cayman
 // RUN: %clang_cc1 -x cl -cl-std=CL1.2 %s -verify -triple r600-unknown-unknown -target-cpu cayman
-// RUN: %clang_cc1 -x cl -cl-std=CL2.0 %s -verify -triple r600-unknown-unknown -target-cpu cayman
 // RUN: %clang_cc1 -x cl -cl-std=CL %s -verify -triple r600-unknown-unknown -Wpedantic-core-features -DTEST_CORE_FEATURES -target-cpu cayman
 // RUN: %clang_cc1 -x cl -cl-std=CL1.1 %s -verify -triple r600-unknown-unknown -Wpedantic-core-features -DTEST_CORE_FEATURES -target-cpu cayman
 // RUN: %clang_cc1 -x cl -cl-std=CL1.2 %s -verify -triple r600-unknown-unknown -Wpedantic-core-features -DTEST_CORE_FEATURES -target-cpu cayman
-// RUN: %clang_cc1 -x cl -cl-std=CL2.0 %s -verify -triple r600-unknown-unknown -Wpedantic-core-features -DTEST_CORE_FEATURES -target-cpu cayman
 // RUN: %clang_cc1 -x cl -cl-std=CL %s -verify -triple r600-unknown-unknown -target-cpu cypress
 // RUN: %clang_cc1 -x cl -cl-std=CL1.1 %s -verify -triple r600-unknown-unknown -target-cpu cypress
 // RUN: %clang_cc1 -x cl -cl-std=CL1.2 %s -verify -triple r600-unknown-unknown -target-cpu cypress
-// RUN: %clang_cc1 -x cl -cl-std=CL2.0 %s -verify -triple r600-unknown-unknown -target-cpu cypress
 // RUN: %clang_cc1 -x cl -cl-std=CL %s -verify -triple r600-unknown-unknown -Wpedantic-core-features -DTEST_CORE_FEATURES -target-cpu cypress
 // RUN: %clang_cc1 -x cl -cl-std=CL1.1 %s -verify -triple r600-unknown-unknown -Wpedantic-core-features -DTEST_CORE_FEATURES -target-cpu cypress
 // RUN: %clang_cc1 -x cl -cl-std=CL1.2 %s -verify -triple r600-unknown-unknown -Wpedantic-core-features -DTEST_CORE_FEATURES -target-cpu cypress
-// RUN: %clang_cc1 -x cl -cl-std=CL2.0 %s -verify -triple r600-unknown-unknown -Wpedantic-core-features -DTEST_CORE_FEATURES -target-cpu cypress
 // RUN: %clang_cc1 -x cl -cl-std=CL %s -verify -triple r600-unknown-unknown -target-cpu turks
 // RUN: %clang_cc1 -x cl -cl-std=CL1.1 %s -verify -triple r600-unknown-unknown -target-cpu turks
 // RUN: %clang_cc1 -x cl -cl-std=CL1.2 %s -verify -triple r600-unknown-unknown -target-cpu turks
-// RUN: %clang_cc1 -x cl -cl-std=CL2.0 %s -verify -triple r600-unknown-unknown -target-cpu turks
 // RUN: %clang_cc1 -x cl -cl-std=CL %s -verify -triple r600-unknown-unknown -Wpedantic-core-features -DTEST_CORE_FEATURES -target-cpu turks
 // RUN: %clang_cc1 -x cl -cl-std=CL1.1 %s -verify -triple r600-unknown-unknown -Wpedantic-core-features -DTEST_CORE_FEATURES -target-cpu turks
 // RUN: %clang_cc1 -x cl -cl-std=CL1.2 %s -verify -triple r600-unknown-unknown -Wpedantic-core-features -DTEST_CORE_FEATURES -target-cpu turks
-// RUN: %clang_cc1 -x cl -cl-std=CL2.0 %s -verify -triple r600-unknown-unknown -Wpedantic-core-features -DTEST_CORE_FEATURES -target-cpu turks
 
 // Extensions in all versions
 #ifndef cl_clang_storage_class_specifiers
Index: clang/test/Misc/nvptx.languageOptsOpenCL.cl
===
--- clang/test/Misc/nvptx.languageOptsOpenCL.cl
+++ clang/test/Misc/nvptx.languageOptsOpenCL.cl
@@ -2,19 +2,15 @@
 // RUN: %clang_cc1 -x cl -cl-std=CL %s -verify -triple nvptx-unknown-unknown
 // RUN: %clang_cc1 -x cl -cl-std=CL1.1 %s -verify -triple nvptx-unknown-unknown
 // RUN: %clang_cc1 -x cl -cl-std=CL1.2 %s -verify -triple nvptx-unknown-unknown
-// RUN: %clang_cc1 -x cl -cl-std=CL2.0 %s -verify -triple nvptx-unknown-unknown
 // RUN: %clang_cc1 -x cl -cl-std=CL %s -verify -triple nvptx-unknown-unknown -Wpedantic-core-features -DTEST_CORE_FEATURES
 // RUN: %clang_cc1 -x cl -cl-std=CL1.1 %s -verify -triple nvptx-unknown-unknown -Wpedantic-core-features -

[PATCH] D94472: [WIP][clang][cli] Command line round-trip for HeaderSearch options

2021-01-22 Thread Jan Svoboda via Phabricator via cfe-commits
jansvoboda11 updated this revision to Diff 318459.
jansvoboda11 added a comment.

Fix formatting


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D94472

Files:
  clang/include/clang/Frontend/CompilerInvocation.h
  clang/lib/Frontend/CompilerInvocation.cpp
  llvm/include/llvm/Option/ArgList.h
  llvm/lib/Option/ArgList.cpp

Index: llvm/lib/Option/ArgList.cpp
===
--- llvm/lib/Option/ArgList.cpp
+++ llvm/lib/Option/ArgList.cpp
@@ -90,11 +90,22 @@
 }
 
 std::vector ArgList::getAllArgValues(OptSpecifier Id) const {
+  recordQueriedOpts(Id);
   SmallVector Values;
   AddAllArgValues(Values, Id);
   return std::vector(Values.begin(), Values.end());
 }
 
+void ArgList::AddAllArgsExcept(ArgStringList &Output,
+   const DenseSet &ExcludeIds) const {
+  for (const Arg *Arg : *this) {
+if (!ExcludeIds.contains(Arg->getOption().getID())) {
+  Arg->claim();
+  Arg->render(*this, Output);
+}
+  }
+}
+
 void ArgList::AddAllArgsExcept(ArgStringList &Output,
ArrayRef Ids,
ArrayRef ExcludeIds) const {
Index: llvm/include/llvm/Option/ArgList.h
===
--- llvm/include/llvm/Option/ArgList.h
+++ llvm/include/llvm/Option/ArgList.h
@@ -137,6 +137,16 @@
   /// The first and last index of each different OptSpecifier ID.
   DenseMap OptRanges;
 
+  /// The OptSpecifiers that were queried from this argument list.
+  mutable DenseSet QueriedOpts;
+
+  /// Record the queried OptSpecifiers.
+  template 
+  void recordQueriedOpts(OptSpecifiers... Ids) const {
+SmallVector OptsSpecifiers({toOptSpecifier(Ids).getID()...});
+QueriedOpts.insert(OptsSpecifiers.begin(), OptsSpecifiers.end());
+  }
+
   /// Get the range of indexes in which options with the specified IDs might
   /// reside, or (0, 0) if there are no such options.
   OptRange getRange(std::initializer_list Ids) const;
@@ -203,6 +213,7 @@
   template
   iterator_range>
   filtered(OptSpecifiers ...Ids) const {
+recordQueriedOpts(Ids...);
 OptRange Range = getRange({toOptSpecifier(Ids)...});
 auto B = Args.begin() + Range.first;
 auto E = Args.begin() + Range.second;
@@ -214,6 +225,7 @@
   template
   iterator_range>
   filtered_reverse(OptSpecifiers ...Ids) const {
+recordQueriedOpts(Ids...);
 OptRange Range = getRange({toOptSpecifier(Ids)...});
 auto B = Args.rend() - Range.second;
 auto E = Args.rend() - Range.first;
@@ -308,6 +320,10 @@
   A->render(*this, Output);
   }
 
+  /// AddAllArgsExcept - Render all arguments not matching any of the excluded
+  /// ids.
+  void AddAllArgsExcept(ArgStringList &Output,
+const DenseSet &ExcludeIds) const;
   /// AddAllArgsExcept - Render all arguments matching any of the given ids
   /// and not matching any of the excluded ids.
   void AddAllArgsExcept(ArgStringList &Output, ArrayRef Ids,
@@ -342,6 +358,9 @@
   ///
   void ClaimAllArgs() const;
 
+  /// Return the OptSpecifiers queried from this argument list.
+  const DenseSet &getQueriedOpts() const { return QueriedOpts; }
+
   /// @}
   /// @name Arg Synthesis
   /// @{
Index: clang/lib/Frontend/CompilerInvocation.cpp
===
--- clang/lib/Frontend/CompilerInvocation.cpp
+++ clang/lib/Frontend/CompilerInvocation.cpp
@@ -48,10 +48,12 @@
 #include "llvm/ADT/APInt.h"
 #include "llvm/ADT/ArrayRef.h"
 #include "llvm/ADT/CachedHashString.h"
+#include "llvm/ADT/DenseSet.h"
 #include "llvm/ADT/FloatingPointMode.h"
 #include "llvm/ADT/Hashing.h"
 #include "llvm/ADT/None.h"
 #include "llvm/ADT/Optional.h"
+#include "llvm/ADT/SetOperations.h"
 #include "llvm/ADT/SmallString.h"
 #include "llvm/ADT/SmallVector.h"
 #include "llvm/ADT/StringRef.h"
@@ -151,10 +153,10 @@
 /// unnecessary template instantiations and just ignore it with a variadic
 /// argument.
 static void denormalizeSimpleFlag(SmallVectorImpl &Args,
-  const char *Spelling,
-  CompilerInvocation::StringAllocator,
+  Twine Spelling,
+  CompilerInvocation::StringAllocator SA,
   Option::OptionClass, unsigned, /*T*/...) {
-  Args.push_back(Spelling);
+  Args.push_back(SA(Spelling));
 }
 
 template  static constexpr bool is_uint64_t_convertible() {
@@ -201,18 +203,18 @@
 }
 
 static void denormalizeStringImpl(SmallVectorImpl &Args,
-  const char *Spelling,
+  Twine Spelling,
   CompilerInvocation::StringAllocator SA,
   Option::OptionClass OptClass, unsigned,
   Twine Value) {
   switch 

[PATCH] D92277: [OpenCL] Refactor of targets OpenCL option settings

2021-01-22 Thread Anton Zabaznov via Phabricator via cfe-commits
azabaznov marked an inline comment as done.
azabaznov added inline comments.



Comment at: clang/test/Misc/nvptx.languageOptsOpenCL.cl:18
 // RUN: %clang_cc1 -x cl -cl-std=CL2.0 %s -verify -triple 
nvptx64-unknown-unknown -Wpedantic-core-features -DTEST_CORE_FEATURES
+// XFAIL: *
 

Anastasia wrote:
> We shouldn't disable the test, but only change it to check the conformant 
> behavior i.e. the expected diagnostics for `cl_khr_3d_image_writes` should be 
> guarded by the OpenCL version.
Yeah, sure. This won't a problem in this case as these test contain OpenCL C 
1.2 runs. OpenCL C 3.0 is backward compatible with OpenCL C 1.2 so all 1.2 runs 
should be tested together with 3.0.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D92277

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


[PATCH] D92221: Don't delete default constructor of PathDiagnosticConsumerOptions

2021-01-22 Thread Moritz Sichert via Phabricator via cfe-commits
MoritzS updated this revision to Diff 318463.
MoritzS added a comment.

Rebased onto master, run tests again


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D92221

Files:
  clang/include/clang/Analysis/PathDiagnostic.h


Index: clang/include/clang/Analysis/PathDiagnostic.h
===
--- clang/include/clang/Analysis/PathDiagnostic.h
+++ clang/include/clang/Analysis/PathDiagnostic.h
@@ -95,8 +95,6 @@
   /// Whether the consumer should present the name of the entity that emitted
   /// the diagnostic (eg., a checker) so that the user knew how to disable it.
   bool ShouldDisplayDiagnosticName;
-
-  PathDiagnosticConsumerOptions() = delete;
 };
 
 class PathDiagnosticConsumer {


Index: clang/include/clang/Analysis/PathDiagnostic.h
===
--- clang/include/clang/Analysis/PathDiagnostic.h
+++ clang/include/clang/Analysis/PathDiagnostic.h
@@ -95,8 +95,6 @@
   /// Whether the consumer should present the name of the entity that emitted
   /// the diagnostic (eg., a checker) so that the user knew how to disable it.
   bool ShouldDisplayDiagnosticName;
-
-  PathDiagnosticConsumerOptions() = delete;
 };
 
 class PathDiagnosticConsumer {
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D95131: [CodeComplete] Add ranged for loops code pattern.

2021-01-22 Thread Kadir Cetinkaya via Phabricator via cfe-commits
kadircet accepted this revision.
kadircet added a comment.
This revision is now accepted and ready to land.

thanks, lgtm!


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D95131

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


[PATCH] D95087: [clangd] Inject context provider rather than config into ClangdServer. NFC

2021-01-22 Thread Kadir Cetinkaya via Phabricator via cfe-commits
kadircet accepted this revision.
kadircet added inline comments.
This revision is now accepted and ready to land.



Comment at: clang-tools-extra/clangd/ClangdServer.cpp:277
+ D.getColumnNo(), D.getMessage());
+break;
+  }

nit: maybe finish here with a `return` and unify the duplicated `if 
(ClientDiags) ClientDags->push_back..` after the `switch`.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D95087

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


[PATCH] D92277: [OpenCL] Refactor of targets OpenCL option settings

2021-01-22 Thread Anastasia Stulova via Phabricator via cfe-commits
Anastasia accepted this revision.
Anastasia added a comment.

Cool. Thanks!


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D92277

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


[PATCH] D95206: [clangd][SwapIndex] ensure that the old index is alive while we are using it via the function returned by `SwapIndex::indexedFiles()` call

2021-01-22 Thread Aleksandr Platonov via Phabricator via cfe-commits
ArcsinX updated this revision to Diff 318470.
ArcsinX added a comment.

Call snapshot() only once to avoid possible race.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D95206

Files:
  clang-tools-extra/clangd/index/Index.cpp
  clang-tools-extra/clangd/index/Merge.cpp


Index: clang-tools-extra/clangd/index/Merge.cpp
===
--- clang-tools-extra/clangd/index/Merge.cpp
+++ clang-tools-extra/clangd/index/Merge.cpp
@@ -44,21 +44,23 @@
   SymbolSlab Dyn = std::move(DynB).build();
 
   llvm::DenseSet SeenDynamicSymbols;
-  auto DynamicContainsFile = Dynamic->indexedFiles();
-  More |= Static->fuzzyFind(Req, [&](const Symbol &S) {
-// We expect the definition to see the canonical declaration, so it seems
-// to be enough to check only the definition if it exists.
-if (DynamicContainsFile(S.Definition ? S.Definition.FileURI
- : S.CanonicalDeclaration.FileURI))
-  return;
-auto DynS = Dyn.find(S.ID);
-++StaticCount;
-if (DynS == Dyn.end())
-  return Callback(S);
-++MergedCount;
-SeenDynamicSymbols.insert(S.ID);
-Callback(mergeSymbol(*DynS, S));
-  });
+  {
+auto DynamicContainsFile = Dynamic->indexedFiles();
+More |= Static->fuzzyFind(Req, [&](const Symbol &S) {
+  // We expect the definition to see the canonical declaration, so it seems
+  // to be enough to check only the definition if it exists.
+  if (DynamicContainsFile(S.Definition ? S.Definition.FileURI
+   : S.CanonicalDeclaration.FileURI))
+return;
+  auto DynS = Dyn.find(S.ID);
+  ++StaticCount;
+  if (DynS == Dyn.end())
+return Callback(S);
+  ++MergedCount;
+  SeenDynamicSymbols.insert(S.ID);
+  Callback(mergeSymbol(*DynS, S));
+});
+  }
   SPAN_ATTACH(Tracer, "dynamic", DynamicCount);
   SPAN_ATTACH(Tracer, "static", StaticCount);
   SPAN_ATTACH(Tracer, "merged", MergedCount);
@@ -77,20 +79,22 @@
   Dynamic->lookup(Req, [&](const Symbol &S) { B.insert(S); });
 
   auto RemainingIDs = Req.IDs;
-  auto DynamicContainsFile = Dynamic->indexedFiles();
-  Static->lookup(Req, [&](const Symbol &S) {
-// We expect the definition to see the canonical declaration, so it seems
-// to be enough to check only the definition if it exists.
-if (DynamicContainsFile(S.Definition ? S.Definition.FileURI
- : S.CanonicalDeclaration.FileURI))
-  return;
-const Symbol *Sym = B.find(S.ID);
-RemainingIDs.erase(S.ID);
-if (!Sym)
-  Callback(S);
-else
-  Callback(mergeSymbol(*Sym, S));
-  });
+  {
+auto DynamicContainsFile = Dynamic->indexedFiles();
+Static->lookup(Req, [&](const Symbol &S) {
+  // We expect the definition to see the canonical declaration, so it seems
+  // to be enough to check only the definition if it exists.
+  if (DynamicContainsFile(S.Definition ? S.Definition.FileURI
+   : S.CanonicalDeclaration.FileURI))
+return;
+  const Symbol *Sym = B.find(S.ID);
+  RemainingIDs.erase(S.ID);
+  if (!Sym)
+Callback(S);
+  else
+Callback(mergeSymbol(*Sym, S));
+});
+  }
   for (const auto &ID : RemainingIDs)
 if (const Symbol *Sym = B.find(ID))
   Callback(*Sym);
Index: clang-tools-extra/clangd/index/Index.cpp
===
--- clang-tools-extra/clangd/index/Index.cpp
+++ clang-tools-extra/clangd/index/Index.cpp
@@ -78,7 +78,12 @@
 
 llvm::unique_function
 SwapIndex::indexedFiles() const {
-  return snapshot()->indexedFiles();
+  // The index snapshot should outlive this method return value.
+  auto SnapShot = snapshot();
+  auto IndexedFiles = SnapShot->indexedFiles();
+  return [KeepAlive{std::move(SnapShot)},
+  IndexContainsFile{std::move(IndexedFiles)}](
+ llvm::StringRef File) { return IndexContainsFile(File); };
 }
 
 size_t SwapIndex::estimateMemoryUsage() const {


Index: clang-tools-extra/clangd/index/Merge.cpp
===
--- clang-tools-extra/clangd/index/Merge.cpp
+++ clang-tools-extra/clangd/index/Merge.cpp
@@ -44,21 +44,23 @@
   SymbolSlab Dyn = std::move(DynB).build();
 
   llvm::DenseSet SeenDynamicSymbols;
-  auto DynamicContainsFile = Dynamic->indexedFiles();
-  More |= Static->fuzzyFind(Req, [&](const Symbol &S) {
-// We expect the definition to see the canonical declaration, so it seems
-// to be enough to check only the definition if it exists.
-if (DynamicContainsFile(S.Definition ? S.Definition.FileURI
- : S.CanonicalDeclaration.FileURI))
-  return;
-auto DynS = Dyn.find(S.ID);
-++StaticCount;
-if (DynS == Dyn.end())
-  return Call

[PATCH] D95206: [clangd][SwapIndex] ensure that the old index is alive while we are using it via the function returned by `SwapIndex::indexedFiles()` call

2021-01-22 Thread Aleksandr Platonov via Phabricator via cfe-commits
ArcsinX updated this revision to Diff 318474.
ArcsinX added a comment.

Fix format


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D95206

Files:
  clang-tools-extra/clangd/index/Index.cpp
  clang-tools-extra/clangd/index/Merge.cpp


Index: clang-tools-extra/clangd/index/Merge.cpp
===
--- clang-tools-extra/clangd/index/Merge.cpp
+++ clang-tools-extra/clangd/index/Merge.cpp
@@ -44,21 +44,23 @@
   SymbolSlab Dyn = std::move(DynB).build();
 
   llvm::DenseSet SeenDynamicSymbols;
-  auto DynamicContainsFile = Dynamic->indexedFiles();
-  More |= Static->fuzzyFind(Req, [&](const Symbol &S) {
-// We expect the definition to see the canonical declaration, so it seems
-// to be enough to check only the definition if it exists.
-if (DynamicContainsFile(S.Definition ? S.Definition.FileURI
- : S.CanonicalDeclaration.FileURI))
-  return;
-auto DynS = Dyn.find(S.ID);
-++StaticCount;
-if (DynS == Dyn.end())
-  return Callback(S);
-++MergedCount;
-SeenDynamicSymbols.insert(S.ID);
-Callback(mergeSymbol(*DynS, S));
-  });
+  {
+auto DynamicContainsFile = Dynamic->indexedFiles();
+More |= Static->fuzzyFind(Req, [&](const Symbol &S) {
+  // We expect the definition to see the canonical declaration, so it seems
+  // to be enough to check only the definition if it exists.
+  if (DynamicContainsFile(S.Definition ? S.Definition.FileURI
+   : S.CanonicalDeclaration.FileURI))
+return;
+  auto DynS = Dyn.find(S.ID);
+  ++StaticCount;
+  if (DynS == Dyn.end())
+return Callback(S);
+  ++MergedCount;
+  SeenDynamicSymbols.insert(S.ID);
+  Callback(mergeSymbol(*DynS, S));
+});
+  }
   SPAN_ATTACH(Tracer, "dynamic", DynamicCount);
   SPAN_ATTACH(Tracer, "static", StaticCount);
   SPAN_ATTACH(Tracer, "merged", MergedCount);
@@ -77,20 +79,22 @@
   Dynamic->lookup(Req, [&](const Symbol &S) { B.insert(S); });
 
   auto RemainingIDs = Req.IDs;
-  auto DynamicContainsFile = Dynamic->indexedFiles();
-  Static->lookup(Req, [&](const Symbol &S) {
-// We expect the definition to see the canonical declaration, so it seems
-// to be enough to check only the definition if it exists.
-if (DynamicContainsFile(S.Definition ? S.Definition.FileURI
- : S.CanonicalDeclaration.FileURI))
-  return;
-const Symbol *Sym = B.find(S.ID);
-RemainingIDs.erase(S.ID);
-if (!Sym)
-  Callback(S);
-else
-  Callback(mergeSymbol(*Sym, S));
-  });
+  {
+auto DynamicContainsFile = Dynamic->indexedFiles();
+Static->lookup(Req, [&](const Symbol &S) {
+  // We expect the definition to see the canonical declaration, so it seems
+  // to be enough to check only the definition if it exists.
+  if (DynamicContainsFile(S.Definition ? S.Definition.FileURI
+   : S.CanonicalDeclaration.FileURI))
+return;
+  const Symbol *Sym = B.find(S.ID);
+  RemainingIDs.erase(S.ID);
+  if (!Sym)
+Callback(S);
+  else
+Callback(mergeSymbol(*Sym, S));
+});
+  }
   for (const auto &ID : RemainingIDs)
 if (const Symbol *Sym = B.find(ID))
   Callback(*Sym);
Index: clang-tools-extra/clangd/index/Index.cpp
===
--- clang-tools-extra/clangd/index/Index.cpp
+++ clang-tools-extra/clangd/index/Index.cpp
@@ -78,7 +78,13 @@
 
 llvm::unique_function
 SwapIndex::indexedFiles() const {
-  return snapshot()->indexedFiles();
+  // The index snapshot should outlive this method return value.
+  auto SnapShot = snapshot();
+  auto IndexedFiles = SnapShot->indexedFiles();
+  return [KeepAlive{std::move(SnapShot)},
+  IndexContainsFile{std::move(IndexedFiles)}](llvm::StringRef File) {
+return IndexContainsFile(File);
+  };
 }
 
 size_t SwapIndex::estimateMemoryUsage() const {


Index: clang-tools-extra/clangd/index/Merge.cpp
===
--- clang-tools-extra/clangd/index/Merge.cpp
+++ clang-tools-extra/clangd/index/Merge.cpp
@@ -44,21 +44,23 @@
   SymbolSlab Dyn = std::move(DynB).build();
 
   llvm::DenseSet SeenDynamicSymbols;
-  auto DynamicContainsFile = Dynamic->indexedFiles();
-  More |= Static->fuzzyFind(Req, [&](const Symbol &S) {
-// We expect the definition to see the canonical declaration, so it seems
-// to be enough to check only the definition if it exists.
-if (DynamicContainsFile(S.Definition ? S.Definition.FileURI
- : S.CanonicalDeclaration.FileURI))
-  return;
-auto DynS = Dyn.find(S.ID);
-++StaticCount;
-if (DynS == Dyn.end())
-  return Callback(S);
-++MergedCount;
-SeenDynamicS

[PATCH] D92221: Don't delete default constructor of PathDiagnosticConsumerOptions

2021-01-22 Thread Valeriy Savchenko via Phabricator via cfe-commits
vsavchenko accepted this revision.
vsavchenko added a comment.

Hi @MoritzS thanks for the cleanup!
Maybe while you are on it, you can set default values as pointed by @NoQ?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D92221

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


[PATCH] D94942: [clangd] Add tweak for implementing abstract class

2021-01-22 Thread Kadir Cetinkaya via Phabricator via cfe-commits
kadircet added a comment.

Thanks this looks great, and something i've been longing for some time! But I 
got a couple of questions about the how the interaction is designed (sorry if I 
missed some high level discussions elsewhere, feel free to just point me in 
that direction).

- Why do we just declare methods, rather than defining them too (with dummy 
bodies) ? This would allow users to move function bodies out-of-line if they 
want to easily. Also it would enforce them to fill in the bodies, rather than 
forgetting/skipping some of the methods. (Even more maybe we should take the 
extra step and offer another action to declare the function inline and define 
it out-of-line, but I think that could be done iteratively if we see the need)
- Implementing all (pure) virtuals vs offering a code action for each possible 
method. It is unfortunate that our existing tweak infrastructure doesn't enable 
a single tweak to output multiple code actions, but I believe in this case we 
might achieve a whole lot better UX if we did offer implementing each method 
one by one, while possibly still suggesting implement "all" overrides or "only" 
pures. It is still useful in its current form ofcourse, as the user can 
manually change the declaration into a pure one, or delete it, but it sounds 
cumbersome if they only want to implement a small subset of all possible pure 
methods .
- Acting on non-pure virtuals too, i believe this is also a quite common use 
case that could benefit a lot of users. but this definitely increases the need 
for a code action per override.
- When to trigger? I suppose what you have in the code ATM makes sense (e.g. 
just on `[[class X]] : ... [[{]] [[}]]`) but it would be great to spell it out 
explicitly so that others have a chance to raise concerns. I don't think 
triggering within the body would be useful though, as users are likely to 
navigate within class body for various reasons, and spamming them with lots of 
codeactions at each cursor move is likely to be annoying.
- When to land this :) we are at the edge of a branch cut, and tweaks are a 
feature triggered automatically by editors. so any crashes in there are likely 
to make clangd useless (as they'll persist no matter what). so I believe we 
should either wait for release cut, and land this afterwards and fixing any 
crash reports we get until next release, or include it in current release while 
marking the tweak as hidden so that it will only annoy experimental users.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D94942

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


[PATCH] D94472: [WIP][clang][cli] Command line round-trip for HeaderSearch options

2021-01-22 Thread Jan Svoboda via Phabricator via cfe-commits
jansvoboda11 updated this revision to Diff 318475.
jansvoboda11 added a comment.
Herald added a subscriber: dang.

Add round-tripping arguments


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D94472

Files:
  clang/include/clang/Driver/Options.td
  clang/include/clang/Frontend/CompilerInvocation.h
  clang/lib/Driver/ToolChains/Clang.cpp
  clang/lib/Frontend/CompilerInvocation.cpp
  llvm/include/llvm/Option/ArgList.h
  llvm/lib/Option/ArgList.cpp

Index: llvm/lib/Option/ArgList.cpp
===
--- llvm/lib/Option/ArgList.cpp
+++ llvm/lib/Option/ArgList.cpp
@@ -90,11 +90,22 @@
 }
 
 std::vector ArgList::getAllArgValues(OptSpecifier Id) const {
+  recordQueriedOpts(Id);
   SmallVector Values;
   AddAllArgValues(Values, Id);
   return std::vector(Values.begin(), Values.end());
 }
 
+void ArgList::AddAllArgsExcept(ArgStringList &Output,
+   const DenseSet &ExcludeIds) const {
+  for (const Arg *Arg : *this) {
+if (!ExcludeIds.contains(Arg->getOption().getID())) {
+  Arg->claim();
+  Arg->render(*this, Output);
+}
+  }
+}
+
 void ArgList::AddAllArgsExcept(ArgStringList &Output,
ArrayRef Ids,
ArrayRef ExcludeIds) const {
Index: llvm/include/llvm/Option/ArgList.h
===
--- llvm/include/llvm/Option/ArgList.h
+++ llvm/include/llvm/Option/ArgList.h
@@ -137,6 +137,16 @@
   /// The first and last index of each different OptSpecifier ID.
   DenseMap OptRanges;
 
+  /// The OptSpecifiers that were queried from this argument list.
+  mutable DenseSet QueriedOpts;
+
+  /// Record the queried OptSpecifiers.
+  template 
+  void recordQueriedOpts(OptSpecifiers... Ids) const {
+SmallVector OptsSpecifiers({toOptSpecifier(Ids).getID()...});
+QueriedOpts.insert(OptsSpecifiers.begin(), OptsSpecifiers.end());
+  }
+
   /// Get the range of indexes in which options with the specified IDs might
   /// reside, or (0, 0) if there are no such options.
   OptRange getRange(std::initializer_list Ids) const;
@@ -203,6 +213,7 @@
   template
   iterator_range>
   filtered(OptSpecifiers ...Ids) const {
+recordQueriedOpts(Ids...);
 OptRange Range = getRange({toOptSpecifier(Ids)...});
 auto B = Args.begin() + Range.first;
 auto E = Args.begin() + Range.second;
@@ -214,6 +225,7 @@
   template
   iterator_range>
   filtered_reverse(OptSpecifiers ...Ids) const {
+recordQueriedOpts(Ids...);
 OptRange Range = getRange({toOptSpecifier(Ids)...});
 auto B = Args.rend() - Range.second;
 auto E = Args.rend() - Range.first;
@@ -308,6 +320,10 @@
   A->render(*this, Output);
   }
 
+  /// AddAllArgsExcept - Render all arguments not matching any of the excluded
+  /// ids.
+  void AddAllArgsExcept(ArgStringList &Output,
+const DenseSet &ExcludeIds) const;
   /// AddAllArgsExcept - Render all arguments matching any of the given ids
   /// and not matching any of the excluded ids.
   void AddAllArgsExcept(ArgStringList &Output, ArrayRef Ids,
@@ -342,6 +358,9 @@
   ///
   void ClaimAllArgs() const;
 
+  /// Return the OptSpecifiers queried from this argument list.
+  const DenseSet &getQueriedOpts() const { return QueriedOpts; }
+
   /// @}
   /// @name Arg Synthesis
   /// @{
Index: clang/lib/Frontend/CompilerInvocation.cpp
===
--- clang/lib/Frontend/CompilerInvocation.cpp
+++ clang/lib/Frontend/CompilerInvocation.cpp
@@ -48,10 +48,13 @@
 #include "llvm/ADT/APInt.h"
 #include "llvm/ADT/ArrayRef.h"
 #include "llvm/ADT/CachedHashString.h"
+#include "llvm/ADT/DenseSet.h"
 #include "llvm/ADT/FloatingPointMode.h"
 #include "llvm/ADT/Hashing.h"
 #include "llvm/ADT/None.h"
 #include "llvm/ADT/Optional.h"
+#include "llvm/ADT/STLExtras.h"
+#include "llvm/ADT/SetOperations.h"
 #include "llvm/ADT/SmallString.h"
 #include "llvm/ADT/SmallVector.h"
 #include "llvm/ADT/StringRef.h"
@@ -151,10 +154,10 @@
 /// unnecessary template instantiations and just ignore it with a variadic
 /// argument.
 static void denormalizeSimpleFlag(SmallVectorImpl &Args,
-  const char *Spelling,
-  CompilerInvocation::StringAllocator,
+  Twine Spelling,
+  CompilerInvocation::StringAllocator SA,
   Option::OptionClass, unsigned, /*T*/...) {
-  Args.push_back(Spelling);
+  Args.push_back(SA(Spelling));
 }
 
 template  static constexpr bool is_uint64_t_convertible() {
@@ -201,18 +204,18 @@
 }
 
 static void denormalizeStringImpl(SmallVectorImpl &Args,
-  const char *Spelling,
+  Twine Spelling,
   CompilerInvocat

[clang-tools-extra] 4cca222 - [clangd] Add documentation for building and testing clangd

2021-01-22 Thread Kadir Cetinkaya via cfe-commits

Author: Kadir Cetinkaya
Date: 2021-01-22T11:53:31+01:00
New Revision: 4cca79396c4e4d484ba79e74c5dc45fe63e4

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

LOG: [clangd] Add documentation for building and testing clangd

Adds minimal cmake configuration required to build and test clangd,
while telling target names. Should be helpful for people unfamiliar with the
LLVM repo.

See https://github.com/clangd/clangd/issues/579 for a request.

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

Added: 


Modified: 
clang-tools-extra/clangd/README.md

Removed: 




diff  --git a/clang-tools-extra/clangd/README.md 
b/clang-tools-extra/clangd/README.md
index c9a75895acab..3ef9174c9529 100644
--- a/clang-tools-extra/clangd/README.md
+++ b/clang-tools-extra/clangd/README.md
@@ -17,3 +17,22 @@ through one of these channels:
   channel](https://discord.gg/xS7Z362).
 - user questions and feature requests can be asked in the clangd topic on [LLVM
   Discussion Forums](https://llvm.discourse.group/c/llvm-project/clangd/34)
+
+### Building and testing clangd
+
+For a minimal setup on building clangd:
+- Clone the LLVM repo to `$LLVM_ROOT`.
+- Create a build directory, for example at `$LLVM_ROOT/build`.
+- Inside the build directory run: `cmake $LLVM_ROOT/llvm/
+  -DCMAKE_BUILD_TYPE=Release -DLLVM_ENABLE_PROJECTS="clang;clang-tools-extra"`.
+
+  - We suggest building in `Release` mode as building DEBUG binaries requires
+considerably more resources. You can check
+[Building LLVM with CMake documentation](https://llvm.org/docs/CMake.html)
+for more details about cmake flags.
+  - In addition to that using `Ninja` as a generator rather than default `make`
+is preferred. To do that consider passing `-G Ninja` to cmake invocation.
+  - Finally, you can turn on assertions via `-DLLVM_ENABLE_ASSERTS=On`.
+
+- Afterwards you can build clangd with `cmake --build $LLVM_ROOT/build --target
+  clangd`, similarly run tests by changing target to `check-clangd`.



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


[PATCH] D91186: [clangd] Add documentation for building and testing clangd

2021-01-22 Thread Kadir Cetinkaya via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG4cca7939: [clangd] Add documentation for building and 
testing clangd (authored by kadircet).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D91186

Files:
  clang-tools-extra/clangd/README.md


Index: clang-tools-extra/clangd/README.md
===
--- clang-tools-extra/clangd/README.md
+++ clang-tools-extra/clangd/README.md
@@ -17,3 +17,22 @@
   channel](https://discord.gg/xS7Z362).
 - user questions and feature requests can be asked in the clangd topic on [LLVM
   Discussion Forums](https://llvm.discourse.group/c/llvm-project/clangd/34)
+
+### Building and testing clangd
+
+For a minimal setup on building clangd:
+- Clone the LLVM repo to `$LLVM_ROOT`.
+- Create a build directory, for example at `$LLVM_ROOT/build`.
+- Inside the build directory run: `cmake $LLVM_ROOT/llvm/
+  -DCMAKE_BUILD_TYPE=Release -DLLVM_ENABLE_PROJECTS="clang;clang-tools-extra"`.
+
+  - We suggest building in `Release` mode as building DEBUG binaries requires
+considerably more resources. You can check
+[Building LLVM with CMake documentation](https://llvm.org/docs/CMake.html)
+for more details about cmake flags.
+  - In addition to that using `Ninja` as a generator rather than default `make`
+is preferred. To do that consider passing `-G Ninja` to cmake invocation.
+  - Finally, you can turn on assertions via `-DLLVM_ENABLE_ASSERTS=On`.
+
+- Afterwards you can build clangd with `cmake --build $LLVM_ROOT/build --target
+  clangd`, similarly run tests by changing target to `check-clangd`.


Index: clang-tools-extra/clangd/README.md
===
--- clang-tools-extra/clangd/README.md
+++ clang-tools-extra/clangd/README.md
@@ -17,3 +17,22 @@
   channel](https://discord.gg/xS7Z362).
 - user questions and feature requests can be asked in the clangd topic on [LLVM
   Discussion Forums](https://llvm.discourse.group/c/llvm-project/clangd/34)
+
+### Building and testing clangd
+
+For a minimal setup on building clangd:
+- Clone the LLVM repo to `$LLVM_ROOT`.
+- Create a build directory, for example at `$LLVM_ROOT/build`.
+- Inside the build directory run: `cmake $LLVM_ROOT/llvm/
+  -DCMAKE_BUILD_TYPE=Release -DLLVM_ENABLE_PROJECTS="clang;clang-tools-extra"`.
+
+  - We suggest building in `Release` mode as building DEBUG binaries requires
+considerably more resources. You can check
+[Building LLVM with CMake documentation](https://llvm.org/docs/CMake.html)
+for more details about cmake flags.
+  - In addition to that using `Ninja` as a generator rather than default `make`
+is preferred. To do that consider passing `-G Ninja` to cmake invocation.
+  - Finally, you can turn on assertions via `-DLLVM_ENABLE_ASSERTS=On`.
+
+- Afterwards you can build clangd with `cmake --build $LLVM_ROOT/build --target
+  clangd`, similarly run tests by changing target to `check-clangd`.
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D92221: Don't delete default constructor of PathDiagnosticConsumerOptions

2021-01-22 Thread Moritz Sichert via Phabricator via cfe-commits
MoritzS updated this revision to Diff 318477.
MoritzS edited the summary of this revision.
MoritzS added a comment.

Initialize bool flags


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D92221

Files:
  clang/include/clang/Analysis/PathDiagnostic.h


Index: clang/include/clang/Analysis/PathDiagnostic.h
===
--- clang/include/clang/Analysis/PathDiagnostic.h
+++ clang/include/clang/Analysis/PathDiagnostic.h
@@ -68,11 +68,11 @@
   /// Whether to include additional information about macro expansions
   /// with the diagnostics, because otherwise they can be hard to obtain
   /// without re-compiling the program under analysis.
-  bool ShouldDisplayMacroExpansions;
+  bool ShouldDisplayMacroExpansions = false;
 
   /// Whether to include LLVM statistics of the process in the diagnostic.
   /// Useful for profiling the tool on large real-world codebases.
-  bool ShouldSerializeStats;
+  bool ShouldSerializeStats = false;
 
   /// If the consumer intends to produce multiple output files, should it
   /// use randomly generated file names for these files (with the tiny risk of
@@ -82,21 +82,19 @@
   /// because deterministic mode is always superior when done right, but
   /// for some consumers this mode is experimental and needs to be
   /// off by default.
-  bool ShouldWriteStableReportFilename;
+  bool ShouldWriteStableReportFilename = false;
 
   /// Whether the consumer should treat consumed diagnostics as hard errors.
   /// Useful for breaking your build when issues are found.
-  bool ShouldDisplayWarningsAsErrors;
+  bool ShouldDisplayWarningsAsErrors = false;
 
   /// Whether the consumer should attempt to rewrite the source file
   /// with fix-it hints attached to the diagnostics it consumes.
-  bool ShouldApplyFixIts;
+  bool ShouldApplyFixIts = false;
 
   /// Whether the consumer should present the name of the entity that emitted
   /// the diagnostic (eg., a checker) so that the user knew how to disable it.
-  bool ShouldDisplayDiagnosticName;
-
-  PathDiagnosticConsumerOptions() = delete;
+  bool ShouldDisplayDiagnosticName = false;
 };
 
 class PathDiagnosticConsumer {


Index: clang/include/clang/Analysis/PathDiagnostic.h
===
--- clang/include/clang/Analysis/PathDiagnostic.h
+++ clang/include/clang/Analysis/PathDiagnostic.h
@@ -68,11 +68,11 @@
   /// Whether to include additional information about macro expansions
   /// with the diagnostics, because otherwise they can be hard to obtain
   /// without re-compiling the program under analysis.
-  bool ShouldDisplayMacroExpansions;
+  bool ShouldDisplayMacroExpansions = false;
 
   /// Whether to include LLVM statistics of the process in the diagnostic.
   /// Useful for profiling the tool on large real-world codebases.
-  bool ShouldSerializeStats;
+  bool ShouldSerializeStats = false;
 
   /// If the consumer intends to produce multiple output files, should it
   /// use randomly generated file names for these files (with the tiny risk of
@@ -82,21 +82,19 @@
   /// because deterministic mode is always superior when done right, but
   /// for some consumers this mode is experimental and needs to be
   /// off by default.
-  bool ShouldWriteStableReportFilename;
+  bool ShouldWriteStableReportFilename = false;
 
   /// Whether the consumer should treat consumed diagnostics as hard errors.
   /// Useful for breaking your build when issues are found.
-  bool ShouldDisplayWarningsAsErrors;
+  bool ShouldDisplayWarningsAsErrors = false;
 
   /// Whether the consumer should attempt to rewrite the source file
   /// with fix-it hints attached to the diagnostics it consumes.
-  bool ShouldApplyFixIts;
+  bool ShouldApplyFixIts = false;
 
   /// Whether the consumer should present the name of the entity that emitted
   /// the diagnostic (eg., a checker) so that the user knew how to disable it.
-  bool ShouldDisplayDiagnosticName;
-
-  PathDiagnosticConsumerOptions() = delete;
+  bool ShouldDisplayDiagnosticName = false;
 };
 
 class PathDiagnosticConsumer {
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D92221: Don't delete default constructor of PathDiagnosticConsumerOptions

2021-01-22 Thread Moritz Sichert via Phabricator via cfe-commits
MoritzS added a comment.

Some tests were failing, I'll try to fix that and then commit the changes.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D92221

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


[PATCH] D93986: [clang-format] Add the possibility to align assignments spanning empty lines or comments

2021-01-22 Thread Lukas Barth via Phabricator via cfe-commits
tinloaf added inline comments.



Comment at: clang/docs/tools/dump_format_style.py:194
+# is used.
+pass
 elif state == State.InEnumMemberComment:

curdeius wrote:
> Just a nit, maybe we should have a warning at least?
Not sure. After this commit gets in, we'll always have an enum 
(`AlignConsecutiveStyle`) with five undocumented options. Thus, every run of 
this script would emit five warnings, and these warnings would become "intended 
behavior". I think this would probably confuse people?

Sure, one could implement some more elaborate way of detecting an intentionally 
undocumented enum, but I guess this would mean a larger modification of this 
state machine, and I'd rather not lump this together with this PR.  


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D93986

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


[PATCH] D93222: [analyzer] Introduce MacroExpansionContext to libAnalysis

2021-01-22 Thread Balázs Benics via Phabricator via cfe-commits
steakhal updated this revision to Diff 318480.
steakhal marked 2 inline comments as done.
steakhal retitled this revision from "[RFC][analyzer] Introduce 
MacroExpansionContext to libAnalysis" to "[analyzer] Introduce 
MacroExpansionContext to libAnalysis".
steakhal edited the summary of this revision.
steakhal added a comment.

No changes made besides backporting API changes from the immediate child 
revision, D93223 .
This way the API of `MacroExpansionContext` won't be changed in later parts of 
this stack.


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

https://reviews.llvm.org/D93222

Files:
  clang/include/clang/Analysis/MacroExpansionContext.h
  clang/lib/Analysis/CMakeLists.txt
  clang/lib/Analysis/MacroExpansionContext.cpp
  clang/unittests/Analysis/CMakeLists.txt
  clang/unittests/Analysis/MacroExpansionContextTest.cpp

Index: clang/unittests/Analysis/MacroExpansionContextTest.cpp
===
--- /dev/null
+++ clang/unittests/Analysis/MacroExpansionContextTest.cpp
@@ -0,0 +1,385 @@
+//===- unittests/Analysis/MacroExpansionContextTest.cpp - -===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+
+#include "clang/Analysis/MacroExpansionContext.h"
+#include "clang/AST/ASTConsumer.h"
+#include "clang/AST/ASTContext.h"
+#include "clang/Basic/Diagnostic.h"
+#include "clang/Basic/DiagnosticOptions.h"
+#include "clang/Basic/FileManager.h"
+#include "clang/Basic/LangOptions.h"
+#include "clang/Basic/SourceManager.h"
+#include "clang/Basic/TargetInfo.h"
+#include "clang/Basic/TargetOptions.h"
+#include "clang/Lex/HeaderSearch.h"
+#include "clang/Lex/HeaderSearchOptions.h"
+#include "clang/Lex/Preprocessor.h"
+#include "clang/Lex/PreprocessorOptions.h"
+#include "clang/Parse/Parser.h"
+#include "llvm/ADT/SmallString.h"
+#include "gtest/gtest.h"
+
+// static bool HACK_EnableDebugInUnitTest = (::llvm::DebugFlag = true);
+
+namespace clang {
+namespace analysis {
+namespace {
+
+class MacroExpansionContextTest : public ::testing::Test {
+protected:
+  MacroExpansionContextTest()
+  : InMemoryFileSystem(new llvm::vfs::InMemoryFileSystem),
+FileMgr(FileSystemOptions(), InMemoryFileSystem),
+DiagID(new DiagnosticIDs()), DiagOpts(new DiagnosticOptions()),
+Diags(DiagID, DiagOpts.get(), new IgnoringDiagConsumer()),
+SourceMgr(Diags, FileMgr), TargetOpts(new TargetOptions()) {
+TargetOpts->Triple = "x86_64-pc-linux-unknown";
+Target = TargetInfo::CreateTargetInfo(Diags, TargetOpts);
+LangOpts.CPlusPlus20 = 1; // For __VA_OPT__
+  }
+
+  IntrusiveRefCntPtr InMemoryFileSystem;
+  FileManager FileMgr;
+  IntrusiveRefCntPtr DiagID;
+  IntrusiveRefCntPtr DiagOpts;
+  DiagnosticsEngine Diags;
+  SourceManager SourceMgr;
+  LangOptions LangOpts;
+  std::shared_ptr TargetOpts;
+  IntrusiveRefCntPtr Target;
+
+  std::unique_ptr
+  getMacroExpansionContextFor(StringRef SourceText) {
+std::unique_ptr Buf =
+llvm::MemoryBuffer::getMemBuffer(SourceText);
+SourceMgr.setMainFileID(SourceMgr.createFileID(std::move(Buf)));
+TrivialModuleLoader ModLoader;
+HeaderSearch HeaderInfo(std::make_shared(), SourceMgr,
+Diags, LangOpts, Target.get());
+Preprocessor PP(std::make_shared(), Diags, LangOpts,
+SourceMgr, HeaderInfo, ModLoader,
+/*IILookup =*/nullptr,
+/*OwnsHeaderSearch =*/false);
+
+PP.Initialize(*Target);
+auto Ctx = std::make_unique(LangOpts);
+Ctx->registerForPreprocessor(PP);
+
+// Lex source text.
+PP.EnterMainSourceFile();
+
+while (true) {
+  Token Tok;
+  PP.Lex(Tok);
+  if (Tok.is(tok::eof))
+break;
+}
+
+// Callbacks have been executed at this point.
+return Ctx;
+  }
+
+  /// Returns the expansion location to main file at the given row and column.
+  SourceLocation at(unsigned row, unsigned col) const {
+SourceLocation Loc =
+SourceMgr.translateLineCol(SourceMgr.getMainFileID(), row, col);
+return SourceMgr.getExpansionLoc(Loc);
+  }
+};
+
+TEST_F(MacroExpansionContextTest, NoneForNonExpansionLocations) {
+  const auto Ctx = getMacroExpansionContextFor(R"code(
+  #define EMPTY
+  A b cd EMPTY ef EMPTY gh
+EMPTY zz
+  )code");
+  // After preprocessing:
+  //  A b cd ef gh
+  //  zz
+
+  // That's the beginning of the definition of EMPTY.
+  EXPECT_FALSE(Ctx->getExpandedText(at(2, 11)).hasValue());
+  EXPECT_FALSE(Ctx->getOriginalText(at(2, 11)).hasValue());
+
+  // The space before the first expansion of EMPTY.
+  EXPECT_FALSE(Ctx->getExpandedText(at(3, 9)).hasValue());
+  EXPECT_FALSE(Ctx->getOriginalText(at(3, 9)

[PATCH] D93223: [analyzer] Create MacroExpansionContext member in AnalysisConsumer

2021-01-22 Thread Balázs Benics via Phabricator via cfe-commits
steakhal updated this revision to Diff 318482.
steakhal retitled this revision from "[RFC][analyzer] Create 
MacroExpansionContext member in AnalysisConsumer and pass down to the 
diagnostics consumers" to "[analyzer] Create MacroExpansionContext member in 
AnalysisConsumer".
steakhal edited the summary of this revision.
steakhal added a comment.

Nothing changed besides moving some parts to the parent revision.

- `registerForPreprocessor` member function
- `Optional` return type
- `NoneForNonExpansionLocations` unittest-case


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

https://reviews.llvm.org/D93223

Files:
  clang/include/clang/StaticAnalyzer/Core/PathDiagnosticConsumers.h
  clang/lib/StaticAnalyzer/Core/HTMLDiagnostics.cpp
  clang/lib/StaticAnalyzer/Core/PlistDiagnostics.cpp
  clang/lib/StaticAnalyzer/Core/SarifDiagnostics.cpp
  clang/lib/StaticAnalyzer/Core/TextDiagnostics.cpp
  clang/lib/StaticAnalyzer/Frontend/AnalysisConsumer.cpp

Index: clang/lib/StaticAnalyzer/Frontend/AnalysisConsumer.cpp
===
--- clang/lib/StaticAnalyzer/Frontend/AnalysisConsumer.cpp
+++ clang/lib/StaticAnalyzer/Frontend/AnalysisConsumer.cpp
@@ -20,6 +20,7 @@
 #include "clang/Analysis/CFG.h"
 #include "clang/Analysis/CallGraph.h"
 #include "clang/Analysis/CodeInjector.h"
+#include "clang/Analysis/MacroExpansionContext.h"
 #include "clang/Analysis/PathDiagnostic.h"
 #include "clang/Basic/SourceManager.h"
 #include "clang/CrossTU/CrossTranslationUnit.h"
@@ -98,6 +99,8 @@
   /// working with a PCH file.
   SetOfDecls LocalTUDecls;
 
+  MacroExpansionContext MacroExpansions;
+
   // Set of PathDiagnosticConsumers.  Owned by AnalysisManager.
   PathDiagnosticConsumers PathConsumers;
 
@@ -122,7 +125,8 @@
CodeInjector *injector)
   : RecVisitorMode(0), RecVisitorBR(nullptr), Ctx(nullptr),
 PP(CI.getPreprocessor()), OutDir(outdir), Opts(std::move(opts)),
-Plugins(plugins), Injector(injector), CTU(CI) {
+Plugins(plugins), Injector(injector), CTU(CI),
+MacroExpansions(CI.getLangOpts()) {
 DigestAnalyzerOptions();
 if (Opts->PrintStats || Opts->ShouldSerializeStats) {
   AnalyzerTimers = std::make_unique(
@@ -136,6 +140,9 @@
   *AnalyzerTimers);
   llvm::EnableStatistics(/* PrintOnExit= */ false);
 }
+
+if (Opts->ShouldDisplayMacroExpansions)
+  MacroExpansions.registerForPreprocessor(PP);
   }
 
   ~AnalysisConsumer() override {
@@ -150,7 +157,8 @@
   break;
 #define ANALYSIS_DIAGNOSTICS(NAME, CMDFLAG, DESC, CREATEFN)\
   case PD_##NAME:  \
-CREATEFN(Opts->getDiagOpts(), PathConsumers, OutDir, PP, CTU); \
+CREATEFN(Opts->getDiagOpts(), PathConsumers, OutDir, PP, CTU,  \
+ MacroExpansions); \
 break;
 #include "clang/StaticAnalyzer/Core/Analyses.def"
 default:
Index: clang/lib/StaticAnalyzer/Core/TextDiagnostics.cpp
===
--- clang/lib/StaticAnalyzer/Core/TextDiagnostics.cpp
+++ clang/lib/StaticAnalyzer/Core/TextDiagnostics.cpp
@@ -10,6 +10,7 @@
 //
 //===--===//
 
+#include "clang/Analysis/MacroExpansionContext.h"
 #include "clang/Analysis/PathDiagnostic.h"
 #include "clang/Basic/SourceManager.h"
 #include "clang/Basic/Version.h"
@@ -138,8 +139,9 @@
 
 void ento::createTextPathDiagnosticConsumer(
 PathDiagnosticConsumerOptions DiagOpts, PathDiagnosticConsumers &C,
-const std::string &Prefix, const clang::Preprocessor &PP,
-const cross_tu::CrossTranslationUnitContext &CTU) {
+const std::string &Prefix, const Preprocessor &PP,
+const cross_tu::CrossTranslationUnitContext &CTU,
+const MacroExpansionContext &MacroExpansions) {
   C.emplace_back(new TextDiagnostics(std::move(DiagOpts), PP.getDiagnostics(),
  PP.getLangOpts(),
  /*ShouldDisplayPathNotes=*/true));
@@ -147,8 +149,9 @@
 
 void ento::createTextMinimalPathDiagnosticConsumer(
 PathDiagnosticConsumerOptions DiagOpts, PathDiagnosticConsumers &C,
-const std::string &Prefix, const clang::Preprocessor &PP,
-const cross_tu::CrossTranslationUnitContext &CTU) {
+const std::string &Prefix, const Preprocessor &PP,
+const cross_tu::CrossTranslationUnitContext &CTU,
+const MacroExpansionContext &MacroExpansions) {
   C.emplace_back(new TextDiagnostics(std::move(DiagOpts), PP.getDiagnostics(),
  PP.getLangOpts(),
  /*ShouldDisplayPathNotes=*/false));
Index: clang/lib/StaticAnalyzer/Core/SarifDiagnostics.cpp
===
--- clang/lib/StaticAnalyzer/Core/SarifDiagnostic

[clang] d972d4c - Revert "[clang] Suppress "follow-up" diagnostics on recovery call expressions."

2021-01-22 Thread Haojian Wu via cfe-commits

Author: Haojian Wu
Date: 2021-01-22T13:04:37+01:00
New Revision: d972d4c749048531953a16b815e07c67e8455a3b

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

LOG: Revert "[clang] Suppress "follow-up" diagnostics on recovery call 
expressions."

This reverts commit efa9aaad703e6b150980ed1a74b4e7c9da7d85a2 and adds a
crash test.

The commit caused a crash in CodeGen with -fms-compatibility, see
https://bugs.llvm.org/show_bug.cgi?id=48690.

Added: 
clang/test/CodeGenCXX/ms-lookup-template-base-classes.cpp

Modified: 
clang/lib/Sema/SemaOverload.cpp
clang/test/AST/ast-dump-recovery.cpp
clang/test/SemaCXX/typo-correction-delayed.cpp

Removed: 




diff  --git a/clang/lib/Sema/SemaOverload.cpp b/clang/lib/Sema/SemaOverload.cpp
index 13d2125d1a28..2bef37b76763 100644
--- a/clang/lib/Sema/SemaOverload.cpp
+++ b/clang/lib/Sema/SemaOverload.cpp
@@ -12923,7 +12923,7 @@ BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
 return ExprError();
   }
 
-  // Build an implicit member access expression if appropriate. Just drop the
+  // Build an implicit member call if appropriate.  Just drop the
   // casts and such from the call, we don't really care.
   ExprResult NewFn = ExprError();
   if ((*R.begin())->isCXXClassMember())
@@ -12938,19 +12938,12 @@ BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr 
*Fn,
   if (NewFn.isInvalid())
 return ExprError();
 
-  auto CallE =
-  SemaRef.BuildCallExpr(/*Scope*/ nullptr, NewFn.get(), LParenLoc,
-MultiExprArg(Args.data(), Args.size()), RParenLoc);
-  if (CallE.isInvalid())
-return ExprError();
-  // We now have recovered a callee. However, building a real call may lead to
-  // incorrect secondary diagnostics if our recovery wasn't correct.
-  // We keep the recovery behavior but suppress all following diagnostics by
-  // using RecoveryExpr. We deliberately drop the return type of the recovery
-  // function, and rely on clang's dependent mechanism to suppress following
-  // diagnostics.
-  return SemaRef.CreateRecoveryExpr(CallE.get()->getBeginLoc(),
-CallE.get()->getEndLoc(), {CallE.get()});
+  // This shouldn't cause an infinite loop because we're giving it
+  // an expression with viable lookup results, which should never
+  // end up here.
+  return SemaRef.BuildCallExpr(/*Scope*/ nullptr, NewFn.get(), LParenLoc,
+   MultiExprArg(Args.data(), Args.size()),
+   RParenLoc);
 }
 
 /// Constructs and populates an OverloadedCandidateSet from

diff  --git a/clang/test/AST/ast-dump-recovery.cpp 
b/clang/test/AST/ast-dump-recovery.cpp
index a8da2b8ad449..b6d7ac1d0a8e 100644
--- a/clang/test/AST/ast-dump-recovery.cpp
+++ b/clang/test/AST/ast-dump-recovery.cpp
@@ -296,14 +296,3 @@ void InvalidCondition() {
   // CHECK-NEXT: `-IntegerLiteral {{.*}} 'int' 2
   invalid() ? 1 : 2;
 }
-
-void abcc();
-void TypoCorrection() {
-  // RecoveryExpr is always dependent-type in this case in order to suppress
-  // following diagnostics.
-  // CHECK:  RecoveryExpr {{.*}} ''
-  // CHECK-NEXT: `-CallExpr {{.*}} 'void'
-  // CHECK-NEXT:   `-ImplicitCastExpr
-  // CHECK-NEXT: `-DeclRefExpr {{.*}} 'abcc'
-  abc();
-}

diff  --git a/clang/test/CodeGenCXX/ms-lookup-template-base-classes.cpp 
b/clang/test/CodeGenCXX/ms-lookup-template-base-classes.cpp
new file mode 100644
index ..fbc211aca17a
--- /dev/null
+++ b/clang/test/CodeGenCXX/ms-lookup-template-base-classes.cpp
@@ -0,0 +1,15 @@
+// RUN: %clang_cc1 -triple x86_64-windows-msvc -emit-obj -fms-compatibility %s 
-o -
+// CHECK that we don't crash.
+
+struct Base {
+  void b(int, int);
+};
+
+template  struct Derived : Base {
+  void d() { b(1, 2); }
+};
+
+void use() {
+  Derived d;
+  d.d();
+}

diff  --git a/clang/test/SemaCXX/typo-correction-delayed.cpp 
b/clang/test/SemaCXX/typo-correction-delayed.cpp
index aa136a08be4f..66d19daf66fd 100644
--- a/clang/test/SemaCXX/typo-correction-delayed.cpp
+++ b/clang/test/SemaCXX/typo-correction-delayed.cpp
@@ -209,15 +209,6 @@ int z = 1 ? N : ;  // expected-error {{expected 
expression}}
 // expected-error-re@-1 {{use of undeclared identifier 'N'{{$
 }
 
-namespace noSecondaryDiags {
-void abcc(); // expected-note {{'abcc' declared here}}
-
-void test() {
-  // Verify the secondary diagnostic ".. convertible to 'bool'" is suppressed.
-  if (abc()) {} // expected-error {{use of undeclared identifier 'abc'; did 
you mean 'abcc'?}}
-}
-}
-
 // PR 23285. This test must be at the end of the file to avoid additional,
 // unwanted diagnostics.
 // expected-error-re@+2 {{use of undeclared identifier 'uintmax_t'{{$



___
cfe-commits mailing list
cfe-commits@lists

[PATCH] D94745: [OpenMP][WIP] Build the deviceRTLs with OpenMP instead of target dependent language - NOT FOR REVIEW

2021-01-22 Thread Jon Chesterfield via Phabricator via cfe-commits
JonChesterfield added inline comments.



Comment at: openmp/libomptarget/deviceRTLs/nvptx/CMakeLists.txt:24
+  return()
+endif()
+

jdoerfert wrote:
> we need the 32 bit versions as well, I guess?
We could limit to 64 and see if a feature request for 32 comes in.



Comment at: openmp/libomptarget/deviceRTLs/nvptx/src/target_impl.h:62
 #else
+#error "Wrong number!"
 #define MAX_SM 16

Unintended?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D94745

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


[PATCH] D94779: [Clang] Ensure vector predication pragma is ignored only when vectorization width is 1.

2021-01-22 Thread Dave Green via Phabricator via cfe-commits
dmgreen added a comment.

Thanks. @fhahn @SjoerdMeijer what do we think about the edge case where the 
width==1? As far as I understand (with this patch):

  #pragma clang loop vectorize_predicate(disable) vectorize_width(4)
  Gives llvm.loop.vectorize.predicate.enable=false, 
llvm.loop.vectorize.width=4, llvm.loop.vectorize.scalable.enable=false, 
llvm.loop.vectorize.enable=true
  
  #pragma clang loop vectorize_predicate(disable) vectorize_width(4)
  Gives llvm.loop.vectorize.predicate.enable=true, llvm.loop.vectorize.width=4, 
llvm.loop.vectorize.scalable.enable=false, llvm.loop.vectorize.enable=true
  
  #pragma clang loop vectorize_predicate(enable) vectorize_width(1)
  Gives llvm.loop.vectorize.width=1, llvm.loop.vectorize.scalable.enable=false
  
  #pragma clang loop vectorize_predicate(disable) vectorize_width(1)
  Gives llvm.loop.vectorize.width=1, llvm.loop.vectorize.scalable.enable=false

Should we be adding llvm.loop.vectorize.predicate.enable metadata even when 
width=1? I would be inclined to emit the predication pragma anyway.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D94779

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


[PATCH] D95016: [Clang][RISCV] Add custom TableGen backend for riscv-vector intrinsics.

2021-01-22 Thread Craig Topper via Phabricator via cfe-commits
craig.topper added inline comments.



Comment at: clang/utils/TableGen/RISCVVEmitter.cpp:772
+  // Parse records
+  SmallVector, 512> Defs;
+  std::vector RV = Records.getAllDerivedDefinitions("RVVBuiltin");

This getAllDerivedDefinitions, loop, call createRVVIntrinsic is repeated in 4 
places. I realize it was copied from the NeonEmitter to the SveEmitter, but I 
don't think we should repeat that.

Maybe just sink the loop and getAllDerivedDefinitions into createRVVIntrinsic, 
rename it createRVVIntrinsics and have it return the Defs vector?



Comment at: clang/utils/TableGen/RISCVVEmitter.cpp:772
+  // Parse records
+  SmallVector, 512> Defs;
+  std::vector RV = Records.getAllDerivedDefinitions("RVVBuiltin");

craig.topper wrote:
> This getAllDerivedDefinitions, loop, call createRVVIntrinsic is repeated in 4 
> places. I realize it was copied from the NeonEmitter to the SveEmitter, but I 
> don't think we should repeat that.
> 
> Maybe just sink the loop and getAllDerivedDefinitions into 
> createRVVIntrinsic, rename it createRVVIntrinsics and have it return the Defs 
> vector?
Given what I know about the namer of builtins we need, there's no way we're 
going to fit in this 512 right? Except if we're only generate a subset of 
tests? If that's the case probably should just use a std::vector.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D95016

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


[PATCH] D95016: [Clang][RISCV] Add custom TableGen backend for riscv-vector intrinsics.

2021-01-22 Thread Craig Topper via Phabricator via cfe-commits
craig.topper added inline comments.



Comment at: clang/utils/TableGen/RISCVVEmitter.cpp:772
+  // Parse records
+  SmallVector, 512> Defs;
+  std::vector RV = Records.getAllDerivedDefinitions("RVVBuiltin");

craig.topper wrote:
> craig.topper wrote:
> > This getAllDerivedDefinitions, loop, call createRVVIntrinsic is repeated in 
> > 4 places. I realize it was copied from the NeonEmitter to the SveEmitter, 
> > but I don't think we should repeat that.
> > 
> > Maybe just sink the loop and getAllDerivedDefinitions into 
> > createRVVIntrinsic, rename it createRVVIntrinsics and have it return the 
> > Defs vector?
> Given what I know about the namer of builtins we need, there's no way we're 
> going to fit in this 512 right? Except if we're only generate a subset of 
> tests? If that's the case probably should just use a std::vector.
Oops that should have said "number of builtins we need"


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D95016

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


[PATCH] D95016: [Clang][RISCV] Add custom TableGen backend for riscv-vector intrinsics.

2021-01-22 Thread Zakk Chen via Phabricator via cfe-commits
khchen updated this revision to Diff 318423.
khchen added a comment.

1. address @craig.topper's comment.
2. rewrite script as python.

I'm still have no idea to make generating tests mechanism be more elegant...


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D95016

Files:
  clang/include/clang/Basic/BuiltinsRISCV.def
  clang/include/clang/Basic/CMakeLists.txt
  clang/include/clang/Basic/riscv_vector.td
  clang/lib/CodeGen/CGBuiltin.cpp
  clang/lib/Headers/CMakeLists.txt
  clang/test/CodeGen/RISCV/riscv-rvv-intrinsics-generic/vadd.c
  clang/test/CodeGen/RISCV/riscv-rvv-intrinsics-generic/vfadd.c
  clang/test/CodeGen/RISCV/riscv-rvv-intrinsics/vadd.c
  clang/test/CodeGen/RISCV/riscv-rvv-intrinsics/vfadd.c
  clang/test/CodeGen/RISCV/vadd.c
  clang/test/Headers/riscv-vector-header.c
  clang/utils/TableGen/CMakeLists.txt
  clang/utils/TableGen/RISCVVEmitter.cpp
  clang/utils/TableGen/TableGen.cpp
  clang/utils/TableGen/TableGenBackends.h
  clang/utils/TestUtils/gen-riscv-v-tests.sh
  clang/utils/TestUtils/gen-rvv-tests.py
  llvm/docs/CommandGuide/tblgen.rst

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


[PATCH] D95016: [Clang][RISCV] Add custom TableGen backend for riscv-vector intrinsics.

2021-01-22 Thread Zakk Chen via Phabricator via cfe-commits
khchen marked 7 inline comments as done.
khchen added inline comments.



Comment at: clang/include/clang/Basic/riscv_vector.td:191
+defvar suffix = s_p[1];
+defvar prototype = s_p[2];
+

Paul-C-Anagnostopoulos wrote:
> Well now, thanks for highlighting an inconsistency I did not know about. The 
> documentation says that x[0] produces a list of the 0th element of x, which 
> is why I suggested using !head. But that is true only in certain contexts, 
> such as when x is a defvar. Otherwise it produces the single element. Ouch.
I also thanks for your suggestion. When I was trying to use `!head(s_p[1])` but 
it didn't work, and then I found giving the index is clearer.



Comment at: clang/include/clang/Basic/riscv_vector.td:204
+// op_list in gen-riscv-v-tests.sh.
+#ifdef ALL
+#define VADD

jrtc27 wrote:
> Probably nicer to have a notion of a builtin group and allow the records to 
> be filtered (with the default being to process all of them). Depending on 
> what's still to come you could even use NAME automatically as the group for 
> RVVBinBuiltinSet's RVV(Bin)Builtins given that's always the lowercase version 
> of the macro guarding the definitions at the moment.
@jrtc27 Sorry, I still have no idea to do that, could you please elaborate it 
more?
In our downstream implementation, some builtins inherit `RVVBuiltin` class 
directly. Does your solution still work in this situation?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D95016

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


[PATCH] D95016: [Clang][RISCV] Add custom TableGen backend for riscv-vector intrinsics.

2021-01-22 Thread Zakk Chen via Phabricator via cfe-commits
khchen updated this revision to Diff 318447.
khchen marked 2 inline comments as done.
khchen added a comment.

1. do not need to manually define new op in gen-rvv-tests.py.
2. do not need to manually add new op define in ALL marco.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D95016

Files:
  clang/include/clang/Basic/BuiltinsRISCV.def
  clang/include/clang/Basic/CMakeLists.txt
  clang/include/clang/Basic/riscv_vector.td
  clang/lib/CodeGen/CGBuiltin.cpp
  clang/lib/Headers/CMakeLists.txt
  clang/test/CodeGen/RISCV/riscv-rvv-intrinsics-generic/vadd.c
  clang/test/CodeGen/RISCV/riscv-rvv-intrinsics-generic/vfadd.c
  clang/test/CodeGen/RISCV/riscv-rvv-intrinsics/vadd.c
  clang/test/CodeGen/RISCV/riscv-rvv-intrinsics/vfadd.c
  clang/test/CodeGen/RISCV/vadd.c
  clang/test/Headers/riscv-vector-header.c
  clang/utils/TableGen/CMakeLists.txt
  clang/utils/TableGen/RISCVVEmitter.cpp
  clang/utils/TableGen/TableGen.cpp
  clang/utils/TableGen/TableGenBackends.h
  clang/utils/TestUtils/gen-rvv-tests.py
  llvm/docs/CommandGuide/tblgen.rst

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


[PATCH] D95221: [clang][cli] NFC: Move prefix to the front of BoolOption

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

The prefix used to be the last (optional) argument to BoolOption. This decision 
was made with the expectation that only few command line options would need to 
pass it explicitly instead of using Bool{F,G}Option. It turns out that a 
considerable number of options don't conform to Bool{F,G}Option and need to 
provide the prefix anyways. This sometimes requires to explicitly pass 
`BothFlags<[]>`.

This patch makes prefix the first parameter, so it now directly precedes the 
spelling base string. Now 8 options dropped `BothFlags<[]>` and only two 
options (`pthread` and `emit_llvm_uselists`) need to pass an empty prefix.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D95221

Files:
  clang/include/clang/Driver/Options.td

Index: clang/include/clang/Driver/Options.td
===
--- clang/include/clang/Driver/Options.td
+++ clang/include/clang/Driver/Options.td
@@ -375,10 +375,10 @@
 // BoolOption is the API that should be used most of the time. Use this only
 // when you need more control (e.g. to represent a marshalled option whose
 // keypath defaults to an arbitrarily complex boolean expression).
-multiclass BoolOptionBase,
-  string prefix = ""> {
+  FlagDefSuffix flags_suffix = FlagDefSuffix<[], "">> {
   defvar flag1 = FlagDefExpanded.Result,
  prefix, NAME, spelling_base>;
 
@@ -436,29 +436,28 @@
 /// Creates two command line flags that control the same boolean keypath.
 ///
 /// Example:
-///   defm my_boolean_option : BoolOption<"my-boolean-option",
+///   defm my_boolean_option : BoolOption<"f", "my-boolean-option",
 /// CodeGenOpts<"MyBooleanOption">, DefaultsToFalse,
 /// ChangedBy,
 /// ResetBy,
 /// BothFlags<[CoreOption], " my boolean option.">;
 ///
 ///   The Clang driver now knows two new command line flags: the "positive"
-///   -my-boolean-option and the "negative" -no-my-boolean-option. The positive
-///   flag is also available on the CC1 command line.
+///   -fmy-boolean-option and the "negative" -fno-my-boolean-option. The
+///   positive flag is also available on the CC1 command line.
 ///
 ///   * When the command line contains neither of the flags, the keypath value
 /// defaults to false.
 ///   * When the command line contains the positive -my-boolean-option, the
 /// keypath value changes to true.
-///   * When the command line contains the negative -no-my-bool-option, the
+///   * When the command line contains the negative -fno-my-bool-option, the
 /// keypath value resets to false.
 ///
 ///   The help text for -my-boolean-option is "Enable my boolean option." and
-///   "Disable my boolean option." for -no-my-boolean-option.
-multiclass BoolOption,
-  string name_prefix = ""> {
+  ResetBy reset_by, BothFlags both = BothFlags<[], "">> {
   defvar default = Default;
 
   defvar changed_by_flag = FlagDef;
 
-  defm NAME : BoolOptionBase;
+  defm NAME : BoolOptionBase;
 }
 
 /// Creates a BoolOption with the changing available on the CC1 command line.
-multiclass BoolCC1Option,
- string name_prefix = ""> {
+ ResetBy reset_by, BothFlags both = BothFlags<[], "">> {
   defvar changed_by_cc1
 = ChangedBy;
 
-  defm NAME : BoolOption;
+  defm NAME : BoolOption;
 }
 
 /// Creates a BoolOption where both of the flags are prefixed with "f", are in
@@ -494,8 +492,8 @@
 multiclass BoolFOption> {
-  defm NAME : BoolCC1Option,
+  defm NAME : BoolCC1Option<"f", flag_base, kpm, defaults_to, changed_by,
+reset_by, both>,
   Group;
 }
 
@@ -505,8 +503,8 @@
 multiclass BoolGOption> {
-  defm NAME : BoolCC1Option,
+  defm NAME : BoolCC1Option<"g", flag_base, kpm, defaults_to, changed_by,
+reset_by, both>,
   Group;
 }
 
@@ -1269,11 +1267,11 @@
   Flags<[CoreOption, CC1Option]>, HelpText<"Place uninitialized global variables in a common block">,
   MarshallingInfoNegativeFlag>;
 def fcompile_resource_EQ : Joined<["-"], "fcompile-resource=">, Group;
-defm complete_member_pointers : BoolOption<"complete-member-pointers",
+defm complete_member_pointers : BoolOption<"f", "complete-member-pointers",
   LangOpts<"CompleteMemberPointers">, DefaultsToFalse,
   ChangedBy, ResetBy,
   BothFlags<[CoreOption], " member pointer base types to be complete if they"
-" would be significant under the Microsoft ABI">, "f">,
+" would be significant under the Microsoft ABI">>,
   Group;
 def fcf_runtime_abi_EQ : Joined<["-"], "fcf-runtime-abi=">, Group,
 Flags<[CC1Option]>, Values<"unspecified,stand

[clang] e16959c - Don't delete default constructor of PathDiagnosticConsumerOptions

2021-01-22 Thread Moritz Sichert via cfe-commits

Author: Moritz Sichert
Date: 2021-01-22T13:42:38+01:00
New Revision: e16959c9b8553a60ec5e9aa55d101154d5805292

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

LOG: Don't delete default constructor of PathDiagnosticConsumerOptions

This type is used as an aggregate, i.e. it has no member functions.
Starting with C++20 types with deleted default constructors are not
aggregate types anymore which means that aggregate initialization will
not work for this class anymore. This leads to a compile error in
clang::AnalyzerOptions::getDiagOpts() for example.

Also set the boolean flags to false by default to avoid undefined
behavior. Previously this was prevented by deleting the default
constructor, now we explicitly initialize them.

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

Added: 


Modified: 
clang/include/clang/Analysis/PathDiagnostic.h

Removed: 




diff  --git a/clang/include/clang/Analysis/PathDiagnostic.h 
b/clang/include/clang/Analysis/PathDiagnostic.h
index 544e9f4662d3..539aa20b8168 100644
--- a/clang/include/clang/Analysis/PathDiagnostic.h
+++ b/clang/include/clang/Analysis/PathDiagnostic.h
@@ -68,11 +68,11 @@ struct PathDiagnosticConsumerOptions {
   /// Whether to include additional information about macro expansions
   /// with the diagnostics, because otherwise they can be hard to obtain
   /// without re-compiling the program under analysis.
-  bool ShouldDisplayMacroExpansions;
+  bool ShouldDisplayMacroExpansions = false;
 
   /// Whether to include LLVM statistics of the process in the diagnostic.
   /// Useful for profiling the tool on large real-world codebases.
-  bool ShouldSerializeStats;
+  bool ShouldSerializeStats = false;
 
   /// If the consumer intends to produce multiple output files, should it
   /// use randomly generated file names for these files (with the tiny risk of
@@ -82,21 +82,19 @@ struct PathDiagnosticConsumerOptions {
   /// because deterministic mode is always superior when done right, but
   /// for some consumers this mode is experimental and needs to be
   /// off by default.
-  bool ShouldWriteStableReportFilename;
+  bool ShouldWriteStableReportFilename = false;
 
   /// Whether the consumer should treat consumed diagnostics as hard errors.
   /// Useful for breaking your build when issues are found.
-  bool ShouldDisplayWarningsAsErrors;
+  bool ShouldDisplayWarningsAsErrors = false;
 
   /// Whether the consumer should attempt to rewrite the source file
   /// with fix-it hints attached to the diagnostics it consumes.
-  bool ShouldApplyFixIts;
+  bool ShouldApplyFixIts = false;
 
   /// Whether the consumer should present the name of the entity that emitted
   /// the diagnostic (eg., a checker) so that the user knew how to disable it.
-  bool ShouldDisplayDiagnosticName;
-
-  PathDiagnosticConsumerOptions() = delete;
+  bool ShouldDisplayDiagnosticName = false;
 };
 
 class PathDiagnosticConsumer {



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


[PATCH] D92221: Don't delete default constructor of PathDiagnosticConsumerOptions

2021-01-22 Thread Moritz Sichert via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rGe16959c9b855: Don't delete default constructor of 
PathDiagnosticConsumerOptions (authored by MoritzS).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D92221

Files:
  clang/include/clang/Analysis/PathDiagnostic.h


Index: clang/include/clang/Analysis/PathDiagnostic.h
===
--- clang/include/clang/Analysis/PathDiagnostic.h
+++ clang/include/clang/Analysis/PathDiagnostic.h
@@ -68,11 +68,11 @@
   /// Whether to include additional information about macro expansions
   /// with the diagnostics, because otherwise they can be hard to obtain
   /// without re-compiling the program under analysis.
-  bool ShouldDisplayMacroExpansions;
+  bool ShouldDisplayMacroExpansions = false;
 
   /// Whether to include LLVM statistics of the process in the diagnostic.
   /// Useful for profiling the tool on large real-world codebases.
-  bool ShouldSerializeStats;
+  bool ShouldSerializeStats = false;
 
   /// If the consumer intends to produce multiple output files, should it
   /// use randomly generated file names for these files (with the tiny risk of
@@ -82,21 +82,19 @@
   /// because deterministic mode is always superior when done right, but
   /// for some consumers this mode is experimental and needs to be
   /// off by default.
-  bool ShouldWriteStableReportFilename;
+  bool ShouldWriteStableReportFilename = false;
 
   /// Whether the consumer should treat consumed diagnostics as hard errors.
   /// Useful for breaking your build when issues are found.
-  bool ShouldDisplayWarningsAsErrors;
+  bool ShouldDisplayWarningsAsErrors = false;
 
   /// Whether the consumer should attempt to rewrite the source file
   /// with fix-it hints attached to the diagnostics it consumes.
-  bool ShouldApplyFixIts;
+  bool ShouldApplyFixIts = false;
 
   /// Whether the consumer should present the name of the entity that emitted
   /// the diagnostic (eg., a checker) so that the user knew how to disable it.
-  bool ShouldDisplayDiagnosticName;
-
-  PathDiagnosticConsumerOptions() = delete;
+  bool ShouldDisplayDiagnosticName = false;
 };
 
 class PathDiagnosticConsumer {


Index: clang/include/clang/Analysis/PathDiagnostic.h
===
--- clang/include/clang/Analysis/PathDiagnostic.h
+++ clang/include/clang/Analysis/PathDiagnostic.h
@@ -68,11 +68,11 @@
   /// Whether to include additional information about macro expansions
   /// with the diagnostics, because otherwise they can be hard to obtain
   /// without re-compiling the program under analysis.
-  bool ShouldDisplayMacroExpansions;
+  bool ShouldDisplayMacroExpansions = false;
 
   /// Whether to include LLVM statistics of the process in the diagnostic.
   /// Useful for profiling the tool on large real-world codebases.
-  bool ShouldSerializeStats;
+  bool ShouldSerializeStats = false;
 
   /// If the consumer intends to produce multiple output files, should it
   /// use randomly generated file names for these files (with the tiny risk of
@@ -82,21 +82,19 @@
   /// because deterministic mode is always superior when done right, but
   /// for some consumers this mode is experimental and needs to be
   /// off by default.
-  bool ShouldWriteStableReportFilename;
+  bool ShouldWriteStableReportFilename = false;
 
   /// Whether the consumer should treat consumed diagnostics as hard errors.
   /// Useful for breaking your build when issues are found.
-  bool ShouldDisplayWarningsAsErrors;
+  bool ShouldDisplayWarningsAsErrors = false;
 
   /// Whether the consumer should attempt to rewrite the source file
   /// with fix-it hints attached to the diagnostics it consumes.
-  bool ShouldApplyFixIts;
+  bool ShouldApplyFixIts = false;
 
   /// Whether the consumer should present the name of the entity that emitted
   /// the diagnostic (eg., a checker) so that the user knew how to disable it.
-  bool ShouldDisplayDiagnosticName;
-
-  PathDiagnosticConsumerOptions() = delete;
+  bool ShouldDisplayDiagnosticName = false;
 };
 
 class PathDiagnosticConsumer {
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] a0e3091 - [clang][Tooling] Get rid of a hack in SymbolOccurrences, NFCI

2021-01-22 Thread Mikhail Maltsev via cfe-commits

Author: Mikhail Maltsev
Date: 2021-01-22T13:01:41Z
New Revision: a0e30914f8c8bb60795a008ce2d9e3c0a4f9b7a2

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

LOG: [clang][Tooling] Get rid of a hack in SymbolOccurrences, NFCI

The class `SymbolOccurrences` can store either a single `SourceRange`
in-place or multiple `SourceRanges` on the heap. In the latter case
the number of source ranges is stored in the internal representation
of the beginning `SourceLocation` of the in-place `SourceRange`
object.

This change gets rid of such hack by placing `SourceRange` in a union
which holds either a valid `SourceRange` or an `unsigned int` (a number
of ranges).

The change also adds `static_assert`s that check that `SourceRange` and
`SourceLocation` are trivially destructible (this is required for the
current patch and for D94237 which has already been committed).

Reviewed By: MarkMurrayARM, simon_tatham

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

Added: 


Modified: 
clang/include/clang/Tooling/Refactoring/Rename/SymbolOccurrences.h
clang/lib/Basic/SourceLocation.cpp
clang/lib/Tooling/Refactoring/Rename/SymbolOccurrences.cpp

Removed: 




diff  --git 
a/clang/include/clang/Tooling/Refactoring/Rename/SymbolOccurrences.h 
b/clang/include/clang/Tooling/Refactoring/Rename/SymbolOccurrences.h
index 3b903cb822f3..c4bfaa9cc377 100644
--- a/clang/include/clang/Tooling/Refactoring/Rename/SymbolOccurrences.h
+++ b/clang/include/clang/Tooling/Refactoring/Rename/SymbolOccurrences.h
@@ -69,17 +69,18 @@ class SymbolOccurrence {
   OccurrenceKind getKind() const { return Kind; }
 
   ArrayRef getNameRanges() const {
-if (MultipleRanges) {
-  return llvm::makeArrayRef(MultipleRanges.get(),
-RangeOrNumRanges.getBegin().getRawEncoding());
-}
-return RangeOrNumRanges;
+if (MultipleRanges)
+  return llvm::makeArrayRef(MultipleRanges.get(), NumRanges);
+return SingleRange;
   }
 
 private:
   OccurrenceKind Kind;
   std::unique_ptr MultipleRanges;
-  SourceRange RangeOrNumRanges;
+  union {
+SourceRange SingleRange;
+unsigned NumRanges;
+  };
 };
 
 using SymbolOccurrences = std::vector;

diff  --git a/clang/lib/Basic/SourceLocation.cpp 
b/clang/lib/Basic/SourceLocation.cpp
index fde139932c40..6f6412028d77 100644
--- a/clang/lib/Basic/SourceLocation.cpp
+++ b/clang/lib/Basic/SourceLocation.cpp
@@ -42,6 +42,14 @@ void PrettyStackTraceLoc::print(raw_ostream &OS) const {
 // SourceLocation
 
//===--===//
 
+static_assert(std::is_trivially_destructible::value,
+  "SourceLocation must be trivially destructible because it is "
+  "used in unions");
+
+static_assert(std::is_trivially_destructible::value,
+  "SourceRange must be trivially destructible because it is "
+  "used in unions");
+
 unsigned SourceLocation::getHashValue() const {
   return llvm::DenseMapInfo::getHashValue(ID);
 }

diff  --git a/clang/lib/Tooling/Refactoring/Rename/SymbolOccurrences.cpp 
b/clang/lib/Tooling/Refactoring/Rename/SymbolOccurrences.cpp
index 9e69d37e81ad..762864c953d8 100644
--- a/clang/lib/Tooling/Refactoring/Rename/SymbolOccurrences.cpp
+++ b/clang/lib/Tooling/Refactoring/Rename/SymbolOccurrences.cpp
@@ -21,13 +21,12 @@ SymbolOccurrence::SymbolOccurrence(const SymbolName &Name, 
OccurrenceKind Kind,
  "mismatching number of locations and lengths");
   assert(!Locations.empty() && "no locations");
   if (Locations.size() == 1) {
-RangeOrNumRanges = SourceRange(
+new (&SingleRange) SourceRange(
 Locations[0], Locations[0].getLocWithOffset(NamePieces[0].size()));
 return;
   }
   MultipleRanges = std::make_unique(Locations.size());
-  RangeOrNumRanges.setBegin(
-  SourceLocation::getFromRawEncoding(Locations.size()));
+  NumRanges = Locations.size();
   for (const auto &Loc : llvm::enumerate(Locations)) {
 MultipleRanges[Loc.index()] = SourceRange(
 Loc.value(),



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


[PATCH] D94599: [clang][Tooling] Get rid of a hack in SymbolOccurrences, NFCI

2021-01-22 Thread Mikhail Maltsev via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rGa0e30914f8c8: [clang][Tooling] Get rid of a hack in 
SymbolOccurrences, NFCI (authored by miyuki).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D94599

Files:
  clang/include/clang/Tooling/Refactoring/Rename/SymbolOccurrences.h
  clang/lib/Basic/SourceLocation.cpp
  clang/lib/Tooling/Refactoring/Rename/SymbolOccurrences.cpp


Index: clang/lib/Tooling/Refactoring/Rename/SymbolOccurrences.cpp
===
--- clang/lib/Tooling/Refactoring/Rename/SymbolOccurrences.cpp
+++ clang/lib/Tooling/Refactoring/Rename/SymbolOccurrences.cpp
@@ -21,13 +21,12 @@
  "mismatching number of locations and lengths");
   assert(!Locations.empty() && "no locations");
   if (Locations.size() == 1) {
-RangeOrNumRanges = SourceRange(
+new (&SingleRange) SourceRange(
 Locations[0], Locations[0].getLocWithOffset(NamePieces[0].size()));
 return;
   }
   MultipleRanges = std::make_unique(Locations.size());
-  RangeOrNumRanges.setBegin(
-  SourceLocation::getFromRawEncoding(Locations.size()));
+  NumRanges = Locations.size();
   for (const auto &Loc : llvm::enumerate(Locations)) {
 MultipleRanges[Loc.index()] = SourceRange(
 Loc.value(),
Index: clang/lib/Basic/SourceLocation.cpp
===
--- clang/lib/Basic/SourceLocation.cpp
+++ clang/lib/Basic/SourceLocation.cpp
@@ -42,6 +42,14 @@
 // SourceLocation
 
//===--===//
 
+static_assert(std::is_trivially_destructible::value,
+  "SourceLocation must be trivially destructible because it is "
+  "used in unions");
+
+static_assert(std::is_trivially_destructible::value,
+  "SourceRange must be trivially destructible because it is "
+  "used in unions");
+
 unsigned SourceLocation::getHashValue() const {
   return llvm::DenseMapInfo::getHashValue(ID);
 }
Index: clang/include/clang/Tooling/Refactoring/Rename/SymbolOccurrences.h
===
--- clang/include/clang/Tooling/Refactoring/Rename/SymbolOccurrences.h
+++ clang/include/clang/Tooling/Refactoring/Rename/SymbolOccurrences.h
@@ -69,17 +69,18 @@
   OccurrenceKind getKind() const { return Kind; }
 
   ArrayRef getNameRanges() const {
-if (MultipleRanges) {
-  return llvm::makeArrayRef(MultipleRanges.get(),
-RangeOrNumRanges.getBegin().getRawEncoding());
-}
-return RangeOrNumRanges;
+if (MultipleRanges)
+  return llvm::makeArrayRef(MultipleRanges.get(), NumRanges);
+return SingleRange;
   }
 
 private:
   OccurrenceKind Kind;
   std::unique_ptr MultipleRanges;
-  SourceRange RangeOrNumRanges;
+  union {
+SourceRange SingleRange;
+unsigned NumRanges;
+  };
 };
 
 using SymbolOccurrences = std::vector;


Index: clang/lib/Tooling/Refactoring/Rename/SymbolOccurrences.cpp
===
--- clang/lib/Tooling/Refactoring/Rename/SymbolOccurrences.cpp
+++ clang/lib/Tooling/Refactoring/Rename/SymbolOccurrences.cpp
@@ -21,13 +21,12 @@
  "mismatching number of locations and lengths");
   assert(!Locations.empty() && "no locations");
   if (Locations.size() == 1) {
-RangeOrNumRanges = SourceRange(
+new (&SingleRange) SourceRange(
 Locations[0], Locations[0].getLocWithOffset(NamePieces[0].size()));
 return;
   }
   MultipleRanges = std::make_unique(Locations.size());
-  RangeOrNumRanges.setBegin(
-  SourceLocation::getFromRawEncoding(Locations.size()));
+  NumRanges = Locations.size();
   for (const auto &Loc : llvm::enumerate(Locations)) {
 MultipleRanges[Loc.index()] = SourceRange(
 Loc.value(),
Index: clang/lib/Basic/SourceLocation.cpp
===
--- clang/lib/Basic/SourceLocation.cpp
+++ clang/lib/Basic/SourceLocation.cpp
@@ -42,6 +42,14 @@
 // SourceLocation
 //===--===//
 
+static_assert(std::is_trivially_destructible::value,
+  "SourceLocation must be trivially destructible because it is "
+  "used in unions");
+
+static_assert(std::is_trivially_destructible::value,
+  "SourceRange must be trivially destructible because it is "
+  "used in unions");
+
 unsigned SourceLocation::getHashValue() const {
   return llvm::DenseMapInfo::getHashValue(ID);
 }
Index: clang/include/clang/Tooling/Refactoring/Rename/SymbolOccurrences.h
===
--- clang/include/clang/Tooling/Refactoring/Rename/SymbolOccurrences.h
+++ clang/include/clang/Tooling/Refactoring/Rename/SymbolOccurre

[PATCH] D95225: [clang][cli] NFC: Pass CC1Option explicitly to BoolOption

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

When `Bool{F,G}Option` were introduced, they were designed after the existing 
`Opt{In,Out}FFlag` in that they implied `CC1Option` for the `ChangedBy` flag.

This means less typing, but can be misleading in situations when the `ResetBy` 
has explicit `CC1Option` and `ChangedBy` doesn't.

This patch stops implicitly putting `CC1Option` to `ChangedBy` flag.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D95225

Files:
  clang/include/clang/Driver/Options.td

Index: clang/include/clang/Driver/Options.td
===
--- clang/include/clang/Driver/Options.td
+++ clang/include/clang/Driver/Options.td
@@ -473,38 +473,23 @@
  changed_by_flag, reset_by_flag, flag_suffix>;
 }
 
-/// Creates a BoolOption with the changing available on the CC1 command line.
-multiclass BoolCC1Option> {
-  defvar changed_by_cc1
-= ChangedBy;
-
-  defm NAME : BoolOption;
-}
-
-/// Creates a BoolOption where both of the flags are prefixed with "f", are in
-/// the Group, and the changing flag is also available on the CC1
-/// command line.
+/// Creates a BoolOption where both of the flags are prefixed with "f" and have
+/// the Group.
 multiclass BoolFOption> {
-  defm NAME : BoolCC1Option<"f", flag_base, kpm, defaults_to, changed_by,
-reset_by, both>,
+  defm NAME : BoolOption<"f", flag_base, kpm, defaults_to, changed_by, reset_by,
+ both>,
   Group;
 }
 
-// Creates a BoolOption where both of the flags are prefixed with "g", are in
-// the Group, and the changing flag is also available on the CC1
-// command line.
+// Creates a BoolOption where both of the flags are prefixed with "g" and have
+// the Group.
 multiclass BoolGOption> {
-  defm NAME : BoolCC1Option<"g", flag_base, kpm, defaults_to, changed_by,
-reset_by, both>,
+  defm NAME : BoolOption<"g", flag_base, kpm, defaults_to, changed_by, reset_by,
+ both>,
   Group;
 }
 
@@ -951,7 +936,7 @@
   " approximate transcendental functions">;
 defm gpu_rdc : BoolFOption<"gpu-rdc",
   LangOpts<"GPURelocatableDeviceCode">, DefaultsToFalse,
-  ChangedBy,
+  ChangedBy,
   ResetBy>;
 def : Flag<["-"], "fcuda-rdc">, Alias;
 def : Flag<["-"], "fno-cuda-rdc">, Alias;
@@ -971,17 +956,17 @@
   Group, Flags<[NoArgumentUnused, HelpHidden]>;
 defm hip_new_launch_api : BoolFOption<"hip-new-launch-api",
   LangOpts<"HIPUseNewLaunchAPI">, DefaultsToFalse,
-  ChangedBy, ResetBy,
+  ChangedBy, ResetBy,
   BothFlags<[], " new kernel launching API for HIP">>;
 defm gpu_allow_device_init : OptInFFlag<"gpu-allow-device-init",
   "Allow", "Don't allow", " device side init function in HIP">;
 defm gpu_defer_diag : BoolFOption<"gpu-defer-diag",
   LangOpts<"GPUDeferDiag">, DefaultsToFalse,
-  ChangedBy, ResetBy,
+  ChangedBy, ResetBy,
   BothFlags<[], " host/device related diagnostic messages for CUDA/HIP">>;
 defm gpu_exclude_wrong_side_overloads : BoolFOption<"gpu-exclude-wrong-side-overloads",
   LangOpts<"GPUExcludeWrongSideOverloads">, DefaultsToFalse,
-  ChangedBy,
+  ChangedBy,
   ResetBy,
   BothFlags<[HelpHidden], " in overloading resolution for CUDA/HIP">>;
 def gpu_max_threads_per_block_EQ : Joined<["--"], "gpu-max-threads-per-block=">,
@@ -1043,14 +1028,14 @@
 def fno_PIE : Flag<["-"], "fno-PIE">, Group;
 defm access_control : BoolFOption<"access-control",
   LangOpts<"AccessControl">, DefaultsToTrue,
-  ChangedBy,
+  ChangedBy,
   ResetBy>;
 def falign_functions : Flag<["-"], "falign-functions">, Group;
 def falign_functions_EQ : Joined<["-"], "falign-functions=">, Group;
 def fno_align_functions: Flag<["-"], "fno-align-functions">, Group;
 defm allow_editor_placeholders : BoolFOption<"allow-editor-placeholders",
   LangOpts<"AllowEditorPlaceholders">, DefaultsToFalse,
-  ChangedBy,
+  ChangedBy,
   ResetBy>;
 def fallow_unsupported : Flag<["-"], "fallow-unsupported">, Group;
 def fapple_kext : Flag<["-"], "fapple-kext">, Group, Flags<[CC1Option]>,
@@ -1058,7 +1043,7 @@
   MarshallingInfoFlag>;
 defm apple_pragma_pack : BoolFOption<"apple-pragma-pack",
   LangOpts<"ApplePragmaPack">, DefaultsToFalse,
-  ChangedBy,
+  ChangedBy,
   ResetBy>;
 def fxl_pragma_pack : Flag<["-"], "fxl-pragma-pack">, Group, Flags<[CC1Option]>,
   HelpText<"Enable IBM XL #pragma pack handling">;
@@ -1106,7 +1091,7 @@
   HelpText<"Embed placeholder LLVM IR data as a marker">;
 defm gnu_inline_asm : BoolFOption<"gnu-inline-asm",
   LangOpts<"GNUAsm">, DefaultsToTrue,
-  ChangedBy, ResetBy>;
+  ChangedBy, ResetBy>;
 
 def fprofile_sample_use : Flag<["-"], "fprofile-sample-use">, Group,
 Flags<[CoreOption]>;
@@ -1145,7 +1130,7 @@
 Alias;
 defm d

[clang-tools-extra] 7388c34 - [clangd][SwapIndex] ensure that the old index is alive while we are using it via the function returned by `SwapIndex::indexedFiles()` call

2021-01-22 Thread Aleksandr Platonov via cfe-commits

Author: Aleksandr Platonov
Date: 2021-01-22T16:26:39+03:00
New Revision: 7388c34685954862e5f1fa4734f42f7087e697a2

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

LOG: [clangd][SwapIndex] ensure that the old index is alive while we are using 
it via the function returned by `SwapIndex::indexedFiles()` call

Without this patch the old index could be freed, but there still could be tries 
to access it via the function returned by `SwapIndex::indexedFiles()` call.
This leads to hard to reproduce clangd crashes at code completion.
This patch keeps the old index alive until the function returned by 
`SwapIndex::indexedFiles()` call is alive.

Reviewed By: sammccall

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

Added: 


Modified: 
clang-tools-extra/clangd/index/Index.cpp
clang-tools-extra/clangd/index/Merge.cpp

Removed: 




diff  --git a/clang-tools-extra/clangd/index/Index.cpp 
b/clang-tools-extra/clangd/index/Index.cpp
index 5da06f36ffe4..1b085140b4ff 100644
--- a/clang-tools-extra/clangd/index/Index.cpp
+++ b/clang-tools-extra/clangd/index/Index.cpp
@@ -78,7 +78,13 @@ void SwapIndex::relations(
 
 llvm::unique_function
 SwapIndex::indexedFiles() const {
-  return snapshot()->indexedFiles();
+  // The index snapshot should outlive this method return value.
+  auto SnapShot = snapshot();
+  auto IndexedFiles = SnapShot->indexedFiles();
+  return [KeepAlive{std::move(SnapShot)},
+  IndexContainsFile{std::move(IndexedFiles)}](llvm::StringRef File) {
+return IndexContainsFile(File);
+  };
 }
 
 size_t SwapIndex::estimateMemoryUsage() const {

diff  --git a/clang-tools-extra/clangd/index/Merge.cpp 
b/clang-tools-extra/clangd/index/Merge.cpp
index 0dd0d9e01518..6f369ed2edcf 100644
--- a/clang-tools-extra/clangd/index/Merge.cpp
+++ b/clang-tools-extra/clangd/index/Merge.cpp
@@ -44,21 +44,23 @@ bool MergedIndex::fuzzyFind(
   SymbolSlab Dyn = std::move(DynB).build();
 
   llvm::DenseSet SeenDynamicSymbols;
-  auto DynamicContainsFile = Dynamic->indexedFiles();
-  More |= Static->fuzzyFind(Req, [&](const Symbol &S) {
-// We expect the definition to see the canonical declaration, so it seems
-// to be enough to check only the definition if it exists.
-if (DynamicContainsFile(S.Definition ? S.Definition.FileURI
- : S.CanonicalDeclaration.FileURI))
-  return;
-auto DynS = Dyn.find(S.ID);
-++StaticCount;
-if (DynS == Dyn.end())
-  return Callback(S);
-++MergedCount;
-SeenDynamicSymbols.insert(S.ID);
-Callback(mergeSymbol(*DynS, S));
-  });
+  {
+auto DynamicContainsFile = Dynamic->indexedFiles();
+More |= Static->fuzzyFind(Req, [&](const Symbol &S) {
+  // We expect the definition to see the canonical declaration, so it seems
+  // to be enough to check only the definition if it exists.
+  if (DynamicContainsFile(S.Definition ? S.Definition.FileURI
+   : S.CanonicalDeclaration.FileURI))
+return;
+  auto DynS = Dyn.find(S.ID);
+  ++StaticCount;
+  if (DynS == Dyn.end())
+return Callback(S);
+  ++MergedCount;
+  SeenDynamicSymbols.insert(S.ID);
+  Callback(mergeSymbol(*DynS, S));
+});
+  }
   SPAN_ATTACH(Tracer, "dynamic", DynamicCount);
   SPAN_ATTACH(Tracer, "static", StaticCount);
   SPAN_ATTACH(Tracer, "merged", MergedCount);
@@ -77,20 +79,22 @@ void MergedIndex::lookup(
   Dynamic->lookup(Req, [&](const Symbol &S) { B.insert(S); });
 
   auto RemainingIDs = Req.IDs;
-  auto DynamicContainsFile = Dynamic->indexedFiles();
-  Static->lookup(Req, [&](const Symbol &S) {
-// We expect the definition to see the canonical declaration, so it seems
-// to be enough to check only the definition if it exists.
-if (DynamicContainsFile(S.Definition ? S.Definition.FileURI
- : S.CanonicalDeclaration.FileURI))
-  return;
-const Symbol *Sym = B.find(S.ID);
-RemainingIDs.erase(S.ID);
-if (!Sym)
-  Callback(S);
-else
-  Callback(mergeSymbol(*Sym, S));
-  });
+  {
+auto DynamicContainsFile = Dynamic->indexedFiles();
+Static->lookup(Req, [&](const Symbol &S) {
+  // We expect the definition to see the canonical declaration, so it seems
+  // to be enough to check only the definition if it exists.
+  if (DynamicContainsFile(S.Definition ? S.Definition.FileURI
+   : S.CanonicalDeclaration.FileURI))
+return;
+  const Symbol *Sym = B.find(S.ID);
+  RemainingIDs.erase(S.ID);
+  if (!Sym)
+Callback(S);
+  else
+Callback(mergeSymbol(*Sym, S));
+});
+  }
   for (const auto &ID : RemainingIDs)
 if (const Symbol *Sym = B.fi

[PATCH] D95206: [clangd][SwapIndex] ensure that the old index is alive while we are using it via the function returned by `SwapIndex::indexedFiles()` call

2021-01-22 Thread Aleksandr Platonov via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG7388c3468595: [clangd][SwapIndex] ensure that the old index 
is alive while we are using it… (authored by ArcsinX).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D95206

Files:
  clang-tools-extra/clangd/index/Index.cpp
  clang-tools-extra/clangd/index/Merge.cpp


Index: clang-tools-extra/clangd/index/Merge.cpp
===
--- clang-tools-extra/clangd/index/Merge.cpp
+++ clang-tools-extra/clangd/index/Merge.cpp
@@ -44,21 +44,23 @@
   SymbolSlab Dyn = std::move(DynB).build();
 
   llvm::DenseSet SeenDynamicSymbols;
-  auto DynamicContainsFile = Dynamic->indexedFiles();
-  More |= Static->fuzzyFind(Req, [&](const Symbol &S) {
-// We expect the definition to see the canonical declaration, so it seems
-// to be enough to check only the definition if it exists.
-if (DynamicContainsFile(S.Definition ? S.Definition.FileURI
- : S.CanonicalDeclaration.FileURI))
-  return;
-auto DynS = Dyn.find(S.ID);
-++StaticCount;
-if (DynS == Dyn.end())
-  return Callback(S);
-++MergedCount;
-SeenDynamicSymbols.insert(S.ID);
-Callback(mergeSymbol(*DynS, S));
-  });
+  {
+auto DynamicContainsFile = Dynamic->indexedFiles();
+More |= Static->fuzzyFind(Req, [&](const Symbol &S) {
+  // We expect the definition to see the canonical declaration, so it seems
+  // to be enough to check only the definition if it exists.
+  if (DynamicContainsFile(S.Definition ? S.Definition.FileURI
+   : S.CanonicalDeclaration.FileURI))
+return;
+  auto DynS = Dyn.find(S.ID);
+  ++StaticCount;
+  if (DynS == Dyn.end())
+return Callback(S);
+  ++MergedCount;
+  SeenDynamicSymbols.insert(S.ID);
+  Callback(mergeSymbol(*DynS, S));
+});
+  }
   SPAN_ATTACH(Tracer, "dynamic", DynamicCount);
   SPAN_ATTACH(Tracer, "static", StaticCount);
   SPAN_ATTACH(Tracer, "merged", MergedCount);
@@ -77,20 +79,22 @@
   Dynamic->lookup(Req, [&](const Symbol &S) { B.insert(S); });
 
   auto RemainingIDs = Req.IDs;
-  auto DynamicContainsFile = Dynamic->indexedFiles();
-  Static->lookup(Req, [&](const Symbol &S) {
-// We expect the definition to see the canonical declaration, so it seems
-// to be enough to check only the definition if it exists.
-if (DynamicContainsFile(S.Definition ? S.Definition.FileURI
- : S.CanonicalDeclaration.FileURI))
-  return;
-const Symbol *Sym = B.find(S.ID);
-RemainingIDs.erase(S.ID);
-if (!Sym)
-  Callback(S);
-else
-  Callback(mergeSymbol(*Sym, S));
-  });
+  {
+auto DynamicContainsFile = Dynamic->indexedFiles();
+Static->lookup(Req, [&](const Symbol &S) {
+  // We expect the definition to see the canonical declaration, so it seems
+  // to be enough to check only the definition if it exists.
+  if (DynamicContainsFile(S.Definition ? S.Definition.FileURI
+   : S.CanonicalDeclaration.FileURI))
+return;
+  const Symbol *Sym = B.find(S.ID);
+  RemainingIDs.erase(S.ID);
+  if (!Sym)
+Callback(S);
+  else
+Callback(mergeSymbol(*Sym, S));
+});
+  }
   for (const auto &ID : RemainingIDs)
 if (const Symbol *Sym = B.find(ID))
   Callback(*Sym);
Index: clang-tools-extra/clangd/index/Index.cpp
===
--- clang-tools-extra/clangd/index/Index.cpp
+++ clang-tools-extra/clangd/index/Index.cpp
@@ -78,7 +78,13 @@
 
 llvm::unique_function
 SwapIndex::indexedFiles() const {
-  return snapshot()->indexedFiles();
+  // The index snapshot should outlive this method return value.
+  auto SnapShot = snapshot();
+  auto IndexedFiles = SnapShot->indexedFiles();
+  return [KeepAlive{std::move(SnapShot)},
+  IndexContainsFile{std::move(IndexedFiles)}](llvm::StringRef File) {
+return IndexContainsFile(File);
+  };
 }
 
 size_t SwapIndex::estimateMemoryUsage() const {


Index: clang-tools-extra/clangd/index/Merge.cpp
===
--- clang-tools-extra/clangd/index/Merge.cpp
+++ clang-tools-extra/clangd/index/Merge.cpp
@@ -44,21 +44,23 @@
   SymbolSlab Dyn = std::move(DynB).build();
 
   llvm::DenseSet SeenDynamicSymbols;
-  auto DynamicContainsFile = Dynamic->indexedFiles();
-  More |= Static->fuzzyFind(Req, [&](const Symbol &S) {
-// We expect the definition to see the canonical declaration, so it seems
-// to be enough to check only the definition if it exists.
-if (DynamicContainsFile(S.Definition ? S.Definition.FileURI
- : S.CanonicalDeclaration.FileURI))
-  return;
-auto DynS = Dyn

[clang-tools-extra] 60cd75a - [clangd] Inject context provider rather than config into ClangdServer. NFC

2021-01-22 Thread Sam McCall via cfe-commits

Author: Sam McCall
Date: 2021-01-22T14:34:30+01:00
New Revision: 60cd75a098d4f18d9c8903ddcb466b4e7deb0580

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

LOG: [clangd] Inject context provider rather than config into ClangdServer. NFC

This is a step towards allowing CDB behavior to being configurable.

Previously ClangdServer itself created the configs and installed them into
contexts. This was natural as it knows how to deal with resulting diagnostics.

However this prevents config being used in CDB, which must be created before
ClangdServer. So we extract the context provider (config loader) as a separate
object, which publishes diagnostics to a ClangdServer::Callbacks itself.

Now initialization looks like:
 - First create the config::Provider
 - Then create the ClangdLSPServer, passing config provider
 - Next, create the context provider, passing config provider + diagnostic 
callbacks
 - now create the CDB, passing context provider
 - finally create ClangdServer, passing CDB, context provider, and diagnostic 
callbacks

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

Added: 


Modified: 
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/unittests/ClangdTests.cpp

Removed: 




diff  --git a/clang-tools-extra/clangd/ClangdLSPServer.cpp 
b/clang-tools-extra/clangd/ClangdLSPServer.cpp
index 4e5d9f8bf0fa..24d3a3509ca8 100644
--- a/clang-tools-extra/clangd/ClangdLSPServer.cpp
+++ b/clang-tools-extra/clangd/ClangdLSPServer.cpp
@@ -1469,6 +1469,12 @@ ClangdLSPServer::ClangdLSPServer(class Transport &Transp,
   MsgHandler(new MessageHandler(*this)), TFS(TFS),
   SupportedSymbolKinds(defaultSymbolKinds()),
   SupportedCompletionItemKinds(defaultCompletionItemKinds()), Opts(Opts) {
+  if (Opts.ConfigProvider) {
+assert(!Opts.ContextProvider &&
+   "Only one of ConfigProvider and ContextProvider allowed!");
+this->Opts.ContextProvider = ClangdServer::createConfiguredContextProvider(
+Opts.ConfigProvider, this);
+  }
 
   // clang-format off
   MsgHandler->bind("initialize", &ClangdLSPServer::onInitialize);

diff  --git a/clang-tools-extra/clangd/ClangdLSPServer.h 
b/clang-tools-extra/clangd/ClangdLSPServer.h
index a41bc5666af3..3a46bd7b1bea 100644
--- a/clang-tools-extra/clangd/ClangdLSPServer.h
+++ b/clang-tools-extra/clangd/ClangdLSPServer.h
@@ -41,6 +41,8 @@ class SymbolIndex;
 class ClangdLSPServer : private ClangdServer::Callbacks {
 public:
   struct Options : ClangdServer::Options {
+/// Supplies configuration (overrides ClangdServer::ContextProvider).
+config::Provider *ConfigProvider = nullptr;
 /// Look for compilation databases, rather than using compile commands
 /// set via LSP (extensions) only.
 bool UseDirBasedCDB = true;

diff  --git a/clang-tools-extra/clangd/ClangdServer.cpp 
b/clang-tools-extra/clangd/ClangdServer.cpp
index 32e08e688f44..4f9ea0499077 100644
--- a/clang-tools-extra/clangd/ClangdServer.cpp
+++ b/clang-tools-extra/clangd/ClangdServer.cpp
@@ -133,14 +133,14 @@ ClangdServer::Options::operator TUScheduler::Options() 
const {
   Opts.StorePreamblesInMemory = StorePreamblesInMemory;
   Opts.UpdateDebounce = UpdateDebounce;
   Opts.AsyncPreambleBuilds = AsyncPreambleBuilds;
+  Opts.ContextProvider = ContextProvider;
   return Opts;
 }
 
 ClangdServer::ClangdServer(const GlobalCompilationDatabase &CDB,
const ThreadsafeFS &TFS, const Options &Opts,
Callbacks *Callbacks)
-: ConfigProvider(Opts.ConfigProvider), CDB(CDB), TFS(TFS),
-  ServerCallbacks(Callbacks),
+: CDB(CDB), TFS(TFS),
   DynamicIdx(Opts.BuildDynamicSymbolIndex
  ? new FileIndex(Opts.HeavyweightDynamicSymbolIndex,
  Opts.CollectMainFileRefs)
@@ -153,14 +153,7 @@ ClangdServer::ClangdServer(const GlobalCompilationDatabase 
&CDB,
   // FIXME(ioeric): this can be slow and we may be able to index on less
   // critical paths.
   WorkScheduler(
-  CDB,
-  [&, this] {
-TUScheduler::Options O(Opts);
-O.ContextProvider = [this](PathRef P) {
-  return createProcessingContext(P);
-};
-return O;
-  }(),
+  CDB, TUScheduler::Options(Opts),
   std::make_unique(
   DynamicIdx.get(), Callbacks, Opts.TheiaSemanticHighlighting)) {
   // Adds an index to the stack, at higher priority than existing indexes.
@@ -181,9 +174,7 @@ ClangdServer::ClangdServer(const GlobalCompilationDatabase 
&CDB,
   if (Callbacks)
 Callbacks->onBackground

[PATCH] D95087: [clangd] Inject context provider rather than config into ClangdServer. NFC

2021-01-22 Thread Sam McCall via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG60cd75a098d4: [clangd] Inject context provider rather than 
config into ClangdServer. NFC (authored by sammccall).

Changed prior to commit:
  https://reviews.llvm.org/D95087?vs=317995&id=318498#toc

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D95087

Files:
  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/unittests/ClangdTests.cpp

Index: clang-tools-extra/clangd/unittests/ClangdTests.cpp
===
--- clang-tools-extra/clangd/unittests/ClangdTests.cpp
+++ clang-tools-extra/clangd/unittests/ClangdTests.cpp
@@ -348,7 +348,8 @@
   } CfgProvider;
 
   auto Opts = ClangdServer::optsForTest();
-  Opts.ConfigProvider = &CfgProvider;
+  Opts.ContextProvider =
+  ClangdServer::createConfiguredContextProvider(&CfgProvider, nullptr);
   OverlayCDB CDB(/*Base=*/nullptr, /*FallbackFlags=*/{},
  tooling::ArgumentsAdjuster(CommandMangler::forTests()));
   MockFS FS;
Index: clang-tools-extra/clangd/ClangdServer.h
===
--- clang-tools-extra/clangd/ClangdServer.h
+++ clang-tools-extra/clangd/ClangdServer.h
@@ -80,6 +80,12 @@
 virtual void
 onBackgroundIndexProgress(const BackgroundQueue::Stats &Stats) {}
   };
+  /// Creates a context provider that loads and installs config.
+  /// Errors in loading config are reported as diagnostics via Callbacks.
+  /// (This is typically used as ClangdServer::Options::ContextProvider).
+  static std::function
+  createConfiguredContextProvider(const config::Provider *Provider,
+  ClangdServer::Callbacks *);
 
   struct Options {
 /// To process requests asynchronously, ClangdServer spawns worker threads.
@@ -111,8 +117,16 @@
 /// If set, use this index to augment code completion results.
 SymbolIndex *StaticIndex = nullptr;
 
-/// If set, queried to obtain the configuration to handle each request.
-config::Provider *ConfigProvider = nullptr;
+/// If set, queried to derive a processing context for some work.
+/// Usually used to inject Config (see createConfiguredContextProvider).
+///
+/// When the provider is called, the active context will be that inherited
+/// from the request (e.g. addDocument()), or from the ClangdServer
+/// constructor if there is no such request (e.g. background indexing).
+///
+/// The path is an absolute path of the file being processed.
+/// If there is no particular file (e.g. project loading) then it is empty.
+std::function ContextProvider;
 
 /// The Options provider to use when running clang-tidy. If null, clang-tidy
 /// checks will be disabled.
@@ -343,19 +357,8 @@
   ArrayRef Ranges,
   Callback CB);
 
-  /// Derives a context for a task processing the specified source file.
-  /// This includes the current configuration (see Options::ConfigProvider).
-  /// The empty string means no particular file is the target.
-  /// Rather than called by each feature, this is exposed to the components
-  /// that control worker threads, like TUScheduler and BackgroundIndex.
-  /// This means it's OK to do some IO here, and it cuts across all features.
-  Context createProcessingContext(PathRef) const;
-  config::Provider *ConfigProvider = nullptr;
-
   const GlobalCompilationDatabase &CDB;
   const ThreadsafeFS &TFS;
-  Callbacks *ServerCallbacks = nullptr;
-  mutable std::mutex ConfigDiagnosticsMu;
 
   Path ResourceDir;
   // The index used to look up symbols. This could be:
Index: clang-tools-extra/clangd/ClangdServer.cpp
===
--- clang-tools-extra/clangd/ClangdServer.cpp
+++ clang-tools-extra/clangd/ClangdServer.cpp
@@ -133,14 +133,14 @@
   Opts.StorePreamblesInMemory = StorePreamblesInMemory;
   Opts.UpdateDebounce = UpdateDebounce;
   Opts.AsyncPreambleBuilds = AsyncPreambleBuilds;
+  Opts.ContextProvider = ContextProvider;
   return Opts;
 }
 
 ClangdServer::ClangdServer(const GlobalCompilationDatabase &CDB,
const ThreadsafeFS &TFS, const Options &Opts,
Callbacks *Callbacks)
-: ConfigProvider(Opts.ConfigProvider), CDB(CDB), TFS(TFS),
-  ServerCallbacks(Callbacks),
+: CDB(CDB), TFS(TFS),
   DynamicIdx(Opts.BuildDynamicSymbolIndex
  ? new FileIndex(Opts.HeavyweightDynamicSymbolIndex,
  Opts.CollectMainFileRefs)
@@ -153,14 +153,7 @@
   // FIXME(ioeric): this can be slow and we may be able to index on less
   // critical paths.
   WorkScheduler(
-

[PATCH] D95057: [clangd] WIP: configurable compilation database directory

2021-01-22 Thread Sam McCall via Phabricator via cfe-commits
sammccall updated this revision to Diff 318499.
sammccall added a comment.

Rebase, implement yaml bits (no tests yet)


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D95057

Files:
  clang-tools-extra/clangd/ClangdLSPServer.cpp
  clang-tools-extra/clangd/Config.h
  clang-tools-extra/clangd/ConfigCompile.cpp
  clang-tools-extra/clangd/ConfigFragment.h
  clang-tools-extra/clangd/ConfigYAML.cpp
  clang-tools-extra/clangd/GlobalCompilationDatabase.cpp
  clang-tools-extra/clangd/GlobalCompilationDatabase.h
  clang-tools-extra/clangd/unittests/ClangdLSPServerTests.cpp

Index: clang-tools-extra/clangd/unittests/ClangdLSPServerTests.cpp
===
--- clang-tools-extra/clangd/unittests/ClangdLSPServerTests.cpp
+++ clang-tools-extra/clangd/unittests/ClangdLSPServerTests.cpp
@@ -194,6 +194,33 @@
   EXPECT_EQ(From["name"], "caller1");
 }
 
+TEST_F(LSPTest, CDBConfigIntegration) {
+  auto CfgProvider =
+  config::Provider::fromAncestorRelativeYAMLFiles(".clangd", FS);
+  Opts.ConfigProvider = CfgProvider.get();
+
+  // Map bar.cpp to a different compilation database which defines FOO->BAR.
+  FS.Files[".clangd"] = R"yaml(
+If:
+  PathMatch: bar.cpp
+CompileFlags:
+  CompilationDatabase: bar
+)yaml";
+  FS.Files["bar/compile_flags.txt"] = "-DFOO=BAR";
+
+  auto &Client = start();
+  // foo.cpp gets parsed as normal.
+  Client.didOpen("foo.cpp", "int x = FOO;");
+  EXPECT_THAT(Client.diagnostics("foo.cpp"),
+  llvm::ValueIs(testing::ElementsAre(
+  DiagMessage("Use of undeclared identifier 'FOO'";
+  // bar.cpp shows the configured compile command.
+  Client.didOpen("bar.cpp", "int x = FOO;");
+  EXPECT_THAT(Client.diagnostics("bar.cpp"),
+  llvm::ValueIs(testing::ElementsAre(
+  DiagMessage("Use of undeclared identifier 'BAR'";
+}
+
 } // namespace
 } // namespace clangd
 } // namespace clang
Index: clang-tools-extra/clangd/GlobalCompilationDatabase.h
===
--- clang-tools-extra/clangd/GlobalCompilationDatabase.h
+++ clang-tools-extra/clangd/GlobalCompilationDatabase.h
@@ -103,8 +103,10 @@
 // (This is more expensive to check frequently, as we check many locations).
 std::chrono::steady_clock::duration RevalidateMissingAfter =
 std::chrono::seconds(30);
+// Used to provide per-file configuration.
+std::function ContextProvider;
 // Only look for a compilation database in this one fixed directory.
-llvm::Optional CompileCommandsDir;
+llvm::Optional CompileCommandsDir; // XXX
   };
 
   DirectoryBasedGlobalCompilationDatabase(const Options &Opts);
@@ -126,14 +128,9 @@
   Options Opts;
 
   class DirectoryCache;
-  // If there's an explicit CompileCommandsDir, cache of the CDB found there.
-  mutable std::unique_ptr OnlyDirCache;
-
   // Keyed by possibly-case-folded directory path.
   // We can hand out pointers as they're stable and entries are never removed.
-  // Empty if CompileCommandsDir is given (OnlyDirCache is used instead).
   mutable llvm::StringMap DirCaches;
-  // DirCaches access must be locked (unlike OnlyDirCache, which is threadsafe).
   mutable std::mutex DirCachesMutex;
 
   std::vector
Index: clang-tools-extra/clangd/GlobalCompilationDatabase.cpp
===
--- clang-tools-extra/clangd/GlobalCompilationDatabase.cpp
+++ clang-tools-extra/clangd/GlobalCompilationDatabase.cpp
@@ -7,6 +7,7 @@
 //===--===//
 
 #include "GlobalCompilationDatabase.h"
+#include "Config.h"
 #include "FS.h"
 #include "SourceCode.h"
 #include "support/Logger.h"
@@ -20,6 +21,7 @@
 #include "clang/Tooling/JSONCompilationDatabase.h"
 #include "llvm/ADT/None.h"
 #include "llvm/ADT/Optional.h"
+#include "llvm/ADT/PointerIntPair.h"
 #include "llvm/ADT/STLExtras.h"
 #include "llvm/ADT/ScopeExit.h"
 #include "llvm/ADT/SmallString.h"
@@ -362,8 +364,10 @@
 DirectoryBasedGlobalCompilationDatabase::
 DirectoryBasedGlobalCompilationDatabase(const Options &Opts)
 : Opts(Opts), Broadcaster(std::make_unique(*this)) {
-  if (Opts.CompileCommandsDir)
-OnlyDirCache = std::make_unique(*Opts.CompileCommandsDir);
+  if (!this->Opts.ContextProvider)
+this->Opts.ContextProvider = [](llvm::StringRef) {
+  return Context::current().clone();
+};
 }
 
 DirectoryBasedGlobalCompilationDatabase::
@@ -405,14 +409,6 @@
 #endif
 }
 
-static bool pathEqual(PathRef A, PathRef B) {
-#if defined(_WIN32) || defined(__APPLE__)
-  return A.equals_lower(B);
-#else
-  return A == B;
-#endif
-}
-
 std::vector
 DirectoryBasedGlobalCompilationDatabase::getDirectoryCaches(
 llvm::ArrayRef Dirs) const {
@@ -441,31 +437,42 @@
   assert(llvm::sys::path::is_absolute(Request.FileName) &&
  "path must be absolute");
 
+ 

[PATCH] D85528: [analyzer] Fix cast evaluation on scoped enums in ExprEngine

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

The patch doesn't seem to affect the reports.
It only introduced 3 new reports during the analysis of clang + clang-tidy.
The analysis times indeed increased slightly, ~~ +3%.

Overall, I think it's a valuable patch, which resolves crashes when the Z3 
refutation enabled.
However, I can evaluate this patch on more C++ projects if you are still not 
convinced.

---

You can inspect my evaluation results at:
https://codechecker-demo.eastus.cloudapp.azure.com/Default/runs?run=D85528-fix-scoped-enum-cast-evaluation&sort-by=name&sort-desc=false


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D85528

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


[PATCH] D94293: [clangd] automatically index STL

2021-01-22 Thread Christian Kühnel via Phabricator via cfe-commits
kuhnel abandoned this revision.
kuhnel added a comment.

thx for the review and feedback!

I guess I'll re-design the feature and add a new indexing layer instead. 
However that might take a while, so I'll abandon this revision and start a new 
one later on.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D94293

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


[PATCH] D94986: Remove requirement for -maltivec to be used when using -mabi=vec-extabi or -mabi=vec-default when not using vector code

2021-01-22 Thread Hubert Tong via Phabricator via cfe-commits
hubert.reinterpretcast added inline comments.



Comment at: clang/lib/Driver/ToolChains/Clang.cpp:4671
+  D.Diag(diag::err_aix_default_altivec_abi);
   }
 

Just to confirm, because the patch description confuses me a bit on this: The 
intent is to not complain on `-mabi=vec-default` or `-mabi=vec-extabi` at all 
on AIX, right? That is, `-mabi=vec-extabi` is one way to prepare non-vector 
code for eventual compatibility purposes. @ZarkoCA, I suggest updating the 
patch description (and eventual commit message).


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D94986

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


[PATCH] D94814: [HIP] Support `__managed__` attribute

2021-01-22 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman accepted this revision.
aaron.ballman added a comment.

The attribute parts LGTM aside from some small nits.




Comment at: clang/include/clang/Basic/DiagnosticSemaKinds.td:8245
 "%select{__device__|__global__|__host__|__host__ __device__}0 functions">;
-def err_cuda_nonstatic_constdev: Error<"__constant__ and __device__ are not 
allowed on non-static local variables">;
+def err_cuda_nonstatic_constdev: Error<"__constant__, __device__, and 
__managed__ are not allowed on non-static local variables">;
 def err_cuda_ovl_target : Error<

Since we're modifying this line anyway, can you wrap it for the 80-col limit?



Comment at: clang/test/SemaCUDA/managed-var.cu:45
+__managed__ A a;
+// expected-error@-1 {{dynamic initialization is not supported for __device__, 
__constant__, __shared__, and __managed__ variables}}

I think you're missing tests that check that the new managed attribute accepts 
no arguments and that it doesn't apply to things other than variables (like a 
function declaration).


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

https://reviews.llvm.org/D94814

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


[PATCH] D94786: [clang][ASTImporter] Add support for importing CXXFoldExpr.

2021-01-22 Thread Balázs Kéri via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG98a8344895a8: [clang][ASTImporter] Add support for importing 
CXXFoldExpr. (authored by balazske).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D94786

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


Index: clang/unittests/AST/ASTImporterTest.cpp
===
--- clang/unittests/AST/ASTImporterTest.cpp
+++ clang/unittests/AST/ASTImporterTest.cpp
@@ -639,6 +639,38 @@
   hasUnqualifiedDesugaredType(constantArrayType(hasSize(7));
 }
 
+const internal::VariadicDynCastAllOfMatcher cxxFoldExpr;
+
+AST_MATCHER_P(CXXFoldExpr, hasOperator, BinaryOperatorKind, Op) {
+  return Node.getOperator() == Op;
+}
+AST_MATCHER(CXXFoldExpr, hasInit) { return Node.getInit(); }
+AST_MATCHER(CXXFoldExpr, isRightFold) { return Node.isRightFold(); }
+AST_MATCHER(CXXFoldExpr, isLeftFold) { return Node.isLeftFold(); }
+
+TEST_P(ImportExpr, ImportCXXFoldExpr) {
+  auto Match1 =
+  cxxFoldExpr(hasOperator(BO_Add), isLeftFold(), unless(hasInit()));
+  auto Match2 = cxxFoldExpr(hasOperator(BO_Sub), isLeftFold(), hasInit());
+  auto Match3 =
+  cxxFoldExpr(hasOperator(BO_Mul), isRightFold(), unless(hasInit()));
+  auto Match4 = cxxFoldExpr(hasOperator(BO_Div), isRightFold(), hasInit());
+
+  MatchVerifier Verifier;
+  testImport("template "
+ "void declToImport(Ts... args) {"
+ "  const int i1 = (... + args);"
+ "  const int i2 = (1 - ... - args);"
+ "  const int i3 = (args * ...);"
+ "  const int i4 = (args / ... / 1);"
+ "};"
+ "void g() { declToImport(1, 2, 3, 4, 5); }",
+ Lang_CXX17, "", Lang_CXX17, Verifier,
+ functionTemplateDecl(hasDescendant(Match1), hasDescendant(Match2),
+  hasDescendant(Match3),
+  hasDescendant(Match4)));
+}
+
 /// \brief Matches __builtin_types_compatible_p:
 /// GNU extension to check equivalent types
 /// Given
Index: clang/lib/AST/ASTImporter.cpp
===
--- clang/lib/AST/ASTImporter.cpp
+++ clang/lib/AST/ASTImporter.cpp
@@ -644,6 +644,7 @@
 ExpectedStmt 
VisitSubstNonTypeTemplateParmExpr(SubstNonTypeTemplateParmExpr *E);
 ExpectedStmt VisitTypeTraitExpr(TypeTraitExpr *E);
 ExpectedStmt VisitCXXTypeidExpr(CXXTypeidExpr *E);
+ExpectedStmt VisitCXXFoldExpr(CXXFoldExpr *E);
 
 template
 Error ImportArrayChecked(IIter Ibegin, IIter Iend, OIter Obegin) {
@@ -8011,6 +8012,25 @@
   *ToTypeOrErr, *ToExprOperandOrErr, *ToSourceRangeOrErr);
 }
 
+ExpectedStmt ASTNodeImporter::VisitCXXFoldExpr(CXXFoldExpr *E) {
+  Error Err = Error::success();
+
+  QualType ToType = importChecked(Err, E->getType());
+  UnresolvedLookupExpr *ToCallee = importChecked(Err, E->getCallee());
+  SourceLocation ToLParenLoc = importChecked(Err, E->getLParenLoc());
+  Expr *ToLHS = importChecked(Err, E->getLHS());
+  SourceLocation ToEllipsisLoc = importChecked(Err, E->getEllipsisLoc());
+  Expr *ToRHS = importChecked(Err, E->getRHS());
+  SourceLocation ToRParenLoc = importChecked(Err, E->getRParenLoc());
+
+  if (Err)
+return std::move(Err);
+
+  return new (Importer.getToContext())
+  CXXFoldExpr(ToType, ToCallee, ToLParenLoc, ToLHS, E->getOperator(),
+  ToEllipsisLoc, ToRHS, ToRParenLoc, E->getNumExpansions());
+}
+
 Error ASTNodeImporter::ImportOverriddenMethods(CXXMethodDecl *ToMethod,
CXXMethodDecl *FromMethod) {
   Error ImportErrors = Error::success();


Index: clang/unittests/AST/ASTImporterTest.cpp
===
--- clang/unittests/AST/ASTImporterTest.cpp
+++ clang/unittests/AST/ASTImporterTest.cpp
@@ -639,6 +639,38 @@
   hasUnqualifiedDesugaredType(constantArrayType(hasSize(7));
 }
 
+const internal::VariadicDynCastAllOfMatcher cxxFoldExpr;
+
+AST_MATCHER_P(CXXFoldExpr, hasOperator, BinaryOperatorKind, Op) {
+  return Node.getOperator() == Op;
+}
+AST_MATCHER(CXXFoldExpr, hasInit) { return Node.getInit(); }
+AST_MATCHER(CXXFoldExpr, isRightFold) { return Node.isRightFold(); }
+AST_MATCHER(CXXFoldExpr, isLeftFold) { return Node.isLeftFold(); }
+
+TEST_P(ImportExpr, ImportCXXFoldExpr) {
+  auto Match1 =
+  cxxFoldExpr(hasOperator(BO_Add), isLeftFold(), unless(hasInit()));
+  auto Match2 = cxxFoldExpr(hasOperator(BO_Sub), isLeftFold(), hasInit());
+  auto Match3 =
+  cxxFoldExpr(hasOperator(BO_Mul), isRightFold(), unless(hasInit()));
+  auto Match4 = cxxFoldExpr(hasOperator(BO_Div), isRightFold(), hasInit());
+
+  MatchVerifier Verifier;
+  testImport("template "
+ "void declToImport(Ts... args) {"
+ "  const int i1 = (.

[clang] 98a8344 - [clang][ASTImporter] Add support for importing CXXFoldExpr.

2021-01-22 Thread Balázs Kéri via cfe-commits

Author: Balázs Kéri
Date: 2021-01-22T15:20:55+01:00
New Revision: 98a8344895a8e1f2cfa98b664b50fb7b864afa52

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

LOG: [clang][ASTImporter] Add support for importing CXXFoldExpr.

Reviewed By: shafik, martong

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

Added: 


Modified: 
clang/lib/AST/ASTImporter.cpp
clang/unittests/AST/ASTImporterTest.cpp

Removed: 




diff  --git a/clang/lib/AST/ASTImporter.cpp b/clang/lib/AST/ASTImporter.cpp
index 5c6aa5d3c015..085c50c0667b 100644
--- a/clang/lib/AST/ASTImporter.cpp
+++ b/clang/lib/AST/ASTImporter.cpp
@@ -644,6 +644,7 @@ namespace clang {
 ExpectedStmt 
VisitSubstNonTypeTemplateParmExpr(SubstNonTypeTemplateParmExpr *E);
 ExpectedStmt VisitTypeTraitExpr(TypeTraitExpr *E);
 ExpectedStmt VisitCXXTypeidExpr(CXXTypeidExpr *E);
+ExpectedStmt VisitCXXFoldExpr(CXXFoldExpr *E);
 
 template
 Error ImportArrayChecked(IIter Ibegin, IIter Iend, OIter Obegin) {
@@ -8011,6 +8012,25 @@ ExpectedStmt 
ASTNodeImporter::VisitCXXTypeidExpr(CXXTypeidExpr *E) {
   *ToTypeOrErr, *ToExprOperandOrErr, *ToSourceRangeOrErr);
 }
 
+ExpectedStmt ASTNodeImporter::VisitCXXFoldExpr(CXXFoldExpr *E) {
+  Error Err = Error::success();
+
+  QualType ToType = importChecked(Err, E->getType());
+  UnresolvedLookupExpr *ToCallee = importChecked(Err, E->getCallee());
+  SourceLocation ToLParenLoc = importChecked(Err, E->getLParenLoc());
+  Expr *ToLHS = importChecked(Err, E->getLHS());
+  SourceLocation ToEllipsisLoc = importChecked(Err, E->getEllipsisLoc());
+  Expr *ToRHS = importChecked(Err, E->getRHS());
+  SourceLocation ToRParenLoc = importChecked(Err, E->getRParenLoc());
+
+  if (Err)
+return std::move(Err);
+
+  return new (Importer.getToContext())
+  CXXFoldExpr(ToType, ToCallee, ToLParenLoc, ToLHS, E->getOperator(),
+  ToEllipsisLoc, ToRHS, ToRParenLoc, E->getNumExpansions());
+}
+
 Error ASTNodeImporter::ImportOverriddenMethods(CXXMethodDecl *ToMethod,
CXXMethodDecl *FromMethod) {
   Error ImportErrors = Error::success();

diff  --git a/clang/unittests/AST/ASTImporterTest.cpp 
b/clang/unittests/AST/ASTImporterTest.cpp
index 8a07a5b8e0df..193523f2fc51 100644
--- a/clang/unittests/AST/ASTImporterTest.cpp
+++ b/clang/unittests/AST/ASTImporterTest.cpp
@@ -639,6 +639,38 @@ TEST_P(ImportExpr, ImportSizeOfPackExpr) {
   hasUnqualifiedDesugaredType(constantArrayType(hasSize(7));
 }
 
+const internal::VariadicDynCastAllOfMatcher cxxFoldExpr;
+
+AST_MATCHER_P(CXXFoldExpr, hasOperator, BinaryOperatorKind, Op) {
+  return Node.getOperator() == Op;
+}
+AST_MATCHER(CXXFoldExpr, hasInit) { return Node.getInit(); }
+AST_MATCHER(CXXFoldExpr, isRightFold) { return Node.isRightFold(); }
+AST_MATCHER(CXXFoldExpr, isLeftFold) { return Node.isLeftFold(); }
+
+TEST_P(ImportExpr, ImportCXXFoldExpr) {
+  auto Match1 =
+  cxxFoldExpr(hasOperator(BO_Add), isLeftFold(), unless(hasInit()));
+  auto Match2 = cxxFoldExpr(hasOperator(BO_Sub), isLeftFold(), hasInit());
+  auto Match3 =
+  cxxFoldExpr(hasOperator(BO_Mul), isRightFold(), unless(hasInit()));
+  auto Match4 = cxxFoldExpr(hasOperator(BO_Div), isRightFold(), hasInit());
+
+  MatchVerifier Verifier;
+  testImport("template "
+ "void declToImport(Ts... args) {"
+ "  const int i1 = (... + args);"
+ "  const int i2 = (1 - ... - args);"
+ "  const int i3 = (args * ...);"
+ "  const int i4 = (args / ... / 1);"
+ "};"
+ "void g() { declToImport(1, 2, 3, 4, 5); }",
+ Lang_CXX17, "", Lang_CXX17, Verifier,
+ functionTemplateDecl(hasDescendant(Match1), hasDescendant(Match2),
+  hasDescendant(Match3),
+  hasDescendant(Match4)));
+}
+
 /// \brief Matches __builtin_types_compatible_p:
 /// GNU extension to check equivalent types
 /// Given



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


[PATCH] D95145: [clang] Fix a nullptr dereference bug on invalid code

2021-01-22 Thread Adam Czachorowski via Phabricator via cfe-commits
adamcz added inline comments.



Comment at: clang/test/SemaCXX/subst-func-type-invalid-ret-type.cpp:2
+// RUN: %clang -fsyntax-only -std=c++17 %s -Xclang -verify
+#include 
+

hokein wrote:
> A common practice is to avoid depending on STL in tests. I think we need to 
> pull out (even simplify?) std::result_of implementation if it is needed for 
> reproducing the crash.
I've noticed that pattern, but can't tell why this is. Is it documented 
somewhere?



Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D95145

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


[PATCH] D95228: Add swift_async_context parameter attribute mapping to IR equivalent

2021-01-22 Thread Tim Northover via Phabricator via cfe-commits
t.p.northover created this revision.
Herald added subscribers: dexonsmith, jdoerfert, mcrosier.
Herald added a reviewer: aaron.ballman.
t.p.northover requested review of this revision.

This adds `__attribute__((swift_async_context))` very much following the 
existing `swift_context` so that Swift's runtime implementation in C++ can 
generate functions that interact with Swift code properly. Hopefully nothing 
too controversial.

It depends on D95044  for the IR support.


https://reviews.llvm.org/D95228

Files:
  clang/include/clang/AST/Attr.h
  clang/include/clang/Basic/Attr.td
  clang/include/clang/Basic/AttrDocs.td
  clang/include/clang/Basic/Specifiers.h
  clang/lib/AST/ItaniumMangle.cpp
  clang/lib/AST/TypePrinter.cpp
  clang/lib/CodeGen/CGCall.cpp
  clang/lib/Sema/SemaDeclAttr.cpp
  clang/lib/Sema/SemaType.cpp
  clang/test/CodeGen/arm-swiftcall.c
  clang/test/Misc/pragma-attribute-supported-attributes-list.test
  clang/test/Sema/attr-swiftcall.c

Index: clang/test/Sema/attr-swiftcall.c
===
--- clang/test/Sema/attr-swiftcall.c
+++ clang/test/Sema/attr-swiftcall.c
@@ -5,6 +5,7 @@
 #define INDIRECT_RESULT __attribute__((swift_indirect_result))
 #define ERROR_RESULT __attribute__((swift_error_result))
 #define CONTEXT __attribute__((swift_context))
+#define ASYNC_CONTEXT __attribute__((swift_async_context))
 
 int notAFunction SWIFTCALL; // expected-warning {{'swiftcall' only applies to function types; type here is 'int'}}
 void variadic(int x, ...) SWIFTCALL; // expected-error {{variadic function cannot use swiftcall calling convention}}
@@ -29,3 +30,8 @@
 void context_bad_type(CONTEXT int context) SWIFTCALL; // expected-error {{'swift_context' parameter must have pointer type; type here is 'int'}}
 void context_okay(CONTEXT void *context) SWIFTCALL;
 void context_okay2(CONTEXT void *context, void *selfType, char **selfWitnessTable) SWIFTCALL;
+
+void async_context_okay_for_now(ASYNC_CONTEXT void *context);
+void async_context_bad_type(ASYNC_CONTEXT int context) SWIFTCALL; // expected-error {{'swift_async_context' parameter must have pointer type; type here is 'int'}}
+void async_context_okay(ASYNC_CONTEXT void *context) SWIFTCALL;
+void async_context_okay2(ASYNC_CONTEXT void *context, void *selfType, char **selfWitnessTable) SWIFTCALL;
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
@@ -154,6 +154,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: SwiftAsyncContext (SubjectMatchRule_variable_is_parameter)
 // CHECK-NEXT: SwiftAsyncName (SubjectMatchRule_objc_method, SubjectMatchRule_function)
 // CHECK-NEXT: SwiftBridgedTypedef (SubjectMatchRule_type_alias)
 // CHECK-NEXT: SwiftContext (SubjectMatchRule_variable_is_parameter)
Index: clang/test/CodeGen/arm-swiftcall.c
===
--- clang/test/CodeGen/arm-swiftcall.c
+++ clang/test/CodeGen/arm-swiftcall.c
@@ -6,6 +6,7 @@
 #define OUT __attribute__((swift_indirect_result))
 #define ERROR __attribute__((swift_error_result))
 #define CONTEXT __attribute__((swift_context))
+#define ASYNC_CONTEXT __attribute__((swift_async_context))
 
 /*/
 /** PARAMETER ABIS ***/
@@ -53,6 +54,9 @@
 SWIFTCALL void context_error_2(short s, CONTEXT int *self, ERROR float **error) {}
 // CHECK-LABEL: define{{.*}} void @context_error_2(i16{{.*}}, i32* swiftself{{.*}}, float** swifterror %0)
 
+SWIFTCALL void async_context_1(ASYNC_CONTEXT void *self) {}
+// CHECK-LABEL: define {{.*}} void @async_context_1(i8* swiftasync
+
 /*/
 /** LOWERING */
 /*/
Index: clang/lib/Sema/SemaType.cpp
===
--- clang/lib/Sema/SemaType.cpp
+++ clang/lib/Sema/SemaType.cpp
@@ -2791,6 +2791,10 @@
   checkForSwiftCC(paramIndex);
   continue;
 
+case ParameterABI::SwiftAsyncContext:
+  // FIXME: might want to require swiftasynccc when it exists
+  continue;
+
 // swift_error parameters must be preceded by a swift_context parameter.
 case ParameterABI::SwiftErrorResult:
   checkForSwiftCC(paramIndex);
Index: clang/lib/Sema/SemaDeclAttr.cpp
=

[PATCH] D95229: [clangd] Treat optional field type mismatches as soft failures

2021-01-22 Thread Kadir Cetinkaya via Phabricator via cfe-commits
kadircet created this revision.
kadircet added a reviewer: sammccall.
Herald added subscribers: usaxena95, arphaman.
kadircet requested review of this revision.
Herald added subscribers: cfe-commits, MaskRay, ilya-biryukov.
Herald added a project: clang.

Clangd currently throws away any protocol messages whenever an optional
field has an unexpected type. This patch changes the behaviour to treat such
fields as missing.

This enables clangd to be more tolerant against small violations to the LSP
spec.

Fixes https://github.com/clangd/vscode-clangd/issues/134


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D95229

Files:
  clang-tools-extra/clangd/Protocol.cpp

Index: clang-tools-extra/clangd/Protocol.cpp
===
--- clang-tools-extra/clangd/Protocol.cpp
+++ clang-tools-extra/clangd/Protocol.cpp
@@ -27,6 +27,19 @@
 
 namespace clang {
 namespace clangd {
+namespace {
+// Helper to ignore type mismatches on optional fields.
+template 
+bool mapOptionalOrLog(llvm::json::ObjectMapper &O, llvm::StringLiteral Prop,
+  T &Out) {
+  if (!O.mapOptional(Prop, Out)) {
+elog("Unexpected value for optional field '{0}', ignoring", Prop);
+Out = T{}; // Default-initialize Out to ensure we don't have a
+   // half-constructed object.
+  }
+  return true;
+}
+} // namespace
 
 char LSPError::ID;
 
@@ -490,7 +503,7 @@
   return O && O.map("textDocument", R.textDocument) &&
  O.map("contentChanges", R.contentChanges) &&
  O.map("wantDiagnostics", R.wantDiagnostics) &&
- O.mapOptional("forceRebuild", R.forceRebuild);
+ mapOptionalOrLog(O, "forceRebuild", R.forceRebuild);
 }
 
 bool fromJSON(const llvm::json::Value &E, FileChangeType &Out,
@@ -580,10 +593,10 @@
   llvm::json::Path P) {
   llvm::json::ObjectMapper O(Params, P);
   return O && O.map("range", R.range) && O.map("message", R.message) &&
- O.mapOptional("severity", R.severity) &&
- O.mapOptional("category", R.category) &&
- O.mapOptional("code", R.code) && O.mapOptional("source", R.source);
-  return true;
+ mapOptionalOrLog(O, "severity", R.severity) &&
+ mapOptionalOrLog(O, "category", R.category) &&
+ mapOptionalOrLog(O, "code", R.code) &&
+ mapOptionalOrLog(O, "source", R.source);
 }
 
 llvm::json::Value toJSON(const PublishDiagnosticsParams &PDP) {
@@ -817,9 +830,9 @@
   llvm::json::Path P) {
   llvm::json::ObjectMapper O(Params, P);
   int TriggerKind;
-  if (!O || !O.map("triggerKind", TriggerKind) ||
-  !O.mapOptional("triggerCharacter", R.triggerCharacter))
+  if (!O || !O.map("triggerKind", TriggerKind))
 return false;
+  mapOptionalOrLog(O, "triggerCharacter", R.triggerCharacter);
   R.triggerKind = static_cast(TriggerKind);
   return true;
 }
@@ -1121,8 +1134,9 @@
   llvm::json::ObjectMapper O(Params, P);
   if (!O)
 return true; // 'any' type in LSP.
-  return O.mapOptional("compilationDatabaseChanges",
-   S.compilationDatabaseChanges);
+  mapOptionalOrLog(O, "compilationDatabaseChanges",
+   S.compilationDatabaseChanges);
+  return true;
 }
 
 bool fromJSON(const llvm::json::Value &Params, InitializationOptions &Opts,
@@ -1133,8 +1147,8 @@
 
   return fromJSON(Params, Opts.ConfigSettings, P) &&
  O.map("compilationDatabasePath", Opts.compilationDatabasePath) &&
- O.mapOptional("fallbackFlags", Opts.fallbackFlags) &&
- O.mapOptional("clangdFileStatus", Opts.FileStatus);
+ mapOptionalOrLog(O, "fallbackFlags", Opts.fallbackFlags) &&
+ mapOptionalOrLog(O, "clangdFileStatus", Opts.FileStatus);
 }
 
 bool fromJSON(const llvm::json::Value &E, TypeHierarchyDirection &Out,
@@ -1190,10 +1204,11 @@
   return O && O.map("name", I.name) && O.map("kind", I.kind) &&
  O.map("uri", I.uri) && O.map("range", I.range) &&
  O.map("selectionRange", I.selectionRange) &&
- O.mapOptional("detail", I.detail) &&
- O.mapOptional("deprecated", I.deprecated) &&
- O.mapOptional("parents", I.parents) &&
- O.mapOptional("children", I.children) && O.mapOptional("data", I.data);
+ mapOptionalOrLog(O, "detail", I.detail) &&
+ mapOptionalOrLog(O, "deprecated", I.deprecated) &&
+ mapOptionalOrLog(O, "parents", I.parents) &&
+ mapOptionalOrLog(O, "children", I.children) &&
+ mapOptionalOrLog(O, "data", I.data);
 }
 
 bool fromJSON(const llvm::json::Value &Params,
@@ -1238,7 +1253,7 @@
   return O && O.map("name", I.name) && O.map("kind", I.kind) &&
  O.map("uri", I.uri) && O.map("range", I.range) &&
  O.map("selectionRange", I.selectionRange) &&
- O.mapOptional("data", I.data);
+ mapOptionalOrLog(O, "data", I.data);
 }
 
 bool fromJSON(const llvm::json::Value &Params,
___
cfe-commits mailing list
cfe-commits@lists.l

[PATCH] D94942: [clangd] Add tweak for implementing abstract class

2021-01-22 Thread Nathan James via Phabricator via cfe-commits
njames93 added a comment.

In D94942#2515049 , @kadircet wrote:

> Thanks this looks great, and something i've been longing for some time! But I 
> got a couple of questions about the how the interaction is designed (sorry if 
> I missed some high level discussions elsewhere, feel free to just point me in 
> that direction).

There was no high level discussions on my end. I'm just a guy on my own, who 
makes what I like, I don't even work in software. Though if there is a public 
place where people seem to discuss these I'd like to be pointed in the 
direction(discord seems to be mainly used for user support and clangd-dev has 
only had one relevant post in the last 6 months). Right now seems that GitHub 
issues and here are my best bets.

> - Why do we just declare methods, rather than defining them too (with dummy 
> bodies) ? This would allow users to move function bodies out-of-line if they 
> want to easily. Also it would enforce them to fill in the bodies, rather than 
> forgetting/skipping some of the methods. (Even more maybe we should take the 
> extra step and offer another action to declare the function inline and define 
> it out-of-line, but I think that could be done iteratively if we see the need)

I'm still unsure of the best way to go about that, Trouble with just defining 
empty methods is we will undoubtedly generate code that can't compile (without 
warnings), Mostly due to methods not having return statements or if we try and 
fix that, how do you implement the return when the function needs to return a 
reference.

> - Implementing all (pure) virtuals vs offering a code action for each 
> possible method. It is unfortunate that our existing tweak infrastructure 
> doesn't enable a single tweak to output multiple code actions, but I believe 
> in this case we might achieve a whole lot better UX if we did offer 
> implementing each method one by one, while possibly still suggesting 
> implement "all" overrides or "only" pures. It is still useful in its current 
> form ofcourse, as the user can manually change the declaration into a pure 
> one, or delete it, but it sounds cumbersome if they only want to implement a 
> small subset of all possible pure methods .
> - Acting on non-pure virtuals too, i believe this is also a quite common use 
> case that could benefit a lot of users. but this definitely increases the 
> need for a code action per override.

As code completion can help implement just one virtual method, not much is 
gained by offering to implement methods one by one.
Then there's the issue of say if a class has 50 virtual methods, Having 50 
different refactoring show up in the UI is likely going to be some issue.
There's a discussion 
 of adding a 
refactoring related methods to LSP which would enable a more interactive 
experience. There hasn't been an agreed design yet though. If that does make it 
through it would definitely extend the usefulness of this. Presenting a 
Interface to the user where they could choose exactly what methods they want to 
implement as well as letting them override already implemented virtual 
functions.

> - When to trigger? I suppose what you have in the code ATM makes sense (e.g. 
> just on `[[class X]] : ... [[{]] [[}]]`) but it would be great to spell it 
> out explicitly so that others have a chance to raise concerns. I don't think 
> triggering within the body would be useful though, as users are likely to 
> navigate within class body for various reasons, and spamming them with lots 
> of codeactions at each cursor move is likely to be annoying.

Fair point. Regarding the base specifier, Currently it doesn't offer the tweak 
when over the base specifier, I may be inclined to tweak behaviour so If you 
are over the base specifier, then only offer to implement pure virtual methods 
from that base class. Although rather annoyingly, The selection considers the 
`public|private|protected|virtual` part of a base specifier as part of the 
derived class, Instead of being part of the base specifier. I'm gonna push a 
separate patch to address that though.

> - When to land this :) we are at the edge of a branch cut, and tweaks are a 
> feature triggered automatically by editors. so any crashes in there are 
> likely to make clangd useless (as they'll persist no matter what). so I 
> believe we should either wait for release cut, and land this afterwards and 
> fixing any crash reports we get until next release, or include it in current 
> release while marking the tweak as hidden so that it will only annoy 
> experimental users.

I couldn't even rush this and get it ready before Tuesday :) Definitely not 
gonna make the 12 cut, even in experimental state.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D94942

___

[PATCH] D95231: [clangd] Selection handles CXXBaseSpecifier

2021-01-22 Thread Nathan James via Phabricator via cfe-commits
njames93 created this revision.
njames93 added reviewers: kadircet, hokein, sammccall.
Herald added subscribers: usaxena95, arphaman.
njames93 requested review of this revision.
Herald added subscribers: cfe-commits, MaskRay, ilya-biryukov.
Herald added a project: clang.

Selection now includes the virtual and access modifier as part of their range 
for cxx base specifiers.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D95231

Files:
  clang-tools-extra/clangd/Selection.cpp
  clang-tools-extra/clangd/unittests/SelectionTests.cpp
  clang/lib/AST/ASTTypeTraits.cpp


Index: clang/lib/AST/ASTTypeTraits.cpp
===
--- clang/lib/AST/ASTTypeTraits.cpp
+++ clang/lib/AST/ASTTypeTraits.cpp
@@ -193,5 +193,7 @@
 return TAL->getSourceRange();
   if (const auto *C = get())
 return SourceRange(C->getBeginLoc(), C->getEndLoc());
+  if (const auto *CBS = get())
+return CBS->getSourceRange();
   return SourceRange();
 }
Index: clang-tools-extra/clangd/unittests/SelectionTests.cpp
===
--- clang-tools-extra/clangd/unittests/SelectionTests.cpp
+++ clang-tools-extra/clangd/unittests/SelectionTests.cpp
@@ -261,6 +261,27 @@
   )cpp",
   "StringLiteral", // Not DeclRefExpr to operator()!
   },
+  {
+  R"cpp(
+struct Foo {};
+struct Bar : [[v^ir^tual private Foo]] {};
+  )cpp",
+  "CXXBaseSpecifier",
+  },
+  {
+  R"cpp(
+struct Foo {};
+struct Bar : [[private Fo^o]] {};
+  )cpp",
+  "CXXBaseSpecifier",
+  },
+  {
+  R"cpp(
+struct Foo {};
+struct Bar : [[Fo^o]] {};
+  )cpp",
+  "CXXBaseSpecifier",
+  },
 
   // Point selections.
   {"void foo() { [[^foo]](); }", "DeclRefExpr"},
Index: clang-tools-extra/clangd/Selection.cpp
===
--- clang-tools-extra/clangd/Selection.cpp
+++ clang-tools-extra/clangd/Selection.cpp
@@ -493,6 +493,14 @@
 return traverseNode(
 X, [&] { return Base::TraverseConstructorInitializer(X); });
   }
+  bool TraverseCXXBaseSpecifier(const CXXBaseSpecifier &X) {
+auto N = DynTypedNode::create(X);
+if (canSafelySkipNode(N))
+  return true;
+push(std::move(N));
+pop();
+return true;
+  }
   // Stmt is the same, but this form allows the data recursion optimization.
   bool dataTraverseStmtPre(Stmt *X) {
 if (!X || isImplicit(X))


Index: clang/lib/AST/ASTTypeTraits.cpp
===
--- clang/lib/AST/ASTTypeTraits.cpp
+++ clang/lib/AST/ASTTypeTraits.cpp
@@ -193,5 +193,7 @@
 return TAL->getSourceRange();
   if (const auto *C = get())
 return SourceRange(C->getBeginLoc(), C->getEndLoc());
+  if (const auto *CBS = get())
+return CBS->getSourceRange();
   return SourceRange();
 }
Index: clang-tools-extra/clangd/unittests/SelectionTests.cpp
===
--- clang-tools-extra/clangd/unittests/SelectionTests.cpp
+++ clang-tools-extra/clangd/unittests/SelectionTests.cpp
@@ -261,6 +261,27 @@
   )cpp",
   "StringLiteral", // Not DeclRefExpr to operator()!
   },
+  {
+  R"cpp(
+struct Foo {};
+struct Bar : [[v^ir^tual private Foo]] {};
+  )cpp",
+  "CXXBaseSpecifier",
+  },
+  {
+  R"cpp(
+struct Foo {};
+struct Bar : [[private Fo^o]] {};
+  )cpp",
+  "CXXBaseSpecifier",
+  },
+  {
+  R"cpp(
+struct Foo {};
+struct Bar : [[Fo^o]] {};
+  )cpp",
+  "CXXBaseSpecifier",
+  },
 
   // Point selections.
   {"void foo() { [[^foo]](); }", "DeclRefExpr"},
Index: clang-tools-extra/clangd/Selection.cpp
===
--- clang-tools-extra/clangd/Selection.cpp
+++ clang-tools-extra/clangd/Selection.cpp
@@ -493,6 +493,14 @@
 return traverseNode(
 X, [&] { return Base::TraverseConstructorInitializer(X); });
   }
+  bool TraverseCXXBaseSpecifier(const CXXBaseSpecifier &X) {
+auto N = DynTypedNode::create(X);
+if (canSafelySkipNode(N))
+  return true;
+push(std::move(N));
+pop();
+return true;
+  }
   // Stmt is the same, but this form allows the data recursion optimization.
   bool dataTraverseStmtPre(Stmt *X) {
 if (!X || isImplicit(X))
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D94779: [Clang] Ensure vector predication pragma is ignored only when vectorization width is 1.

2021-01-22 Thread Sjoerd Meijer via Phabricator via cfe-commits
SjoerdMeijer added a comment.

In D94779#2515157 , @dmgreen wrote:

> Thanks. @fhahn @SjoerdMeijer what do we think about the edge case where the 
> width==1? As far as I understand (with this patch):
>
>   #pragma clang loop vectorize_predicate(disable) vectorize_width(4)
>   Gives llvm.loop.vectorize.predicate.enable=false, 
> llvm.loop.vectorize.width=4, llvm.loop.vectorize.scalable.enable=false, 
> llvm.loop.vectorize.enable=true
>   
>   #pragma clang loop vectorize_predicate(disable) vectorize_width(4)

I guess this is a typo, and should be `vectorize_predicate(enable)`

> Gives llvm.loop.vectorize.predicate.enable=true, llvm.loop.vectorize.width=4, 
> llvm.loop.vectorize.scalable.enable=false, llvm.loop.vectorize.enable=true
>
> #pragma clang loop vectorize_predicate(enable) vectorize_width(1)
> Gives llvm.loop.vectorize.width=1, llvm.loop.vectorize.scalable.enable=false
>
> #pragma clang loop vectorize_predicate(disable) vectorize_width(1)
> Gives llvm.loop.vectorize.width=1, llvm.loop.vectorize.scalable.enable=false
>
>   Should we be adding llvm.loop.vectorize.predicate.enable metadata even when 
> width=1? I would be inclined to emit the predication pragma anyway.

So yeah, I got confused about this edge case width=1 earlier, but have 
refreshed my memory.
I would like to ask the question if it matters? Vectorize.width = 1 disables 
vectorisation, so unless I miss something, I don't think it matters if we emit 
`llvm.loop.vectorize.predicate.enable=true` or 
`llvm.loop.vectorize.predicate.enable=false` because it is ignored anyway? But 
if we have a combination that doesn't make sense, like `width(1)` and 
`predicate(enable)`, should we emit a diagnostic if this is not already done?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D94779

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


[PATCH] D95002: [RISCV] Update B extension version to 0.93.

2021-01-22 Thread Fraser Cormack via Phabricator via cfe-commits
frasercrmck added inline comments.



Comment at: llvm/lib/Target/RISCV/RISCVInstrInfoB.td:732
 // There's no encoding for roli in the current version of the 'B' extension
 // (v0.92) as it can be implemented with rori by negating the immediate.
 let Predicates = [HasStdExtZbbOrZbp] in {

This might need updated. The statement is still true in 0.92, but it's not the 
"current version"


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D95002

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


[PATCH] D95231: [clangd] Selection handles CXXBaseSpecifier

2021-01-22 Thread Nathan James via Phabricator via cfe-commits
njames93 updated this revision to Diff 318523.
njames93 added a comment.

Update FindTargets to fix symbol renaming on a CXXBaseSpecifier.
Add test to ensure rename wont trigger on a CXXBaseSpecifier.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D95231

Files:
  clang-tools-extra/clangd/FindTarget.cpp
  clang-tools-extra/clangd/Selection.cpp
  clang-tools-extra/clangd/unittests/RenameTests.cpp
  clang-tools-extra/clangd/unittests/SelectionTests.cpp
  clang/lib/AST/ASTTypeTraits.cpp


Index: clang/lib/AST/ASTTypeTraits.cpp
===
--- clang/lib/AST/ASTTypeTraits.cpp
+++ clang/lib/AST/ASTTypeTraits.cpp
@@ -193,5 +193,7 @@
 return TAL->getSourceRange();
   if (const auto *C = get())
 return SourceRange(C->getBeginLoc(), C->getEndLoc());
+  if (const auto *CBS = get())
+return CBS->getSourceRange();
   return SourceRange();
 }
Index: clang-tools-extra/clangd/unittests/SelectionTests.cpp
===
--- clang-tools-extra/clangd/unittests/SelectionTests.cpp
+++ clang-tools-extra/clangd/unittests/SelectionTests.cpp
@@ -261,6 +261,27 @@
   )cpp",
   "StringLiteral", // Not DeclRefExpr to operator()!
   },
+  {
+  R"cpp(
+struct Foo {};
+struct Bar : [[v^ir^tual private Foo]] {};
+  )cpp",
+  "CXXBaseSpecifier",
+  },
+  {
+  R"cpp(
+struct Foo {};
+struct Bar : [[private Fo^o]] {};
+  )cpp",
+  "CXXBaseSpecifier",
+  },
+  {
+  R"cpp(
+struct Foo {};
+struct Bar : [[Fo^o]] {};
+  )cpp",
+  "CXXBaseSpecifier",
+  },
 
   // Point selections.
   {"void foo() { [[^foo]](); }", "DeclRefExpr"},
Index: clang-tools-extra/clangd/unittests/RenameTests.cpp
===
--- clang-tools-extra/clangd/unittests/RenameTests.cpp
+++ clang-tools-extra/clangd/unittests/RenameTests.cpp
@@ -1024,6 +1024,12 @@
 }
   )cpp",
"new name is the same", !HeaderFile, nullptr, "SameName"},
+  {R"cpp(// Ensure it doesn't associate base specifier with base name.
+struct A {};
+struct B : priv^ate A {};
+  )cpp",
+   "Cannot rename symbol: there is no symbol at the given location", false,
+   nullptr},
   };
 
   for (const auto& Case : Cases) {
Index: clang-tools-extra/clangd/Selection.cpp
===
--- clang-tools-extra/clangd/Selection.cpp
+++ clang-tools-extra/clangd/Selection.cpp
@@ -493,6 +493,14 @@
 return traverseNode(
 X, [&] { return Base::TraverseConstructorInitializer(X); });
   }
+  bool TraverseCXXBaseSpecifier(const CXXBaseSpecifier &X) {
+auto N = DynTypedNode::create(X);
+if (canSafelySkipNode(N))
+  return true;
+push(std::move(N));
+pop();
+return true;
+  }
   // Stmt is the same, but this form allows the data recursion optimization.
   bool dataTraverseStmtPre(Stmt *X) {
 if (!X || isImplicit(X))
Index: clang-tools-extra/clangd/FindTarget.cpp
===
--- clang-tools-extra/clangd/FindTarget.cpp
+++ clang-tools-extra/clangd/FindTarget.cpp
@@ -710,7 +710,8 @@
 Finder.add(CCI, Flags);
   else if (const TemplateArgumentLoc *TAL = N.get())
 Finder.add(TAL->getArgument(), Flags);
-
+  else if (const CXXBaseSpecifier *CBS = N.get())
+Finder.add(CBS->getType(), Flags);
   return Finder.takeDecls();
 }
 


Index: clang/lib/AST/ASTTypeTraits.cpp
===
--- clang/lib/AST/ASTTypeTraits.cpp
+++ clang/lib/AST/ASTTypeTraits.cpp
@@ -193,5 +193,7 @@
 return TAL->getSourceRange();
   if (const auto *C = get())
 return SourceRange(C->getBeginLoc(), C->getEndLoc());
+  if (const auto *CBS = get())
+return CBS->getSourceRange();
   return SourceRange();
 }
Index: clang-tools-extra/clangd/unittests/SelectionTests.cpp
===
--- clang-tools-extra/clangd/unittests/SelectionTests.cpp
+++ clang-tools-extra/clangd/unittests/SelectionTests.cpp
@@ -261,6 +261,27 @@
   )cpp",
   "StringLiteral", // Not DeclRefExpr to operator()!
   },
+  {
+  R"cpp(
+struct Foo {};
+struct Bar : [[v^ir^tual private Foo]] {};
+  )cpp",
+  "CXXBaseSpecifier",
+  },
+  {
+  R"cpp(
+struct Foo {};
+struct Bar : [[private Fo^o]] {};
+  )cpp",
+  "CXXBaseSpecifier",
+  },
+  {
+  R"cpp(
+struct Foo {};
+struct Bar : [[Fo^o]] {};
+  )cpp",
+  "CXXBaseSpecifier",
+  },
 
   // Point sel

[PATCH] D95057: [clangd] WIP: configurable compilation database directory

2021-01-22 Thread Sam McCall via Phabricator via cfe-commits
sammccall updated this revision to Diff 318526.
sammccall added a comment.

Add tests and fix bugs


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D95057

Files:
  clang-tools-extra/clangd/ClangdLSPServer.cpp
  clang-tools-extra/clangd/Config.h
  clang-tools-extra/clangd/ConfigCompile.cpp
  clang-tools-extra/clangd/ConfigFragment.h
  clang-tools-extra/clangd/ConfigYAML.cpp
  clang-tools-extra/clangd/GlobalCompilationDatabase.cpp
  clang-tools-extra/clangd/GlobalCompilationDatabase.h
  clang-tools-extra/clangd/unittests/ClangdLSPServerTests.cpp
  clang-tools-extra/clangd/unittests/ConfigCompileTests.cpp
  clang-tools-extra/clangd/unittests/GlobalCompilationDatabaseTests.cpp

Index: clang-tools-extra/clangd/unittests/GlobalCompilationDatabaseTests.cpp
===
--- clang-tools-extra/clangd/unittests/GlobalCompilationDatabaseTests.cpp
+++ clang-tools-extra/clangd/unittests/GlobalCompilationDatabaseTests.cpp
@@ -8,6 +8,7 @@
 
 #include "GlobalCompilationDatabase.h"
 
+#include "Config.h"
 #include "Matchers.h"
 #include "TestFS.h"
 #include "support/Path.h"
@@ -205,10 +206,12 @@
   llvm::formatv(CDBOuter, llvm::sys::path::convert_to_slash(testRoot()));
   FS.Files[testPath("build/compile_commands.json")] =
   llvm::formatv(CDBInner, llvm::sys::path::convert_to_slash(testRoot()));
+  FS.Files[testPath("foo/compile_flags.txt")] = "-DFOO";
 
   // Note that gen2.cc goes missing with our following model, not sure this
   // happens in practice though.
   {
+SCOPED_TRACE("Default ancestor scanning");
 DirectoryBasedGlobalCompilationDatabase DB(FS);
 std::vector DiscoveredFiles;
 auto Sub =
@@ -227,8 +230,53 @@
 EXPECT_THAT(DiscoveredFiles, UnorderedElementsAre(EndsWith("gen.cc")));
   }
 
-  // With a custom compile commands dir.
   {
+SCOPED_TRACE("With config");
+DirectoryBasedGlobalCompilationDatabase::Options Opts(FS);
+Opts.ContextProvider = [&](llvm::StringRef Path) {
+  Config Cfg;
+  if (Path.endswith("a.cc")) {
+// a.cc uses another directory's CDB, so it won't be discovered.
+Cfg.CompileFlags.CDBSearch.Policy = Config::CDBSearchSpec::FixedDir;
+Cfg.CompileFlags.CDBSearch.FixedCDBPath = testPath("foo");
+  } else if (Path.endswith("gen.cc")) {
+// gen.cc has CDB search disabled, so it won't be discovered.
+Cfg.CompileFlags.CDBSearch.Policy = Config::CDBSearchSpec::NoCDBSearch;
+  } else if (Path.endswith("gen2.cc")) {
+// gen2.cc explicitly lists this directory, so it will be discovered.
+Cfg.CompileFlags.CDBSearch.Policy = Config::CDBSearchSpec::FixedDir;
+Cfg.CompileFlags.CDBSearch.FixedCDBPath = testRoot();
+  }
+  return Context::current().derive(Config::Key, std::move(Cfg));
+};
+DirectoryBasedGlobalCompilationDatabase DB(Opts);
+std::vector DiscoveredFiles;
+auto Sub =
+DB.watch([&DiscoveredFiles](const std::vector Changes) {
+  DiscoveredFiles = Changes;
+});
+
+// Does not use the root CDB, so no broadcast.
+auto Cmd = DB.getCompileCommand(testPath("build/../a.cc"));
+ASSERT_TRUE(Cmd.hasValue());
+EXPECT_THAT(Cmd->CommandLine, Contains("-DFOO")) << "a.cc uses foo/ CDB";
+ASSERT_TRUE(DB.blockUntilIdle(timeoutSeconds(10)));
+EXPECT_THAT(DiscoveredFiles, IsEmpty()) << "Root CDB not discovered yet";
+
+// No special config for b.cc, so we trigger broadcast of the root CDB.
+DB.getCompileCommand(testPath("b.cc"));
+ASSERT_TRUE(DB.blockUntilIdle(timeoutSeconds(10)));
+EXPECT_THAT(DiscoveredFiles, ElementsAre(testPath("build/gen2.cc")));
+DiscoveredFiles.clear();
+
+// No CDB search so no discovery/broadcast triggered for build/ CDB.
+DB.getCompileCommand(testPath("build/gen.cc"));
+ASSERT_TRUE(DB.blockUntilIdle(timeoutSeconds(10)));
+EXPECT_THAT(DiscoveredFiles, IsEmpty());
+  }
+
+  {
+SCOPED_TRACE("With custom compile commands dir");
 DirectoryBasedGlobalCompilationDatabase::Options Opts(FS);
 Opts.CompileCommandsDir = testRoot();
 DirectoryBasedGlobalCompilationDatabase DB(Opts);
@@ -294,6 +342,58 @@
   EXPECT_EQ(testPath("x"), Commands.getValue().Directory);
 }
 
+MATCHER_P(hasArg, Flag, "") {
+  if (!arg.hasValue()) {
+*result_listener << "command is null";
+return false;
+  }
+  if (!llvm::is_contained(arg->CommandLine, Flag)) {
+*result_listener << "flags are " << llvm::join(arg->CommandLine, " ");
+return false;
+  }
+  return true;
+}
+
+TEST(GlobalCompilationDatabaseTest, Config) {
+  MockFS FS;
+  FS.Files[testPath("x/compile_flags.txt")] = "-DX";
+  FS.Files[testPath("x/y/z/compile_flags.txt")] = "-DZ";
+
+  Config::CDBSearchSpec Spec;
+  DirectoryBasedGlobalCompilationDatabase::Options Opts(FS);
+  Opts.ContextProvider = [&](llvm::StringRef Path) {
+Config C;
+C.CompileFlags.CDBSearch = Sp

[PATCH] D95221: [clang][cli] NFC: Move prefix to the front of BoolOption

2021-01-22 Thread Duncan P. N. Exon Smith via Phabricator via cfe-commits
dexonsmith accepted this revision.
dexonsmith added a comment.
This revision is now accepted and ready to land.

LGTM.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D95221

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


[PATCH] D95225: [clang][cli] NFC: Pass CC1Option explicitly to BoolOption

2021-01-22 Thread Duncan P. N. Exon Smith via Phabricator via cfe-commits
dexonsmith accepted this revision.
dexonsmith added a comment.
This revision is now accepted and ready to land.

LGTM; this is much better!


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D95225

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


[PATCH] D94919: [clangd] Fix a crash when indexing invalid ObjC method declaration

2021-01-22 Thread Adam Czachorowski via Phabricator via cfe-commits
adamcz updated this revision to Diff 318529.
adamcz marked an inline comment as done.
adamcz added a comment.

addressed review comments


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D94919

Files:
  clang-tools-extra/clangd/unittests/SymbolCollectorTests.cpp
  clang/lib/Sema/SemaCodeComplete.cpp


Index: clang/lib/Sema/SemaCodeComplete.cpp
===
--- clang/lib/Sema/SemaCodeComplete.cpp
+++ clang/lib/Sema/SemaCodeComplete.cpp
@@ -3506,9 +3506,11 @@
 Result.AddTypedTextChunk("");
 }
 unsigned Idx = 0;
+// The extra Idx < Sel.getNumArgs() check is needed due to legacy C-style
+// method parameters.
 for (ObjCMethodDecl::param_const_iterator P = Method->param_begin(),
   PEnd = Method->param_end();
- P != PEnd; (void)++P, ++Idx) {
+ P != PEnd && Idx < Sel.getNumArgs(); (void)++P, ++Idx) {
   if (Idx > 0) {
 std::string Keyword;
 if (Idx > StartParameter)
Index: clang-tools-extra/clangd/unittests/SymbolCollectorTests.cpp
===
--- clang-tools-extra/clangd/unittests/SymbolCollectorTests.cpp
+++ clang-tools-extra/clangd/unittests/SymbolCollectorTests.cpp
@@ -1801,6 +1801,20 @@
   EXPECT_THAT(TU.headerSymbols(), Not(Contains(QName("X";
 }
 
+TEST_F(SymbolCollectorTest, NoCrashOnObjCMethodCStyleParam) {
+  auto TU = TestTU::withCode(R"objc(
+@interface Foo
+- (void)fun:(bool)foo, bool bar;
+@end
+  )objc");
+  TU.ExtraArgs.push_back("-xobjective-c++");
+
+  TU.build();
+  // We mostly care about not crashing.
+  EXPECT_THAT(TU.headerSymbols(),
+  UnorderedElementsAre(QName("Foo"), QName("Foo::fun:")));
+}
+
 } // namespace
 } // namespace clangd
 } // namespace clang


Index: clang/lib/Sema/SemaCodeComplete.cpp
===
--- clang/lib/Sema/SemaCodeComplete.cpp
+++ clang/lib/Sema/SemaCodeComplete.cpp
@@ -3506,9 +3506,11 @@
 Result.AddTypedTextChunk("");
 }
 unsigned Idx = 0;
+// The extra Idx < Sel.getNumArgs() check is needed due to legacy C-style
+// method parameters.
 for (ObjCMethodDecl::param_const_iterator P = Method->param_begin(),
   PEnd = Method->param_end();
- P != PEnd; (void)++P, ++Idx) {
+ P != PEnd && Idx < Sel.getNumArgs(); (void)++P, ++Idx) {
   if (Idx > 0) {
 std::string Keyword;
 if (Idx > StartParameter)
Index: clang-tools-extra/clangd/unittests/SymbolCollectorTests.cpp
===
--- clang-tools-extra/clangd/unittests/SymbolCollectorTests.cpp
+++ clang-tools-extra/clangd/unittests/SymbolCollectorTests.cpp
@@ -1801,6 +1801,20 @@
   EXPECT_THAT(TU.headerSymbols(), Not(Contains(QName("X";
 }
 
+TEST_F(SymbolCollectorTest, NoCrashOnObjCMethodCStyleParam) {
+  auto TU = TestTU::withCode(R"objc(
+@interface Foo
+- (void)fun:(bool)foo, bool bar;
+@end
+  )objc");
+  TU.ExtraArgs.push_back("-xobjective-c++");
+
+  TU.build();
+  // We mostly care about not crashing.
+  EXPECT_THAT(TU.headerSymbols(),
+  UnorderedElementsAre(QName("Foo"), QName("Foo::fun:")));
+}
+
 } // namespace
 } // namespace clangd
 } // namespace clang
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D94919: [clangd] Fix a crash when indexing invalid ObjC method declaration

2021-01-22 Thread Adam Czachorowski via Phabricator via cfe-commits
adamcz added inline comments.



Comment at: 
clang-tools-extra/clangd/unittests/SymbolCollectorTests.cpp:1807-1811
+@interface Foo
+- (void)fun:(bool)foo
+  bar:(bool)bar,
+  baz:(bool)baz;
+@end

dgoldman wrote:
> It's hard to tell what Clang makes of this, I think instead we should test 
> out the root cause of this crash, IIUC, are the legacy C style parameters:
> 
> ```
> @interface Foo
> - (void)func:(bool)foo, bool bar;
> @end
> ```
Oh yeah, thanks. Like I said, I don't know ObjC, so I was just randomly 
changing code until it crashed ;-)



Comment at: 
clang-tools-extra/clangd/unittests/SymbolCollectorTests.cpp:1816-1819
+  // We mostly care about not crashing, but verify that we didn't insert 
garbage
+  // about X too.
+  EXPECT_THAT(TU.headerSymbols(), Not(Contains(QName("X";
+}

dgoldman wrote:
> We should verify the method name is exactly as expected but comment we mostly 
> care about not crashing.
Oops, that's a copy/paste leftover, sorry about that. 


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D94919

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


[PATCH] D95017: [clang-format] add case aware include sorting

2021-01-22 Thread Björn Schäpers via Phabricator via cfe-commits
HazardyKnusperkeks added a comment.

I can push that, but will wait a bit longer so the others have time to object.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D95017

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


[PATCH] D94814: [HIP] Support `__managed__` attribute

2021-01-22 Thread Yaxun Liu via Phabricator via cfe-commits
yaxunl marked 2 inline comments as done.
yaxunl added inline comments.



Comment at: clang/include/clang/Basic/DiagnosticSemaKinds.td:8245
 "%select{__device__|__global__|__host__|__host__ __device__}0 functions">;
-def err_cuda_nonstatic_constdev: Error<"__constant__ and __device__ are not 
allowed on non-static local variables">;
+def err_cuda_nonstatic_constdev: Error<"__constant__, __device__, and 
__managed__ are not allowed on non-static local variables">;
 def err_cuda_ovl_target : Error<

aaron.ballman wrote:
> Since we're modifying this line anyway, can you wrap it for the 80-col limit?
will fix when committing



Comment at: clang/test/SemaCUDA/managed-var.cu:45
+__managed__ A a;
+// expected-error@-1 {{dynamic initialization is not supported for __device__, 
__constant__, __shared__, and __managed__ variables}}

aaron.ballman wrote:
> I think you're missing tests that check that the new managed attribute 
> accepts no arguments and that it doesn't apply to things other than variables 
> (like a function declaration).
will add tests when committing


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

https://reviews.llvm.org/D94814

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


[PATCH] D95145: [clang] Fix a nullptr dereference bug on invalid code

2021-01-22 Thread Adam Czachorowski via Phabricator via cfe-commits
adamcz updated this revision to Diff 318534.
adamcz added a comment.

addressed review comments


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D95145

Files:
  clang/lib/Sema/SemaTemplateInstantiateDecl.cpp
  clang/test/SemaCXX/subst-func-type-invalid-ret-type.cpp


Index: clang/test/SemaCXX/subst-func-type-invalid-ret-type.cpp
===
--- /dev/null
+++ clang/test/SemaCXX/subst-func-type-invalid-ret-type.cpp
@@ -0,0 +1,16 @@
+// RUN: %clang -fsyntax-only -std=c++17 %s -Xclang -verify
+
+// The important part is that we do not crash.
+
+template T declval();
+
+template 
+auto Call(T x) -> decltype(declval()(0)) {} // expected-note{{candidate 
template ignored}}
+
+class Status {};
+
+void fun() {
+  // The Status() (instead of Status) here used to cause a crash.
+  Call([](auto x) -> Status() {}); // expected-error{{function cannot return 
function type 'Status ()}}
+  // expected-error@-1{{no matching function for call to 'Call'}}
+}
Index: clang/lib/Sema/SemaTemplateInstantiateDecl.cpp
===
--- clang/lib/Sema/SemaTemplateInstantiateDecl.cpp
+++ clang/lib/Sema/SemaTemplateInstantiateDecl.cpp
@@ -4189,6 +4189,9 @@
   for (unsigned OldIdx = 0, NumOldParams = OldProtoLoc.getNumParams();
OldIdx != NumOldParams; ++OldIdx) {
 ParmVarDecl *OldParam = OldProtoLoc.getParam(OldIdx);
+if (!OldParam)
+  return nullptr;
+
 LocalInstantiationScope *Scope = SemaRef.CurrentInstantiationScope;
 
 Optional NumArgumentsInExpansion;


Index: clang/test/SemaCXX/subst-func-type-invalid-ret-type.cpp
===
--- /dev/null
+++ clang/test/SemaCXX/subst-func-type-invalid-ret-type.cpp
@@ -0,0 +1,16 @@
+// RUN: %clang -fsyntax-only -std=c++17 %s -Xclang -verify
+
+// The important part is that we do not crash.
+
+template T declval();
+
+template 
+auto Call(T x) -> decltype(declval()(0)) {} // expected-note{{candidate template ignored}}
+
+class Status {};
+
+void fun() {
+  // The Status() (instead of Status) here used to cause a crash.
+  Call([](auto x) -> Status() {}); // expected-error{{function cannot return function type 'Status ()}}
+  // expected-error@-1{{no matching function for call to 'Call'}}
+}
Index: clang/lib/Sema/SemaTemplateInstantiateDecl.cpp
===
--- clang/lib/Sema/SemaTemplateInstantiateDecl.cpp
+++ clang/lib/Sema/SemaTemplateInstantiateDecl.cpp
@@ -4189,6 +4189,9 @@
   for (unsigned OldIdx = 0, NumOldParams = OldProtoLoc.getNumParams();
OldIdx != NumOldParams; ++OldIdx) {
 ParmVarDecl *OldParam = OldProtoLoc.getParam(OldIdx);
+if (!OldParam)
+  return nullptr;
+
 LocalInstantiationScope *Scope = SemaRef.CurrentInstantiationScope;
 
 Optional NumArgumentsInExpansion;
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D95145: [clang] Fix a nullptr dereference bug on invalid code

2021-01-22 Thread Adam Czachorowski via Phabricator via cfe-commits
adamcz added a comment.

PTAL




Comment at: clang/test/SemaCXX/subst-func-type-invalid-ret-type.cpp:2
+// RUN: %clang -fsyntax-only -std=c++17 %s -Xclang -verify
+#include 
+

adamcz wrote:
> hokein wrote:
> > A common practice is to avoid depending on STL in tests. I think we need to 
> > pull out (even simplify?) std::result_of implementation if it is needed for 
> > reproducing the crash.
> I've noticed that pattern, but can't tell why this is. Is it documented 
> somewhere?
> 
Anyway, I updated the change to not require type_traits. Turned out to be 
simpler than expected ;-)


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D95145

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


[clang] 622eaa4 - [HIP] Support __managed__ attribute

2021-01-22 Thread Yaxun Liu via cfe-commits

Author: Yaxun (Sam) Liu
Date: 2021-01-22T11:43:58-05:00
New Revision: 622eaa4a4cea17c2cec6942d9702b010deae392b

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

LOG: [HIP] Support __managed__ attribute

This patch implements codegen for __managed__ variable attribute for HIP.

Diagnostics will be added later.

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

Added: 
clang/test/AST/Inputs/cuda.h
clang/test/AST/ast-dump-managed-var.cu
clang/test/CodeGenCUDA/managed-var.cu
clang/test/SemaCUDA/managed-var.cu
llvm/include/llvm/IR/ReplaceConstant.h
llvm/lib/IR/ReplaceConstant.cpp

Modified: 
clang/include/clang/Basic/Attr.td
clang/include/clang/Basic/AttrDocs.td
clang/include/clang/Basic/DiagnosticSemaKinds.td
clang/lib/CodeGen/CGCUDANV.cpp
clang/lib/CodeGen/CGCUDARuntime.h
clang/lib/CodeGen/CodeGenModule.cpp
clang/lib/Sema/SemaDeclAttr.cpp
clang/test/CodeGenCUDA/Inputs/cuda.h
clang/test/Misc/pragma-attribute-supported-attributes-list.test
clang/test/SemaCUDA/Inputs/cuda.h
clang/test/SemaCUDA/bad-attributes.cu
clang/test/SemaCUDA/device-var-init.cu
clang/test/SemaCUDA/function-overload.cu
clang/test/SemaCUDA/union-init.cu
llvm/lib/IR/CMakeLists.txt
llvm/lib/Target/XCore/XCoreLowerThreadLocal.cpp

Removed: 




diff  --git a/clang/include/clang/Basic/Attr.td 
b/clang/include/clang/Basic/Attr.td
index b30b91d3d4a6..bfd50f6a6779 100644
--- a/clang/include/clang/Basic/Attr.td
+++ b/clang/include/clang/Basic/Attr.td
@@ -324,6 +324,7 @@ class LangOpt {
 def MicrosoftExt : LangOpt<"MicrosoftExt">;
 def Borland : LangOpt<"Borland">;
 def CUDA : LangOpt<"CUDA">;
+def HIP : LangOpt<"HIP">;
 def SYCL : LangOpt<"SYCLIsDevice">;
 def COnly : LangOpt<"", "!LangOpts.CPlusPlus">;
 def CPlusPlus : LangOpt<"CPlusPlus">;
@@ -1115,6 +1116,13 @@ def CUDAHost : InheritableAttr {
   let Documentation = [Undocumented];
 }
 
+def HIPManaged : InheritableAttr {
+  let Spellings = [GNU<"managed">, Declspec<"__managed__">];
+  let Subjects = SubjectList<[Var]>;
+  let LangOpts = [HIP];
+  let Documentation = [HIPManagedAttrDocs];
+}
+
 def CUDAInvalidTarget : InheritableAttr {
   let Spellings = [];
   let Subjects = SubjectList<[Function]>;

diff  --git a/clang/include/clang/Basic/AttrDocs.td 
b/clang/include/clang/Basic/AttrDocs.td
index fffede41db1e..170a0fe3d4c4 100644
--- a/clang/include/clang/Basic/AttrDocs.td
+++ b/clang/include/clang/Basic/AttrDocs.td
@@ -5419,6 +5419,17 @@ unbind runtime APIs.
   }];
 }
 
+def HIPManagedAttrDocs : Documentation {
+  let Category = DocCatDecl;
+  let Content = [{
+The ``__managed__`` attribute can be applied to a global variable declaration 
in HIP.
+A managed variable is emitted as an undefined global symbol in the device 
binary and is
+registered by ``__hipRegisterManagedVariable`` in init functions. The HIP 
runtime allocates
+managed memory and uses it to define the symbol when loading the device binary.
+A managed variable can be accessed in both device and host code.
+  }];
+}
+
 def LifetimeOwnerDocs : Documentation {
   let Category = DocCatDecl;
   let Content = [{

diff  --git a/clang/include/clang/Basic/DiagnosticSemaKinds.td 
b/clang/include/clang/Basic/DiagnosticSemaKinds.td
index 758b2ed3e90b..67c59f3ca09a 100644
--- a/clang/include/clang/Basic/DiagnosticSemaKinds.td
+++ b/clang/include/clang/Basic/DiagnosticSemaKinds.td
@@ -8237,7 +8237,7 @@ def err_cuda_device_exceptions : Error<
   "%select{__device__|__global__|__host__|__host__ __device__}1 function">;
 def err_dynamic_var_init : Error<
 "dynamic initialization is not supported for "
-"__device__, __constant__, and __shared__ variables.">;
+"__device__, __constant__, __shared__, and __managed__ variables.">;
 def err_shared_var_init : Error<
 "initialization is not supported for __shared__ variables.">;
 def err_cuda_vla : Error<
@@ -8247,7 +8247,8 @@ def err_cuda_extern_shared : Error<"__shared__ variable 
%0 cannot be 'extern'">;
 def err_cuda_host_shared : Error<
 "__shared__ local variables not allowed in "
 "%select{__device__|__global__|__host__|__host__ __device__}0 functions">;
-def err_cuda_nonstatic_constdev: Error<"__constant__ and __device__ are not 
allowed on non-static local variables">;
+def err_cuda_nonstatic_constdev: Error<"__constant__, __device__, and "
+"__managed__ are not allowed on non-static local variables">;
 def err_cuda_ovl_target : Error<
   "%select{__device__|__global__|__host__|__host__ __device__}0 function %1 "
   "cannot overload %select{__device__|__global__|__host__|__host__ 
__device__}2 function %3">;

diff  --git a/clang/lib/CodeGen/CGCUDANV.cpp b/clang/lib/CodeGen/CGCUDANV.cpp
index 7c5ab39a85ec..33a2d6f4483e 100644
--- a/clang/lib/CodeGen/CGCUD

[PATCH] D94814: [HIP] Support `__managed__` attribute

2021-01-22 Thread Yaxun Liu via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
yaxunl marked 2 inline comments as done.
Closed by commit rG622eaa4a4cea: [HIP] Support __managed__ attribute (authored 
by yaxunl).
Herald added a project: clang.

Changed prior to commit:
  https://reviews.llvm.org/D94814?vs=318243&id=318537#toc

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D94814

Files:
  clang/include/clang/Basic/Attr.td
  clang/include/clang/Basic/AttrDocs.td
  clang/include/clang/Basic/DiagnosticSemaKinds.td
  clang/lib/CodeGen/CGCUDANV.cpp
  clang/lib/CodeGen/CGCUDARuntime.h
  clang/lib/CodeGen/CodeGenModule.cpp
  clang/lib/Sema/SemaDeclAttr.cpp
  clang/test/AST/Inputs/cuda.h
  clang/test/AST/ast-dump-managed-var.cu
  clang/test/CodeGenCUDA/Inputs/cuda.h
  clang/test/CodeGenCUDA/managed-var.cu
  clang/test/Misc/pragma-attribute-supported-attributes-list.test
  clang/test/SemaCUDA/Inputs/cuda.h
  clang/test/SemaCUDA/bad-attributes.cu
  clang/test/SemaCUDA/device-var-init.cu
  clang/test/SemaCUDA/function-overload.cu
  clang/test/SemaCUDA/managed-var.cu
  clang/test/SemaCUDA/union-init.cu
  llvm/include/llvm/IR/ReplaceConstant.h
  llvm/lib/IR/CMakeLists.txt
  llvm/lib/IR/ReplaceConstant.cpp
  llvm/lib/Target/XCore/XCoreLowerThreadLocal.cpp

Index: llvm/lib/Target/XCore/XCoreLowerThreadLocal.cpp
===
--- llvm/lib/Target/XCore/XCoreLowerThreadLocal.cpp
+++ llvm/lib/Target/XCore/XCoreLowerThreadLocal.cpp
@@ -21,6 +21,7 @@
 #include "llvm/IR/IntrinsicsXCore.h"
 #include "llvm/IR/Module.h"
 #include "llvm/IR/NoFolder.h"
+#include "llvm/IR/ReplaceConstant.h"
 #include "llvm/IR/ValueHandle.h"
 #include "llvm/Pass.h"
 #include "llvm/Support/CommandLine.h"
@@ -74,57 +75,6 @@
   return ConstantArray::get(NewType, Elements);
 }
 
-static Instruction *
-createReplacementInstr(ConstantExpr *CE, Instruction *Instr) {
-  IRBuilder Builder(Instr);
-  unsigned OpCode = CE->getOpcode();
-  switch (OpCode) {
-case Instruction::GetElementPtr: {
-  SmallVector CEOpVec(CE->operands());
-  ArrayRef CEOps(CEOpVec);
-  return dyn_cast(Builder.CreateInBoundsGEP(
-  cast(CE)->getSourceElementType(), CEOps[0],
-  CEOps.slice(1)));
-}
-case Instruction::Add:
-case Instruction::Sub:
-case Instruction::Mul:
-case Instruction::UDiv:
-case Instruction::SDiv:
-case Instruction::FDiv:
-case Instruction::URem:
-case Instruction::SRem:
-case Instruction::FRem:
-case Instruction::Shl:
-case Instruction::LShr:
-case Instruction::AShr:
-case Instruction::And:
-case Instruction::Or:
-case Instruction::Xor:
-  return dyn_cast(
-  Builder.CreateBinOp((Instruction::BinaryOps)OpCode,
-  CE->getOperand(0), CE->getOperand(1),
-  CE->getName()));
-case Instruction::Trunc:
-case Instruction::ZExt:
-case Instruction::SExt:
-case Instruction::FPToUI:
-case Instruction::FPToSI:
-case Instruction::UIToFP:
-case Instruction::SIToFP:
-case Instruction::FPTrunc:
-case Instruction::FPExt:
-case Instruction::PtrToInt:
-case Instruction::IntToPtr:
-case Instruction::BitCast:
-  return dyn_cast(
-  Builder.CreateCast((Instruction::CastOps)OpCode,
- CE->getOperand(0), CE->getType(),
- CE->getName()));
-default:
-  llvm_unreachable("Unhandled constant expression!\n");
-  }
-}
 
 static bool replaceConstantExprOp(ConstantExpr *CE, Pass *P) {
   do {
Index: llvm/lib/IR/ReplaceConstant.cpp
===
--- /dev/null
+++ llvm/lib/IR/ReplaceConstant.cpp
@@ -0,0 +1,70 @@
+//===- ReplaceConstant.cpp - Replace LLVM constant expression--===//
+//
+// 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
+//
+//===--===//
+//
+// This file implements a utility function for replacing LLVM constant
+// expressions by instructions.
+//
+//===--===//
+
+#include "llvm/IR/ReplaceConstant.h"
+#include "llvm/IR/IRBuilder.h"
+#include "llvm/IR/Instructions.h"
+#include "llvm/IR/NoFolder.h"
+
+namespace llvm {
+// Replace a constant expression by instructions with equivalent operations at
+// a specified location.
+Instruction *createReplacementInstr(ConstantExpr *CE, Instruction *Instr) {
+  IRBuilder Builder(Instr);
+  unsigned OpCode = CE->getOpcode();
+  switch (OpCode) {
+  case Instruction::GetElementPtr: {
+SmallVector CEOpVec(CE->operands());
+ArrayRef CEOps

[PATCH] D95244: [clang][AST] Handle overload callee type in CallExpr::getCallReturnType.

2021-01-22 Thread Balázs Kéri via Phabricator via cfe-commits
balazske created this revision.
Herald added subscribers: martong, gamesh411, Szelethus, dkrupp.
balazske requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

Type of `Callee` can be overloaded function type that was not handled.
This causes a crash if the function is called in such case.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D95244

Files:
  clang/lib/AST/Expr.cpp


Index: clang/lib/AST/Expr.cpp
===
--- clang/lib/AST/Expr.cpp
+++ clang/lib/AST/Expr.cpp
@@ -1392,6 +1392,11 @@
 
 // This should never be overloaded and so should never return null.
 CalleeType = Expr::findBoundMemberType(Callee);
+  } else if (CalleeType->isSpecificPlaceholderType(BuiltinType::Overload)) {
+ASTContext::GetBuiltinTypeError Error;
+QualType RetTy = Ctx.GetBuiltinType(BuiltinType::Dependent, Error);
+assert(Error == ASTContext::GE_None);
+return RetTy;
   }
 
   const FunctionType *FnType = CalleeType->castAs();


Index: clang/lib/AST/Expr.cpp
===
--- clang/lib/AST/Expr.cpp
+++ clang/lib/AST/Expr.cpp
@@ -1392,6 +1392,11 @@
 
 // This should never be overloaded and so should never return null.
 CalleeType = Expr::findBoundMemberType(Callee);
+  } else if (CalleeType->isSpecificPlaceholderType(BuiltinType::Overload)) {
+ASTContext::GetBuiltinTypeError Error;
+QualType RetTy = Ctx.GetBuiltinType(BuiltinType::Dependent, Error);
+assert(Error == ASTContext::GE_None);
+return RetTy;
   }
 
   const FunctionType *FnType = CalleeType->castAs();
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D95244: [clang][AST] Handle overload callee type in CallExpr::getCallReturnType.

2021-01-22 Thread Balázs Kéri via Phabricator via cfe-commits
balazske added a comment.

Should add some responsible (for this code) reviewers.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D95244

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


[PATCH] D95002: [RISCV] Update B extension version to 0.93.

2021-01-22 Thread Craig Topper via Phabricator via cfe-commits
craig.topper updated this revision to Diff 318548.
craig.topper added a comment.

Remove reference to version from the rori comment. The version doesn't really 
matter, I doubt the encoding will ever be added.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D95002

Files:
  clang/lib/Driver/ToolChains/Arch/RISCV.cpp
  clang/test/Driver/riscv-arch.c
  clang/test/Preprocessor/riscv-target-features.c
  llvm/lib/Target/RISCV/RISCVInstrInfoB.td


Index: llvm/lib/Target/RISCV/RISCVInstrInfoB.td
===
--- llvm/lib/Target/RISCV/RISCVInstrInfoB.td
+++ llvm/lib/Target/RISCV/RISCVInstrInfoB.td
@@ -7,7 +7,7 @@
 
//===--===//
 //
 // This file describes the RISC-V instructions from the standard 'B' Bitmanip
-// extension, version 0.92.
+// extension, version 0.93.
 // This version is still experimental as the 'B' extension hasn't been
 // ratified yet.
 //
@@ -728,8 +728,8 @@
   (SROI GPR:$rs1, uimmlog2xlen:$shamt)>;
 } // Predicates = [HasStdExtZbp]
 
-// There's no encoding for roli in the current version of the 'B' extension
-// (v0.92) as it can be implemented with rori by negating the immediate.
+// There's no encoding for roli in the the 'B' extension as it can be
+// implemented with rori by negating the immediate.
 let Predicates = [HasStdExtZbbOrZbp] in {
 def : Pat<(rotr GPR:$rs1, uimmlog2xlen:$shamt),
   (RORI GPR:$rs1, uimmlog2xlen:$shamt)>;
Index: clang/test/Preprocessor/riscv-target-features.c
===
--- clang/test/Preprocessor/riscv-target-features.c
+++ clang/test/Preprocessor/riscv-target-features.c
@@ -49,9 +49,9 @@
 // RUN: -o - | FileCheck --check-prefix=CHECK-C-EXT %s
 // CHECK-C-EXT: __riscv_compressed 1
 
-// RUN: %clang -target riscv32-unknown-linux-gnu 
-menable-experimental-extensions -march=rv32ib0p92 -x c -E -dM %s \
+// RUN: %clang -target riscv32-unknown-linux-gnu 
-menable-experimental-extensions -march=rv32ib0p93 -x c -E -dM %s \
 // RUN: -o - | FileCheck --check-prefix=CHECK-B-EXT %s
-// RUN: %clang -target riscv64-unknown-linux-gnu 
-menable-experimental-extensions -march=rv64ib0p92 -x c -E -dM %s \
+// RUN: %clang -target riscv64-unknown-linux-gnu 
-menable-experimental-extensions -march=rv64ib0p93 -x c -E -dM %s \
 // RUN: -o - | FileCheck --check-prefix=CHECK-B-EXT %s
 // CHECK-B-EXT: __riscv_bitmanip 1
 
Index: clang/test/Driver/riscv-arch.c
===
--- clang/test/Driver/riscv-arch.c
+++ clang/test/Driver/riscv-arch.c
@@ -343,7 +343,7 @@
 // RV32-EXPERIMENTAL-BADVERS: error: invalid arch name 'rv32ib0p1'
 // RV32-EXPERIMENTAL-BADVERS: unsupported version number 0.1 for experimental 
extension
 
-// RUN: %clang -target riscv32-unknown-elf -march=rv32ib0p92 
-menable-experimental-extensions -### %s \
+// RUN: %clang -target riscv32-unknown-elf -march=rv32ib0p93 
-menable-experimental-extensions -### %s \
 // RUN: -fsyntax-only 2>&1 | FileCheck 
-check-prefix=RV32-EXPERIMENTAL-GOODVERS %s
 // RV32-EXPERIMENTAL-GOODVERS: "-target-feature" "+experimental-b"
 
@@ -352,20 +352,20 @@
 // RV32-EXPERIMENTAL-ZBB-NOFLAG: error: invalid arch name 'rv32izbb'
 // RV32-EXPERIMENTAL-ZBB-NOFLAG: requires '-menable-experimental-extensions'
 
-// RUN: %clang -target riscv32-unknown-elf -march=rv32izbb0p92 
-menable-experimental-extensions -### %s \
+// RUN: %clang -target riscv32-unknown-elf -march=rv32izbb0p93 
-menable-experimental-extensions -### %s \
 // RUN: -fsyntax-only 2>&1 | FileCheck -check-prefix=RV32-EXPERIMENTAL-ZBB %s
 // RV32-EXPERIMENTAL-ZBB: "-target-feature" "+experimental-zbb"
 
-// RUN: %clang -target riscv32-unknown-elf -march=rv32izbb0p92_zbp0p92 
-menable-experimental-extensions -### %s \
+// RUN: %clang -target riscv32-unknown-elf -march=rv32izbb0p93_zbp0p93 
-menable-experimental-extensions -### %s \
 // RUN: -fsyntax-only 2>&1 | FileCheck -check-prefix=RV32-EXPERIMENTAL-ZBB-ZBP 
%s
 // RV32-EXPERIMENTAL-ZBB-ZBP: "-target-feature" "+experimental-zbb"
 // RV32-EXPERIMENTAL-ZBB-ZBP: "-target-feature" "+experimental-zbp"
 
-// RUN: %clang -target riscv32-unknown-elf -march=rv32izbb0p92zbp0p92 
-menable-experimental-extensions -### %s \
+// RUN: %clang -target riscv32-unknown-elf -march=rv32izbb0p93zbp0p93 
-menable-experimental-extensions -### %s \
 // RUN: -fsyntax-only 2>&1 | FileCheck 
-check-prefix=RV32-EXPERIMENTAL-ZBB-ZBP-UNDERSCORE %s
-// RV32-EXPERIMENTAL-ZBB-ZBP-UNDERSCORE: error: invalid arch name 
'rv32izbb0p92zbp0p92', multi-character extensions must be separated by 
underscores
+// RV32-EXPERIMENTAL-ZBB-ZBP-UNDERSCORE: error: invalid arch name 
'rv32izbb0p93zbp0p93', multi-character extensions must be separated by 
underscores
 
-// RUN: %clang -target riscv32-unknown-elf -march=rv32izba0p92 
-menable-experimental-extensio

[PATCH] D94942: [clangd] Add tweak for implementing abstract class

2021-01-22 Thread Nathan James via Phabricator via cfe-commits
njames93 updated this revision to Diff 318552.
njames93 added a comment.

If cursor is over one of the base specifiers, offer to implement only the pure 
methods from that base class.
Depends on D95231 


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D94942

Files:
  clang-tools-extra/clangd/refactor/tweaks/CMakeLists.txt
  clang-tools-extra/clangd/refactor/tweaks/ImplementAbstract.cpp
  clang-tools-extra/clangd/unittests/CMakeLists.txt
  clang-tools-extra/clangd/unittests/tweaks/ImplementAbstractTests.cpp

Index: clang-tools-extra/clangd/unittests/tweaks/ImplementAbstractTests.cpp
===
--- /dev/null
+++ clang-tools-extra/clangd/unittests/tweaks/ImplementAbstractTests.cpp
@@ -0,0 +1,391 @@
+//===-- ImplementAbstractTests.cpp --*- C++ -*-===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+
+#include "TestTU.h"
+#include "TweakTesting.h"
+#include "gmock/gmock-matchers.h"
+#include "gmock/gmock.h"
+#include "gtest/gtest.h"
+
+using ::testing::Not;
+
+namespace clang {
+namespace clangd {
+namespace {
+
+TWEAK_TEST(ImplementAbstract);
+
+TEST_F(ImplementAbstractTest, TestUnavailable) {
+
+  StringRef Cases[]{
+  // Not a pure virtual method.
+  R"cpp(
+  class A {
+virtual void Foo();
+  };
+  class ^B : public A {};
+)cpp",
+  // Pure virtual method overridden in class.
+  R"cpp(
+  class A {
+virtual void Foo() = 0;
+  };
+  class ^B : public A {
+void Foo() override;
+  };
+)cpp",
+  // Pure virtual method overridden in class with virtual keyword
+  R"cpp(
+  class A {
+virtual void Foo() = 0;
+  };
+  class ^B : public A {
+virtual void Foo() override;
+  };
+)cpp",
+  // Pure virtual method overridden in class without override keyword
+  R"cpp(
+  class A {
+virtual void Foo() = 0;
+  };
+  class ^B : public A {
+void Foo();
+  };
+)cpp",
+  // Pure virtual method overriden in base class.
+  R"cpp(
+  class A {
+virtual void Foo() = 0;
+  };
+  class B : public A {
+void Foo() override;
+  };
+  class ^C : public B {
+  };
+)cpp"};
+  for (const auto &Case : Cases) {
+EXPECT_THAT(Case, Not(isAvailable()));
+  }
+}
+
+TEST_F(ImplementAbstractTest, NormalAvailable) {
+  struct Case {
+llvm::StringRef TestHeader;
+llvm::StringRef TestSource;
+llvm::StringRef ExpectedSource;
+  };
+
+  Case Cases[]{
+  {
+  R"cpp(
+class A {
+  virtual void Foo() = 0;
+};)cpp",
+  R"cpp(
+class B : public A {^};
+  )cpp",
+  R"cpp(
+class B : public A {
+  void Foo() override;
+  };
+  )cpp",
+  },
+  {
+  R"cpp(
+class A {
+  public:
+  virtual void Foo() = 0;
+};)cpp",
+  R"cpp(
+class ^B : public A {};
+  )cpp",
+  R"cpp(
+class B : public A {
+  public:
+
+  void Foo() override;
+  };
+  )cpp",
+  },
+  {
+  R"cpp(
+class A {
+  virtual void Foo(int Param) = 0;
+};)cpp",
+  R"cpp(
+class ^B : public A {};
+  )cpp",
+  R"cpp(
+class B : public A {
+  void Foo(int Param) override;
+  };
+  )cpp",
+  },
+  {
+  R"cpp(
+class A {
+  virtual void Foo(int Param) = 0;
+};)cpp",
+  R"cpp(
+struct ^B : public A {};
+  )cpp",
+  R"cpp(
+struct B : public A {
+  private:
+
+  void Foo(int Param) override;
+  };
+  )cpp",
+  },
+  {
+  R"cpp(
+class A {
+  virtual void Foo(int Param) const volatile = 0;
+  public:
+  virtual void Bar(int Param) = 0;
+};)cpp",
+  R"cpp(
+class ^B : public A {
+  void Foo(int Param) const volatile override;
+};
+  )cpp",
+  R"cpp(
+class B : public A {
+  void Foo(int Param) const volatile override;
+
+  public:
+
+  void Bar(int Param) override;
+  };
+  )cpp",
+  },
+  {
+  R"cpp(
+ class A {
+  virtual void Foo() = 0;
+  virtual void Bar() = 0;
+};
+class B : public A {
+  void Foo() o

[PATCH] D94919: [clangd] Fix a crash when indexing invalid ObjC method declaration

2021-01-22 Thread David Goldman via Phabricator via cfe-commits
dgoldman requested changes to this revision.
dgoldman added a comment.
This revision now requires changes to proceed.

Looks good but I think for posterity we should add a similar test to 
clang-tools-extra/clangd/unittests/CodeCompleteTests.cpp for the exact intended 
code complete behavior (or instead of SymbolCollectorTests.cpp - is there a 
particular reason you added a test there)?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D94919

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


[PATCH] D92191: [clang-scan-deps] Add support for clang-cl

2021-01-22 Thread Sylvain Audi via Phabricator via cfe-commits
saudi updated this revision to Diff 318553.
saudi marked an inline comment as done.
saudi added a comment.

Applied the suggestions from the parent patch D95099 



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

https://reviews.llvm.org/D92191

Files:
  clang/test/ClangScanDeps/Inputs/has_include_if_elif.json
  clang/test/ClangScanDeps/Inputs/header_stat_before_open_cdb.json
  clang/test/ClangScanDeps/Inputs/headerwithdirname.json
  clang/test/ClangScanDeps/Inputs/headerwithdirnamefollowedbyinclude.json
  clang/test/ClangScanDeps/Inputs/modules_cdb_clangcl.json
  clang/test/ClangScanDeps/Inputs/no-werror.json
  clang/test/ClangScanDeps/Inputs/regular_cdb_clangcl.json
  clang/test/ClangScanDeps/Inputs/static-analyzer-cdb.json
  clang/test/ClangScanDeps/Inputs/strip_diag_serialize.json
  clang/test/ClangScanDeps/Inputs/target-filename-cdb.json
  clang/test/ClangScanDeps/Inputs/vfsoverlay_cdb.json
  clang/test/ClangScanDeps/error.cpp
  clang/test/ClangScanDeps/has_include_if_elif.cpp
  clang/test/ClangScanDeps/header_stat_before_open.m
  clang/test/ClangScanDeps/headerwithdirname.cpp
  clang/test/ClangScanDeps/headerwithdirnamefollowedbyinclude.cpp
  clang/test/ClangScanDeps/modules-full.cpp
  clang/test/ClangScanDeps/modules.cpp
  clang/test/ClangScanDeps/no-werror.cpp
  clang/test/ClangScanDeps/regular_cdb.cpp
  clang/test/ClangScanDeps/static-analyzer.c
  clang/test/ClangScanDeps/strip_diag_serialize.cpp
  clang/test/ClangScanDeps/target-filename.cpp
  clang/test/ClangScanDeps/vfsoverlay.cpp
  clang/tools/clang-scan-deps/ClangScanDeps.cpp

Index: clang/tools/clang-scan-deps/ClangScanDeps.cpp
===
--- clang/tools/clang-scan-deps/ClangScanDeps.cpp
+++ clang/tools/clang-scan-deps/ClangScanDeps.cpp
@@ -12,6 +12,8 @@
 #include "clang/Tooling/DependencyScanning/DependencyScanningTool.h"
 #include "clang/Tooling/DependencyScanning/DependencyScanningWorker.h"
 #include "clang/Tooling/JSONCompilationDatabase.h"
+#include "llvm/ADT/STLExtras.h"
+#include "llvm/ADT/Twine.h"
 #include "llvm/Support/CommandLine.h"
 #include "llvm/Support/FileUtilities.h"
 #include "llvm/Support/InitLLVM.h"
@@ -49,7 +51,8 @@
   /// option and cache the results for reuse. \returns resource directory path
   /// associated with the given invocation command or empty string if the
   /// compiler path is NOT an absolute path.
-  StringRef findResourceDir(const tooling::CommandLineArguments &Args) {
+  StringRef findResourceDir(const tooling::CommandLineArguments &Args,
+bool ClangCLMode) {
 if (Args.size() < 1)
   return "";
 
@@ -65,8 +68,12 @@
 if (CachedResourceDir != Cache.end())
   return CachedResourceDir->second;
 
-std::vector PrintResourceDirArgs{ClangBinaryName,
-"-print-resource-dir"};
+std::vector PrintResourceDirArgs{ClangBinaryName};
+if (ClangCLMode)
+  PrintResourceDirArgs.push_back("/clang:-print-resource-dir");
+else
+  PrintResourceDirArgs.push_back("-print-resource-dir");
+
 llvm::SmallString<64> OutputFile, ErrorFile;
 llvm::sys::fs::createTemporaryFile("print-resource-dir-output",
"" /*no-suffix*/, OutputFile);
@@ -421,27 +428,55 @@
 bool HasMQ = false;
 bool HasMD = false;
 bool HasResourceDir = false;
+bool ClangCLMode = false;
 auto FlagsEnd = llvm::find(Args, "--");
 
 // We need to find the last -o value.
 if (FlagsEnd != Args.begin()) {
+  ClangCLMode =
+  llvm::sys::path::stem(Args[0]).contains_lower("clang-cl") ||
+  llvm::is_contained(Args, "--driver-mode=cl");
+
   // Reverse scan, starting at the end or at the element before "--".
   for (auto RB = llvm::make_reverse_iterator(FlagsEnd), RI = RB,
 RE = Args.rend();
RI != RE; ++RI) {
 StringRef Arg = *RI;
-if (LastO.empty()) {
-  if (Arg == "-o" && RI != RB)
-LastO = RI[-1]; // Next argument (reverse iterator)
-  else if (Arg.startswith("-o"))
-LastO = Arg.drop_front(2).str();
+if (ClangCLMode) {
+  if (LastO.empty()) {
+// With clang-cl, the output obj file can be specified with
+// "/opath", "/o path", "/Fopath", and the dash counterparts.
+// Also, clang-cl adds ".obj" extension if none is found.
+if ((Arg == "-o" || Arg == "/o") && RI != RB)
+  LastO = RI[-1]; // Next argument (reverse iterator)
+else if (Arg.startswith("/Fo") || Arg.startswith("-Fo"))
+  LastO = Arg.drop_front(3).str();
+else if (Arg.startswith("/o") || Arg.startswith("-o"))
+  LastO = Arg.drop_front(2).str();
+
+if (!

[PATCH] D95246: [SystemZ][z/OS] Fix No such file or directory expression error matching in lit tests - continued

2021-01-22 Thread Abhina Sree via Phabricator via cfe-commits
abhina.sreeskantharajan created this revision.
abhina.sreeskantharajan added reviewers: fanbo-meng, anirudhp, muiez, Kai, 
yusra.syeda.
Herald added subscribers: rupprecht, steven_wu, hiraditya, sbc100.
Herald added a reviewer: alexshap.
Herald added a reviewer: rupprecht.
Herald added a reviewer: jhenderson.
abhina.sreeskantharajan requested review of this revision.
Herald added subscribers: llvm-commits, cfe-commits, MaskRay, aheejin.
Herald added projects: clang, LLVM.

This is a continuation of https://reviews.llvm.org/D94239. I missed some other 
spellings of the same error.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D95246

Files:
  clang/test/Driver/clang-offload-bundler.c
  clang/test/Frontend/output-failures.c
  llvm/test/Object/archive-extract-dir.test
  llvm/test/Object/archive-extract.test
  llvm/test/Object/directory.ll
  llvm/test/tools/llvm-ar/error-opening-directory.test
  llvm/test/tools/llvm-ar/move.test
  llvm/test/tools/llvm-ar/print.test
  llvm/test/tools/llvm-ar/quick-append.test
  llvm/test/tools/llvm-libtool-darwin/invalid-input-output-args.test
  llvm/test/tools/llvm-lipo/create-arch.test
  llvm/test/tools/llvm-lipo/replace-invalid-input.test
  llvm/test/tools/llvm-lto/error.ll
  llvm/test/tools/llvm-objcopy/wasm/dump-section.test
  llvm/test/tools/llvm-symbolizer/pdb/missing_pdb.test

Index: llvm/test/tools/llvm-symbolizer/pdb/missing_pdb.test
===
--- llvm/test/tools/llvm-symbolizer/pdb/missing_pdb.test
+++ llvm/test/tools/llvm-symbolizer/pdb/missing_pdb.test
@@ -4,7 +4,7 @@
 
 llvm-symbolizer should print one error and two unknown line info records.
 
-ERROR: LLVMSymbolizer: error reading file: {{.*}}: {{N|n}}o such file or directory
+ERROR: LLVMSymbolizer: error reading file: {{.*}}: {{.*}}{{N|n}}o such file or directory
 ERROR-NOT: error reading file
 
 CHECK: ??
Index: llvm/test/tools/llvm-objcopy/wasm/dump-section.test
===
--- llvm/test/tools/llvm-objcopy/wasm/dump-section.test
+++ llvm/test/tools/llvm-objcopy/wasm/dump-section.test
@@ -11,7 +11,7 @@
 # CHECK: 020 63 6c 61 6e 67 05 39 2e 30 2e 30
 
 # NONEXISTENT: section 'nonexistent' not found
-# DIROUT: error: {{.*}}/bar': {{[nN]}}o such file or directory
+# DIROUT: error: {{.*}}/bar': {{.*}}{{[nN]}}o such file or directory
 
 ## Check that dumping and removing a section works in the same invocation
 # RUN: llvm-objcopy --dump-section=producers=%t.sec --remove-section=producers %t %t2
Index: llvm/test/tools/llvm-lto/error.ll
===
--- llvm/test/tools/llvm-lto/error.ll
+++ llvm/test/tools/llvm-lto/error.ll
@@ -1,5 +1,5 @@
 ; RUN: not llvm-lto foobar 2>&1 | FileCheck %s
-; CHECK: llvm-lto: error loading file 'foobar': {{N|n}}o such file or directory
+; CHECK: llvm-lto: error loading file 'foobar': {{.*}}{{N|n}}o such file or directory
 
 ; RUN: not llvm-lto --list-symbols-only %S/Inputs/empty.bc 2>&1 | FileCheck %s --check-prefix=CHECK-LIST
 ; CHECK-LIST: llvm-lto: error loading file '{{.*}}/Inputs/empty.bc': The file was not recognized as a valid object file
Index: llvm/test/tools/llvm-lipo/replace-invalid-input.test
===
--- llvm/test/tools/llvm-lipo/replace-invalid-input.test
+++ llvm/test/tools/llvm-lipo/replace-invalid-input.test
@@ -12,7 +12,7 @@
 # INPUT_ARGS: error: replace expects a single input file
 
 # RUN: not llvm-lipo %t-universal.o -replace i386 %t-33.o  -o %t.o 2>&1 | FileCheck --check-prefix=INVALID_FILE %s
-# INVALID_FILE: {{[nN]}}o such file or directory
+# INVALID_FILE: {{.*}}{{[nN]}}o such file or directory
 
 # RUN: not llvm-lipo %t-universal.o -replace i3866 %t-32.o -o %t.o 2>&1 | FileCheck --check-prefix=INVALID_ARCH %s
 # INVALID_ARCH: error: Invalid architecture: i3866
Index: llvm/test/tools/llvm-lipo/create-arch.test
===
--- llvm/test/tools/llvm-lipo/create-arch.test
+++ llvm/test/tools/llvm-lipo/create-arch.test
@@ -14,4 +14,4 @@
 # INVALID_ARCH: error: Invalid architecture: i3866
 #
 # RUN: not llvm-lipo -arch i386 %t-33.o -create -o /dev/null 2>&1 | FileCheck --check-prefix=INVALID_FILE %s
-# INVALID_FILE: {{[nN]}}o such file or directory
+# INVALID_FILE: {{.*}}{{[nN]}}o such file or directory
Index: llvm/test/tools/llvm-libtool-darwin/invalid-input-output-args.test
===
--- llvm/test/tools/llvm-libtool-darwin/invalid-input-output-args.test
+++ llvm/test/tools/llvm-libtool-darwin/invalid-input-output-args.test
@@ -28,7 +28,7 @@
 # RUN: not llvm-libtool-darwin -static -o %t.lib %t.missing 2>&1 | \
 # RUN:   FileCheck %s --check-prefix=NO-FILE -DFILE=%t.missing
 
-# NO-FILE: error: '[[FILE]]': {{[nN]}}o such file or directory
+# NO-FILE: error: '[[FILE]]': {{.*}}{{[nN]}}o such file or directory
 

[PATCH] D92808: [ObjC][ARC] Annotate calls with attributes instead of emitting retainRV or claimRV calls in the IR

2021-01-22 Thread Akira Hatanaka via Phabricator via cfe-commits
ahatanak added inline comments.



Comment at: clang/lib/CodeGen/CGObjC.cpp:2342
+attrs = attrs.addAttribute(CGF.getLLVMContext(),
+   llvm::AttributeList::ReturnIndex, "rv_marker");
+callBase->setAttributes(attrs);

rjmccall wrote:
> ahatanak wrote:
> > rjmccall wrote:
> > > It's weird that these attributes use two different capitalization styles. 
> > >  Also, why are they both needed?  Did you consider making the role 
> > > (retain/claim) be the value of the attribute rather than a separate 
> > > attribute?
> > > 
> > > Should the attribute be namespaced, like `clang.arc.rv_marker`?
> > > 
> > > Let's go ahead and add globals for these strings so we can refer to them 
> > > symbolically, like you did with `retainRVMarkerKey`.  Is there an LLVM 
> > > header for ARC optimization we could reasonably pull them from, or are we 
> > > doomed to repeat ourselves across projects?
> > I think you are asking why both `retain/claim` and `rv_marker` are needed? 
> > Or are you asking why both 'retain' and 'claim' are needed?
> > 
> > We could do without `clang.arc.rv_marker` and just use 
> > `clang.arc.rv=retain/claim` since the middle-end and backend passes can 
> > easily determine whether a marker is needed or not. The only drawback to 
> > using only `clang.arc.rv` I can think of is that it's no longer possible to 
> > tell whether an instruction is implicitly followed by marker+retain/claimRV 
> > or just the marker, which makes `Instruction::mayWriteToMemory` return a 
> > conservative answer if the function call is read-only. A read-only call 
> > cannot be treated as read-only if it's followed by marker+retain/claimRV, 
> > but it is still read-only if it is followed just by the marker.
> > 
> > Note that ARC contract pass emits the retain/claimRV instruction into the 
> > IR and drops the corresponding `clang.arc.rv` attribute but doesn't remove 
> > the `clang.arc.rv_marker` attribute. So if we used only `clang.arc.rv`, a 
> > call annotated with the attribute would be implicitly followed by 
> > marker+retain/claimRV before ARC contract, while it would be followed by 
> > just the marker after ARC contract, but `Instruction::mayWriteToMemory` 
> > wouldn't' be able to tell the difference.
> > I think you are asking why both retain/claim and rv_marker are needed?
> 
> Yes.
> 
> > We could do without clang.arc.rv_marker and just use 
> > clang.arc.rv=retain/claim since the middle-end and backend passes can 
> > easily determine whether a marker is needed or not. The only drawback to 
> > using only clang.arc.rv I can think of is that it's no longer possible to 
> > tell whether an instruction is implicitly followed by marker+retain/claimRV 
> > or just the marker, which makes Instruction::mayWriteToMemory return a 
> > conservative answer if the function call is read-only. A read-only call 
> > cannot be treated as read-only if it's followed by marker+retain/claimRV, 
> > but it is still read-only if it is followed just by the marker.
> 
> Is there a situation where we emit the marker but not a following call?  Or 
> is that just in the places where we've already made the following call 
> explicit in IR?  Because in the latter case, presumably the following call 
> will still act as a barrier to anything that's querying `mayWriteToMemory`, 
> right?  (That is: in general, I expect that nobody just asks whether a 
> specific instruction can write to memory, they ask if any of the instructions 
> in a region can write to memory, and since the following call can...)
I think you are right. The retainRV/claimRV instruction that follows the 
annotated call will act as a barrier, so using `clang.arc.rv_marker` to 
distinguish between marker+retain/claimRV and marker only probably won't help 
the optimizations in practice.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D92808

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


[PATCH] D95246: [SystemZ][z/OS] Fix No such file or directory expression error matching in lit tests - continued

2021-01-22 Thread Muiez Ahmed via Phabricator via cfe-commits
muiez accepted this revision.
muiez added a comment.
This revision is now accepted and ready to land.

LGTM


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D95246

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


[PATCH] D95168: Add InsertBraces option

2021-01-22 Thread Tiago Macarios via Phabricator via cfe-commits
tiagoma added inline comments.



Comment at: clang/docs/ClangFormatStyleOptions.rst:2254
+
+  * ``BIS_WrapLikely`` (in configuration: ``WrapLikely``)
+Insert braces if wrapping is likely

curdeius wrote:
> Shouldn't it be consistent with clang-tidy? So instead of an enum, this 
> option might take a number of lines that will trigger brace insertion? None 
> may be sth like -1. "Likely" is very vague.
I am not sure this is possible. clang-tidy assumes the code is already 
formatted, we cannot assume that in clang-format. This pass runs before the 
formatter pass, so basing the behavior on line count would lead to different 
behavior across runs. For example:

Assuming we can set this option to 2 lines and we have the following code:


```
if (condition)
very_long_line_that_will_wrap(arg, arg, arg ,arg)
```

first run:


```
if (condition)
very_long_line_that_will_wrap(
arg, arg, arg ,arg)
```

second run:


```
if (condition) {
very_long_line_that_will_wrap(
arg, arg, arg ,arg)}
}
```

Likely is indeed vague by design. We "guess" that it will wrap in the formatter 
pass based on the current column value. See Format.cpp @ 1707. What might 
happen is that the line is incorrectly indentented and the wrapping never 
actually happens.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D95168

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


[PATCH] D94844: [VFS] Add support to RedirectingFileSystem for mapping a virtual directory to one in the external FS.

2021-01-22 Thread Jonas Devlieghere via Phabricator via cfe-commits
JDevlieghere added a comment.

Overall this looks good. I wonder if abstracting the ExternalRedirect as a 
small wrapper class around a SmallString would help. There's a few operations 
that are repeated, like the example below, and it could also house the logic 
that's currently in the lambda.

  if (ExternalRedirect.empty()) {
assert(RE->getKind() == RedirectingFileSystem::EK_File);
ExternalRedirect = RE->getExternalContentsPath();
  }

One thing I found tricky during the review was differentiating between places 
where the ExternalRedirect was computed and uses. Looking at the signatures the 
`lookupPath` functions are computing it and `status` is consuming it, although 
the latter then changes the StringRef (which I guess shouldn't persist?). I 
don't know if the wrapper could alleviate this as well.




Comment at: llvm/include/llvm/Support/VirtualFileSystem.h:564
 ///
+/// Re-mapped directories are represented as
+/// /// \verbatim

I think we should expand on this a bit more to contrast a directory-remapped 
directory vs a file-remapped directory (for a lack of better term). 
Specifically, an empty file-remapped directory could be confusing, as it 
behaves quite differently but looks pretty similar in YAML. 

```
{
  'type': 'file',
  'name': ,
  'external-contents': 
}
```

```
{
  'type': 'directory',
  'name': ,
  'contents': []
}
```

Looking at the two, I wonder if there would be any benefit to changing the 
`type` in the yaml to match the `NameKind`.






Comment at: llvm/include/llvm/Support/VirtualFileSystem.h:624
+
+/// whether to use the external path as the name for this file or 
directory.
+bool useExternalName(bool GlobalUseExternalName) const {

nit: s/whether/Whether/



Comment at: llvm/include/llvm/Support/VirtualFileSystem.h:776-778
   /// Looks up \p Path in \c Roots.
-  ErrorOr lookupPath(const Twine &Path) const;
+  ErrorOr lookupPath(const Twine &Path,
+  SmallVectorImpl &ExternalRedirect) const;

dexonsmith wrote:
> It's not entirely clear what the extra parameters do / when they're filled in 
> / etc; can you add a bit more documentation?
> 
> Also, I see that the public caller ignores the `ExternalRedirect` parameter. 
> I wonder if this should be renamed to `lookupPathWithName` or 
> `lookupPathImpl`, leaving behind a `lookupPath` wrapper that creates the 
> ignored buffer for the public interface... no strong opinion though.
+1.


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

https://reviews.llvm.org/D94844

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


Re: [PATCH] D70701: Fix more VFS tests on Windows

2021-01-22 Thread Adrian McCarthy via cfe-commits
BTW, I hope I didn't come across as overly negative in my previous
response.  I'd love to see the situation improved.  I just don't know what
that would look like.

> One thing I see, but wasn't obvious from your description, is that the
mixed/hybrid separator behaviour only happens for `defined(_WIN_32)`.
> [copy of `is_separator` elided]

It's a runtime decision based on the specified style, not a compile-time
one based on _WIN_32.  If the caller of `is_separator` passes
`Style::windows` then it'll accept either `/` or `\\`, even if LLVM was
compiled and run on Linux or Mac.  I believe there's a VFS test that
redirects a Windows-style path to a Posix-style one (an in-memory file
system), and that test passes on both kinds of hosts.

But I get the gist of the point.  My feeling is that, unless we can
eliminate hybrid styles, Paths should support a Style::hybrid.  It would be
messy because more ambiguities about how to map things crop up.

> Honestly, I'm not sure we have a good definition of what makeAbsolute
> should do.

I should have said:  **I** don't have a good understanding of what
makeAbsolute should do.  Even saying it should prepend the current working
directory is an incomplete answer.  On Windows, a process can have multiple
current directories:  one for each drive.  And a process has one current
drive.  So the current working directory is the current directory for the
current drive.  A Windows path like "D:foo.txt" is a relative path.
Literally prepending the current working directory gives us
`C:\users\me\D:foo.txt`, which is syntactically wrong.  But even if we're
smart enough to fix up the syntax, we'd get `C:\users\me\foo.txt` or
`D:\users\me\foo.txt`, both of which would (likely) be wrong.  The way the
OS would resolve it is to look up the process's current directory for the
D: drive, and insert that into the missing bit.

Anyway, I look forward to any and all proposals to improve this situation.


On Thu, Jan 21, 2021 at 6:47 PM Duncan P. N. Exon Smith via Phabricator <
revi...@reviews.llvm.org> wrote:

> dexonsmith added a comment.
>
> Thanks for the quick and detailed response!
>
> Your explanation of hybrid behaviour on Windows was especially helpful, as
> I didn't fully understand how that worked before.
>
> One thing I see, but wasn't obvious from your description, is that the
> mixed/hybrid separator behaviour only happens for `defined(_WIN_32)`. E.g.,
> from Path.cpp:
>
>   bool is_separator(char value, Style style) {
> if (value == '/')
>   return true;
> if (real_style(style) == Style::windows)
>   return value == '\\';
> return false;
>   }
>
>
>
> In D70701#2514143 , @amccarth
> wrote:
>
> >> - The path style is detected when reading the YAML file (as now).
> >
> > Which path's style?  The virtual one that's going to be redirected or the
> > actual one it's redirected at?
>
> Both, but you've mostly convinced me not to go down this route.
>
> > - Paths in the YAML file are canonicalized to native at parse time.
> >
> > If we canonicalize the virtual path, VFS would no longer be valuable for
> > creating platform-agnostic tests.
>
> This is a good point I hadn't considered.
>
> > In LLDB, we have the additional wrinkle of remote debugging, where the
> > debugger may be running on a Windows machine while the program being
> > debugged is running on a Linux box.  You always have to know whether a
> path
> > will be used on the debugger host or the debuggee host.  And there are
> > similar concerns for post-mortem debugging from a crash collected on a
> > different type of host.
>
> Ah, interesting.
>
> > Honestly, I'm not sure we have a good definition of what makeAbsolute
> > should do.
>
> Perhaps the name isn't ideal --
> `prependRelativePathsWithCurrentWorkingDirectory()` would be more precise
> -- but otherwise I'm not sure I fully agree. Regardless, I acknowledge your
> point that the two worlds are awkwardly different.
>
> I'm going to think about other options; thanks again for your feedback. I
> am still leaning toward `FileSystem::makeAbsolute()` not being virtual /
> overridden, but I have a better idea of how to approach that. One idea is
> for the `RedirectingFileSystem` to keep track of where different styles
> were used when parsing I'm not sure if that'll pan out though.
>
>
> Repository:
>   rG LLVM Github Monorepo
>
> CHANGES SINCE LAST ACTION
>   https://reviews.llvm.org/D70701/new/
>
> https://reviews.llvm.org/D70701
>
>
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D95168: [clang-format] Add InsertBraces option

2021-01-22 Thread Tiago Macarios via Phabricator via cfe-commits
tiagoma updated this revision to Diff 318563.
tiagoma added a comment.

Update comments


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D95168

Files:
  clang/docs/ClangFormatStyleOptions.rst
  clang/include/clang/Format/Format.h
  clang/lib/Format/Format.cpp
  clang/unittests/Format/FormatTest.cpp

Index: clang/unittests/Format/FormatTest.cpp
===
--- clang/unittests/Format/FormatTest.cpp
+++ clang/unittests/Format/FormatTest.cpp
@@ -14749,6 +14749,12 @@
   CHECK_PARSE("IndentExternBlock: false", IndentExternBlock,
   FormatStyle::IEBS_NoIndent);
 
+  Style.InsertBraces = FormatStyle::BIS_Never;
+  CHECK_PARSE("InsertBraces: Always", InsertBraces, FormatStyle::BIS_Always);
+  CHECK_PARSE("InsertBraces: WrapLikely", InsertBraces,
+  FormatStyle::BIS_WrapLikely);
+  CHECK_PARSE("InsertBraces: Never", InsertBraces, FormatStyle::BIS_Never);
+
   Style.BitFieldColonSpacing = FormatStyle::BFCS_None;
   CHECK_PARSE("BitFieldColonSpacing: Both", BitFieldColonSpacing,
   FormatStyle::BFCS_Both);
@@ -17890,6 +17896,105 @@
 "}",
 format(Source, Style));
 }
+
+TEST_F(FormatTest, InsertBraces) {
+  FormatStyle Style = getLLVMStyle();
+  StringRef IfSourceShort = "if (condition)\n"
+"  call_function(arg, arg);";
+  EXPECT_EQ(IfSourceShort, format(IfSourceShort, Style));
+
+  StringRef IfSourceLong = "if (condition)\n"
+   "  call_function(arg, arg, arg, arg, arg, arg);";
+  EXPECT_EQ(IfSourceLong, format(IfSourceLong, Style));
+
+  StringRef IfElseSourceShort = "if (condition)\n"
+"  a_function(arg, arg);\n"
+"else\n"
+"  another_function(arg, arg);";
+  EXPECT_EQ(IfElseSourceShort, format(IfElseSourceShort, Style));
+
+  StringRef IfElseSourceLong =
+  "if (condition)\n"
+  "  a_function(arg, arg, arg, arg, arg, arg);\n"
+  "else\n"
+  "  another_function(arg, arg, arg, arg, arg, arg);";
+  EXPECT_EQ(IfElseSourceLong, format(IfElseSourceLong, Style));
+
+  StringRef ForSourceShort = "for (auto val : container)\n"
+ "  call_function(arg, arg);";
+  EXPECT_EQ(ForSourceShort, format(ForSourceShort, Style));
+
+  StringRef ForSourceLong = "for (auto val : container)\n"
+"  call_function(arg, arg, arg, arg, arg, arg);";
+  EXPECT_EQ(ForSourceLong, format(ForSourceLong, Style));
+
+  Style.InsertBraces = FormatStyle::BIS_Always;
+
+  EXPECT_EQ("if (condition) {\n"
+"  call_function(arg, arg);\n"
+"}",
+format(IfSourceShort, Style));
+
+  EXPECT_EQ("if (condition) {\n"
+"  call_function(arg, arg, arg, arg, arg, arg);\n"
+"}",
+format(IfSourceLong, Style));
+
+  EXPECT_EQ("if (condition) {\n"
+"  a_function(arg, arg);\n"
+"} else {\n"
+"  another_function(arg, arg);\n"
+"}",
+format(IfElseSourceShort, Style));
+
+  EXPECT_EQ("if (condition) {\n"
+"  a_function(arg, arg, arg, arg, arg, arg);\n"
+"} else {\n"
+"  another_function(arg, arg, arg, arg, arg, arg);\n"
+"}",
+format(IfElseSourceLong, Style));
+
+  EXPECT_EQ("for (auto val : container) {\n"
+"  call_function(arg, arg);\n"
+"}",
+format(ForSourceShort, Style));
+
+  EXPECT_EQ("for (auto val : container) {\n"
+"  call_function(arg, arg, arg, arg, arg, arg);\n"
+"}",
+format(ForSourceLong, Style));
+
+  Style.InsertBraces = FormatStyle::BIS_WrapLikely;
+  Style.ColumnLimit = 35;
+
+  EXPECT_EQ(IfSourceShort, format(IfSourceShort, Style));
+
+  EXPECT_EQ("if (condition) {\n"
+"  call_function(arg, arg, arg, arg,\n"
+"arg, arg);\n"
+"}",
+format(IfSourceLong, Style));
+
+  EXPECT_EQ(IfElseSourceShort, format(IfElseSourceShort, Style));
+
+  EXPECT_EQ("if (condition) {\n"
+"  a_function(arg, arg, arg, arg,\n"
+" arg, arg);\n"
+"} else {\n"
+"  another_function(arg, arg, arg,\n"
+"   arg, arg, arg);\n"
+"}",
+format(IfElseSourceLong, Style));
+
+  EXPECT_EQ(ForSourceShort, format(ForSourceShort, Style));
+
+  EXPECT_EQ("for (auto val : container) {\n"
+"  call_function(arg, arg, arg, arg,\n"
+"arg, arg);\n"
+"}",
+format(ForSourceLong, Style));
+}
+
 } // namespace
 } // namespace format
 } // namespace clang
Index: clang/lib/Format/Format.cpp
===
--- clang/lib/Format/Format.cpp
+++ clang/lib/Format

[PATCH] D94614: [FPEnv][X86] Platform builtins edition: clang should get from the AST the metadata for constrained FP builtins

2021-01-22 Thread Kevin P. Neal via Phabricator via cfe-commits
kpn updated this revision to Diff 318567.
kpn added a comment.

Update for review comments: Move uses of CGFPOptionsRAII lower and closer to 
where they are needed. This should be less error prone as well.


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

https://reviews.llvm.org/D94614

Files:
  clang/lib/CodeGen/CGBuiltin.cpp
  clang/test/CodeGen/X86/avx-builtins-constrained-cmp.c
  clang/test/CodeGen/X86/avx512dq-builtins-constrained.c
  clang/test/CodeGen/X86/avx512f-builtins-constrained.c
  clang/test/CodeGen/X86/fma-builtins-constrained.c
  clang/test/CodeGen/X86/sse-builtins-constrained.c

Index: clang/test/CodeGen/X86/sse-builtins-constrained.c
===
--- clang/test/CodeGen/X86/sse-builtins-constrained.c
+++ clang/test/CodeGen/X86/sse-builtins-constrained.c
@@ -1,8 +1,15 @@
 // REQUIRES: x86-registered-target
 // RUN: %clang_cc1 -ffreestanding %s -triple=x86_64-unknown-linux-gnu -target-feature +sse -emit-llvm -o - -Wall -Werror | FileCheck %s --check-prefix=UNCONSTRAINED --check-prefix=COMMON --check-prefix=COMMONIR
-// RUN: %clang_cc1 -ffreestanding %s -triple=x86_64-unknown-linux-gnu -target-feature +sse -ffp-exception-behavior=strict -emit-llvm -o - -Wall -Werror | FileCheck %s --check-prefix=CONSTRAINED --check-prefix=COMMON --check-prefix=COMMONIR
+// RUN: %clang_cc1 -ffreestanding %s -triple=x86_64-unknown-linux-gnu -target-feature +sse -ffp-exception-behavior=maytrap -DSTRICT=1 -emit-llvm -o - -Wall -Werror | FileCheck %s --check-prefix=CONSTRAINED --check-prefix=COMMON --check-prefix=COMMONIR
 // RUN: %clang_cc1 -ffreestanding %s -triple=x86_64-unknown-linux-gnu -target-feature +sse -S %s -o - -Wall -Werror | FileCheck %s --check-prefix=CHECK-ASM --check-prefix=COMMON
-// RUN: %clang_cc1 -ffreestanding %s -triple=x86_64-unknown-linux-gnu -target-feature +sse -ffp-exception-behavior=strict -S %s -o - -Wall -Werror | FileCheck %s --check-prefix=CHECK-ASM --check-prefix=COMMON
+// RUN: %clang_cc1 -ffreestanding %s -triple=x86_64-unknown-linux-gnu -target-feature +sse -ffp-exception-behavior=maytrap -DSTRICT=1 -S %s -o - -Wall -Werror | FileCheck %s --check-prefix=CHECK-ASM --check-prefix=COMMON
+
+#ifdef STRICT
+// Test that the constrained intrinsics are picking up the exception
+// metadata from the AST instead of the global default from the command line.
+
+#pragma float_control(except, on)
+#endif
 
 
 #include 
Index: clang/test/CodeGen/X86/fma-builtins-constrained.c
===
--- clang/test/CodeGen/X86/fma-builtins-constrained.c
+++ clang/test/CodeGen/X86/fma-builtins-constrained.c
@@ -1,8 +1,15 @@
 // REQUIRES: x86-registered-target
 // RUN: %clang_cc1 -ffreestanding %s -triple=x86_64-unknown-linux-gnu -target-feature +fma -O2 -emit-llvm -o - | FileCheck %s --check-prefixes=COMMON,COMMONIR,UNCONSTRAINED
-// RUN: %clang_cc1 -ffreestanding %s -triple=x86_64-unknown-linux-gnu -target-feature +fma -ffp-exception-behavior=strict -O2 -emit-llvm -o - | FileCheck %s --check-prefixes=COMMON,COMMONIR,CONSTRAINED
+// RUN: %clang_cc1 -ffreestanding %s -triple=x86_64-unknown-linux-gnu -target-feature +fma -ffp-exception-behavior=maytrap -DSTRICT=1 -O2 -emit-llvm -o - | FileCheck %s --check-prefixes=COMMON,COMMONIR,CONSTRAINED
 // RUN: %clang_cc1 -ffreestanding %s -triple=x86_64-unknown-linux-gnu -target-feature +fma -O2 -S -o - | FileCheck %s --check-prefixes=COMMON,CHECK-ASM
-// RUN: %clang_cc1 -ffreestanding %s -triple=x86_64-unknown-linux-gnu -target-feature +fma -O2 -ffp-exception-behavior=strict -S -o - | FileCheck %s --check-prefixes=COMMON,CHECK-ASM
+// RUN: %clang_cc1 -ffreestanding %s -triple=x86_64-unknown-linux-gnu -target-feature +fma -O2 -ffp-exception-behavior=maytrap -DSTRICT=1 -S -o - | FileCheck %s --check-prefixes=COMMON,CHECK-ASM
+
+#ifdef STRICT
+// Test that the constrained intrinsics are picking up the exception
+// metadata from the AST instead of the global default from the command line.
+
+#pragma float_control(except, on)
+#endif
 
 #include 
 
Index: clang/test/CodeGen/X86/avx512f-builtins-constrained.c
===
--- clang/test/CodeGen/X86/avx512f-builtins-constrained.c
+++ clang/test/CodeGen/X86/avx512f-builtins-constrained.c
@@ -1,10 +1,17 @@
 // REQUIRES: x86-registered-target
 // RUN: %clang_cc1 -fexperimental-new-pass-manager -flax-vector-conversions=none -ffreestanding %s -triple=x86_64-unknown-linux-gnu -target-feature +avx512f -emit-llvm -o - -Wall -Werror | FileCheck --check-prefix=COMMON --check-prefix=COMMONIR --check-prefix=UNCONSTRAINED %s
 // RUN: %clang_cc1 -fexperimental-new-pass-manager -flax-vector-conversions=none -fms-extensions -fms-compatibility -ffreestanding %s -triple=x86_64-windows-msvc -target-feature +avx512f -emit-llvm -o - -Wall -Werror | FileCheck --check-prefix=COMMON --check-prefix=COMMONIR --check-prefix=UNCONSTRAINED %s
-// RUN: %clang_cc1 -fexpe

[PATCH] D94919: [clangd] Fix a crash when indexing invalid ObjC method declaration

2021-01-22 Thread Adam Czachorowski via Phabricator via cfe-commits
adamcz added a comment.

The crash happens while indexing the file, not during code completion. The code 
completion tests generally specify a cursor position, but in this case it is 
not relevant and could confuse the reader. This seemed like a logical place for 
indexing bug, in the spirit of using minimal repro case (i.e. you don't need to 
trigger code completion at all)


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D94919

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


[PATCH] D94919: [clangd] Fix a crash when indexing invalid ObjC method declaration

2021-01-22 Thread David Goldman via Phabricator via cfe-commits
dgoldman accepted this revision.
dgoldman added a comment.
This revision is now accepted and ready to land.

In D94919#2515987 , @adamcz wrote:

> The crash happens while indexing the file, not during code completion. The 
> code completion tests generally specify a cursor position, but in this case 
> it is not relevant and could confuse the reader. This seemed like a logical 
> place for indexing bug, in the spirit of using minimal repro case (i.e. you 
> don't need to trigger code completion at all)

I see, thanks.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D94919

___
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-01-22 Thread Alex Orlov via Phabricator via cfe-commits
aorlov added a comment.

Please, look at my solution. Is it worth to be accepted?


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] D94942: [clangd] Add tweak for implementing abstract class

2021-01-22 Thread Nathan James via Phabricator via cfe-commits
njames93 added inline comments.



Comment at: clang-tools-extra/clangd/refactor/tweaks/ImplementAbstract.cpp:354
+  return "Implement pure virtual methods from '" +
+ FromBase->getType().getAsString() + "'";
+}

Maybe this should be changed as it currently prints the fully qualified type.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D94942

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


[PATCH] D95249: [NFC] Disallow unused prefixes in clang/test/Analysis

2021-01-22 Thread Mircea Trofin via Phabricator via cfe-commits
mtrofin created this revision.
mtrofin 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/D95249

Files:
  clang/test/Analysis/auto-obj-dtors-cfg-output.cpp
  clang/test/Analysis/cfg-rich-constructors.cpp
  clang/test/Analysis/cfg-rich-constructors.mm
  clang/test/Analysis/cfg.c
  clang/test/Analysis/exploded-graph-rewriter/trimmers.dot
  clang/test/Analysis/lit.local.cfg

Index: clang/test/Analysis/lit.local.cfg
===
--- clang/test/Analysis/lit.local.cfg
+++ clang/test/Analysis/lit.local.cfg
@@ -1,5 +1,5 @@
 # -*- Python -*- vim: set ft=python ts=4 sw=4 expandtab tw=79:
-
+from lit.llvm.subst import ToolSubst
 import site
 
 # Load the custom analyzer test format, which runs the test again with Z3 if it
@@ -26,3 +26,9 @@
 
 if not config.root.clang_staticanalyzer:
 config.unsupported = True
+
+fc = ToolSubst('FileCheck', unresolved='fatal')
+# Insert this first. Then, we'll first update the blank FileCheck command; then,
+# the default substitution of FileCheck will replace it to its full path.
+config.substitutions.insert(0, (fc.regex,
+'FileCheck --allow-unused-prefixes=false'))
Index: clang/test/Analysis/exploded-graph-rewriter/trimmers.dot
===
--- clang/test/Analysis/exploded-graph-rewriter/trimmers.dot
+++ clang/test/Analysis/exploded-graph-rewriter/trimmers.dot
@@ -1,17 +1,17 @@
 // RUN: %exploded_graph_rewriter %s \
 // RUN: | FileCheck %s -check-prefixes=ONE,TWO,THREE,FOUR
 // RUN: %exploded_graph_rewriter -s %s \
-// RUN: | FileCheck %s -check-prefixes=ONE,TWO,NOTHREE,FOUR
+// RUN: | FileCheck %s -check-prefixes=ONE,TWO,FOUR
 // RUN: %exploded_graph_rewriter --to=0x2 %s \
-// RUN: | FileCheck %s -check-prefixes=ONE,TWO,NOTHREE,NOFOUR
+// RUN: | FileCheck %s -check-prefixes=ONE,TWO
 // RUN: %exploded_graph_rewriter --to 2 %s \
-// RUN: | FileCheck %s -check-prefixes=ONE,TWO,NOTHREE,NOFOUR
+// RUN: | FileCheck %s -check-prefixes=ONE,TWO
 // RUN: %exploded_graph_rewriter --to 2,3 %s \
-// RUN: | FileCheck %s -check-prefixes=ONE,TWO,THREE,NOFOUR
+// RUN: | FileCheck %s -check-prefixes=ONE,TWO,THREE
 // RUN: %exploded_graph_rewriter --to 4 %s \
 // RUN: | FileCheck %s -check-prefixes=ONE,TWO,THREE,FOUR
 // RUN: %exploded_graph_rewriter --to 4 -s %s \
-// RUN: | FileCheck %s -check-prefixes=ONE,TWO,NOTHREE,FOUR
+// RUN: | FileCheck %s -check-prefixes=ONE,TWO,FOUR
 
 Node0x1 [shape=record,label=
  "{{ "state_id": 0, "program_state": null, "program_points": [
Index: clang/test/Analysis/cfg.c
===
--- clang/test/Analysis/cfg.c
+++ clang/test/Analysis/cfg.c
@@ -1,5 +1,5 @@
 // RUN: %clang_analyze_cc1 -analyzer-checker=debug.DumpCFG -triple x86_64-apple-darwin12 -fheinous-gnu-extensions %s > %t 2>&1
-// RUN: FileCheck --input-file=%t -check-prefixes=CHECK,WARNINGS %s
+// RUN: FileCheck --input-file=%t --check-prefix=CHECK %s
 
 // This file is the C version of cfg.cpp.
 // Tests that are C-specific should go into this file.
Index: clang/test/Analysis/cfg-rich-constructors.mm
===
--- clang/test/Analysis/cfg-rich-constructors.mm
+++ clang/test/Analysis/cfg-rich-constructors.mm
@@ -1,11 +1,11 @@
 // RUN: %clang_analyze_cc1 -analyzer-checker=debug.DumpCFG -triple x86_64-apple-darwin12 -std=c++11 -w %s > %t 2>&1
-// RUN: FileCheck --input-file=%t -check-prefixes=CHECK,CXX11,ELIDE,CXX11-ELIDE %s
+// RUN: FileCheck --input-file=%t -check-prefixes=CHECK,CXX11,CXX11-ELIDE %s
 // RUN: %clang_analyze_cc1 -analyzer-checker=debug.DumpCFG -triple x86_64-apple-darwin12 -std=c++17 -w %s > %t 2>&1
-// RUN: FileCheck --input-file=%t -check-prefixes=CHECK,CXX17,ELIDE,CXX17-ELIDE %s
+// RUN: FileCheck --input-file=%t -check-prefixes=CHECK,CXX17 %s
 // RUN: %clang_analyze_cc1 -analyzer-checker=debug.DumpCFG -triple x86_64-apple-darwin12 -std=c++11 -w -analyzer-config elide-constructors=false %s > %t 2>&1
-// RUN: FileCheck --input-file=%t -check-prefixes=CHECK,CXX11,NOELIDE,CXX11-NOELIDE %s
+// RUN: FileCheck --input-file=%t -check-prefixes=CHECK,CXX11,CXX11-NOELIDE %s
 // RUN: %clang_analyze_cc1 -analyzer-checker=debug.DumpCFG -triple x86_64-apple-darwin12 -std=c++17 -w -analyzer-config elide-constructors=false %s > %t 2>&1
-// RUN: FileCheck --input-file=%t -check-prefixes=CHECK,CXX17,NOELIDE,CXX17-NOELIDE %s
+// RUN: FileCheck --input-file=%t -check-prefixes=CHECK,CXX17 %s
 
 class D {
 public:
Index: clang/test/Analysis/cfg-rich-constructors.cpp
===
--- clang/test/Analysis/cfg-rich-constructors.cpp
+++ clang/test/Analysis/cfg-rich-constructors.cpp
@@ -1,11 +1,11 @@
 // RUN: %clang_analyze_cc1 -analyzer-checker=debug.DumpCFG -triple x86_64-

[PATCH] D94355: [SimplifyCFG] Add relative switch lookup tables

2021-01-22 Thread Leonard Chan via Phabricator via cfe-commits
leonardchan added a comment.

Almost there! Just a few more comments on my end.




Comment at: llvm/lib/Transforms/Utils/SimplifyCFG.cpp:5694
+Constant *CaseRes = Values[I].second;
+if (auto *GlobalVal = dyn_cast(CaseRes))
+  if (!GlobalVal->isDSOLocal())

I think we should also return false if it doesn't turn out to be a GlobalValue 
here.



Comment at: 
llvm/test/Transforms/SimplifyCFG/X86/switch_to_relative_lookup_table.ll:201-203
+; If there is a lookup table, where each element contains the same value,
+; a relative lookup should not be generated
+define void @single_value(i32 %cond)  {

It looks like this might not be testing what the comment says it should. It 
looks like in the phi statements below that each of the cases have different 
values. I think maybe you'll want something like:

```
  %str1.0 = phi i8* [ getelementptr inbounds ([5 x i8], [5 x i8]* @.str, i64 0, 
i64 0), %sw.default ], [ getelementptr inbounds ([5 x i8], [5 x i8]* @.str, i64 
0, i64 0), %sw.bb2 ], [ getelementptr inbounds ([5 x i8], [5 x i8]* @.str, i64 
0, i64 0), %sw.bb1 ], [ getelementptr inbounds ([5 x i8], [5 x i8]* @.str, i64 
0, i64 0), %entry ]
  ret i8* %str1.0  ; instead of `ret void` to ensure the `%str1.0` isn't 
optimized out
```

Then ensure this just lowers directly to a GEP for `@.str` and no lookup table 
is generated.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D94355

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


[PATCH] D95246: [SystemZ][z/OS] Fix No such file or directory expression error matching in lit tests - continued

2021-01-22 Thread Abhina Sree via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG520b5ecf8561: [SystemZ][z/OS] Fix No such file or directory 
expression error matching in lit… (authored by abhina.sreeskantharajan).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D95246

Files:
  clang/test/Driver/clang-offload-bundler.c
  clang/test/Frontend/output-failures.c
  llvm/test/Object/archive-extract-dir.test
  llvm/test/Object/archive-extract.test
  llvm/test/Object/directory.ll
  llvm/test/tools/llvm-ar/error-opening-directory.test
  llvm/test/tools/llvm-ar/move.test
  llvm/test/tools/llvm-ar/print.test
  llvm/test/tools/llvm-ar/quick-append.test
  llvm/test/tools/llvm-libtool-darwin/invalid-input-output-args.test
  llvm/test/tools/llvm-lipo/create-arch.test
  llvm/test/tools/llvm-lipo/replace-invalid-input.test
  llvm/test/tools/llvm-lto/error.ll
  llvm/test/tools/llvm-objcopy/wasm/dump-section.test
  llvm/test/tools/llvm-symbolizer/pdb/missing_pdb.test

Index: llvm/test/tools/llvm-symbolizer/pdb/missing_pdb.test
===
--- llvm/test/tools/llvm-symbolizer/pdb/missing_pdb.test
+++ llvm/test/tools/llvm-symbolizer/pdb/missing_pdb.test
@@ -4,7 +4,7 @@
 
 llvm-symbolizer should print one error and two unknown line info records.
 
-ERROR: LLVMSymbolizer: error reading file: {{.*}}: {{N|n}}o such file or directory
+ERROR: LLVMSymbolizer: error reading file: {{.*}}: {{.*}}{{N|n}}o such file or directory
 ERROR-NOT: error reading file
 
 CHECK: ??
Index: llvm/test/tools/llvm-objcopy/wasm/dump-section.test
===
--- llvm/test/tools/llvm-objcopy/wasm/dump-section.test
+++ llvm/test/tools/llvm-objcopy/wasm/dump-section.test
@@ -11,7 +11,7 @@
 # CHECK: 020 63 6c 61 6e 67 05 39 2e 30 2e 30
 
 # NONEXISTENT: section 'nonexistent' not found
-# DIROUT: error: {{.*}}/bar': {{[nN]}}o such file or directory
+# DIROUT: error: {{.*}}/bar': {{.*}}{{[nN]}}o such file or directory
 
 ## Check that dumping and removing a section works in the same invocation
 # RUN: llvm-objcopy --dump-section=producers=%t.sec --remove-section=producers %t %t2
Index: llvm/test/tools/llvm-lto/error.ll
===
--- llvm/test/tools/llvm-lto/error.ll
+++ llvm/test/tools/llvm-lto/error.ll
@@ -1,5 +1,5 @@
 ; RUN: not llvm-lto foobar 2>&1 | FileCheck %s
-; CHECK: llvm-lto: error loading file 'foobar': {{N|n}}o such file or directory
+; CHECK: llvm-lto: error loading file 'foobar': {{.*}}{{N|n}}o such file or directory
 
 ; RUN: not llvm-lto --list-symbols-only %S/Inputs/empty.bc 2>&1 | FileCheck %s --check-prefix=CHECK-LIST
 ; CHECK-LIST: llvm-lto: error loading file '{{.*}}/Inputs/empty.bc': The file was not recognized as a valid object file
Index: llvm/test/tools/llvm-lipo/replace-invalid-input.test
===
--- llvm/test/tools/llvm-lipo/replace-invalid-input.test
+++ llvm/test/tools/llvm-lipo/replace-invalid-input.test
@@ -12,7 +12,7 @@
 # INPUT_ARGS: error: replace expects a single input file
 
 # RUN: not llvm-lipo %t-universal.o -replace i386 %t-33.o  -o %t.o 2>&1 | FileCheck --check-prefix=INVALID_FILE %s
-# INVALID_FILE: {{[nN]}}o such file or directory
+# INVALID_FILE: {{.*}}{{[nN]}}o such file or directory
 
 # RUN: not llvm-lipo %t-universal.o -replace i3866 %t-32.o -o %t.o 2>&1 | FileCheck --check-prefix=INVALID_ARCH %s
 # INVALID_ARCH: error: Invalid architecture: i3866
Index: llvm/test/tools/llvm-lipo/create-arch.test
===
--- llvm/test/tools/llvm-lipo/create-arch.test
+++ llvm/test/tools/llvm-lipo/create-arch.test
@@ -14,4 +14,4 @@
 # INVALID_ARCH: error: Invalid architecture: i3866
 #
 # RUN: not llvm-lipo -arch i386 %t-33.o -create -o /dev/null 2>&1 | FileCheck --check-prefix=INVALID_FILE %s
-# INVALID_FILE: {{[nN]}}o such file or directory
+# INVALID_FILE: {{.*}}{{[nN]}}o such file or directory
Index: llvm/test/tools/llvm-libtool-darwin/invalid-input-output-args.test
===
--- llvm/test/tools/llvm-libtool-darwin/invalid-input-output-args.test
+++ llvm/test/tools/llvm-libtool-darwin/invalid-input-output-args.test
@@ -28,7 +28,7 @@
 # RUN: not llvm-libtool-darwin -static -o %t.lib %t.missing 2>&1 | \
 # RUN:   FileCheck %s --check-prefix=NO-FILE -DFILE=%t.missing
 
-# NO-FILE: error: '[[FILE]]': {{[nN]}}o such file or directory
+# NO-FILE: error: '[[FILE]]': {{.*}}{{[nN]}}o such file or directory
 
 ## Input file is not an object file:
 # RUN: touch %t.invalid
Index: llvm/test/tools/llvm-ar/quick-append.test
===
--- llvm/test/tools/llvm-ar/quick-append.test
+++ llvm/test/tools/llvm-ar/quick-append.test
@@ -60,7 +60,7 @@
 # RU

[clang] 520b5ec - [SystemZ][z/OS] Fix No such file or directory expression error matching in lit tests - continued

2021-01-22 Thread Abhina Sreeskantharajan via cfe-commits

Author: Abhina Sreeskantharajan
Date: 2021-01-22T13:54:25-05:00
New Revision: 520b5ecf856152f35ee38207eec39f5674dd2bd4

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

LOG: [SystemZ][z/OS] Fix No such file or directory expression error matching in 
lit tests - continued

This is a continuation of https://reviews.llvm.org/D94239. I missed some other 
spellings of the same error.

Reviewed By: muiez

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

Added: 


Modified: 
clang/test/Driver/clang-offload-bundler.c
clang/test/Frontend/output-failures.c
llvm/test/Object/archive-extract-dir.test
llvm/test/Object/archive-extract.test
llvm/test/Object/directory.ll
llvm/test/tools/llvm-ar/error-opening-directory.test
llvm/test/tools/llvm-ar/move.test
llvm/test/tools/llvm-ar/print.test
llvm/test/tools/llvm-ar/quick-append.test
llvm/test/tools/llvm-libtool-darwin/invalid-input-output-args.test
llvm/test/tools/llvm-lipo/create-arch.test
llvm/test/tools/llvm-lipo/replace-invalid-input.test
llvm/test/tools/llvm-lto/error.ll
llvm/test/tools/llvm-objcopy/wasm/dump-section.test
llvm/test/tools/llvm-symbolizer/pdb/missing_pdb.test

Removed: 




diff  --git a/clang/test/Driver/clang-offload-bundler.c 
b/clang/test/Driver/clang-offload-bundler.c
index 3e1fab25d754..f7428d7f02f4 100644
--- a/clang/test/Driver/clang-offload-bundler.c
+++ b/clang/test/Driver/clang-offload-bundler.c
@@ -72,7 +72,7 @@
 
 // RUN: not clang-offload-bundler -type=i 
-targets=host-%itanium_abi_triple,openmp-powerpc64le-ibm-linux-gnu,openmp-x86_64-pc-linux-gnu
 -inputs=%t.i,%t.tgt1,%t.tgt2.notexist -outputs=%t.bundle.i 2>&1 | FileCheck %s 
-DFILE=%t.tgt2.notexist --check-prefix CK-ERR5
 // RUN: not clang-offload-bundler -type=i 
-targets=host-%itanium_abi_triple,openmp-powerpc64le-ibm-linux-gnu,openmp-x86_64-pc-linux-gnu
 -outputs=%t.i,%t.tgt1,%t.tgt2 -inputs=%t.bundle.i.notexist -unbundle 2>&1 | 
FileCheck %s -DFILE=%t.bundle.i.notexist --check-prefix CK-ERR5
-// CK-ERR5: error: '[[FILE]]': {{N|n}}o such file or directory
+// CK-ERR5: error: '[[FILE]]': {{.*}}{{N|n}}o such file or directory
 
 // RUN: not clang-offload-bundler -type=invalid 
-targets=host-%itanium_abi_triple,openmp-powerpc64le-ibm-linux-gnu,openmp-x86_64-pc-linux-gnu
 -inputs=%t.i,%t.tgt1,%t.tgt2 -outputs=%t.bundle.i 2>&1 | FileCheck %s 
-DTYPE=invalid --check-prefix CK-ERR6
 // CK-ERR6: error: '[[TYPE]]': invalid file type specified

diff  --git a/clang/test/Frontend/output-failures.c 
b/clang/test/Frontend/output-failures.c
index 0e9ea63f8067..26d25fdbef36 100644
--- a/clang/test/Frontend/output-failures.c
+++ b/clang/test/Frontend/output-failures.c
@@ -1,4 +1,4 @@
 // RUN: not %clang_cc1 -emit-llvm -o %t.doesnotexist/somename %s 2> %t
 // RUN: FileCheck -check-prefix=OUTPUTFAIL -input-file=%t %s
 
-// OUTPUTFAIL: error: unable to open output file 
'{{.*}}doesnotexist{{.}}somename': '{{[nN]}}o such file or directory'
+// OUTPUTFAIL: error: unable to open output file 
'{{.*}}doesnotexist{{.}}somename': '{{.*}}{{[nN]}}o such file or 
directory{{.*}}'

diff  --git a/llvm/test/Object/archive-extract-dir.test 
b/llvm/test/Object/archive-extract-dir.test
index 5182a2f91411..d6a721c090b3 100644
--- a/llvm/test/Object/archive-extract-dir.test
+++ b/llvm/test/Object/archive-extract-dir.test
@@ -8,4 +8,4 @@ RUN: rm foo
 RUN: mkdir foo
 RUN: not llvm-ar x test.a foo 2>&1 | FileCheck %s
 
-CHECK: foo: {{[Ii]}}s a directory
+CHECK: foo: {{.*}}{{[Ii]}}s a directory{{.*}}

diff  --git a/llvm/test/Object/archive-extract.test 
b/llvm/test/Object/archive-extract.test
index 11ca12e3353b..589e8b8fe856 100644
--- a/llvm/test/Object/archive-extract.test
+++ b/llvm/test/Object/archive-extract.test
@@ -58,4 +58,4 @@ RUN: llvm-ar p %p/Inputs/thin.a evenlen | FileCheck %s 
--check-prefix=EVENLEN
 EVENLEN: evenlen
 
 RUN: not llvm-ar p %p/Inputs/thin-path.a t/test2.o 2>&1 | FileCheck %s 
--check-prefix=MISSING
-MISSING: error: {{N|n}}o such file or directory
+MISSING: error: {{.*}}{{N|n}}o such file or directory

diff  --git a/llvm/test/Object/directory.ll b/llvm/test/Object/directory.ll
index 3e9ac2ce202e..d9e340a587b1 100644
--- a/llvm/test/Object/directory.ll
+++ b/llvm/test/Object/directory.ll
@@ -1,6 +1,6 @@
 ;RUN: rm -rf %t && mkdir -p %t
 ;RUN: not llvm-ar r %t/test.a . 2>&1 | FileCheck %s
-;CHECK: .: {{I|i}}s a directory
+;CHECK: .: {{.*}}{{I|i}}s a directory{{.*}}
 
 ;RUN: rm -f %t/test.a
 ;RUN: touch %t/a-very-long-file-name

diff  --git a/llvm/test/tools/llvm-ar/error-opening-directory.test 
b/llvm/test/tools/llvm-ar/error-opening-directory.test
index c3068871230f..5a6491bd29c8 100644
--- a/llvm/test/tools/llvm-ar/error-opening-directory.test
+++ b/llvm/test/tools/llvm-ar/error-opening-directory.test
@@ -9,4 

[PATCH] D95187: [DebugInfo][CodeView] Use as the display name for lambdas.

2021-01-22 Thread Reid Kleckner via Phabricator via cfe-commits
rnk added a comment.

I see a variety of presubmit failures in Harbormaster that seem related, so 
make sure to check those.




Comment at: clang/include/clang/AST/Mangle.h:92
 
+  virtual StringRef getLambdaString(const CXXRecordDecl *Lambda) = 0;
+

I think I would prefer to have this return a number. I think CGDebugInfo should 
be responsible for the formatting of the display names, not the mangler. Both 
the MS and Itanium manglers have private methods for numbering internal linkage 
lambdas, and I think it would be reasonable to hook those up to a public 
virtual method.



Comment at: clang/lib/CodeGen/CGDebugInfo.cpp:320-321
 
   // The CodeView printer in LLVM wants to see the names of unnamed types: it 
is
   // used to reconstruct the fully qualified type names.
   if (CGM.getCodeGenOpts().EmitCodeView) {

I think this comment could be improved, and I think it would help address some 
of David's concerns in the previous patch about the format requirements of 
codeview.



Comment at: clang/test/CodeGenCXX/debug-info-gline-tables-only-codeview.cpp:13
 
+auto lambda1 = []() { return 1; };
+

Please add tests for a lambda in an inline function and one in a non-inline 
function. The inline lambda will be externally visible and have a mangling 
number, and the non-inline one will be internal, and will not have a mangling 
number. They should both get `` names, though.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D95187

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


[PATCH] D95253: [clang][Fuchsia] Add relative-vtables + asan multilibs

2021-01-22 Thread Leonard Chan via Phabricator via cfe-commits
leonardchan created this revision.
leonardchan added reviewers: phosek, mcgrathr.
leonardchan added a project: clang.
Herald added a subscriber: mgorny.
leonardchan requested review of this revision.

We're choosing to take an opt-in approach for landing Relative VTables, so 
we'll need asan-equivalent multilibs with relative vtables enabled. Afterwards, 
we can just flip the switch in our build.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D95253

Files:
  clang/cmake/caches/Fuchsia-stage2.cmake
  clang/lib/Driver/ToolChains/Fuchsia.cpp
  
clang/test/Driver/Inputs/basic_fuchsia_tree/lib/x86_64-fuchsia/c++/relative-vtables+asan+noexcept/libc++.so
  
clang/test/Driver/Inputs/basic_fuchsia_tree/lib/x86_64-fuchsia/c++/relative-vtables+asan/libc++.so
  clang/test/Driver/fuchsia.cpp

Index: clang/test/Driver/fuchsia.cpp
===
--- clang/test/Driver/fuchsia.cpp
+++ clang/test/Driver/fuchsia.cpp
@@ -96,10 +96,37 @@
 // RUN: -resource-dir=%S/Inputs/resource_dir_with_per_target_subdir \
 // RUN: -fuse-ld=lld 2>&1\
 // RUN: | FileCheck %s -check-prefixes=CHECK-MULTILIB-X86,CHECK-MULTILIB-RELATIVE-VTABLES-NOEXCEPT-X86
+// RUN: %clangxx %s -### --target=x86_64-fuchsia -fexperimental-relative-c++-abi-vtables -fsanitize=address \
+// RUN: -ccc-install-dir %S/Inputs/basic_fuchsia_tree/bin \
+// RUN: -resource-dir=%S/Inputs/resource_dir_with_per_target_subdir \
+// RUN: -fuse-ld=lld 2>&1\
+// RUN: | FileCheck %s -check-prefixes=CHECK-MULTILIB-X86,CHECK-MULTILIB-RELATIVE-VTABLES-ASAN-X86
+// RUN: %clangxx %s -### --target=x86_64-fuchsia -fexperimental-relative-c++-abi-vtables -fno-exceptions -fsanitize=address \
+// RUN: -ccc-install-dir %S/Inputs/basic_fuchsia_tree/bin \
+// RUN: -resource-dir=%S/Inputs/resource_dir_with_per_target_subdir \
+// RUN: -fuse-ld=lld 2>&1\
+// RUN: | FileCheck %s -check-prefixes=CHECK-MULTILIB-X86,CHECK-MULTILIB-RELATIVE-VTABLES-ASAN-NOEXCEPT-X86
+// RUN: %clangxx %s -### --target=x86_64-fuchsia -fno-experimental-relative-c++-abi-vtables \
+// RUN: -ccc-install-dir %S/Inputs/basic_fuchsia_tree/bin \
+// RUN: -resource-dir=%S/Inputs/resource_dir_with_per_target_subdir \
+// RUN: -fuse-ld=lld 2>&1\
+// RUN: | FileCheck %s -check-prefixes=CHECK-MULTILIB-X86
+// RUN: %clangxx %s -### --target=x86_64-fuchsia -fno-experimental-relative-c++-abi-vtables \
+// RUN: -ccc-install-dir %S/Inputs/basic_fuchsia_tree/bin \
+// RUN: -resource-dir=%S/Inputs/resource_dir_with_per_target_subdir \
+// RUN: -fuse-ld=lld 2>&1\
+// RUN: | FileCheck %s -check-prefixes=CHECK-MULTILIB-X86
+// RUN: %clangxx %s -### --target=x86_64-fuchsia -fno-experimental-relative-c++-abi-vtables -fexperimental-relative-c++-abi-vtables \
+// RUN: -ccc-install-dir %S/Inputs/basic_fuchsia_tree/bin \
+// RUN: -resource-dir=%S/Inputs/resource_dir_with_per_target_subdir \
+// RUN: -fuse-ld=lld 2>&1\
+// RUN: | FileCheck %s -check-prefixes=CHECK-MULTILIB-X86
 // CHECK-MULTILIB-X86: "-resource-dir" "[[RESOURCE_DIR:[^"]+]]"
 // CHECK-MULTILIB-ASAN-X86: "-L{{.*}}{{/|}}..{{/|}}lib{{/|}}x86_64-fuchsia{{/|}}c++{{/|}}asan"
 // CHECK-MULTILIB-NOEXCEPT-X86: "-L{{.*}}{{/|}}..{{/|}}lib{{/|}}x86_64-fuchsia{{/|}}c++{{/|}}noexcept"
 // CHECK-MULTILIB-ASAN-NOEXCEPT-X86: "-L{{.*}}{{/|}}..{{/|}}lib{{/|}}x86_64-fuchsia{{/|}}c++{{/|}}asan+noexcept"
 // CHECK-MULTILIB-RELATIVE-VTABLES-X86: "-L{{.*}}{{/|}}..{{/|}}lib{{/|}}x86_64-fuchsia{{/|}}c++{{/|}}relative-vtables"
 // CHECK-MULTILIB-RELATIVE-VTABLES-NOEXCEPT-X86: "-L{{.*}}{{/|}}..{{/|}}lib{{/|}}x86_64-fuchsia{{/|}}c++{{/|}}relative-vtables+noexcept"
+// CHECK-MULTILIB-RELATIVE-VTABLES-ASAN-X86: "-L{{.*}}{{/|}}..{{/|}}lib{{/|}}x86_64-fuchsia{{/|}}c++{{/|}}relative-vtables+asan"
+// CHECK-MULTILIB-RELATIVE-VTABLES-ASAN-NOEXCEPT-X86: "-L{{.*}}{{/|}}..{{/|}}lib{{/|}}x86_64-fuchsia{{/|}}c++{{/|}}relative-vtables+asan+noexcept"
 // CHECK-MULTILIB-X86: "-L{{.*}}{{/|}}..{{/|}}lib{{/|}}x86_64-fuchsia{{/|}}c++"
Index: clang/lib/Driver/ToolChains/Fuchsia.cpp
===
--- clang/lib/Driver/ToolChains/Fuchsia.cpp
+++ clang/lib/Driver/ToolChains/Fuchsia.cpp
@@ -217,6 +217,14 @@
   .flag("+fexperimental-relative-c++-abi-vtables")
   .flag("-fexceptions")
   .flag("+fno-exceptions"));
+  Multilibs.push_back(Multilib("relative-vtables+asan", {}, {}, 6)
+  .flag("+fexperimental-relative-c++-abi-vtables")
+  .flag("+fsanitize=address"));
+  Multilibs.push_back(Multilib("relative-vtables+asan+noexcept", {}, {}, 7)
+  .flag("+fexperimental-relative-c++-abi-vtables")
+  .flag("+fsaniti

[PATCH] D89490: Introduce __attribute__((darwin_abi))

2021-01-22 Thread John McCall via Phabricator via cfe-commits
rjmccall added a comment.

In D89490#2514695 , @aguinet wrote:

>> I may be over-reacting to the way the patch seemed to be touching on the C++ 
>> ABI in multiple places.  My understanding is that `ms_abi` is just a 
>> calling-convention attribute; it's basically "use the (default) calling 
>> convention that MSVC would use for this function".  If that's all you want, 
>> then this is reasonable, although I am worried about creating a new 
>> attribute for every system that Wine chooses to target.
>
> I literally based this patch on how ms_abi was implemented. It's 
> unfortunately more than just teaching clang to change the calling convention 
> on LLVM IR functions. The fact that ABI implementations are spread all over 
> the place between various places in LLVM is, as far as I remember, a known 
> problem discussed many times on llvm-dev, and looks like a hard one to fix.

Right, I understand that — I've even given an LLVM talk about it.  I was just 
confused about your intent because you made some effort to match other parts of 
the ABI besides what we might traditionally consider the calling convention.  I 
suppose some of those changes could be thought of as feature-specific calling 
conventions, but I don't usually think of them that way.

>> About "darwin": technically, every Apple platform has a different ABI.  Our 
>> current ARM64 platforms do all agree about things like the calling 
>> convention, at least if you count newer watches (which use a 32-on-64 ABI in 
>> userspace) as not ARM64.  That is not true of other architectures, most 
>> notably on ARM32, where the 32-bit iOS ABI is very different from the armv7k 
>> Apple Watch ABI; and it is certainly conceivable that Apple might release a 
>> new ARM64 platform in the future with a different calling convention.  The 
>> more technically correct and future-proof thing would be to use the OS name 
>> (or maybe even the triple!) in the attribute, probably as an argument to the 
>> attribute, like `__attribute__((target_abi("arm64-apple-ios")))`.
>
> I'm a bit afraid that `__attribute__((target_abi(XX)))` would conflict with 
> the existing `__attribute__((ms_abi))`.

They don't *conflict*.  It's a more general scheme than the existing attribute, 
but the existing attribute can be thought of as a shorthand for one case of 
that more general scheme, so I don't see a problem here.  I would like to not 
have to add a new attribute for every OS that Wine decides to support.

> About Apple that would create as much ABIs as products, I guess we have a 
> living example: is the ABI for OSX/ARM64 different than the ABI for 
> iOS/ARM64? I can't seem find any official documentation about this :/ (only 
> talking about arm64 here, but I get your points about armv7 targets).

No, we've used the same basic ABI on iOS, macOS, and tvOS for ARM64.  But 
that's not surprising because those products were all released within a 
relatively short period of time from each other, so we don't have much of a 
laundry list of things we'd like to improve about them.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D89490

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


[PATCH] D92808: [ObjC][ARC] Annotate calls with attributes instead of emitting retainRV or claimRV calls in the IR

2021-01-22 Thread Akira Hatanaka via Phabricator via cfe-commits
ahatanak updated this revision to Diff 318594.
ahatanak edited the summary of this revision.
ahatanak added a comment.

Stop using `clang.arc.rv_marker` and just use "clang.arc.rv"="retain/claim".


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D92808

Files:
  clang/lib/CodeGen/CGObjC.cpp
  clang/test/CodeGenObjC/arc-rv-attr.m
  clang/test/CodeGenObjC/arc-unsafeclaim.m
  llvm/include/llvm/Analysis/ObjCARCRVAttr.h
  llvm/lib/IR/AutoUpgrade.cpp
  llvm/lib/IR/Instruction.cpp
  llvm/lib/Target/AArch64/AArch64ISelLowering.cpp
  llvm/lib/Transforms/IPO/DeadArgumentElimination.cpp
  llvm/lib/Transforms/ObjCARC/ARCRuntimeEntryPoints.h
  llvm/lib/Transforms/ObjCARC/ObjCARC.cpp
  llvm/lib/Transforms/ObjCARC/ObjCARC.h
  llvm/lib/Transforms/ObjCARC/ObjCARCContract.cpp
  llvm/lib/Transforms/ObjCARC/ObjCARCOpts.cpp
  llvm/lib/Transforms/ObjCARC/PtrState.cpp
  llvm/lib/Transforms/ObjCARC/PtrState.h
  llvm/lib/Transforms/Utils/InlineFunction.cpp
  llvm/test/CodeGen/AArch64/call-rv-marker.ll
  llvm/test/Transforms/DeadArgElim/deadretval.ll
  llvm/test/Transforms/Inline/inline-retainRV-call.ll
  llvm/test/Transforms/ObjCARC/contract-marker-funclet.ll
  llvm/test/Transforms/ObjCARC/contract-rv-attr.ll
  llvm/test/Transforms/ObjCARC/rv.ll

Index: llvm/test/Transforms/ObjCARC/rv.ll
===
--- llvm/test/Transforms/ObjCARC/rv.ll
+++ llvm/test/Transforms/ObjCARC/rv.ll
@@ -452,6 +452,28 @@
   ret i8* %v3
 }
 
+; Remove attributes and the autoreleaseRV call if the call is a tail call.
+
+; CHECK-LABEL: define i8* @test31(
+; CHECK: %[[CALL:.*]] = tail call i8* @returner()
+; CHECK: ret i8* %[[CALL]]
+
+define i8* @test31() {
+  %call = tail call "clang.arc.rv"="retain" i8* @returner()
+  %1 = call i8* @llvm.objc.autoreleaseReturnValue(i8* %call)
+  ret i8* %1
+}
+
+; CHECK-LABEL: define i8* @test32(
+; CHECK: %[[CALL:.*]] = call "clang.arc.rv"="retain" i8* @returner()
+; CHECK: call i8* @llvm.objc.autoreleaseReturnValue(i8* %[[CALL]])
+
+define i8* @test32() {
+  %call = call "clang.arc.rv"="retain" i8* @returner()
+  %1 = call i8* @llvm.objc.autoreleaseReturnValue(i8* %call)
+  ret i8* %1
+}
+
 !0 = !{}
 
 ; CHECK: attributes [[NUW]] = { nounwind }
Index: llvm/test/Transforms/ObjCARC/contract-rv-attr.ll
===
--- /dev/null
+++ llvm/test/Transforms/ObjCARC/contract-rv-attr.ll
@@ -0,0 +1,63 @@
+; RUN: opt -objc-arc-contract -S < %s | FileCheck %s
+; RUN: opt -passes=objc-arc-contract -S < %s | FileCheck %s
+
+; CHECK-LABEL: define void @test0() {
+; CHECK: %[[CALL:.*]] = notail call "clang.arc.rv"="retain" i8* @foo()
+; CHECK: call i8* @llvm.objc.retainAutoreleasedReturnValue(i8* %[[CALL]])
+
+define void @test0() {
+  %call1 = call "clang.arc.rv"="retain" i8* @foo()
+  ret void
+}
+
+; CHECK-LABEL: define void @test1() {
+; CHECK: %[[CALL:.*]] = notail call "clang.arc.rv"="claim" i8* @foo()
+; CHECK: call i8* @llvm.objc.unsafeClaimAutoreleasedReturnValue(i8* %[[CALL]])
+
+define void @test1() {
+  %call1 = call "clang.arc.rv"="claim" i8* @foo()
+  ret void
+}
+
+; CHECK-LABEL:define i8* @test2(
+; CHECK: %[[CALL1:.*]] = invoke "clang.arc.rv"="retain" i8* @foo()
+
+; CHECK: %[[V0:.*]] = call i8* @llvm.objc.retainAutoreleasedReturnValue(i8* %[[CALL1]])
+; CHECK-NEXT: br
+
+; CHECK: %[[CALL3:.*]] = invoke "clang.arc.rv"="retain" i8* @foo()
+
+; CHECK: %[[V2:.*]] = call i8* @llvm.objc.retainAutoreleasedReturnValue(i8* %[[CALL3]])
+; CHECK-NEXT: br
+
+; CHECK: %[[RETVAL:.*]] = phi i8* [ %[[V0]], {{.*}} ], [ %[[V2]], {{.*}} ]
+; CHECK: ret i8* %[[RETVAL]]
+
+define i8* @test2(i1 zeroext %b) personality i8* bitcast (i32 (...)* @__gxx_personality_v0 to i8*) {
+entry:
+  br i1 %b, label %if.then, label %if.end
+
+if.then:
+  %call1 = invoke "clang.arc.rv"="retain" i8* @foo()
+  to label %cleanup unwind label %lpad
+
+lpad:
+  %0 = landingpad { i8*, i32 }
+  cleanup
+  resume { i8*, i32 } undef
+
+if.end:
+  %call3 = invoke "clang.arc.rv"="retain" i8* @foo()
+  to label %cleanup unwind label %lpad
+
+cleanup:
+  %retval.0 = phi i8* [ %call1, %if.then ], [ %call3, %if.end ]
+  ret i8* %retval.0
+}
+
+declare i8* @foo()
+declare i32 @__gxx_personality_v0(...)
+
+!llvm.module.flags = !{!0}
+
+!0 = !{i32 1, !"clang.arc.retainAutoreleasedReturnValueMarker", !"mov\09fp, fp\09\09// marker for objc_retainAutoreleaseReturnValue"}
Index: llvm/test/Transforms/ObjCARC/contract-marker-funclet.ll
===
--- llvm/test/Transforms/ObjCARC/contract-marker-funclet.ll
+++ llvm/test/Transforms/ObjCARC/contract-marker-funclet.ll
@@ -10,6 +10,16 @@
 ;   }
 ; }
 
+; CHECK-LABEL: define void @"\01?g@@YAXXZ"()
+; CHECK-LABEL: catch
+; CHECK: call void asm sideeffect "movl{{.*}}%ebp, %ebp{{.*}}", ""() [ "funclet"(token %1) ]
+
+; CHECK-LABEL: catch.1
+; CHECK: call void asm sideef

[clang] 72f863f - [CodeGen] Use getCharWidth() more consistently in CGRecordLowering. NFC

2021-01-22 Thread Bjorn Pettersson via cfe-commits

Author: Bjorn Pettersson
Date: 2021-01-22T21:12:17+01:00
New Revision: 72f863fd37c3471e7e1b152ac613da00ab6faaba

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

LOG: [CodeGen] Use getCharWidth() more consistently in CGRecordLowering. NFC

When using getByteArrayType the requested size is calculated in
char units, but the type used for the array was hardcoded to the
Int8Ty. This patch is using getCharWIdth a bit more consistently
by using getIntNTy in combination with getCharWidth, instead
of explictly using getInt8Ty.

Reviewed By: rjmccall

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

Added: 


Modified: 
clang/lib/CodeGen/CGRecordLayoutBuilder.cpp

Removed: 




diff  --git a/clang/lib/CodeGen/CGRecordLayoutBuilder.cpp 
b/clang/lib/CodeGen/CGRecordLayoutBuilder.cpp
index 880342dfed1f..cf8313f92587 100644
--- a/clang/lib/CodeGen/CGRecordLayoutBuilder.cpp
+++ b/clang/lib/CodeGen/CGRecordLayoutBuilder.cpp
@@ -127,15 +127,20 @@ struct CGRecordLowering {
 
   /// Wraps llvm::Type::getIntNTy with some implicit arguments.
   llvm::Type *getIntNType(uint64_t NumBits) {
+unsigned AlignedBits = llvm::alignTo(NumBits, Context.getCharWidth());
+return llvm::Type::getIntNTy(Types.getLLVMContext(), AlignedBits);
+  }
+  /// Get the LLVM type sized as one character unit.
+  llvm::Type *getCharType() {
 return llvm::Type::getIntNTy(Types.getLLVMContext(),
- (unsigned)llvm::alignTo(NumBits, 8));
+ Context.getCharWidth());
   }
-  /// Gets an llvm type of size NumBytes and alignment 1.
-  llvm::Type *getByteArrayType(CharUnits NumBytes) {
-assert(!NumBytes.isZero() && "Empty byte arrays aren't allowed.");
-llvm::Type *Type = llvm::Type::getInt8Ty(Types.getLLVMContext());
-return NumBytes == CharUnits::One() ? Type :
-(llvm::Type *)llvm::ArrayType::get(Type, NumBytes.getQuantity());
+  /// Gets an llvm type of size NumChars and alignment 1.
+  llvm::Type *getByteArrayType(CharUnits NumChars) {
+assert(!NumChars.isZero() && "Empty byte arrays aren't allowed.");
+llvm::Type *Type = getCharType();
+return NumChars == CharUnits::One() ? Type :
+(llvm::Type *)llvm::ArrayType::get(Type, NumChars.getQuantity());
   }
   /// Gets the storage type for a field decl and handles storage
   /// for itanium bitfields that are smaller than their declared type.



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


[clang] ea2cfda - [CGExpr] Use getCharWidth() more consistently in CCGExprConstant. NFC

2021-01-22 Thread Bjorn Pettersson via cfe-commits

Author: Bjorn Pettersson
Date: 2021-01-22T21:12:17+01:00
New Revision: ea2cfda386f1a0f0b8cab06a9400bbf4cf7bfbaa

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

LOG: [CGExpr] Use getCharWidth() more consistently in CCGExprConstant. NFC

Most of CGExprConstant.cpp is using the CharUnits abstraction
and is using getCharWidth() (directly of indirectly) when converting
between size of a char and size in bits. This patch is making that
abstraction more consistent by adding CharTy to the CodeGenTypeCache
(honoring getCharWidth() when mapping from char to LLVM IR types,
instead of using Int8Ty directly).

Reviewed By: rjmccall

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

Added: 


Modified: 
clang/lib/CodeGen/CGExprConstant.cpp
clang/lib/CodeGen/CodeGenModule.cpp
clang/lib/CodeGen/CodeGenTypeCache.h

Removed: 




diff  --git a/clang/lib/CodeGen/CGExprConstant.cpp 
b/clang/lib/CodeGen/CGExprConstant.cpp
index ca1d3a937fa8..497f9c04c9f8 100644
--- a/clang/lib/CodeGen/CGExprConstant.cpp
+++ b/clang/lib/CodeGen/CGExprConstant.cpp
@@ -58,14 +58,14 @@ struct ConstantAggregateBuilderUtils {
   }
 
   llvm::Constant *getPadding(CharUnits PadSize) const {
-llvm::Type *Ty = CGM.Int8Ty;
+llvm::Type *Ty = CGM.CharTy;
 if (PadSize > CharUnits::One())
   Ty = llvm::ArrayType::get(Ty, PadSize.getQuantity());
 return llvm::UndefValue::get(Ty);
   }
 
   llvm::Constant *getZeroes(CharUnits ZeroSize) const {
-llvm::Type *Ty = llvm::ArrayType::get(CGM.Int8Ty, ZeroSize.getQuantity());
+llvm::Type *Ty = llvm::ArrayType::get(CGM.CharTy, ZeroSize.getQuantity());
 return llvm::ConstantAggregateZero::get(Ty);
   }
 };
@@ -1069,7 +1069,7 @@ class ConstExprEmitter :
 
   assert(CurSize <= TotalSize && "Union size mismatch!");
   if (unsigned NumPadBytes = TotalSize - CurSize) {
-llvm::Type *Ty = CGM.Int8Ty;
+llvm::Type *Ty = CGM.CharTy;
 if (NumPadBytes > 1)
   Ty = llvm::ArrayType::get(Ty, NumPadBytes);
 

diff  --git a/clang/lib/CodeGen/CodeGenModule.cpp 
b/clang/lib/CodeGen/CodeGenModule.cpp
index 18d633911f55..d93c9690cfb2 100644
--- a/clang/lib/CodeGen/CodeGenModule.cpp
+++ b/clang/lib/CodeGen/CodeGenModule.cpp
@@ -123,6 +123,8 @@ CodeGenModule::CodeGenModule(ASTContext &C, const 
HeaderSearchOptions &HSO,
 
C.toCharUnitsFromBits(C.getTargetInfo().getMaxPointerWidth()).getQuantity();
   IntAlignInBytes =
 C.toCharUnitsFromBits(C.getTargetInfo().getIntAlign()).getQuantity();
+  CharTy =
+llvm::IntegerType::get(LLVMContext, C.getTargetInfo().getCharWidth());
   IntTy = llvm::IntegerType::get(LLVMContext, C.getTargetInfo().getIntWidth());
   IntPtrTy = llvm::IntegerType::get(LLVMContext,
 C.getTargetInfo().getMaxPointerWidth());

diff  --git a/clang/lib/CodeGen/CodeGenTypeCache.h 
b/clang/lib/CodeGen/CodeGenTypeCache.h
index 20a3263c0b1a..f258234fb4d8 100644
--- a/clang/lib/CodeGen/CodeGenTypeCache.h
+++ b/clang/lib/CodeGen/CodeGenTypeCache.h
@@ -41,6 +41,9 @@ struct CodeGenTypeCache {
   /// int
   llvm::IntegerType *IntTy;
 
+  /// char
+  llvm::IntegerType *CharTy;
+
   /// intptr_t, size_t, and ptr
diff _t, which we assume are the same size.
   union {
 llvm::IntegerType *IntPtrTy;



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


[PATCH] D94977: [CodeGen] Use getCharWidth() more consistently in CGRecordLowering. NFC

2021-01-22 Thread Bjorn Pettersson 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 rG72f863fd37c3: [CodeGen] Use getCharWidth() more consistently 
in CGRecordLowering. NFC (authored by bjope).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D94977

Files:
  clang/lib/CodeGen/CGRecordLayoutBuilder.cpp


Index: clang/lib/CodeGen/CGRecordLayoutBuilder.cpp
===
--- clang/lib/CodeGen/CGRecordLayoutBuilder.cpp
+++ clang/lib/CodeGen/CGRecordLayoutBuilder.cpp
@@ -127,15 +127,20 @@
 
   /// Wraps llvm::Type::getIntNTy with some implicit arguments.
   llvm::Type *getIntNType(uint64_t NumBits) {
+unsigned AlignedBits = llvm::alignTo(NumBits, Context.getCharWidth());
+return llvm::Type::getIntNTy(Types.getLLVMContext(), AlignedBits);
+  }
+  /// Get the LLVM type sized as one character unit.
+  llvm::Type *getCharType() {
 return llvm::Type::getIntNTy(Types.getLLVMContext(),
- (unsigned)llvm::alignTo(NumBits, 8));
+ Context.getCharWidth());
   }
-  /// Gets an llvm type of size NumBytes and alignment 1.
-  llvm::Type *getByteArrayType(CharUnits NumBytes) {
-assert(!NumBytes.isZero() && "Empty byte arrays aren't allowed.");
-llvm::Type *Type = llvm::Type::getInt8Ty(Types.getLLVMContext());
-return NumBytes == CharUnits::One() ? Type :
-(llvm::Type *)llvm::ArrayType::get(Type, NumBytes.getQuantity());
+  /// Gets an llvm type of size NumChars and alignment 1.
+  llvm::Type *getByteArrayType(CharUnits NumChars) {
+assert(!NumChars.isZero() && "Empty byte arrays aren't allowed.");
+llvm::Type *Type = getCharType();
+return NumChars == CharUnits::One() ? Type :
+(llvm::Type *)llvm::ArrayType::get(Type, NumChars.getQuantity());
   }
   /// Gets the storage type for a field decl and handles storage
   /// for itanium bitfields that are smaller than their declared type.


Index: clang/lib/CodeGen/CGRecordLayoutBuilder.cpp
===
--- clang/lib/CodeGen/CGRecordLayoutBuilder.cpp
+++ clang/lib/CodeGen/CGRecordLayoutBuilder.cpp
@@ -127,15 +127,20 @@
 
   /// Wraps llvm::Type::getIntNTy with some implicit arguments.
   llvm::Type *getIntNType(uint64_t NumBits) {
+unsigned AlignedBits = llvm::alignTo(NumBits, Context.getCharWidth());
+return llvm::Type::getIntNTy(Types.getLLVMContext(), AlignedBits);
+  }
+  /// Get the LLVM type sized as one character unit.
+  llvm::Type *getCharType() {
 return llvm::Type::getIntNTy(Types.getLLVMContext(),
- (unsigned)llvm::alignTo(NumBits, 8));
+ Context.getCharWidth());
   }
-  /// Gets an llvm type of size NumBytes and alignment 1.
-  llvm::Type *getByteArrayType(CharUnits NumBytes) {
-assert(!NumBytes.isZero() && "Empty byte arrays aren't allowed.");
-llvm::Type *Type = llvm::Type::getInt8Ty(Types.getLLVMContext());
-return NumBytes == CharUnits::One() ? Type :
-(llvm::Type *)llvm::ArrayType::get(Type, NumBytes.getQuantity());
+  /// Gets an llvm type of size NumChars and alignment 1.
+  llvm::Type *getByteArrayType(CharUnits NumChars) {
+assert(!NumChars.isZero() && "Empty byte arrays aren't allowed.");
+llvm::Type *Type = getCharType();
+return NumChars == CharUnits::One() ? Type :
+(llvm::Type *)llvm::ArrayType::get(Type, NumChars.getQuantity());
   }
   /// Gets the storage type for a field decl and handles storage
   /// for itanium bitfields that are smaller than their declared type.
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


  1   2   >