1 //===- NewPMDriver.cpp - Driver for opt with new PM -----------------------===// 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 /// \file 9 /// 10 /// This file is just a split of the code that logically belongs in opt.cpp but 11 /// that includes the new pass manager headers. 12 /// 13 //===----------------------------------------------------------------------===// 14 15 #include "NewPMDriver.h" 16 #include "PassPrinters.h" 17 #include "llvm/ADT/SmallVector.h" 18 #include "llvm/ADT/StringRef.h" 19 #include "llvm/Analysis/CGSCCPassManager.h" 20 #include "llvm/Analysis/TargetLibraryInfo.h" 21 #include "llvm/Bitcode/BitcodeWriterPass.h" 22 #include "llvm/Config/llvm-config.h" 23 #include "llvm/IR/Dominators.h" 24 #include "llvm/IR/IRPrintingPasses.h" 25 #include "llvm/IR/LLVMContext.h" 26 #include "llvm/IR/Module.h" 27 #include "llvm/IR/PassManager.h" 28 #include "llvm/IR/Verifier.h" 29 #include "llvm/Passes/PassBuilder.h" 30 #include "llvm/Passes/PassPlugin.h" 31 #include "llvm/Passes/StandardInstrumentations.h" 32 #include "llvm/Support/ErrorHandling.h" 33 #include "llvm/Support/ToolOutputFile.h" 34 #include "llvm/Target/TargetMachine.h" 35 #include "llvm/Transforms/IPO/ThinLTOBitcodeWriter.h" 36 #include "llvm/Transforms/Instrumentation/AddressSanitizer.h" 37 #include "llvm/Transforms/Scalar/LoopPassManager.h" 38 #include "llvm/Transforms/Utils/Debugify.h" 39 40 using namespace llvm; 41 using namespace opt_tool; 42 43 namespace llvm { 44 cl::opt<bool> DebugifyEach( 45 "debugify-each", 46 cl::desc("Start each pass with debugify and end it with check-debugify")); 47 48 cl::opt<std::string> 49 DebugifyExport("debugify-export", 50 cl::desc("Export per-pass debugify statistics to this file"), 51 cl::value_desc("filename")); 52 } // namespace llvm 53 54 static cl::opt<bool> 55 DebugPM("debug-pass-manager", cl::Hidden, 56 cl::desc("Print pass management debugging information")); 57 58 static cl::list<std::string> 59 PassPlugins("load-pass-plugin", 60 cl::desc("Load passes from plugin library")); 61 62 // This flag specifies a textual description of the alias analysis pipeline to 63 // use when querying for aliasing information. It only works in concert with 64 // the "passes" flag above. 65 static cl::opt<std::string> 66 AAPipeline("aa-pipeline", 67 cl::desc("A textual description of the alias analysis " 68 "pipeline for handling managed aliasing queries"), 69 cl::Hidden); 70 71 /// {{@ These options accept textual pipeline descriptions which will be 72 /// inserted into default pipelines at the respective extension points 73 static cl::opt<std::string> PeepholeEPPipeline( 74 "passes-ep-peephole", 75 cl::desc("A textual description of the function pass pipeline inserted at " 76 "the Peephole extension points into default pipelines"), 77 cl::Hidden); 78 static cl::opt<std::string> LateLoopOptimizationsEPPipeline( 79 "passes-ep-late-loop-optimizations", 80 cl::desc( 81 "A textual description of the loop pass pipeline inserted at " 82 "the LateLoopOptimizations extension point into default pipelines"), 83 cl::Hidden); 84 static cl::opt<std::string> LoopOptimizerEndEPPipeline( 85 "passes-ep-loop-optimizer-end", 86 cl::desc("A textual description of the loop pass pipeline inserted at " 87 "the LoopOptimizerEnd extension point into default pipelines"), 88 cl::Hidden); 89 static cl::opt<std::string> ScalarOptimizerLateEPPipeline( 90 "passes-ep-scalar-optimizer-late", 91 cl::desc("A textual description of the function pass pipeline inserted at " 92 "the ScalarOptimizerLate extension point into default pipelines"), 93 cl::Hidden); 94 static cl::opt<std::string> CGSCCOptimizerLateEPPipeline( 95 "passes-ep-cgscc-optimizer-late", 96 cl::desc("A textual description of the cgscc pass pipeline inserted at " 97 "the CGSCCOptimizerLate extension point into default pipelines"), 98 cl::Hidden); 99 static cl::opt<std::string> VectorizerStartEPPipeline( 100 "passes-ep-vectorizer-start", 101 cl::desc("A textual description of the function pass pipeline inserted at " 102 "the VectorizerStart extension point into default pipelines"), 103 cl::Hidden); 104 static cl::opt<std::string> PipelineStartEPPipeline( 105 "passes-ep-pipeline-start", 106 cl::desc("A textual description of the module pass pipeline inserted at " 107 "the PipelineStart extension point into default pipelines"), 108 cl::Hidden); 109 static cl::opt<std::string> PipelineEarlySimplificationEPPipeline( 110 "passes-ep-pipeline-early-simplification", 111 cl::desc("A textual description of the module pass pipeline inserted at " 112 "the EarlySimplification extension point into default pipelines"), 113 cl::Hidden); 114 static cl::opt<std::string> OptimizerLastEPPipeline( 115 "passes-ep-optimizer-last", 116 cl::desc("A textual description of the module pass pipeline inserted at " 117 "the OptimizerLast extension point into default pipelines"), 118 cl::Hidden); 119 120 // Individual pipeline tuning options. 121 extern cl::opt<bool> DisableLoopUnrolling; 122 123 extern cl::opt<PGOKind> PGOKindFlag; 124 extern cl::opt<std::string> ProfileFile; 125 extern cl::opt<CSPGOKind> CSPGOKindFlag; 126 extern cl::opt<std::string> CSProfileGenFile; 127 extern cl::opt<bool> DisableBasicAA; 128 129 static cl::opt<std::string> 130 ProfileRemappingFile("profile-remapping-file", 131 cl::desc("Path to the profile remapping file."), 132 cl::Hidden); 133 static cl::opt<bool> DebugInfoForProfiling( 134 "new-pm-debug-info-for-profiling", cl::init(false), cl::Hidden, 135 cl::desc("Emit special debug info to enable PGO profile generation.")); 136 /// @}} 137 138 template <typename PassManagerT> 139 bool tryParsePipelineText(PassBuilder &PB, 140 const cl::opt<std::string> &PipelineOpt) { 141 if (PipelineOpt.empty()) 142 return false; 143 144 // Verify the pipeline is parseable: 145 PassManagerT PM; 146 if (auto Err = PB.parsePassPipeline(PM, PipelineOpt)) { 147 errs() << "Could not parse -" << PipelineOpt.ArgStr 148 << " pipeline: " << toString(std::move(Err)) 149 << "... I'm going to ignore it.\n"; 150 return false; 151 } 152 return true; 153 } 154 155 /// If one of the EPPipeline command line options was given, register callbacks 156 /// for parsing and inserting the given pipeline 157 static void registerEPCallbacks(PassBuilder &PB) { 158 if (tryParsePipelineText<FunctionPassManager>(PB, PeepholeEPPipeline)) 159 PB.registerPeepholeEPCallback( 160 [&PB](FunctionPassManager &PM, PassBuilder::OptimizationLevel Level) { 161 ExitOnError Err("Unable to parse PeepholeEP pipeline: "); 162 Err(PB.parsePassPipeline(PM, PeepholeEPPipeline)); 163 }); 164 if (tryParsePipelineText<LoopPassManager>(PB, 165 LateLoopOptimizationsEPPipeline)) 166 PB.registerLateLoopOptimizationsEPCallback( 167 [&PB](LoopPassManager &PM, PassBuilder::OptimizationLevel Level) { 168 ExitOnError Err("Unable to parse LateLoopOptimizationsEP pipeline: "); 169 Err(PB.parsePassPipeline(PM, LateLoopOptimizationsEPPipeline)); 170 }); 171 if (tryParsePipelineText<LoopPassManager>(PB, LoopOptimizerEndEPPipeline)) 172 PB.registerLoopOptimizerEndEPCallback( 173 [&PB](LoopPassManager &PM, PassBuilder::OptimizationLevel Level) { 174 ExitOnError Err("Unable to parse LoopOptimizerEndEP pipeline: "); 175 Err(PB.parsePassPipeline(PM, LoopOptimizerEndEPPipeline)); 176 }); 177 if (tryParsePipelineText<FunctionPassManager>(PB, 178 ScalarOptimizerLateEPPipeline)) 179 PB.registerScalarOptimizerLateEPCallback( 180 [&PB](FunctionPassManager &PM, PassBuilder::OptimizationLevel Level) { 181 ExitOnError Err("Unable to parse ScalarOptimizerLateEP pipeline: "); 182 Err(PB.parsePassPipeline(PM, ScalarOptimizerLateEPPipeline)); 183 }); 184 if (tryParsePipelineText<CGSCCPassManager>(PB, CGSCCOptimizerLateEPPipeline)) 185 PB.registerCGSCCOptimizerLateEPCallback( 186 [&PB](CGSCCPassManager &PM, PassBuilder::OptimizationLevel Level) { 187 ExitOnError Err("Unable to parse CGSCCOptimizerLateEP pipeline: "); 188 Err(PB.parsePassPipeline(PM, CGSCCOptimizerLateEPPipeline)); 189 }); 190 if (tryParsePipelineText<FunctionPassManager>(PB, VectorizerStartEPPipeline)) 191 PB.registerVectorizerStartEPCallback( 192 [&PB](FunctionPassManager &PM, PassBuilder::OptimizationLevel Level) { 193 ExitOnError Err("Unable to parse VectorizerStartEP pipeline: "); 194 Err(PB.parsePassPipeline(PM, VectorizerStartEPPipeline)); 195 }); 196 if (tryParsePipelineText<ModulePassManager>(PB, PipelineStartEPPipeline)) 197 PB.registerPipelineStartEPCallback( 198 [&PB](ModulePassManager &PM, PassBuilder::OptimizationLevel) { 199 ExitOnError Err("Unable to parse PipelineStartEP pipeline: "); 200 Err(PB.parsePassPipeline(PM, PipelineStartEPPipeline)); 201 }); 202 if (tryParsePipelineText<ModulePassManager>( 203 PB, PipelineEarlySimplificationEPPipeline)) 204 PB.registerPipelineEarlySimplificationEPCallback( 205 [&PB](ModulePassManager &PM, PassBuilder::OptimizationLevel) { 206 ExitOnError Err("Unable to parse EarlySimplification pipeline: "); 207 Err(PB.parsePassPipeline(PM, PipelineEarlySimplificationEPPipeline)); 208 }); 209 if (tryParsePipelineText<FunctionPassManager>(PB, OptimizerLastEPPipeline)) 210 PB.registerOptimizerLastEPCallback( 211 [&PB](ModulePassManager &PM, PassBuilder::OptimizationLevel) { 212 ExitOnError Err("Unable to parse OptimizerLastEP pipeline: "); 213 Err(PB.parsePassPipeline(PM, OptimizerLastEPPipeline)); 214 }); 215 } 216 217 #define HANDLE_EXTENSION(Ext) \ 218 llvm::PassPluginLibraryInfo get##Ext##PluginInfo(); 219 #include "llvm/Support/Extension.def" 220 221 bool llvm::runPassPipeline(StringRef Arg0, Module &M, TargetMachine *TM, 222 TargetLibraryInfoImpl *TLII, ToolOutputFile *Out, 223 ToolOutputFile *ThinLTOLinkOut, 224 ToolOutputFile *OptRemarkFile, 225 StringRef PassPipeline, ArrayRef<StringRef> Passes, 226 OutputKind OK, VerifierKind VK, 227 bool ShouldPreserveAssemblyUseListOrder, 228 bool ShouldPreserveBitcodeUseListOrder, 229 bool EmitSummaryIndex, bool EmitModuleHash, 230 bool EnableDebugify, bool Coroutines) { 231 bool VerifyEachPass = VK == VK_VerifyEachPass; 232 233 Optional<PGOOptions> P; 234 switch (PGOKindFlag) { 235 case InstrGen: 236 P = PGOOptions(ProfileFile, "", "", PGOOptions::IRInstr); 237 break; 238 case InstrUse: 239 P = PGOOptions(ProfileFile, "", ProfileRemappingFile, PGOOptions::IRUse); 240 break; 241 case SampleUse: 242 P = PGOOptions(ProfileFile, "", ProfileRemappingFile, 243 PGOOptions::SampleUse); 244 break; 245 case NoPGO: 246 if (DebugInfoForProfiling) 247 P = PGOOptions("", "", "", PGOOptions::NoAction, PGOOptions::NoCSAction, 248 true); 249 else 250 P = None; 251 } 252 if (CSPGOKindFlag != NoCSPGO) { 253 if (P && (P->Action == PGOOptions::IRInstr || 254 P->Action == PGOOptions::SampleUse)) 255 errs() << "CSPGOKind cannot be used with IRInstr or SampleUse"; 256 if (CSPGOKindFlag == CSInstrGen) { 257 if (CSProfileGenFile.empty()) 258 errs() << "CSInstrGen needs to specify CSProfileGenFile"; 259 if (P) { 260 P->CSAction = PGOOptions::CSIRInstr; 261 P->CSProfileGenFile = CSProfileGenFile; 262 } else 263 P = PGOOptions("", CSProfileGenFile, ProfileRemappingFile, 264 PGOOptions::NoAction, PGOOptions::CSIRInstr); 265 } else /* CSPGOKindFlag == CSInstrUse */ { 266 if (!P) 267 errs() << "CSInstrUse needs to be together with InstrUse"; 268 P->CSAction = PGOOptions::CSIRUse; 269 } 270 } 271 PassInstrumentationCallbacks PIC; 272 StandardInstrumentations SI(DebugPM, VerifyEachPass); 273 SI.registerCallbacks(PIC); 274 DebugifyEachInstrumentation Debugify; 275 if (DebugifyEach) 276 Debugify.registerCallbacks(PIC); 277 278 PipelineTuningOptions PTO; 279 // LoopUnrolling defaults on to true and DisableLoopUnrolling is initialized 280 // to false above so we shouldn't necessarily need to check whether or not the 281 // option has been enabled. 282 PTO.LoopUnrolling = !DisableLoopUnrolling; 283 PTO.Coroutines = Coroutines; 284 PassBuilder PB(DebugPM, TM, PTO, P, &PIC); 285 registerEPCallbacks(PB); 286 287 // Load requested pass plugins and let them register pass builder callbacks 288 for (auto &PluginFN : PassPlugins) { 289 auto PassPlugin = PassPlugin::Load(PluginFN); 290 if (!PassPlugin) { 291 errs() << "Failed to load passes from '" << PluginFN 292 << "'. Request ignored.\n"; 293 continue; 294 } 295 296 PassPlugin->registerPassBuilderCallbacks(PB); 297 } 298 299 // Register a callback that creates the debugify passes as needed. 300 PB.registerPipelineParsingCallback( 301 [](StringRef Name, ModulePassManager &MPM, 302 ArrayRef<PassBuilder::PipelineElement>) { 303 if (Name == "debugify") { 304 MPM.addPass(NewPMDebugifyPass()); 305 return true; 306 } else if (Name == "check-debugify") { 307 MPM.addPass(NewPMCheckDebugifyPass()); 308 return true; 309 } 310 return false; 311 }); 312 PB.registerPipelineParsingCallback( 313 [](StringRef Name, ModulePassManager &MPM, 314 ArrayRef<PassBuilder::PipelineElement>) { 315 if (Name == "asan-pipeline") { 316 MPM.addPass( 317 RequireAnalysisPass<ASanGlobalsMetadataAnalysis, Module>()); 318 MPM.addPass( 319 createModuleToFunctionPassAdaptor(AddressSanitizerPass())); 320 MPM.addPass(ModuleAddressSanitizerPass()); 321 return true; 322 } else if (Name == "asan-function-pipeline") { 323 MPM.addPass( 324 RequireAnalysisPass<ASanGlobalsMetadataAnalysis, Module>()); 325 MPM.addPass( 326 createModuleToFunctionPassAdaptor(AddressSanitizerPass())); 327 return true; 328 } 329 return false; 330 }); 331 332 #define HANDLE_EXTENSION(Ext) \ 333 get##Ext##PluginInfo().RegisterPassBuilderCallbacks(PB); 334 #include "llvm/Support/Extension.def" 335 336 // Specially handle the alias analysis manager so that we can register 337 // a custom pipeline of AA passes with it. 338 AAManager AA; 339 if (!AAPipeline.empty()) { 340 assert(Passes.empty() && 341 "--aa-pipeline and -foo-pass should not both be specified"); 342 if (auto Err = PB.parseAAPipeline(AA, AAPipeline)) { 343 errs() << Arg0 << ": " << toString(std::move(Err)) << "\n"; 344 return false; 345 } 346 } 347 348 // For compatibility with the legacy PM AA pipeline. 349 // AAResultsWrapperPass by default provides basic-aa in the legacy PM 350 // unless -disable-basic-aa is specified. 351 // TODO: remove this once tests implicitly requiring basic-aa use -passes= and 352 // -aa-pipeline=basic-aa. 353 if (!Passes.empty() && !DisableBasicAA) { 354 if (auto Err = PB.parseAAPipeline(AA, "basic-aa")) { 355 errs() << Arg0 << ": " << toString(std::move(Err)) << "\n"; 356 return false; 357 } 358 } 359 360 // For compatibility with legacy pass manager. 361 // Alias analyses are not specially specified when using the legacy PM. 362 for (auto PassName : Passes) { 363 if (PB.isAAPassName(PassName)) { 364 if (auto Err = PB.parseAAPipeline(AA, PassName)) { 365 errs() << Arg0 << ": " << toString(std::move(Err)) << "\n"; 366 return false; 367 } 368 } 369 } 370 371 LoopAnalysisManager LAM(DebugPM); 372 FunctionAnalysisManager FAM(DebugPM); 373 CGSCCAnalysisManager CGAM(DebugPM); 374 ModuleAnalysisManager MAM(DebugPM); 375 376 // Register the AA manager first so that our version is the one used. 377 FAM.registerPass([&] { return std::move(AA); }); 378 // Register our TargetLibraryInfoImpl. 379 FAM.registerPass([&] { return TargetLibraryAnalysis(*TLII); }); 380 381 // Register all the basic analyses with the managers. 382 PB.registerModuleAnalyses(MAM); 383 PB.registerCGSCCAnalyses(CGAM); 384 PB.registerFunctionAnalyses(FAM); 385 PB.registerLoopAnalyses(LAM); 386 PB.crossRegisterProxies(LAM, FAM, CGAM, MAM); 387 388 ModulePassManager MPM(DebugPM); 389 if (VK > VK_NoVerifier) 390 MPM.addPass(VerifierPass()); 391 if (EnableDebugify) 392 MPM.addPass(NewPMDebugifyPass()); 393 394 if (!PassPipeline.empty()) { 395 assert(Passes.empty() && 396 "PassPipeline and Passes should not both contain passes"); 397 if (auto Err = PB.parsePassPipeline(MPM, PassPipeline)) { 398 errs() << Arg0 << ": " << toString(std::move(Err)) << "\n"; 399 return false; 400 } 401 } 402 for (auto PassName : Passes) { 403 std::string ModifiedPassName(PassName.begin(), PassName.end()); 404 if (PB.isAnalysisPassName(PassName)) 405 ModifiedPassName = "require<" + ModifiedPassName + ">"; 406 if (auto Err = PB.parsePassPipeline(MPM, ModifiedPassName)) { 407 errs() << Arg0 << ": " << toString(std::move(Err)) << "\n"; 408 return false; 409 } 410 } 411 412 if (VK > VK_NoVerifier) 413 MPM.addPass(VerifierPass()); 414 if (EnableDebugify) 415 MPM.addPass(NewPMCheckDebugifyPass()); 416 417 // Add any relevant output pass at the end of the pipeline. 418 switch (OK) { 419 case OK_NoOutput: 420 break; // No output pass needed. 421 case OK_OutputAssembly: 422 MPM.addPass( 423 PrintModulePass(Out->os(), "", ShouldPreserveAssemblyUseListOrder)); 424 break; 425 case OK_OutputBitcode: 426 MPM.addPass(BitcodeWriterPass(Out->os(), ShouldPreserveBitcodeUseListOrder, 427 EmitSummaryIndex, EmitModuleHash)); 428 break; 429 case OK_OutputThinLTOBitcode: 430 MPM.addPass(ThinLTOBitcodeWriterPass( 431 Out->os(), ThinLTOLinkOut ? &ThinLTOLinkOut->os() : nullptr)); 432 break; 433 } 434 435 // Before executing passes, print the final values of the LLVM options. 436 cl::PrintOptionValues(); 437 438 // Now that we have all of the passes ready, run them. 439 MPM.run(M, MAM); 440 441 // Declare success. 442 if (OK != OK_NoOutput) { 443 Out->keep(); 444 if (OK == OK_OutputThinLTOBitcode && ThinLTOLinkOut) 445 ThinLTOLinkOut->keep(); 446 } 447 448 if (OptRemarkFile) 449 OptRemarkFile->keep(); 450 451 if (DebugifyEach && !DebugifyExport.empty()) 452 exportDebugifyStats(DebugifyExport, Debugify.StatsMap); 453 454 return true; 455 } 456