1 //===-- ARMLowOverheadLoops.cpp - CodeGen Low-overhead Loops ---*- 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 /// Finalize v8.1-m low-overhead loops by converting the associated pseudo 10 /// instructions into machine operations. 11 /// The expectation is that the loop contains three pseudo instructions: 12 /// - t2*LoopStart - placed in the preheader or pre-preheader. The do-loop 13 /// form should be in the preheader, whereas the while form should be in the 14 /// preheaders only predecessor. 15 /// - t2LoopDec - placed within in the loop body. 16 /// - t2LoopEnd - the loop latch terminator. 17 /// 18 /// In addition to this, we also look for the presence of the VCTP instruction, 19 /// which determines whether we can generated the tail-predicated low-overhead 20 /// loop form. 21 /// 22 /// Assumptions and Dependencies: 23 /// Low-overhead loops are constructed and executed using a setup instruction: 24 /// DLS, WLS, DLSTP or WLSTP and an instruction that loops back: LE or LETP. 25 /// WLS(TP) and LE(TP) are branching instructions with a (large) limited range 26 /// but fixed polarity: WLS can only branch forwards and LE can only branch 27 /// backwards. These restrictions mean that this pass is dependent upon block 28 /// layout and block sizes, which is why it's the last pass to run. The same is 29 /// true for ConstantIslands, but this pass does not increase the size of the 30 /// basic blocks, nor does it change the CFG. Instructions are mainly removed 31 /// during the transform and pseudo instructions are replaced by real ones. In 32 /// some cases, when we have to revert to a 'normal' loop, we have to introduce 33 /// multiple instructions for a single pseudo (see RevertWhile and 34 /// RevertLoopEnd). To handle this situation, t2WhileLoopStart and t2LoopEnd 35 /// are defined to be as large as this maximum sequence of replacement 36 /// instructions. 37 /// 38 //===----------------------------------------------------------------------===// 39 40 #include "ARM.h" 41 #include "ARMBaseInstrInfo.h" 42 #include "ARMBaseRegisterInfo.h" 43 #include "ARMBasicBlockInfo.h" 44 #include "ARMSubtarget.h" 45 #include "Thumb2InstrInfo.h" 46 #include "llvm/ADT/SetOperations.h" 47 #include "llvm/ADT/SmallSet.h" 48 #include "llvm/CodeGen/LivePhysRegs.h" 49 #include "llvm/CodeGen/MachineFunctionPass.h" 50 #include "llvm/CodeGen/MachineLoopInfo.h" 51 #include "llvm/CodeGen/MachineLoopUtils.h" 52 #include "llvm/CodeGen/MachineRegisterInfo.h" 53 #include "llvm/CodeGen/Passes.h" 54 #include "llvm/CodeGen/ReachingDefAnalysis.h" 55 #include "llvm/MC/MCInstrDesc.h" 56 57 using namespace llvm; 58 59 #define DEBUG_TYPE "arm-low-overhead-loops" 60 #define ARM_LOW_OVERHEAD_LOOPS_NAME "ARM Low Overhead Loops pass" 61 62 namespace { 63 64 class PostOrderLoopTraversal { 65 MachineLoop &ML; 66 MachineLoopInfo &MLI; 67 SmallPtrSet<MachineBasicBlock*, 4> Visited; 68 SmallVector<MachineBasicBlock*, 4> Order; 69 70 public: 71 PostOrderLoopTraversal(MachineLoop &ML, MachineLoopInfo &MLI) 72 : ML(ML), MLI(MLI) { } 73 74 const SmallVectorImpl<MachineBasicBlock*> &getOrder() const { 75 return Order; 76 } 77 78 // Visit all the blocks within the loop, as well as exit blocks and any 79 // blocks properly dominating the header. 80 void ProcessLoop() { 81 std::function<void(MachineBasicBlock*)> Search = [this, &Search] 82 (MachineBasicBlock *MBB) -> void { 83 if (Visited.count(MBB)) 84 return; 85 86 Visited.insert(MBB); 87 for (auto *Succ : MBB->successors()) { 88 if (!ML.contains(Succ)) 89 continue; 90 Search(Succ); 91 } 92 Order.push_back(MBB); 93 }; 94 95 // Insert exit blocks. 96 SmallVector<MachineBasicBlock*, 2> ExitBlocks; 97 ML.getExitBlocks(ExitBlocks); 98 for (auto *MBB : ExitBlocks) 99 Order.push_back(MBB); 100 101 // Then add the loop body. 102 Search(ML.getHeader()); 103 104 // Then try the preheader and its predecessors. 105 std::function<void(MachineBasicBlock*)> GetPredecessor = 106 [this, &GetPredecessor] (MachineBasicBlock *MBB) -> void { 107 Order.push_back(MBB); 108 if (MBB->pred_size() == 1) 109 GetPredecessor(*MBB->pred_begin()); 110 }; 111 112 if (auto *Preheader = ML.getLoopPreheader()) 113 GetPredecessor(Preheader); 114 else if (auto *Preheader = MLI.findLoopPreheader(&ML, true)) 115 GetPredecessor(Preheader); 116 } 117 }; 118 119 struct PredicatedMI { 120 MachineInstr *MI = nullptr; 121 SetVector<MachineInstr*> Predicates; 122 123 public: 124 PredicatedMI(MachineInstr *I, SetVector<MachineInstr*> &Preds) : 125 MI(I) { Predicates.insert(Preds.begin(), Preds.end()); } 126 }; 127 128 // Represent a VPT block, a list of instructions that begins with a VPST and 129 // has a maximum of four proceeding instructions. All instructions within the 130 // block are predicated upon the vpr and we allow instructions to define the 131 // vpr within in the block too. 132 class VPTBlock { 133 std::unique_ptr<PredicatedMI> VPST; 134 PredicatedMI *Divergent = nullptr; 135 SmallVector<PredicatedMI, 4> Insts; 136 137 public: 138 VPTBlock(MachineInstr *MI, SetVector<MachineInstr*> &Preds) { 139 VPST = std::make_unique<PredicatedMI>(MI, Preds); 140 } 141 142 void addInst(MachineInstr *MI, SetVector<MachineInstr*> &Preds) { 143 LLVM_DEBUG(dbgs() << "ARM Loops: Adding predicated MI: " << *MI); 144 if (!Divergent && !set_difference(Preds, VPST->Predicates).empty()) { 145 Divergent = &Insts.back(); 146 LLVM_DEBUG(dbgs() << " - has divergent predicate: " << *Divergent->MI); 147 } 148 Insts.emplace_back(MI, Preds); 149 assert(Insts.size() <= 4 && "Too many instructions in VPT block!"); 150 } 151 152 // Have we found an instruction within the block which defines the vpr? If 153 // so, not all the instructions in the block will have the same predicate. 154 bool HasNonUniformPredicate() const { 155 return Divergent != nullptr; 156 } 157 158 // Is the given instruction part of the predicate set controlling the entry 159 // to the block. 160 bool IsPredicatedOn(MachineInstr *MI) const { 161 return VPST->Predicates.count(MI); 162 } 163 164 // Is the given instruction the only predicate which controls the entry to 165 // the block. 166 bool IsOnlyPredicatedOn(MachineInstr *MI) const { 167 return IsPredicatedOn(MI) && VPST->Predicates.size() == 1; 168 } 169 170 unsigned size() const { return Insts.size(); } 171 SmallVectorImpl<PredicatedMI> &getInsts() { return Insts; } 172 MachineInstr *getVPST() const { return VPST->MI; } 173 PredicatedMI *getDivergent() const { return Divergent; } 174 }; 175 176 struct LowOverheadLoop { 177 178 MachineLoop &ML; 179 MachineLoopInfo &MLI; 180 ReachingDefAnalysis &RDA; 181 const TargetRegisterInfo &TRI; 182 MachineFunction *MF = nullptr; 183 MachineInstr *InsertPt = nullptr; 184 MachineInstr *Start = nullptr; 185 MachineInstr *Dec = nullptr; 186 MachineInstr *End = nullptr; 187 MachineInstr *VCTP = nullptr; 188 VPTBlock *CurrentBlock = nullptr; 189 SetVector<MachineInstr*> CurrentPredicate; 190 SmallVector<VPTBlock, 4> VPTBlocks; 191 SmallPtrSet<MachineInstr*, 4> ToRemove; 192 bool Revert = false; 193 bool CannotTailPredicate = false; 194 195 LowOverheadLoop(MachineLoop &ML, MachineLoopInfo &MLI, 196 ReachingDefAnalysis &RDA, const TargetRegisterInfo &TRI) 197 : ML(ML), MLI(MLI), RDA(RDA), TRI(TRI) { 198 MF = ML.getHeader()->getParent(); 199 } 200 201 // If this is an MVE instruction, check that we know how to use tail 202 // predication with it. Record VPT blocks and return whether the 203 // instruction is valid for tail predication. 204 bool ValidateMVEInst(MachineInstr *MI); 205 206 void AnalyseMVEInst(MachineInstr *MI) { 207 CannotTailPredicate = !ValidateMVEInst(MI); 208 } 209 210 bool IsTailPredicationLegal() const { 211 // For now, let's keep things really simple and only support a single 212 // block for tail predication. 213 return !Revert && FoundAllComponents() && VCTP && 214 !CannotTailPredicate && ML.getNumBlocks() == 1; 215 } 216 217 // Check that the predication in the loop will be equivalent once we 218 // perform the conversion. Also ensure that we can provide the number 219 // of elements to the loop start instruction. 220 bool ValidateTailPredicate(MachineInstr *StartInsertPt); 221 222 // Check that any values available outside of the loop will be the same 223 // after tail predication conversion. 224 bool ValidateLiveOuts() const; 225 226 // Is it safe to define LR with DLS/WLS? 227 // LR can be defined if it is the operand to start, because it's the same 228 // value, or if it's going to be equivalent to the operand to Start. 229 MachineInstr *isSafeToDefineLR(); 230 231 // Check the branch targets are within range and we satisfy our 232 // restrictions. 233 void CheckLegality(ARMBasicBlockUtils *BBUtils); 234 235 bool FoundAllComponents() const { 236 return Start && Dec && End; 237 } 238 239 SmallVectorImpl<VPTBlock> &getVPTBlocks() { return VPTBlocks; } 240 241 // Return the loop iteration count, or the number of elements if we're tail 242 // predicating. 243 MachineOperand &getCount() { 244 return IsTailPredicationLegal() ? 245 VCTP->getOperand(1) : Start->getOperand(0); 246 } 247 248 unsigned getStartOpcode() const { 249 bool IsDo = Start->getOpcode() == ARM::t2DoLoopStart; 250 if (!IsTailPredicationLegal()) 251 return IsDo ? ARM::t2DLS : ARM::t2WLS; 252 253 return VCTPOpcodeToLSTP(VCTP->getOpcode(), IsDo); 254 } 255 256 void dump() const { 257 if (Start) dbgs() << "ARM Loops: Found Loop Start: " << *Start; 258 if (Dec) dbgs() << "ARM Loops: Found Loop Dec: " << *Dec; 259 if (End) dbgs() << "ARM Loops: Found Loop End: " << *End; 260 if (VCTP) dbgs() << "ARM Loops: Found VCTP: " << *VCTP; 261 if (!FoundAllComponents()) 262 dbgs() << "ARM Loops: Not a low-overhead loop.\n"; 263 else if (!(Start && Dec && End)) 264 dbgs() << "ARM Loops: Failed to find all loop components.\n"; 265 } 266 }; 267 268 class ARMLowOverheadLoops : public MachineFunctionPass { 269 MachineFunction *MF = nullptr; 270 MachineLoopInfo *MLI = nullptr; 271 ReachingDefAnalysis *RDA = nullptr; 272 const ARMBaseInstrInfo *TII = nullptr; 273 MachineRegisterInfo *MRI = nullptr; 274 const TargetRegisterInfo *TRI = nullptr; 275 std::unique_ptr<ARMBasicBlockUtils> BBUtils = nullptr; 276 277 public: 278 static char ID; 279 280 ARMLowOverheadLoops() : MachineFunctionPass(ID) { } 281 282 void getAnalysisUsage(AnalysisUsage &AU) const override { 283 AU.setPreservesCFG(); 284 AU.addRequired<MachineLoopInfo>(); 285 AU.addRequired<ReachingDefAnalysis>(); 286 MachineFunctionPass::getAnalysisUsage(AU); 287 } 288 289 bool runOnMachineFunction(MachineFunction &MF) override; 290 291 MachineFunctionProperties getRequiredProperties() const override { 292 return MachineFunctionProperties().set( 293 MachineFunctionProperties::Property::NoVRegs).set( 294 MachineFunctionProperties::Property::TracksLiveness); 295 } 296 297 StringRef getPassName() const override { 298 return ARM_LOW_OVERHEAD_LOOPS_NAME; 299 } 300 301 private: 302 bool ProcessLoop(MachineLoop *ML); 303 304 bool RevertNonLoops(); 305 306 void RevertWhile(MachineInstr *MI) const; 307 308 bool RevertLoopDec(MachineInstr *MI) const; 309 310 void RevertLoopEnd(MachineInstr *MI, bool SkipCmp = false) const; 311 312 void ConvertVPTBlocks(LowOverheadLoop &LoLoop); 313 314 MachineInstr *ExpandLoopStart(LowOverheadLoop &LoLoop); 315 316 void Expand(LowOverheadLoop &LoLoop); 317 318 void IterationCountDCE(LowOverheadLoop &LoLoop); 319 }; 320 } 321 322 char ARMLowOverheadLoops::ID = 0; 323 324 INITIALIZE_PASS(ARMLowOverheadLoops, DEBUG_TYPE, ARM_LOW_OVERHEAD_LOOPS_NAME, 325 false, false) 326 327 MachineInstr *LowOverheadLoop::isSafeToDefineLR() { 328 // We can define LR because LR already contains the same value. 329 if (Start->getOperand(0).getReg() == ARM::LR) 330 return Start; 331 332 unsigned CountReg = Start->getOperand(0).getReg(); 333 auto IsMoveLR = [&CountReg](MachineInstr *MI) { 334 return MI->getOpcode() == ARM::tMOVr && 335 MI->getOperand(0).getReg() == ARM::LR && 336 MI->getOperand(1).getReg() == CountReg && 337 MI->getOperand(2).getImm() == ARMCC::AL; 338 }; 339 340 MachineBasicBlock *MBB = Start->getParent(); 341 342 // Find an insertion point: 343 // - Is there a (mov lr, Count) before Start? If so, and nothing else writes 344 // to Count before Start, we can insert at that mov. 345 if (auto *LRDef = RDA.getReachingMIDef(Start, ARM::LR)) 346 if (IsMoveLR(LRDef) && RDA.hasSameReachingDef(Start, LRDef, CountReg)) 347 return LRDef; 348 349 // - Is there a (mov lr, Count) after Start? If so, and nothing else writes 350 // to Count after Start, we can insert at that mov. 351 if (auto *LRDef = RDA.getLocalLiveOutMIDef(MBB, ARM::LR)) 352 if (IsMoveLR(LRDef) && RDA.hasSameReachingDef(Start, LRDef, CountReg)) 353 return LRDef; 354 355 // We've found no suitable LR def and Start doesn't use LR directly. Can we 356 // just define LR anyway? 357 return RDA.isSafeToDefRegAt(Start, ARM::LR) ? Start : nullptr; 358 } 359 360 bool LowOverheadLoop::ValidateTailPredicate(MachineInstr *StartInsertPt) { 361 assert(VCTP && "VCTP instruction expected but is not set"); 362 // All predication within the loop should be based on vctp. If the block 363 // isn't predicated on entry, check whether the vctp is within the block 364 // and that all other instructions are then predicated on it. 365 for (auto &Block : VPTBlocks) { 366 if (Block.IsPredicatedOn(VCTP)) 367 continue; 368 if (!Block.HasNonUniformPredicate() || !isVCTP(Block.getDivergent()->MI)) { 369 LLVM_DEBUG(dbgs() << "ARM Loops: Found unsupported diverging predicate: " 370 << *Block.getDivergent()->MI); 371 return false; 372 } 373 SmallVectorImpl<PredicatedMI> &Insts = Block.getInsts(); 374 for (auto &PredMI : Insts) { 375 if (PredMI.Predicates.count(VCTP) || isVCTP(PredMI.MI)) 376 continue; 377 LLVM_DEBUG(dbgs() << "ARM Loops: Can't convert: " << *PredMI.MI 378 << " - which is predicated on:\n"; 379 for (auto *MI : PredMI.Predicates) 380 dbgs() << " - " << *MI); 381 return false; 382 } 383 } 384 385 if (!ValidateLiveOuts()) 386 return false; 387 388 // For tail predication, we need to provide the number of elements, instead 389 // of the iteration count, to the loop start instruction. The number of 390 // elements is provided to the vctp instruction, so we need to check that 391 // we can use this register at InsertPt. 392 Register NumElements = VCTP->getOperand(1).getReg(); 393 394 // If the register is defined within loop, then we can't perform TP. 395 // TODO: Check whether this is just a mov of a register that would be 396 // available. 397 if (RDA.hasLocalDefBefore(VCTP, NumElements)) { 398 LLVM_DEBUG(dbgs() << "ARM Loops: VCTP operand is defined in the loop.\n"); 399 return false; 400 } 401 402 // The element count register maybe defined after InsertPt, in which case we 403 // need to try to move either InsertPt or the def so that the [w|d]lstp can 404 // use the value. 405 // TODO: On failing to move an instruction, check if the count is provided by 406 // a mov and whether we can use the mov operand directly. 407 MachineBasicBlock *InsertBB = StartInsertPt->getParent(); 408 if (!RDA.isReachingDefLiveOut(StartInsertPt, NumElements)) { 409 if (auto *ElemDef = RDA.getLocalLiveOutMIDef(InsertBB, NumElements)) { 410 if (RDA.isSafeToMoveForwards(ElemDef, StartInsertPt)) { 411 ElemDef->removeFromParent(); 412 InsertBB->insert(MachineBasicBlock::iterator(StartInsertPt), ElemDef); 413 LLVM_DEBUG(dbgs() << "ARM Loops: Moved element count def: " 414 << *ElemDef); 415 } else if (RDA.isSafeToMoveBackwards(StartInsertPt, ElemDef)) { 416 StartInsertPt->removeFromParent(); 417 InsertBB->insertAfter(MachineBasicBlock::iterator(ElemDef), 418 StartInsertPt); 419 LLVM_DEBUG(dbgs() << "ARM Loops: Moved start past: " << *ElemDef); 420 } else { 421 LLVM_DEBUG(dbgs() << "ARM Loops: Unable to move element count to loop " 422 << "start instruction.\n"); 423 return false; 424 } 425 } 426 } 427 428 // Especially in the case of while loops, InsertBB may not be the 429 // preheader, so we need to check that the register isn't redefined 430 // before entering the loop. 431 auto CannotProvideElements = [this](MachineBasicBlock *MBB, 432 Register NumElements) { 433 // NumElements is redefined in this block. 434 if (RDA.hasLocalDefBefore(&MBB->back(), NumElements)) 435 return true; 436 437 // Don't continue searching up through multiple predecessors. 438 if (MBB->pred_size() > 1) 439 return true; 440 441 return false; 442 }; 443 444 // First, find the block that looks like the preheader. 445 MachineBasicBlock *MBB = MLI.findLoopPreheader(&ML, true); 446 if (!MBB) { 447 LLVM_DEBUG(dbgs() << "ARM Loops: Didn't find preheader.\n"); 448 return false; 449 } 450 451 // Then search backwards for a def, until we get to InsertBB. 452 while (MBB != InsertBB) { 453 if (CannotProvideElements(MBB, NumElements)) { 454 LLVM_DEBUG(dbgs() << "ARM Loops: Unable to provide element count.\n"); 455 return false; 456 } 457 MBB = *MBB->pred_begin(); 458 } 459 460 // Check that the value change of the element count is what we expect and 461 // that the predication will be equivalent. For this we need: 462 // NumElements = NumElements - VectorWidth. The sub will be a sub immediate 463 // and we can also allow register copies within the chain too. 464 auto IsValidSub = [](MachineInstr *MI, unsigned ExpectedVecWidth) { 465 unsigned ImmOpIdx = 0; 466 switch (MI->getOpcode()) { 467 default: 468 llvm_unreachable("unhandled sub opcode"); 469 case ARM::tSUBi3: 470 case ARM::tSUBi8: 471 ImmOpIdx = 3; 472 break; 473 case ARM::t2SUBri: 474 case ARM::t2SUBri12: 475 ImmOpIdx = 2; 476 break; 477 } 478 return MI->getOperand(ImmOpIdx).getImm() == ExpectedVecWidth; 479 }; 480 481 MBB = VCTP->getParent(); 482 if (MachineInstr *Def = RDA.getReachingMIDef(&MBB->back(), NumElements)) { 483 SmallPtrSet<MachineInstr*, 2> ElementChain; 484 SmallPtrSet<MachineInstr*, 2> Ignore = { VCTP }; 485 unsigned ExpectedVectorWidth = getTailPredVectorWidth(VCTP->getOpcode()); 486 487 if (RDA.isSafeToRemove(Def, ElementChain, Ignore)) { 488 bool FoundSub = false; 489 490 for (auto *MI : ElementChain) { 491 if (isMovRegOpcode(MI->getOpcode())) 492 continue; 493 494 if (isSubImmOpcode(MI->getOpcode())) { 495 if (FoundSub || !IsValidSub(MI, ExpectedVectorWidth)) 496 return false; 497 FoundSub = true; 498 } else 499 return false; 500 } 501 502 LLVM_DEBUG(dbgs() << "ARM Loops: Will remove element count chain:\n"; 503 for (auto *MI : ElementChain) 504 dbgs() << " - " << *MI); 505 ToRemove.insert(ElementChain.begin(), ElementChain.end()); 506 } 507 } 508 return true; 509 } 510 511 bool LowOverheadLoop::ValidateLiveOuts() const { 512 // Collect Q-regs that are live in the exit blocks. We don't collect scalars 513 // because they won't be affected by lane predication. 514 const TargetRegisterClass *QPRs = TRI.getRegClass(ARM::MQPRRegClassID); 515 SmallSet<Register, 2> LiveOuts; 516 SmallVector<MachineBasicBlock*, 2> ExitBlocks; 517 ML.getExitBlocks(ExitBlocks); 518 for (auto *MBB : ExitBlocks) 519 for (const MachineBasicBlock::RegisterMaskPair &RegMask : MBB->liveins()) 520 if (QPRs->contains(RegMask.PhysReg)) 521 LiveOuts.insert(RegMask.PhysReg); 522 523 // Collect the instructions in the loop body that define the live-out values. 524 SmallPtrSet<MachineInstr*, 2> LiveMIs; 525 MachineBasicBlock *MBB = ML.getHeader(); 526 for (auto Reg : LiveOuts) 527 if (auto *MI = RDA.getLocalLiveOutMIDef(MBB, Reg)) 528 LiveMIs.insert(MI); 529 530 LLVM_DEBUG(dbgs() << "ARM Loops: Found loop live-outs:\n"; 531 for (auto *MI : LiveMIs) 532 dbgs() << " - " << *MI); 533 // We've already validated that any VPT predication within the loop will be 534 // equivalent when we perform the predication transformation; so we know that 535 // any VPT predicated instruction is predicated upon VCTP. Any live-out 536 // instruction needs to be predicated, so check this here. 537 for (auto *MI : LiveMIs) { 538 int PIdx = llvm::findFirstVPTPredOperandIdx(*MI); 539 if (PIdx == -1 || MI->getOperand(PIdx+1).getReg() != ARM::VPR) 540 return false; 541 } 542 543 return true; 544 } 545 546 void LowOverheadLoop::CheckLegality(ARMBasicBlockUtils *BBUtils) { 547 if (Revert) 548 return; 549 550 if (!End->getOperand(1).isMBB()) 551 report_fatal_error("Expected LoopEnd to target basic block"); 552 553 // TODO Maybe there's cases where the target doesn't have to be the header, 554 // but for now be safe and revert. 555 if (End->getOperand(1).getMBB() != ML.getHeader()) { 556 LLVM_DEBUG(dbgs() << "ARM Loops: LoopEnd is not targetting header.\n"); 557 Revert = true; 558 return; 559 } 560 561 // The WLS and LE instructions have 12-bits for the label offset. WLS 562 // requires a positive offset, while LE uses negative. 563 if (BBUtils->getOffsetOf(End) < BBUtils->getOffsetOf(ML.getHeader()) || 564 !BBUtils->isBBInRange(End, ML.getHeader(), 4094)) { 565 LLVM_DEBUG(dbgs() << "ARM Loops: LE offset is out-of-range\n"); 566 Revert = true; 567 return; 568 } 569 570 if (Start->getOpcode() == ARM::t2WhileLoopStart && 571 (BBUtils->getOffsetOf(Start) > 572 BBUtils->getOffsetOf(Start->getOperand(1).getMBB()) || 573 !BBUtils->isBBInRange(Start, Start->getOperand(1).getMBB(), 4094))) { 574 LLVM_DEBUG(dbgs() << "ARM Loops: WLS offset is out-of-range!\n"); 575 Revert = true; 576 return; 577 } 578 579 InsertPt = Revert ? nullptr : isSafeToDefineLR(); 580 if (!InsertPt) { 581 LLVM_DEBUG(dbgs() << "ARM Loops: Unable to find safe insertion point.\n"); 582 Revert = true; 583 return; 584 } else 585 LLVM_DEBUG(dbgs() << "ARM Loops: Start insertion point: " << *InsertPt); 586 587 if (!IsTailPredicationLegal()) { 588 LLVM_DEBUG(if (!VCTP) 589 dbgs() << "ARM Loops: Didn't find a VCTP instruction.\n"; 590 dbgs() << "ARM Loops: Tail-predication is not valid.\n"); 591 return; 592 } 593 594 assert(ML.getBlocks().size() == 1 && 595 "Shouldn't be processing a loop with more than one block"); 596 CannotTailPredicate = !ValidateTailPredicate(InsertPt); 597 LLVM_DEBUG(if (CannotTailPredicate) 598 dbgs() << "ARM Loops: Couldn't validate tail predicate.\n"); 599 } 600 601 bool LowOverheadLoop::ValidateMVEInst(MachineInstr* MI) { 602 if (CannotTailPredicate) 603 return false; 604 605 // Only support a single vctp. 606 if (isVCTP(MI) && VCTP) 607 return false; 608 609 // Start a new vpt block when we discover a vpt. 610 if (MI->getOpcode() == ARM::MVE_VPST) { 611 VPTBlocks.emplace_back(MI, CurrentPredicate); 612 CurrentBlock = &VPTBlocks.back(); 613 return true; 614 } else if (isVCTP(MI)) 615 VCTP = MI; 616 else if (MI->getOpcode() == ARM::MVE_VPSEL || 617 MI->getOpcode() == ARM::MVE_VPNOT) 618 return false; 619 620 // TODO: Allow VPSEL and VPNOT, we currently cannot because: 621 // 1) It will use the VPR as a predicate operand, but doesn't have to be 622 // instead a VPT block, which means we can assert while building up 623 // the VPT block because we don't find another VPST to being a new 624 // one. 625 // 2) VPSEL still requires a VPR operand even after tail predicating, 626 // which means we can't remove it unless there is another 627 // instruction, such as vcmp, that can provide the VPR def. 628 629 bool IsUse = false; 630 bool IsDef = false; 631 const MCInstrDesc &MCID = MI->getDesc(); 632 for (int i = MI->getNumOperands() - 1; i >= 0; --i) { 633 const MachineOperand &MO = MI->getOperand(i); 634 if (!MO.isReg() || MO.getReg() != ARM::VPR) 635 continue; 636 637 if (MO.isDef()) { 638 CurrentPredicate.insert(MI); 639 IsDef = true; 640 } else if (ARM::isVpred(MCID.OpInfo[i].OperandType)) { 641 CurrentBlock->addInst(MI, CurrentPredicate); 642 IsUse = true; 643 } else { 644 LLVM_DEBUG(dbgs() << "ARM Loops: Found instruction using vpr: " << *MI); 645 return false; 646 } 647 } 648 649 // If we find a vpr def that is not already predicated on the vctp, we've 650 // got disjoint predicates that may not be equivalent when we do the 651 // conversion. 652 if (IsDef && !IsUse && VCTP && !isVCTP(MI)) { 653 LLVM_DEBUG(dbgs() << "ARM Loops: Found disjoint vpr def: " << *MI); 654 return false; 655 } 656 657 uint64_t Flags = MCID.TSFlags; 658 if ((Flags & ARMII::DomainMask) != ARMII::DomainMVE) 659 return true; 660 661 // If we find an instruction that has been marked as not valid for tail 662 // predication, only allow the instruction if it's contained within a valid 663 // VPT block. 664 if ((Flags & ARMII::ValidForTailPredication) == 0 && !IsUse) { 665 LLVM_DEBUG(dbgs() << "ARM Loops: Can't tail predicate: " << *MI); 666 return false; 667 } 668 669 // If the instruction is already explicitly predicated, then the conversion 670 // will be fine, but ensure that all memory operations are predicated. 671 return !IsUse && MI->mayLoadOrStore() ? false : true; 672 } 673 674 bool ARMLowOverheadLoops::runOnMachineFunction(MachineFunction &mf) { 675 const ARMSubtarget &ST = static_cast<const ARMSubtarget&>(mf.getSubtarget()); 676 if (!ST.hasLOB()) 677 return false; 678 679 MF = &mf; 680 LLVM_DEBUG(dbgs() << "ARM Loops on " << MF->getName() << " ------------- \n"); 681 682 MLI = &getAnalysis<MachineLoopInfo>(); 683 RDA = &getAnalysis<ReachingDefAnalysis>(); 684 MF->getProperties().set(MachineFunctionProperties::Property::TracksLiveness); 685 MRI = &MF->getRegInfo(); 686 TII = static_cast<const ARMBaseInstrInfo*>(ST.getInstrInfo()); 687 TRI = ST.getRegisterInfo(); 688 BBUtils = std::unique_ptr<ARMBasicBlockUtils>(new ARMBasicBlockUtils(*MF)); 689 BBUtils->computeAllBlockSizes(); 690 BBUtils->adjustBBOffsetsAfter(&MF->front()); 691 692 bool Changed = false; 693 for (auto ML : *MLI) { 694 if (!ML->getParentLoop()) 695 Changed |= ProcessLoop(ML); 696 } 697 Changed |= RevertNonLoops(); 698 return Changed; 699 } 700 701 bool ARMLowOverheadLoops::ProcessLoop(MachineLoop *ML) { 702 703 bool Changed = false; 704 705 // Process inner loops first. 706 for (auto I = ML->begin(), E = ML->end(); I != E; ++I) 707 Changed |= ProcessLoop(*I); 708 709 LLVM_DEBUG(dbgs() << "ARM Loops: Processing loop containing:\n"; 710 if (auto *Preheader = ML->getLoopPreheader()) 711 dbgs() << " - " << Preheader->getName() << "\n"; 712 else if (auto *Preheader = MLI->findLoopPreheader(ML)) 713 dbgs() << " - " << Preheader->getName() << "\n"; 714 else if (auto *Preheader = MLI->findLoopPreheader(ML, true)) 715 dbgs() << " - " << Preheader->getName() << "\n"; 716 for (auto *MBB : ML->getBlocks()) 717 dbgs() << " - " << MBB->getName() << "\n"; 718 ); 719 720 // Search the given block for a loop start instruction. If one isn't found, 721 // and there's only one predecessor block, search that one too. 722 std::function<MachineInstr*(MachineBasicBlock*)> SearchForStart = 723 [&SearchForStart](MachineBasicBlock *MBB) -> MachineInstr* { 724 for (auto &MI : *MBB) { 725 if (isLoopStart(MI)) 726 return &MI; 727 } 728 if (MBB->pred_size() == 1) 729 return SearchForStart(*MBB->pred_begin()); 730 return nullptr; 731 }; 732 733 LowOverheadLoop LoLoop(*ML, *MLI, *RDA, *TRI); 734 // Search the preheader for the start intrinsic. 735 // FIXME: I don't see why we shouldn't be supporting multiple predecessors 736 // with potentially multiple set.loop.iterations, so we need to enable this. 737 if (auto *Preheader = ML->getLoopPreheader()) 738 LoLoop.Start = SearchForStart(Preheader); 739 else if (auto *Preheader = MLI->findLoopPreheader(ML, true)) 740 LoLoop.Start = SearchForStart(Preheader); 741 else 742 return false; 743 744 // Find the low-overhead loop components and decide whether or not to fall 745 // back to a normal loop. Also look for a vctp instructions and decide 746 // whether we can convert that predicate using tail predication. 747 for (auto *MBB : reverse(ML->getBlocks())) { 748 for (auto &MI : *MBB) { 749 if (MI.isDebugValue()) 750 continue; 751 else if (MI.getOpcode() == ARM::t2LoopDec) 752 LoLoop.Dec = &MI; 753 else if (MI.getOpcode() == ARM::t2LoopEnd) 754 LoLoop.End = &MI; 755 else if (isLoopStart(MI)) 756 LoLoop.Start = &MI; 757 else if (MI.getDesc().isCall()) { 758 // TODO: Though the call will require LE to execute again, does this 759 // mean we should revert? Always executing LE hopefully should be 760 // faster than performing a sub,cmp,br or even subs,br. 761 LoLoop.Revert = true; 762 LLVM_DEBUG(dbgs() << "ARM Loops: Found call.\n"); 763 } else { 764 // Record VPR defs and build up their corresponding vpt blocks. 765 // Check we know how to tail predicate any mve instructions. 766 LoLoop.AnalyseMVEInst(&MI); 767 } 768 } 769 } 770 771 LLVM_DEBUG(LoLoop.dump()); 772 if (!LoLoop.FoundAllComponents()) { 773 LLVM_DEBUG(dbgs() << "ARM Loops: Didn't find loop start, update, end\n"); 774 return false; 775 } 776 777 // Check that the only instruction using LoopDec is LoopEnd. 778 // TODO: Check for copy chains that really have no effect. 779 SmallPtrSet<MachineInstr*, 2> Uses; 780 RDA->getReachingLocalUses(LoLoop.Dec, ARM::LR, Uses); 781 if (Uses.size() > 1 || !Uses.count(LoLoop.End)) { 782 LLVM_DEBUG(dbgs() << "ARM Loops: Unable to remove LoopDec.\n"); 783 LoLoop.Revert = true; 784 } 785 LoLoop.CheckLegality(BBUtils.get()); 786 Expand(LoLoop); 787 return true; 788 } 789 790 // WhileLoopStart holds the exit block, so produce a cmp lr, 0 and then a 791 // beq that branches to the exit branch. 792 // TODO: We could also try to generate a cbz if the value in LR is also in 793 // another low register. 794 void ARMLowOverheadLoops::RevertWhile(MachineInstr *MI) const { 795 LLVM_DEBUG(dbgs() << "ARM Loops: Reverting to cmp: " << *MI); 796 MachineBasicBlock *MBB = MI->getParent(); 797 MachineInstrBuilder MIB = BuildMI(*MBB, MI, MI->getDebugLoc(), 798 TII->get(ARM::t2CMPri)); 799 MIB.add(MI->getOperand(0)); 800 MIB.addImm(0); 801 MIB.addImm(ARMCC::AL); 802 MIB.addReg(ARM::NoRegister); 803 804 MachineBasicBlock *DestBB = MI->getOperand(1).getMBB(); 805 unsigned BrOpc = BBUtils->isBBInRange(MI, DestBB, 254) ? 806 ARM::tBcc : ARM::t2Bcc; 807 808 MIB = BuildMI(*MBB, MI, MI->getDebugLoc(), TII->get(BrOpc)); 809 MIB.add(MI->getOperand(1)); // branch target 810 MIB.addImm(ARMCC::EQ); // condition code 811 MIB.addReg(ARM::CPSR); 812 MI->eraseFromParent(); 813 } 814 815 bool ARMLowOverheadLoops::RevertLoopDec(MachineInstr *MI) const { 816 LLVM_DEBUG(dbgs() << "ARM Loops: Reverting to sub: " << *MI); 817 MachineBasicBlock *MBB = MI->getParent(); 818 MachineInstr *Last = &MBB->back(); 819 SmallPtrSet<MachineInstr*, 1> Ignore; 820 if (Last->getOpcode() == ARM::t2LoopEnd) 821 Ignore.insert(Last); 822 823 // If nothing defines CPSR between LoopDec and LoopEnd, use a t2SUBS. 824 bool SetFlags = RDA->isSafeToDefRegAt(MI, ARM::CPSR, Ignore); 825 826 MachineInstrBuilder MIB = BuildMI(*MBB, MI, MI->getDebugLoc(), 827 TII->get(ARM::t2SUBri)); 828 MIB.addDef(ARM::LR); 829 MIB.add(MI->getOperand(1)); 830 MIB.add(MI->getOperand(2)); 831 MIB.addImm(ARMCC::AL); 832 MIB.addReg(0); 833 834 if (SetFlags) { 835 MIB.addReg(ARM::CPSR); 836 MIB->getOperand(5).setIsDef(true); 837 } else 838 MIB.addReg(0); 839 840 MI->eraseFromParent(); 841 return SetFlags; 842 } 843 844 // Generate a subs, or sub and cmp, and a branch instead of an LE. 845 void ARMLowOverheadLoops::RevertLoopEnd(MachineInstr *MI, bool SkipCmp) const { 846 LLVM_DEBUG(dbgs() << "ARM Loops: Reverting to cmp, br: " << *MI); 847 848 MachineBasicBlock *MBB = MI->getParent(); 849 // Create cmp 850 if (!SkipCmp) { 851 MachineInstrBuilder MIB = BuildMI(*MBB, MI, MI->getDebugLoc(), 852 TII->get(ARM::t2CMPri)); 853 MIB.addReg(ARM::LR); 854 MIB.addImm(0); 855 MIB.addImm(ARMCC::AL); 856 MIB.addReg(ARM::NoRegister); 857 } 858 859 MachineBasicBlock *DestBB = MI->getOperand(1).getMBB(); 860 unsigned BrOpc = BBUtils->isBBInRange(MI, DestBB, 254) ? 861 ARM::tBcc : ARM::t2Bcc; 862 863 // Create bne 864 MachineInstrBuilder MIB = 865 BuildMI(*MBB, MI, MI->getDebugLoc(), TII->get(BrOpc)); 866 MIB.add(MI->getOperand(1)); // branch target 867 MIB.addImm(ARMCC::NE); // condition code 868 MIB.addReg(ARM::CPSR); 869 MI->eraseFromParent(); 870 } 871 872 // Perform dead code elimation on the loop iteration count setup expression. 873 // If we are tail-predicating, the number of elements to be processed is the 874 // operand of the VCTP instruction in the vector body, see getCount(), which is 875 // register $r3 in this example: 876 // 877 // $lr = big-itercount-expression 878 // .. 879 // t2DoLoopStart renamable $lr 880 // vector.body: 881 // .. 882 // $vpr = MVE_VCTP32 renamable $r3 883 // renamable $lr = t2LoopDec killed renamable $lr, 1 884 // t2LoopEnd renamable $lr, %vector.body 885 // tB %end 886 // 887 // What we would like achieve here is to replace the do-loop start pseudo 888 // instruction t2DoLoopStart with: 889 // 890 // $lr = MVE_DLSTP_32 killed renamable $r3 891 // 892 // Thus, $r3 which defines the number of elements, is written to $lr, 893 // and then we want to delete the whole chain that used to define $lr, 894 // see the comment below how this chain could look like. 895 // 896 void ARMLowOverheadLoops::IterationCountDCE(LowOverheadLoop &LoLoop) { 897 if (!LoLoop.IsTailPredicationLegal()) 898 return; 899 900 if (auto *Def = RDA->getReachingMIDef(LoLoop.Start, 901 LoLoop.Start->getOperand(0).getReg())) { 902 SmallPtrSet<MachineInstr*, 4> Remove; 903 SmallPtrSet<MachineInstr*, 4> Ignore = { LoLoop.Start, LoLoop.Dec, 904 LoLoop.End, LoLoop.InsertPt }; 905 SmallVector<MachineInstr*, 4> Chain = { Def }; 906 while (!Chain.empty()) { 907 MachineInstr *MI = Chain.back(); 908 Chain.pop_back(); 909 910 // If an instruction is conditionally executed, we assume here that this 911 // an IT-block with just this single instruction in it, otherwise we 912 // continue and can't perform dead-code elimination on it. This will 913 // capture most cases, because the loop iteration count expression 914 // that performs a round-up to next multiple of the vector length will 915 // look like this: 916 // 917 // %mull = .. 918 // %0 = add i32 %mul, 3 919 // %1 = icmp slt i32 %mul, 4 920 // %smin = select i1 %1, i32 %mul, i32 4 921 // %2 = sub i32 %0, %smin 922 // %3 = lshr i32 %2, 2 923 // %4 = add nuw nsw i32 %3, 1 924 // 925 // There can be a select instruction, checking if we need to execute only 926 // 1 vector iteration (in this examples that means 4 elements). Thus, 927 // we conditionally execute one instructions to materialise the iteration 928 // count. 929 MachineInstr *IT = nullptr; 930 if (TII->getPredicate(*MI) != ARMCC::AL) { 931 auto PrevMI = std::prev(MI->getIterator()); 932 auto NextMI = std::next(MI->getIterator()); 933 934 if (PrevMI->getOpcode() == ARM::t2IT && 935 TII->getPredicate(*NextMI) == ARMCC::AL) 936 IT = &*PrevMI; 937 else 938 // We can't analyse IT-blocks with multiple statements. Be 939 // conservative here: clear the list, and don't remove any statements 940 // at all. 941 return; 942 } 943 944 if (RDA->isSafeToRemove(MI, Remove, Ignore)) { 945 for (auto &MO : MI->operands()) { 946 if (!MO.isReg() || !MO.isUse() || MO.getReg() == 0) 947 continue; 948 if (auto *Op = RDA->getReachingMIDef(MI, MO.getReg())) 949 Chain.push_back(Op); 950 } 951 Ignore.insert(MI); 952 953 if (IT) 954 Remove.insert(IT); 955 } 956 } 957 LoLoop.ToRemove.insert(Remove.begin(), Remove.end()); 958 } 959 } 960 961 MachineInstr* ARMLowOverheadLoops::ExpandLoopStart(LowOverheadLoop &LoLoop) { 962 LLVM_DEBUG(dbgs() << "ARM Loops: Expanding LoopStart.\n"); 963 // When using tail-predication, try to delete the dead code that was used to 964 // calculate the number of loop iterations. 965 IterationCountDCE(LoLoop); 966 967 MachineInstr *InsertPt = LoLoop.InsertPt; 968 MachineInstr *Start = LoLoop.Start; 969 MachineBasicBlock *MBB = InsertPt->getParent(); 970 bool IsDo = Start->getOpcode() == ARM::t2DoLoopStart; 971 unsigned Opc = LoLoop.getStartOpcode(); 972 MachineOperand &Count = LoLoop.getCount(); 973 974 MachineInstrBuilder MIB = 975 BuildMI(*MBB, InsertPt, InsertPt->getDebugLoc(), TII->get(Opc)); 976 977 MIB.addDef(ARM::LR); 978 MIB.add(Count); 979 if (!IsDo) 980 MIB.add(Start->getOperand(1)); 981 982 // If we're inserting at a mov lr, then remove it as it's redundant. 983 if (InsertPt != Start) 984 LoLoop.ToRemove.insert(InsertPt); 985 LoLoop.ToRemove.insert(Start); 986 LLVM_DEBUG(dbgs() << "ARM Loops: Inserted start: " << *MIB); 987 return &*MIB; 988 } 989 990 void ARMLowOverheadLoops::ConvertVPTBlocks(LowOverheadLoop &LoLoop) { 991 auto RemovePredicate = [](MachineInstr *MI) { 992 LLVM_DEBUG(dbgs() << "ARM Loops: Removing predicate from: " << *MI); 993 if (int PIdx = llvm::findFirstVPTPredOperandIdx(*MI)) { 994 assert(MI->getOperand(PIdx).getImm() == ARMVCC::Then && 995 "Expected Then predicate!"); 996 MI->getOperand(PIdx).setImm(ARMVCC::None); 997 MI->getOperand(PIdx+1).setReg(0); 998 } else 999 llvm_unreachable("trying to unpredicate a non-predicated instruction"); 1000 }; 1001 1002 // There are a few scenarios which we have to fix up: 1003 // 1) A VPT block with is only predicated by the vctp and has no internal vpr 1004 // defs. 1005 // 2) A VPT block which is only predicated by the vctp but has an internal 1006 // vpr def. 1007 // 3) A VPT block which is predicated upon the vctp as well as another vpr 1008 // def. 1009 // 4) A VPT block which is not predicated upon a vctp, but contains it and 1010 // all instructions within the block are predicated upon in. 1011 1012 for (auto &Block : LoLoop.getVPTBlocks()) { 1013 SmallVectorImpl<PredicatedMI> &Insts = Block.getInsts(); 1014 if (Block.HasNonUniformPredicate()) { 1015 PredicatedMI *Divergent = Block.getDivergent(); 1016 if (isVCTP(Divergent->MI)) { 1017 // The vctp will be removed, so the size of the vpt block needs to be 1018 // modified. 1019 uint64_t Size = getARMVPTBlockMask(Block.size() - 1); 1020 Block.getVPST()->getOperand(0).setImm(Size); 1021 LLVM_DEBUG(dbgs() << "ARM Loops: Modified VPT block mask.\n"); 1022 } else if (Block.IsOnlyPredicatedOn(LoLoop.VCTP)) { 1023 // The VPT block has a non-uniform predicate but it's entry is guarded 1024 // only by a vctp, which means we: 1025 // - Need to remove the original vpst. 1026 // - Then need to unpredicate any following instructions, until 1027 // we come across the divergent vpr def. 1028 // - Insert a new vpst to predicate the instruction(s) that following 1029 // the divergent vpr def. 1030 // TODO: We could be producing more VPT blocks than necessary and could 1031 // fold the newly created one into a proceeding one. 1032 for (auto I = ++MachineBasicBlock::iterator(Block.getVPST()), 1033 E = ++MachineBasicBlock::iterator(Divergent->MI); I != E; ++I) 1034 RemovePredicate(&*I); 1035 1036 unsigned Size = 0; 1037 auto E = MachineBasicBlock::reverse_iterator(Divergent->MI); 1038 auto I = MachineBasicBlock::reverse_iterator(Insts.back().MI); 1039 MachineInstr *InsertAt = nullptr; 1040 while (I != E) { 1041 InsertAt = &*I; 1042 ++Size; 1043 ++I; 1044 } 1045 MachineInstrBuilder MIB = BuildMI(*InsertAt->getParent(), InsertAt, 1046 InsertAt->getDebugLoc(), 1047 TII->get(ARM::MVE_VPST)); 1048 MIB.addImm(getARMVPTBlockMask(Size)); 1049 LLVM_DEBUG(dbgs() << "ARM Loops: Removing VPST: " << *Block.getVPST()); 1050 LLVM_DEBUG(dbgs() << "ARM Loops: Created VPST: " << *MIB); 1051 LoLoop.ToRemove.insert(Block.getVPST()); 1052 } 1053 } else if (Block.IsOnlyPredicatedOn(LoLoop.VCTP)) { 1054 // A vpt block which is only predicated upon vctp and has no internal vpr 1055 // defs: 1056 // - Remove vpst. 1057 // - Unpredicate the remaining instructions. 1058 LLVM_DEBUG(dbgs() << "ARM Loops: Removing VPST: " << *Block.getVPST()); 1059 LoLoop.ToRemove.insert(Block.getVPST()); 1060 for (auto &PredMI : Insts) 1061 RemovePredicate(PredMI.MI); 1062 } 1063 } 1064 LLVM_DEBUG(dbgs() << "ARM Loops: Removing VCTP: " << *LoLoop.VCTP); 1065 LoLoop.ToRemove.insert(LoLoop.VCTP); 1066 } 1067 1068 void ARMLowOverheadLoops::Expand(LowOverheadLoop &LoLoop) { 1069 1070 // Combine the LoopDec and LoopEnd instructions into LE(TP). 1071 auto ExpandLoopEnd = [this](LowOverheadLoop &LoLoop) { 1072 MachineInstr *End = LoLoop.End; 1073 MachineBasicBlock *MBB = End->getParent(); 1074 unsigned Opc = LoLoop.IsTailPredicationLegal() ? 1075 ARM::MVE_LETP : ARM::t2LEUpdate; 1076 MachineInstrBuilder MIB = BuildMI(*MBB, End, End->getDebugLoc(), 1077 TII->get(Opc)); 1078 MIB.addDef(ARM::LR); 1079 MIB.add(End->getOperand(0)); 1080 MIB.add(End->getOperand(1)); 1081 LLVM_DEBUG(dbgs() << "ARM Loops: Inserted LE: " << *MIB); 1082 LoLoop.Dec->eraseFromParent(); 1083 End->eraseFromParent(); 1084 return &*MIB; 1085 }; 1086 1087 // TODO: We should be able to automatically remove these branches before we 1088 // get here - probably by teaching analyzeBranch about the pseudo 1089 // instructions. 1090 // If there is an unconditional branch, after I, that just branches to the 1091 // next block, remove it. 1092 auto RemoveDeadBranch = [](MachineInstr *I) { 1093 MachineBasicBlock *BB = I->getParent(); 1094 MachineInstr *Terminator = &BB->instr_back(); 1095 if (Terminator->isUnconditionalBranch() && I != Terminator) { 1096 MachineBasicBlock *Succ = Terminator->getOperand(0).getMBB(); 1097 if (BB->isLayoutSuccessor(Succ)) { 1098 LLVM_DEBUG(dbgs() << "ARM Loops: Removing branch: " << *Terminator); 1099 Terminator->eraseFromParent(); 1100 } 1101 } 1102 }; 1103 1104 if (LoLoop.Revert) { 1105 if (LoLoop.Start->getOpcode() == ARM::t2WhileLoopStart) 1106 RevertWhile(LoLoop.Start); 1107 else 1108 LoLoop.Start->eraseFromParent(); 1109 bool FlagsAlreadySet = RevertLoopDec(LoLoop.Dec); 1110 RevertLoopEnd(LoLoop.End, FlagsAlreadySet); 1111 } else { 1112 LoLoop.Start = ExpandLoopStart(LoLoop); 1113 RemoveDeadBranch(LoLoop.Start); 1114 LoLoop.End = ExpandLoopEnd(LoLoop); 1115 RemoveDeadBranch(LoLoop.End); 1116 if (LoLoop.IsTailPredicationLegal()) 1117 ConvertVPTBlocks(LoLoop); 1118 for (auto *I : LoLoop.ToRemove) { 1119 LLVM_DEBUG(dbgs() << "ARM Loops: Erasing " << *I); 1120 I->eraseFromParent(); 1121 } 1122 } 1123 1124 PostOrderLoopTraversal DFS(LoLoop.ML, *MLI); 1125 DFS.ProcessLoop(); 1126 const SmallVectorImpl<MachineBasicBlock*> &PostOrder = DFS.getOrder(); 1127 for (auto *MBB : PostOrder) { 1128 recomputeLiveIns(*MBB); 1129 // FIXME: For some reason, the live-in print order is non-deterministic for 1130 // our tests and I can't out why... So just sort them. 1131 MBB->sortUniqueLiveIns(); 1132 } 1133 1134 for (auto *MBB : reverse(PostOrder)) 1135 recomputeLivenessFlags(*MBB); 1136 } 1137 1138 bool ARMLowOverheadLoops::RevertNonLoops() { 1139 LLVM_DEBUG(dbgs() << "ARM Loops: Reverting any remaining pseudos...\n"); 1140 bool Changed = false; 1141 1142 for (auto &MBB : *MF) { 1143 SmallVector<MachineInstr*, 4> Starts; 1144 SmallVector<MachineInstr*, 4> Decs; 1145 SmallVector<MachineInstr*, 4> Ends; 1146 1147 for (auto &I : MBB) { 1148 if (isLoopStart(I)) 1149 Starts.push_back(&I); 1150 else if (I.getOpcode() == ARM::t2LoopDec) 1151 Decs.push_back(&I); 1152 else if (I.getOpcode() == ARM::t2LoopEnd) 1153 Ends.push_back(&I); 1154 } 1155 1156 if (Starts.empty() && Decs.empty() && Ends.empty()) 1157 continue; 1158 1159 Changed = true; 1160 1161 for (auto *Start : Starts) { 1162 if (Start->getOpcode() == ARM::t2WhileLoopStart) 1163 RevertWhile(Start); 1164 else 1165 Start->eraseFromParent(); 1166 } 1167 for (auto *Dec : Decs) 1168 RevertLoopDec(Dec); 1169 1170 for (auto *End : Ends) 1171 RevertLoopEnd(End); 1172 } 1173 return Changed; 1174 } 1175 1176 FunctionPass *llvm::createARMLowOverheadLoopsPass() { 1177 return new ARMLowOverheadLoops(); 1178 } 1179