| File: | src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/Support/GenericDomTree.h |
| Warning: | line 494, column 12 Called C++ object pointer is null |
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
| ||||||||
| 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 | //==- llvm/CodeGen/MachineDominators.h - Machine Dom Calculation -*- 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 defines classes mirroring those in llvm/Analysis/Dominators.h, |
| 10 | // but for target-specific code rather than target-independent IR. |
| 11 | // |
| 12 | //===----------------------------------------------------------------------===// |
| 13 | |
| 14 | #ifndef LLVM_CODEGEN_MACHINEDOMINATORS_H |
| 15 | #define LLVM_CODEGEN_MACHINEDOMINATORS_H |
| 16 | |
| 17 | #include "llvm/ADT/SmallSet.h" |
| 18 | #include "llvm/ADT/SmallVector.h" |
| 19 | #include "llvm/CodeGen/MachineBasicBlock.h" |
| 20 | #include "llvm/CodeGen/MachineFunctionPass.h" |
| 21 | #include "llvm/CodeGen/MachineInstr.h" |
| 22 | #include "llvm/Support/GenericDomTree.h" |
| 23 | #include "llvm/Support/GenericDomTreeConstruction.h" |
| 24 | #include <cassert> |
| 25 | #include <memory> |
| 26 | |
| 27 | namespace llvm { |
| 28 | |
| 29 | template <> |
| 30 | inline void DominatorTreeBase<MachineBasicBlock, false>::addRoot( |
| 31 | MachineBasicBlock *MBB) { |
| 32 | this->Roots.push_back(MBB); |
| 33 | } |
| 34 | |
| 35 | extern template class DomTreeNodeBase<MachineBasicBlock>; |
| 36 | extern template class DominatorTreeBase<MachineBasicBlock, false>; // DomTree |
| 37 | extern template class DominatorTreeBase<MachineBasicBlock, true>; // PostDomTree |
| 38 | |
| 39 | using MachineDomTreeNode = DomTreeNodeBase<MachineBasicBlock>; |
| 40 | |
| 41 | //===------------------------------------- |
| 42 | /// DominatorTree Class - Concrete subclass of DominatorTreeBase that is used to |
| 43 | /// compute a normal dominator tree. |
| 44 | /// |
| 45 | class MachineDominatorTree : public MachineFunctionPass { |
| 46 | using DomTreeT = DomTreeBase<MachineBasicBlock>; |
| 47 | |
| 48 | /// Helper structure used to hold all the basic blocks |
| 49 | /// involved in the split of a critical edge. |
| 50 | struct CriticalEdge { |
| 51 | MachineBasicBlock *FromBB; |
| 52 | MachineBasicBlock *ToBB; |
| 53 | MachineBasicBlock *NewBB; |
| 54 | }; |
| 55 | |
| 56 | /// Pile up all the critical edges to be split. |
| 57 | /// The splitting of a critical edge is local and thus, it is possible |
| 58 | /// to apply several of those changes at the same time. |
| 59 | mutable SmallVector<CriticalEdge, 32> CriticalEdgesToSplit; |
| 60 | |
| 61 | /// Remember all the basic blocks that are inserted during |
| 62 | /// edge splitting. |
| 63 | /// Invariant: NewBBs == all the basic blocks contained in the NewBB |
| 64 | /// field of all the elements of CriticalEdgesToSplit. |
| 65 | /// I.e., forall elt in CriticalEdgesToSplit, it exists BB in NewBBs |
| 66 | /// such as BB == elt.NewBB. |
| 67 | mutable SmallSet<MachineBasicBlock *, 32> NewBBs; |
| 68 | |
| 69 | /// The DominatorTreeBase that is used to compute a normal dominator tree. |
| 70 | std::unique_ptr<DomTreeT> DT; |
| 71 | |
| 72 | /// Apply all the recorded critical edges to the DT. |
| 73 | /// This updates the underlying DT information in a way that uses |
| 74 | /// the fast query path of DT as much as possible. |
| 75 | /// |
| 76 | /// \post CriticalEdgesToSplit.empty(). |
| 77 | void applySplitCriticalEdges() const; |
| 78 | |
| 79 | public: |
| 80 | static char ID; // Pass ID, replacement for typeid |
| 81 | |
| 82 | MachineDominatorTree(); |
| 83 | explicit MachineDominatorTree(MachineFunction &MF) : MachineFunctionPass(ID) { |
| 84 | calculate(MF); |
| 85 | } |
| 86 | |
| 87 | DomTreeT &getBase() { |
| 88 | if (!DT) DT.reset(new DomTreeT()); |
| 89 | applySplitCriticalEdges(); |
| 90 | return *DT; |
| 91 | } |
| 92 | |
| 93 | void getAnalysisUsage(AnalysisUsage &AU) const override; |
| 94 | |
| 95 | MachineBasicBlock *getRoot() const { |
| 96 | applySplitCriticalEdges(); |
| 97 | return DT->getRoot(); |
| 98 | } |
| 99 | |
| 100 | MachineDomTreeNode *getRootNode() const { |
| 101 | applySplitCriticalEdges(); |
| 102 | return DT->getRootNode(); |
| 103 | } |
| 104 | |
| 105 | bool runOnMachineFunction(MachineFunction &F) override; |
| 106 | |
| 107 | void calculate(MachineFunction &F); |
| 108 | |
| 109 | bool dominates(const MachineDomTreeNode *A, |
| 110 | const MachineDomTreeNode *B) const { |
| 111 | applySplitCriticalEdges(); |
| 112 | return DT->dominates(A, B); |
| 113 | } |
| 114 | |
| 115 | bool dominates(const MachineBasicBlock *A, const MachineBasicBlock *B) const { |
| 116 | applySplitCriticalEdges(); |
| 117 | return DT->dominates(A, B); |
| 118 | } |
| 119 | |
| 120 | // dominates - Return true if A dominates B. This performs the |
| 121 | // special checks necessary if A and B are in the same basic block. |
| 122 | bool dominates(const MachineInstr *A, const MachineInstr *B) const { |
| 123 | applySplitCriticalEdges(); |
| 124 | const MachineBasicBlock *BBA = A->getParent(), *BBB = B->getParent(); |
| 125 | if (BBA != BBB) return DT->dominates(BBA, BBB); |
| 126 | |
| 127 | // Loop through the basic block until we find A or B. |
| 128 | MachineBasicBlock::const_iterator I = BBA->begin(); |
| 129 | for (; &*I != A && &*I != B; ++I) |
| 130 | /*empty*/ ; |
| 131 | |
| 132 | return &*I == A; |
| 133 | } |
| 134 | |
| 135 | bool properlyDominates(const MachineDomTreeNode *A, |
| 136 | const MachineDomTreeNode *B) const { |
| 137 | applySplitCriticalEdges(); |
| 138 | return DT->properlyDominates(A, B); |
| 139 | } |
| 140 | |
| 141 | bool properlyDominates(const MachineBasicBlock *A, |
| 142 | const MachineBasicBlock *B) const { |
| 143 | applySplitCriticalEdges(); |
| 144 | return DT->properlyDominates(A, B); |
| 145 | } |
| 146 | |
| 147 | /// findNearestCommonDominator - Find nearest common dominator basic block |
| 148 | /// for basic block A and B. If there is no such block then return NULL. |
| 149 | MachineBasicBlock *findNearestCommonDominator(MachineBasicBlock *A, |
| 150 | MachineBasicBlock *B) { |
| 151 | applySplitCriticalEdges(); |
| 152 | return DT->findNearestCommonDominator(A, B); |
| 153 | } |
| 154 | |
| 155 | MachineDomTreeNode *operator[](MachineBasicBlock *BB) const { |
| 156 | applySplitCriticalEdges(); |
| 157 | return DT->getNode(BB); |
| 158 | } |
| 159 | |
| 160 | /// getNode - return the (Post)DominatorTree node for the specified basic |
| 161 | /// block. This is the same as using operator[] on this class. |
| 162 | /// |
| 163 | MachineDomTreeNode *getNode(MachineBasicBlock *BB) const { |
| 164 | applySplitCriticalEdges(); |
| 165 | return DT->getNode(BB); |
| 166 | } |
| 167 | |
| 168 | /// addNewBlock - Add a new node to the dominator tree information. This |
| 169 | /// creates a new node as a child of DomBB dominator node,linking it into |
| 170 | /// the children list of the immediate dominator. |
| 171 | MachineDomTreeNode *addNewBlock(MachineBasicBlock *BB, |
| 172 | MachineBasicBlock *DomBB) { |
| 173 | applySplitCriticalEdges(); |
| 174 | return DT->addNewBlock(BB, DomBB); |
| 175 | } |
| 176 | |
| 177 | /// changeImmediateDominator - This method is used to update the dominator |
| 178 | /// tree information when a node's immediate dominator changes. |
| 179 | /// |
| 180 | void changeImmediateDominator(MachineBasicBlock *N, |
| 181 | MachineBasicBlock *NewIDom) { |
| 182 | applySplitCriticalEdges(); |
| 183 | DT->changeImmediateDominator(N, NewIDom); |
| 184 | } |
| 185 | |
| 186 | void changeImmediateDominator(MachineDomTreeNode *N, |
| 187 | MachineDomTreeNode *NewIDom) { |
| 188 | applySplitCriticalEdges(); |
| 189 | DT->changeImmediateDominator(N, NewIDom); |
| 190 | } |
| 191 | |
| 192 | /// eraseNode - Removes a node from the dominator tree. Block must not |
| 193 | /// dominate any other blocks. Removes node from its immediate dominator's |
| 194 | /// children list. Deletes dominator node associated with basic block BB. |
| 195 | void eraseNode(MachineBasicBlock *BB) { |
| 196 | applySplitCriticalEdges(); |
| 197 | DT->eraseNode(BB); |
| 198 | } |
| 199 | |
| 200 | /// splitBlock - BB is split and now it has one successor. Update dominator |
| 201 | /// tree to reflect this change. |
| 202 | void splitBlock(MachineBasicBlock* NewBB) { |
| 203 | applySplitCriticalEdges(); |
| 204 | DT->splitBlock(NewBB); |
| 205 | } |
| 206 | |
| 207 | /// isReachableFromEntry - Return true if A is dominated by the entry |
| 208 | /// block of the function containing it. |
| 209 | bool isReachableFromEntry(const MachineBasicBlock *A) { |
| 210 | applySplitCriticalEdges(); |
| 211 | return DT->isReachableFromEntry(A); |
| 212 | } |
| 213 | |
| 214 | void releaseMemory() override; |
| 215 | |
| 216 | void verifyAnalysis() const override; |
| 217 | |
| 218 | void print(raw_ostream &OS, const Module*) const override; |
| 219 | |
| 220 | /// Record that the critical edge (FromBB, ToBB) has been |
| 221 | /// split with NewBB. |
| 222 | /// This is best to use this method instead of directly update the |
| 223 | /// underlying information, because this helps mitigating the |
| 224 | /// number of time the DT information is invalidated. |
| 225 | /// |
| 226 | /// \note Do not use this method with regular edges. |
| 227 | /// |
| 228 | /// \note To benefit from the compile time improvement incurred by this |
| 229 | /// method, the users of this method have to limit the queries to the DT |
| 230 | /// interface between two edges splitting. In other words, they have to |
| 231 | /// pack the splitting of critical edges as much as possible. |
| 232 | void recordSplitCriticalEdge(MachineBasicBlock *FromBB, |
| 233 | MachineBasicBlock *ToBB, |
| 234 | MachineBasicBlock *NewBB) { |
| 235 | bool Inserted = NewBBs.insert(NewBB).second; |
| 236 | (void)Inserted; |
| 237 | assert(Inserted &&((void)0) |
| 238 | "A basic block inserted via edge splitting cannot appear twice")((void)0); |
| 239 | CriticalEdgesToSplit.push_back({FromBB, ToBB, NewBB}); |
| 240 | } |
| 241 | }; |
| 242 | |
| 243 | //===------------------------------------- |
| 244 | /// DominatorTree GraphTraits specialization so the DominatorTree can be |
| 245 | /// iterable by generic graph iterators. |
| 246 | /// |
| 247 | |
| 248 | template <class Node, class ChildIterator> |
| 249 | struct MachineDomTreeGraphTraitsBase { |
| 250 | using NodeRef = Node *; |
| 251 | using ChildIteratorType = ChildIterator; |
| 252 | |
| 253 | static NodeRef getEntryNode(NodeRef N) { return N; } |
| 254 | static ChildIteratorType child_begin(NodeRef N) { return N->begin(); } |
| 255 | static ChildIteratorType child_end(NodeRef N) { return N->end(); } |
| 256 | }; |
| 257 | |
| 258 | template <class T> struct GraphTraits; |
| 259 | |
| 260 | template <> |
| 261 | struct GraphTraits<MachineDomTreeNode *> |
| 262 | : public MachineDomTreeGraphTraitsBase<MachineDomTreeNode, |
| 263 | MachineDomTreeNode::const_iterator> { |
| 264 | }; |
| 265 | |
| 266 | template <> |
| 267 | struct GraphTraits<const MachineDomTreeNode *> |
| 268 | : public MachineDomTreeGraphTraitsBase<const MachineDomTreeNode, |
| 269 | MachineDomTreeNode::const_iterator> { |
| 270 | }; |
| 271 | |
| 272 | template <> struct GraphTraits<MachineDominatorTree*> |
| 273 | : public GraphTraits<MachineDomTreeNode *> { |
| 274 | static NodeRef getEntryNode(MachineDominatorTree *DT) { |
| 275 | return DT->getRootNode(); |
| 276 | } |
| 277 | }; |
| 278 | |
| 279 | } // end namespace llvm |
| 280 | |
| 281 | #endif // LLVM_CODEGEN_MACHINEDOMINATORS_H |
| 1 | //===- GenericDomTree.h - Generic dominator trees for graphs ----*- 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 | /// \file | |||
| 9 | /// | |||
| 10 | /// This file defines a set of templates that efficiently compute a dominator | |||
| 11 | /// tree over a generic graph. This is used typically in LLVM for fast | |||
| 12 | /// dominance queries on the CFG, but is fully generic w.r.t. the underlying | |||
| 13 | /// graph types. | |||
| 14 | /// | |||
| 15 | /// Unlike ADT/* graph algorithms, generic dominator tree has more requirements | |||
| 16 | /// on the graph's NodeRef. The NodeRef should be a pointer and, | |||
| 17 | /// NodeRef->getParent() must return the parent node that is also a pointer. | |||
| 18 | /// | |||
| 19 | /// FIXME: Maybe GenericDomTree needs a TreeTraits, instead of GraphTraits. | |||
| 20 | /// | |||
| 21 | //===----------------------------------------------------------------------===// | |||
| 22 | ||||
| 23 | #ifndef LLVM_SUPPORT_GENERICDOMTREE_H | |||
| 24 | #define LLVM_SUPPORT_GENERICDOMTREE_H | |||
| 25 | ||||
| 26 | #include "llvm/ADT/DenseMap.h" | |||
| 27 | #include "llvm/ADT/GraphTraits.h" | |||
| 28 | #include "llvm/ADT/STLExtras.h" | |||
| 29 | #include "llvm/ADT/SmallPtrSet.h" | |||
| 30 | #include "llvm/ADT/SmallVector.h" | |||
| 31 | #include "llvm/Support/CFGDiff.h" | |||
| 32 | #include "llvm/Support/CFGUpdate.h" | |||
| 33 | #include "llvm/Support/raw_ostream.h" | |||
| 34 | #include <algorithm> | |||
| 35 | #include <cassert> | |||
| 36 | #include <cstddef> | |||
| 37 | #include <iterator> | |||
| 38 | #include <memory> | |||
| 39 | #include <type_traits> | |||
| 40 | #include <utility> | |||
| 41 | ||||
| 42 | namespace llvm { | |||
| 43 | ||||
| 44 | template <typename NodeT, bool IsPostDom> | |||
| 45 | class DominatorTreeBase; | |||
| 46 | ||||
| 47 | namespace DomTreeBuilder { | |||
| 48 | template <typename DomTreeT> | |||
| 49 | struct SemiNCAInfo; | |||
| 50 | } // namespace DomTreeBuilder | |||
| 51 | ||||
| 52 | /// Base class for the actual dominator tree node. | |||
| 53 | template <class NodeT> class DomTreeNodeBase { | |||
| 54 | friend class PostDominatorTree; | |||
| 55 | friend class DominatorTreeBase<NodeT, false>; | |||
| 56 | friend class DominatorTreeBase<NodeT, true>; | |||
| 57 | friend struct DomTreeBuilder::SemiNCAInfo<DominatorTreeBase<NodeT, false>>; | |||
| 58 | friend struct DomTreeBuilder::SemiNCAInfo<DominatorTreeBase<NodeT, true>>; | |||
| 59 | ||||
| 60 | NodeT *TheBB; | |||
| 61 | DomTreeNodeBase *IDom; | |||
| 62 | unsigned Level; | |||
| 63 | SmallVector<DomTreeNodeBase *, 4> Children; | |||
| 64 | mutable unsigned DFSNumIn = ~0; | |||
| 65 | mutable unsigned DFSNumOut = ~0; | |||
| 66 | ||||
| 67 | public: | |||
| 68 | DomTreeNodeBase(NodeT *BB, DomTreeNodeBase *iDom) | |||
| 69 | : TheBB(BB), IDom(iDom), Level(IDom ? IDom->Level + 1 : 0) {} | |||
| 70 | ||||
| 71 | using iterator = typename SmallVector<DomTreeNodeBase *, 4>::iterator; | |||
| 72 | using const_iterator = | |||
| 73 | typename SmallVector<DomTreeNodeBase *, 4>::const_iterator; | |||
| 74 | ||||
| 75 | iterator begin() { return Children.begin(); } | |||
| 76 | iterator end() { return Children.end(); } | |||
| 77 | const_iterator begin() const { return Children.begin(); } | |||
| 78 | const_iterator end() const { return Children.end(); } | |||
| 79 | ||||
| 80 | DomTreeNodeBase *const &back() const { return Children.back(); } | |||
| 81 | DomTreeNodeBase *&back() { return Children.back(); } | |||
| 82 | ||||
| 83 | iterator_range<iterator> children() { return make_range(begin(), end()); } | |||
| 84 | iterator_range<const_iterator> children() const { | |||
| 85 | return make_range(begin(), end()); | |||
| 86 | } | |||
| 87 | ||||
| 88 | NodeT *getBlock() const { return TheBB; } | |||
| 89 | DomTreeNodeBase *getIDom() const { return IDom; } | |||
| 90 | unsigned getLevel() const { return Level; } | |||
| 91 | ||||
| 92 | std::unique_ptr<DomTreeNodeBase> addChild( | |||
| 93 | std::unique_ptr<DomTreeNodeBase> C) { | |||
| 94 | Children.push_back(C.get()); | |||
| 95 | return C; | |||
| 96 | } | |||
| 97 | ||||
| 98 | bool isLeaf() const { return Children.empty(); } | |||
| 99 | size_t getNumChildren() const { return Children.size(); } | |||
| 100 | ||||
| 101 | void clearAllChildren() { Children.clear(); } | |||
| 102 | ||||
| 103 | bool compare(const DomTreeNodeBase *Other) const { | |||
| 104 | if (getNumChildren() != Other->getNumChildren()) | |||
| 105 | return true; | |||
| 106 | ||||
| 107 | if (Level != Other->Level) return true; | |||
| 108 | ||||
| 109 | SmallPtrSet<const NodeT *, 4> OtherChildren; | |||
| 110 | for (const DomTreeNodeBase *I : *Other) { | |||
| 111 | const NodeT *Nd = I->getBlock(); | |||
| 112 | OtherChildren.insert(Nd); | |||
| 113 | } | |||
| 114 | ||||
| 115 | for (const DomTreeNodeBase *I : *this) { | |||
| 116 | const NodeT *N = I->getBlock(); | |||
| 117 | if (OtherChildren.count(N) == 0) | |||
| 118 | return true; | |||
| 119 | } | |||
| 120 | return false; | |||
| 121 | } | |||
| 122 | ||||
| 123 | void setIDom(DomTreeNodeBase *NewIDom) { | |||
| 124 | assert(IDom && "No immediate dominator?")((void)0); | |||
| 125 | if (IDom == NewIDom) return; | |||
| 126 | ||||
| 127 | auto I = find(IDom->Children, this); | |||
| 128 | assert(I != IDom->Children.end() &&((void)0) | |||
| 129 | "Not in immediate dominator children set!")((void)0); | |||
| 130 | // I am no longer your child... | |||
| 131 | IDom->Children.erase(I); | |||
| 132 | ||||
| 133 | // Switch to new dominator | |||
| 134 | IDom = NewIDom; | |||
| 135 | IDom->Children.push_back(this); | |||
| 136 | ||||
| 137 | UpdateLevel(); | |||
| 138 | } | |||
| 139 | ||||
| 140 | /// getDFSNumIn/getDFSNumOut - These return the DFS visitation order for nodes | |||
| 141 | /// in the dominator tree. They are only guaranteed valid if | |||
| 142 | /// updateDFSNumbers() has been called. | |||
| 143 | unsigned getDFSNumIn() const { return DFSNumIn; } | |||
| 144 | unsigned getDFSNumOut() const { return DFSNumOut; } | |||
| 145 | ||||
| 146 | private: | |||
| 147 | // Return true if this node is dominated by other. Use this only if DFS info | |||
| 148 | // is valid. | |||
| 149 | bool DominatedBy(const DomTreeNodeBase *other) const { | |||
| 150 | return this->DFSNumIn >= other->DFSNumIn && | |||
| 151 | this->DFSNumOut <= other->DFSNumOut; | |||
| 152 | } | |||
| 153 | ||||
| 154 | void UpdateLevel() { | |||
| 155 | assert(IDom)((void)0); | |||
| 156 | if (Level == IDom->Level + 1) return; | |||
| 157 | ||||
| 158 | SmallVector<DomTreeNodeBase *, 64> WorkStack = {this}; | |||
| 159 | ||||
| 160 | while (!WorkStack.empty()) { | |||
| 161 | DomTreeNodeBase *Current = WorkStack.pop_back_val(); | |||
| 162 | Current->Level = Current->IDom->Level + 1; | |||
| 163 | ||||
| 164 | for (DomTreeNodeBase *C : *Current) { | |||
| 165 | assert(C->IDom)((void)0); | |||
| 166 | if (C->Level != C->IDom->Level + 1) WorkStack.push_back(C); | |||
| 167 | } | |||
| 168 | } | |||
| 169 | } | |||
| 170 | }; | |||
| 171 | ||||
| 172 | template <class NodeT> | |||
| 173 | raw_ostream &operator<<(raw_ostream &O, const DomTreeNodeBase<NodeT> *Node) { | |||
| 174 | if (Node->getBlock()) | |||
| 175 | Node->getBlock()->printAsOperand(O, false); | |||
| 176 | else | |||
| 177 | O << " <<exit node>>"; | |||
| 178 | ||||
| 179 | O << " {" << Node->getDFSNumIn() << "," << Node->getDFSNumOut() << "} [" | |||
| 180 | << Node->getLevel() << "]\n"; | |||
| 181 | ||||
| 182 | return O; | |||
| 183 | } | |||
| 184 | ||||
| 185 | template <class NodeT> | |||
| 186 | void PrintDomTree(const DomTreeNodeBase<NodeT> *N, raw_ostream &O, | |||
| 187 | unsigned Lev) { | |||
| 188 | O.indent(2 * Lev) << "[" << Lev << "] " << N; | |||
| 189 | for (typename DomTreeNodeBase<NodeT>::const_iterator I = N->begin(), | |||
| 190 | E = N->end(); | |||
| 191 | I != E; ++I) | |||
| 192 | PrintDomTree<NodeT>(*I, O, Lev + 1); | |||
| 193 | } | |||
| 194 | ||||
| 195 | namespace DomTreeBuilder { | |||
| 196 | // The routines below are provided in a separate header but referenced here. | |||
| 197 | template <typename DomTreeT> | |||
| 198 | void Calculate(DomTreeT &DT); | |||
| 199 | ||||
| 200 | template <typename DomTreeT> | |||
| 201 | void CalculateWithUpdates(DomTreeT &DT, | |||
| 202 | ArrayRef<typename DomTreeT::UpdateType> Updates); | |||
| 203 | ||||
| 204 | template <typename DomTreeT> | |||
| 205 | void InsertEdge(DomTreeT &DT, typename DomTreeT::NodePtr From, | |||
| 206 | typename DomTreeT::NodePtr To); | |||
| 207 | ||||
| 208 | template <typename DomTreeT> | |||
| 209 | void DeleteEdge(DomTreeT &DT, typename DomTreeT::NodePtr From, | |||
| 210 | typename DomTreeT::NodePtr To); | |||
| 211 | ||||
| 212 | template <typename DomTreeT> | |||
| 213 | void ApplyUpdates(DomTreeT &DT, | |||
| 214 | GraphDiff<typename DomTreeT::NodePtr, | |||
| 215 | DomTreeT::IsPostDominator> &PreViewCFG, | |||
| 216 | GraphDiff<typename DomTreeT::NodePtr, | |||
| 217 | DomTreeT::IsPostDominator> *PostViewCFG); | |||
| 218 | ||||
| 219 | template <typename DomTreeT> | |||
| 220 | bool Verify(const DomTreeT &DT, typename DomTreeT::VerificationLevel VL); | |||
| 221 | } // namespace DomTreeBuilder | |||
| 222 | ||||
| 223 | /// Core dominator tree base class. | |||
| 224 | /// | |||
| 225 | /// This class is a generic template over graph nodes. It is instantiated for | |||
| 226 | /// various graphs in the LLVM IR or in the code generator. | |||
| 227 | template <typename NodeT, bool IsPostDom> | |||
| 228 | class DominatorTreeBase { | |||
| 229 | public: | |||
| 230 | static_assert(std::is_pointer<typename GraphTraits<NodeT *>::NodeRef>::value, | |||
| 231 | "Currently DominatorTreeBase supports only pointer nodes"); | |||
| 232 | using NodeType = NodeT; | |||
| 233 | using NodePtr = NodeT *; | |||
| 234 | using ParentPtr = decltype(std::declval<NodeT *>()->getParent()); | |||
| 235 | static_assert(std::is_pointer<ParentPtr>::value, | |||
| 236 | "Currently NodeT's parent must be a pointer type"); | |||
| 237 | using ParentType = std::remove_pointer_t<ParentPtr>; | |||
| 238 | static constexpr bool IsPostDominator = IsPostDom; | |||
| 239 | ||||
| 240 | using UpdateType = cfg::Update<NodePtr>; | |||
| 241 | using UpdateKind = cfg::UpdateKind; | |||
| 242 | static constexpr UpdateKind Insert = UpdateKind::Insert; | |||
| 243 | static constexpr UpdateKind Delete = UpdateKind::Delete; | |||
| 244 | ||||
| 245 | enum class VerificationLevel { Fast, Basic, Full }; | |||
| 246 | ||||
| 247 | protected: | |||
| 248 | // Dominators always have a single root, postdominators can have more. | |||
| 249 | SmallVector<NodeT *, IsPostDom ? 4 : 1> Roots; | |||
| 250 | ||||
| 251 | using DomTreeNodeMapType = | |||
| 252 | DenseMap<NodeT *, std::unique_ptr<DomTreeNodeBase<NodeT>>>; | |||
| 253 | DomTreeNodeMapType DomTreeNodes; | |||
| 254 | DomTreeNodeBase<NodeT> *RootNode = nullptr; | |||
| 255 | ParentPtr Parent = nullptr; | |||
| 256 | ||||
| 257 | mutable bool DFSInfoValid = false; | |||
| 258 | mutable unsigned int SlowQueries = 0; | |||
| 259 | ||||
| 260 | friend struct DomTreeBuilder::SemiNCAInfo<DominatorTreeBase>; | |||
| 261 | ||||
| 262 | public: | |||
| 263 | DominatorTreeBase() {} | |||
| 264 | ||||
| 265 | DominatorTreeBase(DominatorTreeBase &&Arg) | |||
| 266 | : Roots(std::move(Arg.Roots)), | |||
| 267 | DomTreeNodes(std::move(Arg.DomTreeNodes)), | |||
| 268 | RootNode(Arg.RootNode), | |||
| 269 | Parent(Arg.Parent), | |||
| 270 | DFSInfoValid(Arg.DFSInfoValid), | |||
| 271 | SlowQueries(Arg.SlowQueries) { | |||
| 272 | Arg.wipe(); | |||
| 273 | } | |||
| 274 | ||||
| 275 | DominatorTreeBase &operator=(DominatorTreeBase &&RHS) { | |||
| 276 | Roots = std::move(RHS.Roots); | |||
| 277 | DomTreeNodes = std::move(RHS.DomTreeNodes); | |||
| 278 | RootNode = RHS.RootNode; | |||
| 279 | Parent = RHS.Parent; | |||
| 280 | DFSInfoValid = RHS.DFSInfoValid; | |||
| 281 | SlowQueries = RHS.SlowQueries; | |||
| 282 | RHS.wipe(); | |||
| 283 | return *this; | |||
| 284 | } | |||
| 285 | ||||
| 286 | DominatorTreeBase(const DominatorTreeBase &) = delete; | |||
| 287 | DominatorTreeBase &operator=(const DominatorTreeBase &) = delete; | |||
| 288 | ||||
| 289 | /// Iteration over roots. | |||
| 290 | /// | |||
| 291 | /// This may include multiple blocks if we are computing post dominators. | |||
| 292 | /// For forward dominators, this will always be a single block (the entry | |||
| 293 | /// block). | |||
| 294 | using root_iterator = typename SmallVectorImpl<NodeT *>::iterator; | |||
| 295 | using const_root_iterator = typename SmallVectorImpl<NodeT *>::const_iterator; | |||
| 296 | ||||
| 297 | root_iterator root_begin() { return Roots.begin(); } | |||
| 298 | const_root_iterator root_begin() const { return Roots.begin(); } | |||
| 299 | root_iterator root_end() { return Roots.end(); } | |||
| 300 | const_root_iterator root_end() const { return Roots.end(); } | |||
| 301 | ||||
| 302 | size_t root_size() const { return Roots.size(); } | |||
| 303 | ||||
| 304 | iterator_range<root_iterator> roots() { | |||
| 305 | return make_range(root_begin(), root_end()); | |||
| 306 | } | |||
| 307 | iterator_range<const_root_iterator> roots() const { | |||
| 308 | return make_range(root_begin(), root_end()); | |||
| 309 | } | |||
| 310 | ||||
| 311 | /// isPostDominator - Returns true if analysis based of postdoms | |||
| 312 | /// | |||
| 313 | bool isPostDominator() const { return IsPostDominator; } | |||
| 314 | ||||
| 315 | /// compare - Return false if the other dominator tree base matches this | |||
| 316 | /// dominator tree base. Otherwise return true. | |||
| 317 | bool compare(const DominatorTreeBase &Other) const { | |||
| 318 | if (Parent != Other.Parent) return true; | |||
| 319 | ||||
| 320 | if (Roots.size() != Other.Roots.size()) | |||
| 321 | return true; | |||
| 322 | ||||
| 323 | if (!std::is_permutation(Roots.begin(), Roots.end(), Other.Roots.begin())) | |||
| 324 | return true; | |||
| 325 | ||||
| 326 | const DomTreeNodeMapType &OtherDomTreeNodes = Other.DomTreeNodes; | |||
| 327 | if (DomTreeNodes.size() != OtherDomTreeNodes.size()) | |||
| 328 | return true; | |||
| 329 | ||||
| 330 | for (const auto &DomTreeNode : DomTreeNodes) { | |||
| 331 | NodeT *BB = DomTreeNode.first; | |||
| 332 | typename DomTreeNodeMapType::const_iterator OI = | |||
| 333 | OtherDomTreeNodes.find(BB); | |||
| 334 | if (OI == OtherDomTreeNodes.end()) | |||
| 335 | return true; | |||
| 336 | ||||
| 337 | DomTreeNodeBase<NodeT> &MyNd = *DomTreeNode.second; | |||
| 338 | DomTreeNodeBase<NodeT> &OtherNd = *OI->second; | |||
| 339 | ||||
| 340 | if (MyNd.compare(&OtherNd)) | |||
| 341 | return true; | |||
| 342 | } | |||
| 343 | ||||
| 344 | return false; | |||
| 345 | } | |||
| 346 | ||||
| 347 | /// getNode - return the (Post)DominatorTree node for the specified basic | |||
| 348 | /// block. This is the same as using operator[] on this class. The result | |||
| 349 | /// may (but is not required to) be null for a forward (backwards) | |||
| 350 | /// statically unreachable block. | |||
| 351 | DomTreeNodeBase<NodeT> *getNode(const NodeT *BB) const { | |||
| 352 | auto I = DomTreeNodes.find(BB); | |||
| 353 | if (I != DomTreeNodes.end()) | |||
| 354 | return I->second.get(); | |||
| 355 | return nullptr; | |||
| 356 | } | |||
| 357 | ||||
| 358 | /// See getNode. | |||
| 359 | DomTreeNodeBase<NodeT> *operator[](const NodeT *BB) const { | |||
| 360 | return getNode(BB); | |||
| 361 | } | |||
| 362 | ||||
| 363 | /// getRootNode - This returns the entry node for the CFG of the function. If | |||
| 364 | /// this tree represents the post-dominance relations for a function, however, | |||
| 365 | /// this root may be a node with the block == NULL. This is the case when | |||
| 366 | /// there are multiple exit nodes from a particular function. Consumers of | |||
| 367 | /// post-dominance information must be capable of dealing with this | |||
| 368 | /// possibility. | |||
| 369 | /// | |||
| 370 | DomTreeNodeBase<NodeT> *getRootNode() { return RootNode; } | |||
| 371 | const DomTreeNodeBase<NodeT> *getRootNode() const { return RootNode; } | |||
| 372 | ||||
| 373 | /// Get all nodes dominated by R, including R itself. | |||
| 374 | void getDescendants(NodeT *R, SmallVectorImpl<NodeT *> &Result) const { | |||
| 375 | Result.clear(); | |||
| 376 | const DomTreeNodeBase<NodeT> *RN = getNode(R); | |||
| 377 | if (!RN) | |||
| 378 | return; // If R is unreachable, it will not be present in the DOM tree. | |||
| 379 | SmallVector<const DomTreeNodeBase<NodeT> *, 8> WL; | |||
| 380 | WL.push_back(RN); | |||
| 381 | ||||
| 382 | while (!WL.empty()) { | |||
| 383 | const DomTreeNodeBase<NodeT> *N = WL.pop_back_val(); | |||
| 384 | Result.push_back(N->getBlock()); | |||
| 385 | WL.append(N->begin(), N->end()); | |||
| 386 | } | |||
| 387 | } | |||
| 388 | ||||
| 389 | /// properlyDominates - Returns true iff A dominates B and A != B. | |||
| 390 | /// Note that this is not a constant time operation! | |||
| 391 | /// | |||
| 392 | bool properlyDominates(const DomTreeNodeBase<NodeT> *A, | |||
| 393 | const DomTreeNodeBase<NodeT> *B) const { | |||
| 394 | if (!A || !B) | |||
| 395 | return false; | |||
| 396 | if (A == B) | |||
| 397 | return false; | |||
| 398 | return dominates(A, B); | |||
| 399 | } | |||
| 400 | ||||
| 401 | bool properlyDominates(const NodeT *A, const NodeT *B) const; | |||
| 402 | ||||
| 403 | /// isReachableFromEntry - Return true if A is dominated by the entry | |||
| 404 | /// block of the function containing it. | |||
| 405 | bool isReachableFromEntry(const NodeT *A) const { | |||
| 406 | assert(!this->isPostDominator() &&((void)0) | |||
| 407 | "This is not implemented for post dominators")((void)0); | |||
| 408 | return isReachableFromEntry(getNode(const_cast<NodeT *>(A))); | |||
| 409 | } | |||
| 410 | ||||
| 411 | bool isReachableFromEntry(const DomTreeNodeBase<NodeT> *A) const { return A; } | |||
| 412 | ||||
| 413 | /// dominates - Returns true iff A dominates B. Note that this is not a | |||
| 414 | /// constant time operation! | |||
| 415 | /// | |||
| 416 | bool dominates(const DomTreeNodeBase<NodeT> *A, | |||
| 417 | const DomTreeNodeBase<NodeT> *B) const { | |||
| 418 | // A node trivially dominates itself. | |||
| 419 | if (B == A) | |||
| 420 | return true; | |||
| 421 | ||||
| 422 | // An unreachable node is dominated by anything. | |||
| 423 | if (!isReachableFromEntry(B)) | |||
| 424 | return true; | |||
| 425 | ||||
| 426 | // And dominates nothing. | |||
| 427 | if (!isReachableFromEntry(A)) | |||
| 428 | return false; | |||
| 429 | ||||
| 430 | if (B->getIDom() == A) return true; | |||
| 431 | ||||
| 432 | if (A->getIDom() == B) return false; | |||
| 433 | ||||
| 434 | // A can only dominate B if it is higher in the tree. | |||
| 435 | if (A->getLevel() >= B->getLevel()) return false; | |||
| 436 | ||||
| 437 | // Compare the result of the tree walk and the dfs numbers, if expensive | |||
| 438 | // checks are enabled. | |||
| 439 | #ifdef EXPENSIVE_CHECKS | |||
| 440 | assert((!DFSInfoValid ||((void)0) | |||
| 441 | (dominatedBySlowTreeWalk(A, B) == B->DominatedBy(A))) &&((void)0) | |||
| 442 | "Tree walk disagrees with dfs numbers!")((void)0); | |||
| 443 | #endif | |||
| 444 | ||||
| 445 | if (DFSInfoValid) | |||
| 446 | return B->DominatedBy(A); | |||
| 447 | ||||
| 448 | // If we end up with too many slow queries, just update the | |||
| 449 | // DFS numbers on the theory that we are going to keep querying. | |||
| 450 | SlowQueries++; | |||
| 451 | if (SlowQueries > 32) { | |||
| 452 | updateDFSNumbers(); | |||
| 453 | return B->DominatedBy(A); | |||
| 454 | } | |||
| 455 | ||||
| 456 | return dominatedBySlowTreeWalk(A, B); | |||
| 457 | } | |||
| 458 | ||||
| 459 | bool dominates(const NodeT *A, const NodeT *B) const; | |||
| 460 | ||||
| 461 | NodeT *getRoot() const { | |||
| 462 | assert(this->Roots.size() == 1 && "Should always have entry node!")((void)0); | |||
| 463 | return this->Roots[0]; | |||
| 464 | } | |||
| 465 | ||||
| 466 | /// Find nearest common dominator basic block for basic block A and B. A and B | |||
| 467 | /// must have tree nodes. | |||
| 468 | NodeT *findNearestCommonDominator(NodeT *A, NodeT *B) const { | |||
| 469 | assert(A && B && "Pointers are not valid")((void)0); | |||
| 470 | assert(A->getParent() == B->getParent() &&((void)0) | |||
| 471 | "Two blocks are not in same function")((void)0); | |||
| 472 | ||||
| 473 | // If either A or B is a entry block then it is nearest common dominator | |||
| 474 | // (for forward-dominators). | |||
| 475 | if (!isPostDominator()) { | |||
| 476 | NodeT &Entry = A->getParent()->front(); | |||
| 477 | if (A == &Entry || B == &Entry) | |||
| 478 | return &Entry; | |||
| 479 | } | |||
| 480 | ||||
| 481 | DomTreeNodeBase<NodeT> *NodeA = getNode(A); | |||
| 482 | DomTreeNodeBase<NodeT> *NodeB = getNode(B); | |||
| 483 | assert(NodeA && "A must be in the tree")((void)0); | |||
| 484 | assert(NodeB && "B must be in the tree")((void)0); | |||
| 485 | ||||
| 486 | // Use level information to go up the tree until the levels match. Then | |||
| 487 | // continue going up til we arrive at the same node. | |||
| 488 | while (NodeA != NodeB) { | |||
| 489 | if (NodeA->getLevel() < NodeB->getLevel()) std::swap(NodeA, NodeB); | |||
| 490 | ||||
| 491 | NodeA = NodeA->IDom; | |||
| 492 | } | |||
| 493 | ||||
| 494 | return NodeA->getBlock(); | |||
| ||||
| 495 | } | |||
| 496 | ||||
| 497 | const NodeT *findNearestCommonDominator(const NodeT *A, | |||
| 498 | const NodeT *B) const { | |||
| 499 | // Cast away the const qualifiers here. This is ok since | |||
| 500 | // const is re-introduced on the return type. | |||
| 501 | return findNearestCommonDominator(const_cast<NodeT *>(A), | |||
| 502 | const_cast<NodeT *>(B)); | |||
| 503 | } | |||
| 504 | ||||
| 505 | bool isVirtualRoot(const DomTreeNodeBase<NodeT> *A) const { | |||
| 506 | return isPostDominator() && !A->getBlock(); | |||
| 507 | } | |||
| 508 | ||||
| 509 | //===--------------------------------------------------------------------===// | |||
| 510 | // API to update (Post)DominatorTree information based on modifications to | |||
| 511 | // the CFG... | |||
| 512 | ||||
| 513 | /// Inform the dominator tree about a sequence of CFG edge insertions and | |||
| 514 | /// deletions and perform a batch update on the tree. | |||
| 515 | /// | |||
| 516 | /// This function should be used when there were multiple CFG updates after | |||
| 517 | /// the last dominator tree update. It takes care of performing the updates | |||
| 518 | /// in sync with the CFG and optimizes away the redundant operations that | |||
| 519 | /// cancel each other. | |||
| 520 | /// The functions expects the sequence of updates to be balanced. Eg.: | |||
| 521 | /// - {{Insert, A, B}, {Delete, A, B}, {Insert, A, B}} is fine, because | |||
| 522 | /// logically it results in a single insertions. | |||
| 523 | /// - {{Insert, A, B}, {Insert, A, B}} is invalid, because it doesn't make | |||
| 524 | /// sense to insert the same edge twice. | |||
| 525 | /// | |||
| 526 | /// What's more, the functions assumes that it's safe to ask every node in the | |||
| 527 | /// CFG about its children and inverse children. This implies that deletions | |||
| 528 | /// of CFG edges must not delete the CFG nodes before calling this function. | |||
| 529 | /// | |||
| 530 | /// The applyUpdates function can reorder the updates and remove redundant | |||
| 531 | /// ones internally. The batch updater is also able to detect sequences of | |||
| 532 | /// zero and exactly one update -- it's optimized to do less work in these | |||
| 533 | /// cases. | |||
| 534 | /// | |||
| 535 | /// Note that for postdominators it automatically takes care of applying | |||
| 536 | /// updates on reverse edges internally (so there's no need to swap the | |||
| 537 | /// From and To pointers when constructing DominatorTree::UpdateType). | |||
| 538 | /// The type of updates is the same for DomTreeBase<T> and PostDomTreeBase<T> | |||
| 539 | /// with the same template parameter T. | |||
| 540 | /// | |||
| 541 | /// \param Updates An unordered sequence of updates to perform. The current | |||
| 542 | /// CFG and the reverse of these updates provides the pre-view of the CFG. | |||
| 543 | /// | |||
| 544 | void applyUpdates(ArrayRef<UpdateType> Updates) { | |||
| 545 | GraphDiff<NodePtr, IsPostDominator> PreViewCFG( | |||
| 546 | Updates, /*ReverseApplyUpdates=*/true); | |||
| 547 | DomTreeBuilder::ApplyUpdates(*this, PreViewCFG, nullptr); | |||
| 548 | } | |||
| 549 | ||||
| 550 | /// \param Updates An unordered sequence of updates to perform. The current | |||
| 551 | /// CFG and the reverse of these updates provides the pre-view of the CFG. | |||
| 552 | /// \param PostViewUpdates An unordered sequence of update to perform in order | |||
| 553 | /// to obtain a post-view of the CFG. The DT will be updated assuming the | |||
| 554 | /// obtained PostViewCFG is the desired end state. | |||
| 555 | void applyUpdates(ArrayRef<UpdateType> Updates, | |||
| 556 | ArrayRef<UpdateType> PostViewUpdates) { | |||
| 557 | if (Updates.empty()) { | |||
| 558 | GraphDiff<NodePtr, IsPostDom> PostViewCFG(PostViewUpdates); | |||
| 559 | DomTreeBuilder::ApplyUpdates(*this, PostViewCFG, &PostViewCFG); | |||
| 560 | } else { | |||
| 561 | // PreViewCFG needs to merge Updates and PostViewCFG. The updates in | |||
| 562 | // Updates need to be reversed, and match the direction in PostViewCFG. | |||
| 563 | // The PostViewCFG is created with updates reversed (equivalent to changes | |||
| 564 | // made to the CFG), so the PreViewCFG needs all the updates reverse | |||
| 565 | // applied. | |||
| 566 | SmallVector<UpdateType> AllUpdates(Updates.begin(), Updates.end()); | |||
| 567 | append_range(AllUpdates, PostViewUpdates); | |||
| 568 | GraphDiff<NodePtr, IsPostDom> PreViewCFG(AllUpdates, | |||
| 569 | /*ReverseApplyUpdates=*/true); | |||
| 570 | GraphDiff<NodePtr, IsPostDom> PostViewCFG(PostViewUpdates); | |||
| 571 | DomTreeBuilder::ApplyUpdates(*this, PreViewCFG, &PostViewCFG); | |||
| 572 | } | |||
| 573 | } | |||
| 574 | ||||
| 575 | /// Inform the dominator tree about a CFG edge insertion and update the tree. | |||
| 576 | /// | |||
| 577 | /// This function has to be called just before or just after making the update | |||
| 578 | /// on the actual CFG. There cannot be any other updates that the dominator | |||
| 579 | /// tree doesn't know about. | |||
| 580 | /// | |||
| 581 | /// Note that for postdominators it automatically takes care of inserting | |||
| 582 | /// a reverse edge internally (so there's no need to swap the parameters). | |||
| 583 | /// | |||
| 584 | void insertEdge(NodeT *From, NodeT *To) { | |||
| 585 | assert(From)((void)0); | |||
| 586 | assert(To)((void)0); | |||
| 587 | assert(From->getParent() == Parent)((void)0); | |||
| 588 | assert(To->getParent() == Parent)((void)0); | |||
| 589 | DomTreeBuilder::InsertEdge(*this, From, To); | |||
| 590 | } | |||
| 591 | ||||
| 592 | /// Inform the dominator tree about a CFG edge deletion and update the tree. | |||
| 593 | /// | |||
| 594 | /// This function has to be called just after making the update on the actual | |||
| 595 | /// CFG. An internal functions checks if the edge doesn't exist in the CFG in | |||
| 596 | /// DEBUG mode. There cannot be any other updates that the | |||
| 597 | /// dominator tree doesn't know about. | |||
| 598 | /// | |||
| 599 | /// Note that for postdominators it automatically takes care of deleting | |||
| 600 | /// a reverse edge internally (so there's no need to swap the parameters). | |||
| 601 | /// | |||
| 602 | void deleteEdge(NodeT *From, NodeT *To) { | |||
| 603 | assert(From)((void)0); | |||
| 604 | assert(To)((void)0); | |||
| 605 | assert(From->getParent() == Parent)((void)0); | |||
| 606 | assert(To->getParent() == Parent)((void)0); | |||
| 607 | DomTreeBuilder::DeleteEdge(*this, From, To); | |||
| 608 | } | |||
| 609 | ||||
| 610 | /// Add a new node to the dominator tree information. | |||
| 611 | /// | |||
| 612 | /// This creates a new node as a child of DomBB dominator node, linking it | |||
| 613 | /// into the children list of the immediate dominator. | |||
| 614 | /// | |||
| 615 | /// \param BB New node in CFG. | |||
| 616 | /// \param DomBB CFG node that is dominator for BB. | |||
| 617 | /// \returns New dominator tree node that represents new CFG node. | |||
| 618 | /// | |||
| 619 | DomTreeNodeBase<NodeT> *addNewBlock(NodeT *BB, NodeT *DomBB) { | |||
| 620 | assert(getNode(BB) == nullptr && "Block already in dominator tree!")((void)0); | |||
| 621 | DomTreeNodeBase<NodeT> *IDomNode = getNode(DomBB); | |||
| 622 | assert(IDomNode && "Not immediate dominator specified for block!")((void)0); | |||
| 623 | DFSInfoValid = false; | |||
| 624 | return createChild(BB, IDomNode); | |||
| 625 | } | |||
| 626 | ||||
| 627 | /// Add a new node to the forward dominator tree and make it a new root. | |||
| 628 | /// | |||
| 629 | /// \param BB New node in CFG. | |||
| 630 | /// \returns New dominator tree node that represents new CFG node. | |||
| 631 | /// | |||
| 632 | DomTreeNodeBase<NodeT> *setNewRoot(NodeT *BB) { | |||
| 633 | assert(getNode(BB) == nullptr && "Block already in dominator tree!")((void)0); | |||
| 634 | assert(!this->isPostDominator() &&((void)0) | |||
| 635 | "Cannot change root of post-dominator tree")((void)0); | |||
| 636 | DFSInfoValid = false; | |||
| 637 | DomTreeNodeBase<NodeT> *NewNode = createNode(BB); | |||
| 638 | if (Roots.empty()) { | |||
| 639 | addRoot(BB); | |||
| 640 | } else { | |||
| 641 | assert(Roots.size() == 1)((void)0); | |||
| 642 | NodeT *OldRoot = Roots.front(); | |||
| 643 | auto &OldNode = DomTreeNodes[OldRoot]; | |||
| 644 | OldNode = NewNode->addChild(std::move(DomTreeNodes[OldRoot])); | |||
| 645 | OldNode->IDom = NewNode; | |||
| 646 | OldNode->UpdateLevel(); | |||
| 647 | Roots[0] = BB; | |||
| 648 | } | |||
| 649 | return RootNode = NewNode; | |||
| 650 | } | |||
| 651 | ||||
| 652 | /// changeImmediateDominator - This method is used to update the dominator | |||
| 653 | /// tree information when a node's immediate dominator changes. | |||
| 654 | /// | |||
| 655 | void changeImmediateDominator(DomTreeNodeBase<NodeT> *N, | |||
| 656 | DomTreeNodeBase<NodeT> *NewIDom) { | |||
| 657 | assert(N && NewIDom && "Cannot change null node pointers!")((void)0); | |||
| 658 | DFSInfoValid = false; | |||
| 659 | N->setIDom(NewIDom); | |||
| 660 | } | |||
| 661 | ||||
| 662 | void changeImmediateDominator(NodeT *BB, NodeT *NewBB) { | |||
| 663 | changeImmediateDominator(getNode(BB), getNode(NewBB)); | |||
| 664 | } | |||
| 665 | ||||
| 666 | /// eraseNode - Removes a node from the dominator tree. Block must not | |||
| 667 | /// dominate any other blocks. Removes node from its immediate dominator's | |||
| 668 | /// children list. Deletes dominator node associated with basic block BB. | |||
| 669 | void eraseNode(NodeT *BB) { | |||
| 670 | DomTreeNodeBase<NodeT> *Node = getNode(BB); | |||
| 671 | assert(Node && "Removing node that isn't in dominator tree.")((void)0); | |||
| 672 | assert(Node->isLeaf() && "Node is not a leaf node.")((void)0); | |||
| 673 | ||||
| 674 | DFSInfoValid = false; | |||
| 675 | ||||
| 676 | // Remove node from immediate dominator's children list. | |||
| 677 | DomTreeNodeBase<NodeT> *IDom = Node->getIDom(); | |||
| 678 | if (IDom) { | |||
| 679 | const auto I = find(IDom->Children, Node); | |||
| 680 | assert(I != IDom->Children.end() &&((void)0) | |||
| 681 | "Not in immediate dominator children set!")((void)0); | |||
| 682 | // I am no longer your child... | |||
| 683 | IDom->Children.erase(I); | |||
| 684 | } | |||
| 685 | ||||
| 686 | DomTreeNodes.erase(BB); | |||
| 687 | ||||
| 688 | if (!IsPostDom) return; | |||
| 689 | ||||
| 690 | // Remember to update PostDominatorTree roots. | |||
| 691 | auto RIt = llvm::find(Roots, BB); | |||
| 692 | if (RIt != Roots.end()) { | |||
| 693 | std::swap(*RIt, Roots.back()); | |||
| 694 | Roots.pop_back(); | |||
| 695 | } | |||
| 696 | } | |||
| 697 | ||||
| 698 | /// splitBlock - BB is split and now it has one successor. Update dominator | |||
| 699 | /// tree to reflect this change. | |||
| 700 | void splitBlock(NodeT *NewBB) { | |||
| 701 | if (IsPostDominator) | |||
| 702 | Split<Inverse<NodeT *>>(NewBB); | |||
| 703 | else | |||
| 704 | Split<NodeT *>(NewBB); | |||
| 705 | } | |||
| 706 | ||||
| 707 | /// print - Convert to human readable form | |||
| 708 | /// | |||
| 709 | void print(raw_ostream &O) const { | |||
| 710 | O << "=============================--------------------------------\n"; | |||
| 711 | if (IsPostDominator) | |||
| 712 | O << "Inorder PostDominator Tree: "; | |||
| 713 | else | |||
| 714 | O << "Inorder Dominator Tree: "; | |||
| 715 | if (!DFSInfoValid) | |||
| 716 | O << "DFSNumbers invalid: " << SlowQueries << " slow queries."; | |||
| 717 | O << "\n"; | |||
| 718 | ||||
| 719 | // The postdom tree can have a null root if there are no returns. | |||
| 720 | if (getRootNode()) PrintDomTree<NodeT>(getRootNode(), O, 1); | |||
| 721 | O << "Roots: "; | |||
| 722 | for (const NodePtr Block : Roots) { | |||
| 723 | Block->printAsOperand(O, false); | |||
| 724 | O << " "; | |||
| 725 | } | |||
| 726 | O << "\n"; | |||
| 727 | } | |||
| 728 | ||||
| 729 | public: | |||
| 730 | /// updateDFSNumbers - Assign In and Out numbers to the nodes while walking | |||
| 731 | /// dominator tree in dfs order. | |||
| 732 | void updateDFSNumbers() const { | |||
| 733 | if (DFSInfoValid) { | |||
| 734 | SlowQueries = 0; | |||
| 735 | return; | |||
| 736 | } | |||
| 737 | ||||
| 738 | SmallVector<std::pair<const DomTreeNodeBase<NodeT> *, | |||
| 739 | typename DomTreeNodeBase<NodeT>::const_iterator>, | |||
| 740 | 32> WorkStack; | |||
| 741 | ||||
| 742 | const DomTreeNodeBase<NodeT> *ThisRoot = getRootNode(); | |||
| 743 | assert((!Parent || ThisRoot) && "Empty constructed DomTree")((void)0); | |||
| 744 | if (!ThisRoot) | |||
| 745 | return; | |||
| 746 | ||||
| 747 | // Both dominators and postdominators have a single root node. In the case | |||
| 748 | // case of PostDominatorTree, this node is a virtual root. | |||
| 749 | WorkStack.push_back({ThisRoot, ThisRoot->begin()}); | |||
| 750 | ||||
| 751 | unsigned DFSNum = 0; | |||
| 752 | ThisRoot->DFSNumIn = DFSNum++; | |||
| 753 | ||||
| 754 | while (!WorkStack.empty()) { | |||
| 755 | const DomTreeNodeBase<NodeT> *Node = WorkStack.back().first; | |||
| 756 | const auto ChildIt = WorkStack.back().second; | |||
| 757 | ||||
| 758 | // If we visited all of the children of this node, "recurse" back up the | |||
| 759 | // stack setting the DFOutNum. | |||
| 760 | if (ChildIt == Node->end()) { | |||
| 761 | Node->DFSNumOut = DFSNum++; | |||
| 762 | WorkStack.pop_back(); | |||
| 763 | } else { | |||
| 764 | // Otherwise, recursively visit this child. | |||
| 765 | const DomTreeNodeBase<NodeT> *Child = *ChildIt; | |||
| 766 | ++WorkStack.back().second; | |||
| 767 | ||||
| 768 | WorkStack.push_back({Child, Child->begin()}); | |||
| 769 | Child->DFSNumIn = DFSNum++; | |||
| 770 | } | |||
| 771 | } | |||
| 772 | ||||
| 773 | SlowQueries = 0; | |||
| 774 | DFSInfoValid = true; | |||
| 775 | } | |||
| 776 | ||||
| 777 | /// recalculate - compute a dominator tree for the given function | |||
| 778 | void recalculate(ParentType &Func) { | |||
| 779 | Parent = &Func; | |||
| 780 | DomTreeBuilder::Calculate(*this); | |||
| 781 | } | |||
| 782 | ||||
| 783 | void recalculate(ParentType &Func, ArrayRef<UpdateType> Updates) { | |||
| 784 | Parent = &Func; | |||
| 785 | DomTreeBuilder::CalculateWithUpdates(*this, Updates); | |||
| 786 | } | |||
| 787 | ||||
| 788 | /// verify - checks if the tree is correct. There are 3 level of verification: | |||
| 789 | /// - Full -- verifies if the tree is correct by making sure all the | |||
| 790 | /// properties (including the parent and the sibling property) | |||
| 791 | /// hold. | |||
| 792 | /// Takes O(N^3) time. | |||
| 793 | /// | |||
| 794 | /// - Basic -- checks if the tree is correct, but compares it to a freshly | |||
| 795 | /// constructed tree instead of checking the sibling property. | |||
| 796 | /// Takes O(N^2) time. | |||
| 797 | /// | |||
| 798 | /// - Fast -- checks basic tree structure and compares it with a freshly | |||
| 799 | /// constructed tree. | |||
| 800 | /// Takes O(N^2) time worst case, but is faster in practise (same | |||
| 801 | /// as tree construction). | |||
| 802 | bool verify(VerificationLevel VL = VerificationLevel::Full) const { | |||
| 803 | return DomTreeBuilder::Verify(*this, VL); | |||
| 804 | } | |||
| 805 | ||||
| 806 | void reset() { | |||
| 807 | DomTreeNodes.clear(); | |||
| 808 | Roots.clear(); | |||
| 809 | RootNode = nullptr; | |||
| 810 | Parent = nullptr; | |||
| 811 | DFSInfoValid = false; | |||
| 812 | SlowQueries = 0; | |||
| 813 | } | |||
| 814 | ||||
| 815 | protected: | |||
| 816 | void addRoot(NodeT *BB) { this->Roots.push_back(BB); } | |||
| 817 | ||||
| 818 | DomTreeNodeBase<NodeT> *createChild(NodeT *BB, DomTreeNodeBase<NodeT> *IDom) { | |||
| 819 | return (DomTreeNodes[BB] = IDom->addChild( | |||
| 820 | std::make_unique<DomTreeNodeBase<NodeT>>(BB, IDom))) | |||
| 821 | .get(); | |||
| 822 | } | |||
| 823 | ||||
| 824 | DomTreeNodeBase<NodeT> *createNode(NodeT *BB) { | |||
| 825 | return (DomTreeNodes[BB] = | |||
| 826 | std::make_unique<DomTreeNodeBase<NodeT>>(BB, nullptr)) | |||
| 827 | .get(); | |||
| 828 | } | |||
| 829 | ||||
| 830 | // NewBB is split and now it has one successor. Update dominator tree to | |||
| 831 | // reflect this change. | |||
| 832 | template <class N> | |||
| 833 | void Split(typename GraphTraits<N>::NodeRef NewBB) { | |||
| 834 | using GraphT = GraphTraits<N>; | |||
| 835 | using NodeRef = typename GraphT::NodeRef; | |||
| 836 | assert(std::distance(GraphT::child_begin(NewBB),((void)0) | |||
| 837 | GraphT::child_end(NewBB)) == 1 &&((void)0) | |||
| 838 | "NewBB should have a single successor!")((void)0); | |||
| 839 | NodeRef NewBBSucc = *GraphT::child_begin(NewBB); | |||
| 840 | ||||
| 841 | SmallVector<NodeRef, 4> PredBlocks(children<Inverse<N>>(NewBB)); | |||
| 842 | ||||
| 843 | assert(!PredBlocks.empty() && "No predblocks?")((void)0); | |||
| 844 | ||||
| 845 | bool NewBBDominatesNewBBSucc = true; | |||
| 846 | for (auto Pred : children<Inverse<N>>(NewBBSucc)) { | |||
| 847 | if (Pred != NewBB && !dominates(NewBBSucc, Pred) && | |||
| 848 | isReachableFromEntry(Pred)) { | |||
| 849 | NewBBDominatesNewBBSucc = false; | |||
| 850 | break; | |||
| 851 | } | |||
| 852 | } | |||
| 853 | ||||
| 854 | // Find NewBB's immediate dominator and create new dominator tree node for | |||
| 855 | // NewBB. | |||
| 856 | NodeT *NewBBIDom = nullptr; | |||
| 857 | unsigned i = 0; | |||
| 858 | for (i = 0; i < PredBlocks.size(); ++i) | |||
| 859 | if (isReachableFromEntry(PredBlocks[i])) { | |||
| 860 | NewBBIDom = PredBlocks[i]; | |||
| 861 | break; | |||
| 862 | } | |||
| 863 | ||||
| 864 | // It's possible that none of the predecessors of NewBB are reachable; | |||
| 865 | // in that case, NewBB itself is unreachable, so nothing needs to be | |||
| 866 | // changed. | |||
| 867 | if (!NewBBIDom) return; | |||
| 868 | ||||
| 869 | for (i = i + 1; i < PredBlocks.size(); ++i) { | |||
| 870 | if (isReachableFromEntry(PredBlocks[i])) | |||
| 871 | NewBBIDom = findNearestCommonDominator(NewBBIDom, PredBlocks[i]); | |||
| 872 | } | |||
| 873 | ||||
| 874 | // Create the new dominator tree node... and set the idom of NewBB. | |||
| 875 | DomTreeNodeBase<NodeT> *NewBBNode = addNewBlock(NewBB, NewBBIDom); | |||
| 876 | ||||
| 877 | // If NewBB strictly dominates other blocks, then it is now the immediate | |||
| 878 | // dominator of NewBBSucc. Update the dominator tree as appropriate. | |||
| 879 | if (NewBBDominatesNewBBSucc) { | |||
| 880 | DomTreeNodeBase<NodeT> *NewBBSuccNode = getNode(NewBBSucc); | |||
| 881 | changeImmediateDominator(NewBBSuccNode, NewBBNode); | |||
| 882 | } | |||
| 883 | } | |||
| 884 | ||||
| 885 | private: | |||
| 886 | bool dominatedBySlowTreeWalk(const DomTreeNodeBase<NodeT> *A, | |||
| 887 | const DomTreeNodeBase<NodeT> *B) const { | |||
| 888 | assert(A != B)((void)0); | |||
| 889 | assert(isReachableFromEntry(B))((void)0); | |||
| 890 | assert(isReachableFromEntry(A))((void)0); | |||
| 891 | ||||
| 892 | const unsigned ALevel = A->getLevel(); | |||
| 893 | const DomTreeNodeBase<NodeT> *IDom; | |||
| 894 | ||||
| 895 | // Don't walk nodes above A's subtree. When we reach A's level, we must | |||
| 896 | // either find A or be in some other subtree not dominated by A. | |||
| 897 | while ((IDom = B->getIDom()) != nullptr && IDom->getLevel() >= ALevel) | |||
| 898 | B = IDom; // Walk up the tree | |||
| 899 | ||||
| 900 | return B == A; | |||
| 901 | } | |||
| 902 | ||||
| 903 | /// Wipe this tree's state without releasing any resources. | |||
| 904 | /// | |||
| 905 | /// This is essentially a post-move helper only. It leaves the object in an | |||
| 906 | /// assignable and destroyable state, but otherwise invalid. | |||
| 907 | void wipe() { | |||
| 908 | DomTreeNodes.clear(); | |||
| 909 | RootNode = nullptr; | |||
| 910 | Parent = nullptr; | |||
| 911 | } | |||
| 912 | }; | |||
| 913 | ||||
| 914 | template <typename T> | |||
| 915 | using DomTreeBase = DominatorTreeBase<T, false>; | |||
| 916 | ||||
| 917 | template <typename T> | |||
| 918 | using PostDomTreeBase = DominatorTreeBase<T, true>; | |||
| 919 | ||||
| 920 | // These two functions are declared out of line as a workaround for building | |||
| 921 | // with old (< r147295) versions of clang because of pr11642. | |||
| 922 | template <typename NodeT, bool IsPostDom> | |||
| 923 | bool DominatorTreeBase<NodeT, IsPostDom>::dominates(const NodeT *A, | |||
| 924 | const NodeT *B) const { | |||
| 925 | if (A == B) | |||
| 926 | return true; | |||
| 927 | ||||
| 928 | // Cast away the const qualifiers here. This is ok since | |||
| 929 | // this function doesn't actually return the values returned | |||
| 930 | // from getNode. | |||
| 931 | return dominates(getNode(const_cast<NodeT *>(A)), | |||
| 932 | getNode(const_cast<NodeT *>(B))); | |||
| 933 | } | |||
| 934 | template <typename NodeT, bool IsPostDom> | |||
| 935 | bool DominatorTreeBase<NodeT, IsPostDom>::properlyDominates( | |||
| 936 | const NodeT *A, const NodeT *B) const { | |||
| 937 | if (A == B) | |||
| 938 | return false; | |||
| 939 | ||||
| 940 | // Cast away the const qualifiers here. This is ok since | |||
| 941 | // this function doesn't actually return the values returned | |||
| 942 | // from getNode. | |||
| 943 | return dominates(getNode(const_cast<NodeT *>(A)), | |||
| 944 | getNode(const_cast<NodeT *>(B))); | |||
| 945 | } | |||
| 946 | ||||
| 947 | } // end namespace llvm | |||
| 948 | ||||
| 949 | #endif // LLVM_SUPPORT_GENERICDOMTREE_H |
| 1 | //===- llvm/ADT/DenseMap.h - Dense probed hash table ------------*- 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 defines the DenseMap class. |
| 10 | // |
| 11 | //===----------------------------------------------------------------------===// |
| 12 | |
| 13 | #ifndef LLVM_ADT_DENSEMAP_H |
| 14 | #define LLVM_ADT_DENSEMAP_H |
| 15 | |
| 16 | #include "llvm/ADT/DenseMapInfo.h" |
| 17 | #include "llvm/ADT/EpochTracker.h" |
| 18 | #include "llvm/Support/AlignOf.h" |
| 19 | #include "llvm/Support/Compiler.h" |
| 20 | #include "llvm/Support/MathExtras.h" |
| 21 | #include "llvm/Support/MemAlloc.h" |
| 22 | #include "llvm/Support/ReverseIteration.h" |
| 23 | #include "llvm/Support/type_traits.h" |
| 24 | #include <algorithm> |
| 25 | #include <cassert> |
| 26 | #include <cstddef> |
| 27 | #include <cstring> |
| 28 | #include <initializer_list> |
| 29 | #include <iterator> |
| 30 | #include <new> |
| 31 | #include <type_traits> |
| 32 | #include <utility> |
| 33 | |
| 34 | namespace llvm { |
| 35 | |
| 36 | namespace detail { |
| 37 | |
| 38 | // We extend a pair to allow users to override the bucket type with their own |
| 39 | // implementation without requiring two members. |
| 40 | template <typename KeyT, typename ValueT> |
| 41 | struct DenseMapPair : public std::pair<KeyT, ValueT> { |
| 42 | using std::pair<KeyT, ValueT>::pair; |
| 43 | |
| 44 | KeyT &getFirst() { return std::pair<KeyT, ValueT>::first; } |
| 45 | const KeyT &getFirst() const { return std::pair<KeyT, ValueT>::first; } |
| 46 | ValueT &getSecond() { return std::pair<KeyT, ValueT>::second; } |
| 47 | const ValueT &getSecond() const { return std::pair<KeyT, ValueT>::second; } |
| 48 | }; |
| 49 | |
| 50 | } // end namespace detail |
| 51 | |
| 52 | template <typename KeyT, typename ValueT, |
| 53 | typename KeyInfoT = DenseMapInfo<KeyT>, |
| 54 | typename Bucket = llvm::detail::DenseMapPair<KeyT, ValueT>, |
| 55 | bool IsConst = false> |
| 56 | class DenseMapIterator; |
| 57 | |
| 58 | template <typename DerivedT, typename KeyT, typename ValueT, typename KeyInfoT, |
| 59 | typename BucketT> |
| 60 | class DenseMapBase : public DebugEpochBase { |
| 61 | template <typename T> |
| 62 | using const_arg_type_t = typename const_pointer_or_const_ref<T>::type; |
| 63 | |
| 64 | public: |
| 65 | using size_type = unsigned; |
| 66 | using key_type = KeyT; |
| 67 | using mapped_type = ValueT; |
| 68 | using value_type = BucketT; |
| 69 | |
| 70 | using iterator = DenseMapIterator<KeyT, ValueT, KeyInfoT, BucketT>; |
| 71 | using const_iterator = |
| 72 | DenseMapIterator<KeyT, ValueT, KeyInfoT, BucketT, true>; |
| 73 | |
| 74 | inline iterator begin() { |
| 75 | // When the map is empty, avoid the overhead of advancing/retreating past |
| 76 | // empty buckets. |
| 77 | if (empty()) |
| 78 | return end(); |
| 79 | if (shouldReverseIterate<KeyT>()) |
| 80 | return makeIterator(getBucketsEnd() - 1, getBuckets(), *this); |
| 81 | return makeIterator(getBuckets(), getBucketsEnd(), *this); |
| 82 | } |
| 83 | inline iterator end() { |
| 84 | return makeIterator(getBucketsEnd(), getBucketsEnd(), *this, true); |
| 85 | } |
| 86 | inline const_iterator begin() const { |
| 87 | if (empty()) |
| 88 | return end(); |
| 89 | if (shouldReverseIterate<KeyT>()) |
| 90 | return makeConstIterator(getBucketsEnd() - 1, getBuckets(), *this); |
| 91 | return makeConstIterator(getBuckets(), getBucketsEnd(), *this); |
| 92 | } |
| 93 | inline const_iterator end() const { |
| 94 | return makeConstIterator(getBucketsEnd(), getBucketsEnd(), *this, true); |
| 95 | } |
| 96 | |
| 97 | LLVM_NODISCARD[[clang::warn_unused_result]] bool empty() const { |
| 98 | return getNumEntries() == 0; |
| 99 | } |
| 100 | unsigned size() const { return getNumEntries(); } |
| 101 | |
| 102 | /// Grow the densemap so that it can contain at least \p NumEntries items |
| 103 | /// before resizing again. |
| 104 | void reserve(size_type NumEntries) { |
| 105 | auto NumBuckets = getMinBucketToReserveForEntries(NumEntries); |
| 106 | incrementEpoch(); |
| 107 | if (NumBuckets > getNumBuckets()) |
| 108 | grow(NumBuckets); |
| 109 | } |
| 110 | |
| 111 | void clear() { |
| 112 | incrementEpoch(); |
| 113 | if (getNumEntries() == 0 && getNumTombstones() == 0) return; |
| 114 | |
| 115 | // If the capacity of the array is huge, and the # elements used is small, |
| 116 | // shrink the array. |
| 117 | if (getNumEntries() * 4 < getNumBuckets() && getNumBuckets() > 64) { |
| 118 | shrink_and_clear(); |
| 119 | return; |
| 120 | } |
| 121 | |
| 122 | const KeyT EmptyKey = getEmptyKey(), TombstoneKey = getTombstoneKey(); |
| 123 | if (std::is_trivially_destructible<ValueT>::value) { |
| 124 | // Use a simpler loop when values don't need destruction. |
| 125 | for (BucketT *P = getBuckets(), *E = getBucketsEnd(); P != E; ++P) |
| 126 | P->getFirst() = EmptyKey; |
| 127 | } else { |
| 128 | unsigned NumEntries = getNumEntries(); |
| 129 | for (BucketT *P = getBuckets(), *E = getBucketsEnd(); P != E; ++P) { |
| 130 | if (!KeyInfoT::isEqual(P->getFirst(), EmptyKey)) { |
| 131 | if (!KeyInfoT::isEqual(P->getFirst(), TombstoneKey)) { |
| 132 | P->getSecond().~ValueT(); |
| 133 | --NumEntries; |
| 134 | } |
| 135 | P->getFirst() = EmptyKey; |
| 136 | } |
| 137 | } |
| 138 | assert(NumEntries == 0 && "Node count imbalance!")((void)0); |
| 139 | } |
| 140 | setNumEntries(0); |
| 141 | setNumTombstones(0); |
| 142 | } |
| 143 | |
| 144 | /// Return 1 if the specified key is in the map, 0 otherwise. |
| 145 | size_type count(const_arg_type_t<KeyT> Val) const { |
| 146 | const BucketT *TheBucket; |
| 147 | return LookupBucketFor(Val, TheBucket) ? 1 : 0; |
| 148 | } |
| 149 | |
| 150 | iterator find(const_arg_type_t<KeyT> Val) { |
| 151 | BucketT *TheBucket; |
| 152 | if (LookupBucketFor(Val, TheBucket)) |
| 153 | return makeIterator(TheBucket, |
| 154 | shouldReverseIterate<KeyT>() ? getBuckets() |
| 155 | : getBucketsEnd(), |
| 156 | *this, true); |
| 157 | return end(); |
| 158 | } |
| 159 | const_iterator find(const_arg_type_t<KeyT> Val) const { |
| 160 | const BucketT *TheBucket; |
| 161 | if (LookupBucketFor(Val, TheBucket)) |
| 162 | return makeConstIterator(TheBucket, |
| 163 | shouldReverseIterate<KeyT>() ? getBuckets() |
| 164 | : getBucketsEnd(), |
| 165 | *this, true); |
| 166 | return end(); |
| 167 | } |
| 168 | |
| 169 | /// Alternate version of find() which allows a different, and possibly |
| 170 | /// less expensive, key type. |
| 171 | /// The DenseMapInfo is responsible for supplying methods |
| 172 | /// getHashValue(LookupKeyT) and isEqual(LookupKeyT, KeyT) for each key |
| 173 | /// type used. |
| 174 | template<class LookupKeyT> |
| 175 | iterator find_as(const LookupKeyT &Val) { |
| 176 | BucketT *TheBucket; |
| 177 | if (LookupBucketFor(Val, TheBucket)) |
| 178 | return makeIterator(TheBucket, |
| 179 | shouldReverseIterate<KeyT>() ? getBuckets() |
| 180 | : getBucketsEnd(), |
| 181 | *this, true); |
| 182 | return end(); |
| 183 | } |
| 184 | template<class LookupKeyT> |
| 185 | const_iterator find_as(const LookupKeyT &Val) const { |
| 186 | const BucketT *TheBucket; |
| 187 | if (LookupBucketFor(Val, TheBucket)) |
| 188 | return makeConstIterator(TheBucket, |
| 189 | shouldReverseIterate<KeyT>() ? getBuckets() |
| 190 | : getBucketsEnd(), |
| 191 | *this, true); |
| 192 | return end(); |
| 193 | } |
| 194 | |
| 195 | /// lookup - Return the entry for the specified key, or a default |
| 196 | /// constructed value if no such entry exists. |
| 197 | ValueT lookup(const_arg_type_t<KeyT> Val) const { |
| 198 | const BucketT *TheBucket; |
| 199 | if (LookupBucketFor(Val, TheBucket)) |
| 200 | return TheBucket->getSecond(); |
| 201 | return ValueT(); |
| 202 | } |
| 203 | |
| 204 | // Inserts key,value pair into the map if the key isn't already in the map. |
| 205 | // If the key is already in the map, it returns false and doesn't update the |
| 206 | // value. |
| 207 | std::pair<iterator, bool> insert(const std::pair<KeyT, ValueT> &KV) { |
| 208 | return try_emplace(KV.first, KV.second); |
| 209 | } |
| 210 | |
| 211 | // Inserts key,value pair into the map if the key isn't already in the map. |
| 212 | // If the key is already in the map, it returns false and doesn't update the |
| 213 | // value. |
| 214 | std::pair<iterator, bool> insert(std::pair<KeyT, ValueT> &&KV) { |
| 215 | return try_emplace(std::move(KV.first), std::move(KV.second)); |
| 216 | } |
| 217 | |
| 218 | // Inserts key,value pair into the map if the key isn't already in the map. |
| 219 | // The value is constructed in-place if the key is not in the map, otherwise |
| 220 | // it is not moved. |
| 221 | template <typename... Ts> |
| 222 | std::pair<iterator, bool> try_emplace(KeyT &&Key, Ts &&... Args) { |
| 223 | BucketT *TheBucket; |
| 224 | if (LookupBucketFor(Key, TheBucket)) |
| 225 | return std::make_pair(makeIterator(TheBucket, |
| 226 | shouldReverseIterate<KeyT>() |
| 227 | ? getBuckets() |
| 228 | : getBucketsEnd(), |
| 229 | *this, true), |
| 230 | false); // Already in map. |
| 231 | |
| 232 | // Otherwise, insert the new element. |
| 233 | TheBucket = |
| 234 | InsertIntoBucket(TheBucket, std::move(Key), std::forward<Ts>(Args)...); |
| 235 | return std::make_pair(makeIterator(TheBucket, |
| 236 | shouldReverseIterate<KeyT>() |
| 237 | ? getBuckets() |
| 238 | : getBucketsEnd(), |
| 239 | *this, true), |
| 240 | true); |
| 241 | } |
| 242 | |
| 243 | // Inserts key,value pair into the map if the key isn't already in the map. |
| 244 | // The value is constructed in-place if the key is not in the map, otherwise |
| 245 | // it is not moved. |
| 246 | template <typename... Ts> |
| 247 | std::pair<iterator, bool> try_emplace(const KeyT &Key, Ts &&... Args) { |
| 248 | BucketT *TheBucket; |
| 249 | if (LookupBucketFor(Key, TheBucket)) |
| 250 | return std::make_pair(makeIterator(TheBucket, |
| 251 | shouldReverseIterate<KeyT>() |
| 252 | ? getBuckets() |
| 253 | : getBucketsEnd(), |
| 254 | *this, true), |
| 255 | false); // Already in map. |
| 256 | |
| 257 | // Otherwise, insert the new element. |
| 258 | TheBucket = InsertIntoBucket(TheBucket, Key, std::forward<Ts>(Args)...); |
| 259 | return std::make_pair(makeIterator(TheBucket, |
| 260 | shouldReverseIterate<KeyT>() |
| 261 | ? getBuckets() |
| 262 | : getBucketsEnd(), |
| 263 | *this, true), |
| 264 | true); |
| 265 | } |
| 266 | |
| 267 | /// Alternate version of insert() which allows a different, and possibly |
| 268 | /// less expensive, key type. |
| 269 | /// The DenseMapInfo is responsible for supplying methods |
| 270 | /// getHashValue(LookupKeyT) and isEqual(LookupKeyT, KeyT) for each key |
| 271 | /// type used. |
| 272 | template <typename LookupKeyT> |
| 273 | std::pair<iterator, bool> insert_as(std::pair<KeyT, ValueT> &&KV, |
| 274 | const LookupKeyT &Val) { |
| 275 | BucketT *TheBucket; |
| 276 | if (LookupBucketFor(Val, TheBucket)) |
| 277 | return std::make_pair(makeIterator(TheBucket, |
| 278 | shouldReverseIterate<KeyT>() |
| 279 | ? getBuckets() |
| 280 | : getBucketsEnd(), |
| 281 | *this, true), |
| 282 | false); // Already in map. |
| 283 | |
| 284 | // Otherwise, insert the new element. |
| 285 | TheBucket = InsertIntoBucketWithLookup(TheBucket, std::move(KV.first), |
| 286 | std::move(KV.second), Val); |
| 287 | return std::make_pair(makeIterator(TheBucket, |
| 288 | shouldReverseIterate<KeyT>() |
| 289 | ? getBuckets() |
| 290 | : getBucketsEnd(), |
| 291 | *this, true), |
| 292 | true); |
| 293 | } |
| 294 | |
| 295 | /// insert - Range insertion of pairs. |
| 296 | template<typename InputIt> |
| 297 | void insert(InputIt I, InputIt E) { |
| 298 | for (; I != E; ++I) |
| 299 | insert(*I); |
| 300 | } |
| 301 | |
| 302 | bool erase(const KeyT &Val) { |
| 303 | BucketT *TheBucket; |
| 304 | if (!LookupBucketFor(Val, TheBucket)) |
| 305 | return false; // not in map. |
| 306 | |
| 307 | TheBucket->getSecond().~ValueT(); |
| 308 | TheBucket->getFirst() = getTombstoneKey(); |
| 309 | decrementNumEntries(); |
| 310 | incrementNumTombstones(); |
| 311 | return true; |
| 312 | } |
| 313 | void erase(iterator I) { |
| 314 | BucketT *TheBucket = &*I; |
| 315 | TheBucket->getSecond().~ValueT(); |
| 316 | TheBucket->getFirst() = getTombstoneKey(); |
| 317 | decrementNumEntries(); |
| 318 | incrementNumTombstones(); |
| 319 | } |
| 320 | |
| 321 | value_type& FindAndConstruct(const KeyT &Key) { |
| 322 | BucketT *TheBucket; |
| 323 | if (LookupBucketFor(Key, TheBucket)) |
| 324 | return *TheBucket; |
| 325 | |
| 326 | return *InsertIntoBucket(TheBucket, Key); |
| 327 | } |
| 328 | |
| 329 | ValueT &operator[](const KeyT &Key) { |
| 330 | return FindAndConstruct(Key).second; |
| 331 | } |
| 332 | |
| 333 | value_type& FindAndConstruct(KeyT &&Key) { |
| 334 | BucketT *TheBucket; |
| 335 | if (LookupBucketFor(Key, TheBucket)) |
| 336 | return *TheBucket; |
| 337 | |
| 338 | return *InsertIntoBucket(TheBucket, std::move(Key)); |
| 339 | } |
| 340 | |
| 341 | ValueT &operator[](KeyT &&Key) { |
| 342 | return FindAndConstruct(std::move(Key)).second; |
| 343 | } |
| 344 | |
| 345 | /// isPointerIntoBucketsArray - Return true if the specified pointer points |
| 346 | /// somewhere into the DenseMap's array of buckets (i.e. either to a key or |
| 347 | /// value in the DenseMap). |
| 348 | bool isPointerIntoBucketsArray(const void *Ptr) const { |
| 349 | return Ptr >= getBuckets() && Ptr < getBucketsEnd(); |
| 350 | } |
| 351 | |
| 352 | /// getPointerIntoBucketsArray() - Return an opaque pointer into the buckets |
| 353 | /// array. In conjunction with the previous method, this can be used to |
| 354 | /// determine whether an insertion caused the DenseMap to reallocate. |
| 355 | const void *getPointerIntoBucketsArray() const { return getBuckets(); } |
| 356 | |
| 357 | protected: |
| 358 | DenseMapBase() = default; |
| 359 | |
| 360 | void destroyAll() { |
| 361 | if (getNumBuckets() == 0) // Nothing to do. |
| 362 | return; |
| 363 | |
| 364 | const KeyT EmptyKey = getEmptyKey(), TombstoneKey = getTombstoneKey(); |
| 365 | for (BucketT *P = getBuckets(), *E = getBucketsEnd(); P != E; ++P) { |
| 366 | if (!KeyInfoT::isEqual(P->getFirst(), EmptyKey) && |
| 367 | !KeyInfoT::isEqual(P->getFirst(), TombstoneKey)) |
| 368 | P->getSecond().~ValueT(); |
| 369 | P->getFirst().~KeyT(); |
| 370 | } |
| 371 | } |
| 372 | |
| 373 | void initEmpty() { |
| 374 | setNumEntries(0); |
| 375 | setNumTombstones(0); |
| 376 | |
| 377 | assert((getNumBuckets() & (getNumBuckets()-1)) == 0 &&((void)0) |
| 378 | "# initial buckets must be a power of two!")((void)0); |
| 379 | const KeyT EmptyKey = getEmptyKey(); |
| 380 | for (BucketT *B = getBuckets(), *E = getBucketsEnd(); B != E; ++B) |
| 381 | ::new (&B->getFirst()) KeyT(EmptyKey); |
| 382 | } |
| 383 | |
| 384 | /// Returns the number of buckets to allocate to ensure that the DenseMap can |
| 385 | /// accommodate \p NumEntries without need to grow(). |
| 386 | unsigned getMinBucketToReserveForEntries(unsigned NumEntries) { |
| 387 | // Ensure that "NumEntries * 4 < NumBuckets * 3" |
| 388 | if (NumEntries == 0) |
| 389 | return 0; |
| 390 | // +1 is required because of the strict equality. |
| 391 | // For example if NumEntries is 48, we need to return 401. |
| 392 | return NextPowerOf2(NumEntries * 4 / 3 + 1); |
| 393 | } |
| 394 | |
| 395 | void moveFromOldBuckets(BucketT *OldBucketsBegin, BucketT *OldBucketsEnd) { |
| 396 | initEmpty(); |
| 397 | |
| 398 | // Insert all the old elements. |
| 399 | const KeyT EmptyKey = getEmptyKey(); |
| 400 | const KeyT TombstoneKey = getTombstoneKey(); |
| 401 | for (BucketT *B = OldBucketsBegin, *E = OldBucketsEnd; B != E; ++B) { |
| 402 | if (!KeyInfoT::isEqual(B->getFirst(), EmptyKey) && |
| 403 | !KeyInfoT::isEqual(B->getFirst(), TombstoneKey)) { |
| 404 | // Insert the key/value into the new table. |
| 405 | BucketT *DestBucket; |
| 406 | bool FoundVal = LookupBucketFor(B->getFirst(), DestBucket); |
| 407 | (void)FoundVal; // silence warning. |
| 408 | assert(!FoundVal && "Key already in new map?")((void)0); |
| 409 | DestBucket->getFirst() = std::move(B->getFirst()); |
| 410 | ::new (&DestBucket->getSecond()) ValueT(std::move(B->getSecond())); |
| 411 | incrementNumEntries(); |
| 412 | |
| 413 | // Free the value. |
| 414 | B->getSecond().~ValueT(); |
| 415 | } |
| 416 | B->getFirst().~KeyT(); |
| 417 | } |
| 418 | } |
| 419 | |
| 420 | template <typename OtherBaseT> |
| 421 | void copyFrom( |
| 422 | const DenseMapBase<OtherBaseT, KeyT, ValueT, KeyInfoT, BucketT> &other) { |
| 423 | assert(&other != this)((void)0); |
| 424 | assert(getNumBuckets() == other.getNumBuckets())((void)0); |
| 425 | |
| 426 | setNumEntries(other.getNumEntries()); |
| 427 | setNumTombstones(other.getNumTombstones()); |
| 428 | |
| 429 | if (std::is_trivially_copyable<KeyT>::value && |
| 430 | std::is_trivially_copyable<ValueT>::value) |
| 431 | memcpy(reinterpret_cast<void *>(getBuckets()), other.getBuckets(), |
| 432 | getNumBuckets() * sizeof(BucketT)); |
| 433 | else |
| 434 | for (size_t i = 0; i < getNumBuckets(); ++i) { |
| 435 | ::new (&getBuckets()[i].getFirst()) |
| 436 | KeyT(other.getBuckets()[i].getFirst()); |
| 437 | if (!KeyInfoT::isEqual(getBuckets()[i].getFirst(), getEmptyKey()) && |
| 438 | !KeyInfoT::isEqual(getBuckets()[i].getFirst(), getTombstoneKey())) |
| 439 | ::new (&getBuckets()[i].getSecond()) |
| 440 | ValueT(other.getBuckets()[i].getSecond()); |
| 441 | } |
| 442 | } |
| 443 | |
| 444 | static unsigned getHashValue(const KeyT &Val) { |
| 445 | return KeyInfoT::getHashValue(Val); |
| 446 | } |
| 447 | |
| 448 | template<typename LookupKeyT> |
| 449 | static unsigned getHashValue(const LookupKeyT &Val) { |
| 450 | return KeyInfoT::getHashValue(Val); |
| 451 | } |
| 452 | |
| 453 | static const KeyT getEmptyKey() { |
| 454 | static_assert(std::is_base_of<DenseMapBase, DerivedT>::value, |
| 455 | "Must pass the derived type to this template!"); |
| 456 | return KeyInfoT::getEmptyKey(); |
| 457 | } |
| 458 | |
| 459 | static const KeyT getTombstoneKey() { |
| 460 | return KeyInfoT::getTombstoneKey(); |
| 461 | } |
| 462 | |
| 463 | private: |
| 464 | iterator makeIterator(BucketT *P, BucketT *E, |
| 465 | DebugEpochBase &Epoch, |
| 466 | bool NoAdvance=false) { |
| 467 | if (shouldReverseIterate<KeyT>()) { |
| 468 | BucketT *B = P == getBucketsEnd() ? getBuckets() : P + 1; |
| 469 | return iterator(B, E, Epoch, NoAdvance); |
| 470 | } |
| 471 | return iterator(P, E, Epoch, NoAdvance); |
| 472 | } |
| 473 | |
| 474 | const_iterator makeConstIterator(const BucketT *P, const BucketT *E, |
| 475 | const DebugEpochBase &Epoch, |
| 476 | const bool NoAdvance=false) const { |
| 477 | if (shouldReverseIterate<KeyT>()) { |
| 478 | const BucketT *B = P == getBucketsEnd() ? getBuckets() : P + 1; |
| 479 | return const_iterator(B, E, Epoch, NoAdvance); |
| 480 | } |
| 481 | return const_iterator(P, E, Epoch, NoAdvance); |
| 482 | } |
| 483 | |
| 484 | unsigned getNumEntries() const { |
| 485 | return static_cast<const DerivedT *>(this)->getNumEntries(); |
| 486 | } |
| 487 | |
| 488 | void setNumEntries(unsigned Num) { |
| 489 | static_cast<DerivedT *>(this)->setNumEntries(Num); |
| 490 | } |
| 491 | |
| 492 | void incrementNumEntries() { |
| 493 | setNumEntries(getNumEntries() + 1); |
| 494 | } |
| 495 | |
| 496 | void decrementNumEntries() { |
| 497 | setNumEntries(getNumEntries() - 1); |
| 498 | } |
| 499 | |
| 500 | unsigned getNumTombstones() const { |
| 501 | return static_cast<const DerivedT *>(this)->getNumTombstones(); |
| 502 | } |
| 503 | |
| 504 | void setNumTombstones(unsigned Num) { |
| 505 | static_cast<DerivedT *>(this)->setNumTombstones(Num); |
| 506 | } |
| 507 | |
| 508 | void incrementNumTombstones() { |
| 509 | setNumTombstones(getNumTombstones() + 1); |
| 510 | } |
| 511 | |
| 512 | void decrementNumTombstones() { |
| 513 | setNumTombstones(getNumTombstones() - 1); |
| 514 | } |
| 515 | |
| 516 | const BucketT *getBuckets() const { |
| 517 | return static_cast<const DerivedT *>(this)->getBuckets(); |
| 518 | } |
| 519 | |
| 520 | BucketT *getBuckets() { |
| 521 | return static_cast<DerivedT *>(this)->getBuckets(); |
| 522 | } |
| 523 | |
| 524 | unsigned getNumBuckets() const { |
| 525 | return static_cast<const DerivedT *>(this)->getNumBuckets(); |
| 526 | } |
| 527 | |
| 528 | BucketT *getBucketsEnd() { |
| 529 | return getBuckets() + getNumBuckets(); |
| 530 | } |
| 531 | |
| 532 | const BucketT *getBucketsEnd() const { |
| 533 | return getBuckets() + getNumBuckets(); |
| 534 | } |
| 535 | |
| 536 | void grow(unsigned AtLeast) { |
| 537 | static_cast<DerivedT *>(this)->grow(AtLeast); |
| 538 | } |
| 539 | |
| 540 | void shrink_and_clear() { |
| 541 | static_cast<DerivedT *>(this)->shrink_and_clear(); |
| 542 | } |
| 543 | |
| 544 | template <typename KeyArg, typename... ValueArgs> |
| 545 | BucketT *InsertIntoBucket(BucketT *TheBucket, KeyArg &&Key, |
| 546 | ValueArgs &&... Values) { |
| 547 | TheBucket = InsertIntoBucketImpl(Key, Key, TheBucket); |
| 548 | |
| 549 | TheBucket->getFirst() = std::forward<KeyArg>(Key); |
| 550 | ::new (&TheBucket->getSecond()) ValueT(std::forward<ValueArgs>(Values)...); |
| 551 | return TheBucket; |
| 552 | } |
| 553 | |
| 554 | template <typename LookupKeyT> |
| 555 | BucketT *InsertIntoBucketWithLookup(BucketT *TheBucket, KeyT &&Key, |
| 556 | ValueT &&Value, LookupKeyT &Lookup) { |
| 557 | TheBucket = InsertIntoBucketImpl(Key, Lookup, TheBucket); |
| 558 | |
| 559 | TheBucket->getFirst() = std::move(Key); |
| 560 | ::new (&TheBucket->getSecond()) ValueT(std::move(Value)); |
| 561 | return TheBucket; |
| 562 | } |
| 563 | |
| 564 | template <typename LookupKeyT> |
| 565 | BucketT *InsertIntoBucketImpl(const KeyT &Key, const LookupKeyT &Lookup, |
| 566 | BucketT *TheBucket) { |
| 567 | incrementEpoch(); |
| 568 | |
| 569 | // If the load of the hash table is more than 3/4, or if fewer than 1/8 of |
| 570 | // the buckets are empty (meaning that many are filled with tombstones), |
| 571 | // grow the table. |
| 572 | // |
| 573 | // The later case is tricky. For example, if we had one empty bucket with |
| 574 | // tons of tombstones, failing lookups (e.g. for insertion) would have to |
| 575 | // probe almost the entire table until it found the empty bucket. If the |
| 576 | // table completely filled with tombstones, no lookup would ever succeed, |
| 577 | // causing infinite loops in lookup. |
| 578 | unsigned NewNumEntries = getNumEntries() + 1; |
| 579 | unsigned NumBuckets = getNumBuckets(); |
| 580 | if (LLVM_UNLIKELY(NewNumEntries * 4 >= NumBuckets * 3)__builtin_expect((bool)(NewNumEntries * 4 >= NumBuckets * 3 ), false)) { |
| 581 | this->grow(NumBuckets * 2); |
| 582 | LookupBucketFor(Lookup, TheBucket); |
| 583 | NumBuckets = getNumBuckets(); |
| 584 | } else if (LLVM_UNLIKELY(NumBuckets-(NewNumEntries+getNumTombstones()) <=__builtin_expect((bool)(NumBuckets-(NewNumEntries+getNumTombstones ()) <= NumBuckets/8), false) |
| 585 | NumBuckets/8)__builtin_expect((bool)(NumBuckets-(NewNumEntries+getNumTombstones ()) <= NumBuckets/8), false)) { |
| 586 | this->grow(NumBuckets); |
| 587 | LookupBucketFor(Lookup, TheBucket); |
| 588 | } |
| 589 | assert(TheBucket)((void)0); |
| 590 | |
| 591 | // Only update the state after we've grown our bucket space appropriately |
| 592 | // so that when growing buckets we have self-consistent entry count. |
| 593 | incrementNumEntries(); |
| 594 | |
| 595 | // If we are writing over a tombstone, remember this. |
| 596 | const KeyT EmptyKey = getEmptyKey(); |
| 597 | if (!KeyInfoT::isEqual(TheBucket->getFirst(), EmptyKey)) |
| 598 | decrementNumTombstones(); |
| 599 | |
| 600 | return TheBucket; |
| 601 | } |
| 602 | |
| 603 | /// LookupBucketFor - Lookup the appropriate bucket for Val, returning it in |
| 604 | /// FoundBucket. If the bucket contains the key and a value, this returns |
| 605 | /// true, otherwise it returns a bucket with an empty marker or tombstone and |
| 606 | /// returns false. |
| 607 | template<typename LookupKeyT> |
| 608 | bool LookupBucketFor(const LookupKeyT &Val, |
| 609 | const BucketT *&FoundBucket) const { |
| 610 | const BucketT *BucketsPtr = getBuckets(); |
| 611 | const unsigned NumBuckets = getNumBuckets(); |
| 612 | |
| 613 | if (NumBuckets == 0) { |
| 614 | FoundBucket = nullptr; |
| 615 | return false; |
| 616 | } |
| 617 | |
| 618 | // FoundTombstone - Keep track of whether we find a tombstone while probing. |
| 619 | const BucketT *FoundTombstone = nullptr; |
| 620 | const KeyT EmptyKey = getEmptyKey(); |
| 621 | const KeyT TombstoneKey = getTombstoneKey(); |
| 622 | assert(!KeyInfoT::isEqual(Val, EmptyKey) &&((void)0) |
| 623 | !KeyInfoT::isEqual(Val, TombstoneKey) &&((void)0) |
| 624 | "Empty/Tombstone value shouldn't be inserted into map!")((void)0); |
| 625 | |
| 626 | unsigned BucketNo = getHashValue(Val) & (NumBuckets-1); |
| 627 | unsigned ProbeAmt = 1; |
| 628 | while (true) { |
| 629 | const BucketT *ThisBucket = BucketsPtr + BucketNo; |
| 630 | // Found Val's bucket? If so, return it. |
| 631 | if (LLVM_LIKELY(KeyInfoT::isEqual(Val, ThisBucket->getFirst()))__builtin_expect((bool)(KeyInfoT::isEqual(Val, ThisBucket-> getFirst())), true)) { |
| 632 | FoundBucket = ThisBucket; |
| 633 | return true; |
| 634 | } |
| 635 | |
| 636 | // If we found an empty bucket, the key doesn't exist in the set. |
| 637 | // Insert it and return the default value. |
| 638 | if (LLVM_LIKELY(KeyInfoT::isEqual(ThisBucket->getFirst(), EmptyKey))__builtin_expect((bool)(KeyInfoT::isEqual(ThisBucket->getFirst (), EmptyKey)), true)) { |
| 639 | // If we've already seen a tombstone while probing, fill it in instead |
| 640 | // of the empty bucket we eventually probed to. |
| 641 | FoundBucket = FoundTombstone ? FoundTombstone : ThisBucket; |
| 642 | return false; |
| 643 | } |
| 644 | |
| 645 | // If this is a tombstone, remember it. If Val ends up not in the map, we |
| 646 | // prefer to return it than something that would require more probing. |
| 647 | if (KeyInfoT::isEqual(ThisBucket->getFirst(), TombstoneKey) && |
| 648 | !FoundTombstone) |
| 649 | FoundTombstone = ThisBucket; // Remember the first tombstone found. |
| 650 | |
| 651 | // Otherwise, it's a hash collision or a tombstone, continue quadratic |
| 652 | // probing. |
| 653 | BucketNo += ProbeAmt++; |
| 654 | BucketNo &= (NumBuckets-1); |
| 655 | } |
| 656 | } |
| 657 | |
| 658 | template <typename LookupKeyT> |
| 659 | bool LookupBucketFor(const LookupKeyT &Val, BucketT *&FoundBucket) { |
| 660 | const BucketT *ConstFoundBucket; |
| 661 | bool Result = const_cast<const DenseMapBase *>(this) |
| 662 | ->LookupBucketFor(Val, ConstFoundBucket); |
| 663 | FoundBucket = const_cast<BucketT *>(ConstFoundBucket); |
| 664 | return Result; |
| 665 | } |
| 666 | |
| 667 | public: |
| 668 | /// Return the approximate size (in bytes) of the actual map. |
| 669 | /// This is just the raw memory used by DenseMap. |
| 670 | /// If entries are pointers to objects, the size of the referenced objects |
| 671 | /// are not included. |
| 672 | size_t getMemorySize() const { |
| 673 | return getNumBuckets() * sizeof(BucketT); |
| 674 | } |
| 675 | }; |
| 676 | |
| 677 | /// Equality comparison for DenseMap. |
| 678 | /// |
| 679 | /// Iterates over elements of LHS confirming that each (key, value) pair in LHS |
| 680 | /// is also in RHS, and that no additional pairs are in RHS. |
| 681 | /// Equivalent to N calls to RHS.find and N value comparisons. Amortized |
| 682 | /// complexity is linear, worst case is O(N^2) (if every hash collides). |
| 683 | template <typename DerivedT, typename KeyT, typename ValueT, typename KeyInfoT, |
| 684 | typename BucketT> |
| 685 | bool operator==( |
| 686 | const DenseMapBase<DerivedT, KeyT, ValueT, KeyInfoT, BucketT> &LHS, |
| 687 | const DenseMapBase<DerivedT, KeyT, ValueT, KeyInfoT, BucketT> &RHS) { |
| 688 | if (LHS.size() != RHS.size()) |
| 689 | return false; |
| 690 | |
| 691 | for (auto &KV : LHS) { |
| 692 | auto I = RHS.find(KV.first); |
| 693 | if (I == RHS.end() || I->second != KV.second) |
| 694 | return false; |
| 695 | } |
| 696 | |
| 697 | return true; |
| 698 | } |
| 699 | |
| 700 | /// Inequality comparison for DenseMap. |
| 701 | /// |
| 702 | /// Equivalent to !(LHS == RHS). See operator== for performance notes. |
| 703 | template <typename DerivedT, typename KeyT, typename ValueT, typename KeyInfoT, |
| 704 | typename BucketT> |
| 705 | bool operator!=( |
| 706 | const DenseMapBase<DerivedT, KeyT, ValueT, KeyInfoT, BucketT> &LHS, |
| 707 | const DenseMapBase<DerivedT, KeyT, ValueT, KeyInfoT, BucketT> &RHS) { |
| 708 | return !(LHS == RHS); |
| 709 | } |
| 710 | |
| 711 | template <typename KeyT, typename ValueT, |
| 712 | typename KeyInfoT = DenseMapInfo<KeyT>, |
| 713 | typename BucketT = llvm::detail::DenseMapPair<KeyT, ValueT>> |
| 714 | class DenseMap : public DenseMapBase<DenseMap<KeyT, ValueT, KeyInfoT, BucketT>, |
| 715 | KeyT, ValueT, KeyInfoT, BucketT> { |
| 716 | friend class DenseMapBase<DenseMap, KeyT, ValueT, KeyInfoT, BucketT>; |
| 717 | |
| 718 | // Lift some types from the dependent base class into this class for |
| 719 | // simplicity of referring to them. |
| 720 | using BaseT = DenseMapBase<DenseMap, KeyT, ValueT, KeyInfoT, BucketT>; |
| 721 | |
| 722 | BucketT *Buckets; |
| 723 | unsigned NumEntries; |
| 724 | unsigned NumTombstones; |
| 725 | unsigned NumBuckets; |
| 726 | |
| 727 | public: |
| 728 | /// Create a DenseMap with an optional \p InitialReserve that guarantee that |
| 729 | /// this number of elements can be inserted in the map without grow() |
| 730 | explicit DenseMap(unsigned InitialReserve = 0) { init(InitialReserve); } |
| 731 | |
| 732 | DenseMap(const DenseMap &other) : BaseT() { |
| 733 | init(0); |
| 734 | copyFrom(other); |
| 735 | } |
| 736 | |
| 737 | DenseMap(DenseMap &&other) : BaseT() { |
| 738 | init(0); |
| 739 | swap(other); |
| 740 | } |
| 741 | |
| 742 | template<typename InputIt> |
| 743 | DenseMap(const InputIt &I, const InputIt &E) { |
| 744 | init(std::distance(I, E)); |
| 745 | this->insert(I, E); |
| 746 | } |
| 747 | |
| 748 | DenseMap(std::initializer_list<typename BaseT::value_type> Vals) { |
| 749 | init(Vals.size()); |
| 750 | this->insert(Vals.begin(), Vals.end()); |
| 751 | } |
| 752 | |
| 753 | ~DenseMap() { |
| 754 | this->destroyAll(); |
| 755 | deallocate_buffer(Buckets, sizeof(BucketT) * NumBuckets, alignof(BucketT)); |
| 756 | } |
| 757 | |
| 758 | void swap(DenseMap& RHS) { |
| 759 | this->incrementEpoch(); |
| 760 | RHS.incrementEpoch(); |
| 761 | std::swap(Buckets, RHS.Buckets); |
| 762 | std::swap(NumEntries, RHS.NumEntries); |
| 763 | std::swap(NumTombstones, RHS.NumTombstones); |
| 764 | std::swap(NumBuckets, RHS.NumBuckets); |
| 765 | } |
| 766 | |
| 767 | DenseMap& operator=(const DenseMap& other) { |
| 768 | if (&other != this) |
| 769 | copyFrom(other); |
| 770 | return *this; |
| 771 | } |
| 772 | |
| 773 | DenseMap& operator=(DenseMap &&other) { |
| 774 | this->destroyAll(); |
| 775 | deallocate_buffer(Buckets, sizeof(BucketT) * NumBuckets, alignof(BucketT)); |
| 776 | init(0); |
| 777 | swap(other); |
| 778 | return *this; |
| 779 | } |
| 780 | |
| 781 | void copyFrom(const DenseMap& other) { |
| 782 | this->destroyAll(); |
| 783 | deallocate_buffer(Buckets, sizeof(BucketT) * NumBuckets, alignof(BucketT)); |
| 784 | if (allocateBuckets(other.NumBuckets)) { |
| 785 | this->BaseT::copyFrom(other); |
| 786 | } else { |
| 787 | NumEntries = 0; |
| 788 | NumTombstones = 0; |
| 789 | } |
| 790 | } |
| 791 | |
| 792 | void init(unsigned InitNumEntries) { |
| 793 | auto InitBuckets = BaseT::getMinBucketToReserveForEntries(InitNumEntries); |
| 794 | if (allocateBuckets(InitBuckets)) { |
| 795 | this->BaseT::initEmpty(); |
| 796 | } else { |
| 797 | NumEntries = 0; |
| 798 | NumTombstones = 0; |
| 799 | } |
| 800 | } |
| 801 | |
| 802 | void grow(unsigned AtLeast) { |
| 803 | unsigned OldNumBuckets = NumBuckets; |
| 804 | BucketT *OldBuckets = Buckets; |
| 805 | |
| 806 | allocateBuckets(std::max<unsigned>(64, static_cast<unsigned>(NextPowerOf2(AtLeast-1)))); |
| 807 | assert(Buckets)((void)0); |
| 808 | if (!OldBuckets) { |
| 809 | this->BaseT::initEmpty(); |
| 810 | return; |
| 811 | } |
| 812 | |
| 813 | this->moveFromOldBuckets(OldBuckets, OldBuckets+OldNumBuckets); |
| 814 | |
| 815 | // Free the old table. |
| 816 | deallocate_buffer(OldBuckets, sizeof(BucketT) * OldNumBuckets, |
| 817 | alignof(BucketT)); |
| 818 | } |
| 819 | |
| 820 | void shrink_and_clear() { |
| 821 | unsigned OldNumBuckets = NumBuckets; |
| 822 | unsigned OldNumEntries = NumEntries; |
| 823 | this->destroyAll(); |
| 824 | |
| 825 | // Reduce the number of buckets. |
| 826 | unsigned NewNumBuckets = 0; |
| 827 | if (OldNumEntries) |
| 828 | NewNumBuckets = std::max(64, 1 << (Log2_32_Ceil(OldNumEntries) + 1)); |
| 829 | if (NewNumBuckets == NumBuckets) { |
| 830 | this->BaseT::initEmpty(); |
| 831 | return; |
| 832 | } |
| 833 | |
| 834 | deallocate_buffer(Buckets, sizeof(BucketT) * OldNumBuckets, |
| 835 | alignof(BucketT)); |
| 836 | init(NewNumBuckets); |
| 837 | } |
| 838 | |
| 839 | private: |
| 840 | unsigned getNumEntries() const { |
| 841 | return NumEntries; |
| 842 | } |
| 843 | |
| 844 | void setNumEntries(unsigned Num) { |
| 845 | NumEntries = Num; |
| 846 | } |
| 847 | |
| 848 | unsigned getNumTombstones() const { |
| 849 | return NumTombstones; |
| 850 | } |
| 851 | |
| 852 | void setNumTombstones(unsigned Num) { |
| 853 | NumTombstones = Num; |
| 854 | } |
| 855 | |
| 856 | BucketT *getBuckets() const { |
| 857 | return Buckets; |
| 858 | } |
| 859 | |
| 860 | unsigned getNumBuckets() const { |
| 861 | return NumBuckets; |
| 862 | } |
| 863 | |
| 864 | bool allocateBuckets(unsigned Num) { |
| 865 | NumBuckets = Num; |
| 866 | if (NumBuckets == 0) { |
| 867 | Buckets = nullptr; |
| 868 | return false; |
| 869 | } |
| 870 | |
| 871 | Buckets = static_cast<BucketT *>( |
| 872 | allocate_buffer(sizeof(BucketT) * NumBuckets, alignof(BucketT))); |
| 873 | return true; |
| 874 | } |
| 875 | }; |
| 876 | |
| 877 | template <typename KeyT, typename ValueT, unsigned InlineBuckets = 4, |
| 878 | typename KeyInfoT = DenseMapInfo<KeyT>, |
| 879 | typename BucketT = llvm::detail::DenseMapPair<KeyT, ValueT>> |
| 880 | class SmallDenseMap |
| 881 | : public DenseMapBase< |
| 882 | SmallDenseMap<KeyT, ValueT, InlineBuckets, KeyInfoT, BucketT>, KeyT, |
| 883 | ValueT, KeyInfoT, BucketT> { |
| 884 | friend class DenseMapBase<SmallDenseMap, KeyT, ValueT, KeyInfoT, BucketT>; |
| 885 | |
| 886 | // Lift some types from the dependent base class into this class for |
| 887 | // simplicity of referring to them. |
| 888 | using BaseT = DenseMapBase<SmallDenseMap, KeyT, ValueT, KeyInfoT, BucketT>; |
| 889 | |
| 890 | static_assert(isPowerOf2_64(InlineBuckets), |
| 891 | "InlineBuckets must be a power of 2."); |
| 892 | |
| 893 | unsigned Small : 1; |
| 894 | unsigned NumEntries : 31; |
| 895 | unsigned NumTombstones; |
| 896 | |
| 897 | struct LargeRep { |
| 898 | BucketT *Buckets; |
| 899 | unsigned NumBuckets; |
| 900 | }; |
| 901 | |
| 902 | /// A "union" of an inline bucket array and the struct representing |
| 903 | /// a large bucket. This union will be discriminated by the 'Small' bit. |
| 904 | AlignedCharArrayUnion<BucketT[InlineBuckets], LargeRep> storage; |
| 905 | |
| 906 | public: |
| 907 | explicit SmallDenseMap(unsigned NumInitBuckets = 0) { |
| 908 | init(NumInitBuckets); |
| 909 | } |
| 910 | |
| 911 | SmallDenseMap(const SmallDenseMap &other) : BaseT() { |
| 912 | init(0); |
| 913 | copyFrom(other); |
| 914 | } |
| 915 | |
| 916 | SmallDenseMap(SmallDenseMap &&other) : BaseT() { |
| 917 | init(0); |
| 918 | swap(other); |
| 919 | } |
| 920 | |
| 921 | template<typename InputIt> |
| 922 | SmallDenseMap(const InputIt &I, const InputIt &E) { |
| 923 | init(NextPowerOf2(std::distance(I, E))); |
| 924 | this->insert(I, E); |
| 925 | } |
| 926 | |
| 927 | SmallDenseMap(std::initializer_list<typename BaseT::value_type> Vals) |
| 928 | : SmallDenseMap(Vals.begin(), Vals.end()) {} |
| 929 | |
| 930 | ~SmallDenseMap() { |
| 931 | this->destroyAll(); |
| 932 | deallocateBuckets(); |
| 933 | } |
| 934 | |
| 935 | void swap(SmallDenseMap& RHS) { |
| 936 | unsigned TmpNumEntries = RHS.NumEntries; |
| 937 | RHS.NumEntries = NumEntries; |
| 938 | NumEntries = TmpNumEntries; |
| 939 | std::swap(NumTombstones, RHS.NumTombstones); |
| 940 | |
| 941 | const KeyT EmptyKey = this->getEmptyKey(); |
| 942 | const KeyT TombstoneKey = this->getTombstoneKey(); |
| 943 | if (Small && RHS.Small) { |
| 944 | // If we're swapping inline bucket arrays, we have to cope with some of |
| 945 | // the tricky bits of DenseMap's storage system: the buckets are not |
| 946 | // fully initialized. Thus we swap every key, but we may have |
| 947 | // a one-directional move of the value. |
| 948 | for (unsigned i = 0, e = InlineBuckets; i != e; ++i) { |
| 949 | BucketT *LHSB = &getInlineBuckets()[i], |
| 950 | *RHSB = &RHS.getInlineBuckets()[i]; |
| 951 | bool hasLHSValue = (!KeyInfoT::isEqual(LHSB->getFirst(), EmptyKey) && |
| 952 | !KeyInfoT::isEqual(LHSB->getFirst(), TombstoneKey)); |
| 953 | bool hasRHSValue = (!KeyInfoT::isEqual(RHSB->getFirst(), EmptyKey) && |
| 954 | !KeyInfoT::isEqual(RHSB->getFirst(), TombstoneKey)); |
| 955 | if (hasLHSValue && hasRHSValue) { |
| 956 | // Swap together if we can... |
| 957 | std::swap(*LHSB, *RHSB); |
| 958 | continue; |
| 959 | } |
| 960 | // Swap separately and handle any asymmetry. |
| 961 | std::swap(LHSB->getFirst(), RHSB->getFirst()); |
| 962 | if (hasLHSValue) { |
| 963 | ::new (&RHSB->getSecond()) ValueT(std::move(LHSB->getSecond())); |
| 964 | LHSB->getSecond().~ValueT(); |
| 965 | } else if (hasRHSValue) { |
| 966 | ::new (&LHSB->getSecond()) ValueT(std::move(RHSB->getSecond())); |
| 967 | RHSB->getSecond().~ValueT(); |
| 968 | } |
| 969 | } |
| 970 | return; |
| 971 | } |
| 972 | if (!Small && !RHS.Small) { |
| 973 | std::swap(getLargeRep()->Buckets, RHS.getLargeRep()->Buckets); |
| 974 | std::swap(getLargeRep()->NumBuckets, RHS.getLargeRep()->NumBuckets); |
| 975 | return; |
| 976 | } |
| 977 | |
| 978 | SmallDenseMap &SmallSide = Small ? *this : RHS; |
| 979 | SmallDenseMap &LargeSide = Small ? RHS : *this; |
| 980 | |
| 981 | // First stash the large side's rep and move the small side across. |
| 982 | LargeRep TmpRep = std::move(*LargeSide.getLargeRep()); |
| 983 | LargeSide.getLargeRep()->~LargeRep(); |
| 984 | LargeSide.Small = true; |
| 985 | // This is similar to the standard move-from-old-buckets, but the bucket |
| 986 | // count hasn't actually rotated in this case. So we have to carefully |
| 987 | // move construct the keys and values into their new locations, but there |
| 988 | // is no need to re-hash things. |
| 989 | for (unsigned i = 0, e = InlineBuckets; i != e; ++i) { |
| 990 | BucketT *NewB = &LargeSide.getInlineBuckets()[i], |
| 991 | *OldB = &SmallSide.getInlineBuckets()[i]; |
| 992 | ::new (&NewB->getFirst()) KeyT(std::move(OldB->getFirst())); |
| 993 | OldB->getFirst().~KeyT(); |
| 994 | if (!KeyInfoT::isEqual(NewB->getFirst(), EmptyKey) && |
| 995 | !KeyInfoT::isEqual(NewB->getFirst(), TombstoneKey)) { |
| 996 | ::new (&NewB->getSecond()) ValueT(std::move(OldB->getSecond())); |
| 997 | OldB->getSecond().~ValueT(); |
| 998 | } |
| 999 | } |
| 1000 | |
| 1001 | // The hard part of moving the small buckets across is done, just move |
| 1002 | // the TmpRep into its new home. |
| 1003 | SmallSide.Small = false; |
| 1004 | new (SmallSide.getLargeRep()) LargeRep(std::move(TmpRep)); |
| 1005 | } |
| 1006 | |
| 1007 | SmallDenseMap& operator=(const SmallDenseMap& other) { |
| 1008 | if (&other != this) |
| 1009 | copyFrom(other); |
| 1010 | return *this; |
| 1011 | } |
| 1012 | |
| 1013 | SmallDenseMap& operator=(SmallDenseMap &&other) { |
| 1014 | this->destroyAll(); |
| 1015 | deallocateBuckets(); |
| 1016 | init(0); |
| 1017 | swap(other); |
| 1018 | return *this; |
| 1019 | } |
| 1020 | |
| 1021 | void copyFrom(const SmallDenseMap& other) { |
| 1022 | this->destroyAll(); |
| 1023 | deallocateBuckets(); |
| 1024 | Small = true; |
| 1025 | if (other.getNumBuckets() > InlineBuckets) { |
| 1026 | Small = false; |
| 1027 | new (getLargeRep()) LargeRep(allocateBuckets(other.getNumBuckets())); |
| 1028 | } |
| 1029 | this->BaseT::copyFrom(other); |
| 1030 | } |
| 1031 | |
| 1032 | void init(unsigned InitBuckets) { |
| 1033 | Small = true; |
| 1034 | if (InitBuckets > InlineBuckets) { |
| 1035 | Small = false; |
| 1036 | new (getLargeRep()) LargeRep(allocateBuckets(InitBuckets)); |
| 1037 | } |
| 1038 | this->BaseT::initEmpty(); |
| 1039 | } |
| 1040 | |
| 1041 | void grow(unsigned AtLeast) { |
| 1042 | if (AtLeast > InlineBuckets) |
| 1043 | AtLeast = std::max<unsigned>(64, NextPowerOf2(AtLeast-1)); |
| 1044 | |
| 1045 | if (Small) { |
| 1046 | // First move the inline buckets into a temporary storage. |
| 1047 | AlignedCharArrayUnion<BucketT[InlineBuckets]> TmpStorage; |
| 1048 | BucketT *TmpBegin = reinterpret_cast<BucketT *>(&TmpStorage); |
| 1049 | BucketT *TmpEnd = TmpBegin; |
| 1050 | |
| 1051 | // Loop over the buckets, moving non-empty, non-tombstones into the |
| 1052 | // temporary storage. Have the loop move the TmpEnd forward as it goes. |
| 1053 | const KeyT EmptyKey = this->getEmptyKey(); |
| 1054 | const KeyT TombstoneKey = this->getTombstoneKey(); |
| 1055 | for (BucketT *P = getBuckets(), *E = P + InlineBuckets; P != E; ++P) { |
| 1056 | if (!KeyInfoT::isEqual(P->getFirst(), EmptyKey) && |
| 1057 | !KeyInfoT::isEqual(P->getFirst(), TombstoneKey)) { |
| 1058 | assert(size_t(TmpEnd - TmpBegin) < InlineBuckets &&((void)0) |
| 1059 | "Too many inline buckets!")((void)0); |
| 1060 | ::new (&TmpEnd->getFirst()) KeyT(std::move(P->getFirst())); |
| 1061 | ::new (&TmpEnd->getSecond()) ValueT(std::move(P->getSecond())); |
| 1062 | ++TmpEnd; |
| 1063 | P->getSecond().~ValueT(); |
| 1064 | } |
| 1065 | P->getFirst().~KeyT(); |
| 1066 | } |
| 1067 | |
| 1068 | // AtLeast == InlineBuckets can happen if there are many tombstones, |
| 1069 | // and grow() is used to remove them. Usually we always switch to the |
| 1070 | // large rep here. |
| 1071 | if (AtLeast > InlineBuckets) { |
| 1072 | Small = false; |
| 1073 | new (getLargeRep()) LargeRep(allocateBuckets(AtLeast)); |
| 1074 | } |
| 1075 | this->moveFromOldBuckets(TmpBegin, TmpEnd); |
| 1076 | return; |
| 1077 | } |
| 1078 | |
| 1079 | LargeRep OldRep = std::move(*getLargeRep()); |
| 1080 | getLargeRep()->~LargeRep(); |
| 1081 | if (AtLeast <= InlineBuckets) { |
| 1082 | Small = true; |
| 1083 | } else { |
| 1084 | new (getLargeRep()) LargeRep(allocateBuckets(AtLeast)); |
| 1085 | } |
| 1086 | |
| 1087 | this->moveFromOldBuckets(OldRep.Buckets, OldRep.Buckets+OldRep.NumBuckets); |
| 1088 | |
| 1089 | // Free the old table. |
| 1090 | deallocate_buffer(OldRep.Buckets, sizeof(BucketT) * OldRep.NumBuckets, |
| 1091 | alignof(BucketT)); |
| 1092 | } |
| 1093 | |
| 1094 | void shrink_and_clear() { |
| 1095 | unsigned OldSize = this->size(); |
| 1096 | this->destroyAll(); |
| 1097 | |
| 1098 | // Reduce the number of buckets. |
| 1099 | unsigned NewNumBuckets = 0; |
| 1100 | if (OldSize) { |
| 1101 | NewNumBuckets = 1 << (Log2_32_Ceil(OldSize) + 1); |
| 1102 | if (NewNumBuckets > InlineBuckets && NewNumBuckets < 64u) |
| 1103 | NewNumBuckets = 64; |
| 1104 | } |
| 1105 | if ((Small && NewNumBuckets <= InlineBuckets) || |
| 1106 | (!Small && NewNumBuckets == getLargeRep()->NumBuckets)) { |
| 1107 | this->BaseT::initEmpty(); |
| 1108 | return; |
| 1109 | } |
| 1110 | |
| 1111 | deallocateBuckets(); |
| 1112 | init(NewNumBuckets); |
| 1113 | } |
| 1114 | |
| 1115 | private: |
| 1116 | unsigned getNumEntries() const { |
| 1117 | return NumEntries; |
| 1118 | } |
| 1119 | |
| 1120 | void setNumEntries(unsigned Num) { |
| 1121 | // NumEntries is hardcoded to be 31 bits wide. |
| 1122 | assert(Num < (1U << 31) && "Cannot support more than 1<<31 entries")((void)0); |
| 1123 | NumEntries = Num; |
| 1124 | } |
| 1125 | |
| 1126 | unsigned getNumTombstones() const { |
| 1127 | return NumTombstones; |
| 1128 | } |
| 1129 | |
| 1130 | void setNumTombstones(unsigned Num) { |
| 1131 | NumTombstones = Num; |
| 1132 | } |
| 1133 | |
| 1134 | const BucketT *getInlineBuckets() const { |
| 1135 | assert(Small)((void)0); |
| 1136 | // Note that this cast does not violate aliasing rules as we assert that |
| 1137 | // the memory's dynamic type is the small, inline bucket buffer, and the |
| 1138 | // 'storage' is a POD containing a char buffer. |
| 1139 | return reinterpret_cast<const BucketT *>(&storage); |
| 1140 | } |
| 1141 | |
| 1142 | BucketT *getInlineBuckets() { |
| 1143 | return const_cast<BucketT *>( |
| 1144 | const_cast<const SmallDenseMap *>(this)->getInlineBuckets()); |
| 1145 | } |
| 1146 | |
| 1147 | const LargeRep *getLargeRep() const { |
| 1148 | assert(!Small)((void)0); |
| 1149 | // Note, same rule about aliasing as with getInlineBuckets. |
| 1150 | return reinterpret_cast<const LargeRep *>(&storage); |
| 1151 | } |
| 1152 | |
| 1153 | LargeRep *getLargeRep() { |
| 1154 | return const_cast<LargeRep *>( |
| 1155 | const_cast<const SmallDenseMap *>(this)->getLargeRep()); |
| 1156 | } |
| 1157 | |
| 1158 | const BucketT *getBuckets() const { |
| 1159 | return Small ? getInlineBuckets() : getLargeRep()->Buckets; |
| 1160 | } |
| 1161 | |
| 1162 | BucketT *getBuckets() { |
| 1163 | return const_cast<BucketT *>( |
| 1164 | const_cast<const SmallDenseMap *>(this)->getBuckets()); |
| 1165 | } |
| 1166 | |
| 1167 | unsigned getNumBuckets() const { |
| 1168 | return Small ? InlineBuckets : getLargeRep()->NumBuckets; |
| 1169 | } |
| 1170 | |
| 1171 | void deallocateBuckets() { |
| 1172 | if (Small) |
| 1173 | return; |
| 1174 | |
| 1175 | deallocate_buffer(getLargeRep()->Buckets, |
| 1176 | sizeof(BucketT) * getLargeRep()->NumBuckets, |
| 1177 | alignof(BucketT)); |
| 1178 | getLargeRep()->~LargeRep(); |
| 1179 | } |
| 1180 | |
| 1181 | LargeRep allocateBuckets(unsigned Num) { |
| 1182 | assert(Num > InlineBuckets && "Must allocate more buckets than are inline")((void)0); |
| 1183 | LargeRep Rep = {static_cast<BucketT *>(allocate_buffer( |
| 1184 | sizeof(BucketT) * Num, alignof(BucketT))), |
| 1185 | Num}; |
| 1186 | return Rep; |
| 1187 | } |
| 1188 | }; |
| 1189 | |
| 1190 | template <typename KeyT, typename ValueT, typename KeyInfoT, typename Bucket, |
| 1191 | bool IsConst> |
| 1192 | class DenseMapIterator : DebugEpochBase::HandleBase { |
| 1193 | friend class DenseMapIterator<KeyT, ValueT, KeyInfoT, Bucket, true>; |
| 1194 | friend class DenseMapIterator<KeyT, ValueT, KeyInfoT, Bucket, false>; |
| 1195 | |
| 1196 | public: |
| 1197 | using difference_type = ptrdiff_t; |
| 1198 | using value_type = |
| 1199 | typename std::conditional<IsConst, const Bucket, Bucket>::type; |
| 1200 | using pointer = value_type *; |
| 1201 | using reference = value_type &; |
| 1202 | using iterator_category = std::forward_iterator_tag; |
| 1203 | |
| 1204 | private: |
| 1205 | pointer Ptr = nullptr; |
| 1206 | pointer End = nullptr; |
| 1207 | |
| 1208 | public: |
| 1209 | DenseMapIterator() = default; |
| 1210 | |
| 1211 | DenseMapIterator(pointer Pos, pointer E, const DebugEpochBase &Epoch, |
| 1212 | bool NoAdvance = false) |
| 1213 | : DebugEpochBase::HandleBase(&Epoch), Ptr(Pos), End(E) { |
| 1214 | assert(isHandleInSync() && "invalid construction!")((void)0); |
| 1215 | |
| 1216 | if (NoAdvance) return; |
| 1217 | if (shouldReverseIterate<KeyT>()) { |
| 1218 | RetreatPastEmptyBuckets(); |
| 1219 | return; |
| 1220 | } |
| 1221 | AdvancePastEmptyBuckets(); |
| 1222 | } |
| 1223 | |
| 1224 | // Converting ctor from non-const iterators to const iterators. SFINAE'd out |
| 1225 | // for const iterator destinations so it doesn't end up as a user defined copy |
| 1226 | // constructor. |
| 1227 | template <bool IsConstSrc, |
| 1228 | typename = std::enable_if_t<!IsConstSrc && IsConst>> |
| 1229 | DenseMapIterator( |
| 1230 | const DenseMapIterator<KeyT, ValueT, KeyInfoT, Bucket, IsConstSrc> &I) |
| 1231 | : DebugEpochBase::HandleBase(I), Ptr(I.Ptr), End(I.End) {} |
| 1232 | |
| 1233 | reference operator*() const { |
| 1234 | assert(isHandleInSync() && "invalid iterator access!")((void)0); |
| 1235 | assert(Ptr != End && "dereferencing end() iterator")((void)0); |
| 1236 | if (shouldReverseIterate<KeyT>()) |
| 1237 | return Ptr[-1]; |
| 1238 | return *Ptr; |
| 1239 | } |
| 1240 | pointer operator->() const { |
| 1241 | assert(isHandleInSync() && "invalid iterator access!")((void)0); |
| 1242 | assert(Ptr != End && "dereferencing end() iterator")((void)0); |
| 1243 | if (shouldReverseIterate<KeyT>()) |
| 1244 | return &(Ptr[-1]); |
| 1245 | return Ptr; |
| 1246 | } |
| 1247 | |
| 1248 | friend bool operator==(const DenseMapIterator &LHS, |
| 1249 | const DenseMapIterator &RHS) { |
| 1250 | assert((!LHS.Ptr || LHS.isHandleInSync()) && "handle not in sync!")((void)0); |
| 1251 | assert((!RHS.Ptr || RHS.isHandleInSync()) && "handle not in sync!")((void)0); |
| 1252 | assert(LHS.getEpochAddress() == RHS.getEpochAddress() &&((void)0) |
| 1253 | "comparing incomparable iterators!")((void)0); |
| 1254 | return LHS.Ptr == RHS.Ptr; |
| 1255 | } |
| 1256 | |
| 1257 | friend bool operator!=(const DenseMapIterator &LHS, |
| 1258 | const DenseMapIterator &RHS) { |
| 1259 | return !(LHS == RHS); |
| 1260 | } |
| 1261 | |
| 1262 | inline DenseMapIterator& operator++() { // Preincrement |
| 1263 | assert(isHandleInSync() && "invalid iterator access!")((void)0); |
| 1264 | assert(Ptr != End && "incrementing end() iterator")((void)0); |
| 1265 | if (shouldReverseIterate<KeyT>()) { |
| 1266 | --Ptr; |
| 1267 | RetreatPastEmptyBuckets(); |
| 1268 | return *this; |
| 1269 | } |
| 1270 | ++Ptr; |
| 1271 | AdvancePastEmptyBuckets(); |
| 1272 | return *this; |
| 1273 | } |
| 1274 | DenseMapIterator operator++(int) { // Postincrement |
| 1275 | assert(isHandleInSync() && "invalid iterator access!")((void)0); |
| 1276 | DenseMapIterator tmp = *this; ++*this; return tmp; |
| 1277 | } |
| 1278 | |
| 1279 | private: |
| 1280 | void AdvancePastEmptyBuckets() { |
| 1281 | assert(Ptr <= End)((void)0); |
| 1282 | const KeyT Empty = KeyInfoT::getEmptyKey(); |
| 1283 | const KeyT Tombstone = KeyInfoT::getTombstoneKey(); |
| 1284 | |
| 1285 | while (Ptr != End && (KeyInfoT::isEqual(Ptr->getFirst(), Empty) || |
| 1286 | KeyInfoT::isEqual(Ptr->getFirst(), Tombstone))) |
| 1287 | ++Ptr; |
| 1288 | } |
| 1289 | |
| 1290 | void RetreatPastEmptyBuckets() { |
| 1291 | assert(Ptr >= End)((void)0); |
| 1292 | const KeyT Empty = KeyInfoT::getEmptyKey(); |
| 1293 | const KeyT Tombstone = KeyInfoT::getTombstoneKey(); |
| 1294 | |
| 1295 | while (Ptr != End && (KeyInfoT::isEqual(Ptr[-1].getFirst(), Empty) || |
| 1296 | KeyInfoT::isEqual(Ptr[-1].getFirst(), Tombstone))) |
| 1297 | --Ptr; |
| 1298 | } |
| 1299 | }; |
| 1300 | |
| 1301 | template <typename KeyT, typename ValueT, typename KeyInfoT> |
| 1302 | inline size_t capacity_in_bytes(const DenseMap<KeyT, ValueT, KeyInfoT> &X) { |
| 1303 | return X.getMemorySize(); |
| 1304 | } |
| 1305 | |
| 1306 | } // end namespace llvm |
| 1307 | |
| 1308 | #endif // LLVM_ADT_DENSEMAP_H |