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