ConstantFold.cpp revision 256281
1295011Sandrew//===- ConstantFold.cpp - LLVM constant folder ----------------------------===//
2295011Sandrew//
3295011Sandrew//                     The LLVM Compiler Infrastructure
4295011Sandrew//
5295011Sandrew// This file is distributed under the University of Illinois Open Source
6295011Sandrew// License. See LICENSE.TXT for details.
7295011Sandrew//
8295011Sandrew//===----------------------------------------------------------------------===//
9295011Sandrew//
10295011Sandrew// This file implements folding of constants for LLVM.  This implements the
11295011Sandrew// (internal) ConstantFold.h interface, which is used by the
12295011Sandrew// ConstantExpr::get* methods to automatically fold constants when possible.
13295011Sandrew//
14295011Sandrew// The current constant folding implementation is implemented in two pieces: the
15295011Sandrew// pieces that don't need DataLayout, and the pieces that do. This is to avoid
16295011Sandrew// a dependence in IR on Target.
17295011Sandrew//
18295011Sandrew//===----------------------------------------------------------------------===//
19295011Sandrew
20295011Sandrew#include "ConstantFold.h"
21295011Sandrew#include "llvm/ADT/SmallVector.h"
22295011Sandrew#include "llvm/IR/Constants.h"
23295011Sandrew#include "llvm/IR/DerivedTypes.h"
24295011Sandrew#include "llvm/IR/Function.h"
25295011Sandrew#include "llvm/IR/GlobalAlias.h"
26295011Sandrew#include "llvm/IR/GlobalVariable.h"
27295011Sandrew#include "llvm/IR/Instructions.h"
28295011Sandrew#include "llvm/IR/Operator.h"
29295011Sandrew#include "llvm/Support/Compiler.h"
30295011Sandrew#include "llvm/Support/ErrorHandling.h"
31295011Sandrew#include "llvm/Support/GetElementPtrTypeIterator.h"
32295011Sandrew#include "llvm/Support/ManagedStatic.h"
33295011Sandrew#include "llvm/Support/MathExtras.h"
34295011Sandrew#include <limits>
35295011Sandrewusing namespace llvm;
36295011Sandrew
37295011Sandrew//===----------------------------------------------------------------------===//
38295011Sandrew//                ConstantFold*Instruction Implementations
39295011Sandrew//===----------------------------------------------------------------------===//
40295011Sandrew
41295011Sandrew/// BitCastConstantVector - Convert the specified vector Constant node to the
42295011Sandrew/// specified vector type.  At this point, we know that the elements of the
43295011Sandrew/// input vector constant are all simple integer or FP values.
44295011Sandrewstatic Constant *BitCastConstantVector(Constant *CV, VectorType *DstTy) {
45295011Sandrew
46295011Sandrew  if (CV->isAllOnesValue()) return Constant::getAllOnesValue(DstTy);
47295011Sandrew  if (CV->isNullValue()) return Constant::getNullValue(DstTy);
48295011Sandrew
49295011Sandrew  // If this cast changes element count then we can't handle it here:
50295011Sandrew  // doing so requires endianness information.  This should be handled by
51295011Sandrew  // Analysis/ConstantFolding.cpp
52295011Sandrew  unsigned NumElts = DstTy->getNumElements();
53295011Sandrew  if (NumElts != CV->getType()->getVectorNumElements())
54295011Sandrew    return 0;
55295011Sandrew
56295011Sandrew  Type *DstEltTy = DstTy->getElementType();
57295011Sandrew
58295011Sandrew  SmallVector<Constant*, 16> Result;
59295011Sandrew  Type *Ty = IntegerType::get(CV->getContext(), 32);
60295011Sandrew  for (unsigned i = 0; i != NumElts; ++i) {
61295011Sandrew    Constant *C =
62295011Sandrew      ConstantExpr::getExtractElement(CV, ConstantInt::get(Ty, i));
63295011Sandrew    C = ConstantExpr::getBitCast(C, DstEltTy);
64295011Sandrew    Result.push_back(C);
65295011Sandrew  }
66295011Sandrew
67295011Sandrew  return ConstantVector::get(Result);
68295011Sandrew}
69295011Sandrew
70295011Sandrew/// This function determines which opcode to use to fold two constant cast
71295011Sandrew/// expressions together. It uses CastInst::isEliminableCastPair to determine
72295011Sandrew/// the opcode. Consequently its just a wrapper around that function.
73295011Sandrew/// @brief Determine if it is valid to fold a cast of a cast
74295011Sandrewstatic unsigned
75295011SandrewfoldConstantCastPair(
76295011Sandrew  unsigned opc,          ///< opcode of the second cast constant expression
77295011Sandrew  ConstantExpr *Op,      ///< the first cast constant expression
78295011Sandrew  Type *DstTy      ///< desintation type of the first cast
79295011Sandrew) {
80295011Sandrew  assert(Op && Op->isCast() && "Can't fold cast of cast without a cast!");
81295011Sandrew  assert(DstTy && DstTy->isFirstClassType() && "Invalid cast destination type");
82295011Sandrew  assert(CastInst::isCast(opc) && "Invalid cast opcode");
83295011Sandrew
84295011Sandrew  // The the types and opcodes for the two Cast constant expressions
85295011Sandrew  Type *SrcTy = Op->getOperand(0)->getType();
86295011Sandrew  Type *MidTy = Op->getType();
87295011Sandrew  Instruction::CastOps firstOp = Instruction::CastOps(Op->getOpcode());
88295011Sandrew  Instruction::CastOps secondOp = Instruction::CastOps(opc);
89295011Sandrew
90295011Sandrew  // Assume that pointers are never more than 64 bits wide.
91295011Sandrew  IntegerType *FakeIntPtrTy = Type::getInt64Ty(DstTy->getContext());
92295011Sandrew
93295011Sandrew  // Let CastInst::isEliminableCastPair do the heavy lifting.
94295011Sandrew  return CastInst::isEliminableCastPair(firstOp, secondOp, SrcTy, MidTy, DstTy,
95295011Sandrew                                        FakeIntPtrTy, FakeIntPtrTy,
96295011Sandrew                                        FakeIntPtrTy);
97295011Sandrew}
98295011Sandrew
99295011Sandrewstatic Constant *FoldBitCast(Constant *V, Type *DestTy) {
100295011Sandrew  Type *SrcTy = V->getType();
101295011Sandrew  if (SrcTy == DestTy)
102295011Sandrew    return V; // no-op cast
103295011Sandrew
104295011Sandrew  // Check to see if we are casting a pointer to an aggregate to a pointer to
105295011Sandrew  // the first element.  If so, return the appropriate GEP instruction.
106295011Sandrew  if (PointerType *PTy = dyn_cast<PointerType>(V->getType()))
107295011Sandrew    if (PointerType *DPTy = dyn_cast<PointerType>(DestTy))
108295011Sandrew      if (PTy->getAddressSpace() == DPTy->getAddressSpace()
109295011Sandrew          && DPTy->getElementType()->isSized()) {
110295011Sandrew        SmallVector<Value*, 8> IdxList;
111295011Sandrew        Value *Zero =
112295011Sandrew          Constant::getNullValue(Type::getInt32Ty(DPTy->getContext()));
113295011Sandrew        IdxList.push_back(Zero);
114295011Sandrew        Type *ElTy = PTy->getElementType();
115295011Sandrew        while (ElTy != DPTy->getElementType()) {
116295011Sandrew          if (StructType *STy = dyn_cast<StructType>(ElTy)) {
117295011Sandrew            if (STy->getNumElements() == 0) break;
118295011Sandrew            ElTy = STy->getElementType(0);
119295011Sandrew            IdxList.push_back(Zero);
120295011Sandrew          } else if (SequentialType *STy =
121295011Sandrew                     dyn_cast<SequentialType>(ElTy)) {
122295011Sandrew            if (ElTy->isPointerTy()) break;  // Can't index into pointers!
123295011Sandrew            ElTy = STy->getElementType();
124295011Sandrew            IdxList.push_back(Zero);
125295011Sandrew          } else {
126295011Sandrew            break;
127295011Sandrew          }
128295011Sandrew        }
129295011Sandrew
130295011Sandrew        if (ElTy == DPTy->getElementType())
131295011Sandrew          // This GEP is inbounds because all indices are zero.
132295011Sandrew          return ConstantExpr::getInBoundsGetElementPtr(V, IdxList);
133295011Sandrew      }
134295011Sandrew
135295011Sandrew  // Handle casts from one vector constant to another.  We know that the src
136295011Sandrew  // and dest type have the same size (otherwise its an illegal cast).
137295011Sandrew  if (VectorType *DestPTy = dyn_cast<VectorType>(DestTy)) {
138295011Sandrew    if (VectorType *SrcTy = dyn_cast<VectorType>(V->getType())) {
139295011Sandrew      assert(DestPTy->getBitWidth() == SrcTy->getBitWidth() &&
140295011Sandrew             "Not cast between same sized vectors!");
141295011Sandrew      SrcTy = NULL;
142295011Sandrew      // First, check for null.  Undef is already handled.
143295011Sandrew      if (isa<ConstantAggregateZero>(V))
144295011Sandrew        return Constant::getNullValue(DestTy);
145295011Sandrew
146295011Sandrew      // Handle ConstantVector and ConstantAggregateVector.
147295011Sandrew      return BitCastConstantVector(V, DestPTy);
148295011Sandrew    }
149295011Sandrew
150295011Sandrew    // Canonicalize scalar-to-vector bitcasts into vector-to-vector bitcasts
151295011Sandrew    // This allows for other simplifications (although some of them
152295011Sandrew    // can only be handled by Analysis/ConstantFolding.cpp).
153295011Sandrew    if (isa<ConstantInt>(V) || isa<ConstantFP>(V))
154295011Sandrew      return ConstantExpr::getBitCast(ConstantVector::get(V), DestPTy);
155295011Sandrew  }
156295011Sandrew
157295011Sandrew  // Finally, implement bitcast folding now.   The code below doesn't handle
158295011Sandrew  // bitcast right.
159295011Sandrew  if (isa<ConstantPointerNull>(V))  // ptr->ptr cast.
160295011Sandrew    return ConstantPointerNull::get(cast<PointerType>(DestTy));
161295011Sandrew
162295011Sandrew  // Handle integral constant input.
163295011Sandrew  if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
164295011Sandrew    if (DestTy->isIntegerTy())
165295011Sandrew      // Integral -> Integral. This is a no-op because the bit widths must
166295011Sandrew      // be the same. Consequently, we just fold to V.
167295011Sandrew      return V;
168295011Sandrew
169295011Sandrew    if (DestTy->isFloatingPointTy())
170295011Sandrew      return ConstantFP::get(DestTy->getContext(),
171295011Sandrew                             APFloat(DestTy->getFltSemantics(),
172295011Sandrew                                     CI->getValue()));
173295011Sandrew
174295011Sandrew    // Otherwise, can't fold this (vector?)
175295011Sandrew    return 0;
176295011Sandrew  }
177295011Sandrew
178295011Sandrew  // Handle ConstantFP input: FP -> Integral.
179295011Sandrew  if (ConstantFP *FP = dyn_cast<ConstantFP>(V))
180295011Sandrew    return ConstantInt::get(FP->getContext(),
181295011Sandrew                            FP->getValueAPF().bitcastToAPInt());
182295011Sandrew
183295011Sandrew  return 0;
184295011Sandrew}
185295011Sandrew
186295011Sandrew
187295011Sandrew/// ExtractConstantBytes - V is an integer constant which only has a subset of
188295011Sandrew/// its bytes used.  The bytes used are indicated by ByteStart (which is the
189295011Sandrew/// first byte used, counting from the least significant byte) and ByteSize,
190295011Sandrew/// which is the number of bytes used.
191295011Sandrew///
192295011Sandrew/// This function analyzes the specified constant to see if the specified byte
193295011Sandrew/// range can be returned as a simplified constant.  If so, the constant is
194295011Sandrew/// returned, otherwise null is returned.
195295011Sandrew///
196295011Sandrewstatic Constant *ExtractConstantBytes(Constant *C, unsigned ByteStart,
197295011Sandrew                                      unsigned ByteSize) {
198295011Sandrew  assert(C->getType()->isIntegerTy() &&
199295011Sandrew         (cast<IntegerType>(C->getType())->getBitWidth() & 7) == 0 &&
200295011Sandrew         "Non-byte sized integer input");
201295011Sandrew  unsigned CSize = cast<IntegerType>(C->getType())->getBitWidth()/8;
202295011Sandrew  assert(ByteSize && "Must be accessing some piece");
203295011Sandrew  assert(ByteStart+ByteSize <= CSize && "Extracting invalid piece from input");
204295011Sandrew  assert(ByteSize != CSize && "Should not extract everything");
205295011Sandrew
206295011Sandrew  // Constant Integers are simple.
207295011Sandrew  if (ConstantInt *CI = dyn_cast<ConstantInt>(C)) {
208295011Sandrew    APInt V = CI->getValue();
209295011Sandrew    if (ByteStart)
210295011Sandrew      V = V.lshr(ByteStart*8);
211295011Sandrew    V = V.trunc(ByteSize*8);
212295011Sandrew    return ConstantInt::get(CI->getContext(), V);
213295011Sandrew  }
214295011Sandrew
215295011Sandrew  // In the input is a constant expr, we might be able to recursively simplify.
216295011Sandrew  // If not, we definitely can't do anything.
217295011Sandrew  ConstantExpr *CE = dyn_cast<ConstantExpr>(C);
218295011Sandrew  if (CE == 0) return 0;
219295011Sandrew
220295011Sandrew  switch (CE->getOpcode()) {
221295011Sandrew  default: return 0;
222295011Sandrew  case Instruction::Or: {
223295011Sandrew    Constant *RHS = ExtractConstantBytes(CE->getOperand(1), ByteStart,ByteSize);
224295011Sandrew    if (RHS == 0)
225295011Sandrew      return 0;
226295011Sandrew
227295011Sandrew    // X | -1 -> -1.
228295011Sandrew    if (ConstantInt *RHSC = dyn_cast<ConstantInt>(RHS))
229295011Sandrew      if (RHSC->isAllOnesValue())
230295011Sandrew        return RHSC;
231295011Sandrew
232295011Sandrew    Constant *LHS = ExtractConstantBytes(CE->getOperand(0), ByteStart,ByteSize);
233295011Sandrew    if (LHS == 0)
234295011Sandrew      return 0;
235295011Sandrew    return ConstantExpr::getOr(LHS, RHS);
236295011Sandrew  }
237295011Sandrew  case Instruction::And: {
238295011Sandrew    Constant *RHS = ExtractConstantBytes(CE->getOperand(1), ByteStart,ByteSize);
239295011Sandrew    if (RHS == 0)
240295011Sandrew      return 0;
241295011Sandrew
242295011Sandrew    // X & 0 -> 0.
243295011Sandrew    if (RHS->isNullValue())
244295011Sandrew      return RHS;
245295011Sandrew
246295011Sandrew    Constant *LHS = ExtractConstantBytes(CE->getOperand(0), ByteStart,ByteSize);
247295011Sandrew    if (LHS == 0)
248295011Sandrew      return 0;
249295011Sandrew    return ConstantExpr::getAnd(LHS, RHS);
250295011Sandrew  }
251295011Sandrew  case Instruction::LShr: {
252295011Sandrew    ConstantInt *Amt = dyn_cast<ConstantInt>(CE->getOperand(1));
253295011Sandrew    if (Amt == 0)
254295011Sandrew      return 0;
255295011Sandrew    unsigned ShAmt = Amt->getZExtValue();
256295011Sandrew    // Cannot analyze non-byte shifts.
257295011Sandrew    if ((ShAmt & 7) != 0)
258295011Sandrew      return 0;
259295011Sandrew    ShAmt >>= 3;
260295011Sandrew
261295011Sandrew    // If the extract is known to be all zeros, return zero.
262295011Sandrew    if (ByteStart >= CSize-ShAmt)
263295011Sandrew      return Constant::getNullValue(IntegerType::get(CE->getContext(),
264295011Sandrew                                                     ByteSize*8));
265295011Sandrew    // If the extract is known to be fully in the input, extract it.
266295011Sandrew    if (ByteStart+ByteSize+ShAmt <= CSize)
267295011Sandrew      return ExtractConstantBytes(CE->getOperand(0), ByteStart+ShAmt, ByteSize);
268295011Sandrew
269295011Sandrew    // TODO: Handle the 'partially zero' case.
270295011Sandrew    return 0;
271295011Sandrew  }
272295011Sandrew
273295011Sandrew  case Instruction::Shl: {
274295011Sandrew    ConstantInt *Amt = dyn_cast<ConstantInt>(CE->getOperand(1));
275295011Sandrew    if (Amt == 0)
276295011Sandrew      return 0;
277295011Sandrew    unsigned ShAmt = Amt->getZExtValue();
278295011Sandrew    // Cannot analyze non-byte shifts.
279295011Sandrew    if ((ShAmt & 7) != 0)
280295011Sandrew      return 0;
281295011Sandrew    ShAmt >>= 3;
282295011Sandrew
283295011Sandrew    // If the extract is known to be all zeros, return zero.
284295011Sandrew    if (ByteStart+ByteSize <= ShAmt)
285295011Sandrew      return Constant::getNullValue(IntegerType::get(CE->getContext(),
286295011Sandrew                                                     ByteSize*8));
287295011Sandrew    // If the extract is known to be fully in the input, extract it.
288295011Sandrew    if (ByteStart >= ShAmt)
289295011Sandrew      return ExtractConstantBytes(CE->getOperand(0), ByteStart-ShAmt, ByteSize);
290295011Sandrew
291295011Sandrew    // TODO: Handle the 'partially zero' case.
292295011Sandrew    return 0;
293295011Sandrew  }
294295011Sandrew
295295011Sandrew  case Instruction::ZExt: {
296295011Sandrew    unsigned SrcBitSize =
297295011Sandrew      cast<IntegerType>(CE->getOperand(0)->getType())->getBitWidth();
298295011Sandrew
299295011Sandrew    // If extracting something that is completely zero, return 0.
300295011Sandrew    if (ByteStart*8 >= SrcBitSize)
301295011Sandrew      return Constant::getNullValue(IntegerType::get(CE->getContext(),
302295011Sandrew                                                     ByteSize*8));
303295011Sandrew
304295011Sandrew    // If exactly extracting the input, return it.
305295011Sandrew    if (ByteStart == 0 && ByteSize*8 == SrcBitSize)
306295011Sandrew      return CE->getOperand(0);
307295011Sandrew
308295011Sandrew    // If extracting something completely in the input, if if the input is a
309295011Sandrew    // multiple of 8 bits, recurse.
310295011Sandrew    if ((SrcBitSize&7) == 0 && (ByteStart+ByteSize)*8 <= SrcBitSize)
311295011Sandrew      return ExtractConstantBytes(CE->getOperand(0), ByteStart, ByteSize);
312295011Sandrew
313295011Sandrew    // Otherwise, if extracting a subset of the input, which is not multiple of
314295011Sandrew    // 8 bits, do a shift and trunc to get the bits.
315295011Sandrew    if ((ByteStart+ByteSize)*8 < SrcBitSize) {
316295011Sandrew      assert((SrcBitSize&7) && "Shouldn't get byte sized case here");
317295011Sandrew      Constant *Res = CE->getOperand(0);
318295011Sandrew      if (ByteStart)
319295011Sandrew        Res = ConstantExpr::getLShr(Res,
320295011Sandrew                                 ConstantInt::get(Res->getType(), ByteStart*8));
321295011Sandrew      return ConstantExpr::getTrunc(Res, IntegerType::get(C->getContext(),
322295011Sandrew                                                          ByteSize*8));
323295011Sandrew    }
324295011Sandrew
325295011Sandrew    // TODO: Handle the 'partially zero' case.
326295011Sandrew    return 0;
327295011Sandrew  }
328295011Sandrew  }
329295011Sandrew}
330295011Sandrew
331295011Sandrew/// getFoldedSizeOf - Return a ConstantExpr with type DestTy for sizeof
332295011Sandrew/// on Ty, with any known factors factored out. If Folded is false,
333295011Sandrew/// return null if no factoring was possible, to avoid endlessly
334295011Sandrew/// bouncing an unfoldable expression back into the top-level folder.
335295011Sandrew///
336295011Sandrewstatic Constant *getFoldedSizeOf(Type *Ty, Type *DestTy,
337295011Sandrew                                 bool Folded) {
338295011Sandrew  if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
339295011Sandrew    Constant *N = ConstantInt::get(DestTy, ATy->getNumElements());
340295011Sandrew    Constant *E = getFoldedSizeOf(ATy->getElementType(), DestTy, true);
341295011Sandrew    return ConstantExpr::getNUWMul(E, N);
342295011Sandrew  }
343295011Sandrew
344295011Sandrew  if (StructType *STy = dyn_cast<StructType>(Ty))
345295011Sandrew    if (!STy->isPacked()) {
346295011Sandrew      unsigned NumElems = STy->getNumElements();
347295011Sandrew      // An empty struct has size zero.
348295011Sandrew      if (NumElems == 0)
349295011Sandrew        return ConstantExpr::getNullValue(DestTy);
350295011Sandrew      // Check for a struct with all members having the same size.
351295011Sandrew      Constant *MemberSize =
352295011Sandrew        getFoldedSizeOf(STy->getElementType(0), DestTy, true);
353295011Sandrew      bool AllSame = true;
354295011Sandrew      for (unsigned i = 1; i != NumElems; ++i)
355295011Sandrew        if (MemberSize !=
356295011Sandrew            getFoldedSizeOf(STy->getElementType(i), DestTy, true)) {
357295011Sandrew          AllSame = false;
358295011Sandrew          break;
359295011Sandrew        }
360295011Sandrew      if (AllSame) {
361295011Sandrew        Constant *N = ConstantInt::get(DestTy, NumElems);
362295011Sandrew        return ConstantExpr::getNUWMul(MemberSize, N);
363295011Sandrew      }
364295011Sandrew    }
365295011Sandrew
366295011Sandrew  // Pointer size doesn't depend on the pointee type, so canonicalize them
367295011Sandrew  // to an arbitrary pointee.
368295011Sandrew  if (PointerType *PTy = dyn_cast<PointerType>(Ty))
369295011Sandrew    if (!PTy->getElementType()->isIntegerTy(1))
370295011Sandrew      return
371295011Sandrew        getFoldedSizeOf(PointerType::get(IntegerType::get(PTy->getContext(), 1),
372295011Sandrew                                         PTy->getAddressSpace()),
373295011Sandrew                        DestTy, true);
374295011Sandrew
375295011Sandrew  // If there's no interesting folding happening, bail so that we don't create
376295011Sandrew  // a constant that looks like it needs folding but really doesn't.
377295011Sandrew  if (!Folded)
378295011Sandrew    return 0;
379295011Sandrew
380295011Sandrew  // Base case: Get a regular sizeof expression.
381295011Sandrew  Constant *C = ConstantExpr::getSizeOf(Ty);
382295011Sandrew  C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false,
383295011Sandrew                                                    DestTy, false),
384295011Sandrew                            C, DestTy);
385295011Sandrew  return C;
386295011Sandrew}
387295011Sandrew
388295011Sandrew/// getFoldedAlignOf - Return a ConstantExpr with type DestTy for alignof
389295011Sandrew/// on Ty, with any known factors factored out. If Folded is false,
390295011Sandrew/// return null if no factoring was possible, to avoid endlessly
391295011Sandrew/// bouncing an unfoldable expression back into the top-level folder.
392295011Sandrew///
393295011Sandrewstatic Constant *getFoldedAlignOf(Type *Ty, Type *DestTy,
394295011Sandrew                                  bool Folded) {
395295011Sandrew  // The alignment of an array is equal to the alignment of the
396295011Sandrew  // array element. Note that this is not always true for vectors.
397295011Sandrew  if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
398295011Sandrew    Constant *C = ConstantExpr::getAlignOf(ATy->getElementType());
399295011Sandrew    C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false,
400295011Sandrew                                                      DestTy,
401295011Sandrew                                                      false),
402295011Sandrew                              C, DestTy);
403295011Sandrew    return C;
404295011Sandrew  }
405295011Sandrew
406295011Sandrew  if (StructType *STy = dyn_cast<StructType>(Ty)) {
407295011Sandrew    // Packed structs always have an alignment of 1.
408295011Sandrew    if (STy->isPacked())
409295011Sandrew      return ConstantInt::get(DestTy, 1);
410295011Sandrew
411295011Sandrew    // Otherwise, struct alignment is the maximum alignment of any member.
412295011Sandrew    // Without target data, we can't compare much, but we can check to see
413295011Sandrew    // if all the members have the same alignment.
414295011Sandrew    unsigned NumElems = STy->getNumElements();
415295011Sandrew    // An empty struct has minimal alignment.
416295011Sandrew    if (NumElems == 0)
417295011Sandrew      return ConstantInt::get(DestTy, 1);
418295011Sandrew    // Check for a struct with all members having the same alignment.
419295011Sandrew    Constant *MemberAlign =
420295011Sandrew      getFoldedAlignOf(STy->getElementType(0), DestTy, true);
421295011Sandrew    bool AllSame = true;
422295011Sandrew    for (unsigned i = 1; i != NumElems; ++i)
423295011Sandrew      if (MemberAlign != getFoldedAlignOf(STy->getElementType(i), DestTy, true)) {
424295011Sandrew        AllSame = false;
425295011Sandrew        break;
426295011Sandrew      }
427295011Sandrew    if (AllSame)
428295011Sandrew      return MemberAlign;
429295011Sandrew  }
430295011Sandrew
431295011Sandrew  // Pointer alignment doesn't depend on the pointee type, so canonicalize them
432295011Sandrew  // to an arbitrary pointee.
433295011Sandrew  if (PointerType *PTy = dyn_cast<PointerType>(Ty))
434295011Sandrew    if (!PTy->getElementType()->isIntegerTy(1))
435295011Sandrew      return
436295011Sandrew        getFoldedAlignOf(PointerType::get(IntegerType::get(PTy->getContext(),
437295011Sandrew                                                           1),
438295011Sandrew                                          PTy->getAddressSpace()),
439295011Sandrew                         DestTy, true);
440295011Sandrew
441295011Sandrew  // If there's no interesting folding happening, bail so that we don't create
442295011Sandrew  // a constant that looks like it needs folding but really doesn't.
443295011Sandrew  if (!Folded)
444295011Sandrew    return 0;
445295011Sandrew
446295011Sandrew  // Base case: Get a regular alignof expression.
447295011Sandrew  Constant *C = ConstantExpr::getAlignOf(Ty);
448295011Sandrew  C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false,
449295011Sandrew                                                    DestTy, false),
450295011Sandrew                            C, DestTy);
451295011Sandrew  return C;
452295011Sandrew}
453295011Sandrew
454295011Sandrew/// getFoldedOffsetOf - Return a ConstantExpr with type DestTy for offsetof
455295011Sandrew/// on Ty and FieldNo, with any known factors factored out. If Folded is false,
456295011Sandrew/// return null if no factoring was possible, to avoid endlessly
457295011Sandrew/// bouncing an unfoldable expression back into the top-level folder.
458295011Sandrew///
459295011Sandrewstatic Constant *getFoldedOffsetOf(Type *Ty, Constant *FieldNo,
460295011Sandrew                                   Type *DestTy,
461295011Sandrew                                   bool Folded) {
462295011Sandrew  if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
463295011Sandrew    Constant *N = ConstantExpr::getCast(CastInst::getCastOpcode(FieldNo, false,
464295011Sandrew                                                                DestTy, false),
465295011Sandrew                                        FieldNo, DestTy);
466295011Sandrew    Constant *E = getFoldedSizeOf(ATy->getElementType(), DestTy, true);
467295011Sandrew    return ConstantExpr::getNUWMul(E, N);
468295011Sandrew  }
469295011Sandrew
470295011Sandrew  if (StructType *STy = dyn_cast<StructType>(Ty))
471295011Sandrew    if (!STy->isPacked()) {
472295011Sandrew      unsigned NumElems = STy->getNumElements();
473295011Sandrew      // An empty struct has no members.
474295011Sandrew      if (NumElems == 0)
475295011Sandrew        return 0;
476295011Sandrew      // Check for a struct with all members having the same size.
477295011Sandrew      Constant *MemberSize =
478295011Sandrew        getFoldedSizeOf(STy->getElementType(0), DestTy, true);
479295011Sandrew      bool AllSame = true;
480295011Sandrew      for (unsigned i = 1; i != NumElems; ++i)
481295011Sandrew        if (MemberSize !=
482295011Sandrew            getFoldedSizeOf(STy->getElementType(i), DestTy, true)) {
483295011Sandrew          AllSame = false;
484295011Sandrew          break;
485295011Sandrew        }
486295011Sandrew      if (AllSame) {
487295011Sandrew        Constant *N = ConstantExpr::getCast(CastInst::getCastOpcode(FieldNo,
488295011Sandrew                                                                    false,
489295011Sandrew                                                                    DestTy,
490295011Sandrew                                                                    false),
491295011Sandrew                                            FieldNo, DestTy);
492295011Sandrew        return ConstantExpr::getNUWMul(MemberSize, N);
493295011Sandrew      }
494295011Sandrew    }
495295011Sandrew
496295011Sandrew  // If there's no interesting folding happening, bail so that we don't create
497295011Sandrew  // a constant that looks like it needs folding but really doesn't.
498295011Sandrew  if (!Folded)
499295011Sandrew    return 0;
500295011Sandrew
501295011Sandrew  // Base case: Get a regular offsetof expression.
502295011Sandrew  Constant *C = ConstantExpr::getOffsetOf(Ty, FieldNo);
503295011Sandrew  C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false,
504295011Sandrew                                                    DestTy, false),
505295011Sandrew                            C, DestTy);
506295011Sandrew  return C;
507295011Sandrew}
508295011Sandrew
509295011SandrewConstant *llvm::ConstantFoldCastInstruction(unsigned opc, Constant *V,
510295011Sandrew                                            Type *DestTy) {
511295011Sandrew  if (isa<UndefValue>(V)) {
512295011Sandrew    // zext(undef) = 0, because the top bits will be zero.
513295011Sandrew    // sext(undef) = 0, because the top bits will all be the same.
514295011Sandrew    // [us]itofp(undef) = 0, because the result value is bounded.
515295011Sandrew    if (opc == Instruction::ZExt || opc == Instruction::SExt ||
516295011Sandrew        opc == Instruction::UIToFP || opc == Instruction::SIToFP)
517295011Sandrew      return Constant::getNullValue(DestTy);
518295011Sandrew    return UndefValue::get(DestTy);
519295011Sandrew  }
520295011Sandrew
521295011Sandrew  if (V->isNullValue() && !DestTy->isX86_MMXTy())
522295011Sandrew    return Constant::getNullValue(DestTy);
523295011Sandrew
524295011Sandrew  // If the cast operand is a constant expression, there's a few things we can
525295011Sandrew  // do to try to simplify it.
526295011Sandrew  if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) {
527295011Sandrew    if (CE->isCast()) {
528295011Sandrew      // Try hard to fold cast of cast because they are often eliminable.
529295011Sandrew      if (unsigned newOpc = foldConstantCastPair(opc, CE, DestTy))
530295011Sandrew        return ConstantExpr::getCast(newOpc, CE->getOperand(0), DestTy);
531295011Sandrew    } else if (CE->getOpcode() == Instruction::GetElementPtr) {
532295011Sandrew      // If all of the indexes in the GEP are null values, there is no pointer
533295011Sandrew      // adjustment going on.  We might as well cast the source pointer.
534295011Sandrew      bool isAllNull = true;
535295011Sandrew      for (unsigned i = 1, e = CE->getNumOperands(); i != e; ++i)
536295011Sandrew        if (!CE->getOperand(i)->isNullValue()) {
537295011Sandrew          isAllNull = false;
538295011Sandrew          break;
539295011Sandrew        }
540295011Sandrew      if (isAllNull)
541295011Sandrew        // This is casting one pointer type to another, always BitCast
542295011Sandrew        return ConstantExpr::getPointerCast(CE->getOperand(0), DestTy);
543295011Sandrew    }
544295011Sandrew  }
545295011Sandrew
546295011Sandrew  // If the cast operand is a constant vector, perform the cast by
547295011Sandrew  // operating on each element. In the cast of bitcasts, the element
548295011Sandrew  // count may be mismatched; don't attempt to handle that here.
549295011Sandrew  if ((isa<ConstantVector>(V) || isa<ConstantDataVector>(V)) &&
550295011Sandrew      DestTy->isVectorTy() &&
551295011Sandrew      DestTy->getVectorNumElements() == V->getType()->getVectorNumElements()) {
552295011Sandrew    SmallVector<Constant*, 16> res;
553295011Sandrew    VectorType *DestVecTy = cast<VectorType>(DestTy);
554295011Sandrew    Type *DstEltTy = DestVecTy->getElementType();
555295011Sandrew    Type *Ty = IntegerType::get(V->getContext(), 32);
556295011Sandrew    for (unsigned i = 0, e = V->getType()->getVectorNumElements(); i != e; ++i) {
557295011Sandrew      Constant *C =
558295011Sandrew        ConstantExpr::getExtractElement(V, ConstantInt::get(Ty, i));
559295011Sandrew      res.push_back(ConstantExpr::getCast(opc, C, DstEltTy));
560295011Sandrew    }
561295011Sandrew    return ConstantVector::get(res);
562295011Sandrew  }
563295011Sandrew
564295011Sandrew  // We actually have to do a cast now. Perform the cast according to the
565295011Sandrew  // opcode specified.
566295011Sandrew  switch (opc) {
567295011Sandrew  default:
568295011Sandrew    llvm_unreachable("Failed to cast constant expression");
569295011Sandrew  case Instruction::FPTrunc:
570295011Sandrew  case Instruction::FPExt:
571295011Sandrew    if (ConstantFP *FPC = dyn_cast<ConstantFP>(V)) {
572295011Sandrew      bool ignored;
573295011Sandrew      APFloat Val = FPC->getValueAPF();
574295011Sandrew      Val.convert(DestTy->isHalfTy() ? APFloat::IEEEhalf :
575295011Sandrew                  DestTy->isFloatTy() ? APFloat::IEEEsingle :
576295011Sandrew                  DestTy->isDoubleTy() ? APFloat::IEEEdouble :
577295011Sandrew                  DestTy->isX86_FP80Ty() ? APFloat::x87DoubleExtended :
578295011Sandrew                  DestTy->isFP128Ty() ? APFloat::IEEEquad :
579295011Sandrew                  DestTy->isPPC_FP128Ty() ? APFloat::PPCDoubleDouble :
580295011Sandrew                  APFloat::Bogus,
581295011Sandrew                  APFloat::rmNearestTiesToEven, &ignored);
582295011Sandrew      return ConstantFP::get(V->getContext(), Val);
583295011Sandrew    }
584295011Sandrew    return 0; // Can't fold.
585295011Sandrew  case Instruction::FPToUI:
586295011Sandrew  case Instruction::FPToSI:
587295011Sandrew    if (ConstantFP *FPC = dyn_cast<ConstantFP>(V)) {
588295011Sandrew      const APFloat &V = FPC->getValueAPF();
589295011Sandrew      bool ignored;
590295011Sandrew      uint64_t x[2];
591295011Sandrew      uint32_t DestBitWidth = cast<IntegerType>(DestTy)->getBitWidth();
592295011Sandrew      (void) V.convertToInteger(x, DestBitWidth, opc==Instruction::FPToSI,
593295011Sandrew                                APFloat::rmTowardZero, &ignored);
594295011Sandrew      APInt Val(DestBitWidth, x);
595295011Sandrew      return ConstantInt::get(FPC->getContext(), Val);
596295011Sandrew    }
597295011Sandrew    return 0; // Can't fold.
598295011Sandrew  case Instruction::IntToPtr:   //always treated as unsigned
599295011Sandrew    if (V->isNullValue())       // Is it an integral null value?
600295011Sandrew      return ConstantPointerNull::get(cast<PointerType>(DestTy));
601295011Sandrew    return 0;                   // Other pointer types cannot be casted
602295011Sandrew  case Instruction::PtrToInt:   // always treated as unsigned
603295011Sandrew    // Is it a null pointer value?
604295011Sandrew    if (V->isNullValue())
605295011Sandrew      return ConstantInt::get(DestTy, 0);
606295011Sandrew    // If this is a sizeof-like expression, pull out multiplications by
607295011Sandrew    // known factors to expose them to subsequent folding. If it's an
608295011Sandrew    // alignof-like expression, factor out known factors.
609295011Sandrew    if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
610295011Sandrew      if (CE->getOpcode() == Instruction::GetElementPtr &&
611295011Sandrew          CE->getOperand(0)->isNullValue()) {
612295011Sandrew        Type *Ty =
613295011Sandrew          cast<PointerType>(CE->getOperand(0)->getType())->getElementType();
614295011Sandrew        if (CE->getNumOperands() == 2) {
615295011Sandrew          // Handle a sizeof-like expression.
616295011Sandrew          Constant *Idx = CE->getOperand(1);
617295011Sandrew          bool isOne = isa<ConstantInt>(Idx) && cast<ConstantInt>(Idx)->isOne();
618295011Sandrew          if (Constant *C = getFoldedSizeOf(Ty, DestTy, !isOne)) {
619295011Sandrew            Idx = ConstantExpr::getCast(CastInst::getCastOpcode(Idx, true,
620295011Sandrew                                                                DestTy, false),
621295011Sandrew                                        Idx, DestTy);
622295011Sandrew            return ConstantExpr::getMul(C, Idx);
623295011Sandrew          }
624295011Sandrew        } else if (CE->getNumOperands() == 3 &&
625295011Sandrew                   CE->getOperand(1)->isNullValue()) {
626295011Sandrew          // Handle an alignof-like expression.
627295011Sandrew          if (StructType *STy = dyn_cast<StructType>(Ty))
628295011Sandrew            if (!STy->isPacked()) {
629295011Sandrew              ConstantInt *CI = cast<ConstantInt>(CE->getOperand(2));
630295011Sandrew              if (CI->isOne() &&
631295011Sandrew                  STy->getNumElements() == 2 &&
632295011Sandrew                  STy->getElementType(0)->isIntegerTy(1)) {
633295011Sandrew                return getFoldedAlignOf(STy->getElementType(1), DestTy, false);
634295011Sandrew              }
635295011Sandrew            }
636295011Sandrew          // Handle an offsetof-like expression.
637295011Sandrew          if (Ty->isStructTy() || Ty->isArrayTy()) {
638295011Sandrew            if (Constant *C = getFoldedOffsetOf(Ty, CE->getOperand(2),
639295011Sandrew                                                DestTy, false))
640295011Sandrew              return C;
641295011Sandrew          }
642295011Sandrew        }
643295011Sandrew      }
644295011Sandrew    // Other pointer types cannot be casted
645295011Sandrew    return 0;
646295011Sandrew  case Instruction::UIToFP:
647295011Sandrew  case Instruction::SIToFP:
648295011Sandrew    if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
649295011Sandrew      APInt api = CI->getValue();
650295011Sandrew      APFloat apf(DestTy->getFltSemantics(),
651295011Sandrew                  APInt::getNullValue(DestTy->getPrimitiveSizeInBits()));
652295011Sandrew      (void)apf.convertFromAPInt(api,
653295011Sandrew                                 opc==Instruction::SIToFP,
654295011Sandrew                                 APFloat::rmNearestTiesToEven);
655295011Sandrew      return ConstantFP::get(V->getContext(), apf);
656295011Sandrew    }
657295011Sandrew    return 0;
658295011Sandrew  case Instruction::ZExt:
659295011Sandrew    if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
660295011Sandrew      uint32_t BitWidth = cast<IntegerType>(DestTy)->getBitWidth();
661295011Sandrew      return ConstantInt::get(V->getContext(),
662295011Sandrew                              CI->getValue().zext(BitWidth));
663295011Sandrew    }
664295011Sandrew    return 0;
665295011Sandrew  case Instruction::SExt:
666295011Sandrew    if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
667295011Sandrew      uint32_t BitWidth = cast<IntegerType>(DestTy)->getBitWidth();
668295011Sandrew      return ConstantInt::get(V->getContext(),
669295011Sandrew                              CI->getValue().sext(BitWidth));
670295011Sandrew    }
671295011Sandrew    return 0;
672295011Sandrew  case Instruction::Trunc: {
673295011Sandrew    uint32_t DestBitWidth = cast<IntegerType>(DestTy)->getBitWidth();
674295011Sandrew    if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
675295011Sandrew      return ConstantInt::get(V->getContext(),
676295011Sandrew                              CI->getValue().trunc(DestBitWidth));
677295011Sandrew    }
678295011Sandrew
679295011Sandrew    // The input must be a constantexpr.  See if we can simplify this based on
680295011Sandrew    // the bytes we are demanding.  Only do this if the source and dest are an
681295011Sandrew    // even multiple of a byte.
682295011Sandrew    if ((DestBitWidth & 7) == 0 &&
683295011Sandrew        (cast<IntegerType>(V->getType())->getBitWidth() & 7) == 0)
684295011Sandrew      if (Constant *Res = ExtractConstantBytes(V, 0, DestBitWidth / 8))
685295011Sandrew        return Res;
686295011Sandrew
687295011Sandrew    return 0;
688295011Sandrew  }
689295011Sandrew  case Instruction::BitCast:
690295011Sandrew    return FoldBitCast(V, DestTy);
691295011Sandrew  }
692295011Sandrew}
693295011Sandrew
694295011SandrewConstant *llvm::ConstantFoldSelectInstruction(Constant *Cond,
695295011Sandrew                                              Constant *V1, Constant *V2) {
696295011Sandrew  // Check for i1 and vector true/false conditions.
697295011Sandrew  if (Cond->isNullValue()) return V2;
698295011Sandrew  if (Cond->isAllOnesValue()) return V1;
699295011Sandrew
700295011Sandrew  // If the condition is a vector constant, fold the result elementwise.
701295011Sandrew  if (ConstantVector *CondV = dyn_cast<ConstantVector>(Cond)) {
702295011Sandrew    SmallVector<Constant*, 16> Result;
703295011Sandrew    Type *Ty = IntegerType::get(CondV->getContext(), 32);
704295011Sandrew    for (unsigned i = 0, e = V1->getType()->getVectorNumElements(); i != e;++i){
705295011Sandrew      ConstantInt *Cond = dyn_cast<ConstantInt>(CondV->getOperand(i));
706295011Sandrew      if (Cond == 0) break;
707295011Sandrew
708295011Sandrew      Constant *V = Cond->isNullValue() ? V2 : V1;
709295011Sandrew      Constant *Res = ConstantExpr::getExtractElement(V, ConstantInt::get(Ty, i));
710295011Sandrew      Result.push_back(Res);
711295011Sandrew    }
712295011Sandrew
713295011Sandrew    // If we were able to build the vector, return it.
714295011Sandrew    if (Result.size() == V1->getType()->getVectorNumElements())
715295011Sandrew      return ConstantVector::get(Result);
716295011Sandrew  }
717295011Sandrew
718295011Sandrew  if (isa<UndefValue>(Cond)) {
719295011Sandrew    if (isa<UndefValue>(V1)) return V1;
720295011Sandrew    return V2;
721295011Sandrew  }
722295011Sandrew  if (isa<UndefValue>(V1)) return V2;
723295011Sandrew  if (isa<UndefValue>(V2)) return V1;
724295011Sandrew  if (V1 == V2) return V1;
725295011Sandrew
726295011Sandrew  if (ConstantExpr *TrueVal = dyn_cast<ConstantExpr>(V1)) {
727295011Sandrew    if (TrueVal->getOpcode() == Instruction::Select)
728295011Sandrew      if (TrueVal->getOperand(0) == Cond)
729295011Sandrew        return ConstantExpr::getSelect(Cond, TrueVal->getOperand(1), V2);
730295011Sandrew  }
731295011Sandrew  if (ConstantExpr *FalseVal = dyn_cast<ConstantExpr>(V2)) {
732295011Sandrew    if (FalseVal->getOpcode() == Instruction::Select)
733295011Sandrew      if (FalseVal->getOperand(0) == Cond)
734295011Sandrew        return ConstantExpr::getSelect(Cond, V1, FalseVal->getOperand(2));
735295011Sandrew  }
736295011Sandrew
737295011Sandrew  return 0;
738295011Sandrew}
739295011Sandrew
740295011SandrewConstant *llvm::ConstantFoldExtractElementInstruction(Constant *Val,
741295011Sandrew                                                      Constant *Idx) {
742295011Sandrew  if (isa<UndefValue>(Val))  // ee(undef, x) -> undef
743295011Sandrew    return UndefValue::get(Val->getType()->getVectorElementType());
744295011Sandrew  if (Val->isNullValue())  // ee(zero, x) -> zero
745295011Sandrew    return Constant::getNullValue(Val->getType()->getVectorElementType());
746295011Sandrew  // ee({w,x,y,z}, undef) -> undef
747295011Sandrew  if (isa<UndefValue>(Idx))
748295011Sandrew    return UndefValue::get(Val->getType()->getVectorElementType());
749295011Sandrew
750295011Sandrew  if (ConstantInt *CIdx = dyn_cast<ConstantInt>(Idx)) {
751295011Sandrew    uint64_t Index = CIdx->getZExtValue();
752295011Sandrew    // ee({w,x,y,z}, wrong_value) -> undef
753295011Sandrew    if (Index >= Val->getType()->getVectorNumElements())
754295011Sandrew      return UndefValue::get(Val->getType()->getVectorElementType());
755295011Sandrew    return Val->getAggregateElement(Index);
756295011Sandrew  }
757295011Sandrew  return 0;
758295011Sandrew}
759295011Sandrew
760295011SandrewConstant *llvm::ConstantFoldInsertElementInstruction(Constant *Val,
761295011Sandrew                                                     Constant *Elt,
762295011Sandrew                                                     Constant *Idx) {
763295011Sandrew  ConstantInt *CIdx = dyn_cast<ConstantInt>(Idx);
764295011Sandrew  if (!CIdx) return 0;
765295011Sandrew  const APInt &IdxVal = CIdx->getValue();
766295011Sandrew
767295011Sandrew  SmallVector<Constant*, 16> Result;
768295011Sandrew  Type *Ty = IntegerType::get(Val->getContext(), 32);
769295011Sandrew  for (unsigned i = 0, e = Val->getType()->getVectorNumElements(); i != e; ++i){
770295011Sandrew    if (i == IdxVal) {
771295011Sandrew      Result.push_back(Elt);
772295011Sandrew      continue;
773295011Sandrew    }
774295011Sandrew
775295011Sandrew    Constant *C =
776295011Sandrew      ConstantExpr::getExtractElement(Val, ConstantInt::get(Ty, i));
777295011Sandrew    Result.push_back(C);
778295011Sandrew  }
779295011Sandrew
780295011Sandrew  return ConstantVector::get(Result);
781295011Sandrew}
782295011Sandrew
783295011SandrewConstant *llvm::ConstantFoldShuffleVectorInstruction(Constant *V1,
784295011Sandrew                                                     Constant *V2,
785295011Sandrew                                                     Constant *Mask) {
786295011Sandrew  unsigned MaskNumElts = Mask->getType()->getVectorNumElements();
787295011Sandrew  Type *EltTy = V1->getType()->getVectorElementType();
788295011Sandrew
789295011Sandrew  // Undefined shuffle mask -> undefined value.
790295011Sandrew  if (isa<UndefValue>(Mask))
791295011Sandrew    return UndefValue::get(VectorType::get(EltTy, MaskNumElts));
792295011Sandrew
793295011Sandrew  // Don't break the bitcode reader hack.
794295011Sandrew  if (isa<ConstantExpr>(Mask)) return 0;
795295011Sandrew
796295011Sandrew  unsigned SrcNumElts = V1->getType()->getVectorNumElements();
797295011Sandrew
798295011Sandrew  // Loop over the shuffle mask, evaluating each element.
799295011Sandrew  SmallVector<Constant*, 32> Result;
800295011Sandrew  for (unsigned i = 0; i != MaskNumElts; ++i) {
801295011Sandrew    int Elt = ShuffleVectorInst::getMaskValue(Mask, i);
802295011Sandrew    if (Elt == -1) {
803295011Sandrew      Result.push_back(UndefValue::get(EltTy));
804295011Sandrew      continue;
805295011Sandrew    }
806295011Sandrew    Constant *InElt;
807295011Sandrew    if (unsigned(Elt) >= SrcNumElts*2)
808295011Sandrew      InElt = UndefValue::get(EltTy);
809295011Sandrew    else if (unsigned(Elt) >= SrcNumElts) {
810295011Sandrew      Type *Ty = IntegerType::get(V2->getContext(), 32);
811295011Sandrew      InElt =
812295011Sandrew        ConstantExpr::getExtractElement(V2,
813295011Sandrew                                        ConstantInt::get(Ty, Elt - SrcNumElts));
814295011Sandrew    } else {
815295011Sandrew      Type *Ty = IntegerType::get(V1->getContext(), 32);
816295011Sandrew      InElt = ConstantExpr::getExtractElement(V1, ConstantInt::get(Ty, Elt));
817295011Sandrew    }
818295011Sandrew    Result.push_back(InElt);
819295011Sandrew  }
820295011Sandrew
821295011Sandrew  return ConstantVector::get(Result);
822295011Sandrew}
823295011Sandrew
824295011SandrewConstant *llvm::ConstantFoldExtractValueInstruction(Constant *Agg,
825295011Sandrew                                                    ArrayRef<unsigned> Idxs) {
826295011Sandrew  // Base case: no indices, so return the entire value.
827295011Sandrew  if (Idxs.empty())
828295011Sandrew    return Agg;
829295011Sandrew
830295011Sandrew  if (Constant *C = Agg->getAggregateElement(Idxs[0]))
831295011Sandrew    return ConstantFoldExtractValueInstruction(C, Idxs.slice(1));
832295011Sandrew
833295011Sandrew  return 0;
834295011Sandrew}
835295011Sandrew
836295011SandrewConstant *llvm::ConstantFoldInsertValueInstruction(Constant *Agg,
837295011Sandrew                                                   Constant *Val,
838295011Sandrew                                                   ArrayRef<unsigned> Idxs) {
839295011Sandrew  // Base case: no indices, so replace the entire value.
840295011Sandrew  if (Idxs.empty())
841295011Sandrew    return Val;
842295011Sandrew
843295011Sandrew  unsigned NumElts;
844295011Sandrew  if (StructType *ST = dyn_cast<StructType>(Agg->getType()))
845295011Sandrew    NumElts = ST->getNumElements();
846295011Sandrew  else if (ArrayType *AT = dyn_cast<ArrayType>(Agg->getType()))
847295011Sandrew    NumElts = AT->getNumElements();
848295011Sandrew  else
849295011Sandrew    NumElts = Agg->getType()->getVectorNumElements();
850295011Sandrew
851295011Sandrew  SmallVector<Constant*, 32> Result;
852295011Sandrew  for (unsigned i = 0; i != NumElts; ++i) {
853295011Sandrew    Constant *C = Agg->getAggregateElement(i);
854295011Sandrew    if (C == 0) return 0;
855295011Sandrew
856295011Sandrew    if (Idxs[0] == i)
857295011Sandrew      C = ConstantFoldInsertValueInstruction(C, Val, Idxs.slice(1));
858295011Sandrew
859295011Sandrew    Result.push_back(C);
860295011Sandrew  }
861295011Sandrew
862295011Sandrew  if (StructType *ST = dyn_cast<StructType>(Agg->getType()))
863295011Sandrew    return ConstantStruct::get(ST, Result);
864295011Sandrew  if (ArrayType *AT = dyn_cast<ArrayType>(Agg->getType()))
865295011Sandrew    return ConstantArray::get(AT, Result);
866295011Sandrew  return ConstantVector::get(Result);
867295011Sandrew}
868295011Sandrew
869295011Sandrew
870295011SandrewConstant *llvm::ConstantFoldBinaryInstruction(unsigned Opcode,
871295011Sandrew                                              Constant *C1, Constant *C2) {
872295011Sandrew  // Handle UndefValue up front.
873295011Sandrew  if (isa<UndefValue>(C1) || isa<UndefValue>(C2)) {
874    switch (Opcode) {
875    case Instruction::Xor:
876      if (isa<UndefValue>(C1) && isa<UndefValue>(C2))
877        // Handle undef ^ undef -> 0 special case. This is a common
878        // idiom (misuse).
879        return Constant::getNullValue(C1->getType());
880      // Fallthrough
881    case Instruction::Add:
882    case Instruction::Sub:
883      return UndefValue::get(C1->getType());
884    case Instruction::And:
885      if (isa<UndefValue>(C1) && isa<UndefValue>(C2)) // undef & undef -> undef
886        return C1;
887      return Constant::getNullValue(C1->getType());   // undef & X -> 0
888    case Instruction::Mul: {
889      ConstantInt *CI;
890      // X * undef -> undef   if X is odd or undef
891      if (((CI = dyn_cast<ConstantInt>(C1)) && CI->getValue()[0]) ||
892          ((CI = dyn_cast<ConstantInt>(C2)) && CI->getValue()[0]) ||
893          (isa<UndefValue>(C1) && isa<UndefValue>(C2)))
894        return UndefValue::get(C1->getType());
895
896      // X * undef -> 0       otherwise
897      return Constant::getNullValue(C1->getType());
898    }
899    case Instruction::UDiv:
900    case Instruction::SDiv:
901      // undef / 1 -> undef
902      if (Opcode == Instruction::UDiv || Opcode == Instruction::SDiv)
903        if (ConstantInt *CI2 = dyn_cast<ConstantInt>(C2))
904          if (CI2->isOne())
905            return C1;
906      // FALL THROUGH
907    case Instruction::URem:
908    case Instruction::SRem:
909      if (!isa<UndefValue>(C2))                    // undef / X -> 0
910        return Constant::getNullValue(C1->getType());
911      return C2;                                   // X / undef -> undef
912    case Instruction::Or:                          // X | undef -> -1
913      if (isa<UndefValue>(C1) && isa<UndefValue>(C2)) // undef | undef -> undef
914        return C1;
915      return Constant::getAllOnesValue(C1->getType()); // undef | X -> ~0
916    case Instruction::LShr:
917      if (isa<UndefValue>(C2) && isa<UndefValue>(C1))
918        return C1;                                  // undef lshr undef -> undef
919      return Constant::getNullValue(C1->getType()); // X lshr undef -> 0
920                                                    // undef lshr X -> 0
921    case Instruction::AShr:
922      if (!isa<UndefValue>(C2))                     // undef ashr X --> all ones
923        return Constant::getAllOnesValue(C1->getType());
924      else if (isa<UndefValue>(C1))
925        return C1;                                  // undef ashr undef -> undef
926      else
927        return C1;                                  // X ashr undef --> X
928    case Instruction::Shl:
929      if (isa<UndefValue>(C2) && isa<UndefValue>(C1))
930        return C1;                                  // undef shl undef -> undef
931      // undef << X -> 0   or   X << undef -> 0
932      return Constant::getNullValue(C1->getType());
933    }
934  }
935
936  // Handle simplifications when the RHS is a constant int.
937  if (ConstantInt *CI2 = dyn_cast<ConstantInt>(C2)) {
938    switch (Opcode) {
939    case Instruction::Add:
940      if (CI2->equalsInt(0)) return C1;                         // X + 0 == X
941      break;
942    case Instruction::Sub:
943      if (CI2->equalsInt(0)) return C1;                         // X - 0 == X
944      break;
945    case Instruction::Mul:
946      if (CI2->equalsInt(0)) return C2;                         // X * 0 == 0
947      if (CI2->equalsInt(1))
948        return C1;                                              // X * 1 == X
949      break;
950    case Instruction::UDiv:
951    case Instruction::SDiv:
952      if (CI2->equalsInt(1))
953        return C1;                                            // X / 1 == X
954      if (CI2->equalsInt(0))
955        return UndefValue::get(CI2->getType());               // X / 0 == undef
956      break;
957    case Instruction::URem:
958    case Instruction::SRem:
959      if (CI2->equalsInt(1))
960        return Constant::getNullValue(CI2->getType());        // X % 1 == 0
961      if (CI2->equalsInt(0))
962        return UndefValue::get(CI2->getType());               // X % 0 == undef
963      break;
964    case Instruction::And:
965      if (CI2->isZero()) return C2;                           // X & 0 == 0
966      if (CI2->isAllOnesValue())
967        return C1;                                            // X & -1 == X
968
969      if (ConstantExpr *CE1 = dyn_cast<ConstantExpr>(C1)) {
970        // (zext i32 to i64) & 4294967295 -> (zext i32 to i64)
971        if (CE1->getOpcode() == Instruction::ZExt) {
972          unsigned DstWidth = CI2->getType()->getBitWidth();
973          unsigned SrcWidth =
974            CE1->getOperand(0)->getType()->getPrimitiveSizeInBits();
975          APInt PossiblySetBits(APInt::getLowBitsSet(DstWidth, SrcWidth));
976          if ((PossiblySetBits & CI2->getValue()) == PossiblySetBits)
977            return C1;
978        }
979
980        // If and'ing the address of a global with a constant, fold it.
981        if (CE1->getOpcode() == Instruction::PtrToInt &&
982            isa<GlobalValue>(CE1->getOperand(0))) {
983          GlobalValue *GV = cast<GlobalValue>(CE1->getOperand(0));
984
985          // Functions are at least 4-byte aligned.
986          unsigned GVAlign = GV->getAlignment();
987          if (isa<Function>(GV))
988            GVAlign = std::max(GVAlign, 4U);
989
990          if (GVAlign > 1) {
991            unsigned DstWidth = CI2->getType()->getBitWidth();
992            unsigned SrcWidth = std::min(DstWidth, Log2_32(GVAlign));
993            APInt BitsNotSet(APInt::getLowBitsSet(DstWidth, SrcWidth));
994
995            // If checking bits we know are clear, return zero.
996            if ((CI2->getValue() & BitsNotSet) == CI2->getValue())
997              return Constant::getNullValue(CI2->getType());
998          }
999        }
1000      }
1001      break;
1002    case Instruction::Or:
1003      if (CI2->equalsInt(0)) return C1;    // X | 0 == X
1004      if (CI2->isAllOnesValue())
1005        return C2;                         // X | -1 == -1
1006      break;
1007    case Instruction::Xor:
1008      if (CI2->equalsInt(0)) return C1;    // X ^ 0 == X
1009
1010      if (ConstantExpr *CE1 = dyn_cast<ConstantExpr>(C1)) {
1011        switch (CE1->getOpcode()) {
1012        default: break;
1013        case Instruction::ICmp:
1014        case Instruction::FCmp:
1015          // cmp pred ^ true -> cmp !pred
1016          assert(CI2->equalsInt(1));
1017          CmpInst::Predicate pred = (CmpInst::Predicate)CE1->getPredicate();
1018          pred = CmpInst::getInversePredicate(pred);
1019          return ConstantExpr::getCompare(pred, CE1->getOperand(0),
1020                                          CE1->getOperand(1));
1021        }
1022      }
1023      break;
1024    case Instruction::AShr:
1025      // ashr (zext C to Ty), C2 -> lshr (zext C, CSA), C2
1026      if (ConstantExpr *CE1 = dyn_cast<ConstantExpr>(C1))
1027        if (CE1->getOpcode() == Instruction::ZExt)  // Top bits known zero.
1028          return ConstantExpr::getLShr(C1, C2);
1029      break;
1030    }
1031  } else if (isa<ConstantInt>(C1)) {
1032    // If C1 is a ConstantInt and C2 is not, swap the operands.
1033    if (Instruction::isCommutative(Opcode))
1034      return ConstantExpr::get(Opcode, C2, C1);
1035  }
1036
1037  // At this point we know neither constant is an UndefValue.
1038  if (ConstantInt *CI1 = dyn_cast<ConstantInt>(C1)) {
1039    if (ConstantInt *CI2 = dyn_cast<ConstantInt>(C2)) {
1040      const APInt &C1V = CI1->getValue();
1041      const APInt &C2V = CI2->getValue();
1042      switch (Opcode) {
1043      default:
1044        break;
1045      case Instruction::Add:
1046        return ConstantInt::get(CI1->getContext(), C1V + C2V);
1047      case Instruction::Sub:
1048        return ConstantInt::get(CI1->getContext(), C1V - C2V);
1049      case Instruction::Mul:
1050        return ConstantInt::get(CI1->getContext(), C1V * C2V);
1051      case Instruction::UDiv:
1052        assert(!CI2->isNullValue() && "Div by zero handled above");
1053        return ConstantInt::get(CI1->getContext(), C1V.udiv(C2V));
1054      case Instruction::SDiv:
1055        assert(!CI2->isNullValue() && "Div by zero handled above");
1056        if (C2V.isAllOnesValue() && C1V.isMinSignedValue())
1057          return UndefValue::get(CI1->getType());   // MIN_INT / -1 -> undef
1058        return ConstantInt::get(CI1->getContext(), C1V.sdiv(C2V));
1059      case Instruction::URem:
1060        assert(!CI2->isNullValue() && "Div by zero handled above");
1061        return ConstantInt::get(CI1->getContext(), C1V.urem(C2V));
1062      case Instruction::SRem:
1063        assert(!CI2->isNullValue() && "Div by zero handled above");
1064        if (C2V.isAllOnesValue() && C1V.isMinSignedValue())
1065          return UndefValue::get(CI1->getType());   // MIN_INT % -1 -> undef
1066        return ConstantInt::get(CI1->getContext(), C1V.srem(C2V));
1067      case Instruction::And:
1068        return ConstantInt::get(CI1->getContext(), C1V & C2V);
1069      case Instruction::Or:
1070        return ConstantInt::get(CI1->getContext(), C1V | C2V);
1071      case Instruction::Xor:
1072        return ConstantInt::get(CI1->getContext(), C1V ^ C2V);
1073      case Instruction::Shl: {
1074        uint32_t shiftAmt = C2V.getZExtValue();
1075        if (shiftAmt < C1V.getBitWidth())
1076          return ConstantInt::get(CI1->getContext(), C1V.shl(shiftAmt));
1077        else
1078          return UndefValue::get(C1->getType()); // too big shift is undef
1079      }
1080      case Instruction::LShr: {
1081        uint32_t shiftAmt = C2V.getZExtValue();
1082        if (shiftAmt < C1V.getBitWidth())
1083          return ConstantInt::get(CI1->getContext(), C1V.lshr(shiftAmt));
1084        else
1085          return UndefValue::get(C1->getType()); // too big shift is undef
1086      }
1087      case Instruction::AShr: {
1088        uint32_t shiftAmt = C2V.getZExtValue();
1089        if (shiftAmt < C1V.getBitWidth())
1090          return ConstantInt::get(CI1->getContext(), C1V.ashr(shiftAmt));
1091        else
1092          return UndefValue::get(C1->getType()); // too big shift is undef
1093      }
1094      }
1095    }
1096
1097    switch (Opcode) {
1098    case Instruction::SDiv:
1099    case Instruction::UDiv:
1100    case Instruction::URem:
1101    case Instruction::SRem:
1102    case Instruction::LShr:
1103    case Instruction::AShr:
1104    case Instruction::Shl:
1105      if (CI1->equalsInt(0)) return C1;
1106      break;
1107    default:
1108      break;
1109    }
1110  } else if (ConstantFP *CFP1 = dyn_cast<ConstantFP>(C1)) {
1111    if (ConstantFP *CFP2 = dyn_cast<ConstantFP>(C2)) {
1112      APFloat C1V = CFP1->getValueAPF();
1113      APFloat C2V = CFP2->getValueAPF();
1114      APFloat C3V = C1V;  // copy for modification
1115      switch (Opcode) {
1116      default:
1117        break;
1118      case Instruction::FAdd:
1119        (void)C3V.add(C2V, APFloat::rmNearestTiesToEven);
1120        return ConstantFP::get(C1->getContext(), C3V);
1121      case Instruction::FSub:
1122        (void)C3V.subtract(C2V, APFloat::rmNearestTiesToEven);
1123        return ConstantFP::get(C1->getContext(), C3V);
1124      case Instruction::FMul:
1125        (void)C3V.multiply(C2V, APFloat::rmNearestTiesToEven);
1126        return ConstantFP::get(C1->getContext(), C3V);
1127      case Instruction::FDiv:
1128        (void)C3V.divide(C2V, APFloat::rmNearestTiesToEven);
1129        return ConstantFP::get(C1->getContext(), C3V);
1130      case Instruction::FRem:
1131        (void)C3V.mod(C2V, APFloat::rmNearestTiesToEven);
1132        return ConstantFP::get(C1->getContext(), C3V);
1133      }
1134    }
1135  } else if (VectorType *VTy = dyn_cast<VectorType>(C1->getType())) {
1136    // Perform elementwise folding.
1137    SmallVector<Constant*, 16> Result;
1138    Type *Ty = IntegerType::get(VTy->getContext(), 32);
1139    for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
1140      Constant *LHS =
1141        ConstantExpr::getExtractElement(C1, ConstantInt::get(Ty, i));
1142      Constant *RHS =
1143        ConstantExpr::getExtractElement(C2, ConstantInt::get(Ty, i));
1144
1145      Result.push_back(ConstantExpr::get(Opcode, LHS, RHS));
1146    }
1147
1148    return ConstantVector::get(Result);
1149  }
1150
1151  if (ConstantExpr *CE1 = dyn_cast<ConstantExpr>(C1)) {
1152    // There are many possible foldings we could do here.  We should probably
1153    // at least fold add of a pointer with an integer into the appropriate
1154    // getelementptr.  This will improve alias analysis a bit.
1155
1156    // Given ((a + b) + c), if (b + c) folds to something interesting, return
1157    // (a + (b + c)).
1158    if (Instruction::isAssociative(Opcode) && CE1->getOpcode() == Opcode) {
1159      Constant *T = ConstantExpr::get(Opcode, CE1->getOperand(1), C2);
1160      if (!isa<ConstantExpr>(T) || cast<ConstantExpr>(T)->getOpcode() != Opcode)
1161        return ConstantExpr::get(Opcode, CE1->getOperand(0), T);
1162    }
1163  } else if (isa<ConstantExpr>(C2)) {
1164    // If C2 is a constant expr and C1 isn't, flop them around and fold the
1165    // other way if possible.
1166    if (Instruction::isCommutative(Opcode))
1167      return ConstantFoldBinaryInstruction(Opcode, C2, C1);
1168  }
1169
1170  // i1 can be simplified in many cases.
1171  if (C1->getType()->isIntegerTy(1)) {
1172    switch (Opcode) {
1173    case Instruction::Add:
1174    case Instruction::Sub:
1175      return ConstantExpr::getXor(C1, C2);
1176    case Instruction::Mul:
1177      return ConstantExpr::getAnd(C1, C2);
1178    case Instruction::Shl:
1179    case Instruction::LShr:
1180    case Instruction::AShr:
1181      // We can assume that C2 == 0.  If it were one the result would be
1182      // undefined because the shift value is as large as the bitwidth.
1183      return C1;
1184    case Instruction::SDiv:
1185    case Instruction::UDiv:
1186      // We can assume that C2 == 1.  If it were zero the result would be
1187      // undefined through division by zero.
1188      return C1;
1189    case Instruction::URem:
1190    case Instruction::SRem:
1191      // We can assume that C2 == 1.  If it were zero the result would be
1192      // undefined through division by zero.
1193      return ConstantInt::getFalse(C1->getContext());
1194    default:
1195      break;
1196    }
1197  }
1198
1199  // We don't know how to fold this.
1200  return 0;
1201}
1202
1203/// isZeroSizedType - This type is zero sized if its an array or structure of
1204/// zero sized types.  The only leaf zero sized type is an empty structure.
1205static bool isMaybeZeroSizedType(Type *Ty) {
1206  if (StructType *STy = dyn_cast<StructType>(Ty)) {
1207    if (STy->isOpaque()) return true;  // Can't say.
1208
1209    // If all of elements have zero size, this does too.
1210    for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
1211      if (!isMaybeZeroSizedType(STy->getElementType(i))) return false;
1212    return true;
1213
1214  } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1215    return isMaybeZeroSizedType(ATy->getElementType());
1216  }
1217  return false;
1218}
1219
1220/// IdxCompare - Compare the two constants as though they were getelementptr
1221/// indices.  This allows coersion of the types to be the same thing.
1222///
1223/// If the two constants are the "same" (after coersion), return 0.  If the
1224/// first is less than the second, return -1, if the second is less than the
1225/// first, return 1.  If the constants are not integral, return -2.
1226///
1227static int IdxCompare(Constant *C1, Constant *C2, Type *ElTy) {
1228  if (C1 == C2) return 0;
1229
1230  // Ok, we found a different index.  If they are not ConstantInt, we can't do
1231  // anything with them.
1232  if (!isa<ConstantInt>(C1) || !isa<ConstantInt>(C2))
1233    return -2; // don't know!
1234
1235  // Ok, we have two differing integer indices.  Sign extend them to be the same
1236  // type.  Long is always big enough, so we use it.
1237  if (!C1->getType()->isIntegerTy(64))
1238    C1 = ConstantExpr::getSExt(C1, Type::getInt64Ty(C1->getContext()));
1239
1240  if (!C2->getType()->isIntegerTy(64))
1241    C2 = ConstantExpr::getSExt(C2, Type::getInt64Ty(C1->getContext()));
1242
1243  if (C1 == C2) return 0;  // They are equal
1244
1245  // If the type being indexed over is really just a zero sized type, there is
1246  // no pointer difference being made here.
1247  if (isMaybeZeroSizedType(ElTy))
1248    return -2; // dunno.
1249
1250  // If they are really different, now that they are the same type, then we
1251  // found a difference!
1252  if (cast<ConstantInt>(C1)->getSExtValue() <
1253      cast<ConstantInt>(C2)->getSExtValue())
1254    return -1;
1255  else
1256    return 1;
1257}
1258
1259/// evaluateFCmpRelation - This function determines if there is anything we can
1260/// decide about the two constants provided.  This doesn't need to handle simple
1261/// things like ConstantFP comparisons, but should instead handle ConstantExprs.
1262/// If we can determine that the two constants have a particular relation to
1263/// each other, we should return the corresponding FCmpInst predicate,
1264/// otherwise return FCmpInst::BAD_FCMP_PREDICATE. This is used below in
1265/// ConstantFoldCompareInstruction.
1266///
1267/// To simplify this code we canonicalize the relation so that the first
1268/// operand is always the most "complex" of the two.  We consider ConstantFP
1269/// to be the simplest, and ConstantExprs to be the most complex.
1270static FCmpInst::Predicate evaluateFCmpRelation(Constant *V1, Constant *V2) {
1271  assert(V1->getType() == V2->getType() &&
1272         "Cannot compare values of different types!");
1273
1274  // Handle degenerate case quickly
1275  if (V1 == V2) return FCmpInst::FCMP_OEQ;
1276
1277  if (!isa<ConstantExpr>(V1)) {
1278    if (!isa<ConstantExpr>(V2)) {
1279      // We distilled thisUse the standard constant folder for a few cases
1280      ConstantInt *R = 0;
1281      R = dyn_cast<ConstantInt>(
1282                      ConstantExpr::getFCmp(FCmpInst::FCMP_OEQ, V1, V2));
1283      if (R && !R->isZero())
1284        return FCmpInst::FCMP_OEQ;
1285      R = dyn_cast<ConstantInt>(
1286                      ConstantExpr::getFCmp(FCmpInst::FCMP_OLT, V1, V2));
1287      if (R && !R->isZero())
1288        return FCmpInst::FCMP_OLT;
1289      R = dyn_cast<ConstantInt>(
1290                      ConstantExpr::getFCmp(FCmpInst::FCMP_OGT, V1, V2));
1291      if (R && !R->isZero())
1292        return FCmpInst::FCMP_OGT;
1293
1294      // Nothing more we can do
1295      return FCmpInst::BAD_FCMP_PREDICATE;
1296    }
1297
1298    // If the first operand is simple and second is ConstantExpr, swap operands.
1299    FCmpInst::Predicate SwappedRelation = evaluateFCmpRelation(V2, V1);
1300    if (SwappedRelation != FCmpInst::BAD_FCMP_PREDICATE)
1301      return FCmpInst::getSwappedPredicate(SwappedRelation);
1302  } else {
1303    // Ok, the LHS is known to be a constantexpr.  The RHS can be any of a
1304    // constantexpr or a simple constant.
1305    ConstantExpr *CE1 = cast<ConstantExpr>(V1);
1306    switch (CE1->getOpcode()) {
1307    case Instruction::FPTrunc:
1308    case Instruction::FPExt:
1309    case Instruction::UIToFP:
1310    case Instruction::SIToFP:
1311      // We might be able to do something with these but we don't right now.
1312      break;
1313    default:
1314      break;
1315    }
1316  }
1317  // There are MANY other foldings that we could perform here.  They will
1318  // probably be added on demand, as they seem needed.
1319  return FCmpInst::BAD_FCMP_PREDICATE;
1320}
1321
1322/// evaluateICmpRelation - This function determines if there is anything we can
1323/// decide about the two constants provided.  This doesn't need to handle simple
1324/// things like integer comparisons, but should instead handle ConstantExprs
1325/// and GlobalValues.  If we can determine that the two constants have a
1326/// particular relation to each other, we should return the corresponding ICmp
1327/// predicate, otherwise return ICmpInst::BAD_ICMP_PREDICATE.
1328///
1329/// To simplify this code we canonicalize the relation so that the first
1330/// operand is always the most "complex" of the two.  We consider simple
1331/// constants (like ConstantInt) to be the simplest, followed by
1332/// GlobalValues, followed by ConstantExpr's (the most complex).
1333///
1334static ICmpInst::Predicate evaluateICmpRelation(Constant *V1, Constant *V2,
1335                                                bool isSigned) {
1336  assert(V1->getType() == V2->getType() &&
1337         "Cannot compare different types of values!");
1338  if (V1 == V2) return ICmpInst::ICMP_EQ;
1339
1340  if (!isa<ConstantExpr>(V1) && !isa<GlobalValue>(V1) &&
1341      !isa<BlockAddress>(V1)) {
1342    if (!isa<GlobalValue>(V2) && !isa<ConstantExpr>(V2) &&
1343        !isa<BlockAddress>(V2)) {
1344      // We distilled this down to a simple case, use the standard constant
1345      // folder.
1346      ConstantInt *R = 0;
1347      ICmpInst::Predicate pred = ICmpInst::ICMP_EQ;
1348      R = dyn_cast<ConstantInt>(ConstantExpr::getICmp(pred, V1, V2));
1349      if (R && !R->isZero())
1350        return pred;
1351      pred = isSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT;
1352      R = dyn_cast<ConstantInt>(ConstantExpr::getICmp(pred, V1, V2));
1353      if (R && !R->isZero())
1354        return pred;
1355      pred = isSigned ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
1356      R = dyn_cast<ConstantInt>(ConstantExpr::getICmp(pred, V1, V2));
1357      if (R && !R->isZero())
1358        return pred;
1359
1360      // If we couldn't figure it out, bail.
1361      return ICmpInst::BAD_ICMP_PREDICATE;
1362    }
1363
1364    // If the first operand is simple, swap operands.
1365    ICmpInst::Predicate SwappedRelation =
1366      evaluateICmpRelation(V2, V1, isSigned);
1367    if (SwappedRelation != ICmpInst::BAD_ICMP_PREDICATE)
1368      return ICmpInst::getSwappedPredicate(SwappedRelation);
1369
1370  } else if (const GlobalValue *GV = dyn_cast<GlobalValue>(V1)) {
1371    if (isa<ConstantExpr>(V2)) {  // Swap as necessary.
1372      ICmpInst::Predicate SwappedRelation =
1373        evaluateICmpRelation(V2, V1, isSigned);
1374      if (SwappedRelation != ICmpInst::BAD_ICMP_PREDICATE)
1375        return ICmpInst::getSwappedPredicate(SwappedRelation);
1376      return ICmpInst::BAD_ICMP_PREDICATE;
1377    }
1378
1379    // Now we know that the RHS is a GlobalValue, BlockAddress or simple
1380    // constant (which, since the types must match, means that it's a
1381    // ConstantPointerNull).
1382    if (const GlobalValue *GV2 = dyn_cast<GlobalValue>(V2)) {
1383      // Don't try to decide equality of aliases.
1384      if (!isa<GlobalAlias>(GV) && !isa<GlobalAlias>(GV2))
1385        if (!GV->hasExternalWeakLinkage() || !GV2->hasExternalWeakLinkage())
1386          return ICmpInst::ICMP_NE;
1387    } else if (isa<BlockAddress>(V2)) {
1388      return ICmpInst::ICMP_NE; // Globals never equal labels.
1389    } else {
1390      assert(isa<ConstantPointerNull>(V2) && "Canonicalization guarantee!");
1391      // GlobalVals can never be null unless they have external weak linkage.
1392      // We don't try to evaluate aliases here.
1393      if (!GV->hasExternalWeakLinkage() && !isa<GlobalAlias>(GV))
1394        return ICmpInst::ICMP_NE;
1395    }
1396  } else if (const BlockAddress *BA = dyn_cast<BlockAddress>(V1)) {
1397    if (isa<ConstantExpr>(V2)) {  // Swap as necessary.
1398      ICmpInst::Predicate SwappedRelation =
1399        evaluateICmpRelation(V2, V1, isSigned);
1400      if (SwappedRelation != ICmpInst::BAD_ICMP_PREDICATE)
1401        return ICmpInst::getSwappedPredicate(SwappedRelation);
1402      return ICmpInst::BAD_ICMP_PREDICATE;
1403    }
1404
1405    // Now we know that the RHS is a GlobalValue, BlockAddress or simple
1406    // constant (which, since the types must match, means that it is a
1407    // ConstantPointerNull).
1408    if (const BlockAddress *BA2 = dyn_cast<BlockAddress>(V2)) {
1409      // Block address in another function can't equal this one, but block
1410      // addresses in the current function might be the same if blocks are
1411      // empty.
1412      if (BA2->getFunction() != BA->getFunction())
1413        return ICmpInst::ICMP_NE;
1414    } else {
1415      // Block addresses aren't null, don't equal the address of globals.
1416      assert((isa<ConstantPointerNull>(V2) || isa<GlobalValue>(V2)) &&
1417             "Canonicalization guarantee!");
1418      return ICmpInst::ICMP_NE;
1419    }
1420  } else {
1421    // Ok, the LHS is known to be a constantexpr.  The RHS can be any of a
1422    // constantexpr, a global, block address, or a simple constant.
1423    ConstantExpr *CE1 = cast<ConstantExpr>(V1);
1424    Constant *CE1Op0 = CE1->getOperand(0);
1425
1426    switch (CE1->getOpcode()) {
1427    case Instruction::Trunc:
1428    case Instruction::FPTrunc:
1429    case Instruction::FPExt:
1430    case Instruction::FPToUI:
1431    case Instruction::FPToSI:
1432      break; // We can't evaluate floating point casts or truncations.
1433
1434    case Instruction::UIToFP:
1435    case Instruction::SIToFP:
1436    case Instruction::BitCast:
1437    case Instruction::ZExt:
1438    case Instruction::SExt:
1439      // If the cast is not actually changing bits, and the second operand is a
1440      // null pointer, do the comparison with the pre-casted value.
1441      if (V2->isNullValue() &&
1442          (CE1->getType()->isPointerTy() || CE1->getType()->isIntegerTy())) {
1443        if (CE1->getOpcode() == Instruction::ZExt) isSigned = false;
1444        if (CE1->getOpcode() == Instruction::SExt) isSigned = true;
1445        return evaluateICmpRelation(CE1Op0,
1446                                    Constant::getNullValue(CE1Op0->getType()),
1447                                    isSigned);
1448      }
1449      break;
1450
1451    case Instruction::GetElementPtr:
1452      // Ok, since this is a getelementptr, we know that the constant has a
1453      // pointer type.  Check the various cases.
1454      if (isa<ConstantPointerNull>(V2)) {
1455        // If we are comparing a GEP to a null pointer, check to see if the base
1456        // of the GEP equals the null pointer.
1457        if (const GlobalValue *GV = dyn_cast<GlobalValue>(CE1Op0)) {
1458          if (GV->hasExternalWeakLinkage())
1459            // Weak linkage GVals could be zero or not. We're comparing that
1460            // to null pointer so its greater-or-equal
1461            return isSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE;
1462          else
1463            // If its not weak linkage, the GVal must have a non-zero address
1464            // so the result is greater-than
1465            return isSigned ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
1466        } else if (isa<ConstantPointerNull>(CE1Op0)) {
1467          // If we are indexing from a null pointer, check to see if we have any
1468          // non-zero indices.
1469          for (unsigned i = 1, e = CE1->getNumOperands(); i != e; ++i)
1470            if (!CE1->getOperand(i)->isNullValue())
1471              // Offsetting from null, must not be equal.
1472              return isSigned ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
1473          // Only zero indexes from null, must still be zero.
1474          return ICmpInst::ICMP_EQ;
1475        }
1476        // Otherwise, we can't really say if the first operand is null or not.
1477      } else if (const GlobalValue *GV2 = dyn_cast<GlobalValue>(V2)) {
1478        if (isa<ConstantPointerNull>(CE1Op0)) {
1479          if (GV2->hasExternalWeakLinkage())
1480            // Weak linkage GVals could be zero or not. We're comparing it to
1481            // a null pointer, so its less-or-equal
1482            return isSigned ? ICmpInst::ICMP_SLE : ICmpInst::ICMP_ULE;
1483          else
1484            // If its not weak linkage, the GVal must have a non-zero address
1485            // so the result is less-than
1486            return isSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT;
1487        } else if (const GlobalValue *GV = dyn_cast<GlobalValue>(CE1Op0)) {
1488          if (GV == GV2) {
1489            // If this is a getelementptr of the same global, then it must be
1490            // different.  Because the types must match, the getelementptr could
1491            // only have at most one index, and because we fold getelementptr's
1492            // with a single zero index, it must be nonzero.
1493            assert(CE1->getNumOperands() == 2 &&
1494                   !CE1->getOperand(1)->isNullValue() &&
1495                   "Surprising getelementptr!");
1496            return isSigned ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
1497          } else {
1498            // If they are different globals, we don't know what the value is.
1499            return ICmpInst::BAD_ICMP_PREDICATE;
1500          }
1501        }
1502      } else {
1503        ConstantExpr *CE2 = cast<ConstantExpr>(V2);
1504        Constant *CE2Op0 = CE2->getOperand(0);
1505
1506        // There are MANY other foldings that we could perform here.  They will
1507        // probably be added on demand, as they seem needed.
1508        switch (CE2->getOpcode()) {
1509        default: break;
1510        case Instruction::GetElementPtr:
1511          // By far the most common case to handle is when the base pointers are
1512          // obviously to the same global.
1513          if (isa<GlobalValue>(CE1Op0) && isa<GlobalValue>(CE2Op0)) {
1514            if (CE1Op0 != CE2Op0) // Don't know relative ordering.
1515              return ICmpInst::BAD_ICMP_PREDICATE;
1516            // Ok, we know that both getelementptr instructions are based on the
1517            // same global.  From this, we can precisely determine the relative
1518            // ordering of the resultant pointers.
1519            unsigned i = 1;
1520
1521            // The logic below assumes that the result of the comparison
1522            // can be determined by finding the first index that differs.
1523            // This doesn't work if there is over-indexing in any
1524            // subsequent indices, so check for that case first.
1525            if (!CE1->isGEPWithNoNotionalOverIndexing() ||
1526                !CE2->isGEPWithNoNotionalOverIndexing())
1527               return ICmpInst::BAD_ICMP_PREDICATE; // Might be equal.
1528
1529            // Compare all of the operands the GEP's have in common.
1530            gep_type_iterator GTI = gep_type_begin(CE1);
1531            for (;i != CE1->getNumOperands() && i != CE2->getNumOperands();
1532                 ++i, ++GTI)
1533              switch (IdxCompare(CE1->getOperand(i),
1534                                 CE2->getOperand(i), GTI.getIndexedType())) {
1535              case -1: return isSigned ? ICmpInst::ICMP_SLT:ICmpInst::ICMP_ULT;
1536              case 1:  return isSigned ? ICmpInst::ICMP_SGT:ICmpInst::ICMP_UGT;
1537              case -2: return ICmpInst::BAD_ICMP_PREDICATE;
1538              }
1539
1540            // Ok, we ran out of things they have in common.  If any leftovers
1541            // are non-zero then we have a difference, otherwise we are equal.
1542            for (; i < CE1->getNumOperands(); ++i)
1543              if (!CE1->getOperand(i)->isNullValue()) {
1544                if (isa<ConstantInt>(CE1->getOperand(i)))
1545                  return isSigned ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
1546                else
1547                  return ICmpInst::BAD_ICMP_PREDICATE; // Might be equal.
1548              }
1549
1550            for (; i < CE2->getNumOperands(); ++i)
1551              if (!CE2->getOperand(i)->isNullValue()) {
1552                if (isa<ConstantInt>(CE2->getOperand(i)))
1553                  return isSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT;
1554                else
1555                  return ICmpInst::BAD_ICMP_PREDICATE; // Might be equal.
1556              }
1557            return ICmpInst::ICMP_EQ;
1558          }
1559        }
1560      }
1561    default:
1562      break;
1563    }
1564  }
1565
1566  return ICmpInst::BAD_ICMP_PREDICATE;
1567}
1568
1569Constant *llvm::ConstantFoldCompareInstruction(unsigned short pred,
1570                                               Constant *C1, Constant *C2) {
1571  Type *ResultTy;
1572  if (VectorType *VT = dyn_cast<VectorType>(C1->getType()))
1573    ResultTy = VectorType::get(Type::getInt1Ty(C1->getContext()),
1574                               VT->getNumElements());
1575  else
1576    ResultTy = Type::getInt1Ty(C1->getContext());
1577
1578  // Fold FCMP_FALSE/FCMP_TRUE unconditionally.
1579  if (pred == FCmpInst::FCMP_FALSE)
1580    return Constant::getNullValue(ResultTy);
1581
1582  if (pred == FCmpInst::FCMP_TRUE)
1583    return Constant::getAllOnesValue(ResultTy);
1584
1585  // Handle some degenerate cases first
1586  if (isa<UndefValue>(C1) || isa<UndefValue>(C2)) {
1587    // For EQ and NE, we can always pick a value for the undef to make the
1588    // predicate pass or fail, so we can return undef.
1589    // Also, if both operands are undef, we can return undef.
1590    if (ICmpInst::isEquality(ICmpInst::Predicate(pred)) ||
1591        (isa<UndefValue>(C1) && isa<UndefValue>(C2)))
1592      return UndefValue::get(ResultTy);
1593    // Otherwise, pick the same value as the non-undef operand, and fold
1594    // it to true or false.
1595    return ConstantInt::get(ResultTy, CmpInst::isTrueWhenEqual(pred));
1596  }
1597
1598  // icmp eq/ne(null,GV) -> false/true
1599  if (C1->isNullValue()) {
1600    if (const GlobalValue *GV = dyn_cast<GlobalValue>(C2))
1601      // Don't try to evaluate aliases.  External weak GV can be null.
1602      if (!isa<GlobalAlias>(GV) && !GV->hasExternalWeakLinkage()) {
1603        if (pred == ICmpInst::ICMP_EQ)
1604          return ConstantInt::getFalse(C1->getContext());
1605        else if (pred == ICmpInst::ICMP_NE)
1606          return ConstantInt::getTrue(C1->getContext());
1607      }
1608  // icmp eq/ne(GV,null) -> false/true
1609  } else if (C2->isNullValue()) {
1610    if (const GlobalValue *GV = dyn_cast<GlobalValue>(C1))
1611      // Don't try to evaluate aliases.  External weak GV can be null.
1612      if (!isa<GlobalAlias>(GV) && !GV->hasExternalWeakLinkage()) {
1613        if (pred == ICmpInst::ICMP_EQ)
1614          return ConstantInt::getFalse(C1->getContext());
1615        else if (pred == ICmpInst::ICMP_NE)
1616          return ConstantInt::getTrue(C1->getContext());
1617      }
1618  }
1619
1620  // If the comparison is a comparison between two i1's, simplify it.
1621  if (C1->getType()->isIntegerTy(1)) {
1622    switch(pred) {
1623    case ICmpInst::ICMP_EQ:
1624      if (isa<ConstantInt>(C2))
1625        return ConstantExpr::getXor(C1, ConstantExpr::getNot(C2));
1626      return ConstantExpr::getXor(ConstantExpr::getNot(C1), C2);
1627    case ICmpInst::ICMP_NE:
1628      return ConstantExpr::getXor(C1, C2);
1629    default:
1630      break;
1631    }
1632  }
1633
1634  if (isa<ConstantInt>(C1) && isa<ConstantInt>(C2)) {
1635    APInt V1 = cast<ConstantInt>(C1)->getValue();
1636    APInt V2 = cast<ConstantInt>(C2)->getValue();
1637    switch (pred) {
1638    default: llvm_unreachable("Invalid ICmp Predicate");
1639    case ICmpInst::ICMP_EQ:  return ConstantInt::get(ResultTy, V1 == V2);
1640    case ICmpInst::ICMP_NE:  return ConstantInt::get(ResultTy, V1 != V2);
1641    case ICmpInst::ICMP_SLT: return ConstantInt::get(ResultTy, V1.slt(V2));
1642    case ICmpInst::ICMP_SGT: return ConstantInt::get(ResultTy, V1.sgt(V2));
1643    case ICmpInst::ICMP_SLE: return ConstantInt::get(ResultTy, V1.sle(V2));
1644    case ICmpInst::ICMP_SGE: return ConstantInt::get(ResultTy, V1.sge(V2));
1645    case ICmpInst::ICMP_ULT: return ConstantInt::get(ResultTy, V1.ult(V2));
1646    case ICmpInst::ICMP_UGT: return ConstantInt::get(ResultTy, V1.ugt(V2));
1647    case ICmpInst::ICMP_ULE: return ConstantInt::get(ResultTy, V1.ule(V2));
1648    case ICmpInst::ICMP_UGE: return ConstantInt::get(ResultTy, V1.uge(V2));
1649    }
1650  } else if (isa<ConstantFP>(C1) && isa<ConstantFP>(C2)) {
1651    APFloat C1V = cast<ConstantFP>(C1)->getValueAPF();
1652    APFloat C2V = cast<ConstantFP>(C2)->getValueAPF();
1653    APFloat::cmpResult R = C1V.compare(C2V);
1654    switch (pred) {
1655    default: llvm_unreachable("Invalid FCmp Predicate");
1656    case FCmpInst::FCMP_FALSE: return Constant::getNullValue(ResultTy);
1657    case FCmpInst::FCMP_TRUE:  return Constant::getAllOnesValue(ResultTy);
1658    case FCmpInst::FCMP_UNO:
1659      return ConstantInt::get(ResultTy, R==APFloat::cmpUnordered);
1660    case FCmpInst::FCMP_ORD:
1661      return ConstantInt::get(ResultTy, R!=APFloat::cmpUnordered);
1662    case FCmpInst::FCMP_UEQ:
1663      return ConstantInt::get(ResultTy, R==APFloat::cmpUnordered ||
1664                                        R==APFloat::cmpEqual);
1665    case FCmpInst::FCMP_OEQ:
1666      return ConstantInt::get(ResultTy, R==APFloat::cmpEqual);
1667    case FCmpInst::FCMP_UNE:
1668      return ConstantInt::get(ResultTy, R!=APFloat::cmpEqual);
1669    case FCmpInst::FCMP_ONE:
1670      return ConstantInt::get(ResultTy, R==APFloat::cmpLessThan ||
1671                                        R==APFloat::cmpGreaterThan);
1672    case FCmpInst::FCMP_ULT:
1673      return ConstantInt::get(ResultTy, R==APFloat::cmpUnordered ||
1674                                        R==APFloat::cmpLessThan);
1675    case FCmpInst::FCMP_OLT:
1676      return ConstantInt::get(ResultTy, R==APFloat::cmpLessThan);
1677    case FCmpInst::FCMP_UGT:
1678      return ConstantInt::get(ResultTy, R==APFloat::cmpUnordered ||
1679                                        R==APFloat::cmpGreaterThan);
1680    case FCmpInst::FCMP_OGT:
1681      return ConstantInt::get(ResultTy, R==APFloat::cmpGreaterThan);
1682    case FCmpInst::FCMP_ULE:
1683      return ConstantInt::get(ResultTy, R!=APFloat::cmpGreaterThan);
1684    case FCmpInst::FCMP_OLE:
1685      return ConstantInt::get(ResultTy, R==APFloat::cmpLessThan ||
1686                                        R==APFloat::cmpEqual);
1687    case FCmpInst::FCMP_UGE:
1688      return ConstantInt::get(ResultTy, R!=APFloat::cmpLessThan);
1689    case FCmpInst::FCMP_OGE:
1690      return ConstantInt::get(ResultTy, R==APFloat::cmpGreaterThan ||
1691                                        R==APFloat::cmpEqual);
1692    }
1693  } else if (C1->getType()->isVectorTy()) {
1694    // If we can constant fold the comparison of each element, constant fold
1695    // the whole vector comparison.
1696    SmallVector<Constant*, 4> ResElts;
1697    Type *Ty = IntegerType::get(C1->getContext(), 32);
1698    // Compare the elements, producing an i1 result or constant expr.
1699    for (unsigned i = 0, e = C1->getType()->getVectorNumElements(); i != e;++i){
1700      Constant *C1E =
1701        ConstantExpr::getExtractElement(C1, ConstantInt::get(Ty, i));
1702      Constant *C2E =
1703        ConstantExpr::getExtractElement(C2, ConstantInt::get(Ty, i));
1704
1705      ResElts.push_back(ConstantExpr::getCompare(pred, C1E, C2E));
1706    }
1707
1708    return ConstantVector::get(ResElts);
1709  }
1710
1711  if (C1->getType()->isFloatingPointTy()) {
1712    int Result = -1;  // -1 = unknown, 0 = known false, 1 = known true.
1713    switch (evaluateFCmpRelation(C1, C2)) {
1714    default: llvm_unreachable("Unknown relation!");
1715    case FCmpInst::FCMP_UNO:
1716    case FCmpInst::FCMP_ORD:
1717    case FCmpInst::FCMP_UEQ:
1718    case FCmpInst::FCMP_UNE:
1719    case FCmpInst::FCMP_ULT:
1720    case FCmpInst::FCMP_UGT:
1721    case FCmpInst::FCMP_ULE:
1722    case FCmpInst::FCMP_UGE:
1723    case FCmpInst::FCMP_TRUE:
1724    case FCmpInst::FCMP_FALSE:
1725    case FCmpInst::BAD_FCMP_PREDICATE:
1726      break; // Couldn't determine anything about these constants.
1727    case FCmpInst::FCMP_OEQ: // We know that C1 == C2
1728      Result = (pred == FCmpInst::FCMP_UEQ || pred == FCmpInst::FCMP_OEQ ||
1729                pred == FCmpInst::FCMP_ULE || pred == FCmpInst::FCMP_OLE ||
1730                pred == FCmpInst::FCMP_UGE || pred == FCmpInst::FCMP_OGE);
1731      break;
1732    case FCmpInst::FCMP_OLT: // We know that C1 < C2
1733      Result = (pred == FCmpInst::FCMP_UNE || pred == FCmpInst::FCMP_ONE ||
1734                pred == FCmpInst::FCMP_ULT || pred == FCmpInst::FCMP_OLT ||
1735                pred == FCmpInst::FCMP_ULE || pred == FCmpInst::FCMP_OLE);
1736      break;
1737    case FCmpInst::FCMP_OGT: // We know that C1 > C2
1738      Result = (pred == FCmpInst::FCMP_UNE || pred == FCmpInst::FCMP_ONE ||
1739                pred == FCmpInst::FCMP_UGT || pred == FCmpInst::FCMP_OGT ||
1740                pred == FCmpInst::FCMP_UGE || pred == FCmpInst::FCMP_OGE);
1741      break;
1742    case FCmpInst::FCMP_OLE: // We know that C1 <= C2
1743      // We can only partially decide this relation.
1744      if (pred == FCmpInst::FCMP_UGT || pred == FCmpInst::FCMP_OGT)
1745        Result = 0;
1746      else if (pred == FCmpInst::FCMP_ULT || pred == FCmpInst::FCMP_OLT)
1747        Result = 1;
1748      break;
1749    case FCmpInst::FCMP_OGE: // We known that C1 >= C2
1750      // We can only partially decide this relation.
1751      if (pred == FCmpInst::FCMP_ULT || pred == FCmpInst::FCMP_OLT)
1752        Result = 0;
1753      else if (pred == FCmpInst::FCMP_UGT || pred == FCmpInst::FCMP_OGT)
1754        Result = 1;
1755      break;
1756    case FCmpInst::FCMP_ONE: // We know that C1 != C2
1757      // We can only partially decide this relation.
1758      if (pred == FCmpInst::FCMP_OEQ || pred == FCmpInst::FCMP_UEQ)
1759        Result = 0;
1760      else if (pred == FCmpInst::FCMP_ONE || pred == FCmpInst::FCMP_UNE)
1761        Result = 1;
1762      break;
1763    }
1764
1765    // If we evaluated the result, return it now.
1766    if (Result != -1)
1767      return ConstantInt::get(ResultTy, Result);
1768
1769  } else {
1770    // Evaluate the relation between the two constants, per the predicate.
1771    int Result = -1;  // -1 = unknown, 0 = known false, 1 = known true.
1772    switch (evaluateICmpRelation(C1, C2, CmpInst::isSigned(pred))) {
1773    default: llvm_unreachable("Unknown relational!");
1774    case ICmpInst::BAD_ICMP_PREDICATE:
1775      break;  // Couldn't determine anything about these constants.
1776    case ICmpInst::ICMP_EQ:   // We know the constants are equal!
1777      // If we know the constants are equal, we can decide the result of this
1778      // computation precisely.
1779      Result = ICmpInst::isTrueWhenEqual((ICmpInst::Predicate)pred);
1780      break;
1781    case ICmpInst::ICMP_ULT:
1782      switch (pred) {
1783      case ICmpInst::ICMP_ULT: case ICmpInst::ICMP_NE: case ICmpInst::ICMP_ULE:
1784        Result = 1; break;
1785      case ICmpInst::ICMP_UGT: case ICmpInst::ICMP_EQ: case ICmpInst::ICMP_UGE:
1786        Result = 0; break;
1787      }
1788      break;
1789    case ICmpInst::ICMP_SLT:
1790      switch (pred) {
1791      case ICmpInst::ICMP_SLT: case ICmpInst::ICMP_NE: case ICmpInst::ICMP_SLE:
1792        Result = 1; break;
1793      case ICmpInst::ICMP_SGT: case ICmpInst::ICMP_EQ: case ICmpInst::ICMP_SGE:
1794        Result = 0; break;
1795      }
1796      break;
1797    case ICmpInst::ICMP_UGT:
1798      switch (pred) {
1799      case ICmpInst::ICMP_UGT: case ICmpInst::ICMP_NE: case ICmpInst::ICMP_UGE:
1800        Result = 1; break;
1801      case ICmpInst::ICMP_ULT: case ICmpInst::ICMP_EQ: case ICmpInst::ICMP_ULE:
1802        Result = 0; break;
1803      }
1804      break;
1805    case ICmpInst::ICMP_SGT:
1806      switch (pred) {
1807      case ICmpInst::ICMP_SGT: case ICmpInst::ICMP_NE: case ICmpInst::ICMP_SGE:
1808        Result = 1; break;
1809      case ICmpInst::ICMP_SLT: case ICmpInst::ICMP_EQ: case ICmpInst::ICMP_SLE:
1810        Result = 0; break;
1811      }
1812      break;
1813    case ICmpInst::ICMP_ULE:
1814      if (pred == ICmpInst::ICMP_UGT) Result = 0;
1815      if (pred == ICmpInst::ICMP_ULT || pred == ICmpInst::ICMP_ULE) Result = 1;
1816      break;
1817    case ICmpInst::ICMP_SLE:
1818      if (pred == ICmpInst::ICMP_SGT) Result = 0;
1819      if (pred == ICmpInst::ICMP_SLT || pred == ICmpInst::ICMP_SLE) Result = 1;
1820      break;
1821    case ICmpInst::ICMP_UGE:
1822      if (pred == ICmpInst::ICMP_ULT) Result = 0;
1823      if (pred == ICmpInst::ICMP_UGT || pred == ICmpInst::ICMP_UGE) Result = 1;
1824      break;
1825    case ICmpInst::ICMP_SGE:
1826      if (pred == ICmpInst::ICMP_SLT) Result = 0;
1827      if (pred == ICmpInst::ICMP_SGT || pred == ICmpInst::ICMP_SGE) Result = 1;
1828      break;
1829    case ICmpInst::ICMP_NE:
1830      if (pred == ICmpInst::ICMP_EQ) Result = 0;
1831      if (pred == ICmpInst::ICMP_NE) Result = 1;
1832      break;
1833    }
1834
1835    // If we evaluated the result, return it now.
1836    if (Result != -1)
1837      return ConstantInt::get(ResultTy, Result);
1838
1839    // If the right hand side is a bitcast, try using its inverse to simplify
1840    // it by moving it to the left hand side.  We can't do this if it would turn
1841    // a vector compare into a scalar compare or visa versa.
1842    if (ConstantExpr *CE2 = dyn_cast<ConstantExpr>(C2)) {
1843      Constant *CE2Op0 = CE2->getOperand(0);
1844      if (CE2->getOpcode() == Instruction::BitCast &&
1845          CE2->getType()->isVectorTy() == CE2Op0->getType()->isVectorTy()) {
1846        Constant *Inverse = ConstantExpr::getBitCast(C1, CE2Op0->getType());
1847        return ConstantExpr::getICmp(pred, Inverse, CE2Op0);
1848      }
1849    }
1850
1851    // If the left hand side is an extension, try eliminating it.
1852    if (ConstantExpr *CE1 = dyn_cast<ConstantExpr>(C1)) {
1853      if ((CE1->getOpcode() == Instruction::SExt && ICmpInst::isSigned(pred)) ||
1854          (CE1->getOpcode() == Instruction::ZExt && !ICmpInst::isSigned(pred))){
1855        Constant *CE1Op0 = CE1->getOperand(0);
1856        Constant *CE1Inverse = ConstantExpr::getTrunc(CE1, CE1Op0->getType());
1857        if (CE1Inverse == CE1Op0) {
1858          // Check whether we can safely truncate the right hand side.
1859          Constant *C2Inverse = ConstantExpr::getTrunc(C2, CE1Op0->getType());
1860          if (ConstantExpr::getZExt(C2Inverse, C2->getType()) == C2) {
1861            return ConstantExpr::getICmp(pred, CE1Inverse, C2Inverse);
1862          }
1863        }
1864      }
1865    }
1866
1867    if ((!isa<ConstantExpr>(C1) && isa<ConstantExpr>(C2)) ||
1868        (C1->isNullValue() && !C2->isNullValue())) {
1869      // If C2 is a constant expr and C1 isn't, flip them around and fold the
1870      // other way if possible.
1871      // Also, if C1 is null and C2 isn't, flip them around.
1872      pred = ICmpInst::getSwappedPredicate((ICmpInst::Predicate)pred);
1873      return ConstantExpr::getICmp(pred, C2, C1);
1874    }
1875  }
1876  return 0;
1877}
1878
1879/// isInBoundsIndices - Test whether the given sequence of *normalized* indices
1880/// is "inbounds".
1881template<typename IndexTy>
1882static bool isInBoundsIndices(ArrayRef<IndexTy> Idxs) {
1883  // No indices means nothing that could be out of bounds.
1884  if (Idxs.empty()) return true;
1885
1886  // If the first index is zero, it's in bounds.
1887  if (cast<Constant>(Idxs[0])->isNullValue()) return true;
1888
1889  // If the first index is one and all the rest are zero, it's in bounds,
1890  // by the one-past-the-end rule.
1891  if (!cast<ConstantInt>(Idxs[0])->isOne())
1892    return false;
1893  for (unsigned i = 1, e = Idxs.size(); i != e; ++i)
1894    if (!cast<Constant>(Idxs[i])->isNullValue())
1895      return false;
1896  return true;
1897}
1898
1899template<typename IndexTy>
1900static Constant *ConstantFoldGetElementPtrImpl(Constant *C,
1901                                               bool inBounds,
1902                                               ArrayRef<IndexTy> Idxs) {
1903  if (Idxs.empty()) return C;
1904  Constant *Idx0 = cast<Constant>(Idxs[0]);
1905  if ((Idxs.size() == 1 && Idx0->isNullValue()))
1906    return C;
1907
1908  if (isa<UndefValue>(C)) {
1909    PointerType *Ptr = cast<PointerType>(C->getType());
1910    Type *Ty = GetElementPtrInst::getIndexedType(Ptr, Idxs);
1911    assert(Ty != 0 && "Invalid indices for GEP!");
1912    return UndefValue::get(PointerType::get(Ty, Ptr->getAddressSpace()));
1913  }
1914
1915  if (C->isNullValue()) {
1916    bool isNull = true;
1917    for (unsigned i = 0, e = Idxs.size(); i != e; ++i)
1918      if (!cast<Constant>(Idxs[i])->isNullValue()) {
1919        isNull = false;
1920        break;
1921      }
1922    if (isNull) {
1923      PointerType *Ptr = cast<PointerType>(C->getType());
1924      Type *Ty = GetElementPtrInst::getIndexedType(Ptr, Idxs);
1925      assert(Ty != 0 && "Invalid indices for GEP!");
1926      return ConstantPointerNull::get(PointerType::get(Ty,
1927                                                       Ptr->getAddressSpace()));
1928    }
1929  }
1930
1931  if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
1932    // Combine Indices - If the source pointer to this getelementptr instruction
1933    // is a getelementptr instruction, combine the indices of the two
1934    // getelementptr instructions into a single instruction.
1935    //
1936    if (CE->getOpcode() == Instruction::GetElementPtr) {
1937      Type *LastTy = 0;
1938      for (gep_type_iterator I = gep_type_begin(CE), E = gep_type_end(CE);
1939           I != E; ++I)
1940        LastTy = *I;
1941
1942      if ((LastTy && isa<SequentialType>(LastTy)) || Idx0->isNullValue()) {
1943        SmallVector<Value*, 16> NewIndices;
1944        NewIndices.reserve(Idxs.size() + CE->getNumOperands());
1945        for (unsigned i = 1, e = CE->getNumOperands()-1; i != e; ++i)
1946          NewIndices.push_back(CE->getOperand(i));
1947
1948        // Add the last index of the source with the first index of the new GEP.
1949        // Make sure to handle the case when they are actually different types.
1950        Constant *Combined = CE->getOperand(CE->getNumOperands()-1);
1951        // Otherwise it must be an array.
1952        if (!Idx0->isNullValue()) {
1953          Type *IdxTy = Combined->getType();
1954          if (IdxTy != Idx0->getType()) {
1955            Type *Int64Ty = Type::getInt64Ty(IdxTy->getContext());
1956            Constant *C1 = ConstantExpr::getSExtOrBitCast(Idx0, Int64Ty);
1957            Constant *C2 = ConstantExpr::getSExtOrBitCast(Combined, Int64Ty);
1958            Combined = ConstantExpr::get(Instruction::Add, C1, C2);
1959          } else {
1960            Combined =
1961              ConstantExpr::get(Instruction::Add, Idx0, Combined);
1962          }
1963        }
1964
1965        NewIndices.push_back(Combined);
1966        NewIndices.append(Idxs.begin() + 1, Idxs.end());
1967        return
1968          ConstantExpr::getGetElementPtr(CE->getOperand(0), NewIndices,
1969                                         inBounds &&
1970                                           cast<GEPOperator>(CE)->isInBounds());
1971      }
1972    }
1973
1974    // Attempt to fold casts to the same type away.  For example, folding:
1975    //
1976    //   i32* getelementptr ([2 x i32]* bitcast ([3 x i32]* %X to [2 x i32]*),
1977    //                       i64 0, i64 0)
1978    // into:
1979    //
1980    //   i32* getelementptr ([3 x i32]* %X, i64 0, i64 0)
1981    //
1982    // Don't fold if the cast is changing address spaces.
1983    if (CE->isCast() && Idxs.size() > 1 && Idx0->isNullValue()) {
1984      PointerType *SrcPtrTy =
1985        dyn_cast<PointerType>(CE->getOperand(0)->getType());
1986      PointerType *DstPtrTy = dyn_cast<PointerType>(CE->getType());
1987      if (SrcPtrTy && DstPtrTy) {
1988        ArrayType *SrcArrayTy =
1989          dyn_cast<ArrayType>(SrcPtrTy->getElementType());
1990        ArrayType *DstArrayTy =
1991          dyn_cast<ArrayType>(DstPtrTy->getElementType());
1992        if (SrcArrayTy && DstArrayTy
1993            && SrcArrayTy->getElementType() == DstArrayTy->getElementType()
1994            && SrcPtrTy->getAddressSpace() == DstPtrTy->getAddressSpace())
1995          return ConstantExpr::getGetElementPtr((Constant*)CE->getOperand(0),
1996                                                Idxs, inBounds);
1997      }
1998    }
1999  }
2000
2001  // Check to see if any array indices are not within the corresponding
2002  // notional array bounds. If so, try to determine if they can be factored
2003  // out into preceding dimensions.
2004  bool Unknown = false;
2005  SmallVector<Constant *, 8> NewIdxs;
2006  Type *Ty = C->getType();
2007  Type *Prev = 0;
2008  for (unsigned i = 0, e = Idxs.size(); i != e;
2009       Prev = Ty, Ty = cast<CompositeType>(Ty)->getTypeAtIndex(Idxs[i]), ++i) {
2010    if (ConstantInt *CI = dyn_cast<ConstantInt>(Idxs[i])) {
2011      if (ArrayType *ATy = dyn_cast<ArrayType>(Ty))
2012        if (ATy->getNumElements() <= INT64_MAX &&
2013            ATy->getNumElements() != 0 &&
2014            CI->getSExtValue() >= (int64_t)ATy->getNumElements()) {
2015          if (isa<SequentialType>(Prev)) {
2016            // It's out of range, but we can factor it into the prior
2017            // dimension.
2018            NewIdxs.resize(Idxs.size());
2019            ConstantInt *Factor = ConstantInt::get(CI->getType(),
2020                                                   ATy->getNumElements());
2021            NewIdxs[i] = ConstantExpr::getSRem(CI, Factor);
2022
2023            Constant *PrevIdx = cast<Constant>(Idxs[i-1]);
2024            Constant *Div = ConstantExpr::getSDiv(CI, Factor);
2025
2026            // Before adding, extend both operands to i64 to avoid
2027            // overflow trouble.
2028            if (!PrevIdx->getType()->isIntegerTy(64))
2029              PrevIdx = ConstantExpr::getSExt(PrevIdx,
2030                                           Type::getInt64Ty(Div->getContext()));
2031            if (!Div->getType()->isIntegerTy(64))
2032              Div = ConstantExpr::getSExt(Div,
2033                                          Type::getInt64Ty(Div->getContext()));
2034
2035            NewIdxs[i-1] = ConstantExpr::getAdd(PrevIdx, Div);
2036          } else {
2037            // It's out of range, but the prior dimension is a struct
2038            // so we can't do anything about it.
2039            Unknown = true;
2040          }
2041        }
2042    } else {
2043      // We don't know if it's in range or not.
2044      Unknown = true;
2045    }
2046  }
2047
2048  // If we did any factoring, start over with the adjusted indices.
2049  if (!NewIdxs.empty()) {
2050    for (unsigned i = 0, e = Idxs.size(); i != e; ++i)
2051      if (!NewIdxs[i]) NewIdxs[i] = cast<Constant>(Idxs[i]);
2052    return ConstantExpr::getGetElementPtr(C, NewIdxs, inBounds);
2053  }
2054
2055  // If all indices are known integers and normalized, we can do a simple
2056  // check for the "inbounds" property.
2057  if (!Unknown && !inBounds &&
2058      isa<GlobalVariable>(C) && isInBoundsIndices(Idxs))
2059    return ConstantExpr::getInBoundsGetElementPtr(C, Idxs);
2060
2061  return 0;
2062}
2063
2064Constant *llvm::ConstantFoldGetElementPtr(Constant *C,
2065                                          bool inBounds,
2066                                          ArrayRef<Constant *> Idxs) {
2067  return ConstantFoldGetElementPtrImpl(C, inBounds, Idxs);
2068}
2069
2070Constant *llvm::ConstantFoldGetElementPtr(Constant *C,
2071                                          bool inBounds,
2072                                          ArrayRef<Value *> Idxs) {
2073  return ConstantFoldGetElementPtrImpl(C, inBounds, Idxs);
2074}
2075