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