1 //===-- TargetInstrInfo.cpp - Target Instruction Information --------------===// 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 file implements the TargetInstrInfo class. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "llvm/Target/TargetInstrInfo.h" 15 #include "llvm/CodeGen/MachineFrameInfo.h" 16 #include "llvm/CodeGen/MachineInstrBuilder.h" 17 #include "llvm/CodeGen/MachineMemOperand.h" 18 #include "llvm/CodeGen/MachineRegisterInfo.h" 19 #include "llvm/CodeGen/PseudoSourceValue.h" 20 #include "llvm/CodeGen/ScoreboardHazardRecognizer.h" 21 #include "llvm/CodeGen/StackMaps.h" 22 #include "llvm/IR/DataLayout.h" 23 #include "llvm/MC/MCAsmInfo.h" 24 #include "llvm/MC/MCInstrItineraries.h" 25 #include "llvm/Support/CommandLine.h" 26 #include "llvm/Support/ErrorHandling.h" 27 #include "llvm/Support/raw_ostream.h" 28 #include "llvm/Target/TargetLowering.h" 29 #include "llvm/Target/TargetMachine.h" 30 #include "llvm/Target/TargetRegisterInfo.h" 31 #include <cctype> 32 using namespace llvm; 33 34 static cl::opt<bool> DisableHazardRecognizer( 35 "disable-sched-hazard", cl::Hidden, cl::init(false), 36 cl::desc("Disable hazard detection during preRA scheduling")); 37 38 TargetInstrInfo::~TargetInstrInfo() { 39 } 40 41 const TargetRegisterClass* 42 TargetInstrInfo::getRegClass(const MCInstrDesc &MCID, unsigned OpNum, 43 const TargetRegisterInfo *TRI, 44 const MachineFunction &MF) const { 45 if (OpNum >= MCID.getNumOperands()) 46 return nullptr; 47 48 short RegClass = MCID.OpInfo[OpNum].RegClass; 49 if (MCID.OpInfo[OpNum].isLookupPtrRegClass()) 50 return TRI->getPointerRegClass(MF, RegClass); 51 52 // Instructions like INSERT_SUBREG do not have fixed register classes. 53 if (RegClass < 0) 54 return nullptr; 55 56 // Otherwise just look it up normally. 57 return TRI->getRegClass(RegClass); 58 } 59 60 /// insertNoop - Insert a noop into the instruction stream at the specified 61 /// point. 62 void TargetInstrInfo::insertNoop(MachineBasicBlock &MBB, 63 MachineBasicBlock::iterator MI) const { 64 llvm_unreachable("Target didn't implement insertNoop!"); 65 } 66 67 /// Measure the specified inline asm to determine an approximation of its 68 /// length. 69 /// Comments (which run till the next SeparatorString or newline) do not 70 /// count as an instruction. 71 /// Any other non-whitespace text is considered an instruction, with 72 /// multiple instructions separated by SeparatorString or newlines. 73 /// Variable-length instructions are not handled here; this function 74 /// may be overloaded in the target code to do that. 75 unsigned TargetInstrInfo::getInlineAsmLength(const char *Str, 76 const MCAsmInfo &MAI) const { 77 78 79 // Count the number of instructions in the asm. 80 bool atInsnStart = true; 81 unsigned Length = 0; 82 for (; *Str; ++Str) { 83 if (*Str == '\n' || strncmp(Str, MAI.getSeparatorString(), 84 strlen(MAI.getSeparatorString())) == 0) 85 atInsnStart = true; 86 if (atInsnStart && !std::isspace(static_cast<unsigned char>(*Str))) { 87 Length += MAI.getMaxInstLength(); 88 atInsnStart = false; 89 } 90 if (atInsnStart && strncmp(Str, MAI.getCommentString(), 91 strlen(MAI.getCommentString())) == 0) 92 atInsnStart = false; 93 } 94 95 return Length; 96 } 97 98 /// ReplaceTailWithBranchTo - Delete the instruction OldInst and everything 99 /// after it, replacing it with an unconditional branch to NewDest. 100 void 101 TargetInstrInfo::ReplaceTailWithBranchTo(MachineBasicBlock::iterator Tail, 102 MachineBasicBlock *NewDest) const { 103 MachineBasicBlock *MBB = Tail->getParent(); 104 105 // Remove all the old successors of MBB from the CFG. 106 while (!MBB->succ_empty()) 107 MBB->removeSuccessor(MBB->succ_begin()); 108 109 // Remove all the dead instructions from the end of MBB. 110 MBB->erase(Tail, MBB->end()); 111 112 // If MBB isn't immediately before MBB, insert a branch to it. 113 if (++MachineFunction::iterator(MBB) != MachineFunction::iterator(NewDest)) 114 InsertBranch(*MBB, NewDest, nullptr, SmallVector<MachineOperand, 0>(), 115 Tail->getDebugLoc()); 116 MBB->addSuccessor(NewDest); 117 } 118 119 // commuteInstruction - The default implementation of this method just exchanges 120 // the two operands returned by findCommutedOpIndices. 121 MachineInstr *TargetInstrInfo::commuteInstruction(MachineInstr *MI, 122 bool NewMI) const { 123 const MCInstrDesc &MCID = MI->getDesc(); 124 bool HasDef = MCID.getNumDefs(); 125 if (HasDef && !MI->getOperand(0).isReg()) 126 // No idea how to commute this instruction. Target should implement its own. 127 return nullptr; 128 unsigned Idx1, Idx2; 129 if (!findCommutedOpIndices(MI, Idx1, Idx2)) { 130 std::string msg; 131 raw_string_ostream Msg(msg); 132 Msg << "Don't know how to commute: " << *MI; 133 report_fatal_error(Msg.str()); 134 } 135 136 assert(MI->getOperand(Idx1).isReg() && MI->getOperand(Idx2).isReg() && 137 "This only knows how to commute register operands so far"); 138 unsigned Reg0 = HasDef ? MI->getOperand(0).getReg() : 0; 139 unsigned Reg1 = MI->getOperand(Idx1).getReg(); 140 unsigned Reg2 = MI->getOperand(Idx2).getReg(); 141 unsigned SubReg0 = HasDef ? MI->getOperand(0).getSubReg() : 0; 142 unsigned SubReg1 = MI->getOperand(Idx1).getSubReg(); 143 unsigned SubReg2 = MI->getOperand(Idx2).getSubReg(); 144 bool Reg1IsKill = MI->getOperand(Idx1).isKill(); 145 bool Reg2IsKill = MI->getOperand(Idx2).isKill(); 146 // If destination is tied to either of the commuted source register, then 147 // it must be updated. 148 if (HasDef && Reg0 == Reg1 && 149 MI->getDesc().getOperandConstraint(Idx1, MCOI::TIED_TO) == 0) { 150 Reg2IsKill = false; 151 Reg0 = Reg2; 152 SubReg0 = SubReg2; 153 } else if (HasDef && Reg0 == Reg2 && 154 MI->getDesc().getOperandConstraint(Idx2, MCOI::TIED_TO) == 0) { 155 Reg1IsKill = false; 156 Reg0 = Reg1; 157 SubReg0 = SubReg1; 158 } 159 160 if (NewMI) { 161 // Create a new instruction. 162 MachineFunction &MF = *MI->getParent()->getParent(); 163 MI = MF.CloneMachineInstr(MI); 164 } 165 166 if (HasDef) { 167 MI->getOperand(0).setReg(Reg0); 168 MI->getOperand(0).setSubReg(SubReg0); 169 } 170 MI->getOperand(Idx2).setReg(Reg1); 171 MI->getOperand(Idx1).setReg(Reg2); 172 MI->getOperand(Idx2).setSubReg(SubReg1); 173 MI->getOperand(Idx1).setSubReg(SubReg2); 174 MI->getOperand(Idx2).setIsKill(Reg1IsKill); 175 MI->getOperand(Idx1).setIsKill(Reg2IsKill); 176 return MI; 177 } 178 179 /// findCommutedOpIndices - If specified MI is commutable, return the two 180 /// operand indices that would swap value. Return true if the instruction 181 /// is not in a form which this routine understands. 182 bool TargetInstrInfo::findCommutedOpIndices(MachineInstr *MI, 183 unsigned &SrcOpIdx1, 184 unsigned &SrcOpIdx2) const { 185 assert(!MI->isBundle() && 186 "TargetInstrInfo::findCommutedOpIndices() can't handle bundles"); 187 188 const MCInstrDesc &MCID = MI->getDesc(); 189 if (!MCID.isCommutable()) 190 return false; 191 // This assumes v0 = op v1, v2 and commuting would swap v1 and v2. If this 192 // is not true, then the target must implement this. 193 SrcOpIdx1 = MCID.getNumDefs(); 194 SrcOpIdx2 = SrcOpIdx1 + 1; 195 if (!MI->getOperand(SrcOpIdx1).isReg() || 196 !MI->getOperand(SrcOpIdx2).isReg()) 197 // No idea. 198 return false; 199 return true; 200 } 201 202 203 bool 204 TargetInstrInfo::isUnpredicatedTerminator(const MachineInstr *MI) const { 205 if (!MI->isTerminator()) return false; 206 207 // Conditional branch is a special case. 208 if (MI->isBranch() && !MI->isBarrier()) 209 return true; 210 if (!MI->isPredicable()) 211 return true; 212 return !isPredicated(MI); 213 } 214 215 216 bool TargetInstrInfo::PredicateInstruction(MachineInstr *MI, 217 const SmallVectorImpl<MachineOperand> &Pred) const { 218 bool MadeChange = false; 219 220 assert(!MI->isBundle() && 221 "TargetInstrInfo::PredicateInstruction() can't handle bundles"); 222 223 const MCInstrDesc &MCID = MI->getDesc(); 224 if (!MI->isPredicable()) 225 return false; 226 227 for (unsigned j = 0, i = 0, e = MI->getNumOperands(); i != e; ++i) { 228 if (MCID.OpInfo[i].isPredicate()) { 229 MachineOperand &MO = MI->getOperand(i); 230 if (MO.isReg()) { 231 MO.setReg(Pred[j].getReg()); 232 MadeChange = true; 233 } else if (MO.isImm()) { 234 MO.setImm(Pred[j].getImm()); 235 MadeChange = true; 236 } else if (MO.isMBB()) { 237 MO.setMBB(Pred[j].getMBB()); 238 MadeChange = true; 239 } 240 ++j; 241 } 242 } 243 return MadeChange; 244 } 245 246 bool TargetInstrInfo::hasLoadFromStackSlot(const MachineInstr *MI, 247 const MachineMemOperand *&MMO, 248 int &FrameIndex) const { 249 for (MachineInstr::mmo_iterator o = MI->memoperands_begin(), 250 oe = MI->memoperands_end(); 251 o != oe; 252 ++o) { 253 if ((*o)->isLoad()) { 254 if (const FixedStackPseudoSourceValue *Value = 255 dyn_cast_or_null<FixedStackPseudoSourceValue>( 256 (*o)->getPseudoValue())) { 257 FrameIndex = Value->getFrameIndex(); 258 MMO = *o; 259 return true; 260 } 261 } 262 } 263 return false; 264 } 265 266 bool TargetInstrInfo::hasStoreToStackSlot(const MachineInstr *MI, 267 const MachineMemOperand *&MMO, 268 int &FrameIndex) const { 269 for (MachineInstr::mmo_iterator o = MI->memoperands_begin(), 270 oe = MI->memoperands_end(); 271 o != oe; 272 ++o) { 273 if ((*o)->isStore()) { 274 if (const FixedStackPseudoSourceValue *Value = 275 dyn_cast_or_null<FixedStackPseudoSourceValue>( 276 (*o)->getPseudoValue())) { 277 FrameIndex = Value->getFrameIndex(); 278 MMO = *o; 279 return true; 280 } 281 } 282 } 283 return false; 284 } 285 286 bool TargetInstrInfo::getStackSlotRange(const TargetRegisterClass *RC, 287 unsigned SubIdx, unsigned &Size, 288 unsigned &Offset, 289 const TargetMachine *TM) const { 290 if (!SubIdx) { 291 Size = RC->getSize(); 292 Offset = 0; 293 return true; 294 } 295 unsigned BitSize = TM->getRegisterInfo()->getSubRegIdxSize(SubIdx); 296 // Convert bit size to byte size to be consistent with 297 // MCRegisterClass::getSize(). 298 if (BitSize % 8) 299 return false; 300 301 int BitOffset = TM->getRegisterInfo()->getSubRegIdxOffset(SubIdx); 302 if (BitOffset < 0 || BitOffset % 8) 303 return false; 304 305 Size = BitSize /= 8; 306 Offset = (unsigned)BitOffset / 8; 307 308 assert(RC->getSize() >= (Offset + Size) && "bad subregister range"); 309 310 if (!TM->getDataLayout()->isLittleEndian()) { 311 Offset = RC->getSize() - (Offset + Size); 312 } 313 return true; 314 } 315 316 void TargetInstrInfo::reMaterialize(MachineBasicBlock &MBB, 317 MachineBasicBlock::iterator I, 318 unsigned DestReg, 319 unsigned SubIdx, 320 const MachineInstr *Orig, 321 const TargetRegisterInfo &TRI) const { 322 MachineInstr *MI = MBB.getParent()->CloneMachineInstr(Orig); 323 MI->substituteRegister(MI->getOperand(0).getReg(), DestReg, SubIdx, TRI); 324 MBB.insert(I, MI); 325 } 326 327 bool 328 TargetInstrInfo::produceSameValue(const MachineInstr *MI0, 329 const MachineInstr *MI1, 330 const MachineRegisterInfo *MRI) const { 331 return MI0->isIdenticalTo(MI1, MachineInstr::IgnoreVRegDefs); 332 } 333 334 MachineInstr *TargetInstrInfo::duplicate(MachineInstr *Orig, 335 MachineFunction &MF) const { 336 assert(!Orig->isNotDuplicable() && 337 "Instruction cannot be duplicated"); 338 return MF.CloneMachineInstr(Orig); 339 } 340 341 // If the COPY instruction in MI can be folded to a stack operation, return 342 // the register class to use. 343 static const TargetRegisterClass *canFoldCopy(const MachineInstr *MI, 344 unsigned FoldIdx) { 345 assert(MI->isCopy() && "MI must be a COPY instruction"); 346 if (MI->getNumOperands() != 2) 347 return nullptr; 348 assert(FoldIdx<2 && "FoldIdx refers no nonexistent operand"); 349 350 const MachineOperand &FoldOp = MI->getOperand(FoldIdx); 351 const MachineOperand &LiveOp = MI->getOperand(1-FoldIdx); 352 353 if (FoldOp.getSubReg() || LiveOp.getSubReg()) 354 return nullptr; 355 356 unsigned FoldReg = FoldOp.getReg(); 357 unsigned LiveReg = LiveOp.getReg(); 358 359 assert(TargetRegisterInfo::isVirtualRegister(FoldReg) && 360 "Cannot fold physregs"); 361 362 const MachineRegisterInfo &MRI = MI->getParent()->getParent()->getRegInfo(); 363 const TargetRegisterClass *RC = MRI.getRegClass(FoldReg); 364 365 if (TargetRegisterInfo::isPhysicalRegister(LiveOp.getReg())) 366 return RC->contains(LiveOp.getReg()) ? RC : nullptr; 367 368 if (RC->hasSubClassEq(MRI.getRegClass(LiveReg))) 369 return RC; 370 371 // FIXME: Allow folding when register classes are memory compatible. 372 return nullptr; 373 } 374 375 bool TargetInstrInfo:: 376 canFoldMemoryOperand(const MachineInstr *MI, 377 const SmallVectorImpl<unsigned> &Ops) const { 378 return MI->isCopy() && Ops.size() == 1 && canFoldCopy(MI, Ops[0]); 379 } 380 381 static MachineInstr* foldPatchpoint(MachineFunction &MF, 382 MachineInstr *MI, 383 const SmallVectorImpl<unsigned> &Ops, 384 int FrameIndex, 385 const TargetInstrInfo &TII) { 386 unsigned StartIdx = 0; 387 switch (MI->getOpcode()) { 388 case TargetOpcode::STACKMAP: 389 StartIdx = 2; // Skip ID, nShadowBytes. 390 break; 391 case TargetOpcode::PATCHPOINT: { 392 // For PatchPoint, the call args are not foldable. 393 PatchPointOpers opers(MI); 394 StartIdx = opers.getVarIdx(); 395 break; 396 } 397 default: 398 llvm_unreachable("unexpected stackmap opcode"); 399 } 400 401 // Return false if any operands requested for folding are not foldable (not 402 // part of the stackmap's live values). 403 for (SmallVectorImpl<unsigned>::const_iterator I = Ops.begin(), E = Ops.end(); 404 I != E; ++I) { 405 if (*I < StartIdx) 406 return nullptr; 407 } 408 409 MachineInstr *NewMI = 410 MF.CreateMachineInstr(TII.get(MI->getOpcode()), MI->getDebugLoc(), true); 411 MachineInstrBuilder MIB(MF, NewMI); 412 413 // No need to fold return, the meta data, and function arguments 414 for (unsigned i = 0; i < StartIdx; ++i) 415 MIB.addOperand(MI->getOperand(i)); 416 417 for (unsigned i = StartIdx; i < MI->getNumOperands(); ++i) { 418 MachineOperand &MO = MI->getOperand(i); 419 if (std::find(Ops.begin(), Ops.end(), i) != Ops.end()) { 420 unsigned SpillSize; 421 unsigned SpillOffset; 422 // Compute the spill slot size and offset. 423 const TargetRegisterClass *RC = 424 MF.getRegInfo().getRegClass(MO.getReg()); 425 bool Valid = TII.getStackSlotRange(RC, MO.getSubReg(), SpillSize, 426 SpillOffset, &MF.getTarget()); 427 if (!Valid) 428 report_fatal_error("cannot spill patchpoint subregister operand"); 429 MIB.addImm(StackMaps::IndirectMemRefOp); 430 MIB.addImm(SpillSize); 431 MIB.addFrameIndex(FrameIndex); 432 MIB.addImm(SpillOffset); 433 } 434 else 435 MIB.addOperand(MO); 436 } 437 return NewMI; 438 } 439 440 /// foldMemoryOperand - Attempt to fold a load or store of the specified stack 441 /// slot into the specified machine instruction for the specified operand(s). 442 /// If this is possible, a new instruction is returned with the specified 443 /// operand folded, otherwise NULL is returned. The client is responsible for 444 /// removing the old instruction and adding the new one in the instruction 445 /// stream. 446 MachineInstr* 447 TargetInstrInfo::foldMemoryOperand(MachineBasicBlock::iterator MI, 448 const SmallVectorImpl<unsigned> &Ops, 449 int FI) const { 450 unsigned Flags = 0; 451 for (unsigned i = 0, e = Ops.size(); i != e; ++i) 452 if (MI->getOperand(Ops[i]).isDef()) 453 Flags |= MachineMemOperand::MOStore; 454 else 455 Flags |= MachineMemOperand::MOLoad; 456 457 MachineBasicBlock *MBB = MI->getParent(); 458 assert(MBB && "foldMemoryOperand needs an inserted instruction"); 459 MachineFunction &MF = *MBB->getParent(); 460 461 MachineInstr *NewMI = nullptr; 462 463 if (MI->getOpcode() == TargetOpcode::STACKMAP || 464 MI->getOpcode() == TargetOpcode::PATCHPOINT) { 465 // Fold stackmap/patchpoint. 466 NewMI = foldPatchpoint(MF, MI, Ops, FI, *this); 467 } else { 468 // Ask the target to do the actual folding. 469 NewMI =foldMemoryOperandImpl(MF, MI, Ops, FI); 470 } 471 472 if (NewMI) { 473 NewMI->setMemRefs(MI->memoperands_begin(), MI->memoperands_end()); 474 // Add a memory operand, foldMemoryOperandImpl doesn't do that. 475 assert((!(Flags & MachineMemOperand::MOStore) || 476 NewMI->mayStore()) && 477 "Folded a def to a non-store!"); 478 assert((!(Flags & MachineMemOperand::MOLoad) || 479 NewMI->mayLoad()) && 480 "Folded a use to a non-load!"); 481 const MachineFrameInfo &MFI = *MF.getFrameInfo(); 482 assert(MFI.getObjectOffset(FI) != -1); 483 MachineMemOperand *MMO = 484 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(FI), 485 Flags, MFI.getObjectSize(FI), 486 MFI.getObjectAlignment(FI)); 487 NewMI->addMemOperand(MF, MMO); 488 489 // FIXME: change foldMemoryOperandImpl semantics to also insert NewMI. 490 return MBB->insert(MI, NewMI); 491 } 492 493 // Straight COPY may fold as load/store. 494 if (!MI->isCopy() || Ops.size() != 1) 495 return nullptr; 496 497 const TargetRegisterClass *RC = canFoldCopy(MI, Ops[0]); 498 if (!RC) 499 return nullptr; 500 501 const MachineOperand &MO = MI->getOperand(1-Ops[0]); 502 MachineBasicBlock::iterator Pos = MI; 503 const TargetRegisterInfo *TRI = MF.getTarget().getRegisterInfo(); 504 505 if (Flags == MachineMemOperand::MOStore) 506 storeRegToStackSlot(*MBB, Pos, MO.getReg(), MO.isKill(), FI, RC, TRI); 507 else 508 loadRegFromStackSlot(*MBB, Pos, MO.getReg(), FI, RC, TRI); 509 return --Pos; 510 } 511 512 /// foldMemoryOperand - Same as the previous version except it allows folding 513 /// of any load and store from / to any address, not just from a specific 514 /// stack slot. 515 MachineInstr* 516 TargetInstrInfo::foldMemoryOperand(MachineBasicBlock::iterator MI, 517 const SmallVectorImpl<unsigned> &Ops, 518 MachineInstr* LoadMI) const { 519 assert(LoadMI->canFoldAsLoad() && "LoadMI isn't foldable!"); 520 #ifndef NDEBUG 521 for (unsigned i = 0, e = Ops.size(); i != e; ++i) 522 assert(MI->getOperand(Ops[i]).isUse() && "Folding load into def!"); 523 #endif 524 MachineBasicBlock &MBB = *MI->getParent(); 525 MachineFunction &MF = *MBB.getParent(); 526 527 // Ask the target to do the actual folding. 528 MachineInstr *NewMI = nullptr; 529 int FrameIndex = 0; 530 531 if ((MI->getOpcode() == TargetOpcode::STACKMAP || 532 MI->getOpcode() == TargetOpcode::PATCHPOINT) && 533 isLoadFromStackSlot(LoadMI, FrameIndex)) { 534 // Fold stackmap/patchpoint. 535 NewMI = foldPatchpoint(MF, MI, Ops, FrameIndex, *this); 536 } else { 537 // Ask the target to do the actual folding. 538 NewMI = foldMemoryOperandImpl(MF, MI, Ops, LoadMI); 539 } 540 541 if (!NewMI) return nullptr; 542 543 NewMI = MBB.insert(MI, NewMI); 544 545 // Copy the memoperands from the load to the folded instruction. 546 if (MI->memoperands_empty()) { 547 NewMI->setMemRefs(LoadMI->memoperands_begin(), 548 LoadMI->memoperands_end()); 549 } 550 else { 551 // Handle the rare case of folding multiple loads. 552 NewMI->setMemRefs(MI->memoperands_begin(), 553 MI->memoperands_end()); 554 for (MachineInstr::mmo_iterator I = LoadMI->memoperands_begin(), 555 E = LoadMI->memoperands_end(); I != E; ++I) { 556 NewMI->addMemOperand(MF, *I); 557 } 558 } 559 return NewMI; 560 } 561 562 bool TargetInstrInfo:: 563 isReallyTriviallyReMaterializableGeneric(const MachineInstr *MI, 564 AliasAnalysis *AA) const { 565 const MachineFunction &MF = *MI->getParent()->getParent(); 566 const MachineRegisterInfo &MRI = MF.getRegInfo(); 567 const TargetMachine &TM = MF.getTarget(); 568 const TargetInstrInfo &TII = *TM.getInstrInfo(); 569 570 // Remat clients assume operand 0 is the defined register. 571 if (!MI->getNumOperands() || !MI->getOperand(0).isReg()) 572 return false; 573 unsigned DefReg = MI->getOperand(0).getReg(); 574 575 // A sub-register definition can only be rematerialized if the instruction 576 // doesn't read the other parts of the register. Otherwise it is really a 577 // read-modify-write operation on the full virtual register which cannot be 578 // moved safely. 579 if (TargetRegisterInfo::isVirtualRegister(DefReg) && 580 MI->getOperand(0).getSubReg() && MI->readsVirtualRegister(DefReg)) 581 return false; 582 583 // A load from a fixed stack slot can be rematerialized. This may be 584 // redundant with subsequent checks, but it's target-independent, 585 // simple, and a common case. 586 int FrameIdx = 0; 587 if (TII.isLoadFromStackSlot(MI, FrameIdx) && 588 MF.getFrameInfo()->isImmutableObjectIndex(FrameIdx)) 589 return true; 590 591 // Avoid instructions obviously unsafe for remat. 592 if (MI->isNotDuplicable() || MI->mayStore() || 593 MI->hasUnmodeledSideEffects()) 594 return false; 595 596 // Don't remat inline asm. We have no idea how expensive it is 597 // even if it's side effect free. 598 if (MI->isInlineAsm()) 599 return false; 600 601 // Avoid instructions which load from potentially varying memory. 602 if (MI->mayLoad() && !MI->isInvariantLoad(AA)) 603 return false; 604 605 // If any of the registers accessed are non-constant, conservatively assume 606 // the instruction is not rematerializable. 607 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) { 608 const MachineOperand &MO = MI->getOperand(i); 609 if (!MO.isReg()) continue; 610 unsigned Reg = MO.getReg(); 611 if (Reg == 0) 612 continue; 613 614 // Check for a well-behaved physical register. 615 if (TargetRegisterInfo::isPhysicalRegister(Reg)) { 616 if (MO.isUse()) { 617 // If the physreg has no defs anywhere, it's just an ambient register 618 // and we can freely move its uses. Alternatively, if it's allocatable, 619 // it could get allocated to something with a def during allocation. 620 if (!MRI.isConstantPhysReg(Reg, MF)) 621 return false; 622 } else { 623 // A physreg def. We can't remat it. 624 return false; 625 } 626 continue; 627 } 628 629 // Only allow one virtual-register def. There may be multiple defs of the 630 // same virtual register, though. 631 if (MO.isDef() && Reg != DefReg) 632 return false; 633 634 // Don't allow any virtual-register uses. Rematting an instruction with 635 // virtual register uses would length the live ranges of the uses, which 636 // is not necessarily a good idea, certainly not "trivial". 637 if (MO.isUse()) 638 return false; 639 } 640 641 // Everything checked out. 642 return true; 643 } 644 645 /// isSchedulingBoundary - Test if the given instruction should be 646 /// considered a scheduling boundary. This primarily includes labels 647 /// and terminators. 648 bool TargetInstrInfo::isSchedulingBoundary(const MachineInstr *MI, 649 const MachineBasicBlock *MBB, 650 const MachineFunction &MF) const { 651 // Terminators and labels can't be scheduled around. 652 if (MI->isTerminator() || MI->isPosition()) 653 return true; 654 655 // Don't attempt to schedule around any instruction that defines 656 // a stack-oriented pointer, as it's unlikely to be profitable. This 657 // saves compile time, because it doesn't require every single 658 // stack slot reference to depend on the instruction that does the 659 // modification. 660 const TargetLowering &TLI = *MF.getTarget().getTargetLowering(); 661 const TargetRegisterInfo *TRI = MF.getTarget().getRegisterInfo(); 662 if (MI->modifiesRegister(TLI.getStackPointerRegisterToSaveRestore(), TRI)) 663 return true; 664 665 return false; 666 } 667 668 // Provide a global flag for disabling the PreRA hazard recognizer that targets 669 // may choose to honor. 670 bool TargetInstrInfo::usePreRAHazardRecognizer() const { 671 return !DisableHazardRecognizer; 672 } 673 674 // Default implementation of CreateTargetRAHazardRecognizer. 675 ScheduleHazardRecognizer *TargetInstrInfo:: 676 CreateTargetHazardRecognizer(const TargetMachine *TM, 677 const ScheduleDAG *DAG) const { 678 // Dummy hazard recognizer allows all instructions to issue. 679 return new ScheduleHazardRecognizer(); 680 } 681 682 // Default implementation of CreateTargetMIHazardRecognizer. 683 ScheduleHazardRecognizer *TargetInstrInfo:: 684 CreateTargetMIHazardRecognizer(const InstrItineraryData *II, 685 const ScheduleDAG *DAG) const { 686 return (ScheduleHazardRecognizer *) 687 new ScoreboardHazardRecognizer(II, DAG, "misched"); 688 } 689 690 // Default implementation of CreateTargetPostRAHazardRecognizer. 691 ScheduleHazardRecognizer *TargetInstrInfo:: 692 CreateTargetPostRAHazardRecognizer(const InstrItineraryData *II, 693 const ScheduleDAG *DAG) const { 694 return (ScheduleHazardRecognizer *) 695 new ScoreboardHazardRecognizer(II, DAG, "post-RA-sched"); 696 } 697 698 //===----------------------------------------------------------------------===// 699 // SelectionDAG latency interface. 700 //===----------------------------------------------------------------------===// 701 702 int 703 TargetInstrInfo::getOperandLatency(const InstrItineraryData *ItinData, 704 SDNode *DefNode, unsigned DefIdx, 705 SDNode *UseNode, unsigned UseIdx) const { 706 if (!ItinData || ItinData->isEmpty()) 707 return -1; 708 709 if (!DefNode->isMachineOpcode()) 710 return -1; 711 712 unsigned DefClass = get(DefNode->getMachineOpcode()).getSchedClass(); 713 if (!UseNode->isMachineOpcode()) 714 return ItinData->getOperandCycle(DefClass, DefIdx); 715 unsigned UseClass = get(UseNode->getMachineOpcode()).getSchedClass(); 716 return ItinData->getOperandLatency(DefClass, DefIdx, UseClass, UseIdx); 717 } 718 719 int TargetInstrInfo::getInstrLatency(const InstrItineraryData *ItinData, 720 SDNode *N) const { 721 if (!ItinData || ItinData->isEmpty()) 722 return 1; 723 724 if (!N->isMachineOpcode()) 725 return 1; 726 727 return ItinData->getStageLatency(get(N->getMachineOpcode()).getSchedClass()); 728 } 729 730 //===----------------------------------------------------------------------===// 731 // MachineInstr latency interface. 732 //===----------------------------------------------------------------------===// 733 734 unsigned 735 TargetInstrInfo::getNumMicroOps(const InstrItineraryData *ItinData, 736 const MachineInstr *MI) const { 737 if (!ItinData || ItinData->isEmpty()) 738 return 1; 739 740 unsigned Class = MI->getDesc().getSchedClass(); 741 int UOps = ItinData->Itineraries[Class].NumMicroOps; 742 if (UOps >= 0) 743 return UOps; 744 745 // The # of u-ops is dynamically determined. The specific target should 746 // override this function to return the right number. 747 return 1; 748 } 749 750 /// Return the default expected latency for a def based on it's opcode. 751 unsigned TargetInstrInfo::defaultDefLatency(const MCSchedModel *SchedModel, 752 const MachineInstr *DefMI) const { 753 if (DefMI->isTransient()) 754 return 0; 755 if (DefMI->mayLoad()) 756 return SchedModel->LoadLatency; 757 if (isHighLatencyDef(DefMI->getOpcode())) 758 return SchedModel->HighLatency; 759 return 1; 760 } 761 762 unsigned TargetInstrInfo::getPredicationCost(const MachineInstr *) const { 763 return 0; 764 } 765 766 unsigned TargetInstrInfo:: 767 getInstrLatency(const InstrItineraryData *ItinData, 768 const MachineInstr *MI, 769 unsigned *PredCost) const { 770 // Default to one cycle for no itinerary. However, an "empty" itinerary may 771 // still have a MinLatency property, which getStageLatency checks. 772 if (!ItinData) 773 return MI->mayLoad() ? 2 : 1; 774 775 return ItinData->getStageLatency(MI->getDesc().getSchedClass()); 776 } 777 778 bool TargetInstrInfo::hasLowDefLatency(const InstrItineraryData *ItinData, 779 const MachineInstr *DefMI, 780 unsigned DefIdx) const { 781 if (!ItinData || ItinData->isEmpty()) 782 return false; 783 784 unsigned DefClass = DefMI->getDesc().getSchedClass(); 785 int DefCycle = ItinData->getOperandCycle(DefClass, DefIdx); 786 return (DefCycle != -1 && DefCycle <= 1); 787 } 788 789 /// Both DefMI and UseMI must be valid. By default, call directly to the 790 /// itinerary. This may be overriden by the target. 791 int TargetInstrInfo:: 792 getOperandLatency(const InstrItineraryData *ItinData, 793 const MachineInstr *DefMI, unsigned DefIdx, 794 const MachineInstr *UseMI, unsigned UseIdx) const { 795 unsigned DefClass = DefMI->getDesc().getSchedClass(); 796 unsigned UseClass = UseMI->getDesc().getSchedClass(); 797 return ItinData->getOperandLatency(DefClass, DefIdx, UseClass, UseIdx); 798 } 799 800 /// If we can determine the operand latency from the def only, without itinerary 801 /// lookup, do so. Otherwise return -1. 802 int TargetInstrInfo::computeDefOperandLatency( 803 const InstrItineraryData *ItinData, 804 const MachineInstr *DefMI) const { 805 806 // Let the target hook getInstrLatency handle missing itineraries. 807 if (!ItinData) 808 return getInstrLatency(ItinData, DefMI); 809 810 if(ItinData->isEmpty()) 811 return defaultDefLatency(ItinData->SchedModel, DefMI); 812 813 // ...operand lookup required 814 return -1; 815 } 816 817 /// computeOperandLatency - Compute and return the latency of the given data 818 /// dependent def and use when the operand indices are already known. UseMI may 819 /// be NULL for an unknown use. 820 /// 821 /// FindMin may be set to get the minimum vs. expected latency. Minimum 822 /// latency is used for scheduling groups, while expected latency is for 823 /// instruction cost and critical path. 824 /// 825 /// Depending on the subtarget's itinerary properties, this may or may not need 826 /// to call getOperandLatency(). For most subtargets, we don't need DefIdx or 827 /// UseIdx to compute min latency. 828 unsigned TargetInstrInfo:: 829 computeOperandLatency(const InstrItineraryData *ItinData, 830 const MachineInstr *DefMI, unsigned DefIdx, 831 const MachineInstr *UseMI, unsigned UseIdx) const { 832 833 int DefLatency = computeDefOperandLatency(ItinData, DefMI); 834 if (DefLatency >= 0) 835 return DefLatency; 836 837 assert(ItinData && !ItinData->isEmpty() && "computeDefOperandLatency fail"); 838 839 int OperLatency = 0; 840 if (UseMI) 841 OperLatency = getOperandLatency(ItinData, DefMI, DefIdx, UseMI, UseIdx); 842 else { 843 unsigned DefClass = DefMI->getDesc().getSchedClass(); 844 OperLatency = ItinData->getOperandCycle(DefClass, DefIdx); 845 } 846 if (OperLatency >= 0) 847 return OperLatency; 848 849 // No operand latency was found. 850 unsigned InstrLatency = getInstrLatency(ItinData, DefMI); 851 852 // Expected latency is the max of the stage latency and itinerary props. 853 InstrLatency = std::max(InstrLatency, 854 defaultDefLatency(ItinData->SchedModel, DefMI)); 855 return InstrLatency; 856 } 857