llc.cpp revision de2d8694e25a814696358e95141f4b1aa4d8847e
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
16
17#include "llvm/ADT/STLExtras.h"
18#include "llvm/ADT/Triple.h"
19#include "llvm/Analysis/TargetLibraryInfo.h"
20#include "llvm/CodeGen/CommandFlags.h"
21#include "llvm/CodeGen/LinkAllAsmWriterComponents.h"
22#include "llvm/CodeGen/LinkAllCodegenComponents.h"
23#include "llvm/CodeGen/MIRParser/MIRParser.h"
24#include "llvm/CodeGen/MachineFunctionPass.h"
25#include "llvm/CodeGen/MachineModuleInfo.h"
26#include "llvm/CodeGen/TargetPassConfig.h"
27#include "llvm/IR/DataLayout.h"
28#include "llvm/IR/DiagnosticInfo.h"
29#include "llvm/IR/DiagnosticPrinter.h"
30#include "llvm/IR/IRPrintingPasses.h"
31#include "llvm/IR/LLVMContext.h"
32#include "llvm/IR/LegacyPassManager.h"
33#include "llvm/IR/Module.h"
34#include "llvm/IR/Verifier.h"
35#include "llvm/IRReader/IRReader.h"
36#include "llvm/MC/SubtargetFeature.h"
37#include "llvm/Pass.h"
38#include "llvm/Support/CommandLine.h"
39#include "llvm/Support/Debug.h"
40#include "llvm/Support/FileSystem.h"
41#include "llvm/Support/FormattedStream.h"
42#include "llvm/Support/Host.h"
43#include "llvm/Support/ManagedStatic.h"
44#include "llvm/Support/PluginLoader.h"
45#include "llvm/Support/PrettyStackTrace.h"
46#include "llvm/Support/Signals.h"
47#include "llvm/Support/SourceMgr.h"
48#include "llvm/Support/TargetRegistry.h"
49#include "llvm/Support/TargetSelect.h"
50#include "llvm/Support/ToolOutputFile.h"
51#include "llvm/Target/TargetMachine.h"
52#include "llvm/Target/TargetSubtargetInfo.h"
53#include "llvm/Transforms/Utils/Cloning.h"
54#include <memory>
55using namespace llvm;
56
57// General options for llc.  Other pass-specific options are specified
58// within the corresponding llc passes, and target-specific options
59// and back-end code generation options are specified with the target machine.
60//
61static cl::opt<std::string>
62InputFilename(cl::Positional, cl::desc("<input bitcode>"), cl::init("-"));
63
64static cl::opt<std::string>
65OutputFilename("o", cl::desc("Output filename"), cl::value_desc("filename"));
66
67static cl::opt<unsigned>
68TimeCompilations("time-compilations", cl::Hidden, cl::init(1u),
69                 cl::value_desc("N"),
70                 cl::desc("Repeat compilation N times for timing"));
71
72static cl::opt<bool>
73NoIntegratedAssembler("no-integrated-as", cl::Hidden,
74                      cl::desc("Disable integrated assembler"));
75
76static cl::opt<bool>
77    PreserveComments("preserve-as-comments", cl::Hidden,
78                     cl::desc("Preserve Comments in outputted assembly"),
79                     cl::init(true));
80
81// Determine optimization level.
82static cl::opt<char>
83OptLevel("O",
84         cl::desc("Optimization level. [-O0, -O1, -O2, or -O3] "
85                  "(default = '-O2')"),
86         cl::Prefix,
87         cl::ZeroOrMore,
88         cl::init(' '));
89
90static cl::opt<std::string>
91TargetTriple("mtriple", cl::desc("Override target triple for module"));
92
93static cl::opt<bool> NoVerify("disable-verify", cl::Hidden,
94                              cl::desc("Do not verify input module"));
95
96static cl::opt<bool> DisableSimplifyLibCalls("disable-simplify-libcalls",
97                                             cl::desc("Disable simplify-libcalls"));
98
99static cl::opt<bool> ShowMCEncoding("show-mc-encoding", cl::Hidden,
100                                    cl::desc("Show encoding in .s output"));
101
102static cl::opt<bool> EnableDwarfDirectory(
103    "enable-dwarf-directory", cl::Hidden,
104    cl::desc("Use .file directives with an explicit directory."));
105
106static cl::opt<bool> AsmVerbose("asm-verbose",
107                                cl::desc("Add comments to directives."),
108                                cl::init(true));
109
110static cl::opt<bool>
111    CompileTwice("compile-twice", cl::Hidden,
112                 cl::desc("Run everything twice, re-using the same pass "
113                          "manager and verify the result is the same."),
114                 cl::init(false));
115
116static cl::opt<bool> DiscardValueNames(
117    "discard-value-names",
118    cl::desc("Discard names from Value (other than GlobalValue)."),
119    cl::init(false), cl::Hidden);
120
121namespace {
122static ManagedStatic<std::vector<std::string>> RunPassNames;
123
124struct RunPassOption {
125  void operator=(const std::string &Val) const {
126    if (Val.empty())
127      return;
128    SmallVector<StringRef, 8> PassNames;
129    StringRef(Val).split(PassNames, ',', -1, false);
130    for (auto PassName : PassNames)
131      RunPassNames->push_back(PassName);
132  }
133};
134}
135
136static RunPassOption RunPassOpt;
137
138static cl::opt<RunPassOption, true, cl::parser<std::string>> RunPass(
139    "run-pass",
140    cl::desc("Run compiler only for specified passes (comma separated list)"),
141    cl::value_desc("pass-name"), cl::ZeroOrMore, cl::location(RunPassOpt));
142
143static int compileModule(char **, LLVMContext &);
144
145static std::unique_ptr<tool_output_file>
146GetOutputStream(const char *TargetName, Triple::OSType OS,
147                const char *ProgName) {
148  // If we don't yet have an output filename, make one.
149  if (OutputFilename.empty()) {
150    if (InputFilename == "-")
151      OutputFilename = "-";
152    else {
153      // If InputFilename ends in .bc or .ll, remove it.
154      StringRef IFN = InputFilename;
155      if (IFN.endswith(".bc") || IFN.endswith(".ll"))
156        OutputFilename = IFN.drop_back(3);
157      else if (IFN.endswith(".mir"))
158        OutputFilename = IFN.drop_back(4);
159      else
160        OutputFilename = IFN;
161
162      switch (FileType) {
163      case TargetMachine::CGFT_AssemblyFile:
164        if (TargetName[0] == 'c') {
165          if (TargetName[1] == 0)
166            OutputFilename += ".cbe.c";
167          else if (TargetName[1] == 'p' && TargetName[2] == 'p')
168            OutputFilename += ".cpp";
169          else
170            OutputFilename += ".s";
171        } else
172          OutputFilename += ".s";
173        break;
174      case TargetMachine::CGFT_ObjectFile:
175        if (OS == Triple::Win32)
176          OutputFilename += ".obj";
177        else
178          OutputFilename += ".o";
179        break;
180      case TargetMachine::CGFT_Null:
181        OutputFilename += ".null";
182        break;
183      }
184    }
185  }
186
187  // Decide if we need "binary" output.
188  bool Binary = false;
189  switch (FileType) {
190  case TargetMachine::CGFT_AssemblyFile:
191    break;
192  case TargetMachine::CGFT_ObjectFile:
193  case TargetMachine::CGFT_Null:
194    Binary = true;
195    break;
196  }
197
198  // Open the file.
199  std::error_code EC;
200  sys::fs::OpenFlags OpenFlags = sys::fs::F_None;
201  if (!Binary)
202    OpenFlags |= sys::fs::F_Text;
203  auto FDOut = llvm::make_unique<tool_output_file>(OutputFilename, EC,
204                                                   OpenFlags);
205  if (EC) {
206    errs() << EC.message() << '\n';
207    return nullptr;
208  }
209
210  return FDOut;
211}
212
213static void DiagnosticHandler(const DiagnosticInfo &DI, void *Context) {
214  bool *HasError = static_cast<bool *>(Context);
215  if (DI.getSeverity() == DS_Error)
216    *HasError = true;
217
218  DiagnosticPrinterRawOStream DP(errs());
219  errs() << LLVMContext::getDiagnosticMessagePrefix(DI.getSeverity()) << ": ";
220  DI.print(DP);
221  errs() << "\n";
222}
223
224// main - Entry point for the llc compiler.
225//
226int main(int argc, char **argv) {
227  sys::PrintStackTraceOnErrorSignal(argv[0]);
228  PrettyStackTraceProgram X(argc, argv);
229
230  // Enable debug stream buffering.
231  EnableDebugBuffering = true;
232
233  LLVMContext Context;
234  llvm_shutdown_obj Y;  // Call llvm_shutdown() on exit.
235
236  // Initialize targets first, so that --version shows registered targets.
237  InitializeAllTargets();
238  InitializeAllTargetMCs();
239  InitializeAllAsmPrinters();
240  InitializeAllAsmParsers();
241
242  // Initialize codegen and IR passes used by llc so that the -print-after,
243  // -print-before, and -stop-after options work.
244  PassRegistry *Registry = PassRegistry::getPassRegistry();
245  initializeCore(*Registry);
246  initializeCodeGen(*Registry);
247  initializeLoopStrengthReducePass(*Registry);
248  initializeLowerIntrinsicsPass(*Registry);
249  initializeUnreachableBlockElimLegacyPassPass(*Registry);
250
251  // Register the target printer for --version.
252  cl::AddExtraVersionPrinter(TargetRegistry::printRegisteredTargetsForVersion);
253
254  cl::ParseCommandLineOptions(argc, argv, "llvm system compiler\n");
255
256  Context.setDiscardValueNames(DiscardValueNames);
257
258  // Set a diagnostic handler that doesn't exit on the first error
259  bool HasError = false;
260  Context.setDiagnosticHandler(DiagnosticHandler, &HasError);
261
262  // Compile the module TimeCompilations times to give better compile time
263  // metrics.
264  for (unsigned I = TimeCompilations; I; --I)
265    if (int RetVal = compileModule(argv, Context))
266      return RetVal;
267  return 0;
268}
269
270static int compileModule(char **argv, LLVMContext &Context) {
271  // Load the module to be compiled...
272  SMDiagnostic Err;
273  std::unique_ptr<Module> M;
274  std::unique_ptr<MIRParser> MIR;
275  Triple TheTriple;
276
277  bool SkipModule = MCPU == "help" ||
278                    (!MAttrs.empty() && MAttrs.front() == "help");
279
280  // If user just wants to list available options, skip module loading
281  if (!SkipModule) {
282    if (StringRef(InputFilename).endswith_lower(".mir")) {
283      MIR = createMIRParserFromFile(InputFilename, Err, Context);
284      if (MIR)
285        M = MIR->parseLLVMModule();
286    } else
287      M = parseIRFile(InputFilename, Err, Context);
288    if (!M) {
289      Err.print(argv[0], errs());
290      return 1;
291    }
292
293    // Verify module immediately to catch problems before doInitialization() is
294    // called on any passes.
295    if (!NoVerify && verifyModule(*M, &errs())) {
296      errs() << argv[0] << ": " << InputFilename
297             << ": error: input module is broken!\n";
298      return 1;
299    }
300
301    // If we are supposed to override the target triple, do so now.
302    if (!TargetTriple.empty())
303      M->setTargetTriple(Triple::normalize(TargetTriple));
304    TheTriple = Triple(M->getTargetTriple());
305  } else {
306    TheTriple = Triple(Triple::normalize(TargetTriple));
307  }
308
309  if (TheTriple.getTriple().empty())
310    TheTriple.setTriple(sys::getDefaultTargetTriple());
311
312  // Get the target specific parser.
313  std::string Error;
314  const Target *TheTarget = TargetRegistry::lookupTarget(MArch, TheTriple,
315                                                         Error);
316  if (!TheTarget) {
317    errs() << argv[0] << ": " << Error;
318    return 1;
319  }
320
321  std::string CPUStr = getCPUStr(), FeaturesStr = getFeaturesStr();
322
323  CodeGenOpt::Level OLvl = CodeGenOpt::Default;
324  switch (OptLevel) {
325  default:
326    errs() << argv[0] << ": invalid optimization level.\n";
327    return 1;
328  case ' ': break;
329  case '0': OLvl = CodeGenOpt::None; break;
330  case '1': OLvl = CodeGenOpt::Less; break;
331  case '2': OLvl = CodeGenOpt::Default; break;
332  case '3': OLvl = CodeGenOpt::Aggressive; break;
333  }
334
335  TargetOptions Options = InitTargetOptionsFromCodeGenFlags();
336  Options.DisableIntegratedAS = NoIntegratedAssembler;
337  Options.MCOptions.ShowMCEncoding = ShowMCEncoding;
338  Options.MCOptions.MCUseDwarfDirectory = EnableDwarfDirectory;
339  Options.MCOptions.AsmVerbose = AsmVerbose;
340  Options.MCOptions.PreserveAsmComments = PreserveComments;
341
342  std::unique_ptr<TargetMachine> Target(
343      TheTarget->createTargetMachine(TheTriple.getTriple(), CPUStr, FeaturesStr,
344                                     Options, getRelocModel(), CMModel, OLvl));
345
346  assert(Target && "Could not allocate target machine!");
347
348  // If we don't have a module then just exit now. We do this down
349  // here since the CPU/Feature help is underneath the target machine
350  // creation.
351  if (SkipModule)
352    return 0;
353
354  assert(M && "Should have exited if we didn't have a module!");
355  if (FloatABIForCalls != FloatABI::Default)
356    Options.FloatABIType = FloatABIForCalls;
357
358  // Figure out where we are going to send the output.
359  std::unique_ptr<tool_output_file> Out =
360      GetOutputStream(TheTarget->getName(), TheTriple.getOS(), argv[0]);
361  if (!Out) return 1;
362
363  // Build up all of the passes that we want to do to the module.
364  legacy::PassManager PM;
365
366  // Add an appropriate TargetLibraryInfo pass for the module's triple.
367  TargetLibraryInfoImpl TLII(Triple(M->getTargetTriple()));
368
369  // The -disable-simplify-libcalls flag actually disables all builtin optzns.
370  if (DisableSimplifyLibCalls)
371    TLII.disableAllFunctions();
372  PM.add(new TargetLibraryInfoWrapperPass(TLII));
373
374  // Add the target data from the target machine, if it exists, or the module.
375  M->setDataLayout(Target->createDataLayout());
376
377  // Override function attributes based on CPUStr, FeaturesStr, and command line
378  // flags.
379  setFunctionAttributes(CPUStr, FeaturesStr, *M);
380
381  if (RelaxAll.getNumOccurrences() > 0 &&
382      FileType != TargetMachine::CGFT_ObjectFile)
383    errs() << argv[0]
384             << ": warning: ignoring -mc-relax-all because filetype != obj";
385
386  {
387    raw_pwrite_stream *OS = &Out->os();
388
389    // Manually do the buffering rather than using buffer_ostream,
390    // so we can memcmp the contents in CompileTwice mode
391    SmallVector<char, 0> Buffer;
392    std::unique_ptr<raw_svector_ostream> BOS;
393    if ((FileType != TargetMachine::CGFT_AssemblyFile &&
394         !Out->os().supportsSeeking()) ||
395        CompileTwice) {
396      BOS = make_unique<raw_svector_ostream>(Buffer);
397      OS = BOS.get();
398    }
399
400    AnalysisID StartBeforeID = nullptr;
401    AnalysisID StartAfterID = nullptr;
402    AnalysisID StopAfterID = nullptr;
403    const PassRegistry *PR = PassRegistry::getPassRegistry();
404    if (!RunPassNames->empty()) {
405      if (!StartAfter.empty() || !StopAfter.empty()) {
406        errs() << argv[0] << ": start-after and/or stop-after passes are "
407                             "redundant when run-pass is specified.\n";
408        return 1;
409      }
410      if (!MIR) {
411        errs() << argv[0] << ": run-pass needs a .mir input.\n";
412        return 1;
413      }
414      LLVMTargetMachine &LLVMTM = static_cast<LLVMTargetMachine&>(*Target);
415      TargetPassConfig *TPC = LLVMTM.createPassConfig(PM);
416      PM.add(TPC);
417      LLVMTM.addMachineModuleInfo(PM);
418      LLVMTM.addMachineFunctionAnalysis(PM, MIR.get());
419      TPC->printAndVerify("");
420
421      for (std::string &RunPassName : *RunPassNames) {
422        const PassInfo *PI = PR->getPassInfo(RunPassName);
423        if (!PI) {
424          errs() << argv[0] << ": run-pass " << RunPassName << " is not registered.\n";
425          return 1;
426        }
427
428        Pass *P;
429        if (PI->getTargetMachineCtor())
430          P = PI->getTargetMachineCtor()(Target.get());
431        else if (PI->getNormalCtor())
432          P = PI->getNormalCtor()();
433        else {
434          errs() << argv[0] << ": cannot create pass: "
435                 << PI->getPassName() << "\n";
436          return 1;
437        }
438        std::string Banner
439          = std::string("After ") + std::string(P->getPassName());
440        PM.add(P);
441        TPC->printAndVerify(Banner);
442      }
443      PM.add(createPrintMIRPass(*OS));
444    } else {
445      if (!StartAfter.empty()) {
446        const PassInfo *PI = PR->getPassInfo(StartAfter);
447        if (!PI) {
448          errs() << argv[0] << ": start-after pass is not registered.\n";
449          return 1;
450        }
451        StartAfterID = PI->getTypeInfo();
452      }
453      if (!StopAfter.empty()) {
454        const PassInfo *PI = PR->getPassInfo(StopAfter);
455        if (!PI) {
456          errs() << argv[0] << ": stop-after pass is not registered.\n";
457          return 1;
458        }
459        StopAfterID = PI->getTypeInfo();
460      }
461
462      // Ask the target to add backend passes as necessary.
463      if (Target->addPassesToEmitFile(PM, *OS, FileType, NoVerify,
464                                      StartBeforeID, StartAfterID, StopAfterID,
465                                      MIR.get())) {
466        errs() << argv[0] << ": target does not support generation of this"
467               << " file type!\n";
468        return 1;
469      }
470    }
471
472    // Before executing passes, print the final values of the LLVM options.
473    cl::PrintOptionValues();
474
475    // If requested, run the pass manager over the same module again,
476    // to catch any bugs due to persistent state in the passes. Note that
477    // opt has the same functionality, so it may be worth abstracting this out
478    // in the future.
479    SmallVector<char, 0> CompileTwiceBuffer;
480    if (CompileTwice) {
481      std::unique_ptr<Module> M2(llvm::CloneModule(M.get()));
482      PM.run(*M2);
483      CompileTwiceBuffer = Buffer;
484      Buffer.clear();
485    }
486
487    PM.run(*M);
488
489    auto HasError = *static_cast<bool *>(Context.getDiagnosticContext());
490    if (HasError)
491      return 1;
492
493    // Compare the two outputs and make sure they're the same
494    if (CompileTwice) {
495      if (Buffer.size() != CompileTwiceBuffer.size() ||
496          (memcmp(Buffer.data(), CompileTwiceBuffer.data(), Buffer.size()) !=
497           0)) {
498        errs()
499            << "Running the pass manager twice changed the output.\n"
500               "Writing the result of the second run to the specified output\n"
501               "To generate the one-run comparison binary, just run without\n"
502               "the compile-twice option\n";
503        Out->os() << Buffer;
504        Out->keep();
505        return 1;
506      }
507    }
508
509    if (BOS) {
510      Out->os() << Buffer;
511    }
512  }
513
514  // Declare success.
515  Out->keep();
516
517  return 0;
518}
519