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