10b57cec5SDimitry Andric //===-- TargetInstrInfo.cpp - Target Instruction Information --------------===//
20b57cec5SDimitry Andric //
30b57cec5SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
40b57cec5SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
50b57cec5SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
60b57cec5SDimitry Andric //
70b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
80b57cec5SDimitry Andric //
90b57cec5SDimitry Andric // This file implements the TargetInstrInfo class.
100b57cec5SDimitry Andric //
110b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
120b57cec5SDimitry Andric 
130b57cec5SDimitry Andric #include "llvm/CodeGen/TargetInstrInfo.h"
145ffd83dbSDimitry Andric #include "llvm/ADT/StringExtras.h"
1581ad6265SDimitry Andric #include "llvm/BinaryFormat/Dwarf.h"
16bdd1243dSDimitry Andric #include "llvm/CodeGen/MachineCombinerPattern.h"
170b57cec5SDimitry Andric #include "llvm/CodeGen/MachineFrameInfo.h"
180b57cec5SDimitry Andric #include "llvm/CodeGen/MachineInstrBuilder.h"
190b57cec5SDimitry Andric #include "llvm/CodeGen/MachineMemOperand.h"
200b57cec5SDimitry Andric #include "llvm/CodeGen/MachineRegisterInfo.h"
21480093f4SDimitry Andric #include "llvm/CodeGen/MachineScheduler.h"
22fe013be4SDimitry Andric #include "llvm/CodeGen/MachineTraceMetrics.h"
230b57cec5SDimitry Andric #include "llvm/CodeGen/PseudoSourceValue.h"
240b57cec5SDimitry Andric #include "llvm/CodeGen/ScoreboardHazardRecognizer.h"
250b57cec5SDimitry Andric #include "llvm/CodeGen/StackMaps.h"
260b57cec5SDimitry Andric #include "llvm/CodeGen/TargetFrameLowering.h"
270b57cec5SDimitry Andric #include "llvm/CodeGen/TargetLowering.h"
280b57cec5SDimitry Andric #include "llvm/CodeGen/TargetRegisterInfo.h"
290b57cec5SDimitry Andric #include "llvm/CodeGen/TargetSchedule.h"
300b57cec5SDimitry Andric #include "llvm/IR/DataLayout.h"
318bcb0991SDimitry Andric #include "llvm/IR/DebugInfoMetadata.h"
320b57cec5SDimitry Andric #include "llvm/MC/MCAsmInfo.h"
330b57cec5SDimitry Andric #include "llvm/MC/MCInstrItineraries.h"
340b57cec5SDimitry Andric #include "llvm/Support/CommandLine.h"
350b57cec5SDimitry Andric #include "llvm/Support/ErrorHandling.h"
360b57cec5SDimitry Andric #include "llvm/Support/raw_ostream.h"
37*c9157d92SDimitry Andric #include "llvm/Target/TargetMachine.h"
380b57cec5SDimitry Andric 
390b57cec5SDimitry Andric using namespace llvm;
400b57cec5SDimitry Andric 
410b57cec5SDimitry Andric static cl::opt<bool> DisableHazardRecognizer(
420b57cec5SDimitry Andric   "disable-sched-hazard", cl::Hidden, cl::init(false),
430b57cec5SDimitry Andric   cl::desc("Disable hazard detection during preRA scheduling"));
440b57cec5SDimitry Andric 
4581ad6265SDimitry Andric TargetInstrInfo::~TargetInstrInfo() = default;
460b57cec5SDimitry Andric 
470b57cec5SDimitry Andric const TargetRegisterClass*
getRegClass(const MCInstrDesc & MCID,unsigned OpNum,const TargetRegisterInfo * TRI,const MachineFunction & MF) const480b57cec5SDimitry Andric TargetInstrInfo::getRegClass(const MCInstrDesc &MCID, unsigned OpNum,
490b57cec5SDimitry Andric                              const TargetRegisterInfo *TRI,
500b57cec5SDimitry Andric                              const MachineFunction &MF) const {
510b57cec5SDimitry Andric   if (OpNum >= MCID.getNumOperands())
520b57cec5SDimitry Andric     return nullptr;
530b57cec5SDimitry Andric 
54bdd1243dSDimitry Andric   short RegClass = MCID.operands()[OpNum].RegClass;
55bdd1243dSDimitry Andric   if (MCID.operands()[OpNum].isLookupPtrRegClass())
560b57cec5SDimitry Andric     return TRI->getPointerRegClass(MF, RegClass);
570b57cec5SDimitry Andric 
580b57cec5SDimitry Andric   // Instructions like INSERT_SUBREG do not have fixed register classes.
590b57cec5SDimitry Andric   if (RegClass < 0)
600b57cec5SDimitry Andric     return nullptr;
610b57cec5SDimitry Andric 
620b57cec5SDimitry Andric   // Otherwise just look it up normally.
630b57cec5SDimitry Andric   return TRI->getRegClass(RegClass);
640b57cec5SDimitry Andric }
650b57cec5SDimitry Andric 
660b57cec5SDimitry Andric /// insertNoop - Insert a noop into the instruction stream at the specified
670b57cec5SDimitry Andric /// point.
insertNoop(MachineBasicBlock & MBB,MachineBasicBlock::iterator MI) const680b57cec5SDimitry Andric void TargetInstrInfo::insertNoop(MachineBasicBlock &MBB,
690b57cec5SDimitry Andric                                  MachineBasicBlock::iterator MI) const {
700b57cec5SDimitry Andric   llvm_unreachable("Target didn't implement insertNoop!");
710b57cec5SDimitry Andric }
720b57cec5SDimitry Andric 
73e8d8bef9SDimitry Andric /// insertNoops - Insert noops into the instruction stream at the specified
74e8d8bef9SDimitry Andric /// point.
insertNoops(MachineBasicBlock & MBB,MachineBasicBlock::iterator MI,unsigned Quantity) const75e8d8bef9SDimitry Andric void TargetInstrInfo::insertNoops(MachineBasicBlock &MBB,
76e8d8bef9SDimitry Andric                                   MachineBasicBlock::iterator MI,
77e8d8bef9SDimitry Andric                                   unsigned Quantity) const {
78e8d8bef9SDimitry Andric   for (unsigned i = 0; i < Quantity; ++i)
79e8d8bef9SDimitry Andric     insertNoop(MBB, MI);
80e8d8bef9SDimitry Andric }
81e8d8bef9SDimitry Andric 
isAsmComment(const char * Str,const MCAsmInfo & MAI)820b57cec5SDimitry Andric static bool isAsmComment(const char *Str, const MCAsmInfo &MAI) {
830b57cec5SDimitry Andric   return strncmp(Str, MAI.getCommentString().data(),
840b57cec5SDimitry Andric                  MAI.getCommentString().size()) == 0;
850b57cec5SDimitry Andric }
860b57cec5SDimitry Andric 
870b57cec5SDimitry Andric /// Measure the specified inline asm to determine an approximation of its
880b57cec5SDimitry Andric /// length.
890b57cec5SDimitry Andric /// Comments (which run till the next SeparatorString or newline) do not
900b57cec5SDimitry Andric /// count as an instruction.
910b57cec5SDimitry Andric /// Any other non-whitespace text is considered an instruction, with
920b57cec5SDimitry Andric /// multiple instructions separated by SeparatorString or newlines.
930b57cec5SDimitry Andric /// Variable-length instructions are not handled here; this function
940b57cec5SDimitry Andric /// may be overloaded in the target code to do that.
950b57cec5SDimitry Andric /// We implement a special case of the .space directive which takes only a
960b57cec5SDimitry Andric /// single integer argument in base 10 that is the size in bytes. This is a
970b57cec5SDimitry Andric /// restricted form of the GAS directive in that we only interpret
980b57cec5SDimitry Andric /// simple--i.e. not a logical or arithmetic expression--size values without
990b57cec5SDimitry Andric /// the optional fill value. This is primarily used for creating arbitrary
1000b57cec5SDimitry Andric /// sized inline asm blocks for testing purposes.
getInlineAsmLength(const char * Str,const MCAsmInfo & MAI,const TargetSubtargetInfo * STI) const1010b57cec5SDimitry Andric unsigned TargetInstrInfo::getInlineAsmLength(
1020b57cec5SDimitry Andric   const char *Str,
1030b57cec5SDimitry Andric   const MCAsmInfo &MAI, const TargetSubtargetInfo *STI) const {
1040b57cec5SDimitry Andric   // Count the number of instructions in the asm.
1050b57cec5SDimitry Andric   bool AtInsnStart = true;
1060b57cec5SDimitry Andric   unsigned Length = 0;
1070b57cec5SDimitry Andric   const unsigned MaxInstLength = MAI.getMaxInstLength(STI);
1080b57cec5SDimitry Andric   for (; *Str; ++Str) {
1090b57cec5SDimitry Andric     if (*Str == '\n' || strncmp(Str, MAI.getSeparatorString(),
1100b57cec5SDimitry Andric                                 strlen(MAI.getSeparatorString())) == 0) {
1110b57cec5SDimitry Andric       AtInsnStart = true;
1120b57cec5SDimitry Andric     } else if (isAsmComment(Str, MAI)) {
1130b57cec5SDimitry Andric       // Stop counting as an instruction after a comment until the next
1140b57cec5SDimitry Andric       // separator.
1150b57cec5SDimitry Andric       AtInsnStart = false;
1160b57cec5SDimitry Andric     }
1170b57cec5SDimitry Andric 
1185ffd83dbSDimitry Andric     if (AtInsnStart && !isSpace(static_cast<unsigned char>(*Str))) {
1190b57cec5SDimitry Andric       unsigned AddLength = MaxInstLength;
1200b57cec5SDimitry Andric       if (strncmp(Str, ".space", 6) == 0) {
1210b57cec5SDimitry Andric         char *EStr;
1220b57cec5SDimitry Andric         int SpaceSize;
1230b57cec5SDimitry Andric         SpaceSize = strtol(Str + 6, &EStr, 10);
1240b57cec5SDimitry Andric         SpaceSize = SpaceSize < 0 ? 0 : SpaceSize;
1255ffd83dbSDimitry Andric         while (*EStr != '\n' && isSpace(static_cast<unsigned char>(*EStr)))
1260b57cec5SDimitry Andric           ++EStr;
1270b57cec5SDimitry Andric         if (*EStr == '\0' || *EStr == '\n' ||
1280b57cec5SDimitry Andric             isAsmComment(EStr, MAI)) // Successfully parsed .space argument
1290b57cec5SDimitry Andric           AddLength = SpaceSize;
1300b57cec5SDimitry Andric       }
1310b57cec5SDimitry Andric       Length += AddLength;
1320b57cec5SDimitry Andric       AtInsnStart = false;
1330b57cec5SDimitry Andric     }
1340b57cec5SDimitry Andric   }
1350b57cec5SDimitry Andric 
1360b57cec5SDimitry Andric   return Length;
1370b57cec5SDimitry Andric }
1380b57cec5SDimitry Andric 
1390b57cec5SDimitry Andric /// ReplaceTailWithBranchTo - Delete the instruction OldInst and everything
1400b57cec5SDimitry Andric /// after it, replacing it with an unconditional branch to NewDest.
1410b57cec5SDimitry Andric void
ReplaceTailWithBranchTo(MachineBasicBlock::iterator Tail,MachineBasicBlock * NewDest) const1420b57cec5SDimitry Andric TargetInstrInfo::ReplaceTailWithBranchTo(MachineBasicBlock::iterator Tail,
1430b57cec5SDimitry Andric                                          MachineBasicBlock *NewDest) const {
1440b57cec5SDimitry Andric   MachineBasicBlock *MBB = Tail->getParent();
1450b57cec5SDimitry Andric 
1460b57cec5SDimitry Andric   // Remove all the old successors of MBB from the CFG.
1470b57cec5SDimitry Andric   while (!MBB->succ_empty())
1480b57cec5SDimitry Andric     MBB->removeSuccessor(MBB->succ_begin());
1490b57cec5SDimitry Andric 
1500b57cec5SDimitry Andric   // Save off the debug loc before erasing the instruction.
1510b57cec5SDimitry Andric   DebugLoc DL = Tail->getDebugLoc();
1520b57cec5SDimitry Andric 
1530b57cec5SDimitry Andric   // Update call site info and remove all the dead instructions
1540b57cec5SDimitry Andric   // from the end of MBB.
1550b57cec5SDimitry Andric   while (Tail != MBB->end()) {
1560b57cec5SDimitry Andric     auto MI = Tail++;
1575ffd83dbSDimitry Andric     if (MI->shouldUpdateCallSiteInfo())
1588bcb0991SDimitry Andric       MBB->getParent()->eraseCallSiteInfo(&*MI);
1590b57cec5SDimitry Andric     MBB->erase(MI);
1600b57cec5SDimitry Andric   }
1610b57cec5SDimitry Andric 
1620b57cec5SDimitry Andric   // If MBB isn't immediately before MBB, insert a branch to it.
1630b57cec5SDimitry Andric   if (++MachineFunction::iterator(MBB) != MachineFunction::iterator(NewDest))
1640b57cec5SDimitry Andric     insertBranch(*MBB, NewDest, nullptr, SmallVector<MachineOperand, 0>(), DL);
1650b57cec5SDimitry Andric   MBB->addSuccessor(NewDest);
1660b57cec5SDimitry Andric }
1670b57cec5SDimitry Andric 
commuteInstructionImpl(MachineInstr & MI,bool NewMI,unsigned Idx1,unsigned Idx2) const1680b57cec5SDimitry Andric MachineInstr *TargetInstrInfo::commuteInstructionImpl(MachineInstr &MI,
1690b57cec5SDimitry Andric                                                       bool NewMI, unsigned Idx1,
1700b57cec5SDimitry Andric                                                       unsigned Idx2) const {
1710b57cec5SDimitry Andric   const MCInstrDesc &MCID = MI.getDesc();
1720b57cec5SDimitry Andric   bool HasDef = MCID.getNumDefs();
1730b57cec5SDimitry Andric   if (HasDef && !MI.getOperand(0).isReg())
1740b57cec5SDimitry Andric     // No idea how to commute this instruction. Target should implement its own.
1750b57cec5SDimitry Andric     return nullptr;
1760b57cec5SDimitry Andric 
1770b57cec5SDimitry Andric   unsigned CommutableOpIdx1 = Idx1; (void)CommutableOpIdx1;
1780b57cec5SDimitry Andric   unsigned CommutableOpIdx2 = Idx2; (void)CommutableOpIdx2;
1790b57cec5SDimitry Andric   assert(findCommutedOpIndices(MI, CommutableOpIdx1, CommutableOpIdx2) &&
1800b57cec5SDimitry Andric          CommutableOpIdx1 == Idx1 && CommutableOpIdx2 == Idx2 &&
1810b57cec5SDimitry Andric          "TargetInstrInfo::CommuteInstructionImpl(): not commutable operands.");
1820b57cec5SDimitry Andric   assert(MI.getOperand(Idx1).isReg() && MI.getOperand(Idx2).isReg() &&
1830b57cec5SDimitry Andric          "This only knows how to commute register operands so far");
1840b57cec5SDimitry Andric 
1850b57cec5SDimitry Andric   Register Reg0 = HasDef ? MI.getOperand(0).getReg() : Register();
1860b57cec5SDimitry Andric   Register Reg1 = MI.getOperand(Idx1).getReg();
1870b57cec5SDimitry Andric   Register Reg2 = MI.getOperand(Idx2).getReg();
1880b57cec5SDimitry Andric   unsigned SubReg0 = HasDef ? MI.getOperand(0).getSubReg() : 0;
1890b57cec5SDimitry Andric   unsigned SubReg1 = MI.getOperand(Idx1).getSubReg();
1900b57cec5SDimitry Andric   unsigned SubReg2 = MI.getOperand(Idx2).getSubReg();
1910b57cec5SDimitry Andric   bool Reg1IsKill = MI.getOperand(Idx1).isKill();
1920b57cec5SDimitry Andric   bool Reg2IsKill = MI.getOperand(Idx2).isKill();
1930b57cec5SDimitry Andric   bool Reg1IsUndef = MI.getOperand(Idx1).isUndef();
1940b57cec5SDimitry Andric   bool Reg2IsUndef = MI.getOperand(Idx2).isUndef();
1950b57cec5SDimitry Andric   bool Reg1IsInternal = MI.getOperand(Idx1).isInternalRead();
1960b57cec5SDimitry Andric   bool Reg2IsInternal = MI.getOperand(Idx2).isInternalRead();
1970b57cec5SDimitry Andric   // Avoid calling isRenamable for virtual registers since we assert that
1980b57cec5SDimitry Andric   // renamable property is only queried/set for physical registers.
199bdd1243dSDimitry Andric   bool Reg1IsRenamable =
200bdd1243dSDimitry Andric       Reg1.isPhysical() ? MI.getOperand(Idx1).isRenamable() : false;
201bdd1243dSDimitry Andric   bool Reg2IsRenamable =
202bdd1243dSDimitry Andric       Reg2.isPhysical() ? MI.getOperand(Idx2).isRenamable() : false;
2030b57cec5SDimitry Andric   // If destination is tied to either of the commuted source register, then
2040b57cec5SDimitry Andric   // it must be updated.
2050b57cec5SDimitry Andric   if (HasDef && Reg0 == Reg1 &&
2060b57cec5SDimitry Andric       MI.getDesc().getOperandConstraint(Idx1, MCOI::TIED_TO) == 0) {
2070b57cec5SDimitry Andric     Reg2IsKill = false;
2080b57cec5SDimitry Andric     Reg0 = Reg2;
2090b57cec5SDimitry Andric     SubReg0 = SubReg2;
2100b57cec5SDimitry Andric   } else if (HasDef && Reg0 == Reg2 &&
2110b57cec5SDimitry Andric              MI.getDesc().getOperandConstraint(Idx2, MCOI::TIED_TO) == 0) {
2120b57cec5SDimitry Andric     Reg1IsKill = false;
2130b57cec5SDimitry Andric     Reg0 = Reg1;
2140b57cec5SDimitry Andric     SubReg0 = SubReg1;
2150b57cec5SDimitry Andric   }
2160b57cec5SDimitry Andric 
2170b57cec5SDimitry Andric   MachineInstr *CommutedMI = nullptr;
2180b57cec5SDimitry Andric   if (NewMI) {
2190b57cec5SDimitry Andric     // Create a new instruction.
2200b57cec5SDimitry Andric     MachineFunction &MF = *MI.getMF();
2210b57cec5SDimitry Andric     CommutedMI = MF.CloneMachineInstr(&MI);
2220b57cec5SDimitry Andric   } else {
2230b57cec5SDimitry Andric     CommutedMI = &MI;
2240b57cec5SDimitry Andric   }
2250b57cec5SDimitry Andric 
2260b57cec5SDimitry Andric   if (HasDef) {
2270b57cec5SDimitry Andric     CommutedMI->getOperand(0).setReg(Reg0);
2280b57cec5SDimitry Andric     CommutedMI->getOperand(0).setSubReg(SubReg0);
2290b57cec5SDimitry Andric   }
2300b57cec5SDimitry Andric   CommutedMI->getOperand(Idx2).setReg(Reg1);
2310b57cec5SDimitry Andric   CommutedMI->getOperand(Idx1).setReg(Reg2);
2320b57cec5SDimitry Andric   CommutedMI->getOperand(Idx2).setSubReg(SubReg1);
2330b57cec5SDimitry Andric   CommutedMI->getOperand(Idx1).setSubReg(SubReg2);
2340b57cec5SDimitry Andric   CommutedMI->getOperand(Idx2).setIsKill(Reg1IsKill);
2350b57cec5SDimitry Andric   CommutedMI->getOperand(Idx1).setIsKill(Reg2IsKill);
2360b57cec5SDimitry Andric   CommutedMI->getOperand(Idx2).setIsUndef(Reg1IsUndef);
2370b57cec5SDimitry Andric   CommutedMI->getOperand(Idx1).setIsUndef(Reg2IsUndef);
2380b57cec5SDimitry Andric   CommutedMI->getOperand(Idx2).setIsInternalRead(Reg1IsInternal);
2390b57cec5SDimitry Andric   CommutedMI->getOperand(Idx1).setIsInternalRead(Reg2IsInternal);
2400b57cec5SDimitry Andric   // Avoid calling setIsRenamable for virtual registers since we assert that
2410b57cec5SDimitry Andric   // renamable property is only queried/set for physical registers.
242bdd1243dSDimitry Andric   if (Reg1.isPhysical())
2430b57cec5SDimitry Andric     CommutedMI->getOperand(Idx2).setIsRenamable(Reg1IsRenamable);
244bdd1243dSDimitry Andric   if (Reg2.isPhysical())
2450b57cec5SDimitry Andric     CommutedMI->getOperand(Idx1).setIsRenamable(Reg2IsRenamable);
2460b57cec5SDimitry Andric   return CommutedMI;
2470b57cec5SDimitry Andric }
2480b57cec5SDimitry Andric 
commuteInstruction(MachineInstr & MI,bool NewMI,unsigned OpIdx1,unsigned OpIdx2) const2490b57cec5SDimitry Andric MachineInstr *TargetInstrInfo::commuteInstruction(MachineInstr &MI, bool NewMI,
2500b57cec5SDimitry Andric                                                   unsigned OpIdx1,
2510b57cec5SDimitry Andric                                                   unsigned OpIdx2) const {
2520b57cec5SDimitry Andric   // If OpIdx1 or OpIdx2 is not specified, then this method is free to choose
2530b57cec5SDimitry Andric   // any commutable operand, which is done in findCommutedOpIndices() method
2540b57cec5SDimitry Andric   // called below.
2550b57cec5SDimitry Andric   if ((OpIdx1 == CommuteAnyOperandIndex || OpIdx2 == CommuteAnyOperandIndex) &&
2560b57cec5SDimitry Andric       !findCommutedOpIndices(MI, OpIdx1, OpIdx2)) {
2570b57cec5SDimitry Andric     assert(MI.isCommutable() &&
2580b57cec5SDimitry Andric            "Precondition violation: MI must be commutable.");
2590b57cec5SDimitry Andric     return nullptr;
2600b57cec5SDimitry Andric   }
2610b57cec5SDimitry Andric   return commuteInstructionImpl(MI, NewMI, OpIdx1, OpIdx2);
2620b57cec5SDimitry Andric }
2630b57cec5SDimitry Andric 
fixCommutedOpIndices(unsigned & ResultIdx1,unsigned & ResultIdx2,unsigned CommutableOpIdx1,unsigned CommutableOpIdx2)2640b57cec5SDimitry Andric bool TargetInstrInfo::fixCommutedOpIndices(unsigned &ResultIdx1,
2650b57cec5SDimitry Andric                                            unsigned &ResultIdx2,
2660b57cec5SDimitry Andric                                            unsigned CommutableOpIdx1,
2670b57cec5SDimitry Andric                                            unsigned CommutableOpIdx2) {
2680b57cec5SDimitry Andric   if (ResultIdx1 == CommuteAnyOperandIndex &&
2690b57cec5SDimitry Andric       ResultIdx2 == CommuteAnyOperandIndex) {
2700b57cec5SDimitry Andric     ResultIdx1 = CommutableOpIdx1;
2710b57cec5SDimitry Andric     ResultIdx2 = CommutableOpIdx2;
2720b57cec5SDimitry Andric   } else if (ResultIdx1 == CommuteAnyOperandIndex) {
2730b57cec5SDimitry Andric     if (ResultIdx2 == CommutableOpIdx1)
2740b57cec5SDimitry Andric       ResultIdx1 = CommutableOpIdx2;
2750b57cec5SDimitry Andric     else if (ResultIdx2 == CommutableOpIdx2)
2760b57cec5SDimitry Andric       ResultIdx1 = CommutableOpIdx1;
2770b57cec5SDimitry Andric     else
2780b57cec5SDimitry Andric       return false;
2790b57cec5SDimitry Andric   } else if (ResultIdx2 == CommuteAnyOperandIndex) {
2800b57cec5SDimitry Andric     if (ResultIdx1 == CommutableOpIdx1)
2810b57cec5SDimitry Andric       ResultIdx2 = CommutableOpIdx2;
2820b57cec5SDimitry Andric     else if (ResultIdx1 == CommutableOpIdx2)
2830b57cec5SDimitry Andric       ResultIdx2 = CommutableOpIdx1;
2840b57cec5SDimitry Andric     else
2850b57cec5SDimitry Andric       return false;
2860b57cec5SDimitry Andric   } else
2870b57cec5SDimitry Andric     // Check that the result operand indices match the given commutable
2880b57cec5SDimitry Andric     // operand indices.
2890b57cec5SDimitry Andric     return (ResultIdx1 == CommutableOpIdx1 && ResultIdx2 == CommutableOpIdx2) ||
2900b57cec5SDimitry Andric            (ResultIdx1 == CommutableOpIdx2 && ResultIdx2 == CommutableOpIdx1);
2910b57cec5SDimitry Andric 
2920b57cec5SDimitry Andric   return true;
2930b57cec5SDimitry Andric }
2940b57cec5SDimitry Andric 
findCommutedOpIndices(const MachineInstr & MI,unsigned & SrcOpIdx1,unsigned & SrcOpIdx2) const2958bcb0991SDimitry Andric bool TargetInstrInfo::findCommutedOpIndices(const MachineInstr &MI,
2960b57cec5SDimitry Andric                                             unsigned &SrcOpIdx1,
2970b57cec5SDimitry Andric                                             unsigned &SrcOpIdx2) const {
2980b57cec5SDimitry Andric   assert(!MI.isBundle() &&
2990b57cec5SDimitry Andric          "TargetInstrInfo::findCommutedOpIndices() can't handle bundles");
3000b57cec5SDimitry Andric 
3010b57cec5SDimitry Andric   const MCInstrDesc &MCID = MI.getDesc();
3020b57cec5SDimitry Andric   if (!MCID.isCommutable())
3030b57cec5SDimitry Andric     return false;
3040b57cec5SDimitry Andric 
3050b57cec5SDimitry Andric   // This assumes v0 = op v1, v2 and commuting would swap v1 and v2. If this
3060b57cec5SDimitry Andric   // is not true, then the target must implement this.
3070b57cec5SDimitry Andric   unsigned CommutableOpIdx1 = MCID.getNumDefs();
3080b57cec5SDimitry Andric   unsigned CommutableOpIdx2 = CommutableOpIdx1 + 1;
3090b57cec5SDimitry Andric   if (!fixCommutedOpIndices(SrcOpIdx1, SrcOpIdx2,
3100b57cec5SDimitry Andric                             CommutableOpIdx1, CommutableOpIdx2))
3110b57cec5SDimitry Andric     return false;
3120b57cec5SDimitry Andric 
3130b57cec5SDimitry Andric   if (!MI.getOperand(SrcOpIdx1).isReg() || !MI.getOperand(SrcOpIdx2).isReg())
3140b57cec5SDimitry Andric     // No idea.
3150b57cec5SDimitry Andric     return false;
3160b57cec5SDimitry Andric   return true;
3170b57cec5SDimitry Andric }
3180b57cec5SDimitry Andric 
isUnpredicatedTerminator(const MachineInstr & MI) const3190b57cec5SDimitry Andric bool TargetInstrInfo::isUnpredicatedTerminator(const MachineInstr &MI) const {
3200b57cec5SDimitry Andric   if (!MI.isTerminator()) return false;
3210b57cec5SDimitry Andric 
3220b57cec5SDimitry Andric   // Conditional branch is a special case.
3230b57cec5SDimitry Andric   if (MI.isBranch() && !MI.isBarrier())
3240b57cec5SDimitry Andric     return true;
3250b57cec5SDimitry Andric   if (!MI.isPredicable())
3260b57cec5SDimitry Andric     return true;
3270b57cec5SDimitry Andric   return !isPredicated(MI);
3280b57cec5SDimitry Andric }
3290b57cec5SDimitry Andric 
PredicateInstruction(MachineInstr & MI,ArrayRef<MachineOperand> Pred) const3300b57cec5SDimitry Andric bool TargetInstrInfo::PredicateInstruction(
3310b57cec5SDimitry Andric     MachineInstr &MI, ArrayRef<MachineOperand> Pred) const {
3320b57cec5SDimitry Andric   bool MadeChange = false;
3330b57cec5SDimitry Andric 
3340b57cec5SDimitry Andric   assert(!MI.isBundle() &&
3350b57cec5SDimitry Andric          "TargetInstrInfo::PredicateInstruction() can't handle bundles");
3360b57cec5SDimitry Andric 
3370b57cec5SDimitry Andric   const MCInstrDesc &MCID = MI.getDesc();
3380b57cec5SDimitry Andric   if (!MI.isPredicable())
3390b57cec5SDimitry Andric     return false;
3400b57cec5SDimitry Andric 
3410b57cec5SDimitry Andric   for (unsigned j = 0, i = 0, e = MI.getNumOperands(); i != e; ++i) {
342bdd1243dSDimitry Andric     if (MCID.operands()[i].isPredicate()) {
3430b57cec5SDimitry Andric       MachineOperand &MO = MI.getOperand(i);
3440b57cec5SDimitry Andric       if (MO.isReg()) {
3450b57cec5SDimitry Andric         MO.setReg(Pred[j].getReg());
3460b57cec5SDimitry Andric         MadeChange = true;
3470b57cec5SDimitry Andric       } else if (MO.isImm()) {
3480b57cec5SDimitry Andric         MO.setImm(Pred[j].getImm());
3490b57cec5SDimitry Andric         MadeChange = true;
3500b57cec5SDimitry Andric       } else if (MO.isMBB()) {
3510b57cec5SDimitry Andric         MO.setMBB(Pred[j].getMBB());
3520b57cec5SDimitry Andric         MadeChange = true;
3530b57cec5SDimitry Andric       }
3540b57cec5SDimitry Andric       ++j;
3550b57cec5SDimitry Andric     }
3560b57cec5SDimitry Andric   }
3570b57cec5SDimitry Andric   return MadeChange;
3580b57cec5SDimitry Andric }
3590b57cec5SDimitry Andric 
hasLoadFromStackSlot(const MachineInstr & MI,SmallVectorImpl<const MachineMemOperand * > & Accesses) const3600b57cec5SDimitry Andric bool TargetInstrInfo::hasLoadFromStackSlot(
3610b57cec5SDimitry Andric     const MachineInstr &MI,
3620b57cec5SDimitry Andric     SmallVectorImpl<const MachineMemOperand *> &Accesses) const {
3630b57cec5SDimitry Andric   size_t StartSize = Accesses.size();
3640b57cec5SDimitry Andric   for (MachineInstr::mmo_iterator o = MI.memoperands_begin(),
3650b57cec5SDimitry Andric                                   oe = MI.memoperands_end();
3660b57cec5SDimitry Andric        o != oe; ++o) {
3670b57cec5SDimitry Andric     if ((*o)->isLoad() &&
368349cc55cSDimitry Andric         isa_and_nonnull<FixedStackPseudoSourceValue>((*o)->getPseudoValue()))
3690b57cec5SDimitry Andric       Accesses.push_back(*o);
3700b57cec5SDimitry Andric   }
3710b57cec5SDimitry Andric   return Accesses.size() != StartSize;
3720b57cec5SDimitry Andric }
3730b57cec5SDimitry Andric 
hasStoreToStackSlot(const MachineInstr & MI,SmallVectorImpl<const MachineMemOperand * > & Accesses) const3740b57cec5SDimitry Andric bool TargetInstrInfo::hasStoreToStackSlot(
3750b57cec5SDimitry Andric     const MachineInstr &MI,
3760b57cec5SDimitry Andric     SmallVectorImpl<const MachineMemOperand *> &Accesses) const {
3770b57cec5SDimitry Andric   size_t StartSize = Accesses.size();
3780b57cec5SDimitry Andric   for (MachineInstr::mmo_iterator o = MI.memoperands_begin(),
3790b57cec5SDimitry Andric                                   oe = MI.memoperands_end();
3800b57cec5SDimitry Andric        o != oe; ++o) {
3810b57cec5SDimitry Andric     if ((*o)->isStore() &&
382349cc55cSDimitry Andric         isa_and_nonnull<FixedStackPseudoSourceValue>((*o)->getPseudoValue()))
3830b57cec5SDimitry Andric       Accesses.push_back(*o);
3840b57cec5SDimitry Andric   }
3850b57cec5SDimitry Andric   return Accesses.size() != StartSize;
3860b57cec5SDimitry Andric }
3870b57cec5SDimitry Andric 
getStackSlotRange(const TargetRegisterClass * RC,unsigned SubIdx,unsigned & Size,unsigned & Offset,const MachineFunction & MF) const3880b57cec5SDimitry Andric bool TargetInstrInfo::getStackSlotRange(const TargetRegisterClass *RC,
3890b57cec5SDimitry Andric                                         unsigned SubIdx, unsigned &Size,
3900b57cec5SDimitry Andric                                         unsigned &Offset,
3910b57cec5SDimitry Andric                                         const MachineFunction &MF) const {
3920b57cec5SDimitry Andric   const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
3930b57cec5SDimitry Andric   if (!SubIdx) {
3940b57cec5SDimitry Andric     Size = TRI->getSpillSize(*RC);
3950b57cec5SDimitry Andric     Offset = 0;
3960b57cec5SDimitry Andric     return true;
3970b57cec5SDimitry Andric   }
3980b57cec5SDimitry Andric   unsigned BitSize = TRI->getSubRegIdxSize(SubIdx);
3990b57cec5SDimitry Andric   // Convert bit size to byte size.
4000b57cec5SDimitry Andric   if (BitSize % 8)
4010b57cec5SDimitry Andric     return false;
4020b57cec5SDimitry Andric 
4030b57cec5SDimitry Andric   int BitOffset = TRI->getSubRegIdxOffset(SubIdx);
4040b57cec5SDimitry Andric   if (BitOffset < 0 || BitOffset % 8)
4050b57cec5SDimitry Andric     return false;
4060b57cec5SDimitry Andric 
4078bcb0991SDimitry Andric   Size = BitSize / 8;
4080b57cec5SDimitry Andric   Offset = (unsigned)BitOffset / 8;
4090b57cec5SDimitry Andric 
4100b57cec5SDimitry Andric   assert(TRI->getSpillSize(*RC) >= (Offset + Size) && "bad subregister range");
4110b57cec5SDimitry Andric 
4120b57cec5SDimitry Andric   if (!MF.getDataLayout().isLittleEndian()) {
4130b57cec5SDimitry Andric     Offset = TRI->getSpillSize(*RC) - (Offset + Size);
4140b57cec5SDimitry Andric   }
4150b57cec5SDimitry Andric   return true;
4160b57cec5SDimitry Andric }
4170b57cec5SDimitry Andric 
reMaterialize(MachineBasicBlock & MBB,MachineBasicBlock::iterator I,Register DestReg,unsigned SubIdx,const MachineInstr & Orig,const TargetRegisterInfo & TRI) const4180b57cec5SDimitry Andric void TargetInstrInfo::reMaterialize(MachineBasicBlock &MBB,
4190b57cec5SDimitry Andric                                     MachineBasicBlock::iterator I,
4205ffd83dbSDimitry Andric                                     Register DestReg, unsigned SubIdx,
4210b57cec5SDimitry Andric                                     const MachineInstr &Orig,
4220b57cec5SDimitry Andric                                     const TargetRegisterInfo &TRI) const {
4230b57cec5SDimitry Andric   MachineInstr *MI = MBB.getParent()->CloneMachineInstr(&Orig);
4240b57cec5SDimitry Andric   MI->substituteRegister(MI->getOperand(0).getReg(), DestReg, SubIdx, TRI);
4250b57cec5SDimitry Andric   MBB.insert(I, MI);
4260b57cec5SDimitry Andric }
4270b57cec5SDimitry Andric 
produceSameValue(const MachineInstr & MI0,const MachineInstr & MI1,const MachineRegisterInfo * MRI) const4280b57cec5SDimitry Andric bool TargetInstrInfo::produceSameValue(const MachineInstr &MI0,
4290b57cec5SDimitry Andric                                        const MachineInstr &MI1,
4300b57cec5SDimitry Andric                                        const MachineRegisterInfo *MRI) const {
4310b57cec5SDimitry Andric   return MI0.isIdenticalTo(MI1, MachineInstr::IgnoreVRegDefs);
4320b57cec5SDimitry Andric }
4330b57cec5SDimitry Andric 
434*c9157d92SDimitry Andric MachineInstr &
duplicate(MachineBasicBlock & MBB,MachineBasicBlock::iterator InsertBefore,const MachineInstr & Orig) const435*c9157d92SDimitry Andric TargetInstrInfo::duplicate(MachineBasicBlock &MBB,
436*c9157d92SDimitry Andric                            MachineBasicBlock::iterator InsertBefore,
437*c9157d92SDimitry Andric                            const MachineInstr &Orig) const {
4380b57cec5SDimitry Andric   MachineFunction &MF = *MBB.getParent();
439*c9157d92SDimitry Andric   // CFI instructions are marked as non-duplicable, because Darwin compact
440*c9157d92SDimitry Andric   // unwind info emission can't handle multiple prologue setups.
441*c9157d92SDimitry Andric   assert((!Orig.isNotDuplicable() ||
442*c9157d92SDimitry Andric           (!MF.getTarget().getTargetTriple().isOSDarwin() &&
443*c9157d92SDimitry Andric            Orig.isCFIInstruction())) &&
444*c9157d92SDimitry Andric          "Instruction cannot be duplicated");
445*c9157d92SDimitry Andric 
4460eae32dcSDimitry Andric   return MF.cloneMachineInstrBundle(MBB, InsertBefore, Orig);
4470b57cec5SDimitry Andric }
4480b57cec5SDimitry Andric 
4490b57cec5SDimitry Andric // If the COPY instruction in MI can be folded to a stack operation, return
4500b57cec5SDimitry Andric // the register class to use.
canFoldCopy(const MachineInstr & MI,const TargetInstrInfo & TII,unsigned FoldIdx)4510b57cec5SDimitry Andric static const TargetRegisterClass *canFoldCopy(const MachineInstr &MI,
452*c9157d92SDimitry Andric                                               const TargetInstrInfo &TII,
4530b57cec5SDimitry Andric                                               unsigned FoldIdx) {
454*c9157d92SDimitry Andric   assert(TII.isCopyInstr(MI) && "MI must be a COPY instruction");
4550b57cec5SDimitry Andric   if (MI.getNumOperands() != 2)
4560b57cec5SDimitry Andric     return nullptr;
4570b57cec5SDimitry Andric   assert(FoldIdx<2 && "FoldIdx refers no nonexistent operand");
4580b57cec5SDimitry Andric 
4590b57cec5SDimitry Andric   const MachineOperand &FoldOp = MI.getOperand(FoldIdx);
4600b57cec5SDimitry Andric   const MachineOperand &LiveOp = MI.getOperand(1 - FoldIdx);
4610b57cec5SDimitry Andric 
4620b57cec5SDimitry Andric   if (FoldOp.getSubReg() || LiveOp.getSubReg())
4630b57cec5SDimitry Andric     return nullptr;
4640b57cec5SDimitry Andric 
4658bcb0991SDimitry Andric   Register FoldReg = FoldOp.getReg();
4668bcb0991SDimitry Andric   Register LiveReg = LiveOp.getReg();
4670b57cec5SDimitry Andric 
468bdd1243dSDimitry Andric   assert(FoldReg.isVirtual() && "Cannot fold physregs");
4690b57cec5SDimitry Andric 
4700b57cec5SDimitry Andric   const MachineRegisterInfo &MRI = MI.getMF()->getRegInfo();
4710b57cec5SDimitry Andric   const TargetRegisterClass *RC = MRI.getRegClass(FoldReg);
4720b57cec5SDimitry Andric 
473bdd1243dSDimitry Andric   if (LiveOp.getReg().isPhysical())
4740b57cec5SDimitry Andric     return RC->contains(LiveOp.getReg()) ? RC : nullptr;
4750b57cec5SDimitry Andric 
4760b57cec5SDimitry Andric   if (RC->hasSubClassEq(MRI.getRegClass(LiveReg)))
4770b57cec5SDimitry Andric     return RC;
4780b57cec5SDimitry Andric 
4790b57cec5SDimitry Andric   // FIXME: Allow folding when register classes are memory compatible.
4800b57cec5SDimitry Andric   return nullptr;
4810b57cec5SDimitry Andric }
4820b57cec5SDimitry Andric 
getNop() const483fe6060f1SDimitry Andric MCInst TargetInstrInfo::getNop() const { llvm_unreachable("Not implemented"); }
484fe6060f1SDimitry Andric 
485fe6060f1SDimitry Andric std::pair<unsigned, unsigned>
getPatchpointUnfoldableRange(const MachineInstr & MI) const486fe6060f1SDimitry Andric TargetInstrInfo::getPatchpointUnfoldableRange(const MachineInstr &MI) const {
487fe6060f1SDimitry Andric   switch (MI.getOpcode()) {
488fe6060f1SDimitry Andric   case TargetOpcode::STACKMAP:
489fe6060f1SDimitry Andric     // StackMapLiveValues are foldable
490fe6060f1SDimitry Andric     return std::make_pair(0, StackMapOpers(&MI).getVarIdx());
491fe6060f1SDimitry Andric   case TargetOpcode::PATCHPOINT:
492fe6060f1SDimitry Andric     // For PatchPoint, the call args are not foldable (even if reported in the
493fe6060f1SDimitry Andric     // stackmap e.g. via anyregcc).
494fe6060f1SDimitry Andric     return std::make_pair(0, PatchPointOpers(&MI).getVarIdx());
495fe6060f1SDimitry Andric   case TargetOpcode::STATEPOINT:
496fe6060f1SDimitry Andric     // For statepoints, fold deopt and gc arguments, but not call arguments.
497fe6060f1SDimitry Andric     return std::make_pair(MI.getNumDefs(), StatepointOpers(&MI).getVarIdx());
498fe6060f1SDimitry Andric   default:
499fe6060f1SDimitry Andric     llvm_unreachable("unexpected stackmap opcode");
500fe6060f1SDimitry Andric   }
5010b57cec5SDimitry Andric }
5020b57cec5SDimitry Andric 
foldPatchpoint(MachineFunction & MF,MachineInstr & MI,ArrayRef<unsigned> Ops,int FrameIndex,const TargetInstrInfo & TII)5030b57cec5SDimitry Andric static MachineInstr *foldPatchpoint(MachineFunction &MF, MachineInstr &MI,
5040b57cec5SDimitry Andric                                     ArrayRef<unsigned> Ops, int FrameIndex,
5050b57cec5SDimitry Andric                                     const TargetInstrInfo &TII) {
5060b57cec5SDimitry Andric   unsigned StartIdx = 0;
507e8d8bef9SDimitry Andric   unsigned NumDefs = 0;
508fe6060f1SDimitry Andric   // getPatchpointUnfoldableRange throws guarantee if MI is not a patchpoint.
509fe6060f1SDimitry Andric   std::tie(NumDefs, StartIdx) = TII.getPatchpointUnfoldableRange(MI);
5100b57cec5SDimitry Andric 
511e8d8bef9SDimitry Andric   unsigned DefToFoldIdx = MI.getNumOperands();
512e8d8bef9SDimitry Andric 
5130b57cec5SDimitry Andric   // Return false if any operands requested for folding are not foldable (not
5140b57cec5SDimitry Andric   // part of the stackmap's live values).
5150b57cec5SDimitry Andric   for (unsigned Op : Ops) {
516e8d8bef9SDimitry Andric     if (Op < NumDefs) {
517e8d8bef9SDimitry Andric       assert(DefToFoldIdx == MI.getNumOperands() && "Folding multiple defs");
518e8d8bef9SDimitry Andric       DefToFoldIdx = Op;
519e8d8bef9SDimitry Andric     } else if (Op < StartIdx) {
520e8d8bef9SDimitry Andric       return nullptr;
521e8d8bef9SDimitry Andric     }
522e8d8bef9SDimitry Andric     if (MI.getOperand(Op).isTied())
5230b57cec5SDimitry Andric       return nullptr;
5240b57cec5SDimitry Andric   }
5250b57cec5SDimitry Andric 
5260b57cec5SDimitry Andric   MachineInstr *NewMI =
5270b57cec5SDimitry Andric       MF.CreateMachineInstr(TII.get(MI.getOpcode()), MI.getDebugLoc(), true);
5280b57cec5SDimitry Andric   MachineInstrBuilder MIB(MF, NewMI);
5290b57cec5SDimitry Andric 
5300b57cec5SDimitry Andric   // No need to fold return, the meta data, and function arguments
5310b57cec5SDimitry Andric   for (unsigned i = 0; i < StartIdx; ++i)
532e8d8bef9SDimitry Andric     if (i != DefToFoldIdx)
5330b57cec5SDimitry Andric       MIB.add(MI.getOperand(i));
5340b57cec5SDimitry Andric 
535e8d8bef9SDimitry Andric   for (unsigned i = StartIdx, e = MI.getNumOperands(); i < e; ++i) {
5360b57cec5SDimitry Andric     MachineOperand &MO = MI.getOperand(i);
537e8d8bef9SDimitry Andric     unsigned TiedTo = e;
538e8d8bef9SDimitry Andric     (void)MI.isRegTiedToDefOperand(i, &TiedTo);
539e8d8bef9SDimitry Andric 
5400b57cec5SDimitry Andric     if (is_contained(Ops, i)) {
541e8d8bef9SDimitry Andric       assert(TiedTo == e && "Cannot fold tied operands");
5420b57cec5SDimitry Andric       unsigned SpillSize;
5430b57cec5SDimitry Andric       unsigned SpillOffset;
5440b57cec5SDimitry Andric       // Compute the spill slot size and offset.
5450b57cec5SDimitry Andric       const TargetRegisterClass *RC =
5460b57cec5SDimitry Andric         MF.getRegInfo().getRegClass(MO.getReg());
5470b57cec5SDimitry Andric       bool Valid =
5480b57cec5SDimitry Andric           TII.getStackSlotRange(RC, MO.getSubReg(), SpillSize, SpillOffset, MF);
5490b57cec5SDimitry Andric       if (!Valid)
5500b57cec5SDimitry Andric         report_fatal_error("cannot spill patchpoint subregister operand");
5510b57cec5SDimitry Andric       MIB.addImm(StackMaps::IndirectMemRefOp);
5520b57cec5SDimitry Andric       MIB.addImm(SpillSize);
5530b57cec5SDimitry Andric       MIB.addFrameIndex(FrameIndex);
5540b57cec5SDimitry Andric       MIB.addImm(SpillOffset);
555e8d8bef9SDimitry Andric     } else {
5560b57cec5SDimitry Andric       MIB.add(MO);
557e8d8bef9SDimitry Andric       if (TiedTo < e) {
558e8d8bef9SDimitry Andric         assert(TiedTo < NumDefs && "Bad tied operand");
559e8d8bef9SDimitry Andric         if (TiedTo > DefToFoldIdx)
560e8d8bef9SDimitry Andric           --TiedTo;
561e8d8bef9SDimitry Andric         NewMI->tieOperands(TiedTo, NewMI->getNumOperands() - 1);
562e8d8bef9SDimitry Andric       }
563e8d8bef9SDimitry Andric     }
5640b57cec5SDimitry Andric   }
5650b57cec5SDimitry Andric   return NewMI;
5660b57cec5SDimitry Andric }
5670b57cec5SDimitry Andric 
foldInlineAsmMemOperand(MachineInstr * MI,unsigned OpNo,int FI,const TargetInstrInfo & TII)568*c9157d92SDimitry Andric static void foldInlineAsmMemOperand(MachineInstr *MI, unsigned OpNo, int FI,
569*c9157d92SDimitry Andric                                     const TargetInstrInfo &TII) {
570*c9157d92SDimitry Andric   // If the machine operand is tied, untie it first.
571*c9157d92SDimitry Andric   if (MI->getOperand(OpNo).isTied()) {
572*c9157d92SDimitry Andric     unsigned TiedTo = MI->findTiedOperandIdx(OpNo);
573*c9157d92SDimitry Andric     MI->untieRegOperand(OpNo);
574*c9157d92SDimitry Andric     // Intentional recursion!
575*c9157d92SDimitry Andric     foldInlineAsmMemOperand(MI, TiedTo, FI, TII);
576*c9157d92SDimitry Andric   }
577*c9157d92SDimitry Andric 
578*c9157d92SDimitry Andric   SmallVector<MachineOperand, 5> NewOps;
579*c9157d92SDimitry Andric   TII.getFrameIndexOperands(NewOps, FI);
580*c9157d92SDimitry Andric   assert(!NewOps.empty() && "getFrameIndexOperands didn't create any operands");
581*c9157d92SDimitry Andric   MI->removeOperand(OpNo);
582*c9157d92SDimitry Andric   MI->insert(MI->operands_begin() + OpNo, NewOps);
583*c9157d92SDimitry Andric 
584*c9157d92SDimitry Andric   // Change the previous operand to a MemKind InlineAsm::Flag. The second param
585*c9157d92SDimitry Andric   // is the per-target number of operands that represent the memory operand
586*c9157d92SDimitry Andric   // excluding this one (MD). This includes MO.
587*c9157d92SDimitry Andric   InlineAsm::Flag F(InlineAsm::Kind::Mem, NewOps.size());
588*c9157d92SDimitry Andric   F.setMemConstraint(InlineAsm::ConstraintCode::m);
589*c9157d92SDimitry Andric   MachineOperand &MD = MI->getOperand(OpNo - 1);
590*c9157d92SDimitry Andric   MD.setImm(F);
591*c9157d92SDimitry Andric }
592*c9157d92SDimitry Andric 
593*c9157d92SDimitry Andric // Returns nullptr if not possible to fold.
foldInlineAsmMemOperand(MachineInstr & MI,ArrayRef<unsigned> Ops,int FI,const TargetInstrInfo & TII)594*c9157d92SDimitry Andric static MachineInstr *foldInlineAsmMemOperand(MachineInstr &MI,
595*c9157d92SDimitry Andric                                              ArrayRef<unsigned> Ops, int FI,
596*c9157d92SDimitry Andric                                              const TargetInstrInfo &TII) {
597*c9157d92SDimitry Andric   assert(MI.isInlineAsm() && "wrong opcode");
598*c9157d92SDimitry Andric   if (Ops.size() > 1)
599*c9157d92SDimitry Andric     return nullptr;
600*c9157d92SDimitry Andric   unsigned Op = Ops[0];
601*c9157d92SDimitry Andric   assert(Op && "should never be first operand");
602*c9157d92SDimitry Andric   assert(MI.getOperand(Op).isReg() && "shouldn't be folding non-reg operands");
603*c9157d92SDimitry Andric 
604*c9157d92SDimitry Andric   if (!MI.mayFoldInlineAsmRegOp(Op))
605*c9157d92SDimitry Andric     return nullptr;
606*c9157d92SDimitry Andric 
607*c9157d92SDimitry Andric   MachineInstr &NewMI = TII.duplicate(*MI.getParent(), MI.getIterator(), MI);
608*c9157d92SDimitry Andric 
609*c9157d92SDimitry Andric   foldInlineAsmMemOperand(&NewMI, Op, FI, TII);
610*c9157d92SDimitry Andric 
611*c9157d92SDimitry Andric   // Update mayload/maystore metadata, and memoperands.
612*c9157d92SDimitry Andric   const VirtRegInfo &RI =
613*c9157d92SDimitry Andric       AnalyzeVirtRegInBundle(MI, MI.getOperand(Op).getReg());
614*c9157d92SDimitry Andric   MachineOperand &ExtraMO = NewMI.getOperand(InlineAsm::MIOp_ExtraInfo);
615*c9157d92SDimitry Andric   MachineMemOperand::Flags Flags = MachineMemOperand::MONone;
616*c9157d92SDimitry Andric   if (RI.Reads) {
617*c9157d92SDimitry Andric     ExtraMO.setImm(ExtraMO.getImm() | InlineAsm::Extra_MayLoad);
618*c9157d92SDimitry Andric     Flags |= MachineMemOperand::MOLoad;
619*c9157d92SDimitry Andric   }
620*c9157d92SDimitry Andric   if (RI.Writes) {
621*c9157d92SDimitry Andric     ExtraMO.setImm(ExtraMO.getImm() | InlineAsm::Extra_MayStore);
622*c9157d92SDimitry Andric     Flags |= MachineMemOperand::MOStore;
623*c9157d92SDimitry Andric   }
624*c9157d92SDimitry Andric   MachineFunction *MF = NewMI.getMF();
625*c9157d92SDimitry Andric   const MachineFrameInfo &MFI = MF->getFrameInfo();
626*c9157d92SDimitry Andric   MachineMemOperand *MMO = MF->getMachineMemOperand(
627*c9157d92SDimitry Andric       MachinePointerInfo::getFixedStack(*MF, FI), Flags, MFI.getObjectSize(FI),
628*c9157d92SDimitry Andric       MFI.getObjectAlign(FI));
629*c9157d92SDimitry Andric   NewMI.addMemOperand(*MF, MMO);
630*c9157d92SDimitry Andric 
631*c9157d92SDimitry Andric   return &NewMI;
632*c9157d92SDimitry Andric }
633*c9157d92SDimitry Andric 
foldMemoryOperand(MachineInstr & MI,ArrayRef<unsigned> Ops,int FI,LiveIntervals * LIS,VirtRegMap * VRM) const6340b57cec5SDimitry Andric MachineInstr *TargetInstrInfo::foldMemoryOperand(MachineInstr &MI,
6350b57cec5SDimitry Andric                                                  ArrayRef<unsigned> Ops, int FI,
6360b57cec5SDimitry Andric                                                  LiveIntervals *LIS,
6370b57cec5SDimitry Andric                                                  VirtRegMap *VRM) const {
6380b57cec5SDimitry Andric   auto Flags = MachineMemOperand::MONone;
6390b57cec5SDimitry Andric   for (unsigned OpIdx : Ops)
6400b57cec5SDimitry Andric     Flags |= MI.getOperand(OpIdx).isDef() ? MachineMemOperand::MOStore
6410b57cec5SDimitry Andric                                           : MachineMemOperand::MOLoad;
6420b57cec5SDimitry Andric 
6430b57cec5SDimitry Andric   MachineBasicBlock *MBB = MI.getParent();
6440b57cec5SDimitry Andric   assert(MBB && "foldMemoryOperand needs an inserted instruction");
6450b57cec5SDimitry Andric   MachineFunction &MF = *MBB->getParent();
6460b57cec5SDimitry Andric 
6470b57cec5SDimitry Andric   // If we're not folding a load into a subreg, the size of the load is the
6480b57cec5SDimitry Andric   // size of the spill slot. But if we are, we need to figure out what the
6490b57cec5SDimitry Andric   // actual load size is.
6500b57cec5SDimitry Andric   int64_t MemSize = 0;
6510b57cec5SDimitry Andric   const MachineFrameInfo &MFI = MF.getFrameInfo();
6520b57cec5SDimitry Andric   const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
6530b57cec5SDimitry Andric 
6540b57cec5SDimitry Andric   if (Flags & MachineMemOperand::MOStore) {
6550b57cec5SDimitry Andric     MemSize = MFI.getObjectSize(FI);
6560b57cec5SDimitry Andric   } else {
6570b57cec5SDimitry Andric     for (unsigned OpIdx : Ops) {
6580b57cec5SDimitry Andric       int64_t OpSize = MFI.getObjectSize(FI);
6590b57cec5SDimitry Andric 
6600b57cec5SDimitry Andric       if (auto SubReg = MI.getOperand(OpIdx).getSubReg()) {
6610b57cec5SDimitry Andric         unsigned SubRegSize = TRI->getSubRegIdxSize(SubReg);
6620b57cec5SDimitry Andric         if (SubRegSize > 0 && !(SubRegSize % 8))
6630b57cec5SDimitry Andric           OpSize = SubRegSize / 8;
6640b57cec5SDimitry Andric       }
6650b57cec5SDimitry Andric 
6660b57cec5SDimitry Andric       MemSize = std::max(MemSize, OpSize);
6670b57cec5SDimitry Andric     }
6680b57cec5SDimitry Andric   }
6690b57cec5SDimitry Andric 
6700b57cec5SDimitry Andric   assert(MemSize && "Did not expect a zero-sized stack slot");
6710b57cec5SDimitry Andric 
6720b57cec5SDimitry Andric   MachineInstr *NewMI = nullptr;
6730b57cec5SDimitry Andric 
6740b57cec5SDimitry Andric   if (MI.getOpcode() == TargetOpcode::STACKMAP ||
6750b57cec5SDimitry Andric       MI.getOpcode() == TargetOpcode::PATCHPOINT ||
6760b57cec5SDimitry Andric       MI.getOpcode() == TargetOpcode::STATEPOINT) {
6770b57cec5SDimitry Andric     // Fold stackmap/patchpoint.
6780b57cec5SDimitry Andric     NewMI = foldPatchpoint(MF, MI, Ops, FI, *this);
6790b57cec5SDimitry Andric     if (NewMI)
6800b57cec5SDimitry Andric       MBB->insert(MI, NewMI);
681*c9157d92SDimitry Andric   } else if (MI.isInlineAsm()) {
682*c9157d92SDimitry Andric     return foldInlineAsmMemOperand(MI, Ops, FI, *this);
6830b57cec5SDimitry Andric   } else {
6840b57cec5SDimitry Andric     // Ask the target to do the actual folding.
6850b57cec5SDimitry Andric     NewMI = foldMemoryOperandImpl(MF, MI, Ops, MI, FI, LIS, VRM);
6860b57cec5SDimitry Andric   }
6870b57cec5SDimitry Andric 
6880b57cec5SDimitry Andric   if (NewMI) {
6890b57cec5SDimitry Andric     NewMI->setMemRefs(MF, MI.memoperands());
6900b57cec5SDimitry Andric     // Add a memory operand, foldMemoryOperandImpl doesn't do that.
6910b57cec5SDimitry Andric     assert((!(Flags & MachineMemOperand::MOStore) ||
6920b57cec5SDimitry Andric             NewMI->mayStore()) &&
6930b57cec5SDimitry Andric            "Folded a def to a non-store!");
6940b57cec5SDimitry Andric     assert((!(Flags & MachineMemOperand::MOLoad) ||
6950b57cec5SDimitry Andric             NewMI->mayLoad()) &&
6960b57cec5SDimitry Andric            "Folded a use to a non-load!");
6970b57cec5SDimitry Andric     assert(MFI.getObjectOffset(FI) != -1);
6985ffd83dbSDimitry Andric     MachineMemOperand *MMO =
6995ffd83dbSDimitry Andric         MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(MF, FI),
7005ffd83dbSDimitry Andric                                 Flags, MemSize, MFI.getObjectAlign(FI));
7010b57cec5SDimitry Andric     NewMI->addMemOperand(MF, MMO);
7020b57cec5SDimitry Andric 
7035ffd83dbSDimitry Andric     // The pass "x86 speculative load hardening" always attaches symbols to
7045ffd83dbSDimitry Andric     // call instructions. We need copy it form old instruction.
7055ffd83dbSDimitry Andric     NewMI->cloneInstrSymbols(MF, MI);
7065ffd83dbSDimitry Andric 
7070b57cec5SDimitry Andric     return NewMI;
7080b57cec5SDimitry Andric   }
7090b57cec5SDimitry Andric 
7100b57cec5SDimitry Andric   // Straight COPY may fold as load/store.
711*c9157d92SDimitry Andric   if (!isCopyInstr(MI) || Ops.size() != 1)
7120b57cec5SDimitry Andric     return nullptr;
7130b57cec5SDimitry Andric 
714*c9157d92SDimitry Andric   const TargetRegisterClass *RC = canFoldCopy(MI, *this, Ops[0]);
7150b57cec5SDimitry Andric   if (!RC)
7160b57cec5SDimitry Andric     return nullptr;
7170b57cec5SDimitry Andric 
7180b57cec5SDimitry Andric   const MachineOperand &MO = MI.getOperand(1 - Ops[0]);
7190b57cec5SDimitry Andric   MachineBasicBlock::iterator Pos = MI;
7200b57cec5SDimitry Andric 
7210b57cec5SDimitry Andric   if (Flags == MachineMemOperand::MOStore)
722bdd1243dSDimitry Andric     storeRegToStackSlot(*MBB, Pos, MO.getReg(), MO.isKill(), FI, RC, TRI,
723bdd1243dSDimitry Andric                         Register());
7240b57cec5SDimitry Andric   else
725bdd1243dSDimitry Andric     loadRegFromStackSlot(*MBB, Pos, MO.getReg(), FI, RC, TRI, Register());
7260b57cec5SDimitry Andric   return &*--Pos;
7270b57cec5SDimitry Andric }
7280b57cec5SDimitry Andric 
foldMemoryOperand(MachineInstr & MI,ArrayRef<unsigned> Ops,MachineInstr & LoadMI,LiveIntervals * LIS) const7290b57cec5SDimitry Andric MachineInstr *TargetInstrInfo::foldMemoryOperand(MachineInstr &MI,
7300b57cec5SDimitry Andric                                                  ArrayRef<unsigned> Ops,
7310b57cec5SDimitry Andric                                                  MachineInstr &LoadMI,
7320b57cec5SDimitry Andric                                                  LiveIntervals *LIS) const {
7330b57cec5SDimitry Andric   assert(LoadMI.canFoldAsLoad() && "LoadMI isn't foldable!");
7340b57cec5SDimitry Andric #ifndef NDEBUG
7350b57cec5SDimitry Andric   for (unsigned OpIdx : Ops)
7360b57cec5SDimitry Andric     assert(MI.getOperand(OpIdx).isUse() && "Folding load into def!");
7370b57cec5SDimitry Andric #endif
7380b57cec5SDimitry Andric 
7390b57cec5SDimitry Andric   MachineBasicBlock &MBB = *MI.getParent();
7400b57cec5SDimitry Andric   MachineFunction &MF = *MBB.getParent();
7410b57cec5SDimitry Andric 
7420b57cec5SDimitry Andric   // Ask the target to do the actual folding.
7430b57cec5SDimitry Andric   MachineInstr *NewMI = nullptr;
7440b57cec5SDimitry Andric   int FrameIndex = 0;
7450b57cec5SDimitry Andric 
7460b57cec5SDimitry Andric   if ((MI.getOpcode() == TargetOpcode::STACKMAP ||
7470b57cec5SDimitry Andric        MI.getOpcode() == TargetOpcode::PATCHPOINT ||
7480b57cec5SDimitry Andric        MI.getOpcode() == TargetOpcode::STATEPOINT) &&
7490b57cec5SDimitry Andric       isLoadFromStackSlot(LoadMI, FrameIndex)) {
7500b57cec5SDimitry Andric     // Fold stackmap/patchpoint.
7510b57cec5SDimitry Andric     NewMI = foldPatchpoint(MF, MI, Ops, FrameIndex, *this);
7520b57cec5SDimitry Andric     if (NewMI)
7530b57cec5SDimitry Andric       NewMI = &*MBB.insert(MI, NewMI);
754*c9157d92SDimitry Andric   } else if (MI.isInlineAsm() && isLoadFromStackSlot(LoadMI, FrameIndex)) {
755*c9157d92SDimitry Andric     return foldInlineAsmMemOperand(MI, Ops, FrameIndex, *this);
7560b57cec5SDimitry Andric   } else {
7570b57cec5SDimitry Andric     // Ask the target to do the actual folding.
7580b57cec5SDimitry Andric     NewMI = foldMemoryOperandImpl(MF, MI, Ops, MI, LoadMI, LIS);
7590b57cec5SDimitry Andric   }
7600b57cec5SDimitry Andric 
7610b57cec5SDimitry Andric   if (!NewMI)
7620b57cec5SDimitry Andric     return nullptr;
7630b57cec5SDimitry Andric 
7640b57cec5SDimitry Andric   // Copy the memoperands from the load to the folded instruction.
7650b57cec5SDimitry Andric   if (MI.memoperands_empty()) {
7660b57cec5SDimitry Andric     NewMI->setMemRefs(MF, LoadMI.memoperands());
7670b57cec5SDimitry Andric   } else {
7680b57cec5SDimitry Andric     // Handle the rare case of folding multiple loads.
7690b57cec5SDimitry Andric     NewMI->setMemRefs(MF, MI.memoperands());
7700b57cec5SDimitry Andric     for (MachineInstr::mmo_iterator I = LoadMI.memoperands_begin(),
7710b57cec5SDimitry Andric                                     E = LoadMI.memoperands_end();
7720b57cec5SDimitry Andric          I != E; ++I) {
7730b57cec5SDimitry Andric       NewMI->addMemOperand(MF, *I);
7740b57cec5SDimitry Andric     }
7750b57cec5SDimitry Andric   }
7760b57cec5SDimitry Andric   return NewMI;
7770b57cec5SDimitry Andric }
7780b57cec5SDimitry Andric 
779fe013be4SDimitry Andric /// transferImplicitOperands - MI is a pseudo-instruction, and the lowered
780fe013be4SDimitry Andric /// replacement instructions immediately precede it.  Copy any implicit
781fe013be4SDimitry Andric /// operands from MI to the replacement instruction.
transferImplicitOperands(MachineInstr * MI,const TargetRegisterInfo * TRI)782fe013be4SDimitry Andric static void transferImplicitOperands(MachineInstr *MI,
783fe013be4SDimitry Andric                                      const TargetRegisterInfo *TRI) {
784fe013be4SDimitry Andric   MachineBasicBlock::iterator CopyMI = MI;
785fe013be4SDimitry Andric   --CopyMI;
786fe013be4SDimitry Andric 
787fe013be4SDimitry Andric   Register DstReg = MI->getOperand(0).getReg();
788fe013be4SDimitry Andric   for (const MachineOperand &MO : MI->implicit_operands()) {
789fe013be4SDimitry Andric     CopyMI->addOperand(MO);
790fe013be4SDimitry Andric 
791fe013be4SDimitry Andric     // Be conservative about preserving kills when subregister defs are
792fe013be4SDimitry Andric     // involved. If there was implicit kill of a super-register overlapping the
793fe013be4SDimitry Andric     // copy result, we would kill the subregisters previous copies defined.
794fe013be4SDimitry Andric 
795fe013be4SDimitry Andric     if (MO.isKill() && TRI->regsOverlap(DstReg, MO.getReg()))
796fe013be4SDimitry Andric       CopyMI->getOperand(CopyMI->getNumOperands() - 1).setIsKill(false);
797fe013be4SDimitry Andric   }
798fe013be4SDimitry Andric }
799fe013be4SDimitry Andric 
lowerCopy(MachineInstr * MI,const TargetRegisterInfo * TRI) const800fe013be4SDimitry Andric void TargetInstrInfo::lowerCopy(MachineInstr *MI,
801fe013be4SDimitry Andric                                 const TargetRegisterInfo *TRI) const {
802fe013be4SDimitry Andric   if (MI->allDefsAreDead()) {
803fe013be4SDimitry Andric     MI->setDesc(get(TargetOpcode::KILL));
804fe013be4SDimitry Andric     return;
805fe013be4SDimitry Andric   }
806fe013be4SDimitry Andric 
807fe013be4SDimitry Andric   MachineOperand &DstMO = MI->getOperand(0);
808fe013be4SDimitry Andric   MachineOperand &SrcMO = MI->getOperand(1);
809fe013be4SDimitry Andric 
810fe013be4SDimitry Andric   bool IdentityCopy = (SrcMO.getReg() == DstMO.getReg());
811fe013be4SDimitry Andric   if (IdentityCopy || SrcMO.isUndef()) {
812fe013be4SDimitry Andric     // No need to insert an identity copy instruction, but replace with a KILL
813fe013be4SDimitry Andric     // if liveness is changed.
814fe013be4SDimitry Andric     if (SrcMO.isUndef() || MI->getNumOperands() > 2) {
815fe013be4SDimitry Andric       // We must make sure the super-register gets killed. Replace the
816fe013be4SDimitry Andric       // instruction with KILL.
817fe013be4SDimitry Andric       MI->setDesc(get(TargetOpcode::KILL));
818fe013be4SDimitry Andric       return;
819fe013be4SDimitry Andric     }
820fe013be4SDimitry Andric     // Vanilla identity copy.
821fe013be4SDimitry Andric     MI->eraseFromParent();
822fe013be4SDimitry Andric     return;
823fe013be4SDimitry Andric   }
824fe013be4SDimitry Andric 
825fe013be4SDimitry Andric   copyPhysReg(*MI->getParent(), MI, MI->getDebugLoc(), DstMO.getReg(),
826fe013be4SDimitry Andric               SrcMO.getReg(), SrcMO.isKill());
827fe013be4SDimitry Andric 
828fe013be4SDimitry Andric   if (MI->getNumOperands() > 2)
829fe013be4SDimitry Andric     transferImplicitOperands(MI, TRI);
830fe013be4SDimitry Andric   MI->eraseFromParent();
831fe013be4SDimitry Andric }
832fe013be4SDimitry Andric 
hasReassociableOperands(const MachineInstr & Inst,const MachineBasicBlock * MBB) const8330b57cec5SDimitry Andric bool TargetInstrInfo::hasReassociableOperands(
8340b57cec5SDimitry Andric     const MachineInstr &Inst, const MachineBasicBlock *MBB) const {
8350b57cec5SDimitry Andric   const MachineOperand &Op1 = Inst.getOperand(1);
8360b57cec5SDimitry Andric   const MachineOperand &Op2 = Inst.getOperand(2);
8370b57cec5SDimitry Andric   const MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
8380b57cec5SDimitry Andric 
8390b57cec5SDimitry Andric   // We need virtual register definitions for the operands that we will
8400b57cec5SDimitry Andric   // reassociate.
8410b57cec5SDimitry Andric   MachineInstr *MI1 = nullptr;
8420b57cec5SDimitry Andric   MachineInstr *MI2 = nullptr;
843bdd1243dSDimitry Andric   if (Op1.isReg() && Op1.getReg().isVirtual())
8440b57cec5SDimitry Andric     MI1 = MRI.getUniqueVRegDef(Op1.getReg());
845bdd1243dSDimitry Andric   if (Op2.isReg() && Op2.getReg().isVirtual())
8460b57cec5SDimitry Andric     MI2 = MRI.getUniqueVRegDef(Op2.getReg());
8470b57cec5SDimitry Andric 
848bdd1243dSDimitry Andric   // And at least one operand must be defined in MBB.
849bdd1243dSDimitry Andric   return MI1 && MI2 && (MI1->getParent() == MBB || MI2->getParent() == MBB);
850bdd1243dSDimitry Andric }
851bdd1243dSDimitry Andric 
areOpcodesEqualOrInverse(unsigned Opcode1,unsigned Opcode2) const852bdd1243dSDimitry Andric bool TargetInstrInfo::areOpcodesEqualOrInverse(unsigned Opcode1,
853bdd1243dSDimitry Andric                                                unsigned Opcode2) const {
854bdd1243dSDimitry Andric   return Opcode1 == Opcode2 || getInverseOpcode(Opcode1) == Opcode2;
8550b57cec5SDimitry Andric }
8560b57cec5SDimitry Andric 
hasReassociableSibling(const MachineInstr & Inst,bool & Commuted) const8570b57cec5SDimitry Andric bool TargetInstrInfo::hasReassociableSibling(const MachineInstr &Inst,
8580b57cec5SDimitry Andric                                              bool &Commuted) const {
8590b57cec5SDimitry Andric   const MachineBasicBlock *MBB = Inst.getParent();
8600b57cec5SDimitry Andric   const MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
8610b57cec5SDimitry Andric   MachineInstr *MI1 = MRI.getUniqueVRegDef(Inst.getOperand(1).getReg());
8620b57cec5SDimitry Andric   MachineInstr *MI2 = MRI.getUniqueVRegDef(Inst.getOperand(2).getReg());
863bdd1243dSDimitry Andric   unsigned Opcode = Inst.getOpcode();
8640b57cec5SDimitry Andric 
865bdd1243dSDimitry Andric   // If only one operand has the same or inverse opcode and it's the second
866bdd1243dSDimitry Andric   // source operand, the operands must be commuted.
867bdd1243dSDimitry Andric   Commuted = !areOpcodesEqualOrInverse(Opcode, MI1->getOpcode()) &&
868bdd1243dSDimitry Andric              areOpcodesEqualOrInverse(Opcode, MI2->getOpcode());
8690b57cec5SDimitry Andric   if (Commuted)
8700b57cec5SDimitry Andric     std::swap(MI1, MI2);
8710b57cec5SDimitry Andric 
8720b57cec5SDimitry Andric   // 1. The previous instruction must be the same type as Inst.
873bdd1243dSDimitry Andric   // 2. The previous instruction must also be associative/commutative or be the
874bdd1243dSDimitry Andric   //    inverse of such an operation (this can be different even for
875bdd1243dSDimitry Andric   //    instructions with the same opcode if traits like fast-math-flags are
876bdd1243dSDimitry Andric   //    included).
8775ffd83dbSDimitry Andric   // 3. The previous instruction must have virtual register definitions for its
8780b57cec5SDimitry Andric   //    operands in the same basic block as Inst.
8795ffd83dbSDimitry Andric   // 4. The previous instruction's result must only be used by Inst.
880bdd1243dSDimitry Andric   return areOpcodesEqualOrInverse(Opcode, MI1->getOpcode()) &&
881bdd1243dSDimitry Andric          (isAssociativeAndCommutative(*MI1) ||
882bdd1243dSDimitry Andric           isAssociativeAndCommutative(*MI1, /* Invert */ true)) &&
8830b57cec5SDimitry Andric          hasReassociableOperands(*MI1, MBB) &&
8840b57cec5SDimitry Andric          MRI.hasOneNonDBGUse(MI1->getOperand(0).getReg());
8850b57cec5SDimitry Andric }
8860b57cec5SDimitry Andric 
887bdd1243dSDimitry Andric // 1. The operation must be associative and commutative or be the inverse of
888bdd1243dSDimitry Andric //    such an operation.
8890b57cec5SDimitry Andric // 2. The instruction must have virtual register definitions for its
8900b57cec5SDimitry Andric //    operands in the same basic block.
8910b57cec5SDimitry Andric // 3. The instruction must have a reassociable sibling.
isReassociationCandidate(const MachineInstr & Inst,bool & Commuted) const8920b57cec5SDimitry Andric bool TargetInstrInfo::isReassociationCandidate(const MachineInstr &Inst,
8930b57cec5SDimitry Andric                                                bool &Commuted) const {
894bdd1243dSDimitry Andric   return (isAssociativeAndCommutative(Inst) ||
895bdd1243dSDimitry Andric           isAssociativeAndCommutative(Inst, /* Invert */ true)) &&
8960b57cec5SDimitry Andric          hasReassociableOperands(Inst, Inst.getParent()) &&
8970b57cec5SDimitry Andric          hasReassociableSibling(Inst, Commuted);
8980b57cec5SDimitry Andric }
8990b57cec5SDimitry Andric 
9000b57cec5SDimitry Andric // The concept of the reassociation pass is that these operations can benefit
9010b57cec5SDimitry Andric // from this kind of transformation:
9020b57cec5SDimitry Andric //
9030b57cec5SDimitry Andric // A = ? op ?
9040b57cec5SDimitry Andric // B = A op X (Prev)
9050b57cec5SDimitry Andric // C = B op Y (Root)
9060b57cec5SDimitry Andric // -->
9070b57cec5SDimitry Andric // A = ? op ?
9080b57cec5SDimitry Andric // B = X op Y
9090b57cec5SDimitry Andric // C = A op B
9100b57cec5SDimitry Andric //
9110b57cec5SDimitry Andric // breaking the dependency between A and B, allowing them to be executed in
9120b57cec5SDimitry Andric // parallel (or back-to-back in a pipeline) instead of depending on each other.
9130b57cec5SDimitry Andric 
9140b57cec5SDimitry Andric // FIXME: This has the potential to be expensive (compile time) while not
9150b57cec5SDimitry Andric // improving the code at all. Some ways to limit the overhead:
9160b57cec5SDimitry Andric // 1. Track successful transforms; bail out if hit rate gets too low.
9170b57cec5SDimitry Andric // 2. Only enable at -O3 or some other non-default optimization level.
9180b57cec5SDimitry Andric // 3. Pre-screen pattern candidates here: if an operand of the previous
9190b57cec5SDimitry Andric //    instruction is known to not increase the critical path, then don't match
9200b57cec5SDimitry Andric //    that pattern.
getMachineCombinerPatterns(MachineInstr & Root,SmallVectorImpl<MachineCombinerPattern> & Patterns,bool DoRegPressureReduce) const9210b57cec5SDimitry Andric bool TargetInstrInfo::getMachineCombinerPatterns(
922e8d8bef9SDimitry Andric     MachineInstr &Root, SmallVectorImpl<MachineCombinerPattern> &Patterns,
923e8d8bef9SDimitry Andric     bool DoRegPressureReduce) const {
9240b57cec5SDimitry Andric   bool Commute;
9250b57cec5SDimitry Andric   if (isReassociationCandidate(Root, Commute)) {
9260b57cec5SDimitry Andric     // We found a sequence of instructions that may be suitable for a
9270b57cec5SDimitry Andric     // reassociation of operands to increase ILP. Specify each commutation
9280b57cec5SDimitry Andric     // possibility for the Prev instruction in the sequence and let the
9290b57cec5SDimitry Andric     // machine combiner decide if changing the operands is worthwhile.
9300b57cec5SDimitry Andric     if (Commute) {
9310b57cec5SDimitry Andric       Patterns.push_back(MachineCombinerPattern::REASSOC_AX_YB);
9320b57cec5SDimitry Andric       Patterns.push_back(MachineCombinerPattern::REASSOC_XA_YB);
9330b57cec5SDimitry Andric     } else {
9340b57cec5SDimitry Andric       Patterns.push_back(MachineCombinerPattern::REASSOC_AX_BY);
9350b57cec5SDimitry Andric       Patterns.push_back(MachineCombinerPattern::REASSOC_XA_BY);
9360b57cec5SDimitry Andric     }
9370b57cec5SDimitry Andric     return true;
9380b57cec5SDimitry Andric   }
9390b57cec5SDimitry Andric 
9400b57cec5SDimitry Andric   return false;
9410b57cec5SDimitry Andric }
9420b57cec5SDimitry Andric 
9430b57cec5SDimitry Andric /// Return true when a code sequence can improve loop throughput.
9440b57cec5SDimitry Andric bool
isThroughputPattern(MachineCombinerPattern Pattern) const9450b57cec5SDimitry Andric TargetInstrInfo::isThroughputPattern(MachineCombinerPattern Pattern) const {
9460b57cec5SDimitry Andric   return false;
9470b57cec5SDimitry Andric }
9480b57cec5SDimitry Andric 
949bdd1243dSDimitry Andric std::pair<unsigned, unsigned>
getReassociationOpcodes(MachineCombinerPattern Pattern,const MachineInstr & Root,const MachineInstr & Prev) const950bdd1243dSDimitry Andric TargetInstrInfo::getReassociationOpcodes(MachineCombinerPattern Pattern,
951bdd1243dSDimitry Andric                                          const MachineInstr &Root,
952bdd1243dSDimitry Andric                                          const MachineInstr &Prev) const {
953bdd1243dSDimitry Andric   bool AssocCommutRoot = isAssociativeAndCommutative(Root);
954bdd1243dSDimitry Andric   bool AssocCommutPrev = isAssociativeAndCommutative(Prev);
955bdd1243dSDimitry Andric 
956bdd1243dSDimitry Andric   // Early exit if both opcodes are associative and commutative. It's a trivial
957bdd1243dSDimitry Andric   // reassociation when we only change operands order. In this case opcodes are
958bdd1243dSDimitry Andric   // not required to have inverse versions.
959bdd1243dSDimitry Andric   if (AssocCommutRoot && AssocCommutPrev) {
960bdd1243dSDimitry Andric     assert(Root.getOpcode() == Prev.getOpcode() && "Expected to be equal");
961bdd1243dSDimitry Andric     return std::make_pair(Root.getOpcode(), Root.getOpcode());
962bdd1243dSDimitry Andric   }
963bdd1243dSDimitry Andric 
964bdd1243dSDimitry Andric   // At least one instruction is not associative or commutative.
965bdd1243dSDimitry Andric   // Since we have matched one of the reassociation patterns, we expect that the
966bdd1243dSDimitry Andric   // instructions' opcodes are equal or one of them is the inversion of the
967bdd1243dSDimitry Andric   // other.
968bdd1243dSDimitry Andric   assert(areOpcodesEqualOrInverse(Root.getOpcode(), Prev.getOpcode()) &&
969bdd1243dSDimitry Andric          "Incorrectly matched pattern");
970bdd1243dSDimitry Andric   unsigned AssocCommutOpcode = Root.getOpcode();
971bdd1243dSDimitry Andric   unsigned InverseOpcode = *getInverseOpcode(Root.getOpcode());
972bdd1243dSDimitry Andric   if (!AssocCommutRoot)
973bdd1243dSDimitry Andric     std::swap(AssocCommutOpcode, InverseOpcode);
974bdd1243dSDimitry Andric 
975bdd1243dSDimitry Andric   // The transformation rule (`+` is any associative and commutative binary
976bdd1243dSDimitry Andric   // operation, `-` is the inverse):
977bdd1243dSDimitry Andric   // REASSOC_AX_BY:
978bdd1243dSDimitry Andric   //   (A + X) + Y => A + (X + Y)
979bdd1243dSDimitry Andric   //   (A + X) - Y => A + (X - Y)
980bdd1243dSDimitry Andric   //   (A - X) + Y => A - (X - Y)
981bdd1243dSDimitry Andric   //   (A - X) - Y => A - (X + Y)
982bdd1243dSDimitry Andric   // REASSOC_XA_BY:
983bdd1243dSDimitry Andric   //   (X + A) + Y => (X + Y) + A
984bdd1243dSDimitry Andric   //   (X + A) - Y => (X - Y) + A
985bdd1243dSDimitry Andric   //   (X - A) + Y => (X + Y) - A
986bdd1243dSDimitry Andric   //   (X - A) - Y => (X - Y) - A
987bdd1243dSDimitry Andric   // REASSOC_AX_YB:
988bdd1243dSDimitry Andric   //   Y + (A + X) => (Y + X) + A
989bdd1243dSDimitry Andric   //   Y - (A + X) => (Y - X) - A
990bdd1243dSDimitry Andric   //   Y + (A - X) => (Y - X) + A
991bdd1243dSDimitry Andric   //   Y - (A - X) => (Y + X) - A
992bdd1243dSDimitry Andric   // REASSOC_XA_YB:
993bdd1243dSDimitry Andric   //   Y + (X + A) => (Y + X) + A
994bdd1243dSDimitry Andric   //   Y - (X + A) => (Y - X) - A
995bdd1243dSDimitry Andric   //   Y + (X - A) => (Y + X) - A
996bdd1243dSDimitry Andric   //   Y - (X - A) => (Y - X) + A
997bdd1243dSDimitry Andric   switch (Pattern) {
998bdd1243dSDimitry Andric   default:
999bdd1243dSDimitry Andric     llvm_unreachable("Unexpected pattern");
1000bdd1243dSDimitry Andric   case MachineCombinerPattern::REASSOC_AX_BY:
1001bdd1243dSDimitry Andric     if (!AssocCommutRoot && AssocCommutPrev)
1002bdd1243dSDimitry Andric       return {AssocCommutOpcode, InverseOpcode};
1003bdd1243dSDimitry Andric     if (AssocCommutRoot && !AssocCommutPrev)
1004bdd1243dSDimitry Andric       return {InverseOpcode, InverseOpcode};
1005bdd1243dSDimitry Andric     if (!AssocCommutRoot && !AssocCommutPrev)
1006bdd1243dSDimitry Andric       return {InverseOpcode, AssocCommutOpcode};
1007bdd1243dSDimitry Andric     break;
1008bdd1243dSDimitry Andric   case MachineCombinerPattern::REASSOC_XA_BY:
1009bdd1243dSDimitry Andric     if (!AssocCommutRoot && AssocCommutPrev)
1010bdd1243dSDimitry Andric       return {AssocCommutOpcode, InverseOpcode};
1011bdd1243dSDimitry Andric     if (AssocCommutRoot && !AssocCommutPrev)
1012bdd1243dSDimitry Andric       return {InverseOpcode, AssocCommutOpcode};
1013bdd1243dSDimitry Andric     if (!AssocCommutRoot && !AssocCommutPrev)
1014bdd1243dSDimitry Andric       return {InverseOpcode, InverseOpcode};
1015bdd1243dSDimitry Andric     break;
1016bdd1243dSDimitry Andric   case MachineCombinerPattern::REASSOC_AX_YB:
1017bdd1243dSDimitry Andric     if (!AssocCommutRoot && AssocCommutPrev)
1018bdd1243dSDimitry Andric       return {InverseOpcode, InverseOpcode};
1019bdd1243dSDimitry Andric     if (AssocCommutRoot && !AssocCommutPrev)
1020bdd1243dSDimitry Andric       return {AssocCommutOpcode, InverseOpcode};
1021bdd1243dSDimitry Andric     if (!AssocCommutRoot && !AssocCommutPrev)
1022bdd1243dSDimitry Andric       return {InverseOpcode, AssocCommutOpcode};
1023bdd1243dSDimitry Andric     break;
1024bdd1243dSDimitry Andric   case MachineCombinerPattern::REASSOC_XA_YB:
1025bdd1243dSDimitry Andric     if (!AssocCommutRoot && AssocCommutPrev)
1026bdd1243dSDimitry Andric       return {InverseOpcode, InverseOpcode};
1027bdd1243dSDimitry Andric     if (AssocCommutRoot && !AssocCommutPrev)
1028bdd1243dSDimitry Andric       return {InverseOpcode, AssocCommutOpcode};
1029bdd1243dSDimitry Andric     if (!AssocCommutRoot && !AssocCommutPrev)
1030bdd1243dSDimitry Andric       return {AssocCommutOpcode, InverseOpcode};
1031bdd1243dSDimitry Andric     break;
1032bdd1243dSDimitry Andric   }
1033bdd1243dSDimitry Andric   llvm_unreachable("Unhandled combination");
1034bdd1243dSDimitry Andric }
1035bdd1243dSDimitry Andric 
1036bdd1243dSDimitry Andric // Return a pair of boolean flags showing if the new root and new prev operands
1037bdd1243dSDimitry Andric // must be swapped. See visual example of the rule in
1038bdd1243dSDimitry Andric // TargetInstrInfo::getReassociationOpcodes.
mustSwapOperands(MachineCombinerPattern Pattern)1039bdd1243dSDimitry Andric static std::pair<bool, bool> mustSwapOperands(MachineCombinerPattern Pattern) {
1040bdd1243dSDimitry Andric   switch (Pattern) {
1041bdd1243dSDimitry Andric   default:
1042bdd1243dSDimitry Andric     llvm_unreachable("Unexpected pattern");
1043bdd1243dSDimitry Andric   case MachineCombinerPattern::REASSOC_AX_BY:
1044bdd1243dSDimitry Andric     return {false, false};
1045bdd1243dSDimitry Andric   case MachineCombinerPattern::REASSOC_XA_BY:
1046bdd1243dSDimitry Andric     return {true, false};
1047bdd1243dSDimitry Andric   case MachineCombinerPattern::REASSOC_AX_YB:
1048bdd1243dSDimitry Andric     return {true, true};
1049bdd1243dSDimitry Andric   case MachineCombinerPattern::REASSOC_XA_YB:
1050bdd1243dSDimitry Andric     return {true, true};
1051bdd1243dSDimitry Andric   }
1052bdd1243dSDimitry Andric }
1053bdd1243dSDimitry Andric 
10540b57cec5SDimitry Andric /// Attempt the reassociation transformation to reduce critical path length.
10550b57cec5SDimitry Andric /// See the above comments before getMachineCombinerPatterns().
reassociateOps(MachineInstr & Root,MachineInstr & Prev,MachineCombinerPattern Pattern,SmallVectorImpl<MachineInstr * > & InsInstrs,SmallVectorImpl<MachineInstr * > & DelInstrs,DenseMap<unsigned,unsigned> & InstrIdxForVirtReg) const10560b57cec5SDimitry Andric void TargetInstrInfo::reassociateOps(
10570b57cec5SDimitry Andric     MachineInstr &Root, MachineInstr &Prev,
10580b57cec5SDimitry Andric     MachineCombinerPattern Pattern,
10590b57cec5SDimitry Andric     SmallVectorImpl<MachineInstr *> &InsInstrs,
10600b57cec5SDimitry Andric     SmallVectorImpl<MachineInstr *> &DelInstrs,
10610b57cec5SDimitry Andric     DenseMap<unsigned, unsigned> &InstrIdxForVirtReg) const {
10620b57cec5SDimitry Andric   MachineFunction *MF = Root.getMF();
10630b57cec5SDimitry Andric   MachineRegisterInfo &MRI = MF->getRegInfo();
10640b57cec5SDimitry Andric   const TargetInstrInfo *TII = MF->getSubtarget().getInstrInfo();
10650b57cec5SDimitry Andric   const TargetRegisterInfo *TRI = MF->getSubtarget().getRegisterInfo();
10660b57cec5SDimitry Andric   const TargetRegisterClass *RC = Root.getRegClassConstraint(0, TII, TRI);
10670b57cec5SDimitry Andric 
10680b57cec5SDimitry Andric   // This array encodes the operand index for each parameter because the
10690b57cec5SDimitry Andric   // operands may be commuted. Each row corresponds to a pattern value,
10700b57cec5SDimitry Andric   // and each column specifies the index of A, B, X, Y.
10710b57cec5SDimitry Andric   unsigned OpIdx[4][4] = {
10720b57cec5SDimitry Andric     { 1, 1, 2, 2 },
10730b57cec5SDimitry Andric     { 1, 2, 2, 1 },
10740b57cec5SDimitry Andric     { 2, 1, 1, 2 },
10750b57cec5SDimitry Andric     { 2, 2, 1, 1 }
10760b57cec5SDimitry Andric   };
10770b57cec5SDimitry Andric 
10780b57cec5SDimitry Andric   int Row;
10790b57cec5SDimitry Andric   switch (Pattern) {
10800b57cec5SDimitry Andric   case MachineCombinerPattern::REASSOC_AX_BY: Row = 0; break;
10810b57cec5SDimitry Andric   case MachineCombinerPattern::REASSOC_AX_YB: Row = 1; break;
10820b57cec5SDimitry Andric   case MachineCombinerPattern::REASSOC_XA_BY: Row = 2; break;
10830b57cec5SDimitry Andric   case MachineCombinerPattern::REASSOC_XA_YB: Row = 3; break;
10840b57cec5SDimitry Andric   default: llvm_unreachable("unexpected MachineCombinerPattern");
10850b57cec5SDimitry Andric   }
10860b57cec5SDimitry Andric 
10870b57cec5SDimitry Andric   MachineOperand &OpA = Prev.getOperand(OpIdx[Row][0]);
10880b57cec5SDimitry Andric   MachineOperand &OpB = Root.getOperand(OpIdx[Row][1]);
10890b57cec5SDimitry Andric   MachineOperand &OpX = Prev.getOperand(OpIdx[Row][2]);
10900b57cec5SDimitry Andric   MachineOperand &OpY = Root.getOperand(OpIdx[Row][3]);
10910b57cec5SDimitry Andric   MachineOperand &OpC = Root.getOperand(0);
10920b57cec5SDimitry Andric 
10938bcb0991SDimitry Andric   Register RegA = OpA.getReg();
10948bcb0991SDimitry Andric   Register RegB = OpB.getReg();
10958bcb0991SDimitry Andric   Register RegX = OpX.getReg();
10968bcb0991SDimitry Andric   Register RegY = OpY.getReg();
10978bcb0991SDimitry Andric   Register RegC = OpC.getReg();
10980b57cec5SDimitry Andric 
1099bdd1243dSDimitry Andric   if (RegA.isVirtual())
11000b57cec5SDimitry Andric     MRI.constrainRegClass(RegA, RC);
1101bdd1243dSDimitry Andric   if (RegB.isVirtual())
11020b57cec5SDimitry Andric     MRI.constrainRegClass(RegB, RC);
1103bdd1243dSDimitry Andric   if (RegX.isVirtual())
11040b57cec5SDimitry Andric     MRI.constrainRegClass(RegX, RC);
1105bdd1243dSDimitry Andric   if (RegY.isVirtual())
11060b57cec5SDimitry Andric     MRI.constrainRegClass(RegY, RC);
1107bdd1243dSDimitry Andric   if (RegC.isVirtual())
11080b57cec5SDimitry Andric     MRI.constrainRegClass(RegC, RC);
11090b57cec5SDimitry Andric 
11100b57cec5SDimitry Andric   // Create a new virtual register for the result of (X op Y) instead of
11110b57cec5SDimitry Andric   // recycling RegB because the MachineCombiner's computation of the critical
11120b57cec5SDimitry Andric   // path requires a new register definition rather than an existing one.
11138bcb0991SDimitry Andric   Register NewVR = MRI.createVirtualRegister(RC);
11140b57cec5SDimitry Andric   InstrIdxForVirtReg.insert(std::make_pair(NewVR, 0));
11150b57cec5SDimitry Andric 
1116bdd1243dSDimitry Andric   auto [NewRootOpc, NewPrevOpc] = getReassociationOpcodes(Pattern, Root, Prev);
11170b57cec5SDimitry Andric   bool KillA = OpA.isKill();
11180b57cec5SDimitry Andric   bool KillX = OpX.isKill();
11190b57cec5SDimitry Andric   bool KillY = OpY.isKill();
1120bdd1243dSDimitry Andric   bool KillNewVR = true;
1121bdd1243dSDimitry Andric 
1122bdd1243dSDimitry Andric   auto [SwapRootOperands, SwapPrevOperands] = mustSwapOperands(Pattern);
1123bdd1243dSDimitry Andric 
1124bdd1243dSDimitry Andric   if (SwapPrevOperands) {
1125bdd1243dSDimitry Andric     std::swap(RegX, RegY);
1126bdd1243dSDimitry Andric     std::swap(KillX, KillY);
1127bdd1243dSDimitry Andric   }
11280b57cec5SDimitry Andric 
11290b57cec5SDimitry Andric   // Create new instructions for insertion.
11300b57cec5SDimitry Andric   MachineInstrBuilder MIB1 =
1131bdd1243dSDimitry Andric       BuildMI(*MF, MIMetadata(Prev), TII->get(NewPrevOpc), NewVR)
11320b57cec5SDimitry Andric           .addReg(RegX, getKillRegState(KillX))
1133*c9157d92SDimitry Andric           .addReg(RegY, getKillRegState(KillY));
1134bdd1243dSDimitry Andric 
1135bdd1243dSDimitry Andric   if (SwapRootOperands) {
1136bdd1243dSDimitry Andric     std::swap(RegA, NewVR);
1137bdd1243dSDimitry Andric     std::swap(KillA, KillNewVR);
1138bdd1243dSDimitry Andric   }
1139bdd1243dSDimitry Andric 
11400b57cec5SDimitry Andric   MachineInstrBuilder MIB2 =
1141bdd1243dSDimitry Andric       BuildMI(*MF, MIMetadata(Root), TII->get(NewRootOpc), RegC)
11420b57cec5SDimitry Andric           .addReg(RegA, getKillRegState(KillA))
1143*c9157d92SDimitry Andric           .addReg(NewVR, getKillRegState(KillNewVR));
1144*c9157d92SDimitry Andric 
1145*c9157d92SDimitry Andric   // Propagate FP flags from the original instructions.
1146*c9157d92SDimitry Andric   // But clear poison-generating flags because those may not be valid now.
1147*c9157d92SDimitry Andric   // TODO: There should be a helper function for copying only fast-math-flags.
1148*c9157d92SDimitry Andric   uint32_t IntersectedFlags = Root.getFlags() & Prev.getFlags();
1149*c9157d92SDimitry Andric   MIB1->setFlags(IntersectedFlags);
1150*c9157d92SDimitry Andric   MIB1->clearFlag(MachineInstr::MIFlag::NoSWrap);
1151*c9157d92SDimitry Andric   MIB1->clearFlag(MachineInstr::MIFlag::NoUWrap);
1152*c9157d92SDimitry Andric   MIB1->clearFlag(MachineInstr::MIFlag::IsExact);
1153*c9157d92SDimitry Andric 
1154*c9157d92SDimitry Andric   MIB2->setFlags(IntersectedFlags);
1155*c9157d92SDimitry Andric   MIB2->clearFlag(MachineInstr::MIFlag::NoSWrap);
1156*c9157d92SDimitry Andric   MIB2->clearFlag(MachineInstr::MIFlag::NoUWrap);
1157*c9157d92SDimitry Andric   MIB2->clearFlag(MachineInstr::MIFlag::IsExact);
11580b57cec5SDimitry Andric 
11590b57cec5SDimitry Andric   setSpecialOperandAttr(Root, Prev, *MIB1, *MIB2);
11600b57cec5SDimitry Andric 
11610b57cec5SDimitry Andric   // Record new instructions for insertion and old instructions for deletion.
11620b57cec5SDimitry Andric   InsInstrs.push_back(MIB1);
11630b57cec5SDimitry Andric   InsInstrs.push_back(MIB2);
11640b57cec5SDimitry Andric   DelInstrs.push_back(&Prev);
11650b57cec5SDimitry Andric   DelInstrs.push_back(&Root);
1166fe013be4SDimitry Andric 
1167fe013be4SDimitry Andric   // We transformed:
1168fe013be4SDimitry Andric   // B = A op X (Prev)
1169fe013be4SDimitry Andric   // C = B op Y (Root)
1170fe013be4SDimitry Andric   // Into:
1171fe013be4SDimitry Andric   // B = X op Y (MIB1)
1172fe013be4SDimitry Andric   // C = A op B (MIB2)
1173fe013be4SDimitry Andric   // C has the same value as before, B doesn't; as such, keep the debug number
1174fe013be4SDimitry Andric   // of C but not of B.
1175fe013be4SDimitry Andric   if (unsigned OldRootNum = Root.peekDebugInstrNum())
1176fe013be4SDimitry Andric     MIB2.getInstr()->setDebugInstrNum(OldRootNum);
11770b57cec5SDimitry Andric }
11780b57cec5SDimitry Andric 
genAlternativeCodeSequence(MachineInstr & Root,MachineCombinerPattern Pattern,SmallVectorImpl<MachineInstr * > & InsInstrs,SmallVectorImpl<MachineInstr * > & DelInstrs,DenseMap<unsigned,unsigned> & InstIdxForVirtReg) const11790b57cec5SDimitry Andric void TargetInstrInfo::genAlternativeCodeSequence(
11800b57cec5SDimitry Andric     MachineInstr &Root, MachineCombinerPattern Pattern,
11810b57cec5SDimitry Andric     SmallVectorImpl<MachineInstr *> &InsInstrs,
11820b57cec5SDimitry Andric     SmallVectorImpl<MachineInstr *> &DelInstrs,
11830b57cec5SDimitry Andric     DenseMap<unsigned, unsigned> &InstIdxForVirtReg) const {
11840b57cec5SDimitry Andric   MachineRegisterInfo &MRI = Root.getMF()->getRegInfo();
11850b57cec5SDimitry Andric 
11860b57cec5SDimitry Andric   // Select the previous instruction in the sequence based on the input pattern.
11870b57cec5SDimitry Andric   MachineInstr *Prev = nullptr;
11880b57cec5SDimitry Andric   switch (Pattern) {
11890b57cec5SDimitry Andric   case MachineCombinerPattern::REASSOC_AX_BY:
11900b57cec5SDimitry Andric   case MachineCombinerPattern::REASSOC_XA_BY:
11910b57cec5SDimitry Andric     Prev = MRI.getUniqueVRegDef(Root.getOperand(1).getReg());
11920b57cec5SDimitry Andric     break;
11930b57cec5SDimitry Andric   case MachineCombinerPattern::REASSOC_AX_YB:
11940b57cec5SDimitry Andric   case MachineCombinerPattern::REASSOC_XA_YB:
11950b57cec5SDimitry Andric     Prev = MRI.getUniqueVRegDef(Root.getOperand(2).getReg());
11960b57cec5SDimitry Andric     break;
11970b57cec5SDimitry Andric   default:
1198fe013be4SDimitry Andric     llvm_unreachable("Unknown pattern for machine combiner");
11990b57cec5SDimitry Andric   }
12000b57cec5SDimitry Andric 
1201bdd1243dSDimitry Andric   // Don't reassociate if Prev and Root are in different blocks.
1202bdd1243dSDimitry Andric   if (Prev->getParent() != Root.getParent())
1203bdd1243dSDimitry Andric     return;
1204bdd1243dSDimitry Andric 
12050b57cec5SDimitry Andric   reassociateOps(Root, *Prev, Pattern, InsInstrs, DelInstrs, InstIdxForVirtReg);
12060b57cec5SDimitry Andric }
12070b57cec5SDimitry Andric 
getMachineCombinerTraceStrategy() const1208fe013be4SDimitry Andric MachineTraceStrategy TargetInstrInfo::getMachineCombinerTraceStrategy() const {
1209fe013be4SDimitry Andric   return MachineTraceStrategy::TS_MinInstrCount;
1210fe013be4SDimitry Andric }
1211fe013be4SDimitry Andric 
isReallyTriviallyReMaterializable(const MachineInstr & MI) const1212*c9157d92SDimitry Andric bool TargetInstrInfo::isReallyTriviallyReMaterializable(
1213fcaf7f86SDimitry Andric     const MachineInstr &MI) const {
12140b57cec5SDimitry Andric   const MachineFunction &MF = *MI.getMF();
12150b57cec5SDimitry Andric   const MachineRegisterInfo &MRI = MF.getRegInfo();
12160b57cec5SDimitry Andric 
12170b57cec5SDimitry Andric   // Remat clients assume operand 0 is the defined register.
12180b57cec5SDimitry Andric   if (!MI.getNumOperands() || !MI.getOperand(0).isReg())
12190b57cec5SDimitry Andric     return false;
12208bcb0991SDimitry Andric   Register DefReg = MI.getOperand(0).getReg();
12210b57cec5SDimitry Andric 
12220b57cec5SDimitry Andric   // A sub-register definition can only be rematerialized if the instruction
12230b57cec5SDimitry Andric   // doesn't read the other parts of the register.  Otherwise it is really a
12240b57cec5SDimitry Andric   // read-modify-write operation on the full virtual register which cannot be
12250b57cec5SDimitry Andric   // moved safely.
1226bdd1243dSDimitry Andric   if (DefReg.isVirtual() && MI.getOperand(0).getSubReg() &&
12278bcb0991SDimitry Andric       MI.readsVirtualRegister(DefReg))
12280b57cec5SDimitry Andric     return false;
12290b57cec5SDimitry Andric 
12300b57cec5SDimitry Andric   // A load from a fixed stack slot can be rematerialized. This may be
12310b57cec5SDimitry Andric   // redundant with subsequent checks, but it's target-independent,
12320b57cec5SDimitry Andric   // simple, and a common case.
12330b57cec5SDimitry Andric   int FrameIdx = 0;
12340b57cec5SDimitry Andric   if (isLoadFromStackSlot(MI, FrameIdx) &&
12350b57cec5SDimitry Andric       MF.getFrameInfo().isImmutableObjectIndex(FrameIdx))
12360b57cec5SDimitry Andric     return true;
12370b57cec5SDimitry Andric 
12380b57cec5SDimitry Andric   // Avoid instructions obviously unsafe for remat.
12390b57cec5SDimitry Andric   if (MI.isNotDuplicable() || MI.mayStore() || MI.mayRaiseFPException() ||
12400b57cec5SDimitry Andric       MI.hasUnmodeledSideEffects())
12410b57cec5SDimitry Andric     return false;
12420b57cec5SDimitry Andric 
12430b57cec5SDimitry Andric   // Don't remat inline asm. We have no idea how expensive it is
12440b57cec5SDimitry Andric   // even if it's side effect free.
12450b57cec5SDimitry Andric   if (MI.isInlineAsm())
12460b57cec5SDimitry Andric     return false;
12470b57cec5SDimitry Andric 
12480b57cec5SDimitry Andric   // Avoid instructions which load from potentially varying memory.
1249fcaf7f86SDimitry Andric   if (MI.mayLoad() && !MI.isDereferenceableInvariantLoad())
12500b57cec5SDimitry Andric     return false;
12510b57cec5SDimitry Andric 
12520b57cec5SDimitry Andric   // If any of the registers accessed are non-constant, conservatively assume
12530b57cec5SDimitry Andric   // the instruction is not rematerializable.
12544824e7fdSDimitry Andric   for (const MachineOperand &MO : MI.operands()) {
12550b57cec5SDimitry Andric     if (!MO.isReg()) continue;
12568bcb0991SDimitry Andric     Register Reg = MO.getReg();
12570b57cec5SDimitry Andric     if (Reg == 0)
12580b57cec5SDimitry Andric       continue;
12590b57cec5SDimitry Andric 
12600b57cec5SDimitry Andric     // Check for a well-behaved physical register.
1261bdd1243dSDimitry Andric     if (Reg.isPhysical()) {
12620b57cec5SDimitry Andric       if (MO.isUse()) {
12630b57cec5SDimitry Andric         // If the physreg has no defs anywhere, it's just an ambient register
12640b57cec5SDimitry Andric         // and we can freely move its uses. Alternatively, if it's allocatable,
12650b57cec5SDimitry Andric         // it could get allocated to something with a def during allocation.
12660b57cec5SDimitry Andric         if (!MRI.isConstantPhysReg(Reg))
12670b57cec5SDimitry Andric           return false;
12680b57cec5SDimitry Andric       } else {
12690b57cec5SDimitry Andric         // A physreg def. We can't remat it.
12700b57cec5SDimitry Andric         return false;
12710b57cec5SDimitry Andric       }
12720b57cec5SDimitry Andric       continue;
12730b57cec5SDimitry Andric     }
12740b57cec5SDimitry Andric 
12750b57cec5SDimitry Andric     // Only allow one virtual-register def.  There may be multiple defs of the
12760b57cec5SDimitry Andric     // same virtual register, though.
12770b57cec5SDimitry Andric     if (MO.isDef() && Reg != DefReg)
12780b57cec5SDimitry Andric       return false;
12790b57cec5SDimitry Andric 
12800b57cec5SDimitry Andric     // Don't allow any virtual-register uses. Rematting an instruction with
12810b57cec5SDimitry Andric     // virtual register uses would length the live ranges of the uses, which
12820b57cec5SDimitry Andric     // is not necessarily a good idea, certainly not "trivial".
12830b57cec5SDimitry Andric     if (MO.isUse())
12840b57cec5SDimitry Andric       return false;
12850b57cec5SDimitry Andric   }
12860b57cec5SDimitry Andric 
12870b57cec5SDimitry Andric   // Everything checked out.
12880b57cec5SDimitry Andric   return true;
12890b57cec5SDimitry Andric }
12900b57cec5SDimitry Andric 
getSPAdjust(const MachineInstr & MI) const12910b57cec5SDimitry Andric int TargetInstrInfo::getSPAdjust(const MachineInstr &MI) const {
12920b57cec5SDimitry Andric   const MachineFunction *MF = MI.getMF();
12930b57cec5SDimitry Andric   const TargetFrameLowering *TFI = MF->getSubtarget().getFrameLowering();
12940b57cec5SDimitry Andric   bool StackGrowsDown =
12950b57cec5SDimitry Andric     TFI->getStackGrowthDirection() == TargetFrameLowering::StackGrowsDown;
12960b57cec5SDimitry Andric 
12970b57cec5SDimitry Andric   unsigned FrameSetupOpcode = getCallFrameSetupOpcode();
12980b57cec5SDimitry Andric   unsigned FrameDestroyOpcode = getCallFrameDestroyOpcode();
12990b57cec5SDimitry Andric 
13000b57cec5SDimitry Andric   if (!isFrameInstr(MI))
13010b57cec5SDimitry Andric     return 0;
13020b57cec5SDimitry Andric 
13030b57cec5SDimitry Andric   int SPAdj = TFI->alignSPAdjust(getFrameSize(MI));
13040b57cec5SDimitry Andric 
13050b57cec5SDimitry Andric   if ((!StackGrowsDown && MI.getOpcode() == FrameSetupOpcode) ||
13060b57cec5SDimitry Andric       (StackGrowsDown && MI.getOpcode() == FrameDestroyOpcode))
13070b57cec5SDimitry Andric     SPAdj = -SPAdj;
13080b57cec5SDimitry Andric 
13090b57cec5SDimitry Andric   return SPAdj;
13100b57cec5SDimitry Andric }
13110b57cec5SDimitry Andric 
13120b57cec5SDimitry Andric /// isSchedulingBoundary - Test if the given instruction should be
13130b57cec5SDimitry Andric /// considered a scheduling boundary. This primarily includes labels
13140b57cec5SDimitry Andric /// and terminators.
isSchedulingBoundary(const MachineInstr & MI,const MachineBasicBlock * MBB,const MachineFunction & MF) const13150b57cec5SDimitry Andric bool TargetInstrInfo::isSchedulingBoundary(const MachineInstr &MI,
13160b57cec5SDimitry Andric                                            const MachineBasicBlock *MBB,
13170b57cec5SDimitry Andric                                            const MachineFunction &MF) const {
13180b57cec5SDimitry Andric   // Terminators and labels can't be scheduled around.
13190b57cec5SDimitry Andric   if (MI.isTerminator() || MI.isPosition())
13200b57cec5SDimitry Andric     return true;
13210b57cec5SDimitry Andric 
13225ffd83dbSDimitry Andric   // INLINEASM_BR can jump to another block
13235ffd83dbSDimitry Andric   if (MI.getOpcode() == TargetOpcode::INLINEASM_BR)
13245ffd83dbSDimitry Andric     return true;
13255ffd83dbSDimitry Andric 
13260b57cec5SDimitry Andric   // Don't attempt to schedule around any instruction that defines
13270b57cec5SDimitry Andric   // a stack-oriented pointer, as it's unlikely to be profitable. This
13280b57cec5SDimitry Andric   // saves compile time, because it doesn't require every single
13290b57cec5SDimitry Andric   // stack slot reference to depend on the instruction that does the
13300b57cec5SDimitry Andric   // modification.
13310b57cec5SDimitry Andric   const TargetLowering &TLI = *MF.getSubtarget().getTargetLowering();
13320b57cec5SDimitry Andric   const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
13330b57cec5SDimitry Andric   return MI.modifiesRegister(TLI.getStackPointerRegisterToSaveRestore(), TRI);
13340b57cec5SDimitry Andric }
13350b57cec5SDimitry Andric 
13360b57cec5SDimitry Andric // Provide a global flag for disabling the PreRA hazard recognizer that targets
13370b57cec5SDimitry Andric // may choose to honor.
usePreRAHazardRecognizer() const13380b57cec5SDimitry Andric bool TargetInstrInfo::usePreRAHazardRecognizer() const {
13390b57cec5SDimitry Andric   return !DisableHazardRecognizer;
13400b57cec5SDimitry Andric }
13410b57cec5SDimitry Andric 
13420b57cec5SDimitry Andric // Default implementation of CreateTargetRAHazardRecognizer.
13430b57cec5SDimitry Andric ScheduleHazardRecognizer *TargetInstrInfo::
CreateTargetHazardRecognizer(const TargetSubtargetInfo * STI,const ScheduleDAG * DAG) const13440b57cec5SDimitry Andric CreateTargetHazardRecognizer(const TargetSubtargetInfo *STI,
13450b57cec5SDimitry Andric                              const ScheduleDAG *DAG) const {
13460b57cec5SDimitry Andric   // Dummy hazard recognizer allows all instructions to issue.
13470b57cec5SDimitry Andric   return new ScheduleHazardRecognizer();
13480b57cec5SDimitry Andric }
13490b57cec5SDimitry Andric 
13500b57cec5SDimitry Andric // Default implementation of CreateTargetMIHazardRecognizer.
CreateTargetMIHazardRecognizer(const InstrItineraryData * II,const ScheduleDAGMI * DAG) const1351480093f4SDimitry Andric ScheduleHazardRecognizer *TargetInstrInfo::CreateTargetMIHazardRecognizer(
1352480093f4SDimitry Andric     const InstrItineraryData *II, const ScheduleDAGMI *DAG) const {
1353480093f4SDimitry Andric   return new ScoreboardHazardRecognizer(II, DAG, "machine-scheduler");
13540b57cec5SDimitry Andric }
13550b57cec5SDimitry Andric 
13560b57cec5SDimitry Andric // Default implementation of CreateTargetPostRAHazardRecognizer.
13570b57cec5SDimitry Andric ScheduleHazardRecognizer *TargetInstrInfo::
CreateTargetPostRAHazardRecognizer(const InstrItineraryData * II,const ScheduleDAG * DAG) const13580b57cec5SDimitry Andric CreateTargetPostRAHazardRecognizer(const InstrItineraryData *II,
13590b57cec5SDimitry Andric                                    const ScheduleDAG *DAG) const {
1360480093f4SDimitry Andric   return new ScoreboardHazardRecognizer(II, DAG, "post-RA-sched");
13610b57cec5SDimitry Andric }
13620b57cec5SDimitry Andric 
13635ffd83dbSDimitry Andric // Default implementation of getMemOperandWithOffset.
getMemOperandWithOffset(const MachineInstr & MI,const MachineOperand * & BaseOp,int64_t & Offset,bool & OffsetIsScalable,const TargetRegisterInfo * TRI) const13645ffd83dbSDimitry Andric bool TargetInstrInfo::getMemOperandWithOffset(
13655ffd83dbSDimitry Andric     const MachineInstr &MI, const MachineOperand *&BaseOp, int64_t &Offset,
13665ffd83dbSDimitry Andric     bool &OffsetIsScalable, const TargetRegisterInfo *TRI) const {
13675ffd83dbSDimitry Andric   SmallVector<const MachineOperand *, 4> BaseOps;
13685ffd83dbSDimitry Andric   unsigned Width;
13695ffd83dbSDimitry Andric   if (!getMemOperandsWithOffsetWidth(MI, BaseOps, Offset, OffsetIsScalable,
13705ffd83dbSDimitry Andric                                      Width, TRI) ||
13715ffd83dbSDimitry Andric       BaseOps.size() != 1)
13725ffd83dbSDimitry Andric     return false;
13735ffd83dbSDimitry Andric   BaseOp = BaseOps.front();
13745ffd83dbSDimitry Andric   return true;
13755ffd83dbSDimitry Andric }
13765ffd83dbSDimitry Andric 
13770b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
13780b57cec5SDimitry Andric //  SelectionDAG latency interface.
13790b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
13800b57cec5SDimitry Andric 
1381*c9157d92SDimitry Andric std::optional<unsigned>
getOperandLatency(const InstrItineraryData * ItinData,SDNode * DefNode,unsigned DefIdx,SDNode * UseNode,unsigned UseIdx) const13820b57cec5SDimitry Andric TargetInstrInfo::getOperandLatency(const InstrItineraryData *ItinData,
13830b57cec5SDimitry Andric                                    SDNode *DefNode, unsigned DefIdx,
13840b57cec5SDimitry Andric                                    SDNode *UseNode, unsigned UseIdx) const {
13850b57cec5SDimitry Andric   if (!ItinData || ItinData->isEmpty())
1386*c9157d92SDimitry Andric     return std::nullopt;
13870b57cec5SDimitry Andric 
13880b57cec5SDimitry Andric   if (!DefNode->isMachineOpcode())
1389*c9157d92SDimitry Andric     return std::nullopt;
13900b57cec5SDimitry Andric 
13910b57cec5SDimitry Andric   unsigned DefClass = get(DefNode->getMachineOpcode()).getSchedClass();
13920b57cec5SDimitry Andric   if (!UseNode->isMachineOpcode())
13930b57cec5SDimitry Andric     return ItinData->getOperandCycle(DefClass, DefIdx);
13940b57cec5SDimitry Andric   unsigned UseClass = get(UseNode->getMachineOpcode()).getSchedClass();
13950b57cec5SDimitry Andric   return ItinData->getOperandLatency(DefClass, DefIdx, UseClass, UseIdx);
13960b57cec5SDimitry Andric }
13970b57cec5SDimitry Andric 
getInstrLatency(const InstrItineraryData * ItinData,SDNode * N) const1398*c9157d92SDimitry Andric unsigned TargetInstrInfo::getInstrLatency(const InstrItineraryData *ItinData,
13990b57cec5SDimitry Andric                                           SDNode *N) const {
14000b57cec5SDimitry Andric   if (!ItinData || ItinData->isEmpty())
14010b57cec5SDimitry Andric     return 1;
14020b57cec5SDimitry Andric 
14030b57cec5SDimitry Andric   if (!N->isMachineOpcode())
14040b57cec5SDimitry Andric     return 1;
14050b57cec5SDimitry Andric 
14060b57cec5SDimitry Andric   return ItinData->getStageLatency(get(N->getMachineOpcode()).getSchedClass());
14070b57cec5SDimitry Andric }
14080b57cec5SDimitry Andric 
14090b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
14100b57cec5SDimitry Andric //  MachineInstr latency interface.
14110b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
14120b57cec5SDimitry Andric 
getNumMicroOps(const InstrItineraryData * ItinData,const MachineInstr & MI) const14130b57cec5SDimitry Andric unsigned TargetInstrInfo::getNumMicroOps(const InstrItineraryData *ItinData,
14140b57cec5SDimitry Andric                                          const MachineInstr &MI) const {
14150b57cec5SDimitry Andric   if (!ItinData || ItinData->isEmpty())
14160b57cec5SDimitry Andric     return 1;
14170b57cec5SDimitry Andric 
14180b57cec5SDimitry Andric   unsigned Class = MI.getDesc().getSchedClass();
14190b57cec5SDimitry Andric   int UOps = ItinData->Itineraries[Class].NumMicroOps;
14200b57cec5SDimitry Andric   if (UOps >= 0)
14210b57cec5SDimitry Andric     return UOps;
14220b57cec5SDimitry Andric 
14230b57cec5SDimitry Andric   // The # of u-ops is dynamically determined. The specific target should
14240b57cec5SDimitry Andric   // override this function to return the right number.
14250b57cec5SDimitry Andric   return 1;
14260b57cec5SDimitry Andric }
14270b57cec5SDimitry Andric 
14280b57cec5SDimitry Andric /// Return the default expected latency for a def based on it's opcode.
defaultDefLatency(const MCSchedModel & SchedModel,const MachineInstr & DefMI) const14290b57cec5SDimitry Andric unsigned TargetInstrInfo::defaultDefLatency(const MCSchedModel &SchedModel,
14300b57cec5SDimitry Andric                                             const MachineInstr &DefMI) const {
14310b57cec5SDimitry Andric   if (DefMI.isTransient())
14320b57cec5SDimitry Andric     return 0;
14330b57cec5SDimitry Andric   if (DefMI.mayLoad())
14340b57cec5SDimitry Andric     return SchedModel.LoadLatency;
14350b57cec5SDimitry Andric   if (isHighLatencyDef(DefMI.getOpcode()))
14360b57cec5SDimitry Andric     return SchedModel.HighLatency;
14370b57cec5SDimitry Andric   return 1;
14380b57cec5SDimitry Andric }
14390b57cec5SDimitry Andric 
getPredicationCost(const MachineInstr &) const14400b57cec5SDimitry Andric unsigned TargetInstrInfo::getPredicationCost(const MachineInstr &) const {
14410b57cec5SDimitry Andric   return 0;
14420b57cec5SDimitry Andric }
14430b57cec5SDimitry Andric 
getInstrLatency(const InstrItineraryData * ItinData,const MachineInstr & MI,unsigned * PredCost) const14440b57cec5SDimitry Andric unsigned TargetInstrInfo::getInstrLatency(const InstrItineraryData *ItinData,
14450b57cec5SDimitry Andric                                           const MachineInstr &MI,
14460b57cec5SDimitry Andric                                           unsigned *PredCost) const {
14470b57cec5SDimitry Andric   // Default to one cycle for no itinerary. However, an "empty" itinerary may
14480b57cec5SDimitry Andric   // still have a MinLatency property, which getStageLatency checks.
14490b57cec5SDimitry Andric   if (!ItinData)
14500b57cec5SDimitry Andric     return MI.mayLoad() ? 2 : 1;
14510b57cec5SDimitry Andric 
14520b57cec5SDimitry Andric   return ItinData->getStageLatency(MI.getDesc().getSchedClass());
14530b57cec5SDimitry Andric }
14540b57cec5SDimitry Andric 
hasLowDefLatency(const TargetSchedModel & SchedModel,const MachineInstr & DefMI,unsigned DefIdx) const14550b57cec5SDimitry Andric bool TargetInstrInfo::hasLowDefLatency(const TargetSchedModel &SchedModel,
14560b57cec5SDimitry Andric                                        const MachineInstr &DefMI,
14570b57cec5SDimitry Andric                                        unsigned DefIdx) const {
14580b57cec5SDimitry Andric   const InstrItineraryData *ItinData = SchedModel.getInstrItineraries();
14590b57cec5SDimitry Andric   if (!ItinData || ItinData->isEmpty())
14600b57cec5SDimitry Andric     return false;
14610b57cec5SDimitry Andric 
14620b57cec5SDimitry Andric   unsigned DefClass = DefMI.getDesc().getSchedClass();
1463*c9157d92SDimitry Andric   std::optional<unsigned> DefCycle =
1464*c9157d92SDimitry Andric       ItinData->getOperandCycle(DefClass, DefIdx);
1465*c9157d92SDimitry Andric   return DefCycle && DefCycle <= 1U;
1466*c9157d92SDimitry Andric }
1467*c9157d92SDimitry Andric 
isFunctionSafeToSplit(const MachineFunction & MF) const1468*c9157d92SDimitry Andric bool TargetInstrInfo::isFunctionSafeToSplit(const MachineFunction &MF) const {
1469*c9157d92SDimitry Andric   // TODO: We don't split functions where a section attribute has been set
1470*c9157d92SDimitry Andric   // since the split part may not be placed in a contiguous region. It may also
1471*c9157d92SDimitry Andric   // be more beneficial to augment the linker to ensure contiguous layout of
1472*c9157d92SDimitry Andric   // split functions within the same section as specified by the attribute.
1473*c9157d92SDimitry Andric   if (MF.getFunction().hasSection() ||
1474*c9157d92SDimitry Andric       MF.getFunction().hasFnAttribute("implicit-section-name"))
1475*c9157d92SDimitry Andric     return false;
1476*c9157d92SDimitry Andric 
1477*c9157d92SDimitry Andric   // We don't want to proceed further for cold functions
1478*c9157d92SDimitry Andric   // or functions of unknown hotness. Lukewarm functions have no prefix.
1479*c9157d92SDimitry Andric   std::optional<StringRef> SectionPrefix = MF.getFunction().getSectionPrefix();
1480*c9157d92SDimitry Andric   if (SectionPrefix &&
1481*c9157d92SDimitry Andric       (*SectionPrefix == "unlikely" || *SectionPrefix == "unknown")) {
1482*c9157d92SDimitry Andric     return false;
1483*c9157d92SDimitry Andric   }
1484*c9157d92SDimitry Andric 
1485*c9157d92SDimitry Andric   return true;
14860b57cec5SDimitry Andric }
14870b57cec5SDimitry Andric 
1488bdd1243dSDimitry Andric std::optional<ParamLoadedValue>
describeLoadedValue(const MachineInstr & MI,Register Reg) const1489480093f4SDimitry Andric TargetInstrInfo::describeLoadedValue(const MachineInstr &MI,
1490480093f4SDimitry Andric                                      Register Reg) const {
14918bcb0991SDimitry Andric   const MachineFunction *MF = MI.getMF();
1492480093f4SDimitry Andric   const TargetRegisterInfo *TRI = MF->getSubtarget().getRegisterInfo();
1493480093f4SDimitry Andric   DIExpression *Expr = DIExpression::get(MF->getFunction().getContext(), {});
1494480093f4SDimitry Andric   int64_t Offset;
14955ffd83dbSDimitry Andric   bool OffsetIsScalable;
14968bcb0991SDimitry Andric 
1497480093f4SDimitry Andric   // To simplify the sub-register handling, verify that we only need to
1498480093f4SDimitry Andric   // consider physical registers.
1499480093f4SDimitry Andric   assert(MF->getProperties().hasProperty(
1500480093f4SDimitry Andric       MachineFunctionProperties::Property::NoVRegs));
1501480093f4SDimitry Andric 
1502480093f4SDimitry Andric   if (auto DestSrc = isCopyInstr(MI)) {
1503480093f4SDimitry Andric     Register DestReg = DestSrc->Destination->getReg();
1504480093f4SDimitry Andric 
15055ffd83dbSDimitry Andric     // If the copy destination is the forwarding reg, describe the forwarding
15065ffd83dbSDimitry Andric     // reg using the copy source as the backup location. Example:
15075ffd83dbSDimitry Andric     //
15085ffd83dbSDimitry Andric     //   x0 = MOV x7
15095ffd83dbSDimitry Andric     //   call callee(x0)      ; x0 described as x7
1510480093f4SDimitry Andric     if (Reg == DestReg)
1511480093f4SDimitry Andric       return ParamLoadedValue(*DestSrc->Source, Expr);
1512480093f4SDimitry Andric 
1513fe013be4SDimitry Andric     // If the target's hook couldn't describe this copy, give up.
1514bdd1243dSDimitry Andric     return std::nullopt;
1515480093f4SDimitry Andric   } else if (auto RegImm = isAddImmediate(MI, Reg)) {
1516480093f4SDimitry Andric     Register SrcReg = RegImm->Reg;
1517480093f4SDimitry Andric     Offset = RegImm->Imm;
1518480093f4SDimitry Andric     Expr = DIExpression::prepend(Expr, DIExpression::ApplyOffset, Offset);
1519480093f4SDimitry Andric     return ParamLoadedValue(MachineOperand::CreateReg(SrcReg, false), Expr);
1520480093f4SDimitry Andric   } else if (MI.hasOneMemOperand()) {
1521480093f4SDimitry Andric     // Only describe memory which provably does not escape the function. As
1522480093f4SDimitry Andric     // described in llvm.org/PR43343, escaped memory may be clobbered by the
1523480093f4SDimitry Andric     // callee (or by another thread).
1524480093f4SDimitry Andric     const auto &TII = MF->getSubtarget().getInstrInfo();
1525480093f4SDimitry Andric     const MachineFrameInfo &MFI = MF->getFrameInfo();
1526480093f4SDimitry Andric     const MachineMemOperand *MMO = MI.memoperands()[0];
1527480093f4SDimitry Andric     const PseudoSourceValue *PSV = MMO->getPseudoValue();
1528480093f4SDimitry Andric 
1529480093f4SDimitry Andric     // If the address points to "special" memory (e.g. a spill slot), it's
1530480093f4SDimitry Andric     // sufficient to check that it isn't aliased by any high-level IR value.
1531480093f4SDimitry Andric     if (!PSV || PSV->mayAlias(&MFI))
1532bdd1243dSDimitry Andric       return std::nullopt;
1533480093f4SDimitry Andric 
1534480093f4SDimitry Andric     const MachineOperand *BaseOp;
15355ffd83dbSDimitry Andric     if (!TII->getMemOperandWithOffset(MI, BaseOp, Offset, OffsetIsScalable,
15365ffd83dbSDimitry Andric                                       TRI))
1537bdd1243dSDimitry Andric       return std::nullopt;
1538480093f4SDimitry Andric 
15395ffd83dbSDimitry Andric     // FIXME: Scalable offsets are not yet handled in the offset code below.
15405ffd83dbSDimitry Andric     if (OffsetIsScalable)
1541bdd1243dSDimitry Andric       return std::nullopt;
15425ffd83dbSDimitry Andric 
15435ffd83dbSDimitry Andric     // TODO: Can currently only handle mem instructions with a single define.
15445ffd83dbSDimitry Andric     // An example from the x86 target:
15455ffd83dbSDimitry Andric     //    ...
15465ffd83dbSDimitry Andric     //    DIV64m $rsp, 1, $noreg, 24, $noreg, implicit-def dead $rax, implicit-def $rdx
15475ffd83dbSDimitry Andric     //    ...
15485ffd83dbSDimitry Andric     //
15495ffd83dbSDimitry Andric     if (MI.getNumExplicitDefs() != 1)
1550bdd1243dSDimitry Andric       return std::nullopt;
1551480093f4SDimitry Andric 
1552480093f4SDimitry Andric     // TODO: In what way do we need to take Reg into consideration here?
1553480093f4SDimitry Andric 
1554480093f4SDimitry Andric     SmallVector<uint64_t, 8> Ops;
1555480093f4SDimitry Andric     DIExpression::appendOffset(Ops, Offset);
1556480093f4SDimitry Andric     Ops.push_back(dwarf::DW_OP_deref_size);
1557480093f4SDimitry Andric     Ops.push_back(MMO->getSize());
1558480093f4SDimitry Andric     Expr = DIExpression::prependOpcodes(Expr, Ops);
1559480093f4SDimitry Andric     return ParamLoadedValue(*BaseOp, Expr);
15608bcb0991SDimitry Andric   }
15618bcb0991SDimitry Andric 
1562bdd1243dSDimitry Andric   return std::nullopt;
15638bcb0991SDimitry Andric }
15648bcb0991SDimitry Andric 
1565*c9157d92SDimitry Andric // Get the call frame size just before MI.
getCallFrameSizeAt(MachineInstr & MI) const1566*c9157d92SDimitry Andric unsigned TargetInstrInfo::getCallFrameSizeAt(MachineInstr &MI) const {
1567*c9157d92SDimitry Andric   // Search backwards from MI for the most recent call frame instruction.
1568*c9157d92SDimitry Andric   MachineBasicBlock *MBB = MI.getParent();
1569*c9157d92SDimitry Andric   for (auto &AdjI : reverse(make_range(MBB->instr_begin(), MI.getIterator()))) {
1570*c9157d92SDimitry Andric     if (AdjI.getOpcode() == getCallFrameSetupOpcode())
1571*c9157d92SDimitry Andric       return getFrameTotalSize(AdjI);
1572*c9157d92SDimitry Andric     if (AdjI.getOpcode() == getCallFrameDestroyOpcode())
1573*c9157d92SDimitry Andric       return 0;
1574*c9157d92SDimitry Andric   }
1575*c9157d92SDimitry Andric 
1576*c9157d92SDimitry Andric   // If none was found, use the call frame size from the start of the basic
1577*c9157d92SDimitry Andric   // block.
1578*c9157d92SDimitry Andric   return MBB->getCallFrameSize();
1579*c9157d92SDimitry Andric }
1580*c9157d92SDimitry Andric 
15810b57cec5SDimitry Andric /// Both DefMI and UseMI must be valid.  By default, call directly to the
15820b57cec5SDimitry Andric /// itinerary. This may be overriden by the target.
getOperandLatency(const InstrItineraryData * ItinData,const MachineInstr & DefMI,unsigned DefIdx,const MachineInstr & UseMI,unsigned UseIdx) const1583*c9157d92SDimitry Andric std::optional<unsigned> TargetInstrInfo::getOperandLatency(
1584*c9157d92SDimitry Andric     const InstrItineraryData *ItinData, const MachineInstr &DefMI,
1585*c9157d92SDimitry Andric     unsigned DefIdx, const MachineInstr &UseMI, unsigned UseIdx) const {
15860b57cec5SDimitry Andric   unsigned DefClass = DefMI.getDesc().getSchedClass();
15870b57cec5SDimitry Andric   unsigned UseClass = UseMI.getDesc().getSchedClass();
15880b57cec5SDimitry Andric   return ItinData->getOperandLatency(DefClass, DefIdx, UseClass, UseIdx);
15890b57cec5SDimitry Andric }
15900b57cec5SDimitry Andric 
getRegSequenceInputs(const MachineInstr & MI,unsigned DefIdx,SmallVectorImpl<RegSubRegPairAndIdx> & InputRegs) const15910b57cec5SDimitry Andric bool TargetInstrInfo::getRegSequenceInputs(
15920b57cec5SDimitry Andric     const MachineInstr &MI, unsigned DefIdx,
15930b57cec5SDimitry Andric     SmallVectorImpl<RegSubRegPairAndIdx> &InputRegs) const {
15940b57cec5SDimitry Andric   assert((MI.isRegSequence() ||
15950b57cec5SDimitry Andric           MI.isRegSequenceLike()) && "Instruction do not have the proper type");
15960b57cec5SDimitry Andric 
15970b57cec5SDimitry Andric   if (!MI.isRegSequence())
15980b57cec5SDimitry Andric     return getRegSequenceLikeInputs(MI, DefIdx, InputRegs);
15990b57cec5SDimitry Andric 
16000b57cec5SDimitry Andric   // We are looking at:
16010b57cec5SDimitry Andric   // Def = REG_SEQUENCE v0, sub0, v1, sub1, ...
16020b57cec5SDimitry Andric   assert(DefIdx == 0 && "REG_SEQUENCE only has one def");
16030b57cec5SDimitry Andric   for (unsigned OpIdx = 1, EndOpIdx = MI.getNumOperands(); OpIdx != EndOpIdx;
16040b57cec5SDimitry Andric        OpIdx += 2) {
16050b57cec5SDimitry Andric     const MachineOperand &MOReg = MI.getOperand(OpIdx);
16060b57cec5SDimitry Andric     if (MOReg.isUndef())
16070b57cec5SDimitry Andric       continue;
16080b57cec5SDimitry Andric     const MachineOperand &MOSubIdx = MI.getOperand(OpIdx + 1);
16090b57cec5SDimitry Andric     assert(MOSubIdx.isImm() &&
16100b57cec5SDimitry Andric            "One of the subindex of the reg_sequence is not an immediate");
16110b57cec5SDimitry Andric     // Record Reg:SubReg, SubIdx.
16120b57cec5SDimitry Andric     InputRegs.push_back(RegSubRegPairAndIdx(MOReg.getReg(), MOReg.getSubReg(),
16130b57cec5SDimitry Andric                                             (unsigned)MOSubIdx.getImm()));
16140b57cec5SDimitry Andric   }
16150b57cec5SDimitry Andric   return true;
16160b57cec5SDimitry Andric }
16170b57cec5SDimitry Andric 
getExtractSubregInputs(const MachineInstr & MI,unsigned DefIdx,RegSubRegPairAndIdx & InputReg) const16180b57cec5SDimitry Andric bool TargetInstrInfo::getExtractSubregInputs(
16190b57cec5SDimitry Andric     const MachineInstr &MI, unsigned DefIdx,
16200b57cec5SDimitry Andric     RegSubRegPairAndIdx &InputReg) const {
16210b57cec5SDimitry Andric   assert((MI.isExtractSubreg() ||
16220b57cec5SDimitry Andric       MI.isExtractSubregLike()) && "Instruction do not have the proper type");
16230b57cec5SDimitry Andric 
16240b57cec5SDimitry Andric   if (!MI.isExtractSubreg())
16250b57cec5SDimitry Andric     return getExtractSubregLikeInputs(MI, DefIdx, InputReg);
16260b57cec5SDimitry Andric 
16270b57cec5SDimitry Andric   // We are looking at:
16280b57cec5SDimitry Andric   // Def = EXTRACT_SUBREG v0.sub1, sub0.
16290b57cec5SDimitry Andric   assert(DefIdx == 0 && "EXTRACT_SUBREG only has one def");
16300b57cec5SDimitry Andric   const MachineOperand &MOReg = MI.getOperand(1);
16310b57cec5SDimitry Andric   if (MOReg.isUndef())
16320b57cec5SDimitry Andric     return false;
16330b57cec5SDimitry Andric   const MachineOperand &MOSubIdx = MI.getOperand(2);
16340b57cec5SDimitry Andric   assert(MOSubIdx.isImm() &&
16350b57cec5SDimitry Andric          "The subindex of the extract_subreg is not an immediate");
16360b57cec5SDimitry Andric 
16370b57cec5SDimitry Andric   InputReg.Reg = MOReg.getReg();
16380b57cec5SDimitry Andric   InputReg.SubReg = MOReg.getSubReg();
16390b57cec5SDimitry Andric   InputReg.SubIdx = (unsigned)MOSubIdx.getImm();
16400b57cec5SDimitry Andric   return true;
16410b57cec5SDimitry Andric }
16420b57cec5SDimitry Andric 
getInsertSubregInputs(const MachineInstr & MI,unsigned DefIdx,RegSubRegPair & BaseReg,RegSubRegPairAndIdx & InsertedReg) const16430b57cec5SDimitry Andric bool TargetInstrInfo::getInsertSubregInputs(
16440b57cec5SDimitry Andric     const MachineInstr &MI, unsigned DefIdx,
16450b57cec5SDimitry Andric     RegSubRegPair &BaseReg, RegSubRegPairAndIdx &InsertedReg) const {
16460b57cec5SDimitry Andric   assert((MI.isInsertSubreg() ||
16470b57cec5SDimitry Andric       MI.isInsertSubregLike()) && "Instruction do not have the proper type");
16480b57cec5SDimitry Andric 
16490b57cec5SDimitry Andric   if (!MI.isInsertSubreg())
16500b57cec5SDimitry Andric     return getInsertSubregLikeInputs(MI, DefIdx, BaseReg, InsertedReg);
16510b57cec5SDimitry Andric 
16520b57cec5SDimitry Andric   // We are looking at:
16530b57cec5SDimitry Andric   // Def = INSERT_SEQUENCE v0, v1, sub0.
16540b57cec5SDimitry Andric   assert(DefIdx == 0 && "INSERT_SUBREG only has one def");
16550b57cec5SDimitry Andric   const MachineOperand &MOBaseReg = MI.getOperand(1);
16560b57cec5SDimitry Andric   const MachineOperand &MOInsertedReg = MI.getOperand(2);
16570b57cec5SDimitry Andric   if (MOInsertedReg.isUndef())
16580b57cec5SDimitry Andric     return false;
16590b57cec5SDimitry Andric   const MachineOperand &MOSubIdx = MI.getOperand(3);
16600b57cec5SDimitry Andric   assert(MOSubIdx.isImm() &&
16610b57cec5SDimitry Andric          "One of the subindex of the reg_sequence is not an immediate");
16620b57cec5SDimitry Andric   BaseReg.Reg = MOBaseReg.getReg();
16630b57cec5SDimitry Andric   BaseReg.SubReg = MOBaseReg.getSubReg();
16640b57cec5SDimitry Andric 
16650b57cec5SDimitry Andric   InsertedReg.Reg = MOInsertedReg.getReg();
16660b57cec5SDimitry Andric   InsertedReg.SubReg = MOInsertedReg.getSubReg();
16670b57cec5SDimitry Andric   InsertedReg.SubIdx = (unsigned)MOSubIdx.getImm();
16680b57cec5SDimitry Andric   return true;
16690b57cec5SDimitry Andric }
16708bcb0991SDimitry Andric 
16715ffd83dbSDimitry Andric // Returns a MIRPrinter comment for this machine operand.
createMIROperandComment(const MachineInstr & MI,const MachineOperand & Op,unsigned OpIdx,const TargetRegisterInfo * TRI) const16725ffd83dbSDimitry Andric std::string TargetInstrInfo::createMIROperandComment(
16735ffd83dbSDimitry Andric     const MachineInstr &MI, const MachineOperand &Op, unsigned OpIdx,
16745ffd83dbSDimitry Andric     const TargetRegisterInfo *TRI) const {
16755ffd83dbSDimitry Andric 
16765ffd83dbSDimitry Andric   if (!MI.isInlineAsm())
16775ffd83dbSDimitry Andric     return "";
16785ffd83dbSDimitry Andric 
16795ffd83dbSDimitry Andric   std::string Flags;
16805ffd83dbSDimitry Andric   raw_string_ostream OS(Flags);
16815ffd83dbSDimitry Andric 
16825ffd83dbSDimitry Andric   if (OpIdx == InlineAsm::MIOp_ExtraInfo) {
16835ffd83dbSDimitry Andric     // Print HasSideEffects, MayLoad, MayStore, IsAlignStack
16845ffd83dbSDimitry Andric     unsigned ExtraInfo = Op.getImm();
16855ffd83dbSDimitry Andric     bool First = true;
16865ffd83dbSDimitry Andric     for (StringRef Info : InlineAsm::getExtraInfoNames(ExtraInfo)) {
16875ffd83dbSDimitry Andric       if (!First)
16885ffd83dbSDimitry Andric         OS << " ";
16895ffd83dbSDimitry Andric       First = false;
16905ffd83dbSDimitry Andric       OS << Info;
16915ffd83dbSDimitry Andric     }
16925ffd83dbSDimitry Andric 
16935ffd83dbSDimitry Andric     return OS.str();
16945ffd83dbSDimitry Andric   }
16955ffd83dbSDimitry Andric 
16965ffd83dbSDimitry Andric   int FlagIdx = MI.findInlineAsmFlagIdx(OpIdx);
16975ffd83dbSDimitry Andric   if (FlagIdx < 0 || (unsigned)FlagIdx != OpIdx)
16985ffd83dbSDimitry Andric     return "";
16995ffd83dbSDimitry Andric 
17005ffd83dbSDimitry Andric   assert(Op.isImm() && "Expected flag operand to be an immediate");
17015ffd83dbSDimitry Andric   // Pretty print the inline asm operand descriptor.
17025ffd83dbSDimitry Andric   unsigned Flag = Op.getImm();
1703*c9157d92SDimitry Andric   const InlineAsm::Flag F(Flag);
1704*c9157d92SDimitry Andric   OS << F.getKindName();
17055ffd83dbSDimitry Andric 
1706*c9157d92SDimitry Andric   unsigned RCID;
1707*c9157d92SDimitry Andric   if (!F.isImmKind() && !F.isMemKind() && F.hasRegClassConstraint(RCID)) {
17085ffd83dbSDimitry Andric     if (TRI) {
17095ffd83dbSDimitry Andric       OS << ':' << TRI->getRegClassName(TRI->getRegClass(RCID));
17105ffd83dbSDimitry Andric     } else
17115ffd83dbSDimitry Andric       OS << ":RC" << RCID;
17125ffd83dbSDimitry Andric   }
17135ffd83dbSDimitry Andric 
1714*c9157d92SDimitry Andric   if (F.isMemKind()) {
1715*c9157d92SDimitry Andric     InlineAsm::ConstraintCode MCID = F.getMemoryConstraintID();
17165ffd83dbSDimitry Andric     OS << ":" << InlineAsm::getMemConstraintName(MCID);
17175ffd83dbSDimitry Andric   }
17185ffd83dbSDimitry Andric 
1719*c9157d92SDimitry Andric   unsigned TiedTo;
1720*c9157d92SDimitry Andric   if (F.isUseOperandTiedToDef(TiedTo))
17215ffd83dbSDimitry Andric     OS << " tiedto:$" << TiedTo;
17225ffd83dbSDimitry Andric 
1723*c9157d92SDimitry Andric   if ((F.isRegDefKind() || F.isRegDefEarlyClobberKind() || F.isRegUseKind()) &&
1724*c9157d92SDimitry Andric       F.getRegMayBeFolded())
1725*c9157d92SDimitry Andric     OS << " foldable";
1726*c9157d92SDimitry Andric 
17275ffd83dbSDimitry Andric   return OS.str();
17285ffd83dbSDimitry Andric }
17295ffd83dbSDimitry Andric 
173081ad6265SDimitry Andric TargetInstrInfo::PipelinerLoopInfo::~PipelinerLoopInfo() = default;
17314824e7fdSDimitry Andric 
mergeOutliningCandidateAttributes(Function & F,std::vector<outliner::Candidate> & Candidates) const17324824e7fdSDimitry Andric void TargetInstrInfo::mergeOutliningCandidateAttributes(
17334824e7fdSDimitry Andric     Function &F, std::vector<outliner::Candidate> &Candidates) const {
17344824e7fdSDimitry Andric   // Include target features from an arbitrary candidate for the outlined
17354824e7fdSDimitry Andric   // function. This makes sure the outlined function knows what kinds of
17364824e7fdSDimitry Andric   // instructions are going into it. This is fine, since all parent functions
17374824e7fdSDimitry Andric   // must necessarily support the instructions that are in the outlined region.
17384824e7fdSDimitry Andric   outliner::Candidate &FirstCand = Candidates.front();
17394824e7fdSDimitry Andric   const Function &ParentFn = FirstCand.getMF()->getFunction();
17404824e7fdSDimitry Andric   if (ParentFn.hasFnAttribute("target-features"))
17414824e7fdSDimitry Andric     F.addFnAttr(ParentFn.getFnAttribute("target-features"));
1742bdd1243dSDimitry Andric   if (ParentFn.hasFnAttribute("target-cpu"))
1743bdd1243dSDimitry Andric     F.addFnAttr(ParentFn.getFnAttribute("target-cpu"));
17444824e7fdSDimitry Andric 
17454824e7fdSDimitry Andric   // Set nounwind, so we don't generate eh_frame.
17464824e7fdSDimitry Andric   if (llvm::all_of(Candidates, [](const outliner::Candidate &C) {
17474824e7fdSDimitry Andric         return C.getMF()->getFunction().hasFnAttribute(Attribute::NoUnwind);
17484824e7fdSDimitry Andric       }))
17494824e7fdSDimitry Andric     F.addFnAttr(Attribute::NoUnwind);
17504824e7fdSDimitry Andric }
17510eae32dcSDimitry Andric 
getOutliningType(MachineBasicBlock::iterator & MIT,unsigned Flags) const1752fe013be4SDimitry Andric outliner::InstrType TargetInstrInfo::getOutliningType(
1753fe013be4SDimitry Andric     MachineBasicBlock::iterator &MIT, unsigned Flags) const {
1754fe013be4SDimitry Andric   MachineInstr &MI = *MIT;
1755fe013be4SDimitry Andric 
1756fe013be4SDimitry Andric   // NOTE: MI.isMetaInstruction() will match CFI_INSTRUCTION, but some targets
1757fe013be4SDimitry Andric   // have support for outlining those. Special-case that here.
1758fe013be4SDimitry Andric   if (MI.isCFIInstruction())
1759fe013be4SDimitry Andric     // Just go right to the target implementation.
1760fe013be4SDimitry Andric     return getOutliningTypeImpl(MIT, Flags);
1761fe013be4SDimitry Andric 
1762fe013be4SDimitry Andric   // Be conservative about inline assembly.
1763fe013be4SDimitry Andric   if (MI.isInlineAsm())
1764fe013be4SDimitry Andric     return outliner::InstrType::Illegal;
1765fe013be4SDimitry Andric 
1766fe013be4SDimitry Andric   // Labels generally can't safely be outlined.
1767fe013be4SDimitry Andric   if (MI.isLabel())
1768fe013be4SDimitry Andric     return outliner::InstrType::Illegal;
1769fe013be4SDimitry Andric 
1770fe013be4SDimitry Andric   // Don't let debug instructions impact analysis.
1771fe013be4SDimitry Andric   if (MI.isDebugInstr())
1772fe013be4SDimitry Andric     return outliner::InstrType::Invisible;
1773fe013be4SDimitry Andric 
1774fe013be4SDimitry Andric   // Some other special cases.
1775fe013be4SDimitry Andric   switch (MI.getOpcode()) {
1776fe013be4SDimitry Andric     case TargetOpcode::IMPLICIT_DEF:
1777fe013be4SDimitry Andric     case TargetOpcode::KILL:
1778fe013be4SDimitry Andric     case TargetOpcode::LIFETIME_START:
1779fe013be4SDimitry Andric     case TargetOpcode::LIFETIME_END:
1780fe013be4SDimitry Andric       return outliner::InstrType::Invisible;
1781fe013be4SDimitry Andric     default:
1782fe013be4SDimitry Andric       break;
1783fe013be4SDimitry Andric   }
1784fe013be4SDimitry Andric 
1785fe013be4SDimitry Andric   // Is this a terminator for a basic block?
1786fe013be4SDimitry Andric   if (MI.isTerminator()) {
1787fe013be4SDimitry Andric     // If this is a branch to another block, we can't outline it.
1788fe013be4SDimitry Andric     if (!MI.getParent()->succ_empty())
1789fe013be4SDimitry Andric       return outliner::InstrType::Illegal;
1790fe013be4SDimitry Andric 
1791fe013be4SDimitry Andric     // Don't outline if the branch is not unconditional.
1792fe013be4SDimitry Andric     if (isPredicated(MI))
1793fe013be4SDimitry Andric       return outliner::InstrType::Illegal;
1794fe013be4SDimitry Andric   }
1795fe013be4SDimitry Andric 
1796fe013be4SDimitry Andric   // Make sure none of the operands of this instruction do anything that
1797fe013be4SDimitry Andric   // might break if they're moved outside their current function.
1798fe013be4SDimitry Andric   // This includes MachineBasicBlock references, BlockAddressses,
1799fe013be4SDimitry Andric   // Constant pool indices and jump table indices.
1800fe013be4SDimitry Andric   //
1801fe013be4SDimitry Andric   // A quick note on MO_TargetIndex:
1802fe013be4SDimitry Andric   // This doesn't seem to be used in any of the architectures that the
1803fe013be4SDimitry Andric   // MachineOutliner supports, but it was still filtered out in all of them.
1804fe013be4SDimitry Andric   // There was one exception (RISC-V), but MO_TargetIndex also isn't used there.
1805fe013be4SDimitry Andric   // As such, this check is removed both here and in the target-specific
1806fe013be4SDimitry Andric   // implementations. Instead, we assert to make sure this doesn't
1807fe013be4SDimitry Andric   // catch anyone off-guard somewhere down the line.
1808fe013be4SDimitry Andric   for (const MachineOperand &MOP : MI.operands()) {
1809fe013be4SDimitry Andric     // If you hit this assertion, please remove it and adjust
1810fe013be4SDimitry Andric     // `getOutliningTypeImpl` for your target appropriately if necessary.
1811fe013be4SDimitry Andric     // Adding the assertion back to other supported architectures
1812fe013be4SDimitry Andric     // would be nice too :)
1813fe013be4SDimitry Andric     assert(!MOP.isTargetIndex() && "This isn't used quite yet!");
1814fe013be4SDimitry Andric 
1815fe013be4SDimitry Andric     // CFI instructions should already have been filtered out at this point.
1816fe013be4SDimitry Andric     assert(!MOP.isCFIIndex() && "CFI instructions handled elsewhere!");
1817fe013be4SDimitry Andric 
1818fe013be4SDimitry Andric     // PrologEpilogInserter should've already run at this point.
1819fe013be4SDimitry Andric     assert(!MOP.isFI() && "FrameIndex instructions should be gone by now!");
1820fe013be4SDimitry Andric 
1821fe013be4SDimitry Andric     if (MOP.isMBB() || MOP.isBlockAddress() || MOP.isCPI() || MOP.isJTI())
1822fe013be4SDimitry Andric       return outliner::InstrType::Illegal;
1823fe013be4SDimitry Andric   }
1824fe013be4SDimitry Andric 
1825fe013be4SDimitry Andric   // If we don't know, delegate to the target-specific hook.
1826fe013be4SDimitry Andric   return getOutliningTypeImpl(MIT, Flags);
1827fe013be4SDimitry Andric }
1828fe013be4SDimitry Andric 
isMBBSafeToOutlineFrom(MachineBasicBlock & MBB,unsigned & Flags) const18290eae32dcSDimitry Andric bool TargetInstrInfo::isMBBSafeToOutlineFrom(MachineBasicBlock &MBB,
18300eae32dcSDimitry Andric                                              unsigned &Flags) const {
18310eae32dcSDimitry Andric   // Some instrumentations create special TargetOpcode at the start which
18320eae32dcSDimitry Andric   // expands to special code sequences which must be present.
18330eae32dcSDimitry Andric   auto First = MBB.getFirstNonDebugInstr();
1834fe013be4SDimitry Andric   if (First == MBB.end())
1835fe013be4SDimitry Andric     return true;
1836fe013be4SDimitry Andric 
1837fe013be4SDimitry Andric   if (First->getOpcode() == TargetOpcode::FENTRY_CALL ||
1838fe013be4SDimitry Andric       First->getOpcode() == TargetOpcode::PATCHABLE_FUNCTION_ENTER)
18390eae32dcSDimitry Andric     return false;
18400eae32dcSDimitry Andric 
1841fe013be4SDimitry Andric   // Some instrumentations create special pseudo-instructions at or just before
1842fe013be4SDimitry Andric   // the end that must be present.
1843fe013be4SDimitry Andric   auto Last = MBB.getLastNonDebugInstr();
1844fe013be4SDimitry Andric   if (Last->getOpcode() == TargetOpcode::PATCHABLE_RET ||
1845fe013be4SDimitry Andric       Last->getOpcode() == TargetOpcode::PATCHABLE_TAIL_CALL)
1846fe013be4SDimitry Andric     return false;
1847fe013be4SDimitry Andric 
1848fe013be4SDimitry Andric   if (Last != First && Last->isReturn()) {
1849fe013be4SDimitry Andric     --Last;
1850fe013be4SDimitry Andric     if (Last->getOpcode() == TargetOpcode::PATCHABLE_FUNCTION_EXIT ||
1851fe013be4SDimitry Andric         Last->getOpcode() == TargetOpcode::PATCHABLE_TAIL_CALL)
1852fe013be4SDimitry Andric       return false;
1853fe013be4SDimitry Andric   }
18540eae32dcSDimitry Andric   return true;
18550eae32dcSDimitry Andric }
1856