LLVM 17.0.0git
ConstantFold.cpp
Go to the documentation of this file.
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
20#include "llvm/ADT/APSInt.h"
22#include "llvm/IR/Constants.h"
24#include "llvm/IR/Function.h"
26#include "llvm/IR/GlobalAlias.h"
29#include "llvm/IR/Module.h"
30#include "llvm/IR/Operator.h"
33using namespace llvm;
34using 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.
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
68 Type *Ty = IntegerType::get(CV->getContext(), 32);
69 for (unsigned i = 0; i != NumElts; ++i) {
70 Constant *C =
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
83static unsigned
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());
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
109static 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()) {
122 Value *Zero =
123 Constant::getNullValue(Type::getInt32Ty(DPTy->getContext()));
124 IdxList.push_back(Zero);
126 while (ElTy && ElTy != DPTy->getNonOpaquePointerElementType()) {
128 IdxList.push_back(Zero);
129 }
130
131 if (ElTy == DPTy->getNonOpaquePointerElementType())
132 // This GEP is inbounds because all indices are zero.
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))
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.
213static 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;
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))
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))
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
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()) {
413 cast<VectorType>(DestTy)->getElementCount(),
414 ConstantExpr::getCast(opc, Splat, DstEltTy));
415 }
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 =
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(),
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
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();
531 Type *Ty = IntegerType::get(CondV->getContext(), 32);
532 for (unsigned i = 0, e = V1VTy->getNumElements(); i != e; ++i) {
533 Constant *V;
535 ConstantInt::get(Ty, i));
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 return nullptr;
597}
598
600 Constant *Idx) {
601 auto *ValVTy = cast<VectorType>(Val->getType());
602
603 // extractelt poison, C -> poison
604 // extractelt C, undef -> poison
605 if (isa<PoisonValue>(Val) || isa<UndefValue>(Idx))
606 return PoisonValue::get(ValVTy->getElementType());
607
608 // extractelt undef, C -> undef
609 if (isa<UndefValue>(Val))
610 return UndefValue::get(ValVTy->getElementType());
611
612 auto *CIdx = dyn_cast<ConstantInt>(Idx);
613 if (!CIdx)
614 return nullptr;
615
616 if (auto *ValFVTy = dyn_cast<FixedVectorType>(Val->getType())) {
617 // ee({w,x,y,z}, wrong_value) -> poison
618 if (CIdx->uge(ValFVTy->getNumElements()))
619 return PoisonValue::get(ValFVTy->getElementType());
620 }
621
622 // ee (gep (ptr, idx0, ...), idx) -> gep (ee (ptr, idx), ee (idx0, idx), ...)
623 if (auto *CE = dyn_cast<ConstantExpr>(Val)) {
624 if (auto *GEP = dyn_cast<GEPOperator>(CE)) {
626 Ops.reserve(CE->getNumOperands());
627 for (unsigned i = 0, e = CE->getNumOperands(); i != e; ++i) {
628 Constant *Op = CE->getOperand(i);
629 if (Op->getType()->isVectorTy()) {
631 if (!ScalarOp)
632 return nullptr;
633 Ops.push_back(ScalarOp);
634 } else
635 Ops.push_back(Op);
636 }
637 return CE->getWithOperands(Ops, ValVTy->getElementType(), false,
638 GEP->getSourceElementType());
639 } else if (CE->getOpcode() == Instruction::InsertElement) {
640 if (const auto *IEIdx = dyn_cast<ConstantInt>(CE->getOperand(2))) {
641 if (APSInt::isSameValue(APSInt(IEIdx->getValue()),
642 APSInt(CIdx->getValue()))) {
643 return CE->getOperand(1);
644 } else {
645 return ConstantExpr::getExtractElement(CE->getOperand(0), CIdx);
646 }
647 }
648 }
649 }
650
651 if (Constant *C = Val->getAggregateElement(CIdx))
652 return C;
653
654 // Lane < Splat minimum vector width => extractelt Splat(x), Lane -> x
655 if (CIdx->getValue().ult(ValVTy->getElementCount().getKnownMinValue())) {
656 if (Constant *SplatVal = Val->getSplatValue())
657 return SplatVal;
658 }
659
660 return nullptr;
661}
662
664 Constant *Elt,
665 Constant *Idx) {
666 if (isa<UndefValue>(Idx))
667 return PoisonValue::get(Val->getType());
668
669 // Inserting null into all zeros is still all zeros.
670 // TODO: This is true for undef and poison splats too.
671 if (isa<ConstantAggregateZero>(Val) && Elt->isNullValue())
672 return Val;
673
674 ConstantInt *CIdx = dyn_cast<ConstantInt>(Idx);
675 if (!CIdx) return nullptr;
676
677 // Do not iterate on scalable vector. The num of elements is unknown at
678 // compile-time.
679 if (isa<ScalableVectorType>(Val->getType()))
680 return nullptr;
681
682 auto *ValTy = cast<FixedVectorType>(Val->getType());
683
684 unsigned NumElts = ValTy->getNumElements();
685 if (CIdx->uge(NumElts))
686 return PoisonValue::get(Val->getType());
687
689 Result.reserve(NumElts);
690 auto *Ty = Type::getInt32Ty(Val->getContext());
691 uint64_t IdxVal = CIdx->getZExtValue();
692 for (unsigned i = 0; i != NumElts; ++i) {
693 if (i == IdxVal) {
694 Result.push_back(Elt);
695 continue;
696 }
697
699 Result.push_back(C);
700 }
701
702 return ConstantVector::get(Result);
703}
704
706 ArrayRef<int> Mask) {
707 auto *V1VTy = cast<VectorType>(V1->getType());
708 unsigned MaskNumElts = Mask.size();
709 auto MaskEltCount =
710 ElementCount::get(MaskNumElts, isa<ScalableVectorType>(V1VTy));
711 Type *EltTy = V1VTy->getElementType();
712
713 // Undefined shuffle mask -> undefined value.
714 if (all_of(Mask, [](int Elt) { return Elt == PoisonMaskElem; })) {
715 return UndefValue::get(VectorType::get(EltTy, MaskEltCount));
716 }
717
718 // If the mask is all zeros this is a splat, no need to go through all
719 // elements.
720 if (all_of(Mask, [](int Elt) { return Elt == 0; })) {
721 Type *Ty = IntegerType::get(V1->getContext(), 32);
722 Constant *Elt =
724
725 if (Elt->isNullValue()) {
726 auto *VTy = VectorType::get(EltTy, MaskEltCount);
727 return ConstantAggregateZero::get(VTy);
728 } else if (!MaskEltCount.isScalable())
729 return ConstantVector::getSplat(MaskEltCount, Elt);
730 }
731 // Do not iterate on scalable vector. The num of elements is unknown at
732 // compile-time.
733 if (isa<ScalableVectorType>(V1VTy))
734 return nullptr;
735
736 unsigned SrcNumElts = V1VTy->getElementCount().getKnownMinValue();
737
738 // Loop over the shuffle mask, evaluating each element.
740 for (unsigned i = 0; i != MaskNumElts; ++i) {
741 int Elt = Mask[i];
742 if (Elt == -1) {
743 Result.push_back(UndefValue::get(EltTy));
744 continue;
745 }
746 Constant *InElt;
747 if (unsigned(Elt) >= SrcNumElts*2)
748 InElt = UndefValue::get(EltTy);
749 else if (unsigned(Elt) >= SrcNumElts) {
750 Type *Ty = IntegerType::get(V2->getContext(), 32);
751 InElt =
753 ConstantInt::get(Ty, Elt - SrcNumElts));
754 } else {
755 Type *Ty = IntegerType::get(V1->getContext(), 32);
757 }
758 Result.push_back(InElt);
759 }
760
761 return ConstantVector::get(Result);
762}
763
765 ArrayRef<unsigned> Idxs) {
766 // Base case: no indices, so return the entire value.
767 if (Idxs.empty())
768 return Agg;
769
770 if (Constant *C = Agg->getAggregateElement(Idxs[0]))
772
773 return nullptr;
774}
775
777 Constant *Val,
778 ArrayRef<unsigned> Idxs) {
779 // Base case: no indices, so replace the entire value.
780 if (Idxs.empty())
781 return Val;
782
783 unsigned NumElts;
784 if (StructType *ST = dyn_cast<StructType>(Agg->getType()))
785 NumElts = ST->getNumElements();
786 else
787 NumElts = cast<ArrayType>(Agg->getType())->getNumElements();
788
790 for (unsigned i = 0; i != NumElts; ++i) {
791 Constant *C = Agg->getAggregateElement(i);
792 if (!C) return nullptr;
793
794 if (Idxs[0] == i)
796
797 Result.push_back(C);
798 }
799
800 if (StructType *ST = dyn_cast<StructType>(Agg->getType()))
801 return ConstantStruct::get(ST, Result);
802 return ConstantArray::get(cast<ArrayType>(Agg->getType()), Result);
803}
804
806 assert(Instruction::isUnaryOp(Opcode) && "Non-unary instruction detected");
807
808 // Handle scalar UndefValue and scalable vector UndefValue. Fixed-length
809 // vectors are always evaluated per element.
810 bool IsScalableVector = isa<ScalableVectorType>(C->getType());
811 bool HasScalarUndefOrScalableVectorUndef =
812 (!C->getType()->isVectorTy() || IsScalableVector) && isa<UndefValue>(C);
813
814 if (HasScalarUndefOrScalableVectorUndef) {
815 switch (static_cast<Instruction::UnaryOps>(Opcode)) {
816 case Instruction::FNeg:
817 return C; // -undef -> undef
818 case Instruction::UnaryOpsEnd:
819 llvm_unreachable("Invalid UnaryOp");
820 }
821 }
822
823 // Constant should not be UndefValue, unless these are vector constants.
824 assert(!HasScalarUndefOrScalableVectorUndef && "Unexpected UndefValue");
825 // We only have FP UnaryOps right now.
826 assert(!isa<ConstantInt>(C) && "Unexpected Integer UnaryOp");
827
828 if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
829 const APFloat &CV = CFP->getValueAPF();
830 switch (Opcode) {
831 default:
832 break;
833 case Instruction::FNeg:
834 return ConstantFP::get(C->getContext(), neg(CV));
835 }
836 } else if (auto *VTy = dyn_cast<FixedVectorType>(C->getType())) {
837
838 Type *Ty = IntegerType::get(VTy->getContext(), 32);
839 // Fast path for splatted constants.
840 if (Constant *Splat = C->getSplatValue())
841 if (Constant *Elt = ConstantFoldUnaryInstruction(Opcode, Splat))
842 return ConstantVector::getSplat(VTy->getElementCount(), Elt);
843
844 // Fold each element and create a vector constant from those constants.
846 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
847 Constant *ExtractIdx = ConstantInt::get(Ty, i);
848 Constant *Elt = ConstantExpr::getExtractElement(C, ExtractIdx);
849 Constant *Res = ConstantFoldUnaryInstruction(Opcode, Elt);
850 if (!Res)
851 return nullptr;
852 Result.push_back(Res);
853 }
854
855 return ConstantVector::get(Result);
856 }
857
858 // We don't know how to fold this.
859 return nullptr;
860}
861
863 Constant *C2) {
864 assert(Instruction::isBinaryOp(Opcode) && "Non-binary instruction detected");
865
866 // Simplify BinOps with their identity values first. They are no-ops and we
867 // can always return the other value, including undef or poison values.
868 // FIXME: remove unnecessary duplicated identity patterns below.
869 // FIXME: Use AllowRHSConstant with getBinOpIdentity to handle additional ops,
870 // like X << 0 = X.
871 Constant *Identity = ConstantExpr::getBinOpIdentity(Opcode, C1->getType());
872 if (Identity) {
873 if (C1 == Identity)
874 return C2;
875 if (C2 == Identity)
876 return C1;
877 }
878
879 // Binary operations propagate poison.
880 if (isa<PoisonValue>(C1) || isa<PoisonValue>(C2))
881 return PoisonValue::get(C1->getType());
882
883 // Handle scalar UndefValue and scalable vector UndefValue. Fixed-length
884 // vectors are always evaluated per element.
885 bool IsScalableVector = isa<ScalableVectorType>(C1->getType());
886 bool HasScalarUndefOrScalableVectorUndef =
887 (!C1->getType()->isVectorTy() || IsScalableVector) &&
888 (isa<UndefValue>(C1) || isa<UndefValue>(C2));
889 if (HasScalarUndefOrScalableVectorUndef) {
890 switch (static_cast<Instruction::BinaryOps>(Opcode)) {
891 case Instruction::Xor:
892 if (isa<UndefValue>(C1) && isa<UndefValue>(C2))
893 // Handle undef ^ undef -> 0 special case. This is a common
894 // idiom (misuse).
895 return Constant::getNullValue(C1->getType());
896 [[fallthrough]];
897 case Instruction::Add:
898 case Instruction::Sub:
899 return UndefValue::get(C1->getType());
900 case Instruction::And:
901 if (isa<UndefValue>(C1) && isa<UndefValue>(C2)) // undef & undef -> undef
902 return C1;
903 return Constant::getNullValue(C1->getType()); // undef & X -> 0
904 case Instruction::Mul: {
905 // undef * undef -> undef
906 if (isa<UndefValue>(C1) && isa<UndefValue>(C2))
907 return C1;
908 const APInt *CV;
909 // X * undef -> undef if X is odd
910 if (match(C1, m_APInt(CV)) || match(C2, m_APInt(CV)))
911 if ((*CV)[0])
912 return UndefValue::get(C1->getType());
913
914 // X * undef -> 0 otherwise
915 return Constant::getNullValue(C1->getType());
916 }
917 case Instruction::SDiv:
918 case Instruction::UDiv:
919 // X / undef -> poison
920 // X / 0 -> poison
921 if (match(C2, m_CombineOr(m_Undef(), m_Zero())))
922 return PoisonValue::get(C2->getType());
923 // undef / 1 -> undef
924 if (match(C2, m_One()))
925 return C1;
926 // undef / X -> 0 otherwise
927 return Constant::getNullValue(C1->getType());
928 case Instruction::URem:
929 case Instruction::SRem:
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 % X -> 0 otherwise
935 return Constant::getNullValue(C1->getType());
936 case Instruction::Or: // X | undef -> -1
937 if (isa<UndefValue>(C1) && isa<UndefValue>(C2)) // undef | undef -> undef
938 return C1;
939 return Constant::getAllOnesValue(C1->getType()); // undef | X -> ~0
940 case Instruction::LShr:
941 // X >>l undef -> poison
942 if (isa<UndefValue>(C2))
943 return PoisonValue::get(C2->getType());
944 // undef >>l 0 -> undef
945 if (match(C2, m_Zero()))
946 return C1;
947 // undef >>l X -> 0
948 return Constant::getNullValue(C1->getType());
949 case Instruction::AShr:
950 // X >>a undef -> poison
951 if (isa<UndefValue>(C2))
952 return PoisonValue::get(C2->getType());
953 // undef >>a 0 -> undef
954 if (match(C2, m_Zero()))
955 return C1;
956 // TODO: undef >>a X -> poison if the shift is exact
957 // undef >>a X -> 0
958 return Constant::getNullValue(C1->getType());
959 case Instruction::Shl:
960 // X << undef -> undef
961 if (isa<UndefValue>(C2))
962 return PoisonValue::get(C2->getType());
963 // undef << 0 -> undef
964 if (match(C2, m_Zero()))
965 return C1;
966 // undef << X -> 0
967 return Constant::getNullValue(C1->getType());
968 case Instruction::FSub:
969 // -0.0 - undef --> undef (consistent with "fneg undef")
970 if (match(C1, m_NegZeroFP()) && isa<UndefValue>(C2))
971 return C2;
972 [[fallthrough]];
973 case Instruction::FAdd:
974 case Instruction::FMul:
975 case Instruction::FDiv:
976 case Instruction::FRem:
977 // [any flop] undef, undef -> undef
978 if (isa<UndefValue>(C1) && isa<UndefValue>(C2))
979 return C1;
980 // [any flop] C, undef -> NaN
981 // [any flop] undef, C -> NaN
982 // We could potentially specialize NaN/Inf constants vs. 'normal'
983 // constants (possibly differently depending on opcode and operand). This
984 // would allow returning undef sometimes. But it is always safe to fold to
985 // NaN because we can choose the undef operand as NaN, and any FP opcode
986 // with a NaN operand will propagate NaN.
987 return ConstantFP::getNaN(C1->getType());
988 case Instruction::BinaryOpsEnd:
989 llvm_unreachable("Invalid BinaryOp");
990 }
991 }
992
993 // Neither constant should be UndefValue, unless these are vector constants.
994 assert((!HasScalarUndefOrScalableVectorUndef) && "Unexpected UndefValue");
995
996 // Handle simplifications when the RHS is a constant int.
997 if (ConstantInt *CI2 = dyn_cast<ConstantInt>(C2)) {
998 switch (Opcode) {
999 case Instruction::Add:
1000 if (CI2->isZero()) return C1; // X + 0 == X
1001 break;
1002 case Instruction::Sub:
1003 if (CI2->isZero()) return C1; // X - 0 == X
1004 break;
1005 case Instruction::Mul:
1006 if (CI2->isZero()) return C2; // X * 0 == 0
1007 if (CI2->isOne())
1008 return C1; // X * 1 == X
1009 break;
1010 case Instruction::UDiv:
1011 case Instruction::SDiv:
1012 if (CI2->isOne())
1013 return C1; // X / 1 == X
1014 if (CI2->isZero())
1015 return PoisonValue::get(CI2->getType()); // X / 0 == poison
1016 break;
1017 case Instruction::URem:
1018 case Instruction::SRem:
1019 if (CI2->isOne())
1020 return Constant::getNullValue(CI2->getType()); // X % 1 == 0
1021 if (CI2->isZero())
1022 return PoisonValue::get(CI2->getType()); // X % 0 == poison
1023 break;
1024 case Instruction::And:
1025 if (CI2->isZero()) return C2; // X & 0 == 0
1026 if (CI2->isMinusOne())
1027 return C1; // X & -1 == X
1028
1029 if (ConstantExpr *CE1 = dyn_cast<ConstantExpr>(C1)) {
1030 // (zext i32 to i64) & 4294967295 -> (zext i32 to i64)
1031 if (CE1->getOpcode() == Instruction::ZExt) {
1032 unsigned DstWidth = CI2->getType()->getBitWidth();
1033 unsigned SrcWidth =
1034 CE1->getOperand(0)->getType()->getPrimitiveSizeInBits();
1035 APInt PossiblySetBits(APInt::getLowBitsSet(DstWidth, SrcWidth));
1036 if ((PossiblySetBits & CI2->getValue()) == PossiblySetBits)
1037 return C1;
1038 }
1039
1040 // If and'ing the address of a global with a constant, fold it.
1041 if (CE1->getOpcode() == Instruction::PtrToInt &&
1042 isa<GlobalValue>(CE1->getOperand(0))) {
1043 GlobalValue *GV = cast<GlobalValue>(CE1->getOperand(0));
1044
1045 Align GVAlign; // defaults to 1
1046
1047 if (Module *TheModule = GV->getParent()) {
1048 const DataLayout &DL = TheModule->getDataLayout();
1049 GVAlign = GV->getPointerAlignment(DL);
1050
1051 // If the function alignment is not specified then assume that it
1052 // is 4.
1053 // This is dangerous; on x86, the alignment of the pointer
1054 // corresponds to the alignment of the function, but might be less
1055 // than 4 if it isn't explicitly specified.
1056 // However, a fix for this behaviour was reverted because it
1057 // increased code size (see https://reviews.llvm.org/D55115)
1058 // FIXME: This code should be deleted once existing targets have
1059 // appropriate defaults
1060 if (isa<Function>(GV) && !DL.getFunctionPtrAlign())
1061 GVAlign = Align(4);
1062 } else if (isa<GlobalVariable>(GV)) {
1063 GVAlign = cast<GlobalVariable>(GV)->getAlign().valueOrOne();
1064 }
1065
1066 if (GVAlign > 1) {
1067 unsigned DstWidth = CI2->getType()->getBitWidth();
1068 unsigned SrcWidth = std::min(DstWidth, Log2(GVAlign));
1069 APInt BitsNotSet(APInt::getLowBitsSet(DstWidth, SrcWidth));
1070
1071 // If checking bits we know are clear, return zero.
1072 if ((CI2->getValue() & BitsNotSet) == CI2->getValue())
1073 return Constant::getNullValue(CI2->getType());
1074 }
1075 }
1076 }
1077 break;
1078 case Instruction::Or:
1079 if (CI2->isZero()) return C1; // X | 0 == X
1080 if (CI2->isMinusOne())
1081 return C2; // X | -1 == -1
1082 break;
1083 case Instruction::Xor:
1084 if (CI2->isZero()) return C1; // X ^ 0 == X
1085
1086 if (ConstantExpr *CE1 = dyn_cast<ConstantExpr>(C1)) {
1087 switch (CE1->getOpcode()) {
1088 default: break;
1089 case Instruction::ICmp:
1090 case Instruction::FCmp:
1091 // cmp pred ^ true -> cmp !pred
1092 assert(CI2->isOne());
1093 CmpInst::Predicate pred = (CmpInst::Predicate)CE1->getPredicate();
1095 return ConstantExpr::getCompare(pred, CE1->getOperand(0),
1096 CE1->getOperand(1));
1097 }
1098 }
1099 break;
1100 case Instruction::AShr:
1101 // ashr (zext C to Ty), C2 -> lshr (zext C, CSA), C2
1102 if (ConstantExpr *CE1 = dyn_cast<ConstantExpr>(C1))
1103 if (CE1->getOpcode() == Instruction::ZExt) // Top bits known zero.
1104 return ConstantExpr::getLShr(C1, C2);
1105 break;
1106 }
1107 } else if (isa<ConstantInt>(C1)) {
1108 // If C1 is a ConstantInt and C2 is not, swap the operands.
1109 if (Instruction::isCommutative(Opcode))
1110 return ConstantExpr::get(Opcode, C2, C1);
1111 }
1112
1113 if (ConstantInt *CI1 = dyn_cast<ConstantInt>(C1)) {
1114 if (ConstantInt *CI2 = dyn_cast<ConstantInt>(C2)) {
1115 const APInt &C1V = CI1->getValue();
1116 const APInt &C2V = CI2->getValue();
1117 switch (Opcode) {
1118 default:
1119 break;
1120 case Instruction::Add:
1121 return ConstantInt::get(CI1->getContext(), C1V + C2V);
1122 case Instruction::Sub:
1123 return ConstantInt::get(CI1->getContext(), C1V - C2V);
1124 case Instruction::Mul:
1125 return ConstantInt::get(CI1->getContext(), C1V * C2V);
1126 case Instruction::UDiv:
1127 assert(!CI2->isZero() && "Div by zero handled above");
1128 return ConstantInt::get(CI1->getContext(), C1V.udiv(C2V));
1129 case Instruction::SDiv:
1130 assert(!CI2->isZero() && "Div by zero handled above");
1131 if (C2V.isAllOnes() && C1V.isMinSignedValue())
1132 return PoisonValue::get(CI1->getType()); // MIN_INT / -1 -> poison
1133 return ConstantInt::get(CI1->getContext(), C1V.sdiv(C2V));
1134 case Instruction::URem:
1135 assert(!CI2->isZero() && "Div by zero handled above");
1136 return ConstantInt::get(CI1->getContext(), C1V.urem(C2V));
1137 case Instruction::SRem:
1138 assert(!CI2->isZero() && "Div by zero handled above");
1139 if (C2V.isAllOnes() && C1V.isMinSignedValue())
1140 return PoisonValue::get(CI1->getType()); // MIN_INT % -1 -> poison
1141 return ConstantInt::get(CI1->getContext(), C1V.srem(C2V));
1142 case Instruction::And:
1143 return ConstantInt::get(CI1->getContext(), C1V & C2V);
1144 case Instruction::Or:
1145 return ConstantInt::get(CI1->getContext(), C1V | C2V);
1146 case Instruction::Xor:
1147 return ConstantInt::get(CI1->getContext(), C1V ^ C2V);
1148 case Instruction::Shl:
1149 if (C2V.ult(C1V.getBitWidth()))
1150 return ConstantInt::get(CI1->getContext(), C1V.shl(C2V));
1151 return PoisonValue::get(C1->getType()); // too big shift is poison
1152 case Instruction::LShr:
1153 if (C2V.ult(C1V.getBitWidth()))
1154 return ConstantInt::get(CI1->getContext(), C1V.lshr(C2V));
1155 return PoisonValue::get(C1->getType()); // too big shift is poison
1156 case Instruction::AShr:
1157 if (C2V.ult(C1V.getBitWidth()))
1158 return ConstantInt::get(CI1->getContext(), C1V.ashr(C2V));
1159 return PoisonValue::get(C1->getType()); // too big shift is poison
1160 }
1161 }
1162
1163 switch (Opcode) {
1164 case Instruction::SDiv:
1165 case Instruction::UDiv:
1166 case Instruction::URem:
1167 case Instruction::SRem:
1168 case Instruction::LShr:
1169 case Instruction::AShr:
1170 case Instruction::Shl:
1171 if (CI1->isZero()) return C1;
1172 break;
1173 default:
1174 break;
1175 }
1176 } else if (ConstantFP *CFP1 = dyn_cast<ConstantFP>(C1)) {
1177 if (ConstantFP *CFP2 = dyn_cast<ConstantFP>(C2)) {
1178 const APFloat &C1V = CFP1->getValueAPF();
1179 const APFloat &C2V = CFP2->getValueAPF();
1180 APFloat C3V = C1V; // copy for modification
1181 switch (Opcode) {
1182 default:
1183 break;
1184 case Instruction::FAdd:
1185 (void)C3V.add(C2V, APFloat::rmNearestTiesToEven);
1186 return ConstantFP::get(C1->getContext(), C3V);
1187 case Instruction::FSub:
1188 (void)C3V.subtract(C2V, APFloat::rmNearestTiesToEven);
1189 return ConstantFP::get(C1->getContext(), C3V);
1190 case Instruction::FMul:
1191 (void)C3V.multiply(C2V, APFloat::rmNearestTiesToEven);
1192 return ConstantFP::get(C1->getContext(), C3V);
1193 case Instruction::FDiv:
1194 (void)C3V.divide(C2V, APFloat::rmNearestTiesToEven);
1195 return ConstantFP::get(C1->getContext(), C3V);
1196 case Instruction::FRem:
1197 (void)C3V.mod(C2V);
1198 return ConstantFP::get(C1->getContext(), C3V);
1199 }
1200 }
1201 } else if (auto *VTy = dyn_cast<VectorType>(C1->getType())) {
1202 // Fast path for splatted constants.
1203 if (Constant *C2Splat = C2->getSplatValue()) {
1204 if (Instruction::isIntDivRem(Opcode) && C2Splat->isNullValue())
1205 return PoisonValue::get(VTy);
1206 if (Constant *C1Splat = C1->getSplatValue()) {
1207 Constant *Res =
1209 ? ConstantExpr::get(Opcode, C1Splat, C2Splat)
1210 : ConstantFoldBinaryInstruction(Opcode, C1Splat, C2Splat);
1211 if (!Res)
1212 return nullptr;
1213 return ConstantVector::getSplat(VTy->getElementCount(), Res);
1214 }
1215 }
1216
1217 if (auto *FVTy = dyn_cast<FixedVectorType>(VTy)) {
1218 // Fold each element and create a vector constant from those constants.
1220 Type *Ty = IntegerType::get(FVTy->getContext(), 32);
1221 for (unsigned i = 0, e = FVTy->getNumElements(); i != e; ++i) {
1222 Constant *ExtractIdx = ConstantInt::get(Ty, i);
1223 Constant *LHS = ConstantExpr::getExtractElement(C1, ExtractIdx);
1224 Constant *RHS = ConstantExpr::getExtractElement(C2, ExtractIdx);
1225
1226 // If any element of a divisor vector is zero, the whole op is poison.
1227 if (Instruction::isIntDivRem(Opcode) && RHS->isNullValue())
1228 return PoisonValue::get(VTy);
1229
1231 ? ConstantExpr::get(Opcode, LHS, RHS)
1233 if (!Res)
1234 return nullptr;
1235 Result.push_back(Res);
1236 }
1237
1238 return ConstantVector::get(Result);
1239 }
1240 }
1241
1242 if (ConstantExpr *CE1 = dyn_cast<ConstantExpr>(C1)) {
1243 // There are many possible foldings we could do here. We should probably
1244 // at least fold add of a pointer with an integer into the appropriate
1245 // getelementptr. This will improve alias analysis a bit.
1246
1247 // Given ((a + b) + c), if (b + c) folds to something interesting, return
1248 // (a + (b + c)).
1249 if (Instruction::isAssociative(Opcode) && CE1->getOpcode() == Opcode) {
1250 Constant *T = ConstantExpr::get(Opcode, CE1->getOperand(1), C2);
1251 if (!isa<ConstantExpr>(T) || cast<ConstantExpr>(T)->getOpcode() != Opcode)
1252 return ConstantExpr::get(Opcode, CE1->getOperand(0), T);
1253 }
1254 } else if (isa<ConstantExpr>(C2)) {
1255 // If C2 is a constant expr and C1 isn't, flop them around and fold the
1256 // other way if possible.
1257 if (Instruction::isCommutative(Opcode))
1258 return ConstantFoldBinaryInstruction(Opcode, C2, C1);
1259 }
1260
1261 // i1 can be simplified in many cases.
1262 if (C1->getType()->isIntegerTy(1)) {
1263 switch (Opcode) {
1264 case Instruction::Add:
1265 case Instruction::Sub:
1266 return ConstantExpr::getXor(C1, C2);
1267 case Instruction::Mul:
1268 return ConstantExpr::getAnd(C1, C2);
1269 case Instruction::Shl:
1270 case Instruction::LShr:
1271 case Instruction::AShr:
1272 // We can assume that C2 == 0. If it were one the result would be
1273 // undefined because the shift value is as large as the bitwidth.
1274 return C1;
1275 case Instruction::SDiv:
1276 case Instruction::UDiv:
1277 // We can assume that C2 == 1. If it were zero the result would be
1278 // undefined through division by zero.
1279 return C1;
1280 case Instruction::URem:
1281 case Instruction::SRem:
1282 // We can assume that C2 == 1. If it were zero the result would be
1283 // undefined through division by zero.
1284 return ConstantInt::getFalse(C1->getContext());
1285 default:
1286 break;
1287 }
1288 }
1289
1290 // We don't know how to fold this.
1291 return nullptr;
1292}
1293
1294/// This function determines if there is anything we can decide about the two
1295/// constants provided. This doesn't need to handle simple things like
1296/// ConstantFP comparisons, but should instead handle ConstantExprs.
1297/// If we can determine that the two constants have a particular relation to
1298/// each other, we should return the corresponding FCmpInst predicate,
1299/// otherwise return FCmpInst::BAD_FCMP_PREDICATE. This is used below in
1300/// ConstantFoldCompareInstruction.
1301///
1302/// To simplify this code we canonicalize the relation so that the first
1303/// operand is always the most "complex" of the two. We consider ConstantFP
1304/// to be the simplest, and ConstantExprs to be the most complex.
1306 assert(V1->getType() == V2->getType() &&
1307 "Cannot compare values of different types!");
1308
1309 // We do not know if a constant expression will evaluate to a number or NaN.
1310 // Therefore, we can only say that the relation is unordered or equal.
1311 if (V1 == V2) return FCmpInst::FCMP_UEQ;
1312
1313 if (!isa<ConstantExpr>(V1)) {
1314 if (!isa<ConstantExpr>(V2)) {
1315 // Simple case, use the standard constant folder.
1316 ConstantInt *R = nullptr;
1317 R = dyn_cast<ConstantInt>(
1318 ConstantExpr::getFCmp(FCmpInst::FCMP_OEQ, V1, V2));
1319 if (R && !R->isZero())
1320 return FCmpInst::FCMP_OEQ;
1321 R = dyn_cast<ConstantInt>(
1322 ConstantExpr::getFCmp(FCmpInst::FCMP_OLT, V1, V2));
1323 if (R && !R->isZero())
1324 return FCmpInst::FCMP_OLT;
1325 R = dyn_cast<ConstantInt>(
1326 ConstantExpr::getFCmp(FCmpInst::FCMP_OGT, V1, V2));
1327 if (R && !R->isZero())
1328 return FCmpInst::FCMP_OGT;
1329
1330 // Nothing more we can do
1331 return FCmpInst::BAD_FCMP_PREDICATE;
1332 }
1333
1334 // If the first operand is simple and second is ConstantExpr, swap operands.
1335 FCmpInst::Predicate SwappedRelation = evaluateFCmpRelation(V2, V1);
1336 if (SwappedRelation != FCmpInst::BAD_FCMP_PREDICATE)
1337 return FCmpInst::getSwappedPredicate(SwappedRelation);
1338 } else {
1339 // Ok, the LHS is known to be a constantexpr. The RHS can be any of a
1340 // constantexpr or a simple constant.
1341 ConstantExpr *CE1 = cast<ConstantExpr>(V1);
1342 switch (CE1->getOpcode()) {
1343 case Instruction::FPTrunc:
1344 case Instruction::FPExt:
1345 case Instruction::UIToFP:
1346 case Instruction::SIToFP:
1347 // We might be able to do something with these but we don't right now.
1348 break;
1349 default:
1350 break;
1351 }
1352 }
1353 // There are MANY other foldings that we could perform here. They will
1354 // probably be added on demand, as they seem needed.
1355 return FCmpInst::BAD_FCMP_PREDICATE;
1356}
1357
1359 const GlobalValue *GV2) {
1360 auto isGlobalUnsafeForEquality = [](const GlobalValue *GV) {
1361 if (GV->isInterposable() || GV->hasGlobalUnnamedAddr())
1362 return true;
1363 if (const auto *GVar = dyn_cast<GlobalVariable>(GV)) {
1364 Type *Ty = GVar->getValueType();
1365 // A global with opaque type might end up being zero sized.
1366 if (!Ty->isSized())
1367 return true;
1368 // A global with an empty type might lie at the address of any other
1369 // global.
1370 if (Ty->isEmptyTy())
1371 return true;
1372 }
1373 return false;
1374 };
1375 // Don't try to decide equality of aliases.
1376 if (!isa<GlobalAlias>(GV1) && !isa<GlobalAlias>(GV2))
1377 if (!isGlobalUnsafeForEquality(GV1) && !isGlobalUnsafeForEquality(GV2))
1378 return ICmpInst::ICMP_NE;
1379 return ICmpInst::BAD_ICMP_PREDICATE;
1380}
1381
1382/// This function determines if there is anything we can decide about the two
1383/// constants provided. This doesn't need to handle simple things like integer
1384/// comparisons, but should instead handle ConstantExprs and GlobalValues.
1385/// If we can determine that the two constants have a particular relation to
1386/// each other, we should return the corresponding ICmp predicate, otherwise
1387/// return ICmpInst::BAD_ICMP_PREDICATE.
1388///
1389/// To simplify this code we canonicalize the relation so that the first
1390/// operand is always the most "complex" of the two. We consider simple
1391/// constants (like ConstantInt) to be the simplest, followed by
1392/// GlobalValues, followed by ConstantExpr's (the most complex).
1393///
1395 bool isSigned) {
1396 assert(V1->getType() == V2->getType() &&
1397 "Cannot compare different types of values!");
1398 if (V1 == V2) return ICmpInst::ICMP_EQ;
1399
1400 if (!isa<ConstantExpr>(V1) && !isa<GlobalValue>(V1) &&
1401 !isa<BlockAddress>(V1)) {
1402 if (!isa<GlobalValue>(V2) && !isa<ConstantExpr>(V2) &&
1403 !isa<BlockAddress>(V2)) {
1404 // We distilled this down to a simple case, use the standard constant
1405 // folder.
1406 ConstantInt *R = nullptr;
1407 ICmpInst::Predicate pred = ICmpInst::ICMP_EQ;
1408 R = dyn_cast<ConstantInt>(ConstantExpr::getICmp(pred, V1, V2));
1409 if (R && !R->isZero())
1410 return pred;
1411 pred = isSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT;
1412 R = dyn_cast<ConstantInt>(ConstantExpr::getICmp(pred, V1, V2));
1413 if (R && !R->isZero())
1414 return pred;
1415 pred = isSigned ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
1416 R = dyn_cast<ConstantInt>(ConstantExpr::getICmp(pred, V1, V2));
1417 if (R && !R->isZero())
1418 return pred;
1419
1420 // If we couldn't figure it out, bail.
1421 return ICmpInst::BAD_ICMP_PREDICATE;
1422 }
1423
1424 // If the first operand is simple, swap operands.
1425 ICmpInst::Predicate SwappedRelation =
1427 if (SwappedRelation != ICmpInst::BAD_ICMP_PREDICATE)
1428 return ICmpInst::getSwappedPredicate(SwappedRelation);
1429
1430 } else if (const GlobalValue *GV = dyn_cast<GlobalValue>(V1)) {
1431 if (isa<ConstantExpr>(V2)) { // Swap as necessary.
1432 ICmpInst::Predicate SwappedRelation =
1434 if (SwappedRelation != ICmpInst::BAD_ICMP_PREDICATE)
1435 return ICmpInst::getSwappedPredicate(SwappedRelation);
1436 return ICmpInst::BAD_ICMP_PREDICATE;
1437 }
1438
1439 // Now we know that the RHS is a GlobalValue, BlockAddress or simple
1440 // constant (which, since the types must match, means that it's a
1441 // ConstantPointerNull).
1442 if (const GlobalValue *GV2 = dyn_cast<GlobalValue>(V2)) {
1443 return areGlobalsPotentiallyEqual(GV, GV2);
1444 } else if (isa<BlockAddress>(V2)) {
1445 return ICmpInst::ICMP_NE; // Globals never equal labels.
1446 } else {
1447 assert(isa<ConstantPointerNull>(V2) && "Canonicalization guarantee!");
1448 // GlobalVals can never be null unless they have external weak linkage.
1449 // We don't try to evaluate aliases here.
1450 // NOTE: We should not be doing this constant folding if null pointer
1451 // is considered valid for the function. But currently there is no way to
1452 // query it from the Constant type.
1453 if (!GV->hasExternalWeakLinkage() && !isa<GlobalAlias>(GV) &&
1454 !NullPointerIsDefined(nullptr /* F */,
1455 GV->getType()->getAddressSpace()))
1456 return ICmpInst::ICMP_UGT;
1457 }
1458 } else if (const BlockAddress *BA = dyn_cast<BlockAddress>(V1)) {
1459 if (isa<ConstantExpr>(V2)) { // Swap as necessary.
1460 ICmpInst::Predicate SwappedRelation =
1462 if (SwappedRelation != ICmpInst::BAD_ICMP_PREDICATE)
1463 return ICmpInst::getSwappedPredicate(SwappedRelation);
1464 return ICmpInst::BAD_ICMP_PREDICATE;
1465 }
1466
1467 // Now we know that the RHS is a GlobalValue, BlockAddress or simple
1468 // constant (which, since the types must match, means that it is a
1469 // ConstantPointerNull).
1470 if (const BlockAddress *BA2 = dyn_cast<BlockAddress>(V2)) {
1471 // Block address in another function can't equal this one, but block
1472 // addresses in the current function might be the same if blocks are
1473 // empty.
1474 if (BA2->getFunction() != BA->getFunction())
1475 return ICmpInst::ICMP_NE;
1476 } else {
1477 // Block addresses aren't null, don't equal the address of globals.
1478 assert((isa<ConstantPointerNull>(V2) || isa<GlobalValue>(V2)) &&
1479 "Canonicalization guarantee!");
1480 return ICmpInst::ICMP_NE;
1481 }
1482 } else {
1483 // Ok, the LHS is known to be a constantexpr. The RHS can be any of a
1484 // constantexpr, a global, block address, or a simple constant.
1485 ConstantExpr *CE1 = cast<ConstantExpr>(V1);
1486 Constant *CE1Op0 = CE1->getOperand(0);
1487
1488 switch (CE1->getOpcode()) {
1489 case Instruction::Trunc:
1490 case Instruction::FPTrunc:
1491 case Instruction::FPExt:
1492 case Instruction::FPToUI:
1493 case Instruction::FPToSI:
1494 break; // We can't evaluate floating point casts or truncations.
1495
1496 case Instruction::BitCast:
1497 // If this is a global value cast, check to see if the RHS is also a
1498 // GlobalValue.
1499 if (const GlobalValue *GV = dyn_cast<GlobalValue>(CE1Op0))
1500 if (const GlobalValue *GV2 = dyn_cast<GlobalValue>(V2))
1501 return areGlobalsPotentiallyEqual(GV, GV2);
1502 [[fallthrough]];
1503 case Instruction::UIToFP:
1504 case Instruction::SIToFP:
1505 case Instruction::ZExt:
1506 case Instruction::SExt:
1507 // We can't evaluate floating point casts or truncations.
1508 if (CE1Op0->getType()->isFPOrFPVectorTy())
1509 break;
1510
1511 // If the cast is not actually changing bits, and the second operand is a
1512 // null pointer, do the comparison with the pre-casted value.
1513 if (V2->isNullValue() && CE1->getType()->isIntOrPtrTy()) {
1514 if (CE1->getOpcode() == Instruction::ZExt) isSigned = false;
1515 if (CE1->getOpcode() == Instruction::SExt) isSigned = true;
1516 return evaluateICmpRelation(CE1Op0,
1518 isSigned);
1519 }
1520 break;
1521
1522 case Instruction::GetElementPtr: {
1523 GEPOperator *CE1GEP = cast<GEPOperator>(CE1);
1524 // Ok, since this is a getelementptr, we know that the constant has a
1525 // pointer type. Check the various cases.
1526 if (isa<ConstantPointerNull>(V2)) {
1527 // If we are comparing a GEP to a null pointer, check to see if the base
1528 // of the GEP equals the null pointer.
1529 if (const GlobalValue *GV = dyn_cast<GlobalValue>(CE1Op0)) {
1530 // If its not weak linkage, the GVal must have a non-zero address
1531 // so the result is greater-than
1532 if (!GV->hasExternalWeakLinkage() && CE1GEP->isInBounds())
1533 return ICmpInst::ICMP_UGT;
1534 }
1535 } else if (const GlobalValue *GV2 = dyn_cast<GlobalValue>(V2)) {
1536 if (const GlobalValue *GV = dyn_cast<GlobalValue>(CE1Op0)) {
1537 if (GV != GV2) {
1538 if (CE1GEP->hasAllZeroIndices())
1539 return areGlobalsPotentiallyEqual(GV, GV2);
1540 return ICmpInst::BAD_ICMP_PREDICATE;
1541 }
1542 }
1543 } else if (const auto *CE2GEP = dyn_cast<GEPOperator>(V2)) {
1544 // By far the most common case to handle is when the base pointers are
1545 // obviously to the same global.
1546 const Constant *CE2Op0 = cast<Constant>(CE2GEP->getPointerOperand());
1547 if (isa<GlobalValue>(CE1Op0) && isa<GlobalValue>(CE2Op0)) {
1548 // Don't know relative ordering, but check for inequality.
1549 if (CE1Op0 != CE2Op0) {
1550 if (CE1GEP->hasAllZeroIndices() && CE2GEP->hasAllZeroIndices())
1551 return areGlobalsPotentiallyEqual(cast<GlobalValue>(CE1Op0),
1552 cast<GlobalValue>(CE2Op0));
1553 return ICmpInst::BAD_ICMP_PREDICATE;
1554 }
1555 }
1556 }
1557 break;
1558 }
1559 default:
1560 break;
1561 }
1562 }
1563
1564 return ICmpInst::BAD_ICMP_PREDICATE;
1565}
1566
1568 Constant *C1, Constant *C2) {
1569 const GlobalValue *GV = dyn_cast<GlobalValue>(C2);
1570 if (!GV || !C1->isNullValue())
1571 return nullptr;
1572
1573 // Don't try to evaluate aliases. External weak GV can be null.
1574 if (!isa<GlobalAlias>(GV) && !GV->hasExternalWeakLinkage() &&
1575 !NullPointerIsDefined(nullptr /* F */,
1576 GV->getType()->getAddressSpace())) {
1577 if (Predicate == ICmpInst::ICMP_EQ)
1578 return ConstantInt::getFalse(C1->getContext());
1579 else if (Predicate == ICmpInst::ICMP_NE)
1580 return ConstantInt::getTrue(C1->getContext());
1581 }
1582
1583 return nullptr;
1584}
1585
1587 Constant *C1, Constant *C2) {
1588 Type *ResultTy;
1589 if (VectorType *VT = dyn_cast<VectorType>(C1->getType()))
1590 ResultTy = VectorType::get(Type::getInt1Ty(C1->getContext()),
1591 VT->getElementCount());
1592 else
1593 ResultTy = Type::getInt1Ty(C1->getContext());
1594
1595 // Fold FCMP_FALSE/FCMP_TRUE unconditionally.
1596 if (Predicate == FCmpInst::FCMP_FALSE)
1597 return Constant::getNullValue(ResultTy);
1598
1599 if (Predicate == FCmpInst::FCMP_TRUE)
1600 return Constant::getAllOnesValue(ResultTy);
1601
1602 // Handle some degenerate cases first
1603 if (isa<PoisonValue>(C1) || isa<PoisonValue>(C2))
1604 return PoisonValue::get(ResultTy);
1605
1606 if (isa<UndefValue>(C1) || isa<UndefValue>(C2)) {
1607 bool isIntegerPredicate = ICmpInst::isIntPredicate(Predicate);
1608 // For EQ and NE, we can always pick a value for the undef to make the
1609 // predicate pass or fail, so we can return undef.
1610 // Also, if both operands are undef, we can return undef for int comparison.
1611 if (ICmpInst::isEquality(Predicate) || (isIntegerPredicate && C1 == C2))
1612 return UndefValue::get(ResultTy);
1613
1614 // Otherwise, for integer compare, pick the same value as the non-undef
1615 // operand, and fold it to true or false.
1616 if (isIntegerPredicate)
1617 return ConstantInt::get(ResultTy, CmpInst::isTrueWhenEqual(Predicate));
1618
1619 // Choosing NaN for the undef will always make unordered comparison succeed
1620 // and ordered comparison fails.
1621 return ConstantInt::get(ResultTy, CmpInst::isUnordered(Predicate));
1622 }
1623
1624 // icmp eq/ne(null,GV) -> false/true
1625 if (Constant *Folded = constantFoldCompareGlobalToNull(Predicate, C1, C2))
1626 return Folded;
1627
1628 // icmp eq/ne(GV,null) -> false/true
1629 if (Constant *Folded = constantFoldCompareGlobalToNull(Predicate, C2, C1))
1630 return Folded;
1631
1632 if (C2->isNullValue()) {
1633 // The caller is expected to commute the operands if the constant expression
1634 // is C2.
1635 // C1 >= 0 --> true
1636 if (Predicate == ICmpInst::ICMP_UGE)
1637 return Constant::getAllOnesValue(ResultTy);
1638 // C1 < 0 --> false
1639 if (Predicate == ICmpInst::ICMP_ULT)
1640 return Constant::getNullValue(ResultTy);
1641 }
1642
1643 // If the comparison is a comparison between two i1's, simplify it.
1644 if (C1->getType()->isIntegerTy(1)) {
1645 switch (Predicate) {
1646 case ICmpInst::ICMP_EQ:
1647 if (isa<ConstantInt>(C2))
1650 case ICmpInst::ICMP_NE:
1651 return ConstantExpr::getXor(C1, C2);
1652 default:
1653 break;
1654 }
1655 }
1656
1657 if (isa<ConstantInt>(C1) && isa<ConstantInt>(C2)) {
1658 const APInt &V1 = cast<ConstantInt>(C1)->getValue();
1659 const APInt &V2 = cast<ConstantInt>(C2)->getValue();
1660 return ConstantInt::get(ResultTy, ICmpInst::compare(V1, V2, Predicate));
1661 } else if (isa<ConstantFP>(C1) && isa<ConstantFP>(C2)) {
1662 const APFloat &C1V = cast<ConstantFP>(C1)->getValueAPF();
1663 const APFloat &C2V = cast<ConstantFP>(C2)->getValueAPF();
1664 return ConstantInt::get(ResultTy, FCmpInst::compare(C1V, C2V, Predicate));
1665 } else if (auto *C1VTy = dyn_cast<VectorType>(C1->getType())) {
1666
1667 // Fast path for splatted constants.
1668 if (Constant *C1Splat = C1->getSplatValue())
1669 if (Constant *C2Splat = C2->getSplatValue())
1671 C1VTy->getElementCount(),
1672 ConstantExpr::getCompare(Predicate, C1Splat, C2Splat));
1673
1674 // Do not iterate on scalable vector. The number of elements is unknown at
1675 // compile-time.
1676 if (isa<ScalableVectorType>(C1VTy))
1677 return nullptr;
1678
1679 // If we can constant fold the comparison of each element, constant fold
1680 // the whole vector comparison.
1682 Type *Ty = IntegerType::get(C1->getContext(), 32);
1683 // Compare the elements, producing an i1 result or constant expr.
1684 for (unsigned I = 0, E = C1VTy->getElementCount().getKnownMinValue();
1685 I != E; ++I) {
1686 Constant *C1E =
1688 Constant *C2E =
1690
1691 ResElts.push_back(ConstantExpr::getCompare(Predicate, C1E, C2E));
1692 }
1693
1694 return ConstantVector::get(ResElts);
1695 }
1696
1697 if (C1->getType()->isFloatingPointTy() &&
1698 // Only call evaluateFCmpRelation if we have a constant expr to avoid
1699 // infinite recursive loop
1700 (isa<ConstantExpr>(C1) || isa<ConstantExpr>(C2))) {
1701 int Result = -1; // -1 = unknown, 0 = known false, 1 = known true.
1702 switch (evaluateFCmpRelation(C1, C2)) {
1703 default: llvm_unreachable("Unknown relation!");
1704 case FCmpInst::FCMP_UNO:
1705 case FCmpInst::FCMP_ORD:
1706 case FCmpInst::FCMP_UNE:
1707 case FCmpInst::FCMP_ULT:
1708 case FCmpInst::FCMP_UGT:
1709 case FCmpInst::FCMP_ULE:
1710 case FCmpInst::FCMP_UGE:
1711 case FCmpInst::FCMP_TRUE:
1712 case FCmpInst::FCMP_FALSE:
1713 case FCmpInst::BAD_FCMP_PREDICATE:
1714 break; // Couldn't determine anything about these constants.
1715 case FCmpInst::FCMP_OEQ: // We know that C1 == C2
1716 Result =
1717 (Predicate == FCmpInst::FCMP_UEQ || Predicate == FCmpInst::FCMP_OEQ ||
1718 Predicate == FCmpInst::FCMP_ULE || Predicate == FCmpInst::FCMP_OLE ||
1719 Predicate == FCmpInst::FCMP_UGE || Predicate == FCmpInst::FCMP_OGE);
1720 break;
1721 case FCmpInst::FCMP_OLT: // We know that C1 < C2
1722 Result =
1723 (Predicate == FCmpInst::FCMP_UNE || Predicate == FCmpInst::FCMP_ONE ||
1724 Predicate == FCmpInst::FCMP_ULT || Predicate == FCmpInst::FCMP_OLT ||
1725 Predicate == FCmpInst::FCMP_ULE || Predicate == FCmpInst::FCMP_OLE);
1726 break;
1727 case FCmpInst::FCMP_OGT: // We know that C1 > C2
1728 Result =
1729 (Predicate == FCmpInst::FCMP_UNE || Predicate == FCmpInst::FCMP_ONE ||
1730 Predicate == FCmpInst::FCMP_UGT || Predicate == FCmpInst::FCMP_OGT ||
1731 Predicate == FCmpInst::FCMP_UGE || Predicate == FCmpInst::FCMP_OGE);
1732 break;
1733 case FCmpInst::FCMP_OLE: // We know that C1 <= C2
1734 // We can only partially decide this relation.
1735 if (Predicate == FCmpInst::FCMP_UGT || Predicate == FCmpInst::FCMP_OGT)
1736 Result = 0;
1737 else if (Predicate == FCmpInst::FCMP_ULT ||
1738 Predicate == FCmpInst::FCMP_OLT)
1739 Result = 1;
1740 break;
1741 case FCmpInst::FCMP_OGE: // We known that C1 >= C2
1742 // We can only partially decide this relation.
1743 if (Predicate == FCmpInst::FCMP_ULT || Predicate == FCmpInst::FCMP_OLT)
1744 Result = 0;
1745 else if (Predicate == FCmpInst::FCMP_UGT ||
1746 Predicate == FCmpInst::FCMP_OGT)
1747 Result = 1;
1748 break;
1749 case FCmpInst::FCMP_ONE: // We know that C1 != C2
1750 // We can only partially decide this relation.
1751 if (Predicate == FCmpInst::FCMP_OEQ || Predicate == FCmpInst::FCMP_UEQ)
1752 Result = 0;
1753 else if (Predicate == FCmpInst::FCMP_ONE ||
1754 Predicate == FCmpInst::FCMP_UNE)
1755 Result = 1;
1756 break;
1757 case FCmpInst::FCMP_UEQ: // We know that C1 == C2 || isUnordered(C1, C2).
1758 // We can only partially decide this relation.
1759 if (Predicate == FCmpInst::FCMP_ONE)
1760 Result = 0;
1761 else if (Predicate == FCmpInst::FCMP_UEQ)
1762 Result = 1;
1763 break;
1764 }
1765
1766 // If we evaluated the result, return it now.
1767 if (Result != -1)
1768 return ConstantInt::get(ResultTy, Result);
1769
1770 } else {
1771 // Evaluate the relation between the two constants, per the predicate.
1772 int Result = -1; // -1 = unknown, 0 = known false, 1 = known true.
1773 switch (evaluateICmpRelation(C1, C2, CmpInst::isSigned(Predicate))) {
1774 default: llvm_unreachable("Unknown relational!");
1775 case ICmpInst::BAD_ICMP_PREDICATE:
1776 break; // Couldn't determine anything about these constants.
1777 case ICmpInst::ICMP_EQ: // We know the constants are equal!
1778 // If we know the constants are equal, we can decide the result of this
1779 // computation precisely.
1780 Result = ICmpInst::isTrueWhenEqual(Predicate);
1781 break;
1782 case ICmpInst::ICMP_ULT:
1783 switch (Predicate) {
1784 case ICmpInst::ICMP_ULT: case ICmpInst::ICMP_NE: case ICmpInst::ICMP_ULE:
1785 Result = 1; break;
1786 case ICmpInst::ICMP_UGT: case ICmpInst::ICMP_EQ: case ICmpInst::ICMP_UGE:
1787 Result = 0; break;
1788 default:
1789 break;
1790 }
1791 break;
1792 case ICmpInst::ICMP_SLT:
1793 switch (Predicate) {
1794 case ICmpInst::ICMP_SLT: case ICmpInst::ICMP_NE: case ICmpInst::ICMP_SLE:
1795 Result = 1; break;
1796 case ICmpInst::ICMP_SGT: case ICmpInst::ICMP_EQ: case ICmpInst::ICMP_SGE:
1797 Result = 0; break;
1798 default:
1799 break;
1800 }
1801 break;
1802 case ICmpInst::ICMP_UGT:
1803 switch (Predicate) {
1804 case ICmpInst::ICMP_UGT: case ICmpInst::ICMP_NE: case ICmpInst::ICMP_UGE:
1805 Result = 1; break;
1806 case ICmpInst::ICMP_ULT: case ICmpInst::ICMP_EQ: case ICmpInst::ICMP_ULE:
1807 Result = 0; break;
1808 default:
1809 break;
1810 }
1811 break;
1812 case ICmpInst::ICMP_SGT:
1813 switch (Predicate) {
1814 case ICmpInst::ICMP_SGT: case ICmpInst::ICMP_NE: case ICmpInst::ICMP_SGE:
1815 Result = 1; break;
1816 case ICmpInst::ICMP_SLT: case ICmpInst::ICMP_EQ: case ICmpInst::ICMP_SLE:
1817 Result = 0; break;
1818 default:
1819 break;
1820 }
1821 break;
1822 case ICmpInst::ICMP_ULE:
1823 if (Predicate == ICmpInst::ICMP_UGT)
1824 Result = 0;
1825 if (Predicate == ICmpInst::ICMP_ULT || Predicate == ICmpInst::ICMP_ULE)
1826 Result = 1;
1827 break;
1828 case ICmpInst::ICMP_SLE:
1829 if (Predicate == ICmpInst::ICMP_SGT)
1830 Result = 0;
1831 if (Predicate == ICmpInst::ICMP_SLT || Predicate == ICmpInst::ICMP_SLE)
1832 Result = 1;
1833 break;
1834 case ICmpInst::ICMP_UGE:
1835 if (Predicate == ICmpInst::ICMP_ULT)
1836 Result = 0;
1837 if (Predicate == ICmpInst::ICMP_UGT || Predicate == ICmpInst::ICMP_UGE)
1838 Result = 1;
1839 break;
1840 case ICmpInst::ICMP_SGE:
1841 if (Predicate == ICmpInst::ICMP_SLT)
1842 Result = 0;
1843 if (Predicate == ICmpInst::ICMP_SGT || Predicate == ICmpInst::ICMP_SGE)
1844 Result = 1;
1845 break;
1846 case ICmpInst::ICMP_NE:
1847 if (Predicate == ICmpInst::ICMP_EQ)
1848 Result = 0;
1849 if (Predicate == ICmpInst::ICMP_NE)
1850 Result = 1;
1851 break;
1852 }
1853
1854 // If we evaluated the result, return it now.
1855 if (Result != -1)
1856 return ConstantInt::get(ResultTy, Result);
1857
1858 // If the right hand side is a bitcast, try using its inverse to simplify
1859 // it by moving it to the left hand side. We can't do this if it would turn
1860 // a vector compare into a scalar compare or visa versa, or if it would turn
1861 // the operands into FP values.
1862 if (ConstantExpr *CE2 = dyn_cast<ConstantExpr>(C2)) {
1863 Constant *CE2Op0 = CE2->getOperand(0);
1864 if (CE2->getOpcode() == Instruction::BitCast &&
1865 CE2->getType()->isVectorTy() == CE2Op0->getType()->isVectorTy() &&
1866 !CE2Op0->getType()->isFPOrFPVectorTy()) {
1868 return ConstantExpr::getICmp(Predicate, Inverse, CE2Op0);
1869 }
1870 }
1871
1872 // If the left hand side is an extension, try eliminating it.
1873 if (ConstantExpr *CE1 = dyn_cast<ConstantExpr>(C1)) {
1874 if ((CE1->getOpcode() == Instruction::SExt &&
1875 ICmpInst::isSigned(Predicate)) ||
1876 (CE1->getOpcode() == Instruction::ZExt &&
1877 !ICmpInst::isSigned(Predicate))) {
1878 Constant *CE1Op0 = CE1->getOperand(0);
1879 Constant *CE1Inverse = ConstantExpr::getTrunc(CE1, CE1Op0->getType());
1880 if (CE1Inverse == CE1Op0) {
1881 // Check whether we can safely truncate the right hand side.
1882 Constant *C2Inverse = ConstantExpr::getTrunc(C2, CE1Op0->getType());
1883 if (ConstantExpr::getCast(CE1->getOpcode(), C2Inverse,
1884 C2->getType()) == C2)
1885 return ConstantExpr::getICmp(Predicate, CE1Inverse, C2Inverse);
1886 }
1887 }
1888 }
1889
1890 if ((!isa<ConstantExpr>(C1) && isa<ConstantExpr>(C2)) ||
1891 (C1->isNullValue() && !C2->isNullValue())) {
1892 // If C2 is a constant expr and C1 isn't, flip them around and fold the
1893 // other way if possible.
1894 // Also, if C1 is null and C2 isn't, flip them around.
1895 Predicate = ICmpInst::getSwappedPredicate(Predicate);
1896 return ConstantExpr::getICmp(Predicate, C2, C1);
1897 }
1898 }
1899 return nullptr;
1900}
1901
1902/// Test whether the given sequence of *normalized* indices is "inbounds".
1903template<typename IndexTy>
1905 // No indices means nothing that could be out of bounds.
1906 if (Idxs.empty()) return true;
1907
1908 // If the first index is zero, it's in bounds.
1909 if (cast<Constant>(Idxs[0])->isNullValue()) return true;
1910
1911 // If the first index is one and all the rest are zero, it's in bounds,
1912 // by the one-past-the-end rule.
1913 if (auto *CI = dyn_cast<ConstantInt>(Idxs[0])) {
1914 if (!CI->isOne())
1915 return false;
1916 } else {
1917 auto *CV = cast<ConstantDataVector>(Idxs[0]);
1918 CI = dyn_cast_or_null<ConstantInt>(CV->getSplatValue());
1919 if (!CI || !CI->isOne())
1920 return false;
1921 }
1922
1923 for (unsigned i = 1, e = Idxs.size(); i != e; ++i)
1924 if (!cast<Constant>(Idxs[i])->isNullValue())
1925 return false;
1926 return true;
1927}
1928
1929/// Test whether a given ConstantInt is in-range for a SequentialType.
1930static bool isIndexInRangeOfArrayType(uint64_t NumElements,
1931 const ConstantInt *CI) {
1932 // We cannot bounds check the index if it doesn't fit in an int64_t.
1933 if (CI->getValue().getSignificantBits() > 64)
1934 return false;
1935
1936 // A negative index or an index past the end of our sequential type is
1937 // considered out-of-range.
1938 int64_t IndexVal = CI->getSExtValue();
1939 if (IndexVal < 0 || (IndexVal != 0 && (uint64_t)IndexVal >= NumElements))
1940 return false;
1941
1942 // Otherwise, it is in-range.
1943 return true;
1944}
1945
1946// Combine Indices - If the source pointer to this getelementptr instruction
1947// is a getelementptr instruction, combine the indices of the two
1948// getelementptr instructions into a single instruction.
1949static Constant *foldGEPOfGEP(GEPOperator *GEP, Type *PointeeTy, bool InBounds,
1950 ArrayRef<Value *> Idxs) {
1951 if (PointeeTy != GEP->getResultElementType())
1952 return nullptr;
1953
1954 Constant *Idx0 = cast<Constant>(Idxs[0]);
1955 if (Idx0->isNullValue()) {
1956 // Handle the simple case of a zero index.
1957 SmallVector<Value*, 16> NewIndices;
1958 NewIndices.reserve(Idxs.size() + GEP->getNumIndices());
1959 NewIndices.append(GEP->idx_begin(), GEP->idx_end());
1960 NewIndices.append(Idxs.begin() + 1, Idxs.end());
1962 GEP->getSourceElementType(), cast<Constant>(GEP->getPointerOperand()),
1963 NewIndices, InBounds && GEP->isInBounds(), GEP->getInRangeIndex());
1964 }
1965
1968 I != E; ++I)
1969 LastI = I;
1970
1971 // We can't combine GEPs if the last index is a struct type.
1972 if (!LastI.isSequential())
1973 return nullptr;
1974 // We could perform the transform with non-constant index, but prefer leaving
1975 // it as GEP of GEP rather than GEP of add for now.
1976 ConstantInt *CI = dyn_cast<ConstantInt>(Idx0);
1977 if (!CI)
1978 return nullptr;
1979
1980 // TODO: This code may be extended to handle vectors as well.
1981 auto *LastIdx = cast<Constant>(GEP->getOperand(GEP->getNumOperands()-1));
1982 Type *LastIdxTy = LastIdx->getType();
1983 if (LastIdxTy->isVectorTy())
1984 return nullptr;
1985
1986 SmallVector<Value*, 16> NewIndices;
1987 NewIndices.reserve(Idxs.size() + GEP->getNumIndices());
1988 NewIndices.append(GEP->idx_begin(), GEP->idx_end() - 1);
1989
1990 // Add the last index of the source with the first index of the new GEP.
1991 // Make sure to handle the case when they are actually different types.
1992 if (LastIdxTy != Idx0->getType()) {
1993 unsigned CommonExtendedWidth =
1994 std::max(LastIdxTy->getIntegerBitWidth(),
1995 Idx0->getType()->getIntegerBitWidth());
1996 CommonExtendedWidth = std::max(CommonExtendedWidth, 64U);
1997
1998 Type *CommonTy =
1999 Type::getIntNTy(LastIdxTy->getContext(), CommonExtendedWidth);
2000 Idx0 = ConstantExpr::getSExtOrBitCast(Idx0, CommonTy);
2001 LastIdx = ConstantExpr::getSExtOrBitCast(LastIdx, CommonTy);
2002 }
2003
2004 NewIndices.push_back(ConstantExpr::get(Instruction::Add, Idx0, LastIdx));
2005 NewIndices.append(Idxs.begin() + 1, Idxs.end());
2006
2007 // The combined GEP normally inherits its index inrange attribute from
2008 // the inner GEP, but if the inner GEP's last index was adjusted by the
2009 // outer GEP, any inbounds attribute on that index is invalidated.
2010 std::optional<unsigned> IRIndex = GEP->getInRangeIndex();
2011 if (IRIndex && *IRIndex == GEP->getNumIndices() - 1)
2012 IRIndex = std::nullopt;
2013
2015 GEP->getSourceElementType(), cast<Constant>(GEP->getPointerOperand()),
2016 NewIndices, InBounds && GEP->isInBounds(), IRIndex);
2017}
2018
2020 bool InBounds,
2021 std::optional<unsigned> InRangeIndex,
2022 ArrayRef<Value *> Idxs) {
2023 if (Idxs.empty()) return C;
2024
2026 PointeeTy, C, ArrayRef((Value *const *)Idxs.data(), Idxs.size()));
2027
2028 if (isa<PoisonValue>(C))
2029 return PoisonValue::get(GEPTy);
2030
2031 if (isa<UndefValue>(C))
2032 // If inbounds, we can choose an out-of-bounds pointer as a base pointer.
2033 return InBounds ? PoisonValue::get(GEPTy) : UndefValue::get(GEPTy);
2034
2035 auto IsNoOp = [&]() {
2036 // For non-opaque pointers having multiple indices will change the result
2037 // type of the GEP.
2038 if (!C->getType()->getScalarType()->isOpaquePointerTy() && Idxs.size() != 1)
2039 return false;
2040
2041 // Avoid losing inrange information.
2042 if (InRangeIndex)
2043 return false;
2044
2045 return all_of(Idxs, [](Value *Idx) {
2046 Constant *IdxC = cast<Constant>(Idx);
2047 return IdxC->isNullValue() || isa<UndefValue>(IdxC);
2048 });
2049 };
2050 if (IsNoOp())
2051 return GEPTy->isVectorTy() && !C->getType()->isVectorTy()
2053 cast<VectorType>(GEPTy)->getElementCount(), C)
2054 : C;
2055
2056 if (C->isNullValue()) {
2057 bool isNull = true;
2058 for (Value *Idx : Idxs)
2059 if (!isa<UndefValue>(Idx) && !cast<Constant>(Idx)->isNullValue()) {
2060 isNull = false;
2061 break;
2062 }
2063 if (isNull) {
2064 PointerType *PtrTy = cast<PointerType>(C->getType()->getScalarType());
2065 Type *Ty = GetElementPtrInst::getIndexedType(PointeeTy, Idxs);
2066
2067 assert(Ty && "Invalid indices for GEP!");
2068 Type *OrigGEPTy = PointerType::get(Ty, PtrTy->getAddressSpace());
2069 Type *GEPTy = PointerType::get(Ty, PtrTy->getAddressSpace());
2070 if (VectorType *VT = dyn_cast<VectorType>(C->getType()))
2071 GEPTy = VectorType::get(OrigGEPTy, VT->getElementCount());
2072
2073 // The GEP returns a vector of pointers when one of more of
2074 // its arguments is a vector.
2075 for (Value *Idx : Idxs) {
2076 if (auto *VT = dyn_cast<VectorType>(Idx->getType())) {
2077 assert((!isa<VectorType>(GEPTy) || isa<ScalableVectorType>(GEPTy) ==
2078 isa<ScalableVectorType>(VT)) &&
2079 "Mismatched GEPTy vector types");
2080 GEPTy = VectorType::get(OrigGEPTy, VT->getElementCount());
2081 break;
2082 }
2083 }
2084
2085 return Constant::getNullValue(GEPTy);
2086 }
2087 }
2088
2089 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
2090 if (auto *GEP = dyn_cast<GEPOperator>(CE))
2091 if (Constant *C = foldGEPOfGEP(GEP, PointeeTy, InBounds, Idxs))
2092 return C;
2093
2094 // Attempt to fold casts to the same type away. For example, folding:
2095 //
2096 // i32* getelementptr ([2 x i32]* bitcast ([3 x i32]* %X to [2 x i32]*),
2097 // i64 0, i64 0)
2098 // into:
2099 //
2100 // i32* getelementptr ([3 x i32]* %X, i64 0, i64 0)
2101 //
2102 // Don't fold if the cast is changing address spaces.
2103 Constant *Idx0 = cast<Constant>(Idxs[0]);
2104 if (CE->isCast() && Idxs.size() > 1 && Idx0->isNullValue()) {
2105 PointerType *SrcPtrTy =
2106 dyn_cast<PointerType>(CE->getOperand(0)->getType());
2107 PointerType *DstPtrTy = dyn_cast<PointerType>(CE->getType());
2108 if (SrcPtrTy && DstPtrTy && !SrcPtrTy->isOpaque() &&
2109 !DstPtrTy->isOpaque()) {
2110 ArrayType *SrcArrayTy =
2111 dyn_cast<ArrayType>(SrcPtrTy->getNonOpaquePointerElementType());
2112 ArrayType *DstArrayTy =
2113 dyn_cast<ArrayType>(DstPtrTy->getNonOpaquePointerElementType());
2114 if (SrcArrayTy && DstArrayTy
2115 && SrcArrayTy->getElementType() == DstArrayTy->getElementType()
2116 && SrcPtrTy->getAddressSpace() == DstPtrTy->getAddressSpace())
2117 return ConstantExpr::getGetElementPtr(SrcArrayTy,
2118 (Constant *)CE->getOperand(0),
2119 Idxs, InBounds, InRangeIndex);
2120 }
2121 }
2122 }
2123
2124 // Check to see if any array indices are not within the corresponding
2125 // notional array or vector bounds. If so, try to determine if they can be
2126 // factored out into preceding dimensions.
2128 Type *Ty = PointeeTy;
2129 Type *Prev = C->getType();
2130 auto GEPIter = gep_type_begin(PointeeTy, Idxs);
2131 bool Unknown =
2132 !isa<ConstantInt>(Idxs[0]) && !isa<ConstantDataVector>(Idxs[0]);
2133 for (unsigned i = 1, e = Idxs.size(); i != e;
2134 Prev = Ty, Ty = (++GEPIter).getIndexedType(), ++i) {
2135 if (!isa<ConstantInt>(Idxs[i]) && !isa<ConstantDataVector>(Idxs[i])) {
2136 // We don't know if it's in range or not.
2137 Unknown = true;
2138 continue;
2139 }
2140 if (!isa<ConstantInt>(Idxs[i - 1]) && !isa<ConstantDataVector>(Idxs[i - 1]))
2141 // Skip if the type of the previous index is not supported.
2142 continue;
2143 if (InRangeIndex && i == *InRangeIndex + 1) {
2144 // If an index is marked inrange, we cannot apply this canonicalization to
2145 // the following index, as that will cause the inrange index to point to
2146 // the wrong element.
2147 continue;
2148 }
2149 if (isa<StructType>(Ty)) {
2150 // The verify makes sure that GEPs into a struct are in range.
2151 continue;
2152 }
2153 if (isa<VectorType>(Ty)) {
2154 // There can be awkward padding in after a non-power of two vector.
2155 Unknown = true;
2156 continue;
2157 }
2158 auto *STy = cast<ArrayType>(Ty);
2159 if (ConstantInt *CI = dyn_cast<ConstantInt>(Idxs[i])) {
2160 if (isIndexInRangeOfArrayType(STy->getNumElements(), CI))
2161 // It's in range, skip to the next index.
2162 continue;
2163 if (CI->isNegative()) {
2164 // It's out of range and negative, don't try to factor it.
2165 Unknown = true;
2166 continue;
2167 }
2168 } else {
2169 auto *CV = cast<ConstantDataVector>(Idxs[i]);
2170 bool InRange = true;
2171 for (unsigned I = 0, E = CV->getNumElements(); I != E; ++I) {
2172 auto *CI = cast<ConstantInt>(CV->getElementAsConstant(I));
2173 InRange &= isIndexInRangeOfArrayType(STy->getNumElements(), CI);
2174 if (CI->isNegative()) {
2175 Unknown = true;
2176 break;
2177 }
2178 }
2179 if (InRange || Unknown)
2180 // It's in range, skip to the next index.
2181 // It's out of range and negative, don't try to factor it.
2182 continue;
2183 }
2184 if (isa<StructType>(Prev)) {
2185 // It's out of range, but the prior dimension is a struct
2186 // so we can't do anything about it.
2187 Unknown = true;
2188 continue;
2189 }
2190
2191 // Determine the number of elements in our sequential type.
2192 uint64_t NumElements = STy->getArrayNumElements();
2193 if (!NumElements) {
2194 Unknown = true;
2195 continue;
2196 }
2197
2198 // It's out of range, but we can factor it into the prior
2199 // dimension.
2200 NewIdxs.resize(Idxs.size());
2201
2202 // Expand the current index or the previous index to a vector from a scalar
2203 // if necessary.
2204 Constant *CurrIdx = cast<Constant>(Idxs[i]);
2205 auto *PrevIdx =
2206 NewIdxs[i - 1] ? NewIdxs[i - 1] : cast<Constant>(Idxs[i - 1]);
2207 bool IsCurrIdxVector = CurrIdx->getType()->isVectorTy();
2208 bool IsPrevIdxVector = PrevIdx->getType()->isVectorTy();
2209 bool UseVector = IsCurrIdxVector || IsPrevIdxVector;
2210
2211 if (!IsCurrIdxVector && IsPrevIdxVector)
2213 cast<FixedVectorType>(PrevIdx->getType())->getNumElements(), CurrIdx);
2214
2215 if (!IsPrevIdxVector && IsCurrIdxVector)
2217 cast<FixedVectorType>(CurrIdx->getType())->getNumElements(), PrevIdx);
2218
2219 Constant *Factor =
2220 ConstantInt::get(CurrIdx->getType()->getScalarType(), NumElements);
2221 if (UseVector)
2223 IsPrevIdxVector
2224 ? cast<FixedVectorType>(PrevIdx->getType())->getNumElements()
2225 : cast<FixedVectorType>(CurrIdx->getType())->getNumElements(),
2226 Factor);
2227
2228 NewIdxs[i] =
2229 ConstantFoldBinaryInstruction(Instruction::SRem, CurrIdx, Factor);
2230
2231 Constant *Div =
2232 ConstantFoldBinaryInstruction(Instruction::SDiv, CurrIdx, Factor);
2233
2234 // We're working on either ConstantInt or vectors of ConstantInt,
2235 // so these should always fold.
2236 assert(NewIdxs[i] != nullptr && Div != nullptr && "Should have folded");
2237
2238 unsigned CommonExtendedWidth =
2239 std::max(PrevIdx->getType()->getScalarSizeInBits(),
2240 Div->getType()->getScalarSizeInBits());
2241 CommonExtendedWidth = std::max(CommonExtendedWidth, 64U);
2242
2243 // Before adding, extend both operands to i64 to avoid
2244 // overflow trouble.
2245 Type *ExtendedTy = Type::getIntNTy(Div->getContext(), CommonExtendedWidth);
2246 if (UseVector)
2247 ExtendedTy = FixedVectorType::get(
2248 ExtendedTy,
2249 IsPrevIdxVector
2250 ? cast<FixedVectorType>(PrevIdx->getType())->getNumElements()
2251 : cast<FixedVectorType>(CurrIdx->getType())->getNumElements());
2252
2253 if (!PrevIdx->getType()->isIntOrIntVectorTy(CommonExtendedWidth))
2254 PrevIdx = ConstantExpr::getSExt(PrevIdx, ExtendedTy);
2255
2256 if (!Div->getType()->isIntOrIntVectorTy(CommonExtendedWidth))
2257 Div = ConstantExpr::getSExt(Div, ExtendedTy);
2258
2259 NewIdxs[i - 1] = ConstantExpr::getAdd(PrevIdx, Div);
2260 }
2261
2262 // If we did any factoring, start over with the adjusted indices.
2263 if (!NewIdxs.empty()) {
2264 for (unsigned i = 0, e = Idxs.size(); i != e; ++i)
2265 if (!NewIdxs[i]) NewIdxs[i] = cast<Constant>(Idxs[i]);
2266 return ConstantExpr::getGetElementPtr(PointeeTy, C, NewIdxs, InBounds,
2267 InRangeIndex);
2268 }
2269
2270 // If all indices are known integers and normalized, we can do a simple
2271 // check for the "inbounds" property.
2272 if (!Unknown && !InBounds)
2273 if (auto *GV = dyn_cast<GlobalVariable>(C))
2274 if (!GV->hasExternalWeakLinkage() && GV->getValueType() == PointeeTy &&
2275 isInBoundsIndices(Idxs))
2276 return ConstantExpr::getGetElementPtr(PointeeTy, C, Idxs,
2277 /*InBounds=*/true, InRangeIndex);
2278
2279 return nullptr;
2280}
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
This file implements the APSInt class, which is a simple class that represents an arbitrary sized int...
SmallVector< MachineOperand, 4 > Cond
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
static unsigned foldConstantCastPair(unsigned opc, ConstantExpr *Op, Type *DstTy)
This function determines which opcode to use to fold two constant cast expressions together.
static ICmpInst::Predicate evaluateICmpRelation(Constant *V1, Constant *V2, bool isSigned)
This function determines if there is anything we can decide about the two constants provided.
static ICmpInst::Predicate areGlobalsPotentiallyEqual(const GlobalValue *GV1, const GlobalValue *GV2)
static FCmpInst::Predicate evaluateFCmpRelation(Constant *V1, Constant *V2)
This function determines if there is anything we can decide about the two constants provided.
static Constant * constantFoldCompareGlobalToNull(CmpInst::Predicate Predicate, Constant *C1, Constant *C2)
static Constant * FoldBitCast(Constant *V, Type *DestTy)
static bool isIndexInRangeOfArrayType(uint64_t NumElements, const ConstantInt *CI)
Test whether a given ConstantInt is in-range for a SequentialType.
static Constant * foldGEPOfGEP(GEPOperator *GEP, Type *PointeeTy, bool InBounds, ArrayRef< Value * > Idxs)
static bool isInBoundsIndices(ArrayRef< IndexTy > Idxs)
Test whether the given sequence of normalized indices is "inbounds".
static Constant * BitCastConstantVector(Constant *CV, VectorType *DstTy)
Convert the specified vector Constant node to the specified vector type.
static Constant * ExtractConstantBytes(Constant *C, unsigned ByteStart, unsigned ByteSize)
V is an integer constant which only has a subset of its bytes used.
This file contains the declarations for the subclasses of Constant, which represent the different fla...
Returns the sub type a function will return at a given Idx Should correspond to the result type of an ExtractValue instruction executed with just that one unsigned Idx
Looks at all the uses of the given value Returns the Liveness deduced from the uses of this value Adds all uses that cause the result to be MaybeLive to MaybeLiveRetUses If the result is MaybeLiveUses might be modified but its content should be ignored(since it might not be complete). DeadArgumentEliminationPass
static bool isSigned(unsigned int Opcode)
Hexagon Common GEP
hexagon gen pred
#define I(x, y, z)
Definition: MD5.cpp:58
static bool InRange(int64_t Value, unsigned short Shift, int LBound, int HBound)
Module.h This file contains the declarations for the Module class.
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
This file defines the SmallVector class.
static std::optional< unsigned > getOpcode(ArrayRef< VPValue * > Values)
Returns the opcode of Values or ~0 if they do not all agree.
Definition: VPlanSLP.cpp:191
Value * RHS
Value * LHS
opStatus divide(const APFloat &RHS, roundingMode RM)
Definition: APFloat.h:1043
opStatus convert(const fltSemantics &ToSemantics, roundingMode RM, bool *losesInfo)
Definition: APFloat.cpp:5137
opStatus subtract(const APFloat &RHS, roundingMode RM)
Definition: APFloat.h:1025
opStatus add(const APFloat &RHS, roundingMode RM)
Definition: APFloat.h:1016
opStatus convertFromAPInt(const APInt &Input, bool IsSigned, roundingMode RM)
Definition: APFloat.h:1167
opStatus multiply(const APFloat &RHS, roundingMode RM)
Definition: APFloat.h:1034
opStatus mod(const APFloat &RHS)
Definition: APFloat.h:1061
Class for arbitrary precision integers.
Definition: APInt.h:75
APInt udiv(const APInt &RHS) const
Unsigned division operation.
Definition: APInt.cpp:1570
bool isMinSignedValue() const
Determine if this is the smallest signed value.
Definition: APInt.h:415
uint64_t getZExtValue() const
Get zero extended value.
Definition: APInt.h:1498
APInt urem(const APInt &RHS) const
Unsigned remainder operation.
Definition: APInt.cpp:1663
unsigned getBitWidth() const
Return the number of bits in the APInt.
Definition: APInt.h:1443
APInt sdiv(const APInt &RHS) const
Signed division function for APInt.
Definition: APInt.cpp:1641
unsigned getSignificantBits() const
Get the minimum bit size for this signed APInt.
Definition: APInt.h:1486
APInt ashr(unsigned ShiftAmt) const
Arithmetic right-shift function.
Definition: APInt.h:815
APInt srem(const APInt &RHS) const
Function for signed remainder operation.
Definition: APInt.cpp:1733
bool ule(const APInt &RHS) const
Unsigned less or equal comparison.
Definition: APInt.h:1132
APInt shl(unsigned shiftAmt) const
Left-shift function.
Definition: APInt.h:861
static APInt getLowBitsSet(unsigned numBits, unsigned loBitsSet)
Constructs an APInt value that has the bottom loBitsSet bits set.
Definition: APInt.h:289
static APInt getZero(unsigned numBits)
Get the '0' value for the specified bit-width.
Definition: APInt.h:177
void lshrInPlace(unsigned ShiftAmt)
Logical right-shift this APInt by ShiftAmt in place.
Definition: APInt.h:846
APInt lshr(unsigned shiftAmt) const
Logical right-shift function.
Definition: APInt.h:839
bool uge(const APInt &RHS) const
Unsigned greater or equal comparison.
Definition: APInt.h:1203
An arbitrary precision integer that knows its signedness.
Definition: APSInt.h:23
static bool isSameValue(const APSInt &I1, const APSInt &I2)
Determine if two APSInts have the same value, zero- or sign-extending as needed.
Definition: APSInt.h:319
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition: ArrayRef.h:41
iterator end() const
Definition: ArrayRef.h:152
size_t size() const
size - Get the array size.
Definition: ArrayRef.h:163
iterator begin() const
Definition: ArrayRef.h:151
bool empty() const
empty - Check if the array is empty.
Definition: ArrayRef.h:158
const T * data() const
Definition: ArrayRef.h:160
ArrayRef< T > slice(size_t N, size_t M) const
slice(n, m) - Chop off the first N elements of the array, and keep M elements in the array.
Definition: ArrayRef.h:193
Class to represent array types.
Definition: DerivedTypes.h:368
Type * getElementType() const
Definition: DerivedTypes.h:381
The address of a basic block.
Definition: Constants.h:874
static unsigned isEliminableCastPair(Instruction::CastOps firstOpcode, Instruction::CastOps secondOpcode, Type *SrcTy, Type *MidTy, Type *DstTy, Type *SrcIntPtrTy, Type *MidIntPtrTy, Type *DstIntPtrTy)
Determine how a pair of casts can be eliminated, if they can be at all.
Predicate
This enumeration lists the possible predicates for CmpInst subclasses.
Definition: InstrTypes.h:711
bool isSigned() const
Definition: InstrTypes.h:961
bool isTrueWhenEqual() const
This is just a convenience.
Definition: InstrTypes.h:1010
Predicate getInversePredicate() const
For example, EQ -> NE, UGT -> ULE, SLT -> SGE, OEQ -> UNE, UGT -> OLE, OLT -> UGE,...
Definition: InstrTypes.h:825
static bool isUnordered(Predicate predicate)
Determine if the predicate is an unordered operation.
static ConstantAggregateZero * get(Type *Ty)
Definition: Constants.cpp:1579
static Constant * get(ArrayType *T, ArrayRef< Constant * > V)
Definition: Constants.cpp:1235
static Constant * getSplat(unsigned NumElts, Constant *Elt)
Return a ConstantVector with the specified constant in each element.
Definition: Constants.cpp:3002
A constant value that is initialized with an expression using other constant values.
Definition: Constants.h:997
static Constant * getSExtOrBitCast(Constant *C, Type *Ty)
Definition: Constants.cpp:2002
static Constant * getFCmp(unsigned short pred, Constant *LHS, Constant *RHS, bool OnlyIfReduced=false)
Definition: Constants.cpp:2485
static Constant * getExtractElement(Constant *Vec, Constant *Idx, Type *OnlyIfReducedTy=nullptr)
Definition: Constants.cpp:2510
static Constant * getInBoundsGetElementPtr(Type *Ty, Constant *C, ArrayRef< Constant * > IdxList)
Create an "inbounds" getelementptr.
Definition: Constants.h:1253
static Constant * getPointerCast(Constant *C, Type *Ty)
Create a BitCast, AddrSpaceCast, or a PtrToInt cast constant expression.
Definition: Constants.cpp:2025
static Constant * getCast(unsigned ops, Constant *C, Type *Ty, bool OnlyIfReduced=false)
Convenience function for getting a Cast operation.
Definition: Constants.cpp:1957
static Constant * getNot(Constant *C)
Definition: Constants.cpp:2587
static Constant * getICmp(unsigned short pred, Constant *LHS, Constant *RHS, bool OnlyIfReduced=false)
get* - Return some common constants without having to specify the full Instruction::OPCODE identifier...
Definition: Constants.cpp:2460
static Constant * getGetElementPtr(Type *Ty, Constant *C, ArrayRef< Constant * > IdxList, bool InBounds=false, std::optional< unsigned > InRangeIndex=std::nullopt, Type *OnlyIfReducedTy=nullptr)
Getelementptr form.
Definition: Constants.h:1227
static Constant * getXor(Constant *C1, Constant *C2)
Definition: Constants.cpp:2622
static Constant * getSExt(Constant *C, Type *Ty, bool OnlyIfReduced=false)
Definition: Constants.cpp:2089
static Constant * getLShr(Constant *C1, Constant *C2, bool isExact=false)
Definition: Constants.cpp:2633
static Constant * get(unsigned Opcode, Constant *C1, Constant *C2, unsigned Flags=0, Type *OnlyIfReducedTy=nullptr)
get - Return a binary or shift operator constant expression, folding if possible.
Definition: Constants.cpp:2247
static bool isDesirableBinOp(unsigned Opcode)
Whether creating a constant expression for this binary operator is desirable.
Definition: Constants.cpp:2295
unsigned getOpcode() const
Return the opcode at the root of this constant expression.
Definition: Constants.h:1278
static Constant * getOr(Constant *C1, Constant *C2)
Definition: Constants.cpp:2618
static Constant * getAnd(Constant *C1, Constant *C2)
Definition: Constants.cpp:2614
static Constant * getAdd(Constant *C1, Constant *C2, bool HasNUW=false, bool HasNSW=false)
Definition: Constants.cpp:2593
static Constant * getBitCast(Constant *C, Type *Ty, bool OnlyIfReduced=false)
Definition: Constants.cpp:2213
static Constant * getBinOpIdentity(unsigned Opcode, Type *Ty, bool AllowRHSConstant=false, bool NSZ=false)
Return the identity constant for a binary opcode.
Definition: Constants.cpp:2672
static Constant * getTrunc(Constant *C, Type *Ty, bool OnlyIfReduced=false)
Definition: Constants.cpp:2075
static Constant * getCompare(unsigned short pred, Constant *C1, Constant *C2, bool OnlyIfReduced=false)
Return an ICmp or FCmp comparison operator constant expression.
Definition: Constants.cpp:2372
ConstantFP - Floating Point Values [float, double].
Definition: Constants.h:260
static Constant * get(Type *Ty, double V)
This returns a ConstantFP, or a vector containing a splat of a ConstantFP, for the specified value in...
Definition: Constants.cpp:927
static Constant * getNaN(Type *Ty, bool Negative=false, uint64_t Payload=0)
Definition: Constants.cpp:968
This is the shared class of boolean and integer constants.
Definition: Constants.h:78
static ConstantInt * getTrue(LLVMContext &Context)
Definition: Constants.cpp:833
static Constant * get(Type *Ty, uint64_t V, bool IsSigned=false)
If Ty is a vector type, return a Constant with a splat of the given value.
Definition: Constants.cpp:888
static ConstantInt * getFalse(LLVMContext &Context)
Definition: Constants.cpp:840
int64_t getSExtValue() const
Return the constant as a 64-bit integer value after it has been sign extended as appropriate for the ...
Definition: Constants.h:151
uint64_t getZExtValue() const
Return the constant as a 64-bit unsigned integer value after it has been zero extended as appropriate...
Definition: Constants.h:145
const APInt & getValue() const
Return the constant as an APInt value reference.
Definition: Constants.h:136
bool uge(uint64_t Num) const
This function will return true iff this constant represents a value with active bits bigger than 64 b...
Definition: Constants.h:240
static ConstantPointerNull * get(PointerType *T)
Static factory methods - Return objects of the specified value.
Definition: Constants.cpp:1691
static Constant * get(StructType *T, ArrayRef< Constant * > V)
Definition: Constants.cpp:1300
Constant Vector Declarations.
Definition: Constants.h:492
static Constant * getSplat(ElementCount EC, Constant *Elt)
Return a ConstantVector with the specified constant in each element.
Definition: Constants.cpp:1385
static Constant * get(ArrayRef< Constant * > V)
Definition: Constants.cpp:1342
This is an important base class in LLVM.
Definition: Constant.h:41
Constant * getSplatValue(bool AllowUndefs=false) const
If all elements of the vector constant have the same value, return that value.
Definition: Constants.cpp:1615
static Constant * getAllOnesValue(Type *Ty)
Definition: Constants.cpp:403
bool isAllOnesValue() const
Return true if this is the value that would be returned by getAllOnesValue.
Definition: Constants.cpp:93
static Constant * getNullValue(Type *Ty)
Constructor to create a '0' constant of arbitrary type.
Definition: Constants.cpp:356
Constant * getAggregateElement(unsigned Elt) const
For aggregates (struct/array/vector) return the constant that corresponds to the specified element if...
Definition: Constants.cpp:418
bool isNullValue() const
Return true if this is the value that would be returned by getNullValue.
Definition: Constants.cpp:76
A parsed version of the target data layout string in and methods for querying it.
Definition: DataLayout.h:110
static constexpr ElementCount get(ScalarTy MinVal, bool Scalable)
Definition: TypeSize.h:297
static bool compare(const APFloat &LHS, const APFloat &RHS, FCmpInst::Predicate Pred)
Return result of LHS Pred RHS comparison.
static FixedVectorType * get(Type *ElementType, unsigned NumElts)
Definition: Type.cpp:754
bool isInBounds() const
Test whether this is an inbounds GEP, as defined by LangRef.html.
Definition: Operator.h:395
bool hasAllZeroIndices() const
Return true if all of the indices of this GEP are zeros.
Definition: Operator.h:454
static Type * getTypeAtIndex(Type *Ty, Value *Idx)
Return the type of the element at the given index of an indexable type.
static Type * getGEPReturnType(Type *ElTy, Value *Ptr, ArrayRef< Value * > IdxList)
Returns the pointer type returned by the GEP instruction, which may be a vector of pointers.
static Type * getIndexedType(Type *Ty, ArrayRef< Value * > IdxList)
Returns the result type of a getelementptr with the given source element type and indexes.
bool hasExternalWeakLinkage() const
Definition: GlobalValue.h:524
Module * getParent()
Get the module that this global value is contained inside of...
Definition: GlobalValue.h:652
PointerType * getType() const
Global values are always pointers.
Definition: GlobalValue.h:290
static bool compare(const APInt &LHS, const APInt &RHS, ICmpInst::Predicate Pred)
Return result of LHS Pred RHS comparison.
bool isEquality() const
Return true if this predicate is either EQ or NE.
bool isAssociative() const LLVM_READONLY
Return true if the instruction is associative:
bool isCommutative() const LLVM_READONLY
Return true if the instruction is commutative:
bool isBinaryOp() const
Definition: Instruction.h:173
bool isUnaryOp() const
Definition: Instruction.h:172
bool isIntDivRem() const
Definition: Instruction.h:174
Class to represent integer types.
Definition: DerivedTypes.h:40
static IntegerType * get(LLVMContext &C, unsigned NumBits)
This static method is the primary way of constructing an IntegerType.
Definition: Type.cpp:339
A Module instance is used to store all the information related to an LLVM module.
Definition: Module.h:65
Class to represent pointers.
Definition: DerivedTypes.h:643
bool isOpaque() const
Definition: DerivedTypes.h:684
unsigned getAddressSpace() const
Return the address space of the Pointer type.
Definition: DerivedTypes.h:693
static PoisonValue * get(Type *T)
Static factory methods - Return an 'poison' object of the specified type.
Definition: Constants.cpp:1743
bool empty() const
Definition: SmallVector.h:94
void reserve(size_type N)
Definition: SmallVector.h:667
void append(ItTy in_start, ItTy in_end)
Add the specified range to the end of the SmallVector.
Definition: SmallVector.h:687
void resize(size_type N)
Definition: SmallVector.h:642
void push_back(const T &Elt)
Definition: SmallVector.h:416
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Definition: SmallVector.h:1200
Class to represent struct types.
Definition: DerivedTypes.h:213
The instances of the Type class are immutable: once they are created, they are never changed.
Definition: Type.h:45
unsigned getIntegerBitWidth() const
const fltSemantics & getFltSemantics() const
bool isVectorTy() const
True if this is an instance of VectorType.
Definition: Type.h:265
bool isIntOrIntVectorTy() const
Return true if this is an integer type or a vector of integer types.
Definition: Type.h:235
static IntegerType * getInt1Ty(LLVMContext &C)
bool isEmptyTy() const
Return true if this type is empty, that is, it has no elements or all of its elements are empty.
Type * getNonOpaquePointerElementType() const
Only use this method in code that is not reachable with opaque pointers, or part of deprecated method...
Definition: Type.h:423
bool isX86_MMXTy() const
Return true if this is X86 MMX.
Definition: Type.h:201
bool isPPC_FP128Ty() const
Return true if this is powerpc long double.
Definition: Type.h:166
static IntegerType * getIntNTy(LLVMContext &C, unsigned N)
unsigned getScalarSizeInBits() const LLVM_READONLY
If this is a vector type, return the getPrimitiveSizeInBits value for the element type.
bool isFirstClassType() const
Return true if the type is "first class", meaning it is a valid type for a Value.
Definition: Type.h:281
bool isSized(SmallPtrSetImpl< Type * > *Visited=nullptr) const
Return true if it makes sense to take the size of this type.
Definition: Type.h:302
LLVMContext & getContext() const
Return the LLVMContext in which this type was uniqued.
Definition: Type.h:129
bool isFloatingPointTy() const
Return true if this is one of the floating-point types.
Definition: Type.h:185
bool isX86_AMXTy() const
Return true if this is X86 AMX.
Definition: Type.h:204
bool isIntOrPtrTy() const
Return true if this is an integer type or a pointer type.
Definition: Type.h:244
static IntegerType * getInt32Ty(LLVMContext &C)
static IntegerType * getInt64Ty(LLVMContext &C)
bool isIntegerTy() const
True if this is an instance of IntegerType.
Definition: Type.h:229
bool isFPOrFPVectorTy() const
Return true if this is a FP type or a vector of FP.
Definition: Type.h:217
TypeSize getPrimitiveSizeInBits() const LLVM_READONLY
Return the basic size of this type if it is a primitive type.
Type * getScalarType() const
If this is a vector type, return the element type, otherwise return 'this'.
Definition: Type.h:348
static UndefValue * get(Type *T)
Static factory methods - Return an 'undef' object of the specified type.
Definition: Constants.cpp:1724
Value * getOperand(unsigned i) const
Definition: User.h:169
LLVM Value Representation.
Definition: Value.h:74
Type * getType() const
All values are typed, get the type of this value.
Definition: Value.h:255
Align getPointerAlignment(const DataLayout &DL) const
Returns an alignment of the pointer value.
Definition: Value.cpp:921
LLVMContext & getContext() const
All values hold a context through their type.
Definition: Value.cpp:1069
Base class of all SIMD vector types.
Definition: DerivedTypes.h:400
Type * getElementType() const
Definition: DerivedTypes.h:433
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
@ C
The default llvm calling convention, compatible with C.
Definition: CallingConv.h:34
bool match(Val *V, const Pattern &P)
Definition: PatternMatch.h:49
cst_pred_ty< is_one > m_One()
Match an integer 1 or a vector with all elements equal to 1.
Definition: PatternMatch.h:517
cstfp_pred_ty< is_neg_zero_fp > m_NegZeroFP()
Match a floating-point negative zero.
Definition: PatternMatch.h:682
apint_match m_APInt(const APInt *&Res)
Match a ConstantInt or splatted ConstantVector, binding the specified pointer to the contained APInt.
Definition: PatternMatch.h:278
auto m_Undef()
Match an arbitrary undef constant.
Definition: PatternMatch.h:136
is_zero m_Zero()
Match any null constant or a vector with all elements equal to 0.
Definition: PatternMatch.h:537
match_combine_or< LTy, RTy > m_CombineOr(const LTy &L, const RTy &R)
Combine two pattern matchers matching L || R.
Definition: PatternMatch.h:218
This is an optimization pass for GlobalISel generic memory operations.
Definition: AddressRanges.h:18
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly.
Definition: STLExtras.h:1819
Constant * ConstantFoldSelectInstruction(Constant *Cond, Constant *V1, Constant *V2)
Attempt to constant fold a select instruction with the specified operands.
Constant * ConstantFoldGetElementPtr(Type *Ty, Constant *C, bool InBounds, std::optional< unsigned > InRangeIndex, ArrayRef< Value * > Idxs)
Constant * ConstantFoldCompareInstruction(CmpInst::Predicate Predicate, Constant *C1, Constant *C2)
Constant * ConstantFoldUnaryInstruction(unsigned Opcode, Constant *V)
gep_type_iterator gep_type_end(const User *GEP)
Constant * ConstantFoldExtractValueInstruction(Constant *Agg, ArrayRef< unsigned > Idxs)
Attempt to constant fold an extractvalue instruction with the specified operands and indices.
bool NullPointerIsDefined(const Function *F, unsigned AS=0)
Check whether null pointer dereferencing is considered undefined behavior for a given function or an ...
Definition: Function.cpp:2102
Constant * ConstantFoldInsertElementInstruction(Constant *Val, Constant *Elt, Constant *Idx)
Attempt to constant fold an insertelement instruction with the specified operands and indices.
constexpr int PoisonMaskElem
Constant * ConstantFoldExtractElementInstruction(Constant *Val, Constant *Idx)
Attempt to constant fold an extractelement instruction with the specified operands and indices.
constexpr unsigned BitWidth
Definition: BitmaskEnum.h:184
gep_type_iterator gep_type_begin(const User *GEP)
APFloat neg(APFloat X)
Returns the negated value of the argument.
Definition: APFloat.h:1351
Constant * ConstantFoldCastInstruction(unsigned opcode, Constant *V, Type *DestTy)
Constant * ConstantFoldInsertValueInstruction(Constant *Agg, Constant *Val, ArrayRef< unsigned > Idxs)
ConstantFoldInsertValueInstruction - Attempt to constant fold an insertvalue instruction with the spe...
unsigned Log2(Align A)
Returns the log2 of the alignment.
Definition: Alignment.h:208
Constant * ConstantFoldShuffleVectorInstruction(Constant *V1, Constant *V2, ArrayRef< int > Mask)
Attempt to constant fold a shufflevector instruction with the specified operands and mask.
Constant * ConstantFoldBinaryInstruction(unsigned Opcode, Constant *V1, Constant *V2)
This struct is a compact representation of a valid (non-zero power of two) alignment.
Definition: Alignment.h:39