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 initializeSROAPass(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 DisableInline,
269 bool DisableGVNLoadPRE,
270 bool DisableVectorization,
271 std::string &ErrMsg) {
272 if (!optimize(DisableInline, DisableGVNLoadPRE, DisableVectorization, ErrMsg))
275 return compileOptimizedToFile(Name, ErrMsg);
278 std::unique_ptr<MemoryBuffer>
279 LTOCodeGenerator::compile(bool DisableInline, bool DisableGVNLoadPRE,
280 bool DisableVectorization, std::string &ErrMsg) {
281 if (!optimize(DisableInline, DisableGVNLoadPRE, DisableVectorization, ErrMsg))
284 return compileOptimized(ErrMsg);
287 bool LTOCodeGenerator::determineTarget(std::string &ErrMsg) {
291 std::string TripleStr = MergedModule->getTargetTriple();
292 if (TripleStr.empty()) {
293 TripleStr = sys::getDefaultTargetTriple();
294 MergedModule->setTargetTriple(TripleStr);
296 llvm::Triple Triple(TripleStr);
298 // create target machine from info for merged modules
299 const Target *march = TargetRegistry::lookupTarget(TripleStr, ErrMsg);
303 // Construct LTOModule, hand over ownership of module and target. Use MAttr as
304 // the default set of features.
305 SubtargetFeatures Features(MAttr);
306 Features.getDefaultSubtargetFeatures(Triple);
307 FeatureStr = Features.getString();
308 // Set a default CPU for Darwin triples.
309 if (MCpu.empty() && Triple.isOSDarwin()) {
310 if (Triple.getArch() == llvm::Triple::x86_64)
312 else if (Triple.getArch() == llvm::Triple::x86)
314 else if (Triple.getArch() == llvm::Triple::aarch64)
318 TargetMach.reset(march->createTargetMachine(TripleStr, MCpu, FeatureStr,
320 CodeModel::Default, CGOptLevel));
324 void LTOCodeGenerator::
325 applyRestriction(GlobalValue &GV,
326 ArrayRef<StringRef> Libcalls,
327 std::vector<const char*> &MustPreserveList,
328 SmallPtrSetImpl<GlobalValue*> &AsmUsed,
330 // There are no restrictions to apply to declarations.
331 if (GV.isDeclaration())
334 // There is nothing more restrictive than private linkage.
335 if (GV.hasPrivateLinkage())
338 SmallString<64> Buffer;
339 TargetMach->getNameWithPrefix(Buffer, &GV, Mangler);
341 if (MustPreserveSymbols.count(Buffer))
342 MustPreserveList.push_back(GV.getName().data());
343 if (AsmUndefinedRefs.count(Buffer))
346 // Conservatively append user-supplied runtime library functions to
347 // llvm.compiler.used. These could be internalized and deleted by
348 // optimizations like -globalopt, causing problems when later optimizations
349 // add new library calls (e.g., llvm.memset => memset and printf => puts).
350 // Leave it to the linker to remove any dead code (e.g. with -dead_strip).
351 if (isa<Function>(GV) &&
352 std::binary_search(Libcalls.begin(), Libcalls.end(), GV.getName()))
356 static void findUsedValues(GlobalVariable *LLVMUsed,
357 SmallPtrSetImpl<GlobalValue*> &UsedValues) {
358 if (!LLVMUsed) return;
360 ConstantArray *Inits = cast<ConstantArray>(LLVMUsed->getInitializer());
361 for (unsigned i = 0, e = Inits->getNumOperands(); i != e; ++i)
362 if (GlobalValue *GV =
363 dyn_cast<GlobalValue>(Inits->getOperand(i)->stripPointerCasts()))
364 UsedValues.insert(GV);
367 // Collect names of runtime library functions. User-defined functions with the
368 // same names are added to llvm.compiler.used to prevent them from being
369 // deleted by optimizations.
370 static void accumulateAndSortLibcalls(std::vector<StringRef> &Libcalls,
371 const TargetLibraryInfo& TLI,
373 const TargetMachine &TM) {
374 // TargetLibraryInfo has info on C runtime library calls on the current
376 for (unsigned I = 0, E = static_cast<unsigned>(LibFunc::NumLibFuncs);
378 LibFunc::Func F = static_cast<LibFunc::Func>(I);
380 Libcalls.push_back(TLI.getName(F));
383 SmallPtrSet<const TargetLowering *, 1> TLSet;
385 for (const Function &F : Mod) {
386 const TargetLowering *Lowering =
387 TM.getSubtargetImpl(F)->getTargetLowering();
389 if (Lowering && TLSet.insert(Lowering).second)
390 // TargetLowering has info on library calls that CodeGen expects to be
391 // available, both from the C runtime and compiler-rt.
392 for (unsigned I = 0, E = static_cast<unsigned>(RTLIB::UNKNOWN_LIBCALL);
394 if (const char *Name =
395 Lowering->getLibcallName(static_cast<RTLIB::Libcall>(I)))
396 Libcalls.push_back(Name);
399 array_pod_sort(Libcalls.begin(), Libcalls.end());
400 Libcalls.erase(std::unique(Libcalls.begin(), Libcalls.end()),
404 void LTOCodeGenerator::applyScopeRestrictions() {
405 if (ScopeRestrictionsDone || !ShouldInternalize)
408 // Start off with a verification pass.
409 legacy::PassManager passes;
410 passes.add(createVerifierPass());
412 // mark which symbols can not be internalized
414 std::vector<const char*> MustPreserveList;
415 SmallPtrSet<GlobalValue*, 8> AsmUsed;
416 std::vector<StringRef> Libcalls;
417 TargetLibraryInfoImpl TLII(Triple(TargetMach->getTargetTriple()));
418 TargetLibraryInfo TLI(TLII);
420 accumulateAndSortLibcalls(Libcalls, TLI, *MergedModule, *TargetMach);
422 for (Function &f : *MergedModule)
423 applyRestriction(f, Libcalls, MustPreserveList, AsmUsed, Mangler);
424 for (GlobalVariable &v : MergedModule->globals())
425 applyRestriction(v, Libcalls, MustPreserveList, AsmUsed, Mangler);
426 for (GlobalAlias &a : MergedModule->aliases())
427 applyRestriction(a, Libcalls, MustPreserveList, AsmUsed, Mangler);
429 GlobalVariable *LLVMCompilerUsed =
430 MergedModule->getGlobalVariable("llvm.compiler.used");
431 findUsedValues(LLVMCompilerUsed, AsmUsed);
432 if (LLVMCompilerUsed)
433 LLVMCompilerUsed->eraseFromParent();
435 if (!AsmUsed.empty()) {
436 llvm::Type *i8PTy = llvm::Type::getInt8PtrTy(Context);
437 std::vector<Constant*> asmUsed2;
438 for (auto *GV : AsmUsed) {
439 Constant *c = ConstantExpr::getBitCast(GV, i8PTy);
440 asmUsed2.push_back(c);
443 llvm::ArrayType *ATy = llvm::ArrayType::get(i8PTy, asmUsed2.size());
445 new llvm::GlobalVariable(*MergedModule, ATy, false,
446 llvm::GlobalValue::AppendingLinkage,
447 llvm::ConstantArray::get(ATy, asmUsed2),
448 "llvm.compiler.used");
450 LLVMCompilerUsed->setSection("llvm.metadata");
453 passes.add(createInternalizePass(MustPreserveList));
455 // apply scope restrictions
456 passes.run(*MergedModule);
458 ScopeRestrictionsDone = true;
461 /// Optimize merged modules using various IPO passes
462 bool LTOCodeGenerator::optimize(bool DisableInline, bool DisableGVNLoadPRE,
463 bool DisableVectorization,
464 std::string &ErrMsg) {
465 if (!this->determineTarget(ErrMsg))
468 // Mark which symbols can not be internalized
469 this->applyScopeRestrictions();
471 // Instantiate the pass manager to organize the passes.
472 legacy::PassManager passes;
474 // Add an appropriate DataLayout instance for this module...
475 MergedModule->setDataLayout(TargetMach->createDataLayout());
478 createTargetTransformInfoWrapperPass(TargetMach->getTargetIRAnalysis()));
480 Triple TargetTriple(TargetMach->getTargetTriple());
481 PassManagerBuilder PMB;
482 PMB.DisableGVNLoadPRE = DisableGVNLoadPRE;
483 PMB.LoopVectorize = !DisableVectorization;
484 PMB.SLPVectorize = !DisableVectorization;
486 PMB.Inliner = createFunctionInliningPass();
487 PMB.LibraryInfo = new TargetLibraryInfoImpl(TargetTriple);
488 PMB.OptLevel = OptLevel;
489 PMB.VerifyInput = true;
490 PMB.VerifyOutput = true;
492 PMB.populateLTOPassManager(passes);
494 // Run our queue of passes all at once now, efficiently.
495 passes.run(*MergedModule);
500 bool LTOCodeGenerator::compileOptimized(ArrayRef<raw_pwrite_stream *> Out,
501 std::string &ErrMsg) {
502 if (!this->determineTarget(ErrMsg))
505 legacy::PassManager preCodeGenPasses;
507 // If the bitcode files contain ARC code and were compiled with optimization,
508 // the ObjCARCContractPass must be run, so do it unconditionally here.
509 preCodeGenPasses.add(createObjCARCContractPass());
510 preCodeGenPasses.run(*MergedModule);
512 // Do code generation. We need to preserve the module in case the client calls
513 // writeMergedModules() after compilation, but we only need to allow this at
514 // parallelism level 1. This is achieved by having splitCodeGen return the
515 // original module at parallelism level 1 which we then assign back to
518 splitCodeGen(std::move(MergedModule), Out, MCpu, FeatureStr, Options,
519 RelocModel, CodeModel::Default, CGOptLevel);
524 /// setCodeGenDebugOptions - Set codegen debugging options to aid in debugging
526 void LTOCodeGenerator::setCodeGenDebugOptions(const char *Options) {
527 for (std::pair<StringRef, StringRef> o = getToken(Options); !o.first.empty();
528 o = getToken(o.second))
529 CodegenOptions.push_back(o.first);
532 void LTOCodeGenerator::parseCodeGenDebugOptions() {
533 // if options were requested, set them
534 if (!CodegenOptions.empty()) {
535 // ParseCommandLineOptions() expects argv[0] to be program name.
536 std::vector<const char *> CodegenArgv(1, "libLLVMLTO");
537 for (std::string &Arg : CodegenOptions)
538 CodegenArgv.push_back(Arg.c_str());
539 cl::ParseCommandLineOptions(CodegenArgv.size(), CodegenArgv.data());
543 void LTOCodeGenerator::DiagnosticHandler(const DiagnosticInfo &DI,
545 ((LTOCodeGenerator *)Context)->DiagnosticHandler2(DI);
548 void LTOCodeGenerator::DiagnosticHandler2(const DiagnosticInfo &DI) {
549 // Map the LLVM internal diagnostic severity to the LTO diagnostic severity.
550 lto_codegen_diagnostic_severity_t Severity;
551 switch (DI.getSeverity()) {
553 Severity = LTO_DS_ERROR;
556 Severity = LTO_DS_WARNING;
559 Severity = LTO_DS_REMARK;
562 Severity = LTO_DS_NOTE;
565 // Create the string that will be reported to the external diagnostic handler.
566 std::string MsgStorage;
567 raw_string_ostream Stream(MsgStorage);
568 DiagnosticPrinterRawOStream DP(Stream);
572 // If this method has been called it means someone has set up an external
573 // diagnostic handler. Assert on that.
574 assert(DiagHandler && "Invalid diagnostic handler");
575 (*DiagHandler)(Severity, MsgStorage.c_str(), DiagContext);
579 LTOCodeGenerator::setDiagnosticHandler(lto_diagnostic_handler_t DiagHandler,
581 this->DiagHandler = DiagHandler;
582 this->DiagContext = Ctxt;
584 return Context.setDiagnosticHandler(nullptr, nullptr);
585 // Register the LTOCodeGenerator stub in the LLVMContext to forward the
586 // diagnostic to the external DiagHandler.
587 Context.setDiagnosticHandler(LTOCodeGenerator::DiagnosticHandler, this,
588 /* RespectFilters */ true);