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