a9cfcc0a9209d4cc18c11d0a22b3424e08d39905
[oota-llvm.git] / lib / Transforms / Utils / Local.cpp
1 //===-- Local.cpp - Functions to perform local transformations ------------===//
2 //
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 //===----------------------------------------------------------------------===//
9 //
10 // This family of functions perform various local transformations to the
11 // program.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #include "llvm/Transforms/Utils/Local.h"
16 #include "llvm/Constants.h"
17 #include "llvm/DerivedTypes.h"
18 #include "llvm/Instructions.h"
19 #include "llvm/Intrinsics.h"
20 #include "llvm/Support/GetElementPtrTypeIterator.h"
21 #include "llvm/Support/MathExtras.h"
22 #include <cerrno>
23 #include <cmath>
24 using namespace llvm;
25
26 //===----------------------------------------------------------------------===//
27 //  Local constant propagation...
28 //
29
30 /// doConstantPropagation - If an instruction references constants, try to fold
31 /// them together...
32 ///
33 bool llvm::doConstantPropagation(BasicBlock::iterator &II) {
34   if (Constant *C = ConstantFoldInstruction(II)) {
35     // Replaces all of the uses of a variable with uses of the constant.
36     II->replaceAllUsesWith(C);
37
38     // Remove the instruction from the basic block...
39     II = II->getParent()->getInstList().erase(II);
40     return true;
41   }
42
43   return false;
44 }
45
46 /// 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 ///
51 Constant *llvm::ConstantFoldInstruction(Instruction *I) {
52   if (PHINode *PN = dyn_cast<PHINode>(I)) {
53     if (PN->getNumIncomingValues() == 0)
54       return Constant::getNullValue(PN->getType());
55
56     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...
63
64     // If we reach here, all incoming values are the same constant.
65     return Result;
66   } else if (CallInst *CI = dyn_cast<CallInst>(I)) {
67     if (Function *F = CI->getCalledFunction())
68       if (canConstantFoldCallTo(F)) {
69         std::vector<Constant*> Args;
70         for (unsigned i = 1, e = CI->getNumOperands(); i != e; ++i)
71           if (Constant *Op = dyn_cast<Constant>(CI->getOperand(i)))
72             Args.push_back(Op);
73           else
74             return 0;
75         return ConstantFoldCall(F, Args);
76       }
77     return 0;
78   }
79
80   Constant *Op0 = 0, *Op1 = 0;
81   switch (I->getNumOperands()) {
82   default:
83   case 2:
84     Op1 = dyn_cast<Constant>(I->getOperand(1));
85     if (Op1 == 0) return 0;        // Not a constant?, can't fold
86   case 1:
87     Op0 = dyn_cast<Constant>(I->getOperand(0));
88     if (Op0 == 0) return 0;        // Not a constant?, can't fold
89     break;
90   case 0: return 0;
91   }
92
93   if (isa<BinaryOperator>(I) || isa<ShiftInst>(I))
94     return ConstantExpr::get(I->getOpcode(), Op0, Op1);
95
96   switch (I->getOpcode()) {
97   default: return 0;
98   case Instruction::Cast:
99     return ConstantExpr::getCast(Op0, I->getType());
100   case Instruction::Select:
101     if (Constant *Op2 = dyn_cast<Constant>(I->getOperand(2)))
102       return ConstantExpr::getSelect(Op0, Op1, Op2);
103     return 0;
104   case Instruction::GetElementPtr:
105     std::vector<Constant*> IdxList;
106     IdxList.reserve(I->getNumOperands()-1);
107     if (Op1) IdxList.push_back(Op1);
108     for (unsigned i = 2, e = I->getNumOperands(); i != e; ++i)
109       if (Constant *C = dyn_cast<Constant>(I->getOperand(i)))
110         IdxList.push_back(C);
111       else
112         return 0;  // Non-constant operand
113     return ConstantExpr::getGetElementPtr(Op0, IdxList);
114   }
115 }
116
117 // ConstantFoldTerminator - If a terminator instruction is predicated on a
118 // constant value, convert it into an unconditional branch to the constant
119 // destination.
120 //
121 bool llvm::ConstantFoldTerminator(BasicBlock *BB) {
122   TerminatorInst *T = BB->getTerminator();
123
124   // Branch - See if we are conditional jumping on constant
125   if (BranchInst *BI = dyn_cast<BranchInst>(T)) {
126     if (BI->isUnconditional()) return false;  // Can't optimize uncond branch
127     BasicBlock *Dest1 = cast<BasicBlock>(BI->getOperand(0));
128     BasicBlock *Dest2 = cast<BasicBlock>(BI->getOperand(1));
129
130     if (ConstantBool *Cond = dyn_cast<ConstantBool>(BI->getCondition())) {
131       // Are we branching on constant?
132       // YES.  Change to unconditional branch...
133       BasicBlock *Destination = Cond->getValue() ? Dest1 : Dest2;
134       BasicBlock *OldDest     = Cond->getValue() ? Dest2 : Dest1;
135
136       //cerr << "Function: " << T->getParent()->getParent()
137       //     << "\nRemoving branch from " << T->getParent()
138       //     << "\n\nTo: " << OldDest << endl;
139
140       // Let the basic block know that we are letting go of it.  Based on this,
141       // it will adjust it's PHI nodes.
142       assert(BI->getParent() && "Terminator not inserted in block!");
143       OldDest->removePredecessor(BI->getParent());
144
145       // Set the unconditional destination, and change the insn to be an
146       // unconditional branch.
147       BI->setUnconditionalDest(Destination);
148       return true;
149     } else if (Dest2 == Dest1) {       // Conditional branch to same location?
150       // This branch matches something like this:
151       //     br bool %cond, label %Dest, label %Dest
152       // and changes it into:  br label %Dest
153
154       // Let the basic block know that we are letting go of one copy of it.
155       assert(BI->getParent() && "Terminator not inserted in block!");
156       Dest1->removePredecessor(BI->getParent());
157
158       // Change a conditional branch to unconditional.
159       BI->setUnconditionalDest(Dest1);
160       return true;
161     }
162   } else if (SwitchInst *SI = dyn_cast<SwitchInst>(T)) {
163     // If we are switching on a constant, we can convert the switch into a
164     // single branch instruction!
165     ConstantInt *CI = dyn_cast<ConstantInt>(SI->getCondition());
166     BasicBlock *TheOnlyDest = SI->getSuccessor(0);  // The default dest
167     BasicBlock *DefaultDest = TheOnlyDest;
168     assert(TheOnlyDest == SI->getDefaultDest() &&
169            "Default destination is not successor #0?");
170
171     // Figure out which case it goes to...
172     for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i) {
173       // Found case matching a constant operand?
174       if (SI->getSuccessorValue(i) == CI) {
175         TheOnlyDest = SI->getSuccessor(i);
176         break;
177       }
178
179       // Check to see if this branch is going to the same place as the default
180       // dest.  If so, eliminate it as an explicit compare.
181       if (SI->getSuccessor(i) == DefaultDest) {
182         // Remove this entry...
183         DefaultDest->removePredecessor(SI->getParent());
184         SI->removeCase(i);
185         --i; --e;  // Don't skip an entry...
186         continue;
187       }
188
189       // Otherwise, check to see if the switch only branches to one destination.
190       // We do this by reseting "TheOnlyDest" to null when we find two non-equal
191       // destinations.
192       if (SI->getSuccessor(i) != TheOnlyDest) TheOnlyDest = 0;
193     }
194
195     if (CI && !TheOnlyDest) {
196       // Branching on a constant, but not any of the cases, go to the default
197       // successor.
198       TheOnlyDest = SI->getDefaultDest();
199     }
200
201     // If we found a single destination that we can fold the switch into, do so
202     // now.
203     if (TheOnlyDest) {
204       // Insert the new branch..
205       new BranchInst(TheOnlyDest, SI);
206       BasicBlock *BB = SI->getParent();
207
208       // Remove entries from PHI nodes which we no longer branch to...
209       for (unsigned i = 0, e = SI->getNumSuccessors(); i != e; ++i) {
210         // Found case matching a constant operand?
211         BasicBlock *Succ = SI->getSuccessor(i);
212         if (Succ == TheOnlyDest)
213           TheOnlyDest = 0;  // Don't modify the first branch to TheOnlyDest
214         else
215           Succ->removePredecessor(BB);
216       }
217
218       // Delete the old switch...
219       BB->getInstList().erase(SI);
220       return true;
221     } else if (SI->getNumSuccessors() == 2) {
222       // Otherwise, we can fold this switch into a conditional branch
223       // instruction if it has only one non-default destination.
224       Value *Cond = new SetCondInst(Instruction::SetEQ, SI->getCondition(),
225                                     SI->getSuccessorValue(1), "cond", SI);
226       // Insert the new branch...
227       new BranchInst(SI->getSuccessor(1), SI->getSuccessor(0), Cond, SI);
228
229       // Delete the old switch...
230       SI->getParent()->getInstList().erase(SI);
231       return true;
232     }
233   }
234   return false;
235 }
236
237 /// canConstantFoldCallTo - Return true if its even possible to fold a call to
238 /// the specified function.
239 bool llvm::canConstantFoldCallTo(Function *F) {
240   const std::string &Name = F->getName();
241
242   switch (F->getIntrinsicID()) {
243   case Intrinsic::isunordered:
244   case Intrinsic::sqrt:
245     return true;
246   default: break;
247   }
248
249   switch (Name[0])
250   {
251     case 'a':
252       return Name == "acos" || Name == "asin" || Name == "atan" ||
253              Name == "atan2";
254     case 'c':
255       return Name == "ceil" || Name == "cos" || Name == "cosf" ||
256              Name == "cosh";
257     case 'e':
258       return Name == "exp";
259     case 'f':
260       return Name == "fabs" || Name == "fmod" || Name == "floor";
261     case 'l':
262       return Name == "log" || Name == "log10";
263     case 'p':
264       return Name == "pow";
265     case 's':
266       return Name == "sin" || Name == "sinh" || Name == "sqrt";
267     case 't':
268       return Name == "tan" || Name == "tanh";
269     default:
270       return false;
271   }
272 }
273
274 static Constant *ConstantFoldFP(double (*NativeFP)(double), double V,
275                                 const Type *Ty) {
276   errno = 0;
277   V = NativeFP(V);
278   if (errno == 0)
279     return ConstantFP::get(Ty, V);
280   return 0;
281 }
282
283 /// ConstantFoldCall - Attempt to constant fold a call to the specified function
284 /// with the specified arguments, returning null if unsuccessful.
285 Constant *llvm::ConstantFoldCall(Function *F,
286                                  const std::vector<Constant*> &Operands) {
287   const std::string &Name = F->getName();
288   const Type *Ty = F->getReturnType();
289
290   if (Operands.size() == 1) {
291     if (ConstantFP *Op = dyn_cast<ConstantFP>(Operands[0])) {
292       double V = Op->getValue();
293       switch (Name[0])
294       {
295         case 'a':
296           if (Name == "acos")
297             return ConstantFoldFP(acos, V, Ty);
298           else if (Name == "asin")
299             return ConstantFoldFP(asin, V, Ty);
300           else if (Name == "atan")
301             return ConstantFP::get(Ty, atan(V));
302           break;
303         case 'c':
304           if (Name == "ceil")
305             return ConstantFoldFP(ceil, V, Ty);
306           else if (Name == "cos")
307             return ConstantFP::get(Ty, cos(V));
308           else if (Name == "cosh")
309             return ConstantFP::get(Ty, cosh(V));
310           break;
311         case 'e':
312           if (Name == "exp")
313             return ConstantFP::get(Ty, exp(V));
314           break;
315         case 'f':
316           if (Name == "fabs")
317             return ConstantFP::get(Ty, fabs(V));
318           else if (Name == "floor")
319             return ConstantFoldFP(floor, V, Ty);
320           break;
321         case 'l':
322           if (Name == "log" && V > 0)
323             return ConstantFP::get(Ty, log(V));
324           else if (Name == "log10" && V > 0)
325             return ConstantFoldFP(log10, V, Ty);
326           else if (Name == "llvm.sqrt") {
327             if (V >= -0.0)
328               return ConstantFP::get(Ty, sqrt(V));
329             else // Undefined
330               return ConstantFP::get(Ty, 0.0);
331           }
332           break;
333         case 's':
334           if (Name == "sin")
335             return ConstantFP::get(Ty, sin(V));
336           else if (Name == "sinh")
337             return ConstantFP::get(Ty, sinh(V));
338           else if (Name == "sqrt" && V >= 0)
339             return ConstantFP::get(Ty, sqrt(V));
340           break;
341         case 't':
342           if (Name == "tan")
343             return ConstantFP::get(Ty, tan(V));
344           else if (Name == "tanh")
345             return ConstantFP::get(Ty, tanh(V));
346           break;
347         default:
348           break;
349       }
350     }
351   } else if (Operands.size() == 2) {
352     if (ConstantFP *Op1 = dyn_cast<ConstantFP>(Operands[0])) {
353       double Op1V = Op1->getValue();
354       if (ConstantFP *Op2 = dyn_cast<ConstantFP>(Operands[1])) {
355         double Op2V = Op2->getValue();
356
357         if (Name == "llvm.isunordered")
358           return ConstantBool::get(IsNAN(Op1V) || IsNAN(Op2V));
359         else
360         if (Name == "pow") {
361           errno = 0;
362           double V = pow(Op1V, Op2V);
363           if (errno == 0)
364             return ConstantFP::get(Ty, V);
365         } else if (Name == "fmod") {
366           errno = 0;
367           double V = fmod(Op1V, Op2V);
368           if (errno == 0)
369             return ConstantFP::get(Ty, V);
370         } else if (Name == "atan2")
371           return ConstantFP::get(Ty, atan2(Op1V,Op2V));
372       }
373     }
374   }
375   return 0;
376 }
377
378
379 /// ConstantFoldLoadThroughGEPConstantExpr - Given a constant and a
380 /// getelementptr constantexpr, return the constant value being addressed by the
381 /// constant expression, or null if something is funny and we can't decide.
382 Constant *llvm::ConstantFoldLoadThroughGEPConstantExpr(Constant *C, 
383                                                        ConstantExpr *CE) {
384   if (CE->getOperand(1) != Constant::getNullValue(CE->getOperand(1)->getType()))
385     return 0;  // Do not allow stepping over the value!
386   
387   // Loop over all of the operands, tracking down which value we are
388   // addressing...
389   gep_type_iterator I = gep_type_begin(CE), E = gep_type_end(CE);
390   for (++I; I != E; ++I)
391     if (const StructType *STy = dyn_cast<StructType>(*I)) {
392       ConstantUInt *CU = cast<ConstantUInt>(I.getOperand());
393       assert(CU->getValue() < STy->getNumElements() &&
394              "Struct index out of range!");
395       unsigned El = (unsigned)CU->getValue();
396       if (ConstantStruct *CS = dyn_cast<ConstantStruct>(C)) {
397         C = CS->getOperand(El);
398       } else if (isa<ConstantAggregateZero>(C)) {
399         C = Constant::getNullValue(STy->getElementType(El));
400       } else if (isa<UndefValue>(C)) {
401         C = UndefValue::get(STy->getElementType(El));
402       } else {
403         return 0;
404       }
405     } else if (ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand())) {
406       const ArrayType *ATy = cast<ArrayType>(*I);
407       if ((uint64_t)CI->getRawValue() >= ATy->getNumElements()) return 0;
408       if (ConstantArray *CA = dyn_cast<ConstantArray>(C))
409         C = CA->getOperand((unsigned)CI->getRawValue());
410       else if (isa<ConstantAggregateZero>(C))
411         C = Constant::getNullValue(ATy->getElementType());
412       else if (isa<UndefValue>(C))
413         C = UndefValue::get(ATy->getElementType());
414       else
415         return 0;
416     } else {
417       return 0;
418     }
419   return C;
420 }
421
422
423 //===----------------------------------------------------------------------===//
424 //  Local dead code elimination...
425 //
426
427 bool llvm::isInstructionTriviallyDead(Instruction *I) {
428   if (!I->use_empty() || isa<TerminatorInst>(I)) return false;
429
430   if (!I->mayWriteToMemory()) return true;
431
432   if (CallInst *CI = dyn_cast<CallInst>(I))
433     if (Function *F = CI->getCalledFunction())
434       switch (F->getIntrinsicID()) {
435       default: break;
436       case Intrinsic::returnaddress:
437       case Intrinsic::frameaddress:
438       case Intrinsic::isunordered:
439       case Intrinsic::ctpop:
440       case Intrinsic::ctlz:
441       case Intrinsic::cttz:
442       case Intrinsic::sqrt:
443         return true;             // These intrinsics have no side effects.
444       }
445   return false;
446 }
447
448 // dceInstruction - Inspect the instruction at *BBI and figure out if it's
449 // [trivially] dead.  If so, remove the instruction and update the iterator
450 // to point to the instruction that immediately succeeded the original
451 // instruction.
452 //
453 bool llvm::dceInstruction(BasicBlock::iterator &BBI) {
454   // Look for un"used" definitions...
455   if (isInstructionTriviallyDead(BBI)) {
456     BBI = BBI->getParent()->getInstList().erase(BBI);   // Bye bye
457     return true;
458   }
459   return false;
460 }