Add a 'deleteModule' method to the Linker class.
[oota-llvm.git] / lib / LTO / LTOCodeGenerator.cpp
1 //===-LTOCodeGenerator.cpp - LLVM Link Time Optimizer ---------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
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.
12 //
13 //===----------------------------------------------------------------------===//
14
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"
49 using namespace llvm;
50
51 const char* LTOCodeGenerator::getVersionString() {
52 #ifdef LLVM_VERSION_INFO
53   return PACKAGE_NAME " version " PACKAGE_VERSION ", " LLVM_VERSION_INFO;
54 #else
55   return PACKAGE_NAME " version " PACKAGE_VERSION;
56 #endif
57 }
58
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();
64 }
65
66 LTOCodeGenerator::~LTOCodeGenerator() {
67   delete TargetMach;
68   delete NativeObjectFile;
69   TargetMach = NULL;
70   NativeObjectFile = NULL;
71
72   Linker.deleteModule();
73
74   for (std::vector<char *>::iterator I = CodegenOptions.begin(),
75                                      E = CodegenOptions.end();
76        I != E; ++I)
77     free(*I);
78 }
79
80 // Initialize LTO passes. Please keep this funciton in sync with
81 // PassManagerBuilder::populateLTOPassManager(), and make sure all LTO
82 // passes are initialized. 
83 //
84 void LTOCodeGenerator::initializeLTOPasses() {
85   PassRegistry &R = *PassRegistry::getPassRegistry();
86
87   initializeInternalizePassPass(R);
88   initializeIPSCCPPass(R);
89   initializeGlobalOptPass(R);
90   initializeConstantMergePass(R);
91   initializeDAHPass(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);
108 }
109
110 bool LTOCodeGenerator::addModule(LTOModule* mod, std::string& errMsg) {
111   bool ret = Linker.linkInModule(mod->getLLVVMModule(), &errMsg);
112
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;
116
117   return !ret;
118 }
119
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;
139 }
140
141 void LTOCodeGenerator::setDebugInfo(lto_debug_model debug) {
142   switch (debug) {
143   case LTO_DEBUG_MODEL_NONE:
144     EmitDwarfDebugInfo = false;
145     return;
146
147   case LTO_DEBUG_MODEL_DWARF:
148     EmitDwarfDebugInfo = true;
149     return;
150   }
151   llvm_unreachable("Unknown debug format!");
152 }
153
154 void LTOCodeGenerator::setCodePICModel(lto_codegen_model model) {
155   switch (model) {
156   case LTO_CODEGEN_PIC_MODEL_STATIC:
157   case LTO_CODEGEN_PIC_MODEL_DYNAMIC:
158   case LTO_CODEGEN_PIC_MODEL_DYNAMIC_NO_PIC:
159     CodeModel = model;
160     return;
161   }
162   llvm_unreachable("Unknown PIC model!");
163 }
164
165 bool LTOCodeGenerator::writeMergedModules(const char *path,
166                                           std::string &errMsg) {
167   if (!determineTarget(errMsg))
168     return false;
169
170   // mark which symbols can not be internalized
171   applyScopeRestrictions();
172
173   // create output file
174   std::string ErrInfo;
175   tool_output_file Out(path, ErrInfo, sys::fs::F_Binary);
176   if (!ErrInfo.empty()) {
177     errMsg = "could not open bitcode file for writing: ";
178     errMsg += path;
179     return false;
180   }
181
182   // write bitcode to it
183   WriteBitcodeToFile(Linker.getModule(), Out.os());
184   Out.os().close();
185
186   if (Out.os().has_error()) {
187     errMsg = "could not write bitcode file: ";
188     errMsg += path;
189     Out.os().clear_error();
190     return false;
191   }
192
193   Out.keep();
194   return true;
195 }
196
197 bool LTOCodeGenerator::compile_to_file(const char** name, 
198                                        bool disableOpt,
199                                        bool disableInline,
200                                        bool disableGVNLoadPRE,
201                                        std::string& errMsg) {
202   // make unique temp .o file to put generated object file
203   SmallString<128> Filename;
204   int FD;
205   error_code EC = sys::fs::createTemporaryFile("lto-llvm", "o", FD, Filename);
206   if (EC) {
207     errMsg = EC.message();
208     return false;
209   }
210
211   // generate object file
212   tool_output_file objFile(Filename.c_str(), FD);
213
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));
220     return false;
221   }
222
223   objFile.keep();
224   if (!genResult) {
225     sys::fs::remove(Twine(Filename));
226     return false;
227   }
228
229   NativeObjectPath = Filename.c_str();
230   *name = NativeObjectPath.c_str();
231   return true;
232 }
233
234 const void* LTOCodeGenerator::compile(size_t* length,
235                                       bool disableOpt,
236                                       bool disableInline,
237                                       bool disableGVNLoadPRE,
238                                       std::string& errMsg) {
239   const char *name;
240   if (!compile_to_file(&name, disableOpt, disableInline, disableGVNLoadPRE,
241                        errMsg))
242     return NULL;
243
244   // remove old buffer if compile() called twice
245   delete NativeObjectFile;
246
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);
252     return NULL;
253   }
254   NativeObjectFile = BuffPtr.take();
255
256   // remove temp files
257   sys::fs::remove(NativeObjectPath);
258
259   // return buffer, unless error
260   if (NativeObjectFile == NULL)
261     return NULL;
262   *length = NativeObjectFile->getBufferSize();
263   return NativeObjectFile->getBufferStart();
264 }
265
266 bool LTOCodeGenerator::determineTarget(std::string &errMsg) {
267   if (TargetMach != NULL)
268     return true;
269
270   std::string TripleStr = Linker.getModule()->getTargetTriple();
271   if (TripleStr.empty())
272     TripleStr = sys::getDefaultTargetTriple();
273   llvm::Triple Triple(TripleStr);
274
275   // create target machine from info for merged modules
276   const Target *march = TargetRegistry::lookupTarget(TripleStr, errMsg);
277   if (march == NULL)
278     return false;
279
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;
283   switch (CodeModel) {
284   case LTO_CODEGEN_PIC_MODEL_STATIC:
285     RelocModel = Reloc::Static;
286     break;
287   case LTO_CODEGEN_PIC_MODEL_DYNAMIC:
288     RelocModel = Reloc::PIC_;
289     break;
290   case LTO_CODEGEN_PIC_MODEL_DYNAMIC_NO_PIC:
291     RelocModel = Reloc::DynamicNoPIC;
292     break;
293   }
294
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)
302       MCpu = "core2";
303     else if (Triple.getArch() == llvm::Triple::x86)
304       MCpu = "yonah";
305   }
306
307   TargetMach = march->createTargetMachine(TripleStr, MCpu, FeatureStr, Options,
308                                           RelocModel, CodeModel::Default,
309                                           CodeGenOpt::Aggressive);
310   return true;
311 }
312
313 void LTOCodeGenerator::
314 applyRestriction(GlobalValue &GV,
315                  std::vector<const char*> &MustPreserveList,
316                  std::vector<const char*> &DSOList,
317                  SmallPtrSet<GlobalValue*, 8> &AsmUsed,
318                  Mangler &Mangler) {
319   SmallString<64> Buffer;
320   Mangler.getNameWithPrefix(Buffer, &GV, false);
321
322   if (GV.isDeclaration())
323     return;
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))
329     AsmUsed.insert(&GV);
330 }
331
332 static void findUsedValues(GlobalVariable *LLVMUsed,
333                            SmallPtrSet<GlobalValue*, 8> &UsedValues) {
334   if (LLVMUsed == 0) return;
335
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);
341 }
342
343 void LTOCodeGenerator::applyScopeRestrictions() {
344   if (ScopeRestrictionsDone)
345     return;
346   Module *mergedModule = Linker.getModule();
347
348   // Start off with a verification pass.
349   PassManager passes;
350   passes.add(createVerifierPass());
351
352   // mark which symbols can not be internalized
353   MCContext MContext(TargetMach->getMCAsmInfo(), TargetMach->getRegisterInfo(),
354                      NULL);
355   Mangler Mangler(MContext, TargetMach);
356   std::vector<const char*> MustPreserveList;
357   std::vector<const char*> DSOList;
358   SmallPtrSet<GlobalValue*, 8> AsmUsed;
359
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);
369
370   GlobalVariable *LLVMCompilerUsed =
371     mergedModule->getGlobalVariable("llvm.compiler.used");
372   findUsedValues(LLVMCompilerUsed, AsmUsed);
373   if (LLVMCompilerUsed)
374     LLVMCompilerUsed->eraseFromParent();
375
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);
384     }
385
386     llvm::ArrayType *ATy = llvm::ArrayType::get(i8PTy, asmUsed2.size());
387     LLVMCompilerUsed =
388       new llvm::GlobalVariable(*mergedModule, ATy, false,
389                                llvm::GlobalValue::AppendingLinkage,
390                                llvm::ConstantArray::get(ATy, asmUsed2),
391                                "llvm.compiler.used");
392
393     LLVMCompilerUsed->setSection("llvm.metadata");
394   }
395
396   passes.add(createInternalizePass(MustPreserveList, DSOList));
397
398   // apply scope restrictions
399   passes.run(*mergedModule);
400
401   ScopeRestrictionsDone = true;
402 }
403
404 /// Optimize merged modules using various IPO passes
405 bool LTOCodeGenerator::generateObjectFile(raw_ostream &out,
406                                           bool DisableOpt,
407                                           bool DisableInline,
408                                           bool DisableGVNLoadPRE,
409                                           std::string &errMsg) {
410   if (!this->determineTarget(errMsg))
411     return false;
412
413   Module *mergedModule = Linker.getModule();
414
415   // Mark which symbols can not be internalized
416   this->applyScopeRestrictions();
417
418   // Instantiate the pass manager to organize the passes.
419   PassManager passes;
420
421   // Start off with a verification pass.
422   passes.add(createVerifierPass());
423
424   // Add an appropriate DataLayout instance for this module...
425   passes.add(new DataLayout(*TargetMach->getDataLayout()));
426   TargetMach->addAnalysisPasses(passes);
427
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.
431   if (!DisableOpt)
432     PassManagerBuilder().populateLTOPassManager(passes,
433                                               /*Internalize=*/false,
434                                               !DisableInline,
435                                               DisableGVNLoadPRE);
436
437   // Make sure everything is still good.
438   passes.add(createVerifierPass());
439
440   PassManager codeGenPasses;
441
442   codeGenPasses.add(new DataLayout(*TargetMach->getDataLayout()));
443   TargetMach->addAnalysisPasses(codeGenPasses);
444
445   formatted_raw_ostream Out(out);
446
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());
450
451   if (TargetMach->addPassesToEmitFile(codeGenPasses, Out,
452                                       TargetMachine::CGFT_ObjectFile)) {
453     errMsg = "target file type not supported";
454     return false;
455   }
456
457   // Run our queue of passes all at once now, efficiently.
458   passes.run(*mergedModule);
459
460   // Run the code generator, and write assembly file
461   codeGenPasses.run(*mergedModule);
462
463   return true;
464 }
465
466 /// setCodeGenDebugOptions - Set codegen debugging options to aid in debugging
467 /// LTO problems.
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
472     // that.
473     if (CodegenOptions.empty())
474       CodegenOptions.push_back(strdup("libLLVMLTO"));
475     CodegenOptions.push_back(strdup(o.first.str().c_str()));
476   }
477 }
478
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]));
484 }