#include "InstrEmitter.h"
#include "SDNodeDbgValue.h"
#include "llvm/BinaryFormat/Dwarf.h"
#include "llvm/CodeGen/MachineConstantPool.h"
#include "llvm/CodeGen/MachineFunction.h"
#include "llvm/CodeGen/MachineInstrBuilder.h"
#include "llvm/CodeGen/MachineRegisterInfo.h"
#include "llvm/CodeGen/StackMaps.h"
#include "llvm/CodeGen/TargetInstrInfo.h"
#include "llvm/CodeGen/TargetLowering.h"
#include "llvm/CodeGen/TargetSubtargetInfo.h"
#include "llvm/IR/DebugInfoMetadata.h"
#include "llvm/IR/PseudoProbe.h"
#include "llvm/Support/ErrorHandling.h"
#include "llvm/Target/TargetMachine.h"
using namespace llvm;
#define DEBUG_TYPE "instr-emitter"
const unsigned MinRCSize = 4;
unsigned InstrEmitter::CountResults(SDNode *Node) {
unsigned N = Node->getNumValues();
while (N && Node->getValueType(N - 1) == MVT::Glue)
--N;
if (N && Node->getValueType(N - 1) == MVT::Other)
--N; return N;
}
static unsigned countOperands(SDNode *Node, unsigned NumExpUses,
unsigned &NumImpUses) {
unsigned N = Node->getNumOperands();
while (N && Node->getOperand(N - 1).getValueType() == MVT::Glue)
--N;
if (N && Node->getOperand(N - 1).getValueType() == MVT::Other)
--N;
NumImpUses = N - NumExpUses;
for (unsigned I = N; I > NumExpUses; --I) {
if (isa<RegisterMaskSDNode>(Node->getOperand(I - 1)))
continue;
if (RegisterSDNode *RN = dyn_cast<RegisterSDNode>(Node->getOperand(I - 1)))
if (Register::isPhysicalRegister(RN->getReg()))
continue;
NumImpUses = N - I;
break;
}
return N;
}
void InstrEmitter::
EmitCopyFromReg(SDNode *Node, unsigned ResNo, bool IsClone, bool IsCloned,
Register SrcReg, DenseMap<SDValue, Register> &VRBaseMap) {
Register VRBase;
if (SrcReg.isVirtual()) {
SDValue Op(Node, ResNo);
if (IsClone)
VRBaseMap.erase(Op);
bool isNew = VRBaseMap.insert(std::make_pair(Op, SrcReg)).second;
(void)isNew; assert(isNew && "Node emitted out of order - early");
return;
}
bool MatchReg = true;
const TargetRegisterClass *UseRC = nullptr;
MVT VT = Node->getSimpleValueType(ResNo);
if (TLI->isTypeLegal(VT))
UseRC = TLI->getRegClassFor(VT, Node->isDivergent());
if (!IsClone && !IsCloned)
for (SDNode *User : Node->uses()) {
bool Match = true;
if (User->getOpcode() == ISD::CopyToReg &&
User->getOperand(2).getNode() == Node &&
User->getOperand(2).getResNo() == ResNo) {
Register DestReg = cast<RegisterSDNode>(User->getOperand(1))->getReg();
if (DestReg.isVirtual()) {
VRBase = DestReg;
Match = false;
} else if (DestReg != SrcReg)
Match = false;
} else {
for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i) {
SDValue Op = User->getOperand(i);
if (Op.getNode() != Node || Op.getResNo() != ResNo)
continue;
MVT VT = Node->getSimpleValueType(Op.getResNo());
if (VT == MVT::Other || VT == MVT::Glue)
continue;
Match = false;
if (User->isMachineOpcode()) {
const MCInstrDesc &II = TII->get(User->getMachineOpcode());
const TargetRegisterClass *RC = nullptr;
if (i+II.getNumDefs() < II.getNumOperands()) {
RC = TRI->getAllocatableClass(
TII->getRegClass(II, i+II.getNumDefs(), TRI, *MF));
}
if (!UseRC)
UseRC = RC;
else if (RC) {
const TargetRegisterClass *ComRC =
TRI->getCommonSubClass(UseRC, RC);
if (ComRC)
UseRC = ComRC;
}
}
}
}
MatchReg &= Match;
if (VRBase)
break;
}
const TargetRegisterClass *SrcRC = nullptr, *DstRC = nullptr;
SrcRC = TRI->getMinimalPhysRegClass(SrcReg, VT);
if (VRBase) {
DstRC = MRI->getRegClass(VRBase);
} else if (UseRC) {
assert(TRI->isTypeLegalForClass(*UseRC, VT) &&
"Incompatible phys register def and uses!");
DstRC = UseRC;
} else
DstRC = SrcRC;
if (MatchReg && SrcRC->getCopyCost() < 0) {
VRBase = SrcReg;
} else {
VRBase = MRI->createVirtualRegister(DstRC);
BuildMI(*MBB, InsertPos, Node->getDebugLoc(), TII->get(TargetOpcode::COPY),
VRBase).addReg(SrcReg);
}
SDValue Op(Node, ResNo);
if (IsClone)
VRBaseMap.erase(Op);
bool isNew = VRBaseMap.insert(std::make_pair(Op, VRBase)).second;
(void)isNew; assert(isNew && "Node emitted out of order - early");
}
void InstrEmitter::CreateVirtualRegisters(SDNode *Node,
MachineInstrBuilder &MIB,
const MCInstrDesc &II,
bool IsClone, bool IsCloned,
DenseMap<SDValue, Register> &VRBaseMap) {
assert(Node->getMachineOpcode() != TargetOpcode::IMPLICIT_DEF &&
"IMPLICIT_DEF should have been handled as a special case elsewhere!");
unsigned NumResults = CountResults(Node);
bool HasVRegVariadicDefs = !MF->getTarget().usesPhysRegsForValues() &&
II.isVariadic() && II.variadicOpsAreDefs();
unsigned NumVRegs = HasVRegVariadicDefs ? NumResults : II.getNumDefs();
if (Node->getMachineOpcode() == TargetOpcode::STATEPOINT)
NumVRegs = NumResults;
for (unsigned i = 0; i < NumVRegs; ++i) {
Register VRBase;
const TargetRegisterClass *RC =
TRI->getAllocatableClass(TII->getRegClass(II, i, TRI, *MF));
if (i < NumResults && TLI->isTypeLegal(Node->getSimpleValueType(i))) {
const TargetRegisterClass *VTRC = TLI->getRegClassFor(
Node->getSimpleValueType(i),
(Node->isDivergent() || (RC && TRI->isDivergentRegClass(RC))));
if (RC)
VTRC = TRI->getCommonSubClass(RC, VTRC);
if (VTRC)
RC = VTRC;
}
if (II.OpInfo != nullptr && II.OpInfo[i].isOptionalDef()) {
VRBase = cast<RegisterSDNode>(Node->getOperand(i-NumResults))->getReg();
assert(VRBase.isPhysical());
MIB.addReg(VRBase, RegState::Define);
}
if (!VRBase && !IsClone && !IsCloned)
for (SDNode *User : Node->uses()) {
if (User->getOpcode() == ISD::CopyToReg &&
User->getOperand(2).getNode() == Node &&
User->getOperand(2).getResNo() == i) {
unsigned Reg = cast<RegisterSDNode>(User->getOperand(1))->getReg();
if (Register::isVirtualRegister(Reg)) {
const TargetRegisterClass *RegRC = MRI->getRegClass(Reg);
if (RegRC == RC) {
VRBase = Reg;
MIB.addReg(VRBase, RegState::Define);
break;
}
}
}
}
if (VRBase == 0) {
assert(RC && "Isn't a register operand!");
VRBase = MRI->createVirtualRegister(RC);
MIB.addReg(VRBase, RegState::Define);
}
if (i < NumResults) {
SDValue Op(Node, i);
if (IsClone)
VRBaseMap.erase(Op);
bool isNew = VRBaseMap.insert(std::make_pair(Op, VRBase)).second;
(void)isNew; assert(isNew && "Node emitted out of order - early");
}
}
}
Register InstrEmitter::getVR(SDValue Op,
DenseMap<SDValue, Register> &VRBaseMap) {
if (Op.isMachineOpcode() &&
Op.getMachineOpcode() == TargetOpcode::IMPLICIT_DEF) {
const TargetRegisterClass *RC = TLI->getRegClassFor(
Op.getSimpleValueType(), Op.getNode()->isDivergent());
Register VReg = MRI->createVirtualRegister(RC);
BuildMI(*MBB, InsertPos, Op.getDebugLoc(),
TII->get(TargetOpcode::IMPLICIT_DEF), VReg);
return VReg;
}
DenseMap<SDValue, Register>::iterator I = VRBaseMap.find(Op);
assert(I != VRBaseMap.end() && "Node emitted out of order - late");
return I->second;
}
void
InstrEmitter::AddRegisterOperand(MachineInstrBuilder &MIB,
SDValue Op,
unsigned IIOpNum,
const MCInstrDesc *II,
DenseMap<SDValue, Register> &VRBaseMap,
bool IsDebug, bool IsClone, bool IsCloned) {
assert(Op.getValueType() != MVT::Other &&
Op.getValueType() != MVT::Glue &&
"Chain and glue operands should occur at end of operand list!");
Register VReg = getVR(Op, VRBaseMap);
const MCInstrDesc &MCID = MIB->getDesc();
bool isOptDef = IIOpNum < MCID.getNumOperands() &&
MCID.OpInfo[IIOpNum].isOptionalDef();
if (II) {
const TargetRegisterClass *OpRC = nullptr;
if (IIOpNum < II->getNumOperands())
OpRC = TII->getRegClass(*II, IIOpNum, TRI, *MF);
if (OpRC) {
unsigned MinNumRegs = MinRCSize;
if (Op.isMachineOpcode() &&
Op.getMachineOpcode() == TargetOpcode::IMPLICIT_DEF)
MinNumRegs = 0;
const TargetRegisterClass *ConstrainedRC
= MRI->constrainRegClass(VReg, OpRC, MinNumRegs);
if (!ConstrainedRC) {
OpRC = TRI->getAllocatableClass(OpRC);
assert(OpRC && "Constraints cannot be fulfilled for allocation");
Register NewVReg = MRI->createVirtualRegister(OpRC);
BuildMI(*MBB, InsertPos, Op.getNode()->getDebugLoc(),
TII->get(TargetOpcode::COPY), NewVReg).addReg(VReg);
VReg = NewVReg;
} else {
assert(ConstrainedRC->isAllocatable() &&
"Constraining an allocatable VReg produced an unallocatable class?");
}
}
}
bool isKill = Op.hasOneUse() &&
Op.getNode()->getOpcode() != ISD::CopyFromReg &&
!IsDebug &&
!(IsClone || IsCloned);
if (isKill) {
unsigned Idx = MIB->getNumOperands();
while (Idx > 0 &&
MIB->getOperand(Idx-1).isReg() &&
MIB->getOperand(Idx-1).isImplicit())
--Idx;
bool isTied = MCID.getOperandConstraint(Idx, MCOI::TIED_TO) != -1;
if (isTied)
isKill = false;
}
MIB.addReg(VReg, getDefRegState(isOptDef) | getKillRegState(isKill) |
getDebugRegState(IsDebug));
}
void InstrEmitter::AddOperand(MachineInstrBuilder &MIB,
SDValue Op,
unsigned IIOpNum,
const MCInstrDesc *II,
DenseMap<SDValue, Register> &VRBaseMap,
bool IsDebug, bool IsClone, bool IsCloned) {
if (Op.isMachineOpcode()) {
AddRegisterOperand(MIB, Op, IIOpNum, II, VRBaseMap,
IsDebug, IsClone, IsCloned);
} else if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
MIB.addImm(C->getSExtValue());
} else if (ConstantFPSDNode *F = dyn_cast<ConstantFPSDNode>(Op)) {
MIB.addFPImm(F->getConstantFPValue());
} else if (RegisterSDNode *R = dyn_cast<RegisterSDNode>(Op)) {
Register VReg = R->getReg();
MVT OpVT = Op.getSimpleValueType();
const TargetRegisterClass *IIRC =
II ? TRI->getAllocatableClass(TII->getRegClass(*II, IIOpNum, TRI, *MF))
: nullptr;
const TargetRegisterClass *OpRC =
TLI->isTypeLegal(OpVT)
? TLI->getRegClassFor(OpVT,
Op.getNode()->isDivergent() ||
(IIRC && TRI->isDivergentRegClass(IIRC)))
: nullptr;
if (OpRC && IIRC && OpRC != IIRC && Register::isVirtualRegister(VReg)) {
Register NewVReg = MRI->createVirtualRegister(IIRC);
BuildMI(*MBB, InsertPos, Op.getNode()->getDebugLoc(),
TII->get(TargetOpcode::COPY), NewVReg).addReg(VReg);
VReg = NewVReg;
}
bool Imp = II && (IIOpNum >= II->getNumOperands() && !II->isVariadic());
MIB.addReg(VReg, getImplRegState(Imp));
} else if (RegisterMaskSDNode *RM = dyn_cast<RegisterMaskSDNode>(Op)) {
MIB.addRegMask(RM->getRegMask());
} else if (GlobalAddressSDNode *TGA = dyn_cast<GlobalAddressSDNode>(Op)) {
MIB.addGlobalAddress(TGA->getGlobal(), TGA->getOffset(),
TGA->getTargetFlags());
} else if (BasicBlockSDNode *BBNode = dyn_cast<BasicBlockSDNode>(Op)) {
MIB.addMBB(BBNode->getBasicBlock());
} else if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Op)) {
MIB.addFrameIndex(FI->getIndex());
} else if (JumpTableSDNode *JT = dyn_cast<JumpTableSDNode>(Op)) {
MIB.addJumpTableIndex(JT->getIndex(), JT->getTargetFlags());
} else if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(Op)) {
int Offset = CP->getOffset();
Align Alignment = CP->getAlign();
unsigned Idx;
MachineConstantPool *MCP = MF->getConstantPool();
if (CP->isMachineConstantPoolEntry())
Idx = MCP->getConstantPoolIndex(CP->getMachineCPVal(), Alignment);
else
Idx = MCP->getConstantPoolIndex(CP->getConstVal(), Alignment);
MIB.addConstantPoolIndex(Idx, Offset, CP->getTargetFlags());
} else if (ExternalSymbolSDNode *ES = dyn_cast<ExternalSymbolSDNode>(Op)) {
MIB.addExternalSymbol(ES->getSymbol(), ES->getTargetFlags());
} else if (auto *SymNode = dyn_cast<MCSymbolSDNode>(Op)) {
MIB.addSym(SymNode->getMCSymbol());
} else if (BlockAddressSDNode *BA = dyn_cast<BlockAddressSDNode>(Op)) {
MIB.addBlockAddress(BA->getBlockAddress(),
BA->getOffset(),
BA->getTargetFlags());
} else if (TargetIndexSDNode *TI = dyn_cast<TargetIndexSDNode>(Op)) {
MIB.addTargetIndex(TI->getIndex(), TI->getOffset(), TI->getTargetFlags());
} else {
assert(Op.getValueType() != MVT::Other &&
Op.getValueType() != MVT::Glue &&
"Chain and glue operands should occur at end of operand list!");
AddRegisterOperand(MIB, Op, IIOpNum, II, VRBaseMap,
IsDebug, IsClone, IsCloned);
}
}
Register InstrEmitter::ConstrainForSubReg(Register VReg, unsigned SubIdx,
MVT VT, bool isDivergent, const DebugLoc &DL) {
const TargetRegisterClass *VRC = MRI->getRegClass(VReg);
const TargetRegisterClass *RC = TRI->getSubClassWithSubReg(VRC, SubIdx);
if (RC && RC != VRC)
RC = MRI->constrainRegClass(VReg, RC, MinRCSize);
if (RC)
return VReg;
RC = TRI->getSubClassWithSubReg(TLI->getRegClassFor(VT, isDivergent), SubIdx);
assert(RC && "No legal register class for VT supports that SubIdx");
Register NewReg = MRI->createVirtualRegister(RC);
BuildMI(*MBB, InsertPos, DL, TII->get(TargetOpcode::COPY), NewReg)
.addReg(VReg);
return NewReg;
}
void InstrEmitter::EmitSubregNode(SDNode *Node,
DenseMap<SDValue, Register> &VRBaseMap,
bool IsClone, bool IsCloned) {
Register VRBase;
unsigned Opc = Node->getMachineOpcode();
for (SDNode *User : Node->uses()) {
if (User->getOpcode() == ISD::CopyToReg &&
User->getOperand(2).getNode() == Node) {
Register DestReg = cast<RegisterSDNode>(User->getOperand(1))->getReg();
if (DestReg.isVirtual()) {
VRBase = DestReg;
break;
}
}
}
if (Opc == TargetOpcode::EXTRACT_SUBREG) {
unsigned SubIdx = cast<ConstantSDNode>(Node->getOperand(1))->getZExtValue();
const TargetRegisterClass *TRC =
TLI->getRegClassFor(Node->getSimpleValueType(0), Node->isDivergent());
Register Reg;
MachineInstr *DefMI;
RegisterSDNode *R = dyn_cast<RegisterSDNode>(Node->getOperand(0));
if (R && Register::isPhysicalRegister(R->getReg())) {
Reg = R->getReg();
DefMI = nullptr;
} else {
Reg = R ? R->getReg() : getVR(Node->getOperand(0), VRBaseMap);
DefMI = MRI->getVRegDef(Reg);
}
Register SrcReg, DstReg;
unsigned DefSubIdx;
if (DefMI &&
TII->isCoalescableExtInstr(*DefMI, SrcReg, DstReg, DefSubIdx) &&
SubIdx == DefSubIdx &&
TRC == MRI->getRegClass(SrcReg)) {
VRBase = MRI->createVirtualRegister(TRC);
BuildMI(*MBB, InsertPos, Node->getDebugLoc(),
TII->get(TargetOpcode::COPY), VRBase).addReg(SrcReg);
MRI->clearKillFlags(SrcReg);
} else {
if (Reg.isVirtual())
Reg = ConstrainForSubReg(Reg, SubIdx,
Node->getOperand(0).getSimpleValueType(),
Node->isDivergent(), Node->getDebugLoc());
if (!VRBase)
VRBase = MRI->createVirtualRegister(TRC);
MachineInstrBuilder CopyMI =
BuildMI(*MBB, InsertPos, Node->getDebugLoc(),
TII->get(TargetOpcode::COPY), VRBase);
if (Reg.isVirtual())
CopyMI.addReg(Reg, 0, SubIdx);
else
CopyMI.addReg(TRI->getSubReg(Reg, SubIdx));
}
} else if (Opc == TargetOpcode::INSERT_SUBREG ||
Opc == TargetOpcode::SUBREG_TO_REG) {
SDValue N0 = Node->getOperand(0);
SDValue N1 = Node->getOperand(1);
SDValue N2 = Node->getOperand(2);
unsigned SubIdx = cast<ConstantSDNode>(N2)->getZExtValue();
const TargetRegisterClass *SRC =
TLI->getRegClassFor(Node->getSimpleValueType(0), Node->isDivergent());
SRC = TRI->getSubClassWithSubReg(SRC, SubIdx);
assert(SRC && "No register class supports VT and SubIdx for INSERT_SUBREG");
if (VRBase == 0 || !SRC->hasSubClassEq(MRI->getRegClass(VRBase)))
VRBase = MRI->createVirtualRegister(SRC);
MachineInstrBuilder MIB =
BuildMI(*MF, Node->getDebugLoc(), TII->get(Opc), VRBase);
if (Opc == TargetOpcode::SUBREG_TO_REG) {
const ConstantSDNode *SD = cast<ConstantSDNode>(N0);
MIB.addImm(SD->getZExtValue());
} else
AddOperand(MIB, N0, 0, nullptr, VRBaseMap, false,
IsClone, IsCloned);
AddOperand(MIB, N1, 0, nullptr, VRBaseMap, false,
IsClone, IsCloned);
MIB.addImm(SubIdx);
MBB->insert(InsertPos, MIB);
} else
llvm_unreachable("Node is not insert_subreg, extract_subreg, or subreg_to_reg");
SDValue Op(Node, 0);
bool isNew = VRBaseMap.insert(std::make_pair(Op, VRBase)).second;
(void)isNew; assert(isNew && "Node emitted out of order - early");
}
void
InstrEmitter::EmitCopyToRegClassNode(SDNode *Node,
DenseMap<SDValue, Register> &VRBaseMap) {
unsigned VReg = getVR(Node->getOperand(0), VRBaseMap);
unsigned DstRCIdx = cast<ConstantSDNode>(Node->getOperand(1))->getZExtValue();
const TargetRegisterClass *DstRC =
TRI->getAllocatableClass(TRI->getRegClass(DstRCIdx));
Register NewVReg = MRI->createVirtualRegister(DstRC);
BuildMI(*MBB, InsertPos, Node->getDebugLoc(), TII->get(TargetOpcode::COPY),
NewVReg).addReg(VReg);
SDValue Op(Node, 0);
bool isNew = VRBaseMap.insert(std::make_pair(Op, NewVReg)).second;
(void)isNew; assert(isNew && "Node emitted out of order - early");
}
void InstrEmitter::EmitRegSequence(SDNode *Node,
DenseMap<SDValue, Register> &VRBaseMap,
bool IsClone, bool IsCloned) {
unsigned DstRCIdx = cast<ConstantSDNode>(Node->getOperand(0))->getZExtValue();
const TargetRegisterClass *RC = TRI->getRegClass(DstRCIdx);
Register NewVReg = MRI->createVirtualRegister(TRI->getAllocatableClass(RC));
const MCInstrDesc &II = TII->get(TargetOpcode::REG_SEQUENCE);
MachineInstrBuilder MIB = BuildMI(*MF, Node->getDebugLoc(), II, NewVReg);
unsigned NumOps = Node->getNumOperands();
if (NumOps && Node->getOperand(NumOps-1).getValueType() == MVT::Other)
--NumOps;
assert((NumOps & 1) == 1 &&
"REG_SEQUENCE must have an odd number of operands!");
for (unsigned i = 1; i != NumOps; ++i) {
SDValue Op = Node->getOperand(i);
if ((i & 1) == 0) {
RegisterSDNode *R = dyn_cast<RegisterSDNode>(Node->getOperand(i-1));
if (!R || !Register::isPhysicalRegister(R->getReg())) {
unsigned SubIdx = cast<ConstantSDNode>(Op)->getZExtValue();
unsigned SubReg = getVR(Node->getOperand(i-1), VRBaseMap);
const TargetRegisterClass *TRC = MRI->getRegClass(SubReg);
const TargetRegisterClass *SRC =
TRI->getMatchingSuperRegClass(RC, TRC, SubIdx);
if (SRC && SRC != RC) {
MRI->setRegClass(NewVReg, SRC);
RC = SRC;
}
}
}
AddOperand(MIB, Op, i+1, &II, VRBaseMap, false,
IsClone, IsCloned);
}
MBB->insert(InsertPos, MIB);
SDValue Op(Node, 0);
bool isNew = VRBaseMap.insert(std::make_pair(Op, NewVReg)).second;
(void)isNew; assert(isNew && "Node emitted out of order - early");
}
MachineInstr *
InstrEmitter::EmitDbgValue(SDDbgValue *SD,
DenseMap<SDValue, Register> &VRBaseMap) {
MDNode *Var = SD->getVariable();
MDNode *Expr = SD->getExpression();
DebugLoc DL = SD->getDebugLoc();
assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
"Expected inlined-at fields to agree");
SD->setIsEmitted();
ArrayRef<SDDbgOperand> LocationOps = SD->getLocationOps();
assert(!LocationOps.empty() && "dbg_value with no location operands?");
if (SD->isInvalidated())
return EmitDbgNoLocation(SD);
if (SD->isVariadic()) {
const MCInstrDesc &DbgValDesc = TII->get(TargetOpcode::DBG_VALUE_LIST);
auto MIB = BuildMI(*MF, DL, DbgValDesc);
MIB.addMetadata(Var);
MIB.addMetadata(Expr);
AddDbgValueLocationOps(MIB, DbgValDesc, LocationOps, VRBaseMap);
return &*MIB;
}
if (EmitDebugInstrRefs)
if (auto *InstrRef = EmitDbgInstrRef(SD, VRBaseMap))
return InstrRef;
return EmitDbgValueFromSingleOp(SD, VRBaseMap);
}
void InstrEmitter::AddDbgValueLocationOps(
MachineInstrBuilder &MIB, const MCInstrDesc &DbgValDesc,
ArrayRef<SDDbgOperand> LocationOps,
DenseMap<SDValue, Register> &VRBaseMap) {
for (const SDDbgOperand &Op : LocationOps) {
switch (Op.getKind()) {
case SDDbgOperand::FRAMEIX:
MIB.addFrameIndex(Op.getFrameIx());
break;
case SDDbgOperand::VREG:
MIB.addReg(Op.getVReg());
break;
case SDDbgOperand::SDNODE: {
SDValue V = SDValue(Op.getSDNode(), Op.getResNo());
if (VRBaseMap.count(V) == 0)
MIB.addReg(0U); else
AddOperand(MIB, V, (*MIB).getNumOperands(), &DbgValDesc, VRBaseMap,
true, false, false);
} break;
case SDDbgOperand::CONST: {
const Value *V = Op.getConst();
if (const ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
if (CI->getBitWidth() > 64)
MIB.addCImm(CI);
else
MIB.addImm(CI->getSExtValue());
} else if (const ConstantFP *CF = dyn_cast<ConstantFP>(V)) {
MIB.addFPImm(CF);
} else if (isa<ConstantPointerNull>(V)) {
MIB.addImm(0);
} else {
MIB.addReg(0U);
}
} break;
}
}
}
MachineInstr *
InstrEmitter::EmitDbgInstrRef(SDDbgValue *SD,
DenseMap<SDValue, Register> &VRBaseMap) {
assert(!SD->isVariadic());
SDDbgOperand DbgOperand = SD->getLocationOps()[0];
MDNode *Var = SD->getVariable();
DIExpression *Expr = (DIExpression*)SD->getExpression();
DebugLoc DL = SD->getDebugLoc();
const MCInstrDesc &RefII = TII->get(TargetOpcode::DBG_INSTR_REF);
if (DbgOperand.getKind() == SDDbgOperand::FRAMEIX ||
DbgOperand.getKind() == SDDbgOperand::CONST)
return EmitDbgValueFromSingleOp(SD, VRBaseMap);
if (SD->isIndirect()) {
std::vector<uint64_t> Elts = {dwarf::DW_OP_deref};
Expr = DIExpression::append(Expr, Elts);
}
auto EmitHalfDoneInstrRef = [&](unsigned VReg) -> MachineInstr * {
auto MIB = BuildMI(*MF, DL, RefII);
MIB.addReg(VReg);
MIB.addImm(0);
MIB.addMetadata(Var);
MIB.addMetadata(Expr);
return MIB;
};
MachineInstr *DefMI = nullptr;
unsigned VReg;
if (DbgOperand.getKind() == SDDbgOperand::VREG) {
VReg = DbgOperand.getVReg();
if (!MRI->hasOneDef(VReg))
return EmitHalfDoneInstrRef(VReg);
DefMI = &*MRI->def_instr_begin(VReg);
} else {
assert(DbgOperand.getKind() == SDDbgOperand::SDNODE);
SDNode *Node = DbgOperand.getSDNode();
SDValue Op = SDValue(Node, DbgOperand.getResNo());
DenseMap<SDValue, Register>::iterator I = VRBaseMap.find(Op);
if (I==VRBaseMap.end())
return EmitDbgNoLocation(SD);
VReg = getVR(Op, VRBaseMap);
if (!MRI->hasOneDef(VReg))
return EmitHalfDoneInstrRef(VReg);
DefMI = &*MRI->def_instr_begin(VReg);
}
if (DefMI->isCopyLike() || TII->isCopyInstr(*DefMI))
return EmitHalfDoneInstrRef(VReg);
auto MIB = BuildMI(*MF, DL, RefII);
unsigned OperandIdx = 0;
for (const auto &MO : DefMI->operands()) {
if (MO.isReg() && MO.isDef() && MO.getReg() == VReg)
break;
++OperandIdx;
}
assert(OperandIdx < DefMI->getNumOperands());
unsigned InstrNum = DefMI->getDebugInstrNum();
MIB.addImm(InstrNum);
MIB.addImm(OperandIdx);
MIB.addMetadata(Var);
MIB.addMetadata(Expr);
return &*MIB;
}
MachineInstr *InstrEmitter::EmitDbgNoLocation(SDDbgValue *SD) {
MDNode *Var = SD->getVariable();
MDNode *Expr = SD->getExpression();
DebugLoc DL = SD->getDebugLoc();
auto MIB = BuildMI(*MF, DL, TII->get(TargetOpcode::DBG_VALUE));
MIB.addReg(0U);
MIB.addReg(0U);
MIB.addMetadata(Var);
MIB.addMetadata(Expr);
return &*MIB;
}
MachineInstr *
InstrEmitter::EmitDbgValueFromSingleOp(SDDbgValue *SD,
DenseMap<SDValue, Register> &VRBaseMap) {
MDNode *Var = SD->getVariable();
DIExpression *Expr = SD->getExpression();
DebugLoc DL = SD->getDebugLoc();
const MCInstrDesc &II = TII->get(TargetOpcode::DBG_VALUE);
assert(SD->getLocationOps().size() == 1 &&
"Non variadic dbg_value should have only one location op");
SmallVector<SDDbgOperand, 1> LocationOps(1, SD->getLocationOps()[0]);
if (Expr && LocationOps[0].getKind() == SDDbgOperand::CONST) {
const Value *V = LocationOps[0].getConst();
if (auto *C = dyn_cast<ConstantInt>(V)) {
std::tie(Expr, C) = Expr->constantFold(C);
LocationOps[0] = SDDbgOperand::fromConst(C);
}
}
auto MIB = BuildMI(*MF, DL, II);
AddDbgValueLocationOps(MIB, II, LocationOps, VRBaseMap);
if (SD->isIndirect())
MIB.addImm(0U);
else
MIB.addReg(0U);
return MIB.addMetadata(Var).addMetadata(Expr);
}
MachineInstr *
InstrEmitter::EmitDbgLabel(SDDbgLabel *SD) {
MDNode *Label = SD->getLabel();
DebugLoc DL = SD->getDebugLoc();
assert(cast<DILabel>(Label)->isValidLocationForIntrinsic(DL) &&
"Expected inlined-at fields to agree");
const MCInstrDesc &II = TII->get(TargetOpcode::DBG_LABEL);
MachineInstrBuilder MIB = BuildMI(*MF, DL, II);
MIB.addMetadata(Label);
return &*MIB;
}
void InstrEmitter::
EmitMachineNode(SDNode *Node, bool IsClone, bool IsCloned,
DenseMap<SDValue, Register> &VRBaseMap) {
unsigned Opc = Node->getMachineOpcode();
if (Opc == TargetOpcode::EXTRACT_SUBREG ||
Opc == TargetOpcode::INSERT_SUBREG ||
Opc == TargetOpcode::SUBREG_TO_REG) {
EmitSubregNode(Node, VRBaseMap, IsClone, IsCloned);
return;
}
if (Opc == TargetOpcode::COPY_TO_REGCLASS) {
EmitCopyToRegClassNode(Node, VRBaseMap);
return;
}
if (Opc == TargetOpcode::REG_SEQUENCE) {
EmitRegSequence(Node, VRBaseMap, IsClone, IsCloned);
return;
}
if (Opc == TargetOpcode::IMPLICIT_DEF)
return;
const MCInstrDesc &II = TII->get(Opc);
unsigned NumResults = CountResults(Node);
unsigned NumDefs = II.getNumDefs();
const MCPhysReg *ScratchRegs = nullptr;
if (Opc == TargetOpcode::STACKMAP || Opc == TargetOpcode::PATCHPOINT) {
unsigned CC = CallingConv::AnyReg;
if (Opc == TargetOpcode::PATCHPOINT) {
CC = Node->getConstantOperandVal(PatchPointOpers::CCPos);
NumDefs = NumResults;
}
ScratchRegs = TLI->getScratchRegisters((CallingConv::ID) CC);
} else if (Opc == TargetOpcode::STATEPOINT) {
NumDefs = NumResults;
}
unsigned NumImpUses = 0;
unsigned NodeOperands =
countOperands(Node, II.getNumOperands() - NumDefs, NumImpUses);
bool HasVRegVariadicDefs = !MF->getTarget().usesPhysRegsForValues() &&
II.isVariadic() && II.variadicOpsAreDefs();
bool HasPhysRegOuts = NumResults > NumDefs &&
II.getImplicitDefs() != nullptr && !HasVRegVariadicDefs;
#ifndef NDEBUG
unsigned NumMIOperands = NodeOperands + NumResults;
if (II.isVariadic())
assert(NumMIOperands >= II.getNumOperands() &&
"Too few operands for a variadic node!");
else
assert(NumMIOperands >= II.getNumOperands() &&
NumMIOperands <= II.getNumOperands() + II.getNumImplicitDefs() +
NumImpUses &&
"#operands for dag node doesn't match .td file!");
#endif
MachineInstrBuilder MIB = BuildMI(*MF, Node->getDebugLoc(), II);
if (NumResults) {
CreateVirtualRegisters(Node, MIB, II, IsClone, IsCloned, VRBaseMap);
MachineInstr *MI = MIB.getInstr();
const SDNodeFlags Flags = Node->getFlags();
if (Flags.hasNoSignedZeros())
MI->setFlag(MachineInstr::MIFlag::FmNsz);
if (Flags.hasAllowReciprocal())
MI->setFlag(MachineInstr::MIFlag::FmArcp);
if (Flags.hasNoNaNs())
MI->setFlag(MachineInstr::MIFlag::FmNoNans);
if (Flags.hasNoInfs())
MI->setFlag(MachineInstr::MIFlag::FmNoInfs);
if (Flags.hasAllowContract())
MI->setFlag(MachineInstr::MIFlag::FmContract);
if (Flags.hasApproximateFuncs())
MI->setFlag(MachineInstr::MIFlag::FmAfn);
if (Flags.hasAllowReassociation())
MI->setFlag(MachineInstr::MIFlag::FmReassoc);
if (Flags.hasNoUnsignedWrap())
MI->setFlag(MachineInstr::MIFlag::NoUWrap);
if (Flags.hasNoSignedWrap())
MI->setFlag(MachineInstr::MIFlag::NoSWrap);
if (Flags.hasExact())
MI->setFlag(MachineInstr::MIFlag::IsExact);
if (Flags.hasNoFPExcept())
MI->setFlag(MachineInstr::MIFlag::NoFPExcept);
}
bool HasOptPRefs = NumDefs > NumResults;
assert((!HasOptPRefs || !HasPhysRegOuts) &&
"Unable to cope with optional defs and phys regs defs!");
unsigned NumSkip = HasOptPRefs ? NumDefs - NumResults : 0;
for (unsigned i = NumSkip; i != NodeOperands; ++i)
AddOperand(MIB, Node->getOperand(i), i-NumSkip+NumDefs, &II,
VRBaseMap, false, IsClone, IsCloned);
if (ScratchRegs)
for (unsigned i = 0; ScratchRegs[i]; ++i)
MIB.addReg(ScratchRegs[i], RegState::ImplicitDefine |
RegState::EarlyClobber);
MIB.setMemRefs(cast<MachineSDNode>(Node)->memoperands());
MBB->insert(InsertPos, MIB);
SmallVector<Register, 8> UsedRegs;
if (HasPhysRegOuts) {
for (unsigned i = NumDefs; i < NumResults; ++i) {
Register Reg = II.getImplicitDefs()[i - NumDefs];
if (!Node->hasAnyUseOfValue(i))
continue;
UsedRegs.push_back(Reg);
EmitCopyFromReg(Node, i, IsClone, IsCloned, Reg, VRBaseMap);
}
}
if (Node->getValueType(Node->getNumValues()-1) == MVT::Glue) {
for (SDNode *F = Node->getGluedUser(); F; F = F->getGluedUser()) {
if (F->getOpcode() == ISD::CopyFromReg) {
UsedRegs.push_back(cast<RegisterSDNode>(F->getOperand(1))->getReg());
continue;
} else if (F->getOpcode() == ISD::CopyToReg) {
continue;
}
const MCInstrDesc &MCID = TII->get(F->getMachineOpcode());
UsedRegs.append(MCID.getImplicitUses(),
MCID.getImplicitUses() + MCID.getNumImplicitUses());
for (unsigned i = 0, e = F->getNumOperands(); i != e; ++i)
if (RegisterSDNode *R = dyn_cast<RegisterSDNode>(F->getOperand(i))) {
Register Reg = R->getReg();
if (Reg.isPhysical())
UsedRegs.push_back(Reg);
}
}
}
if (!UsedRegs.empty() || II.getImplicitDefs() || II.hasOptionalDef())
MIB->setPhysRegsDeadExcept(UsedRegs, *TRI);
if (Opc == TargetOpcode::STATEPOINT && NumDefs > 0) {
assert(!HasPhysRegOuts && "STATEPOINT mishandled");
MachineInstr *MI = MIB;
unsigned Def = 0;
int First = StatepointOpers(MI).getFirstGCPtrIdx();
assert(First > 0 && "Statepoint has Defs but no GC ptr list");
unsigned Use = (unsigned)First;
while (Def < NumDefs) {
if (MI->getOperand(Use).isReg())
MI->tieOperands(Def++, Use);
Use = StackMaps::getNextMetaArgIdx(MI, Use);
}
}
if (II.hasPostISelHook())
TLI->AdjustInstrPostInstrSelection(*MIB, Node);
}
void InstrEmitter::
EmitSpecialNode(SDNode *Node, bool IsClone, bool IsCloned,
DenseMap<SDValue, Register> &VRBaseMap) {
switch (Node->getOpcode()) {
default:
#ifndef NDEBUG
Node->dump();
#endif
llvm_unreachable("This target-independent node should have been selected!");
case ISD::EntryToken:
llvm_unreachable("EntryToken should have been excluded from the schedule!");
case ISD::MERGE_VALUES:
case ISD::TokenFactor: break;
case ISD::CopyToReg: {
Register DestReg = cast<RegisterSDNode>(Node->getOperand(1))->getReg();
SDValue SrcVal = Node->getOperand(2);
if (Register::isVirtualRegister(DestReg) && SrcVal.isMachineOpcode() &&
SrcVal.getMachineOpcode() == TargetOpcode::IMPLICIT_DEF) {
BuildMI(*MBB, InsertPos, Node->getDebugLoc(),
TII->get(TargetOpcode::IMPLICIT_DEF), DestReg);
break;
}
Register SrcReg;
if (RegisterSDNode *R = dyn_cast<RegisterSDNode>(SrcVal))
SrcReg = R->getReg();
else
SrcReg = getVR(SrcVal, VRBaseMap);
if (SrcReg == DestReg) break;
BuildMI(*MBB, InsertPos, Node->getDebugLoc(), TII->get(TargetOpcode::COPY),
DestReg).addReg(SrcReg);
break;
}
case ISD::CopyFromReg: {
unsigned SrcReg = cast<RegisterSDNode>(Node->getOperand(1))->getReg();
EmitCopyFromReg(Node, 0, IsClone, IsCloned, SrcReg, VRBaseMap);
break;
}
case ISD::EH_LABEL:
case ISD::ANNOTATION_LABEL: {
unsigned Opc = (Node->getOpcode() == ISD::EH_LABEL)
? TargetOpcode::EH_LABEL
: TargetOpcode::ANNOTATION_LABEL;
MCSymbol *S = cast<LabelSDNode>(Node)->getLabel();
BuildMI(*MBB, InsertPos, Node->getDebugLoc(),
TII->get(Opc)).addSym(S);
break;
}
case ISD::LIFETIME_START:
case ISD::LIFETIME_END: {
unsigned TarOp = (Node->getOpcode() == ISD::LIFETIME_START)
? TargetOpcode::LIFETIME_START
: TargetOpcode::LIFETIME_END;
auto *FI = cast<FrameIndexSDNode>(Node->getOperand(1));
BuildMI(*MBB, InsertPos, Node->getDebugLoc(), TII->get(TarOp))
.addFrameIndex(FI->getIndex());
break;
}
case ISD::PSEUDO_PROBE: {
unsigned TarOp = TargetOpcode::PSEUDO_PROBE;
auto Guid = cast<PseudoProbeSDNode>(Node)->getGuid();
auto Index = cast<PseudoProbeSDNode>(Node)->getIndex();
auto Attr = cast<PseudoProbeSDNode>(Node)->getAttributes();
BuildMI(*MBB, InsertPos, Node->getDebugLoc(), TII->get(TarOp))
.addImm(Guid)
.addImm(Index)
.addImm((uint8_t)PseudoProbeType::Block)
.addImm(Attr);
break;
}
case ISD::INLINEASM:
case ISD::INLINEASM_BR: {
unsigned NumOps = Node->getNumOperands();
if (Node->getOperand(NumOps-1).getValueType() == MVT::Glue)
--NumOps;
unsigned TgtOpc = Node->getOpcode() == ISD::INLINEASM_BR
? TargetOpcode::INLINEASM_BR
: TargetOpcode::INLINEASM;
MachineInstrBuilder MIB =
BuildMI(*MF, Node->getDebugLoc(), TII->get(TgtOpc));
SDValue AsmStrV = Node->getOperand(InlineAsm::Op_AsmString);
const char *AsmStr = cast<ExternalSymbolSDNode>(AsmStrV)->getSymbol();
MIB.addExternalSymbol(AsmStr);
int64_t ExtraInfo =
cast<ConstantSDNode>(Node->getOperand(InlineAsm::Op_ExtraInfo))->
getZExtValue();
MIB.addImm(ExtraInfo);
SmallVector<unsigned, 8> GroupIdx;
SmallVector<unsigned, 8> ECRegs;
for (unsigned i = InlineAsm::Op_FirstOperand; i != NumOps;) {
unsigned Flags =
cast<ConstantSDNode>(Node->getOperand(i))->getZExtValue();
const unsigned NumVals = InlineAsm::getNumOperandRegisters(Flags);
GroupIdx.push_back(MIB->getNumOperands());
MIB.addImm(Flags);
++i;
switch (InlineAsm::getKind(Flags)) {
default: llvm_unreachable("Bad flags!");
case InlineAsm::Kind_RegDef:
for (unsigned j = 0; j != NumVals; ++j, ++i) {
unsigned Reg = cast<RegisterSDNode>(Node->getOperand(i))->getReg();
MIB.addReg(Reg,
RegState::Define |
getImplRegState(Register::isPhysicalRegister(Reg)));
}
break;
case InlineAsm::Kind_RegDefEarlyClobber:
case InlineAsm::Kind_Clobber:
for (unsigned j = 0; j != NumVals; ++j, ++i) {
unsigned Reg = cast<RegisterSDNode>(Node->getOperand(i))->getReg();
MIB.addReg(Reg,
RegState::Define | RegState::EarlyClobber |
getImplRegState(Register::isPhysicalRegister(Reg)));
ECRegs.push_back(Reg);
}
break;
case InlineAsm::Kind_RegUse: case InlineAsm::Kind_Imm: case InlineAsm::Kind_Mem: for (unsigned j = 0; j != NumVals; ++j, ++i)
AddOperand(MIB, Node->getOperand(i), 0, nullptr, VRBaseMap,
false, IsClone, IsCloned);
if (InlineAsm::getKind(Flags) == InlineAsm::Kind_RegUse) {
unsigned DefGroup = 0;
if (InlineAsm::isUseOperandTiedToDef(Flags, DefGroup)) {
unsigned DefIdx = GroupIdx[DefGroup] + 1;
unsigned UseIdx = GroupIdx.back() + 1;
for (unsigned j = 0; j != NumVals; ++j)
MIB->tieOperands(DefIdx + j, UseIdx + j);
}
}
break;
}
}
for (unsigned Reg : ECRegs) {
if (MIB->readsRegister(Reg, TRI)) {
MachineOperand *MO =
MIB->findRegisterDefOperand(Reg, false, false, TRI);
assert(MO && "No def operand for clobbered register?");
MO->setIsEarlyClobber(false);
}
}
SDValue MDV = Node->getOperand(InlineAsm::Op_MDNode);
const MDNode *MD = cast<MDNodeSDNode>(MDV)->getMD();
if (MD)
MIB.addMetadata(MD);
MBB->insert(InsertPos, MIB);
break;
}
}
}
InstrEmitter::InstrEmitter(const TargetMachine &TM, MachineBasicBlock *mbb,
MachineBasicBlock::iterator insertpos,
bool UseInstrRefDebugInfo)
: MF(mbb->getParent()), MRI(&MF->getRegInfo()),
TII(MF->getSubtarget().getInstrInfo()),
TRI(MF->getSubtarget().getRegisterInfo()),
TLI(MF->getSubtarget().getTargetLowering()), MBB(mbb),
InsertPos(insertpos) {
EmitDebugInstrRefs = UseInstrRefDebugInfo;
}