1 //===- LowerGPUToHSACO.cpp - Convert GPU kernel to HSACO blob -------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file implements a pass that serializes a gpu module into HSAco blob and
10 // adds that blob as a string attribute of the module.
11 //
12 //===----------------------------------------------------------------------===//
13 #include "mlir/Dialect/GPU/Passes.h"
14 #include "mlir/IR/Location.h"
15 #include "mlir/IR/MLIRContext.h"
16 
17 #if MLIR_GPU_TO_HSACO_PASS_ENABLE
18 #include "mlir/ExecutionEngine/OptUtils.h"
19 #include "mlir/Pass/Pass.h"
20 #include "mlir/Support/FileUtilities.h"
21 #include "mlir/Target/LLVMIR/Dialect/ROCDL/ROCDLToLLVMIRTranslation.h"
22 #include "mlir/Target/LLVMIR/Export.h"
23 
24 #include "llvm/IR/Constants.h"
25 #include "llvm/IR/GlobalVariable.h"
26 #include "llvm/IR/Module.h"
27 #include "llvm/IRReader/IRReader.h"
28 #include "llvm/Linker/Linker.h"
29 
30 #include "llvm/MC/MCAsmBackend.h"
31 #include "llvm/MC/MCAsmInfo.h"
32 #include "llvm/MC/MCCodeEmitter.h"
33 #include "llvm/MC/MCContext.h"
34 #include "llvm/MC/MCInstrInfo.h"
35 #include "llvm/MC/MCObjectFileInfo.h"
36 #include "llvm/MC/MCObjectWriter.h"
37 #include "llvm/MC/MCParser/MCTargetAsmParser.h"
38 #include "llvm/MC/MCRegisterInfo.h"
39 #include "llvm/MC/MCStreamer.h"
40 #include "llvm/MC/MCSubtargetInfo.h"
41 #include "llvm/MC/TargetRegistry.h"
42 
43 #include "llvm/Support/CommandLine.h"
44 #include "llvm/Support/FileUtilities.h"
45 #include "llvm/Support/Path.h"
46 #include "llvm/Support/Program.h"
47 #include "llvm/Support/SourceMgr.h"
48 #include "llvm/Support/TargetSelect.h"
49 #include "llvm/Support/WithColor.h"
50 
51 #include "llvm/Target/TargetMachine.h"
52 #include "llvm/Target/TargetOptions.h"
53 
54 #include "llvm/Transforms/IPO/Internalize.h"
55 
56 #include <mutex>
57 
58 using namespace mlir;
59 
60 namespace {
61 class SerializeToHsacoPass
62     : public PassWrapper<SerializeToHsacoPass, gpu::SerializeToBlobPass> {
63 public:
64   SerializeToHsacoPass(StringRef triple, StringRef arch, StringRef features,
65                        int optLevel);
66   SerializeToHsacoPass(const SerializeToHsacoPass &other);
67   StringRef getArgument() const override { return "gpu-to-hsaco"; }
68   StringRef getDescription() const override {
69     return "Lower GPU kernel function to HSACO binary annotations";
70   }
71 
72 protected:
73   Option<int> optLevel{
74       *this, "opt-level",
75       llvm::cl::desc("Optimization level for HSACO compilation"),
76       llvm::cl::init(2)};
77 
78   Option<std::string> rocmPath{*this, "rocm-path",
79                                llvm::cl::desc("Path to ROCm install")};
80 
81   // Overload to allow linking in device libs
82   std::unique_ptr<llvm::Module>
83   translateToLLVMIR(llvm::LLVMContext &llvmContext) override;
84 
85   /// Adds LLVM optimization passes
86   LogicalResult optimizeLlvm(llvm::Module &llvmModule,
87                              llvm::TargetMachine &targetMachine) override;
88 
89 private:
90   void getDependentDialects(DialectRegistry &registry) const override;
91 
92   // Loads LLVM bitcode libraries
93   Optional<SmallVector<std::unique_ptr<llvm::Module>, 3>>
94   loadLibraries(SmallVectorImpl<char> &path,
95                 SmallVectorImpl<StringRef> &libraries,
96                 llvm::LLVMContext &context);
97 
98   // Serializes ROCDL to HSACO.
99   std::unique_ptr<std::vector<char>>
100   serializeISA(const std::string &isa) override;
101 
102   std::unique_ptr<SmallVectorImpl<char>> assembleIsa(const std::string &isa);
103   std::unique_ptr<std::vector<char>>
104   createHsaco(const SmallVectorImpl<char> &isaBinary);
105 
106   std::string getRocmPath();
107 };
108 } // namespace
109 
110 SerializeToHsacoPass::SerializeToHsacoPass(const SerializeToHsacoPass &other)
111     : PassWrapper<SerializeToHsacoPass, gpu::SerializeToBlobPass>(other) {}
112 
113 /// Get a user-specified path to ROCm
114 // Tries, in order, the --rocm-path option, the ROCM_PATH environment variable
115 // and a compile-time default
116 std::string SerializeToHsacoPass::getRocmPath() {
117   if (rocmPath.getNumOccurrences() > 0)
118     return rocmPath.getValue();
119 
120   return __DEFAULT_ROCM_PATH__;
121 }
122 
123 // Sets the 'option' to 'value' unless it already has a value.
124 static void maybeSetOption(Pass::Option<std::string> &option,
125                            function_ref<std::string()> getValue) {
126   if (!option.hasValue())
127     option = getValue();
128 }
129 
130 SerializeToHsacoPass::SerializeToHsacoPass(StringRef triple, StringRef arch,
131                                            StringRef features, int optLevel) {
132   maybeSetOption(this->triple, [&triple] { return triple.str(); });
133   maybeSetOption(this->chip, [&arch] { return arch.str(); });
134   maybeSetOption(this->features, [&features] { return features.str(); });
135   if (this->optLevel.getNumOccurrences() == 0)
136     this->optLevel.setValue(optLevel);
137 }
138 
139 void SerializeToHsacoPass::getDependentDialects(
140     DialectRegistry &registry) const {
141   registerROCDLDialectTranslation(registry);
142   gpu::SerializeToBlobPass::getDependentDialects(registry);
143 }
144 
145 Optional<SmallVector<std::unique_ptr<llvm::Module>, 3>>
146 SerializeToHsacoPass::loadLibraries(SmallVectorImpl<char> &path,
147                                     SmallVectorImpl<StringRef> &libraries,
148                                     llvm::LLVMContext &context) {
149   SmallVector<std::unique_ptr<llvm::Module>, 3> ret;
150   size_t dirLength = path.size();
151 
152   if (!llvm::sys::fs::is_directory(path)) {
153     getOperation().emitRemark() << "Bitcode path: " << path
154                                 << " does not exist or is not a directory\n";
155     return llvm::None;
156   }
157 
158   for (const StringRef file : libraries) {
159     llvm::SMDiagnostic error;
160     llvm::sys::path::append(path, file);
161     llvm::StringRef pathRef(path.data(), path.size());
162     std::unique_ptr<llvm::Module> library =
163         llvm::getLazyIRFileModule(pathRef, error, context);
164     path.truncate(dirLength);
165     if (!library) {
166       getOperation().emitError() << "Failed to load library " << file
167                                  << " from " << path << error.getMessage();
168       return llvm::None;
169     }
170     // Some ROCM builds don't strip this like they should
171     if (auto *openclVersion = library->getNamedMetadata("opencl.ocl.version"))
172       library->eraseNamedMetadata(openclVersion);
173     // Stop spamming us with clang version numbers
174     if (auto *ident = library->getNamedMetadata("llvm.ident"))
175       library->eraseNamedMetadata(ident);
176     ret.push_back(std::move(library));
177   }
178 
179   return ret;
180 }
181 
182 std::unique_ptr<llvm::Module>
183 SerializeToHsacoPass::translateToLLVMIR(llvm::LLVMContext &llvmContext) {
184   // MLIR -> LLVM translation
185   std::unique_ptr<llvm::Module> ret =
186       gpu::SerializeToBlobPass::translateToLLVMIR(llvmContext);
187 
188   if (!ret) {
189     getOperation().emitOpError("Module lowering failed");
190     return ret;
191   }
192   // Walk the LLVM module in order to determine if we need to link in device
193   // libs
194   bool needOpenCl = false;
195   bool needOckl = false;
196   bool needOcml = false;
197   for (llvm::Function &f : ret->functions()) {
198     if (f.hasExternalLinkage() && f.hasName() && !f.hasExactDefinition()) {
199       StringRef funcName = f.getName();
200       if ("printf" == funcName)
201         needOpenCl = true;
202       if (funcName.startswith("__ockl_"))
203         needOckl = true;
204       if (funcName.startswith("__ocml_"))
205         needOcml = true;
206     }
207   }
208 
209   if (needOpenCl)
210     needOcml = needOckl = true;
211 
212   // No libraries needed (the typical case)
213   if (!(needOpenCl || needOcml || needOckl))
214     return ret;
215 
216   // Define one of the control constants the ROCm device libraries expect to be
217   // present These constants can either be defined in the module or can be
218   // imported by linking in bitcode that defines the constant. To simplify our
219   // logic, we define the constants into the module we are compiling
220   auto addControlConstant = [&module = *ret](StringRef name, uint32_t value,
221                                              uint32_t bitwidth) {
222     using llvm::GlobalVariable;
223     if (module.getNamedGlobal(name)) {
224       return;
225     }
226     llvm::IntegerType *type =
227         llvm::IntegerType::getIntNTy(module.getContext(), bitwidth);
228     auto *initializer = llvm::ConstantInt::get(type, value, /*isSigned=*/false);
229     auto *constant = new GlobalVariable(
230         module, type,
231         /*isConstant=*/true, GlobalVariable::LinkageTypes::LinkOnceODRLinkage,
232         initializer, name,
233         /*before=*/nullptr,
234         /*threadLocalMode=*/GlobalVariable::ThreadLocalMode::NotThreadLocal,
235         /*addressSpace=*/4);
236     constant->setUnnamedAddr(GlobalVariable::UnnamedAddr::Local);
237     constant->setVisibility(
238         GlobalVariable::VisibilityTypes::ProtectedVisibility);
239     constant->setAlignment(llvm::MaybeAlign(bitwidth / 8));
240   };
241 
242   if (needOcml) {
243     // TODO(kdrewnia): Enable math optimizations once we have support for
244     // `-ffast-math`-like options
245     addControlConstant("__oclc_finite_only_opt", 0, 8);
246     addControlConstant("__oclc_daz_opt", 0, 8);
247     addControlConstant("__oclc_correctly_rounded_sqrt32", 1, 8);
248     addControlConstant("__oclc_unsafe_math_opt", 0, 8);
249   }
250   if (needOcml || needOckl) {
251     addControlConstant("__oclc_wavefrontsize64", 1, 8);
252     StringRef chipSet = this->chip.getValue();
253     if (chipSet.startswith("gfx"))
254       chipSet = chipSet.substr(3);
255     uint32_t minor =
256         llvm::APInt(32, chipSet.substr(chipSet.size() - 2), 16).getZExtValue();
257     uint32_t major = llvm::APInt(32, chipSet.substr(0, chipSet.size() - 2), 10)
258                          .getZExtValue();
259     uint32_t isaNumber = minor + 1000 * major;
260     addControlConstant("__oclc_ISA_version", isaNumber, 32);
261   }
262 
263   // Determine libraries we need to link - order matters due to dependencies
264   llvm::SmallVector<StringRef, 4> libraries;
265   if (needOpenCl)
266     libraries.push_back("opencl.bc");
267   if (needOcml)
268     libraries.push_back("ocml.bc");
269   if (needOckl)
270     libraries.push_back("ockl.bc");
271 
272   Optional<SmallVector<std::unique_ptr<llvm::Module>, 3>> mbModules;
273   std::string theRocmPath = getRocmPath();
274   llvm::SmallString<32> bitcodePath(std::move(theRocmPath));
275   llvm::sys::path::append(bitcodePath, "amdgcn", "bitcode");
276   mbModules = loadLibraries(bitcodePath, libraries, llvmContext);
277 
278   if (!mbModules) {
279     getOperation()
280             .emitWarning("Could not load required device labraries")
281             .attachNote()
282         << "This will probably cause link-time or run-time failures";
283     return ret; // We can still abort here
284   }
285 
286   llvm::Linker linker(*ret);
287   for (std::unique_ptr<llvm::Module> &libModule : mbModules.getValue()) {
288     // This bitcode linking code is substantially similar to what is used in
289     // hip-clang It imports the library functions into the module, allowing LLVM
290     // optimization passes (which must run after linking) to optimize across the
291     // libraries and the module's code. We also only import symbols if they are
292     // referenced by the module or a previous library since there will be no
293     // other source of references to those symbols in this compilation and since
294     // we don't want to bloat the resulting code object.
295     bool err = linker.linkInModule(
296         std::move(libModule), llvm::Linker::Flags::LinkOnlyNeeded,
297         [](llvm::Module &m, const StringSet<> &gvs) {
298           llvm::internalizeModule(m, [&gvs](const llvm::GlobalValue &gv) {
299             return !gv.hasName() || (gvs.count(gv.getName()) == 0);
300           });
301         });
302     // True is linker failure
303     if (err) {
304       getOperation().emitError(
305           "Unrecoverable failure during device library linking.");
306       // We have no guaranties about the state of `ret`, so bail
307       return nullptr;
308     }
309   }
310 
311   return ret;
312 }
313 
314 LogicalResult
315 SerializeToHsacoPass::optimizeLlvm(llvm::Module &llvmModule,
316                                    llvm::TargetMachine &targetMachine) {
317   int optLevel = this->optLevel.getValue();
318   if (optLevel < 0 || optLevel > 3)
319     return getOperation().emitError()
320            << "Invalid HSA optimization level" << optLevel << "\n";
321 
322   targetMachine.setOptLevel(static_cast<llvm::CodeGenOpt::Level>(optLevel));
323 
324   auto transformer =
325       makeOptimizingTransformer(optLevel, /*sizeLevel=*/0, &targetMachine);
326   auto error = transformer(&llvmModule);
327   if (error) {
328     InFlightDiagnostic mlirError = getOperation()->emitError();
329     llvm::handleAllErrors(
330         std::move(error), [&mlirError](const llvm::ErrorInfoBase &ei) {
331           mlirError << "Could not optimize LLVM IR: " << ei.message() << "\n";
332         });
333     return mlirError;
334   }
335   return success();
336 }
337 
338 std::unique_ptr<SmallVectorImpl<char>>
339 SerializeToHsacoPass::assembleIsa(const std::string &isa) {
340   auto loc = getOperation().getLoc();
341 
342   SmallVector<char, 0> result;
343   llvm::raw_svector_ostream os(result);
344 
345   llvm::Triple triple(llvm::Triple::normalize(this->triple));
346   std::string error;
347   const llvm::Target *target =
348       llvm::TargetRegistry::lookupTarget(triple.normalize(), error);
349   if (!target) {
350     emitError(loc, Twine("failed to lookup target: ") + error);
351     return {};
352   }
353 
354   llvm::SourceMgr srcMgr;
355   srcMgr.AddNewSourceBuffer(llvm::MemoryBuffer::getMemBuffer(isa),
356                             SMLoc());
357 
358   const llvm::MCTargetOptions mcOptions;
359   std::unique_ptr<llvm::MCRegisterInfo> mri(
360       target->createMCRegInfo(this->triple));
361   std::unique_ptr<llvm::MCAsmInfo> mai(
362       target->createMCAsmInfo(*mri, this->triple, mcOptions));
363   mai->setRelaxELFRelocations(true);
364   std::unique_ptr<llvm::MCSubtargetInfo> sti(
365       target->createMCSubtargetInfo(this->triple, this->chip, this->features));
366 
367   llvm::MCContext ctx(triple, mai.get(), mri.get(), sti.get(), &srcMgr,
368                       &mcOptions);
369   std::unique_ptr<llvm::MCObjectFileInfo> mofi(target->createMCObjectFileInfo(
370       ctx, /*PIC=*/false, /*LargeCodeModel=*/false));
371   ctx.setObjectFileInfo(mofi.get());
372 
373   SmallString<128> cwd;
374   if (!llvm::sys::fs::current_path(cwd))
375     ctx.setCompilationDir(cwd);
376 
377   std::unique_ptr<llvm::MCStreamer> mcStreamer;
378   std::unique_ptr<llvm::MCInstrInfo> mcii(target->createMCInstrInfo());
379 
380   llvm::MCCodeEmitter *ce = target->createMCCodeEmitter(*mcii, *mri, ctx);
381   llvm::MCAsmBackend *mab = target->createMCAsmBackend(*sti, *mri, mcOptions);
382   mcStreamer.reset(target->createMCObjectStreamer(
383       triple, ctx, std::unique_ptr<llvm::MCAsmBackend>(mab),
384       mab->createObjectWriter(os), std::unique_ptr<llvm::MCCodeEmitter>(ce),
385       *sti, mcOptions.MCRelaxAll, mcOptions.MCIncrementalLinkerCompatible,
386       /*DWARFMustBeAtTheEnd*/ false));
387   mcStreamer->setUseAssemblerInfoForParsing(true);
388 
389   std::unique_ptr<llvm::MCAsmParser> parser(
390       createMCAsmParser(srcMgr, ctx, *mcStreamer, *mai));
391   std::unique_ptr<llvm::MCTargetAsmParser> tap(
392       target->createMCAsmParser(*sti, *parser, *mcii, mcOptions));
393 
394   if (!tap) {
395     emitError(loc, "assembler initialization error");
396     return {};
397   }
398 
399   parser->setTargetParser(*tap);
400   parser->Run(false);
401 
402   return std::make_unique<SmallVector<char, 0>>(std::move(result));
403 }
404 
405 std::unique_ptr<std::vector<char>>
406 SerializeToHsacoPass::createHsaco(const SmallVectorImpl<char> &isaBinary) {
407   auto loc = getOperation().getLoc();
408 
409   // Save the ISA binary to a temp file.
410   int tempIsaBinaryFd = -1;
411   SmallString<128> tempIsaBinaryFilename;
412   if (llvm::sys::fs::createTemporaryFile("kernel", "o", tempIsaBinaryFd,
413                                          tempIsaBinaryFilename)) {
414     emitError(loc, "temporary file for ISA binary creation error");
415     return {};
416   }
417   llvm::FileRemover cleanupIsaBinary(tempIsaBinaryFilename);
418   llvm::raw_fd_ostream tempIsaBinaryOs(tempIsaBinaryFd, true);
419   tempIsaBinaryOs << StringRef(isaBinary.data(), isaBinary.size());
420   tempIsaBinaryOs.close();
421 
422   // Create a temp file for HSA code object.
423   int tempHsacoFD = -1;
424   SmallString<128> tempHsacoFilename;
425   if (llvm::sys::fs::createTemporaryFile("kernel", "hsaco", tempHsacoFD,
426                                          tempHsacoFilename)) {
427     emitError(loc, "temporary file for HSA code object creation error");
428     return {};
429   }
430   llvm::FileRemover cleanupHsaco(tempHsacoFilename);
431 
432   std::string theRocmPath = getRocmPath();
433   llvm::SmallString<32> lldPath(std::move(theRocmPath));
434   llvm::sys::path::append(lldPath, "llvm", "bin", "ld.lld");
435   int lldResult = llvm::sys::ExecuteAndWait(
436       lldPath,
437       {"ld.lld", "-shared", tempIsaBinaryFilename, "-o", tempHsacoFilename});
438   if (lldResult != 0) {
439     emitError(loc, "lld invocation error");
440     return {};
441   }
442 
443   // Load the HSA code object.
444   auto hsacoFile = openInputFile(tempHsacoFilename);
445   if (!hsacoFile) {
446     emitError(loc, "read HSA code object from temp file error");
447     return {};
448   }
449 
450   StringRef buffer = hsacoFile->getBuffer();
451   return std::make_unique<std::vector<char>>(buffer.begin(), buffer.end());
452 }
453 
454 std::unique_ptr<std::vector<char>>
455 SerializeToHsacoPass::serializeISA(const std::string &isa) {
456   auto isaBinary = assembleIsa(isa);
457   if (!isaBinary)
458     return {};
459   return createHsaco(*isaBinary);
460 }
461 
462 // Register pass to serialize GPU kernel functions to a HSACO binary annotation.
463 void mlir::registerGpuSerializeToHsacoPass() {
464   PassRegistration<SerializeToHsacoPass> registerSerializeToHSACO(
465       [] {
466         // Initialize LLVM AMDGPU backend.
467         LLVMInitializeAMDGPUAsmParser();
468         LLVMInitializeAMDGPUAsmPrinter();
469         LLVMInitializeAMDGPUTarget();
470         LLVMInitializeAMDGPUTargetInfo();
471         LLVMInitializeAMDGPUTargetMC();
472 
473         return std::make_unique<SerializeToHsacoPass>("amdgcn-amd-amdhsa", "",
474                                                       "", 2);
475       });
476 }
477 
478 /// Create an instance of the GPU kernel function to HSAco binary serialization
479 /// pass.
480 std::unique_ptr<Pass> mlir::createGpuSerializeToHsacoPass(StringRef triple,
481                                                           StringRef arch,
482                                                           StringRef features,
483                                                           int optLevel) {
484   return std::make_unique<SerializeToHsacoPass>(triple, arch, features,
485                                                 optLevel);
486 }
487 
488 #else  // MLIR_GPU_TO_HSACO_PASS_ENABLE
489 void mlir::registerGpuSerializeToHsacoPass() {}
490 #endif // MLIR_GPU_TO_HSACO_PASS_ENABLE
491