blob: 4be1b8717d28d3916f2e93f96454c15866842829 [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"
Devang Patelc79e1182009-03-06 00:19:37 +000017#include "llvm/GlobalVariable.h"
Chris Lattnerc5f52e62005-09-26 05:27:10 +000018#include "llvm/DerivedTypes.h"
Chris Lattner7822c2a2004-01-12 19:56:36 +000019#include "llvm/Instructions.h"
Chris Lattnercf110352004-06-11 06:16:23 +000020#include "llvm/Intrinsics.h"
Chris Lattner741c0ae2007-12-29 00:59:12 +000021#include "llvm/IntrinsicInst.h"
Chris Lattnercbbc6b72005-10-27 16:34:00 +000022#include "llvm/Analysis/ConstantFolding.h"
Devang Patelc79e1182009-03-06 00:19:37 +000023#include "llvm/Analysis/DebugInfo.h"
Chris Lattner9fa038d2007-01-30 23:13:49 +000024#include "llvm/Target/TargetData.h"
Chris Lattnerc5f52e62005-09-26 05:27:10 +000025#include "llvm/Support/GetElementPtrTypeIterator.h"
26#include "llvm/Support/MathExtras.h"
Chris Lattnerabbc2dd2003-12-19 05:56:28 +000027using namespace llvm;
Brian Gaeked0fde302003-11-11 22:41:34 +000028
Chris Lattner4d1e46e2002-05-07 18:07:59 +000029//===----------------------------------------------------------------------===//
Chris Lattner3481f242008-11-27 22:57:53 +000030// Local constant propagation.
Chris Lattner4d1e46e2002-05-07 18:07:59 +000031//
32
Chris Lattner4d1e46e2002-05-07 18:07:59 +000033// ConstantFoldTerminator - If a terminator instruction is predicated on a
34// constant value, convert it into an unconditional branch to the constant
35// destination.
36//
Chris Lattnerabbc2dd2003-12-19 05:56:28 +000037bool llvm::ConstantFoldTerminator(BasicBlock *BB) {
Chris Lattner76ae3442002-05-21 20:04:50 +000038 TerminatorInst *T = BB->getTerminator();
Misha Brukmanfd939082005-04-21 23:48:37 +000039
Chris Lattner4d1e46e2002-05-07 18:07:59 +000040 // Branch - See if we are conditional jumping on constant
41 if (BranchInst *BI = dyn_cast<BranchInst>(T)) {
42 if (BI->isUnconditional()) return false; // Can't optimize uncond branch
Gabor Greifc1bb13f2009-01-30 18:21:13 +000043 BasicBlock *Dest1 = BI->getSuccessor(0);
44 BasicBlock *Dest2 = BI->getSuccessor(1);
Chris Lattner4d1e46e2002-05-07 18:07:59 +000045
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +000046 if (ConstantInt *Cond = dyn_cast<ConstantInt>(BI->getCondition())) {
Chris Lattner4d1e46e2002-05-07 18:07:59 +000047 // Are we branching on constant?
48 // YES. Change to unconditional branch...
Reid Spencer579dca12007-01-12 04:24:46 +000049 BasicBlock *Destination = Cond->getZExtValue() ? Dest1 : Dest2;
50 BasicBlock *OldDest = Cond->getZExtValue() ? Dest2 : Dest1;
Chris Lattner4d1e46e2002-05-07 18:07:59 +000051
Misha Brukmanfd939082005-04-21 23:48:37 +000052 //cerr << "Function: " << T->getParent()->getParent()
53 // << "\nRemoving branch from " << T->getParent()
Chris Lattner4d1e46e2002-05-07 18:07:59 +000054 // << "\n\nTo: " << OldDest << endl;
55
56 // Let the basic block know that we are letting go of it. Based on this,
57 // it will adjust it's PHI nodes.
58 assert(BI->getParent() && "Terminator not inserted in block!");
59 OldDest->removePredecessor(BI->getParent());
60
61 // Set the unconditional destination, and change the insn to be an
62 // unconditional branch.
63 BI->setUnconditionalDest(Destination);
Chris Lattner4d1e46e2002-05-07 18:07:59 +000064 return true;
Chris Lattner342a9d12003-08-17 19:34:55 +000065 } else if (Dest2 == Dest1) { // Conditional branch to same location?
Misha Brukmanfd939082005-04-21 23:48:37 +000066 // This branch matches something like this:
Chris Lattner4d1e46e2002-05-07 18:07:59 +000067 // br bool %cond, label %Dest, label %Dest
68 // and changes it into: br label %Dest
69
70 // Let the basic block know that we are letting go of one copy of it.
71 assert(BI->getParent() && "Terminator not inserted in block!");
72 Dest1->removePredecessor(BI->getParent());
73
74 // Change a conditional branch to unconditional.
75 BI->setUnconditionalDest(Dest1);
76 return true;
77 }
Chris Lattner10b1f5a2003-08-17 20:21:14 +000078 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(T)) {
79 // If we are switching on a constant, we can convert the switch into a
80 // single branch instruction!
81 ConstantInt *CI = dyn_cast<ConstantInt>(SI->getCondition());
82 BasicBlock *TheOnlyDest = SI->getSuccessor(0); // The default dest
Chris Lattner7d6c24c2003-08-23 23:18:19 +000083 BasicBlock *DefaultDest = TheOnlyDest;
84 assert(TheOnlyDest == SI->getDefaultDest() &&
85 "Default destination is not successor #0?");
Chris Lattner694e37f2003-08-17 19:41:53 +000086
Chris Lattner10b1f5a2003-08-17 20:21:14 +000087 // Figure out which case it goes to...
88 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i) {
89 // Found case matching a constant operand?
90 if (SI->getSuccessorValue(i) == CI) {
91 TheOnlyDest = SI->getSuccessor(i);
92 break;
93 }
Chris Lattner694e37f2003-08-17 19:41:53 +000094
Chris Lattner7d6c24c2003-08-23 23:18:19 +000095 // Check to see if this branch is going to the same place as the default
96 // dest. If so, eliminate it as an explicit compare.
97 if (SI->getSuccessor(i) == DefaultDest) {
98 // Remove this entry...
99 DefaultDest->removePredecessor(SI->getParent());
100 SI->removeCase(i);
101 --i; --e; // Don't skip an entry...
102 continue;
103 }
104
Chris Lattner10b1f5a2003-08-17 20:21:14 +0000105 // Otherwise, check to see if the switch only branches to one destination.
106 // We do this by reseting "TheOnlyDest" to null when we find two non-equal
107 // destinations.
108 if (SI->getSuccessor(i) != TheOnlyDest) TheOnlyDest = 0;
Chris Lattner694e37f2003-08-17 19:41:53 +0000109 }
110
Chris Lattner10b1f5a2003-08-17 20:21:14 +0000111 if (CI && !TheOnlyDest) {
112 // Branching on a constant, but not any of the cases, go to the default
113 // successor.
114 TheOnlyDest = SI->getDefaultDest();
115 }
116
117 // If we found a single destination that we can fold the switch into, do so
118 // now.
119 if (TheOnlyDest) {
120 // Insert the new branch..
Gabor Greif051a9502008-04-06 20:25:17 +0000121 BranchInst::Create(TheOnlyDest, SI);
Chris Lattner10b1f5a2003-08-17 20:21:14 +0000122 BasicBlock *BB = SI->getParent();
123
124 // Remove entries from PHI nodes which we no longer branch to...
125 for (unsigned i = 0, e = SI->getNumSuccessors(); i != e; ++i) {
126 // Found case matching a constant operand?
127 BasicBlock *Succ = SI->getSuccessor(i);
128 if (Succ == TheOnlyDest)
129 TheOnlyDest = 0; // Don't modify the first branch to TheOnlyDest
130 else
131 Succ->removePredecessor(BB);
132 }
133
134 // Delete the old switch...
135 BB->getInstList().erase(SI);
136 return true;
137 } else if (SI->getNumSuccessors() == 2) {
138 // Otherwise, we can fold this switch into a conditional branch
139 // instruction if it has only one non-default destination.
Reid Spencere4d87aa2006-12-23 06:05:41 +0000140 Value *Cond = new ICmpInst(ICmpInst::ICMP_EQ, SI->getCondition(),
141 SI->getSuccessorValue(1), "cond", SI);
Chris Lattner10b1f5a2003-08-17 20:21:14 +0000142 // Insert the new branch...
Gabor Greif051a9502008-04-06 20:25:17 +0000143 BranchInst::Create(SI->getSuccessor(1), SI->getSuccessor(0), Cond, SI);
Chris Lattner10b1f5a2003-08-17 20:21:14 +0000144
145 // Delete the old switch...
Dan Gohman1adec832008-06-21 22:08:46 +0000146 SI->eraseFromParent();
Chris Lattner10b1f5a2003-08-17 20:21:14 +0000147 return true;
148 }
Chris Lattner4d1e46e2002-05-07 18:07:59 +0000149 }
150 return false;
151}
152
Chris Lattner4d1e46e2002-05-07 18:07:59 +0000153
154//===----------------------------------------------------------------------===//
155// Local dead code elimination...
156//
157
Chris Lattner3481f242008-11-27 22:57:53 +0000158/// isInstructionTriviallyDead - Return true if the result produced by the
159/// instruction is not used, and the instruction has no side effects.
160///
Chris Lattnerabbc2dd2003-12-19 05:56:28 +0000161bool llvm::isInstructionTriviallyDead(Instruction *I) {
Chris Lattnerec710c52005-05-06 05:27:34 +0000162 if (!I->use_empty() || isa<TerminatorInst>(I)) return false;
Jeff Cohen00b168892005-07-27 06:12:32 +0000163
Dale Johannesen127a7932009-03-03 23:30:00 +0000164 // We don't want debug info removed by anything this general.
165 if (isa<DbgInfoIntrinsic>(I)) return false;
166
Chris Lattner741c0ae2007-12-29 00:59:12 +0000167 if (!I->mayWriteToMemory())
168 return true;
Chris Lattnerec710c52005-05-06 05:27:34 +0000169
Chris Lattner741c0ae2007-12-29 00:59:12 +0000170 // Special case intrinsics that "may write to memory" but can be deleted when
171 // dead.
172 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I))
173 // Safe to delete llvm.stacksave if dead.
174 if (II->getIntrinsicID() == Intrinsic::stacksave)
175 return true;
176
Chris Lattnerec710c52005-05-06 05:27:34 +0000177 return false;
Chris Lattner4d1e46e2002-05-07 18:07:59 +0000178}
179
Chris Lattner3481f242008-11-27 22:57:53 +0000180/// RecursivelyDeleteTriviallyDeadInstructions - If the specified value is a
181/// trivially dead instruction, delete it. If that makes any of its operands
182/// trivially dead, delete them too, recursively.
Chris Lattner4f02c742008-11-27 23:14:34 +0000183///
184/// If DeadInst is specified, the vector is filled with the instructions that
185/// are actually deleted.
186void llvm::RecursivelyDeleteTriviallyDeadInstructions(Value *V,
187 SmallVectorImpl<Instruction*> *DeadInst) {
Chris Lattner3481f242008-11-27 22:57:53 +0000188 Instruction *I = dyn_cast<Instruction>(V);
Chris Lattner76057302008-11-28 01:20:46 +0000189 if (!I || !I->use_empty() || !isInstructionTriviallyDead(I))
190 return;
Chris Lattner3481f242008-11-27 22:57:53 +0000191
Chris Lattner76057302008-11-28 01:20:46 +0000192 SmallVector<Instruction*, 16> DeadInsts;
193 DeadInsts.push_back(I);
Chris Lattner3481f242008-11-27 22:57:53 +0000194
Chris Lattner76057302008-11-28 01:20:46 +0000195 while (!DeadInsts.empty()) {
196 I = DeadInsts.back();
197 DeadInsts.pop_back();
Chris Lattner28721772008-11-28 00:58:15 +0000198
Chris Lattner76057302008-11-28 01:20:46 +0000199 // If the client wanted to know, tell it about deleted instructions.
Chris Lattner4f02c742008-11-27 23:14:34 +0000200 if (DeadInst)
201 DeadInst->push_back(I);
Chris Lattner76057302008-11-28 01:20:46 +0000202
203 // Null out all of the instruction's operands to see if any operand becomes
204 // dead as we go.
205 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
206 Value *OpV = I->getOperand(i);
207 I->setOperand(i, 0);
208
209 if (!OpV->use_empty()) continue;
210
211 // If the operand is an instruction that became dead as we nulled out the
212 // operand, and if it is 'trivially' dead, delete it in a future loop
213 // iteration.
214 if (Instruction *OpI = dyn_cast<Instruction>(OpV))
215 if (isInstructionTriviallyDead(OpI))
216 DeadInsts.push_back(OpI);
217 }
218
219 I->eraseFromParent();
Chris Lattner4d1e46e2002-05-07 18:07:59 +0000220 }
Chris Lattner4d1e46e2002-05-07 18:07:59 +0000221}
Chris Lattnerb29714a2008-11-27 07:43:12 +0000222
Chris Lattner3481f242008-11-27 22:57:53 +0000223
Chris Lattnerb29714a2008-11-27 07:43:12 +0000224//===----------------------------------------------------------------------===//
225// Control Flow Graph Restructuring...
226//
227
228/// MergeBasicBlockIntoOnlyPred - DestBB is a block with one predecessor and its
229/// predecessor is known to have one successor (DestBB!). Eliminate the edge
230/// between them, moving the instructions in the predecessor into DestBB and
231/// deleting the predecessor block.
232///
233void llvm::MergeBasicBlockIntoOnlyPred(BasicBlock *DestBB) {
234 // If BB has single-entry PHI nodes, fold them.
235 while (PHINode *PN = dyn_cast<PHINode>(DestBB->begin())) {
236 Value *NewVal = PN->getIncomingValue(0);
237 // Replace self referencing PHI with undef, it must be dead.
238 if (NewVal == PN) NewVal = UndefValue::get(PN->getType());
239 PN->replaceAllUsesWith(NewVal);
240 PN->eraseFromParent();
241 }
242
243 BasicBlock *PredBB = DestBB->getSinglePredecessor();
244 assert(PredBB && "Block doesn't have a single predecessor!");
245
246 // Splice all the instructions from PredBB to DestBB.
247 PredBB->getTerminator()->eraseFromParent();
248 DestBB->getInstList().splice(DestBB->begin(), PredBB->getInstList());
249
250 // Anything that branched to PredBB now branches to DestBB.
251 PredBB->replaceAllUsesWith(DestBB);
252
253 // Nuke BB.
254 PredBB->eraseFromParent();
255}
Devang Patel4afc90d2009-02-10 07:00:59 +0000256
257/// OnlyUsedByDbgIntrinsics - Return true if the instruction I is only used
258/// by DbgIntrinsics. If DbgInUses is specified then the vector is filled
259/// with the DbgInfoIntrinsic that use the instruction I.
260bool llvm::OnlyUsedByDbgInfoIntrinsics(Instruction *I,
261 SmallVectorImpl<DbgInfoIntrinsic *> *DbgInUses) {
262 if (DbgInUses)
263 DbgInUses->clear();
264
265 for (Value::use_iterator UI = I->use_begin(), UE = I->use_end(); UI != UE;
266 ++UI) {
267 if (DbgInfoIntrinsic *DI = dyn_cast<DbgInfoIntrinsic>(*UI)) {
268 if (DbgInUses)
269 DbgInUses->push_back(DI);
270 } else {
271 if (DbgInUses)
272 DbgInUses->clear();
273 return false;
274 }
275 }
276 return true;
277}
Devang Patelc79e1182009-03-06 00:19:37 +0000278
279/// UserIsDebugInfo - Return true if U is a constant expr used by
280/// llvm.dbg.variable or llvm.dbg.global_variable
281bool llvm::UserIsDebugInfo(User *U) {
282 ConstantExpr *CE = dyn_cast<ConstantExpr>(U);
283
284 if (!CE || CE->getNumUses() != 1)
285 return false;
286
287 Constant *Init = dyn_cast<Constant>(CE->use_back());
288 if (!Init || Init->getNumUses() != 1)
289 return false;
290
291 GlobalVariable *GV = dyn_cast<GlobalVariable>(Init->use_back());
292 if (!GV || !GV->hasInitializer() || GV->getInitializer() != Init)
293 return false;
294
295 DIVariable DV(GV);
296 if (!DV.isNull())
297 return true; // User is llvm.dbg.variable
298
299 DIGlobalVariable DGV(GV);
300 if (!DGV.isNull())
301 return true; // User is llvm.dbg.global_variable
302
303 return false;
304}
305
306/// RemoveDbgInfoUser - Remove an User which is representing debug info.
307void llvm::RemoveDbgInfoUser(User *U) {
308 assert (UserIsDebugInfo(U) && "Unexpected User!");
309 ConstantExpr *CE = cast<ConstantExpr>(U);
310 while (!CE->use_empty()) {
311 Constant *C = cast<Constant>(CE->use_back());
312 while (!C->use_empty()) {
313 GlobalVariable *GV = cast<GlobalVariable>(C->use_back());
314 GV->eraseFromParent();
315 }
316 C->destroyConstant();
317 }
318 CE->destroyConstant();
319}