hopefully teach cmake to build the .inc file.
[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 #include "llvm/Constants.h"
19 #include "llvm/DerivedTypes.h"
20 #include "llvm/Linker.h"
21 #include "llvm/LLVMContext.h"
22 #include "llvm/Module.h"
23 #include "llvm/PassManager.h"
24 #include "llvm/ADT/StringExtras.h"
25 #include "llvm/ADT/Triple.h"
26 #include "llvm/Analysis/Passes.h"
27 #include "llvm/Bitcode/ReaderWriter.h"
28 #include "llvm/MC/MCAsmInfo.h"
29 #include "llvm/MC/MCContext.h"
30 #include "llvm/Target/Mangler.h"
31 #include "llvm/Target/SubtargetFeature.h"
32 #include "llvm/Target/TargetOptions.h"
33 #include "llvm/Target/TargetData.h"
34 #include "llvm/Target/TargetMachine.h"
35 #include "llvm/Target/TargetRegistry.h"
36 #include "llvm/Target/TargetSelect.h"
37 #include "llvm/Support/CommandLine.h"
38 #include "llvm/Support/FormattedStream.h"
39 #include "llvm/Support/MemoryBuffer.h"
40 #include "llvm/Support/StandardPasses.h"
41 #include "llvm/Support/SystemUtils.h"
42 #include "llvm/System/Host.h"
43 #include "llvm/System/Program.h"
44 #include "llvm/System/Signals.h"
45 #include "llvm/Config/config.h"
46 #include <cstdlib>
47 #include <unistd.h>
48 #include <fcntl.h>
49
50
51 using namespace llvm;
52
53 static cl::opt<bool> DisableInline("disable-inlining",
54   cl::desc("Do not run the inliner pass"));
55
56
57 const char* LTOCodeGenerator::getVersionString()
58 {
59 #ifdef LLVM_VERSION_INFO
60     return PACKAGE_NAME " version " PACKAGE_VERSION ", " LLVM_VERSION_INFO;
61 #else
62     return PACKAGE_NAME " version " PACKAGE_VERSION;
63 #endif
64 }
65
66
67 LTOCodeGenerator::LTOCodeGenerator() 
68     : _context(getGlobalContext()),
69       _linker("LinkTimeOptimizer", "ld-temp.o", _context), _target(NULL),
70       _emitDwarfDebugInfo(false), _scopeRestrictionsDone(false),
71       _codeModel(LTO_CODEGEN_PIC_MODEL_DYNAMIC),
72       _nativeObjectFile(NULL), _assemblerPath(NULL)
73 {
74     InitializeAllTargets();
75     InitializeAllAsmPrinters();
76 }
77
78 LTOCodeGenerator::~LTOCodeGenerator()
79 {
80     delete _target;
81     delete _nativeObjectFile;
82 }
83
84
85
86 bool LTOCodeGenerator::addModule(LTOModule* mod, std::string& errMsg)
87 {
88     return _linker.LinkInModule(mod->getLLVVMModule(), &errMsg);
89 }
90     
91
92 bool LTOCodeGenerator::setDebugInfo(lto_debug_model debug, std::string& errMsg)
93 {
94     switch (debug) {
95         case LTO_DEBUG_MODEL_NONE:
96             _emitDwarfDebugInfo = false;
97             return false;
98             
99         case LTO_DEBUG_MODEL_DWARF:
100             _emitDwarfDebugInfo = true;
101             return false;
102     }
103     errMsg = "unknown debug format";
104     return true;
105 }
106
107
108 bool LTOCodeGenerator::setCodePICModel(lto_codegen_model model, 
109                                        std::string& errMsg)
110 {
111     switch (model) {
112         case LTO_CODEGEN_PIC_MODEL_STATIC:
113         case LTO_CODEGEN_PIC_MODEL_DYNAMIC:
114         case LTO_CODEGEN_PIC_MODEL_DYNAMIC_NO_PIC:
115             _codeModel = model;
116             return false;
117     }
118     errMsg = "unknown pic model";
119     return true;
120 }
121
122 void LTOCodeGenerator::setAssemblerPath(const char* path)
123 {
124     if ( _assemblerPath )
125         delete _assemblerPath;
126     _assemblerPath = new sys::Path(path);
127 }
128
129 void LTOCodeGenerator::addMustPreserveSymbol(const char* sym)
130 {
131     _mustPreserveSymbols[sym] = 1;
132 }
133
134
135 bool LTOCodeGenerator::writeMergedModules(const char *path,
136                                           std::string &errMsg) {
137   if (determineTarget(errMsg))
138     return true;
139
140   // mark which symbols can not be internalized 
141   applyScopeRestrictions();
142
143   // create output file
144   std::string ErrInfo;
145   raw_fd_ostream Out(path, ErrInfo,
146                      raw_fd_ostream::F_Binary);
147   if (!ErrInfo.empty()) {
148     errMsg = "could not open bitcode file for writing: ";
149     errMsg += path;
150     return true;
151   }
152     
153   // write bitcode to it
154   WriteBitcodeToFile(_linker.getModule(), Out);
155   Out.close();
156
157   if (Out.has_error()) {
158     errMsg = "could not write bitcode file: ";
159     errMsg += path;
160     Out.clear_error();
161     return true;
162   }
163   
164   return false;
165 }
166
167
168 const void* LTOCodeGenerator::compile(size_t* length, std::string& errMsg)
169 {
170     // make unique temp .s file to put generated assembly code
171     sys::Path uniqueAsmPath("lto-llvm.s");
172     if ( uniqueAsmPath.createTemporaryFileOnDisk(true, &errMsg) )
173         return NULL;
174     sys::RemoveFileOnSignal(uniqueAsmPath);
175        
176     // generate assembly code
177     bool genResult = false;
178     {
179       raw_fd_ostream asmFD(uniqueAsmPath.c_str(), errMsg);
180       formatted_raw_ostream asmFile(asmFD);
181       if (!errMsg.empty())
182         return NULL;
183       genResult = this->generateAssemblyCode(asmFile, errMsg);
184     }
185     if ( genResult ) {
186         uniqueAsmPath.eraseFromDisk();
187         return NULL;
188     }
189     
190     // make unique temp .o file to put generated object file
191     sys::PathWithStatus uniqueObjPath("lto-llvm.o");
192     if ( uniqueObjPath.createTemporaryFileOnDisk(true, &errMsg) ) {
193         uniqueAsmPath.eraseFromDisk();
194         return NULL;
195     }
196     sys::RemoveFileOnSignal(uniqueObjPath);
197
198     // assemble the assembly code
199     const std::string& uniqueObjStr = uniqueObjPath.str();
200     bool asmResult = this->assemble(uniqueAsmPath.str(), uniqueObjStr, errMsg);
201     if ( !asmResult ) {
202         // remove old buffer if compile() called twice
203         delete _nativeObjectFile;
204         
205         // read .o file into memory buffer
206         _nativeObjectFile = MemoryBuffer::getFile(uniqueObjStr.c_str(),&errMsg);
207     }
208
209     // remove temp files
210     uniqueAsmPath.eraseFromDisk();
211     uniqueObjPath.eraseFromDisk();
212
213     // return buffer, unless error
214     if ( _nativeObjectFile == NULL )
215         return NULL;
216     *length = _nativeObjectFile->getBufferSize();
217     return _nativeObjectFile->getBufferStart();
218 }
219
220
221 bool LTOCodeGenerator::assemble(const std::string& asmPath, 
222                                 const std::string& objPath, std::string& errMsg)
223 {
224     sys::Path tool;
225     bool needsCompilerOptions = true;
226     if ( _assemblerPath ) {
227         tool = *_assemblerPath;
228         needsCompilerOptions = false;
229     } else {
230         // find compiler driver
231         tool = sys::Program::FindProgramByName("gcc");
232         if ( tool.isEmpty() ) {
233             errMsg = "can't locate gcc";
234             return true;
235         }
236     }
237
238     // build argument list
239     std::vector<const char*> args;
240     llvm::Triple targetTriple(_linker.getModule()->getTargetTriple());
241     const char *arch = targetTriple.getArchNameForAssembler();
242
243     args.push_back(tool.c_str());
244
245     if (targetTriple.getOS() == Triple::Darwin) {
246         // darwin specific command line options
247         if (arch != NULL) {
248             args.push_back("-arch");
249             args.push_back(arch);
250         }
251         // add -static to assembler command line when code model requires
252         if ( (_assemblerPath != NULL) &&
253             (_codeModel == LTO_CODEGEN_PIC_MODEL_STATIC) )
254             args.push_back("-static");
255     }
256     if ( needsCompilerOptions ) {
257         args.push_back("-c");
258         args.push_back("-x");
259         args.push_back("assembler");
260     }
261     args.push_back("-o");
262     args.push_back(objPath.c_str());
263     args.push_back(asmPath.c_str());
264     args.push_back(0);
265
266     // invoke assembler
267     if ( sys::Program::ExecuteAndWait(tool, &args[0], 0, 0, 0, 0, &errMsg) ) {
268         errMsg = "error in assembly";    
269         return true;
270     }
271     return false; // success
272 }
273
274
275
276 bool LTOCodeGenerator::determineTarget(std::string& errMsg)
277 {
278     if ( _target == NULL ) {
279         std::string Triple = _linker.getModule()->getTargetTriple();
280         if (Triple.empty())
281           Triple = sys::getHostTriple();
282
283         // create target machine from info for merged modules
284         const Target *march = TargetRegistry::lookupTarget(Triple, errMsg);
285         if ( march == NULL )
286             return true;
287
288         // The relocation model is actually a static member of TargetMachine
289         // and needs to be set before the TargetMachine is instantiated.
290         switch( _codeModel ) {
291         case LTO_CODEGEN_PIC_MODEL_STATIC:
292             TargetMachine::setRelocationModel(Reloc::Static);
293             break;
294         case LTO_CODEGEN_PIC_MODEL_DYNAMIC:
295             TargetMachine::setRelocationModel(Reloc::PIC_);
296             break;
297         case LTO_CODEGEN_PIC_MODEL_DYNAMIC_NO_PIC:
298             TargetMachine::setRelocationModel(Reloc::DynamicNoPIC);
299             break;
300         }
301
302         // construct LTModule, hand over ownership of module and target
303         SubtargetFeatures Features;
304         Features.getDefaultSubtargetFeatures("" /* cpu */, llvm::Triple(Triple));
305         std::string FeatureStr = Features.getString();
306         _target = march->createTargetMachine(Triple, FeatureStr);
307     }
308     return false;
309 }
310
311 void LTOCodeGenerator::applyScopeRestrictions() {
312   if (_scopeRestrictionsDone) return;
313   Module *mergedModule = _linker.getModule();
314
315   // Start off with a verification pass.
316   PassManager passes;
317   passes.add(createVerifierPass());
318
319   // mark which symbols can not be internalized 
320   if (!_mustPreserveSymbols.empty()) {
321     MCContext Context(*_target->getMCAsmInfo());
322     Mangler mangler(Context, *_target->getTargetData());
323     std::vector<const char*> mustPreserveList;
324     for (Module::iterator f = mergedModule->begin(),
325          e = mergedModule->end(); f != e; ++f) {
326       if (!f->isDeclaration() &&
327           _mustPreserveSymbols.count(mangler.getNameWithPrefix(f)))
328         mustPreserveList.push_back(::strdup(f->getNameStr().c_str()));
329     }
330     for (Module::global_iterator v = mergedModule->global_begin(), 
331          e = mergedModule->global_end(); v !=  e; ++v) {
332       if (!v->isDeclaration() &&
333           _mustPreserveSymbols.count(mangler.getNameWithPrefix(v)))
334         mustPreserveList.push_back(::strdup(v->getNameStr().c_str()));
335     }
336     passes.add(createInternalizePass(mustPreserveList));
337   }
338   
339   // apply scope restrictions
340   passes.run(*mergedModule);
341   
342   _scopeRestrictionsDone = true;
343 }
344
345 /// Optimize merged modules using various IPO passes
346 bool LTOCodeGenerator::generateAssemblyCode(formatted_raw_ostream& out,
347                                             std::string& errMsg)
348 {
349     if ( this->determineTarget(errMsg) ) 
350         return true;
351
352     // mark which symbols can not be internalized 
353     this->applyScopeRestrictions();
354
355     Module* mergedModule = _linker.getModule();
356
357     // if options were requested, set them
358     if ( !_codegenOptions.empty() )
359         cl::ParseCommandLineOptions(_codegenOptions.size(), 
360                                     const_cast<char **>(&_codegenOptions[0]));
361
362     // Instantiate the pass manager to organize the passes.
363     PassManager passes;
364
365     // Start off with a verification pass.
366     passes.add(createVerifierPass());
367
368     // Add an appropriate TargetData instance for this module...
369     passes.add(new TargetData(*_target->getTargetData()));
370     
371     createStandardLTOPasses(&passes, /*Internalize=*/ false, !DisableInline,
372                             /*VerifyEach=*/ false);
373
374     // Make sure everything is still good.
375     passes.add(createVerifierPass());
376
377     FunctionPassManager* codeGenPasses = new FunctionPassManager(mergedModule);
378
379     codeGenPasses->add(new TargetData(*_target->getTargetData()));
380
381     if (_target->addPassesToEmitFile(*codeGenPasses, out,
382                                      TargetMachine::CGFT_AssemblyFile,
383                                      CodeGenOpt::Aggressive)) {
384       errMsg = "target file type not supported";
385       return true;
386     }
387
388     // Run our queue of passes all at once now, efficiently.
389     passes.run(*mergedModule);
390
391     // Run the code generator, and write assembly file
392     codeGenPasses->doInitialization();
393
394     for (Module::iterator
395            it = mergedModule->begin(), e = mergedModule->end(); it != e; ++it)
396       if (!it->isDeclaration())
397         codeGenPasses->run(*it);
398
399     codeGenPasses->doFinalization();
400
401     return false; // success
402 }
403
404
405 /// Optimize merged modules using various IPO passes
406 void LTOCodeGenerator::setCodeGenDebugOptions(const char* options)
407 {
408     for (std::pair<StringRef, StringRef> o = getToken(options);
409          !o.first.empty(); o = getToken(o.second)) {
410         // ParseCommandLineOptions() expects argv[0] to be program name.
411         // Lazily add that.
412         if ( _codegenOptions.empty() ) 
413             _codegenOptions.push_back("libLTO");
414         _codegenOptions.push_back(strdup(o.first.str().c_str()));
415     }
416 }