blob: 236ec4b8bea953dc47acbe1d50631bf7211430b0 [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//
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.
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"
Chris Lattnerc5f52e62005-09-26 05:27:10 +000017#include "llvm/DerivedTypes.h"
Chris Lattner7822c2a2004-01-12 19:56:36 +000018#include "llvm/Instructions.h"
Chris Lattnercf110352004-06-11 06:16:23 +000019#include "llvm/Intrinsics.h"
Chris Lattnercbbc6b72005-10-27 16:34:00 +000020#include "llvm/Analysis/ConstantFolding.h"
Chris Lattnerc5f52e62005-09-26 05:27:10 +000021#include "llvm/Support/GetElementPtrTypeIterator.h"
22#include "llvm/Support/MathExtras.h"
Alkis Evlogimenos09233fb2004-04-21 16:11:40 +000023#include <cerrno>
Chris Lattnerabbc2dd2003-12-19 05:56:28 +000024using namespace llvm;
Brian Gaeked0fde302003-11-11 22:41:34 +000025
Chris Lattner4d1e46e2002-05-07 18:07:59 +000026//===----------------------------------------------------------------------===//
Misha Brukman82c89b92003-05-20 21:01:22 +000027// Local constant propagation...
Chris Lattner4d1e46e2002-05-07 18:07:59 +000028//
29
Chris Lattnerabbc2dd2003-12-19 05:56:28 +000030/// doConstantPropagation - If an instruction references constants, try to fold
31/// them together...
32///
33bool llvm::doConstantPropagation(BasicBlock::iterator &II) {
Chris Lattner18961502002-06-25 16:12:52 +000034 if (Constant *C = ConstantFoldInstruction(II)) {
Chris Lattner4d1e46e2002-05-07 18:07:59 +000035 // Replaces all of the uses of a variable with uses of the constant.
Chris Lattner18961502002-06-25 16:12:52 +000036 II->replaceAllUsesWith(C);
Misha Brukmanfd939082005-04-21 23:48:37 +000037
Chris Lattner4d1e46e2002-05-07 18:07:59 +000038 // Remove the instruction from the basic block...
Chris Lattner18961502002-06-25 16:12:52 +000039 II = II->getParent()->getInstList().erase(II);
Chris Lattner4d1e46e2002-05-07 18:07:59 +000040 return true;
41 }
42
43 return false;
44}
45
Chris Lattner8f90b002004-01-12 18:25:22 +000046/// ConstantFoldInstruction - Attempt to constant fold the specified
47/// instruction. If successful, the constant result is returned, if not, null
48/// is returned. Note that this function can only fail when attempting to fold
49/// instructions like loads and stores, which have no constant expression form.
50///
51Constant *llvm::ConstantFoldInstruction(Instruction *I) {
52 if (PHINode *PN = dyn_cast<PHINode>(I)) {
53 if (PN->getNumIncomingValues() == 0)
54 return Constant::getNullValue(PN->getType());
Misha Brukmanfd939082005-04-21 23:48:37 +000055
Chris Lattner8f90b002004-01-12 18:25:22 +000056 Constant *Result = dyn_cast<Constant>(PN->getIncomingValue(0));
57 if (Result == 0) return 0;
58
59 // Handle PHI nodes specially here...
60 for (unsigned i = 1, e = PN->getNumIncomingValues(); i != e; ++i)
61 if (PN->getIncomingValue(i) != Result && PN->getIncomingValue(i) != PN)
62 return 0; // Not all the same incoming constants...
Misha Brukmanfd939082005-04-21 23:48:37 +000063
Chris Lattner8f90b002004-01-12 18:25:22 +000064 // If we reach here, all incoming values are the same constant.
65 return Result;
66 }
67
68 Constant *Op0 = 0, *Op1 = 0;
69 switch (I->getNumOperands()) {
70 default:
71 case 2:
72 Op1 = dyn_cast<Constant>(I->getOperand(1));
73 if (Op1 == 0) return 0; // Not a constant?, can't fold
Reid Spencere4d87aa2006-12-23 06:05:41 +000074 /* FALL THROUGH */
Chris Lattner8f90b002004-01-12 18:25:22 +000075 case 1:
76 Op0 = dyn_cast<Constant>(I->getOperand(0));
77 if (Op0 == 0) return 0; // Not a constant?, can't fold
78 break;
79 case 0: return 0;
80 }
81
Chris Lattner4b30fcb2006-05-27 01:18:04 +000082 if (isa<BinaryOperator>(I) || isa<ShiftInst>(I)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +000083 return ConstantExpr::get(I->getOpcode(), Op0, Op1);
84 } else if (isa<ICmpInst>(I)) {
85 return ConstantExpr::getICmp(cast<ICmpInst>(I)->getPredicate(), Op0, Op1);
86 } else if (isa<FCmpInst>(I)) {
87 return ConstantExpr::getFCmp(cast<FCmpInst>(I)->getPredicate(), Op0, Op1);
Chris Lattner4b30fcb2006-05-27 01:18:04 +000088 }
Chris Lattner8f90b002004-01-12 18:25:22 +000089
Reid Spencere4d87aa2006-12-23 06:05:41 +000090 // Scan the operand list, checking to see if they are all constants, if so,
Chris Lattner4b30fcb2006-05-27 01:18:04 +000091 // hand off to ConstantFoldInstOperands.
92 std::vector<Constant*> Ops;
93 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
94 if (Constant *Op = dyn_cast<Constant>(I->getOperand(i)))
95 Ops.push_back(Op);
96 else
97 return 0; // All operands not constant!
98
Reid Spencere4d87aa2006-12-23 06:05:41 +000099 return ConstantFoldInstOperands(I, Ops);
Chris Lattner4b30fcb2006-05-27 01:18:04 +0000100}
101
102/// ConstantFoldInstOperands - Attempt to constant fold an instruction with the
103/// specified opcode and operands. If successful, the constant result is
104/// returned, if not, null is returned. Note that this function can fail when
105/// attempting to fold instructions like loads and stores, which have no
106/// constant expression form.
107///
Reid Spencere4d87aa2006-12-23 06:05:41 +0000108Constant *llvm::ConstantFoldInstOperands(const Instruction* I,
Chris Lattner4b30fcb2006-05-27 01:18:04 +0000109 const std::vector<Constant*> &Ops) {
Reid Spencere4d87aa2006-12-23 06:05:41 +0000110 unsigned Opc = I->getOpcode();
111 const Type *DestTy = I->getType();
112
113 // Handle easy binops first
114 if (isa<BinaryOperator>(I))
Chris Lattner4b30fcb2006-05-27 01:18:04 +0000115 return ConstantExpr::get(Opc, Ops[0], Ops[1]);
116
117 switch (Opc) {
Chris Lattner8f90b002004-01-12 18:25:22 +0000118 default: return 0;
Chris Lattner4b30fcb2006-05-27 01:18:04 +0000119 case Instruction::Call:
120 if (Function *F = dyn_cast<Function>(Ops[0])) {
121 if (canConstantFoldCallTo(F)) {
122 std::vector<Constant*> Args(Ops.begin()+1, Ops.end());
123 return ConstantFoldCall(F, Args);
124 }
125 }
126 return 0;
Reid Spencere4d87aa2006-12-23 06:05:41 +0000127 case Instruction::ICmp:
128 case Instruction::FCmp:
129 return ConstantExpr::getCompare(cast<CmpInst>(I)->getPredicate(), Ops[0],
130 Ops[1]);
Chris Lattner4b30fcb2006-05-27 01:18:04 +0000131 case Instruction::Shl:
Reid Spencer3822ff52006-11-08 06:47:33 +0000132 case Instruction::LShr:
133 case Instruction::AShr:
Chris Lattner4b30fcb2006-05-27 01:18:04 +0000134 return ConstantExpr::get(Opc, Ops[0], Ops[1]);
Reid Spencer3da59db2006-11-27 01:05:10 +0000135 case Instruction::Trunc:
136 case Instruction::ZExt:
137 case Instruction::SExt:
138 case Instruction::FPTrunc:
139 case Instruction::FPExt:
140 case Instruction::UIToFP:
141 case Instruction::SIToFP:
142 case Instruction::FPToUI:
143 case Instruction::FPToSI:
144 case Instruction::PtrToInt:
145 case Instruction::IntToPtr:
146 case Instruction::BitCast:
147 return ConstantExpr::getCast(Opc, Ops[0], DestTy);
Chris Lattner17fd2732004-03-12 05:53:03 +0000148 case Instruction::Select:
Chris Lattner4b30fcb2006-05-27 01:18:04 +0000149 return ConstantExpr::getSelect(Ops[0], Ops[1], Ops[2]);
Robert Bocchinob52ee7f2006-01-10 19:05:34 +0000150 case Instruction::ExtractElement:
Chris Lattner4b30fcb2006-05-27 01:18:04 +0000151 return ConstantExpr::getExtractElement(Ops[0], Ops[1]);
Robert Bocchino956fd722006-01-17 20:07:07 +0000152 case Instruction::InsertElement:
Chris Lattner4b30fcb2006-05-27 01:18:04 +0000153 return ConstantExpr::getInsertElement(Ops[0], Ops[1], Ops[2]);
Chris Lattner543abdf2006-04-08 01:19:12 +0000154 case Instruction::ShuffleVector:
Chris Lattner4b30fcb2006-05-27 01:18:04 +0000155 return ConstantExpr::getShuffleVector(Ops[0], Ops[1], Ops[2]);
Chris Lattner8f90b002004-01-12 18:25:22 +0000156 case Instruction::GetElementPtr:
Chris Lattner4b30fcb2006-05-27 01:18:04 +0000157 return ConstantExpr::getGetElementPtr(Ops[0],
158 std::vector<Constant*>(Ops.begin()+1,
159 Ops.end()));
Chris Lattner8f90b002004-01-12 18:25:22 +0000160 }
161}
162
Chris Lattner4d1e46e2002-05-07 18:07:59 +0000163// ConstantFoldTerminator - If a terminator instruction is predicated on a
164// constant value, convert it into an unconditional branch to the constant
165// destination.
166//
Chris Lattnerabbc2dd2003-12-19 05:56:28 +0000167bool llvm::ConstantFoldTerminator(BasicBlock *BB) {
Chris Lattner76ae3442002-05-21 20:04:50 +0000168 TerminatorInst *T = BB->getTerminator();
Misha Brukmanfd939082005-04-21 23:48:37 +0000169
Chris Lattner4d1e46e2002-05-07 18:07:59 +0000170 // Branch - See if we are conditional jumping on constant
171 if (BranchInst *BI = dyn_cast<BranchInst>(T)) {
172 if (BI->isUnconditional()) return false; // Can't optimize uncond branch
173 BasicBlock *Dest1 = cast<BasicBlock>(BI->getOperand(0));
174 BasicBlock *Dest2 = cast<BasicBlock>(BI->getOperand(1));
175
176 if (ConstantBool *Cond = dyn_cast<ConstantBool>(BI->getCondition())) {
177 // Are we branching on constant?
178 // YES. Change to unconditional branch...
179 BasicBlock *Destination = Cond->getValue() ? Dest1 : Dest2;
180 BasicBlock *OldDest = Cond->getValue() ? Dest2 : Dest1;
181
Misha Brukmanfd939082005-04-21 23:48:37 +0000182 //cerr << "Function: " << T->getParent()->getParent()
183 // << "\nRemoving branch from " << T->getParent()
Chris Lattner4d1e46e2002-05-07 18:07:59 +0000184 // << "\n\nTo: " << OldDest << endl;
185
186 // Let the basic block know that we are letting go of it. Based on this,
187 // it will adjust it's PHI nodes.
188 assert(BI->getParent() && "Terminator not inserted in block!");
189 OldDest->removePredecessor(BI->getParent());
190
191 // Set the unconditional destination, and change the insn to be an
192 // unconditional branch.
193 BI->setUnconditionalDest(Destination);
Chris Lattner4d1e46e2002-05-07 18:07:59 +0000194 return true;
Chris Lattner342a9d12003-08-17 19:34:55 +0000195 } else if (Dest2 == Dest1) { // Conditional branch to same location?
Misha Brukmanfd939082005-04-21 23:48:37 +0000196 // This branch matches something like this:
Chris Lattner4d1e46e2002-05-07 18:07:59 +0000197 // br bool %cond, label %Dest, label %Dest
198 // and changes it into: br label %Dest
199
200 // Let the basic block know that we are letting go of one copy of it.
201 assert(BI->getParent() && "Terminator not inserted in block!");
202 Dest1->removePredecessor(BI->getParent());
203
204 // Change a conditional branch to unconditional.
205 BI->setUnconditionalDest(Dest1);
206 return true;
207 }
Chris Lattner10b1f5a2003-08-17 20:21:14 +0000208 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(T)) {
209 // If we are switching on a constant, we can convert the switch into a
210 // single branch instruction!
211 ConstantInt *CI = dyn_cast<ConstantInt>(SI->getCondition());
212 BasicBlock *TheOnlyDest = SI->getSuccessor(0); // The default dest
Chris Lattner7d6c24c2003-08-23 23:18:19 +0000213 BasicBlock *DefaultDest = TheOnlyDest;
214 assert(TheOnlyDest == SI->getDefaultDest() &&
215 "Default destination is not successor #0?");
Chris Lattner694e37f2003-08-17 19:41:53 +0000216
Chris Lattner10b1f5a2003-08-17 20:21:14 +0000217 // Figure out which case it goes to...
218 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i) {
219 // Found case matching a constant operand?
220 if (SI->getSuccessorValue(i) == CI) {
221 TheOnlyDest = SI->getSuccessor(i);
222 break;
223 }
Chris Lattner694e37f2003-08-17 19:41:53 +0000224
Chris Lattner7d6c24c2003-08-23 23:18:19 +0000225 // Check to see if this branch is going to the same place as the default
226 // dest. If so, eliminate it as an explicit compare.
227 if (SI->getSuccessor(i) == DefaultDest) {
228 // Remove this entry...
229 DefaultDest->removePredecessor(SI->getParent());
230 SI->removeCase(i);
231 --i; --e; // Don't skip an entry...
232 continue;
233 }
234
Chris Lattner10b1f5a2003-08-17 20:21:14 +0000235 // Otherwise, check to see if the switch only branches to one destination.
236 // We do this by reseting "TheOnlyDest" to null when we find two non-equal
237 // destinations.
238 if (SI->getSuccessor(i) != TheOnlyDest) TheOnlyDest = 0;
Chris Lattner694e37f2003-08-17 19:41:53 +0000239 }
240
Chris Lattner10b1f5a2003-08-17 20:21:14 +0000241 if (CI && !TheOnlyDest) {
242 // Branching on a constant, but not any of the cases, go to the default
243 // successor.
244 TheOnlyDest = SI->getDefaultDest();
245 }
246
247 // If we found a single destination that we can fold the switch into, do so
248 // now.
249 if (TheOnlyDest) {
250 // Insert the new branch..
251 new BranchInst(TheOnlyDest, SI);
252 BasicBlock *BB = SI->getParent();
253
254 // Remove entries from PHI nodes which we no longer branch to...
255 for (unsigned i = 0, e = SI->getNumSuccessors(); i != e; ++i) {
256 // Found case matching a constant operand?
257 BasicBlock *Succ = SI->getSuccessor(i);
258 if (Succ == TheOnlyDest)
259 TheOnlyDest = 0; // Don't modify the first branch to TheOnlyDest
260 else
261 Succ->removePredecessor(BB);
262 }
263
264 // Delete the old switch...
265 BB->getInstList().erase(SI);
266 return true;
267 } else if (SI->getNumSuccessors() == 2) {
268 // Otherwise, we can fold this switch into a conditional branch
269 // instruction if it has only one non-default destination.
Reid Spencere4d87aa2006-12-23 06:05:41 +0000270 Value *Cond = new ICmpInst(ICmpInst::ICMP_EQ, SI->getCondition(),
271 SI->getSuccessorValue(1), "cond", SI);
Chris Lattner10b1f5a2003-08-17 20:21:14 +0000272 // Insert the new branch...
273 new BranchInst(SI->getSuccessor(1), SI->getSuccessor(0), Cond, SI);
274
275 // Delete the old switch...
276 SI->getParent()->getInstList().erase(SI);
277 return true;
278 }
Chris Lattner4d1e46e2002-05-07 18:07:59 +0000279 }
280 return false;
281}
282
Chris Lattnerc5f52e62005-09-26 05:27:10 +0000283/// ConstantFoldLoadThroughGEPConstantExpr - Given a constant and a
284/// getelementptr constantexpr, return the constant value being addressed by the
285/// constant expression, or null if something is funny and we can't decide.
286Constant *llvm::ConstantFoldLoadThroughGEPConstantExpr(Constant *C,
287 ConstantExpr *CE) {
288 if (CE->getOperand(1) != Constant::getNullValue(CE->getOperand(1)->getType()))
289 return 0; // Do not allow stepping over the value!
290
291 // Loop over all of the operands, tracking down which value we are
292 // addressing...
293 gep_type_iterator I = gep_type_begin(CE), E = gep_type_end(CE);
294 for (++I; I != E; ++I)
295 if (const StructType *STy = dyn_cast<StructType>(*I)) {
Reid Spencerb83eb642006-10-20 07:07:24 +0000296 ConstantInt *CU = cast<ConstantInt>(I.getOperand());
297 assert(CU->getZExtValue() < STy->getNumElements() &&
Chris Lattnerc5f52e62005-09-26 05:27:10 +0000298 "Struct index out of range!");
Reid Spencerb83eb642006-10-20 07:07:24 +0000299 unsigned El = (unsigned)CU->getZExtValue();
Chris Lattnerc5f52e62005-09-26 05:27:10 +0000300 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(C)) {
301 C = CS->getOperand(El);
302 } else if (isa<ConstantAggregateZero>(C)) {
303 C = Constant::getNullValue(STy->getElementType(El));
304 } else if (isa<UndefValue>(C)) {
305 C = UndefValue::get(STy->getElementType(El));
306 } else {
307 return 0;
308 }
309 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand())) {
Robert Bocchinod900c6a2006-01-19 23:53:23 +0000310 if (const ArrayType *ATy = dyn_cast<ArrayType>(*I)) {
Reid Spencerb83eb642006-10-20 07:07:24 +0000311 if (CI->getZExtValue() >= ATy->getNumElements())
Chris Lattner99f2af22006-05-25 21:25:12 +0000312 return 0;
Robert Bocchinod900c6a2006-01-19 23:53:23 +0000313 if (ConstantArray *CA = dyn_cast<ConstantArray>(C))
Reid Spencerb83eb642006-10-20 07:07:24 +0000314 C = CA->getOperand(CI->getZExtValue());
Robert Bocchinod900c6a2006-01-19 23:53:23 +0000315 else if (isa<ConstantAggregateZero>(C))
316 C = Constant::getNullValue(ATy->getElementType());
317 else if (isa<UndefValue>(C))
318 C = UndefValue::get(ATy->getElementType());
319 else
320 return 0;
321 } else if (const PackedType *PTy = dyn_cast<PackedType>(*I)) {
Reid Spencerb83eb642006-10-20 07:07:24 +0000322 if (CI->getZExtValue() >= PTy->getNumElements())
Chris Lattner99f2af22006-05-25 21:25:12 +0000323 return 0;
Robert Bocchinod900c6a2006-01-19 23:53:23 +0000324 if (ConstantPacked *CP = dyn_cast<ConstantPacked>(C))
Reid Spencerb83eb642006-10-20 07:07:24 +0000325 C = CP->getOperand(CI->getZExtValue());
Robert Bocchinod900c6a2006-01-19 23:53:23 +0000326 else if (isa<ConstantAggregateZero>(C))
327 C = Constant::getNullValue(PTy->getElementType());
328 else if (isa<UndefValue>(C))
329 C = UndefValue::get(PTy->getElementType());
330 else
331 return 0;
332 } else {
Chris Lattnerc5f52e62005-09-26 05:27:10 +0000333 return 0;
Robert Bocchinod900c6a2006-01-19 23:53:23 +0000334 }
Chris Lattnerc5f52e62005-09-26 05:27:10 +0000335 } else {
336 return 0;
337 }
338 return C;
339}
Chris Lattner4d1e46e2002-05-07 18:07:59 +0000340
341
342//===----------------------------------------------------------------------===//
343// Local dead code elimination...
344//
345
Chris Lattnerabbc2dd2003-12-19 05:56:28 +0000346bool llvm::isInstructionTriviallyDead(Instruction *I) {
Chris Lattnerec710c52005-05-06 05:27:34 +0000347 if (!I->use_empty() || isa<TerminatorInst>(I)) return false;
Jeff Cohen00b168892005-07-27 06:12:32 +0000348
Chris Lattnerec710c52005-05-06 05:27:34 +0000349 if (!I->mayWriteToMemory()) return true;
350
351 if (CallInst *CI = dyn_cast<CallInst>(I))
Chris Lattneraeebe7f2006-03-09 22:38:10 +0000352 if (Function *F = CI->getCalledFunction()) {
Chris Lattner7224f842006-04-02 03:35:01 +0000353 unsigned IntrinsicID = F->getIntrinsicID();
Chris Lattneraeebe7f2006-03-09 22:38:10 +0000354#define GET_SIDE_EFFECT_INFO
355#include "llvm/Intrinsics.gen"
356#undef GET_SIDE_EFFECT_INFO
357 }
Chris Lattnerec710c52005-05-06 05:27:34 +0000358 return false;
Chris Lattner4d1e46e2002-05-07 18:07:59 +0000359}
360
361// dceInstruction - Inspect the instruction at *BBI and figure out if it's
362// [trivially] dead. If so, remove the instruction and update the iterator
363// to point to the instruction that immediately succeeded the original
364// instruction.
365//
Chris Lattnerabbc2dd2003-12-19 05:56:28 +0000366bool llvm::dceInstruction(BasicBlock::iterator &BBI) {
Chris Lattner4d1e46e2002-05-07 18:07:59 +0000367 // Look for un"used" definitions...
Chris Lattner18961502002-06-25 16:12:52 +0000368 if (isInstructionTriviallyDead(BBI)) {
369 BBI = BBI->getParent()->getInstList().erase(BBI); // Bye bye
Chris Lattner4d1e46e2002-05-07 18:07:59 +0000370 return true;
371 }
372 return false;
373}