blob: 63ea62fcc628d54b7043bf724a493792d7898c40 [file] [log] [blame]
Amjad Aboud4563c062017-07-16 17:39:56 +00001//====-- X86CmovConversion.cpp - Convert Cmov to Branch -------------------===//
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/// \file
Sanjay Patel7e5af842017-08-30 13:16:25 +000010/// This file implements a pass that converts X86 cmov instructions into
11/// branches when profitable. This pass is conservative. It transforms if and
Sanjay Patel7b8183f2017-08-30 13:19:23 +000012/// only if it can guarantee a gain with high confidence.
Amjad Aboud4563c062017-07-16 17:39:56 +000013///
14/// Thus, the optimization applies under the following conditions:
Sanjay Patel7e5af842017-08-30 13:16:25 +000015/// 1. Consider as candidates only CMOVs in innermost loops (assume that
16/// most hotspots are represented by these loops).
17/// 2. Given a group of CMOV instructions that are using the same EFLAGS def
Amjad Aboud4563c062017-07-16 17:39:56 +000018/// instruction:
Sanjay Patel7e5af842017-08-30 13:16:25 +000019/// a. Consider them as candidates only if all have the same code condition
20/// or the opposite one to prevent generating more than one conditional
21/// jump per EFLAGS def instruction.
Amjad Aboud4563c062017-07-16 17:39:56 +000022/// b. Consider them as candidates only if all are profitable to be
Sanjay Patel7e5af842017-08-30 13:16:25 +000023/// converted (assume that one bad conversion may cause a degradation).
24/// 3. Apply conversion only for loops that are found profitable and only for
Amjad Aboud4563c062017-07-16 17:39:56 +000025/// CMOV candidates that were found profitable.
Sanjay Patel7e5af842017-08-30 13:16:25 +000026/// a. A loop is considered profitable only if conversion will reduce its
27/// depth cost by some threshold.
Amjad Aboud4563c062017-07-16 17:39:56 +000028/// b. CMOV is considered profitable if the cost of its condition is higher
29/// than the average cost of its true-value and false-value by 25% of
Sanjay Patel7b8183f2017-08-30 13:19:23 +000030/// branch-misprediction-penalty. This assures no degradation even with
Sanjay Patel7e5af842017-08-30 13:16:25 +000031/// 25% branch misprediction.
Amjad Aboud4563c062017-07-16 17:39:56 +000032///
33/// Note: This pass is assumed to run on SSA machine code.
34//===----------------------------------------------------------------------===//
35//
36// External interfaces:
37// FunctionPass *llvm::createX86CmovConverterPass();
38// bool X86CmovConverterPass::runOnMachineFunction(MachineFunction &MF);
39//
40
41#include "X86.h"
42#include "X86InstrInfo.h"
43#include "X86Subtarget.h"
44#include "llvm/ADT/Statistic.h"
45#include "llvm/CodeGen/MachineFunctionPass.h"
46#include "llvm/CodeGen/MachineInstrBuilder.h"
47#include "llvm/CodeGen/MachineLoopInfo.h"
48#include "llvm/CodeGen/MachineRegisterInfo.h"
49#include "llvm/CodeGen/Passes.h"
50#include "llvm/CodeGen/TargetSchedule.h"
51#include "llvm/IR/InstIterator.h"
52#include "llvm/Support/Debug.h"
53#include "llvm/Support/raw_ostream.h"
54using namespace llvm;
55
Amjad Aboud8ef85a02017-10-02 21:46:37 +000056#define DEBUG_TYPE "x86-cmov-conversion"
Amjad Aboud4563c062017-07-16 17:39:56 +000057
58STATISTIC(NumOfSkippedCmovGroups, "Number of unsupported CMOV-groups");
59STATISTIC(NumOfCmovGroupCandidate, "Number of CMOV-group candidates");
60STATISTIC(NumOfLoopCandidate, "Number of CMOV-conversion profitable loops");
61STATISTIC(NumOfOptimizedCmovGroups, "Number of optimized CMOV-groups");
62
Amjad Aboud8ef85a02017-10-02 21:46:37 +000063namespace llvm {
64 void initializeX86CmovConverterPassPass(PassRegistry &);
65}
66
Amjad Aboud4563c062017-07-16 17:39:56 +000067namespace {
68// This internal switch can be used to turn off the cmov/branch optimization.
69static cl::opt<bool>
70 EnableCmovConverter("x86-cmov-converter",
71 cl::desc("Enable the X86 cmov-to-branch optimization."),
72 cl::init(true), cl::Hidden);
73
Amjad Aboud6fa68132017-08-08 12:17:56 +000074static cl::opt<unsigned>
75 GainCycleThreshold("x86-cmov-converter-threshold",
76 cl::desc("Minimum gain per loop (in cycles) threshold."),
77 cl::init(4), cl::Hidden);
78
Chandler Carruth93a64552017-08-19 05:01:19 +000079static cl::opt<bool> ForceMemOperand(
80 "x86-cmov-converter-force-mem-operand",
81 cl::desc("Convert cmovs to branches whenever they have memory operands."),
82 cl::init(true), cl::Hidden);
83
Amjad Aboud4563c062017-07-16 17:39:56 +000084/// Converts X86 cmov instructions into branches when profitable.
85class X86CmovConverterPass : public MachineFunctionPass {
86public:
Amjad Aboud8ef85a02017-10-02 21:46:37 +000087 X86CmovConverterPass() : MachineFunctionPass(ID) {
88 initializeX86CmovConverterPassPass(*PassRegistry::getPassRegistry());
89 }
Amjad Aboud4563c062017-07-16 17:39:56 +000090 ~X86CmovConverterPass() {}
91
92 StringRef getPassName() const override { return "X86 cmov Conversion"; }
93 bool runOnMachineFunction(MachineFunction &MF) override;
94 void getAnalysisUsage(AnalysisUsage &AU) const override;
95
Amjad Aboud4563c062017-07-16 17:39:56 +000096 /// Pass identification, replacement for typeid.
97 static char ID;
98
Amjad Aboud8ef85a02017-10-02 21:46:37 +000099private:
100
Chandler Carruth93a64552017-08-19 05:01:19 +0000101 MachineRegisterInfo *MRI;
Amjad Aboud4563c062017-07-16 17:39:56 +0000102 const TargetInstrInfo *TII;
Chandler Carruth93a64552017-08-19 05:01:19 +0000103 const TargetRegisterInfo *TRI;
Amjad Aboud4563c062017-07-16 17:39:56 +0000104 TargetSchedModel TSchedModel;
105
106 /// List of consecutive CMOV instructions.
107 typedef SmallVector<MachineInstr *, 2> CmovGroup;
108 typedef SmallVector<CmovGroup, 2> CmovGroups;
109
110 /// Collect all CMOV-group-candidates in \p CurrLoop and update \p
111 /// CmovInstGroups accordingly.
112 ///
Chandler Carruthe3b35472017-08-19 04:28:20 +0000113 /// \param Blocks List of blocks to process.
Amjad Aboud4563c062017-07-16 17:39:56 +0000114 /// \param CmovInstGroups List of consecutive CMOV instructions in CurrLoop.
115 /// \returns true iff it found any CMOV-group-candidate.
Chandler Carruthe3b35472017-08-19 04:28:20 +0000116 bool collectCmovCandidates(ArrayRef<MachineBasicBlock *> Blocks,
Chandler Carruth93a64552017-08-19 05:01:19 +0000117 CmovGroups &CmovInstGroups,
118 bool IncludeLoads = false);
Amjad Aboud4563c062017-07-16 17:39:56 +0000119
120 /// Check if it is profitable to transform each CMOV-group-candidates into
121 /// branch. Remove all groups that are not profitable from \p CmovInstGroups.
122 ///
Chandler Carruthe3b35472017-08-19 04:28:20 +0000123 /// \param Blocks List of blocks to process.
Amjad Aboud4563c062017-07-16 17:39:56 +0000124 /// \param CmovInstGroups List of consecutive CMOV instructions in CurrLoop.
125 /// \returns true iff any CMOV-group-candidate remain.
Chandler Carruthe3b35472017-08-19 04:28:20 +0000126 bool checkForProfitableCmovCandidates(ArrayRef<MachineBasicBlock *> Blocks,
Amjad Aboud4563c062017-07-16 17:39:56 +0000127 CmovGroups &CmovInstGroups);
128
129 /// Convert the given list of consecutive CMOV instructions into a branch.
130 ///
131 /// \param Group Consecutive CMOV instructions to be converted into branch.
132 void convertCmovInstsToBranches(SmallVectorImpl<MachineInstr *> &Group) const;
133};
134
Amjad Aboud4563c062017-07-16 17:39:56 +0000135void X86CmovConverterPass::getAnalysisUsage(AnalysisUsage &AU) const {
136 MachineFunctionPass::getAnalysisUsage(AU);
137 AU.addRequired<MachineLoopInfo>();
138}
139
140bool X86CmovConverterPass::runOnMachineFunction(MachineFunction &MF) {
141 if (skipFunction(*MF.getFunction()))
142 return false;
143 if (!EnableCmovConverter)
144 return false;
145
146 DEBUG(dbgs() << "********** " << getPassName() << " : " << MF.getName()
147 << "**********\n");
148
149 bool Changed = false;
150 MachineLoopInfo &MLI = getAnalysis<MachineLoopInfo>();
151 const TargetSubtargetInfo &STI = MF.getSubtarget();
152 MRI = &MF.getRegInfo();
153 TII = STI.getInstrInfo();
Chandler Carruth93a64552017-08-19 05:01:19 +0000154 TRI = STI.getRegisterInfo();
Amjad Aboud4563c062017-07-16 17:39:56 +0000155 TSchedModel.init(STI.getSchedModel(), &STI, TII);
156
Chandler Carruth93a64552017-08-19 05:01:19 +0000157 // Before we handle the more subtle cases of register-register CMOVs inside
158 // of potentially hot loops, we want to quickly remove all CMOVs with
159 // a memory operand. The CMOV will risk a stall waiting for the load to
160 // complete that speculative execution behind a branch is better suited to
161 // handle on modern x86 chips.
162 if (ForceMemOperand) {
163 CmovGroups AllCmovGroups;
164 SmallVector<MachineBasicBlock *, 4> Blocks;
165 for (auto &MBB : MF)
166 Blocks.push_back(&MBB);
167 if (collectCmovCandidates(Blocks, AllCmovGroups, /*IncludeLoads*/ true)) {
168 for (auto &Group : AllCmovGroups) {
169 // Skip any group that doesn't do at least one memory operand cmov.
170 if (!llvm::any_of(Group, [&](MachineInstr *I) { return I->mayLoad(); }))
171 continue;
172
173 // For CMOV groups which we can rewrite and which contain a memory load,
174 // always rewrite them. On x86, a CMOV will dramatically amplify any
175 // memory latency by blocking speculative execution.
176 Changed = true;
177 convertCmovInstsToBranches(Group);
178 }
179 }
180 }
181
Amjad Aboud4563c062017-07-16 17:39:56 +0000182 //===--------------------------------------------------------------------===//
Chandler Carruth93a64552017-08-19 05:01:19 +0000183 // Register-operand Conversion Algorithm
Amjad Aboud4563c062017-07-16 17:39:56 +0000184 // ---------
185 // For each inner most loop
186 // collectCmovCandidates() {
187 // Find all CMOV-group-candidates.
188 // }
189 //
190 // checkForProfitableCmovCandidates() {
191 // * Calculate both loop-depth and optimized-loop-depth.
192 // * Use these depth to check for loop transformation profitability.
193 // * Check for CMOV-group-candidate transformation profitability.
194 // }
195 //
196 // For each profitable CMOV-group-candidate
197 // convertCmovInstsToBranches() {
198 // * Create FalseBB, SinkBB, Conditional branch to SinkBB.
199 // * Replace each CMOV instruction with a PHI instruction in SinkBB.
200 // }
201 //
202 // Note: For more details, see each function description.
203 //===--------------------------------------------------------------------===//
Amjad Aboud4563c062017-07-16 17:39:56 +0000204
Chandler Carruthe3b35472017-08-19 04:28:20 +0000205 // Build up the loops in pre-order.
206 SmallVector<MachineLoop *, 4> Loops(MLI.begin(), MLI.end());
207 // Note that we need to check size on each iteration as we accumulate child
208 // loops.
209 for (int i = 0; i < (int)Loops.size(); ++i)
210 for (MachineLoop *Child : Loops[i]->getSubLoops())
211 Loops.push_back(Child);
212
213 for (MachineLoop *CurrLoop : Loops) {
Amjad Aboud4563c062017-07-16 17:39:56 +0000214 // Optimize only inner most loops.
Chandler Carruthe3b35472017-08-19 04:28:20 +0000215 if (!CurrLoop->getSubLoops().empty())
Amjad Aboud4563c062017-07-16 17:39:56 +0000216 continue;
217
218 // List of consecutive CMOV instructions to be processed.
219 CmovGroups CmovInstGroups;
220
Chandler Carruthe3b35472017-08-19 04:28:20 +0000221 if (!collectCmovCandidates(CurrLoop->getBlocks(), CmovInstGroups))
Amjad Aboud4563c062017-07-16 17:39:56 +0000222 continue;
223
Chandler Carruthe3b35472017-08-19 04:28:20 +0000224 if (!checkForProfitableCmovCandidates(CurrLoop->getBlocks(),
225 CmovInstGroups))
Amjad Aboud4563c062017-07-16 17:39:56 +0000226 continue;
227
228 Changed = true;
229 for (auto &Group : CmovInstGroups)
230 convertCmovInstsToBranches(Group);
231 }
Chandler Carruth93a64552017-08-19 05:01:19 +0000232
Amjad Aboud4563c062017-07-16 17:39:56 +0000233 return Changed;
234}
235
Chandler Carruthe3b35472017-08-19 04:28:20 +0000236bool X86CmovConverterPass::collectCmovCandidates(
Chandler Carruth93a64552017-08-19 05:01:19 +0000237 ArrayRef<MachineBasicBlock *> Blocks, CmovGroups &CmovInstGroups,
238 bool IncludeLoads) {
Amjad Aboud4563c062017-07-16 17:39:56 +0000239 //===--------------------------------------------------------------------===//
240 // Collect all CMOV-group-candidates and add them into CmovInstGroups.
241 //
242 // CMOV-group:
243 // CMOV instructions, in same MBB, that uses same EFLAGS def instruction.
244 //
245 // CMOV-group-candidate:
246 // CMOV-group where all the CMOV instructions are
247 // 1. consecutive.
248 // 2. have same condition code or opposite one.
249 // 3. have only operand registers (X86::CMOVrr).
250 //===--------------------------------------------------------------------===//
251 // List of possible improvement (TODO's):
252 // --------------------------------------
253 // TODO: Add support for X86::CMOVrm instructions.
254 // TODO: Add support for X86::SETcc instructions.
255 // TODO: Add support for CMOV-groups with non consecutive CMOV instructions.
256 //===--------------------------------------------------------------------===//
257
258 // Current processed CMOV-Group.
259 CmovGroup Group;
Chandler Carruthe3b35472017-08-19 04:28:20 +0000260 for (auto *MBB : Blocks) {
Amjad Aboud4563c062017-07-16 17:39:56 +0000261 Group.clear();
262 // Condition code of first CMOV instruction current processed range and its
263 // opposite condition code.
Chandler Carruth93a64552017-08-19 05:01:19 +0000264 X86::CondCode FirstCC, FirstOppCC, MemOpCC;
Amjad Aboud4563c062017-07-16 17:39:56 +0000265 // Indicator of a non CMOVrr instruction in the current processed range.
266 bool FoundNonCMOVInst = false;
267 // Indicator for current processed CMOV-group if it should be skipped.
268 bool SkipGroup = false;
269
270 for (auto &I : *MBB) {
271 X86::CondCode CC = X86::getCondFromCMovOpc(I.getOpcode());
272 // Check if we found a X86::CMOVrr instruction.
Chandler Carruth93a64552017-08-19 05:01:19 +0000273 if (CC != X86::COND_INVALID && (IncludeLoads || !I.mayLoad())) {
Amjad Aboud4563c062017-07-16 17:39:56 +0000274 if (Group.empty()) {
275 // We found first CMOV in the range, reset flags.
276 FirstCC = CC;
277 FirstOppCC = X86::GetOppositeBranchCondition(CC);
Chandler Carruth93a64552017-08-19 05:01:19 +0000278 // Clear out the prior group's memory operand CC.
279 MemOpCC = X86::COND_INVALID;
Amjad Aboud4563c062017-07-16 17:39:56 +0000280 FoundNonCMOVInst = false;
281 SkipGroup = false;
282 }
283 Group.push_back(&I);
284 // Check if it is a non-consecutive CMOV instruction or it has different
285 // condition code than FirstCC or FirstOppCC.
286 if (FoundNonCMOVInst || (CC != FirstCC && CC != FirstOppCC))
287 // Mark the SKipGroup indicator to skip current processed CMOV-Group.
288 SkipGroup = true;
Chandler Carruth93a64552017-08-19 05:01:19 +0000289 if (I.mayLoad()) {
290 if (MemOpCC == X86::COND_INVALID)
291 // The first memory operand CMOV.
292 MemOpCC = CC;
293 else if (CC != MemOpCC)
294 // Can't handle mixed conditions with memory operands.
295 SkipGroup = true;
296 }
Chandler Carruth585bfc82017-09-06 06:28:08 +0000297 // Check if we were relying on zero-extending behavior of the CMOV.
298 if (!SkipGroup &&
299 llvm::any_of(
300 MRI->use_nodbg_instructions(I.defs().begin()->getReg()),
301 [&](MachineInstr &UseI) {
302 return UseI.getOpcode() == X86::SUBREG_TO_REG;
303 }))
304 // FIXME: We should model the cost of using an explicit MOV to handle
305 // the zero-extension rather than just refusing to handle this.
306 SkipGroup = true;
Amjad Aboud4563c062017-07-16 17:39:56 +0000307 continue;
308 }
309 // If Group is empty, keep looking for first CMOV in the range.
310 if (Group.empty())
311 continue;
312
313 // We found a non X86::CMOVrr instruction.
314 FoundNonCMOVInst = true;
315 // Check if this instruction define EFLAGS, to determine end of processed
316 // range, as there would be no more instructions using current EFLAGS def.
317 if (I.definesRegister(X86::EFLAGS)) {
318 // Check if current processed CMOV-group should not be skipped and add
319 // it as a CMOV-group-candidate.
320 if (!SkipGroup)
321 CmovInstGroups.push_back(Group);
322 else
323 ++NumOfSkippedCmovGroups;
324 Group.clear();
325 }
326 }
327 // End of basic block is considered end of range, check if current processed
328 // CMOV-group should not be skipped and add it as a CMOV-group-candidate.
329 if (Group.empty())
330 continue;
331 if (!SkipGroup)
332 CmovInstGroups.push_back(Group);
333 else
334 ++NumOfSkippedCmovGroups;
335 }
336
337 NumOfCmovGroupCandidate += CmovInstGroups.size();
338 return !CmovInstGroups.empty();
339}
340
341/// \returns Depth of CMOV instruction as if it was converted into branch.
342/// \param TrueOpDepth depth cost of CMOV true value operand.
343/// \param FalseOpDepth depth cost of CMOV false value operand.
344static unsigned getDepthOfOptCmov(unsigned TrueOpDepth, unsigned FalseOpDepth) {
345 //===--------------------------------------------------------------------===//
346 // With no info about branch weight, we assume 50% for each value operand.
347 // Thus, depth of optimized CMOV instruction is the rounded up average of
348 // its True-Operand-Value-Depth and False-Operand-Value-Depth.
349 //===--------------------------------------------------------------------===//
350 return (TrueOpDepth + FalseOpDepth + 1) / 2;
351}
352
353bool X86CmovConverterPass::checkForProfitableCmovCandidates(
Chandler Carruthe3b35472017-08-19 04:28:20 +0000354 ArrayRef<MachineBasicBlock *> Blocks, CmovGroups &CmovInstGroups) {
Amjad Aboud4563c062017-07-16 17:39:56 +0000355 struct DepthInfo {
356 /// Depth of original loop.
357 unsigned Depth;
358 /// Depth of optimized loop.
359 unsigned OptDepth;
360 };
361 /// Number of loop iterations to calculate depth for ?!
362 static const unsigned LoopIterations = 2;
363 DenseMap<MachineInstr *, DepthInfo> DepthMap;
364 DepthInfo LoopDepth[LoopIterations] = {{0, 0}, {0, 0}};
365 enum { PhyRegType = 0, VirRegType = 1, RegTypeNum = 2 };
366 /// For each register type maps the register to its last def instruction.
367 DenseMap<unsigned, MachineInstr *> RegDefMaps[RegTypeNum];
368 /// Maps register operand to its def instruction, which can be nullptr if it
369 /// is unknown (e.g., operand is defined outside the loop).
370 DenseMap<MachineOperand *, MachineInstr *> OperandToDefMap;
371
372 // Set depth of unknown instruction (i.e., nullptr) to zero.
373 DepthMap[nullptr] = {0, 0};
374
375 SmallPtrSet<MachineInstr *, 4> CmovInstructions;
376 for (auto &Group : CmovInstGroups)
377 CmovInstructions.insert(Group.begin(), Group.end());
378
379 //===--------------------------------------------------------------------===//
380 // Step 1: Calculate instruction depth and loop depth.
381 // Optimized-Loop:
382 // loop with CMOV-group-candidates converted into branches.
383 //
384 // Instruction-Depth:
385 // instruction latency + max operand depth.
386 // * For CMOV instruction in optimized loop the depth is calculated as:
387 // CMOV latency + getDepthOfOptCmov(True-Op-Depth, False-Op-depth)
388 // TODO: Find a better way to estimate the latency of the branch instruction
389 // rather than using the CMOV latency.
390 //
391 // Loop-Depth:
392 // max instruction depth of all instructions in the loop.
393 // Note: instruction with max depth represents the critical-path in the loop.
394 //
395 // Loop-Depth[i]:
396 // Loop-Depth calculated for first `i` iterations.
397 // Note: it is enough to calculate depth for up to two iterations.
398 //
399 // Depth-Diff[i]:
400 // Number of cycles saved in first 'i` iterations by optimizing the loop.
401 //===--------------------------------------------------------------------===//
402 for (unsigned I = 0; I < LoopIterations; ++I) {
403 DepthInfo &MaxDepth = LoopDepth[I];
Chandler Carruthe3b35472017-08-19 04:28:20 +0000404 for (auto *MBB : Blocks) {
Amjad Aboud4563c062017-07-16 17:39:56 +0000405 // Clear physical registers Def map.
406 RegDefMaps[PhyRegType].clear();
407 for (MachineInstr &MI : *MBB) {
408 unsigned MIDepth = 0;
409 unsigned MIDepthOpt = 0;
410 bool IsCMOV = CmovInstructions.count(&MI);
411 for (auto &MO : MI.uses()) {
412 // Checks for "isUse()" as "uses()" returns also implicit definitions.
413 if (!MO.isReg() || !MO.isUse())
414 continue;
415 unsigned Reg = MO.getReg();
416 auto &RDM = RegDefMaps[TargetRegisterInfo::isVirtualRegister(Reg)];
417 if (MachineInstr *DefMI = RDM.lookup(Reg)) {
418 OperandToDefMap[&MO] = DefMI;
419 DepthInfo Info = DepthMap.lookup(DefMI);
420 MIDepth = std::max(MIDepth, Info.Depth);
421 if (!IsCMOV)
422 MIDepthOpt = std::max(MIDepthOpt, Info.OptDepth);
423 }
424 }
425
426 if (IsCMOV)
427 MIDepthOpt = getDepthOfOptCmov(
428 DepthMap[OperandToDefMap.lookup(&MI.getOperand(1))].OptDepth,
429 DepthMap[OperandToDefMap.lookup(&MI.getOperand(2))].OptDepth);
430
431 // Iterates over all operands to handle implicit definitions as well.
432 for (auto &MO : MI.operands()) {
433 if (!MO.isReg() || !MO.isDef())
434 continue;
435 unsigned Reg = MO.getReg();
436 RegDefMaps[TargetRegisterInfo::isVirtualRegister(Reg)][Reg] = &MI;
437 }
438
439 unsigned Latency = TSchedModel.computeInstrLatency(&MI);
440 DepthMap[&MI] = {MIDepth += Latency, MIDepthOpt += Latency};
441 MaxDepth.Depth = std::max(MaxDepth.Depth, MIDepth);
442 MaxDepth.OptDepth = std::max(MaxDepth.OptDepth, MIDepthOpt);
443 }
444 }
445 }
446
447 unsigned Diff[LoopIterations] = {LoopDepth[0].Depth - LoopDepth[0].OptDepth,
448 LoopDepth[1].Depth - LoopDepth[1].OptDepth};
449
450 //===--------------------------------------------------------------------===//
451 // Step 2: Check if Loop worth to be optimized.
452 // Worth-Optimize-Loop:
453 // case 1: Diff[1] == Diff[0]
454 // Critical-path is iteration independent - there is no dependency
455 // of critical-path instructions on critical-path instructions of
456 // previous iteration.
457 // Thus, it is enough to check gain percent of 1st iteration -
458 // To be conservative, the optimized loop need to have a depth of
459 // 12.5% cycles less than original loop, per iteration.
460 //
461 // case 2: Diff[1] > Diff[0]
462 // Critical-path is iteration dependent - there is dependency of
463 // critical-path instructions on critical-path instructions of
464 // previous iteration.
Amjad Aboud6fa68132017-08-08 12:17:56 +0000465 // Thus, check the gain percent of the 2nd iteration (similar to the
466 // previous case), but it is also required to check the gradient of
467 // the gain - the change in Depth-Diff compared to the change in
468 // Loop-Depth between 1st and 2nd iterations.
Amjad Aboud4563c062017-07-16 17:39:56 +0000469 // To be conservative, the gradient need to be at least 50%.
470 //
Amjad Aboud6fa68132017-08-08 12:17:56 +0000471 // In addition, In order not to optimize loops with very small gain, the
472 // gain (in cycles) after 2nd iteration should not be less than a given
473 // threshold. Thus, the check (Diff[1] >= GainCycleThreshold) must apply.
474 //
Amjad Aboud4563c062017-07-16 17:39:56 +0000475 // If loop is not worth optimizing, remove all CMOV-group-candidates.
476 //===--------------------------------------------------------------------===//
Amjad Aboud6fa68132017-08-08 12:17:56 +0000477 if (Diff[1] < GainCycleThreshold)
478 return false;
479
Amjad Aboud4563c062017-07-16 17:39:56 +0000480 bool WorthOptLoop = false;
481 if (Diff[1] == Diff[0])
482 WorthOptLoop = Diff[0] * 8 >= LoopDepth[0].Depth;
483 else if (Diff[1] > Diff[0])
484 WorthOptLoop =
Amjad Aboud6fa68132017-08-08 12:17:56 +0000485 (Diff[1] - Diff[0]) * 2 >= (LoopDepth[1].Depth - LoopDepth[0].Depth) &&
486 (Diff[1] * 8 >= LoopDepth[1].Depth);
Amjad Aboud4563c062017-07-16 17:39:56 +0000487
488 if (!WorthOptLoop)
489 return false;
490
491 ++NumOfLoopCandidate;
492
493 //===--------------------------------------------------------------------===//
494 // Step 3: Check for each CMOV-group-candidate if it worth to be optimized.
495 // Worth-Optimize-Group:
496 // Iff it worths to optimize all CMOV instructions in the group.
497 //
498 // Worth-Optimize-CMOV:
499 // Predicted branch is faster than CMOV by the difference between depth of
500 // condition operand and depth of taken (predicted) value operand.
501 // To be conservative, the gain of such CMOV transformation should cover at
502 // at least 25% of branch-misprediction-penalty.
503 //===--------------------------------------------------------------------===//
504 unsigned MispredictPenalty = TSchedModel.getMCSchedModel()->MispredictPenalty;
505 CmovGroups TempGroups;
506 std::swap(TempGroups, CmovInstGroups);
507 for (auto &Group : TempGroups) {
508 bool WorthOpGroup = true;
509 for (auto *MI : Group) {
510 // Avoid CMOV instruction which value is used as a pointer to load from.
511 // This is another conservative check to avoid converting CMOV instruction
512 // used with tree-search like algorithm, where the branch is unpredicted.
513 auto UIs = MRI->use_instructions(MI->defs().begin()->getReg());
514 if (UIs.begin() != UIs.end() && ++UIs.begin() == UIs.end()) {
515 unsigned Op = UIs.begin()->getOpcode();
516 if (Op == X86::MOV64rm || Op == X86::MOV32rm) {
517 WorthOpGroup = false;
518 break;
519 }
520 }
521
522 unsigned CondCost =
523 DepthMap[OperandToDefMap.lookup(&MI->getOperand(3))].Depth;
524 unsigned ValCost = getDepthOfOptCmov(
525 DepthMap[OperandToDefMap.lookup(&MI->getOperand(1))].Depth,
526 DepthMap[OperandToDefMap.lookup(&MI->getOperand(2))].Depth);
527 if (ValCost > CondCost || (CondCost - ValCost) * 4 < MispredictPenalty) {
528 WorthOpGroup = false;
529 break;
530 }
531 }
532
533 if (WorthOpGroup)
534 CmovInstGroups.push_back(Group);
535 }
536
537 return !CmovInstGroups.empty();
538}
539
540static bool checkEFLAGSLive(MachineInstr *MI) {
541 if (MI->killsRegister(X86::EFLAGS))
542 return false;
543
544 // The EFLAGS operand of MI might be missing a kill marker.
545 // Figure out whether EFLAGS operand should LIVE after MI instruction.
546 MachineBasicBlock *BB = MI->getParent();
547 MachineBasicBlock::iterator ItrMI = MI;
548
549 // Scan forward through BB for a use/def of EFLAGS.
550 for (auto I = std::next(ItrMI), E = BB->end(); I != E; ++I) {
551 if (I->readsRegister(X86::EFLAGS))
552 return true;
553 if (I->definesRegister(X86::EFLAGS))
554 return false;
555 }
556
557 // We hit the end of the block, check whether EFLAGS is live into a successor.
558 for (auto I = BB->succ_begin(), E = BB->succ_end(); I != E; ++I) {
559 if ((*I)->isLiveIn(X86::EFLAGS))
560 return true;
561 }
562
563 return false;
564}
565
566void X86CmovConverterPass::convertCmovInstsToBranches(
567 SmallVectorImpl<MachineInstr *> &Group) const {
568 assert(!Group.empty() && "No CMOV instructions to convert");
569 ++NumOfOptimizedCmovGroups;
570
571 // To convert a CMOVcc instruction, we actually have to insert the diamond
572 // control-flow pattern. The incoming instruction knows the destination vreg
573 // to set, the condition code register to branch on, the true/false values to
574 // select between, and a branch opcode to use.
575
576 // Before
577 // -----
578 // MBB:
579 // cond = cmp ...
580 // v1 = CMOVge t1, f1, cond
581 // v2 = CMOVlt t2, f2, cond
582 // v3 = CMOVge v1, f3, cond
583 //
584 // After
585 // -----
586 // MBB:
587 // cond = cmp ...
588 // jge %SinkMBB
589 //
590 // FalseMBB:
591 // jmp %SinkMBB
592 //
593 // SinkMBB:
594 // %v1 = phi[%f1, %FalseMBB], [%t1, %MBB]
595 // %v2 = phi[%t2, %FalseMBB], [%f2, %MBB] ; For CMOV with OppCC switch
596 // ; true-value with false-value
597 // %v3 = phi[%f3, %FalseMBB], [%t1, %MBB] ; Phi instruction cannot use
598 // ; previous Phi instruction result
599
600 MachineInstr &MI = *Group.front();
601 MachineInstr *LastCMOV = Group.back();
602 DebugLoc DL = MI.getDebugLoc();
Chandler Carruth93a64552017-08-19 05:01:19 +0000603
Amjad Aboud4563c062017-07-16 17:39:56 +0000604 X86::CondCode CC = X86::CondCode(X86::getCondFromCMovOpc(MI.getOpcode()));
605 X86::CondCode OppCC = X86::GetOppositeBranchCondition(CC);
Chandler Carruth93a64552017-08-19 05:01:19 +0000606 // Potentially swap the condition codes so that any memory operand to a CMOV
607 // is in the *false* position instead of the *true* position. We can invert
608 // any non-memory operand CMOV instructions to cope with this and we ensure
609 // memory operand CMOVs are only included with a single condition code.
610 if (llvm::any_of(Group, [&](MachineInstr *I) {
611 return I->mayLoad() && X86::getCondFromCMovOpc(I->getOpcode()) == CC;
612 }))
613 std::swap(CC, OppCC);
614
Amjad Aboud4563c062017-07-16 17:39:56 +0000615 MachineBasicBlock *MBB = MI.getParent();
616 MachineFunction::iterator It = ++MBB->getIterator();
617 MachineFunction *F = MBB->getParent();
618 const BasicBlock *BB = MBB->getBasicBlock();
619
620 MachineBasicBlock *FalseMBB = F->CreateMachineBasicBlock(BB);
621 MachineBasicBlock *SinkMBB = F->CreateMachineBasicBlock(BB);
622 F->insert(It, FalseMBB);
623 F->insert(It, SinkMBB);
624
625 // If the EFLAGS register isn't dead in the terminator, then claim that it's
626 // live into the sink and copy blocks.
627 if (checkEFLAGSLive(LastCMOV)) {
628 FalseMBB->addLiveIn(X86::EFLAGS);
629 SinkMBB->addLiveIn(X86::EFLAGS);
630 }
631
632 // Transfer the remainder of BB and its successor edges to SinkMBB.
633 SinkMBB->splice(SinkMBB->begin(), MBB,
634 std::next(MachineBasicBlock::iterator(LastCMOV)), MBB->end());
635 SinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
636
637 // Add the false and sink blocks as its successors.
638 MBB->addSuccessor(FalseMBB);
639 MBB->addSuccessor(SinkMBB);
640
641 // Create the conditional branch instruction.
642 BuildMI(MBB, DL, TII->get(X86::GetCondBranchFromCond(CC))).addMBB(SinkMBB);
643
644 // Add the sink block to the false block successors.
645 FalseMBB->addSuccessor(SinkMBB);
646
647 MachineInstrBuilder MIB;
648 MachineBasicBlock::iterator MIItBegin = MachineBasicBlock::iterator(MI);
649 MachineBasicBlock::iterator MIItEnd =
650 std::next(MachineBasicBlock::iterator(LastCMOV));
Chandler Carruth93a64552017-08-19 05:01:19 +0000651 MachineBasicBlock::iterator FalseInsertionPoint = FalseMBB->begin();
Amjad Aboud4563c062017-07-16 17:39:56 +0000652 MachineBasicBlock::iterator SinkInsertionPoint = SinkMBB->begin();
Chandler Carruth93a64552017-08-19 05:01:19 +0000653
654 // First we need to insert an explicit load on the false path for any memory
655 // operand. We also need to potentially do register rewriting here, but it is
656 // simpler as the memory operands are always on the false path so we can
657 // simply take that input, whatever it is.
658 DenseMap<unsigned, unsigned> FalseBBRegRewriteTable;
659 for (MachineBasicBlock::iterator MIIt = MIItBegin; MIIt != MIItEnd;) {
660 auto &MI = *MIIt++;
661 // Skip any CMOVs in this group which don't load from memory.
662 if (!MI.mayLoad()) {
663 // Remember the false-side register input.
Chandler Carruth9ef881e2017-08-19 23:35:50 +0000664 unsigned FalseReg =
Chandler Carruth93a64552017-08-19 05:01:19 +0000665 MI.getOperand(X86::getCondFromCMovOpc(MI.getOpcode()) == CC ? 1 : 2)
666 .getReg();
Chandler Carruth9ef881e2017-08-19 23:35:50 +0000667 // Walk back through any intermediate cmovs referenced.
668 for (;;) {
669 auto FRIt = FalseBBRegRewriteTable.find(FalseReg);
670 if (FRIt == FalseBBRegRewriteTable.end())
671 break;
672 FalseReg = FRIt->second;
673 }
674 FalseBBRegRewriteTable[MI.getOperand(0).getReg()] = FalseReg;
Chandler Carruth93a64552017-08-19 05:01:19 +0000675 continue;
676 }
677
678 // The condition must be the *opposite* of the one we've decided to branch
679 // on as the branch will go *around* the load and the load should happen
680 // when the CMOV condition is false.
681 assert(X86::getCondFromCMovOpc(MI.getOpcode()) == OppCC &&
682 "Can only handle memory-operand cmov instructions with a condition "
683 "opposite to the selected branch direction.");
684
685 // The goal is to rewrite the cmov from:
686 //
687 // MBB:
688 // %A = CMOVcc %B (tied), (mem)
689 //
690 // to
691 //
692 // MBB:
693 // %A = CMOVcc %B (tied), %C
694 // FalseMBB:
695 // %C = MOV (mem)
696 //
697 // Which will allow the next loop to rewrite the CMOV in terms of a PHI:
698 //
699 // MBB:
700 // JMP!cc SinkMBB
701 // FalseMBB:
702 // %C = MOV (mem)
703 // SinkMBB:
704 // %A = PHI [ %C, FalseMBB ], [ %B, MBB]
705
706 // Get a fresh register to use as the destination of the MOV.
707 const TargetRegisterClass *RC = MRI->getRegClass(MI.getOperand(0).getReg());
708 unsigned TmpReg = MRI->createVirtualRegister(RC);
709
710 SmallVector<MachineInstr *, 4> NewMIs;
711 bool Unfolded = TII->unfoldMemoryOperand(*MBB->getParent(), MI, TmpReg,
712 /*UnfoldLoad*/ true,
713 /*UnfoldStore*/ false, NewMIs);
714 (void)Unfolded;
715 assert(Unfolded && "Should never fail to unfold a loading cmov!");
716
717 // Move the new CMOV to just before the old one and reset any impacted
718 // iterator.
719 auto *NewCMOV = NewMIs.pop_back_val();
720 assert(X86::getCondFromCMovOpc(NewCMOV->getOpcode()) == OppCC &&
721 "Last new instruction isn't the expected CMOV!");
722 DEBUG(dbgs() << "\tRewritten cmov: "; NewCMOV->dump());
723 MBB->insert(MachineBasicBlock::iterator(MI), NewCMOV);
724 if (&*MIItBegin == &MI)
725 MIItBegin = MachineBasicBlock::iterator(NewCMOV);
726
727 // Sink whatever instructions were needed to produce the unfolded operand
728 // into the false block.
729 for (auto *NewMI : NewMIs) {
730 DEBUG(dbgs() << "\tRewritten load instr: "; NewMI->dump());
731 FalseMBB->insert(FalseInsertionPoint, NewMI);
732 // Re-map any operands that are from other cmovs to the inputs for this block.
733 for (auto &MOp : NewMI->uses()) {
734 if (!MOp.isReg())
735 continue;
736 auto It = FalseBBRegRewriteTable.find(MOp.getReg());
737 if (It == FalseBBRegRewriteTable.end())
738 continue;
739
740 MOp.setReg(It->second);
741 // This might have been a kill when it referenced the cmov result, but
742 // it won't necessarily be once rewritten.
743 // FIXME: We could potentially improve this by tracking whether the
744 // operand to the cmov was also a kill, and then skipping the PHI node
745 // construction below.
746 MOp.setIsKill(false);
747 }
748 }
749 MBB->erase(MachineBasicBlock::iterator(MI),
750 std::next(MachineBasicBlock::iterator(MI)));
751
752 // Add this PHI to the rewrite table.
753 FalseBBRegRewriteTable[NewCMOV->getOperand(0).getReg()] = TmpReg;
754 }
755
Amjad Aboud4563c062017-07-16 17:39:56 +0000756 // As we are creating the PHIs, we have to be careful if there is more than
757 // one. Later CMOVs may reference the results of earlier CMOVs, but later
758 // PHIs have to reference the individual true/false inputs from earlier PHIs.
759 // That also means that PHI construction must work forward from earlier to
760 // later, and that the code must maintain a mapping from earlier PHI's
761 // destination registers, and the registers that went into the PHI.
762 DenseMap<unsigned, std::pair<unsigned, unsigned>> RegRewriteTable;
763
764 for (MachineBasicBlock::iterator MIIt = MIItBegin; MIIt != MIItEnd; ++MIIt) {
765 unsigned DestReg = MIIt->getOperand(0).getReg();
766 unsigned Op1Reg = MIIt->getOperand(1).getReg();
767 unsigned Op2Reg = MIIt->getOperand(2).getReg();
768
769 // If this CMOV we are processing is the opposite condition from the jump we
770 // generated, then we have to swap the operands for the PHI that is going to
771 // be generated.
772 if (X86::getCondFromCMovOpc(MIIt->getOpcode()) == OppCC)
773 std::swap(Op1Reg, Op2Reg);
774
775 auto Op1Itr = RegRewriteTable.find(Op1Reg);
776 if (Op1Itr != RegRewriteTable.end())
777 Op1Reg = Op1Itr->second.first;
778
779 auto Op2Itr = RegRewriteTable.find(Op2Reg);
780 if (Op2Itr != RegRewriteTable.end())
781 Op2Reg = Op2Itr->second.second;
782
783 // SinkMBB:
784 // %Result = phi [ %FalseValue, FalseMBB ], [ %TrueValue, MBB ]
785 // ...
786 MIB = BuildMI(*SinkMBB, SinkInsertionPoint, DL, TII->get(X86::PHI), DestReg)
787 .addReg(Op1Reg)
788 .addMBB(FalseMBB)
789 .addReg(Op2Reg)
790 .addMBB(MBB);
791 (void)MIB;
792 DEBUG(dbgs() << "\tFrom: "; MIIt->dump());
793 DEBUG(dbgs() << "\tTo: "; MIB->dump());
794
795 // Add this PHI to the rewrite table.
796 RegRewriteTable[DestReg] = std::make_pair(Op1Reg, Op2Reg);
797 }
798
799 // Now remove the CMOV(s).
800 MBB->erase(MIItBegin, MIItEnd);
801}
802
803} // End anonymous namespace.
804
Amjad Aboud8ef85a02017-10-02 21:46:37 +0000805char X86CmovConverterPass::ID = 0;
806
807INITIALIZE_PASS_BEGIN(X86CmovConverterPass, DEBUG_TYPE, "X86 cmov Conversion",
808 false, false)
809INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)
810INITIALIZE_PASS_END(X86CmovConverterPass, DEBUG_TYPE, "X86 cmov Conversion",
811 false, false)
812
Amjad Aboud4563c062017-07-16 17:39:56 +0000813FunctionPass *llvm::createX86CmovConverterPass() {
814 return new X86CmovConverterPass();
815}