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