blob: dc7265dcf6c244403670dfa01e91449599dca50c [file] [log] [blame]
Eugene Zelenko6ac7a342017-06-07 23:53:32 +00001//===- TailDuplicator.cpp - Duplicate blocks into predecessors' tails -----===//
Kyle Butt3232dbb2016-04-08 20:35:01 +00002//
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
Eugene Zelenko6ac7a342017-06-07 23:53:32 +000015#include "llvm/ADT/DenseMap.h"
Kyle Butt3232dbb2016-04-08 20:35:01 +000016#include "llvm/ADT/DenseSet.h"
17#include "llvm/ADT/SetVector.h"
Eugene Zelenko6ac7a342017-06-07 23:53:32 +000018#include "llvm/ADT/SmallPtrSet.h"
19#include "llvm/ADT/SmallVector.h"
Kyle Butt3232dbb2016-04-08 20:35:01 +000020#include "llvm/ADT/Statistic.h"
Eugene Zelenko6ac7a342017-06-07 23:53:32 +000021#include "llvm/ADT/STLExtras.h"
22#include "llvm/CodeGen/MachineBasicBlock.h"
Kyle Butt3232dbb2016-04-08 20:35:01 +000023#include "llvm/CodeGen/MachineBranchProbabilityInfo.h"
Eugene Zelenko6ac7a342017-06-07 23:53:32 +000024#include "llvm/CodeGen/MachineFunction.h"
25#include "llvm/CodeGen/MachineInstr.h"
Kyle Butt3232dbb2016-04-08 20:35:01 +000026#include "llvm/CodeGen/MachineInstrBuilder.h"
Eugene Zelenko6ac7a342017-06-07 23:53:32 +000027#include "llvm/CodeGen/MachineOperand.h"
28#include "llvm/CodeGen/MachineRegisterInfo.h"
29#include "llvm/CodeGen/MachineSSAUpdater.h"
30#include "llvm/CodeGen/TailDuplicator.h"
31#include "llvm/IR/DebugLoc.h"
Kyle Butt3232dbb2016-04-08 20:35:01 +000032#include "llvm/IR/Function.h"
33#include "llvm/Support/CommandLine.h"
34#include "llvm/Support/Debug.h"
35#include "llvm/Support/ErrorHandling.h"
36#include "llvm/Support/raw_ostream.h"
Eugene Zelenko6ac7a342017-06-07 23:53:32 +000037#include "llvm/Target/TargetInstrInfo.h"
38#include "llvm/Target/TargetRegisterInfo.h"
39#include "llvm/Target/TargetSubtargetInfo.h"
40#include <algorithm>
41#include <cassert>
42#include <iterator>
43#include <utility>
44
Kyle Butt3232dbb2016-04-08 20:35:01 +000045using namespace llvm;
46
47#define DEBUG_TYPE "tailduplication"
48
49STATISTIC(NumTails, "Number of tails duplicated");
50STATISTIC(NumTailDups, "Number of tail duplicated blocks");
Geoff Berryf8c29d62016-06-14 19:40:10 +000051STATISTIC(NumTailDupAdded,
52 "Number of instructions added due to tail duplication");
53STATISTIC(NumTailDupRemoved,
54 "Number of instructions removed due to tail duplication");
Kyle Butt3232dbb2016-04-08 20:35:01 +000055STATISTIC(NumDeadBlocks, "Number of dead blocks removed");
56STATISTIC(NumAddedPHIs, "Number of phis added");
57
58// Heuristic for tail duplication.
59static cl::opt<unsigned> TailDuplicateSize(
60 "tail-dup-size",
61 cl::desc("Maximum instructions to consider tail duplicating"), cl::init(2),
62 cl::Hidden);
63
Eugene Zelenko6ac7a342017-06-07 23:53:32 +000064static cl::opt<unsigned> TailDupIndirectBranchSize(
Kyle Butt61aca6e2016-08-30 18:18:54 +000065 "tail-dup-indirect-size",
66 cl::desc("Maximum instructions to consider tail duplicating blocks that "
67 "end with indirect branches."), cl::init(20),
68 cl::Hidden);
69
Kyle Butt3232dbb2016-04-08 20:35:01 +000070static cl::opt<bool>
71 TailDupVerify("tail-dup-verify",
72 cl::desc("Verify sanity of PHI instructions during taildup"),
73 cl::init(false), cl::Hidden);
74
75static cl::opt<unsigned> TailDupLimit("tail-dup-limit", cl::init(~0U),
76 cl::Hidden);
77
Kyle Butt3ed42732016-08-25 01:37:03 +000078void TailDuplicator::initMF(MachineFunction &MFin,
Kyle Buttdb3391e2016-08-17 21:07:35 +000079 const MachineBranchProbabilityInfo *MBPIin,
Kyle Butt0846e562016-10-11 20:36:43 +000080 bool LayoutModeIn, unsigned TailDupSizeIn) {
Kyle Butt3ed42732016-08-25 01:37:03 +000081 MF = &MFin;
82 TII = MF->getSubtarget().getInstrInfo();
83 TRI = MF->getSubtarget().getRegisterInfo();
84 MRI = &MF->getRegInfo();
Kyle Buttc7f1eac2016-08-25 01:37:07 +000085 MMI = &MF->getMMI();
Kyle Butt3232dbb2016-04-08 20:35:01 +000086 MBPI = MBPIin;
Kyle Buttdb3391e2016-08-17 21:07:35 +000087 TailDupSize = TailDupSizeIn;
Kyle Butt3232dbb2016-04-08 20:35:01 +000088
89 assert(MBPI != nullptr && "Machine Branch Probability Info required");
90
Kyle Butt0846e562016-10-11 20:36:43 +000091 LayoutMode = LayoutModeIn;
Kyle Butt3232dbb2016-04-08 20:35:01 +000092 PreRegAlloc = MRI->isSSA();
Kyle Butt3232dbb2016-04-08 20:35:01 +000093}
94
95static void VerifyPHIs(MachineFunction &MF, bool CheckExtra) {
96 for (MachineFunction::iterator I = ++MF.begin(), E = MF.end(); I != E; ++I) {
97 MachineBasicBlock *MBB = &*I;
98 SmallSetVector<MachineBasicBlock *, 8> Preds(MBB->pred_begin(),
99 MBB->pred_end());
100 MachineBasicBlock::iterator MI = MBB->begin();
101 while (MI != MBB->end()) {
102 if (!MI->isPHI())
103 break;
Matt Arsenaultb8037a12016-08-16 20:38:05 +0000104 for (MachineBasicBlock *PredBB : Preds) {
Kyle Butt3232dbb2016-04-08 20:35:01 +0000105 bool Found = false;
106 for (unsigned i = 1, e = MI->getNumOperands(); i != e; i += 2) {
107 MachineBasicBlock *PHIBB = MI->getOperand(i + 1).getMBB();
108 if (PHIBB == PredBB) {
109 Found = true;
110 break;
111 }
112 }
113 if (!Found) {
114 dbgs() << "Malformed PHI in BB#" << MBB->getNumber() << ": " << *MI;
115 dbgs() << " missing input from predecessor BB#"
116 << PredBB->getNumber() << '\n';
117 llvm_unreachable(nullptr);
118 }
119 }
120
121 for (unsigned i = 1, e = MI->getNumOperands(); i != e; i += 2) {
122 MachineBasicBlock *PHIBB = MI->getOperand(i + 1).getMBB();
123 if (CheckExtra && !Preds.count(PHIBB)) {
124 dbgs() << "Warning: malformed PHI in BB#" << MBB->getNumber() << ": "
125 << *MI;
126 dbgs() << " extra input from predecessor BB#" << PHIBB->getNumber()
127 << '\n';
128 llvm_unreachable(nullptr);
129 }
130 if (PHIBB->getNumber() < 0) {
131 dbgs() << "Malformed PHI in BB#" << MBB->getNumber() << ": " << *MI;
132 dbgs() << " non-existing BB#" << PHIBB->getNumber() << '\n';
133 llvm_unreachable(nullptr);
134 }
135 }
136 ++MI;
137 }
138 }
139}
140
141/// Tail duplicate the block and cleanup.
Kyle Butt723aa132016-08-26 20:12:40 +0000142/// \p IsSimple - return value of isSimpleBB
143/// \p MBB - block to be duplicated
Kyle Butt0846e562016-10-11 20:36:43 +0000144/// \p ForcedLayoutPred - If non-null, treat this block as the layout
145/// predecessor, instead of using the ordering in MF
Kyle Butt723aa132016-08-26 20:12:40 +0000146/// \p DuplicatedPreds - if non-null, \p DuplicatedPreds will contain a list of
147/// all Preds that received a copy of \p MBB.
Kyle Butt0846e562016-10-11 20:36:43 +0000148/// \p RemovalCallback - if non-null, called just before MBB is deleted.
Kyle Butt723aa132016-08-26 20:12:40 +0000149bool TailDuplicator::tailDuplicateAndUpdate(
150 bool IsSimple, MachineBasicBlock *MBB,
Kyle Butt0846e562016-10-11 20:36:43 +0000151 MachineBasicBlock *ForcedLayoutPred,
152 SmallVectorImpl<MachineBasicBlock*> *DuplicatedPreds,
Eugene Zelenko6ac7a342017-06-07 23:53:32 +0000153 function_ref<void(MachineBasicBlock *)> *RemovalCallback) {
Kyle Butt3232dbb2016-04-08 20:35:01 +0000154 // Save the successors list.
155 SmallSetVector<MachineBasicBlock *, 8> Succs(MBB->succ_begin(),
156 MBB->succ_end());
157
158 SmallVector<MachineBasicBlock *, 8> TDBBs;
159 SmallVector<MachineInstr *, 16> Copies;
Kyle Butt0846e562016-10-11 20:36:43 +0000160 if (!tailDuplicate(IsSimple, MBB, ForcedLayoutPred, TDBBs, Copies))
Kyle Butt3232dbb2016-04-08 20:35:01 +0000161 return false;
162
163 ++NumTails;
164
165 SmallVector<MachineInstr *, 8> NewPHIs;
Kyle Butt3ed42732016-08-25 01:37:03 +0000166 MachineSSAUpdater SSAUpdate(*MF, &NewPHIs);
Kyle Butt3232dbb2016-04-08 20:35:01 +0000167
168 // TailBB's immediate successors are now successors of those predecessors
169 // which duplicated TailBB. Add the predecessors as sources to the PHI
170 // instructions.
171 bool isDead = MBB->pred_empty() && !MBB->hasAddressTaken();
172 if (PreRegAlloc)
173 updateSuccessorsPHIs(MBB, isDead, TDBBs, Succs);
174
175 // If it is dead, remove it.
176 if (isDead) {
Geoff Berryf8c29d62016-06-14 19:40:10 +0000177 NumTailDupRemoved += MBB->size();
Kyle Butt0846e562016-10-11 20:36:43 +0000178 removeDeadBlock(MBB, RemovalCallback);
Kyle Butt3232dbb2016-04-08 20:35:01 +0000179 ++NumDeadBlocks;
180 }
181
182 // Update SSA form.
183 if (!SSAUpdateVRs.empty()) {
184 for (unsigned i = 0, e = SSAUpdateVRs.size(); i != e; ++i) {
185 unsigned VReg = SSAUpdateVRs[i];
186 SSAUpdate.Initialize(VReg);
187
188 // If the original definition is still around, add it as an available
189 // value.
190 MachineInstr *DefMI = MRI->getVRegDef(VReg);
191 MachineBasicBlock *DefBB = nullptr;
192 if (DefMI) {
193 DefBB = DefMI->getParent();
194 SSAUpdate.AddAvailableValue(DefBB, VReg);
195 }
196
197 // Add the new vregs as available values.
198 DenseMap<unsigned, AvailableValsTy>::iterator LI =
199 SSAUpdateVals.find(VReg);
200 for (unsigned j = 0, ee = LI->second.size(); j != ee; ++j) {
201 MachineBasicBlock *SrcBB = LI->second[j].first;
202 unsigned SrcReg = LI->second[j].second;
203 SSAUpdate.AddAvailableValue(SrcBB, SrcReg);
204 }
205
206 // Rewrite uses that are outside of the original def's block.
207 MachineRegisterInfo::use_iterator UI = MRI->use_begin(VReg);
208 while (UI != MRI->use_end()) {
209 MachineOperand &UseMO = *UI;
210 MachineInstr *UseMI = UseMO.getParent();
211 ++UI;
212 if (UseMI->isDebugValue()) {
213 // SSAUpdate can replace the use with an undef. That creates
214 // a debug instruction that is a kill.
215 // FIXME: Should it SSAUpdate job to delete debug instructions
216 // instead of replacing the use with undef?
217 UseMI->eraseFromParent();
218 continue;
219 }
220 if (UseMI->getParent() == DefBB && !UseMI->isPHI())
221 continue;
222 SSAUpdate.RewriteUse(UseMO);
223 }
224 }
225
226 SSAUpdateVRs.clear();
227 SSAUpdateVals.clear();
228 }
229
230 // Eliminate some of the copies inserted by tail duplication to maintain
231 // SSA form.
232 for (unsigned i = 0, e = Copies.size(); i != e; ++i) {
233 MachineInstr *Copy = Copies[i];
234 if (!Copy->isCopy())
235 continue;
236 unsigned Dst = Copy->getOperand(0).getReg();
237 unsigned Src = Copy->getOperand(1).getReg();
238 if (MRI->hasOneNonDBGUse(Src) &&
239 MRI->constrainRegClass(Src, MRI->getRegClass(Dst))) {
240 // Copy is the only use. Do trivial copy propagation here.
241 MRI->replaceRegWith(Dst, Src);
242 Copy->eraseFromParent();
243 }
244 }
245
246 if (NewPHIs.size())
247 NumAddedPHIs += NewPHIs.size();
248
Kyle Butt723aa132016-08-26 20:12:40 +0000249 if (DuplicatedPreds)
250 *DuplicatedPreds = std::move(TDBBs);
251
Kyle Butt3232dbb2016-04-08 20:35:01 +0000252 return true;
253}
254
255/// Look for small blocks that are unconditionally branched to and do not fall
256/// through. Tail-duplicate their instructions into their predecessors to
257/// eliminate (dynamic) branches.
Kyle Butt3ed42732016-08-25 01:37:03 +0000258bool TailDuplicator::tailDuplicateBlocks() {
Kyle Butt3232dbb2016-04-08 20:35:01 +0000259 bool MadeChange = false;
260
261 if (PreRegAlloc && TailDupVerify) {
262 DEBUG(dbgs() << "\n*** Before tail-duplicating\n");
Kyle Butt3ed42732016-08-25 01:37:03 +0000263 VerifyPHIs(*MF, true);
Kyle Butt3232dbb2016-04-08 20:35:01 +0000264 }
265
Kyle Butt3ed42732016-08-25 01:37:03 +0000266 for (MachineFunction::iterator I = ++MF->begin(), E = MF->end(); I != E;) {
Kyle Butt3232dbb2016-04-08 20:35:01 +0000267 MachineBasicBlock *MBB = &*I++;
268
269 if (NumTails == TailDupLimit)
270 break;
271
272 bool IsSimple = isSimpleBB(MBB);
273
Kyle Butt3ed42732016-08-25 01:37:03 +0000274 if (!shouldTailDuplicate(IsSimple, *MBB))
Kyle Butt3232dbb2016-04-08 20:35:01 +0000275 continue;
276
Kyle Butt0846e562016-10-11 20:36:43 +0000277 MadeChange |= tailDuplicateAndUpdate(IsSimple, MBB, nullptr);
Kyle Butt3232dbb2016-04-08 20:35:01 +0000278 }
279
280 if (PreRegAlloc && TailDupVerify)
Kyle Butt3ed42732016-08-25 01:37:03 +0000281 VerifyPHIs(*MF, false);
Kyle Butt3232dbb2016-04-08 20:35:01 +0000282
283 return MadeChange;
284}
285
286static bool isDefLiveOut(unsigned Reg, MachineBasicBlock *BB,
287 const MachineRegisterInfo *MRI) {
288 for (MachineInstr &UseMI : MRI->use_instructions(Reg)) {
289 if (UseMI.isDebugValue())
290 continue;
291 if (UseMI.getParent() != BB)
292 return true;
293 }
294 return false;
295}
296
297static unsigned getPHISrcRegOpIdx(MachineInstr *MI, MachineBasicBlock *SrcBB) {
298 for (unsigned i = 1, e = MI->getNumOperands(); i != e; i += 2)
299 if (MI->getOperand(i + 1).getMBB() == SrcBB)
300 return i;
301 return 0;
302}
303
304// Remember which registers are used by phis in this block. This is
305// used to determine which registers are liveout while modifying the
306// block (which is why we need to copy the information).
307static void getRegsUsedByPHIs(const MachineBasicBlock &BB,
308 DenseSet<unsigned> *UsedByPhi) {
309 for (const auto &MI : BB) {
310 if (!MI.isPHI())
311 break;
312 for (unsigned i = 1, e = MI.getNumOperands(); i != e; i += 2) {
313 unsigned SrcReg = MI.getOperand(i).getReg();
314 UsedByPhi->insert(SrcReg);
315 }
316 }
317}
318
319/// Add a definition and source virtual registers pair for SSA update.
320void TailDuplicator::addSSAUpdateEntry(unsigned OrigReg, unsigned NewReg,
321 MachineBasicBlock *BB) {
322 DenseMap<unsigned, AvailableValsTy>::iterator LI =
323 SSAUpdateVals.find(OrigReg);
324 if (LI != SSAUpdateVals.end())
325 LI->second.push_back(std::make_pair(BB, NewReg));
326 else {
327 AvailableValsTy Vals;
328 Vals.push_back(std::make_pair(BB, NewReg));
329 SSAUpdateVals.insert(std::make_pair(OrigReg, Vals));
330 SSAUpdateVRs.push_back(OrigReg);
331 }
332}
333
334/// Process PHI node in TailBB by turning it into a copy in PredBB. Remember the
335/// source register that's contributed by PredBB and update SSA update map.
336void TailDuplicator::processPHI(
337 MachineInstr *MI, MachineBasicBlock *TailBB, MachineBasicBlock *PredBB,
Krzysztof Parzyszek4773f642016-04-26 18:36:34 +0000338 DenseMap<unsigned, RegSubRegPair> &LocalVRMap,
339 SmallVectorImpl<std::pair<unsigned, RegSubRegPair>> &Copies,
Kyle Butt3232dbb2016-04-08 20:35:01 +0000340 const DenseSet<unsigned> &RegsUsedByPhi, bool Remove) {
341 unsigned DefReg = MI->getOperand(0).getReg();
342 unsigned SrcOpIdx = getPHISrcRegOpIdx(MI, PredBB);
343 assert(SrcOpIdx && "Unable to find matching PHI source?");
344 unsigned SrcReg = MI->getOperand(SrcOpIdx).getReg();
Krzysztof Parzyszek4773f642016-04-26 18:36:34 +0000345 unsigned SrcSubReg = MI->getOperand(SrcOpIdx).getSubReg();
Kyle Butt3232dbb2016-04-08 20:35:01 +0000346 const TargetRegisterClass *RC = MRI->getRegClass(DefReg);
Krzysztof Parzyszek4773f642016-04-26 18:36:34 +0000347 LocalVRMap.insert(std::make_pair(DefReg, RegSubRegPair(SrcReg, SrcSubReg)));
Kyle Butt3232dbb2016-04-08 20:35:01 +0000348
349 // Insert a copy from source to the end of the block. The def register is the
350 // available value liveout of the block.
351 unsigned NewDef = MRI->createVirtualRegister(RC);
Krzysztof Parzyszek4773f642016-04-26 18:36:34 +0000352 Copies.push_back(std::make_pair(NewDef, RegSubRegPair(SrcReg, SrcSubReg)));
Kyle Butt3232dbb2016-04-08 20:35:01 +0000353 if (isDefLiveOut(DefReg, TailBB, MRI) || RegsUsedByPhi.count(DefReg))
354 addSSAUpdateEntry(DefReg, NewDef, PredBB);
355
356 if (!Remove)
357 return;
358
359 // Remove PredBB from the PHI node.
360 MI->RemoveOperand(SrcOpIdx + 1);
361 MI->RemoveOperand(SrcOpIdx);
362 if (MI->getNumOperands() == 1)
363 MI->eraseFromParent();
364}
365
366/// Duplicate a TailBB instruction to PredBB and update
367/// the source operands due to earlier PHI translation.
368void TailDuplicator::duplicateInstruction(
369 MachineInstr *MI, MachineBasicBlock *TailBB, MachineBasicBlock *PredBB,
Krzysztof Parzyszek4773f642016-04-26 18:36:34 +0000370 DenseMap<unsigned, RegSubRegPair> &LocalVRMap,
Kyle Butt3232dbb2016-04-08 20:35:01 +0000371 const DenseSet<unsigned> &UsedByPhi) {
Kyle Butt3ed42732016-08-25 01:37:03 +0000372 MachineInstr *NewMI = TII->duplicate(*MI, *MF);
Kyle Butt3232dbb2016-04-08 20:35:01 +0000373 if (PreRegAlloc) {
374 for (unsigned i = 0, e = NewMI->getNumOperands(); i != e; ++i) {
375 MachineOperand &MO = NewMI->getOperand(i);
376 if (!MO.isReg())
377 continue;
378 unsigned Reg = MO.getReg();
379 if (!TargetRegisterInfo::isVirtualRegister(Reg))
380 continue;
381 if (MO.isDef()) {
382 const TargetRegisterClass *RC = MRI->getRegClass(Reg);
383 unsigned NewReg = MRI->createVirtualRegister(RC);
384 MO.setReg(NewReg);
Krzysztof Parzyszek4773f642016-04-26 18:36:34 +0000385 LocalVRMap.insert(std::make_pair(Reg, RegSubRegPair(NewReg, 0)));
Kyle Butt3232dbb2016-04-08 20:35:01 +0000386 if (isDefLiveOut(Reg, TailBB, MRI) || UsedByPhi.count(Reg))
387 addSSAUpdateEntry(Reg, NewReg, PredBB);
388 } else {
Krzysztof Parzyszek4773f642016-04-26 18:36:34 +0000389 auto VI = LocalVRMap.find(Reg);
Kyle Butt3232dbb2016-04-08 20:35:01 +0000390 if (VI != LocalVRMap.end()) {
Krzysztof Parzyszek4773f642016-04-26 18:36:34 +0000391 // Need to make sure that the register class of the mapped register
392 // will satisfy the constraints of the class of the register being
393 // replaced.
394 auto *OrigRC = MRI->getRegClass(Reg);
395 auto *MappedRC = MRI->getRegClass(VI->second.Reg);
396 const TargetRegisterClass *ConstrRC;
397 if (VI->second.SubReg != 0) {
398 ConstrRC = TRI->getMatchingSuperRegClass(MappedRC, OrigRC,
399 VI->second.SubReg);
400 if (ConstrRC) {
401 // The actual constraining (as in "find appropriate new class")
402 // is done by getMatchingSuperRegClass, so now we only need to
403 // change the class of the mapped register.
404 MRI->setRegClass(VI->second.Reg, ConstrRC);
405 }
406 } else {
407 // For mapped registers that do not have sub-registers, simply
408 // restrict their class to match the original one.
409 ConstrRC = MRI->constrainRegClass(VI->second.Reg, OrigRC);
410 }
411
412 if (ConstrRC) {
413 // If the class constraining succeeded, we can simply replace
414 // the old register with the mapped one.
415 MO.setReg(VI->second.Reg);
416 // We have Reg -> VI.Reg:VI.SubReg, so if Reg is used with a
417 // sub-register, we need to compose the sub-register indices.
418 MO.setSubReg(TRI->composeSubRegIndices(MO.getSubReg(),
419 VI->second.SubReg));
420 } else {
421 // The direct replacement is not possible, due to failing register
422 // class constraints. An explicit COPY is necessary. Create one
423 // that can be reused
424 auto *NewRC = MI->getRegClassConstraint(i, TII, TRI);
425 if (NewRC == nullptr)
426 NewRC = OrigRC;
427 unsigned NewReg = MRI->createVirtualRegister(NewRC);
428 BuildMI(*PredBB, MI, MI->getDebugLoc(),
429 TII->get(TargetOpcode::COPY), NewReg)
430 .addReg(VI->second.Reg, 0, VI->second.SubReg);
431 LocalVRMap.erase(VI);
432 LocalVRMap.insert(std::make_pair(Reg, RegSubRegPair(NewReg, 0)));
433 MO.setReg(NewReg);
434 // The composed VI.Reg:VI.SubReg is replaced with NewReg, which
435 // is equivalent to the whole register Reg. Hence, Reg:subreg
436 // is same as NewReg:subreg, so keep the sub-register index
437 // unchanged.
438 }
Kyle Butt3232dbb2016-04-08 20:35:01 +0000439 // Clear any kill flags from this operand. The new register could
440 // have uses after this one, so kills are not valid here.
441 MO.setIsKill(false);
Kyle Butt3232dbb2016-04-08 20:35:01 +0000442 }
443 }
444 }
445 }
446 PredBB->insert(PredBB->instr_end(), NewMI);
447}
448
449/// After FromBB is tail duplicated into its predecessor blocks, the successors
450/// have gained new predecessors. Update the PHI instructions in them
451/// accordingly.
452void TailDuplicator::updateSuccessorsPHIs(
453 MachineBasicBlock *FromBB, bool isDead,
454 SmallVectorImpl<MachineBasicBlock *> &TDBBs,
455 SmallSetVector<MachineBasicBlock *, 8> &Succs) {
Matt Arsenaultb8037a12016-08-16 20:38:05 +0000456 for (MachineBasicBlock *SuccBB : Succs) {
457 for (MachineInstr &MI : *SuccBB) {
458 if (!MI.isPHI())
Kyle Butt3232dbb2016-04-08 20:35:01 +0000459 break;
Matt Arsenaultb8037a12016-08-16 20:38:05 +0000460 MachineInstrBuilder MIB(*FromBB->getParent(), MI);
Kyle Butt3232dbb2016-04-08 20:35:01 +0000461 unsigned Idx = 0;
Matt Arsenaultb8037a12016-08-16 20:38:05 +0000462 for (unsigned i = 1, e = MI.getNumOperands(); i != e; i += 2) {
463 MachineOperand &MO = MI.getOperand(i + 1);
Kyle Butt3232dbb2016-04-08 20:35:01 +0000464 if (MO.getMBB() == FromBB) {
465 Idx = i;
466 break;
467 }
468 }
469
470 assert(Idx != 0);
Matt Arsenaultb8037a12016-08-16 20:38:05 +0000471 MachineOperand &MO0 = MI.getOperand(Idx);
Kyle Butt3232dbb2016-04-08 20:35:01 +0000472 unsigned Reg = MO0.getReg();
473 if (isDead) {
474 // Folded into the previous BB.
475 // There could be duplicate phi source entries. FIXME: Should sdisel
476 // or earlier pass fixed this?
Matt Arsenaultb8037a12016-08-16 20:38:05 +0000477 for (unsigned i = MI.getNumOperands() - 2; i != Idx; i -= 2) {
478 MachineOperand &MO = MI.getOperand(i + 1);
Kyle Butt3232dbb2016-04-08 20:35:01 +0000479 if (MO.getMBB() == FromBB) {
Matt Arsenaultb8037a12016-08-16 20:38:05 +0000480 MI.RemoveOperand(i + 1);
481 MI.RemoveOperand(i);
Kyle Butt3232dbb2016-04-08 20:35:01 +0000482 }
483 }
484 } else
485 Idx = 0;
486
487 // If Idx is set, the operands at Idx and Idx+1 must be removed.
488 // We reuse the location to avoid expensive RemoveOperand calls.
489
490 DenseMap<unsigned, AvailableValsTy>::iterator LI =
491 SSAUpdateVals.find(Reg);
492 if (LI != SSAUpdateVals.end()) {
493 // This register is defined in the tail block.
494 for (unsigned j = 0, ee = LI->second.size(); j != ee; ++j) {
495 MachineBasicBlock *SrcBB = LI->second[j].first;
496 // If we didn't duplicate a bb into a particular predecessor, we
497 // might still have added an entry to SSAUpdateVals to correcly
498 // recompute SSA. If that case, avoid adding a dummy extra argument
499 // this PHI.
500 if (!SrcBB->isSuccessor(SuccBB))
501 continue;
502
503 unsigned SrcReg = LI->second[j].second;
504 if (Idx != 0) {
Matt Arsenaultb8037a12016-08-16 20:38:05 +0000505 MI.getOperand(Idx).setReg(SrcReg);
506 MI.getOperand(Idx + 1).setMBB(SrcBB);
Kyle Butt3232dbb2016-04-08 20:35:01 +0000507 Idx = 0;
508 } else {
509 MIB.addReg(SrcReg).addMBB(SrcBB);
510 }
511 }
512 } else {
513 // Live in tail block, must also be live in predecessors.
514 for (unsigned j = 0, ee = TDBBs.size(); j != ee; ++j) {
515 MachineBasicBlock *SrcBB = TDBBs[j];
516 if (Idx != 0) {
Matt Arsenaultb8037a12016-08-16 20:38:05 +0000517 MI.getOperand(Idx).setReg(Reg);
518 MI.getOperand(Idx + 1).setMBB(SrcBB);
Kyle Butt3232dbb2016-04-08 20:35:01 +0000519 Idx = 0;
520 } else {
521 MIB.addReg(Reg).addMBB(SrcBB);
522 }
523 }
524 }
525 if (Idx != 0) {
Matt Arsenaultb8037a12016-08-16 20:38:05 +0000526 MI.RemoveOperand(Idx + 1);
527 MI.RemoveOperand(Idx);
Kyle Butt3232dbb2016-04-08 20:35:01 +0000528 }
529 }
530 }
531}
532
533/// Determine if it is profitable to duplicate this block.
Kyle Butt3ed42732016-08-25 01:37:03 +0000534bool TailDuplicator::shouldTailDuplicate(bool IsSimple,
Kyle Butt3232dbb2016-04-08 20:35:01 +0000535 MachineBasicBlock &TailBB) {
Kyle Butt0846e562016-10-11 20:36:43 +0000536 // When doing tail-duplication during layout, the block ordering is in flux,
537 // so canFallThrough returns a result based on incorrect information and
538 // should just be ignored.
539 if (!LayoutMode && TailBB.canFallThrough())
Kyle Butt3232dbb2016-04-08 20:35:01 +0000540 return false;
541
542 // Don't try to tail-duplicate single-block loops.
543 if (TailBB.isSuccessor(&TailBB))
544 return false;
545
546 // Set the limit on the cost to duplicate. When optimizing for size,
547 // duplicate only one, because one branch instruction can be eliminated to
548 // compensate for the duplication.
549 unsigned MaxDuplicateCount;
Kyle Buttdb3391e2016-08-17 21:07:35 +0000550 if (TailDupSize == 0 &&
551 TailDuplicateSize.getNumOccurrences() == 0 &&
Kyle Butt3ed42732016-08-25 01:37:03 +0000552 MF->getFunction()->optForSize())
Kyle Butt3232dbb2016-04-08 20:35:01 +0000553 MaxDuplicateCount = 1;
Kyle Buttdb3391e2016-08-17 21:07:35 +0000554 else if (TailDupSize == 0)
Kyle Butt3232dbb2016-04-08 20:35:01 +0000555 MaxDuplicateCount = TailDuplicateSize;
Kyle Buttdb3391e2016-08-17 21:07:35 +0000556 else
557 MaxDuplicateCount = TailDupSize;
Kyle Butt3232dbb2016-04-08 20:35:01 +0000558
Kyle Butt07d61422016-08-16 22:56:14 +0000559 // If the block to be duplicated ends in an unanalyzable fallthrough, don't
560 // duplicate it.
561 // A similar check is necessary in MachineBlockPlacement to make sure pairs of
562 // blocks with unanalyzable fallthrough get layed out contiguously.
563 MachineBasicBlock *PredTBB = nullptr, *PredFBB = nullptr;
564 SmallVector<MachineOperand, 4> PredCond;
Sanjoy Dasd7389d62016-12-15 05:08:57 +0000565 if (TII->analyzeBranch(TailBB, PredTBB, PredFBB, PredCond) &&
566 TailBB.canFallThrough())
Kyle Butt07d61422016-08-16 22:56:14 +0000567 return false;
568
Kyle Butt3232dbb2016-04-08 20:35:01 +0000569 // If the target has hardware branch prediction that can handle indirect
570 // branches, duplicating them can often make them predictable when there
571 // are common paths through the code. The limit needs to be high enough
572 // to allow undoing the effects of tail merging and other optimizations
573 // that rearrange the predecessors of the indirect branch.
574
575 bool HasIndirectbr = false;
576 if (!TailBB.empty())
577 HasIndirectbr = TailBB.back().isIndirectBranch();
578
579 if (HasIndirectbr && PreRegAlloc)
Kyle Butt61aca6e2016-08-30 18:18:54 +0000580 MaxDuplicateCount = TailDupIndirectBranchSize;
Kyle Butt3232dbb2016-04-08 20:35:01 +0000581
582 // Check the instructions in the block to determine whether tail-duplication
583 // is invalid or unlikely to be profitable.
584 unsigned InstrCount = 0;
585 for (MachineInstr &MI : TailBB) {
586 // Non-duplicable things shouldn't be tail-duplicated.
587 if (MI.isNotDuplicable())
588 return false;
589
590 // Convergent instructions can be duplicated only if doing so doesn't add
591 // new control dependencies, which is what we're going to do here.
592 if (MI.isConvergent())
593 return false;
594
595 // Do not duplicate 'return' instructions if this is a pre-regalloc run.
596 // A return may expand into a lot more instructions (e.g. reload of callee
597 // saved registers) after PEI.
598 if (PreRegAlloc && MI.isReturn())
599 return false;
600
601 // Avoid duplicating calls before register allocation. Calls presents a
602 // barrier to register allocation so duplicating them may end up increasing
603 // spills.
604 if (PreRegAlloc && MI.isCall())
605 return false;
606
607 if (!MI.isPHI() && !MI.isDebugValue())
608 InstrCount += 1;
609
610 if (InstrCount > MaxDuplicateCount)
611 return false;
612 }
613
614 // Check if any of the successors of TailBB has a PHI node in which the
615 // value corresponding to TailBB uses a subregister.
616 // If a phi node uses a register paired with a subregister, the actual
617 // "value type" of the phi may differ from the type of the register without
618 // any subregisters. Due to a bug, tail duplication may add a new operand
619 // without a necessary subregister, producing an invalid code. This is
620 // demonstrated by test/CodeGen/Hexagon/tail-dup-subreg-abort.ll.
621 // Disable tail duplication for this case for now, until the problem is
622 // fixed.
623 for (auto SB : TailBB.successors()) {
624 for (auto &I : *SB) {
625 if (!I.isPHI())
626 break;
627 unsigned Idx = getPHISrcRegOpIdx(&I, &TailBB);
628 assert(Idx != 0);
629 MachineOperand &PU = I.getOperand(Idx);
630 if (PU.getSubReg() != 0)
631 return false;
632 }
633 }
634
635 if (HasIndirectbr && PreRegAlloc)
636 return true;
637
638 if (IsSimple)
639 return true;
640
641 if (!PreRegAlloc)
642 return true;
643
644 return canCompletelyDuplicateBB(TailBB);
645}
646
647/// True if this BB has only one unconditional jump.
648bool TailDuplicator::isSimpleBB(MachineBasicBlock *TailBB) {
649 if (TailBB->succ_size() != 1)
650 return false;
651 if (TailBB->pred_empty())
652 return false;
653 MachineBasicBlock::iterator I = TailBB->getFirstNonDebugInstr();
654 if (I == TailBB->end())
655 return true;
656 return I->isUnconditionalBranch();
657}
658
659static bool bothUsedInPHI(const MachineBasicBlock &A,
Benjamin Kramerbdc49562016-06-12 15:39:02 +0000660 const SmallPtrSet<MachineBasicBlock *, 8> &SuccsB) {
Kyle Butt3232dbb2016-04-08 20:35:01 +0000661 for (MachineBasicBlock *BB : A.successors())
662 if (SuccsB.count(BB) && !BB->empty() && BB->begin()->isPHI())
663 return true;
664
665 return false;
666}
667
668bool TailDuplicator::canCompletelyDuplicateBB(MachineBasicBlock &BB) {
669 for (MachineBasicBlock *PredBB : BB.predecessors()) {
670 if (PredBB->succ_size() > 1)
671 return false;
672
673 MachineBasicBlock *PredTBB = nullptr, *PredFBB = nullptr;
674 SmallVector<MachineOperand, 4> PredCond;
Sanjoy Dasd7389d62016-12-15 05:08:57 +0000675 if (TII->analyzeBranch(*PredBB, PredTBB, PredFBB, PredCond))
Kyle Butt3232dbb2016-04-08 20:35:01 +0000676 return false;
677
678 if (!PredCond.empty())
679 return false;
680 }
681 return true;
682}
683
684bool TailDuplicator::duplicateSimpleBB(
685 MachineBasicBlock *TailBB, SmallVectorImpl<MachineBasicBlock *> &TDBBs,
686 const DenseSet<unsigned> &UsedByPhi,
687 SmallVectorImpl<MachineInstr *> &Copies) {
688 SmallPtrSet<MachineBasicBlock *, 8> Succs(TailBB->succ_begin(),
689 TailBB->succ_end());
690 SmallVector<MachineBasicBlock *, 8> Preds(TailBB->pred_begin(),
691 TailBB->pred_end());
692 bool Changed = false;
Matt Arsenaultb8037a12016-08-16 20:38:05 +0000693 for (MachineBasicBlock *PredBB : Preds) {
Kyle Butt3232dbb2016-04-08 20:35:01 +0000694 if (PredBB->hasEHPadSuccessor())
695 continue;
696
697 if (bothUsedInPHI(*PredBB, Succs))
698 continue;
699
700 MachineBasicBlock *PredTBB = nullptr, *PredFBB = nullptr;
701 SmallVector<MachineOperand, 4> PredCond;
Sanjoy Dasd7389d62016-12-15 05:08:57 +0000702 if (TII->analyzeBranch(*PredBB, PredTBB, PredFBB, PredCond))
Kyle Butt3232dbb2016-04-08 20:35:01 +0000703 continue;
704
705 Changed = true;
706 DEBUG(dbgs() << "\nTail-duplicating into PredBB: " << *PredBB
707 << "From simple Succ: " << *TailBB);
708
709 MachineBasicBlock *NewTarget = *TailBB->succ_begin();
Matthias Braun6442fc12016-08-18 00:59:32 +0000710 MachineBasicBlock *NextBB = PredBB->getNextNode();
Kyle Butt3232dbb2016-04-08 20:35:01 +0000711
712 // Make PredFBB explicit.
713 if (PredCond.empty())
714 PredFBB = PredTBB;
715
716 // Make fall through explicit.
717 if (!PredTBB)
718 PredTBB = NextBB;
719 if (!PredFBB)
720 PredFBB = NextBB;
721
722 // Redirect
723 if (PredFBB == TailBB)
724 PredFBB = NewTarget;
725 if (PredTBB == TailBB)
726 PredTBB = NewTarget;
727
728 // Make the branch unconditional if possible
729 if (PredTBB == PredFBB) {
730 PredCond.clear();
731 PredFBB = nullptr;
732 }
733
734 // Avoid adding fall through branches.
735 if (PredFBB == NextBB)
736 PredFBB = nullptr;
737 if (PredTBB == NextBB && PredFBB == nullptr)
738 PredTBB = nullptr;
739
Taewook Oha49eb852017-02-27 19:30:01 +0000740 auto DL = PredBB->findBranchDebugLoc();
Matt Arsenault1b9fc8e2016-09-14 20:43:16 +0000741 TII->removeBranch(*PredBB);
Kyle Butt3232dbb2016-04-08 20:35:01 +0000742
743 if (!PredBB->isSuccessor(NewTarget))
744 PredBB->replaceSuccessor(TailBB, NewTarget);
745 else {
746 PredBB->removeSuccessor(TailBB, true);
747 assert(PredBB->succ_size() <= 1);
748 }
749
750 if (PredTBB)
Taewook Oha49eb852017-02-27 19:30:01 +0000751 TII->insertBranch(*PredBB, PredTBB, PredFBB, PredCond, DL);
Kyle Butt3232dbb2016-04-08 20:35:01 +0000752
753 TDBBs.push_back(PredBB);
754 }
755 return Changed;
756}
757
Kyle Butt9e52c062016-07-19 23:54:21 +0000758bool TailDuplicator::canTailDuplicate(MachineBasicBlock *TailBB,
759 MachineBasicBlock *PredBB) {
Kyle Butt0846e562016-10-11 20:36:43 +0000760 // EH edges are ignored by analyzeBranch.
Kyle Butt9e52c062016-07-19 23:54:21 +0000761 if (PredBB->succ_size() > 1)
762 return false;
763
Vitaly Bukab238cb82017-05-22 21:33:54 +0000764 MachineBasicBlock *PredTBB = nullptr, *PredFBB = nullptr;
Kyle Butt9e52c062016-07-19 23:54:21 +0000765 SmallVector<MachineOperand, 4> PredCond;
Sanjoy Dasd7389d62016-12-15 05:08:57 +0000766 if (TII->analyzeBranch(*PredBB, PredTBB, PredFBB, PredCond))
Kyle Butt9e52c062016-07-19 23:54:21 +0000767 return false;
768 if (!PredCond.empty())
769 return false;
770 return true;
771}
772
Kyle Butt3232dbb2016-04-08 20:35:01 +0000773/// If it is profitable, duplicate TailBB's contents in each
774/// of its predecessors.
Kyle Butt0846e562016-10-11 20:36:43 +0000775/// \p IsSimple result of isSimpleBB
776/// \p TailBB Block to be duplicated.
777/// \p ForcedLayoutPred When non-null, use this block as the layout predecessor
778/// instead of the previous block in MF's order.
779/// \p TDBBs A vector to keep track of all blocks tail-duplicated
780/// into.
781/// \p Copies A vector of copy instructions inserted. Used later to
782/// walk all the inserted copies and remove redundant ones.
Kyle Butt3ed42732016-08-25 01:37:03 +0000783bool TailDuplicator::tailDuplicate(bool IsSimple, MachineBasicBlock *TailBB,
Kyle Butt0846e562016-10-11 20:36:43 +0000784 MachineBasicBlock *ForcedLayoutPred,
Kyle Butt3232dbb2016-04-08 20:35:01 +0000785 SmallVectorImpl<MachineBasicBlock *> &TDBBs,
786 SmallVectorImpl<MachineInstr *> &Copies) {
787 DEBUG(dbgs() << "\n*** Tail-duplicating BB#" << TailBB->getNumber() << '\n');
788
789 DenseSet<unsigned> UsedByPhi;
790 getRegsUsedByPHIs(*TailBB, &UsedByPhi);
791
792 if (IsSimple)
793 return duplicateSimpleBB(TailBB, TDBBs, UsedByPhi, Copies);
794
795 // Iterate through all the unique predecessors and tail-duplicate this
796 // block into them, if possible. Copying the list ahead of time also
797 // avoids trouble with the predecessor list reallocating.
798 bool Changed = false;
799 SmallSetVector<MachineBasicBlock *, 8> Preds(TailBB->pred_begin(),
800 TailBB->pred_end());
Matt Arsenaultb8037a12016-08-16 20:38:05 +0000801 for (MachineBasicBlock *PredBB : Preds) {
Kyle Butt3232dbb2016-04-08 20:35:01 +0000802 assert(TailBB != PredBB &&
803 "Single-block loop should have been rejected earlier!");
Kyle Butt9e52c062016-07-19 23:54:21 +0000804
805 if (!canTailDuplicate(TailBB, PredBB))
Kyle Butt3232dbb2016-04-08 20:35:01 +0000806 continue;
807
Kyle Butt3232dbb2016-04-08 20:35:01 +0000808 // Don't duplicate into a fall-through predecessor (at least for now).
Kyle Butt0846e562016-10-11 20:36:43 +0000809 bool IsLayoutSuccessor = false;
810 if (ForcedLayoutPred)
811 IsLayoutSuccessor = (ForcedLayoutPred == PredBB);
812 else if (PredBB->isLayoutSuccessor(TailBB) && PredBB->canFallThrough())
813 IsLayoutSuccessor = true;
814 if (IsLayoutSuccessor)
Kyle Butt3232dbb2016-04-08 20:35:01 +0000815 continue;
816
817 DEBUG(dbgs() << "\nTail-duplicating into PredBB: " << *PredBB
818 << "From Succ: " << *TailBB);
819
820 TDBBs.push_back(PredBB);
821
822 // Remove PredBB's unconditional branch.
Matt Arsenault1b9fc8e2016-09-14 20:43:16 +0000823 TII->removeBranch(*PredBB);
Kyle Butt3232dbb2016-04-08 20:35:01 +0000824
Kyle Butt3232dbb2016-04-08 20:35:01 +0000825 // Clone the contents of TailBB into PredBB.
Krzysztof Parzyszek4773f642016-04-26 18:36:34 +0000826 DenseMap<unsigned, RegSubRegPair> LocalVRMap;
827 SmallVector<std::pair<unsigned, RegSubRegPair>, 4> CopyInfos;
Kyle Butt3232dbb2016-04-08 20:35:01 +0000828 // Use instr_iterator here to properly handle bundles, e.g.
829 // ARM Thumb2 IT block.
830 MachineBasicBlock::instr_iterator I = TailBB->instr_begin();
831 while (I != TailBB->instr_end()) {
832 MachineInstr *MI = &*I;
833 ++I;
834 if (MI->isPHI()) {
835 // Replace the uses of the def of the PHI with the register coming
836 // from PredBB.
837 processPHI(MI, TailBB, PredBB, LocalVRMap, CopyInfos, UsedByPhi, true);
838 } else {
839 // Replace def of virtual registers with new registers, and update
840 // uses with PHI source register or the new registers.
Kyle Butt3ed42732016-08-25 01:37:03 +0000841 duplicateInstruction(MI, TailBB, PredBB, LocalVRMap, UsedByPhi);
Kyle Butt3232dbb2016-04-08 20:35:01 +0000842 }
843 }
Krzysztof Parzyszek4773f642016-04-26 18:36:34 +0000844 appendCopies(PredBB, CopyInfos, Copies);
Kyle Butt3232dbb2016-04-08 20:35:01 +0000845
846 // Simplify
Vitaly Bukab238cb82017-05-22 21:33:54 +0000847 MachineBasicBlock *PredTBB = nullptr, *PredFBB = nullptr;
Kyle Butt9e52c062016-07-19 23:54:21 +0000848 SmallVector<MachineOperand, 4> PredCond;
Sanjoy Dasd7389d62016-12-15 05:08:57 +0000849 TII->analyzeBranch(*PredBB, PredTBB, PredFBB, PredCond);
Kyle Butt3232dbb2016-04-08 20:35:01 +0000850
Geoff Berryf8c29d62016-06-14 19:40:10 +0000851 NumTailDupAdded += TailBB->size() - 1; // subtract one for removed branch
Kyle Butt3232dbb2016-04-08 20:35:01 +0000852
853 // Update the CFG.
854 PredBB->removeSuccessor(PredBB->succ_begin());
855 assert(PredBB->succ_empty() &&
856 "TailDuplicate called on block with multiple successors!");
Matt Arsenaultb8037a12016-08-16 20:38:05 +0000857 for (MachineBasicBlock *Succ : TailBB->successors())
858 PredBB->addSuccessor(Succ, MBPI->getEdgeProbability(TailBB, Succ));
Kyle Butt3232dbb2016-04-08 20:35:01 +0000859
860 Changed = true;
861 ++NumTailDups;
862 }
863
864 // If TailBB was duplicated into all its predecessors except for the prior
865 // block, which falls through unconditionally, move the contents of this
866 // block into the prior block.
Kyle Butt0846e562016-10-11 20:36:43 +0000867 MachineBasicBlock *PrevBB = ForcedLayoutPred;
868 if (!PrevBB)
869 PrevBB = &*std::prev(TailBB->getIterator());
Kyle Butt3232dbb2016-04-08 20:35:01 +0000870 MachineBasicBlock *PriorTBB = nullptr, *PriorFBB = nullptr;
871 SmallVector<MachineOperand, 4> PriorCond;
872 // This has to check PrevBB->succ_size() because EH edges are ignored by
Kyle Butt0846e562016-10-11 20:36:43 +0000873 // analyzeBranch.
Kyle Butt3232dbb2016-04-08 20:35:01 +0000874 if (PrevBB->succ_size() == 1 &&
Kyle Buttd2b886e2016-07-20 00:01:51 +0000875 // Layout preds are not always CFG preds. Check.
876 *PrevBB->succ_begin() == TailBB &&
Sanjoy Dasd7389d62016-12-15 05:08:57 +0000877 !TII->analyzeBranch(*PrevBB, PriorTBB, PriorFBB, PriorCond) &&
Kyle Butt0846e562016-10-11 20:36:43 +0000878 PriorCond.empty() &&
879 (!PriorTBB || PriorTBB == TailBB) &&
880 TailBB->pred_size() == 1 &&
Kyle Butt3232dbb2016-04-08 20:35:01 +0000881 !TailBB->hasAddressTaken()) {
882 DEBUG(dbgs() << "\nMerging into block: " << *PrevBB
883 << "From MBB: " << *TailBB);
Kyle Butt0846e562016-10-11 20:36:43 +0000884 // There may be a branch to the layout successor. This is unlikely but it
885 // happens. The correct thing to do is to remove the branch before
886 // duplicating the instructions in all cases.
887 TII->removeBranch(*PrevBB);
Kyle Butt3232dbb2016-04-08 20:35:01 +0000888 if (PreRegAlloc) {
Krzysztof Parzyszek4773f642016-04-26 18:36:34 +0000889 DenseMap<unsigned, RegSubRegPair> LocalVRMap;
890 SmallVector<std::pair<unsigned, RegSubRegPair>, 4> CopyInfos;
Kyle Butt3232dbb2016-04-08 20:35:01 +0000891 MachineBasicBlock::iterator I = TailBB->begin();
892 // Process PHI instructions first.
893 while (I != TailBB->end() && I->isPHI()) {
894 // Replace the uses of the def of the PHI with the register coming
895 // from PredBB.
896 MachineInstr *MI = &*I++;
897 processPHI(MI, TailBB, PrevBB, LocalVRMap, CopyInfos, UsedByPhi, true);
Kyle Butt3232dbb2016-04-08 20:35:01 +0000898 }
899
900 // Now copy the non-PHI instructions.
901 while (I != TailBB->end()) {
902 // Replace def of virtual registers with new registers, and update
903 // uses with PHI source register or the new registers.
904 MachineInstr *MI = &*I++;
905 assert(!MI->isBundle() && "Not expecting bundles before regalloc!");
Kyle Butt3ed42732016-08-25 01:37:03 +0000906 duplicateInstruction(MI, TailBB, PrevBB, LocalVRMap, UsedByPhi);
Kyle Butt3232dbb2016-04-08 20:35:01 +0000907 MI->eraseFromParent();
908 }
Krzysztof Parzyszek4773f642016-04-26 18:36:34 +0000909 appendCopies(PrevBB, CopyInfos, Copies);
Kyle Butt3232dbb2016-04-08 20:35:01 +0000910 } else {
Kyle Butt0846e562016-10-11 20:36:43 +0000911 TII->removeBranch(*PrevBB);
Kyle Butt3232dbb2016-04-08 20:35:01 +0000912 // No PHIs to worry about, just splice the instructions over.
913 PrevBB->splice(PrevBB->end(), TailBB, TailBB->begin(), TailBB->end());
914 }
915 PrevBB->removeSuccessor(PrevBB->succ_begin());
916 assert(PrevBB->succ_empty());
917 PrevBB->transferSuccessors(TailBB);
918 TDBBs.push_back(PrevBB);
919 Changed = true;
920 }
921
922 // If this is after register allocation, there are no phis to fix.
923 if (!PreRegAlloc)
924 return Changed;
925
926 // If we made no changes so far, we are safe.
927 if (!Changed)
928 return Changed;
929
930 // Handle the nasty case in that we duplicated a block that is part of a loop
931 // into some but not all of its predecessors. For example:
932 // 1 -> 2 <-> 3 |
933 // \ |
934 // \---> rest |
935 // if we duplicate 2 into 1 but not into 3, we end up with
936 // 12 -> 3 <-> 2 -> rest |
937 // \ / |
938 // \----->-----/ |
939 // If there was a "var = phi(1, 3)" in 2, it has to be ultimately replaced
940 // with a phi in 3 (which now dominates 2).
941 // What we do here is introduce a copy in 3 of the register defined by the
942 // phi, just like when we are duplicating 2 into 3, but we don't copy any
943 // real instructions or remove the 3 -> 2 edge from the phi in 2.
Matt Arsenaultb8037a12016-08-16 20:38:05 +0000944 for (MachineBasicBlock *PredBB : Preds) {
David Majnemer0d955d02016-08-11 22:21:41 +0000945 if (is_contained(TDBBs, PredBB))
Kyle Butt3232dbb2016-04-08 20:35:01 +0000946 continue;
947
948 // EH edges
949 if (PredBB->succ_size() != 1)
950 continue;
951
Krzysztof Parzyszek4773f642016-04-26 18:36:34 +0000952 DenseMap<unsigned, RegSubRegPair> LocalVRMap;
953 SmallVector<std::pair<unsigned, RegSubRegPair>, 4> CopyInfos;
Kyle Butt3232dbb2016-04-08 20:35:01 +0000954 MachineBasicBlock::iterator I = TailBB->begin();
955 // Process PHI instructions first.
956 while (I != TailBB->end() && I->isPHI()) {
957 // Replace the uses of the def of the PHI with the register coming
958 // from PredBB.
959 MachineInstr *MI = &*I++;
960 processPHI(MI, TailBB, PredBB, LocalVRMap, CopyInfos, UsedByPhi, false);
961 }
Krzysztof Parzyszek4773f642016-04-26 18:36:34 +0000962 appendCopies(PredBB, CopyInfos, Copies);
Kyle Butt3232dbb2016-04-08 20:35:01 +0000963 }
964
965 return Changed;
966}
967
Krzysztof Parzyszek4773f642016-04-26 18:36:34 +0000968/// At the end of the block \p MBB generate COPY instructions between registers
969/// described by \p CopyInfos. Append resulting instructions to \p Copies.
970void TailDuplicator::appendCopies(MachineBasicBlock *MBB,
971 SmallVectorImpl<std::pair<unsigned,RegSubRegPair>> &CopyInfos,
972 SmallVectorImpl<MachineInstr*> &Copies) {
973 MachineBasicBlock::iterator Loc = MBB->getFirstTerminator();
974 const MCInstrDesc &CopyD = TII->get(TargetOpcode::COPY);
975 for (auto &CI : CopyInfos) {
976 auto C = BuildMI(*MBB, Loc, DebugLoc(), CopyD, CI.first)
977 .addReg(CI.second.Reg, 0, CI.second.SubReg);
978 Copies.push_back(C);
979 }
980}
981
Kyle Butt3232dbb2016-04-08 20:35:01 +0000982/// Remove the specified dead machine basic block from the function, updating
983/// the CFG.
Kyle Butt0846e562016-10-11 20:36:43 +0000984void TailDuplicator::removeDeadBlock(
985 MachineBasicBlock *MBB,
Eugene Zelenko6ac7a342017-06-07 23:53:32 +0000986 function_ref<void(MachineBasicBlock *)> *RemovalCallback) {
Kyle Butt3232dbb2016-04-08 20:35:01 +0000987 assert(MBB->pred_empty() && "MBB must be dead!");
988 DEBUG(dbgs() << "\nRemoving MBB: " << *MBB);
989
Kyle Butt0846e562016-10-11 20:36:43 +0000990 if (RemovalCallback)
991 (*RemovalCallback)(MBB);
992
Kyle Butt3232dbb2016-04-08 20:35:01 +0000993 // Remove all successors.
994 while (!MBB->succ_empty())
995 MBB->removeSuccessor(MBB->succ_end() - 1);
996
997 // Remove the block.
998 MBB->eraseFromParent();
999}