[PATCH] D116806: [clang-format] Ensure we can correctly parse lambda in the template argument list

2022-01-10 Thread MyDeveloperDay via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG5c2e7c9ca043: [clang-format] Ensure we can correctly parse 
lambda in the template argument… (authored by MyDeveloperDay).

Changed prior to commit:
  https://reviews.llvm.org/D116806?vs=398124=398521#toc

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D116806

Files:
  clang/lib/Format/UnwrappedLineParser.cpp
  clang/unittests/Format/FormatTest.cpp


Index: clang/unittests/Format/FormatTest.cpp
===
--- clang/unittests/Format/FormatTest.cpp
+++ clang/unittests/Format/FormatTest.cpp
@@ -23212,6 +23212,15 @@
Style);
 }
 
+TEST_F(FormatTest, ShortTemplatedArgumentLists) {
+  auto Style = getLLVMStyle();
+
+  verifyFormat("struct Y : X<[] { return 0; }> {};", Style);
+  verifyFormat("struct Y<[] { return 0; }> {};", Style);
+
+  verifyFormat("struct Z : X {};", Style);
+}
+
 } // namespace
 } // namespace format
 } // namespace clang
Index: clang/lib/Format/UnwrappedLineParser.cpp
===
--- clang/lib/Format/UnwrappedLineParser.cpp
+++ clang/lib/Format/UnwrappedLineParser.cpp
@@ -2874,6 +2874,8 @@
 if (!tryToParseBracedList())
   break;
   }
+  if (FormatTok->is(tok::l_square) && !tryToParseLambda())
+break;
   if (FormatTok->Tok.is(tok::semi))
 return;
   if (Style.isCSharp() && FormatTok->is(Keywords.kw_where)) {


Index: clang/unittests/Format/FormatTest.cpp
===
--- clang/unittests/Format/FormatTest.cpp
+++ clang/unittests/Format/FormatTest.cpp
@@ -23212,6 +23212,15 @@
Style);
 }
 
+TEST_F(FormatTest, ShortTemplatedArgumentLists) {
+  auto Style = getLLVMStyle();
+
+  verifyFormat("struct Y : X<[] { return 0; }> {};", Style);
+  verifyFormat("struct Y<[] { return 0; }> {};", Style);
+
+  verifyFormat("struct Z : X {};", Style);
+}
+
 } // namespace
 } // namespace format
 } // namespace clang
Index: clang/lib/Format/UnwrappedLineParser.cpp
===
--- clang/lib/Format/UnwrappedLineParser.cpp
+++ clang/lib/Format/UnwrappedLineParser.cpp
@@ -2874,6 +2874,8 @@
 if (!tryToParseBracedList())
   break;
   }
+  if (FormatTok->is(tok::l_square) && !tryToParseLambda())
+break;
   if (FormatTok->Tok.is(tok::semi))
 return;
   if (Style.isCSharp() && FormatTok->is(Keywords.kw_where)) {
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] 5c2e7c9 - [clang-format] Ensure we can correctly parse lambda in the template argument list

2022-01-10 Thread via cfe-commits

Author: mydeveloperday
Date: 2022-01-10T08:29:35Z
New Revision: 5c2e7c9ca043d92bed75b08e653fb47c384edd13

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

LOG: [clang-format] Ensure we can correctly parse lambda in the template 
argument list

https://github.com/llvm/llvm-project/issues/46505

The presence of a lambda in an argument template list ignored the [] as a 
lambda at all, this caused the contents of the <> to be incorrectly analyzed.

```
struct Y : X < [] {
  return 0;
} > {};
```
Fixes: #46505

Reviewed By: curdeius

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

Added: 


Modified: 
clang/lib/Format/UnwrappedLineParser.cpp
clang/unittests/Format/FormatTest.cpp

Removed: 




diff  --git a/clang/lib/Format/UnwrappedLineParser.cpp 
b/clang/lib/Format/UnwrappedLineParser.cpp
index c293c236193c0..410cce79a0876 100644
--- a/clang/lib/Format/UnwrappedLineParser.cpp
+++ b/clang/lib/Format/UnwrappedLineParser.cpp
@@ -2874,6 +2874,8 @@ void UnwrappedLineParser::parseRecord(bool ParseAsExpr) {
 if (!tryToParseBracedList())
   break;
   }
+  if (FormatTok->is(tok::l_square) && !tryToParseLambda())
+break;
   if (FormatTok->Tok.is(tok::semi))
 return;
   if (Style.isCSharp() && FormatTok->is(Keywords.kw_where)) {

diff  --git a/clang/unittests/Format/FormatTest.cpp 
b/clang/unittests/Format/FormatTest.cpp
index 85ce3171bbc89..d3e4479a5aa84 100644
--- a/clang/unittests/Format/FormatTest.cpp
+++ b/clang/unittests/Format/FormatTest.cpp
@@ -23212,6 +23212,15 @@ TEST_F(FormatTest, EmptyShortBlock) {
Style);
 }
 
+TEST_F(FormatTest, ShortTemplatedArgumentLists) {
+  auto Style = getLLVMStyle();
+
+  verifyFormat("struct Y : X<[] { return 0; }> {};", Style);
+  verifyFormat("struct Y<[] { return 0; }> {};", Style);
+
+  verifyFormat("struct Z : X {};", Style);
+}
+
 } // namespace
 } // namespace format
 } // namespace clang



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


[PATCH] D116793: [AST] Add more source information for DecltypeTypeLoc.

2022-01-10 Thread Haojian Wu via Phabricator via cfe-commits
This revision was landed with ongoing or failed builds.
This revision was automatically updated to reflect the committed changes.
hokein marked an inline comment as done.
Closed by commit rG4a4b8e4f99e2: [AST] Add more source information for 
DecltypeTypeLoc. (authored by hokein).

Changed prior to commit:
  https://reviews.llvm.org/D116793?vs=398101=398522#toc

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D116793

Files:
  clang-tools-extra/clangd/Selection.cpp
  clang-tools-extra/clangd/unittests/SelectionTests.cpp
  clang/include/clang/AST/TypeLoc.h
  clang/lib/Parse/ParseDeclCXX.cpp
  clang/lib/Sema/SemaCXXScopeSpec.cpp
  clang/lib/Sema/SemaExprCXX.cpp
  clang/lib/Sema/SemaType.cpp
  clang/lib/Sema/TreeTransform.h
  clang/lib/Serialization/ASTReader.cpp
  clang/lib/Serialization/ASTWriter.cpp
  clang/unittests/AST/SourceLocationTest.cpp

Index: clang/unittests/AST/SourceLocationTest.cpp
===
--- clang/unittests/AST/SourceLocationTest.cpp
+++ clang/unittests/AST/SourceLocationTest.cpp
@@ -215,6 +215,33 @@
   EXPECT_TRUE(Verifier.match("long a;", typeLoc()));
 }
 
+TEST(TypeLoc, DecltypeTypeLocRange) {
+  llvm::Annotations Code(R"(
+$full1[[decltype(1)]] a;
+struct A {struct B{};} var;
+$full2[[decltype(var)]]::B c;
+  )");
+  auto AST = tooling::buildASTFromCodeWithArgs(Code.code(), /*Args=*/{});
+  ASTContext  = AST->getASTContext();
+  const auto  = Ctx.getSourceManager();
+
+  auto MatchedLocs = clang::ast_matchers::match(
+  typeLoc(loc(decltypeType())).bind("target"), Ctx);
+  ASSERT_EQ(MatchedLocs.size(), 2u);
+  auto verify = [&](SourceRange ActualRange,
+const llvm::Annotations::Range ) {
+auto ActualCharRange =
+Lexer::getAsCharRange(ActualRange, SM, Ctx.getLangOpts());
+EXPECT_EQ(SM.getFileOffset(ActualCharRange.getBegin()), Expected.Begin);
+EXPECT_EQ(SM.getFileOffset(ActualCharRange.getEnd()), Expected.End);
+  };
+  const auto *Target1 = MatchedLocs[0].getNodeAs("target");
+  verify(Target1->getSourceRange(), Code.range("full1"));
+
+  const auto *Target2 = MatchedLocs[1].getNodeAs("target");
+  verify(Target2->getSourceRange(), Code.range("full2"));
+}
+
 TEST(TypeLoc, LongDoubleRange) {
   RangeVerifier Verifier;
   Verifier.expectRange(1, 1, 1, 6);
@@ -559,7 +586,7 @@
 
 TEST(FriendDecl, FriendDecltypeRange) {
   RangeVerifier Verifier;
-  Verifier.expectRange(4, 1, 4, 8);
+  Verifier.expectRange(4, 1, 4, 22);
   EXPECT_TRUE(Verifier.match("struct A;\n"
  "A foo();\n"
  "struct A {\n"
Index: clang/lib/Serialization/ASTWriter.cpp
===
--- clang/lib/Serialization/ASTWriter.cpp
+++ clang/lib/Serialization/ASTWriter.cpp
@@ -427,7 +427,8 @@
 }
 
 void TypeLocWriter::VisitDecltypeTypeLoc(DecltypeTypeLoc TL) {
-  Record.AddSourceLocation(TL.getNameLoc());
+  Record.AddSourceLocation(TL.getDecltypeLoc());
+  Record.AddSourceLocation(TL.getRParenLoc());
 }
 
 void TypeLocWriter::VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) {
Index: clang/lib/Serialization/ASTReader.cpp
===
--- clang/lib/Serialization/ASTReader.cpp
+++ clang/lib/Serialization/ASTReader.cpp
@@ -6628,7 +6628,8 @@
 }
 
 void TypeLocReader::VisitDecltypeTypeLoc(DecltypeTypeLoc TL) {
-  TL.setNameLoc(readSourceLocation());
+  TL.setDecltypeLoc(readSourceLocation());
+  TL.setRParenLoc(readSourceLocation());
 }
 
 void TypeLocReader::VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) {
Index: clang/lib/Sema/TreeTransform.h
===
--- clang/lib/Sema/TreeTransform.h
+++ clang/lib/Sema/TreeTransform.h
@@ -6228,15 +6228,15 @@
   QualType Result = TL.getType();
   if (getDerived().AlwaysRebuild() ||
   E.get() != T->getUnderlyingExpr()) {
-Result = getDerived().RebuildDecltypeType(E.get(), TL.getNameLoc());
+Result = getDerived().RebuildDecltypeType(E.get(), TL.getDecltypeLoc());
 if (Result.isNull())
   return QualType();
   }
   else E.get();
 
   DecltypeTypeLoc NewTL = TLB.push(Result);
-  NewTL.setNameLoc(TL.getNameLoc());
-
+  NewTL.setDecltypeLoc(TL.getDecltypeLoc());
+  NewTL.setRParenLoc(TL.getRParenLoc());
   return Result;
 }
 
Index: clang/lib/Sema/SemaType.cpp
===
--- clang/lib/Sema/SemaType.cpp
+++ clang/lib/Sema/SemaType.cpp
@@ -5973,6 +5973,11 @@
   Sema::GetTypeFromParser(DS.getRepAsType(), );
   TL.setUnderlyingTInfo(TInfo);
 }
+void VisitDecltypeTypeLoc(DecltypeTypeLoc TL) {
+  assert(DS.getTypeSpecType() == DeclSpec::TST_decltype);
+  TL.setDecltypeLoc(DS.getTypeSpecTypeLoc());
+  TL.setRParenLoc(DS.getTypeofParensRange().getEnd());
+}
 void 

[PATCH] D116713: [clangd] Support configuration of inlay hints.

2022-01-10 Thread Haojian Wu via Phabricator via cfe-commits
hokein accepted this revision.
hokein added inline comments.
This revision is now accepted and ready to land.



Comment at: clang-tools-extra/clangd/InlayHints.cpp:51
   bool VisitCXXConstructExpr(CXXConstructExpr *E) {
+if (!Cfg.InlayHints.DeducedTypes)
+  return true;

sammccall wrote:
> hokein wrote:
> > this should be `!Cfg.InlayHints.ParameterNames`.
> > 
> > What do you think the idea of moving guards deeper (`processCall` and 
> > `addTypeHint`)? The code seems clearer and we don't have to add them in all 
> > Visit* implementation,  this means that we pay cost of running some 
> > necessary code, but I think it is trivial and probably worthy. 
> I agree where to put the checks is an annoying question (and worth 
> minimizing, since I've managed to get two wrong already).
> I do think there needs to be a pattern so we don't accidentally skip checks.
> 
> - Easest is to postfilter (check in addInlayHint). That *does* hurt 
> performance. Debug build on my laptop is ~170ms for all hints, ~160ms for 
> postfilter with all categories disabled, ~5ms for current impl (prefilter) 
> with all categories disabled. (On SemaCodeComplete.cpp, just eyeballing 
> traces)
> - Checking in VisitXXX methods (as done here) is a very regular pattern. 
> Downside is you need many checks, and you can forget/break one
> - Checks in helpers so that one is always hit (as you propose) touches fewer 
> places but it's ad-hoc. I'm afraid of getting it wrong as the impl is 
> modified (missing checks, doing too much work first, etc).
> - Splitting RAV per category is an interesting option. Checking is very 
> elegant, nicer code structure, can trace per-category latency, disabled 
> categories can't crash... The downside is extra overhead, but this must be 
> <5ms in the performance above. We can still choose to bundle simple 
> categories together...
> 
> I think I'll do as you propose for now, improve the tests, and refactor to 
> try to make it feel less ad-hoc later.
> Also I should work out what we're spending 170ms on... EDIT: it turns out 
> it's just assembling JSON objects :-\
Thanks for digging into this.

> ~5ms for current impl (prefilter) with all categories disabled. (On 
> SemaCodeComplete.cpp, just eyeballing traces)

Yeah, we should have this prefilter implementation when all categories are 
disabled.


> Debug build on my laptop is ~170ms for all hints, ~160ms for postfilter with 
> all categories disabled,

The data doesn't seem reasonable, I think the total cost comes from two main 
sources (AST traversal cost + assembling JSON object cost),
I would expect the `allhints` and `postfilter` have the similar AST traversal 
cost, but `postfilter` should have a near zero cost of assembling JSON objectcs 
(as it returns an empty vector), so the AST traversal cost is ~160ms.

> Also I should work out what we're spending 170ms on... EDIT: it turns out 
> it's just assembling JSON objects :-\

And based on this, it turns out the cost of `all-hints` approach should be 
larger than 170ms, which should be ~300ms (160ms for AST traversal + 170ms for 
assembling JSON objects).


Anyway, the current implementation looks good.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D116713

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


[PATCH] D115490: [clangd] Include fixer for missing functions in C

2022-01-10 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/lib/Sema/SemaDecl.cpp:14995
+DeclFilterCCC CCC{};
+Corrected = CorrectTypo(DeclarationNameInfo(, Loc), LookupOrdinaryName,
+S, nullptr, CCC, CTK_NonError);

maybe some comments around importance of the sequencing here? it would probably 
be nice to have that at a higher level documentation too, but unclear where. as 
in theory it's not just about the typo correction but also emitting diagnostics 
while doing so.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D115490

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


[PATCH] D116920: [clang-format] clang-format eats space in front of attributes for operator delete

2022-01-10 Thread Marek Kurdej via Phabricator via cfe-commits
curdeius added inline comments.



Comment at: clang/lib/Format/TokenAnnotator.cpp:1729
 } else if (Current.is(tok::r_paren)) {
   if (rParenEndsCast(Current))
 Current.setType(TT_CastRParen);

The current solution looks a bit like a hack to me.
Unless I'm mistaken, casts can appear only in expressions, but not in 
declarations (except for inside `decltype` stuff in templates or concepts, but 
these are still expressions at this level).
Given that `void operator delete...` is not an expression but a declaration, we 
shouldn't check `rParenEndsCast` in this case at all, no?
So, would it be possible to check here for e.g. `Line.MightBeFunctionDecl` or 
something like this to avoid it?

Also, how is it that you don't need to special-case `new` operator?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D116920

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


[PATCH] D116924: [clang-extdef-mapping] Allow clang-extdef-mapping tool to output customized filename for each index entry

2022-01-10 Thread Ella Ma via Phabricator via cfe-commits
OikawaKirie created this revision.
OikawaKirie added reviewers: martong, NoQ, steakhal.
OikawaKirie added a project: clang.
Herald added subscribers: arphaman, rnkovacs.
OikawaKirie requested review of this revision.
Herald added a subscriber: cfe-commits.

The clang-extdef-mapping tool can only output the real file name of the input 
source file. When analyzing with AST file based CTU analysis, the file name 
should be adjusted to the corresponding AST file, where `.ast` will be appended 
to the file name, and sometimes the path will even be changed. It is very 
inconvenient to adjust the file path with such a separated step, especially on 
Windows, where utility tools such as `sed` are not available.

This patch uses `Regex::sub` function to adjust the output file name for each 
index entry with the pattern provided by the user.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D116924

Files:
  clang/test/Analysis/func-mapping-path.c
  clang/tools/clang-extdef-mapping/ClangExtDefMapGen.cpp

Index: clang/tools/clang-extdef-mapping/ClangExtDefMapGen.cpp
===
--- clang/tools/clang-extdef-mapping/ClangExtDefMapGen.cpp
+++ clang/tools/clang-extdef-mapping/ClangExtDefMapGen.cpp
@@ -30,11 +30,45 @@
 using namespace clang::tooling;
 
 static cl::OptionCategory ClangExtDefMapGenCategory("clang-extdefmapgen options");
+static cl::opt OutputPathAdjusterMatcher(
+"m", cl::desc("Match the part of output path to be replaced with regex"),
+cl::cat(ClangExtDefMapGenCategory));
+static cl::opt OutputPathAdjusterNewPath(
+"r", cl::desc("The string which matched pattern will be replaced to"),
+cl::cat(ClangExtDefMapGenCategory));
+
+namespace {
+class OutputPathAdjuster {
+  Regex Matcher;
+  std::string NewPath;
+
+public:
+  std::string adjust(StringRef Path) const {
+return Matcher.sub(NewPath, Path);
+  }
+
+  bool resetMatcher(StringRef MatcherStr, StringRef NewPathStr);
+};
+
+bool OutputPathAdjuster::resetMatcher(StringRef MatcherStr,
+  StringRef NewPathStr) {
+  std::string ErrMsg;
+  Regex MatcherRegex(MatcherStr);
+  if (!MatcherRegex.isValid(ErrMsg)) {
+errs() << "Invalid adjuster template: " << ErrMsg << '\n';
+return false;
+  }
+
+  Matcher = std::move(MatcherRegex);
+  NewPath = NewPathStr.str();
+  return true;
+}
+} // namespace
 
 class MapExtDefNamesConsumer : public ASTConsumer {
 public:
-  MapExtDefNamesConsumer(ASTContext )
-  : Ctx(Context), SM(Context.getSourceManager()) {}
+  MapExtDefNamesConsumer(const OutputPathAdjuster *Adjuster)
+  : Adjuster(Adjuster) {}
 
   ~MapExtDefNamesConsumer() {
 // Flush results to standard output.
@@ -49,10 +83,9 @@
   void handleDecl(const Decl *D);
   void addIfInMain(const DeclaratorDecl *DD, SourceLocation defStart);
 
-  ASTContext 
-  SourceManager 
   llvm::StringMap Index;
   std::string CurrentFileName;
+  const OutputPathAdjuster *Adjuster = nullptr;
 };
 
 void MapExtDefNamesConsumer::handleDecl(const Decl *D) {
@@ -64,7 +97,7 @@
   if (const Stmt *Body = FD->getBody())
 addIfInMain(FD, Body->getBeginLoc());
   } else if (const auto *VD = dyn_cast(D)) {
-if (cross_tu::containsConst(VD, Ctx) && VD->hasInit())
+if (cross_tu::containsConst(VD, VD->getASTContext()) && VD->hasInit())
   if (const Expr *Init = VD->getInit())
 addIfInMain(VD, Init->getBeginLoc());
   }
@@ -82,9 +115,12 @@
 return;
   assert(!LookupName->empty() && "Lookup name should be non-empty.");
 
+  SourceManager  = DD->getASTContext().getSourceManager();
   if (CurrentFileName.empty()) {
 CurrentFileName = std::string(
 SM.getFileEntryForID(SM.getMainFileID())->tryGetRealPathName());
+if (Adjuster)
+  CurrentFileName = Adjuster->adjust(CurrentFileName);
 if (CurrentFileName.empty())
   CurrentFileName = "invalid_file";
   }
@@ -101,11 +137,15 @@
   }
 }
 
-class MapExtDefNamesAction : public ASTFrontendAction {
-protected:
-  std::unique_ptr CreateASTConsumer(CompilerInstance ,
- llvm::StringRef) override {
-return std::make_unique(CI.getASTContext());
+class MapExtDefNamesConsumerFactory {
+  const OutputPathAdjuster *Adjuster = nullptr;
+
+public:
+  MapExtDefNamesConsumerFactory(const OutputPathAdjuster *Adjuster)
+  : Adjuster(Adjuster) {}
+
+  std::unique_ptr newASTConsumer() {
+return std::make_unique(Adjuster);
   }
 };
 
@@ -118,7 +158,8 @@
 
   const char *Overview = "\nThis tool collects the USR name and location "
  "of external definitions in the source files "
- "(excluding headers).\n";
+ "(excluding headers).\n\nReset output path with -m "
+ " -r .\n";
   auto ExpectedParser = CommonOptionsParser::create(
   argc, argv, ClangExtDefMapGenCategory, cl::ZeroOrMore, Overview);
   if (!ExpectedParser) {

[PATCH] D116921: [clangd] Enable expand-auto for decltype(auto).

2022-01-10 Thread Haojian Wu via Phabricator via cfe-commits
hokein created this revision.
hokein added a reviewer: sammccall.
Herald added subscribers: usaxena95, kadircet, arphaman.
hokein requested review of this revision.
Herald added subscribers: MaskRay, ilya-biryukov.
Herald added a project: clang-tools-extra.

Based on https://reviews.llvm.org/D116919.

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


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D116921

Files:
  clang-tools-extra/clangd/refactor/tweaks/ExpandAutoType.cpp
  clang-tools-extra/clangd/unittests/tweaks/ExpandAutoTypeTests.cpp


Index: clang-tools-extra/clangd/unittests/tweaks/ExpandAutoTypeTests.cpp
===
--- clang-tools-extra/clangd/unittests/tweaks/ExpandAutoTypeTests.cpp
+++ clang-tools-extra/clangd/unittests/tweaks/ExpandAutoTypeTests.cpp
@@ -71,7 +71,8 @@
   apply("void ns::Func() { au^to x = new ns::Class::Nested{}; }"),
   "void ns::Func() { ns::Class::Nested * x = new ns::Class::Nested{}; }");
 
-  EXPECT_UNAVAILABLE("dec^ltype(au^to) x = 10;");
+  EXPECT_EQ(apply("dec^ltype(auto) x = 10;"), "int x = 10;");
+  EXPECT_EQ(apply("decltype(au^to) x = 10;"), "int x = 10;");
   // expanding types in structured bindings is syntactically invalid.
   EXPECT_UNAVAILABLE("const ^auto &[x,y] = (int[]){1,2};");
 
Index: clang-tools-extra/clangd/refactor/tweaks/ExpandAutoType.cpp
===
--- clang-tools-extra/clangd/refactor/tweaks/ExpandAutoType.cpp
+++ clang-tools-extra/clangd/refactor/tweaks/ExpandAutoType.cpp
@@ -96,9 +96,7 @@
   if (auto *Node = Inputs.ASTSelection.commonAncestor()) {
 if (auto *TypeNode = Node->ASTNode.get()) {
   if (const AutoTypeLoc Result = TypeNode->getAs()) {
-// Code in apply() does handle 'decltype(auto)' yet.
-if (!Result.getTypePtr()->isDecltypeAuto() &&
-!isStructuredBindingType(Node) &&
+if (!isStructuredBindingType(Node) &&
 !isDeducedAsLambda(Node, Result.getBeginLoc()) &&
 !isTemplateParam(Node))
   CachedLocation = Result;


Index: clang-tools-extra/clangd/unittests/tweaks/ExpandAutoTypeTests.cpp
===
--- clang-tools-extra/clangd/unittests/tweaks/ExpandAutoTypeTests.cpp
+++ clang-tools-extra/clangd/unittests/tweaks/ExpandAutoTypeTests.cpp
@@ -71,7 +71,8 @@
   apply("void ns::Func() { au^to x = new ns::Class::Nested{}; }"),
   "void ns::Func() { ns::Class::Nested * x = new ns::Class::Nested{}; }");
 
-  EXPECT_UNAVAILABLE("dec^ltype(au^to) x = 10;");
+  EXPECT_EQ(apply("dec^ltype(auto) x = 10;"), "int x = 10;");
+  EXPECT_EQ(apply("decltype(au^to) x = 10;"), "int x = 10;");
   // expanding types in structured bindings is syntactically invalid.
   EXPECT_UNAVAILABLE("const ^auto &[x,y] = (int[]){1,2};");
 
Index: clang-tools-extra/clangd/refactor/tweaks/ExpandAutoType.cpp
===
--- clang-tools-extra/clangd/refactor/tweaks/ExpandAutoType.cpp
+++ clang-tools-extra/clangd/refactor/tweaks/ExpandAutoType.cpp
@@ -96,9 +96,7 @@
   if (auto *Node = Inputs.ASTSelection.commonAncestor()) {
 if (auto *TypeNode = Node->ASTNode.get()) {
   if (const AutoTypeLoc Result = TypeNode->getAs()) {
-// Code in apply() does handle 'decltype(auto)' yet.
-if (!Result.getTypePtr()->isDecltypeAuto() &&
-!isStructuredBindingType(Node) &&
+if (!isStructuredBindingType(Node) &&
 !isDeducedAsLambda(Node, Result.getBeginLoc()) &&
 !isTemplateParam(Node))
   CachedLocation = Result;
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D116387: [CodeCompletion][clangd] Clean __uglified parameter names in completion & hover

2022-01-10 Thread Sam McCall via Phabricator via cfe-commits
sammccall added a comment.

In D116387#3230893 , @hokein wrote:

> Agree that __ reserved names are ugly,  but I'm not sure this is a great 
> improvement.
>
> I played around the patch locally, and found the new behavior being confused 
> in some cases (mostly inconsistencies between deuglified places vs uglified 
> places), and seems hard for readers to predict it:

Agree, but I don't think it needs to be predictable, it's enough that the 
output can be understood.
(e.g. I never particularly noticed *which* identifiers in stdlib were ugly, 
just that the thing overall was hard to read).
i.e. if we remove the underscores half the time, that seems like a win.

> - inconsistency with doc-comment which still uses the __ name (this seems 
> hard to fix)
>
> F21562126: image.png 

Yes :-( However I don't think a human reader is likely to be confused by this.

> - the print type in hover still uses __name (maybe this is expected, or we 
> could introduce a `reserved` field in hover, like `template-type-param Tp 
> (reserved)`)
>
> F21562145: image.png 

This is an oversight, I'll fix this.

> - the deuglified behavior is triggered on (template/function) parameters, 
> which means we have uglified name for `void foo(_ReservedClass& abc)` vs 
> deuglified name for `template void 
> foo(_ReservedClass& abc)` (expanding the scope could fix that, but it doesn't 
> seem something we want to do)

This is deliberate: `_ReservedClass` is part of the API of `foo`, so renaming 
it is a semantic change.
I don't this change increases the amount of inconsistency:  today we 
have`vector` vs `push_back` vs `_ReservedClass` vs `_Tp`.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D116387

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


[PATCH] D99031: [clang-format] Fix CompactNamespaces corner case when AllowShortLambdasOnASingleLine/BraceWrapping.BeforeLambdaBody are set

2022-01-10 Thread Marek Kurdej via Phabricator via cfe-commits
curdeius added a comment.

@aybassiouny, still interested in working on this?


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

https://reviews.llvm.org/D99031

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


[PATCH] D94955: [clang-format] Treat ForEachMacros as loops

2022-01-10 Thread Marek Kurdej via Phabricator via cfe-commits
curdeius added a comment.

@GoBigorGoHome, are you still interested in this review?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D94955

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


[PATCH] D116920: [clang-format] clang-format eats space in front of attributes for operator delete

2022-01-10 Thread MyDeveloperDay via Phabricator via cfe-commits
MyDeveloperDay created this revision.
MyDeveloperDay added reviewers: curdeius, HazardyKnusperkeks, owenpan, thakis.
MyDeveloperDay added projects: clang, clang-format.
MyDeveloperDay requested review of this revision.

https://github.com/llvm/llvm-project/issues/27037

Sorry its taken so long to get to this issue! (got it before it hit its 6th 
birthday!)

  void operator delete(void *foo)ATTRIB;

(void *foo) is incorrectly determined to be a C-Style Cast resulting in the 
space being removed after the ) and before the attrib, due to the detection of

  delete (A* )a;

The following was previously unaffected

  void operator new(void *foo) ATTRIB;

Fixes #27037


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D116920

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


Index: clang/unittests/Format/FormatTest.cpp
===
--- clang/unittests/Format/FormatTest.cpp
+++ clang/unittests/Format/FormatTest.cpp
@@ -9459,6 +9459,9 @@
"new 
(aa(aaa))\n"
"typename ();");
   verifyFormat("delete[] h->p;");
+
+  verifyFormat("void operator delete(void *foo) ATTRIB;");
+  verifyFormat("void operator new(void *foo) ATTRIB;");
 }
 
 TEST_F(FormatTest, UnderstandsUsesOfStarAndAmp) {
Index: clang/lib/Format/TokenAnnotator.cpp
===
--- clang/lib/Format/TokenAnnotator.cpp
+++ clang/lib/Format/TokenAnnotator.cpp
@@ -1893,6 +1893,14 @@
 LeftOfParens = LeftOfParens->MatchingParen->Previous;
   }
 
+  // The Condition directly below this one will see the operator arguments
+  // as a (void *foo) cast.
+  //   void operator delete(void *foo) ATTRIB;
+  if (LeftOfParens->Tok.getIdentifierInfo() &&
+  LeftOfParens->is(tok::kw_delete) && LeftOfParens->Previous &&
+  LeftOfParens->Previous->is(tok::kw_operator))
+return false;
+
   // If there is an identifier (or with a few exceptions a keyword) right
   // before the parentheses, this is unlikely to be a cast.
   if (LeftOfParens->Tok.getIdentifierInfo() &&


Index: clang/unittests/Format/FormatTest.cpp
===
--- clang/unittests/Format/FormatTest.cpp
+++ clang/unittests/Format/FormatTest.cpp
@@ -9459,6 +9459,9 @@
"new (aa(aaa))\n"
"typename ();");
   verifyFormat("delete[] h->p;");
+
+  verifyFormat("void operator delete(void *foo) ATTRIB;");
+  verifyFormat("void operator new(void *foo) ATTRIB;");
 }
 
 TEST_F(FormatTest, UnderstandsUsesOfStarAndAmp) {
Index: clang/lib/Format/TokenAnnotator.cpp
===
--- clang/lib/Format/TokenAnnotator.cpp
+++ clang/lib/Format/TokenAnnotator.cpp
@@ -1893,6 +1893,14 @@
 LeftOfParens = LeftOfParens->MatchingParen->Previous;
   }
 
+  // The Condition directly below this one will see the operator arguments
+  // as a (void *foo) cast.
+  //   void operator delete(void *foo) ATTRIB;
+  if (LeftOfParens->Tok.getIdentifierInfo() &&
+  LeftOfParens->is(tok::kw_delete) && LeftOfParens->Previous &&
+  LeftOfParens->Previous->is(tok::kw_operator))
+return false;
+
   // If there is an identifier (or with a few exceptions a keyword) right
   // before the parentheses, this is unlikely to be a cast.
   if (LeftOfParens->Tok.getIdentifierInfo() &&
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D116922: [AST] Use recovery-expr to preserve incomplete-type-member-access expression.

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

Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D116922

Files:
  clang/lib/Sema/SemaExprCXX.cpp
  clang/test/AST/ast-dump-recovery.cpp
  clang/test/OpenMP/declare_reduction_messages.cpp


Index: clang/test/OpenMP/declare_reduction_messages.cpp
===
--- clang/test/OpenMP/declare_reduction_messages.cpp
+++ clang/test/OpenMP/declare_reduction_messages.cpp
@@ -169,7 +169,6 @@
   #pragma omp declare reduction (xxx : U, S : bar(omp_in)) // expected-error 
{{non-const lvalue reference to type 'S<1>' cannot bind to a value of unrelated 
type 'U'}}
   static void bar(S ); // expected-note {{passing argument to parameter 'x' 
here}}
 };
-// expected-warning@+2 {{extra tokens at the end of '#pragma omp declare 
reduction' are ignored}}
 // expected-note@+1 {{in instantiation of template class 'S<1>' requested 
here}}
 #pragma omp declare reduction (bar : S<1> : omp_out.foo(omp_in))
 
Index: clang/test/AST/ast-dump-recovery.cpp
===
--- clang/test/AST/ast-dump-recovery.cpp
+++ clang/test/AST/ast-dump-recovery.cpp
@@ -121,6 +121,16 @@
   foo->func(x);
 }
 
+void AccessIncompleteClass() {
+  struct Forward;
+  Forward* ptr;
+  // CHECK:  CallExpr {{.*}} ''
+  // CHECK-NEXT: `-CXXDependentScopeMemberExpr {{.*}} ''
+  // CHECK-NEXT:   `-RecoveryExpr {{.*}} '' contains-errors
+  // CHECK-NEXT: `-DeclRefExpr {{.*}} 'Forward *'
+  ptr->method();
+}
+
 struct Foo2 {
   double func();
   class ForwardClass;
Index: clang/lib/Sema/SemaExprCXX.cpp
===
--- clang/lib/Sema/SemaExprCXX.cpp
+++ clang/lib/Sema/SemaExprCXX.cpp
@@ -7410,8 +7410,10 @@
   //   the member function body.
   if (!BaseType->isDependentType() &&
   !isThisOutsideMemberFunctionBody(BaseType) &&
-  RequireCompleteType(OpLoc, BaseType, diag::err_incomplete_member_access))
-return ExprError();
+  RequireCompleteType(OpLoc, BaseType,
+  diag::err_incomplete_member_access)) {
+return CreateRecoveryExpr(Base->getBeginLoc(), Base->getEndLoc(), {Base});
+  }
 
   // C++ [basic.lookup.classref]p2:
   //   If the id-expression in a class member access (5.2.5) is an


Index: clang/test/OpenMP/declare_reduction_messages.cpp
===
--- clang/test/OpenMP/declare_reduction_messages.cpp
+++ clang/test/OpenMP/declare_reduction_messages.cpp
@@ -169,7 +169,6 @@
   #pragma omp declare reduction (xxx : U, S : bar(omp_in)) // expected-error {{non-const lvalue reference to type 'S<1>' cannot bind to a value of unrelated type 'U'}}
   static void bar(S ); // expected-note {{passing argument to parameter 'x' here}}
 };
-// expected-warning@+2 {{extra tokens at the end of '#pragma omp declare reduction' are ignored}}
 // expected-note@+1 {{in instantiation of template class 'S<1>' requested here}}
 #pragma omp declare reduction (bar : S<1> : omp_out.foo(omp_in))
 
Index: clang/test/AST/ast-dump-recovery.cpp
===
--- clang/test/AST/ast-dump-recovery.cpp
+++ clang/test/AST/ast-dump-recovery.cpp
@@ -121,6 +121,16 @@
   foo->func(x);
 }
 
+void AccessIncompleteClass() {
+  struct Forward;
+  Forward* ptr;
+  // CHECK:  CallExpr {{.*}} ''
+  // CHECK-NEXT: `-CXXDependentScopeMemberExpr {{.*}} ''
+  // CHECK-NEXT:   `-RecoveryExpr {{.*}} '' contains-errors
+  // CHECK-NEXT: `-DeclRefExpr {{.*}} 'Forward *'
+  ptr->method();
+}
+
 struct Foo2 {
   double func();
   class ForwardClass;
Index: clang/lib/Sema/SemaExprCXX.cpp
===
--- clang/lib/Sema/SemaExprCXX.cpp
+++ clang/lib/Sema/SemaExprCXX.cpp
@@ -7410,8 +7410,10 @@
   //   the member function body.
   if (!BaseType->isDependentType() &&
   !isThisOutsideMemberFunctionBody(BaseType) &&
-  RequireCompleteType(OpLoc, BaseType, diag::err_incomplete_member_access))
-return ExprError();
+  RequireCompleteType(OpLoc, BaseType,
+  diag::err_incomplete_member_access)) {
+return CreateRecoveryExpr(Base->getBeginLoc(), Base->getEndLoc(), {Base});
+  }
 
   // C++ [basic.lookup.classref]p2:
   //   If the id-expression in a class member access (5.2.5) is an
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] 27ea0c4 - [Parse] Use empty RecoveryExpr when if/while/do/switch conditions fail to parse

2022-01-10 Thread Sam McCall via cfe-commits

Author: Sam McCall
Date: 2022-01-10T10:38:27+01:00
New Revision: 27ea0c4e7234f3b15cbbb696e6c408af7141f342

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

LOG: [Parse] Use empty RecoveryExpr when if/while/do/switch conditions fail to 
parse

This allows the body to be parsed.
An special-case that would replace a missing if condition with OpaqueValueExpr
was removed as it's now redundant (unless recovery-expr is disabled).

For loops are not handled at this point, as the parsing is more complicated.

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

Added: 
clang/test/AST/loop-recovery.cpp

Modified: 
clang/include/clang/Parse/Parser.h
clang/include/clang/Sema/Sema.h
clang/lib/AST/ExprConstant.cpp
clang/lib/Parse/ParseExprCXX.cpp
clang/lib/Parse/ParseStmt.cpp
clang/lib/Sema/SemaExpr.cpp
clang/lib/Sema/SemaStmt.cpp
clang/lib/Sema/TreeTransform.h
clang/test/AST/ast-dump-invalid.cpp
clang/test/Parser/cxx0x-attributes.cpp
clang/test/Sema/complex-int.c
clang/test/SemaCXX/condition.cpp
clang/test/SemaCXX/constexpr-function-recovery-crash.cpp

Removed: 




diff  --git a/clang/include/clang/Parse/Parser.h 
b/clang/include/clang/Parse/Parser.h
index d266a0b37265c..b651929fa9da1 100644
--- a/clang/include/clang/Parse/Parser.h
+++ b/clang/include/clang/Parse/Parser.h
@@ -1975,6 +1975,7 @@ class Parser : public CodeCompletionHandler {
   Sema::ConditionResult ParseCXXCondition(StmtResult *InitStmt,
   SourceLocation Loc,
   Sema::ConditionKind CK,
+  bool MissingOK,
   ForRangeInfo *FRI = nullptr,
   bool EnterForConditionScope = false);
   DeclGroupPtrTy
@@ -2079,8 +2080,8 @@ class Parser : public CodeCompletionHandler {
   bool ParseParenExprOrCondition(StmtResult *InitStmt,
  Sema::ConditionResult ,
  SourceLocation Loc, Sema::ConditionKind CK,
- SourceLocation *LParenLoc = nullptr,
- SourceLocation *RParenLoc = nullptr);
+ bool MissingOK, SourceLocation *LParenLoc,
+ SourceLocation *RParenLoc);
   StmtResult ParseIfStatement(SourceLocation *TrailingElseLoc);
   StmtResult ParseSwitchStatement(SourceLocation *TrailingElseLoc);
   StmtResult ParseWhileStatement(SourceLocation *TrailingElseLoc);

diff  --git a/clang/include/clang/Sema/Sema.h b/clang/include/clang/Sema/Sema.h
index 9521b24e44a79..9b6d9d20ca431 100644
--- a/clang/include/clang/Sema/Sema.h
+++ b/clang/include/clang/Sema/Sema.h
@@ -12080,9 +12080,12 @@ class Sema final {
 ConstexprIf, ///< A constant boolean condition from 'if constexpr'.
 Switch   ///< An integral condition for a 'switch' statement.
   };
+  QualType PreferredConditionType(ConditionKind K) const {
+return K == ConditionKind::Switch ? Context.IntTy : Context.BoolTy;
+  }
 
-  ConditionResult ActOnCondition(Scope *S, SourceLocation Loc,
- Expr *SubExpr, ConditionKind CK);
+  ConditionResult ActOnCondition(Scope *S, SourceLocation Loc, Expr *SubExpr,
+ ConditionKind CK, bool MissingOK = false);
 
   ConditionResult ActOnConditionVariable(Decl *ConditionVar,
  SourceLocation StmtLoc,

diff  --git a/clang/lib/AST/ExprConstant.cpp b/clang/lib/AST/ExprConstant.cpp
index 51e8a55f2e4b7..f9416e8e215d1 100644
--- a/clang/lib/AST/ExprConstant.cpp
+++ b/clang/lib/AST/ExprConstant.cpp
@@ -4933,8 +4933,13 @@ static EvalStmtResult EvaluateSwitch(StmtResult , 
EvalInfo ,
 if (SS->getConditionVariable() &&
 !EvaluateDecl(Info, SS->getConditionVariable()))
   return ESR_Failed;
-if (!EvaluateInteger(SS->getCond(), Value, Info))
-  return ESR_Failed;
+if (SS->getCond()->isValueDependent()) {
+  if (!EvaluateDependentExpr(SS->getCond(), Info))
+return ESR_Failed;
+} else {
+  if (!EvaluateInteger(SS->getCond(), Value, Info))
+return ESR_Failed;
+}
 if (!CondScope.destroy())
   return ESR_Failed;
   }

diff  --git a/clang/lib/Parse/ParseExprCXX.cpp 
b/clang/lib/Parse/ParseExprCXX.cpp
index 6685c0e897021..cd600c4247a72 100644
--- a/clang/lib/Parse/ParseExprCXX.cpp
+++ b/clang/lib/Parse/ParseExprCXX.cpp
@@ -1953,6 +1953,9 @@ 
Parser::ParseAliasDeclarationInInitStatement(DeclaratorContext Context,
 /// \param Loc The location of the start of the statement that requires this
 /// condition, e.g., the "for" in a for loop.
 ///
+/// \param MissingOK Whether an 

[clang-tools-extra] 16fd5c2 - [clangd] Support configuration of inlay hints.

2022-01-10 Thread Sam McCall via cfe-commits

Author: Sam McCall
Date: 2022-01-10T10:49:35+01:00
New Revision: 16fd5c278488b3d3275afc381a00ba0b51b070ee

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

LOG: [clangd] Support configuration of inlay hints.

The idea is that the feature will always be advertised at the LSP level, but
depending on config we'll return partial or no responses.

We try to avoid doing the analysis for hints we're not going to return.

Examples of syntax:
```
InlayHints:
  Enabled: No
---
InlayHints:
  ParameterNames: No
---
InlayHints:
  ParameterNames: Yes
  DeducedTypes: Yes
```

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

Added: 


Modified: 
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/InlayHints.cpp
clang-tools-extra/clangd/unittests/ConfigYAMLTests.cpp
clang-tools-extra/clangd/unittests/InlayHintTests.cpp

Removed: 




diff  --git a/clang-tools-extra/clangd/Config.h 
b/clang-tools-extra/clangd/Config.h
index 38fc93fa361c..952626db31e4 100644
--- a/clang-tools-extra/clangd/Config.h
+++ b/clang-tools-extra/clangd/Config.h
@@ -122,6 +122,15 @@ struct Config {
 /// Whether hover show a.k.a type.
 bool ShowAKA = false;
   } Hover;
+
+  struct {
+/// If false, inlay hints are completely disabled.
+bool Enabled = true;
+
+// Whether specific categories of hints are enabled.
+bool Parameters = true;
+bool DeducedTypes = true;
+  } InlayHints;
 };
 
 } // namespace clangd

diff  --git a/clang-tools-extra/clangd/ConfigCompile.cpp 
b/clang-tools-extra/clangd/ConfigCompile.cpp
index 18afdeb3cb5c..a606b98a2dba 100644
--- a/clang-tools-extra/clangd/ConfigCompile.cpp
+++ b/clang-tools-extra/clangd/ConfigCompile.cpp
@@ -197,6 +197,7 @@ struct FragmentCompiler {
 compile(std::move(F.Diagnostics));
 compile(std::move(F.Completion));
 compile(std::move(F.Hover));
+compile(std::move(F.InlayHints));
   }
 
   void compile(Fragment::IfBlock &) {
@@ -526,6 +527,22 @@ struct FragmentCompiler {
 }
   }
 
+  void compile(Fragment::InlayHintsBlock &) {
+if (F.Enabled)
+  Out.Apply.push_back([Value(**F.Enabled)](const Params &, Config ) {
+C.InlayHints.Enabled = Value;
+  });
+if (F.ParameterNames)
+  Out.Apply.push_back(
+  [Value(**F.ParameterNames)](const Params &, Config ) {
+C.InlayHints.Parameters = Value;
+  });
+if (F.DeducedTypes)
+  Out.Apply.push_back([Value(**F.DeducedTypes)](const Params &, Config ) 
{
+C.InlayHints.DeducedTypes = Value;
+  });
+  }
+
   constexpr static llvm::SourceMgr::DiagKind Error = llvm::SourceMgr::DK_Error;
   constexpr static llvm::SourceMgr::DiagKind Warning =
   llvm::SourceMgr::DK_Warning;

diff  --git a/clang-tools-extra/clangd/ConfigFragment.h 
b/clang-tools-extra/clangd/ConfigFragment.h
index 31c4636efa0b..d165b6305aa5 100644
--- a/clang-tools-extra/clangd/ConfigFragment.h
+++ b/clang-tools-extra/clangd/ConfigFragment.h
@@ -283,6 +283,18 @@ struct Fragment {
 llvm::Optional> ShowAKA;
   };
   HoverBlock Hover;
+
+  /// Configures labels shown inline with the code.
+  struct InlayHintsBlock {
+/// Enables/disables the inlay-hints feature.
+llvm::Optional> Enabled;
+
+/// Show parameter names before function arguments.
+llvm::Optional> ParameterNames;
+/// Show deduced types for `auto`.
+llvm::Optional> DeducedTypes;
+  };
+  InlayHintsBlock InlayHints;
 };
 
 } // namespace config

diff  --git a/clang-tools-extra/clangd/ConfigYAML.cpp 
b/clang-tools-extra/clangd/ConfigYAML.cpp
index 0487c3281576..04c0c633a3bb 100644
--- a/clang-tools-extra/clangd/ConfigYAML.cpp
+++ b/clang-tools-extra/clangd/ConfigYAML.cpp
@@ -66,6 +66,7 @@ class Parser {
 Dict.handle("Diagnostics", [&](Node ) { parse(F.Diagnostics, N); });
 Dict.handle("Completion", [&](Node ) { parse(F.Completion, N); });
 Dict.handle("Hover", [&](Node ) { parse(F.Hover, N); });
+Dict.handle("InlayHints", [&](Node ) { parse(F.InlayHints, N); });
 Dict.parse(N);
 return !(N.failed() || HadError);
   }
@@ -199,12 +200,8 @@ class Parser {
   void parse(Fragment::CompletionBlock , Node ) {
 DictParser Dict("Completion", this);
 Dict.handle("AllScopes", [&](Node ) {
-  if (auto Value = scalarValue(N, "AllScopes")) {
-if (auto AllScopes = llvm::yaml::parseBool(**Value))
-  F.AllScopes = *AllScopes;
-else
-  warning("AllScopes should be a boolean", N);
-  }
+  if (auto AllScopes = boolValue(N, "AllScopes"))
+F.AllScopes = *AllScopes;
 });
 Dict.parse(N);
   }
@@ -212,12 +209,25 @@ class Parser {
   void 

[PATCH] D113752: [Parse] Use empty RecoveryExpr when if/while/do/switch conditions fail to parse

2022-01-10 Thread Sam McCall 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 rG27ea0c4e7234: [Parse] Use empty RecoveryExpr when 
if/while/do/switch conditions fail to parse (authored by sammccall).

Changed prior to commit:
  https://reviews.llvm.org/D113752?vs=396662=398535#toc

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D113752

Files:
  clang/include/clang/Parse/Parser.h
  clang/include/clang/Sema/Sema.h
  clang/lib/AST/ExprConstant.cpp
  clang/lib/Parse/ParseExprCXX.cpp
  clang/lib/Parse/ParseStmt.cpp
  clang/lib/Sema/SemaExpr.cpp
  clang/lib/Sema/SemaStmt.cpp
  clang/lib/Sema/TreeTransform.h
  clang/test/AST/ast-dump-invalid.cpp
  clang/test/AST/loop-recovery.cpp
  clang/test/Parser/cxx0x-attributes.cpp
  clang/test/Sema/complex-int.c
  clang/test/SemaCXX/condition.cpp
  clang/test/SemaCXX/constexpr-function-recovery-crash.cpp

Index: clang/test/SemaCXX/constexpr-function-recovery-crash.cpp
===
--- clang/test/SemaCXX/constexpr-function-recovery-crash.cpp
+++ clang/test/SemaCXX/constexpr-function-recovery-crash.cpp
@@ -77,3 +77,25 @@
 
 constexpr int test12() { return "wrong"; } // expected-error {{cannot initialize return object of type 'int'}}
 constexpr int force12 = test12();  // expected-error {{must be initialized by a constant}}
+
+#define TEST_EVALUATE(Name, X) \
+  constexpr int testEvaluate##Name() { \
+X return 0;\
+  }\
+  constexpr int forceEvaluate##Name = testEvaluate##Name()
+// Check that a variety of broken loops don't crash constant evaluation.
+// We're not checking specific recovery here so don't assert diagnostics.
+TEST_EVALUATE(Switch, switch (!!){});  // expected-error + {{}}
+TEST_EVALUATE(SwitchInit, switch (auto x = !!){}); // expected-error + {{}}
+TEST_EVALUATE(For, for (!!){}); // expected-error + {{}}
+// FIXME: should bail out instead of looping.
+// expected-note@-2 + {{infinite loop}}
+// expected-note@-3 {{in call}}
+TEST_EVALUATE(ForRange, for (auto x : !!){}); // expected-error + {{}}
+TEST_EVALUATE(While, while (!!){});   // expected-error + {{}}
+TEST_EVALUATE(DoWhile, do {} while (!!););// expected-error + {{}}
+TEST_EVALUATE(If, if (!!){};);// expected-error + {{}}
+TEST_EVALUATE(IfInit, if (auto x = !!; 1){};);// expected-error + {{}}
+TEST_EVALUATE(ForInit, if (!!;;){};); // expected-error + {{}}
+TEST_EVALUATE(ForCond, if (; !!;){};);// expected-error + {{}}
+TEST_EVALUATE(ForInc, if (;; !!){};); // expected-error + {{}}
Index: clang/test/SemaCXX/condition.cpp
===
--- clang/test/SemaCXX/condition.cpp
+++ clang/test/SemaCXX/condition.cpp
@@ -20,6 +20,8 @@
   while (struct S {} *x=0) ; // expected-error {{'S' cannot be defined in a condition}}
   while (struct {} *x=0) ; // expected-error-re {{'(unnamed struct at {{.*}})' cannot be defined in a condition}}
   switch (enum {E} x=0) ; // expected-error-re {{'(unnamed enum at {{.*}})' cannot be defined in a condition}}
+  // expected-warning@-1 {{switch statement has empty body}}
+  // expected-note@-2 {{put the semicolon on a separate line}}
 
   if (int x=0) { // expected-note 2 {{previous definition is here}}
 int x;  // expected-error {{redefinition of 'x'}}
Index: clang/test/Sema/complex-int.c
===
--- clang/test/Sema/complex-int.c
+++ clang/test/Sema/complex-int.c
@@ -18,8 +18,8 @@
 result = xx*yy;
 
 switch (arr) { // expected-error{{statement requires expression of integer type ('_Complex int' invalid)}}
-  case brr: ;
-  case xx: ;
+  case brr: ; // expected-error{{integer constant expression must have integer type}}
+  case xx: ; // expected-error{{integer constant expression must have integer type}}
 }
 switch (ii) {
   case brr: ; // expected-error{{integer constant expression must have integer type}}
Index: clang/test/Parser/cxx0x-attributes.cpp
===
--- clang/test/Parser/cxx0x-attributes.cpp
+++ clang/test/Parser/cxx0x-attributes.cpp
@@ -152,6 +152,7 @@
   [[ab]ab] ns::i); // expected-error {{an attribute list cannot appear here}}
   do {} while ( // expected-note {{to match this '('}}
   alignas(4 ns::i; // expected-note {{to match this '('}}
+   // expected-error@-1 {{expected ';' after do/while}}
 } // expected-error 2{{expected ')'}} expected-error {{expected expression}}
 
 [[]] using T = int; // expected-error {{an attribute list cannot appear here}}
Index: 

[PATCH] D116713: [clangd] Support configuration of inlay hints.

2022-01-10 Thread Sam McCall via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG16fd5c278488: [clangd] Support configuration of inlay hints. 
(authored by sammccall).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D116713

Files:
  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/InlayHints.cpp
  clang-tools-extra/clangd/unittests/ConfigYAMLTests.cpp
  clang-tools-extra/clangd/unittests/InlayHintTests.cpp

Index: clang-tools-extra/clangd/unittests/InlayHintTests.cpp
===
--- clang-tools-extra/clangd/unittests/InlayHintTests.cpp
+++ clang-tools-extra/clangd/unittests/InlayHintTests.cpp
@@ -6,11 +6,13 @@
 //
 //===--===//
 #include "Annotations.h"
+#include "Config.h"
 #include "InlayHints.h"
 #include "Protocol.h"
 #include "TestTU.h"
 #include "TestWorkspace.h"
 #include "XRefs.h"
+#include "support/Context.h"
 #include "gmock/gmock.h"
 #include "gtest/gtest.h"
 
@@ -24,6 +26,8 @@
 namespace {
 
 using ::testing::ElementsAre;
+using ::testing::IsEmpty;
+using ::testing::UnorderedElementsAre;
 
 std::vector hintsOfKind(ParsedAST , InlayHintKind Kind) {
   std::vector Result;
@@ -56,6 +60,13 @@
 
 MATCHER_P(labelIs, Label, "") { return arg.label == Label; }
 
+Config noHintsConfig() {
+  Config C;
+  C.InlayHints.Parameters = false;
+  C.InlayHints.DeducedTypes = false;
+  return C;
+}
+
 template 
 void assertHints(InlayHintKind Kind, llvm::StringRef AnnotatedSource,
  ExpectedHints... Expected) {
@@ -66,6 +77,10 @@
 
   EXPECT_THAT(hintsOfKind(AST, Kind),
   ElementsAre(HintMatcher(Expected, Source)...));
+  // Sneak in a cross-cutting check that hints are disabled by config.
+  // We'll hit an assertion failure if addInlayHint still gets called.
+  WithContextValue WithCfg(Config::Key, noHintsConfig());
+  EXPECT_THAT(inlayHints(AST, llvm::None), IsEmpty());
 }
 
 // Hack to allow expression-statements operating on parameter packs in C++14.
Index: clang-tools-extra/clangd/unittests/ConfigYAMLTests.cpp
===
--- clang-tools-extra/clangd/unittests/ConfigYAMLTests.cpp
+++ clang-tools-extra/clangd/unittests/ConfigYAMLTests.cpp
@@ -228,6 +228,23 @@
   ASSERT_EQ(Results.size(), 1u);
   EXPECT_THAT(Results[0].Hover.ShowAKA, llvm::ValueIs(Val(true)));
 }
+
+TEST(ParseYAML, InlayHints) {
+  CapturedDiags Diags;
+  Annotations YAML(R"yaml(
+InlayHints:
+  Enabled: No
+  ParameterNames: Yes
+  )yaml");
+  auto Results =
+  Fragment::parseYAML(YAML.code(), "config.yaml", Diags.callback());
+  ASSERT_THAT(Diags.Diagnostics, IsEmpty());
+  ASSERT_EQ(Results.size(), 1u);
+  EXPECT_THAT(Results[0].InlayHints.Enabled, llvm::ValueIs(Val(false)));
+  EXPECT_THAT(Results[0].InlayHints.ParameterNames, llvm::ValueIs(Val(true)));
+  EXPECT_EQ(Results[0].InlayHints.DeducedTypes, llvm::None);
+}
+
 } // namespace
 } // namespace config
 } // namespace clangd
Index: clang-tools-extra/clangd/InlayHints.cpp
===
--- clang-tools-extra/clangd/InlayHints.cpp
+++ clang-tools-extra/clangd/InlayHints.cpp
@@ -6,6 +6,7 @@
 //
 //===--===//
 #include "InlayHints.h"
+#include "Config.h"
 #include "HeuristicResolver.h"
 #include "ParsedAST.h"
 #include "clang/AST/DeclarationName.h"
@@ -23,8 +24,8 @@
 class InlayHintVisitor : public RecursiveASTVisitor {
 public:
   InlayHintVisitor(std::vector , ParsedAST ,
-   llvm::Optional RestrictRange)
-  : Results(Results), AST(AST.getASTContext()),
+   const Config , llvm::Optional RestrictRange)
+  : Results(Results), AST(AST.getASTContext()), Cfg(Cfg),
 RestrictRange(std::move(RestrictRange)),
 MainFileID(AST.getSourceManager().getMainFileID()),
 Resolver(AST.getHeuristicResolver()),
@@ -65,6 +66,9 @@
   }
 
   bool VisitCallExpr(CallExpr *E) {
+if (!Cfg.InlayHints.Parameters)
+  return true;
+
 // Do not show parameter hints for operator calls written using operator
 // syntax or user-defined literals. (Among other reasons, the resulting
 // hints can look awkard, e.g. the expression can itself be a function
@@ -135,7 +139,7 @@
   // the entire argument list likely appears in the main file and can be hinted.
   void processCall(SourceLocation Anchor, const FunctionDecl *Callee,
llvm::ArrayRef Args) {
-if (Args.size() == 0 || !Callee)
+if (!Cfg.InlayHints.Parameters || Args.size() == 0 || !Callee)
   return;
 
 // If the anchor location comes from a macro defintion, there's nowhere to
@@ -323,6 

[PATCH] D116920: [clang-format] clang-format eats space in front of attributes for operator delete

2022-01-10 Thread MyDeveloperDay via Phabricator via cfe-commits
MyDeveloperDay added inline comments.



Comment at: clang/lib/Format/TokenAnnotator.cpp:1729
 } else if (Current.is(tok::r_paren)) {
   if (rParenEndsCast(Current))
 Current.setType(TT_CastRParen);

curdeius wrote:
> The current solution looks a bit like a hack to me.
> Unless I'm mistaken, casts can appear only in expressions, but not in 
> declarations (except for inside `decltype` stuff in templates or concepts, 
> but these are still expressions at this level).
> Given that `void operator delete...` is not an expression but a declaration, 
> we shouldn't check `rParenEndsCast` in this case at all, no?
> So, would it be possible to check here for e.g. `Line.MightBeFunctionDecl` or 
> something like this to avoid it?
> 
> Also, how is it that you don't need to special-case `new` operator?
I will check to see if we can use that..

To answer your second question, the existing code was this... 

`!isOneOf(Keywords.kw_in, tok::kw_return, tok::kw_case,tok::kw_delete)`

its the `kw_delete` here that breaks the previous code.

to cover this being a cast

`delete (A *)a;`

my change is to use more context by avoid `operator delete (A* a) a;` from 
being seen as a cast




Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D116920

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


[PATCH] D113752: [Parse] Use empty RecoveryExpr when if/while/do/switch conditions fail to parse

2022-01-10 Thread Haojian Wu via Phabricator via cfe-commits
hokein accepted this revision.
hokein added a comment.
This revision is now accepted and ready to land.

thanks, this looks good (sorry, I missed this.)


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D113752

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


[PATCH] D116859: Fix for: clang-format: break added to macro define with ColumnLimit: 0

2022-01-10 Thread MyDeveloperDay via Phabricator via cfe-commits
MyDeveloperDay added inline comments.



Comment at: clang/unittests/Format/FormatTest.cpp:4811
+  verifyFormat("#define STRINGIFY(t) #t\n"
+   "#define MAKEVERSIONSTRING(x, y, z, build) STRINGIFY(x) \".\" 
STRINGIFY(y) \".\" STRINGIFY(z) \".\" STRINGIFY(build)\n",
+   ZeroColumn);

Can you fix this first


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D116859

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


[clang] 4a4b8e4 - [AST] Add more source information for DecltypeTypeLoc.

2022-01-10 Thread Haojian Wu via cfe-commits

Author: Haojian Wu
Date: 2022-01-10T09:34:18+01:00
New Revision: 4a4b8e4f99e2a82286b0595d561a51e7ad1945d2

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

LOG: [AST] Add more source information for DecltypeTypeLoc.

Adds the paren source location, and removes the hack in clangd.

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

Added: 


Modified: 
clang-tools-extra/clangd/Selection.cpp
clang-tools-extra/clangd/unittests/SelectionTests.cpp
clang/include/clang/AST/TypeLoc.h
clang/lib/Parse/ParseDeclCXX.cpp
clang/lib/Sema/SemaCXXScopeSpec.cpp
clang/lib/Sema/SemaExprCXX.cpp
clang/lib/Sema/SemaType.cpp
clang/lib/Sema/TreeTransform.h
clang/lib/Serialization/ASTReader.cpp
clang/lib/Serialization/ASTWriter.cpp
clang/unittests/AST/SourceLocationTest.cpp

Removed: 




diff  --git a/clang-tools-extra/clangd/Selection.cpp 
b/clang-tools-extra/clangd/Selection.cpp
index 7dc8a868ea00e..7c6b8b3134fe1 100644
--- a/clang-tools-extra/clangd/Selection.cpp
+++ b/clang-tools-extra/clangd/Selection.cpp
@@ -60,21 +60,6 @@ void recordMetrics(const SelectionTree , const LangOptions 
) {
 
 // Return the range covering a node and all its children.
 SourceRange getSourceRange(const DynTypedNode ) {
-  // DeclTypeTypeLoc::getSourceRange() is incomplete, which would lead to
-  // failing to descend into the child expression.
-  // decltype(2+2);
-  // ~ <-- correct range
-  //   <-- range reported by getSourceRange()
-  //   <-- range with this hack(i.e, missing closing paren)
-  // FIXME: Alter DecltypeTypeLoc to contain parentheses locations and get
-  // rid of this patch.
-  if (const auto *TL = N.get()) {
-if (auto DT = TL->getAs()) {
-  SourceRange S = DT.getSourceRange();
-  S.setEnd(DT.getUnderlyingExpr()->getEndLoc());
-  return S;
-}
-  }
   // MemberExprs to implicitly access anonymous fields should not claim any
   // tokens for themselves. Given:
   //   struct A { struct { int b; }; };

diff  --git a/clang-tools-extra/clangd/unittests/SelectionTests.cpp 
b/clang-tools-extra/clangd/unittests/SelectionTests.cpp
index 9da111f684c31..7e19f07a2215e 100644
--- a/clang-tools-extra/clangd/unittests/SelectionTests.cpp
+++ b/clang-tools-extra/clangd/unittests/SelectionTests.cpp
@@ -390,7 +390,7 @@ TEST(SelectionTest, CommonAncestor) {
 decltype([[^a]] + a) b;
 )cpp",
   "DeclRefExpr"},
-  {"[[decltype]]^(1) b;", "DecltypeTypeLoc"}, // Not the VarDecl.
+  {"[[decltype^(1)]] b;", "DecltypeTypeLoc"}, // Not the VarDecl.
 
   // Objective-C nullability attributes.
   {

diff  --git a/clang/include/clang/AST/TypeLoc.h 
b/clang/include/clang/AST/TypeLoc.h
index 7a036836e8c48..9a43d34a9ec38 100644
--- a/clang/include/clang/AST/TypeLoc.h
+++ b/clang/include/clang/AST/TypeLoc.h
@@ -1994,12 +1994,35 @@ class TypeOfTypeLoc
   void initializeLocal(ASTContext , SourceLocation Loc);
 };
 
-// FIXME: location of the 'decltype' and parens.
-class DecltypeTypeLoc : public InheritingConcreteTypeLoc {
+// decltype(expression) abc;
+//   DecltypeLoc
+//~  RParenLoc
+// FIXME: add LParenLoc, it is tricky to support due to the limitation of
+// annotated-decltype token.
+struct DecltypeTypeLocInfo {
+  SourceLocation DecltypeLoc;
+  SourceLocation RParenLoc;
+};
+class DecltypeTypeLoc
+: public ConcreteTypeLoc {
 public:
   Expr *getUnderlyingExpr() const { return getTypePtr()->getUnderlyingExpr(); }
+
+  SourceLocation getDecltypeLoc() const { return getLocalData()->DecltypeLoc; }
+  void setDecltypeLoc(SourceLocation Loc) { getLocalData()->DecltypeLoc = Loc; 
}
+
+  SourceLocation getRParenLoc() const { return getLocalData()->RParenLoc; }
+  void setRParenLoc(SourceLocation Loc) { getLocalData()->RParenLoc = Loc; }
+
+  SourceRange getLocalSourceRange() const {
+return SourceRange(getDecltypeLoc(), getRParenLoc());
+  }
+
+  void initializeLocal(ASTContext , SourceLocation Loc) {
+setDecltypeLoc(Loc);
+setRParenLoc(Loc);
+  }
 };
 
 struct UnaryTransformTypeLocInfo {

diff  --git a/clang/lib/Parse/ParseDeclCXX.cpp 
b/clang/lib/Parse/ParseDeclCXX.cpp
index 8ab1231e1bc10..c08a586604b1f 100644
--- a/clang/lib/Parse/ParseDeclCXX.cpp
+++ b/clang/lib/Parse/ParseDeclCXX.cpp
@@ -1007,6 +1007,9 @@ SourceLocation Parser::ParseDecltypeSpecifier(DeclSpec 
) {
   if (Tok.is(tok::annot_decltype)) {
 Result = getExprAnnotation(Tok);
 EndLoc = Tok.getAnnotationEndLoc();
+// Unfortunately, we don't know the LParen source location as the annotated
+// token doesn't have it.
+DS.setTypeofParensRange(SourceRange(SourceLocation(), EndLoc));
 ConsumeAnnotationToken();
 if (Result.isInvalid()) {
   

[PATCH] D116859: Fix for: clang-format: break added to macro define with ColumnLimit: 0

2022-01-10 Thread Marek Kurdej via Phabricator via cfe-commits
curdeius added inline comments.



Comment at: clang/unittests/Format/FormatTest.cpp:4810-4811
+
+  verifyFormat("#define STRINGIFY(t) #t\n"
+   "#define MAKEVERSIONSTRING(x, y, z, build) STRINGIFY(x) \".\" 
STRINGIFY(y) \".\" STRINGIFY(z) \".\" STRINGIFY(build)\n",
+   ZeroColumn);

Please test with something simpler.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D116859

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


[PATCH] D116919: [AST] Add RParen loc for decltype AutoTypeloc.

2022-01-10 Thread Haojian Wu via Phabricator via cfe-commits
hokein created this revision.
hokein added a reviewer: sammccall.
Herald added subscribers: usaxena95, kadircet, arphaman.
hokein requested review of this revision.
Herald added projects: clang, clang-tools-extra.

Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D116919

Files:
  clang-tools-extra/clangd/unittests/SelectionTests.cpp
  clang/include/clang/AST/TypeLoc.h
  clang/lib/AST/TypeLoc.cpp
  clang/lib/Sema/SemaType.cpp
  clang/lib/Serialization/ASTReader.cpp
  clang/lib/Serialization/ASTWriter.cpp
  clang/test/AST/ast-dump-template-decls-json.cpp
  clang/test/AST/ast-dump-template-decls.cpp
  clang/unittests/AST/SourceLocationTest.cpp

Index: clang/unittests/AST/SourceLocationTest.cpp
===
--- clang/unittests/AST/SourceLocationTest.cpp
+++ clang/unittests/AST/SourceLocationTest.cpp
@@ -242,6 +242,13 @@
   verify(Target2->getSourceRange(), Code.range("full2"));
 }
 
+TEST(TypeLoc, AutoTypeLocRange) {
+  RangeVerifier Verifier;
+  Verifier.expectRange(1, 1, 1, 14);
+  EXPECT_TRUE(Verifier.match("decltype(auto) a = 1;", typeLoc(loc(autoType())),
+ Lang_CXX11));
+}
+
 TEST(TypeLoc, LongDoubleRange) {
   RangeVerifier Verifier;
   Verifier.expectRange(1, 1, 1, 6);
Index: clang/test/AST/ast-dump-template-decls.cpp
===
--- clang/test/AST/ast-dump-template-decls.cpp
+++ clang/test/AST/ast-dump-template-decls.cpp
@@ -90,7 +90,7 @@
 
 template 
 // CHECK: ClassTemplateDecl 0x{{[^ ]*}}  col:8 U
-// CHECK-NEXT: NonTypeTemplateParmDecl 0x{{[^ ]*}}  col:25 'decltype(auto)' depth 0 index 0
+// CHECK-NEXT: NonTypeTemplateParmDecl 0x{{[^ ]*}}  col:25 'decltype(auto)' depth 0 index 0
 struct U {};
 
 template 
Index: clang/test/AST/ast-dump-template-decls-json.cpp
===
--- clang/test/AST/ast-dump-template-decls-json.cpp
+++ clang/test/AST/ast-dump-template-decls-json.cpp
@@ -2130,9 +2130,9 @@
 // CHECK-NEXT:"tokLen": 8
 // CHECK-NEXT:   },
 // CHECK-NEXT:   "end": {
-// CHECK-NEXT:"offset": 705,
-// CHECK-NEXT:"col": 11,
-// CHECK-NEXT:"tokLen": 8
+// CHECK-NEXT:"offset": 718,
+// CHECK-NEXT:"col": 24,
+// CHECK-NEXT:"tokLen": 1
 // CHECK-NEXT:   }
 // CHECK-NEXT:  },
 // CHECK-NEXT:  "type": {
Index: clang/lib/Serialization/ASTWriter.cpp
===
--- clang/lib/Serialization/ASTWriter.cpp
+++ clang/lib/Serialization/ASTWriter.cpp
@@ -452,6 +452,9 @@
   Record.AddTemplateArgumentLocInfo(TL.getTypePtr()->getArg(I).getKind(),
 TL.getArgLocInfo(I));
   }
+  Record.push_back(TL.isDecltypeAuto());
+  if (TL.isDecltypeAuto())
+Record.AddSourceLocation(TL.getRParenLoc());
 }
 
 void TypeLocWriter::VisitDeducedTemplateSpecializationTypeLoc(
Index: clang/lib/Serialization/ASTReader.cpp
===
--- clang/lib/Serialization/ASTReader.cpp
+++ clang/lib/Serialization/ASTReader.cpp
@@ -6652,6 +6652,8 @@
   TL.setArgLocInfo(i, Reader.readTemplateArgumentLocInfo(
   TL.getTypePtr()->getArg(i).getKind()));
   }
+  if (Reader.readBool())
+TL.setRParenLoc(readSourceLocation());
 }
 
 void TypeLocReader::VisitDeducedTemplateSpecializationTypeLoc(
Index: clang/lib/Sema/SemaType.cpp
===
--- clang/lib/Sema/SemaType.cpp
+++ clang/lib/Sema/SemaType.cpp
@@ -22,6 +22,7 @@
 #include "clang/AST/TypeLoc.h"
 #include "clang/AST/TypeLocVisitor.h"
 #include "clang/Basic/PartialDiagnostic.h"
+#include "clang/Basic/Specifiers.h"
 #include "clang/Basic/TargetInfo.h"
 #include "clang/Lex/Preprocessor.h"
 #include "clang/Sema/DeclSpec.h"
@@ -6041,6 +6042,8 @@
  DS.getTypeSpecType() == TST_auto_type ||
  DS.getTypeSpecType() == TST_unspecified);
   TL.setNameLoc(DS.getTypeSpecTypeLoc());
+  if (DS.getTypeSpecType() == TST_decltype_auto)
+TL.setRParenLoc(DS.getTypeofParensRange().getEnd());
   if (!DS.isConstrainedAuto())
 return;
   TemplateIdAnnotation *TemplateId = DS.getRepAsTemplateId();
Index: clang/lib/AST/TypeLoc.cpp
===
--- clang/lib/AST/TypeLoc.cpp
+++ clang/lib/AST/TypeLoc.cpp
@@ -622,6 +622,7 @@
   setFoundDecl(nullptr);
   setRAngleLoc(Loc);
   setLAngleLoc(Loc);
+  setRParenLoc(Loc);
   TemplateSpecializationTypeLoc::initializeArgLocs(Context, getNumArgs(),
getTypePtr()->getArgs(),
getArgInfos(), Loc);
Index: clang/include/clang/AST/TypeLoc.h
===
--- clang/include/clang/AST/TypeLoc.h
+++ 

[PATCH] D116294: [CodeCompletion] (mostly) fix completion in incomplete C++ ctor initializers.

2022-01-10 Thread Kadir Cetinkaya via Phabricator via cfe-commits
kadircet added inline comments.



Comment at: clang/lib/Parse/ParseCXXInlineMethods.cpp:153
+  // probably truncated, so don't eat more tokens.
+  if (!Toks.back().is(tok::code_completion))
+SkipMalformedDecl();

i don't follow the logic here. maybe i am reading the comment wrong, but we are 
actually going to eat **more** tokens by calling `SkipMalformedDecl`, possibly 
the following one, right? for example in a scenario like:
```
struct Foo {
  Foo : ^b
  int bar;
}
```
`ConsumeAndStoreFunctionPrologue` will actually put `b` following the code 
completion token (`^`) into `Toks` as well, hence when we skip, we actually 
skip until the next semicolon and throw away bar. But when the code completion 
token is after `b`, `ConsumeAndStoreFunctionPrologue` we'll have code 
completion token at the end of the `Toks` and won't skip anything

 Do we have cases that break miserably when we don't perform an extra skip here 
for the (possible) reminder of current initalizer?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D116294

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


[PATCH] D116387: [CodeCompletion][clangd] Clean __uglified parameter names in completion & hover

2022-01-10 Thread Haojian Wu via Phabricator via cfe-commits
hokein added a comment.

Agree that __ reserved names are ugly,  but I'm not sure this is a great 
improvement.

I played around the patch locally, and found the new behavior being confused in 
some cases (mostly inconsistencies between deuglified places vs uglified 
places), and seems hard for readers to predict it:

- inconsistency with doc-comment which still uses the __ name (this seems hard 
to fix)

F21562126: image.png 

- the print type in hover still uses __name (maybe this is expected, or we 
could introduce a `reserved` field in hover, like `template-type-param Tp 
(reserved)`)

F21562145: image.png 

- the deuglified behavior is triggered on (template/function) parameters, which 
means we have uglified name for `void foo(_ReservedClass& abc)` vs deuglified 
name for `template void foo(_ReservedClass& abc)` 
(expanding the scope could fix that, but it doesn't seem something we want to 
do)


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D116387

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


[PATCH] D116490: [clangd] Code action to declare missing move/copy constructor/assignment

2022-01-10 Thread Haojian Wu via Phabricator via cfe-commits
hokein added inline comments.



Comment at: clang-tools-extra/clangd/refactor/tweaks/SpecialMembers.cpp:72
+//
+// e.g. given `struct S{};`, produces:
+//   struct S {

nit: add trigger points.



Comment at: clang-tools-extra/clangd/refactor/tweaks/SpecialMembers.cpp:120
+// they should be =default or =delete.
+Inputs.AST->getSema().ForceDeclarationOfImplicitMembers(Class);
+std::string Code = buildSpecialMemberDeclarations(*Class);

I think we need this because these members are created lazily in clang, e.g. if 
the empty struct `s` is not used, there is no constructor decl being created.

The `ForceDeclarationOfImplicitMembers` is a member function which can mutate 
the parameter `Class`, I was wondering whether it would lead some bad 
side-effect, but I didn't come out one (and the mutation is mostly creating a 
new ctor-decl and adding it to the Class).



Comment at: clang-tools-extra/clangd/refactor/tweaks/SpecialMembers.cpp:146
+private:
+  bool NeedCopy, NeedMove;
+  CXXRecordDecl *Class = nullptr;

nit: add default value


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D116490

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


[PATCH] D116337: [clang] set __NO_MATH_ERRNO__ if -fno-math-errno

2022-01-10 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman closed this revision.
aaron.ballman added a comment.

Thanks for the patch! I've landed on your behalf in 
f282b6809105075b65974989459ee420ecd406e9 
.


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

https://reviews.llvm.org/D116337

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


[PATCH] D116599: Simplify AttrBuilder storage for target dependent attributes

2022-01-10 Thread serge 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 rGd2cc6c2d0c2f: Use a sorted array instead of a map to store 
AttrBuilder string attributes (authored by serge-sans-paille).
Herald added a subscriber: awarzynski.

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D116599

Files:
  clang/lib/CodeGen/CGAtomic.cpp
  clang/lib/CodeGen/CGBuiltin.cpp
  clang/lib/CodeGen/CGCall.cpp
  clang/lib/CodeGen/CGExpr.cpp
  clang/lib/CodeGen/CodeGenModule.cpp
  clang/lib/CodeGen/TargetInfo.cpp
  llvm/include/llvm/CodeGen/IndirectThunks.h
  llvm/include/llvm/IR/Attributes.h
  llvm/lib/AsmParser/LLParser.cpp
  llvm/lib/Bitcode/Reader/BitcodeReader.cpp
  llvm/lib/CodeGen/Analysis.cpp
  llvm/lib/CodeGen/CommandFlags.cpp
  llvm/lib/CodeGen/GlobalISel/LegalizerHelper.cpp
  llvm/lib/CodeGen/SelectionDAG/TargetLowering.cpp
  llvm/lib/IR/Attributes.cpp
  llvm/lib/IR/AutoUpgrade.cpp
  llvm/lib/IR/Function.cpp
  llvm/lib/IR/Verifier.cpp
  llvm/lib/Target/WebAssembly/WebAssemblyLowerEmscriptenEHSjLj.cpp
  llvm/lib/Transforms/Coroutines/CoroSplit.cpp
  llvm/lib/Transforms/IPO/DeadArgumentElimination.cpp
  llvm/lib/Transforms/InstCombine/InstCombineCalls.cpp
  llvm/lib/Transforms/Scalar/RewriteStatepointsForGC.cpp
  llvm/lib/Transforms/Utils/CallPromotionUtils.cpp
  llvm/lib/Transforms/Utils/InlineFunction.cpp
  llvm/lib/Transforms/Utils/SimplifyLibCalls.cpp
  llvm/tools/bugpoint/CrashDebugger.cpp
  llvm/tools/llvm-reduce/deltas/ReduceAttributes.cpp
  llvm/unittests/ExecutionEngine/Orc/IndirectionUtilsTest.cpp
  llvm/unittests/IR/AttributesTest.cpp
  llvm/unittests/IR/InstructionsTest.cpp
  mlir/lib/Target/LLVMIR/ModuleTranslation.cpp

Index: mlir/lib/Target/LLVMIR/ModuleTranslation.cpp
===
--- mlir/lib/Target/LLVMIR/ModuleTranslation.cpp
+++ mlir/lib/Target/LLVMIR/ModuleTranslation.cpp
@@ -753,7 +753,7 @@
 return func.emitError(
 "llvm.align attribute attached to LLVM non-pointer argument");
   llvmArg.addAttrs(
-  llvm::AttrBuilder().addAlignmentAttr(llvm::Align(attr.getInt(;
+  llvm::AttrBuilder(llvmArg.getContext()).addAlignmentAttr(llvm::Align(attr.getInt(;
 }
 
 if (auto attr = func.getArgAttrOfType(argIdx, "llvm.sret")) {
@@ -761,7 +761,7 @@
   if (!argTy.isa())
 return func.emitError(
 "llvm.sret attribute attached to LLVM non-pointer argument");
-  llvmArg.addAttrs(llvm::AttrBuilder().addStructRetAttr(
+  llvmArg.addAttrs(llvm::AttrBuilder(llvmArg.getContext()).addStructRetAttr(
   llvmArg.getType()->getPointerElementType()));
 }
 
@@ -770,7 +770,7 @@
   if (!argTy.isa())
 return func.emitError(
 "llvm.byval attribute attached to LLVM non-pointer argument");
-  llvmArg.addAttrs(llvm::AttrBuilder().addByValAttr(
+  llvmArg.addAttrs(llvm::AttrBuilder(llvmArg.getContext()).addByValAttr(
   llvmArg.getType()->getPointerElementType()));
 }
 
Index: llvm/unittests/IR/InstructionsTest.cpp
===
--- llvm/unittests/IR/InstructionsTest.cpp
+++ llvm/unittests/IR/InstructionsTest.cpp
@@ -614,7 +614,7 @@
 
   // Test cloning an attribute.
   {
-AttrBuilder AB;
+AttrBuilder AB(C);
 AB.addAttribute(Attribute::ReadOnly);
 Call->setAttributes(
 AttributeList::get(C, AttributeList::FunctionIndex, AB));
@@ -633,7 +633,7 @@
   std::unique_ptr Call(
   CallInst::Create(FnTy, Callee, Args, OldBundle, "result"));
   Call->setTailCallKind(CallInst::TailCallKind::TCK_NoTail);
-  AttrBuilder AB;
+  AttrBuilder AB(C);
   AB.addAttribute(Attribute::Cold);
   Call->setAttributes(AttributeList::get(C, AttributeList::FunctionIndex, AB));
   Call->setDebugLoc(DebugLoc(MDNode::get(C, None)));
@@ -662,7 +662,7 @@
   std::unique_ptr Invoke(
   InvokeInst::Create(FnTy, Callee, NormalDest.get(), UnwindDest.get(), Args,
  OldBundle, "result"));
-  AttrBuilder AB;
+  AttrBuilder AB(C);
   AB.addAttribute(Attribute::Cold);
   Invoke->setAttributes(
   AttributeList::get(C, AttributeList::FunctionIndex, AB));
Index: llvm/unittests/IR/AttributesTest.cpp
===
--- llvm/unittests/IR/AttributesTest.cpp
+++ llvm/unittests/IR/AttributesTest.cpp
@@ -62,9 +62,9 @@
 TEST(Attributes, AddAttributes) {
   LLVMContext C;
   AttributeList AL;
-  AttrBuilder B;
+  AttrBuilder B(C);
   B.addAttribute(Attribute::NoReturn);
-  AL = AL.addFnAttributes(C, AttributeSet::get(C, B));
+  AL = AL.addFnAttributes(C, AttrBuilder(C, AttributeSet::get(C, B)));
   EXPECT_TRUE(AL.hasFnAttr(Attribute::NoReturn));
   B.clear();
   B.addAttribute(Attribute::SExt);
@@ -78,12 +78,12 @@
 
   Attribute AlignAttr = Attribute::getWithAlignment(C, 

[PATCH] D116919: [AST] Add RParen loc for decltype AutoTypeloc.

2022-01-10 Thread Nico Weber via Phabricator via cfe-commits
thakis added a comment.

Looks like this breaks tests: http://45.33.8.238/linux/64726/step_8.txt


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D116919

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


Re: [clang] 80e2c58 - [clang] Remove redundant member initialization (NFC)

2022-01-10 Thread Martin Storsjö via cfe-commits

On Sun, 9 Jan 2022, Kazu Hirata via cfe-commits wrote:



Author: Kazu Hirata
Date: 2022-01-09T00:19:51-08:00
New Revision: 80e2c587498a7b2bf14dde47a33a058da6e88a9a

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

LOG: [clang] Remove redundant member initialization (NFC)

Identified with readability-redundant-member-init.


While technically NFC, this causes lots of build warnings (689 warnings) 
when built with GCC, like this:


In file included from 
llvm-project/clang/include/clang/Basic/SourceManager.h:37:0,
 from 
llvm-project/clang/lib/Lex/ScratchBuffer.cpp:14:
llvm-project/clang/include/clang/Basic/Diagnostic.h: In 
copy constructor ‘clang::DiagnosticBuilder::DiagnosticBuilder(const 
clang::DiagnosticBuilder&)’:
llvm-project/clang/include/clang/Basic/Diagnostic.h:1329:3: 
warning: base class ‘class clang::StreamingDiagnostic’ should be 
explicitly initialized in the copy constructor [-Wextra]

   DiagnosticBuilder(const DiagnosticBuilder ) {
   ^


With that in mind, I would like to revert this commit - is that ok with 
you?


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


[PATCH] D116925: [clangd] Suppress warning about system_header pragma when editing headers

2022-01-10 Thread Sam McCall via Phabricator via cfe-commits
sammccall added a comment.

I wasn't sure whether to suppress this in clang or clangd, wonder what you 
think.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D116925

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


[PATCH] D116925: [clangd] Suppress warning about system_header pragma when editing headers

2022-01-10 Thread Sam McCall via Phabricator via cfe-commits
sammccall created this revision.
sammccall added a reviewer: hokein.
Herald added subscribers: usaxena95, kadircet, arphaman.
sammccall requested review of this revision.
Herald added subscribers: cfe-commits, MaskRay, ilya-biryukov.
Herald added a project: clang-tools-extra.

Not sure it's OK to suppress this in clang itself - if we're building a PCH
or module, maybe it matters?


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D116925

Files:
  clang-tools-extra/clangd/Diagnostics.cpp
  clang-tools-extra/clangd/ParsedAST.cpp
  clang-tools-extra/clangd/Preamble.cpp


Index: clang-tools-extra/clangd/Preamble.cpp
===
--- clang-tools-extra/clangd/Preamble.cpp
+++ clang-tools-extra/clangd/Preamble.cpp
@@ -350,7 +350,8 @@
   PreambleDiagnostics.setLevelAdjuster([&](DiagnosticsEngine::Level DiagLevel,
const clang::Diagnostic ) {
 if (Cfg.Diagnostics.SuppressAll ||
-isBuiltinDiagnosticSuppressed(Info.getID(), Cfg.Diagnostics.Suppress))
+isBuiltinDiagnosticSuppressed(Info.getID(), Cfg.Diagnostics.Suppress,
+  *CI.getLangOpts()))
   return DiagnosticsEngine::Ignored;
 switch (Info.getID()) {
 case diag::warn_no_newline_eof:
Index: clang-tools-extra/clangd/ParsedAST.cpp
===
--- clang-tools-extra/clangd/ParsedAST.cpp
+++ clang-tools-extra/clangd/ParsedAST.cpp
@@ -445,7 +445,8 @@
 ASTDiags.setLevelAdjuster([&](DiagnosticsEngine::Level DiagLevel,
   const clang::Diagnostic ) {
   if (Cfg.Diagnostics.SuppressAll ||
-  isBuiltinDiagnosticSuppressed(Info.getID(), 
Cfg.Diagnostics.Suppress))
+  isBuiltinDiagnosticSuppressed(Info.getID(), Cfg.Diagnostics.Suppress,
+Clang->getLangOpts()))
 return DiagnosticsEngine::Ignored;
 
   auto It = OverriddenSeverity.find(Info.getID());
Index: clang-tools-extra/clangd/Diagnostics.cpp
===
--- clang-tools-extra/clangd/Diagnostics.cpp
+++ clang-tools-extra/clangd/Diagnostics.cpp
@@ -879,7 +879,13 @@
 }
 
 bool isBuiltinDiagnosticSuppressed(unsigned ID,
-   const llvm::StringSet<> ) {
+   const llvm::StringSet<> ,
+   const LangOptions ) {
+  // Don't complain about header-only stuff in mainfiles if the main file is a
+  // header. (Not clear if this is reasonable to suppress in clang).
+  if (ID == diag::pp_pragma_sysheader_in_main_file && LangOpts.IsHeaderFile)
+return true;
+
   if (const char *CodePtr = getDiagnosticCode(ID)) {
 if (Suppress.contains(normalizeSuppressedCode(CodePtr)))
   return true;


Index: clang-tools-extra/clangd/Preamble.cpp
===
--- clang-tools-extra/clangd/Preamble.cpp
+++ clang-tools-extra/clangd/Preamble.cpp
@@ -350,7 +350,8 @@
   PreambleDiagnostics.setLevelAdjuster([&](DiagnosticsEngine::Level DiagLevel,
const clang::Diagnostic ) {
 if (Cfg.Diagnostics.SuppressAll ||
-isBuiltinDiagnosticSuppressed(Info.getID(), Cfg.Diagnostics.Suppress))
+isBuiltinDiagnosticSuppressed(Info.getID(), Cfg.Diagnostics.Suppress,
+  *CI.getLangOpts()))
   return DiagnosticsEngine::Ignored;
 switch (Info.getID()) {
 case diag::warn_no_newline_eof:
Index: clang-tools-extra/clangd/ParsedAST.cpp
===
--- clang-tools-extra/clangd/ParsedAST.cpp
+++ clang-tools-extra/clangd/ParsedAST.cpp
@@ -445,7 +445,8 @@
 ASTDiags.setLevelAdjuster([&](DiagnosticsEngine::Level DiagLevel,
   const clang::Diagnostic ) {
   if (Cfg.Diagnostics.SuppressAll ||
-  isBuiltinDiagnosticSuppressed(Info.getID(), Cfg.Diagnostics.Suppress))
+  isBuiltinDiagnosticSuppressed(Info.getID(), Cfg.Diagnostics.Suppress,
+Clang->getLangOpts()))
 return DiagnosticsEngine::Ignored;
 
   auto It = OverriddenSeverity.find(Info.getID());
Index: clang-tools-extra/clangd/Diagnostics.cpp
===
--- clang-tools-extra/clangd/Diagnostics.cpp
+++ clang-tools-extra/clangd/Diagnostics.cpp
@@ -879,7 +879,13 @@
 }
 
 bool isBuiltinDiagnosticSuppressed(unsigned ID,
-   const llvm::StringSet<> ) {
+   const llvm::StringSet<> ,
+   const LangOptions ) {
+  // Don't complain about header-only stuff in mainfiles if the main file is a
+  // header. (Not clear if this is reasonable to suppress in clang).
+  if (ID == 

[PATCH] D115932: [Analyzer] Create and handle SymbolCast for pointer to integral conversion

2022-01-10 Thread Denys Petrov via Phabricator via cfe-commits
ASDenysPetrov added inline comments.



Comment at: clang/lib/StaticAnalyzer/Core/SValBuilder.cpp:415-423
+  // FIXME This should be done in getAsSymbol. But then getAsSymbol should be
+  // the member function of SValBuilder (?)
+  if (symRHS)
+if (auto RLocAsInt = RHS.getAs()) {
+  auto FromTy = symRHS->getType();
+  auto ToTy = RLocAsInt->getType(this->Context);
+  symRHS = this->getSymbolManager().getCastSymbol(symRHS, FromTy, ToTy);

IMO this is not the right place for producing `SymbolCast` because we can meet 
`(type)x`-like semantics in a different contexts and expressions.



Comment at: clang/lib/StaticAnalyzer/Core/SValBuilder.cpp:419-420
+if (auto RLocAsInt = RHS.getAs()) {
+  auto FromTy = symRHS->getType();
+  auto ToTy = RLocAsInt->getType(this->Context);
+  symRHS = this->getSymbolManager().getCastSymbol(symRHS, FromTy, ToTy);

According to https://llvm.org/docs/CodingStandards.html#id28



Comment at: clang/lib/StaticAnalyzer/Core/SValBuilder.cpp:471-478
+  if (Optional RV = rhs.getAs()) {
+// Support pointer arithmetic where the addend is on the left
+// and the pointer on the right.
 
-if (IsCommutative(op)) {
-  // Swap operands.
-  return evalBinOpLN(state, op, *RV, lhs.castAs(), type);
-}
+assert(op == BO_Add);
 
+// Commute the operands.

This can be carried out to the separate revert revision as it is not related to 
this one directly


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D115932

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


[PATCH] D116266: [SPIR-V] Add linking of separate translation units using spirv-link

2022-01-10 Thread Sven van Haastregt via Phabricator via cfe-commits
svenvh accepted this revision.
svenvh added a comment.
This revision is now accepted and ready to land.

LGTM.  I made some minor comments, that can be fixed before committing.




Comment at: clang/docs/UsersManual.rst:3567
 
+Linking is done using `spirv-link` linker from `the SPIRV-Tools project
+`_. Similar to other

(or: "+the spirv-link linker")



Comment at: clang/docs/UsersManual.rst:3569
+`_. Similar to other
+linkers Clang will expect `spirv-link` to be installed separately and to be
+present in the ``PATH`` environment variable. Please refer to `the build and





Comment at: clang/lib/Driver/ToolChains/SPIRV.cpp:78
+void SPIRV::Linker::ConstructJob(Compilation , const JobAction ,
+  const InputInfo ,
+  const InputInfoList ,

Indentation seems to be slightly off?  Can be fixed on commit.


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

https://reviews.llvm.org/D116266

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


[PATCH] D116643: [clangd] Don't rename on symbols from system headers.

2022-01-10 Thread Haojian Wu via Phabricator via cfe-commits
hokein updated this revision to Diff 398588.
hokein marked 3 inline comments as done.
hokein added a comment.

address comments.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D116643

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


Index: clang-tools-extra/clangd/unittests/RenameTests.cpp
===
--- clang-tools-extra/clangd/unittests/RenameTests.cpp
+++ clang-tools-extra/clangd/unittests/RenameTests.cpp
@@ -1198,6 +1198,29 @@
 expectedResult(Code, NewName));
 }
 
+TEST(RenameTest, NoRenameOnSymbolsFromSystemHeaders) {
+  // Filter out references not from main file.
+  llvm::StringRef Test =
+  R"cpp(
+#include 
+SystemSym^bol abc;
+)cpp";
+
+  Annotations Code(Test);
+  auto TU = TestTU::withCode(Code.code());
+  TU.AdditionalFiles["system"] = R"cpp(
+class SystemSymbol {};
+)cpp";
+  TU.ExtraArgs = {"-isystem", testRoot()};
+  auto AST = TU.build();
+  llvm::StringRef NewName = "abcde";
+
+  auto Results = rename({Code.point(), NewName, AST, testPath(TU.Filename)});
+  EXPECT_FALSE(Results) << "expected rename returned an error: " << 
Code.code();
+  auto ActualMessage = llvm::toString(Results.takeError());
+  EXPECT_THAT(ActualMessage, testing::HasSubstr("not a supported kind"));
+}
+
 TEST(RenameTest, ProtobufSymbolIsExcluded) {
   Annotations Code("Prot^obuf buf;");
   auto TU = TestTU::withCode(Code.code());
Index: clang-tools-extra/clangd/refactor/Rename.cpp
===
--- clang-tools-extra/clangd/refactor/Rename.cpp
+++ clang-tools-extra/clangd/refactor/Rename.cpp
@@ -159,13 +159,17 @@
   return Result;
 }
 
-// By default, we exclude C++ standard symbols and protobuf symbols as rename
-// these symbols would change system/generated files which are unlikely to be
-// modified.
+// By default, we exclude symbols from system headers and protobuf symbols as
+// renaming these symbols would change system/generated files which are 
unlikely
+// to be good candidates for modification.
 bool isExcluded(const NamedDecl ) {
-  if (isProtoFile(RenameDecl.getLocation(),
-  RenameDecl.getASTContext().getSourceManager()))
+  const auto  = RenameDecl.getASTContext().getSourceManager();
+  if (SM.isInSystemHeader(RenameDecl.getLocation()))
 return true;
+  if (isProtoFile(RenameDecl.getLocation(), SM))
+return true;
+  // FIXME: Remove this std symbol list, as they should be covered by the
+  // above isInSystemHeader check.
   static const auto *StdSymbols = new llvm::DenseSet({
 #define SYMBOL(Name, NameSpace, Header) {#NameSpace #Name},
 #include "StdSymbolMap.inc"
@@ -248,6 +252,7 @@
 }
 llvm_unreachable("unhandled reason kind");
   };
+  // abc
   return error("Cannot rename symbol: {0}", Message(Reason));
 }
 


Index: clang-tools-extra/clangd/unittests/RenameTests.cpp
===
--- clang-tools-extra/clangd/unittests/RenameTests.cpp
+++ clang-tools-extra/clangd/unittests/RenameTests.cpp
@@ -1198,6 +1198,29 @@
 expectedResult(Code, NewName));
 }
 
+TEST(RenameTest, NoRenameOnSymbolsFromSystemHeaders) {
+  // Filter out references not from main file.
+  llvm::StringRef Test =
+  R"cpp(
+#include 
+SystemSym^bol abc;
+)cpp";
+
+  Annotations Code(Test);
+  auto TU = TestTU::withCode(Code.code());
+  TU.AdditionalFiles["system"] = R"cpp(
+class SystemSymbol {};
+)cpp";
+  TU.ExtraArgs = {"-isystem", testRoot()};
+  auto AST = TU.build();
+  llvm::StringRef NewName = "abcde";
+
+  auto Results = rename({Code.point(), NewName, AST, testPath(TU.Filename)});
+  EXPECT_FALSE(Results) << "expected rename returned an error: " << Code.code();
+  auto ActualMessage = llvm::toString(Results.takeError());
+  EXPECT_THAT(ActualMessage, testing::HasSubstr("not a supported kind"));
+}
+
 TEST(RenameTest, ProtobufSymbolIsExcluded) {
   Annotations Code("Prot^obuf buf;");
   auto TU = TestTU::withCode(Code.code());
Index: clang-tools-extra/clangd/refactor/Rename.cpp
===
--- clang-tools-extra/clangd/refactor/Rename.cpp
+++ clang-tools-extra/clangd/refactor/Rename.cpp
@@ -159,13 +159,17 @@
   return Result;
 }
 
-// By default, we exclude C++ standard symbols and protobuf symbols as rename
-// these symbols would change system/generated files which are unlikely to be
-// modified.
+// By default, we exclude symbols from system headers and protobuf symbols as
+// renaming these symbols would change system/generated files which are unlikely
+// to be good candidates for modification.
 bool isExcluded(const NamedDecl ) {
-  if (isProtoFile(RenameDecl.getLocation(),
-  

[PATCH] D116643: [clangd] Don't rename on symbols from system headers.

2022-01-10 Thread Haojian Wu via Phabricator via cfe-commits
hokein updated this revision to Diff 398589.
hokein added a comment.

remove accident changes.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D116643

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


Index: clang-tools-extra/clangd/unittests/RenameTests.cpp
===
--- clang-tools-extra/clangd/unittests/RenameTests.cpp
+++ clang-tools-extra/clangd/unittests/RenameTests.cpp
@@ -1198,6 +1198,29 @@
 expectedResult(Code, NewName));
 }
 
+TEST(RenameTest, NoRenameOnSymbolsFromSystemHeaders) {
+  // Filter out references not from main file.
+  llvm::StringRef Test =
+  R"cpp(
+#include 
+SystemSym^bol abc;
+)cpp";
+
+  Annotations Code(Test);
+  auto TU = TestTU::withCode(Code.code());
+  TU.AdditionalFiles["system"] = R"cpp(
+class SystemSymbol {};
+)cpp";
+  TU.ExtraArgs = {"-isystem", testRoot()};
+  auto AST = TU.build();
+  llvm::StringRef NewName = "abcde";
+
+  auto Results = rename({Code.point(), NewName, AST, testPath(TU.Filename)});
+  EXPECT_FALSE(Results) << "expected rename returned an error: " << 
Code.code();
+  auto ActualMessage = llvm::toString(Results.takeError());
+  EXPECT_THAT(ActualMessage, testing::HasSubstr("not a supported kind"));
+}
+
 TEST(RenameTest, ProtobufSymbolIsExcluded) {
   Annotations Code("Prot^obuf buf;");
   auto TU = TestTU::withCode(Code.code());
Index: clang-tools-extra/clangd/refactor/Rename.cpp
===
--- clang-tools-extra/clangd/refactor/Rename.cpp
+++ clang-tools-extra/clangd/refactor/Rename.cpp
@@ -159,13 +159,17 @@
   return Result;
 }
 
-// By default, we exclude C++ standard symbols and protobuf symbols as rename
-// these symbols would change system/generated files which are unlikely to be
-// modified.
+// By default, we exclude symbols from system headers and protobuf symbols as
+// renaming these symbols would change system/generated files which are 
unlikely
+// to be good candidates for modification.
 bool isExcluded(const NamedDecl ) {
-  if (isProtoFile(RenameDecl.getLocation(),
-  RenameDecl.getASTContext().getSourceManager()))
+  const auto  = RenameDecl.getASTContext().getSourceManager();
+  if (SM.isInSystemHeader(RenameDecl.getLocation()))
 return true;
+  if (isProtoFile(RenameDecl.getLocation(), SM))
+return true;
+  // FIXME: Remove this std symbol list, as they should be covered by the
+  // above isInSystemHeader check.
   static const auto *StdSymbols = new llvm::DenseSet({
 #define SYMBOL(Name, NameSpace, Header) {#NameSpace #Name},
 #include "StdSymbolMap.inc"


Index: clang-tools-extra/clangd/unittests/RenameTests.cpp
===
--- clang-tools-extra/clangd/unittests/RenameTests.cpp
+++ clang-tools-extra/clangd/unittests/RenameTests.cpp
@@ -1198,6 +1198,29 @@
 expectedResult(Code, NewName));
 }
 
+TEST(RenameTest, NoRenameOnSymbolsFromSystemHeaders) {
+  // Filter out references not from main file.
+  llvm::StringRef Test =
+  R"cpp(
+#include 
+SystemSym^bol abc;
+)cpp";
+
+  Annotations Code(Test);
+  auto TU = TestTU::withCode(Code.code());
+  TU.AdditionalFiles["system"] = R"cpp(
+class SystemSymbol {};
+)cpp";
+  TU.ExtraArgs = {"-isystem", testRoot()};
+  auto AST = TU.build();
+  llvm::StringRef NewName = "abcde";
+
+  auto Results = rename({Code.point(), NewName, AST, testPath(TU.Filename)});
+  EXPECT_FALSE(Results) << "expected rename returned an error: " << Code.code();
+  auto ActualMessage = llvm::toString(Results.takeError());
+  EXPECT_THAT(ActualMessage, testing::HasSubstr("not a supported kind"));
+}
+
 TEST(RenameTest, ProtobufSymbolIsExcluded) {
   Annotations Code("Prot^obuf buf;");
   auto TU = TestTU::withCode(Code.code());
Index: clang-tools-extra/clangd/refactor/Rename.cpp
===
--- clang-tools-extra/clangd/refactor/Rename.cpp
+++ clang-tools-extra/clangd/refactor/Rename.cpp
@@ -159,13 +159,17 @@
   return Result;
 }
 
-// By default, we exclude C++ standard symbols and protobuf symbols as rename
-// these symbols would change system/generated files which are unlikely to be
-// modified.
+// By default, we exclude symbols from system headers and protobuf symbols as
+// renaming these symbols would change system/generated files which are unlikely
+// to be good candidates for modification.
 bool isExcluded(const NamedDecl ) {
-  if (isProtoFile(RenameDecl.getLocation(),
-  RenameDecl.getASTContext().getSourceManager()))
+  const auto  = RenameDecl.getASTContext().getSourceManager();
+  if (SM.isInSystemHeader(RenameDecl.getLocation()))
 return true;
+  if (isProtoFile(RenameDecl.getLocation(), SM))
+ 

[PATCH] D116643: [clangd] Don't rename on symbols from system headers.

2022-01-10 Thread Haojian Wu via Phabricator via cfe-commits
hokein added inline comments.



Comment at: clang-tools-extra/clangd/refactor/Rename.cpp:171
+return true;
+  // FIXME: Remove this std symbol list, as they should be covered by the
+  // above isInSystemHeader check.

kbobyrev wrote:
> Any reason not to do this right now? (if we keep the comment, then it's 
> probably better as "Remove this check because it is redundant in the presence 
> of isInSystemHeader")
We could do it in this patch, I slightly prefer to do it in a followup patch, 
it'd require some changes in the unittests. (this FIXME was added in the last 
minute -- at the very beginning I didn't notice that it could be simplified) 


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D116643

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


[PATCH] D116503: [clang] Add --start-no-unused-arguments/--end-no-unused-arguments to silence some unused argument warnings

2022-01-10 Thread Martin Storsjö via Phabricator via cfe-commits
mstorsjo added a comment.

In D116503#3223094 , @MaskRay wrote:

> But make sure to wait a bit to see what others think.

Do you think it's ok to go ahead and land this change now, or should I wait a 
bit more? (I'd like to have it landed with enough margin before the 14.x branch 
so that it has time to settle before that.)


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D116503

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


[PATCH] D115932: [Analyzer] Create and handle SymbolCast for pointer to integral conversion

2022-01-10 Thread Denys Petrov via Phabricator via cfe-commits
ASDenysPetrov added inline comments.



Comment at: clang/lib/StaticAnalyzer/Core/SValBuilder.cpp:420
+  auto FromTy = symRHS->getType();
+  auto ToTy = RLocAsInt->getType(this->Context);
+  symRHS = this->getSymbolManager().getCastSymbol(symRHS, FromTy, ToTy);

Please take into account that `SVal::getType` may return NULL `QualType`. See 
function's description.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D115932

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


[PATCH] D115490: [clangd] Include fixer for missing functions in C

2022-01-10 Thread Sam McCall via Phabricator via cfe-commits
This revision was landed with ongoing or failed builds.
This revision was automatically updated to reflect the committed changes.
sammccall marked an inline comment as done.
Closed by commit rG1ab13793beaf: [clangd] Include fixer for missing functions 
in C (authored by sammccall).

Changed prior to commit:
  https://reviews.llvm.org/D115490?vs=393369=398556#toc

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D115490

Files:
  clang-tools-extra/clangd/Diagnostics.cpp
  clang-tools-extra/clangd/IncludeFixer.cpp
  clang-tools-extra/clangd/ParsedAST.cpp
  clang-tools-extra/clangd/unittests/DiagnosticsTests.cpp
  clang/lib/Sema/SemaDecl.cpp

Index: clang/lib/Sema/SemaDecl.cpp
===
--- clang/lib/Sema/SemaDecl.cpp
+++ clang/lib/Sema/SemaDecl.cpp
@@ -15002,7 +15002,24 @@
 diag_id = diag::ext_implicit_function_decl;
   else
 diag_id = diag::warn_implicit_function_decl;
+
+  TypoCorrection Corrected;
+  // Because typo correction is expensive, only do it if the implicit
+  // function declaration is going to be treated as an error.
+  //
+  // Perform the corection before issuing the main diagnostic, as some consumers
+  // use typo-correction callbacks to enhance the main diagnostic.
+  if (S && !ExternCPrev &&
+  (Diags.getDiagnosticLevel(diag_id, Loc) >= DiagnosticsEngine::Error)) {
+DeclFilterCCC CCC{};
+Corrected = CorrectTypo(DeclarationNameInfo(, Loc), LookupOrdinaryName,
+S, nullptr, CCC, CTK_NonError);
+  }
+
   Diag(Loc, diag_id) << 
+  if (Corrected)
+diagnoseTypo(Corrected, PDiag(diag::note_function_suggestion),
+ /*ErrorRecovery*/ false);
 
   // If we found a prior declaration of this function, don't bother building
   // another one. We've already pushed that one into scope, so there's nothing
@@ -15010,18 +15027,6 @@
   if (ExternCPrev)
 return ExternCPrev;
 
-  // Because typo correction is expensive, only do it if the implicit
-  // function declaration is going to be treated as an error.
-  if (Diags.getDiagnosticLevel(diag_id, Loc) >= DiagnosticsEngine::Error) {
-TypoCorrection Corrected;
-DeclFilterCCC CCC{};
-if (S && (Corrected =
-  CorrectTypo(DeclarationNameInfo(, Loc), LookupOrdinaryName,
-  S, nullptr, CCC, CTK_NonError)))
-  diagnoseTypo(Corrected, PDiag(diag::note_function_suggestion),
-   /*ErrorRecovery*/false);
-  }
-
   // Set a Declarator for the implicit definition: int foo();
   const char *Dummy;
   AttributeFactory attrFactory;
Index: clang-tools-extra/clangd/unittests/DiagnosticsTests.cpp
===
--- clang-tools-extra/clangd/unittests/DiagnosticsTests.cpp
+++ clang-tools-extra/clangd/unittests/DiagnosticsTests.cpp
@@ -1285,6 +1285,31 @@
   "Include  for symbol printf");
 }
 
+TEST(IncludeFixerTest, CImplicitFunctionDecl) {
+  Annotations Test("void x() { [[foo]](); }");
+  auto TU = TestTU::withCode(Test.code());
+  TU.Filename = "test.c";
+
+  Symbol Sym = func("foo");
+  Sym.Flags |= Symbol::IndexedForCodeCompletion;
+  Sym.CanonicalDeclaration.FileURI = "unittest:///foo.h";
+  Sym.IncludeHeaders.emplace_back("\"foo.h\"", 1);
+
+  SymbolSlab::Builder Slab;
+  Slab.insert(Sym);
+  auto Index =
+  MemIndex::build(std::move(Slab).build(), RefSlab(), RelationSlab());
+  TU.ExternalIndex = Index.get();
+
+  EXPECT_THAT(
+  *TU.build().getDiagnostics(),
+  ElementsAre(AllOf(
+  Diag(Test.range(),
+   "implicit declaration of function 'foo' is invalid in C99"),
+  WithFix(Fix(Range{}, "#include \"foo.h\"\n",
+  "Include \"foo.h\" for symbol foo");
+}
+
 TEST(DiagsInHeaders, DiagInsideHeader) {
   Annotations Main(R"cpp(
 #include [["a.h"]]
Index: clang-tools-extra/clangd/ParsedAST.cpp
===
--- clang-tools-extra/clangd/ParsedAST.cpp
+++ clang-tools-extra/clangd/ParsedAST.cpp
@@ -30,6 +30,7 @@
 #include "clang/AST/ASTContext.h"
 #include "clang/AST/Decl.h"
 #include "clang/Basic/Diagnostic.h"
+#include "clang/Basic/DiagnosticSema.h"
 #include "clang/Basic/LangOptions.h"
 #include "clang/Basic/SourceLocation.h"
 #include "clang/Basic/SourceManager.h"
@@ -37,17 +38,10 @@
 #include "clang/Frontend/CompilerInstance.h"
 #include "clang/Frontend/CompilerInvocation.h"
 #include "clang/Frontend/FrontendActions.h"
-#include "clang/Frontend/Utils.h"
-#include "clang/Index/IndexDataConsumer.h"
-#include "clang/Index/IndexingAction.h"
 #include "clang/Lex/Lexer.h"
-#include "clang/Lex/MacroInfo.h"
 #include "clang/Lex/PPCallbacks.h"
 #include "clang/Lex/Preprocessor.h"
-#include "clang/Lex/PreprocessorOptions.h"
-#include "clang/Sema/Sema.h"
 #include "clang/Serialization/ASTWriter.h"
-#include 

[clang-tools-extra] 1ab1379 - [clangd] Include fixer for missing functions in C

2022-01-10 Thread Sam McCall via cfe-commits

Author: Sam McCall
Date: 2022-01-10T12:17:19+01:00
New Revision: 1ab13793beafd1db0159a410560b3ce998b15f5e

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

LOG: [clangd] Include fixer for missing functions in C

A function call `unresolved()` in C will generate an implicit declaration
of the missing function and warn `ext_implicit_function_decl` or so.
(Compared to in C++ where we get `err_undeclared_var_use`).
We want to try to resolve these names.

Unfortunately typo correction is disabled in sema for performance
reasons unless this warning is promoted to error.
(We need typo correction for include-fixer.)
It's not clear to me where a switch to force this correction on should
go, include-fixer is kind of a hack. So hack more by telling sema we're
promoting them to error.

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

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

Added: 


Modified: 
clang-tools-extra/clangd/Diagnostics.cpp
clang-tools-extra/clangd/IncludeFixer.cpp
clang-tools-extra/clangd/ParsedAST.cpp
clang-tools-extra/clangd/unittests/DiagnosticsTests.cpp
clang/lib/Sema/SemaDecl.cpp

Removed: 




diff  --git a/clang-tools-extra/clangd/Diagnostics.cpp 
b/clang-tools-extra/clangd/Diagnostics.cpp
index b90a6a8fa945..126f4c3e50ad 100644
--- a/clang-tools-extra/clangd/Diagnostics.cpp
+++ b/clang-tools-extra/clangd/Diagnostics.cpp
@@ -419,6 +419,7 @@ llvm::raw_ostream <<(llvm::raw_ostream , const 
Diag ) {
   OS << Sep << Fix;
   Sep = ", ";
 }
+OS << "}";
   }
   return OS;
 }

diff  --git a/clang-tools-extra/clangd/IncludeFixer.cpp 
b/clang-tools-extra/clangd/IncludeFixer.cpp
index 8c020f2486f0..1f0515c1df70 100644
--- a/clang-tools-extra/clangd/IncludeFixer.cpp
+++ b/clang-tools-extra/clangd/IncludeFixer.cpp
@@ -193,6 +193,14 @@ std::vector 
IncludeFixer::fix(DiagnosticsEngine::Level DiagLevel,
   case diag::err_no_member_suggest:
   case diag::err_no_member_template:
   case diag::err_no_member_template_suggest:
+  case diag::warn_implicit_function_decl:
+  case diag::ext_implicit_function_decl:
+  case diag::err_opencl_implicit_function_decl:
+dlog("Unresolved name at {0}, last typo was {1}",
+ Info.getLocation().printToString(Info.getSourceManager()),
+ LastUnresolvedName
+ ? LastUnresolvedName->Loc.printToString(Info.getSourceManager())
+ : "none");
 if (LastUnresolvedName) {
   // Try to fix unresolved name caused by missing declaration.
   // E.g.
@@ -205,8 +213,7 @@ std::vector IncludeFixer::fix(DiagnosticsEngine::Level 
DiagLevel,
   //  UnresolvedName
   // We only attempt to recover a diagnostic if it has the same location as
   // the last seen unresolved name.
-  if (DiagLevel >= DiagnosticsEngine::Error &&
-  LastUnresolvedName->Loc == Info.getLocation())
+  if (LastUnresolvedName->Loc == Info.getLocation())
 return fixUnresolvedName();
 }
 break;
@@ -481,6 +488,7 @@ class IncludeFixer::UnresolvedNameRecorder : public 
ExternalSemaSource {
  CorrectionCandidateCallback ,
  DeclContext *MemberContext, bool EnteringContext,
  const ObjCObjectPointerType *OPT) override {
+dlog("CorrectTypo: {0}", Typo.getAsString());
 assert(SemaPtr && "Sema must have been set.");
 if (SemaPtr->isSFINAEContext())
   return TypoCorrection();

diff  --git a/clang-tools-extra/clangd/ParsedAST.cpp 
b/clang-tools-extra/clangd/ParsedAST.cpp
index 732c36813800..42552e9831a0 100644
--- a/clang-tools-extra/clangd/ParsedAST.cpp
+++ b/clang-tools-extra/clangd/ParsedAST.cpp
@@ -30,6 +30,7 @@
 #include "clang/AST/ASTContext.h"
 #include "clang/AST/Decl.h"
 #include "clang/Basic/Diagnostic.h"
+#include "clang/Basic/DiagnosticSema.h"
 #include "clang/Basic/LangOptions.h"
 #include "clang/Basic/SourceLocation.h"
 #include "clang/Basic/SourceManager.h"
@@ -37,17 +38,10 @@
 #include "clang/Frontend/CompilerInstance.h"
 #include "clang/Frontend/CompilerInvocation.h"
 #include "clang/Frontend/FrontendActions.h"
-#include "clang/Frontend/Utils.h"
-#include "clang/Index/IndexDataConsumer.h"
-#include "clang/Index/IndexingAction.h"
 #include "clang/Lex/Lexer.h"
-#include "clang/Lex/MacroInfo.h"
 #include "clang/Lex/PPCallbacks.h"
 #include "clang/Lex/Preprocessor.h"
-#include "clang/Lex/PreprocessorOptions.h"
-#include "clang/Sema/Sema.h"
 #include "clang/Serialization/ASTWriter.h"
-#include "clang/Serialization/PCHContainerOperations.h"
 #include "clang/Tooling/CompilationDatabase.h"
 #include "clang/Tooling/Syntax/Tokens.h"
 #include "llvm/ADT/ArrayRef.h"
@@ -55,7 +49,6 @@
 #include "llvm/ADT/SmallString.h"
 #include 

[PATCH] D116906: [OpenMP][AMDGPU] Optimize the linked in math libraries

2022-01-10 Thread Jon Chesterfield via Phabricator via cfe-commits
JonChesterfield accepted this revision.
JonChesterfield added a comment.
This revision is now accepted and ready to land.

Using the optimiser to hide errors in how we're pulling in libm is clearly not 
right, but it leaves us less obviously broken than we are at present.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D116906

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


[PATCH] D115932: [Analyzer] Create and handle SymbolCast for pointer to integral conversion

2022-01-10 Thread Denys Petrov via Phabricator via cfe-commits
ASDenysPetrov added a comment.

Starting producing `SymbolCast` you should be careful. Please pay attention on 
my revision D105340  before doing this. I 
don't want you walk through the thing I fought.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D115932

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


[PATCH] D116925: [clangd] Suppress warning about system_header pragma when editing headers

2022-01-10 Thread Haojian Wu via Phabricator via cfe-commits
hokein added a comment.

In D116925#3230991 , @sammccall wrote:

> I wasn't sure whether to suppress this in clang or clangd, wonder what you 
> think.

I think it is fine to do it in clang. `pp_pragma_once_in_main_file` is a 
similar diag, and clang has already suppressed it.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D116925

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


[clang] d2cc6c2 - Use a sorted array instead of a map to store AttrBuilder string attributes

2022-01-10 Thread via cfe-commits

Author: Serge Guelton
Date: 2022-01-10T14:49:53+01:00
New Revision: d2cc6c2d0c2f8a6e272110416a3fd579ed5a3ac1

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

LOG: Use a sorted array instead of a map to store AttrBuilder string attributes

Using and std::map for target dependent attributes is
inefficient: it makes its constructor slightly heavier, and involves extra
allocation for each new string attribute. Storing the attribute key/value as
strings implies extra allocation/copy step.

Use a sorted vector instead. Given the low number of attributes generally
involved, this is cheaper, as showcased by

https://llvm-compile-time-tracker.com/compare.php?from=5de322295f4ade692dc4f1823ae4450ad3c48af2=05bc480bf641a9e3b466619af43a2d123ee3f71d=instructions

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

Added: 


Modified: 
clang/lib/CodeGen/CGAtomic.cpp
clang/lib/CodeGen/CGBuiltin.cpp
clang/lib/CodeGen/CGCall.cpp
clang/lib/CodeGen/CGExpr.cpp
clang/lib/CodeGen/CodeGenModule.cpp
clang/lib/CodeGen/TargetInfo.cpp
llvm/include/llvm/CodeGen/IndirectThunks.h
llvm/include/llvm/IR/Attributes.h
llvm/lib/AsmParser/LLParser.cpp
llvm/lib/Bitcode/Reader/BitcodeReader.cpp
llvm/lib/CodeGen/Analysis.cpp
llvm/lib/CodeGen/CommandFlags.cpp
llvm/lib/CodeGen/GlobalISel/LegalizerHelper.cpp
llvm/lib/CodeGen/SelectionDAG/TargetLowering.cpp
llvm/lib/IR/Attributes.cpp
llvm/lib/IR/AutoUpgrade.cpp
llvm/lib/IR/Function.cpp
llvm/lib/IR/Verifier.cpp
llvm/lib/Target/WebAssembly/WebAssemblyLowerEmscriptenEHSjLj.cpp
llvm/lib/Transforms/Coroutines/CoroSplit.cpp
llvm/lib/Transforms/IPO/DeadArgumentElimination.cpp
llvm/lib/Transforms/InstCombine/InstCombineCalls.cpp
llvm/lib/Transforms/Scalar/RewriteStatepointsForGC.cpp
llvm/lib/Transforms/Utils/CallPromotionUtils.cpp
llvm/lib/Transforms/Utils/InlineFunction.cpp
llvm/lib/Transforms/Utils/SimplifyLibCalls.cpp
llvm/tools/bugpoint/CrashDebugger.cpp
llvm/tools/llvm-reduce/deltas/ReduceAttributes.cpp
llvm/unittests/ExecutionEngine/Orc/IndirectionUtilsTest.cpp
llvm/unittests/IR/AttributesTest.cpp
llvm/unittests/IR/InstructionsTest.cpp
mlir/lib/Target/LLVMIR/ModuleTranslation.cpp

Removed: 




diff  --git a/clang/lib/CodeGen/CGAtomic.cpp b/clang/lib/CodeGen/CGAtomic.cpp
index e81c5ba5055c6..6532f02879612 100644
--- a/clang/lib/CodeGen/CGAtomic.cpp
+++ b/clang/lib/CodeGen/CGAtomic.cpp
@@ -307,7 +307,7 @@ static RValue emitAtomicLibcall(CodeGenFunction ,
   const CGFunctionInfo  =
 CGF.CGM.getTypes().arrangeBuiltinFunctionCall(resultType, args);
   llvm::FunctionType *fnTy = CGF.CGM.getTypes().GetFunctionType(fnInfo);
-  llvm::AttrBuilder fnAttrB;
+  llvm::AttrBuilder fnAttrB(CGF.getLLVMContext());
   fnAttrB.addAttribute(llvm::Attribute::NoUnwind);
   fnAttrB.addAttribute(llvm::Attribute::WillReturn);
   llvm::AttributeList fnAttrs = llvm::AttributeList::get(

diff  --git a/clang/lib/CodeGen/CGBuiltin.cpp b/clang/lib/CodeGen/CGBuiltin.cpp
index 716134b123dd6..7b5d202afbba2 100644
--- a/clang/lib/CodeGen/CGBuiltin.cpp
+++ b/clang/lib/CodeGen/CGBuiltin.cpp
@@ -4925,7 +4925,7 @@ RValue CodeGenFunction::EmitBuiltinExpr(const GlobalDecl 
GD, unsigned BuiltinID,
   llvm::Value *Block =
   Builder.CreatePointerCast(Info.BlockArg, GenericVoidPtrTy);
 
-  AttrBuilder B;
+  AttrBuilder B(Builder.getContext());
   B.addByValAttr(NDRangeL.getAddress(*this).getElementType());
   llvm::AttributeList ByValAttrSet =
   llvm::AttributeList::get(CGM.getModule().getContext(), 3U, B);

diff  --git a/clang/lib/CodeGen/CGCall.cpp b/clang/lib/CodeGen/CGCall.cpp
index d70f78fea6b42..26f005131c7f4 100644
--- a/clang/lib/CodeGen/CGCall.cpp
+++ b/clang/lib/CodeGen/CGCall.cpp
@@ -1892,7 +1892,7 @@ void 
CodeGenModule::getDefaultFunctionAttributes(StringRef Name,
 }
 
 void CodeGenModule::addDefaultFunctionDefinitionAttributes(llvm::Function ) {
-  llvm::AttrBuilder FuncAttrs;
+  llvm::AttrBuilder FuncAttrs(F.getContext());
   getDefaultFunctionAttributes(F.getName(), F.hasOptNone(),
/* AttrOnCallSite = */ false, FuncAttrs);
   // TODO: call GetCPUAndFeaturesAttributes?
@@ -2014,8 +2014,8 @@ void CodeGenModule::ConstructAttributeList(StringRef Name,
llvm::AttributeList ,
unsigned ,
bool AttrOnCallSite, bool IsThunk) {
-  llvm::AttrBuilder FuncAttrs;
-  llvm::AttrBuilder RetAttrs;
+  llvm::AttrBuilder FuncAttrs(getLLVMContext());
+  llvm::AttrBuilder RetAttrs(getLLVMContext());
 
   // Collect function IR attributes from the CC lowering.
   // We'll collect the paramete and 

[PATCH] D115490: [clangd] Include fixer for missing functions in C

2022-01-10 Thread Sam McCall via Phabricator via cfe-commits
sammccall marked an inline comment as done.
sammccall added inline comments.



Comment at: clang/lib/Sema/SemaDecl.cpp:14995
+DeclFilterCCC CCC{};
+Corrected = CorrectTypo(DeclarationNameInfo(, Loc), LookupOrdinaryName,
+S, nullptr, CCC, CTK_NonError);

kadircet wrote:
> maybe some comments around importance of the sequencing here? it would 
> probably be nice to have that at a higher level documentation too, but 
> unclear where. as in theory it's not just about the typo correction but also 
> emitting diagnostics while doing so.
Yeah, this is obviously pretty hacky, and I don't have great ideas to improve 
it.
Added a comment to leave some breadcrumbs and discourage moving this code 
around.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D115490

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


[PATCH] D112646: [clang-tidy] Add `readability-container-contains` check

2022-01-10 Thread Adrian Vogelsgesang via Phabricator via cfe-commits
avogelsgesang added a comment.

Happy new year! - and a gentle ping ;)

Afaict, there are only two smaller issues remaining (see non-closed inline 
comments):

- do we want a test expectation to check for unmodified code
- should we remove a couple of comments from the code

Personally, I have no real opinion on those questions. Would be happy to get 
some guidance here, @whisperity, so we can wrap this review up


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D112646

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


[clang] d17fb46 - [Clang][AArch64][ARM] PMUv3.4 Option Added

2022-01-10 Thread Mubashar Ahmad via cfe-commits

Author: Mubashar Ahmad
Date: 2022-01-10T11:28:19Z
New Revision: d17fb46e894501568a1bf3b11a5d920817444630

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

LOG: [Clang][AArch64][ARM] PMUv3.4 Option Added

An option has been added to Clang to enable or disable
the PMU v3.4 architecture extension.

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

Added: 
clang/test/Driver/aarch64-perfmon.c
clang/test/Driver/arm-perfmon.c

Modified: 
llvm/include/llvm/Support/AArch64TargetParser.def
llvm/include/llvm/Support/AArch64TargetParser.h
llvm/include/llvm/Support/ARMTargetParser.def
llvm/include/llvm/Support/ARMTargetParser.h
llvm/lib/Support/AArch64TargetParser.cpp
llvm/unittests/Support/TargetParserTest.cpp

Removed: 




diff  --git a/clang/test/Driver/aarch64-perfmon.c 
b/clang/test/Driver/aarch64-perfmon.c
new file mode 100644
index 0..228e6d6f3f15a
--- /dev/null
+++ b/clang/test/Driver/aarch64-perfmon.c
@@ -0,0 +1,13 @@
+// RUN: %clang -### -target aarch64-none-none-eabi -march=armv8.4a+pmuv3p4 %s 
2>&1 | FileCheck --check-prefix=CHECK-PERFMON %s
+// RUN: %clang -### -target aarch64-none-none-eabi -march=armv8.2a+pmuv3p4 %s 
2>&1 | FileCheck --check-prefix=CHECK-PERFMON %s
+// CHECK-PERFMON: "-target-feature" "+perfmon"
+
+// RUN: %clang -### -target aarch64-none-none-eabi -march=armv8.4a+nopmuv3p4 
%s 2>&1 | FileCheck --check-prefix=CHECK-NOPERFMON %s
+// RUN: %clang -### -target aarch64-none-none-eabi -march=armv8.2a+nopmuv3p4 
%s 2>&1 | FileCheck --check-prefix=CHECK-NOPERFMON %s
+// CHECK-NOPERFMON: "-target-feature" "-perfmon"
+
+// RUN: %clang -### -target aarch64-none-none-eabi %s 2>&1 | 
FileCheck %s --check-prefix=ABSENTPERFMON
+// RUN: %clang -### -target aarch64-none-none-eabi -march=armv8.4a %s 2>&1 | 
FileCheck %s --check-prefix=ABSENTPERFMON
+// RUN: %clang -### -target aarch64-none-none-eabi -march=armv8.2a %s 2>&1 | 
FileCheck %s --check-prefix=ABSENTPERFMON
+// ABSENTPERFMON-NOT: "-target-feature" "+perfmon"
+// ABSENTPERFMON-NOT: "-target-feature" "-perfmon"
\ No newline at end of file

diff  --git a/clang/test/Driver/arm-perfmon.c b/clang/test/Driver/arm-perfmon.c
new file mode 100644
index 0..618bd98044691
--- /dev/null
+++ b/clang/test/Driver/arm-perfmon.c
@@ -0,0 +1,13 @@
+// RUN: %clang -### -target arm-none-none-eabi -march=armv8.4a+pmuv3p4 %s 2>&1 
| FileCheck --check-prefix=CHECK-PERFMON %s
+// RUN: %clang -### -target arm-none-none-eabi -march=armv8.2a+pmuv3p4 %s 2>&1 
| FileCheck --check-prefix=CHECK-PERFMON %s
+// CHECK-PERFMON: "-target-feature" "+perfmon"
+
+// RUN: %clang -### -target arm-none-none-eabi -march=armv8.4a+nopmuv3p4 %s 
2>&1 | FileCheck --check-prefix=CHECK-NOPERFMON %s
+// RUN: %clang -### -target arm-none-none-eabi -march=armv8.2a+nopmuv3p4 %s 
2>&1 | FileCheck --check-prefix=CHECK-NOPERFMON %s
+// CHECK-NOPERFMON: "-target-feature" "-perfmon"
+
+// RUN: %clang -### -target arm-none-none-eabi %s 2>&1 | 
FileCheck %s --check-prefix=ABSENTPERFMON
+// RUN: %clang -### -target arm-none-none-eabi -march=armv8.4a %s 2>&1 | 
FileCheck %s --check-prefix=ABSENTPERFMON
+// RUN: %clang -### -target arm-none-none-eabi -march=armv8.2a %s 2>&1 | 
FileCheck %s --check-prefix=ABSENTPERFMON
+// ABSENTPERFMON-NOT: "-target-feature" "+perfmon"
+// ABSENTPERFMON-NOT: "-target-feature" "-perfmon"
\ No newline at end of file

diff  --git a/llvm/include/llvm/Support/AArch64TargetParser.def 
b/llvm/include/llvm/Support/AArch64TargetParser.def
index 9d45f6abae6be..6619864e7ca16 100644
--- a/llvm/include/llvm/Support/AArch64TargetParser.def
+++ b/llvm/include/llvm/Support/AArch64TargetParser.def
@@ -144,6 +144,7 @@ AARCH64_ARCH_EXT_NAME("flagm",AArch64::AEK_FLAGM,   
"+flagm", "-flag
 AARCH64_ARCH_EXT_NAME("sme",  AArch64::AEK_SME, "+sme",   
"-sme")
 AARCH64_ARCH_EXT_NAME("sme-f64",  AArch64::AEK_SMEF64,  "+sme-f64", 
"-sme-f64")
 AARCH64_ARCH_EXT_NAME("sme-i64",  AArch64::AEK_SMEI64,  "+sme-i64", 
"-sme-i64")
+AARCH64_ARCH_EXT_NAME("pmuv3p4",  AArch64::AEK_PERFMON, "+perfmon", 
"-perfmon")
 #undef AARCH64_ARCH_EXT_NAME
 
 #ifndef AARCH64_CPU_NAME

diff  --git a/llvm/include/llvm/Support/AArch64TargetParser.h 
b/llvm/include/llvm/Support/AArch64TargetParser.h
index 15bb428f19bcd..06aad515c8bde 100644
--- a/llvm/include/llvm/Support/AArch64TargetParser.h
+++ b/llvm/include/llvm/Support/AArch64TargetParser.h
@@ -69,6 +69,7 @@ enum ArchExtKind : uint64_t {
   AEK_SME = 1ULL << 37,
   AEK_SMEF64 =  1ULL << 38,
   AEK_SMEI64 =  1ULL << 39,
+  AEK_PERFMON = 1ULL << 40,
 };
 
 enum class ArchKind {

diff  --git a/llvm/include/llvm/Support/ARMTargetParser.def 
b/llvm/include/llvm/Support/ARMTargetParser.def

[PATCH] D116748: [AArch64][ARM][Clang] PerfMon Extension Added

2022-01-10 Thread Mubashar Ahmad 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 rGd17fb46e8945: [Clang][AArch64][ARM] PMUv3.4 Option Added 
(authored by mubashar_).

Changed prior to commit:
  https://reviews.llvm.org/D116748?vs=397893=398558#toc

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D116748

Files:
  clang/test/Driver/aarch64-perfmon.c
  clang/test/Driver/arm-perfmon.c
  llvm/include/llvm/Support/AArch64TargetParser.def
  llvm/include/llvm/Support/AArch64TargetParser.h
  llvm/include/llvm/Support/ARMTargetParser.def
  llvm/include/llvm/Support/ARMTargetParser.h
  llvm/lib/Support/AArch64TargetParser.cpp
  llvm/unittests/Support/TargetParserTest.cpp

Index: llvm/unittests/Support/TargetParserTest.cpp
===
--- llvm/unittests/Support/TargetParserTest.cpp
+++ llvm/unittests/Support/TargetParserTest.cpp
@@ -728,7 +728,8 @@
   {"sb", "nosb", "+sb", "-sb"},
   {"i8mm", "noi8mm", "+i8mm", "-i8mm"},
   {"mve", "nomve", "+mve", "-mve"},
-  {"mve.fp", "nomve.fp", "+mve.fp", "-mve.fp"}};
+  {"mve.fp", "nomve.fp", "+mve.fp", "-mve.fp"},
+  {"pmuv3p4", "nopmuv3p4", "+perfmon", "-perfmon"}};
 
   for (unsigned i = 0; i < array_lengthof(ArchExt); i++) {
 EXPECT_EQ(StringRef(ArchExt[i][2]), ARM::getArchExtFeature(ArchExt[i][0]));
@@ -1428,17 +1429,14 @@
 
 TEST(TargetParserTest, AArch64ExtensionFeatures) {
   std::vector Extensions = {
-AArch64::AEK_CRC,  AArch64::AEK_CRYPTO,
-AArch64::AEK_FP,   AArch64::AEK_SIMD,
-AArch64::AEK_FP16, AArch64::AEK_PROFILE,
-AArch64::AEK_RAS,  AArch64::AEK_LSE,
-AArch64::AEK_RDM,  AArch64::AEK_DOTPROD,
-AArch64::AEK_SVE,  AArch64::AEK_SVE2,
-AArch64::AEK_SVE2AES,  AArch64::AEK_SVE2SM4,
-AArch64::AEK_SVE2SHA3, AArch64::AEK_SVE2BITPERM,
-AArch64::AEK_RCPC, AArch64::AEK_FP16FML,
-AArch64::AEK_SME,  AArch64::AEK_SMEF64,
-AArch64::AEK_SMEI64 };
+  AArch64::AEK_CRC, AArch64::AEK_CRYPTO,  AArch64::AEK_FP,
+  AArch64::AEK_SIMD,AArch64::AEK_FP16,AArch64::AEK_PROFILE,
+  AArch64::AEK_RAS, AArch64::AEK_LSE, AArch64::AEK_RDM,
+  AArch64::AEK_DOTPROD, AArch64::AEK_SVE, AArch64::AEK_SVE2,
+  AArch64::AEK_SVE2AES, AArch64::AEK_SVE2SM4, AArch64::AEK_SVE2SHA3,
+  AArch64::AEK_SVE2BITPERM, AArch64::AEK_RCPC,AArch64::AEK_FP16FML,
+  AArch64::AEK_SME, AArch64::AEK_SMEF64,  AArch64::AEK_SMEI64,
+  AArch64::AEK_PERFMON};
 
   std::vector Features;
 
@@ -1473,6 +1471,7 @@
   EXPECT_TRUE(llvm::is_contained(Features, "+sme"));
   EXPECT_TRUE(llvm::is_contained(Features, "+sme-f64"));
   EXPECT_TRUE(llvm::is_contained(Features, "+sme-i64"));
+  EXPECT_TRUE(llvm::is_contained(Features, "+perfmon"));
 }
 
 TEST(TargetParserTest, AArch64ArchFeatures) {
@@ -1485,43 +1484,41 @@
 }
 
 TEST(TargetParserTest, AArch64ArchExtFeature) {
-  const char *ArchExt[][4] = {{"crc", "nocrc", "+crc", "-crc"},
-  {"crypto", "nocrypto", "+crypto", "-crypto"},
-  {"flagm", "noflagm", "+flagm", "-flagm"},
-  {"fp", "nofp", "+fp-armv8", "-fp-armv8"},
-  {"simd", "nosimd", "+neon", "-neon"},
-  {"fp16", "nofp16", "+fullfp16", "-fullfp16"},
-  {"fp16fml", "nofp16fml", "+fp16fml", "-fp16fml"},
-  {"profile", "noprofile", "+spe", "-spe"},
-  {"ras", "noras", "+ras", "-ras"},
-  {"lse", "nolse", "+lse", "-lse"},
-  {"rdm", "nordm", "+rdm", "-rdm"},
-  {"sve", "nosve", "+sve", "-sve"},
-  {"sve2", "nosve2", "+sve2", "-sve2"},
-  {"sve2-aes", "nosve2-aes", "+sve2-aes",
-   "-sve2-aes"},
-  {"sve2-sm4", "nosve2-sm4", "+sve2-sm4",
-   "-sve2-sm4"},
-  {"sve2-sha3", "nosve2-sha3", "+sve2-sha3",
-   "-sve2-sha3"},
-  {"sve2-bitperm", "nosve2-bitperm",
-   "+sve2-bitperm", "-sve2-bitperm"},
-  {"dotprod", "nodotprod", "+dotprod", "-dotprod"},
-  {"rcpc", "norcpc", "+rcpc", "-rcpc" },
-  {"rng", "norng", "+rand", "-rand"},
-  {"memtag", "nomemtag", "+mte", "-mte"},
-  {"tme", "notme", "+tme", "-tme"},
-   

[clang] abe3003 - [AST] Use recovery-expr to preserve incomplete-type-member-access expression.

2022-01-10 Thread Haojian Wu via cfe-commits

Author: Haojian Wu
Date: 2022-01-10T12:45:20+01:00
New Revision: abe3003ead808518190d1e9717495735786938d3

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

LOG: [AST] Use recovery-expr to preserve incomplete-type-member-access 
expression.

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

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

Added: 


Modified: 
clang/lib/Sema/SemaExprCXX.cpp
clang/test/AST/ast-dump-recovery.cpp
clang/test/OpenMP/declare_reduction_messages.cpp

Removed: 




diff  --git a/clang/lib/Sema/SemaExprCXX.cpp b/clang/lib/Sema/SemaExprCXX.cpp
index 4c6a96acdb91..b34b744d7312 100644
--- a/clang/lib/Sema/SemaExprCXX.cpp
+++ b/clang/lib/Sema/SemaExprCXX.cpp
@@ -7410,8 +7410,10 @@ ExprResult Sema::ActOnStartCXXMemberReference(Scope *S, 
Expr *Base,
   //   the member function body.
   if (!BaseType->isDependentType() &&
   !isThisOutsideMemberFunctionBody(BaseType) &&
-  RequireCompleteType(OpLoc, BaseType, diag::err_incomplete_member_access))
-return ExprError();
+  RequireCompleteType(OpLoc, BaseType,
+  diag::err_incomplete_member_access)) {
+return CreateRecoveryExpr(Base->getBeginLoc(), Base->getEndLoc(), {Base});
+  }
 
   // C++ [basic.lookup.classref]p2:
   //   If the id-expression in a class member access (5.2.5) is an

diff  --git a/clang/test/AST/ast-dump-recovery.cpp 
b/clang/test/AST/ast-dump-recovery.cpp
index c196f629bad9..0bdd726ab3ce 100644
--- a/clang/test/AST/ast-dump-recovery.cpp
+++ b/clang/test/AST/ast-dump-recovery.cpp
@@ -121,6 +121,16 @@ void test(int x) {
   foo->func(x);
 }
 
+void AccessIncompleteClass() {
+  struct Forward;
+  Forward* ptr;
+  // CHECK:  CallExpr {{.*}} ''
+  // CHECK-NEXT: `-CXXDependentScopeMemberExpr {{.*}} ''
+  // CHECK-NEXT:   `-RecoveryExpr {{.*}} '' contains-errors
+  // CHECK-NEXT: `-DeclRefExpr {{.*}} 'Forward *'
+  ptr->method();
+}
+
 struct Foo2 {
   double func();
   class ForwardClass;

diff  --git a/clang/test/OpenMP/declare_reduction_messages.cpp 
b/clang/test/OpenMP/declare_reduction_messages.cpp
index b1e59591d998..38a5d766eead 100644
--- a/clang/test/OpenMP/declare_reduction_messages.cpp
+++ b/clang/test/OpenMP/declare_reduction_messages.cpp
@@ -169,7 +169,6 @@ struct S
   #pragma omp declare reduction (xxx : U, S : bar(omp_in)) // expected-error 
{{non-const lvalue reference to type 'S<1>' cannot bind to a value of unrelated 
type 'U'}}
   static void bar(S ); // expected-note {{passing argument to parameter 'x' 
here}}
 };
-// expected-warning@+2 {{extra tokens at the end of '#pragma omp declare 
reduction' are ignored}}
 // expected-note@+1 {{in instantiation of template class 'S<1>' requested 
here}}
 #pragma omp declare reduction (bar : S<1> : omp_out.foo(omp_in))
 



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


[PATCH] D116922: [AST] Use recovery-expr to preserve incomplete-type-member-access expression.

2022-01-10 Thread Haojian Wu via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rGabe3003ead80: [AST] Use recovery-expr to preserve 
incomplete-type-member-access expression. (authored by hokein).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D116922

Files:
  clang/lib/Sema/SemaExprCXX.cpp
  clang/test/AST/ast-dump-recovery.cpp
  clang/test/OpenMP/declare_reduction_messages.cpp


Index: clang/test/OpenMP/declare_reduction_messages.cpp
===
--- clang/test/OpenMP/declare_reduction_messages.cpp
+++ clang/test/OpenMP/declare_reduction_messages.cpp
@@ -169,7 +169,6 @@
   #pragma omp declare reduction (xxx : U, S : bar(omp_in)) // expected-error 
{{non-const lvalue reference to type 'S<1>' cannot bind to a value of unrelated 
type 'U'}}
   static void bar(S ); // expected-note {{passing argument to parameter 'x' 
here}}
 };
-// expected-warning@+2 {{extra tokens at the end of '#pragma omp declare 
reduction' are ignored}}
 // expected-note@+1 {{in instantiation of template class 'S<1>' requested 
here}}
 #pragma omp declare reduction (bar : S<1> : omp_out.foo(omp_in))
 
Index: clang/test/AST/ast-dump-recovery.cpp
===
--- clang/test/AST/ast-dump-recovery.cpp
+++ clang/test/AST/ast-dump-recovery.cpp
@@ -121,6 +121,16 @@
   foo->func(x);
 }
 
+void AccessIncompleteClass() {
+  struct Forward;
+  Forward* ptr;
+  // CHECK:  CallExpr {{.*}} ''
+  // CHECK-NEXT: `-CXXDependentScopeMemberExpr {{.*}} ''
+  // CHECK-NEXT:   `-RecoveryExpr {{.*}} '' contains-errors
+  // CHECK-NEXT: `-DeclRefExpr {{.*}} 'Forward *'
+  ptr->method();
+}
+
 struct Foo2 {
   double func();
   class ForwardClass;
Index: clang/lib/Sema/SemaExprCXX.cpp
===
--- clang/lib/Sema/SemaExprCXX.cpp
+++ clang/lib/Sema/SemaExprCXX.cpp
@@ -7410,8 +7410,10 @@
   //   the member function body.
   if (!BaseType->isDependentType() &&
   !isThisOutsideMemberFunctionBody(BaseType) &&
-  RequireCompleteType(OpLoc, BaseType, diag::err_incomplete_member_access))
-return ExprError();
+  RequireCompleteType(OpLoc, BaseType,
+  diag::err_incomplete_member_access)) {
+return CreateRecoveryExpr(Base->getBeginLoc(), Base->getEndLoc(), {Base});
+  }
 
   // C++ [basic.lookup.classref]p2:
   //   If the id-expression in a class member access (5.2.5) is an


Index: clang/test/OpenMP/declare_reduction_messages.cpp
===
--- clang/test/OpenMP/declare_reduction_messages.cpp
+++ clang/test/OpenMP/declare_reduction_messages.cpp
@@ -169,7 +169,6 @@
   #pragma omp declare reduction (xxx : U, S : bar(omp_in)) // expected-error {{non-const lvalue reference to type 'S<1>' cannot bind to a value of unrelated type 'U'}}
   static void bar(S ); // expected-note {{passing argument to parameter 'x' here}}
 };
-// expected-warning@+2 {{extra tokens at the end of '#pragma omp declare reduction' are ignored}}
 // expected-note@+1 {{in instantiation of template class 'S<1>' requested here}}
 #pragma omp declare reduction (bar : S<1> : omp_out.foo(omp_in))
 
Index: clang/test/AST/ast-dump-recovery.cpp
===
--- clang/test/AST/ast-dump-recovery.cpp
+++ clang/test/AST/ast-dump-recovery.cpp
@@ -121,6 +121,16 @@
   foo->func(x);
 }
 
+void AccessIncompleteClass() {
+  struct Forward;
+  Forward* ptr;
+  // CHECK:  CallExpr {{.*}} ''
+  // CHECK-NEXT: `-CXXDependentScopeMemberExpr {{.*}} ''
+  // CHECK-NEXT:   `-RecoveryExpr {{.*}} '' contains-errors
+  // CHECK-NEXT: `-DeclRefExpr {{.*}} 'Forward *'
+  ptr->method();
+}
+
 struct Foo2 {
   double func();
   class ForwardClass;
Index: clang/lib/Sema/SemaExprCXX.cpp
===
--- clang/lib/Sema/SemaExprCXX.cpp
+++ clang/lib/Sema/SemaExprCXX.cpp
@@ -7410,8 +7410,10 @@
   //   the member function body.
   if (!BaseType->isDependentType() &&
   !isThisOutsideMemberFunctionBody(BaseType) &&
-  RequireCompleteType(OpLoc, BaseType, diag::err_incomplete_member_access))
-return ExprError();
+  RequireCompleteType(OpLoc, BaseType,
+  diag::err_incomplete_member_access)) {
+return CreateRecoveryExpr(Base->getBeginLoc(), Base->getEndLoc(), {Base});
+  }
 
   // C++ [basic.lookup.classref]p2:
   //   If the id-expression in a class member access (5.2.5) is an
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] 55d96ac - [AST] Add RParen loc for decltype AutoTypeloc.

2022-01-10 Thread Haojian Wu via cfe-commits

Author: Haojian Wu
Date: 2022-01-10T12:46:27+01:00
New Revision: 55d96ac3dc56bdebea854952a724c2a50d96ce19

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

LOG: [AST] Add RParen loc for decltype AutoTypeloc.

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

Added: 


Modified: 
clang-tools-extra/clangd/unittests/SelectionTests.cpp
clang/include/clang/AST/TypeLoc.h
clang/lib/AST/TypeLoc.cpp
clang/lib/Sema/SemaType.cpp
clang/lib/Serialization/ASTReader.cpp
clang/lib/Serialization/ASTWriter.cpp
clang/test/AST/ast-dump-template-decls-json.cpp
clang/test/AST/ast-dump-template-decls.cpp
clang/unittests/AST/SourceLocationTest.cpp

Removed: 




diff  --git a/clang-tools-extra/clangd/unittests/SelectionTests.cpp 
b/clang-tools-extra/clangd/unittests/SelectionTests.cpp
index 7e19f07a2215e..0f4464122c8fb 100644
--- a/clang-tools-extra/clangd/unittests/SelectionTests.cpp
+++ b/clang-tools-extra/clangd/unittests/SelectionTests.cpp
@@ -391,6 +391,8 @@ TEST(SelectionTest, CommonAncestor) {
 )cpp",
   "DeclRefExpr"},
   {"[[decltype^(1)]] b;", "DecltypeTypeLoc"}, // Not the VarDecl.
+  // decltype(auto) is an AutoTypeLoc!
+  {"[[de^cltype(a^uto)]] a = 1;", "AutoTypeLoc"},
 
   // Objective-C nullability attributes.
   {

diff  --git a/clang/include/clang/AST/TypeLoc.h 
b/clang/include/clang/AST/TypeLoc.h
index 9a43d34a9ec38..9c7ab4e8ddb7b 100644
--- a/clang/include/clang/AST/TypeLoc.h
+++ b/clang/include/clang/AST/TypeLoc.h
@@ -2081,6 +2081,9 @@ struct AutoTypeLocInfo : TypeSpecLocInfo {
   NamedDecl *FoundDecl;
   SourceLocation LAngleLoc;
   SourceLocation RAngleLoc;
+
+  // For decltype(auto).
+  SourceLocation RParenLoc;
 };
 
 class AutoTypeLoc
@@ -2093,6 +2096,10 @@ class AutoTypeLoc
 return getTypePtr()->getKeyword();
   }
 
+  bool isDecltypeAuto() const { return getTypePtr()->isDecltypeAuto(); }
+  SourceLocation getRParenLoc() const { return getLocalData()->RParenLoc; }
+  void setRParenLoc(SourceLocation Loc) { getLocalData()->RParenLoc = Loc; }
+
   bool isConstrained() const {
 return getTypePtr()->isConstrained();
   }
@@ -2173,16 +2180,13 @@ class AutoTypeLoc
   }
 
   SourceRange getLocalSourceRange() const {
-return{
-isConstrained()
-  ? (getNestedNameSpecifierLoc()
-   ? getNestedNameSpecifierLoc().getBeginLoc()
-   : (getTemplateKWLoc().isValid()
-  ? getTemplateKWLoc()
-  : getConceptNameLoc()))
-  : getNameLoc(),
-getNameLoc()
-};
+return {isConstrained()
+? (getNestedNameSpecifierLoc()
+   ? getNestedNameSpecifierLoc().getBeginLoc()
+   : (getTemplateKWLoc().isValid() ? getTemplateKWLoc()
+   : getConceptNameLoc()))
+: getNameLoc(),
+isDecltypeAuto() ? getRParenLoc() : getNameLoc()};
   }
 
   void copy(AutoTypeLoc Loc) {

diff  --git a/clang/lib/AST/TypeLoc.cpp b/clang/lib/AST/TypeLoc.cpp
index c3ed08d5a8b3e..13aa54c48f66c 100644
--- a/clang/lib/AST/TypeLoc.cpp
+++ b/clang/lib/AST/TypeLoc.cpp
@@ -622,6 +622,7 @@ void AutoTypeLoc::initializeLocal(ASTContext , 
SourceLocation Loc) {
   setFoundDecl(nullptr);
   setRAngleLoc(Loc);
   setLAngleLoc(Loc);
+  setRParenLoc(Loc);
   TemplateSpecializationTypeLoc::initializeArgLocs(Context, getNumArgs(),
getTypePtr()->getArgs(),
getArgInfos(), Loc);

diff  --git a/clang/lib/Sema/SemaType.cpp b/clang/lib/Sema/SemaType.cpp
index f0bbbcf59c751..959f4903b0306 100644
--- a/clang/lib/Sema/SemaType.cpp
+++ b/clang/lib/Sema/SemaType.cpp
@@ -22,6 +22,7 @@
 #include "clang/AST/TypeLoc.h"
 #include "clang/AST/TypeLocVisitor.h"
 #include "clang/Basic/PartialDiagnostic.h"
+#include "clang/Basic/Specifiers.h"
 #include "clang/Basic/TargetInfo.h"
 #include "clang/Lex/Preprocessor.h"
 #include "clang/Sema/DeclSpec.h"
@@ -6041,6 +6042,8 @@ namespace {
  DS.getTypeSpecType() == TST_auto_type ||
  DS.getTypeSpecType() == TST_unspecified);
   TL.setNameLoc(DS.getTypeSpecTypeLoc());
+  if (DS.getTypeSpecType() == TST_decltype_auto)
+TL.setRParenLoc(DS.getTypeofParensRange().getEnd());
   if (!DS.isConstrainedAuto())
 return;
   TemplateIdAnnotation *TemplateId = DS.getRepAsTemplateId();

diff  --git a/clang/lib/Serialization/ASTReader.cpp 
b/clang/lib/Serialization/ASTReader.cpp
index b8ec5b2722a95..9056f00978c8f 100644
--- a/clang/lib/Serialization/ASTReader.cpp
+++ b/clang/lib/Serialization/ASTReader.cpp
@@ -6652,6 +6652,8 @@ void TypeLocReader::VisitAutoTypeLoc(AutoTypeLoc 

[PATCH] D116919: [AST] Add RParen loc for decltype AutoTypeloc.

2022-01-10 Thread Haojian Wu 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 rG55d96ac3dc56: [AST] Add RParen loc for decltype AutoTypeloc. 
(authored by hokein).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D116919

Files:
  clang-tools-extra/clangd/unittests/SelectionTests.cpp
  clang/include/clang/AST/TypeLoc.h
  clang/lib/AST/TypeLoc.cpp
  clang/lib/Sema/SemaType.cpp
  clang/lib/Serialization/ASTReader.cpp
  clang/lib/Serialization/ASTWriter.cpp
  clang/test/AST/ast-dump-template-decls-json.cpp
  clang/test/AST/ast-dump-template-decls.cpp
  clang/unittests/AST/SourceLocationTest.cpp

Index: clang/unittests/AST/SourceLocationTest.cpp
===
--- clang/unittests/AST/SourceLocationTest.cpp
+++ clang/unittests/AST/SourceLocationTest.cpp
@@ -242,6 +242,13 @@
   verify(Target2->getSourceRange(), Code.range("full2"));
 }
 
+TEST(TypeLoc, AutoTypeLocRange) {
+  RangeVerifier Verifier;
+  Verifier.expectRange(1, 1, 1, 14);
+  EXPECT_TRUE(Verifier.match("decltype(auto) a = 1;", typeLoc(loc(autoType())),
+ Lang_CXX11));
+}
+
 TEST(TypeLoc, LongDoubleRange) {
   RangeVerifier Verifier;
   Verifier.expectRange(1, 1, 1, 6);
Index: clang/test/AST/ast-dump-template-decls.cpp
===
--- clang/test/AST/ast-dump-template-decls.cpp
+++ clang/test/AST/ast-dump-template-decls.cpp
@@ -90,7 +90,7 @@
 
 template 
 // CHECK: ClassTemplateDecl 0x{{[^ ]*}}  col:8 U
-// CHECK-NEXT: NonTypeTemplateParmDecl 0x{{[^ ]*}}  col:25 'decltype(auto)' depth 0 index 0
+// CHECK-NEXT: NonTypeTemplateParmDecl 0x{{[^ ]*}}  col:25 'decltype(auto)' depth 0 index 0
 struct U {};
 
 template 
Index: clang/test/AST/ast-dump-template-decls-json.cpp
===
--- clang/test/AST/ast-dump-template-decls-json.cpp
+++ clang/test/AST/ast-dump-template-decls-json.cpp
@@ -2130,9 +2130,9 @@
 // CHECK-NEXT:"tokLen": 8
 // CHECK-NEXT:   },
 // CHECK-NEXT:   "end": {
-// CHECK-NEXT:"offset": 705,
-// CHECK-NEXT:"col": 11,
-// CHECK-NEXT:"tokLen": 8
+// CHECK-NEXT:"offset": 718,
+// CHECK-NEXT:"col": 24,
+// CHECK-NEXT:"tokLen": 1
 // CHECK-NEXT:   }
 // CHECK-NEXT:  },
 // CHECK-NEXT:  "type": {
Index: clang/lib/Serialization/ASTWriter.cpp
===
--- clang/lib/Serialization/ASTWriter.cpp
+++ clang/lib/Serialization/ASTWriter.cpp
@@ -452,6 +452,9 @@
   Record.AddTemplateArgumentLocInfo(TL.getTypePtr()->getArg(I).getKind(),
 TL.getArgLocInfo(I));
   }
+  Record.push_back(TL.isDecltypeAuto());
+  if (TL.isDecltypeAuto())
+Record.AddSourceLocation(TL.getRParenLoc());
 }
 
 void TypeLocWriter::VisitDeducedTemplateSpecializationTypeLoc(
Index: clang/lib/Serialization/ASTReader.cpp
===
--- clang/lib/Serialization/ASTReader.cpp
+++ clang/lib/Serialization/ASTReader.cpp
@@ -6652,6 +6652,8 @@
   TL.setArgLocInfo(i, Reader.readTemplateArgumentLocInfo(
   TL.getTypePtr()->getArg(i).getKind()));
   }
+  if (Reader.readBool())
+TL.setRParenLoc(readSourceLocation());
 }
 
 void TypeLocReader::VisitDeducedTemplateSpecializationTypeLoc(
Index: clang/lib/Sema/SemaType.cpp
===
--- clang/lib/Sema/SemaType.cpp
+++ clang/lib/Sema/SemaType.cpp
@@ -22,6 +22,7 @@
 #include "clang/AST/TypeLoc.h"
 #include "clang/AST/TypeLocVisitor.h"
 #include "clang/Basic/PartialDiagnostic.h"
+#include "clang/Basic/Specifiers.h"
 #include "clang/Basic/TargetInfo.h"
 #include "clang/Lex/Preprocessor.h"
 #include "clang/Sema/DeclSpec.h"
@@ -6041,6 +6042,8 @@
  DS.getTypeSpecType() == TST_auto_type ||
  DS.getTypeSpecType() == TST_unspecified);
   TL.setNameLoc(DS.getTypeSpecTypeLoc());
+  if (DS.getTypeSpecType() == TST_decltype_auto)
+TL.setRParenLoc(DS.getTypeofParensRange().getEnd());
   if (!DS.isConstrainedAuto())
 return;
   TemplateIdAnnotation *TemplateId = DS.getRepAsTemplateId();
Index: clang/lib/AST/TypeLoc.cpp
===
--- clang/lib/AST/TypeLoc.cpp
+++ clang/lib/AST/TypeLoc.cpp
@@ -622,6 +622,7 @@
   setFoundDecl(nullptr);
   setRAngleLoc(Loc);
   setLAngleLoc(Loc);
+  setRParenLoc(Loc);
   TemplateSpecializationTypeLoc::initializeArgLocs(Context, getNumArgs(),
getTypePtr()->getArgs(),
getArgInfos(), Loc);
Index: clang/include/clang/AST/TypeLoc.h

[PATCH] D116266: [SPIR-V] Add linking of separate translation units using spirv-link

2022-01-10 Thread Anastasia Stulova via Phabricator via cfe-commits
Anastasia added a comment.

RFC to clang dev list: 
https://lists.llvm.org/pipermail/cfe-dev/2022-January/069658.html


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

https://reviews.llvm.org/D116266

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


[clang-tools-extra] 37ec65e - [clangd] Enable expand-auto for decltype(auto).

2022-01-10 Thread Haojian Wu via cfe-commits

Author: Haojian Wu
Date: 2022-01-10T13:46:56+01:00
New Revision: 37ec65e1d705f56fe5551de1dfcbac1e071588a2

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

LOG: [clangd] Enable expand-auto for decltype(auto).

Based on https://reviews.llvm.org/D116919.

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

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

Added: 


Modified: 
clang-tools-extra/clangd/refactor/tweaks/ExpandAutoType.cpp
clang-tools-extra/clangd/unittests/tweaks/ExpandAutoTypeTests.cpp

Removed: 




diff  --git a/clang-tools-extra/clangd/refactor/tweaks/ExpandAutoType.cpp 
b/clang-tools-extra/clangd/refactor/tweaks/ExpandAutoType.cpp
index 3776e1c3505d1..914564e9ae218 100644
--- a/clang-tools-extra/clangd/refactor/tweaks/ExpandAutoType.cpp
+++ b/clang-tools-extra/clangd/refactor/tweaks/ExpandAutoType.cpp
@@ -96,9 +96,7 @@ bool ExpandAutoType::prepare(const Selection& Inputs) {
   if (auto *Node = Inputs.ASTSelection.commonAncestor()) {
 if (auto *TypeNode = Node->ASTNode.get()) {
   if (const AutoTypeLoc Result = TypeNode->getAs()) {
-// Code in apply() does handle 'decltype(auto)' yet.
-if (!Result.getTypePtr()->isDecltypeAuto() &&
-!isStructuredBindingType(Node) &&
+if (!isStructuredBindingType(Node) &&
 !isDeducedAsLambda(Node, Result.getBeginLoc()) &&
 !isTemplateParam(Node))
   CachedLocation = Result;

diff  --git a/clang-tools-extra/clangd/unittests/tweaks/ExpandAutoTypeTests.cpp 
b/clang-tools-extra/clangd/unittests/tweaks/ExpandAutoTypeTests.cpp
index 96574a67b5a46..6d9d4362be7af 100644
--- a/clang-tools-extra/clangd/unittests/tweaks/ExpandAutoTypeTests.cpp
+++ b/clang-tools-extra/clangd/unittests/tweaks/ExpandAutoTypeTests.cpp
@@ -71,7 +71,8 @@ TEST_F(ExpandAutoTypeTest, Test) {
   apply("void ns::Func() { au^to x = new ns::Class::Nested{}; }"),
   "void ns::Func() { ns::Class::Nested * x = new ns::Class::Nested{}; }");
 
-  EXPECT_UNAVAILABLE("dec^ltype(au^to) x = 10;");
+  EXPECT_EQ(apply("dec^ltype(auto) x = 10;"), "int x = 10;");
+  EXPECT_EQ(apply("decltype(au^to) x = 10;"), "int x = 10;");
   // expanding types in structured bindings is syntactically invalid.
   EXPECT_UNAVAILABLE("const ^auto &[x,y] = (int[]){1,2};");
 



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


[PATCH] D116921: [clangd] Enable expand-auto for decltype(auto).

2022-01-10 Thread Haojian Wu via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG37ec65e1d705: [clangd] Enable expand-auto for 
decltype(auto). (authored by hokein).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D116921

Files:
  clang-tools-extra/clangd/refactor/tweaks/ExpandAutoType.cpp
  clang-tools-extra/clangd/unittests/tweaks/ExpandAutoTypeTests.cpp


Index: clang-tools-extra/clangd/unittests/tweaks/ExpandAutoTypeTests.cpp
===
--- clang-tools-extra/clangd/unittests/tweaks/ExpandAutoTypeTests.cpp
+++ clang-tools-extra/clangd/unittests/tweaks/ExpandAutoTypeTests.cpp
@@ -71,7 +71,8 @@
   apply("void ns::Func() { au^to x = new ns::Class::Nested{}; }"),
   "void ns::Func() { ns::Class::Nested * x = new ns::Class::Nested{}; }");
 
-  EXPECT_UNAVAILABLE("dec^ltype(au^to) x = 10;");
+  EXPECT_EQ(apply("dec^ltype(auto) x = 10;"), "int x = 10;");
+  EXPECT_EQ(apply("decltype(au^to) x = 10;"), "int x = 10;");
   // expanding types in structured bindings is syntactically invalid.
   EXPECT_UNAVAILABLE("const ^auto &[x,y] = (int[]){1,2};");
 
Index: clang-tools-extra/clangd/refactor/tweaks/ExpandAutoType.cpp
===
--- clang-tools-extra/clangd/refactor/tweaks/ExpandAutoType.cpp
+++ clang-tools-extra/clangd/refactor/tweaks/ExpandAutoType.cpp
@@ -96,9 +96,7 @@
   if (auto *Node = Inputs.ASTSelection.commonAncestor()) {
 if (auto *TypeNode = Node->ASTNode.get()) {
   if (const AutoTypeLoc Result = TypeNode->getAs()) {
-// Code in apply() does handle 'decltype(auto)' yet.
-if (!Result.getTypePtr()->isDecltypeAuto() &&
-!isStructuredBindingType(Node) &&
+if (!isStructuredBindingType(Node) &&
 !isDeducedAsLambda(Node, Result.getBeginLoc()) &&
 !isTemplateParam(Node))
   CachedLocation = Result;


Index: clang-tools-extra/clangd/unittests/tweaks/ExpandAutoTypeTests.cpp
===
--- clang-tools-extra/clangd/unittests/tweaks/ExpandAutoTypeTests.cpp
+++ clang-tools-extra/clangd/unittests/tweaks/ExpandAutoTypeTests.cpp
@@ -71,7 +71,8 @@
   apply("void ns::Func() { au^to x = new ns::Class::Nested{}; }"),
   "void ns::Func() { ns::Class::Nested * x = new ns::Class::Nested{}; }");
 
-  EXPECT_UNAVAILABLE("dec^ltype(au^to) x = 10;");
+  EXPECT_EQ(apply("dec^ltype(auto) x = 10;"), "int x = 10;");
+  EXPECT_EQ(apply("decltype(au^to) x = 10;"), "int x = 10;");
   // expanding types in structured bindings is syntactically invalid.
   EXPECT_UNAVAILABLE("const ^auto &[x,y] = (int[]){1,2};");
 
Index: clang-tools-extra/clangd/refactor/tweaks/ExpandAutoType.cpp
===
--- clang-tools-extra/clangd/refactor/tweaks/ExpandAutoType.cpp
+++ clang-tools-extra/clangd/refactor/tweaks/ExpandAutoType.cpp
@@ -96,9 +96,7 @@
   if (auto *Node = Inputs.ASTSelection.commonAncestor()) {
 if (auto *TypeNode = Node->ASTNode.get()) {
   if (const AutoTypeLoc Result = TypeNode->getAs()) {
-// Code in apply() does handle 'decltype(auto)' yet.
-if (!Result.getTypePtr()->isDecltypeAuto() &&
-!isStructuredBindingType(Node) &&
+if (!isStructuredBindingType(Node) &&
 !isDeducedAsLambda(Node, Result.getBeginLoc()) &&
 !isTemplateParam(Node))
   CachedLocation = Result;
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D116595: [clang][sema] Add missing diagnostic parameter

2022-01-10 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman added inline comments.



Comment at: clang/test/Modules/cxx20-export-import.cpp:1-2
+
+// RUN: %clang_cc1 -std=c++20 -fmodules -fmodules-cache-path=%t 
-fimplicit-module-maps -I%S/Inputs -stdlib=libc++ -verify %s
+export import dummy; // expected-error {{export declaration can only be used 
within a module interface unit after the module declaration}}

Also, does this test require `-fmodules-cache-path=%t` or 
`-fimplicit-module-maps`?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D116595

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


[clang] f282b68 - set __NO_MATH_ERRNO__ if -fno-math-errno

2022-01-10 Thread Aaron Ballman via cfe-commits

Author: Alex Xu (Hello71)
Date: 2022-01-10T08:45:46-05:00
New Revision: f282b6809105075b65974989459ee420ecd406e9

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

LOG: set __NO_MATH_ERRNO__ if -fno-math-errno

This causes modern glibc to unset math_errhandling MATH_ERRNO. gcc 12
also sets some other macros, but most of them are associated with
flags ignored by clang, so without library examples, it is difficult to
determine whether they should be set. I think setting this one macro is
OK for now.

Added: 


Modified: 
clang/lib/Frontend/InitPreprocessor.cpp
clang/test/Preprocessor/init-aarch64.c
clang/test/Preprocessor/init.c
clang/test/Preprocessor/predefined-macros.c

Removed: 




diff  --git a/clang/lib/Frontend/InitPreprocessor.cpp 
b/clang/lib/Frontend/InitPreprocessor.cpp
index 629f991106616..ec40170b0a788 100644
--- a/clang/lib/Frontend/InitPreprocessor.cpp
+++ b/clang/lib/Frontend/InitPreprocessor.cpp
@@ -1039,6 +1039,9 @@ static void InitializePredefinedMacros(const TargetInfo 
,
 
   Builder.defineMacro("__USER_LABEL_PREFIX__", TI.getUserLabelPrefix());
 
+  if (!LangOpts.MathErrno)
+Builder.defineMacro("__NO_MATH_ERRNO__");
+
   if (LangOpts.FastMath || LangOpts.FiniteMathOnly)
 Builder.defineMacro("__FINITE_MATH_ONLY__", "1");
   else

diff  --git a/clang/test/Preprocessor/init-aarch64.c 
b/clang/test/Preprocessor/init-aarch64.c
index 3b6f4ddaabde8..8787d24f01cee 100644
--- a/clang/test/Preprocessor/init-aarch64.c
+++ b/clang/test/Preprocessor/init-aarch64.c
@@ -192,6 +192,7 @@
 // AARCH64-NEXT: #define __LONG_MAX__ 9223372036854775807L
 // AARCH64-NEXT: #define __LP64__ 1
 // AARCH64-NEXT: #define __NO_INLINE__ 1
+// AARCH64-NEXT: #define __NO_MATH_ERRNO__ 1
 // AARCH64-NEXT: #define __OBJC_BOOL_IS_BOOL 0
 // AARCH64-NEXT: #define __OPENCL_MEMORY_SCOPE_ALL_SVM_DEVICES 3
 // AARCH64-NEXT: #define __OPENCL_MEMORY_SCOPE_DEVICE 2

diff  --git a/clang/test/Preprocessor/init.c b/clang/test/Preprocessor/init.c
index 7d838413b8513..45d494112a4f5 100644
--- a/clang/test/Preprocessor/init.c
+++ b/clang/test/Preprocessor/init.c
@@ -1691,6 +1691,7 @@
 // WEBASSEMBLY64-NEXT:#define __LONG_MAX__ 9223372036854775807L
 // WEBASSEMBLY64-NEXT:#define __LP64__ 1
 // WEBASSEMBLY-NEXT:#define __NO_INLINE__ 1
+// WEBASSEMBLY-NEXT:#define __NO_MATH_ERRNO__ 1
 // WEBASSEMBLY-NEXT:#define __OBJC_BOOL_IS_BOOL 0
 // WEBASSEMBLY-NEXT:#define __OPENCL_MEMORY_SCOPE_ALL_SVM_DEVICES 3
 // WEBASSEMBLY-NEXT:#define __OPENCL_MEMORY_SCOPE_DEVICE 2

diff  --git a/clang/test/Preprocessor/predefined-macros.c 
b/clang/test/Preprocessor/predefined-macros.c
index 2304eb82b50df..0b67cbe233ca2 100644
--- a/clang/test/Preprocessor/predefined-macros.c
+++ b/clang/test/Preprocessor/predefined-macros.c
@@ -60,6 +60,15 @@
 // RUN:   | FileCheck -match-full-lines %s --check-prefix=CHECK-FAST-MATH
 // CHECK-FAST-MATH: #define __FAST_MATH__ 1
 // CHECK-FAST-MATH: #define __FINITE_MATH_ONLY__ 1
+// CHECK-FAST-MATH: #define __NO_MATH_ERRNO__ 1
+//
+// RUN: %clang_cc1 %s -E -dM -fmath-errno -o - \
+// RUN:   | FileCheck -match-full-lines %s --check-prefix=CHECK-MATH-ERRNO
+// CHECK-MATH-ERRNO-NOT: __NO_MATH_ERRNO__
+//
+// RUN: %clang %s -E -dM -fno-math-errno -o - \
+// RUN:   | FileCheck -match-full-lines %s --check-prefix=CHECK-NO-MATH-ERRNO
+// CHECK-NO-MATH-ERRNO: #define __NO_MATH_ERRNO__ 1
 //
 // RUN: %clang_cc1 %s -E -dM -ffinite-math-only -o - \
 // RUN:   | FileCheck -match-full-lines %s 
--check-prefix=CHECK-FINITE-MATH-ONLY



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


[PATCH] D116412: [Clang][Sema] Fix attribute mismatch warning for ObjC class properties

2022-01-10 Thread Egor Zhdan via Phabricator via cfe-commits
egorzhdan updated this revision to Diff 398601.
egorzhdan added a comment.

Diagnose mismatches between class property of a class and a class property of 
its superclass.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D116412

Files:
  clang/include/clang/AST/DeclObjC.h
  clang/lib/AST/DeclObjC.cpp
  clang/lib/Sema/SemaObjCProperty.cpp
  clang/test/SemaObjC/class-property-inheritance.m

Index: clang/test/SemaObjC/class-property-inheritance.m
===
--- /dev/null
+++ clang/test/SemaObjC/class-property-inheritance.m
@@ -0,0 +1,39 @@
+// RUN: %clang_cc1 -fsyntax-only -verify %s
+
+@class MyObject;
+
+
+@interface TopClassWithClassProperty0
+@property(nullable, readonly, strong, class) MyObject *foo;
+@end
+
+@interface SubClassWithClassProperty0 : TopClassWithClassProperty0
+@property(nonnull, readonly, copy, class) MyObject *foo; // expected-warning {{'copy' attribute on property 'foo' does not match the property inherited from 'TopClassWithClassProperty0'}}
+@end
+
+
+
+@interface TopClassWithInstanceProperty1
+@property(nullable, readonly, strong) MyObject *foo;
+@end
+
+@interface ClassWithClassProperty1 : TopClassWithInstanceProperty1
+@property(nonnull, readonly, copy, class) MyObject *foo; // no-warning
+@end
+
+@interface SubClassWithInstanceProperty1 : ClassWithClassProperty1
+@property(nullable, readonly, copy) MyObject *foo; // expected-warning {{'copy' attribute on property 'foo' does not match the property inherited from 'TopClassWithInstanceProperty1'}}
+@end
+
+
+@interface TopClassWithClassProperty2
+@property(nullable, readonly, strong, class) MyObject *foo;
+@end
+
+@interface ClassWithInstanceProperty2 : TopClassWithClassProperty2
+@property(nonnull, readonly, copy) MyObject *foo; // no-warning
+@end
+
+@interface SubClassWithClassProperty2 : ClassWithInstanceProperty2
+@property(nonnull, readonly, copy, class) MyObject *foo; // expected-warning {{'copy' attribute on property 'foo' does not match the property inherited from 'TopClassWithClassProperty2'}}
+@end
Index: clang/lib/Sema/SemaObjCProperty.cpp
===
--- clang/lib/Sema/SemaObjCProperty.cpp
+++ clang/lib/Sema/SemaObjCProperty.cpp
@@ -112,8 +112,8 @@
 return;
 
   // Look for a property with the same name.
-  if (ObjCPropertyDecl *ProtoProp =
-  Proto->lookup(Prop->getDeclName()).find_first()) {
+  if (ObjCPropertyDecl *ProtoProp = Proto->getProperty(
+  Prop->getIdentifier(), Prop->isInstanceProperty())) {
 S.DiagnosePropertyMismatch(Prop, ProtoProp, Proto->getIdentifier(), true);
 return;
   }
@@ -231,8 +231,8 @@
 bool FoundInSuper = false;
 ObjCInterfaceDecl *CurrentInterfaceDecl = IFace;
 while (ObjCInterfaceDecl *Super = CurrentInterfaceDecl->getSuperClass()) {
-  if (ObjCPropertyDecl *SuperProp =
-  Super->lookup(Res->getDeclName()).find_first()) {
+  if (ObjCPropertyDecl *SuperProp = Super->getProperty(
+  Res->getIdentifier(), Res->isInstanceProperty())) {
 DiagnosePropertyMismatch(Res, SuperProp, Super->getIdentifier(), false);
 FoundInSuper = true;
 break;
Index: clang/lib/AST/DeclObjC.cpp
===
--- clang/lib/AST/DeclObjC.cpp
+++ clang/lib/AST/DeclObjC.cpp
@@ -232,6 +232,19 @@
   return (ivarName.str());
 }
 
+ObjCPropertyDecl *
+ObjCContainerDecl::getProperty(const IdentifierInfo *Id,
+   bool IsInstance) const {
+  for (auto *LookupResult : lookup(Id)) {
+if (auto *Prop = dyn_cast(LookupResult)) {
+  if (Prop->isInstanceProperty() == IsInstance) {
+return Prop;
+  }
+}
+  }
+  return nullptr;
+}
+
 /// FindPropertyDeclaration - Finds declaration of the property given its name
 /// in 'PropertyId' and returns it. It returns 0, if not found.
 ObjCPropertyDecl *ObjCContainerDecl::FindPropertyDeclaration(
Index: clang/include/clang/AST/DeclObjC.h
===
--- clang/include/clang/AST/DeclObjC.h
+++ clang/include/clang/AST/DeclObjC.h
@@ -1071,6 +1071,9 @@
   bool HasUserDeclaredSetterMethod(const ObjCPropertyDecl *P) const;
   ObjCIvarDecl *getIvarDecl(IdentifierInfo *Id) const;
 
+  ObjCPropertyDecl *getProperty(const IdentifierInfo *Id,
+bool IsInstance) const;
+
   ObjCPropertyDecl *
   FindPropertyDeclaration(const IdentifierInfo *PropertyId,
   ObjCPropertyQueryKind QueryKind) const;
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D111566: [SYCL] Fix function pointer address space

2022-01-10 Thread Elizabeth Andrews via Phabricator via cfe-commits
eandrews added a comment.

In D111566#3228949 , @rjmccall wrote:

> Block pointers are actually data pointers and should stay in the generic 
> address space if they don't have an address space qualifier.  That might 
> require new logic.

Thanks! I kept the existing behavior for block pointers by passing qualifiers 
to `getTargetAddressSpace`.


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

https://reviews.llvm.org/D111566

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


[libunwind] 914fffc - [libunwind][cmake] Create `LIBUNWIND_INSTALL_INCLUDE_DIR` CACHE PATH

2022-01-10 Thread John Ericson via cfe-commits

Author: John Ericson
Date: 2022-01-10T21:31:52Z
New Revision: 914fffc7f2492a1e4bc419a80c30fdb3f9440698

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

LOG: [libunwind][cmake] Create `LIBUNWIND_INSTALL_INCLUDE_DIR` CACHE PATH

This is created on analogy with the other CACHE PATHs in this package,
and other `*_INSTALL_INCLUDE_DIR` in other packages.

The branching is adjusted to deduplicate some existing code, and
likewise avoid having to define this new variable more than once.

This will be used for D99484.

Reviewed By: #libunwind, compnerd

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

Added: 


Modified: 
libunwind/CMakeLists.txt
libunwind/include/CMakeLists.txt

Removed: 




diff  --git a/libunwind/CMakeLists.txt b/libunwind/CMakeLists.txt
index e3cc66dd22267..efbd88a27f05a 100644
--- a/libunwind/CMakeLists.txt
+++ b/libunwind/CMakeLists.txt
@@ -141,26 +141,25 @@ if(LLVM_ENABLE_PER_TARGET_RUNTIME_DIR AND NOT APPLE)
   set(LIBUNWIND_LIBRARY_DIR 
${LLVM_LIBRARY_OUTPUT_INTDIR}/${LLVM_DEFAULT_TARGET_TRIPLE})
   set(LIBUNWIND_INSTALL_LIBRARY_DIR 
lib${LLVM_LIBDIR_SUFFIX}/${LLVM_DEFAULT_TARGET_TRIPLE} CACHE PATH
   "Path where built libunwind libraries should be installed.")
-  set(LIBUNWIND_INSTALL_RUNTIME_DIR bin CACHE PATH
-  "Path where built libunwind runtime libraries should be installed.")
   if(LIBCXX_LIBDIR_SUBDIR)
 string(APPEND LIBUNWIND_LIBRARY_DIR /${LIBUNWIND_LIBDIR_SUBDIR})
 string(APPEND LIBUNWIND_INSTALL_LIBRARY_DIR /${LIBUNWIND_LIBDIR_SUBDIR})
   endif()
-elseif(LLVM_LIBRARY_OUTPUT_INTDIR)
-  set(LIBUNWIND_LIBRARY_DIR ${LLVM_LIBRARY_OUTPUT_INTDIR})
-  set(LIBUNWIND_INSTALL_LIBRARY_DIR lib${LIBUNWIND_LIBDIR_SUFFIX} CACHE PATH
-  "Path where built libunwind libraries should be installed.")
-  set(LIBUNWIND_INSTALL_RUNTIME_DIR bin CACHE PATH
-  "Path where built libunwind runtime libraries should be installed.")
 else()
-  set(LIBUNWIND_LIBRARY_DIR ${CMAKE_BINARY_DIR}/lib${LIBUNWIND_LIBDIR_SUFFIX})
+  if(LLVM_LIBRARY_OUTPUT_INTDIR)
+set(LIBUNWIND_LIBRARY_DIR ${LLVM_LIBRARY_OUTPUT_INTDIR})
+  else()
+set(LIBUNWIND_LIBRARY_DIR 
${CMAKE_BINARY_DIR}/lib${LIBUNWIND_LIBDIR_SUFFIX})
+  endif()
   set(LIBUNWIND_INSTALL_LIBRARY_DIR lib${LIBUNWIND_LIBDIR_SUFFIX} CACHE PATH
   "Path where built libunwind libraries should be installed.")
-  set(LIBUNWIND_INSTALL_RUNTIME_DIR bin CACHE PATH
-  "Path where built libunwind runtime libraries should be installed.")
 endif()
 
+set(LIBUNWIND_INSTALL_INCLUDE_DIR include CACHE PATH
+"Path where built libunwind headers should be installed.")
+set(LIBUNWIND_INSTALL_RUNTIME_DIR bin CACHE PATH
+"Path where built libunwind runtime libraries should be installed.")
+
 set(CMAKE_ARCHIVE_OUTPUT_DIRECTORY ${LIBUNWIND_LIBRARY_DIR})
 set(CMAKE_LIBRARY_OUTPUT_DIRECTORY ${LIBUNWIND_LIBRARY_DIR})
 set(CMAKE_RUNTIME_OUTPUT_DIRECTORY ${LIBUNWIND_LIBRARY_DIR})

diff  --git a/libunwind/include/CMakeLists.txt 
b/libunwind/include/CMakeLists.txt
index c3bb1dd0f69fa..adf1766c44cbc 100644
--- a/libunwind/include/CMakeLists.txt
+++ b/libunwind/include/CMakeLists.txt
@@ -14,7 +14,7 @@ if(LIBUNWIND_INSTALL_HEADERS)
   foreach(file ${files})
 get_filename_component(dir ${file} DIRECTORY)
 install(FILES ${file}
-  DESTINATION "include/${dir}"
+  DESTINATION "${LIBUNWIND_INSTALL_INCLUDE_DIR}/${dir}"
   COMPONENT unwind-headers
   PERMISSIONS OWNER_READ OWNER_WRITE GROUP_READ WORLD_READ
 )



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


[PATCH] D116518: [ast-matchers] Add hasSubstatementSequence matcher

2022-01-10 Thread Richard via Phabricator via cfe-commits
LegalizeAdulthood updated this revision to Diff 398754.
LegalizeAdulthood added a comment.

clang-format


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

https://reviews.llvm.org/D116518

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

Index: clang/unittests/ASTMatchers/ASTMatchersNarrowingTest.cpp
===
--- clang/unittests/ASTMatchers/ASTMatchersNarrowingTest.cpp
+++ clang/unittests/ASTMatchers/ASTMatchersNarrowingTest.cpp
@@ -2604,6 +2604,73 @@
   EXPECT_TRUE(matchesObjC("void f() { ^{}(); }", blockExpr()));
 }
 
+TEST_P(ASTMatchersTest, HasSubstatementSequenceSimple) {
+  const char *Text = "int f() { int x = 5; if (x < 0) return 1; return 0; }";
+  EXPECT_TRUE(matches(
+  Text, compoundStmt(hasSubstatementSequence(ifStmt(), returnStmt();
+  EXPECT_FALSE(matches(
+  Text, compoundStmt(hasSubstatementSequence(ifStmt(), labelStmt();
+  EXPECT_FALSE(matches(
+  Text, compoundStmt(hasSubstatementSequence(returnStmt(), ifStmt();
+  EXPECT_FALSE(matches(
+  Text, compoundStmt(hasSubstatementSequence(switchStmt(), labelStmt();
+}
+
+TEST_P(ASTMatchersTest, HasSubstatementSequenceAlmost) {
+  const char *Text = R"code(
+int f() {
+  int x = 5;
+  if (x < 10)
+;
+  if (x < 0)
+return 1;
+  return 0;
+}
+)code";
+  EXPECT_TRUE(matches(
+  Text, compoundStmt(hasSubstatementSequence(ifStmt(), returnStmt();
+  EXPECT_TRUE(
+  matches(Text, compoundStmt(hasSubstatementSequence(ifStmt(), ifStmt();
+}
+
+TEST_P(ASTMatchersTest, HasSubstatementSequenceComplex) {
+  const char *Text = R"code(
+int f() {
+  int x = 5;
+  if (x < 10)
+x -= 10;
+  if (x < 0)
+return 1;
+  return 0;
+}
+)code";
+  EXPECT_TRUE(matches(
+  Text, compoundStmt(hasSubstatementSequence(ifStmt(), returnStmt();
+  EXPECT_FALSE(
+  matches(Text, compoundStmt(hasSubstatementSequence(ifStmt(), expr();
+}
+
+TEST_P(ASTMatchersTest, HasSubstatementSequenceExpression) {
+  const char *Text = R"code(
+int f() {
+  return ({ int x = 5;
+  int result;
+  if (x < 10)
+x -= 10;
+  if (x < 0)
+result = 1;
+  else
+result = 0;
+  result;
+});
+  }
+)code";
+  EXPECT_TRUE(
+  matches(Text, stmtExpr(hasSubstatementSequence(ifStmt(), expr();
+  EXPECT_FALSE(
+  matches(Text, stmtExpr(hasSubstatementSequence(ifStmt(), returnStmt();
+}
+
 TEST_P(ASTMatchersTest,
StatementCountIs_FindsNoStatementsInAnEmptyCompoundStatement) {
   EXPECT_TRUE(matches("void f() { }", compoundStmt(statementCountIs(0;
Index: clang/lib/ASTMatchers/Dynamic/Registry.cpp
===
--- clang/lib/ASTMatchers/Dynamic/Registry.cpp
+++ clang/lib/ASTMatchers/Dynamic/Registry.cpp
@@ -355,6 +355,7 @@
   REGISTER_MATCHER(hasSpecializedTemplate);
   REGISTER_MATCHER(hasStaticStorageDuration);
   REGISTER_MATCHER(hasStructuredBlock);
+  REGISTER_MATCHER(hasSubstatementSequence);
   REGISTER_MATCHER(hasSyntacticForm);
   REGISTER_MATCHER(hasTargetDecl);
   REGISTER_MATCHER(hasTemplateArgument);
Index: clang/include/clang/ASTMatchers/ASTMatchers.h
===
--- clang/include/clang/ASTMatchers/ASTMatchers.h
+++ clang/include/clang/ASTMatchers/ASTMatchers.h
@@ -5431,6 +5431,35 @@
   Builder) != CS->body_end();
 }
 
+/// Matches two consecutive statements within a compound statement.
+///
+/// Given
+/// \code
+///   { if (x > 0) return true; return false; }
+/// \endcode
+/// compoundStmt(hasSubstatementSequence(ifStmt(), returnStmt()))
+///   matches '{ if (x > 0) return true; return false; }'
+AST_POLYMORPHIC_MATCHER_P2(hasSubstatementSequence,
+   AST_POLYMORPHIC_SUPPORTED_TYPES(CompoundStmt,
+   StmtExpr),
+   internal::Matcher, InnerMatcher1,
+   internal::Matcher, InnerMatcher2) {
+  if (const CompoundStmt *CS = CompoundStmtMatcher::get(Node)) {
+auto It = matchesFirstInPointerRange(InnerMatcher1, CS->body_begin(),
+ CS->body_end(), Finder, Builder);
+while (It != CS->body_end()) {
+  ++It;
+  if (It == CS->body_end())
+return false;
+  if (InnerMatcher2.matches(**It, Finder, Builder))
+return true;
+  It = matchesFirstInPointerRange(InnerMatcher1, It, CS->body_end(), Finder,
+  Builder);
+}
+  }
+  return false;
+}
+
 /// Checks that a compound statement contains a specific number of
 /// child statements.
 ///
Index: clang/docs/ReleaseNotes.rst

[PATCH] D7982: [clang-tidy] Add readability-duplicate-include check

2022-01-10 Thread Richard via Phabricator via cfe-commits
LegalizeAdulthood updated this revision to Diff 398756.
LegalizeAdulthood added a comment.

clang-format


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

https://reviews.llvm.org/D7982

Files:
  clang-tools-extra/clang-tidy/readability/CMakeLists.txt
  clang-tools-extra/clang-tidy/readability/DuplicateIncludeCheck.cpp
  clang-tools-extra/clang-tidy/readability/DuplicateIncludeCheck.h
  clang-tools-extra/clang-tidy/readability/ReadabilityTidyModule.cpp
  clang-tools-extra/docs/ReleaseNotes.rst
  clang-tools-extra/docs/clang-tidy/checks/list.rst
  clang-tools-extra/docs/clang-tidy/checks/readability-duplicate-include.rst
  
clang-tools-extra/test/clang-tidy/checkers/Inputs/readability-duplicate-include/iostream
  
clang-tools-extra/test/clang-tidy/checkers/Inputs/readability-duplicate-include/readability-duplicate-include.h
  
clang-tools-extra/test/clang-tidy/checkers/Inputs/readability-duplicate-include/string.h
  
clang-tools-extra/test/clang-tidy/checkers/Inputs/readability-duplicate-include/sys/types.h
  
clang-tools-extra/test/clang-tidy/checkers/Inputs/readability-duplicate-include/types.h
  clang-tools-extra/test/clang-tidy/checkers/readability-duplicate-include.cpp

Index: clang-tools-extra/test/clang-tidy/checkers/readability-duplicate-include.cpp
===
--- /dev/null
+++ clang-tools-extra/test/clang-tidy/checkers/readability-duplicate-include.cpp
@@ -0,0 +1,72 @@
+// RUN: %check_clang_tidy -std=c++98-or-later %s readability-duplicate-include %t -- -- -I%S/Inputs/readability-duplicate-include
+
+int a;
+#include 
+int b;
+#include 
+int c;
+// CHECK-MESSAGES: :[[@LINE-2]]:1: warning: duplicate include [readability-duplicate-include]
+// CHECK-FIXES:  {{^int a;$}}
+// CHECK-FIXES-NEXT: {{^#include $}}
+// CHECK-FIXES-NEXT: {{^int b;$}}
+// CHECK-FIXES-NEXT: {{^int c;$}}
+
+int d;
+#include 
+int e;
+#include  // extra stuff that will also be removed
+int f;
+// CHECK-MESSAGES: :[[@LINE-2]]:1: warning: {{.*}}
+// CHECK-FIXES:  {{^int d;$}}
+// CHECK-FIXES-NEXT: {{^#include $}}
+// CHECK-FIXES-NEXT: {{^int e;$}}
+// CHECK-FIXES-NEXT: {{^int f;$}}
+
+int g;
+#include "readability-duplicate-include.h"
+int h;
+#include "readability-duplicate-include.h"
+int i;
+// CHECK-MESSAGES: :[[@LINE-2]]:1: warning: {{.*}}
+// CHECK-FIXES:  {{^int g;$}}
+// CHECK-FIXES-NEXT: {{^#include "readability-duplicate-include.h"$}}
+// CHECK-FIXES-NEXT: {{^int h;$}}
+// CHECK-FIXES-NEXT: {{^int i;$}}
+
+#include "types.h"
+
+int j;
+#include 
+int k;
+#include 
+int l;
+// CHECK-MESSAGES: :[[@LINE-2]]:1: warning: {{.*}}
+// CHECK-FIXES:  {{^int j;$}}
+// CHECK-FIXES-NEXT: {{^#include $}}
+// CHECK-FIXES-NEXT: {{^int k;$}}
+// CHECK-FIXES-NEXT: {{^int l;$}}
+
+int m;
+#  include   // lots of space
+int n;
+// CHECK-MESSAGES: :[[@LINE-2]]:9: warning: {{.*}}
+// CHECK-FIXES:  {{^int m;$}}
+// CHECK-FIXES-NEXT: {{^int n;$}}
+
+// defining a macro in the main file resets the included file cache
+#define ARBITRARY_MACRO
+int o;
+#include 
+int p;
+// CHECK-FIXES:  {{^int o;$}}
+// CHECK-FIXES-NEXT: {{^#include $}}
+// CHECK-FIXES-NEXT: {{^int p;$}}
+
+// undefining a macro resets the cache
+#undef ARBITRARY_MACRO
+int q;
+#include 
+int r;
+// CHECK-FIXES:  {{^int q;$}}
+// CHECK-FIXES-NEXT: {{^#include $}}
+// CHECK-FIXES-NEXT: {{^int r;$}}
Index: clang-tools-extra/test/clang-tidy/checkers/Inputs/readability-duplicate-include/types.h
===
--- /dev/null
+++ clang-tools-extra/test/clang-tidy/checkers/Inputs/readability-duplicate-include/types.h
@@ -0,0 +1 @@
+// empty file used by readability-duplicate-include.cpp
Index: clang-tools-extra/test/clang-tidy/checkers/Inputs/readability-duplicate-include/sys/types.h
===
--- /dev/null
+++ clang-tools-extra/test/clang-tidy/checkers/Inputs/readability-duplicate-include/sys/types.h
@@ -0,0 +1 @@
+// empty file used by readability-duplicate-include.cpp
Index: clang-tools-extra/test/clang-tidy/checkers/Inputs/readability-duplicate-include/string.h
===
--- /dev/null
+++ clang-tools-extra/test/clang-tidy/checkers/Inputs/readability-duplicate-include/string.h
@@ -0,0 +1 @@
+// empty file used by readability-duplicate-include.cpp
Index: clang-tools-extra/test/clang-tidy/checkers/Inputs/readability-duplicate-include/readability-duplicate-include.h
===
--- /dev/null
+++ clang-tools-extra/test/clang-tidy/checkers/Inputs/readability-duplicate-include/readability-duplicate-include.h
@@ -0,0 +1 @@
+// empty file used by readability-duplicate-include.cpp
Index: clang-tools-extra/test/clang-tidy/checkers/Inputs/readability-duplicate-include/iostream
===
--- 

[PATCH] D116967: [HIP] Fix device malloc/free

2022-01-10 Thread Artem Belevich via Phabricator via cfe-commits
tra accepted this revision.
tra added inline comments.
This revision is now accepted and ready to land.



Comment at: clang/lib/Headers/__clang_hip_runtime_wrapper.h:80
 
+#if HIP_VERSION_MAJOR > 4 || (HIP_VERSION_MAJOR == 4 && HIP_VERSION_MINOR >= 5)
+extern "C" __device__ unsigned long long __ockl_dm_alloc(unsigned long long 
__size);

Nit: perhaps something like this would express the intent a bit more directly:

```
# if HIP_VERSION_MAJOR*100+HIP_VERSION_MINOR*10 > 450
```




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

https://reviews.llvm.org/D116967

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


[PATCH] D105340: [analyzer] Produce SymbolCast symbols for integral types in SValBuilder::evalCast

2022-01-10 Thread Artem Dergachev via Phabricator via cfe-commits
NoQ accepted this revision.
NoQ added a comment.
This revision is now accepted and ready to land.

This looks great with the option flag. Landing this patch will enable more 
people to test the new mode and produce feedback on whether the constraint 
solver keeps working well enough in presence of the new symbols.




Comment at: clang/lib/StaticAnalyzer/Core/SValBuilder.cpp:1004
+  QualType CastTy) {
+  // We use seven conditions to recognize a simplification case.
+  // For the clarity let `CastTy` be `C`, SE->getType() - `T`, root type - `R`,

I really hope these are correct with respect to sign extension 爛



Comment at: clang/test/Analysis/produce-symbolcast_x64.cpp:15
+void test_schar(schar x) {
+  clang_analyzer_dump(x); // expected-warning{{reg_$0}}
+

There's `clang_analyzer_denote()`/`clang_analyzer_express()` which is slightly 
better because it avoids testing the specific dump format (so we could change 
it more easily if we want). No pressure though, if it's too much work to re-do 
then let's keep them as is.


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

https://reviews.llvm.org/D105340

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


[PATCH] D116549: [OpenMP][Clang] Allow passing target features in ISA trait for metadirective clause

2022-01-10 Thread Johannes Doerfert via Phabricator via cfe-commits
jdoerfert added inline comments.



Comment at: clang/lib/Parse/ParseOpenMP.cpp:2533
+std::function DiagUnknownTrait = [this, Loc](
+StringRef ISATrait) {};
+TargetOMPContext OMPCtx(ASTContext, std::move(DiagUnknownTrait),

saiislam wrote:
> jdoerfert wrote:
> > jdoerfert wrote:
> > > saiislam wrote:
> > > > jdoerfert wrote:
> > > > > Why doesn't this diagnose nothing?
> > > > Because an isa-feature will fail at least once, for either host 
> > > > compilation or device compilation. So, no point in always giving a 
> > > > warning.
> > > That is debatable. 
> > > 
> > > First, if I compile for a single architecture there is no device 
> > > compilation and it should warn.
> > > Second, if I place the metadirective into a declare variant function or 
> > > add a `kind(...)` selector to it it will also not warn even if you have 
> > > multiple architectures.
> > > 
> > > 
> > ```
> > ASTContext  = getASTContext();
> > std::function DiagUnknownTrait = [this,
> > ┊ ┊ ┊ ┊ ┊ ┊ ┊ ┊ ┊ ┊CE](StringRef 
> > ISATrait) {
> > ┊ // TODO Track the selector locations in a way that is accessible here 
> > to
> > ┊ // improve the diagnostic location.
> > ┊ Diag(CE->getBeginLoc(), diag::warn_unknown_declare_variant_isa_trait)
> > ┊ ┊ ┊ << ISATrait;   
> > };
> > TargetOMPContext OMPCtx(Context, std::move(DiagUnknownTrait),   
> > 
> > 
> >
> > ┊ ┊ ┊ ┊ ┊ ┊ ┊ ┊ ┊ ┊ getCurFunctionDecl(), 
> > DSAStack->getConstructTraits());
> > ```
> > Already exists (SemaOpenMP). Why do we need a second, different diagnostic?
> Isn't giving a remark better than a warning, when we know in many cases this 
> will be hit during a normal (expected) compilation for target offload?
> Remark diagnostic will give ample handle for understanding the flow without 
> the need to explicitly deal with this warning during compilation of user 
> programs.
> 
> I am fine changing it to a warning if you feel strongly about this.
1) Having two diagnostics for the same thing is generally bad and there doesn't 
seem to be a reason why we would need/want to treat metadirective and declare 
variant differently.
 Thus, if we want to move to remarks we should move the second diagnostic as 
well. Cleaning up existing code is more important than adding new code.
2) I still don't see why this is "normal" or "expected" at all. The warning 
reads:
`isa trait 'foo' is not known to the current target; verify the spelling or 
consider restricting the context selector with the 'arch' selector further`.
Hence, `device={isa("flat..."), arch(amdgcn)}` should not cause a warning even 
if you compile it for the host, an nvidia gpu, or anything other than AMDGCN.
FWIW, this is [supposed to be] ensured by the positioning of the isa trait 
selector in OMPKinds.def:
```
  // Note that we put isa last so that the other conditions are checked first.
  // This allows us to issue warnings wrt. isa only if we match otherwise.
  __OMP_TRAIT_SELECTOR(device, isa, true)
```


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D116549

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


[PATCH] D116975: [OpenMP] Initial Implementation of LTO and bitcode linking in linker wrapper

2022-01-10 Thread Joseph Huber via Phabricator via cfe-commits
jhuber6 updated this revision to Diff 398748.
jhuber6 added a comment.

Undoing accidental clang format.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D116975

Files:
  clang/lib/Driver/Driver.cpp
  clang/lib/Driver/ToolChains/Clang.cpp
  clang/tools/clang-linker-wrapper/CMakeLists.txt
  clang/tools/clang-linker-wrapper/ClangLinkerWrapper.cpp
  llvm/lib/Passes/PassBuilderPipelines.cpp

Index: llvm/lib/Passes/PassBuilderPipelines.cpp
===
--- llvm/lib/Passes/PassBuilderPipelines.cpp
+++ llvm/lib/Passes/PassBuilderPipelines.cpp
@@ -1464,6 +1464,9 @@
   // libraries and other oracles.
   MPM.addPass(InferFunctionAttrsPass());
 
+  if (Level.getSpeedupLevel() > 1)
+MPM.addPass(OpenMPOptPass());
+
   if (Level.getSpeedupLevel() > 1) {
 FunctionPassManager EarlyFPM;
 EarlyFPM.addPass(CallSiteSplittingPass());
@@ -1773,6 +1776,7 @@
   MPM.addPass(createModuleToFunctionPassAdaptor(CoroEarlyPass()));
   CGSCCPassManager CGPM;
   CGPM.addPass(CoroSplitPass());
+  CGPM.addPass(OpenMPOptCGSCCPass());
   MPM.addPass(createModuleToPostOrderCGSCCPassAdaptor(std::move(CGPM)));
   MPM.addPass(createModuleToFunctionPassAdaptor(CoroCleanupPass()));
 
Index: clang/tools/clang-linker-wrapper/ClangLinkerWrapper.cpp
===
--- clang/tools/clang-linker-wrapper/ClangLinkerWrapper.cpp
+++ clang/tools/clang-linker-wrapper/ClangLinkerWrapper.cpp
@@ -17,9 +17,12 @@
 #include "clang/Basic/Version.h"
 #include "llvm/BinaryFormat/Magic.h"
 #include "llvm/Bitcode/BitcodeWriter.h"
+#include "llvm/CodeGen/CommandFlags.h"
 #include "llvm/IR/Constants.h"
+#include "llvm/IR/DiagnosticPrinter.h"
 #include "llvm/IR/Module.h"
 #include "llvm/IRReader/IRReader.h"
+#include "llvm/LTO/LTO.h"
 #include "llvm/Object/Archive.h"
 #include "llvm/Object/ArchiveWriter.h"
 #include "llvm/Object/Binary.h"
@@ -36,6 +39,7 @@
 #include "llvm/Support/Signals.h"
 #include "llvm/Support/SourceMgr.h"
 #include "llvm/Support/StringSaver.h"
+#include "llvm/Support/TargetSelect.h"
 #include "llvm/Support/WithColor.h"
 #include "llvm/Support/raw_ostream.h"
 
@@ -58,6 +62,15 @@
cl::desc("Path of linker binary"),
cl::cat(ClangLinkerWrapperCategory));
 
+static cl::opt
+TargetFeatures("target-feature", cl::desc("Target features for triple"),
+   cl::cat(ClangLinkerWrapperCategory));
+
+static cl::opt OptLevel("opt-level",
+ cl::desc("Optimization level for LTO"),
+ cl::init("O0"),
+ cl::cat(ClangLinkerWrapperCategory));
+
 // Do not parse linker options.
 static cl::list
 HostLinkerArgs(cl::Sink, cl::desc("..."));
@@ -68,6 +81,9 @@
 /// Temporary files created by the linker wrapper.
 static SmallVector TempFiles;
 
+/// Codegen flags for LTO backend.
+static codegen::RegisterCodeGenFlags CodeGenFlags;
+
 /// Magic section string that marks the existence of offloading data. The
 /// section string will be formatted as `.llvm.offloading..`.
 #define OFFLOAD_SECTION_MAGIC_STR ".llvm.offloading."
@@ -195,6 +211,28 @@
   if (ToBeStripped.empty())
 return None;
 
+  // If the object file to strip doesn't exist we need to write it so we can
+  // pass it to llvm-strip.
+  SmallString<128> StripFile = Obj.getFileName();
+  if (!sys::fs::exists(StripFile)) {
+SmallString<128> TempFile;
+if (std::error_code EC = sys::fs::createTemporaryFile(
+sys::path::stem(StripFile), "o", TempFile))
+  return createFileError(TempFile, EC);
+TempFiles.push_back(static_cast(TempFile));
+
+auto Contents = Obj.getMemoryBufferRef().getBuffer();
+Expected> OutputOrErr =
+FileOutputBuffer::create(TempFile, Contents.size());
+if (!OutputOrErr)
+  return OutputOrErr.takeError();
+std::unique_ptr Output = std::move(*OutputOrErr);
+std::copy(Contents.begin(), Contents.end(), Output->getBufferStart());
+if (Error E = Output->commit())
+  return E;
+StripFile = TempFile;
+  }
+
   // We will use llvm-strip to remove the now unneeded section containing the
   // offloading code.
   ErrorOr StripPath = sys::findProgramByName(
@@ -214,7 +252,7 @@
   SmallVector StripArgs;
   StripArgs.push_back(*StripPath);
   StripArgs.push_back("--no-strip-all");
-  StripArgs.push_back(Obj.getFileName());
+  StripArgs.push_back(StripFile);
   for (auto  : ToBeStripped) {
 StripArgs.push_back("--remove-section");
 StripArgs.push_back(Section);
@@ -419,6 +457,44 @@
 
 // TODO: Move these to a separate file.
 namespace nvptx {
+Expected assemble(StringRef InputFile, Triple TheTriple,
+   StringRef Arch) {
+  // NVPTX uses the nvlink binary to link device object files.
+  ErrorOr 

[PATCH] D56343: [clang-tidy] Refactor: Extract Class CheckRunner on check_clang_tidy.py

2022-01-10 Thread Richard via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rGa2c33b0ec976: [clang-tidy] Refactor: Extract Class 
CheckRunner on check_clang_tidy.py (authored by LegalizeAdulthood).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D56343

Files:
  clang-tools-extra/test/clang-tidy/check_clang_tidy.py

Index: clang-tools-extra/test/clang-tidy/check_clang_tidy.py
===
--- clang-tools-extra/test/clang-tidy/check_clang_tidy.py
+++ clang-tools-extra/test/clang-tidy/check_clang_tidy.py
@@ -39,170 +39,169 @@
 f.truncate()
 
 
-def run_test_once(args, extra_args):
-  resource_dir = args.resource_dir
-  assume_file_name = args.assume_filename
-  input_file_name = args.input_file_name
-  check_name = args.check_name
-  temp_file_name = args.temp_file_name
-  expect_clang_tidy_error = args.expect_clang_tidy_error
-  std = args.std
-
-  file_name_with_extension = assume_file_name or input_file_name
-  _, extension = os.path.splitext(file_name_with_extension)
-  if extension not in ['.c', '.hpp', '.m', '.mm']:
-extension = '.cpp'
-  temp_file_name = temp_file_name + extension
-
-  clang_tidy_extra_args = extra_args
-  clang_extra_args = []
-  if '--' in extra_args:
-i = clang_tidy_extra_args.index('--')
-clang_extra_args = clang_tidy_extra_args[i + 1:]
-clang_tidy_extra_args = clang_tidy_extra_args[:i]
-
-  # If the test does not specify a config style, force an empty one; otherwise
-  # autodetection logic can discover a ".clang-tidy" file that is not related to
-  # the test.
-  if not any(
-  [arg.startswith('-config=') for arg in clang_tidy_extra_args]):
-clang_tidy_extra_args.append('-config={}')
-
-  if extension in ['.m', '.mm']:
-clang_extra_args = ['-fobjc-abi-version=2', '-fobjc-arc', '-fblocks'] + \
-clang_extra_args
-
-  if extension in ['.cpp', '.hpp', '.mm']:
-clang_extra_args.append('-std=' + std)
-
-  # Tests should not rely on STL being available, and instead provide mock
-  # implementations of relevant APIs.
-  clang_extra_args.append('-nostdinc++')
-
-  if resource_dir is not None:
-clang_extra_args.append('-resource-dir=%s' % resource_dir)
-
-  with open(input_file_name, 'r', encoding='utf-8') as input_file:
-input_text = input_file.read()
-
-  check_fixes_prefixes = []
-  check_messages_prefixes = []
-  check_notes_prefixes = []
-
-  has_check_fixes = False
-  has_check_messages = False
-  has_check_notes = False
-
-  for check in args.check_suffix:
-if check and not re.match('^[A-Z0-9\-]+$', check):
-  sys.exit('Only A..Z, 0..9 and "-" are ' +
-'allowed in check suffixes list, but "%s" was given' % (check))
-
-file_check_suffix = ('-' + check) if check else ''
-check_fixes_prefix = 'CHECK-FIXES' + file_check_suffix
-check_messages_prefix = 'CHECK-MESSAGES' + file_check_suffix
-check_notes_prefix = 'CHECK-NOTES' + file_check_suffix
-
-has_check_fix = check_fixes_prefix in input_text
-has_check_message = check_messages_prefix in input_text
-has_check_note = check_notes_prefix in input_text
-
-if has_check_note and has_check_message:
-  sys.exit('Please use either %s or %s but not both' %
-(check_notes_prefix, check_messages_prefix))
-
-if not has_check_fix and not has_check_message and not has_check_note:
-  sys.exit('%s, %s or %s not found in the input' %
-(check_fixes_prefix, check_messages_prefix, check_notes_prefix))
-
-has_check_fixes = has_check_fixes or has_check_fix
-has_check_messages = has_check_messages or has_check_message
-has_check_notes = has_check_notes or has_check_note
-
-if has_check_fix:
-  check_fixes_prefixes.append(check_fixes_prefix)
-if has_check_message:
-  check_messages_prefixes.append(check_messages_prefix)
-if has_check_note:
-  check_notes_prefixes.append(check_notes_prefix)
-
-  assert has_check_fixes or has_check_messages or has_check_notes
-  # Remove the contents of the CHECK lines to avoid CHECKs matching on
-  # themselves.  We need to keep the comments to preserve line numbers while
-  # avoiding empty lines which could potentially trigger formatting-related
-  # checks.
-  cleaned_test = re.sub('// *CHECK-[A-Z0-9\-]*:[^\r\n]*', '//', input_text)
-
-  write_file(temp_file_name, cleaned_test)
-
-  original_file_name = temp_file_name + ".orig"
-  write_file(original_file_name, cleaned_test)
-
-  args = ['clang-tidy', temp_file_name, '-fix', '--checks=-*,' + check_name] + \
-  clang_tidy_extra_args + ['--'] + clang_extra_args
-  if expect_clang_tidy_error:
-args.insert(0, 'not')
-  print('Running ' + repr(args) + '...')
+def try_run(args, raise_error=True):
   try:
-clang_tidy_output = \
-subprocess.check_output(args, stderr=subprocess.STDOUT).decode()
+process_output = \
+  

[clang-tools-extra] a2c33b0 - [clang-tidy] Refactor: Extract Class CheckRunner on check_clang_tidy.py

2022-01-10 Thread via cfe-commits

Author: Richard
Date: 2022-01-10T15:44:12-07:00
New Revision: a2c33b0ec976c894dc45558d0b50c9c2fe87e1da

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

LOG: [clang-tidy] Refactor: Extract Class CheckRunner on check_clang_tidy.py

Break up the huge function by extracting a class, storing intermediate
state as class members and breaking up the big function into a group
of class methods all at the same level of abstraction.

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

Added: 


Modified: 
clang-tools-extra/test/clang-tidy/check_clang_tidy.py

Removed: 




diff  --git a/clang-tools-extra/test/clang-tidy/check_clang_tidy.py 
b/clang-tools-extra/test/clang-tidy/check_clang_tidy.py
index 4edae67f7076..1a234029b60b 100755
--- a/clang-tools-extra/test/clang-tidy/check_clang_tidy.py
+++ b/clang-tools-extra/test/clang-tidy/check_clang_tidy.py
@@ -39,170 +39,169 @@ def write_file(file_name, text):
 f.truncate()
 
 
-def run_test_once(args, extra_args):
-  resource_dir = args.resource_dir
-  assume_file_name = args.assume_filename
-  input_file_name = args.input_file_name
-  check_name = args.check_name
-  temp_file_name = args.temp_file_name
-  expect_clang_tidy_error = args.expect_clang_tidy_error
-  std = args.std
-
-  file_name_with_extension = assume_file_name or input_file_name
-  _, extension = os.path.splitext(file_name_with_extension)
-  if extension not in ['.c', '.hpp', '.m', '.mm']:
-extension = '.cpp'
-  temp_file_name = temp_file_name + extension
-
-  clang_tidy_extra_args = extra_args
-  clang_extra_args = []
-  if '--' in extra_args:
-i = clang_tidy_extra_args.index('--')
-clang_extra_args = clang_tidy_extra_args[i + 1:]
-clang_tidy_extra_args = clang_tidy_extra_args[:i]
-
-  # If the test does not specify a config style, force an empty one; otherwise
-  # autodetection logic can discover a ".clang-tidy" file that is not related 
to
-  # the test.
-  if not any(
-  [arg.startswith('-config=') for arg in clang_tidy_extra_args]):
-clang_tidy_extra_args.append('-config={}')
-
-  if extension in ['.m', '.mm']:
-clang_extra_args = ['-fobjc-abi-version=2', '-fobjc-arc', '-fblocks'] + \
-clang_extra_args
-
-  if extension in ['.cpp', '.hpp', '.mm']:
-clang_extra_args.append('-std=' + std)
-
-  # Tests should not rely on STL being available, and instead provide mock
-  # implementations of relevant APIs.
-  clang_extra_args.append('-nostdinc++')
-
-  if resource_dir is not None:
-clang_extra_args.append('-resource-dir=%s' % resource_dir)
-
-  with open(input_file_name, 'r', encoding='utf-8') as input_file:
-input_text = input_file.read()
-
-  check_fixes_prefixes = []
-  check_messages_prefixes = []
-  check_notes_prefixes = []
-
-  has_check_fixes = False
-  has_check_messages = False
-  has_check_notes = False
-
-  for check in args.check_suffix:
-if check and not re.match('^[A-Z0-9\-]+$', check):
-  sys.exit('Only A..Z, 0..9 and "-" are ' +
-'allowed in check suffixes list, but "%s" was given' % (check))
-
-file_check_suffix = ('-' + check) if check else ''
-check_fixes_prefix = 'CHECK-FIXES' + file_check_suffix
-check_messages_prefix = 'CHECK-MESSAGES' + file_check_suffix
-check_notes_prefix = 'CHECK-NOTES' + file_check_suffix
-
-has_check_fix = check_fixes_prefix in input_text
-has_check_message = check_messages_prefix in input_text
-has_check_note = check_notes_prefix in input_text
-
-if has_check_note and has_check_message:
-  sys.exit('Please use either %s or %s but not both' %
-(check_notes_prefix, check_messages_prefix))
-
-if not has_check_fix and not has_check_message and not has_check_note:
-  sys.exit('%s, %s or %s not found in the input' %
-(check_fixes_prefix, check_messages_prefix, check_notes_prefix))
-
-has_check_fixes = has_check_fixes or has_check_fix
-has_check_messages = has_check_messages or has_check_message
-has_check_notes = has_check_notes or has_check_note
-
-if has_check_fix:
-  check_fixes_prefixes.append(check_fixes_prefix)
-if has_check_message:
-  check_messages_prefixes.append(check_messages_prefix)
-if has_check_note:
-  check_notes_prefixes.append(check_notes_prefix)
-
-  assert has_check_fixes or has_check_messages or has_check_notes
-  # Remove the contents of the CHECK lines to avoid CHECKs matching on
-  # themselves.  We need to keep the comments to preserve line numbers while
-  # avoiding empty lines which could potentially trigger formatting-related
-  # checks.
-  cleaned_test = re.sub('// *CHECK-[A-Z0-9\-]*:[^\r\n]*', '//', input_text)
-
-  write_file(temp_file_name, cleaned_test)
-
-  original_file_name = temp_file_name + ".orig"
-  

[PATCH] D111566: [SYCL] Fix function pointer address space

2022-01-10 Thread Elizabeth Andrews via Phabricator via cfe-commits
eandrews added inline comments.



Comment at: clang/lib/AST/ASTContext.cpp:11494
+  const Type *TypePtr = T.getTypePtr();
+  return TypePtr->isFunctionType()
+ ? llvm::DataLayout(getTargetInfo().getDataLayoutString())

rjmccall wrote:
> You can just do `T->isFunctionType()`.
Thanks! I'll make the change



Comment at: clang/lib/AST/ASTContext.cpp:11497
+   .getProgramAddressSpace()
+ : getTargetAddressSpace(T.getQualifiers());
+}

rjmccall wrote:
> If a function type has an address space qualifier, we should prefer that, 
> right?  Or is that impossible by construction?
I thought you could only use address space qualifiers for variables. I am not 
sure though. 

This patch retains existing behavior for pointers.  The existing code (deleted 
in CodeGenTypes.cpp in his patch) doesn't take qualifiers into consideration. 


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

https://reviews.llvm.org/D111566

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


[clang] d789ea7 - [Diagnostics] Don't drop a statically set NoWarningAsError flag during option processing

2022-01-10 Thread Wolfgang Pieb via cfe-commits

Author: Wolfgang Pieb
Date: 2022-01-10T16:38:01-08:00
New Revision: d789ea713372d44e50ff52a85a198ac6bbedaef9

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

LOG: [Diagnostics] Don't drop a statically set NoWarningAsError flag during 
option processing

When a -W option is given on the command line, and the corresponding 
diagnostic has
the NoWarnOnError flag set, prevent the flag from being dropped when the 
severity is reevaluated.
This fixes PR51837.

Reviewed By: dexonsmith

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

Added: 


Modified: 
clang/lib/Basic/Diagnostic.cpp
clang/test/Lexer/pragma-message.c

Removed: 




diff  --git a/clang/lib/Basic/Diagnostic.cpp b/clang/lib/Basic/Diagnostic.cpp
index 9b7ad96b949f1..ac4b9d2cd5a2b 100644
--- a/clang/lib/Basic/Diagnostic.cpp
+++ b/clang/lib/Basic/Diagnostic.cpp
@@ -374,6 +374,12 @@ void DiagnosticsEngine::setSeverity(diag::kind Diag, 
diag::Severity Map,
   DiagnosticMapping Mapping = makeUserMapping(Map, L);
   Mapping.setUpgradedFromWarning(WasUpgradedFromWarning);
 
+  // Make sure we propagate the NoWarningAsError flag from an existing
+  // mapping (which may be the default mapping).
+  DiagnosticMapping  = GetCurDiagState()->getOrAddMapping(Diag);
+  Mapping.setNoWarningAsError(Info.hasNoWarningAsError() ||
+  Mapping.hasNoWarningAsError());
+
   // Common case; setting all the diagnostics of a group in one place.
   if ((L.isInvalid() || L == DiagStatesByLoc.getCurDiagStateLoc()) &&
   DiagStatesByLoc.getCurDiagState()) {

diff  --git a/clang/test/Lexer/pragma-message.c 
b/clang/test/Lexer/pragma-message.c
index d0bbe9ea3a628..aca9f14fa2f6d 100644
--- a/clang/test/Lexer/pragma-message.c
+++ b/clang/test/Lexer/pragma-message.c
@@ -1,6 +1,5 @@
 /* Test pragma message directive from
http://msdn.microsoft.com/en-us/library/x7dkzch2.aspx */
-
 // message: Sends a string literal to the standard output without terminating
 // the compilation.
 // #pragma message(messagestring)
@@ -8,6 +7,7 @@
 // #pragma message messagestring
 //
 // RUN: %clang_cc1 -fsyntax-only -verify -Werror %s
+// RUN: %clang_cc1 -fsyntax-only -verify -Werror -W#pragma-messages %s
 #define STRING2(x) #x
 #define STRING(x) STRING2(x)
 #pragma message(":O I'm a message! " STRING(__LINE__)) // expected-warning 
{{:O I'm a message! 13}}



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


[PATCH] D114908: [clang] Don't call inheritDefaultTemplateArguments() on CXXDeductionGuideDecl's template parameters

2022-01-10 Thread Arthur Eubanks via Phabricator via cfe-commits
aeubanks added inline comments.



Comment at: clang/lib/Serialization/ASTReaderDecl.cpp:3784-3790
+  if (auto *TD = dyn_cast(D)) {
+// CXXDeductionGuideDecls reference the class template parameters so we 
need
+// to make sure not to call this twice on the same template parameters.
+if (!isa(TD->getTemplatedDecl()))
+  inheritDefaultTemplateArguments(Reader.getContext(),
+  cast(Previous), TD);
+  }

rsmith wrote:
> An implicit deduction guide can get template parameters from both the class 
> template and the constructor template. The ones from the class template are 
> not copied and owned by the deduction guide, but the ones from the 
> constructor template are. So I think we may need to do this for *some* of the 
> template parameters and not others. Perhaps we could check to see if the 
> template parameter is actually owned by this template and skip updating it if 
> not.
> 
> (Alternatively, I think it'd be fine, and probably simpler and cleaner, to 
> make implicit deduction guide generation always clone the template parameters 
> of the class template. The confusion caused by having the template parameters 
> appear in the "wrong" template is probably not justified by the time / memory 
> savings.)
I tried https://reviews.llvm.org/D116983 and it still doesn't fix this issue, 
although I'm having trouble understanding the Clang AST and the decl chains.
How would you check that the template parameter is owned by this template?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D114908

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


[PATCH] D116859: Fix for: clang-format: break added to macro define with ColumnLimit: 0

2022-01-10 Thread Marek Kurdej via Phabricator via cfe-commits
curdeius added inline comments.



Comment at: clang/unittests/Format/FormatTest.cpp:4810-4811
+
+  verifyFormat("#define STRINGIFY(t) #t\n"
+   "#define MAKEVERSIONSTRING(x, y, z, build) STRINGIFY(x) \".\" 
STRINGIFY(y) \".\" STRINGIFY(z) \".\" STRINGIFY(build)\n",
+   ZeroColumn);

HazardyKnusperkeks wrote:
> curdeius wrote:
> > Please test with something simpler.
> Did this show the bugged behavior without the patch?
> 
> Regarding the `// clang-format off` there is the question what do we want in 
> the tests? Show the long lines as the long lines, then we need to turn it off 
> some times. Or do we want to keep the limit and break the strings, thus 
> making it harder to read for the human?
> Did this show the bugged behavior without the patch?
Yes. I checked with a pretty fresh master.

> Regarding the `// clang-format off` there is the question what do we want in 
> the tests? Show the long lines as the long lines, then we need to turn it off 
> some times. Or do we want to keep the limit and break the strings, thus 
> making it harder to read for the human?
I'm pretty much against adding `// clang-format off` too, it hurts more than it 
helps IMO.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D116859

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


[PATCH] D116978: [clangd] Selection: Prune gtest TEST()s earlier

2022-01-10 Thread Sam McCall via Phabricator via cfe-commits
sammccall created this revision.
sammccall added a reviewer: usaxena95.
Herald added subscribers: kadircet, arphaman.
sammccall requested review of this revision.
Herald added subscribers: cfe-commits, MaskRay, ilya-biryukov.
Herald added a project: clang-tools-extra.

When searching for AST nodes that may overlap the selection, mayHit() was only
attempting to prune nodes whose begin/end are both in the main file.

While failing to prune never gives wrong results, it hurts performance.
In GTest unit-tests, `TEST()` macros at the top level declare classes.
These were never pruned and we traversed *every* such class for any selection.

We fix this by reasoning about what tokens such a node might claim.
They must lie within its ultimate macro expansion range, so if this doesn't
overlap with the selection, we can prune the node.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D116978

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


Index: clang-tools-extra/clangd/Selection.cpp
===
--- clang-tools-extra/clangd/Selection.cpp
+++ clang-tools-extra/clangd/Selection.cpp
@@ -313,12 +313,19 @@
   bool mayHit(SourceRange R) const {
 if (SpelledTokens.empty())
   return false;
-auto B = SM.getDecomposedLoc(R.getBegin());
-auto E = SM.getDecomposedLoc(R.getEnd());
-if (B.first == SelFile && E.first == SelFile)
-  if (E.second < SpelledTokens.front().Offset ||
-  B.second > SpelledTokens.back().Offset)
+// If the node ends before the selection begins, it is not selected.
+if (R.getEnd().isFileID()) {
+  auto E = SM.getDecomposedLoc(R.getEnd());
+  if (E.first == SelFile && E.second < SpelledTokens.front().Offset)
 return false;
+}
+// If the node starts after the selection ends, it is not selected.
+// All tokens a macro location might claim are >= its expansion site.
+// So it's safe to use the expansions location for the comparison.
+// (This is particularly helpful for GTest's TEST macro).
+auto B = SM.getDecomposedExpansionLoc(R.getBegin());
+if (B.first == SelFile && B.second > SpelledTokens.back().Offset)
+  return false;
 return true;
   }
 


Index: clang-tools-extra/clangd/Selection.cpp
===
--- clang-tools-extra/clangd/Selection.cpp
+++ clang-tools-extra/clangd/Selection.cpp
@@ -313,12 +313,19 @@
   bool mayHit(SourceRange R) const {
 if (SpelledTokens.empty())
   return false;
-auto B = SM.getDecomposedLoc(R.getBegin());
-auto E = SM.getDecomposedLoc(R.getEnd());
-if (B.first == SelFile && E.first == SelFile)
-  if (E.second < SpelledTokens.front().Offset ||
-  B.second > SpelledTokens.back().Offset)
+// If the node ends before the selection begins, it is not selected.
+if (R.getEnd().isFileID()) {
+  auto E = SM.getDecomposedLoc(R.getEnd());
+  if (E.first == SelFile && E.second < SpelledTokens.front().Offset)
 return false;
+}
+// If the node starts after the selection ends, it is not selected.
+// All tokens a macro location might claim are >= its expansion site.
+// So it's safe to use the expansions location for the comparison.
+// (This is particularly helpful for GTest's TEST macro).
+auto B = SM.getDecomposedExpansionLoc(R.getBegin());
+if (B.first == SelFile && B.second > SpelledTokens.back().Offset)
+  return false;
 return true;
   }
 
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D116721: [Tooling] When transferring compile commands between files, always use '--'

2022-01-10 Thread Sam McCall 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 rG4258d68dc737: [Tooling] When transferring compile commands 
between files, always use -- (authored by sammccall).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D116721

Files:
  clang-tools-extra/clangd/CompileCommands.cpp
  clang/include/clang/Tooling/CompilationDatabase.h
  clang/lib/Tooling/InterpolatingCompilationDatabase.cpp
  clang/unittests/Tooling/CompilationDatabaseTest.cpp


Index: clang/unittests/Tooling/CompilationDatabaseTest.cpp
===
--- clang/unittests/Tooling/CompilationDatabaseTest.cpp
+++ clang/unittests/Tooling/CompilationDatabaseTest.cpp
@@ -739,6 +739,9 @@
 EXPECT_EQ(Results[0].CommandLine.back(), MakeNative ? path(F) : F)
 << "Last arg should be the file";
 Results[0].CommandLine.pop_back();
+EXPECT_EQ(Results[0].CommandLine.back(), "--")
+<< "Second-last arg should be --";
+Results[0].CommandLine.pop_back();
 return llvm::join(Results[0].CommandLine, " ");
   }
 
@@ -826,18 +829,6 @@
   EXPECT_EQ(getCommand("dir/bar.cpp"), "clang -D dir/foo.cpp -Wall 
-std=c++14");
 }
 
-TEST_F(InterpolateTest, InsertDoubleDash) {
-  add("dir/foo.cpp", "-o foo.o -std=c++14 -Wall");
-  EXPECT_EQ(getCommand("-dir/bar.cpp", false),
-"clang -D dir/foo.cpp -Wall -std=c++14 --");
-}
-
-TEST_F(InterpolateTest, InsertDoubleDashForClangCL) {
-  add("dir/foo.cpp", "clang-cl", "/std:c++14 /W4");
-  EXPECT_EQ(getCommand("/dir/bar.cpp", false),
-"clang-cl -D dir/foo.cpp /W4 /std:c++14 --");
-}
-
 TEST_F(InterpolateTest, Case) {
   add("FOO/BAR/BAZ/SHOUT.cc");
   add("foo/bar/baz/quiet.cc");
@@ -879,7 +870,7 @@
   CompileCommand Transferred = transferCompileCommand(std::move(Cmd), "foo.h");
   EXPECT_EQ(Transferred.Filename, "foo.h");
   EXPECT_THAT(Transferred.CommandLine,
-  ElementsAre("clang", "-Wall", "-x", "c++-header", "foo.h"));
+  ElementsAre("clang", "-Wall", "-x", "c++-header", "--", 
"foo.h"));
   EXPECT_EQ(Transferred.Directory, "dir");
 }
 
Index: clang/lib/Tooling/InterpolatingCompilationDatabase.cpp
===
--- clang/lib/Tooling/InterpolatingCompilationDatabase.cpp
+++ clang/lib/Tooling/InterpolatingCompilationDatabase.cpp
@@ -243,8 +243,7 @@
   llvm::Twine(ClangCLMode ? "/std:" : "-std=") +
   LangStandard::getLangStandardForKind(Std).getName()).str());
 }
-if (Filename.startswith("-") || (ClangCLMode && Filename.startswith("/")))
-  Result.CommandLine.push_back("--");
+Result.CommandLine.push_back("--");
 Result.CommandLine.push_back(std::string(Filename));
 return Result;
   }
Index: clang/include/clang/Tooling/CompilationDatabase.h
===
--- clang/include/clang/Tooling/CompilationDatabase.h
+++ clang/include/clang/Tooling/CompilationDatabase.h
@@ -216,6 +216,8 @@
 /// Transforms a compile command so that it applies the same configuration to
 /// a different file. Most args are left intact, but tweaks may be needed
 /// to certain flags (-x, -std etc).
+///
+/// The output command will always end in {"--", Filename}.
 tooling::CompileCommand transferCompileCommand(tooling::CompileCommand,
StringRef Filename);
 
Index: clang-tools-extra/clangd/CompileCommands.cpp
===
--- clang-tools-extra/clangd/CompileCommands.cpp
+++ clang-tools-extra/clangd/CompileCommands.cpp
@@ -290,16 +290,9 @@
 TransferCmd.CommandLine = std::move(Cmd);
 TransferCmd = transferCompileCommand(std::move(TransferCmd), File);
 Cmd = std::move(TransferCmd.CommandLine);
-
-// Restore the canonical "driver --opts -- filename" form we expect.
-// FIXME: This is ugly and coupled. Make transferCompileCommand ensure it?
-assert(!Cmd.empty() && Cmd.back() == File);
-Cmd.pop_back();
-if (!Cmd.empty() && Cmd.back() == "--")
-  Cmd.pop_back();
-assert(!llvm::is_contained(Cmd, "--"));
-Cmd.push_back("--");
-Cmd.push_back(File.str());
+assert(Cmd.size() >= 2 && Cmd.back() == File &&
+   Cmd[Cmd.size() - 2] == "--" &&
+   "TransferCommand should produce a command ending in -- filename");
   }
 
   for (auto  : Config::current().CompileFlags.Edits)


Index: clang/unittests/Tooling/CompilationDatabaseTest.cpp
===
--- clang/unittests/Tooling/CompilationDatabaseTest.cpp
+++ clang/unittests/Tooling/CompilationDatabaseTest.cpp
@@ -739,6 +739,9 @@
 EXPECT_EQ(Results[0].CommandLine.back(), MakeNative ? path(F) : F)
 << "Last arg should be the file";
 

[clang-tools-extra] 4258d68 - [Tooling] When transferring compile commands between files, always use '--'

2022-01-10 Thread Sam McCall via cfe-commits

Author: Sam McCall
Date: 2022-01-11T01:41:42+01:00
New Revision: 4258d68dc73789bc7fc491734c9c392809b1b29a

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

LOG: [Tooling] When transferring compile commands between files, always use '--'

"driver  -- " is a particularly convenient form of the
compile command to manipulate, with fewer special cases to handle.

Guaranteeing that the output command is of that form is cheap and makes
it easier to consume the result in some cases.

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

Added: 


Modified: 
clang-tools-extra/clangd/CompileCommands.cpp
clang/include/clang/Tooling/CompilationDatabase.h
clang/lib/Tooling/InterpolatingCompilationDatabase.cpp
clang/unittests/Tooling/CompilationDatabaseTest.cpp

Removed: 




diff  --git a/clang-tools-extra/clangd/CompileCommands.cpp 
b/clang-tools-extra/clangd/CompileCommands.cpp
index 5c98e40a87fdd..7d6f612cb8b96 100644
--- a/clang-tools-extra/clangd/CompileCommands.cpp
+++ b/clang-tools-extra/clangd/CompileCommands.cpp
@@ -290,16 +290,9 @@ void CommandMangler::adjust(std::vector ,
 TransferCmd.CommandLine = std::move(Cmd);
 TransferCmd = transferCompileCommand(std::move(TransferCmd), File);
 Cmd = std::move(TransferCmd.CommandLine);
-
-// Restore the canonical "driver --opts -- filename" form we expect.
-// FIXME: This is ugly and coupled. Make transferCompileCommand ensure it?
-assert(!Cmd.empty() && Cmd.back() == File);
-Cmd.pop_back();
-if (!Cmd.empty() && Cmd.back() == "--")
-  Cmd.pop_back();
-assert(!llvm::is_contained(Cmd, "--"));
-Cmd.push_back("--");
-Cmd.push_back(File.str());
+assert(Cmd.size() >= 2 && Cmd.back() == File &&
+   Cmd[Cmd.size() - 2] == "--" &&
+   "TransferCommand should produce a command ending in -- filename");
   }
 
   for (auto  : Config::current().CompileFlags.Edits)

diff  --git a/clang/include/clang/Tooling/CompilationDatabase.h 
b/clang/include/clang/Tooling/CompilationDatabase.h
index 90af15536961e..fee584acb4862 100644
--- a/clang/include/clang/Tooling/CompilationDatabase.h
+++ b/clang/include/clang/Tooling/CompilationDatabase.h
@@ -216,6 +216,8 @@ class FixedCompilationDatabase : public CompilationDatabase 
{
 /// Transforms a compile command so that it applies the same configuration to
 /// a 
diff erent file. Most args are left intact, but tweaks may be needed
 /// to certain flags (-x, -std etc).
+///
+/// The output command will always end in {"--", Filename}.
 tooling::CompileCommand transferCompileCommand(tooling::CompileCommand,
StringRef Filename);
 

diff  --git a/clang/lib/Tooling/InterpolatingCompilationDatabase.cpp 
b/clang/lib/Tooling/InterpolatingCompilationDatabase.cpp
index c1e25c41f7198..51e8439b6b79b 100644
--- a/clang/lib/Tooling/InterpolatingCompilationDatabase.cpp
+++ b/clang/lib/Tooling/InterpolatingCompilationDatabase.cpp
@@ -243,8 +243,7 @@ struct TransferableCommand {
   llvm::Twine(ClangCLMode ? "/std:" : "-std=") +
   LangStandard::getLangStandardForKind(Std).getName()).str());
 }
-if (Filename.startswith("-") || (ClangCLMode && Filename.startswith("/")))
-  Result.CommandLine.push_back("--");
+Result.CommandLine.push_back("--");
 Result.CommandLine.push_back(std::string(Filename));
 return Result;
   }

diff  --git a/clang/unittests/Tooling/CompilationDatabaseTest.cpp 
b/clang/unittests/Tooling/CompilationDatabaseTest.cpp
index 218a352f86f06..adb9de0c1cbaa 100644
--- a/clang/unittests/Tooling/CompilationDatabaseTest.cpp
+++ b/clang/unittests/Tooling/CompilationDatabaseTest.cpp
@@ -739,6 +739,9 @@ class InterpolateTest : public MemDBTest {
 EXPECT_EQ(Results[0].CommandLine.back(), MakeNative ? path(F) : F)
 << "Last arg should be the file";
 Results[0].CommandLine.pop_back();
+EXPECT_EQ(Results[0].CommandLine.back(), "--")
+<< "Second-last arg should be --";
+Results[0].CommandLine.pop_back();
 return llvm::join(Results[0].CommandLine, " ");
   }
 
@@ -826,18 +829,6 @@ TEST_F(InterpolateTest, StripDoubleDash) {
   EXPECT_EQ(getCommand("dir/bar.cpp"), "clang -D dir/foo.cpp -Wall 
-std=c++14");
 }
 
-TEST_F(InterpolateTest, InsertDoubleDash) {
-  add("dir/foo.cpp", "-o foo.o -std=c++14 -Wall");
-  EXPECT_EQ(getCommand("-dir/bar.cpp", false),
-"clang -D dir/foo.cpp -Wall -std=c++14 --");
-}
-
-TEST_F(InterpolateTest, InsertDoubleDashForClangCL) {
-  add("dir/foo.cpp", "clang-cl", "/std:c++14 /W4");
-  EXPECT_EQ(getCommand("/dir/bar.cpp", false),
-"clang-cl -D dir/foo.cpp /W4 /std:c++14 --");
-}
-
 TEST_F(InterpolateTest, Case) {
   add("FOO/BAR/BAZ/SHOUT.cc");
   add("foo/bar/baz/quiet.cc");
@@ 

[PATCH] D116387: [CodeCompletion][clangd] Clean __uglified parameter names in completion & hover

2022-01-10 Thread Sam McCall via Phabricator via cfe-commits
sammccall updated this revision to Diff 398779.
sammccall added a comment.

Fix printName


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D116387

Files:
  clang-tools-extra/clangd/AST.cpp
  clang-tools-extra/clangd/AST.h
  clang-tools-extra/clangd/Hover.cpp
  clang-tools-extra/clangd/unittests/HoverTests.cpp
  clang-tools-extra/clangd/unittests/SymbolCollectorTests.cpp
  clang/include/clang/AST/PrettyPrinter.h
  clang/include/clang/Basic/IdentifierTable.h
  clang/lib/AST/DeclPrinter.cpp
  clang/lib/AST/StmtPrinter.cpp
  clang/lib/AST/TemplateName.cpp
  clang/lib/AST/TypePrinter.cpp
  clang/lib/Basic/IdentifierTable.cpp
  clang/lib/Sema/SemaCodeComplete.cpp
  clang/test/CodeCompletion/deuglify.cpp
  clang/unittests/AST/DeclPrinterTest.cpp
  clang/unittests/AST/StmtPrinterTest.cpp
  clang/unittests/AST/TypePrinterTest.cpp

Index: clang/unittests/AST/TypePrinterTest.cpp
===
--- clang/unittests/AST/TypePrinterTest.cpp
+++ clang/unittests/AST/TypePrinterTest.cpp
@@ -62,4 +62,21 @@
   ASSERT_TRUE(PrintedTypeMatches(
   Code, {}, Matcher, "const N::Type &",
   [](PrintingPolicy ) { Policy.FullyQualifiedName = true; }));
-}
\ No newline at end of file
+}
+
+TEST(TypePrinter, ParamsUglified) {
+  llvm::StringLiteral Code = R"cpp(
+template  class __f>
+const __f<_Tp&> *A = nullptr;
+  )cpp";
+  auto Clean = [](PrintingPolicy ) {
+Policy.CleanUglifiedParameters = true;
+  };
+
+  ASSERT_TRUE(PrintedTypeMatches(Code, {},
+ varDecl(hasType(qualType().bind("id"))),
+ "const __f<_Tp &> *", nullptr));
+  ASSERT_TRUE(PrintedTypeMatches(Code, {},
+ varDecl(hasType(qualType().bind("id"))),
+ "const f *", Clean));
+}
Index: clang/unittests/AST/StmtPrinterTest.cpp
===
--- clang/unittests/AST/StmtPrinterTest.cpp
+++ clang/unittests/AST/StmtPrinterTest.cpp
@@ -263,3 +263,22 @@
 
   [](PrintingPolicy ) { PP.TerseOutput = true; }));
 }
+
+TEST(StmtPrinter, ParamsUglified) {
+  llvm::StringLiteral Code = R"cpp(
+template  class _C>
+auto foo(int __j) {
+  return typename _C<_T>::_F(_I, __j);
+}
+  )cpp";
+  auto Clean = [](PrintingPolicy ) {
+Policy.CleanUglifiedParameters = true;
+  };
+
+  ASSERT_TRUE(PrintedStmtCXXMatches(StdVer::CXX14, Code,
+returnStmt().bind("id"),
+"return typename _C<_T>::_F(_I, __j);\n"));
+  ASSERT_TRUE(
+  PrintedStmtCXXMatches(StdVer::CXX14, Code, returnStmt().bind("id"),
+"return typename C::_F(I, j);\n", Clean));
+}
Index: clang/unittests/AST/DeclPrinterTest.cpp
===
--- clang/unittests/AST/DeclPrinterTest.cpp
+++ clang/unittests/AST/DeclPrinterTest.cpp
@@ -1336,6 +1336,41 @@
   ASSERT_TRUE(PrintedDeclCXX11Matches(Code, "NT2", "int NT2 = 5"));
 }
 
+TEST(DeclPrinter, TestFunctionParamUglified) {
+  llvm::StringLiteral Code = R"cpp(
+class __c;
+void _A(__c *__param);
+  )cpp";
+  auto Clean = [](PrintingPolicy ) {
+Policy.CleanUglifiedParameters = true;
+  };
+
+  ASSERT_TRUE(PrintedDeclCXX17Matches(Code, namedDecl(hasName("_A")).bind("id"),
+  "void _A(__c *__param)"));
+  ASSERT_TRUE(PrintedDeclCXX17Matches(Code, namedDecl(hasName("_A")).bind("id"),
+  "void _A(__c *param)", Clean));
+}
+
+TEST(DeclPrinter, TestTemplateParamUglified) {
+  llvm::StringLiteral Code = R"cpp(
+template  class _Container>
+struct _A{};
+  )cpp";
+  auto Clean = [](PrintingPolicy ) {
+Policy.CleanUglifiedParameters = true;
+  };
+
+  ASSERT_TRUE(PrintedDeclCXX17Matches(
+  Code, classTemplateDecl(hasName("_A")).bind("id"),
+  "template  class _Container> "
+  "struct _A {}"));
+  ASSERT_TRUE(PrintedDeclCXX17Matches(
+  Code, classTemplateDecl(hasName("_A")).bind("id"),
+  "template  class Container> "
+  "struct _A {}",
+  Clean));
+}
+
 TEST(DeclPrinter, TestStaticAssert1) {
   ASSERT_TRUE(PrintedDeclCXX17Matches("static_assert(true);",
   staticAssertDecl().bind("id"),
Index: clang/test/CodeCompletion/deuglify.cpp
===
--- /dev/null
+++ clang/test/CodeCompletion/deuglify.cpp
@@ -0,0 +1,25 @@
+// Fake standard library with uglified names.
+// Parameters (including template params) get ugliness stripped.
+namespace std {
+
+template 
+class __vector_base {};
+
+template 
+class vector : private __vector_base<_Tp> {
+public:
+  _Tp (unsigned __index) const;
+  int __stays_ugly();
+};
+
+} // namespace std
+
+int x = std::vector{}.at(42);
+// RUN: %clang_cc1 

[clang] 86c5b87 - [AST] Don't consider 'ExportDecl' when calculating DeclContext 'Encloses'

2022-01-10 Thread Chuanqi Xu via cfe-commits

Author: Chuanqi Xu
Date: 2022-01-11T09:54:57+08:00
New Revision: 86c5b870b2e5192a9414204500a53b31524db065

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

LOG: [AST] Don't consider 'ExportDecl' when calculating DeclContext 'Encloses'

This mimics the style of 90010c2e1 (Don't consider 'LinkageSpec' when
calculating DeclContext 'Encloses'). Since ExportDecl and LinkageSpec
are transparent DeclContext, they share some similarity.

Reviewed By: erichkeane

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

Added: 
clang/test/SemaCXX/lookup-through-export.cpp

Modified: 
clang/lib/AST/DeclBase.cpp

Removed: 




diff  --git a/clang/lib/AST/DeclBase.cpp b/clang/lib/AST/DeclBase.cpp
index 064012ba865c8..52b8a45721105 100644
--- a/clang/lib/AST/DeclBase.cpp
+++ b/clang/lib/AST/DeclBase.cpp
@@ -1212,7 +1212,8 @@ bool DeclContext::Encloses(const DeclContext *DC) const {
 return getPrimaryContext()->Encloses(DC);
 
   for (; DC; DC = DC->getParent())
-if (!isa(DC) && DC->getPrimaryContext() == this)
+if (!isa(DC) && !isa(DC) &&
+DC->getPrimaryContext() == this)
   return true;
   return false;
 }

diff  --git a/clang/test/SemaCXX/lookup-through-export.cpp 
b/clang/test/SemaCXX/lookup-through-export.cpp
new file mode 100644
index 0..503a694655608
--- /dev/null
+++ b/clang/test/SemaCXX/lookup-through-export.cpp
@@ -0,0 +1,31 @@
+// RUN: %clang_cc1 -std=c++20 %s -verify
+
+// expected-no-diagnostics
+export module X;
+export {
+  namespace A {
+  namespace B {
+  int bar;
+  }
+  } // namespace A
+  namespace C {
+  void foo() {
+using namespace A;
+(void)B::bar;
+  }
+  } // namespace C
+}
+
+export {
+  namespace D {
+  namespace E {
+  int bar;
+  }
+  } // namespace D
+  namespace F {
+  void foo() {
+using namespace D;
+(void)E::bar;
+  }
+  } // namespace F
+}



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


[PATCH] D111566: [SYCL] Fix function pointer address space

2022-01-10 Thread John McCall via Phabricator via cfe-commits
rjmccall added inline comments.



Comment at: clang/lib/AST/ASTContext.cpp:11496
+   .getProgramAddressSpace()
+ : getTargetAddressSpace(T.getQualifiers());
+}

Oh, I'm sorry I missed this.  Parsing the data layout string into an 
`llvm::DataLayout` is definitely not an okay thing to be doing here.  The IRGen 
version of this had a cached `DataLayout` object which it queried, which was 
okay, but this function is used too tightly to be doing that much redundant 
work.

We could just cache a `DataLayout` in the `clang::TargetInfo`, but I think 
we've been trying to avoid that as a layering violation.  Instead, `TargetInfo` 
should just have a `getProgramAddressSpace` method or something like that, and 
the targets with non-default address spaces for code should set that manually.



Comment at: clang/lib/AST/ASTContext.cpp:11497
+   .getProgramAddressSpace()
+ : getTargetAddressSpace(T.getQualifiers());
+}

eandrews wrote:
> rjmccall wrote:
> > If a function type has an address space qualifier, we should prefer that, 
> > right?  Or is that impossible by construction?
> I thought you could only use address space qualifiers for variables. I am not 
> sure though. 
> 
> This patch retains existing behavior for pointers.  The existing code 
> (deleted in CodeGenTypes.cpp in his patch) doesn't take qualifiers into 
> consideration. 
Ah, yes, I see.  Alright.


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

https://reviews.llvm.org/D111566

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


[PATCH] D111566: [SYCL] Fix function pointer address space

2022-01-10 Thread John McCall via Phabricator via cfe-commits
rjmccall added inline comments.



Comment at: clang/lib/AST/ASTContext.cpp:11494
+  const Type *TypePtr = T.getTypePtr();
+  return TypePtr->isFunctionType()
+ ? llvm::DataLayout(getTargetInfo().getDataLayoutString())

You can just do `T->isFunctionType()`.



Comment at: clang/lib/AST/ASTContext.cpp:11497
+   .getProgramAddressSpace()
+ : getTargetAddressSpace(T.getQualifiers());
+}

If a function type has an address space qualifier, we should prefer that, 
right?  Or is that impossible by construction?



Comment at: clang/lib/CodeGen/CodeGenTypes.cpp:747
   : ConvertTypeForMem(FTy);
-unsigned AS = Context.getTargetAddressSpace(FTy);
+unsigned AS = Context.getTargetAddressSpace(FTy.getQualifiers());
 ResultType = llvm::PointerType::get(PointeeType, AS);

Please add a comment here explaining that it's important to not just use `FTy` 
because in the absence of an explicit address space we need to get the default 
address space for a data pointer, not a function.


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

https://reviews.llvm.org/D111566

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


[PATCH] D116975: [OpenMP] Initial Implementation of LTO and bitcode linking in linker wrapper

2022-01-10 Thread Joseph Huber via Phabricator via cfe-commits
jhuber6 created this revision.
jhuber6 added reviewers: jdoerfert, gregrodgers, JonChesterfield, ronlieb.
Herald added subscribers: guansong, hiraditya, inglorion, yaxunl, mgorny.
jhuber6 requested review of this revision.
Herald added subscribers: llvm-commits, cfe-commits, sstefan1.
Herald added projects: clang, LLVM.

This patch implements the fist support for handling LTO in the
offloading pipeline. The flag `-foffload-lto` is used to control if
bitcode is embedded into the device. If bitcode is found in the device,
the extracted files will be sent to the LTO pipeline to be linked and
sent to the backend. This implementation does not separately link the
device bitcode libraries yet.

Depends on D116675 


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D116975

Files:
  clang/lib/Driver/Driver.cpp
  clang/lib/Driver/ToolChains/Clang.cpp
  clang/tools/clang-linker-wrapper/CMakeLists.txt
  clang/tools/clang-linker-wrapper/ClangLinkerWrapper.cpp
  llvm/lib/Passes/PassBuilderPipelines.cpp

Index: llvm/lib/Passes/PassBuilderPipelines.cpp
===
--- llvm/lib/Passes/PassBuilderPipelines.cpp
+++ llvm/lib/Passes/PassBuilderPipelines.cpp
@@ -1464,6 +1464,9 @@
   // libraries and other oracles.
   MPM.addPass(InferFunctionAttrsPass());
 
+  if (Level.getSpeedupLevel() > 1)
+MPM.addPass(OpenMPOptPass());
+
   if (Level.getSpeedupLevel() > 1) {
 FunctionPassManager EarlyFPM;
 EarlyFPM.addPass(CallSiteSplittingPass());
@@ -1773,6 +1776,7 @@
   MPM.addPass(createModuleToFunctionPassAdaptor(CoroEarlyPass()));
   CGSCCPassManager CGPM;
   CGPM.addPass(CoroSplitPass());
+  CGPM.addPass(OpenMPOptCGSCCPass());
   MPM.addPass(createModuleToPostOrderCGSCCPassAdaptor(std::move(CGPM)));
   MPM.addPass(createModuleToFunctionPassAdaptor(CoroCleanupPass()));
 
Index: clang/tools/clang-linker-wrapper/ClangLinkerWrapper.cpp
===
--- clang/tools/clang-linker-wrapper/ClangLinkerWrapper.cpp
+++ clang/tools/clang-linker-wrapper/ClangLinkerWrapper.cpp
@@ -17,9 +17,12 @@
 #include "clang/Basic/Version.h"
 #include "llvm/BinaryFormat/Magic.h"
 #include "llvm/Bitcode/BitcodeWriter.h"
+#include "llvm/CodeGen/CommandFlags.h"
 #include "llvm/IR/Constants.h"
+#include "llvm/IR/DiagnosticPrinter.h"
 #include "llvm/IR/Module.h"
 #include "llvm/IRReader/IRReader.h"
+#include "llvm/LTO/LTO.h"
 #include "llvm/Object/Archive.h"
 #include "llvm/Object/ArchiveWriter.h"
 #include "llvm/Object/Binary.h"
@@ -36,6 +39,7 @@
 #include "llvm/Support/Signals.h"
 #include "llvm/Support/SourceMgr.h"
 #include "llvm/Support/StringSaver.h"
+#include "llvm/Support/TargetSelect.h"
 #include "llvm/Support/WithColor.h"
 #include "llvm/Support/raw_ostream.h"
 
@@ -58,6 +62,15 @@
cl::desc("Path of linker binary"),
cl::cat(ClangLinkerWrapperCategory));
 
+static cl::opt
+TargetFeatures("target-feature", cl::desc("Target features for triple"),
+   cl::cat(ClangLinkerWrapperCategory));
+
+static cl::opt OptLevel("opt-level",
+ cl::desc("Optimization level for LTO"),
+ cl::init("O0"),
+ cl::cat(ClangLinkerWrapperCategory));
+
 // Do not parse linker options.
 static cl::list
 HostLinkerArgs(cl::Sink, cl::desc("..."));
@@ -68,6 +81,9 @@
 /// Temporary files created by the linker wrapper.
 static SmallVector TempFiles;
 
+/// Codegen flags for LTO backend.
+static codegen::RegisterCodeGenFlags CodeGenFlags;
+
 /// Magic section string that marks the existence of offloading data. The
 /// section string will be formatted as `.llvm.offloading..`.
 #define OFFLOAD_SECTION_MAGIC_STR ".llvm.offloading."
@@ -195,6 +211,28 @@
   if (ToBeStripped.empty())
 return None;
 
+  // If the object file to strip doesn't exist we need to write it so we can
+  // pass it to llvm-strip.
+  SmallString<128> StripFile = Obj.getFileName();
+  if (!sys::fs::exists(StripFile)) {
+SmallString<128> TempFile;
+if (std::error_code EC = sys::fs::createTemporaryFile(
+sys::path::stem(StripFile), "o", TempFile))
+  return createFileError(TempFile, EC);
+TempFiles.push_back(static_cast(TempFile));
+
+auto Contents = Obj.getMemoryBufferRef().getBuffer();
+Expected> OutputOrErr =
+FileOutputBuffer::create(TempFile, Contents.size());
+if (!OutputOrErr)
+  return OutputOrErr.takeError();
+std::unique_ptr Output = std::move(*OutputOrErr);
+std::copy(Contents.begin(), Contents.end(), Output->getBufferStart());
+if (Error E = Output->commit())
+  return E;
+StripFile = TempFile;
+  }
+
   // We will use llvm-strip to remove the now unneeded section containing the
   // offloading code.
   ErrorOr StripPath = sys::findProgramByName(
@@ 

[PATCH] D116294: [CodeCompletion] (mostly) fix completion in incomplete C++ ctor initializers.

2022-01-10 Thread Sam McCall via Phabricator via cfe-commits
sammccall updated this revision to Diff 398775.
sammccall added a comment.

Never eat malformed decl while code completing


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D116294

Files:
  clang-tools-extra/clangd/unittests/CodeCompleteTests.cpp
  clang/lib/Parse/ParseCXXInlineMethods.cpp
  clang/test/CodeCompletion/ctor-initializer.cpp

Index: clang/test/CodeCompletion/ctor-initializer.cpp
===
--- clang/test/CodeCompletion/ctor-initializer.cpp
+++ clang/test/CodeCompletion/ctor-initializer.cpp
@@ -103,3 +103,23 @@
 // RUN: %clang_cc1 -fsyntax-only -std=c++98 -code-completion-at=%s:100:9 %s -o - | FileCheck -check-prefix=CHECK-CC11 %s
 // RUN: %clang_cc1 -fsyntax-only -std=c++14 -code-completion-at=%s:100:9 %s -o - | FileCheck -check-prefix=CHECK-CC11 %s
 // CHECK-CC11: Pattern : Y(<#Y#>)
+
+// Test with incomplete init lists. (Relevant as parsing is *not* cut off).
+struct Incomplete1 {
+  Incomplete1() : mem
+
+  int member1;
+  int member2;
+};
+// RUN: not %clang_cc1 -fsyntax-only -std=c++14 -code-completion-at=%s:109:19 %s -o - | FileCheck -check-prefix=CHECK-CC12 %s
+// CHECK-CC12: COMPLETION: Pattern : member1(<#int#>)
+// CHECK-CC12: COMPLETION: Pattern : member2(<#int#>)
+
+struct Incomplete2 {
+  Incomplete2() : member2(
+
+  int member1;
+  int member2;
+};
+// RUN: not %clang_cc1 -fsyntax-only -std=c++14 -code-completion-at=%s:119:27 %s -o - | FileCheck -check-prefix=CHECK-CC13 %s
+// CHECK-CC13: PREFERRED-TYPE: int
Index: clang/lib/Parse/ParseCXXInlineMethods.cpp
===
--- clang/lib/Parse/ParseCXXInlineMethods.cpp
+++ clang/lib/Parse/ParseCXXInlineMethods.cpp
@@ -140,8 +140,22 @@
   // function body.
   if (ConsumeAndStoreFunctionPrologue(Toks)) {
 // We didn't find the left-brace we expected after the
-// constructor initializer; we already printed an error, and it's likely
-// impossible to recover, so don't try to parse this method later.
+// constructor initializer.
+
+// If we're code-completing and the completion point was in the broken
+// initializer, we want to parse it even though that will fail.
+if (PP.isCodeCompletionEnabled() &&
+llvm::any_of(Toks, [](const Token ) {
+  return Tok.is(tok::code_completion);
+})) {
+  // If we gave up at the completion point, the initializer list was
+  // likely truncated, so don't eat more tokens. We'll hit some extra
+  // errors, but they should be ignored in code completion.
+  return FnD;
+}
+
+// We already printed an error, and it's likely impossible to recover,
+// so don't try to parse this method later.
 // Skip over the rest of the decl and back to somewhere that looks
 // reasonable.
 SkipMalformedDecl();
Index: clang-tools-extra/clangd/unittests/CodeCompleteTests.cpp
===
--- clang-tools-extra/clangd/unittests/CodeCompleteTests.cpp
+++ clang-tools-extra/clangd/unittests/CodeCompleteTests.cpp
@@ -2006,6 +2006,36 @@
   UnorderedElementsAre(AllOf(Scope("ns::X::"), Named("x_";
 }
 
+// Like other class members, constructor init lists have to parse what's below,
+// after the completion point.
+// But recovering from an incomplete constructor init list is particularly
+// tricky because the bulk of the list is not surrounded by brackets.
+TEST(CompletionTest, ConstructorInitListIncomplete) {
+  auto Results = completions(
+  R"cpp(
+namespace ns {
+  struct X {
+X() : x^
+int xyz_;
+  };
+}
+  )cpp");
+  EXPECT_THAT(Results.Completions, ElementsAre(Named("xyz_")));
+
+  Results = completions(
+  R"cpp(
+int foo();
+
+namespace ns {
+  struct X {
+X() : xyz_(fo^
+int xyz_;
+  };
+}
+  )cpp");
+  EXPECT_THAT(Results.Completions, ElementsAre(Named("foo")));
+}
+
 TEST(CompletionTest, CodeCompletionContext) {
   auto Results = completions(
   R"cpp(
@@ -2650,9 +2680,7 @@
 TEST(SignatureHelpTest, ConstructorInitializeFields) {
   {
 const auto Results = signatures(R"cpp(
-  struct A {
-A(int);
-  };
+  struct A { A(int); };
   struct B {
 B() : a_elem(^) {}
 A a_elem;
@@ -2662,6 +2690,31 @@
 UnorderedElementsAre(Sig("A([[int]])"), Sig("A([[A &&]])"),
  Sig("A([[const A &]])")));
   }
+  {
+const auto Results = signatures(R"cpp(
+  struct A { A(int); };
+  struct B {
+B() : a_elem(^
+A a_elem;
+  };
+)cpp");
+// FIXME: currently the parser skips over the decl of a_elem as part of the
+// (broken) init list, so we don't get signatures for the first member.
+EXPECT_THAT(Results.signatures, 

[PATCH] D116294: [CodeCompletion] (mostly) fix completion in incomplete C++ ctor initializers.

2022-01-10 Thread Sam McCall via Phabricator via cfe-commits
sammccall added inline comments.



Comment at: clang/lib/Parse/ParseCXXInlineMethods.cpp:153
+  // probably truncated, so don't eat more tokens.
+  if (!Toks.back().is(tok::code_completion))
+SkipMalformedDecl();

kadircet wrote:
> i don't follow the logic here. maybe i am reading the comment wrong, but we 
> are actually going to eat **more** tokens by calling `SkipMalformedDecl`, 
> possibly the following one, right? for example in a scenario like:
> ```
> struct Foo {
>   Foo : ^b
>   int bar;
> }
> ```
> `ConsumeAndStoreFunctionPrologue` will actually put `b` following the code 
> completion token (`^`) into `Toks` as well, hence when we skip, we actually 
> skip until the next semicolon and throw away bar. But when the code 
> completion token is after `b`, `ConsumeAndStoreFunctionPrologue` we'll have 
> code completion token at the end of the `Toks` and won't skip anything
> 
>  Do we have cases that break miserably when we don't perform an extra skip 
> here for the (possible) reminder of current initalizer?
> i don't follow the logic here. maybe i am reading the comment wrong, 

Neither the code nor the comment are very good, but I think they are consistent.

Baseline behavior: we're going to recover by letting SkipMalformedDecl() eat 
tokens.
Exception: if we already ate the code completion token *and* stopped right 
afterwards.
Reason: CC token followed by heuristic stop are consistent with the function 
being truncated at the code completion point.

This exception allows some motivating testcases to pass. I thought maybe 
further improvements were possible but didn't want to get into them in this 
patch. However

>  Do we have cases that break miserably when we don't perform an extra skip 
> here for the (possible) reminder of current initalizer?

Um, apparently not. I thought I did!
Never skipping is simple and intuitive and makes more testcases pass.
Let's try it, the risk seems low.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D116294

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


[PATCH] D109981: [Diagnostics] Don't drop a statically set NoWarningAsError flag during option processing

2022-01-10 Thread Wolfgang Pieb via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rGd789ea713372: [Diagnostics] Dont drop a statically set 
NoWarningAsError flag during option… (authored by wolfgangp).
Herald added a project: clang.

Changed prior to commit:
  https://reviews.llvm.org/D109981?vs=373255=398778#toc

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D109981

Files:
  clang/lib/Basic/Diagnostic.cpp
  clang/test/Lexer/pragma-message.c


Index: clang/test/Lexer/pragma-message.c
===
--- clang/test/Lexer/pragma-message.c
+++ clang/test/Lexer/pragma-message.c
@@ -1,6 +1,5 @@
 /* Test pragma message directive from
http://msdn.microsoft.com/en-us/library/x7dkzch2.aspx */
-
 // message: Sends a string literal to the standard output without terminating
 // the compilation.
 // #pragma message(messagestring)
@@ -8,6 +7,7 @@
 // #pragma message messagestring
 //
 // RUN: %clang_cc1 -fsyntax-only -verify -Werror %s
+// RUN: %clang_cc1 -fsyntax-only -verify -Werror -W#pragma-messages %s
 #define STRING2(x) #x
 #define STRING(x) STRING2(x)
 #pragma message(":O I'm a message! " STRING(__LINE__)) // expected-warning 
{{:O I'm a message! 13}}
Index: clang/lib/Basic/Diagnostic.cpp
===
--- clang/lib/Basic/Diagnostic.cpp
+++ clang/lib/Basic/Diagnostic.cpp
@@ -374,6 +374,12 @@
   DiagnosticMapping Mapping = makeUserMapping(Map, L);
   Mapping.setUpgradedFromWarning(WasUpgradedFromWarning);
 
+  // Make sure we propagate the NoWarningAsError flag from an existing
+  // mapping (which may be the default mapping).
+  DiagnosticMapping  = GetCurDiagState()->getOrAddMapping(Diag);
+  Mapping.setNoWarningAsError(Info.hasNoWarningAsError() ||
+  Mapping.hasNoWarningAsError());
+
   // Common case; setting all the diagnostics of a group in one place.
   if ((L.isInvalid() || L == DiagStatesByLoc.getCurDiagStateLoc()) &&
   DiagStatesByLoc.getCurDiagState()) {


Index: clang/test/Lexer/pragma-message.c
===
--- clang/test/Lexer/pragma-message.c
+++ clang/test/Lexer/pragma-message.c
@@ -1,6 +1,5 @@
 /* Test pragma message directive from
http://msdn.microsoft.com/en-us/library/x7dkzch2.aspx */
-
 // message: Sends a string literal to the standard output without terminating
 // the compilation.
 // #pragma message(messagestring)
@@ -8,6 +7,7 @@
 // #pragma message messagestring
 //
 // RUN: %clang_cc1 -fsyntax-only -verify -Werror %s
+// RUN: %clang_cc1 -fsyntax-only -verify -Werror -W#pragma-messages %s
 #define STRING2(x) #x
 #define STRING(x) STRING2(x)
 #pragma message(":O I'm a message! " STRING(__LINE__)) // expected-warning {{:O I'm a message! 13}}
Index: clang/lib/Basic/Diagnostic.cpp
===
--- clang/lib/Basic/Diagnostic.cpp
+++ clang/lib/Basic/Diagnostic.cpp
@@ -374,6 +374,12 @@
   DiagnosticMapping Mapping = makeUserMapping(Map, L);
   Mapping.setUpgradedFromWarning(WasUpgradedFromWarning);
 
+  // Make sure we propagate the NoWarningAsError flag from an existing
+  // mapping (which may be the default mapping).
+  DiagnosticMapping  = GetCurDiagState()->getOrAddMapping(Diag);
+  Mapping.setNoWarningAsError(Info.hasNoWarningAsError() ||
+  Mapping.hasNoWarningAsError());
+
   // Common case; setting all the diagnostics of a group in one place.
   if ((L.isInvalid() || L == DiagStatesByLoc.getCurDiagStateLoc()) &&
   DiagStatesByLoc.getCurDiagState()) {
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] 98ab43a - [HIP] Fix device only linking for -fgpu-rdc

2022-01-10 Thread Yaxun Liu via cfe-commits

Author: Yaxun (Sam) Liu
Date: 2022-01-10T17:38:02-05:00
New Revision: 98ab43a1d209875ce9cc39420d3e6af57ed0f5b2

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

LOG: [HIP] Fix device only linking for -fgpu-rdc

Currently when -fgpu-rdc is specified, HIP toolchain always does host linking 
even
if --cuda-device-only is specified.

This patch fixes that. Only device linking is performed when --cuda-device-only
is specified.

Reviewed by: Artem Belevich

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

Added: 


Modified: 
clang/lib/Driver/Driver.cpp
clang/test/Driver/hip-phases.hip
clang/test/Driver/hip-toolchain-rdc-separate.hip

Removed: 




diff  --git a/clang/lib/Driver/Driver.cpp b/clang/lib/Driver/Driver.cpp
index bb7ccf7dd97eb..ac8438bb45a6a 100644
--- a/clang/lib/Driver/Driver.cpp
+++ b/clang/lib/Driver/Driver.cpp
@@ -3110,7 +3110,7 @@ class OffloadingActionBuilder final {
 // We will pass the device action as a host dependence, so we don't
 // need to do anything else with them.
 CudaDeviceActions.clear();
-return ABRT_Success;
+return CompileDeviceOnly ? ABRT_Ignore_Host : ABRT_Success;
   }
 
   // By default, we produce an action for each device arch.
@@ -3143,6 +3143,7 @@ class OffloadingActionBuilder final {
   assert(DeviceLinkerInputs.size() == GpuArchList.size() &&
  "Linker inputs and GPU arch list sizes do not match.");
 
+  ActionList Actions;
   // Append a new link action for each device.
   unsigned I = 0;
   for (auto  : DeviceLinkerInputs) {
@@ -3154,22 +3155,29 @@ class OffloadingActionBuilder final {
 OffloadAction::DeviceDependences DeviceLinkDeps;
 DeviceLinkDeps.add(*DeviceLinkAction, *ToolChains[0],
 GpuArchList[I], AssociatedOffloadKind);
-AL.push_back(C.MakeAction(DeviceLinkDeps,
-DeviceLinkAction->getType()));
+Actions.push_back(C.MakeAction(
+DeviceLinkDeps, DeviceLinkAction->getType()));
 ++I;
   }
   DeviceLinkerInputs.clear();
 
   // Create a host object from all the device images by embedding them
-  // in a fat binary.
+  // in a fat binary for mixed host-device compilation. For device-only
+  // compilation, creates a fat binary.
   OffloadAction::DeviceDependences DDeps;
-  auto *TopDeviceLinkAction =
-  C.MakeAction(AL, types::TY_Object);
-  DDeps.add(*TopDeviceLinkAction, *ToolChains[0],
-  nullptr, AssociatedOffloadKind);
-
-  // Offload the host object to the host linker.
-  AL.push_back(C.MakeAction(DDeps, 
TopDeviceLinkAction->getType()));
+  if (!CompileDeviceOnly || !BundleOutput.hasValue() ||
+  BundleOutput.getValue()) {
+auto *TopDeviceLinkAction = C.MakeAction(
+Actions,
+CompileDeviceOnly ? types::TY_HIP_FATBIN : types::TY_Object);
+DDeps.add(*TopDeviceLinkAction, *ToolChains[0], nullptr,
+  AssociatedOffloadKind);
+// Offload the host object to the host linker.
+AL.push_back(
+C.MakeAction(DDeps, 
TopDeviceLinkAction->getType()));
+  } else {
+AL.append(Actions);
+  }
 }
 
 Action* appendLinkHostActions(ActionList ) override { return AL.back(); 
}
@@ -3556,15 +3564,18 @@ class OffloadingActionBuilder final {
 return false;
   }
 
-  Action* makeHostLinkAction() {
-// Build a list of device linking actions.
-ActionList DeviceAL;
+  void appendDeviceLinkActions(ActionList ) {
 for (DeviceActionBuilder *SB : SpecializedBuilders) {
   if (!SB->isValid())
 continue;
-  SB->appendLinkDeviceActions(DeviceAL);
+  SB->appendLinkDeviceActions(AL);
 }
+  }
 
+  Action *makeHostLinkAction() {
+// Build a list of device linking actions.
+ActionList DeviceAL;
+appendDeviceLinkActions(DeviceAL);
 if (DeviceAL.empty())
   return nullptr;
 
@@ -3893,6 +3904,13 @@ void Driver::BuildActions(Compilation , DerivedArgList 
,
   }
 
   // Add a link action if necessary.
+
+  if (LinkerInputs.empty()) {
+Arg *FinalPhaseArg;
+if (getFinalPhase(Args, ) == phases::Link)
+  OffloadBuilder.appendDeviceLinkActions(Actions);
+  }
+
   if (!LinkerInputs.empty()) {
 if (Action *Wrapper = OffloadBuilder.makeHostLinkAction())
   LinkerInputs.push_back(Wrapper);

diff  --git a/clang/test/Driver/hip-phases.hip 
b/clang/test/Driver/hip-phases.hip
index 623299b13dd0c..93bf635dab63f 100644
--- a/clang/test/Driver/hip-phases.hip
+++ b/clang/test/Driver/hip-phases.hip
@@ -311,22 +311,36 @@
 //
 // RUN: %clang -target x86_64-unknown-linux-gnu -ccc-print-phases --hip-link \
 // RUN: --cuda-gpu-arch=gfx803 --cuda-gpu-arch=gfx900 %T/obj1.o 

[PATCH] D116840: [HIP] Fix device only linking for -fgpu-rdc

2022-01-10 Thread Yaxun Liu 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 rG98ab43a1d209: [HIP] Fix device only linking for -fgpu-rdc 
(authored by yaxunl).
Herald added a project: clang.

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D116840

Files:
  clang/lib/Driver/Driver.cpp
  clang/test/Driver/hip-phases.hip
  clang/test/Driver/hip-toolchain-rdc-separate.hip

Index: clang/test/Driver/hip-toolchain-rdc-separate.hip
===
--- clang/test/Driver/hip-toolchain-rdc-separate.hip
+++ clang/test/Driver/hip-toolchain-rdc-separate.hip
@@ -88,47 +88,66 @@
 // RUN:   --cuda-gpu-arch=gfx803 --cuda-gpu-arch=gfx900 \
 // RUN:   -fuse-ld=lld -fgpu-rdc -nogpuinc \
 // RUN:   %T/a.o %T/b.o \
-// RUN: 2>&1 | FileCheck -check-prefix=LINK %s
+// RUN: 2>&1 | FileCheck -check-prefixes=LINK,LINK-HOST-UNBUNDLE,LLD-TMP,LINK-BUNDLE,LINK-EMBED %s
 
-// LINK: [[BUNDLER:".*clang-offload-bundler"]] "-type=o"
-// LINK-SAME: "-targets=host-x86_64-unknown-linux-gnu,hip-amdgcn-amd-amdhsa-gfx803,hip-amdgcn-amd-amdhsa-gfx900"
-// LINK-SAME: "-inputs=[[A_O:.*a.o]]" "-outputs=[[A_OBJ_HOST:.*o]],{{.*o}},{{.*o}}"
-// LINK: "-unbundle" "-allow-missing-bundles"
+// RUN: %clang --hip-link -### -target x86_64-linux-gnu \
+// RUN:   --cuda-gpu-arch=gfx803 --cuda-gpu-arch=gfx900 \
+// RUN:   -fuse-ld=lld -fgpu-rdc -nogpuinc \
+// RUN:   %T/a.o %T/b.o --cuda-device-only \
+// RUN: 2>&1 | FileCheck -check-prefixes=LINK,LLD-TMP,LINK-BUNDLE,LINK-NOEMBED %s
 
-// LINK: [[BUNDLER:".*clang-offload-bundler"]] "-type=o"
-// LINK-SAME: "-targets=host-x86_64-unknown-linux-gnu,hip-amdgcn-amd-amdhsa-gfx803,hip-amdgcn-amd-amdhsa-gfx900"
-// LINK-SAME: "-inputs=[[B_O:.*b.o]]" "-outputs=[[B_OBJ_HOST:.*o]],{{.*o}},{{.*o}}"
-// LINK: "-unbundle" "-allow-missing-bundles"
+// RUN: %clang --hip-link -### -target x86_64-linux-gnu \
+// RUN:   --cuda-gpu-arch=gfx803 --cuda-gpu-arch=gfx900 \
+// RUN:   -fuse-ld=lld -fgpu-rdc -nogpuinc \
+// RUN:   %T/a.o %T/b.o --cuda-device-only --no-gpu-bundle-output \
+// RUN: 2>&1 | FileCheck -check-prefixes=LINK,LLD-FIN,LINK-NOBUNDLE,LINK-NOEMBED %s
+
+// LINK-HOST-UNBUNDLE: [[BUNDLER:".*clang-offload-bundler"]] "-type=o"
+// LINK-HOST-UNBUNDLE-SAME: "-targets=host-x86_64-unknown-linux-gnu,hip-amdgcn-amd-amdhsa-gfx803,hip-amdgcn-amd-amdhsa-gfx900"
+// LINK-HOST-UNBUNDLE-SAME: "-inputs=[[A_O:.*a.o]]" "-outputs=[[A_OBJ_HOST:.*o]],{{.*o}},{{.*o}}"
+// LINK-HOST-UNBUNDLE: "-unbundle" "-allow-missing-bundles"
+
+// LINK-HOST-UNBUNDLE: [[BUNDLER:".*clang-offload-bundler"]] "-type=o"
+// LINK-HOST-UNBUNDLE-SAME: "-targets=host-x86_64-unknown-linux-gnu,hip-amdgcn-amd-amdhsa-gfx803,hip-amdgcn-amd-amdhsa-gfx900"
+// LINK-HOST-UNBUNDLE-SAME: "-inputs=[[B_O:.*b.o]]" "-outputs=[[B_OBJ_HOST:.*o]],{{.*o}},{{.*o}}"
+// LINK-HOST-UNBUNDLE: "-unbundle" "-allow-missing-bundles"
 
 // LINK: [[BUNDLER:".*clang-offload-bundler"]] "-type=o"
 // LINK-SAME: "-targets=host-x86_64-unknown-linux-gnu,hip-amdgcn-amd-amdhsa-gfx803,hip-amdgcn-amd-amdhsa-gfx900"
-// LINK-SAME: "-inputs=[[A_O]]" "-outputs={{.*o}},[[A_BC1:.*o]],[[A_BC2:.*o]]"
-// LINK: "-unbundle" "-allow-missing-bundles"
+// LINK-SAME: "-inputs=[[A_O:.*a.o]]" "-outputs={{.*o}},[[A_BC1:.*o]],[[A_BC2:.*o]]"
+// LINK-SAME: "-unbundle" "-allow-missing-bundles"
 
 // LINK: [[BUNDLER:".*clang-offload-bundler"]] "-type=o"
 // LINK-SAME: "-targets=host-x86_64-unknown-linux-gnu,hip-amdgcn-amd-amdhsa-gfx803,hip-amdgcn-amd-amdhsa-gfx900"
-// LINK-SAME: "-inputs=[[B_O]]" "-outputs={{.*o}},[[B_BC1:.*o]],[[B_BC2:.*o]]"
-// LINK: "-unbundle" "-allow-missing-bundles"
+// LINK-SAME: "-inputs=[[B_O:.*b.o]]" "-outputs={{.*o}},[[B_BC1:.*o]],[[B_BC2:.*o]]"
+// LINK-SAME: "-unbundle" "-allow-missing-bundles"
 
 // LINK-NOT: "*.llvm-link"
 // LINK-NOT: ".*opt"
 // LINK-NOT: ".*llc"
 // LINK: {{".*lld.*"}} {{.*}} "-plugin-opt=-amdgpu-internalize-symbols"
-// LINK: "-plugin-opt=mcpu=gfx803"
-// LINK-SAME: "-o" "[[IMG_DEV1:.*.out]]" "[[A_BC1]]" "[[B_BC1]]"
+// LINK-SAME: "-plugin-opt=mcpu=gfx803"
+// LLD-TMP-SAME: "-o" "[[IMG_DEV1:.*.out]]"
+// LLD-FIN-SAME: "-o" "[[IMG_DEV1:a.out-.*gfx803]]"
+// LINK-SAME "[[A_BC1]]" "[[B_BC1]]"
 
 // LINK-NOT: "*.llvm-link"
 // LINK-NOT: ".*opt"
 // LINK-NOT: ".*llc"
 // LINK: {{".*lld.*"}} {{.*}} "-plugin-opt=-amdgpu-internalize-symbols"
-// LINK: "-plugin-opt=mcpu=gfx900"
-// LINK-SAME: "-o" "[[IMG_DEV2:.*.out]]" "[[A_BC2]]" "[[B_BC2]]"
-
-// LINK: [[BUNDLER:".*clang-offload-bundler"]] "-type=o"
-// LINK-SAME: "-targets={{.*}},hipv4-amdgcn-amd-amdhsa--gfx803,hipv4-amdgcn-amd-amdhsa--gfx900"
-// LINK-SAME: "-inputs={{.*}},[[IMG_DEV1]],[[IMG_DEV2]]" "-outputs=[[BUNDLE:.*hipfb]]"
-
-// LINK: {{".*llvm-mc.*"}} "-o" "[[OBJBUNDLE:.*o]]" "{{.*}}.mcin" "--filetype=obj"
-
-// LINK: [[LD:".*ld.*"]] {{.*}} "-o" "a.out" {{.*}} "[[A_OBJ_HOST]]"
-// LINK-SAME: "[[B_OBJ_HOST]]" 

[PATCH] D116503: [clang] Add --start-no-unused-arguments/--end-no-unused-arguments to silence some unused argument warnings

2022-01-10 Thread Fangrui Song via Phabricator via cfe-commits
MaskRay accepted this revision.
MaskRay added a comment.

In D116503#3231138 , @mstorsjo wrote:

> In D116503#3223094 , @MaskRay wrote:
>
>> But make sure to wait a bit to see what others think.
>
> Do you think it's ok to go ahead and land this change now, or should I wait a 
> bit more? (I'd like to have it landed with enough margin before the 14.x 
> branch so that it has time to settle before that.)

The wait time has been sufficiently long to me:) Go head.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D116503

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


[PATCH] D116764: [clang][OpenMP5.1] Initial parsing/sema for 'indirect' clause

2022-01-10 Thread Jennifer Yu via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG140a6b1e5c68: [clang][OpenMP5.1] Initial parsing/sema for 
indirect clause (authored by jyu2).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D116764

Files:
  clang/include/clang/Basic/Attr.td
  clang/include/clang/Basic/DiagnosticParseKinds.td
  clang/include/clang/Parse/Parser.h
  clang/include/clang/Sema/Sema.h
  clang/lib/AST/AttrImpl.cpp
  clang/lib/CodeGen/CGStmtOpenMP.cpp
  clang/lib/Parse/ParseOpenMP.cpp
  clang/lib/Sema/SemaOpenMP.cpp
  clang/lib/Serialization/ASTReaderDecl.cpp
  clang/test/OpenMP/declare_target_ast_print.cpp
  clang/test/OpenMP/declare_target_messages.cpp
  flang/lib/Semantics/check-omp-structure.cpp
  llvm/include/llvm/Frontend/OpenMP/OMP.td

Index: llvm/include/llvm/Frontend/OpenMP/OMP.td
===
--- llvm/include/llvm/Frontend/OpenMP/OMP.td
+++ llvm/include/llvm/Frontend/OpenMP/OMP.td
@@ -358,6 +358,7 @@
 def OMPC_Link : Clause<"link"> {
   let flangClass = "OmpObjectList";
 }
+def OMPC_Indirect : Clause<"indirect"> {}
 def OMPC_Inbranch : Clause<"inbranch"> {}
 def OMPC_Notinbranch : Clause<"notinbranch"> {}
 def OMPC_Filter : Clause<"filter"> {
@@ -973,12 +974,14 @@
 VersionedClause,
 VersionedClause,
 VersionedClause,
+VersionedClause
   ];
 }
 def OMP_DeclareTarget : Directive<"declare target"> {
   let allowedClauses = [
 VersionedClause,
-VersionedClause
+VersionedClause,
+VersionedClause
   ];
 }
 def OMP_EndDeclareTarget : Directive<"end declare target"> {}
Index: flang/lib/Semantics/check-omp-structure.cpp
===
--- flang/lib/Semantics/check-omp-structure.cpp
+++ flang/lib/Semantics/check-omp-structure.cpp
@@ -1528,6 +1528,7 @@
 CHECK_SIMPLE_CLAUSE(Inbranch, OMPC_inbranch)
 CHECK_SIMPLE_CLAUSE(IsDevicePtr, OMPC_is_device_ptr)
 CHECK_SIMPLE_CLAUSE(Link, OMPC_link)
+CHECK_SIMPLE_CLAUSE(Indirect, OMPC_indirect)
 CHECK_SIMPLE_CLAUSE(Mergeable, OMPC_mergeable)
 CHECK_SIMPLE_CLAUSE(Nogroup, OMPC_nogroup)
 CHECK_SIMPLE_CLAUSE(Notinbranch, OMPC_notinbranch)
Index: clang/test/OpenMP/declare_target_messages.cpp
===
--- clang/test/OpenMP/declare_target_messages.cpp
+++ clang/test/OpenMP/declare_target_messages.cpp
@@ -5,11 +5,13 @@
 // RUN: %clang_cc1 -triple x86_64-apple-macos10.7.0 -verify=expected,omp5,host5 -fopenmp-simd -fopenmp-targets=x86_64-apple-macos10.7.0 -fnoopenmp-use-tls -ferror-limit 100 -o - %s
 // RUN: %clang_cc1 -triple x86_64-apple-macos10.7.0 -verify=expected,omp5,host5 -fopenmp-simd -fopenmp-is-device -fopenmp-targets=x86_64-apple-macos10.7.0 -fnoopenmp-use-tls -ferror-limit 100 -o - %s
 // RUN: %clang_cc1 -triple x86_64-apple-macos10.7.0 -verify=expected,omp45 -fopenmp-version=45 -fopenmp-simd -fnoopenmp-use-tls -ferror-limit 100 -o - %s
+// RUN: %clang_cc1 -triple x86_64-apple-macos10.7.0 -verify=expected,omp51 -fopenmp -fopenmp-version=51 -fnoopenmp-use-tls -ferror-limit 100 -o - %s
+// RUN: %clang_cc1 -triple x86_64-apple-macos10.7.0 -verify=expected,omp51 -fopenmp-version=51 -fopenmp-simd -fnoopenmp-use-tls -ferror-limit 100 -o - %s
 
 // RUN: %clang_cc1 -triple x86_64-apple-macos10.7.0 -verify=expected,omp5 -fopenmp -fnoopenmp-use-tls -ferror-limit 100 -o - %s
 #pragma omp end declare target // expected-error {{unexpected OpenMP directive '#pragma omp end declare target'}}
 
-int a, b, z; // omp5-error {{variable captured in declare target region must appear in a to clause}}
+int a, b, z; // omp5-error {{variable captured in declare target region must appear in a to clause}} // omp51-error {{variable captured in declare target region must appear in a to clause}}
 __thread int t; // expected-note {{defined as threadprivate or thread local}}
 
 #pragma omp declare target . // expected-error {{expected '(' after 'declare target'}}
@@ -18,7 +20,7 @@
 void f();
 #pragma omp end declare target shared(a) // expected-warning {{extra tokens at the end of '#pragma omp end declare target' are ignored}}
 
-#pragma omp declare target map(a) // expected-error {{expected at least one 'to' or 'link' clause}} omp45-error {{unexpected 'map' clause, only 'to' or 'link' clauses expected}} omp5-error {{unexpected 'map' clause, only 'to', 'link' or 'device_type' clauses expected}}
+#pragma omp declare target map(a) // omp45-error {{expected at least one 'to' or 'link' clause}} omp5-error {{expected at least one 'to' or 'link' clause}} omp51-error {{expected at least one 'to', 'link' or 'indirect' clause}} omp45-error {{unexpected 'map' clause, only 'to' or 'link' clauses expected}} omp5-error {{unexpected 'map' clause, only 'to', 'link' or 'device_type' clauses expected}} omp51-error {{unexpected 'map' clause, only 'to', 'link', 'device_type' or 'indirect' clauses expected}}
 
 

[clang] 140a6b1 - [clang][OpenMP5.1] Initial parsing/sema for 'indirect' clause

2022-01-10 Thread Jennifer Yu via cfe-commits

Author: Jennifer Yu
Date: 2022-01-10T16:58:56-08:00
New Revision: 140a6b1e5c6857617a83f66680b4829ff2b08d82

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

LOG: [clang][OpenMP5.1] Initial parsing/sema for 'indirect' clause

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

Added: 


Modified: 
clang/include/clang/Basic/Attr.td
clang/include/clang/Basic/DiagnosticParseKinds.td
clang/include/clang/Parse/Parser.h
clang/include/clang/Sema/Sema.h
clang/lib/AST/AttrImpl.cpp
clang/lib/CodeGen/CGStmtOpenMP.cpp
clang/lib/Parse/ParseOpenMP.cpp
clang/lib/Sema/SemaOpenMP.cpp
clang/lib/Serialization/ASTReaderDecl.cpp
clang/test/OpenMP/declare_target_ast_print.cpp
clang/test/OpenMP/declare_target_messages.cpp
flang/lib/Semantics/check-omp-structure.cpp
llvm/include/llvm/Frontend/OpenMP/OMP.td

Removed: 




diff  --git a/clang/include/clang/Basic/Attr.td 
b/clang/include/clang/Basic/Attr.td
index 10c5c7f1b879a..b071ebb4d576b 100644
--- a/clang/include/clang/Basic/Attr.td
+++ b/clang/include/clang/Basic/Attr.td
@@ -3686,6 +3686,8 @@ def OMPDeclareTargetDecl : InheritableAttr {
 EnumArgument<"DevType", "DevTypeTy",
  [ "host", "nohost", "any" ],
  [ "DT_Host", "DT_NoHost", "DT_Any" ]>,
+ExprArgument<"IndirectExpr">,
+BoolArgument<"Indirect">,
 UnsignedArgument<"Level">
   ];
   let AdditionalMembers = [{

diff  --git a/clang/include/clang/Basic/DiagnosticParseKinds.td 
b/clang/include/clang/Basic/DiagnosticParseKinds.td
index 9dc036c03faa8..193dff8b9c8f6 100644
--- a/clang/include/clang/Basic/DiagnosticParseKinds.td
+++ b/clang/include/clang/Basic/DiagnosticParseKinds.td
@@ -1344,15 +1344,17 @@ def warn_omp_unknown_assumption_clause_without_args
 def note_omp_assumption_clause_continue_here
 : Note<"the ignored tokens spans until here">;
 def err_omp_declare_target_unexpected_clause: Error<
-  "unexpected '%0' clause, only %select{'device_type'|'to' or 'link'|'to', 
'link' or 'device_type'}1 clauses expected">;
+  "unexpected '%0' clause, only %select{'device_type'|'to' or 'link'|'to', 
'link' or 'device_type'|'device_type', 'indirect'|'to', 'link', 'device_type' 
or 'indirect'}1 clauses expected">;
 def err_omp_begin_declare_target_unexpected_implicit_to_clause: Error<
   "unexpected '(', only 'to', 'link' or 'device_type' clauses expected for 
'begin declare target' directive">;
 def err_omp_declare_target_unexpected_clause_after_implicit_to: Error<
   "unexpected clause after an implicit 'to' clause">;
 def err_omp_declare_target_missing_to_or_link_clause: Error<
-  "expected at least one 'to' or 'link' clause">;
+  "expected at least one %select{'to' or 'link'|'to', 'link' or 'indirect'}0 
clause">;
 def err_omp_declare_target_multiple : Error<
   "%0 appears multiple times in clauses on the same declare target directive">;
+def err_omp_declare_target_indirect_device_type: Error<
+  "only 'device_type(any)' clause is allowed with indirect clause">;
 def err_omp_expected_clause: Error<
   "expected at least one clause on '#pragma omp %0' directive">;
 def err_omp_mapper_illegal_identifier : Error<

diff  --git a/clang/include/clang/Parse/Parser.h 
b/clang/include/clang/Parse/Parser.h
index a98ad78401f02..74935c8900178 100644
--- a/clang/include/clang/Parse/Parser.h
+++ b/clang/include/clang/Parse/Parser.h
@@ -3316,6 +3316,11 @@ class Parser : public CodeCompletionHandler {
   /// nullptr.
   ///
   OMPClause *ParseOpenMPSimpleClause(OpenMPClauseKind Kind, bool ParseOnly);
+  /// Parses indirect clause
+  /// \param ParseOnly true to skip the clause's semantic actions and return
+  // false;
+  bool ParseOpenMPIndirectClause(Sema::DeclareTargetContextInfo ,
+ bool ParseOnly);
   /// Parses clause with a single expression and an additional argument
   /// of a kind \a Kind.
   ///

diff  --git a/clang/include/clang/Sema/Sema.h b/clang/include/clang/Sema/Sema.h
index 9b6d9d20ca431..f1e90356c8367 100644
--- a/clang/include/clang/Sema/Sema.h
+++ b/clang/include/clang/Sema/Sema.h
@@ -10333,6 +10333,9 @@ class Sema final {
 /// The directive kind, `begin declare target` or `declare target`.
 OpenMPDirectiveKind Kind;
 
+/// The directive with indirect clause.
+Optional Indirect;
+
 /// The directive location.
 SourceLocation Loc;
 
@@ -10639,7 +10642,7 @@ class Sema final {
   /// Called on correct id-expression from the '#pragma omp declare target'.
   void ActOnOpenMPDeclareTargetName(NamedDecl *ND, SourceLocation Loc,
 OMPDeclareTargetDeclAttr::MapTypeTy MT,
-OMPDeclareTargetDeclAttr::DevTypeTy DT);
+DeclareTargetContextInfo 

[PATCH] D111566: [SYCL] Fix function pointer address space

2022-01-10 Thread Elizabeth Andrews via Phabricator via cfe-commits
eandrews updated this revision to Diff 398784.
eandrews added a comment.

Implement review comments - add a comment + remove unnecessary code


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

https://reviews.llvm.org/D111566

Files:
  clang/include/clang/AST/ASTContext.h
  clang/lib/AST/ASTContext.cpp
  clang/lib/CodeGen/CodeGenTypes.cpp
  clang/test/CodeGenSYCL/functionptr-addressspace.cpp

Index: clang/test/CodeGenSYCL/functionptr-addressspace.cpp
===
--- /dev/null
+++ clang/test/CodeGenSYCL/functionptr-addressspace.cpp
@@ -0,0 +1,25 @@
+// RUN: %clang_cc1 -fsycl-is-device -emit-llvm -triple spir64 -verify -emit-llvm %s -o - | FileCheck %s
+
+// expected-no-diagnostics
+
+template 
+__attribute__((sycl_kernel)) void kernel_single_task(const Func ) {
+  kernelFunc();
+}
+
+// CHECK: define dso_local spir_func{{.*}}invoke_function{{.*}}(i32 ()* %fptr, i32 addrspace(4)* %ptr)
+void invoke_function(int (*fptr)(), int *ptr) {}
+
+int f() { return 0; }
+
+int main() {
+  kernel_single_task([=]() {
+int (*p)() = f;
+int ()() = *p;
+int a = 10;
+invoke_function(p, );
+invoke_function(r, );
+invoke_function(f, );
+  });
+  return 0;
+}
Index: clang/lib/CodeGen/CodeGenTypes.cpp
===
--- clang/lib/CodeGen/CodeGenTypes.cpp
+++ clang/lib/CodeGen/CodeGenTypes.cpp
@@ -643,11 +643,7 @@
 llvm::Type *PointeeType = ConvertTypeForMem(ETy);
 if (PointeeType->isVoidTy())
   PointeeType = llvm::Type::getInt8Ty(getLLVMContext());
-
-unsigned AS = PointeeType->isFunctionTy()
-  ? getDataLayout().getProgramAddressSpace()
-  : Context.getTargetAddressSpace(ETy);
-
+unsigned AS = Context.getTargetAddressSpace(ETy);
 ResultType = llvm::PointerType::get(PointeeType, AS);
 break;
   }
@@ -748,7 +744,13 @@
 llvm::Type *PointeeType = CGM.getLangOpts().OpenCL
   ? CGM.getGenericBlockLiteralType()
   : ConvertTypeForMem(FTy);
-unsigned AS = Context.getTargetAddressSpace(FTy);
+// Block pointers lower to function type. For function type,
+// getTargetAddressSpace() returns default address space for
+// function pointer i.e. program address space. Therefore, for block
+// pointers, it is important to pass qualifiers when calling
+// getTargetAddressSpace(), to ensure that we get the address space
+// for data pointers and not function pointers.
+unsigned AS = Context.getTargetAddressSpace(FTy.getQualifiers());
 ResultType = llvm::PointerType::get(PointeeType, AS);
 break;
   }
Index: clang/lib/AST/ASTContext.cpp
===
--- clang/lib/AST/ASTContext.cpp
+++ clang/lib/AST/ASTContext.cpp
@@ -80,6 +80,7 @@
 #include "llvm/ADT/StringExtras.h"
 #include "llvm/ADT/StringRef.h"
 #include "llvm/ADT/Triple.h"
+#include "llvm/IR/DataLayout.h"
 #include "llvm/Support/Capacity.h"
 #include "llvm/Support/Casting.h"
 #include "llvm/Support/Compiler.h"
@@ -11488,6 +11489,17 @@
   return getTargetInfo().getNullPointerValue(AS);
 }
 
+unsigned ASTContext::getTargetAddressSpace(QualType T) const {
+  return T->isFunctionType()
+ ? llvm::DataLayout(getTargetInfo().getDataLayoutString())
+   .getProgramAddressSpace()
+ : getTargetAddressSpace(T.getQualifiers());
+}
+
+unsigned ASTContext::getTargetAddressSpace(Qualifiers Q) const {
+  return getTargetAddressSpace(Q.getAddressSpace());
+}
+
 unsigned ASTContext::getTargetAddressSpace(LangAS AS) const {
   if (isTargetAddressSpace(AS))
 return toTargetAddressSpace(AS);
Index: clang/include/clang/AST/ASTContext.h
===
--- clang/include/clang/AST/ASTContext.h
+++ clang/include/clang/AST/ASTContext.h
@@ -2709,13 +2709,9 @@
   QualType getFloatingTypeOfSizeWithinDomain(QualType typeSize,
  QualType typeDomain) const;
 
-  unsigned getTargetAddressSpace(QualType T) const {
-return getTargetAddressSpace(T.getQualifiers());
-  }
+  unsigned getTargetAddressSpace(QualType T) const;
 
-  unsigned getTargetAddressSpace(Qualifiers Q) const {
-return getTargetAddressSpace(Q.getAddressSpace());
-  }
+  unsigned getTargetAddressSpace(Qualifiers Q) const;
 
   unsigned getTargetAddressSpace(LangAS AS) const;
 
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D111566: [SYCL] Fix function pointer address space

2022-01-10 Thread Elizabeth Andrews via Phabricator via cfe-commits
eandrews updated this revision to Diff 398723.
eandrews added a comment.

Implemented review comment to move logic into function 
(`getTargetAddressSpace`) as opposed to call site.


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

https://reviews.llvm.org/D111566

Files:
  clang/include/clang/AST/ASTContext.h
  clang/lib/AST/ASTContext.cpp
  clang/lib/CodeGen/CodeGenTypes.cpp
  clang/test/CodeGenSYCL/functionptr-addressspace.cpp

Index: clang/test/CodeGenSYCL/functionptr-addressspace.cpp
===
--- /dev/null
+++ clang/test/CodeGenSYCL/functionptr-addressspace.cpp
@@ -0,0 +1,25 @@
+// RUN: %clang_cc1 -fsycl-is-device -emit-llvm -triple spir64 -verify -emit-llvm %s -o - | FileCheck %s
+
+// expected-no-diagnostics
+
+template 
+__attribute__((sycl_kernel)) void kernel_single_task(const Func ) {
+  kernelFunc();
+}
+
+// CHECK: define dso_local spir_func{{.*}}invoke_function{{.*}}(i32 ()* %fptr, i32 addrspace(4)* %ptr)
+void invoke_function(int (*fptr)(), int *ptr) {}
+
+int f() { return 0; }
+
+int main() {
+  kernel_single_task([=]() {
+int (*p)() = f;
+int ()() = *p;
+int a = 10;
+invoke_function(p, );
+invoke_function(r, );
+invoke_function(f, );
+  });
+  return 0;
+}
Index: clang/lib/CodeGen/CodeGenTypes.cpp
===
--- clang/lib/CodeGen/CodeGenTypes.cpp
+++ clang/lib/CodeGen/CodeGenTypes.cpp
@@ -643,11 +643,7 @@
 llvm::Type *PointeeType = ConvertTypeForMem(ETy);
 if (PointeeType->isVoidTy())
   PointeeType = llvm::Type::getInt8Ty(getLLVMContext());
-
-unsigned AS = PointeeType->isFunctionTy()
-  ? getDataLayout().getProgramAddressSpace()
-  : Context.getTargetAddressSpace(ETy);
-
+unsigned AS = Context.getTargetAddressSpace(ETy);
 ResultType = llvm::PointerType::get(PointeeType, AS);
 break;
   }
@@ -748,7 +744,7 @@
 llvm::Type *PointeeType = CGM.getLangOpts().OpenCL
   ? CGM.getGenericBlockLiteralType()
   : ConvertTypeForMem(FTy);
-unsigned AS = Context.getTargetAddressSpace(FTy);
+unsigned AS = Context.getTargetAddressSpace(FTy.getQualifiers());
 ResultType = llvm::PointerType::get(PointeeType, AS);
 break;
   }
Index: clang/lib/AST/ASTContext.cpp
===
--- clang/lib/AST/ASTContext.cpp
+++ clang/lib/AST/ASTContext.cpp
@@ -80,6 +80,7 @@
 #include "llvm/ADT/StringExtras.h"
 #include "llvm/ADT/StringRef.h"
 #include "llvm/ADT/Triple.h"
+#include "llvm/IR/DataLayout.h"
 #include "llvm/Support/Capacity.h"
 #include "llvm/Support/Casting.h"
 #include "llvm/Support/Compiler.h"
@@ -11488,6 +11489,18 @@
   return getTargetInfo().getNullPointerValue(AS);
 }
 
+unsigned ASTContext::getTargetAddressSpace(QualType T) const {
+  const Type *TypePtr = T.getTypePtr();
+  return TypePtr->isFunctionType()
+ ? llvm::DataLayout(getTargetInfo().getDataLayoutString())
+   .getProgramAddressSpace()
+ : getTargetAddressSpace(T.getQualifiers());
+}
+
+unsigned ASTContext::getTargetAddressSpace(Qualifiers Q) const {
+  return getTargetAddressSpace(Q.getAddressSpace());
+}
+
 unsigned ASTContext::getTargetAddressSpace(LangAS AS) const {
   if (isTargetAddressSpace(AS))
 return toTargetAddressSpace(AS);
Index: clang/include/clang/AST/ASTContext.h
===
--- clang/include/clang/AST/ASTContext.h
+++ clang/include/clang/AST/ASTContext.h
@@ -2709,13 +2709,9 @@
   QualType getFloatingTypeOfSizeWithinDomain(QualType typeSize,
  QualType typeDomain) const;
 
-  unsigned getTargetAddressSpace(QualType T) const {
-return getTargetAddressSpace(T.getQualifiers());
-  }
+  unsigned getTargetAddressSpace(QualType T) const;
 
-  unsigned getTargetAddressSpace(Qualifiers Q) const {
-return getTargetAddressSpace(Q.getAddressSpace());
-  }
+  unsigned getTargetAddressSpace(Qualifiers Q) const;
 
   unsigned getTargetAddressSpace(LangAS AS) const;
 
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D116935: [IRBuilder] Introduce folder using inst-simplify, use for Or fold.

2022-01-10 Thread Craig Topper via Phabricator via cfe-commits
craig.topper added a comment.

In D116935#3232584 , @fhahn wrote:

> Rebased and made sure comments are consistent between different folders.
>
> In D116935#3232227 , @craig.topper 
> wrote:
>
>> In D116935#3232203 , @lebedev.ri 
>> wrote:
>>
>>> In D116935#3232126 , 
>>> @craig.topper wrote:
>>>
 If I remember correctly, the Or and And folds for 0 and all 1s are there 
 to optimize bitfield codegen for the frontend. Are we losing that 
 optimization if this patch goes in before switching clang to 
 InstSimplifyFolder?
>>>
>>> True, but why is that optimization there in the first place?
>>> Presumably it shouldn't matter nowadays.
>>
>> Probably for -O0 where there is no optimizer,
>>
>>   commit 0fc4311f0ea4034b4bad1c82c652dc04bb763cda
>>   Author: Chris Lattner 
>>   Date:   Wed Nov 4 05:00:12 2009 +
>>   
>>   make IRBuilder zap "X|0" and "X&-1" when building IR, this happens
>>   during bitfield codegen and slows down -O0 compile times by making
>>   useless IR.  rdar://7362516
>>   
>>   llvm-svn: 86006
>
> I collected numbers using the compile-time tracker and the data seems to 
> indicate this is not an issue any longer, there are no notable changes for 
> any config: 
> http://llvm-compile-time-tracker.com/compare.php?from=baa5b54d43419b5d4a1ec36f3788c36d52187e11=e22fc3bb9b024699fdfd12b89c68205565215b27=instructions

Do the programs in compile-time tracker make much use of bitfields? Is there 
any indication in rdar://7362516 what program needed this? It looks like 
assigning a bitfield to 0 is enough to generate an or with 0 that survives 
through fast isel at -O0 on X86. But a few assignments to 0 wouldn't make for a 
huge problem, so I imagine there must have been something pathological about 
some program.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D116935

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


[PATCH] D116987: [clang][utils] Remove StringRef lldb summary provider

2022-01-10 Thread Dave Lee via Phabricator via cfe-commits
kastiglione created this revision.
kastiglione added reviewers: akyrtzi, jingham.
Herald added subscribers: usaxena95, arphaman.
kastiglione requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

Remove the `StringRef` summary provider in favor of the implementation in
`llvm/utils/lldbDataFormatters.py`.

This implementation was resulting in errors in some cases.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D116987

Files:
  clang/utils/ClangDataFormat.py


Index: clang/utils/ClangDataFormat.py
===
--- clang/utils/ClangDataFormat.py
+++ clang/utils/ClangDataFormat.py
@@ -24,7 +24,6 @@
 def __lldb_init_module(debugger, internal_dict):
debugger.HandleCommand("type summary add -F 
ClangDataFormat.SourceLocation_summary clang::SourceLocation")
debugger.HandleCommand("type summary add -F 
ClangDataFormat.QualType_summary clang::QualType")
-   debugger.HandleCommand("type summary add -F 
ClangDataFormat.StringRef_summary llvm::StringRef")
 
 def SourceLocation_summary(srcloc, internal_dict):
return SourceLocation(srcloc).summary()
@@ -32,9 +31,6 @@
 def QualType_summary(qualty, internal_dict):
return QualType(qualty).summary()
 
-def StringRef_summary(strref, internal_dict):
-   return StringRef(strref).summary()
-
 class SourceLocation(object):
def __init__(self, srcloc):
self.srcloc = srcloc
@@ -79,23 +75,6 @@
return ""
return desc
 
-class StringRef(object):
-   def __init__(self, strref):
-   self.strref = strref
-   self.Data_value = strref.GetChildAtIndex(0)
-   self.Length = strref.GetChildAtIndex(1).GetValueAsUnsigned()
-
-   def summary(self):
-   if self.Length == 0:
-   return '""'
-   data = self.Data_value.GetPointeeData(0, self.Length)
-   error = lldb.SBError()
-   string = data.ReadRawData(error, 0, data.GetByteSize())
-   if error.Fail():
-   return None
-   return '"%s"' % string
-
-
 # Key is a (function address, type name) tuple, value is the expression path 
for
 # an object with such a type name from inside that function.
 FramePathMapCache = {}


Index: clang/utils/ClangDataFormat.py
===
--- clang/utils/ClangDataFormat.py
+++ clang/utils/ClangDataFormat.py
@@ -24,7 +24,6 @@
 def __lldb_init_module(debugger, internal_dict):
 	debugger.HandleCommand("type summary add -F ClangDataFormat.SourceLocation_summary clang::SourceLocation")
 	debugger.HandleCommand("type summary add -F ClangDataFormat.QualType_summary clang::QualType")
-	debugger.HandleCommand("type summary add -F ClangDataFormat.StringRef_summary llvm::StringRef")
 
 def SourceLocation_summary(srcloc, internal_dict):
 	return SourceLocation(srcloc).summary()
@@ -32,9 +31,6 @@
 def QualType_summary(qualty, internal_dict):
 	return QualType(qualty).summary()
 
-def StringRef_summary(strref, internal_dict):
-	return StringRef(strref).summary()
-
 class SourceLocation(object):
 	def __init__(self, srcloc):
 		self.srcloc = srcloc
@@ -79,23 +75,6 @@
 			return ""
 		return desc
 
-class StringRef(object):
-	def __init__(self, strref):
-		self.strref = strref
-		self.Data_value = strref.GetChildAtIndex(0)
-		self.Length = strref.GetChildAtIndex(1).GetValueAsUnsigned()
-
-	def summary(self):
-		if self.Length == 0:
-			return '""'
-		data = self.Data_value.GetPointeeData(0, self.Length)
-		error = lldb.SBError()
-		string = data.ReadRawData(error, 0, data.GetByteSize())
-		if error.Fail():
-			return None
-		return '"%s"' % string
-
-
 # Key is a (function address, type name) tuple, value is the expression path for
 # an object with such a type name from inside that function.
 FramePathMapCache = {}
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D115440: Provide __builtin_alloca*_uninitialized variants

2022-01-10 Thread John McCall via Phabricator via cfe-commits
rjmccall added a comment.

Yes, this LGTM implementation-wise.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D115440

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


[PATCH] D116833: [clang] Introduce support for disabling warnings in system macros

2022-01-10 Thread Eli Friedman via Phabricator via cfe-commits
efriedma added a comment.

I'll just note here that doing this globally is likely to have unexpected 
results... consider, for example:

  #include 
  void f() { long x = M_PI; }

Currently, the implicit conversion warning points into math.h.

That said, I don't see any problem with the current implementation.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D116833

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


[PATCH] D116412: [Clang][Sema] Fix attribute mismatch warning for ObjC class properties

2022-01-10 Thread Alex Lorenz via Phabricator via cfe-commits
arphaman accepted this revision.
arphaman added a comment.
This revision is now accepted and ready to land.

LGTM, Cheers!


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D116412

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


[PATCH] D116412: [Clang][Sema] Fix attribute mismatch warning for ObjC class properties

2022-01-10 Thread Egor Zhdan via Phabricator via cfe-commits
egorzhdan updated this revision to Diff 398753.
egorzhdan added a comment.

Fix clang-format warning


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D116412

Files:
  clang/include/clang/AST/DeclObjC.h
  clang/lib/AST/DeclObjC.cpp
  clang/lib/Sema/SemaObjCProperty.cpp
  clang/test/SemaObjC/class-property-inheritance.m

Index: clang/test/SemaObjC/class-property-inheritance.m
===
--- /dev/null
+++ clang/test/SemaObjC/class-property-inheritance.m
@@ -0,0 +1,39 @@
+// RUN: %clang_cc1 -fsyntax-only -verify %s
+
+@class MyObject;
+
+
+@interface TopClassWithClassProperty0
+@property(nullable, readonly, strong, class) MyObject *foo;
+@end
+
+@interface SubClassWithClassProperty0 : TopClassWithClassProperty0
+@property(nonnull, readonly, copy, class) MyObject *foo; // expected-warning {{'copy' attribute on property 'foo' does not match the property inherited from 'TopClassWithClassProperty0'}}
+@end
+
+
+
+@interface TopClassWithInstanceProperty1
+@property(nullable, readonly, strong) MyObject *foo;
+@end
+
+@interface ClassWithClassProperty1 : TopClassWithInstanceProperty1
+@property(nonnull, readonly, copy, class) MyObject *foo; // no-warning
+@end
+
+@interface SubClassWithInstanceProperty1 : ClassWithClassProperty1
+@property(nullable, readonly, copy) MyObject *foo; // expected-warning {{'copy' attribute on property 'foo' does not match the property inherited from 'TopClassWithInstanceProperty1'}}
+@end
+
+
+@interface TopClassWithClassProperty2
+@property(nullable, readonly, strong, class) MyObject *foo;
+@end
+
+@interface ClassWithInstanceProperty2 : TopClassWithClassProperty2
+@property(nonnull, readonly, copy) MyObject *foo; // no-warning
+@end
+
+@interface SubClassWithClassProperty2 : ClassWithInstanceProperty2
+@property(nonnull, readonly, copy, class) MyObject *foo; // expected-warning {{'copy' attribute on property 'foo' does not match the property inherited from 'TopClassWithClassProperty2'}}
+@end
Index: clang/lib/Sema/SemaObjCProperty.cpp
===
--- clang/lib/Sema/SemaObjCProperty.cpp
+++ clang/lib/Sema/SemaObjCProperty.cpp
@@ -112,8 +112,8 @@
 return;
 
   // Look for a property with the same name.
-  if (ObjCPropertyDecl *ProtoProp =
-  Proto->lookup(Prop->getDeclName()).find_first()) {
+  if (ObjCPropertyDecl *ProtoProp = Proto->getProperty(
+  Prop->getIdentifier(), Prop->isInstanceProperty())) {
 S.DiagnosePropertyMismatch(Prop, ProtoProp, Proto->getIdentifier(), true);
 return;
   }
@@ -231,8 +231,8 @@
 bool FoundInSuper = false;
 ObjCInterfaceDecl *CurrentInterfaceDecl = IFace;
 while (ObjCInterfaceDecl *Super = CurrentInterfaceDecl->getSuperClass()) {
-  if (ObjCPropertyDecl *SuperProp =
-  Super->lookup(Res->getDeclName()).find_first()) {
+  if (ObjCPropertyDecl *SuperProp = Super->getProperty(
+  Res->getIdentifier(), Res->isInstanceProperty())) {
 DiagnosePropertyMismatch(Res, SuperProp, Super->getIdentifier(), false);
 FoundInSuper = true;
 break;
Index: clang/lib/AST/DeclObjC.cpp
===
--- clang/lib/AST/DeclObjC.cpp
+++ clang/lib/AST/DeclObjC.cpp
@@ -232,6 +232,18 @@
   return (ivarName.str());
 }
 
+ObjCPropertyDecl *ObjCContainerDecl::getProperty(const IdentifierInfo *Id,
+ bool IsInstance) const {
+  for (auto *LookupResult : lookup(Id)) {
+if (auto *Prop = dyn_cast(LookupResult)) {
+  if (Prop->isInstanceProperty() == IsInstance) {
+return Prop;
+  }
+}
+  }
+  return nullptr;
+}
+
 /// FindPropertyDeclaration - Finds declaration of the property given its name
 /// in 'PropertyId' and returns it. It returns 0, if not found.
 ObjCPropertyDecl *ObjCContainerDecl::FindPropertyDeclaration(
Index: clang/include/clang/AST/DeclObjC.h
===
--- clang/include/clang/AST/DeclObjC.h
+++ clang/include/clang/AST/DeclObjC.h
@@ -1071,6 +1071,9 @@
   bool HasUserDeclaredSetterMethod(const ObjCPropertyDecl *P) const;
   ObjCIvarDecl *getIvarDecl(IdentifierInfo *Id) const;
 
+  ObjCPropertyDecl *getProperty(const IdentifierInfo *Id,
+bool IsInstance) const;
+
   ObjCPropertyDecl *
   FindPropertyDeclaration(const IdentifierInfo *PropertyId,
   ObjCPropertyQueryKind QueryKind) const;
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D45438: [CodeView] Enable debugging of captured variables within C++ lambdas

2022-01-10 Thread David Blaikie via Phabricator via cfe-commits
dblaikie added inline comments.



Comment at: lib/CodeGen/CGDebugInfo.cpp:812-814
+  // CodeView types with C++ mangling need a type identifier.
+  if (CGM.getCodeGenOpts().EmitCodeView)
+return true;

Just came across this code today - it's /probably/ a problem for LTO. LLVM IR 
linking depends on the identifier to determine if two structs are the same for 
linkage purposes - so if an identifier is added for a non-linkage (local/not 
externally visible) type, LLVM will consider them to be the same even though 
they're unrelated:
```
namespace { struct t1 { int i; int j; }; }
t1 v1;
void *v3 = 
```
```
namespace { struct t1 { int i; }; }
t1 v1;
void *v2 = 
```
```
$ clang++-tot -emit-llvm -S a.cpp b.cpp -g -gcodeview  && 
~/dev/llvm/build/default/bin/llvm-link -o ab.bc a.ll b.ll && 
~/dev/llvm/build/default/bin/llvm-dis ab.bc && cat ab.ll | grep "\"t1\""
!8 = distinct !DICompositeType(tag: DW_TAG_structure_type, name: "t1", scope: 
!9, file: !3, line: 1, size: 64, flags: DIFlagTypePassByValue, elements: !10, 
identifier: "_ZTSN12_GLOBAL__N_12t1E")
$ clang++-tot -emit-llvm -S a.cpp b.cpp -g && 
~/dev/llvm/build/default/bin/llvm-link -o ab.bc a.ll b.ll && 
~/dev/llvm/build/default/bin/llvm-dis ab.bc && cat ab.ll | grep "\"t1\""
!8 = distinct !DICompositeType(tag: DW_TAG_structure_type, name: "t1", scope: 
!9, file: !3, line: 1, size: 64, flags: DIFlagTypePassByValue, elements: !10)
!21 = distinct !DICompositeType(tag: DW_TAG_structure_type, name: "t1", scope: 
!9, file: !17, line: 1, size: 32, flags: DIFlagTypePassByValue, elements: !22)
```

So in linking, now both `a.cpp` and `b.cpp` refer to a single `t1` type (in 
this case, it looks like the first one - the 64 bit wide one).

If CodeView actually can't represent these two distinct types with the same 
name in the same object file, so be it? But this looks like it's likely to 
cause problems for consumers/users.


Repository:
  rC Clang

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

https://reviews.llvm.org/D45438

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


[clang] bbf234b - [CodeCompletion] Complete designators for fields in anonymous structs/unions

2022-01-10 Thread Sam McCall via cfe-commits

Author: Sam McCall
Date: 2022-01-11T00:58:49+01:00
New Revision: bbf234b56a82d1b9b7fa58f8b10f16d417500d9b

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

LOG: [CodeCompletion] Complete designators for fields in anonymous 
structs/unions

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

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

Added: 


Modified: 
clang/lib/Sema/SemaCodeComplete.cpp
clang/test/CodeCompletion/desig-init.cpp

Removed: 




diff  --git a/clang/lib/Sema/SemaCodeComplete.cpp 
b/clang/lib/Sema/SemaCodeComplete.cpp
index c075cbf536caf..9266deb6699af 100644
--- a/clang/lib/Sema/SemaCodeComplete.cpp
+++ b/clang/lib/Sema/SemaCodeComplete.cpp
@@ -6344,7 +6344,15 @@ void Sema::CodeCompleteDesignator(QualType BaseType,
 CodeCompleter->getCodeCompletionTUInfo(), CCC);
 
   Results.EnterNewScope();
-  for (const auto *FD : RD->fields()) {
+  for (const Decl *D : RD->decls()) {
+const FieldDecl *FD;
+if (auto *IFD = dyn_cast(D))
+  FD = IFD->getAnonField();
+else if (auto *DFD = dyn_cast(D))
+  FD = DFD;
+else
+  continue;
+
 // FIXME: Make use of previous designators to mark any fields before those
 // inaccessible, and also compute the next initializer priority.
 ResultBuilder::Result Result(FD, Results.getBasePriority(FD));

diff  --git a/clang/test/CodeCompletion/desig-init.cpp 
b/clang/test/CodeCompletion/desig-init.cpp
index 999f368ba5634..76f6d2dea010d 100644
--- a/clang/test/CodeCompletion/desig-init.cpp
+++ b/clang/test/CodeCompletion/desig-init.cpp
@@ -77,3 +77,11 @@ namespace signature_regression {
   // CHECK-SIGNATURE-REGRESSION-NOT: OVERLOAD: [#int#]wrongFunction
 }
 
+struct WithAnon {
+  int outer;
+  struct { int inner; };
+};
+auto TestWithAnon = WithAnon { .inner = 2 };
+  // RUN: %clang_cc1 -fsyntax-only -code-completion-patterns 
-code-completion-at=%s:84:33 %s -o - -std=c++2a | FileCheck 
-check-prefix=CHECK-CC5 %s
+  // CHECK-CC5: COMPLETION: inner : [#int#]inner
+  // CHECK-CC5: COMPLETION: outer : [#int#]outer



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


[PATCH] D116717: [CodeCompletion] Complete designators for fields in anonymous structs/unions

2022-01-10 Thread Sam McCall 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 rGbbf234b56a82: [CodeCompletion] Complete designators for 
fields in anonymous structs/unions (authored by sammccall).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D116717

Files:
  clang/lib/Sema/SemaCodeComplete.cpp
  clang/test/CodeCompletion/desig-init.cpp


Index: clang/test/CodeCompletion/desig-init.cpp
===
--- clang/test/CodeCompletion/desig-init.cpp
+++ clang/test/CodeCompletion/desig-init.cpp
@@ -77,3 +77,11 @@
   // CHECK-SIGNATURE-REGRESSION-NOT: OVERLOAD: [#int#]wrongFunction
 }
 
+struct WithAnon {
+  int outer;
+  struct { int inner; };
+};
+auto TestWithAnon = WithAnon { .inner = 2 };
+  // RUN: %clang_cc1 -fsyntax-only -code-completion-patterns 
-code-completion-at=%s:84:33 %s -o - -std=c++2a | FileCheck 
-check-prefix=CHECK-CC5 %s
+  // CHECK-CC5: COMPLETION: inner : [#int#]inner
+  // CHECK-CC5: COMPLETION: outer : [#int#]outer
Index: clang/lib/Sema/SemaCodeComplete.cpp
===
--- clang/lib/Sema/SemaCodeComplete.cpp
+++ clang/lib/Sema/SemaCodeComplete.cpp
@@ -6344,7 +6344,15 @@
 CodeCompleter->getCodeCompletionTUInfo(), CCC);
 
   Results.EnterNewScope();
-  for (const auto *FD : RD->fields()) {
+  for (const Decl *D : RD->decls()) {
+const FieldDecl *FD;
+if (auto *IFD = dyn_cast(D))
+  FD = IFD->getAnonField();
+else if (auto *DFD = dyn_cast(D))
+  FD = DFD;
+else
+  continue;
+
 // FIXME: Make use of previous designators to mark any fields before those
 // inaccessible, and also compute the next initializer priority.
 ResultBuilder::Result Result(FD, Results.getBasePriority(FD));


Index: clang/test/CodeCompletion/desig-init.cpp
===
--- clang/test/CodeCompletion/desig-init.cpp
+++ clang/test/CodeCompletion/desig-init.cpp
@@ -77,3 +77,11 @@
   // CHECK-SIGNATURE-REGRESSION-NOT: OVERLOAD: [#int#]wrongFunction
 }
 
+struct WithAnon {
+  int outer;
+  struct { int inner; };
+};
+auto TestWithAnon = WithAnon { .inner = 2 };
+  // RUN: %clang_cc1 -fsyntax-only -code-completion-patterns -code-completion-at=%s:84:33 %s -o - -std=c++2a | FileCheck -check-prefix=CHECK-CC5 %s
+  // CHECK-CC5: COMPLETION: inner : [#int#]inner
+  // CHECK-CC5: COMPLETION: outer : [#int#]outer
Index: clang/lib/Sema/SemaCodeComplete.cpp
===
--- clang/lib/Sema/SemaCodeComplete.cpp
+++ clang/lib/Sema/SemaCodeComplete.cpp
@@ -6344,7 +6344,15 @@
 CodeCompleter->getCodeCompletionTUInfo(), CCC);
 
   Results.EnterNewScope();
-  for (const auto *FD : RD->fields()) {
+  for (const Decl *D : RD->decls()) {
+const FieldDecl *FD;
+if (auto *IFD = dyn_cast(D))
+  FD = IFD->getAnonField();
+else if (auto *DFD = dyn_cast(D))
+  FD = DFD;
+else
+  continue;
+
 // FIXME: Make use of previous designators to mark any fields before those
 // inaccessible, and also compute the next initializer priority.
 ResultBuilder::Result Result(FD, Results.getBasePriority(FD));
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


  1   2   3   >