ConstantFolding.cpp revision de2d74b213844b17eb5327fba27f21e699d3af66
1//===-- ConstantFolding.cpp - Analyze constant folding possibilities ------===//
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 family of functions determines the possibility of performing constant
11// folding.
12//
13//===----------------------------------------------------------------------===//
14
15#include "llvm/Analysis/ConstantFolding.h"
16#include "llvm/Constants.h"
17#include "llvm/DerivedTypes.h"
18#include "llvm/Function.h"
19#include "llvm/Instructions.h"
20#include "llvm/Intrinsics.h"
21#include "llvm/ADT/SmallVector.h"
22#include "llvm/ADT/StringMap.h"
23#include "llvm/Target/TargetData.h"
24#include "llvm/Support/GetElementPtrTypeIterator.h"
25#include "llvm/Support/MathExtras.h"
26#include <cerrno>
27#include <cmath>
28using namespace llvm;
29
30//===----------------------------------------------------------------------===//
31// Constant Folding internal helper functions
32//===----------------------------------------------------------------------===//
33
34/// IsConstantOffsetFromGlobal - If this constant is actually a constant offset
35/// from a global, return the global and the constant.  Because of
36/// constantexprs, this function is recursive.
37static bool IsConstantOffsetFromGlobal(Constant *C, GlobalValue *&GV,
38                                       int64_t &Offset, const TargetData &TD) {
39  // Trivial case, constant is the global.
40  if ((GV = dyn_cast<GlobalValue>(C))) {
41    Offset = 0;
42    return true;
43  }
44
45  // Otherwise, if this isn't a constant expr, bail out.
46  ConstantExpr *CE = dyn_cast<ConstantExpr>(C);
47  if (!CE) return false;
48
49  // Look through ptr->int and ptr->ptr casts.
50  if (CE->getOpcode() == Instruction::PtrToInt ||
51      CE->getOpcode() == Instruction::BitCast)
52    return IsConstantOffsetFromGlobal(CE->getOperand(0), GV, Offset, TD);
53
54  // i32* getelementptr ([5 x i32]* @a, i32 0, i32 5)
55  if (CE->getOpcode() == Instruction::GetElementPtr) {
56    // Cannot compute this if the element type of the pointer is missing size
57    // info.
58    if (!cast<PointerType>(CE->getOperand(0)->getType())
59                 ->getElementType()->isSized())
60      return false;
61
62    // If the base isn't a global+constant, we aren't either.
63    if (!IsConstantOffsetFromGlobal(CE->getOperand(0), GV, Offset, TD))
64      return false;
65
66    // Otherwise, add any offset that our operands provide.
67    gep_type_iterator GTI = gep_type_begin(CE);
68    for (User::const_op_iterator i = CE->op_begin() + 1, e = CE->op_end();
69	 i != e; ++i, ++GTI) {
70      ConstantInt *CI = dyn_cast<ConstantInt>(*i);
71      if (!CI) return false;  // Index isn't a simple constant?
72      if (CI->getZExtValue() == 0) continue;  // Not adding anything.
73
74      if (const StructType *ST = dyn_cast<StructType>(*GTI)) {
75        // N = N + Offset
76        Offset += TD.getStructLayout(ST)->getElementOffset(CI->getZExtValue());
77      } else {
78        const SequentialType *SQT = cast<SequentialType>(*GTI);
79        Offset += TD.getABITypeSize(SQT->getElementType())*CI->getSExtValue();
80      }
81    }
82    return true;
83  }
84
85  return false;
86}
87
88
89/// SymbolicallyEvaluateBinop - One of Op0/Op1 is a constant expression.
90/// Attempt to symbolically evaluate the result of  a binary operator merging
91/// these together.  If target data info is available, it is provided as TD,
92/// otherwise TD is null.
93static Constant *SymbolicallyEvaluateBinop(unsigned Opc, Constant *Op0,
94                                           Constant *Op1, const TargetData *TD){
95  // SROA
96
97  // Fold (and 0xffffffff00000000, (shl x, 32)) -> shl.
98  // Fold (lshr (or X, Y), 32) -> (lshr [X/Y], 32) if one doesn't contribute
99  // bits.
100
101
102  // If the constant expr is something like &A[123] - &A[4].f, fold this into a
103  // constant.  This happens frequently when iterating over a global array.
104  if (Opc == Instruction::Sub && TD) {
105    GlobalValue *GV1, *GV2;
106    int64_t Offs1, Offs2;
107
108    if (IsConstantOffsetFromGlobal(Op0, GV1, Offs1, *TD))
109      if (IsConstantOffsetFromGlobal(Op1, GV2, Offs2, *TD) &&
110          GV1 == GV2) {
111        // (&GV+C1) - (&GV+C2) -> C1-C2, pointer arithmetic cannot overflow.
112        return ConstantInt::get(Op0->getType(), Offs1-Offs2);
113      }
114  }
115
116  // TODO: Fold icmp setne/seteq as well.
117  return 0;
118}
119
120/// SymbolicallyEvaluateGEP - If we can symbolically evaluate the specified GEP
121/// constant expression, do so.
122static Constant *SymbolicallyEvaluateGEP(Constant* const* Ops, unsigned NumOps,
123                                         const Type *ResultTy,
124                                         const TargetData *TD) {
125  Constant *Ptr = Ops[0];
126  if (!TD || !cast<PointerType>(Ptr->getType())->getElementType()->isSized())
127    return 0;
128
129  uint64_t BasePtr = 0;
130  if (!Ptr->isNullValue()) {
131    // If this is a inttoptr from a constant int, we can fold this as the base,
132    // otherwise we can't.
133    if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
134      if (CE->getOpcode() == Instruction::IntToPtr)
135        if (ConstantInt *Base = dyn_cast<ConstantInt>(CE->getOperand(0)))
136          BasePtr = Base->getZExtValue();
137
138    if (BasePtr == 0)
139      return 0;
140  }
141
142  // If this is a constant expr gep that is effectively computing an
143  // "offsetof", fold it into 'cast int Size to T*' instead of 'gep 0, 0, 12'
144  for (unsigned i = 1; i != NumOps; ++i)
145    if (!isa<ConstantInt>(Ops[i]))
146      return false;
147
148  uint64_t Offset = TD->getIndexedOffset(Ptr->getType(),
149                                         (Value**)Ops+1, NumOps-1);
150  Constant *C = ConstantInt::get(TD->getIntPtrType(), Offset+BasePtr);
151  return ConstantExpr::getIntToPtr(C, ResultTy);
152}
153
154/// FoldBitCast - Constant fold bitcast, symbolically evaluating it with
155/// targetdata.  Return 0 if unfoldable.
156static Constant *FoldBitCast(Constant *C, const Type *DestTy,
157                             const TargetData &TD) {
158  // If this is a bitcast from constant vector -> vector, fold it.
159  if (ConstantVector *CV = dyn_cast<ConstantVector>(C)) {
160    if (const VectorType *DestVTy = dyn_cast<VectorType>(DestTy)) {
161      // If the element types match, VMCore can fold it.
162      unsigned NumDstElt = DestVTy->getNumElements();
163      unsigned NumSrcElt = CV->getNumOperands();
164      if (NumDstElt == NumSrcElt)
165        return 0;
166
167      const Type *SrcEltTy = CV->getType()->getElementType();
168      const Type *DstEltTy = DestVTy->getElementType();
169
170      // Otherwise, we're changing the number of elements in a vector, which
171      // requires endianness information to do the right thing.  For example,
172      //    bitcast (<2 x i64> <i64 0, i64 1> to <4 x i32>)
173      // folds to (little endian):
174      //    <4 x i32> <i32 0, i32 0, i32 1, i32 0>
175      // and to (big endian):
176      //    <4 x i32> <i32 0, i32 0, i32 0, i32 1>
177
178      // First thing is first.  We only want to think about integer here, so if
179      // we have something in FP form, recast it as integer.
180      if (DstEltTy->isFloatingPoint()) {
181        // Fold to an vector of integers with same size as our FP type.
182        unsigned FPWidth = DstEltTy->getPrimitiveSizeInBits();
183        const Type *DestIVTy = VectorType::get(IntegerType::get(FPWidth),
184                                               NumDstElt);
185        // Recursively handle this integer conversion, if possible.
186        C = FoldBitCast(C, DestIVTy, TD);
187        if (!C) return 0;
188
189        // Finally, VMCore can handle this now that #elts line up.
190        return ConstantExpr::getBitCast(C, DestTy);
191      }
192
193      // Okay, we know the destination is integer, if the input is FP, convert
194      // it to integer first.
195      if (SrcEltTy->isFloatingPoint()) {
196        unsigned FPWidth = SrcEltTy->getPrimitiveSizeInBits();
197        const Type *SrcIVTy = VectorType::get(IntegerType::get(FPWidth),
198                                              NumSrcElt);
199        // Ask VMCore to do the conversion now that #elts line up.
200        C = ConstantExpr::getBitCast(C, SrcIVTy);
201        CV = dyn_cast<ConstantVector>(C);
202        if (!CV) return 0;  // If VMCore wasn't able to fold it, bail out.
203      }
204
205      // Now we know that the input and output vectors are both integer vectors
206      // of the same size, and that their #elements is not the same.  Do the
207      // conversion here, which depends on whether the input or output has
208      // more elements.
209      bool isLittleEndian = TD.isLittleEndian();
210
211      SmallVector<Constant*, 32> Result;
212      if (NumDstElt < NumSrcElt) {
213        // Handle: bitcast (<4 x i32> <i32 0, i32 1, i32 2, i32 3> to <2 x i64>)
214        Constant *Zero = Constant::getNullValue(DstEltTy);
215        unsigned Ratio = NumSrcElt/NumDstElt;
216        unsigned SrcBitSize = SrcEltTy->getPrimitiveSizeInBits();
217        unsigned SrcElt = 0;
218        for (unsigned i = 0; i != NumDstElt; ++i) {
219          // Build each element of the result.
220          Constant *Elt = Zero;
221          unsigned ShiftAmt = isLittleEndian ? 0 : SrcBitSize*(Ratio-1);
222          for (unsigned j = 0; j != Ratio; ++j) {
223            Constant *Src = dyn_cast<ConstantInt>(CV->getOperand(SrcElt++));
224            if (!Src) return 0;  // Reject constantexpr elements.
225
226            // Zero extend the element to the right size.
227            Src = ConstantExpr::getZExt(Src, Elt->getType());
228
229            // Shift it to the right place, depending on endianness.
230            Src = ConstantExpr::getShl(Src,
231                                    ConstantInt::get(Src->getType(), ShiftAmt));
232            ShiftAmt += isLittleEndian ? SrcBitSize : -SrcBitSize;
233
234            // Mix it in.
235            Elt = ConstantExpr::getOr(Elt, Src);
236          }
237          Result.push_back(Elt);
238        }
239      } else {
240        // Handle: bitcast (<2 x i64> <i64 0, i64 1> to <4 x i32>)
241        unsigned Ratio = NumDstElt/NumSrcElt;
242        unsigned DstBitSize = DstEltTy->getPrimitiveSizeInBits();
243
244        // Loop over each source value, expanding into multiple results.
245        for (unsigned i = 0; i != NumSrcElt; ++i) {
246          Constant *Src = dyn_cast<ConstantInt>(CV->getOperand(i));
247          if (!Src) return 0;  // Reject constantexpr elements.
248
249          unsigned ShiftAmt = isLittleEndian ? 0 : DstBitSize*(Ratio-1);
250          for (unsigned j = 0; j != Ratio; ++j) {
251            // Shift the piece of the value into the right place, depending on
252            // endianness.
253            Constant *Elt = ConstantExpr::getLShr(Src,
254                                ConstantInt::get(Src->getType(), ShiftAmt));
255            ShiftAmt += isLittleEndian ? DstBitSize : -DstBitSize;
256
257            // Truncate and remember this piece.
258            Result.push_back(ConstantExpr::getTrunc(Elt, DstEltTy));
259          }
260        }
261      }
262
263      return ConstantVector::get(&Result[0], Result.size());
264    }
265  }
266
267  return 0;
268}
269
270
271//===----------------------------------------------------------------------===//
272// Constant Folding public APIs
273//===----------------------------------------------------------------------===//
274
275
276/// ConstantFoldInstruction - Attempt to constant fold the specified
277/// instruction.  If successful, the constant result is returned, if not, null
278/// is returned.  Note that this function can only fail when attempting to fold
279/// instructions like loads and stores, which have no constant expression form.
280///
281Constant *llvm::ConstantFoldInstruction(Instruction *I, const TargetData *TD) {
282  if (PHINode *PN = dyn_cast<PHINode>(I)) {
283    if (PN->getNumIncomingValues() == 0)
284      return Constant::getNullValue(PN->getType());
285
286    Constant *Result = dyn_cast<Constant>(PN->getIncomingValue(0));
287    if (Result == 0) return 0;
288
289    // Handle PHI nodes specially here...
290    for (unsigned i = 1, e = PN->getNumIncomingValues(); i != e; ++i)
291      if (PN->getIncomingValue(i) != Result && PN->getIncomingValue(i) != PN)
292        return 0;   // Not all the same incoming constants...
293
294    // If we reach here, all incoming values are the same constant.
295    return Result;
296  }
297
298  // Scan the operand list, checking to see if they are all constants, if so,
299  // hand off to ConstantFoldInstOperands.
300  SmallVector<Constant*, 8> Ops;
301  for (User::op_iterator i = I->op_begin(), e = I->op_end(); i != e; ++i)
302    if (Constant *Op = dyn_cast<Constant>(*i))
303      Ops.push_back(Op);
304    else
305      return 0;  // All operands not constant!
306
307  if (const CmpInst *CI = dyn_cast<CmpInst>(I))
308    return ConstantFoldCompareInstOperands(CI->getPredicate(),
309                                           &Ops[0], Ops.size(), TD);
310  else
311    return ConstantFoldInstOperands(I->getOpcode(), I->getType(),
312                                    &Ops[0], Ops.size(), TD);
313}
314
315/// ConstantFoldInstOperands - Attempt to constant fold an instruction with the
316/// specified opcode and operands.  If successful, the constant result is
317/// returned, if not, null is returned.  Note that this function can fail when
318/// attempting to fold instructions like loads and stores, which have no
319/// constant expression form.
320///
321Constant *llvm::ConstantFoldInstOperands(unsigned Opcode, const Type *DestTy,
322                                         Constant* const* Ops, unsigned NumOps,
323                                         const TargetData *TD) {
324  // Handle easy binops first.
325  if (Instruction::isBinaryOp(Opcode)) {
326    if (isa<ConstantExpr>(Ops[0]) || isa<ConstantExpr>(Ops[1]))
327      if (Constant *C = SymbolicallyEvaluateBinop(Opcode, Ops[0], Ops[1], TD))
328        return C;
329
330    return ConstantExpr::get(Opcode, Ops[0], Ops[1]);
331  }
332
333  switch (Opcode) {
334  default: return 0;
335  case Instruction::Call:
336    if (Function *F = dyn_cast<Function>(Ops[0]))
337      if (canConstantFoldCallTo(F))
338        return ConstantFoldCall(F, Ops+1, NumOps-1);
339    return 0;
340  case Instruction::ICmp:
341  case Instruction::FCmp:
342    assert(0 &&"This function is invalid for compares: no predicate specified");
343  case Instruction::PtrToInt:
344    // If the input is a inttoptr, eliminate the pair.  This requires knowing
345    // the width of a pointer, so it can't be done in ConstantExpr::getCast.
346    if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ops[0])) {
347      if (TD && CE->getOpcode() == Instruction::IntToPtr) {
348        Constant *Input = CE->getOperand(0);
349        unsigned InWidth = Input->getType()->getPrimitiveSizeInBits();
350        Constant *Mask =
351          ConstantInt::get(APInt::getLowBitsSet(InWidth,
352                                                TD->getPointerSizeInBits()));
353        Input = ConstantExpr::getAnd(Input, Mask);
354        // Do a zext or trunc to get to the dest size.
355        return ConstantExpr::getIntegerCast(Input, DestTy, false);
356      }
357    }
358    return ConstantExpr::getCast(Opcode, Ops[0], DestTy);
359  case Instruction::IntToPtr:
360  case Instruction::Trunc:
361  case Instruction::ZExt:
362  case Instruction::SExt:
363  case Instruction::FPTrunc:
364  case Instruction::FPExt:
365  case Instruction::UIToFP:
366  case Instruction::SIToFP:
367  case Instruction::FPToUI:
368  case Instruction::FPToSI:
369      return ConstantExpr::getCast(Opcode, Ops[0], DestTy);
370  case Instruction::BitCast:
371    if (TD)
372      if (Constant *C = FoldBitCast(Ops[0], DestTy, *TD))
373        return C;
374    return ConstantExpr::getBitCast(Ops[0], DestTy);
375  case Instruction::Select:
376    return ConstantExpr::getSelect(Ops[0], Ops[1], Ops[2]);
377  case Instruction::ExtractElement:
378    return ConstantExpr::getExtractElement(Ops[0], Ops[1]);
379  case Instruction::InsertElement:
380    return ConstantExpr::getInsertElement(Ops[0], Ops[1], Ops[2]);
381  case Instruction::ShuffleVector:
382    return ConstantExpr::getShuffleVector(Ops[0], Ops[1], Ops[2]);
383  case Instruction::GetElementPtr:
384    if (Constant *C = SymbolicallyEvaluateGEP(Ops, NumOps, DestTy, TD))
385      return C;
386
387    return ConstantExpr::getGetElementPtr(Ops[0], Ops+1, NumOps-1);
388  }
389}
390
391/// ConstantFoldCompareInstOperands - Attempt to constant fold a compare
392/// instruction (icmp/fcmp) with the specified operands.  If it fails, it
393/// returns a constant expression of the specified operands.
394///
395Constant *llvm::ConstantFoldCompareInstOperands(unsigned Predicate,
396                                                Constant*const * Ops,
397                                                unsigned NumOps,
398                                                const TargetData *TD) {
399  // fold: icmp (inttoptr x), null         -> icmp x, 0
400  // fold: icmp (ptrtoint x), 0            -> icmp x, null
401  // fold: icmp (inttoptr x), (inttoptr y) -> icmp x, y
402  // fold: icmp (ptrtoint x), (ptrtoint y) -> icmp x, y
403  //
404  // ConstantExpr::getCompare cannot do this, because it doesn't have TD
405  // around to know if bit truncation is happening.
406  if (ConstantExpr *CE0 = dyn_cast<ConstantExpr>(Ops[0])) {
407    if (TD && Ops[1]->isNullValue()) {
408      const Type *IntPtrTy = TD->getIntPtrType();
409      if (CE0->getOpcode() == Instruction::IntToPtr) {
410        // Convert the integer value to the right size to ensure we get the
411        // proper extension or truncation.
412        Constant *C = ConstantExpr::getIntegerCast(CE0->getOperand(0),
413                                                   IntPtrTy, false);
414        Constant *NewOps[] = { C, Constant::getNullValue(C->getType()) };
415        return ConstantFoldCompareInstOperands(Predicate, NewOps, 2, TD);
416      }
417
418      // Only do this transformation if the int is intptrty in size, otherwise
419      // there is a truncation or extension that we aren't modeling.
420      if (CE0->getOpcode() == Instruction::PtrToInt &&
421          CE0->getType() == IntPtrTy) {
422        Constant *C = CE0->getOperand(0);
423        Constant *NewOps[] = { C, Constant::getNullValue(C->getType()) };
424        // FIXME!
425        return ConstantFoldCompareInstOperands(Predicate, NewOps, 2, TD);
426      }
427    }
428
429    if (TD && isa<ConstantExpr>(Ops[1]) &&
430        cast<ConstantExpr>(Ops[1])->getOpcode() == CE0->getOpcode()) {
431      const Type *IntPtrTy = TD->getIntPtrType();
432      // Only do this transformation if the int is intptrty in size, otherwise
433      // there is a truncation or extension that we aren't modeling.
434      if ((CE0->getOpcode() == Instruction::IntToPtr &&
435           CE0->getOperand(0)->getType() == IntPtrTy &&
436           Ops[1]->getOperand(0)->getType() == IntPtrTy) ||
437          (CE0->getOpcode() == Instruction::PtrToInt &&
438           CE0->getType() == IntPtrTy &&
439           CE0->getOperand(0)->getType() == Ops[1]->getOperand(0)->getType())) {
440        Constant *NewOps[] = {
441          CE0->getOperand(0), cast<ConstantExpr>(Ops[1])->getOperand(0)
442        };
443        return ConstantFoldCompareInstOperands(Predicate, NewOps, 2, TD);
444      }
445    }
446  }
447  return ConstantExpr::getCompare(Predicate, Ops[0], Ops[1]);
448}
449
450
451/// ConstantFoldLoadThroughGEPConstantExpr - Given a constant and a
452/// getelementptr constantexpr, return the constant value being addressed by the
453/// constant expression, or null if something is funny and we can't decide.
454Constant *llvm::ConstantFoldLoadThroughGEPConstantExpr(Constant *C,
455                                                       ConstantExpr *CE) {
456  if (CE->getOperand(1) != Constant::getNullValue(CE->getOperand(1)->getType()))
457    return 0;  // Do not allow stepping over the value!
458
459  // Loop over all of the operands, tracking down which value we are
460  // addressing...
461  gep_type_iterator I = gep_type_begin(CE), E = gep_type_end(CE);
462  for (++I; I != E; ++I)
463    if (const StructType *STy = dyn_cast<StructType>(*I)) {
464      ConstantInt *CU = cast<ConstantInt>(I.getOperand());
465      assert(CU->getZExtValue() < STy->getNumElements() &&
466             "Struct index out of range!");
467      unsigned El = (unsigned)CU->getZExtValue();
468      if (ConstantStruct *CS = dyn_cast<ConstantStruct>(C)) {
469        C = CS->getOperand(El);
470      } else if (isa<ConstantAggregateZero>(C)) {
471        C = Constant::getNullValue(STy->getElementType(El));
472      } else if (isa<UndefValue>(C)) {
473        C = UndefValue::get(STy->getElementType(El));
474      } else {
475        return 0;
476      }
477    } else if (ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand())) {
478      if (const ArrayType *ATy = dyn_cast<ArrayType>(*I)) {
479        if (CI->getZExtValue() >= ATy->getNumElements())
480         return 0;
481        if (ConstantArray *CA = dyn_cast<ConstantArray>(C))
482          C = CA->getOperand(CI->getZExtValue());
483        else if (isa<ConstantAggregateZero>(C))
484          C = Constant::getNullValue(ATy->getElementType());
485        else if (isa<UndefValue>(C))
486          C = UndefValue::get(ATy->getElementType());
487        else
488          return 0;
489      } else if (const VectorType *PTy = dyn_cast<VectorType>(*I)) {
490        if (CI->getZExtValue() >= PTy->getNumElements())
491          return 0;
492        if (ConstantVector *CP = dyn_cast<ConstantVector>(C))
493          C = CP->getOperand(CI->getZExtValue());
494        else if (isa<ConstantAggregateZero>(C))
495          C = Constant::getNullValue(PTy->getElementType());
496        else if (isa<UndefValue>(C))
497          C = UndefValue::get(PTy->getElementType());
498        else
499          return 0;
500      } else {
501        return 0;
502      }
503    } else {
504      return 0;
505    }
506  return C;
507}
508
509
510//===----------------------------------------------------------------------===//
511//  Constant Folding for Calls
512//
513
514/// canConstantFoldCallTo - Return true if its even possible to fold a call to
515/// the specified function.
516bool
517llvm::canConstantFoldCallTo(const Function *F) {
518  switch (F->getIntrinsicID()) {
519  case Intrinsic::sqrt:
520  case Intrinsic::powi:
521  case Intrinsic::bswap:
522  case Intrinsic::ctpop:
523  case Intrinsic::ctlz:
524  case Intrinsic::cttz:
525    return true;
526  default: break;
527  }
528
529  const ValueName *NameVal = F->getValueName();
530  if (NameVal == 0) return false;
531  const char *Str = NameVal->getKeyData();
532  unsigned Len = NameVal->getKeyLength();
533
534  // In these cases, the check of the length is required.  We don't want to
535  // return true for a name like "cos\0blah" which strcmp would return equal to
536  // "cos", but has length 8.
537  switch (Str[0]) {
538  default: return false;
539  case 'a':
540    if (Len == 4)
541      return !strcmp(Str, "acos") || !strcmp(Str, "asin") ||
542             !strcmp(Str, "atan");
543    else if (Len == 5)
544      return !strcmp(Str, "atan2");
545    return false;
546  case 'c':
547    if (Len == 3)
548      return !strcmp(Str, "cos");
549    else if (Len == 4)
550      return !strcmp(Str, "ceil") || !strcmp(Str, "cosf") ||
551             !strcmp(Str, "cosh");
552    return false;
553  case 'e':
554    if (Len == 3)
555      return !strcmp(Str, "exp");
556    return false;
557  case 'f':
558    if (Len == 4)
559      return !strcmp(Str, "fabs") || !strcmp(Str, "fmod");
560    else if (Len == 5)
561      return !strcmp(Str, "floor");
562    return false;
563    break;
564  case 'l':
565    if (Len == 3 && !strcmp(Str, "log"))
566      return true;
567    if (Len == 5 && !strcmp(Str, "log10"))
568      return true;
569    return false;
570  case 'p':
571    if (Len == 3 && !strcmp(Str, "pow"))
572      return true;
573    return false;
574  case 's':
575    if (Len == 3)
576      return !strcmp(Str, "sin");
577    if (Len == 4)
578      return !strcmp(Str, "sinh") || !strcmp(Str, "sqrt") ||
579             !strcmp(Str, "sinf");
580    if (Len == 5)
581      return !strcmp(Str, "sqrtf");
582    return false;
583  case 't':
584    if (Len == 3 && !strcmp(Str, "tan"))
585      return true;
586    else if (Len == 4 && !strcmp(Str, "tanh"))
587      return true;
588    return false;
589  }
590}
591
592static Constant *ConstantFoldFP(double (*NativeFP)(double), double V,
593                                const Type *Ty) {
594  errno = 0;
595  V = NativeFP(V);
596  if (errno != 0) {
597    errno = 0;
598    return 0;
599  }
600
601  if (Ty == Type::FloatTy)
602    return ConstantFP::get(APFloat((float)V));
603  if (Ty == Type::DoubleTy)
604    return ConstantFP::get(APFloat(V));
605  assert(0 && "Can only constant fold float/double");
606  return 0; // dummy return to suppress warning
607}
608
609static Constant *ConstantFoldBinaryFP(double (*NativeFP)(double, double),
610                                      double V, double W,
611                                      const Type *Ty) {
612  errno = 0;
613  V = NativeFP(V, W);
614  if (errno != 0) {
615    errno = 0;
616    return 0;
617  }
618
619  if (Ty == Type::FloatTy)
620    return ConstantFP::get(APFloat((float)V));
621  if (Ty == Type::DoubleTy)
622    return ConstantFP::get(APFloat(V));
623  assert(0 && "Can only constant fold float/double");
624  return 0; // dummy return to suppress warning
625}
626
627/// ConstantFoldCall - Attempt to constant fold a call to the specified function
628/// with the specified arguments, returning null if unsuccessful.
629
630Constant *
631llvm::ConstantFoldCall(Function *F,
632                       Constant* const* Operands, unsigned NumOperands) {
633  const ValueName *NameVal = F->getValueName();
634  if (NameVal == 0) return 0;
635  const char *Str = NameVal->getKeyData();
636  unsigned Len = NameVal->getKeyLength();
637
638  const Type *Ty = F->getReturnType();
639  if (NumOperands == 1) {
640    if (ConstantFP *Op = dyn_cast<ConstantFP>(Operands[0])) {
641      if (Ty!=Type::FloatTy && Ty!=Type::DoubleTy)
642        return 0;
643      /// Currently APFloat versions of these functions do not exist, so we use
644      /// the host native double versions.  Float versions are not called
645      /// directly but for all these it is true (float)(f((double)arg)) ==
646      /// f(arg).  Long double not supported yet.
647      double V = Ty==Type::FloatTy ? (double)Op->getValueAPF().convertToFloat():
648                                     Op->getValueAPF().convertToDouble();
649      switch (Str[0]) {
650      case 'a':
651        if (Len == 4 && !strcmp(Str, "acos"))
652          return ConstantFoldFP(acos, V, Ty);
653        else if (Len == 4 && !strcmp(Str, "asin"))
654          return ConstantFoldFP(asin, V, Ty);
655        else if (Len == 4 && !strcmp(Str, "atan"))
656          return ConstantFoldFP(atan, V, Ty);
657        break;
658      case 'c':
659        if (Len == 4 && !strcmp(Str, "ceil"))
660          return ConstantFoldFP(ceil, V, Ty);
661        else if (Len == 3 && !strcmp(Str, "cos"))
662          return ConstantFoldFP(cos, V, Ty);
663        else if (Len == 4 && !strcmp(Str, "cosh"))
664          return ConstantFoldFP(cosh, V, Ty);
665        else if (Len == 4 && !strcmp(Str, "cosf"))
666          return ConstantFoldFP(cos, V, Ty);
667        break;
668      case 'e':
669        if (Len == 3 && !strcmp(Str, "exp"))
670          return ConstantFoldFP(exp, V, Ty);
671        break;
672      case 'f':
673        if (Len == 4 && !strcmp(Str, "fabs"))
674          return ConstantFoldFP(fabs, V, Ty);
675        else if (Len == 5 && !strcmp(Str, "floor"))
676          return ConstantFoldFP(floor, V, Ty);
677        break;
678      case 'l':
679        if (Len == 3 && !strcmp(Str, "log") && V > 0)
680          return ConstantFoldFP(log, V, Ty);
681        else if (Len == 5 && !strcmp(Str, "log10") && V > 0)
682          return ConstantFoldFP(log10, V, Ty);
683        else if (!strcmp(Str, "llvm.sqrt.f32") ||
684                 !strcmp(Str, "llvm.sqrt.f64")) {
685          if (V >= -0.0)
686            return ConstantFoldFP(sqrt, V, Ty);
687          else // Undefined
688            return Constant::getNullValue(Ty);
689        }
690        break;
691      case 's':
692        if (Len == 3 && !strcmp(Str, "sin"))
693          return ConstantFoldFP(sin, V, Ty);
694        else if (Len == 4 && !strcmp(Str, "sinh"))
695          return ConstantFoldFP(sinh, V, Ty);
696        else if (Len == 4 && !strcmp(Str, "sqrt") && V >= 0)
697          return ConstantFoldFP(sqrt, V, Ty);
698        else if (Len == 5 && !strcmp(Str, "sqrtf") && V >= 0)
699          return ConstantFoldFP(sqrt, V, Ty);
700        else if (Len == 4 && !strcmp(Str, "sinf"))
701          return ConstantFoldFP(sin, V, Ty);
702        break;
703      case 't':
704        if (Len == 3 && !strcmp(Str, "tan"))
705          return ConstantFoldFP(tan, V, Ty);
706        else if (Len == 4 && !strcmp(Str, "tanh"))
707          return ConstantFoldFP(tanh, V, Ty);
708        break;
709      default:
710        break;
711      }
712    } else if (ConstantInt *Op = dyn_cast<ConstantInt>(Operands[0])) {
713      if (Len > 11 && !memcmp(Str, "llvm.bswap", 10))
714        return ConstantInt::get(Op->getValue().byteSwap());
715      else if (Len > 11 && !memcmp(Str, "llvm.ctpop", 10))
716        return ConstantInt::get(Ty, Op->getValue().countPopulation());
717      else if (Len > 10 && !memcmp(Str, "llvm.cttz", 9))
718        return ConstantInt::get(Ty, Op->getValue().countTrailingZeros());
719      else if (Len > 10 && !memcmp(Str, "llvm.ctlz", 9))
720        return ConstantInt::get(Ty, Op->getValue().countLeadingZeros());
721    }
722  } else if (NumOperands == 2) {
723    if (ConstantFP *Op1 = dyn_cast<ConstantFP>(Operands[0])) {
724      if (Ty!=Type::FloatTy && Ty!=Type::DoubleTy)
725        return 0;
726      double Op1V = Ty==Type::FloatTy ?
727                      (double)Op1->getValueAPF().convertToFloat():
728                      Op1->getValueAPF().convertToDouble();
729      if (ConstantFP *Op2 = dyn_cast<ConstantFP>(Operands[1])) {
730        double Op2V = Ty==Type::FloatTy ?
731                      (double)Op2->getValueAPF().convertToFloat():
732                      Op2->getValueAPF().convertToDouble();
733
734        if (Len == 3 && !strcmp(Str, "pow")) {
735          return ConstantFoldBinaryFP(pow, Op1V, Op2V, Ty);
736        } else if (Len == 4 && !strcmp(Str, "fmod")) {
737          return ConstantFoldBinaryFP(fmod, Op1V, Op2V, Ty);
738        } else if (Len == 5 && !strcmp(Str, "atan2")) {
739          return ConstantFoldBinaryFP(atan2, Op1V, Op2V, Ty);
740        }
741      } else if (ConstantInt *Op2C = dyn_cast<ConstantInt>(Operands[1])) {
742        if (!strcmp(Str, "llvm.powi.f32")) {
743          return ConstantFP::get(APFloat((float)std::pow((float)Op1V,
744                                                 (int)Op2C->getZExtValue())));
745        } else if (!strcmp(Str, "llvm.powi.f64")) {
746          return ConstantFP::get(APFloat((double)std::pow((double)Op1V,
747                                                 (int)Op2C->getZExtValue())));
748        }
749      }
750    }
751  }
752  return 0;
753}
754
755