llc.cpp revision 288943
1193323Sed//===-- llc.cpp - Implement the LLVM Native Code Generator ----------------===//
2193323Sed//
3193323Sed//                     The LLVM Compiler Infrastructure
4193323Sed//
5193323Sed// This file is distributed under the University of Illinois Open Source
6193323Sed// License. See LICENSE.TXT for details.
7193323Sed//
8193323Sed//===----------------------------------------------------------------------===//
9193323Sed//
10193323Sed// This is the llc code generator driver. It provides a convenient
11193323Sed// command-line interface for generating native assembly-language code
12193323Sed// or C code, given LLVM bitcode.
13193323Sed//
14193323Sed//===----------------------------------------------------------------------===//
15193323Sed
16261991Sdim
17288943Sdim#include "llvm/ADT/STLExtras.h"
18198090Srdivacky#include "llvm/ADT/Triple.h"
19288943Sdim#include "llvm/Analysis/TargetLibraryInfo.h"
20243830Sdim#include "llvm/CodeGen/CommandFlags.h"
21198090Srdivacky#include "llvm/CodeGen/LinkAllAsmWriterComponents.h"
22198090Srdivacky#include "llvm/CodeGen/LinkAllCodegenComponents.h"
23288943Sdim#include "llvm/CodeGen/MIRParser/MIRParser.h"
24249423Sdim#include "llvm/IR/DataLayout.h"
25276479Sdim#include "llvm/IR/IRPrintingPasses.h"
26276479Sdim#include "llvm/IR/LLVMContext.h"
27288943Sdim#include "llvm/IR/LegacyPassManager.h"
28249423Sdim#include "llvm/IR/Module.h"
29288943Sdim#include "llvm/IR/Verifier.h"
30249423Sdim#include "llvm/IRReader/IRReader.h"
31224133Sdim#include "llvm/MC/SubtargetFeature.h"
32249423Sdim#include "llvm/Pass.h"
33193323Sed#include "llvm/Support/CommandLine.h"
34202375Srdivacky#include "llvm/Support/Debug.h"
35276479Sdim#include "llvm/Support/FileSystem.h"
36198090Srdivacky#include "llvm/Support/FormattedStream.h"
37249423Sdim#include "llvm/Support/Host.h"
38193323Sed#include "llvm/Support/ManagedStatic.h"
39193323Sed#include "llvm/Support/PluginLoader.h"
40193323Sed#include "llvm/Support/PrettyStackTrace.h"
41218885Sdim#include "llvm/Support/Signals.h"
42249423Sdim#include "llvm/Support/SourceMgr.h"
43226584Sdim#include "llvm/Support/TargetRegistry.h"
44226584Sdim#include "llvm/Support/TargetSelect.h"
45249423Sdim#include "llvm/Support/ToolOutputFile.h"
46198090Srdivacky#include "llvm/Target/TargetMachine.h"
47280031Sdim#include "llvm/Target/TargetSubtargetInfo.h"
48193323Sed#include <memory>
49193323Sedusing namespace llvm;
50193323Sed
51193323Sed// General options for llc.  Other pass-specific options are specified
52193323Sed// within the corresponding llc passes, and target-specific options
53193323Sed// and back-end code generation options are specified with the target machine.
54193323Sed//
55193323Sedstatic cl::opt<std::string>
56193323SedInputFilename(cl::Positional, cl::desc("<input bitcode>"), cl::init("-"));
57193323Sed
58193323Sedstatic cl::opt<std::string>
59193323SedOutputFilename("o", cl::desc("Output filename"), cl::value_desc("filename"));
60193323Sed
61249423Sdimstatic cl::opt<unsigned>
62249423SdimTimeCompilations("time-compilations", cl::Hidden, cl::init(1u),
63249423Sdim                 cl::value_desc("N"),
64249423Sdim                 cl::desc("Repeat compilation N times for timing"));
65249423Sdim
66276479Sdimstatic cl::opt<bool>
67276479SdimNoIntegratedAssembler("no-integrated-as", cl::Hidden,
68276479Sdim                      cl::desc("Disable integrated assembler"));
69276479Sdim
70193323Sed// Determine optimization level.
71193323Sedstatic cl::opt<char>
72193323SedOptLevel("O",
73193323Sed         cl::desc("Optimization level. [-O0, -O1, -O2, or -O3] "
74193323Sed                  "(default = '-O2')"),
75193323Sed         cl::Prefix,
76193323Sed         cl::ZeroOrMore,
77193323Sed         cl::init(' '));
78193323Sed
79193323Sedstatic cl::opt<std::string>
80193323SedTargetTriple("mtriple", cl::desc("Override target triple for module"));
81193323Sed
82276479Sdimstatic cl::opt<bool> NoVerify("disable-verify", cl::Hidden,
83276479Sdim                              cl::desc("Do not verify input module"));
84193323Sed
85276479Sdimstatic cl::opt<bool> DisableSimplifyLibCalls("disable-simplify-libcalls",
86276479Sdim                                             cl::desc("Disable simplify-libcalls"));
87239462Sdim
88276479Sdimstatic cl::opt<bool> ShowMCEncoding("show-mc-encoding", cl::Hidden,
89276479Sdim                                    cl::desc("Show encoding in .s output"));
90249423Sdim
91276479Sdimstatic cl::opt<bool> EnableDwarfDirectory(
92276479Sdim    "enable-dwarf-directory", cl::Hidden,
93276479Sdim    cl::desc("Use .file directives with an explicit directory."));
94276479Sdim
95276479Sdimstatic cl::opt<bool> AsmVerbose("asm-verbose",
96276479Sdim                                cl::desc("Add comments to directives."),
97276479Sdim                                cl::init(true));
98276479Sdim
99276479Sdimstatic int compileModule(char **, LLVMContext &);
100276479Sdim
101280031Sdimstatic std::unique_ptr<tool_output_file>
102280031SdimGetOutputStream(const char *TargetName, Triple::OSType OS,
103280031Sdim                const char *ProgName) {
104212793Sdim  // If we don't yet have an output filename, make one.
105212793Sdim  if (OutputFilename.empty()) {
106212793Sdim    if (InputFilename == "-")
107212793Sdim      OutputFilename = "-";
108212793Sdim    else {
109280031Sdim      // If InputFilename ends in .bc or .ll, remove it.
110280031Sdim      StringRef IFN = InputFilename;
111280031Sdim      if (IFN.endswith(".bc") || IFN.endswith(".ll"))
112280031Sdim        OutputFilename = IFN.drop_back(3);
113288943Sdim      else if (IFN.endswith(".mir"))
114288943Sdim        OutputFilename = IFN.drop_back(4);
115280031Sdim      else
116280031Sdim        OutputFilename = IFN;
117193323Sed
118212793Sdim      switch (FileType) {
119212793Sdim      case TargetMachine::CGFT_AssemblyFile:
120212793Sdim        if (TargetName[0] == 'c') {
121212793Sdim          if (TargetName[1] == 0)
122212793Sdim            OutputFilename += ".cbe.c";
123212793Sdim          else if (TargetName[1] == 'p' && TargetName[2] == 'p')
124212793Sdim            OutputFilename += ".cpp";
125212793Sdim          else
126212793Sdim            OutputFilename += ".s";
127212793Sdim        } else
128212793Sdim          OutputFilename += ".s";
129212793Sdim        break;
130212793Sdim      case TargetMachine::CGFT_ObjectFile:
131212793Sdim        if (OS == Triple::Win32)
132212793Sdim          OutputFilename += ".obj";
133212793Sdim        else
134212793Sdim          OutputFilename += ".o";
135212793Sdim        break;
136212793Sdim      case TargetMachine::CGFT_Null:
137212793Sdim        OutputFilename += ".null";
138212793Sdim        break;
139212793Sdim      }
140193323Sed    }
141193323Sed  }
142193323Sed
143212793Sdim  // Decide if we need "binary" output.
144193323Sed  bool Binary = false;
145193323Sed  switch (FileType) {
146203954Srdivacky  case TargetMachine::CGFT_AssemblyFile:
147193323Sed    break;
148203954Srdivacky  case TargetMachine::CGFT_ObjectFile:
149203954Srdivacky  case TargetMachine::CGFT_Null:
150193323Sed    Binary = true;
151193323Sed    break;
152193323Sed  }
153193323Sed
154212793Sdim  // Open the file.
155280031Sdim  std::error_code EC;
156261991Sdim  sys::fs::OpenFlags OpenFlags = sys::fs::F_None;
157276479Sdim  if (!Binary)
158276479Sdim    OpenFlags |= sys::fs::F_Text;
159280031Sdim  auto FDOut = llvm::make_unique<tool_output_file>(OutputFilename, EC,
160280031Sdim                                                   OpenFlags);
161280031Sdim  if (EC) {
162280031Sdim    errs() << EC.message() << '\n';
163276479Sdim    return nullptr;
164193323Sed  }
165193323Sed
166212793Sdim  return FDOut;
167193323Sed}
168193323Sed
169193323Sed// main - Entry point for the llc compiler.
170193323Sed//
171193323Sedint main(int argc, char **argv) {
172193323Sed  sys::PrintStackTraceOnErrorSignal();
173193323Sed  PrettyStackTraceProgram X(argc, argv);
174202375Srdivacky
175202375Srdivacky  // Enable debug stream buffering.
176202375Srdivacky  EnableDebugBuffering = true;
177202375Srdivacky
178198090Srdivacky  LLVMContext &Context = getGlobalContext();
179193323Sed  llvm_shutdown_obj Y;  // Call llvm_shutdown() on exit.
180193323Sed
181198090Srdivacky  // Initialize targets first, so that --version shows registered targets.
182194612Sed  InitializeAllTargets();
183226584Sdim  InitializeAllTargetMCs();
184194612Sed  InitializeAllAsmPrinters();
185206274Srdivacky  InitializeAllAsmParsers();
186198090Srdivacky
187239462Sdim  // Initialize codegen and IR passes used by llc so that the -print-after,
188239462Sdim  // -print-before, and -stop-after options work.
189239462Sdim  PassRegistry *Registry = PassRegistry::getPassRegistry();
190239462Sdim  initializeCore(*Registry);
191239462Sdim  initializeCodeGen(*Registry);
192239462Sdim  initializeLoopStrengthReducePass(*Registry);
193239462Sdim  initializeLowerIntrinsicsPass(*Registry);
194239462Sdim  initializeUnreachableBlockElimPass(*Registry);
195239462Sdim
196226584Sdim  // Register the target printer for --version.
197226584Sdim  cl::AddExtraVersionPrinter(TargetRegistry::printRegisteredTargetsForVersion);
198226584Sdim
199198090Srdivacky  cl::ParseCommandLineOptions(argc, argv, "llvm system compiler\n");
200221337Sdim
201249423Sdim  // Compile the module TimeCompilations times to give better compile time
202249423Sdim  // metrics.
203249423Sdim  for (unsigned I = TimeCompilations; I; --I)
204249423Sdim    if (int RetVal = compileModule(argv, Context))
205249423Sdim      return RetVal;
206249423Sdim  return 0;
207249423Sdim}
208249423Sdim
209249423Sdimstatic int compileModule(char **argv, LLVMContext &Context) {
210193323Sed  // Load the module to be compiled...
211198090Srdivacky  SMDiagnostic Err;
212276479Sdim  std::unique_ptr<Module> M;
213288943Sdim  std::unique_ptr<MIRParser> MIR;
214239462Sdim  Triple TheTriple;
215193323Sed
216239462Sdim  bool SkipModule = MCPU == "help" ||
217239462Sdim                    (!MAttrs.empty() && MAttrs.front() == "help");
218193323Sed
219239462Sdim  // If user just wants to list available options, skip module loading
220239462Sdim  if (!SkipModule) {
221288943Sdim    if (StringRef(InputFilename).endswith_lower(".mir")) {
222288943Sdim      MIR = createMIRParserFromFile(InputFilename, Err, Context);
223288943Sdim      if (MIR) {
224288943Sdim        M = MIR->parseLLVMModule();
225288943Sdim        assert(M && "parseLLVMModule should exit on failure");
226288943Sdim      }
227288943Sdim    } else
228288943Sdim      M = parseIRFile(InputFilename, Err, Context);
229280031Sdim    if (!M) {
230239462Sdim      Err.print(argv[0], errs());
231198090Srdivacky      return 1;
232198090Srdivacky    }
233198090Srdivacky
234288943Sdim    // Verify module immediately to catch problems before doInitialization() is
235288943Sdim    // called on any passes.
236288943Sdim    if (!NoVerify && verifyModule(*M, &errs())) {
237288943Sdim      errs() << argv[0] << ": " << InputFilename
238288943Sdim             << ": error: input module is broken!\n";
239288943Sdim      return 1;
240288943Sdim    }
241288943Sdim
242239462Sdim    // If we are supposed to override the target triple, do so now.
243239462Sdim    if (!TargetTriple.empty())
244280031Sdim      M->setTargetTriple(Triple::normalize(TargetTriple));
245280031Sdim    TheTriple = Triple(M->getTargetTriple());
246198090Srdivacky  } else {
247239462Sdim    TheTriple = Triple(Triple::normalize(TargetTriple));
248193323Sed  }
249193323Sed
250239462Sdim  if (TheTriple.getTriple().empty())
251239462Sdim    TheTriple.setTriple(sys::getDefaultTargetTriple());
252239462Sdim
253239462Sdim  // Get the target specific parser.
254239462Sdim  std::string Error;
255239462Sdim  const Target *TheTarget = TargetRegistry::lookupTarget(MArch, TheTriple,
256239462Sdim                                                         Error);
257239462Sdim  if (!TheTarget) {
258239462Sdim    errs() << argv[0] << ": " << Error;
259239462Sdim    return 1;
260239462Sdim  }
261239462Sdim
262288943Sdim  std::string CPUStr = getCPUStr(), FeaturesStr = getFeaturesStr();
263193323Sed
264234353Sdim  CodeGenOpt::Level OLvl = CodeGenOpt::Default;
265234353Sdim  switch (OptLevel) {
266234353Sdim  default:
267234353Sdim    errs() << argv[0] << ": invalid optimization level.\n";
268234353Sdim    return 1;
269234353Sdim  case ' ': break;
270234353Sdim  case '0': OLvl = CodeGenOpt::None; break;
271234353Sdim  case '1': OLvl = CodeGenOpt::Less; break;
272234353Sdim  case '2': OLvl = CodeGenOpt::Default; break;
273234353Sdim  case '3': OLvl = CodeGenOpt::Aggressive; break;
274234353Sdim  }
275234353Sdim
276276479Sdim  TargetOptions Options = InitTargetOptionsFromCodeGenFlags();
277276479Sdim  Options.DisableIntegratedAS = NoIntegratedAssembler;
278276479Sdim  Options.MCOptions.ShowMCEncoding = ShowMCEncoding;
279276479Sdim  Options.MCOptions.MCUseDwarfDirectory = EnableDwarfDirectory;
280276479Sdim  Options.MCOptions.AsmVerbose = AsmVerbose;
281234353Sdim
282280031Sdim  std::unique_ptr<TargetMachine> Target(
283288943Sdim      TheTarget->createTargetMachine(TheTriple.getTriple(), CPUStr, FeaturesStr,
284276479Sdim                                     Options, RelocModel, CMModel, OLvl));
285288943Sdim
286280031Sdim  assert(Target && "Could not allocate target machine!");
287193323Sed
288276479Sdim  // If we don't have a module then just exit now. We do this down
289276479Sdim  // here since the CPU/Feature help is underneath the target machine
290276479Sdim  // creation.
291276479Sdim  if (SkipModule)
292276479Sdim    return 0;
293218885Sdim
294280031Sdim  assert(M && "Should have exited if we didn't have a module!");
295288943Sdim  if (FloatABIForCalls != FloatABI::Default)
296288943Sdim    Options.FloatABIType = FloatABIForCalls;
297221337Sdim
298239462Sdim  // Figure out where we are going to send the output.
299280031Sdim  std::unique_ptr<tool_output_file> Out =
300280031Sdim      GetOutputStream(TheTarget->getName(), TheTriple.getOS(), argv[0]);
301212793Sdim  if (!Out) return 1;
302193323Sed
303208599Srdivacky  // Build up all of the passes that we want to do to the module.
304288943Sdim  legacy::PassManager PM;
305198090Srdivacky
306239462Sdim  // Add an appropriate TargetLibraryInfo pass for the module's triple.
307288943Sdim  TargetLibraryInfoImpl TLII(Triple(M->getTargetTriple()));
308288943Sdim
309288943Sdim  // The -disable-simplify-libcalls flag actually disables all builtin optzns.
310239462Sdim  if (DisableSimplifyLibCalls)
311288943Sdim    TLII.disableAllFunctions();
312288943Sdim  PM.add(new TargetLibraryInfoWrapperPass(TLII));
313239462Sdim
314208599Srdivacky  // Add the target data from the target machine, if it exists, or the module.
315288943Sdim  if (const DataLayout *DL = Target->getDataLayout())
316288943Sdim    M->setDataLayout(*DL);
317198090Srdivacky
318288943Sdim  // Override function attributes based on CPUStr, FeaturesStr, and command line
319288943Sdim  // flags.
320288943Sdim  setFunctionAttributes(CPUStr, FeaturesStr, *M);
321288943Sdim
322276479Sdim  if (RelaxAll.getNumOccurrences() > 0 &&
323276479Sdim      FileType != TargetMachine::CGFT_ObjectFile)
324276479Sdim    errs() << argv[0]
325212793Sdim             << ": warning: ignoring -mc-relax-all because filetype != obj";
326198090Srdivacky
327212793Sdim  {
328288943Sdim    raw_pwrite_stream *OS = &Out->os();
329288943Sdim    std::unique_ptr<buffer_ostream> BOS;
330288943Sdim    if (FileType != TargetMachine::CGFT_AssemblyFile &&
331288943Sdim        !Out->os().supportsSeeking()) {
332288943Sdim      BOS = make_unique<buffer_ostream>(*OS);
333288943Sdim      OS = BOS.get();
334288943Sdim    }
335193323Sed
336288943Sdim    AnalysisID StartBeforeID = nullptr;
337276479Sdim    AnalysisID StartAfterID = nullptr;
338276479Sdim    AnalysisID StopAfterID = nullptr;
339239462Sdim    const PassRegistry *PR = PassRegistry::getPassRegistry();
340288943Sdim    if (!RunPass.empty()) {
341288943Sdim      if (!StartAfter.empty() || !StopAfter.empty()) {
342288943Sdim        errs() << argv[0] << ": start-after and/or stop-after passes are "
343288943Sdim                             "redundant when run-pass is specified.\n";
344239462Sdim        return 1;
345239462Sdim      }
346288943Sdim      const PassInfo *PI = PR->getPassInfo(RunPass);
347239462Sdim      if (!PI) {
348288943Sdim        errs() << argv[0] << ": run-pass pass is not registered.\n";
349239462Sdim        return 1;
350239462Sdim      }
351288943Sdim      StopAfterID = StartBeforeID = PI->getTypeInfo();
352288943Sdim    } else {
353288943Sdim      if (!StartAfter.empty()) {
354288943Sdim        const PassInfo *PI = PR->getPassInfo(StartAfter);
355288943Sdim        if (!PI) {
356288943Sdim          errs() << argv[0] << ": start-after pass is not registered.\n";
357288943Sdim          return 1;
358288943Sdim        }
359288943Sdim        StartAfterID = PI->getTypeInfo();
360288943Sdim      }
361288943Sdim      if (!StopAfter.empty()) {
362288943Sdim        const PassInfo *PI = PR->getPassInfo(StopAfter);
363288943Sdim        if (!PI) {
364288943Sdim          errs() << argv[0] << ": stop-after pass is not registered.\n";
365288943Sdim          return 1;
366288943Sdim        }
367288943Sdim        StopAfterID = PI->getTypeInfo();
368288943Sdim      }
369239462Sdim    }
370239462Sdim
371212793Sdim    // Ask the target to add backend passes as necessary.
372288943Sdim    if (Target->addPassesToEmitFile(PM, *OS, FileType, NoVerify, StartBeforeID,
373288943Sdim                                    StartAfterID, StopAfterID, MIR.get())) {
374212793Sdim      errs() << argv[0] << ": target does not support generation of this"
375212793Sdim             << " file type!\n";
376212793Sdim      return 1;
377212793Sdim    }
378193323Sed
379221337Sdim    // Before executing passes, print the final values of the LLVM options.
380221337Sdim    cl::PrintOptionValues();
381221337Sdim
382280031Sdim    PM.run(*M);
383212793Sdim  }
384212793Sdim
385212793Sdim  // Declare success.
386212793Sdim  Out->keep();
387212793Sdim
388193323Sed  return 0;
389193323Sed}
390