]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/tools/llc/llc.cpp
Merge llvm, clang, lld, lldb, compiler-rt and libc++ r302069, and update
[FreeBSD/FreeBSD.git] / contrib / llvm / tools / llc / llc.cpp
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>
55 using 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 //
61 static cl::opt<std::string>
62 InputFilename(cl::Positional, cl::desc("<input bitcode>"), cl::init("-"));
63
64 static cl::opt<std::string>
65 OutputFilename("o", cl::desc("Output filename"), cl::value_desc("filename"));
66
67 static cl::opt<unsigned>
68 TimeCompilations("time-compilations", cl::Hidden, cl::init(1u),
69                  cl::value_desc("N"),
70                  cl::desc("Repeat compilation N times for timing"));
71
72 static cl::opt<bool>
73 NoIntegratedAssembler("no-integrated-as", cl::Hidden,
74                       cl::desc("Disable integrated assembler"));
75
76 static 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.
82 static cl::opt<char>
83 OptLevel("O",
84          cl::desc("Optimization level. [-O0, -O1, -O2, or -O3] "
85                   "(default = '-O2')"),
86          cl::Prefix,
87          cl::ZeroOrMore,
88          cl::init(' '));
89
90 static cl::opt<std::string>
91 TargetTriple("mtriple", cl::desc("Override target triple for module"));
92
93 static cl::opt<std::string> SplitDwarfFile(
94     "split-dwarf-file",
95     cl::desc(
96         "Specify the name of the .dwo file to encode in the DWARF output"));
97
98 static cl::opt<bool> NoVerify("disable-verify", cl::Hidden,
99                               cl::desc("Do not verify input module"));
100
101 static cl::opt<bool> DisableSimplifyLibCalls("disable-simplify-libcalls",
102                                              cl::desc("Disable simplify-libcalls"));
103
104 static cl::opt<bool> ShowMCEncoding("show-mc-encoding", cl::Hidden,
105                                     cl::desc("Show encoding in .s output"));
106
107 static cl::opt<bool> EnableDwarfDirectory(
108     "enable-dwarf-directory", cl::Hidden,
109     cl::desc("Use .file directives with an explicit directory."));
110
111 static cl::opt<bool> AsmVerbose("asm-verbose",
112                                 cl::desc("Add comments to directives."),
113                                 cl::init(true));
114
115 static cl::opt<bool>
116     CompileTwice("compile-twice", cl::Hidden,
117                  cl::desc("Run everything twice, re-using the same pass "
118                           "manager and verify the result is the same."),
119                  cl::init(false));
120
121 static cl::opt<bool> DiscardValueNames(
122     "discard-value-names",
123     cl::desc("Discard names from Value (other than GlobalValue)."),
124     cl::init(false), cl::Hidden);
125
126 static cl::opt<std::string> StopBefore("stop-before",
127     cl::desc("Stop compilation before a specific pass"),
128     cl::value_desc("pass-name"), cl::init(""));
129
130 static cl::opt<std::string> StopAfter("stop-after",
131     cl::desc("Stop compilation after a specific pass"),
132     cl::value_desc("pass-name"), cl::init(""));
133
134 static cl::opt<std::string> StartBefore("start-before",
135     cl::desc("Resume compilation before a specific pass"),
136     cl::value_desc("pass-name"), cl::init(""));
137
138 static cl::opt<std::string> StartAfter("start-after",
139     cl::desc("Resume compilation after a specific pass"),
140     cl::value_desc("pass-name"), cl::init(""));
141
142 static cl::list<std::string> IncludeDirs("I", cl::desc("include search path"));
143
144 static cl::opt<bool> PassRemarksWithHotness(
145     "pass-remarks-with-hotness",
146     cl::desc("With PGO, include profile count in optimization remarks"),
147     cl::Hidden);
148
149 static cl::opt<std::string>
150     RemarksFilename("pass-remarks-output",
151                     cl::desc("YAML output filename for pass remarks"),
152                     cl::value_desc("filename"));
153
154 namespace {
155 static ManagedStatic<std::vector<std::string>> RunPassNames;
156
157 struct RunPassOption {
158   void operator=(const std::string &Val) const {
159     if (Val.empty())
160       return;
161     SmallVector<StringRef, 8> PassNames;
162     StringRef(Val).split(PassNames, ',', -1, false);
163     for (auto PassName : PassNames)
164       RunPassNames->push_back(PassName);
165   }
166 };
167 }
168
169 static RunPassOption RunPassOpt;
170
171 static cl::opt<RunPassOption, true, cl::parser<std::string>> RunPass(
172     "run-pass",
173     cl::desc("Run compiler only for specified passes (comma separated list)"),
174     cl::value_desc("pass-name"), cl::ZeroOrMore, cl::location(RunPassOpt));
175
176 static int compileModule(char **, LLVMContext &);
177
178 static std::unique_ptr<tool_output_file>
179 GetOutputStream(const char *TargetName, Triple::OSType OS,
180                 const char *ProgName) {
181   // If we don't yet have an output filename, make one.
182   if (OutputFilename.empty()) {
183     if (InputFilename == "-")
184       OutputFilename = "-";
185     else {
186       // If InputFilename ends in .bc or .ll, remove it.
187       StringRef IFN = InputFilename;
188       if (IFN.endswith(".bc") || IFN.endswith(".ll"))
189         OutputFilename = IFN.drop_back(3);
190       else if (IFN.endswith(".mir"))
191         OutputFilename = IFN.drop_back(4);
192       else
193         OutputFilename = IFN;
194
195       switch (FileType) {
196       case TargetMachine::CGFT_AssemblyFile:
197         if (TargetName[0] == 'c') {
198           if (TargetName[1] == 0)
199             OutputFilename += ".cbe.c";
200           else if (TargetName[1] == 'p' && TargetName[2] == 'p')
201             OutputFilename += ".cpp";
202           else
203             OutputFilename += ".s";
204         } else
205           OutputFilename += ".s";
206         break;
207       case TargetMachine::CGFT_ObjectFile:
208         if (OS == Triple::Win32)
209           OutputFilename += ".obj";
210         else
211           OutputFilename += ".o";
212         break;
213       case TargetMachine::CGFT_Null:
214         OutputFilename += ".null";
215         break;
216       }
217     }
218   }
219
220   // Decide if we need "binary" output.
221   bool Binary = false;
222   switch (FileType) {
223   case TargetMachine::CGFT_AssemblyFile:
224     break;
225   case TargetMachine::CGFT_ObjectFile:
226   case TargetMachine::CGFT_Null:
227     Binary = true;
228     break;
229   }
230
231   // Open the file.
232   std::error_code EC;
233   sys::fs::OpenFlags OpenFlags = sys::fs::F_None;
234   if (!Binary)
235     OpenFlags |= sys::fs::F_Text;
236   auto FDOut = llvm::make_unique<tool_output_file>(OutputFilename, EC,
237                                                    OpenFlags);
238   if (EC) {
239     errs() << EC.message() << '\n';
240     return nullptr;
241   }
242
243   return FDOut;
244 }
245
246 static void DiagnosticHandler(const DiagnosticInfo &DI, void *Context) {
247   bool *HasError = static_cast<bool *>(Context);
248   if (DI.getSeverity() == DS_Error)
249     *HasError = true;
250
251   if (auto *Remark = dyn_cast<DiagnosticInfoOptimizationBase>(&DI))
252     if (!Remark->isEnabled())
253       return;
254
255   DiagnosticPrinterRawOStream DP(errs());
256   errs() << LLVMContext::getDiagnosticMessagePrefix(DI.getSeverity()) << ": ";
257   DI.print(DP);
258   errs() << "\n";
259 }
260
261 static void InlineAsmDiagHandler(const SMDiagnostic &SMD, void *Context,
262                                  unsigned LocCookie) {
263   bool *HasError = static_cast<bool *>(Context);
264   if (SMD.getKind() == SourceMgr::DK_Error)
265     *HasError = true;
266
267   SMD.print(nullptr, errs());
268
269   // For testing purposes, we print the LocCookie here.
270   if (LocCookie)
271     errs() << "note: !srcloc = " << LocCookie << "\n";
272 }
273
274 // main - Entry point for the llc compiler.
275 //
276 int main(int argc, char **argv) {
277   sys::PrintStackTraceOnErrorSignal(argv[0]);
278   PrettyStackTraceProgram X(argc, argv);
279
280   // Enable debug stream buffering.
281   EnableDebugBuffering = true;
282
283   LLVMContext Context;
284   llvm_shutdown_obj Y;  // Call llvm_shutdown() on exit.
285
286   // Initialize targets first, so that --version shows registered targets.
287   InitializeAllTargets();
288   InitializeAllTargetMCs();
289   InitializeAllAsmPrinters();
290   InitializeAllAsmParsers();
291
292   // Initialize codegen and IR passes used by llc so that the -print-after,
293   // -print-before, and -stop-after options work.
294   PassRegistry *Registry = PassRegistry::getPassRegistry();
295   initializeCore(*Registry);
296   initializeCodeGen(*Registry);
297   initializeLoopStrengthReducePass(*Registry);
298   initializeLowerIntrinsicsPass(*Registry);
299   initializeCountingFunctionInserterPass(*Registry);
300   initializeUnreachableBlockElimLegacyPassPass(*Registry);
301   initializeConstantHoistingLegacyPassPass(*Registry);
302   initializeScalarOpts(*Registry);
303   initializeVectorization(*Registry);
304
305   // Register the target printer for --version.
306   cl::AddExtraVersionPrinter(TargetRegistry::printRegisteredTargetsForVersion);
307
308   cl::ParseCommandLineOptions(argc, argv, "llvm system compiler\n");
309
310   Context.setDiscardValueNames(DiscardValueNames);
311
312   // Set a diagnostic handler that doesn't exit on the first error
313   bool HasError = false;
314   Context.setDiagnosticHandler(DiagnosticHandler, &HasError);
315   Context.setInlineAsmDiagnosticHandler(InlineAsmDiagHandler, &HasError);
316
317   if (PassRemarksWithHotness)
318     Context.setDiagnosticHotnessRequested(true);
319
320   std::unique_ptr<tool_output_file> YamlFile;
321   if (RemarksFilename != "") {
322     std::error_code EC;
323     YamlFile = llvm::make_unique<tool_output_file>(RemarksFilename, EC,
324                                                    sys::fs::F_None);
325     if (EC) {
326       errs() << EC.message() << '\n';
327       return 1;
328     }
329     Context.setDiagnosticsOutputFile(
330         llvm::make_unique<yaml::Output>(YamlFile->os()));
331   }
332
333   // Compile the module TimeCompilations times to give better compile time
334   // metrics.
335   for (unsigned I = TimeCompilations; I; --I)
336     if (int RetVal = compileModule(argv, Context))
337       return RetVal;
338
339   if (YamlFile)
340     YamlFile->keep();
341   return 0;
342 }
343
344 static bool addPass(PassManagerBase &PM, const char *argv0,
345                     StringRef PassName, TargetPassConfig &TPC) {
346   if (PassName == "none")
347     return false;
348
349   const PassRegistry *PR = PassRegistry::getPassRegistry();
350   const PassInfo *PI = PR->getPassInfo(PassName);
351   if (!PI) {
352     errs() << argv0 << ": run-pass " << PassName << " is not registered.\n";
353     return true;
354   }
355
356   Pass *P;
357   if (PI->getTargetMachineCtor())
358     P = PI->getTargetMachineCtor()(&TPC.getTM<TargetMachine>());
359   else if (PI->getNormalCtor())
360     P = PI->getNormalCtor()();
361   else {
362     errs() << argv0 << ": cannot create pass: " << PI->getPassName() << "\n";
363     return true;
364   }
365   std::string Banner = std::string("After ") + std::string(P->getPassName());
366   PM.add(P);
367   TPC.printAndVerify(Banner);
368
369   return false;
370 }
371
372 static AnalysisID getPassID(const char *argv0, const char *OptionName,
373                             StringRef PassName) {
374   if (PassName.empty())
375     return nullptr;
376
377   const PassRegistry &PR = *PassRegistry::getPassRegistry();
378   const PassInfo *PI = PR.getPassInfo(PassName);
379   if (!PI) {
380     errs() << argv0 << ": " << OptionName << " pass is not registered.\n";
381     exit(1);
382   }
383   return PI->getTypeInfo();
384 }
385
386 static int compileModule(char **argv, LLVMContext &Context) {
387   // Load the module to be compiled...
388   SMDiagnostic Err;
389   std::unique_ptr<Module> M;
390   std::unique_ptr<MIRParser> MIR;
391   Triple TheTriple;
392
393   bool SkipModule = MCPU == "help" ||
394                     (!MAttrs.empty() && MAttrs.front() == "help");
395
396   // If user just wants to list available options, skip module loading
397   if (!SkipModule) {
398     if (StringRef(InputFilename).endswith_lower(".mir")) {
399       MIR = createMIRParserFromFile(InputFilename, Err, Context);
400       if (MIR)
401         M = MIR->parseLLVMModule();
402     } else
403       M = parseIRFile(InputFilename, Err, Context);
404     if (!M) {
405       Err.print(argv[0], errs());
406       return 1;
407     }
408
409     // Verify module immediately to catch problems before doInitialization() is
410     // called on any passes.
411     if (!NoVerify && verifyModule(*M, &errs())) {
412       errs() << argv[0] << ": " << InputFilename
413              << ": error: input module is broken!\n";
414       return 1;
415     }
416
417     // If we are supposed to override the target triple, do so now.
418     if (!TargetTriple.empty())
419       M->setTargetTriple(Triple::normalize(TargetTriple));
420     TheTriple = Triple(M->getTargetTriple());
421   } else {
422     TheTriple = Triple(Triple::normalize(TargetTriple));
423   }
424
425   if (TheTriple.getTriple().empty())
426     TheTriple.setTriple(sys::getDefaultTargetTriple());
427
428   // Get the target specific parser.
429   std::string Error;
430   const Target *TheTarget = TargetRegistry::lookupTarget(MArch, TheTriple,
431                                                          Error);
432   if (!TheTarget) {
433     errs() << argv[0] << ": " << Error;
434     return 1;
435   }
436
437   std::string CPUStr = getCPUStr(), FeaturesStr = getFeaturesStr();
438
439   CodeGenOpt::Level OLvl = CodeGenOpt::Default;
440   switch (OptLevel) {
441   default:
442     errs() << argv[0] << ": invalid optimization level.\n";
443     return 1;
444   case ' ': break;
445   case '0': OLvl = CodeGenOpt::None; break;
446   case '1': OLvl = CodeGenOpt::Less; break;
447   case '2': OLvl = CodeGenOpt::Default; break;
448   case '3': OLvl = CodeGenOpt::Aggressive; break;
449   }
450
451   TargetOptions Options = InitTargetOptionsFromCodeGenFlags();
452   Options.DisableIntegratedAS = NoIntegratedAssembler;
453   Options.MCOptions.ShowMCEncoding = ShowMCEncoding;
454   Options.MCOptions.MCUseDwarfDirectory = EnableDwarfDirectory;
455   Options.MCOptions.AsmVerbose = AsmVerbose;
456   Options.MCOptions.PreserveAsmComments = PreserveComments;
457   Options.MCOptions.IASSearchPaths = IncludeDirs;
458   Options.MCOptions.SplitDwarfFile = SplitDwarfFile;
459
460   std::unique_ptr<TargetMachine> Target(
461       TheTarget->createTargetMachine(TheTriple.getTriple(), CPUStr, FeaturesStr,
462                                      Options, getRelocModel(), CMModel, OLvl));
463
464   assert(Target && "Could not allocate target machine!");
465
466   // If we don't have a module then just exit now. We do this down
467   // here since the CPU/Feature help is underneath the target machine
468   // creation.
469   if (SkipModule)
470     return 0;
471
472   assert(M && "Should have exited if we didn't have a module!");
473   if (FloatABIForCalls != FloatABI::Default)
474     Options.FloatABIType = FloatABIForCalls;
475
476   // Figure out where we are going to send the output.
477   std::unique_ptr<tool_output_file> Out =
478       GetOutputStream(TheTarget->getName(), TheTriple.getOS(), argv[0]);
479   if (!Out) return 1;
480
481   // Build up all of the passes that we want to do to the module.
482   legacy::PassManager PM;
483
484   // Add an appropriate TargetLibraryInfo pass for the module's triple.
485   TargetLibraryInfoImpl TLII(Triple(M->getTargetTriple()));
486
487   // The -disable-simplify-libcalls flag actually disables all builtin optzns.
488   if (DisableSimplifyLibCalls)
489     TLII.disableAllFunctions();
490   PM.add(new TargetLibraryInfoWrapperPass(TLII));
491
492   // Add the target data from the target machine, if it exists, or the module.
493   M->setDataLayout(Target->createDataLayout());
494
495   // Override function attributes based on CPUStr, FeaturesStr, and command line
496   // flags.
497   setFunctionAttributes(CPUStr, FeaturesStr, *M);
498
499   if (RelaxAll.getNumOccurrences() > 0 &&
500       FileType != TargetMachine::CGFT_ObjectFile)
501     errs() << argv[0]
502              << ": warning: ignoring -mc-relax-all because filetype != obj";
503
504   {
505     raw_pwrite_stream *OS = &Out->os();
506
507     // Manually do the buffering rather than using buffer_ostream,
508     // so we can memcmp the contents in CompileTwice mode
509     SmallVector<char, 0> Buffer;
510     std::unique_ptr<raw_svector_ostream> BOS;
511     if ((FileType != TargetMachine::CGFT_AssemblyFile &&
512          !Out->os().supportsSeeking()) ||
513         CompileTwice) {
514       BOS = make_unique<raw_svector_ostream>(Buffer);
515       OS = BOS.get();
516     }
517
518     if (!RunPassNames->empty()) {
519       if (!StartAfter.empty() || !StopAfter.empty() || !StartBefore.empty() ||
520           !StopBefore.empty()) {
521         errs() << argv[0] << ": start-after and/or stop-after passes are "
522                              "redundant when run-pass is specified.\n";
523         return 1;
524       }
525       if (!MIR) {
526         errs() << argv[0] << ": run-pass needs a .mir input.\n";
527         return 1;
528       }
529       LLVMTargetMachine &LLVMTM = static_cast<LLVMTargetMachine&>(*Target);
530       TargetPassConfig &TPC = *LLVMTM.createPassConfig(PM);
531       PM.add(&TPC);
532       MachineModuleInfo *MMI = new MachineModuleInfo(&LLVMTM);
533       MMI->setMachineFunctionInitializer(MIR.get());
534       PM.add(MMI);
535       TPC.printAndVerify("");
536
537       for (const std::string &RunPassName : *RunPassNames) {
538         if (addPass(PM, argv[0], RunPassName, TPC))
539           return 1;
540       }
541       PM.add(createPrintMIRPass(*OS));
542     } else {
543       const char *argv0 = argv[0];
544       AnalysisID StartBeforeID = getPassID(argv0, "start-before", StartBefore);
545       AnalysisID StartAfterID = getPassID(argv0, "start-after", StartAfter);
546       AnalysisID StopAfterID = getPassID(argv0, "stop-after", StopAfter);
547       AnalysisID StopBeforeID = getPassID(argv0, "stop-before", StopBefore);
548
549       if (StartBeforeID && StartAfterID) {
550         errs() << argv[0] << ": -start-before and -start-after specified!\n";
551         return 1;
552       }
553       if (StopBeforeID && StopAfterID) {
554         errs() << argv[0] << ": -stop-before and -stop-after specified!\n";
555         return 1;
556       }
557
558       // Ask the target to add backend passes as necessary.
559       if (Target->addPassesToEmitFile(PM, *OS, FileType, NoVerify,
560                                       StartBeforeID, StartAfterID, StopBeforeID,
561                                       StopAfterID, MIR.get())) {
562         errs() << argv[0] << ": target does not support generation of this"
563                << " file type!\n";
564         return 1;
565       }
566     }
567
568     // Before executing passes, print the final values of the LLVM options.
569     cl::PrintOptionValues();
570
571     // If requested, run the pass manager over the same module again,
572     // to catch any bugs due to persistent state in the passes. Note that
573     // opt has the same functionality, so it may be worth abstracting this out
574     // in the future.
575     SmallVector<char, 0> CompileTwiceBuffer;
576     if (CompileTwice) {
577       std::unique_ptr<Module> M2(llvm::CloneModule(M.get()));
578       PM.run(*M2);
579       CompileTwiceBuffer = Buffer;
580       Buffer.clear();
581     }
582
583     PM.run(*M);
584
585     auto HasError = *static_cast<bool *>(Context.getDiagnosticContext());
586     if (HasError)
587       return 1;
588
589     // Compare the two outputs and make sure they're the same
590     if (CompileTwice) {
591       if (Buffer.size() != CompileTwiceBuffer.size() ||
592           (memcmp(Buffer.data(), CompileTwiceBuffer.data(), Buffer.size()) !=
593            0)) {
594         errs()
595             << "Running the pass manager twice changed the output.\n"
596                "Writing the result of the second run to the specified output\n"
597                "To generate the one-run comparison binary, just run without\n"
598                "the compile-twice option\n";
599         Out->os() << Buffer;
600         Out->keep();
601         return 1;
602       }
603     }
604
605     if (BOS) {
606       Out->os() << Buffer;
607     }
608   }
609
610   // Declare success.
611   Out->keep();
612
613   return 0;
614 }