[PATCH] D123874: [Clang][IA] support -generate-unused-section-symbols={yes|no}

2022-04-22 Thread Fangrui Song via Phabricator via cfe-commits
MaskRay requested changes to this revision.
MaskRay added a comment.
This revision now requires changes to proceed.

In D123874#3454723 , @MaskRay wrote:

>> Add support to clang (-Wa,-generate-unused-section-symbols={yes|no}) and 
>> llvm-mc.
>
>
>
>> This feature might be used by the Linux kernel. 
>> https://lore.kernel.org/linux-toolchains/ylluqpk4cwzeh...@hirez.programming.kicks-ass.net/
>
>
>
>> This has been supported by GNU binutils since 2.36. 
>> https://sourceware.org/git/?p=binutils-gdb.git;a=commit;h=d1bcae833b32f1408485ce69f844dcd7ded093a8
>
> AFAICT GNU as never gets an option named 
> `-generate-unused-section-symbols=yes`.
> It just has a quirk  
> that interprets nearly all `-g*` options as `-g`, which indicates generation 
> of some compile units for ELF symbols with the help of `.size` directives.
> It's very different from generating unused section symbols.

Latest GNU as added an error for an unknown `-g` option.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D123874

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


[PATCH] D124215: [clang-format][NFC] Use isComment() in setCommentLineLevels()

2022-04-22 Thread Marek Kurdej via Phabricator via cfe-commits
curdeius accepted this revision.
curdeius added a comment.
This revision is now accepted and ready to land.

Thanks for the clean up!


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124215

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


[PATCH] D100394: [Clang][NVPTX] Add NVPTX intrinsics and builtins for CUDA PTX cp.async instructions

2022-04-22 Thread Steffen Larsen via Phabricator via cfe-commits
steffenlarsen added a comment.

In D100394#3466316 , @nirvedhmeshram 
wrote:

> Hello, I was interested in using `llvm.nvvm.cp.async.cg.shared.global.8` and 
> `llvm.nvvm.cp.async.cg.shared.global.4` and was wondering if there is some 
> fundamental reason they were not added here. I only see the ca variants for 
> these.

Hi @nirvedhmeshram! According to the PTX ISA 

 there is only a 16 variant of `cp.async.cg.shared.global`. That said, they 
have an example further down using 8 with it, so it seems there's either a 
problem in the Syntax subsection or the examples. Either way, that is the 
explanation as to why it was not added with this.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D100394

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


[PATCH] D123668: [Testing] TestAST, a helper for writing straight-line AST tests

2022-04-22 Thread Sam McCall via Phabricator via cfe-commits
sammccall marked an inline comment as done.
sammccall added a subscriber: hliao.
sammccall added a comment.

In D123668#3466376 , @maryammo wrote:

> It seems it breaks the  following builds:
> https://lab.llvm.org/buildbot/#/builders/121/builds/18618
> https://lab.llvm.org/buildbot/#/builders/57/builds/17125

It looks like @hliao fixed these aready, thanks!




Comment at: clang/lib/Testing/CMakeLists.txt:18
+  clangBasic
+  clangFrontend
+  )

thakis wrote:
> Making clang/lib/Testing depend on clangFrontend (and hence on basically 
> everything) seems pretty heavy. Maybe this should be in a new library?
I don't think there's any real dependency regression here. AFAICS everything 
using clangTesting was also using Frontend already, and this isn't a 
coincidence.

Before this patch, clang/lib/testing contained only lists of command-line 
flags. In practice these are useful for parsing code in a variety of 
configurations, which requires frontend and everything.

(In general I *would* prefer to have many fine-grained libraries of a header or 
two each, but our CMake setup makes it very costly to do so)


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D123668

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


[clang] 5c6a146 - [C++20][Modules][Driver][HU 1/N] Initial handling for -xc++-{system,user}-header.

2022-04-22 Thread Iain Sandoe via cfe-commits

Author: Iain Sandoe
Date: 2022-04-22T09:24:29+01:00
New Revision: 5c6a14649843ccd2c50ed9e2fcacaa8ebd820ae8

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

LOG: [C++20][Modules][Driver][HU 1/N] Initial handling for 
-xc++-{system,user}-header.

This adds file types and handling for three input types, representing a C++20
header unit source:

 1. When provided with a complete pathname for the header.
 2. For a header to be looked up (by the frontend) in the user search paths
 3. For a header to be looked up in the system search paths.

We also add a pre-processed file type (although that is a single type, 
regardless
of the original input type).

These types may be specified with -xc++-{user,system,header-unit}-header .

These types allow us to disambiguate header unit jobs from PCH ones, and thus
we handle these differently from other header jobs in two ways:

 1. The job construction is altered to build a C++20 header unit (rather than a
PCH file, as would be the case for other headers).
 2. When the type is "user" or "system" we defer checking for the file until the
front end is run, since we need to look up the header in the relevant paths
which are not known at this point.

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

Added: 
clang/test/Driver/Inputs/header-unit-01.hh
clang/test/Driver/cxx20-header-units-01.cpp

Modified: 
clang/include/clang/Driver/Types.def
clang/lib/Driver/Driver.cpp
clang/lib/Driver/ToolChains/Clang.cpp
clang/lib/Driver/Types.cpp
clang/lib/Frontend/FrontendOptions.cpp

Removed: 




