LLVM  6.0.0svn
AMDGPUMCInstLower.cpp
Go to the documentation of this file.
1 //===- AMDGPUMCInstLower.cpp - Lower AMDGPU MachineInstr to an MCInst -----===//
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 /// \file
11 /// \brief Code to lower AMDGPU MachineInstrs to their corresponding MCInst.
12 //
13 //===----------------------------------------------------------------------===//
14 //
15 
16 #include "AMDGPUMCInstLower.h"
17 #include "AMDGPUAsmPrinter.h"
18 #include "AMDGPUSubtarget.h"
19 #include "AMDGPUTargetMachine.h"
21 #include "SIInstrInfo.h"
24 #include "llvm/IR/Constants.h"
25 #include "llvm/IR/Function.h"
26 #include "llvm/IR/GlobalVariable.h"
27 #include "llvm/MC/MCCodeEmitter.h"
28 #include "llvm/MC/MCContext.h"
29 #include "llvm/MC/MCExpr.h"
30 #include "llvm/MC/MCInst.h"
32 #include "llvm/MC/MCStreamer.h"
34 #include "llvm/Support/Format.h"
35 #include <algorithm>
36 
37 using namespace llvm;
38 
39 #include "AMDGPUGenMCPseudoLowering.inc"
40 
42  const AsmPrinter &ap):
43  Ctx(ctx), ST(st), AP(ap) { }
44 
45 static MCSymbolRefExpr::VariantKind getVariantKind(unsigned MOFlags) {
46  switch (MOFlags) {
47  default:
59  }
60 }
61 
62 const MCExpr *AMDGPUMCInstLower::getLongBranchBlockExpr(
63  const MachineBasicBlock &SrcBB,
64  const MachineOperand &MO) const {
65  const MCExpr *DestBBSym
67  const MCExpr *SrcBBSym = MCSymbolRefExpr::create(SrcBB.getSymbol(), Ctx);
68 
69  assert(SrcBB.front().getOpcode() == AMDGPU::S_GETPC_B64 &&
70  ST.getInstrInfo()->get(AMDGPU::S_GETPC_B64).Size == 4);
71 
72  // s_getpc_b64 returns the address of next instruction.
73  const MCConstantExpr *One = MCConstantExpr::create(4, Ctx);
74  SrcBBSym = MCBinaryExpr::createAdd(SrcBBSym, One, Ctx);
75 
77  return MCBinaryExpr::createSub(DestBBSym, SrcBBSym, Ctx);
78 
80  return MCBinaryExpr::createSub(SrcBBSym, DestBBSym, Ctx);
81 }
82 
84  MCOperand &MCOp) const {
85  switch (MO.getType()) {
86  default:
87  llvm_unreachable("unknown operand type");
89  MCOp = MCOperand::createImm(MO.getImm());
90  return true;
93  return true;
95  if (MO.getTargetFlags() != 0) {
96  MCOp = MCOperand::createExpr(
97  getLongBranchBlockExpr(*MO.getParent()->getParent(), MO));
98  } else {
99  MCOp = MCOperand::createExpr(
101  }
102 
103  return true;
104  }
106  const GlobalValue *GV = MO.getGlobal();
107  SmallString<128> SymbolName;
108  AP.getNameWithPrefix(SymbolName, GV);
109  MCSymbol *Sym = Ctx.getOrCreateSymbol(SymbolName);
110  const MCExpr *SymExpr =
112  const MCExpr *Expr = MCBinaryExpr::createAdd(SymExpr,
113  MCConstantExpr::create(MO.getOffset(), Ctx), Ctx);
114  MCOp = MCOperand::createExpr(Expr);
115  return true;
116  }
119  Sym->setExternal(true);
120  const MCSymbolRefExpr *Expr = MCSymbolRefExpr::create(Sym, Ctx);
121  MCOp = MCOperand::createExpr(Expr);
122  return true;
123  }
125  // Regmasks are like implicit defs.
126  return false;
127  }
128 }
129 
130 void AMDGPUMCInstLower::lower(const MachineInstr *MI, MCInst &OutMI) const {
131  unsigned Opcode = MI->getOpcode();
132  const auto *TII = ST.getInstrInfo();
133 
134  // FIXME: Should be able to handle this with emitPseudoExpansionLowering. We
135  // need to select it to the subtarget specific version, and there's no way to
136  // do that with a single pseudo source operation.
137  if (Opcode == AMDGPU::S_SETPC_B64_return)
138  Opcode = AMDGPU::S_SETPC_B64;
139  else if (Opcode == AMDGPU::SI_CALL) {
140  // SI_CALL is just S_SWAPPC_B64 with an additional operand to track the
141  // called function (which we need to remove here).
142  OutMI.setOpcode(TII->pseudoToMCOpcode(AMDGPU::S_SWAPPC_B64));
143  MCOperand Dest, Src;
144  lowerOperand(MI->getOperand(0), Dest);
145  lowerOperand(MI->getOperand(1), Src);
146  OutMI.addOperand(Dest);
147  OutMI.addOperand(Src);
148  return;
149  } else if (Opcode == AMDGPU::SI_TCRETURN) {
150  // TODO: How to use branch immediate and avoid register+add?
151  Opcode = AMDGPU::S_SETPC_B64;
152  }
153 
154  int MCOpcode = TII->pseudoToMCOpcode(Opcode);
155  if (MCOpcode == -1) {
157  C.emitError("AMDGPUMCInstLower::lower - Pseudo instruction doesn't have "
158  "a target-specific version: " + Twine(MI->getOpcode()));
159  }
160 
161  OutMI.setOpcode(MCOpcode);
162 
163  for (const MachineOperand &MO : MI->explicit_operands()) {
164  MCOperand MCOp;
165  lowerOperand(MO, MCOp);
166  OutMI.addOperand(MCOp);
167  }
168 }
169 
171  MCOperand &MCOp) const {
172  const AMDGPUSubtarget &STI = MF->getSubtarget<AMDGPUSubtarget>();
173  AMDGPUMCInstLower MCInstLowering(OutContext, STI, *this);
174  return MCInstLowering.lowerOperand(MO, MCOp);
175 }
176 
178  // TargetMachine does not support llvm-style cast. Use C++-style cast.
179  // This is safe since TM is always of type AMDGPUTargetMachine or its
180  // derived class.
181  auto *AT = static_cast<AMDGPUTargetMachine*>(&TM);
182  auto *CE = dyn_cast<ConstantExpr>(CV);
183 
184  // Lower null pointers in private and local address space.
185  // Clang generates addrspacecast for null pointers in private and local
186  // address space, which needs to be lowered.
187  if (CE && CE->getOpcode() == Instruction::AddrSpaceCast) {
188  auto Op = CE->getOperand(0);
189  auto SrcAddr = Op->getType()->getPointerAddressSpace();
190  if (Op->isNullValue() && AT->getNullPointerValue(SrcAddr) == 0) {
191  auto DstAddr = CE->getType()->getPointerAddressSpace();
192  return MCConstantExpr::create(AT->getNullPointerValue(DstAddr),
193  OutContext);
194  }
195  }
196  return AsmPrinter::lowerConstant(CV);
197 }
198 
200  if (emitPseudoExpansionLowering(*OutStreamer, MI))
201  return;
202 
203  const AMDGPUSubtarget &STI = MF->getSubtarget<AMDGPUSubtarget>();
204  AMDGPUMCInstLower MCInstLowering(OutContext, STI, *this);
205 
206  StringRef Err;
207  if (!STI.getInstrInfo()->verifyInstruction(*MI, Err)) {
209  C.emitError("Illegal instruction detected: " + Err);
210  MI->print(errs());
211  }
212 
213  if (MI->isBundle()) {
214  const MachineBasicBlock *MBB = MI->getParent();
216  while (I != MBB->instr_end() && I->isInsideBundle()) {
217  EmitInstruction(&*I);
218  ++I;
219  }
220  } else {
221  // We don't want SI_MASK_BRANCH/SI_RETURN_TO_EPILOG encoded. They are
222  // placeholder terminator instructions and should only be printed as
223  // comments.
224  if (MI->getOpcode() == AMDGPU::SI_MASK_BRANCH) {
225  if (isVerbose()) {
226  SmallVector<char, 16> BBStr;
227  raw_svector_ostream Str(BBStr);
228 
229  const MachineBasicBlock *MBB = MI->getOperand(0).getMBB();
230  const MCSymbolRefExpr *Expr
231  = MCSymbolRefExpr::create(MBB->getSymbol(), OutContext);
232  Expr->print(Str, MAI);
233  OutStreamer->emitRawComment(" mask branch " + BBStr);
234  }
235 
236  return;
237  }
238 
239  if (MI->getOpcode() == AMDGPU::SI_RETURN_TO_EPILOG) {
240  if (isVerbose())
241  OutStreamer->emitRawComment(" return to shader part epilog");
242  return;
243  }
244 
245  if (MI->getOpcode() == AMDGPU::WAVE_BARRIER) {
246  if (isVerbose())
247  OutStreamer->emitRawComment(" wave barrier");
248  return;
249  }
250 
251  if (MI->getOpcode() == AMDGPU::SI_MASKED_UNREACHABLE) {
252  if (isVerbose())
253  OutStreamer->emitRawComment(" divergent unreachable");
254  return;
255  }
256 
257  MCInst TmpInst;
258  MCInstLowering.lower(MI, TmpInst);
259  EmitToStreamer(*OutStreamer, TmpInst);
260 
261  if (STI.dumpCode()) {
262  // Disassemble instruction/operands to text.
263  DisasmLines.resize(DisasmLines.size() + 1);
264  std::string &DisasmLine = DisasmLines.back();
265  raw_string_ostream DisasmStream(DisasmLine);
266 
267  AMDGPUInstPrinter InstPrinter(*TM.getMCAsmInfo(),
268  *STI.getInstrInfo(),
269  *STI.getRegisterInfo());
270  InstPrinter.printInst(&TmpInst, DisasmStream, StringRef(), STI);
271 
272  // Disassemble instruction/operands to hex representation.
274  SmallVector<char, 16> CodeBytes;
275  raw_svector_ostream CodeStream(CodeBytes);
276 
277  auto &ObjStreamer = static_cast<MCObjectStreamer&>(*OutStreamer);
278  MCCodeEmitter &InstEmitter = ObjStreamer.getAssembler().getEmitter();
279  InstEmitter.encodeInstruction(TmpInst, CodeStream, Fixups,
280  MF->getSubtarget<MCSubtargetInfo>());
281  HexLines.resize(HexLines.size() + 1);
282  std::string &HexLine = HexLines.back();
283  raw_string_ostream HexStream(HexLine);
284 
285  for (size_t i = 0; i < CodeBytes.size(); i += 4) {
286  unsigned int CodeDWord = *(unsigned int *)&CodeBytes[i];
287  HexStream << format("%s%08X", (i > 0 ? " " : ""), CodeDWord);
288  }
289 
290  DisasmStream.flush();
291  DisasmLineMaxLen = std::max(DisasmLineMaxLen, DisasmLine.size());
292  }
293  }
294 }
unsigned getTargetFlags() const
uint64_t CallInst * C
const AMDGPURegisterInfo * getRegisterInfo() const override=0
const MCExpr * lowerConstant(const Constant *CV) override
Lower the specified LLVM Constant to an MCExpr.
raw_ostream & errs()
This returns a reference to a raw_ostream for standard error.
MachineInstr * getParent()
getParent - Return the instruction that this operand belongs to.
GCNRegPressure max(const GCNRegPressure &P1, const GCNRegPressure &P2)
AMDGPU specific subclass of TargetSubtarget.
instr_iterator instr_end()
MachineBasicBlock * getMBB() const
static const MCSymbolRefExpr * create(const MCSymbol *Symbol, MCContext &Ctx)
Definition: MCExpr.h:305
Compute iterated dominance frontiers using a linear time algorithm.
Definition: AllocatorList.h:24
MCSymbol - Instances of this class represent a symbol name in the MC file, and MCSymbols are created ...
Definition: MCSymbol.h:42
iterator_range< mop_iterator > explicit_operands()
Definition: MachineInstr.h:312
LLVM_ATTRIBUTE_ALWAYS_INLINE size_type size() const
Definition: SmallVector.h:136
static MCOperand createExpr(const MCExpr *Val)
Definition: MCInst.h:137
unsigned getReg() const
getReg - Returns the register number.
format_object< Ts... > format(const char *Fmt, const Ts &... Vals)
These are helper functions used to produce formatted output.
Definition: Format.h:124
A raw_ostream that writes to an SmallVector or SmallString.
Definition: raw_ostream.h:493
MachineBasicBlock reference.
Mask of preserved registers.
void setExternal(bool Value) const
Definition: MCSymbol.h:393
static MCOperand createReg(unsigned Reg)
Definition: MCInst.h:116
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition: Twine.h:81
const HexagonInstrInfo * TII
virtual void encodeInstruction(const MCInst &Inst, raw_ostream &OS, SmallVectorImpl< MCFixup > &Fixups, const MCSubtargetInfo &STI) const =0
EncodeInstruction - Encode the given Inst to bytes on the output stream OS.
Base class for the full range of assembler expressions which are needed for parsing.
Definition: MCExpr.h:36
Name of external global symbol.
Represent a reference to a symbol from inside an expression.
Definition: MCExpr.h:165
unsigned getOpcode() const
Returns the opcode of this MachineInstr.
Definition: MachineInstr.h:279
const char * getSymbolName() const
Context object for machine code objects.
Definition: MCContext.h:59
void emitError(unsigned LocCookie, const Twine &ErrorStr)
emitError - Emit an error message to the currently installed error handler with optional location inf...
A constant value that is initialized with an expression using other constant values.
Definition: Constants.h:862
void EmitInstruction(const MachineInstr *MI) override
Implemented in AMDGPUMCInstLower.cpp.
bool isBundle() const
Definition: MachineInstr.h:822
static const MCBinaryExpr * createSub(const MCExpr *LHS, const MCExpr *RHS, MCContext &Ctx)
Definition: MCExpr.h:528
Streaming object file generation interface.
static const MCBinaryExpr * createAdd(const MCExpr *LHS, const MCExpr *RHS, MCContext &Ctx)
Definition: MCExpr.h:443
Instances of this class represent a single low-level machine instruction.
Definition: MCInst.h:159
Address of a global value.
void print(raw_ostream &OS, const MCAsmInfo *MAI, bool InParens=false) const
Definition: MCExpr.cpp:40
This is an important class for using LLVM in a threaded context.
Definition: LLVMContext.h:69
This is an important base class in LLVM.
Definition: Constant.h:42
This file contains the declarations for the subclasses of Constant, which represent the different fla...
const GlobalValue * getGlobal() const
MCCodeEmitter - Generic instruction encoding interface.
Definition: MCCodeEmitter.h:22
This class is intended to be used as a driving class for all asm writers.
Definition: AsmPrinter.h:76
void getNameWithPrefix(SmallVectorImpl< char > &Name, const GlobalValue *GV) const
Definition: AsmPrinter.cpp:417
self_iterator getIterator()
Definition: ilist_node.h:82
The AMDGPU TargetMachine interface definition for hw codgen targets.
LLVMContext & getContext() const
getContext - Return a reference to the LLVMContext associated with this function. ...
Definition: Function.cpp:194
const AMDGPUInstrInfo * getInstrInfo() const override=0
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
static MCSymbolRefExpr::VariantKind getVariantKind(unsigned MOFlags)
Iterator for intrusive lists based on ilist_node.
void setOpcode(unsigned Op)
Definition: MCInst.h:167
virtual const MCExpr * lowerConstant(const Constant *CV)
Lower the specified LLVM Constant to an MCExpr.
MachineOperand class - Representation of each machine instruction operand.
This is a &#39;vector&#39; (really, a variable-sized array), optimized for the case when the array is small...
Definition: SmallVector.h:864
int64_t getImm() const
void lower(const MachineInstr *MI, MCInst &OutMI) const
Lower a MachineInstr to an MCInst.
const MachineBasicBlock * getParent() const
Definition: MachineInstr.h:139
Representation of each machine instruction.
Definition: MachineInstr.h:59
const MachineFunction * getParent() const
Return the MachineFunction containing this basic block.
Interface definition for SIInstrInfo.
MCSymbol * getOrCreateSymbol(const Twine &Name)
Lookup the symbol inside with the specified Name.
Definition: MCContext.cpp:121
int64_t getOffset() const
Return the offset from the symbol in this operand.
MCSymbol * getSymbol() const
Return the MCSymbol for this basic block.
#define I(x, y, z)
Definition: MD5.cpp:58
void printInst(const MCInst *MI, raw_ostream &O, StringRef Annot, const MCSubtargetInfo &STI) override
Print the specified MCInst to the specified raw_ostream.
AMDGPU Assembly printer class.
MCSubtargetInfo - Generic base class for all target subtargets.
LLVM_NODISCARD std::enable_if<!is_simple_type< Y >::value, typename cast_retty< X, const Y >::ret_type >::type dyn_cast(const Y &Val)
Definition: Casting.h:323
void print(raw_ostream &OS, bool SkipOpers=false, bool SkipDebugLoc=false, const TargetInstrInfo *TII=nullptr) const
Debugging supportPrint this MI to OS.
const Function * getFunction() const
getFunction - Return the LLVM function that this machine code represents
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
A raw_ostream that writes to an std::string.
Definition: raw_ostream.h:466
unsigned getMCReg(unsigned Reg, const MCSubtargetInfo &STI)
If Reg is a pseudo reg, return the correct hardware register given STI otherwise return Reg...
IRTranslator LLVM IR MI
void addOperand(const MCOperand &Op)
Definition: MCInst.h:177
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:49
bool lowerOperand(const MachineOperand &MO, MCOperand &MCOp) const
Wrapper for MCInstLowering.lowerOperand() for the tblgen&#39;erated pseudo lowering.
const MachineOperand & getOperand(unsigned i) const
Definition: MachineInstr.h:284
Instances of this class represent operands of the MCInst class.
Definition: MCInst.h:35
AMDGPUMCInstLower(MCContext &ctx, const AMDGPUSubtarget &ST, const AsmPrinter &AP)
MachineOperandType getType() const
getType - Returns the MachineOperandType for this operand.
static MCOperand createImm(int64_t Val)
Definition: MCInst.h:123
static const MCConstantExpr * create(int64_t Value, MCContext &Ctx)
Definition: MCExpr.cpp:159
bool lowerOperand(const MachineOperand &MO, MCOperand &MCOp) const