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