blob: 772e09bea35cd6e4788eb0e94081c76f66678039 [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 Lattner9fa038d2007-01-30 23:13:49 +000021#include "llvm/Target/TargetData.h"
Chris Lattnerc5f52e62005-09-26 05:27:10 +000022#include "llvm/Support/GetElementPtrTypeIterator.h"
23#include "llvm/Support/MathExtras.h"
Chris Lattner9fa038d2007-01-30 23:13:49 +000024#include "llvm/ADT/SmallVector.h"
Alkis Evlogimenos09233fb2004-04-21 16:11:40 +000025#include <cerrno>
Chris Lattnerabbc2dd2003-12-19 05:56:28 +000026using namespace llvm;
Brian Gaeked0fde302003-11-11 22:41:34 +000027
Chris Lattner4d1e46e2002-05-07 18:07:59 +000028//===----------------------------------------------------------------------===//
Misha Brukman82c89b92003-05-20 21:01:22 +000029// Local constant propagation...
Chris Lattner4d1e46e2002-05-07 18:07:59 +000030//
31
Chris Lattnerabbc2dd2003-12-19 05:56:28 +000032/// doConstantPropagation - If an instruction references constants, try to fold
33/// them together...
34///
Chris Lattner9fa038d2007-01-30 23:13:49 +000035bool llvm::doConstantPropagation(BasicBlock::iterator &II,
36 const TargetData *TD) {
37 if (Constant *C = ConstantFoldInstruction(II, TD)) {
Chris Lattner4d1e46e2002-05-07 18:07:59 +000038 // Replaces all of the uses of a variable with uses of the constant.
Chris Lattner18961502002-06-25 16:12:52 +000039 II->replaceAllUsesWith(C);
Misha Brukmanfd939082005-04-21 23:48:37 +000040
Chris Lattner4d1e46e2002-05-07 18:07:59 +000041 // Remove the instruction from the basic block...
Chris Lattner18961502002-06-25 16:12:52 +000042 II = II->getParent()->getInstList().erase(II);
Chris Lattner4d1e46e2002-05-07 18:07:59 +000043 return true;
44 }
45
46 return false;
47}
48
Chris Lattner8f90b002004-01-12 18:25:22 +000049/// ConstantFoldInstruction - Attempt to constant fold the specified
50/// instruction. If successful, the constant result is returned, if not, null
51/// is returned. Note that this function can only fail when attempting to fold
52/// instructions like loads and stores, which have no constant expression form.
53///
Chris Lattner9fa038d2007-01-30 23:13:49 +000054Constant *llvm::ConstantFoldInstruction(Instruction *I, const TargetData *TD) {
Chris Lattner8f90b002004-01-12 18:25:22 +000055 if (PHINode *PN = dyn_cast<PHINode>(I)) {
56 if (PN->getNumIncomingValues() == 0)
57 return Constant::getNullValue(PN->getType());
Misha Brukmanfd939082005-04-21 23:48:37 +000058
Chris Lattner8f90b002004-01-12 18:25:22 +000059 Constant *Result = dyn_cast<Constant>(PN->getIncomingValue(0));
60 if (Result == 0) return 0;
61
62 // Handle PHI nodes specially here...
63 for (unsigned i = 1, e = PN->getNumIncomingValues(); i != e; ++i)
64 if (PN->getIncomingValue(i) != Result && PN->getIncomingValue(i) != PN)
65 return 0; // Not all the same incoming constants...
Misha Brukmanfd939082005-04-21 23:48:37 +000066
Chris Lattner8f90b002004-01-12 18:25:22 +000067 // If we reach here, all incoming values are the same constant.
68 return Result;
69 }
70
71 Constant *Op0 = 0, *Op1 = 0;
72 switch (I->getNumOperands()) {
73 default:
74 case 2:
75 Op1 = dyn_cast<Constant>(I->getOperand(1));
76 if (Op1 == 0) return 0; // Not a constant?, can't fold
Reid Spencere4d87aa2006-12-23 06:05:41 +000077 /* FALL THROUGH */
Chris Lattner8f90b002004-01-12 18:25:22 +000078 case 1:
79 Op0 = dyn_cast<Constant>(I->getOperand(0));
80 if (Op0 == 0) return 0; // Not a constant?, can't fold
81 break;
82 case 0: return 0;
83 }
84
Reid Spencere4d87aa2006-12-23 06:05:41 +000085 // Scan the operand list, checking to see if they are all constants, if so,
Chris Lattner4b30fcb2006-05-27 01:18:04 +000086 // hand off to ConstantFoldInstOperands.
Chris Lattner9fa038d2007-01-30 23:13:49 +000087 SmallVector<Constant*, 8> Ops;
Chris Lattner4b30fcb2006-05-27 01:18:04 +000088 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
89 if (Constant *Op = dyn_cast<Constant>(I->getOperand(i)))
90 Ops.push_back(Op);
91 else
92 return 0; // All operands not constant!
93
Chris Lattner9fa038d2007-01-30 23:13:49 +000094 return ConstantFoldInstOperands(I, &Ops[0], Ops.size());
Chris Lattner4b30fcb2006-05-27 01:18:04 +000095}
96
97/// ConstantFoldInstOperands - Attempt to constant fold an instruction with the
98/// specified opcode and operands. If successful, the constant result is
99/// returned, if not, null is returned. Note that this function can fail when
100/// attempting to fold instructions like loads and stores, which have no
101/// constant expression form.
102///
Reid Spencere4d87aa2006-12-23 06:05:41 +0000103Constant *llvm::ConstantFoldInstOperands(const Instruction* I,
Chris Lattner9fa038d2007-01-30 23:13:49 +0000104 Constant** Ops, unsigned NumOps,
105 const TargetData *TD) {
Reid Spencere4d87aa2006-12-23 06:05:41 +0000106 unsigned Opc = I->getOpcode();
107 const Type *DestTy = I->getType();
108
109 // Handle easy binops first
110 if (isa<BinaryOperator>(I))
Chris Lattner4b30fcb2006-05-27 01:18:04 +0000111 return ConstantExpr::get(Opc, Ops[0], Ops[1]);
112
113 switch (Opc) {
Chris Lattner8f90b002004-01-12 18:25:22 +0000114 default: return 0;
Chris Lattner4b30fcb2006-05-27 01:18:04 +0000115 case Instruction::Call:
Chris Lattner9fa038d2007-01-30 23:13:49 +0000116 if (Function *F = dyn_cast<Function>(Ops[0]))
117 if (canConstantFoldCallTo(F))
118 return ConstantFoldCall(F, Ops+1, NumOps);
Chris Lattner4b30fcb2006-05-27 01:18:04 +0000119 return 0;
Reid Spencere4d87aa2006-12-23 06:05:41 +0000120 case Instruction::ICmp:
121 case Instruction::FCmp:
122 return ConstantExpr::getCompare(cast<CmpInst>(I)->getPredicate(), Ops[0],
123 Ops[1]);
Chris Lattner4b30fcb2006-05-27 01:18:04 +0000124 case Instruction::Shl:
Reid Spencer3822ff52006-11-08 06:47:33 +0000125 case Instruction::LShr:
126 case Instruction::AShr:
Chris Lattner4b30fcb2006-05-27 01:18:04 +0000127 return ConstantExpr::get(Opc, Ops[0], Ops[1]);
Reid Spencer3da59db2006-11-27 01:05:10 +0000128 case Instruction::Trunc:
129 case Instruction::ZExt:
130 case Instruction::SExt:
131 case Instruction::FPTrunc:
132 case Instruction::FPExt:
133 case Instruction::UIToFP:
134 case Instruction::SIToFP:
135 case Instruction::FPToUI:
136 case Instruction::FPToSI:
137 case Instruction::PtrToInt:
138 case Instruction::IntToPtr:
139 case Instruction::BitCast:
140 return ConstantExpr::getCast(Opc, Ops[0], DestTy);
Chris Lattner17fd2732004-03-12 05:53:03 +0000141 case Instruction::Select:
Chris Lattner4b30fcb2006-05-27 01:18:04 +0000142 return ConstantExpr::getSelect(Ops[0], Ops[1], Ops[2]);
Robert Bocchinob52ee7f2006-01-10 19:05:34 +0000143 case Instruction::ExtractElement:
Chris Lattner4b30fcb2006-05-27 01:18:04 +0000144 return ConstantExpr::getExtractElement(Ops[0], Ops[1]);
Robert Bocchino956fd722006-01-17 20:07:07 +0000145 case Instruction::InsertElement:
Chris Lattner4b30fcb2006-05-27 01:18:04 +0000146 return ConstantExpr::getInsertElement(Ops[0], Ops[1], Ops[2]);
Chris Lattner543abdf2006-04-08 01:19:12 +0000147 case Instruction::ShuffleVector:
Chris Lattner4b30fcb2006-05-27 01:18:04 +0000148 return ConstantExpr::getShuffleVector(Ops[0], Ops[1], Ops[2]);
Chris Lattner8f90b002004-01-12 18:25:22 +0000149 case Instruction::GetElementPtr:
Chris Lattner4b30fcb2006-05-27 01:18:04 +0000150 return ConstantExpr::getGetElementPtr(Ops[0],
Chris Lattner9fa038d2007-01-30 23:13:49 +0000151 std::vector<Constant*>(Ops+1,
152 Ops+NumOps));
Chris Lattner8f90b002004-01-12 18:25:22 +0000153 }
154}
155
Chris Lattner4d1e46e2002-05-07 18:07:59 +0000156// ConstantFoldTerminator - If a terminator instruction is predicated on a
157// constant value, convert it into an unconditional branch to the constant
158// destination.
159//
Chris Lattnerabbc2dd2003-12-19 05:56:28 +0000160bool llvm::ConstantFoldTerminator(BasicBlock *BB) {
Chris Lattner76ae3442002-05-21 20:04:50 +0000161 TerminatorInst *T = BB->getTerminator();
Misha Brukmanfd939082005-04-21 23:48:37 +0000162
Chris Lattner4d1e46e2002-05-07 18:07:59 +0000163 // Branch - See if we are conditional jumping on constant
164 if (BranchInst *BI = dyn_cast<BranchInst>(T)) {
165 if (BI->isUnconditional()) return false; // Can't optimize uncond branch
166 BasicBlock *Dest1 = cast<BasicBlock>(BI->getOperand(0));
167 BasicBlock *Dest2 = cast<BasicBlock>(BI->getOperand(1));
168
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000169 if (ConstantInt *Cond = dyn_cast<ConstantInt>(BI->getCondition())) {
Chris Lattner4d1e46e2002-05-07 18:07:59 +0000170 // Are we branching on constant?
171 // YES. Change to unconditional branch...
Reid Spencer579dca12007-01-12 04:24:46 +0000172 BasicBlock *Destination = Cond->getZExtValue() ? Dest1 : Dest2;
173 BasicBlock *OldDest = Cond->getZExtValue() ? Dest2 : Dest1;
Chris Lattner4d1e46e2002-05-07 18:07:59 +0000174
Misha Brukmanfd939082005-04-21 23:48:37 +0000175 //cerr << "Function: " << T->getParent()->getParent()
176 // << "\nRemoving branch from " << T->getParent()
Chris Lattner4d1e46e2002-05-07 18:07:59 +0000177 // << "\n\nTo: " << OldDest << endl;
178
179 // Let the basic block know that we are letting go of it. Based on this,
180 // it will adjust it's PHI nodes.
181 assert(BI->getParent() && "Terminator not inserted in block!");
182 OldDest->removePredecessor(BI->getParent());
183
184 // Set the unconditional destination, and change the insn to be an
185 // unconditional branch.
186 BI->setUnconditionalDest(Destination);
Chris Lattner4d1e46e2002-05-07 18:07:59 +0000187 return true;
Chris Lattner342a9d12003-08-17 19:34:55 +0000188 } else if (Dest2 == Dest1) { // Conditional branch to same location?
Misha Brukmanfd939082005-04-21 23:48:37 +0000189 // This branch matches something like this:
Chris Lattner4d1e46e2002-05-07 18:07:59 +0000190 // br bool %cond, label %Dest, label %Dest
191 // and changes it into: br label %Dest
192
193 // Let the basic block know that we are letting go of one copy of it.
194 assert(BI->getParent() && "Terminator not inserted in block!");
195 Dest1->removePredecessor(BI->getParent());
196
197 // Change a conditional branch to unconditional.
198 BI->setUnconditionalDest(Dest1);
199 return true;
200 }
Chris Lattner10b1f5a2003-08-17 20:21:14 +0000201 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(T)) {
202 // If we are switching on a constant, we can convert the switch into a
203 // single branch instruction!
204 ConstantInt *CI = dyn_cast<ConstantInt>(SI->getCondition());
205 BasicBlock *TheOnlyDest = SI->getSuccessor(0); // The default dest
Chris Lattner7d6c24c2003-08-23 23:18:19 +0000206 BasicBlock *DefaultDest = TheOnlyDest;
207 assert(TheOnlyDest == SI->getDefaultDest() &&
208 "Default destination is not successor #0?");
Chris Lattner694e37f2003-08-17 19:41:53 +0000209
Chris Lattner10b1f5a2003-08-17 20:21:14 +0000210 // Figure out which case it goes to...
211 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i) {
212 // Found case matching a constant operand?
213 if (SI->getSuccessorValue(i) == CI) {
214 TheOnlyDest = SI->getSuccessor(i);
215 break;
216 }
Chris Lattner694e37f2003-08-17 19:41:53 +0000217
Chris Lattner7d6c24c2003-08-23 23:18:19 +0000218 // Check to see if this branch is going to the same place as the default
219 // dest. If so, eliminate it as an explicit compare.
220 if (SI->getSuccessor(i) == DefaultDest) {
221 // Remove this entry...
222 DefaultDest->removePredecessor(SI->getParent());
223 SI->removeCase(i);
224 --i; --e; // Don't skip an entry...
225 continue;
226 }
227
Chris Lattner10b1f5a2003-08-17 20:21:14 +0000228 // Otherwise, check to see if the switch only branches to one destination.
229 // We do this by reseting "TheOnlyDest" to null when we find two non-equal
230 // destinations.
231 if (SI->getSuccessor(i) != TheOnlyDest) TheOnlyDest = 0;
Chris Lattner694e37f2003-08-17 19:41:53 +0000232 }
233
Chris Lattner10b1f5a2003-08-17 20:21:14 +0000234 if (CI && !TheOnlyDest) {
235 // Branching on a constant, but not any of the cases, go to the default
236 // successor.
237 TheOnlyDest = SI->getDefaultDest();
238 }
239
240 // If we found a single destination that we can fold the switch into, do so
241 // now.
242 if (TheOnlyDest) {
243 // Insert the new branch..
244 new BranchInst(TheOnlyDest, SI);
245 BasicBlock *BB = SI->getParent();
246
247 // Remove entries from PHI nodes which we no longer branch to...
248 for (unsigned i = 0, e = SI->getNumSuccessors(); i != e; ++i) {
249 // Found case matching a constant operand?
250 BasicBlock *Succ = SI->getSuccessor(i);
251 if (Succ == TheOnlyDest)
252 TheOnlyDest = 0; // Don't modify the first branch to TheOnlyDest
253 else
254 Succ->removePredecessor(BB);
255 }
256
257 // Delete the old switch...
258 BB->getInstList().erase(SI);
259 return true;
260 } else if (SI->getNumSuccessors() == 2) {
261 // Otherwise, we can fold this switch into a conditional branch
262 // instruction if it has only one non-default destination.
Reid Spencere4d87aa2006-12-23 06:05:41 +0000263 Value *Cond = new ICmpInst(ICmpInst::ICMP_EQ, SI->getCondition(),
264 SI->getSuccessorValue(1), "cond", SI);
Chris Lattner10b1f5a2003-08-17 20:21:14 +0000265 // Insert the new branch...
266 new BranchInst(SI->getSuccessor(1), SI->getSuccessor(0), Cond, SI);
267
268 // Delete the old switch...
269 SI->getParent()->getInstList().erase(SI);
270 return true;
271 }
Chris Lattner4d1e46e2002-05-07 18:07:59 +0000272 }
273 return false;
274}
275
Chris Lattnerc5f52e62005-09-26 05:27:10 +0000276/// ConstantFoldLoadThroughGEPConstantExpr - Given a constant and a
277/// getelementptr constantexpr, return the constant value being addressed by the
278/// constant expression, or null if something is funny and we can't decide.
279Constant *llvm::ConstantFoldLoadThroughGEPConstantExpr(Constant *C,
280 ConstantExpr *CE) {
281 if (CE->getOperand(1) != Constant::getNullValue(CE->getOperand(1)->getType()))
282 return 0; // Do not allow stepping over the value!
283
284 // Loop over all of the operands, tracking down which value we are
285 // addressing...
286 gep_type_iterator I = gep_type_begin(CE), E = gep_type_end(CE);
287 for (++I; I != E; ++I)
288 if (const StructType *STy = dyn_cast<StructType>(*I)) {
Reid Spencerb83eb642006-10-20 07:07:24 +0000289 ConstantInt *CU = cast<ConstantInt>(I.getOperand());
290 assert(CU->getZExtValue() < STy->getNumElements() &&
Chris Lattnerc5f52e62005-09-26 05:27:10 +0000291 "Struct index out of range!");
Reid Spencerb83eb642006-10-20 07:07:24 +0000292 unsigned El = (unsigned)CU->getZExtValue();
Chris Lattnerc5f52e62005-09-26 05:27:10 +0000293 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(C)) {
294 C = CS->getOperand(El);
295 } else if (isa<ConstantAggregateZero>(C)) {
296 C = Constant::getNullValue(STy->getElementType(El));
297 } else if (isa<UndefValue>(C)) {
298 C = UndefValue::get(STy->getElementType(El));
299 } else {
300 return 0;
301 }
302 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand())) {
Robert Bocchinod900c6a2006-01-19 23:53:23 +0000303 if (const ArrayType *ATy = dyn_cast<ArrayType>(*I)) {
Reid Spencerb83eb642006-10-20 07:07:24 +0000304 if (CI->getZExtValue() >= ATy->getNumElements())
Chris Lattner99f2af22006-05-25 21:25:12 +0000305 return 0;
Robert Bocchinod900c6a2006-01-19 23:53:23 +0000306 if (ConstantArray *CA = dyn_cast<ConstantArray>(C))
Reid Spencerb83eb642006-10-20 07:07:24 +0000307 C = CA->getOperand(CI->getZExtValue());
Robert Bocchinod900c6a2006-01-19 23:53:23 +0000308 else if (isa<ConstantAggregateZero>(C))
309 C = Constant::getNullValue(ATy->getElementType());
310 else if (isa<UndefValue>(C))
311 C = UndefValue::get(ATy->getElementType());
312 else
313 return 0;
314 } else if (const PackedType *PTy = dyn_cast<PackedType>(*I)) {
Reid Spencerb83eb642006-10-20 07:07:24 +0000315 if (CI->getZExtValue() >= PTy->getNumElements())
Chris Lattner99f2af22006-05-25 21:25:12 +0000316 return 0;
Robert Bocchinod900c6a2006-01-19 23:53:23 +0000317 if (ConstantPacked *CP = dyn_cast<ConstantPacked>(C))
Reid Spencerb83eb642006-10-20 07:07:24 +0000318 C = CP->getOperand(CI->getZExtValue());
Robert Bocchinod900c6a2006-01-19 23:53:23 +0000319 else if (isa<ConstantAggregateZero>(C))
320 C = Constant::getNullValue(PTy->getElementType());
321 else if (isa<UndefValue>(C))
322 C = UndefValue::get(PTy->getElementType());
323 else
324 return 0;
325 } else {
Chris Lattnerc5f52e62005-09-26 05:27:10 +0000326 return 0;
Robert Bocchinod900c6a2006-01-19 23:53:23 +0000327 }
Chris Lattnerc5f52e62005-09-26 05:27:10 +0000328 } else {
329 return 0;
330 }
331 return C;
332}
Chris Lattner4d1e46e2002-05-07 18:07:59 +0000333
334
335//===----------------------------------------------------------------------===//
336// Local dead code elimination...
337//
338
Chris Lattnerabbc2dd2003-12-19 05:56:28 +0000339bool llvm::isInstructionTriviallyDead(Instruction *I) {
Chris Lattnerec710c52005-05-06 05:27:34 +0000340 if (!I->use_empty() || isa<TerminatorInst>(I)) return false;
Jeff Cohen00b168892005-07-27 06:12:32 +0000341
Chris Lattnerec710c52005-05-06 05:27:34 +0000342 if (!I->mayWriteToMemory()) return true;
343
344 if (CallInst *CI = dyn_cast<CallInst>(I))
Chris Lattneraeebe7f2006-03-09 22:38:10 +0000345 if (Function *F = CI->getCalledFunction()) {
Chris Lattner7224f842006-04-02 03:35:01 +0000346 unsigned IntrinsicID = F->getIntrinsicID();
Chris Lattneraeebe7f2006-03-09 22:38:10 +0000347#define GET_SIDE_EFFECT_INFO
348#include "llvm/Intrinsics.gen"
349#undef GET_SIDE_EFFECT_INFO
350 }
Chris Lattnerec710c52005-05-06 05:27:34 +0000351 return false;
Chris Lattner4d1e46e2002-05-07 18:07:59 +0000352}
353
354// dceInstruction - Inspect the instruction at *BBI and figure out if it's
355// [trivially] dead. If so, remove the instruction and update the iterator
356// to point to the instruction that immediately succeeded the original
357// instruction.
358//
Chris Lattnerabbc2dd2003-12-19 05:56:28 +0000359bool llvm::dceInstruction(BasicBlock::iterator &BBI) {
Chris Lattner4d1e46e2002-05-07 18:07:59 +0000360 // Look for un"used" definitions...
Chris Lattner18961502002-06-25 16:12:52 +0000361 if (isInstructionTriviallyDead(BBI)) {
362 BBI = BBI->getParent()->getInstList().erase(BBI); // Bye bye
Chris Lattner4d1e46e2002-05-07 18:07:59 +0000363 return true;
364 }
365 return false;
366}