1 //===- MachineSink.cpp - Sinking for machine instructions -----------------===//
2 //
3 // 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
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This pass moves instructions into successor blocks when possible, so that
10 // they aren't executed on paths where their results aren't needed.
11 //
12 // This pass is not intended to be a replacement or a complete alternative
13 // for an LLVM-IR-level sinking pass. It is only designed to sink simple
14 // constructs that are not exposed before lowering and instruction selection.
15 //
16 //===----------------------------------------------------------------------===//
17
18 #include "llvm/ADT/DenseSet.h"
19 #include "llvm/ADT/PointerIntPair.h"
20 #include "llvm/ADT/SetVector.h"
21 #include "llvm/ADT/SmallSet.h"
22 #include "llvm/ADT/SmallVector.h"
23 #include "llvm/ADT/SparseBitVector.h"
24 #include "llvm/ADT/Statistic.h"
25 #include "llvm/Analysis/AliasAnalysis.h"
26 #include "llvm/CodeGen/MachineBasicBlock.h"
27 #include "llvm/CodeGen/MachineBlockFrequencyInfo.h"
28 #include "llvm/CodeGen/MachineBranchProbabilityInfo.h"
29 #include "llvm/CodeGen/MachineDominators.h"
30 #include "llvm/CodeGen/MachineFunction.h"
31 #include "llvm/CodeGen/MachineFunctionPass.h"
32 #include "llvm/CodeGen/MachineInstr.h"
33 #include "llvm/CodeGen/MachineLoopInfo.h"
34 #include "llvm/CodeGen/MachineOperand.h"
35 #include "llvm/CodeGen/MachinePostDominators.h"
36 #include "llvm/CodeGen/MachineRegisterInfo.h"
37 #include "llvm/CodeGen/RegisterClassInfo.h"
38 #include "llvm/CodeGen/RegisterPressure.h"
39 #include "llvm/CodeGen/TargetInstrInfo.h"
40 #include "llvm/CodeGen/TargetRegisterInfo.h"
41 #include "llvm/CodeGen/TargetSubtargetInfo.h"
42 #include "llvm/IR/BasicBlock.h"
43 #include "llvm/IR/DebugInfoMetadata.h"
44 #include "llvm/IR/LLVMContext.h"
45 #include "llvm/InitializePasses.h"
46 #include "llvm/MC/MCRegisterInfo.h"
47 #include "llvm/Pass.h"
48 #include "llvm/Support/BranchProbability.h"
49 #include "llvm/Support/CommandLine.h"
50 #include "llvm/Support/Debug.h"
51 #include "llvm/Support/raw_ostream.h"
52 #include <algorithm>
53 #include <cassert>
54 #include <cstdint>
55 #include <map>
56 #include <utility>
57 #include <vector>
58
59 using namespace llvm;
60
61 #define DEBUG_TYPE "machine-sink"
62
63 static cl::opt<bool>
64 SplitEdges("machine-sink-split",
65 cl::desc("Split critical edges during machine sinking"),
66 cl::init(true), cl::Hidden);
67
68 static cl::opt<bool>
69 UseBlockFreqInfo("machine-sink-bfi",
70 cl::desc("Use block frequency info to find successors to sink"),
71 cl::init(true), cl::Hidden);
72
73 static cl::opt<unsigned> SplitEdgeProbabilityThreshold(
74 "machine-sink-split-probability-threshold",
75 cl::desc(
76 "Percentage threshold for splitting single-instruction critical edge. "
77 "If the branch threshold is higher than this threshold, we allow "
78 "speculative execution of up to 1 instruction to avoid branching to "
79 "splitted critical edge"),
80 cl::init(40), cl::Hidden);
81
82 STATISTIC(NumSunk, "Number of machine instructions sunk");
83 STATISTIC(NumSplit, "Number of critical edges split");
84 STATISTIC(NumCoalesces, "Number of copies coalesced");
85 STATISTIC(NumPostRACopySink, "Number of copies sunk after RA");
86
87 namespace {
88
89 class MachineSinking : public MachineFunctionPass {
90 const TargetInstrInfo *TII;
91 const TargetRegisterInfo *TRI;
92 MachineRegisterInfo *MRI; // Machine register information
93 MachineDominatorTree *DT; // Machine dominator tree
94 MachinePostDominatorTree *PDT; // Machine post dominator tree
95 MachineLoopInfo *LI;
96 MachineBlockFrequencyInfo *MBFI;
97 const MachineBranchProbabilityInfo *MBPI;
98 AliasAnalysis *AA;
99 RegisterClassInfo RegClassInfo;
100
101 // Remember which edges have been considered for breaking.
102 SmallSet<std::pair<MachineBasicBlock*, MachineBasicBlock*>, 8>
103 CEBCandidates;
104 // Remember which edges we are about to split.
105 // This is different from CEBCandidates since those edges
106 // will be split.
107 SetVector<std::pair<MachineBasicBlock *, MachineBasicBlock *>> ToSplit;
108
109 SparseBitVector<> RegsToClearKillFlags;
110
111 using AllSuccsCache =
112 std::map<MachineBasicBlock *, SmallVector<MachineBasicBlock *, 4>>;
113
114 /// DBG_VALUE pointer and flag. The flag is true if this DBG_VALUE is
115 /// post-dominated by another DBG_VALUE of the same variable location.
116 /// This is necessary to detect sequences such as:
117 /// %0 = someinst
118 /// DBG_VALUE %0, !123, !DIExpression()
119 /// %1 = anotherinst
120 /// DBG_VALUE %1, !123, !DIExpression()
121 /// Where if %0 were to sink, the DBG_VAUE should not sink with it, as that
122 /// would re-order assignments.
123 using SeenDbgUser = PointerIntPair<MachineInstr *, 1>;
124
125 /// Record of DBG_VALUE uses of vregs in a block, so that we can identify
126 /// debug instructions to sink.
127 SmallDenseMap<unsigned, TinyPtrVector<SeenDbgUser>> SeenDbgUsers;
128
129 /// Record of debug variables that have had their locations set in the
130 /// current block.
131 DenseSet<DebugVariable> SeenDbgVars;
132
133 std::map<std::pair<MachineBasicBlock *, MachineBasicBlock *>, bool>
134 HasStoreCache;
135 std::map<std::pair<MachineBasicBlock *, MachineBasicBlock *>,
136 std::vector<MachineInstr *>>
137 StoreInstrCache;
138
139 /// Cached BB's register pressure.
140 std::map<MachineBasicBlock *, std::vector<unsigned>> CachedRegisterPressure;
141
142 public:
143 static char ID; // Pass identification
144
MachineSinking()145 MachineSinking() : MachineFunctionPass(ID) {
146 initializeMachineSinkingPass(*PassRegistry::getPassRegistry());
147 }
148
149 bool runOnMachineFunction(MachineFunction &MF) override;
150
getAnalysisUsage(AnalysisUsage & AU) const151 void getAnalysisUsage(AnalysisUsage &AU) const override {
152 MachineFunctionPass::getAnalysisUsage(AU);
153 AU.addRequired<AAResultsWrapperPass>();
154 AU.addRequired<MachineDominatorTree>();
155 AU.addRequired<MachinePostDominatorTree>();
156 AU.addRequired<MachineLoopInfo>();
157 AU.addRequired<MachineBranchProbabilityInfo>();
158 AU.addPreserved<MachineLoopInfo>();
159 if (UseBlockFreqInfo)
160 AU.addRequired<MachineBlockFrequencyInfo>();
161 }
162
releaseMemory()163 void releaseMemory() override {
164 CEBCandidates.clear();
165 }
166
167 private:
168 bool ProcessBlock(MachineBasicBlock &MBB);
169 void ProcessDbgInst(MachineInstr &MI);
170 bool isWorthBreakingCriticalEdge(MachineInstr &MI,
171 MachineBasicBlock *From,
172 MachineBasicBlock *To);
173
174 bool hasStoreBetween(MachineBasicBlock *From, MachineBasicBlock *To,
175 MachineInstr &MI);
176
177 /// Postpone the splitting of the given critical
178 /// edge (\p From, \p To).
179 ///
180 /// We do not split the edges on the fly. Indeed, this invalidates
181 /// the dominance information and thus triggers a lot of updates
182 /// of that information underneath.
183 /// Instead, we postpone all the splits after each iteration of
184 /// the main loop. That way, the information is at least valid
185 /// for the lifetime of an iteration.
186 ///
187 /// \return True if the edge is marked as toSplit, false otherwise.
188 /// False can be returned if, for instance, this is not profitable.
189 bool PostponeSplitCriticalEdge(MachineInstr &MI,
190 MachineBasicBlock *From,
191 MachineBasicBlock *To,
192 bool BreakPHIEdge);
193 bool SinkInstruction(MachineInstr &MI, bool &SawStore,
194 AllSuccsCache &AllSuccessors);
195
196 /// If we sink a COPY inst, some debug users of it's destination may no
197 /// longer be dominated by the COPY, and will eventually be dropped.
198 /// This is easily rectified by forwarding the non-dominated debug uses
199 /// to the copy source.
200 void SalvageUnsunkDebugUsersOfCopy(MachineInstr &,
201 MachineBasicBlock *TargetBlock);
202 bool AllUsesDominatedByBlock(Register Reg, MachineBasicBlock *MBB,
203 MachineBasicBlock *DefMBB, bool &BreakPHIEdge,
204 bool &LocalUse) const;
205 MachineBasicBlock *FindSuccToSinkTo(MachineInstr &MI, MachineBasicBlock *MBB,
206 bool &BreakPHIEdge, AllSuccsCache &AllSuccessors);
207 bool isProfitableToSinkTo(Register Reg, MachineInstr &MI,
208 MachineBasicBlock *MBB,
209 MachineBasicBlock *SuccToSinkTo,
210 AllSuccsCache &AllSuccessors);
211
212 bool PerformTrivialForwardCoalescing(MachineInstr &MI,
213 MachineBasicBlock *MBB);
214
215 SmallVector<MachineBasicBlock *, 4> &
216 GetAllSortedSuccessors(MachineInstr &MI, MachineBasicBlock *MBB,
217 AllSuccsCache &AllSuccessors) const;
218
219 std::vector<unsigned> &getBBRegisterPressure(MachineBasicBlock &MBB);
220 };
221
222 } // end anonymous namespace
223
224 char MachineSinking::ID = 0;
225
226 char &llvm::MachineSinkingID = MachineSinking::ID;
227
228 INITIALIZE_PASS_BEGIN(MachineSinking, DEBUG_TYPE,
229 "Machine code sinking", false, false)
INITIALIZE_PASS_DEPENDENCY(MachineBranchProbabilityInfo)230 INITIALIZE_PASS_DEPENDENCY(MachineBranchProbabilityInfo)
231 INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)
232 INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)
233 INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
234 INITIALIZE_PASS_END(MachineSinking, DEBUG_TYPE,
235 "Machine code sinking", false, false)
236
237 bool MachineSinking::PerformTrivialForwardCoalescing(MachineInstr &MI,
238 MachineBasicBlock *MBB) {
239 if (!MI.isCopy())
240 return false;
241
242 Register SrcReg = MI.getOperand(1).getReg();
243 Register DstReg = MI.getOperand(0).getReg();
244 if (!Register::isVirtualRegister(SrcReg) ||
245 !Register::isVirtualRegister(DstReg) || !MRI->hasOneNonDBGUse(SrcReg))
246 return false;
247
248 const TargetRegisterClass *SRC = MRI->getRegClass(SrcReg);
249 const TargetRegisterClass *DRC = MRI->getRegClass(DstReg);
250 if (SRC != DRC)
251 return false;
252
253 MachineInstr *DefMI = MRI->getVRegDef(SrcReg);
254 if (DefMI->isCopyLike())
255 return false;
256 LLVM_DEBUG(dbgs() << "Coalescing: " << *DefMI);
257 LLVM_DEBUG(dbgs() << "*** to: " << MI);
258 MRI->replaceRegWith(DstReg, SrcReg);
259 MI.eraseFromParent();
260
261 // Conservatively, clear any kill flags, since it's possible that they are no
262 // longer correct.
263 MRI->clearKillFlags(SrcReg);
264
265 ++NumCoalesces;
266 return true;
267 }
268
269 /// AllUsesDominatedByBlock - Return true if all uses of the specified register
270 /// occur in blocks dominated by the specified block. If any use is in the
271 /// definition block, then return false since it is never legal to move def
272 /// after uses.
AllUsesDominatedByBlock(Register Reg,MachineBasicBlock * MBB,MachineBasicBlock * DefMBB,bool & BreakPHIEdge,bool & LocalUse) const273 bool MachineSinking::AllUsesDominatedByBlock(Register Reg,
274 MachineBasicBlock *MBB,
275 MachineBasicBlock *DefMBB,
276 bool &BreakPHIEdge,
277 bool &LocalUse) const {
278 assert(Register::isVirtualRegister(Reg) && "Only makes sense for vregs");
279
280 // Ignore debug uses because debug info doesn't affect the code.
281 if (MRI->use_nodbg_empty(Reg))
282 return true;
283
284 // BreakPHIEdge is true if all the uses are in the successor MBB being sunken
285 // into and they are all PHI nodes. In this case, machine-sink must break
286 // the critical edge first. e.g.
287 //
288 // %bb.1:
289 // Predecessors according to CFG: %bb.0
290 // ...
291 // %def = DEC64_32r %x, implicit-def dead %eflags
292 // ...
293 // JE_4 <%bb.37>, implicit %eflags
294 // Successors according to CFG: %bb.37 %bb.2
295 //
296 // %bb.2:
297 // %p = PHI %y, %bb.0, %def, %bb.1
298 if (all_of(MRI->use_nodbg_operands(Reg), [&](MachineOperand &MO) {
299 MachineInstr *UseInst = MO.getParent();
300 unsigned OpNo = UseInst->getOperandNo(&MO);
301 MachineBasicBlock *UseBlock = UseInst->getParent();
302 return UseBlock == MBB && UseInst->isPHI() &&
303 UseInst->getOperand(OpNo + 1).getMBB() == DefMBB;
304 })) {
305 BreakPHIEdge = true;
306 return true;
307 }
308
309 for (MachineOperand &MO : MRI->use_nodbg_operands(Reg)) {
310 // Determine the block of the use.
311 MachineInstr *UseInst = MO.getParent();
312 unsigned OpNo = &MO - &UseInst->getOperand(0);
313 MachineBasicBlock *UseBlock = UseInst->getParent();
314 if (UseInst->isPHI()) {
315 // PHI nodes use the operand in the predecessor block, not the block with
316 // the PHI.
317 UseBlock = UseInst->getOperand(OpNo+1).getMBB();
318 } else if (UseBlock == DefMBB) {
319 LocalUse = true;
320 return false;
321 }
322
323 // Check that it dominates.
324 if (!DT->dominates(MBB, UseBlock))
325 return false;
326 }
327
328 return true;
329 }
330
runOnMachineFunction(MachineFunction & MF)331 bool MachineSinking::runOnMachineFunction(MachineFunction &MF) {
332 if (skipFunction(MF.getFunction()))
333 return false;
334
335 LLVM_DEBUG(dbgs() << "******** Machine Sinking ********\n");
336
337 TII = MF.getSubtarget().getInstrInfo();
338 TRI = MF.getSubtarget().getRegisterInfo();
339 MRI = &MF.getRegInfo();
340 DT = &getAnalysis<MachineDominatorTree>();
341 PDT = &getAnalysis<MachinePostDominatorTree>();
342 LI = &getAnalysis<MachineLoopInfo>();
343 MBFI = UseBlockFreqInfo ? &getAnalysis<MachineBlockFrequencyInfo>() : nullptr;
344 MBPI = &getAnalysis<MachineBranchProbabilityInfo>();
345 AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
346 RegClassInfo.runOnMachineFunction(MF);
347
348 bool EverMadeChange = false;
349
350 while (true) {
351 bool MadeChange = false;
352
353 // Process all basic blocks.
354 CEBCandidates.clear();
355 ToSplit.clear();
356 for (auto &MBB: MF)
357 MadeChange |= ProcessBlock(MBB);
358
359 // If we have anything we marked as toSplit, split it now.
360 for (auto &Pair : ToSplit) {
361 auto NewSucc = Pair.first->SplitCriticalEdge(Pair.second, *this);
362 if (NewSucc != nullptr) {
363 LLVM_DEBUG(dbgs() << " *** Splitting critical edge: "
364 << printMBBReference(*Pair.first) << " -- "
365 << printMBBReference(*NewSucc) << " -- "
366 << printMBBReference(*Pair.second) << '\n');
367 if (MBFI)
368 MBFI->onEdgeSplit(*Pair.first, *NewSucc, *MBPI);
369
370 MadeChange = true;
371 ++NumSplit;
372 } else
373 LLVM_DEBUG(dbgs() << " *** Not legal to break critical edge\n");
374 }
375 // If this iteration over the code changed anything, keep iterating.
376 if (!MadeChange) break;
377 EverMadeChange = true;
378 }
379
380 HasStoreCache.clear();
381 StoreInstrCache.clear();
382
383 // Now clear any kill flags for recorded registers.
384 for (auto I : RegsToClearKillFlags)
385 MRI->clearKillFlags(I);
386 RegsToClearKillFlags.clear();
387
388 return EverMadeChange;
389 }
390
ProcessBlock(MachineBasicBlock & MBB)391 bool MachineSinking::ProcessBlock(MachineBasicBlock &MBB) {
392 // Can't sink anything out of a block that has less than two successors.
393 if (MBB.succ_size() <= 1 || MBB.empty()) return false;
394
395 // Don't bother sinking code out of unreachable blocks. In addition to being
396 // unprofitable, it can also lead to infinite looping, because in an
397 // unreachable loop there may be nowhere to stop.
398 if (!DT->isReachableFromEntry(&MBB)) return false;
399
400 bool MadeChange = false;
401
402 // Cache all successors, sorted by frequency info and loop depth.
403 AllSuccsCache AllSuccessors;
404
405 // Walk the basic block bottom-up. Remember if we saw a store.
406 MachineBasicBlock::iterator I = MBB.end();
407 --I;
408 bool ProcessedBegin, SawStore = false;
409 do {
410 MachineInstr &MI = *I; // The instruction to sink.
411
412 // Predecrement I (if it's not begin) so that it isn't invalidated by
413 // sinking.
414 ProcessedBegin = I == MBB.begin();
415 if (!ProcessedBegin)
416 --I;
417
418 if (MI.isDebugInstr()) {
419 if (MI.isDebugValue())
420 ProcessDbgInst(MI);
421 continue;
422 }
423
424 bool Joined = PerformTrivialForwardCoalescing(MI, &MBB);
425 if (Joined) {
426 MadeChange = true;
427 continue;
428 }
429
430 if (SinkInstruction(MI, SawStore, AllSuccessors)) {
431 ++NumSunk;
432 MadeChange = true;
433 }
434
435 // If we just processed the first instruction in the block, we're done.
436 } while (!ProcessedBegin);
437
438 SeenDbgUsers.clear();
439 SeenDbgVars.clear();
440 // recalculate the bb register pressure after sinking one BB.
441 CachedRegisterPressure.clear();
442
443 return MadeChange;
444 }
445
ProcessDbgInst(MachineInstr & MI)446 void MachineSinking::ProcessDbgInst(MachineInstr &MI) {
447 // When we see DBG_VALUEs for registers, record any vreg it reads, so that
448 // we know what to sink if the vreg def sinks.
449 assert(MI.isDebugValue() && "Expected DBG_VALUE for processing");
450
451 DebugVariable Var(MI.getDebugVariable(), MI.getDebugExpression(),
452 MI.getDebugLoc()->getInlinedAt());
453 bool SeenBefore = SeenDbgVars.count(Var) != 0;
454
455 MachineOperand &MO = MI.getDebugOperand(0);
456 if (MO.isReg() && MO.getReg().isVirtual())
457 SeenDbgUsers[MO.getReg()].push_back(SeenDbgUser(&MI, SeenBefore));
458
459 // Record the variable for any DBG_VALUE, to avoid re-ordering any of them.
460 SeenDbgVars.insert(Var);
461 }
462
isWorthBreakingCriticalEdge(MachineInstr & MI,MachineBasicBlock * From,MachineBasicBlock * To)463 bool MachineSinking::isWorthBreakingCriticalEdge(MachineInstr &MI,
464 MachineBasicBlock *From,
465 MachineBasicBlock *To) {
466 // FIXME: Need much better heuristics.
467
468 // If the pass has already considered breaking this edge (during this pass
469 // through the function), then let's go ahead and break it. This means
470 // sinking multiple "cheap" instructions into the same block.
471 if (!CEBCandidates.insert(std::make_pair(From, To)).second)
472 return true;
473
474 if (!MI.isCopy() && !TII->isAsCheapAsAMove(MI))
475 return true;
476
477 if (From->isSuccessor(To) && MBPI->getEdgeProbability(From, To) <=
478 BranchProbability(SplitEdgeProbabilityThreshold, 100))
479 return true;
480
481 // MI is cheap, we probably don't want to break the critical edge for it.
482 // However, if this would allow some definitions of its source operands
483 // to be sunk then it's probably worth it.
484 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
485 const MachineOperand &MO = MI.getOperand(i);
486 if (!MO.isReg() || !MO.isUse())
487 continue;
488 Register Reg = MO.getReg();
489 if (Reg == 0)
490 continue;
491
492 // We don't move live definitions of physical registers,
493 // so sinking their uses won't enable any opportunities.
494 if (Register::isPhysicalRegister(Reg))
495 continue;
496
497 // If this instruction is the only user of a virtual register,
498 // check if breaking the edge will enable sinking
499 // both this instruction and the defining instruction.
500 if (MRI->hasOneNonDBGUse(Reg)) {
501 // If the definition resides in same MBB,
502 // claim it's likely we can sink these together.
503 // If definition resides elsewhere, we aren't
504 // blocking it from being sunk so don't break the edge.
505 MachineInstr *DefMI = MRI->getVRegDef(Reg);
506 if (DefMI->getParent() == MI.getParent())
507 return true;
508 }
509 }
510
511 return false;
512 }
513
PostponeSplitCriticalEdge(MachineInstr & MI,MachineBasicBlock * FromBB,MachineBasicBlock * ToBB,bool BreakPHIEdge)514 bool MachineSinking::PostponeSplitCriticalEdge(MachineInstr &MI,
515 MachineBasicBlock *FromBB,
516 MachineBasicBlock *ToBB,
517 bool BreakPHIEdge) {
518 if (!isWorthBreakingCriticalEdge(MI, FromBB, ToBB))
519 return false;
520
521 // Avoid breaking back edge. From == To means backedge for single BB loop.
522 if (!SplitEdges || FromBB == ToBB)
523 return false;
524
525 // Check for backedges of more "complex" loops.
526 if (LI->getLoopFor(FromBB) == LI->getLoopFor(ToBB) &&
527 LI->isLoopHeader(ToBB))
528 return false;
529
530 // It's not always legal to break critical edges and sink the computation
531 // to the edge.
532 //
533 // %bb.1:
534 // v1024
535 // Beq %bb.3
536 // <fallthrough>
537 // %bb.2:
538 // ... no uses of v1024
539 // <fallthrough>
540 // %bb.3:
541 // ...
542 // = v1024
543 //
544 // If %bb.1 -> %bb.3 edge is broken and computation of v1024 is inserted:
545 //
546 // %bb.1:
547 // ...
548 // Bne %bb.2
549 // %bb.4:
550 // v1024 =
551 // B %bb.3
552 // %bb.2:
553 // ... no uses of v1024
554 // <fallthrough>
555 // %bb.3:
556 // ...
557 // = v1024
558 //
559 // This is incorrect since v1024 is not computed along the %bb.1->%bb.2->%bb.3
560 // flow. We need to ensure the new basic block where the computation is
561 // sunk to dominates all the uses.
562 // It's only legal to break critical edge and sink the computation to the
563 // new block if all the predecessors of "To", except for "From", are
564 // not dominated by "From". Given SSA property, this means these
565 // predecessors are dominated by "To".
566 //
567 // There is no need to do this check if all the uses are PHI nodes. PHI
568 // sources are only defined on the specific predecessor edges.
569 if (!BreakPHIEdge) {
570 for (MachineBasicBlock::pred_iterator PI = ToBB->pred_begin(),
571 E = ToBB->pred_end(); PI != E; ++PI) {
572 if (*PI == FromBB)
573 continue;
574 if (!DT->dominates(ToBB, *PI))
575 return false;
576 }
577 }
578
579 ToSplit.insert(std::make_pair(FromBB, ToBB));
580
581 return true;
582 }
583
584 std::vector<unsigned> &
getBBRegisterPressure(MachineBasicBlock & MBB)585 MachineSinking::getBBRegisterPressure(MachineBasicBlock &MBB) {
586 // Currently to save compiling time, MBB's register pressure will not change
587 // in one ProcessBlock iteration because of CachedRegisterPressure. but MBB's
588 // register pressure is changed after sinking any instructions into it.
589 // FIXME: need a accurate and cheap register pressure estiminate model here.
590 auto RP = CachedRegisterPressure.find(&MBB);
591 if (RP != CachedRegisterPressure.end())
592 return RP->second;
593
594 RegionPressure Pressure;
595 RegPressureTracker RPTracker(Pressure);
596
597 // Initialize the register pressure tracker.
598 RPTracker.init(MBB.getParent(), &RegClassInfo, nullptr, &MBB, MBB.end(),
599 /*TrackLaneMasks*/ false, /*TrackUntiedDefs=*/true);
600
601 for (MachineBasicBlock::iterator MII = MBB.instr_end(),
602 MIE = MBB.instr_begin();
603 MII != MIE; --MII) {
604 MachineInstr &MI = *std::prev(MII);
605 if (MI.isDebugValue() || MI.isDebugLabel())
606 continue;
607 RegisterOperands RegOpers;
608 RegOpers.collect(MI, *TRI, *MRI, false, false);
609 RPTracker.recedeSkipDebugValues();
610 assert(&*RPTracker.getPos() == &MI && "RPTracker sync error!");
611 RPTracker.recede(RegOpers);
612 }
613
614 RPTracker.closeRegion();
615 auto It = CachedRegisterPressure.insert(
616 std::make_pair(&MBB, RPTracker.getPressure().MaxSetPressure));
617 return It.first->second;
618 }
619
620 /// isProfitableToSinkTo - Return true if it is profitable to sink MI.
isProfitableToSinkTo(Register Reg,MachineInstr & MI,MachineBasicBlock * MBB,MachineBasicBlock * SuccToSinkTo,AllSuccsCache & AllSuccessors)621 bool MachineSinking::isProfitableToSinkTo(Register Reg, MachineInstr &MI,
622 MachineBasicBlock *MBB,
623 MachineBasicBlock *SuccToSinkTo,
624 AllSuccsCache &AllSuccessors) {
625 assert (SuccToSinkTo && "Invalid SinkTo Candidate BB");
626
627 if (MBB == SuccToSinkTo)
628 return false;
629
630 // It is profitable if SuccToSinkTo does not post dominate current block.
631 if (!PDT->dominates(SuccToSinkTo, MBB))
632 return true;
633
634 // It is profitable to sink an instruction from a deeper loop to a shallower
635 // loop, even if the latter post-dominates the former (PR21115).
636 if (LI->getLoopDepth(MBB) > LI->getLoopDepth(SuccToSinkTo))
637 return true;
638
639 // Check if only use in post dominated block is PHI instruction.
640 bool NonPHIUse = false;
641 for (MachineInstr &UseInst : MRI->use_nodbg_instructions(Reg)) {
642 MachineBasicBlock *UseBlock = UseInst.getParent();
643 if (UseBlock == SuccToSinkTo && !UseInst.isPHI())
644 NonPHIUse = true;
645 }
646 if (!NonPHIUse)
647 return true;
648
649 // If SuccToSinkTo post dominates then also it may be profitable if MI
650 // can further profitably sinked into another block in next round.
651 bool BreakPHIEdge = false;
652 // FIXME - If finding successor is compile time expensive then cache results.
653 if (MachineBasicBlock *MBB2 =
654 FindSuccToSinkTo(MI, SuccToSinkTo, BreakPHIEdge, AllSuccessors))
655 return isProfitableToSinkTo(Reg, MI, SuccToSinkTo, MBB2, AllSuccessors);
656
657 MachineLoop *ML = LI->getLoopFor(MBB);
658
659 // If the instruction is not inside a loop, it is not profitable to sink MI to
660 // a post dominate block SuccToSinkTo.
661 if (!ML)
662 return false;
663
664 auto isRegisterPressureSetExceedLimit = [&](const TargetRegisterClass *RC) {
665 unsigned Weight = TRI->getRegClassWeight(RC).RegWeight;
666 const int *PS = TRI->getRegClassPressureSets(RC);
667 // Get register pressure for block SuccToSinkTo.
668 std::vector<unsigned> BBRegisterPressure =
669 getBBRegisterPressure(*SuccToSinkTo);
670 for (; *PS != -1; PS++)
671 // check if any register pressure set exceeds limit in block SuccToSinkTo
672 // after sinking.
673 if (Weight + BBRegisterPressure[*PS] >=
674 TRI->getRegPressureSetLimit(*MBB->getParent(), *PS))
675 return true;
676 return false;
677 };
678
679 // If this instruction is inside a loop and sinking this instruction can make
680 // more registers live range shorten, it is still prifitable.
681 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
682 const MachineOperand &MO = MI.getOperand(i);
683 // Ignore non-register operands.
684 if (!MO.isReg())
685 continue;
686 Register Reg = MO.getReg();
687 if (Reg == 0)
688 continue;
689
690 // Don't handle physical register.
691 if (Register::isPhysicalRegister(Reg))
692 return false;
693
694 // Users for the defs are all dominated by SuccToSinkTo.
695 if (MO.isDef()) {
696 // This def register's live range is shortened after sinking.
697 bool LocalUse = false;
698 if (!AllUsesDominatedByBlock(Reg, SuccToSinkTo, MBB, BreakPHIEdge,
699 LocalUse))
700 return false;
701 } else {
702 MachineInstr *DefMI = MRI->getVRegDef(Reg);
703 // DefMI is defined outside of loop. There should be no live range
704 // impact for this operand. Defination outside of loop means:
705 // 1: defination is outside of loop.
706 // 2: defination is in this loop, but it is a PHI in the loop header.
707 if (LI->getLoopFor(DefMI->getParent()) != ML ||
708 (DefMI->isPHI() && LI->isLoopHeader(DefMI->getParent())))
709 continue;
710 // The DefMI is defined inside the loop.
711 // If sinking this operand makes some register pressure set exceed limit,
712 // it is not profitable.
713 if (isRegisterPressureSetExceedLimit(MRI->getRegClass(Reg))) {
714 LLVM_DEBUG(dbgs() << "register pressure exceed limit, not profitable.");
715 return false;
716 }
717 }
718 }
719
720 // If MI is in loop and all its operands are alive across the whole loop or if
721 // no operand sinking make register pressure set exceed limit, it is
722 // profitable to sink MI.
723 return true;
724 }
725
726 /// Get the sorted sequence of successors for this MachineBasicBlock, possibly
727 /// computing it if it was not already cached.
728 SmallVector<MachineBasicBlock *, 4> &
GetAllSortedSuccessors(MachineInstr & MI,MachineBasicBlock * MBB,AllSuccsCache & AllSuccessors) const729 MachineSinking::GetAllSortedSuccessors(MachineInstr &MI, MachineBasicBlock *MBB,
730 AllSuccsCache &AllSuccessors) const {
731 // Do we have the sorted successors in cache ?
732 auto Succs = AllSuccessors.find(MBB);
733 if (Succs != AllSuccessors.end())
734 return Succs->second;
735
736 SmallVector<MachineBasicBlock *, 4> AllSuccs(MBB->succ_begin(),
737 MBB->succ_end());
738
739 // Handle cases where sinking can happen but where the sink point isn't a
740 // successor. For example:
741 //
742 // x = computation
743 // if () {} else {}
744 // use x
745 //
746 for (MachineDomTreeNode *DTChild : DT->getNode(MBB)->children()) {
747 // DomTree children of MBB that have MBB as immediate dominator are added.
748 if (DTChild->getIDom()->getBlock() == MI.getParent() &&
749 // Skip MBBs already added to the AllSuccs vector above.
750 !MBB->isSuccessor(DTChild->getBlock()))
751 AllSuccs.push_back(DTChild->getBlock());
752 }
753
754 // Sort Successors according to their loop depth or block frequency info.
755 llvm::stable_sort(
756 AllSuccs, [this](const MachineBasicBlock *L, const MachineBasicBlock *R) {
757 uint64_t LHSFreq = MBFI ? MBFI->getBlockFreq(L).getFrequency() : 0;
758 uint64_t RHSFreq = MBFI ? MBFI->getBlockFreq(R).getFrequency() : 0;
759 bool HasBlockFreq = LHSFreq != 0 && RHSFreq != 0;
760 return HasBlockFreq ? LHSFreq < RHSFreq
761 : LI->getLoopDepth(L) < LI->getLoopDepth(R);
762 });
763
764 auto it = AllSuccessors.insert(std::make_pair(MBB, AllSuccs));
765
766 return it.first->second;
767 }
768
769 /// FindSuccToSinkTo - Find a successor to sink this instruction to.
770 MachineBasicBlock *
FindSuccToSinkTo(MachineInstr & MI,MachineBasicBlock * MBB,bool & BreakPHIEdge,AllSuccsCache & AllSuccessors)771 MachineSinking::FindSuccToSinkTo(MachineInstr &MI, MachineBasicBlock *MBB,
772 bool &BreakPHIEdge,
773 AllSuccsCache &AllSuccessors) {
774 assert (MBB && "Invalid MachineBasicBlock!");
775
776 // Loop over all the operands of the specified instruction. If there is
777 // anything we can't handle, bail out.
778
779 // SuccToSinkTo - This is the successor to sink this instruction to, once we
780 // decide.
781 MachineBasicBlock *SuccToSinkTo = nullptr;
782 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
783 const MachineOperand &MO = MI.getOperand(i);
784 if (!MO.isReg()) continue; // Ignore non-register operands.
785
786 Register Reg = MO.getReg();
787 if (Reg == 0) continue;
788
789 if (Register::isPhysicalRegister(Reg)) {
790 if (MO.isUse()) {
791 // If the physreg has no defs anywhere, it's just an ambient register
792 // and we can freely move its uses. Alternatively, if it's allocatable,
793 // it could get allocated to something with a def during allocation.
794 if (!MRI->isConstantPhysReg(Reg))
795 return nullptr;
796 } else if (!MO.isDead()) {
797 // A def that isn't dead. We can't move it.
798 return nullptr;
799 }
800 } else {
801 // Virtual register uses are always safe to sink.
802 if (MO.isUse()) continue;
803
804 // If it's not safe to move defs of the register class, then abort.
805 if (!TII->isSafeToMoveRegClassDefs(MRI->getRegClass(Reg)))
806 return nullptr;
807
808 // Virtual register defs can only be sunk if all their uses are in blocks
809 // dominated by one of the successors.
810 if (SuccToSinkTo) {
811 // If a previous operand picked a block to sink to, then this operand
812 // must be sinkable to the same block.
813 bool LocalUse = false;
814 if (!AllUsesDominatedByBlock(Reg, SuccToSinkTo, MBB,
815 BreakPHIEdge, LocalUse))
816 return nullptr;
817
818 continue;
819 }
820
821 // Otherwise, we should look at all the successors and decide which one
822 // we should sink to. If we have reliable block frequency information
823 // (frequency != 0) available, give successors with smaller frequencies
824 // higher priority, otherwise prioritize smaller loop depths.
825 for (MachineBasicBlock *SuccBlock :
826 GetAllSortedSuccessors(MI, MBB, AllSuccessors)) {
827 bool LocalUse = false;
828 if (AllUsesDominatedByBlock(Reg, SuccBlock, MBB,
829 BreakPHIEdge, LocalUse)) {
830 SuccToSinkTo = SuccBlock;
831 break;
832 }
833 if (LocalUse)
834 // Def is used locally, it's never safe to move this def.
835 return nullptr;
836 }
837
838 // If we couldn't find a block to sink to, ignore this instruction.
839 if (!SuccToSinkTo)
840 return nullptr;
841 if (!isProfitableToSinkTo(Reg, MI, MBB, SuccToSinkTo, AllSuccessors))
842 return nullptr;
843 }
844 }
845
846 // It is not possible to sink an instruction into its own block. This can
847 // happen with loops.
848 if (MBB == SuccToSinkTo)
849 return nullptr;
850
851 // It's not safe to sink instructions to EH landing pad. Control flow into
852 // landing pad is implicitly defined.
853 if (SuccToSinkTo && SuccToSinkTo->isEHPad())
854 return nullptr;
855
856 // It ought to be okay to sink instructions into an INLINEASM_BR target, but
857 // only if we make sure that MI occurs _before_ an INLINEASM_BR instruction in
858 // the source block (which this code does not yet do). So for now, forbid
859 // doing so.
860 if (SuccToSinkTo && SuccToSinkTo->isInlineAsmBrIndirectTarget())
861 return nullptr;
862
863 return SuccToSinkTo;
864 }
865
866 /// Return true if MI is likely to be usable as a memory operation by the
867 /// implicit null check optimization.
868 ///
869 /// This is a "best effort" heuristic, and should not be relied upon for
870 /// correctness. This returning true does not guarantee that the implicit null
871 /// check optimization is legal over MI, and this returning false does not
872 /// guarantee MI cannot possibly be used to do a null check.
SinkingPreventsImplicitNullCheck(MachineInstr & MI,const TargetInstrInfo * TII,const TargetRegisterInfo * TRI)873 static bool SinkingPreventsImplicitNullCheck(MachineInstr &MI,
874 const TargetInstrInfo *TII,
875 const TargetRegisterInfo *TRI) {
876 using MachineBranchPredicate = TargetInstrInfo::MachineBranchPredicate;
877
878 auto *MBB = MI.getParent();
879 if (MBB->pred_size() != 1)
880 return false;
881
882 auto *PredMBB = *MBB->pred_begin();
883 auto *PredBB = PredMBB->getBasicBlock();
884
885 // Frontends that don't use implicit null checks have no reason to emit
886 // branches with make.implicit metadata, and this function should always
887 // return false for them.
888 if (!PredBB ||
889 !PredBB->getTerminator()->getMetadata(LLVMContext::MD_make_implicit))
890 return false;
891
892 const MachineOperand *BaseOp;
893 int64_t Offset;
894 bool OffsetIsScalable;
895 if (!TII->getMemOperandWithOffset(MI, BaseOp, Offset, OffsetIsScalable, TRI))
896 return false;
897
898 if (!BaseOp->isReg())
899 return false;
900
901 if (!(MI.mayLoad() && !MI.isPredicable()))
902 return false;
903
904 MachineBranchPredicate MBP;
905 if (TII->analyzeBranchPredicate(*PredMBB, MBP, false))
906 return false;
907
908 return MBP.LHS.isReg() && MBP.RHS.isImm() && MBP.RHS.getImm() == 0 &&
909 (MBP.Predicate == MachineBranchPredicate::PRED_NE ||
910 MBP.Predicate == MachineBranchPredicate::PRED_EQ) &&
911 MBP.LHS.getReg() == BaseOp->getReg();
912 }
913
914 /// If the sunk instruction is a copy, try to forward the copy instead of
915 /// leaving an 'undef' DBG_VALUE in the original location. Don't do this if
916 /// there's any subregister weirdness involved. Returns true if copy
917 /// propagation occurred.
attemptDebugCopyProp(MachineInstr & SinkInst,MachineInstr & DbgMI)918 static bool attemptDebugCopyProp(MachineInstr &SinkInst, MachineInstr &DbgMI) {
919 const MachineRegisterInfo &MRI = SinkInst.getMF()->getRegInfo();
920 const TargetInstrInfo &TII = *SinkInst.getMF()->getSubtarget().getInstrInfo();
921
922 // Copy DBG_VALUE operand and set the original to undef. We then check to
923 // see whether this is something that can be copy-forwarded. If it isn't,
924 // continue around the loop.
925 MachineOperand &DbgMO = DbgMI.getDebugOperand(0);
926
927 const MachineOperand *SrcMO = nullptr, *DstMO = nullptr;
928 auto CopyOperands = TII.isCopyInstr(SinkInst);
929 if (!CopyOperands)
930 return false;
931 SrcMO = CopyOperands->Source;
932 DstMO = CopyOperands->Destination;
933
934 // Check validity of forwarding this copy.
935 bool PostRA = MRI.getNumVirtRegs() == 0;
936
937 // Trying to forward between physical and virtual registers is too hard.
938 if (DbgMO.getReg().isVirtual() != SrcMO->getReg().isVirtual())
939 return false;
940
941 // Only try virtual register copy-forwarding before regalloc, and physical
942 // register copy-forwarding after regalloc.
943 bool arePhysRegs = !DbgMO.getReg().isVirtual();
944 if (arePhysRegs != PostRA)
945 return false;
946
947 // Pre-regalloc, only forward if all subregisters agree (or there are no
948 // subregs at all). More analysis might recover some forwardable copies.
949 if (!PostRA && (DbgMO.getSubReg() != SrcMO->getSubReg() ||
950 DbgMO.getSubReg() != DstMO->getSubReg()))
951 return false;
952
953 // Post-regalloc, we may be sinking a DBG_VALUE of a sub or super-register
954 // of this copy. Only forward the copy if the DBG_VALUE operand exactly
955 // matches the copy destination.
956 if (PostRA && DbgMO.getReg() != DstMO->getReg())
957 return false;
958
959 DbgMO.setReg(SrcMO->getReg());
960 DbgMO.setSubReg(SrcMO->getSubReg());
961 return true;
962 }
963
964 /// Sink an instruction and its associated debug instructions.
performSink(MachineInstr & MI,MachineBasicBlock & SuccToSinkTo,MachineBasicBlock::iterator InsertPos,SmallVectorImpl<MachineInstr * > & DbgValuesToSink)965 static void performSink(MachineInstr &MI, MachineBasicBlock &SuccToSinkTo,
966 MachineBasicBlock::iterator InsertPos,
967 SmallVectorImpl<MachineInstr *> &DbgValuesToSink) {
968
969 // If we cannot find a location to use (merge with), then we erase the debug
970 // location to prevent debug-info driven tools from potentially reporting
971 // wrong location information.
972 if (!SuccToSinkTo.empty() && InsertPos != SuccToSinkTo.end())
973 MI.setDebugLoc(DILocation::getMergedLocation(MI.getDebugLoc(),
974 InsertPos->getDebugLoc()));
975 else
976 MI.setDebugLoc(DebugLoc());
977
978 // Move the instruction.
979 MachineBasicBlock *ParentBlock = MI.getParent();
980 SuccToSinkTo.splice(InsertPos, ParentBlock, MI,
981 ++MachineBasicBlock::iterator(MI));
982
983 // Sink a copy of debug users to the insert position. Mark the original
984 // DBG_VALUE location as 'undef', indicating that any earlier variable
985 // location should be terminated as we've optimised away the value at this
986 // point.
987 for (SmallVectorImpl<MachineInstr *>::iterator DBI = DbgValuesToSink.begin(),
988 DBE = DbgValuesToSink.end();
989 DBI != DBE; ++DBI) {
990 MachineInstr *DbgMI = *DBI;
991 MachineInstr *NewDbgMI = DbgMI->getMF()->CloneMachineInstr(*DBI);
992 SuccToSinkTo.insert(InsertPos, NewDbgMI);
993
994 if (!attemptDebugCopyProp(MI, *DbgMI))
995 DbgMI->setDebugValueUndef();
996 }
997 }
998
999 /// hasStoreBetween - check if there is store betweeen straight line blocks From
1000 /// and To.
hasStoreBetween(MachineBasicBlock * From,MachineBasicBlock * To,MachineInstr & MI)1001 bool MachineSinking::hasStoreBetween(MachineBasicBlock *From,
1002 MachineBasicBlock *To, MachineInstr &MI) {
1003 // Make sure From and To are in straight line which means From dominates To
1004 // and To post dominates From.
1005 if (!DT->dominates(From, To) || !PDT->dominates(To, From))
1006 return true;
1007
1008 auto BlockPair = std::make_pair(From, To);
1009
1010 // Does these two blocks pair be queried before and have a definite cached
1011 // result?
1012 if (HasStoreCache.find(BlockPair) != HasStoreCache.end())
1013 return HasStoreCache[BlockPair];
1014
1015 if (StoreInstrCache.find(BlockPair) != StoreInstrCache.end())
1016 return std::any_of(
1017 StoreInstrCache[BlockPair].begin(), StoreInstrCache[BlockPair].end(),
1018 [&](MachineInstr *I) { return I->mayAlias(AA, MI, false); });
1019
1020 bool SawStore = false;
1021 bool HasAliasedStore = false;
1022 DenseSet<MachineBasicBlock *> HandledBlocks;
1023 // Go through all reachable blocks from From.
1024 for (MachineBasicBlock *BB : depth_first(From)) {
1025 // We insert the instruction at the start of block To, so no need to worry
1026 // about stores inside To.
1027 // Store in block From should be already considered when just enter function
1028 // SinkInstruction.
1029 if (BB == To || BB == From)
1030 continue;
1031
1032 // We already handle this BB in previous iteration.
1033 if (HandledBlocks.count(BB))
1034 continue;
1035
1036 HandledBlocks.insert(BB);
1037 // To post dominates BB, it must be a path from block From.
1038 if (PDT->dominates(To, BB)) {
1039 for (MachineInstr &I : *BB) {
1040 // Treat as alias conservatively for a call or an ordered memory
1041 // operation.
1042 if (I.isCall() || I.hasOrderedMemoryRef()) {
1043 HasStoreCache[BlockPair] = true;
1044 return true;
1045 }
1046
1047 if (I.mayStore()) {
1048 SawStore = true;
1049 // We still have chance to sink MI if all stores between are not
1050 // aliased to MI.
1051 // Cache all store instructions, so that we don't need to go through
1052 // all From reachable blocks for next load instruction.
1053 if (I.mayAlias(AA, MI, false))
1054 HasAliasedStore = true;
1055 StoreInstrCache[BlockPair].push_back(&I);
1056 }
1057 }
1058 }
1059 }
1060 // If there is no store at all, cache the result.
1061 if (!SawStore)
1062 HasStoreCache[BlockPair] = false;
1063 return HasAliasedStore;
1064 }
1065
1066 /// SinkInstruction - Determine whether it is safe to sink the specified machine
1067 /// instruction out of its current block into a successor.
SinkInstruction(MachineInstr & MI,bool & SawStore,AllSuccsCache & AllSuccessors)1068 bool MachineSinking::SinkInstruction(MachineInstr &MI, bool &SawStore,
1069 AllSuccsCache &AllSuccessors) {
1070 // Don't sink instructions that the target prefers not to sink.
1071 if (!TII->shouldSink(MI))
1072 return false;
1073
1074 // Check if it's safe to move the instruction.
1075 if (!MI.isSafeToMove(AA, SawStore))
1076 return false;
1077
1078 // Convergent operations may not be made control-dependent on additional
1079 // values.
1080 if (MI.isConvergent())
1081 return false;
1082
1083 // Don't break implicit null checks. This is a performance heuristic, and not
1084 // required for correctness.
1085 if (SinkingPreventsImplicitNullCheck(MI, TII, TRI))
1086 return false;
1087
1088 // FIXME: This should include support for sinking instructions within the
1089 // block they are currently in to shorten the live ranges. We often get
1090 // instructions sunk into the top of a large block, but it would be better to
1091 // also sink them down before their first use in the block. This xform has to
1092 // be careful not to *increase* register pressure though, e.g. sinking
1093 // "x = y + z" down if it kills y and z would increase the live ranges of y
1094 // and z and only shrink the live range of x.
1095
1096 bool BreakPHIEdge = false;
1097 MachineBasicBlock *ParentBlock = MI.getParent();
1098 MachineBasicBlock *SuccToSinkTo =
1099 FindSuccToSinkTo(MI, ParentBlock, BreakPHIEdge, AllSuccessors);
1100
1101 // If there are no outputs, it must have side-effects.
1102 if (!SuccToSinkTo)
1103 return false;
1104
1105 // If the instruction to move defines a dead physical register which is live
1106 // when leaving the basic block, don't move it because it could turn into a
1107 // "zombie" define of that preg. E.g., EFLAGS. (<rdar://problem/8030636>)
1108 for (unsigned I = 0, E = MI.getNumOperands(); I != E; ++I) {
1109 const MachineOperand &MO = MI.getOperand(I);
1110 if (!MO.isReg()) continue;
1111 Register Reg = MO.getReg();
1112 if (Reg == 0 || !Register::isPhysicalRegister(Reg))
1113 continue;
1114 if (SuccToSinkTo->isLiveIn(Reg))
1115 return false;
1116 }
1117
1118 LLVM_DEBUG(dbgs() << "Sink instr " << MI << "\tinto block " << *SuccToSinkTo);
1119
1120 // If the block has multiple predecessors, this is a critical edge.
1121 // Decide if we can sink along it or need to break the edge.
1122 if (SuccToSinkTo->pred_size() > 1) {
1123 // We cannot sink a load across a critical edge - there may be stores in
1124 // other code paths.
1125 bool TryBreak = false;
1126 bool Store =
1127 MI.mayLoad() ? hasStoreBetween(ParentBlock, SuccToSinkTo, MI) : true;
1128 if (!MI.isSafeToMove(AA, Store)) {
1129 LLVM_DEBUG(dbgs() << " *** NOTE: Won't sink load along critical edge.\n");
1130 TryBreak = true;
1131 }
1132
1133 // We don't want to sink across a critical edge if we don't dominate the
1134 // successor. We could be introducing calculations to new code paths.
1135 if (!TryBreak && !DT->dominates(ParentBlock, SuccToSinkTo)) {
1136 LLVM_DEBUG(dbgs() << " *** NOTE: Critical edge found\n");
1137 TryBreak = true;
1138 }
1139
1140 // Don't sink instructions into a loop.
1141 if (!TryBreak && LI->isLoopHeader(SuccToSinkTo)) {
1142 LLVM_DEBUG(dbgs() << " *** NOTE: Loop header found\n");
1143 TryBreak = true;
1144 }
1145
1146 // Otherwise we are OK with sinking along a critical edge.
1147 if (!TryBreak)
1148 LLVM_DEBUG(dbgs() << "Sinking along critical edge.\n");
1149 else {
1150 // Mark this edge as to be split.
1151 // If the edge can actually be split, the next iteration of the main loop
1152 // will sink MI in the newly created block.
1153 bool Status =
1154 PostponeSplitCriticalEdge(MI, ParentBlock, SuccToSinkTo, BreakPHIEdge);
1155 if (!Status)
1156 LLVM_DEBUG(dbgs() << " *** PUNTING: Not legal or profitable to "
1157 "break critical edge\n");
1158 // The instruction will not be sunk this time.
1159 return false;
1160 }
1161 }
1162
1163 if (BreakPHIEdge) {
1164 // BreakPHIEdge is true if all the uses are in the successor MBB being
1165 // sunken into and they are all PHI nodes. In this case, machine-sink must
1166 // break the critical edge first.
1167 bool Status = PostponeSplitCriticalEdge(MI, ParentBlock,
1168 SuccToSinkTo, BreakPHIEdge);
1169 if (!Status)
1170 LLVM_DEBUG(dbgs() << " *** PUNTING: Not legal or profitable to "
1171 "break critical edge\n");
1172 // The instruction will not be sunk this time.
1173 return false;
1174 }
1175
1176 // Determine where to insert into. Skip phi nodes.
1177 MachineBasicBlock::iterator InsertPos = SuccToSinkTo->begin();
1178 while (InsertPos != SuccToSinkTo->end() && InsertPos->isPHI())
1179 ++InsertPos;
1180
1181 // Collect debug users of any vreg that this inst defines.
1182 SmallVector<MachineInstr *, 4> DbgUsersToSink;
1183 for (auto &MO : MI.operands()) {
1184 if (!MO.isReg() || !MO.isDef() || !MO.getReg().isVirtual())
1185 continue;
1186 if (!SeenDbgUsers.count(MO.getReg()))
1187 continue;
1188
1189 // Sink any users that don't pass any other DBG_VALUEs for this variable.
1190 auto &Users = SeenDbgUsers[MO.getReg()];
1191 for (auto &User : Users) {
1192 MachineInstr *DbgMI = User.getPointer();
1193 if (User.getInt()) {
1194 // This DBG_VALUE would re-order assignments. If we can't copy-propagate
1195 // it, it can't be recovered. Set it undef.
1196 if (!attemptDebugCopyProp(MI, *DbgMI))
1197 DbgMI->setDebugValueUndef();
1198 } else {
1199 DbgUsersToSink.push_back(DbgMI);
1200 }
1201 }
1202 }
1203
1204 // After sinking, some debug users may not be dominated any more. If possible,
1205 // copy-propagate their operands. As it's expensive, don't do this if there's
1206 // no debuginfo in the program.
1207 if (MI.getMF()->getFunction().getSubprogram() && MI.isCopy())
1208 SalvageUnsunkDebugUsersOfCopy(MI, SuccToSinkTo);
1209
1210 performSink(MI, *SuccToSinkTo, InsertPos, DbgUsersToSink);
1211
1212 // Conservatively, clear any kill flags, since it's possible that they are no
1213 // longer correct.
1214 // Note that we have to clear the kill flags for any register this instruction
1215 // uses as we may sink over another instruction which currently kills the
1216 // used registers.
1217 for (MachineOperand &MO : MI.operands()) {
1218 if (MO.isReg() && MO.isUse())
1219 RegsToClearKillFlags.set(MO.getReg()); // Remember to clear kill flags.
1220 }
1221
1222 return true;
1223 }
1224
SalvageUnsunkDebugUsersOfCopy(MachineInstr & MI,MachineBasicBlock * TargetBlock)1225 void MachineSinking::SalvageUnsunkDebugUsersOfCopy(
1226 MachineInstr &MI, MachineBasicBlock *TargetBlock) {
1227 assert(MI.isCopy());
1228 assert(MI.getOperand(1).isReg());
1229
1230 // Enumerate all users of vreg operands that are def'd. Skip those that will
1231 // be sunk. For the rest, if they are not dominated by the block we will sink
1232 // MI into, propagate the copy source to them.
1233 SmallVector<MachineInstr *, 4> DbgDefUsers;
1234 const MachineRegisterInfo &MRI = MI.getMF()->getRegInfo();
1235 for (auto &MO : MI.operands()) {
1236 if (!MO.isReg() || !MO.isDef() || !MO.getReg().isVirtual())
1237 continue;
1238 for (auto &User : MRI.use_instructions(MO.getReg())) {
1239 if (!User.isDebugValue() || DT->dominates(TargetBlock, User.getParent()))
1240 continue;
1241
1242 // If is in same block, will either sink or be use-before-def.
1243 if (User.getParent() == MI.getParent())
1244 continue;
1245
1246 assert(User.getDebugOperand(0).isReg() &&
1247 "DBG_VALUE user of vreg, but non reg operand?");
1248 DbgDefUsers.push_back(&User);
1249 }
1250 }
1251
1252 // Point the users of this copy that are no longer dominated, at the source
1253 // of the copy.
1254 for (auto *User : DbgDefUsers) {
1255 User->getDebugOperand(0).setReg(MI.getOperand(1).getReg());
1256 User->getDebugOperand(0).setSubReg(MI.getOperand(1).getSubReg());
1257 }
1258 }
1259
1260 //===----------------------------------------------------------------------===//
1261 // This pass is not intended to be a replacement or a complete alternative
1262 // for the pre-ra machine sink pass. It is only designed to sink COPY
1263 // instructions which should be handled after RA.
1264 //
1265 // This pass sinks COPY instructions into a successor block, if the COPY is not
1266 // used in the current block and the COPY is live-in to a single successor
1267 // (i.e., doesn't require the COPY to be duplicated). This avoids executing the
1268 // copy on paths where their results aren't needed. This also exposes
1269 // additional opportunites for dead copy elimination and shrink wrapping.
1270 //
1271 // These copies were either not handled by or are inserted after the MachineSink
1272 // pass. As an example of the former case, the MachineSink pass cannot sink
1273 // COPY instructions with allocatable source registers; for AArch64 these type
1274 // of copy instructions are frequently used to move function parameters (PhyReg)
1275 // into virtual registers in the entry block.
1276 //
1277 // For the machine IR below, this pass will sink %w19 in the entry into its
1278 // successor (%bb.1) because %w19 is only live-in in %bb.1.
1279 // %bb.0:
1280 // %wzr = SUBSWri %w1, 1
1281 // %w19 = COPY %w0
1282 // Bcc 11, %bb.2
1283 // %bb.1:
1284 // Live Ins: %w19
1285 // BL @fun
1286 // %w0 = ADDWrr %w0, %w19
1287 // RET %w0
1288 // %bb.2:
1289 // %w0 = COPY %wzr
1290 // RET %w0
1291 // As we sink %w19 (CSR in AArch64) into %bb.1, the shrink-wrapping pass will be
1292 // able to see %bb.0 as a candidate.
1293 //===----------------------------------------------------------------------===//
1294 namespace {
1295
1296 class PostRAMachineSinking : public MachineFunctionPass {
1297 public:
1298 bool runOnMachineFunction(MachineFunction &MF) override;
1299
1300 static char ID;
PostRAMachineSinking()1301 PostRAMachineSinking() : MachineFunctionPass(ID) {}
getPassName() const1302 StringRef getPassName() const override { return "PostRA Machine Sink"; }
1303
getAnalysisUsage(AnalysisUsage & AU) const1304 void getAnalysisUsage(AnalysisUsage &AU) const override {
1305 AU.setPreservesCFG();
1306 MachineFunctionPass::getAnalysisUsage(AU);
1307 }
1308
getRequiredProperties() const1309 MachineFunctionProperties getRequiredProperties() const override {
1310 return MachineFunctionProperties().set(
1311 MachineFunctionProperties::Property::NoVRegs);
1312 }
1313
1314 private:
1315 /// Track which register units have been modified and used.
1316 LiveRegUnits ModifiedRegUnits, UsedRegUnits;
1317
1318 /// Track DBG_VALUEs of (unmodified) register units. Each DBG_VALUE has an
1319 /// entry in this map for each unit it touches.
1320 DenseMap<unsigned, TinyPtrVector<MachineInstr *>> SeenDbgInstrs;
1321
1322 /// Sink Copy instructions unused in the same block close to their uses in
1323 /// successors.
1324 bool tryToSinkCopy(MachineBasicBlock &BB, MachineFunction &MF,
1325 const TargetRegisterInfo *TRI, const TargetInstrInfo *TII);
1326 };
1327 } // namespace
1328
1329 char PostRAMachineSinking::ID = 0;
1330 char &llvm::PostRAMachineSinkingID = PostRAMachineSinking::ID;
1331
1332 INITIALIZE_PASS(PostRAMachineSinking, "postra-machine-sink",
1333 "PostRA Machine Sink", false, false)
1334
aliasWithRegsInLiveIn(MachineBasicBlock & MBB,unsigned Reg,const TargetRegisterInfo * TRI)1335 static bool aliasWithRegsInLiveIn(MachineBasicBlock &MBB, unsigned Reg,
1336 const TargetRegisterInfo *TRI) {
1337 LiveRegUnits LiveInRegUnits(*TRI);
1338 LiveInRegUnits.addLiveIns(MBB);
1339 return !LiveInRegUnits.available(Reg);
1340 }
1341
1342 static MachineBasicBlock *
getSingleLiveInSuccBB(MachineBasicBlock & CurBB,const SmallPtrSetImpl<MachineBasicBlock * > & SinkableBBs,unsigned Reg,const TargetRegisterInfo * TRI)1343 getSingleLiveInSuccBB(MachineBasicBlock &CurBB,
1344 const SmallPtrSetImpl<MachineBasicBlock *> &SinkableBBs,
1345 unsigned Reg, const TargetRegisterInfo *TRI) {
1346 // Try to find a single sinkable successor in which Reg is live-in.
1347 MachineBasicBlock *BB = nullptr;
1348 for (auto *SI : SinkableBBs) {
1349 if (aliasWithRegsInLiveIn(*SI, Reg, TRI)) {
1350 // If BB is set here, Reg is live-in to at least two sinkable successors,
1351 // so quit.
1352 if (BB)
1353 return nullptr;
1354 BB = SI;
1355 }
1356 }
1357 // Reg is not live-in to any sinkable successors.
1358 if (!BB)
1359 return nullptr;
1360
1361 // Check if any register aliased with Reg is live-in in other successors.
1362 for (auto *SI : CurBB.successors()) {
1363 if (!SinkableBBs.count(SI) && aliasWithRegsInLiveIn(*SI, Reg, TRI))
1364 return nullptr;
1365 }
1366 return BB;
1367 }
1368
1369 static MachineBasicBlock *
getSingleLiveInSuccBB(MachineBasicBlock & CurBB,const SmallPtrSetImpl<MachineBasicBlock * > & SinkableBBs,ArrayRef<unsigned> DefedRegsInCopy,const TargetRegisterInfo * TRI)1370 getSingleLiveInSuccBB(MachineBasicBlock &CurBB,
1371 const SmallPtrSetImpl<MachineBasicBlock *> &SinkableBBs,
1372 ArrayRef<unsigned> DefedRegsInCopy,
1373 const TargetRegisterInfo *TRI) {
1374 MachineBasicBlock *SingleBB = nullptr;
1375 for (auto DefReg : DefedRegsInCopy) {
1376 MachineBasicBlock *BB =
1377 getSingleLiveInSuccBB(CurBB, SinkableBBs, DefReg, TRI);
1378 if (!BB || (SingleBB && SingleBB != BB))
1379 return nullptr;
1380 SingleBB = BB;
1381 }
1382 return SingleBB;
1383 }
1384
clearKillFlags(MachineInstr * MI,MachineBasicBlock & CurBB,SmallVectorImpl<unsigned> & UsedOpsInCopy,LiveRegUnits & UsedRegUnits,const TargetRegisterInfo * TRI)1385 static void clearKillFlags(MachineInstr *MI, MachineBasicBlock &CurBB,
1386 SmallVectorImpl<unsigned> &UsedOpsInCopy,
1387 LiveRegUnits &UsedRegUnits,
1388 const TargetRegisterInfo *TRI) {
1389 for (auto U : UsedOpsInCopy) {
1390 MachineOperand &MO = MI->getOperand(U);
1391 Register SrcReg = MO.getReg();
1392 if (!UsedRegUnits.available(SrcReg)) {
1393 MachineBasicBlock::iterator NI = std::next(MI->getIterator());
1394 for (MachineInstr &UI : make_range(NI, CurBB.end())) {
1395 if (UI.killsRegister(SrcReg, TRI)) {
1396 UI.clearRegisterKills(SrcReg, TRI);
1397 MO.setIsKill(true);
1398 break;
1399 }
1400 }
1401 }
1402 }
1403 }
1404
updateLiveIn(MachineInstr * MI,MachineBasicBlock * SuccBB,SmallVectorImpl<unsigned> & UsedOpsInCopy,SmallVectorImpl<unsigned> & DefedRegsInCopy)1405 static void updateLiveIn(MachineInstr *MI, MachineBasicBlock *SuccBB,
1406 SmallVectorImpl<unsigned> &UsedOpsInCopy,
1407 SmallVectorImpl<unsigned> &DefedRegsInCopy) {
1408 MachineFunction &MF = *SuccBB->getParent();
1409 const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
1410 for (unsigned DefReg : DefedRegsInCopy)
1411 for (MCSubRegIterator S(DefReg, TRI, true); S.isValid(); ++S)
1412 SuccBB->removeLiveIn(*S);
1413 for (auto U : UsedOpsInCopy) {
1414 Register SrcReg = MI->getOperand(U).getReg();
1415 LaneBitmask Mask;
1416 for (MCRegUnitMaskIterator S(SrcReg, TRI); S.isValid(); ++S) {
1417 Mask |= (*S).second;
1418 }
1419 SuccBB->addLiveIn(SrcReg, Mask.any() ? Mask : LaneBitmask::getAll());
1420 }
1421 SuccBB->sortUniqueLiveIns();
1422 }
1423
hasRegisterDependency(MachineInstr * MI,SmallVectorImpl<unsigned> & UsedOpsInCopy,SmallVectorImpl<unsigned> & DefedRegsInCopy,LiveRegUnits & ModifiedRegUnits,LiveRegUnits & UsedRegUnits)1424 static bool hasRegisterDependency(MachineInstr *MI,
1425 SmallVectorImpl<unsigned> &UsedOpsInCopy,
1426 SmallVectorImpl<unsigned> &DefedRegsInCopy,
1427 LiveRegUnits &ModifiedRegUnits,
1428 LiveRegUnits &UsedRegUnits) {
1429 bool HasRegDependency = false;
1430 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1431 MachineOperand &MO = MI->getOperand(i);
1432 if (!MO.isReg())
1433 continue;
1434 Register Reg = MO.getReg();
1435 if (!Reg)
1436 continue;
1437 if (MO.isDef()) {
1438 if (!ModifiedRegUnits.available(Reg) || !UsedRegUnits.available(Reg)) {
1439 HasRegDependency = true;
1440 break;
1441 }
1442 DefedRegsInCopy.push_back(Reg);
1443
1444 // FIXME: instead of isUse(), readsReg() would be a better fix here,
1445 // For example, we can ignore modifications in reg with undef. However,
1446 // it's not perfectly clear if skipping the internal read is safe in all
1447 // other targets.
1448 } else if (MO.isUse()) {
1449 if (!ModifiedRegUnits.available(Reg)) {
1450 HasRegDependency = true;
1451 break;
1452 }
1453 UsedOpsInCopy.push_back(i);
1454 }
1455 }
1456 return HasRegDependency;
1457 }
1458
getRegUnits(MCRegister Reg,const TargetRegisterInfo * TRI)1459 static SmallSet<MCRegister, 4> getRegUnits(MCRegister Reg,
1460 const TargetRegisterInfo *TRI) {
1461 SmallSet<MCRegister, 4> RegUnits;
1462 for (auto RI = MCRegUnitIterator(Reg, TRI); RI.isValid(); ++RI)
1463 RegUnits.insert(*RI);
1464 return RegUnits;
1465 }
1466
tryToSinkCopy(MachineBasicBlock & CurBB,MachineFunction & MF,const TargetRegisterInfo * TRI,const TargetInstrInfo * TII)1467 bool PostRAMachineSinking::tryToSinkCopy(MachineBasicBlock &CurBB,
1468 MachineFunction &MF,
1469 const TargetRegisterInfo *TRI,
1470 const TargetInstrInfo *TII) {
1471 SmallPtrSet<MachineBasicBlock *, 2> SinkableBBs;
1472 // FIXME: For now, we sink only to a successor which has a single predecessor
1473 // so that we can directly sink COPY instructions to the successor without
1474 // adding any new block or branch instruction.
1475 for (MachineBasicBlock *SI : CurBB.successors())
1476 if (!SI->livein_empty() && SI->pred_size() == 1)
1477 SinkableBBs.insert(SI);
1478
1479 if (SinkableBBs.empty())
1480 return false;
1481
1482 bool Changed = false;
1483
1484 // Track which registers have been modified and used between the end of the
1485 // block and the current instruction.
1486 ModifiedRegUnits.clear();
1487 UsedRegUnits.clear();
1488 SeenDbgInstrs.clear();
1489
1490 for (auto I = CurBB.rbegin(), E = CurBB.rend(); I != E;) {
1491 MachineInstr *MI = &*I;
1492 ++I;
1493
1494 // Track the operand index for use in Copy.
1495 SmallVector<unsigned, 2> UsedOpsInCopy;
1496 // Track the register number defed in Copy.
1497 SmallVector<unsigned, 2> DefedRegsInCopy;
1498
1499 // We must sink this DBG_VALUE if its operand is sunk. To avoid searching
1500 // for DBG_VALUEs later, record them when they're encountered.
1501 if (MI->isDebugValue()) {
1502 auto &MO = MI->getDebugOperand(0);
1503 if (MO.isReg() && Register::isPhysicalRegister(MO.getReg())) {
1504 // Bail if we can already tell the sink would be rejected, rather
1505 // than needlessly accumulating lots of DBG_VALUEs.
1506 if (hasRegisterDependency(MI, UsedOpsInCopy, DefedRegsInCopy,
1507 ModifiedRegUnits, UsedRegUnits))
1508 continue;
1509
1510 // Record debug use of each reg unit.
1511 SmallSet<MCRegister, 4> Units = getRegUnits(MO.getReg(), TRI);
1512 for (MCRegister Reg : Units)
1513 SeenDbgInstrs[Reg].push_back(MI);
1514 }
1515 continue;
1516 }
1517
1518 if (MI->isDebugInstr())
1519 continue;
1520
1521 // Do not move any instruction across function call.
1522 if (MI->isCall())
1523 return false;
1524
1525 if (!MI->isCopy() || !MI->getOperand(0).isRenamable()) {
1526 LiveRegUnits::accumulateUsedDefed(*MI, ModifiedRegUnits, UsedRegUnits,
1527 TRI);
1528 continue;
1529 }
1530
1531 // Don't sink the COPY if it would violate a register dependency.
1532 if (hasRegisterDependency(MI, UsedOpsInCopy, DefedRegsInCopy,
1533 ModifiedRegUnits, UsedRegUnits)) {
1534 LiveRegUnits::accumulateUsedDefed(*MI, ModifiedRegUnits, UsedRegUnits,
1535 TRI);
1536 continue;
1537 }
1538 assert((!UsedOpsInCopy.empty() && !DefedRegsInCopy.empty()) &&
1539 "Unexpect SrcReg or DefReg");
1540 MachineBasicBlock *SuccBB =
1541 getSingleLiveInSuccBB(CurBB, SinkableBBs, DefedRegsInCopy, TRI);
1542 // Don't sink if we cannot find a single sinkable successor in which Reg
1543 // is live-in.
1544 if (!SuccBB) {
1545 LiveRegUnits::accumulateUsedDefed(*MI, ModifiedRegUnits, UsedRegUnits,
1546 TRI);
1547 continue;
1548 }
1549 assert((SuccBB->pred_size() == 1 && *SuccBB->pred_begin() == &CurBB) &&
1550 "Unexpected predecessor");
1551
1552 // Collect DBG_VALUEs that must sink with this copy. We've previously
1553 // recorded which reg units that DBG_VALUEs read, if this instruction
1554 // writes any of those units then the corresponding DBG_VALUEs must sink.
1555 SetVector<MachineInstr *> DbgValsToSinkSet;
1556 SmallVector<MachineInstr *, 4> DbgValsToSink;
1557 for (auto &MO : MI->operands()) {
1558 if (!MO.isReg() || !MO.isDef())
1559 continue;
1560
1561 SmallSet<MCRegister, 4> Units = getRegUnits(MO.getReg(), TRI);
1562 for (MCRegister Reg : Units)
1563 for (auto *MI : SeenDbgInstrs.lookup(Reg))
1564 DbgValsToSinkSet.insert(MI);
1565 }
1566 DbgValsToSink.insert(DbgValsToSink.begin(), DbgValsToSinkSet.begin(),
1567 DbgValsToSinkSet.end());
1568
1569 // Clear the kill flag if SrcReg is killed between MI and the end of the
1570 // block.
1571 clearKillFlags(MI, CurBB, UsedOpsInCopy, UsedRegUnits, TRI);
1572 MachineBasicBlock::iterator InsertPos = SuccBB->getFirstNonPHI();
1573 performSink(*MI, *SuccBB, InsertPos, DbgValsToSink);
1574 updateLiveIn(MI, SuccBB, UsedOpsInCopy, DefedRegsInCopy);
1575
1576 Changed = true;
1577 ++NumPostRACopySink;
1578 }
1579 return Changed;
1580 }
1581
runOnMachineFunction(MachineFunction & MF)1582 bool PostRAMachineSinking::runOnMachineFunction(MachineFunction &MF) {
1583 if (skipFunction(MF.getFunction()))
1584 return false;
1585
1586 bool Changed = false;
1587 const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
1588 const TargetInstrInfo *TII = MF.getSubtarget().getInstrInfo();
1589
1590 ModifiedRegUnits.init(*TRI);
1591 UsedRegUnits.init(*TRI);
1592 for (auto &BB : MF)
1593 Changed |= tryToSinkCopy(BB, MF, TRI, TII);
1594
1595 return Changed;
1596 }
1597