Fix support to use NEON for single precision fp math.
[llvm/avr.git] / tools / lto / LTOCodeGenerator.cpp
blob598da7fa6649055078d0d035d99d1fdd9797fd2f
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.
13 //===----------------------------------------------------------------------===//
15 #include "LTOModule.h"
16 #include "LTOCodeGenerator.h"
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/Analysis/Passes.h"
28 #include "llvm/Analysis/LoopPass.h"
29 #include "llvm/Analysis/Verifier.h"
30 #include "llvm/Bitcode/ReaderWriter.h"
31 #include "llvm/CodeGen/FileWriters.h"
32 #include "llvm/Support/CommandLine.h"
33 #include "llvm/Support/FormattedStream.h"
34 #include "llvm/Support/Mangler.h"
35 #include "llvm/Support/MemoryBuffer.h"
36 #include "llvm/Support/StandardPasses.h"
37 #include "llvm/Support/SystemUtils.h"
38 #include "llvm/System/Host.h"
39 #include "llvm/System/Signals.h"
40 #include "llvm/Target/SubtargetFeature.h"
41 #include "llvm/Target/TargetOptions.h"
42 #include "llvm/Target/TargetAsmInfo.h"
43 #include "llvm/Target/TargetData.h"
44 #include "llvm/Target/TargetMachine.h"
45 #include "llvm/Target/TargetRegistry.h"
46 #include "llvm/Target/TargetSelect.h"
47 #include "llvm/Transforms/IPO.h"
48 #include "llvm/Transforms/Scalar.h"
49 #include "llvm/Config/config.h"
52 #include <cstdlib>
53 #include <fstream>
54 #include <unistd.h>
55 #include <fcntl.h>
58 using namespace llvm;
60 static cl::opt<bool> DisableInline("disable-inlining",
61 cl::desc("Do not run the inliner pass"));
64 const char* LTOCodeGenerator::getVersionString()
66 #ifdef LLVM_VERSION_INFO
67 return PACKAGE_NAME " version " PACKAGE_VERSION ", " LLVM_VERSION_INFO;
68 #else
69 return PACKAGE_NAME " version " PACKAGE_VERSION;
70 #endif
74 LTOCodeGenerator::LTOCodeGenerator()
75 : _context(getGlobalContext()),
76 _linker("LinkTimeOptimizer", "ld-temp.o", _context), _target(NULL),
77 _emitDwarfDebugInfo(false), _scopeRestrictionsDone(false),
78 _codeModel(LTO_CODEGEN_PIC_MODEL_DYNAMIC),
79 _nativeObjectFile(NULL), _assemblerPath(NULL)
81 InitializeAllTargets();
82 InitializeAllAsmPrinters();
85 LTOCodeGenerator::~LTOCodeGenerator()
87 delete _target;
88 delete _nativeObjectFile;
93 bool LTOCodeGenerator::addModule(LTOModule* mod, std::string& errMsg)
95 return _linker.LinkInModule(mod->getLLVVMModule(), &errMsg);
99 bool LTOCodeGenerator::setDebugInfo(lto_debug_model debug, std::string& errMsg)
101 switch (debug) {
102 case LTO_DEBUG_MODEL_NONE:
103 _emitDwarfDebugInfo = false;
104 return false;
106 case LTO_DEBUG_MODEL_DWARF:
107 _emitDwarfDebugInfo = true;
108 return false;
110 errMsg = "unknown debug format";
111 return true;
115 bool LTOCodeGenerator::setCodePICModel(lto_codegen_model model,
116 std::string& errMsg)
118 switch (model) {
119 case LTO_CODEGEN_PIC_MODEL_STATIC:
120 case LTO_CODEGEN_PIC_MODEL_DYNAMIC:
121 case LTO_CODEGEN_PIC_MODEL_DYNAMIC_NO_PIC:
122 _codeModel = model;
123 return false;
125 errMsg = "unknown pic model";
126 return true;
129 void LTOCodeGenerator::setAssemblerPath(const char* path)
131 if ( _assemblerPath )
132 delete _assemblerPath;
133 _assemblerPath = new sys::Path(path);
136 void LTOCodeGenerator::addMustPreserveSymbol(const char* sym)
138 _mustPreserveSymbols[sym] = 1;
142 bool LTOCodeGenerator::writeMergedModules(const char* path, std::string& errMsg)
144 if ( this->determineTarget(errMsg) )
145 return true;
147 // mark which symbols can not be internalized
148 this->applyScopeRestrictions();
150 // create output file
151 std::ofstream out(path, std::ios_base::out|std::ios::trunc|std::ios::binary);
152 if ( out.fail() ) {
153 errMsg = "could not open bitcode file for writing: ";
154 errMsg += path;
155 return true;
158 // write bitcode to it
159 WriteBitcodeToFile(_linker.getModule(), out);
160 if ( out.fail() ) {
161 errMsg = "could not write bitcode file: ";
162 errMsg += path;
163 return true;
166 return false;
170 const void* LTOCodeGenerator::compile(size_t* length, std::string& errMsg)
172 // make unique temp .s file to put generated assembly code
173 sys::Path uniqueAsmPath("lto-llvm.s");
174 if ( uniqueAsmPath.createTemporaryFileOnDisk(true, &errMsg) )
175 return NULL;
176 sys::RemoveFileOnSignal(uniqueAsmPath);
178 // generate assembly code
179 bool genResult = false;
181 raw_fd_ostream asmFD(raw_fd_ostream(uniqueAsmPath.c_str(),
182 /*Binary=*/false, /*Force=*/true,
183 errMsg));
184 formatted_raw_ostream asmFile(asmFD);
185 if (!errMsg.empty())
186 return NULL;
187 genResult = this->generateAssemblyCode(asmFile, errMsg);
189 if ( genResult ) {
190 if ( uniqueAsmPath.exists() )
191 uniqueAsmPath.eraseFromDisk();
192 return NULL;
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;
202 sys::RemoveFileOnSignal(uniqueObjPath);
204 // assemble the assembly code
205 const std::string& uniqueObjStr = uniqueObjPath.toString();
206 bool asmResult = this->assemble(uniqueAsmPath.toString(),
207 uniqueObjStr, errMsg);
208 if ( !asmResult ) {
209 // remove old buffer if compile() called twice
210 delete _nativeObjectFile;
212 // read .o file into memory buffer
213 _nativeObjectFile = MemoryBuffer::getFile(uniqueObjStr.c_str(),&errMsg);
216 // remove temp files
217 uniqueAsmPath.eraseFromDisk();
218 uniqueObjPath.eraseFromDisk();
220 // return buffer, unless error
221 if ( _nativeObjectFile == NULL )
222 return NULL;
223 *length = _nativeObjectFile->getBufferSize();
224 return _nativeObjectFile->getBufferStart();
228 bool LTOCodeGenerator::assemble(const std::string& asmPath,
229 const std::string& objPath, std::string& errMsg)
231 sys::Path tool;
232 bool needsCompilerOptions = true;
233 if ( _assemblerPath ) {
234 tool = *_assemblerPath;
235 needsCompilerOptions = false;
236 } else {
237 // find compiler driver
238 tool = sys::Program::FindProgramByName("gcc");
239 if ( tool.isEmpty() ) {
240 errMsg = "can't locate gcc";
241 return true;
245 // build argument list
246 std::vector<const char*> args;
247 std::string targetTriple = _linker.getModule()->getTargetTriple();
248 args.push_back(tool.c_str());
249 if ( targetTriple.find("darwin") != std::string::npos ) {
250 // darwin specific command line options
251 if (strncmp(targetTriple.c_str(), "i386-apple-", 11) == 0) {
252 args.push_back("-arch");
253 args.push_back("i386");
255 else if (strncmp(targetTriple.c_str(), "x86_64-apple-", 13) == 0) {
256 args.push_back("-arch");
257 args.push_back("x86_64");
259 else if (strncmp(targetTriple.c_str(), "powerpc-apple-", 14) == 0) {
260 args.push_back("-arch");
261 args.push_back("ppc");
263 else if (strncmp(targetTriple.c_str(), "powerpc64-apple-", 16) == 0) {
264 args.push_back("-arch");
265 args.push_back("ppc64");
267 else if (strncmp(targetTriple.c_str(), "arm-apple-", 10) == 0) {
268 args.push_back("-arch");
269 args.push_back("arm");
271 else if ((strncmp(targetTriple.c_str(), "armv4t-apple-", 13) == 0) ||
272 (strncmp(targetTriple.c_str(), "thumbv4t-apple-", 15) == 0)) {
273 args.push_back("-arch");
274 args.push_back("armv4t");
276 else if ((strncmp(targetTriple.c_str(), "armv5-apple-", 12) == 0) ||
277 (strncmp(targetTriple.c_str(), "armv5e-apple-", 13) == 0) ||
278 (strncmp(targetTriple.c_str(), "thumbv5-apple-", 14) == 0) ||
279 (strncmp(targetTriple.c_str(), "thumbv5e-apple-", 15) == 0)) {
280 args.push_back("-arch");
281 args.push_back("armv5");
283 else if ((strncmp(targetTriple.c_str(), "armv6-apple-", 12) == 0) ||
284 (strncmp(targetTriple.c_str(), "thumbv6-apple-", 14) == 0)) {
285 args.push_back("-arch");
286 args.push_back("armv6");
288 else if ((strncmp(targetTriple.c_str(), "armv7-apple-", 12) == 0) ||
289 (strncmp(targetTriple.c_str(), "thumbv7-apple-", 14) == 0)) {
290 args.push_back("-arch");
291 args.push_back("armv7");
293 // add -static to assembler command line when code model requires
294 if ( (_assemblerPath != NULL) && (_codeModel == LTO_CODEGEN_PIC_MODEL_STATIC) )
295 args.push_back("-static");
297 if ( needsCompilerOptions ) {
298 args.push_back("-c");
299 args.push_back("-x");
300 args.push_back("assembler");
302 args.push_back("-o");
303 args.push_back(objPath.c_str());
304 args.push_back(asmPath.c_str());
305 args.push_back(0);
307 // invoke assembler
308 if ( sys::Program::ExecuteAndWait(tool, &args[0], 0, 0, 0, 0, &errMsg) ) {
309 errMsg = "error in assembly";
310 return true;
312 return false; // success
317 bool LTOCodeGenerator::determineTarget(std::string& errMsg)
319 if ( _target == NULL ) {
320 std::string Triple = _linker.getModule()->getTargetTriple();
321 if (Triple.empty())
322 Triple = sys::getHostTriple();
324 // create target machine from info for merged modules
325 const Target *march = TargetRegistry::lookupTarget(Triple, errMsg);
326 if ( march == NULL )
327 return true;
329 // The relocation model is actually a static member of TargetMachine
330 // and needs to be set before the TargetMachine is instantiated.
331 switch( _codeModel ) {
332 case LTO_CODEGEN_PIC_MODEL_STATIC:
333 TargetMachine::setRelocationModel(Reloc::Static);
334 break;
335 case LTO_CODEGEN_PIC_MODEL_DYNAMIC:
336 TargetMachine::setRelocationModel(Reloc::PIC_);
337 break;
338 case LTO_CODEGEN_PIC_MODEL_DYNAMIC_NO_PIC:
339 TargetMachine::setRelocationModel(Reloc::DynamicNoPIC);
340 break;
343 // construct LTModule, hand over ownership of module and target
344 std::string FeatureStr = getFeatureString(Triple.c_str());
345 _target = march->createTargetMachine(Triple, FeatureStr);
347 return false;
350 void LTOCodeGenerator::applyScopeRestrictions()
352 if ( !_scopeRestrictionsDone ) {
353 Module* mergedModule = _linker.getModule();
355 // Start off with a verification pass.
356 PassManager passes;
357 passes.add(createVerifierPass());
359 // mark which symbols can not be internalized
360 if ( !_mustPreserveSymbols.empty() ) {
361 Mangler mangler(*mergedModule,
362 _target->getTargetAsmInfo()->getGlobalPrefix());
363 std::vector<const char*> mustPreserveList;
364 for (Module::iterator f = mergedModule->begin(),
365 e = mergedModule->end(); f != e; ++f) {
366 if ( !f->isDeclaration()
367 && _mustPreserveSymbols.count(mangler.getMangledName(f)) )
368 mustPreserveList.push_back(::strdup(f->getNameStr().c_str()));
370 for (Module::global_iterator v = mergedModule->global_begin(),
371 e = mergedModule->global_end(); v != e; ++v) {
372 if ( !v->isDeclaration()
373 && _mustPreserveSymbols.count(mangler.getMangledName(v)) )
374 mustPreserveList.push_back(::strdup(v->getNameStr().c_str()));
376 passes.add(createInternalizePass(mustPreserveList));
378 // apply scope restrictions
379 passes.run(*mergedModule);
381 _scopeRestrictionsDone = true;
385 /// Optimize merged modules using various IPO passes
386 bool LTOCodeGenerator::generateAssemblyCode(formatted_raw_ostream& out,
387 std::string& errMsg)
389 if ( this->determineTarget(errMsg) )
390 return true;
392 // mark which symbols can not be internalized
393 this->applyScopeRestrictions();
395 Module* mergedModule = _linker.getModule();
397 // If target supports exception handling then enable it now.
398 if ( _target->getTargetAsmInfo()->doesSupportExceptionHandling() )
399 llvm::ExceptionHandling = true;
401 // if options were requested, set them
402 if ( !_codegenOptions.empty() )
403 cl::ParseCommandLineOptions(_codegenOptions.size(),
404 (char**)&_codegenOptions[0]);
406 // Instantiate the pass manager to organize the passes.
407 PassManager passes;
409 // Start off with a verification pass.
410 passes.add(createVerifierPass());
412 // Add an appropriate TargetData instance for this module...
413 passes.add(new TargetData(*_target->getTargetData()));
415 createStandardLTOPasses(&passes, /*Internalize=*/ false, !DisableInline,
416 /*VerifyEach=*/ false);
418 // Make sure everything is still good.
419 passes.add(createVerifierPass());
421 FunctionPassManager* codeGenPasses =
422 new FunctionPassManager(new ExistingModuleProvider(mergedModule));
424 codeGenPasses->add(new TargetData(*_target->getTargetData()));
426 ObjectCodeEmitter* oce = NULL;
428 switch (_target->addPassesToEmitFile(*codeGenPasses, out,
429 TargetMachine::AssemblyFile,
430 CodeGenOpt::Aggressive)) {
431 case FileModel::MachOFile:
432 oce = AddMachOWriter(*codeGenPasses, out, *_target);
433 break;
434 case FileModel::ElfFile:
435 oce = AddELFWriter(*codeGenPasses, out, *_target);
436 break;
437 case FileModel::AsmFile:
438 break;
439 case FileModel::Error:
440 case FileModel::None:
441 errMsg = "target file type not supported";
442 return true;
445 if (_target->addPassesToEmitFileFinish(*codeGenPasses, oce,
446 CodeGenOpt::Aggressive)) {
447 errMsg = "target does not support generation of this file type";
448 return true;
451 // Run our queue of passes all at once now, efficiently.
452 passes.run(*mergedModule);
454 // Run the code generator, and write assembly file
455 codeGenPasses->doInitialization();
457 for (Module::iterator
458 it = mergedModule->begin(), e = mergedModule->end(); it != e; ++it)
459 if (!it->isDeclaration())
460 codeGenPasses->run(*it);
462 codeGenPasses->doFinalization();
464 out.flush();
466 return false; // success
470 /// Optimize merged modules using various IPO passes
471 void LTOCodeGenerator::setCodeGenDebugOptions(const char* options)
473 std::string ops(options);
474 for (std::string o = getToken(ops); !o.empty(); o = getToken(ops)) {
475 // ParseCommandLineOptions() expects argv[0] to be program name.
476 // Lazily add that.
477 if ( _codegenOptions.empty() )
478 _codegenOptions.push_back("libLTO");
479 _codegenOptions.push_back(strdup(o.c_str()));