1 //====- X86FlagsCopyLowering.cpp - Lowers COPY nodes of EFLAGS ------------===//
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
7 //===----------------------------------------------------------------------===//
10 /// Lowers COPY nodes of EFLAGS by directly extracting and preserving individual
13 /// We have to do this by carefully analyzing and rewriting the usage of the
14 /// copied EFLAGS register because there is no general way to rematerialize the
15 /// entire EFLAGS register safely and efficiently. Using `popf` both forces
16 /// dynamic stack adjustment and can create correctness issues due to IF, TF,
17 /// and other non-status flags being overwritten. Using sequences involving
18 /// SAHF don't work on all x86 processors and are often quite slow compared to
19 /// directly testing a single status preserved in its own GPR.
21 //===----------------------------------------------------------------------===//
24 #include "X86InstrBuilder.h"
25 #include "X86InstrInfo.h"
26 #include "X86Subtarget.h"
27 #include "llvm/ADT/ArrayRef.h"
28 #include "llvm/ADT/PostOrderIterator.h"
29 #include "llvm/ADT/STLExtras.h"
30 #include "llvm/ADT/ScopeExit.h"
31 #include "llvm/ADT/SmallPtrSet.h"
32 #include "llvm/ADT/SmallVector.h"
33 #include "llvm/ADT/Statistic.h"
34 #include "llvm/CodeGen/MachineBasicBlock.h"
35 #include "llvm/CodeGen/MachineConstantPool.h"
36 #include "llvm/CodeGen/MachineDominators.h"
37 #include "llvm/CodeGen/MachineFunction.h"
38 #include "llvm/CodeGen/MachineFunctionPass.h"
39 #include "llvm/CodeGen/MachineInstr.h"
40 #include "llvm/CodeGen/MachineInstrBuilder.h"
41 #include "llvm/CodeGen/MachineModuleInfo.h"
42 #include "llvm/CodeGen/MachineOperand.h"
43 #include "llvm/CodeGen/MachineRegisterInfo.h"
44 #include "llvm/CodeGen/MachineSSAUpdater.h"
45 #include "llvm/CodeGen/TargetInstrInfo.h"
46 #include "llvm/CodeGen/TargetRegisterInfo.h"
47 #include "llvm/CodeGen/TargetSchedule.h"
48 #include "llvm/CodeGen/TargetSubtargetInfo.h"
49 #include "llvm/IR/DebugLoc.h"
50 #include "llvm/MC/MCSchedule.h"
51 #include "llvm/Pass.h"
52 #include "llvm/Support/CommandLine.h"
53 #include "llvm/Support/Debug.h"
54 #include "llvm/Support/raw_ostream.h"
62 #define PASS_KEY "x86-flags-copy-lowering"
63 #define DEBUG_TYPE PASS_KEY
65 STATISTIC(NumCopiesEliminated
, "Number of copies of EFLAGS eliminated");
66 STATISTIC(NumSetCCsInserted
, "Number of setCC instructions inserted");
67 STATISTIC(NumTestsInserted
, "Number of test instructions inserted");
68 STATISTIC(NumAddsInserted
, "Number of adds instructions inserted");
72 // Convenient array type for storing registers associated with each condition.
73 using CondRegArray
= std::array
<unsigned, X86::LAST_VALID_COND
+ 1>;
75 class X86FlagsCopyLoweringPass
: public MachineFunctionPass
{
77 X86FlagsCopyLoweringPass() : MachineFunctionPass(ID
) { }
79 StringRef
getPassName() const override
{ return "X86 EFLAGS copy lowering"; }
80 bool runOnMachineFunction(MachineFunction
&MF
) override
;
81 void getAnalysisUsage(AnalysisUsage
&AU
) const override
;
83 /// Pass identification, replacement for typeid.
87 MachineRegisterInfo
*MRI
= nullptr;
88 const X86Subtarget
*Subtarget
= nullptr;
89 const X86InstrInfo
*TII
= nullptr;
90 const TargetRegisterInfo
*TRI
= nullptr;
91 const TargetRegisterClass
*PromoteRC
= nullptr;
92 MachineDominatorTree
*MDT
= nullptr;
94 CondRegArray
collectCondsInRegs(MachineBasicBlock
&MBB
,
95 MachineBasicBlock::iterator CopyDefI
);
97 Register
promoteCondToReg(MachineBasicBlock
&MBB
,
98 MachineBasicBlock::iterator TestPos
,
99 const DebugLoc
&TestLoc
, X86::CondCode Cond
);
100 std::pair
<unsigned, bool> getCondOrInverseInReg(
101 MachineBasicBlock
&TestMBB
, MachineBasicBlock::iterator TestPos
,
102 const DebugLoc
&TestLoc
, X86::CondCode Cond
, CondRegArray
&CondRegs
);
103 void insertTest(MachineBasicBlock
&MBB
, MachineBasicBlock::iterator Pos
,
104 const DebugLoc
&Loc
, unsigned Reg
);
106 void rewriteArithmetic(MachineBasicBlock
&TestMBB
,
107 MachineBasicBlock::iterator TestPos
,
108 const DebugLoc
&TestLoc
, MachineInstr
&MI
,
109 MachineOperand
&FlagUse
, CondRegArray
&CondRegs
);
110 void rewriteCMov(MachineBasicBlock
&TestMBB
,
111 MachineBasicBlock::iterator TestPos
, const DebugLoc
&TestLoc
,
112 MachineInstr
&CMovI
, MachineOperand
&FlagUse
,
113 CondRegArray
&CondRegs
);
114 void rewriteFCMov(MachineBasicBlock
&TestMBB
,
115 MachineBasicBlock::iterator TestPos
,
116 const DebugLoc
&TestLoc
, MachineInstr
&CMovI
,
117 MachineOperand
&FlagUse
, CondRegArray
&CondRegs
);
118 void rewriteCondJmp(MachineBasicBlock
&TestMBB
,
119 MachineBasicBlock::iterator TestPos
,
120 const DebugLoc
&TestLoc
, MachineInstr
&JmpI
,
121 CondRegArray
&CondRegs
);
122 void rewriteCopy(MachineInstr
&MI
, MachineOperand
&FlagUse
,
123 MachineInstr
&CopyDefI
);
124 void rewriteSetCC(MachineBasicBlock
&TestMBB
,
125 MachineBasicBlock::iterator TestPos
,
126 const DebugLoc
&TestLoc
, MachineInstr
&SetCCI
,
127 MachineOperand
&FlagUse
, CondRegArray
&CondRegs
);
130 } // end anonymous namespace
132 INITIALIZE_PASS_BEGIN(X86FlagsCopyLoweringPass
, DEBUG_TYPE
,
133 "X86 EFLAGS copy lowering", false, false)
134 INITIALIZE_PASS_END(X86FlagsCopyLoweringPass
, DEBUG_TYPE
,
135 "X86 EFLAGS copy lowering", false, false)
137 FunctionPass
*llvm::createX86FlagsCopyLoweringPass() {
138 return new X86FlagsCopyLoweringPass();
141 char X86FlagsCopyLoweringPass::ID
= 0;
143 void X86FlagsCopyLoweringPass::getAnalysisUsage(AnalysisUsage
&AU
) const {
144 AU
.addRequired
<MachineDominatorTree
>();
145 MachineFunctionPass::getAnalysisUsage(AU
);
149 /// An enumeration of the arithmetic instruction mnemonics which have
150 /// interesting flag semantics.
152 /// We can map instruction opcodes into these mnemonics to make it easy to
153 /// dispatch with specific functionality.
154 enum class FlagArithMnemonic
{
163 static FlagArithMnemonic
getMnemonicFromOpcode(unsigned Opcode
) {
166 report_fatal_error("No support for lowering a copy into EFLAGS when used "
167 "by this instruction!");
169 #define LLVM_EXPAND_INSTR_SIZES(MNEMONIC, SUFFIX) \
170 case X86::MNEMONIC##8##SUFFIX: \
171 case X86::MNEMONIC##16##SUFFIX: \
172 case X86::MNEMONIC##32##SUFFIX: \
173 case X86::MNEMONIC##64##SUFFIX:
175 #define LLVM_EXPAND_ADC_SBB_INSTR(MNEMONIC) \
176 LLVM_EXPAND_INSTR_SIZES(MNEMONIC, rr) \
177 LLVM_EXPAND_INSTR_SIZES(MNEMONIC, rr_REV) \
178 LLVM_EXPAND_INSTR_SIZES(MNEMONIC, rm) \
179 LLVM_EXPAND_INSTR_SIZES(MNEMONIC, mr) \
180 case X86::MNEMONIC##8ri: \
181 case X86::MNEMONIC##16ri8: \
182 case X86::MNEMONIC##32ri8: \
183 case X86::MNEMONIC##64ri8: \
184 case X86::MNEMONIC##16ri: \
185 case X86::MNEMONIC##32ri: \
186 case X86::MNEMONIC##64ri32: \
187 case X86::MNEMONIC##8mi: \
188 case X86::MNEMONIC##16mi8: \
189 case X86::MNEMONIC##32mi8: \
190 case X86::MNEMONIC##64mi8: \
191 case X86::MNEMONIC##16mi: \
192 case X86::MNEMONIC##32mi: \
193 case X86::MNEMONIC##64mi32: \
194 case X86::MNEMONIC##8i8: \
195 case X86::MNEMONIC##16i16: \
196 case X86::MNEMONIC##32i32: \
197 case X86::MNEMONIC##64i32:
199 LLVM_EXPAND_ADC_SBB_INSTR(ADC
)
200 return FlagArithMnemonic::ADC
;
202 LLVM_EXPAND_ADC_SBB_INSTR(SBB
)
203 return FlagArithMnemonic::SBB
;
205 #undef LLVM_EXPAND_ADC_SBB_INSTR
207 LLVM_EXPAND_INSTR_SIZES(RCL
, rCL
)
208 LLVM_EXPAND_INSTR_SIZES(RCL
, r1
)
209 LLVM_EXPAND_INSTR_SIZES(RCL
, ri
)
210 return FlagArithMnemonic::RCL
;
212 LLVM_EXPAND_INSTR_SIZES(RCR
, rCL
)
213 LLVM_EXPAND_INSTR_SIZES(RCR
, r1
)
214 LLVM_EXPAND_INSTR_SIZES(RCR
, ri
)
215 return FlagArithMnemonic::RCR
;
217 #undef LLVM_EXPAND_INSTR_SIZES
221 return FlagArithMnemonic::SETB
;
225 static MachineBasicBlock
&splitBlock(MachineBasicBlock
&MBB
,
226 MachineInstr
&SplitI
,
227 const X86InstrInfo
&TII
) {
228 MachineFunction
&MF
= *MBB
.getParent();
230 assert(SplitI
.getParent() == &MBB
&&
231 "Split instruction must be in the split block!");
232 assert(SplitI
.isBranch() &&
233 "Only designed to split a tail of branch instructions!");
234 assert(X86::getCondFromBranch(SplitI
) != X86::COND_INVALID
&&
235 "Must split on an actual jCC instruction!");
237 // Dig out the previous instruction to the split point.
238 MachineInstr
&PrevI
= *std::prev(SplitI
.getIterator());
239 assert(PrevI
.isBranch() && "Must split after a branch!");
240 assert(X86::getCondFromBranch(PrevI
) != X86::COND_INVALID
&&
241 "Must split after an actual jCC instruction!");
242 assert(!std::prev(PrevI
.getIterator())->isTerminator() &&
243 "Must only have this one terminator prior to the split!");
245 // Grab the one successor edge that will stay in `MBB`.
246 MachineBasicBlock
&UnsplitSucc
= *PrevI
.getOperand(0).getMBB();
248 // Analyze the original block to see if we are actually splitting an edge
249 // into two edges. This can happen when we have multiple conditional jumps to
250 // the same successor.
252 std::any_of(SplitI
.getIterator(), MBB
.instr_end(),
253 [&](MachineInstr
&MI
) {
254 assert(MI
.isTerminator() &&
255 "Should only have spliced terminators!");
257 MI
.operands(), [&](MachineOperand
&MOp
) {
258 return MOp
.isMBB() && MOp
.getMBB() == &UnsplitSucc
;
261 MBB
.getFallThrough() == &UnsplitSucc
;
263 MachineBasicBlock
&NewMBB
= *MF
.CreateMachineBasicBlock();
265 // Insert the new block immediately after the current one. Any existing
266 // fallthrough will be sunk into this new block anyways.
267 MF
.insert(std::next(MachineFunction::iterator(&MBB
)), &NewMBB
);
269 // Splice the tail of instructions into the new block.
270 NewMBB
.splice(NewMBB
.end(), &MBB
, SplitI
.getIterator(), MBB
.end());
272 // Copy the necessary succesors (and their probability info) into the new
274 for (auto SI
= MBB
.succ_begin(), SE
= MBB
.succ_end(); SI
!= SE
; ++SI
)
275 if (IsEdgeSplit
|| *SI
!= &UnsplitSucc
)
276 NewMBB
.copySuccessor(&MBB
, SI
);
277 // Normalize the probabilities if we didn't end up splitting the edge.
279 NewMBB
.normalizeSuccProbs();
281 // Now replace all of the moved successors in the original block with the new
282 // block. This will merge their probabilities.
283 for (MachineBasicBlock
*Succ
: NewMBB
.successors())
284 if (Succ
!= &UnsplitSucc
)
285 MBB
.replaceSuccessor(Succ
, &NewMBB
);
287 // We should always end up replacing at least one successor.
288 assert(MBB
.isSuccessor(&NewMBB
) &&
289 "Failed to make the new block a successor!");
291 // Now update all the PHIs.
292 for (MachineBasicBlock
*Succ
: NewMBB
.successors()) {
293 for (MachineInstr
&MI
: *Succ
) {
297 for (int OpIdx
= 1, NumOps
= MI
.getNumOperands(); OpIdx
< NumOps
;
299 MachineOperand
&OpV
= MI
.getOperand(OpIdx
);
300 MachineOperand
&OpMBB
= MI
.getOperand(OpIdx
+ 1);
301 assert(OpMBB
.isMBB() && "Block operand to a PHI is not a block!");
302 if (OpMBB
.getMBB() != &MBB
)
305 // Replace the operand for unsplit successors
306 if (!IsEdgeSplit
|| Succ
!= &UnsplitSucc
) {
307 OpMBB
.setMBB(&NewMBB
);
309 // We have to continue scanning as there may be multiple entries in
314 // When we have split the edge append a new successor.
315 MI
.addOperand(MF
, OpV
);
316 MI
.addOperand(MF
, MachineOperand::CreateMBB(&NewMBB
));
325 static X86::CondCode
getCondFromFCMOV(unsigned Opcode
) {
327 default: return X86::COND_INVALID
;
328 case X86::CMOVBE_Fp32
: case X86::CMOVBE_Fp64
: case X86::CMOVBE_Fp80
:
330 case X86::CMOVB_Fp32
: case X86::CMOVB_Fp64
: case X86::CMOVB_Fp80
:
332 case X86::CMOVE_Fp32
: case X86::CMOVE_Fp64
: case X86::CMOVE_Fp80
:
334 case X86::CMOVNBE_Fp32
: case X86::CMOVNBE_Fp64
: case X86::CMOVNBE_Fp80
:
336 case X86::CMOVNB_Fp32
: case X86::CMOVNB_Fp64
: case X86::CMOVNB_Fp80
:
338 case X86::CMOVNE_Fp32
: case X86::CMOVNE_Fp64
: case X86::CMOVNE_Fp80
:
340 case X86::CMOVNP_Fp32
: case X86::CMOVNP_Fp64
: case X86::CMOVNP_Fp80
:
342 case X86::CMOVP_Fp32
: case X86::CMOVP_Fp64
: case X86::CMOVP_Fp80
:
347 bool X86FlagsCopyLoweringPass::runOnMachineFunction(MachineFunction
&MF
) {
348 LLVM_DEBUG(dbgs() << "********** " << getPassName() << " : " << MF
.getName()
351 Subtarget
= &MF
.getSubtarget
<X86Subtarget
>();
352 MRI
= &MF
.getRegInfo();
353 TII
= Subtarget
->getInstrInfo();
354 TRI
= Subtarget
->getRegisterInfo();
355 MDT
= &getAnalysis
<MachineDominatorTree
>();
356 PromoteRC
= &X86::GR8RegClass
;
358 if (MF
.begin() == MF
.end())
359 // Nothing to do for a degenerate empty function...
362 // Collect the copies in RPO so that when there are chains where a copy is in
363 // turn copied again we visit the first one first. This ensures we can find
364 // viable locations for testing the original EFLAGS that dominate all the
365 // uses across complex CFGs.
366 SmallVector
<MachineInstr
*, 4> Copies
;
367 ReversePostOrderTraversal
<MachineFunction
*> RPOT(&MF
);
368 for (MachineBasicBlock
*MBB
: RPOT
)
369 for (MachineInstr
&MI
: *MBB
)
370 if (MI
.getOpcode() == TargetOpcode::COPY
&&
371 MI
.getOperand(0).getReg() == X86::EFLAGS
)
372 Copies
.push_back(&MI
);
374 for (MachineInstr
*CopyI
: Copies
) {
375 MachineBasicBlock
&MBB
= *CopyI
->getParent();
377 MachineOperand
&VOp
= CopyI
->getOperand(1);
378 assert(VOp
.isReg() &&
379 "The input to the copy for EFLAGS should always be a register!");
380 MachineInstr
&CopyDefI
= *MRI
->getVRegDef(VOp
.getReg());
381 if (CopyDefI
.getOpcode() != TargetOpcode::COPY
) {
382 // FIXME: The big likely candidate here are PHI nodes. We could in theory
383 // handle PHI nodes, but it gets really, really hard. Insanely hard. Hard
384 // enough that it is probably better to change every other part of LLVM
385 // to avoid creating them. The issue is that once we have PHIs we won't
386 // know which original EFLAGS value we need to capture with our setCCs
387 // below. The end result will be computing a complete set of setCCs that
388 // we *might* want, computing them in every place where we copy *out* of
389 // EFLAGS and then doing SSA formation on all of them to insert necessary
390 // PHI nodes and consume those here. Then hoping that somehow we DCE the
391 // unnecessary ones. This DCE seems very unlikely to be successful and so
392 // we will almost certainly end up with a glut of dead setCC
393 // instructions. Until we have a motivating test case and fail to avoid
394 // it by changing other parts of LLVM's lowering, we refuse to handle
395 // this complex case here.
397 dbgs() << "ERROR: Encountered unexpected def of an eflags copy: ";
400 "Cannot lower EFLAGS copy unless it is defined in turn by a copy!");
403 auto Cleanup
= make_scope_exit([&] {
404 // All uses of the EFLAGS copy are now rewritten, kill the copy into
405 // eflags and if dead the copy from.
406 CopyI
->eraseFromParent();
407 if (MRI
->use_empty(CopyDefI
.getOperand(0).getReg()))
408 CopyDefI
.eraseFromParent();
409 ++NumCopiesEliminated
;
412 MachineOperand
&DOp
= CopyI
->getOperand(0);
413 assert(DOp
.isDef() && "Expected register def!");
414 assert(DOp
.getReg() == X86::EFLAGS
&& "Unexpected copy def register!");
418 MachineBasicBlock
*TestMBB
= CopyDefI
.getParent();
419 auto TestPos
= CopyDefI
.getIterator();
420 DebugLoc TestLoc
= CopyDefI
.getDebugLoc();
422 LLVM_DEBUG(dbgs() << "Rewriting copy: "; CopyI
->dump());
424 // Walk up across live-in EFLAGS to find where they were actually def'ed.
426 // This copy's def may just be part of a region of blocks covered by
427 // a single def of EFLAGS and we want to find the top of that region where
430 // This is essentially a search for a *candidate* reaching definition
431 // location. We don't need to ever find the actual reaching definition here,
432 // but we want to walk up the dominator tree to find the highest point which
433 // would be viable for such a definition.
434 auto HasEFLAGSClobber
= [&](MachineBasicBlock::iterator Begin
,
435 MachineBasicBlock::iterator End
) {
436 // Scan backwards as we expect these to be relatively short and often find
437 // a clobber near the end.
439 llvm::reverse(llvm::make_range(Begin
, End
)), [&](MachineInstr
&MI
) {
440 // Flag any instruction (other than the copy we are
441 // currently rewriting) that defs EFLAGS.
442 return &MI
!= CopyI
&& MI
.findRegisterDefOperand(X86::EFLAGS
);
445 auto HasEFLAGSClobberPath
= [&](MachineBasicBlock
*BeginMBB
,
446 MachineBasicBlock
*EndMBB
) {
447 assert(MDT
->dominates(BeginMBB
, EndMBB
) &&
448 "Only support paths down the dominator tree!");
449 SmallPtrSet
<MachineBasicBlock
*, 4> Visited
;
450 SmallVector
<MachineBasicBlock
*, 4> Worklist
;
451 // We terminate at the beginning. No need to scan it.
452 Visited
.insert(BeginMBB
);
453 Worklist
.push_back(EndMBB
);
455 auto *MBB
= Worklist
.pop_back_val();
456 for (auto *PredMBB
: MBB
->predecessors()) {
457 if (!Visited
.insert(PredMBB
).second
)
459 if (HasEFLAGSClobber(PredMBB
->begin(), PredMBB
->end()))
461 // Enqueue this block to walk its predecessors.
462 Worklist
.push_back(PredMBB
);
464 } while (!Worklist
.empty());
465 // No clobber found along a path from the begin to end.
468 while (TestMBB
->isLiveIn(X86::EFLAGS
) && !TestMBB
->pred_empty() &&
469 !HasEFLAGSClobber(TestMBB
->begin(), TestPos
)) {
470 // Find the nearest common dominator of the predecessors, as
471 // that will be the best candidate to hoist into.
472 MachineBasicBlock
*HoistMBB
=
473 std::accumulate(std::next(TestMBB
->pred_begin()), TestMBB
->pred_end(),
474 *TestMBB
->pred_begin(),
475 [&](MachineBasicBlock
*LHS
, MachineBasicBlock
*RHS
) {
476 return MDT
->findNearestCommonDominator(LHS
, RHS
);
479 // Now we need to scan all predecessors that may be reached along paths to
480 // the hoist block. A clobber anywhere in any of these blocks the hoist.
481 // Note that this even handles loops because we require *no* clobbers.
482 if (HasEFLAGSClobberPath(HoistMBB
, TestMBB
))
485 // We also need the terminators to not sneakily clobber flags.
486 if (HasEFLAGSClobber(HoistMBB
->getFirstTerminator()->getIterator(),
487 HoistMBB
->instr_end()))
490 // We found a viable location, hoist our test position to it.
492 TestPos
= TestMBB
->getFirstTerminator()->getIterator();
493 // Clear the debug location as it would just be confusing after hoisting.
494 TestLoc
= DebugLoc();
497 auto DefIt
= llvm::find_if(
498 llvm::reverse(llvm::make_range(TestMBB
->instr_begin(), TestPos
)),
499 [&](MachineInstr
&MI
) {
500 return MI
.findRegisterDefOperand(X86::EFLAGS
);
502 if (DefIt
.base() != TestMBB
->instr_begin()) {
503 dbgs() << " Using EFLAGS defined by: ";
506 dbgs() << " Using live-in flags for BB:\n";
511 // While rewriting uses, we buffer jumps and rewrite them in a second pass
512 // because doing so will perturb the CFG that we are walking to find the
513 // uses in the first place.
514 SmallVector
<MachineInstr
*, 4> JmpIs
;
516 // Gather the condition flags that have already been preserved in
517 // registers. We do this from scratch each time as we expect there to be
518 // very few of them and we expect to not revisit the same copy definition
519 // many times. If either of those change sufficiently we could build a map
520 // of these up front instead.
521 CondRegArray CondRegs
= collectCondsInRegs(*TestMBB
, TestPos
);
523 // Collect the basic blocks we need to scan. Typically this will just be
524 // a single basic block but we may have to scan multiple blocks if the
525 // EFLAGS copy lives into successors.
526 SmallVector
<MachineBasicBlock
*, 2> Blocks
;
527 SmallPtrSet
<MachineBasicBlock
*, 2> VisitedBlocks
;
528 Blocks
.push_back(&MBB
);
531 MachineBasicBlock
&UseMBB
= *Blocks
.pop_back_val();
533 // Track when if/when we find a kill of the flags in this block.
534 bool FlagsKilled
= false;
536 // In most cases, we walk from the beginning to the end of the block. But
537 // when the block is the same block as the copy is from, we will visit it
538 // twice. The first time we start from the copy and go to the end. The
539 // second time we start from the beginning and go to the copy. This lets
540 // us handle copies inside of cycles.
541 // FIXME: This loop is *super* confusing. This is at least in part
542 // a symptom of all of this routine needing to be refactored into
543 // documentable components. Once done, there may be a better way to write
545 for (auto MII
= (&UseMBB
== &MBB
&& !VisitedBlocks
.count(&UseMBB
))
546 ? std::next(CopyI
->getIterator())
547 : UseMBB
.instr_begin(),
548 MIE
= UseMBB
.instr_end();
550 MachineInstr
&MI
= *MII
++;
551 // If we are in the original copy block and encounter either the copy
552 // def or the copy itself, break so that we don't re-process any part of
553 // the block or process the instructions in the range that was copied
555 if (&MI
== CopyI
|| &MI
== &CopyDefI
) {
556 assert(&UseMBB
== &MBB
&& VisitedBlocks
.count(&MBB
) &&
557 "Should only encounter these on the second pass over the "
562 MachineOperand
*FlagUse
= MI
.findRegisterUseOperand(X86::EFLAGS
);
564 if (MI
.findRegisterDefOperand(X86::EFLAGS
)) {
565 // If EFLAGS are defined, it's as-if they were killed. We can stop
568 // NB!!! Many instructions only modify some flags. LLVM currently
569 // models this as clobbering all flags, but if that ever changes
570 // this will need to be carefully updated to handle that more
578 LLVM_DEBUG(dbgs() << " Rewriting use: "; MI
.dump());
580 // Check the kill flag before we rewrite as that may change it.
581 if (FlagUse
->isKill())
584 // Once we encounter a branch, the rest of the instructions must also be
585 // branches. We can't rewrite in place here, so we handle them below.
587 // Note that we don't have to handle tail calls here, even conditional
588 // tail calls, as those are not introduced into the X86 MI until post-RA
589 // branch folding or black placement. As a consequence, we get to deal
590 // with the simpler formulation of conditional branches followed by tail
592 if (X86::getCondFromBranch(MI
) != X86::COND_INVALID
) {
593 auto JmpIt
= MI
.getIterator();
595 JmpIs
.push_back(&*JmpIt
);
597 } while (JmpIt
!= UseMBB
.instr_end() &&
598 X86::getCondFromBranch(*JmpIt
) !=
603 // Otherwise we can just rewrite in-place.
604 if (X86::getCondFromCMov(MI
) != X86::COND_INVALID
) {
605 rewriteCMov(*TestMBB
, TestPos
, TestLoc
, MI
, *FlagUse
, CondRegs
);
606 } else if (getCondFromFCMOV(MI
.getOpcode()) != X86::COND_INVALID
) {
607 rewriteFCMov(*TestMBB
, TestPos
, TestLoc
, MI
, *FlagUse
, CondRegs
);
608 } else if (X86::getCondFromSETCC(MI
) != X86::COND_INVALID
) {
609 rewriteSetCC(*TestMBB
, TestPos
, TestLoc
, MI
, *FlagUse
, CondRegs
);
610 } else if (MI
.getOpcode() == TargetOpcode::COPY
) {
611 rewriteCopy(MI
, *FlagUse
, CopyDefI
);
613 // We assume all other instructions that use flags also def them.
614 assert(MI
.findRegisterDefOperand(X86::EFLAGS
) &&
615 "Expected a def of EFLAGS for this instruction!");
617 // NB!!! Several arithmetic instructions only *partially* update
618 // flags. Theoretically, we could generate MI code sequences that
619 // would rely on this fact and observe different flags independently.
620 // But currently LLVM models all of these instructions as clobbering
621 // all the flags in an undef way. We rely on that to simplify the
625 // Generically handle remaining uses as arithmetic instructions.
626 rewriteArithmetic(*TestMBB
, TestPos
, TestLoc
, MI
, *FlagUse
,
630 // If this was the last use of the flags, we're done.
635 // If the flags were killed, we're done with this block.
639 // Otherwise we need to scan successors for ones where the flags live-in
640 // and queue those up for processing.
641 for (MachineBasicBlock
*SuccMBB
: UseMBB
.successors())
642 if (SuccMBB
->isLiveIn(X86::EFLAGS
) &&
643 VisitedBlocks
.insert(SuccMBB
).second
) {
644 // We currently don't do any PHI insertion and so we require that the
645 // test basic block dominates all of the use basic blocks. Further, we
646 // can't have a cycle from the test block back to itself as that would
647 // create a cycle requiring a PHI to break it.
649 // We could in theory do PHI insertion here if it becomes useful by
650 // just taking undef values in along every edge that we don't trace
651 // this EFLAGS copy along. This isn't as bad as fully general PHI
652 // insertion, but still seems like a great deal of complexity.
654 // Because it is theoretically possible that some earlier MI pass or
655 // other lowering transformation could induce this to happen, we do
656 // a hard check even in non-debug builds here.
657 if (SuccMBB
== TestMBB
|| !MDT
->dominates(TestMBB
, SuccMBB
)) {
660 << "ERROR: Encountered use that is not dominated by our test "
661 "basic block! Rewriting this would require inserting PHI "
662 "nodes to track the flag state across the CFG.\n\nTest "
665 dbgs() << "Use block:\n";
669 "Cannot lower EFLAGS copy when original copy def "
670 "does not dominate all uses.");
673 Blocks
.push_back(SuccMBB
);
675 // After this, EFLAGS will be recreated before each use.
676 SuccMBB
->removeLiveIn(X86::EFLAGS
);
678 } while (!Blocks
.empty());
680 // Now rewrite the jumps that use the flags. These we handle specially
681 // because if there are multiple jumps in a single basic block we'll have
682 // to do surgery on the CFG.
683 MachineBasicBlock
*LastJmpMBB
= nullptr;
684 for (MachineInstr
*JmpI
: JmpIs
) {
685 // Past the first jump within a basic block we need to split the blocks
687 if (JmpI
->getParent() == LastJmpMBB
)
688 splitBlock(*JmpI
->getParent(), *JmpI
, *TII
);
690 LastJmpMBB
= JmpI
->getParent();
692 rewriteCondJmp(*TestMBB
, TestPos
, TestLoc
, *JmpI
, CondRegs
);
695 // FIXME: Mark the last use of EFLAGS before the copy's def as a kill if
696 // the copy's def operand is itself a kill.
700 for (MachineBasicBlock
&MBB
: MF
)
701 for (MachineInstr
&MI
: MBB
)
702 if (MI
.getOpcode() == TargetOpcode::COPY
&&
703 (MI
.getOperand(0).getReg() == X86::EFLAGS
||
704 MI
.getOperand(1).getReg() == X86::EFLAGS
)) {
705 LLVM_DEBUG(dbgs() << "ERROR: Found a COPY involving EFLAGS: ";
707 llvm_unreachable("Unlowered EFLAGS copy!");
714 /// Collect any conditions that have already been set in registers so that we
715 /// can re-use them rather than adding duplicates.
716 CondRegArray
X86FlagsCopyLoweringPass::collectCondsInRegs(
717 MachineBasicBlock
&MBB
, MachineBasicBlock::iterator TestPos
) {
718 CondRegArray CondRegs
= {};
720 // Scan backwards across the range of instructions with live EFLAGS.
721 for (MachineInstr
&MI
:
722 llvm::reverse(llvm::make_range(MBB
.begin(), TestPos
))) {
723 X86::CondCode Cond
= X86::getCondFromSETCC(MI
);
724 if (Cond
!= X86::COND_INVALID
&& !MI
.mayStore() &&
725 MI
.getOperand(0).isReg() && MI
.getOperand(0).getReg().isVirtual()) {
726 assert(MI
.getOperand(0).isDef() &&
727 "A non-storing SETcc should always define a register!");
728 CondRegs
[Cond
] = MI
.getOperand(0).getReg();
731 // Stop scanning when we see the first definition of the EFLAGS as prior to
732 // this we would potentially capture the wrong flag state.
733 if (MI
.findRegisterDefOperand(X86::EFLAGS
))
739 Register
X86FlagsCopyLoweringPass::promoteCondToReg(
740 MachineBasicBlock
&TestMBB
, MachineBasicBlock::iterator TestPos
,
741 const DebugLoc
&TestLoc
, X86::CondCode Cond
) {
742 Register Reg
= MRI
->createVirtualRegister(PromoteRC
);
743 auto SetI
= BuildMI(TestMBB
, TestPos
, TestLoc
,
744 TII
->get(X86::SETCCr
), Reg
).addImm(Cond
);
746 LLVM_DEBUG(dbgs() << " save cond: "; SetI
->dump());
751 std::pair
<unsigned, bool> X86FlagsCopyLoweringPass::getCondOrInverseInReg(
752 MachineBasicBlock
&TestMBB
, MachineBasicBlock::iterator TestPos
,
753 const DebugLoc
&TestLoc
, X86::CondCode Cond
, CondRegArray
&CondRegs
) {
754 unsigned &CondReg
= CondRegs
[Cond
];
755 unsigned &InvCondReg
= CondRegs
[X86::GetOppositeBranchCondition(Cond
)];
756 if (!CondReg
&& !InvCondReg
)
757 CondReg
= promoteCondToReg(TestMBB
, TestPos
, TestLoc
, Cond
);
760 return {CondReg
, false};
762 return {InvCondReg
, true};
765 void X86FlagsCopyLoweringPass::insertTest(MachineBasicBlock
&MBB
,
766 MachineBasicBlock::iterator Pos
,
767 const DebugLoc
&Loc
, unsigned Reg
) {
769 BuildMI(MBB
, Pos
, Loc
, TII
->get(X86::TEST8rr
)).addReg(Reg
).addReg(Reg
);
771 LLVM_DEBUG(dbgs() << " test cond: "; TestI
->dump());
775 void X86FlagsCopyLoweringPass::rewriteArithmetic(
776 MachineBasicBlock
&TestMBB
, MachineBasicBlock::iterator TestPos
,
777 const DebugLoc
&TestLoc
, MachineInstr
&MI
, MachineOperand
&FlagUse
,
778 CondRegArray
&CondRegs
) {
779 // Arithmetic is either reading CF or OF. Figure out which condition we need
780 // to preserve in a register.
781 X86::CondCode Cond
= X86::COND_INVALID
;
783 // The addend to use to reset CF or OF when added to the flag value.
786 switch (getMnemonicFromOpcode(MI
.getOpcode())) {
787 case FlagArithMnemonic::ADC
:
788 case FlagArithMnemonic::RCL
:
789 case FlagArithMnemonic::RCR
:
790 case FlagArithMnemonic::SBB
:
791 case FlagArithMnemonic::SETB
:
792 Cond
= X86::COND_B
; // CF == 1
793 // Set up an addend that when one is added will need a carry due to not
794 // having a higher bit available.
799 // Now get a register that contains the value of the flag input to the
800 // arithmetic. We require exactly this flag to simplify the arithmetic
801 // required to materialize it back into the flag.
802 unsigned &CondReg
= CondRegs
[Cond
];
804 CondReg
= promoteCondToReg(TestMBB
, TestPos
, TestLoc
, Cond
);
806 MachineBasicBlock
&MBB
= *MI
.getParent();
808 // Insert an instruction that will set the flag back to the desired value.
809 Register TmpReg
= MRI
->createVirtualRegister(PromoteRC
);
811 BuildMI(MBB
, MI
.getIterator(), MI
.getDebugLoc(), TII
->get(X86::ADD8ri
))
812 .addDef(TmpReg
, RegState::Dead
)
816 LLVM_DEBUG(dbgs() << " add cond: "; AddI
->dump());
818 FlagUse
.setIsKill(true);
821 void X86FlagsCopyLoweringPass::rewriteCMov(MachineBasicBlock
&TestMBB
,
822 MachineBasicBlock::iterator TestPos
,
823 const DebugLoc
&TestLoc
,
825 MachineOperand
&FlagUse
,
826 CondRegArray
&CondRegs
) {
827 // First get the register containing this specific condition.
828 X86::CondCode Cond
= X86::getCondFromCMov(CMovI
);
831 std::tie(CondReg
, Inverted
) =
832 getCondOrInverseInReg(TestMBB
, TestPos
, TestLoc
, Cond
, CondRegs
);
834 MachineBasicBlock
&MBB
= *CMovI
.getParent();
836 // Insert a direct test of the saved register.
837 insertTest(MBB
, CMovI
.getIterator(), CMovI
.getDebugLoc(), CondReg
);
839 // Rewrite the CMov to use the !ZF flag from the test, and then kill its use
840 // of the flags afterward.
841 CMovI
.getOperand(CMovI
.getDesc().getNumOperands() - 1)
842 .setImm(Inverted
? X86::COND_E
: X86::COND_NE
);
843 FlagUse
.setIsKill(true);
844 LLVM_DEBUG(dbgs() << " fixed cmov: "; CMovI
.dump());
847 void X86FlagsCopyLoweringPass::rewriteFCMov(MachineBasicBlock
&TestMBB
,
848 MachineBasicBlock::iterator TestPos
,
849 const DebugLoc
&TestLoc
,
851 MachineOperand
&FlagUse
,
852 CondRegArray
&CondRegs
) {
853 // First get the register containing this specific condition.
854 X86::CondCode Cond
= getCondFromFCMOV(CMovI
.getOpcode());
857 std::tie(CondReg
, Inverted
) =
858 getCondOrInverseInReg(TestMBB
, TestPos
, TestLoc
, Cond
, CondRegs
);
860 MachineBasicBlock
&MBB
= *CMovI
.getParent();
862 // Insert a direct test of the saved register.
863 insertTest(MBB
, CMovI
.getIterator(), CMovI
.getDebugLoc(), CondReg
);
865 auto getFCMOVOpcode
= [](unsigned Opcode
, bool Inverted
) {
867 default: llvm_unreachable("Unexpected opcode!");
868 case X86::CMOVBE_Fp32
: case X86::CMOVNBE_Fp32
:
869 case X86::CMOVB_Fp32
: case X86::CMOVNB_Fp32
:
870 case X86::CMOVE_Fp32
: case X86::CMOVNE_Fp32
:
871 case X86::CMOVP_Fp32
: case X86::CMOVNP_Fp32
:
872 return Inverted
? X86::CMOVE_Fp32
: X86::CMOVNE_Fp32
;
873 case X86::CMOVBE_Fp64
: case X86::CMOVNBE_Fp64
:
874 case X86::CMOVB_Fp64
: case X86::CMOVNB_Fp64
:
875 case X86::CMOVE_Fp64
: case X86::CMOVNE_Fp64
:
876 case X86::CMOVP_Fp64
: case X86::CMOVNP_Fp64
:
877 return Inverted
? X86::CMOVE_Fp64
: X86::CMOVNE_Fp64
;
878 case X86::CMOVBE_Fp80
: case X86::CMOVNBE_Fp80
:
879 case X86::CMOVB_Fp80
: case X86::CMOVNB_Fp80
:
880 case X86::CMOVE_Fp80
: case X86::CMOVNE_Fp80
:
881 case X86::CMOVP_Fp80
: case X86::CMOVNP_Fp80
:
882 return Inverted
? X86::CMOVE_Fp80
: X86::CMOVNE_Fp80
;
886 // Rewrite the CMov to use the !ZF flag from the test.
887 CMovI
.setDesc(TII
->get(getFCMOVOpcode(CMovI
.getOpcode(), Inverted
)));
888 FlagUse
.setIsKill(true);
889 LLVM_DEBUG(dbgs() << " fixed fcmov: "; CMovI
.dump());
892 void X86FlagsCopyLoweringPass::rewriteCondJmp(
893 MachineBasicBlock
&TestMBB
, MachineBasicBlock::iterator TestPos
,
894 const DebugLoc
&TestLoc
, MachineInstr
&JmpI
, CondRegArray
&CondRegs
) {
895 // First get the register containing this specific condition.
896 X86::CondCode Cond
= X86::getCondFromBranch(JmpI
);
899 std::tie(CondReg
, Inverted
) =
900 getCondOrInverseInReg(TestMBB
, TestPos
, TestLoc
, Cond
, CondRegs
);
902 MachineBasicBlock
&JmpMBB
= *JmpI
.getParent();
904 // Insert a direct test of the saved register.
905 insertTest(JmpMBB
, JmpI
.getIterator(), JmpI
.getDebugLoc(), CondReg
);
907 // Rewrite the jump to use the !ZF flag from the test, and kill its use of
909 JmpI
.getOperand(1).setImm(Inverted
? X86::COND_E
: X86::COND_NE
);
910 JmpI
.findRegisterUseOperand(X86::EFLAGS
)->setIsKill(true);
911 LLVM_DEBUG(dbgs() << " fixed jCC: "; JmpI
.dump());
914 void X86FlagsCopyLoweringPass::rewriteCopy(MachineInstr
&MI
,
915 MachineOperand
&FlagUse
,
916 MachineInstr
&CopyDefI
) {
917 // Just replace this copy with the original copy def.
918 MRI
->replaceRegWith(MI
.getOperand(0).getReg(),
919 CopyDefI
.getOperand(0).getReg());
920 MI
.eraseFromParent();
923 void X86FlagsCopyLoweringPass::rewriteSetCC(MachineBasicBlock
&TestMBB
,
924 MachineBasicBlock::iterator TestPos
,
925 const DebugLoc
&TestLoc
,
926 MachineInstr
&SetCCI
,
927 MachineOperand
&FlagUse
,
928 CondRegArray
&CondRegs
) {
929 X86::CondCode Cond
= X86::getCondFromSETCC(SetCCI
);
930 // Note that we can't usefully rewrite this to the inverse without complex
931 // analysis of the users of the setCC. Largely we rely on duplicates which
932 // could have been avoided already being avoided here.
933 unsigned &CondReg
= CondRegs
[Cond
];
935 CondReg
= promoteCondToReg(TestMBB
, TestPos
, TestLoc
, Cond
);
937 // Rewriting a register def is trivial: we just replace the register and
939 if (!SetCCI
.mayStore()) {
940 assert(SetCCI
.getOperand(0).isReg() &&
941 "Cannot have a non-register defined operand to SETcc!");
942 Register OldReg
= SetCCI
.getOperand(0).getReg();
943 // Drop Kill flags on the old register before replacing. CondReg may have
944 // a longer live range.
945 MRI
->clearKillFlags(OldReg
);
946 MRI
->replaceRegWith(OldReg
, CondReg
);
947 SetCCI
.eraseFromParent();
951 // Otherwise, we need to emit a store.
952 auto MIB
= BuildMI(*SetCCI
.getParent(), SetCCI
.getIterator(),
953 SetCCI
.getDebugLoc(), TII
->get(X86::MOV8mr
));
954 // Copy the address operands.
955 for (int i
= 0; i
< X86::AddrNumOperands
; ++i
)
956 MIB
.add(SetCCI
.getOperand(i
));
960 MIB
.setMemRefs(SetCCI
.memoperands());
962 SetCCI
.eraseFromParent();