1 //===- TargetPassConfig.h - Code Generation pass options --------*- C++ -*-===// 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 /// Target-Independent Code Generator Pass Configuration Options pass. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #ifndef LLVM_CODEGEN_TARGETPASSCONFIG_H 15 #define LLVM_CODEGEN_TARGETPASSCONFIG_H 16 17 #include "llvm/Pass.h" 18 #include "llvm/Support/CodeGen.h" 19 #include <cassert> 20 #include <string> 21 22 namespace llvm { 23 24 class LLVMTargetMachine; 25 struct MachineSchedContext; 26 class PassConfigImpl; 27 class ScheduleDAGInstrs; 28 29 // The old pass manager infrastructure is hidden in a legacy namespace now. 30 namespace legacy { 31 32 class PassManagerBase; 33 34 } // end namespace legacy 35 36 using legacy::PassManagerBase; 37 38 /// Discriminated union of Pass ID types. 39 /// 40 /// The PassConfig API prefers dealing with IDs because they are safer and more 41 /// efficient. IDs decouple configuration from instantiation. This way, when a 42 /// pass is overriden, it isn't unnecessarily instantiated. It is also unsafe to 43 /// refer to a Pass pointer after adding it to a pass manager, which deletes 44 /// redundant pass instances. 45 /// 46 /// However, it is convient to directly instantiate target passes with 47 /// non-default ctors. These often don't have a registered PassInfo. Rather than 48 /// force all target passes to implement the pass registry boilerplate, allow 49 /// the PassConfig API to handle either type. 50 /// 51 /// AnalysisID is sadly char*, so PointerIntPair won't work. 52 class IdentifyingPassPtr { 53 union { 54 AnalysisID ID; 55 Pass *P; 56 }; 57 bool IsInstance = false; 58 59 public: 60 IdentifyingPassPtr() : P(nullptr) {} 61 IdentifyingPassPtr(AnalysisID IDPtr) : ID(IDPtr) {} 62 IdentifyingPassPtr(Pass *InstancePtr) : P(InstancePtr), IsInstance(true) {} 63 64 bool isValid() const { return P; } 65 bool isInstance() const { return IsInstance; } 66 67 AnalysisID getID() const { 68 assert(!IsInstance && "Not a Pass ID"); 69 return ID; 70 } 71 72 Pass *getInstance() const { 73 assert(IsInstance && "Not a Pass Instance"); 74 return P; 75 } 76 }; 77 78 template <> struct isPodLike<IdentifyingPassPtr> { 79 static const bool value = true; 80 }; 81 82 /// Target-Independent Code Generator Pass Configuration Options. 83 /// 84 /// This is an ImmutablePass solely for the purpose of exposing CodeGen options 85 /// to the internals of other CodeGen passes. 86 class TargetPassConfig : public ImmutablePass { 87 public: 88 /// Pseudo Pass IDs. These are defined within TargetPassConfig because they 89 /// are unregistered pass IDs. They are only useful for use with 90 /// TargetPassConfig APIs to identify multiple occurrences of the same pass. 91 /// 92 93 /// EarlyTailDuplicate - A clone of the TailDuplicate pass that runs early 94 /// during codegen, on SSA form. 95 static char EarlyTailDuplicateID; 96 97 /// PostRAMachineLICM - A clone of the LICM pass that runs during late machine 98 /// optimization after regalloc. 99 static char PostRAMachineLICMID; 100 101 private: 102 PassManagerBase *PM = nullptr; 103 AnalysisID StartBefore = nullptr; 104 AnalysisID StartAfter = nullptr; 105 AnalysisID StopBefore = nullptr; 106 AnalysisID StopAfter = nullptr; 107 bool Started = true; 108 bool Stopped = false; 109 bool AddingMachinePasses = false; 110 111 protected: 112 LLVMTargetMachine *TM; 113 PassConfigImpl *Impl = nullptr; // Internal data structures 114 bool Initialized = false; // Flagged after all passes are configured. 115 116 // Target Pass Options 117 // Targets provide a default setting, user flags override. 118 bool DisableVerify = false; 119 120 /// Default setting for -enable-tail-merge on this target. 121 bool EnableTailMerge = true; 122 123 /// Require processing of functions such that callees are generated before 124 /// callers. 125 bool RequireCodeGenSCCOrder = false; 126 127 /// Add the actual instruction selection passes. This does not include 128 /// preparation passes on IR. 129 bool addCoreISelPasses(); 130 131 public: 132 TargetPassConfig(LLVMTargetMachine &TM, PassManagerBase &pm); 133 // Dummy constructor. 134 TargetPassConfig(); 135 136 ~TargetPassConfig() override; 137 138 static char ID; 139 140 /// Get the right type of TargetMachine for this target. 141 template<typename TMC> TMC &getTM() const { 142 return *static_cast<TMC*>(TM); 143 } 144 145 // 146 void setInitialized() { Initialized = true; } 147 148 CodeGenOpt::Level getOptLevel() const; 149 150 /// Set the StartAfter, StartBefore and StopAfter passes to allow running only 151 /// a portion of the normal code-gen pass sequence. 152 /// 153 /// If the StartAfter and StartBefore pass ID is zero, then compilation will 154 /// begin at the normal point; otherwise, clear the Started flag to indicate 155 /// that passes should not be added until the starting pass is seen. If the 156 /// Stop pass ID is zero, then compilation will continue to the end. 157 /// 158 /// This function expects that at least one of the StartAfter or the 159 /// StartBefore pass IDs is null. 160 void setStartStopPasses(AnalysisID StartBefore, AnalysisID StartAfter, 161 AnalysisID StopBefore, AnalysisID StopAfter) { 162 assert(!(StartBefore && StartAfter) && 163 "Start after and start before passes are given"); 164 assert(!(StopBefore && StopAfter) && 165 "Stop after and stop before passed are given"); 166 this->StartBefore = StartBefore; 167 this->StartAfter = StartAfter; 168 this->StopBefore = StopBefore; 169 this->StopAfter = StopAfter; 170 Started = (StartAfter == nullptr) && (StartBefore == nullptr); 171 } 172 173 void setDisableVerify(bool Disable) { setOpt(DisableVerify, Disable); } 174 175 bool getEnableTailMerge() const { return EnableTailMerge; } 176 void setEnableTailMerge(bool Enable) { setOpt(EnableTailMerge, Enable); } 177 178 bool requiresCodeGenSCCOrder() const { return RequireCodeGenSCCOrder; } 179 void setRequiresCodeGenSCCOrder(bool Enable = true) { 180 setOpt(RequireCodeGenSCCOrder, Enable); 181 } 182 183 /// Allow the target to override a specific pass without overriding the pass 184 /// pipeline. When passes are added to the standard pipeline at the 185 /// point where StandardID is expected, add TargetID in its place. 186 void substitutePass(AnalysisID StandardID, IdentifyingPassPtr TargetID); 187 188 /// Insert InsertedPassID pass after TargetPassID pass. 189 void insertPass(AnalysisID TargetPassID, IdentifyingPassPtr InsertedPassID, 190 bool VerifyAfter = true, bool PrintAfter = true); 191 192 /// Allow the target to enable a specific standard pass by default. 193 void enablePass(AnalysisID PassID) { substitutePass(PassID, PassID); } 194 195 /// Allow the target to disable a specific standard pass by default. 196 void disablePass(AnalysisID PassID) { 197 substitutePass(PassID, IdentifyingPassPtr()); 198 } 199 200 /// Return the pass substituted for StandardID by the target. 201 /// If no substitution exists, return StandardID. 202 IdentifyingPassPtr getPassSubstitution(AnalysisID StandardID) const; 203 204 /// Return true if the pass has been substituted by the target or 205 /// overridden on the command line. 206 bool isPassSubstitutedOrOverridden(AnalysisID ID) const; 207 208 /// Return true if the optimized regalloc pipeline is enabled. 209 bool getOptimizeRegAlloc() const; 210 211 /// Return true if shrink wrapping is enabled. 212 bool getEnableShrinkWrap() const; 213 214 /// Return true if the default global register allocator is in use and 215 /// has not be overriden on the command line with '-regalloc=...' 216 bool usingDefaultRegAlloc() const; 217 218 /// High level function that adds all passes necessary to go from llvm IR 219 /// representation to the MI representation. 220 /// Adds IR based lowering and target specific optimization passes and finally 221 /// the core instruction selection passes. 222 /// \returns true if an error occured, false otherwise. 223 bool addISelPasses(); 224 225 /// Add common target configurable passes that perform LLVM IR to IR 226 /// transforms following machine independent optimization. 227 virtual void addIRPasses(); 228 229 /// Add passes to lower exception handling for the code generator. 230 void addPassesToHandleExceptions(); 231 232 /// Add pass to prepare the LLVM IR for code generation. This should be done 233 /// before exception handling preparation passes. 234 virtual void addCodeGenPrepare(); 235 236 /// Add common passes that perform LLVM IR to IR transforms in preparation for 237 /// instruction selection. 238 virtual void addISelPrepare(); 239 240 /// addInstSelector - This method should install an instruction selector pass, 241 /// which converts from LLVM code to machine instructions. 242 virtual bool addInstSelector() { 243 return true; 244 } 245 246 /// This method should install an IR translator pass, which converts from 247 /// LLVM code to machine instructions with possibly generic opcodes. 248 virtual bool addIRTranslator() { return true; } 249 250 /// This method may be implemented by targets that want to run passes 251 /// immediately before legalization. 252 virtual void addPreLegalizeMachineIR() {} 253 254 /// This method should install a legalize pass, which converts the instruction 255 /// sequence into one that can be selected by the target. 256 virtual bool addLegalizeMachineIR() { return true; } 257 258 /// This method may be implemented by targets that want to run passes 259 /// immediately before the register bank selection. 260 virtual void addPreRegBankSelect() {} 261 262 /// This method should install a register bank selector pass, which 263 /// assigns register banks to virtual registers without a register 264 /// class or register banks. 265 virtual bool addRegBankSelect() { return true; } 266 267 /// This method may be implemented by targets that want to run passes 268 /// immediately before the (global) instruction selection. 269 virtual void addPreGlobalInstructionSelect() {} 270 271 /// This method should install a (global) instruction selector pass, which 272 /// converts possibly generic instructions to fully target-specific 273 /// instructions, thereby constraining all generic virtual registers to 274 /// register classes. 275 virtual bool addGlobalInstructionSelect() { return true; } 276 277 /// Add the complete, standard set of LLVM CodeGen passes. 278 /// Fully developed targets will not generally override this. 279 virtual void addMachinePasses(); 280 281 /// Create an instance of ScheduleDAGInstrs to be run within the standard 282 /// MachineScheduler pass for this function and target at the current 283 /// optimization level. 284 /// 285 /// This can also be used to plug a new MachineSchedStrategy into an instance 286 /// of the standard ScheduleDAGMI: 287 /// return new ScheduleDAGMI(C, make_unique<MyStrategy>(C), /*RemoveKillFlags=*/false) 288 /// 289 /// Return NULL to select the default (generic) machine scheduler. 290 virtual ScheduleDAGInstrs * 291 createMachineScheduler(MachineSchedContext *C) const { 292 return nullptr; 293 } 294 295 /// Similar to createMachineScheduler but used when postRA machine scheduling 296 /// is enabled. 297 virtual ScheduleDAGInstrs * 298 createPostMachineScheduler(MachineSchedContext *C) const { 299 return nullptr; 300 } 301 302 /// printAndVerify - Add a pass to dump then verify the machine function, if 303 /// those steps are enabled. 304 void printAndVerify(const std::string &Banner); 305 306 /// Add a pass to print the machine function if printing is enabled. 307 void addPrintPass(const std::string &Banner); 308 309 /// Add a pass to perform basic verification of the machine function if 310 /// verification is enabled. 311 void addVerifyPass(const std::string &Banner); 312 313 /// Check whether or not GlobalISel should be enabled by default. 314 /// Fallback/abort behavior is controlled via other methods. 315 virtual bool isGlobalISelEnabled() const; 316 317 /// Check whether or not GlobalISel should abort on error. 318 /// When this is disable, GlobalISel will fall back on SDISel instead of 319 /// erroring out. 320 virtual bool isGlobalISelAbortEnabled() const; 321 322 /// Check whether or not a diagnostic should be emitted when GlobalISel 323 /// uses the fallback path. In other words, it will emit a diagnostic 324 /// when GlobalISel failed and isGlobalISelAbortEnabled is false. 325 virtual bool reportDiagnosticWhenGlobalISelFallback() const; 326 327 protected: 328 // Helper to verify the analysis is really immutable. 329 void setOpt(bool &Opt, bool Val); 330 331 /// Methods with trivial inline returns are convenient points in the common 332 /// codegen pass pipeline where targets may insert passes. Methods with 333 /// out-of-line standard implementations are major CodeGen stages called by 334 /// addMachinePasses. Some targets may override major stages when inserting 335 /// passes is insufficient, but maintaining overriden stages is more work. 336 /// 337 338 /// addPreISelPasses - This method should add any "last minute" LLVM->LLVM 339 /// passes (which are run just before instruction selector). 340 virtual bool addPreISel() { 341 return true; 342 } 343 344 /// addMachineSSAOptimization - Add standard passes that optimize machine 345 /// instructions in SSA form. 346 virtual void addMachineSSAOptimization(); 347 348 /// Add passes that optimize instruction level parallelism for out-of-order 349 /// targets. These passes are run while the machine code is still in SSA 350 /// form, so they can use MachineTraceMetrics to control their heuristics. 351 /// 352 /// All passes added here should preserve the MachineDominatorTree, 353 /// MachineLoopInfo, and MachineTraceMetrics analyses. 354 virtual bool addILPOpts() { 355 return false; 356 } 357 358 /// This method may be implemented by targets that want to run passes 359 /// immediately before register allocation. 360 virtual void addPreRegAlloc() { } 361 362 /// createTargetRegisterAllocator - Create the register allocator pass for 363 /// this target at the current optimization level. 364 virtual FunctionPass *createTargetRegisterAllocator(bool Optimized); 365 366 /// addFastRegAlloc - Add the minimum set of target-independent passes that 367 /// are required for fast register allocation. 368 virtual void addFastRegAlloc(FunctionPass *RegAllocPass); 369 370 /// addOptimizedRegAlloc - Add passes related to register allocation. 371 /// LLVMTargetMachine provides standard regalloc passes for most targets. 372 virtual void addOptimizedRegAlloc(FunctionPass *RegAllocPass); 373 374 /// addPreRewrite - Add passes to the optimized register allocation pipeline 375 /// after register allocation is complete, but before virtual registers are 376 /// rewritten to physical registers. 377 /// 378 /// These passes must preserve VirtRegMap and LiveIntervals, and when running 379 /// after RABasic or RAGreedy, they should take advantage of LiveRegMatrix. 380 /// When these passes run, VirtRegMap contains legal physreg assignments for 381 /// all virtual registers. 382 virtual bool addPreRewrite() { 383 return false; 384 } 385 386 /// This method may be implemented by targets that want to run passes after 387 /// register allocation pass pipeline but before prolog-epilog insertion. 388 virtual void addPostRegAlloc() { } 389 390 /// Add passes that optimize machine instructions after register allocation. 391 virtual void addMachineLateOptimization(); 392 393 /// This method may be implemented by targets that want to run passes after 394 /// prolog-epilog insertion and before the second instruction scheduling pass. 395 virtual void addPreSched2() { } 396 397 /// addGCPasses - Add late codegen passes that analyze code for garbage 398 /// collection. This should return true if GC info should be printed after 399 /// these passes. 400 virtual bool addGCPasses(); 401 402 /// Add standard basic block placement passes. 403 virtual void addBlockPlacement(); 404 405 /// This pass may be implemented by targets that want to run passes 406 /// immediately before machine code is emitted. 407 virtual void addPreEmitPass() { } 408 409 /// Utilities for targets to add passes to the pass manager. 410 /// 411 412 /// Add a CodeGen pass at this point in the pipeline after checking overrides. 413 /// Return the pass that was added, or zero if no pass was added. 414 /// @p printAfter if true and adding a machine function pass add an extra 415 /// machine printer pass afterwards 416 /// @p verifyAfter if true and adding a machine function pass add an extra 417 /// machine verification pass afterwards. 418 AnalysisID addPass(AnalysisID PassID, bool verifyAfter = true, 419 bool printAfter = true); 420 421 /// Add a pass to the PassManager if that pass is supposed to be run, as 422 /// determined by the StartAfter and StopAfter options. Takes ownership of the 423 /// pass. 424 /// @p printAfter if true and adding a machine function pass add an extra 425 /// machine printer pass afterwards 426 /// @p verifyAfter if true and adding a machine function pass add an extra 427 /// machine verification pass afterwards. 428 void addPass(Pass *P, bool verifyAfter = true, bool printAfter = true); 429 430 /// addMachinePasses helper to create the target-selected or overriden 431 /// regalloc pass. 432 FunctionPass *createRegAllocPass(bool Optimized); 433 }; 434 435 } // end namespace llvm 436 437 #endif // LLVM_CODEGEN_TARGETPASSCONFIG_H 438