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::compile_to_file(const char** name,
208 bool disableGVNLoadPRE,
209 bool disableVectorization,
210 std::string& errMsg) {
211 // make unique temp .o file to put generated object file
212 SmallString<128> Filename;
215 sys::fs::createTemporaryFile("lto-llvm", "o", FD, Filename);
217 errMsg = EC.message();
221 // generate object file
222 tool_output_file objFile(Filename.c_str(), FD);
225 generateObjectFile(objFile.os(), disableOpt, disableInline,
226 disableGVNLoadPRE, disableVectorization, errMsg);
227 objFile.os().close();
228 if (objFile.os().has_error()) {
229 objFile.os().clear_error();
230 sys::fs::remove(Twine(Filename));
236 sys::fs::remove(Twine(Filename));
240 NativeObjectPath = Filename.c_str();
241 *name = NativeObjectPath.c_str();
245 const void* LTOCodeGenerator::compile(size_t* length,
248 bool disableGVNLoadPRE,
249 bool disableVectorization,
250 std::string& errMsg) {
252 if (!compile_to_file(&name, disableOpt, disableInline, disableGVNLoadPRE,
253 disableVectorization, errMsg))
256 // read .o file into memory buffer
257 ErrorOr<std::unique_ptr<MemoryBuffer>> BufferOrErr =
258 MemoryBuffer::getFile(name, -1, false);
259 if (std::error_code EC = BufferOrErr.getError()) {
260 errMsg = EC.message();
261 sys::fs::remove(NativeObjectPath);
264 NativeObjectFile = std::move(*BufferOrErr);
267 sys::fs::remove(NativeObjectPath);
269 // return buffer, unless error
270 if (!NativeObjectFile)
272 *length = NativeObjectFile->getBufferSize();
273 return NativeObjectFile->getBufferStart();
276 bool LTOCodeGenerator::determineTarget(std::string &errMsg) {
280 std::string TripleStr = IRLinker.getModule()->getTargetTriple();
281 if (TripleStr.empty())
282 TripleStr = sys::getDefaultTargetTriple();
283 llvm::Triple Triple(TripleStr);
285 // create target machine from info for merged modules
286 const Target *march = TargetRegistry::lookupTarget(TripleStr, errMsg);
290 // The relocation model is actually a static member of TargetMachine and
291 // needs to be set before the TargetMachine is instantiated.
292 Reloc::Model RelocModel = Reloc::Default;
294 case LTO_CODEGEN_PIC_MODEL_STATIC:
295 RelocModel = Reloc::Static;
297 case LTO_CODEGEN_PIC_MODEL_DYNAMIC:
298 RelocModel = Reloc::PIC_;
300 case LTO_CODEGEN_PIC_MODEL_DYNAMIC_NO_PIC:
301 RelocModel = Reloc::DynamicNoPIC;
303 case LTO_CODEGEN_PIC_MODEL_DEFAULT:
304 // RelocModel is already the default, so leave it that way.
308 // Construct LTOModule, hand over ownership of module and target. Use MAttr as
309 // the default set of features.
310 SubtargetFeatures Features(MAttr);
311 Features.getDefaultSubtargetFeatures(Triple);
312 std::string FeatureStr = Features.getString();
313 // Set a default CPU for Darwin triples.
314 if (MCpu.empty() && Triple.isOSDarwin()) {
315 if (Triple.getArch() == llvm::Triple::x86_64)
317 else if (Triple.getArch() == llvm::Triple::x86)
319 else if (Triple.getArch() == llvm::Triple::aarch64)
323 TargetMach = march->createTargetMachine(TripleStr, MCpu, FeatureStr, Options,
324 RelocModel, CodeModel::Default,
325 CodeGenOpt::Aggressive);
329 void LTOCodeGenerator::
330 applyRestriction(GlobalValue &GV,
331 ArrayRef<StringRef> Libcalls,
332 std::vector<const char*> &MustPreserveList,
333 SmallPtrSetImpl<GlobalValue*> &AsmUsed,
335 // There are no restrictions to apply to declarations.
336 if (GV.isDeclaration())
339 // There is nothing more restrictive than private linkage.
340 if (GV.hasPrivateLinkage())
343 SmallString<64> Buffer;
344 TargetMach->getNameWithPrefix(Buffer, &GV, Mangler);
346 if (MustPreserveSymbols.count(Buffer))
347 MustPreserveList.push_back(GV.getName().data());
348 if (AsmUndefinedRefs.count(Buffer))
351 // Conservatively append user-supplied runtime library functions to
352 // llvm.compiler.used. These could be internalized and deleted by
353 // optimizations like -globalopt, causing problems when later optimizations
354 // add new library calls (e.g., llvm.memset => memset and printf => puts).
355 // Leave it to the linker to remove any dead code (e.g. with -dead_strip).
356 if (isa<Function>(GV) &&
357 std::binary_search(Libcalls.begin(), Libcalls.end(), GV.getName()))
361 static void findUsedValues(GlobalVariable *LLVMUsed,
362 SmallPtrSetImpl<GlobalValue*> &UsedValues) {
363 if (!LLVMUsed) return;
365 ConstantArray *Inits = cast<ConstantArray>(LLVMUsed->getInitializer());
366 for (unsigned i = 0, e = Inits->getNumOperands(); i != e; ++i)
367 if (GlobalValue *GV =
368 dyn_cast<GlobalValue>(Inits->getOperand(i)->stripPointerCasts()))
369 UsedValues.insert(GV);
372 // Collect names of runtime library functions. User-defined functions with the
373 // same names are added to llvm.compiler.used to prevent them from being
374 // deleted by optimizations.
375 static void accumulateAndSortLibcalls(std::vector<StringRef> &Libcalls,
376 const TargetLibraryInfo& TLI,
378 const TargetMachine &TM) {
379 // TargetLibraryInfo has info on C runtime library calls on the current
381 for (unsigned I = 0, E = static_cast<unsigned>(LibFunc::NumLibFuncs);
383 LibFunc::Func F = static_cast<LibFunc::Func>(I);
385 Libcalls.push_back(TLI.getName(F));
388 SmallPtrSet<const TargetLowering *, 1> TLSet;
390 for (const Function &F : Mod) {
391 const TargetLowering *Lowering =
392 TM.getSubtargetImpl(F)->getTargetLowering();
394 if (Lowering && TLSet.insert(Lowering).second)
395 // TargetLowering has info on library calls that CodeGen expects to be
396 // available, both from the C runtime and compiler-rt.
397 for (unsigned I = 0, E = static_cast<unsigned>(RTLIB::UNKNOWN_LIBCALL);
399 if (const char *Name =
400 Lowering->getLibcallName(static_cast<RTLIB::Libcall>(I)))
401 Libcalls.push_back(Name);
404 array_pod_sort(Libcalls.begin(), Libcalls.end());
405 Libcalls.erase(std::unique(Libcalls.begin(), Libcalls.end()),
409 void LTOCodeGenerator::applyScopeRestrictions() {
410 if (ScopeRestrictionsDone)
412 Module *mergedModule = IRLinker.getModule();
414 // Start off with a verification pass.
416 passes.add(createVerifierPass());
417 passes.add(createDebugInfoVerifierPass());
419 // mark which symbols can not be internalized
420 Mangler Mangler(TargetMach->getDataLayout());
421 std::vector<const char*> MustPreserveList;
422 SmallPtrSet<GlobalValue*, 8> AsmUsed;
423 std::vector<StringRef> Libcalls;
424 TargetLibraryInfoImpl TLII(Triple(TargetMach->getTargetTriple()));
425 TargetLibraryInfo TLI(TLII);
427 accumulateAndSortLibcalls(Libcalls, TLI, *mergedModule, *TargetMach);
429 for (Module::iterator f = mergedModule->begin(),
430 e = mergedModule->end(); f != e; ++f)
431 applyRestriction(*f, Libcalls, MustPreserveList, AsmUsed, Mangler);
432 for (Module::global_iterator v = mergedModule->global_begin(),
433 e = mergedModule->global_end(); v != e; ++v)
434 applyRestriction(*v, Libcalls, MustPreserveList, AsmUsed, Mangler);
435 for (Module::alias_iterator a = mergedModule->alias_begin(),
436 e = mergedModule->alias_end(); a != e; ++a)
437 applyRestriction(*a, Libcalls, MustPreserveList, AsmUsed, Mangler);
439 GlobalVariable *LLVMCompilerUsed =
440 mergedModule->getGlobalVariable("llvm.compiler.used");
441 findUsedValues(LLVMCompilerUsed, AsmUsed);
442 if (LLVMCompilerUsed)
443 LLVMCompilerUsed->eraseFromParent();
445 if (!AsmUsed.empty()) {
446 llvm::Type *i8PTy = llvm::Type::getInt8PtrTy(Context);
447 std::vector<Constant*> asmUsed2;
448 for (auto *GV : AsmUsed) {
449 Constant *c = ConstantExpr::getBitCast(GV, i8PTy);
450 asmUsed2.push_back(c);
453 llvm::ArrayType *ATy = llvm::ArrayType::get(i8PTy, asmUsed2.size());
455 new llvm::GlobalVariable(*mergedModule, ATy, false,
456 llvm::GlobalValue::AppendingLinkage,
457 llvm::ConstantArray::get(ATy, asmUsed2),
458 "llvm.compiler.used");
460 LLVMCompilerUsed->setSection("llvm.metadata");
463 passes.add(createInternalizePass(MustPreserveList));
465 // apply scope restrictions
466 passes.run(*mergedModule);
468 ScopeRestrictionsDone = true;
471 /// Optimize merged modules using various IPO passes
472 bool LTOCodeGenerator::generateObjectFile(raw_ostream &out,
475 bool DisableGVNLoadPRE,
476 bool DisableVectorization,
477 std::string &errMsg) {
478 if (!this->determineTarget(errMsg))
481 Module *mergedModule = IRLinker.getModule();
483 // Mark which symbols can not be internalized
484 this->applyScopeRestrictions();
486 // Instantiate the pass manager to organize the passes.
489 // Add an appropriate DataLayout instance for this module...
490 mergedModule->setDataLayout(TargetMach->getDataLayout());
492 passes.add(new DataLayoutPass());
493 passes.add(createTargetTransformInfoWrapperPass(TargetMach->getTTI()));
495 Triple TargetTriple(TargetMach->getTargetTriple());
496 PassManagerBuilder PMB;
497 PMB.DisableGVNLoadPRE = DisableGVNLoadPRE;
498 PMB.LoopVectorize = !DisableVectorization;
499 PMB.SLPVectorize = !DisableVectorization;
501 PMB.Inliner = createFunctionInliningPass();
502 PMB.LibraryInfo = new TargetLibraryInfoImpl(TargetTriple);
505 PMB.VerifyInput = true;
506 PMB.VerifyOutput = true;
508 PMB.populateLTOPassManager(passes);
510 PassManager codeGenPasses;
512 codeGenPasses.add(new DataLayoutPass());
514 formatted_raw_ostream Out(out);
516 // If the bitcode files contain ARC code and were compiled with optimization,
517 // the ObjCARCContractPass must be run, so do it unconditionally here.
518 codeGenPasses.add(createObjCARCContractPass());
520 if (TargetMach->addPassesToEmitFile(codeGenPasses, Out,
521 TargetMachine::CGFT_ObjectFile)) {
522 errMsg = "target file type not supported";
526 // Run our queue of passes all at once now, efficiently.
527 passes.run(*mergedModule);
529 // Run the code generator, and write assembly file
530 codeGenPasses.run(*mergedModule);
535 /// setCodeGenDebugOptions - Set codegen debugging options to aid in debugging
537 void LTOCodeGenerator::setCodeGenDebugOptions(const char *options) {
538 for (std::pair<StringRef, StringRef> o = getToken(options);
539 !o.first.empty(); o = getToken(o.second)) {
540 // ParseCommandLineOptions() expects argv[0] to be program name. Lazily add
542 if (CodegenOptions.empty())
543 CodegenOptions.push_back(strdup("libLLVMLTO"));
544 CodegenOptions.push_back(strdup(o.first.str().c_str()));
548 void LTOCodeGenerator::parseCodeGenDebugOptions() {
549 // if options were requested, set them
550 if (!CodegenOptions.empty())
551 cl::ParseCommandLineOptions(CodegenOptions.size(),
552 const_cast<char **>(&CodegenOptions[0]));
555 void LTOCodeGenerator::DiagnosticHandler(const DiagnosticInfo &DI,
557 ((LTOCodeGenerator *)Context)->DiagnosticHandler2(DI);
560 void LTOCodeGenerator::DiagnosticHandler2(const DiagnosticInfo &DI) {
561 // Map the LLVM internal diagnostic severity to the LTO diagnostic severity.
562 lto_codegen_diagnostic_severity_t Severity;
563 switch (DI.getSeverity()) {
565 Severity = LTO_DS_ERROR;
568 Severity = LTO_DS_WARNING;
571 Severity = LTO_DS_REMARK;
574 Severity = LTO_DS_NOTE;
577 // Create the string that will be reported to the external diagnostic handler.
578 std::string MsgStorage;
579 raw_string_ostream Stream(MsgStorage);
580 DiagnosticPrinterRawOStream DP(Stream);
584 // If this method has been called it means someone has set up an external
585 // diagnostic handler. Assert on that.
586 assert(DiagHandler && "Invalid diagnostic handler");
587 (*DiagHandler)(Severity, MsgStorage.c_str(), DiagContext);
591 LTOCodeGenerator::setDiagnosticHandler(lto_diagnostic_handler_t DiagHandler,
593 this->DiagHandler = DiagHandler;
594 this->DiagContext = Ctxt;
596 return Context.setDiagnosticHandler(nullptr, nullptr);
597 // Register the LTOCodeGenerator stub in the LLVMContext to forward the
598 // diagnostic to the external DiagHandler.
599 Context.setDiagnosticHandler(LTOCodeGenerator::DiagnosticHandler, this,
600 /* RespectFilters */ true);