1 //===-- MipsDelaySlotFiller.cpp - Mips Delay Slot Filler ------------------===// 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 // Simple pass to fill delay slots with useful instructions. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "MCTargetDesc/MipsMCNaCl.h" 15 #include "Mips.h" 16 #include "MipsInstrInfo.h" 17 #include "MipsTargetMachine.h" 18 #include "llvm/ADT/BitVector.h" 19 #include "llvm/ADT/SmallPtrSet.h" 20 #include "llvm/ADT/Statistic.h" 21 #include "llvm/Analysis/AliasAnalysis.h" 22 #include "llvm/Analysis/ValueTracking.h" 23 #include "llvm/CodeGen/MachineBranchProbabilityInfo.h" 24 #include "llvm/CodeGen/MachineFunctionPass.h" 25 #include "llvm/CodeGen/MachineInstrBuilder.h" 26 #include "llvm/CodeGen/MachineRegisterInfo.h" 27 #include "llvm/CodeGen/PseudoSourceValue.h" 28 #include "llvm/Support/CommandLine.h" 29 #include "llvm/Target/TargetInstrInfo.h" 30 #include "llvm/Target/TargetMachine.h" 31 #include "llvm/Target/TargetRegisterInfo.h" 32 33 using namespace llvm; 34 35 #define DEBUG_TYPE "delay-slot-filler" 36 37 STATISTIC(FilledSlots, "Number of delay slots filled"); 38 STATISTIC(UsefulSlots, "Number of delay slots filled with instructions that" 39 " are not NOP."); 40 41 static cl::opt<bool> DisableDelaySlotFiller( 42 "disable-mips-delay-filler", 43 cl::init(false), 44 cl::desc("Fill all delay slots with NOPs."), 45 cl::Hidden); 46 47 static cl::opt<bool> DisableForwardSearch( 48 "disable-mips-df-forward-search", 49 cl::init(true), 50 cl::desc("Disallow MIPS delay filler to search forward."), 51 cl::Hidden); 52 53 static cl::opt<bool> DisableSuccBBSearch( 54 "disable-mips-df-succbb-search", 55 cl::init(true), 56 cl::desc("Disallow MIPS delay filler to search successor basic blocks."), 57 cl::Hidden); 58 59 static cl::opt<bool> DisableBackwardSearch( 60 "disable-mips-df-backward-search", 61 cl::init(false), 62 cl::desc("Disallow MIPS delay filler to search backward."), 63 cl::Hidden); 64 65 namespace { 66 typedef MachineBasicBlock::iterator Iter; 67 typedef MachineBasicBlock::reverse_iterator ReverseIter; 68 typedef SmallDenseMap<MachineBasicBlock*, MachineInstr*, 2> BB2BrMap; 69 70 class RegDefsUses { 71 public: 72 RegDefsUses(const TargetRegisterInfo &TRI); 73 void init(const MachineInstr &MI); 74 75 /// This function sets all caller-saved registers in Defs. 76 void setCallerSaved(const MachineInstr &MI); 77 78 /// This function sets all unallocatable registers in Defs. 79 void setUnallocatableRegs(const MachineFunction &MF); 80 81 /// Set bits in Uses corresponding to MBB's live-out registers except for 82 /// the registers that are live-in to SuccBB. 83 void addLiveOut(const MachineBasicBlock &MBB, 84 const MachineBasicBlock &SuccBB); 85 86 bool update(const MachineInstr &MI, unsigned Begin, unsigned End); 87 88 private: 89 bool checkRegDefsUses(BitVector &NewDefs, BitVector &NewUses, unsigned Reg, 90 bool IsDef) const; 91 92 /// Returns true if Reg or its alias is in RegSet. 93 bool isRegInSet(const BitVector &RegSet, unsigned Reg) const; 94 95 const TargetRegisterInfo &TRI; 96 BitVector Defs, Uses; 97 }; 98 99 /// Base class for inspecting loads and stores. 100 class InspectMemInstr { 101 public: 102 InspectMemInstr(bool ForbidMemInstr_) 103 : OrigSeenLoad(false), OrigSeenStore(false), SeenLoad(false), 104 SeenStore(false), ForbidMemInstr(ForbidMemInstr_) {} 105 106 /// Return true if MI cannot be moved to delay slot. 107 bool hasHazard(const MachineInstr &MI); 108 109 virtual ~InspectMemInstr() {} 110 111 protected: 112 /// Flags indicating whether loads or stores have been seen. 113 bool OrigSeenLoad, OrigSeenStore, SeenLoad, SeenStore; 114 115 /// Memory instructions are not allowed to move to delay slot if this flag 116 /// is true. 117 bool ForbidMemInstr; 118 119 private: 120 virtual bool hasHazard_(const MachineInstr &MI) = 0; 121 }; 122 123 /// This subclass rejects any memory instructions. 124 class NoMemInstr : public InspectMemInstr { 125 public: 126 NoMemInstr() : InspectMemInstr(true) {} 127 private: 128 bool hasHazard_(const MachineInstr &MI) override { return true; } 129 }; 130 131 /// This subclass accepts loads from stacks and constant loads. 132 class LoadFromStackOrConst : public InspectMemInstr { 133 public: 134 LoadFromStackOrConst() : InspectMemInstr(false) {} 135 private: 136 bool hasHazard_(const MachineInstr &MI) override; 137 }; 138 139 /// This subclass uses memory dependence information to determine whether a 140 /// memory instruction can be moved to a delay slot. 141 class MemDefsUses : public InspectMemInstr { 142 public: 143 MemDefsUses(const DataLayout &DL, const MachineFrameInfo *MFI); 144 145 private: 146 typedef PointerUnion<const Value *, const PseudoSourceValue *> ValueType; 147 148 bool hasHazard_(const MachineInstr &MI) override; 149 150 /// Update Defs and Uses. Return true if there exist dependences that 151 /// disqualify the delay slot candidate between V and values in Uses and 152 /// Defs. 153 bool updateDefsUses(ValueType V, bool MayStore); 154 155 /// Get the list of underlying objects of MI's memory operand. 156 bool getUnderlyingObjects(const MachineInstr &MI, 157 SmallVectorImpl<ValueType> &Objects) const; 158 159 const MachineFrameInfo *MFI; 160 SmallPtrSet<ValueType, 4> Uses, Defs; 161 const DataLayout &DL; 162 163 /// Flags indicating whether loads or stores with no underlying objects have 164 /// been seen. 165 bool SeenNoObjLoad, SeenNoObjStore; 166 }; 167 168 class Filler : public MachineFunctionPass { 169 public: 170 Filler(TargetMachine &tm) 171 : MachineFunctionPass(ID), TM(tm) { } 172 173 const char *getPassName() const override { 174 return "Mips Delay Slot Filler"; 175 } 176 177 bool runOnMachineFunction(MachineFunction &F) override { 178 bool Changed = false; 179 for (MachineFunction::iterator FI = F.begin(), FE = F.end(); 180 FI != FE; ++FI) 181 Changed |= runOnMachineBasicBlock(*FI); 182 183 // This pass invalidates liveness information when it reorders 184 // instructions to fill delay slot. Without this, -verify-machineinstrs 185 // will fail. 186 if (Changed) 187 F.getRegInfo().invalidateLiveness(); 188 189 return Changed; 190 } 191 192 void getAnalysisUsage(AnalysisUsage &AU) const override { 193 AU.addRequired<MachineBranchProbabilityInfo>(); 194 MachineFunctionPass::getAnalysisUsage(AU); 195 } 196 197 private: 198 bool runOnMachineBasicBlock(MachineBasicBlock &MBB); 199 200 Iter replaceWithCompactBranch(MachineBasicBlock &MBB, 201 Iter Branch, DebugLoc DL); 202 203 Iter replaceWithCompactJump(MachineBasicBlock &MBB, 204 Iter Jump, DebugLoc DL); 205 206 /// This function checks if it is valid to move Candidate to the delay slot 207 /// and returns true if it isn't. It also updates memory and register 208 /// dependence information. 209 bool delayHasHazard(const MachineInstr &Candidate, RegDefsUses &RegDU, 210 InspectMemInstr &IM) const; 211 212 /// This function searches range [Begin, End) for an instruction that can be 213 /// moved to the delay slot. Returns true on success. 214 template<typename IterTy> 215 bool searchRange(MachineBasicBlock &MBB, IterTy Begin, IterTy End, 216 RegDefsUses &RegDU, InspectMemInstr &IM, Iter Slot, 217 IterTy &Filler) const; 218 219 /// This function searches in the backward direction for an instruction that 220 /// can be moved to the delay slot. Returns true on success. 221 bool searchBackward(MachineBasicBlock &MBB, Iter Slot) const; 222 223 /// This function searches MBB in the forward direction for an instruction 224 /// that can be moved to the delay slot. Returns true on success. 225 bool searchForward(MachineBasicBlock &MBB, Iter Slot) const; 226 227 /// This function searches one of MBB's successor blocks for an instruction 228 /// that can be moved to the delay slot and inserts clones of the 229 /// instruction into the successor's predecessor blocks. 230 bool searchSuccBBs(MachineBasicBlock &MBB, Iter Slot) const; 231 232 /// Pick a successor block of MBB. Return NULL if MBB doesn't have a 233 /// successor block that is not a landing pad. 234 MachineBasicBlock *selectSuccBB(MachineBasicBlock &B) const; 235 236 /// This function analyzes MBB and returns an instruction with an unoccupied 237 /// slot that branches to Dst. 238 std::pair<MipsInstrInfo::BranchType, MachineInstr *> 239 getBranch(MachineBasicBlock &MBB, const MachineBasicBlock &Dst) const; 240 241 /// Examine Pred and see if it is possible to insert an instruction into 242 /// one of its branches delay slot or its end. 243 bool examinePred(MachineBasicBlock &Pred, const MachineBasicBlock &Succ, 244 RegDefsUses &RegDU, bool &HasMultipleSuccs, 245 BB2BrMap &BrMap) const; 246 247 bool terminateSearch(const MachineInstr &Candidate) const; 248 249 TargetMachine &TM; 250 251 static char ID; 252 }; 253 char Filler::ID = 0; 254 } // end of anonymous namespace 255 256 static bool hasUnoccupiedSlot(const MachineInstr *MI) { 257 return MI->hasDelaySlot() && !MI->isBundledWithSucc(); 258 } 259 260 /// This function inserts clones of Filler into predecessor blocks. 261 static void insertDelayFiller(Iter Filler, const BB2BrMap &BrMap) { 262 MachineFunction *MF = Filler->getParent()->getParent(); 263 264 for (BB2BrMap::const_iterator I = BrMap.begin(); I != BrMap.end(); ++I) { 265 if (I->second) { 266 MIBundleBuilder(I->second).append(MF->CloneMachineInstr(&*Filler)); 267 ++UsefulSlots; 268 } else { 269 I->first->insert(I->first->end(), MF->CloneMachineInstr(&*Filler)); 270 } 271 } 272 } 273 274 /// This function adds registers Filler defines to MBB's live-in register list. 275 static void addLiveInRegs(Iter Filler, MachineBasicBlock &MBB) { 276 for (unsigned I = 0, E = Filler->getNumOperands(); I != E; ++I) { 277 const MachineOperand &MO = Filler->getOperand(I); 278 unsigned R; 279 280 if (!MO.isReg() || !MO.isDef() || !(R = MO.getReg())) 281 continue; 282 283 #ifndef NDEBUG 284 const MachineFunction &MF = *MBB.getParent(); 285 assert(MF.getSubtarget().getRegisterInfo()->getAllocatableSet(MF).test(R) && 286 "Shouldn't move an instruction with unallocatable registers across " 287 "basic block boundaries."); 288 #endif 289 290 if (!MBB.isLiveIn(R)) 291 MBB.addLiveIn(R); 292 } 293 } 294 295 RegDefsUses::RegDefsUses(const TargetRegisterInfo &TRI) 296 : TRI(TRI), Defs(TRI.getNumRegs(), false), Uses(TRI.getNumRegs(), false) {} 297 298 void RegDefsUses::init(const MachineInstr &MI) { 299 // Add all register operands which are explicit and non-variadic. 300 update(MI, 0, MI.getDesc().getNumOperands()); 301 302 // If MI is a call, add RA to Defs to prevent users of RA from going into 303 // delay slot. 304 if (MI.isCall()) 305 Defs.set(Mips::RA); 306 307 // Add all implicit register operands of branch instructions except 308 // register AT. 309 if (MI.isBranch()) { 310 update(MI, MI.getDesc().getNumOperands(), MI.getNumOperands()); 311 Defs.reset(Mips::AT); 312 } 313 } 314 315 void RegDefsUses::setCallerSaved(const MachineInstr &MI) { 316 assert(MI.isCall()); 317 318 // If MI is a call, add all caller-saved registers to Defs. 319 BitVector CallerSavedRegs(TRI.getNumRegs(), true); 320 321 CallerSavedRegs.reset(Mips::ZERO); 322 CallerSavedRegs.reset(Mips::ZERO_64); 323 324 for (const MCPhysReg *R = TRI.getCalleeSavedRegs(); *R; ++R) 325 for (MCRegAliasIterator AI(*R, &TRI, true); AI.isValid(); ++AI) 326 CallerSavedRegs.reset(*AI); 327 328 Defs |= CallerSavedRegs; 329 } 330 331 void RegDefsUses::setUnallocatableRegs(const MachineFunction &MF) { 332 BitVector AllocSet = TRI.getAllocatableSet(MF); 333 334 for (int R = AllocSet.find_first(); R != -1; R = AllocSet.find_next(R)) 335 for (MCRegAliasIterator AI(R, &TRI, false); AI.isValid(); ++AI) 336 AllocSet.set(*AI); 337 338 AllocSet.set(Mips::ZERO); 339 AllocSet.set(Mips::ZERO_64); 340 341 Defs |= AllocSet.flip(); 342 } 343 344 void RegDefsUses::addLiveOut(const MachineBasicBlock &MBB, 345 const MachineBasicBlock &SuccBB) { 346 for (MachineBasicBlock::const_succ_iterator SI = MBB.succ_begin(), 347 SE = MBB.succ_end(); SI != SE; ++SI) 348 if (*SI != &SuccBB) 349 for (MachineBasicBlock::livein_iterator LI = (*SI)->livein_begin(), 350 LE = (*SI)->livein_end(); LI != LE; ++LI) 351 Uses.set(*LI); 352 } 353 354 bool RegDefsUses::update(const MachineInstr &MI, unsigned Begin, unsigned End) { 355 BitVector NewDefs(TRI.getNumRegs()), NewUses(TRI.getNumRegs()); 356 bool HasHazard = false; 357 358 for (unsigned I = Begin; I != End; ++I) { 359 const MachineOperand &MO = MI.getOperand(I); 360 361 if (MO.isReg() && MO.getReg()) 362 HasHazard |= checkRegDefsUses(NewDefs, NewUses, MO.getReg(), MO.isDef()); 363 } 364 365 Defs |= NewDefs; 366 Uses |= NewUses; 367 368 return HasHazard; 369 } 370 371 bool RegDefsUses::checkRegDefsUses(BitVector &NewDefs, BitVector &NewUses, 372 unsigned Reg, bool IsDef) const { 373 if (IsDef) { 374 NewDefs.set(Reg); 375 // check whether Reg has already been defined or used. 376 return (isRegInSet(Defs, Reg) || isRegInSet(Uses, Reg)); 377 } 378 379 NewUses.set(Reg); 380 // check whether Reg has already been defined. 381 return isRegInSet(Defs, Reg); 382 } 383 384 bool RegDefsUses::isRegInSet(const BitVector &RegSet, unsigned Reg) const { 385 // Check Reg and all aliased Registers. 386 for (MCRegAliasIterator AI(Reg, &TRI, true); AI.isValid(); ++AI) 387 if (RegSet.test(*AI)) 388 return true; 389 return false; 390 } 391 392 bool InspectMemInstr::hasHazard(const MachineInstr &MI) { 393 if (!MI.mayStore() && !MI.mayLoad()) 394 return false; 395 396 if (ForbidMemInstr) 397 return true; 398 399 OrigSeenLoad = SeenLoad; 400 OrigSeenStore = SeenStore; 401 SeenLoad |= MI.mayLoad(); 402 SeenStore |= MI.mayStore(); 403 404 // If MI is an ordered or volatile memory reference, disallow moving 405 // subsequent loads and stores to delay slot. 406 if (MI.hasOrderedMemoryRef() && (OrigSeenLoad || OrigSeenStore)) { 407 ForbidMemInstr = true; 408 return true; 409 } 410 411 return hasHazard_(MI); 412 } 413 414 bool LoadFromStackOrConst::hasHazard_(const MachineInstr &MI) { 415 if (MI.mayStore()) 416 return true; 417 418 if (!MI.hasOneMemOperand() || !(*MI.memoperands_begin())->getPseudoValue()) 419 return true; 420 421 if (const PseudoSourceValue *PSV = 422 (*MI.memoperands_begin())->getPseudoValue()) { 423 if (isa<FixedStackPseudoSourceValue>(PSV)) 424 return false; 425 return !PSV->isConstant(nullptr) && PSV != PseudoSourceValue::getStack(); 426 } 427 428 return true; 429 } 430 431 MemDefsUses::MemDefsUses(const DataLayout &DL, const MachineFrameInfo *MFI_) 432 : InspectMemInstr(false), MFI(MFI_), DL(DL), SeenNoObjLoad(false), 433 SeenNoObjStore(false) {} 434 435 bool MemDefsUses::hasHazard_(const MachineInstr &MI) { 436 bool HasHazard = false; 437 SmallVector<ValueType, 4> Objs; 438 439 // Check underlying object list. 440 if (getUnderlyingObjects(MI, Objs)) { 441 for (SmallVectorImpl<ValueType>::const_iterator I = Objs.begin(); 442 I != Objs.end(); ++I) 443 HasHazard |= updateDefsUses(*I, MI.mayStore()); 444 445 return HasHazard; 446 } 447 448 // No underlying objects found. 449 HasHazard = MI.mayStore() && (OrigSeenLoad || OrigSeenStore); 450 HasHazard |= MI.mayLoad() || OrigSeenStore; 451 452 SeenNoObjLoad |= MI.mayLoad(); 453 SeenNoObjStore |= MI.mayStore(); 454 455 return HasHazard; 456 } 457 458 bool MemDefsUses::updateDefsUses(ValueType V, bool MayStore) { 459 if (MayStore) 460 return !Defs.insert(V).second || Uses.count(V) || SeenNoObjStore || 461 SeenNoObjLoad; 462 463 Uses.insert(V); 464 return Defs.count(V) || SeenNoObjStore; 465 } 466 467 bool MemDefsUses:: 468 getUnderlyingObjects(const MachineInstr &MI, 469 SmallVectorImpl<ValueType> &Objects) const { 470 if (!MI.hasOneMemOperand() || 471 (!(*MI.memoperands_begin())->getValue() && 472 !(*MI.memoperands_begin())->getPseudoValue())) 473 return false; 474 475 if (const PseudoSourceValue *PSV = 476 (*MI.memoperands_begin())->getPseudoValue()) { 477 if (!PSV->isAliased(MFI)) 478 return false; 479 Objects.push_back(PSV); 480 return true; 481 } 482 483 const Value *V = (*MI.memoperands_begin())->getValue(); 484 485 SmallVector<Value *, 4> Objs; 486 GetUnderlyingObjects(const_cast<Value *>(V), Objs, DL); 487 488 for (SmallVectorImpl<Value *>::iterator I = Objs.begin(), E = Objs.end(); 489 I != E; ++I) { 490 if (!isIdentifiedObject(V)) 491 return false; 492 493 Objects.push_back(*I); 494 } 495 496 return true; 497 } 498 499 // Replace Branch with the compact branch instruction. 500 Iter Filler::replaceWithCompactBranch(MachineBasicBlock &MBB, 501 Iter Branch, DebugLoc DL) { 502 const MipsInstrInfo *TII = 503 MBB.getParent()->getSubtarget<MipsSubtarget>().getInstrInfo(); 504 505 unsigned NewOpcode = 506 (((unsigned) Branch->getOpcode()) == Mips::BEQ) ? Mips::BEQZC_MM 507 : Mips::BNEZC_MM; 508 509 const MCInstrDesc &NewDesc = TII->get(NewOpcode); 510 MachineInstrBuilder MIB = BuildMI(MBB, Branch, DL, NewDesc); 511 512 MIB.addReg(Branch->getOperand(0).getReg()); 513 MIB.addMBB(Branch->getOperand(2).getMBB()); 514 515 Iter tmpIter = Branch; 516 Branch = std::prev(Branch); 517 MBB.erase(tmpIter); 518 519 return Branch; 520 } 521 522 // Replace Jumps with the compact jump instruction. 523 Iter Filler::replaceWithCompactJump(MachineBasicBlock &MBB, 524 Iter Jump, DebugLoc DL) { 525 const MipsInstrInfo *TII = 526 MBB.getParent()->getSubtarget<MipsSubtarget>().getInstrInfo(); 527 528 const MCInstrDesc &NewDesc = TII->get(Mips::JRC16_MM); 529 MachineInstrBuilder MIB = BuildMI(MBB, Jump, DL, NewDesc); 530 531 MIB.addReg(Jump->getOperand(0).getReg()); 532 533 Iter tmpIter = Jump; 534 Jump = std::prev(Jump); 535 MBB.erase(tmpIter); 536 537 return Jump; 538 } 539 540 // For given opcode returns opcode of corresponding instruction with short 541 // delay slot. 542 static int getEquivalentCallShort(int Opcode) { 543 switch (Opcode) { 544 case Mips::BGEZAL: 545 return Mips::BGEZALS_MM; 546 case Mips::BLTZAL: 547 return Mips::BLTZALS_MM; 548 case Mips::JAL: 549 return Mips::JALS_MM; 550 case Mips::JALR: 551 return Mips::JALRS_MM; 552 case Mips::JALR16_MM: 553 return Mips::JALRS16_MM; 554 default: 555 llvm_unreachable("Unexpected call instruction for microMIPS."); 556 } 557 } 558 559 /// runOnMachineBasicBlock - Fill in delay slots for the given basic block. 560 /// We assume there is only one delay slot per delayed instruction. 561 bool Filler::runOnMachineBasicBlock(MachineBasicBlock &MBB) { 562 bool Changed = false; 563 const MipsSubtarget &STI = MBB.getParent()->getSubtarget<MipsSubtarget>(); 564 bool InMicroMipsMode = STI.inMicroMipsMode(); 565 const MipsInstrInfo *TII = STI.getInstrInfo(); 566 567 for (Iter I = MBB.begin(); I != MBB.end(); ++I) { 568 if (!hasUnoccupiedSlot(&*I)) 569 continue; 570 571 ++FilledSlots; 572 Changed = true; 573 574 // Delay slot filling is disabled at -O0. 575 if (!DisableDelaySlotFiller && (TM.getOptLevel() != CodeGenOpt::None)) { 576 bool Filled = false; 577 578 if (searchBackward(MBB, I)) { 579 Filled = true; 580 } else if (I->isTerminator()) { 581 if (searchSuccBBs(MBB, I)) { 582 Filled = true; 583 } 584 } else if (searchForward(MBB, I)) { 585 Filled = true; 586 } 587 588 if (Filled) { 589 // Get instruction with delay slot. 590 MachineBasicBlock::instr_iterator DSI(I); 591 592 if (InMicroMipsMode && TII->GetInstSizeInBytes(std::next(DSI)) == 2 && 593 DSI->isCall()) { 594 // If instruction in delay slot is 16b change opcode to 595 // corresponding instruction with short delay slot. 596 DSI->setDesc(TII->get(getEquivalentCallShort(DSI->getOpcode()))); 597 } 598 599 continue; 600 } 601 } 602 603 // If instruction is BEQ or BNE with one ZERO register, then instead of 604 // adding NOP replace this instruction with the corresponding compact 605 // branch instruction, i.e. BEQZC or BNEZC. 606 unsigned Opcode = I->getOpcode(); 607 if (InMicroMipsMode) { 608 switch (Opcode) { 609 case Mips::BEQ: 610 case Mips::BNE: 611 if (((unsigned) I->getOperand(1).getReg()) == Mips::ZERO) { 612 I = replaceWithCompactBranch(MBB, I, I->getDebugLoc()); 613 continue; 614 } 615 break; 616 case Mips::JR: 617 case Mips::PseudoReturn: 618 case Mips::PseudoIndirectBranch: 619 // For microMIPS the PseudoReturn and PseudoIndirectBranch are allways 620 // expanded to JR_MM, so they can be replaced with JRC16_MM. 621 I = replaceWithCompactJump(MBB, I, I->getDebugLoc()); 622 continue; 623 default: 624 break; 625 } 626 } 627 // Bundle the NOP to the instruction with the delay slot. 628 BuildMI(MBB, std::next(I), I->getDebugLoc(), TII->get(Mips::NOP)); 629 MIBundleBuilder(MBB, I, std::next(I, 2)); 630 } 631 632 return Changed; 633 } 634 635 /// createMipsDelaySlotFillerPass - Returns a pass that fills in delay 636 /// slots in Mips MachineFunctions 637 FunctionPass *llvm::createMipsDelaySlotFillerPass(MipsTargetMachine &tm) { 638 return new Filler(tm); 639 } 640 641 template<typename IterTy> 642 bool Filler::searchRange(MachineBasicBlock &MBB, IterTy Begin, IterTy End, 643 RegDefsUses &RegDU, InspectMemInstr& IM, Iter Slot, 644 IterTy &Filler) const { 645 for (IterTy I = Begin; I != End; ++I) { 646 // skip debug value 647 if (I->isDebugValue()) 648 continue; 649 650 if (terminateSearch(*I)) 651 break; 652 653 assert((!I->isCall() && !I->isReturn() && !I->isBranch()) && 654 "Cannot put calls, returns or branches in delay slot."); 655 656 if (delayHasHazard(*I, RegDU, IM)) 657 continue; 658 659 const MipsSubtarget &STI = MBB.getParent()->getSubtarget<MipsSubtarget>(); 660 if (STI.isTargetNaCl()) { 661 // In NaCl, instructions that must be masked are forbidden in delay slots. 662 // We only check for loads, stores and SP changes. Calls, returns and 663 // branches are not checked because non-NaCl targets never put them in 664 // delay slots. 665 unsigned AddrIdx; 666 if ((isBasePlusOffsetMemoryAccess(I->getOpcode(), &AddrIdx) && 667 baseRegNeedsLoadStoreMask(I->getOperand(AddrIdx).getReg())) || 668 I->modifiesRegister(Mips::SP, STI.getRegisterInfo())) 669 continue; 670 } 671 672 bool InMicroMipsMode = STI.inMicroMipsMode(); 673 const MipsInstrInfo *TII = STI.getInstrInfo(); 674 unsigned Opcode = (*Slot).getOpcode(); 675 if (InMicroMipsMode && TII->GetInstSizeInBytes(&(*I)) == 2 && 676 (Opcode == Mips::JR || Opcode == Mips::PseudoIndirectBranch || 677 Opcode == Mips::PseudoReturn)) 678 continue; 679 680 Filler = I; 681 return true; 682 } 683 684 return false; 685 } 686 687 bool Filler::searchBackward(MachineBasicBlock &MBB, Iter Slot) const { 688 if (DisableBackwardSearch) 689 return false; 690 691 RegDefsUses RegDU(*MBB.getParent()->getSubtarget().getRegisterInfo()); 692 MemDefsUses MemDU(*TM.getDataLayout(), MBB.getParent()->getFrameInfo()); 693 ReverseIter Filler; 694 695 RegDU.init(*Slot); 696 697 if (!searchRange(MBB, ReverseIter(Slot), MBB.rend(), RegDU, MemDU, Slot, 698 Filler)) 699 return false; 700 701 MBB.splice(std::next(Slot), &MBB, std::next(Filler).base()); 702 MIBundleBuilder(MBB, Slot, std::next(Slot, 2)); 703 ++UsefulSlots; 704 return true; 705 } 706 707 bool Filler::searchForward(MachineBasicBlock &MBB, Iter Slot) const { 708 // Can handle only calls. 709 if (DisableForwardSearch || !Slot->isCall()) 710 return false; 711 712 RegDefsUses RegDU(*MBB.getParent()->getSubtarget().getRegisterInfo()); 713 NoMemInstr NM; 714 Iter Filler; 715 716 RegDU.setCallerSaved(*Slot); 717 718 if (!searchRange(MBB, std::next(Slot), MBB.end(), RegDU, NM, Slot, Filler)) 719 return false; 720 721 MBB.splice(std::next(Slot), &MBB, Filler); 722 MIBundleBuilder(MBB, Slot, std::next(Slot, 2)); 723 ++UsefulSlots; 724 return true; 725 } 726 727 bool Filler::searchSuccBBs(MachineBasicBlock &MBB, Iter Slot) const { 728 if (DisableSuccBBSearch) 729 return false; 730 731 MachineBasicBlock *SuccBB = selectSuccBB(MBB); 732 733 if (!SuccBB) 734 return false; 735 736 RegDefsUses RegDU(*MBB.getParent()->getSubtarget().getRegisterInfo()); 737 bool HasMultipleSuccs = false; 738 BB2BrMap BrMap; 739 std::unique_ptr<InspectMemInstr> IM; 740 Iter Filler; 741 742 // Iterate over SuccBB's predecessor list. 743 for (MachineBasicBlock::pred_iterator PI = SuccBB->pred_begin(), 744 PE = SuccBB->pred_end(); PI != PE; ++PI) 745 if (!examinePred(**PI, *SuccBB, RegDU, HasMultipleSuccs, BrMap)) 746 return false; 747 748 // Do not allow moving instructions which have unallocatable register operands 749 // across basic block boundaries. 750 RegDU.setUnallocatableRegs(*MBB.getParent()); 751 752 // Only allow moving loads from stack or constants if any of the SuccBB's 753 // predecessors have multiple successors. 754 if (HasMultipleSuccs) { 755 IM.reset(new LoadFromStackOrConst()); 756 } else { 757 const MachineFrameInfo *MFI = MBB.getParent()->getFrameInfo(); 758 IM.reset(new MemDefsUses(*TM.getDataLayout(), MFI)); 759 } 760 761 if (!searchRange(MBB, SuccBB->begin(), SuccBB->end(), RegDU, *IM, Slot, 762 Filler)) 763 return false; 764 765 insertDelayFiller(Filler, BrMap); 766 addLiveInRegs(Filler, *SuccBB); 767 Filler->eraseFromParent(); 768 769 return true; 770 } 771 772 MachineBasicBlock *Filler::selectSuccBB(MachineBasicBlock &B) const { 773 if (B.succ_empty()) 774 return nullptr; 775 776 // Select the successor with the larget edge weight. 777 auto &Prob = getAnalysis<MachineBranchProbabilityInfo>(); 778 MachineBasicBlock *S = *std::max_element(B.succ_begin(), B.succ_end(), 779 [&](const MachineBasicBlock *Dst0, 780 const MachineBasicBlock *Dst1) { 781 return Prob.getEdgeWeight(&B, Dst0) < Prob.getEdgeWeight(&B, Dst1); 782 }); 783 return S->isLandingPad() ? nullptr : S; 784 } 785 786 std::pair<MipsInstrInfo::BranchType, MachineInstr *> 787 Filler::getBranch(MachineBasicBlock &MBB, const MachineBasicBlock &Dst) const { 788 const MipsInstrInfo *TII = 789 MBB.getParent()->getSubtarget<MipsSubtarget>().getInstrInfo(); 790 MachineBasicBlock *TrueBB = nullptr, *FalseBB = nullptr; 791 SmallVector<MachineInstr*, 2> BranchInstrs; 792 SmallVector<MachineOperand, 2> Cond; 793 794 MipsInstrInfo::BranchType R = 795 TII->AnalyzeBranch(MBB, TrueBB, FalseBB, Cond, false, BranchInstrs); 796 797 if ((R == MipsInstrInfo::BT_None) || (R == MipsInstrInfo::BT_NoBranch)) 798 return std::make_pair(R, nullptr); 799 800 if (R != MipsInstrInfo::BT_CondUncond) { 801 if (!hasUnoccupiedSlot(BranchInstrs[0])) 802 return std::make_pair(MipsInstrInfo::BT_None, nullptr); 803 804 assert(((R != MipsInstrInfo::BT_Uncond) || (TrueBB == &Dst))); 805 806 return std::make_pair(R, BranchInstrs[0]); 807 } 808 809 assert((TrueBB == &Dst) || (FalseBB == &Dst)); 810 811 // Examine the conditional branch. See if its slot is occupied. 812 if (hasUnoccupiedSlot(BranchInstrs[0])) 813 return std::make_pair(MipsInstrInfo::BT_Cond, BranchInstrs[0]); 814 815 // If that fails, try the unconditional branch. 816 if (hasUnoccupiedSlot(BranchInstrs[1]) && (FalseBB == &Dst)) 817 return std::make_pair(MipsInstrInfo::BT_Uncond, BranchInstrs[1]); 818 819 return std::make_pair(MipsInstrInfo::BT_None, nullptr); 820 } 821 822 bool Filler::examinePred(MachineBasicBlock &Pred, const MachineBasicBlock &Succ, 823 RegDefsUses &RegDU, bool &HasMultipleSuccs, 824 BB2BrMap &BrMap) const { 825 std::pair<MipsInstrInfo::BranchType, MachineInstr *> P = 826 getBranch(Pred, Succ); 827 828 // Return if either getBranch wasn't able to analyze the branches or there 829 // were no branches with unoccupied slots. 830 if (P.first == MipsInstrInfo::BT_None) 831 return false; 832 833 if ((P.first != MipsInstrInfo::BT_Uncond) && 834 (P.first != MipsInstrInfo::BT_NoBranch)) { 835 HasMultipleSuccs = true; 836 RegDU.addLiveOut(Pred, Succ); 837 } 838 839 BrMap[&Pred] = P.second; 840 return true; 841 } 842 843 bool Filler::delayHasHazard(const MachineInstr &Candidate, RegDefsUses &RegDU, 844 InspectMemInstr &IM) const { 845 bool HasHazard = (Candidate.isImplicitDef() || Candidate.isKill()); 846 847 HasHazard |= IM.hasHazard(Candidate); 848 HasHazard |= RegDU.update(Candidate, 0, Candidate.getNumOperands()); 849 850 return HasHazard; 851 } 852 853 bool Filler::terminateSearch(const MachineInstr &Candidate) const { 854 return (Candidate.isTerminator() || Candidate.isCall() || 855 Candidate.isPosition() || Candidate.isInlineAsm() || 856 Candidate.hasUnmodeledSideEffects()); 857 } 858