[clang] 3090232 - [Clang][OpenMP] Rework recently moved getTargetEntryUniqueInfo to fix incorrect error breaking sanitizer

2023-06-07 Thread Andrew Gozillon via cfe-commits

Author: Andrew Gozillon
Date: 2023-06-07T14:30:25-05:00
New Revision: 309023263dba3b02bc885101faa47d110f662f99

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

LOG: [Clang][OpenMP] Rework recently moved getTargetEntryUniqueInfo to fix 
incorrect error breaking sanitizer

This move was done by 
https://reviews.llvm.org/rGcda46cc4f921f6b288c57a68b901ec2f57134606 and may be 
the issue causing the sanitizer to fail. But in either case, it is an invalid 
assert that required some changes to function correctly.

Added: 


Modified: 
clang/lib/CodeGen/CGOpenMPRuntime.cpp
llvm/include/llvm/Frontend/OpenMP/OMPIRBuilder.h
llvm/lib/Frontend/OpenMP/OMPIRBuilder.cpp

Removed: 




diff  --git a/clang/lib/CodeGen/CGOpenMPRuntime.cpp 
b/clang/lib/CodeGen/CGOpenMPRuntime.cpp
index c7d62fc075fbb..a5a5ed1c98ae0 100644
--- a/clang/lib/CodeGen/CGOpenMPRuntime.cpp
+++ b/clang/lib/CodeGen/CGOpenMPRuntime.cpp
@@ -1646,6 +1646,25 @@ convertCaptureClause(const VarDecl *VD) {
   }
 }
 
