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 //===----------------------------------------------------------------------===//
17 #include "llvm/ADT/Triple.h"
18 #include "llvm/CodeGen/CommandFlags.h"
19 #include "llvm/CodeGen/LinkAllAsmWriterComponents.h"
20 #include "llvm/CodeGen/LinkAllCodegenComponents.h"
21 #include "llvm/IR/DataLayout.h"
22 #include "llvm/IR/IRPrintingPasses.h"
23 #include "llvm/IR/LLVMContext.h"
24 #include "llvm/IR/Module.h"
25 #include "llvm/IRReader/IRReader.h"
26 #include "llvm/MC/SubtargetFeature.h"
27 #include "llvm/Pass.h"
28 #include "llvm/PassManager.h"
29 #include "llvm/Support/CommandLine.h"
30 #include "llvm/Support/Debug.h"
31 #include "llvm/Support/FormattedStream.h"
32 #include "llvm/Support/Host.h"
33 #include "llvm/Support/ManagedStatic.h"
34 #include "llvm/Support/PluginLoader.h"
35 #include "llvm/Support/PrettyStackTrace.h"
36 #include "llvm/Support/Signals.h"
37 #include "llvm/Support/SourceMgr.h"
38 #include "llvm/Support/TargetRegistry.h"
39 #include "llvm/Support/TargetSelect.h"
40 #include "llvm/Support/ToolOutputFile.h"
41 #include "llvm/Target/TargetLibraryInfo.h"
42 #include "llvm/Target/TargetMachine.h"
43 #include <memory>
44 using namespace llvm;
46 // General options for llc. Other pass-specific options are specified
47 // within the corresponding llc passes, and target-specific options
48 // and back-end code generation options are specified with the target machine.
49 //
50 static cl::opt<std::string>
51 InputFilename(cl::Positional, cl::desc("<input bitcode>"), cl::init("-"));
53 static cl::opt<std::string>
54 OutputFilename("o", cl::desc("Output filename"), cl::value_desc("filename"));
56 static cl::opt<unsigned>
57 TimeCompilations("time-compilations", cl::Hidden, cl::init(1u),
58 cl::value_desc("N"),
59 cl::desc("Repeat compilation N times for timing"));
61 static cl::opt<bool>
62 NoIntegratedAssembler("no-integrated-as", cl::Hidden,
63 cl::desc("Disable integrated assembler"));
65 // Determine optimization level.
66 static cl::opt<char>
67 OptLevel("O",
68 cl::desc("Optimization level. [-O0, -O1, -O2, or -O3] "
69 "(default = '-O2')"),
70 cl::Prefix,
71 cl::ZeroOrMore,
72 cl::init(' '));
74 static cl::opt<std::string>
75 TargetTriple("mtriple", cl::desc("Override target triple for module"));
77 cl::opt<bool> NoVerify("disable-verify", cl::Hidden,
78 cl::desc("Do not verify input module"));
80 cl::opt<bool>
81 DisableSimplifyLibCalls("disable-simplify-libcalls",
82 cl::desc("Disable simplify-libcalls"),
83 cl::init(false));
85 static int compileModule(char**, LLVMContext&);
87 // GetFileNameRoot - Helper function to get the basename of a filename.
88 static inline std::string
89 GetFileNameRoot(const std::string &InputFilename) {
90 std::string IFN = InputFilename;
91 std::string outputFilename;
92 int Len = IFN.length();
93 if ((Len > 2) &&
94 IFN[Len-3] == '.' &&
95 ((IFN[Len-2] == 'b' && IFN[Len-1] == 'c') ||
96 (IFN[Len-2] == 'l' && IFN[Len-1] == 'l'))) {
97 outputFilename = std::string(IFN.begin(), IFN.end()-3); // s/.bc/.s/
98 } else {
99 outputFilename = IFN;
100 }
101 return outputFilename;
102 }
104 static tool_output_file *GetOutputStream(const char *TargetName,
105 Triple::OSType OS,
106 const char *ProgName) {
107 // If we don't yet have an output filename, make one.
108 if (OutputFilename.empty()) {
109 if (InputFilename == "-")
110 OutputFilename = "-";
111 else {
112 OutputFilename = GetFileNameRoot(InputFilename);
114 switch (FileType) {
115 case TargetMachine::CGFT_AssemblyFile:
116 if (TargetName[0] == 'c') {
117 if (TargetName[1] == 0)
118 OutputFilename += ".cbe.c";
119 else if (TargetName[1] == 'p' && TargetName[2] == 'p')
120 OutputFilename += ".cpp";
121 else
122 OutputFilename += ".s";
123 } else
124 OutputFilename += ".s";
125 break;
126 case TargetMachine::CGFT_ObjectFile:
127 if (OS == Triple::Win32)
128 OutputFilename += ".obj";
129 else
130 OutputFilename += ".o";
131 break;
132 case TargetMachine::CGFT_Null:
133 OutputFilename += ".null";
134 break;
135 }
136 }
137 }
139 // Decide if we need "binary" output.
140 bool Binary = false;
141 switch (FileType) {
142 case TargetMachine::CGFT_AssemblyFile:
143 break;
144 case TargetMachine::CGFT_ObjectFile:
145 case TargetMachine::CGFT_Null:
146 Binary = true;
147 break;
148 }
150 // Open the file.
151 std::string error;
152 sys::fs::OpenFlags OpenFlags = sys::fs::F_None;
153 if (!Binary)
154 OpenFlags |= sys::fs::F_Text;
155 tool_output_file *FDOut = new tool_output_file(OutputFilename.c_str(), error,
156 OpenFlags);
157 if (!error.empty()) {
158 errs() << error << '\n';
159 delete FDOut;
160 return 0;
161 }
163 return FDOut;
164 }
166 // main - Entry point for the llc compiler.
167 //
168 int main(int argc, char **argv) {
169 sys::PrintStackTraceOnErrorSignal();
170 PrettyStackTraceProgram X(argc, argv);
172 // Enable debug stream buffering.
173 EnableDebugBuffering = true;
175 LLVMContext &Context = getGlobalContext();
176 llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
178 // Initialize targets first, so that --version shows registered targets.
179 InitializeAllTargets();
180 InitializeAllTargetMCs();
181 InitializeAllAsmPrinters();
182 InitializeAllAsmParsers();
184 // Initialize codegen and IR passes used by llc so that the -print-after,
185 // -print-before, and -stop-after options work.
186 PassRegistry *Registry = PassRegistry::getPassRegistry();
187 initializeCore(*Registry);
188 initializeCodeGen(*Registry);
189 initializeLoopStrengthReducePass(*Registry);
190 initializeLowerIntrinsicsPass(*Registry);
191 initializeUnreachableBlockElimPass(*Registry);
193 // Register the target printer for --version.
194 cl::AddExtraVersionPrinter(TargetRegistry::printRegisteredTargetsForVersion);
196 cl::ParseCommandLineOptions(argc, argv, "llvm system compiler\n");
198 // Compile the module TimeCompilations times to give better compile time
199 // metrics.
200 for (unsigned I = TimeCompilations; I; --I)
201 if (int RetVal = compileModule(argv, Context))
202 return RetVal;
203 return 0;
204 }
206 static int compileModule(char **argv, LLVMContext &Context) {
207 // Load the module to be compiled...
208 SMDiagnostic Err;
209 std::unique_ptr<Module> M;
210 Module *mod = 0;
211 Triple TheTriple;
213 bool SkipModule = MCPU == "help" ||
214 (!MAttrs.empty() && MAttrs.front() == "help");
216 // If user asked for the 'native' CPU, autodetect here. If autodection fails,
217 // this will set the CPU to an empty string which tells the target to
218 // pick a basic default.
219 if (MCPU == "native")
220 MCPU = sys::getHostCPUName();
222 // If user just wants to list available options, skip module loading
223 if (!SkipModule) {
224 M.reset(ParseIRFile(InputFilename, Err, Context));
225 mod = M.get();
226 if (mod == 0) {
227 Err.print(argv[0], errs());
228 return 1;
229 }
231 // If we are supposed to override the target triple, do so now.
232 if (!TargetTriple.empty())
233 mod->setTargetTriple(Triple::normalize(TargetTriple));
234 TheTriple = Triple(mod->getTargetTriple());
235 } else {
236 TheTriple = Triple(Triple::normalize(TargetTriple));
237 }
239 if (TheTriple.getTriple().empty())
240 TheTriple.setTriple(sys::getDefaultTargetTriple());
242 // Get the target specific parser.
243 std::string Error;
244 const Target *TheTarget = TargetRegistry::lookupTarget(MArch, TheTriple,
245 Error);
246 if (!TheTarget) {
247 errs() << argv[0] << ": " << Error;
248 return 1;
249 }
251 // Package up features to be passed to target/subtarget
252 std::string FeaturesStr;
253 if (MAttrs.size()) {
254 SubtargetFeatures Features;
255 for (unsigned i = 0; i != MAttrs.size(); ++i)
256 Features.AddFeature(MAttrs[i]);
257 FeaturesStr = Features.getString();
258 }
260 CodeGenOpt::Level OLvl = CodeGenOpt::Default;
261 switch (OptLevel) {
262 default:
263 errs() << argv[0] << ": invalid optimization level.\n";
264 return 1;
265 case ' ': break;
266 case '0': OLvl = CodeGenOpt::None; break;
267 case '1': OLvl = CodeGenOpt::Less; break;
268 case '2': OLvl = CodeGenOpt::Default; break;
269 case '3': OLvl = CodeGenOpt::Aggressive; break;
270 }
272 TargetOptions Options = InitTargetOptionsFromCodeGenFlags();
273 Options.DisableIntegratedAS = NoIntegratedAssembler;
275 std::unique_ptr<TargetMachine> target(
276 TheTarget->createTargetMachine(TheTriple.getTriple(), MCPU, FeaturesStr,
277 Options, RelocModel, CMModel, OLvl));
278 assert(target.get() && "Could not allocate target machine!");
279 assert(mod && "Should have exited after outputting help!");
280 TargetMachine &Target = *target.get();
282 if (DisableCFI)
283 Target.setMCUseCFI(false);
285 if (EnableDwarfDirectory)
286 Target.setMCUseDwarfDirectory(true);
288 if (GenerateSoftFloatCalls)
289 FloatABIForCalls = FloatABI::Soft;
291 // Figure out where we are going to send the output.
292 std::unique_ptr<tool_output_file> Out(
293 GetOutputStream(TheTarget->getName(), TheTriple.getOS(), argv[0]));
294 if (!Out) return 1;
296 // Build up all of the passes that we want to do to the module.
297 PassManager PM;
299 // Add an appropriate TargetLibraryInfo pass for the module's triple.
300 TargetLibraryInfo *TLI = new TargetLibraryInfo(TheTriple);
301 if (DisableSimplifyLibCalls)
302 TLI->disableAllFunctions();
303 PM.add(TLI);
305 // Add the target data from the target machine, if it exists, or the module.
306 if (const DataLayout *DL = Target.getDataLayout())
307 mod->setDataLayout(DL);
308 PM.add(new DataLayoutPass(mod));
310 // Override default to generate verbose assembly.
311 Target.setAsmVerbosityDefault(true);
313 if (RelaxAll) {
314 if (FileType != TargetMachine::CGFT_ObjectFile)
315 errs() << argv[0]
316 << ": warning: ignoring -mc-relax-all because filetype != obj";
317 else
318 Target.setMCRelaxAll(true);
319 }
321 {
322 formatted_raw_ostream FOS(Out->os());
324 AnalysisID StartAfterID = 0;
325 AnalysisID StopAfterID = 0;
326 const PassRegistry *PR = PassRegistry::getPassRegistry();
327 if (!StartAfter.empty()) {
328 const PassInfo *PI = PR->getPassInfo(StartAfter);
329 if (!PI) {
330 errs() << argv[0] << ": start-after pass is not registered.\n";
331 return 1;
332 }
333 StartAfterID = PI->getTypeInfo();
334 }
335 if (!StopAfter.empty()) {
336 const PassInfo *PI = PR->getPassInfo(StopAfter);
337 if (!PI) {
338 errs() << argv[0] << ": stop-after pass is not registered.\n";
339 return 1;
340 }
341 StopAfterID = PI->getTypeInfo();
342 }
344 // Ask the target to add backend passes as necessary.
345 if (Target.addPassesToEmitFile(PM, FOS, FileType, NoVerify,
346 StartAfterID, StopAfterID)) {
347 errs() << argv[0] << ": target does not support generation of this"
348 << " file type!\n";
349 return 1;
350 }
352 // Before executing passes, print the final values of the LLVM options.
353 cl::PrintOptionValues();
355 PM.run(*mod);
356 }
358 // Declare success.
359 Out->keep();
361 return 0;
362 }