1f4a2713aSLionel Sambuc //===- ConstantFold.cpp - LLVM constant folder ----------------------------===//
2f4a2713aSLionel Sambuc //
3f4a2713aSLionel Sambuc //                     The LLVM Compiler Infrastructure
4f4a2713aSLionel Sambuc //
5f4a2713aSLionel Sambuc // This file is distributed under the University of Illinois Open Source
6f4a2713aSLionel Sambuc // License. See LICENSE.TXT for details.
7f4a2713aSLionel Sambuc //
8f4a2713aSLionel Sambuc //===----------------------------------------------------------------------===//
9f4a2713aSLionel Sambuc //
10f4a2713aSLionel Sambuc // This file implements folding of constants for LLVM.  This implements the
11f4a2713aSLionel Sambuc // (internal) ConstantFold.h interface, which is used by the
12f4a2713aSLionel Sambuc // ConstantExpr::get* methods to automatically fold constants when possible.
13f4a2713aSLionel Sambuc //
14f4a2713aSLionel Sambuc // The current constant folding implementation is implemented in two pieces: the
15f4a2713aSLionel Sambuc // pieces that don't need DataLayout, and the pieces that do. This is to avoid
16f4a2713aSLionel Sambuc // a dependence in IR on Target.
17f4a2713aSLionel Sambuc //
18f4a2713aSLionel Sambuc //===----------------------------------------------------------------------===//
19f4a2713aSLionel Sambuc 
20f4a2713aSLionel Sambuc #include "ConstantFold.h"
21f4a2713aSLionel Sambuc #include "llvm/ADT/SmallVector.h"
22f4a2713aSLionel Sambuc #include "llvm/IR/Constants.h"
23f4a2713aSLionel Sambuc #include "llvm/IR/DerivedTypes.h"
24f4a2713aSLionel Sambuc #include "llvm/IR/Function.h"
25*0a6a1f1dSLionel Sambuc #include "llvm/IR/GetElementPtrTypeIterator.h"
26f4a2713aSLionel Sambuc #include "llvm/IR/GlobalAlias.h"
27f4a2713aSLionel Sambuc #include "llvm/IR/GlobalVariable.h"
28f4a2713aSLionel Sambuc #include "llvm/IR/Instructions.h"
29f4a2713aSLionel Sambuc #include "llvm/IR/Operator.h"
30*0a6a1f1dSLionel Sambuc #include "llvm/IR/PatternMatch.h"
31f4a2713aSLionel Sambuc #include "llvm/Support/Compiler.h"
32f4a2713aSLionel Sambuc #include "llvm/Support/ErrorHandling.h"
33f4a2713aSLionel Sambuc #include "llvm/Support/ManagedStatic.h"
34f4a2713aSLionel Sambuc #include "llvm/Support/MathExtras.h"
35f4a2713aSLionel Sambuc #include <limits>
36f4a2713aSLionel Sambuc using namespace llvm;
37*0a6a1f1dSLionel Sambuc using namespace llvm::PatternMatch;
38f4a2713aSLionel Sambuc 
39f4a2713aSLionel Sambuc //===----------------------------------------------------------------------===//
40f4a2713aSLionel Sambuc //                ConstantFold*Instruction Implementations
41f4a2713aSLionel Sambuc //===----------------------------------------------------------------------===//
42f4a2713aSLionel Sambuc 
43f4a2713aSLionel Sambuc /// BitCastConstantVector - Convert the specified vector Constant node to the
44f4a2713aSLionel Sambuc /// specified vector type.  At this point, we know that the elements of the
45f4a2713aSLionel Sambuc /// input vector constant are all simple integer or FP values.
BitCastConstantVector(Constant * CV,VectorType * DstTy)46f4a2713aSLionel Sambuc static Constant *BitCastConstantVector(Constant *CV, VectorType *DstTy) {
47f4a2713aSLionel Sambuc 
48f4a2713aSLionel Sambuc   if (CV->isAllOnesValue()) return Constant::getAllOnesValue(DstTy);
49f4a2713aSLionel Sambuc   if (CV->isNullValue()) return Constant::getNullValue(DstTy);
50f4a2713aSLionel Sambuc 
51f4a2713aSLionel Sambuc   // If this cast changes element count then we can't handle it here:
52f4a2713aSLionel Sambuc   // doing so requires endianness information.  This should be handled by
53f4a2713aSLionel Sambuc   // Analysis/ConstantFolding.cpp
54f4a2713aSLionel Sambuc   unsigned NumElts = DstTy->getNumElements();
55f4a2713aSLionel Sambuc   if (NumElts != CV->getType()->getVectorNumElements())
56*0a6a1f1dSLionel Sambuc     return nullptr;
57f4a2713aSLionel Sambuc 
58f4a2713aSLionel Sambuc   Type *DstEltTy = DstTy->getElementType();
59f4a2713aSLionel Sambuc 
60f4a2713aSLionel Sambuc   SmallVector<Constant*, 16> Result;
61f4a2713aSLionel Sambuc   Type *Ty = IntegerType::get(CV->getContext(), 32);
62f4a2713aSLionel Sambuc   for (unsigned i = 0; i != NumElts; ++i) {
63f4a2713aSLionel Sambuc     Constant *C =
64f4a2713aSLionel Sambuc       ConstantExpr::getExtractElement(CV, ConstantInt::get(Ty, i));
65f4a2713aSLionel Sambuc     C = ConstantExpr::getBitCast(C, DstEltTy);
66f4a2713aSLionel Sambuc     Result.push_back(C);
67f4a2713aSLionel Sambuc   }
68f4a2713aSLionel Sambuc 
69f4a2713aSLionel Sambuc   return ConstantVector::get(Result);
70f4a2713aSLionel Sambuc }
71f4a2713aSLionel Sambuc 
72f4a2713aSLionel Sambuc /// This function determines which opcode to use to fold two constant cast
73f4a2713aSLionel Sambuc /// expressions together. It uses CastInst::isEliminableCastPair to determine
74f4a2713aSLionel Sambuc /// the opcode. Consequently its just a wrapper around that function.
75f4a2713aSLionel Sambuc /// @brief Determine if it is valid to fold a cast of a cast
76f4a2713aSLionel Sambuc static unsigned
foldConstantCastPair(unsigned opc,ConstantExpr * Op,Type * DstTy)77f4a2713aSLionel Sambuc foldConstantCastPair(
78f4a2713aSLionel Sambuc   unsigned opc,          ///< opcode of the second cast constant expression
79f4a2713aSLionel Sambuc   ConstantExpr *Op,      ///< the first cast constant expression
80f4a2713aSLionel Sambuc   Type *DstTy            ///< destination type of the first cast
81f4a2713aSLionel Sambuc ) {
82f4a2713aSLionel Sambuc   assert(Op && Op->isCast() && "Can't fold cast of cast without a cast!");
83f4a2713aSLionel Sambuc   assert(DstTy && DstTy->isFirstClassType() && "Invalid cast destination type");
84f4a2713aSLionel Sambuc   assert(CastInst::isCast(opc) && "Invalid cast opcode");
85f4a2713aSLionel Sambuc 
86f4a2713aSLionel Sambuc   // The the types and opcodes for the two Cast constant expressions
87f4a2713aSLionel Sambuc   Type *SrcTy = Op->getOperand(0)->getType();
88f4a2713aSLionel Sambuc   Type *MidTy = Op->getType();
89f4a2713aSLionel Sambuc   Instruction::CastOps firstOp = Instruction::CastOps(Op->getOpcode());
90f4a2713aSLionel Sambuc   Instruction::CastOps secondOp = Instruction::CastOps(opc);
91f4a2713aSLionel Sambuc 
92f4a2713aSLionel Sambuc   // Assume that pointers are never more than 64 bits wide, and only use this
93f4a2713aSLionel Sambuc   // for the middle type. Otherwise we could end up folding away illegal
94f4a2713aSLionel Sambuc   // bitcasts between address spaces with different sizes.
95f4a2713aSLionel Sambuc   IntegerType *FakeIntPtrTy = Type::getInt64Ty(DstTy->getContext());
96f4a2713aSLionel Sambuc 
97f4a2713aSLionel Sambuc   // Let CastInst::isEliminableCastPair do the heavy lifting.
98f4a2713aSLionel Sambuc   return CastInst::isEliminableCastPair(firstOp, secondOp, SrcTy, MidTy, DstTy,
99*0a6a1f1dSLionel Sambuc                                         nullptr, FakeIntPtrTy, nullptr);
100f4a2713aSLionel Sambuc }
101f4a2713aSLionel Sambuc 
FoldBitCast(Constant * V,Type * DestTy)102f4a2713aSLionel Sambuc static Constant *FoldBitCast(Constant *V, Type *DestTy) {
103f4a2713aSLionel Sambuc   Type *SrcTy = V->getType();
104f4a2713aSLionel Sambuc   if (SrcTy == DestTy)
105f4a2713aSLionel Sambuc     return V; // no-op cast
106f4a2713aSLionel Sambuc 
107f4a2713aSLionel Sambuc   // Check to see if we are casting a pointer to an aggregate to a pointer to
108f4a2713aSLionel Sambuc   // the first element.  If so, return the appropriate GEP instruction.
109f4a2713aSLionel Sambuc   if (PointerType *PTy = dyn_cast<PointerType>(V->getType()))
110f4a2713aSLionel Sambuc     if (PointerType *DPTy = dyn_cast<PointerType>(DestTy))
111f4a2713aSLionel Sambuc       if (PTy->getAddressSpace() == DPTy->getAddressSpace()
112f4a2713aSLionel Sambuc           && DPTy->getElementType()->isSized()) {
113f4a2713aSLionel Sambuc         SmallVector<Value*, 8> IdxList;
114f4a2713aSLionel Sambuc         Value *Zero =
115f4a2713aSLionel Sambuc           Constant::getNullValue(Type::getInt32Ty(DPTy->getContext()));
116f4a2713aSLionel Sambuc         IdxList.push_back(Zero);
117f4a2713aSLionel Sambuc         Type *ElTy = PTy->getElementType();
118f4a2713aSLionel Sambuc         while (ElTy != DPTy->getElementType()) {
119f4a2713aSLionel Sambuc           if (StructType *STy = dyn_cast<StructType>(ElTy)) {
120f4a2713aSLionel Sambuc             if (STy->getNumElements() == 0) break;
121f4a2713aSLionel Sambuc             ElTy = STy->getElementType(0);
122f4a2713aSLionel Sambuc             IdxList.push_back(Zero);
123f4a2713aSLionel Sambuc           } else if (SequentialType *STy =
124f4a2713aSLionel Sambuc                      dyn_cast<SequentialType>(ElTy)) {
125f4a2713aSLionel Sambuc             if (ElTy->isPointerTy()) break;  // Can't index into pointers!
126f4a2713aSLionel Sambuc             ElTy = STy->getElementType();
127f4a2713aSLionel Sambuc             IdxList.push_back(Zero);
128f4a2713aSLionel Sambuc           } else {
129f4a2713aSLionel Sambuc             break;
130f4a2713aSLionel Sambuc           }
131f4a2713aSLionel Sambuc         }
132f4a2713aSLionel Sambuc 
133f4a2713aSLionel Sambuc         if (ElTy == DPTy->getElementType())
134f4a2713aSLionel Sambuc           // This GEP is inbounds because all indices are zero.
135f4a2713aSLionel Sambuc           return ConstantExpr::getInBoundsGetElementPtr(V, IdxList);
136f4a2713aSLionel Sambuc       }
137f4a2713aSLionel Sambuc 
138f4a2713aSLionel Sambuc   // Handle casts from one vector constant to another.  We know that the src
139f4a2713aSLionel Sambuc   // and dest type have the same size (otherwise its an illegal cast).
140f4a2713aSLionel Sambuc   if (VectorType *DestPTy = dyn_cast<VectorType>(DestTy)) {
141f4a2713aSLionel Sambuc     if (VectorType *SrcTy = dyn_cast<VectorType>(V->getType())) {
142f4a2713aSLionel Sambuc       assert(DestPTy->getBitWidth() == SrcTy->getBitWidth() &&
143f4a2713aSLionel Sambuc              "Not cast between same sized vectors!");
144*0a6a1f1dSLionel Sambuc       SrcTy = nullptr;
145f4a2713aSLionel Sambuc       // First, check for null.  Undef is already handled.
146f4a2713aSLionel Sambuc       if (isa<ConstantAggregateZero>(V))
147f4a2713aSLionel Sambuc         return Constant::getNullValue(DestTy);
148f4a2713aSLionel Sambuc 
149f4a2713aSLionel Sambuc       // Handle ConstantVector and ConstantAggregateVector.
150f4a2713aSLionel Sambuc       return BitCastConstantVector(V, DestPTy);
151f4a2713aSLionel Sambuc     }
152f4a2713aSLionel Sambuc 
153f4a2713aSLionel Sambuc     // Canonicalize scalar-to-vector bitcasts into vector-to-vector bitcasts
154f4a2713aSLionel Sambuc     // This allows for other simplifications (although some of them
155f4a2713aSLionel Sambuc     // can only be handled by Analysis/ConstantFolding.cpp).
156f4a2713aSLionel Sambuc     if (isa<ConstantInt>(V) || isa<ConstantFP>(V))
157f4a2713aSLionel Sambuc       return ConstantExpr::getBitCast(ConstantVector::get(V), DestPTy);
158f4a2713aSLionel Sambuc   }
159f4a2713aSLionel Sambuc 
160f4a2713aSLionel Sambuc   // Finally, implement bitcast folding now.   The code below doesn't handle
161f4a2713aSLionel Sambuc   // bitcast right.
162f4a2713aSLionel Sambuc   if (isa<ConstantPointerNull>(V))  // ptr->ptr cast.
163f4a2713aSLionel Sambuc     return ConstantPointerNull::get(cast<PointerType>(DestTy));
164f4a2713aSLionel Sambuc 
165f4a2713aSLionel Sambuc   // Handle integral constant input.
166f4a2713aSLionel Sambuc   if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
167f4a2713aSLionel Sambuc     if (DestTy->isIntegerTy())
168f4a2713aSLionel Sambuc       // Integral -> Integral. This is a no-op because the bit widths must
169f4a2713aSLionel Sambuc       // be the same. Consequently, we just fold to V.
170f4a2713aSLionel Sambuc       return V;
171f4a2713aSLionel Sambuc 
172f4a2713aSLionel Sambuc     if (DestTy->isFloatingPointTy())
173f4a2713aSLionel Sambuc       return ConstantFP::get(DestTy->getContext(),
174f4a2713aSLionel Sambuc                              APFloat(DestTy->getFltSemantics(),
175f4a2713aSLionel Sambuc                                      CI->getValue()));
176f4a2713aSLionel Sambuc 
177f4a2713aSLionel Sambuc     // Otherwise, can't fold this (vector?)
178*0a6a1f1dSLionel Sambuc     return nullptr;
179f4a2713aSLionel Sambuc   }
180f4a2713aSLionel Sambuc 
181f4a2713aSLionel Sambuc   // Handle ConstantFP input: FP -> Integral.
182f4a2713aSLionel Sambuc   if (ConstantFP *FP = dyn_cast<ConstantFP>(V))
183f4a2713aSLionel Sambuc     return ConstantInt::get(FP->getContext(),
184f4a2713aSLionel Sambuc                             FP->getValueAPF().bitcastToAPInt());
185f4a2713aSLionel Sambuc 
186*0a6a1f1dSLionel Sambuc   return nullptr;
187f4a2713aSLionel Sambuc }
188f4a2713aSLionel Sambuc 
189f4a2713aSLionel Sambuc 
190f4a2713aSLionel Sambuc /// ExtractConstantBytes - V is an integer constant which only has a subset of
191f4a2713aSLionel Sambuc /// its bytes used.  The bytes used are indicated by ByteStart (which is the
192f4a2713aSLionel Sambuc /// first byte used, counting from the least significant byte) and ByteSize,
193f4a2713aSLionel Sambuc /// which is the number of bytes used.
194f4a2713aSLionel Sambuc ///
195f4a2713aSLionel Sambuc /// This function analyzes the specified constant to see if the specified byte
196f4a2713aSLionel Sambuc /// range can be returned as a simplified constant.  If so, the constant is
197f4a2713aSLionel Sambuc /// returned, otherwise null is returned.
198f4a2713aSLionel Sambuc ///
ExtractConstantBytes(Constant * C,unsigned ByteStart,unsigned ByteSize)199f4a2713aSLionel Sambuc static Constant *ExtractConstantBytes(Constant *C, unsigned ByteStart,
200f4a2713aSLionel Sambuc                                       unsigned ByteSize) {
201f4a2713aSLionel Sambuc   assert(C->getType()->isIntegerTy() &&
202f4a2713aSLionel Sambuc          (cast<IntegerType>(C->getType())->getBitWidth() & 7) == 0 &&
203f4a2713aSLionel Sambuc          "Non-byte sized integer input");
204f4a2713aSLionel Sambuc   unsigned CSize = cast<IntegerType>(C->getType())->getBitWidth()/8;
205f4a2713aSLionel Sambuc   assert(ByteSize && "Must be accessing some piece");
206f4a2713aSLionel Sambuc   assert(ByteStart+ByteSize <= CSize && "Extracting invalid piece from input");
207f4a2713aSLionel Sambuc   assert(ByteSize != CSize && "Should not extract everything");
208f4a2713aSLionel Sambuc 
209f4a2713aSLionel Sambuc   // Constant Integers are simple.
210f4a2713aSLionel Sambuc   if (ConstantInt *CI = dyn_cast<ConstantInt>(C)) {
211f4a2713aSLionel Sambuc     APInt V = CI->getValue();
212f4a2713aSLionel Sambuc     if (ByteStart)
213f4a2713aSLionel Sambuc       V = V.lshr(ByteStart*8);
214f4a2713aSLionel Sambuc     V = V.trunc(ByteSize*8);
215f4a2713aSLionel Sambuc     return ConstantInt::get(CI->getContext(), V);
216f4a2713aSLionel Sambuc   }
217f4a2713aSLionel Sambuc 
218f4a2713aSLionel Sambuc   // In the input is a constant expr, we might be able to recursively simplify.
219f4a2713aSLionel Sambuc   // If not, we definitely can't do anything.
220f4a2713aSLionel Sambuc   ConstantExpr *CE = dyn_cast<ConstantExpr>(C);
221*0a6a1f1dSLionel Sambuc   if (!CE) return nullptr;
222f4a2713aSLionel Sambuc 
223f4a2713aSLionel Sambuc   switch (CE->getOpcode()) {
224*0a6a1f1dSLionel Sambuc   default: return nullptr;
225f4a2713aSLionel Sambuc   case Instruction::Or: {
226f4a2713aSLionel Sambuc     Constant *RHS = ExtractConstantBytes(CE->getOperand(1), ByteStart,ByteSize);
227*0a6a1f1dSLionel Sambuc     if (!RHS)
228*0a6a1f1dSLionel Sambuc       return nullptr;
229f4a2713aSLionel Sambuc 
230f4a2713aSLionel Sambuc     // X | -1 -> -1.
231f4a2713aSLionel Sambuc     if (ConstantInt *RHSC = dyn_cast<ConstantInt>(RHS))
232f4a2713aSLionel Sambuc       if (RHSC->isAllOnesValue())
233f4a2713aSLionel Sambuc         return RHSC;
234f4a2713aSLionel Sambuc 
235f4a2713aSLionel Sambuc     Constant *LHS = ExtractConstantBytes(CE->getOperand(0), ByteStart,ByteSize);
236*0a6a1f1dSLionel Sambuc     if (!LHS)
237*0a6a1f1dSLionel Sambuc       return nullptr;
238f4a2713aSLionel Sambuc     return ConstantExpr::getOr(LHS, RHS);
239f4a2713aSLionel Sambuc   }
240f4a2713aSLionel Sambuc   case Instruction::And: {
241f4a2713aSLionel Sambuc     Constant *RHS = ExtractConstantBytes(CE->getOperand(1), ByteStart,ByteSize);
242*0a6a1f1dSLionel Sambuc     if (!RHS)
243*0a6a1f1dSLionel Sambuc       return nullptr;
244f4a2713aSLionel Sambuc 
245f4a2713aSLionel Sambuc     // X & 0 -> 0.
246f4a2713aSLionel Sambuc     if (RHS->isNullValue())
247f4a2713aSLionel Sambuc       return RHS;
248f4a2713aSLionel Sambuc 
249f4a2713aSLionel Sambuc     Constant *LHS = ExtractConstantBytes(CE->getOperand(0), ByteStart,ByteSize);
250*0a6a1f1dSLionel Sambuc     if (!LHS)
251*0a6a1f1dSLionel Sambuc       return nullptr;
252f4a2713aSLionel Sambuc     return ConstantExpr::getAnd(LHS, RHS);
253f4a2713aSLionel Sambuc   }
254f4a2713aSLionel Sambuc   case Instruction::LShr: {
255f4a2713aSLionel Sambuc     ConstantInt *Amt = dyn_cast<ConstantInt>(CE->getOperand(1));
256*0a6a1f1dSLionel Sambuc     if (!Amt)
257*0a6a1f1dSLionel Sambuc       return nullptr;
258f4a2713aSLionel Sambuc     unsigned ShAmt = Amt->getZExtValue();
259f4a2713aSLionel Sambuc     // Cannot analyze non-byte shifts.
260f4a2713aSLionel Sambuc     if ((ShAmt & 7) != 0)
261*0a6a1f1dSLionel Sambuc       return nullptr;
262f4a2713aSLionel Sambuc     ShAmt >>= 3;
263f4a2713aSLionel Sambuc 
264f4a2713aSLionel Sambuc     // If the extract is known to be all zeros, return zero.
265f4a2713aSLionel Sambuc     if (ByteStart >= CSize-ShAmt)
266f4a2713aSLionel Sambuc       return Constant::getNullValue(IntegerType::get(CE->getContext(),
267f4a2713aSLionel Sambuc                                                      ByteSize*8));
268f4a2713aSLionel Sambuc     // If the extract is known to be fully in the input, extract it.
269f4a2713aSLionel Sambuc     if (ByteStart+ByteSize+ShAmt <= CSize)
270f4a2713aSLionel Sambuc       return ExtractConstantBytes(CE->getOperand(0), ByteStart+ShAmt, ByteSize);
271f4a2713aSLionel Sambuc 
272f4a2713aSLionel Sambuc     // TODO: Handle the 'partially zero' case.
273*0a6a1f1dSLionel Sambuc     return nullptr;
274f4a2713aSLionel Sambuc   }
275f4a2713aSLionel Sambuc 
276f4a2713aSLionel Sambuc   case Instruction::Shl: {
277f4a2713aSLionel Sambuc     ConstantInt *Amt = dyn_cast<ConstantInt>(CE->getOperand(1));
278*0a6a1f1dSLionel Sambuc     if (!Amt)
279*0a6a1f1dSLionel Sambuc       return nullptr;
280f4a2713aSLionel Sambuc     unsigned ShAmt = Amt->getZExtValue();
281f4a2713aSLionel Sambuc     // Cannot analyze non-byte shifts.
282f4a2713aSLionel Sambuc     if ((ShAmt & 7) != 0)
283*0a6a1f1dSLionel Sambuc       return nullptr;
284f4a2713aSLionel Sambuc     ShAmt >>= 3;
285f4a2713aSLionel Sambuc 
286f4a2713aSLionel Sambuc     // If the extract is known to be all zeros, return zero.
287f4a2713aSLionel Sambuc     if (ByteStart+ByteSize <= ShAmt)
288f4a2713aSLionel Sambuc       return Constant::getNullValue(IntegerType::get(CE->getContext(),
289f4a2713aSLionel Sambuc                                                      ByteSize*8));
290f4a2713aSLionel Sambuc     // If the extract is known to be fully in the input, extract it.
291f4a2713aSLionel Sambuc     if (ByteStart >= ShAmt)
292f4a2713aSLionel Sambuc       return ExtractConstantBytes(CE->getOperand(0), ByteStart-ShAmt, ByteSize);
293f4a2713aSLionel Sambuc 
294f4a2713aSLionel Sambuc     // TODO: Handle the 'partially zero' case.
295*0a6a1f1dSLionel Sambuc     return nullptr;
296f4a2713aSLionel Sambuc   }
297f4a2713aSLionel Sambuc 
298f4a2713aSLionel Sambuc   case Instruction::ZExt: {
299f4a2713aSLionel Sambuc     unsigned SrcBitSize =
300f4a2713aSLionel Sambuc       cast<IntegerType>(CE->getOperand(0)->getType())->getBitWidth();
301f4a2713aSLionel Sambuc 
302f4a2713aSLionel Sambuc     // If extracting something that is completely zero, return 0.
303f4a2713aSLionel Sambuc     if (ByteStart*8 >= SrcBitSize)
304f4a2713aSLionel Sambuc       return Constant::getNullValue(IntegerType::get(CE->getContext(),
305f4a2713aSLionel Sambuc                                                      ByteSize*8));
306f4a2713aSLionel Sambuc 
307f4a2713aSLionel Sambuc     // If exactly extracting the input, return it.
308f4a2713aSLionel Sambuc     if (ByteStart == 0 && ByteSize*8 == SrcBitSize)
309f4a2713aSLionel Sambuc       return CE->getOperand(0);
310f4a2713aSLionel Sambuc 
311f4a2713aSLionel Sambuc     // If extracting something completely in the input, if if the input is a
312f4a2713aSLionel Sambuc     // multiple of 8 bits, recurse.
313f4a2713aSLionel Sambuc     if ((SrcBitSize&7) == 0 && (ByteStart+ByteSize)*8 <= SrcBitSize)
314f4a2713aSLionel Sambuc       return ExtractConstantBytes(CE->getOperand(0), ByteStart, ByteSize);
315f4a2713aSLionel Sambuc 
316f4a2713aSLionel Sambuc     // Otherwise, if extracting a subset of the input, which is not multiple of
317f4a2713aSLionel Sambuc     // 8 bits, do a shift and trunc to get the bits.
318f4a2713aSLionel Sambuc     if ((ByteStart+ByteSize)*8 < SrcBitSize) {
319f4a2713aSLionel Sambuc       assert((SrcBitSize&7) && "Shouldn't get byte sized case here");
320f4a2713aSLionel Sambuc       Constant *Res = CE->getOperand(0);
321f4a2713aSLionel Sambuc       if (ByteStart)
322f4a2713aSLionel Sambuc         Res = ConstantExpr::getLShr(Res,
323f4a2713aSLionel Sambuc                                  ConstantInt::get(Res->getType(), ByteStart*8));
324f4a2713aSLionel Sambuc       return ConstantExpr::getTrunc(Res, IntegerType::get(C->getContext(),
325f4a2713aSLionel Sambuc                                                           ByteSize*8));
326f4a2713aSLionel Sambuc     }
327f4a2713aSLionel Sambuc 
328f4a2713aSLionel Sambuc     // TODO: Handle the 'partially zero' case.
329*0a6a1f1dSLionel Sambuc     return nullptr;
330f4a2713aSLionel Sambuc   }
331f4a2713aSLionel Sambuc   }
332f4a2713aSLionel Sambuc }
333f4a2713aSLionel Sambuc 
334f4a2713aSLionel Sambuc /// getFoldedSizeOf - Return a ConstantExpr with type DestTy for sizeof
335f4a2713aSLionel Sambuc /// on Ty, with any known factors factored out. If Folded is false,
336f4a2713aSLionel Sambuc /// return null if no factoring was possible, to avoid endlessly
337f4a2713aSLionel Sambuc /// bouncing an unfoldable expression back into the top-level folder.
338f4a2713aSLionel Sambuc ///
getFoldedSizeOf(Type * Ty,Type * DestTy,bool Folded)339f4a2713aSLionel Sambuc static Constant *getFoldedSizeOf(Type *Ty, Type *DestTy,
340f4a2713aSLionel Sambuc                                  bool Folded) {
341f4a2713aSLionel Sambuc   if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
342f4a2713aSLionel Sambuc     Constant *N = ConstantInt::get(DestTy, ATy->getNumElements());
343f4a2713aSLionel Sambuc     Constant *E = getFoldedSizeOf(ATy->getElementType(), DestTy, true);
344f4a2713aSLionel Sambuc     return ConstantExpr::getNUWMul(E, N);
345f4a2713aSLionel Sambuc   }
346f4a2713aSLionel Sambuc 
347f4a2713aSLionel Sambuc   if (StructType *STy = dyn_cast<StructType>(Ty))
348f4a2713aSLionel Sambuc     if (!STy->isPacked()) {
349f4a2713aSLionel Sambuc       unsigned NumElems = STy->getNumElements();
350f4a2713aSLionel Sambuc       // An empty struct has size zero.
351f4a2713aSLionel Sambuc       if (NumElems == 0)
352f4a2713aSLionel Sambuc         return ConstantExpr::getNullValue(DestTy);
353f4a2713aSLionel Sambuc       // Check for a struct with all members having the same size.
354f4a2713aSLionel Sambuc       Constant *MemberSize =
355f4a2713aSLionel Sambuc         getFoldedSizeOf(STy->getElementType(0), DestTy, true);
356f4a2713aSLionel Sambuc       bool AllSame = true;
357f4a2713aSLionel Sambuc       for (unsigned i = 1; i != NumElems; ++i)
358f4a2713aSLionel Sambuc         if (MemberSize !=
359f4a2713aSLionel Sambuc             getFoldedSizeOf(STy->getElementType(i), DestTy, true)) {
360f4a2713aSLionel Sambuc           AllSame = false;
361f4a2713aSLionel Sambuc           break;
362f4a2713aSLionel Sambuc         }
363f4a2713aSLionel Sambuc       if (AllSame) {
364f4a2713aSLionel Sambuc         Constant *N = ConstantInt::get(DestTy, NumElems);
365f4a2713aSLionel Sambuc         return ConstantExpr::getNUWMul(MemberSize, N);
366f4a2713aSLionel Sambuc       }
367f4a2713aSLionel Sambuc     }
368f4a2713aSLionel Sambuc 
369f4a2713aSLionel Sambuc   // Pointer size doesn't depend on the pointee type, so canonicalize them
370f4a2713aSLionel Sambuc   // to an arbitrary pointee.
371f4a2713aSLionel Sambuc   if (PointerType *PTy = dyn_cast<PointerType>(Ty))
372f4a2713aSLionel Sambuc     if (!PTy->getElementType()->isIntegerTy(1))
373f4a2713aSLionel Sambuc       return
374f4a2713aSLionel Sambuc         getFoldedSizeOf(PointerType::get(IntegerType::get(PTy->getContext(), 1),
375f4a2713aSLionel Sambuc                                          PTy->getAddressSpace()),
376f4a2713aSLionel Sambuc                         DestTy, true);
377f4a2713aSLionel Sambuc 
378f4a2713aSLionel Sambuc   // If there's no interesting folding happening, bail so that we don't create
379f4a2713aSLionel Sambuc   // a constant that looks like it needs folding but really doesn't.
380f4a2713aSLionel Sambuc   if (!Folded)
381*0a6a1f1dSLionel Sambuc     return nullptr;
382f4a2713aSLionel Sambuc 
383f4a2713aSLionel Sambuc   // Base case: Get a regular sizeof expression.
384f4a2713aSLionel Sambuc   Constant *C = ConstantExpr::getSizeOf(Ty);
385f4a2713aSLionel Sambuc   C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false,
386f4a2713aSLionel Sambuc                                                     DestTy, false),
387f4a2713aSLionel Sambuc                             C, DestTy);
388f4a2713aSLionel Sambuc   return C;
389f4a2713aSLionel Sambuc }
390f4a2713aSLionel Sambuc 
391f4a2713aSLionel Sambuc /// getFoldedAlignOf - Return a ConstantExpr with type DestTy for alignof
392f4a2713aSLionel Sambuc /// on Ty, with any known factors factored out. If Folded is false,
393f4a2713aSLionel Sambuc /// return null if no factoring was possible, to avoid endlessly
394f4a2713aSLionel Sambuc /// bouncing an unfoldable expression back into the top-level folder.
395f4a2713aSLionel Sambuc ///
getFoldedAlignOf(Type * Ty,Type * DestTy,bool Folded)396f4a2713aSLionel Sambuc static Constant *getFoldedAlignOf(Type *Ty, Type *DestTy,
397f4a2713aSLionel Sambuc                                   bool Folded) {
398f4a2713aSLionel Sambuc   // The alignment of an array is equal to the alignment of the
399f4a2713aSLionel Sambuc   // array element. Note that this is not always true for vectors.
400f4a2713aSLionel Sambuc   if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
401f4a2713aSLionel Sambuc     Constant *C = ConstantExpr::getAlignOf(ATy->getElementType());
402f4a2713aSLionel Sambuc     C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false,
403f4a2713aSLionel Sambuc                                                       DestTy,
404f4a2713aSLionel Sambuc                                                       false),
405f4a2713aSLionel Sambuc                               C, DestTy);
406f4a2713aSLionel Sambuc     return C;
407f4a2713aSLionel Sambuc   }
408f4a2713aSLionel Sambuc 
409f4a2713aSLionel Sambuc   if (StructType *STy = dyn_cast<StructType>(Ty)) {
410f4a2713aSLionel Sambuc     // Packed structs always have an alignment of 1.
411f4a2713aSLionel Sambuc     if (STy->isPacked())
412f4a2713aSLionel Sambuc       return ConstantInt::get(DestTy, 1);
413f4a2713aSLionel Sambuc 
414f4a2713aSLionel Sambuc     // Otherwise, struct alignment is the maximum alignment of any member.
415f4a2713aSLionel Sambuc     // Without target data, we can't compare much, but we can check to see
416f4a2713aSLionel Sambuc     // if all the members have the same alignment.
417f4a2713aSLionel Sambuc     unsigned NumElems = STy->getNumElements();
418f4a2713aSLionel Sambuc     // An empty struct has minimal alignment.
419f4a2713aSLionel Sambuc     if (NumElems == 0)
420f4a2713aSLionel Sambuc       return ConstantInt::get(DestTy, 1);
421f4a2713aSLionel Sambuc     // Check for a struct with all members having the same alignment.
422f4a2713aSLionel Sambuc     Constant *MemberAlign =
423f4a2713aSLionel Sambuc       getFoldedAlignOf(STy->getElementType(0), DestTy, true);
424f4a2713aSLionel Sambuc     bool AllSame = true;
425f4a2713aSLionel Sambuc     for (unsigned i = 1; i != NumElems; ++i)
426f4a2713aSLionel Sambuc       if (MemberAlign != getFoldedAlignOf(STy->getElementType(i), DestTy, true)) {
427f4a2713aSLionel Sambuc         AllSame = false;
428f4a2713aSLionel Sambuc         break;
429f4a2713aSLionel Sambuc       }
430f4a2713aSLionel Sambuc     if (AllSame)
431f4a2713aSLionel Sambuc       return MemberAlign;
432f4a2713aSLionel Sambuc   }
433f4a2713aSLionel Sambuc 
434f4a2713aSLionel Sambuc   // Pointer alignment doesn't depend on the pointee type, so canonicalize them
435f4a2713aSLionel Sambuc   // to an arbitrary pointee.
436f4a2713aSLionel Sambuc   if (PointerType *PTy = dyn_cast<PointerType>(Ty))
437f4a2713aSLionel Sambuc     if (!PTy->getElementType()->isIntegerTy(1))
438f4a2713aSLionel Sambuc       return
439f4a2713aSLionel Sambuc         getFoldedAlignOf(PointerType::get(IntegerType::get(PTy->getContext(),
440f4a2713aSLionel Sambuc                                                            1),
441f4a2713aSLionel Sambuc                                           PTy->getAddressSpace()),
442f4a2713aSLionel Sambuc                          DestTy, true);
443f4a2713aSLionel Sambuc 
444f4a2713aSLionel Sambuc   // If there's no interesting folding happening, bail so that we don't create
445f4a2713aSLionel Sambuc   // a constant that looks like it needs folding but really doesn't.
446f4a2713aSLionel Sambuc   if (!Folded)
447*0a6a1f1dSLionel Sambuc     return nullptr;
448f4a2713aSLionel Sambuc 
449f4a2713aSLionel Sambuc   // Base case: Get a regular alignof expression.
450f4a2713aSLionel Sambuc   Constant *C = ConstantExpr::getAlignOf(Ty);
451f4a2713aSLionel Sambuc   C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false,
452f4a2713aSLionel Sambuc                                                     DestTy, false),
453f4a2713aSLionel Sambuc                             C, DestTy);
454f4a2713aSLionel Sambuc   return C;
455f4a2713aSLionel Sambuc }
456f4a2713aSLionel Sambuc 
457f4a2713aSLionel Sambuc /// getFoldedOffsetOf - Return a ConstantExpr with type DestTy for offsetof
458f4a2713aSLionel Sambuc /// on Ty and FieldNo, with any known factors factored out. If Folded is false,
459f4a2713aSLionel Sambuc /// return null if no factoring was possible, to avoid endlessly
460f4a2713aSLionel Sambuc /// bouncing an unfoldable expression back into the top-level folder.
461f4a2713aSLionel Sambuc ///
getFoldedOffsetOf(Type * Ty,Constant * FieldNo,Type * DestTy,bool Folded)462f4a2713aSLionel Sambuc static Constant *getFoldedOffsetOf(Type *Ty, Constant *FieldNo,
463f4a2713aSLionel Sambuc                                    Type *DestTy,
464f4a2713aSLionel Sambuc                                    bool Folded) {
465f4a2713aSLionel Sambuc   if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
466f4a2713aSLionel Sambuc     Constant *N = ConstantExpr::getCast(CastInst::getCastOpcode(FieldNo, false,
467f4a2713aSLionel Sambuc                                                                 DestTy, false),
468f4a2713aSLionel Sambuc                                         FieldNo, DestTy);
469f4a2713aSLionel Sambuc     Constant *E = getFoldedSizeOf(ATy->getElementType(), DestTy, true);
470f4a2713aSLionel Sambuc     return ConstantExpr::getNUWMul(E, N);
471f4a2713aSLionel Sambuc   }
472f4a2713aSLionel Sambuc 
473f4a2713aSLionel Sambuc   if (StructType *STy = dyn_cast<StructType>(Ty))
474f4a2713aSLionel Sambuc     if (!STy->isPacked()) {
475f4a2713aSLionel Sambuc       unsigned NumElems = STy->getNumElements();
476f4a2713aSLionel Sambuc       // An empty struct has no members.
477f4a2713aSLionel Sambuc       if (NumElems == 0)
478*0a6a1f1dSLionel Sambuc         return nullptr;
479f4a2713aSLionel Sambuc       // Check for a struct with all members having the same size.
480f4a2713aSLionel Sambuc       Constant *MemberSize =
481f4a2713aSLionel Sambuc         getFoldedSizeOf(STy->getElementType(0), DestTy, true);
482f4a2713aSLionel Sambuc       bool AllSame = true;
483f4a2713aSLionel Sambuc       for (unsigned i = 1; i != NumElems; ++i)
484f4a2713aSLionel Sambuc         if (MemberSize !=
485f4a2713aSLionel Sambuc             getFoldedSizeOf(STy->getElementType(i), DestTy, true)) {
486f4a2713aSLionel Sambuc           AllSame = false;
487f4a2713aSLionel Sambuc           break;
488f4a2713aSLionel Sambuc         }
489f4a2713aSLionel Sambuc       if (AllSame) {
490f4a2713aSLionel Sambuc         Constant *N = ConstantExpr::getCast(CastInst::getCastOpcode(FieldNo,
491f4a2713aSLionel Sambuc                                                                     false,
492f4a2713aSLionel Sambuc                                                                     DestTy,
493f4a2713aSLionel Sambuc                                                                     false),
494f4a2713aSLionel Sambuc                                             FieldNo, DestTy);
495f4a2713aSLionel Sambuc         return ConstantExpr::getNUWMul(MemberSize, N);
496f4a2713aSLionel Sambuc       }
497f4a2713aSLionel Sambuc     }
498f4a2713aSLionel Sambuc 
499f4a2713aSLionel Sambuc   // If there's no interesting folding happening, bail so that we don't create
500f4a2713aSLionel Sambuc   // a constant that looks like it needs folding but really doesn't.
501f4a2713aSLionel Sambuc   if (!Folded)
502*0a6a1f1dSLionel Sambuc     return nullptr;
503f4a2713aSLionel Sambuc 
504f4a2713aSLionel Sambuc   // Base case: Get a regular offsetof expression.
505f4a2713aSLionel Sambuc   Constant *C = ConstantExpr::getOffsetOf(Ty, FieldNo);
506f4a2713aSLionel Sambuc   C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false,
507f4a2713aSLionel Sambuc                                                     DestTy, false),
508f4a2713aSLionel Sambuc                             C, DestTy);
509f4a2713aSLionel Sambuc   return C;
510f4a2713aSLionel Sambuc }
511f4a2713aSLionel Sambuc 
ConstantFoldCastInstruction(unsigned opc,Constant * V,Type * DestTy)512f4a2713aSLionel Sambuc Constant *llvm::ConstantFoldCastInstruction(unsigned opc, Constant *V,
513f4a2713aSLionel Sambuc                                             Type *DestTy) {
514f4a2713aSLionel Sambuc   if (isa<UndefValue>(V)) {
515f4a2713aSLionel Sambuc     // zext(undef) = 0, because the top bits will be zero.
516f4a2713aSLionel Sambuc     // sext(undef) = 0, because the top bits will all be the same.
517f4a2713aSLionel Sambuc     // [us]itofp(undef) = 0, because the result value is bounded.
518f4a2713aSLionel Sambuc     if (opc == Instruction::ZExt || opc == Instruction::SExt ||
519f4a2713aSLionel Sambuc         opc == Instruction::UIToFP || opc == Instruction::SIToFP)
520f4a2713aSLionel Sambuc       return Constant::getNullValue(DestTy);
521f4a2713aSLionel Sambuc     return UndefValue::get(DestTy);
522f4a2713aSLionel Sambuc   }
523f4a2713aSLionel Sambuc 
524f4a2713aSLionel Sambuc   if (V->isNullValue() && !DestTy->isX86_MMXTy())
525f4a2713aSLionel Sambuc     return Constant::getNullValue(DestTy);
526f4a2713aSLionel Sambuc 
527f4a2713aSLionel Sambuc   // If the cast operand is a constant expression, there's a few things we can
528f4a2713aSLionel Sambuc   // do to try to simplify it.
529f4a2713aSLionel Sambuc   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) {
530f4a2713aSLionel Sambuc     if (CE->isCast()) {
531f4a2713aSLionel Sambuc       // Try hard to fold cast of cast because they are often eliminable.
532f4a2713aSLionel Sambuc       if (unsigned newOpc = foldConstantCastPair(opc, CE, DestTy))
533f4a2713aSLionel Sambuc         return ConstantExpr::getCast(newOpc, CE->getOperand(0), DestTy);
534*0a6a1f1dSLionel Sambuc     } else if (CE->getOpcode() == Instruction::GetElementPtr &&
535*0a6a1f1dSLionel Sambuc                // Do not fold addrspacecast (gep 0, .., 0). It might make the
536*0a6a1f1dSLionel Sambuc                // addrspacecast uncanonicalized.
537*0a6a1f1dSLionel Sambuc                opc != Instruction::AddrSpaceCast) {
538f4a2713aSLionel Sambuc       // If all of the indexes in the GEP are null values, there is no pointer
539f4a2713aSLionel Sambuc       // adjustment going on.  We might as well cast the source pointer.
540f4a2713aSLionel Sambuc       bool isAllNull = true;
541f4a2713aSLionel Sambuc       for (unsigned i = 1, e = CE->getNumOperands(); i != e; ++i)
542f4a2713aSLionel Sambuc         if (!CE->getOperand(i)->isNullValue()) {
543f4a2713aSLionel Sambuc           isAllNull = false;
544f4a2713aSLionel Sambuc           break;
545f4a2713aSLionel Sambuc         }
546f4a2713aSLionel Sambuc       if (isAllNull)
547f4a2713aSLionel Sambuc         // This is casting one pointer type to another, always BitCast
548f4a2713aSLionel Sambuc         return ConstantExpr::getPointerCast(CE->getOperand(0), DestTy);
549f4a2713aSLionel Sambuc     }
550f4a2713aSLionel Sambuc   }
551f4a2713aSLionel Sambuc 
552f4a2713aSLionel Sambuc   // If the cast operand is a constant vector, perform the cast by
553f4a2713aSLionel Sambuc   // operating on each element. In the cast of bitcasts, the element
554f4a2713aSLionel Sambuc   // count may be mismatched; don't attempt to handle that here.
555f4a2713aSLionel Sambuc   if ((isa<ConstantVector>(V) || isa<ConstantDataVector>(V)) &&
556f4a2713aSLionel Sambuc       DestTy->isVectorTy() &&
557f4a2713aSLionel Sambuc       DestTy->getVectorNumElements() == V->getType()->getVectorNumElements()) {
558f4a2713aSLionel Sambuc     SmallVector<Constant*, 16> res;
559f4a2713aSLionel Sambuc     VectorType *DestVecTy = cast<VectorType>(DestTy);
560f4a2713aSLionel Sambuc     Type *DstEltTy = DestVecTy->getElementType();
561f4a2713aSLionel Sambuc     Type *Ty = IntegerType::get(V->getContext(), 32);
562f4a2713aSLionel Sambuc     for (unsigned i = 0, e = V->getType()->getVectorNumElements(); i != e; ++i) {
563f4a2713aSLionel Sambuc       Constant *C =
564f4a2713aSLionel Sambuc         ConstantExpr::getExtractElement(V, ConstantInt::get(Ty, i));
565f4a2713aSLionel Sambuc       res.push_back(ConstantExpr::getCast(opc, C, DstEltTy));
566f4a2713aSLionel Sambuc     }
567f4a2713aSLionel Sambuc     return ConstantVector::get(res);
568f4a2713aSLionel Sambuc   }
569f4a2713aSLionel Sambuc 
570f4a2713aSLionel Sambuc   // We actually have to do a cast now. Perform the cast according to the
571f4a2713aSLionel Sambuc   // opcode specified.
572f4a2713aSLionel Sambuc   switch (opc) {
573f4a2713aSLionel Sambuc   default:
574f4a2713aSLionel Sambuc     llvm_unreachable("Failed to cast constant expression");
575f4a2713aSLionel Sambuc   case Instruction::FPTrunc:
576f4a2713aSLionel Sambuc   case Instruction::FPExt:
577f4a2713aSLionel Sambuc     if (ConstantFP *FPC = dyn_cast<ConstantFP>(V)) {
578f4a2713aSLionel Sambuc       bool ignored;
579f4a2713aSLionel Sambuc       APFloat Val = FPC->getValueAPF();
580f4a2713aSLionel Sambuc       Val.convert(DestTy->isHalfTy() ? APFloat::IEEEhalf :
581f4a2713aSLionel Sambuc                   DestTy->isFloatTy() ? APFloat::IEEEsingle :
582f4a2713aSLionel Sambuc                   DestTy->isDoubleTy() ? APFloat::IEEEdouble :
583f4a2713aSLionel Sambuc                   DestTy->isX86_FP80Ty() ? APFloat::x87DoubleExtended :
584f4a2713aSLionel Sambuc                   DestTy->isFP128Ty() ? APFloat::IEEEquad :
585f4a2713aSLionel Sambuc                   DestTy->isPPC_FP128Ty() ? APFloat::PPCDoubleDouble :
586f4a2713aSLionel Sambuc                   APFloat::Bogus,
587f4a2713aSLionel Sambuc                   APFloat::rmNearestTiesToEven, &ignored);
588f4a2713aSLionel Sambuc       return ConstantFP::get(V->getContext(), Val);
589f4a2713aSLionel Sambuc     }
590*0a6a1f1dSLionel Sambuc     return nullptr; // Can't fold.
591f4a2713aSLionel Sambuc   case Instruction::FPToUI:
592f4a2713aSLionel Sambuc   case Instruction::FPToSI:
593f4a2713aSLionel Sambuc     if (ConstantFP *FPC = dyn_cast<ConstantFP>(V)) {
594f4a2713aSLionel Sambuc       const APFloat &V = FPC->getValueAPF();
595f4a2713aSLionel Sambuc       bool ignored;
596f4a2713aSLionel Sambuc       uint64_t x[2];
597f4a2713aSLionel Sambuc       uint32_t DestBitWidth = cast<IntegerType>(DestTy)->getBitWidth();
598*0a6a1f1dSLionel Sambuc       if (APFloat::opInvalidOp ==
599*0a6a1f1dSLionel Sambuc           V.convertToInteger(x, DestBitWidth, opc==Instruction::FPToSI,
600*0a6a1f1dSLionel Sambuc                              APFloat::rmTowardZero, &ignored)) {
601*0a6a1f1dSLionel Sambuc         // Undefined behavior invoked - the destination type can't represent
602*0a6a1f1dSLionel Sambuc         // the input constant.
603*0a6a1f1dSLionel Sambuc         return UndefValue::get(DestTy);
604*0a6a1f1dSLionel Sambuc       }
605f4a2713aSLionel Sambuc       APInt Val(DestBitWidth, x);
606f4a2713aSLionel Sambuc       return ConstantInt::get(FPC->getContext(), Val);
607f4a2713aSLionel Sambuc     }
608*0a6a1f1dSLionel Sambuc     return nullptr; // Can't fold.
609f4a2713aSLionel Sambuc   case Instruction::IntToPtr:   //always treated as unsigned
610f4a2713aSLionel Sambuc     if (V->isNullValue())       // Is it an integral null value?
611f4a2713aSLionel Sambuc       return ConstantPointerNull::get(cast<PointerType>(DestTy));
612*0a6a1f1dSLionel Sambuc     return nullptr;                   // Other pointer types cannot be casted
613f4a2713aSLionel Sambuc   case Instruction::PtrToInt:   // always treated as unsigned
614f4a2713aSLionel Sambuc     // Is it a null pointer value?
615f4a2713aSLionel Sambuc     if (V->isNullValue())
616f4a2713aSLionel Sambuc       return ConstantInt::get(DestTy, 0);
617f4a2713aSLionel Sambuc     // If this is a sizeof-like expression, pull out multiplications by
618f4a2713aSLionel Sambuc     // known factors to expose them to subsequent folding. If it's an
619f4a2713aSLionel Sambuc     // alignof-like expression, factor out known factors.
620f4a2713aSLionel Sambuc     if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
621f4a2713aSLionel Sambuc       if (CE->getOpcode() == Instruction::GetElementPtr &&
622f4a2713aSLionel Sambuc           CE->getOperand(0)->isNullValue()) {
623f4a2713aSLionel Sambuc         Type *Ty =
624f4a2713aSLionel Sambuc           cast<PointerType>(CE->getOperand(0)->getType())->getElementType();
625f4a2713aSLionel Sambuc         if (CE->getNumOperands() == 2) {
626f4a2713aSLionel Sambuc           // Handle a sizeof-like expression.
627f4a2713aSLionel Sambuc           Constant *Idx = CE->getOperand(1);
628f4a2713aSLionel Sambuc           bool isOne = isa<ConstantInt>(Idx) && cast<ConstantInt>(Idx)->isOne();
629f4a2713aSLionel Sambuc           if (Constant *C = getFoldedSizeOf(Ty, DestTy, !isOne)) {
630f4a2713aSLionel Sambuc             Idx = ConstantExpr::getCast(CastInst::getCastOpcode(Idx, true,
631f4a2713aSLionel Sambuc                                                                 DestTy, false),
632f4a2713aSLionel Sambuc                                         Idx, DestTy);
633f4a2713aSLionel Sambuc             return ConstantExpr::getMul(C, Idx);
634f4a2713aSLionel Sambuc           }
635f4a2713aSLionel Sambuc         } else if (CE->getNumOperands() == 3 &&
636f4a2713aSLionel Sambuc                    CE->getOperand(1)->isNullValue()) {
637f4a2713aSLionel Sambuc           // Handle an alignof-like expression.
638f4a2713aSLionel Sambuc           if (StructType *STy = dyn_cast<StructType>(Ty))
639f4a2713aSLionel Sambuc             if (!STy->isPacked()) {
640f4a2713aSLionel Sambuc               ConstantInt *CI = cast<ConstantInt>(CE->getOperand(2));
641f4a2713aSLionel Sambuc               if (CI->isOne() &&
642f4a2713aSLionel Sambuc                   STy->getNumElements() == 2 &&
643f4a2713aSLionel Sambuc                   STy->getElementType(0)->isIntegerTy(1)) {
644f4a2713aSLionel Sambuc                 return getFoldedAlignOf(STy->getElementType(1), DestTy, false);
645f4a2713aSLionel Sambuc               }
646f4a2713aSLionel Sambuc             }
647f4a2713aSLionel Sambuc           // Handle an offsetof-like expression.
648f4a2713aSLionel Sambuc           if (Ty->isStructTy() || Ty->isArrayTy()) {
649f4a2713aSLionel Sambuc             if (Constant *C = getFoldedOffsetOf(Ty, CE->getOperand(2),
650f4a2713aSLionel Sambuc                                                 DestTy, false))
651f4a2713aSLionel Sambuc               return C;
652f4a2713aSLionel Sambuc           }
653f4a2713aSLionel Sambuc         }
654f4a2713aSLionel Sambuc       }
655f4a2713aSLionel Sambuc     // Other pointer types cannot be casted
656*0a6a1f1dSLionel Sambuc     return nullptr;
657f4a2713aSLionel Sambuc   case Instruction::UIToFP:
658f4a2713aSLionel Sambuc   case Instruction::SIToFP:
659f4a2713aSLionel Sambuc     if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
660f4a2713aSLionel Sambuc       APInt api = CI->getValue();
661f4a2713aSLionel Sambuc       APFloat apf(DestTy->getFltSemantics(),
662f4a2713aSLionel Sambuc                   APInt::getNullValue(DestTy->getPrimitiveSizeInBits()));
663*0a6a1f1dSLionel Sambuc       if (APFloat::opOverflow &
664*0a6a1f1dSLionel Sambuc           apf.convertFromAPInt(api, opc==Instruction::SIToFP,
665*0a6a1f1dSLionel Sambuc                               APFloat::rmNearestTiesToEven)) {
666*0a6a1f1dSLionel Sambuc         // Undefined behavior invoked - the destination type can't represent
667*0a6a1f1dSLionel Sambuc         // the input constant.
668*0a6a1f1dSLionel Sambuc         return UndefValue::get(DestTy);
669*0a6a1f1dSLionel Sambuc       }
670f4a2713aSLionel Sambuc       return ConstantFP::get(V->getContext(), apf);
671f4a2713aSLionel Sambuc     }
672*0a6a1f1dSLionel Sambuc     return nullptr;
673f4a2713aSLionel Sambuc   case Instruction::ZExt:
674f4a2713aSLionel Sambuc     if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
675f4a2713aSLionel Sambuc       uint32_t BitWidth = cast<IntegerType>(DestTy)->getBitWidth();
676f4a2713aSLionel Sambuc       return ConstantInt::get(V->getContext(),
677f4a2713aSLionel Sambuc                               CI->getValue().zext(BitWidth));
678f4a2713aSLionel Sambuc     }
679*0a6a1f1dSLionel Sambuc     return nullptr;
680f4a2713aSLionel Sambuc   case Instruction::SExt:
681f4a2713aSLionel Sambuc     if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
682f4a2713aSLionel Sambuc       uint32_t BitWidth = cast<IntegerType>(DestTy)->getBitWidth();
683f4a2713aSLionel Sambuc       return ConstantInt::get(V->getContext(),
684f4a2713aSLionel Sambuc                               CI->getValue().sext(BitWidth));
685f4a2713aSLionel Sambuc     }
686*0a6a1f1dSLionel Sambuc     return nullptr;
687f4a2713aSLionel Sambuc   case Instruction::Trunc: {
688*0a6a1f1dSLionel Sambuc     if (V->getType()->isVectorTy())
689*0a6a1f1dSLionel Sambuc       return nullptr;
690*0a6a1f1dSLionel Sambuc 
691f4a2713aSLionel Sambuc     uint32_t DestBitWidth = cast<IntegerType>(DestTy)->getBitWidth();
692f4a2713aSLionel Sambuc     if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
693f4a2713aSLionel Sambuc       return ConstantInt::get(V->getContext(),
694f4a2713aSLionel Sambuc                               CI->getValue().trunc(DestBitWidth));
695f4a2713aSLionel Sambuc     }
696f4a2713aSLionel Sambuc 
697f4a2713aSLionel Sambuc     // The input must be a constantexpr.  See if we can simplify this based on
698f4a2713aSLionel Sambuc     // the bytes we are demanding.  Only do this if the source and dest are an
699f4a2713aSLionel Sambuc     // even multiple of a byte.
700f4a2713aSLionel Sambuc     if ((DestBitWidth & 7) == 0 &&
701f4a2713aSLionel Sambuc         (cast<IntegerType>(V->getType())->getBitWidth() & 7) == 0)
702f4a2713aSLionel Sambuc       if (Constant *Res = ExtractConstantBytes(V, 0, DestBitWidth / 8))
703f4a2713aSLionel Sambuc         return Res;
704f4a2713aSLionel Sambuc 
705*0a6a1f1dSLionel Sambuc     return nullptr;
706f4a2713aSLionel Sambuc   }
707f4a2713aSLionel Sambuc   case Instruction::BitCast:
708f4a2713aSLionel Sambuc     return FoldBitCast(V, DestTy);
709f4a2713aSLionel Sambuc   case Instruction::AddrSpaceCast:
710*0a6a1f1dSLionel Sambuc     return nullptr;
711f4a2713aSLionel Sambuc   }
712f4a2713aSLionel Sambuc }
713f4a2713aSLionel Sambuc 
ConstantFoldSelectInstruction(Constant * Cond,Constant * V1,Constant * V2)714f4a2713aSLionel Sambuc Constant *llvm::ConstantFoldSelectInstruction(Constant *Cond,
715f4a2713aSLionel Sambuc                                               Constant *V1, Constant *V2) {
716f4a2713aSLionel Sambuc   // Check for i1 and vector true/false conditions.
717f4a2713aSLionel Sambuc   if (Cond->isNullValue()) return V2;
718f4a2713aSLionel Sambuc   if (Cond->isAllOnesValue()) return V1;
719f4a2713aSLionel Sambuc 
720f4a2713aSLionel Sambuc   // If the condition is a vector constant, fold the result elementwise.
721f4a2713aSLionel Sambuc   if (ConstantVector *CondV = dyn_cast<ConstantVector>(Cond)) {
722f4a2713aSLionel Sambuc     SmallVector<Constant*, 16> Result;
723f4a2713aSLionel Sambuc     Type *Ty = IntegerType::get(CondV->getContext(), 32);
724f4a2713aSLionel Sambuc     for (unsigned i = 0, e = V1->getType()->getVectorNumElements(); i != e;++i){
725*0a6a1f1dSLionel Sambuc       Constant *V;
726*0a6a1f1dSLionel Sambuc       Constant *V1Element = ConstantExpr::getExtractElement(V1,
727*0a6a1f1dSLionel Sambuc                                                     ConstantInt::get(Ty, i));
728*0a6a1f1dSLionel Sambuc       Constant *V2Element = ConstantExpr::getExtractElement(V2,
729*0a6a1f1dSLionel Sambuc                                                     ConstantInt::get(Ty, i));
730*0a6a1f1dSLionel Sambuc       Constant *Cond = dyn_cast<Constant>(CondV->getOperand(i));
731*0a6a1f1dSLionel Sambuc       if (V1Element == V2Element) {
732*0a6a1f1dSLionel Sambuc         V = V1Element;
733*0a6a1f1dSLionel Sambuc       } else if (isa<UndefValue>(Cond)) {
734*0a6a1f1dSLionel Sambuc         V = isa<UndefValue>(V1Element) ? V1Element : V2Element;
735*0a6a1f1dSLionel Sambuc       } else {
736*0a6a1f1dSLionel Sambuc         if (!isa<ConstantInt>(Cond)) break;
737*0a6a1f1dSLionel Sambuc         V = Cond->isNullValue() ? V2Element : V1Element;
738*0a6a1f1dSLionel Sambuc       }
739*0a6a1f1dSLionel Sambuc       Result.push_back(V);
740f4a2713aSLionel Sambuc     }
741f4a2713aSLionel Sambuc 
742f4a2713aSLionel Sambuc     // If we were able to build the vector, return it.
743f4a2713aSLionel Sambuc     if (Result.size() == V1->getType()->getVectorNumElements())
744f4a2713aSLionel Sambuc       return ConstantVector::get(Result);
745f4a2713aSLionel Sambuc   }
746f4a2713aSLionel Sambuc 
747f4a2713aSLionel Sambuc   if (isa<UndefValue>(Cond)) {
748f4a2713aSLionel Sambuc     if (isa<UndefValue>(V1)) return V1;
749f4a2713aSLionel Sambuc     return V2;
750f4a2713aSLionel Sambuc   }
751f4a2713aSLionel Sambuc   if (isa<UndefValue>(V1)) return V2;
752f4a2713aSLionel Sambuc   if (isa<UndefValue>(V2)) return V1;
753f4a2713aSLionel Sambuc   if (V1 == V2) return V1;
754f4a2713aSLionel Sambuc 
755f4a2713aSLionel Sambuc   if (ConstantExpr *TrueVal = dyn_cast<ConstantExpr>(V1)) {
756f4a2713aSLionel Sambuc     if (TrueVal->getOpcode() == Instruction::Select)
757f4a2713aSLionel Sambuc       if (TrueVal->getOperand(0) == Cond)
758f4a2713aSLionel Sambuc         return ConstantExpr::getSelect(Cond, TrueVal->getOperand(1), V2);
759f4a2713aSLionel Sambuc   }
760f4a2713aSLionel Sambuc   if (ConstantExpr *FalseVal = dyn_cast<ConstantExpr>(V2)) {
761f4a2713aSLionel Sambuc     if (FalseVal->getOpcode() == Instruction::Select)
762f4a2713aSLionel Sambuc       if (FalseVal->getOperand(0) == Cond)
763f4a2713aSLionel Sambuc         return ConstantExpr::getSelect(Cond, V1, FalseVal->getOperand(2));
764f4a2713aSLionel Sambuc   }
765f4a2713aSLionel Sambuc 
766*0a6a1f1dSLionel Sambuc   return nullptr;
767f4a2713aSLionel Sambuc }
768f4a2713aSLionel Sambuc 
ConstantFoldExtractElementInstruction(Constant * Val,Constant * Idx)769f4a2713aSLionel Sambuc Constant *llvm::ConstantFoldExtractElementInstruction(Constant *Val,
770f4a2713aSLionel Sambuc                                                       Constant *Idx) {
771f4a2713aSLionel Sambuc   if (isa<UndefValue>(Val))  // ee(undef, x) -> undef
772f4a2713aSLionel Sambuc     return UndefValue::get(Val->getType()->getVectorElementType());
773f4a2713aSLionel Sambuc   if (Val->isNullValue())  // ee(zero, x) -> zero
774f4a2713aSLionel Sambuc     return Constant::getNullValue(Val->getType()->getVectorElementType());
775f4a2713aSLionel Sambuc   // ee({w,x,y,z}, undef) -> undef
776f4a2713aSLionel Sambuc   if (isa<UndefValue>(Idx))
777f4a2713aSLionel Sambuc     return UndefValue::get(Val->getType()->getVectorElementType());
778f4a2713aSLionel Sambuc 
779f4a2713aSLionel Sambuc   if (ConstantInt *CIdx = dyn_cast<ConstantInt>(Idx)) {
780f4a2713aSLionel Sambuc     uint64_t Index = CIdx->getZExtValue();
781f4a2713aSLionel Sambuc     // ee({w,x,y,z}, wrong_value) -> undef
782f4a2713aSLionel Sambuc     if (Index >= Val->getType()->getVectorNumElements())
783f4a2713aSLionel Sambuc       return UndefValue::get(Val->getType()->getVectorElementType());
784f4a2713aSLionel Sambuc     return Val->getAggregateElement(Index);
785f4a2713aSLionel Sambuc   }
786*0a6a1f1dSLionel Sambuc   return nullptr;
787f4a2713aSLionel Sambuc }
788f4a2713aSLionel Sambuc 
ConstantFoldInsertElementInstruction(Constant * Val,Constant * Elt,Constant * Idx)789f4a2713aSLionel Sambuc Constant *llvm::ConstantFoldInsertElementInstruction(Constant *Val,
790f4a2713aSLionel Sambuc                                                      Constant *Elt,
791f4a2713aSLionel Sambuc                                                      Constant *Idx) {
792f4a2713aSLionel Sambuc   ConstantInt *CIdx = dyn_cast<ConstantInt>(Idx);
793*0a6a1f1dSLionel Sambuc   if (!CIdx) return nullptr;
794f4a2713aSLionel Sambuc   const APInt &IdxVal = CIdx->getValue();
795f4a2713aSLionel Sambuc 
796f4a2713aSLionel Sambuc   SmallVector<Constant*, 16> Result;
797f4a2713aSLionel Sambuc   Type *Ty = IntegerType::get(Val->getContext(), 32);
798f4a2713aSLionel Sambuc   for (unsigned i = 0, e = Val->getType()->getVectorNumElements(); i != e; ++i){
799f4a2713aSLionel Sambuc     if (i == IdxVal) {
800f4a2713aSLionel Sambuc       Result.push_back(Elt);
801f4a2713aSLionel Sambuc       continue;
802f4a2713aSLionel Sambuc     }
803f4a2713aSLionel Sambuc 
804f4a2713aSLionel Sambuc     Constant *C =
805f4a2713aSLionel Sambuc       ConstantExpr::getExtractElement(Val, ConstantInt::get(Ty, i));
806f4a2713aSLionel Sambuc     Result.push_back(C);
807f4a2713aSLionel Sambuc   }
808f4a2713aSLionel Sambuc 
809f4a2713aSLionel Sambuc   return ConstantVector::get(Result);
810f4a2713aSLionel Sambuc }
811f4a2713aSLionel Sambuc 
ConstantFoldShuffleVectorInstruction(Constant * V1,Constant * V2,Constant * Mask)812f4a2713aSLionel Sambuc Constant *llvm::ConstantFoldShuffleVectorInstruction(Constant *V1,
813f4a2713aSLionel Sambuc                                                      Constant *V2,
814f4a2713aSLionel Sambuc                                                      Constant *Mask) {
815f4a2713aSLionel Sambuc   unsigned MaskNumElts = Mask->getType()->getVectorNumElements();
816f4a2713aSLionel Sambuc   Type *EltTy = V1->getType()->getVectorElementType();
817f4a2713aSLionel Sambuc 
818f4a2713aSLionel Sambuc   // Undefined shuffle mask -> undefined value.
819f4a2713aSLionel Sambuc   if (isa<UndefValue>(Mask))
820f4a2713aSLionel Sambuc     return UndefValue::get(VectorType::get(EltTy, MaskNumElts));
821f4a2713aSLionel Sambuc 
822f4a2713aSLionel Sambuc   // Don't break the bitcode reader hack.
823*0a6a1f1dSLionel Sambuc   if (isa<ConstantExpr>(Mask)) return nullptr;
824f4a2713aSLionel Sambuc 
825f4a2713aSLionel Sambuc   unsigned SrcNumElts = V1->getType()->getVectorNumElements();
826f4a2713aSLionel Sambuc 
827f4a2713aSLionel Sambuc   // Loop over the shuffle mask, evaluating each element.
828f4a2713aSLionel Sambuc   SmallVector<Constant*, 32> Result;
829f4a2713aSLionel Sambuc   for (unsigned i = 0; i != MaskNumElts; ++i) {
830f4a2713aSLionel Sambuc     int Elt = ShuffleVectorInst::getMaskValue(Mask, i);
831f4a2713aSLionel Sambuc     if (Elt == -1) {
832f4a2713aSLionel Sambuc       Result.push_back(UndefValue::get(EltTy));
833f4a2713aSLionel Sambuc       continue;
834f4a2713aSLionel Sambuc     }
835f4a2713aSLionel Sambuc     Constant *InElt;
836f4a2713aSLionel Sambuc     if (unsigned(Elt) >= SrcNumElts*2)
837f4a2713aSLionel Sambuc       InElt = UndefValue::get(EltTy);
838f4a2713aSLionel Sambuc     else if (unsigned(Elt) >= SrcNumElts) {
839f4a2713aSLionel Sambuc       Type *Ty = IntegerType::get(V2->getContext(), 32);
840f4a2713aSLionel Sambuc       InElt =
841f4a2713aSLionel Sambuc         ConstantExpr::getExtractElement(V2,
842f4a2713aSLionel Sambuc                                         ConstantInt::get(Ty, Elt - SrcNumElts));
843f4a2713aSLionel Sambuc     } else {
844f4a2713aSLionel Sambuc       Type *Ty = IntegerType::get(V1->getContext(), 32);
845f4a2713aSLionel Sambuc       InElt = ConstantExpr::getExtractElement(V1, ConstantInt::get(Ty, Elt));
846f4a2713aSLionel Sambuc     }
847f4a2713aSLionel Sambuc     Result.push_back(InElt);
848f4a2713aSLionel Sambuc   }
849f4a2713aSLionel Sambuc 
850f4a2713aSLionel Sambuc   return ConstantVector::get(Result);
851f4a2713aSLionel Sambuc }
852f4a2713aSLionel Sambuc 
ConstantFoldExtractValueInstruction(Constant * Agg,ArrayRef<unsigned> Idxs)853f4a2713aSLionel Sambuc Constant *llvm::ConstantFoldExtractValueInstruction(Constant *Agg,
854f4a2713aSLionel Sambuc                                                     ArrayRef<unsigned> Idxs) {
855f4a2713aSLionel Sambuc   // Base case: no indices, so return the entire value.
856f4a2713aSLionel Sambuc   if (Idxs.empty())
857f4a2713aSLionel Sambuc     return Agg;
858f4a2713aSLionel Sambuc 
859f4a2713aSLionel Sambuc   if (Constant *C = Agg->getAggregateElement(Idxs[0]))
860f4a2713aSLionel Sambuc     return ConstantFoldExtractValueInstruction(C, Idxs.slice(1));
861f4a2713aSLionel Sambuc 
862*0a6a1f1dSLionel Sambuc   return nullptr;
863f4a2713aSLionel Sambuc }
864f4a2713aSLionel Sambuc 
ConstantFoldInsertValueInstruction(Constant * Agg,Constant * Val,ArrayRef<unsigned> Idxs)865f4a2713aSLionel Sambuc Constant *llvm::ConstantFoldInsertValueInstruction(Constant *Agg,
866f4a2713aSLionel Sambuc                                                    Constant *Val,
867f4a2713aSLionel Sambuc                                                    ArrayRef<unsigned> Idxs) {
868f4a2713aSLionel Sambuc   // Base case: no indices, so replace the entire value.
869f4a2713aSLionel Sambuc   if (Idxs.empty())
870f4a2713aSLionel Sambuc     return Val;
871f4a2713aSLionel Sambuc 
872f4a2713aSLionel Sambuc   unsigned NumElts;
873f4a2713aSLionel Sambuc   if (StructType *ST = dyn_cast<StructType>(Agg->getType()))
874f4a2713aSLionel Sambuc     NumElts = ST->getNumElements();
875f4a2713aSLionel Sambuc   else if (ArrayType *AT = dyn_cast<ArrayType>(Agg->getType()))
876f4a2713aSLionel Sambuc     NumElts = AT->getNumElements();
877f4a2713aSLionel Sambuc   else
878f4a2713aSLionel Sambuc     NumElts = Agg->getType()->getVectorNumElements();
879f4a2713aSLionel Sambuc 
880f4a2713aSLionel Sambuc   SmallVector<Constant*, 32> Result;
881f4a2713aSLionel Sambuc   for (unsigned i = 0; i != NumElts; ++i) {
882f4a2713aSLionel Sambuc     Constant *C = Agg->getAggregateElement(i);
883*0a6a1f1dSLionel Sambuc     if (!C) return nullptr;
884f4a2713aSLionel Sambuc 
885f4a2713aSLionel Sambuc     if (Idxs[0] == i)
886f4a2713aSLionel Sambuc       C = ConstantFoldInsertValueInstruction(C, Val, Idxs.slice(1));
887f4a2713aSLionel Sambuc 
888f4a2713aSLionel Sambuc     Result.push_back(C);
889f4a2713aSLionel Sambuc   }
890f4a2713aSLionel Sambuc 
891f4a2713aSLionel Sambuc   if (StructType *ST = dyn_cast<StructType>(Agg->getType()))
892f4a2713aSLionel Sambuc     return ConstantStruct::get(ST, Result);
893f4a2713aSLionel Sambuc   if (ArrayType *AT = dyn_cast<ArrayType>(Agg->getType()))
894f4a2713aSLionel Sambuc     return ConstantArray::get(AT, Result);
895f4a2713aSLionel Sambuc   return ConstantVector::get(Result);
896f4a2713aSLionel Sambuc }
897f4a2713aSLionel Sambuc 
898f4a2713aSLionel Sambuc 
ConstantFoldBinaryInstruction(unsigned Opcode,Constant * C1,Constant * C2)899f4a2713aSLionel Sambuc Constant *llvm::ConstantFoldBinaryInstruction(unsigned Opcode,
900f4a2713aSLionel Sambuc                                               Constant *C1, Constant *C2) {
901f4a2713aSLionel Sambuc   // Handle UndefValue up front.
902f4a2713aSLionel Sambuc   if (isa<UndefValue>(C1) || isa<UndefValue>(C2)) {
903f4a2713aSLionel Sambuc     switch (Opcode) {
904f4a2713aSLionel Sambuc     case Instruction::Xor:
905f4a2713aSLionel Sambuc       if (isa<UndefValue>(C1) && isa<UndefValue>(C2))
906f4a2713aSLionel Sambuc         // Handle undef ^ undef -> 0 special case. This is a common
907f4a2713aSLionel Sambuc         // idiom (misuse).
908f4a2713aSLionel Sambuc         return Constant::getNullValue(C1->getType());
909f4a2713aSLionel Sambuc       // Fallthrough
910f4a2713aSLionel Sambuc     case Instruction::Add:
911f4a2713aSLionel Sambuc     case Instruction::Sub:
912f4a2713aSLionel Sambuc       return UndefValue::get(C1->getType());
913f4a2713aSLionel Sambuc     case Instruction::And:
914f4a2713aSLionel Sambuc       if (isa<UndefValue>(C1) && isa<UndefValue>(C2)) // undef & undef -> undef
915f4a2713aSLionel Sambuc         return C1;
916f4a2713aSLionel Sambuc       return Constant::getNullValue(C1->getType());   // undef & X -> 0
917f4a2713aSLionel Sambuc     case Instruction::Mul: {
918*0a6a1f1dSLionel Sambuc       // undef * undef -> undef
919*0a6a1f1dSLionel Sambuc       if (isa<UndefValue>(C1) && isa<UndefValue>(C2))
920*0a6a1f1dSLionel Sambuc         return C1;
921*0a6a1f1dSLionel Sambuc       const APInt *CV;
922*0a6a1f1dSLionel Sambuc       // X * undef -> undef   if X is odd
923*0a6a1f1dSLionel Sambuc       if (match(C1, m_APInt(CV)) || match(C2, m_APInt(CV)))
924*0a6a1f1dSLionel Sambuc         if ((*CV)[0])
925f4a2713aSLionel Sambuc           return UndefValue::get(C1->getType());
926f4a2713aSLionel Sambuc 
927f4a2713aSLionel Sambuc       // X * undef -> 0       otherwise
928f4a2713aSLionel Sambuc       return Constant::getNullValue(C1->getType());
929f4a2713aSLionel Sambuc     }
930f4a2713aSLionel Sambuc     case Instruction::SDiv:
931*0a6a1f1dSLionel Sambuc     case Instruction::UDiv:
932*0a6a1f1dSLionel Sambuc       // X / undef -> undef
933*0a6a1f1dSLionel Sambuc       if (match(C1, m_Zero()))
934*0a6a1f1dSLionel Sambuc         return C2;
935*0a6a1f1dSLionel Sambuc       // undef / 0 -> undef
936f4a2713aSLionel Sambuc       // undef / 1 -> undef
937*0a6a1f1dSLionel Sambuc       if (match(C2, m_Zero()) || match(C2, m_One()))
938f4a2713aSLionel Sambuc         return C1;
939*0a6a1f1dSLionel Sambuc       // undef / X -> 0       otherwise
940*0a6a1f1dSLionel Sambuc       return Constant::getNullValue(C1->getType());
941f4a2713aSLionel Sambuc     case Instruction::URem:
942f4a2713aSLionel Sambuc     case Instruction::SRem:
943*0a6a1f1dSLionel Sambuc       // X % undef -> undef
944*0a6a1f1dSLionel Sambuc       if (match(C2, m_Undef()))
945*0a6a1f1dSLionel Sambuc         return C2;
946*0a6a1f1dSLionel Sambuc       // undef % 0 -> undef
947*0a6a1f1dSLionel Sambuc       if (match(C2, m_Zero()))
948*0a6a1f1dSLionel Sambuc         return C1;
949*0a6a1f1dSLionel Sambuc       // undef % X -> 0       otherwise
950f4a2713aSLionel Sambuc       return Constant::getNullValue(C1->getType());
951f4a2713aSLionel Sambuc     case Instruction::Or:                          // X | undef -> -1
952f4a2713aSLionel Sambuc       if (isa<UndefValue>(C1) && isa<UndefValue>(C2)) // undef | undef -> undef
953f4a2713aSLionel Sambuc         return C1;
954f4a2713aSLionel Sambuc       return Constant::getAllOnesValue(C1->getType()); // undef | X -> ~0
955f4a2713aSLionel Sambuc     case Instruction::LShr:
956*0a6a1f1dSLionel Sambuc       // X >>l undef -> undef
957*0a6a1f1dSLionel Sambuc       if (isa<UndefValue>(C2))
958*0a6a1f1dSLionel Sambuc         return C2;
959*0a6a1f1dSLionel Sambuc       // undef >>l 0 -> undef
960*0a6a1f1dSLionel Sambuc       if (match(C2, m_Zero()))
961*0a6a1f1dSLionel Sambuc         return C1;
962*0a6a1f1dSLionel Sambuc       // undef >>l X -> 0
963*0a6a1f1dSLionel Sambuc       return Constant::getNullValue(C1->getType());
964f4a2713aSLionel Sambuc     case Instruction::AShr:
965*0a6a1f1dSLionel Sambuc       // X >>a undef -> undef
966*0a6a1f1dSLionel Sambuc       if (isa<UndefValue>(C2))
967*0a6a1f1dSLionel Sambuc         return C2;
968*0a6a1f1dSLionel Sambuc       // undef >>a 0 -> undef
969*0a6a1f1dSLionel Sambuc       if (match(C2, m_Zero()))
970*0a6a1f1dSLionel Sambuc         return C1;
971*0a6a1f1dSLionel Sambuc       // TODO: undef >>a X -> undef if the shift is exact
972*0a6a1f1dSLionel Sambuc       // undef >>a X -> 0
973*0a6a1f1dSLionel Sambuc       return Constant::getNullValue(C1->getType());
974f4a2713aSLionel Sambuc     case Instruction::Shl:
975*0a6a1f1dSLionel Sambuc       // X << undef -> undef
976*0a6a1f1dSLionel Sambuc       if (isa<UndefValue>(C2))
977*0a6a1f1dSLionel Sambuc         return C2;
978*0a6a1f1dSLionel Sambuc       // undef << 0 -> undef
979*0a6a1f1dSLionel Sambuc       if (match(C2, m_Zero()))
980*0a6a1f1dSLionel Sambuc         return C1;
981*0a6a1f1dSLionel Sambuc       // undef << X -> 0
982f4a2713aSLionel Sambuc       return Constant::getNullValue(C1->getType());
983f4a2713aSLionel Sambuc     }
984f4a2713aSLionel Sambuc   }
985f4a2713aSLionel Sambuc 
986f4a2713aSLionel Sambuc   // Handle simplifications when the RHS is a constant int.
987f4a2713aSLionel Sambuc   if (ConstantInt *CI2 = dyn_cast<ConstantInt>(C2)) {
988f4a2713aSLionel Sambuc     switch (Opcode) {
989f4a2713aSLionel Sambuc     case Instruction::Add:
990f4a2713aSLionel Sambuc       if (CI2->equalsInt(0)) return C1;                         // X + 0 == X
991f4a2713aSLionel Sambuc       break;
992f4a2713aSLionel Sambuc     case Instruction::Sub:
993f4a2713aSLionel Sambuc       if (CI2->equalsInt(0)) return C1;                         // X - 0 == X
994f4a2713aSLionel Sambuc       break;
995f4a2713aSLionel Sambuc     case Instruction::Mul:
996f4a2713aSLionel Sambuc       if (CI2->equalsInt(0)) return C2;                         // X * 0 == 0
997f4a2713aSLionel Sambuc       if (CI2->equalsInt(1))
998f4a2713aSLionel Sambuc         return C1;                                              // X * 1 == X
999f4a2713aSLionel Sambuc       break;
1000f4a2713aSLionel Sambuc     case Instruction::UDiv:
1001f4a2713aSLionel Sambuc     case Instruction::SDiv:
1002f4a2713aSLionel Sambuc       if (CI2->equalsInt(1))
1003f4a2713aSLionel Sambuc         return C1;                                            // X / 1 == X
1004f4a2713aSLionel Sambuc       if (CI2->equalsInt(0))
1005f4a2713aSLionel Sambuc         return UndefValue::get(CI2->getType());               // X / 0 == undef
1006f4a2713aSLionel Sambuc       break;
1007f4a2713aSLionel Sambuc     case Instruction::URem:
1008f4a2713aSLionel Sambuc     case Instruction::SRem:
1009f4a2713aSLionel Sambuc       if (CI2->equalsInt(1))
1010f4a2713aSLionel Sambuc         return Constant::getNullValue(CI2->getType());        // X % 1 == 0
1011f4a2713aSLionel Sambuc       if (CI2->equalsInt(0))
1012f4a2713aSLionel Sambuc         return UndefValue::get(CI2->getType());               // X % 0 == undef
1013f4a2713aSLionel Sambuc       break;
1014f4a2713aSLionel Sambuc     case Instruction::And:
1015f4a2713aSLionel Sambuc       if (CI2->isZero()) return C2;                           // X & 0 == 0
1016f4a2713aSLionel Sambuc       if (CI2->isAllOnesValue())
1017f4a2713aSLionel Sambuc         return C1;                                            // X & -1 == X
1018f4a2713aSLionel Sambuc 
1019f4a2713aSLionel Sambuc       if (ConstantExpr *CE1 = dyn_cast<ConstantExpr>(C1)) {
1020f4a2713aSLionel Sambuc         // (zext i32 to i64) & 4294967295 -> (zext i32 to i64)
1021f4a2713aSLionel Sambuc         if (CE1->getOpcode() == Instruction::ZExt) {
1022f4a2713aSLionel Sambuc           unsigned DstWidth = CI2->getType()->getBitWidth();
1023f4a2713aSLionel Sambuc           unsigned SrcWidth =
1024f4a2713aSLionel Sambuc             CE1->getOperand(0)->getType()->getPrimitiveSizeInBits();
1025f4a2713aSLionel Sambuc           APInt PossiblySetBits(APInt::getLowBitsSet(DstWidth, SrcWidth));
1026f4a2713aSLionel Sambuc           if ((PossiblySetBits & CI2->getValue()) == PossiblySetBits)
1027f4a2713aSLionel Sambuc             return C1;
1028f4a2713aSLionel Sambuc         }
1029f4a2713aSLionel Sambuc 
1030f4a2713aSLionel Sambuc         // If and'ing the address of a global with a constant, fold it.
1031f4a2713aSLionel Sambuc         if (CE1->getOpcode() == Instruction::PtrToInt &&
1032f4a2713aSLionel Sambuc             isa<GlobalValue>(CE1->getOperand(0))) {
1033f4a2713aSLionel Sambuc           GlobalValue *GV = cast<GlobalValue>(CE1->getOperand(0));
1034f4a2713aSLionel Sambuc 
1035f4a2713aSLionel Sambuc           // Functions are at least 4-byte aligned.
1036f4a2713aSLionel Sambuc           unsigned GVAlign = GV->getAlignment();
1037f4a2713aSLionel Sambuc           if (isa<Function>(GV))
1038f4a2713aSLionel Sambuc             GVAlign = std::max(GVAlign, 4U);
1039f4a2713aSLionel Sambuc 
1040f4a2713aSLionel Sambuc           if (GVAlign > 1) {
1041f4a2713aSLionel Sambuc             unsigned DstWidth = CI2->getType()->getBitWidth();
1042f4a2713aSLionel Sambuc             unsigned SrcWidth = std::min(DstWidth, Log2_32(GVAlign));
1043f4a2713aSLionel Sambuc             APInt BitsNotSet(APInt::getLowBitsSet(DstWidth, SrcWidth));
1044f4a2713aSLionel Sambuc 
1045f4a2713aSLionel Sambuc             // If checking bits we know are clear, return zero.
1046f4a2713aSLionel Sambuc             if ((CI2->getValue() & BitsNotSet) == CI2->getValue())
1047f4a2713aSLionel Sambuc               return Constant::getNullValue(CI2->getType());
1048f4a2713aSLionel Sambuc           }
1049f4a2713aSLionel Sambuc         }
1050f4a2713aSLionel Sambuc       }
1051f4a2713aSLionel Sambuc       break;
1052f4a2713aSLionel Sambuc     case Instruction::Or:
1053f4a2713aSLionel Sambuc       if (CI2->equalsInt(0)) return C1;    // X | 0 == X
1054f4a2713aSLionel Sambuc       if (CI2->isAllOnesValue())
1055f4a2713aSLionel Sambuc         return C2;                         // X | -1 == -1
1056f4a2713aSLionel Sambuc       break;
1057f4a2713aSLionel Sambuc     case Instruction::Xor:
1058f4a2713aSLionel Sambuc       if (CI2->equalsInt(0)) return C1;    // X ^ 0 == X
1059f4a2713aSLionel Sambuc 
1060f4a2713aSLionel Sambuc       if (ConstantExpr *CE1 = dyn_cast<ConstantExpr>(C1)) {
1061f4a2713aSLionel Sambuc         switch (CE1->getOpcode()) {
1062f4a2713aSLionel Sambuc         default: break;
1063f4a2713aSLionel Sambuc         case Instruction::ICmp:
1064f4a2713aSLionel Sambuc         case Instruction::FCmp:
1065f4a2713aSLionel Sambuc           // cmp pred ^ true -> cmp !pred
1066f4a2713aSLionel Sambuc           assert(CI2->equalsInt(1));
1067f4a2713aSLionel Sambuc           CmpInst::Predicate pred = (CmpInst::Predicate)CE1->getPredicate();
1068f4a2713aSLionel Sambuc           pred = CmpInst::getInversePredicate(pred);
1069f4a2713aSLionel Sambuc           return ConstantExpr::getCompare(pred, CE1->getOperand(0),
1070f4a2713aSLionel Sambuc                                           CE1->getOperand(1));
1071f4a2713aSLionel Sambuc         }
1072f4a2713aSLionel Sambuc       }
1073f4a2713aSLionel Sambuc       break;
1074f4a2713aSLionel Sambuc     case Instruction::AShr:
1075f4a2713aSLionel Sambuc       // ashr (zext C to Ty), C2 -> lshr (zext C, CSA), C2
1076f4a2713aSLionel Sambuc       if (ConstantExpr *CE1 = dyn_cast<ConstantExpr>(C1))
1077f4a2713aSLionel Sambuc         if (CE1->getOpcode() == Instruction::ZExt)  // Top bits known zero.
1078f4a2713aSLionel Sambuc           return ConstantExpr::getLShr(C1, C2);
1079f4a2713aSLionel Sambuc       break;
1080f4a2713aSLionel Sambuc     }
1081f4a2713aSLionel Sambuc   } else if (isa<ConstantInt>(C1)) {
1082f4a2713aSLionel Sambuc     // If C1 is a ConstantInt and C2 is not, swap the operands.
1083f4a2713aSLionel Sambuc     if (Instruction::isCommutative(Opcode))
1084f4a2713aSLionel Sambuc       return ConstantExpr::get(Opcode, C2, C1);
1085f4a2713aSLionel Sambuc   }
1086f4a2713aSLionel Sambuc 
1087f4a2713aSLionel Sambuc   // At this point we know neither constant is an UndefValue.
1088f4a2713aSLionel Sambuc   if (ConstantInt *CI1 = dyn_cast<ConstantInt>(C1)) {
1089f4a2713aSLionel Sambuc     if (ConstantInt *CI2 = dyn_cast<ConstantInt>(C2)) {
1090f4a2713aSLionel Sambuc       const APInt &C1V = CI1->getValue();
1091f4a2713aSLionel Sambuc       const APInt &C2V = CI2->getValue();
1092f4a2713aSLionel Sambuc       switch (Opcode) {
1093f4a2713aSLionel Sambuc       default:
1094f4a2713aSLionel Sambuc         break;
1095f4a2713aSLionel Sambuc       case Instruction::Add:
1096f4a2713aSLionel Sambuc         return ConstantInt::get(CI1->getContext(), C1V + C2V);
1097f4a2713aSLionel Sambuc       case Instruction::Sub:
1098f4a2713aSLionel Sambuc         return ConstantInt::get(CI1->getContext(), C1V - C2V);
1099f4a2713aSLionel Sambuc       case Instruction::Mul:
1100f4a2713aSLionel Sambuc         return ConstantInt::get(CI1->getContext(), C1V * C2V);
1101f4a2713aSLionel Sambuc       case Instruction::UDiv:
1102f4a2713aSLionel Sambuc         assert(!CI2->isNullValue() && "Div by zero handled above");
1103f4a2713aSLionel Sambuc         return ConstantInt::get(CI1->getContext(), C1V.udiv(C2V));
1104f4a2713aSLionel Sambuc       case Instruction::SDiv:
1105f4a2713aSLionel Sambuc         assert(!CI2->isNullValue() && "Div by zero handled above");
1106f4a2713aSLionel Sambuc         if (C2V.isAllOnesValue() && C1V.isMinSignedValue())
1107f4a2713aSLionel Sambuc           return UndefValue::get(CI1->getType());   // MIN_INT / -1 -> undef
1108f4a2713aSLionel Sambuc         return ConstantInt::get(CI1->getContext(), C1V.sdiv(C2V));
1109f4a2713aSLionel Sambuc       case Instruction::URem:
1110f4a2713aSLionel Sambuc         assert(!CI2->isNullValue() && "Div by zero handled above");
1111f4a2713aSLionel Sambuc         return ConstantInt::get(CI1->getContext(), C1V.urem(C2V));
1112f4a2713aSLionel Sambuc       case Instruction::SRem:
1113f4a2713aSLionel Sambuc         assert(!CI2->isNullValue() && "Div by zero handled above");
1114f4a2713aSLionel Sambuc         if (C2V.isAllOnesValue() && C1V.isMinSignedValue())
1115f4a2713aSLionel Sambuc           return UndefValue::get(CI1->getType());   // MIN_INT % -1 -> undef
1116f4a2713aSLionel Sambuc         return ConstantInt::get(CI1->getContext(), C1V.srem(C2V));
1117f4a2713aSLionel Sambuc       case Instruction::And:
1118f4a2713aSLionel Sambuc         return ConstantInt::get(CI1->getContext(), C1V & C2V);
1119f4a2713aSLionel Sambuc       case Instruction::Or:
1120f4a2713aSLionel Sambuc         return ConstantInt::get(CI1->getContext(), C1V | C2V);
1121f4a2713aSLionel Sambuc       case Instruction::Xor:
1122f4a2713aSLionel Sambuc         return ConstantInt::get(CI1->getContext(), C1V ^ C2V);
1123*0a6a1f1dSLionel Sambuc       case Instruction::Shl:
1124*0a6a1f1dSLionel Sambuc         if (C2V.ult(C1V.getBitWidth()))
1125*0a6a1f1dSLionel Sambuc           return ConstantInt::get(CI1->getContext(), C1V.shl(C2V));
1126f4a2713aSLionel Sambuc         return UndefValue::get(C1->getType()); // too big shift is undef
1127*0a6a1f1dSLionel Sambuc       case Instruction::LShr:
1128*0a6a1f1dSLionel Sambuc         if (C2V.ult(C1V.getBitWidth()))
1129*0a6a1f1dSLionel Sambuc           return ConstantInt::get(CI1->getContext(), C1V.lshr(C2V));
1130f4a2713aSLionel Sambuc         return UndefValue::get(C1->getType()); // too big shift is undef
1131*0a6a1f1dSLionel Sambuc       case Instruction::AShr:
1132*0a6a1f1dSLionel Sambuc         if (C2V.ult(C1V.getBitWidth()))
1133*0a6a1f1dSLionel Sambuc           return ConstantInt::get(CI1->getContext(), C1V.ashr(C2V));
1134f4a2713aSLionel Sambuc         return UndefValue::get(C1->getType()); // too big shift is undef
1135f4a2713aSLionel Sambuc       }
1136f4a2713aSLionel Sambuc     }
1137f4a2713aSLionel Sambuc 
1138f4a2713aSLionel Sambuc     switch (Opcode) {
1139f4a2713aSLionel Sambuc     case Instruction::SDiv:
1140f4a2713aSLionel Sambuc     case Instruction::UDiv:
1141f4a2713aSLionel Sambuc     case Instruction::URem:
1142f4a2713aSLionel Sambuc     case Instruction::SRem:
1143f4a2713aSLionel Sambuc     case Instruction::LShr:
1144f4a2713aSLionel Sambuc     case Instruction::AShr:
1145f4a2713aSLionel Sambuc     case Instruction::Shl:
1146f4a2713aSLionel Sambuc       if (CI1->equalsInt(0)) return C1;
1147f4a2713aSLionel Sambuc       break;
1148f4a2713aSLionel Sambuc     default:
1149f4a2713aSLionel Sambuc       break;
1150f4a2713aSLionel Sambuc     }
1151f4a2713aSLionel Sambuc   } else if (ConstantFP *CFP1 = dyn_cast<ConstantFP>(C1)) {
1152f4a2713aSLionel Sambuc     if (ConstantFP *CFP2 = dyn_cast<ConstantFP>(C2)) {
1153f4a2713aSLionel Sambuc       APFloat C1V = CFP1->getValueAPF();
1154f4a2713aSLionel Sambuc       APFloat C2V = CFP2->getValueAPF();
1155f4a2713aSLionel Sambuc       APFloat C3V = C1V;  // copy for modification
1156f4a2713aSLionel Sambuc       switch (Opcode) {
1157f4a2713aSLionel Sambuc       default:
1158f4a2713aSLionel Sambuc         break;
1159f4a2713aSLionel Sambuc       case Instruction::FAdd:
1160f4a2713aSLionel Sambuc         (void)C3V.add(C2V, APFloat::rmNearestTiesToEven);
1161f4a2713aSLionel Sambuc         return ConstantFP::get(C1->getContext(), C3V);
1162f4a2713aSLionel Sambuc       case Instruction::FSub:
1163f4a2713aSLionel Sambuc         (void)C3V.subtract(C2V, APFloat::rmNearestTiesToEven);
1164f4a2713aSLionel Sambuc         return ConstantFP::get(C1->getContext(), C3V);
1165f4a2713aSLionel Sambuc       case Instruction::FMul:
1166f4a2713aSLionel Sambuc         (void)C3V.multiply(C2V, APFloat::rmNearestTiesToEven);
1167f4a2713aSLionel Sambuc         return ConstantFP::get(C1->getContext(), C3V);
1168f4a2713aSLionel Sambuc       case Instruction::FDiv:
1169f4a2713aSLionel Sambuc         (void)C3V.divide(C2V, APFloat::rmNearestTiesToEven);
1170f4a2713aSLionel Sambuc         return ConstantFP::get(C1->getContext(), C3V);
1171f4a2713aSLionel Sambuc       case Instruction::FRem:
1172f4a2713aSLionel Sambuc         (void)C3V.mod(C2V, APFloat::rmNearestTiesToEven);
1173f4a2713aSLionel Sambuc         return ConstantFP::get(C1->getContext(), C3V);
1174f4a2713aSLionel Sambuc       }
1175f4a2713aSLionel Sambuc     }
1176f4a2713aSLionel Sambuc   } else if (VectorType *VTy = dyn_cast<VectorType>(C1->getType())) {
1177f4a2713aSLionel Sambuc     // Perform elementwise folding.
1178f4a2713aSLionel Sambuc     SmallVector<Constant*, 16> Result;
1179f4a2713aSLionel Sambuc     Type *Ty = IntegerType::get(VTy->getContext(), 32);
1180f4a2713aSLionel Sambuc     for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
1181f4a2713aSLionel Sambuc       Constant *LHS =
1182f4a2713aSLionel Sambuc         ConstantExpr::getExtractElement(C1, ConstantInt::get(Ty, i));
1183f4a2713aSLionel Sambuc       Constant *RHS =
1184f4a2713aSLionel Sambuc         ConstantExpr::getExtractElement(C2, ConstantInt::get(Ty, i));
1185f4a2713aSLionel Sambuc 
1186f4a2713aSLionel Sambuc       Result.push_back(ConstantExpr::get(Opcode, LHS, RHS));
1187f4a2713aSLionel Sambuc     }
1188f4a2713aSLionel Sambuc 
1189f4a2713aSLionel Sambuc     return ConstantVector::get(Result);
1190f4a2713aSLionel Sambuc   }
1191f4a2713aSLionel Sambuc 
1192f4a2713aSLionel Sambuc   if (ConstantExpr *CE1 = dyn_cast<ConstantExpr>(C1)) {
1193f4a2713aSLionel Sambuc     // There are many possible foldings we could do here.  We should probably
1194f4a2713aSLionel Sambuc     // at least fold add of a pointer with an integer into the appropriate
1195f4a2713aSLionel Sambuc     // getelementptr.  This will improve alias analysis a bit.
1196f4a2713aSLionel Sambuc 
1197f4a2713aSLionel Sambuc     // Given ((a + b) + c), if (b + c) folds to something interesting, return
1198f4a2713aSLionel Sambuc     // (a + (b + c)).
1199f4a2713aSLionel Sambuc     if (Instruction::isAssociative(Opcode) && CE1->getOpcode() == Opcode) {
1200f4a2713aSLionel Sambuc       Constant *T = ConstantExpr::get(Opcode, CE1->getOperand(1), C2);
1201f4a2713aSLionel Sambuc       if (!isa<ConstantExpr>(T) || cast<ConstantExpr>(T)->getOpcode() != Opcode)
1202f4a2713aSLionel Sambuc         return ConstantExpr::get(Opcode, CE1->getOperand(0), T);
1203f4a2713aSLionel Sambuc     }
1204f4a2713aSLionel Sambuc   } else if (isa<ConstantExpr>(C2)) {
1205f4a2713aSLionel Sambuc     // If C2 is a constant expr and C1 isn't, flop them around and fold the
1206f4a2713aSLionel Sambuc     // other way if possible.
1207f4a2713aSLionel Sambuc     if (Instruction::isCommutative(Opcode))
1208f4a2713aSLionel Sambuc       return ConstantFoldBinaryInstruction(Opcode, C2, C1);
1209f4a2713aSLionel Sambuc   }
1210f4a2713aSLionel Sambuc 
1211f4a2713aSLionel Sambuc   // i1 can be simplified in many cases.
1212f4a2713aSLionel Sambuc   if (C1->getType()->isIntegerTy(1)) {
1213f4a2713aSLionel Sambuc     switch (Opcode) {
1214f4a2713aSLionel Sambuc     case Instruction::Add:
1215f4a2713aSLionel Sambuc     case Instruction::Sub:
1216f4a2713aSLionel Sambuc       return ConstantExpr::getXor(C1, C2);
1217f4a2713aSLionel Sambuc     case Instruction::Mul:
1218f4a2713aSLionel Sambuc       return ConstantExpr::getAnd(C1, C2);
1219f4a2713aSLionel Sambuc     case Instruction::Shl:
1220f4a2713aSLionel Sambuc     case Instruction::LShr:
1221f4a2713aSLionel Sambuc     case Instruction::AShr:
1222f4a2713aSLionel Sambuc       // We can assume that C2 == 0.  If it were one the result would be
1223f4a2713aSLionel Sambuc       // undefined because the shift value is as large as the bitwidth.
1224f4a2713aSLionel Sambuc       return C1;
1225f4a2713aSLionel Sambuc     case Instruction::SDiv:
1226f4a2713aSLionel Sambuc     case Instruction::UDiv:
1227f4a2713aSLionel Sambuc       // We can assume that C2 == 1.  If it were zero the result would be
1228f4a2713aSLionel Sambuc       // undefined through division by zero.
1229f4a2713aSLionel Sambuc       return C1;
1230f4a2713aSLionel Sambuc     case Instruction::URem:
1231f4a2713aSLionel Sambuc     case Instruction::SRem:
1232f4a2713aSLionel Sambuc       // We can assume that C2 == 1.  If it were zero the result would be
1233f4a2713aSLionel Sambuc       // undefined through division by zero.
1234f4a2713aSLionel Sambuc       return ConstantInt::getFalse(C1->getContext());
1235f4a2713aSLionel Sambuc     default:
1236f4a2713aSLionel Sambuc       break;
1237f4a2713aSLionel Sambuc     }
1238f4a2713aSLionel Sambuc   }
1239f4a2713aSLionel Sambuc 
1240f4a2713aSLionel Sambuc   // We don't know how to fold this.
1241*0a6a1f1dSLionel Sambuc   return nullptr;
1242f4a2713aSLionel Sambuc }
1243f4a2713aSLionel Sambuc 
1244f4a2713aSLionel Sambuc /// isZeroSizedType - This type is zero sized if its an array or structure of
1245f4a2713aSLionel Sambuc /// zero sized types.  The only leaf zero sized type is an empty structure.
isMaybeZeroSizedType(Type * Ty)1246f4a2713aSLionel Sambuc static bool isMaybeZeroSizedType(Type *Ty) {
1247f4a2713aSLionel Sambuc   if (StructType *STy = dyn_cast<StructType>(Ty)) {
1248f4a2713aSLionel Sambuc     if (STy->isOpaque()) return true;  // Can't say.
1249f4a2713aSLionel Sambuc 
1250f4a2713aSLionel Sambuc     // If all of elements have zero size, this does too.
1251f4a2713aSLionel Sambuc     for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
1252f4a2713aSLionel Sambuc       if (!isMaybeZeroSizedType(STy->getElementType(i))) return false;
1253f4a2713aSLionel Sambuc     return true;
1254f4a2713aSLionel Sambuc 
1255f4a2713aSLionel Sambuc   } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1256f4a2713aSLionel Sambuc     return isMaybeZeroSizedType(ATy->getElementType());
1257f4a2713aSLionel Sambuc   }
1258f4a2713aSLionel Sambuc   return false;
1259f4a2713aSLionel Sambuc }
1260f4a2713aSLionel Sambuc 
1261f4a2713aSLionel Sambuc /// IdxCompare - Compare the two constants as though they were getelementptr
1262f4a2713aSLionel Sambuc /// indices.  This allows coersion of the types to be the same thing.
1263f4a2713aSLionel Sambuc ///
1264f4a2713aSLionel Sambuc /// If the two constants are the "same" (after coersion), return 0.  If the
1265f4a2713aSLionel Sambuc /// first is less than the second, return -1, if the second is less than the
1266f4a2713aSLionel Sambuc /// first, return 1.  If the constants are not integral, return -2.
1267f4a2713aSLionel Sambuc ///
IdxCompare(Constant * C1,Constant * C2,Type * ElTy)1268f4a2713aSLionel Sambuc static int IdxCompare(Constant *C1, Constant *C2, Type *ElTy) {
1269f4a2713aSLionel Sambuc   if (C1 == C2) return 0;
1270f4a2713aSLionel Sambuc 
1271f4a2713aSLionel Sambuc   // Ok, we found a different index.  If they are not ConstantInt, we can't do
1272f4a2713aSLionel Sambuc   // anything with them.
1273f4a2713aSLionel Sambuc   if (!isa<ConstantInt>(C1) || !isa<ConstantInt>(C2))
1274f4a2713aSLionel Sambuc     return -2; // don't know!
1275f4a2713aSLionel Sambuc 
1276f4a2713aSLionel Sambuc   // Ok, we have two differing integer indices.  Sign extend them to be the same
1277f4a2713aSLionel Sambuc   // type.  Long is always big enough, so we use it.
1278f4a2713aSLionel Sambuc   if (!C1->getType()->isIntegerTy(64))
1279f4a2713aSLionel Sambuc     C1 = ConstantExpr::getSExt(C1, Type::getInt64Ty(C1->getContext()));
1280f4a2713aSLionel Sambuc 
1281f4a2713aSLionel Sambuc   if (!C2->getType()->isIntegerTy(64))
1282f4a2713aSLionel Sambuc     C2 = ConstantExpr::getSExt(C2, Type::getInt64Ty(C1->getContext()));
1283f4a2713aSLionel Sambuc 
1284f4a2713aSLionel Sambuc   if (C1 == C2) return 0;  // They are equal
1285f4a2713aSLionel Sambuc 
1286f4a2713aSLionel Sambuc   // If the type being indexed over is really just a zero sized type, there is
1287f4a2713aSLionel Sambuc   // no pointer difference being made here.
1288f4a2713aSLionel Sambuc   if (isMaybeZeroSizedType(ElTy))
1289f4a2713aSLionel Sambuc     return -2; // dunno.
1290f4a2713aSLionel Sambuc 
1291f4a2713aSLionel Sambuc   // If they are really different, now that they are the same type, then we
1292f4a2713aSLionel Sambuc   // found a difference!
1293f4a2713aSLionel Sambuc   if (cast<ConstantInt>(C1)->getSExtValue() <
1294f4a2713aSLionel Sambuc       cast<ConstantInt>(C2)->getSExtValue())
1295f4a2713aSLionel Sambuc     return -1;
1296f4a2713aSLionel Sambuc   else
1297f4a2713aSLionel Sambuc     return 1;
1298f4a2713aSLionel Sambuc }
1299f4a2713aSLionel Sambuc 
1300f4a2713aSLionel Sambuc /// evaluateFCmpRelation - This function determines if there is anything we can
1301f4a2713aSLionel Sambuc /// decide about the two constants provided.  This doesn't need to handle simple
1302f4a2713aSLionel Sambuc /// things like ConstantFP comparisons, but should instead handle ConstantExprs.
1303f4a2713aSLionel Sambuc /// If we can determine that the two constants have a particular relation to
1304f4a2713aSLionel Sambuc /// each other, we should return the corresponding FCmpInst predicate,
1305f4a2713aSLionel Sambuc /// otherwise return FCmpInst::BAD_FCMP_PREDICATE. This is used below in
1306f4a2713aSLionel Sambuc /// ConstantFoldCompareInstruction.
1307f4a2713aSLionel Sambuc ///
1308f4a2713aSLionel Sambuc /// To simplify this code we canonicalize the relation so that the first
1309f4a2713aSLionel Sambuc /// operand is always the most "complex" of the two.  We consider ConstantFP
1310f4a2713aSLionel Sambuc /// to be the simplest, and ConstantExprs to be the most complex.
evaluateFCmpRelation(Constant * V1,Constant * V2)1311f4a2713aSLionel Sambuc static FCmpInst::Predicate evaluateFCmpRelation(Constant *V1, Constant *V2) {
1312f4a2713aSLionel Sambuc   assert(V1->getType() == V2->getType() &&
1313f4a2713aSLionel Sambuc          "Cannot compare values of different types!");
1314f4a2713aSLionel Sambuc 
1315f4a2713aSLionel Sambuc   // Handle degenerate case quickly
1316f4a2713aSLionel Sambuc   if (V1 == V2) return FCmpInst::FCMP_OEQ;
1317f4a2713aSLionel Sambuc 
1318f4a2713aSLionel Sambuc   if (!isa<ConstantExpr>(V1)) {
1319f4a2713aSLionel Sambuc     if (!isa<ConstantExpr>(V2)) {
1320f4a2713aSLionel Sambuc       // We distilled thisUse the standard constant folder for a few cases
1321*0a6a1f1dSLionel Sambuc       ConstantInt *R = nullptr;
1322f4a2713aSLionel Sambuc       R = dyn_cast<ConstantInt>(
1323f4a2713aSLionel Sambuc                       ConstantExpr::getFCmp(FCmpInst::FCMP_OEQ, V1, V2));
1324f4a2713aSLionel Sambuc       if (R && !R->isZero())
1325f4a2713aSLionel Sambuc         return FCmpInst::FCMP_OEQ;
1326f4a2713aSLionel Sambuc       R = dyn_cast<ConstantInt>(
1327f4a2713aSLionel Sambuc                       ConstantExpr::getFCmp(FCmpInst::FCMP_OLT, V1, V2));
1328f4a2713aSLionel Sambuc       if (R && !R->isZero())
1329f4a2713aSLionel Sambuc         return FCmpInst::FCMP_OLT;
1330f4a2713aSLionel Sambuc       R = dyn_cast<ConstantInt>(
1331f4a2713aSLionel Sambuc                       ConstantExpr::getFCmp(FCmpInst::FCMP_OGT, V1, V2));
1332f4a2713aSLionel Sambuc       if (R && !R->isZero())
1333f4a2713aSLionel Sambuc         return FCmpInst::FCMP_OGT;
1334f4a2713aSLionel Sambuc 
1335f4a2713aSLionel Sambuc       // Nothing more we can do
1336f4a2713aSLionel Sambuc       return FCmpInst::BAD_FCMP_PREDICATE;
1337f4a2713aSLionel Sambuc     }
1338f4a2713aSLionel Sambuc 
1339f4a2713aSLionel Sambuc     // If the first operand is simple and second is ConstantExpr, swap operands.
1340f4a2713aSLionel Sambuc     FCmpInst::Predicate SwappedRelation = evaluateFCmpRelation(V2, V1);
1341f4a2713aSLionel Sambuc     if (SwappedRelation != FCmpInst::BAD_FCMP_PREDICATE)
1342f4a2713aSLionel Sambuc       return FCmpInst::getSwappedPredicate(SwappedRelation);
1343f4a2713aSLionel Sambuc   } else {
1344f4a2713aSLionel Sambuc     // Ok, the LHS is known to be a constantexpr.  The RHS can be any of a
1345f4a2713aSLionel Sambuc     // constantexpr or a simple constant.
1346f4a2713aSLionel Sambuc     ConstantExpr *CE1 = cast<ConstantExpr>(V1);
1347f4a2713aSLionel Sambuc     switch (CE1->getOpcode()) {
1348f4a2713aSLionel Sambuc     case Instruction::FPTrunc:
1349f4a2713aSLionel Sambuc     case Instruction::FPExt:
1350f4a2713aSLionel Sambuc     case Instruction::UIToFP:
1351f4a2713aSLionel Sambuc     case Instruction::SIToFP:
1352f4a2713aSLionel Sambuc       // We might be able to do something with these but we don't right now.
1353f4a2713aSLionel Sambuc       break;
1354f4a2713aSLionel Sambuc     default:
1355f4a2713aSLionel Sambuc       break;
1356f4a2713aSLionel Sambuc     }
1357f4a2713aSLionel Sambuc   }
1358f4a2713aSLionel Sambuc   // There are MANY other foldings that we could perform here.  They will
1359f4a2713aSLionel Sambuc   // probably be added on demand, as they seem needed.
1360f4a2713aSLionel Sambuc   return FCmpInst::BAD_FCMP_PREDICATE;
1361f4a2713aSLionel Sambuc }
1362f4a2713aSLionel Sambuc 
areGlobalsPotentiallyEqual(const GlobalValue * GV1,const GlobalValue * GV2)1363*0a6a1f1dSLionel Sambuc static ICmpInst::Predicate areGlobalsPotentiallyEqual(const GlobalValue *GV1,
1364*0a6a1f1dSLionel Sambuc                                                       const GlobalValue *GV2) {
1365*0a6a1f1dSLionel Sambuc   auto isGlobalUnsafeForEquality = [](const GlobalValue *GV) {
1366*0a6a1f1dSLionel Sambuc     if (GV->hasExternalWeakLinkage() || GV->hasWeakAnyLinkage())
1367*0a6a1f1dSLionel Sambuc       return true;
1368*0a6a1f1dSLionel Sambuc     if (const auto *GVar = dyn_cast<GlobalVariable>(GV)) {
1369*0a6a1f1dSLionel Sambuc       Type *Ty = GVar->getType()->getPointerElementType();
1370*0a6a1f1dSLionel Sambuc       // A global with opaque type might end up being zero sized.
1371*0a6a1f1dSLionel Sambuc       if (!Ty->isSized())
1372*0a6a1f1dSLionel Sambuc         return true;
1373*0a6a1f1dSLionel Sambuc       // A global with an empty type might lie at the address of any other
1374*0a6a1f1dSLionel Sambuc       // global.
1375*0a6a1f1dSLionel Sambuc       if (Ty->isEmptyTy())
1376*0a6a1f1dSLionel Sambuc         return true;
1377*0a6a1f1dSLionel Sambuc     }
1378*0a6a1f1dSLionel Sambuc     return false;
1379*0a6a1f1dSLionel Sambuc   };
1380*0a6a1f1dSLionel Sambuc   // Don't try to decide equality of aliases.
1381*0a6a1f1dSLionel Sambuc   if (!isa<GlobalAlias>(GV1) && !isa<GlobalAlias>(GV2))
1382*0a6a1f1dSLionel Sambuc     if (!isGlobalUnsafeForEquality(GV1) && !isGlobalUnsafeForEquality(GV2))
1383*0a6a1f1dSLionel Sambuc       return ICmpInst::ICMP_NE;
1384*0a6a1f1dSLionel Sambuc   return ICmpInst::BAD_ICMP_PREDICATE;
1385*0a6a1f1dSLionel Sambuc }
1386*0a6a1f1dSLionel Sambuc 
1387f4a2713aSLionel Sambuc /// evaluateICmpRelation - This function determines if there is anything we can
1388f4a2713aSLionel Sambuc /// decide about the two constants provided.  This doesn't need to handle simple
1389f4a2713aSLionel Sambuc /// things like integer comparisons, but should instead handle ConstantExprs
1390f4a2713aSLionel Sambuc /// and GlobalValues.  If we can determine that the two constants have a
1391f4a2713aSLionel Sambuc /// particular relation to each other, we should return the corresponding ICmp
1392f4a2713aSLionel Sambuc /// predicate, otherwise return ICmpInst::BAD_ICMP_PREDICATE.
1393f4a2713aSLionel Sambuc ///
1394f4a2713aSLionel Sambuc /// To simplify this code we canonicalize the relation so that the first
1395f4a2713aSLionel Sambuc /// operand is always the most "complex" of the two.  We consider simple
1396f4a2713aSLionel Sambuc /// constants (like ConstantInt) to be the simplest, followed by
1397f4a2713aSLionel Sambuc /// GlobalValues, followed by ConstantExpr's (the most complex).
1398f4a2713aSLionel Sambuc ///
evaluateICmpRelation(Constant * V1,Constant * V2,bool isSigned)1399f4a2713aSLionel Sambuc static ICmpInst::Predicate evaluateICmpRelation(Constant *V1, Constant *V2,
1400f4a2713aSLionel Sambuc                                                 bool isSigned) {
1401f4a2713aSLionel Sambuc   assert(V1->getType() == V2->getType() &&
1402f4a2713aSLionel Sambuc          "Cannot compare different types of values!");
1403f4a2713aSLionel Sambuc   if (V1 == V2) return ICmpInst::ICMP_EQ;
1404f4a2713aSLionel Sambuc 
1405f4a2713aSLionel Sambuc   if (!isa<ConstantExpr>(V1) && !isa<GlobalValue>(V1) &&
1406f4a2713aSLionel Sambuc       !isa<BlockAddress>(V1)) {
1407f4a2713aSLionel Sambuc     if (!isa<GlobalValue>(V2) && !isa<ConstantExpr>(V2) &&
1408f4a2713aSLionel Sambuc         !isa<BlockAddress>(V2)) {
1409f4a2713aSLionel Sambuc       // We distilled this down to a simple case, use the standard constant
1410f4a2713aSLionel Sambuc       // folder.
1411*0a6a1f1dSLionel Sambuc       ConstantInt *R = nullptr;
1412f4a2713aSLionel Sambuc       ICmpInst::Predicate pred = ICmpInst::ICMP_EQ;
1413f4a2713aSLionel Sambuc       R = dyn_cast<ConstantInt>(ConstantExpr::getICmp(pred, V1, V2));
1414f4a2713aSLionel Sambuc       if (R && !R->isZero())
1415f4a2713aSLionel Sambuc         return pred;
1416f4a2713aSLionel Sambuc       pred = isSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT;
1417f4a2713aSLionel Sambuc       R = dyn_cast<ConstantInt>(ConstantExpr::getICmp(pred, V1, V2));
1418f4a2713aSLionel Sambuc       if (R && !R->isZero())
1419f4a2713aSLionel Sambuc         return pred;
1420f4a2713aSLionel Sambuc       pred = isSigned ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
1421f4a2713aSLionel Sambuc       R = dyn_cast<ConstantInt>(ConstantExpr::getICmp(pred, V1, V2));
1422f4a2713aSLionel Sambuc       if (R && !R->isZero())
1423f4a2713aSLionel Sambuc         return pred;
1424f4a2713aSLionel Sambuc 
1425f4a2713aSLionel Sambuc       // If we couldn't figure it out, bail.
1426f4a2713aSLionel Sambuc       return ICmpInst::BAD_ICMP_PREDICATE;
1427f4a2713aSLionel Sambuc     }
1428f4a2713aSLionel Sambuc 
1429f4a2713aSLionel Sambuc     // If the first operand is simple, swap operands.
1430f4a2713aSLionel Sambuc     ICmpInst::Predicate SwappedRelation =
1431f4a2713aSLionel Sambuc       evaluateICmpRelation(V2, V1, isSigned);
1432f4a2713aSLionel Sambuc     if (SwappedRelation != ICmpInst::BAD_ICMP_PREDICATE)
1433f4a2713aSLionel Sambuc       return ICmpInst::getSwappedPredicate(SwappedRelation);
1434f4a2713aSLionel Sambuc 
1435f4a2713aSLionel Sambuc   } else if (const GlobalValue *GV = dyn_cast<GlobalValue>(V1)) {
1436f4a2713aSLionel Sambuc     if (isa<ConstantExpr>(V2)) {  // Swap as necessary.
1437f4a2713aSLionel Sambuc       ICmpInst::Predicate SwappedRelation =
1438f4a2713aSLionel Sambuc         evaluateICmpRelation(V2, V1, isSigned);
1439f4a2713aSLionel Sambuc       if (SwappedRelation != ICmpInst::BAD_ICMP_PREDICATE)
1440f4a2713aSLionel Sambuc         return ICmpInst::getSwappedPredicate(SwappedRelation);
1441f4a2713aSLionel Sambuc       return ICmpInst::BAD_ICMP_PREDICATE;
1442f4a2713aSLionel Sambuc     }
1443f4a2713aSLionel Sambuc 
1444f4a2713aSLionel Sambuc     // Now we know that the RHS is a GlobalValue, BlockAddress or simple
1445f4a2713aSLionel Sambuc     // constant (which, since the types must match, means that it's a
1446f4a2713aSLionel Sambuc     // ConstantPointerNull).
1447f4a2713aSLionel Sambuc     if (const GlobalValue *GV2 = dyn_cast<GlobalValue>(V2)) {
1448*0a6a1f1dSLionel Sambuc       return areGlobalsPotentiallyEqual(GV, GV2);
1449f4a2713aSLionel Sambuc     } else if (isa<BlockAddress>(V2)) {
1450f4a2713aSLionel Sambuc       return ICmpInst::ICMP_NE; // Globals never equal labels.
1451f4a2713aSLionel Sambuc     } else {
1452f4a2713aSLionel Sambuc       assert(isa<ConstantPointerNull>(V2) && "Canonicalization guarantee!");
1453f4a2713aSLionel Sambuc       // GlobalVals can never be null unless they have external weak linkage.
1454f4a2713aSLionel Sambuc       // We don't try to evaluate aliases here.
1455f4a2713aSLionel Sambuc       if (!GV->hasExternalWeakLinkage() && !isa<GlobalAlias>(GV))
1456f4a2713aSLionel Sambuc         return ICmpInst::ICMP_NE;
1457f4a2713aSLionel Sambuc     }
1458f4a2713aSLionel Sambuc   } else if (const BlockAddress *BA = dyn_cast<BlockAddress>(V1)) {
1459f4a2713aSLionel Sambuc     if (isa<ConstantExpr>(V2)) {  // Swap as necessary.
1460f4a2713aSLionel Sambuc       ICmpInst::Predicate SwappedRelation =
1461f4a2713aSLionel Sambuc         evaluateICmpRelation(V2, V1, isSigned);
1462f4a2713aSLionel Sambuc       if (SwappedRelation != ICmpInst::BAD_ICMP_PREDICATE)
1463f4a2713aSLionel Sambuc         return ICmpInst::getSwappedPredicate(SwappedRelation);
1464f4a2713aSLionel Sambuc       return ICmpInst::BAD_ICMP_PREDICATE;
1465f4a2713aSLionel Sambuc     }
1466f4a2713aSLionel Sambuc 
1467f4a2713aSLionel Sambuc     // Now we know that the RHS is a GlobalValue, BlockAddress or simple
1468f4a2713aSLionel Sambuc     // constant (which, since the types must match, means that it is a
1469f4a2713aSLionel Sambuc     // ConstantPointerNull).
1470f4a2713aSLionel Sambuc     if (const BlockAddress *BA2 = dyn_cast<BlockAddress>(V2)) {
1471f4a2713aSLionel Sambuc       // Block address in another function can't equal this one, but block
1472f4a2713aSLionel Sambuc       // addresses in the current function might be the same if blocks are
1473f4a2713aSLionel Sambuc       // empty.
1474f4a2713aSLionel Sambuc       if (BA2->getFunction() != BA->getFunction())
1475f4a2713aSLionel Sambuc         return ICmpInst::ICMP_NE;
1476f4a2713aSLionel Sambuc     } else {
1477f4a2713aSLionel Sambuc       // Block addresses aren't null, don't equal the address of globals.
1478f4a2713aSLionel Sambuc       assert((isa<ConstantPointerNull>(V2) || isa<GlobalValue>(V2)) &&
1479f4a2713aSLionel Sambuc              "Canonicalization guarantee!");
1480f4a2713aSLionel Sambuc       return ICmpInst::ICMP_NE;
1481f4a2713aSLionel Sambuc     }
1482f4a2713aSLionel Sambuc   } else {
1483f4a2713aSLionel Sambuc     // Ok, the LHS is known to be a constantexpr.  The RHS can be any of a
1484f4a2713aSLionel Sambuc     // constantexpr, a global, block address, or a simple constant.
1485f4a2713aSLionel Sambuc     ConstantExpr *CE1 = cast<ConstantExpr>(V1);
1486f4a2713aSLionel Sambuc     Constant *CE1Op0 = CE1->getOperand(0);
1487f4a2713aSLionel Sambuc 
1488f4a2713aSLionel Sambuc     switch (CE1->getOpcode()) {
1489f4a2713aSLionel Sambuc     case Instruction::Trunc:
1490f4a2713aSLionel Sambuc     case Instruction::FPTrunc:
1491f4a2713aSLionel Sambuc     case Instruction::FPExt:
1492f4a2713aSLionel Sambuc     case Instruction::FPToUI:
1493f4a2713aSLionel Sambuc     case Instruction::FPToSI:
1494f4a2713aSLionel Sambuc       break; // We can't evaluate floating point casts or truncations.
1495f4a2713aSLionel Sambuc 
1496f4a2713aSLionel Sambuc     case Instruction::UIToFP:
1497f4a2713aSLionel Sambuc     case Instruction::SIToFP:
1498f4a2713aSLionel Sambuc     case Instruction::BitCast:
1499f4a2713aSLionel Sambuc     case Instruction::ZExt:
1500f4a2713aSLionel Sambuc     case Instruction::SExt:
1501f4a2713aSLionel Sambuc       // If the cast is not actually changing bits, and the second operand is a
1502f4a2713aSLionel Sambuc       // null pointer, do the comparison with the pre-casted value.
1503f4a2713aSLionel Sambuc       if (V2->isNullValue() &&
1504f4a2713aSLionel Sambuc           (CE1->getType()->isPointerTy() || CE1->getType()->isIntegerTy())) {
1505f4a2713aSLionel Sambuc         if (CE1->getOpcode() == Instruction::ZExt) isSigned = false;
1506f4a2713aSLionel Sambuc         if (CE1->getOpcode() == Instruction::SExt) isSigned = true;
1507f4a2713aSLionel Sambuc         return evaluateICmpRelation(CE1Op0,
1508f4a2713aSLionel Sambuc                                     Constant::getNullValue(CE1Op0->getType()),
1509f4a2713aSLionel Sambuc                                     isSigned);
1510f4a2713aSLionel Sambuc       }
1511f4a2713aSLionel Sambuc       break;
1512f4a2713aSLionel Sambuc 
1513*0a6a1f1dSLionel Sambuc     case Instruction::GetElementPtr: {
1514*0a6a1f1dSLionel Sambuc       GEPOperator *CE1GEP = cast<GEPOperator>(CE1);
1515f4a2713aSLionel Sambuc       // Ok, since this is a getelementptr, we know that the constant has a
1516f4a2713aSLionel Sambuc       // pointer type.  Check the various cases.
1517f4a2713aSLionel Sambuc       if (isa<ConstantPointerNull>(V2)) {
1518f4a2713aSLionel Sambuc         // If we are comparing a GEP to a null pointer, check to see if the base
1519f4a2713aSLionel Sambuc         // of the GEP equals the null pointer.
1520f4a2713aSLionel Sambuc         if (const GlobalValue *GV = dyn_cast<GlobalValue>(CE1Op0)) {
1521f4a2713aSLionel Sambuc           if (GV->hasExternalWeakLinkage())
1522f4a2713aSLionel Sambuc             // Weak linkage GVals could be zero or not. We're comparing that
1523f4a2713aSLionel Sambuc             // to null pointer so its greater-or-equal
1524f4a2713aSLionel Sambuc             return isSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE;
1525f4a2713aSLionel Sambuc           else
1526f4a2713aSLionel Sambuc             // If its not weak linkage, the GVal must have a non-zero address
1527f4a2713aSLionel Sambuc             // so the result is greater-than
1528f4a2713aSLionel Sambuc             return isSigned ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
1529f4a2713aSLionel Sambuc         } else if (isa<ConstantPointerNull>(CE1Op0)) {
1530f4a2713aSLionel Sambuc           // If we are indexing from a null pointer, check to see if we have any
1531f4a2713aSLionel Sambuc           // non-zero indices.
1532f4a2713aSLionel Sambuc           for (unsigned i = 1, e = CE1->getNumOperands(); i != e; ++i)
1533f4a2713aSLionel Sambuc             if (!CE1->getOperand(i)->isNullValue())
1534f4a2713aSLionel Sambuc               // Offsetting from null, must not be equal.
1535f4a2713aSLionel Sambuc               return isSigned ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
1536f4a2713aSLionel Sambuc           // Only zero indexes from null, must still be zero.
1537f4a2713aSLionel Sambuc           return ICmpInst::ICMP_EQ;
1538f4a2713aSLionel Sambuc         }
1539f4a2713aSLionel Sambuc         // Otherwise, we can't really say if the first operand is null or not.
1540f4a2713aSLionel Sambuc       } else if (const GlobalValue *GV2 = dyn_cast<GlobalValue>(V2)) {
1541f4a2713aSLionel Sambuc         if (isa<ConstantPointerNull>(CE1Op0)) {
1542f4a2713aSLionel Sambuc           if (GV2->hasExternalWeakLinkage())
1543f4a2713aSLionel Sambuc             // Weak linkage GVals could be zero or not. We're comparing it to
1544f4a2713aSLionel Sambuc             // a null pointer, so its less-or-equal
1545f4a2713aSLionel Sambuc             return isSigned ? ICmpInst::ICMP_SLE : ICmpInst::ICMP_ULE;
1546f4a2713aSLionel Sambuc           else
1547f4a2713aSLionel Sambuc             // If its not weak linkage, the GVal must have a non-zero address
1548f4a2713aSLionel Sambuc             // so the result is less-than
1549f4a2713aSLionel Sambuc             return isSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT;
1550f4a2713aSLionel Sambuc         } else if (const GlobalValue *GV = dyn_cast<GlobalValue>(CE1Op0)) {
1551f4a2713aSLionel Sambuc           if (GV == GV2) {
1552f4a2713aSLionel Sambuc             // If this is a getelementptr of the same global, then it must be
1553f4a2713aSLionel Sambuc             // different.  Because the types must match, the getelementptr could
1554f4a2713aSLionel Sambuc             // only have at most one index, and because we fold getelementptr's
1555f4a2713aSLionel Sambuc             // with a single zero index, it must be nonzero.
1556f4a2713aSLionel Sambuc             assert(CE1->getNumOperands() == 2 &&
1557f4a2713aSLionel Sambuc                    !CE1->getOperand(1)->isNullValue() &&
1558f4a2713aSLionel Sambuc                    "Surprising getelementptr!");
1559f4a2713aSLionel Sambuc             return isSigned ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
1560f4a2713aSLionel Sambuc           } else {
1561*0a6a1f1dSLionel Sambuc             if (CE1GEP->hasAllZeroIndices())
1562*0a6a1f1dSLionel Sambuc               return areGlobalsPotentiallyEqual(GV, GV2);
1563f4a2713aSLionel Sambuc             return ICmpInst::BAD_ICMP_PREDICATE;
1564f4a2713aSLionel Sambuc           }
1565f4a2713aSLionel Sambuc         }
1566f4a2713aSLionel Sambuc       } else {
1567f4a2713aSLionel Sambuc         ConstantExpr *CE2 = cast<ConstantExpr>(V2);
1568f4a2713aSLionel Sambuc         Constant *CE2Op0 = CE2->getOperand(0);
1569f4a2713aSLionel Sambuc 
1570f4a2713aSLionel Sambuc         // There are MANY other foldings that we could perform here.  They will
1571f4a2713aSLionel Sambuc         // probably be added on demand, as they seem needed.
1572f4a2713aSLionel Sambuc         switch (CE2->getOpcode()) {
1573f4a2713aSLionel Sambuc         default: break;
1574f4a2713aSLionel Sambuc         case Instruction::GetElementPtr:
1575f4a2713aSLionel Sambuc           // By far the most common case to handle is when the base pointers are
1576f4a2713aSLionel Sambuc           // obviously to the same global.
1577f4a2713aSLionel Sambuc           if (isa<GlobalValue>(CE1Op0) && isa<GlobalValue>(CE2Op0)) {
1578*0a6a1f1dSLionel Sambuc             // Don't know relative ordering, but check for inequality.
1579*0a6a1f1dSLionel Sambuc             if (CE1Op0 != CE2Op0) {
1580*0a6a1f1dSLionel Sambuc               GEPOperator *CE2GEP = cast<GEPOperator>(CE2);
1581*0a6a1f1dSLionel Sambuc               if (CE1GEP->hasAllZeroIndices() && CE2GEP->hasAllZeroIndices())
1582*0a6a1f1dSLionel Sambuc                 return areGlobalsPotentiallyEqual(cast<GlobalValue>(CE1Op0),
1583*0a6a1f1dSLionel Sambuc                                                   cast<GlobalValue>(CE2Op0));
1584f4a2713aSLionel Sambuc               return ICmpInst::BAD_ICMP_PREDICATE;
1585*0a6a1f1dSLionel Sambuc             }
1586f4a2713aSLionel Sambuc             // Ok, we know that both getelementptr instructions are based on the
1587f4a2713aSLionel Sambuc             // same global.  From this, we can precisely determine the relative
1588f4a2713aSLionel Sambuc             // ordering of the resultant pointers.
1589f4a2713aSLionel Sambuc             unsigned i = 1;
1590f4a2713aSLionel Sambuc 
1591f4a2713aSLionel Sambuc             // The logic below assumes that the result of the comparison
1592f4a2713aSLionel Sambuc             // can be determined by finding the first index that differs.
1593f4a2713aSLionel Sambuc             // This doesn't work if there is over-indexing in any
1594f4a2713aSLionel Sambuc             // subsequent indices, so check for that case first.
1595f4a2713aSLionel Sambuc             if (!CE1->isGEPWithNoNotionalOverIndexing() ||
1596f4a2713aSLionel Sambuc                 !CE2->isGEPWithNoNotionalOverIndexing())
1597f4a2713aSLionel Sambuc                return ICmpInst::BAD_ICMP_PREDICATE; // Might be equal.
1598f4a2713aSLionel Sambuc 
1599f4a2713aSLionel Sambuc             // Compare all of the operands the GEP's have in common.
1600f4a2713aSLionel Sambuc             gep_type_iterator GTI = gep_type_begin(CE1);
1601f4a2713aSLionel Sambuc             for (;i != CE1->getNumOperands() && i != CE2->getNumOperands();
1602f4a2713aSLionel Sambuc                  ++i, ++GTI)
1603f4a2713aSLionel Sambuc               switch (IdxCompare(CE1->getOperand(i),
1604f4a2713aSLionel Sambuc                                  CE2->getOperand(i), GTI.getIndexedType())) {
1605f4a2713aSLionel Sambuc               case -1: return isSigned ? ICmpInst::ICMP_SLT:ICmpInst::ICMP_ULT;
1606f4a2713aSLionel Sambuc               case 1:  return isSigned ? ICmpInst::ICMP_SGT:ICmpInst::ICMP_UGT;
1607f4a2713aSLionel Sambuc               case -2: return ICmpInst::BAD_ICMP_PREDICATE;
1608f4a2713aSLionel Sambuc               }
1609f4a2713aSLionel Sambuc 
1610f4a2713aSLionel Sambuc             // Ok, we ran out of things they have in common.  If any leftovers
1611f4a2713aSLionel Sambuc             // are non-zero then we have a difference, otherwise we are equal.
1612f4a2713aSLionel Sambuc             for (; i < CE1->getNumOperands(); ++i)
1613f4a2713aSLionel Sambuc               if (!CE1->getOperand(i)->isNullValue()) {
1614f4a2713aSLionel Sambuc                 if (isa<ConstantInt>(CE1->getOperand(i)))
1615f4a2713aSLionel Sambuc                   return isSigned ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
1616f4a2713aSLionel Sambuc                 else
1617f4a2713aSLionel Sambuc                   return ICmpInst::BAD_ICMP_PREDICATE; // Might be equal.
1618f4a2713aSLionel Sambuc               }
1619f4a2713aSLionel Sambuc 
1620f4a2713aSLionel Sambuc             for (; i < CE2->getNumOperands(); ++i)
1621f4a2713aSLionel Sambuc               if (!CE2->getOperand(i)->isNullValue()) {
1622f4a2713aSLionel Sambuc                 if (isa<ConstantInt>(CE2->getOperand(i)))
1623f4a2713aSLionel Sambuc                   return isSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT;
1624f4a2713aSLionel Sambuc                 else
1625f4a2713aSLionel Sambuc                   return ICmpInst::BAD_ICMP_PREDICATE; // Might be equal.
1626f4a2713aSLionel Sambuc               }
1627f4a2713aSLionel Sambuc             return ICmpInst::ICMP_EQ;
1628f4a2713aSLionel Sambuc           }
1629f4a2713aSLionel Sambuc         }
1630f4a2713aSLionel Sambuc       }
1631*0a6a1f1dSLionel Sambuc     }
1632f4a2713aSLionel Sambuc     default:
1633f4a2713aSLionel Sambuc       break;
1634f4a2713aSLionel Sambuc     }
1635f4a2713aSLionel Sambuc   }
1636f4a2713aSLionel Sambuc 
1637f4a2713aSLionel Sambuc   return ICmpInst::BAD_ICMP_PREDICATE;
1638f4a2713aSLionel Sambuc }
1639f4a2713aSLionel Sambuc 
ConstantFoldCompareInstruction(unsigned short pred,Constant * C1,Constant * C2)1640f4a2713aSLionel Sambuc Constant *llvm::ConstantFoldCompareInstruction(unsigned short pred,
1641f4a2713aSLionel Sambuc                                                Constant *C1, Constant *C2) {
1642f4a2713aSLionel Sambuc   Type *ResultTy;
1643f4a2713aSLionel Sambuc   if (VectorType *VT = dyn_cast<VectorType>(C1->getType()))
1644f4a2713aSLionel Sambuc     ResultTy = VectorType::get(Type::getInt1Ty(C1->getContext()),
1645f4a2713aSLionel Sambuc                                VT->getNumElements());
1646f4a2713aSLionel Sambuc   else
1647f4a2713aSLionel Sambuc     ResultTy = Type::getInt1Ty(C1->getContext());
1648f4a2713aSLionel Sambuc 
1649f4a2713aSLionel Sambuc   // Fold FCMP_FALSE/FCMP_TRUE unconditionally.
1650f4a2713aSLionel Sambuc   if (pred == FCmpInst::FCMP_FALSE)
1651f4a2713aSLionel Sambuc     return Constant::getNullValue(ResultTy);
1652f4a2713aSLionel Sambuc 
1653f4a2713aSLionel Sambuc   if (pred == FCmpInst::FCMP_TRUE)
1654f4a2713aSLionel Sambuc     return Constant::getAllOnesValue(ResultTy);
1655f4a2713aSLionel Sambuc 
1656f4a2713aSLionel Sambuc   // Handle some degenerate cases first
1657f4a2713aSLionel Sambuc   if (isa<UndefValue>(C1) || isa<UndefValue>(C2)) {
1658f4a2713aSLionel Sambuc     // For EQ and NE, we can always pick a value for the undef to make the
1659f4a2713aSLionel Sambuc     // predicate pass or fail, so we can return undef.
1660f4a2713aSLionel Sambuc     // Also, if both operands are undef, we can return undef.
1661f4a2713aSLionel Sambuc     if (ICmpInst::isEquality(ICmpInst::Predicate(pred)) ||
1662f4a2713aSLionel Sambuc         (isa<UndefValue>(C1) && isa<UndefValue>(C2)))
1663f4a2713aSLionel Sambuc       return UndefValue::get(ResultTy);
1664f4a2713aSLionel Sambuc     // Otherwise, pick the same value as the non-undef operand, and fold
1665f4a2713aSLionel Sambuc     // it to true or false.
1666f4a2713aSLionel Sambuc     return ConstantInt::get(ResultTy, CmpInst::isTrueWhenEqual(pred));
1667f4a2713aSLionel Sambuc   }
1668f4a2713aSLionel Sambuc 
1669f4a2713aSLionel Sambuc   // icmp eq/ne(null,GV) -> false/true
1670f4a2713aSLionel Sambuc   if (C1->isNullValue()) {
1671f4a2713aSLionel Sambuc     if (const GlobalValue *GV = dyn_cast<GlobalValue>(C2))
1672f4a2713aSLionel Sambuc       // Don't try to evaluate aliases.  External weak GV can be null.
1673f4a2713aSLionel Sambuc       if (!isa<GlobalAlias>(GV) && !GV->hasExternalWeakLinkage()) {
1674f4a2713aSLionel Sambuc         if (pred == ICmpInst::ICMP_EQ)
1675f4a2713aSLionel Sambuc           return ConstantInt::getFalse(C1->getContext());
1676f4a2713aSLionel Sambuc         else if (pred == ICmpInst::ICMP_NE)
1677f4a2713aSLionel Sambuc           return ConstantInt::getTrue(C1->getContext());
1678f4a2713aSLionel Sambuc       }
1679f4a2713aSLionel Sambuc   // icmp eq/ne(GV,null) -> false/true
1680f4a2713aSLionel Sambuc   } else if (C2->isNullValue()) {
1681f4a2713aSLionel Sambuc     if (const GlobalValue *GV = dyn_cast<GlobalValue>(C1))
1682f4a2713aSLionel Sambuc       // Don't try to evaluate aliases.  External weak GV can be null.
1683f4a2713aSLionel Sambuc       if (!isa<GlobalAlias>(GV) && !GV->hasExternalWeakLinkage()) {
1684f4a2713aSLionel Sambuc         if (pred == ICmpInst::ICMP_EQ)
1685f4a2713aSLionel Sambuc           return ConstantInt::getFalse(C1->getContext());
1686f4a2713aSLionel Sambuc         else if (pred == ICmpInst::ICMP_NE)
1687f4a2713aSLionel Sambuc           return ConstantInt::getTrue(C1->getContext());
1688f4a2713aSLionel Sambuc       }
1689f4a2713aSLionel Sambuc   }
1690f4a2713aSLionel Sambuc 
1691f4a2713aSLionel Sambuc   // If the comparison is a comparison between two i1's, simplify it.
1692f4a2713aSLionel Sambuc   if (C1->getType()->isIntegerTy(1)) {
1693f4a2713aSLionel Sambuc     switch(pred) {
1694f4a2713aSLionel Sambuc     case ICmpInst::ICMP_EQ:
1695f4a2713aSLionel Sambuc       if (isa<ConstantInt>(C2))
1696f4a2713aSLionel Sambuc         return ConstantExpr::getXor(C1, ConstantExpr::getNot(C2));
1697f4a2713aSLionel Sambuc       return ConstantExpr::getXor(ConstantExpr::getNot(C1), C2);
1698f4a2713aSLionel Sambuc     case ICmpInst::ICMP_NE:
1699f4a2713aSLionel Sambuc       return ConstantExpr::getXor(C1, C2);
1700f4a2713aSLionel Sambuc     default:
1701f4a2713aSLionel Sambuc       break;
1702f4a2713aSLionel Sambuc     }
1703f4a2713aSLionel Sambuc   }
1704f4a2713aSLionel Sambuc 
1705f4a2713aSLionel Sambuc   if (isa<ConstantInt>(C1) && isa<ConstantInt>(C2)) {
1706f4a2713aSLionel Sambuc     APInt V1 = cast<ConstantInt>(C1)->getValue();
1707f4a2713aSLionel Sambuc     APInt V2 = cast<ConstantInt>(C2)->getValue();
1708f4a2713aSLionel Sambuc     switch (pred) {
1709f4a2713aSLionel Sambuc     default: llvm_unreachable("Invalid ICmp Predicate");
1710f4a2713aSLionel Sambuc     case ICmpInst::ICMP_EQ:  return ConstantInt::get(ResultTy, V1 == V2);
1711f4a2713aSLionel Sambuc     case ICmpInst::ICMP_NE:  return ConstantInt::get(ResultTy, V1 != V2);
1712f4a2713aSLionel Sambuc     case ICmpInst::ICMP_SLT: return ConstantInt::get(ResultTy, V1.slt(V2));
1713f4a2713aSLionel Sambuc     case ICmpInst::ICMP_SGT: return ConstantInt::get(ResultTy, V1.sgt(V2));
1714f4a2713aSLionel Sambuc     case ICmpInst::ICMP_SLE: return ConstantInt::get(ResultTy, V1.sle(V2));
1715f4a2713aSLionel Sambuc     case ICmpInst::ICMP_SGE: return ConstantInt::get(ResultTy, V1.sge(V2));
1716f4a2713aSLionel Sambuc     case ICmpInst::ICMP_ULT: return ConstantInt::get(ResultTy, V1.ult(V2));
1717f4a2713aSLionel Sambuc     case ICmpInst::ICMP_UGT: return ConstantInt::get(ResultTy, V1.ugt(V2));
1718f4a2713aSLionel Sambuc     case ICmpInst::ICMP_ULE: return ConstantInt::get(ResultTy, V1.ule(V2));
1719f4a2713aSLionel Sambuc     case ICmpInst::ICMP_UGE: return ConstantInt::get(ResultTy, V1.uge(V2));
1720f4a2713aSLionel Sambuc     }
1721f4a2713aSLionel Sambuc   } else if (isa<ConstantFP>(C1) && isa<ConstantFP>(C2)) {
1722f4a2713aSLionel Sambuc     APFloat C1V = cast<ConstantFP>(C1)->getValueAPF();
1723f4a2713aSLionel Sambuc     APFloat C2V = cast<ConstantFP>(C2)->getValueAPF();
1724f4a2713aSLionel Sambuc     APFloat::cmpResult R = C1V.compare(C2V);
1725f4a2713aSLionel Sambuc     switch (pred) {
1726f4a2713aSLionel Sambuc     default: llvm_unreachable("Invalid FCmp Predicate");
1727f4a2713aSLionel Sambuc     case FCmpInst::FCMP_FALSE: return Constant::getNullValue(ResultTy);
1728f4a2713aSLionel Sambuc     case FCmpInst::FCMP_TRUE:  return Constant::getAllOnesValue(ResultTy);
1729f4a2713aSLionel Sambuc     case FCmpInst::FCMP_UNO:
1730f4a2713aSLionel Sambuc       return ConstantInt::get(ResultTy, R==APFloat::cmpUnordered);
1731f4a2713aSLionel Sambuc     case FCmpInst::FCMP_ORD:
1732f4a2713aSLionel Sambuc       return ConstantInt::get(ResultTy, R!=APFloat::cmpUnordered);
1733f4a2713aSLionel Sambuc     case FCmpInst::FCMP_UEQ:
1734f4a2713aSLionel Sambuc       return ConstantInt::get(ResultTy, R==APFloat::cmpUnordered ||
1735f4a2713aSLionel Sambuc                                         R==APFloat::cmpEqual);
1736f4a2713aSLionel Sambuc     case FCmpInst::FCMP_OEQ:
1737f4a2713aSLionel Sambuc       return ConstantInt::get(ResultTy, R==APFloat::cmpEqual);
1738f4a2713aSLionel Sambuc     case FCmpInst::FCMP_UNE:
1739f4a2713aSLionel Sambuc       return ConstantInt::get(ResultTy, R!=APFloat::cmpEqual);
1740f4a2713aSLionel Sambuc     case FCmpInst::FCMP_ONE:
1741f4a2713aSLionel Sambuc       return ConstantInt::get(ResultTy, R==APFloat::cmpLessThan ||
1742f4a2713aSLionel Sambuc                                         R==APFloat::cmpGreaterThan);
1743f4a2713aSLionel Sambuc     case FCmpInst::FCMP_ULT:
1744f4a2713aSLionel Sambuc       return ConstantInt::get(ResultTy, R==APFloat::cmpUnordered ||
1745f4a2713aSLionel Sambuc                                         R==APFloat::cmpLessThan);
1746f4a2713aSLionel Sambuc     case FCmpInst::FCMP_OLT:
1747f4a2713aSLionel Sambuc       return ConstantInt::get(ResultTy, R==APFloat::cmpLessThan);
1748f4a2713aSLionel Sambuc     case FCmpInst::FCMP_UGT:
1749f4a2713aSLionel Sambuc       return ConstantInt::get(ResultTy, R==APFloat::cmpUnordered ||
1750f4a2713aSLionel Sambuc                                         R==APFloat::cmpGreaterThan);
1751f4a2713aSLionel Sambuc     case FCmpInst::FCMP_OGT:
1752f4a2713aSLionel Sambuc       return ConstantInt::get(ResultTy, R==APFloat::cmpGreaterThan);
1753f4a2713aSLionel Sambuc     case FCmpInst::FCMP_ULE:
1754f4a2713aSLionel Sambuc       return ConstantInt::get(ResultTy, R!=APFloat::cmpGreaterThan);
1755f4a2713aSLionel Sambuc     case FCmpInst::FCMP_OLE:
1756f4a2713aSLionel Sambuc       return ConstantInt::get(ResultTy, R==APFloat::cmpLessThan ||
1757f4a2713aSLionel Sambuc                                         R==APFloat::cmpEqual);
1758f4a2713aSLionel Sambuc     case FCmpInst::FCMP_UGE:
1759f4a2713aSLionel Sambuc       return ConstantInt::get(ResultTy, R!=APFloat::cmpLessThan);
1760f4a2713aSLionel Sambuc     case FCmpInst::FCMP_OGE:
1761f4a2713aSLionel Sambuc       return ConstantInt::get(ResultTy, R==APFloat::cmpGreaterThan ||
1762f4a2713aSLionel Sambuc                                         R==APFloat::cmpEqual);
1763f4a2713aSLionel Sambuc     }
1764f4a2713aSLionel Sambuc   } else if (C1->getType()->isVectorTy()) {
1765f4a2713aSLionel Sambuc     // If we can constant fold the comparison of each element, constant fold
1766f4a2713aSLionel Sambuc     // the whole vector comparison.
1767f4a2713aSLionel Sambuc     SmallVector<Constant*, 4> ResElts;
1768f4a2713aSLionel Sambuc     Type *Ty = IntegerType::get(C1->getContext(), 32);
1769f4a2713aSLionel Sambuc     // Compare the elements, producing an i1 result or constant expr.
1770f4a2713aSLionel Sambuc     for (unsigned i = 0, e = C1->getType()->getVectorNumElements(); i != e;++i){
1771f4a2713aSLionel Sambuc       Constant *C1E =
1772f4a2713aSLionel Sambuc         ConstantExpr::getExtractElement(C1, ConstantInt::get(Ty, i));
1773f4a2713aSLionel Sambuc       Constant *C2E =
1774f4a2713aSLionel Sambuc         ConstantExpr::getExtractElement(C2, ConstantInt::get(Ty, i));
1775f4a2713aSLionel Sambuc 
1776f4a2713aSLionel Sambuc       ResElts.push_back(ConstantExpr::getCompare(pred, C1E, C2E));
1777f4a2713aSLionel Sambuc     }
1778f4a2713aSLionel Sambuc 
1779f4a2713aSLionel Sambuc     return ConstantVector::get(ResElts);
1780f4a2713aSLionel Sambuc   }
1781f4a2713aSLionel Sambuc 
1782f4a2713aSLionel Sambuc   if (C1->getType()->isFloatingPointTy()) {
1783f4a2713aSLionel Sambuc     int Result = -1;  // -1 = unknown, 0 = known false, 1 = known true.
1784f4a2713aSLionel Sambuc     switch (evaluateFCmpRelation(C1, C2)) {
1785f4a2713aSLionel Sambuc     default: llvm_unreachable("Unknown relation!");
1786f4a2713aSLionel Sambuc     case FCmpInst::FCMP_UNO:
1787f4a2713aSLionel Sambuc     case FCmpInst::FCMP_ORD:
1788f4a2713aSLionel Sambuc     case FCmpInst::FCMP_UEQ:
1789f4a2713aSLionel Sambuc     case FCmpInst::FCMP_UNE:
1790f4a2713aSLionel Sambuc     case FCmpInst::FCMP_ULT:
1791f4a2713aSLionel Sambuc     case FCmpInst::FCMP_UGT:
1792f4a2713aSLionel Sambuc     case FCmpInst::FCMP_ULE:
1793f4a2713aSLionel Sambuc     case FCmpInst::FCMP_UGE:
1794f4a2713aSLionel Sambuc     case FCmpInst::FCMP_TRUE:
1795f4a2713aSLionel Sambuc     case FCmpInst::FCMP_FALSE:
1796f4a2713aSLionel Sambuc     case FCmpInst::BAD_FCMP_PREDICATE:
1797f4a2713aSLionel Sambuc       break; // Couldn't determine anything about these constants.
1798f4a2713aSLionel Sambuc     case FCmpInst::FCMP_OEQ: // We know that C1 == C2
1799f4a2713aSLionel Sambuc       Result = (pred == FCmpInst::FCMP_UEQ || pred == FCmpInst::FCMP_OEQ ||
1800f4a2713aSLionel Sambuc                 pred == FCmpInst::FCMP_ULE || pred == FCmpInst::FCMP_OLE ||
1801f4a2713aSLionel Sambuc                 pred == FCmpInst::FCMP_UGE || pred == FCmpInst::FCMP_OGE);
1802f4a2713aSLionel Sambuc       break;
1803f4a2713aSLionel Sambuc     case FCmpInst::FCMP_OLT: // We know that C1 < C2
1804f4a2713aSLionel Sambuc       Result = (pred == FCmpInst::FCMP_UNE || pred == FCmpInst::FCMP_ONE ||
1805f4a2713aSLionel Sambuc                 pred == FCmpInst::FCMP_ULT || pred == FCmpInst::FCMP_OLT ||
1806f4a2713aSLionel Sambuc                 pred == FCmpInst::FCMP_ULE || pred == FCmpInst::FCMP_OLE);
1807f4a2713aSLionel Sambuc       break;
1808f4a2713aSLionel Sambuc     case FCmpInst::FCMP_OGT: // We know that C1 > C2
1809f4a2713aSLionel Sambuc       Result = (pred == FCmpInst::FCMP_UNE || pred == FCmpInst::FCMP_ONE ||
1810f4a2713aSLionel Sambuc                 pred == FCmpInst::FCMP_UGT || pred == FCmpInst::FCMP_OGT ||
1811f4a2713aSLionel Sambuc                 pred == FCmpInst::FCMP_UGE || pred == FCmpInst::FCMP_OGE);
1812f4a2713aSLionel Sambuc       break;
1813f4a2713aSLionel Sambuc     case FCmpInst::FCMP_OLE: // We know that C1 <= C2
1814f4a2713aSLionel Sambuc       // We can only partially decide this relation.
1815f4a2713aSLionel Sambuc       if (pred == FCmpInst::FCMP_UGT || pred == FCmpInst::FCMP_OGT)
1816f4a2713aSLionel Sambuc         Result = 0;
1817f4a2713aSLionel Sambuc       else if (pred == FCmpInst::FCMP_ULT || pred == FCmpInst::FCMP_OLT)
1818f4a2713aSLionel Sambuc         Result = 1;
1819f4a2713aSLionel Sambuc       break;
1820f4a2713aSLionel Sambuc     case FCmpInst::FCMP_OGE: // We known that C1 >= C2
1821f4a2713aSLionel Sambuc       // We can only partially decide this relation.
1822f4a2713aSLionel Sambuc       if (pred == FCmpInst::FCMP_ULT || pred == FCmpInst::FCMP_OLT)
1823f4a2713aSLionel Sambuc         Result = 0;
1824f4a2713aSLionel Sambuc       else if (pred == FCmpInst::FCMP_UGT || pred == FCmpInst::FCMP_OGT)
1825f4a2713aSLionel Sambuc         Result = 1;
1826f4a2713aSLionel Sambuc       break;
1827f4a2713aSLionel Sambuc     case FCmpInst::FCMP_ONE: // We know that C1 != C2
1828f4a2713aSLionel Sambuc       // We can only partially decide this relation.
1829f4a2713aSLionel Sambuc       if (pred == FCmpInst::FCMP_OEQ || pred == FCmpInst::FCMP_UEQ)
1830f4a2713aSLionel Sambuc         Result = 0;
1831f4a2713aSLionel Sambuc       else if (pred == FCmpInst::FCMP_ONE || pred == FCmpInst::FCMP_UNE)
1832f4a2713aSLionel Sambuc         Result = 1;
1833f4a2713aSLionel Sambuc       break;
1834f4a2713aSLionel Sambuc     }
1835f4a2713aSLionel Sambuc 
1836f4a2713aSLionel Sambuc     // If we evaluated the result, return it now.
1837f4a2713aSLionel Sambuc     if (Result != -1)
1838f4a2713aSLionel Sambuc       return ConstantInt::get(ResultTy, Result);
1839f4a2713aSLionel Sambuc 
1840f4a2713aSLionel Sambuc   } else {
1841f4a2713aSLionel Sambuc     // Evaluate the relation between the two constants, per the predicate.
1842f4a2713aSLionel Sambuc     int Result = -1;  // -1 = unknown, 0 = known false, 1 = known true.
1843f4a2713aSLionel Sambuc     switch (evaluateICmpRelation(C1, C2, CmpInst::isSigned(pred))) {
1844f4a2713aSLionel Sambuc     default: llvm_unreachable("Unknown relational!");
1845f4a2713aSLionel Sambuc     case ICmpInst::BAD_ICMP_PREDICATE:
1846f4a2713aSLionel Sambuc       break;  // Couldn't determine anything about these constants.
1847f4a2713aSLionel Sambuc     case ICmpInst::ICMP_EQ:   // We know the constants are equal!
1848f4a2713aSLionel Sambuc       // If we know the constants are equal, we can decide the result of this
1849f4a2713aSLionel Sambuc       // computation precisely.
1850f4a2713aSLionel Sambuc       Result = ICmpInst::isTrueWhenEqual((ICmpInst::Predicate)pred);
1851f4a2713aSLionel Sambuc       break;
1852f4a2713aSLionel Sambuc     case ICmpInst::ICMP_ULT:
1853f4a2713aSLionel Sambuc       switch (pred) {
1854f4a2713aSLionel Sambuc       case ICmpInst::ICMP_ULT: case ICmpInst::ICMP_NE: case ICmpInst::ICMP_ULE:
1855f4a2713aSLionel Sambuc         Result = 1; break;
1856f4a2713aSLionel Sambuc       case ICmpInst::ICMP_UGT: case ICmpInst::ICMP_EQ: case ICmpInst::ICMP_UGE:
1857f4a2713aSLionel Sambuc         Result = 0; break;
1858f4a2713aSLionel Sambuc       }
1859f4a2713aSLionel Sambuc       break;
1860f4a2713aSLionel Sambuc     case ICmpInst::ICMP_SLT:
1861f4a2713aSLionel Sambuc       switch (pred) {
1862f4a2713aSLionel Sambuc       case ICmpInst::ICMP_SLT: case ICmpInst::ICMP_NE: case ICmpInst::ICMP_SLE:
1863f4a2713aSLionel Sambuc         Result = 1; break;
1864f4a2713aSLionel Sambuc       case ICmpInst::ICMP_SGT: case ICmpInst::ICMP_EQ: case ICmpInst::ICMP_SGE:
1865f4a2713aSLionel Sambuc         Result = 0; break;
1866f4a2713aSLionel Sambuc       }
1867f4a2713aSLionel Sambuc       break;
1868f4a2713aSLionel Sambuc     case ICmpInst::ICMP_UGT:
1869f4a2713aSLionel Sambuc       switch (pred) {
1870f4a2713aSLionel Sambuc       case ICmpInst::ICMP_UGT: case ICmpInst::ICMP_NE: case ICmpInst::ICMP_UGE:
1871f4a2713aSLionel Sambuc         Result = 1; break;
1872f4a2713aSLionel Sambuc       case ICmpInst::ICMP_ULT: case ICmpInst::ICMP_EQ: case ICmpInst::ICMP_ULE:
1873f4a2713aSLionel Sambuc         Result = 0; break;
1874f4a2713aSLionel Sambuc       }
1875f4a2713aSLionel Sambuc       break;
1876f4a2713aSLionel Sambuc     case ICmpInst::ICMP_SGT:
1877f4a2713aSLionel Sambuc       switch (pred) {
1878f4a2713aSLionel Sambuc       case ICmpInst::ICMP_SGT: case ICmpInst::ICMP_NE: case ICmpInst::ICMP_SGE:
1879f4a2713aSLionel Sambuc         Result = 1; break;
1880f4a2713aSLionel Sambuc       case ICmpInst::ICMP_SLT: case ICmpInst::ICMP_EQ: case ICmpInst::ICMP_SLE:
1881f4a2713aSLionel Sambuc         Result = 0; break;
1882f4a2713aSLionel Sambuc       }
1883f4a2713aSLionel Sambuc       break;
1884f4a2713aSLionel Sambuc     case ICmpInst::ICMP_ULE:
1885f4a2713aSLionel Sambuc       if (pred == ICmpInst::ICMP_UGT) Result = 0;
1886f4a2713aSLionel Sambuc       if (pred == ICmpInst::ICMP_ULT || pred == ICmpInst::ICMP_ULE) Result = 1;
1887f4a2713aSLionel Sambuc       break;
1888f4a2713aSLionel Sambuc     case ICmpInst::ICMP_SLE:
1889f4a2713aSLionel Sambuc       if (pred == ICmpInst::ICMP_SGT) Result = 0;
1890f4a2713aSLionel Sambuc       if (pred == ICmpInst::ICMP_SLT || pred == ICmpInst::ICMP_SLE) Result = 1;
1891f4a2713aSLionel Sambuc       break;
1892f4a2713aSLionel Sambuc     case ICmpInst::ICMP_UGE:
1893f4a2713aSLionel Sambuc       if (pred == ICmpInst::ICMP_ULT) Result = 0;
1894f4a2713aSLionel Sambuc       if (pred == ICmpInst::ICMP_UGT || pred == ICmpInst::ICMP_UGE) Result = 1;
1895f4a2713aSLionel Sambuc       break;
1896f4a2713aSLionel Sambuc     case ICmpInst::ICMP_SGE:
1897f4a2713aSLionel Sambuc       if (pred == ICmpInst::ICMP_SLT) Result = 0;
1898f4a2713aSLionel Sambuc       if (pred == ICmpInst::ICMP_SGT || pred == ICmpInst::ICMP_SGE) Result = 1;
1899f4a2713aSLionel Sambuc       break;
1900f4a2713aSLionel Sambuc     case ICmpInst::ICMP_NE:
1901f4a2713aSLionel Sambuc       if (pred == ICmpInst::ICMP_EQ) Result = 0;
1902f4a2713aSLionel Sambuc       if (pred == ICmpInst::ICMP_NE) Result = 1;
1903f4a2713aSLionel Sambuc       break;
1904f4a2713aSLionel Sambuc     }
1905f4a2713aSLionel Sambuc 
1906f4a2713aSLionel Sambuc     // If we evaluated the result, return it now.
1907f4a2713aSLionel Sambuc     if (Result != -1)
1908f4a2713aSLionel Sambuc       return ConstantInt::get(ResultTy, Result);
1909f4a2713aSLionel Sambuc 
1910f4a2713aSLionel Sambuc     // If the right hand side is a bitcast, try using its inverse to simplify
1911f4a2713aSLionel Sambuc     // it by moving it to the left hand side.  We can't do this if it would turn
1912f4a2713aSLionel Sambuc     // a vector compare into a scalar compare or visa versa.
1913f4a2713aSLionel Sambuc     if (ConstantExpr *CE2 = dyn_cast<ConstantExpr>(C2)) {
1914f4a2713aSLionel Sambuc       Constant *CE2Op0 = CE2->getOperand(0);
1915f4a2713aSLionel Sambuc       if (CE2->getOpcode() == Instruction::BitCast &&
1916f4a2713aSLionel Sambuc           CE2->getType()->isVectorTy() == CE2Op0->getType()->isVectorTy()) {
1917f4a2713aSLionel Sambuc         Constant *Inverse = ConstantExpr::getBitCast(C1, CE2Op0->getType());
1918f4a2713aSLionel Sambuc         return ConstantExpr::getICmp(pred, Inverse, CE2Op0);
1919f4a2713aSLionel Sambuc       }
1920f4a2713aSLionel Sambuc     }
1921f4a2713aSLionel Sambuc 
1922f4a2713aSLionel Sambuc     // If the left hand side is an extension, try eliminating it.
1923f4a2713aSLionel Sambuc     if (ConstantExpr *CE1 = dyn_cast<ConstantExpr>(C1)) {
1924f4a2713aSLionel Sambuc       if ((CE1->getOpcode() == Instruction::SExt && ICmpInst::isSigned(pred)) ||
1925f4a2713aSLionel Sambuc           (CE1->getOpcode() == Instruction::ZExt && !ICmpInst::isSigned(pred))){
1926f4a2713aSLionel Sambuc         Constant *CE1Op0 = CE1->getOperand(0);
1927f4a2713aSLionel Sambuc         Constant *CE1Inverse = ConstantExpr::getTrunc(CE1, CE1Op0->getType());
1928f4a2713aSLionel Sambuc         if (CE1Inverse == CE1Op0) {
1929f4a2713aSLionel Sambuc           // Check whether we can safely truncate the right hand side.
1930f4a2713aSLionel Sambuc           Constant *C2Inverse = ConstantExpr::getTrunc(C2, CE1Op0->getType());
1931f4a2713aSLionel Sambuc           if (ConstantExpr::getCast(CE1->getOpcode(), C2Inverse,
1932f4a2713aSLionel Sambuc                                     C2->getType()) == C2)
1933f4a2713aSLionel Sambuc             return ConstantExpr::getICmp(pred, CE1Inverse, C2Inverse);
1934f4a2713aSLionel Sambuc         }
1935f4a2713aSLionel Sambuc       }
1936f4a2713aSLionel Sambuc     }
1937f4a2713aSLionel Sambuc 
1938f4a2713aSLionel Sambuc     if ((!isa<ConstantExpr>(C1) && isa<ConstantExpr>(C2)) ||
1939f4a2713aSLionel Sambuc         (C1->isNullValue() && !C2->isNullValue())) {
1940f4a2713aSLionel Sambuc       // If C2 is a constant expr and C1 isn't, flip them around and fold the
1941f4a2713aSLionel Sambuc       // other way if possible.
1942f4a2713aSLionel Sambuc       // Also, if C1 is null and C2 isn't, flip them around.
1943f4a2713aSLionel Sambuc       pred = ICmpInst::getSwappedPredicate((ICmpInst::Predicate)pred);
1944f4a2713aSLionel Sambuc       return ConstantExpr::getICmp(pred, C2, C1);
1945f4a2713aSLionel Sambuc     }
1946f4a2713aSLionel Sambuc   }
1947*0a6a1f1dSLionel Sambuc   return nullptr;
1948f4a2713aSLionel Sambuc }
1949f4a2713aSLionel Sambuc 
1950f4a2713aSLionel Sambuc /// isInBoundsIndices - Test whether the given sequence of *normalized* indices
1951f4a2713aSLionel Sambuc /// is "inbounds".
1952f4a2713aSLionel Sambuc template<typename IndexTy>
isInBoundsIndices(ArrayRef<IndexTy> Idxs)1953f4a2713aSLionel Sambuc static bool isInBoundsIndices(ArrayRef<IndexTy> Idxs) {
1954f4a2713aSLionel Sambuc   // No indices means nothing that could be out of bounds.
1955f4a2713aSLionel Sambuc   if (Idxs.empty()) return true;
1956f4a2713aSLionel Sambuc 
1957f4a2713aSLionel Sambuc   // If the first index is zero, it's in bounds.
1958f4a2713aSLionel Sambuc   if (cast<Constant>(Idxs[0])->isNullValue()) return true;
1959f4a2713aSLionel Sambuc 
1960f4a2713aSLionel Sambuc   // If the first index is one and all the rest are zero, it's in bounds,
1961f4a2713aSLionel Sambuc   // by the one-past-the-end rule.
1962f4a2713aSLionel Sambuc   if (!cast<ConstantInt>(Idxs[0])->isOne())
1963f4a2713aSLionel Sambuc     return false;
1964f4a2713aSLionel Sambuc   for (unsigned i = 1, e = Idxs.size(); i != e; ++i)
1965f4a2713aSLionel Sambuc     if (!cast<Constant>(Idxs[i])->isNullValue())
1966f4a2713aSLionel Sambuc       return false;
1967f4a2713aSLionel Sambuc   return true;
1968f4a2713aSLionel Sambuc }
1969f4a2713aSLionel Sambuc 
1970f4a2713aSLionel Sambuc /// \brief Test whether a given ConstantInt is in-range for a SequentialType.
isIndexInRangeOfSequentialType(const SequentialType * STy,const ConstantInt * CI)1971f4a2713aSLionel Sambuc static bool isIndexInRangeOfSequentialType(const SequentialType *STy,
1972f4a2713aSLionel Sambuc                                            const ConstantInt *CI) {
1973f4a2713aSLionel Sambuc   if (const PointerType *PTy = dyn_cast<PointerType>(STy))
1974f4a2713aSLionel Sambuc     // Only handle pointers to sized types, not pointers to functions.
1975f4a2713aSLionel Sambuc     return PTy->getElementType()->isSized();
1976f4a2713aSLionel Sambuc 
1977f4a2713aSLionel Sambuc   uint64_t NumElements = 0;
1978f4a2713aSLionel Sambuc   // Determine the number of elements in our sequential type.
1979f4a2713aSLionel Sambuc   if (const ArrayType *ATy = dyn_cast<ArrayType>(STy))
1980f4a2713aSLionel Sambuc     NumElements = ATy->getNumElements();
1981f4a2713aSLionel Sambuc   else if (const VectorType *VTy = dyn_cast<VectorType>(STy))
1982f4a2713aSLionel Sambuc     NumElements = VTy->getNumElements();
1983f4a2713aSLionel Sambuc 
1984f4a2713aSLionel Sambuc   assert((isa<ArrayType>(STy) || NumElements > 0) &&
1985f4a2713aSLionel Sambuc          "didn't expect non-array type to have zero elements!");
1986f4a2713aSLionel Sambuc 
1987f4a2713aSLionel Sambuc   // We cannot bounds check the index if it doesn't fit in an int64_t.
1988f4a2713aSLionel Sambuc   if (CI->getValue().getActiveBits() > 64)
1989f4a2713aSLionel Sambuc     return false;
1990f4a2713aSLionel Sambuc 
1991f4a2713aSLionel Sambuc   // A negative index or an index past the end of our sequential type is
1992f4a2713aSLionel Sambuc   // considered out-of-range.
1993f4a2713aSLionel Sambuc   int64_t IndexVal = CI->getSExtValue();
1994f4a2713aSLionel Sambuc   if (IndexVal < 0 || (NumElements > 0 && (uint64_t)IndexVal >= NumElements))
1995f4a2713aSLionel Sambuc     return false;
1996f4a2713aSLionel Sambuc 
1997f4a2713aSLionel Sambuc   // Otherwise, it is in-range.
1998f4a2713aSLionel Sambuc   return true;
1999f4a2713aSLionel Sambuc }
2000f4a2713aSLionel Sambuc 
2001f4a2713aSLionel Sambuc template<typename IndexTy>
ConstantFoldGetElementPtrImpl(Constant * C,bool inBounds,ArrayRef<IndexTy> Idxs)2002f4a2713aSLionel Sambuc static Constant *ConstantFoldGetElementPtrImpl(Constant *C,
2003f4a2713aSLionel Sambuc                                                bool inBounds,
2004f4a2713aSLionel Sambuc                                                ArrayRef<IndexTy> Idxs) {
2005f4a2713aSLionel Sambuc   if (Idxs.empty()) return C;
2006f4a2713aSLionel Sambuc   Constant *Idx0 = cast<Constant>(Idxs[0]);
2007f4a2713aSLionel Sambuc   if ((Idxs.size() == 1 && Idx0->isNullValue()))
2008f4a2713aSLionel Sambuc     return C;
2009f4a2713aSLionel Sambuc 
2010f4a2713aSLionel Sambuc   if (isa<UndefValue>(C)) {
2011f4a2713aSLionel Sambuc     PointerType *Ptr = cast<PointerType>(C->getType());
2012f4a2713aSLionel Sambuc     Type *Ty = GetElementPtrInst::getIndexedType(Ptr, Idxs);
2013*0a6a1f1dSLionel Sambuc     assert(Ty && "Invalid indices for GEP!");
2014f4a2713aSLionel Sambuc     return UndefValue::get(PointerType::get(Ty, Ptr->getAddressSpace()));
2015f4a2713aSLionel Sambuc   }
2016f4a2713aSLionel Sambuc 
2017f4a2713aSLionel Sambuc   if (C->isNullValue()) {
2018f4a2713aSLionel Sambuc     bool isNull = true;
2019f4a2713aSLionel Sambuc     for (unsigned i = 0, e = Idxs.size(); i != e; ++i)
2020f4a2713aSLionel Sambuc       if (!cast<Constant>(Idxs[i])->isNullValue()) {
2021f4a2713aSLionel Sambuc         isNull = false;
2022f4a2713aSLionel Sambuc         break;
2023f4a2713aSLionel Sambuc       }
2024f4a2713aSLionel Sambuc     if (isNull) {
2025f4a2713aSLionel Sambuc       PointerType *Ptr = cast<PointerType>(C->getType());
2026f4a2713aSLionel Sambuc       Type *Ty = GetElementPtrInst::getIndexedType(Ptr, Idxs);
2027*0a6a1f1dSLionel Sambuc       assert(Ty && "Invalid indices for GEP!");
2028f4a2713aSLionel Sambuc       return ConstantPointerNull::get(PointerType::get(Ty,
2029f4a2713aSLionel Sambuc                                                        Ptr->getAddressSpace()));
2030f4a2713aSLionel Sambuc     }
2031f4a2713aSLionel Sambuc   }
2032f4a2713aSLionel Sambuc 
2033f4a2713aSLionel Sambuc   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
2034f4a2713aSLionel Sambuc     // Combine Indices - If the source pointer to this getelementptr instruction
2035f4a2713aSLionel Sambuc     // is a getelementptr instruction, combine the indices of the two
2036f4a2713aSLionel Sambuc     // getelementptr instructions into a single instruction.
2037f4a2713aSLionel Sambuc     //
2038f4a2713aSLionel Sambuc     if (CE->getOpcode() == Instruction::GetElementPtr) {
2039*0a6a1f1dSLionel Sambuc       Type *LastTy = nullptr;
2040f4a2713aSLionel Sambuc       for (gep_type_iterator I = gep_type_begin(CE), E = gep_type_end(CE);
2041f4a2713aSLionel Sambuc            I != E; ++I)
2042f4a2713aSLionel Sambuc         LastTy = *I;
2043f4a2713aSLionel Sambuc 
2044f4a2713aSLionel Sambuc       // We cannot combine indices if doing so would take us outside of an
2045f4a2713aSLionel Sambuc       // array or vector.  Doing otherwise could trick us if we evaluated such a
2046f4a2713aSLionel Sambuc       // GEP as part of a load.
2047f4a2713aSLionel Sambuc       //
2048f4a2713aSLionel Sambuc       // e.g. Consider if the original GEP was:
2049f4a2713aSLionel Sambuc       // i8* getelementptr ({ [2 x i8], i32, i8, [3 x i8] }* @main.c,
2050f4a2713aSLionel Sambuc       //                    i32 0, i32 0, i64 0)
2051f4a2713aSLionel Sambuc       //
2052f4a2713aSLionel Sambuc       // If we then tried to offset it by '8' to get to the third element,
2053f4a2713aSLionel Sambuc       // an i8, we should *not* get:
2054f4a2713aSLionel Sambuc       // i8* getelementptr ({ [2 x i8], i32, i8, [3 x i8] }* @main.c,
2055f4a2713aSLionel Sambuc       //                    i32 0, i32 0, i64 8)
2056f4a2713aSLionel Sambuc       //
2057f4a2713aSLionel Sambuc       // This GEP tries to index array element '8  which runs out-of-bounds.
2058f4a2713aSLionel Sambuc       // Subsequent evaluation would get confused and produce erroneous results.
2059f4a2713aSLionel Sambuc       //
2060f4a2713aSLionel Sambuc       // The following prohibits such a GEP from being formed by checking to see
2061f4a2713aSLionel Sambuc       // if the index is in-range with respect to an array or vector.
2062f4a2713aSLionel Sambuc       bool PerformFold = false;
2063f4a2713aSLionel Sambuc       if (Idx0->isNullValue())
2064f4a2713aSLionel Sambuc         PerformFold = true;
2065f4a2713aSLionel Sambuc       else if (SequentialType *STy = dyn_cast_or_null<SequentialType>(LastTy))
2066f4a2713aSLionel Sambuc         if (ConstantInt *CI = dyn_cast<ConstantInt>(Idx0))
2067f4a2713aSLionel Sambuc           PerformFold = isIndexInRangeOfSequentialType(STy, CI);
2068f4a2713aSLionel Sambuc 
2069f4a2713aSLionel Sambuc       if (PerformFold) {
2070f4a2713aSLionel Sambuc         SmallVector<Value*, 16> NewIndices;
2071f4a2713aSLionel Sambuc         NewIndices.reserve(Idxs.size() + CE->getNumOperands());
2072f4a2713aSLionel Sambuc         for (unsigned i = 1, e = CE->getNumOperands()-1; i != e; ++i)
2073f4a2713aSLionel Sambuc           NewIndices.push_back(CE->getOperand(i));
2074f4a2713aSLionel Sambuc 
2075f4a2713aSLionel Sambuc         // Add the last index of the source with the first index of the new GEP.
2076f4a2713aSLionel Sambuc         // Make sure to handle the case when they are actually different types.
2077f4a2713aSLionel Sambuc         Constant *Combined = CE->getOperand(CE->getNumOperands()-1);
2078f4a2713aSLionel Sambuc         // Otherwise it must be an array.
2079f4a2713aSLionel Sambuc         if (!Idx0->isNullValue()) {
2080f4a2713aSLionel Sambuc           Type *IdxTy = Combined->getType();
2081f4a2713aSLionel Sambuc           if (IdxTy != Idx0->getType()) {
2082f4a2713aSLionel Sambuc             Type *Int64Ty = Type::getInt64Ty(IdxTy->getContext());
2083f4a2713aSLionel Sambuc             Constant *C1 = ConstantExpr::getSExtOrBitCast(Idx0, Int64Ty);
2084f4a2713aSLionel Sambuc             Constant *C2 = ConstantExpr::getSExtOrBitCast(Combined, Int64Ty);
2085f4a2713aSLionel Sambuc             Combined = ConstantExpr::get(Instruction::Add, C1, C2);
2086f4a2713aSLionel Sambuc           } else {
2087f4a2713aSLionel Sambuc             Combined =
2088f4a2713aSLionel Sambuc               ConstantExpr::get(Instruction::Add, Idx0, Combined);
2089f4a2713aSLionel Sambuc           }
2090f4a2713aSLionel Sambuc         }
2091f4a2713aSLionel Sambuc 
2092f4a2713aSLionel Sambuc         NewIndices.push_back(Combined);
2093f4a2713aSLionel Sambuc         NewIndices.append(Idxs.begin() + 1, Idxs.end());
2094f4a2713aSLionel Sambuc         return
2095f4a2713aSLionel Sambuc           ConstantExpr::getGetElementPtr(CE->getOperand(0), NewIndices,
2096f4a2713aSLionel Sambuc                                          inBounds &&
2097f4a2713aSLionel Sambuc                                            cast<GEPOperator>(CE)->isInBounds());
2098f4a2713aSLionel Sambuc       }
2099f4a2713aSLionel Sambuc     }
2100f4a2713aSLionel Sambuc 
2101f4a2713aSLionel Sambuc     // Attempt to fold casts to the same type away.  For example, folding:
2102f4a2713aSLionel Sambuc     //
2103f4a2713aSLionel Sambuc     //   i32* getelementptr ([2 x i32]* bitcast ([3 x i32]* %X to [2 x i32]*),
2104f4a2713aSLionel Sambuc     //                       i64 0, i64 0)
2105f4a2713aSLionel Sambuc     // into:
2106f4a2713aSLionel Sambuc     //
2107f4a2713aSLionel Sambuc     //   i32* getelementptr ([3 x i32]* %X, i64 0, i64 0)
2108f4a2713aSLionel Sambuc     //
2109f4a2713aSLionel Sambuc     // Don't fold if the cast is changing address spaces.
2110f4a2713aSLionel Sambuc     if (CE->isCast() && Idxs.size() > 1 && Idx0->isNullValue()) {
2111f4a2713aSLionel Sambuc       PointerType *SrcPtrTy =
2112f4a2713aSLionel Sambuc         dyn_cast<PointerType>(CE->getOperand(0)->getType());
2113f4a2713aSLionel Sambuc       PointerType *DstPtrTy = dyn_cast<PointerType>(CE->getType());
2114f4a2713aSLionel Sambuc       if (SrcPtrTy && DstPtrTy) {
2115f4a2713aSLionel Sambuc         ArrayType *SrcArrayTy =
2116f4a2713aSLionel Sambuc           dyn_cast<ArrayType>(SrcPtrTy->getElementType());
2117f4a2713aSLionel Sambuc         ArrayType *DstArrayTy =
2118f4a2713aSLionel Sambuc           dyn_cast<ArrayType>(DstPtrTy->getElementType());
2119f4a2713aSLionel Sambuc         if (SrcArrayTy && DstArrayTy
2120f4a2713aSLionel Sambuc             && SrcArrayTy->getElementType() == DstArrayTy->getElementType()
2121f4a2713aSLionel Sambuc             && SrcPtrTy->getAddressSpace() == DstPtrTy->getAddressSpace())
2122f4a2713aSLionel Sambuc           return ConstantExpr::getGetElementPtr((Constant*)CE->getOperand(0),
2123f4a2713aSLionel Sambuc                                                 Idxs, inBounds);
2124f4a2713aSLionel Sambuc       }
2125f4a2713aSLionel Sambuc     }
2126f4a2713aSLionel Sambuc   }
2127f4a2713aSLionel Sambuc 
2128f4a2713aSLionel Sambuc   // Check to see if any array indices are not within the corresponding
2129f4a2713aSLionel Sambuc   // notional array or vector bounds. If so, try to determine if they can be
2130f4a2713aSLionel Sambuc   // factored out into preceding dimensions.
2131f4a2713aSLionel Sambuc   bool Unknown = false;
2132f4a2713aSLionel Sambuc   SmallVector<Constant *, 8> NewIdxs;
2133f4a2713aSLionel Sambuc   Type *Ty = C->getType();
2134*0a6a1f1dSLionel Sambuc   Type *Prev = nullptr;
2135f4a2713aSLionel Sambuc   for (unsigned i = 0, e = Idxs.size(); i != e;
2136f4a2713aSLionel Sambuc        Prev = Ty, Ty = cast<CompositeType>(Ty)->getTypeAtIndex(Idxs[i]), ++i) {
2137f4a2713aSLionel Sambuc     if (ConstantInt *CI = dyn_cast<ConstantInt>(Idxs[i])) {
2138f4a2713aSLionel Sambuc       if (isa<ArrayType>(Ty) || isa<VectorType>(Ty))
2139f4a2713aSLionel Sambuc         if (CI->getSExtValue() > 0 &&
2140f4a2713aSLionel Sambuc             !isIndexInRangeOfSequentialType(cast<SequentialType>(Ty), CI)) {
2141f4a2713aSLionel Sambuc           if (isa<SequentialType>(Prev)) {
2142f4a2713aSLionel Sambuc             // It's out of range, but we can factor it into the prior
2143f4a2713aSLionel Sambuc             // dimension.
2144f4a2713aSLionel Sambuc             NewIdxs.resize(Idxs.size());
2145f4a2713aSLionel Sambuc             uint64_t NumElements = 0;
2146f4a2713aSLionel Sambuc             if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty))
2147f4a2713aSLionel Sambuc               NumElements = ATy->getNumElements();
2148f4a2713aSLionel Sambuc             else
2149f4a2713aSLionel Sambuc               NumElements = cast<VectorType>(Ty)->getNumElements();
2150f4a2713aSLionel Sambuc 
2151f4a2713aSLionel Sambuc             ConstantInt *Factor = ConstantInt::get(CI->getType(), NumElements);
2152f4a2713aSLionel Sambuc             NewIdxs[i] = ConstantExpr::getSRem(CI, Factor);
2153f4a2713aSLionel Sambuc 
2154f4a2713aSLionel Sambuc             Constant *PrevIdx = cast<Constant>(Idxs[i-1]);
2155f4a2713aSLionel Sambuc             Constant *Div = ConstantExpr::getSDiv(CI, Factor);
2156f4a2713aSLionel Sambuc 
2157f4a2713aSLionel Sambuc             // Before adding, extend both operands to i64 to avoid
2158f4a2713aSLionel Sambuc             // overflow trouble.
2159f4a2713aSLionel Sambuc             if (!PrevIdx->getType()->isIntegerTy(64))
2160f4a2713aSLionel Sambuc               PrevIdx = ConstantExpr::getSExt(PrevIdx,
2161f4a2713aSLionel Sambuc                                            Type::getInt64Ty(Div->getContext()));
2162f4a2713aSLionel Sambuc             if (!Div->getType()->isIntegerTy(64))
2163f4a2713aSLionel Sambuc               Div = ConstantExpr::getSExt(Div,
2164f4a2713aSLionel Sambuc                                           Type::getInt64Ty(Div->getContext()));
2165f4a2713aSLionel Sambuc 
2166f4a2713aSLionel Sambuc             NewIdxs[i-1] = ConstantExpr::getAdd(PrevIdx, Div);
2167f4a2713aSLionel Sambuc           } else {
2168f4a2713aSLionel Sambuc             // It's out of range, but the prior dimension is a struct
2169f4a2713aSLionel Sambuc             // so we can't do anything about it.
2170f4a2713aSLionel Sambuc             Unknown = true;
2171f4a2713aSLionel Sambuc           }
2172f4a2713aSLionel Sambuc         }
2173f4a2713aSLionel Sambuc     } else {
2174f4a2713aSLionel Sambuc       // We don't know if it's in range or not.
2175f4a2713aSLionel Sambuc       Unknown = true;
2176f4a2713aSLionel Sambuc     }
2177f4a2713aSLionel Sambuc   }
2178f4a2713aSLionel Sambuc 
2179f4a2713aSLionel Sambuc   // If we did any factoring, start over with the adjusted indices.
2180f4a2713aSLionel Sambuc   if (!NewIdxs.empty()) {
2181f4a2713aSLionel Sambuc     for (unsigned i = 0, e = Idxs.size(); i != e; ++i)
2182f4a2713aSLionel Sambuc       if (!NewIdxs[i]) NewIdxs[i] = cast<Constant>(Idxs[i]);
2183f4a2713aSLionel Sambuc     return ConstantExpr::getGetElementPtr(C, NewIdxs, inBounds);
2184f4a2713aSLionel Sambuc   }
2185f4a2713aSLionel Sambuc 
2186f4a2713aSLionel Sambuc   // If all indices are known integers and normalized, we can do a simple
2187f4a2713aSLionel Sambuc   // check for the "inbounds" property.
2188*0a6a1f1dSLionel Sambuc   if (!Unknown && !inBounds)
2189*0a6a1f1dSLionel Sambuc     if (auto *GV = dyn_cast<GlobalVariable>(C))
2190*0a6a1f1dSLionel Sambuc       if (!GV->hasExternalWeakLinkage() && isInBoundsIndices(Idxs))
2191f4a2713aSLionel Sambuc         return ConstantExpr::getInBoundsGetElementPtr(C, Idxs);
2192f4a2713aSLionel Sambuc 
2193*0a6a1f1dSLionel Sambuc   return nullptr;
2194f4a2713aSLionel Sambuc }
2195f4a2713aSLionel Sambuc 
ConstantFoldGetElementPtr(Constant * C,bool inBounds,ArrayRef<Constant * > Idxs)2196f4a2713aSLionel Sambuc Constant *llvm::ConstantFoldGetElementPtr(Constant *C,
2197f4a2713aSLionel Sambuc                                           bool inBounds,
2198f4a2713aSLionel Sambuc                                           ArrayRef<Constant *> Idxs) {
2199f4a2713aSLionel Sambuc   return ConstantFoldGetElementPtrImpl(C, inBounds, Idxs);
2200f4a2713aSLionel Sambuc }
2201f4a2713aSLionel Sambuc 
ConstantFoldGetElementPtr(Constant * C,bool inBounds,ArrayRef<Value * > Idxs)2202f4a2713aSLionel Sambuc Constant *llvm::ConstantFoldGetElementPtr(Constant *C,
2203f4a2713aSLionel Sambuc                                           bool inBounds,
2204f4a2713aSLionel Sambuc                                           ArrayRef<Value *> Idxs) {
2205f4a2713aSLionel Sambuc   return ConstantFoldGetElementPtrImpl(C, inBounds, Idxs);
2206f4a2713aSLionel Sambuc }
2207