]> git.proxmox.com Git - rustc.git/blame - src/llvm/tools/llc/llc.cpp
Imported Upstream version 1.0.0+dfsg1
[rustc.git] / src / llvm / tools / llc / llc.cpp
CommitLineData
223e47cc
LB
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
1a4d82fc 16
223e47cc 17#include "llvm/ADT/Triple.h"
970d7e83 18#include "llvm/CodeGen/CommandFlags.h"
223e47cc
LB
19#include "llvm/CodeGen/LinkAllAsmWriterComponents.h"
20#include "llvm/CodeGen/LinkAllCodegenComponents.h"
970d7e83 21#include "llvm/IR/DataLayout.h"
1a4d82fc
JJ
22#include "llvm/IR/IRPrintingPasses.h"
23#include "llvm/IR/LLVMContext.h"
970d7e83 24#include "llvm/IR/Module.h"
1a4d82fc 25#include "llvm/IRReader/IRReader.h"
223e47cc 26#include "llvm/MC/SubtargetFeature.h"
970d7e83
LB
27#include "llvm/Pass.h"
28#include "llvm/PassManager.h"
223e47cc
LB
29#include "llvm/Support/CommandLine.h"
30#include "llvm/Support/Debug.h"
1a4d82fc 31#include "llvm/Support/FileSystem.h"
223e47cc 32#include "llvm/Support/FormattedStream.h"
970d7e83 33#include "llvm/Support/Host.h"
223e47cc
LB
34#include "llvm/Support/ManagedStatic.h"
35#include "llvm/Support/PluginLoader.h"
36#include "llvm/Support/PrettyStackTrace.h"
223e47cc 37#include "llvm/Support/Signals.h"
1a4d82fc 38#include "llvm/Support/SourceMgr.h"
223e47cc
LB
39#include "llvm/Support/TargetRegistry.h"
40#include "llvm/Support/TargetSelect.h"
970d7e83 41#include "llvm/Support/ToolOutputFile.h"
223e47cc
LB
42#include "llvm/Target/TargetLibraryInfo.h"
43#include "llvm/Target/TargetMachine.h"
1a4d82fc 44#include "llvm/Target/TargetSubtargetInfo.h"
223e47cc
LB
45#include <memory>
46using namespace llvm;
47
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.
51//
52static cl::opt<std::string>
53InputFilename(cl::Positional, cl::desc("<input bitcode>"), cl::init("-"));
54
55static cl::opt<std::string>
56OutputFilename("o", cl::desc("Output filename"), cl::value_desc("filename"));
57
970d7e83
LB
58static cl::opt<unsigned>
59TimeCompilations("time-compilations", cl::Hidden, cl::init(1u),
60 cl::value_desc("N"),
61 cl::desc("Repeat compilation N times for timing"));
62
1a4d82fc
JJ
63static cl::opt<bool>
64NoIntegratedAssembler("no-integrated-as", cl::Hidden,
65 cl::desc("Disable integrated assembler"));
66
223e47cc
LB
67// Determine optimization level.
68static cl::opt<char>
69OptLevel("O",
70 cl::desc("Optimization level. [-O0, -O1, -O2, or -O3] "
71 "(default = '-O2')"),
72 cl::Prefix,
73 cl::ZeroOrMore,
74 cl::init(' '));
75
76static cl::opt<std::string>
77TargetTriple("mtriple", cl::desc("Override target triple for module"));
78
1a4d82fc
JJ
79static cl::opt<bool> NoVerify("disable-verify", cl::Hidden,
80 cl::desc("Do not verify input module"));
81
82static cl::opt<bool> DisableSimplifyLibCalls("disable-simplify-libcalls",
83 cl::desc("Disable simplify-libcalls"));
84
85static cl::opt<bool> ShowMCEncoding("show-mc-encoding", cl::Hidden,
86 cl::desc("Show encoding in .s output"));
87
88static cl::opt<bool> EnableDwarfDirectory(
89 "enable-dwarf-directory", cl::Hidden,
90 cl::desc("Use .file directives with an explicit directory."));
91
92static cl::opt<bool> AsmVerbose("asm-verbose",
93 cl::desc("Add comments to directives."),
94 cl::init(true));
95
96static int compileModule(char **, LLVMContext &);
223e47cc 97
85aaf69f
SL
98static std::unique_ptr<tool_output_file>
99GetOutputStream(const char *TargetName, Triple::OSType OS,
100 const char *ProgName) {
223e47cc
LB
101 // If we don't yet have an output filename, make one.
102 if (OutputFilename.empty()) {
103 if (InputFilename == "-")
104 OutputFilename = "-";
105 else {
1a4d82fc
JJ
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);
110 else
111 OutputFilename = IFN;
223e47cc
LB
112
113 switch (FileType) {
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";
120 else
121 OutputFilename += ".s";
122 } else
123 OutputFilename += ".s";
124 break;
125 case TargetMachine::CGFT_ObjectFile:
126 if (OS == Triple::Win32)
127 OutputFilename += ".obj";
128 else
129 OutputFilename += ".o";
130 break;
131 case TargetMachine::CGFT_Null:
132 OutputFilename += ".null";
133 break;
134 }
135 }
136 }
137
138 // Decide if we need "binary" output.
139 bool Binary = false;
140 switch (FileType) {
141 case TargetMachine::CGFT_AssemblyFile:
142 break;
143 case TargetMachine::CGFT_ObjectFile:
144 case TargetMachine::CGFT_Null:
145 Binary = true;
146 break;
147 }
148
149 // Open the file.
1a4d82fc
JJ
150 std::error_code EC;
151 sys::fs::OpenFlags OpenFlags = sys::fs::F_None;
152 if (!Binary)
153 OpenFlags |= sys::fs::F_Text;
85aaf69f
SL
154 auto FDOut = llvm::make_unique<tool_output_file>(OutputFilename, EC,
155 OpenFlags);
1a4d82fc
JJ
156 if (EC) {
157 errs() << EC.message() << '\n';
1a4d82fc 158 return nullptr;
223e47cc
LB
159 }
160
161 return FDOut;
162}
163
164// main - Entry point for the llc compiler.
165//
166int main(int argc, char **argv) {
167 sys::PrintStackTraceOnErrorSignal();
168 PrettyStackTraceProgram X(argc, argv);
169
170 // Enable debug stream buffering.
171 EnableDebugBuffering = true;
172
173 LLVMContext &Context = getGlobalContext();
174 llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
175
176 // Initialize targets first, so that --version shows registered targets.
177 InitializeAllTargets();
178 InitializeAllTargetMCs();
179 InitializeAllAsmPrinters();
180 InitializeAllAsmParsers();
181
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);
190
191 // Register the target printer for --version.
192 cl::AddExtraVersionPrinter(TargetRegistry::printRegisteredTargetsForVersion);
193
194 cl::ParseCommandLineOptions(argc, argv, "llvm system compiler\n");
195
970d7e83
LB
196 // Compile the module TimeCompilations times to give better compile time
197 // metrics.
198 for (unsigned I = TimeCompilations; I; --I)
199 if (int RetVal = compileModule(argv, Context))
200 return RetVal;
201 return 0;
202}
203
204static int compileModule(char **argv, LLVMContext &Context) {
223e47cc
LB
205 // Load the module to be compiled...
206 SMDiagnostic Err;
1a4d82fc 207 std::unique_ptr<Module> M;
223e47cc
LB
208 Triple TheTriple;
209
210 bool SkipModule = MCPU == "help" ||
211 (!MAttrs.empty() && MAttrs.front() == "help");
212
1a4d82fc
JJ
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();
218
223e47cc
LB
219 // If user just wants to list available options, skip module loading
220 if (!SkipModule) {
1a4d82fc 221 M = parseIRFile(InputFilename, Err, Context);
85aaf69f 222 if (!M) {
223e47cc
LB
223 Err.print(argv[0], errs());
224 return 1;
225 }
226
227 // If we are supposed to override the target triple, do so now.
228 if (!TargetTriple.empty())
85aaf69f
SL
229 M->setTargetTriple(Triple::normalize(TargetTriple));
230 TheTriple = Triple(M->getTargetTriple());
223e47cc
LB
231 } else {
232 TheTriple = Triple(Triple::normalize(TargetTriple));
233 }
234
235 if (TheTriple.getTriple().empty())
236 TheTriple.setTriple(sys::getDefaultTargetTriple());
237
238 // Get the target specific parser.
239 std::string Error;
240 const Target *TheTarget = TargetRegistry::lookupTarget(MArch, TheTriple,
241 Error);
242 if (!TheTarget) {
243 errs() << argv[0] << ": " << Error;
244 return 1;
245 }
246
247 // Package up features to be passed to target/subtarget
248 std::string FeaturesStr;
249 if (MAttrs.size()) {
250 SubtargetFeatures Features;
251 for (unsigned i = 0; i != MAttrs.size(); ++i)
252 Features.AddFeature(MAttrs[i]);
253 FeaturesStr = Features.getString();
254 }
255
256 CodeGenOpt::Level OLvl = CodeGenOpt::Default;
257 switch (OptLevel) {
258 default:
259 errs() << argv[0] << ": invalid optimization level.\n";
260 return 1;
261 case ' ': break;
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;
266 }
267
1a4d82fc
JJ
268 TargetOptions Options = InitTargetOptionsFromCodeGenFlags();
269 Options.DisableIntegratedAS = NoIntegratedAssembler;
270 Options.MCOptions.ShowMCEncoding = ShowMCEncoding;
271 Options.MCOptions.MCUseDwarfDirectory = EnableDwarfDirectory;
272 Options.MCOptions.AsmVerbose = AsmVerbose;
223e47cc 273
85aaf69f 274 std::unique_ptr<TargetMachine> Target(
1a4d82fc
JJ
275 TheTarget->createTargetMachine(TheTriple.getTriple(), MCPU, FeaturesStr,
276 Options, RelocModel, CMModel, OLvl));
85aaf69f 277 assert(Target && "Could not allocate target machine!");
223e47cc 278
1a4d82fc
JJ
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
281 // creation.
282 if (SkipModule)
283 return 0;
223e47cc 284
85aaf69f 285 assert(M && "Should have exited if we didn't have a module!");
223e47cc
LB
286
287 if (GenerateSoftFloatCalls)
288 FloatABIForCalls = FloatABI::Soft;
289
223e47cc 290 // Figure out where we are going to send the output.
85aaf69f
SL
291 std::unique_ptr<tool_output_file> Out =
292 GetOutputStream(TheTarget->getName(), TheTriple.getOS(), argv[0]);
223e47cc
LB
293 if (!Out) return 1;
294
295 // Build up all of the passes that we want to do to the module.
296 PassManager PM;
297
298 // Add an appropriate TargetLibraryInfo pass for the module's triple.
299 TargetLibraryInfo *TLI = new TargetLibraryInfo(TheTriple);
300 if (DisableSimplifyLibCalls)
301 TLI->disableAllFunctions();
302 PM.add(TLI);
303
304 // Add the target data from the target machine, if it exists, or the module.
85aaf69f
SL
305 if (const DataLayout *DL = Target->getSubtargetImpl()->getDataLayout())
306 M->setDataLayout(DL);
1a4d82fc 307 PM.add(new DataLayoutPass());
223e47cc 308
1a4d82fc
JJ
309 if (RelaxAll.getNumOccurrences() > 0 &&
310 FileType != TargetMachine::CGFT_ObjectFile)
311 errs() << argv[0]
223e47cc 312 << ": warning: ignoring -mc-relax-all because filetype != obj";
223e47cc
LB
313
314 {
315 formatted_raw_ostream FOS(Out->os());
316
1a4d82fc
JJ
317 AnalysisID StartAfterID = nullptr;
318 AnalysisID StopAfterID = nullptr;
223e47cc
LB
319 const PassRegistry *PR = PassRegistry::getPassRegistry();
320 if (!StartAfter.empty()) {
321 const PassInfo *PI = PR->getPassInfo(StartAfter);
322 if (!PI) {
323 errs() << argv[0] << ": start-after pass is not registered.\n";
324 return 1;
325 }
326 StartAfterID = PI->getTypeInfo();
327 }
328 if (!StopAfter.empty()) {
329 const PassInfo *PI = PR->getPassInfo(StopAfter);
330 if (!PI) {
331 errs() << argv[0] << ": stop-after pass is not registered.\n";
332 return 1;
333 }
334 StopAfterID = PI->getTypeInfo();
335 }
336
337 // Ask the target to add backend passes as necessary.
85aaf69f
SL
338 if (Target->addPassesToEmitFile(PM, FOS, FileType, NoVerify,
339 StartAfterID, StopAfterID)) {
223e47cc
LB
340 errs() << argv[0] << ": target does not support generation of this"
341 << " file type!\n";
342 return 1;
343 }
344
345 // Before executing passes, print the final values of the LLVM options.
346 cl::PrintOptionValues();
347
85aaf69f 348 PM.run(*M);
223e47cc
LB
349 }
350
351 // Declare success.
352 Out->keep();
353
354 return 0;
355}