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 LTOCodeGenerator::LTOCodeGenerator(LLVMContext &Context)
69 MergedModule(new Module("ld-temp.o", Context)),
70 IRLinker(new Linker(*MergedModule)) {
71 initializeLTOPasses();
74 LTOCodeGenerator::~LTOCodeGenerator() {}
76 // Initialize LTO passes. Please keep this function in sync with
77 // PassManagerBuilder::populateLTOPassManager(), and make sure all LTO
78 // passes are initialized.
79 void LTOCodeGenerator::initializeLTOPasses() {
80 PassRegistry &R = *PassRegistry::getPassRegistry();
82 initializeInternalizePassPass(R);
83 initializeIPSCCPPass(R);
84 initializeGlobalOptPass(R);
85 initializeConstantMergePass(R);
87 initializeInstructionCombiningPassPass(R);
88 initializeSimpleInlinerPass(R);
89 initializePruneEHPass(R);
90 initializeGlobalDCEPass(R);
91 initializeArgPromotionPass(R);
92 initializeJumpThreadingPass(R);
93 initializeSROALegacyPassPass(R);
94 initializeSROA_DTPass(R);
95 initializeSROA_SSAUpPass(R);
96 initializeFunctionAttrsPass(R);
97 initializeGlobalsAAWrapperPassPass(R);
98 initializeLICMPass(R);
99 initializeMergedLoadStoreMotionPass(R);
100 initializeGVNPass(R);
101 initializeMemCpyOptPass(R);
102 initializeDCEPass(R);
103 initializeCFGSimplifyPassPass(R);
106 bool LTOCodeGenerator::addModule(LTOModule *Mod) {
107 assert(&Mod->getModule().getContext() == &Context &&
108 "Expected module in same context");
110 bool ret = IRLinker->linkInModule(Mod->getModule());
112 const std::vector<const char *> &undefs = Mod->getAsmUndefinedRefs();
113 for (int i = 0, e = undefs.size(); i != e; ++i)
114 AsmUndefinedRefs[undefs[i]] = 1;
119 void LTOCodeGenerator::setModule(std::unique_ptr<LTOModule> Mod) {
120 assert(&Mod->getModule().getContext() == &Context &&
121 "Expected module in same context");
123 AsmUndefinedRefs.clear();
125 MergedModule = Mod->takeModule();
126 IRLinker = make_unique<Linker>(*MergedModule);
128 const std::vector<const char*> &Undefs = Mod->getAsmUndefinedRefs();
129 for (int I = 0, E = Undefs.size(); I != E; ++I)
130 AsmUndefinedRefs[Undefs[I]] = 1;
133 void LTOCodeGenerator::setTargetOptions(TargetOptions Options) {
134 this->Options = Options;
137 void LTOCodeGenerator::setDebugInfo(lto_debug_model Debug) {
139 case LTO_DEBUG_MODEL_NONE:
140 EmitDwarfDebugInfo = false;
143 case LTO_DEBUG_MODEL_DWARF:
144 EmitDwarfDebugInfo = true;
147 llvm_unreachable("Unknown debug format!");
150 void LTOCodeGenerator::setOptLevel(unsigned Level) {
154 CGOptLevel = CodeGenOpt::None;
157 CGOptLevel = CodeGenOpt::Less;
160 CGOptLevel = CodeGenOpt::Default;
163 CGOptLevel = CodeGenOpt::Aggressive;
168 bool LTOCodeGenerator::writeMergedModules(const char *Path) {
169 if (!determineTarget())
172 // mark which symbols can not be internalized
173 applyScopeRestrictions();
175 // create output file
177 tool_output_file Out(Path, EC, sys::fs::F_None);
179 std::string ErrMsg = "could not open bitcode file for writing: ";
185 // write bitcode to it
186 WriteBitcodeToFile(MergedModule.get(), Out.os(), ShouldEmbedUselists);
189 if (Out.os().has_error()) {
190 std::string ErrMsg = "could not write bitcode file: ";
193 Out.os().clear_error();
201 bool LTOCodeGenerator::compileOptimizedToFile(const char **Name) {
202 // make unique temp output file to put generated code
203 SmallString<128> Filename;
206 const char *Extension =
207 (FileType == TargetMachine::CGFT_AssemblyFile ? "s" : "o");
210 sys::fs::createTemporaryFile("lto-llvm", Extension, FD, Filename);
212 emitError(EC.message());
216 // generate object file
217 tool_output_file objFile(Filename.c_str(), FD);
219 bool genResult = compileOptimized(&objFile.os());
220 objFile.os().close();
221 if (objFile.os().has_error()) {
222 objFile.os().clear_error();
223 sys::fs::remove(Twine(Filename));
229 sys::fs::remove(Twine(Filename));
233 NativeObjectPath = Filename.c_str();
234 *Name = NativeObjectPath.c_str();
238 std::unique_ptr<MemoryBuffer>
239 LTOCodeGenerator::compileOptimized() {
241 if (!compileOptimizedToFile(&name))
244 // read .o file into memory buffer
245 ErrorOr<std::unique_ptr<MemoryBuffer>> BufferOrErr =
246 MemoryBuffer::getFile(name, -1, false);
247 if (std::error_code EC = BufferOrErr.getError()) {
248 emitError(EC.message());
249 sys::fs::remove(NativeObjectPath);
254 sys::fs::remove(NativeObjectPath);
256 return std::move(*BufferOrErr);
259 bool LTOCodeGenerator::compile_to_file(const char **Name, bool DisableVerify,
261 bool DisableGVNLoadPRE,
262 bool DisableVectorization) {
263 if (!optimize(DisableVerify, DisableInline, DisableGVNLoadPRE,
264 DisableVectorization))
267 return compileOptimizedToFile(Name);
270 std::unique_ptr<MemoryBuffer>
271 LTOCodeGenerator::compile(bool DisableVerify, bool DisableInline,
272 bool DisableGVNLoadPRE, bool DisableVectorization) {
273 if (!optimize(DisableVerify, DisableInline, DisableGVNLoadPRE,
274 DisableVectorization))
277 return compileOptimized();
280 bool LTOCodeGenerator::determineTarget() {
284 std::string TripleStr = MergedModule->getTargetTriple();
285 if (TripleStr.empty()) {
286 TripleStr = sys::getDefaultTargetTriple();
287 MergedModule->setTargetTriple(TripleStr);
289 llvm::Triple Triple(TripleStr);
291 // create target machine from info for merged modules
293 const Target *march = TargetRegistry::lookupTarget(TripleStr, ErrMsg);
299 // Construct LTOModule, hand over ownership of module and target. Use MAttr as
300 // the default set of features.
301 SubtargetFeatures Features(MAttr);
302 Features.getDefaultSubtargetFeatures(Triple);
303 FeatureStr = Features.getString();
304 // Set a default CPU for Darwin triples.
305 if (MCpu.empty() && Triple.isOSDarwin()) {
306 if (Triple.getArch() == llvm::Triple::x86_64)
308 else if (Triple.getArch() == llvm::Triple::x86)
310 else if (Triple.getArch() == llvm::Triple::aarch64)
314 TargetMach.reset(march->createTargetMachine(TripleStr, MCpu, FeatureStr,
316 CodeModel::Default, CGOptLevel));
320 void LTOCodeGenerator::
321 applyRestriction(GlobalValue &GV,
322 ArrayRef<StringRef> Libcalls,
323 std::vector<const char*> &MustPreserveList,
324 SmallPtrSetImpl<GlobalValue*> &AsmUsed,
326 // There are no restrictions to apply to declarations.
327 if (GV.isDeclaration())
330 // There is nothing more restrictive than private linkage.
331 if (GV.hasPrivateLinkage())
334 SmallString<64> Buffer;
335 TargetMach->getNameWithPrefix(Buffer, &GV, Mangler);
337 if (MustPreserveSymbols.count(Buffer))
338 MustPreserveList.push_back(GV.getName().data());
339 if (AsmUndefinedRefs.count(Buffer))
342 // Conservatively append user-supplied runtime library functions to
343 // llvm.compiler.used. These could be internalized and deleted by
344 // optimizations like -globalopt, causing problems when later optimizations
345 // add new library calls (e.g., llvm.memset => memset and printf => puts).
346 // Leave it to the linker to remove any dead code (e.g. with -dead_strip).
347 if (isa<Function>(GV) &&
348 std::binary_search(Libcalls.begin(), Libcalls.end(), GV.getName()))
352 static void findUsedValues(GlobalVariable *LLVMUsed,
353 SmallPtrSetImpl<GlobalValue*> &UsedValues) {
354 if (!LLVMUsed) return;
356 ConstantArray *Inits = cast<ConstantArray>(LLVMUsed->getInitializer());
357 for (unsigned i = 0, e = Inits->getNumOperands(); i != e; ++i)
358 if (GlobalValue *GV =
359 dyn_cast<GlobalValue>(Inits->getOperand(i)->stripPointerCasts()))
360 UsedValues.insert(GV);
363 // Collect names of runtime library functions. User-defined functions with the
364 // same names are added to llvm.compiler.used to prevent them from being
365 // deleted by optimizations.
366 static void accumulateAndSortLibcalls(std::vector<StringRef> &Libcalls,
367 const TargetLibraryInfo& TLI,
369 const TargetMachine &TM) {
370 // TargetLibraryInfo has info on C runtime library calls on the current
372 for (unsigned I = 0, E = static_cast<unsigned>(LibFunc::NumLibFuncs);
374 LibFunc::Func F = static_cast<LibFunc::Func>(I);
376 Libcalls.push_back(TLI.getName(F));
379 SmallPtrSet<const TargetLowering *, 1> TLSet;
381 for (const Function &F : Mod) {
382 const TargetLowering *Lowering =
383 TM.getSubtargetImpl(F)->getTargetLowering();
385 if (Lowering && TLSet.insert(Lowering).second)
386 // TargetLowering has info on library calls that CodeGen expects to be
387 // available, both from the C runtime and compiler-rt.
388 for (unsigned I = 0, E = static_cast<unsigned>(RTLIB::UNKNOWN_LIBCALL);
390 if (const char *Name =
391 Lowering->getLibcallName(static_cast<RTLIB::Libcall>(I)))
392 Libcalls.push_back(Name);
395 array_pod_sort(Libcalls.begin(), Libcalls.end());
396 Libcalls.erase(std::unique(Libcalls.begin(), Libcalls.end()),
400 void LTOCodeGenerator::applyScopeRestrictions() {
401 if (ScopeRestrictionsDone || !ShouldInternalize)
404 // Start off with a verification pass.
405 legacy::PassManager passes;
406 passes.add(createVerifierPass());
408 // mark which symbols can not be internalized
410 std::vector<const char*> MustPreserveList;
411 SmallPtrSet<GlobalValue*, 8> AsmUsed;
412 std::vector<StringRef> Libcalls;
413 TargetLibraryInfoImpl TLII(Triple(TargetMach->getTargetTriple()));
414 TargetLibraryInfo TLI(TLII);
416 accumulateAndSortLibcalls(Libcalls, TLI, *MergedModule, *TargetMach);
418 for (Function &f : *MergedModule)
419 applyRestriction(f, Libcalls, MustPreserveList, AsmUsed, Mangler);
420 for (GlobalVariable &v : MergedModule->globals())
421 applyRestriction(v, Libcalls, MustPreserveList, AsmUsed, Mangler);
422 for (GlobalAlias &a : MergedModule->aliases())
423 applyRestriction(a, Libcalls, MustPreserveList, AsmUsed, Mangler);
425 GlobalVariable *LLVMCompilerUsed =
426 MergedModule->getGlobalVariable("llvm.compiler.used");
427 findUsedValues(LLVMCompilerUsed, AsmUsed);
428 if (LLVMCompilerUsed)
429 LLVMCompilerUsed->eraseFromParent();
431 if (!AsmUsed.empty()) {
432 llvm::Type *i8PTy = llvm::Type::getInt8PtrTy(Context);
433 std::vector<Constant*> asmUsed2;
434 for (auto *GV : AsmUsed) {
435 Constant *c = ConstantExpr::getBitCast(GV, i8PTy);
436 asmUsed2.push_back(c);
439 llvm::ArrayType *ATy = llvm::ArrayType::get(i8PTy, asmUsed2.size());
441 new llvm::GlobalVariable(*MergedModule, ATy, false,
442 llvm::GlobalValue::AppendingLinkage,
443 llvm::ConstantArray::get(ATy, asmUsed2),
444 "llvm.compiler.used");
446 LLVMCompilerUsed->setSection("llvm.metadata");
449 passes.add(createInternalizePass(MustPreserveList));
451 // apply scope restrictions
452 passes.run(*MergedModule);
454 ScopeRestrictionsDone = true;
457 /// Optimize merged modules using various IPO passes
458 bool LTOCodeGenerator::optimize(bool DisableVerify, bool DisableInline,
459 bool DisableGVNLoadPRE,
460 bool DisableVectorization) {
461 if (!this->determineTarget())
464 // Mark which symbols can not be internalized
465 this->applyScopeRestrictions();
467 // Instantiate the pass manager to organize the passes.
468 legacy::PassManager passes;
470 // Add an appropriate DataLayout instance for this module...
471 MergedModule->setDataLayout(TargetMach->createDataLayout());
474 createTargetTransformInfoWrapperPass(TargetMach->getTargetIRAnalysis()));
476 Triple TargetTriple(TargetMach->getTargetTriple());
477 PassManagerBuilder PMB;
478 PMB.DisableGVNLoadPRE = DisableGVNLoadPRE;
479 PMB.LoopVectorize = !DisableVectorization;
480 PMB.SLPVectorize = !DisableVectorization;
482 PMB.Inliner = createFunctionInliningPass();
483 PMB.LibraryInfo = new TargetLibraryInfoImpl(TargetTriple);
484 PMB.OptLevel = OptLevel;
485 PMB.VerifyInput = !DisableVerify;
486 PMB.VerifyOutput = !DisableVerify;
488 PMB.populateLTOPassManager(passes);
490 // Run our queue of passes all at once now, efficiently.
491 passes.run(*MergedModule);
496 bool LTOCodeGenerator::compileOptimized(ArrayRef<raw_pwrite_stream *> Out) {
497 if (!this->determineTarget())
500 legacy::PassManager preCodeGenPasses;
502 // If the bitcode files contain ARC code and were compiled with optimization,
503 // the ObjCARCContractPass must be run, so do it unconditionally here.
504 preCodeGenPasses.add(createObjCARCContractPass());
505 preCodeGenPasses.run(*MergedModule);
507 // Do code generation. We need to preserve the module in case the client calls
508 // writeMergedModules() after compilation, but we only need to allow this at
509 // parallelism level 1. This is achieved by having splitCodeGen return the
510 // original module at parallelism level 1 which we then assign back to
513 splitCodeGen(std::move(MergedModule), Out, MCpu, FeatureStr, Options,
514 RelocModel, CodeModel::Default, CGOptLevel, FileType);
519 /// setCodeGenDebugOptions - Set codegen debugging options to aid in debugging
521 void LTOCodeGenerator::setCodeGenDebugOptions(const char *Options) {
522 for (std::pair<StringRef, StringRef> o = getToken(Options); !o.first.empty();
523 o = getToken(o.second))
524 CodegenOptions.push_back(o.first);
527 void LTOCodeGenerator::parseCodeGenDebugOptions() {
528 // if options were requested, set them
529 if (!CodegenOptions.empty()) {
530 // ParseCommandLineOptions() expects argv[0] to be program name.
531 std::vector<const char *> CodegenArgv(1, "libLLVMLTO");
532 for (std::string &Arg : CodegenOptions)
533 CodegenArgv.push_back(Arg.c_str());
534 cl::ParseCommandLineOptions(CodegenArgv.size(), CodegenArgv.data());
538 void LTOCodeGenerator::DiagnosticHandler(const DiagnosticInfo &DI,
540 ((LTOCodeGenerator *)Context)->DiagnosticHandler2(DI);
543 void LTOCodeGenerator::DiagnosticHandler2(const DiagnosticInfo &DI) {
544 // Map the LLVM internal diagnostic severity to the LTO diagnostic severity.
545 lto_codegen_diagnostic_severity_t Severity;
546 switch (DI.getSeverity()) {
548 Severity = LTO_DS_ERROR;
551 Severity = LTO_DS_WARNING;
554 Severity = LTO_DS_REMARK;
557 Severity = LTO_DS_NOTE;
560 // Create the string that will be reported to the external diagnostic handler.
561 std::string MsgStorage;
562 raw_string_ostream Stream(MsgStorage);
563 DiagnosticPrinterRawOStream DP(Stream);
567 // If this method has been called it means someone has set up an external
568 // diagnostic handler. Assert on that.
569 assert(DiagHandler && "Invalid diagnostic handler");
570 (*DiagHandler)(Severity, MsgStorage.c_str(), DiagContext);
574 LTOCodeGenerator::setDiagnosticHandler(lto_diagnostic_handler_t DiagHandler,
576 this->DiagHandler = DiagHandler;
577 this->DiagContext = Ctxt;
579 return Context.setDiagnosticHandler(nullptr, nullptr);
580 // Register the LTOCodeGenerator stub in the LLVMContext to forward the
581 // diagnostic to the external DiagHandler.
582 Context.setDiagnosticHandler(LTOCodeGenerator::DiagnosticHandler, this,
583 /* RespectFilters */ true);
587 class LTODiagnosticInfo : public DiagnosticInfo {
590 LTODiagnosticInfo(const Twine &DiagMsg, DiagnosticSeverity Severity=DS_Error)
591 : DiagnosticInfo(DK_Linker, Severity), Msg(DiagMsg) {}
592 void print(DiagnosticPrinter &DP) const override { DP << Msg; }
596 void LTOCodeGenerator::emitError(const std::string &ErrMsg) {
598 (*DiagHandler)(LTO_DS_ERROR, ErrMsg.c_str(), DiagContext);
600 Context.diagnose(LTODiagnosticInfo(ErrMsg));