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();
91 // Initialize LTO passes. Please keep this funciton in sync with
92 // PassManagerBuilder::populateLTOPassManager(), and make sure all LTO
93 // passes are initialized.
94 void LTOCodeGenerator::initializeLTOPasses() {
95 PassRegistry &R = *PassRegistry::getPassRegistry();
97 initializeInternalizePassPass(R);
98 initializeIPSCCPPass(R);
99 initializeGlobalOptPass(R);
100 initializeConstantMergePass(R);
101 initializeDAHPass(R);
102 initializeInstructionCombiningPassPass(R);
103 initializeSimpleInlinerPass(R);
104 initializePruneEHPass(R);
105 initializeGlobalDCEPass(R);
106 initializeArgPromotionPass(R);
107 initializeJumpThreadingPass(R);
108 initializeSROAPass(R);
109 initializeSROA_DTPass(R);
110 initializeSROA_SSAUpPass(R);
111 initializeFunctionAttrsPass(R);
112 initializeGlobalsModRefPass(R);
113 initializeLICMPass(R);
114 initializeMergedLoadStoreMotionPass(R);
115 initializeGVNPass(R);
116 initializeMemCpyOptPass(R);
117 initializeDCEPass(R);
118 initializeCFGSimplifyPassPass(R);
121 bool LTOCodeGenerator::addModule(LTOModule *mod) {
122 assert(&mod->getModule().getContext() == &Context &&
123 "Expected module in same context");
125 bool ret = IRLinker.linkInModule(&mod->getModule());
127 const std::vector<const char*> &undefs = mod->getAsmUndefinedRefs();
128 for (int i = 0, e = undefs.size(); i != e; ++i)
129 AsmUndefinedRefs[undefs[i]] = 1;
134 void LTOCodeGenerator::setModule(LTOModule *Mod) {
135 assert(&Mod->getModule().getContext() == &Context &&
136 "Expected module in same context");
138 // Delete the old merged module.
139 destroyMergedModule();
140 AsmUndefinedRefs.clear();
143 IRLinker.setModule(&Mod->getModule());
145 const std::vector<const char*> &Undefs = Mod->getAsmUndefinedRefs();
146 for (int I = 0, E = Undefs.size(); I != E; ++I)
147 AsmUndefinedRefs[Undefs[I]] = 1;
150 void LTOCodeGenerator::setTargetOptions(TargetOptions options) {
154 void LTOCodeGenerator::setDebugInfo(lto_debug_model debug) {
156 case LTO_DEBUG_MODEL_NONE:
157 EmitDwarfDebugInfo = false;
160 case LTO_DEBUG_MODEL_DWARF:
161 EmitDwarfDebugInfo = true;
164 llvm_unreachable("Unknown debug format!");
167 void LTOCodeGenerator::setOptLevel(unsigned level) {
171 CGOptLevel = CodeGenOpt::None;
174 CGOptLevel = CodeGenOpt::Less;
177 CGOptLevel = CodeGenOpt::Default;
180 CGOptLevel = CodeGenOpt::Aggressive;
185 bool LTOCodeGenerator::writeMergedModules(const char *path,
186 std::string &errMsg) {
187 if (!determineTarget(errMsg))
190 // mark which symbols can not be internalized
191 applyScopeRestrictions();
193 // create output file
195 tool_output_file Out(path, EC, sys::fs::F_None);
197 errMsg = "could not open bitcode file for writing: ";
202 // write bitcode to it
203 WriteBitcodeToFile(IRLinker.getModule(), Out.os(), ShouldEmbedUselists);
206 if (Out.os().has_error()) {
207 errMsg = "could not write bitcode file: ";
209 Out.os().clear_error();
217 bool LTOCodeGenerator::compileOptimizedToFile(const char **name,
218 std::string &errMsg) {
219 // make unique temp .o file to put generated object file
220 SmallString<128> Filename;
223 sys::fs::createTemporaryFile("lto-llvm", "o", FD, Filename);
225 errMsg = EC.message();
229 // generate object file
230 tool_output_file objFile(Filename.c_str(), FD);
232 bool genResult = compileOptimized(objFile.os(), errMsg);
233 objFile.os().close();
234 if (objFile.os().has_error()) {
235 objFile.os().clear_error();
236 sys::fs::remove(Twine(Filename));
242 sys::fs::remove(Twine(Filename));
246 NativeObjectPath = Filename.c_str();
247 *name = NativeObjectPath.c_str();
251 std::unique_ptr<MemoryBuffer>
252 LTOCodeGenerator::compileOptimized(std::string &errMsg) {
254 if (!compileOptimizedToFile(&name, errMsg))
257 // read .o file into memory buffer
258 ErrorOr<std::unique_ptr<MemoryBuffer>> BufferOrErr =
259 MemoryBuffer::getFile(name, -1, false);
260 if (std::error_code EC = BufferOrErr.getError()) {
261 errMsg = EC.message();
262 sys::fs::remove(NativeObjectPath);
267 sys::fs::remove(NativeObjectPath);
269 return std::move(*BufferOrErr);
273 bool LTOCodeGenerator::compile_to_file(const char **name,
275 bool disableGVNLoadPRE,
276 bool disableVectorization,
277 std::string &errMsg) {
278 if (!optimize(disableInline, disableGVNLoadPRE,
279 disableVectorization, errMsg))
282 return compileOptimizedToFile(name, errMsg);
285 std::unique_ptr<MemoryBuffer>
286 LTOCodeGenerator::compile(bool disableInline, bool disableGVNLoadPRE,
287 bool disableVectorization, std::string &errMsg) {
288 if (!optimize(disableInline, disableGVNLoadPRE,
289 disableVectorization, errMsg))
292 return compileOptimized(errMsg);
295 bool LTOCodeGenerator::determineTarget(std::string &errMsg) {
299 std::string TripleStr = IRLinker.getModule()->getTargetTriple();
300 if (TripleStr.empty()) {
301 TripleStr = sys::getDefaultTargetTriple();
302 IRLinker.getModule()->setTargetTriple(TripleStr);
304 llvm::Triple Triple(TripleStr);
306 // create target machine from info for merged modules
307 const Target *march = TargetRegistry::lookupTarget(TripleStr, errMsg);
311 // Construct LTOModule, hand over ownership of module and target. Use MAttr as
312 // the default set of features.
313 SubtargetFeatures Features(MAttr);
314 Features.getDefaultSubtargetFeatures(Triple);
315 FeatureStr = Features.getString();
316 // Set a default CPU for Darwin triples.
317 if (MCpu.empty() && Triple.isOSDarwin()) {
318 if (Triple.getArch() == llvm::Triple::x86_64)
320 else if (Triple.getArch() == llvm::Triple::x86)
322 else if (Triple.getArch() == llvm::Triple::aarch64)
326 TargetMach.reset(march->createTargetMachine(TripleStr, MCpu, FeatureStr,
328 CodeModel::Default, CGOptLevel));
332 void LTOCodeGenerator::
333 applyRestriction(GlobalValue &GV,
334 ArrayRef<StringRef> Libcalls,
335 std::vector<const char*> &MustPreserveList,
336 SmallPtrSetImpl<GlobalValue*> &AsmUsed,
338 // There are no restrictions to apply to declarations.
339 if (GV.isDeclaration())
342 // There is nothing more restrictive than private linkage.
343 if (GV.hasPrivateLinkage())
346 SmallString<64> Buffer;
347 TargetMach->getNameWithPrefix(Buffer, &GV, Mangler);
349 if (MustPreserveSymbols.count(Buffer))
350 MustPreserveList.push_back(GV.getName().data());
351 if (AsmUndefinedRefs.count(Buffer))
354 // Conservatively append user-supplied runtime library functions to
355 // llvm.compiler.used. These could be internalized and deleted by
356 // optimizations like -globalopt, causing problems when later optimizations
357 // add new library calls (e.g., llvm.memset => memset and printf => puts).
358 // Leave it to the linker to remove any dead code (e.g. with -dead_strip).
359 if (isa<Function>(GV) &&
360 std::binary_search(Libcalls.begin(), Libcalls.end(), GV.getName()))
364 static void findUsedValues(GlobalVariable *LLVMUsed,
365 SmallPtrSetImpl<GlobalValue*> &UsedValues) {
366 if (!LLVMUsed) return;
368 ConstantArray *Inits = cast<ConstantArray>(LLVMUsed->getInitializer());
369 for (unsigned i = 0, e = Inits->getNumOperands(); i != e; ++i)
370 if (GlobalValue *GV =
371 dyn_cast<GlobalValue>(Inits->getOperand(i)->stripPointerCasts()))
372 UsedValues.insert(GV);
375 // Collect names of runtime library functions. User-defined functions with the
376 // same names are added to llvm.compiler.used to prevent them from being
377 // deleted by optimizations.
378 static void accumulateAndSortLibcalls(std::vector<StringRef> &Libcalls,
379 const TargetLibraryInfo& TLI,
381 const TargetMachine &TM) {
382 // TargetLibraryInfo has info on C runtime library calls on the current
384 for (unsigned I = 0, E = static_cast<unsigned>(LibFunc::NumLibFuncs);
386 LibFunc::Func F = static_cast<LibFunc::Func>(I);
388 Libcalls.push_back(TLI.getName(F));
391 SmallPtrSet<const TargetLowering *, 1> TLSet;
393 for (const Function &F : Mod) {
394 const TargetLowering *Lowering =
395 TM.getSubtargetImpl(F)->getTargetLowering();
397 if (Lowering && TLSet.insert(Lowering).second)
398 // TargetLowering has info on library calls that CodeGen expects to be
399 // available, both from the C runtime and compiler-rt.
400 for (unsigned I = 0, E = static_cast<unsigned>(RTLIB::UNKNOWN_LIBCALL);
402 if (const char *Name =
403 Lowering->getLibcallName(static_cast<RTLIB::Libcall>(I)))
404 Libcalls.push_back(Name);
407 array_pod_sort(Libcalls.begin(), Libcalls.end());
408 Libcalls.erase(std::unique(Libcalls.begin(), Libcalls.end()),
412 void LTOCodeGenerator::applyScopeRestrictions() {
413 if (ScopeRestrictionsDone || !ShouldInternalize)
415 Module *MergedModule = IRLinker.getModule();
417 // Start off with a verification pass.
418 legacy::PassManager passes;
419 passes.add(createVerifierPass());
421 // mark which symbols can not be internalized
423 std::vector<const char*> MustPreserveList;
424 SmallPtrSet<GlobalValue*, 8> AsmUsed;
425 std::vector<StringRef> Libcalls;
426 TargetLibraryInfoImpl TLII(Triple(TargetMach->getTargetTriple()));
427 TargetLibraryInfo TLI(TLII);
429 accumulateAndSortLibcalls(Libcalls, TLI, *MergedModule, *TargetMach);
431 for (Function &f : *MergedModule)
432 applyRestriction(f, Libcalls, MustPreserveList, AsmUsed, Mangler);
433 for (GlobalVariable &v : MergedModule->globals())
434 applyRestriction(v, Libcalls, MustPreserveList, AsmUsed, Mangler);
435 for (GlobalAlias &a : MergedModule->aliases())
436 applyRestriction(a, Libcalls, MustPreserveList, AsmUsed, Mangler);
438 GlobalVariable *LLVMCompilerUsed =
439 MergedModule->getGlobalVariable("llvm.compiler.used");
440 findUsedValues(LLVMCompilerUsed, AsmUsed);
441 if (LLVMCompilerUsed)
442 LLVMCompilerUsed->eraseFromParent();
444 if (!AsmUsed.empty()) {
445 llvm::Type *i8PTy = llvm::Type::getInt8PtrTy(Context);
446 std::vector<Constant*> asmUsed2;
447 for (auto *GV : AsmUsed) {
448 Constant *c = ConstantExpr::getBitCast(GV, i8PTy);
449 asmUsed2.push_back(c);
452 llvm::ArrayType *ATy = llvm::ArrayType::get(i8PTy, asmUsed2.size());
454 new llvm::GlobalVariable(*MergedModule, ATy, false,
455 llvm::GlobalValue::AppendingLinkage,
456 llvm::ConstantArray::get(ATy, asmUsed2),
457 "llvm.compiler.used");
459 LLVMCompilerUsed->setSection("llvm.metadata");
462 passes.add(createInternalizePass(MustPreserveList));
464 // apply scope restrictions
465 passes.run(*MergedModule);
467 ScopeRestrictionsDone = true;
470 /// Optimize merged modules using various IPO passes
471 bool LTOCodeGenerator::optimize(bool DisableInline,
472 bool DisableGVNLoadPRE,
473 bool DisableVectorization,
474 std::string &errMsg) {
475 if (!this->determineTarget(errMsg))
478 Module *MergedModule = IRLinker.getModule();
480 // Mark which symbols can not be internalized
481 this->applyScopeRestrictions();
483 // Instantiate the pass manager to organize the passes.
484 legacy::PassManager passes;
486 // Add an appropriate DataLayout instance for this module...
487 MergedModule->setDataLayout(TargetMach->createDataLayout());
490 createTargetTransformInfoWrapperPass(TargetMach->getTargetIRAnalysis()));
492 Triple TargetTriple(TargetMach->getTargetTriple());
493 PassManagerBuilder PMB;
494 PMB.DisableGVNLoadPRE = DisableGVNLoadPRE;
495 PMB.LoopVectorize = !DisableVectorization;
496 PMB.SLPVectorize = !DisableVectorization;
498 PMB.Inliner = createFunctionInliningPass();
499 PMB.LibraryInfo = new TargetLibraryInfoImpl(TargetTriple);
500 PMB.OptLevel = OptLevel;
501 PMB.VerifyInput = true;
502 PMB.VerifyOutput = true;
504 PMB.populateLTOPassManager(passes);
506 // Run our queue of passes all at once now, efficiently.
507 passes.run(*MergedModule);
512 bool LTOCodeGenerator::compileOptimized(raw_pwrite_stream &out,
513 std::string &errMsg) {
514 if (!this->determineTarget(errMsg))
517 Module *MergedModule = IRLinker.getModule();
519 legacy::PassManager codeGenPasses;
521 // If the bitcode files contain ARC code and were compiled with optimization,
522 // the ObjCARCContractPass must be run, so do it unconditionally here.
523 codeGenPasses.add(createObjCARCContractPass());
525 if (TargetMach->addPassesToEmitFile(codeGenPasses, out,
526 TargetMachine::CGFT_ObjectFile)) {
527 errMsg = "target file type not supported";
531 // Run the code generator, and write object file
532 codeGenPasses.run(*MergedModule);
537 /// setCodeGenDebugOptions - Set codegen debugging options to aid in debugging
539 void LTOCodeGenerator::setCodeGenDebugOptions(const char *options) {
540 for (std::pair<StringRef, StringRef> o = getToken(options);
541 !o.first.empty(); o = getToken(o.second))
542 CodegenOptions.push_back(o.first);
545 void LTOCodeGenerator::parseCodeGenDebugOptions() {
546 // if options were requested, set them
547 if (!CodegenOptions.empty()) {
548 // ParseCommandLineOptions() expects argv[0] to be program name.
549 std::vector<const char *> CodegenArgv(1, "libLLVMLTO");
550 for (std::string &Arg : CodegenOptions)
551 CodegenArgv.push_back(Arg.c_str());
552 cl::ParseCommandLineOptions(CodegenArgv.size(), CodegenArgv.data());
556 void LTOCodeGenerator::DiagnosticHandler(const DiagnosticInfo &DI,
558 ((LTOCodeGenerator *)Context)->DiagnosticHandler2(DI);
561 void LTOCodeGenerator::DiagnosticHandler2(const DiagnosticInfo &DI) {
562 // Map the LLVM internal diagnostic severity to the LTO diagnostic severity.
563 lto_codegen_diagnostic_severity_t Severity;
564 switch (DI.getSeverity()) {
566 Severity = LTO_DS_ERROR;
569 Severity = LTO_DS_WARNING;
572 Severity = LTO_DS_REMARK;
575 Severity = LTO_DS_NOTE;
578 // Create the string that will be reported to the external diagnostic handler.
579 std::string MsgStorage;
580 raw_string_ostream Stream(MsgStorage);
581 DiagnosticPrinterRawOStream DP(Stream);
585 // If this method has been called it means someone has set up an external
586 // diagnostic handler. Assert on that.
587 assert(DiagHandler && "Invalid diagnostic handler");
588 (*DiagHandler)(Severity, MsgStorage.c_str(), DiagContext);
592 LTOCodeGenerator::setDiagnosticHandler(lto_diagnostic_handler_t DiagHandler,
594 this->DiagHandler = DiagHandler;
595 this->DiagContext = Ctxt;
597 return Context.setDiagnosticHandler(nullptr, nullptr);
598 // Register the LTOCodeGenerator stub in the LLVMContext to forward the
599 // diagnostic to the external DiagHandler.
600 Context.setDiagnosticHandler(LTOCodeGenerator::DiagnosticHandler, this,
601 /* RespectFilters */ true);