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/Mangler.h"
30 #include "llvm/IR/Module.h"
31 #include "llvm/IR/Verifier.h"
32 #include "llvm/InitializePasses.h"
33 #include "llvm/LTO/LTOModule.h"
34 #include "llvm/Linker/Linker.h"
35 #include "llvm/MC/MCAsmInfo.h"
36 #include "llvm/MC/MCContext.h"
37 #include "llvm/MC/SubtargetFeature.h"
38 #include "llvm/PassManager.h"
39 #include "llvm/Support/CommandLine.h"
40 #include "llvm/Support/FileSystem.h"
41 #include "llvm/Support/FormattedStream.h"
42 #include "llvm/Support/Host.h"
43 #include "llvm/Support/MemoryBuffer.h"
44 #include "llvm/Support/Signals.h"
45 #include "llvm/Support/TargetRegistry.h"
46 #include "llvm/Support/TargetSelect.h"
47 #include "llvm/Support/ToolOutputFile.h"
48 #include "llvm/Support/raw_ostream.h"
49 #include "llvm/Target/TargetLowering.h"
50 #include "llvm/Target/TargetOptions.h"
51 #include "llvm/Target/TargetRegisterInfo.h"
52 #include "llvm/Target/TargetSubtargetInfo.h"
53 #include "llvm/Transforms/IPO.h"
54 #include "llvm/Transforms/IPO/PassManagerBuilder.h"
55 #include "llvm/Transforms/ObjCARC.h"
56 #include <system_error>
59 const char* LTOCodeGenerator::getVersionString() {
60 #ifdef LLVM_VERSION_INFO
61 return PACKAGE_NAME " version " PACKAGE_VERSION ", " LLVM_VERSION_INFO;
63 return PACKAGE_NAME " version " PACKAGE_VERSION;
67 LTOCodeGenerator::LTOCodeGenerator()
68 : Context(getGlobalContext()), IRLinker(new Module("ld-temp.o", Context)) {
72 LTOCodeGenerator::LTOCodeGenerator(std::unique_ptr<LLVMContext> Context)
73 : OwnedContext(std::move(Context)), Context(*OwnedContext),
74 IRLinker(new Module("ld-temp.o", *OwnedContext)) {
78 void LTOCodeGenerator::initialize() {
80 EmitDwarfDebugInfo = false;
81 ScopeRestrictionsDone = false;
82 CodeModel = LTO_CODEGEN_PIC_MODEL_DEFAULT;
83 DiagHandler = nullptr;
84 DiagContext = nullptr;
86 initializeLTOPasses();
89 LTOCodeGenerator::~LTOCodeGenerator() {
93 IRLinker.deleteModule();
95 for (std::vector<char *>::iterator I = CodegenOptions.begin(),
96 E = CodegenOptions.end();
101 // Initialize LTO passes. Please keep this funciton in sync with
102 // PassManagerBuilder::populateLTOPassManager(), and make sure all LTO
103 // passes are initialized.
104 void LTOCodeGenerator::initializeLTOPasses() {
105 PassRegistry &R = *PassRegistry::getPassRegistry();
107 initializeInternalizePassPass(R);
108 initializeIPSCCPPass(R);
109 initializeGlobalOptPass(R);
110 initializeConstantMergePass(R);
111 initializeDAHPass(R);
112 initializeInstructionCombiningPassPass(R);
113 initializeSimpleInlinerPass(R);
114 initializePruneEHPass(R);
115 initializeGlobalDCEPass(R);
116 initializeArgPromotionPass(R);
117 initializeJumpThreadingPass(R);
118 initializeSROAPass(R);
119 initializeSROA_DTPass(R);
120 initializeSROA_SSAUpPass(R);
121 initializeFunctionAttrsPass(R);
122 initializeGlobalsModRefPass(R);
123 initializeLICMPass(R);
124 initializeMergedLoadStoreMotionPass(R);
125 initializeGVNPass(R);
126 initializeMemCpyOptPass(R);
127 initializeDCEPass(R);
128 initializeCFGSimplifyPassPass(R);
131 bool LTOCodeGenerator::addModule(LTOModule *mod) {
132 assert(&mod->getModule().getContext() == &Context &&
133 "Expected module in same context");
135 bool ret = IRLinker.linkInModule(&mod->getModule());
137 const std::vector<const char*> &undefs = mod->getAsmUndefinedRefs();
138 for (int i = 0, e = undefs.size(); i != e; ++i)
139 AsmUndefinedRefs[undefs[i]] = 1;
144 void LTOCodeGenerator::setTargetOptions(TargetOptions options) {
148 void LTOCodeGenerator::setDebugInfo(lto_debug_model debug) {
150 case LTO_DEBUG_MODEL_NONE:
151 EmitDwarfDebugInfo = false;
154 case LTO_DEBUG_MODEL_DWARF:
155 EmitDwarfDebugInfo = true;
158 llvm_unreachable("Unknown debug format!");
161 void LTOCodeGenerator::setCodePICModel(lto_codegen_model model) {
163 case LTO_CODEGEN_PIC_MODEL_STATIC:
164 case LTO_CODEGEN_PIC_MODEL_DYNAMIC:
165 case LTO_CODEGEN_PIC_MODEL_DYNAMIC_NO_PIC:
166 case LTO_CODEGEN_PIC_MODEL_DEFAULT:
170 llvm_unreachable("Unknown PIC model!");
173 bool LTOCodeGenerator::writeMergedModules(const char *path,
174 std::string &errMsg) {
175 if (!determineTarget(errMsg))
178 // mark which symbols can not be internalized
179 applyScopeRestrictions();
181 // create output file
183 tool_output_file Out(path, EC, sys::fs::F_None);
185 errMsg = "could not open bitcode file for writing: ";
190 // write bitcode to it
191 WriteBitcodeToFile(IRLinker.getModule(), Out.os());
194 if (Out.os().has_error()) {
195 errMsg = "could not write bitcode file: ";
197 Out.os().clear_error();
205 bool LTOCodeGenerator::compileOptimizedToFile(const char **name,
206 std::string &errMsg) {
207 // make unique temp .o file to put generated object file
208 SmallString<128> Filename;
211 sys::fs::createTemporaryFile("lto-llvm", "o", FD, Filename);
213 errMsg = EC.message();
217 // generate object file
218 tool_output_file objFile(Filename.c_str(), FD);
220 bool genResult = compileOptimized(objFile.os(), errMsg);
221 objFile.os().close();
222 if (objFile.os().has_error()) {
223 objFile.os().clear_error();
224 sys::fs::remove(Twine(Filename));
230 sys::fs::remove(Twine(Filename));
234 NativeObjectPath = Filename.c_str();
235 *name = NativeObjectPath.c_str();
239 const void *LTOCodeGenerator::compileOptimized(size_t *length,
240 std::string &errMsg) {
242 if (!compileOptimizedToFile(&name, errMsg))
245 // read .o file into memory buffer
246 ErrorOr<std::unique_ptr<MemoryBuffer>> BufferOrErr =
247 MemoryBuffer::getFile(name, -1, false);
248 if (std::error_code EC = BufferOrErr.getError()) {
249 errMsg = EC.message();
250 sys::fs::remove(NativeObjectPath);
253 NativeObjectFile = std::move(*BufferOrErr);
256 sys::fs::remove(NativeObjectPath);
258 // return buffer, unless error
259 if (!NativeObjectFile)
261 *length = NativeObjectFile->getBufferSize();
262 return NativeObjectFile->getBufferStart();
266 bool LTOCodeGenerator::compile_to_file(const char **name,
269 bool disableGVNLoadPRE,
270 bool disableVectorization,
271 std::string &errMsg) {
272 if (!optimize(disableOpt, disableInline, disableGVNLoadPRE,
273 disableVectorization, errMsg))
276 return compileOptimizedToFile(name, errMsg);
279 const void* LTOCodeGenerator::compile(size_t *length,
282 bool disableGVNLoadPRE,
283 bool disableVectorization,
284 std::string &errMsg) {
285 if (!optimize(disableOpt, disableInline, disableGVNLoadPRE,
286 disableVectorization, errMsg))
289 return compileOptimized(length, 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 TargetMach = march->createTargetMachine(TripleStr, MCpu, FeatureStr, Options,
340 RelocModel, CodeModel::Default,
341 CodeGenOpt::Aggressive);
345 void LTOCodeGenerator::
346 applyRestriction(GlobalValue &GV,
347 ArrayRef<StringRef> Libcalls,
348 std::vector<const char*> &MustPreserveList,
349 SmallPtrSetImpl<GlobalValue*> &AsmUsed,
351 // There are no restrictions to apply to declarations.
352 if (GV.isDeclaration())
355 // There is nothing more restrictive than private linkage.
356 if (GV.hasPrivateLinkage())
359 SmallString<64> Buffer;
360 TargetMach->getNameWithPrefix(Buffer, &GV, Mangler);
362 if (MustPreserveSymbols.count(Buffer))
363 MustPreserveList.push_back(GV.getName().data());
364 if (AsmUndefinedRefs.count(Buffer))
367 // Conservatively append user-supplied runtime library functions to
368 // llvm.compiler.used. These could be internalized and deleted by
369 // optimizations like -globalopt, causing problems when later optimizations
370 // add new library calls (e.g., llvm.memset => memset and printf => puts).
371 // Leave it to the linker to remove any dead code (e.g. with -dead_strip).
372 if (isa<Function>(GV) &&
373 std::binary_search(Libcalls.begin(), Libcalls.end(), GV.getName()))
377 static void findUsedValues(GlobalVariable *LLVMUsed,
378 SmallPtrSetImpl<GlobalValue*> &UsedValues) {
379 if (!LLVMUsed) return;
381 ConstantArray *Inits = cast<ConstantArray>(LLVMUsed->getInitializer());
382 for (unsigned i = 0, e = Inits->getNumOperands(); i != e; ++i)
383 if (GlobalValue *GV =
384 dyn_cast<GlobalValue>(Inits->getOperand(i)->stripPointerCasts()))
385 UsedValues.insert(GV);
388 // Collect names of runtime library functions. User-defined functions with the
389 // same names are added to llvm.compiler.used to prevent them from being
390 // deleted by optimizations.
391 static void accumulateAndSortLibcalls(std::vector<StringRef> &Libcalls,
392 const TargetLibraryInfo& TLI,
394 const TargetMachine &TM) {
395 // TargetLibraryInfo has info on C runtime library calls on the current
397 for (unsigned I = 0, E = static_cast<unsigned>(LibFunc::NumLibFuncs);
399 LibFunc::Func F = static_cast<LibFunc::Func>(I);
401 Libcalls.push_back(TLI.getName(F));
404 SmallPtrSet<const TargetLowering *, 1> TLSet;
406 for (const Function &F : Mod) {
407 const TargetLowering *Lowering =
408 TM.getSubtargetImpl(F)->getTargetLowering();
410 if (Lowering && TLSet.insert(Lowering).second)
411 // TargetLowering has info on library calls that CodeGen expects to be
412 // available, both from the C runtime and compiler-rt.
413 for (unsigned I = 0, E = static_cast<unsigned>(RTLIB::UNKNOWN_LIBCALL);
415 if (const char *Name =
416 Lowering->getLibcallName(static_cast<RTLIB::Libcall>(I)))
417 Libcalls.push_back(Name);
420 array_pod_sort(Libcalls.begin(), Libcalls.end());
421 Libcalls.erase(std::unique(Libcalls.begin(), Libcalls.end()),
425 void LTOCodeGenerator::applyScopeRestrictions() {
426 if (ScopeRestrictionsDone)
428 Module *mergedModule = IRLinker.getModule();
430 // Start off with a verification pass.
432 passes.add(createVerifierPass());
433 passes.add(createDebugInfoVerifierPass());
435 // mark which symbols can not be internalized
436 Mangler Mangler(TargetMach->getDataLayout());
437 std::vector<const char*> MustPreserveList;
438 SmallPtrSet<GlobalValue*, 8> AsmUsed;
439 std::vector<StringRef> Libcalls;
440 TargetLibraryInfoImpl TLII(Triple(TargetMach->getTargetTriple()));
441 TargetLibraryInfo TLI(TLII);
443 accumulateAndSortLibcalls(Libcalls, TLI, *mergedModule, *TargetMach);
445 for (Module::iterator f = mergedModule->begin(),
446 e = mergedModule->end(); f != e; ++f)
447 applyRestriction(*f, Libcalls, MustPreserveList, AsmUsed, Mangler);
448 for (Module::global_iterator v = mergedModule->global_begin(),
449 e = mergedModule->global_end(); v != e; ++v)
450 applyRestriction(*v, Libcalls, MustPreserveList, AsmUsed, Mangler);
451 for (Module::alias_iterator a = mergedModule->alias_begin(),
452 e = mergedModule->alias_end(); a != e; ++a)
453 applyRestriction(*a, Libcalls, MustPreserveList, AsmUsed, Mangler);
455 GlobalVariable *LLVMCompilerUsed =
456 mergedModule->getGlobalVariable("llvm.compiler.used");
457 findUsedValues(LLVMCompilerUsed, AsmUsed);
458 if (LLVMCompilerUsed)
459 LLVMCompilerUsed->eraseFromParent();
461 if (!AsmUsed.empty()) {
462 llvm::Type *i8PTy = llvm::Type::getInt8PtrTy(Context);
463 std::vector<Constant*> asmUsed2;
464 for (auto *GV : AsmUsed) {
465 Constant *c = ConstantExpr::getBitCast(GV, i8PTy);
466 asmUsed2.push_back(c);
469 llvm::ArrayType *ATy = llvm::ArrayType::get(i8PTy, asmUsed2.size());
471 new llvm::GlobalVariable(*mergedModule, ATy, false,
472 llvm::GlobalValue::AppendingLinkage,
473 llvm::ConstantArray::get(ATy, asmUsed2),
474 "llvm.compiler.used");
476 LLVMCompilerUsed->setSection("llvm.metadata");
479 passes.add(createInternalizePass(MustPreserveList));
481 // apply scope restrictions
482 passes.run(*mergedModule);
484 ScopeRestrictionsDone = true;
487 /// Optimize merged modules using various IPO passes
488 bool LTOCodeGenerator::optimize(bool DisableOpt,
490 bool DisableGVNLoadPRE,
491 bool DisableVectorization,
492 std::string &errMsg) {
493 if (!this->determineTarget(errMsg))
496 Module *mergedModule = IRLinker.getModule();
498 // Mark which symbols can not be internalized
499 this->applyScopeRestrictions();
501 // Instantiate the pass manager to organize the passes.
504 // Add an appropriate DataLayout instance for this module...
505 mergedModule->setDataLayout(TargetMach->getDataLayout());
507 passes.add(new DataLayoutPass());
509 createTargetTransformInfoWrapperPass(TargetMach->getTargetIRAnalysis()));
511 Triple TargetTriple(TargetMach->getTargetTriple());
512 PassManagerBuilder PMB;
513 PMB.DisableGVNLoadPRE = DisableGVNLoadPRE;
514 PMB.LoopVectorize = !DisableVectorization;
515 PMB.SLPVectorize = !DisableVectorization;
517 PMB.Inliner = createFunctionInliningPass();
518 PMB.LibraryInfo = new TargetLibraryInfoImpl(TargetTriple);
521 PMB.VerifyInput = true;
522 PMB.VerifyOutput = true;
524 PMB.populateLTOPassManager(passes);
526 // Run our queue of passes all at once now, efficiently.
527 passes.run(*mergedModule);
532 bool LTOCodeGenerator::compileOptimized(raw_ostream &out, std::string &errMsg) {
533 if (!this->determineTarget(errMsg))
536 Module *mergedModule = IRLinker.getModule();
538 // Mark which symbols can not be internalized
539 this->applyScopeRestrictions();
541 PassManager codeGenPasses;
543 codeGenPasses.add(new DataLayoutPass());
545 formatted_raw_ostream Out(out);
547 // If the bitcode files contain ARC code and were compiled with optimization,
548 // the ObjCARCContractPass must be run, so do it unconditionally here.
549 codeGenPasses.add(createObjCARCContractPass());
551 if (TargetMach->addPassesToEmitFile(codeGenPasses, Out,
552 TargetMachine::CGFT_ObjectFile)) {
553 errMsg = "target file type not supported";
557 // Run the code generator, and write assembly file
558 codeGenPasses.run(*mergedModule);
563 /// setCodeGenDebugOptions - Set codegen debugging options to aid in debugging
565 void LTOCodeGenerator::setCodeGenDebugOptions(const char *options) {
566 for (std::pair<StringRef, StringRef> o = getToken(options);
567 !o.first.empty(); o = getToken(o.second)) {
568 // ParseCommandLineOptions() expects argv[0] to be program name. Lazily add
570 if (CodegenOptions.empty())
571 CodegenOptions.push_back(strdup("libLLVMLTO"));
572 CodegenOptions.push_back(strdup(o.first.str().c_str()));
576 void LTOCodeGenerator::parseCodeGenDebugOptions() {
577 // if options were requested, set them
578 if (!CodegenOptions.empty())
579 cl::ParseCommandLineOptions(CodegenOptions.size(),
580 const_cast<char **>(&CodegenOptions[0]));
583 void LTOCodeGenerator::DiagnosticHandler(const DiagnosticInfo &DI,
585 ((LTOCodeGenerator *)Context)->DiagnosticHandler2(DI);
588 void LTOCodeGenerator::DiagnosticHandler2(const DiagnosticInfo &DI) {
589 // Map the LLVM internal diagnostic severity to the LTO diagnostic severity.
590 lto_codegen_diagnostic_severity_t Severity;
591 switch (DI.getSeverity()) {
593 Severity = LTO_DS_ERROR;
596 Severity = LTO_DS_WARNING;
599 Severity = LTO_DS_REMARK;
602 Severity = LTO_DS_NOTE;
605 // Create the string that will be reported to the external diagnostic handler.
606 std::string MsgStorage;
607 raw_string_ostream Stream(MsgStorage);
608 DiagnosticPrinterRawOStream DP(Stream);
612 // If this method has been called it means someone has set up an external
613 // diagnostic handler. Assert on that.
614 assert(DiagHandler && "Invalid diagnostic handler");
615 (*DiagHandler)(Severity, MsgStorage.c_str(), DiagContext);
619 LTOCodeGenerator::setDiagnosticHandler(lto_diagnostic_handler_t DiagHandler,
621 this->DiagHandler = DiagHandler;
622 this->DiagContext = Ctxt;
624 return Context.setDiagnosticHandler(nullptr, nullptr);
625 // Register the LTOCodeGenerator stub in the LLVMContext to forward the
626 // diagnostic to the external DiagHandler.
627 Context.setDiagnosticHandler(LTOCodeGenerator::DiagnosticHandler, this,
628 /* RespectFilters */ true);