xref: /llvm-project/llvm/lib/IR/ConstantFold.cpp (revision 6f10b65297707c1e964d570421ab4559dc2928d4)
1 //===- ConstantFold.cpp - LLVM constant folder ----------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file implements folding of constants for LLVM.  This implements the
10 // (internal) ConstantFold.h interface, which is used by the
11 // ConstantExpr::get* methods to automatically fold constants when possible.
12 //
13 // The current constant folding implementation is implemented in two pieces: the
14 // pieces that don't need DataLayout, and the pieces that do. This is to avoid
15 // a dependence in IR on Target.
16 //
17 //===----------------------------------------------------------------------===//
18 
19 #include "llvm/IR/ConstantFold.h"
20 #include "llvm/ADT/APSInt.h"
21 #include "llvm/ADT/SmallVector.h"
22 #include "llvm/IR/Constants.h"
23 #include "llvm/IR/DerivedTypes.h"
24 #include "llvm/IR/Function.h"
25 #include "llvm/IR/GlobalAlias.h"
26 #include "llvm/IR/GlobalVariable.h"
27 #include "llvm/IR/Instructions.h"
28 #include "llvm/IR/Module.h"
29 #include "llvm/IR/Operator.h"
30 #include "llvm/IR/PatternMatch.h"
31 #include "llvm/Support/ErrorHandling.h"
32 using namespace llvm;
33 using namespace llvm::PatternMatch;
34 
35 //===----------------------------------------------------------------------===//
36 //                ConstantFold*Instruction Implementations
37 //===----------------------------------------------------------------------===//
38 
39 /// This function determines which opcode to use to fold two constant cast
40 /// expressions together. It uses CastInst::isEliminableCastPair to determine
41 /// the opcode. Consequently its just a wrapper around that function.
42 /// Determine if it is valid to fold a cast of a cast
43 static unsigned
44 foldConstantCastPair(
45   unsigned opc,          ///< opcode of the second cast constant expression
46   ConstantExpr *Op,      ///< the first cast constant expression
47   Type *DstTy            ///< destination type of the first cast
48 ) {
49   assert(Op && Op->isCast() && "Can't fold cast of cast without a cast!");
50   assert(DstTy && DstTy->isFirstClassType() && "Invalid cast destination type");
51   assert(CastInst::isCast(opc) && "Invalid cast opcode");
52 
53   // The types and opcodes for the two Cast constant expressions
54   Type *SrcTy = Op->getOperand(0)->getType();
55   Type *MidTy = Op->getType();
56   Instruction::CastOps firstOp = Instruction::CastOps(Op->getOpcode());
57   Instruction::CastOps secondOp = Instruction::CastOps(opc);
58 
59   // Assume that pointers are never more than 64 bits wide, and only use this
60   // for the middle type. Otherwise we could end up folding away illegal
61   // bitcasts between address spaces with different sizes.
62   IntegerType *FakeIntPtrTy = Type::getInt64Ty(DstTy->getContext());
63 
64   // Let CastInst::isEliminableCastPair do the heavy lifting.
65   return CastInst::isEliminableCastPair(firstOp, secondOp, SrcTy, MidTy, DstTy,
66                                         nullptr, FakeIntPtrTy, nullptr);
67 }
68 
69 static Constant *FoldBitCast(Constant *V, Type *DestTy) {
70   Type *SrcTy = V->getType();
71   if (SrcTy == DestTy)
72     return V; // no-op cast
73 
74   // Handle casts from one vector constant to another.  We know that the src
75   // and dest type have the same size (otherwise its an illegal cast).
76   if (VectorType *DestPTy = dyn_cast<VectorType>(DestTy)) {
77     if (V->isAllOnesValue())
78       return Constant::getAllOnesValue(DestTy);
79 
80     // Canonicalize scalar-to-vector bitcasts into vector-to-vector bitcasts
81     // This allows for other simplifications (although some of them
82     // can only be handled by Analysis/ConstantFolding.cpp).
83     if (!isa<VectorType>(SrcTy))
84       if (isa<ConstantInt>(V) || isa<ConstantFP>(V))
85         return ConstantExpr::getBitCast(ConstantVector::get(V), DestPTy);
86     return nullptr;
87   }
88 
89   // Handle integral constant input.
90   if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
91     // See note below regarding the PPC_FP128 restriction.
92     if (DestTy->isFloatingPointTy() && !DestTy->isPPC_FP128Ty())
93       return ConstantFP::get(DestTy->getContext(),
94                              APFloat(DestTy->getFltSemantics(),
95                                      CI->getValue()));
96 
97     // Otherwise, can't fold this (vector?)
98     return nullptr;
99   }
100 
101   // Handle ConstantFP input: FP -> Integral.
102   if (ConstantFP *FP = dyn_cast<ConstantFP>(V)) {
103     // PPC_FP128 is really the sum of two consecutive doubles, where the first
104     // double is always stored first in memory, regardless of the target
105     // endianness. The memory layout of i128, however, depends on the target
106     // endianness, and so we can't fold this without target endianness
107     // information. This should instead be handled by
108     // Analysis/ConstantFolding.cpp
109     if (FP->getType()->isPPC_FP128Ty())
110       return nullptr;
111 
112     // Make sure dest type is compatible with the folded integer constant.
113     if (!DestTy->isIntegerTy())
114       return nullptr;
115 
116     return ConstantInt::get(FP->getContext(),
117                             FP->getValueAPF().bitcastToAPInt());
118   }
119 
120   return nullptr;
121 }
122 
123 static Constant *foldMaybeUndesirableCast(unsigned opc, Constant *V,
124                                           Type *DestTy) {
125   return ConstantExpr::isDesirableCastOp(opc)
126              ? ConstantExpr::getCast(opc, V, DestTy)
127              : ConstantFoldCastInstruction(opc, V, DestTy);
128 }
129 
130 Constant *llvm::ConstantFoldCastInstruction(unsigned opc, Constant *V,
131                                             Type *DestTy) {
132   if (isa<PoisonValue>(V))
133     return PoisonValue::get(DestTy);
134 
135   if (isa<UndefValue>(V)) {
136     // zext(undef) = 0, because the top bits will be zero.
137     // sext(undef) = 0, because the top bits will all be the same.
138     // [us]itofp(undef) = 0, because the result value is bounded.
139     if (opc == Instruction::ZExt || opc == Instruction::SExt ||
140         opc == Instruction::UIToFP || opc == Instruction::SIToFP)
141       return Constant::getNullValue(DestTy);
142     return UndefValue::get(DestTy);
143   }
144 
145   if (V->isNullValue() && !DestTy->isX86_AMXTy() &&
146       opc != Instruction::AddrSpaceCast)
147     return Constant::getNullValue(DestTy);
148 
149   // If the cast operand is a constant expression, there's a few things we can
150   // do to try to simplify it.
151   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) {
152     if (CE->isCast()) {
153       // Try hard to fold cast of cast because they are often eliminable.
154       if (unsigned newOpc = foldConstantCastPair(opc, CE, DestTy))
155         return foldMaybeUndesirableCast(newOpc, CE->getOperand(0), DestTy);
156     }
157   }
158 
159   // If the cast operand is a constant vector, perform the cast by
160   // operating on each element. In the cast of bitcasts, the element
161   // count may be mismatched; don't attempt to handle that here.
162   if ((isa<ConstantVector>(V) || isa<ConstantDataVector>(V)) &&
163       DestTy->isVectorTy() &&
164       cast<FixedVectorType>(DestTy)->getNumElements() ==
165           cast<FixedVectorType>(V->getType())->getNumElements()) {
166     VectorType *DestVecTy = cast<VectorType>(DestTy);
167     Type *DstEltTy = DestVecTy->getElementType();
168     // Fast path for splatted constants.
169     if (Constant *Splat = V->getSplatValue()) {
170       Constant *Res = foldMaybeUndesirableCast(opc, Splat, DstEltTy);
171       if (!Res)
172         return nullptr;
173       return ConstantVector::getSplat(
174           cast<VectorType>(DestTy)->getElementCount(), Res);
175     }
176     SmallVector<Constant *, 16> res;
177     Type *Ty = IntegerType::get(V->getContext(), 32);
178     for (unsigned i = 0,
179                   e = cast<FixedVectorType>(V->getType())->getNumElements();
180          i != e; ++i) {
181       Constant *C = ConstantExpr::getExtractElement(V, ConstantInt::get(Ty, i));
182       Constant *Casted = foldMaybeUndesirableCast(opc, C, DstEltTy);
183       if (!Casted)
184         return nullptr;
185       res.push_back(Casted);
186     }
187     return ConstantVector::get(res);
188   }
189 
190   // We actually have to do a cast now. Perform the cast according to the
191   // opcode specified.
192   switch (opc) {
193   default:
194     llvm_unreachable("Failed to cast constant expression");
195   case Instruction::FPTrunc:
196   case Instruction::FPExt:
197     if (ConstantFP *FPC = dyn_cast<ConstantFP>(V)) {
198       bool ignored;
199       APFloat Val = FPC->getValueAPF();
200       Val.convert(DestTy->getFltSemantics(), APFloat::rmNearestTiesToEven,
201                   &ignored);
202       return ConstantFP::get(V->getContext(), Val);
203     }
204     return nullptr; // Can't fold.
205   case Instruction::FPToUI:
206   case Instruction::FPToSI:
207     if (ConstantFP *FPC = dyn_cast<ConstantFP>(V)) {
208       const APFloat &V = FPC->getValueAPF();
209       bool ignored;
210       uint32_t DestBitWidth = cast<IntegerType>(DestTy)->getBitWidth();
211       APSInt IntVal(DestBitWidth, opc == Instruction::FPToUI);
212       if (APFloat::opInvalidOp ==
213           V.convertToInteger(IntVal, APFloat::rmTowardZero, &ignored)) {
214         // Undefined behavior invoked - the destination type can't represent
215         // the input constant.
216         return PoisonValue::get(DestTy);
217       }
218       return ConstantInt::get(FPC->getContext(), IntVal);
219     }
220     return nullptr; // Can't fold.
221   case Instruction::UIToFP:
222   case Instruction::SIToFP:
223     if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
224       const APInt &api = CI->getValue();
225       APFloat apf(DestTy->getFltSemantics(),
226                   APInt::getZero(DestTy->getPrimitiveSizeInBits()));
227       apf.convertFromAPInt(api, opc==Instruction::SIToFP,
228                            APFloat::rmNearestTiesToEven);
229       return ConstantFP::get(V->getContext(), apf);
230     }
231     return nullptr;
232   case Instruction::ZExt:
233     if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
234       uint32_t BitWidth = cast<IntegerType>(DestTy)->getBitWidth();
235       return ConstantInt::get(V->getContext(),
236                               CI->getValue().zext(BitWidth));
237     }
238     return nullptr;
239   case Instruction::SExt:
240     if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
241       uint32_t BitWidth = cast<IntegerType>(DestTy)->getBitWidth();
242       return ConstantInt::get(V->getContext(),
243                               CI->getValue().sext(BitWidth));
244     }
245     return nullptr;
246   case Instruction::Trunc: {
247     if (V->getType()->isVectorTy())
248       return nullptr;
249 
250     uint32_t DestBitWidth = cast<IntegerType>(DestTy)->getBitWidth();
251     if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
252       return ConstantInt::get(V->getContext(),
253                               CI->getValue().trunc(DestBitWidth));
254     }
255 
256     return nullptr;
257   }
258   case Instruction::BitCast:
259     return FoldBitCast(V, DestTy);
260   case Instruction::AddrSpaceCast:
261   case Instruction::IntToPtr:
262   case Instruction::PtrToInt:
263     return nullptr;
264   }
265 }
266 
267 Constant *llvm::ConstantFoldSelectInstruction(Constant *Cond,
268                                               Constant *V1, Constant *V2) {
269   // Check for i1 and vector true/false conditions.
270   if (Cond->isNullValue()) return V2;
271   if (Cond->isAllOnesValue()) return V1;
272 
273   // If the condition is a vector constant, fold the result elementwise.
274   if (ConstantVector *CondV = dyn_cast<ConstantVector>(Cond)) {
275     auto *V1VTy = CondV->getType();
276     SmallVector<Constant*, 16> Result;
277     Type *Ty = IntegerType::get(CondV->getContext(), 32);
278     for (unsigned i = 0, e = V1VTy->getNumElements(); i != e; ++i) {
279       Constant *V;
280       Constant *V1Element = ConstantExpr::getExtractElement(V1,
281                                                     ConstantInt::get(Ty, i));
282       Constant *V2Element = ConstantExpr::getExtractElement(V2,
283                                                     ConstantInt::get(Ty, i));
284       auto *Cond = cast<Constant>(CondV->getOperand(i));
285       if (isa<PoisonValue>(Cond)) {
286         V = PoisonValue::get(V1Element->getType());
287       } else if (V1Element == V2Element) {
288         V = V1Element;
289       } else if (isa<UndefValue>(Cond)) {
290         V = isa<UndefValue>(V1Element) ? V1Element : V2Element;
291       } else {
292         if (!isa<ConstantInt>(Cond)) break;
293         V = Cond->isNullValue() ? V2Element : V1Element;
294       }
295       Result.push_back(V);
296     }
297 
298     // If we were able to build the vector, return it.
299     if (Result.size() == V1VTy->getNumElements())
300       return ConstantVector::get(Result);
301   }
302 
303   if (isa<PoisonValue>(Cond))
304     return PoisonValue::get(V1->getType());
305 
306   if (isa<UndefValue>(Cond)) {
307     if (isa<UndefValue>(V1)) return V1;
308     return V2;
309   }
310 
311   if (V1 == V2) return V1;
312 
313   if (isa<PoisonValue>(V1))
314     return V2;
315   if (isa<PoisonValue>(V2))
316     return V1;
317 
318   // If the true or false value is undef, we can fold to the other value as
319   // long as the other value isn't poison.
320   auto NotPoison = [](Constant *C) {
321     if (isa<PoisonValue>(C))
322       return false;
323 
324     // TODO: We can analyze ConstExpr by opcode to determine if there is any
325     //       possibility of poison.
326     if (isa<ConstantExpr>(C))
327       return false;
328 
329     if (isa<ConstantInt>(C) || isa<GlobalVariable>(C) || isa<ConstantFP>(C) ||
330         isa<ConstantPointerNull>(C) || isa<Function>(C))
331       return true;
332 
333     if (C->getType()->isVectorTy())
334       return !C->containsPoisonElement() && !C->containsConstantExpression();
335 
336     // TODO: Recursively analyze aggregates or other constants.
337     return false;
338   };
339   if (isa<UndefValue>(V1) && NotPoison(V2)) return V2;
340   if (isa<UndefValue>(V2) && NotPoison(V1)) return V1;
341 
342   return nullptr;
343 }
344 
345 Constant *llvm::ConstantFoldExtractElementInstruction(Constant *Val,
346                                                       Constant *Idx) {
347   auto *ValVTy = cast<VectorType>(Val->getType());
348 
349   // extractelt poison, C -> poison
350   // extractelt C, undef -> poison
351   if (isa<PoisonValue>(Val) || isa<UndefValue>(Idx))
352     return PoisonValue::get(ValVTy->getElementType());
353 
354   // extractelt undef, C -> undef
355   if (isa<UndefValue>(Val))
356     return UndefValue::get(ValVTy->getElementType());
357 
358   auto *CIdx = dyn_cast<ConstantInt>(Idx);
359   if (!CIdx)
360     return nullptr;
361 
362   if (auto *ValFVTy = dyn_cast<FixedVectorType>(Val->getType())) {
363     // ee({w,x,y,z}, wrong_value) -> poison
364     if (CIdx->uge(ValFVTy->getNumElements()))
365       return PoisonValue::get(ValFVTy->getElementType());
366   }
367 
368   // ee (gep (ptr, idx0, ...), idx) -> gep (ee (ptr, idx), ee (idx0, idx), ...)
369   if (auto *CE = dyn_cast<ConstantExpr>(Val)) {
370     if (auto *GEP = dyn_cast<GEPOperator>(CE)) {
371       SmallVector<Constant *, 8> Ops;
372       Ops.reserve(CE->getNumOperands());
373       for (unsigned i = 0, e = CE->getNumOperands(); i != e; ++i) {
374         Constant *Op = CE->getOperand(i);
375         if (Op->getType()->isVectorTy()) {
376           Constant *ScalarOp = ConstantExpr::getExtractElement(Op, Idx);
377           if (!ScalarOp)
378             return nullptr;
379           Ops.push_back(ScalarOp);
380         } else
381           Ops.push_back(Op);
382       }
383       return CE->getWithOperands(Ops, ValVTy->getElementType(), false,
384                                  GEP->getSourceElementType());
385     } else if (CE->getOpcode() == Instruction::InsertElement) {
386       if (const auto *IEIdx = dyn_cast<ConstantInt>(CE->getOperand(2))) {
387         if (APSInt::isSameValue(APSInt(IEIdx->getValue()),
388                                 APSInt(CIdx->getValue()))) {
389           return CE->getOperand(1);
390         } else {
391           return ConstantExpr::getExtractElement(CE->getOperand(0), CIdx);
392         }
393       }
394     }
395   }
396 
397   if (Constant *C = Val->getAggregateElement(CIdx))
398     return C;
399 
400   // Lane < Splat minimum vector width => extractelt Splat(x), Lane -> x
401   if (CIdx->getValue().ult(ValVTy->getElementCount().getKnownMinValue())) {
402     if (Constant *SplatVal = Val->getSplatValue())
403       return SplatVal;
404   }
405 
406   return nullptr;
407 }
408 
409 Constant *llvm::ConstantFoldInsertElementInstruction(Constant *Val,
410                                                      Constant *Elt,
411                                                      Constant *Idx) {
412   if (isa<UndefValue>(Idx))
413     return PoisonValue::get(Val->getType());
414 
415   // Inserting null into all zeros is still all zeros.
416   // TODO: This is true for undef and poison splats too.
417   if (isa<ConstantAggregateZero>(Val) && Elt->isNullValue())
418     return Val;
419 
420   ConstantInt *CIdx = dyn_cast<ConstantInt>(Idx);
421   if (!CIdx) return nullptr;
422 
423   // Do not iterate on scalable vector. The num of elements is unknown at
424   // compile-time.
425   if (isa<ScalableVectorType>(Val->getType()))
426     return nullptr;
427 
428   auto *ValTy = cast<FixedVectorType>(Val->getType());
429 
430   unsigned NumElts = ValTy->getNumElements();
431   if (CIdx->uge(NumElts))
432     return PoisonValue::get(Val->getType());
433 
434   SmallVector<Constant*, 16> Result;
435   Result.reserve(NumElts);
436   auto *Ty = Type::getInt32Ty(Val->getContext());
437   uint64_t IdxVal = CIdx->getZExtValue();
438   for (unsigned i = 0; i != NumElts; ++i) {
439     if (i == IdxVal) {
440       Result.push_back(Elt);
441       continue;
442     }
443 
444     Constant *C = ConstantExpr::getExtractElement(Val, ConstantInt::get(Ty, i));
445     Result.push_back(C);
446   }
447 
448   return ConstantVector::get(Result);
449 }
450 
451 Constant *llvm::ConstantFoldShuffleVectorInstruction(Constant *V1, Constant *V2,
452                                                      ArrayRef<int> Mask) {
453   auto *V1VTy = cast<VectorType>(V1->getType());
454   unsigned MaskNumElts = Mask.size();
455   auto MaskEltCount =
456       ElementCount::get(MaskNumElts, isa<ScalableVectorType>(V1VTy));
457   Type *EltTy = V1VTy->getElementType();
458 
459   // Poison shuffle mask -> poison value.
460   if (all_of(Mask, [](int Elt) { return Elt == PoisonMaskElem; })) {
461     return PoisonValue::get(VectorType::get(EltTy, MaskEltCount));
462   }
463 
464   // If the mask is all zeros this is a splat, no need to go through all
465   // elements.
466   if (all_of(Mask, [](int Elt) { return Elt == 0; })) {
467     Type *Ty = IntegerType::get(V1->getContext(), 32);
468     Constant *Elt =
469         ConstantExpr::getExtractElement(V1, ConstantInt::get(Ty, 0));
470 
471     if (Elt->isNullValue()) {
472       auto *VTy = VectorType::get(EltTy, MaskEltCount);
473       return ConstantAggregateZero::get(VTy);
474     } else if (!MaskEltCount.isScalable())
475       return ConstantVector::getSplat(MaskEltCount, Elt);
476   }
477 
478   // Do not iterate on scalable vector. The num of elements is unknown at
479   // compile-time.
480   if (isa<ScalableVectorType>(V1VTy))
481     return nullptr;
482 
483   unsigned SrcNumElts = V1VTy->getElementCount().getKnownMinValue();
484 
485   // Loop over the shuffle mask, evaluating each element.
486   SmallVector<Constant*, 32> Result;
487   for (unsigned i = 0; i != MaskNumElts; ++i) {
488     int Elt = Mask[i];
489     if (Elt == -1) {
490       Result.push_back(UndefValue::get(EltTy));
491       continue;
492     }
493     Constant *InElt;
494     if (unsigned(Elt) >= SrcNumElts*2)
495       InElt = UndefValue::get(EltTy);
496     else if (unsigned(Elt) >= SrcNumElts) {
497       Type *Ty = IntegerType::get(V2->getContext(), 32);
498       InElt =
499         ConstantExpr::getExtractElement(V2,
500                                         ConstantInt::get(Ty, Elt - SrcNumElts));
501     } else {
502       Type *Ty = IntegerType::get(V1->getContext(), 32);
503       InElt = ConstantExpr::getExtractElement(V1, ConstantInt::get(Ty, Elt));
504     }
505     Result.push_back(InElt);
506   }
507 
508   return ConstantVector::get(Result);
509 }
510 
511 Constant *llvm::ConstantFoldExtractValueInstruction(Constant *Agg,
512                                                     ArrayRef<unsigned> Idxs) {
513   // Base case: no indices, so return the entire value.
514   if (Idxs.empty())
515     return Agg;
516 
517   if (Constant *C = Agg->getAggregateElement(Idxs[0]))
518     return ConstantFoldExtractValueInstruction(C, Idxs.slice(1));
519 
520   return nullptr;
521 }
522 
523 Constant *llvm::ConstantFoldInsertValueInstruction(Constant *Agg,
524                                                    Constant *Val,
525                                                    ArrayRef<unsigned> Idxs) {
526   // Base case: no indices, so replace the entire value.
527   if (Idxs.empty())
528     return Val;
529 
530   unsigned NumElts;
531   if (StructType *ST = dyn_cast<StructType>(Agg->getType()))
532     NumElts = ST->getNumElements();
533   else
534     NumElts = cast<ArrayType>(Agg->getType())->getNumElements();
535 
536   SmallVector<Constant*, 32> Result;
537   for (unsigned i = 0; i != NumElts; ++i) {
538     Constant *C = Agg->getAggregateElement(i);
539     if (!C) return nullptr;
540 
541     if (Idxs[0] == i)
542       C = ConstantFoldInsertValueInstruction(C, Val, Idxs.slice(1));
543 
544     Result.push_back(C);
545   }
546 
547   if (StructType *ST = dyn_cast<StructType>(Agg->getType()))
548     return ConstantStruct::get(ST, Result);
549   return ConstantArray::get(cast<ArrayType>(Agg->getType()), Result);
550 }
551 
552 Constant *llvm::ConstantFoldUnaryInstruction(unsigned Opcode, Constant *C) {
553   assert(Instruction::isUnaryOp(Opcode) && "Non-unary instruction detected");
554 
555   // Handle scalar UndefValue and scalable vector UndefValue. Fixed-length
556   // vectors are always evaluated per element.
557   bool IsScalableVector = isa<ScalableVectorType>(C->getType());
558   bool HasScalarUndefOrScalableVectorUndef =
559       (!C->getType()->isVectorTy() || IsScalableVector) && isa<UndefValue>(C);
560 
561   if (HasScalarUndefOrScalableVectorUndef) {
562     switch (static_cast<Instruction::UnaryOps>(Opcode)) {
563     case Instruction::FNeg:
564       return C; // -undef -> undef
565     case Instruction::UnaryOpsEnd:
566       llvm_unreachable("Invalid UnaryOp");
567     }
568   }
569 
570   // Constant should not be UndefValue, unless these are vector constants.
571   assert(!HasScalarUndefOrScalableVectorUndef && "Unexpected UndefValue");
572   // We only have FP UnaryOps right now.
573   assert(!isa<ConstantInt>(C) && "Unexpected Integer UnaryOp");
574 
575   if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
576     const APFloat &CV = CFP->getValueAPF();
577     switch (Opcode) {
578     default:
579       break;
580     case Instruction::FNeg:
581       return ConstantFP::get(C->getContext(), neg(CV));
582     }
583   } else if (auto *VTy = dyn_cast<VectorType>(C->getType())) {
584     // Fast path for splatted constants.
585     if (Constant *Splat = C->getSplatValue())
586       if (Constant *Elt = ConstantFoldUnaryInstruction(Opcode, Splat))
587         return ConstantVector::getSplat(VTy->getElementCount(), Elt);
588 
589     if (auto *FVTy = dyn_cast<FixedVectorType>(VTy)) {
590       // Fold each element and create a vector constant from those constants.
591       Type *Ty = IntegerType::get(FVTy->getContext(), 32);
592       SmallVector<Constant *, 16> Result;
593       for (unsigned i = 0, e = FVTy->getNumElements(); i != e; ++i) {
594         Constant *ExtractIdx = ConstantInt::get(Ty, i);
595         Constant *Elt = ConstantExpr::getExtractElement(C, ExtractIdx);
596         Constant *Res = ConstantFoldUnaryInstruction(Opcode, Elt);
597         if (!Res)
598           return nullptr;
599         Result.push_back(Res);
600       }
601 
602       return ConstantVector::get(Result);
603     }
604   }
605 
606   // We don't know how to fold this.
607   return nullptr;
608 }
609 
610 Constant *llvm::ConstantFoldBinaryInstruction(unsigned Opcode, Constant *C1,
611                                               Constant *C2) {
612   assert(Instruction::isBinaryOp(Opcode) && "Non-binary instruction detected");
613 
614   // Simplify BinOps with their identity values first. They are no-ops and we
615   // can always return the other value, including undef or poison values.
616   if (Constant *Identity = ConstantExpr::getBinOpIdentity(
617           Opcode, C1->getType(), /*AllowRHSIdentity*/ false)) {
618     if (C1 == Identity)
619       return C2;
620     if (C2 == Identity)
621       return C1;
622   } else if (Constant *Identity = ConstantExpr::getBinOpIdentity(
623                  Opcode, C1->getType(), /*AllowRHSIdentity*/ true)) {
624     if (C2 == Identity)
625       return C1;
626   }
627 
628   // Binary operations propagate poison.
629   if (isa<PoisonValue>(C1) || isa<PoisonValue>(C2))
630     return PoisonValue::get(C1->getType());
631 
632   // Handle scalar UndefValue and scalable vector UndefValue. Fixed-length
633   // vectors are always evaluated per element.
634   bool IsScalableVector = isa<ScalableVectorType>(C1->getType());
635   bool HasScalarUndefOrScalableVectorUndef =
636       (!C1->getType()->isVectorTy() || IsScalableVector) &&
637       (isa<UndefValue>(C1) || isa<UndefValue>(C2));
638   if (HasScalarUndefOrScalableVectorUndef) {
639     switch (static_cast<Instruction::BinaryOps>(Opcode)) {
640     case Instruction::Xor:
641       if (isa<UndefValue>(C1) && isa<UndefValue>(C2))
642         // Handle undef ^ undef -> 0 special case. This is a common
643         // idiom (misuse).
644         return Constant::getNullValue(C1->getType());
645       [[fallthrough]];
646     case Instruction::Add:
647     case Instruction::Sub:
648       return UndefValue::get(C1->getType());
649     case Instruction::And:
650       if (isa<UndefValue>(C1) && isa<UndefValue>(C2)) // undef & undef -> undef
651         return C1;
652       return Constant::getNullValue(C1->getType());   // undef & X -> 0
653     case Instruction::Mul: {
654       // undef * undef -> undef
655       if (isa<UndefValue>(C1) && isa<UndefValue>(C2))
656         return C1;
657       const APInt *CV;
658       // X * undef -> undef   if X is odd
659       if (match(C1, m_APInt(CV)) || match(C2, m_APInt(CV)))
660         if ((*CV)[0])
661           return UndefValue::get(C1->getType());
662 
663       // X * undef -> 0       otherwise
664       return Constant::getNullValue(C1->getType());
665     }
666     case Instruction::SDiv:
667     case Instruction::UDiv:
668       // X / undef -> poison
669       // X / 0 -> poison
670       if (match(C2, m_CombineOr(m_Undef(), m_Zero())))
671         return PoisonValue::get(C2->getType());
672       // undef / X -> 0       otherwise
673       return Constant::getNullValue(C1->getType());
674     case Instruction::URem:
675     case Instruction::SRem:
676       // X % undef -> poison
677       // X % 0 -> poison
678       if (match(C2, m_CombineOr(m_Undef(), m_Zero())))
679         return PoisonValue::get(C2->getType());
680       // undef % X -> 0       otherwise
681       return Constant::getNullValue(C1->getType());
682     case Instruction::Or:                          // X | undef -> -1
683       if (isa<UndefValue>(C1) && isa<UndefValue>(C2)) // undef | undef -> undef
684         return C1;
685       return Constant::getAllOnesValue(C1->getType()); // undef | X -> ~0
686     case Instruction::LShr:
687       // X >>l undef -> poison
688       if (isa<UndefValue>(C2))
689         return PoisonValue::get(C2->getType());
690       // undef >>l X -> 0
691       return Constant::getNullValue(C1->getType());
692     case Instruction::AShr:
693       // X >>a undef -> poison
694       if (isa<UndefValue>(C2))
695         return PoisonValue::get(C2->getType());
696       // TODO: undef >>a X -> poison if the shift is exact
697       // undef >>a X -> 0
698       return Constant::getNullValue(C1->getType());
699     case Instruction::Shl:
700       // X << undef -> undef
701       if (isa<UndefValue>(C2))
702         return PoisonValue::get(C2->getType());
703       // undef << X -> 0
704       return Constant::getNullValue(C1->getType());
705     case Instruction::FSub:
706       // -0.0 - undef --> undef (consistent with "fneg undef")
707       if (match(C1, m_NegZeroFP()) && isa<UndefValue>(C2))
708         return C2;
709       [[fallthrough]];
710     case Instruction::FAdd:
711     case Instruction::FMul:
712     case Instruction::FDiv:
713     case Instruction::FRem:
714       // [any flop] undef, undef -> undef
715       if (isa<UndefValue>(C1) && isa<UndefValue>(C2))
716         return C1;
717       // [any flop] C, undef -> NaN
718       // [any flop] undef, C -> NaN
719       // We could potentially specialize NaN/Inf constants vs. 'normal'
720       // constants (possibly differently depending on opcode and operand). This
721       // would allow returning undef sometimes. But it is always safe to fold to
722       // NaN because we can choose the undef operand as NaN, and any FP opcode
723       // with a NaN operand will propagate NaN.
724       return ConstantFP::getNaN(C1->getType());
725     case Instruction::BinaryOpsEnd:
726       llvm_unreachable("Invalid BinaryOp");
727     }
728   }
729 
730   // Neither constant should be UndefValue, unless these are vector constants.
731   assert((!HasScalarUndefOrScalableVectorUndef) && "Unexpected UndefValue");
732 
733   // Handle simplifications when the RHS is a constant int.
734   if (ConstantInt *CI2 = dyn_cast<ConstantInt>(C2)) {
735     if (C2 == ConstantExpr::getBinOpAbsorber(Opcode, C2->getType(),
736                                              /*AllowLHSConstant*/ false))
737       return C2;
738 
739     switch (Opcode) {
740     case Instruction::UDiv:
741     case Instruction::SDiv:
742       if (CI2->isZero())
743         return PoisonValue::get(CI2->getType());              // X / 0 == poison
744       break;
745     case Instruction::URem:
746     case Instruction::SRem:
747       if (CI2->isOne())
748         return Constant::getNullValue(CI2->getType());        // X % 1 == 0
749       if (CI2->isZero())
750         return PoisonValue::get(CI2->getType());              // X % 0 == poison
751       break;
752     case Instruction::And:
753       assert(!CI2->isZero() && "And zero handled above");
754       if (ConstantExpr *CE1 = dyn_cast<ConstantExpr>(C1)) {
755         // If and'ing the address of a global with a constant, fold it.
756         if (CE1->getOpcode() == Instruction::PtrToInt &&
757             isa<GlobalValue>(CE1->getOperand(0))) {
758           GlobalValue *GV = cast<GlobalValue>(CE1->getOperand(0));
759 
760           Align GVAlign; // defaults to 1
761 
762           if (Module *TheModule = GV->getParent()) {
763             const DataLayout &DL = TheModule->getDataLayout();
764             GVAlign = GV->getPointerAlignment(DL);
765 
766             // If the function alignment is not specified then assume that it
767             // is 4.
768             // This is dangerous; on x86, the alignment of the pointer
769             // corresponds to the alignment of the function, but might be less
770             // than 4 if it isn't explicitly specified.
771             // However, a fix for this behaviour was reverted because it
772             // increased code size (see https://reviews.llvm.org/D55115)
773             // FIXME: This code should be deleted once existing targets have
774             // appropriate defaults
775             if (isa<Function>(GV) && !DL.getFunctionPtrAlign())
776               GVAlign = Align(4);
777           } else if (isa<GlobalVariable>(GV)) {
778             GVAlign = cast<GlobalVariable>(GV)->getAlign().valueOrOne();
779           }
780 
781           if (GVAlign > 1) {
782             unsigned DstWidth = CI2->getBitWidth();
783             unsigned SrcWidth = std::min(DstWidth, Log2(GVAlign));
784             APInt BitsNotSet(APInt::getLowBitsSet(DstWidth, SrcWidth));
785 
786             // If checking bits we know are clear, return zero.
787             if ((CI2->getValue() & BitsNotSet) == CI2->getValue())
788               return Constant::getNullValue(CI2->getType());
789           }
790         }
791       }
792       break;
793     }
794   } else if (isa<ConstantInt>(C1)) {
795     // If C1 is a ConstantInt and C2 is not, swap the operands.
796     if (Instruction::isCommutative(Opcode))
797       return ConstantExpr::isDesirableBinOp(Opcode)
798                  ? ConstantExpr::get(Opcode, C2, C1)
799                  : ConstantFoldBinaryInstruction(Opcode, C2, C1);
800   }
801 
802   if (ConstantInt *CI1 = dyn_cast<ConstantInt>(C1)) {
803     if (ConstantInt *CI2 = dyn_cast<ConstantInt>(C2)) {
804       const APInt &C1V = CI1->getValue();
805       const APInt &C2V = CI2->getValue();
806       switch (Opcode) {
807       default:
808         break;
809       case Instruction::Add:
810         return ConstantInt::get(CI1->getContext(), C1V + C2V);
811       case Instruction::Sub:
812         return ConstantInt::get(CI1->getContext(), C1V - C2V);
813       case Instruction::Mul:
814         return ConstantInt::get(CI1->getContext(), C1V * C2V);
815       case Instruction::UDiv:
816         assert(!CI2->isZero() && "Div by zero handled above");
817         return ConstantInt::get(CI1->getContext(), C1V.udiv(C2V));
818       case Instruction::SDiv:
819         assert(!CI2->isZero() && "Div by zero handled above");
820         if (C2V.isAllOnes() && C1V.isMinSignedValue())
821           return PoisonValue::get(CI1->getType());   // MIN_INT / -1 -> poison
822         return ConstantInt::get(CI1->getContext(), C1V.sdiv(C2V));
823       case Instruction::URem:
824         assert(!CI2->isZero() && "Div by zero handled above");
825         return ConstantInt::get(CI1->getContext(), C1V.urem(C2V));
826       case Instruction::SRem:
827         assert(!CI2->isZero() && "Div by zero handled above");
828         if (C2V.isAllOnes() && C1V.isMinSignedValue())
829           return PoisonValue::get(CI1->getType());   // MIN_INT % -1 -> poison
830         return ConstantInt::get(CI1->getContext(), C1V.srem(C2V));
831       case Instruction::And:
832         return ConstantInt::get(CI1->getContext(), C1V & C2V);
833       case Instruction::Or:
834         return ConstantInt::get(CI1->getContext(), C1V | C2V);
835       case Instruction::Xor:
836         return ConstantInt::get(CI1->getContext(), C1V ^ C2V);
837       case Instruction::Shl:
838         if (C2V.ult(C1V.getBitWidth()))
839           return ConstantInt::get(CI1->getContext(), C1V.shl(C2V));
840         return PoisonValue::get(C1->getType()); // too big shift is poison
841       case Instruction::LShr:
842         if (C2V.ult(C1V.getBitWidth()))
843           return ConstantInt::get(CI1->getContext(), C1V.lshr(C2V));
844         return PoisonValue::get(C1->getType()); // too big shift is poison
845       case Instruction::AShr:
846         if (C2V.ult(C1V.getBitWidth()))
847           return ConstantInt::get(CI1->getContext(), C1V.ashr(C2V));
848         return PoisonValue::get(C1->getType()); // too big shift is poison
849       }
850     }
851 
852     if (C1 == ConstantExpr::getBinOpAbsorber(Opcode, C1->getType(),
853                                              /*AllowLHSConstant*/ true))
854       return C1;
855   } else if (ConstantFP *CFP1 = dyn_cast<ConstantFP>(C1)) {
856     if (ConstantFP *CFP2 = dyn_cast<ConstantFP>(C2)) {
857       const APFloat &C1V = CFP1->getValueAPF();
858       const APFloat &C2V = CFP2->getValueAPF();
859       APFloat C3V = C1V;  // copy for modification
860       switch (Opcode) {
861       default:
862         break;
863       case Instruction::FAdd:
864         (void)C3V.add(C2V, APFloat::rmNearestTiesToEven);
865         return ConstantFP::get(C1->getContext(), C3V);
866       case Instruction::FSub:
867         (void)C3V.subtract(C2V, APFloat::rmNearestTiesToEven);
868         return ConstantFP::get(C1->getContext(), C3V);
869       case Instruction::FMul:
870         (void)C3V.multiply(C2V, APFloat::rmNearestTiesToEven);
871         return ConstantFP::get(C1->getContext(), C3V);
872       case Instruction::FDiv:
873         (void)C3V.divide(C2V, APFloat::rmNearestTiesToEven);
874         return ConstantFP::get(C1->getContext(), C3V);
875       case Instruction::FRem:
876         (void)C3V.mod(C2V);
877         return ConstantFP::get(C1->getContext(), C3V);
878       }
879     }
880   } else if (auto *VTy = dyn_cast<VectorType>(C1->getType())) {
881     // Fast path for splatted constants.
882     if (Constant *C2Splat = C2->getSplatValue()) {
883       if (Instruction::isIntDivRem(Opcode) && C2Splat->isNullValue())
884         return PoisonValue::get(VTy);
885       if (Constant *C1Splat = C1->getSplatValue()) {
886         Constant *Res =
887             ConstantExpr::isDesirableBinOp(Opcode)
888                 ? ConstantExpr::get(Opcode, C1Splat, C2Splat)
889                 : ConstantFoldBinaryInstruction(Opcode, C1Splat, C2Splat);
890         if (!Res)
891           return nullptr;
892         return ConstantVector::getSplat(VTy->getElementCount(), Res);
893       }
894     }
895 
896     if (auto *FVTy = dyn_cast<FixedVectorType>(VTy)) {
897       // Fold each element and create a vector constant from those constants.
898       SmallVector<Constant*, 16> Result;
899       Type *Ty = IntegerType::get(FVTy->getContext(), 32);
900       for (unsigned i = 0, e = FVTy->getNumElements(); i != e; ++i) {
901         Constant *ExtractIdx = ConstantInt::get(Ty, i);
902         Constant *LHS = ConstantExpr::getExtractElement(C1, ExtractIdx);
903         Constant *RHS = ConstantExpr::getExtractElement(C2, ExtractIdx);
904         Constant *Res = ConstantExpr::isDesirableBinOp(Opcode)
905                             ? ConstantExpr::get(Opcode, LHS, RHS)
906                             : ConstantFoldBinaryInstruction(Opcode, LHS, RHS);
907         if (!Res)
908           return nullptr;
909         Result.push_back(Res);
910       }
911 
912       return ConstantVector::get(Result);
913     }
914   }
915 
916   if (ConstantExpr *CE1 = dyn_cast<ConstantExpr>(C1)) {
917     // There are many possible foldings we could do here.  We should probably
918     // at least fold add of a pointer with an integer into the appropriate
919     // getelementptr.  This will improve alias analysis a bit.
920 
921     // Given ((a + b) + c), if (b + c) folds to something interesting, return
922     // (a + (b + c)).
923     if (Instruction::isAssociative(Opcode) && CE1->getOpcode() == Opcode) {
924       Constant *T = ConstantExpr::get(Opcode, CE1->getOperand(1), C2);
925       if (!isa<ConstantExpr>(T) || cast<ConstantExpr>(T)->getOpcode() != Opcode)
926         return ConstantExpr::get(Opcode, CE1->getOperand(0), T);
927     }
928   } else if (isa<ConstantExpr>(C2)) {
929     // If C2 is a constant expr and C1 isn't, flop them around and fold the
930     // other way if possible.
931     if (Instruction::isCommutative(Opcode))
932       return ConstantFoldBinaryInstruction(Opcode, C2, C1);
933   }
934 
935   // i1 can be simplified in many cases.
936   if (C1->getType()->isIntegerTy(1)) {
937     switch (Opcode) {
938     case Instruction::Add:
939     case Instruction::Sub:
940       return ConstantExpr::getXor(C1, C2);
941     case Instruction::Shl:
942     case Instruction::LShr:
943     case Instruction::AShr:
944       // We can assume that C2 == 0.  If it were one the result would be
945       // undefined because the shift value is as large as the bitwidth.
946       return C1;
947     case Instruction::SDiv:
948     case Instruction::UDiv:
949       // We can assume that C2 == 1.  If it were zero the result would be
950       // undefined through division by zero.
951       return C1;
952     case Instruction::URem:
953     case Instruction::SRem:
954       // We can assume that C2 == 1.  If it were zero the result would be
955       // undefined through division by zero.
956       return ConstantInt::getFalse(C1->getContext());
957     default:
958       break;
959     }
960   }
961 
962   // We don't know how to fold this.
963   return nullptr;
964 }
965 
966 static ICmpInst::Predicate areGlobalsPotentiallyEqual(const GlobalValue *GV1,
967                                                       const GlobalValue *GV2) {
968   auto isGlobalUnsafeForEquality = [](const GlobalValue *GV) {
969     if (GV->isInterposable() || GV->hasGlobalUnnamedAddr())
970       return true;
971     if (const auto *GVar = dyn_cast<GlobalVariable>(GV)) {
972       Type *Ty = GVar->getValueType();
973       // A global with opaque type might end up being zero sized.
974       if (!Ty->isSized())
975         return true;
976       // A global with an empty type might lie at the address of any other
977       // global.
978       if (Ty->isEmptyTy())
979         return true;
980     }
981     return false;
982   };
983   // Don't try to decide equality of aliases.
984   if (!isa<GlobalAlias>(GV1) && !isa<GlobalAlias>(GV2))
985     if (!isGlobalUnsafeForEquality(GV1) && !isGlobalUnsafeForEquality(GV2))
986       return ICmpInst::ICMP_NE;
987   return ICmpInst::BAD_ICMP_PREDICATE;
988 }
989 
990 /// This function determines if there is anything we can decide about the two
991 /// constants provided. This doesn't need to handle simple things like integer
992 /// comparisons, but should instead handle ConstantExprs and GlobalValues.
993 /// If we can determine that the two constants have a particular relation to
994 /// each other, we should return the corresponding ICmp predicate, otherwise
995 /// return ICmpInst::BAD_ICMP_PREDICATE.
996 static ICmpInst::Predicate evaluateICmpRelation(Constant *V1, Constant *V2) {
997   assert(V1->getType() == V2->getType() &&
998          "Cannot compare different types of values!");
999   if (V1 == V2) return ICmpInst::ICMP_EQ;
1000 
1001   // The following folds only apply to pointers.
1002   if (!V1->getType()->isPointerTy())
1003     return ICmpInst::BAD_ICMP_PREDICATE;
1004 
1005   // To simplify this code we canonicalize the relation so that the first
1006   // operand is always the most "complex" of the two.  We consider simple
1007   // constants (like ConstantPointerNull) to be the simplest, followed by
1008   // BlockAddress, GlobalValues, and ConstantExpr's (the most complex).
1009   auto GetComplexity = [](Constant *V) {
1010     if (isa<ConstantExpr>(V))
1011       return 3;
1012     if (isa<GlobalValue>(V))
1013       return 2;
1014     if (isa<BlockAddress>(V))
1015       return 1;
1016     return 0;
1017   };
1018   if (GetComplexity(V1) < GetComplexity(V2)) {
1019     ICmpInst::Predicate SwappedRelation = evaluateICmpRelation(V2, V1);
1020     if (SwappedRelation != ICmpInst::BAD_ICMP_PREDICATE)
1021       return ICmpInst::getSwappedPredicate(SwappedRelation);
1022     return ICmpInst::BAD_ICMP_PREDICATE;
1023   }
1024 
1025   if (const BlockAddress *BA = dyn_cast<BlockAddress>(V1)) {
1026     // Now we know that the RHS is a BlockAddress or simple constant.
1027     if (const BlockAddress *BA2 = dyn_cast<BlockAddress>(V2)) {
1028       // Block address in another function can't equal this one, but block
1029       // addresses in the current function might be the same if blocks are
1030       // empty.
1031       if (BA2->getFunction() != BA->getFunction())
1032         return ICmpInst::ICMP_NE;
1033     } else if (isa<ConstantPointerNull>(V2)) {
1034       return ICmpInst::ICMP_NE;
1035     }
1036   } else if (const GlobalValue *GV = dyn_cast<GlobalValue>(V1)) {
1037     // Now we know that the RHS is a GlobalValue, BlockAddress or simple
1038     // constant.
1039     if (const GlobalValue *GV2 = dyn_cast<GlobalValue>(V2)) {
1040       return areGlobalsPotentiallyEqual(GV, GV2);
1041     } else if (isa<BlockAddress>(V2)) {
1042       return ICmpInst::ICMP_NE; // Globals never equal labels.
1043     } else if (isa<ConstantPointerNull>(V2)) {
1044       // GlobalVals can never be null unless they have external weak linkage.
1045       // We don't try to evaluate aliases here.
1046       // NOTE: We should not be doing this constant folding if null pointer
1047       // is considered valid for the function. But currently there is no way to
1048       // query it from the Constant type.
1049       if (!GV->hasExternalWeakLinkage() && !isa<GlobalAlias>(GV) &&
1050           !NullPointerIsDefined(nullptr /* F */,
1051                                 GV->getType()->getAddressSpace()))
1052         return ICmpInst::ICMP_UGT;
1053     }
1054   } else if (auto *CE1 = dyn_cast<ConstantExpr>(V1)) {
1055     // Ok, the LHS is known to be a constantexpr.  The RHS can be any of a
1056     // constantexpr, a global, block address, or a simple constant.
1057     Constant *CE1Op0 = CE1->getOperand(0);
1058 
1059     switch (CE1->getOpcode()) {
1060     case Instruction::GetElementPtr: {
1061       GEPOperator *CE1GEP = cast<GEPOperator>(CE1);
1062       // Ok, since this is a getelementptr, we know that the constant has a
1063       // pointer type.  Check the various cases.
1064       if (isa<ConstantPointerNull>(V2)) {
1065         // If we are comparing a GEP to a null pointer, check to see if the base
1066         // of the GEP equals the null pointer.
1067         if (const GlobalValue *GV = dyn_cast<GlobalValue>(CE1Op0)) {
1068           // If its not weak linkage, the GVal must have a non-zero address
1069           // so the result is greater-than
1070           if (!GV->hasExternalWeakLinkage() && CE1GEP->isInBounds())
1071             return ICmpInst::ICMP_UGT;
1072         }
1073       } else if (const GlobalValue *GV2 = dyn_cast<GlobalValue>(V2)) {
1074         if (const GlobalValue *GV = dyn_cast<GlobalValue>(CE1Op0)) {
1075           if (GV != GV2) {
1076             if (CE1GEP->hasAllZeroIndices())
1077               return areGlobalsPotentiallyEqual(GV, GV2);
1078             return ICmpInst::BAD_ICMP_PREDICATE;
1079           }
1080         }
1081       } else if (const auto *CE2GEP = dyn_cast<GEPOperator>(V2)) {
1082         // By far the most common case to handle is when the base pointers are
1083         // obviously to the same global.
1084         const Constant *CE2Op0 = cast<Constant>(CE2GEP->getPointerOperand());
1085         if (isa<GlobalValue>(CE1Op0) && isa<GlobalValue>(CE2Op0)) {
1086           // Don't know relative ordering, but check for inequality.
1087           if (CE1Op0 != CE2Op0) {
1088             if (CE1GEP->hasAllZeroIndices() && CE2GEP->hasAllZeroIndices())
1089               return areGlobalsPotentiallyEqual(cast<GlobalValue>(CE1Op0),
1090                                                 cast<GlobalValue>(CE2Op0));
1091             return ICmpInst::BAD_ICMP_PREDICATE;
1092           }
1093         }
1094       }
1095       break;
1096     }
1097     default:
1098       break;
1099     }
1100   }
1101 
1102   return ICmpInst::BAD_ICMP_PREDICATE;
1103 }
1104 
1105 Constant *llvm::ConstantFoldCompareInstruction(CmpInst::Predicate Predicate,
1106                                                Constant *C1, Constant *C2) {
1107   Type *ResultTy;
1108   if (VectorType *VT = dyn_cast<VectorType>(C1->getType()))
1109     ResultTy = VectorType::get(Type::getInt1Ty(C1->getContext()),
1110                                VT->getElementCount());
1111   else
1112     ResultTy = Type::getInt1Ty(C1->getContext());
1113 
1114   // Fold FCMP_FALSE/FCMP_TRUE unconditionally.
1115   if (Predicate == FCmpInst::FCMP_FALSE)
1116     return Constant::getNullValue(ResultTy);
1117 
1118   if (Predicate == FCmpInst::FCMP_TRUE)
1119     return Constant::getAllOnesValue(ResultTy);
1120 
1121   // Handle some degenerate cases first
1122   if (isa<PoisonValue>(C1) || isa<PoisonValue>(C2))
1123     return PoisonValue::get(ResultTy);
1124 
1125   if (isa<UndefValue>(C1) || isa<UndefValue>(C2)) {
1126     bool isIntegerPredicate = ICmpInst::isIntPredicate(Predicate);
1127     // For EQ and NE, we can always pick a value for the undef to make the
1128     // predicate pass or fail, so we can return undef.
1129     // Also, if both operands are undef, we can return undef for int comparison.
1130     if (ICmpInst::isEquality(Predicate) || (isIntegerPredicate && C1 == C2))
1131       return UndefValue::get(ResultTy);
1132 
1133     // Otherwise, for integer compare, pick the same value as the non-undef
1134     // operand, and fold it to true or false.
1135     if (isIntegerPredicate)
1136       return ConstantInt::get(ResultTy, CmpInst::isTrueWhenEqual(Predicate));
1137 
1138     // Choosing NaN for the undef will always make unordered comparison succeed
1139     // and ordered comparison fails.
1140     return ConstantInt::get(ResultTy, CmpInst::isUnordered(Predicate));
1141   }
1142 
1143   if (C2->isNullValue()) {
1144     // The caller is expected to commute the operands if the constant expression
1145     // is C2.
1146     // C1 >= 0 --> true
1147     if (Predicate == ICmpInst::ICMP_UGE)
1148       return Constant::getAllOnesValue(ResultTy);
1149     // C1 < 0 --> false
1150     if (Predicate == ICmpInst::ICMP_ULT)
1151       return Constant::getNullValue(ResultTy);
1152   }
1153 
1154   // If the comparison is a comparison between two i1's, simplify it.
1155   if (C1->getType()->isIntegerTy(1)) {
1156     switch (Predicate) {
1157     case ICmpInst::ICMP_EQ:
1158       if (isa<ConstantInt>(C2))
1159         return ConstantExpr::getXor(C1, ConstantExpr::getNot(C2));
1160       return ConstantExpr::getXor(ConstantExpr::getNot(C1), C2);
1161     case ICmpInst::ICMP_NE:
1162       return ConstantExpr::getXor(C1, C2);
1163     default:
1164       break;
1165     }
1166   }
1167 
1168   if (isa<ConstantInt>(C1) && isa<ConstantInt>(C2)) {
1169     const APInt &V1 = cast<ConstantInt>(C1)->getValue();
1170     const APInt &V2 = cast<ConstantInt>(C2)->getValue();
1171     return ConstantInt::get(ResultTy, ICmpInst::compare(V1, V2, Predicate));
1172   } else if (isa<ConstantFP>(C1) && isa<ConstantFP>(C2)) {
1173     const APFloat &C1V = cast<ConstantFP>(C1)->getValueAPF();
1174     const APFloat &C2V = cast<ConstantFP>(C2)->getValueAPF();
1175     return ConstantInt::get(ResultTy, FCmpInst::compare(C1V, C2V, Predicate));
1176   } else if (auto *C1VTy = dyn_cast<VectorType>(C1->getType())) {
1177 
1178     // Fast path for splatted constants.
1179     if (Constant *C1Splat = C1->getSplatValue())
1180       if (Constant *C2Splat = C2->getSplatValue())
1181         if (Constant *Elt =
1182                 ConstantFoldCompareInstruction(Predicate, C1Splat, C2Splat))
1183           return ConstantVector::getSplat(C1VTy->getElementCount(), Elt);
1184 
1185     // Do not iterate on scalable vector. The number of elements is unknown at
1186     // compile-time.
1187     if (isa<ScalableVectorType>(C1VTy))
1188       return nullptr;
1189 
1190     // If we can constant fold the comparison of each element, constant fold
1191     // the whole vector comparison.
1192     SmallVector<Constant*, 4> ResElts;
1193     Type *Ty = IntegerType::get(C1->getContext(), 32);
1194     // Compare the elements, producing an i1 result or constant expr.
1195     for (unsigned I = 0, E = C1VTy->getElementCount().getKnownMinValue();
1196          I != E; ++I) {
1197       Constant *C1E =
1198           ConstantExpr::getExtractElement(C1, ConstantInt::get(Ty, I));
1199       Constant *C2E =
1200           ConstantExpr::getExtractElement(C2, ConstantInt::get(Ty, I));
1201       Constant *Elt = ConstantFoldCompareInstruction(Predicate, C1E, C2E);
1202       if (!Elt)
1203         return nullptr;
1204 
1205       ResElts.push_back(Elt);
1206     }
1207 
1208     return ConstantVector::get(ResElts);
1209   }
1210 
1211   if (C1->getType()->isFPOrFPVectorTy()) {
1212     if (C1 == C2) {
1213       // We know that C1 == C2 || isUnordered(C1, C2).
1214       if (Predicate == FCmpInst::FCMP_ONE)
1215         return ConstantInt::getFalse(ResultTy);
1216       else if (Predicate == FCmpInst::FCMP_UEQ)
1217         return ConstantInt::getTrue(ResultTy);
1218     }
1219   } else {
1220     // Evaluate the relation between the two constants, per the predicate.
1221     int Result = -1;  // -1 = unknown, 0 = known false, 1 = known true.
1222     switch (evaluateICmpRelation(C1, C2)) {
1223     default: llvm_unreachable("Unknown relational!");
1224     case ICmpInst::BAD_ICMP_PREDICATE:
1225       break;  // Couldn't determine anything about these constants.
1226     case ICmpInst::ICMP_EQ:   // We know the constants are equal!
1227       // If we know the constants are equal, we can decide the result of this
1228       // computation precisely.
1229       Result = ICmpInst::isTrueWhenEqual(Predicate);
1230       break;
1231     case ICmpInst::ICMP_ULT:
1232       switch (Predicate) {
1233       case ICmpInst::ICMP_ULT: case ICmpInst::ICMP_NE: case ICmpInst::ICMP_ULE:
1234         Result = 1; break;
1235       case ICmpInst::ICMP_UGT: case ICmpInst::ICMP_EQ: case ICmpInst::ICMP_UGE:
1236         Result = 0; break;
1237       default:
1238         break;
1239       }
1240       break;
1241     case ICmpInst::ICMP_SLT:
1242       switch (Predicate) {
1243       case ICmpInst::ICMP_SLT: case ICmpInst::ICMP_NE: case ICmpInst::ICMP_SLE:
1244         Result = 1; break;
1245       case ICmpInst::ICMP_SGT: case ICmpInst::ICMP_EQ: case ICmpInst::ICMP_SGE:
1246         Result = 0; break;
1247       default:
1248         break;
1249       }
1250       break;
1251     case ICmpInst::ICMP_UGT:
1252       switch (Predicate) {
1253       case ICmpInst::ICMP_UGT: case ICmpInst::ICMP_NE: case ICmpInst::ICMP_UGE:
1254         Result = 1; break;
1255       case ICmpInst::ICMP_ULT: case ICmpInst::ICMP_EQ: case ICmpInst::ICMP_ULE:
1256         Result = 0; break;
1257       default:
1258         break;
1259       }
1260       break;
1261     case ICmpInst::ICMP_SGT:
1262       switch (Predicate) {
1263       case ICmpInst::ICMP_SGT: case ICmpInst::ICMP_NE: case ICmpInst::ICMP_SGE:
1264         Result = 1; break;
1265       case ICmpInst::ICMP_SLT: case ICmpInst::ICMP_EQ: case ICmpInst::ICMP_SLE:
1266         Result = 0; break;
1267       default:
1268         break;
1269       }
1270       break;
1271     case ICmpInst::ICMP_ULE:
1272       if (Predicate == ICmpInst::ICMP_UGT)
1273         Result = 0;
1274       if (Predicate == ICmpInst::ICMP_ULT || Predicate == ICmpInst::ICMP_ULE)
1275         Result = 1;
1276       break;
1277     case ICmpInst::ICMP_SLE:
1278       if (Predicate == ICmpInst::ICMP_SGT)
1279         Result = 0;
1280       if (Predicate == ICmpInst::ICMP_SLT || Predicate == ICmpInst::ICMP_SLE)
1281         Result = 1;
1282       break;
1283     case ICmpInst::ICMP_UGE:
1284       if (Predicate == ICmpInst::ICMP_ULT)
1285         Result = 0;
1286       if (Predicate == ICmpInst::ICMP_UGT || Predicate == ICmpInst::ICMP_UGE)
1287         Result = 1;
1288       break;
1289     case ICmpInst::ICMP_SGE:
1290       if (Predicate == ICmpInst::ICMP_SLT)
1291         Result = 0;
1292       if (Predicate == ICmpInst::ICMP_SGT || Predicate == ICmpInst::ICMP_SGE)
1293         Result = 1;
1294       break;
1295     case ICmpInst::ICMP_NE:
1296       if (Predicate == ICmpInst::ICMP_EQ)
1297         Result = 0;
1298       if (Predicate == ICmpInst::ICMP_NE)
1299         Result = 1;
1300       break;
1301     }
1302 
1303     // If we evaluated the result, return it now.
1304     if (Result != -1)
1305       return ConstantInt::get(ResultTy, Result);
1306 
1307     if ((!isa<ConstantExpr>(C1) && isa<ConstantExpr>(C2)) ||
1308         (C1->isNullValue() && !C2->isNullValue())) {
1309       // If C2 is a constant expr and C1 isn't, flip them around and fold the
1310       // other way if possible.
1311       // Also, if C1 is null and C2 isn't, flip them around.
1312       Predicate = ICmpInst::getSwappedPredicate(Predicate);
1313       return ConstantFoldCompareInstruction(Predicate, C2, C1);
1314     }
1315   }
1316   return nullptr;
1317 }
1318 
1319 Constant *llvm::ConstantFoldGetElementPtr(Type *PointeeTy, Constant *C,
1320                                           std::optional<ConstantRange> InRange,
1321                                           ArrayRef<Value *> Idxs) {
1322   if (Idxs.empty()) return C;
1323 
1324   Type *GEPTy = GetElementPtrInst::getGEPReturnType(
1325       C, ArrayRef((Value *const *)Idxs.data(), Idxs.size()));
1326 
1327   if (isa<PoisonValue>(C))
1328     return PoisonValue::get(GEPTy);
1329 
1330   if (isa<UndefValue>(C))
1331     return UndefValue::get(GEPTy);
1332 
1333   auto IsNoOp = [&]() {
1334     // Avoid losing inrange information.
1335     if (InRange)
1336       return false;
1337 
1338     return all_of(Idxs, [](Value *Idx) {
1339       Constant *IdxC = cast<Constant>(Idx);
1340       return IdxC->isNullValue() || isa<UndefValue>(IdxC);
1341     });
1342   };
1343   if (IsNoOp())
1344     return GEPTy->isVectorTy() && !C->getType()->isVectorTy()
1345                ? ConstantVector::getSplat(
1346                      cast<VectorType>(GEPTy)->getElementCount(), C)
1347                : C;
1348 
1349   return nullptr;
1350 }
1351