1 //===----- HexagonPacketizer.cpp - vliw packetizer ---------------------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // This implements a simple VLIW packetizer using DFA. The packetizer works on 11 // machine basic blocks. For each instruction I in BB, the packetizer consults 12 // the DFA to see if machine resources are available to execute I. If so, the 13 // packetizer checks if I depends on any instruction J in the current packet. 14 // If no dependency is found, I is added to current packet and machine resource 15 // is marked as taken. If any dependency is found, a target API call is made to 16 // prune the dependence. 17 // 18 //===----------------------------------------------------------------------===// 19 #include "HexagonRegisterInfo.h" 20 #include "HexagonSubtarget.h" 21 #include "HexagonTargetMachine.h" 22 #include "HexagonVLIWPacketizer.h" 23 #include "llvm/Analysis/AliasAnalysis.h" 24 #include "llvm/CodeGen/MachineDominators.h" 25 #include "llvm/CodeGen/MachineFunctionAnalysis.h" 26 #include "llvm/CodeGen/MachineFunctionPass.h" 27 #include "llvm/CodeGen/MachineLoopInfo.h" 28 #include "llvm/CodeGen/MachineRegisterInfo.h" 29 #include "llvm/CodeGen/Passes.h" 30 #include "llvm/Support/CommandLine.h" 31 #include "llvm/Support/Debug.h" 32 33 using namespace llvm; 34 35 #define DEBUG_TYPE "packets" 36 37 static cl::opt<bool> DisablePacketizer("disable-packetizer", cl::Hidden, 38 cl::ZeroOrMore, cl::init(false), 39 cl::desc("Disable Hexagon packetizer pass")); 40 41 static cl::opt<bool> PacketizeVolatiles("hexagon-packetize-volatiles", 42 cl::ZeroOrMore, cl::Hidden, cl::init(true), 43 cl::desc("Allow non-solo packetization of volatile memory references")); 44 45 static cl::opt<bool> EnableGenAllInsnClass("enable-gen-insn", cl::init(false), 46 cl::Hidden, cl::ZeroOrMore, cl::desc("Generate all instruction with TC")); 47 48 static cl::opt<bool> DisableVecDblNVStores("disable-vecdbl-nv-stores", 49 cl::init(false), cl::Hidden, cl::ZeroOrMore, 50 cl::desc("Disable vector double new-value-stores")); 51 52 extern cl::opt<bool> ScheduleInlineAsm; 53 54 namespace llvm { 55 FunctionPass *createHexagonPacketizer(); 56 void initializeHexagonPacketizerPass(PassRegistry&); 57 } 58 59 60 namespace { 61 class HexagonPacketizer : public MachineFunctionPass { 62 public: 63 static char ID; 64 HexagonPacketizer() : MachineFunctionPass(ID) { 65 initializeHexagonPacketizerPass(*PassRegistry::getPassRegistry()); 66 } 67 68 void getAnalysisUsage(AnalysisUsage &AU) const override { 69 AU.setPreservesCFG(); 70 AU.addRequired<AAResultsWrapperPass>(); 71 AU.addRequired<MachineBranchProbabilityInfo>(); 72 AU.addRequired<MachineDominatorTree>(); 73 AU.addRequired<MachineLoopInfo>(); 74 AU.addPreserved<MachineDominatorTree>(); 75 AU.addPreserved<MachineLoopInfo>(); 76 MachineFunctionPass::getAnalysisUsage(AU); 77 } 78 const char *getPassName() const override { 79 return "Hexagon Packetizer"; 80 } 81 bool runOnMachineFunction(MachineFunction &Fn) override; 82 MachineFunctionProperties getRequiredProperties() const override { 83 return MachineFunctionProperties().set( 84 MachineFunctionProperties::Property::AllVRegsAllocated); 85 } 86 87 private: 88 const HexagonInstrInfo *HII; 89 const HexagonRegisterInfo *HRI; 90 }; 91 92 char HexagonPacketizer::ID = 0; 93 } 94 95 INITIALIZE_PASS_BEGIN(HexagonPacketizer, "packets", "Hexagon Packetizer", 96 false, false) 97 INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree) 98 INITIALIZE_PASS_DEPENDENCY(MachineBranchProbabilityInfo) 99 INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo) 100 INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass) 101 INITIALIZE_PASS_END(HexagonPacketizer, "packets", "Hexagon Packetizer", 102 false, false) 103 104 105 HexagonPacketizerList::HexagonPacketizerList(MachineFunction &MF, 106 MachineLoopInfo &MLI, AliasAnalysis *AA, 107 const MachineBranchProbabilityInfo *MBPI) 108 : VLIWPacketizerList(MF, MLI, AA), MBPI(MBPI), MLI(&MLI) { 109 HII = MF.getSubtarget<HexagonSubtarget>().getInstrInfo(); 110 HRI = MF.getSubtarget<HexagonSubtarget>().getRegisterInfo(); 111 } 112 113 // Check if FirstI modifies a register that SecondI reads. 114 static bool hasWriteToReadDep(const MachineInstr *FirstI, 115 const MachineInstr *SecondI, const TargetRegisterInfo *TRI) { 116 for (auto &MO : FirstI->operands()) { 117 if (!MO.isReg() || !MO.isDef()) 118 continue; 119 unsigned R = MO.getReg(); 120 if (SecondI->readsRegister(R, TRI)) 121 return true; 122 } 123 return false; 124 } 125 126 127 static MachineBasicBlock::iterator moveInstrOut(MachineInstr *MI, 128 MachineBasicBlock::iterator BundleIt, bool Before) { 129 MachineBasicBlock::instr_iterator InsertPt; 130 if (Before) 131 InsertPt = BundleIt.getInstrIterator(); 132 else 133 InsertPt = std::next(BundleIt).getInstrIterator(); 134 135 MachineBasicBlock &B = *MI->getParent(); 136 // The instruction should at least be bundled with the preceding instruction 137 // (there will always be one, i.e. BUNDLE, if nothing else). 138 assert(MI->isBundledWithPred()); 139 if (MI->isBundledWithSucc()) { 140 MI->clearFlag(MachineInstr::BundledSucc); 141 MI->clearFlag(MachineInstr::BundledPred); 142 } else { 143 // If it's not bundled with the successor (i.e. it is the last one 144 // in the bundle), then we can simply unbundle it from the predecessor, 145 // which will take care of updating the predecessor's flag. 146 MI->unbundleFromPred(); 147 } 148 B.splice(InsertPt, &B, MI); 149 150 // Get the size of the bundle without asserting. 151 MachineBasicBlock::const_instr_iterator I(BundleIt); 152 MachineBasicBlock::const_instr_iterator E = B.instr_end(); 153 unsigned Size = 0; 154 for (++I; I != E && I->isBundledWithPred(); ++I) 155 ++Size; 156 157 // If there are still two or more instructions, then there is nothing 158 // else to be done. 159 if (Size > 1) 160 return BundleIt; 161 162 // Otherwise, extract the single instruction out and delete the bundle. 163 MachineBasicBlock::iterator NextIt = std::next(BundleIt); 164 MachineInstr *SingleI = BundleIt->getNextNode(); 165 SingleI->unbundleFromPred(); 166 assert(!SingleI->isBundledWithSucc()); 167 BundleIt->eraseFromParent(); 168 return NextIt; 169 } 170 171 172 bool HexagonPacketizer::runOnMachineFunction(MachineFunction &MF) { 173 if (DisablePacketizer || skipFunction(*MF.getFunction())) 174 return false; 175 176 HII = MF.getSubtarget<HexagonSubtarget>().getInstrInfo(); 177 HRI = MF.getSubtarget<HexagonSubtarget>().getRegisterInfo(); 178 auto &MLI = getAnalysis<MachineLoopInfo>(); 179 auto *AA = &getAnalysis<AAResultsWrapperPass>().getAAResults(); 180 auto *MBPI = &getAnalysis<MachineBranchProbabilityInfo>(); 181 182 if (EnableGenAllInsnClass) 183 HII->genAllInsnTimingClasses(MF); 184 185 // Instantiate the packetizer. 186 HexagonPacketizerList Packetizer(MF, MLI, AA, MBPI); 187 188 // DFA state table should not be empty. 189 assert(Packetizer.getResourceTracker() && "Empty DFA table!"); 190 191 // 192 // Loop over all basic blocks and remove KILL pseudo-instructions 193 // These instructions confuse the dependence analysis. Consider: 194 // D0 = ... (Insn 0) 195 // R0 = KILL R0, D0 (Insn 1) 196 // R0 = ... (Insn 2) 197 // Here, Insn 1 will result in the dependence graph not emitting an output 198 // dependence between Insn 0 and Insn 2. This can lead to incorrect 199 // packetization 200 // 201 for (auto &MB : MF) { 202 auto End = MB.end(); 203 auto MI = MB.begin(); 204 while (MI != End) { 205 auto NextI = std::next(MI); 206 if (MI->isKill()) { 207 MB.erase(MI); 208 End = MB.end(); 209 } 210 MI = NextI; 211 } 212 } 213 214 // Loop over all of the basic blocks. 215 for (auto &MB : MF) { 216 auto Begin = MB.begin(), End = MB.end(); 217 while (Begin != End) { 218 // First the first non-boundary starting from the end of the last 219 // scheduling region. 220 MachineBasicBlock::iterator RB = Begin; 221 while (RB != End && HII->isSchedulingBoundary(RB, &MB, MF)) 222 ++RB; 223 // First the first boundary starting from the beginning of the new 224 // region. 225 MachineBasicBlock::iterator RE = RB; 226 while (RE != End && !HII->isSchedulingBoundary(RE, &MB, MF)) 227 ++RE; 228 // Add the scheduling boundary if it's not block end. 229 if (RE != End) 230 ++RE; 231 // If RB == End, then RE == End. 232 if (RB != End) 233 Packetizer.PacketizeMIs(&MB, RB, RE); 234 235 Begin = RE; 236 } 237 } 238 239 Packetizer.unpacketizeSoloInstrs(MF); 240 return true; 241 } 242 243 244 // Reserve resources for a constant extender. Trigger an assertion if the 245 // reservation fails. 246 void HexagonPacketizerList::reserveResourcesForConstExt() { 247 if (!tryAllocateResourcesForConstExt(true)) 248 llvm_unreachable("Resources not available"); 249 } 250 251 bool HexagonPacketizerList::canReserveResourcesForConstExt() { 252 return tryAllocateResourcesForConstExt(false); 253 } 254 255 // Allocate resources (i.e. 4 bytes) for constant extender. If succeeded, 256 // return true, otherwise, return false. 257 bool HexagonPacketizerList::tryAllocateResourcesForConstExt(bool Reserve) { 258 auto *ExtMI = MF.CreateMachineInstr(HII->get(Hexagon::A4_ext), DebugLoc()); 259 bool Avail = ResourceTracker->canReserveResources(*ExtMI); 260 if (Reserve && Avail) 261 ResourceTracker->reserveResources(*ExtMI); 262 MF.DeleteMachineInstr(ExtMI); 263 return Avail; 264 } 265 266 267 bool HexagonPacketizerList::isCallDependent(const MachineInstr* MI, 268 SDep::Kind DepType, unsigned DepReg) { 269 // Check for LR dependence. 270 if (DepReg == HRI->getRARegister()) 271 return true; 272 273 if (HII->isDeallocRet(MI)) 274 if (DepReg == HRI->getFrameRegister() || DepReg == HRI->getStackRegister()) 275 return true; 276 277 // Check if this is a predicate dependence. 278 const TargetRegisterClass* RC = HRI->getMinimalPhysRegClass(DepReg); 279 if (RC == &Hexagon::PredRegsRegClass) 280 return true; 281 282 // Assumes that the first operand of the CALLr is the function address. 283 if (HII->isIndirectCall(MI) && (DepType == SDep::Data)) { 284 MachineOperand MO = MI->getOperand(0); 285 if (MO.isReg() && MO.isUse() && (MO.getReg() == DepReg)) 286 return true; 287 } 288 289 return false; 290 } 291 292 static bool isRegDependence(const SDep::Kind DepType) { 293 return DepType == SDep::Data || DepType == SDep::Anti || 294 DepType == SDep::Output; 295 } 296 297 static bool isDirectJump(const MachineInstr* MI) { 298 return MI->getOpcode() == Hexagon::J2_jump; 299 } 300 301 static bool isSchedBarrier(const MachineInstr* MI) { 302 switch (MI->getOpcode()) { 303 case Hexagon::Y2_barrier: 304 return true; 305 } 306 return false; 307 } 308 309 static bool isControlFlow(const MachineInstr* MI) { 310 return (MI->getDesc().isTerminator() || MI->getDesc().isCall()); 311 } 312 313 314 /// Returns true if the instruction modifies a callee-saved register. 315 static bool doesModifyCalleeSavedReg(const MachineInstr *MI, 316 const TargetRegisterInfo *TRI) { 317 const MachineFunction &MF = *MI->getParent()->getParent(); 318 for (auto *CSR = TRI->getCalleeSavedRegs(&MF); CSR && *CSR; ++CSR) 319 if (MI->modifiesRegister(*CSR, TRI)) 320 return true; 321 return false; 322 } 323 324 // TODO: MI->isIndirectBranch() and IsRegisterJump(MI) 325 // Returns true if an instruction can be promoted to .new predicate or 326 // new-value store. 327 bool HexagonPacketizerList::isNewifiable(const MachineInstr* MI) { 328 return HII->isCondInst(MI) || MI->isReturn() || HII->mayBeNewStore(MI); 329 } 330 331 // Promote an instructiont to its .cur form. 332 // At this time, we have already made a call to canPromoteToDotCur and made 333 // sure that it can *indeed* be promoted. 334 bool HexagonPacketizerList::promoteToDotCur(MachineInstr* MI, 335 SDep::Kind DepType, MachineBasicBlock::iterator &MII, 336 const TargetRegisterClass* RC) { 337 assert(DepType == SDep::Data); 338 int CurOpcode = HII->getDotCurOp(MI); 339 MI->setDesc(HII->get(CurOpcode)); 340 return true; 341 } 342 343 void HexagonPacketizerList::cleanUpDotCur() { 344 MachineInstr *MI = NULL; 345 for (auto BI : CurrentPacketMIs) { 346 DEBUG(dbgs() << "Cleanup packet has "; BI->dump();); 347 if (BI->getOpcode() == Hexagon::V6_vL32b_cur_ai) { 348 MI = BI; 349 continue; 350 } 351 if (MI) { 352 for (auto &MO : BI->operands()) 353 if (MO.isReg() && MO.getReg() == MI->getOperand(0).getReg()) 354 return; 355 } 356 } 357 if (!MI) 358 return; 359 // We did not find a use of the CUR, so de-cur it. 360 MI->setDesc(HII->get(Hexagon::V6_vL32b_ai)); 361 DEBUG(dbgs() << "Demoted CUR "; MI->dump();); 362 } 363 364 // Check to see if an instruction can be dot cur. 365 bool HexagonPacketizerList::canPromoteToDotCur(const MachineInstr *MI, 366 const SUnit *PacketSU, unsigned DepReg, MachineBasicBlock::iterator &MII, 367 const TargetRegisterClass *RC) { 368 if (!HII->isV60VectorInstruction(MI)) 369 return false; 370 if (!HII->isV60VectorInstruction(MII)) 371 return false; 372 373 // Already a dot new instruction. 374 if (HII->isDotCurInst(MI) && !HII->mayBeCurLoad(MI)) 375 return false; 376 377 if (!HII->mayBeCurLoad(MI)) 378 return false; 379 380 // The "cur value" cannot come from inline asm. 381 if (PacketSU->getInstr()->isInlineAsm()) 382 return false; 383 384 // Make sure candidate instruction uses cur. 385 DEBUG(dbgs() << "Can we DOT Cur Vector MI\n"; 386 MI->dump(); 387 dbgs() << "in packet\n";); 388 MachineInstr *MJ = MII; 389 DEBUG(dbgs() << "Checking CUR against "; MJ->dump();); 390 unsigned DestReg = MI->getOperand(0).getReg(); 391 bool FoundMatch = false; 392 for (auto &MO : MJ->operands()) 393 if (MO.isReg() && MO.getReg() == DestReg) 394 FoundMatch = true; 395 if (!FoundMatch) 396 return false; 397 398 // Check for existing uses of a vector register within the packet which 399 // would be affected by converting a vector load into .cur formt. 400 for (auto BI : CurrentPacketMIs) { 401 DEBUG(dbgs() << "packet has "; BI->dump();); 402 if (BI->readsRegister(DepReg, MF.getSubtarget().getRegisterInfo())) 403 return false; 404 } 405 406 DEBUG(dbgs() << "Can Dot CUR MI\n"; MI->dump();); 407 // We can convert the opcode into a .cur. 408 return true; 409 } 410 411 // Promote an instruction to its .new form. At this time, we have already 412 // made a call to canPromoteToDotNew and made sure that it can *indeed* be 413 // promoted. 414 bool HexagonPacketizerList::promoteToDotNew(MachineInstr* MI, 415 SDep::Kind DepType, MachineBasicBlock::iterator &MII, 416 const TargetRegisterClass* RC) { 417 assert (DepType == SDep::Data); 418 int NewOpcode; 419 if (RC == &Hexagon::PredRegsRegClass) 420 NewOpcode = HII->getDotNewPredOp(MI, MBPI); 421 else 422 NewOpcode = HII->getDotNewOp(MI); 423 MI->setDesc(HII->get(NewOpcode)); 424 return true; 425 } 426 427 bool HexagonPacketizerList::demoteToDotOld(MachineInstr* MI) { 428 int NewOpcode = HII->getDotOldOp(MI->getOpcode()); 429 MI->setDesc(HII->get(NewOpcode)); 430 return true; 431 } 432 433 enum PredicateKind { 434 PK_False, 435 PK_True, 436 PK_Unknown 437 }; 438 439 /// Returns true if an instruction is predicated on p0 and false if it's 440 /// predicated on !p0. 441 static PredicateKind getPredicateSense(const MachineInstr &MI, 442 const HexagonInstrInfo *HII) { 443 if (!HII->isPredicated(MI)) 444 return PK_Unknown; 445 if (HII->isPredicatedTrue(MI)) 446 return PK_True; 447 return PK_False; 448 } 449 450 static const MachineOperand &getPostIncrementOperand(const MachineInstr *MI, 451 const HexagonInstrInfo *HII) { 452 assert(HII->isPostIncrement(MI) && "Not a post increment operation."); 453 #ifndef NDEBUG 454 // Post Increment means duplicates. Use dense map to find duplicates in the 455 // list. Caution: Densemap initializes with the minimum of 64 buckets, 456 // whereas there are at most 5 operands in the post increment. 457 DenseSet<unsigned> DefRegsSet; 458 for (auto &MO : MI->operands()) 459 if (MO.isReg() && MO.isDef()) 460 DefRegsSet.insert(MO.getReg()); 461 462 for (auto &MO : MI->operands()) 463 if (MO.isReg() && MO.isUse() && DefRegsSet.count(MO.getReg())) 464 return MO; 465 #else 466 if (MI->mayLoad()) { 467 const MachineOperand &Op1 = MI->getOperand(1); 468 // The 2nd operand is always the post increment operand in load. 469 assert(Op1.isReg() && "Post increment operand has be to a register."); 470 return Op1; 471 } 472 if (MI->getDesc().mayStore()) { 473 const MachineOperand &Op0 = MI->getOperand(0); 474 // The 1st operand is always the post increment operand in store. 475 assert(Op0.isReg() && "Post increment operand has be to a register."); 476 return Op0; 477 } 478 #endif 479 // we should never come here. 480 llvm_unreachable("mayLoad or mayStore not set for Post Increment operation"); 481 } 482 483 // Get the value being stored. 484 static const MachineOperand& getStoreValueOperand(const MachineInstr *MI) { 485 // value being stored is always the last operand. 486 return MI->getOperand(MI->getNumOperands()-1); 487 } 488 489 static bool isLoadAbsSet(const MachineInstr *MI) { 490 unsigned Opc = MI->getOpcode(); 491 switch (Opc) { 492 case Hexagon::L4_loadrd_ap: 493 case Hexagon::L4_loadrb_ap: 494 case Hexagon::L4_loadrh_ap: 495 case Hexagon::L4_loadrub_ap: 496 case Hexagon::L4_loadruh_ap: 497 case Hexagon::L4_loadri_ap: 498 return true; 499 } 500 return false; 501 } 502 503 static const MachineOperand &getAbsSetOperand(const MachineInstr *MI) { 504 assert(isLoadAbsSet(MI)); 505 return MI->getOperand(1); 506 } 507 508 509 // Can be new value store? 510 // Following restrictions are to be respected in convert a store into 511 // a new value store. 512 // 1. If an instruction uses auto-increment, its address register cannot 513 // be a new-value register. Arch Spec 5.4.2.1 514 // 2. If an instruction uses absolute-set addressing mode, its address 515 // register cannot be a new-value register. Arch Spec 5.4.2.1. 516 // 3. If an instruction produces a 64-bit result, its registers cannot be used 517 // as new-value registers. Arch Spec 5.4.2.2. 518 // 4. If the instruction that sets the new-value register is conditional, then 519 // the instruction that uses the new-value register must also be conditional, 520 // and both must always have their predicates evaluate identically. 521 // Arch Spec 5.4.2.3. 522 // 5. There is an implied restriction that a packet cannot have another store, 523 // if there is a new value store in the packet. Corollary: if there is 524 // already a store in a packet, there can not be a new value store. 525 // Arch Spec: 3.4.4.2 526 bool HexagonPacketizerList::canPromoteToNewValueStore(const MachineInstr *MI, 527 const MachineInstr *PacketMI, unsigned DepReg) { 528 // Make sure we are looking at the store, that can be promoted. 529 if (!HII->mayBeNewStore(MI)) 530 return false; 531 532 // Make sure there is dependency and can be new value'd. 533 const MachineOperand &Val = getStoreValueOperand(MI); 534 if (Val.isReg() && Val.getReg() != DepReg) 535 return false; 536 537 const MCInstrDesc& MCID = PacketMI->getDesc(); 538 539 // First operand is always the result. 540 const TargetRegisterClass *PacketRC = HII->getRegClass(MCID, 0, HRI, MF); 541 // Double regs can not feed into new value store: PRM section: 5.4.2.2. 542 if (PacketRC == &Hexagon::DoubleRegsRegClass) 543 return false; 544 545 // New-value stores are of class NV (slot 0), dual stores require class ST 546 // in slot 0 (PRM 5.5). 547 for (auto I : CurrentPacketMIs) { 548 SUnit *PacketSU = MIToSUnit.find(I)->second; 549 if (PacketSU->getInstr()->mayStore()) 550 return false; 551 } 552 553 // Make sure it's NOT the post increment register that we are going to 554 // new value. 555 if (HII->isPostIncrement(MI) && 556 getPostIncrementOperand(MI, HII).getReg() == DepReg) { 557 return false; 558 } 559 560 if (HII->isPostIncrement(PacketMI) && PacketMI->mayLoad() && 561 getPostIncrementOperand(PacketMI, HII).getReg() == DepReg) { 562 // If source is post_inc, or absolute-set addressing, it can not feed 563 // into new value store 564 // r3 = memw(r2++#4) 565 // memw(r30 + #-1404) = r2.new -> can not be new value store 566 // arch spec section: 5.4.2.1. 567 return false; 568 } 569 570 if (isLoadAbsSet(PacketMI) && getAbsSetOperand(PacketMI).getReg() == DepReg) 571 return false; 572 573 // If the source that feeds the store is predicated, new value store must 574 // also be predicated. 575 if (HII->isPredicated(*PacketMI)) { 576 if (!HII->isPredicated(*MI)) 577 return false; 578 579 // Check to make sure that they both will have their predicates 580 // evaluate identically. 581 unsigned predRegNumSrc = 0; 582 unsigned predRegNumDst = 0; 583 const TargetRegisterClass* predRegClass = nullptr; 584 585 // Get predicate register used in the source instruction. 586 for (auto &MO : PacketMI->operands()) { 587 if (!MO.isReg()) 588 continue; 589 predRegNumSrc = MO.getReg(); 590 predRegClass = HRI->getMinimalPhysRegClass(predRegNumSrc); 591 if (predRegClass == &Hexagon::PredRegsRegClass) 592 break; 593 } 594 assert((predRegClass == &Hexagon::PredRegsRegClass) && 595 "predicate register not found in a predicated PacketMI instruction"); 596 597 // Get predicate register used in new-value store instruction. 598 for (auto &MO : MI->operands()) { 599 if (!MO.isReg()) 600 continue; 601 predRegNumDst = MO.getReg(); 602 predRegClass = HRI->getMinimalPhysRegClass(predRegNumDst); 603 if (predRegClass == &Hexagon::PredRegsRegClass) 604 break; 605 } 606 assert((predRegClass == &Hexagon::PredRegsRegClass) && 607 "predicate register not found in a predicated MI instruction"); 608 609 // New-value register producer and user (store) need to satisfy these 610 // constraints: 611 // 1) Both instructions should be predicated on the same register. 612 // 2) If producer of the new-value register is .new predicated then store 613 // should also be .new predicated and if producer is not .new predicated 614 // then store should not be .new predicated. 615 // 3) Both new-value register producer and user should have same predicate 616 // sense, i.e, either both should be negated or both should be non-negated. 617 if (predRegNumDst != predRegNumSrc || 618 HII->isDotNewInst(PacketMI) != HII->isDotNewInst(MI) || 619 getPredicateSense(*MI, HII) != getPredicateSense(*PacketMI, HII)) 620 return false; 621 } 622 623 // Make sure that other than the new-value register no other store instruction 624 // register has been modified in the same packet. Predicate registers can be 625 // modified by they should not be modified between the producer and the store 626 // instruction as it will make them both conditional on different values. 627 // We already know this to be true for all the instructions before and 628 // including PacketMI. Howerver, we need to perform the check for the 629 // remaining instructions in the packet. 630 631 unsigned StartCheck = 0; 632 633 for (auto I : CurrentPacketMIs) { 634 SUnit *TempSU = MIToSUnit.find(I)->second; 635 MachineInstr* TempMI = TempSU->getInstr(); 636 637 // Following condition is true for all the instructions until PacketMI is 638 // reached (StartCheck is set to 0 before the for loop). 639 // StartCheck flag is 1 for all the instructions after PacketMI. 640 if (TempMI != PacketMI && !StartCheck) // Start processing only after 641 continue; // encountering PacketMI. 642 643 StartCheck = 1; 644 if (TempMI == PacketMI) // We don't want to check PacketMI for dependence. 645 continue; 646 647 for (auto &MO : MI->operands()) 648 if (MO.isReg() && TempSU->getInstr()->modifiesRegister(MO.getReg(), HRI)) 649 return false; 650 } 651 652 // Make sure that for non-POST_INC stores: 653 // 1. The only use of reg is DepReg and no other registers. 654 // This handles V4 base+index registers. 655 // The following store can not be dot new. 656 // Eg. r0 = add(r0, #3) 657 // memw(r1+r0<<#2) = r0 658 if (!HII->isPostIncrement(MI)) { 659 for (unsigned opNum = 0; opNum < MI->getNumOperands()-1; opNum++) { 660 const MachineOperand &MO = MI->getOperand(opNum); 661 if (MO.isReg() && MO.getReg() == DepReg) 662 return false; 663 } 664 } 665 666 // If data definition is because of implicit definition of the register, 667 // do not newify the store. Eg. 668 // %R9<def> = ZXTH %R12, %D6<imp-use>, %R12<imp-def> 669 // S2_storerh_io %R8, 2, %R12<kill>; mem:ST2[%scevgep343] 670 for (auto &MO : PacketMI->operands()) { 671 if (!MO.isReg() || !MO.isDef() || !MO.isImplicit()) 672 continue; 673 unsigned R = MO.getReg(); 674 if (R == DepReg || HRI->isSuperRegister(DepReg, R)) 675 return false; 676 } 677 678 // Handle imp-use of super reg case. There is a target independent side 679 // change that should prevent this situation but I am handling it for 680 // just-in-case. For example, we cannot newify R2 in the following case: 681 // %R3<def> = A2_tfrsi 0; 682 // S2_storeri_io %R0<kill>, 0, %R2<kill>, %D1<imp-use,kill>; 683 for (auto &MO : MI->operands()) { 684 if (MO.isReg() && MO.isUse() && MO.isImplicit() && MO.getReg() == DepReg) 685 return false; 686 } 687 688 // Can be dot new store. 689 return true; 690 } 691 692 // Can this MI to promoted to either new value store or new value jump. 693 bool HexagonPacketizerList::canPromoteToNewValue(const MachineInstr *MI, 694 const SUnit *PacketSU, unsigned DepReg, 695 MachineBasicBlock::iterator &MII) { 696 if (!HII->mayBeNewStore(MI)) 697 return false; 698 699 // Check to see the store can be new value'ed. 700 MachineInstr *PacketMI = PacketSU->getInstr(); 701 if (canPromoteToNewValueStore(MI, PacketMI, DepReg)) 702 return true; 703 704 // Check to see the compare/jump can be new value'ed. 705 // This is done as a pass on its own. Don't need to check it here. 706 return false; 707 } 708 709 static bool isImplicitDependency(const MachineInstr *I, unsigned DepReg) { 710 for (auto &MO : I->operands()) 711 if (MO.isReg() && MO.isDef() && (MO.getReg() == DepReg) && MO.isImplicit()) 712 return true; 713 return false; 714 } 715 716 // Check to see if an instruction can be dot new 717 // There are three kinds. 718 // 1. dot new on predicate - V2/V3/V4 719 // 2. dot new on stores NV/ST - V4 720 // 3. dot new on jump NV/J - V4 -- This is generated in a pass. 721 bool HexagonPacketizerList::canPromoteToDotNew(const MachineInstr *MI, 722 const SUnit *PacketSU, unsigned DepReg, MachineBasicBlock::iterator &MII, 723 const TargetRegisterClass* RC) { 724 // Already a dot new instruction. 725 if (HII->isDotNewInst(MI) && !HII->mayBeNewStore(MI)) 726 return false; 727 728 if (!isNewifiable(MI)) 729 return false; 730 731 const MachineInstr *PI = PacketSU->getInstr(); 732 733 // The "new value" cannot come from inline asm. 734 if (PI->isInlineAsm()) 735 return false; 736 737 // IMPLICIT_DEFs won't materialize as real instructions, so .new makes no 738 // sense. 739 if (PI->isImplicitDef()) 740 return false; 741 742 // If dependency is trough an implicitly defined register, we should not 743 // newify the use. 744 if (isImplicitDependency(PI, DepReg)) 745 return false; 746 747 const MCInstrDesc& MCID = PI->getDesc(); 748 const TargetRegisterClass *VecRC = HII->getRegClass(MCID, 0, HRI, MF); 749 if (DisableVecDblNVStores && VecRC == &Hexagon::VecDblRegsRegClass) 750 return false; 751 752 // predicate .new 753 // bug 5670: until that is fixed 754 // TODO: MI->isIndirectBranch() and IsRegisterJump(MI) 755 if (RC == &Hexagon::PredRegsRegClass) 756 if (HII->isCondInst(MI) || MI->isReturn()) 757 return HII->predCanBeUsedAsDotNew(PI, DepReg); 758 759 if (RC != &Hexagon::PredRegsRegClass && !HII->mayBeNewStore(MI)) 760 return false; 761 762 // Create a dot new machine instruction to see if resources can be 763 // allocated. If not, bail out now. 764 int NewOpcode = HII->getDotNewOp(MI); 765 const MCInstrDesc &D = HII->get(NewOpcode); 766 MachineInstr *NewMI = MF.CreateMachineInstr(D, DebugLoc()); 767 bool ResourcesAvailable = ResourceTracker->canReserveResources(*NewMI); 768 MF.DeleteMachineInstr(NewMI); 769 if (!ResourcesAvailable) 770 return false; 771 772 // New Value Store only. New Value Jump generated as a separate pass. 773 if (!canPromoteToNewValue(MI, PacketSU, DepReg, MII)) 774 return false; 775 776 return true; 777 } 778 779 // Go through the packet instructions and search for an anti dependency between 780 // them and DepReg from MI. Consider this case: 781 // Trying to add 782 // a) %R1<def> = TFRI_cdNotPt %P3, 2 783 // to this packet: 784 // { 785 // b) %P0<def> = C2_or %P3<kill>, %P0<kill> 786 // c) %P3<def> = C2_tfrrp %R23 787 // d) %R1<def> = C2_cmovenewit %P3, 4 788 // } 789 // The P3 from a) and d) will be complements after 790 // a)'s P3 is converted to .new form 791 // Anti-dep between c) and b) is irrelevant for this case 792 bool HexagonPacketizerList::restrictingDepExistInPacket(MachineInstr* MI, 793 unsigned DepReg) { 794 SUnit *PacketSUDep = MIToSUnit.find(MI)->second; 795 796 for (auto I : CurrentPacketMIs) { 797 // We only care for dependencies to predicated instructions 798 if (!HII->isPredicated(*I)) 799 continue; 800 801 // Scheduling Unit for current insn in the packet 802 SUnit *PacketSU = MIToSUnit.find(I)->second; 803 804 // Look at dependencies between current members of the packet and 805 // predicate defining instruction MI. Make sure that dependency is 806 // on the exact register we care about. 807 if (PacketSU->isSucc(PacketSUDep)) { 808 for (unsigned i = 0; i < PacketSU->Succs.size(); ++i) { 809 auto &Dep = PacketSU->Succs[i]; 810 if (Dep.getSUnit() == PacketSUDep && Dep.getKind() == SDep::Anti && 811 Dep.getReg() == DepReg) 812 return true; 813 } 814 } 815 } 816 817 return false; 818 } 819 820 821 /// Gets the predicate register of a predicated instruction. 822 static unsigned getPredicatedRegister(MachineInstr &MI, 823 const HexagonInstrInfo *QII) { 824 /// We use the following rule: The first predicate register that is a use is 825 /// the predicate register of a predicated instruction. 826 assert(QII->isPredicated(MI) && "Must be predicated instruction"); 827 828 for (auto &Op : MI.operands()) { 829 if (Op.isReg() && Op.getReg() && Op.isUse() && 830 Hexagon::PredRegsRegClass.contains(Op.getReg())) 831 return Op.getReg(); 832 } 833 834 llvm_unreachable("Unknown instruction operand layout"); 835 return 0; 836 } 837 838 // Given two predicated instructions, this function detects whether 839 // the predicates are complements. 840 bool HexagonPacketizerList::arePredicatesComplements(MachineInstr &MI1, 841 MachineInstr &MI2) { 842 // If we don't know the predicate sense of the instructions bail out early, we 843 // need it later. 844 if (getPredicateSense(MI1, HII) == PK_Unknown || 845 getPredicateSense(MI2, HII) == PK_Unknown) 846 return false; 847 848 // Scheduling unit for candidate. 849 SUnit *SU = MIToSUnit[&MI1]; 850 851 // One corner case deals with the following scenario: 852 // Trying to add 853 // a) %R24<def> = A2_tfrt %P0, %R25 854 // to this packet: 855 // { 856 // b) %R25<def> = A2_tfrf %P0, %R24 857 // c) %P0<def> = C2_cmpeqi %R26, 1 858 // } 859 // 860 // On general check a) and b) are complements, but presence of c) will 861 // convert a) to .new form, and then it is not a complement. 862 // We attempt to detect it by analyzing existing dependencies in the packet. 863 864 // Analyze relationships between all existing members of the packet. 865 // Look for Anti dependecy on the same predicate reg as used in the 866 // candidate. 867 for (auto I : CurrentPacketMIs) { 868 // Scheduling Unit for current insn in the packet. 869 SUnit *PacketSU = MIToSUnit.find(I)->second; 870 871 // If this instruction in the packet is succeeded by the candidate... 872 if (PacketSU->isSucc(SU)) { 873 for (unsigned i = 0; i < PacketSU->Succs.size(); ++i) { 874 auto Dep = PacketSU->Succs[i]; 875 // The corner case exist when there is true data dependency between 876 // candidate and one of current packet members, this dep is on 877 // predicate reg, and there already exist anti dep on the same pred in 878 // the packet. 879 if (Dep.getSUnit() == SU && Dep.getKind() == SDep::Data && 880 Hexagon::PredRegsRegClass.contains(Dep.getReg())) { 881 // Here I know that I is predicate setting instruction with true 882 // data dep to candidate on the register we care about - c) in the 883 // above example. Now I need to see if there is an anti dependency 884 // from c) to any other instruction in the same packet on the pred 885 // reg of interest. 886 if (restrictingDepExistInPacket(I, Dep.getReg())) 887 return false; 888 } 889 } 890 } 891 } 892 893 // If the above case does not apply, check regular complement condition. 894 // Check that the predicate register is the same and that the predicate 895 // sense is different We also need to differentiate .old vs. .new: !p0 896 // is not complementary to p0.new. 897 unsigned PReg1 = getPredicatedRegister(MI1, HII); 898 unsigned PReg2 = getPredicatedRegister(MI2, HII); 899 return PReg1 == PReg2 && 900 Hexagon::PredRegsRegClass.contains(PReg1) && 901 Hexagon::PredRegsRegClass.contains(PReg2) && 902 getPredicateSense(MI1, HII) != getPredicateSense(MI2, HII) && 903 HII->isDotNewInst(&MI1) == HII->isDotNewInst(&MI2); 904 } 905 906 // Initialize packetizer flags. 907 void HexagonPacketizerList::initPacketizerState() { 908 Dependence = false; 909 PromotedToDotNew = false; 910 GlueToNewValueJump = false; 911 GlueAllocframeStore = false; 912 FoundSequentialDependence = false; 913 } 914 915 // Ignore bundling of pseudo instructions. 916 bool HexagonPacketizerList::ignorePseudoInstruction(const MachineInstr &MI, 917 const MachineBasicBlock *) { 918 if (MI.isDebugValue()) 919 return true; 920 921 if (MI.isCFIInstruction()) 922 return false; 923 924 // We must print out inline assembly. 925 if (MI.isInlineAsm()) 926 return false; 927 928 if (MI.isImplicitDef()) 929 return false; 930 931 // We check if MI has any functional units mapped to it. If it doesn't, 932 // we ignore the instruction. 933 const MCInstrDesc& TID = MI.getDesc(); 934 auto *IS = ResourceTracker->getInstrItins()->beginStage(TID.getSchedClass()); 935 unsigned FuncUnits = IS->getUnits(); 936 return !FuncUnits; 937 } 938 939 bool HexagonPacketizerList::isSoloInstruction(const MachineInstr &MI) { 940 if (MI.isEHLabel() || MI.isCFIInstruction()) 941 return true; 942 943 // Consider inline asm to not be a solo instruction by default. 944 // Inline asm will be put in a packet temporarily, but then it will be 945 // removed, and placed outside of the packet (before or after, depending 946 // on dependencies). This is to reduce the impact of inline asm as a 947 // "packet splitting" instruction. 948 if (MI.isInlineAsm() && !ScheduleInlineAsm) 949 return true; 950 951 // From Hexagon V4 Programmer's Reference Manual 3.4.4 Grouping constraints: 952 // trap, pause, barrier, icinva, isync, and syncht are solo instructions. 953 // They must not be grouped with other instructions in a packet. 954 if (isSchedBarrier(&MI)) 955 return true; 956 957 if (HII->isSolo(&MI)) 958 return true; 959 960 if (MI.getOpcode() == Hexagon::A2_nop) 961 return true; 962 963 return false; 964 } 965 966 967 // Quick check if instructions MI and MJ cannot coexist in the same packet. 968 // Limit the tests to be "one-way", e.g. "if MI->isBranch and MJ->isInlineAsm", 969 // but not the symmetric case: "if MJ->isBranch and MI->isInlineAsm". 970 // For full test call this function twice: 971 // cannotCoexistAsymm(MI, MJ) || cannotCoexistAsymm(MJ, MI) 972 // Doing the test only one way saves the amount of code in this function, 973 // since every test would need to be repeated with the MI and MJ reversed. 974 static bool cannotCoexistAsymm(const MachineInstr *MI, const MachineInstr *MJ, 975 const HexagonInstrInfo &HII) { 976 const MachineFunction *MF = MI->getParent()->getParent(); 977 if (MF->getSubtarget<HexagonSubtarget>().hasV60TOpsOnly() && 978 HII.isHVXMemWithAIndirect(MI, MJ)) 979 return true; 980 981 // An inline asm cannot be together with a branch, because we may not be 982 // able to remove the asm out after packetizing (i.e. if the asm must be 983 // moved past the bundle). Similarly, two asms cannot be together to avoid 984 // complications when determining their relative order outside of a bundle. 985 if (MI->isInlineAsm()) 986 return MJ->isInlineAsm() || MJ->isBranch() || MJ->isBarrier() || 987 MJ->isCall() || MJ->isTerminator(); 988 989 // "False" really means that the quick check failed to determine if 990 // I and J cannot coexist. 991 return false; 992 } 993 994 995 // Full, symmetric check. 996 bool HexagonPacketizerList::cannotCoexist(const MachineInstr *MI, 997 const MachineInstr *MJ) { 998 return cannotCoexistAsymm(MI, MJ, *HII) || cannotCoexistAsymm(MJ, MI, *HII); 999 } 1000 1001 void HexagonPacketizerList::unpacketizeSoloInstrs(MachineFunction &MF) { 1002 for (auto &B : MF) { 1003 MachineBasicBlock::iterator BundleIt; 1004 MachineBasicBlock::instr_iterator NextI; 1005 for (auto I = B.instr_begin(), E = B.instr_end(); I != E; I = NextI) { 1006 NextI = std::next(I); 1007 MachineInstr *MI = &*I; 1008 if (MI->isBundle()) 1009 BundleIt = I; 1010 if (!MI->isInsideBundle()) 1011 continue; 1012 1013 // Decide on where to insert the instruction that we are pulling out. 1014 // Debug instructions always go before the bundle, but the placement of 1015 // INLINE_ASM depends on potential dependencies. By default, try to 1016 // put it before the bundle, but if the asm writes to a register that 1017 // other instructions in the bundle read, then we need to place it 1018 // after the bundle (to preserve the bundle semantics). 1019 bool InsertBeforeBundle; 1020 if (MI->isInlineAsm()) 1021 InsertBeforeBundle = !hasWriteToReadDep(MI, BundleIt, HRI); 1022 else if (MI->isDebugValue()) 1023 InsertBeforeBundle = true; 1024 else 1025 continue; 1026 1027 BundleIt = moveInstrOut(MI, BundleIt, InsertBeforeBundle); 1028 } 1029 } 1030 } 1031 1032 // Check if a given instruction is of class "system". 1033 static bool isSystemInstr(const MachineInstr *MI) { 1034 unsigned Opc = MI->getOpcode(); 1035 switch (Opc) { 1036 case Hexagon::Y2_barrier: 1037 case Hexagon::Y2_dcfetchbo: 1038 return true; 1039 } 1040 return false; 1041 } 1042 1043 bool HexagonPacketizerList::hasDeadDependence(const MachineInstr *I, 1044 const MachineInstr *J) { 1045 // The dependence graph may not include edges between dead definitions, 1046 // so without extra checks, we could end up packetizing two instruction 1047 // defining the same (dead) register. 1048 if (I->isCall() || J->isCall()) 1049 return false; 1050 if (HII->isPredicated(*I) || HII->isPredicated(*J)) 1051 return false; 1052 1053 BitVector DeadDefs(Hexagon::NUM_TARGET_REGS); 1054 for (auto &MO : I->operands()) { 1055 if (!MO.isReg() || !MO.isDef() || !MO.isDead()) 1056 continue; 1057 DeadDefs[MO.getReg()] = true; 1058 } 1059 1060 for (auto &MO : J->operands()) { 1061 if (!MO.isReg() || !MO.isDef() || !MO.isDead()) 1062 continue; 1063 unsigned R = MO.getReg(); 1064 if (R != Hexagon::USR_OVF && DeadDefs[R]) 1065 return true; 1066 } 1067 return false; 1068 } 1069 1070 bool HexagonPacketizerList::hasControlDependence(const MachineInstr *I, 1071 const MachineInstr *J) { 1072 // A save callee-save register function call can only be in a packet 1073 // with instructions that don't write to the callee-save registers. 1074 if ((HII->isSaveCalleeSavedRegsCall(I) && 1075 doesModifyCalleeSavedReg(J, HRI)) || 1076 (HII->isSaveCalleeSavedRegsCall(J) && 1077 doesModifyCalleeSavedReg(I, HRI))) 1078 return true; 1079 1080 // Two control flow instructions cannot go in the same packet. 1081 if (isControlFlow(I) && isControlFlow(J)) 1082 return true; 1083 1084 // \ref-manual (7.3.4) A loop setup packet in loopN or spNloop0 cannot 1085 // contain a speculative indirect jump, 1086 // a new-value compare jump or a dealloc_return. 1087 auto isBadForLoopN = [this] (const MachineInstr *MI) -> bool { 1088 if (MI->isCall() || HII->isDeallocRet(MI) || HII->isNewValueJump(MI)) 1089 return true; 1090 if (HII->isPredicated(*MI) && HII->isPredicatedNew(*MI) && HII->isJumpR(MI)) 1091 return true; 1092 return false; 1093 }; 1094 1095 if (HII->isLoopN(I) && isBadForLoopN(J)) 1096 return true; 1097 if (HII->isLoopN(J) && isBadForLoopN(I)) 1098 return true; 1099 1100 // dealloc_return cannot appear in the same packet as a conditional or 1101 // unconditional jump. 1102 return HII->isDeallocRet(I) && 1103 (J->isBranch() || J->isCall() || J->isBarrier()); 1104 } 1105 1106 bool HexagonPacketizerList::hasV4SpecificDependence(const MachineInstr *I, 1107 const MachineInstr *J) { 1108 bool SysI = isSystemInstr(I), SysJ = isSystemInstr(J); 1109 bool StoreI = I->mayStore(), StoreJ = J->mayStore(); 1110 if ((SysI && StoreJ) || (SysJ && StoreI)) 1111 return true; 1112 1113 if (StoreI && StoreJ) { 1114 if (HII->isNewValueInst(J) || HII->isMemOp(J) || HII->isMemOp(I)) 1115 return true; 1116 } else { 1117 // A memop cannot be in the same packet with another memop or a store. 1118 // Two stores can be together, but here I and J cannot both be stores. 1119 bool MopStI = HII->isMemOp(I) || StoreI; 1120 bool MopStJ = HII->isMemOp(J) || StoreJ; 1121 if (MopStI && MopStJ) 1122 return true; 1123 } 1124 1125 return (StoreJ && HII->isDeallocRet(I)) || (StoreI && HII->isDeallocRet(J)); 1126 } 1127 1128 // SUI is the current instruction that is out side of the current packet. 1129 // SUJ is the current instruction inside the current packet against which that 1130 // SUI will be packetized. 1131 bool HexagonPacketizerList::isLegalToPacketizeTogether(SUnit *SUI, SUnit *SUJ) { 1132 MachineInstr *I = SUI->getInstr(); 1133 MachineInstr *J = SUJ->getInstr(); 1134 assert(I && J && "Unable to packetize null instruction!"); 1135 1136 // Clear IgnoreDepMIs when Packet starts. 1137 if (CurrentPacketMIs.size() == 1) 1138 IgnoreDepMIs.clear(); 1139 1140 MachineBasicBlock::iterator II = I; 1141 const unsigned FrameSize = MF.getFrameInfo()->getStackSize(); 1142 1143 // Solo instructions cannot go in the packet. 1144 assert(!isSoloInstruction(*I) && "Unexpected solo instr!"); 1145 1146 if (cannotCoexist(I, J)) 1147 return false; 1148 1149 Dependence = hasDeadDependence(I, J) || hasControlDependence(I, J); 1150 if (Dependence) 1151 return false; 1152 1153 // V4 allows dual stores. It does not allow second store, if the first 1154 // store is not in SLOT0. New value store, new value jump, dealloc_return 1155 // and memop always take SLOT0. Arch spec 3.4.4.2. 1156 Dependence = hasV4SpecificDependence(I, J); 1157 if (Dependence) 1158 return false; 1159 1160 // If an instruction feeds new value jump, glue it. 1161 MachineBasicBlock::iterator NextMII = I; 1162 ++NextMII; 1163 if (NextMII != I->getParent()->end() && HII->isNewValueJump(NextMII)) { 1164 MachineInstr *NextMI = NextMII; 1165 1166 bool secondRegMatch = false; 1167 const MachineOperand &NOp0 = NextMI->getOperand(0); 1168 const MachineOperand &NOp1 = NextMI->getOperand(1); 1169 1170 if (NOp1.isReg() && I->getOperand(0).getReg() == NOp1.getReg()) 1171 secondRegMatch = true; 1172 1173 for (auto I : CurrentPacketMIs) { 1174 SUnit *PacketSU = MIToSUnit.find(I)->second; 1175 MachineInstr *PI = PacketSU->getInstr(); 1176 // NVJ can not be part of the dual jump - Arch Spec: section 7.8. 1177 if (PI->isCall()) { 1178 Dependence = true; 1179 break; 1180 } 1181 // Validate: 1182 // 1. Packet does not have a store in it. 1183 // 2. If the first operand of the nvj is newified, and the second 1184 // operand is also a reg, it (second reg) is not defined in 1185 // the same packet. 1186 // 3. If the second operand of the nvj is newified, (which means 1187 // first operand is also a reg), first reg is not defined in 1188 // the same packet. 1189 if (PI->getOpcode() == Hexagon::S2_allocframe || PI->mayStore() || 1190 HII->isLoopN(PI)) { 1191 Dependence = true; 1192 break; 1193 } 1194 // Check #2/#3. 1195 const MachineOperand &OpR = secondRegMatch ? NOp0 : NOp1; 1196 if (OpR.isReg() && PI->modifiesRegister(OpR.getReg(), HRI)) { 1197 Dependence = true; 1198 break; 1199 } 1200 } 1201 1202 if (Dependence) 1203 return false; 1204 GlueToNewValueJump = true; 1205 } 1206 1207 // There no dependency between a prolog instruction and its successor. 1208 if (!SUJ->isSucc(SUI)) 1209 return true; 1210 1211 for (unsigned i = 0; i < SUJ->Succs.size(); ++i) { 1212 if (FoundSequentialDependence) 1213 break; 1214 1215 if (SUJ->Succs[i].getSUnit() != SUI) 1216 continue; 1217 1218 SDep::Kind DepType = SUJ->Succs[i].getKind(); 1219 // For direct calls: 1220 // Ignore register dependences for call instructions for packetization 1221 // purposes except for those due to r31 and predicate registers. 1222 // 1223 // For indirect calls: 1224 // Same as direct calls + check for true dependences to the register 1225 // used in the indirect call. 1226 // 1227 // We completely ignore Order dependences for call instructions. 1228 // 1229 // For returns: 1230 // Ignore register dependences for return instructions like jumpr, 1231 // dealloc return unless we have dependencies on the explicit uses 1232 // of the registers used by jumpr (like r31) or dealloc return 1233 // (like r29 or r30). 1234 // 1235 // TODO: Currently, jumpr is handling only return of r31. So, the 1236 // following logic (specificaly isCallDependent) is working fine. 1237 // We need to enable jumpr for register other than r31 and then, 1238 // we need to rework the last part, where it handles indirect call 1239 // of that (isCallDependent) function. Bug 6216 is opened for this. 1240 unsigned DepReg = 0; 1241 const TargetRegisterClass *RC = nullptr; 1242 if (DepType == SDep::Data) { 1243 DepReg = SUJ->Succs[i].getReg(); 1244 RC = HRI->getMinimalPhysRegClass(DepReg); 1245 } 1246 1247 if (I->isCall() || I->isReturn()) { 1248 if (!isRegDependence(DepType)) 1249 continue; 1250 if (!isCallDependent(I, DepType, SUJ->Succs[i].getReg())) 1251 continue; 1252 } 1253 1254 if (DepType == SDep::Data) { 1255 if (canPromoteToDotCur(J, SUJ, DepReg, II, RC)) 1256 if (promoteToDotCur(J, DepType, II, RC)) 1257 continue; 1258 } 1259 1260 // Data dpendence ok if we have load.cur. 1261 if (DepType == SDep::Data && HII->isDotCurInst(J)) { 1262 if (HII->isV60VectorInstruction(I)) 1263 continue; 1264 } 1265 1266 // For instructions that can be promoted to dot-new, try to promote. 1267 if (DepType == SDep::Data) { 1268 if (canPromoteToDotNew(I, SUJ, DepReg, II, RC)) { 1269 if (promoteToDotNew(I, DepType, II, RC)) { 1270 PromotedToDotNew = true; 1271 continue; 1272 } 1273 } 1274 if (HII->isNewValueJump(I)) 1275 continue; 1276 } 1277 1278 // For predicated instructions, if the predicates are complements then 1279 // there can be no dependence. 1280 if (HII->isPredicated(*I) && HII->isPredicated(*J) && 1281 arePredicatesComplements(*I, *J)) { 1282 // Not always safe to do this translation. 1283 // DAG Builder attempts to reduce dependence edges using transitive 1284 // nature of dependencies. Here is an example: 1285 // 1286 // r0 = tfr_pt ... (1) 1287 // r0 = tfr_pf ... (2) 1288 // r0 = tfr_pt ... (3) 1289 // 1290 // There will be an output dependence between (1)->(2) and (2)->(3). 1291 // However, there is no dependence edge between (1)->(3). This results 1292 // in all 3 instructions going in the same packet. We ignore dependce 1293 // only once to avoid this situation. 1294 auto Itr = std::find(IgnoreDepMIs.begin(), IgnoreDepMIs.end(), J); 1295 if (Itr != IgnoreDepMIs.end()) { 1296 Dependence = true; 1297 return false; 1298 } 1299 IgnoreDepMIs.push_back(I); 1300 continue; 1301 } 1302 1303 // Ignore Order dependences between unconditional direct branches 1304 // and non-control-flow instructions. 1305 if (isDirectJump(I) && !J->isBranch() && !J->isCall() && 1306 DepType == SDep::Order) 1307 continue; 1308 1309 // Ignore all dependences for jumps except for true and output 1310 // dependences. 1311 if (I->isConditionalBranch() && DepType != SDep::Data && 1312 DepType != SDep::Output) 1313 continue; 1314 1315 // Ignore output dependences due to superregs. We can write to two 1316 // different subregisters of R1:0 for instance in the same cycle. 1317 1318 // If neither I nor J defines DepReg, then this is a superfluous output 1319 // dependence. The dependence must be of the form: 1320 // R0 = ... 1321 // R1 = ... 1322 // and there is an output dependence between the two instructions with 1323 // DepReg = D0. 1324 // We want to ignore these dependences. Ideally, the dependence 1325 // constructor should annotate such dependences. We can then avoid this 1326 // relatively expensive check. 1327 // 1328 if (DepType == SDep::Output) { 1329 // DepReg is the register that's responsible for the dependence. 1330 unsigned DepReg = SUJ->Succs[i].getReg(); 1331 1332 // Check if I and J really defines DepReg. 1333 if (!I->definesRegister(DepReg) && !J->definesRegister(DepReg)) 1334 continue; 1335 FoundSequentialDependence = true; 1336 break; 1337 } 1338 1339 // For Order dependences: 1340 // 1. On V4 or later, volatile loads/stores can be packetized together, 1341 // unless other rules prevent is. 1342 // 2. Store followed by a load is not allowed. 1343 // 3. Store followed by a store is only valid on V4 or later. 1344 // 4. Load followed by any memory operation is allowed. 1345 if (DepType == SDep::Order) { 1346 if (!PacketizeVolatiles) { 1347 bool OrdRefs = I->hasOrderedMemoryRef() || J->hasOrderedMemoryRef(); 1348 if (OrdRefs) { 1349 FoundSequentialDependence = true; 1350 break; 1351 } 1352 } 1353 // J is first, I is second. 1354 bool LoadJ = J->mayLoad(), StoreJ = J->mayStore(); 1355 bool LoadI = I->mayLoad(), StoreI = I->mayStore(); 1356 if (StoreJ) { 1357 // Two stores are only allowed on V4+. Load following store is never 1358 // allowed. 1359 if (LoadI) { 1360 FoundSequentialDependence = true; 1361 break; 1362 } 1363 } else if (!LoadJ || (!LoadI && !StoreI)) { 1364 // If J is neither load nor store, assume a dependency. 1365 // If J is a load, but I is neither, also assume a dependency. 1366 FoundSequentialDependence = true; 1367 break; 1368 } 1369 // Store followed by store: not OK on V2. 1370 // Store followed by load: not OK on all. 1371 // Load followed by store: OK on all. 1372 // Load followed by load: OK on all. 1373 continue; 1374 } 1375 1376 // For V4, special case ALLOCFRAME. Even though there is dependency 1377 // between ALLOCFRAME and subsequent store, allow it to be packetized 1378 // in a same packet. This implies that the store is using the caller's 1379 // SP. Hence, offset needs to be updated accordingly. 1380 if (DepType == SDep::Data && J->getOpcode() == Hexagon::S2_allocframe) { 1381 unsigned Opc = I->getOpcode(); 1382 switch (Opc) { 1383 case Hexagon::S2_storerd_io: 1384 case Hexagon::S2_storeri_io: 1385 case Hexagon::S2_storerh_io: 1386 case Hexagon::S2_storerb_io: 1387 if (I->getOperand(0).getReg() == HRI->getStackRegister()) { 1388 int64_t Imm = I->getOperand(1).getImm(); 1389 int64_t NewOff = Imm - (FrameSize + HEXAGON_LRFP_SIZE); 1390 if (HII->isValidOffset(Opc, NewOff)) { 1391 GlueAllocframeStore = true; 1392 // Since this store is to be glued with allocframe in the same 1393 // packet, it will use SP of the previous stack frame, i.e. 1394 // caller's SP. Therefore, we need to recalculate offset 1395 // according to this change. 1396 I->getOperand(1).setImm(NewOff); 1397 continue; 1398 } 1399 } 1400 default: 1401 break; 1402 } 1403 } 1404 1405 // Skip over anti-dependences. Two instructions that are anti-dependent 1406 // can share a packet. 1407 if (DepType != SDep::Anti) { 1408 FoundSequentialDependence = true; 1409 break; 1410 } 1411 } 1412 1413 if (FoundSequentialDependence) { 1414 Dependence = true; 1415 return false; 1416 } 1417 1418 return true; 1419 } 1420 1421 bool HexagonPacketizerList::isLegalToPruneDependencies(SUnit *SUI, SUnit *SUJ) { 1422 MachineInstr *I = SUI->getInstr(); 1423 MachineInstr *J = SUJ->getInstr(); 1424 assert(I && J && "Unable to packetize null instruction!"); 1425 1426 if (cannotCoexist(I, J)) 1427 return false; 1428 1429 if (!Dependence) 1430 return true; 1431 1432 // Check if the instruction was promoted to a dot-new. If so, demote it 1433 // back into a dot-old. 1434 if (PromotedToDotNew) 1435 demoteToDotOld(I); 1436 1437 cleanUpDotCur(); 1438 // Check if the instruction (must be a store) was glued with an allocframe 1439 // instruction. If so, restore its offset to its original value, i.e. use 1440 // current SP instead of caller's SP. 1441 if (GlueAllocframeStore) { 1442 unsigned FrameSize = MF.getFrameInfo()->getStackSize(); 1443 MachineOperand &MOff = I->getOperand(1); 1444 MOff.setImm(MOff.getImm() + FrameSize + HEXAGON_LRFP_SIZE); 1445 } 1446 return false; 1447 } 1448 1449 MachineBasicBlock::iterator 1450 HexagonPacketizerList::addToPacket(MachineInstr &MI) { 1451 MachineBasicBlock::iterator MII = MI; 1452 MachineBasicBlock *MBB = MI.getParent(); 1453 if (MI.isImplicitDef()) { 1454 unsigned R = MI.getOperand(0).getReg(); 1455 if (Hexagon::IntRegsRegClass.contains(R)) { 1456 MCSuperRegIterator S(R, HRI, false); 1457 MI.addOperand(MachineOperand::CreateReg(*S, true, true)); 1458 } 1459 return MII; 1460 } 1461 assert(ResourceTracker->canReserveResources(MI)); 1462 1463 bool ExtMI = HII->isExtended(&MI) || HII->isConstExtended(&MI); 1464 bool Good = true; 1465 1466 if (GlueToNewValueJump) { 1467 MachineInstr &NvjMI = *++MII; 1468 // We need to put both instructions in the same packet: MI and NvjMI. 1469 // Either of them can require a constant extender. Try to add both to 1470 // the current packet, and if that fails, end the packet and start a 1471 // new one. 1472 ResourceTracker->reserveResources(MI); 1473 if (ExtMI) 1474 Good = tryAllocateResourcesForConstExt(true); 1475 1476 bool ExtNvjMI = HII->isExtended(&NvjMI) || HII->isConstExtended(&NvjMI); 1477 if (Good) { 1478 if (ResourceTracker->canReserveResources(NvjMI)) 1479 ResourceTracker->reserveResources(NvjMI); 1480 else 1481 Good = false; 1482 } 1483 if (Good && ExtNvjMI) 1484 Good = tryAllocateResourcesForConstExt(true); 1485 1486 if (!Good) { 1487 endPacket(MBB, MI); 1488 assert(ResourceTracker->canReserveResources(MI)); 1489 ResourceTracker->reserveResources(MI); 1490 if (ExtMI) { 1491 assert(canReserveResourcesForConstExt()); 1492 tryAllocateResourcesForConstExt(true); 1493 } 1494 assert(ResourceTracker->canReserveResources(NvjMI)); 1495 ResourceTracker->reserveResources(NvjMI); 1496 if (ExtNvjMI) { 1497 assert(canReserveResourcesForConstExt()); 1498 reserveResourcesForConstExt(); 1499 } 1500 } 1501 CurrentPacketMIs.push_back(&MI); 1502 CurrentPacketMIs.push_back(&NvjMI); 1503 return MII; 1504 } 1505 1506 ResourceTracker->reserveResources(MI); 1507 if (ExtMI && !tryAllocateResourcesForConstExt(true)) { 1508 endPacket(MBB, MI); 1509 if (PromotedToDotNew) 1510 demoteToDotOld(&MI); 1511 ResourceTracker->reserveResources(MI); 1512 reserveResourcesForConstExt(); 1513 } 1514 1515 CurrentPacketMIs.push_back(&MI); 1516 return MII; 1517 } 1518 1519 void HexagonPacketizerList::endPacket(MachineBasicBlock *MBB, 1520 MachineBasicBlock::iterator MI) { 1521 OldPacketMIs = CurrentPacketMIs; 1522 VLIWPacketizerList::endPacket(MBB, MI); 1523 } 1524 1525 bool HexagonPacketizerList::shouldAddToPacket(const MachineInstr &MI) { 1526 return !producesStall(&MI); 1527 } 1528 1529 1530 // Return true when ConsMI uses a register defined by ProdMI. 1531 static bool isDependent(const MachineInstr *ProdMI, 1532 const MachineInstr *ConsMI) { 1533 if (!ProdMI->getOperand(0).isReg()) 1534 return false; 1535 unsigned DstReg = ProdMI->getOperand(0).getReg(); 1536 1537 for (auto &Op : ConsMI->operands()) 1538 if (Op.isReg() && Op.isUse() && Op.getReg() == DstReg) 1539 // The MIs depend on each other. 1540 return true; 1541 1542 return false; 1543 } 1544 1545 // V60 forward scheduling. 1546 bool HexagonPacketizerList::producesStall(const MachineInstr *I) { 1547 // Check whether the previous packet is in a different loop. If this is the 1548 // case, there is little point in trying to avoid a stall because that would 1549 // favor the rare case (loop entry) over the common case (loop iteration). 1550 // 1551 // TODO: We should really be able to check all the incoming edges if this is 1552 // the first packet in a basic block, so we can avoid stalls from the loop 1553 // backedge. 1554 if (!OldPacketMIs.empty()) { 1555 auto *OldBB = OldPacketMIs.front()->getParent(); 1556 auto *ThisBB = I->getParent(); 1557 if (MLI->getLoopFor(OldBB) != MLI->getLoopFor(ThisBB)) 1558 return false; 1559 } 1560 1561 // Check for stall between two vector instructions. 1562 if (HII->isV60VectorInstruction(I)) { 1563 for (auto J : OldPacketMIs) { 1564 if (!HII->isV60VectorInstruction(J)) 1565 continue; 1566 if (isDependent(J, I) && !HII->isVecUsableNextPacket(J, I)) 1567 return true; 1568 } 1569 return false; 1570 } 1571 1572 // Check for stall between two scalar instructions. First, check that 1573 // there is no definition of a use in the current packet, because it 1574 // may be a candidate for .new. 1575 for (auto J : CurrentPacketMIs) 1576 if (!HII->isV60VectorInstruction(J) && isDependent(J, I)) 1577 return false; 1578 1579 // Check for stall between I and instructions in the previous packet. 1580 if (MF.getSubtarget<HexagonSubtarget>().useBSBScheduling()) { 1581 for (auto J : OldPacketMIs) { 1582 if (HII->isV60VectorInstruction(J)) 1583 continue; 1584 if (!HII->isLateInstrFeedsEarlyInstr(J, I)) 1585 continue; 1586 if (isDependent(J, I) && !HII->canExecuteInBundle(J, I)) 1587 return true; 1588 } 1589 } 1590 1591 return false; 1592 } 1593 1594 1595 //===----------------------------------------------------------------------===// 1596 // Public Constructor Functions 1597 //===----------------------------------------------------------------------===// 1598 1599 FunctionPass *llvm::createHexagonPacketizer() { 1600 return new HexagonPacketizer(); 1601 } 1602