3ef6d5594cadd47de89f881135ca119177783ba9
[oota-llvm.git] / lib / Analysis / ConstantFolding.cpp
1 //===-- ConstantFolding.cpp - Fold instructions into constants ------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file defines routines for folding instructions into constants.
11 //
12 // Also, to supplement the basic VMCore ConstantExpr simplifications,
13 // this file defines some additional folding routines that can make use of
14 // TargetData information. These functions cannot go in VMCore due to library
15 // dependency issues.
16 //
17 //===----------------------------------------------------------------------===//
18
19 #include "llvm/Analysis/ConstantFolding.h"
20 #include "llvm/Constants.h"
21 #include "llvm/DerivedTypes.h"
22 #include "llvm/Function.h"
23 #include "llvm/GlobalVariable.h"
24 #include "llvm/Instructions.h"
25 #include "llvm/Intrinsics.h"
26 #include "llvm/LLVMContext.h"
27 #include "llvm/Analysis/ValueTracking.h"
28 #include "llvm/Target/TargetData.h"
29 #include "llvm/ADT/SmallVector.h"
30 #include "llvm/ADT/StringMap.h"
31 #include "llvm/Support/ErrorHandling.h"
32 #include "llvm/Support/GetElementPtrTypeIterator.h"
33 #include "llvm/Support/MathExtras.h"
34 #include <cerrno>
35 #include <cmath>
36 using namespace llvm;
37
38 //===----------------------------------------------------------------------===//
39 // Constant Folding internal helper functions
40 //===----------------------------------------------------------------------===//
41
42 /// IsConstantOffsetFromGlobal - If this constant is actually a constant offset
43 /// from a global, return the global and the constant.  Because of
44 /// constantexprs, this function is recursive.
45 static bool IsConstantOffsetFromGlobal(Constant *C, GlobalValue *&GV,
46                                        int64_t &Offset, const TargetData &TD) {
47   // Trivial case, constant is the global.
48   if ((GV = dyn_cast<GlobalValue>(C))) {
49     Offset = 0;
50     return true;
51   }
52   
53   // Otherwise, if this isn't a constant expr, bail out.
54   ConstantExpr *CE = dyn_cast<ConstantExpr>(C);
55   if (!CE) return false;
56   
57   // Look through ptr->int and ptr->ptr casts.
58   if (CE->getOpcode() == Instruction::PtrToInt ||
59       CE->getOpcode() == Instruction::BitCast)
60     return IsConstantOffsetFromGlobal(CE->getOperand(0), GV, Offset, TD);
61   
62   // i32* getelementptr ([5 x i32]* @a, i32 0, i32 5)    
63   if (CE->getOpcode() == Instruction::GetElementPtr) {
64     // Cannot compute this if the element type of the pointer is missing size
65     // info.
66     if (!cast<PointerType>(CE->getOperand(0)->getType())
67                  ->getElementType()->isSized())
68       return false;
69     
70     // If the base isn't a global+constant, we aren't either.
71     if (!IsConstantOffsetFromGlobal(CE->getOperand(0), GV, Offset, TD))
72       return false;
73     
74     // Otherwise, add any offset that our operands provide.
75     gep_type_iterator GTI = gep_type_begin(CE);
76     for (User::const_op_iterator i = CE->op_begin() + 1, e = CE->op_end();
77          i != e; ++i, ++GTI) {
78       ConstantInt *CI = dyn_cast<ConstantInt>(*i);
79       if (!CI) return false;  // Index isn't a simple constant?
80       if (CI->getZExtValue() == 0) continue;  // Not adding anything.
81       
82       if (const StructType *ST = dyn_cast<StructType>(*GTI)) {
83         // N = N + Offset
84         Offset += TD.getStructLayout(ST)->getElementOffset(CI->getZExtValue());
85       } else {
86         const SequentialType *SQT = cast<SequentialType>(*GTI);
87         Offset += TD.getTypeAllocSize(SQT->getElementType())*CI->getSExtValue();
88       }
89     }
90     return true;
91   }
92   
93   return false;
94 }
95
96 /// ConstantFoldLoadFromConstPtr - Return the value that a load from C would
97 /// produce if it is constant and determinable.  If this is not determinable,
98 /// return null.
99 Constant *llvm::ConstantFoldLoadFromConstPtr(Constant *C,
100                                              const TargetData *TD) {
101   // First, try the easy cases:
102   if (GlobalVariable *GV = dyn_cast<GlobalVariable>(C))
103     if (GV->isConstant() && GV->hasDefinitiveInitializer())
104       return GV->getInitializer();
105
106   // If the loaded value isn't a constant expr, we can't handle it.
107   ConstantExpr *CE = dyn_cast<ConstantExpr>(C);
108   if (!CE) return 0;
109   
110   if (CE->getOpcode() == Instruction::GetElementPtr) {
111     if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
112       if (GV->isConstant() && GV->hasDefinitiveInitializer())
113         if (Constant *V = 
114              ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE))
115           return V;
116   }
117   
118   // Instead of loading constant c string, use corresponding integer value
119   // directly if string length is small enough.
120   std::string Str;
121   if (TD && GetConstantStringInfo(CE->getOperand(0), Str) && !Str.empty()) {
122     unsigned len = Str.length();
123     const Type *Ty = cast<PointerType>(CE->getType())->getElementType();
124     unsigned numBits = Ty->getPrimitiveSizeInBits();
125     // Replace LI with immediate integer store.
126     if ((numBits >> 3) == len + 1) {
127       APInt StrVal(numBits, 0);
128       APInt SingleChar(numBits, 0);
129       if (TD->isLittleEndian()) {
130         for (signed i = len-1; i >= 0; i--) {
131           SingleChar = (uint64_t) Str[i] & UCHAR_MAX;
132           StrVal = (StrVal << 8) | SingleChar;
133         }
134       } else {
135         for (unsigned i = 0; i < len; i++) {
136           SingleChar = (uint64_t) Str[i] & UCHAR_MAX;
137           StrVal = (StrVal << 8) | SingleChar;
138         }
139         // Append NULL at the end.
140         SingleChar = 0;
141         StrVal = (StrVal << 8) | SingleChar;
142       }
143       return ConstantInt::get(CE->getContext(), StrVal);
144     }
145   }
146   
147   // If this load comes from anywhere in a constant global, and if the global
148   // is all undef or zero, we know what it loads.
149   if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getUnderlyingObject())){
150     if (GV->isConstant() && GV->hasDefinitiveInitializer()) {
151       const Type *ResTy = cast<PointerType>(C->getType())->getElementType();
152       if (GV->getInitializer()->isNullValue())
153         return Constant::getNullValue(ResTy);
154       if (isa<UndefValue>(GV->getInitializer()))
155         return UndefValue::get(ResTy);
156     }
157   }
158   
159   return 0;
160 }
161
162 static Constant *ConstantFoldLoadInst(const LoadInst *LI, const TargetData *TD){
163   if (LI->isVolatile()) return 0;
164   
165   if (Constant *C = dyn_cast<Constant>(LI->getOperand(0)))
166     return ConstantFoldLoadFromConstPtr(C, TD);
167     
168   return 0;
169 }
170
171 /// SymbolicallyEvaluateBinop - One of Op0/Op1 is a constant expression.
172 /// Attempt to symbolically evaluate the result of a binary operator merging
173 /// these together.  If target data info is available, it is provided as TD, 
174 /// otherwise TD is null.
175 static Constant *SymbolicallyEvaluateBinop(unsigned Opc, Constant *Op0,
176                                            Constant *Op1, const TargetData *TD,
177                                            LLVMContext &Context){
178   // SROA
179   
180   // Fold (and 0xffffffff00000000, (shl x, 32)) -> shl.
181   // Fold (lshr (or X, Y), 32) -> (lshr [X/Y], 32) if one doesn't contribute
182   // bits.
183   
184   
185   // If the constant expr is something like &A[123] - &A[4].f, fold this into a
186   // constant.  This happens frequently when iterating over a global array.
187   if (Opc == Instruction::Sub && TD) {
188     GlobalValue *GV1, *GV2;
189     int64_t Offs1, Offs2;
190     
191     if (IsConstantOffsetFromGlobal(Op0, GV1, Offs1, *TD))
192       if (IsConstantOffsetFromGlobal(Op1, GV2, Offs2, *TD) &&
193           GV1 == GV2) {
194         // (&GV+C1) - (&GV+C2) -> C1-C2, pointer arithmetic cannot overflow.
195         return ConstantInt::get(Op0->getType(), Offs1-Offs2);
196       }
197   }
198     
199   return 0;
200 }
201
202 /// SymbolicallyEvaluateGEP - If we can symbolically evaluate the specified GEP
203 /// constant expression, do so.
204 static Constant *SymbolicallyEvaluateGEP(Constant* const* Ops, unsigned NumOps,
205                                          const Type *ResultTy,
206                                          LLVMContext &Context,
207                                          const TargetData *TD) {
208   Constant *Ptr = Ops[0];
209   if (!TD || !cast<PointerType>(Ptr->getType())->getElementType()->isSized())
210     return 0;
211
212   unsigned BitWidth = TD->getTypeSizeInBits(TD->getIntPtrType(Context));
213   APInt BasePtr(BitWidth, 0);
214   bool BaseIsInt = true;
215   if (!Ptr->isNullValue()) {
216     // If this is a inttoptr from a constant int, we can fold this as the base,
217     // otherwise we can't.
218     if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
219       if (CE->getOpcode() == Instruction::IntToPtr)
220         if (ConstantInt *Base = dyn_cast<ConstantInt>(CE->getOperand(0))) {
221           BasePtr = Base->getValue();
222           BasePtr.zextOrTrunc(BitWidth);
223         }
224     
225     if (BasePtr == 0)
226       BaseIsInt = false;
227   }
228
229   // If this is a constant expr gep that is effectively computing an
230   // "offsetof", fold it into 'cast int Size to T*' instead of 'gep 0, 0, 12'
231   for (unsigned i = 1; i != NumOps; ++i)
232     if (!isa<ConstantInt>(Ops[i]))
233       return 0;
234   
235   APInt Offset = APInt(BitWidth,
236                        TD->getIndexedOffset(Ptr->getType(),
237                                             (Value**)Ops+1, NumOps-1));
238   // If the base value for this address is a literal integer value, fold the
239   // getelementptr to the resulting integer value casted to the pointer type.
240   if (BaseIsInt) {
241     Constant *C = ConstantInt::get(Context, Offset+BasePtr);
242     return ConstantExpr::getIntToPtr(C, ResultTy);
243   }
244
245   // Otherwise form a regular getelementptr. Recompute the indices so that
246   // we eliminate over-indexing of the notional static type array bounds.
247   // This makes it easy to determine if the getelementptr is "inbounds".
248   // Also, this helps GlobalOpt do SROA on GlobalVariables.
249   const Type *Ty = Ptr->getType();
250   SmallVector<Constant*, 32> NewIdxs;
251   do {
252     if (const SequentialType *ATy = dyn_cast<SequentialType>(Ty)) {
253       // The only pointer indexing we'll do is on the first index of the GEP.
254       if (isa<PointerType>(ATy) && !NewIdxs.empty())
255         break;
256       // Determine which element of the array the offset points into.
257       APInt ElemSize(BitWidth, TD->getTypeAllocSize(ATy->getElementType()));
258       if (ElemSize == 0)
259         return 0;
260       APInt NewIdx = Offset.udiv(ElemSize);
261       Offset -= NewIdx * ElemSize;
262       NewIdxs.push_back(ConstantInt::get(TD->getIntPtrType(Context), NewIdx));
263       Ty = ATy->getElementType();
264     } else if (const StructType *STy = dyn_cast<StructType>(Ty)) {
265       // Determine which field of the struct the offset points into. The
266       // getZExtValue is at least as safe as the StructLayout API because we
267       // know the offset is within the struct at this point.
268       const StructLayout &SL = *TD->getStructLayout(STy);
269       unsigned ElIdx = SL.getElementContainingOffset(Offset.getZExtValue());
270       NewIdxs.push_back(ConstantInt::get(Type::getInt32Ty(Context), ElIdx));
271       Offset -= APInt(BitWidth, SL.getElementOffset(ElIdx));
272       Ty = STy->getTypeAtIndex(ElIdx);
273     } else {
274       // We've reached some non-indexable type.
275       break;
276     }
277   } while (Ty != cast<PointerType>(ResultTy)->getElementType());
278
279   // If we haven't used up the entire offset by descending the static
280   // type, then the offset is pointing into the middle of an indivisible
281   // member, so we can't simplify it.
282   if (Offset != 0)
283     return 0;
284
285   // Create a GEP.
286   Constant *C =
287     ConstantExpr::getGetElementPtr(Ptr, &NewIdxs[0], NewIdxs.size());
288   assert(cast<PointerType>(C->getType())->getElementType() == Ty &&
289          "Computed GetElementPtr has unexpected type!");
290
291   // If we ended up indexing a member with a type that doesn't match
292   // the type of what the original indices indexed, add a cast.
293   if (Ty != cast<PointerType>(ResultTy)->getElementType())
294     C = ConstantExpr::getBitCast(C, ResultTy);
295
296   return C;
297 }
298
299 /// FoldBitCast - Constant fold bitcast, symbolically evaluating it with 
300 /// targetdata.  Return 0 if unfoldable.
301 static Constant *FoldBitCast(Constant *C, const Type *DestTy,
302                              const TargetData &TD, LLVMContext &Context) {
303   // If this is a bitcast from constant vector -> vector, fold it.
304   if (ConstantVector *CV = dyn_cast<ConstantVector>(C)) {
305     if (const VectorType *DestVTy = dyn_cast<VectorType>(DestTy)) {
306       // If the element types match, VMCore can fold it.
307       unsigned NumDstElt = DestVTy->getNumElements();
308       unsigned NumSrcElt = CV->getNumOperands();
309       if (NumDstElt == NumSrcElt)
310         return 0;
311       
312       const Type *SrcEltTy = CV->getType()->getElementType();
313       const Type *DstEltTy = DestVTy->getElementType();
314       
315       // Otherwise, we're changing the number of elements in a vector, which 
316       // requires endianness information to do the right thing.  For example,
317       //    bitcast (<2 x i64> <i64 0, i64 1> to <4 x i32>)
318       // folds to (little endian):
319       //    <4 x i32> <i32 0, i32 0, i32 1, i32 0>
320       // and to (big endian):
321       //    <4 x i32> <i32 0, i32 0, i32 0, i32 1>
322       
323       // First thing is first.  We only want to think about integer here, so if
324       // we have something in FP form, recast it as integer.
325       if (DstEltTy->isFloatingPoint()) {
326         // Fold to an vector of integers with same size as our FP type.
327         unsigned FPWidth = DstEltTy->getPrimitiveSizeInBits();
328         const Type *DestIVTy = VectorType::get(
329                                  IntegerType::get(Context, FPWidth), NumDstElt);
330         // Recursively handle this integer conversion, if possible.
331         C = FoldBitCast(C, DestIVTy, TD, Context);
332         if (!C) return 0;
333         
334         // Finally, VMCore can handle this now that #elts line up.
335         return ConstantExpr::getBitCast(C, DestTy);
336       }
337       
338       // Okay, we know the destination is integer, if the input is FP, convert
339       // it to integer first.
340       if (SrcEltTy->isFloatingPoint()) {
341         unsigned FPWidth = SrcEltTy->getPrimitiveSizeInBits();
342         const Type *SrcIVTy = VectorType::get(
343                                  IntegerType::get(Context, FPWidth), NumSrcElt);
344         // Ask VMCore to do the conversion now that #elts line up.
345         C = ConstantExpr::getBitCast(C, SrcIVTy);
346         CV = dyn_cast<ConstantVector>(C);
347         if (!CV) return 0;  // If VMCore wasn't able to fold it, bail out.
348       }
349       
350       // Now we know that the input and output vectors are both integer vectors
351       // of the same size, and that their #elements is not the same.  Do the
352       // conversion here, which depends on whether the input or output has
353       // more elements.
354       bool isLittleEndian = TD.isLittleEndian();
355       
356       SmallVector<Constant*, 32> Result;
357       if (NumDstElt < NumSrcElt) {
358         // Handle: bitcast (<4 x i32> <i32 0, i32 1, i32 2, i32 3> to <2 x i64>)
359         Constant *Zero = Constant::getNullValue(DstEltTy);
360         unsigned Ratio = NumSrcElt/NumDstElt;
361         unsigned SrcBitSize = SrcEltTy->getPrimitiveSizeInBits();
362         unsigned SrcElt = 0;
363         for (unsigned i = 0; i != NumDstElt; ++i) {
364           // Build each element of the result.
365           Constant *Elt = Zero;
366           unsigned ShiftAmt = isLittleEndian ? 0 : SrcBitSize*(Ratio-1);
367           for (unsigned j = 0; j != Ratio; ++j) {
368             Constant *Src = dyn_cast<ConstantInt>(CV->getOperand(SrcElt++));
369             if (!Src) return 0;  // Reject constantexpr elements.
370             
371             // Zero extend the element to the right size.
372             Src = ConstantExpr::getZExt(Src, Elt->getType());
373             
374             // Shift it to the right place, depending on endianness.
375             Src = ConstantExpr::getShl(Src, 
376                              ConstantInt::get(Src->getType(), ShiftAmt));
377             ShiftAmt += isLittleEndian ? SrcBitSize : -SrcBitSize;
378             
379             // Mix it in.
380             Elt = ConstantExpr::getOr(Elt, Src);
381           }
382           Result.push_back(Elt);
383         }
384       } else {
385         // Handle: bitcast (<2 x i64> <i64 0, i64 1> to <4 x i32>)
386         unsigned Ratio = NumDstElt/NumSrcElt;
387         unsigned DstBitSize = DstEltTy->getPrimitiveSizeInBits();
388         
389         // Loop over each source value, expanding into multiple results.
390         for (unsigned i = 0; i != NumSrcElt; ++i) {
391           Constant *Src = dyn_cast<ConstantInt>(CV->getOperand(i));
392           if (!Src) return 0;  // Reject constantexpr elements.
393
394           unsigned ShiftAmt = isLittleEndian ? 0 : DstBitSize*(Ratio-1);
395           for (unsigned j = 0; j != Ratio; ++j) {
396             // Shift the piece of the value into the right place, depending on
397             // endianness.
398             Constant *Elt = ConstantExpr::getLShr(Src, 
399                             ConstantInt::get(Src->getType(), ShiftAmt));
400             ShiftAmt += isLittleEndian ? DstBitSize : -DstBitSize;
401
402             // Truncate and remember this piece.
403             Result.push_back(ConstantExpr::getTrunc(Elt, DstEltTy));
404           }
405         }
406       }
407       
408       return ConstantVector::get(Result.data(), Result.size());
409     }
410   }
411   
412   return 0;
413 }
414
415
416 //===----------------------------------------------------------------------===//
417 // Constant Folding public APIs
418 //===----------------------------------------------------------------------===//
419
420
421 /// ConstantFoldInstruction - Attempt to constant fold the specified
422 /// instruction.  If successful, the constant result is returned, if not, null
423 /// is returned.  Note that this function can only fail when attempting to fold
424 /// instructions like loads and stores, which have no constant expression form.
425 ///
426 Constant *llvm::ConstantFoldInstruction(Instruction *I, LLVMContext &Context,
427                                         const TargetData *TD) {
428   if (PHINode *PN = dyn_cast<PHINode>(I)) {
429     if (PN->getNumIncomingValues() == 0)
430       return UndefValue::get(PN->getType());
431
432     Constant *Result = dyn_cast<Constant>(PN->getIncomingValue(0));
433     if (Result == 0) return 0;
434
435     // Handle PHI nodes specially here...
436     for (unsigned i = 1, e = PN->getNumIncomingValues(); i != e; ++i)
437       if (PN->getIncomingValue(i) != Result && PN->getIncomingValue(i) != PN)
438         return 0;   // Not all the same incoming constants...
439
440     // If we reach here, all incoming values are the same constant.
441     return Result;
442   }
443
444   // Scan the operand list, checking to see if they are all constants, if so,
445   // hand off to ConstantFoldInstOperands.
446   SmallVector<Constant*, 8> Ops;
447   for (User::op_iterator i = I->op_begin(), e = I->op_end(); i != e; ++i)
448     if (Constant *Op = dyn_cast<Constant>(*i))
449       Ops.push_back(Op);
450     else
451       return 0;  // All operands not constant!
452
453   if (const CmpInst *CI = dyn_cast<CmpInst>(I))
454     return ConstantFoldCompareInstOperands(CI->getPredicate(),
455                                            Ops.data(), Ops.size(), 
456                                            Context, TD);
457   
458   if (const LoadInst *LI = dyn_cast<LoadInst>(I))
459     return ConstantFoldLoadInst(LI, TD);
460   
461   return ConstantFoldInstOperands(I->getOpcode(), I->getType(),
462                                   Ops.data(), Ops.size(), Context, TD);
463 }
464
465 /// ConstantFoldConstantExpression - Attempt to fold the constant expression
466 /// using the specified TargetData.  If successful, the constant result is
467 /// result is returned, if not, null is returned.
468 Constant *llvm::ConstantFoldConstantExpression(ConstantExpr *CE,
469                                                LLVMContext &Context,
470                                                const TargetData *TD) {
471   SmallVector<Constant*, 8> Ops;
472   for (User::op_iterator i = CE->op_begin(), e = CE->op_end(); i != e; ++i)
473     Ops.push_back(cast<Constant>(*i));
474
475   if (CE->isCompare())
476     return ConstantFoldCompareInstOperands(CE->getPredicate(),
477                                            Ops.data(), Ops.size(), 
478                                            Context, TD);
479   return ConstantFoldInstOperands(CE->getOpcode(), CE->getType(),
480                                   Ops.data(), Ops.size(), Context, TD);
481 }
482
483 /// ConstantFoldInstOperands - Attempt to constant fold an instruction with the
484 /// specified opcode and operands.  If successful, the constant result is
485 /// returned, if not, null is returned.  Note that this function can fail when
486 /// attempting to fold instructions like loads and stores, which have no
487 /// constant expression form.
488 ///
489 Constant *llvm::ConstantFoldInstOperands(unsigned Opcode, const Type *DestTy, 
490                                          Constant* const* Ops, unsigned NumOps,
491                                          LLVMContext &Context,
492                                          const TargetData *TD) {
493   // Handle easy binops first.
494   if (Instruction::isBinaryOp(Opcode)) {
495     if (isa<ConstantExpr>(Ops[0]) || isa<ConstantExpr>(Ops[1]))
496       if (Constant *C = SymbolicallyEvaluateBinop(Opcode, Ops[0], Ops[1], TD,
497                                                   Context))
498         return C;
499     
500     return ConstantExpr::get(Opcode, Ops[0], Ops[1]);
501   }
502   
503   switch (Opcode) {
504   default: return 0;
505   case Instruction::Call:
506     if (Function *F = dyn_cast<Function>(Ops[0]))
507       if (canConstantFoldCallTo(F))
508         return ConstantFoldCall(F, Ops+1, NumOps-1);
509     return 0;
510   case Instruction::ICmp:
511   case Instruction::FCmp:
512     llvm_unreachable("This function is invalid for compares: no predicate specified");
513   case Instruction::PtrToInt:
514     // If the input is a inttoptr, eliminate the pair.  This requires knowing
515     // the width of a pointer, so it can't be done in ConstantExpr::getCast.
516     if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ops[0])) {
517       if (TD && CE->getOpcode() == Instruction::IntToPtr) {
518         Constant *Input = CE->getOperand(0);
519         unsigned InWidth = Input->getType()->getScalarSizeInBits();
520         if (TD->getPointerSizeInBits() < InWidth) {
521           Constant *Mask = 
522             ConstantInt::get(Context, APInt::getLowBitsSet(InWidth,
523                                                   TD->getPointerSizeInBits()));
524           Input = ConstantExpr::getAnd(Input, Mask);
525         }
526         // Do a zext or trunc to get to the dest size.
527         return ConstantExpr::getIntegerCast(Input, DestTy, false);
528       }
529     }
530     return ConstantExpr::getCast(Opcode, Ops[0], DestTy);
531   case Instruction::IntToPtr:
532     // If the input is a ptrtoint, turn the pair into a ptr to ptr bitcast if
533     // the int size is >= the ptr size.  This requires knowing the width of a
534     // pointer, so it can't be done in ConstantExpr::getCast.
535     if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ops[0])) {
536       if (TD &&
537           TD->getPointerSizeInBits() <=
538           CE->getType()->getScalarSizeInBits()) {
539         if (CE->getOpcode() == Instruction::PtrToInt) {
540           Constant *Input = CE->getOperand(0);
541           Constant *C = FoldBitCast(Input, DestTy, *TD, Context);
542           return C ? C : ConstantExpr::getBitCast(Input, DestTy);
543         }
544         // If there's a constant offset added to the integer value before
545         // it is casted back to a pointer, see if the expression can be
546         // converted into a GEP.
547         if (CE->getOpcode() == Instruction::Add)
548           if (ConstantInt *L = dyn_cast<ConstantInt>(CE->getOperand(0)))
549             if (ConstantExpr *R = dyn_cast<ConstantExpr>(CE->getOperand(1)))
550               if (R->getOpcode() == Instruction::PtrToInt)
551                 if (GlobalVariable *GV =
552                       dyn_cast<GlobalVariable>(R->getOperand(0))) {
553                   const PointerType *GVTy = cast<PointerType>(GV->getType());
554                   if (const ArrayType *AT =
555                         dyn_cast<ArrayType>(GVTy->getElementType())) {
556                     const Type *ElTy = AT->getElementType();
557                     uint64_t AllocSize = TD->getTypeAllocSize(ElTy);
558                     APInt PSA(L->getValue().getBitWidth(), AllocSize);
559                     if (ElTy == cast<PointerType>(DestTy)->getElementType() &&
560                         L->getValue().urem(PSA) == 0) {
561                       APInt ElemIdx = L->getValue().udiv(PSA);
562                       if (ElemIdx.ult(APInt(ElemIdx.getBitWidth(),
563                                             AT->getNumElements()))) {
564                         Constant *Index[] = {
565                           Constant::getNullValue(CE->getType()),
566                           ConstantInt::get(Context, ElemIdx)
567                         };
568                         return
569                         ConstantExpr::getGetElementPtr(GV, &Index[0], 2);
570                       }
571                     }
572                   }
573                 }
574       }
575     }
576     return ConstantExpr::getCast(Opcode, Ops[0], DestTy);
577   case Instruction::Trunc:
578   case Instruction::ZExt:
579   case Instruction::SExt:
580   case Instruction::FPTrunc:
581   case Instruction::FPExt:
582   case Instruction::UIToFP:
583   case Instruction::SIToFP:
584   case Instruction::FPToUI:
585   case Instruction::FPToSI:
586       return ConstantExpr::getCast(Opcode, Ops[0], DestTy);
587   case Instruction::BitCast:
588     if (TD)
589       if (Constant *C = FoldBitCast(Ops[0], DestTy, *TD, Context))
590         return C;
591     return ConstantExpr::getBitCast(Ops[0], DestTy);
592   case Instruction::Select:
593     return ConstantExpr::getSelect(Ops[0], Ops[1], Ops[2]);
594   case Instruction::ExtractElement:
595     return ConstantExpr::getExtractElement(Ops[0], Ops[1]);
596   case Instruction::InsertElement:
597     return ConstantExpr::getInsertElement(Ops[0], Ops[1], Ops[2]);
598   case Instruction::ShuffleVector:
599     return ConstantExpr::getShuffleVector(Ops[0], Ops[1], Ops[2]);
600   case Instruction::GetElementPtr:
601     if (Constant *C = SymbolicallyEvaluateGEP(Ops, NumOps, DestTy, Context, TD))
602       return C;
603     
604     return ConstantExpr::getGetElementPtr(Ops[0], Ops+1, NumOps-1);
605   }
606 }
607
608 /// ConstantFoldCompareInstOperands - Attempt to constant fold a compare
609 /// instruction (icmp/fcmp) with the specified operands.  If it fails, it
610 /// returns a constant expression of the specified operands.
611 ///
612 Constant *llvm::ConstantFoldCompareInstOperands(unsigned Predicate,
613                                                 Constant*const * Ops, 
614                                                 unsigned NumOps,
615                                                 LLVMContext &Context,
616                                                 const TargetData *TD) {
617   // fold: icmp (inttoptr x), null         -> icmp x, 0
618   // fold: icmp (ptrtoint x), 0            -> icmp x, null
619   // fold: icmp (inttoptr x), (inttoptr y) -> icmp trunc/zext x, trunc/zext y
620   // fold: icmp (ptrtoint x), (ptrtoint y) -> icmp x, y
621   //
622   // ConstantExpr::getCompare cannot do this, because it doesn't have TD
623   // around to know if bit truncation is happening.
624   if (ConstantExpr *CE0 = dyn_cast<ConstantExpr>(Ops[0])) {
625     if (TD && Ops[1]->isNullValue()) {
626       const Type *IntPtrTy = TD->getIntPtrType(Context);
627       if (CE0->getOpcode() == Instruction::IntToPtr) {
628         // Convert the integer value to the right size to ensure we get the
629         // proper extension or truncation.
630         Constant *C = ConstantExpr::getIntegerCast(CE0->getOperand(0),
631                                                    IntPtrTy, false);
632         Constant *NewOps[] = { C, Constant::getNullValue(C->getType()) };
633         return ConstantFoldCompareInstOperands(Predicate, NewOps, 2,
634                                                Context, TD);
635       }
636       
637       // Only do this transformation if the int is intptrty in size, otherwise
638       // there is a truncation or extension that we aren't modeling.
639       if (CE0->getOpcode() == Instruction::PtrToInt && 
640           CE0->getType() == IntPtrTy) {
641         Constant *C = CE0->getOperand(0);
642         Constant *NewOps[] = { C, Constant::getNullValue(C->getType()) };
643         // FIXME!
644         return ConstantFoldCompareInstOperands(Predicate, NewOps, 2,
645                                                Context, TD);
646       }
647     }
648     
649     if (ConstantExpr *CE1 = dyn_cast<ConstantExpr>(Ops[1])) {
650       if (TD && CE0->getOpcode() == CE1->getOpcode()) {
651         const Type *IntPtrTy = TD->getIntPtrType(Context);
652
653         if (CE0->getOpcode() == Instruction::IntToPtr) {
654           // Convert the integer value to the right size to ensure we get the
655           // proper extension or truncation.
656           Constant *C0 = ConstantExpr::getIntegerCast(CE0->getOperand(0),
657                                                       IntPtrTy, false);
658           Constant *C1 = ConstantExpr::getIntegerCast(CE1->getOperand(0),
659                                                       IntPtrTy, false);
660           Constant *NewOps[] = { C0, C1 };
661           return ConstantFoldCompareInstOperands(Predicate, NewOps, 2, 
662                                                  Context, TD);
663         }
664
665         // Only do this transformation if the int is intptrty in size, otherwise
666         // there is a truncation or extension that we aren't modeling.
667         if ((CE0->getOpcode() == Instruction::PtrToInt &&
668              CE0->getType() == IntPtrTy &&
669              CE0->getOperand(0)->getType() == CE1->getOperand(0)->getType())) {
670           Constant *NewOps[] = { 
671             CE0->getOperand(0), CE1->getOperand(0) 
672           };
673           return ConstantFoldCompareInstOperands(Predicate, NewOps, 2, 
674                                                  Context, TD);
675         }
676       }
677     }
678   }
679   return ConstantExpr::getCompare(Predicate, Ops[0], Ops[1]);
680 }
681
682
683 /// ConstantFoldLoadThroughGEPConstantExpr - Given a constant and a
684 /// getelementptr constantexpr, return the constant value being addressed by the
685 /// constant expression, or null if something is funny and we can't decide.
686 Constant *llvm::ConstantFoldLoadThroughGEPConstantExpr(Constant *C, 
687                                                        ConstantExpr *CE) {
688   if (CE->getOperand(1) != Constant::getNullValue(CE->getOperand(1)->getType()))
689     return 0;  // Do not allow stepping over the value!
690   
691   // Loop over all of the operands, tracking down which value we are
692   // addressing...
693   gep_type_iterator I = gep_type_begin(CE), E = gep_type_end(CE);
694   for (++I; I != E; ++I)
695     if (const StructType *STy = dyn_cast<StructType>(*I)) {
696       ConstantInt *CU = cast<ConstantInt>(I.getOperand());
697       assert(CU->getZExtValue() < STy->getNumElements() &&
698              "Struct index out of range!");
699       unsigned El = (unsigned)CU->getZExtValue();
700       if (ConstantStruct *CS = dyn_cast<ConstantStruct>(C)) {
701         C = CS->getOperand(El);
702       } else if (isa<ConstantAggregateZero>(C)) {
703         C = Constant::getNullValue(STy->getElementType(El));
704       } else if (isa<UndefValue>(C)) {
705         C = UndefValue::get(STy->getElementType(El));
706       } else {
707         return 0;
708       }
709     } else if (ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand())) {
710       if (const ArrayType *ATy = dyn_cast<ArrayType>(*I)) {
711         if (CI->getZExtValue() >= ATy->getNumElements())
712          return 0;
713         if (ConstantArray *CA = dyn_cast<ConstantArray>(C))
714           C = CA->getOperand(CI->getZExtValue());
715         else if (isa<ConstantAggregateZero>(C))
716           C = Constant::getNullValue(ATy->getElementType());
717         else if (isa<UndefValue>(C))
718           C = UndefValue::get(ATy->getElementType());
719         else
720           return 0;
721       } else if (const VectorType *VTy = dyn_cast<VectorType>(*I)) {
722         if (CI->getZExtValue() >= VTy->getNumElements())
723           return 0;
724         if (ConstantVector *CP = dyn_cast<ConstantVector>(C))
725           C = CP->getOperand(CI->getZExtValue());
726         else if (isa<ConstantAggregateZero>(C))
727           C = Constant::getNullValue(VTy->getElementType());
728         else if (isa<UndefValue>(C))
729           C = UndefValue::get(VTy->getElementType());
730         else
731           return 0;
732       } else {
733         return 0;
734       }
735     } else {
736       return 0;
737     }
738   return C;
739 }
740
741
742 //===----------------------------------------------------------------------===//
743 //  Constant Folding for Calls
744 //
745
746 /// canConstantFoldCallTo - Return true if its even possible to fold a call to
747 /// the specified function.
748 bool
749 llvm::canConstantFoldCallTo(const Function *F) {
750   switch (F->getIntrinsicID()) {
751   case Intrinsic::sqrt:
752   case Intrinsic::powi:
753   case Intrinsic::bswap:
754   case Intrinsic::ctpop:
755   case Intrinsic::ctlz:
756   case Intrinsic::cttz:
757   case Intrinsic::uadd_with_overflow:
758   case Intrinsic::usub_with_overflow:
759   case Intrinsic::sadd_with_overflow:
760   case Intrinsic::ssub_with_overflow:
761     return true;
762   default:
763     return false;
764   case 0: break;
765   }
766
767   if (!F->hasName()) return false;
768   StringRef Name = F->getName();
769   
770   // In these cases, the check of the length is required.  We don't want to
771   // return true for a name like "cos\0blah" which strcmp would return equal to
772   // "cos", but has length 8.
773   switch (Name[0]) {
774   default: return false;
775   case 'a':
776     return Name == "acos" || Name == "asin" || 
777       Name == "atan" || Name == "atan2";
778   case 'c':
779     return Name == "cos" || Name == "ceil" || Name == "cosf" || Name == "cosh";
780   case 'e':
781     return Name == "exp";
782   case 'f':
783     return Name == "fabs" || Name == "fmod" || Name == "floor";
784   case 'l':
785     return Name == "log" || Name == "log10";
786   case 'p':
787     return Name == "pow";
788   case 's':
789     return Name == "sin" || Name == "sinh" || Name == "sqrt" ||
790       Name == "sinf" || Name == "sqrtf";
791   case 't':
792     return Name == "tan" || Name == "tanh";
793   }
794 }
795
796 static Constant *ConstantFoldFP(double (*NativeFP)(double), double V, 
797                                 const Type *Ty, LLVMContext &Context) {
798   errno = 0;
799   V = NativeFP(V);
800   if (errno != 0) {
801     errno = 0;
802     return 0;
803   }
804   
805   if (Ty->isFloatTy())
806     return ConstantFP::get(Context, APFloat((float)V));
807   if (Ty->isDoubleTy())
808     return ConstantFP::get(Context, APFloat(V));
809   llvm_unreachable("Can only constant fold float/double");
810   return 0; // dummy return to suppress warning
811 }
812
813 static Constant *ConstantFoldBinaryFP(double (*NativeFP)(double, double),
814                                       double V, double W,
815                                       const Type *Ty,
816                                       LLVMContext &Context) {
817   errno = 0;
818   V = NativeFP(V, W);
819   if (errno != 0) {
820     errno = 0;
821     return 0;
822   }
823   
824   if (Ty->isFloatTy())
825     return ConstantFP::get(Context, APFloat((float)V));
826   if (Ty->isDoubleTy())
827     return ConstantFP::get(Context, APFloat(V));
828   llvm_unreachable("Can only constant fold float/double");
829   return 0; // dummy return to suppress warning
830 }
831
832 /// ConstantFoldCall - Attempt to constant fold a call to the specified function
833 /// with the specified arguments, returning null if unsuccessful.
834 Constant *
835 llvm::ConstantFoldCall(Function *F, 
836                        Constant *const *Operands, unsigned NumOperands) {
837   if (!F->hasName()) return 0;
838   LLVMContext &Context = F->getContext();
839   StringRef Name = F->getName();
840
841   const Type *Ty = F->getReturnType();
842   if (NumOperands == 1) {
843     if (ConstantFP *Op = dyn_cast<ConstantFP>(Operands[0])) {
844       if (!Ty->isFloatTy() && !Ty->isDoubleTy())
845         return 0;
846       /// Currently APFloat versions of these functions do not exist, so we use
847       /// the host native double versions.  Float versions are not called
848       /// directly but for all these it is true (float)(f((double)arg)) ==
849       /// f(arg).  Long double not supported yet.
850       double V = Ty->isFloatTy() ? (double)Op->getValueAPF().convertToFloat() :
851                                      Op->getValueAPF().convertToDouble();
852       switch (Name[0]) {
853       case 'a':
854         if (Name == "acos")
855           return ConstantFoldFP(acos, V, Ty, Context);
856         else if (Name == "asin")
857           return ConstantFoldFP(asin, V, Ty, Context);
858         else if (Name == "atan")
859           return ConstantFoldFP(atan, V, Ty, Context);
860         break;
861       case 'c':
862         if (Name == "ceil")
863           return ConstantFoldFP(ceil, V, Ty, Context);
864         else if (Name == "cos")
865           return ConstantFoldFP(cos, V, Ty, Context);
866         else if (Name == "cosh")
867           return ConstantFoldFP(cosh, V, Ty, Context);
868         else if (Name == "cosf")
869           return ConstantFoldFP(cos, V, Ty, Context);
870         break;
871       case 'e':
872         if (Name == "exp")
873           return ConstantFoldFP(exp, V, Ty, Context);
874         break;
875       case 'f':
876         if (Name == "fabs")
877           return ConstantFoldFP(fabs, V, Ty, Context);
878         else if (Name == "floor")
879           return ConstantFoldFP(floor, V, Ty, Context);
880         break;
881       case 'l':
882         if (Name == "log" && V > 0)
883           return ConstantFoldFP(log, V, Ty, Context);
884         else if (Name == "log10" && V > 0)
885           return ConstantFoldFP(log10, V, Ty, Context);
886         else if (Name == "llvm.sqrt.f32" ||
887                  Name == "llvm.sqrt.f64") {
888           if (V >= -0.0)
889             return ConstantFoldFP(sqrt, V, Ty, Context);
890           else // Undefined
891             return Constant::getNullValue(Ty);
892         }
893         break;
894       case 's':
895         if (Name == "sin")
896           return ConstantFoldFP(sin, V, Ty, Context);
897         else if (Name == "sinh")
898           return ConstantFoldFP(sinh, V, Ty, Context);
899         else if (Name == "sqrt" && V >= 0)
900           return ConstantFoldFP(sqrt, V, Ty, Context);
901         else if (Name == "sqrtf" && V >= 0)
902           return ConstantFoldFP(sqrt, V, Ty, Context);
903         else if (Name == "sinf")
904           return ConstantFoldFP(sin, V, Ty, Context);
905         break;
906       case 't':
907         if (Name == "tan")
908           return ConstantFoldFP(tan, V, Ty, Context);
909         else if (Name == "tanh")
910           return ConstantFoldFP(tanh, V, Ty, Context);
911         break;
912       default:
913         break;
914       }
915       return 0;
916     }
917     
918     
919     if (ConstantInt *Op = dyn_cast<ConstantInt>(Operands[0])) {
920       if (Name.startswith("llvm.bswap"))
921         return ConstantInt::get(Context, Op->getValue().byteSwap());
922       else if (Name.startswith("llvm.ctpop"))
923         return ConstantInt::get(Ty, Op->getValue().countPopulation());
924       else if (Name.startswith("llvm.cttz"))
925         return ConstantInt::get(Ty, Op->getValue().countTrailingZeros());
926       else if (Name.startswith("llvm.ctlz"))
927         return ConstantInt::get(Ty, Op->getValue().countLeadingZeros());
928       return 0;
929     }
930     
931     return 0;
932   }
933   
934   if (NumOperands == 2) {
935     if (ConstantFP *Op1 = dyn_cast<ConstantFP>(Operands[0])) {
936       if (!Ty->isFloatTy() && !Ty->isDoubleTy())
937         return 0;
938       double Op1V = Ty->isFloatTy() ? 
939                       (double)Op1->getValueAPF().convertToFloat() :
940                       Op1->getValueAPF().convertToDouble();
941       if (ConstantFP *Op2 = dyn_cast<ConstantFP>(Operands[1])) {
942         if (Op2->getType() != Op1->getType())
943           return 0;
944         
945         double Op2V = Ty->isFloatTy() ? 
946                       (double)Op2->getValueAPF().convertToFloat():
947                       Op2->getValueAPF().convertToDouble();
948
949         if (Name == "pow")
950           return ConstantFoldBinaryFP(pow, Op1V, Op2V, Ty, Context);
951         if (Name == "fmod")
952           return ConstantFoldBinaryFP(fmod, Op1V, Op2V, Ty, Context);
953         if (Name == "atan2")
954           return ConstantFoldBinaryFP(atan2, Op1V, Op2V, Ty, Context);
955       } else if (ConstantInt *Op2C = dyn_cast<ConstantInt>(Operands[1])) {
956         if (Name == "llvm.powi.f32")
957           return ConstantFP::get(Context, APFloat((float)std::pow((float)Op1V,
958                                                  (int)Op2C->getZExtValue())));
959         if (Name == "llvm.powi.f64")
960           return ConstantFP::get(Context, APFloat((double)std::pow((double)Op1V,
961                                                  (int)Op2C->getZExtValue())));
962       }
963       return 0;
964     }
965     
966     
967     if (ConstantInt *Op1 = dyn_cast<ConstantInt>(Operands[0])) {
968       if (ConstantInt *Op2 = dyn_cast<ConstantInt>(Operands[1])) {
969         switch (F->getIntrinsicID()) {
970         default: break;
971         case Intrinsic::uadd_with_overflow: {
972           Constant *Res = ConstantExpr::getAdd(Op1, Op2);           // result.
973           Constant *Ops[] = {
974             Res, ConstantExpr::getICmp(CmpInst::ICMP_ULT, Res, Op1) // overflow.
975           };
976           return ConstantStruct::get(F->getContext(), Ops, 2, false);
977         }
978         case Intrinsic::usub_with_overflow: {
979           Constant *Res = ConstantExpr::getSub(Op1, Op2);           // result.
980           Constant *Ops[] = {
981             Res, ConstantExpr::getICmp(CmpInst::ICMP_UGT, Res, Op1) // overflow.
982           };
983           return ConstantStruct::get(F->getContext(), Ops, 2, false);
984         }
985         case Intrinsic::sadd_with_overflow: {
986           Constant *Res = ConstantExpr::getAdd(Op1, Op2);           // result.
987           Constant *Overflow = ConstantExpr::getSelect(
988               ConstantExpr::getICmp(CmpInst::ICMP_SGT,
989                 ConstantInt::get(Op1->getType(), 0), Op1),
990               ConstantExpr::getICmp(CmpInst::ICMP_SGT, Res, Op2), 
991               ConstantExpr::getICmp(CmpInst::ICMP_SLT, Res, Op2)); // overflow.
992
993           Constant *Ops[] = { Res, Overflow };
994           return ConstantStruct::get(F->getContext(), Ops, 2, false);
995         }
996         case Intrinsic::ssub_with_overflow: {
997           Constant *Res = ConstantExpr::getSub(Op1, Op2);           // result.
998           Constant *Overflow = ConstantExpr::getSelect(
999               ConstantExpr::getICmp(CmpInst::ICMP_SGT,
1000                 ConstantInt::get(Op2->getType(), 0), Op2),
1001               ConstantExpr::getICmp(CmpInst::ICMP_SLT, Res, Op1), 
1002               ConstantExpr::getICmp(CmpInst::ICMP_SGT, Res, Op1)); // overflow.
1003
1004           Constant *Ops[] = { Res, Overflow };
1005           return ConstantStruct::get(F->getContext(), Ops, 2, false);
1006         }
1007         }
1008       }
1009       
1010       return 0;
1011     }
1012     return 0;
1013   }
1014   return 0;
1015 }
1016