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