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 /// A note on VPR.P0 (the lane mask): 39 /// VPT, VCMP, VPNOT and VCTP won't overwrite VPR.P0 when they update it in a 40 /// "VPT Active" context (which includes low-overhead loops and vpt blocks). 41 /// They will simply "and" the result of their calculation with the current 42 /// value of VPR.P0. You can think of it like this: 43 /// \verbatim 44 /// if VPT active: ; Between a DLSTP/LETP, or for predicated instrs 45 /// VPR.P0 &= Value 46 /// else 47 /// VPR.P0 = Value 48 /// \endverbatim 49 /// When we're inside the low-overhead loop (between DLSTP and LETP), we always 50 /// fall in the "VPT active" case, so we can consider that all VPR writes by 51 /// one of those instruction is actually a "and". 52 //===----------------------------------------------------------------------===// 53 54 #include "ARM.h" 55 #include "ARMBaseInstrInfo.h" 56 #include "ARMBaseRegisterInfo.h" 57 #include "ARMBasicBlockInfo.h" 58 #include "ARMSubtarget.h" 59 #include "MVETailPredUtils.h" 60 #include "Thumb2InstrInfo.h" 61 #include "llvm/ADT/SetOperations.h" 62 #include "llvm/ADT/SmallSet.h" 63 #include "llvm/CodeGen/LivePhysRegs.h" 64 #include "llvm/CodeGen/MachineFunctionPass.h" 65 #include "llvm/CodeGen/MachineLoopInfo.h" 66 #include "llvm/CodeGen/MachineLoopUtils.h" 67 #include "llvm/CodeGen/MachineRegisterInfo.h" 68 #include "llvm/CodeGen/Passes.h" 69 #include "llvm/CodeGen/ReachingDefAnalysis.h" 70 #include "llvm/MC/MCInstrDesc.h" 71 72 using namespace llvm; 73 74 #define DEBUG_TYPE "arm-low-overhead-loops" 75 #define ARM_LOW_OVERHEAD_LOOPS_NAME "ARM Low Overhead Loops pass" 76 77 static cl::opt<bool> 78 DisableTailPredication("arm-loloops-disable-tailpred", cl::Hidden, 79 cl::desc("Disable tail-predication in the ARM LowOverheadLoop pass"), 80 cl::init(false)); 81 82 static bool isVectorPredicated(MachineInstr *MI) { 83 int PIdx = llvm::findFirstVPTPredOperandIdx(*MI); 84 return PIdx != -1 && MI->getOperand(PIdx + 1).getReg() == ARM::VPR; 85 } 86 87 static bool isVectorPredicate(MachineInstr *MI) { 88 return MI->findRegisterDefOperandIdx(ARM::VPR) != -1; 89 } 90 91 static bool hasVPRUse(MachineInstr &MI) { 92 return MI.findRegisterUseOperandIdx(ARM::VPR) != -1; 93 } 94 95 static bool isDomainMVE(MachineInstr *MI) { 96 uint64_t Domain = MI->getDesc().TSFlags & ARMII::DomainMask; 97 return Domain == ARMII::DomainMVE; 98 } 99 100 static bool shouldInspect(MachineInstr &MI) { 101 return isDomainMVE(&MI) || isVectorPredicate(&MI) || hasVPRUse(MI); 102 } 103 104 static bool isDo(MachineInstr *MI) { 105 return MI->getOpcode() != ARM::t2WhileLoopStart; 106 } 107 108 namespace { 109 110 using InstSet = SmallPtrSetImpl<MachineInstr *>; 111 112 class PostOrderLoopTraversal { 113 MachineLoop &ML; 114 MachineLoopInfo &MLI; 115 SmallPtrSet<MachineBasicBlock*, 4> Visited; 116 SmallVector<MachineBasicBlock*, 4> Order; 117 118 public: 119 PostOrderLoopTraversal(MachineLoop &ML, MachineLoopInfo &MLI) 120 : ML(ML), MLI(MLI) { } 121 122 const SmallVectorImpl<MachineBasicBlock*> &getOrder() const { 123 return Order; 124 } 125 126 // Visit all the blocks within the loop, as well as exit blocks and any 127 // blocks properly dominating the header. 128 void ProcessLoop() { 129 std::function<void(MachineBasicBlock*)> Search = [this, &Search] 130 (MachineBasicBlock *MBB) -> void { 131 if (Visited.count(MBB)) 132 return; 133 134 Visited.insert(MBB); 135 for (auto *Succ : MBB->successors()) { 136 if (!ML.contains(Succ)) 137 continue; 138 Search(Succ); 139 } 140 Order.push_back(MBB); 141 }; 142 143 // Insert exit blocks. 144 SmallVector<MachineBasicBlock*, 2> ExitBlocks; 145 ML.getExitBlocks(ExitBlocks); 146 for (auto *MBB : ExitBlocks) 147 Order.push_back(MBB); 148 149 // Then add the loop body. 150 Search(ML.getHeader()); 151 152 // Then try the preheader and its predecessors. 153 std::function<void(MachineBasicBlock*)> GetPredecessor = 154 [this, &GetPredecessor] (MachineBasicBlock *MBB) -> void { 155 Order.push_back(MBB); 156 if (MBB->pred_size() == 1) 157 GetPredecessor(*MBB->pred_begin()); 158 }; 159 160 if (auto *Preheader = ML.getLoopPreheader()) 161 GetPredecessor(Preheader); 162 else if (auto *Preheader = MLI.findLoopPreheader(&ML, true)) 163 GetPredecessor(Preheader); 164 } 165 }; 166 167 struct PredicatedMI { 168 MachineInstr *MI = nullptr; 169 SetVector<MachineInstr*> Predicates; 170 171 public: 172 PredicatedMI(MachineInstr *I, SetVector<MachineInstr *> &Preds) : MI(I) { 173 assert(I && "Instruction must not be null!"); 174 Predicates.insert(Preds.begin(), Preds.end()); 175 } 176 }; 177 178 // Represent the current state of the VPR and hold all instances which 179 // represent a VPT block, which is a list of instructions that begins with a 180 // VPT/VPST and has a maximum of four proceeding instructions. All 181 // instructions within the block are predicated upon the vpr and we allow 182 // instructions to define the vpr within in the block too. 183 class VPTState { 184 friend struct LowOverheadLoop; 185 186 SmallVector<MachineInstr *, 4> Insts; 187 188 static SmallVector<VPTState, 4> Blocks; 189 static SetVector<MachineInstr *> CurrentPredicates; 190 static std::map<MachineInstr *, 191 std::unique_ptr<PredicatedMI>> PredicatedInsts; 192 193 static void CreateVPTBlock(MachineInstr *MI) { 194 assert((CurrentPredicates.size() || MI->getParent()->isLiveIn(ARM::VPR)) 195 && "Can't begin VPT without predicate"); 196 Blocks.emplace_back(MI); 197 // The execution of MI is predicated upon the current set of instructions 198 // that are AND'ed together to form the VPR predicate value. In the case 199 // that MI is a VPT, CurrentPredicates will also just be MI. 200 PredicatedInsts.emplace( 201 MI, std::make_unique<PredicatedMI>(MI, CurrentPredicates)); 202 } 203 204 static void reset() { 205 Blocks.clear(); 206 PredicatedInsts.clear(); 207 CurrentPredicates.clear(); 208 } 209 210 static void addInst(MachineInstr *MI) { 211 Blocks.back().insert(MI); 212 PredicatedInsts.emplace( 213 MI, std::make_unique<PredicatedMI>(MI, CurrentPredicates)); 214 } 215 216 static void addPredicate(MachineInstr *MI) { 217 LLVM_DEBUG(dbgs() << "ARM Loops: Adding VPT Predicate: " << *MI); 218 CurrentPredicates.insert(MI); 219 } 220 221 static void resetPredicate(MachineInstr *MI) { 222 LLVM_DEBUG(dbgs() << "ARM Loops: Resetting VPT Predicate: " << *MI); 223 CurrentPredicates.clear(); 224 CurrentPredicates.insert(MI); 225 } 226 227 public: 228 // Have we found an instruction within the block which defines the vpr? If 229 // so, not all the instructions in the block will have the same predicate. 230 static bool hasUniformPredicate(VPTState &Block) { 231 return getDivergent(Block) == nullptr; 232 } 233 234 // If it exists, return the first internal instruction which modifies the 235 // VPR. 236 static MachineInstr *getDivergent(VPTState &Block) { 237 SmallVectorImpl<MachineInstr *> &Insts = Block.getInsts(); 238 for (unsigned i = 1; i < Insts.size(); ++i) { 239 MachineInstr *Next = Insts[i]; 240 if (isVectorPredicate(Next)) 241 return Next; // Found an instruction altering the vpr. 242 } 243 return nullptr; 244 } 245 246 // Return whether the given instruction is predicated upon a VCTP. 247 static bool isPredicatedOnVCTP(MachineInstr *MI, bool Exclusive = false) { 248 SetVector<MachineInstr *> &Predicates = PredicatedInsts[MI]->Predicates; 249 if (Exclusive && Predicates.size() != 1) 250 return false; 251 for (auto *PredMI : Predicates) 252 if (isVCTP(PredMI)) 253 return true; 254 return false; 255 } 256 257 // Is the VPST, controlling the block entry, predicated upon a VCTP. 258 static bool isEntryPredicatedOnVCTP(VPTState &Block, 259 bool Exclusive = false) { 260 SmallVectorImpl<MachineInstr *> &Insts = Block.getInsts(); 261 return isPredicatedOnVCTP(Insts.front(), Exclusive); 262 } 263 264 // If this block begins with a VPT, we can check whether it's using 265 // at least one predicated input(s), as well as possible loop invariant 266 // which would result in it being implicitly predicated. 267 static bool hasImplicitlyValidVPT(VPTState &Block, 268 ReachingDefAnalysis &RDA) { 269 SmallVectorImpl<MachineInstr *> &Insts = Block.getInsts(); 270 MachineInstr *VPT = Insts.front(); 271 assert(isVPTOpcode(VPT->getOpcode()) && 272 "Expected VPT block to begin with VPT/VPST"); 273 274 if (VPT->getOpcode() == ARM::MVE_VPST) 275 return false; 276 277 auto IsOperandPredicated = [&](MachineInstr *MI, unsigned Idx) { 278 MachineInstr *Op = RDA.getMIOperand(MI, MI->getOperand(Idx)); 279 return Op && PredicatedInsts.count(Op) && isPredicatedOnVCTP(Op); 280 }; 281 282 auto IsOperandInvariant = [&](MachineInstr *MI, unsigned Idx) { 283 MachineOperand &MO = MI->getOperand(Idx); 284 if (!MO.isReg() || !MO.getReg()) 285 return true; 286 287 SmallPtrSet<MachineInstr *, 2> Defs; 288 RDA.getGlobalReachingDefs(MI, MO.getReg(), Defs); 289 if (Defs.empty()) 290 return true; 291 292 for (auto *Def : Defs) 293 if (Def->getParent() == VPT->getParent()) 294 return false; 295 return true; 296 }; 297 298 // Check that at least one of the operands is directly predicated on a 299 // vctp and allow an invariant value too. 300 return (IsOperandPredicated(VPT, 1) || IsOperandPredicated(VPT, 2)) && 301 (IsOperandPredicated(VPT, 1) || IsOperandInvariant(VPT, 1)) && 302 (IsOperandPredicated(VPT, 2) || IsOperandInvariant(VPT, 2)); 303 } 304 305 static bool isValid(ReachingDefAnalysis &RDA) { 306 // All predication within the loop should be based on vctp. If the block 307 // isn't predicated on entry, check whether the vctp is within the block 308 // and that all other instructions are then predicated on it. 309 for (auto &Block : Blocks) { 310 if (isEntryPredicatedOnVCTP(Block, false) || 311 hasImplicitlyValidVPT(Block, RDA)) 312 continue; 313 314 SmallVectorImpl<MachineInstr *> &Insts = Block.getInsts(); 315 for (auto *MI : Insts) { 316 // Check that any internal VCTPs are 'Then' predicated. 317 if (isVCTP(MI) && getVPTInstrPredicate(*MI) != ARMVCC::Then) 318 return false; 319 // Skip other instructions that build up the predicate. 320 if (MI->getOpcode() == ARM::MVE_VPST || isVectorPredicate(MI)) 321 continue; 322 // Check that any other instructions are predicated upon a vctp. 323 // TODO: We could infer when VPTs are implicitly predicated on the 324 // vctp (when the operands are predicated). 325 if (!isPredicatedOnVCTP(MI)) { 326 LLVM_DEBUG(dbgs() << "ARM Loops: Can't convert: " << *MI); 327 return false; 328 } 329 } 330 } 331 return true; 332 } 333 334 VPTState(MachineInstr *MI) { Insts.push_back(MI); } 335 336 void insert(MachineInstr *MI) { 337 Insts.push_back(MI); 338 // VPT/VPST + 4 predicated instructions. 339 assert(Insts.size() <= 5 && "Too many instructions in VPT block!"); 340 } 341 342 bool containsVCTP() const { 343 for (auto *MI : Insts) 344 if (isVCTP(MI)) 345 return true; 346 return false; 347 } 348 349 unsigned size() const { return Insts.size(); } 350 SmallVectorImpl<MachineInstr *> &getInsts() { return Insts; } 351 }; 352 353 struct LowOverheadLoop { 354 355 MachineLoop &ML; 356 MachineBasicBlock *Preheader = nullptr; 357 MachineLoopInfo &MLI; 358 ReachingDefAnalysis &RDA; 359 const TargetRegisterInfo &TRI; 360 const ARMBaseInstrInfo &TII; 361 MachineFunction *MF = nullptr; 362 MachineBasicBlock::iterator StartInsertPt; 363 MachineBasicBlock *StartInsertBB = nullptr; 364 MachineInstr *Start = nullptr; 365 MachineInstr *Dec = nullptr; 366 MachineInstr *End = nullptr; 367 MachineOperand TPNumElements; 368 SmallVector<MachineInstr*, 4> VCTPs; 369 SmallPtrSet<MachineInstr*, 4> ToRemove; 370 SmallPtrSet<MachineInstr*, 4> BlockMasksToRecompute; 371 bool Revert = false; 372 bool CannotTailPredicate = false; 373 374 LowOverheadLoop(MachineLoop &ML, MachineLoopInfo &MLI, 375 ReachingDefAnalysis &RDA, const TargetRegisterInfo &TRI, 376 const ARMBaseInstrInfo &TII) 377 : ML(ML), MLI(MLI), RDA(RDA), TRI(TRI), TII(TII), 378 TPNumElements(MachineOperand::CreateImm(0)) { 379 MF = ML.getHeader()->getParent(); 380 if (auto *MBB = ML.getLoopPreheader()) 381 Preheader = MBB; 382 else if (auto *MBB = MLI.findLoopPreheader(&ML, true)) 383 Preheader = MBB; 384 VPTState::reset(); 385 } 386 387 // If this is an MVE instruction, check that we know how to use tail 388 // predication with it. Record VPT blocks and return whether the 389 // instruction is valid for tail predication. 390 bool ValidateMVEInst(MachineInstr *MI); 391 392 void AnalyseMVEInst(MachineInstr *MI) { 393 CannotTailPredicate = !ValidateMVEInst(MI); 394 } 395 396 bool IsTailPredicationLegal() const { 397 // For now, let's keep things really simple and only support a single 398 // block for tail predication. 399 return !Revert && FoundAllComponents() && !VCTPs.empty() && 400 !CannotTailPredicate && ML.getNumBlocks() == 1; 401 } 402 403 // Given that MI is a VCTP, check that is equivalent to any other VCTPs 404 // found. 405 bool AddVCTP(MachineInstr *MI); 406 407 // Check that the predication in the loop will be equivalent once we 408 // perform the conversion. Also ensure that we can provide the number 409 // of elements to the loop start instruction. 410 bool ValidateTailPredicate(); 411 412 // Check that any values available outside of the loop will be the same 413 // after tail predication conversion. 414 bool ValidateLiveOuts(); 415 416 // Is it safe to define LR with DLS/WLS? 417 // LR can be defined if it is the operand to start, because it's the same 418 // value, or if it's going to be equivalent to the operand to Start. 419 MachineInstr *isSafeToDefineLR(); 420 421 // Check the branch targets are within range and we satisfy our 422 // restrictions. 423 void Validate(ARMBasicBlockUtils *BBUtils); 424 425 bool FoundAllComponents() const { 426 return Start && Dec && End; 427 } 428 429 SmallVectorImpl<VPTState> &getVPTBlocks() { 430 return VPTState::Blocks; 431 } 432 433 // Return the operand for the loop start instruction. This will be the loop 434 // iteration count, or the number of elements if we're tail predicating. 435 MachineOperand &getLoopStartOperand() { 436 if (IsTailPredicationLegal()) 437 return TPNumElements; 438 return isDo(Start) ? Start->getOperand(1) : Start->getOperand(0); 439 } 440 441 unsigned getStartOpcode() const { 442 bool IsDo = isDo(Start); 443 if (!IsTailPredicationLegal()) 444 return IsDo ? ARM::t2DLS : ARM::t2WLS; 445 446 return VCTPOpcodeToLSTP(VCTPs.back()->getOpcode(), IsDo); 447 } 448 449 void dump() const { 450 if (Start) dbgs() << "ARM Loops: Found Loop Start: " << *Start; 451 if (Dec) dbgs() << "ARM Loops: Found Loop Dec: " << *Dec; 452 if (End) dbgs() << "ARM Loops: Found Loop End: " << *End; 453 if (!VCTPs.empty()) { 454 dbgs() << "ARM Loops: Found VCTP(s):\n"; 455 for (auto *MI : VCTPs) 456 dbgs() << " - " << *MI; 457 } 458 if (!FoundAllComponents()) 459 dbgs() << "ARM Loops: Not a low-overhead loop.\n"; 460 else if (!(Start && Dec && End)) 461 dbgs() << "ARM Loops: Failed to find all loop components.\n"; 462 } 463 }; 464 465 class ARMLowOverheadLoops : public MachineFunctionPass { 466 MachineFunction *MF = nullptr; 467 MachineLoopInfo *MLI = nullptr; 468 ReachingDefAnalysis *RDA = nullptr; 469 const ARMBaseInstrInfo *TII = nullptr; 470 MachineRegisterInfo *MRI = nullptr; 471 const TargetRegisterInfo *TRI = nullptr; 472 std::unique_ptr<ARMBasicBlockUtils> BBUtils = nullptr; 473 474 public: 475 static char ID; 476 477 ARMLowOverheadLoops() : MachineFunctionPass(ID) { } 478 479 void getAnalysisUsage(AnalysisUsage &AU) const override { 480 AU.setPreservesCFG(); 481 AU.addRequired<MachineLoopInfo>(); 482 AU.addRequired<ReachingDefAnalysis>(); 483 MachineFunctionPass::getAnalysisUsage(AU); 484 } 485 486 bool runOnMachineFunction(MachineFunction &MF) override; 487 488 MachineFunctionProperties getRequiredProperties() const override { 489 return MachineFunctionProperties().set( 490 MachineFunctionProperties::Property::NoVRegs).set( 491 MachineFunctionProperties::Property::TracksLiveness); 492 } 493 494 StringRef getPassName() const override { 495 return ARM_LOW_OVERHEAD_LOOPS_NAME; 496 } 497 498 private: 499 bool ProcessLoop(MachineLoop *ML); 500 501 bool RevertNonLoops(); 502 503 void RevertWhile(MachineInstr *MI) const; 504 void RevertDo(MachineInstr *MI) const; 505 506 bool RevertLoopDec(MachineInstr *MI) const; 507 508 void RevertLoopEnd(MachineInstr *MI, bool SkipCmp = false) const; 509 510 void RevertLoopEndDec(MachineInstr *MI) const; 511 512 void ConvertVPTBlocks(LowOverheadLoop &LoLoop); 513 514 MachineInstr *ExpandLoopStart(LowOverheadLoop &LoLoop); 515 516 void Expand(LowOverheadLoop &LoLoop); 517 518 void IterationCountDCE(LowOverheadLoop &LoLoop); 519 }; 520 } 521 522 char ARMLowOverheadLoops::ID = 0; 523 524 SmallVector<VPTState, 4> VPTState::Blocks; 525 SetVector<MachineInstr *> VPTState::CurrentPredicates; 526 std::map<MachineInstr *, 527 std::unique_ptr<PredicatedMI>> VPTState::PredicatedInsts; 528 529 INITIALIZE_PASS(ARMLowOverheadLoops, DEBUG_TYPE, ARM_LOW_OVERHEAD_LOOPS_NAME, 530 false, false) 531 532 static bool TryRemove(MachineInstr *MI, ReachingDefAnalysis &RDA, 533 InstSet &ToRemove, InstSet &Ignore) { 534 535 // Check that we can remove all of Killed without having to modify any IT 536 // blocks. 537 auto WontCorruptITs = [](InstSet &Killed, ReachingDefAnalysis &RDA) { 538 // Collect the dead code and the MBBs in which they reside. 539 SmallPtrSet<MachineBasicBlock*, 2> BasicBlocks; 540 for (auto *Dead : Killed) 541 BasicBlocks.insert(Dead->getParent()); 542 543 // Collect IT blocks in all affected basic blocks. 544 std::map<MachineInstr *, SmallPtrSet<MachineInstr *, 2>> ITBlocks; 545 for (auto *MBB : BasicBlocks) { 546 for (auto &IT : *MBB) { 547 if (IT.getOpcode() != ARM::t2IT) 548 continue; 549 RDA.getReachingLocalUses(&IT, MCRegister::from(ARM::ITSTATE), 550 ITBlocks[&IT]); 551 } 552 } 553 554 // If we're removing all of the instructions within an IT block, then 555 // also remove the IT instruction. 556 SmallPtrSet<MachineInstr *, 2> ModifiedITs; 557 SmallPtrSet<MachineInstr *, 2> RemoveITs; 558 for (auto *Dead : Killed) { 559 if (MachineOperand *MO = Dead->findRegisterUseOperand(ARM::ITSTATE)) { 560 MachineInstr *IT = RDA.getMIOperand(Dead, *MO); 561 RemoveITs.insert(IT); 562 auto &CurrentBlock = ITBlocks[IT]; 563 CurrentBlock.erase(Dead); 564 if (CurrentBlock.empty()) 565 ModifiedITs.erase(IT); 566 else 567 ModifiedITs.insert(IT); 568 } 569 } 570 if (!ModifiedITs.empty()) 571 return false; 572 Killed.insert(RemoveITs.begin(), RemoveITs.end()); 573 return true; 574 }; 575 576 SmallPtrSet<MachineInstr *, 2> Uses; 577 if (!RDA.isSafeToRemove(MI, Uses, Ignore)) 578 return false; 579 580 if (WontCorruptITs(Uses, RDA)) { 581 ToRemove.insert(Uses.begin(), Uses.end()); 582 LLVM_DEBUG(dbgs() << "ARM Loops: Able to remove: " << *MI 583 << " - can also remove:\n"; 584 for (auto *Use : Uses) 585 dbgs() << " - " << *Use); 586 587 SmallPtrSet<MachineInstr*, 4> Killed; 588 RDA.collectKilledOperands(MI, Killed); 589 if (WontCorruptITs(Killed, RDA)) { 590 ToRemove.insert(Killed.begin(), Killed.end()); 591 LLVM_DEBUG(for (auto *Dead : Killed) 592 dbgs() << " - " << *Dead); 593 } 594 return true; 595 } 596 return false; 597 } 598 599 bool LowOverheadLoop::ValidateTailPredicate() { 600 if (!IsTailPredicationLegal()) { 601 LLVM_DEBUG(if (VCTPs.empty()) 602 dbgs() << "ARM Loops: Didn't find a VCTP instruction.\n"; 603 dbgs() << "ARM Loops: Tail-predication is not valid.\n"); 604 return false; 605 } 606 607 assert(!VCTPs.empty() && "VCTP instruction expected but is not set"); 608 assert(ML.getBlocks().size() == 1 && 609 "Shouldn't be processing a loop with more than one block"); 610 611 if (DisableTailPredication) { 612 LLVM_DEBUG(dbgs() << "ARM Loops: tail-predication is disabled\n"); 613 return false; 614 } 615 616 if (!VPTState::isValid(RDA)) { 617 LLVM_DEBUG(dbgs() << "ARM Loops: Invalid VPT state.\n"); 618 return false; 619 } 620 621 if (!ValidateLiveOuts()) { 622 LLVM_DEBUG(dbgs() << "ARM Loops: Invalid live outs.\n"); 623 return false; 624 } 625 626 // Check that creating a [W|D]LSTP, which will define LR with an element 627 // count instead of iteration count, won't affect any other instructions 628 // than the LoopStart and LoopDec. 629 // TODO: We should try to insert the [W|D]LSTP after any of the other uses. 630 Register StartReg = isDo(Start) ? Start->getOperand(1).getReg() 631 : Start->getOperand(0).getReg(); 632 if (StartInsertPt == Start && StartReg == ARM::LR) { 633 if (auto *IterCount = RDA.getMIOperand(Start, isDo(Start) ? 1 : 0)) { 634 SmallPtrSet<MachineInstr *, 2> Uses; 635 RDA.getGlobalUses(IterCount, MCRegister::from(ARM::LR), Uses); 636 for (auto *Use : Uses) { 637 if (Use != Start && Use != Dec) { 638 LLVM_DEBUG(dbgs() << " ARM Loops: Found LR use: " << *Use); 639 return false; 640 } 641 } 642 } 643 } 644 645 // For tail predication, we need to provide the number of elements, instead 646 // of the iteration count, to the loop start instruction. The number of 647 // elements is provided to the vctp instruction, so we need to check that 648 // we can use this register at InsertPt. 649 MachineInstr *VCTP = VCTPs.back(); 650 if (Start->getOpcode() == ARM::t2DoLoopStartTP) { 651 TPNumElements = Start->getOperand(2); 652 StartInsertPt = Start; 653 StartInsertBB = Start->getParent(); 654 } else { 655 TPNumElements = VCTP->getOperand(1); 656 MCRegister NumElements = TPNumElements.getReg().asMCReg(); 657 658 // If the register is defined within loop, then we can't perform TP. 659 // TODO: Check whether this is just a mov of a register that would be 660 // available. 661 if (RDA.hasLocalDefBefore(VCTP, NumElements)) { 662 LLVM_DEBUG(dbgs() << "ARM Loops: VCTP operand is defined in the loop.\n"); 663 return false; 664 } 665 666 // The element count register maybe defined after InsertPt, in which case we 667 // need to try to move either InsertPt or the def so that the [w|d]lstp can 668 // use the value. 669 670 if (StartInsertPt != StartInsertBB->end() && 671 !RDA.isReachingDefLiveOut(&*StartInsertPt, NumElements)) { 672 if (auto *ElemDef = 673 RDA.getLocalLiveOutMIDef(StartInsertBB, NumElements)) { 674 if (RDA.isSafeToMoveForwards(ElemDef, &*StartInsertPt)) { 675 ElemDef->removeFromParent(); 676 StartInsertBB->insert(StartInsertPt, ElemDef); 677 LLVM_DEBUG(dbgs() 678 << "ARM Loops: Moved element count def: " << *ElemDef); 679 } else if (RDA.isSafeToMoveBackwards(&*StartInsertPt, ElemDef)) { 680 StartInsertPt->removeFromParent(); 681 StartInsertBB->insertAfter(MachineBasicBlock::iterator(ElemDef), 682 &*StartInsertPt); 683 LLVM_DEBUG(dbgs() << "ARM Loops: Moved start past: " << *ElemDef); 684 } else { 685 // If we fail to move an instruction and the element count is provided 686 // by a mov, use the mov operand if it will have the same value at the 687 // insertion point 688 MachineOperand Operand = ElemDef->getOperand(1); 689 if (isMovRegOpcode(ElemDef->getOpcode()) && 690 RDA.getUniqueReachingMIDef(ElemDef, Operand.getReg().asMCReg()) == 691 RDA.getUniqueReachingMIDef(&*StartInsertPt, 692 Operand.getReg().asMCReg())) { 693 TPNumElements = Operand; 694 NumElements = TPNumElements.getReg(); 695 } else { 696 LLVM_DEBUG(dbgs() 697 << "ARM Loops: Unable to move element count to loop " 698 << "start instruction.\n"); 699 return false; 700 } 701 } 702 } 703 } 704 705 // Especially in the case of while loops, InsertBB may not be the 706 // preheader, so we need to check that the register isn't redefined 707 // before entering the loop. 708 auto CannotProvideElements = [this](MachineBasicBlock *MBB, 709 MCRegister NumElements) { 710 if (MBB->empty()) 711 return false; 712 // NumElements is redefined in this block. 713 if (RDA.hasLocalDefBefore(&MBB->back(), NumElements)) 714 return true; 715 716 // Don't continue searching up through multiple predecessors. 717 if (MBB->pred_size() > 1) 718 return true; 719 720 return false; 721 }; 722 723 // Search backwards for a def, until we get to InsertBB. 724 MachineBasicBlock *MBB = Preheader; 725 while (MBB && MBB != StartInsertBB) { 726 if (CannotProvideElements(MBB, NumElements)) { 727 LLVM_DEBUG(dbgs() << "ARM Loops: Unable to provide element count.\n"); 728 return false; 729 } 730 MBB = *MBB->pred_begin(); 731 } 732 } 733 734 // Could inserting the [W|D]LSTP cause some unintended affects? In a perfect 735 // world the [w|d]lstp instruction would be last instruction in the preheader 736 // and so it would only affect instructions within the loop body. But due to 737 // scheduling, and/or the logic in this pass (above), the insertion point can 738 // be moved earlier. So if the Loop Start isn't the last instruction in the 739 // preheader, and if the initial element count is smaller than the vector 740 // width, the Loop Start instruction will immediately generate one or more 741 // false lane mask which can, incorrectly, affect the proceeding MVE 742 // instructions in the preheader. 743 if (std::any_of(StartInsertPt, StartInsertBB->end(), shouldInspect)) { 744 LLVM_DEBUG(dbgs() << "ARM Loops: Instruction blocks [W|D]LSTP\n"); 745 return false; 746 } 747 748 // Check that the value change of the element count is what we expect and 749 // that the predication will be equivalent. For this we need: 750 // NumElements = NumElements - VectorWidth. The sub will be a sub immediate 751 // and we can also allow register copies within the chain too. 752 auto IsValidSub = [](MachineInstr *MI, int ExpectedVecWidth) { 753 return -getAddSubImmediate(*MI) == ExpectedVecWidth; 754 }; 755 756 MachineBasicBlock *MBB = VCTP->getParent(); 757 // Remove modifications to the element count since they have no purpose in a 758 // tail predicated loop. Explicitly refer to the vctp operand no matter which 759 // register NumElements has been assigned to, since that is what the 760 // modifications will be using 761 if (auto *Def = RDA.getUniqueReachingMIDef( 762 &MBB->back(), VCTP->getOperand(1).getReg().asMCReg())) { 763 SmallPtrSet<MachineInstr*, 2> ElementChain; 764 SmallPtrSet<MachineInstr*, 2> Ignore; 765 unsigned ExpectedVectorWidth = getTailPredVectorWidth(VCTP->getOpcode()); 766 767 Ignore.insert(VCTPs.begin(), VCTPs.end()); 768 769 if (TryRemove(Def, RDA, ElementChain, Ignore)) { 770 bool FoundSub = false; 771 772 for (auto *MI : ElementChain) { 773 if (isMovRegOpcode(MI->getOpcode())) 774 continue; 775 776 if (isSubImmOpcode(MI->getOpcode())) { 777 if (FoundSub || !IsValidSub(MI, ExpectedVectorWidth)) { 778 LLVM_DEBUG(dbgs() << "ARM Loops: Unexpected instruction in element" 779 " count: " << *MI); 780 return false; 781 } 782 FoundSub = true; 783 } else { 784 LLVM_DEBUG(dbgs() << "ARM Loops: Unexpected instruction in element" 785 " count: " << *MI); 786 return false; 787 } 788 } 789 ToRemove.insert(ElementChain.begin(), ElementChain.end()); 790 } 791 } 792 return true; 793 } 794 795 static bool isRegInClass(const MachineOperand &MO, 796 const TargetRegisterClass *Class) { 797 return MO.isReg() && MO.getReg() && Class->contains(MO.getReg()); 798 } 799 800 // MVE 'narrowing' operate on half a lane, reading from half and writing 801 // to half, which are referred to has the top and bottom half. The other 802 // half retains its previous value. 803 static bool retainsPreviousHalfElement(const MachineInstr &MI) { 804 const MCInstrDesc &MCID = MI.getDesc(); 805 uint64_t Flags = MCID.TSFlags; 806 return (Flags & ARMII::RetainsPreviousHalfElement) != 0; 807 } 808 809 // Some MVE instructions read from the top/bottom halves of their operand(s) 810 // and generate a vector result with result elements that are double the 811 // width of the input. 812 static bool producesDoubleWidthResult(const MachineInstr &MI) { 813 const MCInstrDesc &MCID = MI.getDesc(); 814 uint64_t Flags = MCID.TSFlags; 815 return (Flags & ARMII::DoubleWidthResult) != 0; 816 } 817 818 static bool isHorizontalReduction(const MachineInstr &MI) { 819 const MCInstrDesc &MCID = MI.getDesc(); 820 uint64_t Flags = MCID.TSFlags; 821 return (Flags & ARMII::HorizontalReduction) != 0; 822 } 823 824 // Can this instruction generate a non-zero result when given only zeroed 825 // operands? This allows us to know that, given operands with false bytes 826 // zeroed by masked loads, that the result will also contain zeros in those 827 // bytes. 828 static bool canGenerateNonZeros(const MachineInstr &MI) { 829 830 // Check for instructions which can write into a larger element size, 831 // possibly writing into a previous zero'd lane. 832 if (producesDoubleWidthResult(MI)) 833 return true; 834 835 switch (MI.getOpcode()) { 836 default: 837 break; 838 // FIXME: VNEG FP and -0? I think we'll need to handle this once we allow 839 // fp16 -> fp32 vector conversions. 840 // Instructions that perform a NOT will generate 1s from 0s. 841 case ARM::MVE_VMVN: 842 case ARM::MVE_VORN: 843 // Count leading zeros will do just that! 844 case ARM::MVE_VCLZs8: 845 case ARM::MVE_VCLZs16: 846 case ARM::MVE_VCLZs32: 847 return true; 848 } 849 return false; 850 } 851 852 // Look at its register uses to see if it only can only receive zeros 853 // into its false lanes which would then produce zeros. Also check that 854 // the output register is also defined by an FalseLanesZero instruction 855 // so that if tail-predication happens, the lanes that aren't updated will 856 // still be zeros. 857 static bool producesFalseLanesZero(MachineInstr &MI, 858 const TargetRegisterClass *QPRs, 859 const ReachingDefAnalysis &RDA, 860 InstSet &FalseLanesZero) { 861 if (canGenerateNonZeros(MI)) 862 return false; 863 864 bool isPredicated = isVectorPredicated(&MI); 865 // Predicated loads will write zeros to the falsely predicated bytes of the 866 // destination register. 867 if (MI.mayLoad()) 868 return isPredicated; 869 870 auto IsZeroInit = [](MachineInstr *Def) { 871 return !isVectorPredicated(Def) && 872 Def->getOpcode() == ARM::MVE_VMOVimmi32 && 873 Def->getOperand(1).getImm() == 0; 874 }; 875 876 bool AllowScalars = isHorizontalReduction(MI); 877 for (auto &MO : MI.operands()) { 878 if (!MO.isReg() || !MO.getReg()) 879 continue; 880 if (!isRegInClass(MO, QPRs) && AllowScalars) 881 continue; 882 883 // Check that this instruction will produce zeros in its false lanes: 884 // - If it only consumes false lanes zero or constant 0 (vmov #0) 885 // - If it's predicated, it only matters that it's def register already has 886 // false lane zeros, so we can ignore the uses. 887 SmallPtrSet<MachineInstr *, 2> Defs; 888 RDA.getGlobalReachingDefs(&MI, MO.getReg(), Defs); 889 for (auto *Def : Defs) { 890 if (Def == &MI || FalseLanesZero.count(Def) || IsZeroInit(Def)) 891 continue; 892 if (MO.isUse() && isPredicated) 893 continue; 894 return false; 895 } 896 } 897 LLVM_DEBUG(dbgs() << "ARM Loops: Always False Zeros: " << MI); 898 return true; 899 } 900 901 bool LowOverheadLoop::ValidateLiveOuts() { 902 // We want to find out if the tail-predicated version of this loop will 903 // produce the same values as the loop in its original form. For this to 904 // be true, the newly inserted implicit predication must not change the 905 // the (observable) results. 906 // We're doing this because many instructions in the loop will not be 907 // predicated and so the conversion from VPT predication to tail-predication 908 // can result in different values being produced; due to the tail-predication 909 // preventing many instructions from updating their falsely predicated 910 // lanes. This analysis assumes that all the instructions perform lane-wise 911 // operations and don't perform any exchanges. 912 // A masked load, whether through VPT or tail predication, will write zeros 913 // to any of the falsely predicated bytes. So, from the loads, we know that 914 // the false lanes are zeroed and here we're trying to track that those false 915 // lanes remain zero, or where they change, the differences are masked away 916 // by their user(s). 917 // All MVE stores have to be predicated, so we know that any predicate load 918 // operands, or stored results are equivalent already. Other explicitly 919 // predicated instructions will perform the same operation in the original 920 // loop and the tail-predicated form too. Because of this, we can insert 921 // loads, stores and other predicated instructions into our Predicated 922 // set and build from there. 923 const TargetRegisterClass *QPRs = TRI.getRegClass(ARM::MQPRRegClassID); 924 SetVector<MachineInstr *> FalseLanesUnknown; 925 SmallPtrSet<MachineInstr *, 4> FalseLanesZero; 926 SmallPtrSet<MachineInstr *, 4> Predicated; 927 MachineBasicBlock *Header = ML.getHeader(); 928 929 for (auto &MI : *Header) { 930 if (!shouldInspect(MI)) 931 continue; 932 933 if (isVCTP(&MI) || isVPTOpcode(MI.getOpcode())) 934 continue; 935 936 bool isPredicated = isVectorPredicated(&MI); 937 bool retainsOrReduces = 938 retainsPreviousHalfElement(MI) || isHorizontalReduction(MI); 939 940 if (isPredicated) 941 Predicated.insert(&MI); 942 if (producesFalseLanesZero(MI, QPRs, RDA, FalseLanesZero)) 943 FalseLanesZero.insert(&MI); 944 else if (MI.getNumDefs() == 0) 945 continue; 946 else if (!isPredicated && retainsOrReduces) 947 return false; 948 else if (!isPredicated) 949 FalseLanesUnknown.insert(&MI); 950 } 951 952 auto HasPredicatedUsers = [this](MachineInstr *MI, const MachineOperand &MO, 953 SmallPtrSetImpl<MachineInstr *> &Predicated) { 954 SmallPtrSet<MachineInstr *, 2> Uses; 955 RDA.getGlobalUses(MI, MO.getReg().asMCReg(), Uses); 956 for (auto *Use : Uses) { 957 if (Use != MI && !Predicated.count(Use)) 958 return false; 959 } 960 return true; 961 }; 962 963 // Visit the unknowns in reverse so that we can start at the values being 964 // stored and then we can work towards the leaves, hopefully adding more 965 // instructions to Predicated. Successfully terminating the loop means that 966 // all the unknown values have to found to be masked by predicated user(s). 967 // For any unpredicated values, we store them in NonPredicated so that we 968 // can later check whether these form a reduction. 969 SmallPtrSet<MachineInstr*, 2> NonPredicated; 970 for (auto *MI : reverse(FalseLanesUnknown)) { 971 for (auto &MO : MI->operands()) { 972 if (!isRegInClass(MO, QPRs) || !MO.isDef()) 973 continue; 974 if (!HasPredicatedUsers(MI, MO, Predicated)) { 975 LLVM_DEBUG(dbgs() << "ARM Loops: Found an unknown def of : " 976 << TRI.getRegAsmName(MO.getReg()) << " at " << *MI); 977 NonPredicated.insert(MI); 978 break; 979 } 980 } 981 // Any unknown false lanes have been masked away by the user(s). 982 if (!NonPredicated.contains(MI)) 983 Predicated.insert(MI); 984 } 985 986 SmallPtrSet<MachineInstr *, 2> LiveOutMIs; 987 SmallVector<MachineBasicBlock *, 2> ExitBlocks; 988 ML.getExitBlocks(ExitBlocks); 989 assert(ML.getNumBlocks() == 1 && "Expected single block loop!"); 990 assert(ExitBlocks.size() == 1 && "Expected a single exit block"); 991 MachineBasicBlock *ExitBB = ExitBlocks.front(); 992 for (const MachineBasicBlock::RegisterMaskPair &RegMask : ExitBB->liveins()) { 993 // TODO: Instead of blocking predication, we could move the vctp to the exit 994 // block and calculate it's operand there in or the preheader. 995 if (RegMask.PhysReg == ARM::VPR) 996 return false; 997 // Check Q-regs that are live in the exit blocks. We don't collect scalars 998 // because they won't be affected by lane predication. 999 if (QPRs->contains(RegMask.PhysReg)) 1000 if (auto *MI = RDA.getLocalLiveOutMIDef(Header, RegMask.PhysReg)) 1001 LiveOutMIs.insert(MI); 1002 } 1003 1004 // We've already validated that any VPT predication within the loop will be 1005 // equivalent when we perform the predication transformation; so we know that 1006 // any VPT predicated instruction is predicated upon VCTP. Any live-out 1007 // instruction needs to be predicated, so check this here. The instructions 1008 // in NonPredicated have been found to be a reduction that we can ensure its 1009 // legality. 1010 for (auto *MI : LiveOutMIs) { 1011 if (NonPredicated.count(MI) && FalseLanesUnknown.contains(MI)) { 1012 LLVM_DEBUG(dbgs() << "ARM Loops: Unable to handle live out: " << *MI); 1013 return false; 1014 } 1015 } 1016 1017 return true; 1018 } 1019 1020 void LowOverheadLoop::Validate(ARMBasicBlockUtils *BBUtils) { 1021 if (Revert) 1022 return; 1023 1024 // Check branch target ranges: WLS[TP] can only branch forwards and LE[TP] 1025 // can only jump back. 1026 auto ValidateRanges = [](MachineInstr *Start, MachineInstr *End, 1027 ARMBasicBlockUtils *BBUtils, MachineLoop &ML) { 1028 MachineBasicBlock *TgtBB = End->getOpcode() == ARM::t2LoopEnd 1029 ? End->getOperand(1).getMBB() 1030 : End->getOperand(2).getMBB(); 1031 // TODO Maybe there's cases where the target doesn't have to be the header, 1032 // but for now be safe and revert. 1033 if (TgtBB != ML.getHeader()) { 1034 LLVM_DEBUG(dbgs() << "ARM Loops: LoopEnd is not targeting header.\n"); 1035 return false; 1036 } 1037 1038 // The WLS and LE instructions have 12-bits for the label offset. WLS 1039 // requires a positive offset, while LE uses negative. 1040 if (BBUtils->getOffsetOf(End) < BBUtils->getOffsetOf(ML.getHeader()) || 1041 !BBUtils->isBBInRange(End, ML.getHeader(), 4094)) { 1042 LLVM_DEBUG(dbgs() << "ARM Loops: LE offset is out-of-range\n"); 1043 return false; 1044 } 1045 1046 if (Start->getOpcode() == ARM::t2WhileLoopStart && 1047 (BBUtils->getOffsetOf(Start) > 1048 BBUtils->getOffsetOf(Start->getOperand(1).getMBB()) || 1049 !BBUtils->isBBInRange(Start, Start->getOperand(1).getMBB(), 4094))) { 1050 LLVM_DEBUG(dbgs() << "ARM Loops: WLS offset is out-of-range!\n"); 1051 return false; 1052 } 1053 return true; 1054 }; 1055 1056 // Find a suitable position to insert the loop start instruction. It needs to 1057 // be able to safely define LR. 1058 auto FindStartInsertionPoint = [](MachineInstr *Start, MachineInstr *Dec, 1059 MachineBasicBlock::iterator &InsertPt, 1060 MachineBasicBlock *&InsertBB, 1061 ReachingDefAnalysis &RDA, 1062 InstSet &ToRemove) { 1063 // For a t2DoLoopStart it is always valid to use the start insertion point. 1064 // For WLS we can define LR if LR already contains the same value. 1065 if (isDo(Start) || Start->getOperand(0).getReg() == ARM::LR) { 1066 InsertPt = MachineBasicBlock::iterator(Start); 1067 InsertBB = Start->getParent(); 1068 return true; 1069 } 1070 1071 // We've found no suitable LR def and Start doesn't use LR directly. Can we 1072 // just define LR anyway? 1073 if (!RDA.isSafeToDefRegAt(Start, MCRegister::from(ARM::LR))) 1074 return false; 1075 1076 InsertPt = MachineBasicBlock::iterator(Start); 1077 InsertBB = Start->getParent(); 1078 return true; 1079 }; 1080 1081 if (!FindStartInsertionPoint(Start, Dec, StartInsertPt, StartInsertBB, RDA, 1082 ToRemove)) { 1083 LLVM_DEBUG(dbgs() << "ARM Loops: Unable to find safe insertion point.\n"); 1084 Revert = true; 1085 return; 1086 } 1087 LLVM_DEBUG(if (StartInsertPt == StartInsertBB->end()) 1088 dbgs() << "ARM Loops: Will insert LoopStart at end of block\n"; 1089 else 1090 dbgs() << "ARM Loops: Will insert LoopStart at " 1091 << *StartInsertPt 1092 ); 1093 1094 Revert = !ValidateRanges(Start, End, BBUtils, ML); 1095 CannotTailPredicate = !ValidateTailPredicate(); 1096 } 1097 1098 bool LowOverheadLoop::AddVCTP(MachineInstr *MI) { 1099 LLVM_DEBUG(dbgs() << "ARM Loops: Adding VCTP: " << *MI); 1100 if (VCTPs.empty()) { 1101 VCTPs.push_back(MI); 1102 return true; 1103 } 1104 1105 // If we find another VCTP, check whether it uses the same value as the main VCTP. 1106 // If it does, store it in the VCTPs set, else refuse it. 1107 MachineInstr *Prev = VCTPs.back(); 1108 if (!Prev->getOperand(1).isIdenticalTo(MI->getOperand(1)) || 1109 !RDA.hasSameReachingDef(Prev, MI, MI->getOperand(1).getReg().asMCReg())) { 1110 LLVM_DEBUG(dbgs() << "ARM Loops: Found VCTP with a different reaching " 1111 "definition from the main VCTP"); 1112 return false; 1113 } 1114 VCTPs.push_back(MI); 1115 return true; 1116 } 1117 1118 bool LowOverheadLoop::ValidateMVEInst(MachineInstr* MI) { 1119 if (CannotTailPredicate) 1120 return false; 1121 1122 if (!shouldInspect(*MI)) 1123 return true; 1124 1125 if (MI->getOpcode() == ARM::MVE_VPSEL || 1126 MI->getOpcode() == ARM::MVE_VPNOT) { 1127 // TODO: Allow VPSEL and VPNOT, we currently cannot because: 1128 // 1) It will use the VPR as a predicate operand, but doesn't have to be 1129 // instead a VPT block, which means we can assert while building up 1130 // the VPT block because we don't find another VPT or VPST to being a new 1131 // one. 1132 // 2) VPSEL still requires a VPR operand even after tail predicating, 1133 // which means we can't remove it unless there is another 1134 // instruction, such as vcmp, that can provide the VPR def. 1135 return false; 1136 } 1137 1138 // Record all VCTPs and check that they're equivalent to one another. 1139 if (isVCTP(MI) && !AddVCTP(MI)) 1140 return false; 1141 1142 // Inspect uses first so that any instructions that alter the VPR don't 1143 // alter the predicate upon themselves. 1144 const MCInstrDesc &MCID = MI->getDesc(); 1145 bool IsUse = false; 1146 unsigned LastOpIdx = MI->getNumOperands() - 1; 1147 for (auto &Op : enumerate(reverse(MCID.operands()))) { 1148 const MachineOperand &MO = MI->getOperand(LastOpIdx - Op.index()); 1149 if (!MO.isReg() || !MO.isUse() || MO.getReg() != ARM::VPR) 1150 continue; 1151 1152 if (ARM::isVpred(Op.value().OperandType)) { 1153 VPTState::addInst(MI); 1154 IsUse = true; 1155 } else if (MI->getOpcode() != ARM::MVE_VPST) { 1156 LLVM_DEBUG(dbgs() << "ARM Loops: Found instruction using vpr: " << *MI); 1157 return false; 1158 } 1159 } 1160 1161 // If we find an instruction that has been marked as not valid for tail 1162 // predication, only allow the instruction if it's contained within a valid 1163 // VPT block. 1164 bool RequiresExplicitPredication = 1165 (MCID.TSFlags & ARMII::ValidForTailPredication) == 0; 1166 if (isDomainMVE(MI) && RequiresExplicitPredication) { 1167 LLVM_DEBUG(if (!IsUse) 1168 dbgs() << "ARM Loops: Can't tail predicate: " << *MI); 1169 return IsUse; 1170 } 1171 1172 // If the instruction is already explicitly predicated, then the conversion 1173 // will be fine, but ensure that all store operations are predicated. 1174 if (MI->mayStore()) 1175 return IsUse; 1176 1177 // If this instruction defines the VPR, update the predicate for the 1178 // proceeding instructions. 1179 if (isVectorPredicate(MI)) { 1180 // Clear the existing predicate when we're not in VPT Active state, 1181 // otherwise we add to it. 1182 if (!isVectorPredicated(MI)) 1183 VPTState::resetPredicate(MI); 1184 else 1185 VPTState::addPredicate(MI); 1186 } 1187 1188 // Finally once the predicate has been modified, we can start a new VPT 1189 // block if necessary. 1190 if (isVPTOpcode(MI->getOpcode())) 1191 VPTState::CreateVPTBlock(MI); 1192 1193 return true; 1194 } 1195 1196 bool ARMLowOverheadLoops::runOnMachineFunction(MachineFunction &mf) { 1197 const ARMSubtarget &ST = static_cast<const ARMSubtarget&>(mf.getSubtarget()); 1198 if (!ST.hasLOB()) 1199 return false; 1200 1201 MF = &mf; 1202 LLVM_DEBUG(dbgs() << "ARM Loops on " << MF->getName() << " ------------- \n"); 1203 1204 MLI = &getAnalysis<MachineLoopInfo>(); 1205 RDA = &getAnalysis<ReachingDefAnalysis>(); 1206 MF->getProperties().set(MachineFunctionProperties::Property::TracksLiveness); 1207 MRI = &MF->getRegInfo(); 1208 TII = static_cast<const ARMBaseInstrInfo*>(ST.getInstrInfo()); 1209 TRI = ST.getRegisterInfo(); 1210 BBUtils = std::unique_ptr<ARMBasicBlockUtils>(new ARMBasicBlockUtils(*MF)); 1211 BBUtils->computeAllBlockSizes(); 1212 BBUtils->adjustBBOffsetsAfter(&MF->front()); 1213 1214 bool Changed = false; 1215 for (auto ML : *MLI) { 1216 if (ML->isOutermost()) 1217 Changed |= ProcessLoop(ML); 1218 } 1219 Changed |= RevertNonLoops(); 1220 return Changed; 1221 } 1222 1223 bool ARMLowOverheadLoops::ProcessLoop(MachineLoop *ML) { 1224 1225 bool Changed = false; 1226 1227 // Process inner loops first. 1228 for (auto I = ML->begin(), E = ML->end(); I != E; ++I) 1229 Changed |= ProcessLoop(*I); 1230 1231 LLVM_DEBUG(dbgs() << "ARM Loops: Processing loop containing:\n"; 1232 if (auto *Preheader = ML->getLoopPreheader()) 1233 dbgs() << " - " << Preheader->getName() << "\n"; 1234 else if (auto *Preheader = MLI->findLoopPreheader(ML)) 1235 dbgs() << " - " << Preheader->getName() << "\n"; 1236 else if (auto *Preheader = MLI->findLoopPreheader(ML, true)) 1237 dbgs() << " - " << Preheader->getName() << "\n"; 1238 for (auto *MBB : ML->getBlocks()) 1239 dbgs() << " - " << MBB->getName() << "\n"; 1240 ); 1241 1242 // Search the given block for a loop start instruction. If one isn't found, 1243 // and there's only one predecessor block, search that one too. 1244 std::function<MachineInstr*(MachineBasicBlock*)> SearchForStart = 1245 [&SearchForStart](MachineBasicBlock *MBB) -> MachineInstr* { 1246 for (auto &MI : *MBB) { 1247 if (isLoopStart(MI)) 1248 return &MI; 1249 } 1250 if (MBB->pred_size() == 1) 1251 return SearchForStart(*MBB->pred_begin()); 1252 return nullptr; 1253 }; 1254 1255 LowOverheadLoop LoLoop(*ML, *MLI, *RDA, *TRI, *TII); 1256 // Search the preheader for the start intrinsic. 1257 // FIXME: I don't see why we shouldn't be supporting multiple predecessors 1258 // with potentially multiple set.loop.iterations, so we need to enable this. 1259 if (LoLoop.Preheader) 1260 LoLoop.Start = SearchForStart(LoLoop.Preheader); 1261 else 1262 return false; 1263 1264 // Find the low-overhead loop components and decide whether or not to fall 1265 // back to a normal loop. Also look for a vctp instructions and decide 1266 // whether we can convert that predicate using tail predication. 1267 for (auto *MBB : reverse(ML->getBlocks())) { 1268 for (auto &MI : *MBB) { 1269 if (MI.isDebugValue()) 1270 continue; 1271 else if (MI.getOpcode() == ARM::t2LoopDec) 1272 LoLoop.Dec = &MI; 1273 else if (MI.getOpcode() == ARM::t2LoopEnd) 1274 LoLoop.End = &MI; 1275 else if (MI.getOpcode() == ARM::t2LoopEndDec) 1276 LoLoop.End = LoLoop.Dec = &MI; 1277 else if (isLoopStart(MI)) 1278 LoLoop.Start = &MI; 1279 else if (MI.getDesc().isCall()) { 1280 // TODO: Though the call will require LE to execute again, does this 1281 // mean we should revert? Always executing LE hopefully should be 1282 // faster than performing a sub,cmp,br or even subs,br. 1283 LoLoop.Revert = true; 1284 LLVM_DEBUG(dbgs() << "ARM Loops: Found call.\n"); 1285 } else { 1286 // Record VPR defs and build up their corresponding vpt blocks. 1287 // Check we know how to tail predicate any mve instructions. 1288 LoLoop.AnalyseMVEInst(&MI); 1289 } 1290 } 1291 } 1292 1293 LLVM_DEBUG(LoLoop.dump()); 1294 if (!LoLoop.FoundAllComponents()) { 1295 LLVM_DEBUG(dbgs() << "ARM Loops: Didn't find loop start, update, end\n"); 1296 return false; 1297 } 1298 1299 // Check that the only instruction using LoopDec is LoopEnd. This can only 1300 // happen when the Dec and End are separate, not a single t2LoopEndDec. 1301 // TODO: Check for copy chains that really have no effect. 1302 if (LoLoop.Dec != LoLoop.End) { 1303 SmallPtrSet<MachineInstr *, 2> Uses; 1304 RDA->getReachingLocalUses(LoLoop.Dec, MCRegister::from(ARM::LR), Uses); 1305 if (Uses.size() > 1 || !Uses.count(LoLoop.End)) { 1306 LLVM_DEBUG(dbgs() << "ARM Loops: Unable to remove LoopDec.\n"); 1307 LoLoop.Revert = true; 1308 } 1309 } 1310 LoLoop.Validate(BBUtils.get()); 1311 Expand(LoLoop); 1312 return true; 1313 } 1314 1315 // WhileLoopStart holds the exit block, so produce a cmp lr, 0 and then a 1316 // beq that branches to the exit branch. 1317 // TODO: We could also try to generate a cbz if the value in LR is also in 1318 // another low register. 1319 void ARMLowOverheadLoops::RevertWhile(MachineInstr *MI) const { 1320 LLVM_DEBUG(dbgs() << "ARM Loops: Reverting to cmp: " << *MI); 1321 MachineBasicBlock *DestBB = MI->getOperand(1).getMBB(); 1322 unsigned BrOpc = BBUtils->isBBInRange(MI, DestBB, 254) ? 1323 ARM::tBcc : ARM::t2Bcc; 1324 1325 RevertWhileLoopStart(MI, TII, BrOpc); 1326 } 1327 1328 void ARMLowOverheadLoops::RevertDo(MachineInstr *MI) const { 1329 LLVM_DEBUG(dbgs() << "ARM Loops: Reverting to mov: " << *MI); 1330 RevertDoLoopStart(MI, TII); 1331 } 1332 1333 bool ARMLowOverheadLoops::RevertLoopDec(MachineInstr *MI) const { 1334 LLVM_DEBUG(dbgs() << "ARM Loops: Reverting to sub: " << *MI); 1335 MachineBasicBlock *MBB = MI->getParent(); 1336 SmallPtrSet<MachineInstr*, 1> Ignore; 1337 for (auto I = MachineBasicBlock::iterator(MI), E = MBB->end(); I != E; ++I) { 1338 if (I->getOpcode() == ARM::t2LoopEnd) { 1339 Ignore.insert(&*I); 1340 break; 1341 } 1342 } 1343 1344 // If nothing defines CPSR between LoopDec and LoopEnd, use a t2SUBS. 1345 bool SetFlags = 1346 RDA->isSafeToDefRegAt(MI, MCRegister::from(ARM::CPSR), Ignore); 1347 1348 llvm::RevertLoopDec(MI, TII, SetFlags); 1349 return SetFlags; 1350 } 1351 1352 // Generate a subs, or sub and cmp, and a branch instead of an LE. 1353 void ARMLowOverheadLoops::RevertLoopEnd(MachineInstr *MI, bool SkipCmp) const { 1354 LLVM_DEBUG(dbgs() << "ARM Loops: Reverting to cmp, br: " << *MI); 1355 1356 MachineBasicBlock *DestBB = MI->getOperand(1).getMBB(); 1357 unsigned BrOpc = BBUtils->isBBInRange(MI, DestBB, 254) ? 1358 ARM::tBcc : ARM::t2Bcc; 1359 1360 llvm::RevertLoopEnd(MI, TII, BrOpc, SkipCmp); 1361 } 1362 1363 // Generate a subs, or sub and cmp, and a branch instead of an LE. 1364 void ARMLowOverheadLoops::RevertLoopEndDec(MachineInstr *MI) const { 1365 LLVM_DEBUG(dbgs() << "ARM Loops: Reverting to subs, br: " << *MI); 1366 assert(MI->getOpcode() == ARM::t2LoopEndDec && "Expected a t2LoopEndDec!"); 1367 MachineBasicBlock *MBB = MI->getParent(); 1368 1369 MachineInstrBuilder MIB = 1370 BuildMI(*MBB, MI, MI->getDebugLoc(), TII->get(ARM::t2SUBri)); 1371 MIB.addDef(ARM::LR); 1372 MIB.add(MI->getOperand(1)); 1373 MIB.addImm(1); 1374 MIB.addImm(ARMCC::AL); 1375 MIB.addReg(ARM::NoRegister); 1376 MIB.addReg(ARM::CPSR); 1377 MIB->getOperand(5).setIsDef(true); 1378 1379 MachineBasicBlock *DestBB = MI->getOperand(2).getMBB(); 1380 unsigned BrOpc = 1381 BBUtils->isBBInRange(MI, DestBB, 254) ? ARM::tBcc : ARM::t2Bcc; 1382 1383 // Create bne 1384 MIB = BuildMI(*MBB, MI, MI->getDebugLoc(), TII->get(BrOpc)); 1385 MIB.add(MI->getOperand(2)); // branch target 1386 MIB.addImm(ARMCC::NE); // condition code 1387 MIB.addReg(ARM::CPSR); 1388 1389 MI->eraseFromParent(); 1390 } 1391 1392 // Perform dead code elimation on the loop iteration count setup expression. 1393 // If we are tail-predicating, the number of elements to be processed is the 1394 // operand of the VCTP instruction in the vector body, see getCount(), which is 1395 // register $r3 in this example: 1396 // 1397 // $lr = big-itercount-expression 1398 // .. 1399 // $lr = t2DoLoopStart renamable $lr 1400 // vector.body: 1401 // .. 1402 // $vpr = MVE_VCTP32 renamable $r3 1403 // renamable $lr = t2LoopDec killed renamable $lr, 1 1404 // t2LoopEnd renamable $lr, %vector.body 1405 // tB %end 1406 // 1407 // What we would like achieve here is to replace the do-loop start pseudo 1408 // instruction t2DoLoopStart with: 1409 // 1410 // $lr = MVE_DLSTP_32 killed renamable $r3 1411 // 1412 // Thus, $r3 which defines the number of elements, is written to $lr, 1413 // and then we want to delete the whole chain that used to define $lr, 1414 // see the comment below how this chain could look like. 1415 // 1416 void ARMLowOverheadLoops::IterationCountDCE(LowOverheadLoop &LoLoop) { 1417 if (!LoLoop.IsTailPredicationLegal()) 1418 return; 1419 1420 LLVM_DEBUG(dbgs() << "ARM Loops: Trying DCE on loop iteration count.\n"); 1421 1422 MachineInstr *Def = 1423 RDA->getMIOperand(LoLoop.Start, isDo(LoLoop.Start) ? 1 : 0); 1424 if (!Def) { 1425 LLVM_DEBUG(dbgs() << "ARM Loops: Couldn't find iteration count.\n"); 1426 return; 1427 } 1428 1429 // Collect and remove the users of iteration count. 1430 SmallPtrSet<MachineInstr*, 4> Killed = { LoLoop.Start, LoLoop.Dec, 1431 LoLoop.End }; 1432 if (!TryRemove(Def, *RDA, LoLoop.ToRemove, Killed)) 1433 LLVM_DEBUG(dbgs() << "ARM Loops: Unsafe to remove loop iteration count.\n"); 1434 } 1435 1436 MachineInstr* ARMLowOverheadLoops::ExpandLoopStart(LowOverheadLoop &LoLoop) { 1437 LLVM_DEBUG(dbgs() << "ARM Loops: Expanding LoopStart.\n"); 1438 // When using tail-predication, try to delete the dead code that was used to 1439 // calculate the number of loop iterations. 1440 IterationCountDCE(LoLoop); 1441 1442 MachineBasicBlock::iterator InsertPt = LoLoop.StartInsertPt; 1443 MachineInstr *Start = LoLoop.Start; 1444 MachineBasicBlock *MBB = LoLoop.StartInsertBB; 1445 unsigned Opc = LoLoop.getStartOpcode(); 1446 MachineOperand &Count = LoLoop.getLoopStartOperand(); 1447 1448 MachineInstrBuilder MIB = 1449 BuildMI(*MBB, InsertPt, Start->getDebugLoc(), TII->get(Opc)); 1450 1451 MIB.addDef(ARM::LR); 1452 MIB.add(Count); 1453 if (!isDo(Start)) 1454 MIB.add(Start->getOperand(1)); 1455 1456 LoLoop.ToRemove.insert(Start); 1457 LLVM_DEBUG(dbgs() << "ARM Loops: Inserted start: " << *MIB); 1458 return &*MIB; 1459 } 1460 1461 void ARMLowOverheadLoops::ConvertVPTBlocks(LowOverheadLoop &LoLoop) { 1462 auto RemovePredicate = [](MachineInstr *MI) { 1463 LLVM_DEBUG(dbgs() << "ARM Loops: Removing predicate from: " << *MI); 1464 if (int PIdx = llvm::findFirstVPTPredOperandIdx(*MI)) { 1465 assert(MI->getOperand(PIdx).getImm() == ARMVCC::Then && 1466 "Expected Then predicate!"); 1467 MI->getOperand(PIdx).setImm(ARMVCC::None); 1468 MI->getOperand(PIdx+1).setReg(0); 1469 } else 1470 llvm_unreachable("trying to unpredicate a non-predicated instruction"); 1471 }; 1472 1473 for (auto &Block : LoLoop.getVPTBlocks()) { 1474 SmallVectorImpl<MachineInstr *> &Insts = Block.getInsts(); 1475 1476 auto ReplaceVCMPWithVPT = [&](MachineInstr *&TheVCMP, MachineInstr *At) { 1477 assert(TheVCMP && "Replacing a removed or non-existent VCMP"); 1478 // Replace the VCMP with a VPT 1479 MachineInstrBuilder MIB = 1480 BuildMI(*At->getParent(), At, At->getDebugLoc(), 1481 TII->get(VCMPOpcodeToVPT(TheVCMP->getOpcode()))); 1482 MIB.addImm(ARMVCC::Then); 1483 // Register one 1484 MIB.add(TheVCMP->getOperand(1)); 1485 // Register two 1486 MIB.add(TheVCMP->getOperand(2)); 1487 // The comparison code, e.g. ge, eq, lt 1488 MIB.add(TheVCMP->getOperand(3)); 1489 LLVM_DEBUG(dbgs() << "ARM Loops: Combining with VCMP to VPT: " << *MIB); 1490 LoLoop.BlockMasksToRecompute.insert(MIB.getInstr()); 1491 LoLoop.ToRemove.insert(TheVCMP); 1492 TheVCMP = nullptr; 1493 }; 1494 1495 if (VPTState::isEntryPredicatedOnVCTP(Block, /*exclusive*/ true)) { 1496 MachineInstr *VPST = Insts.front(); 1497 if (VPTState::hasUniformPredicate(Block)) { 1498 // A vpt block starting with VPST, is only predicated upon vctp and has no 1499 // internal vpr defs: 1500 // - Remove vpst. 1501 // - Unpredicate the remaining instructions. 1502 LLVM_DEBUG(dbgs() << "ARM Loops: Removing VPST: " << *VPST); 1503 for (unsigned i = 1; i < Insts.size(); ++i) 1504 RemovePredicate(Insts[i]); 1505 } else { 1506 // The VPT block has a non-uniform predicate but it uses a vpst and its 1507 // entry is guarded only by a vctp, which means we: 1508 // - Need to remove the original vpst. 1509 // - Then need to unpredicate any following instructions, until 1510 // we come across the divergent vpr def. 1511 // - Insert a new vpst to predicate the instruction(s) that following 1512 // the divergent vpr def. 1513 MachineInstr *Divergent = VPTState::getDivergent(Block); 1514 auto DivergentNext = ++MachineBasicBlock::iterator(Divergent); 1515 bool DivergentNextIsPredicated = 1516 getVPTInstrPredicate(*DivergentNext) != ARMVCC::None; 1517 1518 for (auto I = ++MachineBasicBlock::iterator(VPST), E = DivergentNext; 1519 I != E; ++I) 1520 RemovePredicate(&*I); 1521 1522 // Check if the instruction defining vpr is a vcmp so it can be combined 1523 // with the VPST This should be the divergent instruction 1524 MachineInstr *VCMP = 1525 VCMPOpcodeToVPT(Divergent->getOpcode()) != 0 ? Divergent : nullptr; 1526 1527 if (DivergentNextIsPredicated) { 1528 // Insert a VPST at the divergent only if the next instruction 1529 // would actually use it. A VCMP following a VPST can be 1530 // merged into a VPT so do that instead if the VCMP exists. 1531 if (!VCMP) { 1532 // Create a VPST (with a null mask for now, we'll recompute it 1533 // later) 1534 MachineInstrBuilder MIB = 1535 BuildMI(*Divergent->getParent(), Divergent, 1536 Divergent->getDebugLoc(), TII->get(ARM::MVE_VPST)); 1537 MIB.addImm(0); 1538 LLVM_DEBUG(dbgs() << "ARM Loops: Created VPST: " << *MIB); 1539 LoLoop.BlockMasksToRecompute.insert(MIB.getInstr()); 1540 } else { 1541 // No RDA checks are necessary here since the VPST would have been 1542 // directly after the VCMP 1543 ReplaceVCMPWithVPT(VCMP, VCMP); 1544 } 1545 } 1546 } 1547 LLVM_DEBUG(dbgs() << "ARM Loops: Removing VPST: " << *VPST); 1548 LoLoop.ToRemove.insert(VPST); 1549 } else if (Block.containsVCTP()) { 1550 // The vctp will be removed, so the block mask of the vp(s)t will need 1551 // to be recomputed. 1552 LoLoop.BlockMasksToRecompute.insert(Insts.front()); 1553 } else if (Insts.front()->getOpcode() == ARM::MVE_VPST) { 1554 // If this block starts with a VPST then attempt to merge it with the 1555 // preceeding un-merged VCMP into a VPT. This VCMP comes from a VPT 1556 // block that no longer exists 1557 MachineInstr *VPST = Insts.front(); 1558 auto Next = ++MachineBasicBlock::iterator(VPST); 1559 assert(getVPTInstrPredicate(*Next) != ARMVCC::None && 1560 "The instruction after a VPST must be predicated"); 1561 (void)Next; 1562 MachineInstr *VprDef = RDA->getUniqueReachingMIDef(VPST, ARM::VPR); 1563 if (VprDef && VCMPOpcodeToVPT(VprDef->getOpcode()) && 1564 !LoLoop.ToRemove.contains(VprDef)) { 1565 MachineInstr *VCMP = VprDef; 1566 // The VCMP and VPST can only be merged if the VCMP's operands will have 1567 // the same values at the VPST. 1568 // If any of the instructions between the VCMP and VPST are predicated 1569 // then a different code path is expected to have merged the VCMP and 1570 // VPST already. 1571 if (!std::any_of(++MachineBasicBlock::iterator(VCMP), 1572 MachineBasicBlock::iterator(VPST), hasVPRUse) && 1573 RDA->hasSameReachingDef(VCMP, VPST, VCMP->getOperand(1).getReg()) && 1574 RDA->hasSameReachingDef(VCMP, VPST, VCMP->getOperand(2).getReg())) { 1575 ReplaceVCMPWithVPT(VCMP, VPST); 1576 LLVM_DEBUG(dbgs() << "ARM Loops: Removing VPST: " << *VPST); 1577 LoLoop.ToRemove.insert(VPST); 1578 } 1579 } 1580 } 1581 } 1582 1583 LoLoop.ToRemove.insert(LoLoop.VCTPs.begin(), LoLoop.VCTPs.end()); 1584 } 1585 1586 void ARMLowOverheadLoops::Expand(LowOverheadLoop &LoLoop) { 1587 1588 // Combine the LoopDec and LoopEnd instructions into LE(TP). 1589 auto ExpandLoopEnd = [this](LowOverheadLoop &LoLoop) { 1590 MachineInstr *End = LoLoop.End; 1591 MachineBasicBlock *MBB = End->getParent(); 1592 unsigned Opc = LoLoop.IsTailPredicationLegal() ? 1593 ARM::MVE_LETP : ARM::t2LEUpdate; 1594 MachineInstrBuilder MIB = BuildMI(*MBB, End, End->getDebugLoc(), 1595 TII->get(Opc)); 1596 MIB.addDef(ARM::LR); 1597 unsigned Off = LoLoop.Dec == LoLoop.End ? 1 : 0; 1598 MIB.add(End->getOperand(Off + 0)); 1599 MIB.add(End->getOperand(Off + 1)); 1600 LLVM_DEBUG(dbgs() << "ARM Loops: Inserted LE: " << *MIB); 1601 LoLoop.ToRemove.insert(LoLoop.Dec); 1602 LoLoop.ToRemove.insert(End); 1603 return &*MIB; 1604 }; 1605 1606 // TODO: We should be able to automatically remove these branches before we 1607 // get here - probably by teaching analyzeBranch about the pseudo 1608 // instructions. 1609 // If there is an unconditional branch, after I, that just branches to the 1610 // next block, remove it. 1611 auto RemoveDeadBranch = [](MachineInstr *I) { 1612 MachineBasicBlock *BB = I->getParent(); 1613 MachineInstr *Terminator = &BB->instr_back(); 1614 if (Terminator->isUnconditionalBranch() && I != Terminator) { 1615 MachineBasicBlock *Succ = Terminator->getOperand(0).getMBB(); 1616 if (BB->isLayoutSuccessor(Succ)) { 1617 LLVM_DEBUG(dbgs() << "ARM Loops: Removing branch: " << *Terminator); 1618 Terminator->eraseFromParent(); 1619 } 1620 } 1621 }; 1622 1623 if (LoLoop.Revert) { 1624 if (LoLoop.Start->getOpcode() == ARM::t2WhileLoopStart) 1625 RevertWhile(LoLoop.Start); 1626 else 1627 RevertDo(LoLoop.Start); 1628 if (LoLoop.Dec == LoLoop.End) 1629 RevertLoopEndDec(LoLoop.End); 1630 else 1631 RevertLoopEnd(LoLoop.End, RevertLoopDec(LoLoop.Dec)); 1632 } else { 1633 LoLoop.Start = ExpandLoopStart(LoLoop); 1634 RemoveDeadBranch(LoLoop.Start); 1635 LoLoop.End = ExpandLoopEnd(LoLoop); 1636 RemoveDeadBranch(LoLoop.End); 1637 if (LoLoop.IsTailPredicationLegal()) 1638 ConvertVPTBlocks(LoLoop); 1639 for (auto *I : LoLoop.ToRemove) { 1640 LLVM_DEBUG(dbgs() << "ARM Loops: Erasing " << *I); 1641 I->eraseFromParent(); 1642 } 1643 for (auto *I : LoLoop.BlockMasksToRecompute) { 1644 LLVM_DEBUG(dbgs() << "ARM Loops: Recomputing VPT/VPST Block Mask: " << *I); 1645 recomputeVPTBlockMask(*I); 1646 LLVM_DEBUG(dbgs() << " ... done: " << *I); 1647 } 1648 } 1649 1650 PostOrderLoopTraversal DFS(LoLoop.ML, *MLI); 1651 DFS.ProcessLoop(); 1652 const SmallVectorImpl<MachineBasicBlock*> &PostOrder = DFS.getOrder(); 1653 for (auto *MBB : PostOrder) { 1654 recomputeLiveIns(*MBB); 1655 // FIXME: For some reason, the live-in print order is non-deterministic for 1656 // our tests and I can't out why... So just sort them. 1657 MBB->sortUniqueLiveIns(); 1658 } 1659 1660 for (auto *MBB : reverse(PostOrder)) 1661 recomputeLivenessFlags(*MBB); 1662 1663 // We've moved, removed and inserted new instructions, so update RDA. 1664 RDA->reset(); 1665 } 1666 1667 bool ARMLowOverheadLoops::RevertNonLoops() { 1668 LLVM_DEBUG(dbgs() << "ARM Loops: Reverting any remaining pseudos...\n"); 1669 bool Changed = false; 1670 1671 for (auto &MBB : *MF) { 1672 SmallVector<MachineInstr*, 4> Starts; 1673 SmallVector<MachineInstr*, 4> Decs; 1674 SmallVector<MachineInstr*, 4> Ends; 1675 SmallVector<MachineInstr *, 4> EndDecs; 1676 1677 for (auto &I : MBB) { 1678 if (isLoopStart(I)) 1679 Starts.push_back(&I); 1680 else if (I.getOpcode() == ARM::t2LoopDec) 1681 Decs.push_back(&I); 1682 else if (I.getOpcode() == ARM::t2LoopEnd) 1683 Ends.push_back(&I); 1684 else if (I.getOpcode() == ARM::t2LoopEndDec) 1685 EndDecs.push_back(&I); 1686 } 1687 1688 if (Starts.empty() && Decs.empty() && Ends.empty() && EndDecs.empty()) 1689 continue; 1690 1691 Changed = true; 1692 1693 for (auto *Start : Starts) { 1694 if (Start->getOpcode() == ARM::t2WhileLoopStart) 1695 RevertWhile(Start); 1696 else 1697 RevertDo(Start); 1698 } 1699 for (auto *Dec : Decs) 1700 RevertLoopDec(Dec); 1701 1702 for (auto *End : Ends) 1703 RevertLoopEnd(End); 1704 for (auto *End : EndDecs) 1705 RevertLoopEndDec(End); 1706 } 1707 return Changed; 1708 } 1709 1710 FunctionPass *llvm::createARMLowOverheadLoopsPass() { 1711 return new ARMLowOverheadLoops(); 1712 } 1713