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