1 //===-- llc.cpp - Implement the LLVM Native Code Generator ----------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This is the llc code generator driver. It provides a convenient
10 // command-line interface for generating native assembly-language code
11 // or C code, given LLVM bitcode.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #include "llvm/ADT/STLExtras.h"
16 #include "llvm/ADT/Triple.h"
17 #include "llvm/Analysis/TargetLibraryInfo.h"
18 #include "llvm/CodeGen/CommandFlags.h"
19 #include "llvm/CodeGen/LinkAllAsmWriterComponents.h"
20 #include "llvm/CodeGen/LinkAllCodegenComponents.h"
21 #include "llvm/CodeGen/MIRParser/MIRParser.h"
22 #include "llvm/CodeGen/MachineFunctionPass.h"
23 #include "llvm/CodeGen/MachineModuleInfo.h"
24 #include "llvm/CodeGen/TargetPassConfig.h"
25 #include "llvm/CodeGen/TargetSubtargetInfo.h"
26 #include "llvm/IR/AutoUpgrade.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/LLVMRemarkStreamer.h"
33 #include "llvm/IR/LegacyPassManager.h"
34 #include "llvm/IR/Module.h"
35 #include "llvm/IR/Verifier.h"
36 #include "llvm/IRReader/IRReader.h"
37 #include "llvm/InitializePasses.h"
38 #include "llvm/MC/SubtargetFeature.h"
39 #include "llvm/Pass.h"
40 #include "llvm/Remarks/HotnessThresholdParser.h"
41 #include "llvm/Support/CommandLine.h"
42 #include "llvm/Support/Debug.h"
43 #include "llvm/Support/FileSystem.h"
44 #include "llvm/Support/FormattedStream.h"
45 #include "llvm/Support/Host.h"
46 #include "llvm/Support/InitLLVM.h"
47 #include "llvm/Support/ManagedStatic.h"
48 #include "llvm/Support/PluginLoader.h"
49 #include "llvm/Support/SourceMgr.h"
50 #include "llvm/Support/TargetRegistry.h"
51 #include "llvm/Support/TargetSelect.h"
52 #include "llvm/Support/ToolOutputFile.h"
53 #include "llvm/Support/WithColor.h"
54 #include "llvm/Target/TargetLoweringObjectFile.h"
55 #include "llvm/Target/TargetMachine.h"
56 #include "llvm/Transforms/Utils/Cloning.h"
57 #include <memory>
58 using namespace llvm;
59
60 static codegen::RegisterCodeGenFlags CGF;
61
62 // General options for llc. Other pass-specific options are specified
63 // within the corresponding llc passes, and target-specific options
64 // and back-end code generation options are specified with the target machine.
65 //
66 static cl::opt<std::string>
67 InputFilename(cl::Positional, cl::desc("<input bitcode>"), cl::init("-"));
68
69 static cl::opt<std::string>
70 InputLanguage("x", cl::desc("Input language ('ir' or 'mir')"));
71
72 static cl::opt<std::string>
73 OutputFilename("o", cl::desc("Output filename"), cl::value_desc("filename"));
74
75 static cl::opt<std::string>
76 SplitDwarfOutputFile("split-dwarf-output",
77 cl::desc(".dwo output filename"),
78 cl::value_desc("filename"));
79
80 static cl::opt<unsigned>
81 TimeCompilations("time-compilations", cl::Hidden, cl::init(1u),
82 cl::value_desc("N"),
83 cl::desc("Repeat compilation N times for timing"));
84
85 static cl::opt<std::string>
86 BinutilsVersion("binutils-version", cl::Hidden,
87 cl::desc("Produced object files can use all ELF features "
88 "supported by this binutils version and newer."
89 "If -no-integrated-as is specified, the generated "
90 "assembly will consider GNU as support."
91 "'none' means that all ELF features can be used, "
92 "regardless of binutils support"));
93
94 static cl::opt<bool>
95 NoIntegratedAssembler("no-integrated-as", cl::Hidden,
96 cl::desc("Disable integrated assembler"));
97
98 static cl::opt<bool>
99 PreserveComments("preserve-as-comments", cl::Hidden,
100 cl::desc("Preserve Comments in outputted assembly"),
101 cl::init(true));
102
103 // Determine optimization level.
104 static cl::opt<char>
105 OptLevel("O",
106 cl::desc("Optimization level. [-O0, -O1, -O2, or -O3] "
107 "(default = '-O2')"),
108 cl::Prefix,
109 cl::ZeroOrMore,
110 cl::init(' '));
111
112 static cl::opt<std::string>
113 TargetTriple("mtriple", cl::desc("Override target triple for module"));
114
115 static cl::opt<std::string> SplitDwarfFile(
116 "split-dwarf-file",
117 cl::desc(
118 "Specify the name of the .dwo file to encode in the DWARF output"));
119
120 static cl::opt<bool> NoVerify("disable-verify", cl::Hidden,
121 cl::desc("Do not verify input module"));
122
123 static cl::opt<bool> DisableSimplifyLibCalls("disable-simplify-libcalls",
124 cl::desc("Disable simplify-libcalls"));
125
126 static cl::opt<bool> ShowMCEncoding("show-mc-encoding", cl::Hidden,
127 cl::desc("Show encoding in .s output"));
128
129 static cl::opt<bool> EnableDwarfDirectory(
130 "enable-dwarf-directory", cl::Hidden,
131 cl::desc("Use .file directives with an explicit directory."));
132
133 static cl::opt<bool> AsmVerbose("asm-verbose",
134 cl::desc("Add comments to directives."),
135 cl::init(true));
136
137 static cl::opt<bool>
138 CompileTwice("compile-twice", cl::Hidden,
139 cl::desc("Run everything twice, re-using the same pass "
140 "manager and verify the result is the same."),
141 cl::init(false));
142
143 static cl::opt<bool> DiscardValueNames(
144 "discard-value-names",
145 cl::desc("Discard names from Value (other than GlobalValue)."),
146 cl::init(false), cl::Hidden);
147
148 static cl::list<std::string> IncludeDirs("I", cl::desc("include search path"));
149
150 static cl::opt<bool> RemarksWithHotness(
151 "pass-remarks-with-hotness",
152 cl::desc("With PGO, include profile count in optimization remarks"),
153 cl::Hidden);
154
155 static cl::opt<Optional<uint64_t>, false, remarks::HotnessThresholdParser>
156 RemarksHotnessThreshold(
157 "pass-remarks-hotness-threshold",
158 cl::desc("Minimum profile count required for "
159 "an optimization remark to be output. "
160 "Use 'auto' to apply the threshold from profile summary."),
161 cl::value_desc("N or 'auto'"), cl::init(0), cl::Hidden);
162
163 static cl::opt<std::string>
164 RemarksFilename("pass-remarks-output",
165 cl::desc("Output filename for pass remarks"),
166 cl::value_desc("filename"));
167
168 static cl::opt<std::string>
169 RemarksPasses("pass-remarks-filter",
170 cl::desc("Only record optimization remarks from passes whose "
171 "names match the given regular expression"),
172 cl::value_desc("regex"));
173
174 static cl::opt<std::string> RemarksFormat(
175 "pass-remarks-format",
176 cl::desc("The format used for serializing remarks (default: YAML)"),
177 cl::value_desc("format"), cl::init("yaml"));
178
179 namespace {
180 static ManagedStatic<std::vector<std::string>> RunPassNames;
181
182 struct RunPassOption {
operator =__anon0a34ca500111::RunPassOption183 void operator=(const std::string &Val) const {
184 if (Val.empty())
185 return;
186 SmallVector<StringRef, 8> PassNames;
187 StringRef(Val).split(PassNames, ',', -1, false);
188 for (auto PassName : PassNames)
189 RunPassNames->push_back(std::string(PassName));
190 }
191 };
192 }
193
194 static RunPassOption RunPassOpt;
195
196 static cl::opt<RunPassOption, true, cl::parser<std::string>> RunPass(
197 "run-pass",
198 cl::desc("Run compiler only for specified passes (comma separated list)"),
199 cl::value_desc("pass-name"), cl::ZeroOrMore, cl::location(RunPassOpt));
200
201 static int compileModule(char **, LLVMContext &);
202
reportError(Twine Msg,StringRef Filename="")203 LLVM_ATTRIBUTE_NORETURN static void reportError(Twine Msg,
204 StringRef Filename = "") {
205 SmallString<256> Prefix;
206 if (!Filename.empty()) {
207 if (Filename == "-")
208 Filename = "<stdin>";
209 ("'" + Twine(Filename) + "': ").toStringRef(Prefix);
210 }
211 WithColor::error(errs(), "llc") << Prefix << Msg << "\n";
212 exit(1);
213 }
214
reportError(Error Err,StringRef Filename)215 LLVM_ATTRIBUTE_NORETURN static void reportError(Error Err, StringRef Filename) {
216 assert(Err);
217 handleAllErrors(createFileError(Filename, std::move(Err)),
218 [&](const ErrorInfoBase &EI) { reportError(EI.message()); });
219 llvm_unreachable("reportError() should not return");
220 }
221
GetOutputStream(const char * TargetName,Triple::OSType OS,const char * ProgName)222 static std::unique_ptr<ToolOutputFile> GetOutputStream(const char *TargetName,
223 Triple::OSType OS,
224 const char *ProgName) {
225 // If we don't yet have an output filename, make one.
226 if (OutputFilename.empty()) {
227 if (InputFilename == "-")
228 OutputFilename = "-";
229 else {
230 // If InputFilename ends in .bc or .ll, remove it.
231 StringRef IFN = InputFilename;
232 if (IFN.endswith(".bc") || IFN.endswith(".ll"))
233 OutputFilename = std::string(IFN.drop_back(3));
234 else if (IFN.endswith(".mir"))
235 OutputFilename = std::string(IFN.drop_back(4));
236 else
237 OutputFilename = std::string(IFN);
238
239 switch (codegen::getFileType()) {
240 case CGFT_AssemblyFile:
241 if (TargetName[0] == 'c') {
242 if (TargetName[1] == 0)
243 OutputFilename += ".cbe.c";
244 else if (TargetName[1] == 'p' && TargetName[2] == 'p')
245 OutputFilename += ".cpp";
246 else
247 OutputFilename += ".s";
248 } else
249 OutputFilename += ".s";
250 break;
251 case CGFT_ObjectFile:
252 if (OS == Triple::Win32)
253 OutputFilename += ".obj";
254 else
255 OutputFilename += ".o";
256 break;
257 case CGFT_Null:
258 OutputFilename = "-";
259 break;
260 }
261 }
262 }
263
264 // Decide if we need "binary" output.
265 bool Binary = false;
266 switch (codegen::getFileType()) {
267 case CGFT_AssemblyFile:
268 break;
269 case CGFT_ObjectFile:
270 case CGFT_Null:
271 Binary = true;
272 break;
273 }
274
275 // Open the file.
276 std::error_code EC;
277 sys::fs::OpenFlags OpenFlags = sys::fs::OF_None;
278 if (!Binary)
279 OpenFlags |= sys::fs::OF_TextWithCRLF;
280 auto FDOut = std::make_unique<ToolOutputFile>(OutputFilename, EC, OpenFlags);
281 if (EC) {
282 reportError(EC.message());
283 return nullptr;
284 }
285
286 return FDOut;
287 }
288
289 struct LLCDiagnosticHandler : public DiagnosticHandler {
290 bool *HasError;
LLCDiagnosticHandlerLLCDiagnosticHandler291 LLCDiagnosticHandler(bool *HasErrorPtr) : HasError(HasErrorPtr) {}
handleDiagnosticsLLCDiagnosticHandler292 bool handleDiagnostics(const DiagnosticInfo &DI) override {
293 if (DI.getKind() == llvm::DK_SrcMgr) {
294 const auto &DISM = cast<DiagnosticInfoSrcMgr>(DI);
295 const SMDiagnostic &SMD = DISM.getSMDiag();
296
297 if (SMD.getKind() == SourceMgr::DK_Error)
298 *HasError = true;
299
300 SMD.print(nullptr, errs());
301
302 // For testing purposes, we print the LocCookie here.
303 if (DISM.isInlineAsmDiag() && DISM.getLocCookie())
304 WithColor::note() << "!srcloc = " << DISM.getLocCookie() << "\n";
305
306 return true;
307 }
308
309 if (DI.getSeverity() == DS_Error)
310 *HasError = true;
311
312 if (auto *Remark = dyn_cast<DiagnosticInfoOptimizationBase>(&DI))
313 if (!Remark->isEnabled())
314 return true;
315
316 DiagnosticPrinterRawOStream DP(errs());
317 errs() << LLVMContext::getDiagnosticMessagePrefix(DI.getSeverity()) << ": ";
318 DI.print(DP);
319 errs() << "\n";
320 return true;
321 }
322 };
323
324 // main - Entry point for the llc compiler.
325 //
main(int argc,char ** argv)326 int main(int argc, char **argv) {
327 InitLLVM X(argc, argv);
328
329 // Enable debug stream buffering.
330 EnableDebugBuffering = true;
331
332 LLVMContext Context;
333
334 // Initialize targets first, so that --version shows registered targets.
335 InitializeAllTargets();
336 InitializeAllTargetMCs();
337 InitializeAllAsmPrinters();
338 InitializeAllAsmParsers();
339
340 // Initialize codegen and IR passes used by llc so that the -print-after,
341 // -print-before, and -stop-after options work.
342 PassRegistry *Registry = PassRegistry::getPassRegistry();
343 initializeCore(*Registry);
344 initializeCodeGen(*Registry);
345 initializeLoopStrengthReducePass(*Registry);
346 initializeLowerIntrinsicsPass(*Registry);
347 initializeEntryExitInstrumenterPass(*Registry);
348 initializePostInlineEntryExitInstrumenterPass(*Registry);
349 initializeUnreachableBlockElimLegacyPassPass(*Registry);
350 initializeConstantHoistingLegacyPassPass(*Registry);
351 initializeScalarOpts(*Registry);
352 initializeVectorization(*Registry);
353 initializeScalarizeMaskedMemIntrinLegacyPassPass(*Registry);
354 initializeExpandReductionsPass(*Registry);
355 initializeExpandVectorPredicationPass(*Registry);
356 initializeHardwareLoopsPass(*Registry);
357 initializeTransformUtils(*Registry);
358 initializeReplaceWithVeclibLegacyPass(*Registry);
359
360 // Initialize debugging passes.
361 initializeScavengerTestPass(*Registry);
362
363 // Register the target printer for --version.
364 cl::AddExtraVersionPrinter(TargetRegistry::printRegisteredTargetsForVersion);
365
366 cl::ParseCommandLineOptions(argc, argv, "llvm system compiler\n");
367
368 Context.setDiscardValueNames(DiscardValueNames);
369
370 // Set a diagnostic handler that doesn't exit on the first error
371 bool HasError = false;
372 Context.setDiagnosticHandler(
373 std::make_unique<LLCDiagnosticHandler>(&HasError));
374
375 Expected<std::unique_ptr<ToolOutputFile>> RemarksFileOrErr =
376 setupLLVMOptimizationRemarks(Context, RemarksFilename, RemarksPasses,
377 RemarksFormat, RemarksWithHotness,
378 RemarksHotnessThreshold);
379 if (Error E = RemarksFileOrErr.takeError())
380 reportError(std::move(E), RemarksFilename);
381 std::unique_ptr<ToolOutputFile> RemarksFile = std::move(*RemarksFileOrErr);
382
383 if (InputLanguage != "" && InputLanguage != "ir" && InputLanguage != "mir")
384 reportError("input language must be '', 'IR' or 'MIR'");
385
386 // Compile the module TimeCompilations times to give better compile time
387 // metrics.
388 for (unsigned I = TimeCompilations; I; --I)
389 if (int RetVal = compileModule(argv, Context))
390 return RetVal;
391
392 if (RemarksFile)
393 RemarksFile->keep();
394 return 0;
395 }
396
addPass(PassManagerBase & PM,const char * argv0,StringRef PassName,TargetPassConfig & TPC)397 static bool addPass(PassManagerBase &PM, const char *argv0,
398 StringRef PassName, TargetPassConfig &TPC) {
399 if (PassName == "none")
400 return false;
401
402 const PassRegistry *PR = PassRegistry::getPassRegistry();
403 const PassInfo *PI = PR->getPassInfo(PassName);
404 if (!PI) {
405 WithColor::error(errs(), argv0)
406 << "run-pass " << PassName << " is not registered.\n";
407 return true;
408 }
409
410 Pass *P;
411 if (PI->getNormalCtor())
412 P = PI->getNormalCtor()();
413 else {
414 WithColor::error(errs(), argv0)
415 << "cannot create pass: " << PI->getPassName() << "\n";
416 return true;
417 }
418 std::string Banner = std::string("After ") + std::string(P->getPassName());
419 TPC.addMachinePrePasses();
420 PM.add(P);
421 TPC.addMachinePostPasses(Banner);
422
423 return false;
424 }
425
compileModule(char ** argv,LLVMContext & Context)426 static int compileModule(char **argv, LLVMContext &Context) {
427 // Load the module to be compiled...
428 SMDiagnostic Err;
429 std::unique_ptr<Module> M;
430 std::unique_ptr<MIRParser> MIR;
431 Triple TheTriple;
432 std::string CPUStr = codegen::getCPUStr(),
433 FeaturesStr = codegen::getFeaturesStr();
434
435 // Set attributes on functions as loaded from MIR from command line arguments.
436 auto setMIRFunctionAttributes = [&CPUStr, &FeaturesStr](Function &F) {
437 codegen::setFunctionAttributes(CPUStr, FeaturesStr, F);
438 };
439
440 auto MAttrs = codegen::getMAttrs();
441 bool SkipModule = codegen::getMCPU() == "help" ||
442 (!MAttrs.empty() && MAttrs.front() == "help");
443
444 CodeGenOpt::Level OLvl = CodeGenOpt::Default;
445 switch (OptLevel) {
446 default:
447 WithColor::error(errs(), argv[0]) << "invalid optimization level.\n";
448 return 1;
449 case ' ': break;
450 case '0': OLvl = CodeGenOpt::None; break;
451 case '1': OLvl = CodeGenOpt::Less; break;
452 case '2': OLvl = CodeGenOpt::Default; break;
453 case '3': OLvl = CodeGenOpt::Aggressive; break;
454 }
455
456 // Parse 'none' or '$major.$minor'. Disallow -binutils-version=0 because we
457 // use that to indicate the MC default.
458 if (!BinutilsVersion.empty() && BinutilsVersion != "none") {
459 StringRef V = BinutilsVersion.getValue();
460 unsigned Num;
461 if (V.consumeInteger(10, Num) || Num == 0 ||
462 !(V.empty() ||
463 (V.consume_front(".") && !V.consumeInteger(10, Num) && V.empty()))) {
464 WithColor::error(errs(), argv[0])
465 << "invalid -binutils-version, accepting 'none' or major.minor\n";
466 return 1;
467 }
468 }
469 TargetOptions Options;
470 auto InitializeOptions = [&](const Triple &TheTriple) {
471 Options = codegen::InitTargetOptionsFromCodeGenFlags(TheTriple);
472 Options.BinutilsVersion =
473 TargetMachine::parseBinutilsVersion(BinutilsVersion);
474 Options.DisableIntegratedAS = NoIntegratedAssembler;
475 Options.MCOptions.ShowMCEncoding = ShowMCEncoding;
476 Options.MCOptions.MCUseDwarfDirectory = EnableDwarfDirectory;
477 Options.MCOptions.AsmVerbose = AsmVerbose;
478 Options.MCOptions.PreserveAsmComments = PreserveComments;
479 Options.MCOptions.IASSearchPaths = IncludeDirs;
480 Options.MCOptions.SplitDwarfFile = SplitDwarfFile;
481 };
482
483 Optional<Reloc::Model> RM = codegen::getExplicitRelocModel();
484
485 const Target *TheTarget = nullptr;
486 std::unique_ptr<TargetMachine> Target;
487
488 // If user just wants to list available options, skip module loading
489 if (!SkipModule) {
490 auto SetDataLayout =
491 [&](StringRef DataLayoutTargetTriple) -> Optional<std::string> {
492 // If we are supposed to override the target triple, do so now.
493 std::string IRTargetTriple = DataLayoutTargetTriple.str();
494 if (!TargetTriple.empty())
495 IRTargetTriple = Triple::normalize(TargetTriple);
496 TheTriple = Triple(IRTargetTriple);
497 if (TheTriple.getTriple().empty())
498 TheTriple.setTriple(sys::getDefaultTargetTriple());
499
500 std::string Error;
501 TheTarget =
502 TargetRegistry::lookupTarget(codegen::getMArch(), TheTriple, Error);
503 if (!TheTarget) {
504 WithColor::error(errs(), argv[0]) << Error;
505 exit(1);
506 }
507
508 // On AIX, setting the relocation model to anything other than PIC is
509 // considered a user error.
510 if (TheTriple.isOSAIX() && RM.hasValue() && *RM != Reloc::PIC_)
511 reportError("invalid relocation model, AIX only supports PIC",
512 InputFilename);
513
514 InitializeOptions(TheTriple);
515 Target = std::unique_ptr<TargetMachine>(TheTarget->createTargetMachine(
516 TheTriple.getTriple(), CPUStr, FeaturesStr, Options, RM,
517 codegen::getExplicitCodeModel(), OLvl));
518 assert(Target && "Could not allocate target machine!");
519
520 return Target->createDataLayout().getStringRepresentation();
521 };
522 if (InputLanguage == "mir" ||
523 (InputLanguage == "" && StringRef(InputFilename).endswith(".mir"))) {
524 MIR = createMIRParserFromFile(InputFilename, Err, Context,
525 setMIRFunctionAttributes);
526 if (MIR)
527 M = MIR->parseIRModule(SetDataLayout);
528 } else {
529 M = parseIRFile(InputFilename, Err, Context, SetDataLayout);
530 }
531 if (!M) {
532 Err.print(argv[0], WithColor::error(errs(), argv[0]));
533 return 1;
534 }
535 if (!TargetTriple.empty())
536 M->setTargetTriple(Triple::normalize(TargetTriple));
537 } else {
538 TheTriple = Triple(Triple::normalize(TargetTriple));
539 if (TheTriple.getTriple().empty())
540 TheTriple.setTriple(sys::getDefaultTargetTriple());
541
542 // Get the target specific parser.
543 std::string Error;
544 TheTarget =
545 TargetRegistry::lookupTarget(codegen::getMArch(), TheTriple, Error);
546 if (!TheTarget) {
547 WithColor::error(errs(), argv[0]) << Error;
548 return 1;
549 }
550
551 // On AIX, setting the relocation model to anything other than PIC is
552 // considered a user error.
553 if (TheTriple.isOSAIX() && RM.hasValue() && *RM != Reloc::PIC_) {
554 WithColor::error(errs(), argv[0])
555 << "invalid relocation model, AIX only supports PIC.\n";
556 return 1;
557 }
558
559 InitializeOptions(TheTriple);
560 Target = std::unique_ptr<TargetMachine>(TheTarget->createTargetMachine(
561 TheTriple.getTriple(), CPUStr, FeaturesStr, Options, RM,
562 codegen::getExplicitCodeModel(), OLvl));
563 assert(Target && "Could not allocate target machine!");
564
565 // If we don't have a module then just exit now. We do this down
566 // here since the CPU/Feature help is underneath the target machine
567 // creation.
568 return 0;
569 }
570
571 assert(M && "Should have exited if we didn't have a module!");
572 if (codegen::getFloatABIForCalls() != FloatABI::Default)
573 Options.FloatABIType = codegen::getFloatABIForCalls();
574
575 // Figure out where we are going to send the output.
576 std::unique_ptr<ToolOutputFile> Out =
577 GetOutputStream(TheTarget->getName(), TheTriple.getOS(), argv[0]);
578 if (!Out) return 1;
579
580 std::unique_ptr<ToolOutputFile> DwoOut;
581 if (!SplitDwarfOutputFile.empty()) {
582 std::error_code EC;
583 DwoOut = std::make_unique<ToolOutputFile>(SplitDwarfOutputFile, EC,
584 sys::fs::OF_None);
585 if (EC)
586 reportError(EC.message(), SplitDwarfOutputFile);
587 }
588
589 // Build up all of the passes that we want to do to the module.
590 legacy::PassManager PM;
591
592 // Add an appropriate TargetLibraryInfo pass for the module's triple.
593 TargetLibraryInfoImpl TLII(Triple(M->getTargetTriple()));
594
595 // The -disable-simplify-libcalls flag actually disables all builtin optzns.
596 if (DisableSimplifyLibCalls)
597 TLII.disableAllFunctions();
598 PM.add(new TargetLibraryInfoWrapperPass(TLII));
599
600 // Verify module immediately to catch problems before doInitialization() is
601 // called on any passes.
602 if (!NoVerify && verifyModule(*M, &errs()))
603 reportError("input module cannot be verified", InputFilename);
604
605 // Override function attributes based on CPUStr, FeaturesStr, and command line
606 // flags.
607 codegen::setFunctionAttributes(CPUStr, FeaturesStr, *M);
608
609 if (mc::getExplicitRelaxAll() && codegen::getFileType() != CGFT_ObjectFile)
610 WithColor::warning(errs(), argv[0])
611 << ": warning: ignoring -mc-relax-all because filetype != obj";
612
613 {
614 raw_pwrite_stream *OS = &Out->os();
615
616 // Manually do the buffering rather than using buffer_ostream,
617 // so we can memcmp the contents in CompileTwice mode
618 SmallVector<char, 0> Buffer;
619 std::unique_ptr<raw_svector_ostream> BOS;
620 if ((codegen::getFileType() != CGFT_AssemblyFile &&
621 !Out->os().supportsSeeking()) ||
622 CompileTwice) {
623 BOS = std::make_unique<raw_svector_ostream>(Buffer);
624 OS = BOS.get();
625 }
626
627 const char *argv0 = argv[0];
628 LLVMTargetMachine &LLVMTM = static_cast<LLVMTargetMachine &>(*Target);
629 MachineModuleInfoWrapperPass *MMIWP =
630 new MachineModuleInfoWrapperPass(&LLVMTM);
631
632 // Construct a custom pass pipeline that starts after instruction
633 // selection.
634 if (!RunPassNames->empty()) {
635 if (!MIR) {
636 WithColor::warning(errs(), argv[0])
637 << "run-pass is for .mir file only.\n";
638 return 1;
639 }
640 TargetPassConfig &TPC = *LLVMTM.createPassConfig(PM);
641 if (TPC.hasLimitedCodeGenPipeline()) {
642 WithColor::warning(errs(), argv[0])
643 << "run-pass cannot be used with "
644 << TPC.getLimitedCodeGenPipelineReason(" and ") << ".\n";
645 return 1;
646 }
647
648 TPC.setDisableVerify(NoVerify);
649 PM.add(&TPC);
650 PM.add(MMIWP);
651 TPC.printAndVerify("");
652 for (const std::string &RunPassName : *RunPassNames) {
653 if (addPass(PM, argv0, RunPassName, TPC))
654 return 1;
655 }
656 TPC.setInitialized();
657 PM.add(createPrintMIRPass(*OS));
658 PM.add(createFreeMachineFunctionPass());
659 } else if (Target->addPassesToEmitFile(
660 PM, *OS, DwoOut ? &DwoOut->os() : nullptr,
661 codegen::getFileType(), NoVerify, MMIWP)) {
662 reportError("target does not support generation of this file type");
663 }
664
665 const_cast<TargetLoweringObjectFile *>(LLVMTM.getObjFileLowering())
666 ->Initialize(MMIWP->getMMI().getContext(), *Target);
667 if (MIR) {
668 assert(MMIWP && "Forgot to create MMIWP?");
669 if (MIR->parseMachineFunctions(*M, MMIWP->getMMI()))
670 return 1;
671 }
672
673 // Before executing passes, print the final values of the LLVM options.
674 cl::PrintOptionValues();
675
676 // If requested, run the pass manager over the same module again,
677 // to catch any bugs due to persistent state in the passes. Note that
678 // opt has the same functionality, so it may be worth abstracting this out
679 // in the future.
680 SmallVector<char, 0> CompileTwiceBuffer;
681 if (CompileTwice) {
682 std::unique_ptr<Module> M2(llvm::CloneModule(*M));
683 PM.run(*M2);
684 CompileTwiceBuffer = Buffer;
685 Buffer.clear();
686 }
687
688 PM.run(*M);
689
690 auto HasError =
691 ((const LLCDiagnosticHandler *)(Context.getDiagHandlerPtr()))->HasError;
692 if (*HasError)
693 return 1;
694
695 // Compare the two outputs and make sure they're the same
696 if (CompileTwice) {
697 if (Buffer.size() != CompileTwiceBuffer.size() ||
698 (memcmp(Buffer.data(), CompileTwiceBuffer.data(), Buffer.size()) !=
699 0)) {
700 errs()
701 << "Running the pass manager twice changed the output.\n"
702 "Writing the result of the second run to the specified output\n"
703 "To generate the one-run comparison binary, just run without\n"
704 "the compile-twice option\n";
705 Out->os() << Buffer;
706 Out->keep();
707 return 1;
708 }
709 }
710
711 if (BOS) {
712 Out->os() << Buffer;
713 }
714 }
715
716 // Declare success.
717 Out->keep();
718 if (DwoOut)
719 DwoOut->keep();
720
721 return 0;
722 }
723