| File: | src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/MC/MCRegisterInfo.h |
| Warning: | line 217, column 21 Dereference of null pointer |
Press '?' to see keyboard shortcuts
Keyboard shortcuts:
| 1 | //===- MachineSink.cpp - Sinking for machine instructions -----------------===// | ||||
| 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 pass moves instructions into successor blocks when possible, so that | ||||
| 10 | // they aren't executed on paths where their results aren't needed. | ||||
| 11 | // | ||||
| 12 | // This pass is not intended to be a replacement or a complete alternative | ||||
| 13 | // for an LLVM-IR-level sinking pass. It is only designed to sink simple | ||||
| 14 | // constructs that are not exposed before lowering and instruction selection. | ||||
| 15 | // | ||||
| 16 | //===----------------------------------------------------------------------===// | ||||
| 17 | |||||
| 18 | #include "llvm/ADT/DenseSet.h" | ||||
| 19 | #include "llvm/ADT/MapVector.h" | ||||
| 20 | #include "llvm/ADT/PointerIntPair.h" | ||||
| 21 | #include "llvm/ADT/SetVector.h" | ||||
| 22 | #include "llvm/ADT/SmallSet.h" | ||||
| 23 | #include "llvm/ADT/SmallVector.h" | ||||
| 24 | #include "llvm/ADT/SparseBitVector.h" | ||||
| 25 | #include "llvm/ADT/Statistic.h" | ||||
| 26 | #include "llvm/Analysis/AliasAnalysis.h" | ||||
| 27 | #include "llvm/CodeGen/MachineBasicBlock.h" | ||||
| 28 | #include "llvm/CodeGen/MachineBlockFrequencyInfo.h" | ||||
| 29 | #include "llvm/CodeGen/MachineBranchProbabilityInfo.h" | ||||
| 30 | #include "llvm/CodeGen/MachineDominators.h" | ||||
| 31 | #include "llvm/CodeGen/MachineFunction.h" | ||||
| 32 | #include "llvm/CodeGen/MachineFunctionPass.h" | ||||
| 33 | #include "llvm/CodeGen/MachineInstr.h" | ||||
| 34 | #include "llvm/CodeGen/MachineLoopInfo.h" | ||||
| 35 | #include "llvm/CodeGen/MachineOperand.h" | ||||
| 36 | #include "llvm/CodeGen/MachinePostDominators.h" | ||||
| 37 | #include "llvm/CodeGen/MachineRegisterInfo.h" | ||||
| 38 | #include "llvm/CodeGen/RegisterClassInfo.h" | ||||
| 39 | #include "llvm/CodeGen/RegisterPressure.h" | ||||
| 40 | #include "llvm/CodeGen/TargetInstrInfo.h" | ||||
| 41 | #include "llvm/CodeGen/TargetRegisterInfo.h" | ||||
| 42 | #include "llvm/CodeGen/TargetSubtargetInfo.h" | ||||
| 43 | #include "llvm/IR/BasicBlock.h" | ||||
| 44 | #include "llvm/IR/DebugInfoMetadata.h" | ||||
| 45 | #include "llvm/IR/LLVMContext.h" | ||||
| 46 | #include "llvm/InitializePasses.h" | ||||
| 47 | #include "llvm/MC/MCRegisterInfo.h" | ||||
| 48 | #include "llvm/Pass.h" | ||||
| 49 | #include "llvm/Support/BranchProbability.h" | ||||
| 50 | #include "llvm/Support/CommandLine.h" | ||||
| 51 | #include "llvm/Support/Debug.h" | ||||
| 52 | #include "llvm/Support/raw_ostream.h" | ||||
| 53 | #include <algorithm> | ||||
| 54 | #include <cassert> | ||||
| 55 | #include <cstdint> | ||||
| 56 | #include <map> | ||||
| 57 | #include <utility> | ||||
| 58 | #include <vector> | ||||
| 59 | |||||
| 60 | using namespace llvm; | ||||
| 61 | |||||
| 62 | #define DEBUG_TYPE"machine-sink" "machine-sink" | ||||
| 63 | |||||
| 64 | static cl::opt<bool> | ||||
| 65 | SplitEdges("machine-sink-split", | ||||
| 66 | cl::desc("Split critical edges during machine sinking"), | ||||
| 67 | cl::init(true), cl::Hidden); | ||||
| 68 | |||||
| 69 | static cl::opt<bool> | ||||
| 70 | UseBlockFreqInfo("machine-sink-bfi", | ||||
| 71 | cl::desc("Use block frequency info to find successors to sink"), | ||||
| 72 | cl::init(true), cl::Hidden); | ||||
| 73 | |||||
| 74 | static cl::opt<unsigned> SplitEdgeProbabilityThreshold( | ||||
| 75 | "machine-sink-split-probability-threshold", | ||||
| 76 | cl::desc( | ||||
| 77 | "Percentage threshold for splitting single-instruction critical edge. " | ||||
| 78 | "If the branch threshold is higher than this threshold, we allow " | ||||
| 79 | "speculative execution of up to 1 instruction to avoid branching to " | ||||
| 80 | "splitted critical edge"), | ||||
| 81 | cl::init(40), cl::Hidden); | ||||
| 82 | |||||
| 83 | static cl::opt<unsigned> SinkLoadInstsPerBlockThreshold( | ||||
| 84 | "machine-sink-load-instrs-threshold", | ||||
| 85 | cl::desc("Do not try to find alias store for a load if there is a in-path " | ||||
| 86 | "block whose instruction number is higher than this threshold."), | ||||
| 87 | cl::init(2000), cl::Hidden); | ||||
| 88 | |||||
| 89 | static cl::opt<unsigned> SinkLoadBlocksThreshold( | ||||
| 90 | "machine-sink-load-blocks-threshold", | ||||
| 91 | cl::desc("Do not try to find alias store for a load if the block number in " | ||||
| 92 | "the straight line is higher than this threshold."), | ||||
| 93 | cl::init(20), cl::Hidden); | ||||
| 94 | |||||
| 95 | static cl::opt<bool> | ||||
| 96 | SinkInstsIntoLoop("sink-insts-to-avoid-spills", | ||||
| 97 | cl::desc("Sink instructions into loops to avoid " | ||||
| 98 | "register spills"), | ||||
| 99 | cl::init(false), cl::Hidden); | ||||
| 100 | |||||
| 101 | static cl::opt<unsigned> SinkIntoLoopLimit( | ||||
| 102 | "machine-sink-loop-limit", | ||||
| 103 | cl::desc("The maximum number of instructions considered for loop sinking."), | ||||
| 104 | cl::init(50), cl::Hidden); | ||||
| 105 | |||||
| 106 | STATISTIC(NumSunk, "Number of machine instructions sunk")static llvm::Statistic NumSunk = {"machine-sink", "NumSunk", "Number of machine instructions sunk" }; | ||||
| 107 | STATISTIC(NumLoopSunk, "Number of machine instructions sunk into a loop")static llvm::Statistic NumLoopSunk = {"machine-sink", "NumLoopSunk" , "Number of machine instructions sunk into a loop"}; | ||||
| 108 | STATISTIC(NumSplit, "Number of critical edges split")static llvm::Statistic NumSplit = {"machine-sink", "NumSplit" , "Number of critical edges split"}; | ||||
| 109 | STATISTIC(NumCoalesces, "Number of copies coalesced")static llvm::Statistic NumCoalesces = {"machine-sink", "NumCoalesces" , "Number of copies coalesced"}; | ||||
| 110 | STATISTIC(NumPostRACopySink, "Number of copies sunk after RA")static llvm::Statistic NumPostRACopySink = {"machine-sink", "NumPostRACopySink" , "Number of copies sunk after RA"}; | ||||
| 111 | |||||
| 112 | namespace { | ||||
| 113 | |||||
| 114 | class MachineSinking : public MachineFunctionPass { | ||||
| 115 | const TargetInstrInfo *TII; | ||||
| 116 | const TargetRegisterInfo *TRI; | ||||
| 117 | MachineRegisterInfo *MRI; // Machine register information | ||||
| 118 | MachineDominatorTree *DT; // Machine dominator tree | ||||
| 119 | MachinePostDominatorTree *PDT; // Machine post dominator tree | ||||
| 120 | MachineLoopInfo *LI; | ||||
| 121 | MachineBlockFrequencyInfo *MBFI; | ||||
| 122 | const MachineBranchProbabilityInfo *MBPI; | ||||
| 123 | AliasAnalysis *AA; | ||||
| 124 | RegisterClassInfo RegClassInfo; | ||||
| 125 | |||||
| 126 | // Remember which edges have been considered for breaking. | ||||
| 127 | SmallSet<std::pair<MachineBasicBlock*, MachineBasicBlock*>, 8> | ||||
| 128 | CEBCandidates; | ||||
| 129 | // Remember which edges we are about to split. | ||||
| 130 | // This is different from CEBCandidates since those edges | ||||
| 131 | // will be split. | ||||
| 132 | SetVector<std::pair<MachineBasicBlock *, MachineBasicBlock *>> ToSplit; | ||||
| 133 | |||||
| 134 | SparseBitVector<> RegsToClearKillFlags; | ||||
| 135 | |||||
| 136 | using AllSuccsCache = | ||||
| 137 | std::map<MachineBasicBlock *, SmallVector<MachineBasicBlock *, 4>>; | ||||
| 138 | |||||
| 139 | /// DBG_VALUE pointer and flag. The flag is true if this DBG_VALUE is | ||||
| 140 | /// post-dominated by another DBG_VALUE of the same variable location. | ||||
| 141 | /// This is necessary to detect sequences such as: | ||||
| 142 | /// %0 = someinst | ||||
| 143 | /// DBG_VALUE %0, !123, !DIExpression() | ||||
| 144 | /// %1 = anotherinst | ||||
| 145 | /// DBG_VALUE %1, !123, !DIExpression() | ||||
| 146 | /// Where if %0 were to sink, the DBG_VAUE should not sink with it, as that | ||||
| 147 | /// would re-order assignments. | ||||
| 148 | using SeenDbgUser = PointerIntPair<MachineInstr *, 1>; | ||||
| 149 | |||||
| 150 | /// Record of DBG_VALUE uses of vregs in a block, so that we can identify | ||||
| 151 | /// debug instructions to sink. | ||||
| 152 | SmallDenseMap<unsigned, TinyPtrVector<SeenDbgUser>> SeenDbgUsers; | ||||
| 153 | |||||
| 154 | /// Record of debug variables that have had their locations set in the | ||||
| 155 | /// current block. | ||||
| 156 | DenseSet<DebugVariable> SeenDbgVars; | ||||
| 157 | |||||
| 158 | std::map<std::pair<MachineBasicBlock *, MachineBasicBlock *>, bool> | ||||
| 159 | HasStoreCache; | ||||
| 160 | std::map<std::pair<MachineBasicBlock *, MachineBasicBlock *>, | ||||
| 161 | std::vector<MachineInstr *>> | ||||
| 162 | StoreInstrCache; | ||||
| 163 | |||||
| 164 | /// Cached BB's register pressure. | ||||
| 165 | std::map<MachineBasicBlock *, std::vector<unsigned>> CachedRegisterPressure; | ||||
| 166 | |||||
| 167 | public: | ||||
| 168 | static char ID; // Pass identification | ||||
| 169 | |||||
| 170 | MachineSinking() : MachineFunctionPass(ID) { | ||||
| 171 | initializeMachineSinkingPass(*PassRegistry::getPassRegistry()); | ||||
| 172 | } | ||||
| 173 | |||||
| 174 | bool runOnMachineFunction(MachineFunction &MF) override; | ||||
| 175 | |||||
| 176 | void getAnalysisUsage(AnalysisUsage &AU) const override { | ||||
| 177 | MachineFunctionPass::getAnalysisUsage(AU); | ||||
| 178 | AU.addRequired<AAResultsWrapperPass>(); | ||||
| 179 | AU.addRequired<MachineDominatorTree>(); | ||||
| 180 | AU.addRequired<MachinePostDominatorTree>(); | ||||
| 181 | AU.addRequired<MachineLoopInfo>(); | ||||
| 182 | AU.addRequired<MachineBranchProbabilityInfo>(); | ||||
| 183 | AU.addPreserved<MachineLoopInfo>(); | ||||
| 184 | if (UseBlockFreqInfo) | ||||
| 185 | AU.addRequired<MachineBlockFrequencyInfo>(); | ||||
| 186 | } | ||||
| 187 | |||||
| 188 | void releaseMemory() override { | ||||
| 189 | CEBCandidates.clear(); | ||||
| 190 | } | ||||
| 191 | |||||
| 192 | private: | ||||
| 193 | bool ProcessBlock(MachineBasicBlock &MBB); | ||||
| 194 | void ProcessDbgInst(MachineInstr &MI); | ||||
| 195 | bool isWorthBreakingCriticalEdge(MachineInstr &MI, | ||||
| 196 | MachineBasicBlock *From, | ||||
| 197 | MachineBasicBlock *To); | ||||
| 198 | |||||
| 199 | bool hasStoreBetween(MachineBasicBlock *From, MachineBasicBlock *To, | ||||
| 200 | MachineInstr &MI); | ||||
| 201 | |||||
| 202 | /// Postpone the splitting of the given critical | ||||
| 203 | /// edge (\p From, \p To). | ||||
| 204 | /// | ||||
| 205 | /// We do not split the edges on the fly. Indeed, this invalidates | ||||
| 206 | /// the dominance information and thus triggers a lot of updates | ||||
| 207 | /// of that information underneath. | ||||
| 208 | /// Instead, we postpone all the splits after each iteration of | ||||
| 209 | /// the main loop. That way, the information is at least valid | ||||
| 210 | /// for the lifetime of an iteration. | ||||
| 211 | /// | ||||
| 212 | /// \return True if the edge is marked as toSplit, false otherwise. | ||||
| 213 | /// False can be returned if, for instance, this is not profitable. | ||||
| 214 | bool PostponeSplitCriticalEdge(MachineInstr &MI, | ||||
| 215 | MachineBasicBlock *From, | ||||
| 216 | MachineBasicBlock *To, | ||||
| 217 | bool BreakPHIEdge); | ||||
| 218 | bool SinkInstruction(MachineInstr &MI, bool &SawStore, | ||||
| 219 | AllSuccsCache &AllSuccessors); | ||||
| 220 | |||||
| 221 | /// If we sink a COPY inst, some debug users of it's destination may no | ||||
| 222 | /// longer be dominated by the COPY, and will eventually be dropped. | ||||
| 223 | /// This is easily rectified by forwarding the non-dominated debug uses | ||||
| 224 | /// to the copy source. | ||||
| 225 | void SalvageUnsunkDebugUsersOfCopy(MachineInstr &, | ||||
| 226 | MachineBasicBlock *TargetBlock); | ||||
| 227 | bool AllUsesDominatedByBlock(Register Reg, MachineBasicBlock *MBB, | ||||
| 228 | MachineBasicBlock *DefMBB, bool &BreakPHIEdge, | ||||
| 229 | bool &LocalUse) const; | ||||
| 230 | MachineBasicBlock *FindSuccToSinkTo(MachineInstr &MI, MachineBasicBlock *MBB, | ||||
| 231 | bool &BreakPHIEdge, AllSuccsCache &AllSuccessors); | ||||
| 232 | |||||
| 233 | void FindLoopSinkCandidates(MachineLoop *L, MachineBasicBlock *BB, | ||||
| 234 | SmallVectorImpl<MachineInstr *> &Candidates); | ||||
| 235 | bool SinkIntoLoop(MachineLoop *L, MachineInstr &I); | ||||
| 236 | |||||
| 237 | bool isProfitableToSinkTo(Register Reg, MachineInstr &MI, | ||||
| 238 | MachineBasicBlock *MBB, | ||||
| 239 | MachineBasicBlock *SuccToSinkTo, | ||||
| 240 | AllSuccsCache &AllSuccessors); | ||||
| 241 | |||||
| 242 | bool PerformTrivialForwardCoalescing(MachineInstr &MI, | ||||
| 243 | MachineBasicBlock *MBB); | ||||
| 244 | |||||
| 245 | SmallVector<MachineBasicBlock *, 4> & | ||||
| 246 | GetAllSortedSuccessors(MachineInstr &MI, MachineBasicBlock *MBB, | ||||
| 247 | AllSuccsCache &AllSuccessors) const; | ||||
| 248 | |||||
| 249 | std::vector<unsigned> &getBBRegisterPressure(MachineBasicBlock &MBB); | ||||
| 250 | }; | ||||
| 251 | |||||
| 252 | } // end anonymous namespace | ||||
| 253 | |||||
| 254 | char MachineSinking::ID = 0; | ||||
| 255 | |||||
| 256 | char &llvm::MachineSinkingID = MachineSinking::ID; | ||||
| 257 | |||||
| 258 | INITIALIZE_PASS_BEGIN(MachineSinking, DEBUG_TYPE,static void *initializeMachineSinkingPassOnce(PassRegistry & Registry) { | ||||
| 259 | "Machine code sinking", false, false)static void *initializeMachineSinkingPassOnce(PassRegistry & Registry) { | ||||
| 260 | INITIALIZE_PASS_DEPENDENCY(MachineBranchProbabilityInfo)initializeMachineBranchProbabilityInfoPass(Registry); | ||||
| 261 | INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)initializeMachineDominatorTreePass(Registry); | ||||
| 262 | INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)initializeMachineLoopInfoPass(Registry); | ||||
| 263 | INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)initializeAAResultsWrapperPassPass(Registry); | ||||
| 264 | INITIALIZE_PASS_END(MachineSinking, DEBUG_TYPE,PassInfo *PI = new PassInfo( "Machine code sinking", "machine-sink" , &MachineSinking::ID, PassInfo::NormalCtor_t(callDefaultCtor <MachineSinking>), false, false); Registry.registerPass (*PI, true); return PI; } static llvm::once_flag InitializeMachineSinkingPassFlag ; void llvm::initializeMachineSinkingPass(PassRegistry &Registry ) { llvm::call_once(InitializeMachineSinkingPassFlag, initializeMachineSinkingPassOnce , std::ref(Registry)); } | ||||
| 265 | "Machine code sinking", false, false)PassInfo *PI = new PassInfo( "Machine code sinking", "machine-sink" , &MachineSinking::ID, PassInfo::NormalCtor_t(callDefaultCtor <MachineSinking>), false, false); Registry.registerPass (*PI, true); return PI; } static llvm::once_flag InitializeMachineSinkingPassFlag ; void llvm::initializeMachineSinkingPass(PassRegistry &Registry ) { llvm::call_once(InitializeMachineSinkingPassFlag, initializeMachineSinkingPassOnce , std::ref(Registry)); } | ||||
| 266 | |||||
| 267 | bool MachineSinking::PerformTrivialForwardCoalescing(MachineInstr &MI, | ||||
| 268 | MachineBasicBlock *MBB) { | ||||
| 269 | if (!MI.isCopy()) | ||||
| 270 | return false; | ||||
| 271 | |||||
| 272 | Register SrcReg = MI.getOperand(1).getReg(); | ||||
| 273 | Register DstReg = MI.getOperand(0).getReg(); | ||||
| 274 | if (!Register::isVirtualRegister(SrcReg) || | ||||
| 275 | !Register::isVirtualRegister(DstReg) || !MRI->hasOneNonDBGUse(SrcReg)) | ||||
| 276 | return false; | ||||
| 277 | |||||
| 278 | const TargetRegisterClass *SRC = MRI->getRegClass(SrcReg); | ||||
| 279 | const TargetRegisterClass *DRC = MRI->getRegClass(DstReg); | ||||
| 280 | if (SRC != DRC) | ||||
| 281 | return false; | ||||
| 282 | |||||
| 283 | MachineInstr *DefMI = MRI->getVRegDef(SrcReg); | ||||
| 284 | if (DefMI->isCopyLike()) | ||||
| 285 | return false; | ||||
| 286 | LLVM_DEBUG(dbgs() << "Coalescing: " << *DefMI)do { } while (false); | ||||
| 287 | LLVM_DEBUG(dbgs() << "*** to: " << MI)do { } while (false); | ||||
| 288 | MRI->replaceRegWith(DstReg, SrcReg); | ||||
| 289 | MI.eraseFromParent(); | ||||
| 290 | |||||
| 291 | // Conservatively, clear any kill flags, since it's possible that they are no | ||||
| 292 | // longer correct. | ||||
| 293 | MRI->clearKillFlags(SrcReg); | ||||
| 294 | |||||
| 295 | ++NumCoalesces; | ||||
| 296 | return true; | ||||
| 297 | } | ||||
| 298 | |||||
| 299 | /// AllUsesDominatedByBlock - Return true if all uses of the specified register | ||||
| 300 | /// occur in blocks dominated by the specified block. If any use is in the | ||||
| 301 | /// definition block, then return false since it is never legal to move def | ||||
| 302 | /// after uses. | ||||
| 303 | bool MachineSinking::AllUsesDominatedByBlock(Register Reg, | ||||
| 304 | MachineBasicBlock *MBB, | ||||
| 305 | MachineBasicBlock *DefMBB, | ||||
| 306 | bool &BreakPHIEdge, | ||||
| 307 | bool &LocalUse) const { | ||||
| 308 | assert(Register::isVirtualRegister(Reg) && "Only makes sense for vregs")((void)0); | ||||
| 309 | |||||
| 310 | // Ignore debug uses because debug info doesn't affect the code. | ||||
| 311 | if (MRI->use_nodbg_empty(Reg)) | ||||
| 312 | return true; | ||||
| 313 | |||||
| 314 | // BreakPHIEdge is true if all the uses are in the successor MBB being sunken | ||||
| 315 | // into and they are all PHI nodes. In this case, machine-sink must break | ||||
| 316 | // the critical edge first. e.g. | ||||
| 317 | // | ||||
| 318 | // %bb.1: | ||||
| 319 | // Predecessors according to CFG: %bb.0 | ||||
| 320 | // ... | ||||
| 321 | // %def = DEC64_32r %x, implicit-def dead %eflags | ||||
| 322 | // ... | ||||
| 323 | // JE_4 <%bb.37>, implicit %eflags | ||||
| 324 | // Successors according to CFG: %bb.37 %bb.2 | ||||
| 325 | // | ||||
| 326 | // %bb.2: | ||||
| 327 | // %p = PHI %y, %bb.0, %def, %bb.1 | ||||
| 328 | if (all_of(MRI->use_nodbg_operands(Reg), [&](MachineOperand &MO) { | ||||
| 329 | MachineInstr *UseInst = MO.getParent(); | ||||
| 330 | unsigned OpNo = UseInst->getOperandNo(&MO); | ||||
| 331 | MachineBasicBlock *UseBlock = UseInst->getParent(); | ||||
| 332 | return UseBlock == MBB && UseInst->isPHI() && | ||||
| 333 | UseInst->getOperand(OpNo + 1).getMBB() == DefMBB; | ||||
| 334 | })) { | ||||
| 335 | BreakPHIEdge = true; | ||||
| 336 | return true; | ||||
| 337 | } | ||||
| 338 | |||||
| 339 | for (MachineOperand &MO : MRI->use_nodbg_operands(Reg)) { | ||||
| 340 | // Determine the block of the use. | ||||
| 341 | MachineInstr *UseInst = MO.getParent(); | ||||
| 342 | unsigned OpNo = &MO - &UseInst->getOperand(0); | ||||
| 343 | MachineBasicBlock *UseBlock = UseInst->getParent(); | ||||
| 344 | if (UseInst->isPHI()) { | ||||
| 345 | // PHI nodes use the operand in the predecessor block, not the block with | ||||
| 346 | // the PHI. | ||||
| 347 | UseBlock = UseInst->getOperand(OpNo+1).getMBB(); | ||||
| 348 | } else if (UseBlock == DefMBB) { | ||||
| 349 | LocalUse = true; | ||||
| 350 | return false; | ||||
| 351 | } | ||||
| 352 | |||||
| 353 | // Check that it dominates. | ||||
| 354 | if (!DT->dominates(MBB, UseBlock)) | ||||
| 355 | return false; | ||||
| 356 | } | ||||
| 357 | |||||
| 358 | return true; | ||||
| 359 | } | ||||
| 360 | |||||
| 361 | /// Return true if this machine instruction loads from global offset table or | ||||
| 362 | /// constant pool. | ||||
| 363 | static bool mayLoadFromGOTOrConstantPool(MachineInstr &MI) { | ||||
| 364 | assert(MI.mayLoad() && "Expected MI that loads!")((void)0); | ||||
| 365 | |||||
| 366 | // If we lost memory operands, conservatively assume that the instruction | ||||
| 367 | // reads from everything.. | ||||
| 368 | if (MI.memoperands_empty()) | ||||
| 369 | return true; | ||||
| 370 | |||||
| 371 | for (MachineMemOperand *MemOp : MI.memoperands()) | ||||
| 372 | if (const PseudoSourceValue *PSV = MemOp->getPseudoValue()) | ||||
| 373 | if (PSV->isGOT() || PSV->isConstantPool()) | ||||
| 374 | return true; | ||||
| 375 | |||||
| 376 | return false; | ||||
| 377 | } | ||||
| 378 | |||||
| 379 | void MachineSinking::FindLoopSinkCandidates(MachineLoop *L, MachineBasicBlock *BB, | ||||
| 380 | SmallVectorImpl<MachineInstr *> &Candidates) { | ||||
| 381 | for (auto &MI : *BB) { | ||||
| 382 | LLVM_DEBUG(dbgs() << "LoopSink: Analysing candidate: " << MI)do { } while (false); | ||||
| 383 | if (!TII->shouldSink(MI)) { | ||||
| 384 | LLVM_DEBUG(dbgs() << "LoopSink: Instruction not a candidate for this "do { } while (false) | ||||
| 385 | "target\n")do { } while (false); | ||||
| 386 | continue; | ||||
| 387 | } | ||||
| 388 | if (!L->isLoopInvariant(MI)) { | ||||
| 389 | LLVM_DEBUG(dbgs() << "LoopSink: Instruction is not loop invariant\n")do { } while (false); | ||||
| 390 | continue; | ||||
| 391 | } | ||||
| 392 | bool DontMoveAcrossStore = true; | ||||
| 393 | if (!MI.isSafeToMove(AA, DontMoveAcrossStore)) { | ||||
| 394 | LLVM_DEBUG(dbgs() << "LoopSink: Instruction not safe to move.\n")do { } while (false); | ||||
| 395 | continue; | ||||
| 396 | } | ||||
| 397 | if (MI.mayLoad() && !mayLoadFromGOTOrConstantPool(MI)) { | ||||
| 398 | LLVM_DEBUG(dbgs() << "LoopSink: Dont sink GOT or constant pool loads\n")do { } while (false); | ||||
| 399 | continue; | ||||
| 400 | } | ||||
| 401 | if (MI.isConvergent()) | ||||
| 402 | continue; | ||||
| 403 | |||||
| 404 | const MachineOperand &MO = MI.getOperand(0); | ||||
| 405 | if (!MO.isReg() || !MO.getReg() || !MO.isDef()) | ||||
| 406 | continue; | ||||
| 407 | if (!MRI->hasOneDef(MO.getReg())) | ||||
| 408 | continue; | ||||
| 409 | |||||
| 410 | LLVM_DEBUG(dbgs() << "LoopSink: Instruction added as candidate.\n")do { } while (false); | ||||
| 411 | Candidates.push_back(&MI); | ||||
| 412 | } | ||||
| 413 | } | ||||
| 414 | |||||
| 415 | bool MachineSinking::runOnMachineFunction(MachineFunction &MF) { | ||||
| 416 | if (skipFunction(MF.getFunction())) | ||||
| 417 | return false; | ||||
| 418 | |||||
| 419 | LLVM_DEBUG(dbgs() << "******** Machine Sinking ********\n")do { } while (false); | ||||
| 420 | |||||
| 421 | TII = MF.getSubtarget().getInstrInfo(); | ||||
| 422 | TRI = MF.getSubtarget().getRegisterInfo(); | ||||
| 423 | MRI = &MF.getRegInfo(); | ||||
| 424 | DT = &getAnalysis<MachineDominatorTree>(); | ||||
| 425 | PDT = &getAnalysis<MachinePostDominatorTree>(); | ||||
| 426 | LI = &getAnalysis<MachineLoopInfo>(); | ||||
| 427 | MBFI = UseBlockFreqInfo ? &getAnalysis<MachineBlockFrequencyInfo>() : nullptr; | ||||
| 428 | MBPI = &getAnalysis<MachineBranchProbabilityInfo>(); | ||||
| 429 | AA = &getAnalysis<AAResultsWrapperPass>().getAAResults(); | ||||
| 430 | RegClassInfo.runOnMachineFunction(MF); | ||||
| 431 | |||||
| 432 | bool EverMadeChange = false; | ||||
| 433 | |||||
| 434 | while (true) { | ||||
| 435 | bool MadeChange = false; | ||||
| 436 | |||||
| 437 | // Process all basic blocks. | ||||
| 438 | CEBCandidates.clear(); | ||||
| 439 | ToSplit.clear(); | ||||
| 440 | for (auto &MBB: MF) | ||||
| 441 | MadeChange |= ProcessBlock(MBB); | ||||
| 442 | |||||
| 443 | // If we have anything we marked as toSplit, split it now. | ||||
| 444 | for (auto &Pair : ToSplit) { | ||||
| 445 | auto NewSucc = Pair.first->SplitCriticalEdge(Pair.second, *this); | ||||
| 446 | if (NewSucc != nullptr) { | ||||
| 447 | LLVM_DEBUG(dbgs() << " *** Splitting critical edge: "do { } while (false) | ||||
| 448 | << printMBBReference(*Pair.first) << " -- "do { } while (false) | ||||
| 449 | << printMBBReference(*NewSucc) << " -- "do { } while (false) | ||||
| 450 | << printMBBReference(*Pair.second) << '\n')do { } while (false); | ||||
| 451 | if (MBFI) | ||||
| 452 | MBFI->onEdgeSplit(*Pair.first, *NewSucc, *MBPI); | ||||
| 453 | |||||
| 454 | MadeChange = true; | ||||
| 455 | ++NumSplit; | ||||
| 456 | } else | ||||
| 457 | LLVM_DEBUG(dbgs() << " *** Not legal to break critical edge\n")do { } while (false); | ||||
| 458 | } | ||||
| 459 | // If this iteration over the code changed anything, keep iterating. | ||||
| 460 | if (!MadeChange) break; | ||||
| 461 | EverMadeChange = true; | ||||
| 462 | } | ||||
| 463 | |||||
| 464 | if (SinkInstsIntoLoop) { | ||||
| 465 | SmallVector<MachineLoop *, 8> Loops(LI->begin(), LI->end()); | ||||
| 466 | for (auto *L : Loops) { | ||||
| 467 | MachineBasicBlock *Preheader = LI->findLoopPreheader(L); | ||||
| 468 | if (!Preheader) { | ||||
| 469 | LLVM_DEBUG(dbgs() << "LoopSink: Can't find preheader\n")do { } while (false); | ||||
| 470 | continue; | ||||
| 471 | } | ||||
| 472 | SmallVector<MachineInstr *, 8> Candidates; | ||||
| 473 | FindLoopSinkCandidates(L, Preheader, Candidates); | ||||
| 474 | |||||
| 475 | // Walk the candidates in reverse order so that we start with the use | ||||
| 476 | // of a def-use chain, if there is any. | ||||
| 477 | // TODO: Sort the candidates using a cost-model. | ||||
| 478 | unsigned i = 0; | ||||
| 479 | for (auto It = Candidates.rbegin(); It != Candidates.rend(); ++It) { | ||||
| 480 | if (i++ == SinkIntoLoopLimit) { | ||||
| 481 | LLVM_DEBUG(dbgs() << "LoopSink: Limit reached of instructions to "do { } while (false) | ||||
| 482 | "be analysed.")do { } while (false); | ||||
| 483 | break; | ||||
| 484 | } | ||||
| 485 | |||||
| 486 | MachineInstr *I = *It; | ||||
| 487 | if (!SinkIntoLoop(L, *I)) | ||||
| 488 | break; | ||||
| 489 | EverMadeChange = true; | ||||
| 490 | ++NumLoopSunk; | ||||
| 491 | } | ||||
| 492 | } | ||||
| 493 | } | ||||
| 494 | |||||
| 495 | HasStoreCache.clear(); | ||||
| 496 | StoreInstrCache.clear(); | ||||
| 497 | |||||
| 498 | // Now clear any kill flags for recorded registers. | ||||
| 499 | for (auto I : RegsToClearKillFlags) | ||||
| 500 | MRI->clearKillFlags(I); | ||||
| 501 | RegsToClearKillFlags.clear(); | ||||
| 502 | |||||
| 503 | return EverMadeChange; | ||||
| 504 | } | ||||
| 505 | |||||
| 506 | bool MachineSinking::ProcessBlock(MachineBasicBlock &MBB) { | ||||
| 507 | // Can't sink anything out of a block that has less than two successors. | ||||
| 508 | if (MBB.succ_size() <= 1 || MBB.empty()) return false; | ||||
| 509 | |||||
| 510 | // Don't bother sinking code out of unreachable blocks. In addition to being | ||||
| 511 | // unprofitable, it can also lead to infinite looping, because in an | ||||
| 512 | // unreachable loop there may be nowhere to stop. | ||||
| 513 | if (!DT->isReachableFromEntry(&MBB)) return false; | ||||
| 514 | |||||
| 515 | bool MadeChange = false; | ||||
| 516 | |||||
| 517 | // Cache all successors, sorted by frequency info and loop depth. | ||||
| 518 | AllSuccsCache AllSuccessors; | ||||
| 519 | |||||
| 520 | // Walk the basic block bottom-up. Remember if we saw a store. | ||||
| 521 | MachineBasicBlock::iterator I = MBB.end(); | ||||
| 522 | --I; | ||||
| 523 | bool ProcessedBegin, SawStore = false; | ||||
| 524 | do { | ||||
| 525 | MachineInstr &MI = *I; // The instruction to sink. | ||||
| 526 | |||||
| 527 | // Predecrement I (if it's not begin) so that it isn't invalidated by | ||||
| 528 | // sinking. | ||||
| 529 | ProcessedBegin = I == MBB.begin(); | ||||
| 530 | if (!ProcessedBegin) | ||||
| 531 | --I; | ||||
| 532 | |||||
| 533 | if (MI.isDebugOrPseudoInstr()) { | ||||
| 534 | if (MI.isDebugValue()) | ||||
| 535 | ProcessDbgInst(MI); | ||||
| 536 | continue; | ||||
| 537 | } | ||||
| 538 | |||||
| 539 | bool Joined = PerformTrivialForwardCoalescing(MI, &MBB); | ||||
| 540 | if (Joined) { | ||||
| 541 | MadeChange = true; | ||||
| 542 | continue; | ||||
| 543 | } | ||||
| 544 | |||||
| 545 | if (SinkInstruction(MI, SawStore, AllSuccessors)) { | ||||
| 546 | ++NumSunk; | ||||
| 547 | MadeChange = true; | ||||
| 548 | } | ||||
| 549 | |||||
| 550 | // If we just processed the first instruction in the block, we're done. | ||||
| 551 | } while (!ProcessedBegin); | ||||
| 552 | |||||
| 553 | SeenDbgUsers.clear(); | ||||
| 554 | SeenDbgVars.clear(); | ||||
| 555 | // recalculate the bb register pressure after sinking one BB. | ||||
| 556 | CachedRegisterPressure.clear(); | ||||
| 557 | |||||
| 558 | return MadeChange; | ||||
| 559 | } | ||||
| 560 | |||||
| 561 | void MachineSinking::ProcessDbgInst(MachineInstr &MI) { | ||||
| 562 | // When we see DBG_VALUEs for registers, record any vreg it reads, so that | ||||
| 563 | // we know what to sink if the vreg def sinks. | ||||
| 564 | assert(MI.isDebugValue() && "Expected DBG_VALUE for processing")((void)0); | ||||
| 565 | |||||
| 566 | DebugVariable Var(MI.getDebugVariable(), MI.getDebugExpression(), | ||||
| 567 | MI.getDebugLoc()->getInlinedAt()); | ||||
| 568 | bool SeenBefore = SeenDbgVars.contains(Var); | ||||
| 569 | |||||
| 570 | for (MachineOperand &MO : MI.debug_operands()) { | ||||
| 571 | if (MO.isReg() && MO.getReg().isVirtual()) | ||||
| 572 | SeenDbgUsers[MO.getReg()].push_back(SeenDbgUser(&MI, SeenBefore)); | ||||
| 573 | } | ||||
| 574 | |||||
| 575 | // Record the variable for any DBG_VALUE, to avoid re-ordering any of them. | ||||
| 576 | SeenDbgVars.insert(Var); | ||||
| 577 | } | ||||
| 578 | |||||
| 579 | bool MachineSinking::isWorthBreakingCriticalEdge(MachineInstr &MI, | ||||
| 580 | MachineBasicBlock *From, | ||||
| 581 | MachineBasicBlock *To) { | ||||
| 582 | // FIXME: Need much better heuristics. | ||||
| 583 | |||||
| 584 | // If the pass has already considered breaking this edge (during this pass | ||||
| 585 | // through the function), then let's go ahead and break it. This means | ||||
| 586 | // sinking multiple "cheap" instructions into the same block. | ||||
| 587 | if (!CEBCandidates.insert(std::make_pair(From, To)).second) | ||||
| 588 | return true; | ||||
| 589 | |||||
| 590 | if (!MI.isCopy() && !TII->isAsCheapAsAMove(MI)) | ||||
| 591 | return true; | ||||
| 592 | |||||
| 593 | if (From->isSuccessor(To) && MBPI->getEdgeProbability(From, To) <= | ||||
| 594 | BranchProbability(SplitEdgeProbabilityThreshold, 100)) | ||||
| 595 | return true; | ||||
| 596 | |||||
| 597 | // MI is cheap, we probably don't want to break the critical edge for it. | ||||
| 598 | // However, if this would allow some definitions of its source operands | ||||
| 599 | // to be sunk then it's probably worth it. | ||||
| 600 | for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) { | ||||
| 601 | const MachineOperand &MO = MI.getOperand(i); | ||||
| 602 | if (!MO.isReg() || !MO.isUse()) | ||||
| 603 | continue; | ||||
| 604 | Register Reg = MO.getReg(); | ||||
| 605 | if (Reg == 0) | ||||
| 606 | continue; | ||||
| 607 | |||||
| 608 | // We don't move live definitions of physical registers, | ||||
| 609 | // so sinking their uses won't enable any opportunities. | ||||
| 610 | if (Register::isPhysicalRegister(Reg)) | ||||
| 611 | continue; | ||||
| 612 | |||||
| 613 | // If this instruction is the only user of a virtual register, | ||||
| 614 | // check if breaking the edge will enable sinking | ||||
| 615 | // both this instruction and the defining instruction. | ||||
| 616 | if (MRI->hasOneNonDBGUse(Reg)) { | ||||
| 617 | // If the definition resides in same MBB, | ||||
| 618 | // claim it's likely we can sink these together. | ||||
| 619 | // If definition resides elsewhere, we aren't | ||||
| 620 | // blocking it from being sunk so don't break the edge. | ||||
| 621 | MachineInstr *DefMI = MRI->getVRegDef(Reg); | ||||
| 622 | if (DefMI->getParent() == MI.getParent()) | ||||
| 623 | return true; | ||||
| 624 | } | ||||
| 625 | } | ||||
| 626 | |||||
| 627 | return false; | ||||
| 628 | } | ||||
| 629 | |||||
| 630 | bool MachineSinking::PostponeSplitCriticalEdge(MachineInstr &MI, | ||||
| 631 | MachineBasicBlock *FromBB, | ||||
| 632 | MachineBasicBlock *ToBB, | ||||
| 633 | bool BreakPHIEdge) { | ||||
| 634 | if (!isWorthBreakingCriticalEdge(MI, FromBB, ToBB)) | ||||
| 635 | return false; | ||||
| 636 | |||||
| 637 | // Avoid breaking back edge. From == To means backedge for single BB loop. | ||||
| 638 | if (!SplitEdges || FromBB == ToBB) | ||||
| 639 | return false; | ||||
| 640 | |||||
| 641 | // Check for backedges of more "complex" loops. | ||||
| 642 | if (LI->getLoopFor(FromBB) == LI->getLoopFor(ToBB) && | ||||
| 643 | LI->isLoopHeader(ToBB)) | ||||
| 644 | return false; | ||||
| 645 | |||||
| 646 | // It's not always legal to break critical edges and sink the computation | ||||
| 647 | // to the edge. | ||||
| 648 | // | ||||
| 649 | // %bb.1: | ||||
| 650 | // v1024 | ||||
| 651 | // Beq %bb.3 | ||||
| 652 | // <fallthrough> | ||||
| 653 | // %bb.2: | ||||
| 654 | // ... no uses of v1024 | ||||
| 655 | // <fallthrough> | ||||
| 656 | // %bb.3: | ||||
| 657 | // ... | ||||
| 658 | // = v1024 | ||||
| 659 | // | ||||
| 660 | // If %bb.1 -> %bb.3 edge is broken and computation of v1024 is inserted: | ||||
| 661 | // | ||||
| 662 | // %bb.1: | ||||
| 663 | // ... | ||||
| 664 | // Bne %bb.2 | ||||
| 665 | // %bb.4: | ||||
| 666 | // v1024 = | ||||
| 667 | // B %bb.3 | ||||
| 668 | // %bb.2: | ||||
| 669 | // ... no uses of v1024 | ||||
| 670 | // <fallthrough> | ||||
| 671 | // %bb.3: | ||||
| 672 | // ... | ||||
| 673 | // = v1024 | ||||
| 674 | // | ||||
| 675 | // This is incorrect since v1024 is not computed along the %bb.1->%bb.2->%bb.3 | ||||
| 676 | // flow. We need to ensure the new basic block where the computation is | ||||
| 677 | // sunk to dominates all the uses. | ||||
| 678 | // It's only legal to break critical edge and sink the computation to the | ||||
| 679 | // new block if all the predecessors of "To", except for "From", are | ||||
| 680 | // not dominated by "From". Given SSA property, this means these | ||||
| 681 | // predecessors are dominated by "To". | ||||
| 682 | // | ||||
| 683 | // There is no need to do this check if all the uses are PHI nodes. PHI | ||||
| 684 | // sources are only defined on the specific predecessor edges. | ||||
| 685 | if (!BreakPHIEdge) { | ||||
| 686 | for (MachineBasicBlock::pred_iterator PI = ToBB->pred_begin(), | ||||
| 687 | E = ToBB->pred_end(); PI != E; ++PI) { | ||||
| 688 | if (*PI == FromBB) | ||||
| 689 | continue; | ||||
| 690 | if (!DT->dominates(ToBB, *PI)) | ||||
| 691 | return false; | ||||
| 692 | } | ||||
| 693 | } | ||||
| 694 | |||||
| 695 | ToSplit.insert(std::make_pair(FromBB, ToBB)); | ||||
| 696 | |||||
| 697 | return true; | ||||
| 698 | } | ||||
| 699 | |||||
| 700 | std::vector<unsigned> & | ||||
| 701 | MachineSinking::getBBRegisterPressure(MachineBasicBlock &MBB) { | ||||
| 702 | // Currently to save compiling time, MBB's register pressure will not change | ||||
| 703 | // in one ProcessBlock iteration because of CachedRegisterPressure. but MBB's | ||||
| 704 | // register pressure is changed after sinking any instructions into it. | ||||
| 705 | // FIXME: need a accurate and cheap register pressure estiminate model here. | ||||
| 706 | auto RP = CachedRegisterPressure.find(&MBB); | ||||
| 707 | if (RP != CachedRegisterPressure.end()) | ||||
| 708 | return RP->second; | ||||
| 709 | |||||
| 710 | RegionPressure Pressure; | ||||
| 711 | RegPressureTracker RPTracker(Pressure); | ||||
| 712 | |||||
| 713 | // Initialize the register pressure tracker. | ||||
| 714 | RPTracker.init(MBB.getParent(), &RegClassInfo, nullptr, &MBB, MBB.end(), | ||||
| 715 | /*TrackLaneMasks*/ false, /*TrackUntiedDefs=*/true); | ||||
| 716 | |||||
| 717 | for (MachineBasicBlock::iterator MII = MBB.instr_end(), | ||||
| 718 | MIE = MBB.instr_begin(); | ||||
| 719 | MII != MIE; --MII) { | ||||
| 720 | MachineInstr &MI = *std::prev(MII); | ||||
| 721 | if (MI.isDebugInstr() || MI.isPseudoProbe()) | ||||
| 722 | continue; | ||||
| 723 | RegisterOperands RegOpers; | ||||
| 724 | RegOpers.collect(MI, *TRI, *MRI, false, false); | ||||
| 725 | RPTracker.recedeSkipDebugValues(); | ||||
| 726 | assert(&*RPTracker.getPos() == &MI && "RPTracker sync error!")((void)0); | ||||
| 727 | RPTracker.recede(RegOpers); | ||||
| 728 | } | ||||
| 729 | |||||
| 730 | RPTracker.closeRegion(); | ||||
| 731 | auto It = CachedRegisterPressure.insert( | ||||
| 732 | std::make_pair(&MBB, RPTracker.getPressure().MaxSetPressure)); | ||||
| 733 | return It.first->second; | ||||
| 734 | } | ||||
| 735 | |||||
| 736 | /// isProfitableToSinkTo - Return true if it is profitable to sink MI. | ||||
| 737 | bool MachineSinking::isProfitableToSinkTo(Register Reg, MachineInstr &MI, | ||||
| 738 | MachineBasicBlock *MBB, | ||||
| 739 | MachineBasicBlock *SuccToSinkTo, | ||||
| 740 | AllSuccsCache &AllSuccessors) { | ||||
| 741 | assert (SuccToSinkTo && "Invalid SinkTo Candidate BB")((void)0); | ||||
| 742 | |||||
| 743 | if (MBB == SuccToSinkTo) | ||||
| 744 | return false; | ||||
| 745 | |||||
| 746 | // It is profitable if SuccToSinkTo does not post dominate current block. | ||||
| 747 | if (!PDT->dominates(SuccToSinkTo, MBB)) | ||||
| 748 | return true; | ||||
| 749 | |||||
| 750 | // It is profitable to sink an instruction from a deeper loop to a shallower | ||||
| 751 | // loop, even if the latter post-dominates the former (PR21115). | ||||
| 752 | if (LI->getLoopDepth(MBB) > LI->getLoopDepth(SuccToSinkTo)) | ||||
| 753 | return true; | ||||
| 754 | |||||
| 755 | // Check if only use in post dominated block is PHI instruction. | ||||
| 756 | bool NonPHIUse = false; | ||||
| 757 | for (MachineInstr &UseInst : MRI->use_nodbg_instructions(Reg)) { | ||||
| 758 | MachineBasicBlock *UseBlock = UseInst.getParent(); | ||||
| 759 | if (UseBlock == SuccToSinkTo && !UseInst.isPHI()) | ||||
| 760 | NonPHIUse = true; | ||||
| 761 | } | ||||
| 762 | if (!NonPHIUse) | ||||
| 763 | return true; | ||||
| 764 | |||||
| 765 | // If SuccToSinkTo post dominates then also it may be profitable if MI | ||||
| 766 | // can further profitably sinked into another block in next round. | ||||
| 767 | bool BreakPHIEdge = false; | ||||
| 768 | // FIXME - If finding successor is compile time expensive then cache results. | ||||
| 769 | if (MachineBasicBlock *MBB2 = | ||||
| 770 | FindSuccToSinkTo(MI, SuccToSinkTo, BreakPHIEdge, AllSuccessors)) | ||||
| 771 | return isProfitableToSinkTo(Reg, MI, SuccToSinkTo, MBB2, AllSuccessors); | ||||
| 772 | |||||
| 773 | MachineLoop *ML = LI->getLoopFor(MBB); | ||||
| 774 | |||||
| 775 | // If the instruction is not inside a loop, it is not profitable to sink MI to | ||||
| 776 | // a post dominate block SuccToSinkTo. | ||||
| 777 | if (!ML) | ||||
| 778 | return false; | ||||
| 779 | |||||
| 780 | auto isRegisterPressureSetExceedLimit = [&](const TargetRegisterClass *RC) { | ||||
| 781 | unsigned Weight = TRI->getRegClassWeight(RC).RegWeight; | ||||
| 782 | const int *PS = TRI->getRegClassPressureSets(RC); | ||||
| 783 | // Get register pressure for block SuccToSinkTo. | ||||
| 784 | std::vector<unsigned> BBRegisterPressure = | ||||
| 785 | getBBRegisterPressure(*SuccToSinkTo); | ||||
| 786 | for (; *PS != -1; PS++) | ||||
| 787 | // check if any register pressure set exceeds limit in block SuccToSinkTo | ||||
| 788 | // after sinking. | ||||
| 789 | if (Weight + BBRegisterPressure[*PS] >= | ||||
| 790 | TRI->getRegPressureSetLimit(*MBB->getParent(), *PS)) | ||||
| 791 | return true; | ||||
| 792 | return false; | ||||
| 793 | }; | ||||
| 794 | |||||
| 795 | // If this instruction is inside a loop and sinking this instruction can make | ||||
| 796 | // more registers live range shorten, it is still prifitable. | ||||
| 797 | for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) { | ||||
| 798 | const MachineOperand &MO = MI.getOperand(i); | ||||
| 799 | // Ignore non-register operands. | ||||
| 800 | if (!MO.isReg()) | ||||
| 801 | continue; | ||||
| 802 | Register Reg = MO.getReg(); | ||||
| 803 | if (Reg == 0) | ||||
| 804 | continue; | ||||
| 805 | |||||
| 806 | // Don't handle physical register. | ||||
| 807 | if (Register::isPhysicalRegister(Reg)) | ||||
| 808 | return false; | ||||
| 809 | |||||
| 810 | // Users for the defs are all dominated by SuccToSinkTo. | ||||
| 811 | if (MO.isDef()) { | ||||
| 812 | // This def register's live range is shortened after sinking. | ||||
| 813 | bool LocalUse = false; | ||||
| 814 | if (!AllUsesDominatedByBlock(Reg, SuccToSinkTo, MBB, BreakPHIEdge, | ||||
| 815 | LocalUse)) | ||||
| 816 | return false; | ||||
| 817 | } else { | ||||
| 818 | MachineInstr *DefMI = MRI->getVRegDef(Reg); | ||||
| 819 | // DefMI is defined outside of loop. There should be no live range | ||||
| 820 | // impact for this operand. Defination outside of loop means: | ||||
| 821 | // 1: defination is outside of loop. | ||||
| 822 | // 2: defination is in this loop, but it is a PHI in the loop header. | ||||
| 823 | if (LI->getLoopFor(DefMI->getParent()) != ML || | ||||
| 824 | (DefMI->isPHI() && LI->isLoopHeader(DefMI->getParent()))) | ||||
| 825 | continue; | ||||
| 826 | // The DefMI is defined inside the loop. | ||||
| 827 | // If sinking this operand makes some register pressure set exceed limit, | ||||
| 828 | // it is not profitable. | ||||
| 829 | if (isRegisterPressureSetExceedLimit(MRI->getRegClass(Reg))) { | ||||
| 830 | LLVM_DEBUG(dbgs() << "register pressure exceed limit, not profitable.")do { } while (false); | ||||
| 831 | return false; | ||||
| 832 | } | ||||
| 833 | } | ||||
| 834 | } | ||||
| 835 | |||||
| 836 | // If MI is in loop and all its operands are alive across the whole loop or if | ||||
| 837 | // no operand sinking make register pressure set exceed limit, it is | ||||
| 838 | // profitable to sink MI. | ||||
| 839 | return true; | ||||
| 840 | } | ||||
| 841 | |||||
| 842 | /// Get the sorted sequence of successors for this MachineBasicBlock, possibly | ||||
| 843 | /// computing it if it was not already cached. | ||||
| 844 | SmallVector<MachineBasicBlock *, 4> & | ||||
| 845 | MachineSinking::GetAllSortedSuccessors(MachineInstr &MI, MachineBasicBlock *MBB, | ||||
| 846 | AllSuccsCache &AllSuccessors) const { | ||||
| 847 | // Do we have the sorted successors in cache ? | ||||
| 848 | auto Succs = AllSuccessors.find(MBB); | ||||
| 849 | if (Succs != AllSuccessors.end()) | ||||
| 850 | return Succs->second; | ||||
| 851 | |||||
| 852 | SmallVector<MachineBasicBlock *, 4> AllSuccs(MBB->successors()); | ||||
| 853 | |||||
| 854 | // Handle cases where sinking can happen but where the sink point isn't a | ||||
| 855 | // successor. For example: | ||||
| 856 | // | ||||
| 857 | // x = computation | ||||
| 858 | // if () {} else {} | ||||
| 859 | // use x | ||||
| 860 | // | ||||
| 861 | for (MachineDomTreeNode *DTChild : DT->getNode(MBB)->children()) { | ||||
| 862 | // DomTree children of MBB that have MBB as immediate dominator are added. | ||||
| 863 | if (DTChild->getIDom()->getBlock() == MI.getParent() && | ||||
| 864 | // Skip MBBs already added to the AllSuccs vector above. | ||||
| 865 | !MBB->isSuccessor(DTChild->getBlock())) | ||||
| 866 | AllSuccs.push_back(DTChild->getBlock()); | ||||
| 867 | } | ||||
| 868 | |||||
| 869 | // Sort Successors according to their loop depth or block frequency info. | ||||
| 870 | llvm::stable_sort( | ||||
| 871 | AllSuccs, [this](const MachineBasicBlock *L, const MachineBasicBlock *R) { | ||||
| 872 | uint64_t LHSFreq = MBFI ? MBFI->getBlockFreq(L).getFrequency() : 0; | ||||
| 873 | uint64_t RHSFreq = MBFI ? MBFI->getBlockFreq(R).getFrequency() : 0; | ||||
| 874 | bool HasBlockFreq = LHSFreq != 0 && RHSFreq != 0; | ||||
| 875 | return HasBlockFreq ? LHSFreq < RHSFreq | ||||
| 876 | : LI->getLoopDepth(L) < LI->getLoopDepth(R); | ||||
| 877 | }); | ||||
| 878 | |||||
| 879 | auto it = AllSuccessors.insert(std::make_pair(MBB, AllSuccs)); | ||||
| 880 | |||||
| 881 | return it.first->second; | ||||
| 882 | } | ||||
| 883 | |||||
| 884 | /// FindSuccToSinkTo - Find a successor to sink this instruction to. | ||||
| 885 | MachineBasicBlock * | ||||
| 886 | MachineSinking::FindSuccToSinkTo(MachineInstr &MI, MachineBasicBlock *MBB, | ||||
| 887 | bool &BreakPHIEdge, | ||||
| 888 | AllSuccsCache &AllSuccessors) { | ||||
| 889 | assert (MBB && "Invalid MachineBasicBlock!")((void)0); | ||||
| 890 | |||||
| 891 | // Loop over all the operands of the specified instruction. If there is | ||||
| 892 | // anything we can't handle, bail out. | ||||
| 893 | |||||
| 894 | // SuccToSinkTo - This is the successor to sink this instruction to, once we | ||||
| 895 | // decide. | ||||
| 896 | MachineBasicBlock *SuccToSinkTo = nullptr; | ||||
| 897 | for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) { | ||||
| 898 | const MachineOperand &MO = MI.getOperand(i); | ||||
| 899 | if (!MO.isReg()) continue; // Ignore non-register operands. | ||||
| 900 | |||||
| 901 | Register Reg = MO.getReg(); | ||||
| 902 | if (Reg == 0) continue; | ||||
| 903 | |||||
| 904 | if (Register::isPhysicalRegister(Reg)) { | ||||
| 905 | if (MO.isUse()) { | ||||
| 906 | // If the physreg has no defs anywhere, it's just an ambient register | ||||
| 907 | // and we can freely move its uses. Alternatively, if it's allocatable, | ||||
| 908 | // it could get allocated to something with a def during allocation. | ||||
| 909 | if (!MRI->isConstantPhysReg(Reg)) | ||||
| 910 | return nullptr; | ||||
| 911 | } else if (!MO.isDead()) { | ||||
| 912 | // A def that isn't dead. We can't move it. | ||||
| 913 | return nullptr; | ||||
| 914 | } | ||||
| 915 | } else { | ||||
| 916 | // Virtual register uses are always safe to sink. | ||||
| 917 | if (MO.isUse()) continue; | ||||
| 918 | |||||
| 919 | // If it's not safe to move defs of the register class, then abort. | ||||
| 920 | if (!TII->isSafeToMoveRegClassDefs(MRI->getRegClass(Reg))) | ||||
| 921 | return nullptr; | ||||
| 922 | |||||
| 923 | // Virtual register defs can only be sunk if all their uses are in blocks | ||||
| 924 | // dominated by one of the successors. | ||||
| 925 | if (SuccToSinkTo) { | ||||
| 926 | // If a previous operand picked a block to sink to, then this operand | ||||
| 927 | // must be sinkable to the same block. | ||||
| 928 | bool LocalUse = false; | ||||
| 929 | if (!AllUsesDominatedByBlock(Reg, SuccToSinkTo, MBB, | ||||
| 930 | BreakPHIEdge, LocalUse)) | ||||
| 931 | return nullptr; | ||||
| 932 | |||||
| 933 | continue; | ||||
| 934 | } | ||||
| 935 | |||||
| 936 | // Otherwise, we should look at all the successors and decide which one | ||||
| 937 | // we should sink to. If we have reliable block frequency information | ||||
| 938 | // (frequency != 0) available, give successors with smaller frequencies | ||||
| 939 | // higher priority, otherwise prioritize smaller loop depths. | ||||
| 940 | for (MachineBasicBlock *SuccBlock : | ||||
| 941 | GetAllSortedSuccessors(MI, MBB, AllSuccessors)) { | ||||
| 942 | bool LocalUse = false; | ||||
| 943 | if (AllUsesDominatedByBlock(Reg, SuccBlock, MBB, | ||||
| 944 | BreakPHIEdge, LocalUse)) { | ||||
| 945 | SuccToSinkTo = SuccBlock; | ||||
| 946 | break; | ||||
| 947 | } | ||||
| 948 | if (LocalUse) | ||||
| 949 | // Def is used locally, it's never safe to move this def. | ||||
| 950 | return nullptr; | ||||
| 951 | } | ||||
| 952 | |||||
| 953 | // If we couldn't find a block to sink to, ignore this instruction. | ||||
| 954 | if (!SuccToSinkTo) | ||||
| 955 | return nullptr; | ||||
| 956 | if (!isProfitableToSinkTo(Reg, MI, MBB, SuccToSinkTo, AllSuccessors)) | ||||
| 957 | return nullptr; | ||||
| 958 | } | ||||
| 959 | } | ||||
| 960 | |||||
| 961 | // It is not possible to sink an instruction into its own block. This can | ||||
| 962 | // happen with loops. | ||||
| 963 | if (MBB == SuccToSinkTo) | ||||
| 964 | return nullptr; | ||||
| 965 | |||||
| 966 | // It's not safe to sink instructions to EH landing pad. Control flow into | ||||
| 967 | // landing pad is implicitly defined. | ||||
| 968 | if (SuccToSinkTo && SuccToSinkTo->isEHPad()) | ||||
| 969 | return nullptr; | ||||
| 970 | |||||
| 971 | // It ought to be okay to sink instructions into an INLINEASM_BR target, but | ||||
| 972 | // only if we make sure that MI occurs _before_ an INLINEASM_BR instruction in | ||||
| 973 | // the source block (which this code does not yet do). So for now, forbid | ||||
| 974 | // doing so. | ||||
| 975 | if (SuccToSinkTo && SuccToSinkTo->isInlineAsmBrIndirectTarget()) | ||||
| 976 | return nullptr; | ||||
| 977 | |||||
| 978 | return SuccToSinkTo; | ||||
| 979 | } | ||||
| 980 | |||||
| 981 | /// Return true if MI is likely to be usable as a memory operation by the | ||||
| 982 | /// implicit null check optimization. | ||||
| 983 | /// | ||||
| 984 | /// This is a "best effort" heuristic, and should not be relied upon for | ||||
| 985 | /// correctness. This returning true does not guarantee that the implicit null | ||||
| 986 | /// check optimization is legal over MI, and this returning false does not | ||||
| 987 | /// guarantee MI cannot possibly be used to do a null check. | ||||
| 988 | static bool SinkingPreventsImplicitNullCheck(MachineInstr &MI, | ||||
| 989 | const TargetInstrInfo *TII, | ||||
| 990 | const TargetRegisterInfo *TRI) { | ||||
| 991 | using MachineBranchPredicate = TargetInstrInfo::MachineBranchPredicate; | ||||
| 992 | |||||
| 993 | auto *MBB = MI.getParent(); | ||||
| 994 | if (MBB->pred_size() != 1) | ||||
| 995 | return false; | ||||
| 996 | |||||
| 997 | auto *PredMBB = *MBB->pred_begin(); | ||||
| 998 | auto *PredBB = PredMBB->getBasicBlock(); | ||||
| 999 | |||||
| 1000 | // Frontends that don't use implicit null checks have no reason to emit | ||||
| 1001 | // branches with make.implicit metadata, and this function should always | ||||
| 1002 | // return false for them. | ||||
| 1003 | if (!PredBB || | ||||
| 1004 | !PredBB->getTerminator()->getMetadata(LLVMContext::MD_make_implicit)) | ||||
| 1005 | return false; | ||||
| 1006 | |||||
| 1007 | const MachineOperand *BaseOp; | ||||
| 1008 | int64_t Offset; | ||||
| 1009 | bool OffsetIsScalable; | ||||
| 1010 | if (!TII->getMemOperandWithOffset(MI, BaseOp, Offset, OffsetIsScalable, TRI)) | ||||
| 1011 | return false; | ||||
| 1012 | |||||
| 1013 | if (!BaseOp->isReg()) | ||||
| 1014 | return false; | ||||
| 1015 | |||||
| 1016 | if (!(MI.mayLoad() && !MI.isPredicable())) | ||||
| 1017 | return false; | ||||
| 1018 | |||||
| 1019 | MachineBranchPredicate MBP; | ||||
| 1020 | if (TII->analyzeBranchPredicate(*PredMBB, MBP, false)) | ||||
| 1021 | return false; | ||||
| 1022 | |||||
| 1023 | return MBP.LHS.isReg() && MBP.RHS.isImm() && MBP.RHS.getImm() == 0 && | ||||
| 1024 | (MBP.Predicate == MachineBranchPredicate::PRED_NE || | ||||
| 1025 | MBP.Predicate == MachineBranchPredicate::PRED_EQ) && | ||||
| 1026 | MBP.LHS.getReg() == BaseOp->getReg(); | ||||
| 1027 | } | ||||
| 1028 | |||||
| 1029 | /// If the sunk instruction is a copy, try to forward the copy instead of | ||||
| 1030 | /// leaving an 'undef' DBG_VALUE in the original location. Don't do this if | ||||
| 1031 | /// there's any subregister weirdness involved. Returns true if copy | ||||
| 1032 | /// propagation occurred. | ||||
| 1033 | static bool attemptDebugCopyProp(MachineInstr &SinkInst, MachineInstr &DbgMI, | ||||
| 1034 | Register Reg) { | ||||
| 1035 | const MachineRegisterInfo &MRI = SinkInst.getMF()->getRegInfo(); | ||||
| 1036 | const TargetInstrInfo &TII = *SinkInst.getMF()->getSubtarget().getInstrInfo(); | ||||
| 1037 | |||||
| 1038 | // Copy DBG_VALUE operand and set the original to undef. We then check to | ||||
| 1039 | // see whether this is something that can be copy-forwarded. If it isn't, | ||||
| 1040 | // continue around the loop. | ||||
| 1041 | |||||
| 1042 | const MachineOperand *SrcMO = nullptr, *DstMO = nullptr; | ||||
| 1043 | auto CopyOperands = TII.isCopyInstr(SinkInst); | ||||
| 1044 | if (!CopyOperands) | ||||
| 1045 | return false; | ||||
| 1046 | SrcMO = CopyOperands->Source; | ||||
| 1047 | DstMO = CopyOperands->Destination; | ||||
| 1048 | |||||
| 1049 | // Check validity of forwarding this copy. | ||||
| 1050 | bool PostRA = MRI.getNumVirtRegs() == 0; | ||||
| 1051 | |||||
| 1052 | // Trying to forward between physical and virtual registers is too hard. | ||||
| 1053 | if (Reg.isVirtual() != SrcMO->getReg().isVirtual()) | ||||
| 1054 | return false; | ||||
| 1055 | |||||
| 1056 | // Only try virtual register copy-forwarding before regalloc, and physical | ||||
| 1057 | // register copy-forwarding after regalloc. | ||||
| 1058 | bool arePhysRegs = !Reg.isVirtual(); | ||||
| 1059 | if (arePhysRegs != PostRA) | ||||
| 1060 | return false; | ||||
| 1061 | |||||
| 1062 | // Pre-regalloc, only forward if all subregisters agree (or there are no | ||||
| 1063 | // subregs at all). More analysis might recover some forwardable copies. | ||||
| 1064 | if (!PostRA) | ||||
| 1065 | for (auto &DbgMO : DbgMI.getDebugOperandsForReg(Reg)) | ||||
| 1066 | if (DbgMO.getSubReg() != SrcMO->getSubReg() || | ||||
| 1067 | DbgMO.getSubReg() != DstMO->getSubReg()) | ||||
| 1068 | return false; | ||||
| 1069 | |||||
| 1070 | // Post-regalloc, we may be sinking a DBG_VALUE of a sub or super-register | ||||
| 1071 | // of this copy. Only forward the copy if the DBG_VALUE operand exactly | ||||
| 1072 | // matches the copy destination. | ||||
| 1073 | if (PostRA && Reg != DstMO->getReg()) | ||||
| 1074 | return false; | ||||
| 1075 | |||||
| 1076 | for (auto &DbgMO : DbgMI.getDebugOperandsForReg(Reg)) { | ||||
| 1077 | DbgMO.setReg(SrcMO->getReg()); | ||||
| 1078 | DbgMO.setSubReg(SrcMO->getSubReg()); | ||||
| 1079 | } | ||||
| 1080 | return true; | ||||
| 1081 | } | ||||
| 1082 | |||||
| 1083 | using MIRegs = std::pair<MachineInstr *, SmallVector<unsigned, 2>>; | ||||
| 1084 | /// Sink an instruction and its associated debug instructions. | ||||
| 1085 | static void performSink(MachineInstr &MI, MachineBasicBlock &SuccToSinkTo, | ||||
| 1086 | MachineBasicBlock::iterator InsertPos, | ||||
| 1087 | SmallVectorImpl<MIRegs> &DbgValuesToSink) { | ||||
| 1088 | |||||
| 1089 | // If we cannot find a location to use (merge with), then we erase the debug | ||||
| 1090 | // location to prevent debug-info driven tools from potentially reporting | ||||
| 1091 | // wrong location information. | ||||
| 1092 | if (!SuccToSinkTo.empty() && InsertPos != SuccToSinkTo.end()) | ||||
| 1093 | MI.setDebugLoc(DILocation::getMergedLocation(MI.getDebugLoc(), | ||||
| 1094 | InsertPos->getDebugLoc())); | ||||
| 1095 | else | ||||
| 1096 | MI.setDebugLoc(DebugLoc()); | ||||
| 1097 | |||||
| 1098 | // Move the instruction. | ||||
| 1099 | MachineBasicBlock *ParentBlock = MI.getParent(); | ||||
| 1100 | SuccToSinkTo.splice(InsertPos, ParentBlock, MI, | ||||
| 1101 | ++MachineBasicBlock::iterator(MI)); | ||||
| 1102 | |||||
| 1103 | // Sink a copy of debug users to the insert position. Mark the original | ||||
| 1104 | // DBG_VALUE location as 'undef', indicating that any earlier variable | ||||
| 1105 | // location should be terminated as we've optimised away the value at this | ||||
| 1106 | // point. | ||||
| 1107 | for (auto DbgValueToSink : DbgValuesToSink) { | ||||
| 1108 | MachineInstr *DbgMI = DbgValueToSink.first; | ||||
| 1109 | MachineInstr *NewDbgMI = DbgMI->getMF()->CloneMachineInstr(DbgMI); | ||||
| 1110 | SuccToSinkTo.insert(InsertPos, NewDbgMI); | ||||
| 1111 | |||||
| 1112 | bool PropagatedAllSunkOps = true; | ||||
| 1113 | for (unsigned Reg : DbgValueToSink.second) { | ||||
| 1114 | if (DbgMI->hasDebugOperandForReg(Reg)) { | ||||
| 1115 | if (!attemptDebugCopyProp(MI, *DbgMI, Reg)) { | ||||
| 1116 | PropagatedAllSunkOps = false; | ||||
| 1117 | break; | ||||
| 1118 | } | ||||
| 1119 | } | ||||
| 1120 | } | ||||
| 1121 | if (!PropagatedAllSunkOps) | ||||
| 1122 | DbgMI->setDebugValueUndef(); | ||||
| 1123 | } | ||||
| 1124 | } | ||||
| 1125 | |||||
| 1126 | /// hasStoreBetween - check if there is store betweeen straight line blocks From | ||||
| 1127 | /// and To. | ||||
| 1128 | bool MachineSinking::hasStoreBetween(MachineBasicBlock *From, | ||||
| 1129 | MachineBasicBlock *To, MachineInstr &MI) { | ||||
| 1130 | // Make sure From and To are in straight line which means From dominates To | ||||
| 1131 | // and To post dominates From. | ||||
| 1132 | if (!DT->dominates(From, To) || !PDT->dominates(To, From)) | ||||
| 1133 | return true; | ||||
| 1134 | |||||
| 1135 | auto BlockPair = std::make_pair(From, To); | ||||
| 1136 | |||||
| 1137 | // Does these two blocks pair be queried before and have a definite cached | ||||
| 1138 | // result? | ||||
| 1139 | if (HasStoreCache.find(BlockPair) != HasStoreCache.end()) | ||||
| 1140 | return HasStoreCache[BlockPair]; | ||||
| 1141 | |||||
| 1142 | if (StoreInstrCache.find(BlockPair) != StoreInstrCache.end()) | ||||
| 1143 | return llvm::any_of(StoreInstrCache[BlockPair], [&](MachineInstr *I) { | ||||
| 1144 | return I->mayAlias(AA, MI, false); | ||||
| 1145 | }); | ||||
| 1146 | |||||
| 1147 | bool SawStore = false; | ||||
| 1148 | bool HasAliasedStore = false; | ||||
| 1149 | DenseSet<MachineBasicBlock *> HandledBlocks; | ||||
| 1150 | DenseSet<MachineBasicBlock *> HandledDomBlocks; | ||||
| 1151 | // Go through all reachable blocks from From. | ||||
| 1152 | for (MachineBasicBlock *BB : depth_first(From)) { | ||||
| 1153 | // We insert the instruction at the start of block To, so no need to worry | ||||
| 1154 | // about stores inside To. | ||||
| 1155 | // Store in block From should be already considered when just enter function | ||||
| 1156 | // SinkInstruction. | ||||
| 1157 | if (BB == To || BB == From) | ||||
| 1158 | continue; | ||||
| 1159 | |||||
| 1160 | // We already handle this BB in previous iteration. | ||||
| 1161 | if (HandledBlocks.count(BB)) | ||||
| 1162 | continue; | ||||
| 1163 | |||||
| 1164 | HandledBlocks.insert(BB); | ||||
| 1165 | // To post dominates BB, it must be a path from block From. | ||||
| 1166 | if (PDT->dominates(To, BB)) { | ||||
| 1167 | if (!HandledDomBlocks.count(BB)) | ||||
| 1168 | HandledDomBlocks.insert(BB); | ||||
| 1169 | |||||
| 1170 | // If this BB is too big or the block number in straight line between From | ||||
| 1171 | // and To is too big, stop searching to save compiling time. | ||||
| 1172 | if (BB->size() > SinkLoadInstsPerBlockThreshold || | ||||
| 1173 | HandledDomBlocks.size() > SinkLoadBlocksThreshold) { | ||||
| 1174 | for (auto *DomBB : HandledDomBlocks) { | ||||
| 1175 | if (DomBB != BB && DT->dominates(DomBB, BB)) | ||||
| 1176 | HasStoreCache[std::make_pair(DomBB, To)] = true; | ||||
| 1177 | else if(DomBB != BB && DT->dominates(BB, DomBB)) | ||||
| 1178 | HasStoreCache[std::make_pair(From, DomBB)] = true; | ||||
| 1179 | } | ||||
| 1180 | HasStoreCache[BlockPair] = true; | ||||
| 1181 | return true; | ||||
| 1182 | } | ||||
| 1183 | |||||
| 1184 | for (MachineInstr &I : *BB) { | ||||
| 1185 | // Treat as alias conservatively for a call or an ordered memory | ||||
| 1186 | // operation. | ||||
| 1187 | if (I.isCall() || I.hasOrderedMemoryRef()) { | ||||
| 1188 | for (auto *DomBB : HandledDomBlocks) { | ||||
| 1189 | if (DomBB != BB && DT->dominates(DomBB, BB)) | ||||
| 1190 | HasStoreCache[std::make_pair(DomBB, To)] = true; | ||||
| 1191 | else if(DomBB != BB && DT->dominates(BB, DomBB)) | ||||
| 1192 | HasStoreCache[std::make_pair(From, DomBB)] = true; | ||||
| 1193 | } | ||||
| 1194 | HasStoreCache[BlockPair] = true; | ||||
| 1195 | return true; | ||||
| 1196 | } | ||||
| 1197 | |||||
| 1198 | if (I.mayStore()) { | ||||
| 1199 | SawStore = true; | ||||
| 1200 | // We still have chance to sink MI if all stores between are not | ||||
| 1201 | // aliased to MI. | ||||
| 1202 | // Cache all store instructions, so that we don't need to go through | ||||
| 1203 | // all From reachable blocks for next load instruction. | ||||
| 1204 | if (I.mayAlias(AA, MI, false)) | ||||
| 1205 | HasAliasedStore = true; | ||||
| 1206 | StoreInstrCache[BlockPair].push_back(&I); | ||||
| 1207 | } | ||||
| 1208 | } | ||||
| 1209 | } | ||||
| 1210 | } | ||||
| 1211 | // If there is no store at all, cache the result. | ||||
| 1212 | if (!SawStore) | ||||
| 1213 | HasStoreCache[BlockPair] = false; | ||||
| 1214 | return HasAliasedStore; | ||||
| 1215 | } | ||||
| 1216 | |||||
| 1217 | /// Sink instructions into loops if profitable. This especially tries to prevent | ||||
| 1218 | /// register spills caused by register pressure if there is little to no | ||||
| 1219 | /// overhead moving instructions into loops. | ||||
| 1220 | bool MachineSinking::SinkIntoLoop(MachineLoop *L, MachineInstr &I) { | ||||
| 1221 | LLVM_DEBUG(dbgs() << "LoopSink: Finding sink block for: " << I)do { } while (false); | ||||
| 1222 | MachineBasicBlock *Preheader = L->getLoopPreheader(); | ||||
| 1223 | assert(Preheader && "Loop sink needs a preheader block")((void)0); | ||||
| 1224 | MachineBasicBlock *SinkBlock = nullptr; | ||||
| 1225 | bool CanSink = true; | ||||
| 1226 | const MachineOperand &MO = I.getOperand(0); | ||||
| 1227 | |||||
| 1228 | for (MachineInstr &MI : MRI->use_instructions(MO.getReg())) { | ||||
| 1229 | LLVM_DEBUG(dbgs() << "LoopSink: Analysing use: " << MI)do { } while (false); | ||||
| 1230 | if (!L->contains(&MI)) { | ||||
| 1231 | LLVM_DEBUG(dbgs() << "LoopSink: Use not in loop, can't sink.\n")do { } while (false); | ||||
| 1232 | CanSink = false; | ||||
| 1233 | break; | ||||
| 1234 | } | ||||
| 1235 | |||||
| 1236 | // FIXME: Come up with a proper cost model that estimates whether sinking | ||||
| 1237 | // the instruction (and thus possibly executing it on every loop | ||||
| 1238 | // iteration) is more expensive than a register. | ||||
| 1239 | // For now assumes that copies are cheap and thus almost always worth it. | ||||
| 1240 | if (!MI.isCopy()) { | ||||
| 1241 | LLVM_DEBUG(dbgs() << "LoopSink: Use is not a copy\n")do { } while (false); | ||||
| 1242 | CanSink = false; | ||||
| 1243 | break; | ||||
| 1244 | } | ||||
| 1245 | if (!SinkBlock) { | ||||
| 1246 | SinkBlock = MI.getParent(); | ||||
| 1247 | LLVM_DEBUG(dbgs() << "LoopSink: Setting sink block to: "do { } while (false) | ||||
| 1248 | << printMBBReference(*SinkBlock) << "\n")do { } while (false); | ||||
| 1249 | continue; | ||||
| 1250 | } | ||||
| 1251 | SinkBlock = DT->findNearestCommonDominator(SinkBlock, MI.getParent()); | ||||
| 1252 | if (!SinkBlock) { | ||||
| 1253 | LLVM_DEBUG(dbgs() << "LoopSink: Can't find nearest dominator\n")do { } while (false); | ||||
| 1254 | CanSink = false; | ||||
| 1255 | break; | ||||
| 1256 | } | ||||
| 1257 | LLVM_DEBUG(dbgs() << "LoopSink: Setting nearest common dom block: " <<do { } while (false) | ||||
| 1258 | printMBBReference(*SinkBlock) << "\n")do { } while (false); | ||||
| 1259 | } | ||||
| 1260 | |||||
| 1261 | if (!CanSink) { | ||||
| 1262 | LLVM_DEBUG(dbgs() << "LoopSink: Can't sink instruction.\n")do { } while (false); | ||||
| 1263 | return false; | ||||
| 1264 | } | ||||
| 1265 | if (!SinkBlock) { | ||||
| 1266 | LLVM_DEBUG(dbgs() << "LoopSink: Not sinking, can't find sink block.\n")do { } while (false); | ||||
| 1267 | return false; | ||||
| 1268 | } | ||||
| 1269 | if (SinkBlock == Preheader) { | ||||
| 1270 | LLVM_DEBUG(dbgs() << "LoopSink: Not sinking, sink block is the preheader\n")do { } while (false); | ||||
| 1271 | return false; | ||||
| 1272 | } | ||||
| 1273 | if (SinkBlock->size() > SinkLoadInstsPerBlockThreshold) { | ||||
| 1274 | LLVM_DEBUG(dbgs() << "LoopSink: Not Sinking, block too large to analyse.\n")do { } while (false); | ||||
| 1275 | return false; | ||||
| 1276 | } | ||||
| 1277 | |||||
| 1278 | LLVM_DEBUG(dbgs() << "LoopSink: Sinking instruction!\n")do { } while (false); | ||||
| 1279 | SinkBlock->splice(SinkBlock->getFirstNonPHI(), Preheader, I); | ||||
| 1280 | |||||
| 1281 | // The instruction is moved from its basic block, so do not retain the | ||||
| 1282 | // debug information. | ||||
| 1283 | assert(!I.isDebugInstr() && "Should not sink debug inst")((void)0); | ||||
| 1284 | I.setDebugLoc(DebugLoc()); | ||||
| 1285 | return true; | ||||
| 1286 | } | ||||
| 1287 | |||||
| 1288 | /// SinkInstruction - Determine whether it is safe to sink the specified machine | ||||
| 1289 | /// instruction out of its current block into a successor. | ||||
| 1290 | bool MachineSinking::SinkInstruction(MachineInstr &MI, bool &SawStore, | ||||
| 1291 | AllSuccsCache &AllSuccessors) { | ||||
| 1292 | // Don't sink instructions that the target prefers not to sink. | ||||
| 1293 | if (!TII->shouldSink(MI)) | ||||
| 1294 | return false; | ||||
| 1295 | |||||
| 1296 | // Check if it's safe to move the instruction. | ||||
| 1297 | if (!MI.isSafeToMove(AA, SawStore)) | ||||
| 1298 | return false; | ||||
| 1299 | |||||
| 1300 | // Convergent operations may not be made control-dependent on additional | ||||
| 1301 | // values. | ||||
| 1302 | if (MI.isConvergent()) | ||||
| 1303 | return false; | ||||
| 1304 | |||||
| 1305 | // Don't break implicit null checks. This is a performance heuristic, and not | ||||
| 1306 | // required for correctness. | ||||
| 1307 | if (SinkingPreventsImplicitNullCheck(MI, TII, TRI)) | ||||
| 1308 | return false; | ||||
| 1309 | |||||
| 1310 | // FIXME: This should include support for sinking instructions within the | ||||
| 1311 | // block they are currently in to shorten the live ranges. We often get | ||||
| 1312 | // instructions sunk into the top of a large block, but it would be better to | ||||
| 1313 | // also sink them down before their first use in the block. This xform has to | ||||
| 1314 | // be careful not to *increase* register pressure though, e.g. sinking | ||||
| 1315 | // "x = y + z" down if it kills y and z would increase the live ranges of y | ||||
| 1316 | // and z and only shrink the live range of x. | ||||
| 1317 | |||||
| 1318 | bool BreakPHIEdge = false; | ||||
| 1319 | MachineBasicBlock *ParentBlock = MI.getParent(); | ||||
| 1320 | MachineBasicBlock *SuccToSinkTo = | ||||
| 1321 | FindSuccToSinkTo(MI, ParentBlock, BreakPHIEdge, AllSuccessors); | ||||
| 1322 | |||||
| 1323 | // If there are no outputs, it must have side-effects. | ||||
| 1324 | if (!SuccToSinkTo) | ||||
| 1325 | return false; | ||||
| 1326 | |||||
| 1327 | // If the instruction to move defines a dead physical register which is live | ||||
| 1328 | // when leaving the basic block, don't move it because it could turn into a | ||||
| 1329 | // "zombie" define of that preg. E.g., EFLAGS. (<rdar://problem/8030636>) | ||||
| 1330 | for (unsigned I = 0, E = MI.getNumOperands(); I != E; ++I) { | ||||
| 1331 | const MachineOperand &MO = MI.getOperand(I); | ||||
| 1332 | if (!MO.isReg()) continue; | ||||
| 1333 | Register Reg = MO.getReg(); | ||||
| 1334 | if (Reg == 0 || !Register::isPhysicalRegister(Reg)) | ||||
| 1335 | continue; | ||||
| 1336 | if (SuccToSinkTo->isLiveIn(Reg)) | ||||
| 1337 | return false; | ||||
| 1338 | } | ||||
| 1339 | |||||
| 1340 | LLVM_DEBUG(dbgs() << "Sink instr " << MI << "\tinto block " << *SuccToSinkTo)do { } while (false); | ||||
| 1341 | |||||
| 1342 | // If the block has multiple predecessors, this is a critical edge. | ||||
| 1343 | // Decide if we can sink along it or need to break the edge. | ||||
| 1344 | if (SuccToSinkTo->pred_size() > 1) { | ||||
| 1345 | // We cannot sink a load across a critical edge - there may be stores in | ||||
| 1346 | // other code paths. | ||||
| 1347 | bool TryBreak = false; | ||||
| 1348 | bool Store = | ||||
| 1349 | MI.mayLoad() ? hasStoreBetween(ParentBlock, SuccToSinkTo, MI) : true; | ||||
| 1350 | if (!MI.isSafeToMove(AA, Store)) { | ||||
| 1351 | LLVM_DEBUG(dbgs() << " *** NOTE: Won't sink load along critical edge.\n")do { } while (false); | ||||
| 1352 | TryBreak = true; | ||||
| 1353 | } | ||||
| 1354 | |||||
| 1355 | // We don't want to sink across a critical edge if we don't dominate the | ||||
| 1356 | // successor. We could be introducing calculations to new code paths. | ||||
| 1357 | if (!TryBreak && !DT->dominates(ParentBlock, SuccToSinkTo)) { | ||||
| 1358 | LLVM_DEBUG(dbgs() << " *** NOTE: Critical edge found\n")do { } while (false); | ||||
| 1359 | TryBreak = true; | ||||
| 1360 | } | ||||
| 1361 | |||||
| 1362 | // Don't sink instructions into a loop. | ||||
| 1363 | if (!TryBreak && LI->isLoopHeader(SuccToSinkTo)) { | ||||
| 1364 | LLVM_DEBUG(dbgs() << " *** NOTE: Loop header found\n")do { } while (false); | ||||
| 1365 | TryBreak = true; | ||||
| 1366 | } | ||||
| 1367 | |||||
| 1368 | // Otherwise we are OK with sinking along a critical edge. | ||||
| 1369 | if (!TryBreak) | ||||
| 1370 | LLVM_DEBUG(dbgs() << "Sinking along critical edge.\n")do { } while (false); | ||||
| 1371 | else { | ||||
| 1372 | // Mark this edge as to be split. | ||||
| 1373 | // If the edge can actually be split, the next iteration of the main loop | ||||
| 1374 | // will sink MI in the newly created block. | ||||
| 1375 | bool Status = | ||||
| 1376 | PostponeSplitCriticalEdge(MI, ParentBlock, SuccToSinkTo, BreakPHIEdge); | ||||
| 1377 | if (!Status) | ||||
| 1378 | LLVM_DEBUG(dbgs() << " *** PUNTING: Not legal or profitable to "do { } while (false) | ||||
| 1379 | "break critical edge\n")do { } while (false); | ||||
| 1380 | // The instruction will not be sunk this time. | ||||
| 1381 | return false; | ||||
| 1382 | } | ||||
| 1383 | } | ||||
| 1384 | |||||
| 1385 | if (BreakPHIEdge) { | ||||
| 1386 | // BreakPHIEdge is true if all the uses are in the successor MBB being | ||||
| 1387 | // sunken into and they are all PHI nodes. In this case, machine-sink must | ||||
| 1388 | // break the critical edge first. | ||||
| 1389 | bool Status = PostponeSplitCriticalEdge(MI, ParentBlock, | ||||
| 1390 | SuccToSinkTo, BreakPHIEdge); | ||||
| 1391 | if (!Status) | ||||
| 1392 | LLVM_DEBUG(dbgs() << " *** PUNTING: Not legal or profitable to "do { } while (false) | ||||
| 1393 | "break critical edge\n")do { } while (false); | ||||
| 1394 | // The instruction will not be sunk this time. | ||||
| 1395 | return false; | ||||
| 1396 | } | ||||
| 1397 | |||||
| 1398 | // Determine where to insert into. Skip phi nodes. | ||||
| 1399 | MachineBasicBlock::iterator InsertPos = SuccToSinkTo->begin(); | ||||
| 1400 | while (InsertPos != SuccToSinkTo->end() && InsertPos->isPHI()) | ||||
| 1401 | ++InsertPos; | ||||
| 1402 | |||||
| 1403 | // Collect debug users of any vreg that this inst defines. | ||||
| 1404 | SmallVector<MIRegs, 4> DbgUsersToSink; | ||||
| 1405 | for (auto &MO : MI.operands()) { | ||||
| 1406 | if (!MO.isReg() || !MO.isDef() || !MO.getReg().isVirtual()) | ||||
| 1407 | continue; | ||||
| 1408 | if (!SeenDbgUsers.count(MO.getReg())) | ||||
| 1409 | continue; | ||||
| 1410 | |||||
| 1411 | // Sink any users that don't pass any other DBG_VALUEs for this variable. | ||||
| 1412 | auto &Users = SeenDbgUsers[MO.getReg()]; | ||||
| 1413 | for (auto &User : Users) { | ||||
| 1414 | MachineInstr *DbgMI = User.getPointer(); | ||||
| 1415 | if (User.getInt()) { | ||||
| 1416 | // This DBG_VALUE would re-order assignments. If we can't copy-propagate | ||||
| 1417 | // it, it can't be recovered. Set it undef. | ||||
| 1418 | if (!attemptDebugCopyProp(MI, *DbgMI, MO.getReg())) | ||||
| 1419 | DbgMI->setDebugValueUndef(); | ||||
| 1420 | } else { | ||||
| 1421 | DbgUsersToSink.push_back( | ||||
| 1422 | {DbgMI, SmallVector<unsigned, 2>(1, MO.getReg())}); | ||||
| 1423 | } | ||||
| 1424 | } | ||||
| 1425 | } | ||||
| 1426 | |||||
| 1427 | // After sinking, some debug users may not be dominated any more. If possible, | ||||
| 1428 | // copy-propagate their operands. As it's expensive, don't do this if there's | ||||
| 1429 | // no debuginfo in the program. | ||||
| 1430 | if (MI.getMF()->getFunction().getSubprogram() && MI.isCopy()) | ||||
| 1431 | SalvageUnsunkDebugUsersOfCopy(MI, SuccToSinkTo); | ||||
| 1432 | |||||
| 1433 | performSink(MI, *SuccToSinkTo, InsertPos, DbgUsersToSink); | ||||
| 1434 | |||||
| 1435 | // Conservatively, clear any kill flags, since it's possible that they are no | ||||
| 1436 | // longer correct. | ||||
| 1437 | // Note that we have to clear the kill flags for any register this instruction | ||||
| 1438 | // uses as we may sink over another instruction which currently kills the | ||||
| 1439 | // used registers. | ||||
| 1440 | for (MachineOperand &MO : MI.operands()) { | ||||
| 1441 | if (MO.isReg() && MO.isUse()) | ||||
| 1442 | RegsToClearKillFlags.set(MO.getReg()); // Remember to clear kill flags. | ||||
| 1443 | } | ||||
| 1444 | |||||
| 1445 | return true; | ||||
| 1446 | } | ||||
| 1447 | |||||
| 1448 | void MachineSinking::SalvageUnsunkDebugUsersOfCopy( | ||||
| 1449 | MachineInstr &MI, MachineBasicBlock *TargetBlock) { | ||||
| 1450 | assert(MI.isCopy())((void)0); | ||||
| 1451 | assert(MI.getOperand(1).isReg())((void)0); | ||||
| 1452 | |||||
| 1453 | // Enumerate all users of vreg operands that are def'd. Skip those that will | ||||
| 1454 | // be sunk. For the rest, if they are not dominated by the block we will sink | ||||
| 1455 | // MI into, propagate the copy source to them. | ||||
| 1456 | SmallVector<MachineInstr *, 4> DbgDefUsers; | ||||
| 1457 | SmallVector<Register, 4> DbgUseRegs; | ||||
| 1458 | const MachineRegisterInfo &MRI = MI.getMF()->getRegInfo(); | ||||
| 1459 | for (auto &MO : MI.operands()) { | ||||
| 1460 | if (!MO.isReg() || !MO.isDef() || !MO.getReg().isVirtual()) | ||||
| 1461 | continue; | ||||
| 1462 | DbgUseRegs.push_back(MO.getReg()); | ||||
| 1463 | for (auto &User : MRI.use_instructions(MO.getReg())) { | ||||
| 1464 | if (!User.isDebugValue() || DT->dominates(TargetBlock, User.getParent())) | ||||
| 1465 | continue; | ||||
| 1466 | |||||
| 1467 | // If is in same block, will either sink or be use-before-def. | ||||
| 1468 | if (User.getParent() == MI.getParent()) | ||||
| 1469 | continue; | ||||
| 1470 | |||||
| 1471 | assert(User.hasDebugOperandForReg(MO.getReg()) &&((void)0) | ||||
| 1472 | "DBG_VALUE user of vreg, but has no operand for it?")((void)0); | ||||
| 1473 | DbgDefUsers.push_back(&User); | ||||
| 1474 | } | ||||
| 1475 | } | ||||
| 1476 | |||||
| 1477 | // Point the users of this copy that are no longer dominated, at the source | ||||
| 1478 | // of the copy. | ||||
| 1479 | for (auto *User : DbgDefUsers) { | ||||
| 1480 | for (auto &Reg : DbgUseRegs) { | ||||
| 1481 | for (auto &DbgOp : User->getDebugOperandsForReg(Reg)) { | ||||
| 1482 | DbgOp.setReg(MI.getOperand(1).getReg()); | ||||
| 1483 | DbgOp.setSubReg(MI.getOperand(1).getSubReg()); | ||||
| 1484 | } | ||||
| 1485 | } | ||||
| 1486 | } | ||||
| 1487 | } | ||||
| 1488 | |||||
| 1489 | //===----------------------------------------------------------------------===// | ||||
| 1490 | // This pass is not intended to be a replacement or a complete alternative | ||||
| 1491 | // for the pre-ra machine sink pass. It is only designed to sink COPY | ||||
| 1492 | // instructions which should be handled after RA. | ||||
| 1493 | // | ||||
| 1494 | // This pass sinks COPY instructions into a successor block, if the COPY is not | ||||
| 1495 | // used in the current block and the COPY is live-in to a single successor | ||||
| 1496 | // (i.e., doesn't require the COPY to be duplicated). This avoids executing the | ||||
| 1497 | // copy on paths where their results aren't needed. This also exposes | ||||
| 1498 | // additional opportunites for dead copy elimination and shrink wrapping. | ||||
| 1499 | // | ||||
| 1500 | // These copies were either not handled by or are inserted after the MachineSink | ||||
| 1501 | // pass. As an example of the former case, the MachineSink pass cannot sink | ||||
| 1502 | // COPY instructions with allocatable source registers; for AArch64 these type | ||||
| 1503 | // of copy instructions are frequently used to move function parameters (PhyReg) | ||||
| 1504 | // into virtual registers in the entry block. | ||||
| 1505 | // | ||||
| 1506 | // For the machine IR below, this pass will sink %w19 in the entry into its | ||||
| 1507 | // successor (%bb.1) because %w19 is only live-in in %bb.1. | ||||
| 1508 | // %bb.0: | ||||
| 1509 | // %wzr = SUBSWri %w1, 1 | ||||
| 1510 | // %w19 = COPY %w0 | ||||
| 1511 | // Bcc 11, %bb.2 | ||||
| 1512 | // %bb.1: | ||||
| 1513 | // Live Ins: %w19 | ||||
| 1514 | // BL @fun | ||||
| 1515 | // %w0 = ADDWrr %w0, %w19 | ||||
| 1516 | // RET %w0 | ||||
| 1517 | // %bb.2: | ||||
| 1518 | // %w0 = COPY %wzr | ||||
| 1519 | // RET %w0 | ||||
| 1520 | // As we sink %w19 (CSR in AArch64) into %bb.1, the shrink-wrapping pass will be | ||||
| 1521 | // able to see %bb.0 as a candidate. | ||||
| 1522 | //===----------------------------------------------------------------------===// | ||||
| 1523 | namespace { | ||||
| 1524 | |||||
| 1525 | class PostRAMachineSinking : public MachineFunctionPass { | ||||
| 1526 | public: | ||||
| 1527 | bool runOnMachineFunction(MachineFunction &MF) override; | ||||
| 1528 | |||||
| 1529 | static char ID; | ||||
| 1530 | PostRAMachineSinking() : MachineFunctionPass(ID) {} | ||||
| 1531 | StringRef getPassName() const override { return "PostRA Machine Sink"; } | ||||
| 1532 | |||||
| 1533 | void getAnalysisUsage(AnalysisUsage &AU) const override { | ||||
| 1534 | AU.setPreservesCFG(); | ||||
| 1535 | MachineFunctionPass::getAnalysisUsage(AU); | ||||
| 1536 | } | ||||
| 1537 | |||||
| 1538 | MachineFunctionProperties getRequiredProperties() const override { | ||||
| 1539 | return MachineFunctionProperties().set( | ||||
| 1540 | MachineFunctionProperties::Property::NoVRegs); | ||||
| 1541 | } | ||||
| 1542 | |||||
| 1543 | private: | ||||
| 1544 | /// Track which register units have been modified and used. | ||||
| 1545 | LiveRegUnits ModifiedRegUnits, UsedRegUnits; | ||||
| 1546 | |||||
| 1547 | /// Track DBG_VALUEs of (unmodified) register units. Each DBG_VALUE has an | ||||
| 1548 | /// entry in this map for each unit it touches. The DBG_VALUE's entry | ||||
| 1549 | /// consists of a pointer to the instruction itself, and a vector of registers | ||||
| 1550 | /// referred to by the instruction that overlap the key register unit. | ||||
| 1551 | DenseMap<unsigned, SmallVector<MIRegs, 2>> SeenDbgInstrs; | ||||
| 1552 | |||||
| 1553 | /// Sink Copy instructions unused in the same block close to their uses in | ||||
| 1554 | /// successors. | ||||
| 1555 | bool tryToSinkCopy(MachineBasicBlock &BB, MachineFunction &MF, | ||||
| 1556 | const TargetRegisterInfo *TRI, const TargetInstrInfo *TII); | ||||
| 1557 | }; | ||||
| 1558 | } // namespace | ||||
| 1559 | |||||
| 1560 | char PostRAMachineSinking::ID = 0; | ||||
| 1561 | char &llvm::PostRAMachineSinkingID = PostRAMachineSinking::ID; | ||||
| 1562 | |||||
| 1563 | INITIALIZE_PASS(PostRAMachineSinking, "postra-machine-sink",static void *initializePostRAMachineSinkingPassOnce(PassRegistry &Registry) { PassInfo *PI = new PassInfo( "PostRA Machine Sink" , "postra-machine-sink", &PostRAMachineSinking::ID, PassInfo ::NormalCtor_t(callDefaultCtor<PostRAMachineSinking>), false , false); Registry.registerPass(*PI, true); return PI; } static llvm::once_flag InitializePostRAMachineSinkingPassFlag; void llvm::initializePostRAMachineSinkingPass(PassRegistry &Registry ) { llvm::call_once(InitializePostRAMachineSinkingPassFlag, initializePostRAMachineSinkingPassOnce , std::ref(Registry)); } | ||||
| 1564 | "PostRA Machine Sink", false, false)static void *initializePostRAMachineSinkingPassOnce(PassRegistry &Registry) { PassInfo *PI = new PassInfo( "PostRA Machine Sink" , "postra-machine-sink", &PostRAMachineSinking::ID, PassInfo ::NormalCtor_t(callDefaultCtor<PostRAMachineSinking>), false , false); Registry.registerPass(*PI, true); return PI; } static llvm::once_flag InitializePostRAMachineSinkingPassFlag; void llvm::initializePostRAMachineSinkingPass(PassRegistry &Registry ) { llvm::call_once(InitializePostRAMachineSinkingPassFlag, initializePostRAMachineSinkingPassOnce , std::ref(Registry)); } | ||||
| 1565 | |||||
| 1566 | static bool aliasWithRegsInLiveIn(MachineBasicBlock &MBB, unsigned Reg, | ||||
| 1567 | const TargetRegisterInfo *TRI) { | ||||
| 1568 | LiveRegUnits LiveInRegUnits(*TRI); | ||||
| 1569 | LiveInRegUnits.addLiveIns(MBB); | ||||
| 1570 | return !LiveInRegUnits.available(Reg); | ||||
| 1571 | } | ||||
| 1572 | |||||
| 1573 | static MachineBasicBlock * | ||||
| 1574 | getSingleLiveInSuccBB(MachineBasicBlock &CurBB, | ||||
| 1575 | const SmallPtrSetImpl<MachineBasicBlock *> &SinkableBBs, | ||||
| 1576 | unsigned Reg, const TargetRegisterInfo *TRI) { | ||||
| 1577 | // Try to find a single sinkable successor in which Reg is live-in. | ||||
| 1578 | MachineBasicBlock *BB = nullptr; | ||||
| 1579 | for (auto *SI : SinkableBBs) { | ||||
| 1580 | if (aliasWithRegsInLiveIn(*SI, Reg, TRI)) { | ||||
| 1581 | // If BB is set here, Reg is live-in to at least two sinkable successors, | ||||
| 1582 | // so quit. | ||||
| 1583 | if (BB) | ||||
| 1584 | return nullptr; | ||||
| 1585 | BB = SI; | ||||
| 1586 | } | ||||
| 1587 | } | ||||
| 1588 | // Reg is not live-in to any sinkable successors. | ||||
| 1589 | if (!BB) | ||||
| 1590 | return nullptr; | ||||
| 1591 | |||||
| 1592 | // Check if any register aliased with Reg is live-in in other successors. | ||||
| 1593 | for (auto *SI : CurBB.successors()) { | ||||
| 1594 | if (!SinkableBBs.count(SI) && aliasWithRegsInLiveIn(*SI, Reg, TRI)) | ||||
| 1595 | return nullptr; | ||||
| 1596 | } | ||||
| 1597 | return BB; | ||||
| 1598 | } | ||||
| 1599 | |||||
| 1600 | static MachineBasicBlock * | ||||
| 1601 | getSingleLiveInSuccBB(MachineBasicBlock &CurBB, | ||||
| 1602 | const SmallPtrSetImpl<MachineBasicBlock *> &SinkableBBs, | ||||
| 1603 | ArrayRef<unsigned> DefedRegsInCopy, | ||||
| 1604 | const TargetRegisterInfo *TRI) { | ||||
| 1605 | MachineBasicBlock *SingleBB = nullptr; | ||||
| 1606 | for (auto DefReg : DefedRegsInCopy) { | ||||
| 1607 | MachineBasicBlock *BB = | ||||
| 1608 | getSingleLiveInSuccBB(CurBB, SinkableBBs, DefReg, TRI); | ||||
| 1609 | if (!BB || (SingleBB && SingleBB != BB)) | ||||
| 1610 | return nullptr; | ||||
| 1611 | SingleBB = BB; | ||||
| 1612 | } | ||||
| 1613 | return SingleBB; | ||||
| 1614 | } | ||||
| 1615 | |||||
| 1616 | static void clearKillFlags(MachineInstr *MI, MachineBasicBlock &CurBB, | ||||
| 1617 | SmallVectorImpl<unsigned> &UsedOpsInCopy, | ||||
| 1618 | LiveRegUnits &UsedRegUnits, | ||||
| 1619 | const TargetRegisterInfo *TRI) { | ||||
| 1620 | for (auto U : UsedOpsInCopy) { | ||||
| 1621 | MachineOperand &MO = MI->getOperand(U); | ||||
| 1622 | Register SrcReg = MO.getReg(); | ||||
| 1623 | if (!UsedRegUnits.available(SrcReg)) { | ||||
| 1624 | MachineBasicBlock::iterator NI = std::next(MI->getIterator()); | ||||
| 1625 | for (MachineInstr &UI : make_range(NI, CurBB.end())) { | ||||
| 1626 | if (UI.killsRegister(SrcReg, TRI)) { | ||||
| 1627 | UI.clearRegisterKills(SrcReg, TRI); | ||||
| 1628 | MO.setIsKill(true); | ||||
| 1629 | break; | ||||
| 1630 | } | ||||
| 1631 | } | ||||
| 1632 | } | ||||
| 1633 | } | ||||
| 1634 | } | ||||
| 1635 | |||||
| 1636 | static void updateLiveIn(MachineInstr *MI, MachineBasicBlock *SuccBB, | ||||
| 1637 | SmallVectorImpl<unsigned> &UsedOpsInCopy, | ||||
| 1638 | SmallVectorImpl<unsigned> &DefedRegsInCopy) { | ||||
| 1639 | MachineFunction &MF = *SuccBB->getParent(); | ||||
| 1640 | const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo(); | ||||
| 1641 | for (unsigned DefReg : DefedRegsInCopy) | ||||
| 1642 | for (MCSubRegIterator S(DefReg, TRI, true); S.isValid(); ++S) | ||||
| 1643 | SuccBB->removeLiveIn(*S); | ||||
| 1644 | for (auto U : UsedOpsInCopy) { | ||||
| 1645 | Register SrcReg = MI->getOperand(U).getReg(); | ||||
| 1646 | LaneBitmask Mask; | ||||
| 1647 | for (MCRegUnitMaskIterator S(SrcReg, TRI); S.isValid(); ++S) { | ||||
| 1648 | Mask |= (*S).second; | ||||
| 1649 | } | ||||
| 1650 | SuccBB->addLiveIn(SrcReg, Mask.any() ? Mask : LaneBitmask::getAll()); | ||||
| 1651 | } | ||||
| 1652 | SuccBB->sortUniqueLiveIns(); | ||||
| 1653 | } | ||||
| 1654 | |||||
| 1655 | static bool hasRegisterDependency(MachineInstr *MI, | ||||
| 1656 | SmallVectorImpl<unsigned> &UsedOpsInCopy, | ||||
| 1657 | SmallVectorImpl<unsigned> &DefedRegsInCopy, | ||||
| 1658 | LiveRegUnits &ModifiedRegUnits, | ||||
| 1659 | LiveRegUnits &UsedRegUnits) { | ||||
| 1660 | bool HasRegDependency = false; | ||||
| 1661 | for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) { | ||||
| 1662 | MachineOperand &MO = MI->getOperand(i); | ||||
| 1663 | if (!MO.isReg()) | ||||
| 1664 | continue; | ||||
| 1665 | Register Reg = MO.getReg(); | ||||
| 1666 | if (!Reg) | ||||
| 1667 | continue; | ||||
| 1668 | if (MO.isDef()) { | ||||
| 1669 | if (!ModifiedRegUnits.available(Reg) || !UsedRegUnits.available(Reg)) { | ||||
| 1670 | HasRegDependency = true; | ||||
| 1671 | break; | ||||
| 1672 | } | ||||
| 1673 | DefedRegsInCopy.push_back(Reg); | ||||
| 1674 | |||||
| 1675 | // FIXME: instead of isUse(), readsReg() would be a better fix here, | ||||
| 1676 | // For example, we can ignore modifications in reg with undef. However, | ||||
| 1677 | // it's not perfectly clear if skipping the internal read is safe in all | ||||
| 1678 | // other targets. | ||||
| 1679 | } else if (MO.isUse()) { | ||||
| 1680 | if (!ModifiedRegUnits.available(Reg)) { | ||||
| 1681 | HasRegDependency = true; | ||||
| 1682 | break; | ||||
| 1683 | } | ||||
| 1684 | UsedOpsInCopy.push_back(i); | ||||
| 1685 | } | ||||
| 1686 | } | ||||
| 1687 | return HasRegDependency; | ||||
| 1688 | } | ||||
| 1689 | |||||
| 1690 | static SmallSet<MCRegister, 4> getRegUnits(MCRegister Reg, | ||||
| 1691 | const TargetRegisterInfo *TRI) { | ||||
| 1692 | SmallSet<MCRegister, 4> RegUnits; | ||||
| 1693 | for (auto RI = MCRegUnitIterator(Reg, TRI); RI.isValid(); ++RI) | ||||
| 1694 | RegUnits.insert(*RI); | ||||
| 1695 | return RegUnits; | ||||
| 1696 | } | ||||
| 1697 | |||||
| 1698 | bool PostRAMachineSinking::tryToSinkCopy(MachineBasicBlock &CurBB, | ||||
| 1699 | MachineFunction &MF, | ||||
| 1700 | const TargetRegisterInfo *TRI, | ||||
| 1701 | const TargetInstrInfo *TII) { | ||||
| 1702 | SmallPtrSet<MachineBasicBlock *, 2> SinkableBBs; | ||||
| 1703 | // FIXME: For now, we sink only to a successor which has a single predecessor | ||||
| 1704 | // so that we can directly sink COPY instructions to the successor without | ||||
| 1705 | // adding any new block or branch instruction. | ||||
| 1706 | for (MachineBasicBlock *SI : CurBB.successors()) | ||||
| 1707 | if (!SI->livein_empty() && SI->pred_size() == 1) | ||||
| 1708 | SinkableBBs.insert(SI); | ||||
| 1709 | |||||
| 1710 | if (SinkableBBs.empty()) | ||||
| 1711 | return false; | ||||
| 1712 | |||||
| 1713 | bool Changed = false; | ||||
| 1714 | |||||
| 1715 | // Track which registers have been modified and used between the end of the | ||||
| 1716 | // block and the current instruction. | ||||
| 1717 | ModifiedRegUnits.clear(); | ||||
| 1718 | UsedRegUnits.clear(); | ||||
| 1719 | SeenDbgInstrs.clear(); | ||||
| 1720 | |||||
| 1721 | for (auto I = CurBB.rbegin(), E = CurBB.rend(); I != E;) { | ||||
| 1722 | MachineInstr *MI = &*I; | ||||
| 1723 | ++I; | ||||
| 1724 | |||||
| 1725 | // Track the operand index for use in Copy. | ||||
| 1726 | SmallVector<unsigned, 2> UsedOpsInCopy; | ||||
| 1727 | // Track the register number defed in Copy. | ||||
| 1728 | SmallVector<unsigned, 2> DefedRegsInCopy; | ||||
| 1729 | |||||
| 1730 | // We must sink this DBG_VALUE if its operand is sunk. To avoid searching | ||||
| 1731 | // for DBG_VALUEs later, record them when they're encountered. | ||||
| 1732 | if (MI->isDebugValue()) { | ||||
| 1733 | SmallDenseMap<MCRegister, SmallVector<unsigned, 2>, 4> MIUnits; | ||||
| 1734 | bool IsValid = true; | ||||
| 1735 | for (MachineOperand &MO : MI->debug_operands()) { | ||||
| 1736 | if (MO.isReg() && Register::isPhysicalRegister(MO.getReg())) { | ||||
| 1737 | // Bail if we can already tell the sink would be rejected, rather | ||||
| 1738 | // than needlessly accumulating lots of DBG_VALUEs. | ||||
| 1739 | if (hasRegisterDependency(MI, UsedOpsInCopy, DefedRegsInCopy, | ||||
| 1740 | ModifiedRegUnits, UsedRegUnits)) { | ||||
| 1741 | IsValid = false; | ||||
| 1742 | break; | ||||
| 1743 | } | ||||
| 1744 | |||||
| 1745 | // Record debug use of each reg unit. | ||||
| 1746 | SmallSet<MCRegister, 4> RegUnits = getRegUnits(MO.getReg(), TRI); | ||||
| 1747 | for (MCRegister Reg : RegUnits) | ||||
| 1748 | MIUnits[Reg].push_back(MO.getReg()); | ||||
| 1749 | } | ||||
| 1750 | } | ||||
| 1751 | if (IsValid) { | ||||
| 1752 | for (auto RegOps : MIUnits) | ||||
| 1753 | SeenDbgInstrs[RegOps.first].push_back({MI, RegOps.second}); | ||||
| 1754 | } | ||||
| 1755 | continue; | ||||
| 1756 | } | ||||
| 1757 | |||||
| 1758 | if (MI->isDebugOrPseudoInstr()) | ||||
| 1759 | continue; | ||||
| 1760 | |||||
| 1761 | // Do not move any instruction across function call. | ||||
| 1762 | if (MI->isCall()) | ||||
| 1763 | return false; | ||||
| 1764 | |||||
| 1765 | if (!MI->isCopy() || !MI->getOperand(0).isRenamable()) { | ||||
| 1766 | LiveRegUnits::accumulateUsedDefed(*MI, ModifiedRegUnits, UsedRegUnits, | ||||
| 1767 | TRI); | ||||
| 1768 | continue; | ||||
| 1769 | } | ||||
| 1770 | |||||
| 1771 | // Don't sink the COPY if it would violate a register dependency. | ||||
| 1772 | if (hasRegisterDependency(MI, UsedOpsInCopy, DefedRegsInCopy, | ||||
| 1773 | ModifiedRegUnits, UsedRegUnits)) { | ||||
| 1774 | LiveRegUnits::accumulateUsedDefed(*MI, ModifiedRegUnits, UsedRegUnits, | ||||
| 1775 | TRI); | ||||
| 1776 | continue; | ||||
| 1777 | } | ||||
| 1778 | assert((!UsedOpsInCopy.empty() && !DefedRegsInCopy.empty()) &&((void)0) | ||||
| 1779 | "Unexpect SrcReg or DefReg")((void)0); | ||||
| 1780 | MachineBasicBlock *SuccBB = | ||||
| 1781 | getSingleLiveInSuccBB(CurBB, SinkableBBs, DefedRegsInCopy, TRI); | ||||
| 1782 | // Don't sink if we cannot find a single sinkable successor in which Reg | ||||
| 1783 | // is live-in. | ||||
| 1784 | if (!SuccBB
| ||||
| 1785 | LiveRegUnits::accumulateUsedDefed(*MI, ModifiedRegUnits, UsedRegUnits, | ||||
| 1786 | TRI); | ||||
| 1787 | continue; | ||||
| 1788 | } | ||||
| 1789 | assert((SuccBB->pred_size() == 1 && *SuccBB->pred_begin() == &CurBB) &&((void)0) | ||||
| 1790 | "Unexpected predecessor")((void)0); | ||||
| 1791 | |||||
| 1792 | // Collect DBG_VALUEs that must sink with this copy. We've previously | ||||
| 1793 | // recorded which reg units that DBG_VALUEs read, if this instruction | ||||
| 1794 | // writes any of those units then the corresponding DBG_VALUEs must sink. | ||||
| 1795 | MapVector<MachineInstr *, MIRegs::second_type> DbgValsToSinkMap; | ||||
| 1796 | for (auto &MO : MI->operands()) { | ||||
| 1797 | if (!MO.isReg() || !MO.isDef()) | ||||
| 1798 | continue; | ||||
| 1799 | |||||
| 1800 | SmallSet<MCRegister, 4> Units = getRegUnits(MO.getReg(), TRI); | ||||
| 1801 | for (MCRegister Reg : Units) { | ||||
| 1802 | for (auto MIRegs : SeenDbgInstrs.lookup(Reg)) { | ||||
| 1803 | auto &Regs = DbgValsToSinkMap[MIRegs.first]; | ||||
| 1804 | for (unsigned Reg : MIRegs.second) | ||||
| 1805 | Regs.push_back(Reg); | ||||
| 1806 | } | ||||
| 1807 | } | ||||
| 1808 | } | ||||
| 1809 | SmallVector<MIRegs, 4> DbgValsToSink(DbgValsToSinkMap.begin(), | ||||
| 1810 | DbgValsToSinkMap.end()); | ||||
| 1811 | |||||
| 1812 | // Clear the kill flag if SrcReg is killed between MI and the end of the | ||||
| 1813 | // block. | ||||
| 1814 | clearKillFlags(MI, CurBB, UsedOpsInCopy, UsedRegUnits, TRI); | ||||
| 1815 | MachineBasicBlock::iterator InsertPos = SuccBB->getFirstNonPHI(); | ||||
| 1816 | performSink(*MI, *SuccBB, InsertPos, DbgValsToSink); | ||||
| 1817 | updateLiveIn(MI, SuccBB, UsedOpsInCopy, DefedRegsInCopy); | ||||
| 1818 | |||||
| 1819 | Changed = true; | ||||
| 1820 | ++NumPostRACopySink; | ||||
| 1821 | } | ||||
| 1822 | return Changed; | ||||
| 1823 | } | ||||
| 1824 | |||||
| 1825 | bool PostRAMachineSinking::runOnMachineFunction(MachineFunction &MF) { | ||||
| 1826 | if (skipFunction(MF.getFunction())) | ||||
| |||||
| 1827 | return false; | ||||
| 1828 | |||||
| 1829 | bool Changed = false; | ||||
| 1830 | const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo(); | ||||
| 1831 | const TargetInstrInfo *TII = MF.getSubtarget().getInstrInfo(); | ||||
| 1832 | |||||
| 1833 | ModifiedRegUnits.init(*TRI); | ||||
| 1834 | UsedRegUnits.init(*TRI); | ||||
| 1835 | for (auto &BB : MF) | ||||
| 1836 | Changed |= tryToSinkCopy(BB, MF, TRI, TII); | ||||
| 1837 | |||||
| 1838 | return Changed; | ||||
| 1839 | } |
| 1 | //===- MC/MCRegisterInfo.h - Target Register Description --------*- C++ -*-===// | |||
| 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 file describes an abstract interface used to get information about a | |||
| 10 | // target machines register file. This information is used for a variety of | |||
| 11 | // purposed, especially register allocation. | |||
| 12 | // | |||
| 13 | //===----------------------------------------------------------------------===// | |||
| 14 | ||||
| 15 | #ifndef LLVM_MC_MCREGISTERINFO_H | |||
| 16 | #define LLVM_MC_MCREGISTERINFO_H | |||
| 17 | ||||
| 18 | #include "llvm/ADT/DenseMap.h" | |||
| 19 | #include "llvm/ADT/iterator.h" | |||
| 20 | #include "llvm/ADT/iterator_range.h" | |||
| 21 | #include "llvm/MC/LaneBitmask.h" | |||
| 22 | #include "llvm/MC/MCRegister.h" | |||
| 23 | #include <cassert> | |||
| 24 | #include <cstdint> | |||
| 25 | #include <iterator> | |||
| 26 | #include <utility> | |||
| 27 | ||||
| 28 | namespace llvm { | |||
| 29 | ||||
| 30 | /// MCRegisterClass - Base class of TargetRegisterClass. | |||
| 31 | class MCRegisterClass { | |||
| 32 | public: | |||
| 33 | using iterator = const MCPhysReg*; | |||
| 34 | using const_iterator = const MCPhysReg*; | |||
| 35 | ||||
| 36 | const iterator RegsBegin; | |||
| 37 | const uint8_t *const RegSet; | |||
| 38 | const uint32_t NameIdx; | |||
| 39 | const uint16_t RegsSize; | |||
| 40 | const uint16_t RegSetSize; | |||
| 41 | const uint16_t ID; | |||
| 42 | const uint16_t RegSizeInBits; | |||
| 43 | const int8_t CopyCost; | |||
| 44 | const bool Allocatable; | |||
| 45 | ||||
| 46 | /// getID() - Return the register class ID number. | |||
| 47 | /// | |||
| 48 | unsigned getID() const { return ID; } | |||
| 49 | ||||
| 50 | /// begin/end - Return all of the registers in this class. | |||
| 51 | /// | |||
| 52 | iterator begin() const { return RegsBegin; } | |||
| 53 | iterator end() const { return RegsBegin + RegsSize; } | |||
| 54 | ||||
| 55 | /// getNumRegs - Return the number of registers in this class. | |||
| 56 | /// | |||
| 57 | unsigned getNumRegs() const { return RegsSize; } | |||
| 58 | ||||
| 59 | /// getRegister - Return the specified register in the class. | |||
| 60 | /// | |||
| 61 | unsigned getRegister(unsigned i) const { | |||
| 62 | assert(i < getNumRegs() && "Register number out of range!")((void)0); | |||
| 63 | return RegsBegin[i]; | |||
| 64 | } | |||
| 65 | ||||
| 66 | /// contains - Return true if the specified register is included in this | |||
| 67 | /// register class. This does not include virtual registers. | |||
| 68 | bool contains(MCRegister Reg) const { | |||
| 69 | unsigned RegNo = unsigned(Reg); | |||
| 70 | unsigned InByte = RegNo % 8; | |||
| 71 | unsigned Byte = RegNo / 8; | |||
| 72 | if (Byte >= RegSetSize) | |||
| 73 | return false; | |||
| 74 | return (RegSet[Byte] & (1 << InByte)) != 0; | |||
| 75 | } | |||
| 76 | ||||
| 77 | /// contains - Return true if both registers are in this class. | |||
| 78 | bool contains(MCRegister Reg1, MCRegister Reg2) const { | |||
| 79 | return contains(Reg1) && contains(Reg2); | |||
| 80 | } | |||
| 81 | ||||
| 82 | /// Return the size of the physical register in bits if we are able to | |||
| 83 | /// determine it. This always returns zero for registers of targets that use | |||
| 84 | /// HW modes, as we need more information to determine the size of registers | |||
| 85 | /// in such cases. Use TargetRegisterInfo to cover them. | |||
| 86 | unsigned getSizeInBits() const { return RegSizeInBits; } | |||
| 87 | ||||
| 88 | /// getCopyCost - Return the cost of copying a value between two registers in | |||
| 89 | /// this class. A negative number means the register class is very expensive | |||
| 90 | /// to copy e.g. status flag register classes. | |||
| 91 | int getCopyCost() const { return CopyCost; } | |||
| 92 | ||||
| 93 | /// isAllocatable - Return true if this register class may be used to create | |||
| 94 | /// virtual registers. | |||
| 95 | bool isAllocatable() const { return Allocatable; } | |||
| 96 | }; | |||
| 97 | ||||
| 98 | /// MCRegisterDesc - This record contains information about a particular | |||
| 99 | /// register. The SubRegs field is a zero terminated array of registers that | |||
| 100 | /// are sub-registers of the specific register, e.g. AL, AH are sub-registers | |||
| 101 | /// of AX. The SuperRegs field is a zero terminated array of registers that are | |||
| 102 | /// super-registers of the specific register, e.g. RAX, EAX, are | |||
| 103 | /// super-registers of AX. | |||
| 104 | /// | |||
| 105 | struct MCRegisterDesc { | |||
| 106 | uint32_t Name; // Printable name for the reg (for debugging) | |||
| 107 | uint32_t SubRegs; // Sub-register set, described above | |||
| 108 | uint32_t SuperRegs; // Super-register set, described above | |||
| 109 | ||||
| 110 | // Offset into MCRI::SubRegIndices of a list of sub-register indices for each | |||
| 111 | // sub-register in SubRegs. | |||
| 112 | uint32_t SubRegIndices; | |||
| 113 | ||||
| 114 | // RegUnits - Points to the list of register units. The low 4 bits holds the | |||
| 115 | // Scale, the high bits hold an offset into DiffLists. See MCRegUnitIterator. | |||
| 116 | uint32_t RegUnits; | |||
| 117 | ||||
| 118 | /// Index into list with lane mask sequences. The sequence contains a lanemask | |||
| 119 | /// for every register unit. | |||
| 120 | uint16_t RegUnitLaneMasks; | |||
| 121 | }; | |||
| 122 | ||||
| 123 | /// MCRegisterInfo base class - We assume that the target defines a static | |||
| 124 | /// array of MCRegisterDesc objects that represent all of the machine | |||
| 125 | /// registers that the target has. As such, we simply have to track a pointer | |||
| 126 | /// to this array so that we can turn register number into a register | |||
| 127 | /// descriptor. | |||
| 128 | /// | |||
| 129 | /// Note this class is designed to be a base class of TargetRegisterInfo, which | |||
| 130 | /// is the interface used by codegen. However, specific targets *should never* | |||
| 131 | /// specialize this class. MCRegisterInfo should only contain getters to access | |||
| 132 | /// TableGen generated physical register data. It must not be extended with | |||
| 133 | /// virtual methods. | |||
| 134 | /// | |||
| 135 | class MCRegisterInfo { | |||
| 136 | public: | |||
| 137 | using regclass_iterator = const MCRegisterClass *; | |||
| 138 | ||||
| 139 | /// DwarfLLVMRegPair - Emitted by tablegen so Dwarf<->LLVM reg mappings can be | |||
| 140 | /// performed with a binary search. | |||
| 141 | struct DwarfLLVMRegPair { | |||
| 142 | unsigned FromReg; | |||
| 143 | unsigned ToReg; | |||
| 144 | ||||
| 145 | bool operator<(DwarfLLVMRegPair RHS) const { return FromReg < RHS.FromReg; } | |||
| 146 | }; | |||
| 147 | ||||
| 148 | /// SubRegCoveredBits - Emitted by tablegen: bit range covered by a subreg | |||
| 149 | /// index, -1 in any being invalid. | |||
| 150 | struct SubRegCoveredBits { | |||
| 151 | uint16_t Offset; | |||
| 152 | uint16_t Size; | |||
| 153 | }; | |||
| 154 | ||||
| 155 | private: | |||
| 156 | const MCRegisterDesc *Desc; // Pointer to the descriptor array | |||
| 157 | unsigned NumRegs; // Number of entries in the array | |||
| 158 | MCRegister RAReg; // Return address register | |||
| 159 | MCRegister PCReg; // Program counter register | |||
| 160 | const MCRegisterClass *Classes; // Pointer to the regclass array | |||
| 161 | unsigned NumClasses; // Number of entries in the array | |||
| 162 | unsigned NumRegUnits; // Number of regunits. | |||
| 163 | const MCPhysReg (*RegUnitRoots)[2]; // Pointer to regunit root table. | |||
| 164 | const MCPhysReg *DiffLists; // Pointer to the difflists array | |||
| 165 | const LaneBitmask *RegUnitMaskSequences; // Pointer to lane mask sequences | |||
| 166 | // for register units. | |||
| 167 | const char *RegStrings; // Pointer to the string table. | |||
| 168 | const char *RegClassStrings; // Pointer to the class strings. | |||
| 169 | const uint16_t *SubRegIndices; // Pointer to the subreg lookup | |||
| 170 | // array. | |||
| 171 | const SubRegCoveredBits *SubRegIdxRanges; // Pointer to the subreg covered | |||
| 172 | // bit ranges array. | |||
| 173 | unsigned NumSubRegIndices; // Number of subreg indices. | |||
| 174 | const uint16_t *RegEncodingTable; // Pointer to array of register | |||
| 175 | // encodings. | |||
| 176 | ||||
| 177 | unsigned L2DwarfRegsSize; | |||
| 178 | unsigned EHL2DwarfRegsSize; | |||
| 179 | unsigned Dwarf2LRegsSize; | |||
| 180 | unsigned EHDwarf2LRegsSize; | |||
| 181 | const DwarfLLVMRegPair *L2DwarfRegs; // LLVM to Dwarf regs mapping | |||
| 182 | const DwarfLLVMRegPair *EHL2DwarfRegs; // LLVM to Dwarf regs mapping EH | |||
| 183 | const DwarfLLVMRegPair *Dwarf2LRegs; // Dwarf to LLVM regs mapping | |||
| 184 | const DwarfLLVMRegPair *EHDwarf2LRegs; // Dwarf to LLVM regs mapping EH | |||
| 185 | DenseMap<MCRegister, int> L2SEHRegs; // LLVM to SEH regs mapping | |||
| 186 | DenseMap<MCRegister, int> L2CVRegs; // LLVM to CV regs mapping | |||
| 187 | ||||
| 188 | public: | |||
| 189 | // Forward declaration to become a friend class of DiffListIterator. | |||
| 190 | template <class SubT> class mc_difflist_iterator; | |||
| 191 | ||||
| 192 | /// DiffListIterator - Base iterator class that can traverse the | |||
| 193 | /// differentially encoded register and regunit lists in DiffLists. | |||
| 194 | /// Don't use this class directly, use one of the specialized sub-classes | |||
| 195 | /// defined below. | |||
| 196 | class DiffListIterator { | |||
| 197 | uint16_t Val = 0; | |||
| 198 | const MCPhysReg *List = nullptr; | |||
| 199 | ||||
| 200 | protected: | |||
| 201 | /// Create an invalid iterator. Call init() to point to something useful. | |||
| 202 | DiffListIterator() = default; | |||
| 203 | ||||
| 204 | /// init - Point the iterator to InitVal, decoding subsequent values from | |||
| 205 | /// DiffList. The iterator will initially point to InitVal, sub-classes are | |||
| 206 | /// responsible for skipping the seed value if it is not part of the list. | |||
| 207 | void init(MCPhysReg InitVal, const MCPhysReg *DiffList) { | |||
| 208 | Val = InitVal; | |||
| 209 | List = DiffList; | |||
| 210 | } | |||
| 211 | ||||
| 212 | /// advance - Move to the next list position, return the applied | |||
| 213 | /// differential. This function does not detect the end of the list, that | |||
| 214 | /// is the caller's responsibility (by checking for a 0 return value). | |||
| 215 | MCRegister advance() { | |||
| 216 | assert(isValid() && "Cannot move off the end of the list.")((void)0); | |||
| 217 | MCPhysReg D = *List++; | |||
| ||||
| 218 | Val += D; | |||
| 219 | return D; | |||
| 220 | } | |||
| 221 | ||||
| 222 | public: | |||
| 223 | /// isValid - returns true if this iterator is not yet at the end. | |||
| 224 | bool isValid() const { return List; } | |||
| 225 | ||||
| 226 | /// Dereference the iterator to get the value at the current position. | |||
| 227 | MCRegister operator*() const { return Val; } | |||
| 228 | ||||
| 229 | /// Pre-increment to move to the next position. | |||
| 230 | void operator++() { | |||
| 231 | // The end of the list is encoded as a 0 differential. | |||
| 232 | if (!advance()) | |||
| 233 | List = nullptr; | |||
| 234 | } | |||
| 235 | ||||
| 236 | template <class SubT> friend class MCRegisterInfo::mc_difflist_iterator; | |||
| 237 | }; | |||
| 238 | ||||
| 239 | /// Forward iterator using DiffListIterator. | |||
| 240 | template <class SubT> | |||
| 241 | class mc_difflist_iterator | |||
| 242 | : public iterator_facade_base<mc_difflist_iterator<SubT>, | |||
| 243 | std::forward_iterator_tag, MCPhysReg> { | |||
| 244 | MCRegisterInfo::DiffListIterator Iter; | |||
| 245 | /// Current value as MCPhysReg, so we can return a reference to it. | |||
| 246 | MCPhysReg Val; | |||
| 247 | ||||
| 248 | protected: | |||
| 249 | mc_difflist_iterator(MCRegisterInfo::DiffListIterator Iter) : Iter(Iter) {} | |||
| 250 | ||||
| 251 | // Allow conversion between instantiations where valid. | |||
| 252 | mc_difflist_iterator(MCRegister Reg, const MCPhysReg *DiffList) { | |||
| 253 | Iter.init(Reg, DiffList); | |||
| 254 | Val = *Iter; | |||
| 255 | } | |||
| 256 | ||||
| 257 | public: | |||
| 258 | // Allow default construction to build variables, but this doesn't build | |||
| 259 | // a useful iterator. | |||
| 260 | mc_difflist_iterator() = default; | |||
| 261 | ||||
| 262 | /// Return an iterator past the last element. | |||
| 263 | static SubT end() { | |||
| 264 | SubT End; | |||
| 265 | End.Iter.List = nullptr; | |||
| 266 | return End; | |||
| 267 | } | |||
| 268 | ||||
| 269 | bool operator==(const mc_difflist_iterator &Arg) const { | |||
| 270 | return Iter.List == Arg.Iter.List; | |||
| 271 | } | |||
| 272 | ||||
| 273 | const MCPhysReg &operator*() const { return Val; } | |||
| 274 | ||||
| 275 | using mc_difflist_iterator::iterator_facade_base::operator++; | |||
| 276 | void operator++() { | |||
| 277 | assert(Iter.List && "Cannot increment the end iterator!")((void)0); | |||
| 278 | ++Iter; | |||
| 279 | Val = *Iter; | |||
| 280 | } | |||
| 281 | }; | |||
| 282 | ||||
| 283 | /// Forward iterator over all sub-registers. | |||
| 284 | /// TODO: Replace remaining uses of MCSubRegIterator. | |||
| 285 | class mc_subreg_iterator : public mc_difflist_iterator<mc_subreg_iterator> { | |||
| 286 | public: | |||
| 287 | mc_subreg_iterator(MCRegisterInfo::DiffListIterator Iter) | |||
| 288 | : mc_difflist_iterator(Iter) {} | |||
| 289 | mc_subreg_iterator() = default; | |||
| 290 | mc_subreg_iterator(MCRegister Reg, const MCRegisterInfo *MCRI) | |||
| 291 | : mc_difflist_iterator(Reg, MCRI->DiffLists + MCRI->get(Reg).SubRegs) {} | |||
| 292 | }; | |||
| 293 | ||||
| 294 | /// Forward iterator over all super-registers. | |||
| 295 | /// TODO: Replace remaining uses of MCSuperRegIterator. | |||
| 296 | class mc_superreg_iterator | |||
| 297 | : public mc_difflist_iterator<mc_superreg_iterator> { | |||
| 298 | public: | |||
| 299 | mc_superreg_iterator(MCRegisterInfo::DiffListIterator Iter) | |||
| 300 | : mc_difflist_iterator(Iter) {} | |||
| 301 | mc_superreg_iterator() = default; | |||
| 302 | mc_superreg_iterator(MCRegister Reg, const MCRegisterInfo *MCRI) | |||
| 303 | : mc_difflist_iterator(Reg, | |||
| 304 | MCRI->DiffLists + MCRI->get(Reg).SuperRegs) {} | |||
| 305 | }; | |||
| 306 | ||||
| 307 | /// Return an iterator range over all sub-registers of \p Reg, excluding \p | |||
| 308 | /// Reg. | |||
| 309 | iterator_range<mc_subreg_iterator> subregs(MCRegister Reg) const { | |||
| 310 | return make_range(std::next(mc_subreg_iterator(Reg, this)), | |||
| 311 | mc_subreg_iterator::end()); | |||
| 312 | } | |||
| 313 | ||||
| 314 | /// Return an iterator range over all sub-registers of \p Reg, including \p | |||
| 315 | /// Reg. | |||
| 316 | iterator_range<mc_subreg_iterator> subregs_inclusive(MCRegister Reg) const { | |||
| 317 | return make_range({Reg, this}, mc_subreg_iterator::end()); | |||
| 318 | } | |||
| 319 | ||||
| 320 | /// Return an iterator range over all super-registers of \p Reg, excluding \p | |||
| 321 | /// Reg. | |||
| 322 | iterator_range<mc_superreg_iterator> superregs(MCRegister Reg) const { | |||
| 323 | return make_range(std::next(mc_superreg_iterator(Reg, this)), | |||
| 324 | mc_superreg_iterator::end()); | |||
| 325 | } | |||
| 326 | ||||
| 327 | /// Return an iterator range over all super-registers of \p Reg, including \p | |||
| 328 | /// Reg. | |||
| 329 | iterator_range<mc_superreg_iterator> | |||
| 330 | superregs_inclusive(MCRegister Reg) const { | |||
| 331 | return make_range({Reg, this}, mc_superreg_iterator::end()); | |||
| 332 | } | |||
| 333 | ||||
| 334 | /// Return an iterator range over all sub- and super-registers of \p Reg, | |||
| 335 | /// including \p Reg. | |||
| 336 | detail::concat_range<const MCPhysReg, iterator_range<mc_subreg_iterator>, | |||
| 337 | iterator_range<mc_superreg_iterator>> | |||
| 338 | sub_and_superregs_inclusive(MCRegister Reg) const { | |||
| 339 | return concat<const MCPhysReg>(subregs_inclusive(Reg), superregs(Reg)); | |||
| 340 | } | |||
| 341 | ||||
| 342 | // These iterators are allowed to sub-class DiffListIterator and access | |||
| 343 | // internal list pointers. | |||
| 344 | friend class MCSubRegIterator; | |||
| 345 | friend class MCSubRegIndexIterator; | |||
| 346 | friend class MCSuperRegIterator; | |||
| 347 | friend class MCRegUnitIterator; | |||
| 348 | friend class MCRegUnitMaskIterator; | |||
| 349 | friend class MCRegUnitRootIterator; | |||
| 350 | ||||
| 351 | /// Initialize MCRegisterInfo, called by TableGen | |||
| 352 | /// auto-generated routines. *DO NOT USE*. | |||
| 353 | void InitMCRegisterInfo(const MCRegisterDesc *D, unsigned NR, unsigned RA, | |||
| 354 | unsigned PC, | |||
| 355 | const MCRegisterClass *C, unsigned NC, | |||
| 356 | const MCPhysReg (*RURoots)[2], | |||
| 357 | unsigned NRU, | |||
| 358 | const MCPhysReg *DL, | |||
| 359 | const LaneBitmask *RUMS, | |||
| 360 | const char *Strings, | |||
| 361 | const char *ClassStrings, | |||
| 362 | const uint16_t *SubIndices, | |||
| 363 | unsigned NumIndices, | |||
| 364 | const SubRegCoveredBits *SubIdxRanges, | |||
| 365 | const uint16_t *RET) { | |||
| 366 | Desc = D; | |||
| 367 | NumRegs = NR; | |||
| 368 | RAReg = RA; | |||
| 369 | PCReg = PC; | |||
| 370 | Classes = C; | |||
| 371 | DiffLists = DL; | |||
| 372 | RegUnitMaskSequences = RUMS; | |||
| 373 | RegStrings = Strings; | |||
| 374 | RegClassStrings = ClassStrings; | |||
| 375 | NumClasses = NC; | |||
| 376 | RegUnitRoots = RURoots; | |||
| 377 | NumRegUnits = NRU; | |||
| 378 | SubRegIndices = SubIndices; | |||
| 379 | NumSubRegIndices = NumIndices; | |||
| 380 | SubRegIdxRanges = SubIdxRanges; | |||
| 381 | RegEncodingTable = RET; | |||
| 382 | ||||
| 383 | // Initialize DWARF register mapping variables | |||
| 384 | EHL2DwarfRegs = nullptr; | |||
| 385 | EHL2DwarfRegsSize = 0; | |||
| 386 | L2DwarfRegs = nullptr; | |||
| 387 | L2DwarfRegsSize = 0; | |||
| 388 | EHDwarf2LRegs = nullptr; | |||
| 389 | EHDwarf2LRegsSize = 0; | |||
| 390 | Dwarf2LRegs = nullptr; | |||
| 391 | Dwarf2LRegsSize = 0; | |||
| 392 | } | |||
| 393 | ||||
| 394 | /// Used to initialize LLVM register to Dwarf | |||
| 395 | /// register number mapping. Called by TableGen auto-generated routines. | |||
| 396 | /// *DO NOT USE*. | |||
| 397 | void mapLLVMRegsToDwarfRegs(const DwarfLLVMRegPair *Map, unsigned Size, | |||
| 398 | bool isEH) { | |||
| 399 | if (isEH) { | |||
| 400 | EHL2DwarfRegs = Map; | |||
| 401 | EHL2DwarfRegsSize = Size; | |||
| 402 | } else { | |||
| 403 | L2DwarfRegs = Map; | |||
| 404 | L2DwarfRegsSize = Size; | |||
| 405 | } | |||
| 406 | } | |||
| 407 | ||||
| 408 | /// Used to initialize Dwarf register to LLVM | |||
| 409 | /// register number mapping. Called by TableGen auto-generated routines. | |||
| 410 | /// *DO NOT USE*. | |||
| 411 | void mapDwarfRegsToLLVMRegs(const DwarfLLVMRegPair *Map, unsigned Size, | |||
| 412 | bool isEH) { | |||
| 413 | if (isEH) { | |||
| 414 | EHDwarf2LRegs = Map; | |||
| 415 | EHDwarf2LRegsSize = Size; | |||
| 416 | } else { | |||
| 417 | Dwarf2LRegs = Map; | |||
| 418 | Dwarf2LRegsSize = Size; | |||
| 419 | } | |||
| 420 | } | |||
| 421 | ||||
| 422 | /// mapLLVMRegToSEHReg - Used to initialize LLVM register to SEH register | |||
| 423 | /// number mapping. By default the SEH register number is just the same | |||
| 424 | /// as the LLVM register number. | |||
| 425 | /// FIXME: TableGen these numbers. Currently this requires target specific | |||
| 426 | /// initialization code. | |||
| 427 | void mapLLVMRegToSEHReg(MCRegister LLVMReg, int SEHReg) { | |||
| 428 | L2SEHRegs[LLVMReg] = SEHReg; | |||
| 429 | } | |||
| 430 | ||||
| 431 | void mapLLVMRegToCVReg(MCRegister LLVMReg, int CVReg) { | |||
| 432 | L2CVRegs[LLVMReg] = CVReg; | |||
| 433 | } | |||
| 434 | ||||
| 435 | /// This method should return the register where the return | |||
| 436 | /// address can be found. | |||
| 437 | MCRegister getRARegister() const { | |||
| 438 | return RAReg; | |||
| 439 | } | |||
| 440 | ||||
| 441 | /// Return the register which is the program counter. | |||
| 442 | MCRegister getProgramCounter() const { | |||
| 443 | return PCReg; | |||
| 444 | } | |||
| 445 | ||||
| 446 | const MCRegisterDesc &operator[](MCRegister RegNo) const { | |||
| 447 | assert(RegNo < NumRegs &&((void)0) | |||
| 448 | "Attempting to access record for invalid register number!")((void)0); | |||
| 449 | return Desc[RegNo]; | |||
| 450 | } | |||
| 451 | ||||
| 452 | /// Provide a get method, equivalent to [], but more useful with a | |||
| 453 | /// pointer to this object. | |||
| 454 | const MCRegisterDesc &get(MCRegister RegNo) const { | |||
| 455 | return operator[](RegNo); | |||
| 456 | } | |||
| 457 | ||||
| 458 | /// Returns the physical register number of sub-register "Index" | |||
| 459 | /// for physical register RegNo. Return zero if the sub-register does not | |||
| 460 | /// exist. | |||
| 461 | MCRegister getSubReg(MCRegister Reg, unsigned Idx) const; | |||
| 462 | ||||
| 463 | /// Return a super-register of the specified register | |||
| 464 | /// Reg so its sub-register of index SubIdx is Reg. | |||
| 465 | MCRegister getMatchingSuperReg(MCRegister Reg, unsigned SubIdx, | |||
| 466 | const MCRegisterClass *RC) const; | |||
| 467 | ||||
| 468 | /// For a given register pair, return the sub-register index | |||
| 469 | /// if the second register is a sub-register of the first. Return zero | |||
| 470 | /// otherwise. | |||
| 471 | unsigned getSubRegIndex(MCRegister RegNo, MCRegister SubRegNo) const; | |||
| 472 | ||||
| 473 | /// Get the size of the bit range covered by a sub-register index. | |||
| 474 | /// If the index isn't continuous, return the sum of the sizes of its parts. | |||
| 475 | /// If the index is used to access subregisters of different sizes, return -1. | |||
| 476 | unsigned getSubRegIdxSize(unsigned Idx) const; | |||
| 477 | ||||
| 478 | /// Get the offset of the bit range covered by a sub-register index. | |||
| 479 | /// If an Offset doesn't make sense (the index isn't continuous, or is used to | |||
| 480 | /// access sub-registers at different offsets), return -1. | |||
| 481 | unsigned getSubRegIdxOffset(unsigned Idx) const; | |||
| 482 | ||||
| 483 | /// Return the human-readable symbolic target-specific name for the | |||
| 484 | /// specified physical register. | |||
| 485 | const char *getName(MCRegister RegNo) const { | |||
| 486 | return RegStrings + get(RegNo).Name; | |||
| 487 | } | |||
| 488 | ||||
| 489 | /// Return the number of registers this target has (useful for | |||
| 490 | /// sizing arrays holding per register information) | |||
| 491 | unsigned getNumRegs() const { | |||
| 492 | return NumRegs; | |||
| 493 | } | |||
| 494 | ||||
| 495 | /// Return the number of sub-register indices | |||
| 496 | /// understood by the target. Index 0 is reserved for the no-op sub-register, | |||
| 497 | /// while 1 to getNumSubRegIndices() - 1 represent real sub-registers. | |||
| 498 | unsigned getNumSubRegIndices() const { | |||
| 499 | return NumSubRegIndices; | |||
| 500 | } | |||
| 501 | ||||
| 502 | /// Return the number of (native) register units in the | |||
| 503 | /// target. Register units are numbered from 0 to getNumRegUnits() - 1. They | |||
| 504 | /// can be accessed through MCRegUnitIterator defined below. | |||
| 505 | unsigned getNumRegUnits() const { | |||
| 506 | return NumRegUnits; | |||
| 507 | } | |||
| 508 | ||||
| 509 | /// Map a target register to an equivalent dwarf register | |||
| 510 | /// number. Returns -1 if there is no equivalent value. The second | |||
| 511 | /// parameter allows targets to use different numberings for EH info and | |||
| 512 | /// debugging info. | |||
| 513 | int getDwarfRegNum(MCRegister RegNum, bool isEH) const; | |||
| 514 | ||||
| 515 | /// Map a dwarf register back to a target register. Returns None is there is | |||
| 516 | /// no mapping. | |||
| 517 | Optional<unsigned> getLLVMRegNum(unsigned RegNum, bool isEH) const; | |||
| 518 | ||||
| 519 | /// Map a target EH register number to an equivalent DWARF register | |||
| 520 | /// number. | |||
| 521 | int getDwarfRegNumFromDwarfEHRegNum(unsigned RegNum) const; | |||
| 522 | ||||
| 523 | /// Map a target register to an equivalent SEH register | |||
| 524 | /// number. Returns LLVM register number if there is no equivalent value. | |||
| 525 | int getSEHRegNum(MCRegister RegNum) const; | |||
| 526 | ||||
| 527 | /// Map a target register to an equivalent CodeView register | |||
| 528 | /// number. | |||
| 529 | int getCodeViewRegNum(MCRegister RegNum) const; | |||
| 530 | ||||
| 531 | regclass_iterator regclass_begin() const { return Classes; } | |||
| 532 | regclass_iterator regclass_end() const { return Classes+NumClasses; } | |||
| 533 | iterator_range<regclass_iterator> regclasses() const { | |||
| 534 | return make_range(regclass_begin(), regclass_end()); | |||
| 535 | } | |||
| 536 | ||||
| 537 | unsigned getNumRegClasses() const { | |||
| 538 | return (unsigned)(regclass_end()-regclass_begin()); | |||
| 539 | } | |||
| 540 | ||||
| 541 | /// Returns the register class associated with the enumeration | |||
| 542 | /// value. See class MCOperandInfo. | |||
| 543 | const MCRegisterClass& getRegClass(unsigned i) const { | |||
| 544 | assert(i < getNumRegClasses() && "Register Class ID out of range")((void)0); | |||
| 545 | return Classes[i]; | |||
| 546 | } | |||
| 547 | ||||
| 548 | const char *getRegClassName(const MCRegisterClass *Class) const { | |||
| 549 | return RegClassStrings + Class->NameIdx; | |||
| 550 | } | |||
| 551 | ||||
| 552 | /// Returns the encoding for RegNo | |||
| 553 | uint16_t getEncodingValue(MCRegister RegNo) const { | |||
| 554 | assert(RegNo < NumRegs &&((void)0) | |||
| 555 | "Attempting to get encoding for invalid register number!")((void)0); | |||
| 556 | return RegEncodingTable[RegNo]; | |||
| 557 | } | |||
| 558 | ||||
| 559 | /// Returns true if RegB is a sub-register of RegA. | |||
| 560 | bool isSubRegister(MCRegister RegA, MCRegister RegB) const { | |||
| 561 | return isSuperRegister(RegB, RegA); | |||
| 562 | } | |||
| 563 | ||||
| 564 | /// Returns true if RegB is a super-register of RegA. | |||
| 565 | bool isSuperRegister(MCRegister RegA, MCRegister RegB) const; | |||
| 566 | ||||
| 567 | /// Returns true if RegB is a sub-register of RegA or if RegB == RegA. | |||
| 568 | bool isSubRegisterEq(MCRegister RegA, MCRegister RegB) const { | |||
| 569 | return isSuperRegisterEq(RegB, RegA); | |||
| 570 | } | |||
| 571 | ||||
| 572 | /// Returns true if RegB is a super-register of RegA or if | |||
| 573 | /// RegB == RegA. | |||
| 574 | bool isSuperRegisterEq(MCRegister RegA, MCRegister RegB) const { | |||
| 575 | return RegA == RegB || isSuperRegister(RegA, RegB); | |||
| 576 | } | |||
| 577 | ||||
| 578 | /// Returns true if RegB is a super-register or sub-register of RegA | |||
| 579 | /// or if RegB == RegA. | |||
| 580 | bool isSuperOrSubRegisterEq(MCRegister RegA, MCRegister RegB) const { | |||
| 581 | return isSubRegisterEq(RegA, RegB) || isSuperRegister(RegA, RegB); | |||
| 582 | } | |||
| 583 | }; | |||
| 584 | ||||
| 585 | //===----------------------------------------------------------------------===// | |||
| 586 | // Register List Iterators | |||
| 587 | //===----------------------------------------------------------------------===// | |||
| 588 | ||||
| 589 | // MCRegisterInfo provides lists of super-registers, sub-registers, and | |||
| 590 | // aliasing registers. Use these iterator classes to traverse the lists. | |||
| 591 | ||||
| 592 | /// MCSubRegIterator enumerates all sub-registers of Reg. | |||
| 593 | /// If IncludeSelf is set, Reg itself is included in the list. | |||
| 594 | class MCSubRegIterator : public MCRegisterInfo::DiffListIterator { | |||
| 595 | public: | |||
| 596 | MCSubRegIterator(MCRegister Reg, const MCRegisterInfo *MCRI, | |||
| 597 | bool IncludeSelf = false) { | |||
| 598 | init(Reg, MCRI->DiffLists + MCRI->get(Reg).SubRegs); | |||
| 599 | // Initially, the iterator points to Reg itself. | |||
| 600 | if (!IncludeSelf) | |||
| 601 | ++*this; | |||
| 602 | } | |||
| 603 | }; | |||
| 604 | ||||
| 605 | /// Iterator that enumerates the sub-registers of a Reg and the associated | |||
| 606 | /// sub-register indices. | |||
| 607 | class MCSubRegIndexIterator { | |||
| 608 | MCSubRegIterator SRIter; | |||
| 609 | const uint16_t *SRIndex; | |||
| 610 | ||||
| 611 | public: | |||
| 612 | /// Constructs an iterator that traverses subregisters and their | |||
| 613 | /// associated subregister indices. | |||
| 614 | MCSubRegIndexIterator(MCRegister Reg, const MCRegisterInfo *MCRI) | |||
| 615 | : SRIter(Reg, MCRI) { | |||
| 616 | SRIndex = MCRI->SubRegIndices + MCRI->get(Reg).SubRegIndices; | |||
| 617 | } | |||
| 618 | ||||
| 619 | /// Returns current sub-register. | |||
| 620 | MCRegister getSubReg() const { | |||
| 621 | return *SRIter; | |||
| 622 | } | |||
| 623 | ||||
| 624 | /// Returns sub-register index of the current sub-register. | |||
| 625 | unsigned getSubRegIndex() const { | |||
| 626 | return *SRIndex; | |||
| 627 | } | |||
| 628 | ||||
| 629 | /// Returns true if this iterator is not yet at the end. | |||
| 630 | bool isValid() const { return SRIter.isValid(); } | |||
| 631 | ||||
| 632 | /// Moves to the next position. | |||
| 633 | void operator++() { | |||
| 634 | ++SRIter; | |||
| 635 | ++SRIndex; | |||
| 636 | } | |||
| 637 | }; | |||
| 638 | ||||
| 639 | /// MCSuperRegIterator enumerates all super-registers of Reg. | |||
| 640 | /// If IncludeSelf is set, Reg itself is included in the list. | |||
| 641 | class MCSuperRegIterator : public MCRegisterInfo::DiffListIterator { | |||
| 642 | public: | |||
| 643 | MCSuperRegIterator() = default; | |||
| 644 | ||||
| 645 | MCSuperRegIterator(MCRegister Reg, const MCRegisterInfo *MCRI, | |||
| 646 | bool IncludeSelf = false) { | |||
| 647 | init(Reg, MCRI->DiffLists + MCRI->get(Reg).SuperRegs); | |||
| 648 | // Initially, the iterator points to Reg itself. | |||
| 649 | if (!IncludeSelf) | |||
| 650 | ++*this; | |||
| 651 | } | |||
| 652 | }; | |||
| 653 | ||||
| 654 | // Definition for isSuperRegister. Put it down here since it needs the | |||
| 655 | // iterator defined above in addition to the MCRegisterInfo class itself. | |||
| 656 | inline bool MCRegisterInfo::isSuperRegister(MCRegister RegA, MCRegister RegB) const{ | |||
| 657 | for (MCSuperRegIterator I(RegA, this); I.isValid(); ++I) | |||
| 658 | if (*I == RegB) | |||
| 659 | return true; | |||
| 660 | return false; | |||
| 661 | } | |||
| 662 | ||||
| 663 | //===----------------------------------------------------------------------===// | |||
| 664 | // Register Units | |||
| 665 | //===----------------------------------------------------------------------===// | |||
| 666 | ||||
| 667 | // Register units are used to compute register aliasing. Every register has at | |||
| 668 | // least one register unit, but it can have more. Two registers overlap if and | |||
| 669 | // only if they have a common register unit. | |||
| 670 | // | |||
| 671 | // A target with a complicated sub-register structure will typically have many | |||
| 672 | // fewer register units than actual registers. MCRI::getNumRegUnits() returns | |||
| 673 | // the number of register units in the target. | |||
| 674 | ||||
| 675 | // MCRegUnitIterator enumerates a list of register units for Reg. The list is | |||
| 676 | // in ascending numerical order. | |||
| 677 | class MCRegUnitIterator : public MCRegisterInfo::DiffListIterator { | |||
| 678 | public: | |||
| 679 | /// MCRegUnitIterator - Create an iterator that traverses the register units | |||
| 680 | /// in Reg. | |||
| 681 | MCRegUnitIterator() = default; | |||
| 682 | ||||
| 683 | MCRegUnitIterator(MCRegister Reg, const MCRegisterInfo *MCRI) { | |||
| 684 | assert(Reg && "Null register has no regunits")((void)0); | |||
| 685 | assert(MCRegister::isPhysicalRegister(Reg.id()))((void)0); | |||
| 686 | // Decode the RegUnits MCRegisterDesc field. | |||
| 687 | unsigned RU = MCRI->get(Reg).RegUnits; | |||
| 688 | unsigned Scale = RU & 15; | |||
| 689 | unsigned Offset = RU >> 4; | |||
| 690 | ||||
| 691 | // Initialize the iterator to Reg * Scale, and the List pointer to | |||
| 692 | // DiffLists + Offset. | |||
| 693 | init(Reg * Scale, MCRI->DiffLists + Offset); | |||
| 694 | ||||
| 695 | // That may not be a valid unit, we need to advance by one to get the real | |||
| 696 | // unit number. The first differential can be 0 which would normally | |||
| 697 | // terminate the list, but since we know every register has at least one | |||
| 698 | // unit, we can allow a 0 differential here. | |||
| 699 | advance(); | |||
| 700 | } | |||
| 701 | }; | |||
| 702 | ||||
| 703 | /// MCRegUnitMaskIterator enumerates a list of register units and their | |||
| 704 | /// associated lane masks for Reg. The register units are in ascending | |||
| 705 | /// numerical order. | |||
| 706 | class MCRegUnitMaskIterator { | |||
| 707 | MCRegUnitIterator RUIter; | |||
| 708 | const LaneBitmask *MaskListIter; | |||
| 709 | ||||
| 710 | public: | |||
| 711 | MCRegUnitMaskIterator() = default; | |||
| 712 | ||||
| 713 | /// Constructs an iterator that traverses the register units and their | |||
| 714 | /// associated LaneMasks in Reg. | |||
| 715 | MCRegUnitMaskIterator(MCRegister Reg, const MCRegisterInfo *MCRI) | |||
| 716 | : RUIter(Reg, MCRI) { | |||
| 717 | uint16_t Idx = MCRI->get(Reg).RegUnitLaneMasks; | |||
| 718 | MaskListIter = &MCRI->RegUnitMaskSequences[Idx]; | |||
| 719 | } | |||
| 720 | ||||
| 721 | /// Returns a (RegUnit, LaneMask) pair. | |||
| 722 | std::pair<unsigned,LaneBitmask> operator*() const { | |||
| 723 | return std::make_pair(*RUIter, *MaskListIter); | |||
| 724 | } | |||
| 725 | ||||
| 726 | /// Returns true if this iterator is not yet at the end. | |||
| 727 | bool isValid() const { return RUIter.isValid(); } | |||
| 728 | ||||
| 729 | /// Moves to the next position. | |||
| 730 | void operator++() { | |||
| 731 | ++MaskListIter; | |||
| 732 | ++RUIter; | |||
| 733 | } | |||
| 734 | }; | |||
| 735 | ||||
| 736 | // Each register unit has one or two root registers. The complete set of | |||
| 737 | // registers containing a register unit is the union of the roots and their | |||
| 738 | // super-registers. All registers aliasing Unit can be visited like this: | |||
| 739 | // | |||
| 740 | // for (MCRegUnitRootIterator RI(Unit, MCRI); RI.isValid(); ++RI) { | |||
| 741 | // for (MCSuperRegIterator SI(*RI, MCRI, true); SI.isValid(); ++SI) | |||
| 742 | // visit(*SI); | |||
| 743 | // } | |||
| 744 | ||||
| 745 | /// MCRegUnitRootIterator enumerates the root registers of a register unit. | |||
| 746 | class MCRegUnitRootIterator { | |||
| 747 | uint16_t Reg0 = 0; | |||
| 748 | uint16_t Reg1 = 0; | |||
| 749 | ||||
| 750 | public: | |||
| 751 | MCRegUnitRootIterator() = default; | |||
| 752 | ||||
| 753 | MCRegUnitRootIterator(unsigned RegUnit, const MCRegisterInfo *MCRI) { | |||
| 754 | assert(RegUnit < MCRI->getNumRegUnits() && "Invalid register unit")((void)0); | |||
| 755 | Reg0 = MCRI->RegUnitRoots[RegUnit][0]; | |||
| 756 | Reg1 = MCRI->RegUnitRoots[RegUnit][1]; | |||
| 757 | } | |||
| 758 | ||||
| 759 | /// Dereference to get the current root register. | |||
| 760 | unsigned operator*() const { | |||
| 761 | return Reg0; | |||
| 762 | } | |||
| 763 | ||||
| 764 | /// Check if the iterator is at the end of the list. | |||
| 765 | bool isValid() const { | |||
| 766 | return Reg0; | |||
| 767 | } | |||
| 768 | ||||
| 769 | /// Preincrement to move to the next root register. | |||
| 770 | void operator++() { | |||
| 771 | assert(isValid() && "Cannot move off the end of the list.")((void)0); | |||
| 772 | Reg0 = Reg1; | |||
| 773 | Reg1 = 0; | |||
| 774 | } | |||
| 775 | }; | |||
| 776 | ||||
| 777 | /// MCRegAliasIterator enumerates all registers aliasing Reg. If IncludeSelf is | |||
| 778 | /// set, Reg itself is included in the list. This iterator does not guarantee | |||
| 779 | /// any ordering or that entries are unique. | |||
| 780 | class MCRegAliasIterator { | |||
| 781 | private: | |||
| 782 | MCRegister Reg; | |||
| 783 | const MCRegisterInfo *MCRI; | |||
| 784 | bool IncludeSelf; | |||
| 785 | ||||
| 786 | MCRegUnitIterator RI; | |||
| 787 | MCRegUnitRootIterator RRI; | |||
| 788 | MCSuperRegIterator SI; | |||
| 789 | ||||
| 790 | public: | |||
| 791 | MCRegAliasIterator(MCRegister Reg, const MCRegisterInfo *MCRI, | |||
| 792 | bool IncludeSelf) | |||
| 793 | : Reg(Reg), MCRI(MCRI), IncludeSelf(IncludeSelf) { | |||
| 794 | // Initialize the iterators. | |||
| 795 | for (RI = MCRegUnitIterator(Reg, MCRI); RI.isValid(); ++RI) { | |||
| 796 | for (RRI = MCRegUnitRootIterator(*RI, MCRI); RRI.isValid(); ++RRI) { | |||
| 797 | for (SI = MCSuperRegIterator(*RRI, MCRI, true); SI.isValid(); ++SI) { | |||
| 798 | if (!(!IncludeSelf && Reg == *SI)) | |||
| 799 | return; | |||
| 800 | } | |||
| 801 | } | |||
| 802 | } | |||
| 803 | } | |||
| 804 | ||||
| 805 | bool isValid() const { return RI.isValid(); } | |||
| 806 | ||||
| 807 | MCRegister operator*() const { | |||
| 808 | assert(SI.isValid() && "Cannot dereference an invalid iterator.")((void)0); | |||
| 809 | return *SI; | |||
| 810 | } | |||
| 811 | ||||
| 812 | void advance() { | |||
| 813 | // Assuming SI is valid. | |||
| 814 | ++SI; | |||
| 815 | if (SI.isValid()) return; | |||
| 816 | ||||
| 817 | ++RRI; | |||
| 818 | if (RRI.isValid()) { | |||
| 819 | SI = MCSuperRegIterator(*RRI, MCRI, true); | |||
| 820 | return; | |||
| 821 | } | |||
| 822 | ||||
| 823 | ++RI; | |||
| 824 | if (RI.isValid()) { | |||
| 825 | RRI = MCRegUnitRootIterator(*RI, MCRI); | |||
| 826 | SI = MCSuperRegIterator(*RRI, MCRI, true); | |||
| 827 | } | |||
| 828 | } | |||
| 829 | ||||
| 830 | void operator++() { | |||
| 831 | assert(isValid() && "Cannot move off the end of the list.")((void)0); | |||
| 832 | do advance(); | |||
| 833 | while (!IncludeSelf && isValid() && *SI == Reg); | |||
| 834 | } | |||
| 835 | }; | |||
| 836 | ||||
| 837 | } // end namespace llvm | |||
| 838 | ||||
| 839 | #endif // LLVM_MC_MCREGISTERINFO_H |