+static llvm::TargetRegionEntryInfo getEntryInfoFromPresumedLoc(
+CodeGenModule , llvm::OpenMPIRBuilder ,
+SourceLocation BeginLoc, llvm::StringRef ParentName = "") {
+
+  auto FileInfoCallBack = [&]() {
+SourceManager  = CGM.getContext().getSourceManager();
+PresumedLoc PLoc = SM.getPresumedLoc(BeginLoc);
+
+llvm::sys::fs::UniqueID ID;
+if (auto EC = llvm::sys::fs::getUniqueID(PLoc.getFilename(), ID)) {
+  PLoc = SM.getPresumedLoc(BeginLoc, /*UseLineDirectives=*/false);
+}
+
+return std::pair(PLoc.getFilename(), 
PLoc.getLine());
+  };
+
+  return OMPBuilder.getTargetEntryUniqueInfo(FileInfoCallBack, ParentName);
+}
+
 Address CGOpenMPRuntime::getAddrOfDeclareTargetVar(const VarDecl *VD) {
   auto AddrOfGlobal = [, this]() { return CGM.GetAddrOfGlobal(VD); };
 
@@ -1654,11 +1673,6 @@ Address CGOpenMPRuntime::getAddrOfDeclareTargetVar(const 
VarDecl *VD) {
   };
 
   std::vector GeneratedRefs;
-  auto PLoc = CGM.getContext().getSourceManager().getPresumedLoc(
-  VD->getCanonicalDecl()->getBeginLoc());
-  if (PLoc.isInvalid())
-PLoc = CGM.getContext().getSourceManager().getPresumedLoc(
-VD->getCanonicalDecl()->getBeginLoc(), /*UseLineDirectives=*/false);
 
   llvm::Type *LlvmPtrTy = CGM.getTypes().ConvertTypeForMem(
   CGM.getContext().getPointerType(VD->getType()));
@@ -1666,7 +1680,8 @@ Address CGOpenMPRuntime::getAddrOfDeclareTargetVar(const 
VarDecl *VD) {
   convertCaptureClause(VD), convertDeviceClause(VD),
   VD->hasDefinition(CGM.getContext()) == VarDecl::DeclarationOnly,
   VD->isExternallyVisible(),
-  OMPBuilder.getTargetEntryUniqueInfo(PLoc.getFilename(), PLoc.getLine()),
+  getEntryInfoFromPresumedLoc(CGM, OMPBuilder,
+  VD->getCanonicalDecl()->getBeginLoc()),
   CGM.getMangledName(VD), GeneratedRefs, CGM.getLangOpts().OpenMPSimd,
   CGM.getLangOpts().OMPTargetTriples, LlvmPtrTy, AddrOfGlobal,
   LinkageForVariable);
@@ -1849,19 +1864,6 @@ llvm::Function 
*CGOpenMPRuntime::emitThreadPrivateVarDefinition(
   return nullptr;
 }
 
-static llvm::TargetRegionEntryInfo getEntryInfoFromPresumedLoc(
-CodeGenModule , llvm::OpenMPIRBuilder ,
-SourceLocation BeginLoc, llvm::StringRef ParentName) {
-
-  auto PLoc = CGM.getContext().getSourceManager().getPresumedLoc(BeginLoc);
-  if (PLoc.isInvalid())
-PLoc = CGM.getContext().getSourceManager().getPresumedLoc(
-BeginLoc, /*UseLineDirectives=*/false);
-
-  return OMPBuilder.getTargetEntryUniqueInfo(PLoc.getFilename(), 
PLoc.getLine(),
- ParentName);
-}
-
 bool CGOpenMPRuntime::emitDeclareTargetVarDefinition(const VarDecl *VD,
  llvm::GlobalVariable 
*Addr,
  bool PerformInit) {
@@ -10349,16 +10351,12 @@ void 
CGOpenMPRuntime::registerTargetGlobalVariable(const VarDecl *VD,
   };
 
   std::vector GeneratedRefs;
-  auto PLoc = CGM.getContext().getSourceManager().getPresumedLoc(
-  VD->getCanonicalDecl()->getBeginLoc());
-  if (PLoc.isInvalid())
-PLoc = CGM.getContext().getSourceManager().getPresumedLoc(
-VD->getCanonicalDecl()->getBeginLoc(), /*UseLineDirectives=*/false);
   OMPBuilder.registerTargetGlobalVariable(
   convertCaptureClause(VD), convertDeviceClause(VD),
   VD->hasDefinition(CGM.getContext()) == VarDecl::DeclarationOnly,
   VD->isExternallyVisible(),
-  OMPBuilder.getTargetEntryUniqueInfo(PLoc.getFilename(), PLoc.getLine()),
+  getEntryInfoFromPresumedLoc(CGM, OMPBuilder,
+  VD->getCanonicalDecl()->getBeginLoc()),
   CGM.getMangledName(VD), GeneratedRefs, CGM.getLangOpts().OpenMPSimd,
   

[clang] cda46cc - [Clang][OpenMP][IRBuilder] Move registerTargetGlobalVariable & getAddrOfDeclareTargetVar into the OMPIRBuilder

2023-06-07 Thread Andrew Gozillon via cfe-commits

Author: Andrew Gozillon
Date: 2023-06-07T07:02:25-05:00
New Revision: cda46cc4f921f6b288c57a68b901ec2f57134606

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

LOG: [Clang][OpenMP][IRBuilder] Move registerTargetGlobalVariable & 
getAddrOfDeclareTargetVar into the OMPIRBuilder

This change tries to move registerTargetglobalVariable and
getAddrOfDeclareTargetVar out of Clang's CGOpenMPRuntime
and into the OMPIRBuilder for shared use with MLIR's OpenMPDialect
and Flang (or other languages that may want to utilise it).

This primarily does this by trying to hoist the Clang specific
types into arguments or callback functions in the form of
lambdas, replacing it with LLVM equivelants and
utilising shared OMPIRBuilder enumerators for
the clauses, rather than Clang's own variation.

Reviewers: jsjodin, jdoerfert

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

Added: 


Modified: 
clang/lib/CodeGen/CGOpenMPRuntime.cpp
llvm/include/llvm/Frontend/OpenMP/OMPIRBuilder.h
llvm/lib/Frontend/OpenMP/OMPIRBuilder.cpp
llvm/unittests/Frontend/OpenMPIRBuilderTest.cpp

Removed: 




diff  --git a/clang/lib/CodeGen/CGOpenMPRuntime.cpp 
b/clang/lib/CodeGen/CGOpenMPRuntime.cpp
index 2feab9e9a3322..6958ed28bffb2 100644
--- a/clang/lib/CodeGen/CGOpenMPRuntime.cpp
+++ b/clang/lib/CodeGen/CGOpenMPRuntime.cpp
@@ -1601,71 +1601,79 @@ CGOpenMPRuntime::createDispatchNextFunction(unsigned 
IVSize, bool IVSigned) {
   return CGM.CreateRuntimeFunction(FnTy, Name);
 }
 
-/// Obtain information that uniquely identifies a target entry. This
-/// consists of the file and device IDs as well as line number associated with
-/// the relevant entry source location.
-static llvm::TargetRegionEntryInfo
-getTargetEntryUniqueInfo(ASTContext , SourceLocation Loc,
- StringRef ParentName = "") {
-  SourceManager  = C.getSourceManager();
-
-  // The loc should be always valid and have a file ID (the user cannot use
-  // #pragma directives in macros)
-
-  assert(Loc.isValid() && "Source location is expected to be always valid.");
-
-  PresumedLoc PLoc = SM.getPresumedLoc(Loc);
-  assert(PLoc.isValid() && "Source location is expected to be always valid.");
+llvm::OffloadEntriesInfoManager::OMPTargetDeviceClauseKind
+convertDeviceClause(const VarDecl *VD) {
+  std::optional DevTy =
+  OMPDeclareTargetDeclAttr::getDeviceType(VD);
+  if (!DevTy)
+return llvm::OffloadEntriesInfoManager::OMPTargetDeviceClauseNone;
 
-  llvm::sys::fs::UniqueID ID;
-  if (auto EC = llvm::sys::fs::getUniqueID(PLoc.getFilename(), ID)) {
-PLoc = SM.getPresumedLoc(Loc, /*UseLineDirectives=*/false);
-assert(PLoc.isValid() && "Source location is expected to be always 
valid.");
-if (auto EC = llvm::sys::fs::getUniqueID(PLoc.getFilename(), ID))
-  SM.getDiagnostics().Report(diag::err_cannot_open_file)
-  << PLoc.getFilename() << EC.message();
+  switch (*DevTy) {
+  case OMPDeclareTargetDeclAttr::DT_Host:
+return llvm::OffloadEntriesInfoManager::OMPTargetDeviceClauseHost;
+break;
+  case OMPDeclareTargetDeclAttr::DT_NoHost:
+return llvm::OffloadEntriesInfoManager::OMPTargetDeviceClauseNoHost;
+break;
+  case OMPDeclareTargetDeclAttr::DT_Any:
+return llvm::OffloadEntriesInfoManager::OMPTargetDeviceClauseAny;
+break;
+  default:
+return llvm::OffloadEntriesInfoManager::OMPTargetDeviceClauseNone;
+break;
   }
+}
 
-  return llvm::TargetRegionEntryInfo(ParentName, ID.getDevice(), ID.getFile(),
- PLoc.getLine());
+llvm::OffloadEntriesInfoManager::OMPTargetGlobalVarEntryKind
+convertCaptureClause(const VarDecl *VD) {
+  std::optional MapType =
+  OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD);
+  if (!MapType)
+return llvm::OffloadEntriesInfoManager::OMPTargetGlobalVarEntryNone;
+  switch (*MapType) {
+  case OMPDeclareTargetDeclAttr::MapTypeTy::MT_To:
+return llvm::OffloadEntriesInfoManager::OMPTargetGlobalVarEntryTo;
+break;
+  case OMPDeclareTargetDeclAttr::MapTypeTy::MT_Enter:
+return llvm::OffloadEntriesInfoManager::OMPTargetGlobalVarEntryEnter;
+break;
+  case OMPDeclareTargetDeclAttr::MapTypeTy::MT_Link:
+return llvm::OffloadEntriesInfoManager::OMPTargetGlobalVarEntryLink;
+break;
+  default:
+return llvm::OffloadEntriesInfoManager::OMPTargetGlobalVarEntryNone;
+break;
+  }
 }
 
 Address CGOpenMPRuntime::getAddrOfDeclareTargetVar(const VarDecl *VD) {
-  if (CGM.getLangOpts().OpenMPSimd)
-return Address::invalid();
-  std::optional Res =
-  OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD);
-  if (Res && (*Res == OMPDeclareTargetDeclAttr::MT_Link ||
-  ((*Res == OMPDeclareTargetDeclAttr::MT_To ||
-*Res == 

[clang] 48c3ae5 - [Clang][Flang][OpenMP] Add loadOffloadInfoMetadata and createOffloadEntriesAndInfoMetadata into OMPIRBuilder's finalize and initialize

2023-05-16 Thread Andrew Gozillon via cfe-commits

Author: Andrew Gozillon
Date: 2023-05-16T11:51:36-05:00
New Revision: 48c3ae5cc3d4612283018ea597db3f7214aabfd9

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

LOG: [Clang][Flang][OpenMP] Add loadOffloadInfoMetadata and 
createOffloadEntriesAndInfoMetadata into OMPIRBuilder's finalize and initialize

This allows the generation of OpenMP offload metadata for the OpenMP
dialect when lowering to LLVM-IR and moves some of the shared logic
between the OpenMP Dialect and Clang into the IRBuilder.

Reviewers: jsjodin, jdoerfert, kiranchandramohan

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

Added: 


Modified: 
clang/lib/CodeGen/CGOpenMPRuntime.cpp
clang/lib/CodeGen/CGOpenMPRuntime.h
llvm/include/llvm/Frontend/OpenMP/OMPIRBuilder.h
llvm/lib/Frontend/OpenMP/CMakeLists.txt
llvm/lib/Frontend/OpenMP/OMPIRBuilder.cpp
mlir/lib/Target/LLVMIR/ModuleTranslation.cpp

Removed: 




diff  --git a/clang/lib/CodeGen/CGOpenMPRuntime.cpp 
b/clang/lib/CodeGen/CGOpenMPRuntime.cpp
index a74f63cd1fac9..8900f33383e21 100644
--- a/clang/lib/CodeGen/CGOpenMPRuntime.cpp
+++ b/clang/lib/CodeGen/CGOpenMPRuntime.cpp
@@ -1059,10 +1059,10 @@ CGOpenMPRuntime::CGOpenMPRuntime(CodeGenModule )
   llvm::OpenMPIRBuilderConfig Config(CGM.getLangOpts().OpenMPIsDevice, false,
  hasRequiresUnifiedSharedMemory(),
  CGM.getLangOpts().OpenMPOffloadMandatory);
-  // Initialize Types used in OpenMPIRBuilder from OMPKinds.def
-  OMPBuilder.initialize();
+  OMPBuilder.initialize(CGM.getLangOpts().OpenMPIsDevice
+? CGM.getLangOpts().OMPHostIRFile
+: StringRef{});
   OMPBuilder.setConfig(Config);
-  loadOffloadInfoMetadata();
 }
 
 void CGOpenMPRuntime::clear() {
@@ -3006,40 +3006,6 @@ void 
CGOpenMPRuntime::createOffloadEntriesAndInfoMetadata() {
   OMPBuilder.createOffloadEntriesAndInfoMetadata(ErrorReportFn);
 }
 
-/// Loads all the offload entries information from the host IR
-/// metadata.
-void CGOpenMPRuntime::loadOffloadInfoMetadata() {
-  // If we are in target mode, load the metadata from the host IR. This code 
has
-  // to match the metadaata creation in createOffloadEntriesAndInfoMetadata().
-
-  if (!CGM.getLangOpts().OpenMPIsDevice)
-return;
-
-  if (CGM.getLangOpts().OMPHostIRFile.empty())
-return;
-
-  auto Buf = llvm::MemoryBuffer::getFile(CGM.getLangOpts().OMPHostIRFile);
-  if (auto EC = Buf.getError()) {
-CGM.getDiags().Report(diag::err_cannot_open_file)
-<< CGM.getLangOpts().OMPHostIRFile << EC.message();
-return;
-  }
-
-  llvm::LLVMContext C;
-  auto ME = expectedToErrorOrAndEmitErrors(
-  C, llvm::parseBitcodeFile(Buf.get()->getMemBufferRef(), C));
-
-  if (auto EC = ME.getError()) {
-unsigned DiagID = CGM.getDiags().getCustomDiagID(
-DiagnosticsEngine::Error, "Unable to parse host IR file '%0':'%1'");
-CGM.getDiags().Report(DiagID)
-<< CGM.getLangOpts().OMPHostIRFile << EC.message();
-return;
-  }
-
-  OMPBuilder.loadOffloadInfoMetadata(*ME.get());
-}
-
 void CGOpenMPRuntime::emitKmpRoutineEntryT(QualType KmpInt32Ty) {
   if (!KmpRoutineEntryPtrTy) {
 // Build typedef kmp_int32 (* kmp_routine_entry_t)(kmp_int32, void *); 
type.

diff  --git a/clang/lib/CodeGen/CGOpenMPRuntime.h 
b/clang/lib/CodeGen/CGOpenMPRuntime.h
index 27ca20ea584f4..bd27642867719 100644
--- a/clang/lib/CodeGen/CGOpenMPRuntime.h
+++ b/clang/lib/CodeGen/CGOpenMPRuntime.h
@@ -551,10 +551,6 @@ class CGOpenMPRuntime {
   /// Device routines are specific to the
   bool HasEmittedDeclareTargetRegion = false;
 
-  /// Loads all the offload entries information from the host IR
-  /// metadata.
-  void loadOffloadInfoMetadata();
-
   /// Start scanning from statement \a S and emit all target regions
   /// found along the way.
   /// \param S Starting statement.

diff  --git a/llvm/include/llvm/Frontend/OpenMP/OMPIRBuilder.h 
b/llvm/include/llvm/Frontend/OpenMP/OMPIRBuilder.h
index d5d1646fb5a37..74b46f192ce3f 100644
--- a/llvm/include/llvm/Frontend/OpenMP/OMPIRBuilder.h
+++ b/llvm/include/llvm/Frontend/OpenMP/OMPIRBuilder.h
@@ -418,8 +418,14 @@ class OpenMPIRBuilder {
 
   /// Initialize the internal state, this will put structures types and
   /// potentially other helpers into the underlying module. Must be called
-  /// before any other method and only once!
-  void initialize();
+  /// before any other method and only once! This internal state includes
+  /// Types used in the OpenMPIRBuilder generated from OMPKinds.def as well
+  /// as loading offload metadata for device from the OpenMP host IR file
+  /// passed in as the HostFilePath argument.
+  /// \param HostFilePath The path to the host IR file, used to load in
+  

[clang] 2e63436 - [Flang][OpenMP][Driver][MLIR] Port fopenmp-host-ir-file-path flag and add MLIR module attribute to proliferate to OpenMP IR lowering

2023-04-24 Thread Andrew Gozillon via cfe-commits

Author: Andrew Gozillon
Date: 2023-04-24T10:06:21-05:00
New Revision: 2e634367be6a2ed6b8a4ee5c29b720dd90c0d70a

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

LOG: [Flang][OpenMP][Driver][MLIR] Port fopenmp-host-ir-file-path flag and add 
MLIR module attribute to proliferate to OpenMP IR lowering

This patch ports the fopenmp-host-ir-file-path flag from Clang to Flang-new, 
this flag
is added by the driver to the device pass when doing two phase compilation 
(device + host).

This flag is then applied to the module when compiling during the OpenMP device 
phase.
This file can then be utilised during lowering of the OpenMP dialect to 
LLVM-IR, which
allows the device and host to maintain 1:1 mapping of OpenMP metadata for 
variables
during lowering via the OpenMPIRBuilders loadOffloadInfoMetadata facilities
(which is used for declare target and I believe target regions as well).

Reviewer: awarzynski

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

Added: 
flang/test/Lower/OpenMP/omp-host-ir-flag.f90

Modified: 
clang/include/clang/Driver/Options.td
clang/lib/Driver/ToolChains/Flang.cpp
flang/include/flang/Frontend/LangOptions.h
flang/include/flang/Tools/CrossToolHelpers.h
flang/lib/Frontend/CompilerInvocation.cpp
flang/test/Driver/driver-help.f90
flang/test/Driver/omp-driver-offload.f90
mlir/include/mlir/Dialect/OpenMP/OpenMPOpsInterfaces.td

Removed: 




diff  --git a/clang/include/clang/Driver/Options.td 
b/clang/include/clang/Driver/Options.td
index 3b07244b98e82..d8ae398c61218 100644
--- a/clang/include/clang/Driver/Options.td
+++ b/clang/include/clang/Driver/Options.td
@@ -6554,12 +6554,14 @@ def fno_cuda_host_device_constexpr : Flag<["-"], 
"fno-cuda-host-device-constexpr
 // OpenMP Options
 
//===--===//
 
+let Flags = [CC1Option, FC1Option, NoDriverOption] in {
+
 def fopenmp_is_device : Flag<["-"], "fopenmp-is-device">,
-  HelpText<"Generate code only for an OpenMP target device.">,
-  Flags<[CC1Option, FC1Option, NoDriverOption]>;
+  HelpText<"Generate code only for an OpenMP target device.">;
 def fopenmp_host_ir_file_path : Separate<["-"], "fopenmp-host-ir-file-path">,
-  HelpText<"Path to the IR file produced by the frontend for the host.">,
-  Flags<[CC1Option, NoDriverOption]>;
+  HelpText<"Path to the IR file produced by the frontend for the host.">;
+
+} // let Flags = [CC1Option, FC1Option, NoDriverOption]
 
 
//===--===//
 // SYCL Options

diff  --git a/clang/lib/Driver/ToolChains/Flang.cpp 
b/clang/lib/Driver/ToolChains/Flang.cpp
index 300072db35edc..ffd30af08fd0d 100644
--- a/clang/lib/Driver/ToolChains/Flang.cpp
+++ b/clang/lib/Driver/ToolChains/Flang.cpp
@@ -194,15 +194,29 @@ void Flang::addOffloadOptions(Compilation , const 
InputInfoList ,
 
   // Skips the primary input file, which is the input file that the compilation
   // proccess will be executed upon (e.g. the host bitcode file) and
-  // adds the other secondary input (e.g. device bitcode files for embedding)
-  // to the embed offload object. This is condensed logic from the Clang driver
-  // for embedding offload objects during HostOffloading.
-  if (IsHostOffloadingAction) {
-for (size_t i = 1; i < Inputs.size(); ++i) {
-  if (Inputs[i].getType() != types::TY_Nothing)
-CmdArgs.push_back(
-Args.MakeArgString("-fembed-offload-object=" +
-   getToolChain().getInputFilename(Inputs[i])));
+  // adds other secondary input (e.g. device bitcode files for embedding to the
+  // -fembed-offload-object argument or the host IR file for proccessing
+  // during device compilation to the fopenmp-host-ir-file-path argument via
+  // OpenMPDeviceInput). This is condensed logic from the ConstructJob
+  // function inside of the Clang driver for pushing on further input arguments
+  // needed for offloading during various phases of compilation.
+  for (size_t i = 1; i < Inputs.size(); ++i) {
+if (Inputs[i].getType() == types::TY_Nothing) {
+  // contains nothing, so it's skippable
+} else if (IsHostOffloadingAction) {
+  CmdArgs.push_back(
+  Args.MakeArgString("-fembed-offload-object=" +
+ getToolChain().getInputFilename(Inputs[i])));
+} else if (IsOpenMPDevice) {
+  if (Inputs[i].getFilename()) {
+CmdArgs.push_back("-fopenmp-host-ir-file-path");
+CmdArgs.push_back(Args.MakeArgString(Inputs[i].getFilename()));
+  } else {
+llvm_unreachable("missing openmp host-ir file for device offloading");
+  }
+} else {
+  llvm_unreachable(
+  "unexpectedly given multiple inputs or 

[clang] 53152f1 - [OpenMP][MLIR][Flang][bbc][Driver] Add OpenMP RTL Flags to Flang and generate omp.FlagsAttr from them

2023-04-05 Thread Andrew Gozillon via cfe-commits

Author: Andrew Gozillon
Date: 2023-04-05T12:50:32-05:00
New Revision: 53152f12a47bf6e97f1f2f2d6b71e7b4d4e3740a

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

LOG: [OpenMP][MLIR][Flang][bbc][Driver] Add OpenMP RTL Flags to Flang and 
generate omp.FlagsAttr from them

This patch ports OpenMP RTL flags from the shared Clang compiler
options to Flang. As well as adding a limited subset to bbc.

This patch enables the flags below (and any equals or inverse variants)
for Flang that exist in Clang:

-fopenmp-target-debug
-fopenmp-assume-threads-oversubscription
-fopenmp-assume-teams-oversubscription
-fopenmp-assume-no-nested-parallelism
-fopenmp-assume-no-thread-state

For the bbc tool it only utilises the primary variants to minimize
additional complexity in the tool.

The patch also provides FlagAttr generation from these flags. Which
will be lowered to LLVM-IR in a subsequent patch.

Reviewers: kiranchandramohan, awarzynski

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

Added: 
flang/test/Lower/OpenMP/rtl-flags.f90

Modified: 
clang/include/clang/Driver/Options.td
clang/lib/Driver/ToolChains/Flang.cpp
flang/include/flang/Frontend/LangOptions.def
flang/include/flang/Tools/CrossToolHelpers.h
flang/lib/Frontend/CompilerInvocation.cpp
flang/lib/Frontend/FrontendActions.cpp
flang/test/Driver/driver-help.f90
flang/test/Driver/omp-frontend-forwarding.f90
flang/tools/bbc/bbc.cpp

Removed: 




diff  --git a/clang/include/clang/Driver/Options.td 
b/clang/include/clang/Driver/Options.td
index 831f8dd65a3e6..5e008fc9b26ee 100644
--- a/clang/include/clang/Driver/Options.td
+++ b/clang/include/clang/Driver/Options.td
@@ -2680,26 +2680,39 @@ def fopenmp_cuda_blocks_per_sm_EQ : Joined<["-"], 
"fopenmp-cuda-blocks-per-sm=">
   Flags<[CC1Option, NoArgumentUnused, HelpHidden]>;
 def fopenmp_cuda_teams_reduction_recs_num_EQ : Joined<["-"], 
"fopenmp-cuda-teams-reduction-recs-num=">, Group,
   Flags<[CC1Option, NoArgumentUnused, HelpHidden]>;
-def fopenmp_target_debug : Flag<["-"], "fopenmp-target-debug">, 
Group, Flags<[CC1Option, NoArgumentUnused]>,
+
+//===--===//
+// Shared cc1 + fc1 OpenMP Target Options
+//===--===//
+
+let Flags = [CC1Option, FC1Option, NoArgumentUnused] in {
+let Group = f_Group in {
+
+def fopenmp_target_debug : Flag<["-"], "fopenmp-target-debug">,
   HelpText<"Enable debugging in the OpenMP offloading device RTL">;
-def fno_openmp_target_debug : Flag<["-"], "fno-openmp-target-debug">, 
Group, Flags<[NoArgumentUnused]>;
-def fopenmp_target_debug_EQ : Joined<["-"], "fopenmp-target-debug=">, 
Group, Flags<[CC1Option, NoArgumentUnused, HelpHidden]>;
-def fopenmp_assume_teams_oversubscription : Flag<["-"], 
"fopenmp-assume-teams-oversubscription">,
-  Group, Flags<[CC1Option, NoArgumentUnused, HelpHidden]>;
-def fopenmp_assume_threads_oversubscription : Flag<["-"], 
"fopenmp-assume-threads-oversubscription">,
-  Group, Flags<[CC1Option, NoArgumentUnused, HelpHidden]>;
-def fno_openmp_assume_teams_oversubscription : Flag<["-"], 
"fno-openmp-assume-teams-oversubscription">,
-  Group, Flags<[CC1Option, NoArgumentUnused, HelpHidden]>;
-def fno_openmp_assume_threads_oversubscription : Flag<["-"], 
"fno-openmp-assume-threads-oversubscription">,
-  Group, Flags<[CC1Option, NoArgumentUnused, HelpHidden]>;
-def fopenmp_assume_no_thread_state : Flag<["-"], 
"fopenmp-assume-no-thread-state">, Group,
-  Flags<[CC1Option, NoArgumentUnused, HelpHidden]>,
+def fno_openmp_target_debug : Flag<["-"], "fno-openmp-target-debug">;
+
+} // let Group = f_Group
+} // let Flags = [CC1Option, FC1Option, NoArgumentUnused]
+
+let Flags = [CC1Option, FC1Option, NoArgumentUnused, HelpHidden] in {
+let Group = f_Group in {
+
+def fopenmp_target_debug_EQ : Joined<["-"], "fopenmp-target-debug=">;
+def fopenmp_assume_teams_oversubscription : Flag<["-"], 
"fopenmp-assume-teams-oversubscription">;
+def fopenmp_assume_threads_oversubscription : Flag<["-"], 
"fopenmp-assume-threads-oversubscription">;
+def fno_openmp_assume_teams_oversubscription : Flag<["-"], 
"fno-openmp-assume-teams-oversubscription">;
+def fno_openmp_assume_threads_oversubscription : Flag<["-"], 
"fno-openmp-assume-threads-oversubscription">;
+def fopenmp_assume_no_thread_state : Flag<["-"], 
"fopenmp-assume-no-thread-state">,
   HelpText<"Assert no thread in a parallel region modifies an ICV">,
   MarshallingInfoFlag>;
-def fopenmp_assume_no_nested_parallelism : Flag<["-"], 
"fopenmp-assume-no-nested-parallelism">, Group,
-  Flags<[CC1Option, NoArgumentUnused, HelpHidden]>,
+def fopenmp_assume_no_nested_parallelism : Flag<["-"], 

[clang] 0cd31a7 - [Flang][Driver] Add support for fopenmp-is-device and fembed-offload-object to Flang ToolChain

2023-03-17 Thread Andrew Gozillon via cfe-commits

Author: Andrew Gozillon
Date: 2023-03-17T11:12:16-05:00
New Revision: 0cd31a7d308714d26f49391ac4ea9f6bce5fa324

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

LOG: [Flang][Driver] Add support for fopenmp-is-device and 
fembed-offload-object to Flang ToolChain

This allows-fembed-offload-object's and -fopenmp-is-device
compiler invocation arguments to be passed to the Flang frontend
during split compilation when offloading in OpenMP.

An example use case is when passing an offload-arch alongside
-fopenmp to embed device objects compiled for the offload-arch
within the host architecture.

This borrows from existing clangDriver+Clang.h/.cpp work and the intent
is currently to reuse as much of the existing infrastructure and design as
we can to achieve offloading for Flang+OpenMP. An overview of
Clang's offloading design can be found
here: https://clang.llvm.org/docs/OffloadingDesign.html

Reviewers:
awarzynski
jhuber6

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

Added: 
flang/test/Driver/omp-frontend-forwarding.f90

Modified: 
clang/lib/Driver/ToolChains/Flang.cpp
clang/lib/Driver/ToolChains/Flang.h

Removed: 




diff  --git a/clang/lib/Driver/ToolChains/Flang.cpp 
b/clang/lib/Driver/ToolChains/Flang.cpp
index 10a518c34351..0a4a0de99b89 100644
--- a/clang/lib/Driver/ToolChains/Flang.cpp
+++ b/clang/lib/Driver/ToolChains/Flang.cpp
@@ -114,6 +114,35 @@ void Flang::addTargetOptions(const ArgList ,
   // TODO: Add target specific flags, ABI, mtune option etc.
 }
 
+void Flang::addOffloadOptions(Compilation , const InputInfoList ,
+  const JobAction , const ArgList ,
+  ArgStringList ) const {
+  bool IsOpenMPDevice = JA.isDeviceOffloading(Action::OFK_OpenMP);
+  bool IsHostOffloadingAction = JA.isHostOffloading(Action::OFK_OpenMP) ||
+JA.isHostOffloading(C.getActiveOffloadKinds());
+
+  // Skips the primary input file, which is the input file that the compilation
+  // proccess will be executed upon (e.g. the host bitcode file) and
+  // adds the other secondary input (e.g. device bitcode files for embedding)
+  // to the embed offload object. This is condensed logic from the Clang driver
+  // for embedding offload objects during HostOffloading.
+  if (IsHostOffloadingAction) {
+for (size_t i = 1; i < Inputs.size(); ++i) {
+  if (Inputs[i].getType() != types::TY_Nothing)
+CmdArgs.push_back(
+Args.MakeArgString("-fembed-offload-object=" +
+   getToolChain().getInputFilename(Inputs[i])));
+}
+  }
+
+  if (IsOpenMPDevice) {
+// -fopenmp-is-device is passed along to tell the frontend that it is
+// generating code for a device, so that only the relevant code is
+// emitted.
+CmdArgs.push_back("-fopenmp-is-device");
+  }
+}
+
 static void addFloatingPointOptions(const Driver , const ArgList ,
 ArgStringList ) {
   StringRef FPContract;
@@ -327,6 +356,9 @@ void Flang::ConstructJob(Compilation , const JobAction 
,
   // Add other compile options
   addOtherOptions(Args, CmdArgs);
 
+  // Offloading related options
+  addOffloadOptions(C, Inputs, JA, Args, CmdArgs);
+
   // Forward -Xflang arguments to -fc1
   Args.AddAllArgValues(CmdArgs, options::OPT_Xflang);
 

diff  --git a/clang/lib/Driver/ToolChains/Flang.h 
b/clang/lib/Driver/ToolChains/Flang.h
index 4c85c602e267..0dc3cb7eeadc 100644
--- a/clang/lib/Driver/ToolChains/Flang.h
+++ b/clang/lib/Driver/ToolChains/Flang.h
@@ -56,6 +56,17 @@ class LLVM_LIBRARY_VISIBILITY Flang : public Tool {
   void addTargetOptions(const llvm::opt::ArgList ,
 llvm::opt::ArgStringList ) const;
 
+  /// Extract offload options from the driver arguments and add them to
+  /// the command arguments.
+  /// \param [in] C The current compilation for the driver invocation
+  /// \param [in] Inputs The input infomration on the current file inputs
+  /// \param [in] JA The job action
+  /// \param [in] Args The list of input driver arguments
+  /// \param [out] CmdArgs The list of output command arguments
+  void addOffloadOptions(Compilation , const InputInfoList ,
+ const JobAction , const llvm::opt::ArgList ,
+ llvm::opt::ArgStringList ) const;
+
   /// Extract other compilation options from the driver arguments and add them
   /// to the command arguments.
   ///

diff  --git a/flang/test/Driver/omp-frontend-forwarding.f90 
b/flang/test/Driver/omp-frontend-forwarding.f90
new file mode 100644
index ..063e20b1bee3
--- /dev/null
+++ b/flang/test/Driver/omp-frontend-forwarding.f90
@@ -0,0 +1,22 @@
+! Test that flang-new OpenMP and OpenMP offload related 
+! commands 

[clang] e002a38 - [Flang][OpenMP][MLIR][Driver][bbc] Add -fopenmp-is-device flag to Flang -fc1 & the bbc tool, and omp.is_device attribute

2023-03-07 Thread Andrew Gozillon via cfe-commits

Author: Andrew Gozillon
Date: 2023-03-07T12:57:58-06:00
New Revision: e002a38b20e3ac40aecbbfa0774f8ba7b9690b0c

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

LOG: [Flang][OpenMP][MLIR][Driver][bbc] Add -fopenmp-is-device flag to Flang 
-fc1 & the bbc tool, and omp.is_device attribute

Adds the -fopenmp-is-device flag to bbc and Flang's -fc1 (but not flang-new) 
and in addition adds an omp.is_device attribute onto the module when fopenmp is 
passed, this is a boolean attribute that is set to false or true dependent on 
if fopenmp-is-device is specified alongside the fopenmp flag on the commandline 
when invoking flang or bbc.

Reviewers:
awarzynski
kiranchandramohan

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

Added: 
flang/test/Lower/OpenMP/omp-is-device.f90

Modified: 
clang/include/clang/Driver/Options.td
flang/include/flang/Frontend/LangOptions.def
flang/lib/Frontend/CompilerInvocation.cpp
flang/lib/Frontend/FrontendActions.cpp
flang/test/Driver/driver-help.f90
flang/tools/bbc/bbc.cpp
mlir/include/mlir/Dialect/OpenMP/OpenMPOps.td
mlir/lib/Dialect/OpenMP/IR/OpenMPDialect.cpp

Removed: 




diff  --git a/clang/include/clang/Driver/Options.td 
b/clang/include/clang/Driver/Options.td
index d61083f8b538a..b8a12660b32b7 100644
--- a/clang/include/clang/Driver/Options.td
+++ b/clang/include/clang/Driver/Options.td
@@ -6530,7 +6530,7 @@ def fno_cuda_host_device_constexpr : Flag<["-"], 
"fno-cuda-host-device-constexpr
 
 def fopenmp_is_device : Flag<["-"], "fopenmp-is-device">,
   HelpText<"Generate code only for an OpenMP target device.">,
-  Flags<[CC1Option, NoDriverOption]>;
+  Flags<[CC1Option, FC1Option, NoDriverOption]>;
 def fopenmp_host_ir_file_path : Separate<["-"], "fopenmp-host-ir-file-path">,
   HelpText<"Path to the IR file produced by the frontend for the host.">,
   Flags<[CC1Option, NoDriverOption]>;

diff  --git a/flang/include/flang/Frontend/LangOptions.def 
b/flang/include/flang/Frontend/LangOptions.def
index 9471beda8e05a..3648e09154520 100644
--- a/flang/include/flang/Frontend/LangOptions.def
+++ b/flang/include/flang/Frontend/LangOptions.def
@@ -34,6 +34,8 @@ LANGOPT(NoSignedZeros, 1, false)
 LANGOPT(AssociativeMath, 1, false)
 /// Allow division operations to be reassociated
 LANGOPT(ReciprocalMath, 1, false)
+/// Generate code only for OpenMP target device
+LANGOPT(OpenMPIsDevice, 1, false)
 
 #undef LANGOPT
 #undef ENUM_LANGOPT

diff  --git a/flang/lib/Frontend/CompilerInvocation.cpp 
b/flang/lib/Frontend/CompilerInvocation.cpp
index 4fb1eb8ef902c..d043df3d7 100644
--- a/flang/lib/Frontend/CompilerInvocation.cpp
+++ b/flang/lib/Frontend/CompilerInvocation.cpp
@@ -670,6 +670,10 @@ static bool parseDialectArgs(CompilerInvocation , 
llvm::opt::ArgList ,
   if (args.hasArg(clang::driver::options::OPT_fopenmp)) {
 res.getFrontendOpts().features.Enable(
 Fortran::common::LanguageFeature::OpenMP);
+
+if (args.hasArg(clang::driver::options::OPT_fopenmp_is_device)) {
+  res.getLangOpts().OpenMPIsDevice = 1;
+}
   }
 
   // -pedantic

diff  --git a/flang/lib/Frontend/FrontendActions.cpp 
b/flang/lib/Frontend/FrontendActions.cpp
index d2d3ab4cf1e35..d6c06e4c370d0 100644
--- a/flang/lib/Frontend/FrontendActions.cpp
+++ b/flang/lib/Frontend/FrontendActions.cpp
@@ -177,6 +177,13 @@ bool CodeGenAction::beginSourceFileAction() {
 
   // Fetch module from lb, so we can set
   mlirModule = std::make_unique(lb.getModule());
+
+  if (ci.getInvocation().getFrontendOpts().features.IsEnabled(
+  Fortran::common::LanguageFeature::OpenMP)) {
+mlir::omp::OpenMPDialect::setIsDevice(
+*mlirModule, ci.getInvocation().getLangOpts().OpenMPIsDevice);
+  }
+
   setUpTargetMachine();
   const llvm::DataLayout  = tm->createDataLayout();
   setMLIRDataLayout(*mlirModule, dl);

diff  --git a/flang/test/Driver/driver-help.f90 
b/flang/test/Driver/driver-help.f90
index 7fdce71190f61..ca5d7cf42a3c3 100644
--- a/flang/test/Driver/driver-help.f90
+++ b/flang/test/Driver/driver-help.f90
@@ -138,6 +138,7 @@
 ! HELP-FC1-NEXT: -fno-signed-zeros  Allow optimizations that ignore the 
sign of floating point zeros
 ! HELP-FC1-NEXT: -fno-stack-arrays  Allocate array temporaries on the heap 
(default)
 ! HELP-FC1-NEXT: -fopenacc  Enable OpenACC
+! HELP-FC1-NEXT: -fopenmp-is-device Generate code only for an OpenMP 
target device.
 ! HELP-FC1-NEXT: -fopenmp   Parse OpenMP pragmas and generate 
parallel code.
 ! HELP-FC1-NEXT: -fpass-plugin= Load pass plugin from a dynamic 
shared object file (only with new pass manager).
 ! HELP-FC1-NEXT: -freciprocal-math  Allow division operations to be 
reassociated

diff  --git a/flang/test/Lower/OpenMP/omp-is-device.f90 

Re: r314650 - Dependent Address Space Support Test File

2017-10-02 Thread Andrew Gozillon via cfe-commits
Thank you very much for the help. I have committed a change that should fix 
this, I tested it with my normal build and the triple you referenced and it 
works in both cases. I shall continue to keep an eye on the build bot.


Best Regards,

Andrew Gozillon


From: NAKAMURA Takumi <geek4ci...@gmail.com>
Sent: 02 October 2017 11:09:51
To: Andrew Gozillon; cfe-commits@lists.llvm.org
Subject: Re: r314650 - Dependent Address Space Support Test File

On Mon, Oct 2, 2017 at 3:33 PM Andrew Gozillon via cfe-commits 
<cfe-commits@lists.llvm.org<mailto:cfe-commits@lists.llvm.org>> wrote:
Author: agozillon
Date: Sun Oct  1 23:31:25 2017
New Revision: 314650

URL: http://llvm.org/viewvc/llvm-project?rev=314650=rev
Log:
Dependent Address Space Support Test File

Adding regression test for Dependent Address Spaces in relation to
https://reviews.llvm.org/D33666 I forgot to svn add the test file
before commiting the prior changes. I appologies.


Added:
cfe/trunk/test/SemaTemplate/address_space-dependent.cpp

Added: cfe/trunk/test/SemaTemplate/address_space-dependent.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/SemaTemplate/address_space-dependent.cpp?rev=314650=auto
==
--- cfe/trunk/test/SemaTemplate/address_space-dependent.cpp (added)
+++ cfe/trunk/test/SemaTemplate/address_space-dependent.cpp Sun Oct  1 23:31:25 
2017
@@ -0,0 +1,119 @@
+// RUN: %clang_cc1 -x c++ -std=c++14 -fsyntax-only -verify %s
+
+template 
+void car() {
+  int __attribute__((address_space(I))) __attribute__((address_space(J))) * Y; 
 // expected-error {{multiple address spaces specified for type}}
+  int *__attribute__((address_space(I))) __attribute__((address_space(J))) * 
Z; // expected-error {{multiple address spaces specified for type}}
+
+  __attribute__((address_space(I))) int local;// expected-error 
{{automatic variable qualified with an address space}}
+  __attribute__((address_space(J))) int array[5]; // expected-error 
{{automatic variable qualified with an address space}}
+  __attribute__((address_space(I))) int arrarr[5][5]; // expected-error 
{{automatic variable qualified with an address space}}
+
+  __attribute__((address_space(J))) * x; // expected-error {{C++ requires a 
type specifier for all declarations}}
+
+  __attribute__((address_space(I))) float *B;
+
+  typedef __attribute__((address_space(J))) int AS2Int;
+  struct HasASFields {
+AS2Int typedef_as_field; // expected-error {{field may not be qualified 
with an address space}}
+  };
+
+  struct _st {
+int x, y;
+  } s __attribute((address_space(I))) = {1, 1};
+}
+
+template 
+struct HasASTemplateFields {
+  __attribute__((address_space(I))) int as_field; // expected-error {{field 
may not be qualified with an address space}}
+};
+
+template 
+void foo(__attribute__((address_space(I))) float *a, // expected-note 
{{candidate template ignored: substitution failure [with I = 1, J = 2]: 
parameter may not be qualified with an address space}}
+ __attribute__((address_space(J))) float b) {
+  *a = 5.0f + b;
+}
+
+template void foo<1, 2>(float *, float); // expected-error {{explicit 
instantiation of 'foo' does not refer to a function template, variable 
template, member function, member class, or static data member}}
+
+template 
+void neg() {
+  __attribute__((address_space(I))) int *bounds; // expected-error {{address 
space is negative}}
+}
+
+template 
+void toBig() {
+  __attribute__((address_space(I))) int *bounds; // expected-error {{address 
space is larger than the maximum supported (8388599)}}
+}
+
+template 
+void correct() {
+  __attribute__((address_space(I))) int *bounds;
+}
+
+template 
+char *cmp(__attribute__((address_space(I))) char *x, 
__attribute__((address_space(J))) char *y) {
+  return x < y ? x : y; // expected-error {{comparison of distinct pointer 
types ('__attribute__((address_space(1))) char *' and 
'__attribute__((address_space(2))) char *')}}
+}
+
+typedef void ft(void);
+
+template 
+struct fooFunction {
+  __attribute__((address_space(I))) void **const base = 0;
+
+  void *get_0(void) {
+return base[0]; // expected-error {{cannot initialize return object of 
type 'void *' with an lvalue of type '__attribute__((address_space(1))) void *}}
+  }
+
+  __attribute__((address_space(I))) ft qf; // expected-error {{function type 
may not be qualified with an address space}}
+  __attribute__((address_space(I))) char *test3_val;
+
+  void test3(void) {
+extern void test3_helper(char *p); // expected-note {{passing argument to 
parameter 'p' here}}
+test3_helper(test3_val);   // expected-error {{cannot initialize a 
parameter of type 'char *' with an lvalue of type 
'__attribute__((address_space(1))) char *'}}
+  }
+};
+
+template 
+int GetAddressSpaceValue(T __attribute__((address_space(N))) * p) {
+  return N;
+}
+
+template  int __attribute__((addres

r314668 - Dependent Address Space Support Test Fix

2017-10-02 Thread Andrew Gozillon via cfe-commits
Author: agozillon
Date: Mon Oct  2 06:32:59 2017
New Revision: 314668

URL: http://llvm.org/viewvc/llvm-project?rev=314668=rev
Log:
Dependent Address Space Support Test Fix

Modifying a non-type template integer arguement that is causing errors 
in some builds as it's too large for 32-bit longs. This hopefully (and 
seems to when testing) should fix all of the build bot errors relating 
to this test. I also modified the name of the function call to be more 
apt.

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


Modified:
cfe/trunk/test/SemaTemplate/address_space-dependent.cpp

Modified: cfe/trunk/test/SemaTemplate/address_space-dependent.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/SemaTemplate/address_space-dependent.cpp?rev=314668=314667=314668=diff
==
--- cfe/trunk/test/SemaTemplate/address_space-dependent.cpp (original)
+++ cfe/trunk/test/SemaTemplate/address_space-dependent.cpp Mon Oct  2 06:32:59 
2017
@@ -42,7 +42,7 @@ void neg() {
 }
 
 template 
-void toBig() {
+void tooBig() {
   __attribute__((address_space(I))) int *bounds; // expected-error {{address 
space is larger than the maximum supported (8388599)}}
 }
 
@@ -102,7 +102,7 @@ int main() {
   HasASTemplateFields<1> HASTF;
   neg<-1>(); // expected-note {{in instantiation of function template 
specialization 'neg<-1>' requested here}}
   correct<0x77>();
-  toBig<4294967500>(); // expected-note {{in instantiation of function 
template specialization 'toBig<4294967500>' requested here}}
+  tooBig<8388650>(); // expected-note {{in instantiation of function template 
specialization 'tooBig<8388650>' requested here}}
 
   __attribute__((address_space(1))) char *x;
   __attribute__((address_space(2))) char *y;


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


r314650 - Dependent Address Space Support Test File

2017-10-02 Thread Andrew Gozillon via cfe-commits
Author: agozillon
Date: Sun Oct  1 23:31:25 2017
New Revision: 314650

URL: http://llvm.org/viewvc/llvm-project?rev=314650=rev
Log:
Dependent Address Space Support Test File

Adding regression test for Dependent Address Spaces in relation to
https://reviews.llvm.org/D33666 I forgot to svn add the test file 
before commiting the prior changes. I appologies. 


Added:
cfe/trunk/test/SemaTemplate/address_space-dependent.cpp

Added: cfe/trunk/test/SemaTemplate/address_space-dependent.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/SemaTemplate/address_space-dependent.cpp?rev=314650=auto
==
--- cfe/trunk/test/SemaTemplate/address_space-dependent.cpp (added)
+++ cfe/trunk/test/SemaTemplate/address_space-dependent.cpp Sun Oct  1 23:31:25 
2017
@@ -0,0 +1,119 @@
+// RUN: %clang_cc1 -x c++ -std=c++14 -fsyntax-only -verify %s
+
+template 
+void car() {
+  int __attribute__((address_space(I))) __attribute__((address_space(J))) * Y; 
 // expected-error {{multiple address spaces specified for type}}
+  int *__attribute__((address_space(I))) __attribute__((address_space(J))) * 
Z; // expected-error {{multiple address spaces specified for type}}
+
+  __attribute__((address_space(I))) int local;// expected-error 
{{automatic variable qualified with an address space}}
+  __attribute__((address_space(J))) int array[5]; // expected-error 
{{automatic variable qualified with an address space}}
+  __attribute__((address_space(I))) int arrarr[5][5]; // expected-error 
{{automatic variable qualified with an address space}}
+
+  __attribute__((address_space(J))) * x; // expected-error {{C++ requires a 
type specifier for all declarations}}
+
+  __attribute__((address_space(I))) float *B;
+
+  typedef __attribute__((address_space(J))) int AS2Int;
+  struct HasASFields {
+AS2Int typedef_as_field; // expected-error {{field may not be qualified 
with an address space}}
+  };
+
+  struct _st {
+int x, y;
+  } s __attribute((address_space(I))) = {1, 1};
+}
+
+template 
+struct HasASTemplateFields {
+  __attribute__((address_space(I))) int as_field; // expected-error {{field 
may not be qualified with an address space}}
+};
+
+template 
+void foo(__attribute__((address_space(I))) float *a, // expected-note 
{{candidate template ignored: substitution failure [with I = 1, J = 2]: 
parameter may not be qualified with an address space}}
+ __attribute__((address_space(J))) float b) {
+  *a = 5.0f + b;
+}
+
+template void foo<1, 2>(float *, float); // expected-error {{explicit 
instantiation of 'foo' does not refer to a function template, variable 
template, member function, member class, or static data member}}
+
+template 
+void neg() {
+  __attribute__((address_space(I))) int *bounds; // expected-error {{address 
space is negative}}
+}
+
+template 
+void toBig() {
+  __attribute__((address_space(I))) int *bounds; // expected-error {{address 
space is larger than the maximum supported (8388599)}}
+}
+
+template 
+void correct() {
+  __attribute__((address_space(I))) int *bounds;
+}
+
+template 
+char *cmp(__attribute__((address_space(I))) char *x, 
__attribute__((address_space(J))) char *y) {
+  return x < y ? x : y; // expected-error {{comparison of distinct pointer 
types ('__attribute__((address_space(1))) char *' and 
'__attribute__((address_space(2))) char *')}}
+}
+
+typedef void ft(void);
+
+template 
+struct fooFunction {
+  __attribute__((address_space(I))) void **const base = 0;
+
+  void *get_0(void) {
+return base[0]; // expected-error {{cannot initialize return object of 
type 'void *' with an lvalue of type '__attribute__((address_space(1))) void *}}
+  }
+
+  __attribute__((address_space(I))) ft qf; // expected-error {{function type 
may not be qualified with an address space}}
+  __attribute__((address_space(I))) char *test3_val;
+
+  void test3(void) {
+extern void test3_helper(char *p); // expected-note {{passing argument to 
parameter 'p' here}}
+test3_helper(test3_val);   // expected-error {{cannot initialize a 
parameter of type 'char *' with an lvalue of type 
'__attribute__((address_space(1))) char *'}}
+  }
+};
+
+template 
+int GetAddressSpaceValue(T __attribute__((address_space(N))) * p) {
+  return N;
+}
+
+template  int __attribute__((address_space(A))) *same_template();
+template  int __attribute__((address_space(B))) *same_template();
+void test_same_template() { (void) same_template<0>(); }
+
+template  int __attribute__((address_space(A))) 
*different_template(); // expected-note {{candidate function [with A = 0]}}
+template  int __attribute__((address_space(B+1))) 
*different_template(); // expected-note {{candidate function [with B = 0]}}
+void test_different_template() { (void) different_template<0>(); } // 
expected-error {{call to 'different_template' is ambiguous}}
+
+template  struct partial_spec_deduce_as;
+template  
+struct partial_spec_deduce_as 

