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 /// Set the StartAfter, StartBefore and StopAfter passes to allow running only 112 /// a portion of the normal code-gen pass sequence. 113 /// 114 /// If the StartAfter and StartBefore pass ID is zero, then compilation will 115 /// begin at the normal point; otherwise, clear the Started flag to indicate 116 /// that passes should not be added until the starting pass is seen. If the 117 /// Stop pass ID is zero, then compilation will continue to the end. 118 /// 119 /// This function expects that at least one of the StartAfter or the 120 /// StartBefore pass IDs is null. 121 void setStartStopPasses(); 122 123 protected: 124 LLVMTargetMachine *TM; 125 PassConfigImpl *Impl = nullptr; // Internal data structures 126 bool Initialized = false; // Flagged after all passes are configured. 127 128 // Target Pass Options 129 // Targets provide a default setting, user flags override. 130 bool DisableVerify = false; 131 132 /// Default setting for -enable-tail-merge on this target. 133 bool EnableTailMerge = true; 134 135 /// Require processing of functions such that callees are generated before 136 /// callers. 137 bool RequireCodeGenSCCOrder = false; 138 139 /// Add the actual instruction selection passes. This does not include 140 /// preparation passes on IR. 141 bool addCoreISelPasses(); 142 143 public: 144 TargetPassConfig(LLVMTargetMachine &TM, PassManagerBase &pm); 145 // Dummy constructor. 146 TargetPassConfig(); 147 148 ~TargetPassConfig() override; 149 150 static char ID; 151 152 /// Get the right type of TargetMachine for this target. 153 template<typename TMC> TMC &getTM() const { 154 return *static_cast<TMC*>(TM); 155 } 156 157 // 158 void setInitialized() { Initialized = true; } 159 160 CodeGenOpt::Level getOptLevel() const; 161 162 /// Describe the status of the codegen 163 /// pipeline set by this target pass config. 164 /// Having a limited codegen pipeline means that options 165 /// have been used to restrict what codegen is doing. 166 /// In particular, that means that codegen won't emit 167 /// assembly code. 168 bool hasLimitedCodeGenPipeline() const; 169 170 /// If hasLimitedCodeGenPipeline is true, this method 171 /// returns a string with the name of the options, separated 172 /// by \p Separator that caused this pipeline to be limited. 173 std::string 174 getLimitedCodeGenPipelineReason(const char *Separator = "/") const; 175 176 /// Check if the codegen pipeline is limited in such a way that it 177 /// won't be complete. When the codegen pipeline is not complete, 178 /// this means it may not be possible to generate assembly from it. 179 bool willCompleteCodeGenPipeline() const { 180 return !hasLimitedCodeGenPipeline() || (!StopAfter && !StopBefore); 181 } 182 183 void setDisableVerify(bool Disable) { setOpt(DisableVerify, Disable); } 184 185 bool getEnableTailMerge() const { return EnableTailMerge; } 186 void setEnableTailMerge(bool Enable) { setOpt(EnableTailMerge, Enable); } 187 188 bool requiresCodeGenSCCOrder() const { return RequireCodeGenSCCOrder; } 189 void setRequiresCodeGenSCCOrder(bool Enable = true) { 190 setOpt(RequireCodeGenSCCOrder, Enable); 191 } 192 193 /// Allow the target to override a specific pass without overriding the pass 194 /// pipeline. When passes are added to the standard pipeline at the 195 /// point where StandardID is expected, add TargetID in its place. 196 void substitutePass(AnalysisID StandardID, IdentifyingPassPtr TargetID); 197 198 /// Insert InsertedPassID pass after TargetPassID pass. 199 void insertPass(AnalysisID TargetPassID, IdentifyingPassPtr InsertedPassID, 200 bool VerifyAfter = true, bool PrintAfter = true); 201 202 /// Allow the target to enable a specific standard pass by default. 203 void enablePass(AnalysisID PassID) { substitutePass(PassID, PassID); } 204 205 /// Allow the target to disable a specific standard pass by default. 206 void disablePass(AnalysisID PassID) { 207 substitutePass(PassID, IdentifyingPassPtr()); 208 } 209 210 /// Return the pass substituted for StandardID by the target. 211 /// If no substitution exists, return StandardID. 212 IdentifyingPassPtr getPassSubstitution(AnalysisID StandardID) const; 213 214 /// Return true if the pass has been substituted by the target or 215 /// overridden on the command line. 216 bool isPassSubstitutedOrOverridden(AnalysisID ID) const; 217 218 /// Return true if the optimized regalloc pipeline is enabled. 219 bool getOptimizeRegAlloc() const; 220 221 /// Return true if shrink wrapping is enabled. 222 bool getEnableShrinkWrap() const; 223 224 /// Return true if the default global register allocator is in use and 225 /// has not be overriden on the command line with '-regalloc=...' 226 bool usingDefaultRegAlloc() const; 227 228 /// High level function that adds all passes necessary to go from llvm IR 229 /// representation to the MI representation. 230 /// Adds IR based lowering and target specific optimization passes and finally 231 /// the core instruction selection passes. 232 /// \returns true if an error occured, false otherwise. 233 bool addISelPasses(); 234 235 /// Add common target configurable passes that perform LLVM IR to IR 236 /// transforms following machine independent optimization. 237 virtual void addIRPasses(); 238 239 /// Add passes to lower exception handling for the code generator. 240 void addPassesToHandleExceptions(); 241 242 /// Add pass to prepare the LLVM IR for code generation. This should be done 243 /// before exception handling preparation passes. 244 virtual void addCodeGenPrepare(); 245 246 /// Add common passes that perform LLVM IR to IR transforms in preparation for 247 /// instruction selection. 248 virtual void addISelPrepare(); 249 250 /// addInstSelector - This method should install an instruction selector pass, 251 /// which converts from LLVM code to machine instructions. 252 virtual bool addInstSelector() { 253 return true; 254 } 255 256 /// This method should install an IR translator pass, which converts from 257 /// LLVM code to machine instructions with possibly generic opcodes. 258 virtual bool addIRTranslator() { return true; } 259 260 /// This method may be implemented by targets that want to run passes 261 /// immediately before legalization. 262 virtual void addPreLegalizeMachineIR() {} 263 264 /// This method should install a legalize pass, which converts the instruction 265 /// sequence into one that can be selected by the target. 266 virtual bool addLegalizeMachineIR() { return true; } 267 268 /// This method may be implemented by targets that want to run passes 269 /// immediately before the register bank selection. 270 virtual void addPreRegBankSelect() {} 271 272 /// This method should install a register bank selector pass, which 273 /// assigns register banks to virtual registers without a register 274 /// class or register banks. 275 virtual bool addRegBankSelect() { return true; } 276 277 /// This method may be implemented by targets that want to run passes 278 /// immediately before the (global) instruction selection. 279 virtual void addPreGlobalInstructionSelect() {} 280 281 /// This method should install a (global) instruction selector pass, which 282 /// converts possibly generic instructions to fully target-specific 283 /// instructions, thereby constraining all generic virtual registers to 284 /// register classes. 285 virtual bool addGlobalInstructionSelect() { return true; } 286 287 /// Add the complete, standard set of LLVM CodeGen passes. 288 /// Fully developed targets will not generally override this. 289 virtual void addMachinePasses(); 290 291 /// Create an instance of ScheduleDAGInstrs to be run within the standard 292 /// MachineScheduler pass for this function and target at the current 293 /// optimization level. 294 /// 295 /// This can also be used to plug a new MachineSchedStrategy into an instance 296 /// of the standard ScheduleDAGMI: 297 /// return new ScheduleDAGMI(C, make_unique<MyStrategy>(C), /*RemoveKillFlags=*/false) 298 /// 299 /// Return NULL to select the default (generic) machine scheduler. 300 virtual ScheduleDAGInstrs * 301 createMachineScheduler(MachineSchedContext *C) const { 302 return nullptr; 303 } 304 305 /// Similar to createMachineScheduler but used when postRA machine scheduling 306 /// is enabled. 307 virtual ScheduleDAGInstrs * 308 createPostMachineScheduler(MachineSchedContext *C) const { 309 return nullptr; 310 } 311 312 /// printAndVerify - Add a pass to dump then verify the machine function, if 313 /// those steps are enabled. 314 void printAndVerify(const std::string &Banner); 315 316 /// Add a pass to print the machine function if printing is enabled. 317 void addPrintPass(const std::string &Banner); 318 319 /// Add a pass to perform basic verification of the machine function if 320 /// verification is enabled. 321 void addVerifyPass(const std::string &Banner); 322 323 /// Check whether or not GlobalISel should be enabled by default. 324 /// Fallback/abort behavior is controlled via other methods. 325 virtual bool isGlobalISelEnabled() const; 326 327 /// Check whether or not GlobalISel should abort on error. 328 /// When this is disabled, GlobalISel will fall back on SDISel instead of 329 /// erroring out. 330 bool isGlobalISelAbortEnabled() const; 331 332 /// Check whether or not a diagnostic should be emitted when GlobalISel 333 /// uses the fallback path. In other words, it will emit a diagnostic 334 /// when GlobalISel failed and isGlobalISelAbortEnabled is false. 335 virtual bool reportDiagnosticWhenGlobalISelFallback() const; 336 337 protected: 338 // Helper to verify the analysis is really immutable. 339 void setOpt(bool &Opt, bool Val); 340 341 /// Methods with trivial inline returns are convenient points in the common 342 /// codegen pass pipeline where targets may insert passes. Methods with 343 /// out-of-line standard implementations are major CodeGen stages called by 344 /// addMachinePasses. Some targets may override major stages when inserting 345 /// passes is insufficient, but maintaining overriden stages is more work. 346 /// 347 348 /// addPreISelPasses - This method should add any "last minute" LLVM->LLVM 349 /// passes (which are run just before instruction selector). 350 virtual bool addPreISel() { 351 return true; 352 } 353 354 /// addMachineSSAOptimization - Add standard passes that optimize machine 355 /// instructions in SSA form. 356 virtual void addMachineSSAOptimization(); 357 358 /// Add passes that optimize instruction level parallelism for out-of-order 359 /// targets. These passes are run while the machine code is still in SSA 360 /// form, so they can use MachineTraceMetrics to control their heuristics. 361 /// 362 /// All passes added here should preserve the MachineDominatorTree, 363 /// MachineLoopInfo, and MachineTraceMetrics analyses. 364 virtual bool addILPOpts() { 365 return false; 366 } 367 368 /// This method may be implemented by targets that want to run passes 369 /// immediately before register allocation. 370 virtual void addPreRegAlloc() { } 371 372 /// createTargetRegisterAllocator - Create the register allocator pass for 373 /// this target at the current optimization level. 374 virtual FunctionPass *createTargetRegisterAllocator(bool Optimized); 375 376 /// addFastRegAlloc - Add the minimum set of target-independent passes that 377 /// are required for fast register allocation. 378 virtual void addFastRegAlloc(FunctionPass *RegAllocPass); 379 380 /// addOptimizedRegAlloc - Add passes related to register allocation. 381 /// LLVMTargetMachine provides standard regalloc passes for most targets. 382 virtual void addOptimizedRegAlloc(FunctionPass *RegAllocPass); 383 384 /// addPreRewrite - Add passes to the optimized register allocation pipeline 385 /// after register allocation is complete, but before virtual registers are 386 /// rewritten to physical registers. 387 /// 388 /// These passes must preserve VirtRegMap and LiveIntervals, and when running 389 /// after RABasic or RAGreedy, they should take advantage of LiveRegMatrix. 390 /// When these passes run, VirtRegMap contains legal physreg assignments for 391 /// all virtual registers. 392 virtual bool addPreRewrite() { 393 return false; 394 } 395 396 /// This method may be implemented by targets that want to run passes after 397 /// register allocation pass pipeline but before prolog-epilog insertion. 398 virtual void addPostRegAlloc() { } 399 400 /// Add passes that optimize machine instructions after register allocation. 401 virtual void addMachineLateOptimization(); 402 403 /// This method may be implemented by targets that want to run passes after 404 /// prolog-epilog insertion and before the second instruction scheduling pass. 405 virtual void addPreSched2() { } 406 407 /// addGCPasses - Add late codegen passes that analyze code for garbage 408 /// collection. This should return true if GC info should be printed after 409 /// these passes. 410 virtual bool addGCPasses(); 411 412 /// Add standard basic block placement passes. 413 virtual void addBlockPlacement(); 414 415 /// This pass may be implemented by targets that want to run passes 416 /// immediately before machine code is emitted. 417 virtual void addPreEmitPass() { } 418 419 /// Targets may add passes immediately before machine code is emitted in this 420 /// callback. This is called even later than `addPreEmitPass`. 421 // FIXME: Rename `addPreEmitPass` to something more sensible given its actual 422 // position and remove the `2` suffix here as this callback is what 423 // `addPreEmitPass` *should* be but in reality isn't. 424 virtual void addPreEmitPass2() {} 425 426 /// Utilities for targets to add passes to the pass manager. 427 /// 428 429 /// Add a CodeGen pass at this point in the pipeline after checking overrides. 430 /// Return the pass that was added, or zero if no pass was added. 431 /// @p printAfter if true and adding a machine function pass add an extra 432 /// machine printer pass afterwards 433 /// @p verifyAfter if true and adding a machine function pass add an extra 434 /// machine verification pass afterwards. 435 AnalysisID addPass(AnalysisID PassID, bool verifyAfter = true, 436 bool printAfter = true); 437 438 /// Add a pass to the PassManager if that pass is supposed to be run, as 439 /// determined by the StartAfter and StopAfter options. Takes ownership of the 440 /// pass. 441 /// @p printAfter if true and adding a machine function pass add an extra 442 /// machine printer pass afterwards 443 /// @p verifyAfter if true and adding a machine function pass add an extra 444 /// machine verification pass afterwards. 445 void addPass(Pass *P, bool verifyAfter = true, bool printAfter = true); 446 447 /// addMachinePasses helper to create the target-selected or overriden 448 /// regalloc pass. 449 FunctionPass *createRegAllocPass(bool Optimized); 450 }; 451 452 } // end namespace llvm 453 454 #endif // LLVM_CODEGEN_TARGETPASSCONFIG_H 455