1 //===- MVETailPredication.cpp - MVE Tail Predication ------------*- 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 // 9 /// \file 10 /// Armv8.1m introduced MVE, M-Profile Vector Extension, and low-overhead 11 /// branches to help accelerate DSP applications. These two extensions, 12 /// combined with a new form of predication called tail-predication, can be used 13 /// to provide implicit vector predication within a low-overhead loop. 14 /// This is implicit because the predicate of active/inactive lanes is 15 /// calculated by hardware, and thus does not need to be explicitly passed 16 /// to vector instructions. The instructions responsible for this are the 17 /// DLSTP and WLSTP instructions, which setup a tail-predicated loop and the 18 /// the total number of data elements processed by the loop. The loop-end 19 /// LETP instruction is responsible for decrementing and setting the remaining 20 /// elements to be processed and generating the mask of active lanes. 21 /// 22 /// The HardwareLoops pass inserts intrinsics identifying loops that the 23 /// backend will attempt to convert into a low-overhead loop. The vectorizer is 24 /// responsible for generating a vectorized loop in which the lanes are 25 /// predicated upon the iteration counter. This pass looks at these predicated 26 /// vector loops, that are targets for low-overhead loops, and prepares it for 27 /// code generation. Once the vectorizer has produced a masked loop, there's a 28 /// couple of final forms: 29 /// - A tail-predicated loop, with implicit predication. 30 /// - A loop containing multiple VCPT instructions, predicating multiple VPT 31 /// blocks of instructions operating on different vector types. 32 /// 33 /// This pass: 34 /// 1) Checks if the predicates of the masked load/store instructions are 35 /// generated by intrinsic @llvm.get.active.lanes(). This intrinsic consumes 36 /// the Backedge Taken Count (BTC) of the scalar loop as its second argument, 37 /// which we extract to set up the number of elements processed by the loop. 38 /// 2) Intrinsic @llvm.get.active.lanes() is then replaced by the MVE target 39 /// specific VCTP intrinsic to represent the effect of tail predication. 40 /// This will be picked up by the ARM Low-overhead loop pass, which performs 41 /// the final transformation to a DLSTP or WLSTP tail-predicated loop. 42 43 #include "ARM.h" 44 #include "ARMSubtarget.h" 45 #include "llvm/Analysis/LoopInfo.h" 46 #include "llvm/Analysis/LoopPass.h" 47 #include "llvm/Analysis/ScalarEvolution.h" 48 #include "llvm/Analysis/ScalarEvolutionExpressions.h" 49 #include "llvm/Analysis/TargetLibraryInfo.h" 50 #include "llvm/Analysis/TargetTransformInfo.h" 51 #include "llvm/CodeGen/TargetPassConfig.h" 52 #include "llvm/IR/IRBuilder.h" 53 #include "llvm/IR/Instructions.h" 54 #include "llvm/IR/IntrinsicsARM.h" 55 #include "llvm/IR/PatternMatch.h" 56 #include "llvm/InitializePasses.h" 57 #include "llvm/Support/Debug.h" 58 #include "llvm/Transforms/Utils/BasicBlockUtils.h" 59 #include "llvm/Transforms/Utils/LoopUtils.h" 60 #include "llvm/Transforms/Utils/ScalarEvolutionExpander.h" 61 62 using namespace llvm; 63 64 #define DEBUG_TYPE "mve-tail-predication" 65 #define DESC "Transform predicated vector loops to use MVE tail predication" 66 67 static cl::opt<bool> 68 ForceTailPredication("force-mve-tail-predication", cl::Hidden, cl::init(false), 69 cl::desc("Force MVE tail-predication even if it might be " 70 "unsafe (e.g. possible overflow in loop " 71 "counters)")); 72 73 cl::opt<bool> 74 DisableTailPredication("disable-mve-tail-predication", cl::Hidden, 75 cl::init(true), 76 cl::desc("Disable MVE Tail Predication")); 77 namespace { 78 79 class MVETailPredication : public LoopPass { 80 SmallVector<IntrinsicInst*, 4> MaskedInsts; 81 Loop *L = nullptr; 82 ScalarEvolution *SE = nullptr; 83 TargetTransformInfo *TTI = nullptr; 84 const ARMSubtarget *ST = nullptr; 85 86 public: 87 static char ID; 88 89 MVETailPredication() : LoopPass(ID) { } 90 91 void getAnalysisUsage(AnalysisUsage &AU) const override { 92 AU.addRequired<ScalarEvolutionWrapperPass>(); 93 AU.addRequired<LoopInfoWrapperPass>(); 94 AU.addRequired<TargetPassConfig>(); 95 AU.addRequired<TargetTransformInfoWrapperPass>(); 96 AU.addPreserved<LoopInfoWrapperPass>(); 97 AU.setPreservesCFG(); 98 } 99 100 bool runOnLoop(Loop *L, LPPassManager&) override; 101 102 private: 103 /// Perform the relevant checks on the loop and convert if possible. 104 bool TryConvert(Value *TripCount); 105 106 /// Return whether this is a vectorized loop, that contains masked 107 /// load/stores. 108 bool IsPredicatedVectorLoop(); 109 110 /// Perform checks on the arguments of @llvm.get.active.lane.mask 111 /// intrinsic: check if the first is a loop induction variable, and for the 112 /// the second check that no overflow can occur in the expression that use 113 /// this backedge-taken count. 114 bool IsSafeActiveMask(IntrinsicInst *ActiveLaneMask, Value *TripCount, 115 FixedVectorType *VecTy); 116 117 /// Insert the intrinsic to represent the effect of tail predication. 118 void InsertVCTPIntrinsic(IntrinsicInst *ActiveLaneMask, Value *TripCount, 119 FixedVectorType *VecTy); 120 121 /// Rematerialize the iteration count in exit blocks, which enables 122 /// ARMLowOverheadLoops to better optimise away loop update statements inside 123 /// hardware-loops. 124 void RematerializeIterCount(); 125 }; 126 127 } // end namespace 128 129 static bool IsDecrement(Instruction &I) { 130 auto *Call = dyn_cast<IntrinsicInst>(&I); 131 if (!Call) 132 return false; 133 134 Intrinsic::ID ID = Call->getIntrinsicID(); 135 return ID == Intrinsic::loop_decrement_reg; 136 } 137 138 static bool IsMasked(Instruction *I) { 139 auto *Call = dyn_cast<IntrinsicInst>(I); 140 if (!Call) 141 return false; 142 143 Intrinsic::ID ID = Call->getIntrinsicID(); 144 // TODO: Support gather/scatter expand/compress operations. 145 return ID == Intrinsic::masked_store || ID == Intrinsic::masked_load; 146 } 147 148 bool MVETailPredication::runOnLoop(Loop *L, LPPassManager&) { 149 if (skipLoop(L) || DisableTailPredication) 150 return false; 151 152 MaskedInsts.clear(); 153 Function &F = *L->getHeader()->getParent(); 154 auto &TPC = getAnalysis<TargetPassConfig>(); 155 auto &TM = TPC.getTM<TargetMachine>(); 156 ST = &TM.getSubtarget<ARMSubtarget>(F); 157 TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F); 158 SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE(); 159 this->L = L; 160 161 // The MVE and LOB extensions are combined to enable tail-predication, but 162 // there's nothing preventing us from generating VCTP instructions for v8.1m. 163 if (!ST->hasMVEIntegerOps() || !ST->hasV8_1MMainlineOps()) { 164 LLVM_DEBUG(dbgs() << "ARM TP: Not a v8.1m.main+mve target.\n"); 165 return false; 166 } 167 168 BasicBlock *Preheader = L->getLoopPreheader(); 169 if (!Preheader) 170 return false; 171 172 auto FindLoopIterations = [](BasicBlock *BB) -> IntrinsicInst* { 173 for (auto &I : *BB) { 174 auto *Call = dyn_cast<IntrinsicInst>(&I); 175 if (!Call) 176 continue; 177 178 Intrinsic::ID ID = Call->getIntrinsicID(); 179 if (ID == Intrinsic::set_loop_iterations || 180 ID == Intrinsic::test_set_loop_iterations) 181 return cast<IntrinsicInst>(&I); 182 } 183 return nullptr; 184 }; 185 186 // Look for the hardware loop intrinsic that sets the iteration count. 187 IntrinsicInst *Setup = FindLoopIterations(Preheader); 188 189 // The test.set iteration could live in the pre-preheader. 190 if (!Setup) { 191 if (!Preheader->getSinglePredecessor()) 192 return false; 193 Setup = FindLoopIterations(Preheader->getSinglePredecessor()); 194 if (!Setup) 195 return false; 196 } 197 198 // Search for the hardware loop intrinic that decrements the loop counter. 199 IntrinsicInst *Decrement = nullptr; 200 for (auto *BB : L->getBlocks()) { 201 for (auto &I : *BB) { 202 if (IsDecrement(I)) { 203 Decrement = cast<IntrinsicInst>(&I); 204 break; 205 } 206 } 207 } 208 209 if (!Decrement) 210 return false; 211 212 LLVM_DEBUG(dbgs() << "ARM TP: Running on Loop: " << *L << *Setup << "\n" 213 << *Decrement << "\n"); 214 215 if (!TryConvert(Setup->getArgOperand(0))) { 216 LLVM_DEBUG(dbgs() << "ARM TP: Can't tail-predicate this loop.\n"); 217 return false; 218 } 219 220 return true; 221 } 222 223 static FixedVectorType *getVectorType(IntrinsicInst *I) { 224 unsigned TypeOp = I->getIntrinsicID() == Intrinsic::masked_load ? 0 : 1; 225 auto *PtrTy = cast<PointerType>(I->getOperand(TypeOp)->getType()); 226 auto *VecTy = cast<FixedVectorType>(PtrTy->getElementType()); 227 assert(VecTy && "No scalable vectors expected here"); 228 return VecTy; 229 } 230 231 bool MVETailPredication::IsPredicatedVectorLoop() { 232 // Check that the loop contains at least one masked load/store intrinsic. 233 // We only support 'normal' vector instructions - other than masked 234 // load/stores. 235 bool ActiveLaneMask = false; 236 for (auto *BB : L->getBlocks()) { 237 for (auto &I : *BB) { 238 auto *Int = dyn_cast<IntrinsicInst>(&I); 239 if (!Int) 240 continue; 241 242 switch (Int->getIntrinsicID()) { 243 case Intrinsic::get_active_lane_mask: 244 ActiveLaneMask = true; 245 LLVM_FALLTHROUGH; 246 case Intrinsic::sadd_sat: 247 case Intrinsic::uadd_sat: 248 case Intrinsic::ssub_sat: 249 case Intrinsic::usub_sat: 250 continue; 251 case Intrinsic::fma: 252 case Intrinsic::trunc: 253 case Intrinsic::rint: 254 case Intrinsic::round: 255 case Intrinsic::floor: 256 case Intrinsic::ceil: 257 case Intrinsic::fabs: 258 if (ST->hasMVEFloatOps()) 259 continue; 260 LLVM_FALLTHROUGH; 261 default: 262 break; 263 } 264 265 if (IsMasked(&I)) { 266 auto *VecTy = getVectorType(Int); 267 unsigned Lanes = VecTy->getNumElements(); 268 unsigned ElementWidth = VecTy->getScalarSizeInBits(); 269 // MVE vectors are 128-bit, but don't support 128 x i1. 270 // TODO: Can we support vectors larger than 128-bits? 271 unsigned MaxWidth = TTI->getRegisterBitWidth(true); 272 if (Lanes * ElementWidth > MaxWidth || Lanes == MaxWidth) 273 return false; 274 MaskedInsts.push_back(cast<IntrinsicInst>(&I)); 275 continue; 276 } 277 278 for (const Use &U : Int->args()) { 279 if (isa<VectorType>(U->getType())) 280 return false; 281 } 282 } 283 } 284 285 if (!ActiveLaneMask) { 286 LLVM_DEBUG(dbgs() << "ARM TP: No get.active.lane.mask intrinsic found.\n"); 287 return false; 288 } 289 return !MaskedInsts.empty(); 290 } 291 292 // Look through the exit block to see whether there's a duplicate predicate 293 // instruction. This can happen when we need to perform a select on values 294 // from the last and previous iteration. Instead of doing a straight 295 // replacement of that predicate with the vctp, clone the vctp and place it 296 // in the block. This means that the VPR doesn't have to be live into the 297 // exit block which should make it easier to convert this loop into a proper 298 // tail predicated loop. 299 static void Cleanup(SetVector<Instruction*> &MaybeDead, Loop *L) { 300 BasicBlock *Exit = L->getUniqueExitBlock(); 301 if (!Exit) { 302 LLVM_DEBUG(dbgs() << "ARM TP: can't find loop exit block\n"); 303 return; 304 } 305 306 // Drop references and add operands to check for dead. 307 SmallPtrSet<Instruction*, 4> Dead; 308 while (!MaybeDead.empty()) { 309 auto *I = MaybeDead.front(); 310 MaybeDead.remove(I); 311 if (I->hasNUsesOrMore(1)) 312 continue; 313 314 for (auto &U : I->operands()) 315 if (auto *OpI = dyn_cast<Instruction>(U)) 316 MaybeDead.insert(OpI); 317 318 Dead.insert(I); 319 } 320 321 for (auto *I : Dead) { 322 LLVM_DEBUG(dbgs() << "ARM TP: removing dead insn: "; I->dump()); 323 I->eraseFromParent(); 324 } 325 326 for (auto I : L->blocks()) 327 DeleteDeadPHIs(I); 328 } 329 330 // The active lane intrinsic has this form: 331 // 332 // @llvm.get.active.lane.mask(IV, BTC) 333 // 334 // Here we perform checks that this intrinsic behaves as expected, 335 // which means: 336 // 337 // 1) The element count, which is calculated with BTC + 1, cannot overflow. 338 // 2) The element count needs to be sufficiently large that the decrement of 339 // element counter doesn't overflow, which means that we need to prove: 340 // ceil(ElementCount / VectorWidth) >= TripCount 341 // by rounding up ElementCount up: 342 // ((ElementCount + (VectorWidth - 1)) / VectorWidth 343 // and evaluate if expression isKnownNonNegative: 344 // (((ElementCount + (VectorWidth - 1)) / VectorWidth) - TripCount 345 // 3) The IV must be an induction phi with an increment equal to the 346 // vector width. 347 bool MVETailPredication::IsSafeActiveMask(IntrinsicInst *ActiveLaneMask, 348 Value *TripCount, FixedVectorType *VecTy) { 349 // 1) Test whether entry to the loop is protected by a conditional 350 // BTC + 1 < 0. In other words, if the scalar trip count overflows, 351 // becomes negative, we shouldn't enter the loop and creating 352 // tripcount expression BTC + 1 is not safe. So, check that BTC 353 // isn't max. This is evaluated in unsigned, because the semantics 354 // of @get.active.lane.mask is a ULE comparison. 355 356 int VectorWidth = VecTy->getNumElements(); 357 auto *BackedgeTakenCount = ActiveLaneMask->getOperand(1); 358 auto *BTC = SE->getSCEV(BackedgeTakenCount); 359 360 if (!llvm::cannotBeMaxInLoop(BTC, L, *SE, false /*Signed*/) && 361 !ForceTailPredication) { 362 LLVM_DEBUG(dbgs() << "ARM TP: Overflow possible, BTC can be max: "; 363 BTC->dump()); 364 return false; 365 } 366 367 // 2) Prove that the sub expression is non-negative, i.e. it doesn't overflow: 368 // 369 // (((ElementCount + (VectorWidth - 1)) / VectorWidth) - TripCount 370 // 371 // 2.1) First prove overflow can't happen in: 372 // 373 // ElementCount + (VectorWidth - 1) 374 // 375 // Because of a lack of context, it is difficult to get a useful bounds on 376 // this expression. But since ElementCount uses the same variables as the 377 // TripCount (TC), for which we can find meaningful value ranges, we use that 378 // instead and assert that: 379 // 380 // upperbound(TC) <= UINT_MAX - VectorWidth 381 // 382 auto *TC = SE->getSCEV(TripCount); 383 unsigned SizeInBits = TripCount->getType()->getScalarSizeInBits(); 384 auto Diff = APInt(SizeInBits, ~0) - APInt(SizeInBits, VectorWidth); 385 uint64_t MaxMinusVW = Diff.getZExtValue(); 386 uint64_t UpperboundTC = SE->getSignedRange(TC).getUpper().getZExtValue(); 387 388 if (UpperboundTC > MaxMinusVW && !ForceTailPredication) { 389 LLVM_DEBUG(dbgs() << "ARM TP: Overflow possible in tripcount rounding:\n"; 390 dbgs() << "upperbound(TC) <= UINT_MAX - VectorWidth\n"; 391 dbgs() << UpperboundTC << " <= " << MaxMinusVW << "== false\n";); 392 return false; 393 } 394 395 // 2.2) Make sure overflow doesn't happen in final expression: 396 // (((ElementCount + (VectorWidth - 1)) / VectorWidth) - TripCount, 397 // To do this, compare the full ranges of these subexpressions: 398 // 399 // Range(Ceil) <= Range(TC) 400 // 401 // where Ceil = ElementCount + (VW-1) / VW. If Ceil and TC are runtime 402 // values (and not constants), we have to compensate for the lowerbound value 403 // range to be off by 1. The reason is that BTC lives in the preheader in 404 // this form: 405 // 406 // %trip.count.minus = add nsw nuw i32 %N, -1 407 // 408 // For the loop to be executed, %N has to be >= 1 and as a result the value 409 // range of %trip.count.minus has a lower bound of 0. Value %TC has this form: 410 // 411 // %5 = add nuw nsw i32 %4, 1 412 // call void @llvm.set.loop.iterations.i32(i32 %5) 413 // 414 // where %5 is some expression using %N, which needs to have a lower bound of 415 // 1. Thus, if the ranges of Ceil and TC are not a single constant but a set, 416 // we first add 0 to TC such that we can do the <= comparison on both sets. 417 // 418 auto *One = SE->getOne(TripCount->getType()); 419 // ElementCount = BTC + 1 420 auto *ElementCount = SE->getAddExpr(BTC, One); 421 // Tmp = ElementCount + (VW-1) 422 auto *ECPlusVWMinus1 = SE->getAddExpr(ElementCount, 423 SE->getSCEV(ConstantInt::get(TripCount->getType(), VectorWidth - 1))); 424 // Ceil = ElementCount + (VW-1) / VW 425 auto *Ceil = SE->getUDivExpr(ECPlusVWMinus1, 426 SE->getSCEV(ConstantInt::get(TripCount->getType(), VectorWidth))); 427 428 ConstantRange RangeCeil = SE->getSignedRange(Ceil) ; 429 ConstantRange RangeTC = SE->getSignedRange(TC) ; 430 if (!RangeTC.isSingleElement()) { 431 auto ZeroRange = 432 ConstantRange(APInt(TripCount->getType()->getScalarSizeInBits(), 0)); 433 RangeTC = RangeTC.unionWith(ZeroRange); 434 } 435 if (!RangeTC.contains(RangeCeil) && !ForceTailPredication) { 436 LLVM_DEBUG(dbgs() << "ARM TP: Overflow possible in sub\n"); 437 return false; 438 } 439 440 // 3) Find out if IV is an induction phi. Note that We can't use Loop 441 // helpers here to get the induction variable, because the hardware loop is 442 // no longer in loopsimplify form, and also the hwloop intrinsic use a 443 // different counter. Using SCEV, we check that the induction is of the 444 // form i = i + 4, where the increment must be equal to the VectorWidth. 445 auto *IV = ActiveLaneMask->getOperand(0); 446 auto *IVExpr = SE->getSCEV(IV); 447 auto *AddExpr = dyn_cast<SCEVAddRecExpr>(IVExpr); 448 if (!AddExpr) { 449 LLVM_DEBUG(dbgs() << "ARM TP: induction not an add expr: "; IVExpr->dump()); 450 return false; 451 } 452 // Check that this AddRec is associated with this loop. 453 if (AddExpr->getLoop() != L) { 454 LLVM_DEBUG(dbgs() << "ARM TP: phi not part of this loop\n"); 455 return false; 456 } 457 auto *Step = dyn_cast<SCEVConstant>(AddExpr->getOperand(1)); 458 if (!Step) { 459 LLVM_DEBUG(dbgs() << "ARM TP: induction step is not a constant: "; 460 AddExpr->getOperand(1)->dump()); 461 return false; 462 } 463 auto StepValue = Step->getValue()->getSExtValue(); 464 if (VectorWidth == StepValue) 465 return true; 466 467 LLVM_DEBUG(dbgs() << "ARM TP: Step value " << StepValue << " doesn't match " 468 "vector width " << VectorWidth << "\n"); 469 470 return false; 471 } 472 473 // Materialize NumElements in the preheader block. 474 static Value *getNumElements(BasicBlock *Preheader, Value *BTC) { 475 // First, check the preheader if it not already exist: 476 // 477 // preheader: 478 // %BTC = add i32 %N, -1 479 // .. 480 // vector.body: 481 // 482 // if %BTC already exists. We don't need to emit %NumElems = %BTC + 1, 483 // but instead can just return %N. 484 for (auto &I : *Preheader) { 485 if (I.getOpcode() != Instruction::Add || &I != BTC) 486 continue; 487 ConstantInt *MinusOne = nullptr; 488 if (!(MinusOne = dyn_cast<ConstantInt>(I.getOperand(1)))) 489 continue; 490 if (MinusOne->getSExtValue() == -1) { 491 LLVM_DEBUG(dbgs() << "ARM TP: Found num elems: " << I << "\n"); 492 return I.getOperand(0); 493 } 494 } 495 496 // But we do need to materialise BTC if it is not already there, 497 // e.g. if it is a constant. 498 IRBuilder<> Builder(Preheader->getTerminator()); 499 Value *NumElements = Builder.CreateAdd(BTC, 500 ConstantInt::get(BTC->getType(), 1), "num.elements"); 501 LLVM_DEBUG(dbgs() << "ARM TP: Created num elems: " << *NumElements << "\n"); 502 return NumElements; 503 } 504 505 void MVETailPredication::InsertVCTPIntrinsic(IntrinsicInst *ActiveLaneMask, 506 Value *TripCount, FixedVectorType *VecTy) { 507 IRBuilder<> Builder(L->getLoopPreheader()->getTerminator()); 508 Module *M = L->getHeader()->getModule(); 509 Type *Ty = IntegerType::get(M->getContext(), 32); 510 unsigned VectorWidth = VecTy->getNumElements(); 511 512 // The backedge-taken count in @llvm.get.active.lane.mask, its 2nd operand, 513 // is one less than the trip count. So we need to find or create 514 // %num.elements = %BTC + 1 in the preheader. 515 Value *BTC = ActiveLaneMask->getOperand(1); 516 Builder.SetInsertPoint(L->getLoopPreheader()->getTerminator()); 517 Value *NumElements = getNumElements(L->getLoopPreheader(), BTC); 518 519 // Insert a phi to count the number of elements processed by the loop. 520 Builder.SetInsertPoint(L->getHeader()->getFirstNonPHI() ); 521 PHINode *Processed = Builder.CreatePHI(Ty, 2); 522 Processed->addIncoming(NumElements, L->getLoopPreheader()); 523 524 // Replace @llvm.get.active.mask() with the ARM specific VCTP intrinic, and thus 525 // represent the effect of tail predication. 526 Builder.SetInsertPoint(ActiveLaneMask); 527 ConstantInt *Factor = 528 ConstantInt::get(cast<IntegerType>(Ty), VectorWidth); 529 530 Intrinsic::ID VCTPID; 531 switch (VectorWidth) { 532 default: 533 llvm_unreachable("unexpected number of lanes"); 534 case 4: VCTPID = Intrinsic::arm_mve_vctp32; break; 535 case 8: VCTPID = Intrinsic::arm_mve_vctp16; break; 536 case 16: VCTPID = Intrinsic::arm_mve_vctp8; break; 537 538 // FIXME: vctp64 currently not supported because the predicate 539 // vector wants to be <2 x i1>, but v2i1 is not a legal MVE 540 // type, so problems happen at isel time. 541 // Intrinsic::arm_mve_vctp64 exists for ACLE intrinsics 542 // purposes, but takes a v4i1 instead of a v2i1. 543 } 544 Function *VCTP = Intrinsic::getDeclaration(M, VCTPID); 545 Value *VCTPCall = Builder.CreateCall(VCTP, Processed); 546 ActiveLaneMask->replaceAllUsesWith(VCTPCall); 547 548 // Add the incoming value to the new phi. 549 // TODO: This add likely already exists in the loop. 550 Value *Remaining = Builder.CreateSub(Processed, Factor); 551 Processed->addIncoming(Remaining, L->getLoopLatch()); 552 LLVM_DEBUG(dbgs() << "ARM TP: Insert processed elements phi: " 553 << *Processed << "\n" 554 << "ARM TP: Inserted VCTP: " << *VCTPCall << "\n"); 555 } 556 557 bool MVETailPredication::TryConvert(Value *TripCount) { 558 if (!IsPredicatedVectorLoop()) { 559 LLVM_DEBUG(dbgs() << "ARM TP: no masked instructions in loop.\n"); 560 return false; 561 } 562 563 LLVM_DEBUG(dbgs() << "ARM TP: Found predicated vector loop.\n"); 564 SetVector<Instruction*> Predicates; 565 566 // Walk through the masked intrinsics and try to find whether the predicate 567 // operand is generated by intrinsic @llvm.get.active.lane.mask(). 568 for (auto *I : MaskedInsts) { 569 unsigned PredOp = I->getIntrinsicID() == Intrinsic::masked_load ? 2 : 3; 570 auto *Predicate = dyn_cast<Instruction>(I->getArgOperand(PredOp)); 571 if (!Predicate || Predicates.count(Predicate)) 572 continue; 573 574 auto *ActiveLaneMask = dyn_cast<IntrinsicInst>(Predicate); 575 if (!ActiveLaneMask || 576 ActiveLaneMask->getIntrinsicID() != Intrinsic::get_active_lane_mask) 577 continue; 578 579 Predicates.insert(Predicate); 580 LLVM_DEBUG(dbgs() << "ARM TP: Found active lane mask: " 581 << *ActiveLaneMask << "\n"); 582 583 auto *VecTy = getVectorType(I); 584 if (!IsSafeActiveMask(ActiveLaneMask, TripCount, VecTy)) { 585 LLVM_DEBUG(dbgs() << "ARM TP: Not safe to insert VCTP.\n"); 586 return false; 587 } 588 LLVM_DEBUG(dbgs() << "ARM TP: Safe to insert VCTP.\n"); 589 InsertVCTPIntrinsic(ActiveLaneMask, TripCount, VecTy); 590 } 591 592 Cleanup(Predicates, L); 593 return true; 594 } 595 596 Pass *llvm::createMVETailPredicationPass() { 597 return new MVETailPredication(); 598 } 599 600 char MVETailPredication::ID = 0; 601 602 INITIALIZE_PASS_BEGIN(MVETailPredication, DEBUG_TYPE, DESC, false, false) 603 INITIALIZE_PASS_END(MVETailPredication, DEBUG_TYPE, DESC, false, false) 604