r314649 - Dependent Address Space Support

2017-10-02 Thread Andrew Gozillon via cfe-commits
Author: agozillon
Date: Sun Oct  1 23:25:51 2017
New Revision: 314649

URL: http://llvm.org/viewvc/llvm-project?rev=314649=rev
Log:
Dependent Address Space Support

This patch relates to: https://reviews.llvm.org/D33666 This adds support
for template parameters to be passed to the address_space attribute. 
The main goal is to add further flexibility to the attribute and allow 
for it to be used easily with templates.

The main additions are a new type (DependentAddressSpaceType) alongside 
its TypeLoc and its mangling. As well as the logic required to support 
dependent address spaces which mainly resides in TreeTransform.h and 
SemaType.cpp.


Modified:
cfe/trunk/include/clang/AST/ASTContext.h
cfe/trunk/include/clang/AST/RecursiveASTVisitor.h
cfe/trunk/include/clang/AST/Type.h
cfe/trunk/include/clang/AST/TypeLoc.h
cfe/trunk/include/clang/AST/TypeNodes.def
cfe/trunk/include/clang/Sema/Sema.h
cfe/trunk/include/clang/Serialization/ASTBitCodes.h
cfe/trunk/lib/AST/ASTContext.cpp
cfe/trunk/lib/AST/ASTStructuralEquivalence.cpp
cfe/trunk/lib/AST/ItaniumMangle.cpp
cfe/trunk/lib/AST/MicrosoftMangle.cpp
cfe/trunk/lib/AST/Type.cpp
cfe/trunk/lib/AST/TypePrinter.cpp
cfe/trunk/lib/Sema/SemaDecl.cpp
cfe/trunk/lib/Sema/SemaTemplate.cpp
cfe/trunk/lib/Sema/SemaTemplateDeduction.cpp
cfe/trunk/lib/Sema/SemaType.cpp
cfe/trunk/lib/Sema/TreeTransform.h
cfe/trunk/lib/Serialization/ASTReader.cpp
cfe/trunk/lib/Serialization/ASTWriter.cpp
cfe/trunk/tools/libclang/CIndex.cpp

