blob: 2d0b1acc4b4c99d651893b559d8bd7ab333c60ea [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,
Kyle Buttdb3391e2016-08-17 21:07:35 +000060 const MachineBranchProbabilityInfo *MBPIin,
61 unsigned TailDupSizeIn) {
Kyle Butt3232dbb2016-04-08 20:35:01 +000062 TII = MF.getSubtarget().getInstrInfo();
63 TRI = MF.getSubtarget().getRegisterInfo();
64 MRI = &MF.getRegInfo();
65 MMI = MMIin;
66 MBPI = MBPIin;
Kyle Buttdb3391e2016-08-17 21:07:35 +000067 TailDupSize = TailDupSizeIn;
Kyle Butt3232dbb2016-04-08 20:35:01 +000068
69 assert(MBPI != nullptr && "Machine Branch Probability Info required");
70
71 PreRegAlloc = MRI->isSSA();
Kyle Butt3232dbb2016-04-08 20:35:01 +000072}
73
74static void VerifyPHIs(MachineFunction &MF, bool CheckExtra) {
75 for (MachineFunction::iterator I = ++MF.begin(), E = MF.end(); I != E; ++I) {
76 MachineBasicBlock *MBB = &*I;
77 SmallSetVector<MachineBasicBlock *, 8> Preds(MBB->pred_begin(),
78 MBB->pred_end());
79 MachineBasicBlock::iterator MI = MBB->begin();
80 while (MI != MBB->end()) {
81 if (!MI->isPHI())
82 break;
Matt Arsenaultb8037a12016-08-16 20:38:05 +000083 for (MachineBasicBlock *PredBB : Preds) {
Kyle Butt3232dbb2016-04-08 20:35:01 +000084 bool Found = false;
85 for (unsigned i = 1, e = MI->getNumOperands(); i != e; i += 2) {
86 MachineBasicBlock *PHIBB = MI->getOperand(i + 1).getMBB();
87 if (PHIBB == PredBB) {
88 Found = true;
89 break;
90 }
91 }
92 if (!Found) {
93 dbgs() << "Malformed PHI in BB#" << MBB->getNumber() << ": " << *MI;
94 dbgs() << " missing input from predecessor BB#"
95 << PredBB->getNumber() << '\n';
96 llvm_unreachable(nullptr);
97 }
98 }
99
100 for (unsigned i = 1, e = MI->getNumOperands(); i != e; i += 2) {
101 MachineBasicBlock *PHIBB = MI->getOperand(i + 1).getMBB();
102 if (CheckExtra && !Preds.count(PHIBB)) {
103 dbgs() << "Warning: malformed PHI in BB#" << MBB->getNumber() << ": "
104 << *MI;
105 dbgs() << " extra input from predecessor BB#" << PHIBB->getNumber()
106 << '\n';
107 llvm_unreachable(nullptr);
108 }
109 if (PHIBB->getNumber() < 0) {
110 dbgs() << "Malformed PHI in BB#" << MBB->getNumber() << ": " << *MI;
111 dbgs() << " non-existing BB#" << PHIBB->getNumber() << '\n';
112 llvm_unreachable(nullptr);
113 }
114 }
115 ++MI;
116 }
117 }
118}
119
120/// Tail duplicate the block and cleanup.
121bool TailDuplicator::tailDuplicateAndUpdate(MachineFunction &MF, bool IsSimple,
122 MachineBasicBlock *MBB) {
123 // Save the successors list.
124 SmallSetVector<MachineBasicBlock *, 8> Succs(MBB->succ_begin(),
125 MBB->succ_end());
126
127 SmallVector<MachineBasicBlock *, 8> TDBBs;
128 SmallVector<MachineInstr *, 16> Copies;
129 if (!tailDuplicate(MF, IsSimple, MBB, TDBBs, Copies))
130 return false;
131
132 ++NumTails;
133
134 SmallVector<MachineInstr *, 8> NewPHIs;
135 MachineSSAUpdater SSAUpdate(MF, &NewPHIs);
136
137 // TailBB's immediate successors are now successors of those predecessors
138 // which duplicated TailBB. Add the predecessors as sources to the PHI
139 // instructions.
140 bool isDead = MBB->pred_empty() && !MBB->hasAddressTaken();
141 if (PreRegAlloc)
142 updateSuccessorsPHIs(MBB, isDead, TDBBs, Succs);
143
144 // If it is dead, remove it.
145 if (isDead) {
Geoff Berryf8c29d62016-06-14 19:40:10 +0000146 NumTailDupRemoved += MBB->size();
Kyle Butt3232dbb2016-04-08 20:35:01 +0000147 removeDeadBlock(MBB);
148 ++NumDeadBlocks;
149 }
150
151 // Update SSA form.
152 if (!SSAUpdateVRs.empty()) {
153 for (unsigned i = 0, e = SSAUpdateVRs.size(); i != e; ++i) {
154 unsigned VReg = SSAUpdateVRs[i];
155 SSAUpdate.Initialize(VReg);
156
157 // If the original definition is still around, add it as an available
158 // value.
159 MachineInstr *DefMI = MRI->getVRegDef(VReg);
160 MachineBasicBlock *DefBB = nullptr;
161 if (DefMI) {
162 DefBB = DefMI->getParent();
163 SSAUpdate.AddAvailableValue(DefBB, VReg);
164 }
165
166 // Add the new vregs as available values.
167 DenseMap<unsigned, AvailableValsTy>::iterator LI =
168 SSAUpdateVals.find(VReg);
169 for (unsigned j = 0, ee = LI->second.size(); j != ee; ++j) {
170 MachineBasicBlock *SrcBB = LI->second[j].first;
171 unsigned SrcReg = LI->second[j].second;
172 SSAUpdate.AddAvailableValue(SrcBB, SrcReg);
173 }
174
175 // Rewrite uses that are outside of the original def's block.
176 MachineRegisterInfo::use_iterator UI = MRI->use_begin(VReg);
177 while (UI != MRI->use_end()) {
178 MachineOperand &UseMO = *UI;
179 MachineInstr *UseMI = UseMO.getParent();
180 ++UI;
181 if (UseMI->isDebugValue()) {
182 // SSAUpdate can replace the use with an undef. That creates
183 // a debug instruction that is a kill.
184 // FIXME: Should it SSAUpdate job to delete debug instructions
185 // instead of replacing the use with undef?
186 UseMI->eraseFromParent();
187 continue;
188 }
189 if (UseMI->getParent() == DefBB && !UseMI->isPHI())
190 continue;
191 SSAUpdate.RewriteUse(UseMO);
192 }
193 }
194
195 SSAUpdateVRs.clear();
196 SSAUpdateVals.clear();
197 }
198
199 // Eliminate some of the copies inserted by tail duplication to maintain
200 // SSA form.
201 for (unsigned i = 0, e = Copies.size(); i != e; ++i) {
202 MachineInstr *Copy = Copies[i];
203 if (!Copy->isCopy())
204 continue;
205 unsigned Dst = Copy->getOperand(0).getReg();
206 unsigned Src = Copy->getOperand(1).getReg();
207 if (MRI->hasOneNonDBGUse(Src) &&
208 MRI->constrainRegClass(Src, MRI->getRegClass(Dst))) {
209 // Copy is the only use. Do trivial copy propagation here.
210 MRI->replaceRegWith(Dst, Src);
211 Copy->eraseFromParent();
212 }
213 }
214
215 if (NewPHIs.size())
216 NumAddedPHIs += NewPHIs.size();
217
218 return true;
219}
220
221/// Look for small blocks that are unconditionally branched to and do not fall
222/// through. Tail-duplicate their instructions into their predecessors to
223/// eliminate (dynamic) branches.
224bool TailDuplicator::tailDuplicateBlocks(MachineFunction &MF) {
225 bool MadeChange = false;
226
227 if (PreRegAlloc && TailDupVerify) {
228 DEBUG(dbgs() << "\n*** Before tail-duplicating\n");
229 VerifyPHIs(MF, true);
230 }
231
232 for (MachineFunction::iterator I = ++MF.begin(), E = MF.end(); I != E;) {
233 MachineBasicBlock *MBB = &*I++;
234
235 if (NumTails == TailDupLimit)
236 break;
237
238 bool IsSimple = isSimpleBB(MBB);
239
240 if (!shouldTailDuplicate(MF, IsSimple, *MBB))
241 continue;
242
243 MadeChange |= tailDuplicateAndUpdate(MF, IsSimple, MBB);
244 }
245
246 if (PreRegAlloc && TailDupVerify)
247 VerifyPHIs(MF, false);
248
249 return MadeChange;
250}
251
252static bool isDefLiveOut(unsigned Reg, MachineBasicBlock *BB,
253 const MachineRegisterInfo *MRI) {
254 for (MachineInstr &UseMI : MRI->use_instructions(Reg)) {
255 if (UseMI.isDebugValue())
256 continue;
257 if (UseMI.getParent() != BB)
258 return true;
259 }
260 return false;
261}
262
263static unsigned getPHISrcRegOpIdx(MachineInstr *MI, MachineBasicBlock *SrcBB) {
264 for (unsigned i = 1, e = MI->getNumOperands(); i != e; i += 2)
265 if (MI->getOperand(i + 1).getMBB() == SrcBB)
266 return i;
267 return 0;
268}
269
270// Remember which registers are used by phis in this block. This is
271// used to determine which registers are liveout while modifying the
272// block (which is why we need to copy the information).
273static void getRegsUsedByPHIs(const MachineBasicBlock &BB,
274 DenseSet<unsigned> *UsedByPhi) {
275 for (const auto &MI : BB) {
276 if (!MI.isPHI())
277 break;
278 for (unsigned i = 1, e = MI.getNumOperands(); i != e; i += 2) {
279 unsigned SrcReg = MI.getOperand(i).getReg();
280 UsedByPhi->insert(SrcReg);
281 }
282 }
283}
284
285/// Add a definition and source virtual registers pair for SSA update.
286void TailDuplicator::addSSAUpdateEntry(unsigned OrigReg, unsigned NewReg,
287 MachineBasicBlock *BB) {
288 DenseMap<unsigned, AvailableValsTy>::iterator LI =
289 SSAUpdateVals.find(OrigReg);
290 if (LI != SSAUpdateVals.end())
291 LI->second.push_back(std::make_pair(BB, NewReg));
292 else {
293 AvailableValsTy Vals;
294 Vals.push_back(std::make_pair(BB, NewReg));
295 SSAUpdateVals.insert(std::make_pair(OrigReg, Vals));
296 SSAUpdateVRs.push_back(OrigReg);
297 }
298}
299
300/// Process PHI node in TailBB by turning it into a copy in PredBB. Remember the
301/// source register that's contributed by PredBB and update SSA update map.
302void TailDuplicator::processPHI(
303 MachineInstr *MI, MachineBasicBlock *TailBB, MachineBasicBlock *PredBB,
Krzysztof Parzyszek4773f642016-04-26 18:36:34 +0000304 DenseMap<unsigned, RegSubRegPair> &LocalVRMap,
305 SmallVectorImpl<std::pair<unsigned, RegSubRegPair>> &Copies,
Kyle Butt3232dbb2016-04-08 20:35:01 +0000306 const DenseSet<unsigned> &RegsUsedByPhi, bool Remove) {
307 unsigned DefReg = MI->getOperand(0).getReg();
308 unsigned SrcOpIdx = getPHISrcRegOpIdx(MI, PredBB);
309 assert(SrcOpIdx && "Unable to find matching PHI source?");
310 unsigned SrcReg = MI->getOperand(SrcOpIdx).getReg();
Krzysztof Parzyszek4773f642016-04-26 18:36:34 +0000311 unsigned SrcSubReg = MI->getOperand(SrcOpIdx).getSubReg();
Kyle Butt3232dbb2016-04-08 20:35:01 +0000312 const TargetRegisterClass *RC = MRI->getRegClass(DefReg);
Krzysztof Parzyszek4773f642016-04-26 18:36:34 +0000313 LocalVRMap.insert(std::make_pair(DefReg, RegSubRegPair(SrcReg, SrcSubReg)));
Kyle Butt3232dbb2016-04-08 20:35:01 +0000314
315 // Insert a copy from source to the end of the block. The def register is the
316 // available value liveout of the block.
317 unsigned NewDef = MRI->createVirtualRegister(RC);
Krzysztof Parzyszek4773f642016-04-26 18:36:34 +0000318 Copies.push_back(std::make_pair(NewDef, RegSubRegPair(SrcReg, SrcSubReg)));
Kyle Butt3232dbb2016-04-08 20:35:01 +0000319 if (isDefLiveOut(DefReg, TailBB, MRI) || RegsUsedByPhi.count(DefReg))
320 addSSAUpdateEntry(DefReg, NewDef, PredBB);
321
322 if (!Remove)
323 return;
324
325 // Remove PredBB from the PHI node.
326 MI->RemoveOperand(SrcOpIdx + 1);
327 MI->RemoveOperand(SrcOpIdx);
328 if (MI->getNumOperands() == 1)
329 MI->eraseFromParent();
330}
331
332/// Duplicate a TailBB instruction to PredBB and update
333/// the source operands due to earlier PHI translation.
334void TailDuplicator::duplicateInstruction(
335 MachineInstr *MI, MachineBasicBlock *TailBB, MachineBasicBlock *PredBB,
Krzysztof Parzyszek4773f642016-04-26 18:36:34 +0000336 MachineFunction &MF,
337 DenseMap<unsigned, RegSubRegPair> &LocalVRMap,
Kyle Butt3232dbb2016-04-08 20:35:01 +0000338 const DenseSet<unsigned> &UsedByPhi) {
Duncan P. N. Exon Smith9cfc75c2016-06-30 00:01:54 +0000339 MachineInstr *NewMI = TII->duplicate(*MI, MF);
Kyle Butt3232dbb2016-04-08 20:35:01 +0000340 if (PreRegAlloc) {
341 for (unsigned i = 0, e = NewMI->getNumOperands(); i != e; ++i) {
342 MachineOperand &MO = NewMI->getOperand(i);
343 if (!MO.isReg())
344 continue;
345 unsigned Reg = MO.getReg();
346 if (!TargetRegisterInfo::isVirtualRegister(Reg))
347 continue;
348 if (MO.isDef()) {
349 const TargetRegisterClass *RC = MRI->getRegClass(Reg);
350 unsigned NewReg = MRI->createVirtualRegister(RC);
351 MO.setReg(NewReg);
Krzysztof Parzyszek4773f642016-04-26 18:36:34 +0000352 LocalVRMap.insert(std::make_pair(Reg, RegSubRegPair(NewReg, 0)));
Kyle Butt3232dbb2016-04-08 20:35:01 +0000353 if (isDefLiveOut(Reg, TailBB, MRI) || UsedByPhi.count(Reg))
354 addSSAUpdateEntry(Reg, NewReg, PredBB);
355 } else {
Krzysztof Parzyszek4773f642016-04-26 18:36:34 +0000356 auto VI = LocalVRMap.find(Reg);
Kyle Butt3232dbb2016-04-08 20:35:01 +0000357 if (VI != LocalVRMap.end()) {
Krzysztof Parzyszek4773f642016-04-26 18:36:34 +0000358 // Need to make sure that the register class of the mapped register
359 // will satisfy the constraints of the class of the register being
360 // replaced.
361 auto *OrigRC = MRI->getRegClass(Reg);
362 auto *MappedRC = MRI->getRegClass(VI->second.Reg);
363 const TargetRegisterClass *ConstrRC;
364 if (VI->second.SubReg != 0) {
365 ConstrRC = TRI->getMatchingSuperRegClass(MappedRC, OrigRC,
366 VI->second.SubReg);
367 if (ConstrRC) {
368 // The actual constraining (as in "find appropriate new class")
369 // is done by getMatchingSuperRegClass, so now we only need to
370 // change the class of the mapped register.
371 MRI->setRegClass(VI->second.Reg, ConstrRC);
372 }
373 } else {
374 // For mapped registers that do not have sub-registers, simply
375 // restrict their class to match the original one.
376 ConstrRC = MRI->constrainRegClass(VI->second.Reg, OrigRC);
377 }
378
379 if (ConstrRC) {
380 // If the class constraining succeeded, we can simply replace
381 // the old register with the mapped one.
382 MO.setReg(VI->second.Reg);
383 // We have Reg -> VI.Reg:VI.SubReg, so if Reg is used with a
384 // sub-register, we need to compose the sub-register indices.
385 MO.setSubReg(TRI->composeSubRegIndices(MO.getSubReg(),
386 VI->second.SubReg));
387 } else {
388 // The direct replacement is not possible, due to failing register
389 // class constraints. An explicit COPY is necessary. Create one
390 // that can be reused
391 auto *NewRC = MI->getRegClassConstraint(i, TII, TRI);
392 if (NewRC == nullptr)
393 NewRC = OrigRC;
394 unsigned NewReg = MRI->createVirtualRegister(NewRC);
395 BuildMI(*PredBB, MI, MI->getDebugLoc(),
396 TII->get(TargetOpcode::COPY), NewReg)
397 .addReg(VI->second.Reg, 0, VI->second.SubReg);
398 LocalVRMap.erase(VI);
399 LocalVRMap.insert(std::make_pair(Reg, RegSubRegPair(NewReg, 0)));
400 MO.setReg(NewReg);
401 // The composed VI.Reg:VI.SubReg is replaced with NewReg, which
402 // is equivalent to the whole register Reg. Hence, Reg:subreg
403 // is same as NewReg:subreg, so keep the sub-register index
404 // unchanged.
405 }
Kyle Butt3232dbb2016-04-08 20:35:01 +0000406 // Clear any kill flags from this operand. The new register could
407 // have uses after this one, so kills are not valid here.
408 MO.setIsKill(false);
Kyle Butt3232dbb2016-04-08 20:35:01 +0000409 }
410 }
411 }
412 }
413 PredBB->insert(PredBB->instr_end(), NewMI);
414}
415
416/// After FromBB is tail duplicated into its predecessor blocks, the successors
417/// have gained new predecessors. Update the PHI instructions in them
418/// accordingly.
419void TailDuplicator::updateSuccessorsPHIs(
420 MachineBasicBlock *FromBB, bool isDead,
421 SmallVectorImpl<MachineBasicBlock *> &TDBBs,
422 SmallSetVector<MachineBasicBlock *, 8> &Succs) {
Matt Arsenaultb8037a12016-08-16 20:38:05 +0000423 for (MachineBasicBlock *SuccBB : Succs) {
424 for (MachineInstr &MI : *SuccBB) {
425 if (!MI.isPHI())
Kyle Butt3232dbb2016-04-08 20:35:01 +0000426 break;
Matt Arsenaultb8037a12016-08-16 20:38:05 +0000427 MachineInstrBuilder MIB(*FromBB->getParent(), MI);
Kyle Butt3232dbb2016-04-08 20:35:01 +0000428 unsigned Idx = 0;
Matt Arsenaultb8037a12016-08-16 20:38:05 +0000429 for (unsigned i = 1, e = MI.getNumOperands(); i != e; i += 2) {
430 MachineOperand &MO = MI.getOperand(i + 1);
Kyle Butt3232dbb2016-04-08 20:35:01 +0000431 if (MO.getMBB() == FromBB) {
432 Idx = i;
433 break;
434 }
435 }
436
437 assert(Idx != 0);
Matt Arsenaultb8037a12016-08-16 20:38:05 +0000438 MachineOperand &MO0 = MI.getOperand(Idx);
Kyle Butt3232dbb2016-04-08 20:35:01 +0000439 unsigned Reg = MO0.getReg();
440 if (isDead) {
441 // Folded into the previous BB.
442 // There could be duplicate phi source entries. FIXME: Should sdisel
443 // or earlier pass fixed this?
Matt Arsenaultb8037a12016-08-16 20:38:05 +0000444 for (unsigned i = MI.getNumOperands() - 2; i != Idx; i -= 2) {
445 MachineOperand &MO = MI.getOperand(i + 1);
Kyle Butt3232dbb2016-04-08 20:35:01 +0000446 if (MO.getMBB() == FromBB) {
Matt Arsenaultb8037a12016-08-16 20:38:05 +0000447 MI.RemoveOperand(i + 1);
448 MI.RemoveOperand(i);
Kyle Butt3232dbb2016-04-08 20:35:01 +0000449 }
450 }
451 } else
452 Idx = 0;
453
454 // If Idx is set, the operands at Idx and Idx+1 must be removed.
455 // We reuse the location to avoid expensive RemoveOperand calls.
456
457 DenseMap<unsigned, AvailableValsTy>::iterator LI =
458 SSAUpdateVals.find(Reg);
459 if (LI != SSAUpdateVals.end()) {
460 // This register is defined in the tail block.
461 for (unsigned j = 0, ee = LI->second.size(); j != ee; ++j) {
462 MachineBasicBlock *SrcBB = LI->second[j].first;
463 // If we didn't duplicate a bb into a particular predecessor, we
464 // might still have added an entry to SSAUpdateVals to correcly
465 // recompute SSA. If that case, avoid adding a dummy extra argument
466 // this PHI.
467 if (!SrcBB->isSuccessor(SuccBB))
468 continue;
469
470 unsigned SrcReg = LI->second[j].second;
471 if (Idx != 0) {
Matt Arsenaultb8037a12016-08-16 20:38:05 +0000472 MI.getOperand(Idx).setReg(SrcReg);
473 MI.getOperand(Idx + 1).setMBB(SrcBB);
Kyle Butt3232dbb2016-04-08 20:35:01 +0000474 Idx = 0;
475 } else {
476 MIB.addReg(SrcReg).addMBB(SrcBB);
477 }
478 }
479 } else {
480 // Live in tail block, must also be live in predecessors.
481 for (unsigned j = 0, ee = TDBBs.size(); j != ee; ++j) {
482 MachineBasicBlock *SrcBB = TDBBs[j];
483 if (Idx != 0) {
Matt Arsenaultb8037a12016-08-16 20:38:05 +0000484 MI.getOperand(Idx).setReg(Reg);
485 MI.getOperand(Idx + 1).setMBB(SrcBB);
Kyle Butt3232dbb2016-04-08 20:35:01 +0000486 Idx = 0;
487 } else {
488 MIB.addReg(Reg).addMBB(SrcBB);
489 }
490 }
491 }
492 if (Idx != 0) {
Matt Arsenaultb8037a12016-08-16 20:38:05 +0000493 MI.RemoveOperand(Idx + 1);
494 MI.RemoveOperand(Idx);
Kyle Butt3232dbb2016-04-08 20:35:01 +0000495 }
496 }
497 }
498}
499
500/// Determine if it is profitable to duplicate this block.
501bool TailDuplicator::shouldTailDuplicate(const MachineFunction &MF,
502 bool IsSimple,
503 MachineBasicBlock &TailBB) {
504 // Only duplicate blocks that end with unconditional branches.
505 if (TailBB.canFallThrough())
506 return false;
507
508 // Don't try to tail-duplicate single-block loops.
509 if (TailBB.isSuccessor(&TailBB))
510 return false;
511
512 // Set the limit on the cost to duplicate. When optimizing for size,
513 // duplicate only one, because one branch instruction can be eliminated to
514 // compensate for the duplication.
515 unsigned MaxDuplicateCount;
Kyle Buttdb3391e2016-08-17 21:07:35 +0000516 if (TailDupSize == 0 &&
517 TailDuplicateSize.getNumOccurrences() == 0 &&
Kyle Buttfeafec52016-08-17 21:07:33 +0000518 MF.getFunction()->optForSize())
Kyle Butt3232dbb2016-04-08 20:35:01 +0000519 MaxDuplicateCount = 1;
Kyle Buttdb3391e2016-08-17 21:07:35 +0000520 else if (TailDupSize == 0)
Kyle Butt3232dbb2016-04-08 20:35:01 +0000521 MaxDuplicateCount = TailDuplicateSize;
Kyle Buttdb3391e2016-08-17 21:07:35 +0000522 else
523 MaxDuplicateCount = TailDupSize;
Kyle Butt3232dbb2016-04-08 20:35:01 +0000524
Kyle Butt07d61422016-08-16 22:56:14 +0000525 // If the block to be duplicated ends in an unanalyzable fallthrough, don't
526 // duplicate it.
527 // A similar check is necessary in MachineBlockPlacement to make sure pairs of
528 // blocks with unanalyzable fallthrough get layed out contiguously.
529 MachineBasicBlock *PredTBB = nullptr, *PredFBB = nullptr;
530 SmallVector<MachineOperand, 4> PredCond;
531 if (TII->analyzeBranch(TailBB, PredTBB, PredFBB, PredCond, true)
532 && TailBB.canFallThrough())
533 return false;
534
Kyle Butt3232dbb2016-04-08 20:35:01 +0000535 // If the target has hardware branch prediction that can handle indirect
536 // branches, duplicating them can often make them predictable when there
537 // are common paths through the code. The limit needs to be high enough
538 // to allow undoing the effects of tail merging and other optimizations
539 // that rearrange the predecessors of the indirect branch.
540
541 bool HasIndirectbr = false;
542 if (!TailBB.empty())
543 HasIndirectbr = TailBB.back().isIndirectBranch();
544
545 if (HasIndirectbr && PreRegAlloc)
546 MaxDuplicateCount = 20;
547
548 // Check the instructions in the block to determine whether tail-duplication
549 // is invalid or unlikely to be profitable.
550 unsigned InstrCount = 0;
551 for (MachineInstr &MI : TailBB) {
552 // Non-duplicable things shouldn't be tail-duplicated.
553 if (MI.isNotDuplicable())
554 return false;
555
556 // Convergent instructions can be duplicated only if doing so doesn't add
557 // new control dependencies, which is what we're going to do here.
558 if (MI.isConvergent())
559 return false;
560
561 // Do not duplicate 'return' instructions if this is a pre-regalloc run.
562 // A return may expand into a lot more instructions (e.g. reload of callee
563 // saved registers) after PEI.
564 if (PreRegAlloc && MI.isReturn())
565 return false;
566
567 // Avoid duplicating calls before register allocation. Calls presents a
568 // barrier to register allocation so duplicating them may end up increasing
569 // spills.
570 if (PreRegAlloc && MI.isCall())
571 return false;
572
573 if (!MI.isPHI() && !MI.isDebugValue())
574 InstrCount += 1;
575
576 if (InstrCount > MaxDuplicateCount)
577 return false;
578 }
579
580 // Check if any of the successors of TailBB has a PHI node in which the
581 // value corresponding to TailBB uses a subregister.
582 // If a phi node uses a register paired with a subregister, the actual
583 // "value type" of the phi may differ from the type of the register without
584 // any subregisters. Due to a bug, tail duplication may add a new operand
585 // without a necessary subregister, producing an invalid code. This is
586 // demonstrated by test/CodeGen/Hexagon/tail-dup-subreg-abort.ll.
587 // Disable tail duplication for this case for now, until the problem is
588 // fixed.
589 for (auto SB : TailBB.successors()) {
590 for (auto &I : *SB) {
591 if (!I.isPHI())
592 break;
593 unsigned Idx = getPHISrcRegOpIdx(&I, &TailBB);
594 assert(Idx != 0);
595 MachineOperand &PU = I.getOperand(Idx);
596 if (PU.getSubReg() != 0)
597 return false;
598 }
599 }
600
601 if (HasIndirectbr && PreRegAlloc)
602 return true;
603
604 if (IsSimple)
605 return true;
606
607 if (!PreRegAlloc)
608 return true;
609
610 return canCompletelyDuplicateBB(TailBB);
611}
612
613/// True if this BB has only one unconditional jump.
614bool TailDuplicator::isSimpleBB(MachineBasicBlock *TailBB) {
615 if (TailBB->succ_size() != 1)
616 return false;
617 if (TailBB->pred_empty())
618 return false;
619 MachineBasicBlock::iterator I = TailBB->getFirstNonDebugInstr();
620 if (I == TailBB->end())
621 return true;
622 return I->isUnconditionalBranch();
623}
624
625static bool bothUsedInPHI(const MachineBasicBlock &A,
Benjamin Kramerbdc49562016-06-12 15:39:02 +0000626 const SmallPtrSet<MachineBasicBlock *, 8> &SuccsB) {
Kyle Butt3232dbb2016-04-08 20:35:01 +0000627 for (MachineBasicBlock *BB : A.successors())
628 if (SuccsB.count(BB) && !BB->empty() && BB->begin()->isPHI())
629 return true;
630
631 return false;
632}
633
634bool TailDuplicator::canCompletelyDuplicateBB(MachineBasicBlock &BB) {
635 for (MachineBasicBlock *PredBB : BB.predecessors()) {
636 if (PredBB->succ_size() > 1)
637 return false;
638
639 MachineBasicBlock *PredTBB = nullptr, *PredFBB = nullptr;
640 SmallVector<MachineOperand, 4> PredCond;
Jacques Pienaar71c30a12016-07-15 14:41:04 +0000641 if (TII->analyzeBranch(*PredBB, PredTBB, PredFBB, PredCond, true))
Kyle Butt3232dbb2016-04-08 20:35:01 +0000642 return false;
643
644 if (!PredCond.empty())
645 return false;
646 }
647 return true;
648}
649
650bool TailDuplicator::duplicateSimpleBB(
651 MachineBasicBlock *TailBB, SmallVectorImpl<MachineBasicBlock *> &TDBBs,
652 const DenseSet<unsigned> &UsedByPhi,
653 SmallVectorImpl<MachineInstr *> &Copies) {
654 SmallPtrSet<MachineBasicBlock *, 8> Succs(TailBB->succ_begin(),
655 TailBB->succ_end());
656 SmallVector<MachineBasicBlock *, 8> Preds(TailBB->pred_begin(),
657 TailBB->pred_end());
658 bool Changed = false;
Matt Arsenaultb8037a12016-08-16 20:38:05 +0000659 for (MachineBasicBlock *PredBB : Preds) {
Kyle Butt3232dbb2016-04-08 20:35:01 +0000660 if (PredBB->hasEHPadSuccessor())
661 continue;
662
663 if (bothUsedInPHI(*PredBB, Succs))
664 continue;
665
666 MachineBasicBlock *PredTBB = nullptr, *PredFBB = nullptr;
667 SmallVector<MachineOperand, 4> PredCond;
Jacques Pienaar71c30a12016-07-15 14:41:04 +0000668 if (TII->analyzeBranch(*PredBB, PredTBB, PredFBB, PredCond, true))
Kyle Butt3232dbb2016-04-08 20:35:01 +0000669 continue;
670
671 Changed = true;
672 DEBUG(dbgs() << "\nTail-duplicating into PredBB: " << *PredBB
673 << "From simple Succ: " << *TailBB);
674
675 MachineBasicBlock *NewTarget = *TailBB->succ_begin();
Matthias Braun6442fc12016-08-18 00:59:32 +0000676 MachineBasicBlock *NextBB = PredBB->getNextNode();
Kyle Butt3232dbb2016-04-08 20:35:01 +0000677
678 // Make PredFBB explicit.
679 if (PredCond.empty())
680 PredFBB = PredTBB;
681
682 // Make fall through explicit.
683 if (!PredTBB)
684 PredTBB = NextBB;
685 if (!PredFBB)
686 PredFBB = NextBB;
687
688 // Redirect
689 if (PredFBB == TailBB)
690 PredFBB = NewTarget;
691 if (PredTBB == TailBB)
692 PredTBB = NewTarget;
693
694 // Make the branch unconditional if possible
695 if (PredTBB == PredFBB) {
696 PredCond.clear();
697 PredFBB = nullptr;
698 }
699
700 // Avoid adding fall through branches.
701 if (PredFBB == NextBB)
702 PredFBB = nullptr;
703 if (PredTBB == NextBB && PredFBB == nullptr)
704 PredTBB = nullptr;
705
706 TII->RemoveBranch(*PredBB);
707
708 if (!PredBB->isSuccessor(NewTarget))
709 PredBB->replaceSuccessor(TailBB, NewTarget);
710 else {
711 PredBB->removeSuccessor(TailBB, true);
712 assert(PredBB->succ_size() <= 1);
713 }
714
715 if (PredTBB)
716 TII->InsertBranch(*PredBB, PredTBB, PredFBB, PredCond, DebugLoc());
717
718 TDBBs.push_back(PredBB);
719 }
720 return Changed;
721}
722
Kyle Butt9e52c062016-07-19 23:54:21 +0000723bool TailDuplicator::canTailDuplicate(MachineBasicBlock *TailBB,
724 MachineBasicBlock *PredBB) {
725 // EH edges are ignored by AnalyzeBranch.
726 if (PredBB->succ_size() > 1)
727 return false;
728
729 MachineBasicBlock *PredTBB, *PredFBB;
730 SmallVector<MachineOperand, 4> PredCond;
731 if (TII->analyzeBranch(*PredBB, PredTBB, PredFBB, PredCond, true))
732 return false;
733 if (!PredCond.empty())
734 return false;
735 return true;
736}
737
Kyle Butt3232dbb2016-04-08 20:35:01 +0000738/// If it is profitable, duplicate TailBB's contents in each
739/// of its predecessors.
740bool TailDuplicator::tailDuplicate(MachineFunction &MF, bool IsSimple,
741 MachineBasicBlock *TailBB,
742 SmallVectorImpl<MachineBasicBlock *> &TDBBs,
743 SmallVectorImpl<MachineInstr *> &Copies) {
744 DEBUG(dbgs() << "\n*** Tail-duplicating BB#" << TailBB->getNumber() << '\n');
745
746 DenseSet<unsigned> UsedByPhi;
747 getRegsUsedByPHIs(*TailBB, &UsedByPhi);
748
749 if (IsSimple)
750 return duplicateSimpleBB(TailBB, TDBBs, UsedByPhi, Copies);
751
752 // Iterate through all the unique predecessors and tail-duplicate this
753 // block into them, if possible. Copying the list ahead of time also
754 // avoids trouble with the predecessor list reallocating.
755 bool Changed = false;
756 SmallSetVector<MachineBasicBlock *, 8> Preds(TailBB->pred_begin(),
757 TailBB->pred_end());
Matt Arsenaultb8037a12016-08-16 20:38:05 +0000758 for (MachineBasicBlock *PredBB : Preds) {
Kyle Butt3232dbb2016-04-08 20:35:01 +0000759 assert(TailBB != PredBB &&
760 "Single-block loop should have been rejected earlier!");
Kyle Butt9e52c062016-07-19 23:54:21 +0000761
762 if (!canTailDuplicate(TailBB, PredBB))
Kyle Butt3232dbb2016-04-08 20:35:01 +0000763 continue;
764
Kyle Butt3232dbb2016-04-08 20:35:01 +0000765 // Don't duplicate into a fall-through predecessor (at least for now).
766 if (PredBB->isLayoutSuccessor(TailBB) && PredBB->canFallThrough())
767 continue;
768
769 DEBUG(dbgs() << "\nTail-duplicating into PredBB: " << *PredBB
770 << "From Succ: " << *TailBB);
771
772 TDBBs.push_back(PredBB);
773
774 // Remove PredBB's unconditional branch.
775 TII->RemoveBranch(*PredBB);
776
Kyle Butt3232dbb2016-04-08 20:35:01 +0000777 // Clone the contents of TailBB into PredBB.
Krzysztof Parzyszek4773f642016-04-26 18:36:34 +0000778 DenseMap<unsigned, RegSubRegPair> LocalVRMap;
779 SmallVector<std::pair<unsigned, RegSubRegPair>, 4> CopyInfos;
Kyle Butt3232dbb2016-04-08 20:35:01 +0000780 // Use instr_iterator here to properly handle bundles, e.g.
781 // ARM Thumb2 IT block.
782 MachineBasicBlock::instr_iterator I = TailBB->instr_begin();
783 while (I != TailBB->instr_end()) {
784 MachineInstr *MI = &*I;
785 ++I;
786 if (MI->isPHI()) {
787 // Replace the uses of the def of the PHI with the register coming
788 // from PredBB.
789 processPHI(MI, TailBB, PredBB, LocalVRMap, CopyInfos, UsedByPhi, true);
790 } else {
791 // Replace def of virtual registers with new registers, and update
792 // uses with PHI source register or the new registers.
793 duplicateInstruction(MI, TailBB, PredBB, MF, LocalVRMap, UsedByPhi);
794 }
795 }
Krzysztof Parzyszek4773f642016-04-26 18:36:34 +0000796 appendCopies(PredBB, CopyInfos, Copies);
Kyle Butt3232dbb2016-04-08 20:35:01 +0000797
798 // Simplify
Kyle Butt9e52c062016-07-19 23:54:21 +0000799 MachineBasicBlock *PredTBB, *PredFBB;
800 SmallVector<MachineOperand, 4> PredCond;
Jacques Pienaar71c30a12016-07-15 14:41:04 +0000801 TII->analyzeBranch(*PredBB, PredTBB, PredFBB, PredCond, true);
Kyle Butt3232dbb2016-04-08 20:35:01 +0000802
Geoff Berryf8c29d62016-06-14 19:40:10 +0000803 NumTailDupAdded += TailBB->size() - 1; // subtract one for removed branch
Kyle Butt3232dbb2016-04-08 20:35:01 +0000804
805 // Update the CFG.
806 PredBB->removeSuccessor(PredBB->succ_begin());
807 assert(PredBB->succ_empty() &&
808 "TailDuplicate called on block with multiple successors!");
Matt Arsenaultb8037a12016-08-16 20:38:05 +0000809 for (MachineBasicBlock *Succ : TailBB->successors())
810 PredBB->addSuccessor(Succ, MBPI->getEdgeProbability(TailBB, Succ));
Kyle Butt3232dbb2016-04-08 20:35:01 +0000811
812 Changed = true;
813 ++NumTailDups;
814 }
815
816 // If TailBB was duplicated into all its predecessors except for the prior
817 // block, which falls through unconditionally, move the contents of this
818 // block into the prior block.
819 MachineBasicBlock *PrevBB = &*std::prev(TailBB->getIterator());
820 MachineBasicBlock *PriorTBB = nullptr, *PriorFBB = nullptr;
821 SmallVector<MachineOperand, 4> PriorCond;
822 // This has to check PrevBB->succ_size() because EH edges are ignored by
823 // AnalyzeBranch.
824 if (PrevBB->succ_size() == 1 &&
Kyle Buttd2b886e2016-07-20 00:01:51 +0000825 // Layout preds are not always CFG preds. Check.
826 *PrevBB->succ_begin() == TailBB &&
Jacques Pienaar71c30a12016-07-15 14:41:04 +0000827 !TII->analyzeBranch(*PrevBB, PriorTBB, PriorFBB, PriorCond, true) &&
Kyle Butt3232dbb2016-04-08 20:35:01 +0000828 PriorCond.empty() && !PriorTBB && TailBB->pred_size() == 1 &&
829 !TailBB->hasAddressTaken()) {
830 DEBUG(dbgs() << "\nMerging into block: " << *PrevBB
831 << "From MBB: " << *TailBB);
832 if (PreRegAlloc) {
Krzysztof Parzyszek4773f642016-04-26 18:36:34 +0000833 DenseMap<unsigned, RegSubRegPair> LocalVRMap;
834 SmallVector<std::pair<unsigned, RegSubRegPair>, 4> CopyInfos;
Kyle Butt3232dbb2016-04-08 20:35:01 +0000835 MachineBasicBlock::iterator I = TailBB->begin();
836 // Process PHI instructions first.
837 while (I != TailBB->end() && I->isPHI()) {
838 // Replace the uses of the def of the PHI with the register coming
839 // from PredBB.
840 MachineInstr *MI = &*I++;
841 processPHI(MI, TailBB, PrevBB, LocalVRMap, CopyInfos, UsedByPhi, true);
Kyle Butt3232dbb2016-04-08 20:35:01 +0000842 }
843
844 // Now copy the non-PHI instructions.
845 while (I != TailBB->end()) {
846 // Replace def of virtual registers with new registers, and update
847 // uses with PHI source register or the new registers.
848 MachineInstr *MI = &*I++;
849 assert(!MI->isBundle() && "Not expecting bundles before regalloc!");
850 duplicateInstruction(MI, TailBB, PrevBB, MF, LocalVRMap, UsedByPhi);
851 MI->eraseFromParent();
852 }
Krzysztof Parzyszek4773f642016-04-26 18:36:34 +0000853 appendCopies(PrevBB, CopyInfos, Copies);
Kyle Butt3232dbb2016-04-08 20:35:01 +0000854 } else {
855 // No PHIs to worry about, just splice the instructions over.
856 PrevBB->splice(PrevBB->end(), TailBB, TailBB->begin(), TailBB->end());
857 }
858 PrevBB->removeSuccessor(PrevBB->succ_begin());
859 assert(PrevBB->succ_empty());
860 PrevBB->transferSuccessors(TailBB);
861 TDBBs.push_back(PrevBB);
862 Changed = true;
863 }
864
865 // If this is after register allocation, there are no phis to fix.
866 if (!PreRegAlloc)
867 return Changed;
868
869 // If we made no changes so far, we are safe.
870 if (!Changed)
871 return Changed;
872
873 // Handle the nasty case in that we duplicated a block that is part of a loop
874 // into some but not all of its predecessors. For example:
875 // 1 -> 2 <-> 3 |
876 // \ |
877 // \---> rest |
878 // if we duplicate 2 into 1 but not into 3, we end up with
879 // 12 -> 3 <-> 2 -> rest |
880 // \ / |
881 // \----->-----/ |
882 // If there was a "var = phi(1, 3)" in 2, it has to be ultimately replaced
883 // with a phi in 3 (which now dominates 2).
884 // What we do here is introduce a copy in 3 of the register defined by the
885 // phi, just like when we are duplicating 2 into 3, but we don't copy any
886 // real instructions or remove the 3 -> 2 edge from the phi in 2.
Matt Arsenaultb8037a12016-08-16 20:38:05 +0000887 for (MachineBasicBlock *PredBB : Preds) {
David Majnemer0d955d02016-08-11 22:21:41 +0000888 if (is_contained(TDBBs, PredBB))
Kyle Butt3232dbb2016-04-08 20:35:01 +0000889 continue;
890
891 // EH edges
892 if (PredBB->succ_size() != 1)
893 continue;
894
Krzysztof Parzyszek4773f642016-04-26 18:36:34 +0000895 DenseMap<unsigned, RegSubRegPair> LocalVRMap;
896 SmallVector<std::pair<unsigned, RegSubRegPair>, 4> CopyInfos;
Kyle Butt3232dbb2016-04-08 20:35:01 +0000897 MachineBasicBlock::iterator I = TailBB->begin();
898 // Process PHI instructions first.
899 while (I != TailBB->end() && I->isPHI()) {
900 // Replace the uses of the def of the PHI with the register coming
901 // from PredBB.
902 MachineInstr *MI = &*I++;
903 processPHI(MI, TailBB, PredBB, LocalVRMap, CopyInfos, UsedByPhi, false);
904 }
Krzysztof Parzyszek4773f642016-04-26 18:36:34 +0000905 appendCopies(PredBB, CopyInfos, Copies);
Kyle Butt3232dbb2016-04-08 20:35:01 +0000906 }
907
908 return Changed;
909}
910
Krzysztof Parzyszek4773f642016-04-26 18:36:34 +0000911/// At the end of the block \p MBB generate COPY instructions between registers
912/// described by \p CopyInfos. Append resulting instructions to \p Copies.
913void TailDuplicator::appendCopies(MachineBasicBlock *MBB,
914 SmallVectorImpl<std::pair<unsigned,RegSubRegPair>> &CopyInfos,
915 SmallVectorImpl<MachineInstr*> &Copies) {
916 MachineBasicBlock::iterator Loc = MBB->getFirstTerminator();
917 const MCInstrDesc &CopyD = TII->get(TargetOpcode::COPY);
918 for (auto &CI : CopyInfos) {
919 auto C = BuildMI(*MBB, Loc, DebugLoc(), CopyD, CI.first)
920 .addReg(CI.second.Reg, 0, CI.second.SubReg);
921 Copies.push_back(C);
922 }
923}
924
Kyle Butt3232dbb2016-04-08 20:35:01 +0000925/// Remove the specified dead machine basic block from the function, updating
926/// the CFG.
927void TailDuplicator::removeDeadBlock(MachineBasicBlock *MBB) {
928 assert(MBB->pred_empty() && "MBB must be dead!");
929 DEBUG(dbgs() << "\nRemoving MBB: " << *MBB);
930
931 // Remove all successors.
932 while (!MBB->succ_empty())
933 MBB->removeSuccessor(MBB->succ_end() - 1);
934
935 // Remove the block.
936 MBB->eraseFromParent();
937}
938
939} // End llvm namespace