blob: 87db1647034bcfebbd095097195706daffc1be0b [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//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
Kyle Butt3232dbb2016-04-08 20:35:01 +00006//
7//===----------------------------------------------------------------------===//
8//
9// This utility class duplicates basic blocks ending in unconditional branches
10// into the tails of their predecessors.
11//
12//===----------------------------------------------------------------------===//
13
David Blaikie3f833ed2017-11-08 01:01:31 +000014#include "llvm/CodeGen/TailDuplicator.h"
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"
David Blaikie3f833ed2017-11-08 01:01:31 +000017#include "llvm/ADT/STLExtras.h"
Kyle Butt3232dbb2016-04-08 20:35:01 +000018#include "llvm/ADT/SetVector.h"
Eugene Zelenko6ac7a342017-06-07 23:53:32 +000019#include "llvm/ADT/SmallPtrSet.h"
20#include "llvm/ADT/SmallVector.h"
Kyle Butt3232dbb2016-04-08 20:35:01 +000021#include "llvm/ADT/Statistic.h"
Hiroshi Yamauchid9ae4932019-12-05 09:39:37 -080022#include "llvm/Analysis/ProfileSummaryInfo.h"
Eugene Zelenko6ac7a342017-06-07 23:53:32 +000023#include "llvm/CodeGen/MachineBasicBlock.h"
Kyle Butt3232dbb2016-04-08 20:35:01 +000024#include "llvm/CodeGen/MachineBranchProbabilityInfo.h"
Hiroshi Yamauchid9ae4932019-12-05 09:39:37 -080025#include "llvm/CodeGen/MachineBlockFrequencyInfo.h"
Eugene Zelenko6ac7a342017-06-07 23:53:32 +000026#include "llvm/CodeGen/MachineFunction.h"
27#include "llvm/CodeGen/MachineInstr.h"
Kyle Butt3232dbb2016-04-08 20:35:01 +000028#include "llvm/CodeGen/MachineInstrBuilder.h"
Eugene Zelenko6ac7a342017-06-07 23:53:32 +000029#include "llvm/CodeGen/MachineOperand.h"
30#include "llvm/CodeGen/MachineRegisterInfo.h"
Hiroshi Yamauchid9ae4932019-12-05 09:39:37 -080031#include "llvm/CodeGen/MachineSizeOpts.h"
Eugene Zelenko6ac7a342017-06-07 23:53:32 +000032#include "llvm/CodeGen/MachineSSAUpdater.h"
David Blaikie3f833ed2017-11-08 01:01:31 +000033#include "llvm/CodeGen/TargetInstrInfo.h"
David Blaikieb3bde2e2017-11-17 01:07:10 +000034#include "llvm/CodeGen/TargetRegisterInfo.h"
35#include "llvm/CodeGen/TargetSubtargetInfo.h"
Eugene Zelenko6ac7a342017-06-07 23:53:32 +000036#include "llvm/IR/DebugLoc.h"
Kyle Butt3232dbb2016-04-08 20:35:01 +000037#include "llvm/IR/Function.h"
38#include "llvm/Support/CommandLine.h"
39#include "llvm/Support/Debug.h"
40#include "llvm/Support/ErrorHandling.h"
41#include "llvm/Support/raw_ostream.h"
Petar Jovanovic540f4cd2018-01-31 15:57:57 +000042#include "llvm/Target/TargetMachine.h"
Eugene Zelenko6ac7a342017-06-07 23:53:32 +000043#include <algorithm>
44#include <cassert>
45#include <iterator>
46#include <utility>
47
Kyle Butt3232dbb2016-04-08 20:35:01 +000048using namespace llvm;
49
50#define DEBUG_TYPE "tailduplication"
51
52STATISTIC(NumTails, "Number of tails duplicated");
53STATISTIC(NumTailDups, "Number of tail duplicated blocks");
Geoff Berryf8c29d62016-06-14 19:40:10 +000054STATISTIC(NumTailDupAdded,
55 "Number of instructions added due to tail duplication");
56STATISTIC(NumTailDupRemoved,
57 "Number of instructions removed due to tail duplication");
Kyle Butt3232dbb2016-04-08 20:35:01 +000058STATISTIC(NumDeadBlocks, "Number of dead blocks removed");
59STATISTIC(NumAddedPHIs, "Number of phis added");
60
61// Heuristic for tail duplication.
62static cl::opt<unsigned> TailDuplicateSize(
63 "tail-dup-size",
64 cl::desc("Maximum instructions to consider tail duplicating"), cl::init(2),
65 cl::Hidden);
66
Eugene Zelenko6ac7a342017-06-07 23:53:32 +000067static cl::opt<unsigned> TailDupIndirectBranchSize(
Kyle Butt61aca6e2016-08-30 18:18:54 +000068 "tail-dup-indirect-size",
69 cl::desc("Maximum instructions to consider tail duplicating blocks that "
70 "end with indirect branches."), cl::init(20),
71 cl::Hidden);
72
Kyle Butt3232dbb2016-04-08 20:35:01 +000073static cl::opt<bool>
74 TailDupVerify("tail-dup-verify",
75 cl::desc("Verify sanity of PHI instructions during taildup"),
76 cl::init(false), cl::Hidden);
77
78static cl::opt<unsigned> TailDupLimit("tail-dup-limit", cl::init(~0U),
79 cl::Hidden);
80
Matthias Braun8426d132017-08-23 03:17:59 +000081void TailDuplicator::initMF(MachineFunction &MFin, bool PreRegAlloc,
Kyle Buttdb3391e2016-08-17 21:07:35 +000082 const MachineBranchProbabilityInfo *MBPIin,
Hiroshi Yamauchiac8da312020-01-29 09:36:31 -080083 MBFIWrapper *MBFIin,
Hiroshi Yamauchid9ae4932019-12-05 09:39:37 -080084 ProfileSummaryInfo *PSIin,
Kyle Butt0846e562016-10-11 20:36:43 +000085 bool LayoutModeIn, unsigned TailDupSizeIn) {
Kyle Butt3ed42732016-08-25 01:37:03 +000086 MF = &MFin;
87 TII = MF->getSubtarget().getInstrInfo();
88 TRI = MF->getSubtarget().getRegisterInfo();
89 MRI = &MF->getRegInfo();
Kyle Buttc7f1eac2016-08-25 01:37:07 +000090 MMI = &MF->getMMI();
Kyle Butt3232dbb2016-04-08 20:35:01 +000091 MBPI = MBPIin;
Hiroshi Yamauchid9ae4932019-12-05 09:39:37 -080092 MBFI = MBFIin;
93 PSI = PSIin;
Kyle Buttdb3391e2016-08-17 21:07:35 +000094 TailDupSize = TailDupSizeIn;
Kyle Butt3232dbb2016-04-08 20:35:01 +000095
96 assert(MBPI != nullptr && "Machine Branch Probability Info required");
97
Kyle Butt0846e562016-10-11 20:36:43 +000098 LayoutMode = LayoutModeIn;
Matthias Braun8426d132017-08-23 03:17:59 +000099 this->PreRegAlloc = PreRegAlloc;
Kyle Butt3232dbb2016-04-08 20:35:01 +0000100}
101
102static void VerifyPHIs(MachineFunction &MF, bool CheckExtra) {
103 for (MachineFunction::iterator I = ++MF.begin(), E = MF.end(); I != E; ++I) {
104 MachineBasicBlock *MBB = &*I;
105 SmallSetVector<MachineBasicBlock *, 8> Preds(MBB->pred_begin(),
106 MBB->pred_end());
107 MachineBasicBlock::iterator MI = MBB->begin();
108 while (MI != MBB->end()) {
109 if (!MI->isPHI())
110 break;
Matt Arsenaultb8037a12016-08-16 20:38:05 +0000111 for (MachineBasicBlock *PredBB : Preds) {
Kyle Butt3232dbb2016-04-08 20:35:01 +0000112 bool Found = false;
113 for (unsigned i = 1, e = MI->getNumOperands(); i != e; i += 2) {
114 MachineBasicBlock *PHIBB = MI->getOperand(i + 1).getMBB();
115 if (PHIBB == PredBB) {
116 Found = true;
117 break;
118 }
119 }
120 if (!Found) {
Francis Visoiu Mistrih25528d62017-12-04 17:18:51 +0000121 dbgs() << "Malformed PHI in " << printMBBReference(*MBB) << ": "
122 << *MI;
123 dbgs() << " missing input from predecessor "
124 << printMBBReference(*PredBB) << '\n';
Kyle Butt3232dbb2016-04-08 20:35:01 +0000125 llvm_unreachable(nullptr);
126 }
127 }
128
129 for (unsigned i = 1, e = MI->getNumOperands(); i != e; i += 2) {
130 MachineBasicBlock *PHIBB = MI->getOperand(i + 1).getMBB();
131 if (CheckExtra && !Preds.count(PHIBB)) {
Francis Visoiu Mistrih25528d62017-12-04 17:18:51 +0000132 dbgs() << "Warning: malformed PHI in " << printMBBReference(*MBB)
133 << ": " << *MI;
134 dbgs() << " extra input from predecessor "
135 << printMBBReference(*PHIBB) << '\n';
Kyle Butt3232dbb2016-04-08 20:35:01 +0000136 llvm_unreachable(nullptr);
137 }
138 if (PHIBB->getNumber() < 0) {
Francis Visoiu Mistrih25528d62017-12-04 17:18:51 +0000139 dbgs() << "Malformed PHI in " << printMBBReference(*MBB) << ": "
140 << *MI;
141 dbgs() << " non-existing " << printMBBReference(*PHIBB) << '\n';
Kyle Butt3232dbb2016-04-08 20:35:01 +0000142 llvm_unreachable(nullptr);
143 }
144 }
145 ++MI;
146 }
147 }
148}
149
150/// Tail duplicate the block and cleanup.
Kyle Butt723aa132016-08-26 20:12:40 +0000151/// \p IsSimple - return value of isSimpleBB
152/// \p MBB - block to be duplicated
Kyle Butt0846e562016-10-11 20:36:43 +0000153/// \p ForcedLayoutPred - If non-null, treat this block as the layout
154/// predecessor, instead of using the ordering in MF
Kyle Butt723aa132016-08-26 20:12:40 +0000155/// \p DuplicatedPreds - if non-null, \p DuplicatedPreds will contain a list of
156/// all Preds that received a copy of \p MBB.
Kyle Butt0846e562016-10-11 20:36:43 +0000157/// \p RemovalCallback - if non-null, called just before MBB is deleted.
Kyle Butt723aa132016-08-26 20:12:40 +0000158bool TailDuplicator::tailDuplicateAndUpdate(
159 bool IsSimple, MachineBasicBlock *MBB,
Kyle Butt0846e562016-10-11 20:36:43 +0000160 MachineBasicBlock *ForcedLayoutPred,
161 SmallVectorImpl<MachineBasicBlock*> *DuplicatedPreds,
Eugene Zelenko6ac7a342017-06-07 23:53:32 +0000162 function_ref<void(MachineBasicBlock *)> *RemovalCallback) {
Kyle Butt3232dbb2016-04-08 20:35:01 +0000163 // Save the successors list.
164 SmallSetVector<MachineBasicBlock *, 8> Succs(MBB->succ_begin(),
165 MBB->succ_end());
166
167 SmallVector<MachineBasicBlock *, 8> TDBBs;
168 SmallVector<MachineInstr *, 16> Copies;
Kyle Butt0846e562016-10-11 20:36:43 +0000169 if (!tailDuplicate(IsSimple, MBB, ForcedLayoutPred, TDBBs, Copies))
Kyle Butt3232dbb2016-04-08 20:35:01 +0000170 return false;
171
172 ++NumTails;
173
174 SmallVector<MachineInstr *, 8> NewPHIs;
Kyle Butt3ed42732016-08-25 01:37:03 +0000175 MachineSSAUpdater SSAUpdate(*MF, &NewPHIs);
Kyle Butt3232dbb2016-04-08 20:35:01 +0000176
177 // TailBB's immediate successors are now successors of those predecessors
178 // which duplicated TailBB. Add the predecessors as sources to the PHI
179 // instructions.
180 bool isDead = MBB->pred_empty() && !MBB->hasAddressTaken();
181 if (PreRegAlloc)
182 updateSuccessorsPHIs(MBB, isDead, TDBBs, Succs);
183
184 // If it is dead, remove it.
185 if (isDead) {
Geoff Berryf8c29d62016-06-14 19:40:10 +0000186 NumTailDupRemoved += MBB->size();
Kyle Butt0846e562016-10-11 20:36:43 +0000187 removeDeadBlock(MBB, RemovalCallback);
Kyle Butt3232dbb2016-04-08 20:35:01 +0000188 ++NumDeadBlocks;
189 }
190
191 // Update SSA form.
192 if (!SSAUpdateVRs.empty()) {
193 for (unsigned i = 0, e = SSAUpdateVRs.size(); i != e; ++i) {
194 unsigned VReg = SSAUpdateVRs[i];
195 SSAUpdate.Initialize(VReg);
196
197 // If the original definition is still around, add it as an available
198 // value.
199 MachineInstr *DefMI = MRI->getVRegDef(VReg);
200 MachineBasicBlock *DefBB = nullptr;
201 if (DefMI) {
202 DefBB = DefMI->getParent();
203 SSAUpdate.AddAvailableValue(DefBB, VReg);
204 }
205
206 // Add the new vregs as available values.
207 DenseMap<unsigned, AvailableValsTy>::iterator LI =
208 SSAUpdateVals.find(VReg);
209 for (unsigned j = 0, ee = LI->second.size(); j != ee; ++j) {
210 MachineBasicBlock *SrcBB = LI->second[j].first;
211 unsigned SrcReg = LI->second[j].second;
212 SSAUpdate.AddAvailableValue(SrcBB, SrcReg);
213 }
214
215 // Rewrite uses that are outside of the original def's block.
216 MachineRegisterInfo::use_iterator UI = MRI->use_begin(VReg);
217 while (UI != MRI->use_end()) {
218 MachineOperand &UseMO = *UI;
219 MachineInstr *UseMI = UseMO.getParent();
220 ++UI;
221 if (UseMI->isDebugValue()) {
222 // SSAUpdate can replace the use with an undef. That creates
223 // a debug instruction that is a kill.
224 // FIXME: Should it SSAUpdate job to delete debug instructions
225 // instead of replacing the use with undef?
226 UseMI->eraseFromParent();
227 continue;
228 }
229 if (UseMI->getParent() == DefBB && !UseMI->isPHI())
230 continue;
231 SSAUpdate.RewriteUse(UseMO);
232 }
233 }
234
235 SSAUpdateVRs.clear();
236 SSAUpdateVals.clear();
237 }
238
239 // Eliminate some of the copies inserted by tail duplication to maintain
240 // SSA form.
241 for (unsigned i = 0, e = Copies.size(); i != e; ++i) {
242 MachineInstr *Copy = Copies[i];
243 if (!Copy->isCopy())
244 continue;
Daniel Sanders0c476112019-08-15 19:22:08 +0000245 Register Dst = Copy->getOperand(0).getReg();
246 Register Src = Copy->getOperand(1).getReg();
Kyle Butt3232dbb2016-04-08 20:35:01 +0000247 if (MRI->hasOneNonDBGUse(Src) &&
248 MRI->constrainRegClass(Src, MRI->getRegClass(Dst))) {
249 // Copy is the only use. Do trivial copy propagation here.
250 MRI->replaceRegWith(Dst, Src);
251 Copy->eraseFromParent();
252 }
253 }
254
255 if (NewPHIs.size())
256 NumAddedPHIs += NewPHIs.size();
257
Kyle Butt723aa132016-08-26 20:12:40 +0000258 if (DuplicatedPreds)
259 *DuplicatedPreds = std::move(TDBBs);
260
Kyle Butt3232dbb2016-04-08 20:35:01 +0000261 return true;
262}
263
264/// Look for small blocks that are unconditionally branched to and do not fall
265/// through. Tail-duplicate their instructions into their predecessors to
266/// eliminate (dynamic) branches.
Kyle Butt3ed42732016-08-25 01:37:03 +0000267bool TailDuplicator::tailDuplicateBlocks() {
Kyle Butt3232dbb2016-04-08 20:35:01 +0000268 bool MadeChange = false;
269
270 if (PreRegAlloc && TailDupVerify) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000271 LLVM_DEBUG(dbgs() << "\n*** Before tail-duplicating\n");
Kyle Butt3ed42732016-08-25 01:37:03 +0000272 VerifyPHIs(*MF, true);
Kyle Butt3232dbb2016-04-08 20:35:01 +0000273 }
274
Kyle Butt3ed42732016-08-25 01:37:03 +0000275 for (MachineFunction::iterator I = ++MF->begin(), E = MF->end(); I != E;) {
Kyle Butt3232dbb2016-04-08 20:35:01 +0000276 MachineBasicBlock *MBB = &*I++;
277
278 if (NumTails == TailDupLimit)
279 break;
280
281 bool IsSimple = isSimpleBB(MBB);
282
Kyle Butt3ed42732016-08-25 01:37:03 +0000283 if (!shouldTailDuplicate(IsSimple, *MBB))
Kyle Butt3232dbb2016-04-08 20:35:01 +0000284 continue;
285
Kyle Butt0846e562016-10-11 20:36:43 +0000286 MadeChange |= tailDuplicateAndUpdate(IsSimple, MBB, nullptr);
Kyle Butt3232dbb2016-04-08 20:35:01 +0000287 }
288
289 if (PreRegAlloc && TailDupVerify)
Kyle Butt3ed42732016-08-25 01:37:03 +0000290 VerifyPHIs(*MF, false);
Kyle Butt3232dbb2016-04-08 20:35:01 +0000291
292 return MadeChange;
293}
294
295static bool isDefLiveOut(unsigned Reg, MachineBasicBlock *BB,
296 const MachineRegisterInfo *MRI) {
297 for (MachineInstr &UseMI : MRI->use_instructions(Reg)) {
298 if (UseMI.isDebugValue())
299 continue;
300 if (UseMI.getParent() != BB)
301 return true;
302 }
303 return false;
304}
305
306static unsigned getPHISrcRegOpIdx(MachineInstr *MI, MachineBasicBlock *SrcBB) {
307 for (unsigned i = 1, e = MI->getNumOperands(); i != e; i += 2)
308 if (MI->getOperand(i + 1).getMBB() == SrcBB)
309 return i;
310 return 0;
311}
312
313// Remember which registers are used by phis in this block. This is
314// used to determine which registers are liveout while modifying the
315// block (which is why we need to copy the information).
316static void getRegsUsedByPHIs(const MachineBasicBlock &BB,
317 DenseSet<unsigned> *UsedByPhi) {
318 for (const auto &MI : BB) {
319 if (!MI.isPHI())
320 break;
321 for (unsigned i = 1, e = MI.getNumOperands(); i != e; i += 2) {
Daniel Sanders0c476112019-08-15 19:22:08 +0000322 Register SrcReg = MI.getOperand(i).getReg();
Kyle Butt3232dbb2016-04-08 20:35:01 +0000323 UsedByPhi->insert(SrcReg);
324 }
325 }
326}
327
328/// Add a definition and source virtual registers pair for SSA update.
329void TailDuplicator::addSSAUpdateEntry(unsigned OrigReg, unsigned NewReg,
330 MachineBasicBlock *BB) {
331 DenseMap<unsigned, AvailableValsTy>::iterator LI =
332 SSAUpdateVals.find(OrigReg);
333 if (LI != SSAUpdateVals.end())
334 LI->second.push_back(std::make_pair(BB, NewReg));
335 else {
336 AvailableValsTy Vals;
337 Vals.push_back(std::make_pair(BB, NewReg));
338 SSAUpdateVals.insert(std::make_pair(OrigReg, Vals));
339 SSAUpdateVRs.push_back(OrigReg);
340 }
341}
342
343/// Process PHI node in TailBB by turning it into a copy in PredBB. Remember the
344/// source register that's contributed by PredBB and update SSA update map.
345void TailDuplicator::processPHI(
346 MachineInstr *MI, MachineBasicBlock *TailBB, MachineBasicBlock *PredBB,
Krzysztof Parzyszek4773f642016-04-26 18:36:34 +0000347 DenseMap<unsigned, RegSubRegPair> &LocalVRMap,
348 SmallVectorImpl<std::pair<unsigned, RegSubRegPair>> &Copies,
Kyle Butt3232dbb2016-04-08 20:35:01 +0000349 const DenseSet<unsigned> &RegsUsedByPhi, bool Remove) {
Daniel Sanders0c476112019-08-15 19:22:08 +0000350 Register DefReg = MI->getOperand(0).getReg();
Kyle Butt3232dbb2016-04-08 20:35:01 +0000351 unsigned SrcOpIdx = getPHISrcRegOpIdx(MI, PredBB);
352 assert(SrcOpIdx && "Unable to find matching PHI source?");
Daniel Sanders0c476112019-08-15 19:22:08 +0000353 Register SrcReg = MI->getOperand(SrcOpIdx).getReg();
Krzysztof Parzyszek4773f642016-04-26 18:36:34 +0000354 unsigned SrcSubReg = MI->getOperand(SrcOpIdx).getSubReg();
Kyle Butt3232dbb2016-04-08 20:35:01 +0000355 const TargetRegisterClass *RC = MRI->getRegClass(DefReg);
Krzysztof Parzyszek4773f642016-04-26 18:36:34 +0000356 LocalVRMap.insert(std::make_pair(DefReg, RegSubRegPair(SrcReg, SrcSubReg)));
Kyle Butt3232dbb2016-04-08 20:35:01 +0000357
358 // Insert a copy from source to the end of the block. The def register is the
359 // available value liveout of the block.
Daniel Sanders0c476112019-08-15 19:22:08 +0000360 Register NewDef = MRI->createVirtualRegister(RC);
Krzysztof Parzyszek4773f642016-04-26 18:36:34 +0000361 Copies.push_back(std::make_pair(NewDef, RegSubRegPair(SrcReg, SrcSubReg)));
Kyle Butt3232dbb2016-04-08 20:35:01 +0000362 if (isDefLiveOut(DefReg, TailBB, MRI) || RegsUsedByPhi.count(DefReg))
363 addSSAUpdateEntry(DefReg, NewDef, PredBB);
364
365 if (!Remove)
366 return;
367
368 // Remove PredBB from the PHI node.
369 MI->RemoveOperand(SrcOpIdx + 1);
370 MI->RemoveOperand(SrcOpIdx);
371 if (MI->getNumOperands() == 1)
372 MI->eraseFromParent();
373}
374
375/// Duplicate a TailBB instruction to PredBB and update
376/// the source operands due to earlier PHI translation.
377void TailDuplicator::duplicateInstruction(
378 MachineInstr *MI, MachineBasicBlock *TailBB, MachineBasicBlock *PredBB,
Krzysztof Parzyszek4773f642016-04-26 18:36:34 +0000379 DenseMap<unsigned, RegSubRegPair> &LocalVRMap,
Kyle Butt3232dbb2016-04-08 20:35:01 +0000380 const DenseSet<unsigned> &UsedByPhi) {
Petar Jovanovic540f4cd2018-01-31 15:57:57 +0000381 // Allow duplication of CFI instructions.
382 if (MI->isCFIInstruction()) {
383 BuildMI(*PredBB, PredBB->end(), PredBB->findDebugLoc(PredBB->begin()),
384 TII->get(TargetOpcode::CFI_INSTRUCTION)).addCFIIndex(
385 MI->getOperand(0).getCFIIndex());
386 return;
387 }
Matthias Braun55bc9b32017-08-22 23:56:30 +0000388 MachineInstr &NewMI = TII->duplicate(*PredBB, PredBB->end(), *MI);
Kyle Butt3232dbb2016-04-08 20:35:01 +0000389 if (PreRegAlloc) {
Matthias Braun55bc9b32017-08-22 23:56:30 +0000390 for (unsigned i = 0, e = NewMI.getNumOperands(); i != e; ++i) {
391 MachineOperand &MO = NewMI.getOperand(i);
Kyle Butt3232dbb2016-04-08 20:35:01 +0000392 if (!MO.isReg())
393 continue;
Daniel Sanders0c476112019-08-15 19:22:08 +0000394 Register Reg = MO.getReg();
Daniel Sanders2bea69b2019-08-01 23:27:28 +0000395 if (!Register::isVirtualRegister(Reg))
Kyle Butt3232dbb2016-04-08 20:35:01 +0000396 continue;
397 if (MO.isDef()) {
398 const TargetRegisterClass *RC = MRI->getRegClass(Reg);
Daniel Sanders0c476112019-08-15 19:22:08 +0000399 Register NewReg = MRI->createVirtualRegister(RC);
Kyle Butt3232dbb2016-04-08 20:35:01 +0000400 MO.setReg(NewReg);
Krzysztof Parzyszek4773f642016-04-26 18:36:34 +0000401 LocalVRMap.insert(std::make_pair(Reg, RegSubRegPair(NewReg, 0)));
Kyle Butt3232dbb2016-04-08 20:35:01 +0000402 if (isDefLiveOut(Reg, TailBB, MRI) || UsedByPhi.count(Reg))
403 addSSAUpdateEntry(Reg, NewReg, PredBB);
404 } else {
Krzysztof Parzyszek4773f642016-04-26 18:36:34 +0000405 auto VI = LocalVRMap.find(Reg);
Kyle Butt3232dbb2016-04-08 20:35:01 +0000406 if (VI != LocalVRMap.end()) {
Krzysztof Parzyszek4773f642016-04-26 18:36:34 +0000407 // Need to make sure that the register class of the mapped register
408 // will satisfy the constraints of the class of the register being
409 // replaced.
410 auto *OrigRC = MRI->getRegClass(Reg);
411 auto *MappedRC = MRI->getRegClass(VI->second.Reg);
412 const TargetRegisterClass *ConstrRC;
413 if (VI->second.SubReg != 0) {
414 ConstrRC = TRI->getMatchingSuperRegClass(MappedRC, OrigRC,
415 VI->second.SubReg);
416 if (ConstrRC) {
417 // The actual constraining (as in "find appropriate new class")
418 // is done by getMatchingSuperRegClass, so now we only need to
419 // change the class of the mapped register.
420 MRI->setRegClass(VI->second.Reg, ConstrRC);
421 }
422 } else {
423 // For mapped registers that do not have sub-registers, simply
424 // restrict their class to match the original one.
425 ConstrRC = MRI->constrainRegClass(VI->second.Reg, OrigRC);
426 }
427
428 if (ConstrRC) {
429 // If the class constraining succeeded, we can simply replace
430 // the old register with the mapped one.
431 MO.setReg(VI->second.Reg);
432 // We have Reg -> VI.Reg:VI.SubReg, so if Reg is used with a
433 // sub-register, we need to compose the sub-register indices.
434 MO.setSubReg(TRI->composeSubRegIndices(MO.getSubReg(),
435 VI->second.SubReg));
436 } else {
437 // The direct replacement is not possible, due to failing register
438 // class constraints. An explicit COPY is necessary. Create one
439 // that can be reused
440 auto *NewRC = MI->getRegClassConstraint(i, TII, TRI);
441 if (NewRC == nullptr)
442 NewRC = OrigRC;
Daniel Sanders0c476112019-08-15 19:22:08 +0000443 Register NewReg = MRI->createVirtualRegister(NewRC);
Amara Emerson000ef2c2019-07-02 06:04:46 +0000444 BuildMI(*PredBB, NewMI, NewMI.getDebugLoc(),
Krzysztof Parzyszek4773f642016-04-26 18:36:34 +0000445 TII->get(TargetOpcode::COPY), NewReg)
446 .addReg(VI->second.Reg, 0, VI->second.SubReg);
447 LocalVRMap.erase(VI);
448 LocalVRMap.insert(std::make_pair(Reg, RegSubRegPair(NewReg, 0)));
449 MO.setReg(NewReg);
450 // The composed VI.Reg:VI.SubReg is replaced with NewReg, which
451 // is equivalent to the whole register Reg. Hence, Reg:subreg
452 // is same as NewReg:subreg, so keep the sub-register index
453 // unchanged.
454 }
Kyle Butt3232dbb2016-04-08 20:35:01 +0000455 // Clear any kill flags from this operand. The new register could
456 // have uses after this one, so kills are not valid here.
457 MO.setIsKill(false);
Kyle Butt3232dbb2016-04-08 20:35:01 +0000458 }
459 }
460 }
461 }
Kyle Butt3232dbb2016-04-08 20:35:01 +0000462}
463
464/// After FromBB is tail duplicated into its predecessor blocks, the successors
465/// have gained new predecessors. Update the PHI instructions in them
466/// accordingly.
467void TailDuplicator::updateSuccessorsPHIs(
468 MachineBasicBlock *FromBB, bool isDead,
469 SmallVectorImpl<MachineBasicBlock *> &TDBBs,
470 SmallSetVector<MachineBasicBlock *, 8> &Succs) {
Matt Arsenaultb8037a12016-08-16 20:38:05 +0000471 for (MachineBasicBlock *SuccBB : Succs) {
472 for (MachineInstr &MI : *SuccBB) {
473 if (!MI.isPHI())
Kyle Butt3232dbb2016-04-08 20:35:01 +0000474 break;
Matt Arsenaultb8037a12016-08-16 20:38:05 +0000475 MachineInstrBuilder MIB(*FromBB->getParent(), MI);
Kyle Butt3232dbb2016-04-08 20:35:01 +0000476 unsigned Idx = 0;
Matt Arsenaultb8037a12016-08-16 20:38:05 +0000477 for (unsigned i = 1, e = MI.getNumOperands(); i != e; i += 2) {
478 MachineOperand &MO = MI.getOperand(i + 1);
Kyle Butt3232dbb2016-04-08 20:35:01 +0000479 if (MO.getMBB() == FromBB) {
480 Idx = i;
481 break;
482 }
483 }
484
485 assert(Idx != 0);
Matt Arsenaultb8037a12016-08-16 20:38:05 +0000486 MachineOperand &MO0 = MI.getOperand(Idx);
Daniel Sanders0c476112019-08-15 19:22:08 +0000487 Register Reg = MO0.getReg();
Kyle Butt3232dbb2016-04-08 20:35:01 +0000488 if (isDead) {
489 // Folded into the previous BB.
490 // There could be duplicate phi source entries. FIXME: Should sdisel
491 // or earlier pass fixed this?
Matt Arsenaultb8037a12016-08-16 20:38:05 +0000492 for (unsigned i = MI.getNumOperands() - 2; i != Idx; i -= 2) {
493 MachineOperand &MO = MI.getOperand(i + 1);
Kyle Butt3232dbb2016-04-08 20:35:01 +0000494 if (MO.getMBB() == FromBB) {
Matt Arsenaultb8037a12016-08-16 20:38:05 +0000495 MI.RemoveOperand(i + 1);
496 MI.RemoveOperand(i);
Kyle Butt3232dbb2016-04-08 20:35:01 +0000497 }
498 }
499 } else
500 Idx = 0;
501
502 // If Idx is set, the operands at Idx and Idx+1 must be removed.
503 // We reuse the location to avoid expensive RemoveOperand calls.
504
505 DenseMap<unsigned, AvailableValsTy>::iterator LI =
506 SSAUpdateVals.find(Reg);
507 if (LI != SSAUpdateVals.end()) {
508 // This register is defined in the tail block.
509 for (unsigned j = 0, ee = LI->second.size(); j != ee; ++j) {
510 MachineBasicBlock *SrcBB = LI->second[j].first;
511 // If we didn't duplicate a bb into a particular predecessor, we
512 // might still have added an entry to SSAUpdateVals to correcly
513 // recompute SSA. If that case, avoid adding a dummy extra argument
514 // this PHI.
515 if (!SrcBB->isSuccessor(SuccBB))
516 continue;
517
518 unsigned SrcReg = LI->second[j].second;
519 if (Idx != 0) {
Matt Arsenaultb8037a12016-08-16 20:38:05 +0000520 MI.getOperand(Idx).setReg(SrcReg);
521 MI.getOperand(Idx + 1).setMBB(SrcBB);
Kyle Butt3232dbb2016-04-08 20:35:01 +0000522 Idx = 0;
523 } else {
524 MIB.addReg(SrcReg).addMBB(SrcBB);
525 }
526 }
527 } else {
528 // Live in tail block, must also be live in predecessors.
529 for (unsigned j = 0, ee = TDBBs.size(); j != ee; ++j) {
530 MachineBasicBlock *SrcBB = TDBBs[j];
531 if (Idx != 0) {
Matt Arsenaultb8037a12016-08-16 20:38:05 +0000532 MI.getOperand(Idx).setReg(Reg);
533 MI.getOperand(Idx + 1).setMBB(SrcBB);
Kyle Butt3232dbb2016-04-08 20:35:01 +0000534 Idx = 0;
535 } else {
536 MIB.addReg(Reg).addMBB(SrcBB);
537 }
538 }
539 }
540 if (Idx != 0) {
Matt Arsenaultb8037a12016-08-16 20:38:05 +0000541 MI.RemoveOperand(Idx + 1);
542 MI.RemoveOperand(Idx);
Kyle Butt3232dbb2016-04-08 20:35:01 +0000543 }
544 }
545 }
546}
547
548/// Determine if it is profitable to duplicate this block.
Kyle Butt3ed42732016-08-25 01:37:03 +0000549bool TailDuplicator::shouldTailDuplicate(bool IsSimple,
Kyle Butt3232dbb2016-04-08 20:35:01 +0000550 MachineBasicBlock &TailBB) {
Kyle Butt0846e562016-10-11 20:36:43 +0000551 // When doing tail-duplication during layout, the block ordering is in flux,
552 // so canFallThrough returns a result based on incorrect information and
553 // should just be ignored.
554 if (!LayoutMode && TailBB.canFallThrough())
Kyle Butt3232dbb2016-04-08 20:35:01 +0000555 return false;
556
557 // Don't try to tail-duplicate single-block loops.
558 if (TailBB.isSuccessor(&TailBB))
559 return false;
560
561 // Set the limit on the cost to duplicate. When optimizing for size,
562 // duplicate only one, because one branch instruction can be eliminated to
563 // compensate for the duplication.
564 unsigned MaxDuplicateCount;
Hiroshi Yamauchid9ae4932019-12-05 09:39:37 -0800565 bool OptForSize = MF->getFunction().hasOptSize() ||
566 llvm::shouldOptimizeForSize(&TailBB, PSI, MBFI);
567 if (TailDupSize == 0)
Kyle Butt3232dbb2016-04-08 20:35:01 +0000568 MaxDuplicateCount = TailDuplicateSize;
Kyle Buttdb3391e2016-08-17 21:07:35 +0000569 else
570 MaxDuplicateCount = TailDupSize;
Hiroshi Yamauchid9ae4932019-12-05 09:39:37 -0800571 if (OptForSize)
572 MaxDuplicateCount = 1;
Kyle Butt3232dbb2016-04-08 20:35:01 +0000573
Kyle Butt07d61422016-08-16 22:56:14 +0000574 // If the block to be duplicated ends in an unanalyzable fallthrough, don't
575 // duplicate it.
576 // A similar check is necessary in MachineBlockPlacement to make sure pairs of
577 // blocks with unanalyzable fallthrough get layed out contiguously.
578 MachineBasicBlock *PredTBB = nullptr, *PredFBB = nullptr;
579 SmallVector<MachineOperand, 4> PredCond;
Sanjoy Dasd7389d62016-12-15 05:08:57 +0000580 if (TII->analyzeBranch(TailBB, PredTBB, PredFBB, PredCond) &&
581 TailBB.canFallThrough())
Kyle Butt07d61422016-08-16 22:56:14 +0000582 return false;
583
Kyle Butt3232dbb2016-04-08 20:35:01 +0000584 // If the target has hardware branch prediction that can handle indirect
585 // branches, duplicating them can often make them predictable when there
586 // are common paths through the code. The limit needs to be high enough
587 // to allow undoing the effects of tail merging and other optimizations
588 // that rearrange the predecessors of the indirect branch.
589
590 bool HasIndirectbr = false;
591 if (!TailBB.empty())
592 HasIndirectbr = TailBB.back().isIndirectBranch();
593
594 if (HasIndirectbr && PreRegAlloc)
Kyle Butt61aca6e2016-08-30 18:18:54 +0000595 MaxDuplicateCount = TailDupIndirectBranchSize;
Kyle Butt3232dbb2016-04-08 20:35:01 +0000596
597 // Check the instructions in the block to determine whether tail-duplication
598 // is invalid or unlikely to be profitable.
599 unsigned InstrCount = 0;
600 for (MachineInstr &MI : TailBB) {
601 // Non-duplicable things shouldn't be tail-duplicated.
Petar Jovanovic540f4cd2018-01-31 15:57:57 +0000602 // CFI instructions are marked as non-duplicable, because Darwin compact
603 // unwind info emission can't handle multiple prologue setups. In case of
604 // DWARF, allow them be duplicated, so that their existence doesn't prevent
605 // tail duplication of some basic blocks, that would be duplicated otherwise.
606 if (MI.isNotDuplicable() &&
607 (TailBB.getParent()->getTarget().getTargetTriple().isOSDarwin() ||
608 !MI.isCFIInstruction()))
Kyle Butt3232dbb2016-04-08 20:35:01 +0000609 return false;
610
611 // Convergent instructions can be duplicated only if doing so doesn't add
612 // new control dependencies, which is what we're going to do here.
613 if (MI.isConvergent())
614 return false;
615
616 // Do not duplicate 'return' instructions if this is a pre-regalloc run.
617 // A return may expand into a lot more instructions (e.g. reload of callee
618 // saved registers) after PEI.
619 if (PreRegAlloc && MI.isReturn())
620 return false;
621
622 // Avoid duplicating calls before register allocation. Calls presents a
623 // barrier to register allocation so duplicating them may end up increasing
624 // spills.
625 if (PreRegAlloc && MI.isCall())
626 return false;
627
Stanislav Mekhanoshin8b417dd2020-01-15 09:38:08 -0800628 if (MI.isBundle())
629 InstrCount += MI.getBundleSize();
630 else if (!MI.isPHI() && !MI.isMetaInstruction())
Reid Kleckner7adb2fd2017-11-08 21:31:14 +0000631 InstrCount += 1;
Kyle Butt3232dbb2016-04-08 20:35:01 +0000632
633 if (InstrCount > MaxDuplicateCount)
634 return false;
635 }
636
637 // Check if any of the successors of TailBB has a PHI node in which the
638 // value corresponding to TailBB uses a subregister.
639 // If a phi node uses a register paired with a subregister, the actual
640 // "value type" of the phi may differ from the type of the register without
641 // any subregisters. Due to a bug, tail duplication may add a new operand
642 // without a necessary subregister, producing an invalid code. This is
643 // demonstrated by test/CodeGen/Hexagon/tail-dup-subreg-abort.ll.
644 // Disable tail duplication for this case for now, until the problem is
645 // fixed.
646 for (auto SB : TailBB.successors()) {
647 for (auto &I : *SB) {
648 if (!I.isPHI())
649 break;
650 unsigned Idx = getPHISrcRegOpIdx(&I, &TailBB);
651 assert(Idx != 0);
652 MachineOperand &PU = I.getOperand(Idx);
653 if (PU.getSubReg() != 0)
654 return false;
655 }
656 }
657
658 if (HasIndirectbr && PreRegAlloc)
659 return true;
660
661 if (IsSimple)
662 return true;
663
664 if (!PreRegAlloc)
665 return true;
666
667 return canCompletelyDuplicateBB(TailBB);
668}
669
670/// True if this BB has only one unconditional jump.
671bool TailDuplicator::isSimpleBB(MachineBasicBlock *TailBB) {
672 if (TailBB->succ_size() != 1)
673 return false;
674 if (TailBB->pred_empty())
675 return false;
676 MachineBasicBlock::iterator I = TailBB->getFirstNonDebugInstr();
677 if (I == TailBB->end())
678 return true;
679 return I->isUnconditionalBranch();
680}
681
682static bool bothUsedInPHI(const MachineBasicBlock &A,
Benjamin Kramerbdc49562016-06-12 15:39:02 +0000683 const SmallPtrSet<MachineBasicBlock *, 8> &SuccsB) {
Kyle Butt3232dbb2016-04-08 20:35:01 +0000684 for (MachineBasicBlock *BB : A.successors())
685 if (SuccsB.count(BB) && !BB->empty() && BB->begin()->isPHI())
686 return true;
687
688 return false;
689}
690
691bool TailDuplicator::canCompletelyDuplicateBB(MachineBasicBlock &BB) {
692 for (MachineBasicBlock *PredBB : BB.predecessors()) {
693 if (PredBB->succ_size() > 1)
694 return false;
695
696 MachineBasicBlock *PredTBB = nullptr, *PredFBB = nullptr;
697 SmallVector<MachineOperand, 4> PredCond;
Sanjoy Dasd7389d62016-12-15 05:08:57 +0000698 if (TII->analyzeBranch(*PredBB, PredTBB, PredFBB, PredCond))
Kyle Butt3232dbb2016-04-08 20:35:01 +0000699 return false;
700
701 if (!PredCond.empty())
702 return false;
703 }
704 return true;
705}
706
707bool TailDuplicator::duplicateSimpleBB(
708 MachineBasicBlock *TailBB, SmallVectorImpl<MachineBasicBlock *> &TDBBs,
709 const DenseSet<unsigned> &UsedByPhi,
710 SmallVectorImpl<MachineInstr *> &Copies) {
711 SmallPtrSet<MachineBasicBlock *, 8> Succs(TailBB->succ_begin(),
712 TailBB->succ_end());
713 SmallVector<MachineBasicBlock *, 8> Preds(TailBB->pred_begin(),
714 TailBB->pred_end());
715 bool Changed = false;
Matt Arsenaultb8037a12016-08-16 20:38:05 +0000716 for (MachineBasicBlock *PredBB : Preds) {
Kyle Butt3232dbb2016-04-08 20:35:01 +0000717 if (PredBB->hasEHPadSuccessor())
718 continue;
719
720 if (bothUsedInPHI(*PredBB, Succs))
721 continue;
722
723 MachineBasicBlock *PredTBB = nullptr, *PredFBB = nullptr;
724 SmallVector<MachineOperand, 4> PredCond;
Sanjoy Dasd7389d62016-12-15 05:08:57 +0000725 if (TII->analyzeBranch(*PredBB, PredTBB, PredFBB, PredCond))
Kyle Butt3232dbb2016-04-08 20:35:01 +0000726 continue;
727
728 Changed = true;
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000729 LLVM_DEBUG(dbgs() << "\nTail-duplicating into PredBB: " << *PredBB
730 << "From simple Succ: " << *TailBB);
Kyle Butt3232dbb2016-04-08 20:35:01 +0000731
732 MachineBasicBlock *NewTarget = *TailBB->succ_begin();
Matthias Braun6442fc12016-08-18 00:59:32 +0000733 MachineBasicBlock *NextBB = PredBB->getNextNode();
Kyle Butt3232dbb2016-04-08 20:35:01 +0000734
735 // Make PredFBB explicit.
736 if (PredCond.empty())
737 PredFBB = PredTBB;
738
739 // Make fall through explicit.
740 if (!PredTBB)
741 PredTBB = NextBB;
742 if (!PredFBB)
743 PredFBB = NextBB;
744
745 // Redirect
746 if (PredFBB == TailBB)
747 PredFBB = NewTarget;
748 if (PredTBB == TailBB)
749 PredTBB = NewTarget;
750
751 // Make the branch unconditional if possible
752 if (PredTBB == PredFBB) {
753 PredCond.clear();
754 PredFBB = nullptr;
755 }
756
757 // Avoid adding fall through branches.
758 if (PredFBB == NextBB)
759 PredFBB = nullptr;
760 if (PredTBB == NextBB && PredFBB == nullptr)
761 PredTBB = nullptr;
762
Taewook Oha49eb852017-02-27 19:30:01 +0000763 auto DL = PredBB->findBranchDebugLoc();
Matt Arsenault1b9fc8e2016-09-14 20:43:16 +0000764 TII->removeBranch(*PredBB);
Kyle Butt3232dbb2016-04-08 20:35:01 +0000765
766 if (!PredBB->isSuccessor(NewTarget))
767 PredBB->replaceSuccessor(TailBB, NewTarget);
768 else {
769 PredBB->removeSuccessor(TailBB, true);
770 assert(PredBB->succ_size() <= 1);
771 }
772
773 if (PredTBB)
Taewook Oha49eb852017-02-27 19:30:01 +0000774 TII->insertBranch(*PredBB, PredTBB, PredFBB, PredCond, DL);
Kyle Butt3232dbb2016-04-08 20:35:01 +0000775
776 TDBBs.push_back(PredBB);
777 }
778 return Changed;
779}
780
Kyle Butt9e52c062016-07-19 23:54:21 +0000781bool TailDuplicator::canTailDuplicate(MachineBasicBlock *TailBB,
782 MachineBasicBlock *PredBB) {
Kyle Butt0846e562016-10-11 20:36:43 +0000783 // EH edges are ignored by analyzeBranch.
Kyle Butt9e52c062016-07-19 23:54:21 +0000784 if (PredBB->succ_size() > 1)
785 return false;
786
Vitaly Bukab238cb82017-05-22 21:33:54 +0000787 MachineBasicBlock *PredTBB = nullptr, *PredFBB = nullptr;
Kyle Butt9e52c062016-07-19 23:54:21 +0000788 SmallVector<MachineOperand, 4> PredCond;
Sanjoy Dasd7389d62016-12-15 05:08:57 +0000789 if (TII->analyzeBranch(*PredBB, PredTBB, PredFBB, PredCond))
Kyle Butt9e52c062016-07-19 23:54:21 +0000790 return false;
791 if (!PredCond.empty())
792 return false;
793 return true;
794}
795
Kyle Butt3232dbb2016-04-08 20:35:01 +0000796/// If it is profitable, duplicate TailBB's contents in each
797/// of its predecessors.
Kyle Butt0846e562016-10-11 20:36:43 +0000798/// \p IsSimple result of isSimpleBB
799/// \p TailBB Block to be duplicated.
800/// \p ForcedLayoutPred When non-null, use this block as the layout predecessor
801/// instead of the previous block in MF's order.
802/// \p TDBBs A vector to keep track of all blocks tail-duplicated
803/// into.
804/// \p Copies A vector of copy instructions inserted. Used later to
805/// walk all the inserted copies and remove redundant ones.
Kyle Butt3ed42732016-08-25 01:37:03 +0000806bool TailDuplicator::tailDuplicate(bool IsSimple, MachineBasicBlock *TailBB,
Kyle Butt0846e562016-10-11 20:36:43 +0000807 MachineBasicBlock *ForcedLayoutPred,
Kyle Butt3232dbb2016-04-08 20:35:01 +0000808 SmallVectorImpl<MachineBasicBlock *> &TDBBs,
809 SmallVectorImpl<MachineInstr *> &Copies) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000810 LLVM_DEBUG(dbgs() << "\n*** Tail-duplicating " << printMBBReference(*TailBB)
811 << '\n');
Kyle Butt3232dbb2016-04-08 20:35:01 +0000812
813 DenseSet<unsigned> UsedByPhi;
814 getRegsUsedByPHIs(*TailBB, &UsedByPhi);
815
816 if (IsSimple)
817 return duplicateSimpleBB(TailBB, TDBBs, UsedByPhi, Copies);
818
819 // Iterate through all the unique predecessors and tail-duplicate this
820 // block into them, if possible. Copying the list ahead of time also
821 // avoids trouble with the predecessor list reallocating.
822 bool Changed = false;
823 SmallSetVector<MachineBasicBlock *, 8> Preds(TailBB->pred_begin(),
824 TailBB->pred_end());
Matt Arsenaultb8037a12016-08-16 20:38:05 +0000825 for (MachineBasicBlock *PredBB : Preds) {
Kyle Butt3232dbb2016-04-08 20:35:01 +0000826 assert(TailBB != PredBB &&
827 "Single-block loop should have been rejected earlier!");
Kyle Butt9e52c062016-07-19 23:54:21 +0000828
829 if (!canTailDuplicate(TailBB, PredBB))
Kyle Butt3232dbb2016-04-08 20:35:01 +0000830 continue;
831
Kyle Butt3232dbb2016-04-08 20:35:01 +0000832 // Don't duplicate into a fall-through predecessor (at least for now).
Kyle Butt0846e562016-10-11 20:36:43 +0000833 bool IsLayoutSuccessor = false;
834 if (ForcedLayoutPred)
835 IsLayoutSuccessor = (ForcedLayoutPred == PredBB);
836 else if (PredBB->isLayoutSuccessor(TailBB) && PredBB->canFallThrough())
837 IsLayoutSuccessor = true;
838 if (IsLayoutSuccessor)
Kyle Butt3232dbb2016-04-08 20:35:01 +0000839 continue;
840
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000841 LLVM_DEBUG(dbgs() << "\nTail-duplicating into PredBB: " << *PredBB
842 << "From Succ: " << *TailBB);
Kyle Butt3232dbb2016-04-08 20:35:01 +0000843
844 TDBBs.push_back(PredBB);
845
846 // Remove PredBB's unconditional branch.
Matt Arsenault1b9fc8e2016-09-14 20:43:16 +0000847 TII->removeBranch(*PredBB);
Kyle Butt3232dbb2016-04-08 20:35:01 +0000848
Kyle Butt3232dbb2016-04-08 20:35:01 +0000849 // Clone the contents of TailBB into PredBB.
Krzysztof Parzyszek4773f642016-04-26 18:36:34 +0000850 DenseMap<unsigned, RegSubRegPair> LocalVRMap;
851 SmallVector<std::pair<unsigned, RegSubRegPair>, 4> CopyInfos;
Matthias Braun55bc9b32017-08-22 23:56:30 +0000852 for (MachineBasicBlock::iterator I = TailBB->begin(), E = TailBB->end();
853 I != E; /* empty */) {
Kyle Butt3232dbb2016-04-08 20:35:01 +0000854 MachineInstr *MI = &*I;
855 ++I;
856 if (MI->isPHI()) {
857 // Replace the uses of the def of the PHI with the register coming
858 // from PredBB.
859 processPHI(MI, TailBB, PredBB, LocalVRMap, CopyInfos, UsedByPhi, true);
860 } else {
861 // Replace def of virtual registers with new registers, and update
862 // uses with PHI source register or the new registers.
Kyle Butt3ed42732016-08-25 01:37:03 +0000863 duplicateInstruction(MI, TailBB, PredBB, LocalVRMap, UsedByPhi);
Kyle Butt3232dbb2016-04-08 20:35:01 +0000864 }
865 }
Krzysztof Parzyszek4773f642016-04-26 18:36:34 +0000866 appendCopies(PredBB, CopyInfos, Copies);
Kyle Butt3232dbb2016-04-08 20:35:01 +0000867
Geoff Berryf8c29d62016-06-14 19:40:10 +0000868 NumTailDupAdded += TailBB->size() - 1; // subtract one for removed branch
Kyle Butt3232dbb2016-04-08 20:35:01 +0000869
870 // Update the CFG.
871 PredBB->removeSuccessor(PredBB->succ_begin());
872 assert(PredBB->succ_empty() &&
873 "TailDuplicate called on block with multiple successors!");
Matt Arsenaultb8037a12016-08-16 20:38:05 +0000874 for (MachineBasicBlock *Succ : TailBB->successors())
875 PredBB->addSuccessor(Succ, MBPI->getEdgeProbability(TailBB, Succ));
Kyle Butt3232dbb2016-04-08 20:35:01 +0000876
877 Changed = true;
878 ++NumTailDups;
879 }
880
881 // If TailBB was duplicated into all its predecessors except for the prior
882 // block, which falls through unconditionally, move the contents of this
883 // block into the prior block.
Kyle Butt0846e562016-10-11 20:36:43 +0000884 MachineBasicBlock *PrevBB = ForcedLayoutPred;
885 if (!PrevBB)
886 PrevBB = &*std::prev(TailBB->getIterator());
Kyle Butt3232dbb2016-04-08 20:35:01 +0000887 MachineBasicBlock *PriorTBB = nullptr, *PriorFBB = nullptr;
888 SmallVector<MachineOperand, 4> PriorCond;
889 // This has to check PrevBB->succ_size() because EH edges are ignored by
Kyle Butt0846e562016-10-11 20:36:43 +0000890 // analyzeBranch.
Kyle Butt3232dbb2016-04-08 20:35:01 +0000891 if (PrevBB->succ_size() == 1 &&
Kyle Buttd2b886e2016-07-20 00:01:51 +0000892 // Layout preds are not always CFG preds. Check.
893 *PrevBB->succ_begin() == TailBB &&
Sanjoy Dasd7389d62016-12-15 05:08:57 +0000894 !TII->analyzeBranch(*PrevBB, PriorTBB, PriorFBB, PriorCond) &&
Kyle Butt0846e562016-10-11 20:36:43 +0000895 PriorCond.empty() &&
896 (!PriorTBB || PriorTBB == TailBB) &&
897 TailBB->pred_size() == 1 &&
Kyle Butt3232dbb2016-04-08 20:35:01 +0000898 !TailBB->hasAddressTaken()) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000899 LLVM_DEBUG(dbgs() << "\nMerging into block: " << *PrevBB
900 << "From MBB: " << *TailBB);
Kyle Butt0846e562016-10-11 20:36:43 +0000901 // There may be a branch to the layout successor. This is unlikely but it
902 // happens. The correct thing to do is to remove the branch before
903 // duplicating the instructions in all cases.
904 TII->removeBranch(*PrevBB);
Kyle Butt3232dbb2016-04-08 20:35:01 +0000905 if (PreRegAlloc) {
Krzysztof Parzyszek4773f642016-04-26 18:36:34 +0000906 DenseMap<unsigned, RegSubRegPair> LocalVRMap;
907 SmallVector<std::pair<unsigned, RegSubRegPair>, 4> CopyInfos;
Kyle Butt3232dbb2016-04-08 20:35:01 +0000908 MachineBasicBlock::iterator I = TailBB->begin();
909 // Process PHI instructions first.
910 while (I != TailBB->end() && I->isPHI()) {
911 // Replace the uses of the def of the PHI with the register coming
912 // from PredBB.
913 MachineInstr *MI = &*I++;
914 processPHI(MI, TailBB, PrevBB, LocalVRMap, CopyInfos, UsedByPhi, true);
Kyle Butt3232dbb2016-04-08 20:35:01 +0000915 }
916
917 // Now copy the non-PHI instructions.
918 while (I != TailBB->end()) {
919 // Replace def of virtual registers with new registers, and update
920 // uses with PHI source register or the new registers.
921 MachineInstr *MI = &*I++;
922 assert(!MI->isBundle() && "Not expecting bundles before regalloc!");
Kyle Butt3ed42732016-08-25 01:37:03 +0000923 duplicateInstruction(MI, TailBB, PrevBB, LocalVRMap, UsedByPhi);
Kyle Butt3232dbb2016-04-08 20:35:01 +0000924 MI->eraseFromParent();
925 }
Krzysztof Parzyszek4773f642016-04-26 18:36:34 +0000926 appendCopies(PrevBB, CopyInfos, Copies);
Kyle Butt3232dbb2016-04-08 20:35:01 +0000927 } else {
Kyle Butt0846e562016-10-11 20:36:43 +0000928 TII->removeBranch(*PrevBB);
Kyle Butt3232dbb2016-04-08 20:35:01 +0000929 // No PHIs to worry about, just splice the instructions over.
930 PrevBB->splice(PrevBB->end(), TailBB, TailBB->begin(), TailBB->end());
931 }
932 PrevBB->removeSuccessor(PrevBB->succ_begin());
933 assert(PrevBB->succ_empty());
934 PrevBB->transferSuccessors(TailBB);
935 TDBBs.push_back(PrevBB);
936 Changed = true;
937 }
938
939 // If this is after register allocation, there are no phis to fix.
940 if (!PreRegAlloc)
941 return Changed;
942
943 // If we made no changes so far, we are safe.
944 if (!Changed)
945 return Changed;
946
947 // Handle the nasty case in that we duplicated a block that is part of a loop
948 // into some but not all of its predecessors. For example:
949 // 1 -> 2 <-> 3 |
950 // \ |
951 // \---> rest |
952 // if we duplicate 2 into 1 but not into 3, we end up with
953 // 12 -> 3 <-> 2 -> rest |
954 // \ / |
955 // \----->-----/ |
956 // If there was a "var = phi(1, 3)" in 2, it has to be ultimately replaced
957 // with a phi in 3 (which now dominates 2).
958 // What we do here is introduce a copy in 3 of the register defined by the
959 // phi, just like when we are duplicating 2 into 3, but we don't copy any
960 // real instructions or remove the 3 -> 2 edge from the phi in 2.
Matt Arsenaultb8037a12016-08-16 20:38:05 +0000961 for (MachineBasicBlock *PredBB : Preds) {
David Majnemer0d955d02016-08-11 22:21:41 +0000962 if (is_contained(TDBBs, PredBB))
Kyle Butt3232dbb2016-04-08 20:35:01 +0000963 continue;
964
965 // EH edges
966 if (PredBB->succ_size() != 1)
967 continue;
968
Krzysztof Parzyszek4773f642016-04-26 18:36:34 +0000969 DenseMap<unsigned, RegSubRegPair> LocalVRMap;
970 SmallVector<std::pair<unsigned, RegSubRegPair>, 4> CopyInfos;
Kyle Butt3232dbb2016-04-08 20:35:01 +0000971 MachineBasicBlock::iterator I = TailBB->begin();
972 // Process PHI instructions first.
973 while (I != TailBB->end() && I->isPHI()) {
974 // Replace the uses of the def of the PHI with the register coming
975 // from PredBB.
976 MachineInstr *MI = &*I++;
977 processPHI(MI, TailBB, PredBB, LocalVRMap, CopyInfos, UsedByPhi, false);
978 }
Krzysztof Parzyszek4773f642016-04-26 18:36:34 +0000979 appendCopies(PredBB, CopyInfos, Copies);
Kyle Butt3232dbb2016-04-08 20:35:01 +0000980 }
981
982 return Changed;
983}
984
Krzysztof Parzyszek4773f642016-04-26 18:36:34 +0000985/// At the end of the block \p MBB generate COPY instructions between registers
986/// described by \p CopyInfos. Append resulting instructions to \p Copies.
987void TailDuplicator::appendCopies(MachineBasicBlock *MBB,
988 SmallVectorImpl<std::pair<unsigned,RegSubRegPair>> &CopyInfos,
989 SmallVectorImpl<MachineInstr*> &Copies) {
990 MachineBasicBlock::iterator Loc = MBB->getFirstTerminator();
991 const MCInstrDesc &CopyD = TII->get(TargetOpcode::COPY);
992 for (auto &CI : CopyInfos) {
993 auto C = BuildMI(*MBB, Loc, DebugLoc(), CopyD, CI.first)
994 .addReg(CI.second.Reg, 0, CI.second.SubReg);
995 Copies.push_back(C);
996 }
997}
998
Kyle Butt3232dbb2016-04-08 20:35:01 +0000999/// Remove the specified dead machine basic block from the function, updating
1000/// the CFG.
Kyle Butt0846e562016-10-11 20:36:43 +00001001void TailDuplicator::removeDeadBlock(
1002 MachineBasicBlock *MBB,
Eugene Zelenko6ac7a342017-06-07 23:53:32 +00001003 function_ref<void(MachineBasicBlock *)> *RemovalCallback) {
Kyle Butt3232dbb2016-04-08 20:35:01 +00001004 assert(MBB->pred_empty() && "MBB must be dead!");
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001005 LLVM_DEBUG(dbgs() << "\nRemoving MBB: " << *MBB);
Kyle Butt3232dbb2016-04-08 20:35:01 +00001006
Kyle Butt0846e562016-10-11 20:36:43 +00001007 if (RemovalCallback)
1008 (*RemovalCallback)(MBB);
1009
Kyle Butt3232dbb2016-04-08 20:35:01 +00001010 // Remove all successors.
1011 while (!MBB->succ_empty())
1012 MBB->removeSuccessor(MBB->succ_end() - 1);
1013
1014 // Remove the block.
1015 MBB->eraseFromParent();
1016}