Modified: cfe/trunk/include/clang/AST/ASTContext.h
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/AST/ASTContext.h?rev=314649=314648=314649=diff
==
--- cfe/trunk/include/clang/AST/ASTContext.h (original)
+++ cfe/trunk/include/clang/AST/ASTContext.h Sun Oct  1 23:25:51 2017
@@ -143,6 +143,8 @@ class ASTContext : public RefCountedBase
   mutable llvm::FoldingSet DependentSizedArrayTypes;
   mutable llvm::FoldingSet
 DependentSizedExtVectorTypes;
+  mutable llvm::FoldingSet
+  DependentAddressSpaceTypes;
   mutable llvm::FoldingSet VectorTypes;
   mutable llvm::FoldingSet FunctionNoProtoTypes;
   mutable llvm::ContextualFoldingSet
@@ -1070,6 +1072,13 @@ public:
   /// replaced.
   QualType getAddrSpaceQualType(QualType T, unsigned AddressSpace) const;
 
+  /// \brief Remove any existing address space on the type and returns the type
+  /// with qualifiers intact (or that's the idea anyway)
+  ///
+  /// The return type should be T with all prior qualifiers minus the address
+  /// space.
+  QualType removeAddrSpaceQualType(QualType T) const;
+
   /// \brief Apply Objective-C protocol qualifiers to the given type.
   /// \param allowOnPointerType specifies if we can apply protocol
   /// qualifiers on ObjCObjectPointerType. It can be set to true when
