8 #include "llvm/Analysis/TargetLibraryInfo.h"
9 #include "llvm/Analysis/TargetTransformInfo.h"
10 #include "llvm/CodeGen/TargetSubtargetInfo.h"
11 #include "llvm/IR/AutoUpgrade.h"
12 #include "llvm/IR/AssemblyAnnotationWriter.h"
13 #include "llvm/IR/IntrinsicInst.h"
14 #include "llvm/Support/CBindingWrapping.h"
15 #include "llvm/Support/FileSystem.h"
16 #include "llvm/Support/Host.h"
17 #include "llvm/Target/TargetMachine.h"
18 #include "llvm/Transforms/IPO/PassManagerBuilder.h"
19 #include "llvm/Transforms/IPO/AlwaysInliner.h"
20 #include "llvm/Transforms/IPO/FunctionImport.h"
21 #include "llvm/Transforms/Instrumentation/AddressSanitizer.h"
22 #include "llvm/Transforms/Instrumentation/MemorySanitizer.h"
23 #include "llvm/Transforms/Instrumentation/ThreadSanitizer.h"
24 #include "llvm/Transforms/Utils/FunctionImportUtils.h"
25 #include "llvm/LTO/LTO.h"
27 #include "llvm-c/Transforms/PassManagerBuilder.h"
30 using namespace llvm::legacy;
32 typedef struct LLVMOpaquePass *LLVMPassRef;
33 typedef struct LLVMOpaqueTargetMachine *LLVMTargetMachineRef;
35 DEFINE_STDCXX_CONVERSION_FUNCTIONS(Pass, LLVMPassRef)
36 DEFINE_STDCXX_CONVERSION_FUNCTIONS(TargetMachine, LLVMTargetMachineRef)
37 DEFINE_STDCXX_CONVERSION_FUNCTIONS(PassManagerBuilder,
38 LLVMPassManagerBuilderRef)
40 extern "C" void LLVMInitializePasses() {
41 PassRegistry &Registry = *PassRegistry::getPassRegistry();
42 initializeCore(Registry);
43 initializeCodeGen(Registry);
44 initializeScalarOpts(Registry);
45 initializeVectorization(Registry);
46 initializeIPO(Registry);
47 initializeAnalysis(Registry);
48 initializeTransformUtils(Registry);
49 initializeInstCombine(Registry);
50 initializeInstrumentation(Registry);
51 initializeTarget(Registry);
54 enum class LLVMRustPassKind {
60 static LLVMRustPassKind toRust(PassKind Kind) {
63 return LLVMRustPassKind::Function;
65 return LLVMRustPassKind::Module;
67 return LLVMRustPassKind::Other;
71 extern "C" LLVMPassRef LLVMRustFindAndCreatePass(const char *PassName) {
72 StringRef SR(PassName);
73 PassRegistry *PR = PassRegistry::getPassRegistry();
75 const PassInfo *PI = PR->getPassInfo(SR);
77 return wrap(PI->createPass());
82 extern "C" LLVMPassRef LLVMRustCreateAddressSanitizerFunctionPass(bool Recover) {
83 const bool CompileKernel = false;
85 return wrap(createAddressSanitizerFunctionPass(CompileKernel, Recover));
88 extern "C" LLVMPassRef LLVMRustCreateModuleAddressSanitizerPass(bool Recover) {
89 const bool CompileKernel = false;
91 return wrap(createModuleAddressSanitizerLegacyPassPass(CompileKernel, Recover));
94 extern "C" LLVMPassRef LLVMRustCreateMemorySanitizerPass(int TrackOrigins, bool Recover) {
95 const bool CompileKernel = false;
97 return wrap(createMemorySanitizerLegacyPassPass(
98 MemorySanitizerOptions{TrackOrigins, Recover, CompileKernel}));
101 extern "C" LLVMPassRef LLVMRustCreateThreadSanitizerPass() {
102 return wrap(createThreadSanitizerLegacyPassPass());
105 extern "C" LLVMRustPassKind LLVMRustPassKind(LLVMPassRef RustPass) {
107 Pass *Pass = unwrap(RustPass);
108 return toRust(Pass->getPassKind());
111 extern "C" void LLVMRustAddPass(LLVMPassManagerRef PMR, LLVMPassRef RustPass) {
113 Pass *Pass = unwrap(RustPass);
114 PassManagerBase *PMB = unwrap(PMR);
119 void LLVMRustPassManagerBuilderPopulateThinLTOPassManager(
120 LLVMPassManagerBuilderRef PMBR,
121 LLVMPassManagerRef PMR
123 unwrap(PMBR)->populateThinLTOPassManager(*unwrap(PMR));
127 void LLVMRustAddLastExtensionPasses(
128 LLVMPassManagerBuilderRef PMBR, LLVMPassRef *Passes, size_t NumPasses) {
129 auto AddExtensionPasses = [Passes, NumPasses](
130 const PassManagerBuilder &Builder, PassManagerBase &PM) {
131 for (size_t I = 0; I < NumPasses; I++) {
132 PM.add(unwrap(Passes[I]));
135 // Add the passes to both of the pre-finalization extension points,
136 // so they are run for optimized and non-optimized builds.
137 unwrap(PMBR)->addExtension(PassManagerBuilder::EP_OptimizerLast,
139 unwrap(PMBR)->addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
143 #ifdef LLVM_COMPONENT_X86
144 #define SUBTARGET_X86 SUBTARGET(X86)
146 #define SUBTARGET_X86
149 #ifdef LLVM_COMPONENT_ARM
150 #define SUBTARGET_ARM SUBTARGET(ARM)
152 #define SUBTARGET_ARM
155 #ifdef LLVM_COMPONENT_AARCH64
156 #define SUBTARGET_AARCH64 SUBTARGET(AArch64)
158 #define SUBTARGET_AARCH64
161 #ifdef LLVM_COMPONENT_MIPS
162 #define SUBTARGET_MIPS SUBTARGET(Mips)
164 #define SUBTARGET_MIPS
167 #ifdef LLVM_COMPONENT_POWERPC
168 #define SUBTARGET_PPC SUBTARGET(PPC)
170 #define SUBTARGET_PPC
173 #ifdef LLVM_COMPONENT_SYSTEMZ
174 #define SUBTARGET_SYSTEMZ SUBTARGET(SystemZ)
176 #define SUBTARGET_SYSTEMZ
179 #ifdef LLVM_COMPONENT_MSP430
180 #define SUBTARGET_MSP430 SUBTARGET(MSP430)
182 #define SUBTARGET_MSP430
185 #ifdef LLVM_COMPONENT_RISCV
186 #define SUBTARGET_RISCV SUBTARGET(RISCV)
188 #define SUBTARGET_RISCV
191 #ifdef LLVM_COMPONENT_SPARC
192 #define SUBTARGET_SPARC SUBTARGET(Sparc)
194 #define SUBTARGET_SPARC
197 #ifdef LLVM_COMPONENT_HEXAGON
198 #define SUBTARGET_HEXAGON SUBTARGET(Hexagon)
200 #define SUBTARGET_HEXAGON
203 #define GEN_SUBTARGETS \
215 #define SUBTARGET(x) \
217 extern const SubtargetFeatureKV x##FeatureKV[]; \
218 extern const SubtargetFeatureKV x##SubTypeKV[]; \
224 extern "C" bool LLVMRustHasFeature(LLVMTargetMachineRef TM,
225 const char *Feature) {
226 TargetMachine *Target = unwrap(TM);
227 const MCSubtargetInfo *MCInfo = Target->getMCSubtargetInfo();
228 return MCInfo->checkFeatures(std::string("+") + Feature);
231 enum class LLVMRustCodeModel {
240 static CodeModel::Model fromRust(LLVMRustCodeModel Model) {
242 case LLVMRustCodeModel::Small:
243 return CodeModel::Small;
244 case LLVMRustCodeModel::Kernel:
245 return CodeModel::Kernel;
246 case LLVMRustCodeModel::Medium:
247 return CodeModel::Medium;
248 case LLVMRustCodeModel::Large:
249 return CodeModel::Large;
251 report_fatal_error("Bad CodeModel.");
255 enum class LLVMRustCodeGenOptLevel {
263 static CodeGenOpt::Level fromRust(LLVMRustCodeGenOptLevel Level) {
265 case LLVMRustCodeGenOptLevel::None:
266 return CodeGenOpt::None;
267 case LLVMRustCodeGenOptLevel::Less:
268 return CodeGenOpt::Less;
269 case LLVMRustCodeGenOptLevel::Default:
270 return CodeGenOpt::Default;
271 case LLVMRustCodeGenOptLevel::Aggressive:
272 return CodeGenOpt::Aggressive;
274 report_fatal_error("Bad CodeGenOptLevel.");
278 enum class LLVMRustRelocMode {
288 static Optional<Reloc::Model> fromRust(LLVMRustRelocMode RustReloc) {
290 case LLVMRustRelocMode::Default:
292 case LLVMRustRelocMode::Static:
293 return Reloc::Static;
294 case LLVMRustRelocMode::PIC:
296 case LLVMRustRelocMode::DynamicNoPic:
297 return Reloc::DynamicNoPIC;
298 case LLVMRustRelocMode::ROPI:
300 case LLVMRustRelocMode::RWPI:
302 case LLVMRustRelocMode::ROPIRWPI:
303 return Reloc::ROPI_RWPI;
305 report_fatal_error("Bad RelocModel.");
309 /// getLongestEntryLength - Return the length of the longest entry in the table.
310 template<typename KV>
311 static size_t getLongestEntryLength(ArrayRef<KV> Table) {
313 for (auto &I : Table)
314 MaxLen = std::max(MaxLen, std::strlen(I.Key));
318 extern "C" void LLVMRustPrintTargetCPUs(LLVMTargetMachineRef TM) {
319 const TargetMachine *Target = unwrap(TM);
320 const MCSubtargetInfo *MCInfo = Target->getMCSubtargetInfo();
321 const Triple::ArchType HostArch = Triple(sys::getProcessTriple()).getArch();
322 const Triple::ArchType TargetArch = Target->getTargetTriple().getArch();
323 const ArrayRef<SubtargetSubTypeKV> CPUTable = MCInfo->getCPUTable();
324 unsigned MaxCPULen = getLongestEntryLength(CPUTable);
326 printf("Available CPUs for this target:\n");
327 if (HostArch == TargetArch) {
328 const StringRef HostCPU = sys::getHostCPUName();
329 printf(" %-*s - Select the CPU of the current host (currently %.*s).\n",
330 MaxCPULen, "native", (int)HostCPU.size(), HostCPU.data());
332 for (auto &CPU : CPUTable)
333 printf(" %-*s\n", MaxCPULen, CPU.Key);
337 extern "C" void LLVMRustPrintTargetFeatures(LLVMTargetMachineRef TM) {
338 const TargetMachine *Target = unwrap(TM);
339 const MCSubtargetInfo *MCInfo = Target->getMCSubtargetInfo();
340 const ArrayRef<SubtargetFeatureKV> FeatTable = MCInfo->getFeatureTable();
341 unsigned MaxFeatLen = getLongestEntryLength(FeatTable);
343 printf("Available features for this target:\n");
344 for (auto &Feature : FeatTable)
345 printf(" %-*s - %s.\n", MaxFeatLen, Feature.Key, Feature.Desc);
348 printf("Use +feature to enable a feature, or -feature to disable it.\n"
349 "For example, rustc -C -target-cpu=mycpu -C "
350 "target-feature=+feature1,-feature2\n\n");
355 extern "C" void LLVMRustPrintTargetCPUs(LLVMTargetMachineRef) {
356 printf("Target CPU help is not supported by this LLVM version.\n\n");
359 extern "C" void LLVMRustPrintTargetFeatures(LLVMTargetMachineRef) {
360 printf("Target features help is not supported by this LLVM version.\n\n");
364 extern "C" const char* LLVMRustGetHostCPUName(size_t *len) {
365 StringRef Name = sys::getHostCPUName();
370 extern "C" LLVMTargetMachineRef LLVMRustCreateTargetMachine(
371 const char *TripleStr, const char *CPU, const char *Feature,
372 const char *ABIStr, LLVMRustCodeModel RustCM, LLVMRustRelocMode RustReloc,
373 LLVMRustCodeGenOptLevel RustOptLevel, bool UseSoftFloat,
374 bool PositionIndependentExecutable, bool FunctionSections,
376 bool TrapUnreachable,
379 bool EmitStackSizeSection) {
381 auto OptLevel = fromRust(RustOptLevel);
382 auto RM = fromRust(RustReloc);
385 Triple Trip(Triple::normalize(TripleStr));
386 const llvm::Target *TheTarget =
387 TargetRegistry::lookupTarget(Trip.getTriple(), Error);
388 if (TheTarget == nullptr) {
389 LLVMRustSetLastError(Error.c_str());
393 TargetOptions Options;
395 Options.FloatABIType = FloatABI::Default;
397 Options.FloatABIType = FloatABI::Soft;
399 Options.DataSections = DataSections;
400 Options.FunctionSections = FunctionSections;
401 Options.MCOptions.AsmVerbose = AsmComments;
402 Options.MCOptions.PreserveAsmComments = AsmComments;
403 Options.MCOptions.ABIName = ABIStr;
405 if (TrapUnreachable) {
406 // Tell LLVM to codegen `unreachable` into an explicit trap instruction.
407 // This limits the extent of possible undefined behavior in some cases, as
408 // it prevents control flow from "falling through" into whatever code
409 // happens to be laid out next in memory.
410 Options.TrapUnreachable = true;
414 Options.ThreadModel = ThreadModel::Single;
417 Options.EmitStackSizeSection = EmitStackSizeSection;
419 Optional<CodeModel::Model> CM;
420 if (RustCM != LLVMRustCodeModel::None)
421 CM = fromRust(RustCM);
422 TargetMachine *TM = TheTarget->createTargetMachine(
423 Trip.getTriple(), CPU, Feature, Options, RM, CM, OptLevel);
427 extern "C" void LLVMRustDisposeTargetMachine(LLVMTargetMachineRef TM) {
431 // Unfortunately, LLVM doesn't expose a C API to add the corresponding analysis
432 // passes for a target to a pass manager. We export that functionality through
434 extern "C" void LLVMRustAddAnalysisPasses(LLVMTargetMachineRef TM,
435 LLVMPassManagerRef PMR,
437 PassManagerBase *PM = unwrap(PMR);
439 createTargetTransformInfoWrapperPass(unwrap(TM)->getTargetIRAnalysis()));
442 extern "C" void LLVMRustConfigurePassManagerBuilder(
443 LLVMPassManagerBuilderRef PMBR, LLVMRustCodeGenOptLevel OptLevel,
444 bool MergeFunctions, bool SLPVectorize, bool LoopVectorize, bool PrepareForThinLTO,
445 const char* PGOGenPath, const char* PGOUsePath) {
446 #if LLVM_VERSION_GE(7, 0)
447 unwrap(PMBR)->MergeFunctions = MergeFunctions;
449 unwrap(PMBR)->SLPVectorize = SLPVectorize;
450 unwrap(PMBR)->OptLevel = fromRust(OptLevel);
451 unwrap(PMBR)->LoopVectorize = LoopVectorize;
452 unwrap(PMBR)->PrepareForThinLTO = PrepareForThinLTO;
456 unwrap(PMBR)->EnablePGOInstrGen = true;
457 unwrap(PMBR)->PGOInstrGen = PGOGenPath;
461 unwrap(PMBR)->PGOInstrUse = PGOUsePath;
465 // Unfortunately, the LLVM C API doesn't provide a way to set the `LibraryInfo`
466 // field of a PassManagerBuilder, we expose our own method of doing so.
467 extern "C" void LLVMRustAddBuilderLibraryInfo(LLVMPassManagerBuilderRef PMBR,
469 bool DisableSimplifyLibCalls) {
470 Triple TargetTriple(unwrap(M)->getTargetTriple());
471 TargetLibraryInfoImpl *TLI = new TargetLibraryInfoImpl(TargetTriple);
472 if (DisableSimplifyLibCalls)
473 TLI->disableAllFunctions();
474 unwrap(PMBR)->LibraryInfo = TLI;
477 // Unfortunately, the LLVM C API doesn't provide a way to create the
478 // TargetLibraryInfo pass, so we use this method to do so.
479 extern "C" void LLVMRustAddLibraryInfo(LLVMPassManagerRef PMR, LLVMModuleRef M,
480 bool DisableSimplifyLibCalls) {
481 Triple TargetTriple(unwrap(M)->getTargetTriple());
482 TargetLibraryInfoImpl TLII(TargetTriple);
483 if (DisableSimplifyLibCalls)
484 TLII.disableAllFunctions();
485 unwrap(PMR)->add(new TargetLibraryInfoWrapperPass(TLII));
488 // Unfortunately, the LLVM C API doesn't provide an easy way of iterating over
489 // all the functions in a module, so we do that manually here. You'll find
490 // similar code in clang's BackendUtil.cpp file.
491 extern "C" void LLVMRustRunFunctionPassManager(LLVMPassManagerRef PMR,
493 llvm::legacy::FunctionPassManager *P =
494 unwrap<llvm::legacy::FunctionPassManager>(PMR);
495 P->doInitialization();
497 // Upgrade all calls to old intrinsics first.
498 for (Module::iterator I = unwrap(M)->begin(), E = unwrap(M)->end(); I != E;)
499 UpgradeCallsToIntrinsic(&*I++); // must be post-increment, as we remove
501 for (Module::iterator I = unwrap(M)->begin(), E = unwrap(M)->end(); I != E;
503 if (!I->isDeclaration())
509 extern "C" void LLVMRustSetLLVMOptions(int Argc, char **Argv) {
510 // Initializing the command-line options more than once is not allowed. So,
511 // check if they've already been initialized. (This could happen if we're
512 // being called from rustpkg, for example). If the arguments change, then
513 // that's just kinda unfortunate.
514 static bool Initialized = false;
518 cl::ParseCommandLineOptions(Argc, Argv);
521 enum class LLVMRustFileType {
527 static TargetMachine::CodeGenFileType fromRust(LLVMRustFileType Type) {
529 case LLVMRustFileType::AssemblyFile:
530 return TargetMachine::CGFT_AssemblyFile;
531 case LLVMRustFileType::ObjectFile:
532 return TargetMachine::CGFT_ObjectFile;
534 report_fatal_error("Bad FileType.");
538 extern "C" LLVMRustResult
539 LLVMRustWriteOutputFile(LLVMTargetMachineRef Target, LLVMPassManagerRef PMR,
540 LLVMModuleRef M, const char *Path,
541 LLVMRustFileType RustFileType) {
542 llvm::legacy::PassManager *PM = unwrap<llvm::legacy::PassManager>(PMR);
543 auto FileType = fromRust(RustFileType);
545 std::string ErrorInfo;
547 raw_fd_ostream OS(Path, EC, sys::fs::F_None);
549 ErrorInfo = EC.message();
550 if (ErrorInfo != "") {
551 LLVMRustSetLastError(ErrorInfo.c_str());
552 return LLVMRustResult::Failure;
555 #if LLVM_VERSION_GE(7, 0)
556 buffer_ostream BOS(OS);
557 unwrap(Target)->addPassesToEmitFile(*PM, BOS, nullptr, FileType, false);
559 unwrap(Target)->addPassesToEmitFile(*PM, OS, FileType, false);
563 // Apparently `addPassesToEmitFile` adds a pointer to our on-the-stack output
564 // stream (OS), so the only real safe place to delete this is here? Don't we
565 // wish this was written in Rust?
567 return LLVMRustResult::Success;
571 // Callback to demangle function name
573 // * name to be demangled
576 // * output buffer len
577 // Returns len of demangled string, or 0 if demangle failed.
578 typedef size_t (*DemangleFn)(const char*, size_t, char*, size_t);
583 class RustAssemblyAnnotationWriter : public AssemblyAnnotationWriter {
585 std::vector<char> Buf;
588 RustAssemblyAnnotationWriter(DemangleFn Demangle) : Demangle(Demangle) {}
590 // Return empty string if demangle failed
591 // or if name does not need to be demangled
592 StringRef CallDemangle(StringRef name) {
597 if (Buf.size() < name.size() * 2) {
598 // Semangled name usually shorter than mangled,
599 // but allocate twice as much memory just in case
600 Buf.resize(name.size() * 2);
603 auto R = Demangle(name.data(), name.size(), Buf.data(), Buf.size());
609 auto Demangled = StringRef(Buf.data(), R);
610 if (Demangled == name) {
611 // Do not print anything if demangled name is equal to mangled.
618 void emitFunctionAnnot(const Function *F,
619 formatted_raw_ostream &OS) override {
620 StringRef Demangled = CallDemangle(F->getName());
621 if (Demangled.empty()) {
625 OS << "; " << Demangled << "\n";
628 void emitInstructionAnnot(const Instruction *I,
629 formatted_raw_ostream &OS) override {
632 if (const CallInst *CI = dyn_cast<CallInst>(I)) {
634 Value = CI->getCalledValue();
635 } else if (const InvokeInst* II = dyn_cast<InvokeInst>(I)) {
637 Value = II->getCalledValue();
639 // Could demangle more operations, e. g.
640 // `store %place, @function`.
644 if (!Value->hasName()) {
648 StringRef Demangled = CallDemangle(Value->getName());
649 if (Demangled.empty()) {
653 OS << "; " << Name << " " << Demangled << "\n";
657 class RustPrintModulePass : public ModulePass {
662 RustPrintModulePass() : ModulePass(ID), OS(nullptr), Demangle(nullptr) {}
663 RustPrintModulePass(raw_ostream &OS, DemangleFn Demangle)
664 : ModulePass(ID), OS(&OS), Demangle(Demangle) {}
666 bool runOnModule(Module &M) override {
667 RustAssemblyAnnotationWriter AW(Demangle);
669 M.print(*OS, &AW, false);
674 void getAnalysisUsage(AnalysisUsage &AU) const override {
675 AU.setPreservesAll();
678 static StringRef name() { return "RustPrintModulePass"; }
684 void initializeRustPrintModulePassPass(PassRegistry&);
687 char RustPrintModulePass::ID = 0;
688 INITIALIZE_PASS(RustPrintModulePass, "print-rust-module",
689 "Print rust module to stderr", false, false)
691 extern "C" LLVMRustResult
692 LLVMRustPrintModule(LLVMPassManagerRef PMR, LLVMModuleRef M,
693 const char *Path, DemangleFn Demangle) {
694 llvm::legacy::PassManager *PM = unwrap<llvm::legacy::PassManager>(PMR);
695 std::string ErrorInfo;
698 raw_fd_ostream OS(Path, EC, sys::fs::F_None);
700 ErrorInfo = EC.message();
701 if (ErrorInfo != "") {
702 LLVMRustSetLastError(ErrorInfo.c_str());
703 return LLVMRustResult::Failure;
706 formatted_raw_ostream FOS(OS);
708 PM->add(new RustPrintModulePass(FOS, Demangle));
712 return LLVMRustResult::Success;
715 extern "C" void LLVMRustPrintPasses() {
716 LLVMInitializePasses();
717 struct MyListener : PassRegistrationListener {
718 void passEnumerate(const PassInfo *Info) {
719 StringRef PassArg = Info->getPassArgument();
720 StringRef PassName = Info->getPassName();
721 if (!PassArg.empty()) {
722 // These unsigned->signed casts could theoretically overflow, but
723 // realistically never will (and even if, the result is implementation
724 // defined rather plain UB).
725 printf("%15.*s - %.*s\n", (int)PassArg.size(), PassArg.data(),
726 (int)PassName.size(), PassName.data());
731 PassRegistry *PR = PassRegistry::getPassRegistry();
732 PR->enumerateWith(&Listener);
735 extern "C" void LLVMRustAddAlwaysInlinePass(LLVMPassManagerBuilderRef PMBR,
737 unwrap(PMBR)->Inliner = llvm::createAlwaysInlinerLegacyPass(AddLifetimes);
740 extern "C" void LLVMRustRunRestrictionPass(LLVMModuleRef M, char **Symbols,
742 llvm::legacy::PassManager passes;
744 auto PreserveFunctions = [=](const GlobalValue &GV) {
745 for (size_t I = 0; I < Len; I++) {
746 if (GV.getName() == Symbols[I]) {
753 passes.add(llvm::createInternalizePass(PreserveFunctions));
755 passes.run(*unwrap(M));
758 extern "C" void LLVMRustMarkAllFunctionsNounwind(LLVMModuleRef M) {
759 for (Module::iterator GV = unwrap(M)->begin(), E = unwrap(M)->end(); GV != E;
761 GV->setDoesNotThrow();
762 Function *F = dyn_cast<Function>(GV);
766 for (Function::iterator B = F->begin(), BE = F->end(); B != BE; ++B) {
767 for (BasicBlock::iterator I = B->begin(), IE = B->end(); I != IE; ++I) {
768 if (isa<InvokeInst>(I)) {
769 InvokeInst *CI = cast<InvokeInst>(I);
770 CI->setDoesNotThrow();
778 LLVMRustSetDataLayoutFromTargetMachine(LLVMModuleRef Module,
779 LLVMTargetMachineRef TMR) {
780 TargetMachine *Target = unwrap(TMR);
781 unwrap(Module)->setDataLayout(Target->createDataLayout());
784 extern "C" void LLVMRustSetModulePICLevel(LLVMModuleRef M) {
785 unwrap(M)->setPICLevel(PICLevel::Level::BigPIC);
788 extern "C" void LLVMRustSetModulePIELevel(LLVMModuleRef M) {
789 unwrap(M)->setPIELevel(PIELevel::Level::Large);
792 // Here you'll find an implementation of ThinLTO as used by the Rust compiler
793 // right now. This ThinLTO support is only enabled on "recent ish" versions of
794 // LLVM, and otherwise it's just blanket rejected from other compilers.
796 // Most of this implementation is straight copied from LLVM. At the time of
797 // this writing it wasn't *quite* suitable to reuse more code from upstream
798 // for our purposes, but we should strive to upstream this support once it's
799 // ready to go! I figure we may want a bit of testing locally first before
800 // sending this upstream to LLVM. I hear though they're quite eager to receive
801 // feedback like this!
803 // If you're reading this code and wondering "what in the world" or you're
804 // working "good lord by LLVM upgrade is *still* failing due to these bindings"
805 // then fear not! (ok maybe fear a little). All code here is mostly based
806 // on `lib/LTO/ThinLTOCodeGenerator.cpp` in LLVM.
808 // You'll find that the general layout here roughly corresponds to the `run`
809 // method in that file as well as `ProcessThinLTOModule`. Functions are
810 // specifically commented below as well, but if you're updating this code
811 // or otherwise trying to understand it, the LLVM source will be useful in
812 // interpreting the mysteries within.
814 // Otherwise I'll apologize in advance, it probably requires a relatively
815 // significant investment on your part to "truly understand" what's going on
816 // here. Not saying I do myself, but it took me awhile staring at LLVM's source
817 // and various online resources about ThinLTO to make heads or tails of all
820 // This is a shared data structure which *must* be threadsafe to share
821 // read-only amongst threads. This also corresponds basically to the arguments
822 // of the `ProcessThinLTOModule` function in the LLVM source.
823 struct LLVMRustThinLTOData {
824 // The combined index that is the global analysis over all modules we're
825 // performing ThinLTO for. This is mostly managed by LLVM.
826 ModuleSummaryIndex Index;
828 // All modules we may look at, stored as in-memory serialized versions. This
829 // is later used when inlining to ensure we can extract any module to inline
831 StringMap<MemoryBufferRef> ModuleMap;
833 // A set that we manage of everything we *don't* want internalized. Note that
834 // this includes all transitive references right now as well, but it may not
836 DenseSet<GlobalValue::GUID> GUIDPreservedSymbols;
838 // Not 100% sure what these are, but they impact what's internalized and
839 // what's inlined across modules, I believe.
840 StringMap<FunctionImporter::ImportMapTy> ImportLists;
841 StringMap<FunctionImporter::ExportSetTy> ExportLists;
842 StringMap<GVSummaryMapTy> ModuleToDefinedGVSummaries;
844 #if LLVM_VERSION_GE(7, 0)
845 LLVMRustThinLTOData() : Index(/* HaveGVs = */ false) {}
849 // Just an argument to the `LLVMRustCreateThinLTOData` function below.
850 struct LLVMRustThinLTOModule {
851 const char *identifier;
856 // This is copied from `lib/LTO/ThinLTOCodeGenerator.cpp`, not sure what it
858 static const GlobalValueSummary *
859 getFirstDefinitionForLinker(const GlobalValueSummaryList &GVSummaryList) {
860 auto StrongDefForLinker = llvm::find_if(
861 GVSummaryList, [](const std::unique_ptr<GlobalValueSummary> &Summary) {
862 auto Linkage = Summary->linkage();
863 return !GlobalValue::isAvailableExternallyLinkage(Linkage) &&
864 !GlobalValue::isWeakForLinker(Linkage);
866 if (StrongDefForLinker != GVSummaryList.end())
867 return StrongDefForLinker->get();
869 auto FirstDefForLinker = llvm::find_if(
870 GVSummaryList, [](const std::unique_ptr<GlobalValueSummary> &Summary) {
871 auto Linkage = Summary->linkage();
872 return !GlobalValue::isAvailableExternallyLinkage(Linkage);
874 if (FirstDefForLinker == GVSummaryList.end())
876 return FirstDefForLinker->get();
879 // The main entry point for creating the global ThinLTO analysis. The structure
880 // here is basically the same as before threads are spawned in the `run`
881 // function of `lib/LTO/ThinLTOCodeGenerator.cpp`.
882 extern "C" LLVMRustThinLTOData*
883 LLVMRustCreateThinLTOData(LLVMRustThinLTOModule *modules,
885 const char **preserved_symbols,
887 auto Ret = llvm::make_unique<LLVMRustThinLTOData>();
889 // Load each module's summary and merge it into one combined index
890 for (int i = 0; i < num_modules; i++) {
891 auto module = &modules[i];
892 StringRef buffer(module->data, module->len);
893 MemoryBufferRef mem_buffer(buffer, module->identifier);
895 Ret->ModuleMap[module->identifier] = mem_buffer;
897 if (Error Err = readModuleSummaryIndex(mem_buffer, Ret->Index, i)) {
898 LLVMRustSetLastError(toString(std::move(Err)).c_str());
903 // Collect for each module the list of function it defines (GUID -> Summary)
904 Ret->Index.collectDefinedGVSummariesPerModule(Ret->ModuleToDefinedGVSummaries);
906 // Convert the preserved symbols set from string to GUID, this is then needed
907 // for internalization.
908 for (int i = 0; i < num_symbols; i++) {
909 auto GUID = GlobalValue::getGUID(preserved_symbols[i]);
910 Ret->GUIDPreservedSymbols.insert(GUID);
913 // Collect the import/export lists for all modules from the call-graph in the
916 // This is copied from `lib/LTO/ThinLTOCodeGenerator.cpp`
917 #if LLVM_VERSION_GE(7, 0)
918 auto deadIsPrevailing = [&](GlobalValue::GUID G) {
919 return PrevailingType::Unknown;
921 #if LLVM_VERSION_GE(8, 0)
922 // We don't have a complete picture in our use of ThinLTO, just our immediate
923 // crate, so we need `ImportEnabled = false` to limit internalization.
924 // Otherwise, we sometimes lose `static` values -- see #60184.
925 computeDeadSymbolsWithConstProp(Ret->Index, Ret->GUIDPreservedSymbols,
926 deadIsPrevailing, /* ImportEnabled = */ false);
928 computeDeadSymbols(Ret->Index, Ret->GUIDPreservedSymbols, deadIsPrevailing);
931 computeDeadSymbols(Ret->Index, Ret->GUIDPreservedSymbols);
933 ComputeCrossModuleImport(
935 Ret->ModuleToDefinedGVSummaries,
940 // Resolve LinkOnce/Weak symbols, this has to be computed early be cause it
941 // impacts the caching.
943 // This is copied from `lib/LTO/ThinLTOCodeGenerator.cpp` with some of this
944 // being lifted from `lib/LTO/LTO.cpp` as well
945 StringMap<std::map<GlobalValue::GUID, GlobalValue::LinkageTypes>> ResolvedODR;
946 DenseMap<GlobalValue::GUID, const GlobalValueSummary *> PrevailingCopy;
947 for (auto &I : Ret->Index) {
948 if (I.second.SummaryList.size() > 1)
949 PrevailingCopy[I.first] = getFirstDefinitionForLinker(I.second.SummaryList);
951 auto isPrevailing = [&](GlobalValue::GUID GUID, const GlobalValueSummary *S) {
952 const auto &Prevailing = PrevailingCopy.find(GUID);
953 if (Prevailing == PrevailingCopy.end())
955 return Prevailing->second == S;
957 auto recordNewLinkage = [&](StringRef ModuleIdentifier,
958 GlobalValue::GUID GUID,
959 GlobalValue::LinkageTypes NewLinkage) {
960 ResolvedODR[ModuleIdentifier][GUID] = NewLinkage;
962 #if LLVM_VERSION_GE(9, 0)
963 thinLTOResolvePrevailingInIndex(Ret->Index, isPrevailing, recordNewLinkage,
964 Ret->GUIDPreservedSymbols);
965 #elif LLVM_VERSION_GE(8, 0)
966 thinLTOResolvePrevailingInIndex(Ret->Index, isPrevailing, recordNewLinkage);
968 thinLTOResolveWeakForLinkerInIndex(Ret->Index, isPrevailing, recordNewLinkage);
971 // Here we calculate an `ExportedGUIDs` set for use in the `isExported`
972 // callback below. This callback below will dictate the linkage for all
973 // summaries in the index, and we basically just only want to ensure that dead
974 // symbols are internalized. Otherwise everything that's already external
975 // linkage will stay as external, and internal will stay as internal.
976 std::set<GlobalValue::GUID> ExportedGUIDs;
977 for (auto &List : Ret->Index) {
978 for (auto &GVS: List.second.SummaryList) {
979 if (GlobalValue::isLocalLinkage(GVS->linkage()))
981 auto GUID = GVS->getOriginalName();
982 if (GVS->flags().Live)
983 ExportedGUIDs.insert(GUID);
986 auto isExported = [&](StringRef ModuleIdentifier, GlobalValue::GUID GUID) {
987 const auto &ExportList = Ret->ExportLists.find(ModuleIdentifier);
988 return (ExportList != Ret->ExportLists.end() &&
989 ExportList->second.count(GUID)) ||
990 ExportedGUIDs.count(GUID);
992 thinLTOInternalizeAndPromoteInIndex(Ret->Index, isExported);
994 return Ret.release();
998 LLVMRustFreeThinLTOData(LLVMRustThinLTOData *Data) {
1002 // Below are the various passes that happen *per module* when doing ThinLTO.
1004 // In other words, these are the functions that are all run concurrently
1005 // with one another, one per module. The passes here correspond to the analysis
1006 // passes in `lib/LTO/ThinLTOCodeGenerator.cpp`, currently found in the
1007 // `ProcessThinLTOModule` function. Here they're split up into separate steps
1008 // so rustc can save off the intermediate bytecode between each step.
1011 LLVMRustPrepareThinLTORename(const LLVMRustThinLTOData *Data, LLVMModuleRef M) {
1012 Module &Mod = *unwrap(M);
1013 if (renameModuleForThinLTO(Mod, Data->Index)) {
1014 LLVMRustSetLastError("renameModuleForThinLTO failed");
1021 LLVMRustPrepareThinLTOResolveWeak(const LLVMRustThinLTOData *Data, LLVMModuleRef M) {
1022 Module &Mod = *unwrap(M);
1023 const auto &DefinedGlobals = Data->ModuleToDefinedGVSummaries.lookup(Mod.getModuleIdentifier());
1024 #if LLVM_VERSION_GE(8, 0)
1025 thinLTOResolvePrevailingInModule(Mod, DefinedGlobals);
1027 thinLTOResolveWeakForLinkerModule(Mod, DefinedGlobals);
1033 LLVMRustPrepareThinLTOInternalize(const LLVMRustThinLTOData *Data, LLVMModuleRef M) {
1034 Module &Mod = *unwrap(M);
1035 const auto &DefinedGlobals = Data->ModuleToDefinedGVSummaries.lookup(Mod.getModuleIdentifier());
1036 thinLTOInternalizeModule(Mod, DefinedGlobals);
1041 LLVMRustPrepareThinLTOImport(const LLVMRustThinLTOData *Data, LLVMModuleRef M) {
1042 Module &Mod = *unwrap(M);
1044 const auto &ImportList = Data->ImportLists.lookup(Mod.getModuleIdentifier());
1045 auto Loader = [&](StringRef Identifier) {
1046 const auto &Memory = Data->ModuleMap.lookup(Identifier);
1047 auto &Context = Mod.getContext();
1048 auto MOrErr = getLazyBitcodeModule(Memory, Context, true, true);
1053 // The rest of this closure is a workaround for
1054 // https://bugs.llvm.org/show_bug.cgi?id=38184 where during ThinLTO imports
1055 // we accidentally import wasm custom sections into different modules,
1056 // duplicating them by in the final output artifact.
1058 // The issue is worked around here by manually removing the
1059 // `wasm.custom_sections` named metadata node from any imported module. This
1060 // we know isn't used by any optimization pass so there's no need for it to
1063 // Note that the metadata is currently lazily loaded, so we materialize it
1064 // here before looking up if there's metadata inside. The `FunctionImporter`
1065 // will immediately materialize metadata anyway after an import, so this
1066 // shouldn't be a perf hit.
1067 if (Error Err = (*MOrErr)->materializeMetadata()) {
1068 Expected<std::unique_ptr<Module>> Ret(std::move(Err));
1072 auto *WasmCustomSections = (*MOrErr)->getNamedMetadata("wasm.custom_sections");
1073 if (WasmCustomSections)
1074 WasmCustomSections->eraseFromParent();
1078 FunctionImporter Importer(Data->Index, Loader);
1079 Expected<bool> Result = Importer.importFunctions(Mod, ImportList);
1081 LLVMRustSetLastError(toString(Result.takeError()).c_str());
1087 extern "C" typedef void (*LLVMRustModuleNameCallback)(void*, // payload
1088 const char*, // importing module name
1089 const char*); // imported module name
1091 // Calls `module_name_callback` for each module import done by ThinLTO.
1092 // The callback is provided with regular null-terminated C strings.
1094 LLVMRustGetThinLTOModuleImports(const LLVMRustThinLTOData *data,
1095 LLVMRustModuleNameCallback module_name_callback,
1096 void* callback_payload) {
1097 for (const auto& importing_module : data->ImportLists) {
1098 const std::string importing_module_id = importing_module.getKey().str();
1099 const auto& imports = importing_module.getValue();
1100 for (const auto& imported_module : imports) {
1101 const std::string imported_module_id = imported_module.getKey().str();
1102 module_name_callback(callback_payload,
1103 importing_module_id.c_str(),
1104 imported_module_id.c_str());
1109 // This struct and various functions are sort of a hack right now, but the
1110 // problem is that we've got in-memory LLVM modules after we generate and
1111 // optimize all codegen-units for one compilation in rustc. To be compatible
1112 // with the LTO support above we need to serialize the modules plus their
1113 // ThinLTO summary into memory.
1115 // This structure is basically an owned version of a serialize module, with
1116 // a ThinLTO summary attached.
1117 struct LLVMRustThinLTOBuffer {
1121 extern "C" LLVMRustThinLTOBuffer*
1122 LLVMRustThinLTOBufferCreate(LLVMModuleRef M) {
1123 auto Ret = llvm::make_unique<LLVMRustThinLTOBuffer>();
1125 raw_string_ostream OS(Ret->data);
1127 legacy::PassManager PM;
1128 PM.add(createWriteThinLTOBitcodePass(OS));
1132 return Ret.release();
1136 LLVMRustThinLTOBufferFree(LLVMRustThinLTOBuffer *Buffer) {
1140 extern "C" const void*
1141 LLVMRustThinLTOBufferPtr(const LLVMRustThinLTOBuffer *Buffer) {
1142 return Buffer->data.data();
1146 LLVMRustThinLTOBufferLen(const LLVMRustThinLTOBuffer *Buffer) {
1147 return Buffer->data.length();
1150 // This is what we used to parse upstream bitcode for actual ThinLTO
1151 // processing. We'll call this once per module optimized through ThinLTO, and
1152 // it'll be called concurrently on many threads.
1153 extern "C" LLVMModuleRef
1154 LLVMRustParseBitcodeForLTO(LLVMContextRef Context,
1157 const char *identifier) {
1158 StringRef Data(data, len);
1159 MemoryBufferRef Buffer(Data, identifier);
1160 unwrap(Context)->enableDebugTypeODRUniquing();
1161 Expected<std::unique_ptr<Module>> SrcOrError =
1162 parseBitcodeFile(Buffer, *unwrap(Context));
1164 LLVMRustSetLastError(toString(SrcOrError.takeError()).c_str());
1167 return wrap(std::move(*SrcOrError).release());
1170 // Rewrite all `DICompileUnit` pointers to the `DICompileUnit` specified. See
1171 // the comment in `back/lto.rs` for why this exists.
1173 LLVMRustThinLTOGetDICompileUnit(LLVMModuleRef Mod,
1175 DICompileUnit **B) {
1176 Module *M = unwrap(Mod);
1177 DICompileUnit **Cur = A;
1178 DICompileUnit **Next = B;
1179 for (DICompileUnit *CU : M->debug_compile_units()) {
1188 // Rewrite all `DICompileUnit` pointers to the `DICompileUnit` specified. See
1189 // the comment in `back/lto.rs` for why this exists.
1191 LLVMRustThinLTOPatchDICompileUnit(LLVMModuleRef Mod, DICompileUnit *Unit) {
1192 Module *M = unwrap(Mod);
1194 // If the original source module didn't have a `DICompileUnit` then try to
1195 // merge all the existing compile units. If there aren't actually any though
1196 // then there's not much for us to do so return.
1197 if (Unit == nullptr) {
1198 for (DICompileUnit *CU : M->debug_compile_units()) {
1202 if (Unit == nullptr)
1206 // Use LLVM's built-in `DebugInfoFinder` to find a bunch of debuginfo and
1207 // process it recursively. Note that we specifically iterate over instructions
1208 // to ensure we feed everything into it.
1209 DebugInfoFinder Finder;
1210 Finder.processModule(*M);
1211 for (Function &F : M->functions()) {
1212 for (auto &FI : F) {
1213 for (Instruction &BI : FI) {
1214 if (auto Loc = BI.getDebugLoc())
1215 Finder.processLocation(*M, Loc);
1216 if (auto DVI = dyn_cast<DbgValueInst>(&BI))
1217 Finder.processValue(*M, DVI);
1218 if (auto DDI = dyn_cast<DbgDeclareInst>(&BI))
1219 Finder.processDeclare(*M, DDI);
1224 // After we've found all our debuginfo, rewrite all subprograms to point to
1225 // the same `DICompileUnit`.
1226 for (auto &F : Finder.subprograms()) {
1227 F->replaceUnit(Unit);
1230 // Erase any other references to other `DICompileUnit` instances, the verifier
1231 // will later ensure that we don't actually have any other stale references to
1233 auto *MD = M->getNamedMetadata("llvm.dbg.cu");
1234 MD->clearOperands();
1235 MD->addOperand(Unit);