1 //===-LTOCodeGenerator.cpp - LLVM Link Time Optimizer ---------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the Link Time Optimization library. This library is
11 // intended to be used by linker to optimize code at link time.
13 //===----------------------------------------------------------------------===//
15 #include "llvm/LTO/LTOCodeGenerator.h"
16 #include "llvm/ADT/StringExtras.h"
17 #include "llvm/Analysis/Passes.h"
18 #include "llvm/Analysis/TargetLibraryInfo.h"
19 #include "llvm/Analysis/TargetTransformInfo.h"
20 #include "llvm/Bitcode/ReaderWriter.h"
21 #include "llvm/CodeGen/RuntimeLibcalls.h"
22 #include "llvm/Config/config.h"
23 #include "llvm/IR/Constants.h"
24 #include "llvm/IR/DataLayout.h"
25 #include "llvm/IR/DerivedTypes.h"
26 #include "llvm/IR/DiagnosticInfo.h"
27 #include "llvm/IR/DiagnosticPrinter.h"
28 #include "llvm/IR/LLVMContext.h"
29 #include "llvm/IR/LegacyPassManager.h"
30 #include "llvm/IR/Mangler.h"
31 #include "llvm/IR/Module.h"
32 #include "llvm/IR/Verifier.h"
33 #include "llvm/InitializePasses.h"
34 #include "llvm/LTO/LTOModule.h"
35 #include "llvm/Linker/Linker.h"
36 #include "llvm/MC/MCAsmInfo.h"
37 #include "llvm/MC/MCContext.h"
38 #include "llvm/MC/SubtargetFeature.h"
39 #include "llvm/Support/CommandLine.h"
40 #include "llvm/Support/FileSystem.h"
41 #include "llvm/Support/Host.h"
42 #include "llvm/Support/MemoryBuffer.h"
43 #include "llvm/Support/Signals.h"
44 #include "llvm/Support/TargetRegistry.h"
45 #include "llvm/Support/TargetSelect.h"
46 #include "llvm/Support/ToolOutputFile.h"
47 #include "llvm/Support/raw_ostream.h"
48 #include "llvm/Target/TargetLowering.h"
49 #include "llvm/Target/TargetOptions.h"
50 #include "llvm/Target/TargetRegisterInfo.h"
51 #include "llvm/Target/TargetSubtargetInfo.h"
52 #include "llvm/Transforms/IPO.h"
53 #include "llvm/Transforms/IPO/PassManagerBuilder.h"
54 #include "llvm/Transforms/ObjCARC.h"
55 #include <system_error>
58 const char* LTOCodeGenerator::getVersionString() {
59 #ifdef LLVM_VERSION_INFO
60 return PACKAGE_NAME " version " PACKAGE_VERSION ", " LLVM_VERSION_INFO;
62 return PACKAGE_NAME " version " PACKAGE_VERSION;
66 LTOCodeGenerator::LTOCodeGenerator()
67 : Context(getGlobalContext()), IRLinker(new Module("ld-temp.o", Context)) {
68 initializeLTOPasses();
71 LTOCodeGenerator::LTOCodeGenerator(std::unique_ptr<LLVMContext> Context)
72 : OwnedContext(std::move(Context)), Context(*OwnedContext),
73 IRLinker(new Module("ld-temp.o", *OwnedContext)) {
74 initializeLTOPasses();
77 void LTOCodeGenerator::destroyMergedModule() {
79 assert(IRLinker.getModule() == &OwnedModule->getModule() &&
80 "The linker's module should be the same as the owned module");
82 OwnedModule = nullptr;
83 } else if (IRLinker.getModule())
84 IRLinker.deleteModule();
87 LTOCodeGenerator::~LTOCodeGenerator() {
88 destroyMergedModule();
94 // Initialize LTO passes. Please keep this funciton in sync with
95 // PassManagerBuilder::populateLTOPassManager(), and make sure all LTO
96 // passes are initialized.
97 void LTOCodeGenerator::initializeLTOPasses() {
98 PassRegistry &R = *PassRegistry::getPassRegistry();
100 initializeInternalizePassPass(R);
101 initializeIPSCCPPass(R);
102 initializeGlobalOptPass(R);
103 initializeConstantMergePass(R);
104 initializeDAHPass(R);
105 initializeInstructionCombiningPassPass(R);
106 initializeSimpleInlinerPass(R);
107 initializePruneEHPass(R);
108 initializeGlobalDCEPass(R);
109 initializeArgPromotionPass(R);
110 initializeJumpThreadingPass(R);
111 initializeSROAPass(R);
112 initializeSROA_DTPass(R);
113 initializeSROA_SSAUpPass(R);
114 initializeFunctionAttrsPass(R);
115 initializeGlobalsModRefPass(R);
116 initializeLICMPass(R);
117 initializeMergedLoadStoreMotionPass(R);
118 initializeGVNPass(R);
119 initializeMemCpyOptPass(R);
120 initializeDCEPass(R);
121 initializeCFGSimplifyPassPass(R);
124 bool LTOCodeGenerator::addModule(LTOModule *mod) {
125 assert(&mod->getModule().getContext() == &Context &&
126 "Expected module in same context");
128 bool ret = IRLinker.linkInModule(&mod->getModule());
130 const std::vector<const char*> &undefs = mod->getAsmUndefinedRefs();
131 for (int i = 0, e = undefs.size(); i != e; ++i)
132 AsmUndefinedRefs[undefs[i]] = 1;
137 void LTOCodeGenerator::setModule(LTOModule *Mod) {
138 assert(&Mod->getModule().getContext() == &Context &&
139 "Expected module in same context");
141 // Delete the old merged module.
142 destroyMergedModule();
143 AsmUndefinedRefs.clear();
146 IRLinker.setModule(&Mod->getModule());
148 const std::vector<const char*> &Undefs = Mod->getAsmUndefinedRefs();
149 for (int I = 0, E = Undefs.size(); I != E; ++I)
150 AsmUndefinedRefs[Undefs[I]] = 1;
153 void LTOCodeGenerator::setTargetOptions(TargetOptions options) {
157 void LTOCodeGenerator::setDebugInfo(lto_debug_model debug) {
159 case LTO_DEBUG_MODEL_NONE:
160 EmitDwarfDebugInfo = false;
163 case LTO_DEBUG_MODEL_DWARF:
164 EmitDwarfDebugInfo = true;
167 llvm_unreachable("Unknown debug format!");
170 void LTOCodeGenerator::setCodePICModel(lto_codegen_model model) {
172 case LTO_CODEGEN_PIC_MODEL_STATIC:
173 case LTO_CODEGEN_PIC_MODEL_DYNAMIC:
174 case LTO_CODEGEN_PIC_MODEL_DYNAMIC_NO_PIC:
175 case LTO_CODEGEN_PIC_MODEL_DEFAULT:
179 llvm_unreachable("Unknown PIC model!");
182 bool LTOCodeGenerator::writeMergedModules(const char *path,
183 std::string &errMsg) {
184 if (!determineTarget(errMsg))
187 // mark which symbols can not be internalized
188 applyScopeRestrictions();
190 // create output file
192 tool_output_file Out(path, EC, sys::fs::F_None);
194 errMsg = "could not open bitcode file for writing: ";
199 // write bitcode to it
200 WriteBitcodeToFile(IRLinker.getModule(), Out.os(), ShouldEmbedUselists);
203 if (Out.os().has_error()) {
204 errMsg = "could not write bitcode file: ";
206 Out.os().clear_error();
214 bool LTOCodeGenerator::compileOptimizedToFile(const char **name,
215 std::string &errMsg) {
216 // make unique temp .o file to put generated object file
217 SmallString<128> Filename;
220 sys::fs::createTemporaryFile("lto-llvm", "o", FD, Filename);
222 errMsg = EC.message();
226 // generate object file
227 tool_output_file objFile(Filename.c_str(), FD);
229 bool genResult = compileOptimized(objFile.os(), errMsg);
230 objFile.os().close();
231 if (objFile.os().has_error()) {
232 objFile.os().clear_error();
233 sys::fs::remove(Twine(Filename));
239 sys::fs::remove(Twine(Filename));
243 NativeObjectPath = Filename.c_str();
244 *name = NativeObjectPath.c_str();
248 std::unique_ptr<MemoryBuffer>
249 LTOCodeGenerator::compileOptimized(std::string &errMsg) {
251 if (!compileOptimizedToFile(&name, errMsg))
254 // read .o file into memory buffer
255 ErrorOr<std::unique_ptr<MemoryBuffer>> BufferOrErr =
256 MemoryBuffer::getFile(name, -1, false);
257 if (std::error_code EC = BufferOrErr.getError()) {
258 errMsg = EC.message();
259 sys::fs::remove(NativeObjectPath);
264 sys::fs::remove(NativeObjectPath);
266 return std::move(*BufferOrErr);
270 bool LTOCodeGenerator::compile_to_file(const char **name,
272 bool disableGVNLoadPRE,
273 bool disableVectorization,
274 std::string &errMsg) {
275 if (!optimize(disableInline, disableGVNLoadPRE,
276 disableVectorization, errMsg))
279 return compileOptimizedToFile(name, errMsg);
282 std::unique_ptr<MemoryBuffer>
283 LTOCodeGenerator::compile(bool disableInline, bool disableGVNLoadPRE,
284 bool disableVectorization, std::string &errMsg) {
285 if (!optimize(disableInline, disableGVNLoadPRE,
286 disableVectorization, errMsg))
289 return compileOptimized(errMsg);
292 bool LTOCodeGenerator::determineTarget(std::string &errMsg) {
296 std::string TripleStr = IRLinker.getModule()->getTargetTriple();
297 if (TripleStr.empty())
298 TripleStr = sys::getDefaultTargetTriple();
299 llvm::Triple Triple(TripleStr);
301 // create target machine from info for merged modules
302 const Target *march = TargetRegistry::lookupTarget(TripleStr, errMsg);
306 // The relocation model is actually a static member of TargetMachine and
307 // needs to be set before the TargetMachine is instantiated.
308 Reloc::Model RelocModel = Reloc::Default;
310 case LTO_CODEGEN_PIC_MODEL_STATIC:
311 RelocModel = Reloc::Static;
313 case LTO_CODEGEN_PIC_MODEL_DYNAMIC:
314 RelocModel = Reloc::PIC_;
316 case LTO_CODEGEN_PIC_MODEL_DYNAMIC_NO_PIC:
317 RelocModel = Reloc::DynamicNoPIC;
319 case LTO_CODEGEN_PIC_MODEL_DEFAULT:
320 // RelocModel is already the default, so leave it that way.
324 // Construct LTOModule, hand over ownership of module and target. Use MAttr as
325 // the default set of features.
326 SubtargetFeatures Features(MAttr);
327 Features.getDefaultSubtargetFeatures(Triple);
328 std::string FeatureStr = Features.getString();
329 // Set a default CPU for Darwin triples.
330 if (MCpu.empty() && Triple.isOSDarwin()) {
331 if (Triple.getArch() == llvm::Triple::x86_64)
333 else if (Triple.getArch() == llvm::Triple::x86)
335 else if (Triple.getArch() == llvm::Triple::aarch64)
339 CodeGenOpt::Level CGOptLevel;
342 CGOptLevel = CodeGenOpt::None;
345 CGOptLevel = CodeGenOpt::Less;
348 CGOptLevel = CodeGenOpt::Default;
351 CGOptLevel = CodeGenOpt::Aggressive;
355 TargetMach = march->createTargetMachine(TripleStr, MCpu, FeatureStr, Options,
356 RelocModel, CodeModel::Default,
361 void LTOCodeGenerator::
362 applyRestriction(GlobalValue &GV,
363 ArrayRef<StringRef> Libcalls,
364 std::vector<const char*> &MustPreserveList,
365 SmallPtrSetImpl<GlobalValue*> &AsmUsed,
367 // There are no restrictions to apply to declarations.
368 if (GV.isDeclaration())
371 // There is nothing more restrictive than private linkage.
372 if (GV.hasPrivateLinkage())
375 SmallString<64> Buffer;
376 TargetMach->getNameWithPrefix(Buffer, &GV, Mangler);
378 if (MustPreserveSymbols.count(Buffer))
379 MustPreserveList.push_back(GV.getName().data());
380 if (AsmUndefinedRefs.count(Buffer))
383 // Conservatively append user-supplied runtime library functions to
384 // llvm.compiler.used. These could be internalized and deleted by
385 // optimizations like -globalopt, causing problems when later optimizations
386 // add new library calls (e.g., llvm.memset => memset and printf => puts).
387 // Leave it to the linker to remove any dead code (e.g. with -dead_strip).
388 if (isa<Function>(GV) &&
389 std::binary_search(Libcalls.begin(), Libcalls.end(), GV.getName()))
393 static void findUsedValues(GlobalVariable *LLVMUsed,
394 SmallPtrSetImpl<GlobalValue*> &UsedValues) {
395 if (!LLVMUsed) return;
397 ConstantArray *Inits = cast<ConstantArray>(LLVMUsed->getInitializer());
398 for (unsigned i = 0, e = Inits->getNumOperands(); i != e; ++i)
399 if (GlobalValue *GV =
400 dyn_cast<GlobalValue>(Inits->getOperand(i)->stripPointerCasts()))
401 UsedValues.insert(GV);
404 // Collect names of runtime library functions. User-defined functions with the
405 // same names are added to llvm.compiler.used to prevent them from being
406 // deleted by optimizations.
407 static void accumulateAndSortLibcalls(std::vector<StringRef> &Libcalls,
408 const TargetLibraryInfo& TLI,
410 const TargetMachine &TM) {
411 // TargetLibraryInfo has info on C runtime library calls on the current
413 for (unsigned I = 0, E = static_cast<unsigned>(LibFunc::NumLibFuncs);
415 LibFunc::Func F = static_cast<LibFunc::Func>(I);
417 Libcalls.push_back(TLI.getName(F));
420 SmallPtrSet<const TargetLowering *, 1> TLSet;
422 for (const Function &F : Mod) {
423 const TargetLowering *Lowering =
424 TM.getSubtargetImpl(F)->getTargetLowering();
426 if (Lowering && TLSet.insert(Lowering).second)
427 // TargetLowering has info on library calls that CodeGen expects to be
428 // available, both from the C runtime and compiler-rt.
429 for (unsigned I = 0, E = static_cast<unsigned>(RTLIB::UNKNOWN_LIBCALL);
431 if (const char *Name =
432 Lowering->getLibcallName(static_cast<RTLIB::Libcall>(I)))
433 Libcalls.push_back(Name);
436 array_pod_sort(Libcalls.begin(), Libcalls.end());
437 Libcalls.erase(std::unique(Libcalls.begin(), Libcalls.end()),
441 void LTOCodeGenerator::applyScopeRestrictions() {
442 if (ScopeRestrictionsDone || !ShouldInternalize)
444 Module *mergedModule = IRLinker.getModule();
446 // Start off with a verification pass.
447 legacy::PassManager passes;
448 passes.add(createVerifierPass());
450 // mark which symbols can not be internalized
452 std::vector<const char*> MustPreserveList;
453 SmallPtrSet<GlobalValue*, 8> AsmUsed;
454 std::vector<StringRef> Libcalls;
455 TargetLibraryInfoImpl TLII(Triple(TargetMach->getTargetTriple()));
456 TargetLibraryInfo TLI(TLII);
458 accumulateAndSortLibcalls(Libcalls, TLI, *mergedModule, *TargetMach);
460 for (Module::iterator f = mergedModule->begin(),
461 e = mergedModule->end(); f != e; ++f)
462 applyRestriction(*f, Libcalls, MustPreserveList, AsmUsed, Mangler);
463 for (Module::global_iterator v = mergedModule->global_begin(),
464 e = mergedModule->global_end(); v != e; ++v)
465 applyRestriction(*v, Libcalls, MustPreserveList, AsmUsed, Mangler);
466 for (Module::alias_iterator a = mergedModule->alias_begin(),
467 e = mergedModule->alias_end(); a != e; ++a)
468 applyRestriction(*a, Libcalls, MustPreserveList, AsmUsed, Mangler);
470 GlobalVariable *LLVMCompilerUsed =
471 mergedModule->getGlobalVariable("llvm.compiler.used");
472 findUsedValues(LLVMCompilerUsed, AsmUsed);
473 if (LLVMCompilerUsed)
474 LLVMCompilerUsed->eraseFromParent();
476 if (!AsmUsed.empty()) {
477 llvm::Type *i8PTy = llvm::Type::getInt8PtrTy(Context);
478 std::vector<Constant*> asmUsed2;
479 for (auto *GV : AsmUsed) {
480 Constant *c = ConstantExpr::getBitCast(GV, i8PTy);
481 asmUsed2.push_back(c);
484 llvm::ArrayType *ATy = llvm::ArrayType::get(i8PTy, asmUsed2.size());
486 new llvm::GlobalVariable(*mergedModule, ATy, false,
487 llvm::GlobalValue::AppendingLinkage,
488 llvm::ConstantArray::get(ATy, asmUsed2),
489 "llvm.compiler.used");
491 LLVMCompilerUsed->setSection("llvm.metadata");
494 passes.add(createInternalizePass(MustPreserveList));
496 // apply scope restrictions
497 passes.run(*mergedModule);
499 ScopeRestrictionsDone = true;
502 /// Optimize merged modules using various IPO passes
503 bool LTOCodeGenerator::optimize(bool DisableInline,
504 bool DisableGVNLoadPRE,
505 bool DisableVectorization,
506 std::string &errMsg) {
507 if (!this->determineTarget(errMsg))
510 Module *mergedModule = IRLinker.getModule();
512 // Mark which symbols can not be internalized
513 this->applyScopeRestrictions();
515 // Instantiate the pass manager to organize the passes.
516 legacy::PassManager passes;
518 // Add an appropriate DataLayout instance for this module...
519 mergedModule->setDataLayout(TargetMach->createDataLayout());
522 createTargetTransformInfoWrapperPass(TargetMach->getTargetIRAnalysis()));
524 Triple TargetTriple(TargetMach->getTargetTriple());
525 PassManagerBuilder PMB;
526 PMB.DisableGVNLoadPRE = DisableGVNLoadPRE;
527 PMB.LoopVectorize = !DisableVectorization;
528 PMB.SLPVectorize = !DisableVectorization;
530 PMB.Inliner = createFunctionInliningPass();
531 PMB.LibraryInfo = new TargetLibraryInfoImpl(TargetTriple);
532 PMB.OptLevel = OptLevel;
533 PMB.VerifyInput = true;
534 PMB.VerifyOutput = true;
536 PMB.populateLTOPassManager(passes);
538 // Run our queue of passes all at once now, efficiently.
539 passes.run(*mergedModule);
544 bool LTOCodeGenerator::compileOptimized(raw_pwrite_stream &out,
545 std::string &errMsg) {
546 if (!this->determineTarget(errMsg))
549 Module *mergedModule = IRLinker.getModule();
551 legacy::PassManager codeGenPasses;
553 // If the bitcode files contain ARC code and were compiled with optimization,
554 // the ObjCARCContractPass must be run, so do it unconditionally here.
555 codeGenPasses.add(createObjCARCContractPass());
557 if (TargetMach->addPassesToEmitFile(codeGenPasses, out,
558 TargetMachine::CGFT_ObjectFile)) {
559 errMsg = "target file type not supported";
563 // Run the code generator, and write assembly file
564 codeGenPasses.run(*mergedModule);
569 /// setCodeGenDebugOptions - Set codegen debugging options to aid in debugging
571 void LTOCodeGenerator::setCodeGenDebugOptions(const char *options) {
572 for (std::pair<StringRef, StringRef> o = getToken(options);
573 !o.first.empty(); o = getToken(o.second))
574 CodegenOptions.push_back(o.first);
577 void LTOCodeGenerator::parseCodeGenDebugOptions() {
578 // if options were requested, set them
579 if (!CodegenOptions.empty()) {
580 // ParseCommandLineOptions() expects argv[0] to be program name.
581 std::vector<const char *> CodegenArgv(1, "libLLVMLTO");
582 for (std::string &Arg : CodegenOptions)
583 CodegenArgv.push_back(Arg.c_str());
584 cl::ParseCommandLineOptions(CodegenArgv.size(), CodegenArgv.data());
588 void LTOCodeGenerator::DiagnosticHandler(const DiagnosticInfo &DI,
590 ((LTOCodeGenerator *)Context)->DiagnosticHandler2(DI);
593 void LTOCodeGenerator::DiagnosticHandler2(const DiagnosticInfo &DI) {
594 // Map the LLVM internal diagnostic severity to the LTO diagnostic severity.
595 lto_codegen_diagnostic_severity_t Severity;
596 switch (DI.getSeverity()) {
598 Severity = LTO_DS_ERROR;
601 Severity = LTO_DS_WARNING;
604 Severity = LTO_DS_REMARK;
607 Severity = LTO_DS_NOTE;
610 // Create the string that will be reported to the external diagnostic handler.
611 std::string MsgStorage;
612 raw_string_ostream Stream(MsgStorage);
613 DiagnosticPrinterRawOStream DP(Stream);
617 // If this method has been called it means someone has set up an external
618 // diagnostic handler. Assert on that.
619 assert(DiagHandler && "Invalid diagnostic handler");
620 (*DiagHandler)(Severity, MsgStorage.c_str(), DiagContext);
624 LTOCodeGenerator::setDiagnosticHandler(lto_diagnostic_handler_t DiagHandler,
626 this->DiagHandler = DiagHandler;
627 this->DiagContext = Ctxt;
629 return Context.setDiagnosticHandler(nullptr, nullptr);
630 // Register the LTOCodeGenerator stub in the LLVMContext to forward the
631 // diagnostic to the external DiagHandler.
632 Context.setDiagnosticHandler(LTOCodeGenerator::DiagnosticHandler, this,
633 /* RespectFilters */ true);