1 //===-- TargetInstrInfo.cpp - Target Instruction Information --------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This file implements the TargetInstrInfo class. 10 // 11 //===----------------------------------------------------------------------===// 12 13 #include "llvm/CodeGen/TargetInstrInfo.h" 14 #include "llvm/CodeGen/MachineFrameInfo.h" 15 #include "llvm/CodeGen/MachineInstrBuilder.h" 16 #include "llvm/CodeGen/MachineMemOperand.h" 17 #include "llvm/CodeGen/MachineRegisterInfo.h" 18 #include "llvm/CodeGen/PseudoSourceValue.h" 19 #include "llvm/CodeGen/ScoreboardHazardRecognizer.h" 20 #include "llvm/CodeGen/StackMaps.h" 21 #include "llvm/CodeGen/TargetFrameLowering.h" 22 #include "llvm/CodeGen/TargetLowering.h" 23 #include "llvm/CodeGen/TargetRegisterInfo.h" 24 #include "llvm/CodeGen/TargetSchedule.h" 25 #include "llvm/IR/DataLayout.h" 26 #include "llvm/IR/DebugInfoMetadata.h" 27 #include "llvm/MC/MCAsmInfo.h" 28 #include "llvm/MC/MCInstrItineraries.h" 29 #include "llvm/Support/CommandLine.h" 30 #include "llvm/Support/ErrorHandling.h" 31 #include "llvm/Support/raw_ostream.h" 32 #include "llvm/Target/TargetMachine.h" 33 #include <cctype> 34 35 using namespace llvm; 36 37 static cl::opt<bool> DisableHazardRecognizer( 38 "disable-sched-hazard", cl::Hidden, cl::init(false), 39 cl::desc("Disable hazard detection during preRA scheduling")); 40 41 TargetInstrInfo::~TargetInstrInfo() { 42 } 43 44 const TargetRegisterClass* 45 TargetInstrInfo::getRegClass(const MCInstrDesc &MCID, unsigned OpNum, 46 const TargetRegisterInfo *TRI, 47 const MachineFunction &MF) const { 48 if (OpNum >= MCID.getNumOperands()) 49 return nullptr; 50 51 short RegClass = MCID.OpInfo[OpNum].RegClass; 52 if (MCID.OpInfo[OpNum].isLookupPtrRegClass()) 53 return TRI->getPointerRegClass(MF, RegClass); 54 55 // Instructions like INSERT_SUBREG do not have fixed register classes. 56 if (RegClass < 0) 57 return nullptr; 58 59 // Otherwise just look it up normally. 60 return TRI->getRegClass(RegClass); 61 } 62 63 /// insertNoop - Insert a noop into the instruction stream at the specified 64 /// point. 65 void TargetInstrInfo::insertNoop(MachineBasicBlock &MBB, 66 MachineBasicBlock::iterator MI) const { 67 llvm_unreachable("Target didn't implement insertNoop!"); 68 } 69 70 static bool isAsmComment(const char *Str, const MCAsmInfo &MAI) { 71 return strncmp(Str, MAI.getCommentString().data(), 72 MAI.getCommentString().size()) == 0; 73 } 74 75 /// Measure the specified inline asm to determine an approximation of its 76 /// length. 77 /// Comments (which run till the next SeparatorString or newline) do not 78 /// count as an instruction. 79 /// Any other non-whitespace text is considered an instruction, with 80 /// multiple instructions separated by SeparatorString or newlines. 81 /// Variable-length instructions are not handled here; this function 82 /// may be overloaded in the target code to do that. 83 /// We implement a special case of the .space directive which takes only a 84 /// single integer argument in base 10 that is the size in bytes. This is a 85 /// restricted form of the GAS directive in that we only interpret 86 /// simple--i.e. not a logical or arithmetic expression--size values without 87 /// the optional fill value. This is primarily used for creating arbitrary 88 /// sized inline asm blocks for testing purposes. 89 unsigned TargetInstrInfo::getInlineAsmLength( 90 const char *Str, 91 const MCAsmInfo &MAI, const TargetSubtargetInfo *STI) const { 92 // Count the number of instructions in the asm. 93 bool AtInsnStart = true; 94 unsigned Length = 0; 95 const unsigned MaxInstLength = MAI.getMaxInstLength(STI); 96 for (; *Str; ++Str) { 97 if (*Str == '\n' || strncmp(Str, MAI.getSeparatorString(), 98 strlen(MAI.getSeparatorString())) == 0) { 99 AtInsnStart = true; 100 } else if (isAsmComment(Str, MAI)) { 101 // Stop counting as an instruction after a comment until the next 102 // separator. 103 AtInsnStart = false; 104 } 105 106 if (AtInsnStart && !std::isspace(static_cast<unsigned char>(*Str))) { 107 unsigned AddLength = MaxInstLength; 108 if (strncmp(Str, ".space", 6) == 0) { 109 char *EStr; 110 int SpaceSize; 111 SpaceSize = strtol(Str + 6, &EStr, 10); 112 SpaceSize = SpaceSize < 0 ? 0 : SpaceSize; 113 while (*EStr != '\n' && std::isspace(static_cast<unsigned char>(*EStr))) 114 ++EStr; 115 if (*EStr == '\0' || *EStr == '\n' || 116 isAsmComment(EStr, MAI)) // Successfully parsed .space argument 117 AddLength = SpaceSize; 118 } 119 Length += AddLength; 120 AtInsnStart = false; 121 } 122 } 123 124 return Length; 125 } 126 127 /// ReplaceTailWithBranchTo - Delete the instruction OldInst and everything 128 /// after it, replacing it with an unconditional branch to NewDest. 129 void 130 TargetInstrInfo::ReplaceTailWithBranchTo(MachineBasicBlock::iterator Tail, 131 MachineBasicBlock *NewDest) const { 132 MachineBasicBlock *MBB = Tail->getParent(); 133 134 // Remove all the old successors of MBB from the CFG. 135 while (!MBB->succ_empty()) 136 MBB->removeSuccessor(MBB->succ_begin()); 137 138 // Save off the debug loc before erasing the instruction. 139 DebugLoc DL = Tail->getDebugLoc(); 140 141 // Update call site info and remove all the dead instructions 142 // from the end of MBB. 143 while (Tail != MBB->end()) { 144 auto MI = Tail++; 145 if (MI->isCall()) 146 MBB->getParent()->updateCallSiteInfo(&*MI); 147 MBB->erase(MI); 148 } 149 150 // If MBB isn't immediately before MBB, insert a branch to it. 151 if (++MachineFunction::iterator(MBB) != MachineFunction::iterator(NewDest)) 152 insertBranch(*MBB, NewDest, nullptr, SmallVector<MachineOperand, 0>(), DL); 153 MBB->addSuccessor(NewDest); 154 } 155 156 MachineInstr *TargetInstrInfo::commuteInstructionImpl(MachineInstr &MI, 157 bool NewMI, unsigned Idx1, 158 unsigned Idx2) const { 159 const MCInstrDesc &MCID = MI.getDesc(); 160 bool HasDef = MCID.getNumDefs(); 161 if (HasDef && !MI.getOperand(0).isReg()) 162 // No idea how to commute this instruction. Target should implement its own. 163 return nullptr; 164 165 unsigned CommutableOpIdx1 = Idx1; (void)CommutableOpIdx1; 166 unsigned CommutableOpIdx2 = Idx2; (void)CommutableOpIdx2; 167 assert(findCommutedOpIndices(MI, CommutableOpIdx1, CommutableOpIdx2) && 168 CommutableOpIdx1 == Idx1 && CommutableOpIdx2 == Idx2 && 169 "TargetInstrInfo::CommuteInstructionImpl(): not commutable operands."); 170 assert(MI.getOperand(Idx1).isReg() && MI.getOperand(Idx2).isReg() && 171 "This only knows how to commute register operands so far"); 172 173 Register Reg0 = HasDef ? MI.getOperand(0).getReg() : Register(); 174 Register Reg1 = MI.getOperand(Idx1).getReg(); 175 Register Reg2 = MI.getOperand(Idx2).getReg(); 176 unsigned SubReg0 = HasDef ? MI.getOperand(0).getSubReg() : 0; 177 unsigned SubReg1 = MI.getOperand(Idx1).getSubReg(); 178 unsigned SubReg2 = MI.getOperand(Idx2).getSubReg(); 179 bool Reg1IsKill = MI.getOperand(Idx1).isKill(); 180 bool Reg2IsKill = MI.getOperand(Idx2).isKill(); 181 bool Reg1IsUndef = MI.getOperand(Idx1).isUndef(); 182 bool Reg2IsUndef = MI.getOperand(Idx2).isUndef(); 183 bool Reg1IsInternal = MI.getOperand(Idx1).isInternalRead(); 184 bool Reg2IsInternal = MI.getOperand(Idx2).isInternalRead(); 185 // Avoid calling isRenamable for virtual registers since we assert that 186 // renamable property is only queried/set for physical registers. 187 bool Reg1IsRenamable = TargetRegisterInfo::isPhysicalRegister(Reg1) 188 ? MI.getOperand(Idx1).isRenamable() 189 : false; 190 bool Reg2IsRenamable = TargetRegisterInfo::isPhysicalRegister(Reg2) 191 ? MI.getOperand(Idx2).isRenamable() 192 : false; 193 // If destination is tied to either of the commuted source register, then 194 // it must be updated. 195 if (HasDef && Reg0 == Reg1 && 196 MI.getDesc().getOperandConstraint(Idx1, MCOI::TIED_TO) == 0) { 197 Reg2IsKill = false; 198 Reg0 = Reg2; 199 SubReg0 = SubReg2; 200 } else if (HasDef && Reg0 == Reg2 && 201 MI.getDesc().getOperandConstraint(Idx2, MCOI::TIED_TO) == 0) { 202 Reg1IsKill = false; 203 Reg0 = Reg1; 204 SubReg0 = SubReg1; 205 } 206 207 MachineInstr *CommutedMI = nullptr; 208 if (NewMI) { 209 // Create a new instruction. 210 MachineFunction &MF = *MI.getMF(); 211 CommutedMI = MF.CloneMachineInstr(&MI); 212 } else { 213 CommutedMI = &MI; 214 } 215 216 if (HasDef) { 217 CommutedMI->getOperand(0).setReg(Reg0); 218 CommutedMI->getOperand(0).setSubReg(SubReg0); 219 } 220 CommutedMI->getOperand(Idx2).setReg(Reg1); 221 CommutedMI->getOperand(Idx1).setReg(Reg2); 222 CommutedMI->getOperand(Idx2).setSubReg(SubReg1); 223 CommutedMI->getOperand(Idx1).setSubReg(SubReg2); 224 CommutedMI->getOperand(Idx2).setIsKill(Reg1IsKill); 225 CommutedMI->getOperand(Idx1).setIsKill(Reg2IsKill); 226 CommutedMI->getOperand(Idx2).setIsUndef(Reg1IsUndef); 227 CommutedMI->getOperand(Idx1).setIsUndef(Reg2IsUndef); 228 CommutedMI->getOperand(Idx2).setIsInternalRead(Reg1IsInternal); 229 CommutedMI->getOperand(Idx1).setIsInternalRead(Reg2IsInternal); 230 // Avoid calling setIsRenamable for virtual registers since we assert that 231 // renamable property is only queried/set for physical registers. 232 if (TargetRegisterInfo::isPhysicalRegister(Reg1)) 233 CommutedMI->getOperand(Idx2).setIsRenamable(Reg1IsRenamable); 234 if (TargetRegisterInfo::isPhysicalRegister(Reg2)) 235 CommutedMI->getOperand(Idx1).setIsRenamable(Reg2IsRenamable); 236 return CommutedMI; 237 } 238 239 MachineInstr *TargetInstrInfo::commuteInstruction(MachineInstr &MI, bool NewMI, 240 unsigned OpIdx1, 241 unsigned OpIdx2) const { 242 // If OpIdx1 or OpIdx2 is not specified, then this method is free to choose 243 // any commutable operand, which is done in findCommutedOpIndices() method 244 // called below. 245 if ((OpIdx1 == CommuteAnyOperandIndex || OpIdx2 == CommuteAnyOperandIndex) && 246 !findCommutedOpIndices(MI, OpIdx1, OpIdx2)) { 247 assert(MI.isCommutable() && 248 "Precondition violation: MI must be commutable."); 249 return nullptr; 250 } 251 return commuteInstructionImpl(MI, NewMI, OpIdx1, OpIdx2); 252 } 253 254 bool TargetInstrInfo::fixCommutedOpIndices(unsigned &ResultIdx1, 255 unsigned &ResultIdx2, 256 unsigned CommutableOpIdx1, 257 unsigned CommutableOpIdx2) { 258 if (ResultIdx1 == CommuteAnyOperandIndex && 259 ResultIdx2 == CommuteAnyOperandIndex) { 260 ResultIdx1 = CommutableOpIdx1; 261 ResultIdx2 = CommutableOpIdx2; 262 } else if (ResultIdx1 == CommuteAnyOperandIndex) { 263 if (ResultIdx2 == CommutableOpIdx1) 264 ResultIdx1 = CommutableOpIdx2; 265 else if (ResultIdx2 == CommutableOpIdx2) 266 ResultIdx1 = CommutableOpIdx1; 267 else 268 return false; 269 } else if (ResultIdx2 == CommuteAnyOperandIndex) { 270 if (ResultIdx1 == CommutableOpIdx1) 271 ResultIdx2 = CommutableOpIdx2; 272 else if (ResultIdx1 == CommutableOpIdx2) 273 ResultIdx2 = CommutableOpIdx1; 274 else 275 return false; 276 } else 277 // Check that the result operand indices match the given commutable 278 // operand indices. 279 return (ResultIdx1 == CommutableOpIdx1 && ResultIdx2 == CommutableOpIdx2) || 280 (ResultIdx1 == CommutableOpIdx2 && ResultIdx2 == CommutableOpIdx1); 281 282 return true; 283 } 284 285 bool TargetInstrInfo::findCommutedOpIndices(MachineInstr &MI, 286 unsigned &SrcOpIdx1, 287 unsigned &SrcOpIdx2) const { 288 assert(!MI.isBundle() && 289 "TargetInstrInfo::findCommutedOpIndices() can't handle bundles"); 290 291 const MCInstrDesc &MCID = MI.getDesc(); 292 if (!MCID.isCommutable()) 293 return false; 294 295 // This assumes v0 = op v1, v2 and commuting would swap v1 and v2. If this 296 // is not true, then the target must implement this. 297 unsigned CommutableOpIdx1 = MCID.getNumDefs(); 298 unsigned CommutableOpIdx2 = CommutableOpIdx1 + 1; 299 if (!fixCommutedOpIndices(SrcOpIdx1, SrcOpIdx2, 300 CommutableOpIdx1, CommutableOpIdx2)) 301 return false; 302 303 if (!MI.getOperand(SrcOpIdx1).isReg() || !MI.getOperand(SrcOpIdx2).isReg()) 304 // No idea. 305 return false; 306 return true; 307 } 308 309 bool TargetInstrInfo::isUnpredicatedTerminator(const MachineInstr &MI) const { 310 if (!MI.isTerminator()) return false; 311 312 // Conditional branch is a special case. 313 if (MI.isBranch() && !MI.isBarrier()) 314 return true; 315 if (!MI.isPredicable()) 316 return true; 317 return !isPredicated(MI); 318 } 319 320 bool TargetInstrInfo::PredicateInstruction( 321 MachineInstr &MI, ArrayRef<MachineOperand> Pred) const { 322 bool MadeChange = false; 323 324 assert(!MI.isBundle() && 325 "TargetInstrInfo::PredicateInstruction() can't handle bundles"); 326 327 const MCInstrDesc &MCID = MI.getDesc(); 328 if (!MI.isPredicable()) 329 return false; 330 331 for (unsigned j = 0, i = 0, e = MI.getNumOperands(); i != e; ++i) { 332 if (MCID.OpInfo[i].isPredicate()) { 333 MachineOperand &MO = MI.getOperand(i); 334 if (MO.isReg()) { 335 MO.setReg(Pred[j].getReg()); 336 MadeChange = true; 337 } else if (MO.isImm()) { 338 MO.setImm(Pred[j].getImm()); 339 MadeChange = true; 340 } else if (MO.isMBB()) { 341 MO.setMBB(Pred[j].getMBB()); 342 MadeChange = true; 343 } 344 ++j; 345 } 346 } 347 return MadeChange; 348 } 349 350 bool TargetInstrInfo::hasLoadFromStackSlot( 351 const MachineInstr &MI, 352 SmallVectorImpl<const MachineMemOperand *> &Accesses) const { 353 size_t StartSize = Accesses.size(); 354 for (MachineInstr::mmo_iterator o = MI.memoperands_begin(), 355 oe = MI.memoperands_end(); 356 o != oe; ++o) { 357 if ((*o)->isLoad() && 358 dyn_cast_or_null<FixedStackPseudoSourceValue>((*o)->getPseudoValue())) 359 Accesses.push_back(*o); 360 } 361 return Accesses.size() != StartSize; 362 } 363 364 bool TargetInstrInfo::hasStoreToStackSlot( 365 const MachineInstr &MI, 366 SmallVectorImpl<const MachineMemOperand *> &Accesses) const { 367 size_t StartSize = Accesses.size(); 368 for (MachineInstr::mmo_iterator o = MI.memoperands_begin(), 369 oe = MI.memoperands_end(); 370 o != oe; ++o) { 371 if ((*o)->isStore() && 372 dyn_cast_or_null<FixedStackPseudoSourceValue>((*o)->getPseudoValue())) 373 Accesses.push_back(*o); 374 } 375 return Accesses.size() != StartSize; 376 } 377 378 bool TargetInstrInfo::getStackSlotRange(const TargetRegisterClass *RC, 379 unsigned SubIdx, unsigned &Size, 380 unsigned &Offset, 381 const MachineFunction &MF) const { 382 const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo(); 383 if (!SubIdx) { 384 Size = TRI->getSpillSize(*RC); 385 Offset = 0; 386 return true; 387 } 388 unsigned BitSize = TRI->getSubRegIdxSize(SubIdx); 389 // Convert bit size to byte size. 390 if (BitSize % 8) 391 return false; 392 393 int BitOffset = TRI->getSubRegIdxOffset(SubIdx); 394 if (BitOffset < 0 || BitOffset % 8) 395 return false; 396 397 Size = BitSize /= 8; 398 Offset = (unsigned)BitOffset / 8; 399 400 assert(TRI->getSpillSize(*RC) >= (Offset + Size) && "bad subregister range"); 401 402 if (!MF.getDataLayout().isLittleEndian()) { 403 Offset = TRI->getSpillSize(*RC) - (Offset + Size); 404 } 405 return true; 406 } 407 408 void TargetInstrInfo::reMaterialize(MachineBasicBlock &MBB, 409 MachineBasicBlock::iterator I, 410 unsigned DestReg, unsigned SubIdx, 411 const MachineInstr &Orig, 412 const TargetRegisterInfo &TRI) const { 413 MachineInstr *MI = MBB.getParent()->CloneMachineInstr(&Orig); 414 MI->substituteRegister(MI->getOperand(0).getReg(), DestReg, SubIdx, TRI); 415 MBB.insert(I, MI); 416 } 417 418 bool TargetInstrInfo::produceSameValue(const MachineInstr &MI0, 419 const MachineInstr &MI1, 420 const MachineRegisterInfo *MRI) const { 421 return MI0.isIdenticalTo(MI1, MachineInstr::IgnoreVRegDefs); 422 } 423 424 MachineInstr &TargetInstrInfo::duplicate(MachineBasicBlock &MBB, 425 MachineBasicBlock::iterator InsertBefore, const MachineInstr &Orig) const { 426 assert(!Orig.isNotDuplicable() && "Instruction cannot be duplicated"); 427 MachineFunction &MF = *MBB.getParent(); 428 return MF.CloneMachineInstrBundle(MBB, InsertBefore, Orig); 429 } 430 431 // If the COPY instruction in MI can be folded to a stack operation, return 432 // the register class to use. 433 static const TargetRegisterClass *canFoldCopy(const MachineInstr &MI, 434 unsigned FoldIdx) { 435 assert(MI.isCopy() && "MI must be a COPY instruction"); 436 if (MI.getNumOperands() != 2) 437 return nullptr; 438 assert(FoldIdx<2 && "FoldIdx refers no nonexistent operand"); 439 440 const MachineOperand &FoldOp = MI.getOperand(FoldIdx); 441 const MachineOperand &LiveOp = MI.getOperand(1 - FoldIdx); 442 443 if (FoldOp.getSubReg() || LiveOp.getSubReg()) 444 return nullptr; 445 446 unsigned FoldReg = FoldOp.getReg(); 447 unsigned LiveReg = LiveOp.getReg(); 448 449 assert(TargetRegisterInfo::isVirtualRegister(FoldReg) && 450 "Cannot fold physregs"); 451 452 const MachineRegisterInfo &MRI = MI.getMF()->getRegInfo(); 453 const TargetRegisterClass *RC = MRI.getRegClass(FoldReg); 454 455 if (TargetRegisterInfo::isPhysicalRegister(LiveOp.getReg())) 456 return RC->contains(LiveOp.getReg()) ? RC : nullptr; 457 458 if (RC->hasSubClassEq(MRI.getRegClass(LiveReg))) 459 return RC; 460 461 // FIXME: Allow folding when register classes are memory compatible. 462 return nullptr; 463 } 464 465 void TargetInstrInfo::getNoop(MCInst &NopInst) const { 466 llvm_unreachable("Not implemented"); 467 } 468 469 static MachineInstr *foldPatchpoint(MachineFunction &MF, MachineInstr &MI, 470 ArrayRef<unsigned> Ops, int FrameIndex, 471 const TargetInstrInfo &TII) { 472 unsigned StartIdx = 0; 473 switch (MI.getOpcode()) { 474 case TargetOpcode::STACKMAP: { 475 // StackMapLiveValues are foldable 476 StartIdx = StackMapOpers(&MI).getVarIdx(); 477 break; 478 } 479 case TargetOpcode::PATCHPOINT: { 480 // For PatchPoint, the call args are not foldable (even if reported in the 481 // stackmap e.g. via anyregcc). 482 StartIdx = PatchPointOpers(&MI).getVarIdx(); 483 break; 484 } 485 case TargetOpcode::STATEPOINT: { 486 // For statepoints, fold deopt and gc arguments, but not call arguments. 487 StartIdx = StatepointOpers(&MI).getVarIdx(); 488 break; 489 } 490 default: 491 llvm_unreachable("unexpected stackmap opcode"); 492 } 493 494 // Return false if any operands requested for folding are not foldable (not 495 // part of the stackmap's live values). 496 for (unsigned Op : Ops) { 497 if (Op < StartIdx) 498 return nullptr; 499 } 500 501 MachineInstr *NewMI = 502 MF.CreateMachineInstr(TII.get(MI.getOpcode()), MI.getDebugLoc(), true); 503 MachineInstrBuilder MIB(MF, NewMI); 504 505 // No need to fold return, the meta data, and function arguments 506 for (unsigned i = 0; i < StartIdx; ++i) 507 MIB.add(MI.getOperand(i)); 508 509 for (unsigned i = StartIdx; i < MI.getNumOperands(); ++i) { 510 MachineOperand &MO = MI.getOperand(i); 511 if (is_contained(Ops, i)) { 512 unsigned SpillSize; 513 unsigned SpillOffset; 514 // Compute the spill slot size and offset. 515 const TargetRegisterClass *RC = 516 MF.getRegInfo().getRegClass(MO.getReg()); 517 bool Valid = 518 TII.getStackSlotRange(RC, MO.getSubReg(), SpillSize, SpillOffset, MF); 519 if (!Valid) 520 report_fatal_error("cannot spill patchpoint subregister operand"); 521 MIB.addImm(StackMaps::IndirectMemRefOp); 522 MIB.addImm(SpillSize); 523 MIB.addFrameIndex(FrameIndex); 524 MIB.addImm(SpillOffset); 525 } 526 else 527 MIB.add(MO); 528 } 529 return NewMI; 530 } 531 532 MachineInstr *TargetInstrInfo::foldMemoryOperand(MachineInstr &MI, 533 ArrayRef<unsigned> Ops, int FI, 534 LiveIntervals *LIS, 535 VirtRegMap *VRM) const { 536 auto Flags = MachineMemOperand::MONone; 537 for (unsigned OpIdx : Ops) 538 Flags |= MI.getOperand(OpIdx).isDef() ? MachineMemOperand::MOStore 539 : MachineMemOperand::MOLoad; 540 541 MachineBasicBlock *MBB = MI.getParent(); 542 assert(MBB && "foldMemoryOperand needs an inserted instruction"); 543 MachineFunction &MF = *MBB->getParent(); 544 545 // If we're not folding a load into a subreg, the size of the load is the 546 // size of the spill slot. But if we are, we need to figure out what the 547 // actual load size is. 548 int64_t MemSize = 0; 549 const MachineFrameInfo &MFI = MF.getFrameInfo(); 550 const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo(); 551 552 if (Flags & MachineMemOperand::MOStore) { 553 MemSize = MFI.getObjectSize(FI); 554 } else { 555 for (unsigned OpIdx : Ops) { 556 int64_t OpSize = MFI.getObjectSize(FI); 557 558 if (auto SubReg = MI.getOperand(OpIdx).getSubReg()) { 559 unsigned SubRegSize = TRI->getSubRegIdxSize(SubReg); 560 if (SubRegSize > 0 && !(SubRegSize % 8)) 561 OpSize = SubRegSize / 8; 562 } 563 564 MemSize = std::max(MemSize, OpSize); 565 } 566 } 567 568 assert(MemSize && "Did not expect a zero-sized stack slot"); 569 570 MachineInstr *NewMI = nullptr; 571 572 if (MI.getOpcode() == TargetOpcode::STACKMAP || 573 MI.getOpcode() == TargetOpcode::PATCHPOINT || 574 MI.getOpcode() == TargetOpcode::STATEPOINT) { 575 // Fold stackmap/patchpoint. 576 NewMI = foldPatchpoint(MF, MI, Ops, FI, *this); 577 if (NewMI) 578 MBB->insert(MI, NewMI); 579 } else { 580 // Ask the target to do the actual folding. 581 NewMI = foldMemoryOperandImpl(MF, MI, Ops, MI, FI, LIS, VRM); 582 } 583 584 if (NewMI) { 585 NewMI->setMemRefs(MF, MI.memoperands()); 586 // Add a memory operand, foldMemoryOperandImpl doesn't do that. 587 assert((!(Flags & MachineMemOperand::MOStore) || 588 NewMI->mayStore()) && 589 "Folded a def to a non-store!"); 590 assert((!(Flags & MachineMemOperand::MOLoad) || 591 NewMI->mayLoad()) && 592 "Folded a use to a non-load!"); 593 assert(MFI.getObjectOffset(FI) != -1); 594 MachineMemOperand *MMO = MF.getMachineMemOperand( 595 MachinePointerInfo::getFixedStack(MF, FI), Flags, MemSize, 596 MFI.getObjectAlignment(FI)); 597 NewMI->addMemOperand(MF, MMO); 598 599 return NewMI; 600 } 601 602 // Straight COPY may fold as load/store. 603 if (!MI.isCopy() || Ops.size() != 1) 604 return nullptr; 605 606 const TargetRegisterClass *RC = canFoldCopy(MI, Ops[0]); 607 if (!RC) 608 return nullptr; 609 610 const MachineOperand &MO = MI.getOperand(1 - Ops[0]); 611 MachineBasicBlock::iterator Pos = MI; 612 613 if (Flags == MachineMemOperand::MOStore) 614 storeRegToStackSlot(*MBB, Pos, MO.getReg(), MO.isKill(), FI, RC, TRI); 615 else 616 loadRegFromStackSlot(*MBB, Pos, MO.getReg(), FI, RC, TRI); 617 return &*--Pos; 618 } 619 620 MachineInstr *TargetInstrInfo::foldMemoryOperand(MachineInstr &MI, 621 ArrayRef<unsigned> Ops, 622 MachineInstr &LoadMI, 623 LiveIntervals *LIS) const { 624 assert(LoadMI.canFoldAsLoad() && "LoadMI isn't foldable!"); 625 #ifndef NDEBUG 626 for (unsigned OpIdx : Ops) 627 assert(MI.getOperand(OpIdx).isUse() && "Folding load into def!"); 628 #endif 629 630 MachineBasicBlock &MBB = *MI.getParent(); 631 MachineFunction &MF = *MBB.getParent(); 632 633 // Ask the target to do the actual folding. 634 MachineInstr *NewMI = nullptr; 635 int FrameIndex = 0; 636 637 if ((MI.getOpcode() == TargetOpcode::STACKMAP || 638 MI.getOpcode() == TargetOpcode::PATCHPOINT || 639 MI.getOpcode() == TargetOpcode::STATEPOINT) && 640 isLoadFromStackSlot(LoadMI, FrameIndex)) { 641 // Fold stackmap/patchpoint. 642 NewMI = foldPatchpoint(MF, MI, Ops, FrameIndex, *this); 643 if (NewMI) 644 NewMI = &*MBB.insert(MI, NewMI); 645 } else { 646 // Ask the target to do the actual folding. 647 NewMI = foldMemoryOperandImpl(MF, MI, Ops, MI, LoadMI, LIS); 648 } 649 650 if (!NewMI) 651 return nullptr; 652 653 // Copy the memoperands from the load to the folded instruction. 654 if (MI.memoperands_empty()) { 655 NewMI->setMemRefs(MF, LoadMI.memoperands()); 656 } else { 657 // Handle the rare case of folding multiple loads. 658 NewMI->setMemRefs(MF, MI.memoperands()); 659 for (MachineInstr::mmo_iterator I = LoadMI.memoperands_begin(), 660 E = LoadMI.memoperands_end(); 661 I != E; ++I) { 662 NewMI->addMemOperand(MF, *I); 663 } 664 } 665 return NewMI; 666 } 667 668 bool TargetInstrInfo::hasReassociableOperands( 669 const MachineInstr &Inst, const MachineBasicBlock *MBB) const { 670 const MachineOperand &Op1 = Inst.getOperand(1); 671 const MachineOperand &Op2 = Inst.getOperand(2); 672 const MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo(); 673 674 // We need virtual register definitions for the operands that we will 675 // reassociate. 676 MachineInstr *MI1 = nullptr; 677 MachineInstr *MI2 = nullptr; 678 if (Op1.isReg() && TargetRegisterInfo::isVirtualRegister(Op1.getReg())) 679 MI1 = MRI.getUniqueVRegDef(Op1.getReg()); 680 if (Op2.isReg() && TargetRegisterInfo::isVirtualRegister(Op2.getReg())) 681 MI2 = MRI.getUniqueVRegDef(Op2.getReg()); 682 683 // And they need to be in the trace (otherwise, they won't have a depth). 684 return MI1 && MI2 && MI1->getParent() == MBB && MI2->getParent() == MBB; 685 } 686 687 bool TargetInstrInfo::hasReassociableSibling(const MachineInstr &Inst, 688 bool &Commuted) const { 689 const MachineBasicBlock *MBB = Inst.getParent(); 690 const MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo(); 691 MachineInstr *MI1 = MRI.getUniqueVRegDef(Inst.getOperand(1).getReg()); 692 MachineInstr *MI2 = MRI.getUniqueVRegDef(Inst.getOperand(2).getReg()); 693 unsigned AssocOpcode = Inst.getOpcode(); 694 695 // If only one operand has the same opcode and it's the second source operand, 696 // the operands must be commuted. 697 Commuted = MI1->getOpcode() != AssocOpcode && MI2->getOpcode() == AssocOpcode; 698 if (Commuted) 699 std::swap(MI1, MI2); 700 701 // 1. The previous instruction must be the same type as Inst. 702 // 2. The previous instruction must have virtual register definitions for its 703 // operands in the same basic block as Inst. 704 // 3. The previous instruction's result must only be used by Inst. 705 return MI1->getOpcode() == AssocOpcode && 706 hasReassociableOperands(*MI1, MBB) && 707 MRI.hasOneNonDBGUse(MI1->getOperand(0).getReg()); 708 } 709 710 // 1. The operation must be associative and commutative. 711 // 2. The instruction must have virtual register definitions for its 712 // operands in the same basic block. 713 // 3. The instruction must have a reassociable sibling. 714 bool TargetInstrInfo::isReassociationCandidate(const MachineInstr &Inst, 715 bool &Commuted) const { 716 return isAssociativeAndCommutative(Inst) && 717 hasReassociableOperands(Inst, Inst.getParent()) && 718 hasReassociableSibling(Inst, Commuted); 719 } 720 721 // The concept of the reassociation pass is that these operations can benefit 722 // from this kind of transformation: 723 // 724 // A = ? op ? 725 // B = A op X (Prev) 726 // C = B op Y (Root) 727 // --> 728 // A = ? op ? 729 // B = X op Y 730 // C = A op B 731 // 732 // breaking the dependency between A and B, allowing them to be executed in 733 // parallel (or back-to-back in a pipeline) instead of depending on each other. 734 735 // FIXME: This has the potential to be expensive (compile time) while not 736 // improving the code at all. Some ways to limit the overhead: 737 // 1. Track successful transforms; bail out if hit rate gets too low. 738 // 2. Only enable at -O3 or some other non-default optimization level. 739 // 3. Pre-screen pattern candidates here: if an operand of the previous 740 // instruction is known to not increase the critical path, then don't match 741 // that pattern. 742 bool TargetInstrInfo::getMachineCombinerPatterns( 743 MachineInstr &Root, 744 SmallVectorImpl<MachineCombinerPattern> &Patterns) const { 745 bool Commute; 746 if (isReassociationCandidate(Root, Commute)) { 747 // We found a sequence of instructions that may be suitable for a 748 // reassociation of operands to increase ILP. Specify each commutation 749 // possibility for the Prev instruction in the sequence and let the 750 // machine combiner decide if changing the operands is worthwhile. 751 if (Commute) { 752 Patterns.push_back(MachineCombinerPattern::REASSOC_AX_YB); 753 Patterns.push_back(MachineCombinerPattern::REASSOC_XA_YB); 754 } else { 755 Patterns.push_back(MachineCombinerPattern::REASSOC_AX_BY); 756 Patterns.push_back(MachineCombinerPattern::REASSOC_XA_BY); 757 } 758 return true; 759 } 760 761 return false; 762 } 763 764 /// Return true when a code sequence can improve loop throughput. 765 bool 766 TargetInstrInfo::isThroughputPattern(MachineCombinerPattern Pattern) const { 767 return false; 768 } 769 770 /// Attempt the reassociation transformation to reduce critical path length. 771 /// See the above comments before getMachineCombinerPatterns(). 772 void TargetInstrInfo::reassociateOps( 773 MachineInstr &Root, MachineInstr &Prev, 774 MachineCombinerPattern Pattern, 775 SmallVectorImpl<MachineInstr *> &InsInstrs, 776 SmallVectorImpl<MachineInstr *> &DelInstrs, 777 DenseMap<unsigned, unsigned> &InstrIdxForVirtReg) const { 778 MachineFunction *MF = Root.getMF(); 779 MachineRegisterInfo &MRI = MF->getRegInfo(); 780 const TargetInstrInfo *TII = MF->getSubtarget().getInstrInfo(); 781 const TargetRegisterInfo *TRI = MF->getSubtarget().getRegisterInfo(); 782 const TargetRegisterClass *RC = Root.getRegClassConstraint(0, TII, TRI); 783 784 // This array encodes the operand index for each parameter because the 785 // operands may be commuted. Each row corresponds to a pattern value, 786 // and each column specifies the index of A, B, X, Y. 787 unsigned OpIdx[4][4] = { 788 { 1, 1, 2, 2 }, 789 { 1, 2, 2, 1 }, 790 { 2, 1, 1, 2 }, 791 { 2, 2, 1, 1 } 792 }; 793 794 int Row; 795 switch (Pattern) { 796 case MachineCombinerPattern::REASSOC_AX_BY: Row = 0; break; 797 case MachineCombinerPattern::REASSOC_AX_YB: Row = 1; break; 798 case MachineCombinerPattern::REASSOC_XA_BY: Row = 2; break; 799 case MachineCombinerPattern::REASSOC_XA_YB: Row = 3; break; 800 default: llvm_unreachable("unexpected MachineCombinerPattern"); 801 } 802 803 MachineOperand &OpA = Prev.getOperand(OpIdx[Row][0]); 804 MachineOperand &OpB = Root.getOperand(OpIdx[Row][1]); 805 MachineOperand &OpX = Prev.getOperand(OpIdx[Row][2]); 806 MachineOperand &OpY = Root.getOperand(OpIdx[Row][3]); 807 MachineOperand &OpC = Root.getOperand(0); 808 809 unsigned RegA = OpA.getReg(); 810 unsigned RegB = OpB.getReg(); 811 unsigned RegX = OpX.getReg(); 812 unsigned RegY = OpY.getReg(); 813 unsigned RegC = OpC.getReg(); 814 815 if (TargetRegisterInfo::isVirtualRegister(RegA)) 816 MRI.constrainRegClass(RegA, RC); 817 if (TargetRegisterInfo::isVirtualRegister(RegB)) 818 MRI.constrainRegClass(RegB, RC); 819 if (TargetRegisterInfo::isVirtualRegister(RegX)) 820 MRI.constrainRegClass(RegX, RC); 821 if (TargetRegisterInfo::isVirtualRegister(RegY)) 822 MRI.constrainRegClass(RegY, RC); 823 if (TargetRegisterInfo::isVirtualRegister(RegC)) 824 MRI.constrainRegClass(RegC, RC); 825 826 // Create a new virtual register for the result of (X op Y) instead of 827 // recycling RegB because the MachineCombiner's computation of the critical 828 // path requires a new register definition rather than an existing one. 829 unsigned NewVR = MRI.createVirtualRegister(RC); 830 InstrIdxForVirtReg.insert(std::make_pair(NewVR, 0)); 831 832 unsigned Opcode = Root.getOpcode(); 833 bool KillA = OpA.isKill(); 834 bool KillX = OpX.isKill(); 835 bool KillY = OpY.isKill(); 836 837 // Create new instructions for insertion. 838 MachineInstrBuilder MIB1 = 839 BuildMI(*MF, Prev.getDebugLoc(), TII->get(Opcode), NewVR) 840 .addReg(RegX, getKillRegState(KillX)) 841 .addReg(RegY, getKillRegState(KillY)); 842 MachineInstrBuilder MIB2 = 843 BuildMI(*MF, Root.getDebugLoc(), TII->get(Opcode), RegC) 844 .addReg(RegA, getKillRegState(KillA)) 845 .addReg(NewVR, getKillRegState(true)); 846 847 setSpecialOperandAttr(Root, Prev, *MIB1, *MIB2); 848 849 // Record new instructions for insertion and old instructions for deletion. 850 InsInstrs.push_back(MIB1); 851 InsInstrs.push_back(MIB2); 852 DelInstrs.push_back(&Prev); 853 DelInstrs.push_back(&Root); 854 } 855 856 void TargetInstrInfo::genAlternativeCodeSequence( 857 MachineInstr &Root, MachineCombinerPattern Pattern, 858 SmallVectorImpl<MachineInstr *> &InsInstrs, 859 SmallVectorImpl<MachineInstr *> &DelInstrs, 860 DenseMap<unsigned, unsigned> &InstIdxForVirtReg) const { 861 MachineRegisterInfo &MRI = Root.getMF()->getRegInfo(); 862 863 // Select the previous instruction in the sequence based on the input pattern. 864 MachineInstr *Prev = nullptr; 865 switch (Pattern) { 866 case MachineCombinerPattern::REASSOC_AX_BY: 867 case MachineCombinerPattern::REASSOC_XA_BY: 868 Prev = MRI.getUniqueVRegDef(Root.getOperand(1).getReg()); 869 break; 870 case MachineCombinerPattern::REASSOC_AX_YB: 871 case MachineCombinerPattern::REASSOC_XA_YB: 872 Prev = MRI.getUniqueVRegDef(Root.getOperand(2).getReg()); 873 break; 874 default: 875 break; 876 } 877 878 assert(Prev && "Unknown pattern for machine combiner"); 879 880 reassociateOps(Root, *Prev, Pattern, InsInstrs, DelInstrs, InstIdxForVirtReg); 881 } 882 883 bool TargetInstrInfo::isReallyTriviallyReMaterializableGeneric( 884 const MachineInstr &MI, AliasAnalysis *AA) const { 885 const MachineFunction &MF = *MI.getMF(); 886 const MachineRegisterInfo &MRI = MF.getRegInfo(); 887 888 // Remat clients assume operand 0 is the defined register. 889 if (!MI.getNumOperands() || !MI.getOperand(0).isReg()) 890 return false; 891 unsigned DefReg = MI.getOperand(0).getReg(); 892 893 // A sub-register definition can only be rematerialized if the instruction 894 // doesn't read the other parts of the register. Otherwise it is really a 895 // read-modify-write operation on the full virtual register which cannot be 896 // moved safely. 897 if (TargetRegisterInfo::isVirtualRegister(DefReg) && 898 MI.getOperand(0).getSubReg() && MI.readsVirtualRegister(DefReg)) 899 return false; 900 901 // A load from a fixed stack slot can be rematerialized. This may be 902 // redundant with subsequent checks, but it's target-independent, 903 // simple, and a common case. 904 int FrameIdx = 0; 905 if (isLoadFromStackSlot(MI, FrameIdx) && 906 MF.getFrameInfo().isImmutableObjectIndex(FrameIdx)) 907 return true; 908 909 // Avoid instructions obviously unsafe for remat. 910 if (MI.isNotDuplicable() || MI.mayStore() || MI.mayRaiseFPException() || 911 MI.hasUnmodeledSideEffects()) 912 return false; 913 914 // Don't remat inline asm. We have no idea how expensive it is 915 // even if it's side effect free. 916 if (MI.isInlineAsm()) 917 return false; 918 919 // Avoid instructions which load from potentially varying memory. 920 if (MI.mayLoad() && !MI.isDereferenceableInvariantLoad(AA)) 921 return false; 922 923 // If any of the registers accessed are non-constant, conservatively assume 924 // the instruction is not rematerializable. 925 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) { 926 const MachineOperand &MO = MI.getOperand(i); 927 if (!MO.isReg()) continue; 928 unsigned Reg = MO.getReg(); 929 if (Reg == 0) 930 continue; 931 932 // Check for a well-behaved physical register. 933 if (TargetRegisterInfo::isPhysicalRegister(Reg)) { 934 if (MO.isUse()) { 935 // If the physreg has no defs anywhere, it's just an ambient register 936 // and we can freely move its uses. Alternatively, if it's allocatable, 937 // it could get allocated to something with a def during allocation. 938 if (!MRI.isConstantPhysReg(Reg)) 939 return false; 940 } else { 941 // A physreg def. We can't remat it. 942 return false; 943 } 944 continue; 945 } 946 947 // Only allow one virtual-register def. There may be multiple defs of the 948 // same virtual register, though. 949 if (MO.isDef() && Reg != DefReg) 950 return false; 951 952 // Don't allow any virtual-register uses. Rematting an instruction with 953 // virtual register uses would length the live ranges of the uses, which 954 // is not necessarily a good idea, certainly not "trivial". 955 if (MO.isUse()) 956 return false; 957 } 958 959 // Everything checked out. 960 return true; 961 } 962 963 int TargetInstrInfo::getSPAdjust(const MachineInstr &MI) const { 964 const MachineFunction *MF = MI.getMF(); 965 const TargetFrameLowering *TFI = MF->getSubtarget().getFrameLowering(); 966 bool StackGrowsDown = 967 TFI->getStackGrowthDirection() == TargetFrameLowering::StackGrowsDown; 968 969 unsigned FrameSetupOpcode = getCallFrameSetupOpcode(); 970 unsigned FrameDestroyOpcode = getCallFrameDestroyOpcode(); 971 972 if (!isFrameInstr(MI)) 973 return 0; 974 975 int SPAdj = TFI->alignSPAdjust(getFrameSize(MI)); 976 977 if ((!StackGrowsDown && MI.getOpcode() == FrameSetupOpcode) || 978 (StackGrowsDown && MI.getOpcode() == FrameDestroyOpcode)) 979 SPAdj = -SPAdj; 980 981 return SPAdj; 982 } 983 984 /// isSchedulingBoundary - Test if the given instruction should be 985 /// considered a scheduling boundary. This primarily includes labels 986 /// and terminators. 987 bool TargetInstrInfo::isSchedulingBoundary(const MachineInstr &MI, 988 const MachineBasicBlock *MBB, 989 const MachineFunction &MF) const { 990 // Terminators and labels can't be scheduled around. 991 if (MI.isTerminator() || MI.isPosition()) 992 return true; 993 994 // Don't attempt to schedule around any instruction that defines 995 // a stack-oriented pointer, as it's unlikely to be profitable. This 996 // saves compile time, because it doesn't require every single 997 // stack slot reference to depend on the instruction that does the 998 // modification. 999 const TargetLowering &TLI = *MF.getSubtarget().getTargetLowering(); 1000 const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo(); 1001 return MI.modifiesRegister(TLI.getStackPointerRegisterToSaveRestore(), TRI); 1002 } 1003 1004 // Provide a global flag for disabling the PreRA hazard recognizer that targets 1005 // may choose to honor. 1006 bool TargetInstrInfo::usePreRAHazardRecognizer() const { 1007 return !DisableHazardRecognizer; 1008 } 1009 1010 // Default implementation of CreateTargetRAHazardRecognizer. 1011 ScheduleHazardRecognizer *TargetInstrInfo:: 1012 CreateTargetHazardRecognizer(const TargetSubtargetInfo *STI, 1013 const ScheduleDAG *DAG) const { 1014 // Dummy hazard recognizer allows all instructions to issue. 1015 return new ScheduleHazardRecognizer(); 1016 } 1017 1018 // Default implementation of CreateTargetMIHazardRecognizer. 1019 ScheduleHazardRecognizer *TargetInstrInfo:: 1020 CreateTargetMIHazardRecognizer(const InstrItineraryData *II, 1021 const ScheduleDAG *DAG) const { 1022 return (ScheduleHazardRecognizer *) 1023 new ScoreboardHazardRecognizer(II, DAG, "machine-scheduler"); 1024 } 1025 1026 // Default implementation of CreateTargetPostRAHazardRecognizer. 1027 ScheduleHazardRecognizer *TargetInstrInfo:: 1028 CreateTargetPostRAHazardRecognizer(const InstrItineraryData *II, 1029 const ScheduleDAG *DAG) const { 1030 return (ScheduleHazardRecognizer *) 1031 new ScoreboardHazardRecognizer(II, DAG, "post-RA-sched"); 1032 } 1033 1034 //===----------------------------------------------------------------------===// 1035 // SelectionDAG latency interface. 1036 //===----------------------------------------------------------------------===// 1037 1038 int 1039 TargetInstrInfo::getOperandLatency(const InstrItineraryData *ItinData, 1040 SDNode *DefNode, unsigned DefIdx, 1041 SDNode *UseNode, unsigned UseIdx) const { 1042 if (!ItinData || ItinData->isEmpty()) 1043 return -1; 1044 1045 if (!DefNode->isMachineOpcode()) 1046 return -1; 1047 1048 unsigned DefClass = get(DefNode->getMachineOpcode()).getSchedClass(); 1049 if (!UseNode->isMachineOpcode()) 1050 return ItinData->getOperandCycle(DefClass, DefIdx); 1051 unsigned UseClass = get(UseNode->getMachineOpcode()).getSchedClass(); 1052 return ItinData->getOperandLatency(DefClass, DefIdx, UseClass, UseIdx); 1053 } 1054 1055 int TargetInstrInfo::getInstrLatency(const InstrItineraryData *ItinData, 1056 SDNode *N) const { 1057 if (!ItinData || ItinData->isEmpty()) 1058 return 1; 1059 1060 if (!N->isMachineOpcode()) 1061 return 1; 1062 1063 return ItinData->getStageLatency(get(N->getMachineOpcode()).getSchedClass()); 1064 } 1065 1066 //===----------------------------------------------------------------------===// 1067 // MachineInstr latency interface. 1068 //===----------------------------------------------------------------------===// 1069 1070 unsigned TargetInstrInfo::getNumMicroOps(const InstrItineraryData *ItinData, 1071 const MachineInstr &MI) const { 1072 if (!ItinData || ItinData->isEmpty()) 1073 return 1; 1074 1075 unsigned Class = MI.getDesc().getSchedClass(); 1076 int UOps = ItinData->Itineraries[Class].NumMicroOps; 1077 if (UOps >= 0) 1078 return UOps; 1079 1080 // The # of u-ops is dynamically determined. The specific target should 1081 // override this function to return the right number. 1082 return 1; 1083 } 1084 1085 /// Return the default expected latency for a def based on it's opcode. 1086 unsigned TargetInstrInfo::defaultDefLatency(const MCSchedModel &SchedModel, 1087 const MachineInstr &DefMI) const { 1088 if (DefMI.isTransient()) 1089 return 0; 1090 if (DefMI.mayLoad()) 1091 return SchedModel.LoadLatency; 1092 if (isHighLatencyDef(DefMI.getOpcode())) 1093 return SchedModel.HighLatency; 1094 return 1; 1095 } 1096 1097 unsigned TargetInstrInfo::getPredicationCost(const MachineInstr &) const { 1098 return 0; 1099 } 1100 1101 unsigned TargetInstrInfo::getInstrLatency(const InstrItineraryData *ItinData, 1102 const MachineInstr &MI, 1103 unsigned *PredCost) const { 1104 // Default to one cycle for no itinerary. However, an "empty" itinerary may 1105 // still have a MinLatency property, which getStageLatency checks. 1106 if (!ItinData) 1107 return MI.mayLoad() ? 2 : 1; 1108 1109 return ItinData->getStageLatency(MI.getDesc().getSchedClass()); 1110 } 1111 1112 bool TargetInstrInfo::hasLowDefLatency(const TargetSchedModel &SchedModel, 1113 const MachineInstr &DefMI, 1114 unsigned DefIdx) const { 1115 const InstrItineraryData *ItinData = SchedModel.getInstrItineraries(); 1116 if (!ItinData || ItinData->isEmpty()) 1117 return false; 1118 1119 unsigned DefClass = DefMI.getDesc().getSchedClass(); 1120 int DefCycle = ItinData->getOperandCycle(DefClass, DefIdx); 1121 return (DefCycle != -1 && DefCycle <= 1); 1122 } 1123 1124 Optional<ParamLoadedValue> 1125 TargetInstrInfo::describeLoadedValue(const MachineInstr &MI) const { 1126 const MachineFunction *MF = MI.getMF(); 1127 const MachineOperand *Op = nullptr; 1128 DIExpression *Expr = DIExpression::get(MF->getFunction().getContext(), {});; 1129 const MachineOperand *SrcRegOp, *DestRegOp; 1130 1131 if (isCopyInstr(MI, SrcRegOp, DestRegOp)) { 1132 Op = SrcRegOp; 1133 return ParamLoadedValue(Op, Expr); 1134 } else if (MI.isMoveImmediate()) { 1135 Op = &MI.getOperand(1); 1136 return ParamLoadedValue(Op, Expr); 1137 } else if (MI.hasOneMemOperand()) { 1138 int64_t Offset; 1139 const auto &TRI = MF->getSubtarget().getRegisterInfo(); 1140 const auto &TII = MF->getSubtarget().getInstrInfo(); 1141 const MachineOperand *BaseOp; 1142 1143 if (!TII->getMemOperandWithOffset(MI, BaseOp, Offset, TRI)) 1144 return None; 1145 1146 Expr = DIExpression::prepend(Expr, DIExpression::DerefAfter, Offset); 1147 Op = BaseOp; 1148 return ParamLoadedValue(Op, Expr); 1149 } 1150 1151 return None; 1152 } 1153 1154 /// Both DefMI and UseMI must be valid. By default, call directly to the 1155 /// itinerary. This may be overriden by the target. 1156 int TargetInstrInfo::getOperandLatency(const InstrItineraryData *ItinData, 1157 const MachineInstr &DefMI, 1158 unsigned DefIdx, 1159 const MachineInstr &UseMI, 1160 unsigned UseIdx) const { 1161 unsigned DefClass = DefMI.getDesc().getSchedClass(); 1162 unsigned UseClass = UseMI.getDesc().getSchedClass(); 1163 return ItinData->getOperandLatency(DefClass, DefIdx, UseClass, UseIdx); 1164 } 1165 1166 /// If we can determine the operand latency from the def only, without itinerary 1167 /// lookup, do so. Otherwise return -1. 1168 int TargetInstrInfo::computeDefOperandLatency( 1169 const InstrItineraryData *ItinData, const MachineInstr &DefMI) const { 1170 1171 // Let the target hook getInstrLatency handle missing itineraries. 1172 if (!ItinData) 1173 return getInstrLatency(ItinData, DefMI); 1174 1175 if(ItinData->isEmpty()) 1176 return defaultDefLatency(ItinData->SchedModel, DefMI); 1177 1178 // ...operand lookup required 1179 return -1; 1180 } 1181 1182 bool TargetInstrInfo::getRegSequenceInputs( 1183 const MachineInstr &MI, unsigned DefIdx, 1184 SmallVectorImpl<RegSubRegPairAndIdx> &InputRegs) const { 1185 assert((MI.isRegSequence() || 1186 MI.isRegSequenceLike()) && "Instruction do not have the proper type"); 1187 1188 if (!MI.isRegSequence()) 1189 return getRegSequenceLikeInputs(MI, DefIdx, InputRegs); 1190 1191 // We are looking at: 1192 // Def = REG_SEQUENCE v0, sub0, v1, sub1, ... 1193 assert(DefIdx == 0 && "REG_SEQUENCE only has one def"); 1194 for (unsigned OpIdx = 1, EndOpIdx = MI.getNumOperands(); OpIdx != EndOpIdx; 1195 OpIdx += 2) { 1196 const MachineOperand &MOReg = MI.getOperand(OpIdx); 1197 if (MOReg.isUndef()) 1198 continue; 1199 const MachineOperand &MOSubIdx = MI.getOperand(OpIdx + 1); 1200 assert(MOSubIdx.isImm() && 1201 "One of the subindex of the reg_sequence is not an immediate"); 1202 // Record Reg:SubReg, SubIdx. 1203 InputRegs.push_back(RegSubRegPairAndIdx(MOReg.getReg(), MOReg.getSubReg(), 1204 (unsigned)MOSubIdx.getImm())); 1205 } 1206 return true; 1207 } 1208 1209 bool TargetInstrInfo::getExtractSubregInputs( 1210 const MachineInstr &MI, unsigned DefIdx, 1211 RegSubRegPairAndIdx &InputReg) const { 1212 assert((MI.isExtractSubreg() || 1213 MI.isExtractSubregLike()) && "Instruction do not have the proper type"); 1214 1215 if (!MI.isExtractSubreg()) 1216 return getExtractSubregLikeInputs(MI, DefIdx, InputReg); 1217 1218 // We are looking at: 1219 // Def = EXTRACT_SUBREG v0.sub1, sub0. 1220 assert(DefIdx == 0 && "EXTRACT_SUBREG only has one def"); 1221 const MachineOperand &MOReg = MI.getOperand(1); 1222 if (MOReg.isUndef()) 1223 return false; 1224 const MachineOperand &MOSubIdx = MI.getOperand(2); 1225 assert(MOSubIdx.isImm() && 1226 "The subindex of the extract_subreg is not an immediate"); 1227 1228 InputReg.Reg = MOReg.getReg(); 1229 InputReg.SubReg = MOReg.getSubReg(); 1230 InputReg.SubIdx = (unsigned)MOSubIdx.getImm(); 1231 return true; 1232 } 1233 1234 bool TargetInstrInfo::getInsertSubregInputs( 1235 const MachineInstr &MI, unsigned DefIdx, 1236 RegSubRegPair &BaseReg, RegSubRegPairAndIdx &InsertedReg) const { 1237 assert((MI.isInsertSubreg() || 1238 MI.isInsertSubregLike()) && "Instruction do not have the proper type"); 1239 1240 if (!MI.isInsertSubreg()) 1241 return getInsertSubregLikeInputs(MI, DefIdx, BaseReg, InsertedReg); 1242 1243 // We are looking at: 1244 // Def = INSERT_SEQUENCE v0, v1, sub0. 1245 assert(DefIdx == 0 && "INSERT_SUBREG only has one def"); 1246 const MachineOperand &MOBaseReg = MI.getOperand(1); 1247 const MachineOperand &MOInsertedReg = MI.getOperand(2); 1248 if (MOInsertedReg.isUndef()) 1249 return false; 1250 const MachineOperand &MOSubIdx = MI.getOperand(3); 1251 assert(MOSubIdx.isImm() && 1252 "One of the subindex of the reg_sequence is not an immediate"); 1253 BaseReg.Reg = MOBaseReg.getReg(); 1254 BaseReg.SubReg = MOBaseReg.getSubReg(); 1255 1256 InsertedReg.Reg = MOInsertedReg.getReg(); 1257 InsertedReg.SubReg = MOInsertedReg.getSubReg(); 1258 InsertedReg.SubIdx = (unsigned)MOSubIdx.getImm(); 1259 return true; 1260 } 1261