Move the support for using .init_array from ARM to the generic
[oota-llvm.git] / tools / llc / llc.cpp
1 //===-- llc.cpp - Implement the LLVM Native Code Generator ----------------===//
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 is the llc code generator driver. It provides a convenient
11 // command-line interface for generating native assembly-language code
12 // or C code, given LLVM bitcode.
13 //
14 //===----------------------------------------------------------------------===//
15
16 #include "llvm/LLVMContext.h"
17 #include "llvm/Module.h"
18 #include "llvm/PassManager.h"
19 #include "llvm/Pass.h"
20 #include "llvm/ADT/Triple.h"
21 #include "llvm/Support/IRReader.h"
22 #include "llvm/CodeGen/LinkAllAsmWriterComponents.h"
23 #include "llvm/CodeGen/LinkAllCodegenComponents.h"
24 #include "llvm/MC/SubtargetFeature.h"
25 #include "llvm/Support/CommandLine.h"
26 #include "llvm/Support/Debug.h"
27 #include "llvm/Support/FormattedStream.h"
28 #include "llvm/Support/ManagedStatic.h"
29 #include "llvm/Support/PluginLoader.h"
30 #include "llvm/Support/PrettyStackTrace.h"
31 #include "llvm/Support/ToolOutputFile.h"
32 #include "llvm/Support/Host.h"
33 #include "llvm/Support/Signals.h"
34 #include "llvm/Support/TargetRegistry.h"
35 #include "llvm/Support/TargetSelect.h"
36 #include "llvm/Target/TargetData.h"
37 #include "llvm/Target/TargetMachine.h"
38 #include <memory>
39 using namespace llvm;
40
41 // General options for llc.  Other pass-specific options are specified
42 // within the corresponding llc passes, and target-specific options
43 // and back-end code generation options are specified with the target machine.
44 //
45 static cl::opt<std::string>
46 InputFilename(cl::Positional, cl::desc("<input bitcode>"), cl::init("-"));
47
48 static cl::opt<std::string>
49 OutputFilename("o", cl::desc("Output filename"), cl::value_desc("filename"));
50
51 // Determine optimization level.
52 static cl::opt<char>
53 OptLevel("O",
54          cl::desc("Optimization level. [-O0, -O1, -O2, or -O3] "
55                   "(default = '-O2')"),
56          cl::Prefix,
57          cl::ZeroOrMore,
58          cl::init(' '));
59
60 static cl::opt<std::string>
61 TargetTriple("mtriple", cl::desc("Override target triple for module"));
62
63 static cl::opt<std::string>
64 MArch("march", cl::desc("Architecture to generate code for (see --version)"));
65
66 static cl::opt<std::string>
67 MCPU("mcpu",
68   cl::desc("Target a specific cpu type (-mcpu=help for details)"),
69   cl::value_desc("cpu-name"),
70   cl::init(""));
71
72 static cl::list<std::string>
73 MAttrs("mattr",
74   cl::CommaSeparated,
75   cl::desc("Target specific attributes (-mattr=help for details)"),
76   cl::value_desc("a1,+a2,-a3,..."));
77
78 static cl::opt<Reloc::Model>
79 RelocModel("relocation-model",
80              cl::desc("Choose relocation model"),
81              cl::init(Reloc::Default),
82              cl::values(
83             clEnumValN(Reloc::Default, "default",
84                        "Target default relocation model"),
85             clEnumValN(Reloc::Static, "static",
86                        "Non-relocatable code"),
87             clEnumValN(Reloc::PIC_, "pic",
88                        "Fully relocatable, position independent code"),
89             clEnumValN(Reloc::DynamicNoPIC, "dynamic-no-pic",
90                        "Relocatable external references, non-relocatable code"),
91             clEnumValEnd));
92
93 static cl::opt<llvm::CodeModel::Model>
94 CMModel("code-model",
95         cl::desc("Choose code model"),
96         cl::init(CodeModel::Default),
97         cl::values(clEnumValN(CodeModel::Default, "default",
98                               "Target default code model"),
99                    clEnumValN(CodeModel::Small, "small",
100                               "Small code model"),
101                    clEnumValN(CodeModel::Kernel, "kernel",
102                               "Kernel code model"),
103                    clEnumValN(CodeModel::Medium, "medium",
104                               "Medium code model"),
105                    clEnumValN(CodeModel::Large, "large",
106                               "Large code model"),
107                    clEnumValEnd));
108
109 static cl::opt<bool>
110 RelaxAll("mc-relax-all",
111   cl::desc("When used with filetype=obj, "
112            "relax all fixups in the emitted object file"));
113
114 cl::opt<TargetMachine::CodeGenFileType>
115 FileType("filetype", cl::init(TargetMachine::CGFT_AssemblyFile),
116   cl::desc("Choose a file type (not all types are supported by all targets):"),
117   cl::values(
118        clEnumValN(TargetMachine::CGFT_AssemblyFile, "asm",
119                   "Emit an assembly ('.s') file"),
120        clEnumValN(TargetMachine::CGFT_ObjectFile, "obj",
121                   "Emit a native object ('.o') file"),
122        clEnumValN(TargetMachine::CGFT_Null, "null",
123                   "Emit nothing, for performance testing"),
124        clEnumValEnd));
125
126 cl::opt<bool> NoVerify("disable-verify", cl::Hidden,
127                        cl::desc("Do not verify input module"));
128
129 cl::opt<bool> DisableDotLoc("disable-dot-loc", cl::Hidden,
130                             cl::desc("Do not use .loc entries"));
131
132 cl::opt<bool> DisableCFI("disable-cfi", cl::Hidden,
133                          cl::desc("Do not use .cfi_* directives"));
134
135 cl::opt<bool> EnableDwarfDirectory("enable-dwarf-directory", cl::Hidden,
136     cl::desc("Use .file directives with an explicit directory."));
137
138 static cl::opt<bool>
139 DisableRedZone("disable-red-zone",
140   cl::desc("Do not emit code that uses the red zone."),
141   cl::init(false));
142
143 static cl::opt<bool>
144 EnableFPMAD("enable-fp-mad",
145   cl::desc("Enable less precise MAD instructions to be generated"),
146   cl::init(false));
147
148 static cl::opt<bool>
149 DisableFPElim("disable-fp-elim",
150   cl::desc("Disable frame pointer elimination optimization"),
151   cl::init(false));
152
153 static cl::opt<bool>
154 DisableFPElimNonLeaf("disable-non-leaf-fp-elim",
155   cl::desc("Disable frame pointer elimination optimization for non-leaf funcs"),
156   cl::init(false));
157
158 static cl::opt<bool>
159 DisableExcessPrecision("disable-excess-fp-precision",
160   cl::desc("Disable optimizations that may increase FP precision"),
161   cl::init(false));
162
163 static cl::opt<bool>
164 EnableUnsafeFPMath("enable-unsafe-fp-math",
165   cl::desc("Enable optimizations that may decrease FP precision"),
166   cl::init(false));
167
168 static cl::opt<bool>
169 EnableNoInfsFPMath("enable-no-infs-fp-math",
170   cl::desc("Enable FP math optimizations that assume no +-Infs"),
171   cl::init(false));
172
173 static cl::opt<bool>
174 EnableNoNaNsFPMath("enable-no-nans-fp-math",
175   cl::desc("Enable FP math optimizations that assume no NaNs"),
176   cl::init(false));
177
178 static cl::opt<bool>
179 EnableHonorSignDependentRoundingFPMath("enable-sign-dependent-rounding-fp-math",
180   cl::Hidden,
181   cl::desc("Force codegen to assume rounding mode can change dynamically"),
182   cl::init(false));
183
184 static cl::opt<bool>
185 GenerateSoftFloatCalls("soft-float",
186   cl::desc("Generate software floating point library calls"),
187   cl::init(false));
188
189 static cl::opt<llvm::FloatABI::ABIType>
190 FloatABIForCalls("float-abi",
191   cl::desc("Choose float ABI type"),
192   cl::init(FloatABI::Default),
193   cl::values(
194     clEnumValN(FloatABI::Default, "default",
195                "Target default float ABI type"),
196     clEnumValN(FloatABI::Soft, "soft",
197                "Soft float ABI (implied by -soft-float)"),
198     clEnumValN(FloatABI::Hard, "hard",
199                "Hard float ABI (uses FP registers)"),
200     clEnumValEnd));
201
202 static cl::opt<bool>
203 DontPlaceZerosInBSS("nozero-initialized-in-bss",
204   cl::desc("Don't place zero-initialized symbols into bss section"),
205   cl::init(false));
206
207 static cl::opt<bool>
208 EnableGuaranteedTailCallOpt("tailcallopt",
209   cl::desc("Turn fastcc calls into tail calls by (potentially) changing ABI."),
210   cl::init(false));
211
212 static cl::opt<bool>
213 DisableTailCalls("disable-tail-calls",
214   cl::desc("Never emit tail calls"),
215   cl::init(false));
216
217 static cl::opt<unsigned>
218 OverrideStackAlignment("stack-alignment",
219   cl::desc("Override default stack alignment"),
220   cl::init(0));
221
222 static cl::opt<bool>
223 EnableRealignStack("realign-stack",
224   cl::desc("Realign stack if needed"),
225   cl::init(true));
226
227 static cl::opt<bool>
228 DisableSwitchTables(cl::Hidden, "disable-jump-tables",
229   cl::desc("Do not generate jump tables."),
230   cl::init(false));
231
232 static cl::opt<std::string>
233 TrapFuncName("trap-func", cl::Hidden,
234   cl::desc("Emit a call to trap function rather than a trap instruction"),
235   cl::init(""));
236
237 static cl::opt<bool>
238 EnablePIE("enable-pie",
239   cl::desc("Assume the creation of a position independent executable."),
240   cl::init(false));
241
242 static cl::opt<bool>
243 SegmentedStacks("segmented-stacks",
244   cl::desc("Use segmented stacks if possible."),
245   cl::init(false));
246
247 static cl::opt<bool>
248 UseInitArray("use-init-array",
249   cl::desc("Use .init_array instead of .ctors."),
250   cl::init(false));
251
252 // GetFileNameRoot - Helper function to get the basename of a filename.
253 static inline std::string
254 GetFileNameRoot(const std::string &InputFilename) {
255   std::string IFN = InputFilename;
256   std::string outputFilename;
257   int Len = IFN.length();
258   if ((Len > 2) &&
259       IFN[Len-3] == '.' &&
260       ((IFN[Len-2] == 'b' && IFN[Len-1] == 'c') ||
261        (IFN[Len-2] == 'l' && IFN[Len-1] == 'l'))) {
262     outputFilename = std::string(IFN.begin(), IFN.end()-3); // s/.bc/.s/
263   } else {
264     outputFilename = IFN;
265   }
266   return outputFilename;
267 }
268
269 static tool_output_file *GetOutputStream(const char *TargetName,
270                                          Triple::OSType OS,
271                                          const char *ProgName) {
272   // If we don't yet have an output filename, make one.
273   if (OutputFilename.empty()) {
274     if (InputFilename == "-")
275       OutputFilename = "-";
276     else {
277       OutputFilename = GetFileNameRoot(InputFilename);
278
279       switch (FileType) {
280       case TargetMachine::CGFT_AssemblyFile:
281         if (TargetName[0] == 'c') {
282           if (TargetName[1] == 0)
283             OutputFilename += ".cbe.c";
284           else if (TargetName[1] == 'p' && TargetName[2] == 'p')
285             OutputFilename += ".cpp";
286           else
287             OutputFilename += ".s";
288         } else
289           OutputFilename += ".s";
290         break;
291       case TargetMachine::CGFT_ObjectFile:
292         if (OS == Triple::Win32)
293           OutputFilename += ".obj";
294         else
295           OutputFilename += ".o";
296         break;
297       case TargetMachine::CGFT_Null:
298         OutputFilename += ".null";
299         break;
300       }
301     }
302   }
303
304   // Decide if we need "binary" output.
305   bool Binary = false;
306   switch (FileType) {
307   case TargetMachine::CGFT_AssemblyFile:
308     break;
309   case TargetMachine::CGFT_ObjectFile:
310   case TargetMachine::CGFT_Null:
311     Binary = true;
312     break;
313   }
314
315   // Open the file.
316   std::string error;
317   unsigned OpenFlags = 0;
318   if (Binary) OpenFlags |= raw_fd_ostream::F_Binary;
319   tool_output_file *FDOut = new tool_output_file(OutputFilename.c_str(), error,
320                                                  OpenFlags);
321   if (!error.empty()) {
322     errs() << error << '\n';
323     delete FDOut;
324     return 0;
325   }
326
327   return FDOut;
328 }
329
330 // main - Entry point for the llc compiler.
331 //
332 int main(int argc, char **argv) {
333   sys::PrintStackTraceOnErrorSignal();
334   PrettyStackTraceProgram X(argc, argv);
335
336   // Enable debug stream buffering.
337   EnableDebugBuffering = true;
338
339   LLVMContext &Context = getGlobalContext();
340   llvm_shutdown_obj Y;  // Call llvm_shutdown() on exit.
341
342   // Initialize targets first, so that --version shows registered targets.
343   InitializeAllTargets();
344   InitializeAllTargetMCs();
345   InitializeAllAsmPrinters();
346   InitializeAllAsmParsers();
347
348   // Register the target printer for --version.
349   cl::AddExtraVersionPrinter(TargetRegistry::printRegisteredTargetsForVersion);
350
351   cl::ParseCommandLineOptions(argc, argv, "llvm system compiler\n");
352
353   // Load the module to be compiled...
354   SMDiagnostic Err;
355   std::auto_ptr<Module> M;
356
357   M.reset(ParseIRFile(InputFilename, Err, Context));
358   if (M.get() == 0) {
359     Err.print(argv[0], errs());
360     return 1;
361   }
362   Module &mod = *M.get();
363
364   // If we are supposed to override the target triple, do so now.
365   if (!TargetTriple.empty())
366     mod.setTargetTriple(Triple::normalize(TargetTriple));
367
368   // Figure out the target triple.
369   Triple TheTriple(mod.getTargetTriple());
370   if (TheTriple.getTriple().empty())
371     TheTriple.setTriple(sys::getDefaultTargetTriple());
372
373   // Get the target specific parser.
374   std::string Error;
375   const Target *TheTarget = TargetRegistry::lookupTarget(MArch, TheTriple,
376                                                          Error);
377   if (!TheTarget) {
378     errs() << argv[0] << ": " << Error;
379     return 1;
380   }
381
382   // Package up features to be passed to target/subtarget
383   std::string FeaturesStr;
384   if (MAttrs.size()) {
385     SubtargetFeatures Features;
386     for (unsigned i = 0; i != MAttrs.size(); ++i)
387       Features.AddFeature(MAttrs[i]);
388     FeaturesStr = Features.getString();
389   }
390
391   CodeGenOpt::Level OLvl = CodeGenOpt::Default;
392   switch (OptLevel) {
393   default:
394     errs() << argv[0] << ": invalid optimization level.\n";
395     return 1;
396   case ' ': break;
397   case '0': OLvl = CodeGenOpt::None; break;
398   case '1': OLvl = CodeGenOpt::Less; break;
399   case '2': OLvl = CodeGenOpt::Default; break;
400   case '3': OLvl = CodeGenOpt::Aggressive; break;
401   }
402
403   TargetOptions Options;
404   Options.LessPreciseFPMADOption = EnableFPMAD;
405   Options.NoFramePointerElim = DisableFPElim;
406   Options.NoFramePointerElimNonLeaf = DisableFPElimNonLeaf;
407   Options.NoExcessFPPrecision = DisableExcessPrecision;
408   Options.UnsafeFPMath = EnableUnsafeFPMath;
409   Options.NoInfsFPMath = EnableNoInfsFPMath;
410   Options.NoNaNsFPMath = EnableNoNaNsFPMath;
411   Options.HonorSignDependentRoundingFPMathOption =
412       EnableHonorSignDependentRoundingFPMath;
413   Options.UseSoftFloat = GenerateSoftFloatCalls;
414   if (FloatABIForCalls != FloatABI::Default)
415     Options.FloatABIType = FloatABIForCalls;
416   Options.NoZerosInBSS = DontPlaceZerosInBSS;
417   Options.GuaranteedTailCallOpt = EnableGuaranteedTailCallOpt;
418   Options.DisableTailCalls = DisableTailCalls;
419   Options.StackAlignmentOverride = OverrideStackAlignment;
420   Options.RealignStack = EnableRealignStack;
421   Options.DisableJumpTables = DisableSwitchTables;
422   Options.TrapFuncName = TrapFuncName;
423   Options.PositionIndependentExecutable = EnablePIE;
424   Options.EnableSegmentedStacks = SegmentedStacks;
425   Options.UseInitArray = UseInitArray;
426
427   std::auto_ptr<TargetMachine>
428     target(TheTarget->createTargetMachine(TheTriple.getTriple(),
429                                           MCPU, FeaturesStr, Options,
430                                           RelocModel, CMModel, OLvl));
431   assert(target.get() && "Could not allocate target machine!");
432   TargetMachine &Target = *target.get();
433
434   if (DisableDotLoc)
435     Target.setMCUseLoc(false);
436
437   if (DisableCFI)
438     Target.setMCUseCFI(false);
439
440   if (EnableDwarfDirectory)
441     Target.setMCUseDwarfDirectory(true);
442
443   if (GenerateSoftFloatCalls)
444     FloatABIForCalls = FloatABI::Soft;
445
446   // Disable .loc support for older OS X versions.
447   if (TheTriple.isMacOSX() &&
448       TheTriple.isMacOSXVersionLT(10, 6))
449     Target.setMCUseLoc(false);
450
451   // Figure out where we are going to send the output...
452   OwningPtr<tool_output_file> Out
453     (GetOutputStream(TheTarget->getName(), TheTriple.getOS(), argv[0]));
454   if (!Out) return 1;
455
456   // Build up all of the passes that we want to do to the module.
457   PassManager PM;
458
459   // Add the target data from the target machine, if it exists, or the module.
460   if (const TargetData *TD = Target.getTargetData())
461     PM.add(new TargetData(*TD));
462   else
463     PM.add(new TargetData(&mod));
464
465   // Override default to generate verbose assembly.
466   Target.setAsmVerbosityDefault(true);
467
468   if (RelaxAll) {
469     if (FileType != TargetMachine::CGFT_ObjectFile)
470       errs() << argv[0]
471              << ": warning: ignoring -mc-relax-all because filetype != obj";
472     else
473       Target.setMCRelaxAll(true);
474   }
475
476   {
477     formatted_raw_ostream FOS(Out->os());
478
479     // Ask the target to add backend passes as necessary.
480     if (Target.addPassesToEmitFile(PM, FOS, FileType, NoVerify)) {
481       errs() << argv[0] << ": target does not support generation of this"
482              << " file type!\n";
483       return 1;
484     }
485
486     // Before executing passes, print the final values of the LLVM options.
487     cl::PrintOptionValues();
488
489     PM.run(mod);
490   }
491
492   // Declare success.
493   Out->keep();
494
495   return 0;
496 }