1 //===-- llc.cpp - Implement the LLVM Native Code Generator ----------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
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.
14 //===----------------------------------------------------------------------===//
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/Support/TargetRegistry.h"
36 #include "llvm/Support/TargetSelect.h"
37 #include "llvm/Target/TargetData.h"
38 #include "llvm/Target/TargetMachine.h"
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.
46 static cl::opt<std::string>
47 InputFilename(cl::Positional, cl::desc("<input bitcode>"), cl::init("-"));
49 static cl::opt<std::string>
50 OutputFilename("o", cl::desc("Output filename"), cl::value_desc("filename"));
52 // Determine optimization level.
55 cl::desc("Optimization level. [-O0, -O1, -O2, or -O3] "
61 static cl::opt<std::string>
62 TargetTriple("mtriple", cl::desc("Override target triple for module"));
64 static cl::opt<std::string>
65 MArch("march", cl::desc("Architecture to generate code for (see --version)"));
67 static cl::opt<std::string>
69 cl::desc("Target a specific cpu type (-mcpu=help for details)"),
70 cl::value_desc("cpu-name"),
73 static cl::list<std::string>
76 cl::desc("Target specific attributes (-mattr=help for details)"),
77 cl::value_desc("a1,+a2,-a3,..."));
79 static cl::opt<Reloc::Model>
80 RelocModel("relocation-model",
81 cl::desc("Choose relocation model"),
82 cl::init(Reloc::Default),
84 clEnumValN(Reloc::Default, "default",
85 "Target default relocation model"),
86 clEnumValN(Reloc::Static, "static",
87 "Non-relocatable code"),
88 clEnumValN(Reloc::PIC_, "pic",
89 "Fully relocatable, position independent code"),
90 clEnumValN(Reloc::DynamicNoPIC, "dynamic-no-pic",
91 "Relocatable external references, non-relocatable code"),
94 static cl::opt<llvm::CodeModel::Model>
96 cl::desc("Choose code model"),
97 cl::init(CodeModel::Default),
98 cl::values(clEnumValN(CodeModel::Default, "default",
99 "Target default code model"),
100 clEnumValN(CodeModel::Small, "small",
102 clEnumValN(CodeModel::Kernel, "kernel",
103 "Kernel code model"),
104 clEnumValN(CodeModel::Medium, "medium",
105 "Medium code model"),
106 clEnumValN(CodeModel::Large, "large",
111 RelaxAll("mc-relax-all",
112 cl::desc("When used with filetype=obj, "
113 "relax all fixups in the emitted object file"));
115 cl::opt<TargetMachine::CodeGenFileType>
116 FileType("filetype", cl::init(TargetMachine::CGFT_AssemblyFile),
117 cl::desc("Choose a file type (not all types are supported by all targets):"),
119 clEnumValN(TargetMachine::CGFT_AssemblyFile, "asm",
120 "Emit an assembly ('.s') file"),
121 clEnumValN(TargetMachine::CGFT_ObjectFile, "obj",
122 "Emit a native object ('.o') file [experimental]"),
123 clEnumValN(TargetMachine::CGFT_Null, "null",
124 "Emit nothing, for performance testing"),
127 cl::opt<bool> NoVerify("disable-verify", cl::Hidden,
128 cl::desc("Do not verify input module"));
130 cl::opt<bool> DisableDotLoc("disable-dot-loc", cl::Hidden,
131 cl::desc("Do not use .loc entries"));
133 cl::opt<bool> DisableCFI("disable-cfi", cl::Hidden,
134 cl::desc("Do not use .cfi_* directives"));
136 cl::opt<bool> DisableDwarfDirectory("disable-dwarf-directory", cl::Hidden,
137 cl::desc("Do not use file directives with an explicit directory."));
140 DisableRedZone("disable-red-zone",
141 cl::desc("Do not emit code that uses the red zone."),
144 // GetFileNameRoot - Helper function to get the basename of a filename.
145 static inline std::string
146 GetFileNameRoot(const std::string &InputFilename) {
147 std::string IFN = InputFilename;
148 std::string outputFilename;
149 int Len = IFN.length();
152 ((IFN[Len-2] == 'b' && IFN[Len-1] == 'c') ||
153 (IFN[Len-2] == 'l' && IFN[Len-1] == 'l'))) {
154 outputFilename = std::string(IFN.begin(), IFN.end()-3); // s/.bc/.s/
156 outputFilename = IFN;
158 return outputFilename;
161 static tool_output_file *GetOutputStream(const char *TargetName,
163 const char *ProgName) {
164 // If we don't yet have an output filename, make one.
165 if (OutputFilename.empty()) {
166 if (InputFilename == "-")
167 OutputFilename = "-";
169 OutputFilename = GetFileNameRoot(InputFilename);
172 default: assert(0 && "Unknown file type");
173 case TargetMachine::CGFT_AssemblyFile:
174 if (TargetName[0] == 'c') {
175 if (TargetName[1] == 0)
176 OutputFilename += ".cbe.c";
177 else if (TargetName[1] == 'p' && TargetName[2] == 'p')
178 OutputFilename += ".cpp";
180 OutputFilename += ".s";
182 OutputFilename += ".s";
184 case TargetMachine::CGFT_ObjectFile:
185 if (OS == Triple::Win32)
186 OutputFilename += ".obj";
188 OutputFilename += ".o";
190 case TargetMachine::CGFT_Null:
191 OutputFilename += ".null";
197 // Decide if we need "binary" output.
200 default: assert(0 && "Unknown file type");
201 case TargetMachine::CGFT_AssemblyFile:
203 case TargetMachine::CGFT_ObjectFile:
204 case TargetMachine::CGFT_Null:
211 unsigned OpenFlags = 0;
212 if (Binary) OpenFlags |= raw_fd_ostream::F_Binary;
213 tool_output_file *FDOut = new tool_output_file(OutputFilename.c_str(), error,
215 if (!error.empty()) {
216 errs() << error << '\n';
224 // main - Entry point for the llc compiler.
226 int main(int argc, char **argv) {
227 sys::PrintStackTraceOnErrorSignal();
228 PrettyStackTraceProgram X(argc, argv);
230 // Enable debug stream buffering.
231 EnableDebugBuffering = true;
233 LLVMContext &Context = getGlobalContext();
234 llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
236 // Initialize targets first, so that --version shows registered targets.
237 InitializeAllTargets();
238 InitializeAllTargetMCs();
239 InitializeAllAsmPrinters();
240 InitializeAllAsmParsers();
242 // Register the target printer for --version.
243 cl::AddExtraVersionPrinter(TargetRegistry::printRegisteredTargetsForVersion);
245 cl::ParseCommandLineOptions(argc, argv, "llvm system compiler\n");
247 // Load the module to be compiled...
249 std::auto_ptr<Module> M;
251 M.reset(ParseIRFile(InputFilename, Err, Context));
253 Err.print(argv[0], errs());
256 Module &mod = *M.get();
258 // If we are supposed to override the target triple, do so now.
259 if (!TargetTriple.empty())
260 mod.setTargetTriple(Triple::normalize(TargetTriple));
262 Triple TheTriple(mod.getTargetTriple());
263 if (TheTriple.getTriple().empty())
264 TheTriple.setTriple(sys::getHostTriple());
266 // Allocate target machine. First, check whether the user has explicitly
267 // specified an architecture to compile for. If so we have to look it up by
268 // name, because it might be a backend that has no mapping to a target triple.
269 const Target *TheTarget = 0;
270 if (!MArch.empty()) {
271 for (TargetRegistry::iterator it = TargetRegistry::begin(),
272 ie = TargetRegistry::end(); it != ie; ++it) {
273 if (MArch == it->getName()) {
280 errs() << argv[0] << ": error: invalid target '" << MArch << "'.\n";
284 // Adjust the triple to match (if known), otherwise stick with the
285 // module/host triple.
286 Triple::ArchType Type = Triple::getArchTypeForLLVMName(MArch);
287 if (Type != Triple::UnknownArch)
288 TheTriple.setArch(Type);
291 TheTarget = TargetRegistry::lookupTarget(TheTriple.getTriple(), Err);
292 if (TheTarget == 0) {
293 errs() << argv[0] << ": error auto-selecting target for module '"
294 << Err << "'. Please use the -march option to explicitly "
295 << "pick a target.\n";
300 // Package up features to be passed to target/subtarget
301 std::string FeaturesStr;
303 SubtargetFeatures Features;
304 for (unsigned i = 0; i != MAttrs.size(); ++i)
305 Features.AddFeature(MAttrs[i]);
306 FeaturesStr = Features.getString();
309 std::auto_ptr<TargetMachine>
310 target(TheTarget->createTargetMachine(TheTriple.getTriple(),
312 RelocModel, CMModel));
313 assert(target.get() && "Could not allocate target machine!");
314 TargetMachine &Target = *target.get();
317 Target.setMCUseLoc(false);
320 Target.setMCUseCFI(false);
322 if (DisableDwarfDirectory)
323 Target.setMCUseDwarfDirectory(false);
325 // Disable .loc support for older OS X versions.
326 if (TheTriple.isMacOSX() &&
327 TheTriple.isMacOSXVersionLT(10, 6))
328 Target.setMCUseLoc(false);
330 // Figure out where we are going to send the output...
331 OwningPtr<tool_output_file> Out
332 (GetOutputStream(TheTarget->getName(), TheTriple.getOS(), argv[0]));
335 CodeGenOpt::Level OLvl = CodeGenOpt::Default;
338 errs() << argv[0] << ": invalid optimization level.\n";
341 case '0': OLvl = CodeGenOpt::None; break;
342 case '1': OLvl = CodeGenOpt::Less; break;
343 case '2': OLvl = CodeGenOpt::Default; break;
344 case '3': OLvl = CodeGenOpt::Aggressive; break;
347 // Build up all of the passes that we want to do to the module.
350 // Add the target data from the target machine, if it exists, or the module.
351 if (const TargetData *TD = Target.getTargetData())
352 PM.add(new TargetData(*TD));
354 PM.add(new TargetData(&mod));
356 // Override default to generate verbose assembly.
357 Target.setAsmVerbosityDefault(true);
360 if (FileType != TargetMachine::CGFT_ObjectFile)
362 << ": warning: ignoring -mc-relax-all because filetype != obj";
364 Target.setMCRelaxAll(true);
368 formatted_raw_ostream FOS(Out->os());
370 // Ask the target to add backend passes as necessary.
371 if (Target.addPassesToEmitFile(PM, FOS, FileType, OLvl, NoVerify)) {
372 errs() << argv[0] << ": target does not support generation of this"
377 // Before executing passes, print the final values of the LLVM options.
378 cl::PrintOptionValues();