1//===- FixIrreducible.cpp - Convert irreducible control-flow into loops ---===//
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// INPUT CFG: The blocks H and B form an irreducible cycle with two headers.
10//
11// Entry
12// / \
13// v v
14// H ----> B
15// ^ /|
16// `----' |
17// v
18// Exit
19//
20// OUTPUT CFG: Converted to a natural loop with a new header N.
21//
22// Entry
23// |
24// v
25// N <---.
26// / \ \
27// / \ |
28// v v /
29// H --> B --'
30// |
31// v
32// Exit
33//
34// To convert an irreducible cycle C to a natural loop L:
35//
36// 1. Add a new node N to C.
37// 2. Redirect all external incoming edges through N.
38// 3. Redirect all edges incident on header H through N.
39//
40// This is sufficient to ensure that:
41//
42// a. Every closed path in C also exists in L, with the modification that any
43// path passing through H now passes through N before reaching H.
44// b. Every external path incident on any entry of C is now incident on N and
45// then redirected to the entry.
46//
47// Thus, L is a strongly connected component dominated by N, and hence L is a
48// natural loop with header N.
49//
50// When an irreducible cycle C with header H is transformed into a loop, the
51// following invariants hold:
52//
53// 1. No new subcycles are "discovered" in the set (C-H). The only internal
54// edges that are redirected by the transform are incident on H. Any subcycle
55// S in (C-H), already existed prior to this transform, and is already in the
56// list of children for this cycle C.
57//
58// 2. Subcycles of C are not modified by the transform. For some subcycle S of
59// C, edges incident on the entries of S are either internal to C, or they
60// are now redirected through N, which is outside of S. So the list of
61// entries to S does not change. Since the transform only adds a block
62// outside S, and redirects edges that are not internal to S, the list of
63// blocks in S does not change.
64//
65// 3. Similarly, any natural loop L included in C is not affected, with one
66// exception: L is "destroyed" by the transform iff its header is H. The
67// backedges of such a loop are now redirected to N instead, and hence the
68// body of this loop gets merged into the new loop with header N.
69//
70// The actual transformation is handled by the ControlFlowHub, which redirects
71// specified control flow edges through a set of guard blocks. This also moves
72// every PHINode in an outgoing block to the hub. Since the hub dominates all
73// the outgoing blocks, each such PHINode continues to dominate its uses. Since
74// every header in an SCC has at least two predecessors, every value used in the
75// header (or later) but defined in a predecessor (or earlier) is represented by
76// a PHINode in a header. Hence the above handling of PHINodes is sufficient and
77// no further processing is required to restore SSA.
78//
79// Limitation: The pass cannot handle indirect branches. They must be lowered to
80// plain branches first.
81//
82// CallBr and Switch support: CallBr and Switch terminators are handled as a
83// more general branch instruction which can have multiple successors. The pass
84// redirects the edges to intermediate target blocks that unconditionally branch
85// to the original target blocks. This allows the control flow hub to know to
86// which of the original target blocks to jump to. Example input CFG:
87// Entry (callbr/switch)
88// / \
89// v v
90// H ----> B
91// ^ /|
92// `----' |
93// v
94// Exit
95//
96// becomes:
97// Entry (callbr/switch)
98// / \
99// v v
100// target.H target.B
101// | |
102// v v
103// H ----> B
104// ^ /|
105// `----' |
106// v
107// Exit
108//
109// Note
110// OUTPUT CFG: Converted to a natural loop with a new header N.
111//
112// Entry (callbr/switch)
113// / \
114// v v
115// target.H target.B
116// \ /
117// \ /
118// v v
119// N <---.
120// / \ \
121// / \ |
122// v v /
123// H --> B --'
124// |
125// v
126// Exit
127//
128//===----------------------------------------------------------------------===//
129
130#include "llvm/Transforms/Utils/FixIrreducible.h"
131#include "llvm/ADT/DenseMap.h"
132#include "llvm/Analysis/CycleAnalysis.h"
133#include "llvm/Analysis/DomTreeUpdater.h"
134#include "llvm/Analysis/LoopInfo.h"
135#include "llvm/IR/Instructions.h"
136#include "llvm/InitializePasses.h"
137#include "llvm/Pass.h"
138#include "llvm/Support/ErrorHandling.h"
139#include "llvm/Transforms/Utils.h"
140#include "llvm/Transforms/Utils/BasicBlockUtils.h"
141#include "llvm/Transforms/Utils/ControlFlowUtils.h"
142
143#define DEBUG_TYPE "fix-irreducible"
144
145using namespace llvm;
146
147namespace {
148struct FixIrreducible : public FunctionPass {
149 static char ID;
150 FixIrreducible() : FunctionPass(ID) {
151 initializeFixIrreduciblePass(*PassRegistry::getPassRegistry());
152 }
153
154 void getAnalysisUsage(AnalysisUsage &AU) const override {
155 AU.addRequired<DominatorTreeWrapperPass>();
156 AU.addRequired<CycleInfoWrapperPass>();
157 AU.addPreserved<DominatorTreeWrapperPass>();
158 AU.addPreserved<CycleInfoWrapperPass>();
159 AU.addPreserved<LoopInfoWrapperPass>();
160 }
161
162 bool runOnFunction(Function &F) override;
163};
164} // namespace
165
166char FixIrreducible::ID = 0;
167
168FunctionPass *llvm::createFixIrreduciblePass() { return new FixIrreducible(); }
169
170INITIALIZE_PASS_BEGIN(FixIrreducible, "fix-irreducible",
171 "Convert irreducible control-flow into natural loops",
172 false /* Only looks at CFG */, false /* Analysis Pass */)
173INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
174INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
175INITIALIZE_PASS_DEPENDENCY(CycleInfoWrapperPass)
176INITIALIZE_PASS_END(FixIrreducible, "fix-irreducible",
177 "Convert irreducible control-flow into natural loops",
178 false /* Only looks at CFG */, false /* Analysis Pass */)
179
180// When a new loop is created, existing children of the parent loop may now be
181// fully inside the new loop. Reconnect these as children of the new loop.
182static void reconnectChildLoops(LoopInfo &LI, Loop *ParentLoop, Loop *NewLoop,
183 BasicBlock *OldHeader) {
184 // Any candidate (sibling of NewLoop, or top-level loop if there is no
185 // parent) is a child iff its header is owned by the new loop. The new loop's
186 // block list is already populated but its subloops are not yet attached, so
187 // query the block list directly rather than contains(), which would derive
188 // from the not-yet-updated block-to-loop map.
189 SmallVector<Loop *, 4> ChildLoops =
190 LI.takeChildrenIf(Parent: ParentLoop, Pred: [&](Loop *L) {
191 return NewLoop != L &&
192 llvm::is_contained(Range: NewLoop->getBlocks(), Element: L->getHeader());
193 });
194
195 for (Loop *Child : ChildLoops) {
196 LLVM_DEBUG(dbgs() << "child loop: " << Child->getHeader()->getName()
197 << "\n");
198 // A child loop whose header was the old cycle header gets destroyed since
199 // its backedges are removed.
200 if (Child->getHeader() == OldHeader) {
201 for (auto *BB : Child->blocks()) {
202 if (LI.getLoopFor(BB) != Child)
203 continue;
204 LI.changeLoopFor(BB, L: NewLoop);
205 LLVM_DEBUG(dbgs() << "moved block from child: " << BB->getName()
206 << "\n");
207 }
208 for (Loop *GrandChildLoop :
209 LI.takeChildrenIf(Parent: Child, Pred: [](const Loop *) { return true; }))
210 NewLoop->addChildLoop(NewChild: GrandChildLoop);
211 LI.destroy(L: Child);
212 LLVM_DEBUG(dbgs() << "subsumed child loop (common header)\n");
213 continue;
214 }
215
216 NewLoop->addChildLoop(NewChild: Child);
217 LLVM_DEBUG(dbgs() << "added child loop to new loop\n");
218 }
219}
220
221static void updateLoopInfo(CycleInfo &CI, LoopInfo &LI, CycleRef C,
222 ArrayRef<BasicBlock *> GuardBlocks) {
223 // The parent loop is a natural loop L mapped to the cycle header H as long as
224 // H is not also the header of L. In the latter case, L is destroyed and we
225 // seek its parent instead.
226 BasicBlock *CycleHeader = CI.getHeader(C);
227 Loop *ParentLoop = LI.getLoopFor(BB: CycleHeader);
228 if (ParentLoop && ParentLoop->getHeader() == CycleHeader)
229 ParentLoop = ParentLoop->getParentLoop();
230
231 // Create a new loop from the now-transformed cycle
232 auto *NewLoop = LI.AllocateLoop();
233 if (ParentLoop) {
234 ParentLoop->addChildLoop(NewChild: NewLoop);
235 } else {
236 LI.addTopLevelLoop(New: NewLoop);
237 }
238
239 // Add the guard blocks to the new loop. The first guard block is
240 // the head of all the backedges, and it is the first to be inserted
241 // in the loop. This ensures that it is recognized as the
242 // header. Since the new loop is already in LoopInfo, the new blocks
243 // are also propagated up the chain of parent loops.
244 for (auto *G : GuardBlocks) {
245 LLVM_DEBUG(dbgs() << "added guard block to loop: " << G->getName() << "\n");
246 NewLoop->addBasicBlockToLoop(NewBB: G, LI);
247 }
248
249 for (auto *BB : CI.getBlocks(C)) {
250 NewLoop->addBlockEntry(BB);
251 if (LI.getLoopFor(BB) == ParentLoop) {
252 LLVM_DEBUG(dbgs() << "moved block from parent: " << BB->getName()
253 << "\n");
254 LI.changeLoopFor(BB, L: NewLoop);
255 } else {
256 LLVM_DEBUG(dbgs() << "added block from child: " << BB->getName() << "\n");
257 }
258 }
259 LLVM_DEBUG(dbgs() << "header for new loop: "
260 << NewLoop->getHeader()->getName() << "\n");
261
262 reconnectChildLoops(LI, ParentLoop, NewLoop, OldHeader: CI.getHeader(C));
263
264 LLVM_DEBUG(dbgs() << "Verify new loop.\n"; NewLoop->print(dbgs()));
265 NewLoop->verifyLoop();
266 if (ParentLoop) {
267 LLVM_DEBUG(dbgs() << "Verify parent loop.\n"; ParentLoop->print(dbgs()));
268 ParentLoop->verifyLoop();
269 }
270}
271
272// Given a set of blocks and headers in an irreducible SCC, convert it into a
273// natural loop. Also insert this new loop at its appropriate place in the
274// hierarchy of loops.
275static bool fixIrreducible(CycleRef C, CycleInfo &CI, DominatorTree &DT,
276 LoopInfo *LI) {
277 if (CI.isReducible(C))
278 return false;
279 LLVM_DEBUG(dbgs() << "Processing cycle:\n" << CI.print(C) << "\n";);
280
281 DomTreeUpdater DTU(DT, DomTreeUpdater::UpdateStrategy::Eager);
282 ControlFlowHub CHub;
283 SetVector<BasicBlock *> Predecessors;
284
285 // Redirect internal edges incident on the header.
286 BasicBlock *Header = CI.getHeader(C);
287 for (BasicBlock *P : predecessors(BB: Header)) {
288 if (CI.contains(C, Block: P))
289 Predecessors.insert(X: P);
290 }
291
292 for (BasicBlock *P : Predecessors) {
293 Instruction *Term = P->getTerminator();
294 if (isa<UncondBrInst>(Val: Term)) {
295 assert(Term->getSuccessor(0) == Header);
296 CHub.addBranch(BB: P, Succ0: Header);
297
298 LLVM_DEBUG(dbgs() << "Added internal branch: " << printBasicBlock(P)
299 << " -> " << printBasicBlock(Header) << '\n');
300 } else if (CondBrInst *Branch = dyn_cast<CondBrInst>(Val: Term)) {
301 BasicBlock *Succ0 = Branch->getSuccessor(i: 0) == Header ? Header : nullptr;
302 BasicBlock *Succ1 = Branch->getSuccessor(i: 1) == Header ? Header : nullptr;
303 assert(Succ0 || Succ1);
304 CHub.addBranch(BB: P, Succ0, Succ1);
305
306 LLVM_DEBUG(dbgs() << "Added internal branch: " << printBasicBlock(P)
307 << " -> " << printBasicBlock(Succ0)
308 << (Succ0 && Succ1 ? " " : "") << printBasicBlock(Succ1)
309 << '\n');
310 } else if (isa<CallBrInst>(Val: Term) || isa<SwitchInst>(Val: Term)) {
311 BasicBlock *NewSucc = nullptr;
312 for (unsigned I = 0; I < Term->getNumSuccessors(); ++I) {
313 BasicBlock *Succ = Term->getSuccessor(Idx: I);
314 if (Succ != Header)
315 continue;
316 NewSucc = SplitMultiBrEdge(MultiBrBlock: P, Succ, SuccIdx: I, BrTarget: NewSucc, DTU: &DTU, CI: &CI, LI);
317 LLVM_DEBUG(dbgs() << "Added internal branch: "
318 << printBasicBlock(NewSucc) << " -> "
319 << printBasicBlock(Succ) << '\n');
320 }
321 if (NewSucc)
322 CHub.addBranch(BB: NewSucc, Succ0: Header);
323 } else {
324 reportFatalUsageError(
325 reason: "unsupported block terminator: fix-irreducible "
326 "only supports br, callbr, and switch instructions");
327 }
328 }
329
330 // Redirect external edges incident on any entry (including the header).
331 // Ignore external edges to non-entry blocks, which can only come from
332 // unreachable predecessors; redirecting them would make the hub branch to a
333 // non-entry block, effectively turning it into a new entry.
334 SmallPtrSet<BasicBlock *, 8> Entries(from_range, CI.getEntries(C));
335 Predecessors.clear();
336 for (BasicBlock *E : CI.getEntries(C)) {
337 for (BasicBlock *P : predecessors(BB: E)) {
338 if (!CI.contains(C, Block: P))
339 Predecessors.insert(X: P);
340 }
341 }
342
343 for (BasicBlock *P : Predecessors) {
344 Instruction *Term = P->getTerminator();
345 if (UncondBrInst *Branch = dyn_cast<UncondBrInst>(Val: Term)) {
346 BasicBlock *Succ0 = Branch->getSuccessor();
347 Succ0 = Entries.contains(Ptr: Succ0) ? Succ0 : nullptr;
348 CHub.addBranch(BB: P, Succ0);
349
350 LLVM_DEBUG(dbgs() << "Added external branch: " << printBasicBlock(P)
351 << " -> " << printBasicBlock(Succ0) << '\n');
352 } else if (CondBrInst *Branch = dyn_cast<CondBrInst>(Val: Term)) {
353 BasicBlock *Succ0 = Branch->getSuccessor(i: 0);
354 Succ0 = Entries.contains(Ptr: Succ0) ? Succ0 : nullptr;
355 BasicBlock *Succ1 = Branch->getSuccessor(i: 1);
356 Succ1 = Entries.contains(Ptr: Succ1) ? Succ1 : nullptr;
357 CHub.addBranch(BB: P, Succ0, Succ1);
358
359 LLVM_DEBUG(dbgs() << "Added external branch: " << printBasicBlock(P)
360 << " -> " << printBasicBlock(Succ0)
361 << (Succ0 && Succ1 ? " " : "") << printBasicBlock(Succ1)
362 << '\n');
363 } else if (isa<CallBrInst>(Val: Term) || isa<SwitchInst>(Val: Term)) {
364 SmallDenseMap<BasicBlock *, BasicBlock *> MultiBrTargets;
365 for (unsigned I = 0; I < Term->getNumSuccessors(); ++I) {
366 BasicBlock *Succ = Term->getSuccessor(Idx: I);
367 if (!Entries.contains(Ptr: Succ))
368 continue;
369 auto It = MultiBrTargets.find(Val: Succ);
370 BasicBlock *ExistingTarget =
371 (It != MultiBrTargets.end()) ? It->second : nullptr;
372
373 BasicBlock *NewSucc =
374 SplitMultiBrEdge(MultiBrBlock: P, Succ, SuccIdx: I, BrTarget: ExistingTarget, DTU: &DTU, CI: &CI, LI);
375 if (!ExistingTarget) {
376 CHub.addBranch(BB: NewSucc, Succ0: Succ);
377 MultiBrTargets[Succ] = NewSucc;
378 }
379 LLVM_DEBUG(dbgs() << "Added external branch: "
380 << printBasicBlock(NewSucc) << " -> "
381 << printBasicBlock(Succ) << '\n');
382 }
383 } else {
384 reportFatalUsageError(
385 reason: "unsupported block terminator: fix-irreducible "
386 "only supports br, callbr, and switch instructions");
387 }
388 }
389
390 // Redirect all the backedges through a "hub" consisting of a series
391 // of guard blocks that manage the flow of control from the
392 // predecessors to the headers.
393 SmallVector<BasicBlock *> GuardBlocks;
394
395 CHub.finalize(DTU: &DTU, GuardBlocks, Prefix: "irr");
396#if defined(EXPENSIVE_CHECKS)
397 assert(DT.verify(DominatorTree::VerificationLevel::Full));
398#else
399 assert(DT.verify(DominatorTree::VerificationLevel::Fast));
400#endif
401
402 // If we are updating LoopInfo, do that now before modifying the cycle. This
403 // ensures that the first guard block is the header of a new natural loop.
404 if (LI)
405 updateLoopInfo(CI, LI&: *LI, C, GuardBlocks);
406
407 for (auto *G : GuardBlocks) {
408 LLVM_DEBUG(dbgs() << "added guard block to cycle: " << G->getName()
409 << "\n");
410 CI.addBlockToCycle(Block: G, C);
411 }
412 CI.setSingleEntry(C, Block: GuardBlocks[0]);
413
414 SmallPtrSet<BasicBlock *, 32> Reachable;
415 CI.verifyCycle(C, Reachable);
416 if (CycleRef Parent = CI.getParentCycle(C))
417 CI.verifyCycle(C: Parent, Reachable);
418
419 LLVM_DEBUG(dbgs() << "Finished one cycle:\n"; CI.print(dbgs()););
420 return true;
421}
422
423static bool FixIrreducibleImpl(Function &F, CycleInfo &CI, DominatorTree &DT,
424 LoopInfo *LI) {
425 LLVM_DEBUG(dbgs() << "===== Fix irreducible control-flow in function: "
426 << F.getName() << "\n");
427
428 bool Changed = false;
429 for (auto C : CI.cycles())
430 Changed |= fixIrreducible(C, CI, DT, LI);
431
432 if (!Changed)
433 return false;
434
435#if defined(EXPENSIVE_CHECKS)
436 CI.verify();
437 if (LI)
438 LI->verify();
439#endif // EXPENSIVE_CHECKS
440
441 return true;
442}
443
444bool FixIrreducible::runOnFunction(Function &F) {
445 auto *LIWP = getAnalysisIfAvailable<LoopInfoWrapperPass>();
446 LoopInfo *LI = LIWP ? &LIWP->getLoopInfo() : nullptr;
447 auto &CI = getAnalysis<CycleInfoWrapperPass>().getResult();
448 auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
449 return FixIrreducibleImpl(F, CI, DT, LI);
450}
451
452PreservedAnalyses FixIrreduciblePass::run(Function &F,
453 FunctionAnalysisManager &AM) {
454 auto *LI = AM.getCachedResult<LoopAnalysis>(IR&: F);
455 auto &CI = AM.getResult<CycleAnalysis>(IR&: F);
456 auto &DT = AM.getResult<DominatorTreeAnalysis>(IR&: F);
457
458 if (!FixIrreducibleImpl(F, CI, DT, LI))
459 return PreservedAnalyses::all();
460
461 PreservedAnalyses PA;
462 PA.preserve<LoopAnalysis>();
463 PA.preserve<CycleAnalysis>();
464 PA.preserve<DominatorTreeAnalysis>();
465 return PA;
466}
467