@@ -1270,6 +1279,10 @@ public:
   Expr *SizeExpr,
   SourceLocation AttrLoc) const;
 
+  QualType getDependentAddressSpaceType(QualType PointeeType,
+Expr *AddrSpaceExpr,
+SourceLocation AttrLoc) const;
+
   /// \brief Return a K style C function type like 'int()'.
   QualType getFunctionNoProtoType(QualType ResultTy,
   const FunctionType::ExtInfo ) const;

Modified: cfe/trunk/include/clang/AST/RecursiveASTVisitor.h
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/AST/RecursiveASTVisitor.h?rev=314649=314648=314649=diff
==
--- cfe/trunk/include/clang/AST/RecursiveASTVisitor.h (original)
+++ cfe/trunk/include/clang/AST/RecursiveASTVisitor.h Sun Oct  1 23:25:51 2017
@@ -988,6 +988,11 @@ DEF_TRAVERSE_TYPE(DependentSizedArrayTyp
 TRY_TO(TraverseStmt(T->getSizeExpr()));
 })
 
+DEF_TRAVERSE_TYPE(DependentAddressSpaceType, {
+  TRY_TO(TraverseStmt(T->getAddrSpaceExpr()));
+  TRY_TO(TraverseType(T->getPointeeType()));
+})
+
 DEF_TRAVERSE_TYPE(DependentSizedExtVectorType, {
   if (T->getSizeExpr())
 TRY_TO(TraverseStmt(T->getSizeExpr()));
@@ -1198,6 +1203,11 @@ DEF_TRAVERSE_TYPELOC(DependentSizedArray
   return TraverseArrayTypeLocHelper(TL);
 })
 
+DEF_TRAVERSE_TYPELOC(DependentAddressSpaceType, {
+  TRY_TO(TraverseStmt(TL.getTypePtr()->getAddrSpaceExpr()));
+  TRY_TO(TraverseType(TL.getTypePtr()->getPointeeType()));
+})
+
 // FIXME: order? why not size expr first?
 // FIXME: base VectorTypeLoc is unfinished
 DEF_TRAVERSE_TYPELOC(DependentSizedExtVectorType, {

Modified: cfe/trunk/include/clang/AST/Type.h
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/AST/Type.h?rev=314649=314648=314649=diff
==
--- 

r314623 - Test Commit.

2017-10-01 Thread Andrew Gozillon via cfe-commits
Author: agozillon
Date: Sun Oct  1 05:16:24 2017
New Revision: 314623

URL: http://llvm.org/viewvc/llvm-project?rev=314623=rev
Log:
Test Commit.


Modified:
cfe/trunk/lib/Sema/SemaType.cpp

Modified: cfe/trunk/lib/Sema/SemaType.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Sema/SemaType.cpp?rev=314623=314622=314623=diff
==
--- cfe/trunk/lib/Sema/SemaType.cpp (original)
+++ cfe/trunk/lib/Sema/SemaType.cpp Sun Oct  1 05:16:24 2017
@@ -5606,7 +5606,6 @@ ParsedType Sema::ActOnObjCInstanceType(S
 /// space for the type.
 static void HandleAddressSpaceTypeAttribute(QualType ,
 const AttributeList , Sema 
){
-
   // If this type is already address space qualified, reject it.
   // ISO/IEC TR 18037 S5.3 (amending C99 6.7.3): "No type shall be qualified by
   // qualifiers for two or more different address spaces."


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