blob: dd84cef587e6f90263d39e3327e8f8f47dc19dd3 [file] [log] [blame]
Kyle Butt3232dbb2016-04-08 20:35:01 +00001//===-- TailDuplicator.cpp - Duplicate blocks into predecessors' tails ---===//
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 utility class duplicates basic blocks ending in unconditional branches
11// into the tails of their predecessors.
12//
13//===----------------------------------------------------------------------===//
14
15#include "llvm/CodeGen/TailDuplicator.h"
16#include "llvm/ADT/DenseSet.h"
17#include "llvm/ADT/SetVector.h"
18#include "llvm/ADT/SmallSet.h"
19#include "llvm/ADT/Statistic.h"
20#include "llvm/CodeGen/MachineBranchProbabilityInfo.h"
21#include "llvm/CodeGen/MachineFunctionPass.h"
22#include "llvm/CodeGen/MachineInstrBuilder.h"
23#include "llvm/CodeGen/MachineModuleInfo.h"
24#include "llvm/CodeGen/Passes.h"
25#include "llvm/IR/Function.h"
26#include "llvm/Support/CommandLine.h"
27#include "llvm/Support/Debug.h"
28#include "llvm/Support/ErrorHandling.h"
29#include "llvm/Support/raw_ostream.h"
30using namespace llvm;
31
32#define DEBUG_TYPE "tailduplication"
33
34STATISTIC(NumTails, "Number of tails duplicated");
35STATISTIC(NumTailDups, "Number of tail duplicated blocks");
Geoff Berryf8c29d62016-06-14 19:40:10 +000036STATISTIC(NumTailDupAdded,
37 "Number of instructions added due to tail duplication");
38STATISTIC(NumTailDupRemoved,
39 "Number of instructions removed due to tail duplication");
Kyle Butt3232dbb2016-04-08 20:35:01 +000040STATISTIC(NumDeadBlocks, "Number of dead blocks removed");
41STATISTIC(NumAddedPHIs, "Number of phis added");
42
43// Heuristic for tail duplication.
44static cl::opt<unsigned> TailDuplicateSize(
45 "tail-dup-size",
46 cl::desc("Maximum instructions to consider tail duplicating"), cl::init(2),
47 cl::Hidden);
48
49static cl::opt<bool>
50 TailDupVerify("tail-dup-verify",
51 cl::desc("Verify sanity of PHI instructions during taildup"),
52 cl::init(false), cl::Hidden);
53
54static cl::opt<unsigned> TailDupLimit("tail-dup-limit", cl::init(~0U),
55 cl::Hidden);
56
57namespace llvm {
58
59void TailDuplicator::initMF(MachineFunction &MF, const MachineModuleInfo *MMIin,
60 const MachineBranchProbabilityInfo *MBPIin) {
61 TII = MF.getSubtarget().getInstrInfo();
62 TRI = MF.getSubtarget().getRegisterInfo();
63 MRI = &MF.getRegInfo();
64 MMI = MMIin;
65 MBPI = MBPIin;
66
67 assert(MBPI != nullptr && "Machine Branch Probability Info required");
68
69 PreRegAlloc = MRI->isSSA();
Kyle Butt3232dbb2016-04-08 20:35:01 +000070}
71
72static void VerifyPHIs(MachineFunction &MF, bool CheckExtra) {
73 for (MachineFunction::iterator I = ++MF.begin(), E = MF.end(); I != E; ++I) {
74 MachineBasicBlock *MBB = &*I;
75 SmallSetVector<MachineBasicBlock *, 8> Preds(MBB->pred_begin(),
76 MBB->pred_end());
77 MachineBasicBlock::iterator MI = MBB->begin();
78 while (MI != MBB->end()) {
79 if (!MI->isPHI())
80 break;
Matt Arsenaultb8037a12016-08-16 20:38:05 +000081 for (MachineBasicBlock *PredBB : Preds) {
Kyle Butt3232dbb2016-04-08 20:35:01 +000082 bool Found = false;
83 for (unsigned i = 1, e = MI->getNumOperands(); i != e; i += 2) {
84 MachineBasicBlock *PHIBB = MI->getOperand(i + 1).getMBB();
85 if (PHIBB == PredBB) {
86 Found = true;
87 break;
88 }
89 }
90 if (!Found) {
91 dbgs() << "Malformed PHI in BB#" << MBB->getNumber() << ": " << *MI;
92 dbgs() << " missing input from predecessor BB#"
93 << PredBB->getNumber() << '\n';
94 llvm_unreachable(nullptr);
95 }
96 }
97
98 for (unsigned i = 1, e = MI->getNumOperands(); i != e; i += 2) {
99 MachineBasicBlock *PHIBB = MI->getOperand(i + 1).getMBB();
100 if (CheckExtra && !Preds.count(PHIBB)) {
101 dbgs() << "Warning: malformed PHI in BB#" << MBB->getNumber() << ": "
102 << *MI;
103 dbgs() << " extra input from predecessor BB#" << PHIBB->getNumber()
104 << '\n';
105 llvm_unreachable(nullptr);
106 }
107 if (PHIBB->getNumber() < 0) {
108 dbgs() << "Malformed PHI in BB#" << MBB->getNumber() << ": " << *MI;
109 dbgs() << " non-existing BB#" << PHIBB->getNumber() << '\n';
110 llvm_unreachable(nullptr);
111 }
112 }
113 ++MI;
114 }
115 }
116}
117
118/// Tail duplicate the block and cleanup.
119bool TailDuplicator::tailDuplicateAndUpdate(MachineFunction &MF, bool IsSimple,
120 MachineBasicBlock *MBB) {
121 // Save the successors list.
122 SmallSetVector<MachineBasicBlock *, 8> Succs(MBB->succ_begin(),
123 MBB->succ_end());
124
125 SmallVector<MachineBasicBlock *, 8> TDBBs;
126 SmallVector<MachineInstr *, 16> Copies;
127 if (!tailDuplicate(MF, IsSimple, MBB, TDBBs, Copies))
128 return false;
129
130 ++NumTails;
131
132 SmallVector<MachineInstr *, 8> NewPHIs;
133 MachineSSAUpdater SSAUpdate(MF, &NewPHIs);
134
135 // TailBB's immediate successors are now successors of those predecessors
136 // which duplicated TailBB. Add the predecessors as sources to the PHI
137 // instructions.
138 bool isDead = MBB->pred_empty() && !MBB->hasAddressTaken();
139 if (PreRegAlloc)
140 updateSuccessorsPHIs(MBB, isDead, TDBBs, Succs);
141
142 // If it is dead, remove it.
143 if (isDead) {
Geoff Berryf8c29d62016-06-14 19:40:10 +0000144 NumTailDupRemoved += MBB->size();
Kyle Butt3232dbb2016-04-08 20:35:01 +0000145 removeDeadBlock(MBB);
146 ++NumDeadBlocks;
147 }
148
149 // Update SSA form.
150 if (!SSAUpdateVRs.empty()) {
151 for (unsigned i = 0, e = SSAUpdateVRs.size(); i != e; ++i) {
152 unsigned VReg = SSAUpdateVRs[i];
153 SSAUpdate.Initialize(VReg);
154
155 // If the original definition is still around, add it as an available
156 // value.
157 MachineInstr *DefMI = MRI->getVRegDef(VReg);
158 MachineBasicBlock *DefBB = nullptr;
159 if (DefMI) {
160 DefBB = DefMI->getParent();
161 SSAUpdate.AddAvailableValue(DefBB, VReg);
162 }
163
164 // Add the new vregs as available values.
165 DenseMap<unsigned, AvailableValsTy>::iterator LI =
166 SSAUpdateVals.find(VReg);
167 for (unsigned j = 0, ee = LI->second.size(); j != ee; ++j) {
168 MachineBasicBlock *SrcBB = LI->second[j].first;
169 unsigned SrcReg = LI->second[j].second;
170 SSAUpdate.AddAvailableValue(SrcBB, SrcReg);
171 }
172
173 // Rewrite uses that are outside of the original def's block.
174 MachineRegisterInfo::use_iterator UI = MRI->use_begin(VReg);
175 while (UI != MRI->use_end()) {
176 MachineOperand &UseMO = *UI;
177 MachineInstr *UseMI = UseMO.getParent();
178 ++UI;
179 if (UseMI->isDebugValue()) {
180 // SSAUpdate can replace the use with an undef. That creates
181 // a debug instruction that is a kill.
182 // FIXME: Should it SSAUpdate job to delete debug instructions
183 // instead of replacing the use with undef?
184 UseMI->eraseFromParent();
185 continue;
186 }
187 if (UseMI->getParent() == DefBB && !UseMI->isPHI())
188 continue;
189 SSAUpdate.RewriteUse(UseMO);
190 }
191 }
192
193 SSAUpdateVRs.clear();
194 SSAUpdateVals.clear();
195 }
196
197 // Eliminate some of the copies inserted by tail duplication to maintain
198 // SSA form.
199 for (unsigned i = 0, e = Copies.size(); i != e; ++i) {
200 MachineInstr *Copy = Copies[i];
201 if (!Copy->isCopy())
202 continue;
203 unsigned Dst = Copy->getOperand(0).getReg();
204 unsigned Src = Copy->getOperand(1).getReg();
205 if (MRI->hasOneNonDBGUse(Src) &&
206 MRI->constrainRegClass(Src, MRI->getRegClass(Dst))) {
207 // Copy is the only use. Do trivial copy propagation here.
208 MRI->replaceRegWith(Dst, Src);
209 Copy->eraseFromParent();
210 }
211 }
212
213 if (NewPHIs.size())
214 NumAddedPHIs += NewPHIs.size();
215
216 return true;
217}
218
219/// Look for small blocks that are unconditionally branched to and do not fall
220/// through. Tail-duplicate their instructions into their predecessors to
221/// eliminate (dynamic) branches.
222bool TailDuplicator::tailDuplicateBlocks(MachineFunction &MF) {
223 bool MadeChange = false;
224
225 if (PreRegAlloc && TailDupVerify) {
226 DEBUG(dbgs() << "\n*** Before tail-duplicating\n");
227 VerifyPHIs(MF, true);
228 }
229
230 for (MachineFunction::iterator I = ++MF.begin(), E = MF.end(); I != E;) {
231 MachineBasicBlock *MBB = &*I++;
232
233 if (NumTails == TailDupLimit)
234 break;
235
236 bool IsSimple = isSimpleBB(MBB);
237
238 if (!shouldTailDuplicate(MF, IsSimple, *MBB))
239 continue;
240
241 MadeChange |= tailDuplicateAndUpdate(MF, IsSimple, MBB);
242 }
243
244 if (PreRegAlloc && TailDupVerify)
245 VerifyPHIs(MF, false);
246
247 return MadeChange;
248}
249
250static bool isDefLiveOut(unsigned Reg, MachineBasicBlock *BB,
251 const MachineRegisterInfo *MRI) {
252 for (MachineInstr &UseMI : MRI->use_instructions(Reg)) {
253 if (UseMI.isDebugValue())
254 continue;
255 if (UseMI.getParent() != BB)
256 return true;
257 }
258 return false;
259}
260
261static unsigned getPHISrcRegOpIdx(MachineInstr *MI, MachineBasicBlock *SrcBB) {
262 for (unsigned i = 1, e = MI->getNumOperands(); i != e; i += 2)
263 if (MI->getOperand(i + 1).getMBB() == SrcBB)
264 return i;
265 return 0;
266}
267
268// Remember which registers are used by phis in this block. This is
269// used to determine which registers are liveout while modifying the
270// block (which is why we need to copy the information).
271static void getRegsUsedByPHIs(const MachineBasicBlock &BB,
272 DenseSet<unsigned> *UsedByPhi) {
273 for (const auto &MI : BB) {
274 if (!MI.isPHI())
275 break;
276 for (unsigned i = 1, e = MI.getNumOperands(); i != e; i += 2) {
277 unsigned SrcReg = MI.getOperand(i).getReg();
278 UsedByPhi->insert(SrcReg);
279 }
280 }
281}
282
283/// Add a definition and source virtual registers pair for SSA update.
284void TailDuplicator::addSSAUpdateEntry(unsigned OrigReg, unsigned NewReg,
285 MachineBasicBlock *BB) {
286 DenseMap<unsigned, AvailableValsTy>::iterator LI =
287 SSAUpdateVals.find(OrigReg);
288 if (LI != SSAUpdateVals.end())
289 LI->second.push_back(std::make_pair(BB, NewReg));
290 else {
291 AvailableValsTy Vals;
292 Vals.push_back(std::make_pair(BB, NewReg));
293 SSAUpdateVals.insert(std::make_pair(OrigReg, Vals));
294 SSAUpdateVRs.push_back(OrigReg);
295 }
296}
297
298/// Process PHI node in TailBB by turning it into a copy in PredBB. Remember the
299/// source register that's contributed by PredBB and update SSA update map.
300void TailDuplicator::processPHI(
301 MachineInstr *MI, MachineBasicBlock *TailBB, MachineBasicBlock *PredBB,
Krzysztof Parzyszek4773f642016-04-26 18:36:34 +0000302 DenseMap<unsigned, RegSubRegPair> &LocalVRMap,
303 SmallVectorImpl<std::pair<unsigned, RegSubRegPair>> &Copies,
Kyle Butt3232dbb2016-04-08 20:35:01 +0000304 const DenseSet<unsigned> &RegsUsedByPhi, bool Remove) {
305 unsigned DefReg = MI->getOperand(0).getReg();
306 unsigned SrcOpIdx = getPHISrcRegOpIdx(MI, PredBB);
307 assert(SrcOpIdx && "Unable to find matching PHI source?");
308 unsigned SrcReg = MI->getOperand(SrcOpIdx).getReg();
Krzysztof Parzyszek4773f642016-04-26 18:36:34 +0000309 unsigned SrcSubReg = MI->getOperand(SrcOpIdx).getSubReg();
Kyle Butt3232dbb2016-04-08 20:35:01 +0000310 const TargetRegisterClass *RC = MRI->getRegClass(DefReg);
Krzysztof Parzyszek4773f642016-04-26 18:36:34 +0000311 LocalVRMap.insert(std::make_pair(DefReg, RegSubRegPair(SrcReg, SrcSubReg)));
Kyle Butt3232dbb2016-04-08 20:35:01 +0000312
313 // Insert a copy from source to the end of the block. The def register is the
314 // available value liveout of the block.
315 unsigned NewDef = MRI->createVirtualRegister(RC);
Krzysztof Parzyszek4773f642016-04-26 18:36:34 +0000316 Copies.push_back(std::make_pair(NewDef, RegSubRegPair(SrcReg, SrcSubReg)));
Kyle Butt3232dbb2016-04-08 20:35:01 +0000317 if (isDefLiveOut(DefReg, TailBB, MRI) || RegsUsedByPhi.count(DefReg))
318 addSSAUpdateEntry(DefReg, NewDef, PredBB);
319
320 if (!Remove)
321 return;
322
323 // Remove PredBB from the PHI node.
324 MI->RemoveOperand(SrcOpIdx + 1);
325 MI->RemoveOperand(SrcOpIdx);
326 if (MI->getNumOperands() == 1)
327 MI->eraseFromParent();
328}
329
330/// Duplicate a TailBB instruction to PredBB and update
331/// the source operands due to earlier PHI translation.
332void TailDuplicator::duplicateInstruction(
333 MachineInstr *MI, MachineBasicBlock *TailBB, MachineBasicBlock *PredBB,
Krzysztof Parzyszek4773f642016-04-26 18:36:34 +0000334 MachineFunction &MF,
335 DenseMap<unsigned, RegSubRegPair> &LocalVRMap,
Kyle Butt3232dbb2016-04-08 20:35:01 +0000336 const DenseSet<unsigned> &UsedByPhi) {
Duncan P. N. Exon Smith9cfc75c2016-06-30 00:01:54 +0000337 MachineInstr *NewMI = TII->duplicate(*MI, MF);
Kyle Butt3232dbb2016-04-08 20:35:01 +0000338 if (PreRegAlloc) {
339 for (unsigned i = 0, e = NewMI->getNumOperands(); i != e; ++i) {
340 MachineOperand &MO = NewMI->getOperand(i);
341 if (!MO.isReg())
342 continue;
343 unsigned Reg = MO.getReg();
344 if (!TargetRegisterInfo::isVirtualRegister(Reg))
345 continue;
346 if (MO.isDef()) {
347 const TargetRegisterClass *RC = MRI->getRegClass(Reg);
348 unsigned NewReg = MRI->createVirtualRegister(RC);
349 MO.setReg(NewReg);
Krzysztof Parzyszek4773f642016-04-26 18:36:34 +0000350 LocalVRMap.insert(std::make_pair(Reg, RegSubRegPair(NewReg, 0)));
Kyle Butt3232dbb2016-04-08 20:35:01 +0000351 if (isDefLiveOut(Reg, TailBB, MRI) || UsedByPhi.count(Reg))
352 addSSAUpdateEntry(Reg, NewReg, PredBB);
353 } else {
Krzysztof Parzyszek4773f642016-04-26 18:36:34 +0000354 auto VI = LocalVRMap.find(Reg);
Kyle Butt3232dbb2016-04-08 20:35:01 +0000355 if (VI != LocalVRMap.end()) {
Krzysztof Parzyszek4773f642016-04-26 18:36:34 +0000356 // Need to make sure that the register class of the mapped register
357 // will satisfy the constraints of the class of the register being
358 // replaced.
359 auto *OrigRC = MRI->getRegClass(Reg);
360 auto *MappedRC = MRI->getRegClass(VI->second.Reg);
361 const TargetRegisterClass *ConstrRC;
362 if (VI->second.SubReg != 0) {
363 ConstrRC = TRI->getMatchingSuperRegClass(MappedRC, OrigRC,
364 VI->second.SubReg);
365 if (ConstrRC) {
366 // The actual constraining (as in "find appropriate new class")
367 // is done by getMatchingSuperRegClass, so now we only need to
368 // change the class of the mapped register.
369 MRI->setRegClass(VI->second.Reg, ConstrRC);
370 }
371 } else {
372 // For mapped registers that do not have sub-registers, simply
373 // restrict their class to match the original one.
374 ConstrRC = MRI->constrainRegClass(VI->second.Reg, OrigRC);
375 }
376
377 if (ConstrRC) {
378 // If the class constraining succeeded, we can simply replace
379 // the old register with the mapped one.
380 MO.setReg(VI->second.Reg);
381 // We have Reg -> VI.Reg:VI.SubReg, so if Reg is used with a
382 // sub-register, we need to compose the sub-register indices.
383 MO.setSubReg(TRI->composeSubRegIndices(MO.getSubReg(),
384 VI->second.SubReg));
385 } else {
386 // The direct replacement is not possible, due to failing register
387 // class constraints. An explicit COPY is necessary. Create one
388 // that can be reused
389 auto *NewRC = MI->getRegClassConstraint(i, TII, TRI);
390 if (NewRC == nullptr)
391 NewRC = OrigRC;
392 unsigned NewReg = MRI->createVirtualRegister(NewRC);
393 BuildMI(*PredBB, MI, MI->getDebugLoc(),
394 TII->get(TargetOpcode::COPY), NewReg)
395 .addReg(VI->second.Reg, 0, VI->second.SubReg);
396 LocalVRMap.erase(VI);
397 LocalVRMap.insert(std::make_pair(Reg, RegSubRegPair(NewReg, 0)));
398 MO.setReg(NewReg);
399 // The composed VI.Reg:VI.SubReg is replaced with NewReg, which
400 // is equivalent to the whole register Reg. Hence, Reg:subreg
401 // is same as NewReg:subreg, so keep the sub-register index
402 // unchanged.
403 }
Kyle Butt3232dbb2016-04-08 20:35:01 +0000404 // Clear any kill flags from this operand. The new register could
405 // have uses after this one, so kills are not valid here.
406 MO.setIsKill(false);
Kyle Butt3232dbb2016-04-08 20:35:01 +0000407 }
408 }
409 }
410 }
411 PredBB->insert(PredBB->instr_end(), NewMI);
412}
413
414/// After FromBB is tail duplicated into its predecessor blocks, the successors
415/// have gained new predecessors. Update the PHI instructions in them
416/// accordingly.
417void TailDuplicator::updateSuccessorsPHIs(
418 MachineBasicBlock *FromBB, bool isDead,
419 SmallVectorImpl<MachineBasicBlock *> &TDBBs,
420 SmallSetVector<MachineBasicBlock *, 8> &Succs) {
Matt Arsenaultb8037a12016-08-16 20:38:05 +0000421 for (MachineBasicBlock *SuccBB : Succs) {
422 for (MachineInstr &MI : *SuccBB) {
423 if (!MI.isPHI())
Kyle Butt3232dbb2016-04-08 20:35:01 +0000424 break;
Matt Arsenaultb8037a12016-08-16 20:38:05 +0000425 MachineInstrBuilder MIB(*FromBB->getParent(), MI);
Kyle Butt3232dbb2016-04-08 20:35:01 +0000426 unsigned Idx = 0;
Matt Arsenaultb8037a12016-08-16 20:38:05 +0000427 for (unsigned i = 1, e = MI.getNumOperands(); i != e; i += 2) {
428 MachineOperand &MO = MI.getOperand(i + 1);
Kyle Butt3232dbb2016-04-08 20:35:01 +0000429 if (MO.getMBB() == FromBB) {
430 Idx = i;
431 break;
432 }
433 }
434
435 assert(Idx != 0);
Matt Arsenaultb8037a12016-08-16 20:38:05 +0000436 MachineOperand &MO0 = MI.getOperand(Idx);
Kyle Butt3232dbb2016-04-08 20:35:01 +0000437 unsigned Reg = MO0.getReg();
438 if (isDead) {
439 // Folded into the previous BB.
440 // There could be duplicate phi source entries. FIXME: Should sdisel
441 // or earlier pass fixed this?
Matt Arsenaultb8037a12016-08-16 20:38:05 +0000442 for (unsigned i = MI.getNumOperands() - 2; i != Idx; i -= 2) {
443 MachineOperand &MO = MI.getOperand(i + 1);
Kyle Butt3232dbb2016-04-08 20:35:01 +0000444 if (MO.getMBB() == FromBB) {
Matt Arsenaultb8037a12016-08-16 20:38:05 +0000445 MI.RemoveOperand(i + 1);
446 MI.RemoveOperand(i);
Kyle Butt3232dbb2016-04-08 20:35:01 +0000447 }
448 }
449 } else
450 Idx = 0;
451
452 // If Idx is set, the operands at Idx and Idx+1 must be removed.
453 // We reuse the location to avoid expensive RemoveOperand calls.
454
455 DenseMap<unsigned, AvailableValsTy>::iterator LI =
456 SSAUpdateVals.find(Reg);
457 if (LI != SSAUpdateVals.end()) {
458 // This register is defined in the tail block.
459 for (unsigned j = 0, ee = LI->second.size(); j != ee; ++j) {
460 MachineBasicBlock *SrcBB = LI->second[j].first;
461 // If we didn't duplicate a bb into a particular predecessor, we
462 // might still have added an entry to SSAUpdateVals to correcly
463 // recompute SSA. If that case, avoid adding a dummy extra argument
464 // this PHI.
465 if (!SrcBB->isSuccessor(SuccBB))
466 continue;
467
468 unsigned SrcReg = LI->second[j].second;
469 if (Idx != 0) {
Matt Arsenaultb8037a12016-08-16 20:38:05 +0000470 MI.getOperand(Idx).setReg(SrcReg);
471 MI.getOperand(Idx + 1).setMBB(SrcBB);
Kyle Butt3232dbb2016-04-08 20:35:01 +0000472 Idx = 0;
473 } else {
474 MIB.addReg(SrcReg).addMBB(SrcBB);
475 }
476 }
477 } else {
478 // Live in tail block, must also be live in predecessors.
479 for (unsigned j = 0, ee = TDBBs.size(); j != ee; ++j) {
480 MachineBasicBlock *SrcBB = TDBBs[j];
481 if (Idx != 0) {
Matt Arsenaultb8037a12016-08-16 20:38:05 +0000482 MI.getOperand(Idx).setReg(Reg);
483 MI.getOperand(Idx + 1).setMBB(SrcBB);
Kyle Butt3232dbb2016-04-08 20:35:01 +0000484 Idx = 0;
485 } else {
486 MIB.addReg(Reg).addMBB(SrcBB);
487 }
488 }
489 }
490 if (Idx != 0) {
Matt Arsenaultb8037a12016-08-16 20:38:05 +0000491 MI.RemoveOperand(Idx + 1);
492 MI.RemoveOperand(Idx);
Kyle Butt3232dbb2016-04-08 20:35:01 +0000493 }
494 }
495 }
496}
497
498/// Determine if it is profitable to duplicate this block.
499bool TailDuplicator::shouldTailDuplicate(const MachineFunction &MF,
500 bool IsSimple,
501 MachineBasicBlock &TailBB) {
502 // Only duplicate blocks that end with unconditional branches.
503 if (TailBB.canFallThrough())
504 return false;
505
506 // Don't try to tail-duplicate single-block loops.
507 if (TailBB.isSuccessor(&TailBB))
508 return false;
509
510 // Set the limit on the cost to duplicate. When optimizing for size,
511 // duplicate only one, because one branch instruction can be eliminated to
512 // compensate for the duplication.
513 unsigned MaxDuplicateCount;
514 if (TailDuplicateSize.getNumOccurrences() == 0 &&
515 // FIXME: Use Function::optForSize().
516 MF.getFunction()->hasFnAttribute(Attribute::OptimizeForSize))
517 MaxDuplicateCount = 1;
518 else
519 MaxDuplicateCount = TailDuplicateSize;
520
Kyle Butt07d61422016-08-16 22:56:14 +0000521 // If the block to be duplicated ends in an unanalyzable fallthrough, don't
522 // duplicate it.
523 // A similar check is necessary in MachineBlockPlacement to make sure pairs of
524 // blocks with unanalyzable fallthrough get layed out contiguously.
525 MachineBasicBlock *PredTBB = nullptr, *PredFBB = nullptr;
526 SmallVector<MachineOperand, 4> PredCond;
527 if (TII->analyzeBranch(TailBB, PredTBB, PredFBB, PredCond, true)
528 && TailBB.canFallThrough())
529 return false;
530
Kyle Butt3232dbb2016-04-08 20:35:01 +0000531 // If the target has hardware branch prediction that can handle indirect
532 // branches, duplicating them can often make them predictable when there
533 // are common paths through the code. The limit needs to be high enough
534 // to allow undoing the effects of tail merging and other optimizations
535 // that rearrange the predecessors of the indirect branch.
536
537 bool HasIndirectbr = false;
538 if (!TailBB.empty())
539 HasIndirectbr = TailBB.back().isIndirectBranch();
540
541 if (HasIndirectbr && PreRegAlloc)
542 MaxDuplicateCount = 20;
543
544 // Check the instructions in the block to determine whether tail-duplication
545 // is invalid or unlikely to be profitable.
546 unsigned InstrCount = 0;
547 for (MachineInstr &MI : TailBB) {
548 // Non-duplicable things shouldn't be tail-duplicated.
549 if (MI.isNotDuplicable())
550 return false;
551
552 // Convergent instructions can be duplicated only if doing so doesn't add
553 // new control dependencies, which is what we're going to do here.
554 if (MI.isConvergent())
555 return false;
556
557 // Do not duplicate 'return' instructions if this is a pre-regalloc run.
558 // A return may expand into a lot more instructions (e.g. reload of callee
559 // saved registers) after PEI.
560 if (PreRegAlloc && MI.isReturn())
561 return false;
562
563 // Avoid duplicating calls before register allocation. Calls presents a
564 // barrier to register allocation so duplicating them may end up increasing
565 // spills.
566 if (PreRegAlloc && MI.isCall())
567 return false;
568
569 if (!MI.isPHI() && !MI.isDebugValue())
570 InstrCount += 1;
571
572 if (InstrCount > MaxDuplicateCount)
573 return false;
574 }
575
576 // Check if any of the successors of TailBB has a PHI node in which the
577 // value corresponding to TailBB uses a subregister.
578 // If a phi node uses a register paired with a subregister, the actual
579 // "value type" of the phi may differ from the type of the register without
580 // any subregisters. Due to a bug, tail duplication may add a new operand
581 // without a necessary subregister, producing an invalid code. This is
582 // demonstrated by test/CodeGen/Hexagon/tail-dup-subreg-abort.ll.
583 // Disable tail duplication for this case for now, until the problem is
584 // fixed.
585 for (auto SB : TailBB.successors()) {
586 for (auto &I : *SB) {
587 if (!I.isPHI())
588 break;
589 unsigned Idx = getPHISrcRegOpIdx(&I, &TailBB);
590 assert(Idx != 0);
591 MachineOperand &PU = I.getOperand(Idx);
592 if (PU.getSubReg() != 0)
593 return false;
594 }
595 }
596
597 if (HasIndirectbr && PreRegAlloc)
598 return true;
599
600 if (IsSimple)
601 return true;
602
603 if (!PreRegAlloc)
604 return true;
605
606 return canCompletelyDuplicateBB(TailBB);
607}
608
609/// True if this BB has only one unconditional jump.
610bool TailDuplicator::isSimpleBB(MachineBasicBlock *TailBB) {
611 if (TailBB->succ_size() != 1)
612 return false;
613 if (TailBB->pred_empty())
614 return false;
615 MachineBasicBlock::iterator I = TailBB->getFirstNonDebugInstr();
616 if (I == TailBB->end())
617 return true;
618 return I->isUnconditionalBranch();
619}
620
621static bool bothUsedInPHI(const MachineBasicBlock &A,
Benjamin Kramerbdc49562016-06-12 15:39:02 +0000622 const SmallPtrSet<MachineBasicBlock *, 8> &SuccsB) {
Kyle Butt3232dbb2016-04-08 20:35:01 +0000623 for (MachineBasicBlock *BB : A.successors())
624 if (SuccsB.count(BB) && !BB->empty() && BB->begin()->isPHI())
625 return true;
626
627 return false;
628}
629
630bool TailDuplicator::canCompletelyDuplicateBB(MachineBasicBlock &BB) {
631 for (MachineBasicBlock *PredBB : BB.predecessors()) {
632 if (PredBB->succ_size() > 1)
633 return false;
634
635 MachineBasicBlock *PredTBB = nullptr, *PredFBB = nullptr;
636 SmallVector<MachineOperand, 4> PredCond;
Jacques Pienaar71c30a12016-07-15 14:41:04 +0000637 if (TII->analyzeBranch(*PredBB, PredTBB, PredFBB, PredCond, true))
Kyle Butt3232dbb2016-04-08 20:35:01 +0000638 return false;
639
640 if (!PredCond.empty())
641 return false;
642 }
643 return true;
644}
645
646bool TailDuplicator::duplicateSimpleBB(
647 MachineBasicBlock *TailBB, SmallVectorImpl<MachineBasicBlock *> &TDBBs,
648 const DenseSet<unsigned> &UsedByPhi,
649 SmallVectorImpl<MachineInstr *> &Copies) {
650 SmallPtrSet<MachineBasicBlock *, 8> Succs(TailBB->succ_begin(),
651 TailBB->succ_end());
652 SmallVector<MachineBasicBlock *, 8> Preds(TailBB->pred_begin(),
653 TailBB->pred_end());
654 bool Changed = false;
Matt Arsenaultb8037a12016-08-16 20:38:05 +0000655 for (MachineBasicBlock *PredBB : Preds) {
Kyle Butt3232dbb2016-04-08 20:35:01 +0000656 if (PredBB->hasEHPadSuccessor())
657 continue;
658
659 if (bothUsedInPHI(*PredBB, Succs))
660 continue;
661
662 MachineBasicBlock *PredTBB = nullptr, *PredFBB = nullptr;
663 SmallVector<MachineOperand, 4> PredCond;
Jacques Pienaar71c30a12016-07-15 14:41:04 +0000664 if (TII->analyzeBranch(*PredBB, PredTBB, PredFBB, PredCond, true))
Kyle Butt3232dbb2016-04-08 20:35:01 +0000665 continue;
666
667 Changed = true;
668 DEBUG(dbgs() << "\nTail-duplicating into PredBB: " << *PredBB
669 << "From simple Succ: " << *TailBB);
670
671 MachineBasicBlock *NewTarget = *TailBB->succ_begin();
672 MachineBasicBlock *NextBB = &*std::next(PredBB->getIterator());
673
674 // Make PredFBB explicit.
675 if (PredCond.empty())
676 PredFBB = PredTBB;
677
678 // Make fall through explicit.
679 if (!PredTBB)
680 PredTBB = NextBB;
681 if (!PredFBB)
682 PredFBB = NextBB;
683
684 // Redirect
685 if (PredFBB == TailBB)
686 PredFBB = NewTarget;
687 if (PredTBB == TailBB)
688 PredTBB = NewTarget;
689
690 // Make the branch unconditional if possible
691 if (PredTBB == PredFBB) {
692 PredCond.clear();
693 PredFBB = nullptr;
694 }
695
696 // Avoid adding fall through branches.
697 if (PredFBB == NextBB)
698 PredFBB = nullptr;
699 if (PredTBB == NextBB && PredFBB == nullptr)
700 PredTBB = nullptr;
701
702 TII->RemoveBranch(*PredBB);
703
704 if (!PredBB->isSuccessor(NewTarget))
705 PredBB->replaceSuccessor(TailBB, NewTarget);
706 else {
707 PredBB->removeSuccessor(TailBB, true);
708 assert(PredBB->succ_size() <= 1);
709 }
710
711 if (PredTBB)
712 TII->InsertBranch(*PredBB, PredTBB, PredFBB, PredCond, DebugLoc());
713
714 TDBBs.push_back(PredBB);
715 }
716 return Changed;
717}
718
Kyle Butt9e52c062016-07-19 23:54:21 +0000719bool TailDuplicator::canTailDuplicate(MachineBasicBlock *TailBB,
720 MachineBasicBlock *PredBB) {
721 // EH edges are ignored by AnalyzeBranch.
722 if (PredBB->succ_size() > 1)
723 return false;
724
725 MachineBasicBlock *PredTBB, *PredFBB;
726 SmallVector<MachineOperand, 4> PredCond;
727 if (TII->analyzeBranch(*PredBB, PredTBB, PredFBB, PredCond, true))
728 return false;
729 if (!PredCond.empty())
730 return false;
731 return true;
732}
733
Kyle Butt3232dbb2016-04-08 20:35:01 +0000734/// If it is profitable, duplicate TailBB's contents in each
735/// of its predecessors.
736bool TailDuplicator::tailDuplicate(MachineFunction &MF, bool IsSimple,
737 MachineBasicBlock *TailBB,
738 SmallVectorImpl<MachineBasicBlock *> &TDBBs,
739 SmallVectorImpl<MachineInstr *> &Copies) {
740 DEBUG(dbgs() << "\n*** Tail-duplicating BB#" << TailBB->getNumber() << '\n');
741
742 DenseSet<unsigned> UsedByPhi;
743 getRegsUsedByPHIs(*TailBB, &UsedByPhi);
744
745 if (IsSimple)
746 return duplicateSimpleBB(TailBB, TDBBs, UsedByPhi, Copies);
747
748 // Iterate through all the unique predecessors and tail-duplicate this
749 // block into them, if possible. Copying the list ahead of time also
750 // avoids trouble with the predecessor list reallocating.
751 bool Changed = false;
752 SmallSetVector<MachineBasicBlock *, 8> Preds(TailBB->pred_begin(),
753 TailBB->pred_end());
Matt Arsenaultb8037a12016-08-16 20:38:05 +0000754 for (MachineBasicBlock *PredBB : Preds) {
Kyle Butt3232dbb2016-04-08 20:35:01 +0000755 assert(TailBB != PredBB &&
756 "Single-block loop should have been rejected earlier!");
Kyle Butt9e52c062016-07-19 23:54:21 +0000757
758 if (!canTailDuplicate(TailBB, PredBB))
Kyle Butt3232dbb2016-04-08 20:35:01 +0000759 continue;
760
Kyle Butt3232dbb2016-04-08 20:35:01 +0000761 // Don't duplicate into a fall-through predecessor (at least for now).
762 if (PredBB->isLayoutSuccessor(TailBB) && PredBB->canFallThrough())
763 continue;
764
765 DEBUG(dbgs() << "\nTail-duplicating into PredBB: " << *PredBB
766 << "From Succ: " << *TailBB);
767
768 TDBBs.push_back(PredBB);
769
770 // Remove PredBB's unconditional branch.
771 TII->RemoveBranch(*PredBB);
772
Kyle Butt3232dbb2016-04-08 20:35:01 +0000773 // Clone the contents of TailBB into PredBB.
Krzysztof Parzyszek4773f642016-04-26 18:36:34 +0000774 DenseMap<unsigned, RegSubRegPair> LocalVRMap;
775 SmallVector<std::pair<unsigned, RegSubRegPair>, 4> CopyInfos;
Kyle Butt3232dbb2016-04-08 20:35:01 +0000776 // Use instr_iterator here to properly handle bundles, e.g.
777 // ARM Thumb2 IT block.
778 MachineBasicBlock::instr_iterator I = TailBB->instr_begin();
779 while (I != TailBB->instr_end()) {
780 MachineInstr *MI = &*I;
781 ++I;
782 if (MI->isPHI()) {
783 // Replace the uses of the def of the PHI with the register coming
784 // from PredBB.
785 processPHI(MI, TailBB, PredBB, LocalVRMap, CopyInfos, UsedByPhi, true);
786 } else {
787 // Replace def of virtual registers with new registers, and update
788 // uses with PHI source register or the new registers.
789 duplicateInstruction(MI, TailBB, PredBB, MF, LocalVRMap, UsedByPhi);
790 }
791 }
Krzysztof Parzyszek4773f642016-04-26 18:36:34 +0000792 appendCopies(PredBB, CopyInfos, Copies);
Kyle Butt3232dbb2016-04-08 20:35:01 +0000793
794 // Simplify
Kyle Butt9e52c062016-07-19 23:54:21 +0000795 MachineBasicBlock *PredTBB, *PredFBB;
796 SmallVector<MachineOperand, 4> PredCond;
Jacques Pienaar71c30a12016-07-15 14:41:04 +0000797 TII->analyzeBranch(*PredBB, PredTBB, PredFBB, PredCond, true);
Kyle Butt3232dbb2016-04-08 20:35:01 +0000798
Geoff Berryf8c29d62016-06-14 19:40:10 +0000799 NumTailDupAdded += TailBB->size() - 1; // subtract one for removed branch
Kyle Butt3232dbb2016-04-08 20:35:01 +0000800
801 // Update the CFG.
802 PredBB->removeSuccessor(PredBB->succ_begin());
803 assert(PredBB->succ_empty() &&
804 "TailDuplicate called on block with multiple successors!");
Matt Arsenaultb8037a12016-08-16 20:38:05 +0000805 for (MachineBasicBlock *Succ : TailBB->successors())
806 PredBB->addSuccessor(Succ, MBPI->getEdgeProbability(TailBB, Succ));
Kyle Butt3232dbb2016-04-08 20:35:01 +0000807
808 Changed = true;
809 ++NumTailDups;
810 }
811
812 // If TailBB was duplicated into all its predecessors except for the prior
813 // block, which falls through unconditionally, move the contents of this
814 // block into the prior block.
815 MachineBasicBlock *PrevBB = &*std::prev(TailBB->getIterator());
816 MachineBasicBlock *PriorTBB = nullptr, *PriorFBB = nullptr;
817 SmallVector<MachineOperand, 4> PriorCond;
818 // This has to check PrevBB->succ_size() because EH edges are ignored by
819 // AnalyzeBranch.
820 if (PrevBB->succ_size() == 1 &&
Kyle Buttd2b886e2016-07-20 00:01:51 +0000821 // Layout preds are not always CFG preds. Check.
822 *PrevBB->succ_begin() == TailBB &&
Jacques Pienaar71c30a12016-07-15 14:41:04 +0000823 !TII->analyzeBranch(*PrevBB, PriorTBB, PriorFBB, PriorCond, true) &&
Kyle Butt3232dbb2016-04-08 20:35:01 +0000824 PriorCond.empty() && !PriorTBB && TailBB->pred_size() == 1 &&
825 !TailBB->hasAddressTaken()) {
826 DEBUG(dbgs() << "\nMerging into block: " << *PrevBB
827 << "From MBB: " << *TailBB);
828 if (PreRegAlloc) {
Krzysztof Parzyszek4773f642016-04-26 18:36:34 +0000829 DenseMap<unsigned, RegSubRegPair> LocalVRMap;
830 SmallVector<std::pair<unsigned, RegSubRegPair>, 4> CopyInfos;
Kyle Butt3232dbb2016-04-08 20:35:01 +0000831 MachineBasicBlock::iterator I = TailBB->begin();
832 // Process PHI instructions first.
833 while (I != TailBB->end() && I->isPHI()) {
834 // Replace the uses of the def of the PHI with the register coming
835 // from PredBB.
836 MachineInstr *MI = &*I++;
837 processPHI(MI, TailBB, PrevBB, LocalVRMap, CopyInfos, UsedByPhi, true);
Kyle Butt3232dbb2016-04-08 20:35:01 +0000838 }
839
840 // Now copy the non-PHI instructions.
841 while (I != TailBB->end()) {
842 // Replace def of virtual registers with new registers, and update
843 // uses with PHI source register or the new registers.
844 MachineInstr *MI = &*I++;
845 assert(!MI->isBundle() && "Not expecting bundles before regalloc!");
846 duplicateInstruction(MI, TailBB, PrevBB, MF, LocalVRMap, UsedByPhi);
847 MI->eraseFromParent();
848 }
Krzysztof Parzyszek4773f642016-04-26 18:36:34 +0000849 appendCopies(PrevBB, CopyInfos, Copies);
Kyle Butt3232dbb2016-04-08 20:35:01 +0000850 } else {
851 // No PHIs to worry about, just splice the instructions over.
852 PrevBB->splice(PrevBB->end(), TailBB, TailBB->begin(), TailBB->end());
853 }
854 PrevBB->removeSuccessor(PrevBB->succ_begin());
855 assert(PrevBB->succ_empty());
856 PrevBB->transferSuccessors(TailBB);
857 TDBBs.push_back(PrevBB);
858 Changed = true;
859 }
860
861 // If this is after register allocation, there are no phis to fix.
862 if (!PreRegAlloc)
863 return Changed;
864
865 // If we made no changes so far, we are safe.
866 if (!Changed)
867 return Changed;
868
869 // Handle the nasty case in that we duplicated a block that is part of a loop
870 // into some but not all of its predecessors. For example:
871 // 1 -> 2 <-> 3 |
872 // \ |
873 // \---> rest |
874 // if we duplicate 2 into 1 but not into 3, we end up with
875 // 12 -> 3 <-> 2 -> rest |
876 // \ / |
877 // \----->-----/ |
878 // If there was a "var = phi(1, 3)" in 2, it has to be ultimately replaced
879 // with a phi in 3 (which now dominates 2).
880 // What we do here is introduce a copy in 3 of the register defined by the
881 // phi, just like when we are duplicating 2 into 3, but we don't copy any
882 // real instructions or remove the 3 -> 2 edge from the phi in 2.
Matt Arsenaultb8037a12016-08-16 20:38:05 +0000883 for (MachineBasicBlock *PredBB : Preds) {
David Majnemer0d955d02016-08-11 22:21:41 +0000884 if (is_contained(TDBBs, PredBB))
Kyle Butt3232dbb2016-04-08 20:35:01 +0000885 continue;
886
887 // EH edges
888 if (PredBB->succ_size() != 1)
889 continue;
890
Krzysztof Parzyszek4773f642016-04-26 18:36:34 +0000891 DenseMap<unsigned, RegSubRegPair> LocalVRMap;
892 SmallVector<std::pair<unsigned, RegSubRegPair>, 4> CopyInfos;
Kyle Butt3232dbb2016-04-08 20:35:01 +0000893 MachineBasicBlock::iterator I = TailBB->begin();
894 // Process PHI instructions first.
895 while (I != TailBB->end() && I->isPHI()) {
896 // Replace the uses of the def of the PHI with the register coming
897 // from PredBB.
898 MachineInstr *MI = &*I++;
899 processPHI(MI, TailBB, PredBB, LocalVRMap, CopyInfos, UsedByPhi, false);
900 }
Krzysztof Parzyszek4773f642016-04-26 18:36:34 +0000901 appendCopies(PredBB, CopyInfos, Copies);
Kyle Butt3232dbb2016-04-08 20:35:01 +0000902 }
903
904 return Changed;
905}
906
Krzysztof Parzyszek4773f642016-04-26 18:36:34 +0000907/// At the end of the block \p MBB generate COPY instructions between registers
908/// described by \p CopyInfos. Append resulting instructions to \p Copies.
909void TailDuplicator::appendCopies(MachineBasicBlock *MBB,
910 SmallVectorImpl<std::pair<unsigned,RegSubRegPair>> &CopyInfos,
911 SmallVectorImpl<MachineInstr*> &Copies) {
912 MachineBasicBlock::iterator Loc = MBB->getFirstTerminator();
913 const MCInstrDesc &CopyD = TII->get(TargetOpcode::COPY);
914 for (auto &CI : CopyInfos) {
915 auto C = BuildMI(*MBB, Loc, DebugLoc(), CopyD, CI.first)
916 .addReg(CI.second.Reg, 0, CI.second.SubReg);
917 Copies.push_back(C);
918 }
919}
920
Kyle Butt3232dbb2016-04-08 20:35:01 +0000921/// Remove the specified dead machine basic block from the function, updating
922/// the CFG.
923void TailDuplicator::removeDeadBlock(MachineBasicBlock *MBB) {
924 assert(MBB->pred_empty() && "MBB must be dead!");
925 DEBUG(dbgs() << "\nRemoving MBB: " << *MBB);
926
927 // Remove all successors.
928 while (!MBB->succ_empty())
929 MBB->removeSuccessor(MBB->succ_end() - 1);
930
931 // Remove the block.
932 MBB->eraseFromParent();
933}
934
935} // End llvm namespace