blob: f0097d0362c3328cde2adea5fb5fa7661dd48878 [file] [log] [blame]
Chris Lattner4d1e46e2002-05-07 18:07:59 +00001//===-- Local.cpp - Functions to perform local transformations ------------===//
Misha Brukmanfd939082005-04-21 23:48:37 +00002//
John Criswellb576c942003-10-20 19:43:21 +00003// The LLVM Compiler Infrastructure
4//
Chris Lattner4ee451d2007-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 Brukmanfd939082005-04-21 23:48:37 +00007//
John Criswellb576c942003-10-20 19:43:21 +00008//===----------------------------------------------------------------------===//
Chris Lattner4d1e46e2002-05-07 18:07:59 +00009//
10// This family of functions perform various local transformations to the
11// program.
12//
13//===----------------------------------------------------------------------===//
14
15#include "llvm/Transforms/Utils/Local.h"
Chris Lattner81ebc302004-01-12 18:35:03 +000016#include "llvm/Constants.h"
Chris Lattner6cc8a932009-06-16 17:23:12 +000017#include "llvm/GlobalAlias.h"
Devang Patelc79e1182009-03-06 00:19:37 +000018#include "llvm/GlobalVariable.h"
Chris Lattnerc5f52e62005-09-26 05:27:10 +000019#include "llvm/DerivedTypes.h"
Chris Lattner7822c2a2004-01-12 19:56:36 +000020#include "llvm/Instructions.h"
Chris Lattnercf110352004-06-11 06:16:23 +000021#include "llvm/Intrinsics.h"
Chris Lattner741c0ae2007-12-29 00:59:12 +000022#include "llvm/IntrinsicInst.h"
Chris Lattner19f2dc42009-12-29 09:12:29 +000023#include "llvm/ADT/DenseMap.h"
Dan Gohmanafc36a92009-05-02 18:29:22 +000024#include "llvm/ADT/SmallPtrSet.h"
Chris Lattnercbbc6b72005-10-27 16:34:00 +000025#include "llvm/Analysis/ConstantFolding.h"
Chris Lattner40d8c282009-11-10 22:26:15 +000026#include "llvm/Analysis/InstructionSimplify.h"
Andreas Neustifterad809812009-09-16 09:26:52 +000027#include "llvm/Analysis/ProfileInfo.h"
Chris Lattner9fa038d2007-01-30 23:13:49 +000028#include "llvm/Target/TargetData.h"
Chris Lattnerdce94d92009-11-10 05:59:26 +000029#include "llvm/Support/CFG.h"
30#include "llvm/Support/Debug.h"
Chris Lattnerc5f52e62005-09-26 05:27:10 +000031#include "llvm/Support/GetElementPtrTypeIterator.h"
32#include "llvm/Support/MathExtras.h"
Chris Lattner19f2dc42009-12-29 09:12:29 +000033#include "llvm/Support/ValueHandle.h"
Chris Lattnerdce94d92009-11-10 05:59:26 +000034#include "llvm/Support/raw_ostream.h"
Chris Lattnerabbc2dd2003-12-19 05:56:28 +000035using namespace llvm;
Brian Gaeked0fde302003-11-11 22:41:34 +000036
Chris Lattner4d1e46e2002-05-07 18:07:59 +000037//===----------------------------------------------------------------------===//
Chris Lattner6cc8a932009-06-16 17:23:12 +000038// Local analysis.
39//
40
Bob Wilson3eb4f7e2010-01-29 19:19:08 +000041/// getUnderlyingObjectWithOffset - Strip off up to MaxLookup GEPs and
42/// bitcasts to get back to the underlying object being addressed, keeping
43/// track of the offset in bytes from the GEPs relative to the result.
44/// This is closely related to Value::getUnderlyingObject but is located
45/// here to avoid making VMCore depend on TargetData.
46static Value *getUnderlyingObjectWithOffset(Value *V, const TargetData *TD,
47 unsigned &ByteOffset,
48 unsigned MaxLookup = 6) {
49 if (!isa<PointerType>(V->getType()))
50 return V;
51 for (unsigned Count = 0; MaxLookup == 0 || Count < MaxLookup; ++Count) {
52 if (GEPOperator *GEP = dyn_cast<GEPOperator>(V)) {
53 if (!GEP->hasAllConstantIndices())
54 return V;
55 SmallVector<Value*, 8> Indices(GEP->op_begin() + 1, GEP->op_end());
56 ByteOffset += TD->getIndexedOffset(GEP->getPointerOperandType(),
57 &Indices[0], Indices.size());
58 V = GEP->getPointerOperand();
59 } else if (Operator::getOpcode(V) == Instruction::BitCast) {
60 V = cast<Operator>(V)->getOperand(0);
61 } else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) {
62 if (GA->mayBeOverridden())
63 return V;
64 V = GA->getAliasee();
65 } else {
66 return V;
67 }
68 assert(isa<PointerType>(V->getType()) && "Unexpected operand type!");
69 }
70 return V;
71}
72
Chris Lattner6cc8a932009-06-16 17:23:12 +000073/// isSafeToLoadUnconditionally - Return true if we know that executing a load
74/// from this value cannot trap. If it is not obviously safe to load from the
75/// specified pointer, we do a quick local scan of the basic block containing
76/// ScanFrom, to determine if the address is already accessed.
Bob Wilson3eb4f7e2010-01-29 19:19:08 +000077bool llvm::isSafeToLoadUnconditionally(Value *V, Instruction *ScanFrom,
78 const TargetData *TD) {
79 unsigned ByteOffset = 0;
80 Value *Base = V;
81 if (TD)
82 Base = getUnderlyingObjectWithOffset(V, TD, ByteOffset);
Chris Lattner6cc8a932009-06-16 17:23:12 +000083
Bob Wilson3eb4f7e2010-01-29 19:19:08 +000084 const Type *BaseType = 0;
85 if (const AllocaInst *AI = dyn_cast<AllocaInst>(Base))
86 // If it is an alloca it is always safe to load from.
87 BaseType = AI->getAllocatedType();
88 else if (const GlobalValue *GV = dyn_cast<GlobalValue>(Base)) {
89 // Global variables are safe to load from but their size cannot be
90 // guaranteed if they are overridden.
91 if (!isa<GlobalAlias>(GV) && !GV->mayBeOverridden())
92 BaseType = GV->getType()->getElementType();
93 }
Chris Lattner6cc8a932009-06-16 17:23:12 +000094
Bob Wilson3eb4f7e2010-01-29 19:19:08 +000095 if (BaseType) {
96 if (!TD)
97 return true; // Loading directly from an alloca or global is OK.
98 if (BaseType->isSized()) {
99 // Check if the load is within the bounds of the underlying object.
100 const PointerType *AddrTy = cast<PointerType>(V->getType());
101 unsigned LoadSize = TD->getTypeStoreSize(AddrTy->getElementType());
102 if (ByteOffset + LoadSize <= TD->getTypeAllocSize(BaseType))
103 return true;
104 }
105 }
106
107 // Otherwise, be a little bit aggressive by scanning the local block where we
Chris Lattner6cc8a932009-06-16 17:23:12 +0000108 // want to check to see if the pointer is already being loaded or stored
109 // from/to. If so, the previous load or store would have already trapped,
110 // so there is no harm doing an extra load (also, CSE will later eliminate
111 // the load entirely).
112 BasicBlock::iterator BBI = ScanFrom, E = ScanFrom->getParent()->begin();
113
114 while (BBI != E) {
115 --BBI;
116
117 // If we see a free or a call which may write to memory (i.e. which might do
118 // a free) the pointer could be marked invalid.
Chris Lattner938e1762009-11-03 05:33:46 +0000119 if (isa<CallInst>(BBI) && BBI->mayWriteToMemory() &&
120 !isa<DbgInfoIntrinsic>(BBI))
Chris Lattner6cc8a932009-06-16 17:23:12 +0000121 return false;
122
123 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
124 if (LI->getOperand(0) == V) return true;
125 } else if (StoreInst *SI = dyn_cast<StoreInst>(BBI)) {
126 if (SI->getOperand(1) == V) return true;
127 }
128 }
129 return false;
130}
131
132
133//===----------------------------------------------------------------------===//
Chris Lattner3481f242008-11-27 22:57:53 +0000134// Local constant propagation.
Chris Lattner4d1e46e2002-05-07 18:07:59 +0000135//
136
Chris Lattner4d1e46e2002-05-07 18:07:59 +0000137// ConstantFoldTerminator - If a terminator instruction is predicated on a
138// constant value, convert it into an unconditional branch to the constant
139// destination.
140//
Chris Lattnerabbc2dd2003-12-19 05:56:28 +0000141bool llvm::ConstantFoldTerminator(BasicBlock *BB) {
Chris Lattner76ae3442002-05-21 20:04:50 +0000142 TerminatorInst *T = BB->getTerminator();
Misha Brukmanfd939082005-04-21 23:48:37 +0000143
Chris Lattner4d1e46e2002-05-07 18:07:59 +0000144 // Branch - See if we are conditional jumping on constant
145 if (BranchInst *BI = dyn_cast<BranchInst>(T)) {
146 if (BI->isUnconditional()) return false; // Can't optimize uncond branch
Gabor Greifc1bb13f2009-01-30 18:21:13 +0000147 BasicBlock *Dest1 = BI->getSuccessor(0);
148 BasicBlock *Dest2 = BI->getSuccessor(1);
Chris Lattner4d1e46e2002-05-07 18:07:59 +0000149
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000150 if (ConstantInt *Cond = dyn_cast<ConstantInt>(BI->getCondition())) {
Chris Lattner4d1e46e2002-05-07 18:07:59 +0000151 // Are we branching on constant?
152 // YES. Change to unconditional branch...
Reid Spencer579dca12007-01-12 04:24:46 +0000153 BasicBlock *Destination = Cond->getZExtValue() ? Dest1 : Dest2;
154 BasicBlock *OldDest = Cond->getZExtValue() ? Dest2 : Dest1;
Chris Lattner4d1e46e2002-05-07 18:07:59 +0000155
Misha Brukmanfd939082005-04-21 23:48:37 +0000156 //cerr << "Function: " << T->getParent()->getParent()
157 // << "\nRemoving branch from " << T->getParent()
Chris Lattner4d1e46e2002-05-07 18:07:59 +0000158 // << "\n\nTo: " << OldDest << endl;
159
160 // Let the basic block know that we are letting go of it. Based on this,
161 // it will adjust it's PHI nodes.
162 assert(BI->getParent() && "Terminator not inserted in block!");
163 OldDest->removePredecessor(BI->getParent());
164
165 // Set the unconditional destination, and change the insn to be an
166 // unconditional branch.
167 BI->setUnconditionalDest(Destination);
Chris Lattner4d1e46e2002-05-07 18:07:59 +0000168 return true;
Chris Lattner0a4c6782009-11-01 03:40:38 +0000169 }
170
171 if (Dest2 == Dest1) { // Conditional branch to same location?
Misha Brukmanfd939082005-04-21 23:48:37 +0000172 // This branch matches something like this:
Chris Lattner4d1e46e2002-05-07 18:07:59 +0000173 // br bool %cond, label %Dest, label %Dest
174 // and changes it into: br label %Dest
175
176 // Let the basic block know that we are letting go of one copy of it.
177 assert(BI->getParent() && "Terminator not inserted in block!");
178 Dest1->removePredecessor(BI->getParent());
179
180 // Change a conditional branch to unconditional.
181 BI->setUnconditionalDest(Dest1);
182 return true;
183 }
Chris Lattner0a4c6782009-11-01 03:40:38 +0000184 return false;
185 }
186
187 if (SwitchInst *SI = dyn_cast<SwitchInst>(T)) {
Chris Lattner10b1f5a2003-08-17 20:21:14 +0000188 // If we are switching on a constant, we can convert the switch into a
189 // single branch instruction!
190 ConstantInt *CI = dyn_cast<ConstantInt>(SI->getCondition());
191 BasicBlock *TheOnlyDest = SI->getSuccessor(0); // The default dest
Chris Lattner7d6c24c2003-08-23 23:18:19 +0000192 BasicBlock *DefaultDest = TheOnlyDest;
193 assert(TheOnlyDest == SI->getDefaultDest() &&
194 "Default destination is not successor #0?");
Chris Lattner694e37f2003-08-17 19:41:53 +0000195
Chris Lattner0a4c6782009-11-01 03:40:38 +0000196 // Figure out which case it goes to.
Chris Lattner10b1f5a2003-08-17 20:21:14 +0000197 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i) {
198 // Found case matching a constant operand?
199 if (SI->getSuccessorValue(i) == CI) {
200 TheOnlyDest = SI->getSuccessor(i);
201 break;
202 }
Chris Lattner694e37f2003-08-17 19:41:53 +0000203
Chris Lattner7d6c24c2003-08-23 23:18:19 +0000204 // Check to see if this branch is going to the same place as the default
205 // dest. If so, eliminate it as an explicit compare.
206 if (SI->getSuccessor(i) == DefaultDest) {
Chris Lattner0a4c6782009-11-01 03:40:38 +0000207 // Remove this entry.
Chris Lattner7d6c24c2003-08-23 23:18:19 +0000208 DefaultDest->removePredecessor(SI->getParent());
209 SI->removeCase(i);
210 --i; --e; // Don't skip an entry...
211 continue;
212 }
213
Chris Lattner10b1f5a2003-08-17 20:21:14 +0000214 // Otherwise, check to see if the switch only branches to one destination.
215 // We do this by reseting "TheOnlyDest" to null when we find two non-equal
216 // destinations.
217 if (SI->getSuccessor(i) != TheOnlyDest) TheOnlyDest = 0;
Chris Lattner694e37f2003-08-17 19:41:53 +0000218 }
219
Chris Lattner10b1f5a2003-08-17 20:21:14 +0000220 if (CI && !TheOnlyDest) {
221 // Branching on a constant, but not any of the cases, go to the default
222 // successor.
223 TheOnlyDest = SI->getDefaultDest();
224 }
225
226 // If we found a single destination that we can fold the switch into, do so
227 // now.
228 if (TheOnlyDest) {
Chris Lattner0a4c6782009-11-01 03:40:38 +0000229 // Insert the new branch.
Gabor Greif051a9502008-04-06 20:25:17 +0000230 BranchInst::Create(TheOnlyDest, SI);
Chris Lattner10b1f5a2003-08-17 20:21:14 +0000231 BasicBlock *BB = SI->getParent();
232
233 // Remove entries from PHI nodes which we no longer branch to...
234 for (unsigned i = 0, e = SI->getNumSuccessors(); i != e; ++i) {
235 // Found case matching a constant operand?
236 BasicBlock *Succ = SI->getSuccessor(i);
237 if (Succ == TheOnlyDest)
238 TheOnlyDest = 0; // Don't modify the first branch to TheOnlyDest
239 else
240 Succ->removePredecessor(BB);
241 }
242
Chris Lattner0a4c6782009-11-01 03:40:38 +0000243 // Delete the old switch.
Chris Lattner10b1f5a2003-08-17 20:21:14 +0000244 BB->getInstList().erase(SI);
245 return true;
Chris Lattner0a4c6782009-11-01 03:40:38 +0000246 }
247
248 if (SI->getNumSuccessors() == 2) {
Chris Lattner10b1f5a2003-08-17 20:21:14 +0000249 // Otherwise, we can fold this switch into a conditional branch
250 // instruction if it has only one non-default destination.
Owen Anderson333c4002009-07-09 23:48:35 +0000251 Value *Cond = new ICmpInst(SI, ICmpInst::ICMP_EQ, SI->getCondition(),
252 SI->getSuccessorValue(1), "cond");
Chris Lattner0a4c6782009-11-01 03:40:38 +0000253 // Insert the new branch.
Gabor Greif051a9502008-04-06 20:25:17 +0000254 BranchInst::Create(SI->getSuccessor(1), SI->getSuccessor(0), Cond, SI);
Chris Lattner10b1f5a2003-08-17 20:21:14 +0000255
Chris Lattner0a4c6782009-11-01 03:40:38 +0000256 // Delete the old switch.
Dan Gohman1adec832008-06-21 22:08:46 +0000257 SI->eraseFromParent();
Chris Lattner10b1f5a2003-08-17 20:21:14 +0000258 return true;
259 }
Chris Lattner0a4c6782009-11-01 03:40:38 +0000260 return false;
Chris Lattner4d1e46e2002-05-07 18:07:59 +0000261 }
Chris Lattner0a4c6782009-11-01 03:40:38 +0000262
263 if (IndirectBrInst *IBI = dyn_cast<IndirectBrInst>(T)) {
264 // indirectbr blockaddress(@F, @BB) -> br label @BB
265 if (BlockAddress *BA =
266 dyn_cast<BlockAddress>(IBI->getAddress()->stripPointerCasts())) {
267 BasicBlock *TheOnlyDest = BA->getBasicBlock();
268 // Insert the new branch.
269 BranchInst::Create(TheOnlyDest, IBI);
270
271 for (unsigned i = 0, e = IBI->getNumDestinations(); i != e; ++i) {
272 if (IBI->getDestination(i) == TheOnlyDest)
273 TheOnlyDest = 0;
274 else
275 IBI->getDestination(i)->removePredecessor(IBI->getParent());
276 }
277 IBI->eraseFromParent();
278
279 // If we didn't find our destination in the IBI successor list, then we
280 // have undefined behavior. Replace the unconditional branch with an
281 // 'unreachable' instruction.
282 if (TheOnlyDest) {
283 BB->getTerminator()->eraseFromParent();
284 new UnreachableInst(BB->getContext(), BB);
285 }
286
287 return true;
288 }
289 }
290
Chris Lattner4d1e46e2002-05-07 18:07:59 +0000291 return false;
292}
293
Chris Lattner4d1e46e2002-05-07 18:07:59 +0000294
295//===----------------------------------------------------------------------===//
Chris Lattner40d8c282009-11-10 22:26:15 +0000296// Local dead code elimination.
Chris Lattner4d1e46e2002-05-07 18:07:59 +0000297//
298
Chris Lattner3481f242008-11-27 22:57:53 +0000299/// isInstructionTriviallyDead - Return true if the result produced by the
300/// instruction is not used, and the instruction has no side effects.
301///
Chris Lattnerabbc2dd2003-12-19 05:56:28 +0000302bool llvm::isInstructionTriviallyDead(Instruction *I) {
Chris Lattnerec710c52005-05-06 05:27:34 +0000303 if (!I->use_empty() || isa<TerminatorInst>(I)) return false;
Jeff Cohen00b168892005-07-27 06:12:32 +0000304
Dale Johannesen127a7932009-03-03 23:30:00 +0000305 // We don't want debug info removed by anything this general.
306 if (isa<DbgInfoIntrinsic>(I)) return false;
Chris Lattnerec710c52005-05-06 05:27:34 +0000307
Duncan Sandsa3da9222009-11-11 15:34:13 +0000308 // Likewise for memory use markers.
309 if (isa<MemoryUseIntrinsic>(I)) return false;
310
Duncan Sands7af1c782009-05-06 06:49:50 +0000311 if (!I->mayHaveSideEffects()) return true;
312
313 // Special case intrinsics that "may have side effects" but can be deleted
314 // when dead.
Chris Lattner741c0ae2007-12-29 00:59:12 +0000315 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I))
316 // Safe to delete llvm.stacksave if dead.
317 if (II->getIntrinsicID() == Intrinsic::stacksave)
318 return true;
Chris Lattnerec710c52005-05-06 05:27:34 +0000319 return false;
Chris Lattner4d1e46e2002-05-07 18:07:59 +0000320}
321
Chris Lattner3481f242008-11-27 22:57:53 +0000322/// RecursivelyDeleteTriviallyDeadInstructions - If the specified value is a
323/// trivially dead instruction, delete it. If that makes any of its operands
Dan Gohman90fe0bd2010-01-05 15:45:31 +0000324/// trivially dead, delete them too, recursively. Return true if any
325/// instructions were deleted.
326bool llvm::RecursivelyDeleteTriviallyDeadInstructions(Value *V) {
Chris Lattner3481f242008-11-27 22:57:53 +0000327 Instruction *I = dyn_cast<Instruction>(V);
Chris Lattner76057302008-11-28 01:20:46 +0000328 if (!I || !I->use_empty() || !isInstructionTriviallyDead(I))
Dan Gohman90fe0bd2010-01-05 15:45:31 +0000329 return false;
Chris Lattner3481f242008-11-27 22:57:53 +0000330
Chris Lattner76057302008-11-28 01:20:46 +0000331 SmallVector<Instruction*, 16> DeadInsts;
332 DeadInsts.push_back(I);
Chris Lattner3481f242008-11-27 22:57:53 +0000333
Dan Gohman321a8132010-01-05 16:27:25 +0000334 do {
Dan Gohmane9d87f42009-05-06 17:22:41 +0000335 I = DeadInsts.pop_back_val();
Chris Lattner28721772008-11-28 00:58:15 +0000336
Chris Lattner76057302008-11-28 01:20:46 +0000337 // Null out all of the instruction's operands to see if any operand becomes
338 // dead as we go.
339 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
340 Value *OpV = I->getOperand(i);
341 I->setOperand(i, 0);
342
343 if (!OpV->use_empty()) continue;
344
345 // If the operand is an instruction that became dead as we nulled out the
346 // operand, and if it is 'trivially' dead, delete it in a future loop
347 // iteration.
348 if (Instruction *OpI = dyn_cast<Instruction>(OpV))
349 if (isInstructionTriviallyDead(OpI))
350 DeadInsts.push_back(OpI);
351 }
352
353 I->eraseFromParent();
Dan Gohman321a8132010-01-05 16:27:25 +0000354 } while (!DeadInsts.empty());
Dan Gohman90fe0bd2010-01-05 15:45:31 +0000355
356 return true;
Chris Lattner4d1e46e2002-05-07 18:07:59 +0000357}
Chris Lattnerb29714a2008-11-27 07:43:12 +0000358
Dan Gohmanafc36a92009-05-02 18:29:22 +0000359/// RecursivelyDeleteDeadPHINode - If the specified value is an effectively
360/// dead PHI node, due to being a def-use chain of single-use nodes that
361/// either forms a cycle or is terminated by a trivially dead instruction,
362/// delete it. If that makes any of its operands trivially dead, delete them
Dan Gohman90fe0bd2010-01-05 15:45:31 +0000363/// too, recursively. Return true if the PHI node is actually deleted.
364bool
Dan Gohman35738ac2009-05-04 22:30:44 +0000365llvm::RecursivelyDeleteDeadPHINode(PHINode *PN) {
Dan Gohmanafc36a92009-05-02 18:29:22 +0000366 // We can remove a PHI if it is on a cycle in the def-use graph
367 // where each node in the cycle has degree one, i.e. only one use,
368 // and is an instruction with no side effects.
369 if (!PN->hasOneUse())
Dan Gohman90fe0bd2010-01-05 15:45:31 +0000370 return false;
Dan Gohmanafc36a92009-05-02 18:29:22 +0000371
Dan Gohman90fe0bd2010-01-05 15:45:31 +0000372 bool Changed = false;
Dan Gohmanafc36a92009-05-02 18:29:22 +0000373 SmallPtrSet<PHINode *, 4> PHIs;
374 PHIs.insert(PN);
375 for (Instruction *J = cast<Instruction>(*PN->use_begin());
Duncan Sands7af1c782009-05-06 06:49:50 +0000376 J->hasOneUse() && !J->mayHaveSideEffects();
Dan Gohmanafc36a92009-05-02 18:29:22 +0000377 J = cast<Instruction>(*J->use_begin()))
378 // If we find a PHI more than once, we're on a cycle that
379 // won't prove fruitful.
380 if (PHINode *JP = dyn_cast<PHINode>(J))
381 if (!PHIs.insert(cast<PHINode>(JP))) {
382 // Break the cycle and delete the PHI and its operands.
Owen Anderson9e9a0d52009-07-30 23:03:37 +0000383 JP->replaceAllUsesWith(UndefValue::get(JP->getType()));
Dan Gohmanba25f092010-01-05 17:50:58 +0000384 (void)RecursivelyDeleteTriviallyDeadInstructions(JP);
385 Changed = true;
Dan Gohmanafc36a92009-05-02 18:29:22 +0000386 break;
387 }
Dan Gohman90fe0bd2010-01-05 15:45:31 +0000388 return Changed;
Dan Gohmanafc36a92009-05-02 18:29:22 +0000389}
Chris Lattner3481f242008-11-27 22:57:53 +0000390
Chris Lattnere234a302010-01-12 19:40:54 +0000391/// SimplifyInstructionsInBlock - Scan the specified basic block and try to
392/// simplify any instructions in it and recursively delete dead instructions.
393///
394/// This returns true if it changed the code, note that it can delete
395/// instructions in other blocks as well in this block.
396bool llvm::SimplifyInstructionsInBlock(BasicBlock *BB, const TargetData *TD) {
397 bool MadeChange = false;
398 for (BasicBlock::iterator BI = BB->begin(), E = BB->end(); BI != E; ) {
399 Instruction *Inst = BI++;
400
401 if (Value *V = SimplifyInstruction(Inst, TD)) {
402 WeakVH BIHandle(BI);
403 ReplaceAndSimplifyAllUses(Inst, V, TD);
404 MadeChange = true;
405 if (BIHandle == 0)
406 BI = BB->begin();
407 continue;
408 }
409
410 MadeChange |= RecursivelyDeleteTriviallyDeadInstructions(Inst);
411 }
412 return MadeChange;
413}
414
Chris Lattnerb29714a2008-11-27 07:43:12 +0000415//===----------------------------------------------------------------------===//
Chris Lattner40d8c282009-11-10 22:26:15 +0000416// Control Flow Graph Restructuring.
Chris Lattnerb29714a2008-11-27 07:43:12 +0000417//
418
Chris Lattner40d8c282009-11-10 22:26:15 +0000419
420/// RemovePredecessorAndSimplify - Like BasicBlock::removePredecessor, this
421/// method is called when we're about to delete Pred as a predecessor of BB. If
422/// BB contains any PHI nodes, this drops the entries in the PHI nodes for Pred.
423///
424/// Unlike the removePredecessor method, this attempts to simplify uses of PHI
425/// nodes that collapse into identity values. For example, if we have:
426/// x = phi(1, 0, 0, 0)
427/// y = and x, z
428///
429/// .. and delete the predecessor corresponding to the '1', this will attempt to
430/// recursively fold the and to 0.
431void llvm::RemovePredecessorAndSimplify(BasicBlock *BB, BasicBlock *Pred,
432 TargetData *TD) {
433 // This only adjusts blocks with PHI nodes.
434 if (!isa<PHINode>(BB->begin()))
435 return;
436
437 // Remove the entries for Pred from the PHI nodes in BB, but do not simplify
438 // them down. This will leave us with single entry phi nodes and other phis
439 // that can be removed.
440 BB->removePredecessor(Pred, true);
441
442 WeakVH PhiIt = &BB->front();
443 while (PHINode *PN = dyn_cast<PHINode>(PhiIt)) {
444 PhiIt = &*++BasicBlock::iterator(cast<Instruction>(PhiIt));
445
446 Value *PNV = PN->hasConstantValue();
447 if (PNV == 0) continue;
448
449 // If we're able to simplify the phi to a single value, substitute the new
450 // value into all of its uses.
451 assert(PNV != PN && "hasConstantValue broken");
452
453 ReplaceAndSimplifyAllUses(PN, PNV, TD);
454
455 // If recursive simplification ended up deleting the next PHI node we would
456 // iterate to, then our iterator is invalid, restart scanning from the top
457 // of the block.
458 if (PhiIt == 0) PhiIt = &BB->front();
459 }
460}
461
462
Chris Lattnerb29714a2008-11-27 07:43:12 +0000463/// MergeBasicBlockIntoOnlyPred - DestBB is a block with one predecessor and its
464/// predecessor is known to have one successor (DestBB!). Eliminate the edge
465/// between them, moving the instructions in the predecessor into DestBB and
466/// deleting the predecessor block.
467///
Andreas Neustifterad809812009-09-16 09:26:52 +0000468void llvm::MergeBasicBlockIntoOnlyPred(BasicBlock *DestBB, Pass *P) {
Chris Lattnerb29714a2008-11-27 07:43:12 +0000469 // If BB has single-entry PHI nodes, fold them.
470 while (PHINode *PN = dyn_cast<PHINode>(DestBB->begin())) {
471 Value *NewVal = PN->getIncomingValue(0);
472 // Replace self referencing PHI with undef, it must be dead.
Owen Anderson9e9a0d52009-07-30 23:03:37 +0000473 if (NewVal == PN) NewVal = UndefValue::get(PN->getType());
Chris Lattnerb29714a2008-11-27 07:43:12 +0000474 PN->replaceAllUsesWith(NewVal);
475 PN->eraseFromParent();
476 }
477
478 BasicBlock *PredBB = DestBB->getSinglePredecessor();
479 assert(PredBB && "Block doesn't have a single predecessor!");
480
481 // Splice all the instructions from PredBB to DestBB.
482 PredBB->getTerminator()->eraseFromParent();
483 DestBB->getInstList().splice(DestBB->begin(), PredBB->getInstList());
484
485 // Anything that branched to PredBB now branches to DestBB.
486 PredBB->replaceAllUsesWith(DestBB);
487
Andreas Neustifterad809812009-09-16 09:26:52 +0000488 if (P) {
489 ProfileInfo *PI = P->getAnalysisIfAvailable<ProfileInfo>();
490 if (PI) {
491 PI->replaceAllUses(PredBB, DestBB);
492 PI->removeEdge(ProfileInfo::getEdge(PredBB, DestBB));
493 }
494 }
Chris Lattnerb29714a2008-11-27 07:43:12 +0000495 // Nuke BB.
496 PredBB->eraseFromParent();
497}
Devang Patel4afc90d2009-02-10 07:00:59 +0000498
Chris Lattnerdce94d92009-11-10 05:59:26 +0000499/// CanPropagatePredecessorsForPHIs - Return true if we can fold BB, an
500/// almost-empty BB ending in an unconditional branch to Succ, into succ.
501///
502/// Assumption: Succ is the single successor for BB.
503///
504static bool CanPropagatePredecessorsForPHIs(BasicBlock *BB, BasicBlock *Succ) {
505 assert(*succ_begin(BB) == Succ && "Succ is not successor of BB!");
506
David Greenefae77062010-01-05 01:26:57 +0000507 DEBUG(dbgs() << "Looking to fold " << BB->getName() << " into "
Chris Lattnerdce94d92009-11-10 05:59:26 +0000508 << Succ->getName() << "\n");
509 // Shortcut, if there is only a single predecessor it must be BB and merging
510 // is always safe
511 if (Succ->getSinglePredecessor()) return true;
512
513 // Make a list of the predecessors of BB
514 typedef SmallPtrSet<BasicBlock*, 16> BlockSet;
515 BlockSet BBPreds(pred_begin(BB), pred_end(BB));
516
517 // Use that list to make another list of common predecessors of BB and Succ
518 BlockSet CommonPreds;
519 for (pred_iterator PI = pred_begin(Succ), PE = pred_end(Succ);
520 PI != PE; ++PI)
521 if (BBPreds.count(*PI))
522 CommonPreds.insert(*PI);
523
524 // Shortcut, if there are no common predecessors, merging is always safe
525 if (CommonPreds.empty())
526 return true;
527
528 // Look at all the phi nodes in Succ, to see if they present a conflict when
529 // merging these blocks
530 for (BasicBlock::iterator I = Succ->begin(); isa<PHINode>(I); ++I) {
531 PHINode *PN = cast<PHINode>(I);
532
533 // If the incoming value from BB is again a PHINode in
534 // BB which has the same incoming value for *PI as PN does, we can
535 // merge the phi nodes and then the blocks can still be merged
536 PHINode *BBPN = dyn_cast<PHINode>(PN->getIncomingValueForBlock(BB));
537 if (BBPN && BBPN->getParent() == BB) {
538 for (BlockSet::iterator PI = CommonPreds.begin(), PE = CommonPreds.end();
539 PI != PE; PI++) {
540 if (BBPN->getIncomingValueForBlock(*PI)
541 != PN->getIncomingValueForBlock(*PI)) {
David Greenefae77062010-01-05 01:26:57 +0000542 DEBUG(dbgs() << "Can't fold, phi node " << PN->getName() << " in "
Chris Lattnerdce94d92009-11-10 05:59:26 +0000543 << Succ->getName() << " is conflicting with "
544 << BBPN->getName() << " with regard to common predecessor "
545 << (*PI)->getName() << "\n");
546 return false;
547 }
548 }
549 } else {
550 Value* Val = PN->getIncomingValueForBlock(BB);
551 for (BlockSet::iterator PI = CommonPreds.begin(), PE = CommonPreds.end();
552 PI != PE; PI++) {
553 // See if the incoming value for the common predecessor is equal to the
554 // one for BB, in which case this phi node will not prevent the merging
555 // of the block.
556 if (Val != PN->getIncomingValueForBlock(*PI)) {
David Greenefae77062010-01-05 01:26:57 +0000557 DEBUG(dbgs() << "Can't fold, phi node " << PN->getName() << " in "
Chris Lattnerdce94d92009-11-10 05:59:26 +0000558 << Succ->getName() << " is conflicting with regard to common "
559 << "predecessor " << (*PI)->getName() << "\n");
560 return false;
561 }
562 }
563 }
564 }
565
566 return true;
567}
568
569/// TryToSimplifyUncondBranchFromEmptyBlock - BB is known to contain an
570/// unconditional branch, and contains no instructions other than PHI nodes,
571/// potential debug intrinsics and the branch. If possible, eliminate BB by
572/// rewriting all the predecessors to branch to the successor block and return
573/// true. If we can't transform, return false.
574bool llvm::TryToSimplifyUncondBranchFromEmptyBlock(BasicBlock *BB) {
575 // We can't eliminate infinite loops.
576 BasicBlock *Succ = cast<BranchInst>(BB->getTerminator())->getSuccessor(0);
577 if (BB == Succ) return false;
578
579 // Check to see if merging these blocks would cause conflicts for any of the
580 // phi nodes in BB or Succ. If not, we can safely merge.
581 if (!CanPropagatePredecessorsForPHIs(BB, Succ)) return false;
582
583 // Check for cases where Succ has multiple predecessors and a PHI node in BB
584 // has uses which will not disappear when the PHI nodes are merged. It is
585 // possible to handle such cases, but difficult: it requires checking whether
586 // BB dominates Succ, which is non-trivial to calculate in the case where
587 // Succ has multiple predecessors. Also, it requires checking whether
588 // constructing the necessary self-referential PHI node doesn't intoduce any
589 // conflicts; this isn't too difficult, but the previous code for doing this
590 // was incorrect.
591 //
592 // Note that if this check finds a live use, BB dominates Succ, so BB is
593 // something like a loop pre-header (or rarely, a part of an irreducible CFG);
594 // folding the branch isn't profitable in that case anyway.
595 if (!Succ->getSinglePredecessor()) {
596 BasicBlock::iterator BBI = BB->begin();
597 while (isa<PHINode>(*BBI)) {
598 for (Value::use_iterator UI = BBI->use_begin(), E = BBI->use_end();
599 UI != E; ++UI) {
600 if (PHINode* PN = dyn_cast<PHINode>(*UI)) {
601 if (PN->getIncomingBlock(UI) != BB)
602 return false;
603 } else {
604 return false;
605 }
606 }
607 ++BBI;
608 }
609 }
610
David Greenefae77062010-01-05 01:26:57 +0000611 DEBUG(dbgs() << "Killing Trivial BB: \n" << *BB);
Chris Lattnerdce94d92009-11-10 05:59:26 +0000612
613 if (isa<PHINode>(Succ->begin())) {
614 // If there is more than one pred of succ, and there are PHI nodes in
615 // the successor, then we need to add incoming edges for the PHI nodes
616 //
617 const SmallVector<BasicBlock*, 16> BBPreds(pred_begin(BB), pred_end(BB));
618
619 // Loop over all of the PHI nodes in the successor of BB.
620 for (BasicBlock::iterator I = Succ->begin(); isa<PHINode>(I); ++I) {
621 PHINode *PN = cast<PHINode>(I);
622 Value *OldVal = PN->removeIncomingValue(BB, false);
623 assert(OldVal && "No entry in PHI for Pred BB!");
624
625 // If this incoming value is one of the PHI nodes in BB, the new entries
626 // in the PHI node are the entries from the old PHI.
627 if (isa<PHINode>(OldVal) && cast<PHINode>(OldVal)->getParent() == BB) {
628 PHINode *OldValPN = cast<PHINode>(OldVal);
629 for (unsigned i = 0, e = OldValPN->getNumIncomingValues(); i != e; ++i)
630 // Note that, since we are merging phi nodes and BB and Succ might
631 // have common predecessors, we could end up with a phi node with
632 // identical incoming branches. This will be cleaned up later (and
633 // will trigger asserts if we try to clean it up now, without also
634 // simplifying the corresponding conditional branch).
635 PN->addIncoming(OldValPN->getIncomingValue(i),
636 OldValPN->getIncomingBlock(i));
637 } else {
638 // Add an incoming value for each of the new incoming values.
639 for (unsigned i = 0, e = BBPreds.size(); i != e; ++i)
640 PN->addIncoming(OldVal, BBPreds[i]);
641 }
642 }
643 }
644
645 while (PHINode *PN = dyn_cast<PHINode>(&BB->front())) {
646 if (Succ->getSinglePredecessor()) {
647 // BB is the only predecessor of Succ, so Succ will end up with exactly
648 // the same predecessors BB had.
649 Succ->getInstList().splice(Succ->begin(),
650 BB->getInstList(), BB->begin());
651 } else {
652 // We explicitly check for such uses in CanPropagatePredecessorsForPHIs.
653 assert(PN->use_empty() && "There shouldn't be any uses here!");
654 PN->eraseFromParent();
655 }
656 }
657
658 // Everything that jumped to BB now goes to Succ.
659 BB->replaceAllUsesWith(Succ);
660 if (!Succ->hasName()) Succ->takeName(BB);
661 BB->eraseFromParent(); // Delete the old basic block.
662 return true;
663}
664
Jim Grosbach43a82412009-12-02 17:06:45 +0000665/// EliminateDuplicatePHINodes - Check for and eliminate duplicate PHI
666/// nodes in this block. This doesn't try to be clever about PHI nodes
667/// which differ only in the order of the incoming values, but instcombine
668/// orders them so it usually won't matter.
669///
670bool llvm::EliminateDuplicatePHINodes(BasicBlock *BB) {
671 bool Changed = false;
672
673 // This implementation doesn't currently consider undef operands
674 // specially. Theroetically, two phis which are identical except for
675 // one having an undef where the other doesn't could be collapsed.
676
677 // Map from PHI hash values to PHI nodes. If multiple PHIs have
678 // the same hash value, the element is the first PHI in the
679 // linked list in CollisionMap.
680 DenseMap<uintptr_t, PHINode *> HashMap;
681
682 // Maintain linked lists of PHI nodes with common hash values.
683 DenseMap<PHINode *, PHINode *> CollisionMap;
684
685 // Examine each PHI.
686 for (BasicBlock::iterator I = BB->begin();
687 PHINode *PN = dyn_cast<PHINode>(I++); ) {
688 // Compute a hash value on the operands. Instcombine will likely have sorted
689 // them, which helps expose duplicates, but we have to check all the
690 // operands to be safe in case instcombine hasn't run.
691 uintptr_t Hash = 0;
692 for (User::op_iterator I = PN->op_begin(), E = PN->op_end(); I != E; ++I) {
693 // This hash algorithm is quite weak as hash functions go, but it seems
694 // to do a good enough job for this particular purpose, and is very quick.
695 Hash ^= reinterpret_cast<uintptr_t>(static_cast<Value *>(*I));
696 Hash = (Hash << 7) | (Hash >> (sizeof(uintptr_t) * CHAR_BIT - 7));
697 }
698 // If we've never seen this hash value before, it's a unique PHI.
699 std::pair<DenseMap<uintptr_t, PHINode *>::iterator, bool> Pair =
700 HashMap.insert(std::make_pair(Hash, PN));
701 if (Pair.second) continue;
702 // Otherwise it's either a duplicate or a hash collision.
703 for (PHINode *OtherPN = Pair.first->second; ; ) {
704 if (OtherPN->isIdenticalTo(PN)) {
705 // A duplicate. Replace this PHI with its duplicate.
706 PN->replaceAllUsesWith(OtherPN);
707 PN->eraseFromParent();
708 Changed = true;
709 break;
710 }
711 // A non-duplicate hash collision.
712 DenseMap<PHINode *, PHINode *>::iterator I = CollisionMap.find(OtherPN);
713 if (I == CollisionMap.end()) {
714 // Set this PHI to be the head of the linked list of colliding PHIs.
715 PHINode *Old = Pair.first->second;
716 Pair.first->second = PN;
717 CollisionMap[PN] = Old;
718 break;
719 }
720 // Procede to the next PHI in the list.
721 OtherPN = I->second;
722 }
723 }
724
725 return Changed;
726}