LLVM  9.0.0svn
X86ExpandPseudo.cpp
Go to the documentation of this file.
1 //===------- X86ExpandPseudo.cpp - Expand pseudo instructions -------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file contains a pass that expands pseudo instructions into target
10 // instructions to allow proper scheduling, if-conversion, other late
11 // optimizations, or simply the encoding of the instructions.
12 //
13 //===----------------------------------------------------------------------===//
14 
15 #include "X86.h"
16 #include "X86FrameLowering.h"
17 #include "X86InstrBuilder.h"
18 #include "X86InstrInfo.h"
19 #include "X86MachineFunctionInfo.h"
20 #include "X86Subtarget.h"
24 #include "llvm/CodeGen/Passes.h" // For IDs of passes that are preserved.
25 #include "llvm/IR/GlobalValue.h"
26 using namespace llvm;
27 
28 #define DEBUG_TYPE "x86-pseudo"
29 #define X86_EXPAND_PSEUDO_NAME "X86 pseudo instruction expansion pass"
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:
62  void ExpandICallBranchFunnel(MachineBasicBlock *MBB,
64 
65  bool ExpandMI(MachineBasicBlock &MBB, MachineBasicBlock::iterator MBBI);
66  bool ExpandMBB(MachineBasicBlock &MBB);
67 };
68 char X86ExpandPseudo::ID = 0;
69 
70 } // End anonymous namespace.
71 
73  false)
74 
75 void X86ExpandPseudo::ExpandICallBranchFunnel(
76  MachineBasicBlock *MBB, MachineBasicBlock::iterator MBBI) {
77  MachineBasicBlock *JTMBB = MBB;
78  MachineInstr *JTInst = &*MBBI;
79  MachineFunction *MF = MBB->getParent();
80  const BasicBlock *BB = MBB->getBasicBlock();
81  auto InsPt = MachineFunction::iterator(MBB);
82  ++InsPt;
83 
84  std::vector<std::pair<MachineBasicBlock *, unsigned>> TargetMBBs;
85  DebugLoc DL = JTInst->getDebugLoc();
86  MachineOperand Selector = JTInst->getOperand(0);
87  const GlobalValue *CombinedGlobal = JTInst->getOperand(1).getGlobal();
88 
89  auto CmpTarget = [&](unsigned Target) {
90  BuildMI(*MBB, MBBI, DL, TII->get(X86::LEA64r), X86::R11)
91  .addReg(X86::RIP)
92  .addImm(1)
93  .addReg(0)
94  .addGlobalAddress(CombinedGlobal,
95  JTInst->getOperand(2 + 2 * Target).getImm())
96  .addReg(0);
97  BuildMI(*MBB, MBBI, DL, TII->get(X86::CMP64rr))
98  .add(Selector)
99  .addReg(X86::R11);
100  };
101 
102  auto CreateMBB = [&]() {
103  auto *NewMBB = MF->CreateMachineBasicBlock(BB);
104  MBB->addSuccessor(NewMBB);
105  return NewMBB;
106  };
107 
108  auto EmitCondJump = [&](unsigned CC, MachineBasicBlock *ThenMBB) {
109  BuildMI(*MBB, MBBI, DL, TII->get(X86::JCC_1)).addMBB(ThenMBB).addImm(CC);
110 
111  auto *ElseMBB = CreateMBB();
112  MF->insert(InsPt, ElseMBB);
113  MBB = ElseMBB;
114  MBBI = MBB->end();
115  };
116 
117  auto EmitCondJumpTarget = [&](unsigned CC, unsigned Target) {
118  auto *ThenMBB = CreateMBB();
119  TargetMBBs.push_back({ThenMBB, Target});
120  EmitCondJump(CC, ThenMBB);
121  };
122 
123  auto EmitTailCall = [&](unsigned Target) {
124  BuildMI(*MBB, MBBI, DL, TII->get(X86::TAILJMPd64))
125  .add(JTInst->getOperand(3 + 2 * Target));
126  };
127 
128  std::function<void(unsigned, unsigned)> EmitBranchFunnel =
129  [&](unsigned FirstTarget, unsigned NumTargets) {
130  if (NumTargets == 1) {
131  EmitTailCall(FirstTarget);
132  return;
133  }
134 
135  if (NumTargets == 2) {
136  CmpTarget(FirstTarget + 1);
137  EmitCondJumpTarget(X86::COND_B, FirstTarget);
138  EmitTailCall(FirstTarget + 1);
139  return;
140  }
141 
142  if (NumTargets < 6) {
143  CmpTarget(FirstTarget + 1);
144  EmitCondJumpTarget(X86::COND_B, FirstTarget);
145  EmitCondJumpTarget(X86::COND_E, FirstTarget + 1);
146  EmitBranchFunnel(FirstTarget + 2, NumTargets - 2);
147  return;
148  }
149 
150  auto *ThenMBB = CreateMBB();
151  CmpTarget(FirstTarget + (NumTargets / 2));
152  EmitCondJump(X86::COND_B, ThenMBB);
153  EmitCondJumpTarget(X86::COND_E, FirstTarget + (NumTargets / 2));
154  EmitBranchFunnel(FirstTarget + (NumTargets / 2) + 1,
155  NumTargets - (NumTargets / 2) - 1);
156 
157  MF->insert(InsPt, ThenMBB);
158  MBB = ThenMBB;
159  MBBI = MBB->end();
160  EmitBranchFunnel(FirstTarget, NumTargets / 2);
161  };
162 
163  EmitBranchFunnel(0, (JTInst->getNumOperands() - 2) / 2);
164  for (auto P : TargetMBBs) {
165  MF->insert(InsPt, P.first);
166  BuildMI(P.first, DL, TII->get(X86::TAILJMPd64))
167  .add(JTInst->getOperand(3 + 2 * P.second));
168  }
169  JTMBB->erase(JTInst);
170 }
171 
172 /// If \p MBBI is a pseudo instruction, this method expands
173 /// it to the corresponding (sequence of) actual instruction(s).
174 /// \returns true if \p MBBI has been expanded.
175 bool X86ExpandPseudo::ExpandMI(MachineBasicBlock &MBB,
177  MachineInstr &MI = *MBBI;
178  unsigned Opcode = MI.getOpcode();
179  DebugLoc DL = MBBI->getDebugLoc();
180  switch (Opcode) {
181  default:
182  return false;
183  case X86::TCRETURNdi:
184  case X86::TCRETURNdicc:
185  case X86::TCRETURNri:
186  case X86::TCRETURNmi:
187  case X86::TCRETURNdi64:
188  case X86::TCRETURNdi64cc:
189  case X86::TCRETURNri64:
190  case X86::TCRETURNmi64: {
191  bool isMem = Opcode == X86::TCRETURNmi || Opcode == X86::TCRETURNmi64;
192  MachineOperand &JumpTarget = MBBI->getOperand(0);
193  MachineOperand &StackAdjust = MBBI->getOperand(isMem ? 5 : 1);
194  assert(StackAdjust.isImm() && "Expecting immediate value.");
195 
196  // Adjust stack pointer.
197  int StackAdj = StackAdjust.getImm();
198  int MaxTCDelta = X86FI->getTCReturnAddrDelta();
199  int Offset = 0;
200  assert(MaxTCDelta <= 0 && "MaxTCDelta should never be positive");
201 
202  // Incoporate the retaddr area.
203  Offset = StackAdj - MaxTCDelta;
204  assert(Offset >= 0 && "Offset should never be negative");
205 
206  if (Opcode == X86::TCRETURNdicc || Opcode == X86::TCRETURNdi64cc) {
207  assert(Offset == 0 && "Conditional tail call cannot adjust the stack.");
208  }
209 
210  if (Offset) {
211  // Check for possible merge with preceding ADD instruction.
212  Offset += X86FL->mergeSPUpdates(MBB, MBBI, true);
213  X86FL->emitSPUpdate(MBB, MBBI, DL, Offset, /*InEpilogue=*/true);
214  }
215 
216  // Jump to label or value in register.
217  bool IsWin64 = STI->isTargetWin64();
218  if (Opcode == X86::TCRETURNdi || Opcode == X86::TCRETURNdicc ||
219  Opcode == X86::TCRETURNdi64 || Opcode == X86::TCRETURNdi64cc) {
220  unsigned Op;
221  switch (Opcode) {
222  case X86::TCRETURNdi:
223  Op = X86::TAILJMPd;
224  break;
225  case X86::TCRETURNdicc:
226  Op = X86::TAILJMPd_CC;
227  break;
228  case X86::TCRETURNdi64cc:
229  assert(!MBB.getParent()->hasWinCFI() &&
230  "Conditional tail calls confuse "
231  "the Win64 unwinder.");
232  Op = X86::TAILJMPd64_CC;
233  break;
234  default:
235  // Note: Win64 uses REX prefixes indirect jumps out of functions, but
236  // not direct ones.
237  Op = X86::TAILJMPd64;
238  break;
239  }
240  MachineInstrBuilder MIB = BuildMI(MBB, MBBI, DL, TII->get(Op));
241  if (JumpTarget.isGlobal()) {
242  MIB.addGlobalAddress(JumpTarget.getGlobal(), JumpTarget.getOffset(),
243  JumpTarget.getTargetFlags());
244  } else {
245  assert(JumpTarget.isSymbol());
246  MIB.addExternalSymbol(JumpTarget.getSymbolName(),
247  JumpTarget.getTargetFlags());
248  }
249  if (Op == X86::TAILJMPd_CC || Op == X86::TAILJMPd64_CC) {
250  MIB.addImm(MBBI->getOperand(2).getImm());
251  }
252 
253  } else if (Opcode == X86::TCRETURNmi || Opcode == X86::TCRETURNmi64) {
254  unsigned Op = (Opcode == X86::TCRETURNmi)
255  ? X86::TAILJMPm
256  : (IsWin64 ? X86::TAILJMPm64_REX : X86::TAILJMPm64);
257  MachineInstrBuilder MIB = BuildMI(MBB, MBBI, DL, TII->get(Op));
258  for (unsigned i = 0; i != 5; ++i)
259  MIB.add(MBBI->getOperand(i));
260  } else if (Opcode == X86::TCRETURNri64) {
261  JumpTarget.setIsKill();
262  BuildMI(MBB, MBBI, DL,
263  TII->get(IsWin64 ? X86::TAILJMPr64_REX : X86::TAILJMPr64))
264  .add(JumpTarget);
265  } else {
266  JumpTarget.setIsKill();
267  BuildMI(MBB, MBBI, DL, TII->get(X86::TAILJMPr))
268  .add(JumpTarget);
269  }
270 
271  MachineInstr &NewMI = *std::prev(MBBI);
272  NewMI.copyImplicitOps(*MBBI->getParent()->getParent(), *MBBI);
273 
274  // Delete the pseudo instruction TCRETURN.
275  MBB.erase(MBBI);
276 
277  return true;
278  }
279  case X86::EH_RETURN:
280  case X86::EH_RETURN64: {
281  MachineOperand &DestAddr = MBBI->getOperand(0);
282  assert(DestAddr.isReg() && "Offset should be in register!");
283  const bool Uses64BitFramePtr =
284  STI->isTarget64BitLP64() || STI->isTargetNaCl64();
285  unsigned StackPtr = TRI->getStackRegister();
286  BuildMI(MBB, MBBI, DL,
287  TII->get(Uses64BitFramePtr ? X86::MOV64rr : X86::MOV32rr), StackPtr)
288  .addReg(DestAddr.getReg());
289  // The EH_RETURN pseudo is really removed during the MC Lowering.
290  return true;
291  }
292  case X86::IRET: {
293  // Adjust stack to erase error code
294  int64_t StackAdj = MBBI->getOperand(0).getImm();
295  X86FL->emitSPUpdate(MBB, MBBI, DL, StackAdj, true);
296  // Replace pseudo with machine iret
297  BuildMI(MBB, MBBI, DL,
298  TII->get(STI->is64Bit() ? X86::IRET64 : X86::IRET32));
299  MBB.erase(MBBI);
300  return true;
301  }
302  case X86::RET: {
303  // Adjust stack to erase error code
304  int64_t StackAdj = MBBI->getOperand(0).getImm();
306  if (StackAdj == 0) {
307  MIB = BuildMI(MBB, MBBI, DL,
308  TII->get(STI->is64Bit() ? X86::RETQ : X86::RETL));
309  } else if (isUInt<16>(StackAdj)) {
310  MIB = BuildMI(MBB, MBBI, DL,
311  TII->get(STI->is64Bit() ? X86::RETIQ : X86::RETIL))
312  .addImm(StackAdj);
313  } else {
314  assert(!STI->is64Bit() &&
315  "shouldn't need to do this for x86_64 targets!");
316  // A ret can only handle immediates as big as 2**16-1. If we need to pop
317  // off bytes before the return address, we must do it manually.
318  BuildMI(MBB, MBBI, DL, TII->get(X86::POP32r)).addReg(X86::ECX, RegState::Define);
319  X86FL->emitSPUpdate(MBB, MBBI, DL, StackAdj, /*InEpilogue=*/true);
320  BuildMI(MBB, MBBI, DL, TII->get(X86::PUSH32r)).addReg(X86::ECX);
321  MIB = BuildMI(MBB, MBBI, DL, TII->get(X86::RETL));
322  }
323  for (unsigned I = 1, E = MBBI->getNumOperands(); I != E; ++I)
324  MIB.add(MBBI->getOperand(I));
325  MBB.erase(MBBI);
326  return true;
327  }
328  case X86::EH_RESTORE: {
329  // Restore ESP and EBP, and optionally ESI if required.
332  X86FL->restoreWin32EHStackPointers(MBB, MBBI, DL, /*RestoreSP=*/IsSEH);
333  MBBI->eraseFromParent();
334  return true;
335  }
336  case X86::LCMPXCHG8B_SAVE_EBX:
337  case X86::LCMPXCHG16B_SAVE_RBX: {
338  // Perform the following transformation.
339  // SaveRbx = pseudocmpxchg Addr, <4 opds for the address>, InArg, SaveRbx
340  // =>
341  // [E|R]BX = InArg
342  // actualcmpxchg Addr
343  // [E|R]BX = SaveRbx
344  const MachineOperand &InArg = MBBI->getOperand(6);
345  unsigned SaveRbx = MBBI->getOperand(7).getReg();
346 
347  unsigned ActualInArg =
348  Opcode == X86::LCMPXCHG8B_SAVE_EBX ? X86::EBX : X86::RBX;
349  // Copy the input argument of the pseudo into the argument of the
350  // actual instruction.
351  TII->copyPhysReg(MBB, MBBI, DL, ActualInArg, InArg.getReg(),
352  InArg.isKill());
353  // Create the actual instruction.
354  unsigned ActualOpc =
355  Opcode == X86::LCMPXCHG8B_SAVE_EBX ? X86::LCMPXCHG8B : X86::LCMPXCHG16B;
356  MachineInstr *NewInstr = BuildMI(MBB, MBBI, DL, TII->get(ActualOpc));
357  // Copy the operands related to the address.
358  for (unsigned Idx = 1; Idx < 6; ++Idx)
359  NewInstr->addOperand(MBBI->getOperand(Idx));
360  // Finally, restore the value of RBX.
361  TII->copyPhysReg(MBB, MBBI, DL, ActualInArg, SaveRbx,
362  /*SrcIsKill*/ true);
363 
364  // Delete the pseudo.
365  MBBI->eraseFromParent();
366  return true;
367  }
368  case TargetOpcode::ICALL_BRANCH_FUNNEL:
369  ExpandICallBranchFunnel(&MBB, MBBI);
370  return true;
371  }
372  llvm_unreachable("Previous switch has a fallthrough?");
373 }
374 
375 /// Expand all pseudo instructions contained in \p MBB.
376 /// \returns true if any expansion occurred for \p MBB.
377 bool X86ExpandPseudo::ExpandMBB(MachineBasicBlock &MBB) {
378  bool Modified = false;
379 
380  // MBBI may be invalidated by the expansion.
381  MachineBasicBlock::iterator MBBI = MBB.begin(), E = MBB.end();
382  while (MBBI != E) {
383  MachineBasicBlock::iterator NMBBI = std::next(MBBI);
384  Modified |= ExpandMI(MBB, MBBI);
385  MBBI = NMBBI;
386  }
387 
388  return Modified;
389 }
390 
391 bool X86ExpandPseudo::runOnMachineFunction(MachineFunction &MF) {
392  STI = &static_cast<const X86Subtarget &>(MF.getSubtarget());
393  TII = STI->getInstrInfo();
394  TRI = STI->getRegisterInfo();
395  X86FI = MF.getInfo<X86MachineFunctionInfo>();
396  X86FL = STI->getFrameLowering();
397 
398  bool Modified = false;
399  for (MachineBasicBlock &MBB : MF)
400  Modified |= ExpandMBB(MBB);
401  return Modified;
402 }
403 
404 /// Returns an instance of the pseudo instruction expansion pass.
406  return new X86ExpandPseudo();
407 }
unsigned getTargetFlags() const
const MachineInstrBuilder & add(const MachineOperand &MO) const
This class represents lattice values for constants.
Definition: AllocatorList.h:23
const DebugLoc & getDebugLoc() const
Returns the debug location id of this MachineInstr.
Definition: MachineInstr.h:384
char & MachineDominatorsID
MachineDominators - This pass is a machine dominators analysis pass.
unsigned getReg() const
getReg - Returns the register number.
unsigned const TargetRegisterInfo * TRI
A debug info location.
Definition: DebugLoc.h:33
const MachineInstrBuilder & addGlobalAddress(const GlobalValue *GV, int64_t Offset=0, unsigned char TargetFlags=0) const
bool isImm() const
isImm - Tests if this is a MO_Immediate operand.
X86MachineFunctionInfo - This class is derived from MachineFunction and contains private X86 target-s...
char & MachineLoopInfoID
MachineLoopInfo - This pass is a loop analysis pass.
instr_iterator erase(instr_iterator I)
Remove an instruction from the instruction list and delete it.
#define DEBUG_TYPE
MachineFunctionPass - This class adapts the FunctionPass interface to allow convenient creation of pa...
const HexagonInstrInfo * TII
unsigned getNumOperands() const
Retuns the total number of operands.
Definition: MachineInstr.h:413
unsigned getOpcode() const
Returns the opcode of this MachineInstr.
Definition: MachineInstr.h:410
INITIALIZE_PASS(X86ExpandPseudo, DEBUG_TYPE, X86_EXPAND_PSEUDO_NAME, false, false) void X86ExpandPseudo
const char * getSymbolName() const
static bool isMem(const MachineInstr &MI, unsigned Op)
Definition: X86InstrInfo.h:122
void copyImplicitOps(MachineFunction &MF, const MachineInstr &MI)
Copy implicit register operands from specified instruction to this instruction.
Return from interrupt. Operand 0 is the number of bytes to pop.
AnalysisUsage & addPreservedID(const void *ID)
MachineBasicBlock * CreateMachineBasicBlock(const BasicBlock *bb=nullptr)
CreateMachineBasicBlock - Allocate a new MachineBasicBlock.
BasicBlockListType::iterator iterator
MachineInstrBuilder BuildMI(MachineFunction &MF, const DebugLoc &DL, const MCInstrDesc &MCID)
Builder interface. Specify how to create the initial instruction itself.
#define P(N)
LLVM Basic Block Representation.
Definition: BasicBlock.h:57
const TargetSubtargetInfo & getSubtarget() const
getSubtarget - Return the subtarget for which this machine code is being compiled.
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...
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
const GlobalValue * getGlobal() const
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.
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:284
static Target * FirstTarget
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
void setIsKill(bool Val=true)
void addSuccessor(MachineBasicBlock *Succ, BranchProbability Prob=BranchProbability::getUnknown())
Add Succ as a successor of this MachineBasicBlock.
void addOperand(MachineFunction &MF, const MachineOperand &Op)
Add the specified operand to the instruction.
bool isGlobal() const
isGlobal - Tests if this is a MO_GlobalAddress operand.
static uint64_t add(uint64_t LeftOp, uint64_t RightOp)
Definition: FileCheck.cpp:196
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:301
int64_t getImm() const
const Function & getFunction() const
Return the LLVM function that this machine code represents.
Target - Wrapper for Target specific information.
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:63
const MachineFunction * getParent() const
Return the MachineFunction containing this basic block.
const MachineInstrBuilder & addImm(int64_t Val) const
Add a new immediate operand.
#define X86_EXPAND_PSEUDO_NAME
int64_t getOffset() const
Return the offset from the symbol in this operand.
const MachineInstrBuilder & addExternalSymbol(const char *FnName, unsigned char TargetFlags=0) const
#define I(x, y, z)
Definition: MD5.cpp:58
const MachineInstrBuilder & addReg(unsigned RegNo, unsigned flags=0, unsigned SubReg=0) const
Add a new virtual register operand.
constexpr bool isUInt< 16 >(uint64_t x)
Definition: MathExtras.h:345
bool isSymbol() const
isSymbol - Tests if this is a MO_ExternalSymbol operand.
bool isReg() const
isReg - Tests if this is a MO_Register operand.
OUTCHAIN = EH_RETURN(INCHAIN, OFFSET, HANDLER) - This node represents &#39;eh_return&#39; gcc dwarf builtin...
Definition: ISDOpcodes.h:101
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
void insert(iterator MBBI, MachineBasicBlock *MBB)
bool isAsynchronousEHPersonality(EHPersonality Pers)
Returns true if this personality function catches asynchronous exceptions.
Constant * getPersonalityFn() const
Get the personality function associated with this function.
Definition: Function.cpp:1385
IRTranslator LLVM IR MI
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:48
const MachineOperand & getOperand(unsigned i) const
Definition: MachineInstr.h:415
Properties which a MachineFunction may have at a given point in time.