blob: 4d3e02e3174cb470844fa72bc701a11f44fd5163 [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"
Eugene Zelenko6ac7a342017-06-07 23:53:32 +000022#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"
David Blaikie3f833ed2017-11-08 01:01:31 +000030#include "llvm/CodeGen/TargetInstrInfo.h"
David Blaikieb3bde2e2017-11-17 01:07:10 +000031#include "llvm/CodeGen/TargetRegisterInfo.h"
32#include "llvm/CodeGen/TargetSubtargetInfo.h"
Eugene Zelenko6ac7a342017-06-07 23:53:32 +000033#include "llvm/IR/DebugLoc.h"
Kyle Butt3232dbb2016-04-08 20:35:01 +000034#include "llvm/IR/Function.h"
35#include "llvm/Support/CommandLine.h"
36#include "llvm/Support/Debug.h"
37#include "llvm/Support/ErrorHandling.h"
38#include "llvm/Support/raw_ostream.h"
Petar Jovanovic540f4cd2018-01-31 15:57:57 +000039#include "llvm/Target/TargetMachine.h"
Eugene Zelenko6ac7a342017-06-07 23:53:32 +000040#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
Matthias Braun8426d132017-08-23 03:17:59 +000078void TailDuplicator::initMF(MachineFunction &MFin, bool PreRegAlloc,
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;
Matthias Braun8426d132017-08-23 03:17:59 +000092 this->PreRegAlloc = PreRegAlloc;
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) {
Francis Visoiu Mistrih25528d62017-12-04 17:18:51 +0000114 dbgs() << "Malformed PHI in " << printMBBReference(*MBB) << ": "
115 << *MI;
116 dbgs() << " missing input from predecessor "
117 << printMBBReference(*PredBB) << '\n';
Kyle Butt3232dbb2016-04-08 20:35:01 +0000118 llvm_unreachable(nullptr);
119 }
120 }
121
122 for (unsigned i = 1, e = MI->getNumOperands(); i != e; i += 2) {
123 MachineBasicBlock *PHIBB = MI->getOperand(i + 1).getMBB();
124 if (CheckExtra && !Preds.count(PHIBB)) {
Francis Visoiu Mistrih25528d62017-12-04 17:18:51 +0000125 dbgs() << "Warning: malformed PHI in " << printMBBReference(*MBB)
126 << ": " << *MI;
127 dbgs() << " extra input from predecessor "
128 << printMBBReference(*PHIBB) << '\n';
Kyle Butt3232dbb2016-04-08 20:35:01 +0000129 llvm_unreachable(nullptr);
130 }
131 if (PHIBB->getNumber() < 0) {
Francis Visoiu Mistrih25528d62017-12-04 17:18:51 +0000132 dbgs() << "Malformed PHI in " << printMBBReference(*MBB) << ": "
133 << *MI;
134 dbgs() << " non-existing " << printMBBReference(*PHIBB) << '\n';
Kyle Butt3232dbb2016-04-08 20:35:01 +0000135 llvm_unreachable(nullptr);
136 }
137 }
138 ++MI;
139 }
140 }
141}
142
143/// Tail duplicate the block and cleanup.
Kyle Butt723aa132016-08-26 20:12:40 +0000144/// \p IsSimple - return value of isSimpleBB
145/// \p MBB - block to be duplicated
Kyle Butt0846e562016-10-11 20:36:43 +0000146/// \p ForcedLayoutPred - If non-null, treat this block as the layout
147/// predecessor, instead of using the ordering in MF
Kyle Butt723aa132016-08-26 20:12:40 +0000148/// \p DuplicatedPreds - if non-null, \p DuplicatedPreds will contain a list of
149/// all Preds that received a copy of \p MBB.
Kyle Butt0846e562016-10-11 20:36:43 +0000150/// \p RemovalCallback - if non-null, called just before MBB is deleted.
Kyle Butt723aa132016-08-26 20:12:40 +0000151bool TailDuplicator::tailDuplicateAndUpdate(
152 bool IsSimple, MachineBasicBlock *MBB,
Kyle Butt0846e562016-10-11 20:36:43 +0000153 MachineBasicBlock *ForcedLayoutPred,
154 SmallVectorImpl<MachineBasicBlock*> *DuplicatedPreds,
Eugene Zelenko6ac7a342017-06-07 23:53:32 +0000155 function_ref<void(MachineBasicBlock *)> *RemovalCallback) {
Kyle Butt3232dbb2016-04-08 20:35:01 +0000156 // Save the successors list.
157 SmallSetVector<MachineBasicBlock *, 8> Succs(MBB->succ_begin(),
158 MBB->succ_end());
159
160 SmallVector<MachineBasicBlock *, 8> TDBBs;
161 SmallVector<MachineInstr *, 16> Copies;
Kyle Butt0846e562016-10-11 20:36:43 +0000162 if (!tailDuplicate(IsSimple, MBB, ForcedLayoutPred, TDBBs, Copies))
Kyle Butt3232dbb2016-04-08 20:35:01 +0000163 return false;
164
165 ++NumTails;
166
167 SmallVector<MachineInstr *, 8> NewPHIs;
Kyle Butt3ed42732016-08-25 01:37:03 +0000168 MachineSSAUpdater SSAUpdate(*MF, &NewPHIs);
Kyle Butt3232dbb2016-04-08 20:35:01 +0000169
170 // TailBB's immediate successors are now successors of those predecessors
171 // which duplicated TailBB. Add the predecessors as sources to the PHI
172 // instructions.
173 bool isDead = MBB->pred_empty() && !MBB->hasAddressTaken();
174 if (PreRegAlloc)
175 updateSuccessorsPHIs(MBB, isDead, TDBBs, Succs);
176
177 // If it is dead, remove it.
178 if (isDead) {
Geoff Berryf8c29d62016-06-14 19:40:10 +0000179 NumTailDupRemoved += MBB->size();
Kyle Butt0846e562016-10-11 20:36:43 +0000180 removeDeadBlock(MBB, RemovalCallback);
Kyle Butt3232dbb2016-04-08 20:35:01 +0000181 ++NumDeadBlocks;
182 }
183
184 // Update SSA form.
185 if (!SSAUpdateVRs.empty()) {
186 for (unsigned i = 0, e = SSAUpdateVRs.size(); i != e; ++i) {
187 unsigned VReg = SSAUpdateVRs[i];
188 SSAUpdate.Initialize(VReg);
189
190 // If the original definition is still around, add it as an available
191 // value.
192 MachineInstr *DefMI = MRI->getVRegDef(VReg);
193 MachineBasicBlock *DefBB = nullptr;
194 if (DefMI) {
195 DefBB = DefMI->getParent();
196 SSAUpdate.AddAvailableValue(DefBB, VReg);
197 }
198
199 // Add the new vregs as available values.
200 DenseMap<unsigned, AvailableValsTy>::iterator LI =
201 SSAUpdateVals.find(VReg);
202 for (unsigned j = 0, ee = LI->second.size(); j != ee; ++j) {
203 MachineBasicBlock *SrcBB = LI->second[j].first;
204 unsigned SrcReg = LI->second[j].second;
205 SSAUpdate.AddAvailableValue(SrcBB, SrcReg);
206 }
207
208 // Rewrite uses that are outside of the original def's block.
209 MachineRegisterInfo::use_iterator UI = MRI->use_begin(VReg);
210 while (UI != MRI->use_end()) {
211 MachineOperand &UseMO = *UI;
212 MachineInstr *UseMI = UseMO.getParent();
213 ++UI;
214 if (UseMI->isDebugValue()) {
215 // SSAUpdate can replace the use with an undef. That creates
216 // a debug instruction that is a kill.
217 // FIXME: Should it SSAUpdate job to delete debug instructions
218 // instead of replacing the use with undef?
219 UseMI->eraseFromParent();
220 continue;
221 }
222 if (UseMI->getParent() == DefBB && !UseMI->isPHI())
223 continue;
224 SSAUpdate.RewriteUse(UseMO);
225 }
226 }
227
228 SSAUpdateVRs.clear();
229 SSAUpdateVals.clear();
230 }
231
232 // Eliminate some of the copies inserted by tail duplication to maintain
233 // SSA form.
234 for (unsigned i = 0, e = Copies.size(); i != e; ++i) {
235 MachineInstr *Copy = Copies[i];
236 if (!Copy->isCopy())
237 continue;
238 unsigned Dst = Copy->getOperand(0).getReg();
239 unsigned Src = Copy->getOperand(1).getReg();
240 if (MRI->hasOneNonDBGUse(Src) &&
241 MRI->constrainRegClass(Src, MRI->getRegClass(Dst))) {
242 // Copy is the only use. Do trivial copy propagation here.
243 MRI->replaceRegWith(Dst, Src);
244 Copy->eraseFromParent();
245 }
246 }
247
248 if (NewPHIs.size())
249 NumAddedPHIs += NewPHIs.size();
250
Kyle Butt723aa132016-08-26 20:12:40 +0000251 if (DuplicatedPreds)
252 *DuplicatedPreds = std::move(TDBBs);
253
Kyle Butt3232dbb2016-04-08 20:35:01 +0000254 return true;
255}
256
257/// Look for small blocks that are unconditionally branched to and do not fall
258/// through. Tail-duplicate their instructions into their predecessors to
259/// eliminate (dynamic) branches.
Kyle Butt3ed42732016-08-25 01:37:03 +0000260bool TailDuplicator::tailDuplicateBlocks() {
Kyle Butt3232dbb2016-04-08 20:35:01 +0000261 bool MadeChange = false;
262
263 if (PreRegAlloc && TailDupVerify) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000264 LLVM_DEBUG(dbgs() << "\n*** Before tail-duplicating\n");
Kyle Butt3ed42732016-08-25 01:37:03 +0000265 VerifyPHIs(*MF, true);
Kyle Butt3232dbb2016-04-08 20:35:01 +0000266 }
267
Kyle Butt3ed42732016-08-25 01:37:03 +0000268 for (MachineFunction::iterator I = ++MF->begin(), E = MF->end(); I != E;) {
Kyle Butt3232dbb2016-04-08 20:35:01 +0000269 MachineBasicBlock *MBB = &*I++;
270
271 if (NumTails == TailDupLimit)
272 break;
273
274 bool IsSimple = isSimpleBB(MBB);
275
Kyle Butt3ed42732016-08-25 01:37:03 +0000276 if (!shouldTailDuplicate(IsSimple, *MBB))
Kyle Butt3232dbb2016-04-08 20:35:01 +0000277 continue;
278
Kyle Butt0846e562016-10-11 20:36:43 +0000279 MadeChange |= tailDuplicateAndUpdate(IsSimple, MBB, nullptr);
Kyle Butt3232dbb2016-04-08 20:35:01 +0000280 }
281
282 if (PreRegAlloc && TailDupVerify)
Kyle Butt3ed42732016-08-25 01:37:03 +0000283 VerifyPHIs(*MF, false);
Kyle Butt3232dbb2016-04-08 20:35:01 +0000284
285 return MadeChange;
286}
287
288static bool isDefLiveOut(unsigned Reg, MachineBasicBlock *BB,
289 const MachineRegisterInfo *MRI) {
290 for (MachineInstr &UseMI : MRI->use_instructions(Reg)) {
291 if (UseMI.isDebugValue())
292 continue;
293 if (UseMI.getParent() != BB)
294 return true;
295 }
296 return false;
297}
298
299static unsigned getPHISrcRegOpIdx(MachineInstr *MI, MachineBasicBlock *SrcBB) {
300 for (unsigned i = 1, e = MI->getNumOperands(); i != e; i += 2)
301 if (MI->getOperand(i + 1).getMBB() == SrcBB)
302 return i;
303 return 0;
304}
305
306// Remember which registers are used by phis in this block. This is
307// used to determine which registers are liveout while modifying the
308// block (which is why we need to copy the information).
309static void getRegsUsedByPHIs(const MachineBasicBlock &BB,
310 DenseSet<unsigned> *UsedByPhi) {
311 for (const auto &MI : BB) {
312 if (!MI.isPHI())
313 break;
314 for (unsigned i = 1, e = MI.getNumOperands(); i != e; i += 2) {
315 unsigned SrcReg = MI.getOperand(i).getReg();
316 UsedByPhi->insert(SrcReg);
317 }
318 }
319}
320
321/// Add a definition and source virtual registers pair for SSA update.
322void TailDuplicator::addSSAUpdateEntry(unsigned OrigReg, unsigned NewReg,
323 MachineBasicBlock *BB) {
324 DenseMap<unsigned, AvailableValsTy>::iterator LI =
325 SSAUpdateVals.find(OrigReg);
326 if (LI != SSAUpdateVals.end())
327 LI->second.push_back(std::make_pair(BB, NewReg));
328 else {
329 AvailableValsTy Vals;
330 Vals.push_back(std::make_pair(BB, NewReg));
331 SSAUpdateVals.insert(std::make_pair(OrigReg, Vals));
332 SSAUpdateVRs.push_back(OrigReg);
333 }
334}
335
336/// Process PHI node in TailBB by turning it into a copy in PredBB. Remember the
337/// source register that's contributed by PredBB and update SSA update map.
338void TailDuplicator::processPHI(
339 MachineInstr *MI, MachineBasicBlock *TailBB, MachineBasicBlock *PredBB,
Krzysztof Parzyszek4773f642016-04-26 18:36:34 +0000340 DenseMap<unsigned, RegSubRegPair> &LocalVRMap,
341 SmallVectorImpl<std::pair<unsigned, RegSubRegPair>> &Copies,
Kyle Butt3232dbb2016-04-08 20:35:01 +0000342 const DenseSet<unsigned> &RegsUsedByPhi, bool Remove) {
343 unsigned DefReg = MI->getOperand(0).getReg();
344 unsigned SrcOpIdx = getPHISrcRegOpIdx(MI, PredBB);
345 assert(SrcOpIdx && "Unable to find matching PHI source?");
346 unsigned SrcReg = MI->getOperand(SrcOpIdx).getReg();
Krzysztof Parzyszek4773f642016-04-26 18:36:34 +0000347 unsigned SrcSubReg = MI->getOperand(SrcOpIdx).getSubReg();
Kyle Butt3232dbb2016-04-08 20:35:01 +0000348 const TargetRegisterClass *RC = MRI->getRegClass(DefReg);
Krzysztof Parzyszek4773f642016-04-26 18:36:34 +0000349 LocalVRMap.insert(std::make_pair(DefReg, RegSubRegPair(SrcReg, SrcSubReg)));
Kyle Butt3232dbb2016-04-08 20:35:01 +0000350
351 // Insert a copy from source to the end of the block. The def register is the
352 // available value liveout of the block.
353 unsigned NewDef = MRI->createVirtualRegister(RC);
Krzysztof Parzyszek4773f642016-04-26 18:36:34 +0000354 Copies.push_back(std::make_pair(NewDef, RegSubRegPair(SrcReg, SrcSubReg)));
Kyle Butt3232dbb2016-04-08 20:35:01 +0000355 if (isDefLiveOut(DefReg, TailBB, MRI) || RegsUsedByPhi.count(DefReg))
356 addSSAUpdateEntry(DefReg, NewDef, PredBB);
357
358 if (!Remove)
359 return;
360
361 // Remove PredBB from the PHI node.
362 MI->RemoveOperand(SrcOpIdx + 1);
363 MI->RemoveOperand(SrcOpIdx);
364 if (MI->getNumOperands() == 1)
365 MI->eraseFromParent();
366}
367
368/// Duplicate a TailBB instruction to PredBB and update
369/// the source operands due to earlier PHI translation.
370void TailDuplicator::duplicateInstruction(
371 MachineInstr *MI, MachineBasicBlock *TailBB, MachineBasicBlock *PredBB,
Krzysztof Parzyszek4773f642016-04-26 18:36:34 +0000372 DenseMap<unsigned, RegSubRegPair> &LocalVRMap,
Kyle Butt3232dbb2016-04-08 20:35:01 +0000373 const DenseSet<unsigned> &UsedByPhi) {
Petar Jovanovic540f4cd2018-01-31 15:57:57 +0000374 // Allow duplication of CFI instructions.
375 if (MI->isCFIInstruction()) {
376 BuildMI(*PredBB, PredBB->end(), PredBB->findDebugLoc(PredBB->begin()),
377 TII->get(TargetOpcode::CFI_INSTRUCTION)).addCFIIndex(
378 MI->getOperand(0).getCFIIndex());
379 return;
380 }
Matthias Braun55bc9b32017-08-22 23:56:30 +0000381 MachineInstr &NewMI = TII->duplicate(*PredBB, PredBB->end(), *MI);
Kyle Butt3232dbb2016-04-08 20:35:01 +0000382 if (PreRegAlloc) {
Matthias Braun55bc9b32017-08-22 23:56:30 +0000383 for (unsigned i = 0, e = NewMI.getNumOperands(); i != e; ++i) {
384 MachineOperand &MO = NewMI.getOperand(i);
Kyle Butt3232dbb2016-04-08 20:35:01 +0000385 if (!MO.isReg())
386 continue;
387 unsigned Reg = MO.getReg();
388 if (!TargetRegisterInfo::isVirtualRegister(Reg))
389 continue;
390 if (MO.isDef()) {
391 const TargetRegisterClass *RC = MRI->getRegClass(Reg);
392 unsigned NewReg = MRI->createVirtualRegister(RC);
393 MO.setReg(NewReg);
Krzysztof Parzyszek4773f642016-04-26 18:36:34 +0000394 LocalVRMap.insert(std::make_pair(Reg, RegSubRegPair(NewReg, 0)));
Kyle Butt3232dbb2016-04-08 20:35:01 +0000395 if (isDefLiveOut(Reg, TailBB, MRI) || UsedByPhi.count(Reg))
396 addSSAUpdateEntry(Reg, NewReg, PredBB);
397 } else {
Krzysztof Parzyszek4773f642016-04-26 18:36:34 +0000398 auto VI = LocalVRMap.find(Reg);
Kyle Butt3232dbb2016-04-08 20:35:01 +0000399 if (VI != LocalVRMap.end()) {
Krzysztof Parzyszek4773f642016-04-26 18:36:34 +0000400 // Need to make sure that the register class of the mapped register
401 // will satisfy the constraints of the class of the register being
402 // replaced.
403 auto *OrigRC = MRI->getRegClass(Reg);
404 auto *MappedRC = MRI->getRegClass(VI->second.Reg);
405 const TargetRegisterClass *ConstrRC;
406 if (VI->second.SubReg != 0) {
407 ConstrRC = TRI->getMatchingSuperRegClass(MappedRC, OrigRC,
408 VI->second.SubReg);
409 if (ConstrRC) {
410 // The actual constraining (as in "find appropriate new class")
411 // is done by getMatchingSuperRegClass, so now we only need to
412 // change the class of the mapped register.
413 MRI->setRegClass(VI->second.Reg, ConstrRC);
414 }
415 } else {
416 // For mapped registers that do not have sub-registers, simply
417 // restrict their class to match the original one.
418 ConstrRC = MRI->constrainRegClass(VI->second.Reg, OrigRC);
419 }
420
421 if (ConstrRC) {
422 // If the class constraining succeeded, we can simply replace
423 // the old register with the mapped one.
424 MO.setReg(VI->second.Reg);
425 // We have Reg -> VI.Reg:VI.SubReg, so if Reg is used with a
426 // sub-register, we need to compose the sub-register indices.
427 MO.setSubReg(TRI->composeSubRegIndices(MO.getSubReg(),
428 VI->second.SubReg));
429 } else {
430 // The direct replacement is not possible, due to failing register
431 // class constraints. An explicit COPY is necessary. Create one
432 // that can be reused
433 auto *NewRC = MI->getRegClassConstraint(i, TII, TRI);
434 if (NewRC == nullptr)
435 NewRC = OrigRC;
436 unsigned NewReg = MRI->createVirtualRegister(NewRC);
437 BuildMI(*PredBB, MI, MI->getDebugLoc(),
438 TII->get(TargetOpcode::COPY), NewReg)
439 .addReg(VI->second.Reg, 0, VI->second.SubReg);
440 LocalVRMap.erase(VI);
441 LocalVRMap.insert(std::make_pair(Reg, RegSubRegPair(NewReg, 0)));
442 MO.setReg(NewReg);
443 // The composed VI.Reg:VI.SubReg is replaced with NewReg, which
444 // is equivalent to the whole register Reg. Hence, Reg:subreg
445 // is same as NewReg:subreg, so keep the sub-register index
446 // unchanged.
447 }
Kyle Butt3232dbb2016-04-08 20:35:01 +0000448 // Clear any kill flags from this operand. The new register could
449 // have uses after this one, so kills are not valid here.
450 MO.setIsKill(false);
Kyle Butt3232dbb2016-04-08 20:35:01 +0000451 }
452 }
453 }
454 }
Kyle Butt3232dbb2016-04-08 20:35:01 +0000455}
456
457/// After FromBB is tail duplicated into its predecessor blocks, the successors
458/// have gained new predecessors. Update the PHI instructions in them
459/// accordingly.
460void TailDuplicator::updateSuccessorsPHIs(
461 MachineBasicBlock *FromBB, bool isDead,
462 SmallVectorImpl<MachineBasicBlock *> &TDBBs,
463 SmallSetVector<MachineBasicBlock *, 8> &Succs) {
Matt Arsenaultb8037a12016-08-16 20:38:05 +0000464 for (MachineBasicBlock *SuccBB : Succs) {
465 for (MachineInstr &MI : *SuccBB) {
466 if (!MI.isPHI())
Kyle Butt3232dbb2016-04-08 20:35:01 +0000467 break;
Matt Arsenaultb8037a12016-08-16 20:38:05 +0000468 MachineInstrBuilder MIB(*FromBB->getParent(), MI);
Kyle Butt3232dbb2016-04-08 20:35:01 +0000469 unsigned Idx = 0;
Matt Arsenaultb8037a12016-08-16 20:38:05 +0000470 for (unsigned i = 1, e = MI.getNumOperands(); i != e; i += 2) {
471 MachineOperand &MO = MI.getOperand(i + 1);
Kyle Butt3232dbb2016-04-08 20:35:01 +0000472 if (MO.getMBB() == FromBB) {
473 Idx = i;
474 break;
475 }
476 }
477
478 assert(Idx != 0);
Matt Arsenaultb8037a12016-08-16 20:38:05 +0000479 MachineOperand &MO0 = MI.getOperand(Idx);
Kyle Butt3232dbb2016-04-08 20:35:01 +0000480 unsigned Reg = MO0.getReg();
481 if (isDead) {
482 // Folded into the previous BB.
483 // There could be duplicate phi source entries. FIXME: Should sdisel
484 // or earlier pass fixed this?
Matt Arsenaultb8037a12016-08-16 20:38:05 +0000485 for (unsigned i = MI.getNumOperands() - 2; i != Idx; i -= 2) {
486 MachineOperand &MO = MI.getOperand(i + 1);
Kyle Butt3232dbb2016-04-08 20:35:01 +0000487 if (MO.getMBB() == FromBB) {
Matt Arsenaultb8037a12016-08-16 20:38:05 +0000488 MI.RemoveOperand(i + 1);
489 MI.RemoveOperand(i);
Kyle Butt3232dbb2016-04-08 20:35:01 +0000490 }
491 }
492 } else
493 Idx = 0;
494
495 // If Idx is set, the operands at Idx and Idx+1 must be removed.
496 // We reuse the location to avoid expensive RemoveOperand calls.
497
498 DenseMap<unsigned, AvailableValsTy>::iterator LI =
499 SSAUpdateVals.find(Reg);
500 if (LI != SSAUpdateVals.end()) {
501 // This register is defined in the tail block.
502 for (unsigned j = 0, ee = LI->second.size(); j != ee; ++j) {
503 MachineBasicBlock *SrcBB = LI->second[j].first;
504 // If we didn't duplicate a bb into a particular predecessor, we
505 // might still have added an entry to SSAUpdateVals to correcly
506 // recompute SSA. If that case, avoid adding a dummy extra argument
507 // this PHI.
508 if (!SrcBB->isSuccessor(SuccBB))
509 continue;
510
511 unsigned SrcReg = LI->second[j].second;
512 if (Idx != 0) {
Matt Arsenaultb8037a12016-08-16 20:38:05 +0000513 MI.getOperand(Idx).setReg(SrcReg);
514 MI.getOperand(Idx + 1).setMBB(SrcBB);
Kyle Butt3232dbb2016-04-08 20:35:01 +0000515 Idx = 0;
516 } else {
517 MIB.addReg(SrcReg).addMBB(SrcBB);
518 }
519 }
520 } else {
521 // Live in tail block, must also be live in predecessors.
522 for (unsigned j = 0, ee = TDBBs.size(); j != ee; ++j) {
523 MachineBasicBlock *SrcBB = TDBBs[j];
524 if (Idx != 0) {
Matt Arsenaultb8037a12016-08-16 20:38:05 +0000525 MI.getOperand(Idx).setReg(Reg);
526 MI.getOperand(Idx + 1).setMBB(SrcBB);
Kyle Butt3232dbb2016-04-08 20:35:01 +0000527 Idx = 0;
528 } else {
529 MIB.addReg(Reg).addMBB(SrcBB);
530 }
531 }
532 }
533 if (Idx != 0) {
Matt Arsenaultb8037a12016-08-16 20:38:05 +0000534 MI.RemoveOperand(Idx + 1);
535 MI.RemoveOperand(Idx);
Kyle Butt3232dbb2016-04-08 20:35:01 +0000536 }
537 }
538 }
539}
540
541/// Determine if it is profitable to duplicate this block.
Kyle Butt3ed42732016-08-25 01:37:03 +0000542bool TailDuplicator::shouldTailDuplicate(bool IsSimple,
Kyle Butt3232dbb2016-04-08 20:35:01 +0000543 MachineBasicBlock &TailBB) {
Kyle Butt0846e562016-10-11 20:36:43 +0000544 // When doing tail-duplication during layout, the block ordering is in flux,
545 // so canFallThrough returns a result based on incorrect information and
546 // should just be ignored.
547 if (!LayoutMode && TailBB.canFallThrough())
Kyle Butt3232dbb2016-04-08 20:35:01 +0000548 return false;
549
550 // Don't try to tail-duplicate single-block loops.
551 if (TailBB.isSuccessor(&TailBB))
552 return false;
553
554 // Set the limit on the cost to duplicate. When optimizing for size,
555 // duplicate only one, because one branch instruction can be eliminated to
556 // compensate for the duplication.
557 unsigned MaxDuplicateCount;
Kyle Buttdb3391e2016-08-17 21:07:35 +0000558 if (TailDupSize == 0 &&
559 TailDuplicateSize.getNumOccurrences() == 0 &&
Evandro Menezes85bd3972019-04-04 22:40:06 +0000560 MF->getFunction().hasOptSize())
Kyle Butt3232dbb2016-04-08 20:35:01 +0000561 MaxDuplicateCount = 1;
Kyle Buttdb3391e2016-08-17 21:07:35 +0000562 else if (TailDupSize == 0)
Kyle Butt3232dbb2016-04-08 20:35:01 +0000563 MaxDuplicateCount = TailDuplicateSize;
Kyle Buttdb3391e2016-08-17 21:07:35 +0000564 else
565 MaxDuplicateCount = TailDupSize;
Kyle Butt3232dbb2016-04-08 20:35:01 +0000566
Kyle Butt07d61422016-08-16 22:56:14 +0000567 // If the block to be duplicated ends in an unanalyzable fallthrough, don't
568 // duplicate it.
569 // A similar check is necessary in MachineBlockPlacement to make sure pairs of
570 // blocks with unanalyzable fallthrough get layed out contiguously.
571 MachineBasicBlock *PredTBB = nullptr, *PredFBB = nullptr;
572 SmallVector<MachineOperand, 4> PredCond;
Sanjoy Dasd7389d62016-12-15 05:08:57 +0000573 if (TII->analyzeBranch(TailBB, PredTBB, PredFBB, PredCond) &&
574 TailBB.canFallThrough())
Kyle Butt07d61422016-08-16 22:56:14 +0000575 return false;
576
Kyle Butt3232dbb2016-04-08 20:35:01 +0000577 // If the target has hardware branch prediction that can handle indirect
578 // branches, duplicating them can often make them predictable when there
579 // are common paths through the code. The limit needs to be high enough
580 // to allow undoing the effects of tail merging and other optimizations
581 // that rearrange the predecessors of the indirect branch.
582
583 bool HasIndirectbr = false;
584 if (!TailBB.empty())
585 HasIndirectbr = TailBB.back().isIndirectBranch();
586
587 if (HasIndirectbr && PreRegAlloc)
Kyle Butt61aca6e2016-08-30 18:18:54 +0000588 MaxDuplicateCount = TailDupIndirectBranchSize;
Kyle Butt3232dbb2016-04-08 20:35:01 +0000589
590 // Check the instructions in the block to determine whether tail-duplication
591 // is invalid or unlikely to be profitable.
592 unsigned InstrCount = 0;
593 for (MachineInstr &MI : TailBB) {
594 // Non-duplicable things shouldn't be tail-duplicated.
Petar Jovanovic540f4cd2018-01-31 15:57:57 +0000595 // CFI instructions are marked as non-duplicable, because Darwin compact
596 // unwind info emission can't handle multiple prologue setups. In case of
597 // DWARF, allow them be duplicated, so that their existence doesn't prevent
598 // tail duplication of some basic blocks, that would be duplicated otherwise.
599 if (MI.isNotDuplicable() &&
600 (TailBB.getParent()->getTarget().getTargetTriple().isOSDarwin() ||
601 !MI.isCFIInstruction()))
Kyle Butt3232dbb2016-04-08 20:35:01 +0000602 return false;
603
604 // Convergent instructions can be duplicated only if doing so doesn't add
605 // new control dependencies, which is what we're going to do here.
606 if (MI.isConvergent())
607 return false;
608
609 // Do not duplicate 'return' instructions if this is a pre-regalloc run.
610 // A return may expand into a lot more instructions (e.g. reload of callee
611 // saved registers) after PEI.
612 if (PreRegAlloc && MI.isReturn())
613 return false;
614
615 // Avoid duplicating calls before register allocation. Calls presents a
616 // barrier to register allocation so duplicating them may end up increasing
617 // spills.
618 if (PreRegAlloc && MI.isCall())
619 return false;
620
Petar Jovanovic540f4cd2018-01-31 15:57:57 +0000621 if (!MI.isPHI() && !MI.isMetaInstruction())
Reid Kleckner7adb2fd2017-11-08 21:31:14 +0000622 InstrCount += 1;
Kyle Butt3232dbb2016-04-08 20:35:01 +0000623
624 if (InstrCount > MaxDuplicateCount)
625 return false;
626 }
627
628 // Check if any of the successors of TailBB has a PHI node in which the
629 // value corresponding to TailBB uses a subregister.
630 // If a phi node uses a register paired with a subregister, the actual
631 // "value type" of the phi may differ from the type of the register without
632 // any subregisters. Due to a bug, tail duplication may add a new operand
633 // without a necessary subregister, producing an invalid code. This is
634 // demonstrated by test/CodeGen/Hexagon/tail-dup-subreg-abort.ll.
635 // Disable tail duplication for this case for now, until the problem is
636 // fixed.
637 for (auto SB : TailBB.successors()) {
638 for (auto &I : *SB) {
639 if (!I.isPHI())
640 break;
641 unsigned Idx = getPHISrcRegOpIdx(&I, &TailBB);
642 assert(Idx != 0);
643 MachineOperand &PU = I.getOperand(Idx);
644 if (PU.getSubReg() != 0)
645 return false;
646 }
647 }
648
649 if (HasIndirectbr && PreRegAlloc)
650 return true;
651
652 if (IsSimple)
653 return true;
654
655 if (!PreRegAlloc)
656 return true;
657
658 return canCompletelyDuplicateBB(TailBB);
659}
660
661/// True if this BB has only one unconditional jump.
662bool TailDuplicator::isSimpleBB(MachineBasicBlock *TailBB) {
663 if (TailBB->succ_size() != 1)
664 return false;
665 if (TailBB->pred_empty())
666 return false;
667 MachineBasicBlock::iterator I = TailBB->getFirstNonDebugInstr();
668 if (I == TailBB->end())
669 return true;
670 return I->isUnconditionalBranch();
671}
672
673static bool bothUsedInPHI(const MachineBasicBlock &A,
Benjamin Kramerbdc49562016-06-12 15:39:02 +0000674 const SmallPtrSet<MachineBasicBlock *, 8> &SuccsB) {
Kyle Butt3232dbb2016-04-08 20:35:01 +0000675 for (MachineBasicBlock *BB : A.successors())
676 if (SuccsB.count(BB) && !BB->empty() && BB->begin()->isPHI())
677 return true;
678
679 return false;
680}
681
682bool TailDuplicator::canCompletelyDuplicateBB(MachineBasicBlock &BB) {
683 for (MachineBasicBlock *PredBB : BB.predecessors()) {
684 if (PredBB->succ_size() > 1)
685 return false;
686
687 MachineBasicBlock *PredTBB = nullptr, *PredFBB = nullptr;
688 SmallVector<MachineOperand, 4> PredCond;
Sanjoy Dasd7389d62016-12-15 05:08:57 +0000689 if (TII->analyzeBranch(*PredBB, PredTBB, PredFBB, PredCond))
Kyle Butt3232dbb2016-04-08 20:35:01 +0000690 return false;
691
692 if (!PredCond.empty())
693 return false;
694 }
695 return true;
696}
697
698bool TailDuplicator::duplicateSimpleBB(
699 MachineBasicBlock *TailBB, SmallVectorImpl<MachineBasicBlock *> &TDBBs,
700 const DenseSet<unsigned> &UsedByPhi,
701 SmallVectorImpl<MachineInstr *> &Copies) {
702 SmallPtrSet<MachineBasicBlock *, 8> Succs(TailBB->succ_begin(),
703 TailBB->succ_end());
704 SmallVector<MachineBasicBlock *, 8> Preds(TailBB->pred_begin(),
705 TailBB->pred_end());
706 bool Changed = false;
Matt Arsenaultb8037a12016-08-16 20:38:05 +0000707 for (MachineBasicBlock *PredBB : Preds) {
Kyle Butt3232dbb2016-04-08 20:35:01 +0000708 if (PredBB->hasEHPadSuccessor())
709 continue;
710
711 if (bothUsedInPHI(*PredBB, Succs))
712 continue;
713
714 MachineBasicBlock *PredTBB = nullptr, *PredFBB = nullptr;
715 SmallVector<MachineOperand, 4> PredCond;
Sanjoy Dasd7389d62016-12-15 05:08:57 +0000716 if (TII->analyzeBranch(*PredBB, PredTBB, PredFBB, PredCond))
Kyle Butt3232dbb2016-04-08 20:35:01 +0000717 continue;
718
719 Changed = true;
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000720 LLVM_DEBUG(dbgs() << "\nTail-duplicating into PredBB: " << *PredBB
721 << "From simple Succ: " << *TailBB);
Kyle Butt3232dbb2016-04-08 20:35:01 +0000722
723 MachineBasicBlock *NewTarget = *TailBB->succ_begin();
Matthias Braun6442fc12016-08-18 00:59:32 +0000724 MachineBasicBlock *NextBB = PredBB->getNextNode();
Kyle Butt3232dbb2016-04-08 20:35:01 +0000725
726 // Make PredFBB explicit.
727 if (PredCond.empty())
728 PredFBB = PredTBB;
729
730 // Make fall through explicit.
731 if (!PredTBB)
732 PredTBB = NextBB;
733 if (!PredFBB)
734 PredFBB = NextBB;
735
736 // Redirect
737 if (PredFBB == TailBB)
738 PredFBB = NewTarget;
739 if (PredTBB == TailBB)
740 PredTBB = NewTarget;
741
742 // Make the branch unconditional if possible
743 if (PredTBB == PredFBB) {
744 PredCond.clear();
745 PredFBB = nullptr;
746 }
747
748 // Avoid adding fall through branches.
749 if (PredFBB == NextBB)
750 PredFBB = nullptr;
751 if (PredTBB == NextBB && PredFBB == nullptr)
752 PredTBB = nullptr;
753
Taewook Oha49eb852017-02-27 19:30:01 +0000754 auto DL = PredBB->findBranchDebugLoc();
Matt Arsenault1b9fc8e2016-09-14 20:43:16 +0000755 TII->removeBranch(*PredBB);
Kyle Butt3232dbb2016-04-08 20:35:01 +0000756
757 if (!PredBB->isSuccessor(NewTarget))
758 PredBB->replaceSuccessor(TailBB, NewTarget);
759 else {
760 PredBB->removeSuccessor(TailBB, true);
761 assert(PredBB->succ_size() <= 1);
762 }
763
764 if (PredTBB)
Taewook Oha49eb852017-02-27 19:30:01 +0000765 TII->insertBranch(*PredBB, PredTBB, PredFBB, PredCond, DL);
Kyle Butt3232dbb2016-04-08 20:35:01 +0000766
767 TDBBs.push_back(PredBB);
768 }
769 return Changed;
770}
771
Kyle Butt9e52c062016-07-19 23:54:21 +0000772bool TailDuplicator::canTailDuplicate(MachineBasicBlock *TailBB,
773 MachineBasicBlock *PredBB) {
Kyle Butt0846e562016-10-11 20:36:43 +0000774 // EH edges are ignored by analyzeBranch.
Kyle Butt9e52c062016-07-19 23:54:21 +0000775 if (PredBB->succ_size() > 1)
776 return false;
777
Vitaly Bukab238cb82017-05-22 21:33:54 +0000778 MachineBasicBlock *PredTBB = nullptr, *PredFBB = nullptr;
Kyle Butt9e52c062016-07-19 23:54:21 +0000779 SmallVector<MachineOperand, 4> PredCond;
Sanjoy Dasd7389d62016-12-15 05:08:57 +0000780 if (TII->analyzeBranch(*PredBB, PredTBB, PredFBB, PredCond))
Kyle Butt9e52c062016-07-19 23:54:21 +0000781 return false;
782 if (!PredCond.empty())
783 return false;
784 return true;
785}
786
Kyle Butt3232dbb2016-04-08 20:35:01 +0000787/// If it is profitable, duplicate TailBB's contents in each
788/// of its predecessors.
Kyle Butt0846e562016-10-11 20:36:43 +0000789/// \p IsSimple result of isSimpleBB
790/// \p TailBB Block to be duplicated.
791/// \p ForcedLayoutPred When non-null, use this block as the layout predecessor
792/// instead of the previous block in MF's order.
793/// \p TDBBs A vector to keep track of all blocks tail-duplicated
794/// into.
795/// \p Copies A vector of copy instructions inserted. Used later to
796/// walk all the inserted copies and remove redundant ones.
Kyle Butt3ed42732016-08-25 01:37:03 +0000797bool TailDuplicator::tailDuplicate(bool IsSimple, MachineBasicBlock *TailBB,
Kyle Butt0846e562016-10-11 20:36:43 +0000798 MachineBasicBlock *ForcedLayoutPred,
Kyle Butt3232dbb2016-04-08 20:35:01 +0000799 SmallVectorImpl<MachineBasicBlock *> &TDBBs,
800 SmallVectorImpl<MachineInstr *> &Copies) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000801 LLVM_DEBUG(dbgs() << "\n*** Tail-duplicating " << printMBBReference(*TailBB)
802 << '\n');
Kyle Butt3232dbb2016-04-08 20:35:01 +0000803
804 DenseSet<unsigned> UsedByPhi;
805 getRegsUsedByPHIs(*TailBB, &UsedByPhi);
806
807 if (IsSimple)
808 return duplicateSimpleBB(TailBB, TDBBs, UsedByPhi, Copies);
809
810 // Iterate through all the unique predecessors and tail-duplicate this
811 // block into them, if possible. Copying the list ahead of time also
812 // avoids trouble with the predecessor list reallocating.
813 bool Changed = false;
814 SmallSetVector<MachineBasicBlock *, 8> Preds(TailBB->pred_begin(),
815 TailBB->pred_end());
Matt Arsenaultb8037a12016-08-16 20:38:05 +0000816 for (MachineBasicBlock *PredBB : Preds) {
Kyle Butt3232dbb2016-04-08 20:35:01 +0000817 assert(TailBB != PredBB &&
818 "Single-block loop should have been rejected earlier!");
Kyle Butt9e52c062016-07-19 23:54:21 +0000819
820 if (!canTailDuplicate(TailBB, PredBB))
Kyle Butt3232dbb2016-04-08 20:35:01 +0000821 continue;
822
Kyle Butt3232dbb2016-04-08 20:35:01 +0000823 // Don't duplicate into a fall-through predecessor (at least for now).
Kyle Butt0846e562016-10-11 20:36:43 +0000824 bool IsLayoutSuccessor = false;
825 if (ForcedLayoutPred)
826 IsLayoutSuccessor = (ForcedLayoutPred == PredBB);
827 else if (PredBB->isLayoutSuccessor(TailBB) && PredBB->canFallThrough())
828 IsLayoutSuccessor = true;
829 if (IsLayoutSuccessor)
Kyle Butt3232dbb2016-04-08 20:35:01 +0000830 continue;
831
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000832 LLVM_DEBUG(dbgs() << "\nTail-duplicating into PredBB: " << *PredBB
833 << "From Succ: " << *TailBB);
Kyle Butt3232dbb2016-04-08 20:35:01 +0000834
835 TDBBs.push_back(PredBB);
836
837 // Remove PredBB's unconditional branch.
Matt Arsenault1b9fc8e2016-09-14 20:43:16 +0000838 TII->removeBranch(*PredBB);
Kyle Butt3232dbb2016-04-08 20:35:01 +0000839
Kyle Butt3232dbb2016-04-08 20:35:01 +0000840 // Clone the contents of TailBB into PredBB.
Krzysztof Parzyszek4773f642016-04-26 18:36:34 +0000841 DenseMap<unsigned, RegSubRegPair> LocalVRMap;
842 SmallVector<std::pair<unsigned, RegSubRegPair>, 4> CopyInfos;
Matthias Braun55bc9b32017-08-22 23:56:30 +0000843 for (MachineBasicBlock::iterator I = TailBB->begin(), E = TailBB->end();
844 I != E; /* empty */) {
Kyle Butt3232dbb2016-04-08 20:35:01 +0000845 MachineInstr *MI = &*I;
846 ++I;
847 if (MI->isPHI()) {
848 // Replace the uses of the def of the PHI with the register coming
849 // from PredBB.
850 processPHI(MI, TailBB, PredBB, LocalVRMap, CopyInfos, UsedByPhi, true);
851 } else {
852 // Replace def of virtual registers with new registers, and update
853 // uses with PHI source register or the new registers.
Kyle Butt3ed42732016-08-25 01:37:03 +0000854 duplicateInstruction(MI, TailBB, PredBB, LocalVRMap, UsedByPhi);
Kyle Butt3232dbb2016-04-08 20:35:01 +0000855 }
856 }
Krzysztof Parzyszek4773f642016-04-26 18:36:34 +0000857 appendCopies(PredBB, CopyInfos, Copies);
Kyle Butt3232dbb2016-04-08 20:35:01 +0000858
Geoff Berryf8c29d62016-06-14 19:40:10 +0000859 NumTailDupAdded += TailBB->size() - 1; // subtract one for removed branch
Kyle Butt3232dbb2016-04-08 20:35:01 +0000860
861 // Update the CFG.
862 PredBB->removeSuccessor(PredBB->succ_begin());
863 assert(PredBB->succ_empty() &&
864 "TailDuplicate called on block with multiple successors!");
Matt Arsenaultb8037a12016-08-16 20:38:05 +0000865 for (MachineBasicBlock *Succ : TailBB->successors())
866 PredBB->addSuccessor(Succ, MBPI->getEdgeProbability(TailBB, Succ));
Kyle Butt3232dbb2016-04-08 20:35:01 +0000867
868 Changed = true;
869 ++NumTailDups;
870 }
871
872 // If TailBB was duplicated into all its predecessors except for the prior
873 // block, which falls through unconditionally, move the contents of this
874 // block into the prior block.
Kyle Butt0846e562016-10-11 20:36:43 +0000875 MachineBasicBlock *PrevBB = ForcedLayoutPred;
876 if (!PrevBB)
877 PrevBB = &*std::prev(TailBB->getIterator());
Kyle Butt3232dbb2016-04-08 20:35:01 +0000878 MachineBasicBlock *PriorTBB = nullptr, *PriorFBB = nullptr;
879 SmallVector<MachineOperand, 4> PriorCond;
880 // This has to check PrevBB->succ_size() because EH edges are ignored by
Kyle Butt0846e562016-10-11 20:36:43 +0000881 // analyzeBranch.
Kyle Butt3232dbb2016-04-08 20:35:01 +0000882 if (PrevBB->succ_size() == 1 &&
Kyle Buttd2b886e2016-07-20 00:01:51 +0000883 // Layout preds are not always CFG preds. Check.
884 *PrevBB->succ_begin() == TailBB &&
Sanjoy Dasd7389d62016-12-15 05:08:57 +0000885 !TII->analyzeBranch(*PrevBB, PriorTBB, PriorFBB, PriorCond) &&
Kyle Butt0846e562016-10-11 20:36:43 +0000886 PriorCond.empty() &&
887 (!PriorTBB || PriorTBB == TailBB) &&
888 TailBB->pred_size() == 1 &&
Kyle Butt3232dbb2016-04-08 20:35:01 +0000889 !TailBB->hasAddressTaken()) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000890 LLVM_DEBUG(dbgs() << "\nMerging into block: " << *PrevBB
891 << "From MBB: " << *TailBB);
Kyle Butt0846e562016-10-11 20:36:43 +0000892 // There may be a branch to the layout successor. This is unlikely but it
893 // happens. The correct thing to do is to remove the branch before
894 // duplicating the instructions in all cases.
895 TII->removeBranch(*PrevBB);
Kyle Butt3232dbb2016-04-08 20:35:01 +0000896 if (PreRegAlloc) {
Krzysztof Parzyszek4773f642016-04-26 18:36:34 +0000897 DenseMap<unsigned, RegSubRegPair> LocalVRMap;
898 SmallVector<std::pair<unsigned, RegSubRegPair>, 4> CopyInfos;
Kyle Butt3232dbb2016-04-08 20:35:01 +0000899 MachineBasicBlock::iterator I = TailBB->begin();
900 // Process PHI instructions first.
901 while (I != TailBB->end() && I->isPHI()) {
902 // Replace the uses of the def of the PHI with the register coming
903 // from PredBB.
904 MachineInstr *MI = &*I++;
905 processPHI(MI, TailBB, PrevBB, LocalVRMap, CopyInfos, UsedByPhi, true);
Kyle Butt3232dbb2016-04-08 20:35:01 +0000906 }
907
908 // Now copy the non-PHI instructions.
909 while (I != TailBB->end()) {
910 // Replace def of virtual registers with new registers, and update
911 // uses with PHI source register or the new registers.
912 MachineInstr *MI = &*I++;
913 assert(!MI->isBundle() && "Not expecting bundles before regalloc!");
Kyle Butt3ed42732016-08-25 01:37:03 +0000914 duplicateInstruction(MI, TailBB, PrevBB, LocalVRMap, UsedByPhi);
Kyle Butt3232dbb2016-04-08 20:35:01 +0000915 MI->eraseFromParent();
916 }
Krzysztof Parzyszek4773f642016-04-26 18:36:34 +0000917 appendCopies(PrevBB, CopyInfos, Copies);
Kyle Butt3232dbb2016-04-08 20:35:01 +0000918 } else {
Kyle Butt0846e562016-10-11 20:36:43 +0000919 TII->removeBranch(*PrevBB);
Kyle Butt3232dbb2016-04-08 20:35:01 +0000920 // No PHIs to worry about, just splice the instructions over.
921 PrevBB->splice(PrevBB->end(), TailBB, TailBB->begin(), TailBB->end());
922 }
923 PrevBB->removeSuccessor(PrevBB->succ_begin());
924 assert(PrevBB->succ_empty());
925 PrevBB->transferSuccessors(TailBB);
926 TDBBs.push_back(PrevBB);
927 Changed = true;
928 }
929
930 // If this is after register allocation, there are no phis to fix.
931 if (!PreRegAlloc)
932 return Changed;
933
934 // If we made no changes so far, we are safe.
935 if (!Changed)
936 return Changed;
937
938 // Handle the nasty case in that we duplicated a block that is part of a loop
939 // into some but not all of its predecessors. For example:
940 // 1 -> 2 <-> 3 |
941 // \ |
942 // \---> rest |
943 // if we duplicate 2 into 1 but not into 3, we end up with
944 // 12 -> 3 <-> 2 -> rest |
945 // \ / |
946 // \----->-----/ |
947 // If there was a "var = phi(1, 3)" in 2, it has to be ultimately replaced
948 // with a phi in 3 (which now dominates 2).
949 // What we do here is introduce a copy in 3 of the register defined by the
950 // phi, just like when we are duplicating 2 into 3, but we don't copy any
951 // real instructions or remove the 3 -> 2 edge from the phi in 2.
Matt Arsenaultb8037a12016-08-16 20:38:05 +0000952 for (MachineBasicBlock *PredBB : Preds) {
David Majnemer0d955d02016-08-11 22:21:41 +0000953 if (is_contained(TDBBs, PredBB))
Kyle Butt3232dbb2016-04-08 20:35:01 +0000954 continue;
955
956 // EH edges
957 if (PredBB->succ_size() != 1)
958 continue;
959
Krzysztof Parzyszek4773f642016-04-26 18:36:34 +0000960 DenseMap<unsigned, RegSubRegPair> LocalVRMap;
961 SmallVector<std::pair<unsigned, RegSubRegPair>, 4> CopyInfos;
Kyle Butt3232dbb2016-04-08 20:35:01 +0000962 MachineBasicBlock::iterator I = TailBB->begin();
963 // Process PHI instructions first.
964 while (I != TailBB->end() && I->isPHI()) {
965 // Replace the uses of the def of the PHI with the register coming
966 // from PredBB.
967 MachineInstr *MI = &*I++;
968 processPHI(MI, TailBB, PredBB, LocalVRMap, CopyInfos, UsedByPhi, false);
969 }
Krzysztof Parzyszek4773f642016-04-26 18:36:34 +0000970 appendCopies(PredBB, CopyInfos, Copies);
Kyle Butt3232dbb2016-04-08 20:35:01 +0000971 }
972
973 return Changed;
974}
975
Krzysztof Parzyszek4773f642016-04-26 18:36:34 +0000976/// At the end of the block \p MBB generate COPY instructions between registers
977/// described by \p CopyInfos. Append resulting instructions to \p Copies.
978void TailDuplicator::appendCopies(MachineBasicBlock *MBB,
979 SmallVectorImpl<std::pair<unsigned,RegSubRegPair>> &CopyInfos,
980 SmallVectorImpl<MachineInstr*> &Copies) {
981 MachineBasicBlock::iterator Loc = MBB->getFirstTerminator();
982 const MCInstrDesc &CopyD = TII->get(TargetOpcode::COPY);
983 for (auto &CI : CopyInfos) {
984 auto C = BuildMI(*MBB, Loc, DebugLoc(), CopyD, CI.first)
985 .addReg(CI.second.Reg, 0, CI.second.SubReg);
986 Copies.push_back(C);
987 }
988}
989
Kyle Butt3232dbb2016-04-08 20:35:01 +0000990/// Remove the specified dead machine basic block from the function, updating
991/// the CFG.
Kyle Butt0846e562016-10-11 20:36:43 +0000992void TailDuplicator::removeDeadBlock(
993 MachineBasicBlock *MBB,
Eugene Zelenko6ac7a342017-06-07 23:53:32 +0000994 function_ref<void(MachineBasicBlock *)> *RemovalCallback) {
Kyle Butt3232dbb2016-04-08 20:35:01 +0000995 assert(MBB->pred_empty() && "MBB must be dead!");
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000996 LLVM_DEBUG(dbgs() << "\nRemoving MBB: " << *MBB);
Kyle Butt3232dbb2016-04-08 20:35:01 +0000997
Kyle Butt0846e562016-10-11 20:36:43 +0000998 if (RemovalCallback)
999 (*RemovalCallback)(MBB);
1000
Kyle Butt3232dbb2016-04-08 20:35:01 +00001001 // Remove all successors.
1002 while (!MBB->succ_empty())
1003 MBB->removeSuccessor(MBB->succ_end() - 1);
1004
1005 // Remove the block.
1006 MBB->eraseFromParent();
1007}