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/ParallelCG.h"
22 #include "llvm/CodeGen/RuntimeLibcalls.h"
23 #include "llvm/Config/config.h"
24 #include "llvm/IR/Constants.h"
25 #include "llvm/IR/DataLayout.h"
26 #include "llvm/IR/DerivedTypes.h"
27 #include "llvm/IR/DiagnosticInfo.h"
28 #include "llvm/IR/DiagnosticPrinter.h"
29 #include "llvm/IR/LLVMContext.h"
30 #include "llvm/IR/LegacyPassManager.h"
31 #include "llvm/IR/Mangler.h"
32 #include "llvm/IR/Module.h"
33 #include "llvm/IR/Verifier.h"
34 #include "llvm/InitializePasses.h"
35 #include "llvm/LTO/LTOModule.h"
36 #include "llvm/Linker/Linker.h"
37 #include "llvm/MC/MCAsmInfo.h"
38 #include "llvm/MC/MCContext.h"
39 #include "llvm/MC/SubtargetFeature.h"
40 #include "llvm/Support/CommandLine.h"
41 #include "llvm/Support/FileSystem.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 static void handleLTODiagnostic(const DiagnosticInfo &DI) {
68 DiagnosticPrinterRawOStream DP(errs());
73 LTOCodeGenerator::LTOCodeGenerator()
74 : Context(getGlobalContext()),
75 MergedModule(new Module("ld-temp.o", Context)),
76 IRLinker(MergedModule.get(), handleLTODiagnostic) {
77 initializeLTOPasses();
80 LTOCodeGenerator::LTOCodeGenerator(std::unique_ptr<LLVMContext> Context)
81 : OwnedContext(std::move(Context)), Context(*OwnedContext),
82 MergedModule(new Module("ld-temp.o", *OwnedContext)),
83 IRLinker(MergedModule.get(), handleLTODiagnostic) {
84 initializeLTOPasses();
87 LTOCodeGenerator::~LTOCodeGenerator() {}
89 // Initialize LTO passes. Please keep this function in sync with
90 // PassManagerBuilder::populateLTOPassManager(), and make sure all LTO
91 // passes are initialized.
92 void LTOCodeGenerator::initializeLTOPasses() {
93 PassRegistry &R = *PassRegistry::getPassRegistry();
95 initializeInternalizePassPass(R);
96 initializeIPSCCPPass(R);
97 initializeGlobalOptPass(R);
98 initializeConstantMergePass(R);
100 initializeInstructionCombiningPassPass(R);
101 initializeSimpleInlinerPass(R);
102 initializePruneEHPass(R);
103 initializeGlobalDCEPass(R);
104 initializeArgPromotionPass(R);
105 initializeJumpThreadingPass(R);
106 initializeSROALegacyPassPass(R);
107 initializeSROA_DTPass(R);
108 initializeSROA_SSAUpPass(R);
109 initializeFunctionAttrsPass(R);
110 initializeGlobalsAAWrapperPassPass(R);
111 initializeLICMPass(R);
112 initializeMergedLoadStoreMotionPass(R);
113 initializeGVNPass(R);
114 initializeMemCpyOptPass(R);
115 initializeDCEPass(R);
116 initializeCFGSimplifyPassPass(R);
119 bool LTOCodeGenerator::addModule(LTOModule *Mod) {
120 assert(&Mod->getModule().getContext() == &Context &&
121 "Expected module in same context");
123 bool ret = IRLinker.linkInModule(&Mod->getModule());
125 const std::vector<const char *> &undefs = Mod->getAsmUndefinedRefs();
126 for (int i = 0, e = undefs.size(); i != e; ++i)
127 AsmUndefinedRefs[undefs[i]] = 1;
132 void LTOCodeGenerator::setModule(std::unique_ptr<LTOModule> Mod) {
133 assert(&Mod->getModule().getContext() == &Context &&
134 "Expected module in same context");
136 AsmUndefinedRefs.clear();
138 MergedModule = Mod->takeModule();
139 IRLinker.setModule(MergedModule.get());
141 const std::vector<const char*> &Undefs = Mod->getAsmUndefinedRefs();
142 for (int I = 0, E = Undefs.size(); I != E; ++I)
143 AsmUndefinedRefs[Undefs[I]] = 1;
146 void LTOCodeGenerator::setTargetOptions(TargetOptions Options) {
147 this->Options = Options;
150 void LTOCodeGenerator::setDebugInfo(lto_debug_model Debug) {
152 case LTO_DEBUG_MODEL_NONE:
153 EmitDwarfDebugInfo = false;
156 case LTO_DEBUG_MODEL_DWARF:
157 EmitDwarfDebugInfo = true;
160 llvm_unreachable("Unknown debug format!");
163 void LTOCodeGenerator::setOptLevel(unsigned Level) {
167 CGOptLevel = CodeGenOpt::None;
170 CGOptLevel = CodeGenOpt::Less;
173 CGOptLevel = CodeGenOpt::Default;
176 CGOptLevel = CodeGenOpt::Aggressive;
181 bool LTOCodeGenerator::writeMergedModules(const char *Path,
182 std::string &ErrMsg) {
183 if (!determineTarget(ErrMsg))
186 // mark which symbols can not be internalized
187 applyScopeRestrictions();
189 // create output file
191 tool_output_file Out(Path, EC, sys::fs::F_None);
193 ErrMsg = "could not open bitcode file for writing: ";
198 // write bitcode to it
199 WriteBitcodeToFile(MergedModule.get(), Out.os(), ShouldEmbedUselists);
202 if (Out.os().has_error()) {
203 ErrMsg = "could not write bitcode file: ";
205 Out.os().clear_error();
213 bool LTOCodeGenerator::compileOptimizedToFile(const char **Name,
214 std::string &ErrMsg) {
215 // make unique temp .o file to put generated object file
216 SmallString<128> Filename;
219 sys::fs::createTemporaryFile("lto-llvm", "o", FD, Filename);
221 ErrMsg = EC.message();
225 // generate object file
226 tool_output_file objFile(Filename.c_str(), FD);
228 bool genResult = compileOptimized(&objFile.os(), ErrMsg);
229 objFile.os().close();
230 if (objFile.os().has_error()) {
231 objFile.os().clear_error();
232 sys::fs::remove(Twine(Filename));
238 sys::fs::remove(Twine(Filename));
242 NativeObjectPath = Filename.c_str();
243 *Name = NativeObjectPath.c_str();
247 std::unique_ptr<MemoryBuffer>
248 LTOCodeGenerator::compileOptimized(std::string &ErrMsg) {
250 if (!compileOptimizedToFile(&name, ErrMsg))
253 // read .o file into memory buffer
254 ErrorOr<std::unique_ptr<MemoryBuffer>> BufferOrErr =
255 MemoryBuffer::getFile(name, -1, false);
256 if (std::error_code EC = BufferOrErr.getError()) {
257 ErrMsg = EC.message();
258 sys::fs::remove(NativeObjectPath);
263 sys::fs::remove(NativeObjectPath);
265 return std::move(*BufferOrErr);
268 bool LTOCodeGenerator::compile_to_file(const char **Name, bool DisableVerify,
270 bool DisableGVNLoadPRE,
271 bool DisableVectorization,
272 std::string &ErrMsg) {
273 if (!optimize(DisableVerify, DisableInline, DisableGVNLoadPRE,
274 DisableVectorization, ErrMsg))
277 return compileOptimizedToFile(Name, ErrMsg);
280 std::unique_ptr<MemoryBuffer>
281 LTOCodeGenerator::compile(bool DisableVerify, bool DisableInline,
282 bool DisableGVNLoadPRE, bool DisableVectorization,
283 std::string &ErrMsg) {
284 if (!optimize(DisableVerify, DisableInline, DisableGVNLoadPRE,
285 DisableVectorization, ErrMsg))
288 return compileOptimized(ErrMsg);
291 bool LTOCodeGenerator::determineTarget(std::string &ErrMsg) {
295 std::string TripleStr = MergedModule->getTargetTriple();
296 if (TripleStr.empty()) {
297 TripleStr = sys::getDefaultTargetTriple();
298 MergedModule->setTargetTriple(TripleStr);
300 llvm::Triple Triple(TripleStr);
302 // create target machine from info for merged modules
303 const Target *march = TargetRegistry::lookupTarget(TripleStr, ErrMsg);
307 // Construct LTOModule, hand over ownership of module and target. Use MAttr as
308 // the default set of features.
309 SubtargetFeatures Features(MAttr);
310 Features.getDefaultSubtargetFeatures(Triple);
311 FeatureStr = Features.getString();
312 // Set a default CPU for Darwin triples.
313 if (MCpu.empty() && Triple.isOSDarwin()) {
314 if (Triple.getArch() == llvm::Triple::x86_64)
316 else if (Triple.getArch() == llvm::Triple::x86)
318 else if (Triple.getArch() == llvm::Triple::aarch64)
322 TargetMach.reset(march->createTargetMachine(TripleStr, MCpu, FeatureStr,
324 CodeModel::Default, CGOptLevel));
328 void LTOCodeGenerator::
329 applyRestriction(GlobalValue &GV,
330 ArrayRef<StringRef> Libcalls,
331 std::vector<const char*> &MustPreserveList,
332 SmallPtrSetImpl<GlobalValue*> &AsmUsed,
334 // There are no restrictions to apply to declarations.
335 if (GV.isDeclaration())
338 // There is nothing more restrictive than private linkage.
339 if (GV.hasPrivateLinkage())
342 SmallString<64> Buffer;
343 TargetMach->getNameWithPrefix(Buffer, &GV, Mangler);
345 if (MustPreserveSymbols.count(Buffer))
346 MustPreserveList.push_back(GV.getName().data());
347 if (AsmUndefinedRefs.count(Buffer))
350 // Conservatively append user-supplied runtime library functions to
351 // llvm.compiler.used. These could be internalized and deleted by
352 // optimizations like -globalopt, causing problems when later optimizations
353 // add new library calls (e.g., llvm.memset => memset and printf => puts).
354 // Leave it to the linker to remove any dead code (e.g. with -dead_strip).
355 if (isa<Function>(GV) &&
356 std::binary_search(Libcalls.begin(), Libcalls.end(), GV.getName()))
360 static void findUsedValues(GlobalVariable *LLVMUsed,
361 SmallPtrSetImpl<GlobalValue*> &UsedValues) {
362 if (!LLVMUsed) return;
364 ConstantArray *Inits = cast<ConstantArray>(LLVMUsed->getInitializer());
365 for (unsigned i = 0, e = Inits->getNumOperands(); i != e; ++i)
366 if (GlobalValue *GV =
367 dyn_cast<GlobalValue>(Inits->getOperand(i)->stripPointerCasts()))
368 UsedValues.insert(GV);
371 // Collect names of runtime library functions. User-defined functions with the
372 // same names are added to llvm.compiler.used to prevent them from being
373 // deleted by optimizations.
374 static void accumulateAndSortLibcalls(std::vector<StringRef> &Libcalls,
375 const TargetLibraryInfo& TLI,
377 const TargetMachine &TM) {
378 // TargetLibraryInfo has info on C runtime library calls on the current
380 for (unsigned I = 0, E = static_cast<unsigned>(LibFunc::NumLibFuncs);
382 LibFunc::Func F = static_cast<LibFunc::Func>(I);
384 Libcalls.push_back(TLI.getName(F));
387 SmallPtrSet<const TargetLowering *, 1> TLSet;
389 for (const Function &F : Mod) {
390 const TargetLowering *Lowering =
391 TM.getSubtargetImpl(F)->getTargetLowering();
393 if (Lowering && TLSet.insert(Lowering).second)
394 // TargetLowering has info on library calls that CodeGen expects to be
395 // available, both from the C runtime and compiler-rt.
396 for (unsigned I = 0, E = static_cast<unsigned>(RTLIB::UNKNOWN_LIBCALL);
398 if (const char *Name =
399 Lowering->getLibcallName(static_cast<RTLIB::Libcall>(I)))
400 Libcalls.push_back(Name);
403 array_pod_sort(Libcalls.begin(), Libcalls.end());
404 Libcalls.erase(std::unique(Libcalls.begin(), Libcalls.end()),
408 void LTOCodeGenerator::applyScopeRestrictions() {
409 if (ScopeRestrictionsDone || !ShouldInternalize)
412 // Start off with a verification pass.
413 legacy::PassManager passes;
414 passes.add(createVerifierPass());
416 // mark which symbols can not be internalized
418 std::vector<const char*> MustPreserveList;
419 SmallPtrSet<GlobalValue*, 8> AsmUsed;
420 std::vector<StringRef> Libcalls;
421 TargetLibraryInfoImpl TLII(Triple(TargetMach->getTargetTriple()));
422 TargetLibraryInfo TLI(TLII);
424 accumulateAndSortLibcalls(Libcalls, TLI, *MergedModule, *TargetMach);
426 for (Function &f : *MergedModule)
427 applyRestriction(f, Libcalls, MustPreserveList, AsmUsed, Mangler);
428 for (GlobalVariable &v : MergedModule->globals())
429 applyRestriction(v, Libcalls, MustPreserveList, AsmUsed, Mangler);
430 for (GlobalAlias &a : MergedModule->aliases())
431 applyRestriction(a, Libcalls, MustPreserveList, AsmUsed, Mangler);
433 GlobalVariable *LLVMCompilerUsed =
434 MergedModule->getGlobalVariable("llvm.compiler.used");
435 findUsedValues(LLVMCompilerUsed, AsmUsed);
436 if (LLVMCompilerUsed)
437 LLVMCompilerUsed->eraseFromParent();
439 if (!AsmUsed.empty()) {
440 llvm::Type *i8PTy = llvm::Type::getInt8PtrTy(Context);
441 std::vector<Constant*> asmUsed2;
442 for (auto *GV : AsmUsed) {
443 Constant *c = ConstantExpr::getBitCast(GV, i8PTy);
444 asmUsed2.push_back(c);
447 llvm::ArrayType *ATy = llvm::ArrayType::get(i8PTy, asmUsed2.size());
449 new llvm::GlobalVariable(*MergedModule, ATy, false,
450 llvm::GlobalValue::AppendingLinkage,
451 llvm::ConstantArray::get(ATy, asmUsed2),
452 "llvm.compiler.used");
454 LLVMCompilerUsed->setSection("llvm.metadata");
457 passes.add(createInternalizePass(MustPreserveList));
459 // apply scope restrictions
460 passes.run(*MergedModule);
462 ScopeRestrictionsDone = true;
465 /// Optimize merged modules using various IPO passes
466 bool LTOCodeGenerator::optimize(bool DisableVerify, bool DisableInline,
467 bool DisableGVNLoadPRE,
468 bool DisableVectorization,
469 std::string &ErrMsg) {
470 if (!this->determineTarget(ErrMsg))
473 // Mark which symbols can not be internalized
474 this->applyScopeRestrictions();
476 // Instantiate the pass manager to organize the passes.
477 legacy::PassManager passes;
479 // Add an appropriate DataLayout instance for this module...
480 MergedModule->setDataLayout(TargetMach->createDataLayout());
483 createTargetTransformInfoWrapperPass(TargetMach->getTargetIRAnalysis()));
485 Triple TargetTriple(TargetMach->getTargetTriple());
486 PassManagerBuilder PMB;
487 PMB.DisableGVNLoadPRE = DisableGVNLoadPRE;
488 PMB.LoopVectorize = !DisableVectorization;
489 PMB.SLPVectorize = !DisableVectorization;
491 PMB.Inliner = createFunctionInliningPass();
492 PMB.LibraryInfo = new TargetLibraryInfoImpl(TargetTriple);
493 PMB.OptLevel = OptLevel;
494 PMB.VerifyInput = !DisableVerify;
495 PMB.VerifyOutput = !DisableVerify;
497 PMB.populateLTOPassManager(passes);
499 // Run our queue of passes all at once now, efficiently.
500 passes.run(*MergedModule);
505 bool LTOCodeGenerator::compileOptimized(ArrayRef<raw_pwrite_stream *> Out,
506 std::string &ErrMsg) {
507 if (!this->determineTarget(ErrMsg))
510 legacy::PassManager preCodeGenPasses;
512 // If the bitcode files contain ARC code and were compiled with optimization,
513 // the ObjCARCContractPass must be run, so do it unconditionally here.
514 preCodeGenPasses.add(createObjCARCContractPass());
515 preCodeGenPasses.run(*MergedModule);
517 // Do code generation. We need to preserve the module in case the client calls
518 // writeMergedModules() after compilation, but we only need to allow this at
519 // parallelism level 1. This is achieved by having splitCodeGen return the
520 // original module at parallelism level 1 which we then assign back to
523 splitCodeGen(std::move(MergedModule), Out, MCpu, FeatureStr, Options,
524 RelocModel, CodeModel::Default, CGOptLevel);
529 /// setCodeGenDebugOptions - Set codegen debugging options to aid in debugging
531 void LTOCodeGenerator::setCodeGenDebugOptions(const char *Options) {
532 for (std::pair<StringRef, StringRef> o = getToken(Options); !o.first.empty();
533 o = getToken(o.second))
534 CodegenOptions.push_back(o.first);
537 void LTOCodeGenerator::parseCodeGenDebugOptions() {
538 // if options were requested, set them
539 if (!CodegenOptions.empty()) {
540 // ParseCommandLineOptions() expects argv[0] to be program name.
541 std::vector<const char *> CodegenArgv(1, "libLLVMLTO");
542 for (std::string &Arg : CodegenOptions)
543 CodegenArgv.push_back(Arg.c_str());
544 cl::ParseCommandLineOptions(CodegenArgv.size(), CodegenArgv.data());
548 void LTOCodeGenerator::DiagnosticHandler(const DiagnosticInfo &DI,
550 ((LTOCodeGenerator *)Context)->DiagnosticHandler2(DI);
553 void LTOCodeGenerator::DiagnosticHandler2(const DiagnosticInfo &DI) {
554 // Map the LLVM internal diagnostic severity to the LTO diagnostic severity.
555 lto_codegen_diagnostic_severity_t Severity;
556 switch (DI.getSeverity()) {
558 Severity = LTO_DS_ERROR;
561 Severity = LTO_DS_WARNING;
564 Severity = LTO_DS_REMARK;
567 Severity = LTO_DS_NOTE;
570 // Create the string that will be reported to the external diagnostic handler.
571 std::string MsgStorage;
572 raw_string_ostream Stream(MsgStorage);
573 DiagnosticPrinterRawOStream DP(Stream);
577 // If this method has been called it means someone has set up an external
578 // diagnostic handler. Assert on that.
579 assert(DiagHandler && "Invalid diagnostic handler");
580 (*DiagHandler)(Severity, MsgStorage.c_str(), DiagContext);
584 LTOCodeGenerator::setDiagnosticHandler(lto_diagnostic_handler_t DiagHandler,
586 this->DiagHandler = DiagHandler;
587 this->DiagContext = Ctxt;
589 return Context.setDiagnosticHandler(nullptr, nullptr);
590 // Register the LTOCodeGenerator stub in the LLVMContext to forward the
591 // diagnostic to the external DiagHandler.
592 Context.setDiagnosticHandler(LTOCodeGenerator::DiagnosticHandler, this,
593 /* RespectFilters */ true);