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