blob: c54765b42785177f7416814de93e276222944a7b [file] [log] [blame]
Chris Lattner28537df2002-05-07 18:07:59 +00001//===-- Local.cpp - Functions to perform local transformations ------------===//
John Criswell482202a2003-10-20 19:43:21 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file was developed by the LLVM research group and is distributed under
6// the University of Illinois Open Source License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
Chris Lattner28537df2002-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 Lattner2853a7e2004-01-12 18:35:03 +000016#include "llvm/Constants.h"
Chris Lattner6b052f212004-01-12 19:56:36 +000017#include "llvm/Instructions.h"
Chris Lattner04efa4b2003-12-19 05:56:28 +000018using namespace llvm;
Brian Gaeke960707c2003-11-11 22:41:34 +000019
Chris Lattner28537df2002-05-07 18:07:59 +000020//===----------------------------------------------------------------------===//
Misha Brukman373086d2003-05-20 21:01:22 +000021// Local constant propagation...
Chris Lattner28537df2002-05-07 18:07:59 +000022//
23
Chris Lattner04efa4b2003-12-19 05:56:28 +000024/// doConstantPropagation - If an instruction references constants, try to fold
25/// them together...
26///
27bool llvm::doConstantPropagation(BasicBlock::iterator &II) {
Chris Lattnerfda72b12002-06-25 16:12:52 +000028 if (Constant *C = ConstantFoldInstruction(II)) {
Chris Lattner28537df2002-05-07 18:07:59 +000029 // Replaces all of the uses of a variable with uses of the constant.
Chris Lattnerfda72b12002-06-25 16:12:52 +000030 II->replaceAllUsesWith(C);
Chris Lattner28537df2002-05-07 18:07:59 +000031
32 // Remove the instruction from the basic block...
Chris Lattnerfda72b12002-06-25 16:12:52 +000033 II = II->getParent()->getInstList().erase(II);
Chris Lattner28537df2002-05-07 18:07:59 +000034 return true;
35 }
36
37 return false;
38}
39
Chris Lattnerfc6c8592004-01-12 18:25:22 +000040/// ConstantFoldInstruction - Attempt to constant fold the specified
41/// instruction. If successful, the constant result is returned, if not, null
42/// is returned. Note that this function can only fail when attempting to fold
43/// instructions like loads and stores, which have no constant expression form.
44///
45Constant *llvm::ConstantFoldInstruction(Instruction *I) {
46 if (PHINode *PN = dyn_cast<PHINode>(I)) {
47 if (PN->getNumIncomingValues() == 0)
48 return Constant::getNullValue(PN->getType());
49
50 Constant *Result = dyn_cast<Constant>(PN->getIncomingValue(0));
51 if (Result == 0) return 0;
52
53 // Handle PHI nodes specially here...
54 for (unsigned i = 1, e = PN->getNumIncomingValues(); i != e; ++i)
55 if (PN->getIncomingValue(i) != Result && PN->getIncomingValue(i) != PN)
56 return 0; // Not all the same incoming constants...
57
58 // If we reach here, all incoming values are the same constant.
59 return Result;
60 }
61
62 Constant *Op0 = 0, *Op1 = 0;
63 switch (I->getNumOperands()) {
64 default:
65 case 2:
66 Op1 = dyn_cast<Constant>(I->getOperand(1));
67 if (Op1 == 0) return 0; // Not a constant?, can't fold
68 case 1:
69 Op0 = dyn_cast<Constant>(I->getOperand(0));
70 if (Op0 == 0) return 0; // Not a constant?, can't fold
71 break;
72 case 0: return 0;
73 }
74
Chris Lattner42996372004-01-12 19:10:58 +000075 if (isa<BinaryOperator>(I) || isa<ShiftInst>(I))
Chris Lattnerfc6c8592004-01-12 18:25:22 +000076 return ConstantExpr::get(I->getOpcode(), Op0, Op1);
77
78 switch (I->getOpcode()) {
79 default: return 0;
80 case Instruction::Cast:
81 return ConstantExpr::getCast(Op0, I->getType());
Chris Lattnercb015ee2004-03-12 05:53:03 +000082 case Instruction::Select:
83 if (Constant *Op2 = dyn_cast<Constant>(I->getOperand(2)))
84 return ConstantExpr::getSelect(Op0, Op1, Op2);
85 return 0;
Chris Lattnerfc6c8592004-01-12 18:25:22 +000086 case Instruction::GetElementPtr:
87 std::vector<Constant*> IdxList;
88 IdxList.reserve(I->getNumOperands()-1);
89 if (Op1) IdxList.push_back(Op1);
90 for (unsigned i = 2, e = I->getNumOperands(); i != e; ++i)
91 if (Constant *C = dyn_cast<Constant>(I->getOperand(i)))
92 IdxList.push_back(C);
93 else
94 return 0; // Non-constant operand
95 return ConstantExpr::getGetElementPtr(Op0, IdxList);
96 }
97}
98
Chris Lattner28537df2002-05-07 18:07:59 +000099// ConstantFoldTerminator - If a terminator instruction is predicated on a
100// constant value, convert it into an unconditional branch to the constant
101// destination.
102//
Chris Lattner04efa4b2003-12-19 05:56:28 +0000103bool llvm::ConstantFoldTerminator(BasicBlock *BB) {
Chris Lattner4b009ad2002-05-21 20:04:50 +0000104 TerminatorInst *T = BB->getTerminator();
105
Chris Lattner28537df2002-05-07 18:07:59 +0000106 // Branch - See if we are conditional jumping on constant
107 if (BranchInst *BI = dyn_cast<BranchInst>(T)) {
108 if (BI->isUnconditional()) return false; // Can't optimize uncond branch
109 BasicBlock *Dest1 = cast<BasicBlock>(BI->getOperand(0));
110 BasicBlock *Dest2 = cast<BasicBlock>(BI->getOperand(1));
111
112 if (ConstantBool *Cond = dyn_cast<ConstantBool>(BI->getCondition())) {
113 // Are we branching on constant?
114 // YES. Change to unconditional branch...
115 BasicBlock *Destination = Cond->getValue() ? Dest1 : Dest2;
116 BasicBlock *OldDest = Cond->getValue() ? Dest2 : Dest1;
117
118 //cerr << "Function: " << T->getParent()->getParent()
119 // << "\nRemoving branch from " << T->getParent()
120 // << "\n\nTo: " << OldDest << endl;
121
122 // Let the basic block know that we are letting go of it. Based on this,
123 // it will adjust it's PHI nodes.
124 assert(BI->getParent() && "Terminator not inserted in block!");
125 OldDest->removePredecessor(BI->getParent());
126
127 // Set the unconditional destination, and change the insn to be an
128 // unconditional branch.
129 BI->setUnconditionalDest(Destination);
Chris Lattner28537df2002-05-07 18:07:59 +0000130 return true;
Chris Lattner4b7e3362003-08-17 19:34:55 +0000131 } else if (Dest2 == Dest1) { // Conditional branch to same location?
Chris Lattner28537df2002-05-07 18:07:59 +0000132 // This branch matches something like this:
133 // br bool %cond, label %Dest, label %Dest
134 // and changes it into: br label %Dest
135
136 // Let the basic block know that we are letting go of one copy of it.
137 assert(BI->getParent() && "Terminator not inserted in block!");
138 Dest1->removePredecessor(BI->getParent());
139
140 // Change a conditional branch to unconditional.
141 BI->setUnconditionalDest(Dest1);
142 return true;
143 }
Chris Lattner821deee2003-08-17 20:21:14 +0000144 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(T)) {
145 // If we are switching on a constant, we can convert the switch into a
146 // single branch instruction!
147 ConstantInt *CI = dyn_cast<ConstantInt>(SI->getCondition());
148 BasicBlock *TheOnlyDest = SI->getSuccessor(0); // The default dest
Chris Lattnerc54d6082003-08-23 23:18:19 +0000149 BasicBlock *DefaultDest = TheOnlyDest;
150 assert(TheOnlyDest == SI->getDefaultDest() &&
151 "Default destination is not successor #0?");
Chris Lattner031340a2003-08-17 19:41:53 +0000152
Chris Lattner821deee2003-08-17 20:21:14 +0000153 // Figure out which case it goes to...
154 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i) {
155 // Found case matching a constant operand?
156 if (SI->getSuccessorValue(i) == CI) {
157 TheOnlyDest = SI->getSuccessor(i);
158 break;
159 }
Chris Lattner031340a2003-08-17 19:41:53 +0000160
Chris Lattnerc54d6082003-08-23 23:18:19 +0000161 // Check to see if this branch is going to the same place as the default
162 // dest. If so, eliminate it as an explicit compare.
163 if (SI->getSuccessor(i) == DefaultDest) {
164 // Remove this entry...
165 DefaultDest->removePredecessor(SI->getParent());
166 SI->removeCase(i);
167 --i; --e; // Don't skip an entry...
168 continue;
169 }
170
Chris Lattner821deee2003-08-17 20:21:14 +0000171 // Otherwise, check to see if the switch only branches to one destination.
172 // We do this by reseting "TheOnlyDest" to null when we find two non-equal
173 // destinations.
174 if (SI->getSuccessor(i) != TheOnlyDest) TheOnlyDest = 0;
Chris Lattner031340a2003-08-17 19:41:53 +0000175 }
176
Chris Lattner821deee2003-08-17 20:21:14 +0000177 if (CI && !TheOnlyDest) {
178 // Branching on a constant, but not any of the cases, go to the default
179 // successor.
180 TheOnlyDest = SI->getDefaultDest();
181 }
182
183 // If we found a single destination that we can fold the switch into, do so
184 // now.
185 if (TheOnlyDest) {
186 // Insert the new branch..
187 new BranchInst(TheOnlyDest, SI);
188 BasicBlock *BB = SI->getParent();
189
190 // Remove entries from PHI nodes which we no longer branch to...
191 for (unsigned i = 0, e = SI->getNumSuccessors(); i != e; ++i) {
192 // Found case matching a constant operand?
193 BasicBlock *Succ = SI->getSuccessor(i);
194 if (Succ == TheOnlyDest)
195 TheOnlyDest = 0; // Don't modify the first branch to TheOnlyDest
196 else
197 Succ->removePredecessor(BB);
198 }
199
200 // Delete the old switch...
201 BB->getInstList().erase(SI);
202 return true;
203 } else if (SI->getNumSuccessors() == 2) {
204 // Otherwise, we can fold this switch into a conditional branch
205 // instruction if it has only one non-default destination.
206 Value *Cond = new SetCondInst(Instruction::SetEQ, SI->getCondition(),
207 SI->getSuccessorValue(1), "cond", SI);
208 // Insert the new branch...
209 new BranchInst(SI->getSuccessor(1), SI->getSuccessor(0), Cond, SI);
210
211 // Delete the old switch...
212 SI->getParent()->getInstList().erase(SI);
213 return true;
214 }
Chris Lattner28537df2002-05-07 18:07:59 +0000215 }
216 return false;
217}
218
219
220
221//===----------------------------------------------------------------------===//
222// Local dead code elimination...
223//
224
Chris Lattner04efa4b2003-12-19 05:56:28 +0000225bool llvm::isInstructionTriviallyDead(Instruction *I) {
Chris Lattner4869f372003-02-24 20:48:32 +0000226 return I->use_empty() && !I->mayWriteToMemory() && !isa<TerminatorInst>(I);
Chris Lattner28537df2002-05-07 18:07:59 +0000227}
228
229// dceInstruction - Inspect the instruction at *BBI and figure out if it's
230// [trivially] dead. If so, remove the instruction and update the iterator
231// to point to the instruction that immediately succeeded the original
232// instruction.
233//
Chris Lattner04efa4b2003-12-19 05:56:28 +0000234bool llvm::dceInstruction(BasicBlock::iterator &BBI) {
Chris Lattner28537df2002-05-07 18:07:59 +0000235 // Look for un"used" definitions...
Chris Lattnerfda72b12002-06-25 16:12:52 +0000236 if (isInstructionTriviallyDead(BBI)) {
237 BBI = BBI->getParent()->getInstList().erase(BBI); // Bye bye
Chris Lattner28537df2002-05-07 18:07:59 +0000238 return true;
239 }
240 return false;
241}
Brian Gaeke960707c2003-11-11 22:41:34 +0000242
Chris Lattner04efa4b2003-12-19 05:56:28 +0000243//===----------------------------------------------------------------------===//
244// PHI Instruction Simplification
245//
246
247/// hasConstantValue - If the specified PHI node always merges together the same
248/// value, return the value, otherwise return null.
249///
250Value *llvm::hasConstantValue(PHINode *PN) {
251 // If the PHI node only has one incoming value, eliminate the PHI node...
252 if (PN->getNumIncomingValues() == 1)
253 return PN->getIncomingValue(0);
254
255 // Otherwise if all of the incoming values are the same for the PHI, replace
256 // the PHI node with the incoming value.
257 //
258 Value *InVal = 0;
259 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
260 if (PN->getIncomingValue(i) != PN) // Not the PHI node itself...
261 if (InVal && PN->getIncomingValue(i) != InVal)
262 return 0; // Not the same, bail out.
263 else
264 InVal = PN->getIncomingValue(i);
265
266 // The only case that could cause InVal to be null is if we have a PHI node
267 // that only has entries for itself. In this case, there is no entry into the
268 // loop, so kill the PHI.
269 //
270 if (InVal == 0) InVal = Constant::getNullValue(PN->getType());
271
272 // All of the incoming values are the same, return the value now.
273 return InVal;
274}