1 //===-- Local.cpp - Functions to perform local transformations ------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This family of functions perform various local transformations to the
13 //===----------------------------------------------------------------------===//
15 #include "llvm/Transforms/Utils/Local.h"
16 #include "llvm/Constants.h"
17 #include "llvm/GlobalAlias.h"
18 #include "llvm/GlobalVariable.h"
19 #include "llvm/DerivedTypes.h"
20 #include "llvm/Instructions.h"
21 #include "llvm/Intrinsics.h"
22 #include "llvm/IntrinsicInst.h"
23 #include "llvm/LLVMContext.h"
24 #include "llvm/ADT/SmallPtrSet.h"
25 #include "llvm/Analysis/ConstantFolding.h"
26 #include "llvm/Analysis/DebugInfo.h"
27 #include "llvm/Analysis/MallocHelper.h"
28 #include "llvm/Analysis/ProfileInfo.h"
29 #include "llvm/Target/TargetData.h"
30 #include "llvm/Support/GetElementPtrTypeIterator.h"
31 #include "llvm/Support/MathExtras.h"
34 //===----------------------------------------------------------------------===//
38 /// isSafeToLoadUnconditionally - Return true if we know that executing a load
39 /// from this value cannot trap. If it is not obviously safe to load from the
40 /// specified pointer, we do a quick local scan of the basic block containing
41 /// ScanFrom, to determine if the address is already accessed.
42 bool llvm::isSafeToLoadUnconditionally(Value *V, Instruction *ScanFrom) {
43 // If it is an alloca it is always safe to load from.
44 if (isa<AllocaInst>(V)) return true;
46 // If it is a global variable it is mostly safe to load from.
47 if (const GlobalValue *GV = dyn_cast<GlobalVariable>(V))
48 // Don't try to evaluate aliases. External weak GV can be null.
49 return !isa<GlobalAlias>(GV) && !GV->hasExternalWeakLinkage();
51 // Otherwise, be a little bit agressive by scanning the local block where we
52 // want to check to see if the pointer is already being loaded or stored
53 // from/to. If so, the previous load or store would have already trapped,
54 // so there is no harm doing an extra load (also, CSE will later eliminate
55 // the load entirely).
56 BasicBlock::iterator BBI = ScanFrom, E = ScanFrom->getParent()->begin();
61 // If we see a free or a call which may write to memory (i.e. which might do
62 // a free) the pointer could be marked invalid.
63 if (isa<FreeInst>(BBI) || isFreeCall(BBI) ||
64 (isa<CallInst>(BBI) && BBI->mayWriteToMemory() &&
65 !isa<DbgInfoIntrinsic>(BBI)))
68 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
69 if (LI->getOperand(0) == V) return true;
70 } else if (StoreInst *SI = dyn_cast<StoreInst>(BBI)) {
71 if (SI->getOperand(1) == V) return true;
78 //===----------------------------------------------------------------------===//
79 // Local constant propagation.
82 // ConstantFoldTerminator - If a terminator instruction is predicated on a
83 // constant value, convert it into an unconditional branch to the constant
86 bool llvm::ConstantFoldTerminator(BasicBlock *BB) {
87 TerminatorInst *T = BB->getTerminator();
89 // Branch - See if we are conditional jumping on constant
90 if (BranchInst *BI = dyn_cast<BranchInst>(T)) {
91 if (BI->isUnconditional()) return false; // Can't optimize uncond branch
92 BasicBlock *Dest1 = BI->getSuccessor(0);
93 BasicBlock *Dest2 = BI->getSuccessor(1);
95 if (ConstantInt *Cond = dyn_cast<ConstantInt>(BI->getCondition())) {
96 // Are we branching on constant?
97 // YES. Change to unconditional branch...
98 BasicBlock *Destination = Cond->getZExtValue() ? Dest1 : Dest2;
99 BasicBlock *OldDest = Cond->getZExtValue() ? Dest2 : Dest1;
101 //cerr << "Function: " << T->getParent()->getParent()
102 // << "\nRemoving branch from " << T->getParent()
103 // << "\n\nTo: " << OldDest << endl;
105 // Let the basic block know that we are letting go of it. Based on this,
106 // it will adjust it's PHI nodes.
107 assert(BI->getParent() && "Terminator not inserted in block!");
108 OldDest->removePredecessor(BI->getParent());
110 // Set the unconditional destination, and change the insn to be an
111 // unconditional branch.
112 BI->setUnconditionalDest(Destination);
114 } else if (Dest2 == Dest1) { // Conditional branch to same location?
115 // This branch matches something like this:
116 // br bool %cond, label %Dest, label %Dest
117 // and changes it into: br label %Dest
119 // Let the basic block know that we are letting go of one copy of it.
120 assert(BI->getParent() && "Terminator not inserted in block!");
121 Dest1->removePredecessor(BI->getParent());
123 // Change a conditional branch to unconditional.
124 BI->setUnconditionalDest(Dest1);
127 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(T)) {
128 // If we are switching on a constant, we can convert the switch into a
129 // single branch instruction!
130 ConstantInt *CI = dyn_cast<ConstantInt>(SI->getCondition());
131 BasicBlock *TheOnlyDest = SI->getSuccessor(0); // The default dest
132 BasicBlock *DefaultDest = TheOnlyDest;
133 assert(TheOnlyDest == SI->getDefaultDest() &&
134 "Default destination is not successor #0?");
136 // Figure out which case it goes to...
137 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i) {
138 // Found case matching a constant operand?
139 if (SI->getSuccessorValue(i) == CI) {
140 TheOnlyDest = SI->getSuccessor(i);
144 // Check to see if this branch is going to the same place as the default
145 // dest. If so, eliminate it as an explicit compare.
146 if (SI->getSuccessor(i) == DefaultDest) {
147 // Remove this entry...
148 DefaultDest->removePredecessor(SI->getParent());
150 --i; --e; // Don't skip an entry...
154 // Otherwise, check to see if the switch only branches to one destination.
155 // We do this by reseting "TheOnlyDest" to null when we find two non-equal
157 if (SI->getSuccessor(i) != TheOnlyDest) TheOnlyDest = 0;
160 if (CI && !TheOnlyDest) {
161 // Branching on a constant, but not any of the cases, go to the default
163 TheOnlyDest = SI->getDefaultDest();
166 // If we found a single destination that we can fold the switch into, do so
169 // Insert the new branch..
170 BranchInst::Create(TheOnlyDest, SI);
171 BasicBlock *BB = SI->getParent();
173 // Remove entries from PHI nodes which we no longer branch to...
174 for (unsigned i = 0, e = SI->getNumSuccessors(); i != e; ++i) {
175 // Found case matching a constant operand?
176 BasicBlock *Succ = SI->getSuccessor(i);
177 if (Succ == TheOnlyDest)
178 TheOnlyDest = 0; // Don't modify the first branch to TheOnlyDest
180 Succ->removePredecessor(BB);
183 // Delete the old switch...
184 BB->getInstList().erase(SI);
186 } else if (SI->getNumSuccessors() == 2) {
187 // Otherwise, we can fold this switch into a conditional branch
188 // instruction if it has only one non-default destination.
189 Value *Cond = new ICmpInst(SI, ICmpInst::ICMP_EQ, SI->getCondition(),
190 SI->getSuccessorValue(1), "cond");
191 // Insert the new branch...
192 BranchInst::Create(SI->getSuccessor(1), SI->getSuccessor(0), Cond, SI);
194 // Delete the old switch...
195 SI->eraseFromParent();
203 //===----------------------------------------------------------------------===//
204 // Local dead code elimination...
207 /// isInstructionTriviallyDead - Return true if the result produced by the
208 /// instruction is not used, and the instruction has no side effects.
210 bool llvm::isInstructionTriviallyDead(Instruction *I) {
211 if (!I->use_empty() || isa<TerminatorInst>(I)) return false;
213 // We don't want debug info removed by anything this general.
214 if (isa<DbgInfoIntrinsic>(I)) return false;
216 if (!I->mayHaveSideEffects()) return true;
218 // Special case intrinsics that "may have side effects" but can be deleted
220 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I))
221 // Safe to delete llvm.stacksave if dead.
222 if (II->getIntrinsicID() == Intrinsic::stacksave)
227 /// RecursivelyDeleteTriviallyDeadInstructions - If the specified value is a
228 /// trivially dead instruction, delete it. If that makes any of its operands
229 /// trivially dead, delete them too, recursively.
230 void llvm::RecursivelyDeleteTriviallyDeadInstructions(Value *V) {
231 Instruction *I = dyn_cast<Instruction>(V);
232 if (!I || !I->use_empty() || !isInstructionTriviallyDead(I))
235 SmallVector<Instruction*, 16> DeadInsts;
236 DeadInsts.push_back(I);
238 while (!DeadInsts.empty()) {
239 I = DeadInsts.pop_back_val();
241 // Null out all of the instruction's operands to see if any operand becomes
243 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
244 Value *OpV = I->getOperand(i);
247 if (!OpV->use_empty()) continue;
249 // If the operand is an instruction that became dead as we nulled out the
250 // operand, and if it is 'trivially' dead, delete it in a future loop
252 if (Instruction *OpI = dyn_cast<Instruction>(OpV))
253 if (isInstructionTriviallyDead(OpI))
254 DeadInsts.push_back(OpI);
257 I->eraseFromParent();
261 /// RecursivelyDeleteDeadPHINode - If the specified value is an effectively
262 /// dead PHI node, due to being a def-use chain of single-use nodes that
263 /// either forms a cycle or is terminated by a trivially dead instruction,
264 /// delete it. If that makes any of its operands trivially dead, delete them
265 /// too, recursively.
267 llvm::RecursivelyDeleteDeadPHINode(PHINode *PN) {
268 // We can remove a PHI if it is on a cycle in the def-use graph
269 // where each node in the cycle has degree one, i.e. only one use,
270 // and is an instruction with no side effects.
271 if (!PN->hasOneUse())
274 SmallPtrSet<PHINode *, 4> PHIs;
276 for (Instruction *J = cast<Instruction>(*PN->use_begin());
277 J->hasOneUse() && !J->mayHaveSideEffects();
278 J = cast<Instruction>(*J->use_begin()))
279 // If we find a PHI more than once, we're on a cycle that
280 // won't prove fruitful.
281 if (PHINode *JP = dyn_cast<PHINode>(J))
282 if (!PHIs.insert(cast<PHINode>(JP))) {
283 // Break the cycle and delete the PHI and its operands.
284 JP->replaceAllUsesWith(UndefValue::get(JP->getType()));
285 RecursivelyDeleteTriviallyDeadInstructions(JP);
290 //===----------------------------------------------------------------------===//
291 // Control Flow Graph Restructuring...
294 /// MergeBasicBlockIntoOnlyPred - DestBB is a block with one predecessor and its
295 /// predecessor is known to have one successor (DestBB!). Eliminate the edge
296 /// between them, moving the instructions in the predecessor into DestBB and
297 /// deleting the predecessor block.
299 void llvm::MergeBasicBlockIntoOnlyPred(BasicBlock *DestBB, Pass *P) {
300 // If BB has single-entry PHI nodes, fold them.
301 while (PHINode *PN = dyn_cast<PHINode>(DestBB->begin())) {
302 Value *NewVal = PN->getIncomingValue(0);
303 // Replace self referencing PHI with undef, it must be dead.
304 if (NewVal == PN) NewVal = UndefValue::get(PN->getType());
305 PN->replaceAllUsesWith(NewVal);
306 PN->eraseFromParent();
309 BasicBlock *PredBB = DestBB->getSinglePredecessor();
310 assert(PredBB && "Block doesn't have a single predecessor!");
312 // Splice all the instructions from PredBB to DestBB.
313 PredBB->getTerminator()->eraseFromParent();
314 DestBB->getInstList().splice(DestBB->begin(), PredBB->getInstList());
316 // Anything that branched to PredBB now branches to DestBB.
317 PredBB->replaceAllUsesWith(DestBB);
320 ProfileInfo *PI = P->getAnalysisIfAvailable<ProfileInfo>();
322 PI->replaceAllUses(PredBB, DestBB);
323 PI->removeEdge(ProfileInfo::getEdge(PredBB, DestBB));
327 PredBB->eraseFromParent();
330 /// OnlyUsedByDbgIntrinsics - Return true if the instruction I is only used
331 /// by DbgIntrinsics. If DbgInUses is specified then the vector is filled
332 /// with the DbgInfoIntrinsic that use the instruction I.
333 bool llvm::OnlyUsedByDbgInfoIntrinsics(Instruction *I,
334 SmallVectorImpl<DbgInfoIntrinsic *> *DbgInUses) {
338 for (Value::use_iterator UI = I->use_begin(), UE = I->use_end(); UI != UE;
340 if (DbgInfoIntrinsic *DI = dyn_cast<DbgInfoIntrinsic>(*UI)) {
342 DbgInUses->push_back(DI);