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 //===----------------------------------------------------------------------===//
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/FileSystem.h"
32 #include "llvm/Support/FormattedStream.h"
33 #include "llvm/Support/Host.h"
34 #include "llvm/Support/ManagedStatic.h"
35 #include "llvm/Support/PluginLoader.h"
36 #include "llvm/Support/PrettyStackTrace.h"
37 #include "llvm/Support/Signals.h"
38 #include "llvm/Support/SourceMgr.h"
39 #include "llvm/Support/TargetRegistry.h"
40 #include "llvm/Support/TargetSelect.h"
41 #include "llvm/Support/ToolOutputFile.h"
42 #include "llvm/Target/TargetLibraryInfo.h"
43 #include "llvm/Target/TargetMachine.h"
47 // General options for llc. Other pass-specific options are specified
48 // within the corresponding llc passes, and target-specific options
49 // and back-end code generation options are specified with the target machine.
51 static cl::opt<std::string>
52 InputFilename(cl::Positional, cl::desc("<input bitcode>"), cl::init("-"));
54 static cl::opt<std::string>
55 OutputFilename("o", cl::desc("Output filename"), cl::value_desc("filename"));
57 static cl::opt<unsigned>
58 TimeCompilations("time-compilations", cl::Hidden, cl::init(1u),
60 cl::desc("Repeat compilation N times for timing"));
63 NoIntegratedAssembler("no-integrated-as", cl::Hidden,
64 cl::desc("Disable integrated assembler"));
66 // Determine optimization level.
69 cl::desc("Optimization level. [-O0, -O1, -O2, or -O3] "
75 static cl::opt<std::string>
76 TargetTriple("mtriple", cl::desc("Override target triple for module"));
78 cl::opt<bool> NoVerify("disable-verify", cl::Hidden,
79 cl::desc("Do not verify input module"));
82 DisableSimplifyLibCalls("disable-simplify-libcalls",
83 cl::desc("Disable simplify-libcalls"),
86 static int compileModule(char**, LLVMContext&);
88 // GetFileNameRoot - Helper function to get the basename of a filename.
89 static inline std::string
90 GetFileNameRoot(const std::string &InputFilename) {
91 std::string IFN = InputFilename;
92 std::string outputFilename;
93 int Len = IFN.length();
96 ((IFN[Len-2] == 'b' && IFN[Len-1] == 'c') ||
97 (IFN[Len-2] == 'l' && IFN[Len-1] == 'l'))) {
98 outputFilename = std::string(IFN.begin(), IFN.end()-3); // s/.bc/.s/
100 outputFilename = IFN;
102 return outputFilename;
105 static tool_output_file *GetOutputStream(const char *TargetName,
107 const char *ProgName) {
108 // If we don't yet have an output filename, make one.
109 if (OutputFilename.empty()) {
110 if (InputFilename == "-")
111 OutputFilename = "-";
113 OutputFilename = GetFileNameRoot(InputFilename);
116 case TargetMachine::CGFT_AssemblyFile:
117 if (TargetName[0] == 'c') {
118 if (TargetName[1] == 0)
119 OutputFilename += ".cbe.c";
120 else if (TargetName[1] == 'p' && TargetName[2] == 'p')
121 OutputFilename += ".cpp";
123 OutputFilename += ".s";
125 OutputFilename += ".s";
127 case TargetMachine::CGFT_ObjectFile:
128 if (OS == Triple::Win32)
129 OutputFilename += ".obj";
131 OutputFilename += ".o";
133 case TargetMachine::CGFT_Null:
134 OutputFilename += ".null";
140 // Decide if we need "binary" output.
143 case TargetMachine::CGFT_AssemblyFile:
145 case TargetMachine::CGFT_ObjectFile:
146 case TargetMachine::CGFT_Null:
153 sys::fs::OpenFlags OpenFlags = sys::fs::F_None;
155 OpenFlags |= sys::fs::F_Text;
156 tool_output_file *FDOut = new tool_output_file(OutputFilename.c_str(), error,
158 if (!error.empty()) {
159 errs() << error << '\n';
167 // main - Entry point for the llc compiler.
169 int main(int argc, char **argv) {
170 sys::PrintStackTraceOnErrorSignal();
171 PrettyStackTraceProgram X(argc, argv);
173 // Enable debug stream buffering.
174 EnableDebugBuffering = true;
176 LLVMContext &Context = getGlobalContext();
177 llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
179 // Initialize targets first, so that --version shows registered targets.
180 InitializeAllTargets();
181 InitializeAllTargetMCs();
182 InitializeAllAsmPrinters();
183 InitializeAllAsmParsers();
185 // Initialize codegen and IR passes used by llc so that the -print-after,
186 // -print-before, and -stop-after options work.
187 PassRegistry *Registry = PassRegistry::getPassRegistry();
188 initializeCore(*Registry);
189 initializeCodeGen(*Registry);
190 initializeLoopStrengthReducePass(*Registry);
191 initializeLowerIntrinsicsPass(*Registry);
192 initializeUnreachableBlockElimPass(*Registry);
194 // Register the target printer for --version.
195 cl::AddExtraVersionPrinter(TargetRegistry::printRegisteredTargetsForVersion);
197 cl::ParseCommandLineOptions(argc, argv, "llvm system compiler\n");
199 // Compile the module TimeCompilations times to give better compile time
201 for (unsigned I = TimeCompilations; I; --I)
202 if (int RetVal = compileModule(argv, Context))
207 static int compileModule(char **argv, LLVMContext &Context) {
208 // Load the module to be compiled...
210 std::unique_ptr<Module> M;
211 Module *mod = nullptr;
214 bool SkipModule = MCPU == "help" ||
215 (!MAttrs.empty() && MAttrs.front() == "help");
217 // If user asked for the 'native' CPU, autodetect here. If autodection fails,
218 // this will set the CPU to an empty string which tells the target to
219 // pick a basic default.
220 if (MCPU == "native")
221 MCPU = sys::getHostCPUName();
223 // If user just wants to list available options, skip module loading
225 M.reset(ParseIRFile(InputFilename, Err, Context));
227 if (mod == nullptr) {
228 Err.print(argv[0], errs());
232 // If we are supposed to override the target triple, do so now.
233 if (!TargetTriple.empty())
234 mod->setTargetTriple(Triple::normalize(TargetTriple));
235 TheTriple = Triple(mod->getTargetTriple());
237 TheTriple = Triple(Triple::normalize(TargetTriple));
240 if (TheTriple.getTriple().empty())
241 TheTriple.setTriple(sys::getDefaultTargetTriple());
243 // Get the target specific parser.
245 const Target *TheTarget = TargetRegistry::lookupTarget(MArch, TheTriple,
248 errs() << argv[0] << ": " << Error;
252 // Package up features to be passed to target/subtarget
253 std::string FeaturesStr;
255 SubtargetFeatures Features;
256 for (unsigned i = 0; i != MAttrs.size(); ++i)
257 Features.AddFeature(MAttrs[i]);
258 FeaturesStr = Features.getString();
261 CodeGenOpt::Level OLvl = CodeGenOpt::Default;
264 errs() << argv[0] << ": invalid optimization level.\n";
267 case '0': OLvl = CodeGenOpt::None; break;
268 case '1': OLvl = CodeGenOpt::Less; break;
269 case '2': OLvl = CodeGenOpt::Default; break;
270 case '3': OLvl = CodeGenOpt::Aggressive; break;
273 TargetOptions Options = InitTargetOptionsFromCodeGenFlags();
274 Options.DisableIntegratedAS = NoIntegratedAssembler;
276 std::unique_ptr<TargetMachine> target(
277 TheTarget->createTargetMachine(TheTriple.getTriple(), MCPU, FeaturesStr,
278 Options, RelocModel, CMModel, OLvl));
279 assert(target.get() && "Could not allocate target machine!");
281 // If we don't have a module then just exit now. We do this down
282 // here since the CPU/Feature help is underneath the target machine
287 assert(mod && "Should have exited if we didn't have a module!");
288 TargetMachine &Target = *target.get();
290 if (GenerateSoftFloatCalls)
291 FloatABIForCalls = FloatABI::Soft;
293 // Figure out where we are going to send the output.
294 std::unique_ptr<tool_output_file> Out(
295 GetOutputStream(TheTarget->getName(), TheTriple.getOS(), argv[0]));
298 // Build up all of the passes that we want to do to the module.
301 // Add an appropriate TargetLibraryInfo pass for the module's triple.
302 TargetLibraryInfo *TLI = new TargetLibraryInfo(TheTriple);
303 if (DisableSimplifyLibCalls)
304 TLI->disableAllFunctions();
307 // Add the target data from the target machine, if it exists, or the module.
308 if (const DataLayout *DL = Target.getDataLayout())
309 mod->setDataLayout(DL);
310 PM.add(new DataLayoutPass(mod));
312 // Override default to generate verbose assembly.
313 Target.setAsmVerbosityDefault(true);
315 if (RelaxAll.getNumOccurrences() > 0 &&
316 FileType != TargetMachine::CGFT_ObjectFile)
318 << ": warning: ignoring -mc-relax-all because filetype != obj";
321 formatted_raw_ostream FOS(Out->os());
323 AnalysisID StartAfterID = nullptr;
324 AnalysisID StopAfterID = nullptr;
325 const PassRegistry *PR = PassRegistry::getPassRegistry();
326 if (!StartAfter.empty()) {
327 const PassInfo *PI = PR->getPassInfo(StartAfter);
329 errs() << argv[0] << ": start-after pass is not registered.\n";
332 StartAfterID = PI->getTypeInfo();
334 if (!StopAfter.empty()) {
335 const PassInfo *PI = PR->getPassInfo(StopAfter);
337 errs() << argv[0] << ": stop-after pass is not registered.\n";
340 StopAfterID = PI->getTypeInfo();
343 // Ask the target to add backend passes as necessary.
344 if (Target.addPassesToEmitFile(PM, FOS, FileType, NoVerify,
345 StartAfterID, StopAfterID)) {
346 errs() << argv[0] << ": target does not support generation of this"
351 // Before executing passes, print the final values of the LLVM options.
352 cl::PrintOptionValues();