[PATCH] D124690: [clangd] add inlay hints for std::forward-ed parameter packs

2022-05-02 Thread Nathan Ridge via Phabricator via cfe-commits
nridge added inline comments.



Comment at: clang-tools-extra/clangd/InlayHints.cpp:388
+// arguments
+auto ForwardedParmMatcher = compoundStmt(forEachDescendant(
+invocation(

upsj wrote:
> sammccall wrote:
> > We tend not to use ASTMatchers for these kind of tasks in clangd (except 
> > when embedding clang-tidy checks of course).
> > 
> > I guess the biggest technical reason is it's hard to reason about their 
> > performance so they end up slow and opaque (and indeed the clang-tidy 
> > checks are slow and we haven't got a clear idea how to fix it). It's also 
> > easy to match too much.
> > 
> > But part of it is just convention - because we have more 
> > RecursiveASTVisitors, the maintainers are more familiar with the quirks 
> > there than the quirks of matchers.
> > 
> > ---
> > 
> > To be clear, I don't see any specific problems with this code! But we still 
> > might ask to change it as there are costs to mixing styles, and we don't 
> > want to end up in a situation where a bug fix requires choosing between an 
> > expensive hasAncestor() matcher and rewriting the logic.
> That makes sense. From the Visitor standpoint, do I understand correctly that 
> you mean something like remembering the top-level templated `FunctionDecl` 
> (or stack of `FunctionDecl`s if we have something like nested Lambdas?) and 
> check every `CallExpr` and `CXXConstructExpr` for `ParmVarDecls` or 
> `std::forward(ParmVarDecl)` matching the parameters of the higher-level 
> `FunctionDecls`? That means basically lazily evaluating the parameter names, 
> so more storage inside the Visitor, but allows us to do recursive resolution 
> in a rather straightforward fashion.
I imagine something like running a `RecursiveASTVisitor` on 
`Callee->getBody()`, and overriding `VisitCallExpr()` and 
`VisitCXXConstructExpr()` to check whether it is a call of the right form.

I don't //think// theres a need to worry about lambdas nested in the body, I 
think we may still be able to get useful parameter names out of them, as in 
e.g.:

```
struct S {
 S(int a, int b);
};

template 
auto Make(Args... args) {
  auto ConstructTask = [&](){ return T(args...); };
  return ConstructTask();
}

int main() {
  auto s = Make(1, 2);
}
```



Comment at: clang-tools-extra/clangd/InlayHints.cpp:474
+// the parameter names from the wrapped function
+if (Args.size() > FixedParamCount && Args.size() == Params.size()) {
+  auto ForwardedParams = matchForwardedParams(

What is the reason for the `Args.size() == Params.size()` condition?

Doesn't this break cases where there is more than one argument matching the 
variadic parameter? For example:

```
void foo(int a, int b);
template 
void bar(Args&&... args) { foo(args...); }
int main() {
  bar(1, 2);
}
```

Here, I expect we'd have `Args.size() == 2` and `Params.size() == 1`.

(We should probably have test coverage for such multiple-arguments cases as 
well. We probably don't need it for all combinations, but we should have at 
least one test case exercising it.)



Comment at: clang-tools-extra/clangd/unittests/InlayHintTests.cpp:178
+  // No hint for anonymous variadic parameter
+  // The prototype is not correct, but is converted into builtin anyways.
+  assertParameterHints(R"cpp(

What does "converted into builtin" mean here?



Comment at: clang-tools-extra/clangd/unittests/InlayHintTests.cpp:203
+TEST(ParameterHints, VariadicForwardedConstructor) {
+  // No hint for anonymous variadic parameter
+  // The prototype is not correct, but is converted into builtin anyways.

This comment seems out of sync with the testcase (same for a few others)



Comment at: clang-tools-extra/clangd/unittests/InlayHintTests.cpp:209
+template 
+T bar(Args&&... args) { return T{$wrapped[[std::forward(args)...]]}; 
}
+void baz() {

The `wrapped` range doesn't seem to be used anywhere (same for a few other 
testcases)



Comment at: clang-tools-extra/clangd/unittests/InlayHintTests.cpp:270
+  )cpp",
+   ExpectedHint{"a: ", "wrapped"},
+   ExpectedHint{"a: ", "param"});

upsj wrote:
> This is a bit of an unfortunate side-effect of looking at instantiated 
> templates.
Perhaps it would make sense to exclude arguments which are pack expansion 
expressions from getting parameter hints?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124690

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


[PATCH] D124752: [HLSL] clang codeGen for HLSLShaderAttr.

2022-05-02 Thread Xiang Li via Phabricator via cfe-commits
python3kgae created this revision.
python3kgae added reviewers: dblaikie, MaskRay, hoy, lebedev.ri.
Herald added subscribers: Anastasia, StephenFan.
Herald added a project: All.
python3kgae requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

Translate HLSLShaderAttr to IR level.

1. Skip mangle for hlsl entry functions.
2. Add function attribute for hlsl entry functions.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D124752

Files:
  clang/lib/AST/Mangle.cpp
  clang/lib/CodeGen/CGHLSLRuntime.cpp
  clang/lib/CodeGen/CGHLSLRuntime.h
  clang/lib/CodeGen/CodeGenModule.cpp
  clang/test/CodeGenHLSL/entry.hlsl
  clang/test/CodeGenHLSL/shader_type_attr.hlsl

Index: clang/test/CodeGenHLSL/shader_type_attr.hlsl
===
--- /dev/null
+++ clang/test/CodeGenHLSL/shader_type_attr.hlsl
@@ -0,0 +1,11 @@
+// RUN: %clang --driver-mode=dxc -Tlib_6_x  -Fo - %s | FileCheck %s
+
+// Make sure not mangle entry.
+// CHECK:define void @foo()
+// Make sure add function attribute.
+// CHECK:"dx.shader"="compute"
+[shader("compute")]
+[numthreads(1,1,1)]
+void foo() {
+
+}
Index: clang/test/CodeGenHLSL/entry.hlsl
===
--- /dev/null
+++ clang/test/CodeGenHLSL/entry.hlsl
@@ -0,0 +1,10 @@
+// RUN: %clang --driver-mode=dxc -Tcs_6_1 -Efoo  -Fo - %s | FileCheck %s
+
+// Make sure not mangle entry.
+// CHECK:define void @foo()
+// Make sure add function attribute.
+// CHECK:"dx.shader"="compute"
+[numthreads(1,1,1)]
+void foo() {
+
+}
Index: clang/lib/CodeGen/CodeGenModule.cpp
===
--- clang/lib/CodeGen/CodeGenModule.cpp
+++ clang/lib/CodeGen/CodeGenModule.cpp
@@ -1650,6 +1650,10 @@
  /*AttrOnCallSite=*/false, IsThunk);
   F->setAttributes(PAL);
   F->setCallingConv(static_cast(CallingConv));
+  if (getLangOpts().HLSL) {
+if (const FunctionDecl *FD = dyn_cast_or_null(GD.getDecl()))
+  getHLSLRuntime().setHLSLFnuctionAttributes(F, FD);
+  }
 }
 
 static void removeImageAccessQualifier(std::string& TyName) {
Index: clang/lib/CodeGen/CGHLSLRuntime.h
===
--- clang/lib/CodeGen/CGHLSLRuntime.h
+++ clang/lib/CodeGen/CGHLSLRuntime.h
@@ -15,8 +15,13 @@
 #ifndef LLVM_CLANG_LIB_CODEGEN_CGHLSLRUNTIME_H
 #define LLVM_CLANG_LIB_CODEGEN_CGHLSLRUNTIME_H
 
+namespace llvm {
+class Function;
+}
 namespace clang {
 
+class FunctionDecl;
+
 namespace CodeGen {
 
 class CodeGenModule;
@@ -30,6 +35,8 @@
   virtual ~CGHLSLRuntime() {}
 
   void finishCodeGen();
+
+  void setHLSLFnuctionAttributes(llvm::Function *, const FunctionDecl *);
 };
 
 } // namespace CodeGen
Index: clang/lib/CodeGen/CGHLSLRuntime.cpp
===
--- clang/lib/CodeGen/CGHLSLRuntime.cpp
+++ clang/lib/CodeGen/CGHLSLRuntime.cpp
@@ -50,3 +50,12 @@
   llvm::Module &M = CGM.getModule();
   addDxilValVersion(TargetOpts.DxilValidatorVersion, M);
 }
+
+void clang::CodeGen::CGHLSLRuntime::setHLSLFnuctionAttributes(
+llvm::Function *F, const FunctionDecl *FD) {
+  if (HLSLShaderAttr *ShaderAttr = FD->getAttr()) {
+const StringRef ShaderAttrKindStr = "dx.shader";
+F->addFnAttr(ShaderAttrKindStr,
+ ShaderAttr->ConvertShaderTypeToStr(ShaderAttr->getType()));
+  }
+}
Index: clang/lib/AST/Mangle.cpp
===
--- clang/lib/AST/Mangle.cpp
+++ clang/lib/AST/Mangle.cpp
@@ -135,6 +135,10 @@
   if (isa(D))
 return true;
 
+  // HLSL shader entry function never need to be mangled.
+  if (getASTContext().getLangOpts().HLSL && D->hasAttr())
+return false;
+
   return shouldMangleCXXName(D);
 }
 
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D124753: [HLSL] Set main as default entry.

2022-05-02 Thread Xiang Li via Phabricator via cfe-commits
python3kgae created this revision.
python3kgae added reviewers: beanz, steven_wu, JonChesterfield, sscalpone, 
pow2clk, rnk, bogner, MaskRay, dexonsmith.
Herald added subscribers: Anastasia, StephenFan.
Herald added a project: All.
python3kgae requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

When there's no -E option, use main as entry function.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D124753

Files:
  clang/lib/Driver/ToolChains/HLSL.cpp
  clang/test/CodeGenHLSL/entry_default.hlsl


Index: clang/test/CodeGenHLSL/entry_default.hlsl
===
--- /dev/null
+++ clang/test/CodeGenHLSL/entry_default.hlsl
@@ -0,0 +1,10 @@
+// RUN: %clang --driver-mode=dxc -Tcs_6_1  -Fo - %s | FileCheck %s
+
+// Make sure main is default entry.
+// Make sure not mangle entry.
+// CHECK:define void @main()
+// Make sure add function attribute.
+// CHECK:"dx.shader"="compute"
+[numthreads(1, 1, 1)] void main() {
+
+}
Index: clang/lib/Driver/ToolChains/HLSL.cpp
===
--- clang/lib/Driver/ToolChains/HLSL.cpp
+++ clang/lib/Driver/ToolChains/HLSL.cpp
@@ -179,5 +179,11 @@
 Opts.getOption(options::OPT_dxil_validator_version),
 DefaultValidatorVer);
   }
+  // If not set entry, default is main.
+  if (!DAL->hasArg(options::OPT_hlsl_entrypoint)) {
+const StringRef DefaultEntry = "main";
+DAL->AddSeparateArg(nullptr, Opts.getOption(options::OPT_hlsl_entrypoint),
+DefaultEntry);
+  }
   return DAL;
 }


Index: clang/test/CodeGenHLSL/entry_default.hlsl
===
--- /dev/null
+++ clang/test/CodeGenHLSL/entry_default.hlsl
@@ -0,0 +1,10 @@
+// RUN: %clang --driver-mode=dxc -Tcs_6_1  -Fo - %s | FileCheck %s
+
+// Make sure main is default entry.
+// Make sure not mangle entry.
+// CHECK:define void @main()
+// Make sure add function attribute.
+// CHECK:"dx.shader"="compute"
+[numthreads(1, 1, 1)] void main() {
+
+}
Index: clang/lib/Driver/ToolChains/HLSL.cpp
===
--- clang/lib/Driver/ToolChains/HLSL.cpp
+++ clang/lib/Driver/ToolChains/HLSL.cpp
@@ -179,5 +179,11 @@
 Opts.getOption(options::OPT_dxil_validator_version),
 DefaultValidatorVer);
   }
+  // If not set entry, default is main.
+  if (!DAL->hasArg(options::OPT_hlsl_entrypoint)) {
+const StringRef DefaultEntry = "main";
+DAL->AddSeparateArg(nullptr, Opts.getOption(options::OPT_hlsl_entrypoint),
+DefaultEntry);
+  }
   return DAL;
 }
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D124359: [clangd] Add inlay hints for mutable reference parameters

2022-05-02 Thread Tobias Ribizel via Phabricator via cfe-commits
upsj updated this revision to Diff 426343.
upsj marked 4 inline comments as done.
upsj added a comment.

address review comments: Move reference hint to the prefix, test type aliases


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124359

Files:
  clang-tools-extra/clangd/InlayHints.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
@@ -157,18 +157,17 @@
   foo($param[[i]]);
 }
   )cpp",
-   ExpectedHint{"&", "param"});
+   ExpectedHint{"&: ", "param"});
 }
 
 TEST(ParameterHints, NoNameRValueReference) {
-  // Reference hint for anonymous r-value ref parameter.
+  // No reference hint for anonymous r-value ref parameter.
   assertParameterHints(R"cpp(
 void foo(int&&);
 void bar() {
   foo($param[[42]]);
 }
-  )cpp",
-   ExpectedHint{"&&", "param"});
+  )cpp");
 }
 
 TEST(ParameterHints, NameInDefinition) {
@@ -215,18 +214,31 @@
   foo($param[[i]]);
 }
   )cpp",
-   ExpectedHint{"param: &", "param"});
+   ExpectedHint{"¶m: ", "param"});
+}
+
+TEST(ParameterHints, NameTypeAliasReference) {
+  // Reference and name hint for l-value ref parameter via type alias.
+  assertParameterHints(R"cpp(
+using alias = int&;
+void foo(alias param);
+void bar() {
+  int i;
+  foo($param[[i]]);
+}
+  )cpp",
+   ExpectedHint{"¶m: ", "param"});
 }
 
 TEST(ParameterHints, NameRValueReference) {
-  // Reference and name hint for r-value ref parameter.
+  // Only name hint for r-value ref parameter.
   assertParameterHints(R"cpp(
 void foo(int&& param);
 void bar() {
   foo($param[[42]]);
 }
   )cpp",
-   ExpectedHint{"param: &&", "param"});
+   ExpectedHint{"param: ", "param"});
 }
 
 TEST(ParameterHints, Operator) {
@@ -380,7 +392,7 @@
   foo2(param);
 }
   )cpp",
-   ExpectedHint{"&", "param"});
+   ExpectedHint{"&: ", "param"});
 }
 
 TEST(ParameterHints, LeadingUnderscore) {
Index: clang-tools-extra/clangd/InlayHints.cpp
===
--- clang-tools-extra/clangd/InlayHints.cpp
+++ clang-tools-extra/clangd/InlayHints.cpp
@@ -404,17 +404,13 @@
 
 for (size_t I = 0; I < ArgCount; ++I) {
   StringRef Name = ParameterNames[I];
-  bool NameHint = shouldNameHint(Args[I], Name);
-  std::string Suffix = ": ";
-  if (!NameHint) {
-Name = "";
-Suffix = "";
-  }
-  Suffix += getRefSuffix(Params[I]);
+  bool NameHint = shouldHintName(Args[I], Name);
+  bool ReferenceHint = shouldHintReference(Params[I]);
 
-  if (!Name.empty() || !Suffix.empty()) {
+  if (NameHint || ReferenceHint) {
 addInlayHint(Args[I]->getSourceRange(), HintSide::Left,
- InlayHintKind::ParameterHint, /*Prefix=*/"", Name, Suffix);
+ InlayHintKind::ParameterHint, ReferenceHint ? "&" : "",
+ NameHint ? Name : "", ": ");
   }
 }
   }
@@ -442,16 +438,7 @@
 return WhatItIsSetting.equals_insensitive(ParamNames[0]);
   }
 
-  StringRef getRefSuffix(const ParmVarDecl *Param) {
-// If the parameter is a non-const reference type, print an inlay hint
-auto Type = Param->getType();
-return Type->isReferenceType() &&
-   !Type.getNonReferenceType().isConstQualified()
-   ? (Type->isLValueReferenceType() ? "&" : "&&")
-   : "";
-  }
-
-  bool shouldNameHint(const Expr *Arg, StringRef ParamName) {
+  bool shouldHintName(const Expr *Arg, StringRef ParamName) {
 if (ParamName.empty())
   return false;
 
@@ -467,6 +454,13 @@
 return true;
   }
 
+  bool shouldHintReference(const ParmVarDecl *Param) {
+// If the parameter is a non-const reference type, print an inlay hint
+auto Type = Param->getType();
+return Type->isLValueReferenceType() &&
+   !Type.getNonReferenceType().isConstQualified();
+  }
+
   // Checks if "E" is spelled in the main file and preceded by a C-style comment
   // whose contents match ParamName (allowing for whitespace and an optional "="
   // at the end.
@@ -580,7 +574,7 @@
 return Result;
   }
 
-  // We pass HintSide rather than SourceLocation because we want to ensure 
+  // We pass HintSide rather than SourceLocation because we want to ensure
   // it is in the same file as the common file range.
   void addInlayHint(SourceRange R, HintSide Side, InlayHintKind Kind,
 llvm::StringRef Prefix, llvm::StringRef Label,

[PATCH] D124359: [clangd] Add inlay hints for mutable reference parameters

2022-05-02 Thread Tobias Ribizel via Phabricator via cfe-commits
upsj added a comment.

Thanks, on second thought moving the hint to the prefix also makes more sense 
to me.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124359

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


[PATCH] D124736: [CodeGen] Use ABI alignment for placement new

2022-05-02 Thread John McCall via Phabricator via cfe-commits
rjmccall added a comment.

It should probably be the ABI alignment in all cases; I think the preferred 
alignment is just supposed to be used to opportunistically over-align things 
like e.g. local variables, which doesn't seem relevant for the ABI code 
involving a call to `operator new`.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124736

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


[PATCH] D124359: [clangd] Add inlay hints for mutable reference parameters

2022-05-02 Thread Nathan Ridge via Phabricator via cfe-commits
nridge added a comment.

Thanks, the changes here look good.

Something is strange about the diff though, it's not letting me see the 
complete changes relative to the baseline, only the incremental changes 
relative to a previous version (I think this is also why Phabricator's build 
status says patch application failed 
)




Comment at: clang-tools-extra/clangd/unittests/InlayHintTests.cpp:223
+  assertParameterHints(R"cpp(
+using alias = int&;
+void foo(alias param);

For good measure, let's add an `alias = const int&` case (expecting no `&`) as 
well


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124359

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


[PATCH] D124359: [clangd] Add inlay hints for mutable reference parameters

2022-05-02 Thread Tobias Ribizel via Phabricator via cfe-commits
upsj updated this revision to Diff 426344.
upsj added a comment.

right, arcanist doesn't entirely match my git mental model. Here's the 
(hopefully) complete patch


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124359

Files:
  clang-tools-extra/clangd/InlayHints.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
@@ -138,6 +138,38 @@
   )cpp");
 }
 
+TEST(ParameterHints, NoNameConstReference) {
+  // No hint for anonymous const l-value ref parameter.
+  assertParameterHints(R"cpp(
+void foo(const int&);
+void bar() {
+  foo(42);
+}
+  )cpp");
+}
+
+TEST(ParameterHints, NoNameReference) {
+  // Reference hint for anonymous l-value ref parameter.
+  assertParameterHints(R"cpp(
+void foo(int&);
+void bar() {
+  int i;
+  foo($param[[i]]);
+}
+  )cpp",
+   ExpectedHint{"&: ", "param"});
+}
+
+TEST(ParameterHints, NoNameRValueReference) {
+  // No reference hint for anonymous r-value ref parameter.
+  assertParameterHints(R"cpp(
+void foo(int&&);
+void bar() {
+  foo($param[[42]]);
+}
+  )cpp");
+}
+
 TEST(ParameterHints, NameInDefinition) {
   // Parameter name picked up from definition if necessary.
   assertParameterHints(R"cpp(
@@ -162,6 +194,53 @@
ExpectedHint{"good: ", "good"});
 }
 
+TEST(ParameterHints, NameConstReference) {
+  // Only name hint for const l-value ref parameter.
+  assertParameterHints(R"cpp(
+void foo(const int& param);
+void bar() {
+  foo($param[[42]]);
+}
+  )cpp",
+   ExpectedHint{"param: ", "param"});
+}
+
+TEST(ParameterHints, NameReference) {
+  // Reference and name hint for l-value ref parameter.
+  assertParameterHints(R"cpp(
+void foo(int& param);
+void bar() {
+  int i;
+  foo($param[[i]]);
+}
+  )cpp",
+   ExpectedHint{"¶m: ", "param"});
+}
+
+TEST(ParameterHints, NameTypeAliasReference) {
+  // Reference and name hint for l-value ref parameter via type alias.
+  assertParameterHints(R"cpp(
+using alias = int&;
+void foo(alias param);
+void bar() {
+  int i;
+  foo($param[[i]]);
+}
+  )cpp",
+   ExpectedHint{"¶m: ", "param"});
+}
+
+TEST(ParameterHints, NameRValueReference) {
+  // Only name hint for r-value ref parameter.
+  assertParameterHints(R"cpp(
+void foo(int&& param);
+void bar() {
+  foo($param[[42]]);
+}
+  )cpp",
+   ExpectedHint{"param: ", "param"});
+}
+
 TEST(ParameterHints, Operator) {
   // No hint for operator call with operator syntax.
   assertParameterHints(R"cpp(
@@ -301,6 +380,21 @@
ExpectedHint{"param: ", "param"});
 }
 
+TEST(ParameterHints, ArgMatchesParamReference) {
+  assertParameterHints(R"cpp(
+void foo(int& param);
+void foo2(const int& param);
+void bar() {
+  int param;
+  // show reference hint on mutable reference
+  foo($param[[param]]);
+  // but not on const reference
+  foo2(param);
+}
+  )cpp",
+   ExpectedHint{"&: ", "param"});
+}
+
 TEST(ParameterHints, LeadingUnderscore) {
   assertParameterHints(R"cpp(
 void foo(int p1, int _p2, int __p3);
Index: clang-tools-extra/clangd/InlayHints.cpp
===
--- clang-tools-extra/clangd/InlayHints.cpp
+++ clang-tools-extra/clangd/InlayHints.cpp
@@ -10,6 +10,7 @@
 #include "Config.h"
 #include "HeuristicResolver.h"
 #include "ParsedAST.h"
+#include "clang/AST/Decl.h"
 #include "clang/AST/DeclarationName.h"
 #include "clang/AST/ExprCXX.h"
 #include "clang/AST/RecursiveASTVisitor.h"
@@ -392,6 +393,7 @@
 // Don't show hints for variadic parameters.
 size_t FixedParamCount = getFixedParamCount(Callee);
 size_t ArgCount = std::min(FixedParamCount, Args.size());
+auto Params = Callee->parameters();
 
 NameVec ParameterNames = chooseParameterNames(Callee, ArgCount);
 
@@ -402,12 +404,14 @@
 
 for (size_t I = 0; I < ArgCount; ++I) {
   StringRef Name = ParameterNames[I];
-  if (!shouldHint(Args[I], Name))
-continue;
+  bool NameHint = shouldHintName(Args[I], Name);
+  bool ReferenceHint = shouldHintReference(Params[I]);
 
-  addInlayHint(Args[I]->getSourceRange(), HintSide::Left,
-   InlayHintKind::ParameterHint, /*Prefix=*/"", Name,
-   /*Suffix=*/": ");
+  if (NameHint || ReferenceHint) {
+addInlayHint(Args[I]->getSourceRange(), HintSide::Left,
+ InlayHintKind::ParameterHint, ReferenceHint ? "&" : "",
+ NameHint ? Name : "", ": ");
+  }
  

[PATCH] D124221: Add new builtin __builtin_reflect_struct.

2022-05-02 Thread Richard Smith - zygoloid via Phabricator via cfe-commits
rsmith updated this revision to Diff 426345.
rsmith added a comment.

- Reimplement __builtin_dump_struct in Sema.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124221

Files:
  clang/docs/LanguageExtensions.rst
  clang/docs/ReleaseNotes.rst
  clang/include/clang/Basic/Builtins.def
  clang/include/clang/Basic/DiagnosticSemaKinds.td
  clang/include/clang/Sema/Sema.h
  clang/lib/AST/Expr.cpp
  clang/lib/CodeGen/CGBuiltin.cpp
  clang/lib/Frontend/FrontendActions.cpp
  clang/lib/Sema/SemaChecking.cpp
  clang/lib/Sema/SemaStmt.cpp
  clang/lib/Sema/SemaTemplateInstantiate.cpp
  clang/test/CodeGen/builtin-dump-struct.c
  clang/test/CodeGen/dump-struct-builtin.c
  clang/test/CodeGenCXX/builtin-dump-struct.cpp
  clang/test/Sema/builtin-dump-struct.c
  clang/test/SemaCXX/builtin-dump-struct.cpp

Index: clang/test/SemaCXX/builtin-dump-struct.cpp
===
--- /dev/null
+++ clang/test/SemaCXX/builtin-dump-struct.cpp
@@ -0,0 +1,135 @@
+// RUN: %clang_cc1 -std=c++20 -verify %s
+
+namespace std {
+  typedef decltype(sizeof(int)) size_t;
+
+  template  struct initializer_list {
+const E *data;
+size_t size;
+
+constexpr initializer_list(const E *data, size_t size)
+: data(data), size(size) {}
+constexpr initializer_list() : data(), size() {}
+
+constexpr const E *begin() const { return data; }
+constexpr const E *end() const { return data + size; }
+  };
+}
+
+struct ConstexprString {
+  constexpr ConstexprString() : ConstexprString("") {}
+  constexpr ConstexprString(const char *p, std::size_t size) : data(new char[size+1]) {
+__builtin_memcpy(data, p, size);
+data[size] = '\0';
+  }
+  constexpr ConstexprString(const char *p) : ConstexprString(p, __builtin_strlen(p)) {}
+  constexpr explicit ConstexprString(const char *p, const char *q) : data(nullptr) {
+auto p_size = __builtin_strlen(p);
+auto q_size = __builtin_strlen(q);
+data = new char[p_size + q_size + 1];
+__builtin_memcpy(data, p, p_size);
+__builtin_memcpy(data + p_size, q, q_size + 1);
+  }
+  constexpr ConstexprString(const ConstexprString &o) : ConstexprString(o.data) {}
+  constexpr ConstexprString(ConstexprString &&o) : data(o.data) { o.data = nullptr; }
+  constexpr ConstexprString &operator=(const ConstexprString &o) {
+return *this = ConstexprString(o);
+  }
+  constexpr ConstexprString &operator=(ConstexprString &&o) {
+delete[] data;
+data = o.data;
+o.data = nullptr;
+return *this;
+  }
+  constexpr ~ConstexprString() { delete[] data; }
+  char *data;
+
+  friend constexpr ConstexprString operator+(const ConstexprString &a, const ConstexprString &b) {
+return ConstexprString(a.data, b.data);
+  }
+  friend constexpr ConstexprString &operator+=(ConstexprString &a, const ConstexprString &b) {
+return a = a + b;
+  }
+  friend constexpr bool operator==(const ConstexprString &a, const ConstexprString &b) {
+return __builtin_strcmp(a.data, b.data) == 0;
+  }
+};
+
+template constexpr void Format(ConstexprString &out, const char *fmt, T... args);
+
+struct Arg {
+  template
+  constexpr Arg(T value) {
+bool negative = false;
+if (value < 0) {
+  value = -value;
+  negative = true;
+}
+while (value > 0) {
+  char str[2] = {char('0' + value % 10), '\0'};
+  s = ConstexprString(str) + s;
+  value /= 10;
+}
+if (negative)
+  s = "-" + s;
+  }
+  template
+  constexpr Arg(T value) {
+__builtin_dump_struct(&value, Format, s);
+  }
+  constexpr Arg(const char *s) : s(s) {}
+  constexpr Arg(const ConstexprString *s) : s("\"" + *s + "\"") {}
+  ConstexprString s;
+};
+
+template constexpr void Format(ConstexprString &out, const char *fmt, T... args) { // #Format
+  Arg formatted_args[] = {args...};
+  int i = 0;
+  while (const char *percent = __builtin_strchr(fmt, '%')) {
+if (percent[1] == '%') continue;
+if (percent != fmt && percent[-1] == '*') --percent;
+out += ConstexprString(fmt, percent - fmt);
+out += formatted_args[i++].s;
+
+// Skip past format specifier until we hit a conversion specifier.
+fmt = percent;
+while (!__builtin_strchr("diouxXeEfFgGcsp", *fmt)) ++fmt;
+// Skip the conversion specifier too. TODO: Check it's the right one.
+++fmt;
+  }
+  out += ConstexprString(fmt);
+}
+
+template constexpr ConstexprString ToString(T t) { return Arg(t).s; }
+
+struct A { int x, y, z : 3; int : 4; ConstexprString s; };
+struct B : A { int p, q; struct { int anon1, anon2; }; union { int anon3; }; };
+
+extern "C" int puts(const char*);
+int main() { puts(ToString(B{1, 2, 3, "hello", 4, 5, 6, 7, 8}).data); }
+
+static_assert(ToString(B{1, 2, 3, "hello", 4, 5, 6, 7, 8}) == &R"(
+struct B {
+struct A {
+int x = 1
+int y = 2
+int z : 3 = 3
+struct ConstexprString s = "hello"
+}
+int p = 4
+int q 

[PATCH] D124221: Reimplement `__builtin_dump_struct` in Sema.

2022-05-02 Thread Richard Smith - zygoloid via Phabricator via cfe-commits
rsmith added a comment.

In D124221#3469251 , @rsmith wrote:

> I think we can address most of my concerns with `__builtin_dump_struct` 
> without a new builtin, by incorporating things from this implementation

Done; this patch now reimplements `__builtin_dump_struct` using the `Sema` 
desugaring approach rather than providing a new builtin. As in the prior patch, 
we still support passing an arbitrary callable and additional arguments, and in 
C++ we support constant-evaluation of the dump as well as generic printing of 
field values even for types that the builtin doesn't natively understand. But 
the interface remains simple enough that you can just call 
`__builtin_dump_struct(&s, printf)` or `__builtin_dump_struct(&s, fprintf, 
stderr)` and get a dump to stdout / stderr.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124221

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


[PATCH] D124359: [clangd] Add inlay hints for mutable reference parameters

2022-05-02 Thread Tobias Ribizel via Phabricator via cfe-commits
upsj updated this revision to Diff 426346.
upsj marked an inline comment as done.
upsj added a comment.

add test for const ref inlay hint via type alias


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124359

Files:
  clang-tools-extra/clangd/InlayHints.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
@@ -138,6 +138,38 @@
   )cpp");
 }
 
+TEST(ParameterHints, NoNameConstReference) {
+  // No hint for anonymous const l-value ref parameter.
+  assertParameterHints(R"cpp(
+void foo(const int&);
+void bar() {
+  foo(42);
+}
+  )cpp");
+}
+
+TEST(ParameterHints, NoNameReference) {
+  // Reference hint for anonymous l-value ref parameter.
+  assertParameterHints(R"cpp(
+void foo(int&);
+void bar() {
+  int i;
+  foo($param[[i]]);
+}
+  )cpp",
+   ExpectedHint{"&: ", "param"});
+}
+
+TEST(ParameterHints, NoNameRValueReference) {
+  // No reference hint for anonymous r-value ref parameter.
+  assertParameterHints(R"cpp(
+void foo(int&&);
+void bar() {
+  foo($param[[42]]);
+}
+  )cpp");
+}
+
 TEST(ParameterHints, NameInDefinition) {
   // Parameter name picked up from definition if necessary.
   assertParameterHints(R"cpp(
@@ -162,6 +194,66 @@
ExpectedHint{"good: ", "good"});
 }
 
+TEST(ParameterHints, NameConstReference) {
+  // Only name hint for const l-value ref parameter.
+  assertParameterHints(R"cpp(
+void foo(const int& param);
+void bar() {
+  foo($param[[42]]);
+}
+  )cpp",
+   ExpectedHint{"param: ", "param"});
+}
+
+TEST(ParameterHints, NameTypeAliasConstReference) {
+  // Only name hint for const l-value ref parameter via type alias.
+  assertParameterHints(R"cpp(
+using alias = const int&;
+void foo(alias param);
+void bar() {
+  int i;
+  foo($param[[i]]);
+}
+  )cpp",
+   ExpectedHint{"param: ", "param"});
+}
+
+TEST(ParameterHints, NameReference) {
+  // Reference and name hint for l-value ref parameter.
+  assertParameterHints(R"cpp(
+void foo(int& param);
+void bar() {
+  int i;
+  foo($param[[i]]);
+}
+  )cpp",
+   ExpectedHint{"¶m: ", "param"});
+}
+
+TEST(ParameterHints, NameTypeAliasReference) {
+  // Reference and name hint for l-value ref parameter via type alias.
+  assertParameterHints(R"cpp(
+using alias = int&;
+void foo(alias param);
+void bar() {
+  int i;
+  foo($param[[i]]);
+}
+  )cpp",
+   ExpectedHint{"¶m: ", "param"});
+}
+
+TEST(ParameterHints, NameRValueReference) {
+  // Only name hint for r-value ref parameter.
+  assertParameterHints(R"cpp(
+void foo(int&& param);
+void bar() {
+  foo($param[[42]]);
+}
+  )cpp",
+   ExpectedHint{"param: ", "param"});
+}
+
 TEST(ParameterHints, Operator) {
   // No hint for operator call with operator syntax.
   assertParameterHints(R"cpp(
@@ -301,6 +393,21 @@
ExpectedHint{"param: ", "param"});
 }
 
+TEST(ParameterHints, ArgMatchesParamReference) {
+  assertParameterHints(R"cpp(
+void foo(int& param);
+void foo2(const int& param);
+void bar() {
+  int param;
+  // show reference hint on mutable reference
+  foo($param[[param]]);
+  // but not on const reference
+  foo2(param);
+}
+  )cpp",
+   ExpectedHint{"&: ", "param"});
+}
+
 TEST(ParameterHints, LeadingUnderscore) {
   assertParameterHints(R"cpp(
 void foo(int p1, int _p2, int __p3);
Index: clang-tools-extra/clangd/InlayHints.cpp
===
--- clang-tools-extra/clangd/InlayHints.cpp
+++ clang-tools-extra/clangd/InlayHints.cpp
@@ -10,6 +10,7 @@
 #include "Config.h"
 #include "HeuristicResolver.h"
 #include "ParsedAST.h"
+#include "clang/AST/Decl.h"
 #include "clang/AST/DeclarationName.h"
 #include "clang/AST/ExprCXX.h"
 #include "clang/AST/RecursiveASTVisitor.h"
@@ -392,6 +393,7 @@
 // Don't show hints for variadic parameters.
 size_t FixedParamCount = getFixedParamCount(Callee);
 size_t ArgCount = std::min(FixedParamCount, Args.size());
+auto Params = Callee->parameters();
 
 NameVec ParameterNames = chooseParameterNames(Callee, ArgCount);
 
@@ -402,12 +404,14 @@
 
 for (size_t I = 0; I < ArgCount; ++I) {
   StringRef Name = ParameterNames[I];
-  if (!shouldHint(Args[I], Name))
-continue;
+  bool NameHint = shouldHintName(Args[I], Name);
+  bool ReferenceHint = shouldHintReference(Params[I]);
 
-  addInlayHint(Args[I]->getSourceRange(), HintSide::Left,
-  

[PATCH] D124221: Reimplement `__builtin_dump_struct` in Sema.

2022-05-02 Thread Richard Smith - zygoloid via Phabricator via cfe-commits
rsmith updated this revision to Diff 426347.
rsmith edited the summary of this revision.
rsmith added a comment.

- Fix example in documentation: the dump is terminated by a newline.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124221

Files:
  clang/docs/LanguageExtensions.rst
  clang/docs/ReleaseNotes.rst
  clang/include/clang/Basic/Builtins.def
  clang/include/clang/Basic/DiagnosticSemaKinds.td
  clang/include/clang/Sema/Sema.h
  clang/lib/AST/Expr.cpp
  clang/lib/CodeGen/CGBuiltin.cpp
  clang/lib/Frontend/FrontendActions.cpp
  clang/lib/Sema/SemaChecking.cpp
  clang/lib/Sema/SemaStmt.cpp
  clang/lib/Sema/SemaTemplateInstantiate.cpp
  clang/test/CodeGen/builtin-dump-struct.c
  clang/test/CodeGen/dump-struct-builtin.c
  clang/test/CodeGenCXX/builtin-dump-struct.cpp
  clang/test/Sema/builtin-dump-struct.c
  clang/test/SemaCXX/builtin-dump-struct.cpp

Index: clang/test/SemaCXX/builtin-dump-struct.cpp
===
--- /dev/null
+++ clang/test/SemaCXX/builtin-dump-struct.cpp
@@ -0,0 +1,135 @@
+// RUN: %clang_cc1 -std=c++20 -verify %s
+
+namespace std {
+  typedef decltype(sizeof(int)) size_t;
+
+  template  struct initializer_list {
+const E *data;
+size_t size;
+
+constexpr initializer_list(const E *data, size_t size)
+: data(data), size(size) {}
+constexpr initializer_list() : data(), size() {}
+
+constexpr const E *begin() const { return data; }
+constexpr const E *end() const { return data + size; }
+  };
+}
+
+struct ConstexprString {
+  constexpr ConstexprString() : ConstexprString("") {}
+  constexpr ConstexprString(const char *p, std::size_t size) : data(new char[size+1]) {
+__builtin_memcpy(data, p, size);
+data[size] = '\0';
+  }
+  constexpr ConstexprString(const char *p) : ConstexprString(p, __builtin_strlen(p)) {}
+  constexpr explicit ConstexprString(const char *p, const char *q) : data(nullptr) {
+auto p_size = __builtin_strlen(p);
+auto q_size = __builtin_strlen(q);
+data = new char[p_size + q_size + 1];
+__builtin_memcpy(data, p, p_size);
+__builtin_memcpy(data + p_size, q, q_size + 1);
+  }
+  constexpr ConstexprString(const ConstexprString &o) : ConstexprString(o.data) {}
+  constexpr ConstexprString(ConstexprString &&o) : data(o.data) { o.data = nullptr; }
+  constexpr ConstexprString &operator=(const ConstexprString &o) {
+return *this = ConstexprString(o);
+  }
+  constexpr ConstexprString &operator=(ConstexprString &&o) {
+delete[] data;
+data = o.data;
+o.data = nullptr;
+return *this;
+  }
+  constexpr ~ConstexprString() { delete[] data; }
+  char *data;
+
+  friend constexpr ConstexprString operator+(const ConstexprString &a, const ConstexprString &b) {
+return ConstexprString(a.data, b.data);
+  }
+  friend constexpr ConstexprString &operator+=(ConstexprString &a, const ConstexprString &b) {
+return a = a + b;
+  }
+  friend constexpr bool operator==(const ConstexprString &a, const ConstexprString &b) {
+return __builtin_strcmp(a.data, b.data) == 0;
+  }
+};
+
+template constexpr void Format(ConstexprString &out, const char *fmt, T... args);
+
+struct Arg {
+  template
+  constexpr Arg(T value) {
+bool negative = false;
+if (value < 0) {
+  value = -value;
+  negative = true;
+}
+while (value > 0) {
+  char str[2] = {char('0' + value % 10), '\0'};
+  s = ConstexprString(str) + s;
+  value /= 10;
+}
+if (negative)
+  s = "-" + s;
+  }
+  template
+  constexpr Arg(T value) {
+__builtin_dump_struct(&value, Format, s);
+  }
+  constexpr Arg(const char *s) : s(s) {}
+  constexpr Arg(const ConstexprString *s) : s("\"" + *s + "\"") {}
+  ConstexprString s;
+};
+
+template constexpr void Format(ConstexprString &out, const char *fmt, T... args) { // #Format
+  Arg formatted_args[] = {args...};
+  int i = 0;
+  while (const char *percent = __builtin_strchr(fmt, '%')) {
+if (percent[1] == '%') continue;
+if (percent != fmt && percent[-1] == '*') --percent;
+out += ConstexprString(fmt, percent - fmt);
+out += formatted_args[i++].s;
+
+// Skip past format specifier until we hit a conversion specifier.
+fmt = percent;
+while (!__builtin_strchr("diouxXeEfFgGcsp", *fmt)) ++fmt;
+// Skip the conversion specifier too. TODO: Check it's the right one.
+++fmt;
+  }
+  out += ConstexprString(fmt);
+}
+
+template constexpr ConstexprString ToString(T t) { return Arg(t).s; }
+
+struct A { int x, y, z : 3; int : 4; ConstexprString s; };
+struct B : A { int p, q; struct { int anon1, anon2; }; union { int anon3; }; };
+
+extern "C" int puts(const char*);
+int main() { puts(ToString(B{1, 2, 3, "hello", 4, 5, 6, 7, 8}).data); }
+
+static_assert(ToString(B{1, 2, 3, "hello", 4, 5, 6, 7, 8}) == &R"(
+struct B {
+struct A {
+int x = 1
+int y = 2
+int z : 3 = 3
+

[PATCH] D124221: Reimplement `__builtin_dump_struct` in Sema.

2022-05-02 Thread Richard Smith - zygoloid via Phabricator via cfe-commits
rsmith updated this revision to Diff 426348.
rsmith added a comment.

- Minor doc correction


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124221

Files:
  clang/docs/LanguageExtensions.rst
  clang/docs/ReleaseNotes.rst
  clang/include/clang/Basic/Builtins.def
  clang/include/clang/Basic/DiagnosticSemaKinds.td
  clang/include/clang/Sema/Sema.h
  clang/lib/AST/Expr.cpp
  clang/lib/CodeGen/CGBuiltin.cpp
  clang/lib/Frontend/FrontendActions.cpp
  clang/lib/Sema/SemaChecking.cpp
  clang/lib/Sema/SemaStmt.cpp
  clang/lib/Sema/SemaTemplateInstantiate.cpp
  clang/test/CodeGen/builtin-dump-struct.c
  clang/test/CodeGen/dump-struct-builtin.c
  clang/test/CodeGenCXX/builtin-dump-struct.cpp
  clang/test/Sema/builtin-dump-struct.c
  clang/test/SemaCXX/builtin-dump-struct.cpp

Index: clang/test/SemaCXX/builtin-dump-struct.cpp
===
--- /dev/null
+++ clang/test/SemaCXX/builtin-dump-struct.cpp
@@ -0,0 +1,135 @@
+// RUN: %clang_cc1 -std=c++20 -verify %s
+
+namespace std {
+  typedef decltype(sizeof(int)) size_t;
+
+  template  struct initializer_list {
+const E *data;
+size_t size;
+
+constexpr initializer_list(const E *data, size_t size)
+: data(data), size(size) {}
+constexpr initializer_list() : data(), size() {}
+
+constexpr const E *begin() const { return data; }
+constexpr const E *end() const { return data + size; }
+  };
+}
+
+struct ConstexprString {
+  constexpr ConstexprString() : ConstexprString("") {}
+  constexpr ConstexprString(const char *p, std::size_t size) : data(new char[size+1]) {
+__builtin_memcpy(data, p, size);
+data[size] = '\0';
+  }
+  constexpr ConstexprString(const char *p) : ConstexprString(p, __builtin_strlen(p)) {}
+  constexpr explicit ConstexprString(const char *p, const char *q) : data(nullptr) {
+auto p_size = __builtin_strlen(p);
+auto q_size = __builtin_strlen(q);
+data = new char[p_size + q_size + 1];
+__builtin_memcpy(data, p, p_size);
+__builtin_memcpy(data + p_size, q, q_size + 1);
+  }
+  constexpr ConstexprString(const ConstexprString &o) : ConstexprString(o.data) {}
+  constexpr ConstexprString(ConstexprString &&o) : data(o.data) { o.data = nullptr; }
+  constexpr ConstexprString &operator=(const ConstexprString &o) {
+return *this = ConstexprString(o);
+  }
+  constexpr ConstexprString &operator=(ConstexprString &&o) {
+delete[] data;
+data = o.data;
+o.data = nullptr;
+return *this;
+  }
+  constexpr ~ConstexprString() { delete[] data; }
+  char *data;
+
+  friend constexpr ConstexprString operator+(const ConstexprString &a, const ConstexprString &b) {
+return ConstexprString(a.data, b.data);
+  }
+  friend constexpr ConstexprString &operator+=(ConstexprString &a, const ConstexprString &b) {
+return a = a + b;
+  }
+  friend constexpr bool operator==(const ConstexprString &a, const ConstexprString &b) {
+return __builtin_strcmp(a.data, b.data) == 0;
+  }
+};
+
+template constexpr void Format(ConstexprString &out, const char *fmt, T... args);
+
+struct Arg {
+  template
+  constexpr Arg(T value) {
+bool negative = false;
+if (value < 0) {
+  value = -value;
+  negative = true;
+}
+while (value > 0) {
+  char str[2] = {char('0' + value % 10), '\0'};
+  s = ConstexprString(str) + s;
+  value /= 10;
+}
+if (negative)
+  s = "-" + s;
+  }
+  template
+  constexpr Arg(T value) {
+__builtin_dump_struct(&value, Format, s);
+  }
+  constexpr Arg(const char *s) : s(s) {}
+  constexpr Arg(const ConstexprString *s) : s("\"" + *s + "\"") {}
+  ConstexprString s;
+};
+
+template constexpr void Format(ConstexprString &out, const char *fmt, T... args) { // #Format
+  Arg formatted_args[] = {args...};
+  int i = 0;
+  while (const char *percent = __builtin_strchr(fmt, '%')) {
+if (percent[1] == '%') continue;
+if (percent != fmt && percent[-1] == '*') --percent;
+out += ConstexprString(fmt, percent - fmt);
+out += formatted_args[i++].s;
+
+// Skip past format specifier until we hit a conversion specifier.
+fmt = percent;
+while (!__builtin_strchr("diouxXeEfFgGcsp", *fmt)) ++fmt;
+// Skip the conversion specifier too. TODO: Check it's the right one.
+++fmt;
+  }
+  out += ConstexprString(fmt);
+}
+
+template constexpr ConstexprString ToString(T t) { return Arg(t).s; }
+
+struct A { int x, y, z : 3; int : 4; ConstexprString s; };
+struct B : A { int p, q; struct { int anon1, anon2; }; union { int anon3; }; };
+
+extern "C" int puts(const char*);
+int main() { puts(ToString(B{1, 2, 3, "hello", 4, 5, 6, 7, 8}).data); }
+
+static_assert(ToString(B{1, 2, 3, "hello", 4, 5, 6, 7, 8}) == &R"(
+struct B {
+struct A {
+int x = 1
+int y = 2
+int z : 3 = 3
+struct ConstexprString s = "hello"
+}
+int p = 4
+int q = 5
+int anon1 = 6

[PATCH] D124221: Reimplement `__builtin_dump_struct` in Sema.

2022-05-02 Thread Richard Smith - zygoloid via Phabricator via cfe-commits
rsmith updated this revision to Diff 426349.
rsmith added a comment.

- Update release notes


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124221

Files:
  clang/docs/LanguageExtensions.rst
  clang/docs/ReleaseNotes.rst
  clang/include/clang/Basic/Builtins.def
  clang/include/clang/Basic/DiagnosticSemaKinds.td
  clang/include/clang/Sema/Sema.h
  clang/lib/AST/Expr.cpp
  clang/lib/CodeGen/CGBuiltin.cpp
  clang/lib/Frontend/FrontendActions.cpp
  clang/lib/Sema/SemaChecking.cpp
  clang/lib/Sema/SemaStmt.cpp
  clang/lib/Sema/SemaTemplateInstantiate.cpp
  clang/test/CodeGen/builtin-dump-struct.c
  clang/test/CodeGen/dump-struct-builtin.c
  clang/test/CodeGenCXX/builtin-dump-struct.cpp
  clang/test/Sema/builtin-dump-struct.c
  clang/test/SemaCXX/builtin-dump-struct.cpp

Index: clang/test/SemaCXX/builtin-dump-struct.cpp
===
--- /dev/null
+++ clang/test/SemaCXX/builtin-dump-struct.cpp
@@ -0,0 +1,135 @@
+// RUN: %clang_cc1 -std=c++20 -verify %s
+
+namespace std {
+  typedef decltype(sizeof(int)) size_t;
+
+  template  struct initializer_list {
+const E *data;
+size_t size;
+
+constexpr initializer_list(const E *data, size_t size)
+: data(data), size(size) {}
+constexpr initializer_list() : data(), size() {}
+
+constexpr const E *begin() const { return data; }
+constexpr const E *end() const { return data + size; }
+  };
+}
+
+struct ConstexprString {
+  constexpr ConstexprString() : ConstexprString("") {}
+  constexpr ConstexprString(const char *p, std::size_t size) : data(new char[size+1]) {
+__builtin_memcpy(data, p, size);
+data[size] = '\0';
+  }
+  constexpr ConstexprString(const char *p) : ConstexprString(p, __builtin_strlen(p)) {}
+  constexpr explicit ConstexprString(const char *p, const char *q) : data(nullptr) {
+auto p_size = __builtin_strlen(p);
+auto q_size = __builtin_strlen(q);
+data = new char[p_size + q_size + 1];
+__builtin_memcpy(data, p, p_size);
+__builtin_memcpy(data + p_size, q, q_size + 1);
+  }
+  constexpr ConstexprString(const ConstexprString &o) : ConstexprString(o.data) {}
+  constexpr ConstexprString(ConstexprString &&o) : data(o.data) { o.data = nullptr; }
+  constexpr ConstexprString &operator=(const ConstexprString &o) {
+return *this = ConstexprString(o);
+  }
+  constexpr ConstexprString &operator=(ConstexprString &&o) {
+delete[] data;
+data = o.data;
+o.data = nullptr;
+return *this;
+  }
+  constexpr ~ConstexprString() { delete[] data; }
+  char *data;
+
+  friend constexpr ConstexprString operator+(const ConstexprString &a, const ConstexprString &b) {
+return ConstexprString(a.data, b.data);
+  }
+  friend constexpr ConstexprString &operator+=(ConstexprString &a, const ConstexprString &b) {
+return a = a + b;
+  }
+  friend constexpr bool operator==(const ConstexprString &a, const ConstexprString &b) {
+return __builtin_strcmp(a.data, b.data) == 0;
+  }
+};
+
+template constexpr void Format(ConstexprString &out, const char *fmt, T... args);
+
+struct Arg {
+  template
+  constexpr Arg(T value) {
+bool negative = false;
+if (value < 0) {
+  value = -value;
+  negative = true;
+}
+while (value > 0) {
+  char str[2] = {char('0' + value % 10), '\0'};
+  s = ConstexprString(str) + s;
+  value /= 10;
+}
+if (negative)
+  s = "-" + s;
+  }
+  template
+  constexpr Arg(T value) {
+__builtin_dump_struct(&value, Format, s);
+  }
+  constexpr Arg(const char *s) : s(s) {}
+  constexpr Arg(const ConstexprString *s) : s("\"" + *s + "\"") {}
+  ConstexprString s;
+};
+
+template constexpr void Format(ConstexprString &out, const char *fmt, T... args) { // #Format
+  Arg formatted_args[] = {args...};
+  int i = 0;
+  while (const char *percent = __builtin_strchr(fmt, '%')) {
+if (percent[1] == '%') continue;
+if (percent != fmt && percent[-1] == '*') --percent;
+out += ConstexprString(fmt, percent - fmt);
+out += formatted_args[i++].s;
+
+// Skip past format specifier until we hit a conversion specifier.
+fmt = percent;
+while (!__builtin_strchr("diouxXeEfFgGcsp", *fmt)) ++fmt;
+// Skip the conversion specifier too. TODO: Check it's the right one.
+++fmt;
+  }
+  out += ConstexprString(fmt);
+}
+
+template constexpr ConstexprString ToString(T t) { return Arg(t).s; }
+
+struct A { int x, y, z : 3; int : 4; ConstexprString s; };
+struct B : A { int p, q; struct { int anon1, anon2; }; union { int anon3; }; };
+
+extern "C" int puts(const char*);
+int main() { puts(ToString(B{1, 2, 3, "hello", 4, 5, 6, 7, 8}).data); }
+
+static_assert(ToString(B{1, 2, 3, "hello", 4, 5, 6, 7, 8}) == &R"(
+struct B {
+struct A {
+int x = 1
+int y = 2
+int z : 3 = 3
+struct ConstexprString s = "hello"
+}
+int p = 4
+int q = 5
+int anon1 = 6

[PATCH] D124667: [flang][driver] Add support for consuming LLVM IR/BC files

2022-05-02 Thread Diana Picus via Phabricator via cfe-commits
rovka accepted this revision.
rovka added a comment.
This revision is now accepted and ready to land.

A few nits, but otherwise LGTM.




Comment at: flang/lib/Frontend/FrontendActions.cpp:86
+
+  // ... otherwise, generate an MLIR module from the input Fortran source
   bool res = RunPrescan() && RunParse() && RunSemanticChecks();

Nit: Should we assert that the language is Language::Fortran at this point?



Comment at: flang/test/Driver/emit-asm-from-llvm-bc.ll:2
+; Verify that the driver can consume LLVM BC files. The expected assembly is
+; fairly (tested on AArch64 an X86_64), but we may need to tweak when testing
+; on other platforms. Note that that the actual output doesn't matter as long





Comment at: flang/test/Driver/emit-asm-from-llvm-bc.ll:3
+; fairly (tested on AArch64 an X86_64), but we may need to tweak when testing
+; on other platforms. Note that that the actual output doesn't matter as long
+; as it's in Assembly format.





Comment at: flang/test/Driver/emit-asm-from-llvm-bc.ll:9
+;-
+; RUN: rm -f %t.bc
+; RUN: %flang_fc1 -emit-llvm-bc %s -o %t.bc

Have you tried %basename_t.bc instead? You might be able to skip all the `rm`s 
then...



Comment at: flang/test/Driver/emit-asm-from-llvm.ll:1
+; Verify that the driver can consume LLVM IR files. The expected assembly is ;
+; fairly generic (verified on AArch64 an X86_64), but we may need to tweak when





Comment at: flang/test/Driver/emit-asm-from-llvm.ll:2
+; Verify that the driver can consume LLVM IR files. The expected assembly is ;
+; fairly generic (verified on AArch64 an X86_64), but we may need to tweak when
+; testing on other platforms. Note that that the actual output doesn't matter





Comment at: flang/test/Driver/emit-asm-from-llvm.ll:3
+; fairly generic (verified on AArch64 an X86_64), but we may need to tweak when
+; testing on other platforms. Note that that the actual output doesn't matter
+; as long as it's in Assembly format.





Comment at: flang/test/Driver/override-triple.ll:20
+; For the triple to be overridden by the driver, it needs to be different to 
the host triple.
+; Use a random string to guaranteed that.
+target triple = "invalid-triple"




Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124667

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


[PATCH] D124606: Use `-text` git attribute instead of `text eol=...'

2022-05-02 Thread Ilya Biryukov via Phabricator via cfe-commits
ilya-biryukov added a comment.

In D124606#3484740 , @Meinersbur 
wrote:

> In D124606#3479793 , @ilya-biryukov 
> wrote:
>
>> LGTM
>
> This and the commit (@MForster ) was too hasty. There should have been time 
> for people discussing D124563  and D97625 
>  to react, and should have been added as 
> reviewers. I didn't even see @ilya-biryukov participating in the other 
> discussions.

We committed this to unbreak our internal integrate at Google. Integrates are 
time-critical for us, so we normally choose to unbreak early and have 
post-commit discussions instead.
We should have probably communicated this better in commit messages and reviews.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124606

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


[PATCH] D124221: Reimplement `__builtin_dump_struct` in Sema.

2022-05-02 Thread Wang Yihan via Phabricator via cfe-commits
yihanaa added inline comments.



Comment at: clang/lib/Sema/SemaChecking.cpp:427
+llvm::SmallString<32> Indent;
+Indent.resize(Depth * 4, ' ');
+return getStringLiteral(Indent);

What do you think of PrintingPolicy.Indentation here?



Comment at: clang/lib/Sema/SemaChecking.cpp:433
+
+  llvm::StringRef getFormatSpecifier(QualType T) {
+if (auto *BT = T->getAs()) {

I think this is better maintained in "clang/AST/FormatString.h". For example 
analyze_printf::PrintfSpecifier can get format specifier, what do you all think 
about?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124221

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


[PATCH] D124688: [clangd] parse all make_unique-like functions in preamble

2022-05-02 Thread Sam McCall via Phabricator via cfe-commits
sammccall added a comment.

In D124688#3485042 , @nridge wrote:

> In D124688#3483895 , @sammccall 
> wrote:
>
>> Trying this on a few files, this seems like it increases preamble sizes up 
>> to 1% or so
>
> Are preamble sizes a good proxy for preamble build times as well? I suspect 
> that may be the metric that's more noticeable for users.

Agree, yes I **think** they're a pretty good proxy for this sort of change 
which parses more/less code. (Preamble size more or less counting AST nodes).


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124688

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


[clang] 5a2e595 - [analyzer] Fix Static Analyzer g_memdup false-positive

2022-05-02 Thread Balazs Benics via cfe-commits

Author: Balazs Benics
Date: 2022-05-02T10:35:51+02:00
New Revision: 5a2e595eb8337e6e36da8ec2289b5c4097522f5b

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

LOG: [analyzer] Fix Static Analyzer g_memdup false-positive

`g_memdup()` allocates and copies memory, thus we should not assume that
the returned memory region is uninitialized because it might not be the
case.

PS: It would be even better to copy the bindings to mimic the actual
content of the buffer, but this works too.

Fixes #53617

Reviewed By: martong

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

Added: 


Modified: 
clang/lib/StaticAnalyzer/Checkers/MallocChecker.cpp
clang/test/Analysis/gmalloc.c

Removed: 




diff  --git a/clang/lib/StaticAnalyzer/Checkers/MallocChecker.cpp 
b/clang/lib/StaticAnalyzer/Checkers/MallocChecker.cpp
index 0bbef394f43e5..ae9a7bc6a3914 100644
--- a/clang/lib/StaticAnalyzer/Checkers/MallocChecker.cpp
+++ b/clang/lib/StaticAnalyzer/Checkers/MallocChecker.cpp
@@ -1408,8 +1408,8 @@ void MallocChecker::checkGMalloc0(const CallEvent &Call,
 void MallocChecker::checkGMemdup(const CallEvent &Call,
  CheckerContext &C) const {
   ProgramStateRef State = C.getState();
-  State = MallocMemAux(C, Call, Call.getArgExpr(1), UndefinedVal(), State,
-   AF_Malloc);
+  State =
+  MallocMemAux(C, Call, Call.getArgExpr(1), UnknownVal(), State, 
AF_Malloc);
   State = ProcessZeroAllocCheck(Call, 1, State);
   C.addTransition(State);
 }

diff  --git a/clang/test/Analysis/gmalloc.c b/clang/test/Analysis/gmalloc.c
index 51f972856b1bb..240138e8a7a05 100644
--- a/clang/test/Analysis/gmalloc.c
+++ b/clang/test/Analysis/gmalloc.c
@@ -21,6 +21,7 @@ gpointer g_try_malloc0_n(gsize n_blocks, gsize n_block_bytes);
 gpointer g_try_realloc_n(gpointer mem, gsize n_blocks, gsize n_block_bytes);
 void g_free(gpointer mem);
 gpointer g_memdup(gconstpointer mem, guint byte_size);
+gpointer g_strconcat(gconstpointer string1, ...);
 
 static const gsize n_bytes = 1024;
 
@@ -167,3 +168,16 @@ void f7(void) {
   g_free(g6);
   g_free(g7);
 }
+
+void f8(void) {
+  typedef struct {
+gpointer str;
+  } test_struct;
+
+  test_struct *s1 = (test_struct *)g_malloc0(sizeof(test_struct));
+  test_struct *s2 = (test_struct *)g_memdup(s1, sizeof(test_struct));
+  gpointer str = g_strconcat("text", s1->str, s2->str, NULL); // no-warning
+  g_free(str);
+  g_free(s2);
+  g_free(s1);
+}



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


[PATCH] D124436: [analyzer] Fix Static Analyzer g_memdup false-positive

2022-05-02 Thread Balázs Benics via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG5a2e595eb833: [analyzer] Fix Static Analyzer g_memdup 
false-positive (authored by steakhal).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124436

Files:
  clang/lib/StaticAnalyzer/Checkers/MallocChecker.cpp
  clang/test/Analysis/gmalloc.c


Index: clang/test/Analysis/gmalloc.c
===
--- clang/test/Analysis/gmalloc.c
+++ clang/test/Analysis/gmalloc.c
@@ -21,6 +21,7 @@
 gpointer g_try_realloc_n(gpointer mem, gsize n_blocks, gsize n_block_bytes);
 void g_free(gpointer mem);
 gpointer g_memdup(gconstpointer mem, guint byte_size);
+gpointer g_strconcat(gconstpointer string1, ...);
 
 static const gsize n_bytes = 1024;
 
@@ -167,3 +168,16 @@
   g_free(g6);
   g_free(g7);
 }
+
+void f8(void) {
+  typedef struct {
+gpointer str;
+  } test_struct;
+
+  test_struct *s1 = (test_struct *)g_malloc0(sizeof(test_struct));
+  test_struct *s2 = (test_struct *)g_memdup(s1, sizeof(test_struct));
+  gpointer str = g_strconcat("text", s1->str, s2->str, NULL); // no-warning
+  g_free(str);
+  g_free(s2);
+  g_free(s1);
+}
Index: clang/lib/StaticAnalyzer/Checkers/MallocChecker.cpp
===
--- clang/lib/StaticAnalyzer/Checkers/MallocChecker.cpp
+++ clang/lib/StaticAnalyzer/Checkers/MallocChecker.cpp
@@ -1408,8 +1408,8 @@
 void MallocChecker::checkGMemdup(const CallEvent &Call,
  CheckerContext &C) const {
   ProgramStateRef State = C.getState();
-  State = MallocMemAux(C, Call, Call.getArgExpr(1), UndefinedVal(), State,
-   AF_Malloc);
+  State =
+  MallocMemAux(C, Call, Call.getArgExpr(1), UnknownVal(), State, 
AF_Malloc);
   State = ProcessZeroAllocCheck(Call, 1, State);
   C.addTransition(State);
 }


Index: clang/test/Analysis/gmalloc.c
===
--- clang/test/Analysis/gmalloc.c
+++ clang/test/Analysis/gmalloc.c
@@ -21,6 +21,7 @@
 gpointer g_try_realloc_n(gpointer mem, gsize n_blocks, gsize n_block_bytes);
 void g_free(gpointer mem);
 gpointer g_memdup(gconstpointer mem, guint byte_size);
+gpointer g_strconcat(gconstpointer string1, ...);
 
 static const gsize n_bytes = 1024;
 
@@ -167,3 +168,16 @@
   g_free(g6);
   g_free(g7);
 }
+
+void f8(void) {
+  typedef struct {
+gpointer str;
+  } test_struct;
+
+  test_struct *s1 = (test_struct *)g_malloc0(sizeof(test_struct));
+  test_struct *s2 = (test_struct *)g_memdup(s1, sizeof(test_struct));
+  gpointer str = g_strconcat("text", s1->str, s2->str, NULL); // no-warning
+  g_free(str);
+  g_free(s2);
+  g_free(s1);
+}
Index: clang/lib/StaticAnalyzer/Checkers/MallocChecker.cpp
===
--- clang/lib/StaticAnalyzer/Checkers/MallocChecker.cpp
+++ clang/lib/StaticAnalyzer/Checkers/MallocChecker.cpp
@@ -1408,8 +1408,8 @@
 void MallocChecker::checkGMemdup(const CallEvent &Call,
  CheckerContext &C) const {
   ProgramStateRef State = C.getState();
-  State = MallocMemAux(C, Call, Call.getArgExpr(1), UndefinedVal(), State,
-   AF_Malloc);
+  State =
+  MallocMemAux(C, Call, Call.getArgExpr(1), UnknownVal(), State, AF_Malloc);
   State = ProcessZeroAllocCheck(Call, 1, State);
   C.addTransition(State);
 }
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] 464c983 - [analyzer][docs] Document alpha.security.cert.pos.34c limitations

2022-05-02 Thread Balazs Benics via cfe-commits

Author: Balazs Benics
Date: 2022-05-02T10:37:23+02:00
New Revision: 464c9833df8049793232bccb10fea84098499e4a

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

LOG: [analyzer][docs] Document alpha.security.cert.pos.34c limitations

Reviewed By: martong

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

Added: 


Modified: 
clang/docs/analyzer/checkers.rst

Removed: 




diff  --git a/clang/docs/analyzer/checkers.rst 
b/clang/docs/analyzer/checkers.rst
index 2f5336ae6a67f..4b0b53ca8da2b 100644
--- a/clang/docs/analyzer/checkers.rst
+++ b/clang/docs/analyzer/checkers.rst
@@ -2268,6 +2268,25 @@ Finds calls to the ``putenv`` function which pass a 
pointer to an automatic vari
 return putenv(env); // putenv function should not be called with auto 
variables
   }
 
+Limitations:
+
+   - Technically, one can pass automatic variables to ``putenv``,
+ but one needs to ensure that the given environment key stays
+ alive until it's removed or overwritten.
+ Since the analyzer cannot keep track of which envvars get overwritten
+ and when, it needs to be slightly more aggressive and warn for such
+ cases too, leading in some cases to false-positive reports like this:
+
+ .. code-block:: c
+
+void baz() {
+  char env[] = "NAME=value";
+  putenv(env); // false-positive warning: putenv function should not 
be called...
+  // More code...
+  putenv((char *)"NAME=anothervalue");
+  // This putenv call overwrites the previous entry, thus that can no 
longer dangle.
+} // 'env' array becomes dead only here.
+
 alpha.security.cert.env
 ^^^
 



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


[PATCH] D124659: [analyzer][docs] Document alpha.security.cert.pos.34c limitations

2022-05-02 Thread Balázs Benics via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG464c9833df80: [analyzer][docs] Document 
alpha.security.cert.pos.34c limitations (authored by steakhal).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124659

Files:
  clang/docs/analyzer/checkers.rst


Index: clang/docs/analyzer/checkers.rst
===
--- clang/docs/analyzer/checkers.rst
+++ clang/docs/analyzer/checkers.rst
@@ -2268,6 +2268,25 @@
 return putenv(env); // putenv function should not be called with auto 
variables
   }
 
+Limitations:
+
+   - Technically, one can pass automatic variables to ``putenv``,
+ but one needs to ensure that the given environment key stays
+ alive until it's removed or overwritten.
+ Since the analyzer cannot keep track of which envvars get overwritten
+ and when, it needs to be slightly more aggressive and warn for such
+ cases too, leading in some cases to false-positive reports like this:
+
+ .. code-block:: c
+
+void baz() {
+  char env[] = "NAME=value";
+  putenv(env); // false-positive warning: putenv function should not 
be called...
+  // More code...
+  putenv((char *)"NAME=anothervalue");
+  // This putenv call overwrites the previous entry, thus that can no 
longer dangle.
+} // 'env' array becomes dead only here.
+
 alpha.security.cert.env
 ^^^
 


Index: clang/docs/analyzer/checkers.rst
===
--- clang/docs/analyzer/checkers.rst
+++ clang/docs/analyzer/checkers.rst
@@ -2268,6 +2268,25 @@
 return putenv(env); // putenv function should not be called with auto variables
   }
 
+Limitations:
+
+   - Technically, one can pass automatic variables to ``putenv``,
+ but one needs to ensure that the given environment key stays
+ alive until it's removed or overwritten.
+ Since the analyzer cannot keep track of which envvars get overwritten
+ and when, it needs to be slightly more aggressive and warn for such
+ cases too, leading in some cases to false-positive reports like this:
+
+ .. code-block:: c
+
+void baz() {
+  char env[] = "NAME=value";
+  putenv(env); // false-positive warning: putenv function should not be called...
+  // More code...
+  putenv((char *)"NAME=anothervalue");
+  // This putenv call overwrites the previous entry, thus that can no longer dangle.
+} // 'env' array becomes dead only here.
+
 alpha.security.cert.env
 ^^^
 
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] c8603db - [clang-format] Fix a bug that misformats Access Specifier after *[]

2022-05-02 Thread via cfe-commits

Author: owenca
Date: 2022-05-02T01:39:26-07:00
New Revision: c8603db0711e451cecb75c8e10a12e882d4e0b31

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

LOG: [clang-format] Fix a bug that misformats Access Specifier after *[]

Fixes #55132.

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

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 d20cead7d3212..520f73ac15eeb 100644
--- a/clang/lib/Format/UnwrappedLineParser.cpp
+++ b/clang/lib/Format/UnwrappedLineParser.cpp
@@ -2048,6 +2048,11 @@ bool UnwrappedLineParser::tryToParseLambdaIntroducer() {
   nextToken();
   if (FormatTok->is(tok::l_square))
 return false;
+  if (FormatTok->is(tok::r_square)) {
+const FormatToken *Next = Tokens->peekNextToken();
+if (Next && Next->is(tok::greater))
+  return false;
+  }
   parseSquare(/*LambdaIntroducer=*/true);
   return true;
 }

diff  --git a/clang/unittests/Format/FormatTest.cpp 
b/clang/unittests/Format/FormatTest.cpp
index c685fa152281c..da25395b7df49 100644
--- a/clang/unittests/Format/FormatTest.cpp
+++ b/clang/unittests/Format/FormatTest.cpp
@@ -3336,6 +3336,14 @@ TEST_F(FormatTest, UnderstandsAccessSpecifiers) {
   verifyFormat("if (public == private)\n");
   verifyFormat("void foo(public, private)");
   verifyFormat("public::foo();");
+
+  verifyFormat("class A {\n"
+   "public:\n"
+   "  std::unique_ptr b() { return nullptr; }\n"
+   "\n"
+   "private:\n"
+   "  int c;\n"
+   "};");
 }
 
 TEST_F(FormatTest, SeparatesLogicalBlocks) {
@@ -21487,6 +21495,7 @@ TEST_F(FormatTest, FormatsLambdas) {
"  bar([]() {} // Did not respect 
SpacesBeforeTrailingComments\n"
"  );\n"
"}");
+  verifyFormat("auto k = *[](int *j) { return j; }(&i);");
 
   // Lambdas created through weird macros.
   verifyFormat("void f() {\n"



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


[PATCH] D115187: [clangd] Expose CoawaitExpr's operand in the AST

2022-05-02 Thread Nathan Ridge via Phabricator via cfe-commits
nridge updated this revision to Diff 426356.
nridge added a comment.

Handle implicit coawait-exprs properly in RebuildCoawaitExpr, other test fixes


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D115187

Files:
  clang-tools-extra/clangd/unittests/FindTargetTests.cpp
  clang/include/clang/AST/ExprCXX.h
  clang/include/clang/Sema/Sema.h
  clang/lib/Sema/SemaCoroutine.cpp
  clang/lib/Sema/TreeTransform.h
  clang/test/AST/coroutine-locals-cleanup-exp-namespace.cpp
  clang/test/AST/coroutine-locals-cleanup.cpp
  clang/test/AST/coroutine-source-location-crash-exp-namespace.cpp
  clang/test/AST/coroutine-source-location-crash.cpp
  clang/test/SemaCXX/co_await-ast.cpp

Index: clang/test/SemaCXX/co_await-ast.cpp
===
--- /dev/null
+++ clang/test/SemaCXX/co_await-ast.cpp
@@ -0,0 +1,97 @@
+// RUN: %clang_cc1 -std=c++20 -fsyntax-only -ast-dump -ast-dump-filter=foo %s | FileCheck %s --strict-whitespace
+
+namespace std {
+template  struct coroutine_traits;
+template  struct coroutine_handle {
+  template 
+  coroutine_handle(coroutine_handle &&) noexcept;
+  static coroutine_handle from_address(void *__addr) noexcept;
+};
+} // namespace std
+
+struct executor {};
+struct awaitable {};
+struct awaitable_frame {
+  awaitable get_return_object();
+  void return_void();
+  void unhandled_exception();
+  struct result_t {
+~result_t();
+bool await_ready() const noexcept;
+void await_suspend(std::coroutine_handle) noexcept;
+void await_resume() const noexcept;
+  };
+  result_t initial_suspend() noexcept;
+  result_t final_suspend() noexcept;
+  result_t await_transform(executor) noexcept;
+};
+
+namespace std {
+template <>
+struct coroutine_traits {
+  typedef awaitable_frame promise_type;
+};
+} // namespace std
+
+awaitable foo() {
+  co_await executor();
+}
+
+// Check that CoawaitExpr contains the correct subexpressions, including
+// the operand expression as written in the source.
+
+// CHECK-LABEL: Dumping foo:
+// CHECK: FunctionDecl {{.*}} foo 'awaitable ()'
+// CHECK: `-CoroutineBodyStmt {{.*}}
+// CHECK:   |-CompoundStmt {{.*}}
+// CHECK:   | `-ExprWithCleanups {{.*}} 'void'
+// CHECK:   |   `-CoawaitExpr {{.*}} 'void'
+// CHECK:   | |-CXXTemporaryObjectExpr {{.*}} 'executor' 'void () noexcept' zeroing
+// CHECK:   | |-MaterializeTemporaryExpr {{.*}} 'awaitable_frame::result_t' lvalue
+// CHECK:   | | `-CXXBindTemporaryExpr {{.*}} 'awaitable_frame::result_t' (CXXTemporary {{.*}})
+// CHECK:   | |   `-CXXMemberCallExpr {{.*}} 'awaitable_frame::result_t'
+// CHECK:   | | |-MemberExpr {{.*}} '' .await_transform {{.*}}
+// CHECK:   | | | `-DeclRefExpr {{.*}} 'std::coroutine_traits::promise_type':'awaitable_frame' lvalue Var {{.*}} '__promise' 'std::coroutine_traits::promise_type':'awaitable_frame'
+// CHECK:   | | `-CXXTemporaryObjectExpr {{.*}} 'executor' 'void () noexcept' zeroing
+// CHECK:   | |-ExprWithCleanups {{.*}} 'bool'
+// CHECK:   | | `-CXXMemberCallExpr {{.*}} 'bool'
+// CHECK:   | |   `-MemberExpr {{.*}} '' .await_ready {{.*}}
+// CHECK:   | | `-ImplicitCastExpr {{.*}} 'const awaitable_frame::result_t' lvalue 
+// CHECK:   | |   `-OpaqueValueExpr {{.*}} 'awaitable_frame::result_t' lvalue
+// CHECK:   | | `-MaterializeTemporaryExpr {{.*}} 'awaitable_frame::result_t' lvalue
+// CHECK:   | |   `-CXXBindTemporaryExpr {{.*}} 'awaitable_frame::result_t' (CXXTemporary {{.*}})
+// CHECK:   | | `-CXXMemberCallExpr {{.*}} 'awaitable_frame::result_t'
+// CHECK:   | |   |-MemberExpr {{.*}} '' .await_transform {{.*}}
+// CHECK:   | |   | `-DeclRefExpr {{.*}} 'std::coroutine_traits::promise_type':'awaitable_frame' lvalue Var {{.*}} '__promise' 'std::coroutine_traits::promise_type':'awaitable_frame'
+// CHECK:   | |   `-CXXTemporaryObjectExpr {{.*}} 'executor' 'void () noexcept' zeroing
+// CHECK:   | |-ExprWithCleanups {{.*}} 'void'
+// CHECK:   | | `-CXXMemberCallExpr {{.*}} 'void'
+// CHECK:   | |   |-MemberExpr {{.*}} '' .await_suspend {{.*}}
+// CHECK:   | |   | `-OpaqueValueExpr {{.*}} 'awaitable_frame::result_t' lvalue
+// CHECK:   | |   |   `-MaterializeTemporaryExpr {{.*}} 'awaitable_frame::result_t' lvalue
+// CHECK:   | |   | `-CXXBindTemporaryExpr {{.*}} 'awaitable_frame::result_t' (CXXTemporary {{.*}})
+// CHECK:   | |   |   `-CXXMemberCallExpr {{.*}} 'awaitable_frame::result_t'
+// CHECK:   | |   | |-MemberExpr {{.*}} '' .await_transform {{.*}}
+// CHECK:   | |   | | `-DeclRefExpr {{.*}} 'std::coroutine_traits::promise_type':'awaitable_frame' lvalue Var {{.*}} '__promise' 'std::coroutine_traits::promise_type':'awaitable_frame'
+// CHECK:   | |   | `-CXXTemporaryObjectExpr {{.*}} 'executor' 'void () noexcept' zeroin

[PATCH] D124589: [clang-format] Fix a bug that misformats Access Specifier after *[]

2022-05-02 Thread Owen Pan via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rGc8603db0711e: [clang-format] Fix a bug that misformats 
Access Specifier after *[] (authored by owenpan).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124589

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
@@ -3336,6 +3336,14 @@
   verifyFormat("if (public == private)\n");
   verifyFormat("void foo(public, private)");
   verifyFormat("public::foo();");
+
+  verifyFormat("class A {\n"
+   "public:\n"
+   "  std::unique_ptr b() { return nullptr; }\n"
+   "\n"
+   "private:\n"
+   "  int c;\n"
+   "};");
 }
 
 TEST_F(FormatTest, SeparatesLogicalBlocks) {
@@ -21487,6 +21495,7 @@
"  bar([]() {} // Did not respect 
SpacesBeforeTrailingComments\n"
"  );\n"
"}");
+  verifyFormat("auto k = *[](int *j) { return j; }(&i);");
 
   // Lambdas created through weird macros.
   verifyFormat("void f() {\n"
Index: clang/lib/Format/UnwrappedLineParser.cpp
===
--- clang/lib/Format/UnwrappedLineParser.cpp
+++ clang/lib/Format/UnwrappedLineParser.cpp
@@ -2048,6 +2048,11 @@
   nextToken();
   if (FormatTok->is(tok::l_square))
 return false;
+  if (FormatTok->is(tok::r_square)) {
+const FormatToken *Next = Tokens->peekNextToken();
+if (Next && Next->is(tok::greater))
+  return false;
+  }
   parseSquare(/*LambdaIntroducer=*/true);
   return true;
 }


Index: clang/unittests/Format/FormatTest.cpp
===
--- clang/unittests/Format/FormatTest.cpp
+++ clang/unittests/Format/FormatTest.cpp
@@ -3336,6 +3336,14 @@
   verifyFormat("if (public == private)\n");
   verifyFormat("void foo(public, private)");
   verifyFormat("public::foo();");
+
+  verifyFormat("class A {\n"
+   "public:\n"
+   "  std::unique_ptr b() { return nullptr; }\n"
+   "\n"
+   "private:\n"
+   "  int c;\n"
+   "};");
 }
 
 TEST_F(FormatTest, SeparatesLogicalBlocks) {
@@ -21487,6 +21495,7 @@
"  bar([]() {} // Did not respect SpacesBeforeTrailingComments\n"
"  );\n"
"}");
+  verifyFormat("auto k = *[](int *j) { return j; }(&i);");
 
   // Lambdas created through weird macros.
   verifyFormat("void f() {\n"
Index: clang/lib/Format/UnwrappedLineParser.cpp
===
--- clang/lib/Format/UnwrappedLineParser.cpp
+++ clang/lib/Format/UnwrappedLineParser.cpp
@@ -2048,6 +2048,11 @@
   nextToken();
   if (FormatTok->is(tok::l_square))
 return false;
+  if (FormatTok->is(tok::r_square)) {
+const FormatToken *Next = Tokens->peekNextToken();
+if (Next && Next->is(tok::greater))
+  return false;
+  }
   parseSquare(/*LambdaIntroducer=*/true);
   return true;
 }
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D124669: [flang][driver] Add support for -save-temps

2022-05-02 Thread Diana Picus via Phabricator via cfe-commits
rovka added inline comments.



Comment at: clang/include/clang/Driver/Options.td:4131
 def : Flag<["-"], "no-integrated-as">, Alias,
-  Flags<[CC1Option, NoXarchOption]>;
+  Flags<[CC1Option,FlangOption,NoXarchOption]>;
 

awarzynski wrote:
> unterumarmung wrote:
> > Why not to add `FC1Option` here and elsewhere like it's done for 
> > `CC1Option`?
> I'm not 100% sure what `-fno-integrated-as` controls in Clang's frontend 
> driver, `clang -cc1`. I'm guessing that it might related to using/not-using 
> LLVM's MCAsmParser. Perhaps for inline assembly?
> 
> In Flang, I'm only focusing on `-save-temps` for which I need to make sure 
> that we don't try to call `flang-new -fc1as` or something similar (it does 
> not exist). Instead, `-save-temps` will have to rely on an external assembler.
> 
> So, we basically don't require -`fno-integrated-as` in `flang-new -fc1` just 
> yet (that's what `FC1Option` is for - marking an option as available in the 
> frontend driver).
I'm not 100% sure either (haven't looked at the code), but my understanding of 
`-fno-integrated-as` is that it forces clang to call the system assembler as 
opposed to using the LLVM libraries to generate machine code directly. Since 
flang never uses the system assembler, I would say the integrated assembler is 
always on in flang. So I'm not convinced it makes sense to add this flag to the 
driver, unless we're actually adding a 
`-fc1as`.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124669

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


[PATCH] D115187: [clangd] Expose CoawaitExpr's operand in the AST

2022-05-02 Thread Nathan Ridge via Phabricator via cfe-commits
nridge added a comment.

In D115187#3471261 , @sammccall wrote:

> We're not supposed to  transform 
> initial/final suspends, but the code is now doing so.
>
> This seems to be a consequence of switching from BuildResolvedCoawaitExpr 
> (which does not apply the transform) to BuildUnresolvedCoawaitExpr (which 
> does) during template instantiation.

Thanks, this helped me get onto the right track for a fix.

Indeed, we have two different codepaths by which `CoawaitExpr`s are built: 
explicit ones use `BuildUnresolvedCoawaitExpr`, while the implicit ones for the 
suspends use `BuildResolvedCoawaitExpr` with a bit of extra logic before (to 
apply `operator coawait` (but not `await_transform`) if appropriate).

Thankfully, `CoawaitExpr` remembers which kind it is in `isImplicit()`, so it's 
straightforward to get `TreeTransform` to do the right thing based on this flag.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D115187

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


[clang] fd7efe3 - [analyzer] Fix cast evaluation on scoped enums in ExprEngine

2022-05-02 Thread Balazs Benics via cfe-commits

Author: Balazs Benics
Date: 2022-05-02T10:54:26+02:00
New Revision: fd7efe33f1b2d0dc3bce940154dba27413b72e7a

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

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

We ignored the cast if the enum was scoped.
This is bad since there is no implicit conversion from the scoped enum to the 
corresponding underlying type.

The fix is basically: isIntegralOrEnumerationType() -> 
isIntegralOr**Unscoped**EnumerationType()

This materialized in crashes on analyzing the LLVM itself using the Z3 
refutation.
Refutation synthesized the given Z3 Binary expression (`BO_And` of `unsigned 
char` aka. 8 bits
and an `int` 32 bits) with the wrong bitwidth in the end, which triggered an 
assert.

Now, we evaluate the cast according to the standard.

This bug could have been triggered using the Z3 CM according to
https://bugs.llvm.org/show_bug.cgi?id=44030

Fixes #47570 #43375

Reviewed By: martong

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

Added: 
clang/test/Analysis/z3-refute-enum-crash.cpp

Modified: 
clang/lib/StaticAnalyzer/Core/SValBuilder.cpp

Removed: 




diff  --git a/clang/lib/StaticAnalyzer/Core/SValBuilder.cpp 
b/clang/lib/StaticAnalyzer/Core/SValBuilder.cpp
index e045c9a91e60c..12b46426c027d 100644
--- a/clang/lib/StaticAnalyzer/Core/SValBuilder.cpp
+++ b/clang/lib/StaticAnalyzer/Core/SValBuilder.cpp
@@ -983,8 +983,8 @@ SVal SValBuilder::evalCastSubKind(nonloc::SymbolVal V, 
QualType CastTy,
 
 // Produce SymbolCast if CastTy and T are 
diff erent integers.
 // NOTE: In the end the type of SymbolCast shall be equal to CastTy.
-if (T->isIntegralOrEnumerationType() &&
-CastTy->isIntegralOrEnumerationType()) {
+if (T->isIntegralOrUnscopedEnumerationType() &&
+CastTy->isIntegralOrUnscopedEnumerationType()) {
   AnalyzerOptions &Opts =
   StateMgr.getOwningEngine().getAnalysisManager().getAnalyzerOptions();
   // If appropriate option is disabled, ignore the cast.

diff  --git a/clang/test/Analysis/z3-refute-enum-crash.cpp 
b/clang/test/Analysis/z3-refute-enum-crash.cpp
new file mode 100644
index 0..355c10f4e284e
--- /dev/null
+++ b/clang/test/Analysis/z3-refute-enum-crash.cpp
@@ -0,0 +1,77 @@
+// RUN: %clang_analyze_cc1 -analyzer-checker=core,debug.ExprInspection \
+// RUN:   -analyzer-config crosscheck-with-z3=true -verify %s
+//
+// RUN: %clang_analyze_cc1 -analyzer-checker=core,debug.ExprInspection \
+// RUN:   -verify %s
+//
+// RUN: %clang_analyze_cc1 -analyzer-checker=core,debug.ExprInspection \
+// RUN:   -analyzer-config support-symbolic-integer-casts=true 
-verify=symbolic %s
+//
+// RUN: %clang_analyze_cc1 -analyzer-checker=core,debug.ExprInspection \
+// RUN:   -analyzer-config support-symbolic-integer-casts=false -verify %s
+//
+// REQUIRES: asserts, z3
+//
+// Requires z3 only for refutation. Works with both constraint managers.
+
+void clang_analyzer_dump(int);
+
+using sugar_t = unsigned char;
+
+// Enum types
+enum class ScopedSugared : sugar_t {};
+enum class ScopedPrimitive : unsigned char {};
+enum UnscopedSugared : sugar_t {};
+enum UnscopedPrimitive : unsigned char {};
+
+template 
+T conjure();
+
+void test_enum_types() {
+  // Let's construct a 'binop(sym, int)', where the binop will trigger an
+  // integral promotion to int. Note that we need to first explicit cast
+  // the scoped-enum to an integral, to make it compile. We could have choosen
+  // any other binary operator.
+  int sym1 = static_cast(conjure()) & 0x0F;
+  int sym2 = static_cast(conjure()) & 0x0F;
+  int sym3 = static_cast(conjure()) & 0x0F;
+  int sym4 = static_cast(conjure()) & 0x0F;
+
+  // We need to introduce a constraint referring to the binop, to get it
+  // serialized during the z3-refutation.
+  if (sym1 && sym2 && sym3 && sym4) {
+// no-crash on these dumps
+//
+// The 'clang_analyzer_dump' will construct a bugreport, which in turn will
+// trigger a z3-refutation. Refutation will walk the bugpath, collect and
+// serialize the path-constraints into z3 expressions. The binop will
+// operate over 'int' type, but the symbolic operand might have a 
diff erent
+// type - surprisingly.
+// Historically, the static analyzer did not emit symbolic casts in a lot
+// of cases, not even when the c++ standard mandated it, like for casting
+// a scoped enum to its underlying type. Hence, during the z3 constraint
+// serialization, it made up these 'missing' integral casts - for the
+// implicit cases at least.
+// However, it would still not emit the cast for missing explicit casts,
+// hence 8-bit wide symbol would be bitwise 'and'-ed with a 32-bit wide
+// int, violating an assertion stating that the ope

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

2022-05-02 Thread Balázs Benics 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 rGfd7efe33f1b2: [analyzer] Fix cast evaluation on scoped enums 
in ExprEngine (authored by steakhal).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D85528

Files:
  clang/lib/StaticAnalyzer/Core/SValBuilder.cpp
  clang/test/Analysis/z3-refute-enum-crash.cpp


Index: clang/test/Analysis/z3-refute-enum-crash.cpp
===
--- /dev/null
+++ clang/test/Analysis/z3-refute-enum-crash.cpp
@@ -0,0 +1,77 @@
+// RUN: %clang_analyze_cc1 -analyzer-checker=core,debug.ExprInspection \
+// RUN:   -analyzer-config crosscheck-with-z3=true -verify %s
+//
+// RUN: %clang_analyze_cc1 -analyzer-checker=core,debug.ExprInspection \
+// RUN:   -verify %s
+//
+// RUN: %clang_analyze_cc1 -analyzer-checker=core,debug.ExprInspection \
+// RUN:   -analyzer-config support-symbolic-integer-casts=true 
-verify=symbolic %s
+//
+// RUN: %clang_analyze_cc1 -analyzer-checker=core,debug.ExprInspection \
+// RUN:   -analyzer-config support-symbolic-integer-casts=false -verify %s
+//
+// REQUIRES: asserts, z3
+//
+// Requires z3 only for refutation. Works with both constraint managers.
+
+void clang_analyzer_dump(int);
+
+using sugar_t = unsigned char;
+
+// Enum types
+enum class ScopedSugared : sugar_t {};
+enum class ScopedPrimitive : unsigned char {};
+enum UnscopedSugared : sugar_t {};
+enum UnscopedPrimitive : unsigned char {};
+
+template 
+T conjure();
+
+void test_enum_types() {
+  // Let's construct a 'binop(sym, int)', where the binop will trigger an
+  // integral promotion to int. Note that we need to first explicit cast
+  // the scoped-enum to an integral, to make it compile. We could have choosen
+  // any other binary operator.
+  int sym1 = static_cast(conjure()) & 0x0F;
+  int sym2 = static_cast(conjure()) & 0x0F;
+  int sym3 = static_cast(conjure()) & 0x0F;
+  int sym4 = static_cast(conjure()) & 0x0F;
+
+  // We need to introduce a constraint referring to the binop, to get it
+  // serialized during the z3-refutation.
+  if (sym1 && sym2 && sym3 && sym4) {
+// no-crash on these dumps
+//
+// The 'clang_analyzer_dump' will construct a bugreport, which in turn will
+// trigger a z3-refutation. Refutation will walk the bugpath, collect and
+// serialize the path-constraints into z3 expressions. The binop will
+// operate over 'int' type, but the symbolic operand might have a different
+// type - surprisingly.
+// Historically, the static analyzer did not emit symbolic casts in a lot
+// of cases, not even when the c++ standard mandated it, like for casting
+// a scoped enum to its underlying type. Hence, during the z3 constraint
+// serialization, it made up these 'missing' integral casts - for the
+// implicit cases at least.
+// However, it would still not emit the cast for missing explicit casts,
+// hence 8-bit wide symbol would be bitwise 'and'-ed with a 32-bit wide
+// int, violating an assertion stating that the operands should have the
+// same bitwidths.
+
+clang_analyzer_dump(sym1);
+// expected-warning-re@-1 {{((unsigned char) (conj_${{[0-9]+}}{enum 
ScopedSugared, LC{{[0-9]+}}, S{{[0-9]+}}, #{{[0-9]+}}})) & 15}}
+// symbolic-warning-re@-2   {{((int) (conj_${{[0-9]+}}{enum 
ScopedSugared, LC{{[0-9]+}}, S{{[0-9]+}}, #{{[0-9]+}}})) & 15}}
+
+clang_analyzer_dump(sym2);
+// expected-warning-re@-1 {{((unsigned char) (conj_${{[0-9]+}}{enum 
ScopedPrimitive, LC{{[0-9]+}}, S{{[0-9]+}}, #{{[0-9]+}}})) & 15}}
+// symbolic-warning-re@-2   {{((int) (conj_${{[0-9]+}}{enum 
ScopedPrimitive, LC{{[0-9]+}}, S{{[0-9]+}}, #{{[0-9]+}}})) & 15}}
+
+clang_analyzer_dump(sym3);
+// expected-warning-re@-1{{(conj_${{[0-9]+}}{enum UnscopedSugared, 
LC{{[0-9]+}}, S{{[0-9]+}}, #{{[0-9]+}}}) & 15}}
+// symbolic-warning-re@-2 {{((int) (conj_${{[0-9]+}}{enum UnscopedSugared, 
LC{{[0-9]+}}, S{{[0-9]+}}, #{{[0-9]+}}})) & 15}}
+
+clang_analyzer_dump(sym4);
+// expected-warning-re@-1{{(conj_${{[0-9]+}}{enum 
UnscopedPrimitive, LC{{[0-9]+}}, S{{[0-9]+}}, #{{[0-9]+}}}) & 15}}
+// symbolic-warning-re@-2 {{((int) (conj_${{[0-9]+}}{enum 
UnscopedPrimitive, LC{{[0-9]+}}, S{{[0-9]+}}, #{{[0-9]+}}})) & 15}}
+  }
+}
+
Index: clang/lib/StaticAnalyzer/Core/SValBuilder.cpp
===
--- clang/lib/StaticAnalyzer/Core/SValBuilder.cpp
+++ clang/lib/StaticAnalyzer/Core/SValBuilder.cpp
@@ -983,8 +983,8 @@
 
 // Produce SymbolCast if CastTy and T are different integers.
 // NOTE: In the end the type of SymbolCast shall be equal to CastTy.
-if (T->isIntegralOrEnumerationType() &&
-CastTy->isIntegralOrEnumerationType()) {
+if (T->isIntegralOrUnscopedEnumerationType(

[PATCH] D124681: [Analyzer] Minor cleanups in StreamChecker

2022-05-02 Thread Marco Antognini via Phabricator via cfe-commits
mantognini created this revision.
Herald added subscribers: manas, steakhal, ASDenysPetrov, martong, dkrupp, 
donat.nagy, Szelethus, mikhail.ramalho, a.sidorin, szepet, baloghadamsoftware, 
xazax.hun.
Herald added a project: All.
mantognini added reviewers: NoQ, balazske, Szelethus.
mantognini published this revision for review.
mantognini added a comment.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

For reference, the modified code was introduced with 
https://reviews.llvm.org/D80015.

Any feedback is appreciated.


Remove unnecessary conversion to Optional<> and incorrect assumption
that BindExpr can return a null state.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D124681

Files:
  clang/lib/StaticAnalyzer/Checkers/StreamChecker.cpp


Index: clang/lib/StaticAnalyzer/Checkers/StreamChecker.cpp
===
--- clang/lib/StaticAnalyzer/Checkers/StreamChecker.cpp
+++ clang/lib/StaticAnalyzer/Checkers/StreamChecker.cpp
@@ -672,24 +672,19 @@
   if (!IsFread || (OldSS->ErrorState != ErrorFEof)) {
 ProgramStateRef StateNotFailed =
 State->BindExpr(CE, C.getLocationContext(), *NMembVal);
-if (StateNotFailed) {
-  StateNotFailed = StateNotFailed->set(
-  StreamSym, StreamState::getOpened(Desc));
-  C.addTransition(StateNotFailed);
-}
+StateNotFailed =
+StateNotFailed->set(StreamSym, 
StreamState::getOpened(Desc));
+C.addTransition(StateNotFailed);
   }
 
   // Add transition for the failed state.
-  Optional RetVal = makeRetVal(C, CE).castAs();
-  assert(RetVal && "Value should be NonLoc.");
+  NonLoc RetVal = makeRetVal(C, CE).castAs();
   ProgramStateRef StateFailed =
-  State->BindExpr(CE, C.getLocationContext(), *RetVal);
-  if (!StateFailed)
-return;
-  auto Cond = C.getSValBuilder()
-  .evalBinOpNN(State, BO_LT, *RetVal, *NMembVal,
-   C.getASTContext().IntTy)
-  .getAs();
+  State->BindExpr(CE, C.getLocationContext(), RetVal);
+  auto Cond =
+  C.getSValBuilder()
+  .evalBinOpNN(State, BO_LT, RetVal, *NMembVal, 
C.getASTContext().IntTy)
+  .getAs();
   if (!Cond)
 return;
   StateFailed = StateFailed->assume(*Cond, true);


Index: clang/lib/StaticAnalyzer/Checkers/StreamChecker.cpp
===
--- clang/lib/StaticAnalyzer/Checkers/StreamChecker.cpp
+++ clang/lib/StaticAnalyzer/Checkers/StreamChecker.cpp
@@ -672,24 +672,19 @@
   if (!IsFread || (OldSS->ErrorState != ErrorFEof)) {
 ProgramStateRef StateNotFailed =
 State->BindExpr(CE, C.getLocationContext(), *NMembVal);
-if (StateNotFailed) {
-  StateNotFailed = StateNotFailed->set(
-  StreamSym, StreamState::getOpened(Desc));
-  C.addTransition(StateNotFailed);
-}
+StateNotFailed =
+StateNotFailed->set(StreamSym, StreamState::getOpened(Desc));
+C.addTransition(StateNotFailed);
   }
 
   // Add transition for the failed state.
-  Optional RetVal = makeRetVal(C, CE).castAs();
-  assert(RetVal && "Value should be NonLoc.");
+  NonLoc RetVal = makeRetVal(C, CE).castAs();
   ProgramStateRef StateFailed =
-  State->BindExpr(CE, C.getLocationContext(), *RetVal);
-  if (!StateFailed)
-return;
-  auto Cond = C.getSValBuilder()
-  .evalBinOpNN(State, BO_LT, *RetVal, *NMembVal,
-   C.getASTContext().IntTy)
-  .getAs();
+  State->BindExpr(CE, C.getLocationContext(), RetVal);
+  auto Cond =
+  C.getSValBuilder()
+  .evalBinOpNN(State, BO_LT, RetVal, *NMembVal, C.getASTContext().IntTy)
+  .getAs();
   if (!Cond)
 return;
   StateFailed = StateFailed->assume(*Cond, true);
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D124359: [clangd] Add inlay hints for mutable reference parameters

2022-05-02 Thread Nathan Ridge via Phabricator via cfe-commits
nridge accepted this revision.
nridge added a comment.
This revision is now accepted and ready to land.

Thanks!

Final nit: please update the commit message as it's a bit out of date, and then 
I'll go ahead and merge




Comment at: clang-tools-extra/clangd/unittests/InlayHintTests.cpp:168
+void bar() {
+  foo($param[[42]]);
+}

nit: the annotation can be removed


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124359

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


[PATCH] D115187: [clangd] Expose CoawaitExpr's operand in the AST

2022-05-02 Thread Sam McCall via Phabricator via cfe-commits
sammccall accepted this revision.
sammccall added a comment.

Looks good to me - this still seems hairy and abstract to me so I'd "expect the 
unexpected" in terms of bot or downstream breakage...




Comment at: clang/include/clang/Sema/Sema.h:10394
+  UnresolvedLookupExpr *Lookup);
+  ExprResult BuildResolvedCoawaitExpr(SourceLocation KwLoc, Expr *Operand,
+  Expr *E, bool IsImplicit = false);

nit: update param names here



Comment at: clang/lib/Sema/SemaCoroutine.cpp:824
+
+ExprResult Sema::BuildUnresolvedCoawaitExpr(SourceLocation Loc, Expr *Operand,
 UnresolvedLookupExpr *Lookup) {

this name is a bit confusing - the result isn't (necessarily) unresolved, it's 
more like the inputs are resolved.

I don't actually think we should rename it, but maybe add a comment like 
`Attempts to resolve and build a CoAwaitExpr from "raw" inputs, bailing out to 
DependentCoawaitExpr if needed`

(Not caused by this patch, but I feel like the only time to add comments to 
make this less confusing is when we've been digging into it)



Comment at: clang/lib/Sema/TreeTransform.h:1476
 bool IsImplicit) {
-return getSema().BuildResolvedCoawaitExpr(CoawaitLoc, Result, IsImplicit);
+// This function rebuilds a coawait-expr given its operator.
+// For an explicit coawait-expr, the rebuild involves the full set

This is essentially inlining BuildUnresolvedCoawaitExpr, with the 
await_transform logic dropped, right? I wonder how that compares to adding a 
`bool Transform` to that function.

Such a param would make everything less direct, but it also seems possible that 
the two copies could unexpectedly diverge either now (e.g. could the 
"placeholder type" logic from BuildUnresolved be relevant here?) or more likely 
in the future.

Up to you, I don't feel strongly here, it just seems a little surprising.



Comment at: clang/test/AST/coroutine-locals-cleanup-exp-namespace.cpp:88
 // CHECK-NEXT:  CoawaitExpr
-// CHECK-NEXT:MaterializeTemporaryExpr {{.*}} 
'Task::Awaiter':'Task::Awaiter'
+// CHECK-NEXT:CXXBindTemporaryExpr {{.*}} 'Task' (CXXTemporary 
{{.*}})
+// CHECK: MaterializeTemporaryExpr {{.*}} 
'Task::Awaiter':'Task::Awaiter'

nit: I think it'd be nice to include the type here for consistency


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D115187

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


[clang] 5ce7050 - [analyzer] Allow exploded graph dumps in release builds

2022-05-02 Thread Balazs Benics via cfe-commits

Author: Balazs Benics
Date: 2022-05-02T11:42:08+02:00
New Revision: 5ce7050f701c6907cc2522fc43d39a8cbcc119d2

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

LOG: [analyzer] Allow exploded graph dumps in release builds

Historically, exploded graph dumps were disabled in non-debug builds.
It was done so probably because a regular user should not dump the
internal representation of the analyzer anyway and the dump methods
might introduce unnecessary binary size overhead.

It turns out some of the users actually want to dump this.

Note that e.g. `LiveExpressionsDumper`, `LiveVariablesDumper`,
`ControlDependencyTreeDumper` etc. worked previously, and they are
unaffected by this change.
However, `CFGViewer` and `CFGDumper` still won't work for a similar
reason. AFAIK only these two won't work after this change.

Addresses #53873

---

**baseline**

| binary | size | size after strip |
| clang | 103M | 83M |
| clang-tidy | 67M | 54M |

**after this change**

| binary | size | size after strip |
| clang | 103M | 84M |
| clang-tidy | 67M | 54M |

CMake configuration:
```
cmake -S llvm -GNinja -DBUILD_SHARED_LIBS=OFF -DCMAKE_BUILD_TYPE=Release
-DCMAKE_CXX_COMPILER=clang++ -DCMAKE_C_COMPILER=clang
-DLLVM_ENABLE_ASSERTIONS=OFF -DLLVM_USE_LINKER=lld
-DLLVM_ENABLE_DUMP=OFF -DLLVM_ENABLE_PROJECTS="clang;clang-tools-extra"
-DLLVM_ENABLE_Z3_SOLVER=ON -DLLVM_TARGETS_TO_BUILD="X86"
```
Built by `clang-14.0.0`.

Reviewed By: martong

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

Added: 


Modified: 
clang/lib/StaticAnalyzer/Core/ExprEngine.cpp
clang/test/Analysis/dump_egraph.c
clang/test/Analysis/dump_egraph.cpp
clang/test/Analysis/exploded-graph-rewriter/dynamic_types.cpp
clang/test/Analysis/exploded-graph-rewriter/escapes.c

clang/test/Analysis/exploded-graph-rewriter/initializers_under_construction.cpp
clang/test/Analysis/exploded-graph-rewriter/l_name_starts_with_l.cpp
clang/test/Analysis/exploded-graph-rewriter/macros.c
clang/test/Analysis/exploded-graph-rewriter/objects_under_construction.cpp
clang/test/Analysis/exploded-graph-rewriter/win_path_forbidden_chars.cpp

Removed: 




diff  --git a/clang/lib/StaticAnalyzer/Core/ExprEngine.cpp 
b/clang/lib/StaticAnalyzer/Core/ExprEngine.cpp
index ec7ab25311454..e748a3554ea2b 100644
--- a/clang/lib/StaticAnalyzer/Core/ExprEngine.cpp
+++ b/clang/lib/StaticAnalyzer/Core/ExprEngine.cpp
@@ -3119,7 +3119,6 @@ void ExprEngine::VisitMSAsmStmt(const MSAsmStmt *A, 
ExplodedNode *Pred,
 // Visualization.
 
//===--===//
 
-#ifndef NDEBUG
 namespace llvm {
 
 template<>
@@ -3217,29 +3216,18 @@ struct DOTGraphTraits : public 
DefaultDOTGraphTraits {
 };
 
 } // namespace llvm
-#endif
 
 void ExprEngine::ViewGraph(bool trim) {
-#ifndef NDEBUG
   std::string Filename = DumpGraph(trim);
   llvm::DisplayGraph(Filename, false, llvm::GraphProgram::DOT);
-#else
-  llvm::errs() << "Warning: viewing graph requires assertions" << "\n";
-#endif
 }
 
-
-void ExprEngine::ViewGraph(ArrayRef Nodes) {
-#ifndef NDEBUG
+void ExprEngine::ViewGraph(ArrayRef Nodes) {
   std::string Filename = DumpGraph(Nodes);
   llvm::DisplayGraph(Filename, false, llvm::GraphProgram::DOT);
-#else
-  llvm::errs() << "Warning: viewing graph requires assertions" << "\n";
-#endif
 }
 
 std::string ExprEngine::DumpGraph(bool trim, StringRef Filename) {
-#ifndef NDEBUG
   if (trim) {
 std::vector Src;
 
@@ -3254,35 +3242,26 @@ std::string ExprEngine::DumpGraph(bool trim, StringRef 
Filename) {
   Src.push_back(N);
 }
 return DumpGraph(Src, Filename);
-  } else {
-return llvm::WriteGraph(&G, "ExprEngine", /*ShortNames=*/false,
-/*Title=*/"Exploded Graph",
-/*Filename=*/std::string(Filename));
   }
-#else
-  llvm::errs() << "Warning: dumping graph requires assertions" << "\n";
-  return "";
-#endif
+
+  return llvm::WriteGraph(&G, "ExprEngine", /*ShortNames=*/false,
+  /*Title=*/"Exploded Graph",
+  /*Filename=*/std::string(Filename));
 }
 
-std::string ExprEngine::DumpGraph(ArrayRef Nodes,
+std::string ExprEngine::DumpGraph(ArrayRef Nodes,
   StringRef Filename) {
-#ifndef NDEBUG
   std::unique_ptr TrimmedG(G.trim(Nodes));
 
   if (!TrimmedG.get()) {
 llvm::errs() << "warning: Trimmed ExplodedGraph is empty.\n";
 return "";
-  } else {
-return llvm::WriteGraph(TrimmedG.get(), "TrimmedExprEngine",
-/*ShortNames=*/false,
-/*Title=*/"Trimmed Exploded Graph",
-/*Filename=*/std::string(Filename));
-  }
-#else
-  llvm::errs() << "Warning: dumping 

[PATCH] D124442: [analyzer] Allow exploded graph dumps in release builds

2022-05-02 Thread Balázs Benics via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG5ce7050f701c: [analyzer] Allow exploded graph dumps in 
release builds (authored by steakhal).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124442

Files:
  clang/lib/StaticAnalyzer/Core/ExprEngine.cpp
  clang/test/Analysis/dump_egraph.c
  clang/test/Analysis/dump_egraph.cpp
  clang/test/Analysis/exploded-graph-rewriter/dynamic_types.cpp
  clang/test/Analysis/exploded-graph-rewriter/escapes.c
  
clang/test/Analysis/exploded-graph-rewriter/initializers_under_construction.cpp
  clang/test/Analysis/exploded-graph-rewriter/l_name_starts_with_l.cpp
  clang/test/Analysis/exploded-graph-rewriter/macros.c
  clang/test/Analysis/exploded-graph-rewriter/objects_under_construction.cpp
  clang/test/Analysis/exploded-graph-rewriter/win_path_forbidden_chars.cpp

Index: clang/test/Analysis/exploded-graph-rewriter/win_path_forbidden_chars.cpp
===
--- clang/test/Analysis/exploded-graph-rewriter/win_path_forbidden_chars.cpp
+++ clang/test/Analysis/exploded-graph-rewriter/win_path_forbidden_chars.cpp
@@ -3,7 +3,6 @@
 // RUN: -analyzer-checker=core \
 // RUN: -analyzer-dump-egraph=%t.dot %s
 // RUN: %exploded_graph_rewriter --verbose %t.dot 2>&1 | FileCheck %s
-// REQUIRES: asserts
 // UNSUPPORTED: !windows
 
 // Angle brackets shall not be presented in the field `file`,
Index: clang/test/Analysis/exploded-graph-rewriter/objects_under_construction.cpp
===
--- clang/test/Analysis/exploded-graph-rewriter/objects_under_construction.cpp
+++ clang/test/Analysis/exploded-graph-rewriter/objects_under_construction.cpp
@@ -4,7 +4,6 @@
 // RUN: -analyzer-checker=core \
 // RUN: -analyzer-dump-egraph=%t.dot %s
 // RUN: %exploded_graph_rewriter %t.dot | FileCheck %s
-// REQUIRES: asserts
 
 struct S {
   S() {}
Index: clang/test/Analysis/exploded-graph-rewriter/macros.c
===
--- clang/test/Analysis/exploded-graph-rewriter/macros.c
+++ clang/test/Analysis/exploded-graph-rewriter/macros.c
@@ -11,7 +11,6 @@
 // RUN: -analyzer-checker=core \
 // RUN: -analyzer-dump-egraph=%t.dot %s
 // RUN: %exploded_graph_rewriter %t.dot | FileCheck %s
-// REQUIRES: asserts
 
 // CHECK: macros.c:3:10
 // CHECK-SAME: 
Index: clang/test/Analysis/exploded-graph-rewriter/l_name_starts_with_l.cpp
===
--- clang/test/Analysis/exploded-graph-rewriter/l_name_starts_with_l.cpp
+++ clang/test/Analysis/exploded-graph-rewriter/l_name_starts_with_l.cpp
@@ -4,7 +4,6 @@
 // RUN: -analyzer-checker=core \
 // RUN: -analyzer-dump-egraph=%t.dot %s
 // RUN: %exploded_graph_rewriter %t.dot | FileCheck %s
-// REQUIRES: asserts
 
 void test1() {
   // Here __FILE__ macros produces a string with `\` delimiters on Windows
Index: clang/test/Analysis/exploded-graph-rewriter/initializers_under_construction.cpp
===
--- clang/test/Analysis/exploded-graph-rewriter/initializers_under_construction.cpp
+++ clang/test/Analysis/exploded-graph-rewriter/initializers_under_construction.cpp
@@ -3,7 +3,6 @@
 // RUN: -analyzer-checker=core \
 // RUN: -analyzer-dump-egraph=%t.dot %s
 // RUN: %exploded_graph_rewriter %t.dot | FileCheck %s
-// REQUIRES: asserts
 
 struct A {
   A() {}
Index: clang/test/Analysis/exploded-graph-rewriter/escapes.c
===
--- clang/test/Analysis/exploded-graph-rewriter/escapes.c
+++ clang/test/Analysis/exploded-graph-rewriter/escapes.c
@@ -3,7 +3,6 @@
 // RUN: -analyzer-checker=core \
 // RUN: -analyzer-dump-egraph=%t.dot %s
 // RUN: %exploded_graph_rewriter %t.dot | FileCheck %s
-// REQUIRES: asserts
 
 void escapes(void) {
   // CHECK: Store:  (0x{{[0-9a-f]*}})
Index: clang/test/Analysis/exploded-graph-rewriter/dynamic_types.cpp
===
--- clang/test/Analysis/exploded-graph-rewriter/dynamic_types.cpp
+++ clang/test/Analysis/exploded-graph-rewriter/dynamic_types.cpp
@@ -3,7 +3,6 @@
 // RUN: -analyzer-checker=core \
 // RUN: -analyzer-dump-egraph=%t.dot %s
 // RUN: %exploded_graph_rewriter %t.dot | FileCheck %s
-// REQUIRES: asserts
 
 struct S {};
 
Index: clang/test/Analysis/dump_egraph.cpp
===
--- clang/test/Analysis/dump_egraph.cpp
+++ clang/test/Analysis/dump_egraph.cpp
@@ -1,6 +1,5 @@
 // RUN: %clang_analyze_cc1 -analyze

[clang] 29dff0d - [analyzer] Allow CFG dumps in release builds

2022-05-02 Thread Balazs Benics via cfe-commits

Author: Balazs Benics
Date: 2022-05-02T11:48:52+02:00
New Revision: 29dff0d4fb46fe8f1e9774fd5e64d3e07937ff35

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

LOG: [analyzer] Allow CFG dumps in release builds

This is a similar commit to D124442, but for CFG dumps.
The binary size diff remained the same demonstrated in that patch.

This time I'm adding tests for demonstrating that all the dump debug
checkers work - even in regular builds without asserts.

Reviewed By: martong

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

Added: 
clang/test/Analysis/debug-checkers.cpp

Modified: 
clang/lib/Analysis/CFG.cpp

Removed: 




diff  --git a/clang/lib/Analysis/CFG.cpp b/clang/lib/Analysis/CFG.cpp
index c80e4bcd7e89d..53d43bfa07b45 100644
--- a/clang/lib/Analysis/CFG.cpp
+++ b/clang/lib/Analysis/CFG.cpp
@@ -6127,17 +6127,13 @@ Stmt *CFGBlock::getTerminatorCondition(bool 
StripParens) {
 // CFG Graphviz Visualization
 
//===--===//
 
-#ifndef NDEBUG
-static StmtPrinterHelper* GraphHelper;
-#endif
+static StmtPrinterHelper *GraphHelper;
 
 void CFG::viewCFG(const LangOptions &LO) const {
-#ifndef NDEBUG
   StmtPrinterHelper H(this, LO);
   GraphHelper = &H;
   llvm::ViewGraph(this,"CFG");
   GraphHelper = nullptr;
-#endif
 }
 
 namespace llvm {
@@ -6146,8 +6142,7 @@ template<>
 struct DOTGraphTraits : public DefaultDOTGraphTraits {
   DOTGraphTraits(bool isSimple = false) : DefaultDOTGraphTraits(isSimple) {}
 
-  static std::string getNodeLabel(const CFGBlock *Node, const CFG* Graph) {
-#ifndef NDEBUG
+  static std::string getNodeLabel(const CFGBlock *Node, const CFG *Graph) {
 std::string OutSStr;
 llvm::raw_string_ostream Out(OutSStr);
 print_block(Out,Graph, *Node, *GraphHelper, false, false);
@@ -6163,9 +6158,6 @@ struct DOTGraphTraits : public 
DefaultDOTGraphTraits {
   }
 
 return OutStr;
-#else
-return {};
-#endif
   }
 };
 

diff  --git a/clang/test/Analysis/debug-checkers.cpp 
b/clang/test/Analysis/debug-checkers.cpp
new file mode 100644
index 0..234edd762503a
--- /dev/null
+++ b/clang/test/Analysis/debug-checkers.cpp
@@ -0,0 +1,51 @@
+// RUN: %clang_analyze_cc1 -analyzer-checker=core,debug.DumpDominators %s > %t 
2>&1
+// RUN: FileCheck --input-file=%t %s -check-prefix=DOM-CHECK
+// DOM-CHECK: Immediate dominance tree (Node#,IDom#)
+
+// RUN: %clang_analyze_cc1 -analyzer-checker=core,debug.DumpPostDominators %s 
> %t 2>&1
+// RUN: FileCheck --input-file=%t %s -check-prefix=POSTDOM-CHECK
+// POSTDOM-CHECK: Immediate post dominance tree (Node#,IDom#)
+
+// RUN: %clang_analyze_cc1 
-analyzer-checker=core,debug.DumpControlDependencies %s > %t 2>&1
+// RUN: FileCheck --input-file=%t %s -check-prefix=CTRLDEPS-CHECK
+// CTRLDEPS-CHECK: Control dependencies (Node#,Dependency#)
+
+// RUN: %clang_analyze_cc1 -analyzer-checker=core,debug.DumpLiveVars %s > %t 
2>&1
+// RUN: FileCheck --input-file=%t %s -check-prefix=LIVE-VARS-CHECK
+// LIVE-VARS-CHECK: live variables at block exit
+
+// RUN: %clang_analyze_cc1 -analyzer-checker=core,debug.DumpLiveExprs %s > %t 
2>&1
+// RUN: FileCheck --input-file=%t %s -check-prefix=LIVE-EXPRS-CHECK
+// LIVE-EXPRS-CHECK: live expressions at block exit
+
+// Skip testing CFGViewer.
+
+// RUN: %clang_analyze_cc1 -analyzer-checker=core,debug.DumpCFG %s > %t 2>&1
+// RUN: FileCheck --input-file=%t %s -check-prefix=CFG-CHECK
+// CFG-CHECK: ENTRY
+
+// Skip testing CallGraphViewer.
+
+// RUN: %clang_analyze_cc1 -analyzer-checker=core,debug.DumpCallGraph %s > %t 
2>&1
+// RUN: FileCheck --input-file=%t %s -check-prefix=CALL-GRAPH-CHECK
+// CALL-GRAPH-CHECK: --- Call graph Dump ---
+
+// RUN: %clang_analyze_cc1 -analyzer-checker=core,debug.ConfigDumper %s > %t 
2>&1
+// RUN: FileCheck --input-file=%t %s -check-prefix=CONFIG-CHECK
+// CONFIG-CHECK: [config]
+
+// Skip testing ExplodedGraphViewer.
+
+// RUN: %clang_analyze_cc1 -analyzer-checker=core,debug.ReportStmts %s > %t 
2>&1
+// RUN: FileCheck --input-file=%t %s -check-prefix=REPORT-STMTS-CHECK
+// REPORT-STMTS-CHECK: warning: Statement
+
+void foo(int *p) {
+  *p = 3;
+}
+
+int bar() {
+  int x;
+  foo(&x);
+  return x;
+}



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


[PATCH] D124443: [analyzer] Allow CFG dumps in release builds

2022-05-02 Thread Balázs Benics via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG29dff0d4fb46: [analyzer] Allow CFG dumps in release builds 
(authored by steakhal).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124443

Files:
  clang/lib/Analysis/CFG.cpp
  clang/test/Analysis/debug-checkers.cpp


Index: clang/test/Analysis/debug-checkers.cpp
===
--- /dev/null
+++ clang/test/Analysis/debug-checkers.cpp
@@ -0,0 +1,51 @@
+// RUN: %clang_analyze_cc1 -analyzer-checker=core,debug.DumpDominators %s > %t 
2>&1
+// RUN: FileCheck --input-file=%t %s -check-prefix=DOM-CHECK
+// DOM-CHECK: Immediate dominance tree (Node#,IDom#)
+
+// RUN: %clang_analyze_cc1 -analyzer-checker=core,debug.DumpPostDominators %s 
> %t 2>&1
+// RUN: FileCheck --input-file=%t %s -check-prefix=POSTDOM-CHECK
+// POSTDOM-CHECK: Immediate post dominance tree (Node#,IDom#)
+
+// RUN: %clang_analyze_cc1 
-analyzer-checker=core,debug.DumpControlDependencies %s > %t 2>&1
+// RUN: FileCheck --input-file=%t %s -check-prefix=CTRLDEPS-CHECK
+// CTRLDEPS-CHECK: Control dependencies (Node#,Dependency#)
+
+// RUN: %clang_analyze_cc1 -analyzer-checker=core,debug.DumpLiveVars %s > %t 
2>&1
+// RUN: FileCheck --input-file=%t %s -check-prefix=LIVE-VARS-CHECK
+// LIVE-VARS-CHECK: live variables at block exit
+
+// RUN: %clang_analyze_cc1 -analyzer-checker=core,debug.DumpLiveExprs %s > %t 
2>&1
+// RUN: FileCheck --input-file=%t %s -check-prefix=LIVE-EXPRS-CHECK
+// LIVE-EXPRS-CHECK: live expressions at block exit
+
+// Skip testing CFGViewer.
+
+// RUN: %clang_analyze_cc1 -analyzer-checker=core,debug.DumpCFG %s > %t 2>&1
+// RUN: FileCheck --input-file=%t %s -check-prefix=CFG-CHECK
+// CFG-CHECK: ENTRY
+
+// Skip testing CallGraphViewer.
+
+// RUN: %clang_analyze_cc1 -analyzer-checker=core,debug.DumpCallGraph %s > %t 
2>&1
+// RUN: FileCheck --input-file=%t %s -check-prefix=CALL-GRAPH-CHECK
+// CALL-GRAPH-CHECK: --- Call graph Dump ---
+
+// RUN: %clang_analyze_cc1 -analyzer-checker=core,debug.ConfigDumper %s > %t 
2>&1
+// RUN: FileCheck --input-file=%t %s -check-prefix=CONFIG-CHECK
+// CONFIG-CHECK: [config]
+
+// Skip testing ExplodedGraphViewer.
+
+// RUN: %clang_analyze_cc1 -analyzer-checker=core,debug.ReportStmts %s > %t 
2>&1
+// RUN: FileCheck --input-file=%t %s -check-prefix=REPORT-STMTS-CHECK
+// REPORT-STMTS-CHECK: warning: Statement
+
+void foo(int *p) {
+  *p = 3;
+}
+
+int bar() {
+  int x;
+  foo(&x);
+  return x;
+}
Index: clang/lib/Analysis/CFG.cpp
===
--- clang/lib/Analysis/CFG.cpp
+++ clang/lib/Analysis/CFG.cpp
@@ -6127,17 +6127,13 @@
 // CFG Graphviz Visualization
 
//===--===//
 
-#ifndef NDEBUG
-static StmtPrinterHelper* GraphHelper;
-#endif
+static StmtPrinterHelper *GraphHelper;
 
 void CFG::viewCFG(const LangOptions &LO) const {
-#ifndef NDEBUG
   StmtPrinterHelper H(this, LO);
   GraphHelper = &H;
   llvm::ViewGraph(this,"CFG");
   GraphHelper = nullptr;
-#endif
 }
 
 namespace llvm {
@@ -6146,8 +6142,7 @@
 struct DOTGraphTraits : public DefaultDOTGraphTraits {
   DOTGraphTraits(bool isSimple = false) : DefaultDOTGraphTraits(isSimple) {}
 
-  static std::string getNodeLabel(const CFGBlock *Node, const CFG* Graph) {
-#ifndef NDEBUG
+  static std::string getNodeLabel(const CFGBlock *Node, const CFG *Graph) {
 std::string OutSStr;
 llvm::raw_string_ostream Out(OutSStr);
 print_block(Out,Graph, *Node, *GraphHelper, false, false);
@@ -6163,9 +6158,6 @@
   }
 
 return OutStr;
-#else
-return {};
-#endif
   }
 };
 


Index: clang/test/Analysis/debug-checkers.cpp
===
--- /dev/null
+++ clang/test/Analysis/debug-checkers.cpp
@@ -0,0 +1,51 @@
+// RUN: %clang_analyze_cc1 -analyzer-checker=core,debug.DumpDominators %s > %t 2>&1
+// RUN: FileCheck --input-file=%t %s -check-prefix=DOM-CHECK
+// DOM-CHECK: Immediate dominance tree (Node#,IDom#)
+
+// RUN: %clang_analyze_cc1 -analyzer-checker=core,debug.DumpPostDominators %s > %t 2>&1
+// RUN: FileCheck --input-file=%t %s -check-prefix=POSTDOM-CHECK
+// POSTDOM-CHECK: Immediate post dominance tree (Node#,IDom#)
+
+// RUN: %clang_analyze_cc1 -analyzer-checker=core,debug.DumpControlDependencies %s > %t 2>&1
+// RUN: FileCheck --input-file=%t %s -check-prefix=CTRLDEPS-CHECK
+// CTRLDEPS-CHECK: Control dependencies (Node#,Dependency#)
+
+// RUN: %clang_analyze_cc1 -analyzer-checker=core,debug.DumpLiveVars %s > %t 2>&1
+// RUN: FileCheck --input-file=%t %s -check-prefix=LIVE-VARS-CHECK
+// LIVE-VARS-CHECK: live variables at block exit
+
+// RUN: %clang_analyze_cc1 -analyzer-checker=core,debug.DumpLiveExprs %s > %t 2>&1
+// RUN: FileCheck --input-file=%t %s -check-prefix=LIVE-EXPRS-CHECK
+// LIVE-EXPRS-CHECK: live expressions at bloc

[clang] a23291b - [Clang] Add integer add reduction builtin

2022-05-02 Thread Simon Pilgrim via cfe-commits

Author: Simon Pilgrim
Date: 2022-05-02T11:03:25+01:00
New Revision: a23291b7db48670f7c57adcfb45877c826a97f22

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

LOG: [Clang] Add integer add reduction builtin

Similar to the existing bitwise reduction builtins, this lowers to a 
llvm.vector.reduce.add intrinsic call.

For other reductions, we've tried to share builtins for float/integer vectors, 
but the fadd reduction intrinsics also take a starting value argument and can 
either do unordered or serialized, but not reduction-trees as specified for the 
builtins. However we address fadd support this shouldn't affect the integer 
case.

(Split off from D117829)

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

Added: 


Modified: 
clang/include/clang/Basic/Builtins.def
clang/lib/CodeGen/CGBuiltin.cpp
clang/lib/Sema/SemaChecking.cpp
clang/test/CodeGen/builtins-reduction-math.c
clang/test/Sema/builtins-reduction-math.c

Removed: 




diff  --git a/clang/include/clang/Basic/Builtins.def 
b/clang/include/clang/Basic/Builtins.def
index c22957e14de7d..e86475b0e2602 100644
--- a/clang/include/clang/Basic/Builtins.def
+++ b/clang/include/clang/Basic/Builtins.def
@@ -663,6 +663,7 @@ BUILTIN(__builtin_reduce_min, "v.", "nct")
 BUILTIN(__builtin_reduce_xor, "v.", "nct")
 BUILTIN(__builtin_reduce_or, "v.", "nct")
 BUILTIN(__builtin_reduce_and, "v.", "nct")
+BUILTIN(__builtin_reduce_add, "v.", "nct")
 
 BUILTIN(__builtin_matrix_transpose, "v.", "nFt")
 BUILTIN(__builtin_matrix_column_major_load, "v.", "nFt")

diff  --git a/clang/lib/CodeGen/CGBuiltin.cpp b/clang/lib/CodeGen/CGBuiltin.cpp
index 70fd869e5c67f..4c203904a0e0e 100644
--- a/clang/lib/CodeGen/CGBuiltin.cpp
+++ b/clang/lib/CodeGen/CGBuiltin.cpp
@@ -3273,6 +3273,9 @@ RValue CodeGenFunction::EmitBuiltinExpr(const GlobalDecl 
GD, unsigned BuiltinID,
 *this, E, GetIntrinsicID(E->getArg(0)->getType()), "rdx.min"));
   }
 
+  case Builtin::BI__builtin_reduce_add:
+return RValue::get(emitUnaryBuiltin(
+*this, E, llvm::Intrinsic::vector_reduce_add, "rdx.add"));
   case Builtin::BI__builtin_reduce_xor:
 return RValue::get(emitUnaryBuiltin(
 *this, E, llvm::Intrinsic::vector_reduce_xor, "rdx.xor"));

diff  --git a/clang/lib/Sema/SemaChecking.cpp b/clang/lib/Sema/SemaChecking.cpp
index 467edd3321b9d..18387c2411852 100644
--- a/clang/lib/Sema/SemaChecking.cpp
+++ b/clang/lib/Sema/SemaChecking.cpp
@@ -2331,6 +2331,8 @@ Sema::CheckBuiltinFunctionCall(FunctionDecl *FDecl, 
unsigned BuiltinID,
   }
 
   // These builtins support vectors of integers only.
+  // TODO: ADD should support floating-point types.
+  case Builtin::BI__builtin_reduce_add:
   case Builtin::BI__builtin_reduce_xor:
   case Builtin::BI__builtin_reduce_or:
   case Builtin::BI__builtin_reduce_and: {

diff  --git a/clang/test/CodeGen/builtins-reduction-math.c 
b/clang/test/CodeGen/builtins-reduction-math.c
index f5fbd0c2b6803..2988a318eb6c6 100644
--- a/clang/test/CodeGen/builtins-reduction-math.c
+++ b/clang/test/CodeGen/builtins-reduction-math.c
@@ -58,6 +58,28 @@ void test_builtin_reduce_min(float4 vf1, si8 vi1, u4 vu1) {
   unsigned long long r5 = __builtin_reduce_min(cvi1);
 }
 
+void test_builtin_reduce_add(si8 vi1, u4 vu1) {
+  // CHECK:  [[VI1:%.+]] = load <8 x i16>, <8 x i16>* %vi1.addr, align 16
+  // CHECK-NEXT: call i16 @llvm.vector.reduce.add.v8i16(<8 x i16> [[VI1]])
+  short r2 = __builtin_reduce_add(vi1);
+
+  // CHECK:  [[VU1:%.+]] = load <4 x i32>, <4 x i32>* %vu1.addr, align 16
+  // CHECK-NEXT: call i32 @llvm.vector.reduce.add.v4i32(<4 x i32> [[VU1]])
+  unsigned r3 = __builtin_reduce_add(vu1);
+
+  // CHECK:  [[CVI1:%.+]] = load <8 x i16>, <8 x i16>* %cvi1, align 16
+  // CHECK-NEXT: [[RDX1:%.+]] = call i16 @llvm.vector.reduce.add.v8i16(<8 x 
i16> [[CVI1]])
+  // CHECK-NEXT: sext i16 [[RDX1]] to i32
+  const si8 cvi1 = vi1;
+  int r4 = __builtin_reduce_add(cvi1);
+
+  // CHECK:  [[CVU1:%.+]] = load <4 x i32>, <4 x i32>* %cvu1, align 16
+  // CHECK-NEXT: [[RDX2:%.+]] = call i32 @llvm.vector.reduce.add.v4i32(<4 x 
i32> [[CVU1]])
+  // CHECK-NEXT: zext i32 [[RDX2]] to i64
+  const u4 cvu1 = vu1;
+  unsigned long long r5 = __builtin_reduce_add(cvu1);
+}
+
 void test_builtin_reduce_xor(si8 vi1, u4 vu1) {
 
   // CHECK:  [[VI1:%.+]] = load <8 x i16>, <8 x i16>* %vi1.addr, align 16

diff  --git a/clang/test/Sema/builtins-reduction-math.c 
b/clang/test/Sema/builtins-reduction-math.c
index a729226056032..10c95a1e531bb 100644
--- a/clang/test/Sema/builtins-reduction-math.c
+++ b/clang/test/Sema/builtins-reduction-math.c
@@ -36,6 +36,23 @@ void test_builtin_reduce_min(int i, float4 v, int3 iv) {
   // expected-error@-1 {{1st argument must be a vector type (was 'int')}}
 }
 
+void test_builtin_reduce_

[PATCH] D124221: Reimplement `__builtin_dump_struct` in Sema.

2022-05-02 Thread Wang Yihan via Phabricator via cfe-commits
yihanaa added inline comments.



Comment at: clang/docs/ReleaseNotes.rst:174
   - Improve the dump format, dump both bitwidth(if its a bitfield) and field 
value.
-  - Remove anonymous tag locations.
-  - Beautify dump format, add indent for nested struct and struct members.
+  - Remove anonymous tag locations and flatten anonymous struct members.
+  - Beautify dump format, add indent for struct members.

I tried it, D124221 will still generate anonymous tag locations, this place 
needs to be corrected, or removed anonymous tag locations.

int main() {
  struct U20A {
_Bool a;
unsigned : 32;
struct {
  int x;
  int y;
} c;
  };

  struct U20A a = {
  .a = 1,
  .c.x = 1998
  };
__builtin_dump_struct(&a, printf);
}

struct U20A {
_Bool a = 1
struct (unnamed struct at ./builtin_dump_struct.c:10:5) c = {
int x = 1998
int y = 0
}
}


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124221

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


[PATCH] D124741: [Clang] Add integer add reduction builtin

2022-05-02 Thread Simon Pilgrim via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rGa23291b7db48: [Clang] Add integer add reduction builtin 
(authored by RKSimon).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124741

Files:
  clang/include/clang/Basic/Builtins.def
  clang/lib/CodeGen/CGBuiltin.cpp
  clang/lib/Sema/SemaChecking.cpp
  clang/test/CodeGen/builtins-reduction-math.c
  clang/test/Sema/builtins-reduction-math.c


Index: clang/test/Sema/builtins-reduction-math.c
===
--- clang/test/Sema/builtins-reduction-math.c
+++ clang/test/Sema/builtins-reduction-math.c
@@ -36,6 +36,23 @@
   // expected-error@-1 {{1st argument must be a vector type (was 'int')}}
 }
 
+void test_builtin_reduce_add(int i, float4 v, int3 iv) {
+  struct Foo s = __builtin_reduce_add(iv);
+  // expected-error@-1 {{initializing 'struct Foo' with an expression of 
incompatible type 'int'}}
+
+  i = __builtin_reduce_add();
+  // expected-error@-1 {{too few arguments to function call, expected 1, have 
0}}
+
+  i = __builtin_reduce_add(iv, iv);
+  // expected-error@-1 {{too many arguments to function call, expected 1, have 
2}}
+
+  i = __builtin_reduce_add(i);
+  // expected-error@-1 {{1st argument must be a vector of integers (was 
'int')}}
+
+  i = __builtin_reduce_add(v);
+  // expected-error@-1 {{1st argument must be a vector of integers (was 
'float4' (vector of 4 'float' values))}}
+}
+
 void test_builtin_reduce_xor(int i, float4 v, int3 iv) {
   struct Foo s = __builtin_reduce_xor(iv);
   // expected-error@-1 {{initializing 'struct Foo' with an expression of 
incompatible type 'int'}}
Index: clang/test/CodeGen/builtins-reduction-math.c
===
--- clang/test/CodeGen/builtins-reduction-math.c
+++ clang/test/CodeGen/builtins-reduction-math.c
@@ -58,6 +58,28 @@
   unsigned long long r5 = __builtin_reduce_min(cvi1);
 }
 
+void test_builtin_reduce_add(si8 vi1, u4 vu1) {
+  // CHECK:  [[VI1:%.+]] = load <8 x i16>, <8 x i16>* %vi1.addr, align 16
+  // CHECK-NEXT: call i16 @llvm.vector.reduce.add.v8i16(<8 x i16> [[VI1]])
+  short r2 = __builtin_reduce_add(vi1);
+
+  // CHECK:  [[VU1:%.+]] = load <4 x i32>, <4 x i32>* %vu1.addr, align 16
+  // CHECK-NEXT: call i32 @llvm.vector.reduce.add.v4i32(<4 x i32> [[VU1]])
+  unsigned r3 = __builtin_reduce_add(vu1);
+
+  // CHECK:  [[CVI1:%.+]] = load <8 x i16>, <8 x i16>* %cvi1, align 16
+  // CHECK-NEXT: [[RDX1:%.+]] = call i16 @llvm.vector.reduce.add.v8i16(<8 x 
i16> [[CVI1]])
+  // CHECK-NEXT: sext i16 [[RDX1]] to i32
+  const si8 cvi1 = vi1;
+  int r4 = __builtin_reduce_add(cvi1);
+
+  // CHECK:  [[CVU1:%.+]] = load <4 x i32>, <4 x i32>* %cvu1, align 16
+  // CHECK-NEXT: [[RDX2:%.+]] = call i32 @llvm.vector.reduce.add.v4i32(<4 x 
i32> [[CVU1]])
+  // CHECK-NEXT: zext i32 [[RDX2]] to i64
+  const u4 cvu1 = vu1;
+  unsigned long long r5 = __builtin_reduce_add(cvu1);
+}
+
 void test_builtin_reduce_xor(si8 vi1, u4 vu1) {
 
   // CHECK:  [[VI1:%.+]] = load <8 x i16>, <8 x i16>* %vi1.addr, align 16
Index: clang/lib/Sema/SemaChecking.cpp
===
--- clang/lib/Sema/SemaChecking.cpp
+++ clang/lib/Sema/SemaChecking.cpp
@@ -2331,6 +2331,8 @@
   }
 
   // These builtins support vectors of integers only.
+  // TODO: ADD should support floating-point types.
+  case Builtin::BI__builtin_reduce_add:
   case Builtin::BI__builtin_reduce_xor:
   case Builtin::BI__builtin_reduce_or:
   case Builtin::BI__builtin_reduce_and: {
Index: clang/lib/CodeGen/CGBuiltin.cpp
===
--- clang/lib/CodeGen/CGBuiltin.cpp
+++ clang/lib/CodeGen/CGBuiltin.cpp
@@ -3273,6 +3273,9 @@
 *this, E, GetIntrinsicID(E->getArg(0)->getType()), "rdx.min"));
   }
 
+  case Builtin::BI__builtin_reduce_add:
+return RValue::get(emitUnaryBuiltin(
+*this, E, llvm::Intrinsic::vector_reduce_add, "rdx.add"));
   case Builtin::BI__builtin_reduce_xor:
 return RValue::get(emitUnaryBuiltin(
 *this, E, llvm::Intrinsic::vector_reduce_xor, "rdx.xor"));
Index: clang/include/clang/Basic/Builtins.def
===
--- clang/include/clang/Basic/Builtins.def
+++ clang/include/clang/Basic/Builtins.def
@@ -663,6 +663,7 @@
 BUILTIN(__builtin_reduce_xor, "v.", "nct")
 BUILTIN(__builtin_reduce_or, "v.", "nct")
 BUILTIN(__builtin_reduce_and, "v.", "nct")
+BUILTIN(__builtin_reduce_add, "v.", "nct")
 
 BUILTIN(__builtin_matrix_transpose, "v.", "nFt")
 BUILTIN(__builtin_matrix_column_major_load, "v.", "nFt")


Index: clang/test/Sema/builtins-reduction-math.c
===
--- clang/test/Sema/builtins-reduction-math.c
+++ clang/test/Sema/builtins-reduction-math.c
@@ -36,6 +36,23 @@
 

[PATCH] D117829: [Clang] Add integer mul reduction builtin

2022-05-02 Thread Simon Pilgrim via Phabricator via cfe-commits
RKSimon updated this revision to Diff 426366.
RKSimon retitled this revision from "[Clang] Add integer add/mul reduction 
builtins" to "[Clang] Add integer mul reduction builtin".
RKSimon edited the summary of this revision.
RKSimon added a comment.

Just handle the mul case now that D124741  
has landed


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D117829

Files:
  clang/include/clang/Basic/Builtins.def
  clang/lib/CodeGen/CGBuiltin.cpp
  clang/lib/Sema/SemaChecking.cpp
  clang/test/CodeGen/builtins-reduction-math.c
  clang/test/Sema/builtins-reduction-math.c

Index: clang/test/Sema/builtins-reduction-math.c
===
--- clang/test/Sema/builtins-reduction-math.c
+++ clang/test/Sema/builtins-reduction-math.c
@@ -53,6 +53,23 @@
   // expected-error@-1 {{1st argument must be a vector of integers (was 'float4' (vector of 4 'float' values))}}
 }
 
+void test_builtin_reduce_mul(int i, float4 v, int3 iv) {
+  struct Foo s = __builtin_reduce_mul(iv);
+  // expected-error@-1 {{initializing 'struct Foo' with an expression of incompatible type 'int'}}
+
+  i = __builtin_reduce_mul();
+  // expected-error@-1 {{too few arguments to function call, expected 1, have 0}}
+
+  i = __builtin_reduce_mul(iv, iv);
+  // expected-error@-1 {{too many arguments to function call, expected 1, have 2}}
+
+  i = __builtin_reduce_mul(i);
+  // expected-error@-1 {{1st argument must be a vector of integers (was 'int')}}
+
+  i = __builtin_reduce_mul(v);
+  // expected-error@-1 {{1st argument must be a vector of integers (was 'float4' (vector of 4 'float' values))}}
+}
+
 void test_builtin_reduce_xor(int i, float4 v, int3 iv) {
   struct Foo s = __builtin_reduce_xor(iv);
   // expected-error@-1 {{initializing 'struct Foo' with an expression of incompatible type 'int'}}
Index: clang/test/CodeGen/builtins-reduction-math.c
===
--- clang/test/CodeGen/builtins-reduction-math.c
+++ clang/test/CodeGen/builtins-reduction-math.c
@@ -80,6 +80,28 @@
   unsigned long long r5 = __builtin_reduce_add(cvu1);
 }
 
+void test_builtin_reduce_mul(si8 vi1, u4 vu1) {
+  // CHECK:  [[VI1:%.+]] = load <8 x i16>, <8 x i16>* %vi1.addr, align 16
+  // CHECK-NEXT: call i16 @llvm.vector.reduce.mul.v8i16(<8 x i16> [[VI1]])
+  short r2 = __builtin_reduce_mul(vi1);
+
+  // CHECK:  [[VU1:%.+]] = load <4 x i32>, <4 x i32>* %vu1.addr, align 16
+  // CHECK-NEXT: call i32 @llvm.vector.reduce.mul.v4i32(<4 x i32> [[VU1]])
+  unsigned r3 = __builtin_reduce_mul(vu1);
+
+  // CHECK:  [[CVI1:%.+]] = load <8 x i16>, <8 x i16>* %cvi1, align 16
+  // CHECK-NEXT: [[RDX1:%.+]] = call i16 @llvm.vector.reduce.mul.v8i16(<8 x i16> [[CVI1]])
+  // CHECK-NEXT: sext i16 [[RDX1]] to i32
+  const si8 cvi1 = vi1;
+  int r4 = __builtin_reduce_mul(cvi1);
+
+  // CHECK:  [[CVU1:%.+]] = load <4 x i32>, <4 x i32>* %cvu1, align 16
+  // CHECK-NEXT: [[RDX2:%.+]] = call i32 @llvm.vector.reduce.mul.v4i32(<4 x i32> [[CVU1]])
+  // CHECK-NEXT: zext i32 [[RDX2]] to i64
+  const u4 cvu1 = vu1;
+  unsigned long long r5 = __builtin_reduce_mul(cvu1);
+}
+
 void test_builtin_reduce_xor(si8 vi1, u4 vu1) {
 
   // CHECK:  [[VI1:%.+]] = load <8 x i16>, <8 x i16>* %vi1.addr, align 16
Index: clang/lib/Sema/SemaChecking.cpp
===
--- clang/lib/Sema/SemaChecking.cpp
+++ clang/lib/Sema/SemaChecking.cpp
@@ -2331,8 +2331,9 @@
   }
 
   // These builtins support vectors of integers only.
-  // TODO: ADD should support floating-point types.
+  // TODO: ADD/MUL should support floating-point types.
   case Builtin::BI__builtin_reduce_add:
+  case Builtin::BI__builtin_reduce_mul:
   case Builtin::BI__builtin_reduce_xor:
   case Builtin::BI__builtin_reduce_or:
   case Builtin::BI__builtin_reduce_and: {
Index: clang/lib/CodeGen/CGBuiltin.cpp
===
--- clang/lib/CodeGen/CGBuiltin.cpp
+++ clang/lib/CodeGen/CGBuiltin.cpp
@@ -3276,6 +3276,9 @@
   case Builtin::BI__builtin_reduce_add:
 return RValue::get(emitUnaryBuiltin(
 *this, E, llvm::Intrinsic::vector_reduce_add, "rdx.add"));
+  case Builtin::BI__builtin_reduce_mul:
+return RValue::get(emitUnaryBuiltin(
+*this, E, llvm::Intrinsic::vector_reduce_mul, "rdx.mul"));
   case Builtin::BI__builtin_reduce_xor:
 return RValue::get(emitUnaryBuiltin(
 *this, E, llvm::Intrinsic::vector_reduce_xor, "rdx.xor"));
Index: clang/include/clang/Basic/Builtins.def
===
--- clang/include/clang/Basic/Builtins.def
+++ clang/include/clang/Basic/Builtins.def
@@ -664,6 +664,7 @@
 BUILTIN(__builtin_reduce_or, "v.", "nct")
 BUILTIN(__builtin_reduce_and, "v.", "nct")
 BUILTIN(__builtin_reduce_add, "v.", "nct")
+BUILTIN(__builtin

[PATCH] D117829: [Clang] Add integer mul reduction builtin

2022-05-02 Thread Simon Pilgrim via Phabricator via cfe-commits
RKSimon updated this revision to Diff 426367.
RKSimon added a comment.

Add "__builtin_reduce_mul" to the docs listing supported reductions


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D117829

Files:
  clang/docs/LanguageExtensions.rst
  clang/include/clang/Basic/Builtins.def
  clang/lib/CodeGen/CGBuiltin.cpp
  clang/lib/Sema/SemaChecking.cpp
  clang/test/CodeGen/builtins-reduction-math.c
  clang/test/Sema/builtins-reduction-math.c

Index: clang/test/Sema/builtins-reduction-math.c
===
--- clang/test/Sema/builtins-reduction-math.c
+++ clang/test/Sema/builtins-reduction-math.c
@@ -53,6 +53,23 @@
   // expected-error@-1 {{1st argument must be a vector of integers (was 'float4' (vector of 4 'float' values))}}
 }
 
+void test_builtin_reduce_mul(int i, float4 v, int3 iv) {
+  struct Foo s = __builtin_reduce_mul(iv);
+  // expected-error@-1 {{initializing 'struct Foo' with an expression of incompatible type 'int'}}
+
+  i = __builtin_reduce_mul();
+  // expected-error@-1 {{too few arguments to function call, expected 1, have 0}}
+
+  i = __builtin_reduce_mul(iv, iv);
+  // expected-error@-1 {{too many arguments to function call, expected 1, have 2}}
+
+  i = __builtin_reduce_mul(i);
+  // expected-error@-1 {{1st argument must be a vector of integers (was 'int')}}
+
+  i = __builtin_reduce_mul(v);
+  // expected-error@-1 {{1st argument must be a vector of integers (was 'float4' (vector of 4 'float' values))}}
+}
+
 void test_builtin_reduce_xor(int i, float4 v, int3 iv) {
   struct Foo s = __builtin_reduce_xor(iv);
   // expected-error@-1 {{initializing 'struct Foo' with an expression of incompatible type 'int'}}
Index: clang/test/CodeGen/builtins-reduction-math.c
===
--- clang/test/CodeGen/builtins-reduction-math.c
+++ clang/test/CodeGen/builtins-reduction-math.c
@@ -80,6 +80,28 @@
   unsigned long long r5 = __builtin_reduce_add(cvu1);
 }
 
+void test_builtin_reduce_mul(si8 vi1, u4 vu1) {
+  // CHECK:  [[VI1:%.+]] = load <8 x i16>, <8 x i16>* %vi1.addr, align 16
+  // CHECK-NEXT: call i16 @llvm.vector.reduce.mul.v8i16(<8 x i16> [[VI1]])
+  short r2 = __builtin_reduce_mul(vi1);
+
+  // CHECK:  [[VU1:%.+]] = load <4 x i32>, <4 x i32>* %vu1.addr, align 16
+  // CHECK-NEXT: call i32 @llvm.vector.reduce.mul.v4i32(<4 x i32> [[VU1]])
+  unsigned r3 = __builtin_reduce_mul(vu1);
+
+  // CHECK:  [[CVI1:%.+]] = load <8 x i16>, <8 x i16>* %cvi1, align 16
+  // CHECK-NEXT: [[RDX1:%.+]] = call i16 @llvm.vector.reduce.mul.v8i16(<8 x i16> [[CVI1]])
+  // CHECK-NEXT: sext i16 [[RDX1]] to i32
+  const si8 cvi1 = vi1;
+  int r4 = __builtin_reduce_mul(cvi1);
+
+  // CHECK:  [[CVU1:%.+]] = load <4 x i32>, <4 x i32>* %cvu1, align 16
+  // CHECK-NEXT: [[RDX2:%.+]] = call i32 @llvm.vector.reduce.mul.v4i32(<4 x i32> [[CVU1]])
+  // CHECK-NEXT: zext i32 [[RDX2]] to i64
+  const u4 cvu1 = vu1;
+  unsigned long long r5 = __builtin_reduce_mul(cvu1);
+}
+
 void test_builtin_reduce_xor(si8 vi1, u4 vu1) {
 
   // CHECK:  [[VI1:%.+]] = load <8 x i16>, <8 x i16>* %vi1.addr, align 16
Index: clang/lib/Sema/SemaChecking.cpp
===
--- clang/lib/Sema/SemaChecking.cpp
+++ clang/lib/Sema/SemaChecking.cpp
@@ -2331,8 +2331,9 @@
   }
 
   // These builtins support vectors of integers only.
-  // TODO: ADD should support floating-point types.
+  // TODO: ADD/MUL should support floating-point types.
   case Builtin::BI__builtin_reduce_add:
+  case Builtin::BI__builtin_reduce_mul:
   case Builtin::BI__builtin_reduce_xor:
   case Builtin::BI__builtin_reduce_or:
   case Builtin::BI__builtin_reduce_and: {
Index: clang/lib/CodeGen/CGBuiltin.cpp
===
--- clang/lib/CodeGen/CGBuiltin.cpp
+++ clang/lib/CodeGen/CGBuiltin.cpp
@@ -3276,6 +3276,9 @@
   case Builtin::BI__builtin_reduce_add:
 return RValue::get(emitUnaryBuiltin(
 *this, E, llvm::Intrinsic::vector_reduce_add, "rdx.add"));
+  case Builtin::BI__builtin_reduce_mul:
+return RValue::get(emitUnaryBuiltin(
+*this, E, llvm::Intrinsic::vector_reduce_mul, "rdx.mul"));
   case Builtin::BI__builtin_reduce_xor:
 return RValue::get(emitUnaryBuiltin(
 *this, E, llvm::Intrinsic::vector_reduce_xor, "rdx.xor"));
Index: clang/include/clang/Basic/Builtins.def
===
--- clang/include/clang/Basic/Builtins.def
+++ clang/include/clang/Basic/Builtins.def
@@ -664,6 +664,7 @@
 BUILTIN(__builtin_reduce_or, "v.", "nct")
 BUILTIN(__builtin_reduce_and, "v.", "nct")
 BUILTIN(__builtin_reduce_add, "v.", "nct")
+BUILTIN(__builtin_reduce_mul, "v.", "nct")
 
 BUILTIN(__builtin_matrix_transpose, "v.", "nFt")
 BUILTIN(__builtin_matrix_column_major_load, "v.", "nFt")
Index: clang/docs/LanguageEx

[PATCH] D124701: [clang] Honor __attribute__((no_builtin("foo"))) on functions

2022-05-02 Thread Hans Wennborg via Phabricator via cfe-commits
hans added a comment.

If I understand correctly, D68028  made it so 
that LLVM doesn't add any builtin calls (e.g. turning for-loops into memcpy), 
but Clang could still turn calls into builtins. Maybe the patch description 
could be expanded to explain this?




Comment at: clang/lib/CodeGen/CGExpr.cpp:5219
+// function.
+else if (!CGF.CurFn->getAttributes().hasFnAttr(AttributeNoBuiltin))
   return CGCallee::forBuiltin(builtinID, FD);

What if CurFn has the "wildcard" no-builtins attribute?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124701

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


[PATCH] D109467: [analyzer] check for std::__addressof for inner pointer checker

2022-05-02 Thread Gabor Marton via Phabricator via cfe-commits
martong accepted this revision.
martong added a comment.
This revision is now accepted and ready to land.

LGTM


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D109467

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


[PATCH] D124359: [clangd] Add inlay hints for mutable reference parameters

2022-05-02 Thread Tobias Ribizel via Phabricator via cfe-commits
upsj updated this revision to Diff 426372.
upsj marked an inline comment as done.
upsj added a comment.

remove unnecessary annotation


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124359

Files:
  clang-tools-extra/clangd/InlayHints.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
@@ -138,6 +138,38 @@
   )cpp");
 }
 
+TEST(ParameterHints, NoNameConstReference) {
+  // No hint for anonymous const l-value ref parameter.
+  assertParameterHints(R"cpp(
+void foo(const int&);
+void bar() {
+  foo(42);
+}
+  )cpp");
+}
+
+TEST(ParameterHints, NoNameReference) {
+  // Reference hint for anonymous l-value ref parameter.
+  assertParameterHints(R"cpp(
+void foo(int&);
+void bar() {
+  int i;
+  foo($param[[i]]);
+}
+  )cpp",
+   ExpectedHint{"&: ", "param"});
+}
+
+TEST(ParameterHints, NoNameRValueReference) {
+  // No reference hint for anonymous r-value ref parameter.
+  assertParameterHints(R"cpp(
+void foo(int&&);
+void bar() {
+  foo(42);
+}
+  )cpp");
+}
+
 TEST(ParameterHints, NameInDefinition) {
   // Parameter name picked up from definition if necessary.
   assertParameterHints(R"cpp(
@@ -162,6 +194,66 @@
ExpectedHint{"good: ", "good"});
 }
 
+TEST(ParameterHints, NameConstReference) {
+  // Only name hint for const l-value ref parameter.
+  assertParameterHints(R"cpp(
+void foo(const int& param);
+void bar() {
+  foo($param[[42]]);
+}
+  )cpp",
+   ExpectedHint{"param: ", "param"});
+}
+
+TEST(ParameterHints, NameTypeAliasConstReference) {
+  // Only name hint for const l-value ref parameter via type alias.
+  assertParameterHints(R"cpp(
+using alias = const int&;
+void foo(alias param);
+void bar() {
+  int i;
+  foo($param[[i]]);
+}
+  )cpp",
+   ExpectedHint{"param: ", "param"});
+}
+
+TEST(ParameterHints, NameReference) {
+  // Reference and name hint for l-value ref parameter.
+  assertParameterHints(R"cpp(
+void foo(int& param);
+void bar() {
+  int i;
+  foo($param[[i]]);
+}
+  )cpp",
+   ExpectedHint{"¶m: ", "param"});
+}
+
+TEST(ParameterHints, NameTypeAliasReference) {
+  // Reference and name hint for l-value ref parameter via type alias.
+  assertParameterHints(R"cpp(
+using alias = int&;
+void foo(alias param);
+void bar() {
+  int i;
+  foo($param[[i]]);
+}
+  )cpp",
+   ExpectedHint{"¶m: ", "param"});
+}
+
+TEST(ParameterHints, NameRValueReference) {
+  // Only name hint for r-value ref parameter.
+  assertParameterHints(R"cpp(
+void foo(int&& param);
+void bar() {
+  foo($param[[42]]);
+}
+  )cpp",
+   ExpectedHint{"param: ", "param"});
+}
+
 TEST(ParameterHints, Operator) {
   // No hint for operator call with operator syntax.
   assertParameterHints(R"cpp(
@@ -301,6 +393,21 @@
ExpectedHint{"param: ", "param"});
 }
 
+TEST(ParameterHints, ArgMatchesParamReference) {
+  assertParameterHints(R"cpp(
+void foo(int& param);
+void foo2(const int& param);
+void bar() {
+  int param;
+  // show reference hint on mutable reference
+  foo($param[[param]]);
+  // but not on const reference
+  foo2(param);
+}
+  )cpp",
+   ExpectedHint{"&: ", "param"});
+}
+
 TEST(ParameterHints, LeadingUnderscore) {
   assertParameterHints(R"cpp(
 void foo(int p1, int _p2, int __p3);
Index: clang-tools-extra/clangd/InlayHints.cpp
===
--- clang-tools-extra/clangd/InlayHints.cpp
+++ clang-tools-extra/clangd/InlayHints.cpp
@@ -10,6 +10,7 @@
 #include "Config.h"
 #include "HeuristicResolver.h"
 #include "ParsedAST.h"
+#include "clang/AST/Decl.h"
 #include "clang/AST/DeclarationName.h"
 #include "clang/AST/ExprCXX.h"
 #include "clang/AST/RecursiveASTVisitor.h"
@@ -392,6 +393,7 @@
 // Don't show hints for variadic parameters.
 size_t FixedParamCount = getFixedParamCount(Callee);
 size_t ArgCount = std::min(FixedParamCount, Args.size());
+auto Params = Callee->parameters();
 
 NameVec ParameterNames = chooseParameterNames(Callee, ArgCount);
 
@@ -402,12 +404,14 @@
 
 for (size_t I = 0; I < ArgCount; ++I) {
   StringRef Name = ParameterNames[I];
-  if (!shouldHint(Args[I], Name))
-continue;
+  bool NameHint = shouldHintName(Args[I], Name);
+  bool ReferenceHint = shouldHintReference(Params[I]);
 
-  addInlayHint(Args[I]->getSourceRange(), HintSide::Left,
-   InlayHintKind::Parameter

[PATCH] D124757: [X86] Replace avx512f integer add reduction builtins with generic builtin

2022-05-02 Thread Simon Pilgrim via Phabricator via cfe-commits
RKSimon created this revision.
RKSimon added reviewers: pengfei, craig.topper.
Herald added a subscriber: StephenFan.
Herald added a project: All.
RKSimon requested review of this revision.
Herald added a project: clang.

D124741  added the generic 
"__builtin_reduce_add" which we can use to replace the x86 specific integer add 
reduction builtins - internally these were mapping to the same intrinsic 
already so there are no test changes required.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D124757

Files:
  clang/include/clang/Basic/BuiltinsX86.def
  clang/lib/CodeGen/CGBuiltin.cpp
  clang/lib/Headers/avx512fintrin.h


Index: clang/lib/Headers/avx512fintrin.h
===
--- clang/lib/Headers/avx512fintrin.h
+++ clang/lib/Headers/avx512fintrin.h
@@ -9319,7 +9319,7 @@
  */
 
 static __inline__ long long __DEFAULT_FN_ATTRS512 
_mm512_reduce_add_epi64(__m512i __W) {
-  return __builtin_ia32_reduce_add_q512(__W);
+  return __builtin_reduce_add((__v8di)__W);
 }
 
 static __inline__ long long __DEFAULT_FN_ATTRS512 
_mm512_reduce_mul_epi64(__m512i __W) {
@@ -9337,7 +9337,7 @@
 static __inline__ long long __DEFAULT_FN_ATTRS512
 _mm512_mask_reduce_add_epi64(__mmask8 __M, __m512i __W) {
   __W = _mm512_maskz_mov_epi64(__M, __W);
-  return __builtin_ia32_reduce_add_q512(__W);
+  return __builtin_reduce_add((__v8di)__W);
 }
 
 static __inline__ long long __DEFAULT_FN_ATTRS512
@@ -9383,7 +9383,7 @@
 
 static __inline__ int __DEFAULT_FN_ATTRS512
 _mm512_reduce_add_epi32(__m512i __W) {
-  return __builtin_ia32_reduce_add_d512((__v16si)__W);
+  return __builtin_reduce_add((__v16si)__W);
 }
 
 static __inline__ int __DEFAULT_FN_ATTRS512
@@ -9404,7 +9404,7 @@
 static __inline__ int __DEFAULT_FN_ATTRS512
 _mm512_mask_reduce_add_epi32( __mmask16 __M, __m512i __W) {
   __W = _mm512_maskz_mov_epi32(__M, __W);
-  return __builtin_ia32_reduce_add_d512((__v16si)__W);
+  return __builtin_reduce_add((__v16si)__W);
 }
 
 static __inline__ int __DEFAULT_FN_ATTRS512
Index: clang/lib/CodeGen/CGBuiltin.cpp
===
--- clang/lib/CodeGen/CGBuiltin.cpp
+++ clang/lib/CodeGen/CGBuiltin.cpp
@@ -14496,12 +14496,6 @@
 return EmitX86FunnelShift(*this, Ops[1], Ops[0], Ops[2], true);
 
   // Reductions
-  case X86::BI__builtin_ia32_reduce_add_d512:
-  case X86::BI__builtin_ia32_reduce_add_q512: {
-Function *F =
-CGM.getIntrinsic(Intrinsic::vector_reduce_add, Ops[0]->getType());
-return Builder.CreateCall(F, {Ops[0]});
-  }
   case X86::BI__builtin_ia32_reduce_fadd_pd512:
   case X86::BI__builtin_ia32_reduce_fadd_ps512:
   case X86::BI__builtin_ia32_reduce_fadd_ph512:
Index: clang/include/clang/Basic/BuiltinsX86.def
===
--- clang/include/clang/Basic/BuiltinsX86.def
+++ clang/include/clang/Basic/BuiltinsX86.def
@@ -1990,8 +1990,6 @@
 TARGET_BUILTIN(__builtin_ia32_selectsd_128, "V2dUcV2dV2d", "ncV:128:", 
"avx512f")
 
 // generic reduction intrinsics
-TARGET_BUILTIN(__builtin_ia32_reduce_add_d512, "iV16i", "ncV:512:", "avx512f")
-TARGET_BUILTIN(__builtin_ia32_reduce_add_q512, "OiV8Oi", "ncV:512:", "avx512f")
 TARGET_BUILTIN(__builtin_ia32_reduce_fadd_pd512, "ddV8d", "ncV:512:", 
"avx512f")
 TARGET_BUILTIN(__builtin_ia32_reduce_fadd_ps512, "ffV16f", "ncV:512:", 
"avx512f")
 TARGET_BUILTIN(__builtin_ia32_reduce_fadd_ph512, "xxV32x", "ncV:512:", 
"avx512fp16")


Index: clang/lib/Headers/avx512fintrin.h
===
--- clang/lib/Headers/avx512fintrin.h
+++ clang/lib/Headers/avx512fintrin.h
@@ -9319,7 +9319,7 @@
  */
 
 static __inline__ long long __DEFAULT_FN_ATTRS512 _mm512_reduce_add_epi64(__m512i __W) {
-  return __builtin_ia32_reduce_add_q512(__W);
+  return __builtin_reduce_add((__v8di)__W);
 }
 
 static __inline__ long long __DEFAULT_FN_ATTRS512 _mm512_reduce_mul_epi64(__m512i __W) {
@@ -9337,7 +9337,7 @@
 static __inline__ long long __DEFAULT_FN_ATTRS512
 _mm512_mask_reduce_add_epi64(__mmask8 __M, __m512i __W) {
   __W = _mm512_maskz_mov_epi64(__M, __W);
-  return __builtin_ia32_reduce_add_q512(__W);
+  return __builtin_reduce_add((__v8di)__W);
 }
 
 static __inline__ long long __DEFAULT_FN_ATTRS512
@@ -9383,7 +9383,7 @@
 
 static __inline__ int __DEFAULT_FN_ATTRS512
 _mm512_reduce_add_epi32(__m512i __W) {
-  return __builtin_ia32_reduce_add_d512((__v16si)__W);
+  return __builtin_reduce_add((__v16si)__W);
 }
 
 static __inline__ int __DEFAULT_FN_ATTRS512
@@ -9404,7 +9404,7 @@
 static __inline__ int __DEFAULT_FN_ATTRS512
 _mm512_mask_reduce_add_epi32( __mmask16 __M, __m512i __W) {
   __W = _mm512_maskz_mov_epi32(__M, __W);
-  return __builtin_ia32_reduce_add_d512((__v16si)__W);
+  return __builtin_reduce_add((__v16si)__W);
 }
 
 static __inline__ int __DEFAULT_FN_ATTRS512
Index: clang/lib/CodeGen/CGBuiltin.cpp
===

[PATCH] D124681: [Analyzer] Minor cleanups in StreamChecker

2022-05-02 Thread Balázs Benics via Phabricator via cfe-commits
steakhal accepted this revision.
steakhal added a comment.
This revision is now accepted and ready to land.

Looks great, thanks. Land it.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124681

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


[PATCH] D124701: [clang] Honor __attribute__((no_builtin("foo"))) on functions

2022-05-02 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman added a comment.

FWIW, it looks like precommit CI found issues in the newly added test which 
should be addressed.




Comment at: clang/test/CodeGen/no-builtin-2.c:3
+
+#include 
+

You shouldn't include system headers -- that will pull from whatever is 
installed on the test system. If you included this for `size_t`, you can do 
something like: `typedef __typeof_(sizeof(0)) size_t;` to work around it.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124701

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


[PATCH] D124758: [analyzer] Implement assume in terms of assumeDual

2022-05-02 Thread Gabor Marton via Phabricator via cfe-commits
martong created this revision.
martong added reviewers: NoQ, steakhal, ASDenysPetrov.
Herald added subscribers: manas, gamesh411, dkrupp, donat.nagy, Szelethus, 
mikhail.ramalho, a.sidorin, rnkovacs, szepet, baloghadamsoftware, xazax.hun.
Herald added a reviewer: Szelethus.
Herald added a project: All.
martong requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

By evaluating both children states, now we are capable of discovering
infeasible parent states. In this patch, `assume` is implemented in the terms
of `assumeDual`. This might be suboptimal (e.g. where there are adjacent
assume(true) and assume(false) calls, next patches addresses that). This patch
fixes a real CRASH.
Fixes https://github.com/llvm/llvm-project/issues/54272


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D124758

Files:
  clang/include/clang/StaticAnalyzer/Core/PathSensitive/ConstraintManager.h
  
clang/include/clang/StaticAnalyzer/Core/PathSensitive/SimpleConstraintManager.h
  clang/lib/StaticAnalyzer/Core/ConstraintManager.cpp
  clang/lib/StaticAnalyzer/Core/SimpleConstraintManager.cpp
  clang/test/Analysis/infeasible-crash.c
  clang/test/Analysis/infeasible-sink.c
  clang/test/Analysis/sink-infeasible.c

Index: clang/test/Analysis/sink-infeasible.c
===
--- /dev/null
+++ clang/test/Analysis/sink-infeasible.c
@@ -1,59 +0,0 @@
-// RUN: %clang_analyze_cc1 %s \
-// RUN:   -analyzer-checker=core \
-// RUN:   -analyzer-checker=debug.ExprInspection \
-// RUN:   -analyzer-config eagerly-assume=false \
-// RUN:   -verify
-
-// Here we test that if it turns out that the parent state is infeasible then
-// both children States (more precisely the ExplodedNodes) are marked as a
-// Sink.
-// We rely on an existing defect of the underlying constraint solver. However,
-// in the future we might strengthen the solver to discover the infeasibility
-// right when we create the parent state. At that point this test will fail,
-// and either we shall find another solver weakness to have this test case
-// functioning, or we shall simply remove this test.
-
-void clang_analyzer_warnIfReached();
-void clang_analyzer_eval(int);
-
-int a, b, c, d, e;
-void f() {
-
-  if (a == 0)
-return;
-
-  if (e != c)
-return;
-
-  d = e - c;
-  b = d;
-  a -= d;
-
-  if (a != 0)
-return;
-
-  clang_analyzer_warnIfReached(); // expected-warning{{REACHABLE}}
-
-  /* The BASELINE passes these checks ('wrning' is used to avoid lit to match)
-  // The parent state is already infeasible, look at this contradiction:
-  clang_analyzer_eval(b > 0);  // expected-wrning{{FALSE}}
-  clang_analyzer_eval(b <= 0); // expected-wrning{{FALSE}}
-  // Crashes with expensive checks.
-  if (b > 0) {
-clang_analyzer_warnIfReached(); // no-warning, OK
-return;
-  }
-  // Should not be reachable.
-  clang_analyzer_warnIfReached(); // expected-wrning{{REACHABLE}}
-  */
-
-  // The parent state is already infeasible, but we realize that only if b is
-  // constrained.
-  clang_analyzer_eval(b > 0);  // expected-warning{{UNKNOWN}}
-  clang_analyzer_eval(b <= 0); // expected-warning{{UNKNOWN}}
-  if (b > 0) {
-clang_analyzer_warnIfReached(); // no-warning
-return;
-  }
-  clang_analyzer_warnIfReached(); // no-warning
-}
Index: clang/test/Analysis/infeasible-crash.c
===
--- /dev/null
+++ clang/test/Analysis/infeasible-crash.c
@@ -0,0 +1,38 @@
+// RUN: %clang_analyze_cc1 %s \
+// RUN:   -analyzer-checker=core \
+// RUN:   -analyzer-checker=alpha.unix.cstring.OutOfBounds,alpha.unix.cstring.UninitializedRead \
+// RUN:   -analyzer-checker=debug.ExprInspection \
+// RUN:   -analyzer-config eagerly-assume=false \
+// RUN:   -verify
+
+// expected-no-diagnostics
+
+void *memmove(void *, const void *, unsigned long);
+
+typedef struct {
+  char a[1024];
+} b;
+int c;
+b *invalidate();
+int d() {
+  b *a = invalidate();
+  if (c < 1024)
+return 0;
+  int f = c & ~3, g = f;
+  g--;
+  if (g)
+return 0;
+
+  // Parent state is already infeasible.
+  // clang_analyzer_printState();
+  // "constraints": [
+  //   { "symbol": "(derived_$3{conj_$0{int, LC1, S728, #1},c}) & -4", "range": "{ [1, 1] }" },
+  //   { "symbol": "derived_$3{conj_$0{int, LC1, S728, #1},c}", "range": "{ [1024, 2147483647] }" }
+  // ],
+
+  // This sould not crash!
+  // It crashes in baseline, since there both true and false states are nullptr!
+  memmove(a->a, &a->a[f], c - f);
+
+  return 0;
+}
Index: clang/lib/StaticAnalyzer/Core/SimpleConstraintManager.cpp
===
--- clang/lib/StaticAnalyzer/Core/SimpleConstraintManager.cpp
+++ clang/lib/StaticAnalyzer/Core/SimpleConstraintManager.cpp
@@ -22,9 +22,9 @@
 
 SimpleConstraintManager::~SimpleConstraintManager() {}
 
-ProgramStateRef SimpleConstraintManager::assume(ProgramStateRef State,
-

[PATCH] D92160: [clang] Fix wrong FDs are used for files with same name in Tooling

2022-05-02 Thread Kale Chen via Phabricator via cfe-commits
Kale added a comment.
Herald added a subscriber: StephenFan.
Herald added a project: All.

In D92160#2449507 , @dexonsmith wrote:

> But it's possible we don't need this. If it's safe for us to update the tests 
> and make `FileManager::getFileRef` always canonicalize to an absolute path, 
> that would definitely be cleaner. `FileManager::makeAbsolute` can use 
> whatever the FS's CWD is at the time of query... nice and clean.

I've tried to fix this bug through this way but found that "making 
`FileManager::getFileRef` always canonicalize to an absolute path" was pretty 
hard, because there are many test cases using states stored in FileManager and 
assuming that they are all in relative form. Besides, the assumption that "the 
CWD won't change" indeed is correct by design and works fine for single 
compiler execution. We might not change that unless for a strong necessity.

So I personally believed that this bug is caused by libtooling's incorrect use 
of `FileManger`. I plan to fix it by implementing a class like 
`LibtoolingFileManager`, or `AbsoluteFileManager`, which extends the original 
`FileManager` and using abs path as key to store the status of seen files, but 
only used for libtooling.

I will try to upload a patch later to verify the possibility.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D92160

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


[PATCH] D124758: [analyzer] Implement assume in terms of assumeDual

2022-05-02 Thread Gabor Marton via Phabricator via cfe-commits
martong added a comment.

Although there is a visible slowdown, the new run-times seem promising. My 
guess is that it is usually not more than 1-2%.

F22955239: image.png 

Full report: F22955251: stats.html 


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124758

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


[PATCH] D124761: [analyzer] Replace adjacent assumeInBound calls to assumeInBoundDual

2022-05-02 Thread Gabor Marton via Phabricator via cfe-commits
martong created this revision.
martong added reviewers: NoQ, steakhal, ASDenysPetrov.
Herald added subscribers: manas, gamesh411, dkrupp, donat.nagy, Szelethus, 
mikhail.ramalho, a.sidorin, rnkovacs, szepet, baloghadamsoftware, xazax.hun.
Herald added a reviewer: Szelethus.
Herald added a project: All.
martong requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

This is to minimize superfluous assume calls.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D124761

Files:
  clang/include/clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h
  clang/lib/StaticAnalyzer/Checkers/ArrayBoundChecker.cpp
  clang/lib/StaticAnalyzer/Checkers/CStringChecker.cpp
  clang/lib/StaticAnalyzer/Checkers/ObjCContainersChecker.cpp
  clang/lib/StaticAnalyzer/Checkers/ReturnPointerRangeChecker.cpp
  clang/lib/StaticAnalyzer/Checkers/UndefResultChecker.cpp
  clang/lib/StaticAnalyzer/Core/ProgramState.cpp

Index: clang/lib/StaticAnalyzer/Core/ProgramState.cpp
===
--- clang/lib/StaticAnalyzer/Core/ProgramState.cpp
+++ clang/lib/StaticAnalyzer/Core/ProgramState.cpp
@@ -314,12 +314,12 @@
   return getStateManager().getPersistentState(NewSt);
 }
 
-ProgramStateRef ProgramState::assumeInBound(DefinedOrUnknownSVal Idx,
-  DefinedOrUnknownSVal UpperBound,
-  bool Assumption,
-  QualType indexTy) const {
+LLVM_NODISCARD std::pair
+ProgramState::assumeInBoundDual(DefinedOrUnknownSVal Idx,
+DefinedOrUnknownSVal UpperBound,
+QualType indexTy) const {
   if (Idx.isUnknown() || UpperBound.isUnknown())
-return this;
+return {this, this};
 
   // Build an expression for 0 <= Idx < UpperBound.
   // This is the same as Idx + MIN < UpperBound + MIN, if overflow is allowed.
@@ -338,7 +338,7 @@
   SVal newIdx = svalBuilder.evalBinOpNN(this, BO_Add,
 Idx.castAs(), Min, indexTy);
   if (newIdx.isUnknownOrUndef())
-return this;
+return {this, this};
 
   // Adjust the upper bound.
   SVal newBound =
@@ -346,17 +346,26 @@
 Min, indexTy);
 
   if (newBound.isUnknownOrUndef())
-return this;
+return {this, this};
 
   // Build the actual comparison.
   SVal inBound = svalBuilder.evalBinOpNN(this, BO_LT, newIdx.castAs(),
  newBound.castAs(), Ctx.IntTy);
   if (inBound.isUnknownOrUndef())
-return this;
+return {this, this};
 
   // Finally, let the constraint manager take care of it.
   ConstraintManager &CM = SM.getConstraintManager();
-  return CM.assume(this, inBound.castAs(), Assumption);
+  return CM.assumeDual(this, inBound.castAs());
+}
+
+ProgramStateRef ProgramState::assumeInBound(DefinedOrUnknownSVal Idx,
+DefinedOrUnknownSVal UpperBound,
+bool Assumption,
+QualType indexTy) const {
+  std::pair R =
+  assumeInBoundDual(Idx, UpperBound, indexTy);
+  return Assumption ? R.first : R.second;
 }
 
 ConditionTruthVal ProgramState::isNonNull(SVal V) const {
Index: clang/lib/StaticAnalyzer/Checkers/UndefResultChecker.cpp
===
--- clang/lib/StaticAnalyzer/Checkers/UndefResultChecker.cpp
+++ clang/lib/StaticAnalyzer/Checkers/UndefResultChecker.cpp
@@ -53,8 +53,8 @@
   DefinedOrUnknownSVal Idx = ER->getIndex().castAs();
   DefinedOrUnknownSVal ElementCount = getDynamicElementCount(
   state, ER->getSuperRegion(), C.getSValBuilder(), ER->getValueType());
-  ProgramStateRef StInBound = state->assumeInBound(Idx, ElementCount, true);
-  ProgramStateRef StOutBound = state->assumeInBound(Idx, ElementCount, false);
+  ProgramStateRef StInBound, StOutBound;
+  std::tie(StInBound, StOutBound) = state->assumeInBoundDual(Idx, ElementCount);
   return StOutBound && !StInBound;
 }
 
Index: clang/lib/StaticAnalyzer/Checkers/ReturnPointerRangeChecker.cpp
===
--- clang/lib/StaticAnalyzer/Checkers/ReturnPointerRangeChecker.cpp
+++ clang/lib/StaticAnalyzer/Checkers/ReturnPointerRangeChecker.cpp
@@ -64,8 +64,8 @@
   if (Idx == ElementCount)
 return;
 
-  ProgramStateRef StInBound = state->assumeInBound(Idx, ElementCount, true);
-  ProgramStateRef StOutBound = state->assumeInBound(Idx, ElementCount, false);
+  ProgramStateRef StInBound, StOutBound;
+  std::tie(StInBound, StOutBound) = state->assumeInBoundDual(Idx, ElementCount);
   if (StOutBound && !StInBound) {
 ExplodedNode *N = C.generateErrorNode(StOutBound);
 
Index: clang/lib/StaticAnalyzer/Checkers/ObjCContainersChecker.cpp
===
--- clang/lib/Stati

[PATCH] D124762: [WinEHPrepare] Avoid truncation of EH funclets with GNUstep ObjC runtime

2022-05-02 Thread Stefan Gränitz via Phabricator via cfe-commits
sgraenitz created this revision.
sgraenitz added reviewers: rnk, theraven, DHowett-MSFT.
Herald added a subscriber: hiraditya.
Herald added a project: All.
sgraenitz requested review of this revision.
Herald added projects: clang, LLVM.
Herald added a subscriber: cfe-commits.

Unwinding ObjC code with automatic reference counting involves calls to 
intrinsics like `llvm.obj.retain` and `llvm.objc.destroyWeak`. Exception 
handling on Windows is based on funclets and WinEHPrepare only allows calls to 
`nounwind` intrinsics. This works just fine, except for ObjC `nounwind` 
intrinsics, because these are lowered into regular function calls in an earlier 
stage already (i.e. PreISelIntrinsicLoweringPass). Thus, WinEHPrepare 
accidentally drops them as implausible instructions and silently truncates 
certain funclets. Eventually, this causes crashes during unwinding on Windows 
with the GNUstep ObjC runtime: https://github.com/gnustep/libobjc2/issues/222

This patch forces the emission of a "funclet" bundle operand for calls to ObjC 
ARC intrinsics during codegen and lets PreISelIntrinsicLowering carry it over 
onto lowered replacement calls. This way all ObjC ARC calls survive 
WinEHPrepare through the FuncletBundleOperand check. The latter had to be 
adjusted in order to allow funclet pads to get optimized away.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D124762

Files:
  clang/lib/CodeGen/CGCall.cpp
  llvm/lib/CodeGen/PreISelIntrinsicLowering.cpp
  llvm/lib/CodeGen/WinEHPrepare.cpp


Index: llvm/lib/CodeGen/WinEHPrepare.cpp
===
--- llvm/lib/CodeGen/WinEHPrepare.cpp
+++ llvm/lib/CodeGen/WinEHPrepare.cpp
@@ -963,7 +963,7 @@
 if (auto BU = CB->getOperandBundle(LLVMContext::OB_funclet))
   FuncletBundleOperand = BU->Inputs.front();
 
-if (FuncletBundleOperand == FuncletPad)
+if (!FuncletPad || FuncletBundleOperand == FuncletPad)
   continue;
 
 // Skip call sites which are nounwind intrinsics or inline asm.
Index: llvm/lib/CodeGen/PreISelIntrinsicLowering.cpp
===
--- llvm/lib/CodeGen/PreISelIntrinsicLowering.cpp
+++ llvm/lib/CodeGen/PreISelIntrinsicLowering.cpp
@@ -107,7 +107,9 @@
 
 IRBuilder<> Builder(CI->getParent(), CI->getIterator());
 SmallVector Args(CI->args());
-CallInst *NewCI = Builder.CreateCall(FCache, Args);
+SmallVector BundleList;
+CI->getOperandBundlesAsDefs(BundleList);
+CallInst *NewCI = Builder.CreateCall(FCache, Args, BundleList);
 NewCI->setName(CI->getName());
 
 // Try to set the most appropriate TailCallKind based on both the current
Index: clang/lib/CodeGen/CGCall.cpp
===
--- clang/lib/CodeGen/CGCall.cpp
+++ clang/lib/CodeGen/CGCall.cpp
@@ -25,11 +25,13 @@
 #include "clang/AST/DeclCXX.h"
 #include "clang/AST/DeclObjC.h"
 #include "clang/Basic/CodeGenOptions.h"
+#include "clang/Basic/ObjCRuntime.h"
 #include "clang/Basic/TargetBuiltins.h"
 #include "clang/Basic/TargetInfo.h"
 #include "clang/CodeGen/CGFunctionInfo.h"
 #include "clang/CodeGen/SwiftCallingConv.h"
 #include "llvm/ADT/StringExtras.h"
+#include "llvm/Analysis/ObjCARCInstKind.h"
 #include "llvm/Analysis/ValueTracking.h"
 #include "llvm/IR/Assumptions.h"
 #include "llvm/IR/Attributes.h"
@@ -4470,11 +4472,30 @@
 return BundleList;
 
   // Skip intrinsics which cannot throw.
+  bool InsertFuncletOp = true;
   auto *CalleeFn = dyn_cast(Callee->stripPointerCasts());
   if (CalleeFn && CalleeFn->isIntrinsic() && CalleeFn->doesNotThrow())
-return BundleList;
+InsertFuncletOp = false;
+
+  // ObjC ARC intrinics are lowered in PreISelIntrinsicLowering. Thus,
+  // WinEHPrepare will see them as regular calls. We need to set the funclet
+  // operand explicitly in this case to avoid accidental truncation of EH
+  // funclets on Windows.
+  using namespace llvm::objcarc;
+  if (GetFunctionClass(CalleeFn) != ARCInstKind::None) {
+assert(CalleeFn->isIntrinsic() && CalleeFn->doesNotThrow() &&
+   "Right now these are nounwind intrinsics");
+if (CGM.getTarget().getTriple().isOSWindows()) {
+  assert(CGM.getLangOpts().ObjCRuntime.getKind() == ObjCRuntime::GNUstep &&
+ "Only reproduced with GNUstep so far, but likely applies to other 
"
+ "ObjC runtimes on Windows");
+  InsertFuncletOp = true;
+}
+  }
+
+  if (InsertFuncletOp)
+BundleList.emplace_back("funclet", CurrentFuncletPad);
 
-  BundleList.emplace_back("funclet", CurrentFuncletPad);
   return BundleList;
 }
 


Index: llvm/lib/CodeGen/WinEHPrepare.cpp
===
--- llvm/lib/CodeGen/WinEHPrepare.cpp
+++ llvm/lib/CodeGen/WinEHPrepare.cpp
@@ -963,7 +963,7 @@
 if (auto BU = CB->getOperandBundle(LLVMContext::OB_funclet))
   FuncletBundleOperand = BU->Inputs.front(

[PATCH] D124757: [X86] Replace avx512f integer add reduction builtins with generic builtin

2022-05-02 Thread Phoebe Wang via Phabricator via cfe-commits
pengfei accepted this revision.
pengfei added a comment.
This revision is now accepted and ready to land.

LGTM. Thanks!


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124757

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


[PATCH] D124761: [analyzer] Replace adjacent assumeInBound calls to assumeInBoundDual

2022-05-02 Thread Gabor Marton via Phabricator via cfe-commits
martong updated this revision to Diff 426382.
martong added a comment.

- Set parent revision (in the commit message b/c the phab ui 'edit related 
revisions' is not operational)


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124761

Files:
  clang/include/clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h
  clang/lib/StaticAnalyzer/Checkers/ArrayBoundChecker.cpp
  clang/lib/StaticAnalyzer/Checkers/CStringChecker.cpp
  clang/lib/StaticAnalyzer/Checkers/ObjCContainersChecker.cpp
  clang/lib/StaticAnalyzer/Checkers/ReturnPointerRangeChecker.cpp
  clang/lib/StaticAnalyzer/Checkers/UndefResultChecker.cpp
  clang/lib/StaticAnalyzer/Core/ProgramState.cpp

Index: clang/lib/StaticAnalyzer/Core/ProgramState.cpp
===
--- clang/lib/StaticAnalyzer/Core/ProgramState.cpp
+++ clang/lib/StaticAnalyzer/Core/ProgramState.cpp
@@ -314,12 +314,12 @@
   return getStateManager().getPersistentState(NewSt);
 }
 
-ProgramStateRef ProgramState::assumeInBound(DefinedOrUnknownSVal Idx,
-  DefinedOrUnknownSVal UpperBound,
-  bool Assumption,
-  QualType indexTy) const {
+LLVM_NODISCARD std::pair
+ProgramState::assumeInBoundDual(DefinedOrUnknownSVal Idx,
+DefinedOrUnknownSVal UpperBound,
+QualType indexTy) const {
   if (Idx.isUnknown() || UpperBound.isUnknown())
-return this;
+return {this, this};
 
   // Build an expression for 0 <= Idx < UpperBound.
   // This is the same as Idx + MIN < UpperBound + MIN, if overflow is allowed.
@@ -338,7 +338,7 @@
   SVal newIdx = svalBuilder.evalBinOpNN(this, BO_Add,
 Idx.castAs(), Min, indexTy);
   if (newIdx.isUnknownOrUndef())
-return this;
+return {this, this};
 
   // Adjust the upper bound.
   SVal newBound =
@@ -346,17 +346,26 @@
 Min, indexTy);
 
   if (newBound.isUnknownOrUndef())
-return this;
+return {this, this};
 
   // Build the actual comparison.
   SVal inBound = svalBuilder.evalBinOpNN(this, BO_LT, newIdx.castAs(),
  newBound.castAs(), Ctx.IntTy);
   if (inBound.isUnknownOrUndef())
-return this;
+return {this, this};
 
   // Finally, let the constraint manager take care of it.
   ConstraintManager &CM = SM.getConstraintManager();
-  return CM.assume(this, inBound.castAs(), Assumption);
+  return CM.assumeDual(this, inBound.castAs());
+}
+
+ProgramStateRef ProgramState::assumeInBound(DefinedOrUnknownSVal Idx,
+DefinedOrUnknownSVal UpperBound,
+bool Assumption,
+QualType indexTy) const {
+  std::pair R =
+  assumeInBoundDual(Idx, UpperBound, indexTy);
+  return Assumption ? R.first : R.second;
 }
 
 ConditionTruthVal ProgramState::isNonNull(SVal V) const {
Index: clang/lib/StaticAnalyzer/Checkers/UndefResultChecker.cpp
===
--- clang/lib/StaticAnalyzer/Checkers/UndefResultChecker.cpp
+++ clang/lib/StaticAnalyzer/Checkers/UndefResultChecker.cpp
@@ -53,8 +53,8 @@
   DefinedOrUnknownSVal Idx = ER->getIndex().castAs();
   DefinedOrUnknownSVal ElementCount = getDynamicElementCount(
   state, ER->getSuperRegion(), C.getSValBuilder(), ER->getValueType());
-  ProgramStateRef StInBound = state->assumeInBound(Idx, ElementCount, true);
-  ProgramStateRef StOutBound = state->assumeInBound(Idx, ElementCount, false);
+  ProgramStateRef StInBound, StOutBound;
+  std::tie(StInBound, StOutBound) = state->assumeInBoundDual(Idx, ElementCount);
   return StOutBound && !StInBound;
 }
 
Index: clang/lib/StaticAnalyzer/Checkers/ReturnPointerRangeChecker.cpp
===
--- clang/lib/StaticAnalyzer/Checkers/ReturnPointerRangeChecker.cpp
+++ clang/lib/StaticAnalyzer/Checkers/ReturnPointerRangeChecker.cpp
@@ -64,8 +64,8 @@
   if (Idx == ElementCount)
 return;
 
-  ProgramStateRef StInBound = state->assumeInBound(Idx, ElementCount, true);
-  ProgramStateRef StOutBound = state->assumeInBound(Idx, ElementCount, false);
+  ProgramStateRef StInBound, StOutBound;
+  std::tie(StInBound, StOutBound) = state->assumeInBoundDual(Idx, ElementCount);
   if (StOutBound && !StInBound) {
 ExplodedNode *N = C.generateErrorNode(StOutBound);
 
Index: clang/lib/StaticAnalyzer/Checkers/ObjCContainersChecker.cpp
===
--- clang/lib/StaticAnalyzer/Checkers/ObjCContainersChecker.cpp
+++ clang/lib/StaticAnalyzer/Checkers/ObjCContainersChecker.cpp
@@ -137,8 +137,8 @@
 
 // Now, check if 'Idx in [0, Size-1]'.
 const QualType T = IdxExpr->getType();

[PATCH] D124721: [OpenMP] Allow compiling multiple target architectures with OpenMP

2022-05-02 Thread Joseph Huber via Phabricator via cfe-commits
jhuber6 added inline comments.



Comment at: clang/test/Driver/amdgpu-openmp-toolchain-new.c:6
 // RUN:   | FileCheck %s
+// RUN:   %clang -### --target=x86_64-unknown-linux-gnu -fopenmp 
-fopenmp-targets=amdgcn-amd-amdhsa \
+// RUN:  --offload-arch=gfx906 
--libomptarget-amdgpu-bc-path=%S/Inputs/hip_dev_lib %s 2>&1 \

saiislam wrote:
> Wouldn't it be better if the user is not required to specify the triple in 
> this shorthand version? We can infer the triple from the GPUArch. We have 
> this support in our downstream branch.
> 
> ```
> clang  --target=x86_64-unknown-linux-gnu -fopenmp --offload-arch=gfx906 
> helloworld.c -o helloworld
> ```
We could, HIP and CUDA both use some kind of `getAMDOffloadTargetTriple`. I 
guess in this case we would consider OpenMP offloading active if the user 
specified `-fopenmp` and `--offload-arch`? I could do this in a separate patch.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124721

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


[PATCH] D124500: [clang-tidy] Support expressions of literals in modernize-macro-to-enum

2022-05-02 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman added a comment.

In D124500#3483328 , 
@LegalizeAdulthood wrote:

> In D124500#3483224 , @aaron.ballman 
> wrote:
>
>> To clarify my previous comments, I'm fine punting on the edge cases until 
>> user reports come in, so don't let them block this review if you feel 
>> strongly about not supporting them. But when user reports start coming in, 
>> at some point I might start asking to replace the custom parser with calling 
>> into the clangParse library through some invented utility interface so that 
>> we don't have to deal with a long tail of bug reports.
>
> Yeah, I think punting on edge cases is the right thing to do here.  As I say,
> the worst that happens is your macro isn't converted automatically when you
> could convert it manually.

I largely agree, but I've found cases where we'll convert correct code to 
incorrect code, so it's a bit stronger than that.

> Maybe we're thinking about this check differently.
>
> I want this check to do the majority of the heavy lifting so that I'm only 
> left with a
> few "weird" macros that I might have to convert by hand.  I never, ever, ever 
> want
> this check to generate invalid code.  Therefore it is of paramount importance 
> that
> it be conservative about what it recognizes as a candidate for conversion.

I think that's a reasonable goal, but we're not meeting the "never ever 
generate invalid code" part. I already know we can break correct C and C++ code 
through overflow. Should we ever allow an option to use an enum with a fixed 
underlying type in C++ (either `enum class` or `enum : type` form), we'll have 
the same breakage there but at different thresholds.

> I think this is the baseline for all the modernize checks, really.  There are 
> still cases
> where loop-convert doesn't recognize an iterator based loop that could be
> converted to a range-based for loop.  The most important thing is that 
> loop-convert
> doesn't take my weird iterator based loop and convert it to a range based for 
> loop
> that doesn't compile.
>
> As for calling into `clangParse`, I think that would be overkill for a couple 
> reasons.
> First, the real parser is going to do a lot of work creating AST nodes which 
> we will
> never use, except to traverse the structure looking for things that would 
> invalidate
> it as a candidate for a constant initializing expression.  Second, we only 
> need to
> match the structure, we don't need to extract any information from the token 
> stream
> other than a "thumbs up" or "thumbs down" that it is a valid initializing 
> expression.

There's a few reasons I disagree with this. First, you need to know the value 
of the constant expression in order to know whether it's valid as an 
enumeration constant. That alone requires expression evaluation capabilities, 
assuming you want the check to behave correctly for those kinds of cases. But 
second, without support for generating that AST and validating it, you can 
never handle cases like this:

  constexpr int a = 12;
  constexpr int foo() { return 12; }
  
  #define FOO (a + 1)
  #define BAR (a + 2)
  #define BAZ (a + 3)
  #define QUUX (foo() + 4)

because you have no way to know whether or not that constant expression is 
valid based solely on token soup (especially when you start to factor in 
namespaces, qualified lookup, template instantiations, etc). So I think 
avoiding the parser will limit the utility of this check. And maybe that's 
fine, maybe it's only ever intended to convert C code using defines to C code 
using enumerations or other such simple cases.

> Many times in clang-tidy reviews performance concerns are raised and I think
> matching the token stream with the recursive descent matcher here is going to 
> be
> much, much faster than invoking `clangParse`, particularly since the matcher 
> bails
> out early on the first token that doesn't match.

Absolutely 100% agreed on this point.

> The only thing I can think of that
> would make it faster is if we could get the lexed tokens from the preprocessor
> instead of making it re-lex the macro body, but that's a change beyond the 
> scope
> of this check or even clang-tidy.

Yeah, and that wouldn't even be sufficient because I still think we're going to 
want to know the *value* of the expression at some point.

All that "this is the wrong way!" doom and gloom aside, I still think 
you're fine to proceed with the current approach if you'd like to. The 
situations under which it will break correct code should be something we 
document explicitly in the check somewhere, but they feel sufficiently like 
edge cases to me that I'm fine moving forward with the caution in mind that if 
this becomes too much more problematic in the future, we have *a* path forward 
we could use to improve things should we decide we need to.




Comment at: 
clang-tools-extra/clang-tidy/modernize/IntegralLiteralExpressi

[PATCH] D124658: [analyzer] Canonicalize SymIntExpr so the RHS is positive when possible

2022-05-02 Thread Balázs Benics via Phabricator via cfe-commits
steakhal added inline comments.



Comment at: clang/lib/StaticAnalyzer/Core/SimpleSValBuilder.cpp:204
+// subtraction/addition of the negated value.
+if (!RHS.isNegative()) {
+  ConvertedRHS = &BasicVals.Convert(resultTy, RHS);

tomasz-kaminski-sonarsource wrote:
> steakhal wrote:
> > I would rather swap these branches though, to leave the default case (aka. 
> > this) to the end.
> I folded the `RHS.isNegative()` into the if for the 
> `BinaryOperator::isAssociative(op)`, as same conversion is performed in final 
> else branch.
I think what confused me is that a different API is used for doing the 
conversion.
 - `resultIntTy.convert(RHS)`
 - `&BasicVals.Convert(resultTy, RHS)`

Anyway, leave it as-is.



Comment at: clang/lib/StaticAnalyzer/Core/SimpleSValBuilder.cpp:212-219
+  llvm::APSInt ConvertedRHSValue = resultIntTy.convert(RHS);
+  // Check if the negation of the RHS is representable,
+  // i.e., the resultTy is signed, and it is not the lowest
+  // representable negative value.
+  if (ConvertedRHSValue > resultIntTy.getMinValue()) {
+ConvertedRHS = &BasicVals.getValue(-ConvertedRHSValue);
+op = (op == BO_Add) ? BO_Sub : BO_Add;

tomasz-kaminski-sonarsource wrote:
> tomasz-kaminski-sonarsource wrote:
> > steakhal wrote:
> > > Somehow I miss a check for signedness here.
> > > Why do you think it would be only triggered for signed types?
> > > 
> > > I have a guess, that since we already handled `x +-0`, SymIntExprs like 
> > > `x - (-0)` cannot exist here, thus cannot trigger this condition 
> > > spuriously. I cannot think of any ther example that could cause this 
> > > misbehaving. So in that sense `ConvertedRHSValue > 
> > > resultIntTy.getMinValue()` implies *at this place* that 
> > > `ConvertedRHSValue.isSigned()`.
> > > I would rather see this redundant check here to make the correctness 
> > > reasoning local though.
> > The integer representation does not have negative zeros (the standard and 
> > clang assume two's complement). However, this condition does need to check 
> > for the signedness of the types. What I mean is that if the `RHS` is 
> > negative, but `ConvertedRHSValue` the branch will trigger and we will 
> > change `x - INT_MIN` to `x + (INT_MAX + 1)U` which is ok, as a negation of 
> > `INT_MIN` is representable as an unsigned type of same or lager bit with.
> > 
> However, I was not able to reach this point with `RHS` being signed, and 
> `resultTy` being unsigned. Any hints how this could be done?
I'm not saying that I can follow this thought process. But the 
`clang/test/Analysis/PR49642.c` would trigger an assertion like this:

```lang=diff
diff --git a/clang/lib/StaticAnalyzer/Core/SimpleSValBuilder.cpp 
b/clang/lib/StaticAnalyzer/Core/SimpleSValBuilder.cpp
index 088c33c8e612..7e59309228e1 100644
--- a/clang/lib/StaticAnalyzer/Core/SimpleSValBuilder.cpp
+++ b/clang/lib/StaticAnalyzer/Core/SimpleSValBuilder.cpp
@@ -207,6 +207,16 @@ SVal SimpleSValBuilder::MakeSymIntVal(const SymExpr *LHS,
"number of bits as its operands.");
 
 llvm::APSInt ConvertedRHSValue = resultIntTy.convert(RHS);
+if (RHS.isSigned() && resultTy->isUnsignedIntegerOrEnumerationType()) {
+  llvm::errs() << "LHS sym:\n";
+  LHS->dump();
+  llvm::errs() << "RHS integral:\n";
+  RHS.dump();
+  llvm::errs() << "OP: " << BinaryOperator::getOpcodeStr(op) << "\n";
+  llvm::errs() << "result type:\n";
+  resultTy->dump();
+  llvm_unreachable("how is it possible??");
+}
 // Check if the negation of the RHS is representable,
 // i.e., the resultTy is signed, and it is not the lowest
 // representable negative value.
```

Which can be reduced into this one:

```lang=c
// RUN: %clang_analyze_cc1 -Wno-implicit-function-declaration -w -verify %s \
// RUN:   -analyzer-checker=core \
// RUN:   -analyzer-checker=apiModeling.StdCLibraryFunctions

// expected-no-diagnostics

typedef int ssize_t;
int write(int, const void *, unsigned long);
unsigned c;
void a() {
  int b = write(0, 0, c);
  b != 0;
  c -= b;
  b < 1;
  ++c; // crash simplifySValOnce: derived_$4{conj_$1{int, LC1, S700, #1},c}  
op(-)  APInt(32b, 4294967295u -1s)  :: unsigned int
}
```


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124658

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


[PATCH] D124721: [OpenMP] Allow compiling multiple target architectures with OpenMP

2022-05-02 Thread Saiyedul Islam via Phabricator via cfe-commits
saiislam added inline comments.



Comment at: clang/test/Driver/amdgpu-openmp-toolchain-new.c:6
 // RUN:   | FileCheck %s
+// RUN:   %clang -### --target=x86_64-unknown-linux-gnu -fopenmp 
-fopenmp-targets=amdgcn-amd-amdhsa \
+// RUN:  --offload-arch=gfx906 
--libomptarget-amdgpu-bc-path=%S/Inputs/hip_dev_lib %s 2>&1 \

jhuber6 wrote:
> saiislam wrote:
> > Wouldn't it be better if the user is not required to specify the triple in 
> > this shorthand version? We can infer the triple from the GPUArch. We have 
> > this support in our downstream branch.
> > 
> > ```
> > clang  --target=x86_64-unknown-linux-gnu -fopenmp --offload-arch=gfx906 
> > helloworld.c -o helloworld
> > ```
> We could, HIP and CUDA both use some kind of `getAMDOffloadTargetTriple`. I 
> guess in this case we would consider OpenMP offloading active if the user 
> specified `-fopenmp` and `--offload-arch`? I could do this in a separate 
> patch.
Yes, exactly. OpenMP offloading should be active when `-fopenmp` and 
`--offload-arch` both are present.

Thank you!


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124721

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


[PATCH] D124702: [MSVC] Add support for pragma function

2022-05-02 Thread Hans Wennborg via Phabricator via cfe-commits
hans added a comment.

From the MS docs:

> Once a function pragma is seen, it takes effect at the first function 
> definition that contains a specified intrinsic function. The effect continues 
> to the end of the source file, or to the appearance of an intrinsic pragma 
> specifying the same intrinsic function. You can only use the function pragma 
> outside of a function, at the global level.

Should we try to handle the interaction between pragma intrinsic and pragma 
function, i.e. that the former "undoes" the latter? And should we error/warn if 
the pragma occurs not in namespace scope?




Comment at: clang/include/clang/Sema/Sema.h:10236
 
+  void ActOnPragmaMSFunction(std::vector NoBuiltins);
+

Pass by const-ref maybe?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124702

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


[PATCH] D124721: [OpenMP] Allow compiling multiple target architectures with OpenMP

2022-05-02 Thread Saiyedul Islam via Phabricator via cfe-commits
saiislam added inline comments.



Comment at: clang/test/Driver/amdgpu-openmp-toolchain-new.c:6
 // RUN:   | FileCheck %s
+// RUN:   %clang -### --target=x86_64-unknown-linux-gnu -fopenmp 
-fopenmp-targets=amdgcn-amd-amdhsa \
+// RUN:  --offload-arch=gfx906 
--libomptarget-amdgpu-bc-path=%S/Inputs/hip_dev_lib %s 2>&1 \

saiislam wrote:
> jhuber6 wrote:
> > saiislam wrote:
> > > Wouldn't it be better if the user is not required to specify the triple 
> > > in this shorthand version? We can infer the triple from the GPUArch. We 
> > > have this support in our downstream branch.
> > > 
> > > ```
> > > clang  --target=x86_64-unknown-linux-gnu -fopenmp --offload-arch=gfx906 
> > > helloworld.c -o helloworld
> > > ```
> > We could, HIP and CUDA both use some kind of `getAMDOffloadTargetTriple`. I 
> > guess in this case we would consider OpenMP offloading active if the user 
> > specified `-fopenmp` and `--offload-arch`? I could do this in a separate 
> > patch.
> Yes, exactly. OpenMP offloading should be active when `-fopenmp` and 
> `--offload-arch` both are present.
> 
> Thank you!
Following code might be useful for your patch (it assumes that OffloadArch is 
associated with each device tool chain so that multiple archs of same triple 
can be compiled together):


  # [[ 
https://github.com/RadeonOpenCompute/llvm-project/blob/359002f885ea860609f0c841d69f4970ccbb37af/clang/lib/Driver/Driver.cpp#L735
 | GetTargetInfoFromOffloadArch() ]]
  # [[ 
https://github.com/RadeonOpenCompute/llvm-project/blob/359002f885ea860609f0c841d69f4970ccbb37af/clang/lib/Driver/Driver.cpp#L779
 | Driver::GetTargetInfoFromMarch() ]]
  # [[ 
https://github.com/RadeonOpenCompute/llvm-project/blob/359002f885ea860609f0c841d69f4970ccbb37af/clang/lib/Driver/Driver.cpp#L819
 | Driver::GetTargetInfoFromOffloadArchOpts() ]]
  # [[ 
https://github.com/RadeonOpenCompute/llvm-project/blob/359002f885ea860609f0c841d69f4970ccbb37af/clang/lib/Driver/Driver.cpp#L851
 | modified definition of Driver::CreateOffloadingDeviceToolChains() ]]



Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124721

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


[PATCH] D124762: [WinEHPrepare] Avoid truncation of EH funclets with GNUstep ObjC runtime

2022-05-02 Thread Stefan Gränitz via Phabricator via cfe-commits
sgraenitz added a comment.

I guess testing must be split in two:

- Clang wants to make sure the "funclet" bundle operand gets emitted for ObjC 
ARC runtime calls on Windows. Maybe that fits into 
clang/test/CodeGenObjC/gnu-exceptions.m 
?
- LLVM wants to check that WinEHPrepare handles these runtime calls correctly. 
For that maybe I can use llvm/test/CodeGen/X86/win-funclet-cfi.ll 

 as a template and adjust it for the ObjC ARC case?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124762

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


[libunwind] 364c502 - [libunwind] Add SystemZ support

2022-05-02 Thread Ulrich Weigand via cfe-commits

Author: Ulrich Weigand
Date: 2022-05-02T14:35:29+02:00
New Revision: 364c5023d2ce1617c706b185892ddfaa2fd4d166

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

LOG: [libunwind] Add SystemZ support

Add support for the SystemZ (s390x) architecture to libunwind.

Support should be feature-complete with the exception of
unwinding from signal handlers (to be added later).

Reviewed by: MaskRay

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

Added: 


Modified: 
libunwind/include/__libunwind_config.h
libunwind/include/libunwind.h
libunwind/src/Registers.hpp
libunwind/src/UnwindCursor.hpp
libunwind/src/UnwindRegistersRestore.S
libunwind/src/UnwindRegistersSave.S
libunwind/src/config.h
libunwind/src/libunwind.cpp

Removed: 




diff  --git a/libunwind/include/__libunwind_config.h 
b/libunwind/include/__libunwind_config.h
index 30f5e0a23d08e..e626567d4e594 100644
--- a/libunwind/include/__libunwind_config.h
+++ b/libunwind/include/__libunwind_config.h
@@ -29,6 +29,7 @@
 #define _LIBUNWIND_HIGHEST_DWARF_REGISTER_HEXAGON   34
 #define _LIBUNWIND_HIGHEST_DWARF_REGISTER_RISCV 64
 #define _LIBUNWIND_HIGHEST_DWARF_REGISTER_VE143
+#define _LIBUNWIND_HIGHEST_DWARF_REGISTER_S390X 83
 
 #if defined(_LIBUNWIND_IS_NATIVE_ONLY)
 # if defined(__linux__)
@@ -160,6 +161,11 @@
 #  define _LIBUNWIND_CONTEXT_SIZE 67
 #  define _LIBUNWIND_CURSOR_SIZE 79
 #  define _LIBUNWIND_HIGHEST_DWARF_REGISTER 
_LIBUNWIND_HIGHEST_DWARF_REGISTER_VE
+# elif defined(__s390x__)
+#  define _LIBUNWIND_TARGET_S390X 1
+#  define _LIBUNWIND_CONTEXT_SIZE 34
+#  define _LIBUNWIND_CURSOR_SIZE 46
+#  define _LIBUNWIND_HIGHEST_DWARF_REGISTER 
_LIBUNWIND_HIGHEST_DWARF_REGISTER_S390X
 # else
 #  error "Unsupported architecture."
 # endif
@@ -178,6 +184,7 @@
 # define _LIBUNWIND_TARGET_HEXAGON 1
 # define _LIBUNWIND_TARGET_RISCV 1
 # define _LIBUNWIND_TARGET_VE 1
+# define _LIBUNWIND_TARGET_S390X 1
 # define _LIBUNWIND_CONTEXT_SIZE 167
 # define _LIBUNWIND_CURSOR_SIZE 179
 # define _LIBUNWIND_HIGHEST_DWARF_REGISTER 287

diff  --git a/libunwind/include/libunwind.h b/libunwind/include/libunwind.h
index a69e72fc132df..3d8fd2146ebbd 100644
--- a/libunwind/include/libunwind.h
+++ b/libunwind/include/libunwind.h
@@ -1177,4 +1177,46 @@ enum {
   UNW_VE_VL   = 145,
 };
 
+// s390x register numbers
+enum {
+  UNW_S390X_R0  = 0,
+  UNW_S390X_R1  = 1,
+  UNW_S390X_R2  = 2,
+  UNW_S390X_R3  = 3,
+  UNW_S390X_R4  = 4,
+  UNW_S390X_R5  = 5,
+  UNW_S390X_R6  = 6,
+  UNW_S390X_R7  = 7,
+  UNW_S390X_R8  = 8,
+  UNW_S390X_R9  = 9,
+  UNW_S390X_R10 = 10,
+  UNW_S390X_R11 = 11,
+  UNW_S390X_R12 = 12,
+  UNW_S390X_R13 = 13,
+  UNW_S390X_R14 = 14,
+  UNW_S390X_R15 = 15,
+  UNW_S390X_F0  = 16,
+  UNW_S390X_F2  = 17,
+  UNW_S390X_F4  = 18,
+  UNW_S390X_F6  = 19,
+  UNW_S390X_F1  = 20,
+  UNW_S390X_F3  = 21,
+  UNW_S390X_F5  = 22,
+  UNW_S390X_F7  = 23,
+  UNW_S390X_F8  = 24,
+  UNW_S390X_F10 = 25,
+  UNW_S390X_F12 = 26,
+  UNW_S390X_F14 = 27,
+  UNW_S390X_F9  = 28,
+  UNW_S390X_F11 = 29,
+  UNW_S390X_F13 = 30,
+  UNW_S390X_F15 = 31,
+  // 32-47 Control Registers
+  // 48-63 Access Registers
+  UNW_S390X_PSWM= 64,
+  UNW_S390X_PSWA= 65,
+  // 66-67 Reserved
+  // 68-83 Vector Registers %v16-%v31
+};
+
 #endif

diff  --git a/libunwind/src/Registers.hpp b/libunwind/src/Registers.hpp
index 32c13e6c9a248..28c617f34999b 100644
--- a/libunwind/src/Registers.hpp
+++ b/libunwind/src/Registers.hpp
@@ -39,6 +39,7 @@ enum {
   REGISTERS_HEXAGON,
   REGISTERS_RISCV,
   REGISTERS_VE,
+  REGISTERS_S390X,
 };
 
 #if defined(_LIBUNWIND_TARGET_I386)
@@ -4716,6 +4717,293 @@ inline const char *Registers_ve::getRegisterName(int 
regNum) {
 }
 #endif // _LIBUNWIND_TARGET_VE
 
+#if defined(_LIBUNWIND_TARGET_S390X)
+/// Registers_s390x holds the register state of a thread in a
+/// 64-bit Linux on IBM zSystems process.
+class _LIBUNWIND_HIDDEN Registers_s390x {
+public:
+  Registers_s390x();
+  Registers_s390x(const void *registers);
+
+  boolvalidRegister(int num) const;
+  uint64_tgetRegister(int num) const;
+  voidsetRegister(int num, uint64_t value);
+  boolvalidFloatRegister(int num) const;
+  double  getFloatRegister(int num) const;
+  voidsetFloatRegister(int num, double value);
+  boolvalidVectorRegister(int num) const;
+  v128getVectorRegister(int num) const;
+  voidsetVectorRegister(int num, v128 value);
+  static const char *getRegisterName(int num);
+  voidjumpto();
+  static int  lastDwarfRegNum() { return 
_LIBUNWIND_HIGHEST_DWARF_REGISTER_S390X; }
+  static int  getArch() { return REGISTERS_S390X; }
+
+  uint6

[PATCH] D124721: [OpenMP] Allow compiling multiple target architectures with OpenMP

2022-05-02 Thread Joseph Huber via Phabricator via cfe-commits
jhuber6 added inline comments.



Comment at: clang/test/Driver/amdgpu-openmp-toolchain-new.c:6
 // RUN:   | FileCheck %s
+// RUN:   %clang -### --target=x86_64-unknown-linux-gnu -fopenmp 
-fopenmp-targets=amdgcn-amd-amdhsa \
+// RUN:  --offload-arch=gfx906 
--libomptarget-amdgpu-bc-path=%S/Inputs/hip_dev_lib %s 2>&1 \

saiislam wrote:
> saiislam wrote:
> > jhuber6 wrote:
> > > saiislam wrote:
> > > > Wouldn't it be better if the user is not required to specify the triple 
> > > > in this shorthand version? We can infer the triple from the GPUArch. We 
> > > > have this support in our downstream branch.
> > > > 
> > > > ```
> > > > clang  --target=x86_64-unknown-linux-gnu -fopenmp --offload-arch=gfx906 
> > > > helloworld.c -o helloworld
> > > > ```
> > > We could, HIP and CUDA both use some kind of `getAMDOffloadTargetTriple`. 
> > > I guess in this case we would consider OpenMP offloading active if the 
> > > user specified `-fopenmp` and `--offload-arch`? I could do this in a 
> > > separate patch.
> > Yes, exactly. OpenMP offloading should be active when `-fopenmp` and 
> > `--offload-arch` both are present.
> > 
> > Thank you!
> Following code might be useful for your patch (it assumes that OffloadArch is 
> associated with each device tool chain so that multiple archs of same triple 
> can be compiled together):
> 
> 
>   # [[ 
> https://github.com/RadeonOpenCompute/llvm-project/blob/359002f885ea860609f0c841d69f4970ccbb37af/clang/lib/Driver/Driver.cpp#L735
>  | GetTargetInfoFromOffloadArch() ]]
>   # [[ 
> https://github.com/RadeonOpenCompute/llvm-project/blob/359002f885ea860609f0c841d69f4970ccbb37af/clang/lib/Driver/Driver.cpp#L779
>  | Driver::GetTargetInfoFromMarch() ]]
>   # [[ 
> https://github.com/RadeonOpenCompute/llvm-project/blob/359002f885ea860609f0c841d69f4970ccbb37af/clang/lib/Driver/Driver.cpp#L819
>  | Driver::GetTargetInfoFromOffloadArchOpts() ]]
>   # [[ 
> https://github.com/RadeonOpenCompute/llvm-project/blob/359002f885ea860609f0c841d69f4970ccbb37af/clang/lib/Driver/Driver.cpp#L851
>  | modified definition of Driver::CreateOffloadingDeviceToolChains() ]]
> 
I'll look into it, I was thinking of a good way to specify architectures per 
triple. So we could theoretically have `--offload-arch=sm_70` and 
`--offload_arch=gfx908` work in unison and it might just be easy to group the 
triples from the architecture.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124721

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


[PATCH] D124724: [Clang][OpenMP] Add the support for floating-point variables for specific atomic clauses

2022-05-02 Thread Alexey Bataev via Phabricator via cfe-commits
ABataev added inline comments.



Comment at: clang/lib/CodeGen/CGStmtOpenMP.cpp:5936-5939
+  CGF.Builder.CreateCast(X.getType()->hasSignedIntegerRepresentation()
+ ? llvm::Instruction::CastOps::SIToFP
+ : llvm::Instruction::CastOps::UIToFP,
+ IC, X.getAddress(CGF).getElementType());

Do we have a test for this? If `X` is not integer, I rather doubt that 
hasSignedIntegerRepresentation is meaningful here


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124724

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


[PATCH] D124688: [clangd] parse all make_unique-like functions in preamble

2022-05-02 Thread Tobias Ribizel via Phabricator via cfe-commits
upsj updated this revision to Diff 426387.
upsj marked 2 inline comments as done.
upsj added a comment.
Herald added a subscriber: javed.absar.

Rewrote detection of forwarding functions in preamble, added 
`--preamble-parse-forwarding` flag

I ran clangd over  `bits/stdc++.h`, and it seems like the condition works very 
well:

It picked up

- container::emplace and friends
- allocator::construct and friends
- make_unique, make_shared and friends
- some parts of `functional`
- some parts of `tuple`
- some parts of `thread`

most of which seem like good candidates for forwarding parameters.

In terms of runtime, I can't see any noticeable difference between parsing with 
or without `--preamble-parse-forwarding`, but of course, all of libstdc++ is 
not the most realistic scenario


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124688

Files:
  clang-tools-extra/clangd/ClangdServer.cpp
  clang-tools-extra/clangd/ClangdServer.h
  clang-tools-extra/clangd/Preamble.cpp
  clang-tools-extra/clangd/Preamble.h
  clang-tools-extra/clangd/TUScheduler.cpp
  clang-tools-extra/clangd/TUScheduler.h
  clang-tools-extra/clangd/tool/Check.cpp
  clang-tools-extra/clangd/tool/ClangdMain.cpp
  clang-tools-extra/clangd/unittests/CodeCompleteTests.cpp
  clang-tools-extra/clangd/unittests/FileIndexTests.cpp
  clang-tools-extra/clangd/unittests/ParsedASTTests.cpp
  clang-tools-extra/clangd/unittests/PreambleTests.cpp
  clang-tools-extra/clangd/unittests/TestTU.cpp

Index: clang-tools-extra/clangd/unittests/TestTU.cpp
===
--- clang-tools-extra/clangd/unittests/TestTU.cpp
+++ clang-tools-extra/clangd/unittests/TestTU.cpp
@@ -101,7 +101,9 @@
   auto ModuleCacheDeleter = llvm::make_scope_exit(
   std::bind(deleteModuleCache, CI->getHeaderSearchOpts().ModuleCachePath));
   return clang::clangd::buildPreamble(testPath(Filename), *CI, Inputs,
-  /*StoreInMemory=*/true, PreambleCallback);
+  /*StoreInMemory=*/true,
+  /*ParseForwardingFunctions=*/false,
+  PreambleCallback);
 }
 
 ParsedAST TestTU::build() const {
@@ -115,9 +117,10 @@
   auto ModuleCacheDeleter = llvm::make_scope_exit(
   std::bind(deleteModuleCache, CI->getHeaderSearchOpts().ModuleCachePath));
 
-  auto Preamble = clang::clangd::buildPreamble(testPath(Filename), *CI, Inputs,
-   /*StoreInMemory=*/true,
-   /*PreambleCallback=*/nullptr);
+  auto Preamble =
+  clang::clangd::buildPreamble(testPath(Filename), *CI, Inputs,
+   /*StoreInMemory=*/true,
+   /*PreambleCallback=*/false, nullptr);
   auto AST = ParsedAST::build(testPath(Filename), Inputs, std::move(CI),
   Diags.take(), Preamble);
   if (!AST.hasValue()) {
Index: clang-tools-extra/clangd/unittests/PreambleTests.cpp
===
--- clang-tools-extra/clangd/unittests/PreambleTests.cpp
+++ clang-tools-extra/clangd/unittests/PreambleTests.cpp
@@ -173,7 +173,8 @@
   TU.AdditionalFiles["c.h"] = "";
   auto PI = TU.inputs(FS);
   auto BaselinePreamble = buildPreamble(
-  TU.Filename, *buildCompilerInvocation(PI, Diags), PI, true, nullptr);
+  TU.Filename, *buildCompilerInvocation(PI, Diags), PI,
+  /*StoreInMemory=*/true, /*ParseForwardingFunctions=*/false, nullptr);
   // We drop c.h from modified and add a new header. Since the latter is patched
   // we should only get a.h in preamble includes.
   TU.Code = R"cpp(
Index: clang-tools-extra/clangd/unittests/ParsedASTTests.cpp
===
--- clang-tools-extra/clangd/unittests/ParsedASTTests.cpp
+++ clang-tools-extra/clangd/unittests/ParsedASTTests.cpp
@@ -497,7 +497,8 @@
   auto Inputs = TU.inputs(FS);
   auto CI = buildCompilerInvocation(Inputs, Diags);
   auto EmptyPreamble =
-  buildPreamble(testPath("foo.cpp"), *CI, Inputs, true, nullptr);
+  buildPreamble(testPath("foo.cpp"), *CI, Inputs, /*StoreInMemory=*/true,
+/*PreambleCallback=*/false, nullptr);
   ASSERT_TRUE(EmptyPreamble);
   EXPECT_THAT(EmptyPreamble->Includes.MainFileIncludes, IsEmpty());
 
@@ -540,7 +541,8 @@
   auto Inputs = TU.inputs(FS);
   auto CI = buildCompilerInvocation(Inputs, Diags);
   auto BaselinePreamble =
-  buildPreamble(testPath("foo.cpp"), *CI, Inputs, true, nullptr);
+  buildPreamble(testPath("foo.cpp"), *CI, Inputs, /*StoreInMemory=*/true,
+/*PreambleCallback=*/false, nullptr);
   ASSERT_TRUE(BaselinePreamble);
   EXPECT_THAT(BaselinePreamble->Includes.MainFileIncludes,
   ElementsAre(testing::Field(&Inclusion::Written, "

[PATCH] D123032: [clang][dataflow] Exclude protobuf types from modeling in the environment.

2022-05-02 Thread Yitzhak Mandelbaum via Phabricator via cfe-commits
ymandel updated this revision to Diff 426388.
ymandel marked an inline comment as done.
ymandel added a comment.

added FIXME


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D123032

Files:
  clang/lib/Analysis/FlowSensitive/DataflowEnvironment.cpp
  clang/unittests/Analysis/FlowSensitive/DataflowEnvironmentTest.cpp

Index: clang/unittests/Analysis/FlowSensitive/DataflowEnvironmentTest.cpp
===
--- clang/unittests/Analysis/FlowSensitive/DataflowEnvironmentTest.cpp
+++ clang/unittests/Analysis/FlowSensitive/DataflowEnvironmentTest.cpp
@@ -20,8 +20,8 @@
 
 using namespace clang;
 using namespace dataflow;
-using ::testing::ElementsAre;
-using ::testing::Pair;
+using ::testing::IsNull;
+using ::testing::NotNull;
 
 class EnvironmentTest : public ::testing::Test {
   DataflowAnalysisContext Context;
@@ -98,4 +98,70 @@
   EXPECT_NE(PV, nullptr);
 }
 
+TEST_F(EnvironmentTest, ExcludeProtobufTypes) {
+  using namespace ast_matchers;
+
+  std::string Code = R"cc(
+namespace proto2 {
+struct Message {};
+}
+
+namespace google {
+namespace protobuf {
+struct Message {};
+}
+}
+
+namespace other {
+namespace google {
+namespace protobuf {
+struct Message {};
+}
+}
+}
+
+struct Foo : public proto2::Message {
+  bool Field;
+};
+
+struct Bar : public google::protobuf::Message {
+  bool Field;
+};
+
+// Not a protobuf, but looks like it. Verify that it is *not* excluded.
+struct Zab : public other::google::protobuf::Message {
+  bool Field;
+};
+
+void target() {
+  Foo F;
+  Bar B;
+  Zab Z;
+  (void)0;
+  /*[[check]]*/
+}
+  )cc";
+
+  auto Unit =
+  tooling::buildASTFromCodeWithArgs(Code, {"-fsyntax-only", "-std=c++11"});
+  auto &Context = Unit->getASTContext();
+
+  ASSERT_EQ(Context.getDiagnostics().getClient()->getNumErrors(), 0U);
+
+  auto Results = match(varDecl(eachOf(varDecl(hasName("F")).bind("varF"),
+  varDecl(hasName("B")).bind("varB"),
+  varDecl(hasName("Z")).bind("varZ"))),
+   Context);
+  const auto *F = selectFirst("varF", Results);
+  ASSERT_TRUE(F != nullptr);
+  const auto *B = selectFirst("varB", Results);
+  ASSERT_TRUE(B != nullptr);
+  const auto *Z = selectFirst("varZ", Results);
+  ASSERT_TRUE(Z != nullptr);
+
+  EXPECT_THAT(Env.createValue(F->getType()), IsNull());
+  EXPECT_THAT(Env.createValue(B->getType()), IsNull());
+  EXPECT_THAT(Env.createValue(Z->getType()), NotNull());
+}
+
 } // namespace
Index: clang/lib/Analysis/FlowSensitive/DataflowEnvironment.cpp
===
--- clang/lib/Analysis/FlowSensitive/DataflowEnvironment.cpp
+++ clang/lib/Analysis/FlowSensitive/DataflowEnvironment.cpp
@@ -443,6 +443,53 @@
   return Val;
 }
 
+// Hard code certain types to exclude from modeling. Currently, we limit to
+// Google protobufs, since they can be very large, and have no value in
+// modeling.
+//
+// FIXME: Remove this specialized exclusion once a more general mechanism is
+// implemented for only modeling accessed fields. Otherwise, consider memoizing
+// this function or caching some of the information on which it relies (like the
+// protobuf `Message` base type) at the TU level.
+static bool isExcludedRecordType(const RecordType *Ty) {
+  const auto *CD = dyn_cast(Ty->getDecl());
+  if (CD == nullptr || !CD->hasDefinition() || CD->getNumBases() != 1)
+return false;
+
+  QualType BQ = CD->bases_begin()->getType();
+  if (BQ.isNull())
+return false;
+
+  const RecordType *BaseTy = BQ->getAs();
+  if (BaseTy == nullptr)
+return false;
+
+  const RecordDecl *RD = BaseTy->getDecl();
+  assert(RD != nullptr);
+  IdentifierInfo *II = RD->getIdentifier();
+  if (II == nullptr || !II->isStr("Message"))
+return false;
+
+  const auto *ND = dyn_cast(RD->getDeclContext());
+  if (ND == nullptr)
+return false;
+  IdentifierInfo *NamespaceII = ND->getIdentifier();
+  if (NamespaceII == nullptr)
+return false;
+  if (NamespaceII->isStr("proto2"))
+return true;
+
+  // Check for `::google::protobuf`:
+  if (!NamespaceII->isStr("protobuf"))
+return false;
+
+  ND = dyn_cast(ND->getDeclContext());
+  if (ND == nullptr || !ND->getParent()->isTranslationUnit())
+return false;
+  NamespaceII = ND->getIdentifier();
+  return NamespaceII != nullptr && NamespaceII->isStr("google");
+}
+
 Value *Environment::createValueUnlessSelfReferential(
 QualType Type, llvm::DenseSet &Visited, int Depth,
 int &CreatedValuesCount) {
@@ -499,7 +546,8 @@
 return &takeOwnership(std::make_unique(PointeeLoc));
   }
 
-  if (Type->isStructureOrClassType()) {
+  if (Type->isStructureOrClassType() &&
+  !isExcludedRecordType(Type->getAs())) {
 CreatedVal

[PATCH] D124688: [clangd] parse all make_unique-like functions in preamble

2022-05-02 Thread Tobias Ribizel via Phabricator via cfe-commits
upsj added inline comments.



Comment at: clang-tools-extra/clangd/Preamble.cpp:167
+// ... whose template parameter comes from the function directly
+if (FT->getTemplateParameters()->getDepth() ==
+PackTypePtr->getDepth()) {

Can PackTypePtr ever be nullptr?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124688

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


[PATCH] D124719: [docs] PCH usage documentation update

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

LGTM, thanks for improving the docs!


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124719

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


[clang] 4b6c2cd - Deferred Concept Instantiation Implementation

2022-05-02 Thread Erich Keane via cfe-commits

Author: Erich Keane
Date: 2022-05-02T05:49:15-07:00
New Revision: 4b6c2cd647e9e5a147954886338f97ffb6a1bcfb

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

LOG: Deferred Concept Instantiation Implementation

As reported here: https://github.com/llvm/llvm-project/issues/44178

Concepts are not supposed to be instantiated until they are checked, so
this patch implements that and goes through significant amounts of work
to make sure we properly re-instantiate the concepts correctly.

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

Added: 
clang/test/SemaTemplate/deferred-concept-inst.cpp
clang/test/SemaTemplate/trailing-return-short-circuit.cpp

Modified: 
clang/docs/ReleaseNotes.rst
clang/include/clang/AST/Decl.h
clang/include/clang/AST/DeclBase.h
clang/include/clang/Sema/Sema.h
clang/include/clang/Sema/Template.h
clang/lib/AST/ASTImporter.cpp
clang/lib/AST/Decl.cpp
clang/lib/AST/DeclBase.cpp
clang/lib/ExtractAPI/ExtractAPIConsumer.cpp
clang/lib/Sema/SemaConcept.cpp
clang/lib/Sema/SemaTemplate.cpp
clang/lib/Sema/SemaTemplateDeduction.cpp
clang/lib/Sema/SemaTemplateInstantiate.cpp
clang/lib/Sema/SemaTemplateInstantiateDecl.cpp
clang/lib/Sema/TreeTransform.h
clang/lib/Serialization/ASTReaderDecl.cpp
clang/lib/Serialization/ASTWriterDecl.cpp

clang/test/CXX/temp/temp.constr/temp.constr.constr/non-function-templates.cpp
clang/test/SemaTemplate/concepts.cpp
clang/test/SemaTemplate/instantiate-requires-clause.cpp

Removed: 




diff  --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 91944e0b11ef0..839a7035a94fd 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -275,6 +275,10 @@ C++20 Feature Support
   `Issue 54578 `_.
 
 - Implemented `__builtin_source_location()` which enables library support for 
std::source_location.
+- Clang now correctly delays the instantiation of function constraints until
+  the time of checking, which should now allow the libstdc++ ranges 
implementation
+  to work for at least trivial examples.  This fixes
+  `Issue 44178 `_.
 
 - The mangling scheme for C++20 modules has incompatibly changed. The
   initial mangling was discovered not to be reversible, and the weak

diff  --git a/clang/include/clang/AST/Decl.h b/clang/include/clang/AST/Decl.h
index c2133f4e79a15..6de480dbfe1ad 100644
--- a/clang/include/clang/AST/Decl.h
+++ b/clang/include/clang/AST/Decl.h
@@ -1890,7 +1890,9 @@ class FunctionDecl : public DeclaratorDecl,
 TK_FunctionTemplateSpecialization,
 // A function template specialization that hasn't yet been resolved to a
 // particular specialized function template.
-TK_DependentFunctionTemplateSpecialization
+TK_DependentFunctionTemplateSpecialization,
+// A non templated function which is in a dependent scope.
+TK_DependentNonTemplate
   };
 
   /// Stashed information about a defaulted function definition whose body has
@@ -1939,20 +1941,21 @@ class FunctionDecl : public DeclaratorDecl,
   /// The template or declaration that this declaration
   /// describes or was instantiated from, respectively.
   ///
-  /// For non-templates, this value will be NULL. For function
-  /// declarations that describe a function template, this will be a
-  /// pointer to a FunctionTemplateDecl. For member functions
-  /// of class template specializations, this will be a 
MemberSpecializationInfo
-  /// pointer containing information about the specialization.
-  /// For function template specializations, this will be a
-  /// FunctionTemplateSpecializationInfo, which contains information about
-  /// the template being specialized and the template arguments involved in
-  /// that specialization.
-  llvm::PointerUnion
-TemplateOrSpecialization;
+  TemplateOrSpecialization;
 
   /// Provides source/type location info for the declaration name embedded in
   /// the DeclaratorDecl base class.
@@ -2688,6 +2691,11 @@ class FunctionDecl : public DeclaratorDecl,
 setInstantiationOfMemberFunction(getASTContext(), FD, TSK);
   }
 
+  /// Specify that this function declaration was instantiated from FunctionDecl
+  /// FD. This is only used if this is a function declaration declared locally
+  /// inside of a function template.
+  void setInstantiatedFromDecl(FunctionDecl *FD);
+
   /// Retrieves the function template that is described by this
   /// function declaration.
   ///
@@ -2702,6 +2710,8 @@ class FunctionDecl : public DeclaratorDecl,
   /// FunctionTemplateDecl from a FunctionDecl.
   FunctionTemplateDecl *getDescribedFunctionTemplate() const;
 
+  FunctionDecl *getInstantiatedFromDecl()

[PATCH] D119544: Deferred Concept Instantiation Implementation

2022-05-02 Thread Erich Keane 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 rG4b6c2cd647e9: Deferred Concept Instantiation Implementation 
(authored by erichkeane).
Herald added a project: clang.

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D119544

Files:
  clang/docs/ReleaseNotes.rst
  clang/include/clang/AST/Decl.h
  clang/include/clang/AST/DeclBase.h
  clang/include/clang/Sema/Sema.h
  clang/include/clang/Sema/Template.h
  clang/lib/AST/ASTImporter.cpp
  clang/lib/AST/Decl.cpp
  clang/lib/AST/DeclBase.cpp
  clang/lib/ExtractAPI/ExtractAPIConsumer.cpp
  clang/lib/Sema/SemaConcept.cpp
  clang/lib/Sema/SemaTemplate.cpp
  clang/lib/Sema/SemaTemplateDeduction.cpp
  clang/lib/Sema/SemaTemplateInstantiate.cpp
  clang/lib/Sema/SemaTemplateInstantiateDecl.cpp
  clang/lib/Sema/TreeTransform.h
  clang/lib/Serialization/ASTReaderDecl.cpp
  clang/lib/Serialization/ASTWriterDecl.cpp
  clang/test/CXX/temp/temp.constr/temp.constr.constr/non-function-templates.cpp
  clang/test/SemaTemplate/concepts.cpp
  clang/test/SemaTemplate/deferred-concept-inst.cpp
  clang/test/SemaTemplate/instantiate-requires-clause.cpp
  clang/test/SemaTemplate/trailing-return-short-circuit.cpp

Index: clang/test/SemaTemplate/trailing-return-short-circuit.cpp
===
--- /dev/null
+++ clang/test/SemaTemplate/trailing-return-short-circuit.cpp
@@ -0,0 +1,62 @@
+// RUN: %clang_cc1 -std=c++20 -verify %s
+
+template 
+  requires(sizeof(T) > 2) || T::value // #FOO_REQ
+void Foo(T){};// #FOO
+
+template 
+void TrailingReturn(T)   // #TRAILING
+  requires(sizeof(T) > 2) || // #TRAILING_REQ
+  T::value   // #TRAILING_REQ_VAL
+{};
+template 
+struct HasValue {
+  static constexpr bool value = B;
+};
+static_assert(sizeof(HasValue) <= 2);
+
+template 
+struct HasValueLarge {
+  static constexpr bool value = B;
+  int I;
+};
+static_assert(sizeof(HasValueLarge) > 2);
+
+void usage() {
+  // Passes the 1st check, short-circuit so the 2nd ::value is not evaluated.
+  Foo(1.0);
+  TrailingReturn(1.0);
+
+  // Fails the 1st check, but has a ::value, so the check happens correctly.
+  Foo(HasValue{});
+  TrailingReturn(HasValue{});
+
+  // Passes the 1st check, but would have passed the 2nd one.
+  Foo(HasValueLarge{});
+  TrailingReturn(HasValueLarge{});
+
+  // Fails the 1st check, fails 2nd because there is no ::value.
+  Foo(true);
+  // expected-error@-1{{no matching function for call to 'Foo'}}
+  // expected-note@#FOO{{candidate template ignored: constraints not satisfied [with T = bool]}}
+  // expected-note@#FOO_REQ{{because 'sizeof(_Bool) > 2' (1 > 2) evaluated to false}}
+  // expected-note@#FOO_REQ{{because substituted constraint expression is ill-formed: type 'bool' cannot be used prior to '::' because it has no members}}
+
+  TrailingReturn(true);
+  // expected-error@-1{{no matching function for call to 'TrailingReturn'}}
+  // expected-note@#TRAILING{{candidate template ignored: constraints not satisfied [with T = bool]}}
+  // expected-note@#TRAILING_REQ{{because 'sizeof(_Bool) > 2' (1 > 2) evaluated to false}}
+  // expected-note@#TRAILING_REQ_VAL{{because substituted constraint expression is ill-formed: type 'bool' cannot be used prior to '::' because it has no members}}
+
+  // Fails the 1st check, fails 2nd because ::value is false.
+  Foo(HasValue{});
+  // expected-error@-1 {{no matching function for call to 'Foo'}}
+  // expected-note@#FOO{{candidate template ignored: constraints not satisfied [with T = HasValue]}}
+  // expected-note@#FOO_REQ{{because 'sizeof(HasValue) > 2' (1 > 2) evaluated to false}}
+  // expected-note@#FOO_REQ{{and 'HasValue::value' evaluated to false}}
+  TrailingReturn(HasValue{});
+  // expected-error@-1 {{no matching function for call to 'TrailingReturn'}}
+  // expected-note@#TRAILING{{candidate template ignored: constraints not satisfied [with T = HasValue]}}
+  // expected-note@#TRAILING_REQ{{because 'sizeof(HasValue) > 2' (1 > 2) evaluated to false}}
+  // expected-note@#TRAILING_REQ_VAL{{and 'HasValue::value' evaluated to false}}
+}
Index: clang/test/SemaTemplate/instantiate-requires-clause.cpp
===
--- clang/test/SemaTemplate/instantiate-requires-clause.cpp
+++ clang/test/SemaTemplate/instantiate-requires-clause.cpp
@@ -1,4 +1,4 @@
-// RUN: %clang_cc1 -std=c++2a -x c++ %s -verify
+// RUN: %clang_cc1 -std=c++2a -x c++ %s -Wno-unused-value -verify
 
 template  requires ((sizeof(Args) == 1), ...)
 // expected-note@-1 {{because '(sizeof(int) == 1) , (sizeof(char) == 1) , (sizeof(int) == 1)' evaluated to false}}
@@ -40,6 +40,20 @@
 
 static_assert(S::f(1));
 
+// Similar to the 'S' test, but tries to use 'U' in the requires clause.
+template 
+struct S1 {
+  // expected-note@+3 {{candidate te

[PATCH] D124767: [Clang] Map .gcda paths according to -fcoverage-prefix-map

2022-05-02 Thread Vitaly Cheptsov via Phabricator via cfe-commits
vit9696 created this revision.
vit9696 added reviewers: keith, phosek.
Herald added a project: All.
vit9696 requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

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


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D124767

Files:
  clang/lib/CodeGen/CodeGenModule.cpp


Index: clang/lib/CodeGen/CodeGenModule.cpp
===
--- clang/lib/CodeGen/CodeGenModule.cpp
+++ clang/lib/CodeGen/CodeGenModule.cpp
@@ -6550,8 +6550,20 @@
 
   llvm::NamedMDNode *GCov = TheModule.getOrInsertNamedMetadata("llvm.gcov");
   llvm::LLVMContext &Ctx = TheModule.getContext();
-  auto *CoverageDataFile =
+  auto &PrefixMap = getCodeGenOpts().CoveragePrefixMap;
+  llvm::SmallString<256> File;
+  if (!PrefixMap.empty()) {
+File = getCodeGenOpts().CoverageDataFile;
+llvm::sys::path::remove_dots(File, /*remove_dot_dot=*/true);
+for (const auto &Entry : PrefixMap) {
+  if (llvm::sys::path::replace_path_prefix(File, Entry.first, 
Entry.second))
+break;
+}
+CoverageDataFile = llvm::MDString::get(Ctx, File.c_str());
+  } else {
+CoverageDataFile =
   llvm::MDString::get(Ctx, getCodeGenOpts().CoverageDataFile);
+  }
   auto *CoverageNotesFile =
   llvm::MDString::get(Ctx, getCodeGenOpts().CoverageNotesFile);
   for (int i = 0, e = CUNode->getNumOperands(); i != e; ++i) {


Index: clang/lib/CodeGen/CodeGenModule.cpp
===
--- clang/lib/CodeGen/CodeGenModule.cpp
+++ clang/lib/CodeGen/CodeGenModule.cpp
@@ -6550,8 +6550,20 @@
 
   llvm::NamedMDNode *GCov = TheModule.getOrInsertNamedMetadata("llvm.gcov");
   llvm::LLVMContext &Ctx = TheModule.getContext();
-  auto *CoverageDataFile =
+  auto &PrefixMap = getCodeGenOpts().CoveragePrefixMap;
+  llvm::SmallString<256> File;
+  if (!PrefixMap.empty()) {
+File = getCodeGenOpts().CoverageDataFile;
+llvm::sys::path::remove_dots(File, /*remove_dot_dot=*/true);
+for (const auto &Entry : PrefixMap) {
+  if (llvm::sys::path::replace_path_prefix(File, Entry.first, Entry.second))
+break;
+}
+CoverageDataFile = llvm::MDString::get(Ctx, File.c_str());
+  } else {
+CoverageDataFile =
   llvm::MDString::get(Ctx, getCodeGenOpts().CoverageDataFile);
+  }
   auto *CoverageNotesFile =
   llvm::MDString::get(Ctx, getCodeGenOpts().CoverageNotesFile);
   for (int i = 0, e = CUNode->getNumOperands(); i != e; ++i) {
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D124534: [clang] Add a diagnostic for line directive of a gnu extension

2022-05-02 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman added inline comments.



Comment at: clang/lib/Lex/PPDirectives.cpp:1356
+
+PP.Diag(FlagTok, diag::ext_pp_gnu_line_directive);
   } else if (FlagVal == 2) {

ken-matsui wrote:
> aaron.ballman wrote:
> > ken-matsui wrote:
> > > aaron.ballman wrote:
> > > > I speculate that this change is wrong.
> > > > 
> > > > The goal here is to diagnose any time there's a GNU line marker and now 
> > > > we're only trigging the diagnostic when the line marker's value is 1; 
> > > > that misses diagnostics when the marker value is something else.
> > > > 
> > > > That's why I suggested warning each place we return `false` from this 
> > > > function -- those are the situations when the line marker is 
> > > > syntactically correct and we're going to make use of it in the caller. 
> > > > (We don't want to warn about use of a line marker when we're going to 
> > > > generate an error anyway.)
> > > @aaron.ballman 
> > > 
> > > Thank you!
> > > 
> > > Just to confirm, do I need to remove the call of `Diag` after 
> > > `GetLineValue` and put `Diag`s into all branches of returning `false` in 
> > > this function?
> > > If so, I think putting `Diag` after the call of this function would be 
> > > better.
> > > If so, I think putting Diag after the call of this function would be 
> > > better.
> > 
> > You are correct and I agree, good suggestion!
> @aaron.ballman 
> Thank you for your response!
> 
> I've updated the code as mentioned, but a bunch of other tests with the 
> `-pedantic` option failed as the following warnings:
> 
> ```
>  TEST 'Clang :: CXX/expr/expr.const/p2-0x.cpp' FAILED 
> 
> Script:
> --
> : 'RUN: at line 1';   /tmp/llvm/llvm-project/build/bin/clang -cc1 
> -internal-isystem /tmp/llvm/llvm-project/build/lib/clang/15.0.0/include 
> -nostdsysteminc -fsyntax-only -std=c++11 -pedantic -verify=expected,cxx11 
> -fcxx-exceptions 
> /tmp/llvm/llvm-project/clang/test/CXX/expr/expr.const/p2-0x.cpp 
> -fconstexpr-depth 128 -triple i686-pc-linux-gnu
> : 'RUN: at line 2';   /tmp/llvm/llvm-project/build/bin/clang -cc1 
> -internal-isystem /tmp/llvm/llvm-project/build/lib/clang/15.0.0/include 
> -nostdsysteminc -fsyntax-only -std=c++2a -pedantic -verify=expected,cxx20 
> -fcxx-exceptions 
> /tmp/llvm/llvm-project/clang/test/CXX/expr/expr.const/p2-0x.cpp 
> -fconstexpr-depth 128 -triple i686-pc-linux-gnu
> --
> Exit Code: 1
> 
> Command Output (stderr):
> --
> error: 'warning' diagnostics seen but not expected: 
>   Line 0: this style of line directive is a GNU extension
>   Line 0: this style of line directive is a GNU extension
> 2 errors generated.
> 
> ...
> ```
> 
> I personally think it would be preferable if the only change of tests would 
> be `line-directive.c`.
> So, how about reducing `Diag` calls until the warning doesn't spill over into 
> other tests?
> I personally think it would be preferable if the only change of tests would 
> be line-directive.c.
> So, how about reducing Diag calls until the warning doesn't spill over into 
> other tests?

No, this is expected. We're adding a diagnostic where there wasn't one 
previously, so some files are going to get caught by that. You can either add 
the `// expected-warning {{}}` comments to those lines, or if the test has a 
lot of those lines but isn't really specific to line markers (it just happens 
to use them to test other functionality) you can disable the diagnostic for 
that test with `-Wno-gnu-line-marker`.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124534

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


[PATCH] D124694: [randstruct] Move initializer check to be more effective

2022-05-02 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman added a comment.

  struct t {
 int a, b, c, d, e;
  } x = { .a = 2, 4, 5, 6 };

This situation seems like it should be an error, shouldn't it? The user 
specified one designated initializer (yay, that one is correct), but the rest 
are positional initializers and so there's no telling what they actually 
initialize due to field randomization.




Comment at: clang/test/Sema/init-randomized-struct.c:1
-// RUN: %clang_cc1 -triple=x86_64-unknown-linux 
-frandomize-layout-seed=1234567890abcdef \
+// RUN: %clang_cc1 -triple=x86_64-unknown-linux 
-frandomize-layout-seed=1234567890abcded \
 // RUN:  -verify -fsyntax-only -Werror %s

Why is this change needed?

(Also, shouldn't there be other test coverage added to the file?)


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124694

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


[PATCH] D124758: [analyzer] Implement assume in terms of assumeDual

2022-05-02 Thread Balázs Benics via Phabricator via cfe-commits
steakhal accepted this revision.
steakhal added a comment.
This revision is now accepted and ready to land.

The patch looks great. Thanks for the stats.

Beyond that, I feel these tests sooo fragile; Although I don't have anything to 
improve that, so be it.




Comment at: clang/test/Analysis/infeasible-crash.c:3
+// RUN:   -analyzer-checker=core \
+// RUN:   
-analyzer-checker=alpha.unix.cstring.OutOfBounds,alpha.unix.cstring.UninitializedRead
 \
+// RUN:   -analyzer-checker=debug.ExprInspection \

Do we really need this?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124758

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


[PATCH] D124768: update

2022-05-02 Thread Shivam Rajput via Phabricator via cfe-commits
phyBrackets created this revision.
Herald added a project: All.
phyBrackets requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D124768

Files:
  clang/include/clang/AST/ASTImportError.h


Index: clang/include/clang/AST/ASTImportError.h
===
--- clang/include/clang/AST/ASTImportError.h
+++ clang/include/clang/AST/ASTImportError.h
@@ -11,6 +11,9 @@
 //
 
//===--===//
 
+#ifndef LLVM_CLANG_AST_ASTIMPORTERROR_H
+#define LLVM_CLANG_AST_ASTIMPORTERROR_H
+
 #include "llvm/Support/Error.h"
 #include "clang/AST/APValue.h"
 
@@ -43,4 +46,6 @@
 std::error_code convertToErrorCode() const override;
   };
 
-}
+  } // namespace clang
+
+#endif // LLVM_CLANG_AST_ASTIMPORTERROR_H


Index: clang/include/clang/AST/ASTImportError.h
===
--- clang/include/clang/AST/ASTImportError.h
+++ clang/include/clang/AST/ASTImportError.h
@@ -11,6 +11,9 @@
 //
 //===--===//
 
+#ifndef LLVM_CLANG_AST_ASTIMPORTERROR_H
+#define LLVM_CLANG_AST_ASTIMPORTERROR_H
+
 #include "llvm/Support/Error.h"
 #include "clang/AST/APValue.h"
 
@@ -43,4 +46,6 @@
 std::error_code convertToErrorCode() const override;
   };
 
-}
+  } // namespace clang
+
+#endif // LLVM_CLANG_AST_ASTIMPORTERROR_H
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D124761: [analyzer] Replace adjacent assumeInBound calls to assumeInBoundDual

2022-05-02 Thread Balázs Benics via Phabricator via cfe-commits
steakhal accepted this revision.
steakhal added a comment.
This revision is now accepted and ready to land.

LGTM; Although, I missed some doc comments here and there. This is a really 
important API, it deserves a few words.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124761

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


[clang] 0c31da4 - Revert "Deferred Concept Instantiation Implementation"

2022-05-02 Thread Erich Keane via cfe-commits

Author: Erich Keane
Date: 2022-05-02T06:25:38-07:00
New Revision: 0c31da48389754822dc3eecc4723160c295b9ab2

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

LOG: Revert "Deferred Concept Instantiation Implementation"

This reverts commit 4b6c2cd647e9e5a147954886338f97ffb6a1bcfb.

The patch caused numerous ARM 32 bit build failures, since we added a
5th item to the PointerUnion, and went over the 2-bits available in the
32 bit pointers.

Added: 


Modified: 
clang/docs/ReleaseNotes.rst
clang/include/clang/AST/Decl.h
clang/include/clang/AST/DeclBase.h
clang/include/clang/Sema/Sema.h
clang/include/clang/Sema/Template.h
clang/lib/AST/ASTImporter.cpp
clang/lib/AST/Decl.cpp
clang/lib/AST/DeclBase.cpp
clang/lib/ExtractAPI/ExtractAPIConsumer.cpp
clang/lib/Sema/SemaConcept.cpp
clang/lib/Sema/SemaTemplate.cpp
clang/lib/Sema/SemaTemplateDeduction.cpp
clang/lib/Sema/SemaTemplateInstantiate.cpp
clang/lib/Sema/SemaTemplateInstantiateDecl.cpp
clang/lib/Sema/TreeTransform.h
clang/lib/Serialization/ASTReaderDecl.cpp
clang/lib/Serialization/ASTWriterDecl.cpp

clang/test/CXX/temp/temp.constr/temp.constr.constr/non-function-templates.cpp
clang/test/SemaTemplate/concepts.cpp
clang/test/SemaTemplate/instantiate-requires-clause.cpp

Removed: 
clang/test/SemaTemplate/deferred-concept-inst.cpp
clang/test/SemaTemplate/trailing-return-short-circuit.cpp



diff  --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 839a7035a94fd..91944e0b11ef0 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -275,10 +275,6 @@ C++20 Feature Support
   `Issue 54578 `_.
 
 - Implemented `__builtin_source_location()` which enables library support for 
std::source_location.
-- Clang now correctly delays the instantiation of function constraints until
-  the time of checking, which should now allow the libstdc++ ranges 
implementation
-  to work for at least trivial examples.  This fixes
-  `Issue 44178 `_.
 
 - The mangling scheme for C++20 modules has incompatibly changed. The
   initial mangling was discovered not to be reversible, and the weak

diff  --git a/clang/include/clang/AST/Decl.h b/clang/include/clang/AST/Decl.h
index 6de480dbfe1ad..c2133f4e79a15 100644
--- a/clang/include/clang/AST/Decl.h
+++ b/clang/include/clang/AST/Decl.h
@@ -1890,9 +1890,7 @@ class FunctionDecl : public DeclaratorDecl,
 TK_FunctionTemplateSpecialization,
 // A function template specialization that hasn't yet been resolved to a
 // particular specialized function template.
-TK_DependentFunctionTemplateSpecialization,
-// A non templated function which is in a dependent scope.
-TK_DependentNonTemplate
+TK_DependentFunctionTemplateSpecialization
   };
 
   /// Stashed information about a defaulted function definition whose body has
@@ -1941,21 +1939,20 @@ class FunctionDecl : public DeclaratorDecl,
   /// The template or declaration that this declaration
   /// describes or was instantiated from, respectively.
   ///
-  /// For non-templates this value will be NULL, unless this non-template
-  /// function declaration was declared directly inside of a function template,
-  /// in which case this will have a pointer to a FunctionDecl. For function
-  /// declarations that describe a function template, this will be a pointer to
-  /// a FunctionTemplateDecl. For member functions of class template
-  /// specializations, this will be a MemberSpecializationInfo pointer
-  /// containing information about the specialization. For function template
-  /// specializations, this will be a FunctionTemplateSpecializationInfo, which
-  /// contains information about the template being specialized and the 
template
-  /// arguments involved in that specialization.
-  llvm::PointerUnion
-  TemplateOrSpecialization;
+TemplateOrSpecialization;
 
   /// Provides source/type location info for the declaration name embedded in
   /// the DeclaratorDecl base class.
@@ -2691,11 +2688,6 @@ class FunctionDecl : public DeclaratorDecl,
 setInstantiationOfMemberFunction(getASTContext(), FD, TSK);
   }
 
-  /// Specify that this function declaration was instantiated from FunctionDecl
-  /// FD. This is only used if this is a function declaration declared locally
-  /// inside of a function template.
-  void setInstantiatedFromDecl(FunctionDecl *FD);
-
   /// Retrieves the function template that is described by this
   /// function declaration.
   ///
@@ -2710,8 +2702,6 @@ class FunctionDecl : public DeclaratorDecl,
   /// FunctionTemplateDecl from a FunctionDecl.
   FunctionTemplateDecl *getDescribedFunctionTe

[clang] 9a14c36 - [X86] Replace avx512f integer add reduction builtins with generic builtin

2022-05-02 Thread Simon Pilgrim via cfe-commits

Author: Simon Pilgrim
Date: 2022-05-02T14:39:17+01:00
New Revision: 9a14c369c422b244db78f1a9f947a891a75d912f

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

LOG: [X86] Replace avx512f integer add reduction builtins with generic builtin

D124741 added the generic "__builtin_reduce_add" which we can use to replace 
the x86 specific integer add reduction builtins - internally these were mapping 
to the same intrinsic already so there are no test changes required.

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

Added: 


Modified: 
clang/include/clang/Basic/BuiltinsX86.def
clang/lib/CodeGen/CGBuiltin.cpp
clang/lib/Headers/avx512fintrin.h

Removed: 




diff  --git a/clang/include/clang/Basic/BuiltinsX86.def 
b/clang/include/clang/Basic/BuiltinsX86.def
index 449acfbec5630..6de7e6f89b47d 100644
--- a/clang/include/clang/Basic/BuiltinsX86.def
+++ b/clang/include/clang/Basic/BuiltinsX86.def
@@ -1990,8 +1990,6 @@ TARGET_BUILTIN(__builtin_ia32_selectss_128, 
"V4fUcV4fV4f", "ncV:128:", "avx512f"
 TARGET_BUILTIN(__builtin_ia32_selectsd_128, "V2dUcV2dV2d", "ncV:128:", 
"avx512f")
 
 // generic reduction intrinsics
-TARGET_BUILTIN(__builtin_ia32_reduce_add_d512, "iV16i", "ncV:512:", "avx512f")
-TARGET_BUILTIN(__builtin_ia32_reduce_add_q512, "OiV8Oi", "ncV:512:", "avx512f")
 TARGET_BUILTIN(__builtin_ia32_reduce_fadd_pd512, "ddV8d", "ncV:512:", 
"avx512f")
 TARGET_BUILTIN(__builtin_ia32_reduce_fadd_ps512, "ffV16f", "ncV:512:", 
"avx512f")
 TARGET_BUILTIN(__builtin_ia32_reduce_fadd_ph512, "xxV32x", "ncV:512:", 
"avx512fp16")

diff  --git a/clang/lib/CodeGen/CGBuiltin.cpp b/clang/lib/CodeGen/CGBuiltin.cpp
index 4c203904a0e0e..caea5d16b2659 100644
--- a/clang/lib/CodeGen/CGBuiltin.cpp
+++ b/clang/lib/CodeGen/CGBuiltin.cpp
@@ -14496,12 +14496,6 @@ Value *CodeGenFunction::EmitX86BuiltinExpr(unsigned 
BuiltinID,
 return EmitX86FunnelShift(*this, Ops[1], Ops[0], Ops[2], true);
 
   // Reductions
-  case X86::BI__builtin_ia32_reduce_add_d512:
-  case X86::BI__builtin_ia32_reduce_add_q512: {
-Function *F =
-CGM.getIntrinsic(Intrinsic::vector_reduce_add, Ops[0]->getType());
-return Builder.CreateCall(F, {Ops[0]});
-  }
   case X86::BI__builtin_ia32_reduce_fadd_pd512:
   case X86::BI__builtin_ia32_reduce_fadd_ps512:
   case X86::BI__builtin_ia32_reduce_fadd_ph512:

diff  --git a/clang/lib/Headers/avx512fintrin.h 
b/clang/lib/Headers/avx512fintrin.h
index d10493fdd0e66..c7f3c96106076 100644
--- a/clang/lib/Headers/avx512fintrin.h
+++ b/clang/lib/Headers/avx512fintrin.h
@@ -9319,7 +9319,7 @@ _mm512_mask_abs_pd(__m512d __W, __mmask8 __K, __m512d __A)
  */
 
 static __inline__ long long __DEFAULT_FN_ATTRS512 
_mm512_reduce_add_epi64(__m512i __W) {
-  return __builtin_ia32_reduce_add_q512(__W);
+  return __builtin_reduce_add((__v8di)__W);
 }
 
 static __inline__ long long __DEFAULT_FN_ATTRS512 
_mm512_reduce_mul_epi64(__m512i __W) {
@@ -9337,7 +9337,7 @@ static __inline__ long long __DEFAULT_FN_ATTRS512 
_mm512_reduce_or_epi64(__m512i
 static __inline__ long long __DEFAULT_FN_ATTRS512
 _mm512_mask_reduce_add_epi64(__mmask8 __M, __m512i __W) {
   __W = _mm512_maskz_mov_epi64(__M, __W);
-  return __builtin_ia32_reduce_add_q512(__W);
+  return __builtin_reduce_add((__v8di)__W);
 }
 
 static __inline__ long long __DEFAULT_FN_ATTRS512
@@ -9383,7 +9383,7 @@ _mm512_mask_reduce_mul_pd(__mmask8 __M, __m512d __W) {
 
 static __inline__ int __DEFAULT_FN_ATTRS512
 _mm512_reduce_add_epi32(__m512i __W) {
-  return __builtin_ia32_reduce_add_d512((__v16si)__W);
+  return __builtin_reduce_add((__v16si)__W);
 }
 
 static __inline__ int __DEFAULT_FN_ATTRS512
@@ -9404,7 +9404,7 @@ _mm512_reduce_or_epi32(__m512i __W) {
 static __inline__ int __DEFAULT_FN_ATTRS512
 _mm512_mask_reduce_add_epi32( __mmask16 __M, __m512i __W) {
   __W = _mm512_maskz_mov_epi32(__M, __W);
-  return __builtin_ia32_reduce_add_d512((__v16si)__W);
+  return __builtin_reduce_add((__v16si)__W);
 }
 
 static __inline__ int __DEFAULT_FN_ATTRS512



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


[PATCH] D124757: [X86] Replace avx512f integer add reduction builtins with generic builtin

2022-05-02 Thread Simon Pilgrim via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG9a14c369c422: [X86] Replace avx512f integer add reduction 
builtins with generic builtin (authored by RKSimon).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124757

Files:
  clang/include/clang/Basic/BuiltinsX86.def
  clang/lib/CodeGen/CGBuiltin.cpp
  clang/lib/Headers/avx512fintrin.h


Index: clang/lib/Headers/avx512fintrin.h
===
--- clang/lib/Headers/avx512fintrin.h
+++ clang/lib/Headers/avx512fintrin.h
@@ -9319,7 +9319,7 @@
  */
 
 static __inline__ long long __DEFAULT_FN_ATTRS512 
_mm512_reduce_add_epi64(__m512i __W) {
-  return __builtin_ia32_reduce_add_q512(__W);
+  return __builtin_reduce_add((__v8di)__W);
 }
 
 static __inline__ long long __DEFAULT_FN_ATTRS512 
_mm512_reduce_mul_epi64(__m512i __W) {
@@ -9337,7 +9337,7 @@
 static __inline__ long long __DEFAULT_FN_ATTRS512
 _mm512_mask_reduce_add_epi64(__mmask8 __M, __m512i __W) {
   __W = _mm512_maskz_mov_epi64(__M, __W);
-  return __builtin_ia32_reduce_add_q512(__W);
+  return __builtin_reduce_add((__v8di)__W);
 }
 
 static __inline__ long long __DEFAULT_FN_ATTRS512
@@ -9383,7 +9383,7 @@
 
 static __inline__ int __DEFAULT_FN_ATTRS512
 _mm512_reduce_add_epi32(__m512i __W) {
-  return __builtin_ia32_reduce_add_d512((__v16si)__W);
+  return __builtin_reduce_add((__v16si)__W);
 }
 
 static __inline__ int __DEFAULT_FN_ATTRS512
@@ -9404,7 +9404,7 @@
 static __inline__ int __DEFAULT_FN_ATTRS512
 _mm512_mask_reduce_add_epi32( __mmask16 __M, __m512i __W) {
   __W = _mm512_maskz_mov_epi32(__M, __W);
-  return __builtin_ia32_reduce_add_d512((__v16si)__W);
+  return __builtin_reduce_add((__v16si)__W);
 }
 
 static __inline__ int __DEFAULT_FN_ATTRS512
Index: clang/lib/CodeGen/CGBuiltin.cpp
===
--- clang/lib/CodeGen/CGBuiltin.cpp
+++ clang/lib/CodeGen/CGBuiltin.cpp
@@ -14496,12 +14496,6 @@
 return EmitX86FunnelShift(*this, Ops[1], Ops[0], Ops[2], true);
 
   // Reductions
-  case X86::BI__builtin_ia32_reduce_add_d512:
-  case X86::BI__builtin_ia32_reduce_add_q512: {
-Function *F =
-CGM.getIntrinsic(Intrinsic::vector_reduce_add, Ops[0]->getType());
-return Builder.CreateCall(F, {Ops[0]});
-  }
   case X86::BI__builtin_ia32_reduce_fadd_pd512:
   case X86::BI__builtin_ia32_reduce_fadd_ps512:
   case X86::BI__builtin_ia32_reduce_fadd_ph512:
Index: clang/include/clang/Basic/BuiltinsX86.def
===
--- clang/include/clang/Basic/BuiltinsX86.def
+++ clang/include/clang/Basic/BuiltinsX86.def
@@ -1990,8 +1990,6 @@
 TARGET_BUILTIN(__builtin_ia32_selectsd_128, "V2dUcV2dV2d", "ncV:128:", 
"avx512f")
 
 // generic reduction intrinsics
-TARGET_BUILTIN(__builtin_ia32_reduce_add_d512, "iV16i", "ncV:512:", "avx512f")
-TARGET_BUILTIN(__builtin_ia32_reduce_add_q512, "OiV8Oi", "ncV:512:", "avx512f")
 TARGET_BUILTIN(__builtin_ia32_reduce_fadd_pd512, "ddV8d", "ncV:512:", 
"avx512f")
 TARGET_BUILTIN(__builtin_ia32_reduce_fadd_ps512, "ffV16f", "ncV:512:", 
"avx512f")
 TARGET_BUILTIN(__builtin_ia32_reduce_fadd_ph512, "xxV32x", "ncV:512:", 
"avx512fp16")


Index: clang/lib/Headers/avx512fintrin.h
===
--- clang/lib/Headers/avx512fintrin.h
+++ clang/lib/Headers/avx512fintrin.h
@@ -9319,7 +9319,7 @@
  */
 
 static __inline__ long long __DEFAULT_FN_ATTRS512 _mm512_reduce_add_epi64(__m512i __W) {
-  return __builtin_ia32_reduce_add_q512(__W);
+  return __builtin_reduce_add((__v8di)__W);
 }
 
 static __inline__ long long __DEFAULT_FN_ATTRS512 _mm512_reduce_mul_epi64(__m512i __W) {
@@ -9337,7 +9337,7 @@
 static __inline__ long long __DEFAULT_FN_ATTRS512
 _mm512_mask_reduce_add_epi64(__mmask8 __M, __m512i __W) {
   __W = _mm512_maskz_mov_epi64(__M, __W);
-  return __builtin_ia32_reduce_add_q512(__W);
+  return __builtin_reduce_add((__v8di)__W);
 }
 
 static __inline__ long long __DEFAULT_FN_ATTRS512
@@ -9383,7 +9383,7 @@
 
 static __inline__ int __DEFAULT_FN_ATTRS512
 _mm512_reduce_add_epi32(__m512i __W) {
-  return __builtin_ia32_reduce_add_d512((__v16si)__W);
+  return __builtin_reduce_add((__v16si)__W);
 }
 
 static __inline__ int __DEFAULT_FN_ATTRS512
@@ -9404,7 +9404,7 @@
 static __inline__ int __DEFAULT_FN_ATTRS512
 _mm512_mask_reduce_add_epi32( __mmask16 __M, __m512i __W) {
   __W = _mm512_maskz_mov_epi32(__M, __W);
-  return __builtin_ia32_reduce_add_d512((__v16si)__W);
+  return __builtin_reduce_add((__v16si)__W);
 }
 
 static __inline__ int __DEFAULT_FN_ATTRS512
Index: clang/lib/CodeGen/CGBuiltin.cpp
===
--- clang/lib/CodeGen/CGBuiltin.cpp
+++ clang/lib/CodeGen/CGBuiltin.cpp
@@ -14496,12 +14496,6 @@
 return EmitX86FunnelShift(*this, Ops[1], Ops[0], Ops[2], true);
 
   // Redu

[PATCH] D124701: [clang] Honor __attribute__((no_builtin("foo"))) on functions

2022-05-02 Thread Stephen Long via Phabricator via cfe-commits
steplong added a comment.

In D124701#3485317 , @hans wrote:

> If I understand correctly, D68028  made it 
> so that LLVM doesn't add any builtin calls (e.g. turning for-loops into 
> memcpy), but Clang could still turn calls into builtins. Maybe the patch 
> description could be expanded to explain this?

I'm not too sure, but I think D68028  just 
adds the attribute nobuiltin, but it gets ignored. It doesn't seem to affect 
the calls in the function. They're still being converted into builtins even 
with the attribute on the function.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124701

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


[PATCH] D124721: [OpenMP] Allow compiling multiple target architectures with OpenMP

2022-05-02 Thread Saiyedul Islam via Phabricator via cfe-commits
saiislam added inline comments.



Comment at: clang/test/Driver/amdgpu-openmp-toolchain-new.c:6
 // RUN:   | FileCheck %s
+// RUN:   %clang -### --target=x86_64-unknown-linux-gnu -fopenmp 
-fopenmp-targets=amdgcn-amd-amdhsa \
+// RUN:  --offload-arch=gfx906 
--libomptarget-amdgpu-bc-path=%S/Inputs/hip_dev_lib %s 2>&1 \

jhuber6 wrote:
> saiislam wrote:
> > saiislam wrote:
> > > jhuber6 wrote:
> > > > saiislam wrote:
> > > > > Wouldn't it be better if the user is not required to specify the 
> > > > > triple in this shorthand version? We can infer the triple from the 
> > > > > GPUArch. We have this support in our downstream branch.
> > > > > 
> > > > > ```
> > > > > clang  --target=x86_64-unknown-linux-gnu -fopenmp 
> > > > > --offload-arch=gfx906 helloworld.c -o helloworld
> > > > > ```
> > > > We could, HIP and CUDA both use some kind of 
> > > > `getAMDOffloadTargetTriple`. I guess in this case we would consider 
> > > > OpenMP offloading active if the user specified `-fopenmp` and 
> > > > `--offload-arch`? I could do this in a separate patch.
> > > Yes, exactly. OpenMP offloading should be active when `-fopenmp` and 
> > > `--offload-arch` both are present.
> > > 
> > > Thank you!
> > Following code might be useful for your patch (it assumes that OffloadArch 
> > is associated with each device tool chain so that multiple archs of same 
> > triple can be compiled together):
> > 
> > 
> >   # [[ 
> > https://github.com/RadeonOpenCompute/llvm-project/blob/359002f885ea860609f0c841d69f4970ccbb37af/clang/lib/Driver/Driver.cpp#L735
> >  | GetTargetInfoFromOffloadArch() ]]
> >   # [[ 
> > https://github.com/RadeonOpenCompute/llvm-project/blob/359002f885ea860609f0c841d69f4970ccbb37af/clang/lib/Driver/Driver.cpp#L779
> >  | Driver::GetTargetInfoFromMarch() ]]
> >   # [[ 
> > https://github.com/RadeonOpenCompute/llvm-project/blob/359002f885ea860609f0c841d69f4970ccbb37af/clang/lib/Driver/Driver.cpp#L819
> >  | Driver::GetTargetInfoFromOffloadArchOpts() ]]
> >   # [[ 
> > https://github.com/RadeonOpenCompute/llvm-project/blob/359002f885ea860609f0c841d69f4970ccbb37af/clang/lib/Driver/Driver.cpp#L851
> >  | modified definition of Driver::CreateOffloadingDeviceToolChains() ]]
> > 
> I'll look into it, I was thinking of a good way to specify architectures per 
> triple. So we could theoretically have `--offload-arch=sm_70` and 
> `--offload_arch=gfx908` work in unison and it might just be easy to group the 
> triples from the architecture.
Along with this, we would also like to support --offload-arch=gfx906 and 
--offload-arch=gfx908 in the same command.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124721

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


[PATCH] D124701: [clang] Honor __attribute__((no_builtin("foo"))) on functions

2022-05-02 Thread Stephen Long via Phabricator via cfe-commits
steplong updated this revision to Diff 426400.

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124701

Files:
  clang/lib/CodeGen/CGExpr.cpp
  clang/test/CodeGen/no-builtin-2.c


Index: clang/test/CodeGen/no-builtin-2.c
===
--- /dev/null
+++ clang/test/CodeGen/no-builtin-2.c
@@ -0,0 +1,45 @@
+// RUN: %clang_cc1 -emit-llvm -o - %s | FileCheck %s
+
+typedef __typeof_(sizeof(0)) size_t;
+
+void bar(char *s);
+void *memset(void *s, int c, size_t n);
+void *memcpy(void *d, const void *s, size_t n);
+
+// CHECK: define{{.*}} void @foo1({{.*}}) #[[NO_NOBUILTIN:[0-9]+]]
+// CHECK:   call void @bar
+// CHECK:   call void @llvm.memset
+// CHECK:   call void @llvm.memcpy
+void foo1(char *s, char *d, size_t n)
+{
+bar(s);
+memset(s, 0, n);
+memcpy(d, s, n);
+}
+
+// CHECK: define{{.*}} void @foo2({{.*}}) #[[NOBUILTIN_MEMSET:[0-9]+]]
+// CHECK:   call void @bar
+// CHECK:   {{.*}}call i8* @memset
+// CHECK:   call void @llvm.memcpy
+void foo2(char *s, char *d, size_t n) __attribute__((no_builtin("memset")))
+{
+bar(s);
+memset(s, 1, n);
+memcpy(d, s, n);
+}
+
+// CHECK: define{{.*}} void @foo3({{.*}}) #[[NOBUILTIN_MEMSET_MEMCPY:[0-9]+]]
+// CHECK:   call void @bar
+// CHECK:   {{.*}}call i8* @memset
+// CHECK:   {{.*}}call i8* @memcpy
+void foo3(char *s, char *d, size_t n) __attribute__((no_builtin("memset", 
"memcpy")))
+{
+bar(s);
+memset(s, 2, n);
+memcpy(d, s, n);
+}
+
+// CHECK-NOT: attributes #[[NO_NOBUILTIN]] = {{{.*}}"no-builtin-memset"{{.*}}}
+// CHECK-NOT: attributes #[[NO_NOBUILTIN]] = 
{{{.*}}"no-builtin-memcpy"{{.*}}"no-builtin-memset"{{.*}}}
+// CHECK: attributes #[[NOBUILTIN_MEMSET]] = 
{{{.*}}"no-builtin-memset"{{.*}}}
+// CHECK: attributes #[[NOBUILTIN_MEMSET_MEMCPY]] = 
{{{.*}}"no-builtin-memcpy"{{.*}}"no-builtin-memset"{{.*}}}
Index: clang/lib/CodeGen/CGExpr.cpp
===
--- clang/lib/CodeGen/CGExpr.cpp
+++ clang/lib/CodeGen/CGExpr.cpp
@@ -5193,6 +5193,7 @@
   const FunctionDecl *FD = cast(GD.getDecl());
 
   if (auto builtinID = FD->getBuiltinID()) {
+std::string AttributeNoBuiltin = "no-builtin-" + FD->getName().str();
 std::string FDInlineName = (FD->getName() + ".inline").str();
 // When directing calling an inline builtin, call it through it's mangled
 // name to make it clear it's not the actual builtin.
@@ -5213,8 +5214,9 @@
 
 // Replaceable builtins provide their own implementation of a builtin. If 
we
 // are in an inline builtin implementation, avoid trivial infinite
-// recursion.
-else
+// recursion. Honor __attribute__((no_builtin("foo"))) on the current
+// function.
+else if (!CGF.CurFn->getAttributes().hasFnAttr(AttributeNoBuiltin))
   return CGCallee::forBuiltin(builtinID, FD);
   }
 


Index: clang/test/CodeGen/no-builtin-2.c
===
--- /dev/null
+++ clang/test/CodeGen/no-builtin-2.c
@@ -0,0 +1,45 @@
+// RUN: %clang_cc1 -emit-llvm -o - %s | FileCheck %s
+
+typedef __typeof_(sizeof(0)) size_t;
+
+void bar(char *s);
+void *memset(void *s, int c, size_t n);
+void *memcpy(void *d, const void *s, size_t n);
+
+// CHECK: define{{.*}} void @foo1({{.*}}) #[[NO_NOBUILTIN:[0-9]+]]
+// CHECK:   call void @bar
+// CHECK:   call void @llvm.memset
+// CHECK:   call void @llvm.memcpy
+void foo1(char *s, char *d, size_t n)
+{
+bar(s);
+memset(s, 0, n);
+memcpy(d, s, n);
+}
+
+// CHECK: define{{.*}} void @foo2({{.*}}) #[[NOBUILTIN_MEMSET:[0-9]+]]
+// CHECK:   call void @bar
+// CHECK:   {{.*}}call i8* @memset
+// CHECK:   call void @llvm.memcpy
+void foo2(char *s, char *d, size_t n) __attribute__((no_builtin("memset")))
+{
+bar(s);
+memset(s, 1, n);
+memcpy(d, s, n);
+}
+
+// CHECK: define{{.*}} void @foo3({{.*}}) #[[NOBUILTIN_MEMSET_MEMCPY:[0-9]+]]
+// CHECK:   call void @bar
+// CHECK:   {{.*}}call i8* @memset
+// CHECK:   {{.*}}call i8* @memcpy
+void foo3(char *s, char *d, size_t n) __attribute__((no_builtin("memset", "memcpy")))
+{
+bar(s);
+memset(s, 2, n);
+memcpy(d, s, n);
+}
+
+// CHECK-NOT: attributes #[[NO_NOBUILTIN]] = {{{.*}}"no-builtin-memset"{{.*}}}
+// CHECK-NOT: attributes #[[NO_NOBUILTIN]] = {{{.*}}"no-builtin-memcpy"{{.*}}"no-builtin-memset"{{.*}}}
+// CHECK: attributes #[[NOBUILTIN_MEMSET]] = {{{.*}}"no-builtin-memset"{{.*}}}
+// CHECK: attributes #[[NOBUILTIN_MEMSET_MEMCPY]] = {{{.*}}"no-builtin-memcpy"{{.*}}"no-builtin-memset"{{.*}}}
Index: clang/lib/CodeGen/CGExpr.cpp
===
--- clang/lib/CodeGen/CGExpr.cpp
+++ clang/lib/CodeGen/CGExpr.cpp
@@ -5193,6 +5193,7 @@
   const FunctionDecl *FD = cast(GD.getDecl());
 
   if (auto builtinID = FD->getBuiltinID()) {
+std::string AttributeNoBuiltin = "no-builtin-" + FD->getName

[PATCH] D124721: [OpenMP] Allow compiling multiple target architectures with OpenMP

2022-05-02 Thread Joseph Huber via Phabricator via cfe-commits
jhuber6 added inline comments.



Comment at: clang/test/Driver/amdgpu-openmp-toolchain-new.c:6
 // RUN:   | FileCheck %s
+// RUN:   %clang -### --target=x86_64-unknown-linux-gnu -fopenmp 
-fopenmp-targets=amdgcn-amd-amdhsa \
+// RUN:  --offload-arch=gfx906 
--libomptarget-amdgpu-bc-path=%S/Inputs/hip_dev_lib %s 2>&1 \

saiislam wrote:
> jhuber6 wrote:
> > saiislam wrote:
> > > saiislam wrote:
> > > > jhuber6 wrote:
> > > > > saiislam wrote:
> > > > > > Wouldn't it be better if the user is not required to specify the 
> > > > > > triple in this shorthand version? We can infer the triple from the 
> > > > > > GPUArch. We have this support in our downstream branch.
> > > > > > 
> > > > > > ```
> > > > > > clang  --target=x86_64-unknown-linux-gnu -fopenmp 
> > > > > > --offload-arch=gfx906 helloworld.c -o helloworld
> > > > > > ```
> > > > > We could, HIP and CUDA both use some kind of 
> > > > > `getAMDOffloadTargetTriple`. I guess in this case we would consider 
> > > > > OpenMP offloading active if the user specified `-fopenmp` and 
> > > > > `--offload-arch`? I could do this in a separate patch.
> > > > Yes, exactly. OpenMP offloading should be active when `-fopenmp` and 
> > > > `--offload-arch` both are present.
> > > > 
> > > > Thank you!
> > > Following code might be useful for your patch (it assumes that 
> > > OffloadArch is associated with each device tool chain so that multiple 
> > > archs of same triple can be compiled together):
> > > 
> > > 
> > >   # [[ 
> > > https://github.com/RadeonOpenCompute/llvm-project/blob/359002f885ea860609f0c841d69f4970ccbb37af/clang/lib/Driver/Driver.cpp#L735
> > >  | GetTargetInfoFromOffloadArch() ]]
> > >   # [[ 
> > > https://github.com/RadeonOpenCompute/llvm-project/blob/359002f885ea860609f0c841d69f4970ccbb37af/clang/lib/Driver/Driver.cpp#L779
> > >  | Driver::GetTargetInfoFromMarch() ]]
> > >   # [[ 
> > > https://github.com/RadeonOpenCompute/llvm-project/blob/359002f885ea860609f0c841d69f4970ccbb37af/clang/lib/Driver/Driver.cpp#L819
> > >  | Driver::GetTargetInfoFromOffloadArchOpts() ]]
> > >   # [[ 
> > > https://github.com/RadeonOpenCompute/llvm-project/blob/359002f885ea860609f0c841d69f4970ccbb37af/clang/lib/Driver/Driver.cpp#L851
> > >  | modified definition of Driver::CreateOffloadingDeviceToolChains() ]]
> > > 
> > I'll look into it, I was thinking of a good way to specify architectures 
> > per triple. So we could theoretically have `--offload-arch=sm_70` and 
> > `--offload_arch=gfx908` work in unison and it might just be easy to group 
> > the triples from the architecture.
> Along with this, we would also like to support --offload-arch=gfx906 and 
> --offload-arch=gfx908 in the same command.
This patch already supports that, we'll compile for all the architectures and 
they'll all end up linked in the linker wrapper. What's missing is the changes 
to select an appropriate image in the `libomptarget` runtime.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124721

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


[PATCH] D123471: [CUDA] Create offloading entries when using the new driver

2022-05-02 Thread Joseph Huber via Phabricator via cfe-commits
jhuber6 updated this revision to Diff 426404.
jhuber6 added a comment.

Fix test.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D123471

Files:
  clang/include/clang/Basic/LangOptions.def
  clang/include/clang/Driver/Options.td
  clang/lib/CodeGen/CGCUDANV.cpp
  clang/lib/CodeGen/CGCUDARuntime.h
  clang/lib/Driver/ToolChains/Clang.cpp
  clang/test/CodeGenCUDA/offloading-entries.cu

Index: clang/test/CodeGenCUDA/offloading-entries.cu
===
--- /dev/null
+++ clang/test/CodeGenCUDA/offloading-entries.cu
@@ -0,0 +1,33 @@
+// NOTE: Assertions have been autogenerated by utils/update_cc_test_checks.py UTC_ARGS: --check-globals
+// RUN: %clang_cc1 -std=c++11 -triple x86_64-unknown-linux-gnu \
+// RUN:   --offload-new-driver -emit-llvm -o - -x cuda  %s | FileCheck \
+// RUN:   --check-prefix=HOST %s
+
+#include "Inputs/cuda.h"
+
+//.
+// HOST: @x = internal global i32 undef, align 4
+// HOST: @.omp_offloading.entry_name = internal unnamed_addr constant [8 x i8] c"_Z3foov\00"
+// HOST: @.omp_offloading.entry._Z3foov = weak constant %struct.__tgt_offload_entry { ptr @_Z18__device_stub__foov, ptr @.omp_offloading.entry_name, i64 0, i32 0, i32 0 }, section "cuda_offloading_entries", align 1
+// HOST: @.omp_offloading.entry_name.1 = internal unnamed_addr constant [8 x i8] c"_Z3barv\00"
+// HOST: @.omp_offloading.entry._Z3barv = weak constant %struct.__tgt_offload_entry { ptr @_Z18__device_stub__barv, ptr @.omp_offloading.entry_name.1, i64 0, i32 0, i32 0 }, section "cuda_offloading_entries", align 1
+// HOST: @.omp_offloading.entry_name.2 = internal unnamed_addr constant [2 x i8] c"x\00"
+// HOST: @.omp_offloading.entry.x = weak constant %struct.__tgt_offload_entry { ptr @x, ptr @.omp_offloading.entry_name.2, i64 4, i32 0, i32 0 }, section "cuda_offloading_entries", align 1
+//.
+// HOST-LABEL: @_Z18__device_stub__foov(
+// HOST-NEXT:  entry:
+// HOST-NEXT:[[TMP0:%.*]] = call i32 @cudaLaunch(ptr @_Z18__device_stub__foov)
+// HOST-NEXT:br label [[SETUP_END:%.*]]
+// HOST:   setup.end:
+// HOST-NEXT:ret void
+//
+__global__ void foo() {}
+// HOST-LABEL: @_Z18__device_stub__barv(
+// HOST-NEXT:  entry:
+// HOST-NEXT:[[TMP0:%.*]] = call i32 @cudaLaunch(ptr @_Z18__device_stub__barv)
+// HOST-NEXT:br label [[SETUP_END:%.*]]
+// HOST:   setup.end:
+// HOST-NEXT:ret void
+//
+__global__ void bar() {}
+__device__ int x = 1;
Index: clang/lib/Driver/ToolChains/Clang.cpp
===
--- clang/lib/Driver/ToolChains/Clang.cpp
+++ clang/lib/Driver/ToolChains/Clang.cpp
@@ -6079,6 +6079,10 @@
options::OPT_fno_openmp_extensions);
   }
 
+  // Forward the new driver to change offloading code generation.
+  if (Args.hasArg(options::OPT_offload_new_driver))
+CmdArgs.push_back("--offload-new-driver");
+
   SanitizeArgs.addArgs(TC, Args, CmdArgs, InputType);
 
   const XRayArgs &XRay = TC.getXRayArgs();
Index: clang/lib/CodeGen/CGCUDARuntime.h
===
--- clang/lib/CodeGen/CGCUDARuntime.h
+++ clang/lib/CodeGen/CGCUDARuntime.h
@@ -52,6 +52,24 @@
   Texture,  // Builtin texture
 };
 
+/// The kind flag of the target region entry.
+enum OffloadRegionEntryKindFlag : uint32_t {
+  /// Mark the region entry as a kernel.
+  OffloadRegionKernelEntry = 0x0,
+};
+
+/// The kind flag of the global variable entry.
+enum OffloadVarEntryKindFlag : uint32_t {
+  /// Mark the entry as a global variable.
+  OffloadGlobalVarEntry = 0x0,
+  /// Mark the entry as a managed global variable.
+  OffloadGlobalManagedEntry = 0x1,
+  /// Mark the entry as a surface variable.
+  OffloadGlobalSurfaceEntry = 0x2,
+  /// Mark the entry as a texture variable.
+  OffloadGlobalTextureEntry = 0x4,
+};
+
   private:
 unsigned Kind : 2;
 unsigned Extern : 1;
Index: clang/lib/CodeGen/CGCUDANV.cpp
===
--- clang/lib/CodeGen/CGCUDANV.cpp
+++ clang/lib/CodeGen/CGCUDANV.cpp
@@ -158,6 +158,8 @@
   llvm::Function *makeModuleDtorFunction();
   /// Transform managed variables for device compilation.
   void transformManagedVars();
+  /// Create offloading entries to register globals in RDC mode.
+  void createOffloadingEntries();
 
 public:
   CGNVCUDARuntime(CodeGenModule &CGM);
@@ -211,7 +213,8 @@
 CGNVCUDARuntime::CGNVCUDARuntime(CodeGenModule &CGM)
 : CGCUDARuntime(CGM), Context(CGM.getLLVMContext()),
   TheModule(CGM.getModule()),
-  RelocatableDeviceCode(CGM.getLangOpts().GPURelocatableDeviceCode),
+  RelocatableDeviceCode(CGM.getLangOpts().GPURelocatableDeviceCode ||
+CGM.getLangOpts().OffloadingNewDriver),
   DeviceMC(InitDeviceMC(CGM)) {
   CodeGen::CodeGenTypes &Types = 

[PATCH] D124320: [clang-tidy] Add createChecks method that also checks for LangaugeOptions

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

Just to double-check, this is an NFC change, isn't it (thus there's no tests)? 
Assuming that's true, this LGTM (though please add NFC to the commit message 
title).


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124320

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


[PATCH] D124702: [MSVC] Add support for pragma function

2022-05-02 Thread Stephen Long via Phabricator via cfe-commits
steplong added a comment.

In D124702#3485475 , @hans wrote:

> From the MS docs:
>
>> Once a function pragma is seen, it takes effect at the first function 
>> definition that contains a specified intrinsic function. The effect 
>> continues to the end of the source file, or to the appearance of an 
>> intrinsic pragma specifying the same intrinsic function. You can only use 
>> the function pragma outside of a function, at the global level.
>
> Should we try to handle the interaction between pragma intrinsic and pragma 
> function, i.e. that the former "undoes" the latter? And should we error/warn 
> if the pragma occurs not in namespace scope?

Oh I wasn't sure how to check if the function pragma was outside of a function. 
Yup, we can try to handle pragma intrinsic


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124702

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


[PATCH] D124767: [Clang] Map .gcda paths according to -fcoverage-prefix-map

2022-05-02 Thread Vitaly Cheptsov via Phabricator via cfe-commits
vit9696 updated this revision to Diff 426414.

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124767

Files:
  clang/lib/CodeGen/CodeGenModule.cpp


Index: clang/lib/CodeGen/CodeGenModule.cpp
===
--- clang/lib/CodeGen/CodeGenModule.cpp
+++ clang/lib/CodeGen/CodeGenModule.cpp
@@ -6550,8 +6550,21 @@
 
   llvm::NamedMDNode *GCov = TheModule.getOrInsertNamedMetadata("llvm.gcov");
   llvm::LLVMContext &Ctx = TheModule.getContext();
-  auto *CoverageDataFile =
+  llvm::MDString *CoverageDataFile = nullptr;
+  auto &PrefixMap = getCodeGenOpts().CoveragePrefixMap;
+  llvm::SmallString<256> File;
+  if (!PrefixMap.empty()) {
+File = getCodeGenOpts().CoverageDataFile;
+llvm::sys::path::remove_dots(File, /*remove_dot_dot=*/true);
+for (const auto &Entry : PrefixMap) {
+  if (llvm::sys::path::replace_path_prefix(File, Entry.first, 
Entry.second))
+break;
+}
+CoverageDataFile = llvm::MDString::get(Ctx, File.c_str());
+  } else {
+CoverageDataFile =
   llvm::MDString::get(Ctx, getCodeGenOpts().CoverageDataFile);
+  }
   auto *CoverageNotesFile =
   llvm::MDString::get(Ctx, getCodeGenOpts().CoverageNotesFile);
   for (int i = 0, e = CUNode->getNumOperands(); i != e; ++i) {


Index: clang/lib/CodeGen/CodeGenModule.cpp
===
--- clang/lib/CodeGen/CodeGenModule.cpp
+++ clang/lib/CodeGen/CodeGenModule.cpp
@@ -6550,8 +6550,21 @@
 
   llvm::NamedMDNode *GCov = TheModule.getOrInsertNamedMetadata("llvm.gcov");
   llvm::LLVMContext &Ctx = TheModule.getContext();
-  auto *CoverageDataFile =
+  llvm::MDString *CoverageDataFile = nullptr;
+  auto &PrefixMap = getCodeGenOpts().CoveragePrefixMap;
+  llvm::SmallString<256> File;
+  if (!PrefixMap.empty()) {
+File = getCodeGenOpts().CoverageDataFile;
+llvm::sys::path::remove_dots(File, /*remove_dot_dot=*/true);
+for (const auto &Entry : PrefixMap) {
+  if (llvm::sys::path::replace_path_prefix(File, Entry.first, Entry.second))
+break;
+}
+CoverageDataFile = llvm::MDString::get(Ctx, File.c_str());
+  } else {
+CoverageDataFile =
   llvm::MDString::get(Ctx, getCodeGenOpts().CoverageDataFile);
+  }
   auto *CoverageNotesFile =
   llvm::MDString::get(Ctx, getCodeGenOpts().CoverageNotesFile);
   for (int i = 0, e = CUNode->getNumOperands(); i != e; ++i) {
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D124687: [Tooling/DependencyScanning & Preprocessor] Refactor dependency scanning to record and use pre-lexed preprocessor directive tokens, instead of minimized sources

2022-05-02 Thread Thorsten via Phabricator via cfe-commits
tschuett added a comment.

Could you split this into smaller patches?
Does this support C++20 modules or is it limited to clang header modules?
Is there overhead in the non dependency scanning mode?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124687

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


[PATCH] D124690: [clangd] add inlay hints for std::forward-ed parameter packs

2022-05-02 Thread Tobias Ribizel via Phabricator via cfe-commits
upsj added inline comments.



Comment at: clang-tools-extra/clangd/InlayHints.cpp:474
+// the parameter names from the wrapped function
+if (Args.size() > FixedParamCount && Args.size() == Params.size()) {
+  auto ForwardedParams = matchForwardedParams(

nridge wrote:
> What is the reason for the `Args.size() == Params.size()` condition?
> 
> Doesn't this break cases where there is more than one argument matching the 
> variadic parameter? For example:
> 
> ```
> void foo(int a, int b);
> template 
> void bar(Args&&... args) { foo(args...); }
> int main() {
>   bar(1, 2);
> }
> ```
> 
> Here, I expect we'd have `Args.size() == 2` and `Params.size() == 1`.
> 
> (We should probably have test coverage for such multiple-arguments cases as 
> well. We probably don't need it for all combinations, but we should have at 
> least one test case exercising it.)
The function we are looking at is an already instantiated template. The check 
`Args.size() == Params.size()` is only necessary because of va_args


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124690

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


[clang] a978991 - Re-apply 4b6c2cd642 "Deferred Concept Instantiation Implementation""

2022-05-02 Thread Erich Keane via cfe-commits

Author: Erich Keane
Date: 2022-05-02T07:49:26-07:00
New Revision: a97899108e495147985e5e9492e742d51d5cc97a

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

LOG: Re-apply 4b6c2cd642 "Deferred Concept Instantiation Implementation""

This reverts commit 0c31da48389754822dc3eecc4723160c295b9ab2.

I've solved the issue with the PointerUnion by making the
`FunctionTemplateDecl` pointer be a NamedDecl, that could be a
`FunctionDecl` or `FunctionTemplateDecl` depending.  This is enforced
with an assert.

Added: 
clang/test/SemaTemplate/deferred-concept-inst.cpp
clang/test/SemaTemplate/trailing-return-short-circuit.cpp

Modified: 
clang/docs/ReleaseNotes.rst
clang/include/clang/AST/Decl.h
clang/include/clang/AST/DeclBase.h
clang/include/clang/Sema/Sema.h
clang/include/clang/Sema/Template.h
clang/lib/AST/ASTImporter.cpp
clang/lib/AST/Decl.cpp
clang/lib/AST/DeclBase.cpp
clang/lib/ExtractAPI/ExtractAPIConsumer.cpp
clang/lib/Sema/SemaConcept.cpp
clang/lib/Sema/SemaTemplate.cpp
clang/lib/Sema/SemaTemplateDeduction.cpp
clang/lib/Sema/SemaTemplateInstantiate.cpp
clang/lib/Sema/SemaTemplateInstantiateDecl.cpp
clang/lib/Sema/TreeTransform.h
clang/lib/Serialization/ASTReaderDecl.cpp
clang/lib/Serialization/ASTWriterDecl.cpp

clang/test/CXX/temp/temp.constr/temp.constr.constr/non-function-templates.cpp
clang/test/SemaTemplate/concepts.cpp
clang/test/SemaTemplate/instantiate-requires-clause.cpp

Removed: 




diff  --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 91944e0b11ef0..839a7035a94fd 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -275,6 +275,10 @@ C++20 Feature Support
   `Issue 54578 `_.
 
 - Implemented `__builtin_source_location()` which enables library support for 
std::source_location.
+- Clang now correctly delays the instantiation of function constraints until
+  the time of checking, which should now allow the libstdc++ ranges 
implementation
+  to work for at least trivial examples.  This fixes
+  `Issue 44178 `_.
 
 - The mangling scheme for C++20 modules has incompatibly changed. The
   initial mangling was discovered not to be reversible, and the weak

diff  --git a/clang/include/clang/AST/Decl.h b/clang/include/clang/AST/Decl.h
index c2133f4e79a15..cc84e746d8d84 100644
--- a/clang/include/clang/AST/Decl.h
+++ b/clang/include/clang/AST/Decl.h
@@ -1890,7 +1890,9 @@ class FunctionDecl : public DeclaratorDecl,
 TK_FunctionTemplateSpecialization,
 // A function template specialization that hasn't yet been resolved to a
 // particular specialized function template.
-TK_DependentFunctionTemplateSpecialization
+TK_DependentFunctionTemplateSpecialization,
+// A non templated function which is in a dependent scope.
+TK_DependentNonTemplate
   };
 
   /// Stashed information about a defaulted function definition whose body has
@@ -1939,20 +1941,21 @@ class FunctionDecl : public DeclaratorDecl,
   /// The template or declaration that this declaration
   /// describes or was instantiated from, respectively.
   ///
-  /// For non-templates, this value will be NULL. For function
-  /// declarations that describe a function template, this will be a
-  /// pointer to a FunctionTemplateDecl. For member functions
-  /// of class template specializations, this will be a 
MemberSpecializationInfo
-  /// pointer containing information about the specialization.
-  /// For function template specializations, this will be a
-  /// FunctionTemplateSpecializationInfo, which contains information about
-  /// the template being specialized and the template arguments involved in
-  /// that specialization.
-  llvm::PointerUnion
-TemplateOrSpecialization;
+  TemplateOrSpecialization;
 
   /// Provides source/type location info for the declaration name embedded in
   /// the DeclaratorDecl base class.
@@ -2688,6 +2691,11 @@ class FunctionDecl : public DeclaratorDecl,
 setInstantiationOfMemberFunction(getASTContext(), FD, TSK);
   }
 
+  /// Specify that this function declaration was instantiated from FunctionDecl
+  /// FD. This is only used if this is a function declaration declared locally
+  /// inside of a function template.
+  void setInstantiatedFromDecl(FunctionDecl *FD);
+
   /// Retrieves the function template that is described by this
   /// function declaration.
   ///
@@ -2702,6 +2710,8 @@ class FunctionDecl : public DeclaratorDecl,
   /// FunctionTemplateDecl from a FunctionDecl.
   FunctionTemplateDecl *getDescribedFunctionTemplate() const;
 
+  FunctionDecl *getInstantiatedFromDecl() const;
+
   void setDescribedFunctionTem

[PATCH] D124221: Reimplement `__builtin_dump_struct` in Sema.

2022-05-02 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman added a comment.

Thanks for working on this, I like the direction it's going!




Comment at: clang/include/clang/Basic/DiagnosticSemaKinds.td:8470-8473
+def err_expected_struct_pointer_argument : Error<
+  "expected pointer to struct as %ordinal0 argument to %1, found %2">;
+def err_expected_callable_argument : Error<
+  "expected a callable expression as %ordinal0 argument to %1, found %2">;

Should we combine these into:
```
def err_builtin_dump_struct_expects : Error<
  "expected %select{pointer to struct|a callable expression}0 as %ordinal1 
argument to %2, found %3">;
```
to reduce the number of diagnostics we have to tablegen?



Comment at: clang/lib/AST/Expr.cpp:2742
+// Otherwise, warn if the result expression would warn.
+const Expr *Result = POE->getResultExpr();
+return Result && Result->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);

I don't think the changes here are incorrect, but I'm wondering if they should 
be split into a different patch as they seem to be largely unrelated to the 
builtin?



Comment at: clang/lib/Sema/SemaChecking.cpp:390
+Expr *Lit = S.Context.getPredefinedStringLiteralFromCache(Str);
+// Wrap the literal in parentheses to attach a source location.
+return new (S.Context) ParenExpr(Loc, Loc, Lit);

Haha, neat trick. Perhaps someday we should allow 
`getPredefinedStringLiteralFromCache()` to specify a `SourceLocation`?



Comment at: clang/lib/Sema/SemaChecking.cpp:397
+SmallVector Args;
+Args.reserve((TheCall->getNumArgs() - 2) + /*Format*/ 1 + Exprs.size());
+Args.assign(TheCall->arg_begin() + 2, TheCall->arg_end());

Can you add an assertion that the call has at least two args?



Comment at: clang/lib/Sema/SemaChecking.cpp:433
+
+  llvm::StringRef getFormatSpecifier(QualType T) {
+if (auto *BT = T->getAs()) {

yihanaa wrote:
> I think this is better maintained in "clang/AST/FormatString.h". For example 
> analyze_printf::PrintfSpecifier can get format specifier, what do you all 
> think about?
+1 to this suggestion -- my hope is that we could generalize it more then as I 
notice there are missing specifiers for things like intmax_t, size_t, 
ptrdiff_t, _Decimal types, etc. Plus, that will hopefully make it easier for 
__builtin_dump_struct to benefit when new format specifiers are added, such as 
ones for printing a _BitInt.



Comment at: clang/lib/Sema/SemaChecking.cpp:500
+// triggering re-evaluation.
+auto *RecordArg = makeOpaqueValueExpr(E);
+bool RecordArgIsPtr = RecordArg->getType()->isPointerType();

Can you spell out the type since it's not in the initialization?



Comment at: clang/lib/Sema/SemaChecking.cpp:507
+// Dump each base class, regardless of whether they're aggregates.
+if (const CXXRecordDecl *CXXRD = dyn_cast(RD)) {
+  for (const auto &Base : CXXRD->bases()) {





Comment at: clang/lib/Sema/SemaChecking.cpp:572-574
+  // We don't know how to print this field. Print out its address
+  // with a format specifier that a smart tool will be able to
+  // recognize and treat specially.

Should we handle array types specifically, or should we continue to punt on 
those for now?



Comment at: clang/lib/Sema/SemaChecking.cpp:625-626
+  QualType FnArgType = TheCall->getArg(1)->getType();
+  if (!FnArgType->isFunctionType() && !FnArgType->isFunctionPointerType() &&
+  !(S.getLangOpts().CPlusPlus && FnArgType->isRecordType())) {
+auto *BT = FnArgType->getAs();

ObjC block?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124221

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


[PATCH] D124221: Reimplement `__builtin_dump_struct` in Sema.

2022-05-02 Thread Erich Keane via Phabricator via cfe-commits
erichkeane added a comment.

This is a pretty nice seeming interface that I think does a fairly good job at 
maintaining backwards compat while improving the functionality. A few 
questions/comments.




Comment at: clang/docs/LanguageExtensions.rst:2442
+
+This builtin does not return a value.
+

I don't know if anyone would be using this value, but I wonder if there is 
value to making this a 'sum' of the results of `f`?  Less useful for the 
purposes of printf, but perhaps to a sprintf-type-function?  

Not sure if we have the use cases to support this however.



Comment at: clang/lib/Sema/SemaChecking.cpp:558
+  auto *InnerRD = FD->getType()->getAsRecordDecl();
+  auto *InnerCXXRD = InnerRD ? dyn_cast(InnerRD) : nullptr;
+  if (InnerRD && (!InnerCXXRD || InnerCXXRD->isAggregate())) {





Comment at: clang/lib/Sema/SemaChecking.cpp:595
+ PseudoObjectExpr::NoResult);
+TheCall->setType(Wrapper->getType());
+TheCall->setValueKind(Wrapper->getValueKind());

What is happening here?  I would expect the opposite to need to happen here 
(wrapper be set to match the call, not the other way around?).  



Comment at: clang/lib/Sema/SemaChecking.cpp:603
+static ExprResult SemaBuiltinDumpStruct(Sema &S, CallExpr *TheCall) {
+  if (TheCall->getNumArgs() < 2 && checkArgCount(S, TheCall, 2))
+return ExprError();

This is unfortunate.  Do we really not have a `checkAtLeastArgCount` type 
function here?  I know we have something similar for attributes.



Comment at: clang/lib/Sema/SemaChecking.cpp:614
+  if (!PtrArgType->isPointerType() ||
+  !PtrArgType->getPointeeType()->isRecordType()) {
+S.Diag(PtrArgResult.get()->getBeginLoc(),

Is this sufficient?  Couldn't this be a pointer to a union?  Do you mean the 
suggestion?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124221

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


[PATCH] D122663: Mark identifier prefixes as substitutable

2022-05-02 Thread Harald van Dijk via Phabricator via cfe-commits
hvdijk added a comment.

In D122663#3471741 , @erichkeane 
wrote:

> Ping me EOW if @rsmith doesn't respond in the meantime.

ping


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D122663

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


[PATCH] D124621: [Analyzer] Fix assumptions about const field with member-initializer

2022-05-02 Thread Marco Antognini via Phabricator via cfe-commits
mantognini added a comment.

In D124621#3482847 , @steakhal wrote:

> For the upcoming patches, it would be nice to test the patches on a small set 
> of open-source projects for exactly this reason.
> I think there is a `clang/utils/analyzer/SATest.py` script helping you on 
> this part.
> It seems we have quite a few projects on the testset 
> `clang/utils/analyzer/projects/projects.json`.
> We are not using it, because we have a different internal testing 
> infrastructure, but it's definitely better than nothing.

Thanks for the tip. I had to fix a thing or two to get SATest.py working with 
my setup (I'll try to upstream those fixes at some point). However, these 
projects do not highlight the false-positive being fixed here. I.e., I get no 
difference in reports with and without this patch. But I'll keep this in mind 
when working on other improvements.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124621

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


[PATCH] D123810: [Cuda] Add initial support for wrapping CUDA images in the new driver.

2022-05-02 Thread Joseph Huber via Phabricator via cfe-commits
jhuber6 updated this revision to Diff 426420.
jhuber6 added a comment.

Updating to use the `OffloadKind` enum rather than the string. I will also 
probably simplify some of the logic for handling multiple files here in a later 
patch.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D123810

Files:
  clang/tools/clang-linker-wrapper/ClangLinkerWrapper.cpp
  clang/tools/clang-linker-wrapper/OffloadWrapper.cpp
  clang/tools/clang-linker-wrapper/OffloadWrapper.h

Index: clang/tools/clang-linker-wrapper/OffloadWrapper.h
===
--- clang/tools/clang-linker-wrapper/OffloadWrapper.h
+++ clang/tools/clang-linker-wrapper/OffloadWrapper.h
@@ -1,4 +1,4 @@
-//===- OffloadWrapper.h ---*- C++ -*-===//
+//===- OffloadWrapper.h --r-*- C++ -*-===//
 //
 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
 // See https://llvm.org/LICENSE.txt for license information.
@@ -14,7 +14,11 @@
 
 /// Wrap the input device images into the module \p M as global symbols and
 /// registers the images with the OpenMP Offloading runtime libomptarget.
-llvm::Error wrapBinaries(llvm::Module &M,
- llvm::ArrayRef> Images);
+llvm::Error wrapOpenMPBinaries(llvm::Module &M,
+   llvm::ArrayRef> Images);
+
+/// Wrap the input fatbinary image into the module \p M as global symbols and
+/// registers the images with the CUDA runtime.
+llvm::Error wrapCudaBinary(llvm::Module &M, llvm::ArrayRef Images);
 
 #endif
Index: clang/tools/clang-linker-wrapper/OffloadWrapper.cpp
===
--- clang/tools/clang-linker-wrapper/OffloadWrapper.cpp
+++ clang/tools/clang-linker-wrapper/OffloadWrapper.cpp
@@ -257,7 +257,7 @@
 
 } // namespace
 
-Error wrapBinaries(Module &M, ArrayRef> Images) {
+Error wrapOpenMPBinaries(Module &M, ArrayRef> Images) {
   GlobalVariable *Desc = createBinDesc(M, Images);
   if (!Desc)
 return createStringError(inconvertibleErrorCode(),
@@ -266,3 +266,8 @@
   createUnregisterFunction(M, Desc);
   return Error::success();
 }
+
+llvm::Error wrapCudaBinary(llvm::Module &M, llvm::ArrayRef Images) {
+  return createStringError(inconvertibleErrorCode(),
+   "Cuda wrapping is not yet supported.");
+}
Index: clang/tools/clang-linker-wrapper/ClangLinkerWrapper.cpp
===
--- clang/tools/clang-linker-wrapper/ClangLinkerWrapper.cpp
+++ clang/tools/clang-linker-wrapper/ClangLinkerWrapper.cpp
@@ -166,11 +166,11 @@
 
 /// Information for a device offloading file extracted from the host.
 struct DeviceFile {
-  DeviceFile(StringRef Kind, StringRef TheTriple, StringRef Arch,
+  DeviceFile(OffloadKind Kind, StringRef TheTriple, StringRef Arch,
  StringRef Filename)
   : Kind(Kind), TheTriple(TheTriple), Arch(Arch), Filename(Filename) {}
 
-  std::string Kind;
+  OffloadKind Kind;
   std::string TheTriple;
   std::string Arch;
   std::string Filename;
@@ -181,15 +181,30 @@
 /// assume device files with matching architectures and triples but different
 /// offloading kinds should be handlded together, this may not be true in the
 /// future.
+
+// Provide DenseMapInfo for OffloadKind.
+template <> struct DenseMapInfo {
+  static inline OffloadKind getEmptyKey() {
+return static_cast(0x);
+  }
+  static inline OffloadKind getTombstoneKey() {
+return static_cast(0x - 1);
+  }
+  static unsigned getHashValue(const OffloadKind &Val) { return Val * 37U; }
+
+  static bool isEqual(const OffloadKind &LHS, const OffloadKind &RHS) {
+return LHS == RHS;
+  }
+};
 template <> struct DenseMapInfo {
   static DeviceFile getEmptyKey() {
-return {DenseMapInfo::getEmptyKey(),
+return {static_cast(DenseMapInfo::getEmptyKey()),
 DenseMapInfo::getEmptyKey(),
 DenseMapInfo::getEmptyKey(),
 DenseMapInfo::getEmptyKey()};
   }
   static DeviceFile getTombstoneKey() {
-return {DenseMapInfo::getTombstoneKey(),
+return {static_cast(DenseMapInfo::getTombstoneKey()),
 DenseMapInfo::getTombstoneKey(),
 DenseMapInfo::getTombstoneKey(),
 DenseMapInfo::getTombstoneKey()};
@@ -230,7 +245,7 @@
   auto DeviceAndPath = StringRef(LibraryStr).split('=');
   auto StringAndArch = DeviceAndPath.first.rsplit('-');
   auto KindAndTriple = StringAndArch.first.split('-');
-  return DeviceFile(KindAndTriple.first, KindAndTriple.second,
+  return DeviceFile(getOffloadKind(KindAndTriple.first), KindAndTriple.second,
 StringAndArch.second, DeviceAndPath.second);
 }
 
@@ -360,8 +375,8 @@
 if (Error E = Output->commit())
   return E;
 
-DeviceFiles.emplace_back(Kind, Binary.getTriple(), Binary.getArch(),
- 

[clang] 5a47acc - [Analyzer] Fix clang::ento::taint::dumpTaint definition

2022-05-02 Thread Marco Antognini via cfe-commits

Author: Marco Antognini
Date: 2022-05-02T17:44:06+02:00
New Revision: 5a47accda88c24d07cc48241be0f0078e8c9dfd0

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

LOG: [Analyzer] Fix clang::ento::taint::dumpTaint definition

Ensure the definition is in the "taint" namespace, like its declaration.

Reviewed By: steakhal

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

Added: 


Modified: 
clang/lib/StaticAnalyzer/Checkers/Taint.cpp

Removed: 




diff  --git a/clang/lib/StaticAnalyzer/Checkers/Taint.cpp 
b/clang/lib/StaticAnalyzer/Checkers/Taint.cpp
index 02a8d6abad2a1..44162094e49a8 100644
--- a/clang/lib/StaticAnalyzer/Checkers/Taint.cpp
+++ b/clang/lib/StaticAnalyzer/Checkers/Taint.cpp
@@ -37,7 +37,9 @@ void taint::printTaint(ProgramStateRef State, raw_ostream 
&Out, const char *NL,
 Out << I.first << " : " << I.second << NL;
 }
 
-void dumpTaint(ProgramStateRef State) { printTaint(State, llvm::errs()); }
+void taint::dumpTaint(ProgramStateRef State) {
+  printTaint(State, llvm::errs());
+}
 
 ProgramStateRef taint::addTaint(ProgramStateRef State, const Stmt *S,
 const LocationContext *LCtx,



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


[PATCH] D124462: [Analyzer] Fix clang::ento::taint::dumpTaint definition

2022-05-02 Thread Marco Antognini via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG5a47accda88c: [Analyzer] Fix clang::ento::taint::dumpTaint 
definition (authored by mantognini).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124462

Files:
  clang/lib/StaticAnalyzer/Checkers/Taint.cpp


Index: clang/lib/StaticAnalyzer/Checkers/Taint.cpp
===
--- clang/lib/StaticAnalyzer/Checkers/Taint.cpp
+++ clang/lib/StaticAnalyzer/Checkers/Taint.cpp
@@ -37,7 +37,9 @@
 Out << I.first << " : " << I.second << NL;
 }
 
-void dumpTaint(ProgramStateRef State) { printTaint(State, llvm::errs()); }
+void taint::dumpTaint(ProgramStateRef State) {
+  printTaint(State, llvm::errs());
+}
 
 ProgramStateRef taint::addTaint(ProgramStateRef State, const Stmt *S,
 const LocationContext *LCtx,


Index: clang/lib/StaticAnalyzer/Checkers/Taint.cpp
===
--- clang/lib/StaticAnalyzer/Checkers/Taint.cpp
+++ clang/lib/StaticAnalyzer/Checkers/Taint.cpp
@@ -37,7 +37,9 @@
 Out << I.first << " : " << I.second << NL;
 }
 
-void dumpTaint(ProgramStateRef State) { printTaint(State, llvm::errs()); }
+void taint::dumpTaint(ProgramStateRef State) {
+  printTaint(State, llvm::errs());
+}
 
 ProgramStateRef taint::addTaint(ProgramStateRef State, const Stmt *S,
 const LocationContext *LCtx,
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D123763: [randstruct] Enforce using a designated init for a randomized struct

2022-05-02 Thread Sam Clegg via Phabricator via cfe-commits
sbc100 added a comment.

This new test has been failing on the emscripten builders.. seemingly ever 
since it landed:

https://ci.chromium.org/ui/p/emscripten-releases/builders/ci/linux-test-suites/b8815286583388131569/overview

It also fails for me locally:

  ../llvm-build/bin/llvm-lit clang/test/Sema/init-randomized-struct.c -v -a
  ninja: Entering directory `/usr/local/google/home/sbc/dev/wasm/llvm-build'
  ninja: no work to do.
  llvm-lit: 
/usr/local/google/home/sbc/dev/wasm/llvm-project/llvm/utils/lit/lit/llvm/config.py:438:
 note: using clang: /usr/local/google/home/sbc/dev/wasm/llvm-build/bin/clang
  -- Testing: 1 tests, 1 workers --
  FAIL: Clang :: Sema/init-randomized-struct.c (1 of 1)
   TEST 'Clang :: Sema/init-randomized-struct.c' FAILED 

  Script:
  --
  : 'RUN: at line 1';   
/usr/local/google/home/sbc/dev/wasm/llvm-build/bin/clang -cc1 -internal-isystem 
/usr/local/google/home/sbc/dev/wasm/llvm-build/lib/clang/15.0.0/include 
-nostdsysteminc -triple=x86_64-unknown-linux 
-frandomize-layout-seed=1234567890abcdef   -verify -fsyntax-only -Werror 
/usr/local/google/home/sbc/dev/wasm/llvm-project/clang/test/Sema/init-randomized-struct.c
  --
  Exit Code: 1
  
  Command Output (stderr):
  --
  error: 'error' diagnostics expected but not seen: 
File 
/usr/local/google/home/sbc/dev/wasm/llvm-project/clang/test/Sema/init-randomized-struct.c
 Line 34: a randomized struct can only be initialized with a designated 
initializer
File 
/usr/local/google/home/sbc/dev/wasm/llvm-project/clang/test/Sema/init-randomized-struct.c
 Line 46: a randomized struct can only be initialized with a designated 
initializer
  error: 'error' diagnostics seen but not expected: 
File 
/usr/local/google/home/sbc/dev/wasm/llvm-project/clang/test/Sema/init-randomized-struct.c
 Line 34: excess elements in struct initializer
File 
/usr/local/google/home/sbc/dev/wasm/llvm-project/clang/test/Sema/init-randomized-struct.c
 Line 46: excess elements in struct initializer
  4 errors generated.
  
  --
  
  
  
  Failed Tests (1):
Clang :: Sema/init-randomized-struct.c
  
  
  Testing Time: 0.08s
Failed: 1

Any ideas?  I wonder why this is not failing for others?

Could it be something about how I'm configuring llvm: `cmake -G Ninja 
-DCMAKE_C_COMPILER=/usr/local/google/home/sbc/dev/chromium/src/third_party/llvm-build/Release+Asserts/bin/clang
 
-DCMAKE_CXX_COMPILER=/usr/local/google/home/sbc/dev/chromium/src/third_party/llvm-build/Release+Asserts/bin/clang++
 -DCMAKE_BUILD_TYPE=Release 
-DCMAKE_INSTALL_PREFIX=/usr/local/google/home/sbc/dev/wasm/waterfall/src/work/wasm-install
 -DCMAKE_SHARED_LINKER_FLAGS=-fuse-ld=gold -DBUILD_SHARED_LIBS=ON 
-DCMAKE_BUILD_WITH_INSTALL_RPATH=ON -DLLVM_BUILD_LLVM_DYLIB=OFF 
-DLLVM_LINK_LLVM_DYLIB=OFF -DCMAKE_EXPORT_COMPILE_COMMANDS=ON 
-DLLVM_ENABLE_ASSERTIONS=ON -DLLVM_ENABLE_SPHINX=ON 
-DLLVM_ENABLE_PROJECTS=lld;clang;libcxx;libcxxabi 
-DLLVM_INSTALL_BINUTILS_SYMLINKS=ON -DLLVM_INSTALL_TOOLCHAIN_ONLY=ON 
-DLLVM_ENABLE_TERMINFO=OFF 
-DCMAKE_SYSROOT=/usr/local/google/home/sbc/dev/wasm/waterfall/src/work/sysroot_debian_stretch_amd64/
 
-DCMAKE_C_COMPILER_LAUNCHER=/usr/local/google/home/sbc/bin/depot_tools/.cipd_bin/gomacc
 
-DCMAKE_CXX_COMPILER_LAUNCHER=/usr/local/google/home/sbc/bin/depot_tools/.cipd_bin/gomacc
 -DLLVM_TARGETS_TO_BUILD=X86;WebAssembly ../llvm-project/llvm`  ?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D123763

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


[clang] f346398 - [Analyzer] Minor cleanups in StreamChecker

2022-05-02 Thread Marco Antognini via cfe-commits

Author: Marco Antognini
Date: 2022-05-02T17:50:10+02:00
New Revision: f34639828f5a99e6d724c092cc164be0c30a9f71

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

LOG: [Analyzer] Minor cleanups in StreamChecker

Remove unnecessary conversion to Optional<> and incorrect assumption
that BindExpr can return a null state.

Reviewed By: steakhal

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

Added: 


Modified: 
clang/lib/StaticAnalyzer/Checkers/StreamChecker.cpp

Removed: 




diff  --git a/clang/lib/StaticAnalyzer/Checkers/StreamChecker.cpp 
b/clang/lib/StaticAnalyzer/Checkers/StreamChecker.cpp
index 099e70aaf7eca..b16e1f012251d 100644
--- a/clang/lib/StaticAnalyzer/Checkers/StreamChecker.cpp
+++ b/clang/lib/StaticAnalyzer/Checkers/StreamChecker.cpp
@@ -672,24 +672,19 @@ void StreamChecker::evalFreadFwrite(const FnDescription 
*Desc,
   if (!IsFread || (OldSS->ErrorState != ErrorFEof)) {
 ProgramStateRef StateNotFailed =
 State->BindExpr(CE, C.getLocationContext(), *NMembVal);
-if (StateNotFailed) {
-  StateNotFailed = StateNotFailed->set(
-  StreamSym, StreamState::getOpened(Desc));
-  C.addTransition(StateNotFailed);
-}
+StateNotFailed =
+StateNotFailed->set(StreamSym, 
StreamState::getOpened(Desc));
+C.addTransition(StateNotFailed);
   }
 
   // Add transition for the failed state.
-  Optional RetVal = makeRetVal(C, CE).castAs();
-  assert(RetVal && "Value should be NonLoc.");
+  NonLoc RetVal = makeRetVal(C, CE).castAs();
   ProgramStateRef StateFailed =
-  State->BindExpr(CE, C.getLocationContext(), *RetVal);
-  if (!StateFailed)
-return;
-  auto Cond = C.getSValBuilder()
-  .evalBinOpNN(State, BO_LT, *RetVal, *NMembVal,
-   C.getASTContext().IntTy)
-  .getAs();
+  State->BindExpr(CE, C.getLocationContext(), RetVal);
+  auto Cond =
+  C.getSValBuilder()
+  .evalBinOpNN(State, BO_LT, RetVal, *NMembVal, 
C.getASTContext().IntTy)
+  .getAs();
   if (!Cond)
 return;
   StateFailed = StateFailed->assume(*Cond, true);



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


[PATCH] D124681: [Analyzer] Minor cleanups in StreamChecker

2022-05-02 Thread Marco Antognini via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rGf34639828f5a: [Analyzer] Minor cleanups in StreamChecker 
(authored by mantognini).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124681

Files:
  clang/lib/StaticAnalyzer/Checkers/StreamChecker.cpp


Index: clang/lib/StaticAnalyzer/Checkers/StreamChecker.cpp
===
--- clang/lib/StaticAnalyzer/Checkers/StreamChecker.cpp
+++ clang/lib/StaticAnalyzer/Checkers/StreamChecker.cpp
@@ -672,24 +672,19 @@
   if (!IsFread || (OldSS->ErrorState != ErrorFEof)) {
 ProgramStateRef StateNotFailed =
 State->BindExpr(CE, C.getLocationContext(), *NMembVal);
-if (StateNotFailed) {
-  StateNotFailed = StateNotFailed->set(
-  StreamSym, StreamState::getOpened(Desc));
-  C.addTransition(StateNotFailed);
-}
+StateNotFailed =
+StateNotFailed->set(StreamSym, 
StreamState::getOpened(Desc));
+C.addTransition(StateNotFailed);
   }
 
   // Add transition for the failed state.
-  Optional RetVal = makeRetVal(C, CE).castAs();
-  assert(RetVal && "Value should be NonLoc.");
+  NonLoc RetVal = makeRetVal(C, CE).castAs();
   ProgramStateRef StateFailed =
-  State->BindExpr(CE, C.getLocationContext(), *RetVal);
-  if (!StateFailed)
-return;
-  auto Cond = C.getSValBuilder()
-  .evalBinOpNN(State, BO_LT, *RetVal, *NMembVal,
-   C.getASTContext().IntTy)
-  .getAs();
+  State->BindExpr(CE, C.getLocationContext(), RetVal);
+  auto Cond =
+  C.getSValBuilder()
+  .evalBinOpNN(State, BO_LT, RetVal, *NMembVal, 
C.getASTContext().IntTy)
+  .getAs();
   if (!Cond)
 return;
   StateFailed = StateFailed->assume(*Cond, true);


Index: clang/lib/StaticAnalyzer/Checkers/StreamChecker.cpp
===
--- clang/lib/StaticAnalyzer/Checkers/StreamChecker.cpp
+++ clang/lib/StaticAnalyzer/Checkers/StreamChecker.cpp
@@ -672,24 +672,19 @@
   if (!IsFread || (OldSS->ErrorState != ErrorFEof)) {
 ProgramStateRef StateNotFailed =
 State->BindExpr(CE, C.getLocationContext(), *NMembVal);
-if (StateNotFailed) {
-  StateNotFailed = StateNotFailed->set(
-  StreamSym, StreamState::getOpened(Desc));
-  C.addTransition(StateNotFailed);
-}
+StateNotFailed =
+StateNotFailed->set(StreamSym, StreamState::getOpened(Desc));
+C.addTransition(StateNotFailed);
   }
 
   // Add transition for the failed state.
-  Optional RetVal = makeRetVal(C, CE).castAs();
-  assert(RetVal && "Value should be NonLoc.");
+  NonLoc RetVal = makeRetVal(C, CE).castAs();
   ProgramStateRef StateFailed =
-  State->BindExpr(CE, C.getLocationContext(), *RetVal);
-  if (!StateFailed)
-return;
-  auto Cond = C.getSValBuilder()
-  .evalBinOpNN(State, BO_LT, *RetVal, *NMembVal,
-   C.getASTContext().IntTy)
-  .getAs();
+  State->BindExpr(CE, C.getLocationContext(), RetVal);
+  auto Cond =
+  C.getSValBuilder()
+  .evalBinOpNN(State, BO_LT, RetVal, *NMembVal, C.getASTContext().IntTy)
+  .getAs();
   if (!Cond)
 return;
   StateFailed = StateFailed->assume(*Cond, true);
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


  1   2   3   >