1 //===-- Local.cpp - Functions to perform local transformations ------------===//
3 // The LLVM Compiler Infrastructure
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.
8 //===----------------------------------------------------------------------===//
10 // This family of functions perform various local transformations to the
13 //===----------------------------------------------------------------------===//
15 #include "llvm/Transforms/Utils/Local.h"
16 #include "llvm/Constants.h"
17 #include "llvm/Instructions.h"
18 #include "llvm/Intrinsics.h"
24 #if defined(__POWERPC__) && defined(__APPLE_CC__)
25 // FIXME: Currently it seems that isnan didn't make its way into the Apple
26 // C++ headers, although it IS in the C headers (which confuses autoconf
27 // in a big way). This is a quick fix to get things compiling, until one of
28 // us has time to write a more complicated autoconf test.
29 extern "C" int isnan (double d);
30 namespace std { int isnan (double d) { return ::isnan (d); } }
35 //===----------------------------------------------------------------------===//
36 // Local constant propagation...
39 /// doConstantPropagation - If an instruction references constants, try to fold
42 bool llvm::doConstantPropagation(BasicBlock::iterator &II) {
43 if (Constant *C = ConstantFoldInstruction(II)) {
44 // Replaces all of the uses of a variable with uses of the constant.
45 II->replaceAllUsesWith(C);
47 // Remove the instruction from the basic block...
48 II = II->getParent()->getInstList().erase(II);
55 /// ConstantFoldInstruction - Attempt to constant fold the specified
56 /// instruction. If successful, the constant result is returned, if not, null
57 /// is returned. Note that this function can only fail when attempting to fold
58 /// instructions like loads and stores, which have no constant expression form.
60 Constant *llvm::ConstantFoldInstruction(Instruction *I) {
61 if (PHINode *PN = dyn_cast<PHINode>(I)) {
62 if (PN->getNumIncomingValues() == 0)
63 return Constant::getNullValue(PN->getType());
65 Constant *Result = dyn_cast<Constant>(PN->getIncomingValue(0));
66 if (Result == 0) return 0;
68 // Handle PHI nodes specially here...
69 for (unsigned i = 1, e = PN->getNumIncomingValues(); i != e; ++i)
70 if (PN->getIncomingValue(i) != Result && PN->getIncomingValue(i) != PN)
71 return 0; // Not all the same incoming constants...
73 // If we reach here, all incoming values are the same constant.
75 } else if (CallInst *CI = dyn_cast<CallInst>(I)) {
76 if (Function *F = CI->getCalledFunction())
77 if (canConstantFoldCallTo(F)) {
78 std::vector<Constant*> Args;
79 for (unsigned i = 1, e = CI->getNumOperands(); i != e; ++i)
80 if (Constant *Op = dyn_cast<Constant>(CI->getOperand(i)))
84 return ConstantFoldCall(F, Args);
89 Constant *Op0 = 0, *Op1 = 0;
90 switch (I->getNumOperands()) {
93 Op1 = dyn_cast<Constant>(I->getOperand(1));
94 if (Op1 == 0) return 0; // Not a constant?, can't fold
96 Op0 = dyn_cast<Constant>(I->getOperand(0));
97 if (Op0 == 0) return 0; // Not a constant?, can't fold
102 if (isa<BinaryOperator>(I) || isa<ShiftInst>(I))
103 return ConstantExpr::get(I->getOpcode(), Op0, Op1);
105 switch (I->getOpcode()) {
107 case Instruction::Cast:
108 return ConstantExpr::getCast(Op0, I->getType());
109 case Instruction::Select:
110 if (Constant *Op2 = dyn_cast<Constant>(I->getOperand(2)))
111 return ConstantExpr::getSelect(Op0, Op1, Op2);
113 case Instruction::GetElementPtr:
114 std::vector<Constant*> IdxList;
115 IdxList.reserve(I->getNumOperands()-1);
116 if (Op1) IdxList.push_back(Op1);
117 for (unsigned i = 2, e = I->getNumOperands(); i != e; ++i)
118 if (Constant *C = dyn_cast<Constant>(I->getOperand(i)))
119 IdxList.push_back(C);
121 return 0; // Non-constant operand
122 return ConstantExpr::getGetElementPtr(Op0, IdxList);
126 // ConstantFoldTerminator - If a terminator instruction is predicated on a
127 // constant value, convert it into an unconditional branch to the constant
130 bool llvm::ConstantFoldTerminator(BasicBlock *BB) {
131 TerminatorInst *T = BB->getTerminator();
133 // Branch - See if we are conditional jumping on constant
134 if (BranchInst *BI = dyn_cast<BranchInst>(T)) {
135 if (BI->isUnconditional()) return false; // Can't optimize uncond branch
136 BasicBlock *Dest1 = cast<BasicBlock>(BI->getOperand(0));
137 BasicBlock *Dest2 = cast<BasicBlock>(BI->getOperand(1));
139 if (ConstantBool *Cond = dyn_cast<ConstantBool>(BI->getCondition())) {
140 // Are we branching on constant?
141 // YES. Change to unconditional branch...
142 BasicBlock *Destination = Cond->getValue() ? Dest1 : Dest2;
143 BasicBlock *OldDest = Cond->getValue() ? Dest2 : Dest1;
145 //cerr << "Function: " << T->getParent()->getParent()
146 // << "\nRemoving branch from " << T->getParent()
147 // << "\n\nTo: " << OldDest << endl;
149 // Let the basic block know that we are letting go of it. Based on this,
150 // it will adjust it's PHI nodes.
151 assert(BI->getParent() && "Terminator not inserted in block!");
152 OldDest->removePredecessor(BI->getParent());
154 // Set the unconditional destination, and change the insn to be an
155 // unconditional branch.
156 BI->setUnconditionalDest(Destination);
158 } else if (Dest2 == Dest1) { // Conditional branch to same location?
159 // This branch matches something like this:
160 // br bool %cond, label %Dest, label %Dest
161 // and changes it into: br label %Dest
163 // Let the basic block know that we are letting go of one copy of it.
164 assert(BI->getParent() && "Terminator not inserted in block!");
165 Dest1->removePredecessor(BI->getParent());
167 // Change a conditional branch to unconditional.
168 BI->setUnconditionalDest(Dest1);
171 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(T)) {
172 // If we are switching on a constant, we can convert the switch into a
173 // single branch instruction!
174 ConstantInt *CI = dyn_cast<ConstantInt>(SI->getCondition());
175 BasicBlock *TheOnlyDest = SI->getSuccessor(0); // The default dest
176 BasicBlock *DefaultDest = TheOnlyDest;
177 assert(TheOnlyDest == SI->getDefaultDest() &&
178 "Default destination is not successor #0?");
180 // Figure out which case it goes to...
181 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i) {
182 // Found case matching a constant operand?
183 if (SI->getSuccessorValue(i) == CI) {
184 TheOnlyDest = SI->getSuccessor(i);
188 // Check to see if this branch is going to the same place as the default
189 // dest. If so, eliminate it as an explicit compare.
190 if (SI->getSuccessor(i) == DefaultDest) {
191 // Remove this entry...
192 DefaultDest->removePredecessor(SI->getParent());
194 --i; --e; // Don't skip an entry...
198 // Otherwise, check to see if the switch only branches to one destination.
199 // We do this by reseting "TheOnlyDest" to null when we find two non-equal
201 if (SI->getSuccessor(i) != TheOnlyDest) TheOnlyDest = 0;
204 if (CI && !TheOnlyDest) {
205 // Branching on a constant, but not any of the cases, go to the default
207 TheOnlyDest = SI->getDefaultDest();
210 // If we found a single destination that we can fold the switch into, do so
213 // Insert the new branch..
214 new BranchInst(TheOnlyDest, SI);
215 BasicBlock *BB = SI->getParent();
217 // Remove entries from PHI nodes which we no longer branch to...
218 for (unsigned i = 0, e = SI->getNumSuccessors(); i != e; ++i) {
219 // Found case matching a constant operand?
220 BasicBlock *Succ = SI->getSuccessor(i);
221 if (Succ == TheOnlyDest)
222 TheOnlyDest = 0; // Don't modify the first branch to TheOnlyDest
224 Succ->removePredecessor(BB);
227 // Delete the old switch...
228 BB->getInstList().erase(SI);
230 } else if (SI->getNumSuccessors() == 2) {
231 // Otherwise, we can fold this switch into a conditional branch
232 // instruction if it has only one non-default destination.
233 Value *Cond = new SetCondInst(Instruction::SetEQ, SI->getCondition(),
234 SI->getSuccessorValue(1), "cond", SI);
235 // Insert the new branch...
236 new BranchInst(SI->getSuccessor(1), SI->getSuccessor(0), Cond, SI);
238 // Delete the old switch...
239 SI->getParent()->getInstList().erase(SI);
246 /// canConstantFoldCallTo - Return true if its even possible to fold a call to
247 /// the specified function.
248 bool llvm::canConstantFoldCallTo(Function *F) {
249 const std::string &Name = F->getName();
251 switch (F->getIntrinsicID()) {
252 case Intrinsic::isunordered: return true;
256 return Name == "sin" || Name == "cos" || Name == "tan" || Name == "sqrt" ||
257 Name == "log" || Name == "log10" || Name == "exp" || Name == "pow" ||
258 Name == "acos" || Name == "asin" || Name == "atan" || Name == "fmod";
261 static Constant *ConstantFoldFP(double (*NativeFP)(double), double V,
266 return ConstantFP::get(Ty, V);
270 /// ConstantFoldCall - Attempt to constant fold a call to the specified function
271 /// with the specified arguments, returning null if unsuccessful.
272 Constant *llvm::ConstantFoldCall(Function *F,
273 const std::vector<Constant*> &Operands) {
274 const std::string &Name = F->getName();
275 const Type *Ty = F->getReturnType();
277 if (Operands.size() == 1) {
278 if (ConstantFP *Op = dyn_cast<ConstantFP>(Operands[0])) {
279 double V = Op->getValue();
281 return ConstantFP::get(Ty, sin(V));
282 else if (Name == "cos")
283 return ConstantFP::get(Ty, cos(V));
284 else if (Name == "tan")
285 return ConstantFP::get(Ty, tan(V));
286 else if (Name == "sqrt" && V >= 0)
287 return ConstantFP::get(Ty, sqrt(V));
288 else if (Name == "exp")
289 return ConstantFP::get(Ty, exp(V));
290 else if (Name == "log" && V > 0)
291 return ConstantFP::get(Ty, log(V));
292 else if (Name == "log10")
293 return ConstantFoldFP(log10, V, Ty);
294 else if (Name == "acos")
295 return ConstantFoldFP(acos, V, Ty);
296 else if (Name == "asin")
297 return ConstantFoldFP(asin, V, Ty);
298 else if (Name == "atan")
299 return ConstantFP::get(Ty, atan(V));
301 } else if (Operands.size() == 2) {
302 if (ConstantFP *Op1 = dyn_cast<ConstantFP>(Operands[0]))
303 if (ConstantFP *Op2 = dyn_cast<ConstantFP>(Operands[1])) {
304 double Op1V = Op1->getValue(), Op2V = Op2->getValue();
307 if (Name == "llvm.isunordered")
308 return ConstantBool::get(std::isnan(Op1V) | std::isnan(Op2V));
313 double V = pow(Op1V, Op2V);
315 return ConstantFP::get(Ty, V);
316 } else if (Name == "fmod") {
318 double V = fmod(Op1V, Op2V);
320 return ConstantFP::get(Ty, V);
330 //===----------------------------------------------------------------------===//
331 // Local dead code elimination...
334 bool llvm::isInstructionTriviallyDead(Instruction *I) {
335 return I->use_empty() && !I->mayWriteToMemory() && !isa<TerminatorInst>(I);
338 // dceInstruction - Inspect the instruction at *BBI and figure out if it's
339 // [trivially] dead. If so, remove the instruction and update the iterator
340 // to point to the instruction that immediately succeeded the original
343 bool llvm::dceInstruction(BasicBlock::iterator &BBI) {
344 // Look for un"used" definitions...
345 if (isInstructionTriviallyDead(BBI)) {
346 BBI = BBI->getParent()->getInstList().erase(BBI); // Bye bye
352 //===----------------------------------------------------------------------===//
353 // PHI Instruction Simplification
356 /// hasConstantValue - If the specified PHI node always merges together the same
357 /// value, return the value, otherwise return null.
359 Value *llvm::hasConstantValue(PHINode *PN) {
360 // If the PHI node only has one incoming value, eliminate the PHI node...
361 if (PN->getNumIncomingValues() == 1)
362 return PN->getIncomingValue(0);
364 // Otherwise if all of the incoming values are the same for the PHI, replace
365 // the PHI node with the incoming value.
368 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
369 if (PN->getIncomingValue(i) != PN) // Not the PHI node itself...
370 if (InVal && PN->getIncomingValue(i) != InVal)
371 return 0; // Not the same, bail out.
373 InVal = PN->getIncomingValue(i);
375 // The only case that could cause InVal to be null is if we have a PHI node
376 // that only has entries for itself. In this case, there is no entry into the
377 // loop, so kill the PHI.
379 if (InVal == 0) InVal = Constant::getNullValue(PN->getType());
381 // All of the incoming values are the same, return the value now.