blob: 3b36362bb3932e2f960460fa43ada776784aa61e [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"
Dan Gohmanafc36a92009-05-02 18:29:22 +000022#include "llvm/ADT/SmallPtrSet.h"
Chris Lattnercbbc6b72005-10-27 16:34:00 +000023#include "llvm/Analysis/ConstantFolding.h"
Devang Patelc79e1182009-03-06 00:19:37 +000024#include "llvm/Analysis/DebugInfo.h"
Chris Lattner9fa038d2007-01-30 23:13:49 +000025#include "llvm/Target/TargetData.h"
Chris Lattnerc5f52e62005-09-26 05:27:10 +000026#include "llvm/Support/GetElementPtrTypeIterator.h"
27#include "llvm/Support/MathExtras.h"
Chris Lattnerabbc2dd2003-12-19 05:56:28 +000028using namespace llvm;
Brian Gaeked0fde302003-11-11 22:41:34 +000029
Chris Lattner4d1e46e2002-05-07 18:07:59 +000030//===----------------------------------------------------------------------===//
Chris Lattner3481f242008-11-27 22:57:53 +000031// Local constant propagation.
Chris Lattner4d1e46e2002-05-07 18:07:59 +000032//
33
Chris Lattner4d1e46e2002-05-07 18:07:59 +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//
Chris Lattnerabbc2dd2003-12-19 05:56:28 +000038bool llvm::ConstantFoldTerminator(BasicBlock *BB) {
Chris Lattner76ae3442002-05-21 20:04:50 +000039 TerminatorInst *T = BB->getTerminator();
Misha Brukmanfd939082005-04-21 23:48:37 +000040
Chris Lattner4d1e46e2002-05-07 18:07:59 +000041 // 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 Greifc1bb13f2009-01-30 18:21:13 +000044 BasicBlock *Dest1 = BI->getSuccessor(0);
45 BasicBlock *Dest2 = BI->getSuccessor(1);
Chris Lattner4d1e46e2002-05-07 18:07:59 +000046
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +000047 if (ConstantInt *Cond = dyn_cast<ConstantInt>(BI->getCondition())) {
Chris Lattner4d1e46e2002-05-07 18:07:59 +000048 // Are we branching on constant?
49 // YES. Change to unconditional branch...
Reid Spencer579dca12007-01-12 04:24:46 +000050 BasicBlock *Destination = Cond->getZExtValue() ? Dest1 : Dest2;
51 BasicBlock *OldDest = Cond->getZExtValue() ? Dest2 : Dest1;
Chris Lattner4d1e46e2002-05-07 18:07:59 +000052
Misha Brukmanfd939082005-04-21 23:48:37 +000053 //cerr << "Function: " << T->getParent()->getParent()
54 // << "\nRemoving branch from " << T->getParent()
Chris Lattner4d1e46e2002-05-07 18:07:59 +000055 // << "\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);
Chris Lattner4d1e46e2002-05-07 18:07:59 +000065 return true;
Chris Lattner342a9d12003-08-17 19:34:55 +000066 } else if (Dest2 == Dest1) { // Conditional branch to same location?
Misha Brukmanfd939082005-04-21 23:48:37 +000067 // This branch matches something like this:
Chris Lattner4d1e46e2002-05-07 18:07:59 +000068 // 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 }
Chris Lattner10b1f5a2003-08-17 20:21:14 +000079 } 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
Chris Lattner7d6c24c2003-08-23 23:18:19 +000084 BasicBlock *DefaultDest = TheOnlyDest;
85 assert(TheOnlyDest == SI->getDefaultDest() &&
86 "Default destination is not successor #0?");
Chris Lattner694e37f2003-08-17 19:41:53 +000087
Chris Lattner10b1f5a2003-08-17 20:21:14 +000088 // 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 }
Chris Lattner694e37f2003-08-17 19:41:53 +000095
Chris Lattner7d6c24c2003-08-23 23:18:19 +000096 // 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
Chris Lattner10b1f5a2003-08-17 20:21:14 +0000106 // 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;
Chris Lattner694e37f2003-08-17 19:41:53 +0000110 }
111
Chris Lattner10b1f5a2003-08-17 20:21:14 +0000112 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 Greif051a9502008-04-06 20:25:17 +0000122 BranchInst::Create(TheOnlyDest, SI);
Chris Lattner10b1f5a2003-08-17 20:21:14 +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.
Reid Spencere4d87aa2006-12-23 06:05:41 +0000141 Value *Cond = new ICmpInst(ICmpInst::ICMP_EQ, SI->getCondition(),
142 SI->getSuccessorValue(1), "cond", SI);
Chris Lattner10b1f5a2003-08-17 20:21:14 +0000143 // Insert the new branch...
Gabor Greif051a9502008-04-06 20:25:17 +0000144 BranchInst::Create(SI->getSuccessor(1), SI->getSuccessor(0), Cond, SI);
Chris Lattner10b1f5a2003-08-17 20:21:14 +0000145
146 // Delete the old switch...
Dan Gohman1adec832008-06-21 22:08:46 +0000147 SI->eraseFromParent();
Chris Lattner10b1f5a2003-08-17 20:21:14 +0000148 return true;
149 }
Chris Lattner4d1e46e2002-05-07 18:07:59 +0000150 }
151 return false;
152}
153
Chris Lattner4d1e46e2002-05-07 18:07:59 +0000154
155//===----------------------------------------------------------------------===//
156// Local dead code elimination...
157//
158
Chris Lattner3481f242008-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///
Chris Lattnerabbc2dd2003-12-19 05:56:28 +0000162bool llvm::isInstructionTriviallyDead(Instruction *I) {
Chris Lattnerec710c52005-05-06 05:27:34 +0000163 if (!I->use_empty() || isa<TerminatorInst>(I)) return false;
Jeff Cohen00b168892005-07-27 06:12:32 +0000164
Dale Johannesen127a7932009-03-03 23:30:00 +0000165 // We don't want debug info removed by anything this general.
166 if (isa<DbgInfoIntrinsic>(I)) return false;
167
Chris Lattner741c0ae2007-12-29 00:59:12 +0000168 if (!I->mayWriteToMemory())
169 return true;
Chris Lattnerec710c52005-05-06 05:27:34 +0000170
Chris Lattner741c0ae2007-12-29 00:59:12 +0000171 // Special case intrinsics that "may write to memory" but can be deleted when
172 // dead.
173 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I))
174 // Safe to delete llvm.stacksave if dead.
175 if (II->getIntrinsicID() == Intrinsic::stacksave)
176 return true;
177
Chris Lattnerec710c52005-05-06 05:27:34 +0000178 return false;
Chris Lattner4d1e46e2002-05-07 18:07:59 +0000179}
180
Dan Gohmanf9a77b72009-05-03 05:46:20 +0000181/// ~ValueDeletionListener - A trivial dtor, defined out of line to give the
182/// class a home.
183llvm::ValueDeletionListener::~ValueDeletionListener() {}
184
Chris Lattner3481f242008-11-27 22:57:53 +0000185/// RecursivelyDeleteTriviallyDeadInstructions - If the specified value is a
186/// trivially dead instruction, delete it. If that makes any of its operands
187/// trivially dead, delete them too, recursively.
Dan Gohmanf9a77b72009-05-03 05:46:20 +0000188///
189/// If a ValueDeletionListener is specified, it is notified of instructions that
190/// are actually deleted (before they are actually deleted).
191void llvm::RecursivelyDeleteTriviallyDeadInstructions(Value *V,
192 ValueDeletionListener *VDL) {
Chris Lattner3481f242008-11-27 22:57:53 +0000193 Instruction *I = dyn_cast<Instruction>(V);
Chris Lattner76057302008-11-28 01:20:46 +0000194 if (!I || !I->use_empty() || !isInstructionTriviallyDead(I))
195 return;
Chris Lattner3481f242008-11-27 22:57:53 +0000196
Chris Lattner76057302008-11-28 01:20:46 +0000197 SmallVector<Instruction*, 16> DeadInsts;
198 DeadInsts.push_back(I);
Chris Lattner3481f242008-11-27 22:57:53 +0000199
Chris Lattner76057302008-11-28 01:20:46 +0000200 while (!DeadInsts.empty()) {
201 I = DeadInsts.back();
202 DeadInsts.pop_back();
Chris Lattner28721772008-11-28 00:58:15 +0000203
Dan Gohmanf9a77b72009-05-03 05:46:20 +0000204 // If the client wanted to know, tell it about deleted instructions.
205 if (VDL)
206 VDL->ValueWillBeDeleted(I);
207
Chris Lattner76057302008-11-28 01:20:46 +0000208 // Null out all of the instruction's operands to see if any operand becomes
209 // dead as we go.
210 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
211 Value *OpV = I->getOperand(i);
212 I->setOperand(i, 0);
213
214 if (!OpV->use_empty()) continue;
215
216 // If the operand is an instruction that became dead as we nulled out the
217 // operand, and if it is 'trivially' dead, delete it in a future loop
218 // iteration.
219 if (Instruction *OpI = dyn_cast<Instruction>(OpV))
220 if (isInstructionTriviallyDead(OpI))
221 DeadInsts.push_back(OpI);
222 }
223
224 I->eraseFromParent();
Chris Lattner4d1e46e2002-05-07 18:07:59 +0000225 }
Chris Lattner4d1e46e2002-05-07 18:07:59 +0000226}
Chris Lattnerb29714a2008-11-27 07:43:12 +0000227
Dan Gohmanafc36a92009-05-02 18:29:22 +0000228/// RecursivelyDeleteDeadPHINode - If the specified value is an effectively
229/// dead PHI node, due to being a def-use chain of single-use nodes that
230/// either forms a cycle or is terminated by a trivially dead instruction,
231/// delete it. If that makes any of its operands trivially dead, delete them
232/// too, recursively.
Dan Gohmanf9a77b72009-05-03 05:46:20 +0000233///
234/// If a ValueDeletionListener is specified, it is notified of instructions that
235/// are actually deleted (before they are actually deleted).
Dan Gohmanafc36a92009-05-02 18:29:22 +0000236void
Dan Gohmanf9a77b72009-05-03 05:46:20 +0000237llvm::RecursivelyDeleteDeadPHINode(PHINode *PN, ValueDeletionListener *VDL) {
Dan Gohmanafc36a92009-05-02 18:29:22 +0000238
239 // We can remove a PHI if it is on a cycle in the def-use graph
240 // where each node in the cycle has degree one, i.e. only one use,
241 // and is an instruction with no side effects.
242 if (!PN->hasOneUse())
243 return;
244
245 SmallPtrSet<PHINode *, 4> PHIs;
246 PHIs.insert(PN);
247 for (Instruction *J = cast<Instruction>(*PN->use_begin());
248 J->hasOneUse() && !J->mayWriteToMemory();
249 J = cast<Instruction>(*J->use_begin()))
250 // If we find a PHI more than once, we're on a cycle that
251 // won't prove fruitful.
252 if (PHINode *JP = dyn_cast<PHINode>(J))
253 if (!PHIs.insert(cast<PHINode>(JP))) {
254 // Break the cycle and delete the PHI and its operands.
255 JP->replaceAllUsesWith(UndefValue::get(JP->getType()));
Dan Gohmanf9a77b72009-05-03 05:46:20 +0000256 RecursivelyDeleteTriviallyDeadInstructions(JP, VDL);
Dan Gohmanafc36a92009-05-02 18:29:22 +0000257 break;
258 }
259}
Chris Lattner3481f242008-11-27 22:57:53 +0000260
Chris Lattnerb29714a2008-11-27 07:43:12 +0000261//===----------------------------------------------------------------------===//
262// Control Flow Graph Restructuring...
263//
264
265/// MergeBasicBlockIntoOnlyPred - DestBB is a block with one predecessor and its
266/// predecessor is known to have one successor (DestBB!). Eliminate the edge
267/// between them, moving the instructions in the predecessor into DestBB and
268/// deleting the predecessor block.
269///
270void llvm::MergeBasicBlockIntoOnlyPred(BasicBlock *DestBB) {
271 // If BB has single-entry PHI nodes, fold them.
272 while (PHINode *PN = dyn_cast<PHINode>(DestBB->begin())) {
273 Value *NewVal = PN->getIncomingValue(0);
274 // Replace self referencing PHI with undef, it must be dead.
275 if (NewVal == PN) NewVal = UndefValue::get(PN->getType());
276 PN->replaceAllUsesWith(NewVal);
277 PN->eraseFromParent();
278 }
279
280 BasicBlock *PredBB = DestBB->getSinglePredecessor();
281 assert(PredBB && "Block doesn't have a single predecessor!");
282
283 // Splice all the instructions from PredBB to DestBB.
284 PredBB->getTerminator()->eraseFromParent();
285 DestBB->getInstList().splice(DestBB->begin(), PredBB->getInstList());
286
287 // Anything that branched to PredBB now branches to DestBB.
288 PredBB->replaceAllUsesWith(DestBB);
289
290 // Nuke BB.
291 PredBB->eraseFromParent();
292}
Devang Patel4afc90d2009-02-10 07:00:59 +0000293
294/// OnlyUsedByDbgIntrinsics - Return true if the instruction I is only used
295/// by DbgIntrinsics. If DbgInUses is specified then the vector is filled
296/// with the DbgInfoIntrinsic that use the instruction I.
297bool llvm::OnlyUsedByDbgInfoIntrinsics(Instruction *I,
298 SmallVectorImpl<DbgInfoIntrinsic *> *DbgInUses) {
299 if (DbgInUses)
300 DbgInUses->clear();
301
302 for (Value::use_iterator UI = I->use_begin(), UE = I->use_end(); UI != UE;
303 ++UI) {
304 if (DbgInfoIntrinsic *DI = dyn_cast<DbgInfoIntrinsic>(*UI)) {
305 if (DbgInUses)
306 DbgInUses->push_back(DI);
307 } else {
308 if (DbgInUses)
309 DbgInUses->clear();
310 return false;
311 }
312 }
313 return true;
314}
Devang Patelc79e1182009-03-06 00:19:37 +0000315
316/// UserIsDebugInfo - Return true if U is a constant expr used by
317/// llvm.dbg.variable or llvm.dbg.global_variable
318bool llvm::UserIsDebugInfo(User *U) {
319 ConstantExpr *CE = dyn_cast<ConstantExpr>(U);
320
321 if (!CE || CE->getNumUses() != 1)
322 return false;
323
324 Constant *Init = dyn_cast<Constant>(CE->use_back());
325 if (!Init || Init->getNumUses() != 1)
326 return false;
327
328 GlobalVariable *GV = dyn_cast<GlobalVariable>(Init->use_back());
329 if (!GV || !GV->hasInitializer() || GV->getInitializer() != Init)
330 return false;
331
332 DIVariable DV(GV);
333 if (!DV.isNull())
334 return true; // User is llvm.dbg.variable
335
336 DIGlobalVariable DGV(GV);
337 if (!DGV.isNull())
338 return true; // User is llvm.dbg.global_variable
339
340 return false;
341}
342
343/// RemoveDbgInfoUser - Remove an User which is representing debug info.
344void llvm::RemoveDbgInfoUser(User *U) {
345 assert (UserIsDebugInfo(U) && "Unexpected User!");
346 ConstantExpr *CE = cast<ConstantExpr>(U);
347 while (!CE->use_empty()) {
348 Constant *C = cast<Constant>(CE->use_back());
349 while (!C->use_empty()) {
350 GlobalVariable *GV = cast<GlobalVariable>(C->use_back());
351 GV->eraseFromParent();
352 }
353 C->destroyConstant();
354 }
355 CE->destroyConstant();
356}