Kyle Butt | 3232dbb | 2016-04-08 20:35:01 +0000 | [diff] [blame] | 1 | //===-- TailDuplicator.cpp - Duplicate blocks into predecessors' tails ---===// |
| 2 | // |
| 3 | // The LLVM Compiler Infrastructure |
| 4 | // |
| 5 | // This file is distributed under the University of Illinois Open Source |
| 6 | // License. See LICENSE.TXT for details. |
| 7 | // |
| 8 | //===----------------------------------------------------------------------===// |
| 9 | // |
| 10 | // This utility class duplicates basic blocks ending in unconditional branches |
| 11 | // into the tails of their predecessors. |
| 12 | // |
| 13 | //===----------------------------------------------------------------------===// |
| 14 | |
| 15 | #include "llvm/CodeGen/TailDuplicator.h" |
| 16 | #include "llvm/ADT/DenseSet.h" |
| 17 | #include "llvm/ADT/SetVector.h" |
| 18 | #include "llvm/ADT/SmallSet.h" |
| 19 | #include "llvm/ADT/Statistic.h" |
| 20 | #include "llvm/CodeGen/MachineBranchProbabilityInfo.h" |
| 21 | #include "llvm/CodeGen/MachineFunctionPass.h" |
| 22 | #include "llvm/CodeGen/MachineInstrBuilder.h" |
| 23 | #include "llvm/CodeGen/MachineModuleInfo.h" |
| 24 | #include "llvm/CodeGen/Passes.h" |
| 25 | #include "llvm/IR/Function.h" |
| 26 | #include "llvm/Support/CommandLine.h" |
| 27 | #include "llvm/Support/Debug.h" |
| 28 | #include "llvm/Support/ErrorHandling.h" |
| 29 | #include "llvm/Support/raw_ostream.h" |
| 30 | using namespace llvm; |
| 31 | |
| 32 | #define DEBUG_TYPE "tailduplication" |
| 33 | |
| 34 | STATISTIC(NumTails, "Number of tails duplicated"); |
| 35 | STATISTIC(NumTailDups, "Number of tail duplicated blocks"); |
Geoff Berry | f8c29d6 | 2016-06-14 19:40:10 +0000 | [diff] [blame] | 36 | STATISTIC(NumTailDupAdded, |
| 37 | "Number of instructions added due to tail duplication"); |
| 38 | STATISTIC(NumTailDupRemoved, |
| 39 | "Number of instructions removed due to tail duplication"); |
Kyle Butt | 3232dbb | 2016-04-08 20:35:01 +0000 | [diff] [blame] | 40 | STATISTIC(NumDeadBlocks, "Number of dead blocks removed"); |
| 41 | STATISTIC(NumAddedPHIs, "Number of phis added"); |
| 42 | |
| 43 | // Heuristic for tail duplication. |
| 44 | static cl::opt<unsigned> TailDuplicateSize( |
| 45 | "tail-dup-size", |
| 46 | cl::desc("Maximum instructions to consider tail duplicating"), cl::init(2), |
| 47 | cl::Hidden); |
| 48 | |
| 49 | static cl::opt<bool> |
| 50 | TailDupVerify("tail-dup-verify", |
| 51 | cl::desc("Verify sanity of PHI instructions during taildup"), |
| 52 | cl::init(false), cl::Hidden); |
| 53 | |
| 54 | static cl::opt<unsigned> TailDupLimit("tail-dup-limit", cl::init(~0U), |
| 55 | cl::Hidden); |
| 56 | |
| 57 | namespace llvm { |
| 58 | |
| 59 | void TailDuplicator::initMF(MachineFunction &MF, const MachineModuleInfo *MMIin, |
| 60 | const MachineBranchProbabilityInfo *MBPIin) { |
| 61 | TII = MF.getSubtarget().getInstrInfo(); |
| 62 | TRI = MF.getSubtarget().getRegisterInfo(); |
| 63 | MRI = &MF.getRegInfo(); |
| 64 | MMI = MMIin; |
| 65 | MBPI = MBPIin; |
| 66 | |
| 67 | assert(MBPI != nullptr && "Machine Branch Probability Info required"); |
| 68 | |
| 69 | PreRegAlloc = MRI->isSSA(); |
Kyle Butt | 3232dbb | 2016-04-08 20:35:01 +0000 | [diff] [blame] | 70 | } |
| 71 | |
| 72 | static void VerifyPHIs(MachineFunction &MF, bool CheckExtra) { |
| 73 | for (MachineFunction::iterator I = ++MF.begin(), E = MF.end(); I != E; ++I) { |
| 74 | MachineBasicBlock *MBB = &*I; |
| 75 | SmallSetVector<MachineBasicBlock *, 8> Preds(MBB->pred_begin(), |
| 76 | MBB->pred_end()); |
| 77 | MachineBasicBlock::iterator MI = MBB->begin(); |
| 78 | while (MI != MBB->end()) { |
| 79 | if (!MI->isPHI()) |
| 80 | break; |
| 81 | for (SmallSetVector<MachineBasicBlock *, 8>::iterator PI = Preds.begin(), |
| 82 | PE = Preds.end(); |
| 83 | PI != PE; ++PI) { |
| 84 | MachineBasicBlock *PredBB = *PI; |
| 85 | bool Found = false; |
| 86 | for (unsigned i = 1, e = MI->getNumOperands(); i != e; i += 2) { |
| 87 | MachineBasicBlock *PHIBB = MI->getOperand(i + 1).getMBB(); |
| 88 | if (PHIBB == PredBB) { |
| 89 | Found = true; |
| 90 | break; |
| 91 | } |
| 92 | } |
| 93 | if (!Found) { |
| 94 | dbgs() << "Malformed PHI in BB#" << MBB->getNumber() << ": " << *MI; |
| 95 | dbgs() << " missing input from predecessor BB#" |
| 96 | << PredBB->getNumber() << '\n'; |
| 97 | llvm_unreachable(nullptr); |
| 98 | } |
| 99 | } |
| 100 | |
| 101 | for (unsigned i = 1, e = MI->getNumOperands(); i != e; i += 2) { |
| 102 | MachineBasicBlock *PHIBB = MI->getOperand(i + 1).getMBB(); |
| 103 | if (CheckExtra && !Preds.count(PHIBB)) { |
| 104 | dbgs() << "Warning: malformed PHI in BB#" << MBB->getNumber() << ": " |
| 105 | << *MI; |
| 106 | dbgs() << " extra input from predecessor BB#" << PHIBB->getNumber() |
| 107 | << '\n'; |
| 108 | llvm_unreachable(nullptr); |
| 109 | } |
| 110 | if (PHIBB->getNumber() < 0) { |
| 111 | dbgs() << "Malformed PHI in BB#" << MBB->getNumber() << ": " << *MI; |
| 112 | dbgs() << " non-existing BB#" << PHIBB->getNumber() << '\n'; |
| 113 | llvm_unreachable(nullptr); |
| 114 | } |
| 115 | } |
| 116 | ++MI; |
| 117 | } |
| 118 | } |
| 119 | } |
| 120 | |
| 121 | /// Tail duplicate the block and cleanup. |
| 122 | bool TailDuplicator::tailDuplicateAndUpdate(MachineFunction &MF, bool IsSimple, |
| 123 | MachineBasicBlock *MBB) { |
| 124 | // Save the successors list. |
| 125 | SmallSetVector<MachineBasicBlock *, 8> Succs(MBB->succ_begin(), |
| 126 | MBB->succ_end()); |
| 127 | |
| 128 | SmallVector<MachineBasicBlock *, 8> TDBBs; |
| 129 | SmallVector<MachineInstr *, 16> Copies; |
| 130 | if (!tailDuplicate(MF, IsSimple, MBB, TDBBs, Copies)) |
| 131 | return false; |
| 132 | |
| 133 | ++NumTails; |
| 134 | |
| 135 | SmallVector<MachineInstr *, 8> NewPHIs; |
| 136 | MachineSSAUpdater SSAUpdate(MF, &NewPHIs); |
| 137 | |
| 138 | // TailBB's immediate successors are now successors of those predecessors |
| 139 | // which duplicated TailBB. Add the predecessors as sources to the PHI |
| 140 | // instructions. |
| 141 | bool isDead = MBB->pred_empty() && !MBB->hasAddressTaken(); |
| 142 | if (PreRegAlloc) |
| 143 | updateSuccessorsPHIs(MBB, isDead, TDBBs, Succs); |
| 144 | |
| 145 | // If it is dead, remove it. |
| 146 | if (isDead) { |
Geoff Berry | f8c29d6 | 2016-06-14 19:40:10 +0000 | [diff] [blame] | 147 | NumTailDupRemoved += MBB->size(); |
Kyle Butt | 3232dbb | 2016-04-08 20:35:01 +0000 | [diff] [blame] | 148 | removeDeadBlock(MBB); |
| 149 | ++NumDeadBlocks; |
| 150 | } |
| 151 | |
| 152 | // Update SSA form. |
| 153 | if (!SSAUpdateVRs.empty()) { |
| 154 | for (unsigned i = 0, e = SSAUpdateVRs.size(); i != e; ++i) { |
| 155 | unsigned VReg = SSAUpdateVRs[i]; |
| 156 | SSAUpdate.Initialize(VReg); |
| 157 | |
| 158 | // If the original definition is still around, add it as an available |
| 159 | // value. |
| 160 | MachineInstr *DefMI = MRI->getVRegDef(VReg); |
| 161 | MachineBasicBlock *DefBB = nullptr; |
| 162 | if (DefMI) { |
| 163 | DefBB = DefMI->getParent(); |
| 164 | SSAUpdate.AddAvailableValue(DefBB, VReg); |
| 165 | } |
| 166 | |
| 167 | // Add the new vregs as available values. |
| 168 | DenseMap<unsigned, AvailableValsTy>::iterator LI = |
| 169 | SSAUpdateVals.find(VReg); |
| 170 | for (unsigned j = 0, ee = LI->second.size(); j != ee; ++j) { |
| 171 | MachineBasicBlock *SrcBB = LI->second[j].first; |
| 172 | unsigned SrcReg = LI->second[j].second; |
| 173 | SSAUpdate.AddAvailableValue(SrcBB, SrcReg); |
| 174 | } |
| 175 | |
| 176 | // Rewrite uses that are outside of the original def's block. |
| 177 | MachineRegisterInfo::use_iterator UI = MRI->use_begin(VReg); |
| 178 | while (UI != MRI->use_end()) { |
| 179 | MachineOperand &UseMO = *UI; |
| 180 | MachineInstr *UseMI = UseMO.getParent(); |
| 181 | ++UI; |
| 182 | if (UseMI->isDebugValue()) { |
| 183 | // SSAUpdate can replace the use with an undef. That creates |
| 184 | // a debug instruction that is a kill. |
| 185 | // FIXME: Should it SSAUpdate job to delete debug instructions |
| 186 | // instead of replacing the use with undef? |
| 187 | UseMI->eraseFromParent(); |
| 188 | continue; |
| 189 | } |
| 190 | if (UseMI->getParent() == DefBB && !UseMI->isPHI()) |
| 191 | continue; |
| 192 | SSAUpdate.RewriteUse(UseMO); |
| 193 | } |
| 194 | } |
| 195 | |
| 196 | SSAUpdateVRs.clear(); |
| 197 | SSAUpdateVals.clear(); |
| 198 | } |
| 199 | |
| 200 | // Eliminate some of the copies inserted by tail duplication to maintain |
| 201 | // SSA form. |
| 202 | for (unsigned i = 0, e = Copies.size(); i != e; ++i) { |
| 203 | MachineInstr *Copy = Copies[i]; |
| 204 | if (!Copy->isCopy()) |
| 205 | continue; |
| 206 | unsigned Dst = Copy->getOperand(0).getReg(); |
| 207 | unsigned Src = Copy->getOperand(1).getReg(); |
| 208 | if (MRI->hasOneNonDBGUse(Src) && |
| 209 | MRI->constrainRegClass(Src, MRI->getRegClass(Dst))) { |
| 210 | // Copy is the only use. Do trivial copy propagation here. |
| 211 | MRI->replaceRegWith(Dst, Src); |
| 212 | Copy->eraseFromParent(); |
| 213 | } |
| 214 | } |
| 215 | |
| 216 | if (NewPHIs.size()) |
| 217 | NumAddedPHIs += NewPHIs.size(); |
| 218 | |
| 219 | return true; |
| 220 | } |
| 221 | |
| 222 | /// Look for small blocks that are unconditionally branched to and do not fall |
| 223 | /// through. Tail-duplicate their instructions into their predecessors to |
| 224 | /// eliminate (dynamic) branches. |
| 225 | bool TailDuplicator::tailDuplicateBlocks(MachineFunction &MF) { |
| 226 | bool MadeChange = false; |
| 227 | |
| 228 | if (PreRegAlloc && TailDupVerify) { |
| 229 | DEBUG(dbgs() << "\n*** Before tail-duplicating\n"); |
| 230 | VerifyPHIs(MF, true); |
| 231 | } |
| 232 | |
| 233 | for (MachineFunction::iterator I = ++MF.begin(), E = MF.end(); I != E;) { |
| 234 | MachineBasicBlock *MBB = &*I++; |
| 235 | |
| 236 | if (NumTails == TailDupLimit) |
| 237 | break; |
| 238 | |
| 239 | bool IsSimple = isSimpleBB(MBB); |
| 240 | |
| 241 | if (!shouldTailDuplicate(MF, IsSimple, *MBB)) |
| 242 | continue; |
| 243 | |
| 244 | MadeChange |= tailDuplicateAndUpdate(MF, IsSimple, MBB); |
| 245 | } |
| 246 | |
| 247 | if (PreRegAlloc && TailDupVerify) |
| 248 | VerifyPHIs(MF, false); |
| 249 | |
| 250 | return MadeChange; |
| 251 | } |
| 252 | |
| 253 | static bool isDefLiveOut(unsigned Reg, MachineBasicBlock *BB, |
| 254 | const MachineRegisterInfo *MRI) { |
| 255 | for (MachineInstr &UseMI : MRI->use_instructions(Reg)) { |
| 256 | if (UseMI.isDebugValue()) |
| 257 | continue; |
| 258 | if (UseMI.getParent() != BB) |
| 259 | return true; |
| 260 | } |
| 261 | return false; |
| 262 | } |
| 263 | |
| 264 | static unsigned getPHISrcRegOpIdx(MachineInstr *MI, MachineBasicBlock *SrcBB) { |
| 265 | for (unsigned i = 1, e = MI->getNumOperands(); i != e; i += 2) |
| 266 | if (MI->getOperand(i + 1).getMBB() == SrcBB) |
| 267 | return i; |
| 268 | return 0; |
| 269 | } |
| 270 | |
| 271 | // Remember which registers are used by phis in this block. This is |
| 272 | // used to determine which registers are liveout while modifying the |
| 273 | // block (which is why we need to copy the information). |
| 274 | static void getRegsUsedByPHIs(const MachineBasicBlock &BB, |
| 275 | DenseSet<unsigned> *UsedByPhi) { |
| 276 | for (const auto &MI : BB) { |
| 277 | if (!MI.isPHI()) |
| 278 | break; |
| 279 | for (unsigned i = 1, e = MI.getNumOperands(); i != e; i += 2) { |
| 280 | unsigned SrcReg = MI.getOperand(i).getReg(); |
| 281 | UsedByPhi->insert(SrcReg); |
| 282 | } |
| 283 | } |
| 284 | } |
| 285 | |
| 286 | /// Add a definition and source virtual registers pair for SSA update. |
| 287 | void TailDuplicator::addSSAUpdateEntry(unsigned OrigReg, unsigned NewReg, |
| 288 | MachineBasicBlock *BB) { |
| 289 | DenseMap<unsigned, AvailableValsTy>::iterator LI = |
| 290 | SSAUpdateVals.find(OrigReg); |
| 291 | if (LI != SSAUpdateVals.end()) |
| 292 | LI->second.push_back(std::make_pair(BB, NewReg)); |
| 293 | else { |
| 294 | AvailableValsTy Vals; |
| 295 | Vals.push_back(std::make_pair(BB, NewReg)); |
| 296 | SSAUpdateVals.insert(std::make_pair(OrigReg, Vals)); |
| 297 | SSAUpdateVRs.push_back(OrigReg); |
| 298 | } |
| 299 | } |
| 300 | |
| 301 | /// Process PHI node in TailBB by turning it into a copy in PredBB. Remember the |
| 302 | /// source register that's contributed by PredBB and update SSA update map. |
| 303 | void TailDuplicator::processPHI( |
| 304 | MachineInstr *MI, MachineBasicBlock *TailBB, MachineBasicBlock *PredBB, |
Krzysztof Parzyszek | 4773f64 | 2016-04-26 18:36:34 +0000 | [diff] [blame] | 305 | DenseMap<unsigned, RegSubRegPair> &LocalVRMap, |
| 306 | SmallVectorImpl<std::pair<unsigned, RegSubRegPair>> &Copies, |
Kyle Butt | 3232dbb | 2016-04-08 20:35:01 +0000 | [diff] [blame] | 307 | const DenseSet<unsigned> &RegsUsedByPhi, bool Remove) { |
| 308 | unsigned DefReg = MI->getOperand(0).getReg(); |
| 309 | unsigned SrcOpIdx = getPHISrcRegOpIdx(MI, PredBB); |
| 310 | assert(SrcOpIdx && "Unable to find matching PHI source?"); |
| 311 | unsigned SrcReg = MI->getOperand(SrcOpIdx).getReg(); |
Krzysztof Parzyszek | 4773f64 | 2016-04-26 18:36:34 +0000 | [diff] [blame] | 312 | unsigned SrcSubReg = MI->getOperand(SrcOpIdx).getSubReg(); |
Kyle Butt | 3232dbb | 2016-04-08 20:35:01 +0000 | [diff] [blame] | 313 | const TargetRegisterClass *RC = MRI->getRegClass(DefReg); |
Krzysztof Parzyszek | 4773f64 | 2016-04-26 18:36:34 +0000 | [diff] [blame] | 314 | LocalVRMap.insert(std::make_pair(DefReg, RegSubRegPair(SrcReg, SrcSubReg))); |
Kyle Butt | 3232dbb | 2016-04-08 20:35:01 +0000 | [diff] [blame] | 315 | |
| 316 | // Insert a copy from source to the end of the block. The def register is the |
| 317 | // available value liveout of the block. |
| 318 | unsigned NewDef = MRI->createVirtualRegister(RC); |
Krzysztof Parzyszek | 4773f64 | 2016-04-26 18:36:34 +0000 | [diff] [blame] | 319 | Copies.push_back(std::make_pair(NewDef, RegSubRegPair(SrcReg, SrcSubReg))); |
Kyle Butt | 3232dbb | 2016-04-08 20:35:01 +0000 | [diff] [blame] | 320 | if (isDefLiveOut(DefReg, TailBB, MRI) || RegsUsedByPhi.count(DefReg)) |
| 321 | addSSAUpdateEntry(DefReg, NewDef, PredBB); |
| 322 | |
| 323 | if (!Remove) |
| 324 | return; |
| 325 | |
| 326 | // Remove PredBB from the PHI node. |
| 327 | MI->RemoveOperand(SrcOpIdx + 1); |
| 328 | MI->RemoveOperand(SrcOpIdx); |
| 329 | if (MI->getNumOperands() == 1) |
| 330 | MI->eraseFromParent(); |
| 331 | } |
| 332 | |
| 333 | /// Duplicate a TailBB instruction to PredBB and update |
| 334 | /// the source operands due to earlier PHI translation. |
| 335 | void TailDuplicator::duplicateInstruction( |
| 336 | MachineInstr *MI, MachineBasicBlock *TailBB, MachineBasicBlock *PredBB, |
Krzysztof Parzyszek | 4773f64 | 2016-04-26 18:36:34 +0000 | [diff] [blame] | 337 | MachineFunction &MF, |
| 338 | DenseMap<unsigned, RegSubRegPair> &LocalVRMap, |
Kyle Butt | 3232dbb | 2016-04-08 20:35:01 +0000 | [diff] [blame] | 339 | const DenseSet<unsigned> &UsedByPhi) { |
Duncan P. N. Exon Smith | 9cfc75c | 2016-06-30 00:01:54 +0000 | [diff] [blame] | 340 | MachineInstr *NewMI = TII->duplicate(*MI, MF); |
Kyle Butt | 3232dbb | 2016-04-08 20:35:01 +0000 | [diff] [blame] | 341 | if (PreRegAlloc) { |
| 342 | for (unsigned i = 0, e = NewMI->getNumOperands(); i != e; ++i) { |
| 343 | MachineOperand &MO = NewMI->getOperand(i); |
| 344 | if (!MO.isReg()) |
| 345 | continue; |
| 346 | unsigned Reg = MO.getReg(); |
| 347 | if (!TargetRegisterInfo::isVirtualRegister(Reg)) |
| 348 | continue; |
| 349 | if (MO.isDef()) { |
| 350 | const TargetRegisterClass *RC = MRI->getRegClass(Reg); |
| 351 | unsigned NewReg = MRI->createVirtualRegister(RC); |
| 352 | MO.setReg(NewReg); |
Krzysztof Parzyszek | 4773f64 | 2016-04-26 18:36:34 +0000 | [diff] [blame] | 353 | LocalVRMap.insert(std::make_pair(Reg, RegSubRegPair(NewReg, 0))); |
Kyle Butt | 3232dbb | 2016-04-08 20:35:01 +0000 | [diff] [blame] | 354 | if (isDefLiveOut(Reg, TailBB, MRI) || UsedByPhi.count(Reg)) |
| 355 | addSSAUpdateEntry(Reg, NewReg, PredBB); |
| 356 | } else { |
Krzysztof Parzyszek | 4773f64 | 2016-04-26 18:36:34 +0000 | [diff] [blame] | 357 | auto VI = LocalVRMap.find(Reg); |
Kyle Butt | 3232dbb | 2016-04-08 20:35:01 +0000 | [diff] [blame] | 358 | if (VI != LocalVRMap.end()) { |
Krzysztof Parzyszek | 4773f64 | 2016-04-26 18:36:34 +0000 | [diff] [blame] | 359 | // Need to make sure that the register class of the mapped register |
| 360 | // will satisfy the constraints of the class of the register being |
| 361 | // replaced. |
| 362 | auto *OrigRC = MRI->getRegClass(Reg); |
| 363 | auto *MappedRC = MRI->getRegClass(VI->second.Reg); |
| 364 | const TargetRegisterClass *ConstrRC; |
| 365 | if (VI->second.SubReg != 0) { |
| 366 | ConstrRC = TRI->getMatchingSuperRegClass(MappedRC, OrigRC, |
| 367 | VI->second.SubReg); |
| 368 | if (ConstrRC) { |
| 369 | // The actual constraining (as in "find appropriate new class") |
| 370 | // is done by getMatchingSuperRegClass, so now we only need to |
| 371 | // change the class of the mapped register. |
| 372 | MRI->setRegClass(VI->second.Reg, ConstrRC); |
| 373 | } |
| 374 | } else { |
| 375 | // For mapped registers that do not have sub-registers, simply |
| 376 | // restrict their class to match the original one. |
| 377 | ConstrRC = MRI->constrainRegClass(VI->second.Reg, OrigRC); |
| 378 | } |
| 379 | |
| 380 | if (ConstrRC) { |
| 381 | // If the class constraining succeeded, we can simply replace |
| 382 | // the old register with the mapped one. |
| 383 | MO.setReg(VI->second.Reg); |
| 384 | // We have Reg -> VI.Reg:VI.SubReg, so if Reg is used with a |
| 385 | // sub-register, we need to compose the sub-register indices. |
| 386 | MO.setSubReg(TRI->composeSubRegIndices(MO.getSubReg(), |
| 387 | VI->second.SubReg)); |
| 388 | } else { |
| 389 | // The direct replacement is not possible, due to failing register |
| 390 | // class constraints. An explicit COPY is necessary. Create one |
| 391 | // that can be reused |
| 392 | auto *NewRC = MI->getRegClassConstraint(i, TII, TRI); |
| 393 | if (NewRC == nullptr) |
| 394 | NewRC = OrigRC; |
| 395 | unsigned NewReg = MRI->createVirtualRegister(NewRC); |
| 396 | BuildMI(*PredBB, MI, MI->getDebugLoc(), |
| 397 | TII->get(TargetOpcode::COPY), NewReg) |
| 398 | .addReg(VI->second.Reg, 0, VI->second.SubReg); |
| 399 | LocalVRMap.erase(VI); |
| 400 | LocalVRMap.insert(std::make_pair(Reg, RegSubRegPair(NewReg, 0))); |
| 401 | MO.setReg(NewReg); |
| 402 | // The composed VI.Reg:VI.SubReg is replaced with NewReg, which |
| 403 | // is equivalent to the whole register Reg. Hence, Reg:subreg |
| 404 | // is same as NewReg:subreg, so keep the sub-register index |
| 405 | // unchanged. |
| 406 | } |
Kyle Butt | 3232dbb | 2016-04-08 20:35:01 +0000 | [diff] [blame] | 407 | // Clear any kill flags from this operand. The new register could |
| 408 | // have uses after this one, so kills are not valid here. |
| 409 | MO.setIsKill(false); |
Kyle Butt | 3232dbb | 2016-04-08 20:35:01 +0000 | [diff] [blame] | 410 | } |
| 411 | } |
| 412 | } |
| 413 | } |
| 414 | PredBB->insert(PredBB->instr_end(), NewMI); |
| 415 | } |
| 416 | |
| 417 | /// After FromBB is tail duplicated into its predecessor blocks, the successors |
| 418 | /// have gained new predecessors. Update the PHI instructions in them |
| 419 | /// accordingly. |
| 420 | void TailDuplicator::updateSuccessorsPHIs( |
| 421 | MachineBasicBlock *FromBB, bool isDead, |
| 422 | SmallVectorImpl<MachineBasicBlock *> &TDBBs, |
| 423 | SmallSetVector<MachineBasicBlock *, 8> &Succs) { |
| 424 | for (SmallSetVector<MachineBasicBlock *, 8>::iterator SI = Succs.begin(), |
| 425 | SE = Succs.end(); |
| 426 | SI != SE; ++SI) { |
| 427 | MachineBasicBlock *SuccBB = *SI; |
| 428 | for (MachineBasicBlock::iterator II = SuccBB->begin(), EE = SuccBB->end(); |
| 429 | II != EE; ++II) { |
| 430 | if (!II->isPHI()) |
| 431 | break; |
| 432 | MachineInstrBuilder MIB(*FromBB->getParent(), II); |
| 433 | unsigned Idx = 0; |
| 434 | for (unsigned i = 1, e = II->getNumOperands(); i != e; i += 2) { |
| 435 | MachineOperand &MO = II->getOperand(i + 1); |
| 436 | if (MO.getMBB() == FromBB) { |
| 437 | Idx = i; |
| 438 | break; |
| 439 | } |
| 440 | } |
| 441 | |
| 442 | assert(Idx != 0); |
| 443 | MachineOperand &MO0 = II->getOperand(Idx); |
| 444 | unsigned Reg = MO0.getReg(); |
| 445 | if (isDead) { |
| 446 | // Folded into the previous BB. |
| 447 | // There could be duplicate phi source entries. FIXME: Should sdisel |
| 448 | // or earlier pass fixed this? |
| 449 | for (unsigned i = II->getNumOperands() - 2; i != Idx; i -= 2) { |
| 450 | MachineOperand &MO = II->getOperand(i + 1); |
| 451 | if (MO.getMBB() == FromBB) { |
| 452 | II->RemoveOperand(i + 1); |
| 453 | II->RemoveOperand(i); |
| 454 | } |
| 455 | } |
| 456 | } else |
| 457 | Idx = 0; |
| 458 | |
| 459 | // If Idx is set, the operands at Idx and Idx+1 must be removed. |
| 460 | // We reuse the location to avoid expensive RemoveOperand calls. |
| 461 | |
| 462 | DenseMap<unsigned, AvailableValsTy>::iterator LI = |
| 463 | SSAUpdateVals.find(Reg); |
| 464 | if (LI != SSAUpdateVals.end()) { |
| 465 | // This register is defined in the tail block. |
| 466 | for (unsigned j = 0, ee = LI->second.size(); j != ee; ++j) { |
| 467 | MachineBasicBlock *SrcBB = LI->second[j].first; |
| 468 | // If we didn't duplicate a bb into a particular predecessor, we |
| 469 | // might still have added an entry to SSAUpdateVals to correcly |
| 470 | // recompute SSA. If that case, avoid adding a dummy extra argument |
| 471 | // this PHI. |
| 472 | if (!SrcBB->isSuccessor(SuccBB)) |
| 473 | continue; |
| 474 | |
| 475 | unsigned SrcReg = LI->second[j].second; |
| 476 | if (Idx != 0) { |
| 477 | II->getOperand(Idx).setReg(SrcReg); |
| 478 | II->getOperand(Idx + 1).setMBB(SrcBB); |
| 479 | Idx = 0; |
| 480 | } else { |
| 481 | MIB.addReg(SrcReg).addMBB(SrcBB); |
| 482 | } |
| 483 | } |
| 484 | } else { |
| 485 | // Live in tail block, must also be live in predecessors. |
| 486 | for (unsigned j = 0, ee = TDBBs.size(); j != ee; ++j) { |
| 487 | MachineBasicBlock *SrcBB = TDBBs[j]; |
| 488 | if (Idx != 0) { |
| 489 | II->getOperand(Idx).setReg(Reg); |
| 490 | II->getOperand(Idx + 1).setMBB(SrcBB); |
| 491 | Idx = 0; |
| 492 | } else { |
| 493 | MIB.addReg(Reg).addMBB(SrcBB); |
| 494 | } |
| 495 | } |
| 496 | } |
| 497 | if (Idx != 0) { |
| 498 | II->RemoveOperand(Idx + 1); |
| 499 | II->RemoveOperand(Idx); |
| 500 | } |
| 501 | } |
| 502 | } |
| 503 | } |
| 504 | |
| 505 | /// Determine if it is profitable to duplicate this block. |
| 506 | bool TailDuplicator::shouldTailDuplicate(const MachineFunction &MF, |
| 507 | bool IsSimple, |
| 508 | MachineBasicBlock &TailBB) { |
| 509 | // Only duplicate blocks that end with unconditional branches. |
| 510 | if (TailBB.canFallThrough()) |
| 511 | return false; |
| 512 | |
| 513 | // Don't try to tail-duplicate single-block loops. |
| 514 | if (TailBB.isSuccessor(&TailBB)) |
| 515 | return false; |
| 516 | |
| 517 | // Set the limit on the cost to duplicate. When optimizing for size, |
| 518 | // duplicate only one, because one branch instruction can be eliminated to |
| 519 | // compensate for the duplication. |
| 520 | unsigned MaxDuplicateCount; |
| 521 | if (TailDuplicateSize.getNumOccurrences() == 0 && |
| 522 | // FIXME: Use Function::optForSize(). |
| 523 | MF.getFunction()->hasFnAttribute(Attribute::OptimizeForSize)) |
| 524 | MaxDuplicateCount = 1; |
| 525 | else |
| 526 | MaxDuplicateCount = TailDuplicateSize; |
| 527 | |
| 528 | // If the target has hardware branch prediction that can handle indirect |
| 529 | // branches, duplicating them can often make them predictable when there |
| 530 | // are common paths through the code. The limit needs to be high enough |
| 531 | // to allow undoing the effects of tail merging and other optimizations |
| 532 | // that rearrange the predecessors of the indirect branch. |
| 533 | |
| 534 | bool HasIndirectbr = false; |
| 535 | if (!TailBB.empty()) |
| 536 | HasIndirectbr = TailBB.back().isIndirectBranch(); |
| 537 | |
| 538 | if (HasIndirectbr && PreRegAlloc) |
| 539 | MaxDuplicateCount = 20; |
| 540 | |
| 541 | // Check the instructions in the block to determine whether tail-duplication |
| 542 | // is invalid or unlikely to be profitable. |
| 543 | unsigned InstrCount = 0; |
| 544 | for (MachineInstr &MI : TailBB) { |
| 545 | // Non-duplicable things shouldn't be tail-duplicated. |
| 546 | if (MI.isNotDuplicable()) |
| 547 | return false; |
| 548 | |
| 549 | // Convergent instructions can be duplicated only if doing so doesn't add |
| 550 | // new control dependencies, which is what we're going to do here. |
| 551 | if (MI.isConvergent()) |
| 552 | return false; |
| 553 | |
| 554 | // Do not duplicate 'return' instructions if this is a pre-regalloc run. |
| 555 | // A return may expand into a lot more instructions (e.g. reload of callee |
| 556 | // saved registers) after PEI. |
| 557 | if (PreRegAlloc && MI.isReturn()) |
| 558 | return false; |
| 559 | |
| 560 | // Avoid duplicating calls before register allocation. Calls presents a |
| 561 | // barrier to register allocation so duplicating them may end up increasing |
| 562 | // spills. |
| 563 | if (PreRegAlloc && MI.isCall()) |
| 564 | return false; |
| 565 | |
| 566 | if (!MI.isPHI() && !MI.isDebugValue()) |
| 567 | InstrCount += 1; |
| 568 | |
| 569 | if (InstrCount > MaxDuplicateCount) |
| 570 | return false; |
| 571 | } |
| 572 | |
| 573 | // Check if any of the successors of TailBB has a PHI node in which the |
| 574 | // value corresponding to TailBB uses a subregister. |
| 575 | // If a phi node uses a register paired with a subregister, the actual |
| 576 | // "value type" of the phi may differ from the type of the register without |
| 577 | // any subregisters. Due to a bug, tail duplication may add a new operand |
| 578 | // without a necessary subregister, producing an invalid code. This is |
| 579 | // demonstrated by test/CodeGen/Hexagon/tail-dup-subreg-abort.ll. |
| 580 | // Disable tail duplication for this case for now, until the problem is |
| 581 | // fixed. |
| 582 | for (auto SB : TailBB.successors()) { |
| 583 | for (auto &I : *SB) { |
| 584 | if (!I.isPHI()) |
| 585 | break; |
| 586 | unsigned Idx = getPHISrcRegOpIdx(&I, &TailBB); |
| 587 | assert(Idx != 0); |
| 588 | MachineOperand &PU = I.getOperand(Idx); |
| 589 | if (PU.getSubReg() != 0) |
| 590 | return false; |
| 591 | } |
| 592 | } |
| 593 | |
| 594 | if (HasIndirectbr && PreRegAlloc) |
| 595 | return true; |
| 596 | |
| 597 | if (IsSimple) |
| 598 | return true; |
| 599 | |
| 600 | if (!PreRegAlloc) |
| 601 | return true; |
| 602 | |
| 603 | return canCompletelyDuplicateBB(TailBB); |
| 604 | } |
| 605 | |
| 606 | /// True if this BB has only one unconditional jump. |
| 607 | bool TailDuplicator::isSimpleBB(MachineBasicBlock *TailBB) { |
| 608 | if (TailBB->succ_size() != 1) |
| 609 | return false; |
| 610 | if (TailBB->pred_empty()) |
| 611 | return false; |
| 612 | MachineBasicBlock::iterator I = TailBB->getFirstNonDebugInstr(); |
| 613 | if (I == TailBB->end()) |
| 614 | return true; |
| 615 | return I->isUnconditionalBranch(); |
| 616 | } |
| 617 | |
| 618 | static bool bothUsedInPHI(const MachineBasicBlock &A, |
Benjamin Kramer | bdc4956 | 2016-06-12 15:39:02 +0000 | [diff] [blame] | 619 | const SmallPtrSet<MachineBasicBlock *, 8> &SuccsB) { |
Kyle Butt | 3232dbb | 2016-04-08 20:35:01 +0000 | [diff] [blame] | 620 | for (MachineBasicBlock *BB : A.successors()) |
| 621 | if (SuccsB.count(BB) && !BB->empty() && BB->begin()->isPHI()) |
| 622 | return true; |
| 623 | |
| 624 | return false; |
| 625 | } |
| 626 | |
| 627 | bool TailDuplicator::canCompletelyDuplicateBB(MachineBasicBlock &BB) { |
| 628 | for (MachineBasicBlock *PredBB : BB.predecessors()) { |
| 629 | if (PredBB->succ_size() > 1) |
| 630 | return false; |
| 631 | |
| 632 | MachineBasicBlock *PredTBB = nullptr, *PredFBB = nullptr; |
| 633 | SmallVector<MachineOperand, 4> PredCond; |
Jacques Pienaar | 71c30a1 | 2016-07-15 14:41:04 +0000 | [diff] [blame] | 634 | if (TII->analyzeBranch(*PredBB, PredTBB, PredFBB, PredCond, true)) |
Kyle Butt | 3232dbb | 2016-04-08 20:35:01 +0000 | [diff] [blame] | 635 | return false; |
| 636 | |
| 637 | if (!PredCond.empty()) |
| 638 | return false; |
| 639 | } |
| 640 | return true; |
| 641 | } |
| 642 | |
| 643 | bool TailDuplicator::duplicateSimpleBB( |
| 644 | MachineBasicBlock *TailBB, SmallVectorImpl<MachineBasicBlock *> &TDBBs, |
| 645 | const DenseSet<unsigned> &UsedByPhi, |
| 646 | SmallVectorImpl<MachineInstr *> &Copies) { |
| 647 | SmallPtrSet<MachineBasicBlock *, 8> Succs(TailBB->succ_begin(), |
| 648 | TailBB->succ_end()); |
| 649 | SmallVector<MachineBasicBlock *, 8> Preds(TailBB->pred_begin(), |
| 650 | TailBB->pred_end()); |
| 651 | bool Changed = false; |
| 652 | for (SmallSetVector<MachineBasicBlock *, 8>::iterator PI = Preds.begin(), |
| 653 | PE = Preds.end(); |
| 654 | PI != PE; ++PI) { |
| 655 | MachineBasicBlock *PredBB = *PI; |
| 656 | |
| 657 | if (PredBB->hasEHPadSuccessor()) |
| 658 | continue; |
| 659 | |
| 660 | if (bothUsedInPHI(*PredBB, Succs)) |
| 661 | continue; |
| 662 | |
| 663 | MachineBasicBlock *PredTBB = nullptr, *PredFBB = nullptr; |
| 664 | SmallVector<MachineOperand, 4> PredCond; |
Jacques Pienaar | 71c30a1 | 2016-07-15 14:41:04 +0000 | [diff] [blame] | 665 | if (TII->analyzeBranch(*PredBB, PredTBB, PredFBB, PredCond, true)) |
Kyle Butt | 3232dbb | 2016-04-08 20:35:01 +0000 | [diff] [blame] | 666 | continue; |
| 667 | |
| 668 | Changed = true; |
| 669 | DEBUG(dbgs() << "\nTail-duplicating into PredBB: " << *PredBB |
| 670 | << "From simple Succ: " << *TailBB); |
| 671 | |
| 672 | MachineBasicBlock *NewTarget = *TailBB->succ_begin(); |
| 673 | MachineBasicBlock *NextBB = &*std::next(PredBB->getIterator()); |
| 674 | |
| 675 | // Make PredFBB explicit. |
| 676 | if (PredCond.empty()) |
| 677 | PredFBB = PredTBB; |
| 678 | |
| 679 | // Make fall through explicit. |
| 680 | if (!PredTBB) |
| 681 | PredTBB = NextBB; |
| 682 | if (!PredFBB) |
| 683 | PredFBB = NextBB; |
| 684 | |
| 685 | // Redirect |
| 686 | if (PredFBB == TailBB) |
| 687 | PredFBB = NewTarget; |
| 688 | if (PredTBB == TailBB) |
| 689 | PredTBB = NewTarget; |
| 690 | |
| 691 | // Make the branch unconditional if possible |
| 692 | if (PredTBB == PredFBB) { |
| 693 | PredCond.clear(); |
| 694 | PredFBB = nullptr; |
| 695 | } |
| 696 | |
| 697 | // Avoid adding fall through branches. |
| 698 | if (PredFBB == NextBB) |
| 699 | PredFBB = nullptr; |
| 700 | if (PredTBB == NextBB && PredFBB == nullptr) |
| 701 | PredTBB = nullptr; |
| 702 | |
| 703 | TII->RemoveBranch(*PredBB); |
| 704 | |
| 705 | if (!PredBB->isSuccessor(NewTarget)) |
| 706 | PredBB->replaceSuccessor(TailBB, NewTarget); |
| 707 | else { |
| 708 | PredBB->removeSuccessor(TailBB, true); |
| 709 | assert(PredBB->succ_size() <= 1); |
| 710 | } |
| 711 | |
| 712 | if (PredTBB) |
| 713 | TII->InsertBranch(*PredBB, PredTBB, PredFBB, PredCond, DebugLoc()); |
| 714 | |
| 715 | TDBBs.push_back(PredBB); |
| 716 | } |
| 717 | return Changed; |
| 718 | } |
| 719 | |
Kyle Butt | 9e52c06 | 2016-07-19 23:54:21 +0000 | [diff] [blame^] | 720 | bool TailDuplicator::canTailDuplicate(MachineBasicBlock *TailBB, |
| 721 | MachineBasicBlock *PredBB) { |
| 722 | // EH edges are ignored by AnalyzeBranch. |
| 723 | if (PredBB->succ_size() > 1) |
| 724 | return false; |
| 725 | |
| 726 | MachineBasicBlock *PredTBB, *PredFBB; |
| 727 | SmallVector<MachineOperand, 4> PredCond; |
| 728 | if (TII->analyzeBranch(*PredBB, PredTBB, PredFBB, PredCond, true)) |
| 729 | return false; |
| 730 | if (!PredCond.empty()) |
| 731 | return false; |
| 732 | return true; |
| 733 | } |
| 734 | |
Kyle Butt | 3232dbb | 2016-04-08 20:35:01 +0000 | [diff] [blame] | 735 | /// If it is profitable, duplicate TailBB's contents in each |
| 736 | /// of its predecessors. |
| 737 | bool TailDuplicator::tailDuplicate(MachineFunction &MF, bool IsSimple, |
| 738 | MachineBasicBlock *TailBB, |
| 739 | SmallVectorImpl<MachineBasicBlock *> &TDBBs, |
| 740 | SmallVectorImpl<MachineInstr *> &Copies) { |
| 741 | DEBUG(dbgs() << "\n*** Tail-duplicating BB#" << TailBB->getNumber() << '\n'); |
| 742 | |
| 743 | DenseSet<unsigned> UsedByPhi; |
| 744 | getRegsUsedByPHIs(*TailBB, &UsedByPhi); |
| 745 | |
| 746 | if (IsSimple) |
| 747 | return duplicateSimpleBB(TailBB, TDBBs, UsedByPhi, Copies); |
| 748 | |
| 749 | // Iterate through all the unique predecessors and tail-duplicate this |
| 750 | // block into them, if possible. Copying the list ahead of time also |
| 751 | // avoids trouble with the predecessor list reallocating. |
| 752 | bool Changed = false; |
| 753 | SmallSetVector<MachineBasicBlock *, 8> Preds(TailBB->pred_begin(), |
| 754 | TailBB->pred_end()); |
| 755 | for (SmallSetVector<MachineBasicBlock *, 8>::iterator PI = Preds.begin(), |
| 756 | PE = Preds.end(); |
| 757 | PI != PE; ++PI) { |
| 758 | MachineBasicBlock *PredBB = *PI; |
Kyle Butt | 3232dbb | 2016-04-08 20:35:01 +0000 | [diff] [blame] | 759 | assert(TailBB != PredBB && |
| 760 | "Single-block loop should have been rejected earlier!"); |
Kyle Butt | 9e52c06 | 2016-07-19 23:54:21 +0000 | [diff] [blame^] | 761 | |
| 762 | if (!canTailDuplicate(TailBB, PredBB)) |
Kyle Butt | 3232dbb | 2016-04-08 20:35:01 +0000 | [diff] [blame] | 763 | continue; |
| 764 | |
Kyle Butt | 3232dbb | 2016-04-08 20:35:01 +0000 | [diff] [blame] | 765 | // Don't duplicate into a fall-through predecessor (at least for now). |
| 766 | if (PredBB->isLayoutSuccessor(TailBB) && PredBB->canFallThrough()) |
| 767 | continue; |
| 768 | |
| 769 | DEBUG(dbgs() << "\nTail-duplicating into PredBB: " << *PredBB |
| 770 | << "From Succ: " << *TailBB); |
| 771 | |
| 772 | TDBBs.push_back(PredBB); |
| 773 | |
| 774 | // Remove PredBB's unconditional branch. |
| 775 | TII->RemoveBranch(*PredBB); |
| 776 | |
Kyle Butt | 3232dbb | 2016-04-08 20:35:01 +0000 | [diff] [blame] | 777 | // Clone the contents of TailBB into PredBB. |
Krzysztof Parzyszek | 4773f64 | 2016-04-26 18:36:34 +0000 | [diff] [blame] | 778 | DenseMap<unsigned, RegSubRegPair> LocalVRMap; |
| 779 | SmallVector<std::pair<unsigned, RegSubRegPair>, 4> CopyInfos; |
Kyle Butt | 3232dbb | 2016-04-08 20:35:01 +0000 | [diff] [blame] | 780 | // Use instr_iterator here to properly handle bundles, e.g. |
| 781 | // ARM Thumb2 IT block. |
| 782 | MachineBasicBlock::instr_iterator I = TailBB->instr_begin(); |
| 783 | while (I != TailBB->instr_end()) { |
| 784 | MachineInstr *MI = &*I; |
| 785 | ++I; |
| 786 | if (MI->isPHI()) { |
| 787 | // Replace the uses of the def of the PHI with the register coming |
| 788 | // from PredBB. |
| 789 | processPHI(MI, TailBB, PredBB, LocalVRMap, CopyInfos, UsedByPhi, true); |
| 790 | } else { |
| 791 | // Replace def of virtual registers with new registers, and update |
| 792 | // uses with PHI source register or the new registers. |
| 793 | duplicateInstruction(MI, TailBB, PredBB, MF, LocalVRMap, UsedByPhi); |
| 794 | } |
| 795 | } |
Krzysztof Parzyszek | 4773f64 | 2016-04-26 18:36:34 +0000 | [diff] [blame] | 796 | appendCopies(PredBB, CopyInfos, Copies); |
Kyle Butt | 3232dbb | 2016-04-08 20:35:01 +0000 | [diff] [blame] | 797 | |
| 798 | // Simplify |
Kyle Butt | 9e52c06 | 2016-07-19 23:54:21 +0000 | [diff] [blame^] | 799 | MachineBasicBlock *PredTBB, *PredFBB; |
| 800 | SmallVector<MachineOperand, 4> PredCond; |
Jacques Pienaar | 71c30a1 | 2016-07-15 14:41:04 +0000 | [diff] [blame] | 801 | TII->analyzeBranch(*PredBB, PredTBB, PredFBB, PredCond, true); |
Kyle Butt | 3232dbb | 2016-04-08 20:35:01 +0000 | [diff] [blame] | 802 | |
Geoff Berry | f8c29d6 | 2016-06-14 19:40:10 +0000 | [diff] [blame] | 803 | NumTailDupAdded += TailBB->size() - 1; // subtract one for removed branch |
Kyle Butt | 3232dbb | 2016-04-08 20:35:01 +0000 | [diff] [blame] | 804 | |
| 805 | // Update the CFG. |
| 806 | PredBB->removeSuccessor(PredBB->succ_begin()); |
| 807 | assert(PredBB->succ_empty() && |
| 808 | "TailDuplicate called on block with multiple successors!"); |
| 809 | for (MachineBasicBlock::succ_iterator I = TailBB->succ_begin(), |
| 810 | E = TailBB->succ_end(); |
| 811 | I != E; ++I) |
| 812 | PredBB->addSuccessor(*I, MBPI->getEdgeProbability(TailBB, I)); |
| 813 | |
| 814 | Changed = true; |
| 815 | ++NumTailDups; |
| 816 | } |
| 817 | |
| 818 | // If TailBB was duplicated into all its predecessors except for the prior |
| 819 | // block, which falls through unconditionally, move the contents of this |
| 820 | // block into the prior block. |
| 821 | MachineBasicBlock *PrevBB = &*std::prev(TailBB->getIterator()); |
| 822 | MachineBasicBlock *PriorTBB = nullptr, *PriorFBB = nullptr; |
| 823 | SmallVector<MachineOperand, 4> PriorCond; |
| 824 | // This has to check PrevBB->succ_size() because EH edges are ignored by |
| 825 | // AnalyzeBranch. |
| 826 | if (PrevBB->succ_size() == 1 && |
Jacques Pienaar | 71c30a1 | 2016-07-15 14:41:04 +0000 | [diff] [blame] | 827 | !TII->analyzeBranch(*PrevBB, PriorTBB, PriorFBB, PriorCond, true) && |
Kyle Butt | 3232dbb | 2016-04-08 20:35:01 +0000 | [diff] [blame] | 828 | PriorCond.empty() && !PriorTBB && TailBB->pred_size() == 1 && |
| 829 | !TailBB->hasAddressTaken()) { |
| 830 | DEBUG(dbgs() << "\nMerging into block: " << *PrevBB |
| 831 | << "From MBB: " << *TailBB); |
| 832 | if (PreRegAlloc) { |
Krzysztof Parzyszek | 4773f64 | 2016-04-26 18:36:34 +0000 | [diff] [blame] | 833 | DenseMap<unsigned, RegSubRegPair> LocalVRMap; |
| 834 | SmallVector<std::pair<unsigned, RegSubRegPair>, 4> CopyInfos; |
Kyle Butt | 3232dbb | 2016-04-08 20:35:01 +0000 | [diff] [blame] | 835 | MachineBasicBlock::iterator I = TailBB->begin(); |
| 836 | // Process PHI instructions first. |
| 837 | while (I != TailBB->end() && I->isPHI()) { |
| 838 | // Replace the uses of the def of the PHI with the register coming |
| 839 | // from PredBB. |
| 840 | MachineInstr *MI = &*I++; |
| 841 | processPHI(MI, TailBB, PrevBB, LocalVRMap, CopyInfos, UsedByPhi, true); |
Kyle Butt | 3232dbb | 2016-04-08 20:35:01 +0000 | [diff] [blame] | 842 | } |
| 843 | |
| 844 | // Now copy the non-PHI instructions. |
| 845 | while (I != TailBB->end()) { |
| 846 | // Replace def of virtual registers with new registers, and update |
| 847 | // uses with PHI source register or the new registers. |
| 848 | MachineInstr *MI = &*I++; |
| 849 | assert(!MI->isBundle() && "Not expecting bundles before regalloc!"); |
| 850 | duplicateInstruction(MI, TailBB, PrevBB, MF, LocalVRMap, UsedByPhi); |
| 851 | MI->eraseFromParent(); |
| 852 | } |
Krzysztof Parzyszek | 4773f64 | 2016-04-26 18:36:34 +0000 | [diff] [blame] | 853 | appendCopies(PrevBB, CopyInfos, Copies); |
Kyle Butt | 3232dbb | 2016-04-08 20:35:01 +0000 | [diff] [blame] | 854 | } else { |
| 855 | // No PHIs to worry about, just splice the instructions over. |
| 856 | PrevBB->splice(PrevBB->end(), TailBB, TailBB->begin(), TailBB->end()); |
| 857 | } |
| 858 | PrevBB->removeSuccessor(PrevBB->succ_begin()); |
| 859 | assert(PrevBB->succ_empty()); |
| 860 | PrevBB->transferSuccessors(TailBB); |
| 861 | TDBBs.push_back(PrevBB); |
| 862 | Changed = true; |
| 863 | } |
| 864 | |
| 865 | // If this is after register allocation, there are no phis to fix. |
| 866 | if (!PreRegAlloc) |
| 867 | return Changed; |
| 868 | |
| 869 | // If we made no changes so far, we are safe. |
| 870 | if (!Changed) |
| 871 | return Changed; |
| 872 | |
| 873 | // Handle the nasty case in that we duplicated a block that is part of a loop |
| 874 | // into some but not all of its predecessors. For example: |
| 875 | // 1 -> 2 <-> 3 | |
| 876 | // \ | |
| 877 | // \---> rest | |
| 878 | // if we duplicate 2 into 1 but not into 3, we end up with |
| 879 | // 12 -> 3 <-> 2 -> rest | |
| 880 | // \ / | |
| 881 | // \----->-----/ | |
| 882 | // If there was a "var = phi(1, 3)" in 2, it has to be ultimately replaced |
| 883 | // with a phi in 3 (which now dominates 2). |
| 884 | // What we do here is introduce a copy in 3 of the register defined by the |
| 885 | // phi, just like when we are duplicating 2 into 3, but we don't copy any |
| 886 | // real instructions or remove the 3 -> 2 edge from the phi in 2. |
| 887 | for (SmallSetVector<MachineBasicBlock *, 8>::iterator PI = Preds.begin(), |
| 888 | PE = Preds.end(); |
| 889 | PI != PE; ++PI) { |
| 890 | MachineBasicBlock *PredBB = *PI; |
| 891 | if (std::find(TDBBs.begin(), TDBBs.end(), PredBB) != TDBBs.end()) |
| 892 | continue; |
| 893 | |
| 894 | // EH edges |
| 895 | if (PredBB->succ_size() != 1) |
| 896 | continue; |
| 897 | |
Krzysztof Parzyszek | 4773f64 | 2016-04-26 18:36:34 +0000 | [diff] [blame] | 898 | DenseMap<unsigned, RegSubRegPair> LocalVRMap; |
| 899 | SmallVector<std::pair<unsigned, RegSubRegPair>, 4> CopyInfos; |
Kyle Butt | 3232dbb | 2016-04-08 20:35:01 +0000 | [diff] [blame] | 900 | MachineBasicBlock::iterator I = TailBB->begin(); |
| 901 | // Process PHI instructions first. |
| 902 | while (I != TailBB->end() && I->isPHI()) { |
| 903 | // Replace the uses of the def of the PHI with the register coming |
| 904 | // from PredBB. |
| 905 | MachineInstr *MI = &*I++; |
| 906 | processPHI(MI, TailBB, PredBB, LocalVRMap, CopyInfos, UsedByPhi, false); |
| 907 | } |
Krzysztof Parzyszek | 4773f64 | 2016-04-26 18:36:34 +0000 | [diff] [blame] | 908 | appendCopies(PredBB, CopyInfos, Copies); |
Kyle Butt | 3232dbb | 2016-04-08 20:35:01 +0000 | [diff] [blame] | 909 | } |
| 910 | |
| 911 | return Changed; |
| 912 | } |
| 913 | |
Krzysztof Parzyszek | 4773f64 | 2016-04-26 18:36:34 +0000 | [diff] [blame] | 914 | /// At the end of the block \p MBB generate COPY instructions between registers |
| 915 | /// described by \p CopyInfos. Append resulting instructions to \p Copies. |
| 916 | void TailDuplicator::appendCopies(MachineBasicBlock *MBB, |
| 917 | SmallVectorImpl<std::pair<unsigned,RegSubRegPair>> &CopyInfos, |
| 918 | SmallVectorImpl<MachineInstr*> &Copies) { |
| 919 | MachineBasicBlock::iterator Loc = MBB->getFirstTerminator(); |
| 920 | const MCInstrDesc &CopyD = TII->get(TargetOpcode::COPY); |
| 921 | for (auto &CI : CopyInfos) { |
| 922 | auto C = BuildMI(*MBB, Loc, DebugLoc(), CopyD, CI.first) |
| 923 | .addReg(CI.second.Reg, 0, CI.second.SubReg); |
| 924 | Copies.push_back(C); |
| 925 | } |
| 926 | } |
| 927 | |
Kyle Butt | 3232dbb | 2016-04-08 20:35:01 +0000 | [diff] [blame] | 928 | /// Remove the specified dead machine basic block from the function, updating |
| 929 | /// the CFG. |
| 930 | void TailDuplicator::removeDeadBlock(MachineBasicBlock *MBB) { |
| 931 | assert(MBB->pred_empty() && "MBB must be dead!"); |
| 932 | DEBUG(dbgs() << "\nRemoving MBB: " << *MBB); |
| 933 | |
| 934 | // Remove all successors. |
| 935 | while (!MBB->succ_empty()) |
| 936 | MBB->removeSuccessor(MBB->succ_end() - 1); |
| 937 | |
| 938 | // Remove the block. |
| 939 | MBB->eraseFromParent(); |
| 940 | } |
| 941 | |
| 942 | } // End llvm namespace |