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/Utils/FunctionImportUtils.h"
22 #include "llvm/LTO/LTO.h"
23 #include "llvm-c/Transforms/PassManagerBuilder.h"
25 #include "llvm/Transforms/Instrumentation.h"
26 #if LLVM_VERSION_GE(9, 0)
27 #include "llvm/Transforms/Instrumentation/AddressSanitizer.h"
29 #if LLVM_VERSION_GE(8, 0)
30 #include "llvm/Transforms/Instrumentation/ThreadSanitizer.h"
31 #include "llvm/Transforms/Instrumentation/MemorySanitizer.h"
35 using namespace llvm::legacy;
37 typedef struct LLVMOpaquePass *LLVMPassRef;
38 typedef struct LLVMOpaqueTargetMachine *LLVMTargetMachineRef;
40 DEFINE_STDCXX_CONVERSION_FUNCTIONS(Pass, LLVMPassRef)
41 DEFINE_STDCXX_CONVERSION_FUNCTIONS(TargetMachine, LLVMTargetMachineRef)
42 DEFINE_STDCXX_CONVERSION_FUNCTIONS(PassManagerBuilder,
43 LLVMPassManagerBuilderRef)
45 extern "C" void LLVMInitializePasses() {
46 PassRegistry &Registry = *PassRegistry::getPassRegistry();
47 initializeCore(Registry);
48 initializeCodeGen(Registry);
49 initializeScalarOpts(Registry);
50 initializeVectorization(Registry);
51 initializeIPO(Registry);
52 initializeAnalysis(Registry);
53 initializeTransformUtils(Registry);
54 initializeInstCombine(Registry);
55 initializeInstrumentation(Registry);
56 initializeTarget(Registry);
59 enum class LLVMRustPassKind {
65 static LLVMRustPassKind toRust(PassKind Kind) {
68 return LLVMRustPassKind::Function;
70 return LLVMRustPassKind::Module;
72 return LLVMRustPassKind::Other;
76 extern "C" LLVMPassRef LLVMRustFindAndCreatePass(const char *PassName) {
77 StringRef SR(PassName);
78 PassRegistry *PR = PassRegistry::getPassRegistry();
80 const PassInfo *PI = PR->getPassInfo(SR);
82 return wrap(PI->createPass());
87 extern "C" LLVMPassRef LLVMRustCreateAddressSanitizerFunctionPass(bool Recover) {
88 const bool CompileKernel = false;
90 return wrap(createAddressSanitizerFunctionPass(CompileKernel, Recover));
93 extern "C" LLVMPassRef LLVMRustCreateModuleAddressSanitizerPass(bool Recover) {
94 const bool CompileKernel = false;
96 #if LLVM_VERSION_GE(9, 0)
97 return wrap(createModuleAddressSanitizerLegacyPassPass(CompileKernel, Recover));
99 return wrap(createAddressSanitizerModulePass(CompileKernel, Recover));
103 extern "C" LLVMPassRef LLVMRustCreateMemorySanitizerPass(int TrackOrigins, bool Recover) {
104 #if LLVM_VERSION_GE(9, 0)
105 const bool CompileKernel = false;
107 return wrap(createMemorySanitizerLegacyPassPass(
108 MemorySanitizerOptions{TrackOrigins, Recover, CompileKernel}));
109 #elif LLVM_VERSION_GE(8, 0)
110 return wrap(createMemorySanitizerLegacyPassPass(TrackOrigins, Recover));
112 return wrap(createMemorySanitizerPass(TrackOrigins, Recover));
116 extern "C" LLVMPassRef LLVMRustCreateThreadSanitizerPass() {
117 #if LLVM_VERSION_GE(8, 0)
118 return wrap(createThreadSanitizerLegacyPassPass());
120 return wrap(createThreadSanitizerPass());
124 extern "C" LLVMRustPassKind LLVMRustPassKind(LLVMPassRef RustPass) {
126 Pass *Pass = unwrap(RustPass);
127 return toRust(Pass->getPassKind());
130 extern "C" void LLVMRustAddPass(LLVMPassManagerRef PMR, LLVMPassRef RustPass) {
132 Pass *Pass = unwrap(RustPass);
133 PassManagerBase *PMB = unwrap(PMR);
138 void LLVMRustPassManagerBuilderPopulateThinLTOPassManager(
139 LLVMPassManagerBuilderRef PMBR,
140 LLVMPassManagerRef PMR
142 unwrap(PMBR)->populateThinLTOPassManager(*unwrap(PMR));
146 void LLVMRustAddLastExtensionPasses(
147 LLVMPassManagerBuilderRef PMBR, LLVMPassRef *Passes, size_t NumPasses) {
148 auto AddExtensionPasses = [Passes, NumPasses](
149 const PassManagerBuilder &Builder, PassManagerBase &PM) {
150 for (size_t I = 0; I < NumPasses; I++) {
151 PM.add(unwrap(Passes[I]));
154 // Add the passes to both of the pre-finalization extension points,
155 // so they are run for optimized and non-optimized builds.
156 unwrap(PMBR)->addExtension(PassManagerBuilder::EP_OptimizerLast,
158 unwrap(PMBR)->addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
162 #ifdef LLVM_COMPONENT_X86
163 #define SUBTARGET_X86 SUBTARGET(X86)
165 #define SUBTARGET_X86
168 #ifdef LLVM_COMPONENT_ARM
169 #define SUBTARGET_ARM SUBTARGET(ARM)
171 #define SUBTARGET_ARM
174 #ifdef LLVM_COMPONENT_AARCH64
175 #define SUBTARGET_AARCH64 SUBTARGET(AArch64)
177 #define SUBTARGET_AARCH64
180 #ifdef LLVM_COMPONENT_MIPS
181 #define SUBTARGET_MIPS SUBTARGET(Mips)
183 #define SUBTARGET_MIPS
186 #ifdef LLVM_COMPONENT_POWERPC
187 #define SUBTARGET_PPC SUBTARGET(PPC)
189 #define SUBTARGET_PPC
192 #ifdef LLVM_COMPONENT_SYSTEMZ
193 #define SUBTARGET_SYSTEMZ SUBTARGET(SystemZ)
195 #define SUBTARGET_SYSTEMZ
198 #ifdef LLVM_COMPONENT_MSP430
199 #define SUBTARGET_MSP430 SUBTARGET(MSP430)
201 #define SUBTARGET_MSP430
204 #ifdef LLVM_COMPONENT_RISCV
205 #define SUBTARGET_RISCV SUBTARGET(RISCV)
207 #define SUBTARGET_RISCV
210 #ifdef LLVM_COMPONENT_SPARC
211 #define SUBTARGET_SPARC SUBTARGET(Sparc)
213 #define SUBTARGET_SPARC
216 #ifdef LLVM_COMPONENT_HEXAGON
217 #define SUBTARGET_HEXAGON SUBTARGET(Hexagon)
219 #define SUBTARGET_HEXAGON
222 #define GEN_SUBTARGETS \
234 #define SUBTARGET(x) \
236 extern const SubtargetFeatureKV x##FeatureKV[]; \
237 extern const SubtargetFeatureKV x##SubTypeKV[]; \
243 extern "C" bool LLVMRustHasFeature(LLVMTargetMachineRef TM,
244 const char *Feature) {
245 TargetMachine *Target = unwrap(TM);
246 const MCSubtargetInfo *MCInfo = Target->getMCSubtargetInfo();
247 return MCInfo->checkFeatures(std::string("+") + Feature);
250 enum class LLVMRustCodeModel {
259 static CodeModel::Model fromRust(LLVMRustCodeModel Model) {
261 case LLVMRustCodeModel::Small:
262 return CodeModel::Small;
263 case LLVMRustCodeModel::Kernel:
264 return CodeModel::Kernel;
265 case LLVMRustCodeModel::Medium:
266 return CodeModel::Medium;
267 case LLVMRustCodeModel::Large:
268 return CodeModel::Large;
270 report_fatal_error("Bad CodeModel.");
274 enum class LLVMRustCodeGenOptLevel {
282 static CodeGenOpt::Level fromRust(LLVMRustCodeGenOptLevel Level) {
284 case LLVMRustCodeGenOptLevel::None:
285 return CodeGenOpt::None;
286 case LLVMRustCodeGenOptLevel::Less:
287 return CodeGenOpt::Less;
288 case LLVMRustCodeGenOptLevel::Default:
289 return CodeGenOpt::Default;
290 case LLVMRustCodeGenOptLevel::Aggressive:
291 return CodeGenOpt::Aggressive;
293 report_fatal_error("Bad CodeGenOptLevel.");
297 enum class LLVMRustRelocMode {
307 static Optional<Reloc::Model> fromRust(LLVMRustRelocMode RustReloc) {
309 case LLVMRustRelocMode::Default:
311 case LLVMRustRelocMode::Static:
312 return Reloc::Static;
313 case LLVMRustRelocMode::PIC:
315 case LLVMRustRelocMode::DynamicNoPic:
316 return Reloc::DynamicNoPIC;
317 case LLVMRustRelocMode::ROPI:
319 case LLVMRustRelocMode::RWPI:
321 case LLVMRustRelocMode::ROPIRWPI:
322 return Reloc::ROPI_RWPI;
324 report_fatal_error("Bad RelocModel.");
328 /// getLongestEntryLength - Return the length of the longest entry in the table.
329 template<typename KV>
330 static size_t getLongestEntryLength(ArrayRef<KV> Table) {
332 for (auto &I : Table)
333 MaxLen = std::max(MaxLen, std::strlen(I.Key));
337 extern "C" void LLVMRustPrintTargetCPUs(LLVMTargetMachineRef TM) {
338 const TargetMachine *Target = unwrap(TM);
339 const MCSubtargetInfo *MCInfo = Target->getMCSubtargetInfo();
340 const Triple::ArchType HostArch = Triple(sys::getProcessTriple()).getArch();
341 const Triple::ArchType TargetArch = Target->getTargetTriple().getArch();
342 const ArrayRef<SubtargetSubTypeKV> CPUTable = MCInfo->getCPUTable();
343 unsigned MaxCPULen = getLongestEntryLength(CPUTable);
345 printf("Available CPUs for this target:\n");
346 if (HostArch == TargetArch) {
347 const StringRef HostCPU = sys::getHostCPUName();
348 printf(" %-*s - Select the CPU of the current host (currently %.*s).\n",
349 MaxCPULen, "native", (int)HostCPU.size(), HostCPU.data());
351 for (auto &CPU : CPUTable)
352 printf(" %-*s\n", MaxCPULen, CPU.Key);
356 extern "C" void LLVMRustPrintTargetFeatures(LLVMTargetMachineRef TM) {
357 const TargetMachine *Target = unwrap(TM);
358 const MCSubtargetInfo *MCInfo = Target->getMCSubtargetInfo();
359 const ArrayRef<SubtargetFeatureKV> FeatTable = MCInfo->getFeatureTable();
360 unsigned MaxFeatLen = getLongestEntryLength(FeatTable);
362 printf("Available features for this target:\n");
363 for (auto &Feature : FeatTable)
364 printf(" %-*s - %s.\n", MaxFeatLen, Feature.Key, Feature.Desc);
367 printf("Use +feature to enable a feature, or -feature to disable it.\n"
368 "For example, rustc -C -target-cpu=mycpu -C "
369 "target-feature=+feature1,-feature2\n\n");
374 extern "C" void LLVMRustPrintTargetCPUs(LLVMTargetMachineRef) {
375 printf("Target CPU help is not supported by this LLVM version.\n\n");
378 extern "C" void LLVMRustPrintTargetFeatures(LLVMTargetMachineRef) {
379 printf("Target features help is not supported by this LLVM version.\n\n");
383 extern "C" const char* LLVMRustGetHostCPUName(size_t *len) {
384 StringRef Name = sys::getHostCPUName();
389 extern "C" LLVMTargetMachineRef LLVMRustCreateTargetMachine(
390 const char *TripleStr, const char *CPU, const char *Feature,
391 const char *ABIStr, LLVMRustCodeModel RustCM, LLVMRustRelocMode RustReloc,
392 LLVMRustCodeGenOptLevel RustOptLevel, bool UseSoftFloat,
393 bool PositionIndependentExecutable, bool FunctionSections,
395 bool TrapUnreachable,
398 bool EmitStackSizeSection,
399 bool RelaxELFRelocations) {
401 auto OptLevel = fromRust(RustOptLevel);
402 auto RM = fromRust(RustReloc);
405 Triple Trip(Triple::normalize(TripleStr));
406 const llvm::Target *TheTarget =
407 TargetRegistry::lookupTarget(Trip.getTriple(), Error);
408 if (TheTarget == nullptr) {
409 LLVMRustSetLastError(Error.c_str());
413 TargetOptions Options;
415 Options.FloatABIType = FloatABI::Default;
417 Options.FloatABIType = FloatABI::Soft;
419 Options.DataSections = DataSections;
420 Options.FunctionSections = FunctionSections;
421 Options.MCOptions.AsmVerbose = AsmComments;
422 Options.MCOptions.PreserveAsmComments = AsmComments;
423 Options.MCOptions.ABIName = ABIStr;
424 Options.RelaxELFRelocations = RelaxELFRelocations;
426 if (TrapUnreachable) {
427 // Tell LLVM to codegen `unreachable` into an explicit trap instruction.
428 // This limits the extent of possible undefined behavior in some cases, as
429 // it prevents control flow from "falling through" into whatever code
430 // happens to be laid out next in memory.
431 Options.TrapUnreachable = true;
435 Options.ThreadModel = ThreadModel::Single;
438 Options.EmitStackSizeSection = EmitStackSizeSection;
440 Optional<CodeModel::Model> CM;
441 if (RustCM != LLVMRustCodeModel::None)
442 CM = fromRust(RustCM);
443 TargetMachine *TM = TheTarget->createTargetMachine(
444 Trip.getTriple(), CPU, Feature, Options, RM, CM, OptLevel);
448 extern "C" void LLVMRustDisposeTargetMachine(LLVMTargetMachineRef TM) {
452 extern "C" void LLVMRustConfigurePassManagerBuilder(
453 LLVMPassManagerBuilderRef PMBR, LLVMRustCodeGenOptLevel OptLevel,
454 bool MergeFunctions, bool SLPVectorize, bool LoopVectorize, bool PrepareForThinLTO,
455 const char* PGOGenPath, const char* PGOUsePath) {
456 unwrap(PMBR)->MergeFunctions = MergeFunctions;
457 unwrap(PMBR)->SLPVectorize = SLPVectorize;
458 unwrap(PMBR)->OptLevel = fromRust(OptLevel);
459 unwrap(PMBR)->LoopVectorize = LoopVectorize;
460 unwrap(PMBR)->PrepareForThinLTO = PrepareForThinLTO;
464 unwrap(PMBR)->EnablePGOInstrGen = true;
465 unwrap(PMBR)->PGOInstrGen = PGOGenPath;
469 unwrap(PMBR)->PGOInstrUse = PGOUsePath;
473 // Unfortunately, the LLVM C API doesn't provide a way to set the `LibraryInfo`
474 // field of a PassManagerBuilder, we expose our own method of doing so.
475 extern "C" void LLVMRustAddBuilderLibraryInfo(LLVMPassManagerBuilderRef PMBR,
477 bool DisableSimplifyLibCalls) {
478 Triple TargetTriple(unwrap(M)->getTargetTriple());
479 TargetLibraryInfoImpl *TLI = new TargetLibraryInfoImpl(TargetTriple);
480 if (DisableSimplifyLibCalls)
481 TLI->disableAllFunctions();
482 unwrap(PMBR)->LibraryInfo = TLI;
485 // Unfortunately, the LLVM C API doesn't provide a way to create the
486 // TargetLibraryInfo pass, so we use this method to do so.
487 extern "C" void LLVMRustAddLibraryInfo(LLVMPassManagerRef PMR, LLVMModuleRef M,
488 bool DisableSimplifyLibCalls) {
489 Triple TargetTriple(unwrap(M)->getTargetTriple());
490 TargetLibraryInfoImpl TLII(TargetTriple);
491 if (DisableSimplifyLibCalls)
492 TLII.disableAllFunctions();
493 unwrap(PMR)->add(new TargetLibraryInfoWrapperPass(TLII));
496 // Unfortunately, the LLVM C API doesn't provide an easy way of iterating over
497 // all the functions in a module, so we do that manually here. You'll find
498 // similar code in clang's BackendUtil.cpp file.
499 extern "C" void LLVMRustRunFunctionPassManager(LLVMPassManagerRef PMR,
501 llvm::legacy::FunctionPassManager *P =
502 unwrap<llvm::legacy::FunctionPassManager>(PMR);
503 P->doInitialization();
505 // Upgrade all calls to old intrinsics first.
506 for (Module::iterator I = unwrap(M)->begin(), E = unwrap(M)->end(); I != E;)
507 UpgradeCallsToIntrinsic(&*I++); // must be post-increment, as we remove
509 for (Module::iterator I = unwrap(M)->begin(), E = unwrap(M)->end(); I != E;
511 if (!I->isDeclaration())
517 extern "C" void LLVMRustSetLLVMOptions(int Argc, char **Argv) {
518 // Initializing the command-line options more than once is not allowed. So,
519 // check if they've already been initialized. (This could happen if we're
520 // being called from rustpkg, for example). If the arguments change, then
521 // that's just kinda unfortunate.
522 static bool Initialized = false;
526 cl::ParseCommandLineOptions(Argc, Argv);
529 enum class LLVMRustFileType {
535 static TargetMachine::CodeGenFileType fromRust(LLVMRustFileType Type) {
537 case LLVMRustFileType::AssemblyFile:
538 return TargetMachine::CGFT_AssemblyFile;
539 case LLVMRustFileType::ObjectFile:
540 return TargetMachine::CGFT_ObjectFile;
542 report_fatal_error("Bad FileType.");
546 extern "C" LLVMRustResult
547 LLVMRustWriteOutputFile(LLVMTargetMachineRef Target, LLVMPassManagerRef PMR,
548 LLVMModuleRef M, const char *Path,
549 LLVMRustFileType RustFileType) {
550 llvm::legacy::PassManager *PM = unwrap<llvm::legacy::PassManager>(PMR);
551 auto FileType = fromRust(RustFileType);
553 std::string ErrorInfo;
555 raw_fd_ostream OS(Path, EC, sys::fs::F_None);
557 ErrorInfo = EC.message();
558 if (ErrorInfo != "") {
559 LLVMRustSetLastError(ErrorInfo.c_str());
560 return LLVMRustResult::Failure;
563 buffer_ostream BOS(OS);
564 unwrap(Target)->addPassesToEmitFile(*PM, BOS, nullptr, FileType, false);
567 // Apparently `addPassesToEmitFile` adds a pointer to our on-the-stack output
568 // stream (OS), so the only real safe place to delete this is here? Don't we
569 // wish this was written in Rust?
570 LLVMDisposePassManager(PMR);
571 return LLVMRustResult::Success;
575 // Callback to demangle function name
577 // * name to be demangled
580 // * output buffer len
581 // Returns len of demangled string, or 0 if demangle failed.
582 typedef size_t (*DemangleFn)(const char*, size_t, char*, size_t);
587 class RustAssemblyAnnotationWriter : public AssemblyAnnotationWriter {
589 std::vector<char> Buf;
592 RustAssemblyAnnotationWriter(DemangleFn Demangle) : Demangle(Demangle) {}
594 // Return empty string if demangle failed
595 // or if name does not need to be demangled
596 StringRef CallDemangle(StringRef name) {
601 if (Buf.size() < name.size() * 2) {
602 // Semangled name usually shorter than mangled,
603 // but allocate twice as much memory just in case
604 Buf.resize(name.size() * 2);
607 auto R = Demangle(name.data(), name.size(), Buf.data(), Buf.size());
613 auto Demangled = StringRef(Buf.data(), R);
614 if (Demangled == name) {
615 // Do not print anything if demangled name is equal to mangled.
622 void emitFunctionAnnot(const Function *F,
623 formatted_raw_ostream &OS) override {
624 StringRef Demangled = CallDemangle(F->getName());
625 if (Demangled.empty()) {
629 OS << "; " << Demangled << "\n";
632 void emitInstructionAnnot(const Instruction *I,
633 formatted_raw_ostream &OS) override {
636 if (const CallInst *CI = dyn_cast<CallInst>(I)) {
638 Value = CI->getCalledValue();
639 } else if (const InvokeInst* II = dyn_cast<InvokeInst>(I)) {
641 Value = II->getCalledValue();
643 // Could demangle more operations, e. g.
644 // `store %place, @function`.
648 if (!Value->hasName()) {
652 StringRef Demangled = CallDemangle(Value->getName());
653 if (Demangled.empty()) {
657 OS << "; " << Name << " " << Demangled << "\n";
663 extern "C" LLVMRustResult
664 LLVMRustPrintModule(LLVMModuleRef M, const char *Path, DemangleFn Demangle) {
665 std::string ErrorInfo;
667 raw_fd_ostream OS(Path, EC, sys::fs::F_None);
669 ErrorInfo = EC.message();
670 if (ErrorInfo != "") {
671 LLVMRustSetLastError(ErrorInfo.c_str());
672 return LLVMRustResult::Failure;
675 RustAssemblyAnnotationWriter AAW(Demangle);
676 formatted_raw_ostream FOS(OS);
677 unwrap(M)->print(FOS, &AAW);
679 return LLVMRustResult::Success;
682 extern "C" void LLVMRustPrintPasses() {
683 LLVMInitializePasses();
684 struct MyListener : PassRegistrationListener {
685 void passEnumerate(const PassInfo *Info) {
686 StringRef PassArg = Info->getPassArgument();
687 StringRef PassName = Info->getPassName();
688 if (!PassArg.empty()) {
689 // These unsigned->signed casts could theoretically overflow, but
690 // realistically never will (and even if, the result is implementation
691 // defined rather plain UB).
692 printf("%15.*s - %.*s\n", (int)PassArg.size(), PassArg.data(),
693 (int)PassName.size(), PassName.data());
698 PassRegistry *PR = PassRegistry::getPassRegistry();
699 PR->enumerateWith(&Listener);
702 extern "C" void LLVMRustAddAlwaysInlinePass(LLVMPassManagerBuilderRef PMBR,
704 unwrap(PMBR)->Inliner = llvm::createAlwaysInlinerLegacyPass(AddLifetimes);
707 extern "C" void LLVMRustRunRestrictionPass(LLVMModuleRef M, char **Symbols,
709 llvm::legacy::PassManager passes;
711 auto PreserveFunctions = [=](const GlobalValue &GV) {
712 for (size_t I = 0; I < Len; I++) {
713 if (GV.getName() == Symbols[I]) {
720 passes.add(llvm::createInternalizePass(PreserveFunctions));
722 passes.run(*unwrap(M));
725 extern "C" void LLVMRustMarkAllFunctionsNounwind(LLVMModuleRef M) {
726 for (Module::iterator GV = unwrap(M)->begin(), E = unwrap(M)->end(); GV != E;
728 GV->setDoesNotThrow();
729 Function *F = dyn_cast<Function>(GV);
733 for (Function::iterator B = F->begin(), BE = F->end(); B != BE; ++B) {
734 for (BasicBlock::iterator I = B->begin(), IE = B->end(); I != IE; ++I) {
735 if (isa<InvokeInst>(I)) {
736 InvokeInst *CI = cast<InvokeInst>(I);
737 CI->setDoesNotThrow();
745 LLVMRustSetDataLayoutFromTargetMachine(LLVMModuleRef Module,
746 LLVMTargetMachineRef TMR) {
747 TargetMachine *Target = unwrap(TMR);
748 unwrap(Module)->setDataLayout(Target->createDataLayout());
751 extern "C" void LLVMRustSetModulePICLevel(LLVMModuleRef M) {
752 unwrap(M)->setPICLevel(PICLevel::Level::BigPIC);
755 extern "C" void LLVMRustSetModulePIELevel(LLVMModuleRef M) {
756 unwrap(M)->setPIELevel(PIELevel::Level::Large);
759 // Here you'll find an implementation of ThinLTO as used by the Rust compiler
760 // right now. This ThinLTO support is only enabled on "recent ish" versions of
761 // LLVM, and otherwise it's just blanket rejected from other compilers.
763 // Most of this implementation is straight copied from LLVM. At the time of
764 // this writing it wasn't *quite* suitable to reuse more code from upstream
765 // for our purposes, but we should strive to upstream this support once it's
766 // ready to go! I figure we may want a bit of testing locally first before
767 // sending this upstream to LLVM. I hear though they're quite eager to receive
768 // feedback like this!
770 // If you're reading this code and wondering "what in the world" or you're
771 // working "good lord by LLVM upgrade is *still* failing due to these bindings"
772 // then fear not! (ok maybe fear a little). All code here is mostly based
773 // on `lib/LTO/ThinLTOCodeGenerator.cpp` in LLVM.
775 // You'll find that the general layout here roughly corresponds to the `run`
776 // method in that file as well as `ProcessThinLTOModule`. Functions are
777 // specifically commented below as well, but if you're updating this code
778 // or otherwise trying to understand it, the LLVM source will be useful in
779 // interpreting the mysteries within.
781 // Otherwise I'll apologize in advance, it probably requires a relatively
782 // significant investment on your part to "truly understand" what's going on
783 // here. Not saying I do myself, but it took me awhile staring at LLVM's source
784 // and various online resources about ThinLTO to make heads or tails of all
787 // This is a shared data structure which *must* be threadsafe to share
788 // read-only amongst threads. This also corresponds basically to the arguments
789 // of the `ProcessThinLTOModule` function in the LLVM source.
790 struct LLVMRustThinLTOData {
791 // The combined index that is the global analysis over all modules we're
792 // performing ThinLTO for. This is mostly managed by LLVM.
793 ModuleSummaryIndex Index;
795 // All modules we may look at, stored as in-memory serialized versions. This
796 // is later used when inlining to ensure we can extract any module to inline
798 StringMap<MemoryBufferRef> ModuleMap;
800 // A set that we manage of everything we *don't* want internalized. Note that
801 // this includes all transitive references right now as well, but it may not
803 DenseSet<GlobalValue::GUID> GUIDPreservedSymbols;
805 // Not 100% sure what these are, but they impact what's internalized and
806 // what's inlined across modules, I believe.
807 StringMap<FunctionImporter::ImportMapTy> ImportLists;
808 StringMap<FunctionImporter::ExportSetTy> ExportLists;
809 StringMap<GVSummaryMapTy> ModuleToDefinedGVSummaries;
811 LLVMRustThinLTOData() : Index(/* HaveGVs = */ false) {}
814 // Just an argument to the `LLVMRustCreateThinLTOData` function below.
815 struct LLVMRustThinLTOModule {
816 const char *identifier;
821 // This is copied from `lib/LTO/ThinLTOCodeGenerator.cpp`, not sure what it
823 static const GlobalValueSummary *
824 getFirstDefinitionForLinker(const GlobalValueSummaryList &GVSummaryList) {
825 auto StrongDefForLinker = llvm::find_if(
826 GVSummaryList, [](const std::unique_ptr<GlobalValueSummary> &Summary) {
827 auto Linkage = Summary->linkage();
828 return !GlobalValue::isAvailableExternallyLinkage(Linkage) &&
829 !GlobalValue::isWeakForLinker(Linkage);
831 if (StrongDefForLinker != GVSummaryList.end())
832 return StrongDefForLinker->get();
834 auto FirstDefForLinker = llvm::find_if(
835 GVSummaryList, [](const std::unique_ptr<GlobalValueSummary> &Summary) {
836 auto Linkage = Summary->linkage();
837 return !GlobalValue::isAvailableExternallyLinkage(Linkage);
839 if (FirstDefForLinker == GVSummaryList.end())
841 return FirstDefForLinker->get();
844 // The main entry point for creating the global ThinLTO analysis. The structure
845 // here is basically the same as before threads are spawned in the `run`
846 // function of `lib/LTO/ThinLTOCodeGenerator.cpp`.
847 extern "C" LLVMRustThinLTOData*
848 LLVMRustCreateThinLTOData(LLVMRustThinLTOModule *modules,
850 const char **preserved_symbols,
852 auto Ret = llvm::make_unique<LLVMRustThinLTOData>();
854 // Load each module's summary and merge it into one combined index
855 for (int i = 0; i < num_modules; i++) {
856 auto module = &modules[i];
857 StringRef buffer(module->data, module->len);
858 MemoryBufferRef mem_buffer(buffer, module->identifier);
860 Ret->ModuleMap[module->identifier] = mem_buffer;
862 if (Error Err = readModuleSummaryIndex(mem_buffer, Ret->Index, i)) {
863 LLVMRustSetLastError(toString(std::move(Err)).c_str());
868 // Collect for each module the list of function it defines (GUID -> Summary)
869 Ret->Index.collectDefinedGVSummariesPerModule(Ret->ModuleToDefinedGVSummaries);
871 // Convert the preserved symbols set from string to GUID, this is then needed
872 // for internalization.
873 for (int i = 0; i < num_symbols; i++) {
874 auto GUID = GlobalValue::getGUID(preserved_symbols[i]);
875 Ret->GUIDPreservedSymbols.insert(GUID);
878 // Collect the import/export lists for all modules from the call-graph in the
881 // This is copied from `lib/LTO/ThinLTOCodeGenerator.cpp`
882 auto deadIsPrevailing = [&](GlobalValue::GUID G) {
883 return PrevailingType::Unknown;
885 #if LLVM_VERSION_GE(8, 0)
886 // We don't have a complete picture in our use of ThinLTO, just our immediate
887 // crate, so we need `ImportEnabled = false` to limit internalization.
888 // Otherwise, we sometimes lose `static` values -- see #60184.
889 computeDeadSymbolsWithConstProp(Ret->Index, Ret->GUIDPreservedSymbols,
890 deadIsPrevailing, /* ImportEnabled = */ false);
892 computeDeadSymbols(Ret->Index, Ret->GUIDPreservedSymbols, deadIsPrevailing);
894 ComputeCrossModuleImport(
896 Ret->ModuleToDefinedGVSummaries,
901 // Resolve LinkOnce/Weak symbols, this has to be computed early be cause it
902 // impacts the caching.
904 // This is copied from `lib/LTO/ThinLTOCodeGenerator.cpp` with some of this
905 // being lifted from `lib/LTO/LTO.cpp` as well
906 StringMap<std::map<GlobalValue::GUID, GlobalValue::LinkageTypes>> ResolvedODR;
907 DenseMap<GlobalValue::GUID, const GlobalValueSummary *> PrevailingCopy;
908 for (auto &I : Ret->Index) {
909 if (I.second.SummaryList.size() > 1)
910 PrevailingCopy[I.first] = getFirstDefinitionForLinker(I.second.SummaryList);
912 auto isPrevailing = [&](GlobalValue::GUID GUID, const GlobalValueSummary *S) {
913 const auto &Prevailing = PrevailingCopy.find(GUID);
914 if (Prevailing == PrevailingCopy.end())
916 return Prevailing->second == S;
918 auto recordNewLinkage = [&](StringRef ModuleIdentifier,
919 GlobalValue::GUID GUID,
920 GlobalValue::LinkageTypes NewLinkage) {
921 ResolvedODR[ModuleIdentifier][GUID] = NewLinkage;
923 #if LLVM_VERSION_GE(9, 0)
924 thinLTOResolvePrevailingInIndex(Ret->Index, isPrevailing, recordNewLinkage,
925 Ret->GUIDPreservedSymbols);
926 #elif LLVM_VERSION_GE(8, 0)
927 thinLTOResolvePrevailingInIndex(Ret->Index, isPrevailing, recordNewLinkage);
929 thinLTOResolveWeakForLinkerInIndex(Ret->Index, isPrevailing, recordNewLinkage);
932 // Here we calculate an `ExportedGUIDs` set for use in the `isExported`
933 // callback below. This callback below will dictate the linkage for all
934 // summaries in the index, and we basically just only want to ensure that dead
935 // symbols are internalized. Otherwise everything that's already external
936 // linkage will stay as external, and internal will stay as internal.
937 std::set<GlobalValue::GUID> ExportedGUIDs;
938 for (auto &List : Ret->Index) {
939 for (auto &GVS: List.second.SummaryList) {
940 if (GlobalValue::isLocalLinkage(GVS->linkage()))
942 auto GUID = GVS->getOriginalName();
943 if (GVS->flags().Live)
944 ExportedGUIDs.insert(GUID);
947 auto isExported = [&](StringRef ModuleIdentifier, GlobalValue::GUID GUID) {
948 const auto &ExportList = Ret->ExportLists.find(ModuleIdentifier);
949 return (ExportList != Ret->ExportLists.end() &&
950 ExportList->second.count(GUID)) ||
951 ExportedGUIDs.count(GUID);
953 thinLTOInternalizeAndPromoteInIndex(Ret->Index, isExported);
955 return Ret.release();
959 LLVMRustFreeThinLTOData(LLVMRustThinLTOData *Data) {
963 // Below are the various passes that happen *per module* when doing ThinLTO.
965 // In other words, these are the functions that are all run concurrently
966 // with one another, one per module. The passes here correspond to the analysis
967 // passes in `lib/LTO/ThinLTOCodeGenerator.cpp`, currently found in the
968 // `ProcessThinLTOModule` function. Here they're split up into separate steps
969 // so rustc can save off the intermediate bytecode between each step.
972 LLVMRustPrepareThinLTORename(const LLVMRustThinLTOData *Data, LLVMModuleRef M) {
973 Module &Mod = *unwrap(M);
974 if (renameModuleForThinLTO(Mod, Data->Index)) {
975 LLVMRustSetLastError("renameModuleForThinLTO failed");
982 LLVMRustPrepareThinLTOResolveWeak(const LLVMRustThinLTOData *Data, LLVMModuleRef M) {
983 Module &Mod = *unwrap(M);
984 const auto &DefinedGlobals = Data->ModuleToDefinedGVSummaries.lookup(Mod.getModuleIdentifier());
985 #if LLVM_VERSION_GE(8, 0)
986 thinLTOResolvePrevailingInModule(Mod, DefinedGlobals);
988 thinLTOResolveWeakForLinkerModule(Mod, DefinedGlobals);
994 LLVMRustPrepareThinLTOInternalize(const LLVMRustThinLTOData *Data, LLVMModuleRef M) {
995 Module &Mod = *unwrap(M);
996 const auto &DefinedGlobals = Data->ModuleToDefinedGVSummaries.lookup(Mod.getModuleIdentifier());
997 thinLTOInternalizeModule(Mod, DefinedGlobals);
1002 LLVMRustPrepareThinLTOImport(const LLVMRustThinLTOData *Data, LLVMModuleRef M) {
1003 Module &Mod = *unwrap(M);
1005 const auto &ImportList = Data->ImportLists.lookup(Mod.getModuleIdentifier());
1006 auto Loader = [&](StringRef Identifier) {
1007 const auto &Memory = Data->ModuleMap.lookup(Identifier);
1008 auto &Context = Mod.getContext();
1009 auto MOrErr = getLazyBitcodeModule(Memory, Context, true, true);
1014 // The rest of this closure is a workaround for
1015 // https://bugs.llvm.org/show_bug.cgi?id=38184 where during ThinLTO imports
1016 // we accidentally import wasm custom sections into different modules,
1017 // duplicating them by in the final output artifact.
1019 // The issue is worked around here by manually removing the
1020 // `wasm.custom_sections` named metadata node from any imported module. This
1021 // we know isn't used by any optimization pass so there's no need for it to
1024 // Note that the metadata is currently lazily loaded, so we materialize it
1025 // here before looking up if there's metadata inside. The `FunctionImporter`
1026 // will immediately materialize metadata anyway after an import, so this
1027 // shouldn't be a perf hit.
1028 if (Error Err = (*MOrErr)->materializeMetadata()) {
1029 Expected<std::unique_ptr<Module>> Ret(std::move(Err));
1033 auto *WasmCustomSections = (*MOrErr)->getNamedMetadata("wasm.custom_sections");
1034 if (WasmCustomSections)
1035 WasmCustomSections->eraseFromParent();
1039 FunctionImporter Importer(Data->Index, Loader);
1040 Expected<bool> Result = Importer.importFunctions(Mod, ImportList);
1042 LLVMRustSetLastError(toString(Result.takeError()).c_str());
1048 extern "C" typedef void (*LLVMRustModuleNameCallback)(void*, // payload
1049 const char*, // importing module name
1050 const char*); // imported module name
1052 // Calls `module_name_callback` for each module import done by ThinLTO.
1053 // The callback is provided with regular null-terminated C strings.
1055 LLVMRustGetThinLTOModuleImports(const LLVMRustThinLTOData *data,
1056 LLVMRustModuleNameCallback module_name_callback,
1057 void* callback_payload) {
1058 for (const auto& importing_module : data->ImportLists) {
1059 const std::string importing_module_id = importing_module.getKey().str();
1060 const auto& imports = importing_module.getValue();
1061 for (const auto& imported_module : imports) {
1062 const std::string imported_module_id = imported_module.getKey().str();
1063 module_name_callback(callback_payload,
1064 importing_module_id.c_str(),
1065 imported_module_id.c_str());
1070 // This struct and various functions are sort of a hack right now, but the
1071 // problem is that we've got in-memory LLVM modules after we generate and
1072 // optimize all codegen-units for one compilation in rustc. To be compatible
1073 // with the LTO support above we need to serialize the modules plus their
1074 // ThinLTO summary into memory.
1076 // This structure is basically an owned version of a serialize module, with
1077 // a ThinLTO summary attached.
1078 struct LLVMRustThinLTOBuffer {
1082 extern "C" LLVMRustThinLTOBuffer*
1083 LLVMRustThinLTOBufferCreate(LLVMModuleRef M) {
1084 auto Ret = llvm::make_unique<LLVMRustThinLTOBuffer>();
1086 raw_string_ostream OS(Ret->data);
1088 legacy::PassManager PM;
1089 PM.add(createWriteThinLTOBitcodePass(OS));
1093 return Ret.release();
1097 LLVMRustThinLTOBufferFree(LLVMRustThinLTOBuffer *Buffer) {
1101 extern "C" const void*
1102 LLVMRustThinLTOBufferPtr(const LLVMRustThinLTOBuffer *Buffer) {
1103 return Buffer->data.data();
1107 LLVMRustThinLTOBufferLen(const LLVMRustThinLTOBuffer *Buffer) {
1108 return Buffer->data.length();
1111 // This is what we used to parse upstream bitcode for actual ThinLTO
1112 // processing. We'll call this once per module optimized through ThinLTO, and
1113 // it'll be called concurrently on many threads.
1114 extern "C" LLVMModuleRef
1115 LLVMRustParseBitcodeForLTO(LLVMContextRef Context,
1118 const char *identifier) {
1119 StringRef Data(data, len);
1120 MemoryBufferRef Buffer(Data, identifier);
1121 unwrap(Context)->enableDebugTypeODRUniquing();
1122 Expected<std::unique_ptr<Module>> SrcOrError =
1123 parseBitcodeFile(Buffer, *unwrap(Context));
1125 LLVMRustSetLastError(toString(SrcOrError.takeError()).c_str());
1128 return wrap(std::move(*SrcOrError).release());
1131 // Rewrite all `DICompileUnit` pointers to the `DICompileUnit` specified. See
1132 // the comment in `back/lto.rs` for why this exists.
1134 LLVMRustThinLTOGetDICompileUnit(LLVMModuleRef Mod,
1136 DICompileUnit **B) {
1137 Module *M = unwrap(Mod);
1138 DICompileUnit **Cur = A;
1139 DICompileUnit **Next = B;
1140 for (DICompileUnit *CU : M->debug_compile_units()) {
1149 // Rewrite all `DICompileUnit` pointers to the `DICompileUnit` specified. See
1150 // the comment in `back/lto.rs` for why this exists.
1152 LLVMRustThinLTOPatchDICompileUnit(LLVMModuleRef Mod, DICompileUnit *Unit) {
1153 Module *M = unwrap(Mod);
1155 // If the original source module didn't have a `DICompileUnit` then try to
1156 // merge all the existing compile units. If there aren't actually any though
1157 // then there's not much for us to do so return.
1158 if (Unit == nullptr) {
1159 for (DICompileUnit *CU : M->debug_compile_units()) {
1163 if (Unit == nullptr)
1167 // Use LLVM's built-in `DebugInfoFinder` to find a bunch of debuginfo and
1168 // process it recursively. Note that we specifically iterate over instructions
1169 // to ensure we feed everything into it.
1170 DebugInfoFinder Finder;
1171 Finder.processModule(*M);
1172 for (Function &F : M->functions()) {
1173 for (auto &FI : F) {
1174 for (Instruction &BI : FI) {
1175 if (auto Loc = BI.getDebugLoc())
1176 Finder.processLocation(*M, Loc);
1177 if (auto DVI = dyn_cast<DbgValueInst>(&BI))
1178 Finder.processValue(*M, DVI);
1179 if (auto DDI = dyn_cast<DbgDeclareInst>(&BI))
1180 Finder.processDeclare(*M, DDI);
1185 // After we've found all our debuginfo, rewrite all subprograms to point to
1186 // the same `DICompileUnit`.
1187 for (auto &F : Finder.subprograms()) {
1188 F->replaceUnit(Unit);
1191 // Erase any other references to other `DICompileUnit` instances, the verifier
1192 // will later ensure that we don't actually have any other stale references to
1194 auto *MD = M->getNamedMetadata("llvm.dbg.cu");
1195 MD->clearOperands();
1196 MD->addOperand(Unit);