Sink SubtargetFeature and TargetInstrItineraries (renamed MCInstrItineraries) into MC.
[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/Config/config.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/Target/TargetData.h"
36 #include "llvm/Target/TargetMachine.h"
37 #include "llvm/Target/TargetRegistry.h"
38 #include "llvm/Target/TargetSelect.h"
39 #include <memory>
40 using namespace llvm;
41
42 // General options for llc.  Other pass-specific options are specified
43 // within the corresponding llc passes, and target-specific options
44 // and back-end code generation options are specified with the target machine.
45 //
46 static cl::opt<std::string>
47 InputFilename(cl::Positional, cl::desc("<input bitcode>"), cl::init("-"));
48
49 static cl::opt<std::string>
50 OutputFilename("o", cl::desc("Output filename"), cl::value_desc("filename"));
51
52 // Determine optimization level.
53 static cl::opt<char>
54 OptLevel("O",
55          cl::desc("Optimization level. [-O0, -O1, -O2, or -O3] "
56                   "(default = '-O2')"),
57          cl::Prefix,
58          cl::ZeroOrMore,
59          cl::init(' '));
60
61 static cl::opt<std::string>
62 TargetTriple("mtriple", cl::desc("Override target triple for module"));
63
64 static cl::opt<std::string>
65 MArch("march", cl::desc("Architecture to generate code for (see --version)"));
66
67 static cl::opt<std::string>
68 MCPU("mcpu",
69   cl::desc("Target a specific cpu type (-mcpu=help for details)"),
70   cl::value_desc("cpu-name"),
71   cl::init(""));
72
73 static cl::list<std::string>
74 MAttrs("mattr",
75   cl::CommaSeparated,
76   cl::desc("Target specific attributes (-mattr=help for details)"),
77   cl::value_desc("a1,+a2,-a3,..."));
78
79 static cl::opt<bool>
80 RelaxAll("mc-relax-all",
81   cl::desc("When used with filetype=obj, "
82            "relax all fixups in the emitted object file"));
83
84 cl::opt<TargetMachine::CodeGenFileType>
85 FileType("filetype", cl::init(TargetMachine::CGFT_AssemblyFile),
86   cl::desc("Choose a file type (not all types are supported by all targets):"),
87   cl::values(
88        clEnumValN(TargetMachine::CGFT_AssemblyFile, "asm",
89                   "Emit an assembly ('.s') file"),
90        clEnumValN(TargetMachine::CGFT_ObjectFile, "obj",
91                   "Emit a native object ('.o') file [experimental]"),
92        clEnumValN(TargetMachine::CGFT_Null, "null",
93                   "Emit nothing, for performance testing"),
94        clEnumValEnd));
95
96 cl::opt<bool> NoVerify("disable-verify", cl::Hidden,
97                        cl::desc("Do not verify input module"));
98
99 cl::opt<bool> DisableDotLoc("disable-dot-loc", cl::Hidden,
100                             cl::desc("Do not use .loc entries"));
101
102 cl::opt<bool> DisableCFI("disable-cfi", cl::Hidden,
103                          cl::desc("Do not use .cfi_* directives"));
104
105 static cl::opt<bool>
106 DisableRedZone("disable-red-zone",
107   cl::desc("Do not emit code that uses the red zone."),
108   cl::init(false));
109
110 // GetFileNameRoot - Helper function to get the basename of a filename.
111 static inline std::string
112 GetFileNameRoot(const std::string &InputFilename) {
113   std::string IFN = InputFilename;
114   std::string outputFilename;
115   int Len = IFN.length();
116   if ((Len > 2) &&
117       IFN[Len-3] == '.' &&
118       ((IFN[Len-2] == 'b' && IFN[Len-1] == 'c') ||
119        (IFN[Len-2] == 'l' && IFN[Len-1] == 'l'))) {
120     outputFilename = std::string(IFN.begin(), IFN.end()-3); // s/.bc/.s/
121   } else {
122     outputFilename = IFN;
123   }
124   return outputFilename;
125 }
126
127 static tool_output_file *GetOutputStream(const char *TargetName,
128                                          Triple::OSType OS,
129                                          const char *ProgName) {
130   // If we don't yet have an output filename, make one.
131   if (OutputFilename.empty()) {
132     if (InputFilename == "-")
133       OutputFilename = "-";
134     else {
135       OutputFilename = GetFileNameRoot(InputFilename);
136
137       switch (FileType) {
138       default: assert(0 && "Unknown file type");
139       case TargetMachine::CGFT_AssemblyFile:
140         if (TargetName[0] == 'c') {
141           if (TargetName[1] == 0)
142             OutputFilename += ".cbe.c";
143           else if (TargetName[1] == 'p' && TargetName[2] == 'p')
144             OutputFilename += ".cpp";
145           else
146             OutputFilename += ".s";
147         } else
148           OutputFilename += ".s";
149         break;
150       case TargetMachine::CGFT_ObjectFile:
151         if (OS == Triple::Win32)
152           OutputFilename += ".obj";
153         else
154           OutputFilename += ".o";
155         break;
156       case TargetMachine::CGFT_Null:
157         OutputFilename += ".null";
158         break;
159       }
160     }
161   }
162
163   // Decide if we need "binary" output.
164   bool Binary = false;
165   switch (FileType) {
166   default: assert(0 && "Unknown file type");
167   case TargetMachine::CGFT_AssemblyFile:
168     break;
169   case TargetMachine::CGFT_ObjectFile:
170   case TargetMachine::CGFT_Null:
171     Binary = true;
172     break;
173   }
174
175   // Open the file.
176   std::string error;
177   unsigned OpenFlags = 0;
178   if (Binary) OpenFlags |= raw_fd_ostream::F_Binary;
179   tool_output_file *FDOut = new tool_output_file(OutputFilename.c_str(), error,
180                                                  OpenFlags);
181   if (!error.empty()) {
182     errs() << error << '\n';
183     delete FDOut;
184     return 0;
185   }
186
187   return FDOut;
188 }
189
190 // main - Entry point for the llc compiler.
191 //
192 int main(int argc, char **argv) {
193   sys::PrintStackTraceOnErrorSignal();
194   PrettyStackTraceProgram X(argc, argv);
195
196   // Enable debug stream buffering.
197   EnableDebugBuffering = true;
198
199   LLVMContext &Context = getGlobalContext();
200   llvm_shutdown_obj Y;  // Call llvm_shutdown() on exit.
201
202   // Initialize targets first, so that --version shows registered targets.
203   InitializeAllTargets();
204   InitializeAllAsmPrinters();
205   InitializeAllAsmParsers();
206
207   cl::ParseCommandLineOptions(argc, argv, "llvm system compiler\n");
208
209   // Load the module to be compiled...
210   SMDiagnostic Err;
211   std::auto_ptr<Module> M;
212
213   M.reset(ParseIRFile(InputFilename, Err, Context));
214   if (M.get() == 0) {
215     Err.Print(argv[0], errs());
216     return 1;
217   }
218   Module &mod = *M.get();
219
220   // If we are supposed to override the target triple, do so now.
221   if (!TargetTriple.empty())
222     mod.setTargetTriple(Triple::normalize(TargetTriple));
223
224   Triple TheTriple(mod.getTargetTriple());
225   if (TheTriple.getTriple().empty())
226     TheTriple.setTriple(sys::getHostTriple());
227
228   // Allocate target machine.  First, check whether the user has explicitly
229   // specified an architecture to compile for. If so we have to look it up by
230   // name, because it might be a backend that has no mapping to a target triple.
231   const Target *TheTarget = 0;
232   if (!MArch.empty()) {
233     for (TargetRegistry::iterator it = TargetRegistry::begin(),
234            ie = TargetRegistry::end(); it != ie; ++it) {
235       if (MArch == it->getName()) {
236         TheTarget = &*it;
237         break;
238       }
239     }
240
241     if (!TheTarget) {
242       errs() << argv[0] << ": error: invalid target '" << MArch << "'.\n";
243       return 1;
244     }
245
246     // Adjust the triple to match (if known), otherwise stick with the
247     // module/host triple.
248     Triple::ArchType Type = Triple::getArchTypeForLLVMName(MArch);
249     if (Type != Triple::UnknownArch)
250       TheTriple.setArch(Type);
251   } else {
252     std::string Err;
253     TheTarget = TargetRegistry::lookupTarget(TheTriple.getTriple(), Err);
254     if (TheTarget == 0) {
255       errs() << argv[0] << ": error auto-selecting target for module '"
256              << Err << "'.  Please use the -march option to explicitly "
257              << "pick a target.\n";
258       return 1;
259     }
260   }
261
262   // Package up features to be passed to target/subtarget
263   std::string FeaturesStr;
264   if (MCPU.size() || MAttrs.size()) {
265     SubtargetFeatures Features;
266     Features.setCPU(MCPU);
267     for (unsigned i = 0; i != MAttrs.size(); ++i)
268       Features.AddFeature(MAttrs[i]);
269     FeaturesStr = Features.getString();
270   }
271
272   std::auto_ptr<TargetMachine>
273     target(TheTarget->createTargetMachine(TheTriple.getTriple(), FeaturesStr));
274   assert(target.get() && "Could not allocate target machine!");
275   TargetMachine &Target = *target.get();
276
277   if (DisableDotLoc)
278     Target.setMCUseLoc(false);
279
280   if (DisableCFI)
281     Target.setMCUseCFI(false);
282
283   // Disable .loc support for older OS X versions.
284   if (TheTriple.isMacOSX() &&
285       TheTriple.isMacOSXVersionLT(10, 6))
286     Target.setMCUseLoc(false);
287
288   // Figure out where we are going to send the output...
289   OwningPtr<tool_output_file> Out
290     (GetOutputStream(TheTarget->getName(), TheTriple.getOS(), argv[0]));
291   if (!Out) return 1;
292
293   CodeGenOpt::Level OLvl = CodeGenOpt::Default;
294   switch (OptLevel) {
295   default:
296     errs() << argv[0] << ": invalid optimization level.\n";
297     return 1;
298   case ' ': break;
299   case '0': OLvl = CodeGenOpt::None; break;
300   case '1': OLvl = CodeGenOpt::Less; break;
301   case '2': OLvl = CodeGenOpt::Default; break;
302   case '3': OLvl = CodeGenOpt::Aggressive; break;
303   }
304
305   // Build up all of the passes that we want to do to the module.
306   PassManager PM;
307
308   // Add the target data from the target machine, if it exists, or the module.
309   if (const TargetData *TD = Target.getTargetData())
310     PM.add(new TargetData(*TD));
311   else
312     PM.add(new TargetData(&mod));
313
314   // Override default to generate verbose assembly.
315   Target.setAsmVerbosityDefault(true);
316
317   if (RelaxAll) {
318     if (FileType != TargetMachine::CGFT_ObjectFile)
319       errs() << argv[0]
320              << ": warning: ignoring -mc-relax-all because filetype != obj";
321     else
322       Target.setMCRelaxAll(true);
323   }
324
325   {
326     formatted_raw_ostream FOS(Out->os());
327
328     // Ask the target to add backend passes as necessary.
329     if (Target.addPassesToEmitFile(PM, FOS, FileType, OLvl, NoVerify)) {
330       errs() << argv[0] << ": target does not support generation of this"
331              << " file type!\n";
332       return 1;
333     }
334
335     // Before executing passes, print the final values of the LLVM options.
336     cl::PrintOptionValues();
337
338     PM.run(mod);
339   }
340
341   // Declare success.
342   Out->keep();
343
344   return 0;
345 }