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/LTO/LTOModule.h"
17 #include "llvm/ADT/StringExtras.h"
18 #include "llvm/Analysis/Passes.h"
19 #include "llvm/Analysis/Verifier.h"
20 #include "llvm/Bitcode/ReaderWriter.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/LLVMContext.h"
26 #include "llvm/IR/Module.h"
27 #include "llvm/InitializePasses.h"
28 #include "llvm/Linker.h"
29 #include "llvm/MC/MCAsmInfo.h"
30 #include "llvm/MC/MCContext.h"
31 #include "llvm/MC/SubtargetFeature.h"
32 #include "llvm/PassManager.h"
33 #include "llvm/Support/CommandLine.h"
34 #include "llvm/Support/FileSystem.h"
35 #include "llvm/Support/FormattedStream.h"
36 #include "llvm/Support/Host.h"
37 #include "llvm/Support/MemoryBuffer.h"
38 #include "llvm/Support/Signals.h"
39 #include "llvm/Support/TargetRegistry.h"
40 #include "llvm/Support/TargetSelect.h"
41 #include "llvm/Support/ToolOutputFile.h"
42 #include "llvm/Support/system_error.h"
43 #include "llvm/Target/TargetOptions.h"
44 #include "llvm/Target/TargetRegisterInfo.h"
45 #include "llvm/Target/Mangler.h"
46 #include "llvm/Transforms/IPO.h"
47 #include "llvm/Transforms/IPO/PassManagerBuilder.h"
48 #include "llvm/Transforms/ObjCARC.h"
51 const char* LTOCodeGenerator::getVersionString() {
52 #ifdef LLVM_VERSION_INFO
53 return PACKAGE_NAME " version " PACKAGE_VERSION ", " LLVM_VERSION_INFO;
55 return PACKAGE_NAME " version " PACKAGE_VERSION;
59 LTOCodeGenerator::LTOCodeGenerator()
60 : Context(getGlobalContext()), Linker(new Module("ld-temp.o", Context)),
61 TargetMach(NULL), EmitDwarfDebugInfo(false), ScopeRestrictionsDone(false),
62 CodeModel(LTO_CODEGEN_PIC_MODEL_DYNAMIC), NativeObjectFile(NULL) {
63 initializeLTOPasses();
66 LTOCodeGenerator::~LTOCodeGenerator() {
68 delete NativeObjectFile;
70 NativeObjectFile = NULL;
72 Linker.deleteModule();
74 for (std::vector<char *>::iterator I = CodegenOptions.begin(),
75 E = CodegenOptions.end();
80 // Initialize LTO passes. Please keep this funciton in sync with
81 // PassManagerBuilder::populateLTOPassManager(), and make sure all LTO
82 // passes are initialized.
84 void LTOCodeGenerator::initializeLTOPasses() {
85 PassRegistry &R = *PassRegistry::getPassRegistry();
87 initializeInternalizePassPass(R);
88 initializeIPSCCPPass(R);
89 initializeGlobalOptPass(R);
90 initializeConstantMergePass(R);
92 initializeInstCombinerPass(R);
93 initializeSimpleInlinerPass(R);
94 initializePruneEHPass(R);
95 initializeGlobalDCEPass(R);
96 initializeArgPromotionPass(R);
97 initializeJumpThreadingPass(R);
98 initializeSROAPass(R);
99 initializeSROA_DTPass(R);
100 initializeSROA_SSAUpPass(R);
101 initializeFunctionAttrsPass(R);
102 initializeGlobalsModRefPass(R);
103 initializeLICMPass(R);
104 initializeGVNPass(R);
105 initializeMemCpyOptPass(R);
106 initializeDCEPass(R);
107 initializeCFGSimplifyPassPass(R);
110 bool LTOCodeGenerator::addModule(LTOModule* mod, std::string& errMsg) {
111 bool ret = Linker.linkInModule(mod->getLLVVMModule(), &errMsg);
113 const std::vector<const char*> &undefs = mod->getAsmUndefinedRefs();
114 for (int i = 0, e = undefs.size(); i != e; ++i)
115 AsmUndefinedRefs[undefs[i]] = 1;
120 void LTOCodeGenerator::setTargetOptions(TargetOptions options) {
121 Options.LessPreciseFPMADOption = options.LessPreciseFPMADOption;
122 Options.NoFramePointerElim = options.NoFramePointerElim;
123 Options.AllowFPOpFusion = options.AllowFPOpFusion;
124 Options.UnsafeFPMath = options.UnsafeFPMath;
125 Options.NoInfsFPMath = options.NoInfsFPMath;
126 Options.NoNaNsFPMath = options.NoNaNsFPMath;
127 Options.HonorSignDependentRoundingFPMathOption =
128 options.HonorSignDependentRoundingFPMathOption;
129 Options.UseSoftFloat = options.UseSoftFloat;
130 Options.FloatABIType = options.FloatABIType;
131 Options.NoZerosInBSS = options.NoZerosInBSS;
132 Options.GuaranteedTailCallOpt = options.GuaranteedTailCallOpt;
133 Options.DisableTailCalls = options.DisableTailCalls;
134 Options.StackAlignmentOverride = options.StackAlignmentOverride;
135 Options.TrapFuncName = options.TrapFuncName;
136 Options.PositionIndependentExecutable = options.PositionIndependentExecutable;
137 Options.EnableSegmentedStacks = options.EnableSegmentedStacks;
138 Options.UseInitArray = options.UseInitArray;
141 void LTOCodeGenerator::setDebugInfo(lto_debug_model debug) {
143 case LTO_DEBUG_MODEL_NONE:
144 EmitDwarfDebugInfo = false;
147 case LTO_DEBUG_MODEL_DWARF:
148 EmitDwarfDebugInfo = true;
151 llvm_unreachable("Unknown debug format!");
154 void LTOCodeGenerator::setCodePICModel(lto_codegen_model model) {
156 case LTO_CODEGEN_PIC_MODEL_STATIC:
157 case LTO_CODEGEN_PIC_MODEL_DYNAMIC:
158 case LTO_CODEGEN_PIC_MODEL_DYNAMIC_NO_PIC:
162 llvm_unreachable("Unknown PIC model!");
165 bool LTOCodeGenerator::writeMergedModules(const char *path,
166 std::string &errMsg) {
167 if (!determineTarget(errMsg))
170 // mark which symbols can not be internalized
171 applyScopeRestrictions();
173 // create output file
175 tool_output_file Out(path, ErrInfo, sys::fs::F_Binary);
176 if (!ErrInfo.empty()) {
177 errMsg = "could not open bitcode file for writing: ";
182 // write bitcode to it
183 WriteBitcodeToFile(Linker.getModule(), Out.os());
186 if (Out.os().has_error()) {
187 errMsg = "could not write bitcode file: ";
189 Out.os().clear_error();
197 bool LTOCodeGenerator::compile_to_file(const char** name,
200 bool disableGVNLoadPRE,
201 std::string& errMsg) {
202 // make unique temp .o file to put generated object file
203 SmallString<128> Filename;
205 error_code EC = sys::fs::createTemporaryFile("lto-llvm", "o", FD, Filename);
207 errMsg = EC.message();
211 // generate object file
212 tool_output_file objFile(Filename.c_str(), FD);
214 bool genResult = generateObjectFile(objFile.os(), disableOpt, disableInline,
215 disableGVNLoadPRE, errMsg);
216 objFile.os().close();
217 if (objFile.os().has_error()) {
218 objFile.os().clear_error();
219 sys::fs::remove(Twine(Filename));
225 sys::fs::remove(Twine(Filename));
229 NativeObjectPath = Filename.c_str();
230 *name = NativeObjectPath.c_str();
234 const void* LTOCodeGenerator::compile(size_t* length,
237 bool disableGVNLoadPRE,
238 std::string& errMsg) {
240 if (!compile_to_file(&name, disableOpt, disableInline, disableGVNLoadPRE,
244 // remove old buffer if compile() called twice
245 delete NativeObjectFile;
247 // read .o file into memory buffer
248 OwningPtr<MemoryBuffer> BuffPtr;
249 if (error_code ec = MemoryBuffer::getFile(name, BuffPtr, -1, false)) {
250 errMsg = ec.message();
251 sys::fs::remove(NativeObjectPath);
254 NativeObjectFile = BuffPtr.take();
257 sys::fs::remove(NativeObjectPath);
259 // return buffer, unless error
260 if (NativeObjectFile == NULL)
262 *length = NativeObjectFile->getBufferSize();
263 return NativeObjectFile->getBufferStart();
266 bool LTOCodeGenerator::determineTarget(std::string &errMsg) {
267 if (TargetMach != NULL)
270 std::string TripleStr = Linker.getModule()->getTargetTriple();
271 if (TripleStr.empty())
272 TripleStr = sys::getDefaultTargetTriple();
273 llvm::Triple Triple(TripleStr);
275 // create target machine from info for merged modules
276 const Target *march = TargetRegistry::lookupTarget(TripleStr, errMsg);
280 // The relocation model is actually a static member of TargetMachine and
281 // needs to be set before the TargetMachine is instantiated.
282 Reloc::Model RelocModel = Reloc::Default;
284 case LTO_CODEGEN_PIC_MODEL_STATIC:
285 RelocModel = Reloc::Static;
287 case LTO_CODEGEN_PIC_MODEL_DYNAMIC:
288 RelocModel = Reloc::PIC_;
290 case LTO_CODEGEN_PIC_MODEL_DYNAMIC_NO_PIC:
291 RelocModel = Reloc::DynamicNoPIC;
295 // construct LTOModule, hand over ownership of module and target
296 SubtargetFeatures Features;
297 Features.getDefaultSubtargetFeatures(Triple);
298 std::string FeatureStr = Features.getString();
299 // Set a default CPU for Darwin triples.
300 if (MCpu.empty() && Triple.isOSDarwin()) {
301 if (Triple.getArch() == llvm::Triple::x86_64)
303 else if (Triple.getArch() == llvm::Triple::x86)
307 TargetMach = march->createTargetMachine(TripleStr, MCpu, FeatureStr, Options,
308 RelocModel, CodeModel::Default,
309 CodeGenOpt::Aggressive);
313 void LTOCodeGenerator::
314 applyRestriction(GlobalValue &GV,
315 std::vector<const char*> &MustPreserveList,
316 std::vector<const char*> &DSOList,
317 SmallPtrSet<GlobalValue*, 8> &AsmUsed,
319 SmallString<64> Buffer;
320 Mangler.getNameWithPrefix(Buffer, &GV, false);
322 if (GV.isDeclaration())
324 if (MustPreserveSymbols.count(Buffer))
325 MustPreserveList.push_back(GV.getName().data());
326 if (DSOSymbols.count(Buffer))
327 DSOList.push_back(GV.getName().data());
328 if (AsmUndefinedRefs.count(Buffer))
332 static void findUsedValues(GlobalVariable *LLVMUsed,
333 SmallPtrSet<GlobalValue*, 8> &UsedValues) {
334 if (LLVMUsed == 0) return;
336 ConstantArray *Inits = cast<ConstantArray>(LLVMUsed->getInitializer());
337 for (unsigned i = 0, e = Inits->getNumOperands(); i != e; ++i)
338 if (GlobalValue *GV =
339 dyn_cast<GlobalValue>(Inits->getOperand(i)->stripPointerCasts()))
340 UsedValues.insert(GV);
343 void LTOCodeGenerator::applyScopeRestrictions() {
344 if (ScopeRestrictionsDone)
346 Module *mergedModule = Linker.getModule();
348 // Start off with a verification pass.
350 passes.add(createVerifierPass());
352 // mark which symbols can not be internalized
353 MCContext MContext(TargetMach->getMCAsmInfo(), TargetMach->getRegisterInfo(),
355 Mangler Mangler(MContext, TargetMach);
356 std::vector<const char*> MustPreserveList;
357 std::vector<const char*> DSOList;
358 SmallPtrSet<GlobalValue*, 8> AsmUsed;
360 for (Module::iterator f = mergedModule->begin(),
361 e = mergedModule->end(); f != e; ++f)
362 applyRestriction(*f, MustPreserveList, DSOList, AsmUsed, Mangler);
363 for (Module::global_iterator v = mergedModule->global_begin(),
364 e = mergedModule->global_end(); v != e; ++v)
365 applyRestriction(*v, MustPreserveList, DSOList, AsmUsed, Mangler);
366 for (Module::alias_iterator a = mergedModule->alias_begin(),
367 e = mergedModule->alias_end(); a != e; ++a)
368 applyRestriction(*a, MustPreserveList, DSOList, AsmUsed, Mangler);
370 GlobalVariable *LLVMCompilerUsed =
371 mergedModule->getGlobalVariable("llvm.compiler.used");
372 findUsedValues(LLVMCompilerUsed, AsmUsed);
373 if (LLVMCompilerUsed)
374 LLVMCompilerUsed->eraseFromParent();
376 if (!AsmUsed.empty()) {
377 llvm::Type *i8PTy = llvm::Type::getInt8PtrTy(Context);
378 std::vector<Constant*> asmUsed2;
379 for (SmallPtrSet<GlobalValue*, 16>::const_iterator i = AsmUsed.begin(),
380 e = AsmUsed.end(); i !=e; ++i) {
381 GlobalValue *GV = *i;
382 Constant *c = ConstantExpr::getBitCast(GV, i8PTy);
383 asmUsed2.push_back(c);
386 llvm::ArrayType *ATy = llvm::ArrayType::get(i8PTy, asmUsed2.size());
388 new llvm::GlobalVariable(*mergedModule, ATy, false,
389 llvm::GlobalValue::AppendingLinkage,
390 llvm::ConstantArray::get(ATy, asmUsed2),
391 "llvm.compiler.used");
393 LLVMCompilerUsed->setSection("llvm.metadata");
396 passes.add(createInternalizePass(MustPreserveList, DSOList));
398 // apply scope restrictions
399 passes.run(*mergedModule);
401 ScopeRestrictionsDone = true;
404 /// Optimize merged modules using various IPO passes
405 bool LTOCodeGenerator::generateObjectFile(raw_ostream &out,
408 bool DisableGVNLoadPRE,
409 std::string &errMsg) {
410 if (!this->determineTarget(errMsg))
413 Module *mergedModule = Linker.getModule();
415 // Mark which symbols can not be internalized
416 this->applyScopeRestrictions();
418 // Instantiate the pass manager to organize the passes.
421 // Start off with a verification pass.
422 passes.add(createVerifierPass());
424 // Add an appropriate DataLayout instance for this module...
425 passes.add(new DataLayout(*TargetMach->getDataLayout()));
426 TargetMach->addAnalysisPasses(passes);
428 // Enabling internalize here would use its AllButMain variant. It
429 // keeps only main if it exists and does nothing for libraries. Instead
430 // we create the pass ourselves with the symbol list provided by the linker.
432 PassManagerBuilder().populateLTOPassManager(passes,
433 /*Internalize=*/false,
437 // Make sure everything is still good.
438 passes.add(createVerifierPass());
440 PassManager codeGenPasses;
442 codeGenPasses.add(new DataLayout(*TargetMach->getDataLayout()));
443 TargetMach->addAnalysisPasses(codeGenPasses);
445 formatted_raw_ostream Out(out);
447 // If the bitcode files contain ARC code and were compiled with optimization,
448 // the ObjCARCContractPass must be run, so do it unconditionally here.
449 codeGenPasses.add(createObjCARCContractPass());
451 if (TargetMach->addPassesToEmitFile(codeGenPasses, Out,
452 TargetMachine::CGFT_ObjectFile)) {
453 errMsg = "target file type not supported";
457 // Run our queue of passes all at once now, efficiently.
458 passes.run(*mergedModule);
460 // Run the code generator, and write assembly file
461 codeGenPasses.run(*mergedModule);
466 /// setCodeGenDebugOptions - Set codegen debugging options to aid in debugging
468 void LTOCodeGenerator::setCodeGenDebugOptions(const char *options) {
469 for (std::pair<StringRef, StringRef> o = getToken(options);
470 !o.first.empty(); o = getToken(o.second)) {
471 // ParseCommandLineOptions() expects argv[0] to be program name. Lazily add
473 if (CodegenOptions.empty())
474 CodegenOptions.push_back(strdup("libLLVMLTO"));
475 CodegenOptions.push_back(strdup(o.first.str().c_str()));
479 void LTOCodeGenerator::parseCodeGenDebugOptions() {
480 // if options were requested, set them
481 if (!CodegenOptions.empty())
482 cl::ParseCommandLineOptions(CodegenOptions.size(),
483 const_cast<char **>(&CodegenOptions[0]));