LLVM  4.0.0
X86ExpandPseudo.cpp
Go to the documentation of this file.
1 //===------- X86ExpandPseudo.cpp - Expand pseudo instructions -------------===//
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 // This file contains a pass that expands pseudo instructions into target
11 // instructions to allow proper scheduling, if-conversion, other late
12 // optimizations, or simply the encoding of the instructions.
13 //
14 //===----------------------------------------------------------------------===//
15 
16 #include "X86.h"
17 #include "X86FrameLowering.h"
18 #include "X86InstrBuilder.h"
19 #include "X86InstrInfo.h"
20 #include "X86MachineFunctionInfo.h"
21 #include "X86Subtarget.h"
25 #include "llvm/CodeGen/Passes.h" // For IDs of passes that are preserved.
26 #include "llvm/IR/GlobalValue.h"
27 using namespace llvm;
28 
29 #define DEBUG_TYPE "x86-pseudo"
30 
31 namespace {
32 class X86ExpandPseudo : public MachineFunctionPass {
33 public:
34  static char ID;
35  X86ExpandPseudo() : MachineFunctionPass(ID) {}
36 
37  void getAnalysisUsage(AnalysisUsage &AU) const override {
38  AU.setPreservesCFG();
42  }
43 
44  const X86Subtarget *STI;
45  const X86InstrInfo *TII;
46  const X86RegisterInfo *TRI;
47  const X86MachineFunctionInfo *X86FI;
48  const X86FrameLowering *X86FL;
49 
50  bool runOnMachineFunction(MachineFunction &Fn) override;
51 
52  MachineFunctionProperties getRequiredProperties() const override {
55  }
56 
57  StringRef getPassName() const override {
58  return "X86 pseudo instruction expansion pass";
59  }
60 
61 private:
63  bool ExpandMBB(MachineBasicBlock &MBB);
64 };
65 char X86ExpandPseudo::ID = 0;
66 } // End anonymous namespace.
67 
68 /// If \p MBBI is a pseudo instruction, this method expands
69 /// it to the corresponding (sequence of) actual instruction(s).
70 /// \returns true if \p MBBI has been expanded.
71 bool X86ExpandPseudo::ExpandMI(MachineBasicBlock &MBB,
73  MachineInstr &MI = *MBBI;
74  unsigned Opcode = MI.getOpcode();
75  DebugLoc DL = MBBI->getDebugLoc();
76  switch (Opcode) {
77  default:
78  return false;
79  case X86::TCRETURNdi:
80  case X86::TCRETURNri:
81  case X86::TCRETURNmi:
82  case X86::TCRETURNdi64:
83  case X86::TCRETURNri64:
84  case X86::TCRETURNmi64: {
85  bool isMem = Opcode == X86::TCRETURNmi || Opcode == X86::TCRETURNmi64;
86  MachineOperand &JumpTarget = MBBI->getOperand(0);
87  MachineOperand &StackAdjust = MBBI->getOperand(isMem ? 5 : 1);
88  assert(StackAdjust.isImm() && "Expecting immediate value.");
89 
90  // Adjust stack pointer.
91  int StackAdj = StackAdjust.getImm();
92  int MaxTCDelta = X86FI->getTCReturnAddrDelta();
93  int Offset = 0;
94  assert(MaxTCDelta <= 0 && "MaxTCDelta should never be positive");
95 
96  // Incoporate the retaddr area.
97  Offset = StackAdj - MaxTCDelta;
98  assert(Offset >= 0 && "Offset should never be negative");
99 
100  if (Offset) {
101  // Check for possible merge with preceding ADD instruction.
102  Offset += X86FL->mergeSPUpdates(MBB, MBBI, true);
103  X86FL->emitSPUpdate(MBB, MBBI, Offset, /*InEpilogue=*/true);
104  }
105 
106  // Jump to label or value in register.
107  bool IsWin64 = STI->isTargetWin64();
108  if (Opcode == X86::TCRETURNdi || Opcode == X86::TCRETURNdi64) {
109  unsigned Op;
110  switch (Opcode) {
111  case X86::TCRETURNdi:
112  Op = X86::TAILJMPd;
113  break;
114  default:
115  // Note: Win64 uses REX prefixes indirect jumps out of functions, but
116  // not direct ones.
117  Op = X86::TAILJMPd64;
118  break;
119  }
120  MachineInstrBuilder MIB = BuildMI(MBB, MBBI, DL, TII->get(Op));
121  if (JumpTarget.isGlobal()) {
122  MIB.addGlobalAddress(JumpTarget.getGlobal(), JumpTarget.getOffset(),
123  JumpTarget.getTargetFlags());
124  } else {
125  assert(JumpTarget.isSymbol());
126  MIB.addExternalSymbol(JumpTarget.getSymbolName(),
127  JumpTarget.getTargetFlags());
128  }
129  } else if (Opcode == X86::TCRETURNmi || Opcode == X86::TCRETURNmi64) {
130  unsigned Op = (Opcode == X86::TCRETURNmi)
131  ? X86::TAILJMPm
132  : (IsWin64 ? X86::TAILJMPm64_REX : X86::TAILJMPm64);
133  MachineInstrBuilder MIB = BuildMI(MBB, MBBI, DL, TII->get(Op));
134  for (unsigned i = 0; i != 5; ++i)
135  MIB.addOperand(MBBI->getOperand(i));
136  } else if (Opcode == X86::TCRETURNri64) {
137  BuildMI(MBB, MBBI, DL,
138  TII->get(IsWin64 ? X86::TAILJMPr64_REX : X86::TAILJMPr64))
139  .addReg(JumpTarget.getReg(), RegState::Kill);
140  } else {
141  BuildMI(MBB, MBBI, DL, TII->get(X86::TAILJMPr))
142  .addReg(JumpTarget.getReg(), RegState::Kill);
143  }
144 
145  MachineInstr &NewMI = *std::prev(MBBI);
146  NewMI.copyImplicitOps(*MBBI->getParent()->getParent(), *MBBI);
147 
148  // Delete the pseudo instruction TCRETURN.
149  MBB.erase(MBBI);
150 
151  return true;
152  }
153  case X86::EH_RETURN:
154  case X86::EH_RETURN64: {
155  MachineOperand &DestAddr = MBBI->getOperand(0);
156  assert(DestAddr.isReg() && "Offset should be in register!");
157  const bool Uses64BitFramePtr =
158  STI->isTarget64BitLP64() || STI->isTargetNaCl64();
159  unsigned StackPtr = TRI->getStackRegister();
160  BuildMI(MBB, MBBI, DL,
161  TII->get(Uses64BitFramePtr ? X86::MOV64rr : X86::MOV32rr), StackPtr)
162  .addReg(DestAddr.getReg());
163  // The EH_RETURN pseudo is really removed during the MC Lowering.
164  return true;
165  }
166  case X86::IRET: {
167  // Adjust stack to erase error code
168  int64_t StackAdj = MBBI->getOperand(0).getImm();
169  X86FL->emitSPUpdate(MBB, MBBI, StackAdj, true);
170  // Replace pseudo with machine iret
171  BuildMI(MBB, MBBI, DL,
172  TII->get(STI->is64Bit() ? X86::IRET64 : X86::IRET32));
173  MBB.erase(MBBI);
174  return true;
175  }
176  case X86::RET: {
177  // Adjust stack to erase error code
178  int64_t StackAdj = MBBI->getOperand(0).getImm();
180  if (StackAdj == 0) {
181  MIB = BuildMI(MBB, MBBI, DL,
182  TII->get(STI->is64Bit() ? X86::RETQ : X86::RETL));
183  } else if (isUInt<16>(StackAdj)) {
184  MIB = BuildMI(MBB, MBBI, DL,
185  TII->get(STI->is64Bit() ? X86::RETIQ : X86::RETIL))
186  .addImm(StackAdj);
187  } else {
188  assert(!STI->is64Bit() &&
189  "shouldn't need to do this for x86_64 targets!");
190  // A ret can only handle immediates as big as 2**16-1. If we need to pop
191  // off bytes before the return address, we must do it manually.
192  BuildMI(MBB, MBBI, DL, TII->get(X86::POP32r)).addReg(X86::ECX, RegState::Define);
193  X86FL->emitSPUpdate(MBB, MBBI, StackAdj, /*InEpilogue=*/true);
194  BuildMI(MBB, MBBI, DL, TII->get(X86::PUSH32r)).addReg(X86::ECX);
195  MIB = BuildMI(MBB, MBBI, DL, TII->get(X86::RETL));
196  }
197  for (unsigned I = 1, E = MBBI->getNumOperands(); I != E; ++I)
198  MIB.addOperand(MBBI->getOperand(I));
199  MBB.erase(MBBI);
200  return true;
201  }
202  case X86::EH_RESTORE: {
203  // Restore ESP and EBP, and optionally ESI if required.
205  MBB.getParent()->getFunction()->getPersonalityFn()));
206  X86FL->restoreWin32EHStackPointers(MBB, MBBI, DL, /*RestoreSP=*/IsSEH);
207  MBBI->eraseFromParent();
208  return true;
209  }
210  case X86::LCMPXCHG8B_SAVE_EBX:
211  case X86::LCMPXCHG16B_SAVE_RBX: {
212  // Perform the following transformation.
213  // SaveRbx = pseudocmpxchg Addr, <4 opds for the address>, InArg, SaveRbx
214  // =>
215  // [E|R]BX = InArg
216  // actualcmpxchg Addr
217  // [E|R]BX = SaveRbx
218  const MachineOperand &InArg = MBBI->getOperand(6);
219  unsigned SaveRbx = MBBI->getOperand(7).getReg();
220 
221  unsigned ActualInArg =
222  Opcode == X86::LCMPXCHG8B_SAVE_EBX ? X86::EBX : X86::RBX;
223  // Copy the input argument of the pseudo into the argument of the
224  // actual instruction.
225  TII->copyPhysReg(MBB, MBBI, DL, ActualInArg, InArg.getReg(),
226  InArg.isKill());
227  // Create the actual instruction.
228  unsigned ActualOpc =
229  Opcode == X86::LCMPXCHG8B_SAVE_EBX ? X86::LCMPXCHG8B : X86::LCMPXCHG16B;
230  MachineInstr *NewInstr = BuildMI(MBB, MBBI, DL, TII->get(ActualOpc));
231  // Copy the operands related to the address.
232  for (unsigned Idx = 1; Idx < 6; ++Idx)
233  NewInstr->addOperand(MBBI->getOperand(Idx));
234  // Finally, restore the value of RBX.
235  TII->copyPhysReg(MBB, MBBI, DL, ActualInArg, SaveRbx,
236  /*SrcIsKill*/ true);
237 
238  // Delete the pseudo.
239  MBBI->eraseFromParent();
240  return true;
241  }
242  }
243  llvm_unreachable("Previous switch has a fallthrough?");
244 }
245 
246 /// Expand all pseudo instructions contained in \p MBB.
247 /// \returns true if any expansion occurred for \p MBB.
248 bool X86ExpandPseudo::ExpandMBB(MachineBasicBlock &MBB) {
249  bool Modified = false;
250 
251  // MBBI may be invalidated by the expansion.
252  MachineBasicBlock::iterator MBBI = MBB.begin(), E = MBB.end();
253  while (MBBI != E) {
254  MachineBasicBlock::iterator NMBBI = std::next(MBBI);
255  Modified |= ExpandMI(MBB, MBBI);
256  MBBI = NMBBI;
257  }
258 
259  return Modified;
260 }
261 
262 bool X86ExpandPseudo::runOnMachineFunction(MachineFunction &MF) {
263  STI = &static_cast<const X86Subtarget &>(MF.getSubtarget());
264  TII = STI->getInstrInfo();
265  TRI = STI->getRegisterInfo();
266  X86FI = MF.getInfo<X86MachineFunctionInfo>();
267  X86FL = STI->getFrameLowering();
268 
269  bool Modified = false;
270  for (MachineBasicBlock &MBB : MF)
271  Modified |= ExpandMBB(MBB);
272  return Modified;
273 }
274 
275 /// Returns an instance of the pseudo instruction expansion pass.
277  return new X86ExpandPseudo();
278 }
const MachineFunction * getParent() const
Return the MachineFunction containing this basic block.
instr_iterator erase(instr_iterator I)
Remove an instruction from the instruction list and delete it.
const GlobalValue * getGlobal() const
size_t i
char & MachineDominatorsID
MachineDominators - This pass is a machine dominators analysis pass.
const char * getSymbolName() const
A debug info location.
Definition: DebugLoc.h:34
const Function * getFunction() const
getFunction - Return the LLVM function that this machine code represents
X86MachineFunctionInfo - This class is derived from MachineFunction and contains private X86 target-s...
char & MachineLoopInfoID
MachineLoopInfo - This pass is a loop analysis pass.
const TargetSubtargetInfo & getSubtarget() const
getSubtarget - Return the subtarget for which this machine code is being compiled.
MachineFunctionPass - This class adapts the FunctionPass interface to allow convenient creation of pa...
const HexagonInstrInfo * TII
bool isImm() const
isImm - Tests if this is a MO_Immediate operand.
bool isReg() const
isReg - Tests if this is a MO_Register operand.
Constant * getPersonalityFn() const
Get the personality function associated with this function.
Definition: Function.cpp:1218
static bool isMem(const MachineInstr &MI, unsigned Op)
Definition: X86InstrInfo.h:135
const MachineInstrBuilder & addImm(int64_t Val) const
Add a new immediate operand.
bool isGlobal() const
isGlobal - Tests if this is a MO_GlobalAddress operand.
const HexagonRegisterInfo & getRegisterInfo() const
HexagonInstrInfo specifics.
void copyImplicitOps(MachineFunction &MF, const MachineInstr &MI)
Copy implicit register operands from specified instruction to this instruction.
bool isKill() const
Return from interrupt. Operand 0 is the number of bytes to pop.
MachineBasicBlock * MBB
AnalysisUsage & addPreservedID(const void *ID)
int64_t getImm() const
unsigned getOpcode() const
Returns the opcode of this MachineInstr.
Definition: MachineInstr.h:273
static GCRegistry::Add< CoreCLRGC > E("coreclr","CoreCLR-compatible GC")
MachineInstrBuilder BuildMI(MachineFunction &MF, const DebugLoc &DL, const MCInstrDesc &MCID)
Builder interface. Specify how to create the initial instruction itself.
unsigned getTargetFlags() const
void getAnalysisUsage(AnalysisUsage &AU) const override
getAnalysisUsage - Subclasses that override getAnalysisUsage must call this.
FunctionPass * createX86ExpandPseudoPass()
Return a Machine IR pass that expands X86-specific pseudo instructions into a sequence of actual inst...
EHPersonality classifyEHPersonality(const Value *Pers)
See if the given exception handling personality function is one that we understand.
Represent the analysis usage information of a pass.
bool isSymbol() const
isSymbol - Tests if this is a MO_ExternalSymbol operand.
uint32_t Offset
Ty * getInfo()
getInfo - Keep track of various per-function pieces of information for backends that would like to do...
FunctionPass class - This class is used to implement most global optimizations.
Definition: Pass.h:298
int64_t getOffset() const
Return the offset from the symbol in this operand.
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
void addOperand(MachineFunction &MF, const MachineOperand &Op)
Add the specified operand to the instruction.
MachineOperand class - Representation of each machine instruction operand.
void setPreservesCFG()
This function should be called by the pass, iff they do not:
Definition: Pass.cpp:276
const MachineInstrBuilder & addGlobalAddress(const GlobalValue *GV, int64_t Offset=0, unsigned char TargetFlags=0) const
void copyPhysReg(MachineBasicBlock &MBB, MachineBasicBlock::iterator I, const DebugLoc &DL, unsigned DestReg, unsigned SrcReg, bool KillSrc) const override
Emit instructions to copy a pair of physical registers.
MachineFunctionProperties & set(Property P)
Representation of each machine instruction.
Definition: MachineInstr.h:52
const MachineInstrBuilder & addExternalSymbol(const char *FnName, unsigned char TargetFlags=0) const
#define I(x, y, z)
Definition: MD5.cpp:54
constexpr bool isUInt< 16 >(uint64_t x)
Definition: MathExtras.h:312
OUTCHAIN = EH_RETURN(INCHAIN, OFFSET, HANDLER) - This node represents 'eh_return' gcc dwarf builtin...
Definition: ISDOpcodes.h:102
unsigned getReg() const
getReg - Returns the register number.
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
bool isAsynchronousEHPersonality(EHPersonality Pers)
Returns true if this personality function catches asynchronous exceptions.
const MachineInstrBuilder & addOperand(const MachineOperand &MO) const
IRTranslator LLVM IR MI
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:47
Properties which a MachineFunction may have at a given point in time.