14#include "llvm/ADT/StringExtras.h"
15#include "llvm/ADT/StringRef.h"
16#include "llvm/Object/Archive.h"
17#include "llvm/Object/ObjectFile.h"
18#include "llvm/Support/MD5.h"
19#include "llvm/Support/MemoryBuffer.h"
20#include "llvm/Support/Path.h"
21#include "llvm/Support/raw_ostream.h"
22#include "llvm/TargetParser/Triple.h"
32#if defined(_WIN32) || defined(_WIN64)
33#define NULL_FILE "nul"
35#define NULL_FILE "/dev/null"
39const unsigned HIPCodeObjectAlign = 4096;
45 return HasTargetID ? (
T.getArchName() +
"-" +
T.getVendorName() +
"-" +
46 T.getOSName() +
"-" +
T.getEnvironmentName())
56 const llvm::opt::ArgList &Args_)
58 DiagID(C.getDriver().getDiags().getCustomDiagID(
60 "Error collecting HIP undefined fatbin symbols: %0")),
61 Quiet(C.getArgs().hasArg(options::OPT__HASH_HASH_HASH)),
62 Verbose(C.getArgs().hasArg(options::OPT_v)) {
66 for (
const auto &Name : FatBinSymbols)
67 llvm::errs() <<
"Found undefined HIP fatbin symbol: " << Name <<
"\n";
68 for (
const auto &Name : GPUBinHandleSymbols)
69 llvm::errs() <<
"Found undefined HIP gpubin handle symbol: " << Name
79 return GPUBinHandleSymbols;
88 bool IsMSVC = Triple.isWindowsMSVCEnvironment();
89 llvm::StringRef Ext = IsMSVC ?
".lib" :
".a";
91 for (
const auto *Arg : Args.filtered(options::OPT_l)) {
92 llvm::StringRef
Value = Arg->getValue();
93 if (
Value.starts_with(
":"))
94 ExactLibNames.push_back(
Value.drop_front());
96 LibNames.push_back(
Value);
98 for (
const auto *Arg : Args.filtered(options::OPT_L)) {
99 auto Path = Arg->getValue();
100 LibPaths.push_back(
Path);
102 llvm::errs() <<
"HIP fatbin symbol search uses library path: " <<
Path
106 auto ProcessLib = [&](llvm::StringRef LibName,
bool IsExact) {
108 IsExact ? Twine(LibName).str()
109 : IsMSVC ? (Twine(LibName) + Ext).str()
110 : (Twine(
"lib") + LibName + Ext).str());
113 for (
const auto Path : LibPaths) {
115 llvm::sys::path::append(FullPath, FullLibName);
117 if (llvm::sys::fs::exists(FullPath)) {
119 llvm::errs() <<
"HIP fatbin symbol search found library: "
121 auto BufferOrErr = llvm::MemoryBuffer::getFile(FullPath);
123 errorHandler(llvm::errorCodeToError(BufferOrErr.getError()));
126 processInput(BufferOrErr.get()->getMemBufferRef());
131 if (!
Found && Verbose)
132 llvm::errs() <<
"HIP fatbin symbol search could not find library: "
133 << FullLibName <<
"\n";
136 for (
const auto LibName : ExactLibNames)
137 ProcessLib(LibName,
true);
139 for (
const auto LibName : LibNames)
140 ProcessLib(LibName,
false);
145 const llvm::opt::ArgList &Args;
149 std::set<std::string> FatBinSymbols;
150 std::set<std::string> GPUBinHandleSymbols;
151 std::set<std::string, std::less<>> DefinedFatBinSymbols;
152 std::set<std::string, std::less<>> DefinedGPUBinHandleSymbols;
153 const std::string FatBinPrefix =
"__hip_fatbin";
154 const std::string GPUBinHandlePrefix =
"__hip_gpubin_handle";
156 void populateSymbols() {
157 std::deque<const Action *> WorkList;
158 std::set<const Action *>
Visited;
160 for (
const auto &
Action : C.getActions())
161 WorkList.push_back(
Action);
163 while (!WorkList.empty()) {
164 const Action *CurrentAction = WorkList.front();
165 WorkList.pop_front();
167 if (!CurrentAction || !
Visited.insert(CurrentAction).second)
170 if (
const auto *IA = dyn_cast<InputAction>(CurrentAction)) {
171 std::string ID = IA->getId().str();
173 ID = llvm::utohexstr(llvm::MD5Hash(ID),
true);
174 FatBinSymbols.insert((FatBinPrefix + Twine(
'_') + ID).str());
175 GPUBinHandleSymbols.insert(
176 (GPUBinHandlePrefix + Twine(
'_') + ID).str());
179 if (IA->getInputArg().getNumValues() == 0)
181 const char *
Filename = IA->getInputArg().getValue();
184 auto BufferOrErr = llvm::MemoryBuffer::getFile(
Filename);
191 processInput(BufferOrErr.get()->getMemBufferRef());
193 WorkList.insert(WorkList.end(), CurrentAction->
getInputs().begin(),
198 void processInput(
const llvm::MemoryBufferRef &Buffer) {
200 auto ObjFileOrErr = llvm::object::ObjectFile::createObjectFile(Buffer);
202 processSymbols(**ObjFileOrErr);
207 llvm::consumeError(ObjFileOrErr.takeError());
208 auto ArchiveOrErr = llvm::object::Archive::create(Buffer);
210 llvm::Error Err = llvm::Error::success();
211 llvm::object::Archive &Archive = *ArchiveOrErr.get();
212 for (
auto &Child : Archive.children(Err)) {
213 auto ChildBufOrErr = Child.getMemoryBufferRef();
215 processInput(*ChildBufOrErr);
217 errorHandler(ChildBufOrErr.takeError());
221 errorHandler(std::move(Err));
226 llvm::consumeError(ArchiveOrErr.takeError());
229 void processSymbols(
const llvm::object::ObjectFile &Obj) {
230 for (
const auto &Symbol : Obj.symbols()) {
231 auto FlagOrErr = Symbol.getFlags();
233 errorHandler(FlagOrErr.takeError());
237 auto NameOrErr = Symbol.getName();
239 errorHandler(NameOrErr.takeError());
242 llvm::StringRef Name = *NameOrErr;
245 FlagOrErr.get() & llvm::object::SymbolRef::SF_Undefined;
246 bool isFatBinSymbol = Name.starts_with(FatBinPrefix);
247 bool isGPUBinHandleSymbol = Name.starts_with(GPUBinHandlePrefix);
251 if (isFatBinSymbol) {
252 DefinedFatBinSymbols.insert(Name.str());
253 FatBinSymbols.erase(Name.str());
254 }
else if (isGPUBinHandleSymbol) {
255 DefinedGPUBinHandleSymbols.insert(Name.str());
256 GPUBinHandleSymbols.erase(Name.str());
262 if (isFatBinSymbol &&
263 DefinedFatBinSymbols.find(Name) == DefinedFatBinSymbols.end())
264 FatBinSymbols.insert(Name.str());
265 else if (isGPUBinHandleSymbol && DefinedGPUBinHandleSymbols.find(Name) ==
266 DefinedGPUBinHandleSymbols.end())
267 GPUBinHandleSymbols.insert(Name.str());
271 void errorHandler(llvm::Error Err) {
274 C.getDriver().Diag(DiagID) << llvm::toString(std::move(Err));
281 llvm::StringRef OutputFileName,
283 const llvm::opt::ArgList &Args,
287 ArgStringList BundlerArgs;
288 BundlerArgs.push_back(Args.MakeArgString(
"-type=o"));
289 BundlerArgs.push_back(
290 Args.MakeArgString(
"-bundle-align=" + Twine(HIPCodeObjectAlign)));
294 std::string BundlerTargetArg =
"-targets=host-x86_64-unknown-linux";
299 std::string OffloadKind =
"hip";
300 auto &TT =
T.getToolChain().getTriple();
302 OffloadKind = OffloadKind +
"v4";
303 for (
const auto &II : Inputs) {
304 const auto *A = II.getAction();
305 auto ArchStr = llvm::StringRef(A->getOffloadingArch());
306 BundlerTargetArg +=
',' + OffloadKind +
'-';
307 if (ArchStr ==
"amdgcnspirv")
312 if (!ArchStr.empty())
313 BundlerTargetArg +=
'-' + ArchStr.str();
315 BundlerArgs.push_back(Args.MakeArgString(BundlerTargetArg));
318 std::string BundlerInputArg =
"-input=" NULL_FILE;
319 BundlerArgs.push_back(Args.MakeArgString(BundlerInputArg));
320 for (
const auto &II : Inputs) {
321 BundlerInputArg = std::string(
"-input=") + II.getFilename();
322 BundlerArgs.push_back(Args.MakeArgString(BundlerInputArg));
325 std::string Output = std::string(OutputFileName);
326 auto *BundlerOutputArg =
327 Args.MakeArgString(std::string(
"-output=").append(Output));
328 BundlerArgs.push_back(BundlerOutputArg);
332 const char *Bundler = Args.MakeArgString(
333 T.getToolChain().GetProgramPath(
"clang-offload-bundler"));
334 C.addCommand(std::make_unique<Command>(
336 InputInfo(&JA, Args.MakeArgString(Output))));
347 std::string Name = std::string(llvm::sys::path::stem(Output.
getFilename()));
352 const char *ObjinFile;
353 const char *BundleFile;
354 if (
D.isSaveTempsEnabled()) {
355 ObjinFile =
C.getArgs().MakeArgString(Name +
".mcin");
356 BundleFile =
C.getArgs().MakeArgString(Name +
".hipfb");
358 auto TmpNameMcin =
D.GetTemporaryPath(Name,
"mcin");
359 ObjinFile =
C.addTempFile(
C.getArgs().MakeArgString(TmpNameMcin));
360 auto TmpNameFb =
D.GetTemporaryPath(Name,
"hipfb");
361 BundleFile =
C.addTempFile(
C.getArgs().MakeArgString(TmpNameFb));
366 std::string ObjBuffer;
367 llvm::raw_string_ostream ObjStream(ObjBuffer);
374 std::string PrimaryHipFatbinSymbol;
375 std::string PrimaryGpuBinHandleSymbol;
376 bool FoundPrimaryHipFatbinSymbol =
false;
377 bool FoundPrimaryGpuBinHandleSymbol =
false;
379 std::vector<std::string> AliasHipFatbinSymbols;
380 std::vector<std::string> AliasGpuBinHandleSymbols;
384 for (
const auto &Symbol : Symbols.getFatBinSymbols()) {
385 if (!FoundPrimaryHipFatbinSymbol) {
386 PrimaryHipFatbinSymbol = Symbol;
387 FoundPrimaryHipFatbinSymbol =
true;
389 AliasHipFatbinSymbols.push_back(Symbol);
392 for (
const auto &Symbol : Symbols.getGPUBinHandleSymbols()) {
393 if (!FoundPrimaryGpuBinHandleSymbol) {
394 PrimaryGpuBinHandleSymbol = Symbol;
395 FoundPrimaryGpuBinHandleSymbol =
true;
397 AliasGpuBinHandleSymbols.push_back(Symbol);
404 ObjStream <<
"# HIP Object Generator\n";
405 ObjStream <<
"# *** Automatically generated by Clang ***\n";
406 if (FoundPrimaryGpuBinHandleSymbol) {
408 if (HostTriple.isWindowsMSVCEnvironment())
409 ObjStream <<
" .section .hip_gpubin_handle,\"dw\"\n";
411 ObjStream <<
" .protected " << PrimaryGpuBinHandleSymbol <<
"\n";
412 ObjStream <<
" .type " << PrimaryGpuBinHandleSymbol <<
",@object\n";
413 ObjStream <<
" .section .hip_gpubin_handle,\"aw\"\n";
415 ObjStream <<
" .globl " << PrimaryGpuBinHandleSymbol <<
"\n";
416 ObjStream <<
" .p2align 3\n";
417 ObjStream << PrimaryGpuBinHandleSymbol <<
":\n";
418 ObjStream <<
" .zero 8\n";
421 for (
const auto &AliasSymbol : AliasGpuBinHandleSymbols) {
422 ObjStream <<
" .globl " << AliasSymbol <<
"\n";
423 ObjStream <<
" .set " << AliasSymbol <<
"," << PrimaryGpuBinHandleSymbol
427 if (FoundPrimaryHipFatbinSymbol) {
429 if (HostTriple.isWindowsMSVCEnvironment())
430 ObjStream <<
" .section .hip_fatbin,\"dw\"\n";
432 ObjStream <<
" .protected " << PrimaryHipFatbinSymbol <<
"\n";
433 ObjStream <<
" .type " << PrimaryHipFatbinSymbol <<
",@object\n";
434 ObjStream <<
" .section .hip_fatbin,\"a\",@progbits\n";
436 ObjStream <<
" .globl " << PrimaryHipFatbinSymbol <<
"\n";
437 ObjStream <<
" .p2align " << llvm::Log2(llvm::Align(HIPCodeObjectAlign))
440 for (
const auto &AliasSymbol : AliasHipFatbinSymbols) {
441 ObjStream <<
" .globl " << AliasSymbol <<
"\n";
442 ObjStream <<
" .set " << AliasSymbol <<
"," << PrimaryHipFatbinSymbol
445 ObjStream << PrimaryHipFatbinSymbol <<
":\n";
446 ObjStream <<
" .incbin ";
447 llvm::sys::printArg(ObjStream, BundleFile,
true);
450 if (HostTriple.isOSLinux() && HostTriple.isOSBinFormatELF())
451 ObjStream <<
" .section .note.GNU-stack, \"\", @progbits\n";
455 if (
C.getArgs().hasArg(options::OPT_fhip_dump_offload_linker_script))
456 llvm::errs() << ObjBuffer;
460 llvm::raw_fd_ostream Objf(ObjinFile, EC, llvm::sys::fs::OF_None);
463 D.Diag(clang::diag::err_unable_to_make_temp) << EC.message();
469 ArgStringList McArgs{
"-target", Args.MakeArgString(HostTriple.normalize()),
474 D.getClangProgramPath(), McArgs,
475 Inputs, Output,
D.getPrependArg()));
static std::string normalizeForBundler(const llvm::Triple &T, bool HasTargetID)
llvm::DenseSet< const void * > Visited
const std::set< std::string > & getGPUBinHandleSymbols() const
void processStaticLibraries()
HIPUndefinedFatBinSymbols(const Compilation &C, const llvm::opt::ArgList &Args_)
const std::set< std::string > & getFatBinSymbols() const
Concrete class used by the front-end to report problems and issues.
Action - Represent an abstract compilation step to perform.
Compilation - A set of tasks to perform for a single driver invocation.
const Driver & getDriver() const
Driver - Encapsulate logic for constructing compilation processes from a set of gcc-driver-like comma...
std::string getTargetTriple() const
The JSON file list parser is used to communicate input to InstallAPI.
const FunctionProtoType * T
static constexpr ResponseFileSupport None()
Returns a ResponseFileSupport indicating that response files are not supported.