diff  --git a/clang/include/clang/Driver/Types.def 
b/clang/include/clang/Driver/Types.def
index 94041b183add2..0cf265e05fedc 100644
--- a/clang/include/clang/Driver/Types.def
+++ b/clang/include/clang/Driver/Types.def
@@ -64,7 +64,11 @@ TYPE("objective-c-header-cpp-output", PP_ObjCHeader, 
INVALID,   "mi", phases
 TYPE("objective-c-header",   ObjCHeader,   PP_ObjCHeader,   "h",  
phases::Preprocess, phases::Precompile)
 TYPE("c++-header-cpp-output",PP_CXXHeader, INVALID, "ii", 
phases::Precompile)
 TYPE("c++-header",   CXXHeader,PP_CXXHeader,"hh", 
phases::Preprocess, phases::Precompile)
-TYPE("objective-c++-header-cpp-output", PP_ObjCXXHeader, INVALID, "mii",  
phases::Precompile)
+TYPE("c++-header-unit-cpp-output", PP_CXXHeaderUnit,INVALID,"iih",
phases::Precompile)
+TYPE("c++-header-unit-header",   CXXHUHeader,  PP_CXXHeaderUnit,"hh", 
phases::Preprocess, phases::Precompile)
+TYPE("c++-system-header",CXXSHeader,   PP_CXXHeaderUnit,"hh", 
phases::Preprocess, phases::Precompile)
+TYPE("c++-user-header",  CXXUHeader,   PP_CXXHeaderUnit,"hh", 
phases::Preprocess, phases::Precompile)
+TYPE("objective-c++-header-cpp-output", PP_ObjCXXHeader, INVALID,"mii",   
phases::Precompile)
 TYPE("objective-c++-header", ObjCXXHeader, PP_ObjCXXHeader, "h",  
phases::Preprocess, phases::Precompile)
 TYPE("c++-module",   CXXModule,PP_CXXModule,"cppm",   
phases::Preprocess, phases::Precompile, phases::Compile, phases::Backend, 
phases::Assemble, phases::Link)
 TYPE("c++-module-cpp-output",PP_CXXModule, INVALID, "iim",
phases::Precompile, phases::Compile, phases::Backend, phases::Assemble, 
phases::Link)
@@ -89,6 +93,7 @@ TYPE("ast",  AST,  INVALID,   
  "ast",phases
 TYPE("ifs",  IFS,  INVALID, "ifs",
phases::IfsMerge)
 TYPE("ifs-cpp",  IFS_CPP,  INVALID, "ifs",
phases::Compile, phases::IfsMerge)
 TYPE("pcm",  ModuleFile,   INVALID, "pcm",
phases::Compile, phases::Backend, phases::Assemble, phases::Link)
+TYPE("header-unit",  HeaderUnit,   INVALID, "pcm",
phases::Compile, phases::Backend, phases::Assemble, phases::Link)
 TYPE("plist",Plist,INVALID, "plist",  
phases::Compile, phases::Backend, phases::Assemble, phases::Link)
 TYPE("rewritten-objc",   RewrittenObjC,INVALID, "cpp",
phases::Compile, phases::Backend, phases::Assemble, phases::Link)
 TYPE("rewritten-legacy-objc",RewrittenLegacyObjC,INVALID,   "cpp",
phases::Compile, phases::Backend, phases::Assemble, phases::Link)

diff  --git a/clang/lib/Driver/Driver.cpp b/clang/lib/Driver/Driver.cpp
index 1c5fb22026e26..6fa95a8834a2c 100644
--- a/clang/lib/Driver/Driver.cpp
+++ b/clang/lib/Driver/Driver.cpp
@@ -2219,6 +2219,11 @@ bool Driver::DiagnoseInputExistence(const DerivedArgList 
&Args, StringRef Value,
   if (Value == "-")
 return true;
 
+  // If it's a header to be found in the system or user search path, then defer
+  // complai

[PATCH] D121588: [C++20][Modules][Driver][HU 1/N] Initial handling for -xc++-{system,user}-header.

2022-04-22 Thread Iain Sandoe 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 rG5c6a14649843: [C++20][Modules][Driver][HU 1/N] Initial 
handling for -xc++-{system,user}… (authored by iains).
Herald added a subscriber: MaskRay.

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D121588

Files:
  clang/include/clang/Driver/Types.def
  clang/lib/Driver/Driver.cpp
  clang/lib/Driver/ToolChains/Clang.cpp
  clang/lib/Driver/Types.cpp
  clang/lib/Frontend/FrontendOptions.cpp
  clang/test/Driver/Inputs/header-unit-01.hh
  clang/test/Driver/cxx20-header-units-01.cpp

Index: clang/test/Driver/cxx20-header-units-01.cpp
===
--- /dev/null
+++ clang/test/Driver/cxx20-header-units-01.cpp
@@ -0,0 +1,19 @@
+// RUN: %clang -### -std=c++20 -xc++-user-header foo.h 2>&1 | \
+// RUN:   FileCheck -check-prefix=CHECK-USER %s
+
+// RUN: %clang -### -std=c++20 -xc++-system-header vector 2>&1 | \
+// RUN:   FileCheck -check-prefix=CHECK-SYSTEM %s
+
+// RUN: %clang -### -std=c++20 \
+// RUN:   -xc++-header-unit-header %/S/Inputs/header-unit-01.hh 2>&1 | \
+// RUN:   FileCheck -check-prefix=CHECK-ABS %s -DTDIR=%/S/Inputs
+
+// CHECK-USER: "-emit-header-unit"
+// CHECK-USER-SAME: "-o" "foo.pcm"
+// CHECK-USER-SAME: "-x" "c++-user-header" "foo.h"
+// CHECK-SYSTEM: "-emit-header-unit"
+// CHECK-SYSTEM-SAME: "-o" "vector.pcm"
+// CHECK-SYSTEM-SAME: "-x" "c++-system-header" "vector"
+// CHECK-ABS: "-emit-header-unit"
+// CHECK-ABS-SAME: "-o" "header-unit-01.pcm"
+// CHECK-ABS-SAME: "-x" "c++-header-unit-header" "[[TDIR]]/header-unit-01.hh"
Index: clang/lib/Frontend/FrontendOptions.cpp
===
--- clang/lib/Frontend/FrontendOptions.cpp
+++ clang/lib/Frontend/FrontendOptions.cpp
@@ -27,7 +27,7 @@
   .Cases("C", "cc", "cp", Language::CXX)
   .Cases("cpp", "CPP", "c++", "cxx", "hpp", "hxx", Language::CXX)
   .Case("cppm", Language::CXX)
-  .Case("iim", InputKind(Language::CXX).getPreprocessed())
+  .Cases("iim", "iih", InputKind(Language::CXX).getPreprocessed())
   .Case("cl", Language::OpenCL)
   .Case("clcpp", Language::OpenCLCXX)
   .Cases("cu", "cuh", Language::CUDA)
Index: clang/lib/Driver/Types.cpp
===
--- clang/lib/Driver/Types.cpp
+++ clang/lib/Driver/Types.cpp
@@ -65,9 +65,16 @@
   return Id == TY_CXXModule || Id == TY_PP_CXXModule;
 }
 
+static bool isPreprocessedHeaderUnitType(ID Id) {
+  return Id == TY_CXXSHeader || Id == TY_CXXUHeader || Id == TY_CXXHUHeader ||
+ Id == TY_PP_CXXHeaderUnit;
+}
+
 types::ID types::getPrecompiledType(ID Id) {
   if (isPreprocessedModuleType(Id))
 return TY_ModuleFile;
+  if (isPreprocessedHeaderUnitType(Id))
+return TY_HeaderUnit;
   if (onlyPrecompileType(Id))
 return TY_PCH;
   return TY_INVALID;
@@ -139,6 +146,10 @@
   case TY_CLHeader:
   case TY_ObjCHeader: case TY_PP_ObjCHeader:
   case TY_CXXHeader: case TY_PP_CXXHeader:
+  case TY_CXXSHeader:
+  case TY_CXXUHeader:
+  case TY_CXXHUHeader:
+  case TY_PP_CXXHeaderUnit:
   case TY_ObjCXXHeader: case TY_PP_ObjCXXHeader:
   case TY_CXXModule: case TY_PP_CXXModule:
   case TY_AST: case TY_ModuleFile: case TY_PCH:
@@ -210,6 +221,10 @@
   case TY_CXX: case TY_PP_CXX:
   case TY_ObjCXX: case TY_PP_ObjCXX: case TY_PP_ObjCXX_Alias:
   case TY_CXXHeader: case TY_PP_CXXHeader:
+  case TY_CXXSHeader:
+  case TY_CXXUHeader:
+  case TY_CXXHUHeader:
+  case TY_PP_CXXHeaderUnit:
   case TY_ObjCXXHeader: case TY_PP_ObjCXXHeader:
   case TY_CXXModule: case TY_PP_CXXModule:
   case TY_CUDA: case TY_PP_CUDA: case TY_CUDA_DEVICE:
@@ -323,6 +338,7 @@
.Case("hpp", TY_CXXHeader)
.Case("hxx", TY_CXXHeader)
.Case("iim", TY_PP_CXXModule)
+   .Case("iih", TY_PP_CXXHeaderUnit)
.Case("lib", TY_Object)
.Case("mii", TY_PP_ObjCXX)
.Case("obj", TY_Object)
Index: clang/lib/Driver/ToolChains/Clang.cpp
===
--- clang/lib/Driver/ToolChains/Clang.cpp
+++ clang/lib/Driver/ToolChains/Clang.cpp
@@ -4609,6 +4609,8 @@
   CmdArgs.push_back(IsHeaderModulePrecompile
 ? "-emit-header-module"
 : "-emit-module-interface");
+else if (JA.getType() == types::TY_HeaderUnit)
+  CmdArgs.push_back("-emit-header-unit");
 else
   CmdArgs.push_back("-emit-pch");
   } else if (isa(JA)) {
Index: clang/lib/Driver/Driver.cpp
===
--- clang/lib/Driver/Driver.cpp
+++ clang/lib/Driver/Driver.cpp
@@ -2219,6 +2219,11 @@
   if (Value == "-")
 return true;
 
+  // If it's a header to be found in the system or user search path, then defer
+  // compla

[PATCH] D123601: [clang][AArch64] Split neon tests into 2 files

2022-04-22 Thread David Spickett via Phabricator via cfe-commits
DavidSpickett abandoned this revision.
DavidSpickett added a comment.

People are leaning toward fixes on the buildkite side.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D123601

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


[PATCH] D124238: [AST] QualifiedTemplateName::getTemplateDecl cleanup.

2022-04-22 Thread Haojian Wu via Phabricator via cfe-commits
hokein created this revision.
hokein added a reviewer: sammccall.
Herald added a subscriber: arphaman.
Herald added a project: All.
hokein requested review of this revision.
Herald added a project: clang.

This is a followup cleanup of 1234b1c6d8113d50beef5801be607ad1d502b2f7 



Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D124238

Files:
  clang/include/clang/AST/TemplateName.h
  clang/lib/AST/ItaniumMangle.cpp
  clang/lib/AST/TemplateName.cpp
  clang/lib/Sema/TreeTransform.h
  clang/tools/libclang/CIndex.cpp


Index: clang/tools/libclang/CIndex.cpp
===
--- clang/tools/libclang/CIndex.cpp
+++ clang/tools/libclang/CIndex.cpp
@@ -1462,8 +1462,10 @@
 
   case TemplateName::QualifiedTemplate:
 // FIXME: Visit nested-name-specifier.
-return Visit(MakeCursorTemplateRef(
-Name.getAsQualifiedTemplateName()->getTemplateDecl(), Loc, TU));
+return Visit(MakeCursorTemplateRef(Name.getAsQualifiedTemplateName()
+   ->getUnderlyingTemplate()
+   .getAsTemplateDecl(),
+   Loc, TU));
 
   case TemplateName::SubstTemplateTemplateParm:
 return Visit(MakeCursorTemplateRef(
Index: clang/lib/Sema/TreeTransform.h
===
--- clang/lib/Sema/TreeTransform.h
+++ clang/lib/Sema/TreeTransform.h
@@ -4280,7 +4280,7 @@
   NamedDecl *FirstQualifierInScope,
   bool AllowInjectedClassName) {
   if (QualifiedTemplateName *QTN = Name.getAsQualifiedTemplateName()) {
-TemplateDecl *Template = QTN->getTemplateDecl();
+TemplateDecl *Template = QTN->getUnderlyingTemplate().getAsTemplateDecl();
 assert(Template && "qualified template name must refer to a template");
 
 TemplateDecl *TransTemplate
Index: clang/lib/AST/TemplateName.cpp
===
--- clang/lib/AST/TemplateName.cpp
+++ clang/lib/AST/TemplateName.cpp
@@ -115,7 +115,7 @@
   }
 
   if (QualifiedTemplateName *QTN = getAsQualifiedTemplateName())
-return QTN->getTemplateDecl();
+return QTN->getUnderlyingTemplate().getAsTemplateDecl();
 
   if (SubstTemplateTemplateParmStorage *sub = getAsSubstTemplateTemplateParm())
 return sub->getReplacement().getAsTemplateDecl();
@@ -273,14 +273,15 @@
 if (Qual == Qualified::Fully &&
 getDependence() !=
 TemplateNameDependenceScope::DependentInstantiation) {
-  QTN->getTemplateDecl()->printQualifiedName(OS, Policy);
+  QTN->getUnderlyingTemplate().getAsTemplateDecl()->printQualifiedName(
+  OS, Policy);
   return;
 }
 if (Qual == Qualified::AsWritten)
   QTN->getQualifier()->print(OS, Policy);
 if (QTN->hasTemplateKeyword())
   OS << "template ";
-OS << *QTN->getTemplateDecl();
+OS << *QTN->getUnderlyingTemplate().getAsTemplateDecl();
   } else if (DependentTemplateName *DTN = getAsDependentTemplateName()) {
 if (Qual == Qualified::AsWritten && DTN->getQualifier())
   DTN->getQualifier()->print(OS, Policy);
Index: clang/lib/AST/ItaniumMangle.cpp
===
--- clang/lib/AST/ItaniumMangle.cpp
+++ clang/lib/AST/ItaniumMangle.cpp
@@ -2204,7 +2204,9 @@
 
   switch (TN.getKind()) {
   case TemplateName::QualifiedTemplate:
-TD = TN.getAsQualifiedTemplateName()->getTemplateDecl();
+TD = TN.getAsQualifiedTemplateName()
+ ->getUnderlyingTemplate()
+ .getAsTemplateDecl();
 goto HaveDecl;
 
   case TemplateName::UsingTemplate:
Index: clang/include/clang/AST/TemplateName.h
===
--- clang/include/clang/AST/TemplateName.h
+++ clang/include/clang/AST/TemplateName.h
@@ -439,13 +439,6 @@
   /// Return the underlying template name.
   TemplateName getUnderlyingTemplate() const { return UnderlyingTemplate; }
 
-  /// The template declaration to which this qualified name
-  /// refers.
-  /// FIXME: remove this and use getUnderlyingTemplate() instead.
-  TemplateDecl *getTemplateDecl() const {
-return UnderlyingTemplate.getAsTemplateDecl();
-  }
-
   void Profile(llvm::FoldingSetNodeID &ID) {
 Profile(ID, getQualifier(), hasTemplateKeyword(), UnderlyingTemplate);
   }


Index: clang/tools/libclang/CIndex.cpp
===
--- clang/tools/libclang/CIndex.cpp
+++ clang/tools/libclang/CIndex.cpp
@@ -1462,8 +1462,10 @@
 
   case TemplateName::QualifiedTemplate:
 // FIXME: Visit nested-name-specifier.
-return Visit(MakeCursorTemplateRef(
-Name.getAsQualifiedTemplateName()->getTemplateDecl(), Loc, TU));
+return Visit(MakeCursorTemplateRef(Name.getAsQ

[PATCH] D124239: [analyzer] Fix ValistChecker false-positive involving symbolic pointers

2022-04-22 Thread Balázs Benics via Phabricator via cfe-commits
steakhal created this revision.
steakhal added reviewers: NoQ, martong, xazax.hun, Szelethus, ASDenysPetrov.
Herald added subscribers: manas, dkrupp, donat.nagy, mikhail.ramalho, 
a.sidorin, rnkovacs, szepet, baloghadamsoftware.
Herald added a project: All.
steakhal requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

In the following example:

  int va_list_get_int(va_list *va) {
return va_arg(*va, int); // FP
  }

The `*va` expression will be something like `Element{SymRegion{va}, 0, 
va_list}`.
We use `ElementRegions` for representing the result of the dereference.
In this case, the `IsSymbolic` was set to `false` in the
`getVAListAsRegion()`.

Hence, before checking if the memregion is a SymRegion, we should take
the base of that region.

Analogously to the previous example, one can craft other cases:

  struct MyVaList {
va_list l;
  };
  int va_list_get_int(struct MyVaList va) {
return va_arg(va.l, int); // FP
  }

But it would also work if the `va_list` would be in the base or derived
part of a class. `ObjCIvarRegions` are likely also susceptible.
I'm not explicitly demonstrating these cases.

PS: Check the `MemRegion::getBaseRegion()` definition.

Fixes #55009


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D124239

Files:
  clang/lib/StaticAnalyzer/Checkers/ValistChecker.cpp
  clang/test/Analysis/valist-uninitialized-no-undef.c


Index: clang/test/Analysis/valist-uninitialized-no-undef.c
===
--- clang/test/Analysis/valist-uninitialized-no-undef.c
+++ clang/test/Analysis/valist-uninitialized-no-undef.c
@@ -16,11 +16,20 @@
 
 void f6(va_list *fst, ...) {
   va_start(*fst, fst);
-  // FIXME: There should be no warning for this.
-  (void)va_arg(*fst, int); // expected-warning{{va_arg() is called on an 
uninitialized va_list}}
-  // expected-note@-1{{va_arg() is called on an uninitialized va_list}}
+  (void)va_arg(*fst, int);
   va_end(*fst);
-} 
+}
+
+int va_list_get_int(va_list *va) {
+  return va_arg(*va, int); // no-warning
+}
+
+struct MyVaList {
+  va_list l;
+};
+int va_list_get_int(struct MyVaList va) {
+  return va_arg(va.l, int); // no-warning
+}
 
 void call_vprintf_bad(int isstring, ...) {
   va_list va;
Index: clang/lib/StaticAnalyzer/Checkers/ValistChecker.cpp
===
--- clang/lib/StaticAnalyzer/Checkers/ValistChecker.cpp
+++ clang/lib/StaticAnalyzer/Checkers/ValistChecker.cpp
@@ -178,7 +178,7 @@
 if (isa(DeclReg->getDecl()))
   Reg = C.getState()->getSVal(SV.castAs()).getAsRegion();
   }
-  IsSymbolic = Reg && Reg->getAs();
+  IsSymbolic = Reg && Reg->getBaseRegion()->getAs();
   // Some VarRegion based VA lists reach here as ElementRegions.
   const auto *EReg = dyn_cast_or_null(Reg);
   return (EReg && VaListModelledAsArray) ? EReg->getSuperRegion() : Reg;


Index: clang/test/Analysis/valist-uninitialized-no-undef.c
===
--- clang/test/Analysis/valist-uninitialized-no-undef.c
+++ clang/test/Analysis/valist-uninitialized-no-undef.c
@@ -16,11 +16,20 @@
 
 void f6(va_list *fst, ...) {
   va_start(*fst, fst);
-  // FIXME: There should be no warning for this.
-  (void)va_arg(*fst, int); // expected-warning{{va_arg() is called on an uninitialized va_list}}
-  // expected-note@-1{{va_arg() is called on an uninitialized va_list}}
+  (void)va_arg(*fst, int);
   va_end(*fst);
-} 
+}
+
+int va_list_get_int(va_list *va) {
+  return va_arg(*va, int); // no-warning
+}
+
+struct MyVaList {
+  va_list l;
+};
+int va_list_get_int(struct MyVaList va) {
+  return va_arg(va.l, int); // no-warning
+}
 
 void call_vprintf_bad(int isstring, ...) {
   va_list va;
Index: clang/lib/StaticAnalyzer/Checkers/ValistChecker.cpp
===
--- clang/lib/StaticAnalyzer/Checkers/ValistChecker.cpp
+++ clang/lib/StaticAnalyzer/Checkers/ValistChecker.cpp
@@ -178,7 +178,7 @@
 if (isa(DeclReg->getDecl()))
   Reg = C.getState()->getSVal(SV.castAs()).getAsRegion();
   }
-  IsSymbolic = Reg && Reg->getAs();
+  IsSymbolic = Reg && Reg->getBaseRegion()->getAs();
   // Some VarRegion based VA lists reach here as ElementRegions.
   const auto *EReg = dyn_cast_or_null(Reg);
   return (EReg && VaListModelledAsArray) ? EReg->getSuperRegion() : Reg;
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D124240: [clangd][NFC] Reduce memory usage while building dex

2022-04-22 Thread Kadir Cetinkaya via Phabricator via cfe-commits
kadircet created this revision.
kadircet added reviewers: sammccall, kbobyrev.
Herald added subscribers: usaxena95, arphaman.
Herald added a project: All.
kadircet requested review of this revision.
Herald added subscribers: cfe-commits, MaskRay, ilya-biryukov.
Herald added a project: clang-tools-extra.

Posting lists were copied into the final inverted index rather than
being moved. Also we weren't shrinking the vectors. This patch should help with
both peak memory usage while building dex (preamble/background-index) and it's
idle memory usage (unclear if copy constructor of vector preserves the capacity
or not).


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D124240

Files:
  clang-tools-extra/clangd/index/dex/Dex.cpp


Index: clang-tools-extra/clangd/index/dex/Dex.cpp
===
--- clang-tools-extra/clangd/index/dex/Dex.cpp
+++ clang-tools-extra/clangd/index/dex/Dex.cpp
@@ -21,6 +21,7 @@
 #include "llvm/Support/ScopedPrinter.h"
 #include 
 #include 
+#include 
 
 namespace clang {
 namespace clangd {
@@ -76,23 +77,42 @@
   }
 
   // Assemble the final compressed posting lists for the added symbols.
-  llvm::DenseMap build() {
+  llvm::DenseMap build() && {
 llvm::DenseMap Result(/*InitialReserve=*/
   TrigramDocs.size() +
   RestrictedCCDocs.size() +
   TypeDocs.size() +
   ScopeDocs.size() +
   ProximityDocs.size());
-for (const auto &E : TrigramDocs)
-  Result.try_emplace(Token(Token::Kind::Trigram, E.first.str()), E.second);
-for (const auto &E : TypeDocs)
-  Result.try_emplace(Token(Token::Kind::Type, E.first()), E.second);
-for (const auto &E : ScopeDocs)
-  Result.try_emplace(Token(Token::Kind::Scope, E.first()), E.second);
-for (const auto &E : ProximityDocs)
-  Result.try_emplace(Token(Token::Kind::ProximityURI, E.first()), 
E.second);
-if (!RestrictedCCDocs.empty())
-  Result.try_emplace(RestrictedForCodeCompletion, RestrictedCCDocs);
+for (auto &E : TrigramDocs) {
+  E.second.shrink_to_fit();
+  Result.try_emplace(Token(Token::Kind::Trigram, E.first.str()),
+ std::move(E.second));
+}
+TrigramDocs.clear();
+for (auto &E : TypeDocs) {
+  E.second.shrink_to_fit();
+  Result.try_emplace(Token(Token::Kind::Type, E.first()),
+ std::move(E.second));
+}
+TypeDocs.clear();
+for (auto &E : ScopeDocs) {
+  E.second.shrink_to_fit();
+  Result.try_emplace(Token(Token::Kind::Scope, E.first()),
+ std::move(E.second));
+}
+ScopeDocs.clear();
+for (auto &E : ProximityDocs) {
+  E.second.shrink_to_fit();
+  Result.try_emplace(Token(Token::Kind::ProximityURI, E.first()),
+ std::move(E.second));
+}
+ProximityDocs.clear();
+if (!RestrictedCCDocs.empty()) {
+  RestrictedCCDocs.shrink_to_fit();
+  Result.try_emplace(RestrictedForCodeCompletion,
+ std::move(RestrictedCCDocs));
+}
 return Result;
   }
 };
@@ -125,7 +145,7 @@
   IndexBuilder Builder;
   for (DocID SymbolRank = 0; SymbolRank < Symbols.size(); ++SymbolRank)
 Builder.add(*Symbols[SymbolRank], SymbolRank);
-  InvertedIndex = Builder.build();
+  InvertedIndex = std::move(Builder).build();
 }
 
 std::unique_ptr Dex::iterator(const Token &Tok) const {


Index: clang-tools-extra/clangd/index/dex/Dex.cpp
===
--- clang-tools-extra/clangd/index/dex/Dex.cpp
+++ clang-tools-extra/clangd/index/dex/Dex.cpp
@@ -21,6 +21,7 @@
 #include "llvm/Support/ScopedPrinter.h"
 #include 
 #include 
+#include 
 
 namespace clang {
 namespace clangd {
@@ -76,23 +77,42 @@
   }
 
   // Assemble the final compressed posting lists for the added symbols.
-  llvm::DenseMap build() {
+  llvm::DenseMap build() && {
 llvm::DenseMap Result(/*InitialReserve=*/
   TrigramDocs.size() +
   RestrictedCCDocs.size() +
   TypeDocs.size() +
   ScopeDocs.size() +
   ProximityDocs.size());
-for (const auto &E : TrigramDocs)
-  Result.try_emplace(Token(Token::Kind::Trigram, E.first.str()), E.second);
-for (const auto &E : TypeDocs)
-  Result.try_emplace(Token(Token::Kind::Type, E.first()), E.second);
-for (const auto &E : ScopeDocs)
-  Result.try_emplace(Token(Token::Kind::Scope, E.first()), E.second);
-for (const auto &E : ProximityDocs)
-  Result.try_emplace(Token(Token::Kind::ProximityURI, E.first()), E.second);
-if (!Restricted

[PATCH] D124240: [clangd][NFC] Reduce memory usage while building dex

2022-04-22 Thread Kadir Cetinkaya via Phabricator via cfe-commits
kadircet updated this revision to Diff 424417.
kadircet added a comment.

Get rid of shrink_to_fit as PostingList representation doesn't really make a 
copy of the vector, but rather build a new representation.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124240

Files:
  clang-tools-extra/clangd/index/dex/Dex.cpp


Index: clang-tools-extra/clangd/index/dex/Dex.cpp
===
--- clang-tools-extra/clangd/index/dex/Dex.cpp
+++ clang-tools-extra/clangd/index/dex/Dex.cpp
@@ -21,6 +21,7 @@
 #include "llvm/Support/ScopedPrinter.h"
 #include 
 #include 
+#include 
 
 namespace clang {
 namespace clangd {
@@ -76,23 +77,32 @@
   }
 
   // Assemble the final compressed posting lists for the added symbols.
-  llvm::DenseMap build() {
+  llvm::DenseMap build() && {
 llvm::DenseMap Result(/*InitialReserve=*/
   TrigramDocs.size() +
   RestrictedCCDocs.size() +
   TypeDocs.size() +
   ScopeDocs.size() +
   ProximityDocs.size());
-for (const auto &E : TrigramDocs)
-  Result.try_emplace(Token(Token::Kind::Trigram, E.first.str()), E.second);
-for (const auto &E : TypeDocs)
-  Result.try_emplace(Token(Token::Kind::Type, E.first()), E.second);
-for (const auto &E : ScopeDocs)
-  Result.try_emplace(Token(Token::Kind::Scope, E.first()), E.second);
-for (const auto &E : ProximityDocs)
-  Result.try_emplace(Token(Token::Kind::ProximityURI, E.first()), 
E.second);
+for (auto &E : TrigramDocs)
+  Result.try_emplace(Token(Token::Kind::Trigram, E.first.str()),
+ std::move(E.second));
+TrigramDocs.clear();
+for (auto &E : TypeDocs)
+  Result.try_emplace(Token(Token::Kind::Type, E.first()),
+ std::move(E.second));
+TypeDocs.clear();
+for (auto &E : ScopeDocs)
+  Result.try_emplace(Token(Token::Kind::Scope, E.first()),
+ std::move(E.second));
+ScopeDocs.clear();
+for (auto &E : ProximityDocs)
+  Result.try_emplace(Token(Token::Kind::ProximityURI, E.first()),
+ std::move(E.second));
+ProximityDocs.clear();
 if (!RestrictedCCDocs.empty())
-  Result.try_emplace(RestrictedForCodeCompletion, RestrictedCCDocs);
+  Result.try_emplace(RestrictedForCodeCompletion,
+ std::move(RestrictedCCDocs));
 return Result;
   }
 };
@@ -125,7 +135,7 @@
   IndexBuilder Builder;
   for (DocID SymbolRank = 0; SymbolRank < Symbols.size(); ++SymbolRank)
 Builder.add(*Symbols[SymbolRank], SymbolRank);
-  InvertedIndex = Builder.build();
+  InvertedIndex = std::move(Builder).build();
 }
 
 std::unique_ptr Dex::iterator(const Token &Tok) const {


Index: clang-tools-extra/clangd/index/dex/Dex.cpp
===
--- clang-tools-extra/clangd/index/dex/Dex.cpp
+++ clang-tools-extra/clangd/index/dex/Dex.cpp
@@ -21,6 +21,7 @@
 #include "llvm/Support/ScopedPrinter.h"
 #include 
 #include 
+#include 
 
 namespace clang {
 namespace clangd {
@@ -76,23 +77,32 @@
   }
 
   // Assemble the final compressed posting lists for the added symbols.
-  llvm::DenseMap build() {
+  llvm::DenseMap build() && {
 llvm::DenseMap Result(/*InitialReserve=*/
   TrigramDocs.size() +
   RestrictedCCDocs.size() +
   TypeDocs.size() +
   ScopeDocs.size() +
   ProximityDocs.size());
-for (const auto &E : TrigramDocs)
-  Result.try_emplace(Token(Token::Kind::Trigram, E.first.str()), E.second);
-for (const auto &E : TypeDocs)
-  Result.try_emplace(Token(Token::Kind::Type, E.first()), E.second);
-for (const auto &E : ScopeDocs)
-  Result.try_emplace(Token(Token::Kind::Scope, E.first()), E.second);
-for (const auto &E : ProximityDocs)
-  Result.try_emplace(Token(Token::Kind::ProximityURI, E.first()), E.second);
+for (auto &E : TrigramDocs)
+  Result.try_emplace(Token(Token::Kind::Trigram, E.first.str()),
+ std::move(E.second));
+TrigramDocs.clear();
+for (auto &E : TypeDocs)
+  Result.try_emplace(Token(Token::Kind::Type, E.first()),
+ std::move(E.second));
+TypeDocs.clear();
+for (auto &E : ScopeDocs)
+  Result.try_emplace(Token(Token::Kind::Scope, E.first()),
+ std::move(E.second));
+ScopeDocs.clear();
+for (auto &E : ProximityDocs)
+  Result.try_emplace(Token(Token::Kind::ProximityURI, E.first()),
+   

[PATCH] D124006: [DebugInfo] Use the 'getTypeAlignIfRequired' function to get DW_AT_alignment correct when attribute((__aligned__)) is present.

2022-04-22 Thread Ying Yi via Phabricator via cfe-commits
MaggieYi updated this revision to Diff 424420.

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

https://reviews.llvm.org/D124006

Files:
  clang/lib/CodeGen/CGDebugInfo.cpp
  clang/test/CodeGenCXX/debug-info-struct-align.cpp


Index: clang/test/CodeGenCXX/debug-info-struct-align.cpp
===
--- /dev/null
+++ clang/test/CodeGenCXX/debug-info-struct-align.cpp
@@ -0,0 +1,27 @@
+//  Test for debug info related to DW_AT_alignment attribute in the struct 
type.
+// RUN: %clang_cc1 -dwarf-version=5 -debug-info-kind=standalone -S -emit-llvm 
%s -o - | FileCheck %s
+
+// CHECK-DAG: DICompositeType(tag: DW_TAG_structure_type, name: "MyType", 
{{.*}}, align: 32
+// CHECK-DAG: DICompositeType(tag: DW_TAG_structure_type, name: "MyType1", 
{{.*}}, align: 8
+// CHECK-DAG: DICompositeType(tag: DW_TAG_structure_type, name: "MyType2", 
{{.*}}, align: 8
+
+struct MyType {
+  int m;
+} __attribute__((aligned(1)));
+MyType mt;
+
+static_assert(alignof(MyType) == 4, "alignof MyType is wrong");
+
+struct MyType1 {
+  int m;
+} __attribute__((packed, aligned(1)));
+MyType1 mt1;
+
+static_assert(alignof(MyType1) == 1, "alignof MyType1 is wrong");
+
+struct MyType2 {
+  __attribute__((packed)) int m;
+} __attribute__((aligned(1)));
+MyType2 mt2;
+
+static_assert(alignof(MyType2) == 1, "alignof MyType2 is wrong");
Index: clang/lib/CodeGen/CGDebugInfo.cpp
===
--- clang/lib/CodeGen/CGDebugInfo.cpp
+++ clang/lib/CodeGen/CGDebugInfo.cpp
@@ -3561,7 +3561,11 @@
 return getOrCreateRecordFwdDecl(Ty, RDContext);
 
   uint64_t Size = CGM.getContext().getTypeSize(Ty);
-  auto Align = getDeclAlignIfRequired(D, CGM.getContext());
+  // __attribute__((aligned)) can increase or decrease alignment *except* on a
+  // struct or struct member, where it only increases  alignment unless 
'packed'
+  // is also specified. To handle this case, the `getTypeAlignIfRequired` needs
+  // to be used.
+  auto Align = getTypeAlignIfRequired(Ty, CGM.getContext());
 
   SmallString<256> Identifier = getTypeIdentifier(Ty, CGM, TheCU);
 


Index: clang/test/CodeGenCXX/debug-info-struct-align.cpp
===
--- /dev/null
+++ clang/test/CodeGenCXX/debug-info-struct-align.cpp
@@ -0,0 +1,27 @@
+//  Test for debug info related to DW_AT_alignment attribute in the struct type.
+// RUN: %clang_cc1 -dwarf-version=5 -debug-info-kind=standalone -S -emit-llvm %s -o - | FileCheck %s
+
+// CHECK-DAG: DICompositeType(tag: DW_TAG_structure_type, name: "MyType", {{.*}}, align: 32
+// CHECK-DAG: DICompositeType(tag: DW_TAG_structure_type, name: "MyType1", {{.*}}, align: 8
+// CHECK-DAG: DICompositeType(tag: DW_TAG_structure_type, name: "MyType2", {{.*}}, align: 8
+
+struct MyType {
+  int m;
+} __attribute__((aligned(1)));
+MyType mt;
+
+static_assert(alignof(MyType) == 4, "alignof MyType is wrong");
+
+struct MyType1 {
+  int m;
+} __attribute__((packed, aligned(1)));
+MyType1 mt1;
+
+static_assert(alignof(MyType1) == 1, "alignof MyType1 is wrong");
+
+struct MyType2 {
+  __attribute__((packed)) int m;
+} __attribute__((aligned(1)));
+MyType2 mt2;
+
+static_assert(alignof(MyType2) == 1, "alignof MyType2 is wrong");
Index: clang/lib/CodeGen/CGDebugInfo.cpp
===
--- clang/lib/CodeGen/CGDebugInfo.cpp
+++ clang/lib/CodeGen/CGDebugInfo.cpp
@@ -3561,7 +3561,11 @@
 return getOrCreateRecordFwdDecl(Ty, RDContext);
 
   uint64_t Size = CGM.getContext().getTypeSize(Ty);
-  auto Align = getDeclAlignIfRequired(D, CGM.getContext());
+  // __attribute__((aligned)) can increase or decrease alignment *except* on a
+  // struct or struct member, where it only increases  alignment unless 'packed'
+  // is also specified. To handle this case, the `getTypeAlignIfRequired` needs
+  // to be used.
+  auto Align = getTypeAlignIfRequired(Ty, CGM.getContext());
 
   SmallString<256> Identifier = getTypeIdentifier(Ty, CGM, TheCU);
 
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D124006: [DebugInfo] Use the 'getTypeAlignIfRequired' function to get DW_AT_alignment correct when attribute((__aligned__)) is present.

2022-04-22 Thread Ying Yi via Phabricator via cfe-commits
MaggieYi added inline comments.



Comment at: clang/test/CodeGenCXX/debug-info-struct-align.cpp:11
+} __attribute__((aligned(1)));
+struct MyType mt;
+

dblaikie wrote:
> You can drop the "struct" here and from other references to these types (in 
> mt1/mt2 and the alignof calls)
Thanks David. All unnecessary `struct`s have been removed. 


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

https://reviews.llvm.org/D124006

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


[PATCH] D124240: [clangd][NFC] Reduce memory usage while building dex

2022-04-22 Thread Sam McCall via Phabricator via cfe-commits
sammccall added inline comments.



Comment at: clang-tools-extra/clangd/index/dex/Dex.cpp:89
+  Result.try_emplace(Token(Token::Kind::Trigram, E.first.str()),
+ std::move(E.second));
+TrigramDocs.clear();

the move here does nothing, we're passing as ArrayRef

did you want to clear the map values (vectors) as you went, too?

(this gets a bit verbose, but you could pull out a function template since all 
4 cases are so regular)


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124240

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


[PATCH] D124242: [Frontend] shrink in-memory PCH buffers to fit

2022-04-22 Thread Sam McCall via Phabricator via cfe-commits
sammccall created this revision.
sammccall added a reviewer: kadircet.
Herald added a project: All.
sammccall requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

After building a PCH, the vector capacity is on average ~1/3 unused.
If we're going to keep it in memory for a while, reallocate to the right size.
Take care to do this once clang is destroyed so that we can reuse its
memory rather than requesting more.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D124242

Files:
  clang/lib/Frontend/PrecompiledPreamble.cpp


Index: clang/lib/Frontend/PrecompiledPreamble.cpp
===
--- clang/lib/Frontend/PrecompiledPreamble.cpp
+++ clang/lib/Frontend/PrecompiledPreamble.cpp
@@ -374,6 +374,15 @@
 return StringRef(Memory->Data.data(), Memory->Data.size());
   }
 
+  // Shrink in-memory buffers to fit.
+  // This incurs a copy, but preambles tend to be long-lived.
+  // Only safe to call once nothing can alias the buffer.
+  void shrink() {
+if (!Memory)
+  return;
+Memory->Data = decltype(Memory->Data)(Memory->Data);
+  }
+
 private:
   PCHStorage() = default;
   PCHStorage(const PCHStorage &) = delete;
@@ -520,7 +529,7 @@
 
   if (!Act->hasEmittedPreamblePCH())
 return BuildPreambleError::CouldntEmitPCH;
-  Act.reset(); // Frees the PCH buffer frees, unless Storage keeps it in 
memory.
+  Act.reset(); // Frees the PCH buffer, unless Storage keeps it in memory.
 
   // Keep track of all of the files that the source manager knows about,
   // so we can verify whether they have changed or not.
@@ -545,6 +554,11 @@
 }
   }
 
+  // Shrinking the storage requires extra temporary memory.
+  // Destroying clang first reduces peak memory usage.
+  CICleanup.unregister();
+  Clang.reset();
+  Storage->shrink();
   return PrecompiledPreamble(
   std::move(Storage), std::move(PreambleBytes), PreambleEndsAtStartOfLine,
   std::move(FilesInPreamble), std::move(MissingFiles));


Index: clang/lib/Frontend/PrecompiledPreamble.cpp
===
--- clang/lib/Frontend/PrecompiledPreamble.cpp
+++ clang/lib/Frontend/PrecompiledPreamble.cpp
@@ -374,6 +374,15 @@
 return StringRef(Memory->Data.data(), Memory->Data.size());
   }
 
+  // Shrink in-memory buffers to fit.
+  // This incurs a copy, but preambles tend to be long-lived.
+  // Only safe to call once nothing can alias the buffer.
+  void shrink() {
+if (!Memory)
+  return;
+Memory->Data = decltype(Memory->Data)(Memory->Data);
+  }
+
 private:
   PCHStorage() = default;
   PCHStorage(const PCHStorage &) = delete;
@@ -520,7 +529,7 @@
 
   if (!Act->hasEmittedPreamblePCH())
 return BuildPreambleError::CouldntEmitPCH;
-  Act.reset(); // Frees the PCH buffer frees, unless Storage keeps it in memory.
+  Act.reset(); // Frees the PCH buffer, unless Storage keeps it in memory.
 
   // Keep track of all of the files that the source manager knows about,
   // so we can verify whether they have changed or not.
@@ -545,6 +554,11 @@
 }
   }
 
+  // Shrinking the storage requires extra temporary memory.
+  // Destroying clang first reduces peak memory usage.
+  CICleanup.unregister();
+  Clang.reset();
+  Storage->shrink();
   return PrecompiledPreamble(
   std::move(Storage), std::move(PreambleBytes), PreambleEndsAtStartOfLine,
   std::move(FilesInPreamble), std::move(MissingFiles));
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D124238: [AST] QualifiedTemplateName::getTemplateDecl cleanup.

2022-04-22 Thread Sam McCall via Phabricator via cfe-commits
sammccall accepted this revision.
sammccall added inline comments.
This revision is now accepted and ready to land.



Comment at: clang/lib/AST/ItaniumMangle.cpp:2206
   switch (TN.getKind()) {
   case TemplateName::QualifiedTemplate:
+TD = TN.getAsQualifiedTemplateName()

can't this just be TN.getAsTemplateDecl() and tacked onto the next case?



Comment at: clang/tools/libclang/CIndex.cpp:1465
 // FIXME: Visit nested-name-specifier.
-return Visit(MakeCursorTemplateRef(
-Name.getAsQualifiedTemplateName()->getTemplateDecl(), Loc, TU));
+return Visit(MakeCursorTemplateRef(Name.getAsQualifiedTemplateName()
+   ->getUnderlyingTemplate()

this can be handled along with the Template/UsingTemplate cases (apart from the 
fixme)


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124238

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


[PATCH] D124244: [analyzer] add StoreToImmutable and ModelConstQualifiedReturn checkers

2022-04-22 Thread Zurab Tsinadze via Phabricator via cfe-commits
zukatsinadze created this revision.
zukatsinadze added reviewers: NoQ, martong, steakhal, balazske, vsavchenko.
zukatsinadze added a project: clang.
Herald added subscribers: manas, ASDenysPetrov, dkrupp, donat.nagy, Szelethus, 
mikhail.ramalho, a.sidorin, rnkovacs, szepet, baloghadamsoftware, xazax.hun, 
mgorny.
Herald added a project: All.
zukatsinadze requested review of this revision.
Herald added a subscriber: cfe-commits.

The patch adds two new checkers. 
//core.StoreToImmutable// that warns binds on immutable memory and
//alpha.security.cert.env.ModelConstQualifiedReturn// that models return values
of some functions that should be considered const qualified. Based on SEI CERT 
ENV30-C: https://wiki.sei.cmu.edu/confluence/x/79UxBQ


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D124244

Files:
  clang/docs/analyzer/checkers.rst
  clang/include/clang/StaticAnalyzer/Checkers/Checkers.td
  clang/include/clang/StaticAnalyzer/Core/PathSensitive/MemRegion.h
  clang/lib/StaticAnalyzer/Checkers/CMakeLists.txt
  clang/lib/StaticAnalyzer/Checkers/StoreToImmutableChecker.cpp
  clang/lib/StaticAnalyzer/Checkers/cert/ModelConstQualifiedReturnChecker.cpp
  clang/test/Analysis/analyzer-enabled-checkers.c
  clang/test/Analysis/cert/env30-c.cpp
  clang/test/Analysis/std-c-library-functions-arg-enabled-checkers.c

Index: clang/test/Analysis/std-c-library-functions-arg-enabled-checkers.c
===
--- clang/test/Analysis/std-c-library-functions-arg-enabled-checkers.c
+++ clang/test/Analysis/std-c-library-functions-arg-enabled-checkers.c
@@ -32,6 +32,7 @@
 // CHECK-NEXT: core.NullDereference
 // CHECK-NEXT: core.StackAddrEscapeBase
 // CHECK-NEXT: core.StackAddressEscape
+// CHECK-NEXT: core.StoreToImmutable
 // CHECK-NEXT: core.UndefinedBinaryOperatorResult
 // CHECK-NEXT: core.VLASize
 // CHECK-NEXT: core.builtin.BuiltinFunctions
Index: clang/test/Analysis/cert/env30-c.cpp
===
--- /dev/null
+++ clang/test/Analysis/cert/env30-c.cpp
@@ -0,0 +1,216 @@
+// RUN: %clang_analyze_cc1 \
+// RUN:  -analyzer-checker=core.StoreToImmutable,alpha.security.cert.env.ModelConstQualifiedReturn \
+// RUN:  -analyzer-output=text -verify -Wno-unused %s
+
+#include "../Inputs/system-header-simulator.h"
+char *getenv(const char *name);
+char *setlocale(int category, const char *locale);
+char *strerror(int errnum);
+int setenv(const char *name, const char *value, int overwrite);
+void free(void *memblock);
+void *malloc(size_t size);
+char *strdup(const char *s);
+
+typedef struct {
+} tm;
+char *asctime(const tm *timeptr);
+
+int strcmp(const char *, const char *);
+void non_const_parameter_function(char *e);
+void const_parameter_function(const char *);
+
+
+
+void getenv_test1() {
+  char *p = getenv("VAR");
+  // expected-note@-1{{return value of 'getenv' should be treated as const-qualified}}
+  *p = 'A';
+  // expected-warning@-1{{modifying immutable memory [core.StoreToImmutable]}}
+  // expected-note@-2{{modifying immutable memory}}
+}
+
+void getenv_test2() {
+  char *p;
+
+  p = getenv("VAR");
+  non_const_parameter_function(p); // FIXME: Maybe we should warn for these.
+}
+
+void getenv_test3() {
+  char *p;
+  p = getenv("VAR");
+  const_parameter_function(p); // no-warning
+}
+
+void modify(char *p) {
+  *p = 'A';
+  // expected-warning@-1{{modifying immutable memory [core.StoreToImmutable]}}
+  // expected-note@-2{{modifying immutable memory}}
+}
+
+void getenv_test4() {
+  char *p = getenv("VAR");
+  // expected-note@-1{{return value of 'getenv' should be treated as const-qualified}}
+  char *pp = p;
+  modify(pp); // Writing to immutable region within the call.
+  // expected-note@-1{{Calling 'modify'}}
+}
+
+void does_not_modify(char *p) {
+  *p;
+}
+
+void getenv_test5() {
+  char *p = getenv("VAR");
+  does_not_modify(p); // no-warning
+}
+
+void getenv_test6() {
+  static char *array[] = {0};
+
+  if (!array[0]) {
+// expected-note@-1{{Taking true branch}}
+array[0] = getenv("TEMPDIR");
+// expected-note@-1{{return value of 'getenv' should be treated as const-qualified}}
+  }
+
+  *array[0] = 'A';
+  // expected-warning@-1{{modifying immutable memory [core.StoreToImmutable]}}
+  // expected-note@-2{{modifying immutable memory}}
+}
+
+void getenv_test7() {
+  char *p = getenv("VAR");
+  // expected-note@-1{{return value of 'getenv' should be treated as const-qualified}}
+  if (!p)
+// expected-note@-1{{Assuming 'p' is non-null}}
+// expected-note@-2{{Taking false branch}}
+return;
+  p[0] = '\0';
+  // expected-warning@-1{{modifying immutable memory [core.StoreToImmutable]}}
+  // expected-note@-2{{modifying immutable memory}}
+}
+
+void setlocale_test() {
+  char *p = setlocale(0, "VAR");
+  // expected-note@-1{{return value of 'setlocale' should be treated as const-qualified}}
+  *p = 'A';
+  // expected-warning@-1{{modifying immutable memory [core.StoreToIm

[clang] b09ba42 - Bug 51277: [DWARF] DW_AT_alignment incorrect when

2022-04-22 Thread Ying Yi via cfe-commits

Author: Ying Yi
Date: 2022-04-22T12:15:00+01:00
New Revision: b09ba42620768c0092b20cf526a30b14752a5dc9

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

LOG: Bug 51277: [DWARF] DW_AT_alignment incorrect when
attribute((__aligned__)) is present but ignored`

In the original code, the 'getDeclAlignIfRequired' function is used.
The 'getDeclAlignIfRequired' function will return the max alignment
of all aligned attributes if the type has aligned attributes. The
function doesn't consider the type at all.

The 'getTypeAlignIfRequired' function uses the type's alignment value,
which also used by the 'alignof' function. I think we should use the
function of 'getTypeAlignIfRequired'.

Reviewed By: dblaikie, jmorse, wolfgangp

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

Added: 
clang/test/CodeGenCXX/debug-info-struct-align.cpp

Modified: 
clang/lib/CodeGen/CGDebugInfo.cpp

Removed: 




diff  --git a/clang/lib/CodeGen/CGDebugInfo.cpp 
b/clang/lib/CodeGen/CGDebugInfo.cpp
index 846b9db76dd4a..a6ea2c0f31abf 100644
--- a/clang/lib/CodeGen/CGDebugInfo.cpp
+++ b/clang/lib/CodeGen/CGDebugInfo.cpp
@@ -3561,7 +3561,11 @@ llvm::DICompositeType 
*CGDebugInfo::CreateLimitedType(const RecordType *Ty) {
 return getOrCreateRecordFwdDecl(Ty, RDContext);
 
   uint64_t Size = CGM.getContext().getTypeSize(Ty);
-  auto Align = getDeclAlignIfRequired(D, CGM.getContext());
+  // __attribute__((aligned)) can increase or decrease alignment *except* on a
+  // struct or struct member, where it only increases  alignment unless 
'packed'
+  // is also specified. To handle this case, the `getTypeAlignIfRequired` needs
+  // to be used.
+  auto Align = getTypeAlignIfRequired(Ty, CGM.getContext());
 
   SmallString<256> Identifier = getTypeIdentifier(Ty, CGM, TheCU);
 

diff  --git a/clang/test/CodeGenCXX/debug-info-struct-align.cpp 
b/clang/test/CodeGenCXX/debug-info-struct-align.cpp
new file mode 100644
index 0..6d75c71476ba1
--- /dev/null
+++ b/clang/test/CodeGenCXX/debug-info-struct-align.cpp
@@ -0,0 +1,27 @@
+//  Test for debug info related to DW_AT_alignment attribute in the struct 
type.
+// RUN: %clang_cc1 -dwarf-version=5 -debug-info-kind=standalone -S -emit-llvm 
%s -o - | FileCheck %s
+
+// CHECK-DAG: DICompositeType(tag: DW_TAG_structure_type, name: "MyType", 
{{.*}}, align: 32
+// CHECK-DAG: DICompositeType(tag: DW_TAG_structure_type, name: "MyType1", 
{{.*}}, align: 8
+// CHECK-DAG: DICompositeType(tag: DW_TAG_structure_type, name: "MyType2", 
{{.*}}, align: 8
+
+struct MyType {
+  int m;
+} __attribute__((aligned(1)));
+MyType mt;
+
+static_assert(alignof(MyType) == 4, "alignof MyType is wrong");
+
+struct MyType1 {
+  int m;
+} __attribute__((packed, aligned(1)));
+MyType1 mt1;
+
+static_assert(alignof(MyType1) == 1, "alignof MyType1 is wrong");
+
+struct MyType2 {
+  __attribute__((packed)) int m;
+} __attribute__((aligned(1)));
+MyType2 mt2;
+
+static_assert(alignof(MyType2) == 1, "alignof MyType2 is wrong");



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


[PATCH] D124006: [DebugInfo] Use the 'getTypeAlignIfRequired' function to get DW_AT_alignment correct when attribute((__aligned__)) is present.

2022-04-22 Thread Ying Yi 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 rGb09ba4262076: Bug 51277: [DWARF] DW_AT_alignment incorrect 
when (authored by MaggieYi).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124006

Files:
  clang/lib/CodeGen/CGDebugInfo.cpp
  clang/test/CodeGenCXX/debug-info-struct-align.cpp


Index: clang/test/CodeGenCXX/debug-info-struct-align.cpp
===
--- /dev/null
+++ clang/test/CodeGenCXX/debug-info-struct-align.cpp
@@ -0,0 +1,27 @@
+//  Test for debug info related to DW_AT_alignment attribute in the struct 
type.
+// RUN: %clang_cc1 -dwarf-version=5 -debug-info-kind=standalone -S -emit-llvm 
%s -o - | FileCheck %s
+
+// CHECK-DAG: DICompositeType(tag: DW_TAG_structure_type, name: "MyType", 
{{.*}}, align: 32
+// CHECK-DAG: DICompositeType(tag: DW_TAG_structure_type, name: "MyType1", 
{{.*}}, align: 8
+// CHECK-DAG: DICompositeType(tag: DW_TAG_structure_type, name: "MyType2", 
{{.*}}, align: 8
+
+struct MyType {
+  int m;
+} __attribute__((aligned(1)));
+MyType mt;
+
+static_assert(alignof(MyType) == 4, "alignof MyType is wrong");
+
+struct MyType1 {
+  int m;
+} __attribute__((packed, aligned(1)));
+MyType1 mt1;
+
+static_assert(alignof(MyType1) == 1, "alignof MyType1 is wrong");
+
+struct MyType2 {
+  __attribute__((packed)) int m;
+} __attribute__((aligned(1)));
+MyType2 mt2;
+
+static_assert(alignof(MyType2) == 1, "alignof MyType2 is wrong");
Index: clang/lib/CodeGen/CGDebugInfo.cpp
===
--- clang/lib/CodeGen/CGDebugInfo.cpp
+++ clang/lib/CodeGen/CGDebugInfo.cpp
@@ -3561,7 +3561,11 @@
 return getOrCreateRecordFwdDecl(Ty, RDContext);
 
   uint64_t Size = CGM.getContext().getTypeSize(Ty);
-  auto Align = getDeclAlignIfRequired(D, CGM.getContext());
+  // __attribute__((aligned)) can increase or decrease alignment *except* on a
+  // struct or struct member, where it only increases  alignment unless 
'packed'
+  // is also specified. To handle this case, the `getTypeAlignIfRequired` needs
+  // to be used.
+  auto Align = getTypeAlignIfRequired(Ty, CGM.getContext());
 
   SmallString<256> Identifier = getTypeIdentifier(Ty, CGM, TheCU);
 


Index: clang/test/CodeGenCXX/debug-info-struct-align.cpp
===
--- /dev/null
+++ clang/test/CodeGenCXX/debug-info-struct-align.cpp
@@ -0,0 +1,27 @@
+//  Test for debug info related to DW_AT_alignment attribute in the struct type.
+// RUN: %clang_cc1 -dwarf-version=5 -debug-info-kind=standalone -S -emit-llvm %s -o - | FileCheck %s
+
+// CHECK-DAG: DICompositeType(tag: DW_TAG_structure_type, name: "MyType", {{.*}}, align: 32
+// CHECK-DAG: DICompositeType(tag: DW_TAG_structure_type, name: "MyType1", {{.*}}, align: 8
+// CHECK-DAG: DICompositeType(tag: DW_TAG_structure_type, name: "MyType2", {{.*}}, align: 8
+
+struct MyType {
+  int m;
+} __attribute__((aligned(1)));
+MyType mt;
+
+static_assert(alignof(MyType) == 4, "alignof MyType is wrong");
+
+struct MyType1 {
+  int m;
+} __attribute__((packed, aligned(1)));
+MyType1 mt1;
+
+static_assert(alignof(MyType1) == 1, "alignof MyType1 is wrong");
+
+struct MyType2 {
+  __attribute__((packed)) int m;
+} __attribute__((aligned(1)));
+MyType2 mt2;
+
+static_assert(alignof(MyType2) == 1, "alignof MyType2 is wrong");
Index: clang/lib/CodeGen/CGDebugInfo.cpp
===
--- clang/lib/CodeGen/CGDebugInfo.cpp
+++ clang/lib/CodeGen/CGDebugInfo.cpp
@@ -3561,7 +3561,11 @@
 return getOrCreateRecordFwdDecl(Ty, RDContext);
 
   uint64_t Size = CGM.getContext().getTypeSize(Ty);
-  auto Align = getDeclAlignIfRequired(D, CGM.getContext());
+  // __attribute__((aligned)) can increase or decrease alignment *except* on a
+  // struct or struct member, where it only increases  alignment unless 'packed'
+  // is also specified. To handle this case, the `getTypeAlignIfRequired` needs
+  // to be used.
+  auto Align = getTypeAlignIfRequired(Ty, CGM.getContext());
 
   SmallString<256> Identifier = getTypeIdentifier(Ty, CGM, TheCU);
 
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D123300: [Clang] Enable opaque pointers by default

2022-04-22 Thread Dawid Jurczak via Phabricator via cfe-commits
yurai007 added a comment.

Hi, unfortunately for some reason it doesn't play well with coroutines HALO. 
There is regression seen on Gor's Nishanov classical code snippet:  
https://godbolt.org/z/PKMxqq4Gr I'm checking IR to find out more.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D123300

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


[PATCH] D124057: [asan] Enable detect_stack_use_after_return=1 by default

2022-04-22 Thread Hans Wennborg via Phabricator via cfe-commits
hans accepted this revision.
hans added inline comments.



Comment at: clang/docs/ReleaseNotes.rst:175
   - Remove anonymous tag locations.
   - Beautify dump format, add indent for nested struct and struct members.
+- Previously disabled sanitizer options now enabled by default

vitalybuka wrote:
> vitalybuka wrote:
> > @hans PTAL 
> I'll move MSAN_OPTIONS into a separate patch if this format is OK
lgtm


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124057

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


[PATCH] D124250: [Serialization] write expr dependence bits as a single integer

2022-04-22 Thread Sam McCall via Phabricator via cfe-commits
sammccall created this revision.
sammccall added a reviewer: ilya-biryukov.
Herald added subscribers: usaxena95, kadircet.
Herald added a project: All.
sammccall requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

When exprs are written unabbreviated:

- these were encoded as 5 x vbr6 = 30 bits
- now they fit exactly into a one-chunk vbr = 6 bits

clangd --check=clangd/AST.cpp reports ~1% reduction in PCH size
(42826720->42474460)


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D124250

Files:
  clang/lib/Serialization/ASTReaderStmt.cpp
  clang/lib/Serialization/ASTWriterDecl.cpp
  clang/lib/Serialization/ASTWriterStmt.cpp

Index: clang/lib/Serialization/ASTWriterStmt.cpp
===
--- clang/lib/Serialization/ASTWriterStmt.cpp
+++ clang/lib/Serialization/ASTWriterStmt.cpp
@@ -543,11 +543,7 @@
 void ASTStmtWriter::VisitExpr(Expr *E) {
   VisitStmt(E);
   Record.AddTypeRef(E->getType());
-  Record.push_back(E->isTypeDependent());
-  Record.push_back(E->isValueDependent());
-  Record.push_back(E->isInstantiationDependent());
-  Record.push_back(E->containsUnexpandedParameterPack());
-  Record.push_back(E->containsErrors());
+  Record.push_back(E->getDependence());
   Record.push_back(E->getValueKind());
   Record.push_back(E->getObjectKind());
 }
Index: clang/lib/Serialization/ASTWriterDecl.cpp
===
--- clang/lib/Serialization/ASTWriterDecl.cpp
+++ clang/lib/Serialization/ASTWriterDecl.cpp
@@ -2294,11 +2294,7 @@
   //Stmt
   // Expr
   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Type
-  Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); //TypeDependent
-  Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); //ValueDependent
-  Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); //InstantiationDependent
-  Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); //UnexpandedParamPack
-  Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); //ContainsErrors
+  Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 5)); // Dependence
   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 3)); //GetValueKind
   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 3)); //GetObjectKind
   //DeclRefExpr
@@ -2318,11 +2314,7 @@
   //Stmt
   // Expr
   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Type
-  Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); //TypeDependent
-  Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); //ValueDependent
-  Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); //InstantiationDependent
-  Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); //UnexpandedParamPack
-  Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); //ContainsErrors
+  Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 5)); // Dependence
   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 3)); //GetValueKind
   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 3)); //GetObjectKind
   //Integer Literal
@@ -2337,11 +2329,7 @@
   //Stmt
   // Expr
   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Type
-  Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); //TypeDependent
-  Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); //ValueDependent
-  Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); //InstantiationDependent
-  Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); //UnexpandedParamPack
-  Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); //ContainsErrors
+  Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 5)); // Dependence
   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 3)); //GetValueKind
   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 3)); //GetObjectKind
   //Character Literal
@@ -2356,11 +2344,7 @@
   // Stmt
   // Expr
   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Type
-  Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); //TypeDependent
-  Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); //ValueDependent
-  Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); //InstantiationDependent
-  Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); //UnexpandedParamPack
-  Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); //ContainsErrors
+  Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 5)); // Dependence
   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 3)); //GetValueKind
   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 3)); //GetObjectKind
   // CastExpr
Index: clang/lib/Serialization/ASTReaderStmt.cpp
===
--- clang/lib/Serialization/ASTReaderStmt.cpp
+++ clang/lib/Serialization/ASTReaderStmt.cpp
@@ -107,8 +107,7 @@
 
 /// The number of record fields required for the Expr class
 /// itself.
-static const unsigned NumExprFields =
-NumStmtFields + llvm::BitWidth + 3;
+static const unsigned NumExprFields = NumStmtFields + 4;
 
 /// Read and initialize a Ex

[PATCH] D123300: [Clang] Enable opaque pointers by default

2022-04-22 Thread Markus Lavin via Phabricator via cfe-commits
markus added a comment.

We have run into a slight performance degrading issue with our downstream 
target. The situation is that we relay on the "consthoist" pass with option 
"-consthoist-gep=1" to factor out the common parts of GEP expresseions to 
reduce the number of symbol references.
For example with the old typed pointers we hade just before that pass

  store i16 100, i16* getelementptr inbounds ([8 x i16], [8 x i16]* 
@extUeValidatedTps, i16 0, i16 0), align 1
  store i16 101, i16* getelementptr inbounds ([8 x i16], [8 x i16]* 
@extUeValidatedTps, i16 0, i16 1), align 1
  store i16 102, i16* getelementptr inbounds ([8 x i16], [8 x i16]* 
@extUeValidatedTps, i16 0, i16 2), align 1

resulting in that the first GEP was factored out (with the other two based on 
it) so in total we had one symbol reference.

Now with opaque pointers we instead have

  store i16 100, ptr @extUeValidatedTps, align 1
  store i16 101, ptr getelementptr inbounds ([8 x i16], ptr @extUeValidatedTps, 
i16 0, i16 1), align 1
  store i16 102, ptr getelementptr inbounds ([8 x i16], ptr @extUeValidatedTps, 
i16 0, i16 2), align 1

again resulting in that the first GEP is factored out with the remaining GEPs 
based on it with offset adjusted. The result of this is that we have two symbol 
references.

So if this pass is to remain functionally equivalent then maybe 
ConstantHoisting.cpp should be taught to treat `ptr @extUeValidatedTps` the 
same way as zero indexed GEP of that symbol?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D123300

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


[PATCH] D124250: [Serialization] write expr dependence bits as a single integer

2022-04-22 Thread Sam McCall via Phabricator via cfe-commits
sammccall updated this revision to Diff 424443.
sammccall added a comment.

Don't hardcode 5 dependence bits in abbreviaions.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124250

Files:
  clang/lib/Serialization/ASTReaderStmt.cpp
  clang/lib/Serialization/ASTWriterDecl.cpp
  clang/lib/Serialization/ASTWriterStmt.cpp

Index: clang/lib/Serialization/ASTWriterStmt.cpp
===
--- clang/lib/Serialization/ASTWriterStmt.cpp
+++ clang/lib/Serialization/ASTWriterStmt.cpp
@@ -543,11 +543,7 @@
 void ASTStmtWriter::VisitExpr(Expr *E) {
   VisitStmt(E);
   Record.AddTypeRef(E->getType());
-  Record.push_back(E->isTypeDependent());
-  Record.push_back(E->isValueDependent());
-  Record.push_back(E->isInstantiationDependent());
-  Record.push_back(E->containsUnexpandedParameterPack());
-  Record.push_back(E->containsErrors());
+  Record.push_back(E->getDependence());
   Record.push_back(E->getValueKind());
   Record.push_back(E->getObjectKind());
 }
Index: clang/lib/Serialization/ASTWriterDecl.cpp
===
--- clang/lib/Serialization/ASTWriterDecl.cpp
+++ clang/lib/Serialization/ASTWriterDecl.cpp
@@ -2288,17 +2288,14 @@
   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
   DeclCXXMethodAbbrev = Stream.EmitAbbrev(std::move(Abv));
 
+  unsigned ExprDependenceBits = llvm::BitWidth;
   // Abbreviation for EXPR_DECL_REF
   Abv = std::make_shared();
   Abv->Add(BitCodeAbbrevOp(serialization::EXPR_DECL_REF));
   //Stmt
   // Expr
   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Type
-  Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); //TypeDependent
-  Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); //ValueDependent
-  Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); //InstantiationDependent
-  Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); //UnexpandedParamPack
-  Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); //ContainsErrors
+  Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, ExprDependenceBits));
   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 3)); //GetValueKind
   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 3)); //GetObjectKind
   //DeclRefExpr
@@ -2318,11 +2315,7 @@
   //Stmt
   // Expr
   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Type
-  Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); //TypeDependent
-  Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); //ValueDependent
-  Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); //InstantiationDependent
-  Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); //UnexpandedParamPack
-  Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); //ContainsErrors
+  Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, ExprDependenceBits));
   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 3)); //GetValueKind
   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 3)); //GetObjectKind
   //Integer Literal
@@ -2337,11 +2330,7 @@
   //Stmt
   // Expr
   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Type
-  Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); //TypeDependent
-  Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); //ValueDependent
-  Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); //InstantiationDependent
-  Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); //UnexpandedParamPack
-  Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); //ContainsErrors
+  Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, ExprDependenceBits));
   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 3)); //GetValueKind
   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 3)); //GetObjectKind
   //Character Literal
@@ -2356,11 +2345,7 @@
   // Stmt
   // Expr
   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Type
-  Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); //TypeDependent
-  Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); //ValueDependent
-  Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); //InstantiationDependent
-  Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); //UnexpandedParamPack
-  Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); //ContainsErrors
+  Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, ExprDependenceBits));
   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 3)); //GetValueKind
   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 3)); //GetObjectKind
   // CastExpr
Index: clang/lib/Serialization/ASTReaderStmt.cpp
===
--- clang/lib/Serialization/ASTReaderStmt.cpp
+++ clang/lib/Serialization/ASTReaderStmt.cpp
@@ -107,8 +107,7 @@
 
 /// The number of record fields required for the Expr class
 /// itself.
-static const unsigned NumExprFields =
-NumStmtFields + llvm::BitWidth + 3;
+static const unsigned NumExprFields = NumStmtFields + 4;
 
 /// Read and initial

[PATCH] D123300: [Clang] Enable opaque pointers by default

2022-04-22 Thread Nikita Popov via Phabricator via cfe-commits
nikic added a comment.

In D123300#3467278 , @markus wrote:

> We have run into a slight performance degrading issue with our downstream 
> target. The situation is that we relay on the "consthoist" pass with option 
> "-consthoist-gep=1" to factor out the common parts of GEP expresseions to 
> reduce the number of symbol references.
> For example with the old typed pointers we hade just before that pass
>
>   store i16 100, i16* getelementptr inbounds ([8 x i16], [8 x i16]* 
> @extUeValidatedTps, i16 0, i16 0), align 1
>   store i16 101, i16* getelementptr inbounds ([8 x i16], [8 x i16]* 
> @extUeValidatedTps, i16 0, i16 1), align 1
>   store i16 102, i16* getelementptr inbounds ([8 x i16], [8 x i16]* 
> @extUeValidatedTps, i16 0, i16 2), align 1
>
> resulting in that the first GEP was factored out (with the other two based on 
> it) so in total we had one symbol reference.
>
> Now with opaque pointers we instead have
>
>   store i16 100, ptr @extUeValidatedTps, align 1
>   store i16 101, ptr getelementptr inbounds ([8 x i16], ptr 
> @extUeValidatedTps, i16 0, i16 1), align 1
>   store i16 102, ptr getelementptr inbounds ([8 x i16], ptr 
> @extUeValidatedTps, i16 0, i16 2), align 1
>
> again resulting in that the first GEP is factored out with the remaining GEPs 
> based on it with offset adjusted. The result of this is that we have two 
> symbol references.
>
> So if this pass is to remain functionally equivalent then maybe 
> ConstantHoisting.cpp should be taught to treat `ptr @extUeValidatedTps` the 
> same way as zero indexed GEP of that symbol?

Sounds reasonable in general -- though isn't this a pre-existing problem you'd 
see if you simply had multiple loads from the same global (without any GEP)? 
Looking at the current ConstantHoist code, it doesn't seem to really consider 
the case where a global symbol address can be expensive, it only handles 
hoisting of large integer values.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D123300

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


[PATCH] D124127: Thread safety analysis: Pack CapabilityExpr using PointerIntPair (NFC)

2022-04-22 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!


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124127

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


[PATCH] D124128: Thread safety analysis: Store CapabilityExprs in ScopedLockableFactEntry (NFC)

2022-04-22 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 aside from a question (if we can't use `emplace_back()` the code is still 
fine).




Comment at: clang/lib/Analysis/ThreadSafety.cpp:911-919
+UnderlyingMutexes.push_back(UnderlyingCapability{M, UCK_Acquired});
   }
 
   void addExclusiveUnlock(const CapabilityExpr &M) {
-UnderlyingMutexes.emplace_back(M.sexpr(), UCK_ReleasedExclusive);
+UnderlyingMutexes.push_back(UnderlyingCapability{M, 
UCK_ReleasedExclusive});
   }
 

I think we can continue to use `emplace_back()` here, can't we?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124128

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


[PATCH] D124033: [NFC] Adding a note about the macro __FLT_EVAL_METHOD__

2022-04-22 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 the cleanup here!


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

https://reviews.llvm.org/D124033

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


[clang] 8dbc6b5 - Revert "[randstruct] Check final randomized layout ordering"

2022-04-22 Thread Nico Weber via cfe-commits

Author: Nico Weber
Date: 2022-04-22T08:27:32-04:00
New Revision: 8dbc6b560055ff5068ff45b550482ba62c36b5a5

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

LOG: Revert "[randstruct] Check final randomized layout ordering"

This reverts commit a7815d33bf8f955f2a1888abbccf974bd4858f79.
Test fails on Windows, see comments on https://reviews.llvm.org/D124199

Added: 


Modified: 
clang/lib/AST/Randstruct.cpp
clang/unittests/AST/RandstructTest.cpp

Removed: 




diff  --git a/clang/lib/AST/Randstruct.cpp b/clang/lib/AST/Randstruct.cpp
index 7d996fbadbe76..fadc727bbc4ed 100644
--- a/clang/lib/AST/Randstruct.cpp
+++ b/clang/lib/AST/Randstruct.cpp
@@ -150,14 +150,14 @@ void randomizeStructureLayoutImpl(const ASTContext 
&Context,
   if (CurrentBitfieldRun)
 Buckets.push_back(std::move(CurrentBitfieldRun));
 
-  llvm::shuffle(std::begin(Buckets), std::end(Buckets), RNG);
+  std::shuffle(std::begin(Buckets), std::end(Buckets), RNG);
 
   // Produce the new ordering of the elements from the Buckets.
   SmallVector FinalOrder;
   for (const std::unique_ptr &B : Buckets) {
 llvm::SmallVectorImpl &RandFields = B->fields();
 if (!B->isBitfieldRun())
-  llvm::shuffle(std::begin(RandFields), std::end(RandFields), RNG);
+  std::shuffle(std::begin(RandFields), std::end(RandFields), RNG);
 
 FinalOrder.insert(FinalOrder.end(), RandFields.begin(), RandFields.end());
   }

diff  --git a/clang/unittests/AST/RandstructTest.cpp 
b/clang/unittests/AST/RandstructTest.cpp
index 3c3f6a78390f9..134752fa7937e 100644
--- a/clang/unittests/AST/RandstructTest.cpp
+++ b/clang/unittests/AST/RandstructTest.cpp
@@ -159,9 +159,7 @@ TEST(RANDSTRUCT_TEST, UnmarkedStruct) {
   EXPECT_FALSE(AST->getDiagnostics().hasErrorOccurred());
 
   const RecordDecl *RD = getRecordDeclFromAST(AST->getASTContext(), "test");
-  const field_names Expected = {"bacon", "lettuce", "tomato", "mayonnaise"};
 
-  EXPECT_EQ(Expected, getFieldNamesFromRecord(RD));
   EXPECT_FALSE(RD->hasAttr());
   EXPECT_FALSE(RD->isRandomized());
 }
@@ -179,9 +177,7 @@ TEST(RANDSTRUCT_TEST, MarkedNoRandomize) {
   EXPECT_FALSE(AST->getDiagnostics().hasErrorOccurred());
 
   const RecordDecl *RD = getRecordDeclFromAST(AST->getASTContext(), "test");
-  const field_names Expected = {"bacon", "lettuce", "tomato", "mayonnaise"};
 
-  EXPECT_EQ(Expected, getFieldNamesFromRecord(RD));
   EXPECT_TRUE(RD->hasAttr());
   EXPECT_FALSE(RD->isRandomized());
 }
@@ -199,9 +195,7 @@ TEST(RANDSTRUCT_TEST, MarkedRandomize) {
   EXPECT_FALSE(AST->getDiagnostics().hasErrorOccurred());
 
   const RecordDecl *RD = getRecordDeclFromAST(AST->getASTContext(), "test");
-  const field_names Expected = {"lettuce", "bacon", "mayonnaise", "tomato"};
 
-  EXPECT_EQ(Expected, getFieldNamesFromRecord(RD));
   EXPECT_TRUE(RD->hasAttr());
   EXPECT_TRUE(RD->isRandomized());
 }
@@ -215,7 +209,8 @@ TEST(RANDSTRUCT_TEST, MismatchedAttrsDeclVsDef) {
 long long tomato;
 float mayonnaise;
 } __attribute__((no_randomize_layout));
-  )c", true);
+  )c",
+ true);
 
   EXPECT_FALSE(AST->getDiagnostics().hasErrorOccurred());
 
@@ -236,7 +231,8 @@ TEST(RANDSTRUCT_TEST, 
MismatchedAttrsRandomizeVsNoRandomize) {
 long long tomato;
 float mayonnaise;
 } __attribute__((randomize_layout)) __attribute__((no_randomize_layout));
-  )c", true);
+  )c",
+ true);
 
   EXPECT_TRUE(AST->getDiagnostics().hasErrorOccurred());
 
@@ -256,7 +252,8 @@ TEST(RANDSTRUCT_TEST, 
MismatchedAttrsNoRandomizeVsRandomize) {
 long long tomato;
 float mayonnaise;
 } __attribute__((no_randomize_layout)) __attribute__((randomize_layout));
-  )c", true);
+  )c",
+ true);
 
   EXPECT_TRUE(AST->getDiagnostics().hasErrorOccurred());
 
@@ -283,16 +280,14 @@ TEST(RANDSTRUCT_TEST, 
CheckAdjacentBitfieldsRemainAdjacentAfterRandomization) {
   EXPECT_FALSE(AST->getDiagnostics().hasErrorOccurred());
 
   const RecordDecl *RD = getRecordDeclFromAST(AST->getASTContext(), "test");
-  const field_names Expected = {
-  "a", "b", "c", "x", "y", "z" // x, y, z needs to be a subsequnce.
-  };
+  const field_names Actual = getFieldNamesFromRecord(RD);
+  const field_names Subseq = {"x", "y", "z"};
 
-  EXPECT_EQ(Expected, getFieldNamesFromRecord(RD));
   EXPECT_TRUE(RD->isRandomized());
+  EXPECT_TRUE(isSubsequence(Actual, Subseq));
 }
 
-// FIXME: Enable when fix for flexible arrays is submitted.
-TEST(RANDSTRUCT_TEST, 
DISABLED_CheckVariableLengthArrayMemberRemainsAtEndOfStructure) {
+TEST(RANDSTRUCT_TEST, CheckVariableLengthArrayMemberRemainsAtEndOfStructure) {
   std::unique_ptr AST = makeAST(R"c(
 struct test {
 int a;
@@ -305,9 

[PATCH] D124199: [randstruct] Check final randomized layout ordering

2022-04-22 Thread Nico Weber via Phabricator via cfe-commits
thakis added a comment.

Reverted in 8dbc6b560055ff5068ff45b550482ba62c36b5a5 
 for now.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124199

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


[PATCH] D124238: [AST] QualifiedTemplateName::getTemplateDecl cleanup.

2022-04-22 Thread Haojian Wu via Phabricator via cfe-commits
hokein updated this revision to Diff 424446.
hokein marked 2 inline comments as done.
hokein added a comment.

address comments


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124238

Files:
  clang/include/clang/AST/TemplateName.h
  clang/lib/AST/ItaniumMangle.cpp
  clang/lib/AST/TemplateName.cpp
  clang/lib/Sema/TreeTransform.h
  clang/tools/libclang/CIndex.cpp


Index: clang/tools/libclang/CIndex.cpp
===
--- clang/tools/libclang/CIndex.cpp
+++ clang/tools/libclang/CIndex.cpp
@@ -1443,6 +1443,7 @@
   switch (Name.getKind()) {
   case TemplateName::Template:
   case TemplateName::UsingTemplate:
+  case TemplateName::QualifiedTemplate: // FIXME: Visit nested-name-specifier.
 return Visit(MakeCursorTemplateRef(Name.getAsTemplateDecl(), Loc, TU));
 
   case TemplateName::OverloadedTemplate:
@@ -1460,11 +1461,6 @@
 // FIXME: Visit nested-name-specifier.
 return false;
 
-  case TemplateName::QualifiedTemplate:
-// FIXME: Visit nested-name-specifier.
-return Visit(MakeCursorTemplateRef(
-Name.getAsQualifiedTemplateName()->getTemplateDecl(), Loc, TU));
-
   case TemplateName::SubstTemplateTemplateParm:
 return Visit(MakeCursorTemplateRef(
 Name.getAsSubstTemplateTemplateParm()->getParameter(), Loc, TU));
Index: clang/lib/Sema/TreeTransform.h
===
--- clang/lib/Sema/TreeTransform.h
+++ clang/lib/Sema/TreeTransform.h
@@ -4280,7 +4280,7 @@
   NamedDecl *FirstQualifierInScope,
   bool AllowInjectedClassName) {
   if (QualifiedTemplateName *QTN = Name.getAsQualifiedTemplateName()) {
-TemplateDecl *Template = QTN->getTemplateDecl();
+TemplateDecl *Template = QTN->getUnderlyingTemplate().getAsTemplateDecl();
 assert(Template && "qualified template name must refer to a template");
 
 TemplateDecl *TransTemplate
Index: clang/lib/AST/TemplateName.cpp
===
--- clang/lib/AST/TemplateName.cpp
+++ clang/lib/AST/TemplateName.cpp
@@ -115,7 +115,7 @@
   }
 
   if (QualifiedTemplateName *QTN = getAsQualifiedTemplateName())
-return QTN->getTemplateDecl();
+return QTN->getUnderlyingTemplate().getAsTemplateDecl();
 
   if (SubstTemplateTemplateParmStorage *sub = getAsSubstTemplateTemplateParm())
 return sub->getReplacement().getAsTemplateDecl();
@@ -273,14 +273,15 @@
 if (Qual == Qualified::Fully &&
 getDependence() !=
 TemplateNameDependenceScope::DependentInstantiation) {
-  QTN->getTemplateDecl()->printQualifiedName(OS, Policy);
+  QTN->getUnderlyingTemplate().getAsTemplateDecl()->printQualifiedName(
+  OS, Policy);
   return;
 }
 if (Qual == Qualified::AsWritten)
   QTN->getQualifier()->print(OS, Policy);
 if (QTN->hasTemplateKeyword())
   OS << "template ";
-OS << *QTN->getTemplateDecl();
+OS << *QTN->getUnderlyingTemplate().getAsTemplateDecl();
   } else if (DependentTemplateName *DTN = getAsDependentTemplateName()) {
 if (Qual == Qualified::AsWritten && DTN->getQualifier())
   DTN->getQualifier()->print(OS, Policy);
Index: clang/lib/AST/ItaniumMangle.cpp
===
--- clang/lib/AST/ItaniumMangle.cpp
+++ clang/lib/AST/ItaniumMangle.cpp
@@ -2204,9 +2204,6 @@
 
   switch (TN.getKind()) {
   case TemplateName::QualifiedTemplate:
-TD = TN.getAsQualifiedTemplateName()->getTemplateDecl();
-goto HaveDecl;
-
   case TemplateName::UsingTemplate:
   case TemplateName::Template:
 TD = TN.getAsTemplateDecl();
Index: clang/include/clang/AST/TemplateName.h
===
--- clang/include/clang/AST/TemplateName.h
+++ clang/include/clang/AST/TemplateName.h
@@ -439,13 +439,6 @@
   /// Return the underlying template name.
   TemplateName getUnderlyingTemplate() const { return UnderlyingTemplate; }
 
-  /// The template declaration to which this qualified name
-  /// refers.
-  /// FIXME: remove this and use getUnderlyingTemplate() instead.
-  TemplateDecl *getTemplateDecl() const {
-return UnderlyingTemplate.getAsTemplateDecl();
-  }
-
   void Profile(llvm::FoldingSetNodeID &ID) {
 Profile(ID, getQualifier(), hasTemplateKeyword(), UnderlyingTemplate);
   }


Index: clang/tools/libclang/CIndex.cpp
===
--- clang/tools/libclang/CIndex.cpp
+++ clang/tools/libclang/CIndex.cpp
@@ -1443,6 +1443,7 @@
   switch (Name.getKind()) {
   case TemplateName::Template:
   case TemplateName::UsingTemplate:
+  case TemplateName::QualifiedTemplate: // FIXME: Visit nested-name-specifier.
 return Visit(MakeCursorTemplateRef(Name.getAsTemplateDecl(), Loc, TU));
 
   c

[clang] 864752c - [AST] QualifiedTemplateName::getTemplateDecl cleanup.

2022-04-22 Thread Haojian Wu via cfe-commits

Author: Haojian Wu
Date: 2022-04-22T14:28:48+02:00
New Revision: 864752cfeba445652b6ee0e040da366894a86c88

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

LOG: [AST] QualifiedTemplateName::getTemplateDecl cleanup.

This is a followup cleanup of 1234b1c6d8113d50beef5801be607ad1d502b2f7

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

Added: 


Modified: 
clang/include/clang/AST/TemplateName.h
clang/lib/AST/ItaniumMangle.cpp
clang/lib/AST/TemplateName.cpp
clang/lib/Sema/TreeTransform.h
clang/tools/libclang/CIndex.cpp

Removed: 




diff  --git a/clang/include/clang/AST/TemplateName.h 
b/clang/include/clang/AST/TemplateName.h
index b6f4332830c8f..ca85adac648b5 100644
--- a/clang/include/clang/AST/TemplateName.h
+++ b/clang/include/clang/AST/TemplateName.h
@@ -439,13 +439,6 @@ class QualifiedTemplateName : public llvm::FoldingSetNode {
   /// Return the underlying template name.
   TemplateName getUnderlyingTemplate() const { return UnderlyingTemplate; }
 
-  /// The template declaration to which this qualified name
-  /// refers.
-  /// FIXME: remove this and use getUnderlyingTemplate() instead.
-  TemplateDecl *getTemplateDecl() const {
-return UnderlyingTemplate.getAsTemplateDecl();
-  }
-
   void Profile(llvm::FoldingSetNodeID &ID) {
 Profile(ID, getQualifier(), hasTemplateKeyword(), UnderlyingTemplate);
   }

diff  --git a/clang/lib/AST/ItaniumMangle.cpp b/clang/lib/AST/ItaniumMangle.cpp
index adab764487c7b..75f072168858b 100644
--- a/clang/lib/AST/ItaniumMangle.cpp
+++ b/clang/lib/AST/ItaniumMangle.cpp
@@ -2204,9 +2204,6 @@ void CXXNameMangler::mangleType(TemplateName TN) {
 
   switch (TN.getKind()) {
   case TemplateName::QualifiedTemplate:
-TD = TN.getAsQualifiedTemplateName()->getTemplateDecl();
-goto HaveDecl;
-
   case TemplateName::UsingTemplate:
   case TemplateName::Template:
 TD = TN.getAsTemplateDecl();

diff  --git a/clang/lib/AST/TemplateName.cpp b/clang/lib/AST/TemplateName.cpp
index 8e32c9c6a6ad7..f0f64cd5a5168 100644
--- a/clang/lib/AST/TemplateName.cpp
+++ b/clang/lib/AST/TemplateName.cpp
@@ -115,7 +115,7 @@ TemplateDecl *TemplateName::getAsTemplateDecl() const {
   }
 
   if (QualifiedTemplateName *QTN = getAsQualifiedTemplateName())
-return QTN->getTemplateDecl();
+return QTN->getUnderlyingTemplate().getAsTemplateDecl();
 
   if (SubstTemplateTemplateParmStorage *sub = getAsSubstTemplateTemplateParm())
 return sub->getReplacement().getAsTemplateDecl();
@@ -273,14 +273,15 @@ void TemplateName::print(raw_ostream &OS, const 
PrintingPolicy &Policy,
 if (Qual == Qualified::Fully &&
 getDependence() !=
 TemplateNameDependenceScope::DependentInstantiation) {
-  QTN->getTemplateDecl()->printQualifiedName(OS, Policy);
+  QTN->getUnderlyingTemplate().getAsTemplateDecl()->printQualifiedName(
+  OS, Policy);
   return;
 }
 if (Qual == Qualified::AsWritten)
   QTN->getQualifier()->print(OS, Policy);
 if (QTN->hasTemplateKeyword())
   OS << "template ";
-OS << *QTN->getTemplateDecl();
+OS << *QTN->getUnderlyingTemplate().getAsTemplateDecl();
   } else if (DependentTemplateName *DTN = getAsDependentTemplateName()) {
 if (Qual == Qualified::AsWritten && DTN->getQualifier())
   DTN->getQualifier()->print(OS, Policy);

diff  --git a/clang/lib/Sema/TreeTransform.h b/clang/lib/Sema/TreeTransform.h
index 282163cf4c923..aef757efc9e71 100644
--- a/clang/lib/Sema/TreeTransform.h
+++ b/clang/lib/Sema/TreeTransform.h
@@ -4280,7 +4280,7 @@ 
TreeTransform::TransformTemplateName(CXXScopeSpec &SS,
   NamedDecl *FirstQualifierInScope,
   bool AllowInjectedClassName) {
   if (QualifiedTemplateName *QTN = Name.getAsQualifiedTemplateName()) {
-TemplateDecl *Template = QTN->getTemplateDecl();
+TemplateDecl *Template = QTN->getUnderlyingTemplate().getAsTemplateDecl();
 assert(Template && "qualified template name must refer to a template");
 
 TemplateDecl *TransTemplate

diff  --git a/clang/tools/libclang/CIndex.cpp b/clang/tools/libclang/CIndex.cpp
index fc6177036b08a..6df673fec4ada 100644
--- a/clang/tools/libclang/CIndex.cpp
+++ b/clang/tools/libclang/CIndex.cpp
@@ -1443,6 +1443,7 @@ bool CursorVisitor::VisitTemplateName(TemplateName Name, 
SourceLocation Loc) {
   switch (Name.getKind()) {
   case TemplateName::Template:
   case TemplateName::UsingTemplate:
+  case TemplateName::QualifiedTemplate: // FIXME: Visit nested-name-specifier.
 return Visit(MakeCursorTemplateRef(Name.getAsTemplateDecl(), Loc, TU));
 
   case TemplateName::OverloadedTemplate:
@@ -1460,11 +1461,6 @@ bool CursorVisitor::VisitTemplateName(TemplateName Name, 
SourceLocation L

[PATCH] D124238: [AST] QualifiedTemplateName::getTemplateDecl cleanup.

2022-04-22 Thread Haojian Wu via Phabricator via cfe-commits
This revision was landed with ongoing or failed builds.
This revision was automatically updated to reflect the committed changes.
Closed by commit rG864752cfeba4: [AST] QualifiedTemplateName::getTemplateDecl 
cleanup. (authored by hokein).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124238

Files:
  clang/include/clang/AST/TemplateName.h
  clang/lib/AST/ItaniumMangle.cpp
  clang/lib/AST/TemplateName.cpp
  clang/lib/Sema/TreeTransform.h
  clang/tools/libclang/CIndex.cpp


Index: clang/tools/libclang/CIndex.cpp
===
--- clang/tools/libclang/CIndex.cpp
+++ clang/tools/libclang/CIndex.cpp
@@ -1443,6 +1443,7 @@
   switch (Name.getKind()) {
   case TemplateName::Template:
   case TemplateName::UsingTemplate:
+  case TemplateName::QualifiedTemplate: // FIXME: Visit nested-name-specifier.
 return Visit(MakeCursorTemplateRef(Name.getAsTemplateDecl(), Loc, TU));
 
   case TemplateName::OverloadedTemplate:
@@ -1460,11 +1461,6 @@
 // FIXME: Visit nested-name-specifier.
 return false;
 
-  case TemplateName::QualifiedTemplate:
-// FIXME: Visit nested-name-specifier.
-return Visit(MakeCursorTemplateRef(
-Name.getAsQualifiedTemplateName()->getTemplateDecl(), Loc, TU));
-
   case TemplateName::SubstTemplateTemplateParm:
 return Visit(MakeCursorTemplateRef(
 Name.getAsSubstTemplateTemplateParm()->getParameter(), Loc, TU));
Index: clang/lib/Sema/TreeTransform.h
===
--- clang/lib/Sema/TreeTransform.h
+++ clang/lib/Sema/TreeTransform.h
@@ -4280,7 +4280,7 @@
   NamedDecl *FirstQualifierInScope,
   bool AllowInjectedClassName) {
   if (QualifiedTemplateName *QTN = Name.getAsQualifiedTemplateName()) {
-TemplateDecl *Template = QTN->getTemplateDecl();
+TemplateDecl *Template = QTN->getUnderlyingTemplate().getAsTemplateDecl();
 assert(Template && "qualified template name must refer to a template");
 
 TemplateDecl *TransTemplate
Index: clang/lib/AST/TemplateName.cpp
===
--- clang/lib/AST/TemplateName.cpp
+++ clang/lib/AST/TemplateName.cpp
@@ -115,7 +115,7 @@
   }
 
   if (QualifiedTemplateName *QTN = getAsQualifiedTemplateName())
-return QTN->getTemplateDecl();
+return QTN->getUnderlyingTemplate().getAsTemplateDecl();
 
   if (SubstTemplateTemplateParmStorage *sub = getAsSubstTemplateTemplateParm())
 return sub->getReplacement().getAsTemplateDecl();
@@ -273,14 +273,15 @@
 if (Qual == Qualified::Fully &&
 getDependence() !=
 TemplateNameDependenceScope::DependentInstantiation) {
-  QTN->getTemplateDecl()->printQualifiedName(OS, Policy);
+  QTN->getUnderlyingTemplate().getAsTemplateDecl()->printQualifiedName(
+  OS, Policy);
   return;
 }
 if (Qual == Qualified::AsWritten)
   QTN->getQualifier()->print(OS, Policy);
 if (QTN->hasTemplateKeyword())
   OS << "template ";
-OS << *QTN->getTemplateDecl();
+OS << *QTN->getUnderlyingTemplate().getAsTemplateDecl();
   } else if (DependentTemplateName *DTN = getAsDependentTemplateName()) {
 if (Qual == Qualified::AsWritten && DTN->getQualifier())
   DTN->getQualifier()->print(OS, Policy);
Index: clang/lib/AST/ItaniumMangle.cpp
===
--- clang/lib/AST/ItaniumMangle.cpp
+++ clang/lib/AST/ItaniumMangle.cpp
@@ -2204,9 +2204,6 @@
 
   switch (TN.getKind()) {
   case TemplateName::QualifiedTemplate:
-TD = TN.getAsQualifiedTemplateName()->getTemplateDecl();
-goto HaveDecl;
-
   case TemplateName::UsingTemplate:
   case TemplateName::Template:
 TD = TN.getAsTemplateDecl();
Index: clang/include/clang/AST/TemplateName.h
===
--- clang/include/clang/AST/TemplateName.h
+++ clang/include/clang/AST/TemplateName.h
@@ -439,13 +439,6 @@
   /// Return the underlying template name.
   TemplateName getUnderlyingTemplate() const { return UnderlyingTemplate; }
 
-  /// The template declaration to which this qualified name
-  /// refers.
-  /// FIXME: remove this and use getUnderlyingTemplate() instead.
-  TemplateDecl *getTemplateDecl() const {
-return UnderlyingTemplate.getAsTemplateDecl();
-  }
-
   void Profile(llvm::FoldingSetNodeID &ID) {
 Profile(ID, getQualifier(), hasTemplateKeyword(), UnderlyingTemplate);
   }


Index: clang/tools/libclang/CIndex.cpp
===
--- clang/tools/libclang/CIndex.cpp
+++ clang/tools/libclang/CIndex.cpp
@@ -1443,6 +1443,7 @@
   switch (Name.getKind()) {
   case TemplateName::Template:
   case TemplateName::UsingTemplate:
+  case TemplateName::QualifiedTemplate: // FIXME: V

[PATCH] D121868: [cc1as] Add support for emitting the build version load command for -darwin-target-variant

2022-04-22 Thread Nico Weber via Phabricator via cfe-commits
thakis added a comment.

Thanks!




Comment at: clang/test/Misc/cc1as-darwin-target-variant-triple.s:2
+// Run cc1as using darwin-target-variant-triple
+// RUN: %clang -cc1as -triple x86_64-apple-macos10.9 
-darwin-target-variant-triple x86_64-apple-ios13.1-macabi -filetype obj %s -o - 
\
+// RUN: | llvm-readobj --file-headers --macho-version-min - \

bc-lee wrote:
> thakis wrote:
> > bc-lee wrote:
> > > MaskRay wrote:
> > > > `-filetype obj` on the `%clang -cc1as` line seems weird.
> > > Without this, I cannot create object file and validate it using 
> > > `llvm-readobj`.
> > If you use `emit-obj` I think this test needs a `REQUIRES: 
> > x86-registered-target`.
> > 
> > I'm not sure if piping binary data works on Windows – it might have stdout 
> > in text mode, which will do some byte replacements.
> A search for `-o -.*\n.*RUN.*llvm-readobj` in the LLVM codebase suggests that 
> there are already several tests using that pattern. Does that really matter?
Well, if it works, it doesn't matter :)

I'll land this and the bots can tell us if it works.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D121868

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


[PATCH] D124220: [OpenMP] Add options to only compile the host or device when offloading

2022-04-22 Thread Joseph Huber via Phabricator via cfe-commits
jhuber6 updated this revision to Diff 424449.
jhuber6 added a comment.

Moving some stuff.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124220

Files:
  clang/include/clang/Driver/Options.td
  clang/lib/Driver/Driver.cpp
  clang/test/Driver/openmp-offload-gpu-new.c

Index: clang/test/Driver/openmp-offload-gpu-new.c
===
--- clang/test/Driver/openmp-offload-gpu-new.c
+++ clang/test/Driver/openmp-offload-gpu-new.c
@@ -3,7 +3,6 @@
 ///
 
 // REQUIRES: x86-registered-target
-// REQUIRES: powerpc-registered-target
 // REQUIRES: nvptx-registered-target
 // REQUIRES: amdgpu-registered-target
 
@@ -50,3 +49,18 @@
 // RUN:   | FileCheck -check-prefix=DRIVER_EMBEDDING %s
 
 // DRIVER_EMBEDDING: -fembed-offload-object=[[CUBIN:.*\.cubin]],openmp,nvptx64-nvidia-cuda,sm_70
+
+// RUN:   %clang -### --target=x86_64-unknown-linux-gnu -ccc-print-bindings -fopenmp -fopenmp-targets=nvptx64-nvidia-cuda \
+// RUN: -foffload-host-only -nogpulib %s 2>&1 | FileCheck %s --check-prefix=CHECK-HOST-ONLY
+// CHECK-HOST-ONLY: "x86_64-unknown-linux-gnu" - "clang", inputs: ["[[INPUT:.*]]"], output: "[[OUTPUT:.*]]"
+// CHECK-HOST-ONLY: "x86_64-unknown-linux-gnu" - "Offload::Linker", inputs: ["[[OUTPUT]]"], output: "a.out"
+
+// RUN:   %clang -### --target=x86_64-unknown-linux-gnu -ccc-print-bindings -fopenmp -fopenmp-targets=nvptx64-nvidia-cuda \
+// RUN: -foffload-device-only -nogpulib %s 2>&1 | FileCheck %s --check-prefix=CHECK-DEVICE-ONLY
+// CHECK-DEVICE-ONLY: "x86_64-unknown-linux-gnu" - "clang", inputs: ["[[INPUT:.*]]"], output: "[[HOST_BC:.*]]"
+// CHECK-DEVICE-ONLY: "nvptx64-nvidia-cuda" - "clang", inputs: ["[[INPUT]]", "[[HOST_BC]]"], output: "[[DEVICE_ASM:.*]]"
+// CHECK-DEVICE-ONLY: "nvptx64-nvidia-cuda" - "NVPTX::Assembler", inputs: ["[[DEVICE_ASM]]"], output: "{{.*}}-openmp-nvptx64-nvidia-cuda.o"
+
+// RUN:   %clang -### --target=x86_64-unknown-linux-gnu -ccc-print-bindings -fopenmp -fopenmp-targets=nvptx64-nvidia-cuda \
+// RUN: -foffload-device-only -E -nogpulib %s 2>&1 | FileCheck %s --check-prefix=CHECK-DEVICE-ONLY-PP
+// CHECK-DEVICE-ONLY-PP: "nvptx64-nvidia-cuda" - "clang", inputs: ["[[INPUT:.*]]"], output: "-"
Index: clang/lib/Driver/Driver.cpp
===
--- clang/lib/Driver/Driver.cpp
+++ clang/lib/Driver/Driver.cpp
@@ -3983,10 +3983,10 @@
 break;
   }
 
-  // Try to build the offloading actions and add the result as a dependency
-  // to the host.
-  if (UseNewOffloadingDriver)
-Current = BuildOffloadingActions(C, Args, I, Current);
+  // We should stop if we only want to compile for the device.
+  if (Args.hasArg(options::OPT_foffload_device_only) &&
+  isa(Current))
+break;
 
   // FIXME: Should we include any prior module file outputs as inputs of
   // later actions in the same command line?
@@ -4011,6 +4011,11 @@
 if (OffloadBuilder.addHostDependenceToDeviceActions(Current, InputArg))
   break;
 
+  // Try to build the offloading actions and add the result as a dependency
+  // to the host.
+  if (UseNewOffloadingDriver)
+Current = BuildOffloadingActions(C, Args, I, Current);
+
   if (Current->getType() == types::TY_Nothing)
 break;
 }
@@ -4143,14 +4148,19 @@
llvm::opt::DerivedArgList &Args,
const InputTy &Input,
Action *HostAction) const {
-  if (!isa(HostAction))
+  if (Args.hasArg(options::OPT_foffload_host_only))
 return HostAction;
 
-  OffloadAction::DeviceDependences DDeps;
-
   types::ID InputType = Input.first;
   const Arg *InputArg = Input.second;
 
+  auto PL = types::getCompilationPhases(*this, Args, InputType);
+
+  if (!isa(HostAction) && PL.back() != phases::Preprocess)
+return HostAction;
+
+  OffloadAction::DeviceDependences DDeps;
+
   const Action::OffloadKind OffloadKinds[] = {Action::OFK_OpenMP};
 
   for (Action::OffloadKind Kind : OffloadKinds) {
@@ -4170,8 +4180,6 @@
 if (DeviceActions.empty())
   return HostAction;
 
-auto PL = types::getCompilationPhases(*this, Args, InputType);
-
 for (phases::ID Phase : PL) {
   if (Phase == phases::Link) {
 assert(Phase == PL.back() && "linking must be final compilation step.");
@@ -4182,7 +4190,8 @@
   for (Action *&A : DeviceActions) {
 A = ConstructPhaseAction(C, Args, Phase, A, Kind);
 
-if (isa(A) && Kind == Action::OFK_OpenMP) {
+if (isa(A) && isa(HostAction) &&
+Kind == Action::OFK_OpenMP) {
   HostAction->setCannotBeCollapsedWithNextDependentAction();
   OffloadAction::HostDependence HDep(
   *HostAction, *C.getSingleOffloadToolChain(),
@@ -4202,6 +4211,10 @@
 }
   }
 
+  if (Args.hasArg

[clang] f693280 - [cc1as] Add support for emitting the build version load command for -darwin-target-variant

2022-04-22 Thread Nico Weber via cfe-commits

Author: Byoungchan Lee
Date: 2022-04-22T08:38:07-04:00
New Revision: f69328049e9e7fde7a314de785c76c1b93e069b2

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

LOG: [cc1as] Add support for emitting the build version load command for 
-darwin-target-variant

This patch extends cc1as to export the build version load command with
LC_VERSION_MIN_MACOSX.
This is especially important for Mac Catalyst as Mac Catalyst uses
the MacOS's compiler rt built-ins.

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

Added: 
clang/test/Misc/cc1as-darwin-target-variant-triple.s

Modified: 
clang/include/clang/Driver/Options.td
clang/include/clang/Driver/ToolChain.h
clang/lib/Driver/ToolChains/Clang.cpp
clang/lib/Driver/ToolChains/Darwin.h
clang/tools/driver/cc1as_main.cpp

Removed: 




diff  --git a/clang/include/clang/Driver/Options.td 
b/clang/include/clang/Driver/Options.td
index bb870dd8bb26c..8c013e3fe5b19 100644
--- a/clang/include/clang/Driver/Options.td
+++ b/clang/include/clang/Driver/Options.td
@@ -4854,16 +4854,21 @@ def target_abi : Separate<["-"], "target-abi">,
   MarshallingInfoString>;
 def target_sdk_version_EQ : Joined<["-"], "target-sdk-version=">,
   HelpText<"The version of target SDK used for compilation">;
-def darwin_target_variant_triple : Separate<["-"], 
"darwin-target-variant-triple">,
-  HelpText<"Specify the darwin target variant triple">,
-  MarshallingInfoString>,
-  Normalizer<"normalizeTriple">;
 def darwin_target_variant_sdk_version_EQ : Joined<["-"],
   "darwin-target-variant-sdk-version=">,
   HelpText<"The version of darwin target variant SDK used for compilation">;
 
 } // let Flags = [CC1Option, CC1AsOption, NoDriverOption]
 
+let Flags = [CC1Option, CC1AsOption] in {
+
+def darwin_target_variant_triple : Separate<["-"], 
"darwin-target-variant-triple">,
+  HelpText<"Specify the darwin target variant triple">,
+  MarshallingInfoString>,
+  Normalizer<"normalizeTriple">;
+
+} // let Flags = [CC1Option, CC1AsOption]
+
 
//===--===//
 // Target Options (cc1 + cc1as + fc1)
 
//===--===//

diff  --git a/clang/include/clang/Driver/ToolChain.h 
b/clang/include/clang/Driver/ToolChain.h
index adf1753e8d3a6..a3da1db2f15ef 100644
--- a/clang/include/clang/Driver/ToolChain.h
+++ b/clang/include/clang/Driver/ToolChain.h
@@ -717,6 +717,10 @@ class ToolChain {
 return llvm::DenormalMode::getIEEE();
   }
 
+  virtual Optional getTargetVariantTriple() const {
+return llvm::None;
+  }
+
   // We want to expand the shortened versions of the triples passed in to
   // the values used for the bitcode libraries.
   static llvm::Triple getOpenMPTriple(StringRef TripleStr) {

diff  --git a/clang/lib/Driver/ToolChains/Clang.cpp 
b/clang/lib/Driver/ToolChains/Clang.cpp
index 28910d4bd4321..ddc9559f0d950 100644
--- a/clang/lib/Driver/ToolChains/Clang.cpp
+++ b/clang/lib/Driver/ToolChains/Clang.cpp
@@ -7721,6 +7721,8 @@ void ClangAs::ConstructJob(Compilation &C, const 
JobAction &JA,
 
   const llvm::Triple &Triple = getToolChain().getEffectiveTriple();
   const std::string &TripleStr = Triple.getTriple();
+  const Optional TargetVariantTriple =
+  getToolChain().getTargetVariantTriple();
   const auto &D = getToolChain().getDriver();
 
   // Don't warn about "clang -w -c foo.s"
@@ -7738,6 +7740,10 @@ void ClangAs::ConstructJob(Compilation &C, const 
JobAction &JA,
   // Add the "effective" target triple.
   CmdArgs.push_back("-triple");
   CmdArgs.push_back(Args.MakeArgString(TripleStr));
+  if (TargetVariantTriple) {
+CmdArgs.push_back("-darwin-target-variant-triple");
+CmdArgs.push_back(Args.MakeArgString(TargetVariantTriple->getTriple()));
+  }
 
   // Set the output mode, we currently only expect to be used as a real
   // assembler.

diff  --git a/clang/lib/Driver/ToolChains/Darwin.h 
b/clang/lib/Driver/ToolChains/Darwin.h
index a5f8e45640b5a..a622024b79930 100644
--- a/clang/lib/Driver/ToolChains/Darwin.h
+++ b/clang/lib/Driver/ToolChains/Darwin.h
@@ -489,6 +489,12 @@ class LLVM_LIBRARY_VISIBILITY Darwin : public MachO {
 : TargetVersion) < VersionTuple(V0, V1, V2);
   }
 
+  /// Returns the darwin target variant triple, the variant of the deployment
+  /// target for which the code is being compiled.
+  Optional getTargetVariantTriple() const override {
+return TargetVariantTriple;
+  }
+
 protected:
   /// Return true if c++17 aligned allocation/deallocation functions are not
   /// implemented in the c++ standard library of the deployment target we are

diff  --git a/clang/test/Misc/cc1as-darwin-target-variant-triple.s 
b/clang/test/Misc/cc1as-darwin-target-variant-triple.s
new 

[PATCH] D121868: [cc1as] Add support for emitting the build version load command for -darwin-target-variant

2022-04-22 Thread Nico Weber via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rGf69328049e9e: [cc1as] Add support for emitting the build 
version load command for -darwin… (authored by bc-lee, committed by thakis).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D121868

Files:
  clang/include/clang/Driver/Options.td
  clang/include/clang/Driver/ToolChain.h
  clang/lib/Driver/ToolChains/Clang.cpp
  clang/lib/Driver/ToolChains/Darwin.h
  clang/test/Misc/cc1as-darwin-target-variant-triple.s
  clang/tools/driver/cc1as_main.cpp

Index: clang/tools/driver/cc1as_main.cpp
===
--- clang/tools/driver/cc1as_main.cpp
+++ clang/tools/driver/cc1as_main.cpp
@@ -144,6 +144,9 @@
   /// otherwise.
   std::string TargetABI;
 
+  /// Darwin target variant triple, the variant of the deployment target
+  /// for which the code is being compiled.
+  llvm::Optional DarwinTargetVariantTriple;
   /// @}
 
 public:
@@ -209,6 +212,9 @@
 
   // Target Options
   Opts.Triple = llvm::Triple::normalize(Args.getLastArgValue(OPT_triple));
+  if (Arg *A = Args.getLastArg(options::OPT_darwin_target_variant_triple))
+Opts.DarwinTargetVariantTriple = llvm::Triple(A->getValue());
+
   Opts.CPU = std::string(Args.getLastArgValue(OPT_target_cpu));
   Opts.Features = Args.getAllArgValues(OPT_target_feature);
 
@@ -407,6 +413,8 @@
   // MCObjectFileInfo needs a MCContext reference in order to initialize itself.
   std::unique_ptr MOFI(
   TheTarget->createMCObjectFileInfo(Ctx, PIC));
+  if (Opts.DarwinTargetVariantTriple)
+MOFI->setDarwinTargetVariantTriple(*Opts.DarwinTargetVariantTriple);
   Ctx.setObjectFileInfo(MOFI.get());
 
   if (Opts.SaveTemporaryLabels)
Index: clang/test/Misc/cc1as-darwin-target-variant-triple.s
===
--- /dev/null
+++ clang/test/Misc/cc1as-darwin-target-variant-triple.s
@@ -0,0 +1,34 @@
+// Run cc1as using darwin-target-variant-triple
+// REQUIRES: x86-registered-target
+// RUN: %clang -cc1as -triple x86_64-apple-macos10.9 -darwin-target-variant-triple x86_64-apple-ios13.1-macabi -filetype obj %s -o - \
+// RUN: | llvm-readobj --file-headers --macho-version-min - \
+// RUN: | FileCheck --check-prefix=CHECK %s
+
+// CHECK: File: 
+// CHECK-NEXT: Format: Mach-O 64-bit x86-64
+// CHECK-NEXT: Arch: x86_64
+// CHECK-NEXT: AddressSize: 64bit
+// CHECK-NEXT: MachHeader {
+// CHECK-NEXT:   Magic: Magic64 (0xFEEDFACF)
+// CHECK-NEXT:   CpuType: X86-64 (0x107)
+// CHECK-NEXT:   CpuSubType: CPU_SUBTYPE_X86_64_ALL (0x3)
+// CHECK-NEXT:   FileType: Relocatable (0x1)
+// CHECK-NEXT:   NumOfLoadCommands: 3
+// CHECK-NEXT:   SizeOfLoadCommands: 192
+// CHECK-NEXT:   Flags [ (0x0)
+// CHECK-NEXT:   ]
+// CHECK-NEXT:   Reserved: 0x0
+// CHECK-NEXT: }
+// CHECK-NEXT: MinVersion {
+// CHECK-NEXT:   Cmd: LC_VERSION_MIN_MACOSX
+// CHECK-NEXT:   Size: 16
+// CHECK-NEXT:   Version: 10.9
+// CHECK-NEXT:   SDK: n/a
+// CHECK-NEXT: }
+// CHECK-NEXT: MinVersion {
+// CHECK-NEXT:   Cmd: LC_BUILD_VERSION
+// CHECK-NEXT:   Size: 24
+// CHECK-NEXT:   Platform: macCatalyst
+// CHECK-NEXT:   Version: 13.1
+// CHECK-NEXT:   SDK: n/a
+// CHECK-NEXT: }
Index: clang/lib/Driver/ToolChains/Darwin.h
===
--- clang/lib/Driver/ToolChains/Darwin.h
+++ clang/lib/Driver/ToolChains/Darwin.h
@@ -489,6 +489,12 @@
 : TargetVersion) < VersionTuple(V0, V1, V2);
   }
 
+  /// Returns the darwin target variant triple, the variant of the deployment
+  /// target for which the code is being compiled.
+  Optional getTargetVariantTriple() const override {
+return TargetVariantTriple;
+  }
+
 protected:
   /// Return true if c++17 aligned allocation/deallocation functions are not
   /// implemented in the c++ standard library of the deployment target we are
Index: clang/lib/Driver/ToolChains/Clang.cpp
===
--- clang/lib/Driver/ToolChains/Clang.cpp
+++ clang/lib/Driver/ToolChains/Clang.cpp
@@ -7721,6 +7721,8 @@
 
   const llvm::Triple &Triple = getToolChain().getEffectiveTriple();
   const std::string &TripleStr = Triple.getTriple();
+  const Optional TargetVariantTriple =
+  getToolChain().getTargetVariantTriple();
   const auto &D = getToolChain().getDriver();
 
   // Don't warn about "clang -w -c foo.s"
@@ -7738,6 +7740,10 @@
   // Add the "effective" target triple.
   CmdArgs.push_back("-triple");
   CmdArgs.push_back(Args.MakeArgString(TripleStr));
+  if (TargetVariantTriple) {
+CmdArgs.push_back("-darwin-target-variant-triple");
+CmdArgs.push_back(Args.MakeArgString(TargetVariantTriple->getTriple()));
+  }
 
   // Set the output mode, we currently only expect to be used as a real
   // assembler.
Index: clang/include/clang/Driver/ToolChain.h
===

[PATCH] D124253: [Clang][OpenMP] Fix the issue that one temp cubin file is not removed after compilation

2022-04-22 Thread Shilei Tian via Phabricator via cfe-commits
tianshilei1992 created this revision.
tianshilei1992 added reviewers: jdoerfert, jhuber6.
Herald added subscribers: guansong, yaxunl.
Herald added a project: All.
tianshilei1992 requested review of this revision.
Herald added subscribers: cfe-commits, sstefan1.
Herald added a project: clang.

The output of `assemble` is not added into `TempFiles`.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D124253

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


Index: clang/tools/clang-linker-wrapper/ClangLinkerWrapper.cpp
===
--- clang/tools/clang-linker-wrapper/ClangLinkerWrapper.cpp
+++ clang/tools/clang-linker-wrapper/ClangLinkerWrapper.cpp
@@ -1093,6 +1093,7 @@
   if (!FileOrErr)
 return FileOrErr.takeError();
   File = *FileOrErr;
+  TempFiles.push_back(static_cast(File));
 }
   }
 


Index: clang/tools/clang-linker-wrapper/ClangLinkerWrapper.cpp
===
--- clang/tools/clang-linker-wrapper/ClangLinkerWrapper.cpp
+++ clang/tools/clang-linker-wrapper/ClangLinkerWrapper.cpp
@@ -1093,6 +1093,7 @@
   if (!FileOrErr)
 return FileOrErr.takeError();
   File = *FileOrErr;
+  TempFiles.push_back(static_cast(File));
 }
   }
 
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D124253: [Clang][OpenMP] Fix the issue that one temp cubin file is not removed after compilation

2022-04-22 Thread Joseph Huber via Phabricator via cfe-commits
jhuber6 added a comment.

Is this really the cause? `nvptx::assemble` should call `createOutputFile` 
which makes a temp file to output to that is added to `TempFiles`.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124253

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


[PATCH] D124253: [Clang][OpenMP] Fix the issue that one temp cubin file is not removed after compilation

2022-04-22 Thread Shilei Tian via Phabricator via cfe-commits
tianshilei1992 added a comment.

In D124253#3467375 , @jhuber6 wrote:

> Is this really the cause? `nvptx::assemble` should call `createOutputFile` 
> which makes a temp file to output to that is added to `TempFiles`.

Hmm, that's interesting. After adding that line, the temp file gets removed.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124253

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


[PATCH] D124240: [clangd][NFC] Reduce memory usage while building dex

2022-04-22 Thread Kadir Cetinkaya via Phabricator via cfe-commits
kadircet added inline comments.



Comment at: clang-tools-extra/clangd/index/dex/Dex.cpp:89
+  Result.try_emplace(Token(Token::Kind::Trigram, E.first.str()),
+ std::move(E.second));
+TrigramDocs.clear();

sammccall wrote:
> the move here does nothing, we're passing as ArrayRef
> 
> did you want to clear the map values (vectors) as you went, too?
> 
> (this gets a bit verbose, but you could pull out a function template since 
> all 4 cases are so regular)
> did you want to clear the map values (vectors) as you went, too?

yes that's the idea. would you prefer an explicit destructor call?

> (this gets a bit verbose, but you could pull out a function template since 
> all 4 cases are so regular)

the problem is 1 of these is a densemap, other three is a stringmap, and onther 
is a vector. densemap and the stringmap doesn't really go together because 
there's no common method to get the key (densemap has `first` as a field, or 
`getFirst()` as a method. stringmap has `first()` or `getKey()` as methods :/).
happy to move out just the three of them into a helper like:
```
buildPostingList(StringMap<..>, TokenKind, Out);
```
if you think that's still helpful (that way we can also get rid of the calls to 
clear since we can just move the maps into the function arguments).


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124240

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


[PATCH] D124199: [randstruct] Check final randomized layout ordering

2022-04-22 Thread David Spickett via Phabricator via cfe-commits
DavidSpickett added a comment.

We (Linaro) also got the same failure: 
https://lab.llvm.org/buildbot/#/builders/186/builds/5626


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124199

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


[PATCH] D124255: [libc++] Make check_assertion.h use setjmp/longjmp instead of fork

2022-04-22 Thread John Brawn via Phabricator via cfe-commits
john.brawn created this revision.
john.brawn added reviewers: ldionne, Mordante, michaelplatings.
Herald added a project: All.
john.brawn requested review of this revision.
Herald added a project: libc++.
Herald added a subscriber: libcxx-commits.
Herald added a reviewer: libc++.

Currently check_assertion.h checks an assertion by forking and checking the 
exit code of the child process, but this means such tests don't work on targets 
where fork doesn't exist (e.g. bare metal targets).

Instead call setjmp just before we call the function we want to test, then 
longjmp out of __libcpp_assertion_handler with a return value indicating 
whether the assert happened as expected.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D124255

Files:
  libcxx/test/support/check_assertion.h
  libcxx/test/support/test.support/test_check_assertion.pass.cpp

Index: libcxx/test/support/test.support/test_check_assertion.pass.cpp
===
--- libcxx/test/support/test.support/test_check_assertion.pass.cpp
+++ libcxx/test/support/test.support/test_check_assertion.pass.cpp
@@ -22,12 +22,6 @@
   DeathTest::ResultKind RK = DT.Run(func);
   auto OnFailure = [&](std::string msg) {
 std::fprintf(stderr, "EXPECT_DEATH( %s ) failed! (%s)\n\n", stmt, msg.c_str());
-if (!DT.getChildStdErr().empty()) {
-  std::fprintf(stderr, "-- standard err --\n%s\n", DT.getChildStdErr().c_str());
-}
-if (!DT.getChildStdOut().empty()) {
-  std::fprintf(stderr, "-- standard out --\n%s\n", DT.getChildStdOut().c_str());
-}
 return false;
   };
   if (RK != ExpectResult)
Index: libcxx/test/support/check_assertion.h
===
--- libcxx/test/support/check_assertion.h
+++ libcxx/test/support/check_assertion.h
@@ -17,9 +17,8 @@
 #include 
 #include 
 
-#include 
 #include 
-#include 
+#include 
 #include "test_macros.h"
 #include "test_allocator.h"
 
@@ -108,9 +107,16 @@
   return GMatch;
 }
 
+static jmp_buf& GetJmpBuf() {
+  static jmp_buf env;
+  return env;
+}
+
 struct DeathTest {
   enum ResultKind {
-RK_DidNotDie, RK_MatchFound, RK_MatchFailure, RK_SetupFailure, RK_Unknown
+// This enum starts from 1 and not 0 as we want to return the ResultKind
+// through setjmp/longjmp, which doesn't permit 0.
+RK_DidNotDie = 1, RK_MatchFound, RK_MatchFailure, RK_Unknown
   };
 
   static const char* ResultKindToString(ResultKind RK) {
@@ -118,7 +124,6 @@
 switch (RK) {
 CASE(RK_MatchFailure);
 CASE(RK_DidNotDie);
-CASE(RK_SetupFailure);
 CASE(RK_MatchFound);
 CASE(RK_Unknown);
 }
@@ -133,114 +138,30 @@
 
   template 
   ResultKind Run(Func&& f) {
-int pipe_res = pipe(stdout_pipe_fd_);
-assert(pipe_res != -1 && "failed to create pipe");
-pipe_res = pipe(stderr_pipe_fd_);
-assert(pipe_res != -1 && "failed to create pipe");
-pid_t child_pid = fork();
-assert(child_pid != -1 &&
-"failed to fork a process to perform a death test");
-child_pid_ = child_pid;
-if (child_pid_ == 0) {
-  RunForChild(std::forward(f));
-  assert(false && "unreachable");
-}
-return RunForParent();
-  }
-
-  int getChildExitCode() const { return exit_code_; }
-  std::string const& getChildStdOut() const { return stdout_from_child_; }
-  std::string const& getChildStdErr() const { return stderr_from_child_; }
-private:
-  template 
-  TEST_NORETURN void RunForChild(Func&& f) {
-close(GetStdOutReadFD()); // don't need to read from the pipe in the child.
-close(GetStdErrReadFD());
-auto DupFD = [](int DestFD, int TargetFD) {
-  int dup_result = dup2(DestFD, TargetFD);
-  if (dup_result == -1)
-std::exit(RK_SetupFailure);
-};
-DupFD(GetStdOutWriteFD(), STDOUT_FILENO);
-DupFD(GetStdErrWriteFD(), STDERR_FILENO);
-
 GlobalMatcher() = matcher_;
-f();
-std::exit(RK_DidNotDie);
-  }
-
-  static std::string ReadChildIOUntilEnd(int FD) {
-std::string error_msg;
-char buffer[256];
-int num_read;
-do {
-  while ((num_read = read(FD, buffer, 255)) > 0) {
-buffer[num_read] = '\0';
-error_msg += buffer;
-  }
-} while (num_read == -1 && errno == EINTR);
-return error_msg;
-  }
-
-  void CaptureIOFromChild() {
-close(GetStdOutWriteFD()); // no need to write from the parent process
-close(GetStdErrWriteFD());
-stdout_from_child_ = ReadChildIOUntilEnd(GetStdOutReadFD());
-stderr_from_child_ = ReadChildIOUntilEnd(GetStdErrReadFD());
-close(GetStdOutReadFD());
-close(GetStdErrReadFD());
-  }
-
-  ResultKind RunForParent() {
-CaptureIOFromChild();
-
-int status_value;
-pid_t result = waitpid(child_pid_, &status_value, 0);
-assert(result != -1 && "there is no child process to wait for");
-
-if (WIFEXITED(status_value)) {
-  exit_code_ = WEXITSTATUS(status_value);
-  if (!IsValid

[PATCH] D124256: [OpenCL] Add cl_khr_subgroup_rotate builtins

2022-04-22 Thread Sven van Haastregt via Phabricator via cfe-commits
svenvh created this revision.
svenvh added a reviewer: Anastasia.
svenvh added a project: clang.
Herald added subscribers: Naghasan, ldrumm, yaxunl.
Herald added a project: All.
svenvh requested review of this revision.
Herald added a subscriber: cfe-commits.

Add the builtins for the new OpenCL extension.  The specification is under 
review here: https://github.com/KhronosGroup/OpenCL-Docs/pull/781


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D124256

Files:
  clang/lib/Headers/opencl-c.h
  clang/lib/Sema/OpenCLBuiltins.td


Index: clang/lib/Sema/OpenCLBuiltins.td
===
--- clang/lib/Sema/OpenCLBuiltins.td
+++ clang/lib/Sema/OpenCLBuiltins.td
@@ -1832,6 +1832,12 @@
   def : Builtin<"dot_acc_sat_4x8packed_su_int", [Int, UInt, UInt, Int], 
Attr.Const>;
 }
 
+// cl_khr_subgroup_rotate
+let Extension = FunctionExtension<"cl_khr_subgroup_rotate"> in {
+  def : Builtin<"sub_group_rotate", [AGenType1, AGenType1, Int], 
Attr.Convergent>;
+  def : Builtin<"sub_group_clustered_rotate", [AGenType1, AGenType1, Int, 
UInt], Attr.Convergent>;
+}
+
 //
 // Arm extensions.
 let Extension = ArmIntegerDotProductInt8 in {
Index: clang/lib/Headers/opencl-c.h
===
--- clang/lib/Headers/opencl-c.h
+++ clang/lib/Headers/opencl-c.h
@@ -17275,6 +17275,40 @@
 int __ovld __cnfn dot_acc_sat_4x8packed_su_int(uint, uint, int);
 #endif // __opencl_c_integer_dot_product_input_4x8bit_packed
 
+#if defined(cl_khr_subgroup_rotate)
+char __ovld __conv sub_group_rotate(char, int);
+uchar __ovld __conv sub_group_rotate(uchar, int);
+short __ovld __conv sub_group_rotate(short, int);
+ushort __ovld __conv sub_group_rotate(ushort, int);
+int __ovld __conv sub_group_rotate(int, int);
+uint __ovld __conv sub_group_rotate(uint, int);
+long __ovld __conv sub_group_rotate(long, int);
+ulong __ovld __conv sub_group_rotate(ulong, int);
+float __ovld __conv sub_group_rotate(float, int);
+#if defined(cl_khr_fp64)
+double __ovld __conv sub_group_rotate(double, int);
+#endif // cl_khr_fp64
+#if defined(cl_khr_fp16)
+half __ovld __conv sub_group_rotate(half, int);
+#endif // cl_khr_fp16
+
+char __ovld __conv sub_group_clustered_rotate(char, int, uint);
+uchar __ovld __conv sub_group_clustered_rotate(uchar, int, uint);
+short __ovld __conv sub_group_clustered_rotate(short, int, uint);
+ushort __ovld __conv sub_group_clustered_rotate(ushort, int, uint);
+int __ovld __conv sub_group_clustered_rotate(int, int, uint);
+uint __ovld __conv sub_group_clustered_rotate(uint, int, uint);
+long __ovld __conv sub_group_clustered_rotate(long, int, uint);
+ulong __ovld __conv sub_group_clustered_rotate(ulong, int, uint);
+float __ovld __conv sub_group_clustered_rotate(float, int, uint);
+#if defined(cl_khr_fp64)
+double __ovld __conv sub_group_clustered_rotate(double, int, uint);
+#endif // cl_khr_fp64
+#if defined(cl_khr_fp16)
+half __ovld __conv sub_group_clustered_rotate(half, int, uint);
+#endif // cl_khr_fp16
+#endif // cl_khr_subgroup_rotate
+
 #if defined(cl_intel_subgroups)
 // Intel-Specific Sub Group Functions
 float   __ovld __conv intel_sub_group_shuffle( float , uint );


Index: clang/lib/Sema/OpenCLBuiltins.td
===
--- clang/lib/Sema/OpenCLBuiltins.td
+++ clang/lib/Sema/OpenCLBuiltins.td
@@ -1832,6 +1832,12 @@
   def : Builtin<"dot_acc_sat_4x8packed_su_int", [Int, UInt, UInt, Int], Attr.Const>;
 }
 
+// cl_khr_subgroup_rotate
+let Extension = FunctionExtension<"cl_khr_subgroup_rotate"> in {
+  def : Builtin<"sub_group_rotate", [AGenType1, AGenType1, Int], Attr.Convergent>;
+  def : Builtin<"sub_group_clustered_rotate", [AGenType1, AGenType1, Int, UInt], Attr.Convergent>;
+}
+
 //
 // Arm extensions.
 let Extension = ArmIntegerDotProductInt8 in {
Index: clang/lib/Headers/opencl-c.h
===
--- clang/lib/Headers/opencl-c.h
+++ clang/lib/Headers/opencl-c.h
@@ -17275,6 +17275,40 @@
 int __ovld __cnfn dot_acc_sat_4x8packed_su_int(uint, uint, int);
 #endif // __opencl_c_integer_dot_product_input_4x8bit_packed
 
+#if defined(cl_khr_subgroup_rotate)
+char __ovld __conv sub_group_rotate(char, int);
+uchar __ovld __conv sub_group_rotate(uchar, int);
+short __ovld __conv sub_group_rotate(short, int);
+ushort __ovld __conv sub_group_rotate(ushort, int);
+int __ovld __conv sub_group_rotate(int, int);
+uint __ovld __conv sub_group_rotate(uint, int);
+long __ovld __conv sub_group_rotate(long, int);
+ulong __ovld __conv sub_group_rotate(ulong, int);
+float __ovld __conv sub_group_rotate(float, int);
+#if defined(cl_khr_fp64)
+double __ovld __conv sub_group_rotate(double, int);
+#endif // cl_khr_fp64
+#if defined(cl_khr_fp16)
+half __ovld __conv sub_group_rotate(half, int);
+#e

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

2022-04-22 Thread Gabor Marton via Phabricator via cfe-commits
martong added a comment.

I'd like to have a guarantee that if `Opts.ShouldSupportSymbolicIntegerCasts` 
is set to `true` then the `SymboCast` is produced both for the scoped and the 
unscoped enums. Could you please have an additional lit test for that? At some 
point we'd like to make `ShouldSupportSymbolicIntegerCasts` to be `true` by 
default, thus in the existing test it would be better to explicitly have 
`-analyzer-config support-symbolic-integer-casts=false` set.


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

https://reviews.llvm.org/D85528

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


[PATCH] D124253: [Clang][OpenMP] Fix the issue that one temp cubin file is not removed after compilation

2022-04-22 Thread Shilei Tian via Phabricator via cfe-commits
tianshilei1992 planned changes to this revision.
tianshilei1992 added a comment.

The issue is in `clang/lib/Driver/ToolChains/Cuda.cpp`.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124253

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


[clang] 4c4ff00 - [C++20][Modules][Driver][HU 2/N] Add fmodule-header, fmodule-header=

2022-04-22 Thread Iain Sandoe via cfe-commits

Author: Iain Sandoe
Date: 2022-04-22T14:14:19+01:00
New Revision: 4c4ff004a2702b9b7538efd569bb621a5efac8f3

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

LOG: [C++20][Modules][Driver][HU 2/N] Add fmodule-header, fmodule-header=

These command-line flags are alternates to providing the -x
c++-*-header indicators that we are building a header unit.

Act on fmodule-header= for headers on the c/l:

If we have x.hh -fmodule-header, then we should treat that header
as a header unit input (equivalent to -xc++-header-unit-header x.hh).

Likewise, for fmodule-header={user,system} the source should be now
recognised as a header unit input (since this can affect the job list
that we need).

It's not practical to recognise a header without any suffix so
-fmodule-header=system foo isn't going to happen. Although
-fmodule-header=system foo.hh will work OK.  However we can make it
work if the user indicates that the item without a suffix is a valid
header. (so -fmodule-header=system -xc++-header vector)

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

Added: 
clang/test/Driver/cxx20-header-units-02.cpp

Modified: 
clang/docs/ClangCommandLineReference.rst
clang/include/clang/Driver/Driver.h
clang/include/clang/Driver/Options.td
clang/lib/Driver/Driver.cpp

Removed: 




diff  --git a/clang/docs/ClangCommandLineReference.rst 
b/clang/docs/ClangCommandLineReference.rst
index 1a0e4805bc263..33f9a55f62484 100644
--- a/clang/docs/ClangCommandLineReference.rst
+++ b/clang/docs/ClangCommandLineReference.rst
@@ -1176,6 +1176,14 @@ Validate the system headers that a module depends on 
when loading the module
 
 Specify the prebuilt module path
 
+.. option:: -fmodule-header
+
+Build a C++20 header unit from a header specified.
+
+.. option:: -fmodule-header=\[user,system\]
+
+Build a C++20 header unit, but search for the header in the user or system 
header search paths respectively.
+
 .. option:: --hip-path=
 
 HIP runtime installation path, used for finding HIP version and adding HIP 
include path.

diff  --git a/clang/include/clang/Driver/Driver.h 
b/clang/include/clang/Driver/Driver.h
index b33b64cd9e6a2..f68f281f0e931 100644
--- a/clang/include/clang/Driver/Driver.h
+++ b/clang/include/clang/Driver/Driver.h
@@ -56,6 +56,16 @@ enum LTOKind {
   LTOK_Unknown
 };
 
+/// Whether headers used to construct C++20 module units should be looked
+/// up by the path supplied on the command line, or in the user or system
+/// search paths.
+enum ModuleHeaderMode {
+  HeaderMode_None,
+  HeaderMode_Default,
+  HeaderMode_User,
+  HeaderMode_System
+};
+
 /// Driver - Encapsulate logic for constructing compilation processes
 /// from a set of gcc-driver-like command line arguments.
 class Driver {
@@ -84,6 +94,13 @@ class Driver {
 EmbedBitcode
   } BitcodeEmbed;
 
+  /// Header unit mode set by -fmodule-header={user,system}.
+  ModuleHeaderMode CXX20HeaderType;
+
+  /// Set if we should process inputs and jobs with C++20 module
+  /// interpretation.
+  bool ModulesModeCXX20;
+
   /// LTO mode selected via -f(no-)?lto(=.*)? options.
   LTOKind LTOMode;
 
@@ -574,6 +591,12 @@ class Driver {
   /// ShouldEmitStaticLibrary - Should the linker emit a static library.
   bool ShouldEmitStaticLibrary(const llvm::opt::ArgList &Args) const;
 
+  /// Returns true if the user has indicated a C++20 header unit mode.
+  bool hasHeaderMode() const { return CXX20HeaderType != HeaderMode_None; }
+
+  /// Get the mode for handling headers as set by fmodule-header{=}.
+  ModuleHeaderMode getModuleHeaderMode() const { return CXX20HeaderType; }
+
   /// Returns true if we are performing any kind of LTO.
   bool isUsingLTO(bool IsOffload = false) const {
 return getLTOMode(IsOffload) != LTOK_None;

diff  --git a/clang/include/clang/Driver/Options.td 
b/clang/include/clang/Driver/Options.td
index 8c013e3fe5b19..8e3611cff2d63 100644
--- a/clang/include/clang/Driver/Options.td
+++ b/clang/include/clang/Driver/Options.td
@@ -2296,6 +2296,11 @@ defm implicit_modules : BoolFOption<"implicit-modules",
   NegFlag, PosFlag, 
BothFlags<[NoXarchOption,CoreOption]>>;
 def fretain_comments_from_system_headers : Flag<["-"], 
"fretain-comments-from-system-headers">, Group, Flags<[CC1Option]>,
   MarshallingInfoFlag>;
+def fmodule_header : Flag <["-"], "fmodule-header">, Group,
+  Flags<[NoXarchOption]>, HelpText<"Build a C++20 Header Unit from a header.">;
+def fmodule_header_EQ : Joined<["-"], "fmodule-header=">, Group,
+  Flags<[NoXarchOption]>, MetaVarName<"">,
+  HelpText<"Build a C++20 Header Unit from a header that should be found in 
the user (fmodule-header=user) or system (fmodule-header=system) search path.">;
 
 def fno_knr_functions : Flag<["-"], "fno-knr-functions">, Group,
   MarshallingInfoFlag>,


[PATCH] D121589: [C++20][Modules][Driver][HU 2/N] Add fmodule-header, fmodule-header=

2022-04-22 Thread Iain Sandoe via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG4c4ff004a270: [C++20][Modules][Driver][HU 2/N] Add 
fmodule-header, fmodule-header= (authored by iains).

Changed prior to commit:
  https://reviews.llvm.org/D121589?vs=418220&id=424459#toc

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D121589

Files:
  clang/docs/ClangCommandLineReference.rst
  clang/include/clang/Driver/Driver.h
  clang/include/clang/Driver/Options.td
  clang/lib/Driver/Driver.cpp
  clang/test/Driver/cxx20-header-units-02.cpp

Index: clang/test/Driver/cxx20-header-units-02.cpp
===
--- /dev/null
+++ clang/test/Driver/cxx20-header-units-02.cpp
@@ -0,0 +1,32 @@
+// Test user-facing command line options to generate C++20 header units.
+
+// RUN: %clang -### -std=c++20 -fmodule-header=user foo.hh  2>&1 | \
+// RUN:   FileCheck -check-prefix=CHECK-USER %s
+
+// RUN: %clang -### -std=c++20 -fmodule-header=system foo.hh 2>&1 | \
+// RUN:   FileCheck -check-prefix=CHECK-SYS1 %s
+
+// RUN: %clang -### -std=c++20 -fmodule-header=system \
+// RUN: -xc++-system-header vector 2>&1 | FileCheck -check-prefix=CHECK-SYS2 %s
+
+// RUN: %clang -### -std=c++20 -fmodule-header=system \
+// RUN: -xc++-header vector 2>&1 | FileCheck -check-prefix=CHECK-SYS2 %s
+
+// RUN: %clang -### -std=c++20 -fmodule-header %/S/Inputs/header-unit-01.hh \
+// RUN: 2>&1 | FileCheck -check-prefix=CHECK-ABS %s -DTDIR=%/S/Inputs
+
+// CHECK-USER: "-emit-header-unit"
+// CHECK-USER-SAME: "-o" "foo.pcm"
+// CHECK-USER-SAME: "-x" "c++-user-header" "foo.hh"
+
+// CHECK-SYS1: "-emit-header-unit"
+// CHECK-SYS1-SAME: "-o" "foo.pcm"
+// CHECK-SYS1-SAME: "-x" "c++-system-header" "foo.hh"
+
+// CHECK-SYS2: "-emit-header-unit"
+// CHECK-SYS2-SAME: "-o" "vector.pcm"
+// CHECK-SYS2-SAME: "-x" "c++-system-header" "vector"
+
+// CHECK-ABS: "-emit-header-unit"
+// CHECK-ABS-SAME: "-o" "header-unit-01.pcm"
+// CHECK-ABS-SAME: "-x" "c++-header-unit-header" "[[TDIR]]/header-unit-01.hh"
Index: clang/lib/Driver/Driver.cpp
===
--- clang/lib/Driver/Driver.cpp
+++ clang/lib/Driver/Driver.cpp
@@ -191,13 +191,14 @@
DiagnosticsEngine &Diags, std::string Title,
IntrusiveRefCntPtr VFS)
 : Diags(Diags), VFS(std::move(VFS)), Mode(GCCMode),
-  SaveTemps(SaveTempsNone), BitcodeEmbed(EmbedNone), LTOMode(LTOK_None),
-  ClangExecutable(ClangExecutable), SysRoot(DEFAULT_SYSROOT),
-  DriverTitle(Title), CCCPrintBindings(false), CCPrintOptions(false),
-  CCPrintHeaders(false), CCLogDiagnostics(false), CCGenDiagnostics(false),
-  CCPrintProcessStats(false), TargetTriple(TargetTriple), Saver(Alloc),
-  CheckInputsExist(true), GenReproducer(false),
-  SuppressMissingInputWarning(false) {
+  SaveTemps(SaveTempsNone), BitcodeEmbed(EmbedNone),
+  CXX20HeaderType(HeaderMode_None), ModulesModeCXX20(false),
+  LTOMode(LTOK_None), ClangExecutable(ClangExecutable),
+  SysRoot(DEFAULT_SYSROOT), DriverTitle(Title), CCCPrintBindings(false),
+  CCPrintOptions(false), CCPrintHeaders(false), CCLogDiagnostics(false),
+  CCGenDiagnostics(false), CCPrintProcessStats(false),
+  TargetTriple(TargetTriple), Saver(Alloc), CheckInputsExist(true),
+  GenReproducer(false), SuppressMissingInputWarning(false) {
   // Provide a sane fallback if no VFS is specified.
   if (!this->VFS)
 this->VFS = llvm::vfs::getRealFileSystem();
@@ -337,9 +338,13 @@
   CCGenDiagnostics) {
 FinalPhase = phases::Preprocess;
 
-  // --precompile only runs up to precompilation.
+// --precompile only runs up to precompilation.
+// Options that cause the output of C++20 compiled module interfaces or
+// header units have the same effect.
   } else if ((PhaseArg = DAL.getLastArg(options::OPT__precompile)) ||
- (PhaseArg = DAL.getLastArg(options::OPT_extract_api))) {
+ (PhaseArg = DAL.getLastArg(options::OPT_extract_api)) ||
+ (PhaseArg = DAL.getLastArg(options::OPT_fmodule_header,
+options::OPT_fmodule_header_EQ))) {
 FinalPhase = phases::Precompile;
 // -{fsyntax-only,-analyze,emit-ast} only run up to the compiler.
   } else if ((PhaseArg = DAL.getLastArg(options::OPT_fsyntax_only)) ||
@@ -1251,6 +1256,37 @@
   BitcodeEmbed = static_cast(Model);
   }
 
+  // Setting up the jobs for some precompile cases depends on whether we are
+  // treating them as PCH, implicit modules or C++20 ones.
+  // TODO: inferring the mode like this seems fragile (it meets the objective
+  // of not requiring anything new for operation, however).
+  const Arg *Std = Args.getLastArg(options::OPT_std_EQ);
+  ModulesModeCXX20 =
+  !Args.hasArg(options::OPT_fmodules) && Std &&
+  (Std->containsValue("c++20") || Std->containsValue("c+

[PATCH] D124240: [clangd][NFC] Reduce memory usage while building dex

2022-04-22 Thread Sam McCall via Phabricator via cfe-commits
sammccall accepted this revision.
sammccall added inline comments.
This revision is now accepted and ready to land.



Comment at: clang-tools-extra/clangd/index/dex/Dex.cpp:89
+  Result.try_emplace(Token(Token::Kind::Trigram, E.first.str()),
+ std::move(E.second));
+TrigramDocs.clear();

kadircet wrote:
> sammccall wrote:
> > the move here does nothing, we're passing as ArrayRef
> > 
> > did you want to clear the map values (vectors) as you went, too?
> > 
> > (this gets a bit verbose, but you could pull out a function template since 
> > all 4 cases are so regular)
> > did you want to clear the map values (vectors) as you went, too?
> 
> yes that's the idea. would you prefer an explicit destructor call?
> 
> > (this gets a bit verbose, but you could pull out a function template since 
> > all 4 cases are so regular)
> 
> the problem is 1 of these is a densemap, other three is a stringmap, and 
> onther is a vector. densemap and the stringmap doesn't really go together 
> because there's no common method to get the key (densemap has `first` as a 
> field, or `getFirst()` as a method. stringmap has `first()` or `getKey()` as 
> methods :/).
> happy to move out just the three of them into a helper like:
> ```
> buildPostingList(StringMap<..>, TokenKind, Out);
> ```
> if you think that's still helpful (that way we can also get rid of the calls 
> to clear since we can just move the maps into the function arguments).
> yes that's the idea. would you prefer an explicit destructor call?

I mean e.second.clear() in the loop.
As it stands, you're only destroying them a whole map at a time, and trigrams 
is (i think) >50% of the total

> the problem is 1 of these is a densemap, other three is a stringmap, and 
> onther is a vector.

Sounds too complicated, nevermind!


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124240

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


[PATCH] D124221: Add new builtin __builtin_reflect_struct.

2022-04-22 Thread Erich Keane via Phabricator via cfe-commits
erichkeane added a comment.

I generally just question the usefulness of this.  Despite its shortcomings, 
the 'dump struct' has the capability of runtime introspection into a type, 
whereas this seems to require that the user 'know' a significant amount about 
the type that they are introspecting (number of bases, number of fields, field 
TYPES). If you knew the type of your struct, THIS well, I would expect you 
wouldn't NEED a builtin like this.




Comment at: clang/docs/LanguageExtensions.rst:2434
+
+ bool print(int arg1, int arg2, std::initializer_list fields) {
+   for (auto f : fields) {

I'm curious as to the need for the 'arg1' and 'arg2'?  Also, what is the type 
of the 'fields' array that works in C?



Comment at: clang/docs/LanguageExtensions.rst:2437
+ std::cout << f.name;
+ if (f.bitwidth)
+   std::cout << " : " << f.bitwidth;

Hmm... what is the type of f.bitwidth?  A zero-length bitwidth is a valid 
thing, so having it just be an 'int' doesn't seem workable.



Comment at: clang/docs/LanguageExtensions.rst:2460
+The ``__builtin_reflect_struct`` function provides simple reflection for a
+class, struct, or union. The first argument of the builtin should be a pointer
+to the type to reflect. The second argument ``f`` should be some callable

While I get the value of a generic reflection 'thing', this is once again 
getting awful close to 'just implement reflection capabilities', at which point 
this seems insufficient.



Comment at: clang/docs/LanguageExtensions.rst:2462
+to the type to reflect. The second argument ``f`` should be some callable
+expression, and can be a function object or an overload set. The builtin calls
+``f``, passing any further arguments ``args...`` followed by an initializer

Is the purpose of the overload set/functor so you can support multiple types 
(seeing how the 'base' below works)?  How does this all work in C? (or do we 
just do fields in C, since they cannot have the rest?

I wonder if we would be better if we treated this function as a 'callback' or a 
'callback set' that returned a discriminated union of a pre-defined type that 
describes what is being returned.  That way it could handle member functions, 
static variables, etc.



Comment at: clang/docs/LanguageExtensions.rst:2464
+``f``, passing any further arguments ``args...`` followed by an initializer
+list describing the struct value.
+

Same question about init-list, how is this usable in C?  It becomes a BIT more 
usable in C if instead we return a single object that represents a single AST 
node.



Comment at: clang/docs/LanguageExtensions.rst:2471
+
+The initializer list contains the following components:
+

I find myself wishing this was a more complete list.



Comment at: clang/docs/LanguageExtensions.rst:2473
+
+* For each direct base class, the address of the base class, in declaration
+  order.

I wonder if bases should include their virtualness or access specifier.



Comment at: clang/lib/Sema/SemaChecking.cpp:420
+auto *FD = IFD ? IFD->getAnonField() : dyn_cast(D);
+if (!FD || (FD->isUnnamedBitfield() || FD->isAnonymousStructOrUnion()))
+  continue;

Losing the unnamed bitfield is unfortunate, and I the 'dump struct' handles.  
As is losing the anonymous struct/union.

Also, how does this handle 'record type' members?  Does the user have to know 
the inner type already?  If they already know that much information about the 
type, they wouldn't really need this, right?



Comment at: clang/test/CodeGenCXX/builtin-reflect-struct.cpp:24
+
+int consume(int, Expected);
+

OH! I see now.  This is unfortunately quite limiting by doing it this way.  At 
this point the user of this builtin is required to know the layout of the 
struct before calling the builtin, which seems unfortunate. Despite the 
downsides of being just a 'dump function', the other builtin had the benefit of 
working on an arbitrary type.


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] D86351: WIP: llvm-buildozer

2022-04-22 Thread Alexandre Ganea via Phabricator via cfe-commits
aganea added inline comments.



Comment at: llvm/lib/Analysis/MemorySSA.cpp:89
 #ifdef EXPENSIVE_CHECKS
-bool llvm::VerifyMemorySSA = true;
+LLVM_THREAD_LOCAL bool llvm::VerifyMemorySSA = true;
 #else

arsenm wrote:
> Do command line flags like this really need to be thread local? Wouldn't ever 
> cl::opt need to be if this is?
This was only for the PoC.

Values pointed by `cl::opt`s -- that is either the internal `cl::opt` data or 
the static pointed by `cl::location` -- should be part of a context of some 
sort. LLD now has `CommonLinkerContext` plus a derived context per-driver. We 
probably need a "context" class along the same lines for the LLVM libs. Should 
it be part of `LLVMContextImpl`? Some options are read a bit earlier, before 
the `LLVMContext` is created.
The `cl::opt`s themselves can remain static.

Unless we assume `cl::opt`s are just for debugging, and move to tablegen any 
such globals that affect multi-threaded compilation?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D86351

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


[PATCH] D123300: [Clang] Enable opaque pointers by default

2022-04-22 Thread Markus Lavin via Phabricator via cfe-commits
markus added a comment.

In D123300#3467309 , @nikic wrote:

> Sounds reasonable in general -- though isn't this a pre-existing problem 
> you'd see if you simply had multiple loads from the same global (without any 
> GEP)? Looking at the current ConstantHoist code, it doesn't seem to really 
> consider the case where a global symbol address can be expensive, it only 
> handles hoisting of large integer values.

Indeed, multiple (GEP-less) loads from the same symbol gives the same problem. 
At least if they are spread out across the CFG, otherwise isel deals with it. 
Not sure what is the right way to deal with this. Maybe we will try making some 
modifications to ConstantHoist.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D123300

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


[PATCH] D124132: Thread safety analysis: Don't pass capability kind where not needed (NFC)

2022-04-22 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!


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124132

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


[PATCH] D124258: [C89/C2x] Change the behavior of implicit int diagnostics

2022-04-22 Thread Erich Keane via Phabricator via cfe-commits
erichkeane added a comment.

Some quick comments... I didn't even bother opening the tests besides checking 
on functionality, so hopefully those are ok too :D




Comment at: clang/docs/ReleaseNotes.rst:169
+  As of C2x, support for implicit int has been removed, and the warning options
+  will have no effect. Specifying ``-Wimplicit-int`` in C89 mode will now issue
+  warnings instead of being a noop.

I find myself thinking that despite it being 'valid code' that `-Wimplicit-int` 
should be on-by-default in C89 mode. We often warn about 'valid, but 
non-future-proof' code, by default, particularly when they are code-breaking 
like this is.



Comment at: clang/include/clang/Basic/LangOptions.h:534
+  /// Returns true if implicit int is supported at all.
+  bool implicitIntEnabled() const { return !CPlusPlus && !C2x; }
+

This name seems inverse of what you mean to me?  IDK if you're 
bike-shed-sniping me here, but:

`prohibitsImplicitInt` to be the reverse of above? It becomes SLIGHTLY 
ambiguous to me (in that we don't mean "the language standard prohibits", we 
mean "the compiler implementation prohibits"), but that can be fixed up with a 
comment.

If you want to keep the direction, perhaps `implicitIntPermitted`, at which 
point I might suggest the one above become `implicitIntRequired`.



Comment at: clang/lib/Parse/Parser.cpp:1198
 
   // If this is C90 and the declspecs were completely missing, fudge in an
   // implicit int.  We do this here because this is the only place where

C90?



Comment at: clang/lib/Sema/SemaDecl.cpp:14329
   if (FTI.Params[i].Param == nullptr) {
-SmallString<256> Code;
-llvm::raw_svector_ostream(Code)
-<< "  int " << FTI.Params[i].Ident->getName() << ";\n";
-Diag(FTI.Params[i].IdentLoc, diag::ext_param_not_declared)
-<< FTI.Params[i].Ident
-<< FixItHint::CreateInsertion(LocAfterDecls, Code);
+if (getLangOpts().C99) {
+  SmallString<256> Code;

IMO there should be a warning here for C89.  Warning for non-future-proof code 
is pretty typical.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124258

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


[PATCH] D124260: [clang-format] ColumnLimit check for trailing comments alignment acts wrong for multi-byte UTF-8 #47624

2022-04-22 Thread Александр Тулуп via Phabricator via cfe-commits
StailGot created this revision.
StailGot added a project: clang-format.
Herald added a project: All.
StailGot requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

Fix for https://github.com/llvm/llvm-project/issues/47624

Used token for counting length instead of logical symbols.
That leads to wrong length count with utf8 symbols


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D124260

Files:
  clang/lib/Format/WhitespaceManager.cpp


Index: clang/lib/Format/WhitespaceManager.cpp
===
--- clang/lib/Format/WhitespaceManager.cpp
+++ clang/lib/Format/WhitespaceManager.cpp
@@ -909,8 +909,8 @@
 
 if (Style.ColumnLimit == 0)
   ChangeMaxColumn = UINT_MAX;
-else if (Style.ColumnLimit >= Changes[i].TokenLength)
-  ChangeMaxColumn = Style.ColumnLimit - Changes[i].TokenLength;
+else if (Style.ColumnLimit >= Changes[i].Tok->ColumnWidth)
+  ChangeMaxColumn = Style.ColumnLimit - Changes[i].Tok->ColumnWidth;
 else
   ChangeMaxColumn = ChangeMinColumn;
 


Index: clang/lib/Format/WhitespaceManager.cpp
===
--- clang/lib/Format/WhitespaceManager.cpp
+++ clang/lib/Format/WhitespaceManager.cpp
@@ -909,8 +909,8 @@
 
 if (Style.ColumnLimit == 0)
   ChangeMaxColumn = UINT_MAX;
-else if (Style.ColumnLimit >= Changes[i].TokenLength)
-  ChangeMaxColumn = Style.ColumnLimit - Changes[i].TokenLength;
+else if (Style.ColumnLimit >= Changes[i].Tok->ColumnWidth)
+  ChangeMaxColumn = Style.ColumnLimit - Changes[i].Tok->ColumnWidth;
 else
   ChangeMaxColumn = ChangeMinColumn;
 
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


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

2022-04-22 Thread Balázs Benics via Phabricator via cfe-commits
steakhal updated this revision to Diff 424470.
steakhal added a comment.

Added two new RUN lines, demonstrating the behavior of 
`support-symbolic-integer-casts={true,false}`.
Also refined the match string to be less fuzzy. It helps to grasp the 
difference between the expectations.


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,55 @@
+// 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 %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() {
+  int sym1 = static_cast(conjure()) & 0x0F;
+  int sym2 = static_cast(conjure()) & 0x0F;
+  int sym3 = static_cast(conjure()) & 0x0F;
+  int sym4 = static_cast(conjure()) & 0x0F;
+
+  if (sym1 && sym2 && sym3 && sym4) {
+// no-crash on these dumps
+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() &&
+CastTy->isIntegralOrUnscopedEnumerationType()) {
   AnalyzerOptions &Opts =
   StateMgr.getOwningEngine().getAnalysisManager().getAnalyzerOptions();
   // If appropriate option is disabled, ignore the cast.


Index: clang/test/Analysis/z3-refute-enum-crash.cpp
===
--- /dev/null
+++ clang/test/Analysis/z3-refute-enum-crash.cpp
@@ -0,0 +1,55 @@
+// 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 %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 {};

[PATCH] D123300: [Clang] Enable opaque pointers by default

2022-04-22 Thread Dawid Jurczak via Phabricator via cfe-commits
yurai007 added a comment.

Just one more thing regarding this:

In D123300#3467165 , @yurai007 wrote:

> Hi, unfortunately for some reason it doesn't play well with coroutines HALO. 
> There is regression seen on Gor's Nishanov classical code snippet:  
> https://godbolt.org/z/PKMxqq4Gr I'm checking IR to find out more.

It's (kind of) related to GEPs as well. From CoroElide perspective the thing is 
that we cannot collect coro.subfn.addrs associated with coro.begin intrinsics 
in processCoroId.
Normally, for each coro.begin we traverse its users list and save found 
coro.subfn.addr. That explains why elision works fine when coro.begin is 
directly used by coro.subfn.addr:

  %35 = call noalias nonnull i8* @llvm.coro.begin(token %31, i8* %34)
  %40 = call i8* @llvm.coro.subfn.addr(i8* nonnull %35, i8 0)

With opaque pointers IR reaching CoroElide has intermediate GEPs so 
coro.subfn.addr is not present on coro.begin's list and DestroyAddrs are not 
collected:

  %22 = call noalias nonnull ptr @llvm.coro.begin(token %18, ptr %21)
  %__promise.reload.addr.i36 = getelementptr inbounds 
%_Z3addIiE9generatorIT_ERS2_S1_.Frame, ptr %22, i64 0, i32 2
  %23 = getelementptr inbounds i8, ptr %__promise.reload.addr.i36, i64 -16
  %24 = call ptr @llvm.coro.subfn.addr(ptr nonnull %23, i8 0)


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D123300

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


[PATCH] D124262: compile commands header to source heuristic lower-cases filenames before inferring file types

2022-04-22 Thread Ishaan Gandhi via Phabricator via cfe-commits
ishaangandhi created this revision.
ishaangandhi added reviewers: nridge, sammccall.
Herald added subscribers: usaxena95, kadircet.
Herald added a project: All.
ishaangandhi requested review of this revision.
Herald added subscribers: cfe-commits, ilya-biryukov.
Herald added a project: clang.

This leads to ".C" files being rewritten as ".c" files and being inferred to be 
"c" files as opposed to "c++" files.

See https://github.com/clangd/clangd/issues/1108 for the original bug report.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D124262

Files:
  clang/lib/Tooling/InterpolatingCompilationDatabase.cpp


Index: clang/lib/Tooling/InterpolatingCompilationDatabase.cpp
===
--- clang/lib/Tooling/InterpolatingCompilationDatabase.cpp
+++ clang/lib/Tooling/InterpolatingCompilationDatabase.cpp
@@ -329,7 +329,7 @@
   StringRef Path = Strings.save(StringRef(OriginalPaths[I]).lower());
 
   Paths.emplace_back(Path, I);
-  Types.push_back(foldType(guessType(Path)));
+  Types.push_back(foldType(guessType(StringRef(OriginalPaths[I];
   Stems.emplace_back(sys::path::stem(Path), I);
   auto Dir = ++sys::path::rbegin(Path), DirEnd = sys::path::rend(Path);
   for (int J = 0; J < DirectorySegmentsIndexed && Dir != DirEnd; ++J, 
++Dir)


Index: clang/lib/Tooling/InterpolatingCompilationDatabase.cpp
===
--- clang/lib/Tooling/InterpolatingCompilationDatabase.cpp
+++ clang/lib/Tooling/InterpolatingCompilationDatabase.cpp
@@ -329,7 +329,7 @@
   StringRef Path = Strings.save(StringRef(OriginalPaths[I]).lower());
 
   Paths.emplace_back(Path, I);
-  Types.push_back(foldType(guessType(Path)));
+  Types.push_back(foldType(guessType(StringRef(OriginalPaths[I];
   Stems.emplace_back(sys::path::stem(Path), I);
   auto Dir = ++sys::path::rbegin(Path), DirEnd = sys::path::rend(Path);
   for (int J = 0; J < DirectorySegmentsIndexed && Dir != DirEnd; ++J, ++Dir)
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D124239: [analyzer] Fix ValistChecker false-positive involving symbolic pointers

2022-04-22 Thread Balázs Benics via Phabricator via cfe-commits
steakhal updated this revision to Diff 424478.
steakhal added a comment.

fix test


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

https://reviews.llvm.org/D124239

Files:
  clang/lib/StaticAnalyzer/Checkers/ValistChecker.cpp
  clang/test/Analysis/valist-uninitialized-no-undef.c


Index: clang/test/Analysis/valist-uninitialized-no-undef.c
===
--- clang/test/Analysis/valist-uninitialized-no-undef.c
+++ clang/test/Analysis/valist-uninitialized-no-undef.c
@@ -16,11 +16,20 @@
 
 void f6(va_list *fst, ...) {
   va_start(*fst, fst);
-  // FIXME: There should be no warning for this.
-  (void)va_arg(*fst, int); // expected-warning{{va_arg() is called on an 
uninitialized va_list}}
-  // expected-note@-1{{va_arg() is called on an uninitialized va_list}}
+  (void)va_arg(*fst, int);
   va_end(*fst);
-} 
+}
+
+int va_list_get_int(va_list *va) {
+  return va_arg(*va, int); // no-warning
+}
+
+struct MyVaList {
+  va_list l;
+};
+int va_list_get_int2(struct MyVaList *va) {
+  return va_arg(va->l, int); // no-warning
+}
 
 void call_vprintf_bad(int isstring, ...) {
   va_list va;
Index: clang/lib/StaticAnalyzer/Checkers/ValistChecker.cpp
===
--- clang/lib/StaticAnalyzer/Checkers/ValistChecker.cpp
+++ clang/lib/StaticAnalyzer/Checkers/ValistChecker.cpp
@@ -178,7 +178,7 @@
 if (isa(DeclReg->getDecl()))
   Reg = C.getState()->getSVal(SV.castAs()).getAsRegion();
   }
-  IsSymbolic = Reg && Reg->getAs();
+  IsSymbolic = Reg && Reg->getBaseRegion()->getAs();
   // Some VarRegion based VA lists reach here as ElementRegions.
   const auto *EReg = dyn_cast_or_null(Reg);
   return (EReg && VaListModelledAsArray) ? EReg->getSuperRegion() : Reg;


Index: clang/test/Analysis/valist-uninitialized-no-undef.c
===
--- clang/test/Analysis/valist-uninitialized-no-undef.c
+++ clang/test/Analysis/valist-uninitialized-no-undef.c
@@ -16,11 +16,20 @@
 
 void f6(va_list *fst, ...) {
   va_start(*fst, fst);
-  // FIXME: There should be no warning for this.
-  (void)va_arg(*fst, int); // expected-warning{{va_arg() is called on an uninitialized va_list}}
-  // expected-note@-1{{va_arg() is called on an uninitialized va_list}}
+  (void)va_arg(*fst, int);
   va_end(*fst);
-} 
+}
+
+int va_list_get_int(va_list *va) {
+  return va_arg(*va, int); // no-warning
+}
+
+struct MyVaList {
+  va_list l;
+};
+int va_list_get_int2(struct MyVaList *va) {
+  return va_arg(va->l, int); // no-warning
+}
 
 void call_vprintf_bad(int isstring, ...) {
   va_list va;
Index: clang/lib/StaticAnalyzer/Checkers/ValistChecker.cpp
===
--- clang/lib/StaticAnalyzer/Checkers/ValistChecker.cpp
+++ clang/lib/StaticAnalyzer/Checkers/ValistChecker.cpp
@@ -178,7 +178,7 @@
 if (isa(DeclReg->getDecl()))
   Reg = C.getState()->getSVal(SV.castAs()).getAsRegion();
   }
-  IsSymbolic = Reg && Reg->getAs();
+  IsSymbolic = Reg && Reg->getBaseRegion()->getAs();
   // Some VarRegion based VA lists reach here as ElementRegions.
   const auto *EReg = dyn_cast_or_null(Reg);
   return (EReg && VaListModelledAsArray) ? EReg->getSuperRegion() : Reg;
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D123300: [Clang] Enable opaque pointers by default

2022-04-22 Thread Nikita Popov via Phabricator via cfe-commits
nikic added a comment.

In D123300#3467615 , @yurai007 wrote:

> Just one more thing regarding this:
>
> In D123300#3467165 , @yurai007 
> wrote:
>
>> Hi, unfortunately for some reason it doesn't play well with coroutines HALO. 
>> There is regression seen on Gor's Nishanov classical code snippet:  
>> https://godbolt.org/z/PKMxqq4Gr I'm checking IR to find out more.
>
> It's (kind of) related to GEPs as well. From CoroElide perspective the thing 
> is that we cannot collect coro.subfn.addrs associated with coro.begin 
> intrinsics in processCoroId.
> Normally, for each coro.begin we traverse its users list and save found 
> coro.subfn.addr. That explains why elision works fine when coro.begin is 
> directly used by coro.subfn.addr:
>
>   %35 = call noalias nonnull i8* @llvm.coro.begin(token %31, i8* %34)
>   %40 = call i8* @llvm.coro.subfn.addr(i8* nonnull %35, i8 0)
>
> With opaque pointers IR reaching CoroElide has intermediate GEPs so 
> coro.subfn.addr is not present on coro.begin's list and DestroyAddrs are not 
> collected:
>
>   %22 = call noalias nonnull ptr @llvm.coro.begin(token %18, ptr %21)
>   %__promise.reload.addr.i36 = getelementptr inbounds 
> %_Z3addIiE9generatorIT_ERS2_S1_.Frame, ptr %22, i64 0, i32 2
>   %23 = getelementptr inbounds i8, ptr %__promise.reload.addr.i36, i64 -16
>   %24 = call ptr @llvm.coro.subfn.addr(ptr nonnull %23, i8 0)

Thanks! I'm not familiar with the coroutine aspect here, but clearly there is a 
big optimization fail here: https://llvm.godbolt.org/z/GPG5df9xT We should be 
folding these two GEPs together, at least for the case of constant offsets. 
Probably we should canonicalize to `i8` GEPs in InstCombine.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D123300

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


[PATCH] D124258: [C89/C2x] Change the behavior of implicit int diagnostics

2022-04-22 Thread Corentin Jabot via Phabricator via cfe-commits
cor3ntin added inline comments.



Comment at: clang/include/clang/Basic/LangOptions.h:534
+  /// Returns true if implicit int is supported at all.
+  bool implicitIntEnabled() const { return !CPlusPlus && !C2x; }
+

erichkeane wrote:
> This name seems inverse of what you mean to me?  IDK if you're 
> bike-shed-sniping me here, but:
> 
> `prohibitsImplicitInt` to be the reverse of above? It becomes SLIGHTLY 
> ambiguous to me (in that we don't mean "the language standard prohibits", we 
> mean "the compiler implementation prohibits"), but that can be fixed up with 
> a comment.
> 
> If you want to keep the direction, perhaps `implicitIntPermitted`, at which 
> point I might suggest the one above become `implicitIntRequired`.
@erichkeane `requiresImplicitInt` is only used twice. Does it needs a name?




Comment at: clang/lib/Sema/SemaDecl.cpp:14329
   if (FTI.Params[i].Param == nullptr) {
-SmallString<256> Code;
-llvm::raw_svector_ostream(Code)
-<< "  int " << FTI.Params[i].Ident->getName() << ";\n";
-Diag(FTI.Params[i].IdentLoc, diag::ext_param_not_declared)
-<< FTI.Params[i].Ident
-<< FixItHint::CreateInsertion(LocAfterDecls, Code);
+if (getLangOpts().C99) {
+  SmallString<256> Code;

erichkeane wrote:
> IMO there should be a warning here for C89.  Warning for non-future-proof 
> code is pretty typical.
Isn't the counter argument that was made on similar changes that people 
specifically asking for C89 have peculiar expectations?
Otherwise i agree



Comment at: clang/lib/Sema/SemaDecl.cpp:14342-14343
 DeclSpec DS(attrs);
-const char* PrevSpec; // unused
-unsigned DiagID; // unused
+const char *PrevSpec; // unused
+unsigned DiagID;  // unused
 DS.SetTypeSpecType(DeclSpec::TST_int, FTI.Params[i].IdentLoc, PrevSpec,

Nitpick: whitespace only change


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124258

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


[PATCH] D124258: [C89/C2x] Change the behavior of implicit int diagnostics

2022-04-22 Thread Erich Keane via Phabricator via cfe-commits
erichkeane added inline comments.



Comment at: clang/include/clang/Basic/LangOptions.h:534
+  /// Returns true if implicit int is supported at all.
+  bool implicitIntEnabled() const { return !CPlusPlus && !C2x; }
+

cor3ntin wrote:
> erichkeane wrote:
> > This name seems inverse of what you mean to me?  IDK if you're 
> > bike-shed-sniping me here, but:
> > 
> > `prohibitsImplicitInt` to be the reverse of above? It becomes SLIGHTLY 
> > ambiguous to me (in that we don't mean "the language standard prohibits", 
> > we mean "the compiler implementation prohibits"), but that can be fixed up 
> > with a comment.
> > 
> > If you want to keep the direction, perhaps `implicitIntPermitted`, at which 
> > point I might suggest the one above become `implicitIntRequired`.
> @erichkeane `requiresImplicitInt` is only used twice. Does it needs a name?
> 
*shrug*, I tend to be of the feeling that if you have to say something this 
often, and functions are basically free, mind as well make one.



Comment at: clang/lib/Sema/SemaDecl.cpp:14329
   if (FTI.Params[i].Param == nullptr) {
-SmallString<256> Code;
-llvm::raw_svector_ostream(Code)
-<< "  int " << FTI.Params[i].Ident->getName() << ";\n";
-Diag(FTI.Params[i].IdentLoc, diag::ext_param_not_declared)
-<< FTI.Params[i].Ident
-<< FixItHint::CreateInsertion(LocAfterDecls, Code);
+if (getLangOpts().C99) {
+  SmallString<256> Code;

cor3ntin wrote:
> erichkeane wrote:
> > IMO there should be a warning here for C89.  Warning for non-future-proof 
> > code is pretty typical.
> Isn't the counter argument that was made on similar changes that people 
> specifically asking for C89 have peculiar expectations?
> Otherwise i agree
Yep, folks asking for C89 ARE peculiar :D  However, warnings-not-as-error are, 
IMO, simply 'helpful'. 



Comment at: clang/lib/Sema/SemaDecl.cpp:14342-14343
 DeclSpec DS(attrs);
-const char* PrevSpec; // unused
-unsigned DiagID; // unused
+const char *PrevSpec; // unused
+unsigned DiagID;  // unused
 DS.SetTypeSpecType(DeclSpec::TST_int, FTI.Params[i].IdentLoc, PrevSpec,

cor3ntin wrote:
> Nitpick: whitespace only change
This might be a clang-format thing based on the previous line.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124258

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


[PATCH] D88905: [Clang] Allow "ext_vector_type" applied to Booleans

2022-04-22 Thread Erich Keane via Phabricator via cfe-commits
erichkeane added a comment.
Herald added a subscriber: StephenFan.

Note the error I found with this: 
https://github.com/llvm/llvm-project/issues/55038


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D88905

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


[PATCH] D124240: [clangd][NFC] Reduce memory usage while building dex

2022-04-22 Thread Kadir Cetinkaya via Phabricator via cfe-commits
kadircet updated this revision to Diff 424489.
kadircet marked 2 inline comments as done.
kadircet added a comment.

Copy-assign to empty containers rather than clear.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124240

Files:
  clang-tools-extra/clangd/index/dex/Dex.cpp


Index: clang-tools-extra/clangd/index/dex/Dex.cpp
===
--- clang-tools-extra/clangd/index/dex/Dex.cpp
+++ clang-tools-extra/clangd/index/dex/Dex.cpp
@@ -13,14 +13,19 @@
 #include "URI.h"
 #include "index/Index.h"
 #include "index/dex/Iterator.h"
+#include "index/dex/Token.h"
 #include "index/dex/Trigram.h"
 #include "support/Logger.h"
 #include "support/Trace.h"
+#include "llvm/ADT/DenseMap.h"
+#include "llvm/ADT/StringMap.h"
 #include "llvm/ADT/StringSet.h"
 #include "llvm/Support/Path.h"
 #include "llvm/Support/ScopedPrinter.h"
 #include 
 #include 
+#include 
+#include 
 
 namespace clang {
 namespace clangd {
@@ -76,23 +81,38 @@
   }
 
   // Assemble the final compressed posting lists for the added symbols.
-  llvm::DenseMap build() {
+  llvm::DenseMap build() && {
 llvm::DenseMap Result(/*InitialReserve=*/
   TrigramDocs.size() +
   RestrictedCCDocs.size() +
   TypeDocs.size() +
   ScopeDocs.size() +
   ProximityDocs.size());
-for (const auto &E : TrigramDocs)
+// Tear down intermediate structs as we go to reduce memory usage.
+// Since we're trying to get rid of underlying allocations, clearing the
+// containers is not enough.
+auto CreatePostingList =
+[&Result](Token::Kind TK, llvm::StringMap> &Docs) {
+  for (auto &E : Docs) {
+Result.try_emplace(Token(TK, E.first()), E.second);
+E.second = {};
+  }
+  Docs = {};
+};
+CreatePostingList(Token::Kind::Type, TypeDocs);
+CreatePostingList(Token::Kind::Scope, ScopeDocs);
+CreatePostingList(Token::Kind::ProximityURI, ProximityDocs);
+
+// TrigramDocs are stored in a DenseMap and RestrictedCCDocs is not even a
+// map, treat them specially.
+for (auto &E : TrigramDocs) {
   Result.try_emplace(Token(Token::Kind::Trigram, E.first.str()), E.second);
-for (const auto &E : TypeDocs)
-  Result.try_emplace(Token(Token::Kind::Type, E.first()), E.second);
-for (const auto &E : ScopeDocs)
-  Result.try_emplace(Token(Token::Kind::Scope, E.first()), E.second);
-for (const auto &E : ProximityDocs)
-  Result.try_emplace(Token(Token::Kind::ProximityURI, E.first()), 
E.second);
+  E.second = {};
+}
+TrigramDocs = llvm::DenseMap>{};
 if (!RestrictedCCDocs.empty())
-  Result.try_emplace(RestrictedForCodeCompletion, RestrictedCCDocs);
+  Result.try_emplace(RestrictedForCodeCompletion,
+ std::move(RestrictedCCDocs));
 return Result;
   }
 };
@@ -125,7 +145,7 @@
   IndexBuilder Builder;
   for (DocID SymbolRank = 0; SymbolRank < Symbols.size(); ++SymbolRank)
 Builder.add(*Symbols[SymbolRank], SymbolRank);
-  InvertedIndex = Builder.build();
+  InvertedIndex = std::move(Builder).build();
 }
 
 std::unique_ptr Dex::iterator(const Token &Tok) const {


Index: clang-tools-extra/clangd/index/dex/Dex.cpp
===
--- clang-tools-extra/clangd/index/dex/Dex.cpp
+++ clang-tools-extra/clangd/index/dex/Dex.cpp
@@ -13,14 +13,19 @@
 #include "URI.h"
 #include "index/Index.h"
 #include "index/dex/Iterator.h"
+#include "index/dex/Token.h"
 #include "index/dex/Trigram.h"
 #include "support/Logger.h"
 #include "support/Trace.h"
+#include "llvm/ADT/DenseMap.h"
+#include "llvm/ADT/StringMap.h"
 #include "llvm/ADT/StringSet.h"
 #include "llvm/Support/Path.h"
 #include "llvm/Support/ScopedPrinter.h"
 #include 
 #include 
+#include 
+#include 
 
 namespace clang {
 namespace clangd {
@@ -76,23 +81,38 @@
   }
 
   // Assemble the final compressed posting lists for the added symbols.
-  llvm::DenseMap build() {
+  llvm::DenseMap build() && {
 llvm::DenseMap Result(/*InitialReserve=*/
   TrigramDocs.size() +
   RestrictedCCDocs.size() +
   TypeDocs.size() +
   ScopeDocs.size() +
   ProximityDocs.size());
-for (const auto &E : TrigramDocs)
+// Tear down intermediate structs as we go to reduce memory usage.
+// Since we're trying to get rid of underlying allocations, clearing the
+// containers is not enough.
+auto CreatePostingList =
+[&Result](Token::Kind TK, llvm::St

[clang-tools-extra] 2efccf5 - [clangd][NFC] Reduce memory usage while building dex

2022-04-22 Thread Kadir Cetinkaya via cfe-commits

Author: Kadir Cetinkaya
Date: 2022-04-22T17:44:47+02:00
New Revision: 2efccf5166f4dd7d188eea2de4f4b7f50b64e477

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

LOG: [clangd][NFC] Reduce memory usage while building dex

Reduce peak memory usage by tearing down the intermediate representation
as we build the final one. Rather than deleting it in the end.

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

Added: 


Modified: 
clang-tools-extra/clangd/index/dex/Dex.cpp

Removed: 




diff  --git a/clang-tools-extra/clangd/index/dex/Dex.cpp 
b/clang-tools-extra/clangd/index/dex/Dex.cpp
index 5829d780c6072..18779077b2c43 100644
--- a/clang-tools-extra/clangd/index/dex/Dex.cpp
+++ b/clang-tools-extra/clangd/index/dex/Dex.cpp
@@ -13,14 +13,19 @@
 #include "URI.h"
 #include "index/Index.h"
 #include "index/dex/Iterator.h"
+#include "index/dex/Token.h"
 #include "index/dex/Trigram.h"
 #include "support/Logger.h"
 #include "support/Trace.h"
+#include "llvm/ADT/DenseMap.h"
+#include "llvm/ADT/StringMap.h"
 #include "llvm/ADT/StringSet.h"
 #include "llvm/Support/Path.h"
 #include "llvm/Support/ScopedPrinter.h"
 #include 
 #include 
+#include 
+#include 
 
 namespace clang {
 namespace clangd {
@@ -76,23 +81,38 @@ class IndexBuilder {
   }
 
   // Assemble the final compressed posting lists for the added symbols.
-  llvm::DenseMap build() {
+  llvm::DenseMap build() && {
 llvm::DenseMap Result(/*InitialReserve=*/
   TrigramDocs.size() +
   RestrictedCCDocs.size() +
   TypeDocs.size() +
   ScopeDocs.size() +
   ProximityDocs.size());
-for (const auto &E : TrigramDocs)
+// Tear down intermediate structs as we go to reduce memory usage.
+// Since we're trying to get rid of underlying allocations, clearing the
+// containers is not enough.
+auto CreatePostingList =
+[&Result](Token::Kind TK, llvm::StringMap> &Docs) {
+  for (auto &E : Docs) {
+Result.try_emplace(Token(TK, E.first()), E.second);
+E.second = {};
+  }
+  Docs = {};
+};
+CreatePostingList(Token::Kind::Type, TypeDocs);
+CreatePostingList(Token::Kind::Scope, ScopeDocs);
+CreatePostingList(Token::Kind::ProximityURI, ProximityDocs);
+
+// TrigramDocs are stored in a DenseMap and RestrictedCCDocs is not even a
+// map, treat them specially.
+for (auto &E : TrigramDocs) {
   Result.try_emplace(Token(Token::Kind::Trigram, E.first.str()), E.second);
-for (const auto &E : TypeDocs)
-  Result.try_emplace(Token(Token::Kind::Type, E.first()), E.second);
-for (const auto &E : ScopeDocs)
-  Result.try_emplace(Token(Token::Kind::Scope, E.first()), E.second);
-for (const auto &E : ProximityDocs)
-  Result.try_emplace(Token(Token::Kind::ProximityURI, E.first()), 
E.second);
+  E.second = {};
+}
+TrigramDocs = llvm::DenseMap>{};
 if (!RestrictedCCDocs.empty())
-  Result.try_emplace(RestrictedForCodeCompletion, RestrictedCCDocs);
+  Result.try_emplace(RestrictedForCodeCompletion,
+ std::move(RestrictedCCDocs));
 return Result;
   }
 };
@@ -125,7 +145,7 @@ void Dex::buildIndex() {
   IndexBuilder Builder;
   for (DocID SymbolRank = 0; SymbolRank < Symbols.size(); ++SymbolRank)
 Builder.add(*Symbols[SymbolRank], SymbolRank);
-  InvertedIndex = Builder.build();
+  InvertedIndex = std::move(Builder).build();
 }
 
 std::unique_ptr Dex::iterator(const Token &Tok) const {



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


[PATCH] D124240: [clangd][NFC] Reduce memory usage while building dex

2022-04-22 Thread Kadir Cetinkaya via Phabricator via cfe-commits
This revision was landed with ongoing or failed builds.
This revision was automatically updated to reflect the committed changes.
Closed by commit rG2efccf5166f4: [clangd][NFC] Reduce memory usage while 
building dex (authored by kadircet).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124240

Files:
  clang-tools-extra/clangd/index/dex/Dex.cpp


Index: clang-tools-extra/clangd/index/dex/Dex.cpp
===
--- clang-tools-extra/clangd/index/dex/Dex.cpp
+++ clang-tools-extra/clangd/index/dex/Dex.cpp
@@ -13,14 +13,19 @@
 #include "URI.h"
 #include "index/Index.h"
 #include "index/dex/Iterator.h"
+#include "index/dex/Token.h"
 #include "index/dex/Trigram.h"
 #include "support/Logger.h"
 #include "support/Trace.h"
+#include "llvm/ADT/DenseMap.h"
+#include "llvm/ADT/StringMap.h"
 #include "llvm/ADT/StringSet.h"
 #include "llvm/Support/Path.h"
 #include "llvm/Support/ScopedPrinter.h"
 #include 
 #include 
+#include 
+#include 
 
 namespace clang {
 namespace clangd {
@@ -76,23 +81,38 @@
   }
 
   // Assemble the final compressed posting lists for the added symbols.
-  llvm::DenseMap build() {
+  llvm::DenseMap build() && {
 llvm::DenseMap Result(/*InitialReserve=*/
   TrigramDocs.size() +
   RestrictedCCDocs.size() +
   TypeDocs.size() +
   ScopeDocs.size() +
   ProximityDocs.size());
-for (const auto &E : TrigramDocs)
+// Tear down intermediate structs as we go to reduce memory usage.
+// Since we're trying to get rid of underlying allocations, clearing the
+// containers is not enough.
+auto CreatePostingList =
+[&Result](Token::Kind TK, llvm::StringMap> &Docs) {
+  for (auto &E : Docs) {
+Result.try_emplace(Token(TK, E.first()), E.second);
+E.second = {};
+  }
+  Docs = {};
+};
+CreatePostingList(Token::Kind::Type, TypeDocs);
+CreatePostingList(Token::Kind::Scope, ScopeDocs);
+CreatePostingList(Token::Kind::ProximityURI, ProximityDocs);
+
+// TrigramDocs are stored in a DenseMap and RestrictedCCDocs is not even a
+// map, treat them specially.
+for (auto &E : TrigramDocs) {
   Result.try_emplace(Token(Token::Kind::Trigram, E.first.str()), E.second);
-for (const auto &E : TypeDocs)
-  Result.try_emplace(Token(Token::Kind::Type, E.first()), E.second);
-for (const auto &E : ScopeDocs)
-  Result.try_emplace(Token(Token::Kind::Scope, E.first()), E.second);
-for (const auto &E : ProximityDocs)
-  Result.try_emplace(Token(Token::Kind::ProximityURI, E.first()), 
E.second);
+  E.second = {};
+}
+TrigramDocs = llvm::DenseMap>{};
 if (!RestrictedCCDocs.empty())
-  Result.try_emplace(RestrictedForCodeCompletion, RestrictedCCDocs);
+  Result.try_emplace(RestrictedForCodeCompletion,
+ std::move(RestrictedCCDocs));
 return Result;
   }
 };
@@ -125,7 +145,7 @@
   IndexBuilder Builder;
   for (DocID SymbolRank = 0; SymbolRank < Symbols.size(); ++SymbolRank)
 Builder.add(*Symbols[SymbolRank], SymbolRank);
-  InvertedIndex = Builder.build();
+  InvertedIndex = std::move(Builder).build();
 }
 
 std::unique_ptr Dex::iterator(const Token &Tok) const {


Index: clang-tools-extra/clangd/index/dex/Dex.cpp
===
--- clang-tools-extra/clangd/index/dex/Dex.cpp
+++ clang-tools-extra/clangd/index/dex/Dex.cpp
@@ -13,14 +13,19 @@
 #include "URI.h"
 #include "index/Index.h"
 #include "index/dex/Iterator.h"
+#include "index/dex/Token.h"
 #include "index/dex/Trigram.h"
 #include "support/Logger.h"
 #include "support/Trace.h"
+#include "llvm/ADT/DenseMap.h"
+#include "llvm/ADT/StringMap.h"
 #include "llvm/ADT/StringSet.h"
 #include "llvm/Support/Path.h"
 #include "llvm/Support/ScopedPrinter.h"
 #include 
 #include 
+#include 
+#include 
 
 namespace clang {
 namespace clangd {
@@ -76,23 +81,38 @@
   }
 
   // Assemble the final compressed posting lists for the added symbols.
-  llvm::DenseMap build() {
+  llvm::DenseMap build() && {
 llvm::DenseMap Result(/*InitialReserve=*/
   TrigramDocs.size() +
   RestrictedCCDocs.size() +
   TypeDocs.size() +
   ScopeDocs.size() +
   ProximityDocs.size());
-for (const auto &E : TrigramDocs)
+// Tear down intermediate structs as we go to reduce memory usage.
+// Since we're trying to get rid of underlying allocations, clearing the
+// containers is not enough.
+

[PATCH] D124244: [analyzer] add StoreToImmutable and ModelConstQualifiedReturn checkers

2022-04-22 Thread Zurab Tsinadze via Phabricator via cfe-commits
zukatsinadze updated this revision to Diff 424493.
zukatsinadze added a comment.

fix clang format


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

https://reviews.llvm.org/D124244

Files:
  clang/docs/analyzer/checkers.rst
  clang/include/clang/StaticAnalyzer/Checkers/Checkers.td
  clang/include/clang/StaticAnalyzer/Core/PathSensitive/MemRegion.h
  clang/lib/StaticAnalyzer/Checkers/CMakeLists.txt
  clang/lib/StaticAnalyzer/Checkers/StoreToImmutableChecker.cpp
  clang/lib/StaticAnalyzer/Checkers/cert/ModelConstQualifiedReturnChecker.cpp
  clang/test/Analysis/analyzer-enabled-checkers.c
  clang/test/Analysis/cert/env30-c.cpp
  clang/test/Analysis/std-c-library-functions-arg-enabled-checkers.c

Index: clang/test/Analysis/std-c-library-functions-arg-enabled-checkers.c
===
--- clang/test/Analysis/std-c-library-functions-arg-enabled-checkers.c
+++ clang/test/Analysis/std-c-library-functions-arg-enabled-checkers.c
@@ -32,6 +32,7 @@
 // CHECK-NEXT: core.NullDereference
 // CHECK-NEXT: core.StackAddrEscapeBase
 // CHECK-NEXT: core.StackAddressEscape
+// CHECK-NEXT: core.StoreToImmutable
 // CHECK-NEXT: core.UndefinedBinaryOperatorResult
 // CHECK-NEXT: core.VLASize
 // CHECK-NEXT: core.builtin.BuiltinFunctions
Index: clang/test/Analysis/cert/env30-c.cpp
===
--- /dev/null
+++ clang/test/Analysis/cert/env30-c.cpp
@@ -0,0 +1,213 @@
+// RUN: %clang_analyze_cc1 \
+// RUN:  -analyzer-checker=core.StoreToImmutable,alpha.security.cert.env.ModelConstQualifiedReturn \
+// RUN:  -analyzer-output=text -verify -Wno-unused %s
+
+#include "../Inputs/system-header-simulator.h"
+char *getenv(const char *name);
+char *setlocale(int category, const char *locale);
+char *strerror(int errnum);
+int setenv(const char *name, const char *value, int overwrite);
+void free(void *memblock);
+void *malloc(size_t size);
+char *strdup(const char *s);
+
+typedef struct {
+} tm;
+char *asctime(const tm *timeptr);
+
+int strcmp(const char *, const char *);
+void non_const_parameter_function(char *e);
+void const_parameter_function(const char *);
+
+void getenv_test1() {
+  char *p = getenv("VAR");
+  // expected-note@-1{{return value of 'getenv' should be treated as const-qualified}}
+  *p = 'A';
+  // expected-warning@-1{{modifying immutable memory [core.StoreToImmutable]}}
+  // expected-note@-2{{modifying immutable memory}}
+}
+
+void getenv_test2() {
+  char *p;
+
+  p = getenv("VAR");
+  non_const_parameter_function(p); // FIXME: Maybe we should warn for these.
+}
+
+void getenv_test3() {
+  char *p;
+  p = getenv("VAR");
+  const_parameter_function(p); // no-warning
+}
+
+void modify(char *p) {
+  *p = 'A';
+  // expected-warning@-1{{modifying immutable memory [core.StoreToImmutable]}}
+  // expected-note@-2{{modifying immutable memory}}
+}
+
+void getenv_test4() {
+  char *p = getenv("VAR");
+  // expected-note@-1{{return value of 'getenv' should be treated as const-qualified}}
+  char *pp = p;
+  modify(pp); // Writing to immutable region within the call.
+  // expected-note@-1{{Calling 'modify'}}
+}
+
+void does_not_modify(char *p) {
+  *p;
+}
+
+void getenv_test5() {
+  char *p = getenv("VAR");
+  does_not_modify(p); // no-warning
+}
+
+void getenv_test6() {
+  static char *array[] = {0};
+
+  if (!array[0]) {
+// expected-note@-1{{Taking true branch}}
+array[0] = getenv("TEMPDIR");
+// expected-note@-1{{return value of 'getenv' should be treated as const-qualified}}
+  }
+
+  *array[0] = 'A';
+  // expected-warning@-1{{modifying immutable memory [core.StoreToImmutable]}}
+  // expected-note@-2{{modifying immutable memory}}
+}
+
+void getenv_test7() {
+  char *p = getenv("VAR");
+  // expected-note@-1{{return value of 'getenv' should be treated as const-qualified}}
+  if (!p)
+// expected-note@-1{{Assuming 'p' is non-null}}
+// expected-note@-2{{Taking false branch}}
+return;
+  p[0] = '\0';
+  // expected-warning@-1{{modifying immutable memory [core.StoreToImmutable]}}
+  // expected-note@-2{{modifying immutable memory}}
+}
+
+void setlocale_test() {
+  char *p = setlocale(0, "VAR");
+  // expected-note@-1{{return value of 'setlocale' should be treated as const-qualified}}
+  *p = 'A';
+  // expected-warning@-1{{modifying immutable memory [core.StoreToImmutable]}}
+  // expected-note@-2{{modifying immutable memory}}
+}
+
+void strerror_test() {
+  char *p = strerror(0);
+  // expected-note@-1{{return value of 'strerror' should be treated as const-qualified}}
+  *p = 'A';
+  // expected-warning@-1{{modifying immutable memory [core.StoreToImmutable]}}
+  // expected-note@-2{{modifying immutable memory}}
+}
+
+void asctime_test() {
+  const tm *t;
+  char *p = asctime(t);
+  // expected-note@-1{{return value of 'asctime' should be treated as const-qualified}}
+
+  *p = 'A';
+  // expected-warning@-1{{modifying immutable memory [core.StoreToImmutable]}}
+  // expected-no

[PATCH] D120272: [CUDA] Add driver support for compiling CUDA with the new driver

2022-04-22 Thread Joseph Huber via Phabricator via cfe-commits
jhuber6 added a comment.

Ping


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D120272

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


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

2022-04-22 Thread Balázs Benics via Phabricator via cfe-commits
steakhal updated this revision to Diff 424497.
steakhal added a comment.

Added the missing `-verify` flag for the new RUN line.
Also, add an elaborate description in the test for explaining the situation.


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() &&
+CastTy->isIntegralOrUnscopedEnumerationType()) {
   AnalyzerOpt

[PATCH] D124221: Add new builtin __builtin_reflect_struct.

2022-04-22 Thread Richard Smith - zygoloid via Phabricator via cfe-commits
rsmith added a comment.

In D124221#3467467 , @erichkeane 
wrote:

> I generally just question the usefulness of this.  Despite its shortcomings, 
> the 'dump struct' has the capability of runtime introspection into a type, 
> whereas this seems to require that the user 'know' a significant amount about 
> the type that they are introspecting (number of bases, number of fields, 
> field TYPES).

I think you've misunderstood; that is not required. Though with the design 
as-is, it might make sense to restrict this to being C++-only, given that 
there's not really a way to effectively use this from C.




Comment at: clang/docs/LanguageExtensions.rst:2434
+
+ bool print(int arg1, int arg2, std::initializer_list fields) {
+   for (auto f : fields) {

erichkeane wrote:
> I'm curious as to the need for the 'arg1' and 'arg2'?  Also, what is the type 
> of the 'fields' array that works in C?
This is aimed to fix a major deficiency in `__builtin_dump_struct`, that 
there's no way to pass information into its callback (other than stashing it in 
TLS).

As noted in the patch description, this builtin is not especially usable in C. 
I'm not sure whether that's fixable, given the very limited metaprogramming 
support in C.



Comment at: clang/docs/LanguageExtensions.rst:2437
+ std::cout << f.name;
+ if (f.bitwidth)
+   std::cout << " : " << f.bitwidth;

erichkeane wrote:
> Hmm... what is the type of f.bitwidth?  A zero-length bitwidth is a valid 
> thing, so having it just be an 'int' doesn't seem workable.
It's a `size_t`. There are no zero-size bitfield members. (Unnamed bitfield 
aren't members, so are excluded here.) In any case, you can tell the difference 
between a bitfield and a regular member by the length of the initialiser list; 
we don't pass a bit width for non-bit-field members.



Comment at: clang/docs/LanguageExtensions.rst:2462
+to the type to reflect. The second argument ``f`` should be some callable
+expression, and can be a function object or an overload set. The builtin calls
+``f``, passing any further arguments ``args...`` followed by an initializer

erichkeane wrote:
> Is the purpose of the overload set/functor so you can support multiple types 
> (seeing how the 'base' below works)?  How does this all work in C? (or do we 
> just do fields in C, since they cannot have the rest?
> 
> I wonder if we would be better if we treated this function as a 'callback' or 
> a 'callback set' that returned a discriminated union of a pre-defined type 
> that describes what is being returned.  That way it could handle member 
> functions, static variables, etc.
This doesn't really work well in C, as noted in the patch description. A set of 
callbacks might work a bit better across both languages, but I don't think it 
solves the larger problem that there's no good way to pass type information 
into a callback in C.



Comment at: clang/docs/LanguageExtensions.rst:2471
+
+The initializer list contains the following components:
+

erichkeane wrote:
> I find myself wishing this was a more complete list.
What else do you want? My goal here was to be able to do what 
`__builtin_dump_struct` does but without its many arbitrary limitations. From 
C++, this is enough for that.



Comment at: clang/docs/LanguageExtensions.rst:2473
+
+* For each direct base class, the address of the base class, in declaration
+  order.

erichkeane wrote:
> I wonder if bases should include their virtualness or access specifier.
I mean, maybe, but I don't have a use case for either. For access in general my 
leaning is to say that the built-in doesn't get special access rights -- either 
it can access everything or you'll get an access error if you use it -- in 
which case including the access for bases and fields doesn't seem likely to be 
super useful.



Comment at: clang/lib/Sema/SemaChecking.cpp:420
+auto *FD = IFD ? IFD->getAnonField() : dyn_cast(D);
+if (!FD || (FD->isUnnamedBitfield() || FD->isAnonymousStructOrUnion()))
+  continue;

erichkeane wrote:
> Losing the unnamed bitfield is unfortunate, and I the 'dump struct' handles.  
> As is losing the anonymous struct/union.
> 
> Also, how does this handle 'record type' members?  Does the user have to know 
> the inner type already?  If they already know that much information about the 
> type, they wouldn't really need this, right?
If `__builtin_dump_struct` includes unnamed bitfields, that's a bug in that 
builtin.

In general, the user function gets given the bases and members with the right 
types, so they can use an overload set or a template to dispatch based on that 
type. See the SemaCXX test for a basic example of that.



Comment at: clang/test/CodeGenCXX/builtin-reflect-struct.cpp

[PATCH] D119296: KCFI sanitizer

2022-04-22 Thread Sami Tolvanen via Phabricator via cfe-commits
samitolvanen added a comment.

In D119296#3466027 , @joaomoreira 
wrote:

> I played a little bit with kcfi and here are some thoughts:
>
> - under -Os I saw functions being inlined, regardless of the source code 
> calling them indirectly. In these scenarios, the KCFI check was still in 
> place, even though there was not a pointer involved in the call. Although not 
> semantically incorrect, it would be great to prevent the unnecessary overhead 
> (see attached source/compile it with -Os and -fsanitize=kcfi).

Yes, I suspect this might be an issue with Clang's existing CFI schemes too, 
and would probably require an additional pass to drop checks before calls that 
were either inlined or optimized into direct calls.

> - I noticed that KCFI checks are placed much before the indirect call 
> arguments are properly placed in the passing registers. This makes the 
> position of the check unpredictable. I assume this is a bad thing in case the 
> kernel eventually decides to come up with an approach that uses alternatives 
> CFI schemes through text-patching.

It shouldn't matter for text patching as we'll still know the exact location of 
the instruction sequence that we want to patch by looking at the `.kcfi_traps` 
section.

> Because of things like the above, in the past I decided to implement these 
> things in the very backend of the compiler, so other optimizations would not 
> break the layout nor leave dummy checks around. I find it nice to have this 
> implemented as a more architecture general feature, but maybe it would be 
> cool to have a finalization pass in the X86 backend just to tie things.

@pcc, any thoughts about these issues?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D119296

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


[clang] c9e7eec - [clang-format][NFC] Use isComment() in setCommentLineLevels()

2022-04-22 Thread via cfe-commits

Author: owenca
Date: 2022-04-22T09:21:28-07:00
New Revision: c9e7eec7bc41e9cb86e01acd5c91faa5c9ee0bf1

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

LOG: [clang-format][NFC] Use isComment() in setCommentLineLevels()

Also replace an unnecessary check with assert() in the unwrapped
line parser.

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

Added: 


Modified: 
clang/lib/Format/TokenAnnotator.cpp
clang/lib/Format/UnwrappedLineParser.cpp

Removed: 




diff  --git a/clang/lib/Format/TokenAnnotator.cpp 
b/clang/lib/Format/TokenAnnotator.cpp
index 5f3b434dba956..cb950f2b2198d 100644
--- a/clang/lib/Format/TokenAnnotator.cpp
+++ b/clang/lib/Format/TokenAnnotator.cpp
@@ -2505,17 +2505,10 @@ void TokenAnnotator::setCommentLineLevels(
   const AnnotatedLine *NextNonCommentLine = nullptr;
   for (AnnotatedLine *Line : llvm::reverse(Lines)) {
 assert(Line->First);
-bool CommentLine = true;
-for (const FormatToken *Tok = Line->First; Tok; Tok = Tok->Next) {
-  if (!Tok->is(tok::comment)) {
-CommentLine = false;
-break;
-  }
-}
 
 // If the comment is currently aligned with the line immediately following
 // it, that's probably intentional and we should keep it.
-if (NextNonCommentLine && CommentLine &&
+if (NextNonCommentLine && Line->isComment() &&
 NextNonCommentLine->First->NewlinesBefore <= 1 &&
 NextNonCommentLine->First->OriginalColumn ==
 Line->First->OriginalColumn) {

diff  --git a/clang/lib/Format/UnwrappedLineParser.cpp 
b/clang/lib/Format/UnwrappedLineParser.cpp
index 018a7ae3ee794..1e2f4d6761e1e 100644
--- a/clang/lib/Format/UnwrappedLineParser.cpp
+++ b/clang/lib/Format/UnwrappedLineParser.cpp
@@ -2470,8 +2470,9 @@ FormatToken 
*UnwrappedLineParser::parseIfThenElse(IfStmtKind *IfKind,
 Kind = IfStmtKind::IfElseIf;
   addUnwrappedLine();
 } else if (FormatTok->is(tok::kw_if)) {
-  FormatToken *Previous = Tokens->getPreviousToken();
-  const bool IsPrecededByComment = Previous && Previous->is(tok::comment);
+  const FormatToken *Previous = Tokens->getPreviousToken();
+  assert(Previous);
+  const bool IsPrecededByComment = Previous->is(tok::comment);
   if (IsPrecededByComment) {
 addUnwrappedLine();
 ++Line->Level;



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


[PATCH] D124215: [clang-format][NFC] Use isComment() in setCommentLineLevels()

2022-04-22 Thread Owen Pan 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 rGc9e7eec7bc41: [clang-format][NFC] Use isComment() in 
setCommentLineLevels() (authored by owenpan).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124215

Files:
  clang/lib/Format/TokenAnnotator.cpp
  clang/lib/Format/UnwrappedLineParser.cpp


Index: clang/lib/Format/UnwrappedLineParser.cpp
===
--- clang/lib/Format/UnwrappedLineParser.cpp
+++ clang/lib/Format/UnwrappedLineParser.cpp
@@ -2470,8 +2470,9 @@
 Kind = IfStmtKind::IfElseIf;
   addUnwrappedLine();
 } else if (FormatTok->is(tok::kw_if)) {
-  FormatToken *Previous = Tokens->getPreviousToken();
-  const bool IsPrecededByComment = Previous && Previous->is(tok::comment);
+  const FormatToken *Previous = Tokens->getPreviousToken();
+  assert(Previous);
+  const bool IsPrecededByComment = Previous->is(tok::comment);
   if (IsPrecededByComment) {
 addUnwrappedLine();
 ++Line->Level;
Index: clang/lib/Format/TokenAnnotator.cpp
===
--- clang/lib/Format/TokenAnnotator.cpp
+++ clang/lib/Format/TokenAnnotator.cpp
@@ -2505,17 +2505,10 @@
   const AnnotatedLine *NextNonCommentLine = nullptr;
   for (AnnotatedLine *Line : llvm::reverse(Lines)) {
 assert(Line->First);
-bool CommentLine = true;
-for (const FormatToken *Tok = Line->First; Tok; Tok = Tok->Next) {
-  if (!Tok->is(tok::comment)) {
-CommentLine = false;
-break;
-  }
-}
 
 // If the comment is currently aligned with the line immediately following
 // it, that's probably intentional and we should keep it.
-if (NextNonCommentLine && CommentLine &&
+if (NextNonCommentLine && Line->isComment() &&
 NextNonCommentLine->First->NewlinesBefore <= 1 &&
 NextNonCommentLine->First->OriginalColumn ==
 Line->First->OriginalColumn) {


Index: clang/lib/Format/UnwrappedLineParser.cpp
===
--- clang/lib/Format/UnwrappedLineParser.cpp
+++ clang/lib/Format/UnwrappedLineParser.cpp
@@ -2470,8 +2470,9 @@
 Kind = IfStmtKind::IfElseIf;
   addUnwrappedLine();
 } else if (FormatTok->is(tok::kw_if)) {
-  FormatToken *Previous = Tokens->getPreviousToken();
-  const bool IsPrecededByComment = Previous && Previous->is(tok::comment);
+  const FormatToken *Previous = Tokens->getPreviousToken();
+  assert(Previous);
+  const bool IsPrecededByComment = Previous->is(tok::comment);
   if (IsPrecededByComment) {
 addUnwrappedLine();
 ++Line->Level;
Index: clang/lib/Format/TokenAnnotator.cpp
===
--- clang/lib/Format/TokenAnnotator.cpp
+++ clang/lib/Format/TokenAnnotator.cpp
@@ -2505,17 +2505,10 @@
   const AnnotatedLine *NextNonCommentLine = nullptr;
   for (AnnotatedLine *Line : llvm::reverse(Lines)) {
 assert(Line->First);
-bool CommentLine = true;
-for (const FormatToken *Tok = Line->First; Tok; Tok = Tok->Next) {
-  if (!Tok->is(tok::comment)) {
-CommentLine = false;
-break;
-  }
-}
 
 // If the comment is currently aligned with the line immediately following
 // it, that's probably intentional and we should keep it.
-if (NextNonCommentLine && CommentLine &&
+if (NextNonCommentLine && Line->isComment() &&
 NextNonCommentLine->First->NewlinesBefore <= 1 &&
 NextNonCommentLine->First->OriginalColumn ==
 Line->First->OriginalColumn) {
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D124258: [C89/C2x] Change the behavior of implicit int diagnostics

2022-04-22 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman marked 2 inline comments as done.
aaron.ballman added inline comments.



Comment at: clang/docs/ReleaseNotes.rst:169
+  As of C2x, support for implicit int has been removed, and the warning options
+  will have no effect. Specifying ``-Wimplicit-int`` in C89 mode will now issue
+  warnings instead of being a noop.

erichkeane wrote:
> I find myself thinking that despite it being 'valid code' that 
> `-Wimplicit-int` should be on-by-default in C89 mode. We often warn about 
> 'valid, but non-future-proof' code, by default, particularly when they are 
> code-breaking like this is.
On the one hand, yes. On the other hand, this is only for people who specify 
`-std=c89` explicitly (which is not the default language mode for C), and I 
think we've been taking the viewpoint that these folks are mostly trying to 
keep old, mostly unmaintained code working.



Comment at: clang/include/clang/Basic/LangOptions.h:534
+  /// Returns true if implicit int is supported at all.
+  bool implicitIntEnabled() const { return !CPlusPlus && !C2x; }
+

erichkeane wrote:
> cor3ntin wrote:
> > erichkeane wrote:
> > > This name seems inverse of what you mean to me?  IDK if you're 
> > > bike-shed-sniping me here, but:
> > > 
> > > `prohibitsImplicitInt` to be the reverse of above? It becomes SLIGHTLY 
> > > ambiguous to me (in that we don't mean "the language standard prohibits", 
> > > we mean "the compiler implementation prohibits"), but that can be fixed 
> > > up with a comment.
> > > 
> > > If you want to keep the direction, perhaps `implicitIntPermitted`, at 
> > > which point I might suggest the one above become `implicitIntRequired`.
> > @erichkeane `requiresImplicitInt` is only used twice. Does it needs a name?
> > 
> *shrug*, I tend to be of the feeling that if you have to say something this 
> often, and functions are basically free, mind as well make one.
The idea here is that `requiresImplicitInt()` tells you when the support is 
mandatory per spec, and `implicitIntEnabled()` tells you when the support is 
either mandatory or an extension. I'm not strongly tied to the names, how do 
these sound?

`isImplicitIntRequired()` and `isImplicitIntAllowed()`?

(I could also add the word `Support` in there as in 
`isImplicitIntSupportRequired()` but then the function names start to get a bit 
longer than I think is reasonable.)



Comment at: clang/lib/Parse/Parser.cpp:1198
 
   // If this is C90 and the declspecs were completely missing, fudge in an
   // implicit int.  We do this here because this is the only place where

erichkeane wrote:
> C90?
I'll fix the comment up. This confusion exists all over the place. :-D



Comment at: clang/lib/Sema/SemaDecl.cpp:14329
   if (FTI.Params[i].Param == nullptr) {
-SmallString<256> Code;
-llvm::raw_svector_ostream(Code)
-<< "  int " << FTI.Params[i].Ident->getName() << ";\n";
-Diag(FTI.Params[i].IdentLoc, diag::ext_param_not_declared)
-<< FTI.Params[i].Ident
-<< FixItHint::CreateInsertion(LocAfterDecls, Code);
+if (getLangOpts().C99) {
+  SmallString<256> Code;

erichkeane wrote:
> cor3ntin wrote:
> > erichkeane wrote:
> > > IMO there should be a warning here for C89.  Warning for non-future-proof 
> > > code is pretty typical.
> > Isn't the counter argument that was made on similar changes that people 
> > specifically asking for C89 have peculiar expectations?
> > Otherwise i agree
> Yep, folks asking for C89 ARE peculiar :D  However, warnings-not-as-error 
> are, IMO, simply 'helpful'. 
Same here as above -- we *could* warn, but I suspect it wouldn't be 
particularly helpful. The fact that we were warning with an extension warning 
was non-conforming though (we shouldn't fail `-pedantic-errors` in C89 over 
that).



Comment at: clang/lib/Sema/SemaDecl.cpp:14342-14343
 DeclSpec DS(attrs);
-const char* PrevSpec; // unused
-unsigned DiagID; // unused
+const char *PrevSpec; // unused
+unsigned DiagID;  // unused
 DS.SetTypeSpecType(DeclSpec::TST_int, FTI.Params[i].IdentLoc, PrevSpec,

erichkeane wrote:
> cor3ntin wrote:
> > Nitpick: whitespace only change
> This might be a clang-format thing based on the previous line.
Yeah, clang-format got a bit aggressive there, I'll be the formatting changes 
out, thanks!


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124258

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


[clang-tools-extra] e9a902c - Revert "Revert "Revert "[clang][pp] adds '#pragma include_instead'"""

2022-04-22 Thread Christopher Di Bella via cfe-commits

Author: Christopher Di Bella
Date: 2022-04-22T16:37:20Z
New Revision: e9a902c7f755a378e197c4b246a32859c0ee162d

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

LOG: Revert "Revert "Revert "[clang][pp] adds '#pragma include_instead'"""

> Includes regression test for problem noted by @hans.
> is reverts commit 973de71.
>
> Differential Revision: https://reviews.llvm.org/D106898

Feature implemented as-is is fairly expensive and hasn't been used by
libc++. A potential reimplementation is possible if libc++ become
interested in this feature again.

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

Added: 


Modified: 
clang-tools-extra/clangd/Selection.cpp
clang-tools-extra/pseudo/lib/Lex.cpp
clang/include/clang/Basic/DiagnosticLexKinds.td
clang/include/clang/Basic/SourceManager.h
clang/include/clang/Lex/HeaderSearch.h
clang/include/clang/Lex/Lexer.h
clang/include/clang/Lex/Preprocessor.h
clang/include/clang/Lex/PreprocessorLexer.h
clang/lib/Frontend/Rewrite/RewriteModernObjC.cpp
clang/lib/Lex/Lexer.cpp
clang/lib/Lex/PPDirectives.cpp
clang/lib/Lex/PPLexerChange.cpp
clang/lib/Lex/Pragma.cpp

Removed: 
clang/test/PCH/ms-pch-macro-include_instead-regression.c
clang/test/Preprocessor/Inputs/include_instead/bad-syntax.h
clang/test/Preprocessor/Inputs/include_instead/file-not-found.h
clang/test/Preprocessor/Inputs/include_instead/non-system-header.h
clang/test/Preprocessor/Inputs/include_instead/private-x.h
clang/test/Preprocessor/Inputs/include_instead/private1.h
clang/test/Preprocessor/Inputs/include_instead/private2.h
clang/test/Preprocessor/Inputs/include_instead/private3.h
clang/test/Preprocessor/Inputs/include_instead/public-after.h
clang/test/Preprocessor/Inputs/include_instead/public-before.h
clang/test/Preprocessor/Inputs/include_instead/public-empty.h
clang/test/Preprocessor/include_instead.cpp
clang/test/Preprocessor/include_instead_file_not_found.cpp



diff  --git a/clang-tools-extra/clangd/Selection.cpp 
b/clang-tools-extra/clangd/Selection.cpp
index ba2f253eb0757..fa3e6ff22a00a 100644
--- a/clang-tools-extra/clangd/Selection.cpp
+++ b/clang-tools-extra/clangd/Selection.cpp
@@ -30,6 +30,7 @@
 #include "llvm/Support/Casting.h"
 #include "llvm/Support/raw_ostream.h"
 #include 
+#include 
 #include 
 
 namespace clang {

diff  --git a/clang-tools-extra/pseudo/lib/Lex.cpp 
b/clang-tools-extra/pseudo/lib/Lex.cpp
index e99bf3a63e5e1..72eff3c12f25c 100644
--- a/clang-tools-extra/pseudo/lib/Lex.cpp
+++ b/clang-tools-extra/pseudo/lib/Lex.cpp
@@ -7,6 +7,7 @@
 
//===--===//
 
 #include "clang-pseudo/Token.h"
+#include "clang/Basic/IdentifierTable.h"
 #include "clang/Basic/SourceLocation.h"
 #include "clang/Basic/TokenKinds.h"
 #include "clang/Lex/Lexer.h"

diff  --git a/clang/include/clang/Basic/DiagnosticLexKinds.td 
b/clang/include/clang/Basic/DiagnosticLexKinds.td
index 0f424b02c812a..543ce8a3649d1 100644
--- a/clang/include/clang/Basic/DiagnosticLexKinds.td
+++ b/clang/include/clang/Basic/DiagnosticLexKinds.td
@@ -315,12 +315,6 @@ def pp_pragma_sysheader_in_main_file : Warning<
   "#pragma system_header ignored in main file">,
   InGroup>;
 
-def err_pragma_include_instead_not_sysheader : Error<
-  "'#pragma clang include_instead' cannot be used outside of system headers">;
-def err_pragma_include_instead_system_reserved : Error<
-  "header '%0' is an implementation detail; #include %select{'%2'|either '%2' "
-  "or '%3'|one of %2}1 instead">;
-
 def err_illegal_use_of_flt_eval_macro : Error<
   "'__FLT_EVAL_METHOD__' cannot be expanded inside a scope containing "
   "'#pragma clang fp eval_method'">;

diff  --git a/clang/include/clang/Basic/SourceManager.h 
b/clang/include/clang/Basic/SourceManager.h
index cc29c24f5a35f..3f3f1bb65c2c1 100644
--- a/clang/include/clang/Basic/SourceManager.h
+++ b/clang/include/clang/Basic/SourceManager.h
@@ -36,6 +36,7 @@
 
 #include "clang/Basic/Diagnostic.h"
 #include "clang/Basic/FileEntry.h"
+#include "clang/Basic/FileManager.h"
 #include "clang/Basic/SourceLocation.h"
 #include "llvm/ADT/ArrayRef.h"
 #include "llvm/ADT/BitVector.h"

diff  --git a/clang/include/clang/Lex/HeaderSearch.h 
b/clang/include/clang/Lex/HeaderSearch.h
index 3a170d2d3fa8d..e88e600ba2b97 100644
--- a/clang/include/clang/Lex/HeaderSearch.h
+++ b/clang/include/clang/Lex/HeaderSearch.h
@@ -20,9 +20,6 @@
 #include "clang/Lex/ModuleMap.h"
 #include "llvm/ADT/ArrayRef.h"
 #include "llvm/ADT/DenseMap.h"
-#include "llvm/ADT/SetVector.h"
-#include "llvm/ADT/SmallSet.h"
-#include "llvm/ADT/SmallString.h"
 #include "llvm/ADT/StringMap.h"
 #include "llvm/ADT/StringRef.h"
 #include "llvm/ADT/StringSet.h"
@@ -119,1

[PATCH] D123885: Revert "Revert "Revert "[clang][pp] adds '#pragma include_instead'"""

2022-04-22 Thread Christopher Di Bella 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 rGe9a902c7f755: Revert "Revert "Revert 
"[clang][pp] adds '#pragma include_instead'""" 
(authored by cjdb).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D123885

Files:
  clang-tools-extra/clangd/Selection.cpp
  clang-tools-extra/pseudo/lib/Lex.cpp
  clang/include/clang/Basic/DiagnosticLexKinds.td
  clang/include/clang/Basic/SourceManager.h
  clang/include/clang/Lex/HeaderSearch.h
  clang/include/clang/Lex/Lexer.h
  clang/include/clang/Lex/Preprocessor.h
  clang/include/clang/Lex/PreprocessorLexer.h
  clang/lib/Frontend/Rewrite/RewriteModernObjC.cpp
  clang/lib/Lex/Lexer.cpp
  clang/lib/Lex/PPDirectives.cpp
  clang/lib/Lex/PPLexerChange.cpp
  clang/lib/Lex/Pragma.cpp
  clang/test/PCH/ms-pch-macro-include_instead-regression.c
  clang/test/Preprocessor/Inputs/include_instead/bad-syntax.h
  clang/test/Preprocessor/Inputs/include_instead/file-not-found.h
  clang/test/Preprocessor/Inputs/include_instead/non-system-header.h
  clang/test/Preprocessor/Inputs/include_instead/private-x.h
  clang/test/Preprocessor/Inputs/include_instead/private1.h
  clang/test/Preprocessor/Inputs/include_instead/private2.h
  clang/test/Preprocessor/Inputs/include_instead/private3.h
  clang/test/Preprocessor/Inputs/include_instead/public-after.h
  clang/test/Preprocessor/Inputs/include_instead/public-before.h
  clang/test/Preprocessor/Inputs/include_instead/public-empty.h
  clang/test/Preprocessor/include_instead.cpp
  clang/test/Preprocessor/include_instead_file_not_found.cpp

Index: clang/test/Preprocessor/include_instead_file_not_found.cpp
===
--- clang/test/Preprocessor/include_instead_file_not_found.cpp
+++ /dev/null
@@ -1,2 +0,0 @@
-// RUN: %clang_cc1 -fsyntax-only -verify -I %S/Inputs %s
-#include 
Index: clang/test/Preprocessor/include_instead.cpp
===
--- clang/test/Preprocessor/include_instead.cpp
+++ /dev/null
@@ -1,16 +0,0 @@
-// RUN: %clang_cc1 -fsyntax-only -verify -I %S/Inputs %s
-
-#include 
-#include 
-
-#include 
-// expected-error@-1{{header '' is an implementation detail; #include '' instead}}
-
-#include "include_instead/private2.h"
-// expected-error@-1{{header '"include_instead/private2.h"' is an implementation detail; #include either '' or '"include_instead/public-after.h"' instead}}
-
-#include 
-// expected-error@-1{{header '' is an implementation detail; #include one of {'', '', '"include_instead/public-before.h"'} instead}}
-
-#include 
-#include 
Index: clang/test/Preprocessor/Inputs/include_instead/public-empty.h
===
--- clang/test/Preprocessor/Inputs/include_instead/public-empty.h
+++ /dev/null
@@ -1 +0,0 @@
-// This file simply needs to exist.
Index: clang/test/Preprocessor/Inputs/include_instead/public-before.h
===
--- clang/test/Preprocessor/Inputs/include_instead/public-before.h
+++ /dev/null
@@ -1,5 +0,0 @@
-#pragma GCC system_header
-
-#include  // no warning expected
-#include  // no warning expected
-#include  // no warning expected
Index: clang/test/Preprocessor/Inputs/include_instead/public-after.h
===
--- clang/test/Preprocessor/Inputs/include_instead/public-after.h
+++ /dev/null
@@ -1,2 +0,0 @@
-#include 
-#pragma GCC system_header
Index: clang/test/Preprocessor/Inputs/include_instead/private3.h
===
--- clang/test/Preprocessor/Inputs/include_instead/private3.h
+++ /dev/null
@@ -1,5 +0,0 @@
-#pragma GCC system_header
-
-#pragma clang include_instead()
-#pragma clang include_instead()
-#pragma clang include_instead("include_instead/public-before.h")
Index: clang/test/Preprocessor/Inputs/include_instead/private2.h
===
--- clang/test/Preprocessor/Inputs/include_instead/private2.h
+++ /dev/null
@@ -1,4 +0,0 @@
-#pragma GCC system_header
-
-#pragma clang include_instead()
-#pragma clang include_instead("include_instead/public-after.h")
Index: clang/test/Preprocessor/Inputs/include_instead/private1.h
===
--- clang/test/Preprocessor/Inputs/include_instead/private1.h
+++ /dev/null
@@ -1,2 +0,0 @@
-#pragma GCC system_header
-#pragma clang include_instead()
Index: clang/test/Preprocessor/Inputs/include_instead/private-x.h
===
--- clang/test/Preprocessor/Inputs/include_instead/private-x.h
+++ /dev/null
@@ -1,4 +0,0 @@
-#include 
-
-#pragma GCC system_header
-#pragma clang include_instead()
Index: clang/test/Pre

[PATCH] D124221: Add new builtin __builtin_reflect_struct.

2022-04-22 Thread Erich Keane via Phabricator via cfe-commits
erichkeane added a comment.

>> I think you've misunderstood; that is not required. Though with the design 
>> as-is, it might make sense to restrict this to being C++-only, given that 
>> there's not really a way to effectively use this from C.

Ah, I see the example in SemaCXX.  its sad we can't do this from C, I would 
consider the use case of `__builtin_dump_struct` to be very handy in C.

I guess I think I would want to start off with, "what do we see the 'usecase' 
of these builtins" being.  `__builtin_dump_struct` to me seems to have a pretty 
clear and semantically enforced one: its useful to printf it for debugging 
purposes.

This seems to be more useful-enough that it leaves me feeling like users would 
very quickly fall into, "man, I wish this did more" because of it.  Its just a 
shame we can't get SG7 to work quicker :)




Comment at: clang/docs/LanguageExtensions.rst:2434
+
+ bool print(int arg1, int arg2, std::initializer_list fields) {
+   for (auto f : fields) {

rsmith wrote:
> erichkeane wrote:
> > I'm curious as to the need for the 'arg1' and 'arg2'?  Also, what is the 
> > type of the 'fields' array that works in C?
> This is aimed to fix a major deficiency in `__builtin_dump_struct`, that 
> there's no way to pass information into its callback (other than stashing it 
> in TLS).
> 
> As noted in the patch description, this builtin is not especially usable in 
> C. I'm not sure whether that's fixable, given the very limited 
> metaprogramming support in C.
Presumably one could also put it in the functor for the callback, or even as a 
capture in the lambda.  Though, I'm not positive I see the VALUE to passing 
this information, but was just curious as to the intent.



Comment at: clang/docs/LanguageExtensions.rst:2437
+ std::cout << f.name;
+ if (f.bitwidth)
+   std::cout << " : " << f.bitwidth;

rsmith wrote:
> erichkeane wrote:
> > Hmm... what is the type of f.bitwidth?  A zero-length bitwidth is a valid 
> > thing, so having it just be an 'int' doesn't seem workable.
> It's a `size_t`. There are no zero-size bitfield members. (Unnamed bitfield 
> aren't members, so are excluded here.) In any case, you can tell the 
> difference between a bitfield and a regular member by the length of the 
> initialiser list; we don't pass a bit width for non-bit-field members.
>>There are no zero-size bitfield members. (Unnamed bitfield aren't members, so 
>>are excluded here.)
Hrm... Semantically YES, lexically I'm not sure folks make that 
differentiation.  One issue with skipping 'unnamed bitfields' is it makes 
something like:

```
struct Foo {
int : 31; // Take up some space so something else could have been put there.
int field : 1; 
int field2 : 2;
};
```
and comparing `sizeof` the type with the output to be... jarring at least.

>> you can tell the difference between a bitfield and a regular member by the 
>> length of the initialiser list;

I see now how you've done that with ctors in C++.  It feels that the way of 
doing this in C is unfortunately quite clunky (in addition, not being able to 
use arbitrary types).



Comment at: clang/docs/LanguageExtensions.rst:2462
+to the type to reflect. The second argument ``f`` should be some callable
+expression, and can be a function object or an overload set. The builtin calls
+``f``, passing any further arguments ``args...`` followed by an initializer

rsmith wrote:
> erichkeane wrote:
> > Is the purpose of the overload set/functor so you can support multiple 
> > types (seeing how the 'base' below works)?  How does this all work in C? 
> > (or do we just do fields in C, since they cannot have the rest?
> > 
> > I wonder if we would be better if we treated this function as a 'callback' 
> > or a 'callback set' that returned a discriminated union of a pre-defined 
> > type that describes what is being returned.  That way it could handle 
> > member functions, static variables, etc.
> This doesn't really work well in C, as noted in the patch description. A set 
> of callbacks might work a bit better across both languages, but I don't think 
> it solves the larger problem that there's no good way to pass type 
> information into a callback in C.
Well, if the callback itself took the discriminated union for each thing, and 
we did 1 callback per base/field/etc, perhaps that would be useful? I just am 
having a hard time seeing this being all that useful in C, which is a shame.





Comment at: clang/docs/LanguageExtensions.rst:2471
+
+The initializer list contains the following components:
+

rsmith wrote:
> erichkeane wrote:
> > I find myself wishing this was a more complete list.
> What else do you want? My goal here was to be able to do what 
> `__builtin_dump_struct` does but without its many arbitrary limitations. From 
> C++, this is enough for that.
I think this is again falling down

[PATCH] D124258: [C89/C2x] Change the behavior of implicit int diagnostics

2022-04-22 Thread Corentin Jabot via Phabricator via cfe-commits
cor3ntin added inline comments.



Comment at: clang/include/clang/Basic/LangOptions.h:534
+  /// Returns true if implicit int is supported at all.
+  bool implicitIntEnabled() const { return !CPlusPlus && !C2x; }
+

aaron.ballman wrote:
> erichkeane wrote:
> > cor3ntin wrote:
> > > erichkeane wrote:
> > > > This name seems inverse of what you mean to me?  IDK if you're 
> > > > bike-shed-sniping me here, but:
> > > > 
> > > > `prohibitsImplicitInt` to be the reverse of above? It becomes SLIGHTLY 
> > > > ambiguous to me (in that we don't mean "the language standard 
> > > > prohibits", we mean "the compiler implementation prohibits"), but that 
> > > > can be fixed up with a comment.
> > > > 
> > > > If you want to keep the direction, perhaps `implicitIntPermitted`, at 
> > > > which point I might suggest the one above become `implicitIntRequired`.
> > > @erichkeane `requiresImplicitInt` is only used twice. Does it needs a 
> > > name?
> > > 
> > *shrug*, I tend to be of the feeling that if you have to say something this 
> > often, and functions are basically free, mind as well make one.
> The idea here is that `requiresImplicitInt()` tells you when the support is 
> mandatory per spec, and `implicitIntEnabled()` tells you when the support is 
> either mandatory or an extension. I'm not strongly tied to the names, how do 
> these sound?
> 
> `isImplicitIntRequired()` and `isImplicitIntAllowed()`?
> 
> (I could also add the word `Support` in there as in 
> `isImplicitIntSupportRequired()` but then the function names start to get a 
> bit longer than I think is reasonable.)
`implicitIntEnabled` makes sense to me. I guess my question is, is there 
precedence for options for language-mandated features?


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

https://reviews.llvm.org/D124258

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


[PATCH] D124258: [C89/C2x] Change the behavior of implicit int diagnostics

2022-04-22 Thread Erich Keane via Phabricator via cfe-commits
erichkeane added inline comments.



Comment at: clang/docs/ReleaseNotes.rst:169
+  As of C2x, support for implicit int has been removed, and the warning options
+  will have no effect. Specifying ``-Wimplicit-int`` in C89 mode will now issue
+  warnings instead of being a noop.

aaron.ballman wrote:
> erichkeane wrote:
> > I find myself thinking that despite it being 'valid code' that 
> > `-Wimplicit-int` should be on-by-default in C89 mode. We often warn about 
> > 'valid, but non-future-proof' code, by default, particularly when they are 
> > code-breaking like this is.
> On the one hand, yes. On the other hand, this is only for people who specify 
> `-std=c89` explicitly (which is not the default language mode for C), and I 
> think we've been taking the viewpoint that these folks are mostly trying to 
> keep old, mostly unmaintained code working.
I'm annoyed by how much I understand/agree with both sides of this argument.  



Comment at: clang/include/clang/Basic/LangOptions.h:534
+  /// Returns true if implicit int is supported at all.
+  bool implicitIntEnabled() const { return !CPlusPlus && !C2x; }
+

aaron.ballman wrote:
> erichkeane wrote:
> > cor3ntin wrote:
> > > erichkeane wrote:
> > > > This name seems inverse of what you mean to me?  IDK if you're 
> > > > bike-shed-sniping me here, but:
> > > > 
> > > > `prohibitsImplicitInt` to be the reverse of above? It becomes SLIGHTLY 
> > > > ambiguous to me (in that we don't mean "the language standard 
> > > > prohibits", we mean "the compiler implementation prohibits"), but that 
> > > > can be fixed up with a comment.
> > > > 
> > > > If you want to keep the direction, perhaps `implicitIntPermitted`, at 
> > > > which point I might suggest the one above become `implicitIntRequired`.
> > > @erichkeane `requiresImplicitInt` is only used twice. Does it needs a 
> > > name?
> > > 
> > *shrug*, I tend to be of the feeling that if you have to say something this 
> > often, and functions are basically free, mind as well make one.
> The idea here is that `requiresImplicitInt()` tells you when the support is 
> mandatory per spec, and `implicitIntEnabled()` tells you when the support is 
> either mandatory or an extension. I'm not strongly tied to the names, how do 
> these sound?
> 
> `isImplicitIntRequired()` and `isImplicitIntAllowed()`?
> 
> (I could also add the word `Support` in there as in 
> `isImplicitIntSupportRequired()` but then the function names start to get a 
> bit longer than I think is reasonable.)
>> The idea here is that requiresImplicitInt() tells you when the support is 
>> mandatory per spec, and implicitIntEnabled() tells you when the support is 
>> either mandatory or an extension. I'm not strongly tied to the names, how do 
>> these sound?

Well, as it is now, the latter tells you whether 'it is allowed as an 
extension'.


>>`isImplicitIntRequired()` and `isImplicitIntAllowed()`?

These seem pretty clear to me.  I don't see 'Support' as being valuable.




Comment at: clang/lib/Sema/SemaDecl.cpp:14329
   if (FTI.Params[i].Param == nullptr) {
-SmallString<256> Code;
-llvm::raw_svector_ostream(Code)
-<< "  int " << FTI.Params[i].Ident->getName() << ";\n";
-Diag(FTI.Params[i].IdentLoc, diag::ext_param_not_declared)
-<< FTI.Params[i].Ident
-<< FixItHint::CreateInsertion(LocAfterDecls, Code);
+if (getLangOpts().C99) {
+  SmallString<256> Code;

aaron.ballman wrote:
> erichkeane wrote:
> > cor3ntin wrote:
> > > erichkeane wrote:
> > > > IMO there should be a warning here for C89.  Warning for 
> > > > non-future-proof code is pretty typical.
> > > Isn't the counter argument that was made on similar changes that people 
> > > specifically asking for C89 have peculiar expectations?
> > > Otherwise i agree
> > Yep, folks asking for C89 ARE peculiar :D  However, warnings-not-as-error 
> > are, IMO, simply 'helpful'. 
> Same here as above -- we *could* warn, but I suspect it wouldn't be 
> particularly helpful. The fact that we were warning with an extension warning 
> was non-conforming though (we shouldn't fail `-pedantic-errors` in C89 over 
> that).
*grumble grumble*.


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

https://reviews.llvm.org/D124258

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


[PATCH] D123667: [clang][AST] Fix crash getting name of a template decl

2022-04-22 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, with a commenting nit. The Precommit CI test failures look unrelated to 
me as well.

Do you need me to commit on your behalf? If so, what name and email address 
would you like me to use for patch attribution? (I can fix the commenting issue 
when I land, so don't worry about pushing up a new patch.)




Comment at: clang/unittests/AST/TypePrinterTest.cpp:74-75
+
+  // regression test ensuring we do not segfault getting the qualtype as a
+  // string
+  ASSERT_TRUE(PrintedTypeMatches(Code, {}, Matcher, "",




Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D123667

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


[PATCH] D123667: [clang][AST] Fix crash getting name of a template decl

2022-04-22 Thread Tom Eccles via Phabricator via cfe-commits
tblah added a comment.

Yes please commit on my behalf. My details are

Tom Eccles

tom.ecc...@codethink.co.uk

Thanks


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D123667

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


[PATCH] D124258: [C89/C2x] Change the behavior of implicit int diagnostics

2022-04-22 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman marked 7 inline comments as done.
aaron.ballman added inline comments.



Comment at: clang/include/clang/Basic/LangOptions.h:534
+  /// Returns true if implicit int is supported at all.
+  bool implicitIntEnabled() const { return !CPlusPlus && !C2x; }
+

cor3ntin wrote:
> erichkeane wrote:
> > aaron.ballman wrote:
> > > erichkeane wrote:
> > > > cor3ntin wrote:
> > > > > erichkeane wrote:
> > > > > > This name seems inverse of what you mean to me?  IDK if you're 
> > > > > > bike-shed-sniping me here, but:
> > > > > > 
> > > > > > `prohibitsImplicitInt` to be the reverse of above? It becomes 
> > > > > > SLIGHTLY ambiguous to me (in that we don't mean "the language 
> > > > > > standard prohibits", we mean "the compiler implementation 
> > > > > > prohibits"), but that can be fixed up with a comment.
> > > > > > 
> > > > > > If you want to keep the direction, perhaps `implicitIntPermitted`, 
> > > > > > at which point I might suggest the one above become 
> > > > > > `implicitIntRequired`.
> > > > > @erichkeane `requiresImplicitInt` is only used twice. Does it needs a 
> > > > > name?
> > > > > 
> > > > *shrug*, I tend to be of the feeling that if you have to say something 
> > > > this often, and functions are basically free, mind as well make one.
> > > The idea here is that `requiresImplicitInt()` tells you when the support 
> > > is mandatory per spec, and `implicitIntEnabled()` tells you when the 
> > > support is either mandatory or an extension. I'm not strongly tied to the 
> > > names, how do these sound?
> > > 
> > > `isImplicitIntRequired()` and `isImplicitIntAllowed()`?
> > > 
> > > (I could also add the word `Support` in there as in 
> > > `isImplicitIntSupportRequired()` but then the function names start to get 
> > > a bit longer than I think is reasonable.)
> > >> The idea here is that requiresImplicitInt() tells you when the support 
> > >> is mandatory per spec, and implicitIntEnabled() tells you when the 
> > >> support is either mandatory or an extension. I'm not strongly tied to 
> > >> the names, how do these sound?
> > 
> > Well, as it is now, the latter tells you whether 'it is allowed as an 
> > extension'.
> > 
> > 
> > >>`isImplicitIntRequired()` and `isImplicitIntAllowed()`?
> > 
> > These seem pretty clear to me.  I don't see 'Support' as being valuable.
> > 
> `implicitIntEnabled` makes sense to me. I guess my question is, is there 
> precedence for options for language-mandated features?
> I guess my question is, is there precedence for options for language-mandated 
> features?

Sure, though many of them also have user-facing command line flags to set the 
options. (wchar_t support, digraphs, etc)

I added these as helper functions mostly because there's no way to have 
language options whose default value is dependent on other language options.


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

https://reviews.llvm.org/D124258

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


[PATCH] D124258: [C89/C2x] Change the behavior of implicit int diagnostics

2022-04-22 Thread Erich Keane via Phabricator via cfe-commits
erichkeane accepted this revision.
erichkeane added a comment.
This revision is now accepted and ready to land.

I'm happy enough.  I see both sides of the C89 debate enough to 'disagree and 
commit' on that one.


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

https://reviews.llvm.org/D124258

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


[clang] 225b91e - Fix crash getting name of a template decl

2022-04-22 Thread Aaron Ballman via cfe-commits

Author: Tom Eccles
Date: 2022-04-22T13:03:28-04:00
New Revision: 225b91e6cbba31ff1ce787a152a67977d08fdcab

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

LOG: Fix crash getting name of a template decl

NamedDecl::getIdentifier can return a nullptr when
DeclarationName::isIdentifier is false, which leads to a null pointer
dereference when TypePrinter::printTemplateId calls ->getName().

NamedDecl::getName does the same thing in the successful case and
returns an empty string in the failure case.

This crash affects the llvm 14 packages on llvm.org.

Added: 


Modified: 
clang/lib/AST/TypePrinter.cpp
clang/unittests/AST/TypePrinterTest.cpp

Removed: 




diff  --git a/clang/lib/AST/TypePrinter.cpp b/clang/lib/AST/TypePrinter.cpp
index 32ca7643a7603..d2feb1c10f06c 100644
--- a/clang/lib/AST/TypePrinter.cpp
+++ b/clang/lib/AST/TypePrinter.cpp
@@ -1467,8 +1467,7 @@ void TypePrinter::printTemplateId(const 
TemplateSpecializationType *T,
 if (!Policy.SuppressScope)
   AppendScope(TD->getDeclContext(), OS, TD->getDeclName());
 
-IdentifierInfo *II = TD->getIdentifier();
-OS << II->getName();
+OS << TD->getName();
   } else {
 T->getTemplateName().print(OS, Policy);
   }

diff  --git a/clang/unittests/AST/TypePrinterTest.cpp 
b/clang/unittests/AST/TypePrinterTest.cpp
index 7b44b1ecece24..12801a7018125 100644
--- a/clang/unittests/AST/TypePrinterTest.cpp
+++ b/clang/unittests/AST/TypePrinterTest.cpp
@@ -64,6 +64,22 @@ TEST(TypePrinter, TemplateId) {
   [](PrintingPolicy &Policy) { Policy.FullyQualifiedName = true; }));
 }
 
+TEST(TypePrinter, TemplateId2) {
+  std::string Code = R"cpp(
+  template  class TemplatedType>
+  void func(TemplatedType Param);
+)cpp";
+  auto Matcher = parmVarDecl(hasType(qualType().bind("id")));
+
+  // Regression test ensuring we do not segfault getting the QualType as a
+  // string.
+  ASSERT_TRUE(PrintedTypeMatches(Code, {}, Matcher, "",
+ [](PrintingPolicy &Policy) {
+   Policy.FullyQualifiedName = true;
+   Policy.PrintCanonicalTypes = true;
+ }));
+}
+
 TEST(TypePrinter, ParamsUglified) {
   llvm::StringLiteral Code = R"cpp(
 template  class __f>



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


[PATCH] D123667: [clang][AST] Fix crash getting name of a template decl

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

Thank you for the fix! I've commit on your behalf in 
225b91e6cbba31ff1ce787a152a67977d08fdcab 
.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D123667

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


[PATCH] D124221: Add new builtin __builtin_reflect_struct.

2022-04-22 Thread Richard Smith - zygoloid via Phabricator via cfe-commits
rsmith added inline comments.



Comment at: clang/docs/LanguageExtensions.rst:2434
+
+ bool print(int arg1, int arg2, std::initializer_list fields) {
+   for (auto f : fields) {

erichkeane wrote:
> rsmith wrote:
> > erichkeane wrote:
> > > I'm curious as to the need for the 'arg1' and 'arg2'?  Also, what is the 
> > > type of the 'fields' array that works in C?
> > This is aimed to fix a major deficiency in `__builtin_dump_struct`, that 
> > there's no way to pass information into its callback (other than stashing 
> > it in TLS).
> > 
> > As noted in the patch description, this builtin is not especially usable in 
> > C. I'm not sure whether that's fixable, given the very limited 
> > metaprogramming support in C.
> Presumably one could also put it in the functor for the callback, or even as 
> a capture in the lambda.  Though, I'm not positive I see the VALUE to passing 
> this information, but was just curious as to the intent.
Suppose you want to dump a struct to a log file, or you want the dump in a 
string. Or you want to carry along an indentation level. My first attempt at 
using `__builtin_dump_struct` essentially failed because it doesn't have 
anything like this; even if we don't want this patch, this is functionality we 
should add to that builtin.



Comment at: clang/docs/LanguageExtensions.rst:2462
+to the type to reflect. The second argument ``f`` should be some callable
+expression, and can be a function object or an overload set. The builtin calls
+``f``, passing any further arguments ``args...`` followed by an initializer

erichkeane wrote:
> rsmith wrote:
> > erichkeane wrote:
> > > Is the purpose of the overload set/functor so you can support multiple 
> > > types (seeing how the 'base' below works)?  How does this all work in C? 
> > > (or do we just do fields in C, since they cannot have the rest?
> > > 
> > > I wonder if we would be better if we treated this function as a 
> > > 'callback' or a 'callback set' that returned a discriminated union of a 
> > > pre-defined type that describes what is being returned.  That way it 
> > > could handle member functions, static variables, etc.
> > This doesn't really work well in C, as noted in the patch description. A 
> > set of callbacks might work a bit better across both languages, but I don't 
> > think it solves the larger problem that there's no good way to pass type 
> > information into a callback in C.
> Well, if the callback itself took the discriminated union for each thing, and 
> we did 1 callback per base/field/etc, perhaps that would be useful? I just am 
> having a hard time seeing this being all that useful in C, which is a shame.
> 
> 
I think that would work. I'm not sure it would be better, though, given that it 
loses the ability to build a type whose shape depends on the number of bases 
and fields, because you're not given them all at once. (Eg, if you want to 
build a static array of field names.)



Comment at: clang/docs/LanguageExtensions.rst:2473
+
+* For each direct base class, the address of the base class, in declaration
+  order.

erichkeane wrote:
> rsmith wrote:
> > erichkeane wrote:
> > > I wonder if bases should include their virtualness or access specifier.
> > I mean, maybe, but I don't have a use case for either. For access in 
> > general my leaning is to say that the built-in doesn't get special access 
> > rights -- either it can access everything or you'll get an access error if 
> > you use it -- in which case including the access for bases and fields 
> > doesn't seem likely to be super useful.
> I guess it depends on the use case for these builtins.  I saw the 
> 'dump-struct' builtin's purpose was for quick & dirty printf-debugging.  At 
> which point the format/features were less important than the action.  So from 
> that perspective, I would see this having 'special access rights' as sort of 
> a necessity.  
> 
> Though again, this is a significantly more general builtin, which comes with 
> additional potential use cases.
The use cases are the things that `__builtin_dump_struct` gets close to but 
fails at, such as: I have an `EXPECT_EQ` macro that I'd like to log the 
difference in input and output values where possible, or I want to build a 
simple print-to-string utility for structs. Or I want a dump to stout but I 
want it formatted differently from what `__builtin_dump_struct` thinks is best.

The fact that the dump built-in gets us into this area but can't solve these 
problems is frustrating.



Comment at: clang/lib/Sema/SemaChecking.cpp:420
+auto *FD = IFD ? IFD->getAnonField() : dyn_cast(D);
+if (!FD || (FD->isUnnamedBitfield() || FD->isAnonymousStructOrUnion()))
+  continue;

erichkeane wrote:
> rsmith wrote:
> > erichkeane wrote:
> > > Losing the unnamed bitfield is unfortunate, and I the 'dump struct' 
> > > handles.  As is losin

[PATCH] D124186: [RISCV] Fix incorrect policy implement for unmasked vslidedown and vslideup.

2022-04-22 Thread Zakk Chen via Phabricator via cfe-commits
khchen updated this revision to Diff 424517.
khchen edited the summary of this revision.
khchen added a comment.

update clang tests.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124186

Files:
  clang/include/clang/Basic/riscv_vector.td
  clang/test/CodeGen/RISCV/rvv-intrinsics-overloaded/vslidedown.c
  clang/test/CodeGen/RISCV/rvv-intrinsics-overloaded/vslideup.c
  clang/test/CodeGen/RISCV/rvv-intrinsics/vslidedown.c
  clang/test/CodeGen/RISCV/rvv-intrinsics/vslideup.c
  llvm/include/llvm/IR/IntrinsicsRISCV.td
  llvm/lib/Target/RISCV/RISCVInstrInfoVPseudos.td
  llvm/lib/Target/RISCV/RISCVInstrInfoVVLPatterns.td
  llvm/test/CodeGen/RISCV/rvv/emergency-slot.mir
  llvm/test/CodeGen/RISCV/rvv/extract-subvector.ll
  llvm/test/CodeGen/RISCV/rvv/fixed-vectors-calling-conv.ll
  llvm/test/CodeGen/RISCV/rvv/fixed-vectors-extload-truncstore.ll
  llvm/test/CodeGen/RISCV/rvv/fixed-vectors-extract-subvector.ll
  llvm/test/CodeGen/RISCV/rvv/fixed-vectors-fp-buildvec.ll
  llvm/test/CodeGen/RISCV/rvv/fixed-vectors-fp-conv.ll
  llvm/test/CodeGen/RISCV/rvv/fixed-vectors-fp-setcc.ll
  llvm/test/CodeGen/RISCV/rvv/fixed-vectors-fp-shuffles.ll
  llvm/test/CodeGen/RISCV/rvv/fixed-vectors-fp2i.ll
  llvm/test/CodeGen/RISCV/rvv/fixed-vectors-i2fp.ll
  llvm/test/CodeGen/RISCV/rvv/fixed-vectors-insert-i1.ll
  llvm/test/CodeGen/RISCV/rvv/fixed-vectors-insert-subvector.ll
  llvm/test/CodeGen/RISCV/rvv/fixed-vectors-insert.ll
  llvm/test/CodeGen/RISCV/rvv/fixed-vectors-int-buildvec.ll
  llvm/test/CodeGen/RISCV/rvv/fixed-vectors-int-exttrunc.ll
  llvm/test/CodeGen/RISCV/rvv/fixed-vectors-int-shuffles.ll
  llvm/test/CodeGen/RISCV/rvv/fixed-vectors-int.ll
  llvm/test/CodeGen/RISCV/rvv/fixed-vectors-mask-buildvec.ll
  llvm/test/CodeGen/RISCV/rvv/fixed-vectors-mask-load-store.ll
  llvm/test/CodeGen/RISCV/rvv/fixed-vectors-mask-splat.ll
  llvm/test/CodeGen/RISCV/rvv/fixed-vectors-masked-gather.ll
  llvm/test/CodeGen/RISCV/rvv/fixed-vectors-unaligned.ll
  llvm/test/CodeGen/RISCV/rvv/fixed-vectors-vpgather.ll
  llvm/test/CodeGen/RISCV/rvv/insert-subvector.ll
  llvm/test/CodeGen/RISCV/rvv/insertelt-fp-rv32.ll
  llvm/test/CodeGen/RISCV/rvv/insertelt-fp-rv64.ll
  llvm/test/CodeGen/RISCV/rvv/insertelt-i1.ll
  llvm/test/CodeGen/RISCV/rvv/insertelt-int-rv32.ll
  llvm/test/CodeGen/RISCV/rvv/insertelt-int-rv64.ll
  llvm/test/CodeGen/RISCV/rvv/masked-tama.ll
  llvm/test/CodeGen/RISCV/rvv/setcc-fp.ll
  llvm/test/CodeGen/RISCV/rvv/setcc-integer.ll
  llvm/test/CodeGen/RISCV/rvv/unmasked-ta.ll
  llvm/test/CodeGen/RISCV/rvv/vector-splice.ll
  llvm/test/CodeGen/RISCV/rvv/vslidedown-rv32.ll
  llvm/test/CodeGen/RISCV/rvv/vslidedown-rv64.ll
  llvm/test/CodeGen/RISCV/rvv/vslideup-rv32.ll
  llvm/test/CodeGen/RISCV/rvv/vslideup-rv64.ll

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


[PATCH] D123787: [clang][OpenMP][DebugInfo] Debug support for TLS variables when present in OpenMP consructs

2022-04-22 Thread Adrian Prantl via Phabricator via cfe-commits
aprantl accepted this revision.
aprantl added a comment.
This revision is now accepted and ready to land.

Oh, it's a //global// variable that supposed to shadow the function parameter! 
Thanks for clarifying.


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

https://reviews.llvm.org/D123787

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


[PATCH] D124221: Add new builtin __builtin_reflect_struct.

2022-04-22 Thread Richard Smith - zygoloid via Phabricator via cfe-commits
rsmith added inline comments.



Comment at: clang/lib/Sema/SemaChecking.cpp:420
+auto *FD = IFD ? IFD->getAnonField() : dyn_cast(D);
+if (!FD || (FD->isUnnamedBitfield() || FD->isAnonymousStructOrUnion()))
+  continue;

rsmith wrote:
> erichkeane wrote:
> > rsmith wrote:
> > > erichkeane wrote:
> > > > Losing the unnamed bitfield is unfortunate, and I the 'dump struct' 
> > > > handles.  As is losing the anonymous struct/union.
> > > > 
> > > > Also, how does this handle 'record type' members?  Does the user have 
> > > > to know the inner type already?  If they already know that much 
> > > > information about the type, they wouldn't really need this, right?
> > > If `__builtin_dump_struct` includes unnamed bitfields, that's a bug in 
> > > that builtin.
> > > 
> > > In general, the user function gets given the bases and members with the 
> > > right types, so they can use an overload set or a template to dispatch 
> > > based on that type. See the SemaCXX test for a basic example of that.
> > I thought it did?  For the use case I see `__builtin_dump_struct` having, I 
> > would think printing the existence of unnamed bitfields to be quite useful.
> > 
> > 
> Why? They're not part of the value, they're just padding.
Looks like `__builtin_dump_struct` currently includes them *and* prints a value 
(whatever garbage happens to be in those padding bits). That's obviously a bug.


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: Add new builtin __builtin_reflect_struct.

2022-04-22 Thread Erich Keane via Phabricator via cfe-commits
erichkeane added inline comments.



Comment at: clang/docs/LanguageExtensions.rst:2434
+
+ bool print(int arg1, int arg2, std::initializer_list fields) {
+   for (auto f : fields) {

rsmith wrote:
> erichkeane wrote:
> > rsmith wrote:
> > > erichkeane wrote:
> > > > I'm curious as to the need for the 'arg1' and 'arg2'?  Also, what is 
> > > > the type of the 'fields' array that works in C?
> > > This is aimed to fix a major deficiency in `__builtin_dump_struct`, that 
> > > there's no way to pass information into its callback (other than stashing 
> > > it in TLS).
> > > 
> > > As noted in the patch description, this builtin is not especially usable 
> > > in C. I'm not sure whether that's fixable, given the very limited 
> > > metaprogramming support in C.
> > Presumably one could also put it in the functor for the callback, or even 
> > as a capture in the lambda.  Though, I'm not positive I see the VALUE to 
> > passing this information, but was just curious as to the intent.
> Suppose you want to dump a struct to a log file, or you want the dump in a 
> string. Or you want to carry along an indentation level. My first attempt at 
> using `__builtin_dump_struct` essentially failed because it doesn't have 
> anything like this; even if we don't want this patch, this is functionality 
> we should add to that builtin.
Ah, I see!  Sure, I can see how those are useful, though again, mostly to the C 
implementation (as those should all be part of the functor's state), and this 
doesn't work particularly well in C.



Comment at: clang/docs/LanguageExtensions.rst:2462
+to the type to reflect. The second argument ``f`` should be some callable
+expression, and can be a function object or an overload set. The builtin calls
+``f``, passing any further arguments ``args...`` followed by an initializer

rsmith wrote:
> erichkeane wrote:
> > rsmith wrote:
> > > erichkeane wrote:
> > > > Is the purpose of the overload set/functor so you can support multiple 
> > > > types (seeing how the 'base' below works)?  How does this all work in 
> > > > C? (or do we just do fields in C, since they cannot have the rest?
> > > > 
> > > > I wonder if we would be better if we treated this function as a 
> > > > 'callback' or a 'callback set' that returned a discriminated union of a 
> > > > pre-defined type that describes what is being returned.  That way it 
> > > > could handle member functions, static variables, etc.
> > > This doesn't really work well in C, as noted in the patch description. A 
> > > set of callbacks might work a bit better across both languages, but I 
> > > don't think it solves the larger problem that there's no good way to pass 
> > > type information into a callback in C.
> > Well, if the callback itself took the discriminated union for each thing, 
> > and we did 1 callback per base/field/etc, perhaps that would be useful? I 
> > just am having a hard time seeing this being all that useful in C, which is 
> > a shame.
> > 
> > 
> I think that would work. I'm not sure it would be better, though, given that 
> it loses the ability to build a type whose shape depends on the number of 
> bases and fields, because you're not given them all at once. (Eg, if you want 
> to build a static array of field names.)
Yep, thats definitely true. There are ways to DO that (either a 2-pass at this 
to get the sizes, allocate something, then go through again filling in your 
struct OR a constant 'append' thing with a `vector` like type), but I see what 
you mean.  It seems that either case we are limiting a couple of useful use 
cases.



Comment at: clang/docs/LanguageExtensions.rst:2473
+
+* For each direct base class, the address of the base class, in declaration
+  order.

rsmith wrote:
> erichkeane wrote:
> > rsmith wrote:
> > > erichkeane wrote:
> > > > I wonder if bases should include their virtualness or access specifier.
> > > I mean, maybe, but I don't have a use case for either. For access in 
> > > general my leaning is to say that the built-in doesn't get special access 
> > > rights -- either it can access everything or you'll get an access error 
> > > if you use it -- in which case including the access for bases and fields 
> > > doesn't seem likely to be super useful.
> > I guess it depends on the use case for these builtins.  I saw the 
> > 'dump-struct' builtin's purpose was for quick & dirty printf-debugging.  At 
> > which point the format/features were less important than the action.  So 
> > from that perspective, I would see this having 'special access rights' as 
> > sort of a necessity.  
> > 
> > Though again, this is a significantly more general builtin, which comes 
> > with additional potential use cases.
> The use cases are the things that `__builtin_dump_struct` gets close to but 
> fails at, such as: I have an `EXPECT_EQ` macro that I'd like to log the 
> difference in input and output va

[PATCH] D120272: [CUDA] Add driver support for compiling CUDA with the new driver

2022-04-22 Thread Artem Belevich via Phabricator via cfe-commits
tra added inline comments.



Comment at: clang/lib/Driver/ToolChains/Clang.cpp:6223-6224
   if (IsCuda || IsHIP) {
-if (Args.hasFlag(options::OPT_fgpu_rdc, options::OPT_fno_gpu_rdc, false))
+if (Args.hasFlag(options::OPT_fgpu_rdc, options::OPT_fno_gpu_rdc, false) ||
+Args.hasArg(options::OPT_foffload_new_driver))
   CmdArgs.push_back("-fgpu-rdc");

If user specifies both `-fno-gpu-rdc` and `-foffload-new-driver` we would still 
enable RDC compilation.
We may want to at least issue a warning. 

Considering that  we have multiple places where we may check for 
`-f[no]gpu-rdc` we should make sure we don't get different ideas whether RDC 
has been enabled.
I think it may make sense to provide a common way to figure it out. Either via 
a helper function that would process CLI arguments or calculate it once and 
save it somewhere.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D120272

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


[PATCH] D120272: [CUDA] Add driver support for compiling CUDA with the new driver

2022-04-22 Thread Joseph Huber via Phabricator via cfe-commits
jhuber6 added inline comments.



Comment at: clang/lib/Driver/ToolChains/Clang.cpp:6223-6224
   if (IsCuda || IsHIP) {
-if (Args.hasFlag(options::OPT_fgpu_rdc, options::OPT_fno_gpu_rdc, false))
+if (Args.hasFlag(options::OPT_fgpu_rdc, options::OPT_fno_gpu_rdc, false) ||
+Args.hasArg(options::OPT_foffload_new_driver))
   CmdArgs.push_back("-fgpu-rdc");

tra wrote:
> If user specifies both `-fno-gpu-rdc` and `-foffload-new-driver` we would 
> still enable RDC compilation.
> We may want to at least issue a warning. 
> 
> Considering that  we have multiple places where we may check for 
> `-f[no]gpu-rdc` we should make sure we don't get different ideas whether RDC 
> has been enabled.
> I think it may make sense to provide a common way to figure it out. Either 
> via a helper function that would process CLI arguments or calculate it once 
> and save it somewhere.
I haven't quite finalized how to handle this. The new driver should be 
compatible with a non-RDC build since we simply wouldn't embed the device image 
or create offloading entries. It's a little bit more difficult here since the 
new method is opt-in so it requires a flag. We should definitely emit a warning 
if both are enabled (I'm assuming there's one for passing both `fgpu-rdc` and 
`fno-gpu-rdc`). I'll add one in.

Also we could consider the new driver *the* RDC in the future which would be 
the easiest. The problem is if we want to support CUDA's method of RDC 
considering how other build systems seem to expect it. I could see us embedding 
the fatbinary in the object file, even if unused, just so that cuobjdump works. 
However we couldn't support the generation of `__cudaRegisterFatBinary_nv` 
functions because then those would cause linker errors. WDYT?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D120272

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


[PATCH] D120272: [CUDA] Add driver support for compiling CUDA with the new driver

2022-04-22 Thread Artem Belevich via Phabricator via cfe-commits
tra added inline comments.



Comment at: clang/lib/Driver/ToolChains/Clang.cpp:6223-6224
   if (IsCuda || IsHIP) {
-if (Args.hasFlag(options::OPT_fgpu_rdc, options::OPT_fno_gpu_rdc, false))
+if (Args.hasFlag(options::OPT_fgpu_rdc, options::OPT_fno_gpu_rdc, false) ||
+Args.hasArg(options::OPT_foffload_new_driver))
   CmdArgs.push_back("-fgpu-rdc");

jhuber6 wrote:
> tra wrote:
> > If user specifies both `-fno-gpu-rdc` and `-foffload-new-driver` we would 
> > still enable RDC compilation.
> > We may want to at least issue a warning. 
> > 
> > Considering that  we have multiple places where we may check for 
> > `-f[no]gpu-rdc` we should make sure we don't get different ideas whether 
> > RDC has been enabled.
> > I think it may make sense to provide a common way to figure it out. Either 
> > via a helper function that would process CLI arguments or calculate it once 
> > and save it somewhere.
> I haven't quite finalized how to handle this. The new driver should be 
> compatible with a non-RDC build since we simply wouldn't embed the device 
> image or create offloading entries. It's a little bit more difficult here 
> since the new method is opt-in so it requires a flag. We should definitely 
> emit a warning if both are enabled (I'm assuming there's one for passing both 
> `fgpu-rdc` and `fno-gpu-rdc`). I'll add one in.
> 
> Also we could consider the new driver *the* RDC in the future which would be 
> the easiest. The problem is if we want to support CUDA's method of RDC 
> considering how other build systems seem to expect it. I could see us 
> embedding the fatbinary in the object file, even if unused, just so that 
> cuobjdump works. However we couldn't support the generation of 
> `__cudaRegisterFatBinary_nv` functions because then those would cause 
> linker errors. WDYT?
> I'm assuming there's one for passing both fgpu-rdc and fno-gpu-rdc

This is not a valid assumption. The whole idea behind `-fno-something` is that 
the options can be overridden. E.g. if the build specifies a standard set of 
compiler options, but we need to override some of them when building a 
particular file. We can only do so by appending to the standard options. 
Potentially we may end up having those options overridden again. While it's not 
very common, it's certainly possible. It's also possible to start with 
'-fno-gpu-rdc' and then override it with `-fgpu-rdc`.

In this case, we care about the final state of RDC specified by -f*gpu-rdc 
options, not by the fact that `-fno-gpu-rdc` is present. 
`Args.hasFlag(options::OPT_fgpu_rdc, options::OPT_fno_gpu_rdc, false)` does 
exactly that -- gives you the final state. If it returns false, but we have 
`-foffload-new-driver`, then we need a warning as these options are 
contradictory.



Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D120272

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


[PATCH] D120272: [CUDA] Add driver support for compiling CUDA with the new driver

2022-04-22 Thread Artem Belevich via Phabricator via cfe-commits
tra added inline comments.



Comment at: clang/lib/Driver/ToolChains/Clang.cpp:6223-6224
   if (IsCuda || IsHIP) {
-if (Args.hasFlag(options::OPT_fgpu_rdc, options::OPT_fno_gpu_rdc, false))
+if (Args.hasFlag(options::OPT_fgpu_rdc, options::OPT_fno_gpu_rdc, false) ||
+Args.hasArg(options::OPT_foffload_new_driver))
   CmdArgs.push_back("-fgpu-rdc");

tra wrote:
> jhuber6 wrote:
> > tra wrote:
> > > If user specifies both `-fno-gpu-rdc` and `-foffload-new-driver` we would 
> > > still enable RDC compilation.
> > > We may want to at least issue a warning. 
> > > 
> > > Considering that  we have multiple places where we may check for 
> > > `-f[no]gpu-rdc` we should make sure we don't get different ideas whether 
> > > RDC has been enabled.
> > > I think it may make sense to provide a common way to figure it out. 
> > > Either via a helper function that would process CLI arguments or 
> > > calculate it once and save it somewhere.
> > I haven't quite finalized how to handle this. The new driver should be 
> > compatible with a non-RDC build since we simply wouldn't embed the device 
> > image or create offloading entries. It's a little bit more difficult here 
> > since the new method is opt-in so it requires a flag. We should definitely 
> > emit a warning if both are enabled (I'm assuming there's one for passing 
> > both `fgpu-rdc` and `fno-gpu-rdc`). I'll add one in.
> > 
> > Also we could consider the new driver *the* RDC in the future which would 
> > be the easiest. The problem is if we want to support CUDA's method of RDC 
> > considering how other build systems seem to expect it. I could see us 
> > embedding the fatbinary in the object file, even if unused, just so that 
> > cuobjdump works. However we couldn't support the generation of 
> > `__cudaRegisterFatBinary_nv` functions because then those would cause 
> > linker errors. WDYT?
> > I'm assuming there's one for passing both fgpu-rdc and fno-gpu-rdc
> 
> This is not a valid assumption. The whole idea behind `-fno-something` is 
> that the options can be overridden. E.g. if the build specifies a standard 
> set of compiler options, but we need to override some of them when building a 
> particular file. We can only do so by appending to the standard options. 
> Potentially we may end up having those options overridden again. While it's 
> not very common, it's certainly possible. It's also possible to start with 
> '-fno-gpu-rdc' and then override it with `-fgpu-rdc`.
> 
> In this case, we care about the final state of RDC specified by -f*gpu-rdc 
> options, not by the fact that `-fno-gpu-rdc` is present. 
> `Args.hasFlag(options::OPT_fgpu_rdc, options::OPT_fno_gpu_rdc, false)` does 
> exactly that -- gives you the final state. If it returns false, but we have 
> `-foffload-new-driver`, then we need a warning as these options are 
> contradictory.
> 
> The new driver should be compatible with a non-RDC build 

In that case, we don't need a warning, but we do need a test verifying this 
behavior.

> Also we could consider the new driver *the* RDC in the future which would be 
> the easiest. 

SGTM. I do not know how it all will work out in the end. Your proposed model 
makes a lot of sense, and I'm guardedly optimistic about it.
Eventually we would deprecate RDC options, but we still need to work sensibly 
when user specifies a mix of these options. 




Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D120272

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


[PATCH] D124280: [git-clang-format] Change run line from python to python3

2022-04-22 Thread Nico Weber via Phabricator via cfe-commits
thakis created this revision.
thakis added a reviewer: MyDeveloperDay.
Herald added a project: All.
thakis requested review of this revision.

Several systems no longer ship `python`.


https://reviews.llvm.org/D124280

Files:
  clang/tools/clang-format/git-clang-format


Index: clang/tools/clang-format/git-clang-format
===
--- clang/tools/clang-format/git-clang-format
+++ clang/tools/clang-format/git-clang-format
@@ -1,4 +1,4 @@
-#!/usr/bin/env python
+#!/usr/bin/env python3
 #
 #===- git-clang-format - ClangFormat Git Integration -*- python 
-*--===#
 #


Index: clang/tools/clang-format/git-clang-format
===
--- clang/tools/clang-format/git-clang-format
+++ clang/tools/clang-format/git-clang-format
@@ -1,4 +1,4 @@
-#!/usr/bin/env python
+#!/usr/bin/env python3
 #
 #===- git-clang-format - ClangFormat Git Integration -*- python -*--===#
 #
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D123812: [CUDA] Add wrapper code generation for registering CUDA images

2022-04-22 Thread Joseph Huber via Phabricator via cfe-commits
jhuber6 updated this revision to Diff 424534.
jhuber6 added a comment.
Herald added a subscriber: MaskRay.

Adding warning for using both `-fno-gpu-rdc` and `-foffload-new-driver`. I 
think this is a good warning to have for now while this is being worked in as 
opt-in. Once this has matured I plan on adding the necessary logic to handle 
RDC and non-RDC builds correctly with this. But for the purposes of this patch 
just warning is fine.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D123812

Files:
  clang/include/clang/Basic/DiagnosticDriverKinds.td
  clang/lib/Driver/ToolChains/Clang.cpp
  clang/test/Driver/linker-wrapper-image.c
  clang/test/Driver/linker-wrapper.c
  clang/tools/clang-linker-wrapper/ClangLinkerWrapper.cpp
  clang/tools/clang-linker-wrapper/OffloadWrapper.cpp

Index: clang/tools/clang-linker-wrapper/OffloadWrapper.cpp
===
--- clang/tools/clang-linker-wrapper/OffloadWrapper.cpp
+++ clang/tools/clang-linker-wrapper/OffloadWrapper.cpp
@@ -20,6 +20,8 @@
 using namespace llvm;
 
 namespace {
+/// Magic number that begins the section containing the CUDA fatbinary.
+constexpr unsigned CudaFatMagic = 0x466243b1;
 
 IntegerType *getSizeTTy(Module &M) {
   LLVMContext &C = M.getContext();
@@ -255,6 +257,265 @@
   appendToGlobalDtors(M, Func, /*Priority*/ 1);
 }
 
+// struct fatbin_wrapper {
+//  int32_t magic;
+//  int32_t version;
+//  void *image;
+//  void *reserved;
+//};
+StructType *getFatbinWrapperTy(Module &M) {
+  LLVMContext &C = M.getContext();
+  StructType *FatbinTy = StructType::getTypeByName(C, "fatbin_wrapper");
+  if (!FatbinTy)
+FatbinTy = StructType::create("fatbin_wrapper", Type::getInt32Ty(C),
+  Type::getInt32Ty(C), Type::getInt8PtrTy(C),
+  Type::getInt8PtrTy(C));
+  return FatbinTy;
+}
+
+/// Embed the image \p Image into the module \p M so it can be found by the
+/// runtime.
+GlobalVariable *createFatbinDesc(Module &M, ArrayRef Image) {
+  LLVMContext &C = M.getContext();
+  llvm::Type *Int8PtrTy = Type::getInt8PtrTy(C);
+  llvm::Triple Triple = llvm::Triple(M.getTargetTriple());
+
+  // Create the global string containing the fatbinary.
+  StringRef FatbinConstantSection =
+  Triple.isMacOSX() ? "__NV_CUDA,__nv_fatbin" : ".nv_fatbin";
+  auto *Data = ConstantDataArray::get(C, Image);
+  auto *Fatbin = new GlobalVariable(M, Data->getType(), /*isConstant*/ true,
+GlobalVariable::InternalLinkage, Data,
+".fatbin_image");
+  Fatbin->setSection(FatbinConstantSection);
+
+  // Create the fatbinary wrapper
+  StringRef FatbinWrapperSection =
+  Triple.isMacOSX() ? "__NV_CUDA,__fatbin" : ".nvFatBinSegment";
+  Constant *FatbinWrapper[] = {
+  ConstantInt::get(Type::getInt32Ty(C), CudaFatMagic),
+  ConstantInt::get(Type::getInt32Ty(C), 1),
+  ConstantExpr::getPointerBitCastOrAddrSpaceCast(Fatbin, Int8PtrTy),
+  ConstantPointerNull::get(Type::getInt8PtrTy(C))};
+
+  Constant *FatbinInitializer =
+  ConstantStruct::get(getFatbinWrapperTy(M), FatbinWrapper);
+
+  auto *FatbinDesc =
+  new GlobalVariable(M, getFatbinWrapperTy(M),
+ /*isConstant*/ true, GlobalValue::InternalLinkage,
+ FatbinInitializer, ".fatbin_wrapper");
+  FatbinDesc->setSection(FatbinWrapperSection);
+  FatbinDesc->setAlignment(Align(8));
+
+  // We create a dummy entry to ensure the linker will define the begin / end
+  // symbols. The CUDA runtime should ignore the null address if we attempt to
+  // register it.
+  auto *DummyInit =
+  ConstantAggregateZero::get(ArrayType::get(getEntryTy(M), 0u));
+  auto *DummyEntry = new GlobalVariable(
+  M, DummyInit->getType(), true, GlobalVariable::ExternalLinkage, DummyInit,
+  "__dummy.cuda_offloading.entry");
+  DummyEntry->setSection("cuda_offloading_entries");
+  DummyEntry->setVisibility(GlobalValue::HiddenVisibility);
+
+  return FatbinDesc;
+}
+
+/// Create the register globals function. We will iterate all of the offloading
+/// entries stored at the begin / end symbols and register them according to
+/// their type. This creates the following function in IR:
+///
+/// extern struct __tgt_offload_entry __start_cuda_offloading_entries;
+/// extern struct __tgt_offload_entry __stop_cuda_offloading_entries;
+///
+/// extern void __cudaRegisterFunction(void **, void *, void *, void *, int,
+///void *, void *, void *, void *, int *);
+/// extern void __cudaRegisterVar(void **, void *, void *, void *, int32_t,
+///   int64_t, int32_t, int32_t);
+///
+/// void __cudaRegisterTest(void **fatbinHandle) {
+///   for (struct __tgt_offload_entry *entry = &__start_cuda_offloading_entries;
+///entry != &__stop_cuda_offloading_entr

[PATCH] D123812: [CUDA] Add wrapper code generation for registering CUDA images

2022-04-22 Thread Joseph Huber via Phabricator via cfe-commits
jhuber6 updated this revision to Diff 424536.
jhuber6 added a comment.

Applied changes to wrong commit, whoops.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D123812

Files:
  clang/test/Driver/linker-wrapper-image.c
  clang/test/Driver/linker-wrapper.c
  clang/tools/clang-linker-wrapper/ClangLinkerWrapper.cpp
  clang/tools/clang-linker-wrapper/OffloadWrapper.cpp

Index: clang/tools/clang-linker-wrapper/OffloadWrapper.cpp
===
--- clang/tools/clang-linker-wrapper/OffloadWrapper.cpp
+++ clang/tools/clang-linker-wrapper/OffloadWrapper.cpp
@@ -20,6 +20,8 @@
 using namespace llvm;
 
 namespace {
+/// Magic number that begins the section containing the CUDA fatbinary.
+constexpr unsigned CudaFatMagic = 0x466243b1;
 
 IntegerType *getSizeTTy(Module &M) {
   LLVMContext &C = M.getContext();
@@ -255,6 +257,265 @@
   appendToGlobalDtors(M, Func, /*Priority*/ 1);
 }
 
+// struct fatbin_wrapper {
+//  int32_t magic;
+//  int32_t version;
+//  void *image;
+//  void *reserved;
+//};
+StructType *getFatbinWrapperTy(Module &M) {
+  LLVMContext &C = M.getContext();
+  StructType *FatbinTy = StructType::getTypeByName(C, "fatbin_wrapper");
+  if (!FatbinTy)
+FatbinTy = StructType::create("fatbin_wrapper", Type::getInt32Ty(C),
+  Type::getInt32Ty(C), Type::getInt8PtrTy(C),
+  Type::getInt8PtrTy(C));
+  return FatbinTy;
+}
+
+/// Embed the image \p Image into the module \p M so it can be found by the
+/// runtime.
+GlobalVariable *createFatbinDesc(Module &M, ArrayRef Image) {
+  LLVMContext &C = M.getContext();
+  llvm::Type *Int8PtrTy = Type::getInt8PtrTy(C);
+  llvm::Triple Triple = llvm::Triple(M.getTargetTriple());
+
+  // Create the global string containing the fatbinary.
+  StringRef FatbinConstantSection =
+  Triple.isMacOSX() ? "__NV_CUDA,__nv_fatbin" : ".nv_fatbin";
+  auto *Data = ConstantDataArray::get(C, Image);
+  auto *Fatbin = new GlobalVariable(M, Data->getType(), /*isConstant*/ true,
+GlobalVariable::InternalLinkage, Data,
+".fatbin_image");
+  Fatbin->setSection(FatbinConstantSection);
+
+  // Create the fatbinary wrapper
+  StringRef FatbinWrapperSection =
+  Triple.isMacOSX() ? "__NV_CUDA,__fatbin" : ".nvFatBinSegment";
+  Constant *FatbinWrapper[] = {
+  ConstantInt::get(Type::getInt32Ty(C), CudaFatMagic),
+  ConstantInt::get(Type::getInt32Ty(C), 1),
+  ConstantExpr::getPointerBitCastOrAddrSpaceCast(Fatbin, Int8PtrTy),
+  ConstantPointerNull::get(Type::getInt8PtrTy(C))};
+
+  Constant *FatbinInitializer =
+  ConstantStruct::get(getFatbinWrapperTy(M), FatbinWrapper);
+
+  auto *FatbinDesc =
+  new GlobalVariable(M, getFatbinWrapperTy(M),
+ /*isConstant*/ true, GlobalValue::InternalLinkage,
+ FatbinInitializer, ".fatbin_wrapper");
+  FatbinDesc->setSection(FatbinWrapperSection);
+  FatbinDesc->setAlignment(Align(8));
+
+  // We create a dummy entry to ensure the linker will define the begin / end
+  // symbols. The CUDA runtime should ignore the null address if we attempt to
+  // register it.
+  auto *DummyInit =
+  ConstantAggregateZero::get(ArrayType::get(getEntryTy(M), 0u));
+  auto *DummyEntry = new GlobalVariable(
+  M, DummyInit->getType(), true, GlobalVariable::ExternalLinkage, DummyInit,
+  "__dummy.cuda_offloading.entry");
+  DummyEntry->setSection("cuda_offloading_entries");
+  DummyEntry->setVisibility(GlobalValue::HiddenVisibility);
+
+  return FatbinDesc;
+}
+
+/// Create the register globals function. We will iterate all of the offloading
+/// entries stored at the begin / end symbols and register them according to
+/// their type. This creates the following function in IR:
+///
+/// extern struct __tgt_offload_entry __start_cuda_offloading_entries;
+/// extern struct __tgt_offload_entry __stop_cuda_offloading_entries;
+///
+/// extern void __cudaRegisterFunction(void **, void *, void *, void *, int,
+///void *, void *, void *, void *, int *);
+/// extern void __cudaRegisterVar(void **, void *, void *, void *, int32_t,
+///   int64_t, int32_t, int32_t);
+///
+/// void __cudaRegisterTest(void **fatbinHandle) {
+///   for (struct __tgt_offload_entry *entry = &__start_cuda_offloading_entries;
+///entry != &__stop_cuda_offloading_entries; ++entry) {
+/// if (!entry->size)
+///   __cudaRegisterFunction(fatbinHandle, entry->addr, entry->name,
+///  entry->name, -1, 0, 0, 0, 0, 0);
+/// else
+///   __cudaRegisterVar(fatbinHandle, entry->addr, entry->name, entry->name,
+/// 0, entry->size, 0, 0);
+///   }
+/// }
+///
+/// TODO: This only registers functions are variables. Additional sup

[PATCH] D120272: [CUDA] Add driver support for compiling CUDA with the new driver

2022-04-22 Thread Joseph Huber via Phabricator via cfe-commits
jhuber6 updated this revision to Diff 424537.
jhuber6 added a comment.

Adding warning for using both -fno-gpu-rdc and -foffload-new-driver. I think 
this is a good warning to have for now while this is being worked in as opt-in. 
Once this has matured I plan on adding the necessary logic to handle RDC and 
non-RDC builds correctly with this. But for the purposes of this patch just 
warning is fine.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D120272

Files:
  clang/include/clang/Basic/Cuda.h
  clang/include/clang/Basic/DiagnosticDriverKinds.td
  clang/lib/Driver/Driver.cpp
  clang/lib/Driver/ToolChains/Clang.cpp
  clang/lib/Driver/ToolChains/Cuda.cpp
  clang/lib/Driver/ToolChains/HIPAMD.cpp
  clang/test/Driver/cuda-openmp-driver.cu
  clang/test/Driver/cuda-phases.cu

Index: clang/test/Driver/cuda-phases.cu
===
--- clang/test/Driver/cuda-phases.cu
+++ clang/test/Driver/cuda-phases.cu
@@ -217,3 +217,32 @@
 // DASM2-DAG: [[P8:[0-9]+]]: backend, {[[P7]]}, assembler, (device-[[T]], [[ARCH2]])
 // DASM2-DAG: [[P9:[0-9]+]]: offload, "device-[[T]] ([[TRIPLE]]:[[ARCH2]])" {[[P8]]}, assembler
 // DASM2-NOT: host
+
+//
+// Test the phases generated when using the new offloading driver.
+//
+// RUN: %clang -### -target powerpc64le-ibm-linux-gnu -ccc-print-phases -foffload-new-driver \
+// RUN: --offload-arch=sm_52 --offload-arch=sm_70 %s 2>&1 | FileCheck --check-prefix=NEW_DRIVER %s
+// NEW_DRIVER: 0: input, "[[INPUT:.*]]", cuda, (host-cuda)
+// NEW_DRIVER: 1: preprocessor, {0}, cuda-cpp-output, (host-cuda)
+// NEW_DRIVER: 2: compiler, {1}, ir, (host-cuda)
+// NEW_DRIVER: 3: input, "[[INPUT]]", cuda, (device-cuda, sm_52)
+// NEW_DRIVER: 4: preprocessor, {3}, cuda-cpp-output, (device-cuda, sm_52)
+// NEW_DRIVER: 5: compiler, {4}, ir, (device-cuda, sm_52)
+// NEW_DRIVER: 6: backend, {5}, assembler, (device-cuda, sm_52)
+// NEW_DRIVER: 7: assembler, {6}, object, (device-cuda, sm_52)
+// NEW_DRIVER: 8: offload, "device-cuda (nvptx64-nvidia-cuda:sm_52)" {7}, object
+// NEW_DRIVER: 9: offload, "device-cuda (nvptx64-nvidia-cuda:sm_52)" {6}, assembler
+// NEW_DRIVER: 10: linker, {8, 9}, cuda-fatbin, (device-cuda, sm_52)
+// NEW_DRIVER: 11: input, "[[INPUT]]", cuda, (device-cuda, sm_70)
+// NEW_DRIVER: 12: preprocessor, {11}, cuda-cpp-output, (device-cuda, sm_70)
+// NEW_DRIVER: 13: compiler, {12}, ir, (device-cuda, sm_70)
+// NEW_DRIVER: 14: backend, {13}, assembler, (device-cuda, sm_70)
+// NEW_DRIVER: 15: assembler, {14}, object, (device-cuda, sm_70)
+// NEW_DRIVER: 16: offload, "device-cuda (nvptx64-nvidia-cuda:sm_70)" {15}, object
+// NEW_DRIVER: 17: offload, "device-cuda (nvptx64-nvidia-cuda:sm_70)" {14}, assembler
+// NEW_DRIVER: 18: linker, {16, 17}, cuda-fatbin, (device-cuda, sm_70)
+// NEW_DRIVER: 19: offload, "host-cuda (powerpc64le-ibm-linux-gnu)" {2}, "device-cuda (nvptx64-nvidia-cuda:sm_52)" {10}, "device-cuda (nvptx64-nvidia-cuda:sm_70)" {18}, ir
+// NEW_DRIVER: 20: backend, {19}, assembler, (host-cuda)
+// NEW_DRIVER: 21: assembler, {20}, object, (host-cuda)
+// NEW_DRIVER: 22: clang-linker-wrapper, {21}, image, (host-cuda)
Index: clang/test/Driver/cuda-openmp-driver.cu
===
--- /dev/null
+++ clang/test/Driver/cuda-openmp-driver.cu
@@ -0,0 +1,19 @@
+// REQUIRES: x86-registered-target
+// REQUIRES: nvptx-registered-target
+
+// RUN: %clang -### -target x86_64-linux-gnu -nocudalib -ccc-print-bindings -fgpu-rdc \
+// RUN:-foffload-new-driver --offload-arch=sm_35 --offload-arch=sm_70 %s 2>&1 \
+// RUN: | FileCheck -check-prefix BINDINGS %s
+
+// BINDINGS: "nvptx64-nvidia-cuda" - "clang", inputs: ["[[INPUT:.+]]"], output: "[[PTX_SM_35:.+]]"
+// BINDINGS-NEXT: "nvptx64-nvidia-cuda" - "NVPTX::Assembler", inputs: ["[[PTX_SM_35]]"], output: "[[CUBIN_SM_35:.+]]"
+// BINDINGS-NEXT: "nvptx64-nvidia-cuda" - "NVPTX::Linker", inputs: ["[[CUBIN_SM_35]]", "[[PTX_SM_35]]"], output: "[[FATBIN_SM_35:.+]]"
+// BINDINGS-NEXT: "nvptx64-nvidia-cuda" - "clang", inputs: ["[[INPUT]]"], output: "[[PTX_SM_70:.+]]"
+// BINDINGS-NEXT: "nvptx64-nvidia-cuda" - "NVPTX::Assembler", inputs: ["[[PTX_SM_70:.+]]"], output: "[[CUBIN_SM_70:.+]]"
+// BINDINGS-NEXT: "nvptx64-nvidia-cuda" - "NVPTX::Linker", inputs: ["[[CUBIN_SM_70]]", "[[PTX_SM_70:.+]]"], output: "[[FATBIN_SM_70:.+]]"
+// BINDINGS-NEXT: "x86_64-unknown-linux-gnu" - "clang", inputs: ["[[INPUT]]", "[[FATBIN_SM_35]]", "[[FATBIN_SM_70]]"], output: "[[HOST_OBJ:.+]]"
+// BINDINGS-NEXT: "x86_64-unknown-linux-gnu" - "Offload::Linker", inputs: ["[[HOST_OBJ]]"], output: "a.out"
+
+// RUN: %clang -### -nocudalib -foffload-new-driver %s 2>&1 | FileCheck -check-prefix RDC %s
+// RDC: clang{{.*}}"-cc1" "-triple" "nvptx64-nvidia-cuda"{{.*}}"-fgpu-rdc"
+// RDC: ptxas{{.*}}-c
Index: clang/lib/Driver/ToolChains/HIPAMD.cpp
===

[PATCH] D124282: [git-clang-format] Add some examples to the help text

2022-04-22 Thread Nico Weber via Phabricator via cfe-commits
thakis created this revision.
thakis added reviewers: MyDeveloperDay, curdeius.
Herald added a project: All.
thakis requested review of this revision.

https://reviews.llvm.org/D124282

Files:
  clang/tools/clang-format/git-clang-format


Index: clang/tools/clang-format/git-clang-format
===
--- clang/tools/clang-format/git-clang-format
+++ clang/tools/clang-format/git-clang-format
@@ -40,6 +40,16 @@
 between the working directory and , which defaults to HEAD.  Changes 
are
 only applied to the working directory, or in the stage/index.
 
+Examples:
+  To format staged changes, i.e everything that's been `git add`ed:
+git clang-format
+
+  To also format everything touched in the most recent commit:
+git clang-format HEAD~1
+
+  If you're on a branch off main, to format everything touched on your branch:
+git clang-format main
+
 If two commits are given (requires --diff), run clang-format on all lines in 
the
 second  that differ from the first .
 


Index: clang/tools/clang-format/git-clang-format
===
--- clang/tools/clang-format/git-clang-format
+++ clang/tools/clang-format/git-clang-format
@@ -40,6 +40,16 @@
 between the working directory and , which defaults to HEAD.  Changes are
 only applied to the working directory, or in the stage/index.
 
+Examples:
+  To format staged changes, i.e everything that's been `git add`ed:
+git clang-format
+
+  To also format everything touched in the most recent commit:
+git clang-format HEAD~1
+
+  If you're on a branch off main, to format everything touched on your branch:
+git clang-format main
+
 If two commits are given (requires --diff), run clang-format on all lines in the
 second  that differ from the first .
 
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D124189: [CUDA][HIP] Externalize kernels with internal linkage

2022-04-22 Thread Artem Belevich via Phabricator via cfe-commits
tra accepted this revision.
tra added a comment.
This revision is now accepted and ready to land.

LGTM overal, with few test nits.




Comment at: clang/lib/AST/ASTContext.cpp:12300
+ (D->hasAttr() &&
+  GetGVALinkageForFunction(cast(D),
+   /*IgnoreCUDAGlobalAttr=*/true) ==

yaxunl wrote:
> tra wrote:
> > yaxunl wrote:
> > > tra wrote:
> > > > yaxunl wrote:
> > > > > tra wrote:
> > > > > > Perhaps we don't need to change the public AST API and plumb 
> > > > > > `IgnoreCUDAGlobalAttr` through.
> > > > > > We cold create CUDA-aware static version of 
> > > > > > `GetGVALinkageForCudaKernel` instead, which would call 
> > > > > > `adjustGVALinkageForExternalDefinitionKind(..., 
> > > > > > adjustGVALinkageForAttributes(IgnoreCUDAGlobalAttr=true))`.
> > > > > We could have a static function but it would be 
> > > > > GetGVALinkageForCUDAKernelWithoutGlobalAttr since we need to know the 
> > > > > linkage of the kernel assuming it has no `__global__` attribute.
> > > > > 
> > > > > If you think it is OK I can make the change.
> > > > No point making public what's of no use to anybody other than this 
> > > > particular instance.
> > > > 
> > > > To think of it, we don't even need a function and could just do 
> > > > ```
> > > >   if (D->hasAttr() ) {
> > > > bool OriginalKernelLinkage = 
> > > > adjustGVALinkageForExternalDefinitionKind(..., 
> > > > adjustGVALinkageForAttributes(IgnoreCUDAGlobalAttr=true));
> > > > return OriginalKernelLinkage == GVA_Internal;
> > > >   }
> > > >   return (IsStaticVar &&)
> > > > ```
> > > > 
> > > > 
> > > One disadvantage of this approach is that it duplicates the code in 
> > > GetGVALinkageForFunction. In the future, if GetGVALinkageForFunction 
> > > changes, the same change needs to be applied to the duplicated code, 
> > > which is error-prone.
> > Good point.  Looking at the code closer, it appears that what we're 
> > interested in is whether the kernel was internal and *became* externally 
> > visible due to it being a kernel. 
> > 
> > Right now we're checking if the function would normally be `GVA_Internal` 
> > (shouldn't we have considered GVA_DiscardableODR, too, BTW?)
> > This is a somewhat indirect way of figuring out what we really need.
> > 
> > The code that determines what we want is essentially this code in 
> > adjustGVALinkageForAttributes that we're trying to enable/disable with 
> > `ConsiderCudaGlobalAttr`. 
> > 
> > It can be easily extracted into a static function, which could then be used 
> > from both `adjustGVALinkageForAttributes`, (which would no longer need 
> > `ConsiderCudaGlobalAttr`) and from here. 
> > 
> > ```
> > bool isInternalKernel(ASTContext *Context, Decl *D) {
> >   L=basicGVALinkageForFunction(Context, D);
> >   return (D->hasAttr() &&
> >   (L == GVA_DiscardableODR || L == GVA_Internal));
> > }
> > ```
> > 
> > This would both avoid logic duplication and would better match our intent.
> > 
> > Does it make sense? Or did I miss something else?
> GVA_DiscardableODR  usually maps to linkonce_odr linkage in LLVM IR. It 
> follows the ODR, therefore we should not make them unique.
> 
> If we use isInternalKernel in adjustGVALinkageForAttributes, there will be 
> two calls of basicGVALinkageForFunction when GetGVALinkageForFunction is 
> called, which seems inefficient. I think we can keep GetGVALinkageForFunction 
> as it was, and use basicGVALinkageForFunction directly in mayExternalize.
SGTM.



Comment at: clang/test/CodeGenCUDA/device-var-linkage.cu:1-2
 // RUN: %clang_cc1 -no-opaque-pointers -triple nvptx -fcuda-is-device \
 // RUN:   -emit-llvm -o - -x hip %s \
 // RUN:   | FileCheck -check-prefixes=DEV,NORDC %s

This is odd -- the tests use `-x hip` and  `-triple nvptx`.

I think we need to change them  into HIP+amdgpu and CUDA +nvptx variants ans we 
now have language-dependent behavior here and are interested in the 
language/triple combinations that we do use in practice.



Comment at: clang/test/CodeGenCUDA/kernel-in-anon-ns.cu:3
 // RUN:   -aux-triple x86_64-unknown-linux-gnu -std=c++11 -fgpu-rdc \
 // RUN:   -emit-llvm -o - -x hip %s > %t.dev
 

We should have CUDA test variants here, too.



Comment at: clang/test/CodeGenCUDA/managed-var.cu:1
 // REQUIRES: x86-registered-target, amdgpu-registered-target
 

Tests above do not have REQUIRED. Is it needed here?



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

https://reviews.llvm.org/D124189

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


  1   2   >