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/Analysis/TargetLibraryInfo.h"
19 #include "llvm/CodeGen/CommandFlags.h"
20 #include "llvm/CodeGen/LinkAllAsmWriterComponents.h"
21 #include "llvm/CodeGen/LinkAllCodegenComponents.h"
22 #include "llvm/IR/DataLayout.h"
23 #include "llvm/IR/IRPrintingPasses.h"
24 #include "llvm/IR/LLVMContext.h"
25 #include "llvm/IR/Module.h"
26 #include "llvm/IRReader/IRReader.h"
27 #include "llvm/MC/SubtargetFeature.h"
28 #include "llvm/Pass.h"
29 #include "llvm/PassManager.h"
30 #include "llvm/Support/CommandLine.h"
31 #include "llvm/Support/Debug.h"
32 #include "llvm/Support/FileSystem.h"
33 #include "llvm/Support/FormattedStream.h"
34 #include "llvm/Support/Host.h"
35 #include "llvm/Support/ManagedStatic.h"
36 #include "llvm/Support/PluginLoader.h"
37 #include "llvm/Support/PrettyStackTrace.h"
38 #include "llvm/Support/Signals.h"
39 #include "llvm/Support/SourceMgr.h"
40 #include "llvm/Support/TargetRegistry.h"
41 #include "llvm/Support/TargetSelect.h"
42 #include "llvm/Support/ToolOutputFile.h"
43 #include "llvm/Target/TargetMachine.h"
44 #include "llvm/Target/TargetSubtargetInfo.h"
48 // General options for llc. Other pass-specific options are specified
49 // within the corresponding llc passes, and target-specific options
50 // and back-end code generation options are specified with the target machine.
52 static cl::opt<std::string>
53 InputFilename(cl::Positional, cl::desc("<input bitcode>"), cl::init("-"));
55 static cl::opt<std::string>
56 OutputFilename("o", cl::desc("Output filename"), cl::value_desc("filename"));
58 static cl::opt<unsigned>
59 TimeCompilations("time-compilations", cl::Hidden, cl::init(1u),
61 cl::desc("Repeat compilation N times for timing"));
64 NoIntegratedAssembler("no-integrated-as", cl::Hidden,
65 cl::desc("Disable integrated assembler"));
67 // Determine optimization level.
70 cl::desc("Optimization level. [-O0, -O1, -O2, or -O3] "
76 static cl::opt<std::string>
77 TargetTriple("mtriple", cl::desc("Override target triple for module"));
79 static cl::opt<bool> NoVerify("disable-verify", cl::Hidden,
80 cl::desc("Do not verify input module"));
82 static cl::opt<bool> DisableSimplifyLibCalls("disable-simplify-libcalls",
83 cl::desc("Disable simplify-libcalls"));
85 static cl::opt<bool> ShowMCEncoding("show-mc-encoding", cl::Hidden,
86 cl::desc("Show encoding in .s output"));
88 static cl::opt<bool> EnableDwarfDirectory(
89 "enable-dwarf-directory", cl::Hidden,
90 cl::desc("Use .file directives with an explicit directory."));
92 static cl::opt<bool> AsmVerbose("asm-verbose",
93 cl::desc("Add comments to directives."),
96 static int compileModule(char **, LLVMContext &);
98 static std::unique_ptr<tool_output_file>
99 GetOutputStream(const char *TargetName, Triple::OSType OS,
100 const char *ProgName) {
101 // If we don't yet have an output filename, make one.
102 if (OutputFilename.empty()) {
103 if (InputFilename == "-")
104 OutputFilename = "-";
106 // If InputFilename ends in .bc or .ll, remove it.
107 StringRef IFN = InputFilename;
108 if (IFN.endswith(".bc") || IFN.endswith(".ll"))
109 OutputFilename = IFN.drop_back(3);
111 OutputFilename = IFN;
114 case TargetMachine::CGFT_AssemblyFile:
115 if (TargetName[0] == 'c') {
116 if (TargetName[1] == 0)
117 OutputFilename += ".cbe.c";
118 else if (TargetName[1] == 'p' && TargetName[2] == 'p')
119 OutputFilename += ".cpp";
121 OutputFilename += ".s";
123 OutputFilename += ".s";
125 case TargetMachine::CGFT_ObjectFile:
126 if (OS == Triple::Win32)
127 OutputFilename += ".obj";
129 OutputFilename += ".o";
131 case TargetMachine::CGFT_Null:
132 OutputFilename += ".null";
138 // Decide if we need "binary" output.
141 case TargetMachine::CGFT_AssemblyFile:
143 case TargetMachine::CGFT_ObjectFile:
144 case TargetMachine::CGFT_Null:
151 sys::fs::OpenFlags OpenFlags = sys::fs::F_None;
153 OpenFlags |= sys::fs::F_Text;
154 auto FDOut = llvm::make_unique<tool_output_file>(OutputFilename, EC,
157 errs() << EC.message() << '\n';
164 // main - Entry point for the llc compiler.
166 int main(int argc, char **argv) {
167 sys::PrintStackTraceOnErrorSignal();
168 PrettyStackTraceProgram X(argc, argv);
170 // Enable debug stream buffering.
171 EnableDebugBuffering = true;
173 LLVMContext &Context = getGlobalContext();
174 llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
176 // Initialize targets first, so that --version shows registered targets.
177 InitializeAllTargets();
178 InitializeAllTargetMCs();
179 InitializeAllAsmPrinters();
180 InitializeAllAsmParsers();
182 // Initialize codegen and IR passes used by llc so that the -print-after,
183 // -print-before, and -stop-after options work.
184 PassRegistry *Registry = PassRegistry::getPassRegistry();
185 initializeCore(*Registry);
186 initializeCodeGen(*Registry);
187 initializeLoopStrengthReducePass(*Registry);
188 initializeLowerIntrinsicsPass(*Registry);
189 initializeUnreachableBlockElimPass(*Registry);
191 // Register the target printer for --version.
192 cl::AddExtraVersionPrinter(TargetRegistry::printRegisteredTargetsForVersion);
194 cl::ParseCommandLineOptions(argc, argv, "llvm system compiler\n");
196 // Compile the module TimeCompilations times to give better compile time
198 for (unsigned I = TimeCompilations; I; --I)
199 if (int RetVal = compileModule(argv, Context))
204 static int compileModule(char **argv, LLVMContext &Context) {
205 // Load the module to be compiled...
207 std::unique_ptr<Module> M;
210 bool SkipModule = MCPU == "help" ||
211 (!MAttrs.empty() && MAttrs.front() == "help");
213 // If user asked for the 'native' CPU, autodetect here. If autodection fails,
214 // this will set the CPU to an empty string which tells the target to
215 // pick a basic default.
216 if (MCPU == "native")
217 MCPU = sys::getHostCPUName();
219 // If user just wants to list available options, skip module loading
221 M = parseIRFile(InputFilename, Err, Context);
223 Err.print(argv[0], errs());
227 // If we are supposed to override the target triple, do so now.
228 if (!TargetTriple.empty())
229 M->setTargetTriple(Triple::normalize(TargetTriple));
230 TheTriple = Triple(M->getTargetTriple());
232 TheTriple = Triple(Triple::normalize(TargetTriple));
235 if (TheTriple.getTriple().empty())
236 TheTriple.setTriple(sys::getDefaultTargetTriple());
238 // Get the target specific parser.
240 const Target *TheTarget = TargetRegistry::lookupTarget(MArch, TheTriple,
243 errs() << argv[0] << ": " << Error;
247 // Package up features to be passed to target/subtarget
248 std::string FeaturesStr;
250 SubtargetFeatures Features;
251 for (unsigned i = 0; i != MAttrs.size(); ++i)
252 Features.AddFeature(MAttrs[i]);
253 FeaturesStr = Features.getString();
256 CodeGenOpt::Level OLvl = CodeGenOpt::Default;
259 errs() << argv[0] << ": invalid optimization level.\n";
262 case '0': OLvl = CodeGenOpt::None; break;
263 case '1': OLvl = CodeGenOpt::Less; break;
264 case '2': OLvl = CodeGenOpt::Default; break;
265 case '3': OLvl = CodeGenOpt::Aggressive; break;
268 TargetOptions Options = InitTargetOptionsFromCodeGenFlags();
269 Options.DisableIntegratedAS = NoIntegratedAssembler;
270 Options.MCOptions.ShowMCEncoding = ShowMCEncoding;
271 Options.MCOptions.MCUseDwarfDirectory = EnableDwarfDirectory;
272 Options.MCOptions.AsmVerbose = AsmVerbose;
274 std::unique_ptr<TargetMachine> Target(
275 TheTarget->createTargetMachine(TheTriple.getTriple(), MCPU, FeaturesStr,
276 Options, RelocModel, CMModel, OLvl));
277 assert(Target && "Could not allocate target machine!");
279 // If we don't have a module then just exit now. We do this down
280 // here since the CPU/Feature help is underneath the target machine
285 assert(M && "Should have exited if we didn't have a module!");
287 if (GenerateSoftFloatCalls)
288 FloatABIForCalls = FloatABI::Soft;
290 // Figure out where we are going to send the output.
291 std::unique_ptr<tool_output_file> Out =
292 GetOutputStream(TheTarget->getName(), TheTriple.getOS(), argv[0]);
295 // Build up all of the passes that we want to do to the module.
298 // Add an appropriate TargetLibraryInfo pass for the module's triple.
299 TargetLibraryInfoImpl TLII(Triple(M->getTargetTriple()));
301 // The -disable-simplify-libcalls flag actually disables all builtin optzns.
302 if (DisableSimplifyLibCalls)
303 TLII.disableAllFunctions();
304 PM.add(new TargetLibraryInfoWrapperPass(TLII));
306 // Add the target data from the target machine, if it exists, or the module.
307 if (const DataLayout *DL = Target->getSubtargetImpl()->getDataLayout())
308 M->setDataLayout(DL);
309 PM.add(new DataLayoutPass());
311 if (RelaxAll.getNumOccurrences() > 0 &&
312 FileType != TargetMachine::CGFT_ObjectFile)
314 << ": warning: ignoring -mc-relax-all because filetype != obj";
317 formatted_raw_ostream FOS(Out->os());
319 AnalysisID StartAfterID = nullptr;
320 AnalysisID StopAfterID = nullptr;
321 const PassRegistry *PR = PassRegistry::getPassRegistry();
322 if (!StartAfter.empty()) {
323 const PassInfo *PI = PR->getPassInfo(StartAfter);
325 errs() << argv[0] << ": start-after pass is not registered.\n";
328 StartAfterID = PI->getTypeInfo();
330 if (!StopAfter.empty()) {
331 const PassInfo *PI = PR->getPassInfo(StopAfter);
333 errs() << argv[0] << ": stop-after pass is not registered.\n";
336 StopAfterID = PI->getTypeInfo();
339 // Ask the target to add backend passes as necessary.
340 if (Target->addPassesToEmitFile(PM, FOS, FileType, NoVerify,
341 StartAfterID, StopAfterID)) {
342 errs() << argv[0] << ": target does not support generation of this"
347 // Before executing passes, print the final values of the LLVM options.
348 cl::PrintOptionValues();