Remove LTO optimization level.
[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 "LTOModule.h"
16 #include "LTOCodeGenerator.h"
17
18
19 #include "llvm/Module.h"
20 #include "llvm/PassManager.h"
21 #include "llvm/Linker.h"
22 #include "llvm/Constants.h"
23 #include "llvm/DerivedTypes.h"
24 #include "llvm/ModuleProvider.h"
25 #include "llvm/Bitcode/ReaderWriter.h"
26 #include "llvm/Support/CommandLine.h"
27 #include "llvm/Support/SystemUtils.h"
28 #include "llvm/Support/Mangler.h"
29 #include "llvm/Support/MemoryBuffer.h"
30 #include "llvm/Support/raw_ostream.h"
31 #include "llvm/System/Signals.h"
32 #include "llvm/Analysis/Passes.h"
33 #include "llvm/Analysis/LoopPass.h"
34 #include "llvm/Analysis/Verifier.h"
35 #include "llvm/CodeGen/FileWriters.h"
36 #include "llvm/Target/SubtargetFeature.h"
37 #include "llvm/Target/TargetOptions.h"
38 #include "llvm/Target/TargetData.h"
39 #include "llvm/Target/TargetMachine.h"
40 #include "llvm/Target/TargetMachineRegistry.h"
41 #include "llvm/Target/TargetAsmInfo.h"
42 #include "llvm/Transforms/IPO.h"
43 #include "llvm/Transforms/Scalar.h"
44 #include "llvm/ADT/StringExtras.h"
45 #include "llvm/Config/config.h"
46
47
48 #include <fstream>
49 #include <unistd.h>
50 #include <stdlib.h>
51 #include <fcntl.h>
52
53
54 using namespace llvm;
55
56 static cl::opt<bool> DisableInline("disable-inlining",
57   cl::desc("Do not run the inliner pass"));
58
59
60 const char* LTOCodeGenerator::getVersionString()
61 {
62 #ifdef LLVM_VERSION_INFO
63     return PACKAGE_NAME " version " PACKAGE_VERSION ", " LLVM_VERSION_INFO;
64 #else
65     return PACKAGE_NAME " version " PACKAGE_VERSION;
66 #endif
67 }
68
69
70 LTOCodeGenerator::LTOCodeGenerator() 
71     : _linker("LinkTimeOptimizer", "ld-temp.o"), _target(NULL),
72       _emitDwarfDebugInfo(false), _scopeRestrictionsDone(false),
73       _codeModel(LTO_CODEGEN_PIC_MODEL_DYNAMIC),
74       _nativeObjectFile(NULL)
75 {
76
77 }
78
79 LTOCodeGenerator::~LTOCodeGenerator()
80 {
81     delete _target;
82     delete _nativeObjectFile;
83 }
84
85
86
87 bool LTOCodeGenerator::addModule(LTOModule* mod, std::string& errMsg)
88 {
89     return _linker.LinkInModule(mod->getLLVVMModule(), &errMsg);
90 }
91     
92
93 bool LTOCodeGenerator::setDebugInfo(lto_debug_model debug, std::string& errMsg)
94 {
95     switch (debug) {
96         case LTO_DEBUG_MODEL_NONE:
97             _emitDwarfDebugInfo = false;
98             return false;
99             
100         case LTO_DEBUG_MODEL_DWARF:
101             _emitDwarfDebugInfo = true;
102             return false;
103     }
104     errMsg = "unknown debug format";
105     return true;
106 }
107
108
109 bool LTOCodeGenerator::setCodePICModel(lto_codegen_model model, 
110                                                         std::string& errMsg)
111 {
112     switch (model) {
113         case LTO_CODEGEN_PIC_MODEL_STATIC:
114         case LTO_CODEGEN_PIC_MODEL_DYNAMIC:
115         case LTO_CODEGEN_PIC_MODEL_DYNAMIC_NO_PIC:
116             _codeModel = model;
117             return false;
118     }
119     errMsg = "unknown pic model";
120     return true;
121 }
122
123 void LTOCodeGenerator::addMustPreserveSymbol(const char* sym)
124 {
125     _mustPreserveSymbols[sym] = 1;
126 }
127
128
129 bool LTOCodeGenerator::writeMergedModules(const char* path, std::string& errMsg)
130 {
131     if ( this->determineTarget(errMsg) ) 
132         return true;
133
134     // mark which symbols can not be internalized 
135     this->applyScopeRestrictions();
136
137     // create output file
138     std::ofstream out(path, std::ios_base::out|std::ios::trunc|std::ios::binary);
139     if ( out.fail() ) {
140         errMsg = "could not open bitcode file for writing: ";
141         errMsg += path;
142         return true;
143     }
144     
145     // write bitcode to it
146     WriteBitcodeToFile(_linker.getModule(), out);
147     if ( out.fail() ) {
148         errMsg = "could not write bitcode file: ";
149         errMsg += path;
150         return true;
151     }
152     
153     return false;
154 }
155
156
157 const void* LTOCodeGenerator::compile(size_t* length, std::string& errMsg)
158 {
159     // make unique temp .s file to put generated assembly code
160     sys::Path uniqueAsmPath("lto-llvm.s");
161     if ( uniqueAsmPath.createTemporaryFileOnDisk(true, &errMsg) )
162         return NULL;
163     sys::RemoveFileOnSignal(uniqueAsmPath);
164        
165     // generate assembly code
166     bool genResult = false;
167     {
168       raw_fd_ostream asmFile(uniqueAsmPath.c_str(), false, errMsg);
169       if (!errMsg.empty())
170         return NULL;
171       genResult = this->generateAssemblyCode(asmFile, errMsg);
172     }
173     if ( genResult ) {
174         if ( uniqueAsmPath.exists() )
175             uniqueAsmPath.eraseFromDisk();
176         return NULL;
177     }
178     
179     // make unique temp .o file to put generated object file
180     sys::PathWithStatus uniqueObjPath("lto-llvm.o");
181     if ( uniqueObjPath.createTemporaryFileOnDisk(true, &errMsg) ) {
182         if ( uniqueAsmPath.exists() )
183             uniqueAsmPath.eraseFromDisk();
184         return NULL;
185     }
186     sys::RemoveFileOnSignal(uniqueObjPath);
187
188     // assemble the assembly code
189     const std::string& uniqueObjStr = uniqueObjPath.toString();
190     bool asmResult = this->assemble(uniqueAsmPath.toString(), 
191                                                         uniqueObjStr, errMsg);
192     if ( !asmResult ) {
193         // remove old buffer if compile() called twice
194         delete _nativeObjectFile;
195         
196         // read .o file into memory buffer
197         _nativeObjectFile = MemoryBuffer::getFile(uniqueObjStr.c_str(),&errMsg);
198     }
199
200     // remove temp files
201     uniqueAsmPath.eraseFromDisk();
202     uniqueObjPath.eraseFromDisk();
203
204     // return buffer, unless error
205     if ( _nativeObjectFile == NULL )
206         return NULL;
207     *length = _nativeObjectFile->getBufferSize();
208     return _nativeObjectFile->getBufferStart();
209 }
210
211
212 bool LTOCodeGenerator::assemble(const std::string& asmPath, 
213                                 const std::string& objPath, std::string& errMsg)
214 {
215     // find compiler driver
216     const sys::Path gcc = sys::Program::FindProgramByName("gcc");
217     if ( gcc.isEmpty() ) {
218         errMsg = "can't locate gcc";
219         return true;
220     }
221
222     // build argument list
223     std::vector<const char*> args;
224     std::string targetTriple = _linker.getModule()->getTargetTriple();
225     args.push_back(gcc.c_str());
226     if ( targetTriple.find("darwin") != targetTriple.size() ) {
227         if (strncmp(targetTriple.c_str(), "i386-apple-", 11) == 0) {
228             args.push_back("-arch");
229             args.push_back("i386");
230         }
231         else if (strncmp(targetTriple.c_str(), "x86_64-apple-", 13) == 0) {
232             args.push_back("-arch");
233             args.push_back("x86_64");
234         }
235         else if (strncmp(targetTriple.c_str(), "powerpc-apple-", 14) == 0) {
236             args.push_back("-arch");
237             args.push_back("ppc");
238         }
239         else if (strncmp(targetTriple.c_str(), "powerpc64-apple-", 16) == 0) {
240             args.push_back("-arch");
241             args.push_back("ppc64");
242         }
243         else if (strncmp(targetTriple.c_str(), "arm-apple-", 10) == 0) {
244             args.push_back("-arch");
245             args.push_back("arm");
246         }
247         else if ((strncmp(targetTriple.c_str(), "armv4t-apple-", 13) == 0) ||
248                  (strncmp(targetTriple.c_str(), "thumbv4t-apple-", 15) == 0)) {
249             args.push_back("-arch");
250             args.push_back("armv4t");
251         }
252         else if ((strncmp(targetTriple.c_str(), "armv5-apple-", 12) == 0) ||
253                  (strncmp(targetTriple.c_str(), "armv5e-apple-", 13) == 0) ||
254                  (strncmp(targetTriple.c_str(), "thumbv5-apple-", 14) == 0) ||
255                  (strncmp(targetTriple.c_str(), "thumbv5e-apple-", 15) == 0)) {
256             args.push_back("-arch");
257             args.push_back("armv5");
258         }
259         else if ((strncmp(targetTriple.c_str(), "armv6-apple-", 12) == 0) ||
260                  (strncmp(targetTriple.c_str(), "thumbv6-apple-", 14) == 0)) {
261             args.push_back("-arch");
262             args.push_back("armv6");
263         }
264     }
265     args.push_back("-c");
266     args.push_back("-x");
267     args.push_back("assembler");
268     args.push_back("-o");
269     args.push_back(objPath.c_str());
270     args.push_back(asmPath.c_str());
271     args.push_back(0);
272
273     // invoke assembler
274     if ( sys::Program::ExecuteAndWait(gcc, &args[0], 0, 0, 0, 0, &errMsg) ) {
275         errMsg = "error in assembly";    
276         return true;
277     }
278     return false; // success
279 }
280
281
282
283 bool LTOCodeGenerator::determineTarget(std::string& errMsg)
284 {
285     if ( _target == NULL ) {
286         // create target machine from info for merged modules
287         Module* mergedModule = _linker.getModule();
288         const TargetMachineRegistry::entry* march = 
289           TargetMachineRegistry::getClosestStaticTargetForModule(
290                                                        *mergedModule, errMsg);
291         if ( march == NULL )
292             return true;
293
294         // construct LTModule, hand over ownership of module and target
295         std::string FeatureStr =
296           getFeatureString(_linker.getModule()->getTargetTriple().c_str());
297         _target = march->CtorFn(*mergedModule, FeatureStr.c_str());
298     }
299     return false;
300 }
301
302 void LTOCodeGenerator::applyScopeRestrictions()
303 {
304     if ( !_scopeRestrictionsDone ) {
305         Module* mergedModule = _linker.getModule();
306
307         // Start off with a verification pass.
308         PassManager passes;
309         passes.add(createVerifierPass());
310
311         // mark which symbols can not be internalized 
312         if ( !_mustPreserveSymbols.empty() ) {
313             Mangler mangler(*mergedModule, 
314                                 _target->getTargetAsmInfo()->getGlobalPrefix());
315             std::vector<const char*> mustPreserveList;
316             for (Module::iterator f = mergedModule->begin(), 
317                                         e = mergedModule->end(); f != e; ++f) {
318                 if ( !f->isDeclaration() 
319                   && _mustPreserveSymbols.count(mangler.getValueName(f)) )
320                     mustPreserveList.push_back(::strdup(f->getName().c_str()));
321             }
322             for (Module::global_iterator v = mergedModule->global_begin(), 
323                                  e = mergedModule->global_end(); v !=  e; ++v) {
324                 if ( !v->isDeclaration()
325                   && _mustPreserveSymbols.count(mangler.getValueName(v)) )
326                     mustPreserveList.push_back(::strdup(v->getName().c_str()));
327             }
328             passes.add(createInternalizePass(mustPreserveList));
329         }
330         // apply scope restrictions
331         passes.run(*mergedModule);
332         
333         _scopeRestrictionsDone = true;
334     }
335 }
336
337 /// Optimize merged modules using various IPO passes
338 bool LTOCodeGenerator::generateAssemblyCode(raw_ostream& out,
339                                             std::string& errMsg)
340 {
341     if (  this->determineTarget(errMsg) ) 
342         return true;
343
344     // mark which symbols can not be internalized 
345     this->applyScopeRestrictions();
346
347     Module* mergedModule = _linker.getModule();
348
349      // If target supports exception handling then enable it now.
350     if ( _target->getTargetAsmInfo()->doesSupportExceptionHandling() )
351         llvm::ExceptionHandling = true;
352
353     // set codegen model
354     switch( _codeModel ) {
355         case LTO_CODEGEN_PIC_MODEL_STATIC:
356             _target->setRelocationModel(Reloc::Static);
357             break;
358         case LTO_CODEGEN_PIC_MODEL_DYNAMIC:
359             _target->setRelocationModel(Reloc::PIC_);
360             break;
361         case LTO_CODEGEN_PIC_MODEL_DYNAMIC_NO_PIC:
362             _target->setRelocationModel(Reloc::DynamicNoPIC);
363             break;
364     }
365
366     // if options were requested, set them
367     if ( !_codegenOptions.empty() )
368         cl::ParseCommandLineOptions(_codegenOptions.size(), 
369                                                 (char**)&_codegenOptions[0]);
370
371     // Instantiate the pass manager to organize the passes.
372     PassManager passes;
373
374     // Start off with a verification pass.
375     passes.add(createVerifierPass());
376
377     // Add an appropriate TargetData instance for this module...
378     passes.add(new TargetData(*_target->getTargetData()));
379     
380     // Propagate constants at call sites into the functions they call.  This
381     // opens opportunities for globalopt (and inlining) by substituting function
382     // pointers passed as arguments to direct uses of functions.  
383     passes.add(createIPSCCPPass());
384
385     // Now that we internalized some globals, see if we can hack on them!
386     passes.add(createGlobalOptimizerPass());
387
388     // Linking modules together can lead to duplicated global constants, only
389     // keep one copy of each constant...
390     passes.add(createConstantMergePass());
391
392     // Remove unused arguments from functions...
393     passes.add(createDeadArgEliminationPass());
394
395     // Reduce the code after globalopt and ipsccp.  Both can open up significant
396     // simplification opportunities, and both can propagate functions through
397     // function pointers.  When this happens, we often have to resolve varargs
398     // calls, etc, so let instcombine do this.
399     passes.add(createInstructionCombiningPass());
400     if (!DisableInline)
401         passes.add(createFunctionInliningPass()); // Inline small functions
402     passes.add(createPruneEHPass());              // Remove dead EH info
403     passes.add(createGlobalDCEPass());            // Remove dead functions
404
405     // If we didn't decide to inline a function, check to see if we can
406     // transform it to pass arguments by value instead of by reference.
407     passes.add(createArgumentPromotionPass());
408
409     // The IPO passes may leave cruft around.  Clean up after them.
410     passes.add(createInstructionCombiningPass());
411     passes.add(createJumpThreadingPass());        // Thread jumps.
412     passes.add(createScalarReplAggregatesPass()); // Break up allocas
413
414     // Run a few AA driven optimizations here and now, to cleanup the code.
415     passes.add(createFunctionAttrsPass());        // Add nocapture
416     passes.add(createGlobalsModRefPass());        // IP alias analysis
417     passes.add(createLICMPass());                 // Hoist loop invariants
418     passes.add(createGVNPass());                  // Remove common subexprs
419     passes.add(createMemCpyOptPass());            // Remove dead memcpy's
420     passes.add(createDeadStoreEliminationPass()); // Nuke dead stores
421
422     // Cleanup and simplify the code after the scalar optimizations.
423     passes.add(createInstructionCombiningPass());
424     passes.add(createJumpThreadingPass());        // Thread jumps.
425     passes.add(createPromoteMemoryToRegisterPass()); // Cleanup after threading.
426
427
428     // Delete basic blocks, which optimization passes may have killed...
429     passes.add(createCFGSimplificationPass());
430
431     // Now that we have optimized the program, discard unreachable functions...
432     passes.add(createGlobalDCEPass());
433
434     // Make sure everything is still good.
435     passes.add(createVerifierPass());
436
437     FunctionPassManager* codeGenPasses =
438             new FunctionPassManager(new ExistingModuleProvider(mergedModule));
439
440     codeGenPasses->add(new TargetData(*_target->getTargetData()));
441
442     MachineCodeEmitter* mce = NULL;
443
444     switch (_target->addPassesToEmitFile(*codeGenPasses, out,
445                                          TargetMachine::AssemblyFile,
446                                          CodeGenOpt::Aggressive)) {
447         case FileModel::MachOFile:
448             mce = AddMachOWriter(*codeGenPasses, out, *_target);
449             break;
450         case FileModel::ElfFile:
451             mce = AddELFWriter(*codeGenPasses, out, *_target);
452             break;
453         case FileModel::AsmFile:
454             break;
455         case FileModel::Error:
456         case FileModel::None:
457             errMsg = "target file type not supported";
458             return true;
459     }
460
461     if (_target->addPassesToEmitFileFinish(*codeGenPasses, mce,
462                                            CodeGenOpt::Aggressive)) {
463         errMsg = "target does not support generation of this file type";
464         return true;
465     }
466
467     // Run our queue of passes all at once now, efficiently.
468     passes.run(*mergedModule);
469
470     // Run the code generator, and write assembly file
471     codeGenPasses->doInitialization();
472
473     for (Module::iterator
474            it = mergedModule->begin(), e = mergedModule->end(); it != e; ++it)
475       if (!it->isDeclaration())
476         codeGenPasses->run(*it);
477
478     codeGenPasses->doFinalization();
479     return false; // success
480 }
481
482
483 /// Optimize merged modules using various IPO passes
484 void LTOCodeGenerator::setCodeGenDebugOptions(const char* options)
485 {
486     std::string ops(options);
487     for (std::string o = getToken(ops); !o.empty(); o = getToken(ops)) {
488         // ParseCommandLineOptions() expects argv[0] to be program name.
489         // Lazily add that.
490         if ( _codegenOptions.empty() ) 
491             _codegenOptions.push_back("libLTO");
492         _codegenOptions.push_back(strdup(o.c_str()));
493     }
494 }