blob: 4f2bb1e3de7a80665c8d4bbbe028d326e29cd709 [file] [log] [blame]
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001//===-- Local.cpp - Functions to perform local transformations ------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner081ce942007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This family of functions perform various local transformations to the
11// program.
12//
13//===----------------------------------------------------------------------===//
14
15#include "llvm/Transforms/Utils/Local.h"
16#include "llvm/Constants.h"
Devang Patel06350be2009-03-06 00:19:37 +000017#include "llvm/GlobalVariable.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000018#include "llvm/DerivedTypes.h"
19#include "llvm/Instructions.h"
20#include "llvm/Intrinsics.h"
Chris Lattner41847892007-12-29 00:59:12 +000021#include "llvm/IntrinsicInst.h"
Dan Gohman93efe962009-05-02 18:29:22 +000022#include "llvm/ADT/SmallPtrSet.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000023#include "llvm/Analysis/ConstantFolding.h"
Devang Patel06350be2009-03-06 00:19:37 +000024#include "llvm/Analysis/DebugInfo.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000025#include "llvm/Target/TargetData.h"
26#include "llvm/Support/GetElementPtrTypeIterator.h"
27#include "llvm/Support/MathExtras.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000028using namespace llvm;
29
30//===----------------------------------------------------------------------===//
Chris Lattner15ca9352008-11-27 22:57:53 +000031// Local constant propagation.
Dan Gohmanf17a25c2007-07-18 16:29:46 +000032//
33
Dan Gohmanf17a25c2007-07-18 16:29:46 +000034// ConstantFoldTerminator - If a terminator instruction is predicated on a
35// constant value, convert it into an unconditional branch to the constant
36// destination.
37//
38bool llvm::ConstantFoldTerminator(BasicBlock *BB) {
39 TerminatorInst *T = BB->getTerminator();
40
41 // Branch - See if we are conditional jumping on constant
42 if (BranchInst *BI = dyn_cast<BranchInst>(T)) {
43 if (BI->isUnconditional()) return false; // Can't optimize uncond branch
Gabor Greif0defde92009-01-30 18:21:13 +000044 BasicBlock *Dest1 = BI->getSuccessor(0);
45 BasicBlock *Dest2 = BI->getSuccessor(1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000046
47 if (ConstantInt *Cond = dyn_cast<ConstantInt>(BI->getCondition())) {
48 // Are we branching on constant?
49 // YES. Change to unconditional branch...
50 BasicBlock *Destination = Cond->getZExtValue() ? Dest1 : Dest2;
51 BasicBlock *OldDest = Cond->getZExtValue() ? Dest2 : Dest1;
52
53 //cerr << "Function: " << T->getParent()->getParent()
54 // << "\nRemoving branch from " << T->getParent()
55 // << "\n\nTo: " << OldDest << endl;
56
57 // Let the basic block know that we are letting go of it. Based on this,
58 // it will adjust it's PHI nodes.
59 assert(BI->getParent() && "Terminator not inserted in block!");
60 OldDest->removePredecessor(BI->getParent());
61
62 // Set the unconditional destination, and change the insn to be an
63 // unconditional branch.
64 BI->setUnconditionalDest(Destination);
65 return true;
66 } else if (Dest2 == Dest1) { // Conditional branch to same location?
67 // This branch matches something like this:
68 // br bool %cond, label %Dest, label %Dest
69 // and changes it into: br label %Dest
70
71 // Let the basic block know that we are letting go of one copy of it.
72 assert(BI->getParent() && "Terminator not inserted in block!");
73 Dest1->removePredecessor(BI->getParent());
74
75 // Change a conditional branch to unconditional.
76 BI->setUnconditionalDest(Dest1);
77 return true;
78 }
79 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(T)) {
80 // If we are switching on a constant, we can convert the switch into a
81 // single branch instruction!
82 ConstantInt *CI = dyn_cast<ConstantInt>(SI->getCondition());
83 BasicBlock *TheOnlyDest = SI->getSuccessor(0); // The default dest
84 BasicBlock *DefaultDest = TheOnlyDest;
85 assert(TheOnlyDest == SI->getDefaultDest() &&
86 "Default destination is not successor #0?");
87
88 // Figure out which case it goes to...
89 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i) {
90 // Found case matching a constant operand?
91 if (SI->getSuccessorValue(i) == CI) {
92 TheOnlyDest = SI->getSuccessor(i);
93 break;
94 }
95
96 // Check to see if this branch is going to the same place as the default
97 // dest. If so, eliminate it as an explicit compare.
98 if (SI->getSuccessor(i) == DefaultDest) {
99 // Remove this entry...
100 DefaultDest->removePredecessor(SI->getParent());
101 SI->removeCase(i);
102 --i; --e; // Don't skip an entry...
103 continue;
104 }
105
106 // Otherwise, check to see if the switch only branches to one destination.
107 // We do this by reseting "TheOnlyDest" to null when we find two non-equal
108 // destinations.
109 if (SI->getSuccessor(i) != TheOnlyDest) TheOnlyDest = 0;
110 }
111
112 if (CI && !TheOnlyDest) {
113 // Branching on a constant, but not any of the cases, go to the default
114 // successor.
115 TheOnlyDest = SI->getDefaultDest();
116 }
117
118 // If we found a single destination that we can fold the switch into, do so
119 // now.
120 if (TheOnlyDest) {
121 // Insert the new branch..
Gabor Greifd6da1d02008-04-06 20:25:17 +0000122 BranchInst::Create(TheOnlyDest, SI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000123 BasicBlock *BB = SI->getParent();
124
125 // Remove entries from PHI nodes which we no longer branch to...
126 for (unsigned i = 0, e = SI->getNumSuccessors(); i != e; ++i) {
127 // Found case matching a constant operand?
128 BasicBlock *Succ = SI->getSuccessor(i);
129 if (Succ == TheOnlyDest)
130 TheOnlyDest = 0; // Don't modify the first branch to TheOnlyDest
131 else
132 Succ->removePredecessor(BB);
133 }
134
135 // Delete the old switch...
136 BB->getInstList().erase(SI);
137 return true;
138 } else if (SI->getNumSuccessors() == 2) {
139 // Otherwise, we can fold this switch into a conditional branch
140 // instruction if it has only one non-default destination.
141 Value *Cond = new ICmpInst(ICmpInst::ICMP_EQ, SI->getCondition(),
142 SI->getSuccessorValue(1), "cond", SI);
143 // Insert the new branch...
Gabor Greifd6da1d02008-04-06 20:25:17 +0000144 BranchInst::Create(SI->getSuccessor(1), SI->getSuccessor(0), Cond, SI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000145
146 // Delete the old switch...
Dan Gohmande087372008-06-21 22:08:46 +0000147 SI->eraseFromParent();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000148 return true;
149 }
150 }
151 return false;
152}
153
154
155//===----------------------------------------------------------------------===//
156// Local dead code elimination...
157//
158
Chris Lattner15ca9352008-11-27 22:57:53 +0000159/// isInstructionTriviallyDead - Return true if the result produced by the
160/// instruction is not used, and the instruction has no side effects.
161///
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000162bool llvm::isInstructionTriviallyDead(Instruction *I) {
163 if (!I->use_empty() || isa<TerminatorInst>(I)) return false;
164
Dale Johannesen4bb1f4a2009-03-03 23:30:00 +0000165 // We don't want debug info removed by anything this general.
166 if (isa<DbgInfoIntrinsic>(I)) return false;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000167
Duncan Sands2f500832009-05-06 06:49:50 +0000168 if (!I->mayHaveSideEffects()) return true;
169
170 // Special case intrinsics that "may have side effects" but can be deleted
171 // when dead.
Chris Lattner41847892007-12-29 00:59:12 +0000172 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I))
173 // Safe to delete llvm.stacksave if dead.
174 if (II->getIntrinsicID() == Intrinsic::stacksave)
175 return true;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000176 return false;
177}
178
Chris Lattner15ca9352008-11-27 22:57:53 +0000179/// RecursivelyDeleteTriviallyDeadInstructions - If the specified value is a
180/// trivially dead instruction, delete it. If that makes any of its operands
181/// trivially dead, delete them too, recursively.
Dan Gohmanbff6b582009-05-04 22:30:44 +0000182void llvm::RecursivelyDeleteTriviallyDeadInstructions(Value *V) {
Chris Lattner15ca9352008-11-27 22:57:53 +0000183 Instruction *I = dyn_cast<Instruction>(V);
Chris Lattnerac498502008-11-28 01:20:46 +0000184 if (!I || !I->use_empty() || !isInstructionTriviallyDead(I))
185 return;
Chris Lattner15ca9352008-11-27 22:57:53 +0000186
Chris Lattnerac498502008-11-28 01:20:46 +0000187 SmallVector<Instruction*, 16> DeadInsts;
188 DeadInsts.push_back(I);
Chris Lattner15ca9352008-11-27 22:57:53 +0000189
Chris Lattnerac498502008-11-28 01:20:46 +0000190 while (!DeadInsts.empty()) {
191 I = DeadInsts.back();
192 DeadInsts.pop_back();
Chris Lattneread0a2b2008-11-28 00:58:15 +0000193
Chris Lattnerac498502008-11-28 01:20:46 +0000194 // Null out all of the instruction's operands to see if any operand becomes
195 // dead as we go.
196 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
197 Value *OpV = I->getOperand(i);
198 I->setOperand(i, 0);
199
200 if (!OpV->use_empty()) continue;
201
202 // If the operand is an instruction that became dead as we nulled out the
203 // operand, and if it is 'trivially' dead, delete it in a future loop
204 // iteration.
205 if (Instruction *OpI = dyn_cast<Instruction>(OpV))
206 if (isInstructionTriviallyDead(OpI))
207 DeadInsts.push_back(OpI);
208 }
209
210 I->eraseFromParent();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000211 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000212}
Chris Lattner490fa482008-11-27 07:43:12 +0000213
Dan Gohman93efe962009-05-02 18:29:22 +0000214/// RecursivelyDeleteDeadPHINode - If the specified value is an effectively
215/// dead PHI node, due to being a def-use chain of single-use nodes that
216/// either forms a cycle or is terminated by a trivially dead instruction,
217/// delete it. If that makes any of its operands trivially dead, delete them
218/// too, recursively.
Dan Gohman93efe962009-05-02 18:29:22 +0000219void
Dan Gohmanbff6b582009-05-04 22:30:44 +0000220llvm::RecursivelyDeleteDeadPHINode(PHINode *PN) {
Dan Gohman93efe962009-05-02 18:29:22 +0000221
222 // We can remove a PHI if it is on a cycle in the def-use graph
223 // where each node in the cycle has degree one, i.e. only one use,
224 // and is an instruction with no side effects.
225 if (!PN->hasOneUse())
226 return;
227
228 SmallPtrSet<PHINode *, 4> PHIs;
229 PHIs.insert(PN);
230 for (Instruction *J = cast<Instruction>(*PN->use_begin());
Duncan Sands2f500832009-05-06 06:49:50 +0000231 J->hasOneUse() && !J->mayHaveSideEffects();
Dan Gohman93efe962009-05-02 18:29:22 +0000232 J = cast<Instruction>(*J->use_begin()))
233 // If we find a PHI more than once, we're on a cycle that
234 // won't prove fruitful.
235 if (PHINode *JP = dyn_cast<PHINode>(J))
236 if (!PHIs.insert(cast<PHINode>(JP))) {
237 // Break the cycle and delete the PHI and its operands.
238 JP->replaceAllUsesWith(UndefValue::get(JP->getType()));
Dan Gohmanbff6b582009-05-04 22:30:44 +0000239 RecursivelyDeleteTriviallyDeadInstructions(JP);
Dan Gohman93efe962009-05-02 18:29:22 +0000240 break;
241 }
242}
Chris Lattner15ca9352008-11-27 22:57:53 +0000243
Chris Lattner490fa482008-11-27 07:43:12 +0000244//===----------------------------------------------------------------------===//
245// Control Flow Graph Restructuring...
246//
247
248/// MergeBasicBlockIntoOnlyPred - DestBB is a block with one predecessor and its
249/// predecessor is known to have one successor (DestBB!). Eliminate the edge
250/// between them, moving the instructions in the predecessor into DestBB and
251/// deleting the predecessor block.
252///
253void llvm::MergeBasicBlockIntoOnlyPred(BasicBlock *DestBB) {
254 // If BB has single-entry PHI nodes, fold them.
255 while (PHINode *PN = dyn_cast<PHINode>(DestBB->begin())) {
256 Value *NewVal = PN->getIncomingValue(0);
257 // Replace self referencing PHI with undef, it must be dead.
258 if (NewVal == PN) NewVal = UndefValue::get(PN->getType());
259 PN->replaceAllUsesWith(NewVal);
260 PN->eraseFromParent();
261 }
262
263 BasicBlock *PredBB = DestBB->getSinglePredecessor();
264 assert(PredBB && "Block doesn't have a single predecessor!");
265
266 // Splice all the instructions from PredBB to DestBB.
267 PredBB->getTerminator()->eraseFromParent();
268 DestBB->getInstList().splice(DestBB->begin(), PredBB->getInstList());
269
270 // Anything that branched to PredBB now branches to DestBB.
271 PredBB->replaceAllUsesWith(DestBB);
272
273 // Nuke BB.
274 PredBB->eraseFromParent();
275}
Devang Patel83637b12009-02-10 07:00:59 +0000276
277/// OnlyUsedByDbgIntrinsics - Return true if the instruction I is only used
278/// by DbgIntrinsics. If DbgInUses is specified then the vector is filled
279/// with the DbgInfoIntrinsic that use the instruction I.
280bool llvm::OnlyUsedByDbgInfoIntrinsics(Instruction *I,
281 SmallVectorImpl<DbgInfoIntrinsic *> *DbgInUses) {
282 if (DbgInUses)
283 DbgInUses->clear();
284
285 for (Value::use_iterator UI = I->use_begin(), UE = I->use_end(); UI != UE;
286 ++UI) {
287 if (DbgInfoIntrinsic *DI = dyn_cast<DbgInfoIntrinsic>(*UI)) {
288 if (DbgInUses)
289 DbgInUses->push_back(DI);
290 } else {
291 if (DbgInUses)
292 DbgInUses->clear();
293 return false;
294 }
295 }
296 return true;
297}
Devang Patel06350be2009-03-06 00:19:37 +0000298
299/// UserIsDebugInfo - Return true if U is a constant expr used by
300/// llvm.dbg.variable or llvm.dbg.global_variable
301bool llvm::UserIsDebugInfo(User *U) {
302 ConstantExpr *CE = dyn_cast<ConstantExpr>(U);
303
304 if (!CE || CE->getNumUses() != 1)
305 return false;
306
307 Constant *Init = dyn_cast<Constant>(CE->use_back());
308 if (!Init || Init->getNumUses() != 1)
309 return false;
310
311 GlobalVariable *GV = dyn_cast<GlobalVariable>(Init->use_back());
312 if (!GV || !GV->hasInitializer() || GV->getInitializer() != Init)
313 return false;
314
315 DIVariable DV(GV);
316 if (!DV.isNull())
317 return true; // User is llvm.dbg.variable
318
319 DIGlobalVariable DGV(GV);
320 if (!DGV.isNull())
321 return true; // User is llvm.dbg.global_variable
322
323 return false;
324}
325
326/// RemoveDbgInfoUser - Remove an User which is representing debug info.
327void llvm::RemoveDbgInfoUser(User *U) {
328 assert (UserIsDebugInfo(U) && "Unexpected User!");
329 ConstantExpr *CE = cast<ConstantExpr>(U);
330 while (!CE->use_empty()) {
331 Constant *C = cast<Constant>(CE->use_back());
332 while (!C->use_empty()) {
333 GlobalVariable *GV = cast<GlobalVariable>(C->use_back());
334 GV->eraseFromParent();
335 }
336 C->destroyConstant();
337 }
338 CE->destroyConstant();
339}