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/Bitcode/ReaderWriter.h"
20 #include "llvm/CodeGen/RuntimeLibcalls.h"
21 #include "llvm/Config/config.h"
22 #include "llvm/IR/Constants.h"
23 #include "llvm/IR/DataLayout.h"
24 #include "llvm/IR/DerivedTypes.h"
25 #include "llvm/IR/DiagnosticInfo.h"
26 #include "llvm/IR/DiagnosticPrinter.h"
27 #include "llvm/IR/LLVMContext.h"
28 #include "llvm/IR/Mangler.h"
29 #include "llvm/IR/Module.h"
30 #include "llvm/IR/Verifier.h"
31 #include "llvm/InitializePasses.h"
32 #include "llvm/LTO/LTOModule.h"
33 #include "llvm/Linker/Linker.h"
34 #include "llvm/MC/MCAsmInfo.h"
35 #include "llvm/MC/MCContext.h"
36 #include "llvm/MC/SubtargetFeature.h"
37 #include "llvm/PassManager.h"
38 #include "llvm/Support/CommandLine.h"
39 #include "llvm/Support/FileSystem.h"
40 #include "llvm/Support/FormattedStream.h"
41 #include "llvm/Support/Host.h"
42 #include "llvm/Support/MemoryBuffer.h"
43 #include "llvm/Support/Signals.h"
44 #include "llvm/Support/TargetRegistry.h"
45 #include "llvm/Support/TargetSelect.h"
46 #include "llvm/Support/ToolOutputFile.h"
47 #include "llvm/Support/raw_ostream.h"
48 #include "llvm/Target/TargetLowering.h"
49 #include "llvm/Target/TargetOptions.h"
50 #include "llvm/Target/TargetRegisterInfo.h"
51 #include "llvm/Target/TargetSubtargetInfo.h"
52 #include "llvm/Transforms/IPO.h"
53 #include "llvm/Transforms/IPO/PassManagerBuilder.h"
54 #include "llvm/Transforms/ObjCARC.h"
55 #include <system_error>
58 const char* LTOCodeGenerator::getVersionString() {
59 #ifdef LLVM_VERSION_INFO
60 return PACKAGE_NAME " version " PACKAGE_VERSION ", " LLVM_VERSION_INFO;
62 return PACKAGE_NAME " version " PACKAGE_VERSION;
66 LTOCodeGenerator::LTOCodeGenerator()
67 : Context(getGlobalContext()), IRLinker(new Module("ld-temp.o", Context)) {
71 LTOCodeGenerator::LTOCodeGenerator(std::unique_ptr<LLVMContext> Context)
72 : OwnedContext(std::move(Context)), Context(*OwnedContext),
73 IRLinker(new Module("ld-temp.o", *OwnedContext)) {
77 void LTOCodeGenerator::initialize() {
79 EmitDwarfDebugInfo = false;
80 ScopeRestrictionsDone = false;
81 CodeModel = LTO_CODEGEN_PIC_MODEL_DEFAULT;
82 DiagHandler = nullptr;
83 DiagContext = nullptr;
85 initializeLTOPasses();
88 LTOCodeGenerator::~LTOCodeGenerator() {
92 IRLinker.deleteModule();
94 for (std::vector<char *>::iterator I = CodegenOptions.begin(),
95 E = CodegenOptions.end();
100 // Initialize LTO passes. Please keep this funciton in sync with
101 // PassManagerBuilder::populateLTOPassManager(), and make sure all LTO
102 // passes are initialized.
103 void LTOCodeGenerator::initializeLTOPasses() {
104 PassRegistry &R = *PassRegistry::getPassRegistry();
106 initializeInternalizePassPass(R);
107 initializeIPSCCPPass(R);
108 initializeGlobalOptPass(R);
109 initializeConstantMergePass(R);
110 initializeDAHPass(R);
111 initializeInstructionCombiningPassPass(R);
112 initializeSimpleInlinerPass(R);
113 initializePruneEHPass(R);
114 initializeGlobalDCEPass(R);
115 initializeArgPromotionPass(R);
116 initializeJumpThreadingPass(R);
117 initializeSROAPass(R);
118 initializeSROA_DTPass(R);
119 initializeSROA_SSAUpPass(R);
120 initializeFunctionAttrsPass(R);
121 initializeGlobalsModRefPass(R);
122 initializeLICMPass(R);
123 initializeMergedLoadStoreMotionPass(R);
124 initializeGVNPass(R);
125 initializeMemCpyOptPass(R);
126 initializeDCEPass(R);
127 initializeCFGSimplifyPassPass(R);
130 bool LTOCodeGenerator::addModule(LTOModule *mod) {
131 assert(&mod->getModule().getContext() == &Context &&
132 "Expected module in same context");
134 bool ret = IRLinker.linkInModule(&mod->getModule());
136 const std::vector<const char*> &undefs = mod->getAsmUndefinedRefs();
137 for (int i = 0, e = undefs.size(); i != e; ++i)
138 AsmUndefinedRefs[undefs[i]] = 1;
143 void LTOCodeGenerator::setTargetOptions(TargetOptions options) {
147 void LTOCodeGenerator::setDebugInfo(lto_debug_model debug) {
149 case LTO_DEBUG_MODEL_NONE:
150 EmitDwarfDebugInfo = false;
153 case LTO_DEBUG_MODEL_DWARF:
154 EmitDwarfDebugInfo = true;
157 llvm_unreachable("Unknown debug format!");
160 void LTOCodeGenerator::setCodePICModel(lto_codegen_model model) {
162 case LTO_CODEGEN_PIC_MODEL_STATIC:
163 case LTO_CODEGEN_PIC_MODEL_DYNAMIC:
164 case LTO_CODEGEN_PIC_MODEL_DYNAMIC_NO_PIC:
165 case LTO_CODEGEN_PIC_MODEL_DEFAULT:
169 llvm_unreachable("Unknown PIC model!");
172 bool LTOCodeGenerator::writeMergedModules(const char *path,
173 std::string &errMsg) {
174 if (!determineTarget(errMsg))
177 // mark which symbols can not be internalized
178 applyScopeRestrictions();
180 // create output file
182 tool_output_file Out(path, EC, sys::fs::F_None);
184 errMsg = "could not open bitcode file for writing: ";
189 // write bitcode to it
190 WriteBitcodeToFile(IRLinker.getModule(), Out.os());
193 if (Out.os().has_error()) {
194 errMsg = "could not write bitcode file: ";
196 Out.os().clear_error();
204 bool LTOCodeGenerator::compile_to_file(const char** name,
207 bool disableGVNLoadPRE,
208 bool disableVectorization,
209 std::string& errMsg) {
210 // make unique temp .o file to put generated object file
211 SmallString<128> Filename;
214 sys::fs::createTemporaryFile("lto-llvm", "o", FD, Filename);
216 errMsg = EC.message();
220 // generate object file
221 tool_output_file objFile(Filename.c_str(), FD);
224 generateObjectFile(objFile.os(), disableOpt, disableInline,
225 disableGVNLoadPRE, disableVectorization, errMsg);
226 objFile.os().close();
227 if (objFile.os().has_error()) {
228 objFile.os().clear_error();
229 sys::fs::remove(Twine(Filename));
235 sys::fs::remove(Twine(Filename));
239 NativeObjectPath = Filename.c_str();
240 *name = NativeObjectPath.c_str();
244 const void* LTOCodeGenerator::compile(size_t* length,
247 bool disableGVNLoadPRE,
248 bool disableVectorization,
249 std::string& errMsg) {
251 if (!compile_to_file(&name, disableOpt, disableInline, disableGVNLoadPRE,
252 disableVectorization, errMsg))
255 // read .o file into memory buffer
256 ErrorOr<std::unique_ptr<MemoryBuffer>> BufferOrErr =
257 MemoryBuffer::getFile(name, -1, false);
258 if (std::error_code EC = BufferOrErr.getError()) {
259 errMsg = EC.message();
260 sys::fs::remove(NativeObjectPath);
263 NativeObjectFile = std::move(*BufferOrErr);
266 sys::fs::remove(NativeObjectPath);
268 // return buffer, unless error
269 if (!NativeObjectFile)
271 *length = NativeObjectFile->getBufferSize();
272 return NativeObjectFile->getBufferStart();
275 bool LTOCodeGenerator::determineTarget(std::string &errMsg) {
279 std::string TripleStr = IRLinker.getModule()->getTargetTriple();
280 if (TripleStr.empty())
281 TripleStr = sys::getDefaultTargetTriple();
282 llvm::Triple Triple(TripleStr);
284 // create target machine from info for merged modules
285 const Target *march = TargetRegistry::lookupTarget(TripleStr, errMsg);
289 // The relocation model is actually a static member of TargetMachine and
290 // needs to be set before the TargetMachine is instantiated.
291 Reloc::Model RelocModel = Reloc::Default;
293 case LTO_CODEGEN_PIC_MODEL_STATIC:
294 RelocModel = Reloc::Static;
296 case LTO_CODEGEN_PIC_MODEL_DYNAMIC:
297 RelocModel = Reloc::PIC_;
299 case LTO_CODEGEN_PIC_MODEL_DYNAMIC_NO_PIC:
300 RelocModel = Reloc::DynamicNoPIC;
302 case LTO_CODEGEN_PIC_MODEL_DEFAULT:
303 // RelocModel is already the default, so leave it that way.
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 std::string 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 = march->createTargetMachine(TripleStr, MCpu, FeatureStr, Options,
323 RelocModel, CodeModel::Default,
324 CodeGenOpt::Aggressive);
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)
411 Module *mergedModule = IRLinker.getModule();
413 // Start off with a verification pass.
415 passes.add(createVerifierPass());
416 passes.add(createDebugInfoVerifierPass());
418 // mark which symbols can not be internalized
419 Mangler Mangler(TargetMach->getDataLayout());
420 std::vector<const char*> MustPreserveList;
421 SmallPtrSet<GlobalValue*, 8> AsmUsed;
422 std::vector<StringRef> Libcalls;
423 TargetLibraryInfoImpl TLII(Triple(TargetMach->getTargetTriple()));
424 TargetLibraryInfo TLI(TLII);
426 accumulateAndSortLibcalls(Libcalls, TLI, *mergedModule, *TargetMach);
428 for (Module::iterator f = mergedModule->begin(),
429 e = mergedModule->end(); f != e; ++f)
430 applyRestriction(*f, Libcalls, MustPreserveList, AsmUsed, Mangler);
431 for (Module::global_iterator v = mergedModule->global_begin(),
432 e = mergedModule->global_end(); v != e; ++v)
433 applyRestriction(*v, Libcalls, MustPreserveList, AsmUsed, Mangler);
434 for (Module::alias_iterator a = mergedModule->alias_begin(),
435 e = mergedModule->alias_end(); a != e; ++a)
436 applyRestriction(*a, Libcalls, MustPreserveList, AsmUsed, Mangler);
438 GlobalVariable *LLVMCompilerUsed =
439 mergedModule->getGlobalVariable("llvm.compiler.used");
440 findUsedValues(LLVMCompilerUsed, AsmUsed);
441 if (LLVMCompilerUsed)
442 LLVMCompilerUsed->eraseFromParent();
444 if (!AsmUsed.empty()) {
445 llvm::Type *i8PTy = llvm::Type::getInt8PtrTy(Context);
446 std::vector<Constant*> asmUsed2;
447 for (auto *GV : AsmUsed) {
448 Constant *c = ConstantExpr::getBitCast(GV, i8PTy);
449 asmUsed2.push_back(c);
452 llvm::ArrayType *ATy = llvm::ArrayType::get(i8PTy, asmUsed2.size());
454 new llvm::GlobalVariable(*mergedModule, ATy, false,
455 llvm::GlobalValue::AppendingLinkage,
456 llvm::ConstantArray::get(ATy, asmUsed2),
457 "llvm.compiler.used");
459 LLVMCompilerUsed->setSection("llvm.metadata");
462 passes.add(createInternalizePass(MustPreserveList));
464 // apply scope restrictions
465 passes.run(*mergedModule);
467 ScopeRestrictionsDone = true;
470 /// Optimize merged modules using various IPO passes
471 bool LTOCodeGenerator::generateObjectFile(raw_ostream &out,
474 bool DisableGVNLoadPRE,
475 bool DisableVectorization,
476 std::string &errMsg) {
477 if (!this->determineTarget(errMsg))
480 Module *mergedModule = IRLinker.getModule();
482 // Mark which symbols can not be internalized
483 this->applyScopeRestrictions();
485 // Instantiate the pass manager to organize the passes.
488 // Add an appropriate DataLayout instance for this module...
489 mergedModule->setDataLayout(TargetMach->getDataLayout());
491 Triple TargetTriple(TargetMach->getTargetTriple());
492 PassManagerBuilder PMB;
493 PMB.DisableGVNLoadPRE = DisableGVNLoadPRE;
494 PMB.LoopVectorize = !DisableVectorization;
495 PMB.SLPVectorize = !DisableVectorization;
497 PMB.Inliner = createFunctionInliningPass();
498 PMB.LibraryInfo = new TargetLibraryInfoImpl(TargetTriple);
501 PMB.VerifyInput = true;
502 PMB.VerifyOutput = true;
504 PMB.populateLTOPassManager(passes, TargetMach);
506 PassManager codeGenPasses;
508 codeGenPasses.add(new DataLayoutPass());
510 formatted_raw_ostream Out(out);
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 codeGenPasses.add(createObjCARCContractPass());
516 if (TargetMach->addPassesToEmitFile(codeGenPasses, Out,
517 TargetMachine::CGFT_ObjectFile)) {
518 errMsg = "target file type not supported";
522 // Run our queue of passes all at once now, efficiently.
523 passes.run(*mergedModule);
525 // Run the code generator, and write assembly file
526 codeGenPasses.run(*mergedModule);
531 /// setCodeGenDebugOptions - Set codegen debugging options to aid in debugging
533 void LTOCodeGenerator::setCodeGenDebugOptions(const char *options) {
534 for (std::pair<StringRef, StringRef> o = getToken(options);
535 !o.first.empty(); o = getToken(o.second)) {
536 // ParseCommandLineOptions() expects argv[0] to be program name. Lazily add
538 if (CodegenOptions.empty())
539 CodegenOptions.push_back(strdup("libLLVMLTO"));
540 CodegenOptions.push_back(strdup(o.first.str().c_str()));
544 void LTOCodeGenerator::parseCodeGenDebugOptions() {
545 // if options were requested, set them
546 if (!CodegenOptions.empty())
547 cl::ParseCommandLineOptions(CodegenOptions.size(),
548 const_cast<char **>(&CodegenOptions[0]));
551 void LTOCodeGenerator::DiagnosticHandler(const DiagnosticInfo &DI,
553 ((LTOCodeGenerator *)Context)->DiagnosticHandler2(DI);
556 void LTOCodeGenerator::DiagnosticHandler2(const DiagnosticInfo &DI) {
557 // Map the LLVM internal diagnostic severity to the LTO diagnostic severity.
558 lto_codegen_diagnostic_severity_t Severity;
559 switch (DI.getSeverity()) {
561 Severity = LTO_DS_ERROR;
564 Severity = LTO_DS_WARNING;
567 Severity = LTO_DS_REMARK;
570 Severity = LTO_DS_NOTE;
573 // Create the string that will be reported to the external diagnostic handler.
574 std::string MsgStorage;
575 raw_string_ostream Stream(MsgStorage);
576 DiagnosticPrinterRawOStream DP(Stream);
580 // If this method has been called it means someone has set up an external
581 // diagnostic handler. Assert on that.
582 assert(DiagHandler && "Invalid diagnostic handler");
583 (*DiagHandler)(Severity, MsgStorage.c_str(), DiagContext);
587 LTOCodeGenerator::setDiagnosticHandler(lto_diagnostic_handler_t DiagHandler,
589 this->DiagHandler = DiagHandler;
590 this->DiagContext = Ctxt;
592 return Context.setDiagnosticHandler(nullptr, nullptr);
593 // Register the LTOCodeGenerator stub in the LLVMContext to forward the
594 // diagnostic to the external DiagHandler.
595 Context.setDiagnosticHandler(LTOCodeGenerator::DiagnosticHandler, this,
596 /* RespectFilters */ true);