blob: c9b0f20818090eaf87ff18237108acd4ab32fc42 [file] [log] [blame]
Eugene Zelenko57bd5a02017-10-27 01:09:08 +00001//===- BasicBlockUtils.cpp - BasicBlock Utilities --------------------------==//
Misha Brukmanb1c93172005-04-21 23:48:37 +00002//
John Criswell482202a2003-10-20 19:43:21 +00003// The LLVM Compiler Infrastructure
4//
Chris Lattnerf3ebc3f2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Misha Brukmanb1c93172005-04-21 23:48:37 +00007//
John Criswell482202a2003-10-20 19:43:21 +00008//===----------------------------------------------------------------------===//
Chris Lattner28537df2002-05-07 18:07:59 +00009//
10// This family of functions perform manipulations on basic blocks, and
11// instructions contained within basic blocks.
12//
13//===----------------------------------------------------------------------===//
14
15#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Eugene Zelenko57bd5a02017-10-27 01:09:08 +000016#include "llvm/ADT/ArrayRef.h"
17#include "llvm/ADT/SmallPtrSet.h"
18#include "llvm/ADT/SmallVector.h"
19#include "llvm/ADT/Twine.h"
Nick Lewycky0b682452013-07-27 01:24:00 +000020#include "llvm/Analysis/CFG.h"
Chris Lattnerf6ae9042011-01-11 08:13:40 +000021#include "llvm/Analysis/LoopInfo.h"
22#include "llvm/Analysis/MemoryDependenceAnalysis.h"
Eugene Zelenko57bd5a02017-10-27 01:09:08 +000023#include "llvm/IR/BasicBlock.h"
24#include "llvm/IR/CFG.h"
25#include "llvm/IR/Constants.h"
Chandler Carruth5ad5f152014-01-13 09:26:24 +000026#include "llvm/IR/Dominators.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000027#include "llvm/IR/Function.h"
Eugene Zelenko57bd5a02017-10-27 01:09:08 +000028#include "llvm/IR/InstrTypes.h"
29#include "llvm/IR/Instruction.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000030#include "llvm/IR/Instructions.h"
Eugene Zelenko57bd5a02017-10-27 01:09:08 +000031#include "llvm/IR/LLVMContext.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000032#include "llvm/IR/Type.h"
Eugene Zelenko57bd5a02017-10-27 01:09:08 +000033#include "llvm/IR/User.h"
34#include "llvm/IR/Value.h"
Chandler Carruth4220e9c2014-03-04 11:17:44 +000035#include "llvm/IR/ValueHandle.h"
Eugene Zelenko57bd5a02017-10-27 01:09:08 +000036#include "llvm/Support/Casting.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000037#include "llvm/Transforms/Utils/Local.h"
Eugene Zelenko57bd5a02017-10-27 01:09:08 +000038#include <cassert>
39#include <cstdint>
40#include <string>
41#include <utility>
42#include <vector>
43
Chris Lattnerdf3c3422004-01-09 06:12:26 +000044using namespace llvm;
Brian Gaeke960707c2003-11-11 22:41:34 +000045
Chris Lattner7eb270e2008-12-03 06:40:52 +000046void llvm::DeleteDeadBlock(BasicBlock *BB) {
Chris Lattner37e01362008-12-03 07:45:15 +000047 assert((pred_begin(BB) == pred_end(BB) ||
48 // Can delete self loop.
49 BB->getSinglePredecessor() == BB) && "Block is not dead!");
Chris Lattnerbcc904a2008-12-03 06:37:44 +000050 TerminatorInst *BBTerm = BB->getTerminator();
Jakub Staszak190db2f2013-01-14 23:16:36 +000051
Chris Lattnerbcc904a2008-12-03 06:37:44 +000052 // Loop through all of our successors and make sure they know that one
53 // of their predecessors is going away.
Pete Cooperebcd7482015-08-06 20:22:46 +000054 for (BasicBlock *Succ : BBTerm->successors())
55 Succ->removePredecessor(BB);
Jakub Staszak190db2f2013-01-14 23:16:36 +000056
Chris Lattnerbcc904a2008-12-03 06:37:44 +000057 // Zap all the instructions in the block.
58 while (!BB->empty()) {
59 Instruction &I = BB->back();
60 // If this instruction is used, replace uses with an arbitrary value.
61 // Because control flow can't get here, we don't care what we replace the
62 // value with. Note that since this block is unreachable, and all values
63 // contained within it must dominate their uses, that all uses will
64 // eventually be removed (they are themselves dead).
65 if (!I.use_empty())
Owen Andersonb292b8c2009-07-30 23:03:37 +000066 I.replaceAllUsesWith(UndefValue::get(I.getType()));
Chris Lattnerbcc904a2008-12-03 06:37:44 +000067 BB->getInstList().pop_back();
68 }
Jakub Staszak190db2f2013-01-14 23:16:36 +000069
Chris Lattnerbcc904a2008-12-03 06:37:44 +000070 // Zap the block!
71 BB->eraseFromParent();
Chris Lattnerbcc904a2008-12-03 06:37:44 +000072}
73
Chandler Carruth96ada252015-07-22 09:52:54 +000074void llvm::FoldSingleEntryPHINodes(BasicBlock *BB,
Chandler Carruth61440d22016-03-10 00:55:30 +000075 MemoryDependenceResults *MemDep) {
Chris Lattnerf6ae9042011-01-11 08:13:40 +000076 if (!isa<PHINode>(BB->begin())) return;
Jakub Staszak190db2f2013-01-14 23:16:36 +000077
Chris Lattnerdc3f6f22008-12-03 19:44:02 +000078 while (PHINode *PN = dyn_cast<PHINode>(BB->begin())) {
79 if (PN->getIncomingValue(0) != PN)
80 PN->replaceAllUsesWith(PN->getIncomingValue(0));
81 else
Owen Andersonb292b8c2009-07-30 23:03:37 +000082 PN->replaceAllUsesWith(UndefValue::get(PN->getType()));
Jakub Staszak190db2f2013-01-14 23:16:36 +000083
Chris Lattnerf6ae9042011-01-11 08:13:40 +000084 if (MemDep)
85 MemDep->removeInstruction(PN); // Memdep updates AA itself.
Jakub Staszak190db2f2013-01-14 23:16:36 +000086
Chris Lattnerdc3f6f22008-12-03 19:44:02 +000087 PN->eraseFromParent();
88 }
89}
90
Benjamin Kramer8bcc9712012-08-29 15:32:21 +000091bool llvm::DeleteDeadPHIs(BasicBlock *BB, const TargetLibraryInfo *TLI) {
Dan Gohmanff089952009-05-02 18:29:22 +000092 // Recursively deleting a PHI may cause multiple PHIs to be deleted
Sanjoy Dase6bca0e2017-05-01 17:07:49 +000093 // or RAUW'd undef, so use an array of WeakTrackingVH for the PHIs to delete.
94 SmallVector<WeakTrackingVH, 8> PHIs;
Dan Gohmanff089952009-05-02 18:29:22 +000095 for (BasicBlock::iterator I = BB->begin();
96 PHINode *PN = dyn_cast<PHINode>(I); ++I)
97 PHIs.push_back(PN);
98
Dan Gohmancb99fe92010-01-05 15:45:31 +000099 bool Changed = false;
Dan Gohmanff089952009-05-02 18:29:22 +0000100 for (unsigned i = 0, e = PHIs.size(); i != e; ++i)
101 if (PHINode *PN = dyn_cast_or_null<PHINode>(PHIs[i].operator Value*()))
Benjamin Kramer8bcc9712012-08-29 15:32:21 +0000102 Changed |= RecursivelyDeleteDeadPHINode(PN, TLI);
Dan Gohmancb99fe92010-01-05 15:45:31 +0000103
104 return Changed;
Dan Gohmanff089952009-05-02 18:29:22 +0000105}
106
Chandler Carruthb5c11532015-01-18 02:11:23 +0000107bool llvm::MergeBlockIntoPredecessor(BasicBlock *BB, DominatorTree *DT,
Chandler Carruth96ada252015-07-22 09:52:54 +0000108 LoopInfo *LI,
Chandler Carruth61440d22016-03-10 00:55:30 +0000109 MemoryDependenceResults *MemDep) {
Dan Gohman941020e2010-08-17 17:07:02 +0000110 // Don't merge away blocks who have their address taken.
111 if (BB->hasAddressTaken()) return false;
Jakub Staszak190db2f2013-01-14 23:16:36 +0000112
Dan Gohman941020e2010-08-17 17:07:02 +0000113 // Can't merge if there are multiple predecessors, or no predecessors.
114 BasicBlock *PredBB = BB->getUniquePredecessor();
Dan Gohman2d02ff82009-10-31 17:33:01 +0000115 if (!PredBB) return false;
Dan Gohman941020e2010-08-17 17:07:02 +0000116
Dan Gohman2d02ff82009-10-31 17:33:01 +0000117 // Don't break self-loops.
118 if (PredBB == BB) return false;
David Majnemer654e1302015-07-31 17:58:14 +0000119 // Don't break unwinding instructions.
120 if (PredBB->getTerminator()->isExceptional())
121 return false;
Jakub Staszak190db2f2013-01-14 23:16:36 +0000122
Dan Gohman2d02ff82009-10-31 17:33:01 +0000123 succ_iterator SI(succ_begin(PredBB)), SE(succ_end(PredBB));
Chris Lattner930b7162011-01-08 19:08:40 +0000124 BasicBlock *OnlySucc = BB;
Dan Gohman2d02ff82009-10-31 17:33:01 +0000125 for (; SI != SE; ++SI)
126 if (*SI != OnlySucc) {
Craig Topperf40110f2014-04-25 05:29:35 +0000127 OnlySucc = nullptr; // There are multiple distinct successors!
Dan Gohman2d02ff82009-10-31 17:33:01 +0000128 break;
129 }
Jakub Staszak190db2f2013-01-14 23:16:36 +0000130
Dan Gohman2d02ff82009-10-31 17:33:01 +0000131 // Can't merge if there are multiple successors.
132 if (!OnlySucc) return false;
Devang Patel0f7a3502008-09-09 01:06:56 +0000133
Dan Gohman2d02ff82009-10-31 17:33:01 +0000134 // Can't merge if there is PHI loop.
135 for (BasicBlock::iterator BI = BB->begin(), BE = BB->end(); BI != BE; ++BI) {
136 if (PHINode *PN = dyn_cast<PHINode>(BI)) {
Pete Cooper833f34d2015-05-12 20:05:31 +0000137 for (Value *IncValue : PN->incoming_values())
138 if (IncValue == PN)
Dan Gohman2d02ff82009-10-31 17:33:01 +0000139 return false;
140 } else
141 break;
142 }
143
144 // Begin by getting rid of unneeded PHIs.
Chandler Carruthb5c11532015-01-18 02:11:23 +0000145 if (isa<PHINode>(BB->front()))
Chandler Carruth96ada252015-07-22 09:52:54 +0000146 FoldSingleEntryPHINodes(BB, MemDep);
Jakub Staszak190db2f2013-01-14 23:16:36 +0000147
Owen Andersonc0623812008-07-17 00:01:40 +0000148 // Delete the unconditional branch from the predecessor...
149 PredBB->getInstList().pop_back();
Jakub Staszak190db2f2013-01-14 23:16:36 +0000150
Owen Andersonc0623812008-07-17 00:01:40 +0000151 // Make all PHI nodes that referred to BB now refer to Pred as their
152 // source...
153 BB->replaceAllUsesWith(PredBB);
Jakub Staszak190db2f2013-01-14 23:16:36 +0000154
Jay Foad61ea0e42011-06-23 09:09:15 +0000155 // Move all definitions in the successor to the predecessor...
156 PredBB->getInstList().splice(PredBB->end(), BB->getInstList());
Jakub Staszak190db2f2013-01-14 23:16:36 +0000157
Dan Gohman2d02ff82009-10-31 17:33:01 +0000158 // Inherit predecessors name if it exists.
Owen Anderson27405ef2008-07-17 19:42:29 +0000159 if (!PredBB->hasName())
160 PredBB->takeName(BB);
Jakub Staszak190db2f2013-01-14 23:16:36 +0000161
Owen Andersonc0623812008-07-17 00:01:40 +0000162 // Finally, erase the old block and update dominator info.
Chandler Carruthb5c11532015-01-18 02:11:23 +0000163 if (DT)
164 if (DomTreeNode *DTN = DT->getNode(BB)) {
165 DomTreeNode *PredDTN = DT->getNode(PredBB);
166 SmallVector<DomTreeNode *, 8> Children(DTN->begin(), DTN->end());
Benjamin Kramer135f7352016-06-26 12:28:59 +0000167 for (DomTreeNode *DI : Children)
168 DT->changeImmediateDominator(DI, PredDTN);
Owen Andersonc0623812008-07-17 00:01:40 +0000169
Chandler Carruthb5c11532015-01-18 02:11:23 +0000170 DT->eraseNode(BB);
Owen Andersonc0623812008-07-17 00:01:40 +0000171 }
Chandler Carruthb5c11532015-01-18 02:11:23 +0000172
173 if (LI)
174 LI->removeBlock(BB);
175
176 if (MemDep)
177 MemDep->invalidateCachedPredecessors();
Jakub Staszak190db2f2013-01-14 23:16:36 +0000178
Owen Andersonc0623812008-07-17 00:01:40 +0000179 BB->eraseFromParent();
Dan Gohman2d02ff82009-10-31 17:33:01 +0000180 return true;
Owen Andersonc0623812008-07-17 00:01:40 +0000181}
182
Chris Lattnerdf3c3422004-01-09 06:12:26 +0000183void llvm::ReplaceInstWithValue(BasicBlock::InstListType &BIL,
184 BasicBlock::iterator &BI, Value *V) {
Chris Lattnerfda72b12002-06-25 16:12:52 +0000185 Instruction &I = *BI;
Chris Lattner28537df2002-05-07 18:07:59 +0000186 // Replaces all of the uses of the instruction with uses of the value
Chris Lattnerfda72b12002-06-25 16:12:52 +0000187 I.replaceAllUsesWith(V);
Chris Lattner28537df2002-05-07 18:07:59 +0000188
Chris Lattner8dd4cae2007-02-11 01:37:51 +0000189 // Make sure to propagate a name if there is one already.
190 if (I.hasName() && !V->hasName())
191 V->takeName(&I);
Misha Brukmanb1c93172005-04-21 23:48:37 +0000192
Misha Brukman7eb05a12003-08-18 14:43:39 +0000193 // Delete the unnecessary instruction now...
Chris Lattnerfda72b12002-06-25 16:12:52 +0000194 BI = BIL.erase(BI);
Chris Lattner28537df2002-05-07 18:07:59 +0000195}
196
Chris Lattnerdf3c3422004-01-09 06:12:26 +0000197void llvm::ReplaceInstWithInst(BasicBlock::InstListType &BIL,
198 BasicBlock::iterator &BI, Instruction *I) {
Craig Toppere73658d2014-04-28 04:05:08 +0000199 assert(I->getParent() == nullptr &&
Chris Lattner28537df2002-05-07 18:07:59 +0000200 "ReplaceInstWithInst: Instruction already inserted into basic block!");
201
Alexey Samsonov19ffcb92015-06-23 21:00:08 +0000202 // Copy debug location to newly added instruction, if it wasn't already set
203 // by the caller.
204 if (!I->getDebugLoc())
205 I->setDebugLoc(BI->getDebugLoc());
206
Chris Lattner28537df2002-05-07 18:07:59 +0000207 // Insert the new instruction into the basic block...
Chris Lattnerfda72b12002-06-25 16:12:52 +0000208 BasicBlock::iterator New = BIL.insert(BI, I);
Chris Lattner28537df2002-05-07 18:07:59 +0000209
210 // Replace all uses of the old instruction, and delete it.
211 ReplaceInstWithValue(BIL, BI, I);
212
213 // Move BI back to point to the newly inserted instruction
Chris Lattnerfda72b12002-06-25 16:12:52 +0000214 BI = New;
Chris Lattner28537df2002-05-07 18:07:59 +0000215}
216
Chris Lattnerdf3c3422004-01-09 06:12:26 +0000217void llvm::ReplaceInstWithInst(Instruction *From, Instruction *To) {
Chris Lattnerfda72b12002-06-25 16:12:52 +0000218 BasicBlock::iterator BI(From);
219 ReplaceInstWithInst(From->getParent()->getInstList(), BI, To);
Chris Lattner28537df2002-05-07 18:07:59 +0000220}
Chris Lattnerb17274e2002-07-29 22:32:08 +0000221
Chandler Carruthd4500562015-01-19 12:36:53 +0000222BasicBlock *llvm::SplitEdge(BasicBlock *BB, BasicBlock *Succ, DominatorTree *DT,
223 LoopInfo *LI) {
Bob Wilsonaff96b22010-02-16 21:06:42 +0000224 unsigned SuccNum = GetSuccessorNumber(BB, Succ);
Jakub Staszak190db2f2013-01-14 23:16:36 +0000225
Chandler Carruth37df2cf2015-01-19 12:09:11 +0000226 // If this is a critical edge, let SplitCriticalEdge do it.
227 TerminatorInst *LatchTerm = BB->getTerminator();
Chandler Carruthd4500562015-01-19 12:36:53 +0000228 if (SplitCriticalEdge(LatchTerm, SuccNum, CriticalEdgeSplittingOptions(DT, LI)
229 .setPreserveLCSSA()))
Chandler Carruth37df2cf2015-01-19 12:09:11 +0000230 return LatchTerm->getSuccessor(SuccNum);
Chandler Carruth32c52c72015-01-18 02:39:37 +0000231
Devang Pateld7767cc2007-07-06 21:39:20 +0000232 // If the edge isn't critical, then BB has a single successor or Succ has a
233 // single pred. Split the block.
Devang Pateld7767cc2007-07-06 21:39:20 +0000234 if (BasicBlock *SP = Succ->getSinglePredecessor()) {
235 // If the successor only has a single pred, split the top of the successor
236 // block.
237 assert(SP == BB && "CFG broken");
Craig Topperf40110f2014-04-25 05:29:35 +0000238 SP = nullptr;
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +0000239 return SplitBlock(Succ, &Succ->front(), DT, LI);
Devang Pateld7767cc2007-07-06 21:39:20 +0000240 }
Jakub Staszak190db2f2013-01-14 23:16:36 +0000241
Chris Lattner30d95f92011-01-08 18:47:43 +0000242 // Otherwise, if BB has a single successor, split it at the bottom of the
243 // block.
244 assert(BB->getTerminator()->getNumSuccessors() == 1 &&
Jakub Staszak190db2f2013-01-14 23:16:36 +0000245 "Should have a single succ!");
Chandler Carruth32c52c72015-01-18 02:39:37 +0000246 return SplitBlock(BB, BB->getTerminator(), DT, LI);
Devang Pateld7767cc2007-07-06 21:39:20 +0000247}
248
Chandler Carruth37df2cf2015-01-19 12:09:11 +0000249unsigned
250llvm::SplitAllCriticalEdges(Function &F,
251 const CriticalEdgeSplittingOptions &Options) {
Kostya Serebryanye5ea4242014-11-19 00:17:31 +0000252 unsigned NumBroken = 0;
Benjamin Kramer135f7352016-06-26 12:28:59 +0000253 for (BasicBlock &BB : F) {
254 TerminatorInst *TI = BB.getTerminator();
Kostya Serebryanye5ea4242014-11-19 00:17:31 +0000255 if (TI->getNumSuccessors() > 1 && !isa<IndirectBrInst>(TI))
256 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
Chandler Carruth37df2cf2015-01-19 12:09:11 +0000257 if (SplitCriticalEdge(TI, i, Options))
Kostya Serebryanye5ea4242014-11-19 00:17:31 +0000258 ++NumBroken;
259 }
260 return NumBroken;
261}
262
Chandler Carruth32c52c72015-01-18 02:39:37 +0000263BasicBlock *llvm::SplitBlock(BasicBlock *Old, Instruction *SplitPt,
264 DominatorTree *DT, LoopInfo *LI) {
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +0000265 BasicBlock::iterator SplitIt = SplitPt->getIterator();
David Majnemer654e1302015-07-31 17:58:14 +0000266 while (isa<PHINode>(SplitIt) || SplitIt->isEHPad())
Devang Pateld7767cc2007-07-06 21:39:20 +0000267 ++SplitIt;
268 BasicBlock *New = Old->splitBasicBlock(SplitIt, Old->getName()+".split");
269
Dan Gohman3ddbc242009-09-08 15:45:00 +0000270 // The new block lives in whichever loop the old one did. This preserves
271 // LCSSA as well, because we force the split point to be after any PHI nodes.
Chandler Carruth32c52c72015-01-18 02:39:37 +0000272 if (LI)
273 if (Loop *L = LI->getLoopFor(Old))
274 L->addBasicBlockToLoop(New, *LI);
Devang Pateld7767cc2007-07-06 21:39:20 +0000275
Chandler Carruth32c52c72015-01-18 02:39:37 +0000276 if (DT)
Gabor Greif2f5f6962010-09-10 22:25:58 +0000277 // Old dominates New. New node dominates all other nodes dominated by Old.
Chandler Carruth32c52c72015-01-18 02:39:37 +0000278 if (DomTreeNode *OldNode = DT->getNode(Old)) {
Benjamin Kramer135f7352016-06-26 12:28:59 +0000279 std::vector<DomTreeNode *> Children(OldNode->begin(), OldNode->end());
Devang Patel186e0d82007-07-19 02:29:24 +0000280
Chandler Carruth32c52c72015-01-18 02:39:37 +0000281 DomTreeNode *NewNode = DT->addNewBlock(New, Old);
Benjamin Kramer135f7352016-06-26 12:28:59 +0000282 for (DomTreeNode *I : Children)
283 DT->changeImmediateDominator(I, NewNode);
Rafael Espindolad3e65e72011-08-24 18:07:01 +0000284 }
Devang Pateld7767cc2007-07-06 21:39:20 +0000285
Devang Pateld7767cc2007-07-06 21:39:20 +0000286 return New;
287}
Chris Lattnera5b11702008-04-21 01:28:02 +0000288
Sanjay Patel85ce0f12016-04-23 16:31:48 +0000289/// Update DominatorTree, LoopInfo, and LCCSA analysis information.
Bill Wendling60291352011-08-18 17:57:57 +0000290static void UpdateAnalysisInformation(BasicBlock *OldBB, BasicBlock *NewBB,
Bill Wendlingec3823d2011-08-18 20:39:32 +0000291 ArrayRef<BasicBlock *> Preds,
Chandler Carruthb5797b62015-01-18 09:21:15 +0000292 DominatorTree *DT, LoopInfo *LI,
293 bool PreserveLCSSA, bool &HasLoopExit) {
294 // Update dominator tree if available.
295 if (DT)
296 DT->splitBlock(NewBB);
Bill Wendling0a693f42011-08-18 05:25:23 +0000297
Chandler Carruthb5797b62015-01-18 09:21:15 +0000298 // The rest of the logic is only relevant for updating the loop structures.
299 if (!LI)
300 return;
301
302 Loop *L = LI->getLoopFor(OldBB);
Bill Wendling0a693f42011-08-18 05:25:23 +0000303
304 // If we need to preserve loop analyses, collect some information about how
305 // this split will affect loops.
306 bool IsLoopEntry = !!L;
307 bool SplitMakesNewLoopHeader = false;
Benjamin Kramer135f7352016-06-26 12:28:59 +0000308 for (BasicBlock *Pred : Preds) {
Chandler Carruthb5797b62015-01-18 09:21:15 +0000309 // If we need to preserve LCSSA, determine if any of the preds is a loop
310 // exit.
311 if (PreserveLCSSA)
312 if (Loop *PL = LI->getLoopFor(Pred))
313 if (!PL->contains(OldBB))
314 HasLoopExit = true;
Bill Wendling0a693f42011-08-18 05:25:23 +0000315
Chandler Carruthb5797b62015-01-18 09:21:15 +0000316 // If we need to preserve LoopInfo, note whether any of the preds crosses
317 // an interesting loop boundary.
318 if (!L)
319 continue;
320 if (L->contains(Pred))
321 IsLoopEntry = false;
322 else
323 SplitMakesNewLoopHeader = true;
Bill Wendling0a693f42011-08-18 05:25:23 +0000324 }
325
Chandler Carruthb5797b62015-01-18 09:21:15 +0000326 // Unless we have a loop for OldBB, nothing else to do here.
327 if (!L)
328 return;
Bill Wendling0a693f42011-08-18 05:25:23 +0000329
330 if (IsLoopEntry) {
331 // Add the new block to the nearest enclosing loop (and not an adjacent
332 // loop). To find this, examine each of the predecessors and determine which
333 // loops enclose them, and select the most-nested loop which contains the
334 // loop containing the block being split.
Craig Topperf40110f2014-04-25 05:29:35 +0000335 Loop *InnermostPredLoop = nullptr;
Benjamin Kramer135f7352016-06-26 12:28:59 +0000336 for (BasicBlock *Pred : Preds) {
Bill Wendlingec3823d2011-08-18 20:39:32 +0000337 if (Loop *PredLoop = LI->getLoopFor(Pred)) {
Bill Wendling0a693f42011-08-18 05:25:23 +0000338 // Seek a loop which actually contains the block being split (to avoid
339 // adjacent loops).
340 while (PredLoop && !PredLoop->contains(OldBB))
341 PredLoop = PredLoop->getParentLoop();
342
343 // Select the most-nested of these loops which contains the block.
344 if (PredLoop && PredLoop->contains(OldBB) &&
345 (!InnermostPredLoop ||
346 InnermostPredLoop->getLoopDepth() < PredLoop->getLoopDepth()))
347 InnermostPredLoop = PredLoop;
348 }
Bill Wendlingec3823d2011-08-18 20:39:32 +0000349 }
Bill Wendling0a693f42011-08-18 05:25:23 +0000350
351 if (InnermostPredLoop)
Chandler Carruth691addc2015-01-18 01:25:51 +0000352 InnermostPredLoop->addBasicBlockToLoop(NewBB, *LI);
Bill Wendling0a693f42011-08-18 05:25:23 +0000353 } else {
Chandler Carruth691addc2015-01-18 01:25:51 +0000354 L->addBasicBlockToLoop(NewBB, *LI);
Bill Wendling0a693f42011-08-18 05:25:23 +0000355 if (SplitMakesNewLoopHeader)
356 L->moveToHeader(NewBB);
357 }
358}
359
Sanjay Patel85ce0f12016-04-23 16:31:48 +0000360/// Update the PHI nodes in OrigBB to include the values coming from NewBB.
361/// This also updates AliasAnalysis, if available.
Bill Wendlingb267e2a2011-08-18 20:51:04 +0000362static void UpdatePHINodes(BasicBlock *OrigBB, BasicBlock *NewBB,
Chandler Carruthb5797b62015-01-18 09:21:15 +0000363 ArrayRef<BasicBlock *> Preds, BranchInst *BI,
Chandler Carruth96ada252015-07-22 09:52:54 +0000364 bool HasLoopExit) {
Bill Wendlingb267e2a2011-08-18 20:51:04 +0000365 // Otherwise, create a new PHI node in NewBB for each PHI node in OrigBB.
Chandler Carruth5bdf72c2014-04-28 10:37:30 +0000366 SmallPtrSet<BasicBlock *, 16> PredSet(Preds.begin(), Preds.end());
Bill Wendlingb267e2a2011-08-18 20:51:04 +0000367 for (BasicBlock::iterator I = OrigBB->begin(); isa<PHINode>(I); ) {
368 PHINode *PN = cast<PHINode>(I++);
369
370 // Check to see if all of the values coming in are the same. If so, we
371 // don't need to create a new PHI node, unless it's needed for LCSSA.
Craig Topperf40110f2014-04-25 05:29:35 +0000372 Value *InVal = nullptr;
Bill Wendlingb267e2a2011-08-18 20:51:04 +0000373 if (!HasLoopExit) {
374 InVal = PN->getIncomingValueForBlock(Preds[0]);
Chandler Carruth5bdf72c2014-04-28 10:37:30 +0000375 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
376 if (!PredSet.count(PN->getIncomingBlock(i)))
377 continue;
378 if (!InVal)
379 InVal = PN->getIncomingValue(i);
380 else if (InVal != PN->getIncomingValue(i)) {
Craig Topperf40110f2014-04-25 05:29:35 +0000381 InVal = nullptr;
Bill Wendlingb267e2a2011-08-18 20:51:04 +0000382 break;
383 }
Chandler Carruth5bdf72c2014-04-28 10:37:30 +0000384 }
Bill Wendlingb267e2a2011-08-18 20:51:04 +0000385 }
386
387 if (InVal) {
388 // If all incoming values for the new PHI would be the same, just don't
389 // make a new PHI. Instead, just remove the incoming values from the old
390 // PHI.
Jakub Staszak190db2f2013-01-14 23:16:36 +0000391
Chandler Carruth5bdf72c2014-04-28 10:37:30 +0000392 // NOTE! This loop walks backwards for a reason! First off, this minimizes
393 // the cost of removal if we end up removing a large number of values, and
394 // second off, this ensures that the indices for the incoming values
395 // aren't invalidated when we remove one.
396 for (int64_t i = PN->getNumIncomingValues() - 1; i >= 0; --i)
397 if (PredSet.count(PN->getIncomingBlock(i)))
398 PN->removeIncomingValue(i, false);
Bill Wendlingb267e2a2011-08-18 20:51:04 +0000399
Chandler Carruth5bdf72c2014-04-28 10:37:30 +0000400 // Add an incoming value to the PHI node in the loop for the preheader
401 // edge.
402 PN->addIncoming(InVal, NewBB);
403 continue;
Bill Wendlingb267e2a2011-08-18 20:51:04 +0000404 }
405
Chandler Carruth5bdf72c2014-04-28 10:37:30 +0000406 // If the values coming into the block are not the same, we need a new
407 // PHI.
408 // Create the new PHI node, insert it into NewBB at the end of the block
409 PHINode *NewPHI =
410 PHINode::Create(PN->getType(), Preds.size(), PN->getName() + ".ph", BI);
Chandler Carruth5bdf72c2014-04-28 10:37:30 +0000411
412 // NOTE! This loop walks backwards for a reason! First off, this minimizes
413 // the cost of removal if we end up removing a large number of values, and
414 // second off, this ensures that the indices for the incoming values aren't
415 // invalidated when we remove one.
416 for (int64_t i = PN->getNumIncomingValues() - 1; i >= 0; --i) {
417 BasicBlock *IncomingBB = PN->getIncomingBlock(i);
418 if (PredSet.count(IncomingBB)) {
419 Value *V = PN->removeIncomingValue(i, false);
420 NewPHI->addIncoming(V, IncomingBB);
421 }
422 }
423
424 PN->addIncoming(NewPHI, NewBB);
Bill Wendlingb267e2a2011-08-18 20:51:04 +0000425 }
426}
427
Jakub Staszak190db2f2013-01-14 23:16:36 +0000428BasicBlock *llvm::SplitBlockPredecessors(BasicBlock *BB,
Chandler Carruthb5797b62015-01-18 09:21:15 +0000429 ArrayRef<BasicBlock *> Preds,
Chandler Carruth96ada252015-07-22 09:52:54 +0000430 const char *Suffix, DominatorTree *DT,
431 LoopInfo *LI, bool PreserveLCSSA) {
David Majnemer654e1302015-07-31 17:58:14 +0000432 // Do not attempt to split that which cannot be split.
433 if (!BB->canSplitPredecessors())
434 return nullptr;
435
Philip Reames9198b332015-01-28 23:06:47 +0000436 // For the landingpads we need to act a bit differently.
437 // Delegate this work to the SplitLandingPadPredecessors.
438 if (BB->isLandingPad()) {
439 SmallVector<BasicBlock*, 2> NewBBs;
440 std::string NewName = std::string(Suffix) + ".split-lp";
441
Chandler Carruth96ada252015-07-22 09:52:54 +0000442 SplitLandingPadPredecessors(BB, Preds, Suffix, NewName.c_str(), NewBBs, DT,
443 LI, PreserveLCSSA);
Philip Reames9198b332015-01-28 23:06:47 +0000444 return NewBBs[0];
445 }
446
Chris Lattnera5b11702008-04-21 01:28:02 +0000447 // Create new basic block, insert right before the original block.
Alexey Samsonovb7f02d32015-06-09 22:10:29 +0000448 BasicBlock *NewBB = BasicBlock::Create(
449 BB->getContext(), BB->getName() + Suffix, BB->getParent(), BB);
Jakub Staszak190db2f2013-01-14 23:16:36 +0000450
Chris Lattnera5b11702008-04-21 01:28:02 +0000451 // The new block unconditionally branches to the old block.
452 BranchInst *BI = BranchInst::Create(BB, NewBB);
Taewook Oh2e945eb2017-02-14 21:10:40 +0000453 BI->setDebugLoc(BB->getFirstNonPHIOrDbg()->getDebugLoc());
Jakub Staszak190db2f2013-01-14 23:16:36 +0000454
Chris Lattnera5b11702008-04-21 01:28:02 +0000455 // Move the edges from Preds to point to NewBB instead of BB.
Jakub Staszakf5b32e52011-12-09 21:19:53 +0000456 for (unsigned i = 0, e = Preds.size(); i != e; ++i) {
Dan Gohman00c79382009-11-05 18:25:44 +0000457 // This is slightly more strict than necessary; the minimum requirement
458 // is that there be no more than one indirectbr branching to BB. And
459 // all BlockAddress uses would need to be updated.
460 assert(!isa<IndirectBrInst>(Preds[i]->getTerminator()) &&
461 "Cannot split an edge from an IndirectBrInst");
Chris Lattnera5b11702008-04-21 01:28:02 +0000462 Preds[i]->getTerminator()->replaceUsesOfWith(BB, NewBB);
Dan Gohman3ddbc242009-09-08 15:45:00 +0000463 }
464
Chris Lattnera5b11702008-04-21 01:28:02 +0000465 // Insert a new PHI node into NewBB for every PHI node in BB and that new PHI
466 // node becomes an incoming value for BB's phi node. However, if the Preds
467 // list is empty, we need to insert dummy entries into the PHI nodes in BB to
468 // account for the newly created predecessor.
Eugene Zelenko57bd5a02017-10-27 01:09:08 +0000469 if (Preds.empty()) {
Chris Lattnera5b11702008-04-21 01:28:02 +0000470 // Insert dummy values as the incoming value.
471 for (BasicBlock::iterator I = BB->begin(); isa<PHINode>(I); ++I)
Owen Andersonb292b8c2009-07-30 23:03:37 +0000472 cast<PHINode>(I)->addIncoming(UndefValue::get(I->getType()), NewBB);
Chris Lattnera5b11702008-04-21 01:28:02 +0000473 return NewBB;
474 }
Dan Gohman3ddbc242009-09-08 15:45:00 +0000475
Bill Wendling0a693f42011-08-18 05:25:23 +0000476 // Update DominatorTree, LoopInfo, and LCCSA analysis information.
477 bool HasLoopExit = false;
Chandler Carruthb5797b62015-01-18 09:21:15 +0000478 UpdateAnalysisInformation(BB, NewBB, Preds, DT, LI, PreserveLCSSA,
479 HasLoopExit);
Dan Gohman3ddbc242009-09-08 15:45:00 +0000480
Bill Wendlingb267e2a2011-08-18 20:51:04 +0000481 // Update the PHI nodes in BB with the values coming from NewBB.
Chandler Carruth96ada252015-07-22 09:52:54 +0000482 UpdatePHINodes(BB, NewBB, Preds, BI, HasLoopExit);
Chris Lattnera5b11702008-04-21 01:28:02 +0000483 return NewBB;
484}
Chris Lattner72f16e72008-11-27 08:10:05 +0000485
Bill Wendlingca7d3092011-08-19 00:05:40 +0000486void llvm::SplitLandingPadPredecessors(BasicBlock *OrigBB,
Chandler Carruth0eae1122015-01-19 03:03:39 +0000487 ArrayRef<BasicBlock *> Preds,
Bill Wendlingca7d3092011-08-19 00:05:40 +0000488 const char *Suffix1, const char *Suffix2,
Chandler Carruth0eae1122015-01-19 03:03:39 +0000489 SmallVectorImpl<BasicBlock *> &NewBBs,
Chandler Carruth96ada252015-07-22 09:52:54 +0000490 DominatorTree *DT, LoopInfo *LI,
491 bool PreserveLCSSA) {
Bill Wendlingca7d3092011-08-19 00:05:40 +0000492 assert(OrigBB->isLandingPad() && "Trying to split a non-landing pad!");
493
494 // Create a new basic block for OrigBB's predecessors listed in Preds. Insert
495 // it right before the original block.
496 BasicBlock *NewBB1 = BasicBlock::Create(OrigBB->getContext(),
497 OrigBB->getName() + Suffix1,
498 OrigBB->getParent(), OrigBB);
499 NewBBs.push_back(NewBB1);
500
501 // The new block unconditionally branches to the old block.
502 BranchInst *BI1 = BranchInst::Create(OrigBB, NewBB1);
Alexey Samsonovb7f02d32015-06-09 22:10:29 +0000503 BI1->setDebugLoc(OrigBB->getFirstNonPHI()->getDebugLoc());
Bill Wendlingca7d3092011-08-19 00:05:40 +0000504
505 // Move the edges from Preds to point to NewBB1 instead of OrigBB.
506 for (unsigned i = 0, e = Preds.size(); i != e; ++i) {
507 // This is slightly more strict than necessary; the minimum requirement
508 // is that there be no more than one indirectbr branching to BB. And
509 // all BlockAddress uses would need to be updated.
510 assert(!isa<IndirectBrInst>(Preds[i]->getTerminator()) &&
511 "Cannot split an edge from an IndirectBrInst");
512 Preds[i]->getTerminator()->replaceUsesOfWith(OrigBB, NewBB1);
513 }
514
Bill Wendlingca7d3092011-08-19 00:05:40 +0000515 bool HasLoopExit = false;
Chandler Carruthb5797b62015-01-18 09:21:15 +0000516 UpdateAnalysisInformation(OrigBB, NewBB1, Preds, DT, LI, PreserveLCSSA,
517 HasLoopExit);
Bill Wendlingca7d3092011-08-19 00:05:40 +0000518
519 // Update the PHI nodes in OrigBB with the values coming from NewBB1.
Chandler Carruth96ada252015-07-22 09:52:54 +0000520 UpdatePHINodes(OrigBB, NewBB1, Preds, BI1, HasLoopExit);
Bill Wendlingca7d3092011-08-19 00:05:40 +0000521
Bill Wendlingca7d3092011-08-19 00:05:40 +0000522 // Move the remaining edges from OrigBB to point to NewBB2.
523 SmallVector<BasicBlock*, 8> NewBB2Preds;
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +0000524 for (pred_iterator i = pred_begin(OrigBB), e = pred_end(OrigBB);
525 i != e; ) {
526 BasicBlock *Pred = *i++;
Bill Wendling38d81302011-08-19 23:46:30 +0000527 if (Pred == NewBB1) continue;
Bill Wendlingca7d3092011-08-19 00:05:40 +0000528 assert(!isa<IndirectBrInst>(Pred->getTerminator()) &&
529 "Cannot split an edge from an IndirectBrInst");
Bill Wendlingca7d3092011-08-19 00:05:40 +0000530 NewBB2Preds.push_back(Pred);
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +0000531 e = pred_end(OrigBB);
Bill Wendlingca7d3092011-08-19 00:05:40 +0000532 }
533
Craig Topperf40110f2014-04-25 05:29:35 +0000534 BasicBlock *NewBB2 = nullptr;
Bill Wendling38d81302011-08-19 23:46:30 +0000535 if (!NewBB2Preds.empty()) {
536 // Create another basic block for the rest of OrigBB's predecessors.
537 NewBB2 = BasicBlock::Create(OrigBB->getContext(),
538 OrigBB->getName() + Suffix2,
539 OrigBB->getParent(), OrigBB);
540 NewBBs.push_back(NewBB2);
Bill Wendlingca7d3092011-08-19 00:05:40 +0000541
Bill Wendling38d81302011-08-19 23:46:30 +0000542 // The new block unconditionally branches to the old block.
543 BranchInst *BI2 = BranchInst::Create(OrigBB, NewBB2);
Alexey Samsonovb7f02d32015-06-09 22:10:29 +0000544 BI2->setDebugLoc(OrigBB->getFirstNonPHI()->getDebugLoc());
Bill Wendling38d81302011-08-19 23:46:30 +0000545
546 // Move the remaining edges from OrigBB to point to NewBB2.
Benjamin Kramer135f7352016-06-26 12:28:59 +0000547 for (BasicBlock *NewBB2Pred : NewBB2Preds)
548 NewBB2Pred->getTerminator()->replaceUsesOfWith(OrigBB, NewBB2);
Bill Wendling38d81302011-08-19 23:46:30 +0000549
550 // Update DominatorTree, LoopInfo, and LCCSA analysis information.
551 HasLoopExit = false;
Chandler Carruthb5797b62015-01-18 09:21:15 +0000552 UpdateAnalysisInformation(OrigBB, NewBB2, NewBB2Preds, DT, LI,
553 PreserveLCSSA, HasLoopExit);
Bill Wendling38d81302011-08-19 23:46:30 +0000554
555 // Update the PHI nodes in OrigBB with the values coming from NewBB2.
Chandler Carruth96ada252015-07-22 09:52:54 +0000556 UpdatePHINodes(OrigBB, NewBB2, NewBB2Preds, BI2, HasLoopExit);
Bill Wendling38d81302011-08-19 23:46:30 +0000557 }
Bill Wendlingca7d3092011-08-19 00:05:40 +0000558
559 LandingPadInst *LPad = OrigBB->getLandingPadInst();
560 Instruction *Clone1 = LPad->clone();
561 Clone1->setName(Twine("lpad") + Suffix1);
562 NewBB1->getInstList().insert(NewBB1->getFirstInsertionPt(), Clone1);
563
Bill Wendling38d81302011-08-19 23:46:30 +0000564 if (NewBB2) {
565 Instruction *Clone2 = LPad->clone();
566 Clone2->setName(Twine("lpad") + Suffix2);
567 NewBB2->getInstList().insert(NewBB2->getFirstInsertionPt(), Clone2);
Bill Wendlingca7d3092011-08-19 00:05:40 +0000568
Chen Li78bde832016-01-06 20:32:05 +0000569 // Create a PHI node for the two cloned landingpad instructions only
570 // if the original landingpad instruction has some uses.
571 if (!LPad->use_empty()) {
572 assert(!LPad->getType()->isTokenTy() &&
573 "Split cannot be applied if LPad is token type. Otherwise an "
574 "invalid PHINode of token type would be created.");
575 PHINode *PN = PHINode::Create(LPad->getType(), 2, "lpad.phi", LPad);
576 PN->addIncoming(Clone1, NewBB1);
577 PN->addIncoming(Clone2, NewBB2);
578 LPad->replaceAllUsesWith(PN);
579 }
Bill Wendling38d81302011-08-19 23:46:30 +0000580 LPad->eraseFromParent();
581 } else {
582 // There is no second clone. Just replace the landing pad with the first
583 // clone.
584 LPad->replaceAllUsesWith(Clone1);
585 LPad->eraseFromParent();
586 }
Bill Wendlingca7d3092011-08-19 00:05:40 +0000587}
588
Evan Chengd983eba2011-01-29 04:46:23 +0000589ReturnInst *llvm::FoldReturnIntoUncondBranch(ReturnInst *RI, BasicBlock *BB,
590 BasicBlock *Pred) {
591 Instruction *UncondBranch = Pred->getTerminator();
592 // Clone the return and add it to the end of the predecessor.
593 Instruction *NewRet = RI->clone();
594 Pred->getInstList().push_back(NewRet);
Jakub Staszak190db2f2013-01-14 23:16:36 +0000595
Evan Chengd983eba2011-01-29 04:46:23 +0000596 // If the return instruction returns a value, and if the value was a
597 // PHI node in "BB", propagate the right value into the return.
598 for (User::op_iterator i = NewRet->op_begin(), e = NewRet->op_end();
Evan Cheng249716e2012-07-27 21:21:26 +0000599 i != e; ++i) {
600 Value *V = *i;
Craig Topperf40110f2014-04-25 05:29:35 +0000601 Instruction *NewBC = nullptr;
Evan Cheng249716e2012-07-27 21:21:26 +0000602 if (BitCastInst *BCI = dyn_cast<BitCastInst>(V)) {
603 // Return value might be bitcasted. Clone and insert it before the
604 // return instruction.
605 V = BCI->getOperand(0);
606 NewBC = BCI->clone();
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +0000607 Pred->getInstList().insert(NewRet->getIterator(), NewBC);
Evan Cheng249716e2012-07-27 21:21:26 +0000608 *i = NewBC;
609 }
610 if (PHINode *PN = dyn_cast<PHINode>(V)) {
611 if (PN->getParent() == BB) {
612 if (NewBC)
613 NewBC->setOperand(0, PN->getIncomingValueForBlock(Pred));
614 else
615 *i = PN->getIncomingValueForBlock(Pred);
616 }
617 }
618 }
Jakub Staszak190db2f2013-01-14 23:16:36 +0000619
Evan Chengd983eba2011-01-29 04:46:23 +0000620 // Update any PHI nodes in the returning block to realize that we no
621 // longer branch to them.
622 BB->removePredecessor(Pred);
623 UncondBranch->eraseFromParent();
624 return cast<ReturnInst>(NewRet);
Chris Lattner351134b2009-05-04 02:25:58 +0000625}
Devang Patela8e74112011-04-29 22:28:59 +0000626
Adam Nemetfdb20592016-03-15 18:06:20 +0000627TerminatorInst *
628llvm::SplitBlockAndInsertIfThen(Value *Cond, Instruction *SplitBefore,
629 bool Unreachable, MDNode *BranchWeights,
630 DominatorTree *DT, LoopInfo *LI) {
Evgeniy Stepanov8eb77d82012-10-19 10:48:31 +0000631 BasicBlock *Head = SplitBefore->getParent();
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +0000632 BasicBlock *Tail = Head->splitBasicBlock(SplitBefore->getIterator());
Evgeniy Stepanov8eb77d82012-10-19 10:48:31 +0000633 TerminatorInst *HeadOldTerm = Head->getTerminator();
634 LLVMContext &C = Head->getContext();
635 BasicBlock *ThenBlock = BasicBlock::Create(C, "", Head->getParent(), Tail);
636 TerminatorInst *CheckTerm;
637 if (Unreachable)
638 CheckTerm = new UnreachableInst(C, ThenBlock);
639 else
640 CheckTerm = BranchInst::Create(Tail, ThenBlock);
Evgeniy Stepanov2275a012014-03-19 12:56:38 +0000641 CheckTerm->setDebugLoc(SplitBefore->getDebugLoc());
Evgeniy Stepanov8eb77d82012-10-19 10:48:31 +0000642 BranchInst *HeadNewTerm =
Evgeniy Stepanova9164e92013-12-19 13:29:56 +0000643 BranchInst::Create(/*ifTrue*/ThenBlock, /*ifFalse*/Tail, Cond);
Evgeniy Stepanov8eb77d82012-10-19 10:48:31 +0000644 HeadNewTerm->setMetadata(LLVMContext::MD_prof, BranchWeights);
645 ReplaceInstWithInst(HeadOldTerm, HeadNewTerm);
Peter Collingbourne818f5c42014-07-15 04:40:27 +0000646
647 if (DT) {
648 if (DomTreeNode *OldNode = DT->getNode(Head)) {
649 std::vector<DomTreeNode *> Children(OldNode->begin(), OldNode->end());
650
651 DomTreeNode *NewNode = DT->addNewBlock(Tail, Head);
Benjamin Kramer135f7352016-06-26 12:28:59 +0000652 for (DomTreeNode *Child : Children)
Peter Collingbourne818f5c42014-07-15 04:40:27 +0000653 DT->changeImmediateDominator(Child, NewNode);
654
655 // Head dominates ThenBlock.
656 DT->addNewBlock(ThenBlock, Head);
657 }
658 }
659
Adam Nemetfdb20592016-03-15 18:06:20 +0000660 if (LI) {
Michael Kruse811de8a2017-03-06 15:33:05 +0000661 if (Loop *L = LI->getLoopFor(Head)) {
662 L->addBasicBlockToLoop(ThenBlock, *LI);
663 L->addBasicBlockToLoop(Tail, *LI);
664 }
Adam Nemetfdb20592016-03-15 18:06:20 +0000665 }
666
Evgeniy Stepanov8eb77d82012-10-19 10:48:31 +0000667 return CheckTerm;
668}
Tom Stellardaa664d92013-08-06 02:43:45 +0000669
Kostya Serebryany530e2072013-12-23 14:15:08 +0000670void llvm::SplitBlockAndInsertIfThenElse(Value *Cond, Instruction *SplitBefore,
671 TerminatorInst **ThenTerm,
672 TerminatorInst **ElseTerm,
673 MDNode *BranchWeights) {
674 BasicBlock *Head = SplitBefore->getParent();
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +0000675 BasicBlock *Tail = Head->splitBasicBlock(SplitBefore->getIterator());
Kostya Serebryany530e2072013-12-23 14:15:08 +0000676 TerminatorInst *HeadOldTerm = Head->getTerminator();
677 LLVMContext &C = Head->getContext();
678 BasicBlock *ThenBlock = BasicBlock::Create(C, "", Head->getParent(), Tail);
679 BasicBlock *ElseBlock = BasicBlock::Create(C, "", Head->getParent(), Tail);
680 *ThenTerm = BranchInst::Create(Tail, ThenBlock);
Evgeniy Stepanov2275a012014-03-19 12:56:38 +0000681 (*ThenTerm)->setDebugLoc(SplitBefore->getDebugLoc());
Kostya Serebryany530e2072013-12-23 14:15:08 +0000682 *ElseTerm = BranchInst::Create(Tail, ElseBlock);
Evgeniy Stepanov2275a012014-03-19 12:56:38 +0000683 (*ElseTerm)->setDebugLoc(SplitBefore->getDebugLoc());
Kostya Serebryany530e2072013-12-23 14:15:08 +0000684 BranchInst *HeadNewTerm =
685 BranchInst::Create(/*ifTrue*/ThenBlock, /*ifFalse*/ElseBlock, Cond);
686 HeadNewTerm->setMetadata(LLVMContext::MD_prof, BranchWeights);
687 ReplaceInstWithInst(HeadOldTerm, HeadNewTerm);
688}
689
Tom Stellardaa664d92013-08-06 02:43:45 +0000690Value *llvm::GetIfCondition(BasicBlock *BB, BasicBlock *&IfTrue,
691 BasicBlock *&IfFalse) {
692 PHINode *SomePHI = dyn_cast<PHINode>(BB->begin());
Craig Topperf40110f2014-04-25 05:29:35 +0000693 BasicBlock *Pred1 = nullptr;
694 BasicBlock *Pred2 = nullptr;
Tom Stellardaa664d92013-08-06 02:43:45 +0000695
696 if (SomePHI) {
697 if (SomePHI->getNumIncomingValues() != 2)
Craig Topperf40110f2014-04-25 05:29:35 +0000698 return nullptr;
Tom Stellardaa664d92013-08-06 02:43:45 +0000699 Pred1 = SomePHI->getIncomingBlock(0);
700 Pred2 = SomePHI->getIncomingBlock(1);
701 } else {
702 pred_iterator PI = pred_begin(BB), PE = pred_end(BB);
703 if (PI == PE) // No predecessor
Craig Topperf40110f2014-04-25 05:29:35 +0000704 return nullptr;
Tom Stellardaa664d92013-08-06 02:43:45 +0000705 Pred1 = *PI++;
706 if (PI == PE) // Only one predecessor
Craig Topperf40110f2014-04-25 05:29:35 +0000707 return nullptr;
Tom Stellardaa664d92013-08-06 02:43:45 +0000708 Pred2 = *PI++;
709 if (PI != PE) // More than two predecessors
Craig Topperf40110f2014-04-25 05:29:35 +0000710 return nullptr;
Tom Stellardaa664d92013-08-06 02:43:45 +0000711 }
712
713 // We can only handle branches. Other control flow will be lowered to
714 // branches if possible anyway.
715 BranchInst *Pred1Br = dyn_cast<BranchInst>(Pred1->getTerminator());
716 BranchInst *Pred2Br = dyn_cast<BranchInst>(Pred2->getTerminator());
Craig Topperf40110f2014-04-25 05:29:35 +0000717 if (!Pred1Br || !Pred2Br)
718 return nullptr;
Tom Stellardaa664d92013-08-06 02:43:45 +0000719
720 // Eliminate code duplication by ensuring that Pred1Br is conditional if
721 // either are.
722 if (Pred2Br->isConditional()) {
723 // If both branches are conditional, we don't have an "if statement". In
724 // reality, we could transform this case, but since the condition will be
725 // required anyway, we stand no chance of eliminating it, so the xform is
726 // probably not profitable.
727 if (Pred1Br->isConditional())
Craig Topperf40110f2014-04-25 05:29:35 +0000728 return nullptr;
Tom Stellardaa664d92013-08-06 02:43:45 +0000729
730 std::swap(Pred1, Pred2);
731 std::swap(Pred1Br, Pred2Br);
732 }
733
734 if (Pred1Br->isConditional()) {
735 // The only thing we have to watch out for here is to make sure that Pred2
736 // doesn't have incoming edges from other blocks. If it does, the condition
737 // doesn't dominate BB.
Craig Topperf40110f2014-04-25 05:29:35 +0000738 if (!Pred2->getSinglePredecessor())
739 return nullptr;
Tom Stellardaa664d92013-08-06 02:43:45 +0000740
741 // If we found a conditional branch predecessor, make sure that it branches
742 // to BB and Pred2Br. If it doesn't, this isn't an "if statement".
743 if (Pred1Br->getSuccessor(0) == BB &&
744 Pred1Br->getSuccessor(1) == Pred2) {
745 IfTrue = Pred1;
746 IfFalse = Pred2;
747 } else if (Pred1Br->getSuccessor(0) == Pred2 &&
748 Pred1Br->getSuccessor(1) == BB) {
749 IfTrue = Pred2;
750 IfFalse = Pred1;
751 } else {
752 // We know that one arm of the conditional goes to BB, so the other must
753 // go somewhere unrelated, and this must not be an "if statement".
Craig Topperf40110f2014-04-25 05:29:35 +0000754 return nullptr;
Tom Stellardaa664d92013-08-06 02:43:45 +0000755 }
756
757 return Pred1Br->getCondition();
758 }
759
760 // Ok, if we got here, both predecessors end with an unconditional branch to
761 // BB. Don't panic! If both blocks only have a single (identical)
762 // predecessor, and THAT is a conditional branch, then we're all ok!
763 BasicBlock *CommonPred = Pred1->getSinglePredecessor();
Craig Topperf40110f2014-04-25 05:29:35 +0000764 if (CommonPred == nullptr || CommonPred != Pred2->getSinglePredecessor())
765 return nullptr;
Tom Stellardaa664d92013-08-06 02:43:45 +0000766
767 // Otherwise, if this is a conditional branch, then we can use it!
768 BranchInst *BI = dyn_cast<BranchInst>(CommonPred->getTerminator());
Craig Topperf40110f2014-04-25 05:29:35 +0000769 if (!BI) return nullptr;
Tom Stellardaa664d92013-08-06 02:43:45 +0000770
771 assert(BI->isConditional() && "Two successors but not conditional?");
772 if (BI->getSuccessor(0) == Pred1) {
773 IfTrue = Pred1;
774 IfFalse = Pred2;
775 } else {
776 IfTrue = Pred2;
777 IfFalse = Pred1;
778 }
779 return BI->getCondition();
780}