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