Factor FlattenCFG out from SimplifyCFG
[oota-llvm.git] / tools / 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 "LTOCodeGenerator.h"
16 #include "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/Mangler.h"
44 #include "llvm/Target/TargetMachine.h"
45 #include "llvm/Target/TargetOptions.h"
46 #include "llvm/Target/TargetRegisterInfo.h"
47 #include "llvm/Transforms/IPO.h"
48 #include "llvm/Transforms/IPO/PassManagerBuilder.h"
49 #include "llvm/Transforms/ObjCARC.h"
50 using namespace llvm;
51
52 static cl::opt<bool>
53 DisableOpt("disable-opt", cl::init(false),
54   cl::desc("Do not run any optimization passes"));
55
56 static cl::opt<bool>
57 DisableInline("disable-inlining", cl::init(false),
58   cl::desc("Do not run the inliner pass"));
59
60 static cl::opt<bool>
61 DisableGVNLoadPRE("disable-gvn-loadpre", cl::init(false),
62   cl::desc("Do not run the GVN load PRE pass"));
63
64 const char* LTOCodeGenerator::getVersionString() {
65 #ifdef LLVM_VERSION_INFO
66   return PACKAGE_NAME " version " PACKAGE_VERSION ", " LLVM_VERSION_INFO;
67 #else
68   return PACKAGE_NAME " version " PACKAGE_VERSION;
69 #endif
70 }
71
72 LTOCodeGenerator::LTOCodeGenerator()
73   : _context(getGlobalContext()),
74     _linker(new Module("ld-temp.o", _context)), _target(NULL),
75     _emitDwarfDebugInfo(false), _scopeRestrictionsDone(false),
76     _codeModel(LTO_CODEGEN_PIC_MODEL_DYNAMIC),
77     _nativeObjectFile(NULL) {
78   InitializeAllTargets();
79   InitializeAllTargetMCs();
80   InitializeAllAsmPrinters();
81   initializeLTOPasses();
82 }
83
84 LTOCodeGenerator::~LTOCodeGenerator() {
85   delete _target;
86   delete _nativeObjectFile;
87   delete _linker.getModule();
88
89   for (std::vector<char*>::iterator I = _codegenOptions.begin(),
90          E = _codegenOptions.end(); I != E; ++I)
91     free(*I);
92 }
93
94 // Initialize LTO passes. Please keep this funciton in sync with
95 // PassManagerBuilder::populateLTOPassManager(), and make sure all LTO
96 // passes are initialized. 
97 //
98 void LTOCodeGenerator::initializeLTOPasses() {
99   PassRegistry &R = *PassRegistry::getPassRegistry();
100
101   initializeInternalizePassPass(R);
102   initializeIPSCCPPass(R);
103   initializeGlobalOptPass(R);
104   initializeConstantMergePass(R);
105   initializeDAHPass(R);
106   initializeInstCombinerPass(R);
107   initializeSimpleInlinerPass(R);
108   initializePruneEHPass(R);
109   initializeGlobalDCEPass(R);
110   initializeArgPromotionPass(R);
111   initializeJumpThreadingPass(R);
112   initializeSROAPass(R);
113   initializeSROA_DTPass(R);
114   initializeSROA_SSAUpPass(R);
115   initializeFunctionAttrsPass(R);
116   initializeGlobalsModRefPass(R);
117   initializeLICMPass(R);
118   initializeGVNPass(R);
119   initializeMemCpyOptPass(R);
120   initializeDCEPass(R);
121   initializeCFGSimplifyPassPass(R);
122 }
123
124 bool LTOCodeGenerator::addModule(LTOModule* mod, std::string& errMsg) {
125   bool ret = _linker.linkInModule(mod->getLLVVMModule(), &errMsg);
126
127   const std::vector<const char*> &undefs = mod->getAsmUndefinedRefs();
128   for (int i = 0, e = undefs.size(); i != e; ++i)
129     _asmUndefinedRefs[undefs[i]] = 1;
130
131   return ret;
132 }
133
134 bool LTOCodeGenerator::setDebugInfo(lto_debug_model debug,
135                                     std::string& errMsg) {
136   switch (debug) {
137   case LTO_DEBUG_MODEL_NONE:
138     _emitDwarfDebugInfo = false;
139     return false;
140
141   case LTO_DEBUG_MODEL_DWARF:
142     _emitDwarfDebugInfo = true;
143     return false;
144   }
145   llvm_unreachable("Unknown debug format!");
146 }
147
148 bool LTOCodeGenerator::setCodePICModel(lto_codegen_model model,
149                                        std::string& errMsg) {
150   switch (model) {
151   case LTO_CODEGEN_PIC_MODEL_STATIC:
152   case LTO_CODEGEN_PIC_MODEL_DYNAMIC:
153   case LTO_CODEGEN_PIC_MODEL_DYNAMIC_NO_PIC:
154     _codeModel = model;
155     return false;
156   }
157   llvm_unreachable("Unknown PIC model!");
158 }
159
160 bool LTOCodeGenerator::writeMergedModules(const char *path,
161                                           std::string &errMsg) {
162   if (determineTarget(errMsg))
163     return true;
164
165   // Run the verifier on the merged modules.
166   PassManager passes;
167   passes.add(createVerifierPass());
168   passes.run(*_linker.getModule());
169
170   // create output file
171   std::string ErrInfo;
172   tool_output_file Out(path, ErrInfo, sys::fs::F_Binary);
173   if (!ErrInfo.empty()) {
174     errMsg = "could not open bitcode file for writing: ";
175     errMsg += path;
176     return true;
177   }
178
179   // write bitcode to it
180   WriteBitcodeToFile(_linker.getModule(), Out.os());
181   Out.os().close();
182
183   if (Out.os().has_error()) {
184     errMsg = "could not write bitcode file: ";
185     errMsg += path;
186     Out.os().clear_error();
187     return true;
188   }
189
190   Out.keep();
191   return false;
192 }
193
194 bool LTOCodeGenerator::compile_to_file(const char** name, std::string& errMsg) {
195   // make unique temp .o file to put generated object file
196   SmallString<128> Filename;
197   int FD;
198   error_code EC = sys::fs::createTemporaryFile("lto-llvm", "o", FD, Filename);
199   if (EC) {
200     errMsg = EC.message();
201     return true;
202   }
203
204   // generate object file
205   tool_output_file objFile(Filename.c_str(), FD);
206
207   bool genResult = generateObjectFile(objFile.os(), errMsg);
208   objFile.os().close();
209   if (objFile.os().has_error()) {
210     objFile.os().clear_error();
211     sys::fs::remove(Twine(Filename));
212     return true;
213   }
214
215   objFile.keep();
216   if (genResult) {
217     sys::fs::remove(Twine(Filename));
218     return true;
219   }
220
221   _nativeObjectPath = Filename.c_str();
222   *name = _nativeObjectPath.c_str();
223   return false;
224 }
225
226 const void* LTOCodeGenerator::compile(size_t* length, std::string& errMsg) {
227   const char *name;
228   if (compile_to_file(&name, errMsg))
229     return NULL;
230
231   // remove old buffer if compile() called twice
232   delete _nativeObjectFile;
233
234   // read .o file into memory buffer
235   OwningPtr<MemoryBuffer> BuffPtr;
236   if (error_code ec = MemoryBuffer::getFile(name, BuffPtr, -1, false)) {
237     errMsg = ec.message();
238     sys::fs::remove(_nativeObjectPath);
239     return NULL;
240   }
241   _nativeObjectFile = BuffPtr.take();
242
243   // remove temp files
244   sys::fs::remove(_nativeObjectPath);
245
246   // return buffer, unless error
247   if (_nativeObjectFile == NULL)
248     return NULL;
249   *length = _nativeObjectFile->getBufferSize();
250   return _nativeObjectFile->getBufferStart();
251 }
252
253 bool LTOCodeGenerator::determineTarget(std::string &errMsg) {
254   if (_target != NULL)
255     return false;
256
257   // if options were requested, set them
258   if (!_codegenOptions.empty())
259     cl::ParseCommandLineOptions(_codegenOptions.size(),
260                                 const_cast<char **>(&_codegenOptions[0]));
261
262   std::string TripleStr = _linker.getModule()->getTargetTriple();
263   if (TripleStr.empty())
264     TripleStr = sys::getDefaultTargetTriple();
265   llvm::Triple Triple(TripleStr);
266
267   // create target machine from info for merged modules
268   const Target *march = TargetRegistry::lookupTarget(TripleStr, errMsg);
269   if (march == NULL)
270     return true;
271
272   // The relocation model is actually a static member of TargetMachine and
273   // needs to be set before the TargetMachine is instantiated.
274   Reloc::Model RelocModel = Reloc::Default;
275   switch (_codeModel) {
276   case LTO_CODEGEN_PIC_MODEL_STATIC:
277     RelocModel = Reloc::Static;
278     break;
279   case LTO_CODEGEN_PIC_MODEL_DYNAMIC:
280     RelocModel = Reloc::PIC_;
281     break;
282   case LTO_CODEGEN_PIC_MODEL_DYNAMIC_NO_PIC:
283     RelocModel = Reloc::DynamicNoPIC;
284     break;
285   }
286
287   // construct LTOModule, hand over ownership of module and target
288   SubtargetFeatures Features;
289   Features.getDefaultSubtargetFeatures(Triple);
290   std::string FeatureStr = Features.getString();
291   // Set a default CPU for Darwin triples.
292   if (_mCpu.empty() && Triple.isOSDarwin()) {
293     if (Triple.getArch() == llvm::Triple::x86_64)
294       _mCpu = "core2";
295     else if (Triple.getArch() == llvm::Triple::x86)
296       _mCpu = "yonah";
297   }
298   TargetOptions Options;
299   LTOModule::getTargetOptions(Options);
300   _target = march->createTargetMachine(TripleStr, _mCpu, FeatureStr, Options,
301                                        RelocModel, CodeModel::Default,
302                                        CodeGenOpt::Aggressive);
303   return false;
304 }
305
306 void LTOCodeGenerator::
307 applyRestriction(GlobalValue &GV,
308                  std::vector<const char*> &mustPreserveList,
309                  SmallPtrSet<GlobalValue*, 8> &asmUsed,
310                  Mangler &mangler) {
311   SmallString<64> Buffer;
312   mangler.getNameWithPrefix(Buffer, &GV, false);
313
314   if (GV.isDeclaration())
315     return;
316   if (_mustPreserveSymbols.count(Buffer))
317     mustPreserveList.push_back(GV.getName().data());
318   if (_asmUndefinedRefs.count(Buffer))
319     asmUsed.insert(&GV);
320 }
321
322 static void findUsedValues(GlobalVariable *LLVMUsed,
323                            SmallPtrSet<GlobalValue*, 8> &UsedValues) {
324   if (LLVMUsed == 0) return;
325
326   ConstantArray *Inits = cast<ConstantArray>(LLVMUsed->getInitializer());
327   for (unsigned i = 0, e = Inits->getNumOperands(); i != e; ++i)
328     if (GlobalValue *GV =
329         dyn_cast<GlobalValue>(Inits->getOperand(i)->stripPointerCasts()))
330       UsedValues.insert(GV);
331 }
332
333 void LTOCodeGenerator::applyScopeRestrictions() {
334   if (_scopeRestrictionsDone) return;
335   Module *mergedModule = _linker.getModule();
336
337   // Start off with a verification pass.
338   PassManager passes;
339   passes.add(createVerifierPass());
340
341   // mark which symbols can not be internalized
342   MCContext Context(_target->getMCAsmInfo(), _target->getRegisterInfo(), NULL);
343   Mangler mangler(Context, _target);
344   std::vector<const char*> mustPreserveList;
345   SmallPtrSet<GlobalValue*, 8> asmUsed;
346
347   for (Module::iterator f = mergedModule->begin(),
348          e = mergedModule->end(); f != e; ++f)
349     applyRestriction(*f, mustPreserveList, asmUsed, mangler);
350   for (Module::global_iterator v = mergedModule->global_begin(),
351          e = mergedModule->global_end(); v !=  e; ++v)
352     applyRestriction(*v, mustPreserveList, asmUsed, mangler);
353   for (Module::alias_iterator a = mergedModule->alias_begin(),
354          e = mergedModule->alias_end(); a != e; ++a)
355     applyRestriction(*a, mustPreserveList, asmUsed, mangler);
356
357   GlobalVariable *LLVMCompilerUsed =
358     mergedModule->getGlobalVariable("llvm.compiler.used");
359   findUsedValues(LLVMCompilerUsed, asmUsed);
360   if (LLVMCompilerUsed)
361     LLVMCompilerUsed->eraseFromParent();
362
363   if (!asmUsed.empty()) {
364     llvm::Type *i8PTy = llvm::Type::getInt8PtrTy(_context);
365     std::vector<Constant*> asmUsed2;
366     for (SmallPtrSet<GlobalValue*, 16>::const_iterator i = asmUsed.begin(),
367            e = asmUsed.end(); i !=e; ++i) {
368       GlobalValue *GV = *i;
369       Constant *c = ConstantExpr::getBitCast(GV, i8PTy);
370       asmUsed2.push_back(c);
371     }
372
373     llvm::ArrayType *ATy = llvm::ArrayType::get(i8PTy, asmUsed2.size());
374     LLVMCompilerUsed =
375       new llvm::GlobalVariable(*mergedModule, ATy, false,
376                                llvm::GlobalValue::AppendingLinkage,
377                                llvm::ConstantArray::get(ATy, asmUsed2),
378                                "llvm.compiler.used");
379
380     LLVMCompilerUsed->setSection("llvm.metadata");
381   }
382
383   passes.add(createInternalizePass(mustPreserveList));
384
385   // apply scope restrictions
386   passes.run(*mergedModule);
387
388   _scopeRestrictionsDone = true;
389 }
390
391 /// Optimize merged modules using various IPO passes
392 bool LTOCodeGenerator::generateObjectFile(raw_ostream &out,
393                                           std::string &errMsg) {
394   if (this->determineTarget(errMsg))
395     return true;
396
397   Module* mergedModule = _linker.getModule();
398
399   // Mark which symbols can not be internalized
400   this->applyScopeRestrictions();
401
402   // Instantiate the pass manager to organize the passes.
403   PassManager passes;
404
405   // Start off with a verification pass.
406   passes.add(createVerifierPass());
407
408   // Add an appropriate DataLayout instance for this module...
409   passes.add(new DataLayout(*_target->getDataLayout()));
410   _target->addAnalysisPasses(passes);
411
412   // Enabling internalize here would use its AllButMain variant. It
413   // keeps only main if it exists and does nothing for libraries. Instead
414   // we create the pass ourselves with the symbol list provided by the linker.
415   if (!DisableOpt)
416     PassManagerBuilder().populateLTOPassManager(passes,
417                                               /*Internalize=*/false,
418                                               !DisableInline,
419                                               DisableGVNLoadPRE);
420
421   // Make sure everything is still good.
422   passes.add(createVerifierPass());
423
424   PassManager codeGenPasses;
425
426   codeGenPasses.add(new DataLayout(*_target->getDataLayout()));
427   _target->addAnalysisPasses(codeGenPasses);
428
429   formatted_raw_ostream Out(out);
430
431   // If the bitcode files contain ARC code and were compiled with optimization,
432   // the ObjCARCContractPass must be run, so do it unconditionally here.
433   codeGenPasses.add(createObjCARCContractPass());
434
435   if (_target->addPassesToEmitFile(codeGenPasses, Out,
436                                    TargetMachine::CGFT_ObjectFile)) {
437     errMsg = "target file type not supported";
438     return true;
439   }
440
441   // Run our queue of passes all at once now, efficiently.
442   passes.run(*mergedModule);
443
444   // Run the code generator, and write assembly file
445   codeGenPasses.run(*mergedModule);
446
447   return false; // success
448 }
449
450 /// setCodeGenDebugOptions - Set codegen debugging options to aid in debugging
451 /// LTO problems.
452 void LTOCodeGenerator::setCodeGenDebugOptions(const char *options) {
453   for (std::pair<StringRef, StringRef> o = getToken(options);
454        !o.first.empty(); o = getToken(o.second)) {
455     // ParseCommandLineOptions() expects argv[0] to be program name. Lazily add
456     // that.
457     if (_codegenOptions.empty())
458       _codegenOptions.push_back(strdup("libLTO"));
459     _codegenOptions.push_back(strdup(o.first.str().c_str()));
460   }
461 }