1706b4fc4SDimitry Andric //===- CodeMoverUtils.cpp - CodeMover Utilities ----------------------------==//
2706b4fc4SDimitry Andric //
3706b4fc4SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4706b4fc4SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
5706b4fc4SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6706b4fc4SDimitry Andric //
7706b4fc4SDimitry Andric //===----------------------------------------------------------------------===//
8706b4fc4SDimitry Andric //
9706b4fc4SDimitry Andric // This family of functions perform movements on basic blocks, and instructions
10706b4fc4SDimitry Andric // contained within a function.
11706b4fc4SDimitry Andric //
12706b4fc4SDimitry Andric //===----------------------------------------------------------------------===//
13706b4fc4SDimitry Andric
14706b4fc4SDimitry Andric #include "llvm/Transforms/Utils/CodeMoverUtils.h"
15706b4fc4SDimitry Andric #include "llvm/ADT/Statistic.h"
16706b4fc4SDimitry Andric #include "llvm/Analysis/DependenceAnalysis.h"
17706b4fc4SDimitry Andric #include "llvm/Analysis/PostDominators.h"
18706b4fc4SDimitry Andric #include "llvm/Analysis/ValueTracking.h"
19706b4fc4SDimitry Andric #include "llvm/IR/Dominators.h"
20706b4fc4SDimitry Andric
21706b4fc4SDimitry Andric using namespace llvm;
22706b4fc4SDimitry Andric
23706b4fc4SDimitry Andric #define DEBUG_TYPE "codemover-utils"
24706b4fc4SDimitry Andric
25706b4fc4SDimitry Andric STATISTIC(HasDependences,
26706b4fc4SDimitry Andric "Cannot move across instructions that has memory dependences");
27706b4fc4SDimitry Andric STATISTIC(MayThrowException, "Cannot move across instructions that may throw");
28706b4fc4SDimitry Andric STATISTIC(NotControlFlowEquivalent,
29706b4fc4SDimitry Andric "Instructions are not control flow equivalent");
30706b4fc4SDimitry Andric STATISTIC(NotMovedPHINode, "Movement of PHINodes are not supported");
31706b4fc4SDimitry Andric STATISTIC(NotMovedTerminator, "Movement of Terminator are not supported");
32706b4fc4SDimitry Andric
33cfca06d7SDimitry Andric namespace {
34cfca06d7SDimitry Andric /// Represent a control condition. A control condition is a condition of a
35cfca06d7SDimitry Andric /// terminator to decide which successors to execute. The pointer field
36cfca06d7SDimitry Andric /// represents the address of the condition of the terminator. The integer field
37cfca06d7SDimitry Andric /// is a bool, it is true when the basic block is executed when V is true. For
38cfca06d7SDimitry Andric /// example, `br %cond, bb0, bb1` %cond is a control condition of bb0 with the
39cfca06d7SDimitry Andric /// integer field equals to true, while %cond is a control condition of bb1 with
40cfca06d7SDimitry Andric /// the integer field equals to false.
41cfca06d7SDimitry Andric using ControlCondition = PointerIntPair<Value *, 1, bool>;
42cfca06d7SDimitry Andric #ifndef NDEBUG
operator <<(raw_ostream & OS,const ControlCondition & C)43cfca06d7SDimitry Andric raw_ostream &operator<<(raw_ostream &OS, const ControlCondition &C) {
44cfca06d7SDimitry Andric OS << "[" << *C.getPointer() << ", " << (C.getInt() ? "true" : "false")
45cfca06d7SDimitry Andric << "]";
46cfca06d7SDimitry Andric return OS;
47cfca06d7SDimitry Andric }
48cfca06d7SDimitry Andric #endif
49cfca06d7SDimitry Andric
50cfca06d7SDimitry Andric /// Represent a set of control conditions required to execute ToBB from FromBB.
51cfca06d7SDimitry Andric class ControlConditions {
52cfca06d7SDimitry Andric using ConditionVectorTy = SmallVector<ControlCondition, 6>;
53cfca06d7SDimitry Andric
54cfca06d7SDimitry Andric /// A SmallVector of control conditions.
55cfca06d7SDimitry Andric ConditionVectorTy Conditions;
56cfca06d7SDimitry Andric
57cfca06d7SDimitry Andric public:
58cfca06d7SDimitry Andric /// Return a ControlConditions which stores all conditions required to execute
59cfca06d7SDimitry Andric /// \p BB from \p Dominator. If \p MaxLookup is non-zero, it limits the
60e3b55780SDimitry Andric /// number of conditions to collect. Return std::nullopt if not all conditions
61e3b55780SDimitry Andric /// are collected successfully, or we hit the limit.
62e3b55780SDimitry Andric static const std::optional<ControlConditions>
63cfca06d7SDimitry Andric collectControlConditions(const BasicBlock &BB, const BasicBlock &Dominator,
64cfca06d7SDimitry Andric const DominatorTree &DT,
65cfca06d7SDimitry Andric const PostDominatorTree &PDT,
66cfca06d7SDimitry Andric unsigned MaxLookup = 6);
67cfca06d7SDimitry Andric
68cfca06d7SDimitry Andric /// Return true if there exists no control conditions required to execute ToBB
69cfca06d7SDimitry Andric /// from FromBB.
isUnconditional() const70cfca06d7SDimitry Andric bool isUnconditional() const { return Conditions.empty(); }
71cfca06d7SDimitry Andric
72cfca06d7SDimitry Andric /// Return a constant reference of Conditions.
getControlConditions() const73cfca06d7SDimitry Andric const ConditionVectorTy &getControlConditions() const { return Conditions; }
74cfca06d7SDimitry Andric
75cfca06d7SDimitry Andric /// Add \p V as one of the ControlCondition in Condition with IsTrueCondition
76cfca06d7SDimitry Andric /// equals to \p True. Return true if inserted successfully.
77cfca06d7SDimitry Andric bool addControlCondition(ControlCondition C);
78cfca06d7SDimitry Andric
79cfca06d7SDimitry Andric /// Return true if for all control conditions in Conditions, there exists an
80cfca06d7SDimitry Andric /// equivalent control condition in \p Other.Conditions.
81cfca06d7SDimitry Andric bool isEquivalent(const ControlConditions &Other) const;
82cfca06d7SDimitry Andric
83cfca06d7SDimitry Andric /// Return true if \p C1 and \p C2 are equivalent.
84cfca06d7SDimitry Andric static bool isEquivalent(const ControlCondition &C1,
85cfca06d7SDimitry Andric const ControlCondition &C2);
86cfca06d7SDimitry Andric
87cfca06d7SDimitry Andric private:
88cfca06d7SDimitry Andric ControlConditions() = default;
89cfca06d7SDimitry Andric
90cfca06d7SDimitry Andric static bool isEquivalent(const Value &V1, const Value &V2);
91cfca06d7SDimitry Andric static bool isInverse(const Value &V1, const Value &V2);
92cfca06d7SDimitry Andric };
93cfca06d7SDimitry Andric } // namespace
94cfca06d7SDimitry Andric
domTreeLevelBefore(DominatorTree * DT,const Instruction * InstA,const Instruction * InstB)95cfca06d7SDimitry Andric static bool domTreeLevelBefore(DominatorTree *DT, const Instruction *InstA,
96cfca06d7SDimitry Andric const Instruction *InstB) {
97cfca06d7SDimitry Andric // Use ordered basic block in case the 2 instructions are in the same
98cfca06d7SDimitry Andric // block.
99cfca06d7SDimitry Andric if (InstA->getParent() == InstB->getParent())
100cfca06d7SDimitry Andric return InstA->comesBefore(InstB);
101cfca06d7SDimitry Andric
102cfca06d7SDimitry Andric DomTreeNode *DA = DT->getNode(InstA->getParent());
103cfca06d7SDimitry Andric DomTreeNode *DB = DT->getNode(InstB->getParent());
104cfca06d7SDimitry Andric return DA->getLevel() < DB->getLevel();
105cfca06d7SDimitry Andric }
106cfca06d7SDimitry Andric
107e3b55780SDimitry Andric const std::optional<ControlConditions>
collectControlConditions(const BasicBlock & BB,const BasicBlock & Dominator,const DominatorTree & DT,const PostDominatorTree & PDT,unsigned MaxLookup)108e3b55780SDimitry Andric ControlConditions::collectControlConditions(const BasicBlock &BB,
109e3b55780SDimitry Andric const BasicBlock &Dominator,
110e3b55780SDimitry Andric const DominatorTree &DT,
111e3b55780SDimitry Andric const PostDominatorTree &PDT,
112e3b55780SDimitry Andric unsigned MaxLookup) {
113cfca06d7SDimitry Andric assert(DT.dominates(&Dominator, &BB) && "Expecting Dominator to dominate BB");
114cfca06d7SDimitry Andric
115cfca06d7SDimitry Andric ControlConditions Conditions;
116cfca06d7SDimitry Andric unsigned NumConditions = 0;
117cfca06d7SDimitry Andric
118cfca06d7SDimitry Andric // BB is executed unconditional from itself.
119cfca06d7SDimitry Andric if (&Dominator == &BB)
120cfca06d7SDimitry Andric return Conditions;
121cfca06d7SDimitry Andric
122cfca06d7SDimitry Andric const BasicBlock *CurBlock = &BB;
123cfca06d7SDimitry Andric // Walk up the dominator tree from the associated DT node for BB to the
124cfca06d7SDimitry Andric // associated DT node for Dominator.
125cfca06d7SDimitry Andric do {
126cfca06d7SDimitry Andric assert(DT.getNode(CurBlock) && "Expecting a valid DT node for CurBlock");
127cfca06d7SDimitry Andric BasicBlock *IDom = DT.getNode(CurBlock)->getIDom()->getBlock();
128cfca06d7SDimitry Andric assert(DT.dominates(&Dominator, IDom) &&
129cfca06d7SDimitry Andric "Expecting Dominator to dominate IDom");
130cfca06d7SDimitry Andric
131cfca06d7SDimitry Andric // Limitation: can only handle branch instruction currently.
132cfca06d7SDimitry Andric const BranchInst *BI = dyn_cast<BranchInst>(IDom->getTerminator());
133cfca06d7SDimitry Andric if (!BI)
134e3b55780SDimitry Andric return std::nullopt;
135cfca06d7SDimitry Andric
136cfca06d7SDimitry Andric bool Inserted = false;
137cfca06d7SDimitry Andric if (PDT.dominates(CurBlock, IDom)) {
138cfca06d7SDimitry Andric LLVM_DEBUG(dbgs() << CurBlock->getName()
139cfca06d7SDimitry Andric << " is executed unconditionally from "
140cfca06d7SDimitry Andric << IDom->getName() << "\n");
141cfca06d7SDimitry Andric } else if (PDT.dominates(CurBlock, BI->getSuccessor(0))) {
142cfca06d7SDimitry Andric LLVM_DEBUG(dbgs() << CurBlock->getName() << " is executed when \""
143cfca06d7SDimitry Andric << *BI->getCondition() << "\" is true from "
144cfca06d7SDimitry Andric << IDom->getName() << "\n");
145cfca06d7SDimitry Andric Inserted = Conditions.addControlCondition(
146cfca06d7SDimitry Andric ControlCondition(BI->getCondition(), true));
147cfca06d7SDimitry Andric } else if (PDT.dominates(CurBlock, BI->getSuccessor(1))) {
148cfca06d7SDimitry Andric LLVM_DEBUG(dbgs() << CurBlock->getName() << " is executed when \""
149cfca06d7SDimitry Andric << *BI->getCondition() << "\" is false from "
150cfca06d7SDimitry Andric << IDom->getName() << "\n");
151cfca06d7SDimitry Andric Inserted = Conditions.addControlCondition(
152cfca06d7SDimitry Andric ControlCondition(BI->getCondition(), false));
153cfca06d7SDimitry Andric } else
154e3b55780SDimitry Andric return std::nullopt;
155cfca06d7SDimitry Andric
156cfca06d7SDimitry Andric if (Inserted)
157cfca06d7SDimitry Andric ++NumConditions;
158cfca06d7SDimitry Andric
159cfca06d7SDimitry Andric if (MaxLookup != 0 && NumConditions > MaxLookup)
160e3b55780SDimitry Andric return std::nullopt;
161cfca06d7SDimitry Andric
162cfca06d7SDimitry Andric CurBlock = IDom;
163cfca06d7SDimitry Andric } while (CurBlock != &Dominator);
164cfca06d7SDimitry Andric
165cfca06d7SDimitry Andric return Conditions;
166cfca06d7SDimitry Andric }
167cfca06d7SDimitry Andric
addControlCondition(ControlCondition C)168cfca06d7SDimitry Andric bool ControlConditions::addControlCondition(ControlCondition C) {
169cfca06d7SDimitry Andric bool Inserted = false;
170cfca06d7SDimitry Andric if (none_of(Conditions, [&](ControlCondition &Exists) {
171cfca06d7SDimitry Andric return ControlConditions::isEquivalent(C, Exists);
172cfca06d7SDimitry Andric })) {
173cfca06d7SDimitry Andric Conditions.push_back(C);
174cfca06d7SDimitry Andric Inserted = true;
175cfca06d7SDimitry Andric }
176cfca06d7SDimitry Andric
177cfca06d7SDimitry Andric LLVM_DEBUG(dbgs() << (Inserted ? "Inserted " : "Not inserted ") << C << "\n");
178cfca06d7SDimitry Andric return Inserted;
179cfca06d7SDimitry Andric }
180cfca06d7SDimitry Andric
isEquivalent(const ControlConditions & Other) const181cfca06d7SDimitry Andric bool ControlConditions::isEquivalent(const ControlConditions &Other) const {
182cfca06d7SDimitry Andric if (Conditions.empty() && Other.Conditions.empty())
183cfca06d7SDimitry Andric return true;
184cfca06d7SDimitry Andric
185cfca06d7SDimitry Andric if (Conditions.size() != Other.Conditions.size())
186cfca06d7SDimitry Andric return false;
187cfca06d7SDimitry Andric
188cfca06d7SDimitry Andric return all_of(Conditions, [&](const ControlCondition &C) {
189cfca06d7SDimitry Andric return any_of(Other.Conditions, [&](const ControlCondition &OtherC) {
190cfca06d7SDimitry Andric return ControlConditions::isEquivalent(C, OtherC);
191cfca06d7SDimitry Andric });
192cfca06d7SDimitry Andric });
193cfca06d7SDimitry Andric }
194cfca06d7SDimitry Andric
isEquivalent(const ControlCondition & C1,const ControlCondition & C2)195cfca06d7SDimitry Andric bool ControlConditions::isEquivalent(const ControlCondition &C1,
196cfca06d7SDimitry Andric const ControlCondition &C2) {
197cfca06d7SDimitry Andric if (C1.getInt() == C2.getInt()) {
198cfca06d7SDimitry Andric if (isEquivalent(*C1.getPointer(), *C2.getPointer()))
199cfca06d7SDimitry Andric return true;
200cfca06d7SDimitry Andric } else if (isInverse(*C1.getPointer(), *C2.getPointer()))
201cfca06d7SDimitry Andric return true;
202cfca06d7SDimitry Andric
203cfca06d7SDimitry Andric return false;
204cfca06d7SDimitry Andric }
205cfca06d7SDimitry Andric
206cfca06d7SDimitry Andric // FIXME: Use SCEV and reuse GVN/CSE logic to check for equivalence between
207cfca06d7SDimitry Andric // Values.
208cfca06d7SDimitry Andric // Currently, isEquivalent rely on other passes to ensure equivalent conditions
209cfca06d7SDimitry Andric // have the same value, e.g. GVN.
isEquivalent(const Value & V1,const Value & V2)210cfca06d7SDimitry Andric bool ControlConditions::isEquivalent(const Value &V1, const Value &V2) {
211cfca06d7SDimitry Andric return &V1 == &V2;
212cfca06d7SDimitry Andric }
213cfca06d7SDimitry Andric
isInverse(const Value & V1,const Value & V2)214cfca06d7SDimitry Andric bool ControlConditions::isInverse(const Value &V1, const Value &V2) {
215cfca06d7SDimitry Andric if (const CmpInst *Cmp1 = dyn_cast<CmpInst>(&V1))
216cfca06d7SDimitry Andric if (const CmpInst *Cmp2 = dyn_cast<CmpInst>(&V2)) {
217cfca06d7SDimitry Andric if (Cmp1->getPredicate() == Cmp2->getInversePredicate() &&
218cfca06d7SDimitry Andric Cmp1->getOperand(0) == Cmp2->getOperand(0) &&
219cfca06d7SDimitry Andric Cmp1->getOperand(1) == Cmp2->getOperand(1))
220cfca06d7SDimitry Andric return true;
221cfca06d7SDimitry Andric
222cfca06d7SDimitry Andric if (Cmp1->getPredicate() ==
223cfca06d7SDimitry Andric CmpInst::getSwappedPredicate(Cmp2->getInversePredicate()) &&
224cfca06d7SDimitry Andric Cmp1->getOperand(0) == Cmp2->getOperand(1) &&
225cfca06d7SDimitry Andric Cmp1->getOperand(1) == Cmp2->getOperand(0))
226cfca06d7SDimitry Andric return true;
227cfca06d7SDimitry Andric }
228cfca06d7SDimitry Andric return false;
229cfca06d7SDimitry Andric }
230cfca06d7SDimitry Andric
isControlFlowEquivalent(const Instruction & I0,const Instruction & I1,const DominatorTree & DT,const PostDominatorTree & PDT)231706b4fc4SDimitry Andric bool llvm::isControlFlowEquivalent(const Instruction &I0, const Instruction &I1,
232706b4fc4SDimitry Andric const DominatorTree &DT,
233706b4fc4SDimitry Andric const PostDominatorTree &PDT) {
234706b4fc4SDimitry Andric return isControlFlowEquivalent(*I0.getParent(), *I1.getParent(), DT, PDT);
235706b4fc4SDimitry Andric }
236706b4fc4SDimitry Andric
isControlFlowEquivalent(const BasicBlock & BB0,const BasicBlock & BB1,const DominatorTree & DT,const PostDominatorTree & PDT)237706b4fc4SDimitry Andric bool llvm::isControlFlowEquivalent(const BasicBlock &BB0, const BasicBlock &BB1,
238706b4fc4SDimitry Andric const DominatorTree &DT,
239706b4fc4SDimitry Andric const PostDominatorTree &PDT) {
240706b4fc4SDimitry Andric if (&BB0 == &BB1)
241706b4fc4SDimitry Andric return true;
242706b4fc4SDimitry Andric
243cfca06d7SDimitry Andric if ((DT.dominates(&BB0, &BB1) && PDT.dominates(&BB1, &BB0)) ||
244cfca06d7SDimitry Andric (PDT.dominates(&BB0, &BB1) && DT.dominates(&BB1, &BB0)))
245cfca06d7SDimitry Andric return true;
246cfca06d7SDimitry Andric
247cfca06d7SDimitry Andric // If the set of conditions required to execute BB0 and BB1 from their common
248cfca06d7SDimitry Andric // dominator are the same, then BB0 and BB1 are control flow equivalent.
249cfca06d7SDimitry Andric const BasicBlock *CommonDominator = DT.findNearestCommonDominator(&BB0, &BB1);
250cfca06d7SDimitry Andric LLVM_DEBUG(dbgs() << "The nearest common dominator of " << BB0.getName()
251cfca06d7SDimitry Andric << " and " << BB1.getName() << " is "
252cfca06d7SDimitry Andric << CommonDominator->getName() << "\n");
253cfca06d7SDimitry Andric
254e3b55780SDimitry Andric const std::optional<ControlConditions> BB0Conditions =
255cfca06d7SDimitry Andric ControlConditions::collectControlConditions(BB0, *CommonDominator, DT,
256cfca06d7SDimitry Andric PDT);
257e3b55780SDimitry Andric if (BB0Conditions == std::nullopt)
258cfca06d7SDimitry Andric return false;
259cfca06d7SDimitry Andric
260e3b55780SDimitry Andric const std::optional<ControlConditions> BB1Conditions =
261cfca06d7SDimitry Andric ControlConditions::collectControlConditions(BB1, *CommonDominator, DT,
262cfca06d7SDimitry Andric PDT);
263e3b55780SDimitry Andric if (BB1Conditions == std::nullopt)
264cfca06d7SDimitry Andric return false;
265cfca06d7SDimitry Andric
266cfca06d7SDimitry Andric return BB0Conditions->isEquivalent(*BB1Conditions);
267706b4fc4SDimitry Andric }
268706b4fc4SDimitry Andric
reportInvalidCandidate(const Instruction & I,llvm::Statistic & Stat)269706b4fc4SDimitry Andric static bool reportInvalidCandidate(const Instruction &I,
270706b4fc4SDimitry Andric llvm::Statistic &Stat) {
271706b4fc4SDimitry Andric ++Stat;
272706b4fc4SDimitry Andric LLVM_DEBUG(dbgs() << "Unable to move instruction: " << I << ". "
273706b4fc4SDimitry Andric << Stat.getDesc());
274706b4fc4SDimitry Andric return false;
275706b4fc4SDimitry Andric }
276706b4fc4SDimitry Andric
277706b4fc4SDimitry Andric /// Collect all instructions in between \p StartInst and \p EndInst, and store
278706b4fc4SDimitry Andric /// them in \p InBetweenInsts.
279706b4fc4SDimitry Andric static void
collectInstructionsInBetween(Instruction & StartInst,const Instruction & EndInst,SmallPtrSetImpl<Instruction * > & InBetweenInsts)280706b4fc4SDimitry Andric collectInstructionsInBetween(Instruction &StartInst, const Instruction &EndInst,
281706b4fc4SDimitry Andric SmallPtrSetImpl<Instruction *> &InBetweenInsts) {
282706b4fc4SDimitry Andric assert(InBetweenInsts.empty() && "Expecting InBetweenInsts to be empty");
283706b4fc4SDimitry Andric
284706b4fc4SDimitry Andric /// Get the next instructions of \p I, and push them to \p WorkList.
285706b4fc4SDimitry Andric auto getNextInsts = [](Instruction &I,
286706b4fc4SDimitry Andric SmallPtrSetImpl<Instruction *> &WorkList) {
287706b4fc4SDimitry Andric if (Instruction *NextInst = I.getNextNode())
288706b4fc4SDimitry Andric WorkList.insert(NextInst);
289706b4fc4SDimitry Andric else {
290706b4fc4SDimitry Andric assert(I.isTerminator() && "Expecting a terminator instruction");
291706b4fc4SDimitry Andric for (BasicBlock *Succ : successors(&I))
292706b4fc4SDimitry Andric WorkList.insert(&Succ->front());
293706b4fc4SDimitry Andric }
294706b4fc4SDimitry Andric };
295706b4fc4SDimitry Andric
296706b4fc4SDimitry Andric SmallPtrSet<Instruction *, 10> WorkList;
297706b4fc4SDimitry Andric getNextInsts(StartInst, WorkList);
298706b4fc4SDimitry Andric while (!WorkList.empty()) {
299706b4fc4SDimitry Andric Instruction *CurInst = *WorkList.begin();
300706b4fc4SDimitry Andric WorkList.erase(CurInst);
301706b4fc4SDimitry Andric
302706b4fc4SDimitry Andric if (CurInst == &EndInst)
303706b4fc4SDimitry Andric continue;
304706b4fc4SDimitry Andric
305706b4fc4SDimitry Andric if (!InBetweenInsts.insert(CurInst).second)
306706b4fc4SDimitry Andric continue;
307706b4fc4SDimitry Andric
308706b4fc4SDimitry Andric getNextInsts(*CurInst, WorkList);
309706b4fc4SDimitry Andric }
310706b4fc4SDimitry Andric }
311706b4fc4SDimitry Andric
isSafeToMoveBefore(Instruction & I,Instruction & InsertPoint,DominatorTree & DT,const PostDominatorTree * PDT,DependenceInfo * DI,bool CheckForEntireBlock)312706b4fc4SDimitry Andric bool llvm::isSafeToMoveBefore(Instruction &I, Instruction &InsertPoint,
313cfca06d7SDimitry Andric DominatorTree &DT, const PostDominatorTree *PDT,
314c0981da4SDimitry Andric DependenceInfo *DI, bool CheckForEntireBlock) {
315cfca06d7SDimitry Andric // Skip tests when we don't have PDT or DI
316cfca06d7SDimitry Andric if (!PDT || !DI)
317cfca06d7SDimitry Andric return false;
318cfca06d7SDimitry Andric
319706b4fc4SDimitry Andric // Cannot move itself before itself.
320706b4fc4SDimitry Andric if (&I == &InsertPoint)
321706b4fc4SDimitry Andric return false;
322706b4fc4SDimitry Andric
323706b4fc4SDimitry Andric // Not moved.
324706b4fc4SDimitry Andric if (I.getNextNode() == &InsertPoint)
325706b4fc4SDimitry Andric return true;
326706b4fc4SDimitry Andric
327706b4fc4SDimitry Andric if (isa<PHINode>(I) || isa<PHINode>(InsertPoint))
328706b4fc4SDimitry Andric return reportInvalidCandidate(I, NotMovedPHINode);
329706b4fc4SDimitry Andric
330706b4fc4SDimitry Andric if (I.isTerminator())
331706b4fc4SDimitry Andric return reportInvalidCandidate(I, NotMovedTerminator);
332706b4fc4SDimitry Andric
333706b4fc4SDimitry Andric // TODO remove this limitation.
334cfca06d7SDimitry Andric if (!isControlFlowEquivalent(I, InsertPoint, DT, *PDT))
335706b4fc4SDimitry Andric return reportInvalidCandidate(I, NotControlFlowEquivalent);
336706b4fc4SDimitry Andric
337c0981da4SDimitry Andric if (isReachedBefore(&I, &InsertPoint, &DT, PDT))
338706b4fc4SDimitry Andric for (const Use &U : I.uses())
339ac9a064cSDimitry Andric if (auto *UserInst = dyn_cast<Instruction>(U.getUser())) {
340ac9a064cSDimitry Andric // If InsertPoint is in a BB that comes after I, then we cannot move if
341ac9a064cSDimitry Andric // I is used in the terminator of the current BB.
342ac9a064cSDimitry Andric if (I.getParent() == InsertPoint.getParent() &&
343ac9a064cSDimitry Andric UserInst == I.getParent()->getTerminator())
344706b4fc4SDimitry Andric return false;
345ac9a064cSDimitry Andric if (UserInst != &InsertPoint && !DT.dominates(&InsertPoint, U)) {
346ac9a064cSDimitry Andric // If UserInst is an instruction that appears later in the same BB as
347ac9a064cSDimitry Andric // I, then it is okay to move since I will still be available when
348ac9a064cSDimitry Andric // UserInst is executed.
349ac9a064cSDimitry Andric if (CheckForEntireBlock && I.getParent() == UserInst->getParent() &&
350ac9a064cSDimitry Andric DT.dominates(&I, UserInst))
351ac9a064cSDimitry Andric continue;
352ac9a064cSDimitry Andric return false;
353ac9a064cSDimitry Andric }
354ac9a064cSDimitry Andric }
355c0981da4SDimitry Andric if (isReachedBefore(&InsertPoint, &I, &DT, PDT))
356706b4fc4SDimitry Andric for (const Value *Op : I.operands())
357c0981da4SDimitry Andric if (auto *OpInst = dyn_cast<Instruction>(Op)) {
358c0981da4SDimitry Andric if (&InsertPoint == OpInst)
359706b4fc4SDimitry Andric return false;
360c0981da4SDimitry Andric // If OpInst is an instruction that appears earlier in the same BB as
361c0981da4SDimitry Andric // I, then it is okay to move since OpInst will still be available.
362c0981da4SDimitry Andric if (CheckForEntireBlock && I.getParent() == OpInst->getParent() &&
363c0981da4SDimitry Andric DT.dominates(OpInst, &I))
364c0981da4SDimitry Andric continue;
365c0981da4SDimitry Andric if (!DT.dominates(OpInst, &InsertPoint))
366c0981da4SDimitry Andric return false;
367c0981da4SDimitry Andric }
368706b4fc4SDimitry Andric
369cfca06d7SDimitry Andric DT.updateDFSNumbers();
370cfca06d7SDimitry Andric const bool MoveForward = domTreeLevelBefore(&DT, &I, &InsertPoint);
371706b4fc4SDimitry Andric Instruction &StartInst = (MoveForward ? I : InsertPoint);
372706b4fc4SDimitry Andric Instruction &EndInst = (MoveForward ? InsertPoint : I);
373706b4fc4SDimitry Andric SmallPtrSet<Instruction *, 10> InstsToCheck;
374706b4fc4SDimitry Andric collectInstructionsInBetween(StartInst, EndInst, InstsToCheck);
375706b4fc4SDimitry Andric if (!MoveForward)
376706b4fc4SDimitry Andric InstsToCheck.insert(&InsertPoint);
377706b4fc4SDimitry Andric
378706b4fc4SDimitry Andric // Check if there exists instructions which may throw, may synchonize, or may
379706b4fc4SDimitry Andric // never return, from I to InsertPoint.
380706b4fc4SDimitry Andric if (!isSafeToSpeculativelyExecute(&I))
381b60736ecSDimitry Andric if (llvm::any_of(InstsToCheck, [](Instruction *I) {
382706b4fc4SDimitry Andric if (I->mayThrow())
383706b4fc4SDimitry Andric return true;
384706b4fc4SDimitry Andric
385706b4fc4SDimitry Andric const CallBase *CB = dyn_cast<CallBase>(I);
386706b4fc4SDimitry Andric if (!CB)
387706b4fc4SDimitry Andric return false;
388706b4fc4SDimitry Andric if (!CB->hasFnAttr(Attribute::WillReturn))
389706b4fc4SDimitry Andric return true;
390706b4fc4SDimitry Andric if (!CB->hasFnAttr(Attribute::NoSync))
391706b4fc4SDimitry Andric return true;
392706b4fc4SDimitry Andric
393706b4fc4SDimitry Andric return false;
394706b4fc4SDimitry Andric })) {
395706b4fc4SDimitry Andric return reportInvalidCandidate(I, MayThrowException);
396706b4fc4SDimitry Andric }
397706b4fc4SDimitry Andric
398706b4fc4SDimitry Andric // Check if I has any output/flow/anti dependences with instructions from \p
399706b4fc4SDimitry Andric // StartInst to \p EndInst.
400b60736ecSDimitry Andric if (llvm::any_of(InstsToCheck, [&DI, &I](Instruction *CurInst) {
401cfca06d7SDimitry Andric auto DepResult = DI->depends(&I, CurInst, true);
402b60736ecSDimitry Andric if (DepResult && (DepResult->isOutput() || DepResult->isFlow() ||
403706b4fc4SDimitry Andric DepResult->isAnti()))
404706b4fc4SDimitry Andric return true;
405706b4fc4SDimitry Andric return false;
406706b4fc4SDimitry Andric }))
407706b4fc4SDimitry Andric return reportInvalidCandidate(I, HasDependences);
408706b4fc4SDimitry Andric
409706b4fc4SDimitry Andric return true;
410706b4fc4SDimitry Andric }
411706b4fc4SDimitry Andric
isSafeToMoveBefore(BasicBlock & BB,Instruction & InsertPoint,DominatorTree & DT,const PostDominatorTree * PDT,DependenceInfo * DI)412cfca06d7SDimitry Andric bool llvm::isSafeToMoveBefore(BasicBlock &BB, Instruction &InsertPoint,
413cfca06d7SDimitry Andric DominatorTree &DT, const PostDominatorTree *PDT,
414cfca06d7SDimitry Andric DependenceInfo *DI) {
415cfca06d7SDimitry Andric return llvm::all_of(BB, [&](Instruction &I) {
416cfca06d7SDimitry Andric if (BB.getTerminator() == &I)
417cfca06d7SDimitry Andric return true;
418cfca06d7SDimitry Andric
419c0981da4SDimitry Andric return isSafeToMoveBefore(I, InsertPoint, DT, PDT, DI,
420c0981da4SDimitry Andric /*CheckForEntireBlock=*/true);
421cfca06d7SDimitry Andric });
422cfca06d7SDimitry Andric }
423cfca06d7SDimitry Andric
moveInstructionsToTheBeginning(BasicBlock & FromBB,BasicBlock & ToBB,DominatorTree & DT,const PostDominatorTree & PDT,DependenceInfo & DI)424cfca06d7SDimitry Andric void llvm::moveInstructionsToTheBeginning(BasicBlock &FromBB, BasicBlock &ToBB,
425cfca06d7SDimitry Andric DominatorTree &DT,
426cfca06d7SDimitry Andric const PostDominatorTree &PDT,
427cfca06d7SDimitry Andric DependenceInfo &DI) {
428c0981da4SDimitry Andric for (Instruction &I :
429c0981da4SDimitry Andric llvm::make_early_inc_range(llvm::drop_begin(llvm::reverse(FromBB)))) {
430706b4fc4SDimitry Andric Instruction *MovePos = ToBB.getFirstNonPHIOrDbg();
431706b4fc4SDimitry Andric
432cfca06d7SDimitry Andric if (isSafeToMoveBefore(I, *MovePos, DT, &PDT, &DI))
433b1c73532SDimitry Andric I.moveBeforePreserving(MovePos);
434cfca06d7SDimitry Andric }
435cfca06d7SDimitry Andric }
436cfca06d7SDimitry Andric
moveInstructionsToTheEnd(BasicBlock & FromBB,BasicBlock & ToBB,DominatorTree & DT,const PostDominatorTree & PDT,DependenceInfo & DI)437cfca06d7SDimitry Andric void llvm::moveInstructionsToTheEnd(BasicBlock &FromBB, BasicBlock &ToBB,
438cfca06d7SDimitry Andric DominatorTree &DT,
439cfca06d7SDimitry Andric const PostDominatorTree &PDT,
440cfca06d7SDimitry Andric DependenceInfo &DI) {
441cfca06d7SDimitry Andric Instruction *MovePos = ToBB.getTerminator();
442cfca06d7SDimitry Andric while (FromBB.size() > 1) {
443cfca06d7SDimitry Andric Instruction &I = FromBB.front();
444cfca06d7SDimitry Andric if (isSafeToMoveBefore(I, *MovePos, DT, &PDT, &DI))
445b1c73532SDimitry Andric I.moveBeforePreserving(MovePos);
446706b4fc4SDimitry Andric }
447706b4fc4SDimitry Andric }
448c0981da4SDimitry Andric
nonStrictlyPostDominate(const BasicBlock * ThisBlock,const BasicBlock * OtherBlock,const DominatorTree * DT,const PostDominatorTree * PDT)449c0981da4SDimitry Andric bool llvm::nonStrictlyPostDominate(const BasicBlock *ThisBlock,
450c0981da4SDimitry Andric const BasicBlock *OtherBlock,
451c0981da4SDimitry Andric const DominatorTree *DT,
452c0981da4SDimitry Andric const PostDominatorTree *PDT) {
453c0981da4SDimitry Andric assert(isControlFlowEquivalent(*ThisBlock, *OtherBlock, *DT, *PDT) &&
454c0981da4SDimitry Andric "ThisBlock and OtherBlock must be CFG equivalent!");
455c0981da4SDimitry Andric const BasicBlock *CommonDominator =
456c0981da4SDimitry Andric DT->findNearestCommonDominator(ThisBlock, OtherBlock);
457c0981da4SDimitry Andric if (CommonDominator == nullptr)
458c0981da4SDimitry Andric return false;
459c0981da4SDimitry Andric
460c0981da4SDimitry Andric /// Recursively check the predecessors of \p ThisBlock up to
461c0981da4SDimitry Andric /// their common dominator, and see if any of them post-dominates
462c0981da4SDimitry Andric /// \p OtherBlock.
463c0981da4SDimitry Andric SmallVector<const BasicBlock *, 8> WorkList;
464c0981da4SDimitry Andric SmallPtrSet<const BasicBlock *, 8> Visited;
465c0981da4SDimitry Andric WorkList.push_back(ThisBlock);
466c0981da4SDimitry Andric while (!WorkList.empty()) {
467c0981da4SDimitry Andric const BasicBlock *CurBlock = WorkList.back();
468c0981da4SDimitry Andric WorkList.pop_back();
469c0981da4SDimitry Andric Visited.insert(CurBlock);
470c0981da4SDimitry Andric if (PDT->dominates(CurBlock, OtherBlock))
471c0981da4SDimitry Andric return true;
472c0981da4SDimitry Andric
473e3b55780SDimitry Andric for (const auto *Pred : predecessors(CurBlock)) {
474c0981da4SDimitry Andric if (Pred == CommonDominator || Visited.count(Pred))
475c0981da4SDimitry Andric continue;
476c0981da4SDimitry Andric WorkList.push_back(Pred);
477c0981da4SDimitry Andric }
478c0981da4SDimitry Andric }
479c0981da4SDimitry Andric return false;
480c0981da4SDimitry Andric }
481c0981da4SDimitry Andric
isReachedBefore(const Instruction * I0,const Instruction * I1,const DominatorTree * DT,const PostDominatorTree * PDT)482c0981da4SDimitry Andric bool llvm::isReachedBefore(const Instruction *I0, const Instruction *I1,
483c0981da4SDimitry Andric const DominatorTree *DT,
484c0981da4SDimitry Andric const PostDominatorTree *PDT) {
485c0981da4SDimitry Andric const BasicBlock *BB0 = I0->getParent();
486c0981da4SDimitry Andric const BasicBlock *BB1 = I1->getParent();
487c0981da4SDimitry Andric if (BB0 == BB1)
488c0981da4SDimitry Andric return DT->dominates(I0, I1);
489c0981da4SDimitry Andric
490c0981da4SDimitry Andric return nonStrictlyPostDominate(BB1, BB0, DT, PDT);
491c0981da4SDimitry Andric }
492